Skip to content

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

Rust

feat(identity): default repository names to remote paths (#1033)

AkitaOnRails77e7b8e23a4c
diff --git a/AGENTS.md b/AGENTS.md
index 2ae06d6e..8d20ace2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -14,9 +14,11 @@ for cross-session continuity.
connecting that hook session id to MCP requests) must pass `workspace` and
`project` together on every project-scoped call, including requests about "this
project", "here", or "our work". Read the exact names from the nearest
- `.ai-memory.toml` when it declares both. If it does not, obtain the names from
- the operator or server configuration; never guess them from a directory name
- and never rely on the server's last active project.
+ `.ai-memory.toml` when it declares both. Without a marker override, derive the
+ project from the normalized `upstream` remote, then `origin`, using the full
+ repository path without its host (`github.com/acme/api` → `acme-api`); use the
+ folder basename only when no valid remote exists. Never rely on the server's
+ last active project.
This rule applies only to project-scoped calls. For cross-project retrieval,
`global=true` must omit `workspace`, `project`, and `scopes`. For a standing
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 59ec66e1..1b8e43f7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -240,13 +240,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`consolidated`, plus `consolidated_by: agent`), defaults the tier to
`episodic`, applies the same duplicate-title suffix, and marks the session's
queued SessionEnd consolidation job completed. (#1038)
-- Added the opt-in `identity_style = "path"` marker key: a new project created
- from a git remote is named from its repository path without the host
- (`github.com/acme/api` → `acme-api`), so worktrees and clones in differently
- named folders share one project. Captures still route by the full repository
- identity, existing projects are never renamed, and when another repository
- (such as the same path on another forge) already holds the name the newcomer
- keeps the name it would otherwise get. The default stays `host_path`. (#1033)
+- Added `identity_style = "path" | "host_path"` marker control for remote-backed
+ project naming. `path` names from the full repository path without the host
+ (`github.com/acme/api` → `acme-api`); `host_path` preserves the former naming
+ behavior as an explicit opt-out. Captures always route by the full hostful
+ identity, and cross-forge path collisions never merge. (#1033)
### Changed
- Changed static CLI/MCP project-name resolution to accept an existing
@@ -260,8 +258,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
post-commit refresh failure for startup repair on both success and any later
operation error, retaining the first warning across busy retries and lease
wait-out; managed-run caller validation happens before promotion.
- Ambiguous cross-forge keys and target-name conflicts fail
- closed, and the default identity style remains `host_path`. (#1033)
+ Ambiguous cross-forge keys and target-name conflicts fail closed. Current
+ clients now explicitly send `path` for a valid remote and send explicit
+ `host_path` for the opt-out; a new server deliberately interprets an omitted
+ field as legacy `host_path` so old clients cannot be silently renamed. Existing compatible projects are
+ promoted only by authorized capture/write and keep their UUID; read-only
+ handoff/static lookups never rename. (#1033)
- Changed the documented precedence between rules and memory: the user's
instructions, then the repository's rules file, then the project's memory,
then the cross-project profile. Where no hard rule exists, agents now use
diff --git a/README.md b/README.md
index 91d7950a..fc29da82 100644
--- a/README.md
+++ b/README.md
@@ -569,7 +569,7 @@ diagram, crate breakdown, schema notes, and invariants.
| [`docs/cross-project-profile.md`](docs/cross-project-profile.md) | **The cross-project profile.** Your usual choices delivered to every project as defaults: defaults per deployment, every setting, per-project opt-outs, multi-user opt-in and privacy, CLI. |
| [`docs/managed-workstreams.md`](docs/managed-workstreams.md) | Optional `ai-memory run` continuity across harnesses: auto harness selection, native resume, argument forwarding, ledger search, privacy, and recovery. |
| [`docs/agent-messaging.md`](docs/agent-messaging.md) | Cross-project agent-to-agent messaging: a directed, claim-once inbox/queue plus the on-start "you have mail" notice. |
-| [`docs/marker-file.md`](docs/marker-file.md) | `.ai-memory.toml` workspace/project routing for multi-client trees, mono-repos, worktrees, and work/personal separation, plus per-repository server profiles. |
+| [`docs/marker-file.md`](docs/marker-file.md) | Default repository-path project naming plus `.ai-memory.toml` workspace/project routing for multi-client trees, mono-repos, worktrees, and work/personal separation, plus per-repository server profiles. |
| [`docs/auto-scope.md`](docs/auto-scope.md) | `[auto_scope]` modes for shared servers: the default `per_actor` isolation, session-aware `per_session` isolation, and the pre-v1.39 `single` slot. |
| [`docs/macos.md`](docs/macos.md) | macOS install paths: menu bar app, native release tarball, source build, Docker wrapper, launchd, and current limitations. |
| [`docs/windows.md`](docs/windows.md) | Windows install modes: full WSL2, native Windows with Docker Desktop, prebuilt native release zip, native source builds, and caveats. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 487dc93d..510dff44 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -2879,11 +2879,11 @@ pub struct LlmTestArgs {
/// Project-resolution strategy to bake into installed hooks.
///
-/// `basename` (the default) bakes nothing — generated hooks behave
-/// exactly as before. `repo-root` bakes a default so every session
-/// resolves its project from the main git repo root (collapsing
-/// subdirectories and worktrees) without a per-repo `.ai-memory.toml`
-/// marker. A marker's own `project_strategy` still wins.
+/// `basename` (the default) bakes nothing. `repo-root` bakes a remote-less
+/// fallback that resolves from the main git repo root (collapsing subdirectories
+/// and worktrees) without a per-repo `.ai-memory.toml` marker. A valid remote's
+/// canonical path name wins while the project remains unpinned; a marker's
+/// explicit `project` or `identity` and operator-home routing still win.
/// Which way capture fails when a repository has no `.ai-memory.toml`
/// marker (#446).
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rs
index 80754cfc..ffbfb664 100644
--- a/crates/ai-memory-cli/src/commands/doctor.rs
+++ b/crates/ai-memory-cli/src/commands/doctor.rs
@@ -616,7 +616,10 @@ fn render_project_coordinate(coordinate: &ProjectCoordinateReport) -> String {
let _ = writeln!(
output,
" repository: source {source}, style {}",
- local.identity_style.as_deref().unwrap_or("host_path")
+ local
+ .identity_style
+ .as_deref()
+ .unwrap_or(ai_memory_core::repository_identity::IdentityStyle::Path.as_str())
);
}
if let Some(canonical) = &local.canonical_candidate {
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index ebbd3f92..5fb4ccdf 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -281,9 +281,9 @@ pub fn url_encode(s: &str) -> String {
/// `default_strategy` is the install-time default baked into the native hook
/// command by `install-hooks --project-strategy` (passed via the `hook
/// --project-strategy` flag). It fills `project_strategy` only when no marker
-/// pinned one — a marker's explicit `project` / `project_strategy` always win
-/// (§3.3). repo-root is resolved here, host-side, because a containerized
-/// server cannot see this checkout.
+/// pins one. A marker's explicit `project` or `identity` and operator-home
+/// routing win; otherwise a valid remote's canonical path wins, and repo-root
+/// is only the host-side no-valid-remote fallback.
pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> String {
marker_query_suffix_impl(cwd, default_strategy, true)
}
@@ -425,13 +425,8 @@ pub(crate) fn inspect_repository_coordinate(
)
});
let identity_style = repository.as_ref().and_then(|identity| {
- (identity.source == ai_memory_core::repository_identity::IdentitySource::GitRemote).then(
- || {
- forwarded_identity_style(marker.fields.identity_style.as_deref())
- .unwrap_or("host_path")
- .to_owned()
- },
- )
+ (identity.source == ai_memory_core::repository_identity::IdentitySource::GitRemote)
+ .then(|| forwarded_identity_style(marker.fields.identity_style.as_deref()).to_owned())
});
RepositoryCoordinateInspection {
evidence: RepositoryCoordinateEvidence {
@@ -540,12 +535,10 @@ fn hook_scope_from_selection(
}
// Only a remote has a host to drop, so the style travels with a remote
// identity and nothing else (#1033).
- let identity_style = identity
- .as_ref()
- .filter(|identity| {
- identity.source == ai_memory_core::repository_identity::IdentitySource::GitRemote
- })
- .and_then(|_| forwarded_identity_style(style.as_deref()));
+ let identity_style = identity.as_ref().and_then(|identity| {
+ (identity.source == ai_memory_core::repository_identity::IdentitySource::GitRemote)
+ .then(|| forwarded_identity_style(style.as_deref()))
+ });
let (identity, identity_src) = match identity {
Some(identity) => (Some(identity.identity), Some(identity.source.as_str())),
None => (None, None),
@@ -564,14 +557,14 @@ fn hook_scope_from_selection(
}
}
-/// The `identity_style` value to forward for a marker's raw setting: `path`
-/// or nothing, since `host_path` is the server's default. Every client makes
-/// this same decision, checked against the shared identity fixture.
-fn forwarded_identity_style(raw: Option<&str>) -> Option<&'static str> {
+/// The `identity_style` every Phase-5 client sends with a valid git remote.
+/// Explicit marker/home-route values win; omission emits `path`. The server
+/// keeps omitted wire input as legacy `host_path` for old-client compatibility.
+fn forwarded_identity_style(raw: Option<&str>) -> &'static str {
use ai_memory_core::repository_identity::IdentityStyle;
raw.and_then(IdentityStyle::from_str_opt)
- .filter(|style| *style == IdentityStyle::Path)
- .map(IdentityStyle::as_str)
+ .unwrap_or(IdentityStyle::Path)
+ .as_str()
}
/// A resolved marker's `[profile]` flag as the explicit value the hook
@@ -1284,7 +1277,7 @@ mod tests {
};
let qs = marker_query_suffix(repo.path().to_str().unwrap(), None);
assert!(
- qs.contains("&identity=git.example.test%2Facme%2Fapi&identity_src=git_remote"),
+ qs.contains("&identity=git.example.test%2Facme%2Fapi&identity_src=git_remote&identity_style=path"),
"{qs}"
);
assert!(
@@ -1375,9 +1368,9 @@ mod tests {
);
}
- /// #1033: `identity_style = "path"` rides along with a remote identity,
- /// and only with one — a declared project or identity has no host to drop,
- /// and the default style sends nothing.
+ /// #1033: every valid remote carries a style. Omission and invalid marker
+ /// values send `path`; explicit `host_path` remains the opt-out. A declared
+ /// project or identity has no inferred remote style.
#[test]
fn marker_query_suffix_forwards_the_path_style_with_a_remote_identity() {
let Some(repo) = repo_with_remotes(&[("origin", "[email protected]:acme/api.git")])
@@ -1387,6 +1380,13 @@ mod tests {
let cwd = repo.path().to_str().unwrap();
let marker = repo.path().join(".ai-memory.toml");
+ std::fs::write(&marker, "").unwrap();
+ let qs = marker_query_suffix(cwd, None);
+ assert!(
+ qs.contains("&identity_src=git_remote&identity_style=path"),
+ "{qs}"
+ );
+
std::fs::write(&marker, "identity_style = \"path\"\n").unwrap();
let qs = marker_query_suffix(cwd, None);
assert!(
@@ -1396,15 +1396,18 @@ mod tests {
let scope = serde_json::to_value(hook_scope(cwd, None)).unwrap();
assert_eq!(scope["identity_style"], "path");
+ std::fs::write(&marker, "identity_style = \"host_path\"\n").unwrap();
+ let qs = marker_query_suffix(cwd, None);
+ assert!(
+ qs.contains("&identity_src=git_remote&identity_style=host_path"),
+ "{qs}"
+ );
+
+ std::fs::write(&marker, "identity_style = \"Path\"\n").unwrap();
+ let qs = marker_query_suffix(cwd, None);
+ assert!(qs.contains("&identity_style=path"), "{qs}");
+
for (body, why) in [
- (
- "identity_style = \"host_path\"\n",
- "the default sends nothing",
- ),
- (
- "identity_style = \"Path\"\n",
- "an unknown value sends nothing",
- ),
(
"identity_style = \"path\"\nproject = \"api\"\n",
"a declared project routes by name",
@@ -1429,10 +1432,10 @@ mod tests {
.unwrap();
for case in cases["identity_style"].as_array().unwrap() {
let value = case["value"].as_str().unwrap();
- let expected = (case["style"].as_str() == Some("path")).then_some("path");
+ let expected = case["style"].as_str().unwrap_or("path");
assert_eq!(forwarded_identity_style(Some(value)), expected, "{value:?}");
}
- assert_eq!(forwarded_identity_style(None), None);
+ assert_eq!(forwarded_identity_style(None), "path");
}
/// No repository, no remote, no declaration: nothing to send, and the
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 5c3cf710..2b87ab39 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -3906,9 +3906,10 @@ function findSettingsMarker(cwd: string | undefined): string | undefined {
/// integrations.
///
/// An install-time default applies only when no marker pins a
-/// `project_strategy` (#128). A marker's own `project` / `project_strategy`
-/// still take precedence (§3.3), and repo-root is resolved host-side via
-/// `repoRootProject`.
+/// `project_strategy` (#128). A marker's explicit `project` or `identity` and
+/// operator-home routing keep precedence; otherwise a valid remote supplies its
+/// canonical path name even when `repo-root` is configured. `repoRootProject`
+/// handles the host-side fallback only when no valid remote exists.
///
/// Scope/settings resolution walks past a capture-only marker to the nearest
/// ancestor marker that declares a setting (#668) via `findSettingsMarker`,
@@ -3977,7 +3978,7 @@ pub(crate) fn ts_apply_marker_params(
if (routeIdentity) {
url.searchParams.set("identity", routeIdentity);
url.searchParams.set("identity_src", "git_remote");
- if (identityStyle === "path") url.searchParams.set("identity_style", "path");
+ url.searchParams.set("identity_style", identityStyleParam(identityStyle));
}
marker = undefined;
} else marker = homeMarker;
@@ -4119,8 +4120,8 @@ function normalizeRemote(raw: string): string | undefined {
return id && id.includes("/") ? id : undefined;
}
-function identityStyleParam(style: string | undefined): string | undefined {
- return style?.trim() === "path" ? "path" : undefined;
+function identityStyleParam(style: string | undefined): "path" | "host_path" {
+ return style?.trim() === "host_path" ? "host_path" : "path";
}
function discoverRemoteIdentity(cwd: string | undefined): string | undefined {
@@ -4163,8 +4164,7 @@ function applyIdentityParams(
if (identity) {
url.searchParams.set("identity", identity);
url.searchParams.set("identity_src", "git_remote");
- const forwarded = identityStyleParam(style);
- if (forwarded) url.searchParams.set("identity_style", forwarded);
+ url.searchParams.set("identity_style", identityStyleParam(style));
return true;
}
return false;
@@ -12914,9 +12914,9 @@ mod identity_parity_tests {
.collect()
}
- /// The `identity_style` fixture: each marker value and whether a client
- /// forwards `identity_style=path` for it (#1033).
- fn style_cases() -> Vec<(String, bool)> {
+ /// The `identity_style` fixture: each marker value and the explicit value
+ /// every client forwards for it (#1033).
+ fn style_cases() -> Vec<(String, Option<String>)> {
let cases: serde_json::Value = serde_json::from_str(CASES).unwrap();
cases["identity_style"]
.as_array()
@@ -12925,7 +12925,7 @@ mod identity_parity_tests {
.map(|case| {
(
case["value"].as_str().unwrap().to_owned(),
- case["style"].as_str() == Some("path"),
+ Some(case["style"].as_str().unwrap_or("path").to_owned()),
)
})
.collect()
@@ -13008,17 +13008,15 @@ mod identity_parity_tests {
/// Compare one port's forwarding decisions, one line per style case.
fn assert_styles_agree(port: &str, lines: &str) {
let got: Vec<&str> = lines.split('\n').collect();
- for (i, (value, forwards)) in style_cases().iter().enumerate() {
+ for (i, (value, style)) in style_cases().iter().enumerate() {
let got = got
.get(i)
.copied()
.unwrap_or("<missing>")
.trim_end_matches('\r');
- let expected = if *forwards {
- "&identity_style=path"
- } else {
- ""
- };
+ let expected = style
+ .as_deref()
+ .map_or_else(String::new, |style| format!("&identity_style={style}"));
assert_eq!(got, expected, "{port} forwarded {value:?} differently");
}
}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index fd63fdac..a39eb973 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -110,11 +110,12 @@ pub mod write_page;
/// Each field is resolved independently, in this order:
///
/// 1. The explicit flag (`--workspace` / `--project`) when non-empty.
-/// 2. The nearest `.ai-memory.toml` marker: `workspace`, and `project` —
-/// or the hook-compatible derived project when the marker leaves it
-/// unpinned (`basename(cwd)` by default, main repo root for `repo-root`).
-/// 3. Today's fallbacks: [`crate::config::DEFAULT_WORKSPACE`] and
-/// [`resolve_project_name`]'s cwd chain.
+/// 2. The nearest `.ai-memory.toml` marker: `workspace` and an explicit
+/// `project`/`identity`; otherwise a valid remote supplies its canonical path
+/// name even when the unpinned strategy is `repo-root`.
+/// 3. Without a valid remote, an explicit marker `repo-root` strategy derives
+/// the main repo root; otherwise use [`crate::config::DEFAULT_WORKSPACE`] and
+/// [`resolve_project_name`]'s cwd-basename fallback.
///
/// Rung 2 is why this function exists. Before it, only the lifecycle hooks
/// read the marker, so a checkout declaring `workspace = "acme"` still had
@@ -200,22 +201,26 @@ pub(crate) fn resolve_scope_with_marker(
Some(explicit) => explicit.to_string(),
None => {
// A marker's explicit `project` pins the name for its whole tree.
- // Otherwise derive exactly as the hook does: basename(cwd) by
- // default, or the main repository root for `repo-root`.
+ // Otherwise a valid remote supplies the canonical path name; only
+ // the no-valid-remote fallback consults basename/repo-root.
let declared = marker
.as_ref()
.and_then(|(scope, identity_cwd, lookup_cwd)| {
- scope.project.clone().or_else(|| {
- if scope.is_repo_root() {
- crate::marker::repo_root_project(lookup_cwd)
- } else {
- ai_memory_consolidate::derive_project_name(
- std::path::Path::new(identity_cwd),
- ai_memory_consolidate::ProjectNameStrategy::Basename,
- )
- .map(|(name, _)| name)
- }
- })
+ scope
+ .project
+ .clone()
+ .or_else(|| scope.canonical_remote_project())
+ .or_else(|| {
+ if scope.is_repo_root() {
+ crate::marker::repo_root_project(lookup_cwd)
+ } else {
+ ai_memory_consolidate::derive_project_name(
+ std::path::Path::new(identity_cwd),
+ ai_memory_consolidate::ProjectNameStrategy::Basename,
+ )
+ .map(|(name, _)| name)
+ }
+ })
});
match declared {
Some(name) => {
@@ -243,9 +248,10 @@ pub(crate) fn resolve_scope_with_marker(
/// changing the process working directory, resolving symlinks, or consulting
/// wrapper cwd overrides.
///
-/// The policy matches [`resolve_scope`]: a marker may pin either half, an
-/// unpinned project under a marker follows that marker's strategy, and a tree
-/// without a scope marker falls back to the main repository root.
+/// The policy matches [`resolve_scope`]: a marker may pin either half, a valid
+/// remote's canonical path wins an unpinned marker strategy, an explicit
+/// `repo-root` strategy handles only the no-valid-remote case, and a tree
+/// without a scope marker otherwise uses the cwd basename.
pub(crate) fn resolve_scope_for_path(
config: &Config,
cwd: &std::path::Path,
@@ -267,6 +273,7 @@ pub(crate) fn resolve_scope_for_path(
Some(scope) => scope
.project
.clone()
+ .or_else(|| scope.canonical_remote_project())
.or_else(|| {
if scope.is_repo_root() {
crate::marker::repo_root_project(&identity)
@@ -279,12 +286,18 @@ pub(crate) fn resolve_scope_for_path(
}
})
.ok_or_else(|| anyhow!("could not derive project name from {}", cwd.display()))?,
- None => ai_memory_consolidate::derive_project_name(
- &cwd,
- ai_memory_consolidate::ProjectNameStrategy::MainRepoRoot,
- )
- .map(|(name, _)| name)
- .ok_or_else(|| anyhow!("could not derive project name from {}", cwd.display()))?,
+ None => crate::marker::discover_remote_identity(&identity)
+ .and_then(|repository| {
+ ai_memory_core::repository_identity::path_style_name(&repository)
+ })
+ .or_else(|| {
+ ai_memory_consolidate::derive_project_name(
+ &cwd,
+ ai_memory_consolidate::ProjectNameStrategy::Basename,
+ )
+ .map(|(name, _)| name)
+ })
+ .ok_or_else(|| anyhow!("could not derive project name from {}", cwd.display()))?,
};
Ok((workspace, project))
}
@@ -365,17 +378,14 @@ fn scope_cwd(config: &Config) -> Option<String> {
///
/// Precedence:
/// 1. `explicit` (the user's `--project` flag) when non-empty.
-/// 2. `AI_MEMORY_HOST_CWD` env var. The docker wrapper sets this
-/// to the host's `$PWD` because inside the container the workdir
-/// is always `/work` (a bind mount), so the container's own
-/// `current_dir()` returns "work" for every invocation. Without
-/// this env var, every dockerised bootstrap would land in project
-/// `default/work` regardless of which host dir it was actually
-/// run from. Honoured here as a basename, same heuristic as the
-/// other fallbacks.
-/// 3. Basename of the git repo root walked up from CWD (handles
-/// running from any subdir of the project).
-/// 4. Basename of the bare CWD (covers non-git directories).
+/// 2. Canonical path-style name from the valid `upstream` remote, then
+/// `origin`, when the checkout has no marker identity/name override.
+/// `AI_MEMORY_HOST_CWD` selects the host checkout before the remote is
+/// inspected; if that path is unavailable in a container it remains the
+/// basename fallback rather than borrowing `/work`'s identity.
+/// 3. Basename of the current directory, including a git-repository
+/// subdirectory or a non-git directory. `repo-root` is used only when a
+/// marker/install strategy explicitly selects it.
///
/// Mirrors the heuristic the hook router uses in
/// `ai-memory-hooks::router::resolve_project_ids`, so commands
@@ -386,13 +396,19 @@ pub(crate) fn resolve_project_name(config: &Config, explicit: Option<&str>) -> R
if let Some(p) = explicit.filter(|s| !s.is_empty()) {
return Ok(p.to_string());
}
- if let Some(host_cwd) = config.runtime_env.host_cwd()
- && let Some(name) = std::path::Path::new(host_cwd)
+ if let Some(host_cwd) = config.runtime_env.host_cwd() {
+ if let Some(repository) = crate::marker::discover_remote_identity(host_cwd)
+ && let Some(name) = ai_memory_core::repository_identity::path_style_name(&repository)
+ {
+ return Ok(name);
+ }
+ if let Some(name) = std::path::Path::new(host_cwd)
.file_name()
.and_then(|s| s.to_str())
.filter(|s| !s.is_empty())
- {
- return Ok(name.to_string());
+ {
+ return Ok(name.to_string());
+ }
}
// Safety net: when running inside the docker wrapper, the
@@ -416,17 +432,17 @@ pub(crate) fn resolve_project_name(config: &Config, explicit: Option<&str>) -> R
);
}
- // Shared with the hook router via `derive_project_name` so the CLI
- // and hooks agree on what "the project for this cwd" means. The
- // `MainRepoRoot` strategy walks worktrees back to the main repo
- // — a session in `~/repo-worktrees/feature-x/` and one in the
- // main checkout resolve to the same project name (the main repo's
- // basename), instead of fragmenting into separate projects.
- // Aligned change from the earlier CLI behaviour (which used the
- // worktree-local `discover_repo_root`).
+ // Shared with the hook router via `derive_project_name`: with no valid
+ // remote and no explicit repo-root strategy, both use the current cwd's
+ // basename, including repository subdirectories.
+ if let Some(repository) = crate::marker::discover_remote_identity(&cwd.to_string_lossy())
+ && let Some(name) = ai_memory_core::repository_identity::path_style_name(&repository)
+ {
+ return Ok(name);
+ }
if let Some((name, _)) = ai_memory_consolidate::derive_project_name(
&cwd,
- ai_memory_consolidate::ProjectNameStrategy::MainRepoRoot,
+ ai_memory_consolidate::ProjectNameStrategy::Basename,
) {
return Ok(name);
}
@@ -476,6 +492,173 @@ mod tests {
);
}
+ fn git(command: &[&str], cwd: &std::path::Path) -> bool {
+ std::process::Command::new("git")
+ .args(command)
+ .current_dir(cwd)
+ .status()
+ .is_ok_and(|status| status.success())
+ }
+
+ #[test]
+ fn resolve_project_name_uses_canonical_remote_path_and_upstream_priority() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ if !git(&["init", "-q"], tmp.path()) {
+ return;
+ }
+ assert!(git(
+ &[
+ "remote",
+ "add",
+ "origin",
+ "https://[email protected]/wrong/origin.git"
+ ],
+ tmp.path()
+ ));
+ assert!(git(
+ &[
+ "remote",
+ "add",
+ "upstream",
+ "[email protected]:Acme/Group/API.git"
+ ],
+ tmp.path()
+ ));
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_for_tests(tmp.path().to_str().unwrap()),
+ ..Config::default()
+ };
+
+ assert_eq!(
+ resolve_project_name(&config, None).unwrap(),
+ "acme-group-api"
+ );
+ }
+
+ #[test]
+ fn static_scope_uses_path_default_and_respects_marker_opt_out_and_project() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let repo = tmp.path().join("checkout");
+ std::fs::create_dir(&repo).unwrap();
+ if !git(&["init", "-q"], &repo) {
+ return;
+ }
+ assert!(git(
+ &[
+ "remote",
+ "add",
+ "origin",
+ "[email protected]:Acme/Group/API.git"
+ ],
+ &repo
+ ));
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_for_tests(repo.to_str().unwrap()),
+ ..Config::default()
+ };
+ assert_eq!(
+ resolve_scope(&config, None, None).unwrap(),
+ ("default".into(), "acme-group-api".into())
+ );
+
+ std::fs::write(
+ repo.join(".ai-memory.toml"),
+ "workspace = \"oss\"\nidentity_style = \"host_path\"\n",
+ )
+ .unwrap();
+ assert_eq!(
+ resolve_scope(&config, None, None).unwrap(),
+ ("oss".into(), "checkout".into())
+ );
+
+ std::fs::write(
+ repo.join(".ai-memory.toml"),
+ "workspace = \"oss\"\nproject = \"pinned\"\n",
+ )
+ .unwrap();
+ assert_eq!(
+ resolve_scope(&config, None, None).unwrap(),
+ ("oss".into(), "pinned".into())
+ );
+ }
+
+ #[test]
+ fn remote_path_wins_explicit_repo_root_strategy_without_project_or_identity_override() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let repo = tmp.path().join("checkout");
+ let subdir = repo.join("crates/cli");
+ std::fs::create_dir_all(&subdir).unwrap();
+ if !git(&["init", "-q"], &repo) {
+ return;
+ }
+ assert!(git(
+ &[
+ "remote",
+ "add",
+ "origin",
+ "[email protected]:Acme/Group/API.git"
+ ],
+ &repo
+ ));
+ std::fs::write(
+ repo.join(".ai-memory.toml"),
+ "workspace = \"oss\"\nproject_strategy = \"repo-root\"\n",
+ )
+ .unwrap();
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_for_tests(subdir.to_str().unwrap()),
+ ..Config::default()
+ };
+
+ assert_eq!(
+ resolve_scope(&config, None, None).unwrap(),
+ ("oss".into(), "acme-group-api".into())
+ );
+ assert_eq!(
+ resolve_scope_for_path(&Config::default(), &subdir).unwrap(),
+ ("oss".into(), "acme-group-api".into())
+ );
+ }
+
+ #[test]
+ fn remote_less_git_subdirectory_uses_basename_unless_repo_root_is_explicit() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let repo = tmp.path().join("checkout");
+ let subdir = repo.join("crates/cli");
+ std::fs::create_dir_all(&subdir).unwrap();
+ if !git(&["init", "-q"], &repo) {
+ return;
+ }
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_for_tests(subdir.to_str().unwrap()),
+ ..Config::default()
+ };
+
+ assert_eq!(resolve_project_name(&config, None).unwrap(), "cli");
+ assert_eq!(
+ resolve_scope(&config, None, None).unwrap(),
+ ("default".into(), "cli".into())
+ );
+ assert_eq!(
+ resolve_scope_for_path(&Config::default(), &subdir).unwrap(),
+ ("default".into(), "cli".into())
+ );
+
+ std::fs::write(
+ repo.join(".ai-memory.toml"),
+ "project_strategy = \"repo-root\"\n",
+ )
+ .unwrap();
+ assert_eq!(
+ resolve_scope(&config, None, None).unwrap(),
+ ("default".into(), "checkout".into())
+ );
+ assert_eq!(
+ resolve_scope_for_path(&Config::default(), &subdir).unwrap(),
+ ("default".into(), "checkout".into())
+ );
+ }
+
#[test]
fn resolve_project_name_uses_host_cwd_basename() {
let config = Config {
@@ -605,7 +788,7 @@ mod tests {
}
#[test]
- fn workspace_only_marker_uses_hook_basename_from_a_subdirectory() {
+ fn workspace_only_marker_without_remote_uses_hook_basename_from_a_subdirectory() {
let tmp = tempfile::TempDir::new().unwrap();
std::fs::write(tmp.path().join(".ai-memory.toml"), "workspace = \"acme\"\n").unwrap();
let subdir = tmp.path().join("crates").join("cli");
@@ -671,7 +854,7 @@ mod tests {
}
#[test]
- fn workspace_only_marker_uses_linked_worktree_directory_name() {
+ fn remote_less_workspace_marker_uses_linked_worktree_directory_name() {
let tmp = tempfile::TempDir::new().unwrap();
let worktree = tmp.path().join("feature-worktree");
std::fs::create_dir_all(&worktree).unwrap();
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index 3eae9354..1491520f 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -210,11 +210,10 @@ pub(crate) fn manifest_json() -> String {
/// Emit OpenClaw's `applyMarkerParams` TypeScript from the shared generator.
///
-/// OpenClaw omits managed-run forwarding and preserves its historical rule
-/// that ordinary local markers inspect repository identity only when aliases
-/// require it. Operator-home routes may still inspect identity for selection.
+/// OpenClaw omits managed-run forwarding but otherwise uses the shared
+/// repository-identity/default-path routing generated for TypeScript clients.
fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
- super::install_hooks::ts_apply_marker_params(default_strategy, false).replacen(
+ super::install_hooks::ts_apply_marker_params(default_strategy, true).replacen(
" const managedRun = process.env.AI_MEMORY_RUN_ID;\n if (managedRun) url.searchParams.set(\"managed_run\", managedRun);\n",
"",
1,
@@ -919,7 +918,7 @@ mod tests {
}
#[test]
- fn openclaw_runtime_gates_local_identity_but_allows_alias_and_home_route_identity() {
+ fn openclaw_runtime_preserves_marker_and_home_identity_precedence() {
if !std::process::Command::new("node")
.args(["--experimental-strip-types", "-e", "0"])
.output()
@@ -960,7 +959,7 @@ mod tests {
.unwrap()
.0;
let source = format!(
- "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync, unlinkSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst repoCwd={};const marker={};const homeMarker={};const run=(body:string)=>{{writeFileSync(marker,body);const url=new URL(\"http://h/hook\");applyMarkerParams(url,repoCwd);return Object.fromEntries(url.searchParams);}};const plain=run('project=\"api\"\\n');const aliases=run('project=\"api\"\\naliases=[\"old-api\"]\\n');unlinkSync(marker);writeFileSync(homeMarker,'[routes.identity.\"github.com/acme/api\"]\\nroute_workspace=\"oss\"\\nroute_project=\"api\"\\n');const routedUrl=new URL(\"http://h/hook\");applyMarkerParams(routedUrl,repoCwd);process.stdout.write(JSON.stringify({{plain,aliases,routed:Object.fromEntries(routedUrl.searchParams)}}));",
+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync, unlinkSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst repoCwd={};const marker={};const homeMarker={};const run=(body:string)=>{{writeFileSync(marker,body);const url=new URL(\"http://h/hook\");applyMarkerParams(url,repoCwd);return Object.fromEntries(url.searchParams);}};const noMarkerUrl=new URL(\"http://h/hook\");applyMarkerParams(noMarkerUrl,repoCwd);const noMarker=Object.fromEntries(noMarkerUrl.searchParams);const plain=run('project=\"api\"\\n');const aliases=run('project=\"api\"\\naliases=[\"old-api\"]\\n');unlinkSync(marker);writeFileSync(homeMarker,'[routes.identity.\"github.com/acme/api\"]\\nroute_workspace=\"oss\"\\nroute_project=\"api\"\\n');const routedUrl=new URL(\"http://h/hook\");applyMarkerParams(routedUrl,repoCwd);process.stdout.write(JSON.stringify({{noMarker,plain,aliases,routed:Object.fromEntries(routedUrl.searchParams)}}));",
helpers,
serde_json::to_string(&repo.to_string_lossy()).unwrap(),
serde_json::to_string(&marker.to_string_lossy()).unwrap(),
@@ -980,6 +979,8 @@ mod tests {
String::from_utf8_lossy(&output.stderr)
);
let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(result["noMarker"]["identity_src"], "git_remote", "{result}");
+ assert_eq!(result["noMarker"]["identity_style"], "path", "{result}");
assert!(result["plain"].get("identity").is_none(), "{result}");
assert_eq!(result["aliases"]["identity_src"], "git_remote", "{result}");
assert_eq!(result["aliases"]["aliases"], "[\"old-api\"]", "{result}");
diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rs
index f3a48441..66991975 100644
--- a/crates/ai-memory-cli/src/marker.rs
+++ b/crates/ai-memory-cli/src/marker.rs
@@ -123,6 +123,16 @@ pub(crate) struct MarkerScope {
pub(crate) project: Option<String>,
/// `project_strategy = "…"`, or the install-wide env default.
pub(crate) project_strategy: Option<String>,
+ /// Explicit repository identity, which keeps name derivation on the legacy
+ /// local path because it is already an operator-chosen coordinate.
+ pub(crate) identity: Option<String>,
+ /// Explicit remote naming style from marker/home routing. When absent, current
+ /// static CLI clients choose and send [`IdentityStyle::Path`]; only omission
+ /// at the server/wire boundary defaults to legacy [`IdentityStyle::HostPath`]
+ /// for old-client compatibility.
+ pub(crate) identity_style: Option<IdentityStyle>,
+ /// Normalized remote discovered for the selected checkout, when any.
+ pub(crate) remote_identity: Option<RepositoryIdentity>,
}
#[derive(Debug, Clone)]
@@ -686,6 +696,12 @@ pub(crate) fn inspect_scope_for(
.filter(|s| !s.trim().is_empty())
.map(str::to_owned)
}),
+ identity: fields.identity.clone(),
+ identity_style: fields
+ .identity_style
+ .as_deref()
+ .and_then(IdentityStyle::from_str_opt),
+ remote_identity: route_identity.clone(),
};
MarkerInspection {
status: match selection.source {
@@ -703,7 +719,22 @@ impl MarkerScope {
/// Whether this marker declares anything that changes scope resolution.
/// A marker that only carries `[capture]` rules does not.
pub(crate) fn declares_scope(&self) -> bool {
- self.workspace.is_some() || self.project.is_some() || self.is_repo_root()
+ self.workspace.is_some()
+ || self.project.is_some()
+ || self.identity.is_some()
+ || self.identity_style.is_some()
+ || self.remote_identity.is_some()
+ || self.is_repo_root()
+ }
+
+ pub(crate) fn canonical_remote_project(&self) -> Option<String> {
+ if self.project.is_some() || self.identity.is_some() {
+ return None;
+ }
+ let repository = self.remote_identity.as_ref()?;
+ (self.identity_style.unwrap_or(IdentityStyle::Path) == IdentityStyle::Path)
+ .then(|| ai_memory_core::repository_identity::path_style_name(repository))
+ .flatten()
}
/// Whether the effective strategy asks for repo-root project naming.
@@ -752,6 +783,20 @@ pub(crate) fn read_scope_for(
workspace: selection.fields.workspace,
project: selection.fields.project,
project_strategy: selection.fields.project_strategy,
+ identity: selection.fields.identity,
+ identity_style: selection
+ .fields
+ .identity_style
+ .as_deref()
+ .and_then(IdentityStyle::from_str_opt),
+ remote_identity: selection
+ .remote_identity
+ .or_else(|| discover_remote_identity(identity_cwd))
+ .or_else(|| {
+ (lookup_cwd != identity_cwd)
+ .then(|| discover_remote_identity(lookup_cwd))
+ .flatten()
+ }),
path: selection.path,
};
if scope.project_strategy.is_none() {
@@ -864,11 +909,11 @@ pub(crate) fn routing_selection_with_home(
path,
fields,
source: RoutingSource::HomeRoot,
- remote_identity: None,
+ remote_identity,
}))
}
-fn discover_remote_identity(cwd: &str) -> Option<RepositoryIdentity> {
+pub(crate) fn discover_remote_identity(cwd: &str) -> Option<RepositoryIdentity> {
let (upstream, origin) = ai_memory_consolidate::read_identity_remotes(Path::new(cwd));
[upstream.as_deref(), origin.as_deref()]
.into_iter()
@@ -1900,6 +1945,9 @@ project = "infra" # this is fine
workspace: None,
project: None,
project_strategy: None,
+ identity: None,
+ identity_style: None,
+ remote_identity: None,
};
for spelling in ["repo-root", "repo_root"] {
@@ -1946,8 +1994,8 @@ project = "infra" # this is fine
}
/// When every marker in the ancestor chain is capture-only (or none
- /// exist), behavior is unchanged from before #668: `read_scope` returns
- /// `None` so the caller falls back to `DEFAULT_WORKSPACE` + repo-root.
+ /// exist), `read_scope` returns `None` so the caller uses the normal
+ /// remote-path identity, or the cwd basename when no valid remote exists.
#[test]
fn read_scope_still_none_when_only_capture_only_markers_exist() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
index 13bd8b95..6700ae49 100644
--- a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
@@ -536,6 +536,7 @@ mod slow {
("project", project_name),
("identity", identity),
("identity_src", "git_remote"),
+ ("identity_style", "host_path"),
])
.json(&json!({
"session_id": format!("00000000-0000-4000-8000-0000000001{index:02x}"),
diff --git a/crates/ai-memory-core/src/repository_identity.rs b/crates/ai-memory-core/src/repository_identity.rs
index 51518bf5..82a80657 100644
--- a/crates/ai-memory-core/src/repository_identity.rs
+++ b/crates/ai-memory-core/src/repository_identity.rs
@@ -555,18 +555,20 @@ fn project_name_from(raw: &str) -> String {
/// How a remote-derived key spells a repository (#1033).
///
/// Chosen by `identity_style` in `.ai-memory.toml`. Either way captures route
-/// by the full #708 identity; the style only decides the name a **new**
-/// remote-backed project is created under. `HostPath` is the default and keeps
-/// today's naming. `Path` names it from the repository path without the host
-/// ([`path_style_name`]), so worktrees and clones agree on a short name. Two
-/// forges hosting the same path must never share a project, so the store
-/// falls back to today's name when the path name is already taken.
+/// by the full #708 identity; the style only decides the canonical name of a
+/// remote-backed project. Phase-5 clients explicitly send `Path` and name it
+/// from the whole repository path without the host ([`path_style_name`]), so
+/// worktrees and clones agree on a short name. The Rust/wire default remains
+/// `HostPath` because pre-Phase-5 clients omitted their implicit host-path
+/// style; preserving omission is the version-skew boundary. Two forges hosting the same path must never
+/// share a project, so the store falls back to the hostful/legacy-safe name when
+/// the path name is already claimed by another full identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IdentityStyle {
/// `acme/api` — the repository path without its host.
Path,
- /// `github.com/acme/api` — the full #708 identity.
+ /// `github.com/acme/api` — the full #708 identity and legacy wire default.
#[default]
HostPath,
}
@@ -1099,9 +1101,8 @@ mod tests {
);
}
- /// The marker spellings every client forwards: only `path` asks for
- /// anything, so a client sends `identity_style=path` exactly when the
- /// fixture's `style` is `path`.
+ /// The explicit marker spellings every client forwards. Omission is not a
+ /// third spelling; each server applies its own versioned default.
#[test]
fn identity_style_values_match_the_shared_fixture() {
let cases: serde_json::Value = serde_json::from_str(CASES).unwrap();
diff --git a/crates/ai-memory-core/src/routing_skills.rs b/crates/ai-memory-core/src/routing_skills.rs
index f8bad2ba..51113526 100644
--- a/crates/ai-memory-core/src/routing_skills.rs
+++ b/crates/ai-memory-core/src/routing_skills.rs
@@ -246,8 +246,9 @@ mod tests {
"Static MCP clients",
"must pass `workspace` and `project` together on every project-scoped call",
"nearest `.ai-memory.toml`",
- "never guess them from a directory name",
- "never rely on the server's last active project",
+ "normalized `upstream`, then `origin`",
+ "folder basename only when no valid remote exists",
+ "Never rely on the server's last active project",
"`global=true` must omit `workspace`, `project`, and `scopes`",
"`scope: \"global\"`",
] {
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md
index f4f94f15..f7f0c921 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md
@@ -50,7 +50,7 @@ Delete only by exact path. If the user gives a vague title or topic, first resol
Choose scope from the MCP client's identity support:
- **Session-aware MCP clients** that forward the real lifecycle-hook session id on every request should use automatic current-project routing. Omit `workspace`, `project`, and `cwd` for the current repository; pass explicit scope only when the user names a different project.
-- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. If it does not, obtain the names from the operator or server configuration; never guess them from a directory name and never rely on the server's last active project.
+- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. Without a marker override, derive the project from normalized `upstream`, then `origin`, using the full repository path without its host (`github.com/acme/api` → `acme-api`); use the folder basename only when no valid remote exists. Never rely on the server's last active project.
This rule applies only to project-scoped calls. For cross-project retrieval, `global=true` must omit `workspace`, `project`, and `scopes`. For a standing preference written with `scope: "global"`, omit `workspace` and `project`.
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
index 6d942b9a..3d5300a0 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-handoff/SKILL.md
@@ -40,6 +40,6 @@ Accept and cancel normally act only on the caller's own plus shared handoffs. `a
Choose scope from the MCP client's identity support:
- **Session-aware MCP clients** that forward the real lifecycle-hook session id on every request should use automatic current-project routing. Omit `workspace`, `project`, and `cwd` for the current repository; pass explicit scope only when the user names a different project.
-- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. If it does not, obtain the names from the operator or server configuration; never guess them from a directory name and never rely on the server's last active project.
+- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. Without a marker override, derive the project from normalized `upstream`, then `origin`, using the full repository path without its host (`github.com/acme/api` → `acme-api`); use the folder basename only when no valid remote exists. Never rely on the server's last active project.
This rule applies only to project-scoped calls. For cross-project retrieval, `global=true` must omit `workspace`, `project`, and `scopes`. For a standing preference written with `scope: "global"`, omit `workspace` and `project`.
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
index b1f02a26..8491b2f0 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
@@ -45,6 +45,6 @@ Generic ai-memory routing guidance, Agent Skill installation details, and tempor
Choose scope from the MCP client's identity support:
- **Session-aware MCP clients** that forward the real lifecycle-hook session id on every request should use automatic current-project routing. Omit `workspace`, `project`, and `cwd` for the current repository; pass explicit scope only when the user names a different project.
-- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. If it does not, obtain the names from the operator or server configuration; never guess them from a directory name and never rely on the server's last active project.
+- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. Without a marker override, derive the project from normalized `upstream`, then `origin`, using the full repository path without its host (`github.com/acme/api` → `acme-api`); use the folder basename only when no valid remote exists. Never rely on the server's last active project.
This rule applies only to project-scoped calls. For cross-project retrieval, `global=true` must omit `workspace`, `project`, and `scopes`. For a standing preference written with `scope: "global"`, omit `workspace` and `project`.
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-messaging/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-messaging/SKILL.md
index 3af172c9..4868efaa 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-messaging/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-messaging/SKILL.md
@@ -28,6 +28,6 @@ Compose the `body` as a complete, standalone prompt: state the goal, the constra
Choose scope from the MCP client's identity support:
- **Session-aware MCP clients** that forward the real lifecycle-hook session id on every request should use automatic current-project routing. Omit `workspace`, `project`, and `cwd` for the current repository; pass explicit scope only when the user names a different project. The RECIPIENT (`to_workspace` + `to_project`) is always named explicitly, since it is by definition another project.
-- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. If it does not, obtain the names from the operator or server configuration; never guess them from a directory name and never rely on the server's last active project.
+- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. Without a marker override, derive the project from normalized `upstream`, then `origin`, using the full repository path without its host (`github.com/acme/api` → `acme-api`); use the folder basename only when no valid remote exists. Never rely on the server's last active project.
This rule applies only to project-scoped calls. For cross-project retrieval, `global=true` must omit `workspace`, `project`, and `scopes`. For a standing preference written with `scope: "global"`, omit `workspace` and `project`.
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
index e3fc1ede..b878d8ea 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
@@ -23,7 +23,7 @@ Use this skill for read-only ai-memory lookups, catch-up, and evaluating remembe
Choose scope from the MCP client's identity support:
- **Session-aware MCP clients** that forward the real lifecycle-hook session id on every request should use automatic current-project routing. Omit `workspace`, `project`, and `cwd` for the current repository; pass explicit scope only when the user names a different project.
-- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. If it does not, obtain the names from the operator or server configuration; never guess them from a directory name and never rely on the server's last active project.
+- **Static MCP clients** (including clients with lifecycle hooks but no bridge connecting that hook session id to MCP requests) must pass `workspace` and `project` together on every project-scoped call, including requests about this project, here, or our work. Read the exact names from the nearest `.ai-memory.toml` when it declares both. Without a marker override, derive the project from normalized `upstream`, then `origin`, using the full repository path without its host (`github.com/acme/api` → `acme-api`); use the folder basename only when no valid remote exists. Never rely on the server's last active project.
This rule applies only to project-scoped calls. For cross-project retrieval, `global=true` must omit `workspace`, `project`, and `scopes`. For a standing preference written with `scope: "global"`, omit `workspace` and `project`.
diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rs
index 291e6ae2..1178989e 100644
--- a/crates/ai-memory-core/src/routing_snippet.rs
+++ b/crates/ai-memory-core/src/routing_snippet.rs
@@ -42,9 +42,11 @@ for cross-session continuity.
connecting that hook session id to MCP requests) must pass `workspace` and
`project` together on every project-scoped call, including requests about "this
project", "here", or "our work". Read the exact names from the nearest
- `.ai-memory.toml` when it declares both. If it does not, obtain the names from
- the operator or server configuration; never guess them from a directory name
- and never rely on the server's last active project.
+ `.ai-memory.toml` when it declares both. Without a marker override, derive the
+ project from the normalized `upstream` remote, then `origin`, using the full
+ repository path without its host (`github.com/acme/api` → `acme-api`); use the
+ folder basename only when no valid remote exists. Never rely on the server's
+ last active project.
This rule applies only to project-scoped calls. For cross-project retrieval,
`global=true` must omit `workspace`, `project`, and `scopes`. For a standing
@@ -146,7 +148,7 @@ This project uses [ai-memory](https://github.com/akitaonrails/ai-memory) for cro
Choose project scope according to the MCP client's session-identity support:
- **Session-aware clients**: for the current project, omit `workspace`, `project`, and `cwd`; pass explicit scope only when the user names a different project.
-- **Static clients**: pass `workspace` and `project` together on every project-scoped call. Prefer the nearest `.ai-memory.toml` when it declares both; otherwise use operator or server configuration. Never guess scope from a directory name or rely on another session's active-project state.
+- **Static clients**: pass `workspace` and `project` together on every project-scoped call. Prefer the nearest `.ai-memory.toml` when it declares both. Without a marker override, derive the project from normalized `upstream`, then `origin`, using the full repository path without its host (`github.com/acme/api` → `acme-api`); use the folder basename only without a valid remote. Never rely on another session's active-project state.
- For cross-project retrieval with `global=true`, omit `workspace`, `project`, and `scopes`. For durable preferences written with `scope: "global"`, omit `workspace` and `project`.
### Capture and durable memory
@@ -303,7 +305,9 @@ mod tests {
assert!(SNIPPET_BODY.contains("must pass `workspace` and"));
assert!(SNIPPET_BODY.contains("`project` together on every project-scoped call"));
assert!(SNIPPET_BODY.contains("nearest\n `.ai-memory.toml`"));
- assert!(SNIPPET_BODY.contains("never rely on the server's last active project"));
+ assert!(SNIPPET_BODY.contains("normalized `upstream` remote, then `origin`"));
+ assert!(SNIPPET_BODY.contains("folder basename only when no valid remote exists"));
+ assert!(SNIPPET_BODY.contains("Never rely on the server's\n last active project"));
assert!(SNIPPET_BODY.contains("`global=true` must omit"));
assert!(SNIPPET_BODY.contains("`scope: \"global\"`"));
}
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index f06009d7..86e44419 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -97,9 +97,9 @@ pub struct HookQuery {
/// Which rung produced `identity`: `explicit` or `git_remote`. Anything
/// else, or a malformed identity, is ignored and the event routes by name.
pub identity_src: Option<String>,
- /// The marker's `identity_style` (#1033). `path` names a new remote-backed
- /// project from its repository path without the host; anything else keeps
- /// the default. Never changes routing, only what a creation is called.
+ /// An explicit marker `identity_style` (#1033). `path` names a
+ /// remote-backed project from its repository path without the host;
+ /// `host_path` preserves legacy naming. Omission uses the server default.
pub identity_style: Option<String>,
/// Compact JSON array of validated former project names from the local
/// marker. Accepted only with a full git-remote identity.
@@ -1325,6 +1325,36 @@ mod tests {
assert!(!ProjectSource::Unspecified.yields_to_session());
}
+ #[test]
+ fn omitted_style_stays_legacy_host_path_while_new_clients_send_path() {
+ let envelope = |identity_style: Option<&str>| {
+ HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt-submit".into(),
+ identity_style: identity_style.map(str::to_owned),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": "s" }),
+ )
+ };
+ assert_eq!(
+ envelope(None).identity_style,
+ ai_memory_core::repository_identity::IdentityStyle::HostPath
+ );
+ assert_eq!(
+ envelope(Some("path")).identity_style,
+ ai_memory_core::repository_identity::IdentityStyle::Path
+ );
+ assert_eq!(
+ envelope(Some("host_path")).identity_style,
+ ai_memory_core::repository_identity::IdentityStyle::HostPath
+ );
+ assert_eq!(
+ envelope(Some("unknown")).identity_style,
+ ai_memory_core::repository_identity::IdentityStyle::HostPath
+ );
+ }
+
#[test]
fn project_source_is_pinned_unspecified_without_an_override() {
// Provenance describes an override; a `project_src` arriving without
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index b95ab934..1abb6e67 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -2530,6 +2530,7 @@ fn cache_key_for(
project_override: Option<&str>,
project_strategy: ProjectStrategy,
identity: Option<&ai_memory_core::repository_identity::RepositoryIdentity>,
+ identity_style: ai_memory_core::repository_identity::IdentityStyle,
aliases: &ai_memory_core::repository_identity::MarkerAliases,
project_source: ProjectSource,
promote_alias: bool,
@@ -2543,9 +2544,10 @@ fn cache_key_for(
// the identity in the key, whichever resolved first would answer for
// both.
format!(
- "{}:{}:{}:{}:{}",
+ "{}:{}:{}:{}:{}:{}",
identity.map(|i| i.source.as_str()).unwrap_or_default(),
identity.map(|i| i.identity.as_str()).unwrap_or_default(),
+ identity_style.as_str(),
aliases.cache_key(),
project_source.as_str(),
if promote_alias { "write" } else { "read" }
@@ -2630,6 +2632,7 @@ async fn resolve_project_ids_inner(
project_override,
project_strategy,
identity,
+ identity_style,
aliases,
project_source,
promote_alias,
@@ -2890,19 +2893,41 @@ 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 (proj, resolution) = state
- .writer
- .resolve_project_by_identity(
- ws,
- identity.clone(),
- identity_style,
- project_name,
- repo_path,
- parent.map(|(parent_id, _)| parent_id),
- creator,
- )
- .await
- .map_err(|e| anyhow::anyhow!("resolve_project_by_identity: {e}"))?;
+ let candidate = parent.map(|(parent_id, _)| parent_id);
+ let resolved = if promote_alias {
+ state
+ .writer
+ .resolve_project_by_identity_for_capture(
+ ws,
+ identity.clone(),
+ identity_style,
+ project_name,
+ repo_path,
+ candidate,
+ creator,
+ )
+ .await
+ } else {
+ state
+ .writer
+ .resolve_project_by_identity(
+ ws,
+ identity.clone(),
+ identity_style,
+ project_name,
+ repo_path,
+ candidate,
+ creator,
+ )
+ .await
+ };
+ let (proj, resolution) =
+ resolved.map_err(|e| anyhow::anyhow!("resolve_project_by_identity: {e}"))?;
+ if resolution == ai_memory_store::IdentityResolution::Promoted
+ && let Err(error) = state.wiki.refresh_renamed_scope(ws, proj).await
+ {
+ warn!(error = %error, "repository identity promotion committed but manifest refresh failed");
+ }
debug!(
identity = %identity.identity,
source = identity.source.as_str(),
@@ -3476,6 +3501,7 @@ async fn process_authorized(
env.project_override.as_deref(),
env.project_strategy,
env.identity.as_ref(),
+ env.identity_style,
&env.aliases,
env.project_source,
true,
@@ -5139,6 +5165,18 @@ mod tests {
.is_none()
);
assert!(HandoffQuery::default().repository_identity().is_none());
+ assert_eq!(
+ HandoffQuery::default().identity_style(),
+ ai_memory_core::repository_identity::IdentityStyle::HostPath
+ );
+ assert_eq!(
+ HandoffQuery {
+ identity_style: Some("host_path".into()),
+ ..Default::default()
+ }
+ .identity_style(),
+ ai_memory_core::repository_identity::IdentityStyle::HostPath
+ );
}
#[test]
@@ -5396,6 +5434,7 @@ mod tests {
Some("acme-api"),
ProjectStrategy::Basename,
Some(&identity),
+ ai_memory_core::repository_identity::IdentityStyle::Path,
&ai_memory_core::repository_identity::MarkerAliases::new(["old-a"]).unwrap(),
ProjectSource::Marker,
true,
@@ -5406,6 +5445,7 @@ mod tests {
Some("acme-api"),
ProjectStrategy::Basename,
Some(&identity),
+ ai_memory_core::repository_identity::IdentityStyle::Path,
&ai_memory_core::repository_identity::MarkerAliases::new(["old-b"]).unwrap(),
ProjectSource::Marker,
true,
@@ -5417,6 +5457,7 @@ mod tests {
Some("acme-api"),
ProjectStrategy::Basename,
Some(&identity),
+ ai_memory_core::repository_identity::IdentityStyle::Path,
&ai_memory_core::repository_identity::MarkerAliases::new(["old-a"]).unwrap(),
ProjectSource::RepoRoot,
true,
@@ -5427,12 +5468,25 @@ mod tests {
Some("acme-api"),
ProjectStrategy::Basename,
Some(&identity),
+ ai_memory_core::repository_identity::IdentityStyle::Path,
&ai_memory_core::repository_identity::MarkerAliases::new(["old-a"]).unwrap(),
ProjectSource::Marker,
false,
);
+ let host_path = cache_key_for(
+ Some("/repo"),
+ Some("default"),
+ Some("acme-api"),
+ ProjectStrategy::Basename,
+ Some(&identity),
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ &ai_memory_core::repository_identity::MarkerAliases::new(["old-a"]).unwrap(),
+ ProjectSource::Marker,
+ true,
+ );
assert_ne!(first, different_provenance);
assert_ne!(first, read_mode);
+ assert_ne!(first, host_path);
}
/// A capture that carries the repository identity its client resolved.
@@ -5448,6 +5502,9 @@ mod tests {
agent: Some("claude-code".into()),
identity: identity.map(|(identity, _)| identity.to_owned()),
identity_src: identity.map(|(_, source)| source.to_owned()),
+ identity_style: identity
+ .filter(|(_, source)| *source == "git_remote")
+ .map(|_| "path".to_owned()),
..Default::default()
},
serde_json::json!({
@@ -5516,10 +5573,9 @@ mod tests {
.project_id
}
- /// #1033 end to end through `/hook`: `identity_style=path` names a new
- /// repository from its path without the host, so a worktree in another
- /// folder lands in it too. The same path on another forge keeps its folder
- /// name instead of joining it, and an unknown style value is the default.
+ /// #1033 end to end through `/hook`: explicit `path` names a new repository
+ /// from its path without the host, while omitted style and explicit
+ /// `host_path` preserve old-client behavior. Another forge never joins it.
#[tokio::test]
async fn the_path_style_names_a_new_repository_and_never_merges_another_forge() {
let tmp = TempDir::new().unwrap();
@@ -5550,12 +5606,22 @@ mod tests {
);
assert_eq!(name(mirror).await.as_deref(), Some("api"));
- let fallback = capture_styled(&state, &unknown, "github.com/acme/web", Some("Path")).await;
+ let omitted = capture_styled(&state, &unknown, "github.com/acme/web", None).await;
assert_eq!(
- name(fallback).await.as_deref(),
+ name(omitted).await.as_deref(),
Some("web"),
- "an unknown style value keeps today's naming"
+ "old-client omission keeps legacy naming"
);
+ let explicit_dir = tmp.path().join("explicit").join("site");
+ std::fs::create_dir_all(&explicit_dir).unwrap();
+ let explicit = capture_styled(
+ &state,
+ &explicit_dir,
+ "github.com/acme/site",
+ Some("host_path"),
+ )
+ .await;
+ assert_eq!(name(explicit).await.as_deref(), Some("site"));
}
/// #708's collision, end to end: two unrelated repositories both checked
@@ -5605,16 +5671,20 @@ mod tests {
.await;
assert_eq!(again, a, "one repository, one project, whatever the folder");
- // A client that sends nothing, or a rung that routes by name, keeps
- // today's routing: the folder name.
+ // A client that sends no repository identity falls back to the folder
+ // name. Here that name is already occupied by repository A, so it
+ // resolves there without inventing another project.
let plain = tmp.path().join("plain").join("api");
std::fs::create_dir_all(&plain).unwrap();
let by_name =
capture_with_identity(&state, &plain, &SessionId::new().to_string(), None).await;
- assert_eq!(
- by_name, a,
- "no identity routes by the folder name, as before"
- );
+ let plain_name = state
+ .reader
+ .project_name_by_id(state.workspace_id, by_name)
+ .await
+ .unwrap();
+ assert_eq!(plain_name.as_deref(), Some("api"));
+ assert_ne!(by_name, a, "canonical path naming leaves `api` available");
let declared = capture_with_identity(
&state,
&plain,
@@ -5622,7 +5692,10 @@ mod tests {
Some(("github.com/orgc/api", "manifest")),
)
.await;
- assert_eq!(declared, a, "a manifest identity is ignored on the wire");
+ assert_eq!(
+ declared, by_name,
+ "a manifest identity is ignored on the wire and routes by folder name"
+ );
}
/// Two machines sharing one server can hold unrelated repositories at the
@@ -9895,7 +9968,7 @@ mod tests {
String::new(),
String::new(),
ProjectStrategy::Basename.as_str().to_string(),
- ":::unspecified:write".to_string(),
+ "::host_path::unspecified:write".to_string(),
);
assert!(
cache.contains_key(&key),
@@ -10242,6 +10315,7 @@ mod tests {
Some("scratch"),
ProjectStrategy::Basename,
None,
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
&ai_memory_core::repository_identity::MarkerAliases::default(),
ProjectSource::Unspecified,
true,
@@ -15489,7 +15563,7 @@ mod tests {
String::new(),
String::new(),
strat.clone(),
- ":::unspecified:write".to_string(),
+ "::host_path::unspecified:write".to_string(),
)),
"cache key must remain case-folded for #806 stickiness"
);
@@ -15499,7 +15573,7 @@ mod tests {
String::new(),
String::new(),
strat,
- ":::unspecified:write".to_string(),
+ "::host_path::unspecified:write".to_string(),
)),
"cache key must not carry the original-case basename"
);
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 9714e4d1..346a673a 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -176,8 +176,10 @@ Long-term memory for the current project.\n\
real lifecycle-hook session id should omit `workspace`, `project`, and `cwd` for \
the current repository. Static MCP clients must pass `workspace` and `project` together \
on every project-scoped call, including calls about 'this project'; read the exact \
-names from the nearest `.ai-memory.toml` or obtain them from the operator/server, \
-never from a guessed directory name or the server's last active project. For \
+names from the nearest `.ai-memory.toml`; without a marker override, derive the \
+project from normalized `upstream`, then `origin`, using the full repository path \
+without its host, and use the folder basename only without a valid remote. Never \
+rely on the server's last active project. For \
`memory_query` with `global=true`, omit all project scope arguments. For \
`memory_write_page` with `scope: \"global\"`, omit `workspace` and `project`.\n\
\n\
@@ -8047,7 +8049,8 @@ mod tests {
);
assert!(
snippet.contains("nearest\n `.ai-memory.toml`")
- && snippet.contains("never rely on the server's last active project"),
+ && snippet.contains("normalized `upstream` remote, then `origin`")
+ && snippet.contains("Never rely on the server's\n last active project"),
"snippet must require exact, repository-owned scope names"
);
assert!(
@@ -8254,7 +8257,9 @@ mod tests {
assert!(
lower.contains("workspace")
&& lower.contains("project")
- && lower.contains("server's last active project"),
+ && lower.contains("upstream")
+ && lower.contains("origin")
+ && lower.contains("last active project"),
"prompt must provide safe explicit-scope guidance"
);
}
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index cbe2dca3..d197ba15 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -398,6 +398,9 @@ pub enum IdentityResolution {
/// refuse — never split, which would let the first outsider after an
/// upgrade take the identity away from the team whose project it is.
Unclaimed,
+ /// An existing identity-backed project was renamed to its canonical path
+ /// name after write authorization, preserving the project UUID.
+ Promoted,
/// No project existed under the name; one was created with the identity.
Created,
/// The name belonged to a project with a different identity, so a new one
@@ -616,11 +619,11 @@ fn insert_project_with_identityless_name(
/// a project this call creates is named
/// [`path_style_name`](ai_memory_core::repository_identity::path_style_name)
/// instead (#1033), but only while no project in the workspace holds that
-/// name. A holder is necessarily a different repository — the identity match
-/// above already returned the same one — typically the same path on another
-/// forge, so the newcomer falls back to the name it would otherwise get and is
-/// never merged in. The style never renames, claims or splits an existing
-/// project: it only changes what a creation is called.
+/// name or canonical key. A holder with another full identity — typically the
+/// same path on another forge — makes the newcomer fall back to the name it
+/// would otherwise get and is never merged in. Capture resolution may claim or
+/// promote a compatible existing row only after write authorization in this
+/// transaction; read-only and non-capture callers never rename.
///
/// An identity already on a project is never overwritten. A created project
/// records its creator in `created_by`, as [`get_or_create_project_as`] does. A
@@ -637,6 +640,7 @@ pub fn resolve_project_by_identity(
workspace_id: &ai_memory_core::WorkspaceId,
identity: &ai_memory_core::repository_identity::RepositoryIdentity,
style: ai_memory_core::repository_identity::IdentityStyle,
+ promote: bool,
name: &str,
repo_path: Option<&str>,
candidate: Option<ai_memory_core::ProjectId>,
@@ -656,6 +660,31 @@ pub fn resolve_project_by_identity(
.optional()?
.is_none())
};
+ let canonical_name_available =
+ |tx: &rusqlite::Transaction<'_>, name: &str| -> StoreResult<bool> {
+ for (column, index) in [
+ ("name", "sqlite_autoindex_projects_2"),
+ ("canonical_name", "idx_projects_canonical_name"),
+ ] {
+ let sql = format!(
+ "SELECT 1 FROM projects INDEXED BY {index} \
+ WHERE workspace_id = ?1 AND {column} = ?2 \
+ AND {column} <> '' AND identity <> ?3 LIMIT 1"
+ );
+ if tx
+ .query_row(
+ &sql,
+ params![workspace_id.as_bytes(), name, identity.identity],
+ |_| Ok(()),
+ )
+ .optional()?
+ .is_some()
+ {
+ return Ok(false);
+ }
+ }
+ Ok(true)
+ };
let path_name = match style {
ai_memory_core::repository_identity::IdentityStyle::Path => {
ai_memory_core::repository_identity::path_style_name(identity)
@@ -663,36 +692,63 @@ pub fn resolve_project_by_identity(
ai_memory_core::repository_identity::IdentityStyle::HostPath => None,
};
let path_name = match path_name {
- Some(path_name) if name_is_free(&tx, &path_name)? => Some(path_name),
+ Some(path_name) if canonical_name_available(&tx, &path_name)? => Some(path_name),
_ => None,
};
- let matched: Option<Vec<u8>> = tx
- .query_row(
- "SELECT id FROM projects WHERE workspace_id = ?1 AND identity = ?2",
- params![workspace_id.as_bytes(), identity.identity],
- |row| row.get(0),
- )
- .optional()?;
- let (id, resolution) = if let Some(bytes) = matched {
- (
- ai_memory_core::ProjectId::from_slice(&bytes)?,
- IdentityResolution::Matched,
- )
+ let matched = crate::project_coordinates::matches(&tx, *workspace_id, name, Some(identity))?
+ .into_iter()
+ .find(|candidate| candidate.provenance.identity);
+ let (id, resolution) = if let Some(matched) = matched {
+ let promote_to = (promote
+ && style == ai_memory_core::repository_identity::IdentityStyle::Path)
+ .then(|| crate::project_coordinates::promotion_target(&matched, path_name.as_deref()?))
+ .flatten()
+ .map(str::to_owned);
+ if let Some(canonical) = promote_to {
+ let may_write = match creator {
+ None => true,
+ Some(user) => crate::project_authz::resolve_project_authz(
+ &tx,
+ *workspace_id,
+ matched.id,
+ &crate::ProjectPrincipal::user(user),
+ true,
+ )?
+ .authorize(crate::ProjectAccess::Write)
+ .is_ok(),
+ };
+ if may_write {
+ rename_project_in_tx(
+ &tx,
+ workspace_id,
+ &matched.id,
+ Some(&matched.current_name),
+ &canonical,
+ creator,
+ "promote_project_name",
+ )?;
+ (matched.id, IdentityResolution::Promoted)
+ } else {
+ (matched.id, IdentityResolution::Matched)
+ }
+ } else {
+ (matched.id, IdentityResolution::Matched)
+ }
} else {
- let candidate_row: Option<(Vec<u8>, String)> = match candidate {
+ let candidate_row: Option<(Vec<u8>, String, String)> = match candidate {
Some(candidate) => tx
.query_row(
- "SELECT id, identity FROM projects WHERE workspace_id = ?1 AND id = ?2",
+ "SELECT id, identity, name FROM projects WHERE workspace_id = ?1 AND id = ?2",
params![workspace_id.as_bytes(), candidate.as_bytes()],
- |row| Ok((row.get(0)?, row.get(1)?)),
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.optional()?,
None => tx
.query_row(
- "SELECT id, identity FROM projects WHERE workspace_id = ?1 AND name = ?2",
+ "SELECT id, identity, name FROM projects WHERE workspace_id = ?1 AND name = ?2",
params![workspace_id.as_bytes(), name],
- |row| Ok((row.get(0)?, row.get(1)?)),
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.optional()?,
};
@@ -711,7 +767,7 @@ pub fn resolve_project_by_identity(
)?;
(id, IdentityResolution::Created)
}
- Some((bytes, held)) if held.is_empty() => {
+ Some((bytes, held, current_name)) if held.is_empty() => {
let id = ai_memory_core::ProjectId::from_slice(&bytes)?;
// The same decision the choke point makes, on this
// transaction, so the claim cannot race a grant change.
@@ -745,7 +801,25 @@ pub fn resolve_project_by_identity(
id.as_bytes()
],
)?;
- (id, IdentityResolution::Claimed)
+ let promote_to = (promote
+ && style == ai_memory_core::repository_identity::IdentityStyle::Path)
+ .then_some(path_name.as_deref())
+ .flatten()
+ .filter(|canonical| *canonical != current_name);
+ if let Some(canonical) = promote_to {
+ rename_project_in_tx(
+ &tx,
+ workspace_id,
+ &id,
+ Some(&current_name),
+ canonical,
+ creator,
+ "promote_project_name",
+ )?;
+ (id, IdentityResolution::Promoted)
+ } else {
+ (id, IdentityResolution::Claimed)
+ }
} else {
(id, IdentityResolution::Unclaimed)
}
diff --git a/crates/ai-memory-store/src/project_coordinates.rs b/crates/ai-memory-store/src/project_coordinates.rs
index 2c5938b0..3e4bd1f8 100644
--- a/crates/ai-memory-store/src/project_coordinates.rs
+++ b/crates/ai-memory-store/src/project_coordinates.rs
@@ -308,6 +308,7 @@ mod tests {
&workspace,
&repository,
ai_memory_core::repository_identity::IdentityStyle::Path,
+ false,
"api",
None,
None,
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index a46ef2cf..7801a9e5 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -103,6 +103,7 @@ pub(crate) enum WriteCmd {
workspace_id: WorkspaceId,
identity: ai_memory_core::repository_identity::RepositoryIdentity,
style: ai_memory_core::repository_identity::IdentityStyle,
+ promote: bool,
name: String,
repo_path: Option<String>,
candidate: Option<ProjectId>,
@@ -1074,12 +1075,38 @@ impl WriterHandle {
repo_path: Option<String>,
candidate: Option<ProjectId>,
creator: Option<ai_memory_core::UserId>,
+ ) -> StoreResult<(ProjectId, ops::IdentityResolution)> {
+ self.resolve_project_by_identity_inner(
+ workspace_id,
+ identity,
+ style,
+ false,
+ name,
+ repo_path,
+ candidate,
+ creator,
+ )
+ .await
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ async fn resolve_project_by_identity_inner(
+ &self,
+ workspace_id: WorkspaceId,
+ identity: ai_memory_core::repository_identity::RepositoryIdentity,
+ style: ai_memory_core::repository_identity::IdentityStyle,
+ promote: bool,
+ name: impl Into<String>,
+ repo_path: Option<String>,
+ candidate: Option<ProjectId>,
+ creator: Option<ai_memory_core::UserId>,
) -> StoreResult<(ProjectId, ops::IdentityResolution)> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::ResolveProjectByIdentity {
workspace_id,
identity,
style,
+ promote,
name: name.into(),
repo_path,
candidate,
@@ -1090,6 +1117,32 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Resolve repository identity for capture and allow transactional
+ /// canonical-name promotion after authorization.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn resolve_project_by_identity_for_capture(
+ &self,
+ workspace_id: WorkspaceId,
+ identity: ai_memory_core::repository_identity::RepositoryIdentity,
+ style: ai_memory_core::repository_identity::IdentityStyle,
+ name: impl Into<String>,
+ repo_path: Option<String>,
+ candidate: Option<ProjectId>,
+ creator: Option<ai_memory_core::UserId>,
+ ) -> StoreResult<(ProjectId, ops::IdentityResolution)> {
+ self.resolve_project_by_identity_inner(
+ workspace_id,
+ identity,
+ style,
+ true,
+ name,
+ repo_path,
+ candidate,
+ creator,
+ )
+ .await
+ }
+
/// Resolve marker aliases inside one workspace and atomically authorize any
/// Phase 1 canonical-name promotion. Returns `None` when no alias exists.
pub async fn resolve_project_aliases_for_write(
@@ -3539,6 +3592,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
workspace_id,
identity,
style,
+ promote,
name,
repo_path,
candidate,
@@ -3550,6 +3604,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
&workspace_id,
&identity,
style,
+ promote,
&name,
repo_path.as_deref(),
candidate,
diff --git a/crates/ai-memory-store/tests/suite/identity_resolution.rs b/crates/ai-memory-store/tests/suite/identity_resolution.rs
index 1b62748b..320c43b3 100644
--- a/crates/ai-memory-store/tests/suite/identity_resolution.rs
+++ b/crates/ai-memory-store/tests/suite/identity_resolution.rs
@@ -96,6 +96,29 @@ async fn resolve_styled(
.unwrap()
}
+async fn resolve_capture(
+ store: &Store,
+ ws: WorkspaceId,
+ identity: &RepositoryIdentity,
+ style: IdentityStyle,
+ name: &str,
+ creator: Option<UserId>,
+) -> (ProjectId, IdentityResolution) {
+ store
+ .writer
+ .resolve_project_by_identity_for_capture(
+ ws,
+ identity.clone(),
+ style,
+ name,
+ Some("/work/api".to_owned()),
+ None,
+ creator,
+ )
+ .await
+ .unwrap()
+}
+
/// The collision the feature exists for: two unrelated `api` checkouts land
/// in two projects, the second named after its owner — and the same
/// repository, wherever it is checked out and whatever the folder is called,
@@ -501,6 +524,142 @@ async fn opting_in_leaves_existing_projects_where_they_are() {
);
}
+#[tokio::test]
+async fn old_client_omitted_style_stays_host_path_and_does_not_promote() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let repository = remote("github.com/acme/api");
+ let project = resolve(&store, ws, &repository, "api", None).await.0;
+
+ let (resolved, how) = resolve_capture(
+ &store,
+ ws,
+ &repository,
+ IdentityStyle::default(),
+ "api-clone",
+ None,
+ )
+ .await;
+
+ assert_eq!(resolved, project);
+ assert_eq!(how, IdentityResolution::Matched);
+ assert_eq!(row(&store, project).0, "api");
+}
+
+#[tokio::test]
+async fn explicit_path_capture_claims_and_promotes_an_identityless_legacy_name_in_one_transaction()
+{
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let legacy = store
+ .writer
+ .get_or_create_project(ws, "api", None)
+ .await
+ .unwrap();
+
+ let (project, how) = resolve_capture(
+ &store,
+ ws,
+ &remote("github.com/acme/api"),
+ IdentityStyle::Path,
+ "api",
+ None,
+ )
+ .await;
+
+ assert_eq!(project, legacy);
+ assert_eq!(how, IdentityResolution::Promoted);
+ assert_eq!(row(&store, project).0, "acme-api");
+ assert_eq!(row(&store, project).1, "github.com/acme/api");
+}
+
+#[tokio::test]
+async fn explicit_path_capture_promotes_an_authorized_legacy_name_without_changing_uuid() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let repository = remote("github.com/acme/api");
+ let project = resolve(&store, ws, &repository, "api", None).await.0;
+
+ let (promoted, how) = resolve_capture(
+ &store,
+ ws,
+ &repository,
+ IdentityStyle::Path,
+ "api-clone",
+ None,
+ )
+ .await;
+
+ assert_eq!(promoted, project);
+ assert_eq!(how, IdentityResolution::Promoted);
+ assert_eq!(row(&store, project).0, "acme-api");
+}
+
+#[tokio::test]
+async fn unauthorized_capture_cannot_claim_or_promote_an_identityless_legacy_name() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let project = store
+ .writer
+ .get_or_create_project(ws, "api", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(project, AccessMode::Restricted)
+ .await
+ .unwrap();
+ let outsider = user(&store, "claim-promotion-outsider", 32).await;
+
+ let (resolved, how) = resolve_capture(
+ &store,
+ ws,
+ &remote("github.com/acme/api"),
+ IdentityStyle::Path,
+ "api",
+ Some(outsider),
+ )
+ .await;
+
+ assert_eq!(resolved, project);
+ assert_eq!(how, IdentityResolution::Unclaimed);
+ assert_eq!(row(&store, project).0, "api");
+ assert_eq!(row(&store, project).1, "");
+}
+
+#[tokio::test]
+async fn unauthorized_capture_resolves_but_cannot_promote_a_legacy_name() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let repository = remote("github.com/acme/api");
+ let project = resolve(&store, ws, &repository, "api", None).await.0;
+ store
+ .writer
+ .set_access_mode(project, AccessMode::Restricted)
+ .await
+ .unwrap();
+ let outsider = user(&store, "promotion-outsider", 33).await;
+
+ let (resolved, how) = resolve_capture(
+ &store,
+ ws,
+ &repository,
+ IdentityStyle::Path,
+ "api-clone",
+ Some(outsider),
+ )
+ .await;
+
+ assert_eq!(resolved, project);
+ assert_eq!(how, IdentityResolution::Matched);
+ assert_eq!(row(&store, project).0, "api");
+}
+
/// The style only renames what has a host to drop: a declared identity keeps
/// the name the client sent.
#[tokio::test]
@@ -1243,6 +1402,25 @@ async fn read_only_user_cannot_promote_a_legacy_name() {
assert_eq!(row(&store, project).0, "api");
}
+#[tokio::test]
+async fn explicit_path_capture_falls_back_when_another_identity_claims_the_canonical_key() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let github = remote("github.com/acme/api");
+ let gitlab = remote("gitlab.com/acme/api");
+ let existing = resolve(&store, ws, &github, "api", None).await.0;
+ let conflicting = resolve(&store, ws, &gitlab, "acme-api", None).await.0;
+
+ let (resolved, how) =
+ resolve_capture(&store, ws, &github, IdentityStyle::Path, "api-clone", None).await;
+
+ assert_eq!(resolved, existing);
+ assert_eq!(how, IdentityResolution::Matched);
+ assert_eq!(row(&store, existing).0, "api");
+ assert_eq!(row(&store, conflicting).0, "acme-api");
+}
+
#[tokio::test]
async fn canonical_target_conflict_rolls_back_the_promotion() {
let tmp = tempfile::TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rs
index 48116ca2..19c4a4ed 100644
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@ -88,8 +88,8 @@ fn page(ws: WorkspaceId, proj: ProjectId, path: &str, title: &str, body: &str) -
}
/// #1033 under invariant #16: two operators on two clones of one repository,
-/// in folders named differently, opt into the `path` style and capture at the
-/// same time. They must land in one project — the same name and the same row —
+/// in folders named differently, use the default `path` style and capture at
+/// the same time. They must land in one project — the same name and the same row —
/// so each reads what the other writes; a race must not split the repository.
#[tokio::test]
async fn two_operators_on_two_clones_of_one_repository_share_its_path_named_project() {
@@ -111,7 +111,7 @@ async fn two_operators_on_two_clones_of_one_repository_share_its_path_named_proj
let repo = repo.clone();
async move {
writer
- .resolve_project_by_identity(
+ .resolve_project_by_identity_for_capture(
ws,
repo,
IdentityStyle::Path,
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 780d6a0c..6da5b388 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -394,7 +394,7 @@ prunable rather than only after it ages in place.
| Table | What |
|---|---|
-| `workspaces`, `projects` | Top of the 3-tuple identity coordinate. `projects.identity` / `identity_source` (V70, #708) hold the repository identity a project routes by — an explicit marker `identity` or a normalised git remote, resolved client-side — unique per workspace when set; empty until a capture claims the project. A marker's `identity_style = "path"` (#1033, forwarded as the `identity_style` hook query param alongside a git-remote identity; default `host_path`) names a project that resolution *creates* from the repository path without the host (`acme-api`), falling back to the usual name when another project already holds it. V76 stores indexed canonical and v2-basename keys derived from that full identity: reads are no-create/no-rename, while an authorized explicit write through the canonical name promotes only `projects.name` in the same resolve-or-create writer transaction and preserves the UUID. Project `_meta.md` carries the optional full identity/source plus derived keys; clean reindex validates them and rebuilds the same UUID/name/coordinate lookup, while older manifests without identity remain valid. Ambiguous cross-forge or multi-candidate keys fail closed. A local marker may additionally send up to 16 validated former names as one transient `aliases` JSON-array query value: lookup stays inside its selected workspace, requires the checkout's full hostful git-remote identity to equal the stored row, returns reads without rename, and lets capture perform only the same authorized UUID-preserving canonical promotion. Aliases are not stored and remain distinct in the hook routing cache. The exact operator-home marker may additionally define bounded `[routes.identity."host/path"]` and `[routes.path."absolute-or-tilde-path"]` blocks: an exact hostful remote match wins the longest component-wise lexical path match, any reachable non-home local settings marker wins both, malformed or ambiguous route maps fail closed, and selected fields reuse the existing marker wire without a server/schema change. `AI_MEMORY_HOME` is authoritative for native callers; portable clients use `HOME`/`USERPROFILE`, and Docker compares its forwarded host cwd. See `docs/marker-file.md#repository-identity`. `projects.access_mode` (V68; `open` default / `restricted`) decides whether any authenticated user or only root, the creator (`projects.created_by`, V69) and grant holders (`project_grants`, V68) reach it, decided by `ai_memory_store::authorize_project` — `docs/users.md#per-project-access`. `projects.profile_contribute` / `profile_consume` (V74) record the marker's `[profile]` opt-outs, forwarded at session start; `profile_candidates`, `profile_harvest_marks` and `profile_entry_ledger` (V75) hold the profile pass's evidence, per-project read position and the entries it wrote. Reserved projects: `scratch`, `_global` (shared preferences; holds the single-user profile under `profile/`), `_profile` (a workspace profile) and `_profile.<user id>` (a private profile, always `restricted`); capture is never attributed to any of them — `docs/cross-project-profile.md`. |
+| `workspaces`, `projects` | Top of the 3-tuple identity coordinate. `projects.identity` / `identity_source` (V70, #708) hold the repository identity a project routes by — an explicit marker `identity` or a normalised git remote, resolved client-side — unique per workspace when set; empty until a capture claims the project. Phase-5 clients explicitly send `IdentityStyle::Path` (#1033) for remote-backed projects, naming them from the full repository path without the host (`acme-api`), and send explicit `host_path` for the pre-v3 opt-out. Server-side omission remains `HostPath` because old clients omitted that historical default; no new wire field is needed. Creation or authorized capture promotion uses that canonical name only when no different hostful identity claims it; otherwise resolution falls back to the existing hostful/legacy-safe name. V76 stores indexed canonical and v2-basename keys derived from that full identity: reads are no-create/no-rename, while an authorized explicit write through the canonical name promotes only `projects.name` in the same resolve-or-create writer transaction and preserves the UUID. Project `_meta.md` carries the optional full identity/source plus derived keys; clean reindex validates them and rebuilds the same UUID/name/coordinate lookup, while older manifests without identity remain valid. Ambiguous cross-forge or multi-candidate keys fail closed. A local marker may additionally send up to 16 validated former names as one transient `aliases` JSON-array query value: lookup stays inside its selected workspace, requires the checkout's full hostful git-remote identity to equal the stored row, returns reads without rename, and lets capture perform only the same authorized UUID-preserving canonical promotion. Aliases are not stored and remain distinct in the hook routing cache. The exact operator-home marker may additionally define bounded `[routes.identity."host/path"]` and `[routes.path."absolute-or-tilde-path"]` blocks: an exact hostful remote match wins the longest component-wise lexical path match, any reachable non-home local settings marker wins both, malformed or ambiguous route maps fail closed, and selected fields reuse the existing marker wire without a server/schema change. `AI_MEMORY_HOME` is authoritative for native callers; portable clients use `HOME`/`USERPROFILE`, and Docker compares its forwarded host cwd. See `docs/marker-file.md#repository-identity`. `projects.access_mode` (V68; `open` default / `restricted`) decides whether any authenticated user or only root, the creator (`projects.created_by`, V69) and grant holders (`project_grants`, V68) reach it, decided by `ai_memory_store::authorize_project` — `docs/users.md#per-project-access`. `projects.profile_contribute` / `profile_consume` (V74) record the marker's `[profile]` opt-outs, forwarded at session start; `profile_candidates`, `profile_harvest_marks` and `profile_entry_ledger` (V75) hold the profile pass's evidence, per-project read position and the entries it wrote. Reserved projects: `scratch`, `_global` (shared preferences; holds the single-user profile under `profile/`), `_profile` (a workspace profile) and `_profile.<user id>` (a private profile, always `restricted`); capture is never attributed to any of them — `docs/cross-project-profile.md`. |
| `pages` | Versioned wiki pages with `is_latest` + `supersedes` chain. M8 columns: `last_accessed_at`, `access_count`, and decay-only tombstone marker `superseded_at`. M9 cols: `embedding_provider`, `embedding_model`, `embedding_dim`. V36: `expires_at` (frontmatter TTL). V37: `salience` (NULL = `salience_default`; derived from `page_feedback`). |
| `pages_fts` | FTS5 virtual table over `(title, body)`, auto-synced by triggers. |
| `sessions`, `observations` | Sanitized, bounded lifecycle-hook projections. `sessions.ended_observation_count` is the stable generation watermark for resumed-session re-end eligibility; wall clocks are not used for that decision. They are an operational audit trail, not a complete native transcript. |
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index 6baab471..d2b29027 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -126,9 +126,11 @@ pointers. The durable `SessionId` stored for hook observations remains global:
if another owner reuses an already-owned id, ai-memory drops that hook before it
can append observations or publish a pointer for the foreign actor.
-Pointers hold project ids, not names, so a project named from its repository
-path ([`identity_style = "path"`](marker-file.md#naming-new-projects-by-repository-path-identity_style),
-#1033) is published and resolved exactly like any other.
+Pointers hold project ids, not names, so the default repository-path project
+name ([`identity_style`](marker-file.md#naming-projects-by-repository-path-identity_style),
+#1033) is published and resolved exactly like any other. Static clients derive
+that name from normalized `upstream`, then `origin`; only a checkout without a
+valid remote uses its folder basename.
Owner and agent are what identify a session; scope is not. The same operator's
session legitimately produces events in another project when its cwd moves, so
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 6c926d57..1880f02e 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -12,8 +12,9 @@ as one server; your agent talks to it over MCP (tools like `memory_query`,
`memory_write_page`) and over lifecycle hooks that automatically capture what you
do. Memory is a **markdown wiki in git** (the source of truth, hand-editable) plus
a derived SQLite index for search. Everything is **scoped per project**
-`(workspace, project)`, resolved from your working directory. It works with no
-LLM at all (capture + full-text search + rule-based summaries); adding a provider
+`(workspace, project)`, resolved from markers/home routes or, by default, the
+normalized repository path (`upstream`, then `origin`; folder basename only
+without a valid remote). It works with no LLM at all (capture + full-text search + rule-based summaries); adding a provider
enables consolidation and auto-improvement.
## Recipe: use ai-memory as your tool's memory
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index aef1724a..47baecda 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -264,7 +264,7 @@ not authorize an unscoped write. Any future schema simplification may improve
the explicit/static path, but must preserve the session-aware path unless a
separate major-version decision replaces its UX and concurrency guarantees.
-**Install-time `project_strategy` default (#128).** `basename(cwd)` stays the v1 default, but an agent shell that `cd`s into a subdirectory and stays there silently forks the rest of the session into a phantom project named after the subdir. A `.ai-memory.toml` marker with `project_strategy = "repo-root"` fixes this (#16, #23, #111) but needs a marker in (or above) every repo; a runtime env-var fallback that the *user* sets was deliberately rejected in #16. `install-hooks --project-strategy repo-root` instead **bakes** the strategy into the generated hook command (and the OpenCode / OMP / OpenClaw plugins) at install time — the same status as the already-baked `AI_MEMORY_AUTH_TOKEN` / `AI_MEMORY_HOOK_URL` / `--data-dir`, not a user runtime override. This is a client/install-time-only change: the server already parses `project_strategy=repo-root`. A marker's own `project_strategy` / `project` still win, and the default stays `basename` (baking nothing) so existing installs are byte-identical.
+**Install-time `project_strategy` default (#128).** `basename(cwd)` remains the fallback for a checkout without a valid remote, but an agent shell that `cd`s into a subdirectory and stays there can otherwise fork the rest of the session into a phantom project named after the subdir. The #1033 default now names remote-backed repositories from normalized `upstream`, then `origin`, before this strategy applies. A `.ai-memory.toml` marker with `project_strategy = "repo-root"` fixes the remote-less case (#16, #23, #111) but needs a marker in (or above) every repo; a runtime env-var fallback that the *user* sets was deliberately rejected in #16. `install-hooks --project-strategy repo-root` instead **bakes** the strategy into the generated hook command (and the OpenCode / OMP / OpenClaw plugins) at install time — the same status as the already-baked `AI_MEMORY_AUTH_TOKEN` / `AI_MEMORY_HOOK_URL` / `--data-dir`, not a user runtime override. This is a client/install-time-only change: the server already parses `project_strategy=repo-root`. A marker's explicit `project` or `identity` and operator-home routing still win; an unpinned marker `project_strategy` changes only the no-valid-remote fallback.
## 12. Operability
diff --git a/docs/design-per-project-authz.md b/docs/design-per-project-authz.md
index e6f78563..cb6b713a 100644
--- a/docs/design-per-project-authz.md
+++ b/docs/design-per-project-authz.md
@@ -233,8 +233,7 @@ project. #1033 makes a remote-derived key the default name, landing in steps on
1. **Normaliser and opt-in naming (landed first).** `repository_identity::
styled_key` spells an identity under `IdentityStyle`: `path` drops a git
remote's host (`github.com/acme/api` → `acme/api`); `host_path` is the #708
- identity unchanged and stays the default. A marker's
- `identity_style = "path"` is forwarded by all four capture clients
+ identity unchanged. A marker's explicit style is forwarded by all four capture clients
alongside a remote identity, and `resolve_project_by_identity` then names a
project it **creates** `path_style_name(identity)` (`acme-api`: `/` written
as `-`, today's split-name character rule). Captures keep routing by the
@@ -247,9 +246,14 @@ project. #1033 makes a remote-derived key the default name, landing in steps on
`fixtures/remote_identity_cases.json` (core plus shell, PowerShell and
TypeScript parity), store adversarial tests, and a two-operator
`multi_session.rs` case. Reporting the fallback in `doctor` is a follow-up.
-2. **Default naming chain** (`upstream` → `origin` → folder) for **new**
- projects without opting in, with marker `project`/`identity` still
- outranking remotes and the same collision fallback.
+2. **Default naming chain (landed final).** `upstream` → `origin` supplies the
+ full hostful identity and the canonical hostless path name for new projects;
+ only a checkout with no valid network remote falls back to its folder. Marker
+ `project`/`identity` and operator-home routes still outrank this inference.
+ Phase-5 clients explicitly send `path`; explicit `host_path` is forwarded as
+ the compatibility opt-out. A new server still treats omission as `host_path`
+ because old clients omitted that historical default. Old servers safely
+ accept or ignore the existing style field; no new wire field is required.
3. **Dual-key resolve and in-place name promotion (landed).** Static callers
still pass only `workspace` + `project`. Within that workspace, exact stored
name, the canonical path-style name derived from a stored full hostful git
@@ -299,7 +303,16 @@ project. #1033 makes a remote-derived key the default name, landing in steps on
provenance, malformed or ambiguous maps fail closed, and old line parsers
ignore the deliberately prefixed `route_*` child fields. Native callers use
`AI_MEMORY_HOME` first; portable clients use `HOME`/`USERPROFILE`, and Docker
- compares the forwarded host cwd. The default remains `IdentityStyle::HostPath`.
+ compares the forwarded host cwd.
+7. **Default flip (landed final).** `Path` is now the explicit client default;
+ the typed server/wire default remains legacy-safe `HostPath`. Authorized
+ captures carrying explicit `path` can claim or promote compatible basename/
+ host-path rows in the same writer transaction and preserve their UUID;
+ handoff/static reads remain no-create/no-rename. Canonical names held by a
+ different hostful identity fail closed and use the existing fallback. The
+ indexed canonical/legacy compatibility keys and marker aliases remain through
+ v3; no schema migration was required for this final slice.
+
Paths stay lexically normalised throughout; nothing canonicalises.
diff --git a/docs/install.md b/docs/install.md
index 80954989..55f7f480 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -218,8 +218,10 @@ they either create local files or start the server itself.
### Default project resolution (`--project-strategy`)
-By default each session files memory under `basename(cwd)`. Because an agent
-shell keeps its working directory between tool calls, a single
+By default an undeclared checkout with a valid `upstream` or `origin` remote
+uses the canonical repository-path project name; current clients send that
+choice explicitly for upgrade safety. Repositories without a valid remote use
+`basename(cwd)`, including from a git subdirectory. Because an agent shell keeps its working directory between tool calls, a single
`mkdir sub && cd sub` reparents the rest of the session into a phantom project
named `sub`. To make every session for an install resolve its project from the
git repo root instead — collapsing subdirectories and worktrees — bake the
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 88c2f999..29935648 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -6,8 +6,10 @@ Declare which workspace (and optionally which project) an agent's
## Why
ai-memory namespaces every wiki page by `(workspace, project)`. By
-default, `workspace = "default"` and `project = basename($cwd)`. That
-works for a solo developer in `~/projects/<repo>` but breaks down
+default, `workspace = "default"`; a valid `upstream`/`origin` remote supplies
+the canonical hostless repository-path project name, and only a checkout
+without one uses `project = basename($cwd)`. That works for a solo developer in
+`~/projects/<repo>` but breaks down
for the cases this marker file is built for:
- **Multi-client consultancies** with `~/projects/<client>/<repo>` —
@@ -25,8 +27,9 @@ Static MCP clients also use the marker as the repository-owned source for
explicit scope arguments. For safe concurrent use, declare both `workspace` and
`project`: managed routing tells static clients to pass that pair on every
project-scoped tool call because they cannot attach the real lifecycle-hook
-session id. If either value is absent, the agent must obtain it from the operator
-or server configuration rather than guessing from the checkout directory.
+session id. Without a marker override, static clients derive the project from normalized
+`upstream`, then `origin`, joining the full hostless path with the standard safe
+name mapping; only no-valid-remote checkouts use their folder basename.
Session-aware bridges keep automatic current-project routing.
## Where to put it
@@ -36,9 +39,9 @@ walk up from `cwd` toward `$HOME` (or `/` if `$HOME` is unset) and use the
**first** marker found. When cwd is outside `$HOME`, the walk stops at the
nearest checkout root (`.git` file or directory); outside a checkout, only cwd
itself is checked. Closer markers override outer ones. When a marker is found,
-hook scripts also forward the current `cwd` so
-workspace-only markers can still resolve `project = basename(cwd)` for
-handoff lookups.
+hook scripts also forward the current `cwd` and normalized remote identity so
+workspace-only markers resolve the canonical repository-path project, with
+`basename(cwd)` retained only when no valid remote exists.
A marker whose only content is a `[capture]` section (see
[Capture exclusions](#capture-exclusions) below) is **transparent** to this
@@ -60,7 +63,9 @@ handoff lookup also sends `cwd` when no marker exists so the default
`project = basename(cwd)` route works consistently. Every client also sends
`identity` / `identity_src` when the checkout has a repository identity (see
[Repository identity](#repository-identity)), with or without a marker, and
-`identity_style=path` alongside a remote identity when the marker opts in.
+an explicit `identity_style=path|host_path` alongside every remote identity.
+Current clients send `path` when no marker/home route overrides it; server-side
+omission stays legacy `host_path` for old-client compatibility.
A marker `project` remains the canonical requested name. Its validated `aliases`
travel as one percent-encoded JSON-array `aliases` query value on both hook and
handoff requests, and are ignored unless the checkout supplies a normalized
@@ -73,12 +78,12 @@ hostful git-remote identity.
workspace = "movvia"
# Optional. When present, forces project = "pe-portais" for every
-# cwd inside this marker's tree. Omit it to let basename(cwd) drive
-# the project name.
+# cwd inside this marker's tree. Omit it to use the canonical remote path,
+# falling back to basename(cwd) when no valid remote exists.
project = "pe-portais"
-# Optional. Omit it to preserve project = basename(cwd). Set it to
-# "repo-root" to derive project from the main git repository root, so
+# Optional. Set it to "repo-root" to derive a remote-less project's name
+# from the main git repository root, so
# linked worktrees and subdirectories share one project. Ignored when
# `project` is present.
project_strategy = "repo-root"
@@ -92,12 +97,12 @@ project_strategy = "repo-root"
# identity" below.
identity = "acme/platform"
-# Optional. "path" names a NEW remote-backed project from its repository
-# path without the host ("acme-api" for github.com/acme/api) instead of the
-# folder name. Default "host_path". Existing identity-backed projects can be
-# promoted in place only by an authorized write through that canonical name.
-# See "Naming new projects by repository path" below.
-identity_style = "path"
+# Optional. The default "path" names a remote-backed project from its whole
+# repository path without the host ("acme-api" for github.com/acme/api).
+# Set "host_path" to preserve the pre-v3 folder/split naming behavior.
+# Existing identity-backed projects can be promoted in place only by an
+# authorized capture/write. See "Naming projects by repository path" below.
+identity_style = "host_path"
# Optional. Former names for this same repository in this workspace. At most
# 16 entries, each at most 128 UTF-8 bytes and matching
@@ -224,8 +229,8 @@ example `~/a/../b`) but is rejected if any `..` would escape above HOME;
absolute selectors retain lexical root clamping. The longest path match wins, while an exact identity
match wins over every path match. A reachable non-home local settings marker
wins over all home routes. When no route matches, existing root-level settings
-in the home marker remain the fallback, followed by the installed strategy and
-existing cwd fallbacks; explicit CLI scope always wins. A matched route replaces
+in the home marker remain the fallback, followed by the default remote-path
+identity and then the installed/cwd fallback; explicit CLI scope always wins. A matched route replaces
only the root `workspace`, `project`, `identity`, `identity_style`, `aliases`, and
`project_strategy` routing fields. Root `server`, `drop_subagent_captures`,
`[recall]`, `[briefing]`, and `[profile]` settings still apply.
@@ -649,8 +654,9 @@ If the marker lives inside the main checkout instead (for example
out-of-tree worktree, or place a shared marker above the worktree parent
directory as shown here.
-Without `project_strategy = "repo-root"`, those same paths keep the
-default behavior and resolve by their current directory basename.
+Without `project_strategy = "repo-root"`, a valid remote still gives every
+worktree the default canonical repository-path name. Only remote-less paths
+resolve by their current directory basename.
Resolution is host-side: lifecycle hooks and generated TypeScript
plugins follow the worktree's commondir pointer (`git rev-parse
@@ -665,8 +671,9 @@ a single `~/.ai-memory.toml` — to select the strategy.
### Repository identity
-A project's name comes from its folder, and folder names collide: two
-unrelated repositories both checked out as `api/` would otherwise share one
+A remote-backed project's default name now comes from its normalized repository
+path, while remote-less folders still use their basename. Folder names collide:
+two unrelated repositories both checked out as `api/` would otherwise share one
project. On a server with per-project grants (#708) that means one grant, so
every client resolves a **repository identity** for the checkout and sends it
with each event. The first rung that yields one wins:
@@ -699,17 +706,16 @@ URL never leave the machine. Other remote names (`fork`, `mine`) are
ignored on purpose: they differ per person, and would give one repository a
different identity for each of them.
-#### Naming new projects by repository path (`identity_style`)
+#### Naming projects by repository path (`identity_style`)
-By default a new repository's project takes its folder name, so the first
-checkout to capture decides it (`main`, `fix-1025`, …). Opt in to naming it
-from the remote's repository path instead (#1033):
+By default, an undeclared checkout with a valid `upstream` or `origin` remote is
+named from the remote's whole repository path without its host (#1033):
```toml
-identity_style = "path" # default: "host_path"
+identity_style = "host_path" # explicit pre-v3 compatibility opt-out
```
-With `path`, a **new** project created from a remote is named from the whole
+With the default `path` style, a project created from a remote is named from the whole
repository path without the host, with `/` written as `-`
(`[email protected]:acme/api.git` → `acme-api`,
`https://gitlab.com/acme/group/api.git` → `acme-group-api`), so every
@@ -719,20 +725,23 @@ only with a remote identity — a declared `project` or `identity` keeps its
own name.
- **Existing projects keep their UUID.** Reads by the canonical path name or
- the v2 basename are find-only and never rename. An authorized write that
- explicitly uses the canonical path name promotes only `projects.name` in one
- transaction; pages, sessions, grants, handoffs and every other dependent row
- remain attached to the same UUID. The v2 basename remains readable after
- promotion.
+ the v2 basename are find-only and never rename. An authorized default-style
+ capture or explicit write through the canonical path name promotes only
+ `projects.name` in one transaction; pages, sessions, grants, handoffs and
+ every other dependent row remain attached to the same UUID. The v2 basename
+ remains readable through v3.
- **Another forge is never merged in.** When the path name is already held by
a different repository — typically the same path on another forge
(`gitlab.com/acme/api` after `github.com/acme/api`) — the newcomer falls
back to the name it would get without the style.
-- `aliases` in this phase are supported only by a local marker reachable from
- the checkout. Identity/path-keyed home configuration is a later rollout
- phase; a single inherited `~/.ai-memory.toml` can still supply ordinary
- settings, but it cannot yet map several repository identities independently.
-- Static CLI/MCP clients still pass only `workspace` + `project`. They may use
+- Local marker aliases and operator-home identity/path routes keep their
+ documented precedence over the default and remain available for migration or
+ deliberate remapping.
+- Static CLI/MCP clients still pass only `workspace` + `project`. The thin CLI
+ derives the canonical path name when no marker/home route overrides it; other
+ static clients should use the same name from `upstream`, then `origin`. A valid
+ remote wins `project_strategy = "repo-root"`; the strategy applies only when
+ no valid remote exists. They may use
the canonical path name (`acme-api`) or the v2 basename (`api`) while it is
unambiguous. A hostless key shared by multiple forges fails closed.
- `ai-memory doctor` combines the effective local marker and normalized
@@ -757,8 +766,9 @@ own name.
~/.ai-memory.toml → workspace = "home"
```
-Every cwd under `$HOME` lands in workspace `home` with
-`project = basename(cwd)`. Useful when you just want to opt out of
+Every cwd under `$HOME` lands in workspace `home`; a valid remote uses its
+canonical path name, while a repository without one uses `project = basename(cwd)`.
+Useful when you just want to opt out of
the `default` bucket entirely.
## Migrating existing projects
@@ -880,9 +890,12 @@ split.
Each field is resolved independently:
1. The explicit flag (`--workspace` / `--project`).
-2. The nearest marker: `workspace`, and `project` — or the main repo root's
- basename when only `project_strategy = "repo-root"` is set.
-3. The previous fallbacks: `default`, and the cwd-derived project name.
+2. The nearest marker: explicit `workspace`/`project`/`identity`; otherwise a
+ valid `upstream`/`origin` remote's canonical path name wins, even when
+ `project_strategy = "repo-root"` is set. The strategy selects the main repo
+ root only when no valid remote exists.
+3. The fallbacks: workspace `default` and the current cwd basename. A git
+ subdirectory does not imply repo-root without an explicit strategy.
When rung 2 decides a field, the command prints one line to stderr naming
the resolved scope, which half (or halves) the marker decided, and the
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 1f636e69..b42cb1b3 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -80,8 +80,8 @@ boundary not yet built.
| 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` | 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`. 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`; 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`; under `identity_style = "path"` (#1033) a project it creates takes `path_style_name` only while no project in the workspace holds that name (checked in the same transaction), so the same path on another forge falls back instead of being merged; later static canonical writes may promote that same identity-backed row's name through the separately inventoried scope boundary while keeping its UUID; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `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` and `an_unclaimed_project_holding_the_path_name_is_not_taken` (both fail with the free-name check removed; 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`; `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 |
-| 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_gates_local_identity_but_allows_alias_and_home_route_identity` proves ordinary local markers 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 |
+| 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` `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`; `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 |
+| 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 |
| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index 31208b29..50213281 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -427,13 +427,15 @@ ai_memory_normalize_remote() {
case "$_ai_rn_id" in */*) printf '%s' "$_ai_rn_id" ;; esac
}
-# Print `&identity_style=path` when the marker's `identity_style` ("$1") is
-# `path`, else nothing: `host_path` is the server's default (#1033). Mirrors
-# `forwarded_identity_style` in hook_capture.rs, checked against the shared
-# fixture.
+# Print the Phase-5 style sent with every valid git-remote identity. Explicit
+# marker/home-route values win; omission or invalid input sends `path`. Servers
+# keep a truly omitted field as legacy `host_path` for old-client compatibility.
ai_memory_identity_style_qs() {
_ai_is_value=$(printf '%s' "$1" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
- [ "$_ai_is_value" = "path" ] && printf '&identity_style=path'
+ case "$_ai_is_value" in
+ host_path) printf '&identity_style=host_path' ;;
+ *) printf '&identity_style=path' ;;
+ esac
return 0
}
@@ -719,7 +721,8 @@ ai_memory_marker_qs() {
[ -n "${iq:-}" ] || iq=$(ai_memory_identity_qs "$cwd" "$idn" "$pr" "$isty" "$aliases")
# Install-time default baked into the hook command by
# `install-hooks --project-strategy` fills the strategy only when no marker
- # pinned one. A marker's explicit project / project_strategy still win.
+ # pins one. Explicit project/identity and home routing win; otherwise a
+ # valid remote identity wins and repo-root is the remote-less fallback.
if [ -z "$st" ] && [ -n "${AI_MEMORY_PROJECT_STRATEGY:-}" ]; then
st="$AI_MEMORY_PROJECT_STRATEGY"
fi
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index 2a8a021b..356e19ee 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -537,14 +537,13 @@ function ConvertTo-AiMemoryRepositoryIdentity {
return $id
}
-# `&identity_style=path` when the marker's `identity_style` is `path`, else "":
-# `host_path` is the server's default (#1033). Mirrors
-# `forwarded_identity_style` in hook_capture.rs, checked against the shared
-# fixture.
+# Send a style with every valid git-remote identity. Explicit marker/home-route
+# values win; omission or invalid input sends `path`. A server receiving a truly
+# omitted field keeps legacy `host_path` behavior for old clients.
function Get-AiMemoryIdentityStyleQuery {
param([string] $Style)
- if ($Style -and $Style.Trim() -ceq "path") { return "&identity_style=path" }
- return ""
+ if ($Style -and $Style.Trim() -ceq "host_path") { return "&identity_style=host_path" }
+ return "&identity_style=path"
}
# `&identity=<v>&identity_src=<rung>` for the checkout at $Cwd, or "".
@@ -637,7 +636,8 @@ function Get-AiMemoryMarkerQuery {
if (-not $identityQuery) { $identityQuery = Get-AiMemoryIdentityQuery -Cwd $Cwd -Explicit $explicitIdentity -Project $proj -Style $identityStyle -Aliases $aliases }
# Install-time default baked into the hook command by
# `install-hooks --project-strategy` fills the strategy only when no marker
- # pinned one. A marker's explicit project / project_strategy still win.
+ # pins one. Explicit project/identity and home routing win; otherwise a
+ # valid remote identity wins and repo-root is the remote-less fallback.
if (-not $strategy -and $env:AI_MEMORY_PROJECT_STRATEGY) {
$strategy = $env:AI_MEMORY_PROJECT_STRATEGY
}
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index 61107204..38c902fd 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -260,7 +260,7 @@ printf 'project = "acme-api"\naliases = [" former-name ", "legacy_name", "former
ALIAS_JSON='["former-name","legacy_name"]'
ALIAS_QS=$(ai_memory_marker_qs "$TMP/aliases")
assert_eq "marker aliases keep canonical project and forward remote identity" "yes" \
- "$(case "$ALIAS_QS" in *'&project=acme-api&project_src=marker'*"&identity=git.example.test%2Facme%2Fapi&identity_src=git_remote&aliases=$(ai_memory_url_encode "$ALIAS_JSON")"*) printf yes ;; *) printf no ;; esac)"
+ "$(case "$ALIAS_QS" in *'&project=acme-api&project_src=marker'*"&identity=git.example.test%2Facme%2Fapi&identity_src=git_remote&identity_style=path&aliases=$(ai_memory_url_encode "$ALIAS_JSON")"*) printf yes ;; *) printf no ;; esac)"
mkdir -p "$TMP/home-routes/src/api/lib" "$TMP/home-routes/src/api-sibling"
HOME="$TMP/home-routes"
@@ -382,7 +382,7 @@ if command -v git >/dev/null 2>&1; then
git -C "$TMP/idrepo" remote add origin "https://someone:[email protected]/Acme/API.git"
ID_CWD=$(ai_memory_url_encode "$TMP/idrepo")
assert_eq "identity: undeclared checkout sends its remote" \
- "&cwd=$ID_CWD&identity=$(ai_memory_url_encode git.example.test/acme/api)&identity_src=git_remote" \
+ "&cwd=$ID_CWD&identity=$(ai_memory_url_encode git.example.test/acme/api)&identity_src=git_remote&identity_style=path" \
"$(ai_memory_marker_qs "$TMP/idrepo")"
printf 'project = "mine"\n' >"$TMP/idrepo/.ai-memory.toml"
assert_eq "identity: a declared project routes by name" \
@@ -392,11 +392,15 @@ if command -v git >/dev/null 2>&1; then
assert_eq "identity: an explicit identity outranks the project" \
"&cwd=$ID_CWD&project=mine&project_src=marker&identity=$(ai_memory_url_encode acme/platform)&identity_src=explicit&profile_contribute=1&profile_consume=1" \
"$(ai_memory_marker_qs "$TMP/idrepo")"
- # #1033: the path style rides along with a remote identity only.
+ # #1033: either explicit style rides along with a remote identity only.
printf 'identity_style = "path"\n' >"$TMP/idrepo/.ai-memory.toml"
assert_eq "identity: the path style rides along with the remote" \
"&cwd=$ID_CWD&identity=$(ai_memory_url_encode git.example.test/acme/api)&identity_src=git_remote&identity_style=path&profile_contribute=1&profile_consume=1" \
"$(ai_memory_marker_qs "$TMP/idrepo")"
+ printf 'identity_style = "host_path"\n' >"$TMP/idrepo/.ai-memory.toml"
+ assert_eq "identity: the host-path opt-out rides along with the remote" \
+ "&cwd=$ID_CWD&identity=$(ai_memory_url_encode git.example.test/acme/api)&identity_src=git_remote&identity_style=host_path&profile_contribute=1&profile_consume=1" \
+ "$(ai_memory_marker_qs "$TMP/idrepo")"
printf 'identity_style = "path"\nidentity = "Acme/Platform"\n' >"$TMP/idrepo/.ai-memory.toml"
assert_eq "identity: a declared identity sends no style" \
"&cwd=$ID_CWD&identity=$(ai_memory_url_encode acme/platform)&identity_src=explicit&profile_contribute=1&profile_consume=1" \