Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(identity): name new remote-backed projects by repository path on opt-in (#1033)
AkitaOnRails47cc74b11de9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 170601a7..fec4d923 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- 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 shared capture privacy checks to the relay and the conversation importer,run before an event is hashed, persisted, previewed or delivered: they refusecredential-shaped native identities, scrub nested credentials while keepingdiff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex c409a7a4..a88811ba 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -328,6 +328,7 @@ pub struct HookScope {#[serde(serialize_with = "serialize_scope_hint")]identity: Option<String>,identity_src: Option<&'static str>,+ identity_style: Option<&'static str>,server_may_remap: bool,}@@ -398,11 +399,13 @@ fn hook_scope_from_marker(let mut project = None;let mut strategy = None;let mut explicit_identity = None;+ let mut style = None;if let Some(marker) = marker {workspace = parse_toml_key(marker, "workspace");project = parse_toml_key(marker, "project");strategy = parse_toml_key(marker, "project_strategy");explicit_identity = parse_toml_key(marker, "identity");+ style = parse_toml_key(marker, "identity_style");}let mut project_src = project.as_ref().map(|_| "marker");let identity = repository_identity(cwd, explicit_identity.as_deref(), project.as_deref());@@ -413,6 +416,14 @@ fn hook_scope_from_marker(project = repo_root_project(cwd);project_src = project.as_ref().map(|_| "repo-root");}+ // 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, identity_src) = match identity {Some(identity) => (Some(identity.identity), Some(identity.source.as_str())),None => (None, None),@@ -425,10 +436,21 @@ fn hook_scope_from_marker(project_strategy: strategy,identity,identity_src,+ identity_style,server_may_remap,}}+/// 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> {+ use ai_memory_core::repository_identity::IdentityStyle;+ raw.and_then(IdentityStyle::from_str_opt)+ .filter(|style| *style == IdentityStyle::Path)+ .map(IdentityStyle::as_str)+}+fn marker_query_suffix_impl(cwd: &str,default_strategy: Option<&str>,@@ -472,6 +494,9 @@ fn marker_query_suffix_impl(source));}+ if let Some(style) = scope.identity_style {+ qs.push_str(&format!("&identity_style={style}"));+ }// Per-project `drop_subagent_captures` opt-in: forward the marker's value as// the `drop_subagent` flag so the server scopes the drop to this project.// The server interprets truthiness (`1`/`true`/…).@@ -1151,6 +1176,66 @@ 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.+ #[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")])+ else {+ return;+ };+ let cwd = repo.path().to_str().unwrap();+ let marker = repo.path().join(".ai-memory.toml");++ std::fs::write(&marker, "identity_style = \"path\"\n").unwrap();+ let qs = marker_query_suffix(cwd, None);+ assert!(+ qs.contains("&identity_src=git_remote&identity_style=path"),+ "{qs}"+ );+ let scope = serde_json::to_value(hook_scope(cwd, None)).unwrap();+ assert_eq!(scope["identity_style"], "path");++ 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",+ ),+ (+ "identity_style = \"path\"\nidentity = \"acme/api\"\n",+ "a declared identity keeps its own name",+ ),+ ] {+ std::fs::write(&marker, body).unwrap();+ let qs = marker_query_suffix(cwd, None);+ assert!(!qs.contains("identity_style"), "{why}: {qs}");+ }+ }++ /// The forwarding decision every client makes, against the shared fixture.+ #[test]+ fn forwarded_identity_style_matches_the_shared_fixture() {+ let cases: serde_json::Value = serde_json::from_str(include_str!(+ "../../../ai-memory-core/fixtures/remote_identity_cases.json"+ ))+ .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");+ assert_eq!(forwarded_identity_style(Some(value)), expected, "{value:?}");+ }+ assert_eq!(forwarded_identity_style(None), None);+ }+/// No repository, no remote, no declaration: nothing to send, and the/// server routes by folder name exactly as before.#[test]diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex c54781d0..36048fc8 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -3875,7 +3875,7 @@ export default AiMemoryOpencode2;/// purpose: `findMarker` stays untouched, well-exercised, nearest-marker/// behavior for every other caller.pub(crate) const TS_FIND_SETTINGS_MARKER: &str = r#"function declaresSettings(text: string): boolean {- for (const key of ["workspace", "project", "project_strategy", "drop_subagent_captures", "identity"]) {+ for (const key of ["workspace", "project", "project_strategy", "drop_subagent_captures", "identity", "identity_style"]) {if (tomlKey(text, key) !== undefined) return true;}if (/^\s*server\s*=/m.test(text)) return true;@@ -3939,7 +3939,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {if (managedRun) url.searchParams.set("managed_run", managedRun);const marker = findSettingsMarker(cwd);if (!marker || !cwd) {- applyIdentityParams(url, cwd, undefined, undefined);+ applyIdentityParams(url, cwd, undefined, undefined, undefined);return;}url.searchParams.set("cwd", cwd);@@ -3947,7 +3947,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {const body = readFileSync(marker, "utf8");const workspace = tomlKey(body, "workspace");const project = tomlKey(body, "project");- applyIdentityParams(url, cwd, tomlKey(body, "identity"), project);+ applyIdentityParams(url, cwd, tomlKey(body, "identity"), project, tomlKey(body, "identity_style"));const projectStrategy = tomlKey(body, "project_strategy");const dropSubagent = tomlKey(body, "drop_subagent_captures");const defaultGlobal = tomlFlag(body, "default_global");@@ -3982,6 +3982,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {let briefing: string | undefined;let briefingBudget: string | undefined;let explicitIdentity: string | undefined;+ let identityStyle: string | undefined;const marker = findSettingsMarker(cwd);if (marker) {try {@@ -3994,11 +3995,12 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {briefing = tomlFlag(body, "inject_on_session_start");briefingBudget = tomlFlag(body, "max_chars");explicitIdentity = tomlKey(body, "identity");+ identityStyle = tomlKey(body, "identity_style");} catch (_e) {}}// Before repo-root can fill `project`: a repo-root name is an inference.- applyIdentityParams(url, cwd, explicitIdentity, project);+ applyIdentityParams(url, cwd, explicitIdentity, project, identityStyle);if (!projectStrategy) projectStrategy = DEFAULT_PROJECT_STRATEGY;if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {const repoProject = repoRootProject(cwd);@@ -4066,11 +4068,16 @@ pub(crate) const TS_IDENTITY: &str = r#"function normalizeRemote(raw: string): sreturn id && id.includes("/") ? id : undefined;}+function identityStyleParam(style: string | undefined): string | undefined {+ return style?.trim() === "path" ? "path" : undefined;+}+function applyIdentityParams(url: URL,cwd: string | undefined,explicit: string | undefined,project: string | undefined,+ style: string | undefined,): void {const declared = explicit?.trim();if (declared) {@@ -4089,6 +4096,8 @@ 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);return;}} catch (_e) {@@ -9527,7 +9536,7 @@ model = "gpt-5"assert!(plugin.contains("function declaresSettings"));assert!(plugin.contains("const marker = findSettingsMarker(cwd);"));assert!(plugin.contains(- "for (const key of [\"workspace\", \"project\", \"project_strategy\", \"drop_subagent_captures\", \"identity\"])"+ "for (const key of [\"workspace\", \"project\", \"project_strategy\", \"drop_subagent_captures\", \"identity\", \"identity_style\"])"));assert!(plugin.contains("for (const key of [\"default_global\", \"inject_on_session_start\", \"max_chars\"])"@@ -12712,6 +12721,41 @@ 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)> {+ let cases: serde_json::Value = serde_json::from_str(CASES).unwrap();+ cases["identity_style"]+ .as_array()+ .unwrap()+ .iter()+ .map(|case| {+ (+ case["value"].as_str().unwrap().to_owned(),+ case["style"].as_str() == Some("path"),+ )+ })+ .collect()+ }++ /// 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() {+ let got = got+ .get(i)+ .copied()+ .unwrap_or("<missing>")+ .trim_end_matches('\r');+ let expected = if *forwards {+ "&identity_style=path"+ } else {+ ""+ };+ assert_eq!(got, expected, "{port} forwarded {value:?} differently");+ }+ }+fn repo_file(relative: &str) -> PathBuf {PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")@@ -12756,6 +12800,17 @@ mod identity_parity_tests {String::from_utf8_lossy(&output.stderr));assert_agrees("hooks/_lib.sh", &output.stdout);++ let output = Command::new("sh")+ .arg("-c")+ .arg(r#". "$1"; shift; for v in "$@"; do printf '%s\n' "$(ai_memory_identity_style_qs "$v")"; done"#)+ .arg("sh")+ .arg(repo_file("hooks/_lib.sh"))+ .args(style_cases().into_iter().map(|(value, _)| value))+ .output()+ .unwrap();+ assert!(output.status.success());+ assert_styles_agree("hooks/_lib.sh", &String::from_utf8_lossy(&output.stdout));}#[test]@@ -12772,28 +12827,35 @@ mod identity_parity_tests {let script = tmp.path().join("parity.ps1");std::fs::write(&script,- "param([string] $Lib, [string] $Cases)\n\+ "param([string] $Lib, [string] $Cases, [string] $Styles)\n\. $Lib\n\foreach ($u in (Get-Content -Raw $Cases | ConvertFrom-Json)) {\n\$id = ConvertTo-AiMemoryRepositoryIdentity -Url $u\n\if ($id) { [Console]::Out.Write(\"$id`n\") } else { [Console]::Out.Write(\"`n\") }\n\}\n\$decisions = @(\n\- (Get-AiMemoryIdentityQuery -Cwd '' -Explicit ' Acme/Platform ' -Project 'proj'),\n\+ (Get-AiMemoryIdentityQuery -Cwd '' -Explicit ' Acme/Platform ' -Project 'proj' -Style 'path'),\n\(Get-AiMemoryIdentityQuery -Cwd '' -Explicit '' -Project 'proj'),\n\(Get-AiMemoryIdentityQuery -Cwd '' -Explicit '' -Project '')\n\)\n\- [Console]::Error.Write($decisions -join '|')\n",+ [Console]::Error.Write($decisions -join '|')\n\+ foreach ($s in (Get-Content -Raw $Styles | ConvertFrom-Json)) {\n\+ [Console]::Out.Write(\"S:$(Get-AiMemoryIdentityStyleQuery -Style $s)`n\")\n\+ }\n",).unwrap();let urls = tmp.path().join("urls.json");let list: Vec<String> = cases().into_iter().map(|(url, _)| url).collect();std::fs::write(&urls, serde_json::to_string(&list).unwrap()).unwrap();+ let styles = tmp.path().join("styles.json");+ let values: Vec<String> = style_cases().into_iter().map(|(value, _)| value).collect();+ std::fs::write(&styles, serde_json::to_string(&values).unwrap()).unwrap();let output = Command::new(pwsh).args(["-NoProfile", "-NonInteractive", "-File"]).arg(&script).arg(repo_file("hooks/lib/ai-memory-hook.ps1")).arg(&urls)+ .arg(&styles).output().unwrap();assert!(@@ -12801,7 +12863,14 @@ mod identity_parity_tests {"{}",String::from_utf8_lossy(&output.stderr));- assert_agrees("hooks/lib/ai-memory-hook.ps1", &output.stdout);+ // Style decisions are tagged `S:` so they can share stdout with the+ // normalised URLs.+ let stdout = String::from_utf8_lossy(&output.stdout);+ let (styles, urls): (Vec<&str>, Vec<&str>) =+ stdout.split('\n').partition(|line| line.starts_with("S:"));+ assert_agrees("hooks/lib/ai-memory-hook.ps1", urls.join("\n").as_bytes());+ let styles: Vec<&str> = styles.iter().map(|line| &line[2..]).collect();+ assert_styles_agree("hooks/lib/ai-memory-hook.ps1", &styles.join("\n"));// Same decisions as the other clients: explicit wins over a declared// project; a declared project alone sends nothing; no cwd sends nothing.assert_eq!(@@ -12822,20 +12891,27 @@ mod identity_parity_tests {let tmp = tempfile::TempDir::new().unwrap();let module = tmp.path().join("parity.ts");let list: Vec<String> = cases().into_iter().map(|(url, _)| url).collect();+ let styles: Vec<String> = style_cases().into_iter().map(|(value, _)| value).collect();let source = format!("import {{ execFileSync }} from \"node:child_process\";\n\void execFileSync;\n\{}\n\const urls: string[] = {};\n\process.stdout.write(urls.map((u) => normalizeRemote(u) ?? \"\").join(\"\\n\") + \"\\n\");\n\+ const styles: string[] = {};\n\+ for (const s of styles) {{\n\+ const forwarded = identityStyleParam(s);\n\+ process.stdout.write(`S:${{forwarded ? `&identity_style=${{forwarded}}` : \"\"}}\\n`);\n\+ }}\n\const decide = (explicit?: string, project?: string): string => {{\n\const url = new URL(\"http://h/hook\");\n\- applyIdentityParams(url, undefined, explicit, project);\n\+ applyIdentityParams(url, undefined, explicit, project, \"path\");\n\return url.search;\n\}};\n\process.stderr.write([decide(\" Acme/Platform \", \"proj\"), decide(undefined, \"proj\"), decide()].join(\"|\"));\n",super::TS_IDENTITY,- serde_json::to_string(&list).unwrap()+ serde_json::to_string(&list).unwrap(),+ serde_json::to_string(&styles).unwrap());std::fs::write(&module, source).unwrap();let output = Command::new("node")@@ -12848,9 +12924,15 @@ mod identity_parity_tests {"{}",String::from_utf8_lossy(&output.stderr));- assert_agrees("TS_IDENTITY", &output.stdout);+ let stdout = String::from_utf8_lossy(&output.stdout);+ let (styles, urls): (Vec<&str>, Vec<&str>) =+ stdout.split('\n').partition(|line| line.starts_with("S:"));+ assert_agrees("TS_IDENTITY", urls.join("\n").as_bytes());+ let styles: Vec<&str> = styles.iter().map(|line| &line[2..]).collect();+ assert_styles_agree("TS_IDENTITY", &styles.join("\n"));// An explicit identity wins over a declared project; a declared- // project alone sends nothing; no cwd sends nothing.+ // project alone sends nothing; no cwd sends nothing. A requested+ // `path` style never rides along with an explicit identity.assert_eq!(String::from_utf8_lossy(&output.stderr),"?identity=acme%2Fplatform&identity_src=explicit||"diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rsindex f02903bf..ee8ea719 100644--- a/crates/ai-memory-cli/src/marker.rs+++ b/crates/ai-memory-cli/src/marker.rs@@ -198,12 +198,13 @@ fn find_marker_matching<T>(/// the file. That is conservative on purpose: it can only turn a marker INTO/// a boundary, never wrongly make one transparent.fn declares_more_than_capture(text: &str) -> bool {- const QUOTED_KEYS: [&str; 5] = [+ const QUOTED_KEYS: [&str; 6] = ["workspace","project","project_strategy","drop_subagent_captures","identity",+ "identity_style",];const FLAG_KEYS: [&str; 3] = ["default_global", "inject_on_session_start", "max_chars"];QUOTED_KEYSdiff --git a/crates/ai-memory-core/fixtures/remote_identity_cases.json b/crates/ai-memory-core/fixtures/remote_identity_cases.jsonindex 51904f99..6cd0b4f0 100644--- a/crates/ai-memory-core/fixtures/remote_identity_cases.json+++ b/crates/ai-memory-core/fixtures/remote_identity_cases.json@@ -43,10 +43,19 @@{ "identity": "ana/personal notes", "name": "ana-personal-notes" }],"styled_key": [- { "identity": "github.com/akitaonrails/ai-memory", "source": "git_remote", "path": "akitaonrails/ai-memory", "host_path": "github.com/akitaonrails/ai-memory" },- { "identity": "gitlab.com/acme/group/api", "source": "git_remote", "path": "acme/group/api", "host_path": "gitlab.com/acme/group/api" },- { "identity": "ssh.dev.azure.com/v3/acme/proj/api", "source": "git_remote", "path": "v3/acme/proj/api", "host_path": "ssh.dev.azure.com/v3/acme/proj/api" },- { "identity": "acme/platform", "source": "explicit", "path": "acme/platform", "host_path": "acme/platform" },- { "identity": "api", "source": "folder_name", "path": "api", "host_path": "api" }+ { "identity": "github.com/akitaonrails/ai-memory", "source": "git_remote", "path": "akitaonrails/ai-memory", "host_path": "github.com/akitaonrails/ai-memory", "path_name": "akitaonrails-ai-memory" },+ { "identity": "gitlab.com/acme/group/api", "source": "git_remote", "path": "acme/group/api", "host_path": "gitlab.com/acme/group/api", "path_name": "acme-group-api" },+ { "identity": "ssh.dev.azure.com/v3/acme/proj/api", "source": "git_remote", "path": "v3/acme/proj/api", "host_path": "ssh.dev.azure.com/v3/acme/proj/api", "path_name": "v3-acme-proj-api" },+ { "identity": "github.com/acme/my api", "source": "git_remote", "path": "acme/my api", "host_path": "github.com/acme/my api", "path_name": "acme-my-api" },+ { "identity": "acme/platform", "source": "explicit", "path": "acme/platform", "host_path": "acme/platform", "path_name": null },+ { "identity": "api", "source": "folder_name", "path": "api", "host_path": "api", "path_name": null }+ ],+ "identity_style": [+ { "value": "path", "style": "path" },+ { "value": "host_path", "style": "host_path" },+ { "value": " path ", "style": "path" },+ { "value": "Path", "style": null },+ { "value": "host-path", "style": null },+ { "value": "", "style": null }]}diff --git a/crates/ai-memory-core/src/repository_identity.rs b/crates/ai-memory-core/src/repository_identity.rsindex 241d2f29..6a85cf28 100644--- a/crates/ai-memory-core/src/repository_identity.rs+++ b/crates/ai-memory-core/src/repository_identity.rs@@ -273,8 +273,29 @@ pub fn split_name_base(identity: &str) -> String {} else {segments.join("-")};- let mut out = String::with_capacity(tail.len());- for c in tail.chars() {+ project_name_from(&tail)+}++/// The project name a `path`-style repository takes (#1033): the git remote's+/// whole repository path without its host, spelled the way+/// [`split_name_base`] spells names (`github.com/acme/group/api` →+/// `acme-group-api`). `None` for any identity that is not a git remote — a+/// declared identity or name keeps the name it already has.+#[must_use]+pub fn path_style_name(identity: &RepositoryIdentity) -> Option<String> {+ if identity.source != IdentitySource::GitRemote {+ return None;+ }+ let key = styled_key(identity, IdentityStyle::Path);+ let joined: Vec<&str> = key.split('/').filter(|s| !s.is_empty()).collect();+ Some(project_name_from(&joined.join("-")))+}++/// Characters a project name cannot carry become `-`, runs collapse, and the+/// ends are trimmed; an empty result is `repository`.+fn project_name_from(raw: &str) -> String {+ let mut out = String::with_capacity(raw.len());+ for c in raw.chars() {let keep = c.is_alphanumeric() || matches!(c, '-' | '_' | '.');let c = if keep { c } else { '-' };if !(c == '-' && out.ends_with('-')) {@@ -291,13 +312,15 @@ pub fn split_name_base(identity: &str) -> String {/// How a remote-derived key spells a repository (#1033).///-/// `HostPath` is the #708 identity exactly as it is stored and routed today,-/// and stays the default: nothing changes until a later step adopts `Path` as-/// a project's name. `Path` drops the host, so worktrees and clones of one-/// repository share a short `owner/repo` key; two forges hosting the same path-/// must still never share a project, which is why adoption has to detect that-/// collision rather than trust the key alone.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+/// 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.+#[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,@@ -809,6 +832,28 @@ mod tests {identity.identity);}+ assert_eq!(+ path_style_name(&identity).as_deref(),+ case["path_name"].as_str(),+ "{} path name",+ identity.identity+ );+ }+ }++ /// 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`.+ #[test]+ fn identity_style_values_match_the_shared_fixture() {+ let cases: serde_json::Value = serde_json::from_str(CASES).unwrap();+ for case in cases["identity_style"].as_array().unwrap() {+ let value = case["value"].as_str().unwrap();+ assert_eq!(+ IdentityStyle::from_str_opt(value).map(IdentityStyle::as_str),+ case["style"].as_str(),+ "{value:?}"+ );}}diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex afe3c9f0..4ad36d1b 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -97,6 +97,10 @@ 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.+ pub identity_style: Option<String>,}/// Coalesced view of an incoming hook event after light parsing of the@@ -129,6 +133,9 @@ pub struct HookEnvelope {/// [`ai_memory_core::repository_identity::accept_wire_identity`]. `None`/// routes by project name, as every event did before identities existed.pub identity: Option<ai_memory_core::repository_identity::RepositoryIdentity>,+ /// How a project this event creates is named; see+ /// [`ai_memory_core::repository_identity::IdentityStyle`].+ pub identity_style: ai_memory_core::repository_identity::IdentityStyle,/// Whether this project opted into `drop_subagent_captures` via its/// `.ai-memory.toml` (forwarded as the `drop_subagent` query flag). The/// ingest router consults this per-event so the drop is scoped to the@@ -539,6 +546,11 @@ impl HookEnvelope {}_ => None,};+ let identity_style = query+ .identity_style+ .as_deref()+ .and_then(ai_memory_core::repository_identity::IdentityStyle::from_str_opt)+ .unwrap_or_default();let drop_subagent_requested = query_flag_truthy(query.drop_subagent.as_deref());let recall_default_global_requested = query_flag_truthy(query.default_global.as_deref());let all_owners_requested = query_flag_truthy(query.all_owners.as_deref());@@ -623,6 +635,7 @@ impl HookEnvelope {project_strategy,project_source,identity,+ identity_style,drop_subagent_requested,recall_default_global_requested,all_owners_requested,diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 8400a110..f168673a 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -1288,6 +1288,7 @@ async fn should_drop_subagent(env.project_override.as_deref(),env.project_strategy,env.identity.as_ref(),+ env.identity_style,viewer,).await@@ -1372,6 +1373,9 @@ pub struct HandoffQuery {/// Rung that produced `identity`; see/// [`crate::payload::HookQuery::identity_src`].pub identity_src: Option<String>,+ /// Naming style for a project this request creates; see+ /// [`crate::payload::HookQuery::identity_style`].+ pub identity_style: Option<String>,}impl HandoffQuery {@@ -1384,6 +1388,14 @@ impl HandoffQuery {self.identity_src.as_deref()?,)}++ /// The requested naming style, the default when absent or unknown.+ fn identity_style(&self) -> ai_memory_core::repository_identity::IdentityStyle {+ self.identity_style+ .as_deref()+ .and_then(ai_memory_core::repository_identity::IdentityStyle::from_str_opt)+ .unwrap_or_default()+ }}/// Synchronous endpoint used by `session-start.sh` to discover any@@ -1463,6 +1475,7 @@ async fn fetch_and_accept_handoff_at(query.project.as_deref(),ProjectStrategy::parse(query.project_strategy.as_deref()),query.repository_identity().as_ref(),+ query.identity_style(),viewer,).await?;@@ -2372,6 +2385,7 @@ fn has_publishable_scope_hint(cwd: Option<&str>, project_override: Option<&str>)/// project_strategy)` so the same `cwd` resolved with and without an/// override (e.g. during a hook-script upgrade window) doesn't poison each/// other's slot.+#[allow(clippy::too_many_arguments)]async fn resolve_project_ids_inner(state: &HookState,cwd: Option<&str>,@@ -2379,6 +2393,7 @@ async fn resolve_project_ids_inner(project_override: Option<&str>,project_strategy: ProjectStrategy,identity: Option<&ai_memory_core::repository_identity::RepositoryIdentity>,+ identity_style: ai_memory_core::repository_identity::IdentityStyle,creator: Option<ai_memory_core::UserId>,) -> anyhow::Result<(WorkspaceId, ProjectId)> {let cwd_raw = cwd.filter(|s| !s.is_empty());@@ -2600,6 +2615,7 @@ async fn resolve_project_ids_inner(.resolve_project_by_identity(ws,identity.clone(),+ identity_style,project_name,repo_path,parent.map(|(parent_id, _)| parent_id),@@ -2662,6 +2678,7 @@ async fn resolve_project_ids(project_override,project_strategy,None,+ Default::default(),None,).await?;@@ -3082,6 +3099,7 @@ async fn process_authorized(env.project_override.as_deref(),env.project_strategy,env.identity.as_ref(),+ env.identity_style,viewer,).await?@@ -3235,6 +3253,7 @@ async fn process_authorized(env.project_override.as_deref(),env.project_strategy,env.identity.as_ref(),+ env.identity_style,viewer,).await?;@@ -4311,6 +4330,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,}}@@ -4837,6 +4857,89 @@ mod tests {.project_id}+ /// A git-remote capture whose marker asked for `identity_style`.+ async fn capture_styled(+ state: &HookState,+ cwd: &std::path::Path,+ identity: &str,+ style: Option<&str>,+ ) -> ProjectId {+ let session = SessionId::new().to_string();+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "user-prompt-submit".into(),+ agent: Some("claude-code".into()),+ identity: Some(identity.to_owned()),+ identity_src: Some("git_remote".into()),+ identity_style: style.map(str::to_owned),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": session,+ "cwd": cwd.to_string_lossy(),+ "prompt": "hello",+ }),+ );+ process_authorized(+ state,+ env,+ None,+ ai_memory_core::AuthLevel::User,+ Vec::new(),+ None,+ )+ .await+ .unwrap();+ state+ .reader+ .observations_for_session(session.parse().unwrap())+ .await+ .unwrap()[0]+ .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.+ #[tokio::test]+ async fn the_path_style_names_a_new_repository_and_never_merges_another_forge() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let main = tmp.path().join("acme").join("main");+ let worktree = tmp.path().join("wt").join("fix-1025");+ let other_forge = tmp.path().join("mirror").join("api");+ let unknown = tmp.path().join("unknown").join("web");+ for dir in [&main, &worktree, &other_forge, &unknown] {+ std::fs::create_dir_all(dir).unwrap();+ }+ let name = |id| {+ let reader = state.reader.clone();+ let ws = state.workspace_id;+ async move { reader.project_name_by_id(ws, id).await.unwrap() }+ };++ let repo = capture_styled(&state, &main, "github.com/acme/api", Some("path")).await;+ assert_eq!(name(repo).await.as_deref(), Some("acme-api"));+ let wt = capture_styled(&state, &worktree, "github.com/acme/api", Some("path")).await;+ assert_eq!(wt, repo, "a worktree in another folder shares the project");++ let mirror =+ capture_styled(&state, &other_forge, "gitlab.com/acme/api", Some("path")).await;+ assert_ne!(+ mirror, repo,+ "another forge's repository is never merged in"+ );+ assert_eq!(name(mirror).await.as_deref(), Some("api"));++ let fallback = capture_styled(&state, &unknown, "github.com/acme/web", Some("Path")).await;+ assert_eq!(+ name(fallback).await.as_deref(),+ Some("web"),+ "an unknown style value keeps today's naming"+ );+ }+/// #708's collision, end to end: two unrelated repositories both checked/// out as `api/` used to land in one project. With the client's identity/// they land in two, and the same repository under a different folder name@@ -11557,6 +11660,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,}),Some(axum::Extension(ai_memory_core::ActorContext {issuer: Some("https://idp.example".into()),@@ -12169,6 +12273,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,};let state = Arc::new(state);let session_start = |viewer: Option<ai_memory_core::UserId>| {@@ -12252,6 +12357,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,};let state = Arc::new(state);@@ -12354,6 +12460,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,};let (status, body) = read_handoff_response(handle_handoff(@@ -12534,6 +12641,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,}),None,None,@@ -13421,6 +13529,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,},None,Vec::new(),@@ -13498,6 +13607,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,},None,Vec::new(),@@ -13567,6 +13677,7 @@ mod tests {session_id: Some(session_id.into()),identity: None,identity_src: None,+ identity_style: None,};let empty_sid = "empty-native-session";let rendered = fetch_and_accept_handoff(&state, query(empty_sid), None, Vec::new(), None)@@ -13709,6 +13820,7 @@ mod tests {session_id: Some("native-2".into()),identity: None,identity_src: None,+ identity_style: None,};let rendered = fetch_and_accept_handoff(&state, query.clone(), None, Vec::new(), None).await@@ -13823,6 +13935,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,};let named = ai_memory_core::ActorContext {@@ -13901,6 +14014,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,};let rendered =@@ -13963,6 +14077,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,};// Non-truthy opt-in: no handoff pending, nothing to inject.@@ -14112,6 +14227,7 @@ mod tests {session_id: Some("kimi-session".into()),identity: None,identity_src: None,+ identity_style: None,};let rendered =@@ -14326,6 +14442,7 @@ mod tests {session_id: None,identity: None,identity_src: None,+ identity_style: None,},None,Vec::new(),diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 200ebd46..afd3b446 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -422,6 +422,16 @@ impl IdentityResolution {/// the identity ([`ai_memory_core::repository_identity::split_name_base`],/// then `-2`, `-3`, …).///+/// Under [`IdentityStyle::Path`](ai_memory_core::repository_identity::IdentityStyle)+/// 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.+////// 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/// split@@ -436,6 +446,7 @@ pub fn resolve_project_by_identity(conn: &mut Connection,workspace_id: &ai_memory_core::WorkspaceId,identity: &ai_memory_core::repository_identity::RepositoryIdentity,+ style: ai_memory_core::repository_identity::IdentityStyle,name: &str,repo_path: Option<&str>,candidate: Option<ai_memory_core::ProjectId>,@@ -445,6 +456,26 @@ pub fn resolve_project_by_identity(let repo_path = repo_path.map(normalize_repo_path_key);let now = Timestamp::now().as_microsecond();let tx = conn.transaction()?;+ let name_is_free = |tx: &rusqlite::Transaction<'_>, name: &str| -> StoreResult<bool> {+ Ok(tx+ .query_row(+ "SELECT 1 FROM projects WHERE workspace_id = ?1 AND name = ?2",+ params![workspace_id.as_bytes(), name],+ |_| Ok(()),+ )+ .optional()?+ .is_none())+ };+ let path_name = match style {+ ai_memory_core::repository_identity::IdentityStyle::Path => {+ ai_memory_core::repository_identity::path_style_name(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),+ _ => None,+ };let matched: Option<Vec<u8>> = tx.query_row(@@ -477,6 +508,7 @@ pub fn resolve_project_by_identity(};match candidate_row {None => {+ let name = path_name.as_deref().unwrap_or(name);let id = insert_project_with_identity(&tx,workspace_id,@@ -516,21 +548,21 @@ pub fn resolve_project_by_identity(}}Some(_) => {- let base = ai_memory_core::repository_identity::split_name_base(&identity.identity);- let mut split_name = base.clone();- let mut n = 2_u32;- while tx- .query_row(- "SELECT 1 FROM projects WHERE workspace_id = ?1 AND name = ?2",- params![workspace_id.as_bytes(), split_name],- |_| Ok(()),- )- .optional()?- .is_some()- {- split_name = format!("{base}-{n}");- n += 1;- }+ let split_name = match path_name {+ Some(path_name) => path_name,+ None => {+ let base = ai_memory_core::repository_identity::split_name_base(+ &identity.identity,+ );+ let mut split_name = base.clone();+ let mut n = 2_u32;+ while !name_is_free(&tx, &split_name)? {+ split_name = format!("{base}-{n}");+ n += 1;+ }+ split_name+ }+ };let id = insert_project_with_identity(&tx,workspace_id,diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 4462d925..4785eaa8 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -81,6 +81,7 @@ pub(crate) enum WriteCmd {ResolveProjectByIdentity {workspace_id: WorkspaceId,identity: ai_memory_core::repository_identity::RepositoryIdentity,+ style: ai_memory_core::repository_identity::IdentityStyle,name: String,repo_path: Option<String>,candidate: Option<ProjectId>,@@ -937,10 +938,12 @@ impl WriterHandle {/// # Errors/// Returns [`StoreError::WriterClosed`] if the actor has shut down, or/// propagates the SQL error.+ #[allow(clippy::too_many_arguments)]pub async fn resolve_project_by_identity(&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>,@@ -950,6 +953,7 @@ impl WriterHandle {self.send(WriteCmd::ResolveProjectByIdentity {workspace_id,identity,+ style,name: name.into(),repo_path,candidate,@@ -3257,6 +3261,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {WriteCmd::ResolveProjectByIdentity {workspace_id,identity,+ style,name,repo_path,candidate,@@ -3267,6 +3272,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {&mut conn,&workspace_id,&identity,+ style,&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.rsindex 52b95b69..e5fee4e2 100644--- a/crates/ai-memory-store/tests/suite/identity_resolution.rs+++ b/crates/ai-memory-store/tests/suite/identity_resolution.rs@@ -8,7 +8,7 @@//! existing project is claimed in place rather than split away, and somebody//! who may not write to it cannot take its identity.-use ai_memory_core::repository_identity::{IdentitySource, RepositoryIdentity};+use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};use ai_memory_core::{NewUser, ProjectId, UserId, WorkspaceId};use ai_memory_store::{AccessMode, GrantLevel, IdentityResolution, ProjectAccess, ProjectPrincipal, Store,@@ -61,12 +61,24 @@ async fn resolve(identity: &RepositoryIdentity,name: &str,creator: Option<UserId>,+) -> (ProjectId, IdentityResolution) {+ resolve_styled(store, ws, identity, IdentityStyle::HostPath, name, creator).await+}++async fn resolve_styled(+ store: &Store,+ ws: WorkspaceId,+ identity: &RepositoryIdentity,+ style: IdentityStyle,+ name: &str,+ creator: Option<UserId>,) -> (ProjectId, IdentityResolution) {store.writer.resolve_project_by_identity(ws,identity.clone(),+ style,name,Some("/work/api".to_owned()),None,@@ -296,6 +308,7 @@ async fn the_prefix_parent_is_the_candidate_when_given() {.resolve_project_by_identity(ws,remote("github.com/acme/monorepo"),+ IdentityStyle::HostPath,"src",None,Some(parent),@@ -315,3 +328,222 @@ async fn the_prefix_parent_is_the_candidate_when_given() {"no fragment project for the subdirectory");}++fn explicit(identity: &str) -> RepositoryIdentity {+ RepositoryIdentity {+ identity: identity.to_owned(),+ source: IdentitySource::Explicit,+ }+}++/// #1033: under the `path` style a new repository is named from its path+/// without the host, so every worktree and clone — whatever its folder is+/// called — lands in that one project.+#[tokio::test]+async fn the_path_style_names_a_new_project_from_the_host_less_path() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = workspace(&store).await;+ let repo = remote("gitlab.com/acme/group/api");++ let (id, how) = resolve_styled(&store, ws, &repo, IdentityStyle::Path, "main", None).await;+ assert_eq!(how, IdentityResolution::Created);+ assert_eq!(row(&store, id).0, "acme-group-api");+ assert_eq!(row(&store, id).1, "gitlab.com/acme/group/api");++ for folder in ["fix-1025", "main"] {+ let (again, how) =+ resolve_styled(&store, ws, &repo, IdentityStyle::Path, folder, None).await;+ assert_eq!((again, how), (id, IdentityResolution::Matched), "{folder}");+ }+ assert!(+ store+ .reader+ .find_project(ws, "main".into())+ .await+ .unwrap()+ .is_none(),+ "no folder-named project was created alongside it"+ );+}++/// The collision the path style must never merge: the same path on another+/// forge is a different repository. Whichever arrives second keeps the name it+/// would have had without the style — the folder name, or the split name when+/// that is taken too — and the first project is left untouched.+#[tokio::test]+async fn the_same_path_on_another_forge_falls_back_instead_of_merging() {+ 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 (first, _) = resolve_styled(&store, ws, &github, IdentityStyle::Path, "api", None).await;+ assert_eq!(row(&store, first).0, "acme-api");++ let (gitlab, how) = resolve_styled(+ &store,+ ws,+ &remote("gitlab.com/acme/api"),+ IdentityStyle::Path,+ "api",+ None,+ )+ .await;+ assert_eq!(how, IdentityResolution::Created);+ assert_ne!(gitlab, first, "another forge's repository is never adopted");+ assert_eq!(row(&store, gitlab).0, "api");+ assert_eq!(row(&store, gitlab).1, "gitlab.com/acme/api");++ // Its folder is called `acme-api` too: that name belongs to the GitHub+ // project, so it splits, and the split name is taken as well.+ let (bitbucket, how) = resolve_styled(+ &store,+ ws,+ &remote("bitbucket.org/acme/api"),+ IdentityStyle::Path,+ "acme-api",+ None,+ )+ .await;+ assert_eq!(how, IdentityResolution::Split);+ assert_eq!(row(&store, bitbucket).0, "acme-api-2");++ assert_eq!(+ row(&store, first),+ (+ "acme-api".into(),+ "github.com/acme/api".into(),+ "git_remote".into(),+ Some("/work/api".into())+ ),+ "the first project kept its name, identity and path"+ );+}++/// A project already holding the path name without any identity is some other+/// checkout's folder project. Taking it would merge two repositories, so the+/// newcomer falls back and the holder stays unclaimed.+#[tokio::test]+async fn an_unclaimed_project_holding_the_path_name_is_not_taken() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = workspace(&store).await;+ let holder = store+ .writer+ .get_or_create_project(ws, "acme-api", None)+ .await+ .unwrap();++ let (id, how) = resolve_styled(+ &store,+ ws,+ &remote("github.com/acme/api"),+ IdentityStyle::Path,+ "api",+ None,+ )+ .await;+ assert_eq!(how, IdentityResolution::Created);+ assert_ne!(id, holder);+ assert_eq!(row(&store, id).0, "api");+ assert_eq!(row(&store, holder).1, "", "the holder was not claimed");+}++/// Opting an install in renames nothing: a repository that already has a+/// project — claimed by identity, or still unclaimed under its folder name —+/// resolves exactly as it would without the style.+#[tokio::test]+async fn opting_in_leaves_existing_projects_where_they_are() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = workspace(&store).await;++ let claimed_repo = remote("github.com/acme/api");+ let (claimed, _) = resolve(&store, ws, &claimed_repo, "api", None).await;+ let (again, how) =+ resolve_styled(&store, ws, &claimed_repo, IdentityStyle::Path, "api", None).await;+ assert_eq!((again, how), (claimed, IdentityResolution::Matched));+ assert_eq!(row(&store, claimed).0, "api", "not renamed to acme-api");++ let legacy = store+ .writer+ .get_or_create_project(ws, "web", None)+ .await+ .unwrap();+ let (id, how) = resolve_styled(+ &store,+ ws,+ &remote("github.com/acme/web"),+ IdentityStyle::Path,+ "web",+ None,+ )+ .await;+ assert_eq!((id, how), (legacy, IdentityResolution::Claimed));+ assert_eq!(row(&store, legacy).0, "web");+ assert!(+ store+ .reader+ .find_project(ws, "acme-web".into())+ .await+ .unwrap()+ .is_none(),+ "no path-named twin split off the legacy project"+ );+}++/// The style only renames what has a host to drop: a declared identity keeps+/// the name the client sent.+#[tokio::test]+async fn the_path_style_leaves_a_declared_identity_named_as_sent() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = workspace(&store).await;+ let (id, how) = resolve_styled(+ &store,+ ws,+ &explicit("acme/platform"),+ IdentityStyle::Path,+ "platform",+ None,+ )+ .await;+ assert_eq!(how, IdentityResolution::Created);+ assert_eq!(row(&store, id).0, "platform");+}++/// Naming a project differently changes nothing about reads: a lookup is+/// still no-create, and the folder name a static client might guess resolves+/// to nothing rather than to a fresh project.+#[tokio::test]+async fn reads_of_a_path_named_project_stay_no_create() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = workspace(&store).await;+ let (id, _) = resolve_styled(+ &store,+ ws,+ &remote("github.com/acme/api"),+ IdentityStyle::Path,+ "api",+ None,+ )+ .await;++ assert_eq!(+ store+ .reader+ .find_project(ws, "acme-api".into())+ .await+ .unwrap(),+ Some(id)+ );+ for _ in 0..2 {+ assert_eq!(+ store.reader.find_project(ws, "api".into()).await.unwrap(),+ None,+ "a lookup of the folder name finds nothing and creates nothing"+ );+ }+}diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex 204f5bd0..54db95fe 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -87,6 +87,83 @@ 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 —+/// 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() {+ use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};++ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("acme".to_string())+ .await+ .unwrap();+ let repo = RepositoryIdentity {+ identity: "github.com/acme/api".into(),+ source: IdentitySource::GitRemote,+ };+ let clone = |folder: &'static str, path: &'static str| {+ let writer = store.writer.clone();+ let repo = repo.clone();+ async move {+ writer+ .resolve_project_by_identity(+ ws,+ repo,+ IdentityStyle::Path,+ folder,+ Some(path.to_owned()),+ None,+ None,+ )+ .await+ .unwrap()+ .0+ }+ };+ let (alice, bob) = tokio::join!(+ clone("api", "/home/alice/src/api"),+ clone("api-main", "/srv/bob/worktrees/api-main"),+ );+ assert_eq!(alice, bob, "two clones of one repository share one project");+ assert_eq!(+ store+ .reader+ .find_project(ws, "acme-api".into())+ .await+ .unwrap(),+ Some(alice)+ );+ for folder in ["api", "api-main"] {+ assert!(+ store+ .reader+ .find_project(ws, folder.into())+ .await+ .unwrap()+ .is_none(),+ "no per-folder fragment for {folder}"+ );+ }++ store+ .writer+ .upsert_page(page(ws, alice, "notes/shared.md", "Shared", "alice's note"))+ .await+ .unwrap();+ let seen = store+ .reader+ .page_body_by_ids(ws, bob, "notes/shared.md")+ .await+ .unwrap()+ .expect("bob reads alice's page in the shared project");+ assert!(seen.body.contains("alice's note"));+}+/// The collaboration guarantee, and the reason a team can use one server:/// what Alice writes, Carol reads.///diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex c6e9af18..4ea563e5 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -345,7 +345,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. 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`. |+| `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; it never renames or re-keys an existing project. 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`. || `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.mdindex 0ba7ee59..b61006e3 100644--- a/docs/auto-scope.md+++ b/docs/auto-scope.md@@ -116,6 +116,10 @@ pointers. The durable `SessionId` stored for hook observations remains global:if another owner reuses an already-owned id, ai-memory drops that hook before itcan 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.+Owner and agent are what identify a session; scope is not. The same operator'ssession legitimately produces events in another project when its cwd moves, soa differing `(workspace, project)` is recorded rather than rejected — seediff --git a/docs/design-per-project-authz.md b/docs/design-per-project-authz.mdindex 4a5686fc..11c315d6 100644--- a/docs/design-per-project-authz.md+++ b/docs/design-per-project-authz.md@@ -230,19 +230,26 @@ that name, so a static client that passes a worktree folder misses the mergedproject. #1033 makes a remote-derived key the default name, landing in steps on`release/2.6`:-1. **Normaliser and style (landed first).** `repository_identity::styled_key`- turns an identity into a key under `IdentityStyle`: `path` drops a git+1. **Normaliser and opt-in naming (landed first).** `repository_identity::+ styled_key` spells an identity under `IdentityStyle`: `path` drops a gitremote's host (`github.com/acme/api` → `acme/api`); `host_path` is the #708- identity unchanged and stays the default. Declared and folder keys never- change. Checked against the `styled_key` section of- `fixtures/remote_identity_cases.json`. Nothing routes or names by it yet.+ identity unchanged and stays the default. A marker's+ `identity_style = "path"` 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+ full identity. **Cross-forge collisions are detected, never merged:** the+ path name is used only while no project in the workspace holds it, checked+ in the same transaction as the identity match, so `gitlab.com/acme/api`+ after `github.com/acme/api` falls back to the name it would otherwise get.+ Existing projects — matched, claimed or unclaimed — are never renamed.+ Checked against the `styled_key` and `identity_style` sections of+ `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, with marker `project`/`identity` still outranking remotes.- **Cross-forge collisions are detected, never merged:** when a newcomer's- `path` key is already held by a project under a different host- (`github.com/acme/api` vs `gitlab.com/acme/api`), the newcomer takes its- `host_path` key instead and `doctor` reports it. Needs an adversarial- isolation test and a security-boundaries row.+ projects without opting in, with marker `project`/`identity` still+ outranking remotes and the same collision fallback.3. **Dual-key resolve and in-place rename** (UUID foreign keys kept, no aliastable) until v3, so existing basename projects are renamed toward theircanonical key rather than split. Two operators on different clones of onediff --git a/docs/marker-file.md b/docs/marker-file.mdindex c27c6c29..c01d84ba 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -59,7 +59,8 @@ hook capture and handoff lookup send the same `cwd`, `workspace`, `project`,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.+[Repository identity](#repository-identity)), with or without a marker, and+`identity_style=path` alongside a remote identity when the marker opts in.## Schema@@ -87,6 +88,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". Never renames an existing project. See+# "Naming new projects by repository path" below.+identity_style = "path"+# Optional. Opt this project into drop_subagent_captures: set it to "true"# and the server accepts but does NOT store this project's subagent-session# captures. A multi-agent harness fans one goal out to many subagent@@ -449,7 +456,7 @@ printf '%s\n' '{"session_id":"demo","cwd":"/example/workspace","tool_name":"EditThe same inspection also reports sanitized `scope` hints (`workspace`, `project`,`project_src`, `project_strategy`, `identity`, `identity_src`,-`server_may_remap`) and `scope_resolution`. These are local hints, not a+`identity_style`, `server_may_remap`) and `scope_resolution`. These are local hints, not aserver lookup: inspection creates no project and may report server-derivedcoordinates that the server later remaps. Partial marker scope fails closed.`event_admits_capture` reports lifecycle eligibility. External producers use@@ -588,6 +595,36 @@ URL never leave the machine. Other remote names (`fork`, `mine`) areignored on purpose: they differ per person, and would give one repository adifferent identity for each of them.+#### Naming new 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):++```toml+identity_style = "path" # default: "host_path"+```++With `path`, a **new** 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+worktree and clone agrees on the name. Only the name changes: captures still+route by the full identity (`github.com/acme/api`), and the style rides along+only with a remote identity — a declared `project` or `identity` keeps its+own name.++- **Existing projects are never renamed or re-keyed.** A repository that+ already has a project, claimed or not, resolves exactly as before.+- **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.+- Put it in `~/.ai-memory.toml` to apply it to every checkout under `$HOME`+ that has no nearer marker, like any other marker key.+- Static MCP clients still resolve by name, so pass the path name (`acme-api`)+ as `project`.+### Single workspace, no per-repo overrides```diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex c2270b69..ded90299 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -71,7 +71,7 @@ boundary not yet built.| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users || 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them || 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 |-| 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`; `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`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |+| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; 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, and no existing project is renamed or claimed differently; `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 || 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) || 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG || 14e | `memory_write_page` session evidence cites only a session of the target project (#708) | `ai-memory-mcp/src/server.rs` `memory_write_page` — a `session_id` is accepted only when `require_session_in_scope` resolves the session (where its observations landed, else its session row, as `Consolidator::session_target` does) to the same `(workspace_id, project_id)` the write grant was checked against; unknown and foreign ids get one refusal, so the error is no existence oracle; `scope: "global"` with a `session_id` is refused; `refuse_pinned_page_overwrite` keeps a write that cites a session off a pinned page; only a write to `sessions/<id>.md` reconciles the session's queued SessionEnd job | `server.rs` `write_page_refuses_a_session_from_another_project` (a foreign and an unknown session refused, no evidence row written, the foreign job still queued; control: the project's own session accepted), `session_evidence_write_leaves_a_pinned_page_alone` (control: the same write without `session_id` edits the page), `session_evidence_on_another_path_leaves_the_job_queued`, `write_page_rejects_a_malformed_or_global_session_id` — each of the scope check, the pinned check and the session-page-only reconcile proven to fail its test when removed | STRONG |diff --git a/hooks/_lib.sh b/hooks/_lib.shindex 7d399382..c5cc501f 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -90,7 +90,7 @@ ai_memory_parse_toml_flag() {ai_memory_marker_declares_settings() {file="$1"[ -f "$file" ] || return 1- for key in workspace project project_strategy drop_subagent_captures identity; do+ for key in workspace project project_strategy drop_subagent_captures identity identity_style; do[ -n "$(ai_memory_parse_toml_key "$file" "$key")" ] && return 0doneai_memory_marker_declares_server "$file" && return 0@@ -409,13 +409,24 @@ 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.+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'+ return 0+}+# Print `&identity=<v>&identity_src=<rung>` for the checkout at "$1", or-# nothing. "$2" is the marker's `identity`, "$3" its declared `project`.+# nothing. "$2" is the marker's `identity`, "$3" its declared `project`, "$4"+# its `identity_style`, forwarded only with a remote identity.# Mirrors `repository_identity` in hook_capture.rs: an explicit identity is# sent; a declared project outranks the remote and routes by name, so git is# not consulted; otherwise the `upstream` remote, else `origin`.ai_memory_identity_qs() {- _ai_id_cwd="$1"; _ai_id_explicit="$2"; _ai_id_project="$3"+ _ai_id_cwd="$1"; _ai_id_explicit="$2"; _ai_id_project="$3"; _ai_id_style="$4"_ai_id_explicit=$(printf '%s' "$_ai_id_explicit" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')if [ -n "$_ai_id_explicit" ]; then_ai_id_value=$(printf '%s' "$_ai_id_explicit" | tr '[:upper:]' '[:lower:]')@@ -430,6 +441,7 @@ ai_memory_identity_qs() {_ai_id_value=$(ai_memory_normalize_remote "$_ai_id_url")if [ -n "$_ai_id_value" ]; thenprintf '&identity=%s&identity_src=git_remote' "$(ai_memory_url_encode "$_ai_id_value")"+ ai_memory_identity_style_qs "$_ai_id_style"return 0fidone@@ -459,6 +471,7 @@ ai_memory_marker_qs() {# latter may yield to session-sticky attribution (#394).ps=""idn=""+ isty=""# The nearest marker that declares more than `[capture]` (#668): a nested# capture-only marker (e.g. one that only sets ignore_paths) must not# shadow an outer marker's workspace/project/etc.@@ -469,11 +482,12 @@ ai_memory_marker_qs() {st=$(ai_memory_parse_toml_key "$marker" project_strategy)ds=$(ai_memory_parse_toml_key "$marker" drop_subagent_captures)idn=$(ai_memory_parse_toml_key "$marker" identity)+ isty=$(ai_memory_parse_toml_key "$marker" identity_style)[ -n "$pr" ] && ps="marker"fi# Before repo-root can fill `pr`: a repo-root name is an inference, while# the identity chain's declared-project rung means a name in the marker.- iq=$(ai_memory_identity_qs "$cwd" "$idn" "$pr")+ iq=$(ai_memory_identity_qs "$cwd" "$idn" "$pr" "$isty")# 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.diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index caf51993..fc045984 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -275,12 +275,24 @@ 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.+function Get-AiMemoryIdentityStyleQuery {+ param([string] $Style)+ if ($Style -and $Style.Trim() -ceq "path") { return "&identity_style=path" }+ return ""+}+# `&identity=<v>&identity_src=<rung>` for the checkout at $Cwd, or "".# Mirrors `repository_identity` in hook_capture.rs: an explicit marker# `identity` is sent; a declared `project` outranks the remote and routes by# name, so git is not consulted; otherwise the `upstream` remote, else `origin`.+# $Style (the marker's `identity_style`) is forwarded only with a remote+# identity.function Get-AiMemoryIdentityQuery {- param([string] $Cwd, [string] $Explicit, [string] $Project)+ param([string] $Cwd, [string] $Explicit, [string] $Project, [string] $Style)if ($Explicit -and $Explicit.Trim()) {$value = $Explicit.Trim().ToLowerInvariant()return "&identity=$([uri]::EscapeDataString($value))&identity_src=explicit"@@ -293,7 +305,7 @@ function Get-AiMemoryIdentityQuery {if (-not $url) { continue }$value = ConvertTo-AiMemoryRepositoryIdentity -Url ([string]$url)if ($value) {- return "&identity=$([uri]::EscapeDataString($value))&identity_src=git_remote"+ return "&identity=$([uri]::EscapeDataString($value))&identity_src=git_remote" + (Get-AiMemoryIdentityStyleQuery -Style $Style)}}return ""@@ -312,6 +324,7 @@ function Get-AiMemoryMarkerQuery {# latter may yield to session-sticky attribution (#394).$projSrc = $null$explicitIdentity = $null+ $identityStyle = $null$marker = Get-AiMemoryMarkerToml -Cwd $Cwdif ($marker) {$ws = Get-AiMemoryTomlKey -File $marker -Key "workspace"@@ -319,11 +332,12 @@ function Get-AiMemoryMarkerQuery {$strategy = Get-AiMemoryTomlKey -File $marker -Key "project_strategy"$dropSubagent = Get-AiMemoryTomlKey -File $marker -Key "drop_subagent_captures"$explicitIdentity = Get-AiMemoryTomlKey -File $marker -Key "identity"+ $identityStyle = Get-AiMemoryTomlKey -File $marker -Key "identity_style"if ($proj) { $projSrc = "marker" }}# Before repo-root can fill $proj: a repo-root name is an inference, while# the identity chain's declared-project rung means a name in the marker.- $identityQuery = Get-AiMemoryIdentityQuery -Cwd $Cwd -Explicit $explicitIdentity -Project $proj+ $identityQuery = Get-AiMemoryIdentityQuery -Cwd $Cwd -Explicit $explicitIdentity -Project $proj -Style $identityStyle# 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.diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex d8ed9702..6b0fae4d 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -294,6 +294,15 @@ if command -v git >/dev/null 2>&1; thenassert_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" \"$(ai_memory_marker_qs "$TMP/idrepo")"+ # #1033: the path 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" \+ "$(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" \+ "$(ai_memory_marker_qs "$TMP/idrepo")"rm -rf "$TMP/idrepo"fi