Skip to content

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

Rust

feat(identity): resolve the identity in every hook client (#708)

luisfnicolaua0f43ead5d01
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 7ffed060..98ce8413 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -260,12 +260,14 @@ fn marker_query_suffix_impl(
let (mut workspace, mut project, mut strategy, mut drop_subagent, mut default_global) =
(None, None, None, None, None);
let (mut briefing, mut briefing_budget) = (None, None);
+ let mut explicit_identity = None;
// 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/briefing/etc.
if let Some(marker) = find_settings_marker(cwd) {
workspace = parse_toml_key(&marker, "workspace");
project = parse_toml_key(&marker, "project");
+ explicit_identity = parse_toml_key(&marker, "identity");
strategy = parse_toml_key(&marker, "project_strategy");
drop_subagent = parse_toml_key(&marker, "drop_subagent_captures");
// `[recall] default_global = true` (or top-level; quoted or bare) —
@@ -281,6 +283,10 @@ fn marker_query_suffix_impl(
// tell a deliberate marker rescope from a host-derived repo-root name.
// Only the latter may yield to session-sticky attribution (#394).
let mut project_src = project.as_ref().map(|_| "marker");
+ // Resolved before repo-root can fill `project` below: a repo-root name is
+ // an inference, while the chain's `manifest` rung means a name somebody
+ // wrote in the marker.
+ let identity = repository_identity(cwd, explicit_identity.as_deref(), project.as_deref());
if strategy.is_none() {
strategy = default_strategy.map(str::to_owned);
}
@@ -300,6 +306,13 @@ fn marker_query_suffix_impl(
if let Some(val) = strategy {
qs.push_str(&format!("&project_strategy={}", url_encode(&val)));
}
+ if let Some(identity) = identity {
+ qs.push_str(&format!(
+ "&identity={}&identity_src={}",
+ url_encode(&identity.identity),
+ identity.source.as_str()
+ ));
+ }
// 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`/…).
@@ -329,6 +342,38 @@ fn marker_query_suffix_impl(
qs
}
+/// The repository identity to send with this checkout's events (#708), or
+/// `None` to let the server route by project name as it always has.
+///
+/// Only the rungs that route by identity are sent: an explicit `identity`
+/// from the marker, or — when the marker declares no `project` — the
+/// `upstream`/`origin` remote. A declared `project` outranks the remote and
+/// routes by name, so git is not consulted at all when one is present; that
+/// also keeps the lookup off the hot path for every repository that declares
+/// itself. The remote is normalised here, so credentials embedded in its URL
+/// never leave the machine.
+fn repository_identity(
+ cwd: &str,
+ explicit_identity: Option<&str>,
+ declared_project: Option<&str>,
+) -> Option<ai_memory_core::repository_identity::RepositoryIdentity> {
+ use ai_memory_core::repository_identity::{IdentityInputs, resolve};
+ let declared = |value: Option<&str>| value.is_some_and(|v| !v.trim().is_empty());
+ let (upstream, origin) = if declared(explicit_identity) || declared(declared_project) {
+ (None, None)
+ } else {
+ ai_memory_consolidate::read_identity_remotes(std::path::Path::new(cwd))
+ };
+ resolve(&IdentityInputs {
+ explicit_identity,
+ manifest_name: declared_project,
+ upstream_remote: upstream.as_deref(),
+ origin_remote: origin.as_deref(),
+ folder_name: None,
+ })
+ .filter(|identity| identity.source.routes_by_identity())
+}
+
/// Build a reqwest client for the hook's one-shot requests. `no_proxy`
/// skips Windows proxy auto-detection (registry / WinINET lookups), which
/// is pure overhead for a loopback/LAN POST. Built once per invocation and
@@ -852,6 +897,105 @@ mod tests {
);
}
+ /// A throwaway repository with the given remotes, or `None` when there is
+ /// no `git` binary to build one with. The host is not a real forge, so a
+ /// developer's global `url.<base>.insteadOf` rules cannot rewrite it.
+ fn repo_with_remotes(remotes: &[(&str, &str)]) -> Option<tempfile::TempDir> {
+ let git = |args: &[&str], dir: &std::path::Path| {
+ std::process::Command::new("git")
+ .arg("-C")
+ .arg(dir)
+ .args(args)
+ .status()
+ .ok()
+ .filter(std::process::ExitStatus::success)
+ };
+ let tmp = tempfile::TempDir::new().unwrap();
+ git(&["init", "-q"], tmp.path())?;
+ for (name, url) in remotes {
+ git(&["remote", "add", name, url], tmp.path())?;
+ }
+ Some(tmp)
+ }
+
+ /// An undeclared checkout sends the identity of its remote — `upstream`
+ /// over `origin` — normalised on this side, so the credentials in the URL
+ /// never reach the query string.
+ #[test]
+ fn marker_query_suffix_sends_the_remote_identity_of_an_undeclared_checkout() {
+ let Some(repo) = repo_with_remotes(&[
+ (
+ "origin",
+ "https://someone:[email protected]/Fork/API.git",
+ ),
+ ("upstream", "[email protected]:Acme/API.git"),
+ ]) else {
+ return;
+ };
+ let qs = marker_query_suffix(repo.path().to_str().unwrap(), None);
+ assert!(
+ qs.contains("&identity=git.example.test%2Facme%2Fapi&identity_src=git_remote"),
+ "{qs}"
+ );
+ assert!(
+ !qs.contains("s3cret"),
+ "credentials must not leave the machine: {qs}"
+ );
+
+ let Some(origin_only) = repo_with_remotes(&[(
+ "origin",
+ "https://someone:[email protected]/Fork/API.git",
+ )]) else {
+ return;
+ };
+ let qs = marker_query_suffix(origin_only.path().to_str().unwrap(), None);
+ assert!(
+ qs.contains("&identity=git.example.test%2Ffork%2Fapi"),
+ "{qs}"
+ );
+ assert!(!qs.contains("s3cret"), "{qs}");
+ }
+
+ /// A declared `project` outranks the remote and routes by name, so nothing
+ /// is sent for it; an explicit `identity` outranks both.
+ #[test]
+ fn marker_query_suffix_lets_declarations_decide_the_identity() {
+ let Some(repo) = repo_with_remotes(&[("upstream", "[email protected]:acme/tool.git")])
+ else {
+ return;
+ };
+ let cwd = repo.path().to_str().unwrap();
+ let marker = repo.path().join(".ai-memory.toml");
+
+ std::fs::write(&marker, "project = \"my-fork\"\n").unwrap();
+ let qs = marker_query_suffix(cwd, None);
+ assert!(qs.contains("&project=my-fork"), "{qs}");
+ assert!(
+ !qs.contains("&identity="),
+ "a declared project routes by name: {qs}"
+ );
+
+ std::fs::write(
+ &marker,
+ "project = \"my-fork\"\nidentity = \"Acme/Platform\"\n",
+ )
+ .unwrap();
+ let qs = marker_query_suffix(cwd, None);
+ assert!(
+ qs.contains("&identity=acme%2Fplatform&identity_src=explicit"),
+ "{qs}"
+ );
+ }
+
+ /// No repository, no remote, no declaration: nothing to send, and the
+ /// server routes by folder name exactly as before.
+ #[test]
+ fn marker_query_suffix_sends_no_identity_outside_a_repository() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let qs = marker_query_suffix(tmp.path().to_str().unwrap(), None);
+ assert!(!qs.contains("identity"), "{qs}");
+ }
+
#[test]
fn marker_query_suffix_appends_marker_fields() {
let tmp = tempfile::TempDir::new().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 99f061db..a84e0a46 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -3528,7 +3528,7 @@ export default AiMemoryOpencode2;
/// purpose: `findMarker` stays untouched, well-exercised, nearest-marker
/// behavior for every other caller.
pub(crate) const TS_FIND_SETTINGS_MARKER: &str = r#"function declaresSettings(text: string): boolean {
- for (const key of ["workspace", "project", "project_strategy", "drop_subagent_captures"]) {
+ for (const key of ["workspace", "project", "project_strategy", "drop_subagent_captures", "identity"]) {
if (tomlKey(text, key) !== undefined) return true;
}
for (const key of ["default_global", "inject_on_session_start", "max_chars"]) {
@@ -3585,17 +3585,21 @@ function findSettingsMarker(cwd: string | undefined): string | undefined {
fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
let Some(default) = default_strategy else {
return format!(
- "{TS_TOML_FLAG}\n{TS_FIND_SETTINGS_MARKER}\n{}",
+ "{TS_TOML_FLAG}\n{TS_FIND_SETTINGS_MARKER}\n{TS_IDENTITY}\n{}",
r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
const managedRun = process.env.AI_MEMORY_RUN_ID;
if (managedRun) url.searchParams.set("managed_run", managedRun);
const marker = findSettingsMarker(cwd);
- if (!marker || !cwd) return;
+ if (!marker || !cwd) {
+ applyIdentityParams(url, cwd, undefined, undefined);
+ return;
+ }
url.searchParams.set("cwd", cwd);
try {
const body = readFileSync(marker, "utf8");
const workspace = tomlKey(body, "workspace");
const project = tomlKey(body, "project");
+ applyIdentityParams(url, cwd, tomlKey(body, "identity"), project);
const projectStrategy = tomlKey(body, "project_strategy");
const dropSubagent = tomlKey(body, "drop_subagent_captures");
const defaultGlobal = tomlFlag(body, "default_global");
@@ -3629,6 +3633,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
let defaultGlobal: string | undefined;
let briefing: string | undefined;
let briefingBudget: string | undefined;
+ let explicitIdentity: string | undefined;
const marker = findSettingsMarker(cwd);
if (marker) {
try {
@@ -3640,9 +3645,12 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
defaultGlobal = tomlFlag(body, "default_global");
briefing = tomlFlag(body, "inject_on_session_start");
briefingBudget = tomlFlag(body, "max_chars");
+ explicitIdentity = tomlKey(body, "identity");
} catch (_e) {
}
}
+ // Before repo-root can fill `project`: a repo-root name is an inference.
+ applyIdentityParams(url, cwd, explicitIdentity, project);
if (!projectStrategy) projectStrategy = DEFAULT_PROJECT_STRATEGY;
if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {
const repoProject = repoRootProject(cwd);
@@ -3657,11 +3665,89 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
}"#;
format!(
- "const DEFAULT_PROJECT_STRATEGY = {};\n{TS_TOML_FLAG}\n{TS_FIND_SETTINGS_MARKER}\n{body}",
+ "const DEFAULT_PROJECT_STRATEGY = {};\n{TS_TOML_FLAG}\n{TS_FIND_SETTINGS_MARKER}\n{TS_IDENTITY}\n{body}",
ts_string_literal(default)
)
}
+/// Repository identity for the TypeScript plugins (#708): a port of
+/// `normalize_remote_url` in `ai-memory-core::repository_identity`, checked
+/// against the shared `fixtures/remote_identity_cases.json`, and
+/// `applyIdentityParams`, which mirrors `repository_identity` in
+/// `hook_capture.rs` — an explicit marker `identity` is sent; a declared
+/// `project` outranks the remote and routes by name, so git is not consulted;
+/// otherwise the `upstream` remote, else `origin`. 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 {
+ const trimmed = raw.trim();
+ if (!trimmed) return undefined;
+ let scheme: string | undefined;
+ let rest = trimmed;
+ const idx = trimmed.indexOf("://");
+ if (idx >= 0) {
+ scheme = trimmed.slice(0, idx).toLowerCase();
+ rest = trimmed.slice(idx + 3);
+ }
+ if (scheme === "file") return undefined;
+ let pathStart = rest.indexOf("/");
+ if (pathStart < 0) pathStart = rest.length;
+ const at = rest.slice(0, pathStart).lastIndexOf("@");
+ const hp = at >= 0 ? rest.slice(at + 1) : rest;
+ let host: string;
+ let path: string;
+ if (scheme !== undefined) {
+ const slash = hp.indexOf("/");
+ host = slash >= 0 ? hp.slice(0, slash) : hp;
+ path = slash >= 0 ? hp.slice(slash + 1) : "";
+ const colon = host.lastIndexOf(":");
+ if (colon >= 0 && /^[0-9]*$/.test(host.slice(colon + 1))) host = host.slice(0, colon);
+ if (!host || !path) return undefined;
+ } else {
+ const colon = hp.indexOf(":");
+ if (colon < 0) return undefined;
+ const slash = hp.indexOf("/");
+ if (slash >= 0 && slash < colon) return undefined;
+ host = hp.slice(0, colon);
+ path = hp.slice(colon + 1);
+ if (host.length <= 1 || !path) return undefined;
+ if (path.includes("\\")) return undefined;
+ }
+ let id = `${host}/${path}`.toLowerCase().replace(/\/+$/, "");
+ if (id.endsWith(".git")) id = id.slice(0, -4);
+ id = id.replace(/\/+$/, "").replace(/\/\/+/g, "/");
+ return id && id.includes("/") ? id : undefined;
+}
+
+function applyIdentityParams(
+ url: URL,
+ cwd: string | undefined,
+ explicit: string | undefined,
+ project: string | undefined,
+): void {
+ const declared = explicit?.trim();
+ if (declared) {
+ url.searchParams.set("identity", declared.toLowerCase());
+ url.searchParams.set("identity_src", "explicit");
+ return;
+ }
+ if (project?.trim() || !cwd) return;
+ for (const name of ["upstream", "origin"]) {
+ try {
+ const remote = execFileSync("git", ["-C", cwd, "config", "--get", `remote.${name}.url`], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ const identity = normalizeRemote(remote);
+ if (identity) {
+ url.searchParams.set("identity", identity);
+ url.searchParams.set("identity_src", "git_remote");
+ return;
+ }
+ } catch (_e) {
+ }
+ }
+}"#;
+
/// `tomlFlag` mirrors the native hook's `parse_toml_flag`: unlike `tomlKey`
/// (quoted strings only) it also accepts a bare token (`default_global =
/// true`, `max_chars = 4000`), so section-style marker keys work whether or
@@ -8752,7 +8838,7 @@ model = "gpt-5"
assert!(plugin.contains("function declaresSettings"));
assert!(plugin.contains("const marker = findSettingsMarker(cwd);"));
assert!(plugin.contains(
- "for (const key of [\"workspace\", \"project\", \"project_strategy\", \"drop_subagent_captures\"])"
+ "for (const key of [\"workspace\", \"project\", \"project_strategy\", \"drop_subagent_captures\", \"identity\"])"
));
assert!(plugin.contains(
"for (const key of [\"default_global\", \"inject_on_session_start\", \"max_chars\"])"
@@ -11801,3 +11887,178 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
assert_eq!(find_grok_project_overlay(&cwd, None), Some(cwd_overlay));
}
}
+
+/// The four clients that normalise a git remote into a repository identity
+/// (#708) must agree on every case, or one repository lands in two projects
+/// depending on which harness captured it. The Rust core is the reference and
+/// checks itself against `remote_identity_cases.json`; these run the same
+/// cases through the shell, PowerShell and TypeScript ports. Each port is
+/// skipped when its interpreter is not installed, so the check never fails for
+/// a missing tool — CI runs it wherever the tool exists.
+#[cfg(test)]
+mod identity_parity_tests {
+ use std::path::PathBuf;
+ use std::process::Command;
+
+ const CASES: &str = include_str!("../../../ai-memory-core/fixtures/remote_identity_cases.json");
+
+ fn cases() -> Vec<(String, Option<String>)> {
+ let cases: serde_json::Value = serde_json::from_str(CASES).unwrap();
+ cases["normalize"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|case| {
+ (
+ case["url"].as_str().unwrap().to_owned(),
+ case["identity"].as_str().map(str::to_owned),
+ )
+ })
+ .collect()
+ }
+
+ fn repo_file(relative: &str) -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../..")
+ .join(relative)
+ }
+
+ /// Compare one port's output, one line per case, with the fixture.
+ fn assert_agrees(port: &str, stdout: &[u8]) {
+ let text = String::from_utf8_lossy(stdout);
+ let got: Vec<&str> = text.split('\n').collect();
+ let cases = cases();
+ for (i, (url, expected)) in cases.iter().enumerate() {
+ let got = got
+ .get(i)
+ .copied()
+ .unwrap_or("<missing>")
+ .trim_end_matches('\r');
+ assert_eq!(
+ got,
+ expected.as_deref().unwrap_or(""),
+ "{port} normalised {url:?} differently from the core"
+ );
+ }
+ }
+
+ #[test]
+ fn the_shell_port_agrees_with_the_core() {
+ if Command::new("sh").arg("-c").arg("true").status().is_err() {
+ return;
+ }
+ let output = Command::new("sh")
+ .arg("-c")
+ .arg(r#". "$1"; shift; for u in "$@"; do printf '%s\n' "$(ai_memory_normalize_remote "$u")"; done"#)
+ .arg("sh")
+ .arg(repo_file("hooks/_lib.sh"))
+ .args(cases().into_iter().map(|(url, _)| url))
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_agrees("hooks/_lib.sh", &output.stdout);
+ }
+
+ #[test]
+ fn the_powershell_port_agrees_with_the_core() {
+ let Some(pwsh) = ["pwsh", "powershell"].into_iter().find(|exe| {
+ Command::new(exe)
+ .args(["-NoProfile", "-Command", "exit 0"])
+ .status()
+ .is_ok()
+ }) else {
+ return;
+ };
+ let tmp = tempfile::TempDir::new().unwrap();
+ let script = tmp.path().join("parity.ps1");
+ std::fs::write(
+ &script,
+ "param([string] $Lib, [string] $Cases)\n\
+ . $Lib\n\
+ foreach ($u in (Get-Content -Raw $Cases | ConvertFrom-Json)) {\n\
+ $id = ConvertTo-AiMemoryRepositoryIdentity -Url $u\n\
+ if ($id) { [Console]::Out.Write(\"$id`n\") } else { [Console]::Out.Write(\"`n\") }\n\
+ }\n\
+ $decisions = @(\n\
+ (Get-AiMemoryIdentityQuery -Cwd '' -Explicit ' Acme/Platform ' -Project 'proj'),\n\
+ (Get-AiMemoryIdentityQuery -Cwd '' -Explicit '' -Project 'proj'),\n\
+ (Get-AiMemoryIdentityQuery -Cwd '' -Explicit '' -Project '')\n\
+ )\n\
+ [Console]::Error.Write($decisions -join '|')\n",
+ )
+ .unwrap();
+ let urls = tmp.path().join("urls.json");
+ let list: Vec<String> = cases().into_iter().map(|(url, _)| url).collect();
+ std::fs::write(&urls, serde_json::to_string(&list).unwrap()).unwrap();
+ let output = Command::new(pwsh)
+ .args(["-NoProfile", "-NonInteractive", "-File"])
+ .arg(&script)
+ .arg(repo_file("hooks/lib/ai-memory-hook.ps1"))
+ .arg(&urls)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_agrees("hooks/lib/ai-memory-hook.ps1", &output.stdout);
+ // Same decisions as the other clients: explicit wins over a declared
+ // project; a declared project alone sends nothing; no cwd sends nothing.
+ assert_eq!(
+ String::from_utf8_lossy(&output.stderr),
+ "&identity=acme%2Fplatform&identity_src=explicit||"
+ );
+ }
+
+ #[test]
+ fn the_typescript_port_agrees_with_the_core() {
+ let strips_types = Command::new("node")
+ .args(["--experimental-strip-types", "-e", "0"])
+ .output()
+ .is_ok_and(|out| out.status.success());
+ if !strips_types {
+ return;
+ }
+ let tmp = tempfile::TempDir::new().unwrap();
+ let module = tmp.path().join("parity.ts");
+ let list: Vec<String> = cases().into_iter().map(|(url, _)| url).collect();
+ let source = format!(
+ "import {{ execFileSync }} from \"node:child_process\";\n\
+ void execFileSync;\n\
+ {}\n\
+ const urls: string[] = {};\n\
+ process.stdout.write(urls.map((u) => normalizeRemote(u) ?? \"\").join(\"\\n\") + \"\\n\");\n\
+ const decide = (explicit?: string, project?: string): string => {{\n\
+ const url = new URL(\"http://h/hook\");\n\
+ applyIdentityParams(url, undefined, explicit, project);\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()
+ );
+ std::fs::write(&module, source).unwrap();
+ let output = Command::new("node")
+ .args(["--experimental-strip-types", "--no-warnings"])
+ .arg(&module)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_agrees("TS_IDENTITY", &output.stdout);
+ // An explicit identity wins over a declared project; a declared
+ // project alone sends nothing; no cwd sends nothing.
+ assert_eq!(
+ String::from_utf8_lossy(&output.stderr),
+ "?identity=acme%2Fplatform&identity_src=explicit||"
+ );
+ }
+}
diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rs
index abc646f4..1aaacad8 100644
--- a/crates/ai-memory-cli/src/marker.rs
+++ b/crates/ai-memory-cli/src/marker.rs
@@ -181,11 +181,12 @@ fn find_marker_matching(
/// the file. That is conservative on purpose: it can only turn a marker INTO
/// a boundary, never wrongly make one transparent.
fn declares_more_than_capture(text: &str) -> bool {
- const QUOTED_KEYS: [&str; 4] = [
+ const QUOTED_KEYS: [&str; 5] = [
"workspace",
"project",
"project_strategy",
"drop_subagent_captures",
+ "identity",
];
const FLAG_KEYS: [&str; 3] = ["default_global", "inject_on_session_start", "max_chars"];
QUOTED_KEYS
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index c703b17d..1e806857 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -80,7 +80,7 @@ ai_memory_parse_toml_flag() {
ai_memory_marker_declares_settings() {
file="$1"
[ -f "$file" ] || return 1
- for key in workspace project project_strategy drop_subagent_captures; do
+ for key in workspace project project_strategy drop_subagent_captures identity; do
[ -n "$(ai_memory_parse_toml_key "$file" "$key")" ] && return 0
done
for key in default_global inject_on_session_start max_chars; do
@@ -293,6 +293,89 @@ ai_memory_repo_root_project() {
basename "$root"
}
+# Normalise a git remote URL ("$1") into a repository identity, or print
+# nothing when it names no network-reachable repository (a local path, a bare
+# host). Port of `normalize_remote_url` in
+# crates/ai-memory-core/src/repository_identity.rs, checked against the same
+# fixture (crates/ai-memory-core/fixtures/remote_identity_cases.json) so the
+# two cannot drift. Credentials are dropped here, on the host, so they never
+# reach the server. Variables are prefixed: POSIX functions share the
+# caller's scope.
+ai_memory_normalize_remote() {
+ _ai_rn_raw=$(printf '%s' "$1" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+ [ -n "$_ai_rn_raw" ] || return 0
+ case "$_ai_rn_raw" in
+ *://*)
+ _ai_rn_has_scheme=1
+ _ai_rn_scheme=$(printf '%s' "${_ai_rn_raw%%://*}" | tr '[:upper:]' '[:lower:]')
+ _ai_rn_rest=${_ai_rn_raw#*://}
+ ;;
+ *)
+ _ai_rn_has_scheme=""
+ _ai_rn_scheme=""
+ _ai_rn_rest=$_ai_rn_raw
+ ;;
+ esac
+ [ "$_ai_rn_scheme" = "file" ] && return 0
+ # Credentials: everything up to the LAST `@` before the path.
+ _ai_rn_auth=${_ai_rn_rest%%/*}
+ _ai_rn_tail=${_ai_rn_rest#"$_ai_rn_auth"}
+ case "$_ai_rn_auth" in *@*) _ai_rn_auth=${_ai_rn_auth##*@} ;; esac
+ _ai_rn_hp="$_ai_rn_auth$_ai_rn_tail"
+ if [ -n "$_ai_rn_has_scheme" ]; then
+ _ai_rn_host=${_ai_rn_hp%%/*}
+ case "$_ai_rn_hp" in */*) _ai_rn_path=${_ai_rn_hp#*/} ;; *) _ai_rn_path="" ;; esac
+ case "$_ai_rn_host" in
+ *:*)
+ case "${_ai_rn_host##*:}" in
+ *[!0-9]*) ;;
+ *) _ai_rn_host=${_ai_rn_host%:*} ;;
+ esac
+ ;;
+ esac
+ [ -n "$_ai_rn_host" ] && [ -n "$_ai_rn_path" ] || return 0
+ else
+ # scp-like `host:path`, or a filesystem path: a `:` before any `/`.
+ case "$_ai_rn_hp" in *:*) ;; *) return 0 ;; esac
+ _ai_rn_host=${_ai_rn_hp%%:*}
+ case "$_ai_rn_host" in */*) return 0 ;; esac
+ _ai_rn_path=${_ai_rn_hp#*:}
+ # A one-character host is a Windows drive letter.
+ [ "${#_ai_rn_host}" -gt 1 ] && [ -n "$_ai_rn_path" ] || return 0
+ case "$_ai_rn_path" in *\\*) return 0 ;; esac
+ fi
+ _ai_rn_id=$(printf '%s/%s' "$_ai_rn_host" "$_ai_rn_path" \
+ | tr '[:upper:]' '[:lower:]' \
+ | sed -e 's#/*$##' -e 's#\.git$##' -e 's#/*$##' -e 's#//*#/#g')
+ case "$_ai_rn_id" in */*) printf '%s' "$_ai_rn_id" ;; esac
+}
+
+# Print `&identity=<v>&identity_src=<rung>` for the checkout at "$1", or
+# nothing. "$2" is the marker's `identity`, "$3" its declared `project`.
+# Mirrors `repository_identity` in hook_capture.rs: an explicit identity is
+# sent; a declared project outranks the remote and routes by name, so git is
+# not consulted; otherwise the `upstream` remote, else `origin`.
+ai_memory_identity_qs() {
+ _ai_id_cwd="$1"; _ai_id_explicit="$2"; _ai_id_project="$3"
+ _ai_id_explicit=$(printf '%s' "$_ai_id_explicit" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
+ if [ -n "$_ai_id_explicit" ]; then
+ _ai_id_value=$(printf '%s' "$_ai_id_explicit" | tr '[:upper:]' '[:lower:]')
+ printf '&identity=%s&identity_src=explicit' "$(ai_memory_url_encode "$_ai_id_value")"
+ return 0
+ fi
+ [ -n "$(printf '%s' "$_ai_id_project" | tr -d '[:space:]')" ] && return 0
+ [ -n "$_ai_id_cwd" ] || return 0
+ command -v git >/dev/null 2>&1 || return 0
+ for _ai_id_remote in upstream origin; do
+ _ai_id_url=$(git -C "$_ai_id_cwd" config --get "remote.$_ai_id_remote.url" 2>/dev/null) || continue
+ _ai_id_value=$(ai_memory_normalize_remote "$_ai_id_url")
+ if [ -n "$_ai_id_value" ]; then
+ printf '&identity=%s&identity_src=git_remote' "$(ai_memory_url_encode "$_ai_id_value")"
+ return 0
+ fi
+ done
+}
+
# Build a query-string suffix from "$1" plus any marker file walked up from
# it. Returns the suffix with the leading `&`, or nothing when cwd is absent.
# `cwd` is always included so `GET /handoff` resolves the same basename project
@@ -312,6 +395,7 @@ ai_memory_marker_qs() {
# deliberate marker rescope from a host-derived repo-root name. Only the
# latter may yield to session-sticky attribution (#394).
ps=""
+ idn=""
# 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.
@@ -321,8 +405,12 @@ ai_memory_marker_qs() {
pr=$(ai_memory_parse_toml_key "$marker" project)
st=$(ai_memory_parse_toml_key "$marker" project_strategy)
ds=$(ai_memory_parse_toml_key "$marker" drop_subagent_captures)
+ idn=$(ai_memory_parse_toml_key "$marker" identity)
[ -n "$pr" ] && ps="marker"
fi
+ # Before repo-root can fill `pr`: a repo-root name is an inference, while
+ # the identity chain's declared-project rung means a name in the marker.
+ iq=$(ai_memory_identity_qs "$cwd" "$idn" "$pr")
# 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.
@@ -347,6 +435,7 @@ ai_memory_marker_qs() {
[ -n "$pr" ] && qs="${qs}&project=$(ai_memory_url_encode "$pr")"
[ -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}"
# 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.ps1
index aefa40e6..63f8f172 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -170,6 +170,90 @@ function Get-AiMemoryRepoRootProject {
return Split-Path $root -Leaf
}
+# Normalise a git remote URL into a repository identity, or $null when it
+# names no network-reachable repository (a local path, a bare host). Port of
+# `normalize_remote_url` in crates/ai-memory-core/src/repository_identity.rs,
+# checked against the same fixture
+# (crates/ai-memory-core/fixtures/remote_identity_cases.json) so the two
+# cannot drift. Credentials are dropped here, on the host.
+function ConvertTo-AiMemoryRepositoryIdentity {
+ param([string] $Url)
+ if ($null -eq $Url) { return $null }
+ $raw = $Url.Trim()
+ if (-not $raw) { return $null }
+ $scheme = $null
+ $hasScheme = $false
+ $rest = $raw
+ $idx = $raw.IndexOf("://")
+ if ($idx -ge 0) {
+ $hasScheme = $true
+ $scheme = $raw.Substring(0, $idx).ToLowerInvariant()
+ $rest = $raw.Substring($idx + 3)
+ }
+ if ($scheme -eq "file") { return $null }
+ # Credentials: everything up to the LAST `@` before the path.
+ $pathStart = $rest.IndexOf("/")
+ if ($pathStart -lt 0) { $pathStart = $rest.Length }
+ $at = $rest.Substring(0, $pathStart).LastIndexOf("@")
+ $hp = if ($at -ge 0) { $rest.Substring($at + 1) } else { $rest }
+ if ($hasScheme) {
+ $slash = $hp.IndexOf("/")
+ if ($slash -ge 0) {
+ $h = $hp.Substring(0, $slash)
+ $p = $hp.Substring($slash + 1)
+ } else {
+ $h = $hp
+ $p = ""
+ }
+ $colon = $h.LastIndexOf(":")
+ if ($colon -ge 0 -and $h.Substring($colon + 1) -match '^[0-9]*$') {
+ $h = $h.Substring(0, $colon)
+ }
+ if (-not $h -or -not $p) { return $null }
+ } else {
+ # scp-like `host:path`, or a filesystem path: a `:` before any `/`.
+ $colon = $hp.IndexOf(":")
+ if ($colon -lt 0) { return $null }
+ $slash = $hp.IndexOf("/")
+ if ($slash -ge 0 -and $slash -lt $colon) { return $null }
+ $h = $hp.Substring(0, $colon)
+ $p = $hp.Substring($colon + 1)
+ # A one-character host is a Windows drive letter.
+ if ($h.Length -le 1 -or -not $p) { return $null }
+ if ($p.Contains("\")) { return $null }
+ }
+ $id = "$h/$p".ToLowerInvariant().TrimEnd('/')
+ if ($id.EndsWith(".git")) { $id = $id.Substring(0, $id.Length - 4) }
+ $id = $id.TrimEnd('/')
+ while ($id.Contains("//")) { $id = $id.Replace("//", "/") }
+ if (-not $id -or -not $id.Contains("/")) { return $null }
+ return $id
+}
+
+# `&identity=<v>&identity_src=<rung>` for the checkout at $Cwd, or "".
+# Mirrors `repository_identity` in hook_capture.rs: an explicit marker
+# `identity` is sent; a declared `project` outranks the remote and routes by
+# name, so git is not consulted; otherwise the `upstream` remote, else `origin`.
+function Get-AiMemoryIdentityQuery {
+ param([string] $Cwd, [string] $Explicit, [string] $Project)
+ if ($Explicit -and $Explicit.Trim()) {
+ $value = $Explicit.Trim().ToLowerInvariant()
+ return "&identity=$([uri]::EscapeDataString($value))&identity_src=explicit"
+ }
+ if ($Project -and $Project.Trim()) { return "" }
+ if (-not $Cwd) { return "" }
+ if (-not (Get-Command git -ErrorAction SilentlyContinue)) { return "" }
+ foreach ($name in @("upstream", "origin")) {
+ $url = (& git -C $Cwd config --get "remote.$name.url" 2>$null)
+ if (-not $url) { continue }
+ $value = ConvertTo-AiMemoryRepositoryIdentity -Url ([string]$url)
+ if ($value) {
+ return "&identity=$([uri]::EscapeDataString($value))&identity_src=git_remote"
+ }
+ }
+ return ""
+}
+
function Get-AiMemoryMarkerQuery {
param([string] $Cwd)
if (-not $Cwd) { return "" }
@@ -182,14 +266,19 @@ function Get-AiMemoryMarkerQuery {
# deliberate marker rescope from a host-derived repo-root name. Only the
# latter may yield to session-sticky attribution (#394).
$projSrc = $null
+ $explicitIdentity = $null
$marker = Get-AiMemoryMarkerToml -Cwd $Cwd
if ($marker) {
$ws = Get-AiMemoryTomlKey -File $marker -Key "workspace"
$proj = Get-AiMemoryTomlKey -File $marker -Key "project"
$strategy = Get-AiMemoryTomlKey -File $marker -Key "project_strategy"
$dropSubagent = Get-AiMemoryTomlKey -File $marker -Key "drop_subagent_captures"
+ $explicitIdentity = Get-AiMemoryTomlKey -File $marker -Key "identity"
if ($proj) { $projSrc = "marker" }
}
+ # Before repo-root can fill $proj: a repo-root name is an inference, while
+ # the identity chain's declared-project rung means a name in the marker.
+ $identityQuery = Get-AiMemoryIdentityQuery -Cwd $Cwd -Explicit $explicitIdentity -Project $proj
# 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.
@@ -206,6 +295,7 @@ function Get-AiMemoryMarkerQuery {
if ($proj) { $qs += "&project=$([uri]::EscapeDataString($proj))" }
if ($projSrc) { $qs += "&project_src=$([uri]::EscapeDataString($projSrc))" }
if ($strategy) { $qs += "&project_strategy=$([uri]::EscapeDataString($strategy))" }
+ $qs += $identityQuery
# 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.sh
index aa1f9ced..ebdee138 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -240,6 +240,31 @@ assert_eq "capture-only marker: marker_qs forwards the OUTER scope" \
"&cwd=$(ai_memory_url_encode "$TMP/scope/inner")&workspace=acme&project=infra&project_src=marker" \
"$(ai_memory_marker_qs "$TMP/scope/inner")"
+# --- repository identity (#708) ----------------------------------------
+# An undeclared checkout sends its normalised remote, with the credentials in
+# the URL dropped on this side; a declared project outranks the remote and
+# routes by name (nothing sent); an explicit identity outranks both.
+# Normalisation itself is checked case by case against the shared fixture by
+# `identity_parity_tests` in install_hooks.rs.
+if command -v git >/dev/null 2>&1; then
+ mkdir -p "$TMP/idrepo"
+ git -C "$TMP/idrepo" init -q
+ git -C "$TMP/idrepo" remote add origin "https://someone:[email protected]/Acme/API.git"
+ ID_CWD=$(ai_memory_url_encode "$TMP/idrepo")
+ assert_eq "identity: undeclared checkout sends its remote" \
+ "&cwd=$ID_CWD&identity=$(ai_memory_url_encode git.example.test/acme/api)&identity_src=git_remote" \
+ "$(ai_memory_marker_qs "$TMP/idrepo")"
+ printf 'project = "mine"\n' >"$TMP/idrepo/.ai-memory.toml"
+ assert_eq "identity: a declared project routes by name" \
+ "&cwd=$ID_CWD&project=mine&project_src=marker" \
+ "$(ai_memory_marker_qs "$TMP/idrepo")"
+ printf 'project = "mine"\nidentity = "Acme/Platform"\n' >"$TMP/idrepo/.ai-memory.toml"
+ assert_eq "identity: an explicit identity outranks the project" \
+ "&cwd=$ID_CWD&project=mine&project_src=marker&identity=$(ai_memory_url_encode acme/platform)&identity_src=explicit" \
+ "$(ai_memory_marker_qs "$TMP/idrepo")"
+ rm -rf "$TMP/idrepo"
+fi
+
# A marker declaring [briefing] but no workspace/project is NOT capture-only
# (it declares a forwarded setting), so it stays a resolution boundary: the
# outer marker's scope must not leak through it.