Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(identity): support safe project marker aliases (#1033)
AkitaOnRails767c35f08903
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e15134c1..95bf5692 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 bounded local `.ai-memory.toml` `aliases = ["former-name"]` routing for+ existing project-coordinate compatibility. Native, POSIX shell, PowerShell,+ and generated TypeScript hook clients forward the same validated aliases for+ capture and SessionStart handoff lookup; resolution remains workspace-local,+ requires the checkout's matching hostful git-remote identity, preserves the+ existing UUID, and permits only write-authorized canonical-name promotion.+ Aliases are not persisted, and the default naming style is unchanged. (#1033)- Added read-only project-coordinate diagnostics to `ai-memory doctor` and theroot-gated `GET /admin/project-coordinate` endpoint. The report classifiesexact, canonical-compatibility, legacy-compatibility, missing, and ambiguousdiff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex ab9af61c..69f6b460 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -329,6 +329,7 @@ pub struct HookScope {identity: Option<String>,identity_src: Option<&'static str>,identity_style: Option<&'static str>,+ aliases: Option<String>,server_may_remap: bool,}@@ -478,15 +479,36 @@ fn hook_scope_from_marker(let mut strategy = None;let mut explicit_identity = None;let mut style = None;+ let mut aliases = 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");+ aliases = match crate::marker::parse_toml_aliases(marker) {+ Ok(Some(aliases)) if !aliases.is_empty() => serde_json::to_string(&aliases).ok(),+ Ok(_) => None,+ Err(_) => Some("invalid".to_owned()),+ };}+ let canonical_project = project.clone();let mut project_src = project.as_ref().map(|_| "marker");- let identity = repository_identity(cwd, explicit_identity.as_deref(), project.as_deref());+ let identity = if aliases.is_none() {+ repository_identity(cwd, explicit_identity.as_deref(), project.as_deref())+ } else {+ repository_identity(cwd, None, None).filter(|identity| {+ identity.source == ai_memory_core::repository_identity::IdentitySource::GitRemote+ })+ };+ if aliases.is_some()+ && (canonical_project.is_none()+ || identity.as_ref().is_none_or(|identity| {+ identity.source != ai_memory_core::repository_identity::IdentitySource::GitRemote+ }))+ {+ aliases = Some("invalid".to_owned());+ }if strategy.is_none() {strategy = default_strategy.map(str::to_owned);}@@ -515,6 +537,7 @@ fn hook_scope_from_marker(identity,identity_src,identity_style,+ aliases,server_may_remap,}}@@ -593,6 +616,9 @@ fn marker_query_suffix_impl(if let Some(style) = scope.identity_style {qs.push_str(&format!("&identity_style={style}"));}+ if let Some(aliases) = scope.aliases {+ qs.push_str(&format!("&aliases={}", url_encode(&aliases)));+ }// 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`/…).@@ -1281,6 +1307,39 @@ mod tests {);}+ #[test]+ fn marker_aliases_keep_project_canonical_and_forward_remote_identity() {+ let Some(repo) = repo_with_remotes(&[("origin", "[email protected]:acme/api.git")])+ else {+ return;+ };+ let cwd = repo.path().to_str().unwrap();+ std::fs::write(+ repo.path().join(".ai-memory.toml"),+ "project = \"acme-api\"\naliases = [\" former-name \", \"legacy_name\", \"former-name\"]\n",+ )+ .unwrap();+ let qs = marker_query_suffix(cwd, None);+ let url = reqwest::Url::parse(&format!("http://localhost/handoff?agent=test{qs}")).unwrap();+ let params = url+ .query_pairs()+ .into_owned()+ .collect::<std::collections::HashMap<_, _>>();+ assert_eq!(params.get("project").map(String::as_str), Some("acme-api"));+ assert_eq!(+ params.get("identity").map(String::as_str),+ Some("git.example.test/acme/api")+ );+ assert_eq!(+ params.get("identity_src").map(String::as_str),+ Some("git_remote")+ );+ assert_eq!(+ params.get("aliases").map(String::as_str),+ Some("[\"former-name\",\"legacy_name\"]")+ );+ }+/// #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.diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex eb54fbf1..85ab1b6c 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -3858,6 +3858,7 @@ pub(crate) const TS_FIND_SETTINGS_MARKER: &str = r#"function declaresSettings(tefor (const key of ["workspace", "project", "project_strategy", "drop_subagent_captures", "identity", "identity_style"]) {if (tomlKey(text, key) !== undefined) return true;}+ if (/^\s*aliases\s*=/m.test(text)) return true;if (/^\s*server\s*=/m.test(text)) return true;for (const key of ["default_global", "inject_on_session_start", "max_chars", "contribute", "consume"]) {if (tomlFlag(text, key) !== undefined) return true;@@ -3919,7 +3920,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, undefined);+ applyIdentityParams(url, cwd, undefined, undefined, undefined, undefined);return;}url.searchParams.set("cwd", cwd);@@ -3927,7 +3928,9 @@ 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, tomlKey(body, "identity_style"));+ const aliases = markerAliases(body);+ const remoteIdentity = applyIdentityParams(url, cwd, tomlKey(body, "identity"), project, tomlKey(body, "identity_style"), aliases);+ if (aliases) url.searchParams.set("aliases", project && remoteIdentity ? aliases : "invalid");const projectStrategy = tomlKey(body, "project_strategy");const dropSubagent = tomlKey(body, "drop_subagent_captures");const defaultGlobal = tomlFlag(body, "default_global");@@ -3937,6 +3940,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {const profileConsume = profileFlag(tomlFlag(body, "consume"));if (workspace) url.searchParams.set("workspace", workspace);if (project) url.searchParams.set("project", project);+ if (project) url.searchParams.set("project_src", "marker");if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);@@ -3969,6 +3973,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {let profileConsume: string | undefined;let explicitIdentity: string | undefined;let identityStyle: string | undefined;+ let aliases: string | undefined;const marker = findSettingsMarker(cwd);if (marker) {try {@@ -3984,11 +3989,13 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {profileConsume = profileFlag(tomlFlag(body, "consume"));explicitIdentity = tomlKey(body, "identity");identityStyle = tomlKey(body, "identity_style");+ aliases = markerAliases(body);} catch (_e) {}}// Before repo-root can fill `project`: a repo-root name is an inference.- applyIdentityParams(url, cwd, explicitIdentity, project, identityStyle);+ const remoteIdentity = applyIdentityParams(url, cwd, explicitIdentity, project, identityStyle, aliases);+ if (aliases) url.searchParams.set("aliases", project && remoteIdentity ? aliases : "invalid");if (!projectStrategy) projectStrategy = DEFAULT_PROJECT_STRATEGY;if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {const repoProject = repoRootProject(cwd);@@ -3996,6 +4003,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {}if (workspace) url.searchParams.set("workspace", workspace);if (project) url.searchParams.set("project", project);+ if (project) url.searchParams.set("project_src", "marker");if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);@@ -4018,7 +4026,39 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {/// `project` outranks the remote and routes by name, so git is not consulted;/// otherwise the `upstream` remote, else `origin`. Normalising here keeps/// credentials embedded in a remote URL on the host.-pub(crate) const TS_IDENTITY: &str = r#"function normalizeRemote(raw: string): string | undefined {+pub(crate) const TS_IDENTITY: &str = r#"function markerAliases(text: string): string | undefined {+ let inTable = false;+ const declarations: string[] = [];+ for (const line of text.split(/\r?\n/)) {+ const trimmed = line.trim();+ if (trimmed.startsWith("[")) inTable = true;+ if (/^aliases\s*=/.test(trimmed)) {+ if (inTable) return "invalid";+ declarations.push(trimmed);+ }+ }+ if (declarations.length === 0) return undefined;+ if (declarations.length !== 1) return "invalid";+ const match = /^aliases\s*=\s*\[([^\]]*)\]\s*$/.exec(declarations[0]);+ if (!match) return "invalid";+ const aliases: string[] = [];+ if (!match[1].trim()) return undefined;+ const parts = match[1].split(",");+ if (parts.length > 16) return "invalid";+ for (const raw of parts) {+ if (raw.includes("\\")) return "invalid";+ const item = /^\s*"([^"]*)"\s*$/.exec(raw);+ if (!item) return "invalid";+ const alias = item[1].trim();+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(alias) || Buffer.byteLength(alias, "utf8") > 128) return "invalid";+ if (!aliases.includes(alias)) {+ aliases.push(alias);+ }+ }+ return JSON.stringify(aliases);+}++function normalizeRemote(raw: string): string | undefined {const trimmed = raw.trim();if (!trimmed) return undefined;let scheme: string | undefined;@@ -4068,14 +4108,15 @@ function applyIdentityParams(explicit: string | undefined,project: string | undefined,style: string | undefined,-): void {+ aliases: string | undefined,+): boolean {const declared = explicit?.trim();- if (declared) {+ if (!aliases && declared) {url.searchParams.set("identity", declared.toLowerCase());url.searchParams.set("identity_src", "explicit");- return;+ return false;}- if (project?.trim() || !cwd) return;+ if ((project?.trim() && !aliases) || !cwd) return false;for (const name of ["upstream", "origin"]) {try {const remote = execFileSync("git", ["-C", cwd, "config", "--get", `remote.${name}.url`], {@@ -4088,11 +4129,12 @@ function applyIdentityParams(url.searchParams.set("identity_src", "git_remote");const forwarded = identityStyleParam(style);if (forwarded) url.searchParams.set("identity_style", forwarded);- return;+ return true;}} catch (_e) {}}+ return false;}"#;/// `tomlFlag` mirrors the native hook's `parse_toml_flag`: unlike `tomlKey`@@ -9537,6 +9579,7 @@ model = "gpt-5"assert!(plugin.contains("for (const key of [\"workspace\", \"project\", \"project_strategy\", \"drop_subagent_captures\", \"identity\", \"identity_style\"])"));+ assert!(plugin.contains("if (/^\\s*aliases\\s*=/m.test(text)) return true;"));assert!(plugin.contains("for (const key of [\"default_global\", \"inject_on_session_start\", \"max_chars\", \"contribute\", \"consume\"])"));@@ -12737,6 +12780,40 @@ mod identity_parity_tests {.collect()}+ fn alias_cases() -> Vec<(String, Option<String>)> {+ let cases: serde_json::Value = serde_json::from_str(CASES).unwrap();+ cases["marker_aliases"]+ .as_array()+ .unwrap()+ .iter()+ .map(|case| {+ (+ case["toml"].as_str().unwrap().to_owned(),+ match case["status"].as_str().unwrap() {+ "valid" => case["aliases"].as_array().and_then(|aliases| {+ (!aliases.is_empty()).then(|| serde_json::to_string(aliases).unwrap())+ }),+ "absent" => None,+ "invalid" => Some("invalid".to_owned()),+ status => panic!("unknown fixture status {status}"),+ },+ )+ })+ .collect()+ }++ fn assert_aliases_agree(port: &str, lines: &str) {+ let got: Vec<&str> = lines.split('\n').collect();+ for (index, (toml, expected)) in alias_cases().iter().enumerate() {+ let got = got+ .get(index)+ .copied()+ .unwrap_or("<missing>")+ .trim_end_matches('\r');+ assert_eq!(got, expected.as_deref().unwrap_or(""), "{port}: {toml}");+ }+ }+/// 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();@@ -12810,6 +12887,31 @@ mod identity_parity_tests {.unwrap();assert!(output.status.success());assert_styles_agree("hooks/_lib.sh", &String::from_utf8_lossy(&output.stdout));++ let temp = tempfile::tempdir().unwrap();+ let files = alias_cases()+ .iter()+ .enumerate()+ .map(|(index, (toml, _))| {+ let path = temp.path().join(format!("alias-{index:03}.toml"));+ std::fs::write(&path, toml).unwrap();+ path+ })+ .collect::<Vec<_>>();+ let output = Command::new("sh")+ .arg("-c")+ .arg(r#". "$1"; shift; for f in "$@"; do printf '%s\n' "$(ai_memory_aliases_json "$f")"; done"#)+ .arg("sh")+ .arg(repo_file("hooks/_lib.sh"))+ .args(&files)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_aliases_agree("hooks/_lib.sh", &String::from_utf8_lossy(&output.stdout));}#[test]@@ -12826,7 +12928,7 @@ mod identity_parity_tests {let script = tmp.path().join("parity.ps1");std::fs::write(&script,- "param([string] $Lib, [string] $Cases, [string] $Styles)\n\+ "param([string] $Lib, [string] $Cases, [string] $Styles, [string] $AliasesDir)\n\. $Lib\n\foreach ($u in (Get-Content -Raw $Cases | ConvertFrom-Json)) {\n\$id = ConvertTo-AiMemoryRepositoryIdentity -Url $u\n\@@ -12840,6 +12942,9 @@ mod identity_parity_tests {[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\+ Get-ChildItem $AliasesDir -Filter '*.toml' | Sort-Object Name | ForEach-Object {\n\+ [Console]::Out.Write(\"A:$(Get-AiMemoryTomlAliases -File $_.FullName)`n\")\n\}\n",).unwrap();@@ -12849,12 +12954,18 @@ mod identity_parity_tests {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 aliases_dir = tmp.path().join("aliases");+ std::fs::create_dir(&aliases_dir).unwrap();+ for (index, (toml, _)) in alias_cases().iter().enumerate() {+ std::fs::write(aliases_dir.join(format!("alias-{index:03}.toml")), toml).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)+ .arg(&aliases_dir).output().unwrap();assert!(@@ -12865,11 +12976,27 @@ mod identity_parity_tests {// 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:"));+ let lines = stdout.split('\n').collect::<Vec<_>>();+ let styles = lines+ .iter()+ .copied()+ .filter(|line| line.starts_with("S:"))+ .collect::<Vec<_>>();+ let aliases = lines+ .iter()+ .copied()+ .filter(|line| line.starts_with("A:"))+ .map(|line| &line[2..])+ .collect::<Vec<_>>();+ let urls = lines+ .iter()+ .copied()+ .filter(|line| !line.starts_with("S:") && !line.starts_with("A:"))+ .collect::<Vec<_>>();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"));+ assert_aliases_agree("hooks/lib/ai-memory-hook.ps1", &aliases.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!(@@ -12878,6 +13005,108 @@ mod identity_parity_tests {);}+ #[test]+ fn generated_typescript_applies_marker_alias_params_together() {+ let strips_types = Command::new("node")+ .args(["--experimental-strip-types", "-e", "0"])+ .output()+ .is_ok_and(|out| out.status.success());+ if !strips_types {+ return;+ }+ for default_strategy in [None, Some("basename")] {+ let tmp = tempfile::TempDir::new().unwrap();+ let repo = tmp.path().join("repo");+ std::fs::create_dir(&repo).unwrap();+ assert!(+ Command::new("git")+ .args(["init", "-q"])+ .current_dir(&repo)+ .status()+ .unwrap()+ .success()+ );+ assert!(+ Command::new("git")+ .args([+ "remote",+ "add",+ "origin",+ "[email protected]:Acme/API.git",+ ])+ .current_dir(&repo)+ .status()+ .unwrap()+ .success()+ );+ std::fs::write(+ repo.join(".ai-memory.toml"),+ "project = \"acme-api\"\naliases = [\"former-name\"]\n",+ )+ .unwrap();+ let module = tmp.path().join("apply-marker.ts");+ let source = format!(+ "import {{ execFileSync }} from \"node:child_process\";\n\+ import {{ existsSync, readFileSync }} from \"node:fs\";\n\+ import {{ basename, dirname, join, resolve, sep }} from \"node:path\";\n\+ import {{ homedir }} from \"node:os\";\n\+ function tomlKey(text: string, key: string): string | undefined {{\n\+ const re = new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`);\n\+ for (const line of text.split(/\\r?\\n/)) {{\n\+ const match = re.exec(line);\n\+ if (match) return match[1];\n\+ }}\n\+ return undefined;\n\+ }}\n\+ {}\n\+ {}\n\+ const url = new URL(\"http://h/hook\");\n\+ applyMarkerParams(url, {});\n\+ process.stdout.write(url.search);\n",+ super::TS_REPO_ROOT_PROJECT,+ super::ts_apply_marker_params(default_strategy),+ serde_json::to_string(&repo.to_string_lossy()).unwrap(),+ );+ std::fs::write(&module, source).unwrap();+ let output = Command::new("node")+ .args(["--experimental-strip-types", "--no-warnings"])+ .arg(&module)+ .env("HOME", tmp.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let params = reqwest::Url::parse(&format!(+ "http://h/hook{}",+ String::from_utf8(output.stdout).unwrap()+ ))+ .unwrap()+ .query_pairs()+ .into_owned()+ .collect::<std::collections::HashMap<_, _>>();+ assert_eq!(params.get("project").map(String::as_str), Some("acme-api"));+ assert_eq!(+ params.get("identity").map(String::as_str),+ Some("git.example.test/acme/api")+ );+ assert_eq!(+ params.get("identity_src").map(String::as_str),+ Some("git_remote")+ );+ assert_eq!(+ params.get("aliases").map(String::as_str),+ Some("[\"former-name\"]")+ );+ assert_eq!(+ params.get("project_src").map(String::as_str),+ Some("marker")+ );+ }+ }+#[test]fn the_typescript_port_agrees_with_the_core() {let strips_types = Command::new("node")@@ -12897,6 +13126,8 @@ mod identity_parity_tests {{}\n\const urls: string[] = {};\n\process.stdout.write(urls.map((u) => normalizeRemote(u) ?? \"\").join(\"\\n\") + \"\\n\");\n\+ const aliasCases: string[] = {};\n\+ for (const marker of aliasCases) process.stdout.write(`A:${{markerAliases(marker) ?? \"\"}}\\n`);\n\const styles: string[] = {};\n\for (const s of styles) {{\n\const forwarded = identityStyleParam(s);\n\@@ -12904,12 +13135,19 @@ mod identity_parity_tests {}}\n\const decide = (explicit?: string, project?: string): string => {{\n\const url = new URL(\"http://h/hook\");\n\- applyIdentityParams(url, undefined, explicit, project, \"path\");\n\+ applyIdentityParams(url, undefined, explicit, project, \"path\", undefined);\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(+ &alias_cases()+ .into_iter()+ .map(|(toml, _)| toml)+ .collect::<Vec<_>>()+ )+ .unwrap(),serde_json::to_string(&styles).unwrap());std::fs::write(&module, source).unwrap();@@ -12924,10 +13162,26 @@ mod identity_parity_tests {String::from_utf8_lossy(&output.stderr));let stdout = String::from_utf8_lossy(&output.stdout);- let (styles, urls): (Vec<&str>, Vec<&str>) =- stdout.split('\n').partition(|line| line.starts_with("S:"));+ let lines = stdout.split('\n').collect::<Vec<_>>();+ let aliases = lines+ .iter()+ .copied()+ .filter(|line| line.starts_with("A:"))+ .map(|line| &line[2..])+ .collect::<Vec<_>>();+ let styles = lines+ .iter()+ .copied()+ .filter(|line| line.starts_with("S:"))+ .map(|line| &line[2..])+ .collect::<Vec<_>>();+ let urls = lines+ .iter()+ .copied()+ .filter(|line| !line.starts_with("S:") && !line.starts_with("A:"))+ .collect::<Vec<_>>();assert_agrees("TS_IDENTITY", urls.join("\n").as_bytes());- let styles: Vec<&str> = styles.iter().map(|line| &line[2..]).collect();+ assert_aliases_agree("TS_IDENTITY", &aliases.join("\n"));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. A requesteddiff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rsindex 4e05dced..4b601775 100644--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs@@ -224,9 +224,10 @@ pub(crate) fn manifest_json() -> String {fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {let toml_flag = super::install_hooks::TS_TOML_FLAG;let find_settings_marker = super::install_hooks::TS_FIND_SETTINGS_MARKER;+ let identity = super::install_hooks::TS_IDENTITY;let Some(default) = default_strategy else {return format!(- "{toml_flag}\n{find_settings_marker}\n{}",+ "{toml_flag}\n{find_settings_marker}\n{identity}\n{}",r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {if (!cwd) return;url.searchParams.set("cwd", cwd);@@ -236,6 +237,11 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {const body = readFileSync(marker, "utf8");const workspace = tomlKey(body, "workspace");const project = tomlKey(body, "project");+ const aliases = markerAliases(body);+ if (aliases) {+ const remoteIdentity = applyIdentityParams(url, cwd, undefined, project, tomlKey(body, "identity_style"), aliases);+ url.searchParams.set("aliases", project && remoteIdentity ? aliases : "invalid");+ }const projectStrategy = tomlKey(body, "project_strategy");const dropSubagent = tomlKey(body, "drop_subagent_captures");const defaultGlobal = tomlFlag(body, "default_global");@@ -279,6 +285,8 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {let briefingBudget: string | undefined;let profileContribute: string | undefined;let profileConsume: string | undefined;+ let identityStyle: string | undefined;+ let aliases: string | undefined;const marker = findSettingsMarker(cwd);if (marker) {try {@@ -292,9 +300,15 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {briefingBudget = tomlFlag(body, "max_chars");profileContribute = profileFlag(tomlFlag(body, "contribute"));profileConsume = profileFlag(tomlFlag(body, "consume"));+ identityStyle = tomlKey(body, "identity_style");+ aliases = markerAliases(body);} catch (_e) {}}+ if (aliases) {+ const remoteIdentity = applyIdentityParams(url, cwd, undefined, project, identityStyle, aliases);+ url.searchParams.set("aliases", project && remoteIdentity ? aliases : "invalid");+ }// `project_src` tells the server a marker rescope from a host-derived// repo-root name; only the latter yields to sticky routing (#394).let projectSrc: string | undefined = project ? "marker" : undefined;@@ -318,7 +332,7 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {if (profileConsume) url.searchParams.set("profile_consume", profileConsume);}"#;format!(- "const DEFAULT_PROJECT_STRATEGY = {};\n{toml_flag}\n{find_settings_marker}\n{body}",+ "const DEFAULT_PROJECT_STRATEGY = {};\n{toml_flag}\n{find_settings_marker}\n{identity}\n{body}",ts_string_literal(default))}@@ -742,6 +756,22 @@ mod tests {);}+ #[test]+ fn openclaw_identity_discovery_is_alias_gated() {+ let plugin = build_plugin("http://127.0.0.1:49374", Some("tok"), None, "denylist");+ let apply = plugin+ .split_once("function applyMarkerParams")+ .unwrap()+ .1+ .split_once("function postHook")+ .unwrap()+ .0;+ assert!(apply.contains("if (!marker) return;"));+ assert_eq!(apply.matches("applyIdentityParams(").count(), 1);+ assert!(apply.contains("if (aliases) {\n const remoteIdentity = applyIdentityParams"));+ assert!(!apply.contains("tomlKey(body, \"identity\")"));+ }+#[test]fn openclaw_plugin_default_omits_baked_strategy() {let plugin = build_plugin("http://127.0.0.1:49374", Some("tok"), None, "denylist");diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rsindex 30f15cec..36f0aff5 100644--- a/crates/ai-memory-cli/src/marker.rs+++ b/crates/ai-memory-cli/src/marker.rs@@ -40,13 +40,30 @@ pub(crate) struct MarkerScope {pub(crate) project_strategy: Option<String>,}-#[derive(Debug, Clone, Default)]+#[derive(Debug, Clone)]pub(crate) struct RoutingFields {pub(crate) workspace: Option<String>,pub(crate) project: Option<String>,pub(crate) project_strategy: Option<String>,pub(crate) identity: Option<String>,pub(crate) identity_style: Option<String>,+ pub(crate) aliases: Result<+ Option<ai_memory_core::repository_identity::MarkerAliases>,+ ai_memory_core::repository_identity::MarkerAliasError,+ >,+}++impl Default for RoutingFields {+ fn default() -> Self {+ Self {+ workspace: None,+ project: None,+ project_strategy: None,+ identity: None,+ identity_style: None,+ aliases: Ok(None),+ }+ }}impl RoutingFields {@@ -57,6 +74,7 @@ impl RoutingFields {project_strategy: parse_key_in(text, "project_strategy"),identity: parse_key_in(text, "identity"),identity_style: parse_key_in(text, "identity_style"),+ aliases: parse_aliases_in(text),}}}@@ -117,12 +135,14 @@ pub(crate) fn inspect_scope(cwd: &str, env: &RuntimeEnv) -> MarkerInspection {return Some(empty("conflicting"));}}- if fields.identity_style.as_deref().is_some_and(|style| {- ai_memory_core::repository_identity::IdentityStyle::from_str_opt(style).is_none()- }) || fields- .project_strategy- .as_deref()- .is_some_and(|strategy| !matches!(strategy, "repo-root" | "repo_root" | "basename"))+ if fields.aliases.is_err()+ || fields.identity_style.as_deref().is_some_and(|style| {+ ai_memory_core::repository_identity::IdentityStyle::from_str_opt(style)+ .is_none()+ })+ || fields.project_strategy.as_deref().is_some_and(|strategy| {+ !matches!(strategy, "repo-root" | "repo_root" | "basename")+ }){return Some(empty("conflicting"));}@@ -326,6 +346,11 @@ fn declares_more_than_capture(text: &str) -> bool {.iter().any(|key| parse_flag_in(text, key).is_some())|| server_selection_in(text).is_some()+ || text.lines().any(|line| {+ line.trim_start()+ .strip_prefix("aliases")+ .is_some_and(|rest| rest.trim_start().starts_with('='))+ })}/// A marker's `server = "<profile>"` selection (#992), and the directory of@@ -496,6 +521,26 @@ fn parse_key_in(text: &str, key: &str) -> Option<String> {None}+pub(crate) fn parse_toml_aliases(+ file: &Path,+) -> Result<+ Option<ai_memory_core::repository_identity::MarkerAliases>,+ ai_memory_core::repository_identity::MarkerAliasError,+> {+ let text = std::fs::read_to_string(file)+ .map_err(|_| ai_memory_core::repository_identity::MarkerAliasError::InvalidWire)?;+ parse_aliases_in(&text)+}++fn parse_aliases_in(+ text: &str,+) -> Result<+ Option<ai_memory_core::repository_identity::MarkerAliases>,+ ai_memory_core::repository_identity::MarkerAliasError,+> {+ ai_memory_core::repository_identity::parse_marker_aliases(text)+}+/// Parse a root-level `key = <value>` line, accepting a quoted string/// (`key = "true"`) OR a bare token (`key = true` / `key = 1`), so a/// `[recall] default_global = true` marker works whether or not the operator@@ -655,6 +700,32 @@ mod tests {/// Happy-path TOML parser: extracts each declared root-level/// `key = "value"` pair. Mirrors the shell `ai_memory_parse_toml_key`.+ #[test]+ fn marker_aliases_match_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["marker_aliases"].as_array().unwrap() {+ let parsed = parse_aliases_in(case["toml"].as_str().unwrap());+ match case["status"].as_str().unwrap() {+ "valid" => {+ let got = parsed.unwrap().unwrap().as_slice().to_vec();+ let expected = case["aliases"]+ .as_array()+ .unwrap()+ .iter()+ .map(|value| value.as_str().unwrap().to_owned())+ .collect::<Vec<_>>();+ assert_eq!(got, expected, "{}", case["toml"]);+ }+ "absent" => assert_eq!(parsed.unwrap(), None, "{}", case["toml"]),+ "invalid" => assert!(parsed.is_err(), "{}", case["toml"]),+ status => panic!("unknown fixture status {status}"),+ }+ }+ }+#[test]fn parse_toml_key_extracts_root_level_strings() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-core/fixtures/remote_identity_cases.json b/crates/ai-memory-core/fixtures/remote_identity_cases.jsonindex 6cd0b4f0..7417e9cb 100644--- a/crates/ai-memory-core/fixtures/remote_identity_cases.json+++ b/crates/ai-memory-core/fixtures/remote_identity_cases.json@@ -1,5 +1,5 @@{- "_comment": "Shared by every client that normalises a git remote into a repository identity: the Rust core, hooks/_lib.sh, hooks/lib/ai-memory-hook.ps1 and the generated TypeScript plugins. A case added here is checked against all four, so they cannot drift apart. `identity: null` means the remote must yield no identity.",+ "_comment": "Shared by every client that normalises a git remote and parses local marker aliases: the Rust core/native client, hooks/_lib.sh, hooks/lib/ai-memory-hook.ps1 and generated TypeScript plugins. Alias cases define the deliberately limited portable grammar: one root-level, one-line JSON-compatible string array; no escapes, duplicate declarations, table placement, multiline arrays, trailing commas, comments, or trailing junk. A case added here is checked against all four, so they cannot drift apart. (#1033)","normalize": [{ "url": "[email protected]:Acme/API.git", "identity": "github.com/acme/api" },{ "url": "[email protected]:acme/api", "identity": "github.com/acme/api" },@@ -57,5 +57,24 @@{ "value": "Path", "style": null },{ "value": "host-path", "style": null },{ "value": "", "style": null }+ ],+ "marker_aliases": [+ { "toml": "aliases = [\" former-name \", \"legacy_name\", \"former-name\", \"V2.name\"]", "status": "valid", "aliases": ["former-name", "legacy_name", "V2.name"] },+ { "toml": "aliases = []", "status": "valid", "aliases": [] },+ { "toml": "aliases = [ ]", "status": "valid", "aliases": [] },+ { "toml": "workspace = \"acme\"", "status": "absent" },+ { "toml": "aliases = [\"-leading\"]", "status": "invalid" },+ { "toml": "aliases = [\"../foreign\"]", "status": "invalid" },+ { "toml": "aliases = [\"nested/project\"]", "status": "invalid" },+ { "toml": "aliases = [\"escaped\\nname\"]", "status": "invalid" },+ { "toml": "aliases = [\"one\",]", "status": "invalid" },+ { "toml": "aliases = [\"one\"] # comment", "status": "invalid" },+ { "toml": "aliases = [\"one\"] junk", "status": "invalid" },+ { "toml": "aliases = [\n \"one\"\n]", "status": "invalid" },+ { "toml": "aliases = [\"one\"]\naliases = [\"two\"]", "status": "invalid" },+ { "toml": "[capture]\naliases = [\"one\"]", "status": "invalid" },+ { "toml": "aliases = [\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"]", "status": "valid", "aliases": ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"] },+ { "toml": "aliases = [\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"]", "status": "invalid" },+ { "toml": "aliases = [\"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\", \"same\"]", "status": "invalid" }]}diff --git a/crates/ai-memory-core/src/repository_identity.rs b/crates/ai-memory-core/src/repository_identity.rsindex 256c64fa..51518bf5 100644--- a/crates/ai-memory-core/src/repository_identity.rs+++ b/crates/ai-memory-core/src/repository_identity.rs@@ -78,6 +78,150 @@ pub const MARKER_FILENAMES: &[&str] = &[MARKER_FILENAME];/// bound exists so a client cannot park an arbitrary blob in a unique index.pub const MAX_IDENTITY_LEN: usize = 512;+/// Maximum former project names accepted from one local marker.+pub const MAX_MARKER_ALIASES: usize = 16;++/// Maximum UTF-8 byte length of one marker alias.+pub const MAX_MARKER_ALIAS_LEN: usize = 128;++/// Why a marker alias list was rejected.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum MarkerAliasError {+ /// More aliases were supplied than the bounded routing request permits.+ TooMany,+ /// One alias was empty, oversized, escaped, or not a plain project token.+ Invalid,+ /// The marker or wire value did not use the portable array grammar.+ InvalidWire,+}++impl std::fmt::Display for MarkerAliasError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(match self {+ Self::TooMany => "too many marker aliases",+ Self::Invalid => "invalid marker alias",+ Self::InvalidWire => "invalid marker aliases wire value",+ })+ }+}++impl std::error::Error for MarkerAliasError {}++/// A validated, bounded marker alias list.+///+/// Construction is limited to the parsers below, so store and router APIs+/// cannot accidentally iterate an unbounded caller-supplied vector.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]+#[serde(transparent)]+pub struct MarkerAliases(Vec<String>);++impl MarkerAliases {+ /// Validate, trim, and first-occurrence-deduplicate aliases.+ pub fn new<I, S>(aliases: I) -> Result<Self, MarkerAliasError>+ where+ I: IntoIterator<Item = S>,+ S: AsRef<str>,+ {+ let mut normalized = Vec::new();+ let mut count = 0_usize;+ for alias in aliases {+ count += 1;+ if count > MAX_MARKER_ALIASES {+ return Err(MarkerAliasError::TooMany);+ }+ let alias = alias.as_ref().trim();+ let mut chars = alias.chars();+ let first_valid = chars.next().is_some_and(|c| {+ c.is_ascii_lowercase() || c.is_ascii_uppercase() || c.is_ascii_digit()+ });+ if !first_valid+ || alias.len() > MAX_MARKER_ALIAS_LEN+ || !chars.all(|c| {+ c.is_ascii_lowercase()+ || c.is_ascii_uppercase()+ || c.is_ascii_digit()+ || matches!(c, '.' | '_' | '-')+ })+ {+ return Err(MarkerAliasError::Invalid);+ }+ if !normalized.iter().any(|seen| seen == alias) {+ normalized.push(alias.to_owned());+ }+ }+ Ok(Self(normalized))+ }++ /// Borrow the bounded names in deterministic marker order.+ #[must_use]+ pub fn as_slice(&self) -> &[String] {+ &self.0+ }++ /// Whether the marker supplied no effective aliases.+ #[must_use]+ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }++ /// Stable cache-key representation; aliases cannot contain this separator.+ #[must_use]+ pub fn cache_key(&self) -> String {+ self.0.join("\u{1f}")+ }+}++/// Decode the compact JSON-array query value used by hook and handoff clients.+pub fn accept_wire_aliases(raw: Option<&str>) -> Result<MarkerAliases, MarkerAliasError> {+ let Some(raw) = raw else {+ return Ok(MarkerAliases::default());+ };+ if raw.len() > (MAX_MARKER_ALIAS_LEN + 6) * MAX_MARKER_ALIASES + 2 {+ return Err(MarkerAliasError::TooMany);+ }+ if raw.contains('\\') {+ return Err(MarkerAliasError::Invalid);+ }+ let aliases: Vec<String> =+ serde_json::from_str(raw).map_err(|_| MarkerAliasError::InvalidWire)?;+ MarkerAliases::new(aliases)+}++/// Parse the portable local-marker alias grammar.+///+/// The only accepted declaration is one root-level, one-line+/// `aliases = ["name", "other"]`. Strings may contain only the alias token+/// characters accepted by [`MarkerAliases::new`]; escapes, trailing commas,+/// comments/trailing junk, duplicate declarations, multiline arrays, and an+/// `aliases` key inside any table are rejected.+pub fn parse_marker_aliases(text: &str) -> Result<Option<MarkerAliases>, MarkerAliasError> {+ let mut found = None;+ let mut in_table = false;+ for line in text.lines() {+ let trimmed = line.trim();+ if trimmed.starts_with('[') {+ in_table = true;+ }+ let Some((key, value)) = trimmed.split_once('=') else {+ continue;+ };+ if key.trim() != "aliases" {+ continue;+ }+ if in_table || found.is_some() {+ return Err(MarkerAliasError::InvalidWire);+ }+ let value = value.trim();+ if value.contains('\\') {+ return Err(MarkerAliasError::Invalid);+ }+ let aliases: Vec<String> =+ serde_json::from_str(value).map_err(|_| MarkerAliasError::InvalidWire)?;+ found = Some(MarkerAliases::new(aliases)?);+ }+ Ok(found)+}+/// Which rung of the chain produced an identity.////// Stored alongside the identity so an operator can tell a globally unique@@ -971,6 +1115,61 @@ mod tests {}}+ #[test]+ fn marker_aliases_are_bounded_trimmed_deduplicated_and_reject_paths() {+ assert_eq!(+ MarkerAliases::new([" former-name ", "legacy_name", "former-name"])+ .unwrap()+ .as_slice(),+ ["former-name", "legacy_name"]+ );+ for invalid in [+ "",+ "-leading",+ "../foreign",+ "nested/project",+ "bad\u{7}name",+ ] {+ assert_eq!(+ MarkerAliases::new([invalid]),+ Err(MarkerAliasError::Invalid),+ "{invalid:?}"+ );+ }+ assert_eq!(+ MarkerAliases::new((0..=MAX_MARKER_ALIASES).map(|index| format!("a{index}"))),+ Err(MarkerAliasError::TooMany)+ );+ assert_eq!(+ MarkerAliases::new([format!("a{}", "x".repeat(MAX_MARKER_ALIAS_LEN))]),+ Err(MarkerAliasError::Invalid)+ );+ }++ #[test]+ fn marker_alias_values_match_the_shared_fixture() {+ let cases: serde_json::Value = serde_json::from_str(CASES).unwrap();+ for case in cases["marker_aliases"].as_array().unwrap() {+ let toml = case["toml"].as_str().unwrap();+ let parsed = parse_marker_aliases(toml);+ match case["status"].as_str().unwrap() {+ "valid" => {+ let got = parsed.unwrap().unwrap().as_slice().to_vec();+ let expected = case["aliases"]+ .as_array()+ .unwrap()+ .iter()+ .map(|value| value.as_str().unwrap().to_owned())+ .collect::<Vec<_>>();+ assert_eq!(got, expected, "{toml}");+ }+ "absent" => assert_eq!(parsed.unwrap(), None, "{toml}"),+ "invalid" => assert!(parsed.is_err(), "{toml}"),+ status => panic!("unknown fixture status {status}"),+ }+ }+ }+/// The same path on two forges keeps two `host_path` keys but shares one/// `path` key — the collision adoption must detect, never merge.#[test]diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 74ec23ac..f06009d7 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -101,6 +101,9 @@ pub struct HookQuery {/// 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>,+ /// Compact JSON array of validated former project names from the local+ /// marker. Accepted only with a full git-remote identity.+ pub aliases: Option<String>,}/// Coalesced view of an incoming hook event after light parsing of the@@ -136,6 +139,10 @@ pub struct HookEnvelope {/// How a project this event creates is named; see/// [`ai_memory_core::repository_identity::IdentityStyle`].pub identity_style: ai_memory_core::repository_identity::IdentityStyle,+ /// Validated, normalized former project names supplied by the local marker.+ pub aliases: ai_memory_core::repository_identity::MarkerAliases,+ /// Whether an alias query was malformed or lacked a git-remote identity.+ pub aliases_invalid: bool,/// 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@@ -190,6 +197,8 @@ impl std::fmt::Debug for HookEnvelope {.field("project_override", &self.project_override).field("project_strategy", &self.project_strategy).field("identity", &self.identity)+ .field("alias_count", &self.aliases.as_slice().len())+ .field("aliases_invalid", &self.aliases_invalid).field("drop_subagent_requested", &self.drop_subagent_requested).field("recall_default_global_requested",@@ -267,6 +276,28 @@ pub(crate) fn query_flag_falsy(value: Option<&str>) -> bool {)}+pub(crate) fn marker_aliases_from_wire(+ project: Option<&str>,+ project_source: ProjectSource,+ identity: Option<&ai_memory_core::repository_identity::RepositoryIdentity>,+ raw: Option<&str>,+) -> Result<+ ai_memory_core::repository_identity::MarkerAliases,+ ai_memory_core::repository_identity::MarkerAliasError,+> {+ let aliases = ai_memory_core::repository_identity::accept_wire_aliases(raw)?;+ if raw.is_some()+ && (project.is_none_or(|project| project.trim().is_empty())+ || project_source != ProjectSource::Marker+ || !identity.is_some_and(|identity| {+ identity.source == ai_memory_core::repository_identity::IdentitySource::GitRemote+ }))+ {+ return Err(ai_memory_core::repository_identity::MarkerAliasError::InvalidWire);+ }+ Ok(aliases)+}+/// How the hook router derives a project name when no explicit/// `project` override is present.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]@@ -561,6 +592,18 @@ impl HookEnvelope {.as_deref().and_then(ai_memory_core::repository_identity::IdentityStyle::from_str_opt).unwrap_or_default();+ let aliases = marker_aliases_from_wire(+ project_override.as_deref(),+ project_source,+ identity.as_ref(),+ query.aliases.as_deref(),+ );+ let aliases_invalid = aliases.is_err();+ let aliases = if aliases_invalid {+ ai_memory_core::repository_identity::MarkerAliases::default()+ } else {+ aliases.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());@@ -646,6 +689,8 @@ impl HookEnvelope {project_source,identity,identity_style,+ aliases,+ aliases_invalid,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 4d04d3db..b95ab934 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -91,7 +91,8 @@ pub const DEFAULT_PROJECT_CACHE_MAX_ENTRIES: usize = 4096;const SUBAGENT_SESSIONS_MAX: usize = 4096;/// Resolved-project cache key:-/// `(cwd, workspace_override, project_override, project_strategy, identity)`.+/// `(cwd, workspace_override, project_override, project_strategy,+/// identity/aliases/provenance/mode)`.pub type ProjectCacheKey = (String, String, String, String, String);/// Shared bounded resolved-project cache.@@ -464,7 +465,7 @@ pub struct HookState {/// the store. Same handle is also held by the wiki and consolidator/// so scrubbing happens at every write boundary.pub sanitizer: Sanitizer,- /// Cache of `(cwd, workspace_override, project_override, project_strategy) → ids`.+ /// Cache of `(cwd, workspace_override, project_override, project_strategy, identity+aliases) → ids`./// The composite key avoids poisoning between callers that resolve/// the same `cwd` with and without an override during a hook-script/// upgrade window. Each tuple element defaults to the empty string@@ -655,6 +656,10 @@ async fn handle_hook(// on for a supported Stop, populate the Stop body with the sanitized excerpt.// Any gate failure leaves an empty Stop with the same 202 "queued" response.crate::assistant_capture::apply_assistant_backstop(&mut env, state.capture_assistant_enabled);+ if env.aliases_invalid {+ HookProcessingOutcome::DroppedInvalid.record(&state.ingest_metrics);+ return (StatusCode::ACCEPTED, "invalid marker aliases");+ }let Some(env) = inspect_capture_envelope(env) else {HookProcessingOutcome::DroppedPolicy.record(&state.ingest_metrics);return (StatusCode::ACCEPTED, "capture policy dropped");@@ -906,6 +911,15 @@ async fn handle_hook_batch(&mut env,state.capture_assistant_enabled,);+ if env.aliases_invalid {+ HookProcessingOutcome::DroppedInvalid.record(&state.ingest_metrics);+ results.push(HookBatchResult {+ index: idx,+ outcome: HookProcessingOutcome::DroppedInvalid,+ });+ accepted_indices.push(idx);+ continue;+ }let Some(env) = inspect_capture_envelope(env) else {// A protocol-directed drop is committed from the spool's point of// view, but intentionally spends neither ingress capacity nor a@@ -1297,6 +1311,9 @@ async fn should_drop_subagent(env.project_strategy,env.identity.as_ref(),env.identity_style,+ &env.aliases,+ env.project_source,+ true,viewer,).await@@ -1355,6 +1372,8 @@ pub struct HandoffQuery {pub workspace: Option<String>,/// Project override (mirror of `HookQuery.project`).pub project: Option<String>,+ /// Provenance of the project override (mirror of `HookQuery.project_src`).+ pub project_src: Option<String>,/// Project strategy (mirror of `HookQuery.project_strategy`).pub project_strategy: Option<String>,/// Per-repo opt-in for the session-start project brief, forwarded by@@ -1384,6 +1403,8 @@ pub struct HandoffQuery {/// Naming style for a project this request creates; see/// [`crate::payload::HookQuery::identity_style`].pub identity_style: Option<String>,+ /// Compact JSON array of former project names from the local marker.+ pub aliases: Option<String>,/// The marker's `[profile] contribute`. An explicit falsy value keeps the/// project out of profile harvesting; absent or anything else keeps it in.pub profile_contribute: Option<String>,@@ -1479,6 +1500,14 @@ async fn fetch_and_accept_handoff_at(now: jiff::Timestamp,) -> anyhow::Result<Option<String>> {let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);+ let repository = query.repository_identity();+ let aliases = crate::payload::marker_aliases_from_wire(+ query.project.as_deref(),+ ProjectSource::parse(query.project_src.as_deref()),+ repository.as_ref(),+ query.aliases.as_deref(),+ )+ .map_err(|_| anyhow::anyhow!("invalid marker aliases"))?;// Keep the active-project key compatible with MCP transports: the native// session id is carried separately below to bind a destructive handoff// claim to its exact receiver.@@ -1492,8 +1521,11 @@ async fn fetch_and_accept_handoff_at(query.workspace.as_deref(),query.project.as_deref(),ProjectStrategy::parse(query.project_strategy.as_deref()),- query.repository_identity().as_ref(),+ repository.as_ref(),query.identity_style(),+ &aliases,+ ProjectSource::parse(query.project_src.as_deref()),+ false,viewer,).await?;@@ -2491,12 +2523,16 @@ pub(crate) fn render_managed_context(/// project strategy. Shared by `resolve_project_ids` (insert/lookup) and/// `process` (eviction on the stale-cache retry) so the two always agree on/// the slot.+#[allow(clippy::too_many_arguments)]fn cache_key_for(cwd_norm: Option<&str>,workspace_override: Option<&str>,project_override: Option<&str>,project_strategy: ProjectStrategy,identity: Option<&ai_memory_core::repository_identity::RepositoryIdentity>,+ aliases: &ai_memory_core::repository_identity::MarkerAliases,+ project_source: ProjectSource,+ promote_alias: bool,) -> ProjectCacheKey {(cwd_norm.unwrap_or_default().to_string(),@@ -2506,9 +2542,14 @@ fn cache_key_for(// Two repositories can sit at the same path on two machines. Without// the identity in the key, whichever resolved first would answer for// both.- identity- .map(|i| format!("{}:{}", i.source.as_str(), i.identity))- .unwrap_or_default(),+ format!(+ "{}:{}:{}:{}:{}",+ identity.map(|i| i.source.as_str()).unwrap_or_default(),+ identity.map(|i| i.identity.as_str()).unwrap_or_default(),+ aliases.cache_key(),+ project_source.as_str(),+ if promote_alias { "write" } else { "read" }+ ),)}@@ -2543,14 +2584,15 @@ fn has_publishable_scope_hint(cwd: Option<&str>, project_override: Option<&str>)/// Precedence:/// 1. `workspace_override` (typically declared by the agent's host-side/// hook via a `.ai-memory.toml` walk-up) OR `DEFAULT_WORKSPACE_NAME`.-/// 2. `project_override` OR marker-selected project strategy OR-/// `basename(cwd)` OR fallback to `state.project_id` (when `cwd` is-/// also unavailable).+/// 2. A canonical marker `project` may resolve through one of its aliases only+/// when the checkout's full git-remote identity matches the stored row.+/// 3. Otherwise `project_override` OR marker-selected project strategy OR+/// `basename(cwd)` OR fallback to `state.project_id` (when `cwd` is also+/// unavailable).///-/// Cache key is `(cwd, workspace_override, project_override,-/// 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.+/// Cache identity includes cwd, overrides, strategy, repository identity,+/// normalized aliases, and read/write alias mode so a SessionStart lookup+/// cannot suppress a later capture promotion.#[allow(clippy::too_many_arguments)]async fn resolve_project_ids_inner(state: &HookState,@@ -2560,6 +2602,9 @@ async fn resolve_project_ids_inner(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,creator: Option<ai_memory_core::UserId>,) -> anyhow::Result<(WorkspaceId, ProjectId)> {let cwd_raw = cwd.filter(|s| !s.is_empty());@@ -2572,14 +2617,22 @@ async fn resolve_project_ids_inner(}// Only the rungs that carry something a name does not route by identity:- // a declared `project` and a folder name keep routing by name.- let identity = identity.filter(|i| i.source.routes_by_identity());+ // a declared `project` and a folder name keep routing by name. Marker+ // projects opt into identity routing only when they carry effective aliases;+ // an accepted empty alias list is inert and preserves marker precedence.+ let identity = identity.filter(|i| {+ i.source.routes_by_identity()+ && !(project_source == ProjectSource::Marker && aliases.is_empty())+ });let cache_key = cache_key_for(cwd_norm.as_deref(),workspace_override,project_override,project_strategy,identity,+ aliases,+ project_source,+ promote_alias,);{@@ -2771,7 +2824,67 @@ async fn resolve_project_ids_inner(.map_err(|e| anyhow::anyhow!("find_project_by_cwd_prefix: {e}"))?,_ => None,};- let proj = if let Some(identity) = identity {+ let alias_match = if aliases.is_empty() {+ None+ } else {+ let identity = identity+ .ok_or_else(|| anyhow::anyhow!("marker aliases require repository identity"))?;+ let resolved = if promote_alias {+ let principal = creator.map(ai_memory_store::ProjectPrincipal::user);+ match state+ .writer+ .resolve_project_aliases_for_write(+ ws,+ project_name.clone(),+ aliases.clone(),+ identity.clone(),+ principal,+ creator.is_some(),+ )+ .await+ {+ Ok(Some(resolved)) => {+ if resolved.promoted_from.is_some()+ && let Err(error) = state+ .wiki+ .refresh_renamed_scope(ws, resolved.project_id)+ .await+ {+ warn!(error = %error, "marker alias promotion committed but manifest refresh failed");+ }+ Ok(Some(resolved.project_id))+ }+ Ok(None) => Ok(None),+ Err(error) => Err(error),+ }+ } else {+ state+ .reader+ .resolve_existing_project_aliases(+ ws,+ project_name.clone(),+ aliases.clone(),+ identity.clone(),+ )+ .await+ };+ match resolved {+ Ok(Some(project)) => Some(project),+ Ok(None) => {+ return Err(anyhow::anyhow!(+ "marker aliases did not match requested project {project_name}"+ ));+ }+ Err(error) => {+ return Err(anyhow::anyhow!(+ "marker aliases refused for requested project {project_name}: {error}"+ ));+ }+ }+ };+ let proj = if let Some(project) = alias_match {+ project+ } else if let Some(identity) = identity {// A repository identity decides the project before any name does: the// project already carrying it wins, whatever it is called, and the// name (or the cwd-prefix parent) is only the candidate for a project@@ -2846,6 +2959,9 @@ async fn resolve_project_ids(project_strategy,None,Default::default(),+ &ai_memory_core::repository_identity::MarkerAliases::default(),+ ProjectSource::Unspecified,+ true,None,).await?;@@ -3161,6 +3277,9 @@ async fn process_authorized(skip_webhooks: Vec<String>,viewer: Option<ai_memory_core::UserId>,) -> anyhow::Result<HookProcessingOutcome> {+ if env.aliases_invalid {+ return Err(anyhow::anyhow!("invalid marker aliases"));+ }let session_id = resolve_session_id(&env)?;// An OpenCode `session.moved` relocation, forwarded by the plugin as a// SessionStart naming the directory the session left. Admission rebinds@@ -3267,6 +3386,9 @@ async fn process_authorized(env.project_strategy,env.identity.as_ref(),env.identity_style,+ &env.aliases,+ env.project_source,+ true,viewer,).await?@@ -3354,6 +3476,9 @@ async fn process_authorized(env.project_override.as_deref(),env.project_strategy,env.identity.as_ref(),+ &env.aliases,+ env.project_source,+ true,);let mut attempts = 0;// Keep the successful keyed-ingest gate until every downstream effect has@@ -3421,6 +3546,9 @@ async fn process_authorized(env.project_strategy,env.identity.as_ref(),env.identity_style,+ &env.aliases,+ env.project_source,+ true,viewer,).await?;@@ -4512,6 +4640,7 @@ mod tests {cwd: Some(cwd.to_string()),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -4520,6 +4649,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,}}@@ -4991,6 +5121,7 @@ mod tests {profile_digest: None,identity: Some(identity.to_owned()),identity_src: Some(source.to_owned()),+ aliases: None,..Default::default()};let got = query("github.com/orga/api", "git_remote")@@ -5010,6 +5141,300 @@ mod tests {assert!(HandoffQuery::default().repository_identity().is_none());}+ #[test]+ fn hook_and_handoff_queries_validate_aliases_identically() {+ let raw = Some("[\" former-name \",\"legacy_name\",\"former-name\"]".to_owned());+ let hook = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ identity: Some("github.com/acme/api".into()),+ project: Some("acme-api".into()),+ project_src: Some("marker".into()),+ identity_src: Some("git_remote".into()),+ aliases: raw.clone(),+ ..Default::default()+ },+ serde_json::json!({}),+ );+ let handoff = HandoffQuery {+ project: Some("acme-api".into()),+ project_src: Some("marker".into()),+ identity: Some("github.com/acme/api".into()),+ identity_src: Some("git_remote".into()),+ aliases: raw,+ ..Default::default()+ };+ assert_eq!(+ hook.aliases,+ crate::payload::marker_aliases_from_wire(+ handoff.project.as_deref(),+ ProjectSource::parse(handoff.project_src.as_deref()),+ handoff.repository_identity().as_ref(),+ handoff.aliases.as_deref(),+ )+ .unwrap()+ );+ assert_eq!(hook.aliases.as_slice(), ["former-name", "legacy_name"]);++ let invalid = Some("[\"../foreign\"]".to_owned());+ let hook = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ project: Some("acme-api".into()),+ project_src: Some("marker".into()),+ identity: Some("github.com/acme/api".into()),+ identity_src: Some("git_remote".into()),+ aliases: invalid.clone(),+ ..Default::default()+ },+ serde_json::json!({}),+ );+ let handoff = HandoffQuery {+ project: Some("acme-api".into()),+ project_src: Some("marker".into()),+ identity: Some("github.com/acme/api".into()),+ identity_src: Some("git_remote".into()),+ aliases: invalid,+ ..Default::default()+ };+ assert!(hook.aliases.is_empty());+ assert!(hook.aliases_invalid);+ assert!(+ crate::payload::marker_aliases_from_wire(+ handoff.project.as_deref(),+ ProjectSource::parse(handoff.project_src.as_deref()),+ handoff.repository_identity().as_ref(),+ handoff.aliases.as_deref(),+ )+ .is_err()+ );++ for project_src in [None, Some("repo-root".to_owned())] {+ let raw = Some("[\"former-name\"]".to_owned());+ let hook = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ project: Some("acme-api".into()),+ project_src: project_src.clone(),+ identity: Some("github.com/acme/api".into()),+ identity_src: Some("git_remote".into()),+ aliases: raw.clone(),+ ..Default::default()+ },+ serde_json::json!({}),+ );+ let handoff = crate::payload::marker_aliases_from_wire(+ Some("acme-api"),+ ProjectSource::parse(project_src.as_deref()),+ Some(&ai_memory_core::repository_identity::RepositoryIdentity {+ identity: "github.com/acme/api".into(),+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,+ }),+ raw.as_deref(),+ );+ assert!(hook.aliases_invalid);+ assert!(handoff.is_err());+ }+ }++ #[tokio::test]+ async fn capture_promotes_an_alias_but_handoff_only_reads_it() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let repository = ai_memory_core::repository_identity::RepositoryIdentity {+ identity: "github.com/acme/api".into(),+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,+ };+ let project = state+ .writer+ .resolve_project_by_identity(+ state.workspace_id,+ repository.clone(),+ ai_memory_core::repository_identity::IdentityStyle::HostPath,+ "former-name",+ None,+ None,+ None,+ )+ .await+ .unwrap()+ .0;+ let aliases =+ ai_memory_core::repository_identity::MarkerAliases::new(["former-name"]).unwrap();+ let handoff = resolve_project_ids_inner(+ &state,+ Some("/repo"),+ Some("default"),+ Some("acme-api"),+ ProjectStrategy::Basename,+ Some(&repository),+ Default::default(),+ &aliases,+ ProjectSource::Marker,+ false,+ None,+ )+ .await+ .unwrap();+ assert_eq!(handoff.1, project);+ assert_eq!(+ state+ .reader+ .project_name_by_id(state.workspace_id, project)+ .await+ .unwrap()+ .as_deref(),+ Some("former-name")+ );+ let capture = resolve_project_ids_inner(+ &state,+ Some("/repo"),+ Some("default"),+ Some("acme-api"),+ ProjectStrategy::Basename,+ Some(&repository),+ Default::default(),+ &aliases,+ ProjectSource::Marker,+ true,+ None,+ )+ .await+ .unwrap();+ assert_eq!(capture.1, project);+ assert_eq!(+ state+ .reader+ .project_name_by_id(state.workspace_id, project)+ .await+ .unwrap()+ .as_deref(),+ Some("acme-api")+ );+ }++ #[tokio::test]+ async fn empty_aliases_preserve_marker_project_precedence() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let repository = ai_memory_core::repository_identity::RepositoryIdentity {+ identity: "github.com/acme/api".into(),+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,+ };+ let identity_project = state+ .writer+ .resolve_project_by_identity(+ state.workspace_id,+ repository.clone(),+ ai_memory_core::repository_identity::IdentityStyle::HostPath,+ "identity-project",+ None,+ None,+ None,+ )+ .await+ .unwrap()+ .0;+ let marker_project = state+ .writer+ .get_or_create_project(state.workspace_id, "marker-project", None)+ .await+ .unwrap();++ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-start".into(),+ project: Some("marker-project".into()),+ project_src: Some("marker".into()),+ identity: Some(repository.identity.clone()),+ identity_src: Some("git_remote".into()),+ aliases: Some("[]".into()),+ ..Default::default()+ },+ serde_json::json!({ "cwd": "/repo" }),+ );+ assert!(!env.aliases_invalid);+ assert!(env.aliases.is_empty());+ let resolved = resolve_project_ids_inner(+ &state,+ env.cwd.as_deref(),+ Some("default"),+ env.project_override.as_deref(),+ env.project_strategy,+ env.identity.as_ref(),+ env.identity_style,+ &env.aliases,+ env.project_source,+ true,+ None,+ )+ .await+ .unwrap();++ assert_eq!(resolved.1, marker_project);+ assert_ne!(resolved.1, identity_project);+ assert_eq!(+ state+ .reader+ .project_name_by_id(state.workspace_id, identity_project)+ .await+ .unwrap()+ .as_deref(),+ Some("identity-project")+ );+ }++ #[test]+ fn project_cache_separates_alias_sets() {+ let identity = ai_memory_core::repository_identity::RepositoryIdentity {+ identity: "github.com/acme/api".into(),+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,+ };+ let first = cache_key_for(+ Some("/repo"),+ Some("default"),+ Some("acme-api"),+ ProjectStrategy::Basename,+ Some(&identity),+ &ai_memory_core::repository_identity::MarkerAliases::new(["old-a"]).unwrap(),+ ProjectSource::Marker,+ true,+ );+ let second = cache_key_for(+ Some("/repo"),+ Some("default"),+ Some("acme-api"),+ ProjectStrategy::Basename,+ Some(&identity),+ &ai_memory_core::repository_identity::MarkerAliases::new(["old-b"]).unwrap(),+ ProjectSource::Marker,+ true,+ );+ assert_ne!(first, second);+ let different_provenance = cache_key_for(+ Some("/repo"),+ Some("default"),+ Some("acme-api"),+ ProjectStrategy::Basename,+ Some(&identity),+ &ai_memory_core::repository_identity::MarkerAliases::new(["old-a"]).unwrap(),+ ProjectSource::RepoRoot,+ true,+ );+ let read_mode = cache_key_for(+ Some("/repo"),+ Some("default"),+ Some("acme-api"),+ ProjectStrategy::Basename,+ Some(&identity),+ &ai_memory_core::repository_identity::MarkerAliases::new(["old-a"]).unwrap(),+ ProjectSource::Marker,+ false,+ );+ assert_ne!(first, different_provenance);+ assert_ne!(first, read_mode);+ }+/// A capture that carries the repository identity its client resolved.async fn capture_with_identity(state: &HookState,@@ -5064,6 +5489,7 @@ mod tests {identity: Some(identity.to_owned()),identity_src: Some("git_remote".into()),identity_style: style.map(str::to_owned),+ aliases: None,..Default::default()},serde_json::json!({@@ -8085,6 +8511,95 @@ mod tests {);}+ #[tokio::test]+ async fn malformed_aliases_are_rejected_before_subagent_scope_resolution() {+ let tmp = TempDir::new().unwrap();+ let state = Arc::new(make_state(&tmp).await);+ let malformed = HookQuery {+ event: "pre-tool-use".into(),+ agent: Some("grok".into()),+ project: Some("must-not-exist".into()),+ project_src: Some("marker".into()),+ identity: Some("github.com/acme/api".into()),+ identity_src: Some("git_remote".into()),+ aliases: Some("[\"../foreign\"]".into()),+ drop_subagent: Some("1".into()),+ ..Default::default()+ };+ let body = serde_json::json!({+ "sessionId": "malformed-alias-session",+ "subagentType": "general-purpose",+ "toolName": "x"+ });++ let response = handle_hook(+ State(state.clone()),+ Query(malformed),+ None,+ None,+ None,+ HeaderMap::new(),+ Json(body),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::ACCEPTED);+ let projects = state+ .reader+ .list_projects_with_stats_for_workspace("default".into(), None)+ .await+ .unwrap();+ assert_eq!(+ projects+ .iter()+ .map(|project| project.project_name.as_str())+ .collect::<Vec<_>>(),+ ["scratch"]+ );+ assert_eq!(state.project_cache.lock().await.len(), 0);++ let response = handle_hook(+ State(state.clone()),+ Query(HookQuery {+ event: "pre-tool-use".into(),+ agent: Some("grok".into()),+ project: Some("legitimate-project".into()),+ drop_subagent: Some("1".into()),+ ..Default::default()+ }),+ None,+ None,+ None,+ HeaderMap::new(),+ Json(serde_json::json!({+ "sessionId": "valid-subagent-session",+ "subagentType": "general-purpose",+ "toolName": "x"+ })),+ )+ .await+ .into_response();+ assert_eq!(response.status(), StatusCode::ACCEPTED);+ let permit = state+ .ingest_semaphore+ .clone()+ .acquire_many_owned(DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT as u32)+ .await+ .unwrap();+ drop(permit);+ let projects = state+ .reader+ .list_projects_with_stats_for_workspace("default".into(), None)+ .await+ .unwrap();+ assert!(+ projects+ .iter()+ .any(|project| project.project_name == "legitimate-project")+ );+ assert_eq!(state.project_cache.lock().await.len(), 1);+ }+#[tokio::test]async fn handle_hook_batch_keeps_subagent_events_when_disabled() {let tmp = TempDir::new().unwrap();@@ -9380,11 +9895,11 @@ mod tests {String::new(),String::new(),ProjectStrategy::Basename.as_str().to_string(),- String::new(),+ ":::unspecified:write".to_string(),);assert!(cache.contains_key(&key),- "cache keyed by (cwd, ws_override, proj_override, project_strategy, identity)"+ "cache keyed by cwd, overrides, strategy, identity, aliases, provenance, and mode");}@@ -9727,6 +10242,9 @@ mod tests {Some("scratch"),ProjectStrategy::Basename,None,+ &ai_memory_core::repository_identity::MarkerAliases::default(),+ ProjectSource::Unspecified,+ true,);let mut cache = state.project_cache.lock().await;assert_eq!(cache.get(&cache_key), Some((cached_ws, cached_proj)));@@ -11972,6 +12490,7 @@ mod tests {cwd: Some(tmp.path().to_string_lossy().into_owned()),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -11980,6 +12499,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,}),Some(axum::Extension(ai_memory_core::ActorContext {issuer: Some("https://idp.example".into()),@@ -12588,6 +13108,7 @@ mod tests {cwd: Some(cwd.clone()),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: Some("1".into()),briefing_budget: None,@@ -12596,6 +13117,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};let state = Arc::new(state);let session_start = |viewer: Option<ai_memory_core::UserId>| {@@ -12675,6 +13197,7 @@ mod tests {cwd: Some(cwd.clone()),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -12683,6 +13206,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};let state = Arc::new(state);@@ -12781,6 +13305,7 @@ mod tests {cwd: Some(cwd),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -12789,6 +13314,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};let (status, body) = read_handoff_response(handle_handoff(@@ -12965,6 +13491,7 @@ mod tests {cwd: Some(cwd.to_string()),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -12973,6 +13500,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,}),None,None,@@ -13856,6 +14384,7 @@ mod tests {cwd: Some(cwd.into()),workspace: Some("acme".into()),project: None,+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -13864,6 +14393,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,},None,Vec::new(),@@ -13937,6 +14467,7 @@ mod tests {cwd: Some("/repo/api/src".into()),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -13945,6 +14476,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,},None,Vec::new(),@@ -14010,6 +14542,7 @@ mod tests {cwd: Some(cwd.clone()),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -14018,6 +14551,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};let empty_sid = "empty-native-session";let rendered = fetch_and_accept_handoff(&state, query(empty_sid), None, Vec::new(), None)@@ -14163,6 +14697,7 @@ mod tests {cwd: Some(cwd),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -14173,6 +14708,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};let rendered = fetch_and_accept_handoff(&state, query.clone(), None, Vec::new(), None).await@@ -14283,6 +14819,7 @@ mod tests {cwd: Some(cwd.into()),workspace: None,project: None,+ project_src: None,project_strategy: None,briefing: Some("true".into()),briefing_budget: None,@@ -14291,6 +14828,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};let named = ai_memory_core::ActorContext {@@ -14365,6 +14903,7 @@ mod tests {cwd: Some(cwd.into()),workspace: None,project: None,+ project_src: None,project_strategy: None,briefing: Some("true".into()),briefing_budget: None,@@ -14373,6 +14912,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};let rendered =@@ -14431,6 +14971,7 @@ mod tests {cwd: Some(cwd.into()),workspace: None,project: None,+ project_src: None,project_strategy: None,briefing: briefing.map(str::to_owned),briefing_budget: None,@@ -14439,6 +14980,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};// Non-truthy opt-in: no handoff pending, nothing to inject.@@ -14593,6 +15135,7 @@ mod tests {cwd: Some("/repo".into()),workspace: Some("default".into()),project: Some("scratch".into()),+ project_src: None,project_strategy: None,briefing: briefing.map(str::to_owned),briefing_budget: None,@@ -14601,6 +15144,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,};let rendered =@@ -14811,6 +15355,7 @@ mod tests {cwd: Some(cwd.into()),workspace: None,project: None,+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -14819,6 +15364,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,},None,Vec::new(),@@ -14943,7 +15489,7 @@ mod tests {String::new(),String::new(),strat.clone(),- String::new(),+ ":::unspecified:write".to_string(),)),"cache key must remain case-folded for #806 stickiness");@@ -14953,7 +15499,7 @@ mod tests {String::new(),String::new(),strat,- String::new(),+ ":::unspecified:write".to_string(),)),"cache key must not carry the original-case basename");@@ -17336,6 +17882,7 @@ mod tests {cwd: Some(cwd.into()),workspace: None,project: None,+ project_src: None,project_strategy: None,briefing: None,briefing_budget: None,@@ -17344,6 +17891,7 @@ mod tests {identity: None,identity_src: None,identity_style: None,+ aliases: None,}}diff --git a/crates/ai-memory-hooks/tests/suite/mod.rs b/crates/ai-memory-hooks/tests/suite/mod.rsindex c13e37e9..24cb3789 100644--- a/crates/ai-memory-hooks/tests/suite/mod.rs+++ b/crates/ai-memory-hooks/tests/suite/mod.rs@@ -3,5 +3,6 @@//! no extra binary; a new file must be declared below.mod powershell_home;+mod powershell_marker_aliases;mod powershell_server_routed;mod powershell_utf8;diff --git a/crates/ai-memory-hooks/tests/suite/powershell_marker_aliases.rs b/crates/ai-memory-hooks/tests/suite/powershell_marker_aliases.rsnew file mode 100644index 00000000..49e796ad--- /dev/null+++ b/crates/ai-memory-hooks/tests/suite/powershell_marker_aliases.rs@@ -0,0 +1,93 @@+#![cfg(windows)]++use std::path::{Path, PathBuf};+use std::process::Command;++fn repo_root() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .and_then(Path::parent)+ .expect("crate should live under crates/ai-memory-hooks")+ .to_path_buf()+}++#[test]+fn powershell_marker_aliases_are_bounded_and_forwarded_with_remote_identity() {+ let temp = tempfile::tempdir().unwrap();+ let repo = temp.path().join("Repo");+ std::fs::create_dir_all(&repo).unwrap();+ assert!(+ Command::new("git")+ .args(["init", "-q"])+ .current_dir(&repo)+ .status()+ .unwrap()+ .success()+ );+ assert!(+ Command::new("git")+ .args([+ "remote",+ "add",+ "origin",+ "[email protected]:Acme/API.git"+ ])+ .current_dir(&repo)+ .status()+ .unwrap()+ .success()+ );+ std::fs::write(+ repo.join(".ai-memory.toml"),+ "project = \"acme-api\"\naliases = [\" Former-Name \", \"legacy_name\", \"Former-Name\"]\n",+ )+ .unwrap();+ let nested = repo.join("nested");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::write(+ nested.join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secrets/**\"]\n",+ )+ .unwrap();+ let helper = repo_root()+ .join("hooks")+ .join("lib")+ .join("ai-memory-hook.ps1")+ .to_string_lossy()+ .replace('\'', "''");+ let cwd = nested.to_string_lossy().replace('\'', "''");+ let program =+ format!(". '{helper}'; [Console]::Out.Write((Get-AiMemoryMarkerQuery -Cwd '{cwd}'))");+ let output = Command::new(ai_memory_test_support::powershell_exe())+ .args([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-ExecutionPolicy",+ "Bypass",+ "-Command",+ &program,+ ])+ .env("HOME", temp.path())+ .env("USERPROFILE", temp.path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let query = String::from_utf8(output.stdout).unwrap();+ assert!(+ query.contains("&project=acme-api&project_src=marker"),+ "{query}"+ );+ assert!(+ query.contains("&identity=git.example.test%2Facme%2Fapi&identity_src=git_remote"),+ "{query}"+ );+ assert!(+ query.contains("&aliases=%5B%22Former-Name%22%2C%22legacy_name%22%5D"),+ "{query}"+ );+}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 2e83ae91..f4e0429a 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -63,10 +63,10 @@ pub use ops::{DeleteWorkspaceSummary, EmbedOutcome, EmbeddingWrite, EntityBackfillSummary,HookSessionAdmission, IdentityResolution, IngestObservationOutcome, LifecycleOnlyEndOutcome,MAX_PENDING_INBOX_MESSAGES, MoveSessionSummary, MoveSummary, ObservationPruneOutcome,- OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PageWindowBackfillSummary, PagesMode, PurgeMode,- PurgeSessionSummary, PurgeSummary, ReorgSummary, RepairSessionTimesSummary,- RepairedSessionTimes, SessionTimesCandidate, SessionTimesSkipReason, SkippedSessionTimes,- StaleAfterRepair, backfill_entity_index, backfill_page_windows,+ OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PageWindowBackfillSummary, PagesMode,+ ProjectAliasWriteResolution, PurgeMode, PurgeSessionSummary, PurgeSummary, ReorgSummary,+ RepairSessionTimesSummary, RepairedSessionTimes, SessionTimesCandidate, SessionTimesSkipReason,+ SkippedSessionTimes, StaleAfterRepair, backfill_entity_index, backfill_page_windows,backfill_page_windows_in_batches, purge_session, record_embed_failure,};pub use profile::{diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 4ac262ea..cbe2dca3 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -419,6 +419,15 @@ pub(crate) struct ProjectNameWriteResolution {pub authorization_error: Option<ai_memory_core::AuthzError>,}+/// Result of resolving transient marker aliases for a write.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectAliasWriteResolution {+ /// Existing project UUID.+ pub project_id: ai_memory_core::ProjectId,+ /// Previous name when canonical promotion committed.+ pub promoted_from: Option<String>,+}+#[allow(clippy::too_many_arguments)]pub(crate) fn resolve_project_name_for_write(conn: &mut Connection,@@ -503,6 +512,65 @@ pub(crate) fn resolve_project_name_for_write(})}+pub(crate) fn resolve_project_aliases_for_write(+ conn: &mut Connection,+ workspace_id: &ai_memory_core::WorkspaceId,+ canonical: &str,+ aliases: &ai_memory_core::repository_identity::MarkerAliases,+ repository: &ai_memory_core::repository_identity::RepositoryIdentity,+ principal: Option<&crate::ProjectPrincipal>,+ distinguishes_operators: bool,+) -> StoreResult<Option<ProjectAliasWriteResolution>> {+ let tx = conn.transaction()?;+ let Some(matched) = crate::project_coordinates::resolve_aliases(+ &tx,+ *workspace_id,+ canonical,+ aliases,+ repository,+ )?+ else {+ return Ok(None);+ };+ if let Some(principal) = principal {+ crate::project_authz::resolve_project_authz(+ &tx,+ *workspace_id,+ matched.id,+ principal,+ distinguishes_operators,+ )?+ .authorize(crate::ProjectAccess::Write)+ .map_err(|error| StoreError::Forbidden(error.message()))?;+ }+ let derived_canonical = ai_memory_core::repository_identity::path_style_name(repository)+ .as_deref()+ == Some(canonical);+ let promote_to = derived_canonical+ .then(|| crate::project_coordinates::promotion_target(&matched, canonical))+ .flatten()+ .map(str::to_owned);+ let promoted_from = if let Some(canonical) = promote_to {+ rename_project_in_tx(+ &tx,+ workspace_id,+ &matched.id,+ Some(&matched.current_name),+ &canonical,+ principal.and_then(|principal| principal.user_id),+ "promote_project_name",+ )?;+ Some(matched.current_name)+ } else {+ None+ };+ tx.commit()?;+ Ok(Some(ProjectAliasWriteResolution {+ project_id: matched.id,+ promoted_from,+ }))+}+fn insert_project_with_identityless_name(tx: &rusqlite::Transaction<'_>,workspace_id: &ai_memory_core::WorkspaceId,diff --git a/crates/ai-memory-store/src/project_coordinates.rs b/crates/ai-memory-store/src/project_coordinates.rsindex 6947f4bd..2c5938b0 100644--- a/crates/ai-memory-store/src/project_coordinates.rs+++ b/crates/ai-memory-store/src/project_coordinates.rs@@ -4,7 +4,7 @@ use ai_memory_core::repository_identity::{IdentitySource, RepositoryIdentity, legacy_basename_name, path_style_name,};use ai_memory_core::{ProjectId, WorkspaceId};-use rusqlite::{Connection, params};+use rusqlite::{Connection, OptionalExtension, params};use crate::{StoreError, StoreResult};@@ -161,6 +161,86 @@ pub(crate) fn resolve(}}+fn row_to_match(row: &rusqlite::Row<'_>) -> rusqlite::Result<ProjectCoordinateMatch> {+ Ok(ProjectCoordinateMatch {+ id: ProjectId::from_slice(&row.get::<_, Vec<u8>>(0)?).map_err(|error| {+ rusqlite::Error::FromSqlConversionFailure(+ 0,+ rusqlite::types::Type::Blob,+ Box::new(error),+ )+ })?,+ current_name: row.get(1)?,+ identity: row.get(2)?,+ identity_source: row.get(3)?,+ canonical_name: row.get(4)?,+ legacy_name: row.get(5)?,+ provenance: MatchProvenance {+ exact: true,+ ..MatchProvenance::default()+ },+ })+}++pub(crate) fn resolve_aliases(+ conn: &Connection,+ workspace_id: WorkspaceId,+ canonical: &str,+ aliases: &ai_memory_core::repository_identity::MarkerAliases,+ repository: &RepositoryIdentity,+) -> StoreResult<Option<ProjectCoordinateMatch>> {+ if repository.source != IdentitySource::GitRemote || aliases.is_empty() {+ return Err(StoreError::ProjectNameAmbiguous(canonical.to_owned()));+ }+ let canonical_match = conn+ .query_row(+ "SELECT id, name, NULLIF(identity, ''), NULLIF(identity_source, ''), \+ NULLIF(canonical_name, ''), NULLIF(legacy_name, '') FROM projects \+ INDEXED BY sqlite_autoindex_projects_2 WHERE workspace_id = ?1 AND name = ?2",+ params![workspace_id.as_bytes(), canonical],+ row_to_match,+ )+ .optional()?;+ if let Some(canonical_match) = canonical_match {+ if canonical_match.identity.as_deref() == Some(repository.identity.as_str())+ && canonical_match.identity_source.as_deref()+ == Some(IdentitySource::GitRemote.as_str())+ {+ return Ok(Some(canonical_match));+ }+ return Err(StoreError::ProjectNameAmbiguous(canonical.to_owned()));+ }+ let mut candidates = Vec::new();+ for alias in aliases.as_slice() {+ let local = conn+ .query_row(+ "SELECT id, name, NULLIF(identity, ''), NULLIF(identity_source, ''), \+ NULLIF(canonical_name, ''), NULLIF(legacy_name, '') FROM projects \+ INDEXED BY sqlite_autoindex_projects_2 WHERE workspace_id = ?1 AND name = ?2",+ params![workspace_id.as_bytes(), alias],+ row_to_match,+ )+ .optional()?;+ if let Some(candidate) = local {+ candidates.push(candidate);+ }+ }+ candidates.sort_by_key(|candidate| candidate.id.to_string());+ candidates.dedup_by_key(|candidate| candidate.id);+ if candidates.len() > 1 {+ return Err(StoreError::ProjectNameAmbiguous(canonical.to_owned()));+ }+ let Some(candidate) = candidates.pop() else {+ return Ok(None);+ };+ if candidate.identity.as_deref() != Some(repository.identity.as_str())+ || candidate.identity_source.as_deref() != Some(IdentitySource::GitRemote.as_str())+ {+ return Err(StoreError::ProjectNameAmbiguous(canonical.to_owned()));+ }+ Ok(Some(candidate))+}+pub(crate) fn promotion_target<'a>(candidate: &'a ProjectCoordinateMatch,requested: &str,diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 2b141b40..cce96751 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -9259,6 +9259,28 @@ impl ReaderPool {.await}+ /// Resolve a local marker's former names inside one workspace, requiring+ /// the selected row to carry the checkout's full git-remote identity.+ pub async fn resolve_existing_project_aliases(+ &self,+ workspace_id: WorkspaceId,+ canonical: String,+ aliases: ai_memory_core::repository_identity::MarkerAliases,+ repository: ai_memory_core::repository_identity::RepositoryIdentity,+ ) -> StoreResult<Option<ProjectId>> {+ self.with_conn(move |conn| {+ crate::project_coordinates::resolve_aliases(+ conn,+ workspace_id,+ &canonical,+ &aliases,+ &repository,+ )+ .map(|matched| matched.map(|matched| matched.id))+ })+ .await+ }+/// Find the existing project whose `repo_path` is the longest/// prefix of `cwd`, if any. Used by the hook router before/// auto-creating a new project from `basename(cwd)` so an eventdiff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex a5369124..a46ef2cf 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -117,6 +117,15 @@ pub(crate) enum WriteCmd {promote: bool,reply: oneshot::Sender<StoreResult<ops::ProjectNameWriteResolution>>,},+ ResolveProjectAliasesForWrite {+ workspace_id: WorkspaceId,+ canonical: String,+ aliases: ai_memory_core::repository_identity::MarkerAliases,+ repository: ai_memory_core::repository_identity::RepositoryIdentity,+ principal: Option<crate::ProjectPrincipal>,+ distinguishes_operators: bool,+ reply: oneshot::Sender<StoreResult<Option<ops::ProjectAliasWriteResolution>>>,+ },EnsureProjectWorkspace {workspace_id: WorkspaceId,project_id: ProjectId,@@ -1081,6 +1090,31 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// 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(+ &self,+ workspace_id: WorkspaceId,+ canonical: impl Into<String>,+ aliases: ai_memory_core::repository_identity::MarkerAliases,+ repository: ai_memory_core::repository_identity::RepositoryIdentity,+ principal: Option<crate::ProjectPrincipal>,+ distinguishes_operators: bool,+ ) -> StoreResult<Option<ops::ProjectAliasWriteResolution>> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::ResolveProjectAliasesForWrite {+ workspace_id,+ canonical: canonical.into(),+ aliases,+ repository,+ principal,+ distinguishes_operators,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+pub(crate) async fn resolve_project_name_for_write(&self,workspace_id: WorkspaceId,@@ -3543,6 +3577,26 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {);send_or_warn(reply, result, "resolve_project_name_for_write");}+ WriteCmd::ResolveProjectAliasesForWrite {+ workspace_id,+ canonical,+ aliases,+ repository,+ principal,+ distinguishes_operators,+ reply,+ } => {+ let result = ops::resolve_project_aliases_for_write(+ &mut conn,+ &workspace_id,+ &canonical,+ &aliases,+ &repository,+ principal.as_ref(),+ distinguishes_operators,+ );+ send_or_warn(reply, result, "resolve_project_aliases_for_write");+ }WriteCmd::EnsureProjectWorkspace {workspace_id,project_id,diff --git a/crates/ai-memory-store/tests/suite/identity_resolution.rs b/crates/ai-memory-store/tests/suite/identity_resolution.rsindex a0792a20..1b62748b 100644--- a/crates/ai-memory-store/tests/suite/identity_resolution.rs+++ b/crates/ai-memory-store/tests/suite/identity_resolution.rs@@ -8,7 +8,9 @@//! 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, IdentityStyle, RepositoryIdentity};+use ai_memory_core::repository_identity::{+ IdentitySource, IdentityStyle, MarkerAliases, RepositoryIdentity,+};use ai_memory_core::{AgentKind, NewHandoff, NewPage, NewSession, NewUser, OwnerFilter, PagePath, ProjectId,SessionId, Tier, UserId, WorkspaceId,@@ -537,6 +539,203 @@ fn preserved_page(ws: WorkspaceId, project: ProjectId) -> NewPage {}}+#[tokio::test]+async fn marker_aliases_require_same_remote_identity_and_preserve_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, "former-name", None)+ .await+ .0;+ store+ .writer+ .set_access_mode(project, AccessMode::Restricted)+ .await+ .unwrap();+ let writer = user(&store, "alias-writer", 7).await;+ store+ .writer+ .grant_memory(writer, project, GrantLevel::Write, None)+ .await+ .unwrap();+ let aliases = MarkerAliases::new(["former-name"]).unwrap();++ let read = store+ .reader+ .resolve_existing_project_aliases(+ ws,+ "acme-api".into(),+ aliases.clone(),+ repository.clone(),+ )+ .await+ .unwrap();+ assert_eq!(read, Some(project));+ assert_eq!(+ row(&store, project).0,+ "former-name",+ "read does not rename"+ );++ let outsider = user(&store, "alias-outsider", 8).await;+ let refused = store+ .writer+ .resolve_project_aliases_for_write(+ ws,+ "acme-api",+ aliases.clone(),+ repository.clone(),+ Some(ProjectPrincipal::user(outsider)),+ true,+ )+ .await;+ assert!(matches!(+ refused,+ Err(ai_memory_store::StoreError::Forbidden(_))+ ));+ assert_eq!(row(&store, project).0, "former-name");++ let promoted = store+ .writer+ .resolve_project_aliases_for_write(+ ws,+ "acme-api",+ aliases,+ repository,+ Some(ProjectPrincipal::user(writer)),+ true,+ )+ .await+ .unwrap()+ .unwrap();+ assert_eq!(promoted.project_id, project);+ assert_eq!(promoted.promoted_from.as_deref(), Some("former-name"));+ assert_eq!(row(&store, project).0, "acme-api");+}++#[tokio::test]+async fn marker_aliases_cannot_promote_to_an_arbitrary_marker_project() {+ 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, "former-name", None)+ .await+ .0;+ let aliases = MarkerAliases::new(["former-name"]).unwrap();++ let resolved = store+ .writer+ .resolve_project_aliases_for_write(+ ws,+ "attacker-chosen-name",+ aliases,+ repository,+ None,+ false,+ )+ .await+ .unwrap()+ .unwrap();++ assert_eq!(resolved.project_id, project);+ assert_eq!(resolved.promoted_from, None);+ assert_eq!(row(&store, project).0, "former-name");+}++#[tokio::test]+async fn hostile_ambiguous_and_cross_workspace_marker_aliases_fail_closed() {+ 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 legitimate = resolve(&store, ws, &repository, "former-name", None)+ .await+ .0;+ let hostile = resolve(+ &store,+ ws,+ &remote("gitlab.com/other/private"),+ "restricted",+ None,+ )+ .await+ .0;+ store+ .writer+ .set_access_mode(hostile, AccessMode::Restricted)+ .await+ .unwrap();+ let open_hostile = resolve(+ &store,+ ws,+ &remote("bitbucket.org/other/public"),+ "open-project",+ None,+ )+ .await+ .0;+ assert_ne!(open_hostile, legitimate);++ assert_eq!(+ store+ .reader+ .resolve_existing_project_aliases(+ ws,+ "acme-api".into(),+ MarkerAliases::new(["former-name"]).unwrap(),+ repository.clone(),+ )+ .await+ .unwrap(),+ Some(legitimate)+ );+ for hostile_name in ["restricted", "open-project"] {+ assert!(+ store+ .reader+ .resolve_existing_project_aliases(+ ws,+ "future-api".into(),+ MarkerAliases::new([hostile_name]).unwrap(),+ repository.clone(),+ )+ .await+ .is_err(),+ "{hostile_name}"+ );+ }+ assert!(+ store+ .reader+ .resolve_existing_project_aliases(+ ws,+ "future-api".into(),+ MarkerAliases::new(["former-name", "restricted"]).unwrap(),+ repository.clone(),+ )+ .await+ .is_err()+ );++ let other_ws = store.writer.get_or_create_workspace("other").await.unwrap();+ let _foreign = resolve(&store, other_ws, &repository, "foreign-only", None).await;+ assert_eq!(+ store+ .reader+ .resolve_existing_project_aliases(+ ws,+ "missing-canonical".into(),+ MarkerAliases::new(["foreign-only"]).unwrap(),+ remote("github.com/acme/else"),+ )+ .await+ .unwrap(),+ None+ );+}+#[tokio::test]async fn coordinate_diagnostic_classifies_exact_canonical_legacy_and_missing_without_mutation() {let tmp = tempfile::TempDir::new().unwrap();diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 49edfaa8..b76d5c3c 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -55,9 +55,16 @@ from hook paths.Agent hot paths never block on the network; saturated servers return HTTP429 instead of queueing unbounded work.For supported native commands and generated OpenCode/OMP/Pi/OpenClaw- integrations, the nearest-marker capture policy runs first: a dropped- recognized file-tool event never enters spool, queue, transport, logs, or- storage. See [Capture exclusions](marker-file.md#capture-exclusions).+ integrations, the nearest-marker capture policy runs first: a dropped+ recognized file-tool event never enters spool, queue, transport, logs, or+ storage. The separate nearest settings marker may also forward a bounded+ JSON-array `aliases` query value on both capture and SessionStart handoff+ lookup. The router accepts it only with marker provenance and the checkout's+ normalized hostful git-remote identity, and resolves names inside the+ selected workspace; the cache key includes aliases, provenance, and+ read/write mode. See+ [the marker reference](marker-file.md).+2. Server's hook router sanitises the payload (the only path fromuntrusted text into the store), assigns an [`ObservationKind`], andenqueues a `WriteCmd` to the writer actor. For native keyed events, the@@ -387,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. 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. 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. 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/design-per-project-authz.md b/docs/design-per-project-authz.mdindex 4db25981..541a87e2 100644--- a/docs/design-per-project-authz.md+++ b/docs/design-per-project-authz.md@@ -283,7 +283,15 @@ project. #1033 makes a remote-derived key the default name, landing in steps onambiguous result may carry the preferred identity-backed candidate UUID andcurrent name for operator context; it still represents no unique resolutionand is never rename-eligible.-5. Marker `aliases`, then 6. identity- or path-keyed blocks in `~/.ai-memory.toml`.+5. **Local marker aliases (landed).** `aliases = ["former-name"]` is bounded,+ normalized, deduplicated and forwarded identically by native, POSIX shell,+ PowerShell and generated TypeScript clients on capture and handoff requests.+ The marker's `project` remains canonical. Alias lookup stays within its+ selected workspace and requires the checkout's full hostful git-remote+ identity to match the stored row; reads do not rename, while capture may use+ only the Phase 1 write-authorized canonical promotion. Alias lists are+ transient routing hints, not persisted rows, and stay supported after v3.+6. Identity- or path-keyed blocks in `~/.ai-memory.toml` remain a later phase.Paths stay lexically normalised throughout; nothing canonicalises.diff --git a/docs/marker-file.md b/docs/marker-file.mdindex 840c364f..54aa2699 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -61,6 +61,10 @@ handoff lookup also sends `cwd` when no marker exists so the default`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.+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+hostful git-remote identity.## Schema@@ -95,6 +99,17 @@ identity = "acme/platform"# See "Naming new projects by repository path" below.identity_style = "path"+# Optional. Former names for this same repository in this workspace. At most+# 16 entries, each at most 128 UTF-8 bytes and matching+# ^[A-Za-z0-9][A-Za-z0-9._-]*$. Whitespace is trimmed and duplicates keep their+# first position. A hostful upstream/origin identity must match the stored+# project's identity; otherwise the aliases are refused. Reads use the+# existing UUID without renaming. Hook capture may rename that UUID to the+# canonical `project` above only after write authorization. Aliases are local+# routing hints, are not persisted, never select another workspace, and remain+# supported after the v3 dual-key compatibility window.+aliases = ["former-name", "old-worktree-name"]+# 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@@ -167,6 +182,20 @@ Anything else is rejected at `get_or_create_workspace` / `_project`time, surfacing as a hook warning. The shell helper URL-encodesdefensively but the server's regex is the source of truth.+`aliases` is all-or-nothing and intentionally uses a portable subset shared by+native Rust, POSIX shell, PowerShell, and generated TypeScript: exactly one+root-level declaration on one line, containing a JSON-compatible array of+unescaped strings. Duplicate declarations, table placement, multiline arrays,+comments/trailing junk, trailing commas, path-like/control-bearing values,+non-strings, oversized values, and over-count lists make hook and handoff+routing fail closed without echoing their contents. An absent or empty list is+inert. The canonical `project` still wins when it already resolves. Otherwise+every local alias hit must deduplicate to one project carrying the checkout's+exact hostful remote identity; a different identity or more than one project+fails closed. Alias lookup never searches another workspace, and capture may+rename only when `project` equals the canonical path-style name derived from+that exact remote identity.+`project_strategy` accepts `repo-root` (or `repo_root`) only. Unknownvalues are ignored and behave like the default `basename(cwd)` strategy.@@ -643,8 +672,10 @@ own name.a different repository — typically the same path on another forge(`gitlab.com/acme/api` after `github.com/acme/api`) — the newcomer fallsback 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.+- `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 usethe canonical path name (`acme-api`) or the v2 basename (`api`) while it isunambiguous. A hostless key shared by multiple forges fails closed.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 2e8def0c..c7bd85e6 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -81,6 +81,7 @@ boundary not yet built.| 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_identity_discovery_is_alias_gated` preserves no-alias identity behavior | 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 || 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) || 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 |diff --git a/hooks/_lib.sh b/hooks/_lib.shindex 7a35b269..1c88a9d5 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -104,6 +104,7 @@ ai_memory_marker_declares_settings() {for key in workspace project project_strategy drop_subagent_captures identity identity_style; do[ -n "$(ai_memory_parse_toml_key "$file" "$key")" ] && return 0done+ LC_ALL=C grep -Eq '^[[:space:]]*aliases[[:space:]]*=' "$file" && return 0ai_memory_marker_declares_server "$file" && return 0for key in default_global inject_on_session_start max_chars contribute consume; do[ -n "$(ai_memory_parse_toml_flag "$file" "$key")" ] && return 0@@ -430,6 +431,70 @@ ai_memory_identity_style_qs() {return 0}+ai_memory_aliases_json() {+ [ -f "$1" ] || return 0+ _ai_alias_body=$(LC_ALL=C awk '+ BEGIN { table = 0; count = 0; bad = 0 }+ {+ line = $0+ sub(/\r$/, "", line)+ trimmed = line+ sub(/^[ \t]*/, "", trimmed)+ if (trimmed ~ /^\[/) table = 1+ if (trimmed ~ /^aliases[ \t]*=/) {+ count+++ if (table || count > 1 || trimmed !~ /^aliases[ \t]*=[ \t]*\[[^]]*\][ \t]*$/) {+ bad = 1+ } else {+ sub(/^aliases[ \t]*=[ \t]*\[/, "", trimmed)+ sub(/\][ \t]*$/, "", trimmed)+ body = trimmed+ }+ }+ }+ END {+ if (bad) print "invalid"+ else if (count == 1) print body+ }+ ' "$1")+ [ "$_ai_alias_body" = "invalid" ] && { printf 'invalid'; return 0; }+ [ -n "$_ai_alias_body" ] || return 0+ _ai_alias_trimmed=$(printf '%s' "$_ai_alias_body" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')+ [ -n "$_ai_alias_trimmed" ] || return 0+ case "$_ai_alias_trimmed" in *,) printf 'invalid'; return 0 ;; esac+ _ai_alias_out=""+ _ai_alias_count=0+ _ai_alias_old_ifs=$IFS+ IFS=,+ for _ai_alias_raw in $_ai_alias_body; do+ IFS=$_ai_alias_old_ifs+ _ai_alias_count=$((_ai_alias_count + 1))+ [ "$_ai_alias_count" -le 16 ] || { printf 'invalid'; return 0; }+ case "$_ai_alias_raw" in *\\*) printf 'invalid'; return 0 ;; esac+ _ai_alias=$(printf '%s' "$_ai_alias_raw" | sed -n -E 's/^[[:space:]]*"([^"]*)"[[:space:]]*$/\1/p' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')+ case "$_ai_alias" in+ ""|*[!A-Za-z0-9._-]*) printf 'invalid'; return 0 ;;+ esac+ [ "${#_ai_alias}" -le 128 ] || { printf 'invalid'; return 0; }+ case "$_ai_alias" in [A-Za-z0-9]*) ;; *) printf 'invalid'; return 0 ;; esac+ case "|$_ai_alias_out|" in *"|$_ai_alias|"*) ;; *)+ _ai_alias_out="${_ai_alias_out}|${_ai_alias}"+ esac+ IFS=,+ done+ IFS=$_ai_alias_old_ifs+ _ai_alias_json="["+ _ai_alias_sep=""+ _ai_alias_rest=${_ai_alias_out#|}+ IFS='|'+ for _ai_alias in $_ai_alias_rest; do+ _ai_alias_json="${_ai_alias_json}${_ai_alias_sep}\"${_ai_alias}\""+ _ai_alias_sep=,+ done+ IFS=$_ai_alias_old_ifs+ printf '%s]' "$_ai_alias_json"+}+# Print `&identity=<v>&identity_src=<rung>` for the checkout at "$1", or# nothing. "$2" is the marker's `identity`, "$3" its declared `project`, "$4"# its `identity_style`, forwarded only with a remote identity.@@ -437,14 +502,14 @@ ai_memory_identity_style_qs() {# 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_style="$4"+ _ai_id_cwd="$1"; _ai_id_explicit="$2"; _ai_id_project="$3"; _ai_id_style="$4"; _ai_id_aliases="$5"_ai_id_explicit=$(printf '%s' "$_ai_id_explicit" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')- if [ -n "$_ai_id_explicit" ]; then+ if [ -z "$_ai_id_aliases" ] && [ -n "$_ai_id_explicit" ]; then_ai_id_value=$(printf '%s' "$_ai_id_explicit" | tr '[:upper:]' '[:lower:]')printf '&identity=%s&identity_src=explicit' "$(ai_memory_url_encode "$_ai_id_value")"return 0fi- [ -n "$(printf '%s' "$_ai_id_project" | tr -d '[:space:]')" ] && return 0+ [ -z "$_ai_id_aliases" ] && [ -n "$(printf '%s' "$_ai_id_project" | tr -d '[:space:]')" ] && return 0[ -n "$_ai_id_cwd" ] || return 0command -v git >/dev/null 2>&1 || return 0for _ai_id_remote in upstream origin; do@@ -485,6 +550,7 @@ ai_memory_marker_qs() {isty=""pcon=""pcons=""+ aliases=""# 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.@@ -496,6 +562,7 @@ ai_memory_marker_qs() {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)+ aliases=$(ai_memory_aliases_json "$marker")# `[profile] contribute` / `consume`, quoted or bare, always sent# explicitly once a marker resolved (0 when falsy, else 1): removing# the key re-enables; no marker sends nothing and the server keeps@@ -506,7 +573,7 @@ ai_memory_marker_qs() {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" "$isty")+ 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.@@ -532,6 +599,14 @@ ai_memory_marker_qs() {[ -n "$ps" ] && qs="${qs}&project_src=$(ai_memory_url_encode "$ps")"[ -n "$st" ] && qs="${qs}&project_strategy=$(ai_memory_url_encode "$st")"qs="${qs}${iq}"+ if [ -n "$aliases" ]; then+ case "$iq" in *'identity_src=git_remote'*)+ [ -n "$pr" ] || aliases=invalid+ ;;+ *) aliases=invalid ;;+ esac+ qs="${qs}&aliases=$(ai_memory_url_encode "$aliases")"+ fi# Per-project drop_subagent_captures opt-in: forward to the server, which# interprets truthiness (1/true/...) and scopes the drop to this project.[ -n "$ds" ] && qs="${qs}&drop_subagent=$(ai_memory_url_encode "$ds")"diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index c8d58775..128b03dc 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -52,6 +52,25 @@ function Get-AiMemoryUserHome {return $trimmed}+function Test-AiMemoryMarkerDeclaresSettings {+ param([string] $File)+ if (-not (Test-Path $File -PathType Leaf)) { return $false }+ try {+ $text = [IO.File]::ReadAllText($File)+ } catch {+ return $false+ }+ foreach ($key in @("workspace", "project", "project_strategy", "drop_subagent_captures", "identity", "identity_style")) {+ if ([regex]::IsMatch($text, "(?m)^\s*$key\s*=")) { return $true }+ }+ if ([regex]::IsMatch($text, '(?m)^\s*aliases\s*=')) { return $true }+ if ([regex]::IsMatch($text, '(?m)^[\s]*server\s*=')) { return $true }+ foreach ($key in @("default_global", "inject_on_session_start", "max_chars", "contribute", "consume")) {+ if ([regex]::IsMatch($text, "(?m)^\s*$key\s*=")) { return $true }+ }+ return $false+}+function Get-AiMemoryMarkerToml {param([string] $Cwd)if (-not $Cwd) { return $null }@@ -82,7 +101,7 @@ function Get-AiMemoryMarkerToml {}while ($dir -and (Test-Path $dir)) {$candidate = Join-Path $dir ".ai-memory.toml"- if (Test-Path $candidate -PathType Leaf) { return $candidate }+ if ((Test-Path $candidate -PathType Leaf) -and (Test-AiMemoryMarkerDeclaresSettings -File $candidate)) { return $candidate }if ($boundary -and $dir -eq $boundary) { return $null }$parent = Split-Path $dir -Parentif (-not $parent -or $parent -eq $dir) { return $null }@@ -141,6 +160,46 @@ function Get-AiMemoryTomlKey {# `[briefing] inject_on_session_start = true` work quoted or not. Parity# with `parse_toml_flag` in hook_capture.rs: line-based, first match wins,# trailing `# comment` stripped.+function Get-AiMemoryTomlAliases {+ param([string] $File)+ if (-not (Test-Path $File -PathType Leaf)) { return $null }+ try {+ $text = [IO.File]::ReadAllText($File)+ $lines = $text -split "`r?`n"+ $inTable = $false+ $matches = [Collections.Generic.List[string]]::new()+ foreach ($line in $lines) {+ $trimmed = $line.Trim()+ if ($trimmed.StartsWith("[")) { $inTable = $true }+ if ($trimmed -match '^aliases\s*=') {+ if ($inTable) { return "invalid" }+ $matches.Add($trimmed)+ }+ }+ if ($matches.Count -eq 0) { return $null }+ if ($matches.Count -ne 1) { return "invalid" }+ $match = [regex]::Match($matches[0], '^aliases\s*=\s*\[([^\]]*)\]\s*$')+ if (-not $match.Success) { return "invalid" }+ $aliases = [Collections.Generic.List[string]]::new()+ if (-not $match.Groups[1].Value.Trim()) { return $null }+ $parts = $match.Groups[1].Value.Split(',')+ if ($parts.Count -gt 16) { return "invalid" }+ foreach ($part in $parts) {+ if ($part.Contains("\")) { return "invalid" }+ $item = [regex]::Match($part, '^\s*"([^"]*)"\s*$')+ if (-not $item.Success) { return "invalid" }+ $value = $item.Groups[1].Value.Trim()+ if (-not $value -or $value.Length -gt 128 -or $value -cnotmatch '^[A-Za-z0-9][A-Za-z0-9._-]*$') { return "invalid" }+ if (-not $aliases.Contains($value)) {+ $aliases.Add($value)+ }+ }+ return [string](ConvertTo-Json -InputObject @($aliases) -Compress)+ } catch {+ return "invalid"+ }+}+function Get-AiMemoryTomlFlag {param([string] $File, [string] $Key)if (-not (Test-Path $File -PathType Leaf)) { return $null }@@ -301,12 +360,12 @@ function Get-AiMemoryIdentityStyleQuery {# $Style (the marker's `identity_style`) is forwarded only with a remote# identity.function Get-AiMemoryIdentityQuery {- param([string] $Cwd, [string] $Explicit, [string] $Project, [string] $Style)- if ($Explicit -and $Explicit.Trim()) {+ param([string] $Cwd, [string] $Explicit, [string] $Project, [string] $Style, [string] $Aliases)+ if (-not $Aliases -and $Explicit -and $Explicit.Trim()) {$value = $Explicit.Trim().ToLowerInvariant()return "&identity=$([uri]::EscapeDataString($value))&identity_src=explicit"}- if ($Project -and $Project.Trim()) { return "" }+ if (-not $Aliases -and $Project -and $Project.Trim()) { return "" }if (-not $Cwd) { return "" }if (-not (Get-Command git -ErrorAction SilentlyContinue)) { return "" }foreach ($name in @("upstream", "origin")) {@@ -336,6 +395,7 @@ function Get-AiMemoryMarkerQuery {$identityStyle = $null$profileContribute = $null$profileConsume = $null+ $aliases = $null$marker = Get-AiMemoryMarkerToml -Cwd $Cwdif ($marker) {$ws = Get-AiMemoryTomlKey -File $marker -Key "workspace"@@ -344,6 +404,7 @@ function Get-AiMemoryMarkerQuery {$dropSubagent = Get-AiMemoryTomlKey -File $marker -Key "drop_subagent_captures"$explicitIdentity = Get-AiMemoryTomlKey -File $marker -Key "identity"$identityStyle = Get-AiMemoryTomlKey -File $marker -Key "identity_style"+ $aliases = Get-AiMemoryTomlAliases -File $marker# `[profile] contribute` / `consume`, quoted or bare; the server# decides truthiness and keeps both on unless explicitly falsy.# Always explicit once a marker resolved (0 when falsy, else 1): removing@@ -355,7 +416,7 @@ function Get-AiMemoryMarkerQuery {}# 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 -Style $identityStyle+ $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.@@ -373,6 +434,10 @@ function Get-AiMemoryMarkerQuery {if ($projSrc) { $qs += "&project_src=$([uri]::EscapeDataString($projSrc))" }if ($strategy) { $qs += "&project_strategy=$([uri]::EscapeDataString($strategy))" }$qs += $identityQuery+ if ($aliases) {+ if (-not $proj -or -not $identityQuery.Contains("identity_src=git_remote")) { $aliases = "invalid" }+ $qs += "&aliases=$([uri]::EscapeDataString($aliases))"+ }# Per-project drop_subagent_captures opt-in: forward to the server, which# interprets truthiness (1/true/...) and scopes the drop to this project.if ($dropSubagent) { $qs += "&drop_subagent=$([uri]::EscapeDataString($dropSubagent))" }diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 195d643b..81e38ae8 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -253,6 +253,15 @@ assert_eq "closer marker wins" "&cwd=$(ai_memory_url_encode "$TMP/a/b/c")&workspQS3=$(ai_memory_marker_qs "$TMP/nonexistent")assert_eq "no marker -> cwd only" "&cwd=$(ai_memory_url_encode "$TMP/nonexistent")" "$QS3"+mkdir -p "$TMP/aliases"+git -C "$TMP/aliases" init -q+git -C "$TMP/aliases" remote add origin [email protected]:acme/api.git+printf 'project = "acme-api"\naliases = [" former-name ", "legacy_name", "former-name"]\n' >"$TMP/aliases/.ai-memory.toml"+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)"+# --- capture-only marker transparency (#668) ---------------------------# A nested marker whose only content is [capture] must not shadow an outer# marker's workspace/project: ai_memory_marker_qs skips it and forwards the