Skip to content

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

Rust

feat(routing): add install-wide home routes (#1033)

AkitaOnRailsf007ef2a0518
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95bf5692..59ec66e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added bounded install-wide identity and component-safe path routes in the exact
+ operator-home `.ai-memory.toml`. Exact hostful repository identity wins the
+ longest lexical path route, local non-home markers stay authoritative, aliases
+ reuse the existing identity-bound marker wire, and malformed or ambiguous route
+ maps fail closed across native, shell, PowerShell, generated TypeScript, and
+ OpenClaw clients. Recognizable malformed route syntax is rejected before
+ fallback, while malformed root-only settings retain legacy parsing. Generated
+ clients preserve marker versus repo-root provenance, and OpenClaw keeps local
+ git identity discovery alias-gated. The default identity style remains
+ unchanged. (#1033)
- 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
diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rs
index 7b53ac4a..80754cfc 100644
--- a/crates/ai-memory-cli/src/commands/doctor.rs
+++ b/crates/ai-memory-cli/src/commands/doctor.rs
@@ -442,7 +442,31 @@ async fn project_coordinate_report(
pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
let (identity_cwd, lookup_cwd) = super::scope_directories(config)
.ok_or_else(|| anyhow::anyhow!("resolving the current working directory"))?;
- let marker = crate::marker::inspect_scope(&lookup_cwd, &config.runtime_env);
+ let explicit_scope = args
+ .workspace
+ .as_deref()
+ .filter(|value| !value.is_empty())
+ .is_some()
+ && args
+ .project
+ .as_deref()
+ .filter(|value| !value.is_empty())
+ .is_some();
+ let marker = if explicit_scope {
+ crate::marker::MarkerInspection {
+ status: "bypassed_explicit_scope",
+ fields: crate::marker::RoutingFields::default(),
+ scope: None,
+ route_identity: None,
+ }
+ } else {
+ let marker =
+ crate::marker::inspect_scope_for(&lookup_cwd, &identity_cwd, &config.runtime_env);
+ if marker.status == "invalid_home_routes" {
+ anyhow::bail!("invalid home route map; doctor did not query a fallback server scope");
+ }
+ marker
+ };
let scope_marker = marker
.scope
.clone()
diff --git a/crates/ai-memory-cli/src/commands/embed.rs b/crates/ai-memory-cli/src/commands/embed.rs
index 20765d79..92b08ddb 100644
--- a/crates/ai-memory-cli/src/commands/embed.rs
+++ b/crates/ai-memory-cli/src/commands/embed.rs
@@ -39,7 +39,7 @@ pub async fn run(config: &Config, args: EmbedArgs) -> Result<()> {
// away, and would announce a project the request never carries.
let (workspace, project) = if all_projects {
(
- super::resolve_workspace(config, args.workspace.as_deref()),
+ super::resolve_workspace(config, args.workspace.as_deref())?,
String::new(),
)
} else {
@@ -73,6 +73,7 @@ pub async fn run(config: &Config, args: EmbedArgs) -> Result<()> {
#[cfg(test)]
mod tests {
use crate::cli::{Cli, Command};
+ use crate::config::{Config, RuntimeEnv};
use clap::Parser;
#[test]
@@ -89,6 +90,27 @@ mod tests {
);
}
+ #[test]
+ fn force_with_explicit_workspace_bypasses_invalid_home_routes() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = tmp.path().join("repo");
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(home.join(".ai-memory.toml"), "route_project=\"orphan\"\n").unwrap();
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_and_home_for_tests(
+ repo.to_string_lossy(),
+ home.to_string_lossy(),
+ ),
+ ..Config::default()
+ };
+ assert_eq!(
+ super::super::resolve_workspace(&config, Some("explicit")).unwrap(),
+ "explicit"
+ );
+ }
+
#[test]
fn force_with_explicit_project_stays_scoped() {
let cli = Cli::try_parse_from(["ai-memory", "embed", "--force", "--project", "consisanet"])
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index c1dd68ce..0ccb3e77 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -701,6 +701,9 @@ where
let marker_present = policy_cwd
.as_deref()
.is_some_and(|cwd| crate::marker::find_marker(cwd).is_some());
+ let routing_valid = policy_cwd
+ .as_deref()
+ .is_none_or(|cwd| crate::marker::routing_selection(cwd).is_ok());
let admits_capture = repository_admits_capture(capture_mode, marker_present);
if args.check_capture {
let protocol = decision.as_ref().map(|decision| decision.protocol());
@@ -719,6 +722,7 @@ where
Some(_) => "server-derived",
};
let policy_admits_capture = admits_capture
+ && routing_valid
&& event_admits_capture
&& !matches!(route, HookRoute::Rejected { .. })
&& scope_resolution != "partial"
@@ -771,7 +775,7 @@ where
// is `None` for UserPromptSubmit, SessionStart/End and Stop, so gating via
// `CaptureDisposition` alone would still spool prompt text from an
// opted-out repository while reporting it as excluded.
- if !admits_capture {
+ if !admits_capture || !routing_valid {
write_success_response(stdout, agent_kind, hook_event)?;
return Ok(());
}
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 69f6b460..ebbd3f92 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -12,8 +12,8 @@ use std::time::Duration;
use crate::commands::path_util::home_dir;
use crate::marker::{
- find_marker, find_settings_marker, is_truthy, parse_toml_flag, parse_toml_key,
- repo_root_project,
+ RoutingSelection, RoutingSource, find_marker, find_settings_marker, is_truthy, parse_toml_flag,
+ parse_toml_key, repo_root_project, routing_selection,
};
use ai_memory_hooks::capture_policy::MAX_MARKER_BYTES;
use ai_memory_hooks::{
@@ -403,8 +403,7 @@ impl HookScope {
/// Inspect the same marker, worktree and repository identity as hook routing.
#[must_use]
pub fn hook_scope(cwd: &str, default_strategy: Option<&str>) -> HookScope {
- let marker = find_settings_marker(cwd);
- hook_scope_from_marker(cwd, default_strategy, marker.as_deref())
+ hook_scope_from_selection(cwd, default_strategy, routing_selection(cwd).ok().flatten())
}
pub(crate) fn inspect_repository_coordinate(
@@ -418,11 +417,13 @@ pub(crate) fn inspect_repository_coordinate(
} else {
marker.fields.project.as_deref()
};
- let repository = repository_identity(
- identity_cwd,
- marker.fields.identity.as_deref(),
- declared_project,
- );
+ let repository = marker.route_identity.clone().or_else(|| {
+ repository_identity(
+ identity_cwd,
+ marker.fields.identity.as_deref(),
+ declared_project,
+ )
+ });
let identity_style = repository.as_ref().and_then(|identity| {
(identity.source == ai_memory_core::repository_identity::IdentitySource::GitRemote).then(
|| {
@@ -456,6 +457,9 @@ pub(crate) fn inspect_repository_coordinate(
.as_ref()
.and_then(ai_memory_core::repository_identity::legacy_basename_name),
messages: match marker.status {
+ "invalid_home_routes" => {
+ vec!["invalid home route map; marker routing was refused".to_owned()]
+ }
"invalid" => vec!["invalid marker TOML; marker routing was ignored".to_owned()],
"unreadable" => vec!["unreadable marker; marker routing was ignored".to_owned()],
"conflicting" => {
@@ -469,32 +473,45 @@ pub(crate) fn inspect_repository_coordinate(
}
}
-fn hook_scope_from_marker(
+fn hook_scope_from_selection(
cwd: &str,
default_strategy: Option<&str>,
- marker: Option<&Path>,
+ selection: Option<RoutingSelection>,
) -> HookScope {
- let mut workspace = None;
- let mut project = None;
- 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 workspace = selection
+ .as_ref()
+ .and_then(|selection| selection.fields.workspace.clone());
+ let mut project = selection
+ .as_ref()
+ .and_then(|selection| selection.fields.project.clone());
+ let mut strategy = selection
+ .as_ref()
+ .and_then(|selection| selection.fields.project_strategy.clone());
+ let explicit_identity = selection
+ .as_ref()
+ .and_then(|selection| selection.fields.identity.clone());
+ let style = selection
+ .as_ref()
+ .and_then(|selection| selection.fields.identity_style.clone());
+ let mut aliases =
+ selection
+ .as_ref()
+ .and_then(|selection| match selection.fields.aliases.clone() {
+ 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 routed = selection.as_ref().is_some_and(|selection| {
+ matches!(
+ selection.source,
+ RoutingSource::HomeIdentityRoute | RoutingSource::HomePathRoute
+ )
+ });
let mut project_src = project.as_ref().map(|_| "marker");
- let identity = if aliases.is_none() {
+ let identity = if routed {
+ selection.and_then(|selection| selection.remote_identity)
+ } else if aliases.is_none() {
repository_identity(cwd, explicit_identity.as_deref(), project.as_deref())
} else {
repository_identity(cwd, None, None).filter(|identity| {
@@ -502,11 +519,16 @@ fn hook_scope_from_marker(
})
};
if aliases.is_some()
- && (canonical_project.is_none()
- || identity.as_ref().is_none_or(|identity| {
- identity.source != ai_memory_core::repository_identity::IdentitySource::GitRemote
- }))
+ && identity.as_ref().is_none_or(|identity| {
+ identity.source != ai_memory_core::repository_identity::IdentitySource::GitRemote
+ })
{
+ aliases = if routed {
+ None
+ } else {
+ Some("invalid".to_owned())
+ };
+ } else if aliases.is_some() && canonical_project.is_none() {
aliases = Some("invalid".to_owned());
}
if strategy.is_none() {
@@ -567,10 +589,23 @@ fn marker_query_suffix_impl(
cwd: &str,
default_strategy: Option<&str>,
include_briefing: bool,
+) -> String {
+ let selection = match routing_selection(cwd) {
+ Ok(selection) => selection,
+ Err(_) => return String::new(),
+ };
+ marker_query_suffix_impl_from_selection(cwd, default_strategy, include_briefing, selection)
+}
+
+fn marker_query_suffix_impl_from_selection(
+ cwd: &str,
+ default_strategy: Option<&str>,
+ include_briefing: bool,
+ selection: Option<RoutingSelection>,
) -> String {
let mut qs = format!("&cwd={}", url_encode(cwd));
- let marker = find_settings_marker(cwd);
- let scope = hook_scope_from_marker(cwd, default_strategy, marker.as_deref());
+ let marker = selection.as_ref().map(|selection| selection.path.clone());
+ let scope = hook_scope_from_selection(cwd, default_strategy, selection);
let (mut drop_subagent, mut default_global) = (None, None);
let (mut briefing, mut briefing_budget) = (None, None);
let (mut profile_contribute, mut profile_consume) = (None, None);
@@ -1409,6 +1444,87 @@ mod tests {
assert!(!qs.contains("identity"), "{qs}");
}
+ #[test]
+ fn matched_home_route_keeps_root_behavior_flags() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = home.join("src/api/lib");
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ home.join(".ai-memory.toml"),
+ "workspace=\"wrong\"\nproject=\"wrong\"\nproject_strategy=\"repo-root\"\ndrop_subagent_captures=\"true\"\n[recall]\ndefault_global=true\n[briefing]\ninject_on_session_start=true\nmax_chars=3210\n[profile]\ncontribute=true\nconsume=false\n[routes.path.\"~/src/api\"]\nroute_workspace=\"right\"\nroute_project=\"api\"\n",
+ )
+ .unwrap();
+ let selection = super::super::super::marker::routing_selection_with_home(
+ repo.to_str().unwrap(),
+ repo.to_str().unwrap(),
+ Some(&home),
+ false,
+ )
+ .unwrap();
+ let query =
+ marker_query_suffix_impl_from_selection(repo.to_str().unwrap(), None, true, selection);
+ for expected in [
+ "&workspace=right",
+ "&project=api",
+ "&drop_subagent=true",
+ "&default_global=true",
+ "&briefing=true",
+ "&briefing_budget=3210",
+ "&profile_contribute=1",
+ "&profile_consume=0",
+ ] {
+ assert!(query.contains(expected), "{expected}: {query}");
+ }
+ assert!(!query.contains("project_strategy="), "{query}");
+ assert!(!query.contains("workspace=wrong"), "{query}");
+ }
+
+ #[test]
+ fn non_git_home_path_route_omits_aliases() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = home.join("src/api");
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ home.join(".ai-memory.toml"),
+ "[routes.path.\"~/src/api\"]\nroute_workspace=\"path\"\nroute_project=\"api\"\nroute_aliases=[\"old-api\"]\n",
+ )
+ .unwrap();
+ let selection = super::super::super::marker::routing_selection_with_home(
+ repo.to_str().unwrap(),
+ repo.to_str().unwrap(),
+ Some(&home),
+ false,
+ )
+ .unwrap();
+ let query =
+ marker_query_suffix_impl_from_selection(repo.to_str().unwrap(), None, false, selection);
+ assert!(query.contains("&workspace=path&project=api"), "{query}");
+ assert!(!query.contains("aliases="), "{query}");
+ assert!(!query.contains("identity_src="), "{query}");
+ }
+
+ #[test]
+ fn invalid_home_routes_produce_no_hook_scope_or_query() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = home.join("repo");
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ home.join(".ai-memory.toml"),
+ "workspace=\"wrong\"\nproject=\"wrong\"\n[routes.path.\"relative\"]\nroute_workspace=\"route\"\nroute_project=\"route\"\n",
+ )
+ .unwrap();
+ let result = super::super::super::marker::routing_selection_with_home(
+ repo.to_str().unwrap(),
+ repo.to_str().unwrap(),
+ Some(&home),
+ false,
+ );
+ assert!(result.is_err());
+ }
+
#[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 85ab1b6c..09217aba 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -3888,8 +3888,12 @@ function findSettingsMarker(cwd: string | undefined): string | undefined {
const marker = join(dir, ".ai-memory.toml");
if (existsSync(marker)) {
try {
- if (declaresSettings(readFileSync(marker, "utf8"))) return marker;
+ const text = marker === join(home, ".ai-memory.toml")
+ ? readHomeRouteText(marker)
+ : readFileSync(marker, "utf8");
+ if (declaresSettings(text)) return marker;
} catch (_e) {
+ return marker;
}
}
if (boundary && dir === boundary) return undefined;
@@ -3898,69 +3902,42 @@ function findSettingsMarker(cwd: string | undefined): string | undefined {
return undefined;
}"#;
-/// Emit the `applyMarkerParams` TypeScript function shared verbatim by the
-/// OpenCode plugin and the OMP extension.
+/// Emit the `applyMarkerParams` TypeScript function shared by generated
+/// integrations.
///
-/// `None` reproduces the historical marker-only function byte-for-byte, so
-/// existing generated files and golden tests are unchanged. `Some(default)`
-/// prepends a `DEFAULT_PROJECT_STRATEGY` const and emits a variant that applies
-/// that install-time default when no marker pins a `project_strategy` (#128).
-/// A marker's own `project` / `project_strategy` still take precedence (§3.3),
-/// and repo-root is resolved host-side via `repoRootProject`.
+/// An install-time default applies only when no marker pins a
+/// `project_strategy` (#128). A marker's own `project` / `project_strategy`
+/// still take precedence (§3.3), and repo-root is resolved host-side via
+/// `repoRootProject`.
///
/// Scope/settings resolution walks past a capture-only marker to the nearest
/// ancestor marker that declares a setting (#668) via `findSettingsMarker`,
-/// emitted alongside this function.
-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_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) {
- applyIdentityParams(url, cwd, undefined, undefined, undefined, undefined);
- return;
- }
- url.searchParams.set("cwd", cwd);
- try {
- const body = readFileSync(marker, "utf8");
- const workspace = tomlKey(body, "workspace");
- const project = tomlKey(body, "project");
- 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");
- const briefing = tomlFlag(body, "inject_on_session_start");
- const briefingBudget = tomlFlag(body, "max_chars");
- const profileContribute = profileFlag(tomlFlag(body, "contribute"));
- 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);
- if (briefing) url.searchParams.set("briefing", briefing);
- if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
- if (profileContribute) url.searchParams.set("profile_contribute", profileContribute);
- if (profileConsume) url.searchParams.set("profile_consume", profileConsume);
- if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {
- const repoProject = repoRootProject(cwd);
- if (repoProject) url.searchParams.set("project", repoProject);
- }
- } catch (_e) {
- }
-}"#
- );
+/// emitted alongside this function. `discover_local_identity` controls whether
+/// an ordinary local marker may inspect git identity; aliases still request it,
+/// and operator-home routes always discover identity for route matching.
+pub(crate) fn ts_apply_marker_params(
+ default_strategy: Option<&str>,
+ discover_local_identity: bool,
+) -> String {
+ let default_line = default_strategy.map_or_else(String::new, |default| {
+ format!(
+ "const DEFAULT_PROJECT_STRATEGY = {};\n",
+ ts_string_literal(default)
+ )
+ });
+ let apply_default = default_strategy.map_or(
+ "",
+ |_| "if (!projectStrategy) projectStrategy = DEFAULT_PROJECT_STRATEGY;",
+ );
+ let apply_identity = if discover_local_identity {
+ "const remoteIdentity = applyIdentityParams(url, cwd, explicitIdentity, project, identityStyle, aliases);"
+ } else {
+ "const remoteIdentity = aliases ? applyIdentityParams(url, cwd, undefined, project, identityStyle, aliases) : false;"
};
- let body = r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
+ let body = r#"function applyMarkerParams(url: URL, cwd: string | undefined): boolean {
const managedRun = process.env.AI_MEMORY_RUN_ID;
if (managedRun) url.searchParams.set("managed_run", managedRun);
- if (!cwd) return;
+ if (!cwd) return true;
url.searchParams.set("cwd", cwd);
let workspace: string | undefined;
let project: string | undefined;
@@ -3974,12 +3951,47 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
let explicitIdentity: string | undefined;
let identityStyle: string | undefined;
let aliases: string | undefined;
- const marker = findSettingsMarker(cwd);
+ let projectSource: "marker" | "repo-root" | undefined;
+ let routed = false;
+ let marker = findSettingsMarker(cwd);
+ if (!marker || marker === join(homedir(), ".ai-memory.toml")) {
+ const homeMarker = join(homedir(), ".ai-memory.toml");
+ if (existsSync(homeMarker)) {
+ try {
+ const body = readHomeRouteText(homeMarker);
+ const routeIdentity = discoverRemoteIdentity(cwd);
+ const route = homeRoute(body, cwd, routeIdentity);
+ dropSubagent = tomlKey(body, "drop_subagent_captures");
+ defaultGlobal = tomlFlag(body, "default_global");
+ briefing = tomlFlag(body, "inject_on_session_start");
+ briefingBudget = tomlFlag(body, "max_chars");
+ profileContribute = profileFlag(tomlFlag(body, "contribute"));
+ profileConsume = profileFlag(tomlFlag(body, "consume"));
+ if (route) {
+ routed = true;
+ workspace = route.workspace;
+ project = route.project;
+ projectSource = "marker";
+ identityStyle = route.style;
+ aliases = routeIdentity ? route.aliases : undefined;
+ if (routeIdentity) {
+ url.searchParams.set("identity", routeIdentity);
+ url.searchParams.set("identity_src", "git_remote");
+ if (identityStyle === "path") url.searchParams.set("identity_style", "path");
+ }
+ marker = undefined;
+ } else marker = homeMarker;
+ } catch (_e) {
+ return false;
+ }
+ }
+ }
if (marker) {
try {
const body = readFileSync(marker, "utf8");
workspace = tomlKey(body, "workspace");
project = tomlKey(body, "project");
+ if (project) projectSource = "marker";
projectStrategy = tomlKey(body, "project_strategy");
dropSubagent = tomlKey(body, "drop_subagent_captures");
defaultGlobal = tomlFlag(body, "default_global");
@@ -3991,19 +4003,26 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
identityStyle = tomlKey(body, "identity_style");
aliases = markerAliases(body);
} catch (_e) {
+ return false;
}
}
- // Before repo-root can fill `project`: a repo-root name is an inference.
- 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 (!routed) {
+ __APPLY_IDENTITY__
+ if (aliases) url.searchParams.set("aliases", project && remoteIdentity ? aliases : "invalid");
+ } else if (aliases) {
+ url.searchParams.set("aliases", aliases);
+ }
+ __DEFAULT_LINE__
if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {
const repoProject = repoRootProject(cwd);
- if (repoProject) project = repoProject;
+ if (repoProject) {
+ project = repoProject;
+ projectSource = "repo-root";
+ }
}
if (workspace) url.searchParams.set("workspace", workspace);
if (project) url.searchParams.set("project", project);
- if (project) url.searchParams.set("project_src", "marker");
+ if (projectSource) url.searchParams.set("project_src", projectSource);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);
if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);
@@ -4011,10 +4030,12 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
if (profileContribute) url.searchParams.set("profile_contribute", profileContribute);
if (profileConsume) url.searchParams.set("profile_consume", profileConsume);
-}"#;
+ return true;
+}"#
+ .replace("__DEFAULT_LINE__", apply_default)
+ .replace("__APPLY_IDENTITY__", apply_identity);
format!(
- "const DEFAULT_PROJECT_STRATEGY = {};\n{TS_TOML_FLAG}\n{TS_FIND_SETTINGS_MARKER}\n{TS_IDENTITY}\n{body}",
- ts_string_literal(default)
+ "{default_line}{TS_TOML_FLAG}\n{TS_FIND_SETTINGS_MARKER}\n{TS_IDENTITY}\n{TS_HOME_ROUTES}\n{body}"
)
}
@@ -4102,6 +4123,27 @@ function identityStyleParam(style: string | undefined): string | undefined {
return style?.trim() === "path" ? "path" : undefined;
}
+function discoverRemoteIdentity(cwd: string | undefined): string | undefined {
+ if (!cwd) return undefined;
+ 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) return identity;
+ } catch (_e) {
+ }
+ }
+ return undefined;
+}
+
+function validNormalizedIdentity(value: string): boolean {
+ const host = value.split("/", 1)[0];
+ return /^[a-z0-9.-]+(?:\/[a-z0-9._-]+)+$/.test(value) && value === value.toLowerCase() && !host.startsWith(".") && !host.endsWith(".");
+}
+
function applyIdentityParams(
url: URL,
cwd: string | undefined,
@@ -4117,22 +4159,13 @@ function applyIdentityParams(
return false;
}
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`], {
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- });
- const identity = normalizeRemote(remote);
- if (identity) {
- url.searchParams.set("identity", identity);
- url.searchParams.set("identity_src", "git_remote");
- const forwarded = identityStyleParam(style);
- if (forwarded) url.searchParams.set("identity_style", forwarded);
- return true;
- }
- } catch (_e) {
- }
+ const identity = discoverRemoteIdentity(cwd);
+ if (identity) {
+ url.searchParams.set("identity", identity);
+ url.searchParams.set("identity_src", "git_remote");
+ const forwarded = identityStyleParam(style);
+ if (forwarded) url.searchParams.set("identity_style", forwarded);
+ return true;
}
return false;
}"#;
@@ -4142,6 +4175,126 @@ function applyIdentityParams(
/// true`, `max_chars = 4000`), so section-style marker keys work whether or
/// not the operator quotes the value. Emitted next to `applyMarkerParams`
/// in every generated TypeScript integration.
+pub(crate) const TS_HOME_ROUTES: &str = r##"type HomeRoute = { workspace: string; project: string; style?: string; aliases?: string };
+type RoutePath = { root: string; parts: string[] };
+
+function readHomeRouteText(file: string): string {
+ const expected = statSync(file).size;
+ if (expected > 65536) throw new Error("invalid home routes");
+ const fd = openSync(file, "r");
+ try {
+ const bytes = Buffer.allocUnsafe(expected + 1);
+ let count = 0;
+ while (count < bytes.length) {
+ const read = readSync(fd, bytes, count, bytes.length - count, count);
+ if (read === 0) break;
+ count += read;
+ }
+ if (count !== expected || count > 65536 || statSync(file).size !== expected) throw new Error("invalid home routes");
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, count));
+ } finally {
+ closeSync(fd);
+ }
+}
+
+function routePathParts(raw: string, home: string, bounded = true): RoutePath | undefined {
+ if (!raw || (bounded && Buffer.byteLength(raw, "utf8") > 512)) return undefined;
+ const homeRelative = raw.startsWith("~/");
+ if (homeRelative) {
+ let depth = 0;
+ for (const part of raw.slice(2).replace(/\\/g, "/").split("/")) {
+ if (!part || part === ".") continue;
+ if (part === "..") { if (depth === 0) return undefined; depth--; } else depth++;
+ }
+ }
+ let value = homeRelative ? home.replace(/[\\/]+$/, "") + "/" + raw.slice(2) : raw;
+ value = value.replace(/\\/g, "/");
+ let root = "";
+ let rest = "";
+ if (value.startsWith("//")) {
+ const parts = value.slice(2).split("/").filter(Boolean);
+ if (parts.length < 2) return undefined;
+ root = `unc:${parts.shift()!.toLowerCase()}/${parts.shift()!.toLowerCase()}`;
+ rest = parts.join("/");
+ } else if (/^[A-Za-z]:\//.test(value)) {
+ root = `drive:${value[0].toLowerCase()}`;
+ rest = value.slice(3);
+ } else if (value.startsWith("/")) {
+ root = "posix";
+ rest = value.slice(1);
+ } else return undefined;
+ const parts: string[] = [];
+ for (const part of rest.split("/")) {
+ if (!part || part === ".") continue;
+ if (part === "..") parts.pop(); else parts.push(root === "posix" ? part : part.toLowerCase());
+ }
+ return parts.length ? { root, parts } : undefined;
+}
+
+function homeRoute(text: string, cwd: string, identity: string | undefined): HomeRoute | undefined {
+ if (Buffer.byteLength(text, "utf8") > 65536) throw new Error("invalid home routes");
+ if (!/^\s*(?:\[routes|routes\s*=|routes\.|route_)/m.test(text)) return undefined;
+ const entries: Array<{ kind: string; selector: string; fields: Record<string, string> }> = [];
+ const rawSeen = new Set<string>();
+ let current: typeof entries[number] | undefined;
+ for (const line of text.split(/\r?\n/)) {
+ const trimmed = line.trim();
+ const header = /^\[routes\.(identity|path)\."([^"\\]+)"\]$/.exec(trimmed);
+ if (header) {
+ if (entries.length >= 64 || Buffer.byteLength(header[2], "utf8") > 512 || rawSeen.has(header[2])) throw new Error("invalid home routes");
+ rawSeen.add(header[2]);
+ current = { kind: header[1], selector: header[2], fields: {} };
+ entries.push(current);
+ continue;
+ }
+ if (trimmed.startsWith("[routes") || trimmed.startsWith("routes.") || /^routes\s*=/.test(trimmed) || (!current && trimmed.startsWith("route_"))) throw new Error("invalid home routes");
+ if (trimmed.startsWith("[")) { current = undefined; continue; }
+ if (!current) {
+ if (/^(workspace|project|project_strategy|drop_subagent_captures|identity|identity_style|server)\s*=/.test(trimmed) && !/^[A-Za-z0-9_]+\s*=\s*"[^"]*"$/.test(trimmed)) throw new Error("invalid home routes");
+ continue;
+ }
+ if (!trimmed || trimmed.startsWith("#")) continue;
+ const field = /^(route_workspace|route_project|route_identity_style|route_aliases)\s*=\s*(.*)$/.exec(trimmed);
+ if (!field || current.fields[field[1]] !== undefined || field[2].includes("\\")) throw new Error("invalid home routes");
+ current.fields[field[1]] = field[2];
+ }
+ const parsed: Array<{ kind: string; selector: string; route: HomeRoute; path?: RoutePath }> = [];
+ const normalizedPaths = new Set<string>();
+ for (const entry of entries) {
+ const str = (name: string) => {
+ const value = /^"([^"\\]+)"$/.exec(entry.fields[name] ?? "")?.[1];
+ return value && Buffer.byteLength(value, "utf8") <= 512 ? value : undefined;
+ };
+ const workspace = str("route_workspace");
+ const project = str("route_project");
+ if (!workspace || !project || Buffer.byteLength(workspace, "utf8") > 512 || Buffer.byteLength(project, "utf8") > 512 || !/^[a-z0-9][a-z0-9._-]*$/.test(workspace) || !/^[a-z0-9][a-z0-9._-]*$/.test(project)) throw new Error("invalid home routes");
+ const style = entry.fields.route_identity_style === undefined ? undefined : str("route_identity_style");
+ if (style !== undefined && style !== "path" && style !== "host_path") throw new Error("invalid home routes");
+ let aliases: string | undefined;
+ if (entry.fields.route_aliases !== undefined) {
+ if (!/^\[[^\]]*\]$/.test(entry.fields.route_aliases) || Buffer.byteLength(entry.fields.route_aliases, "utf8") > 512) throw new Error("invalid home routes");
+ aliases = markerAliases(`aliases = ${entry.fields.route_aliases}`);
+ if (aliases === "invalid") throw new Error("invalid home routes");
+ }
+ if (entry.kind === "identity" && !validNormalizedIdentity(entry.selector)) throw new Error("invalid home routes");
+ const path = entry.kind === "path" ? routePathParts(entry.selector, homedir()) : undefined;
+ if (entry.kind === "path") {
+ if (!path) throw new Error("invalid home routes");
+ const key = `${path.root}/${path.parts.join("/")}`;
+ if (normalizedPaths.has(key)) throw new Error("invalid home routes");
+ normalizedPaths.add(key);
+ }
+ parsed.push({ kind: entry.kind, selector: entry.selector, route: { workspace, project, style, aliases }, path });
+ }
+ const exact = parsed.find((entry) => entry.kind === "identity" && entry.selector === identity);
+ if (exact) return exact.route;
+ const target = routePathParts(cwd, homedir(), false);
+ if (!target) return undefined;
+ const matches = parsed.filter((entry) => entry.kind === "path" && entry.path?.root === target.root && entry.path.parts.length <= target.parts.length && entry.path.parts.every((part, index) => part === target.parts[index]));
+ matches.sort((a, b) => b.path!.parts.length - a.path!.parts.length);
+ return matches[0]?.route;
+}"##;
+
pub(crate) const TS_TOML_FLAG: &str = r#"function tomlFlag(text: string, key: string): string | undefined {
const re = new RegExp(`^\\s*${key}\\s*=\\s*(?:"([^"]*)"|([^#\\s]+))`);
for (const line of text.split(/\r?\n/)) {
@@ -4274,13 +4427,13 @@ fn add_hook_spooling(source: String) -> Result<String> {
"async function drainHookQueue(): Promise<void> {\n if (hookDraining) return;\n requestSpoolDrain();",
1,
);
- let import_anchor = "import { closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync } from \"node:fs\";";
+ let import_anchor = "import { closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync } from \"node:fs\";";
if out.matches(import_anchor).count() != 1 {
anyhow::bail!("TS integration template drifted: node:fs import anchor not unique");
}
out = out.replacen(
import_anchor,
- "import { closeSync, existsSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";",
+ "import { closeSync, existsSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";",
1,
);
Ok(out)
@@ -4295,7 +4448,7 @@ fn build_opencode_plugin(
let token_line = auth_token
.map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t)))
.unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());
- let apply_marker_params = ts_apply_marker_params(project_strategy);
+ let apply_marker_params = ts_apply_marker_params(project_strategy, true);
let capture_policy = ts_capture_policy_v1(capture_mode);
let timeout_signal = ts_timeout_signal();
let body = format!(
@@ -4306,7 +4459,7 @@ fn build_opencode_plugin(
import type {{ Plugin }} from "@opencode-ai/plugin";
import {{ execFileSync }} from "node:child_process";
-import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync }} from "node:fs";
+import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync }} from "node:fs";
import {{ basename, dirname, join, resolve, sep }} from "node:path";
import {{ homedir }} from "node:os";
@@ -4514,7 +4667,7 @@ function postHook(event: string, payload: Record<string, unknown>): void {{
const url = new URL(`${{SERVER}}/hook`);
url.searchParams.set("event", event);
url.searchParams.set("agent", AGENT);
- applyMarkerParams(url, typeof payload.cwd === "string" ? payload.cwd : undefined);
+ if (!applyMarkerParams(url, typeof payload.cwd === "string" ? payload.cwd : undefined)) return;
const policy = capturePolicy(payload, typeof payload.cwd === "string" ? payload.cwd : undefined);
if (policy.disposition === "drop") return;
try {{
@@ -4530,7 +4683,7 @@ async function fetchHandoff(cwd: string, id: string | undefined): Promise<string
url.searchParams.set("agent", AGENT);
url.searchParams.set("cwd", cwd);
if (id) url.searchParams.set("session_id", id);
- applyMarkerParams(url, cwd);
+ if (!applyMarkerParams(url, cwd)) return undefined;
try {{
const response = await fetch(url, {{
headers: authHeaders(),
@@ -5030,7 +5183,7 @@ fn build_omp_extension(
let token_line = auth_token
.map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t)))
.unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());
- let apply_marker_params = ts_apply_marker_params(project_strategy);
+ let apply_marker_params = ts_apply_marker_params(project_strategy, true);
let capture_policy = ts_capture_policy_v1(capture_mode);
let timeout_signal = ts_timeout_signal();
let body = format!(
@@ -5040,7 +5193,7 @@ fn build_omp_extension(
// re-run.
import {{ execFileSync }} from "node:child_process";
-import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync }} from "node:fs";
+import {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync }} from "node:fs";
import {{ basename, dirname, join, resolve, sep }} from "node:path";
import {{ homedir }} from "node:os";
@@ -5254,7 +5407,7 @@ function postHook(event: string, payload: Record<string, unknown>): void {{
const url = new URL(`${{SERVER}}/hook`);
url.searchParams.set("event", event);
url.searchParams.set("agent", AGENT);
- applyMarkerParams(url, typeof payload.cwd === "string" ? payload.cwd : undefined);
+ if (!applyMarkerParams(url, typeof payload.cwd === "string" ? payload.cwd : undefined)) return;
const policy = capturePolicy(payload, typeof payload.cwd === "string" ? payload.cwd : undefined);
if (policy.disposition === "drop") return;
try {{
@@ -5270,7 +5423,7 @@ async function fetchHandoff(cwd: string, id: string | undefined): Promise<string
url.searchParams.set("agent", AGENT);
url.searchParams.set("cwd", cwd);
if (id) url.searchParams.set("session_id", id);
- applyMarkerParams(url, cwd);
+ if (!applyMarkerParams(url, cwd)) return undefined;
try {{
const response = await fetch(url, {{
headers: authHeaders(),
@@ -9575,7 +9728,7 @@ model = "gpt-5"
// capture-only marker does not shadow an outer marker's scope.
assert!(plugin.contains("function findSettingsMarker"));
assert!(plugin.contains("function declaresSettings"));
- assert!(plugin.contains("const marker = findSettingsMarker(cwd);"));
+ assert!(plugin.contains("let marker = findSettingsMarker(cwd);"));
assert!(plugin.contains(
"for (const key of [\"workspace\", \"project\", \"project_strategy\", \"drop_subagent_captures\", \"identity\", \"identity_style\"])"
));
@@ -9583,13 +9736,11 @@ model = "gpt-5"
assert!(plugin.contains(
"for (const key of [\"default_global\", \"inject_on_session_start\", \"max_chars\", \"contribute\", \"consume\"])"
));
- assert!(
- plugin.contains("if (declaresSettings(readFileSync(marker, \"utf8\"))) return marker;")
- );
+ assert!(plugin.contains("if (declaresSettings(text)) return marker;"));
assert!(plugin.contains(
- "applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"
+ "if (!applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined)) return;"
));
- assert!(plugin.contains("applyMarkerParams(url, cwd);"));
+ assert!(plugin.contains("if (!applyMarkerParams(url, cwd)) return undefined;"));
assert!(plugin.contains("postPreCompact"));
assert!(plugin.contains("dispose: async () =>"));
assert!(plugin.contains("const HOOK_DISPOSE_DRAIN_BUDGET_MS = 2000;"));
@@ -9632,7 +9783,8 @@ model = "gpt-5"
plugin
.contains("projectStrategy === \"repo-root\" || projectStrategy === \"repo_root\"")
);
- assert!(plugin.contains("url.searchParams.set(\"project\", repoProject)"));
+ assert!(plugin.contains("project = repoProject;"));
+ assert!(plugin.contains("projectSource = \"repo-root\";"));
}
#[test]
@@ -9909,11 +10061,12 @@ model = "gpt-5"
"must apply the default when a marker pins no strategy: {plugin}"
);
assert!(
- plugin.contains("if (repoProject) project = repoProject;"),
+ plugin.contains("project = repoProject;")
+ && plugin.contains("projectSource = \"repo-root\";"),
"{plugin}"
);
assert!(
- plugin.contains("const marker = findSettingsMarker(cwd);"),
+ plugin.contains("let marker = findSettingsMarker(cwd);"),
"the default-strategy variant must also walk past a capture-only marker (#668): {plugin}"
);
}
@@ -10038,15 +10191,12 @@ model = "gpt-5"
// not shadow an outer marker's scope for the OMP/pi extensions.
assert!(extension.contains("function findSettingsMarker"));
assert!(extension.contains("function declaresSettings"));
- assert!(extension.contains("const marker = findSettingsMarker(cwd);"));
- assert!(
- extension
- .contains("if (declaresSettings(readFileSync(marker, \"utf8\"))) return marker;")
- );
+ assert!(extension.contains("let marker = findSettingsMarker(cwd);"));
+ assert!(extension.contains("if (declaresSettings(text)) return marker;"));
assert!(extension.contains(
- "applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"
+ "if (!applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined)) return;"
));
- assert!(extension.contains("applyMarkerParams(url, cwd);"));
+ assert!(extension.contains("if (!applyMarkerParams(url, cwd)) return undefined;"));
assert!(extension.contains("Bearer ${token}"));
assert!(extension.contains("tok"));
assert!(
@@ -10064,7 +10214,8 @@ model = "gpt-5"
extension
.contains("projectStrategy === \"repo-root\" || projectStrategy === \"repo_root\"")
);
- assert!(extension.contains("url.searchParams.set(\"project\", repoProject)"));
+ assert!(extension.contains("project = repoProject;"));
+ assert!(extension.contains("projectSource = \"repo-root\";"));
// #676: pi/omp await session_shutdown's dispose flush instead of
// returning immediately, so the runtime teardown that follows a sync
// handler no longer kills the in-flight session-end fetch.
@@ -10100,7 +10251,7 @@ model = "gpt-5"
"{extension}"
);
assert!(
- extension.contains("const marker = findSettingsMarker(cwd);"),
+ extension.contains("let marker = findSettingsMarker(cwd);"),
"the default-strategy variant must also walk past a capture-only marker (#668): {extension}"
);
}
@@ -12780,6 +12931,46 @@ mod identity_parity_tests {
.collect()
}
+ fn home_route_cases() -> Vec<serde_json::Value> {
+ let cases: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../ai-memory-core/fixtures/home_route_cases.json"
+ ))
+ .unwrap();
+ cases["cases"].as_array().unwrap().clone()
+ }
+
+ fn expanded_route_case(case: &serde_json::Value, home: &std::path::Path) -> (String, String) {
+ let text = match case["generate"].as_str() {
+ Some("65_routes") => (0..65)
+ .map(|index| format!("[routes.path.\"/route/{index}\"]\nroute_workspace=\"ws\"\nroute_project=\"p{index}\"\n"))
+ .collect(),
+ Some("selector_512") => format!(
+ "[routes.path.\"/{}\"]\nroute_workspace=\"bounds\"\nroute_project=\"valid\"\n",
+ "a".repeat(511)
+ ),
+ Some("selector_513") => format!(
+ "[routes.path.\"/{}\"]\nroute_workspace=\"bounds\"\nroute_project=\"invalid\"\n",
+ "a".repeat(512)
+ ),
+ Some("oversized_file") => format!("#{}\n", "x".repeat(65_536)),
+ Some(other) => panic!("unknown route fixture generator {other}"),
+ None => case["toml"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", home.to_str().unwrap())
+ .replace("{{LONG_513}}", &"a".repeat(513)),
+ };
+ let cwd = match case["cwd_generate"].as_str() {
+ Some("selector_512_child") => format!("/{}/child", "a".repeat(511)),
+ Some(other) => panic!("unknown cwd fixture generator {other}"),
+ None => case["cwd"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", home.to_str().unwrap()),
+ };
+ (text, cwd)
+ }
+
fn alias_cases() -> Vec<(String, Option<String>)> {
let cases: serde_json::Value = serde_json::from_str(CASES).unwrap();
cases["marker_aliases"]
@@ -13005,6 +13196,286 @@ mod identity_parity_tests {
);
}
+ #[test]
+ fn shell_home_route_runtime_fixture_agrees() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ std::fs::create_dir_all(&home).unwrap();
+ for case in home_route_cases() {
+ let (text, cwd) = expanded_route_case(&case, &home);
+ let marker = home.join(".ai-memory.toml");
+ std::fs::write(&marker, text).unwrap();
+ let output = Command::new("sh")
+ .arg("-c")
+ .arg(r#". "$1"; _amhome="$2"; ai_memory_home_route "$3" "$4" "$5""#)
+ .arg("sh")
+ .arg(repo_file("hooks/_lib.sh"))
+ .arg(&home)
+ .arg(&marker)
+ .arg(&cwd)
+ .arg(case["identity"].as_str().unwrap_or(""))
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let result = String::from_utf8(output.stdout).unwrap();
+ let status = case["status"].as_str().unwrap();
+ let expected = match status {
+ "valid" => format!(
+ "{}\u{1c}{}",
+ case["workspace"].as_str().unwrap(),
+ case["project"].as_str().unwrap()
+ ),
+ "invalid" => "invalid".to_owned(),
+ "none" => String::new(),
+ status => panic!("unknown fixture status {status}"),
+ };
+ assert!(
+ result.starts_with(&expected),
+ "{}: {result:?}",
+ case["name"]
+ );
+ }
+ }
+
+ #[test]
+ fn portable_home_route_runtime_fixture_agrees() {
+ 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 home = tmp.path().join("home");
+ std::fs::create_dir_all(&home).unwrap();
+ let cases = home_route_cases();
+ let input = cases
+ .iter()
+ .map(|case| {
+ let (text, cwd) = expanded_route_case(case, &home);
+ serde_json::json!({
+ "name": case["name"],
+ "text": text,
+ "cwd": cwd,
+ "identity": case["identity"],
+ "status": case["status"],
+ "workspace": case["workspace"],
+ "project": case["project"]
+ })
+ })
+ .collect::<Vec<_>>();
+ let module = tmp.path().join("home-route-fixture.ts");
+ let source = format!(
+ "import {{ closeSync, openSync, readSync, statSync }} from \"node:fs\";\nimport {{ homedir }} from \"node:os\";\nfunction markerAliases(text:string):string|undefined{{const m=/^aliases\\s*=\\s*\\[([^\\]]*)\\]\\s*$/.exec(text);if(!m)return \"invalid\";if(!m[1].trim())return undefined;const out:string[]=[];const p=m[1].split(\",\");if(p.length>16)return \"invalid\";for(const r of p){{if(r.includes(\"\\\\\"))return \"invalid\";const x=/^\\s*\"([^\"]*)\"\\s*$/.exec(r);if(!x)return \"invalid\";const v=x[1].trim();if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(v)||Buffer.byteLength(v)>128)return \"invalid\";if(!out.includes(v))out.push(v);}}return JSON.stringify(out);}}\nfunction validNormalizedIdentity(value:string):boolean{{const host=value.split(\"/\",1)[0];return /^[a-z0-9.-]+(?:\\/[a-z0-9._-]+)+$/.test(value)&&value===value.toLowerCase()&&!host.startsWith(\".\")&&!host.endsWith(\".\");}}\n{}\nconst cases={} as any[];for(const c of cases){{try{{const r=homeRoute(c.text,c.cwd,c.identity);process.stdout.write(`${{c.name}}:${{r?r.workspace+\"/\"+r.project:\"none\"}}\\n`);}}catch{{process.stdout.write(`${{c.name}}:invalid\\n`);}}}}",
+ super::TS_HOME_ROUTES,
+ serde_json::to_string(&input).unwrap()
+ );
+ std::fs::write(&module, source).unwrap();
+ let output = Command::new("node")
+ .args(["--experimental-strip-types", "--no-warnings"])
+ .arg(&module)
+ .env("HOME", &home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let lines = String::from_utf8(output.stdout).unwrap();
+ for case in &input {
+ let expected = match case["status"].as_str().unwrap() {
+ "valid" => format!(
+ "{}/{}",
+ case["workspace"].as_str().unwrap(),
+ case["project"].as_str().unwrap()
+ ),
+ status => status.to_owned(),
+ };
+ assert!(
+ lines
+ .lines()
+ .any(|line| line == format!("{}:{expected}", case["name"].as_str().unwrap())),
+ "{}: {lines}",
+ case["name"]
+ );
+ }
+ }
+
+ #[test]
+ fn generated_typescript_applies_home_identity_route_with_alias_provenance() {
+ 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 home = tmp.path().join("home");
+ let repo = tmp.path().join("outside/repo");
+ std::fs::create_dir_all(&home).unwrap();
+ 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(home.join(".ai-memory.toml"), "[routes.identity.\"github.com/acme/api\"]\nroute_workspace=\"oss\"\nroute_project=\"acme-api\"\nroute_identity_style=\"path\"\nroute_aliases=[\"main\"]\n[routes.path.\"/outside\"]\nroute_workspace=\"wrong\"\nroute_project=\"wrong\"\n").unwrap();
+ let module = tmp.path().join("home-route.ts");
+ let source = format!(
+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync, readSync, statSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\n{}\n{}\nconst url=new URL(\"http://h/hook\"); applyMarkerParams(url, {}); process.stdout.write(url.search);",
+ super::TS_REPO_ROOT_PROJECT,
+ super::ts_apply_marker_params(None, true),
+ 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", &home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let query = String::from_utf8(output.stdout).unwrap();
+ assert!(query.contains("workspace=oss"), "{query}");
+ assert!(query.contains("project=acme-api"), "{query}");
+ assert!(query.contains("project_src=marker"), "{query}");
+ assert!(
+ query.contains("identity=github.com%2Facme%2Fapi"),
+ "{query}"
+ );
+ assert!(query.contains("identity_style=path"), "{query}");
+ assert!(query.contains("aliases=%5B%22main%22%5D"), "{query}");
+ }
+
+ #[test]
+ fn generated_typescript_non_git_home_path_route_omits_aliases() {
+ if !Command::new("node")
+ .args(["--experimental-strip-types", "-e", "0"])
+ .output()
+ .is_ok_and(|out| out.status.success())
+ {
+ return;
+ }
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = home.join("src/api");
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ home.join(".ai-memory.toml"),
+ "[routes.path.\"~/src/api\"]\nroute_workspace=\"path\"\nroute_project=\"api\"\nroute_aliases=[\"old-api\"]\n",
+ )
+ .unwrap();
+ let module = tmp.path().join("home-route-no-remote.ts");
+ let source = format!(
+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync, readSync, statSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\n{}\n{}\nconst url=new URL(\"http://h/hook\");applyMarkerParams(url,{});process.stdout.write(url.search);",
+ super::TS_REPO_ROOT_PROJECT,
+ super::ts_apply_marker_params(None, true),
+ 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", &home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let query = String::from_utf8(output.stdout).unwrap();
+ assert!(query.contains("workspace=path"), "{query}");
+ assert!(query.contains("project=api"), "{query}");
+ assert!(!query.contains("aliases="), "{query}");
+ assert!(!query.contains("identity_src="), "{query}");
+ }
+
+ #[test]
+ fn generated_typescript_default_repo_root_sets_derived_provenance() {
+ if !Command::new("node")
+ .args(["--experimental-strip-types", "-e", "0"])
+ .output()
+ .is_ok_and(|out| out.status.success())
+ {
+ return;
+ }
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = tmp.path().join("derived-project");
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::create_dir_all(&repo).unwrap();
+ assert!(
+ Command::new("git")
+ .args(["init", "-q"])
+ .current_dir(&repo)
+ .status()
+ .unwrap()
+ .success()
+ );
+ let module = tmp.path().join("repo-root-provenance.ts");
+ let source = format!(
+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync, readSync, statSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\n{}\n{}\nconst url=new URL(\"http://h/hook\");applyMarkerParams(url,{});process.stdout.write(url.search);",
+ super::TS_REPO_ROOT_PROJECT,
+ super::ts_apply_marker_params(Some("repo-root"), true),
+ 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", &home)
+ .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("derived-project")
+ );
+ assert_eq!(
+ params.get("project_src").map(String::as_str),
+ Some("repo-root")
+ );
+ assert_eq!(
+ params.get("project_strategy").map(String::as_str),
+ Some("repo-root")
+ );
+ }
+
#[test]
fn generated_typescript_applies_marker_alias_params_together() {
let strips_types = Command::new("node")
@@ -13047,7 +13518,7 @@ mod identity_parity_tests {
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 {{ closeSync, existsSync, openSync, readFileSync, readSync, statSync }} 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\
@@ -13064,7 +13535,7 @@ mod identity_parity_tests {
applyMarkerParams(url, {});\n\
process.stdout.write(url.search);\n",
super::TS_REPO_ROOT_PROJECT,
- super::ts_apply_marker_params(default_strategy),
+ super::ts_apply_marker_params(default_strategy, true),
serde_json::to_string(&repo.to_string_lossy()).unwrap(),
);
std::fs::write(&module, source).unwrap();
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index ba0228bd..8f1fdd9f 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -166,7 +166,7 @@ pub(crate) fn resolve_scope(
config,
explicit_ws,
explicit_proj,
- marker_scope(config),
+ marker_scope(config)?,
true,
)
}
@@ -240,7 +240,8 @@ pub(crate) fn resolve_scope_with_marker(
}
/// Resolve `(workspace, project)` for an explicit local directory without
-/// changing the process working directory or consulting wrapper cwd overrides.
+/// changing the process working directory, resolving symlinks, or consulting
+/// wrapper cwd overrides.
///
/// The policy matches [`resolve_scope`]: a marker may pin either half, an
/// unpinned project under a marker follows that marker's strategy, and a tree
@@ -249,11 +250,15 @@ pub(crate) fn resolve_scope_for_path(
config: &Config,
cwd: &std::path::Path,
) -> Result<(String, String)> {
- let cwd = cwd
- .canonicalize()
- .with_context(|| format!("canonicalizing project candidate {}", cwd.display()))?;
+ if !cwd.exists() {
+ return Err(anyhow!(
+ "project candidate does not exist: {}",
+ cwd.display()
+ ));
+ }
+ let cwd = crate::marker::absolute_normalized(cwd);
let identity = cwd.to_string_lossy().into_owned();
- let marker = crate::marker::read_scope(&identity, &config.runtime_env);
+ let marker = crate::marker::read_scope(&identity, &config.runtime_env)?;
let workspace = marker
.as_ref()
.and_then(|scope| scope.workspace.clone())
@@ -288,11 +293,11 @@ pub(crate) fn resolve_scope_for_path(
/// deliberately absent (`embed --force` fans out across every project in the
/// workspace). Resolving the pair there would make the command fail on the
/// cwd-derived project name it is about to throw away.
-pub(crate) fn resolve_workspace(config: &Config, explicit_ws: Option<&str>) -> String {
+pub(crate) fn resolve_workspace(config: &Config, explicit_ws: Option<&str>) -> Result<String> {
if let Some(explicit) = explicit_ws.filter(|s| !s.is_empty()) {
- return explicit.to_string();
+ return Ok(explicit.to_string());
}
- match marker_scope(config) {
+ Ok(match marker_scope(config)? {
Some((scope, _, _)) => match scope.workspace {
Some(declared) => {
eprintln!(
@@ -304,14 +309,20 @@ pub(crate) fn resolve_workspace(config: &Config, explicit_ws: Option<&str>) -> S
None => crate::config::DEFAULT_WORKSPACE.to_string(),
},
None => crate::config::DEFAULT_WORKSPACE.to_string(),
- }
+ })
}
/// The nearest scope-declaring marker plus the cwd the walk started from.
-fn marker_scope(config: &Config) -> Option<(crate::marker::MarkerScope, String, String)> {
- let (identity_cwd, lookup_cwd) = scope_directories(config)?;
- let scope = crate::marker::read_scope(&lookup_cwd, &config.runtime_env)?;
- Some((scope, identity_cwd, lookup_cwd))
+fn marker_scope(config: &Config) -> Result<Option<(crate::marker::MarkerScope, String, String)>> {
+ let Some((identity_cwd, lookup_cwd)) = scope_directories(config) else {
+ return Ok(None);
+ };
+ let Some(scope) =
+ crate::marker::read_scope_for(&lookup_cwd, &identity_cwd, &config.runtime_env)?
+ else {
+ return Ok(None);
+ };
+ Ok(Some((scope, identity_cwd, lookup_cwd)))
}
pub(crate) fn scope_directories(config: &Config) -> Option<(String, String)> {
@@ -512,6 +523,72 @@ mod tests {
/// workspace used to resolve into `default` for every CLI command, while
/// the lifecycle hooks — the only marker reader at the time — sent that
/// same checkout's captures to the declared workspace.
+ #[test]
+ fn explicit_scope_wins_over_home_route_and_home_route_beats_fallback() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = tmp.path().join("outside/repo");
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ home.join(".ai-memory.toml"),
+ format!(
+ "[routes.path.\"{}\"]\nroute_workspace=\"oss\"\nroute_project=\"acme-api\"\n",
+ repo.display()
+ ),
+ )
+ .unwrap();
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_and_home_for_tests(
+ repo.to_string_lossy(),
+ home.to_string_lossy(),
+ ),
+ ..Config::default()
+ };
+ assert_eq!(
+ resolve_scope(&config, None, None).unwrap(),
+ ("oss".into(), "acme-api".into())
+ );
+ assert_eq!(
+ resolve_scope(&config, Some("cli"), Some("explicit")).unwrap(),
+ ("cli".into(), "explicit".into())
+ );
+ }
+
+ #[test]
+ fn invalid_home_routes_refuse_unscoped_and_partial_cli_but_explicit_pair_bypasses() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = tmp.path().join("outside/repo");
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ home.join(".ai-memory.toml"),
+ "workspace=\"wrong\"\nproject=\"wrong\"\n[routes.path.\"relative\"]\nroute_workspace=\"route\"\nroute_project=\"route\"\n",
+ )
+ .unwrap();
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_and_home_for_tests(
+ repo.to_string_lossy(),
+ home.to_string_lossy(),
+ ),
+ ..Config::default()
+ };
+ assert!(resolve_scope(&config, None, None).is_err());
+ assert!(resolve_scope(&config, Some("explicit"), None).is_err());
+ assert!(resolve_scope(&config, None, Some("explicit")).is_err());
+ assert_eq!(
+ resolve_scope(&config, Some("cli"), Some("explicit")).unwrap(),
+ ("cli".into(), "explicit".into())
+ );
+ std::fs::write(home.join(".ai-memory.toml"), "x".repeat(65_537)).unwrap();
+ assert!(resolve_scope(&config, None, None).is_err());
+ assert_eq!(
+ resolve_scope(&config, Some("cli"), Some("explicit")).unwrap(),
+ ("cli".into(), "explicit".into())
+ );
+ }
+
#[test]
fn resolve_scope_takes_the_workspace_from_the_marker() {
let tmp = tempfile::TempDir::new().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index 4b601775..3eaaff6e 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -208,132 +208,16 @@ pub(crate) fn manifest_json() -> String {
+ "\n"
}
-/// Emit the OpenClaw plugin's `applyMarkerParams` TypeScript function.
+/// Emit OpenClaw's `applyMarkerParams` TypeScript from the shared generator.
///
-/// `None` reproduces the historical marker-only function byte-for-byte (the
-/// OpenClaw variant always sets `cwd`, even with no marker). `Some(default)`
-/// prepends a `DEFAULT_PROJECT_STRATEGY` const and applies that install-time
-/// default when no marker pins a `project_strategy` (#128); a marker's own
-/// `project` / `project_strategy` still win (§3.3). Mirrors the opencode/omp
-/// `ts_apply_marker_params` in `install_hooks.rs`.
-///
-/// Scope/settings resolution walks past a capture-only marker to the nearest
-/// ancestor marker that declares a setting (#668) via `findSettingsMarker`
-/// (`TS_FIND_SETTINGS_MARKER`, shared with `ts_apply_marker_params` so both
-/// copies stay equivalent).
+/// OpenClaw omits managed-run forwarding and preserves its historical rule
+/// that ordinary local markers inspect repository identity only when aliases
+/// require it. Operator-home routes may still inspect identity for selection.
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{identity}\n{}",
- r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
- if (!cwd) return;
- url.searchParams.set("cwd", cwd);
- const marker = findSettingsMarker(cwd);
- if (!marker) return;
- try {
- 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");
- const briefing = tomlFlag(body, "inject_on_session_start");
- const briefingBudget = tomlFlag(body, "max_chars");
- const profileContribute = profileFlag(tomlFlag(body, "contribute"));
- const profileConsume = profileFlag(tomlFlag(body, "consume"));
- if (workspace) url.searchParams.set("workspace", workspace);
- if (project) url.searchParams.set("project", project);
- // `project_src` tells the server a marker rescope from a host-derived
- // repo-root name; only the latter yields to sticky routing (#394).
- 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);
- if (briefing) url.searchParams.set("briefing", briefing);
- if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
- if (profileContribute) url.searchParams.set("profile_contribute", profileContribute);
- if (profileConsume) url.searchParams.set("profile_consume", profileConsume);
- if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {
- const repoProject = repoRootProject(cwd);
- if (repoProject) {
- url.searchParams.set("project", repoProject);
- url.searchParams.set("project_src", "repo-root");
- }
- }
- } catch (_e) {
- }
-}"#
- );
- };
- let body = r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
- if (!cwd) return;
- url.searchParams.set("cwd", cwd);
- let workspace: string | undefined;
- let project: string | undefined;
- let projectStrategy: string | undefined;
- let dropSubagent: string | undefined;
- let defaultGlobal: string | undefined;
- let briefing: string | undefined;
- 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 {
- const body = readFileSync(marker, "utf8");
- workspace = tomlKey(body, "workspace");
- project = tomlKey(body, "project");
- projectStrategy = tomlKey(body, "project_strategy");
- dropSubagent = tomlKey(body, "drop_subagent_captures");
- defaultGlobal = tomlFlag(body, "default_global");
- briefing = tomlFlag(body, "inject_on_session_start");
- 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;
- if (!projectStrategy) projectStrategy = DEFAULT_PROJECT_STRATEGY;
- if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {
- const repoProject = repoRootProject(cwd);
- if (repoProject) {
- project = repoProject;
- projectSrc = "repo-root";
- }
- }
- if (workspace) url.searchParams.set("workspace", workspace);
- if (project) url.searchParams.set("project", project);
- if (projectSrc) url.searchParams.set("project_src", projectSrc);
- if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
- if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);
- if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);
- if (briefing) url.searchParams.set("briefing", briefing);
- if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
- if (profileContribute) url.searchParams.set("profile_contribute", profileContribute);
- if (profileConsume) url.searchParams.set("profile_consume", profileConsume);
-}"#;
- format!(
- "const DEFAULT_PROJECT_STRATEGY = {};\n{toml_flag}\n{find_settings_marker}\n{identity}\n{body}",
- ts_string_literal(default)
+ super::install_hooks::ts_apply_marker_params(default_strategy, false).replacen(
+ " const managedRun = process.env.AI_MEMORY_RUN_ID;\n if (managedRun) url.searchParams.set(\"managed_run\", managedRun);\n",
+ "",
+ 1,
)
}
@@ -356,7 +240,7 @@ fn build_plugin(
import {{ definePluginEntry }} from "openclaw/plugin-sdk/plugin-entry";
import {{ execFileSync }} from "node:child_process";
-import {{ closeSync, existsSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, renameSync, unlinkSync, writeFileSync }} from "node:fs";
+import {{ closeSync, existsSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync }} from "node:fs";
import {{ basename, dirname, join, resolve, sep }} from "node:path";
import {{ homedir }} from "node:os";
@@ -494,7 +378,7 @@ function postPreCompact(event: any, ctx: any): void {{
const url = new URL(`${{SERVER}}/hook`);
url.searchParams.set("event", eventName);
url.searchParams.set("agent", AGENT);
- applyMarkerParams(url, typeof body.cwd === "string" ? body.cwd : undefined);
+ if (!applyMarkerParams(url, typeof body.cwd === "string" ? body.cwd : undefined)) return;
const policy = capturePolicy(body, typeof body.cwd === "string" ? body.cwd : undefined);
if (policy.disposition === "drop") return;
try {{
@@ -527,7 +411,7 @@ async function fetchHandoff(event: any, ctx: any): Promise<string | undefined> {
if (captureServerRouted(currentCwd)) return undefined;
const url = new URL(`${{SERVER}}/handoff`);
url.searchParams.set("agent", AGENT);
- applyMarkerParams(url, currentCwd);
+ if (!applyMarkerParams(url, currentCwd)) return undefined;
try {{
const response = await fetch(url, {{
headers: authHeaders(),
@@ -694,10 +578,8 @@ mod tests {
// outer marker's scope here either.
assert!(plugin.contains("function findSettingsMarker"));
assert!(plugin.contains("function declaresSettings"));
- assert!(plugin.contains("const marker = findSettingsMarker(cwd);"));
- assert!(
- plugin.contains("if (declaresSettings(readFileSync(marker, \"utf8\"))) return marker;")
- );
+ assert!(plugin.contains("let marker = findSettingsMarker(cwd);"));
+ assert!(plugin.contains("if (declaresSettings(text)) return marker;"));
assert!(plugin.contains("import { execFileSync } from \"node:child_process\";"));
assert!(
plugin.contains("import { basename, dirname, join, resolve, sep } from \"node:path\";")
@@ -712,11 +594,12 @@ mod tests {
plugin
.contains("projectStrategy === \"repo-root\" || projectStrategy === \"repo_root\"")
);
- assert!(plugin.contains("url.searchParams.set(\"project\", repoProject)"));
+ assert!(plugin.contains("project = repoProject;"));
+ assert!(plugin.contains("projectSource = \"repo-root\";"));
assert!(plugin.contains(
- "applyMarkerParams(url, typeof body.cwd === \"string\" ? body.cwd : undefined);"
+ "if (!applyMarkerParams(url, typeof body.cwd === \"string\" ? body.cwd : undefined)) return;"
));
- assert!(plugin.contains("applyMarkerParams(url, currentCwd);"));
+ assert!(plugin.contains("if (!applyMarkerParams(url, currentCwd)) return undefined;"));
assert!(plugin.contains("fetchHandoff"));
assert!(plugin.contains("// capture-policy-v1 (generated; do not fork between adapters)"));
assert!(plugin.contains("const policy = capturePolicy(body"));
@@ -751,25 +634,355 @@ mod tests {
"must apply the default when a marker pins no strategy: {plugin}"
);
assert!(
- plugin.contains("const marker = findSettingsMarker(cwd);"),
+ plugin.contains("let marker = findSettingsMarker(cwd);"),
"the default-strategy variant must also walk past a capture-only marker (#668): {plugin}"
);
}
#[test]
- fn openclaw_identity_discovery_is_alias_gated() {
+ fn openclaw_executes_shared_home_route_runtime() {
+ if !std::process::Command::new("node")
+ .args(["--experimental-strip-types", "-e", "0"])
+ .output()
+ .is_ok_and(|output| output.status.success())
+ {
+ return;
+ }
+ let tmp = TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo_root = home.join("src/api");
+ let repo = repo_root.join("lib");
+ std::fs::create_dir_all(&repo).unwrap();
+ assert!(
+ std::process::Command::new("git")
+ .args(["init", "-q"])
+ .current_dir(&repo_root)
+ .status()
+ .unwrap()
+ .success()
+ );
+ assert!(
+ std::process::Command::new("git")
+ .args(["remote", "add", "origin", "[email protected]:acme/api.git"])
+ .current_dir(&repo_root)
+ .status()
+ .unwrap()
+ .success()
+ );
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../ai-memory-core/fixtures/home_route_cases.json"
+ ))
+ .unwrap();
+ let text = fixture["cases"][0]["toml"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", &home.to_string_lossy());
+ std::fs::write(home.join(".ai-memory.toml"), text).unwrap();
+ let module = tmp.path().join("openclaw-route.ts");
+ let plugin = build_plugin("http://127.0.0.1:49374", None, None, "denylist");
+ let helpers = plugin
+ .split_once("function tomlFlag")
+ .unwrap()
+ .1
+ .split_once("function postHook")
+ .unwrap()
+ .0;
+ let source = format!(
+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst routeCwd={1};const direct=homeRoute(readHomeRouteText(join(homedir(),\".ai-memory.toml\")),routeCwd,\"github.com/acme/api\");const url=new URL(\"http://h/hook\");const ok=applyMarkerParams(url,routeCwd);process.stdout.write((direct?.project??\"none\")+\":\"+String(ok)+url.search);",
+ helpers,
+ serde_json::to_string(&repo.to_string_lossy()).unwrap()
+ );
+ std::fs::write(&module, source).unwrap();
+ let output = std::process::Command::new("node")
+ .args(["--experimental-strip-types", "--no-warnings"])
+ .arg(&module)
+ .env("HOME", &home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let query = String::from_utf8(output.stdout).unwrap();
+ assert!(query.starts_with("identity-api:true?cwd="), "{query}");
+ for expected in [
+ "workspace=identity",
+ "project=identity-api",
+ "identity=github.com%2Facme%2Fapi",
+ "identity_src=git_remote",
+ "identity_style=path",
+ "aliases=%5B%22main%22%5D",
+ "drop_subagent=true",
+ "default_global=true",
+ "briefing=true",
+ "briefing_budget=3210",
+ "profile_consume=0",
+ ] {
+ assert!(query.contains(expected), "{expected}: {query}");
+ }
+ }
+
+ #[test]
+ fn openclaw_executes_every_shared_home_route_fixture() {
+ if !std::process::Command::new("node")
+ .args(["--experimental-strip-types", "-e", "0"])
+ .output()
+ .is_ok_and(|output| output.status.success())
+ {
+ return;
+ }
+ let tmp = TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ std::fs::create_dir_all(&home).unwrap();
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../ai-memory-core/fixtures/home_route_cases.json"
+ ))
+ .unwrap();
+ let cases = fixture["cases"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|case| {
+ let text = match case["generate"].as_str() {
+ Some("65_routes") => (0..65)
+ .map(|index| format!("[routes.path.\"/route/{index}\"]\nroute_workspace=\"ws\"\nroute_project=\"p{index}\"\n"))
+ .collect(),
+ Some("selector_512") => format!("[routes.path.\"/{}\"]\nroute_workspace=\"bounds\"\nroute_project=\"valid\"\n", "a".repeat(511)),
+ Some("selector_513") => format!("[routes.path.\"/{}\"]\nroute_workspace=\"bounds\"\nroute_project=\"invalid\"\n", "a".repeat(512)),
+ Some("oversized_file") => format!("#{}\n", "x".repeat(65_536)),
+ Some(other) => panic!("unknown fixture generator {other}"),
+ None => case["toml"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", &home.to_string_lossy())
+ .replace("{{LONG_513}}", &"a".repeat(513)),
+ };
+ let mut cwd = match case["cwd_generate"].as_str() {
+ Some("selector_512_child") => format!("/{}/child", "a".repeat(511)),
+ Some(other) => panic!("unknown cwd fixture generator {other}"),
+ None => case["cwd"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", &home.to_string_lossy()),
+ };
+ if let Some(identity) = case["identity"].as_str() {
+ let repo = home
+ .join("fixture-repos")
+ .join(case["name"].as_str().unwrap());
+ std::fs::create_dir_all(&repo).unwrap();
+ assert!(
+ std::process::Command::new("git")
+ .args(["init", "-q"])
+ .current_dir(&repo)
+ .status()
+ .unwrap()
+ .success()
+ );
+ assert!(
+ std::process::Command::new("git")
+ .args([
+ "remote",
+ "add",
+ "origin",
+ &format!("https://{identity}.git"),
+ ])
+ .current_dir(&repo)
+ .status()
+ .unwrap()
+ .success()
+ );
+ cwd = repo.to_string_lossy().into_owned();
+ } else if cwd.starts_with(&*home.to_string_lossy()) {
+ std::fs::create_dir_all(&cwd).unwrap();
+ }
+ serde_json::json!({
+ "name": case["name"],
+ "text": text,
+ "cwd": cwd,
+ "identity": case["identity"],
+ "status": case["status"],
+ "source": case["source"],
+ "workspace": case["workspace"],
+ "project": case["project"],
+ "style": case["style"],
+ "aliases": case["aliases"],
+ "flags": case["flags"]
+ })
+ })
+ .collect::<Vec<_>>();
+ let plugin = build_plugin("http://127.0.0.1:49374", None, None, "denylist");
+ let helpers = plugin
+ .split_once("function tomlFlag")
+ .unwrap()
+ .1
+ .split_once("function postHook")
+ .unwrap()
+ .0;
+ let module = tmp.path().join("openclaw-all-routes.ts");
+ let source = format!(
+ "import {{ execFileSync as realExecFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction execFileSync(command:string,args:string[],options?:any):string{{return realExecFileSync(command,args,options) as string;}}\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst cases={} as any[];for(const c of cases){{const file=join(homedir(),\".ai-memory.toml\");writeFileSync(file,c.text);const url=new URL(\"http://h/hook\");let applied=false;let helper=\"none\";try{{const route=homeRoute(readHomeRouteText(file),c.cwd,c.identity);helper=route?route.workspace+\"/\"+route.project:\"none\";}}catch{{helper=\"invalid\";}}try{{applied=applyMarkerParams(url,c.cwd);}}catch{{applied=false;}}process.stdout.write(JSON.stringify({{name:c.name,applied,helper,params:Object.fromEntries(url.searchParams)}})+\"\\n\");}}",
+ helpers,
+ serde_json::to_string(&cases).unwrap()
+ );
+ std::fs::write(&module, source).unwrap();
+ let output = std::process::Command::new("node")
+ .args(["--experimental-strip-types", "--no-warnings"])
+ .arg(&module)
+ .env("HOME", &home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let results = String::from_utf8(output.stdout)
+ .unwrap()
+ .lines()
+ .map(|line| {
+ let result: serde_json::Value = serde_json::from_str(line).unwrap();
+ (result["name"].as_str().unwrap().to_owned(), result)
+ })
+ .collect::<std::collections::HashMap<_, _>>();
+ for case in &cases {
+ let name = case["name"].as_str().unwrap();
+ let result = &results[name];
+ match case["status"].as_str().unwrap() {
+ "invalid" => {
+ assert_eq!(result["helper"], "invalid", "{name}: {result}");
+ assert_eq!(result["applied"], false, "{name}: {result}");
+ }
+ "none" => {
+ assert_eq!(result["helper"], "none", "{name}: {result}");
+ assert_eq!(result["applied"], true, "{name}: {result}");
+ assert!(
+ result["params"].get("workspace").is_none(),
+ "{name}: {result}"
+ );
+ assert!(
+ result["params"].get("project").is_none(),
+ "{name}: {result}"
+ );
+ }
+ "valid" => {
+ assert_eq!(result["applied"], true, "{name}: {result}");
+ assert_eq!(
+ result["params"]["workspace"], case["workspace"],
+ "{name}: {result}"
+ );
+ assert_eq!(
+ result["params"]["project"], case["project"],
+ "{name}: {result}"
+ );
+ assert_eq!(
+ result["params"]["project_src"], "marker",
+ "{name}: {result}"
+ );
+ let has_remote = result["params"]["identity_src"] == "git_remote";
+ if case["source"] == "identity" && has_remote {
+ assert_eq!(
+ result["params"]["identity"], case["identity"],
+ "{name}: {result}"
+ );
+ } else if case["source"] == "path" {
+ assert!(
+ result["params"].get("aliases").is_none(),
+ "{name}: {result}"
+ );
+ }
+ if let Some(style) = case["style"].as_str()
+ && has_remote
+ {
+ assert_eq!(
+ result["params"]["identity_style"], style,
+ "{name}: {result}"
+ );
+ }
+ if let Some(aliases) = case["aliases"].as_str()
+ && has_remote
+ {
+ assert_eq!(result["params"]["aliases"], aliases, "{name}: {result}");
+ }
+ if let Some(flags) = case["flags"].as_str() {
+ for pair in flags.split('&') {
+ let (key, value) = pair.split_once('=').unwrap();
+ assert_eq!(result["params"][key], value, "{name}: {result}");
+ }
+ }
+ }
+ status => panic!("unknown fixture status {status}"),
+ }
+ }
+ }
+
+ #[test]
+ fn openclaw_runtime_gates_local_identity_but_allows_alias_and_home_route_identity() {
+ if !std::process::Command::new("node")
+ .args(["--experimental-strip-types", "-e", "0"])
+ .output()
+ .is_ok_and(|output| output.status.success())
+ {
+ return;
+ }
+ let tmp = TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = tmp.path().join("repo");
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::create_dir_all(&repo).unwrap();
+ assert!(
+ std::process::Command::new("git")
+ .args(["init", "-q"])
+ .current_dir(&repo)
+ .status()
+ .unwrap()
+ .success()
+ );
+ assert!(
+ std::process::Command::new("git")
+ .args(["remote", "add", "origin", "[email protected]:acme/api.git"])
+ .current_dir(&repo)
+ .status()
+ .unwrap()
+ .success()
+ );
+ let marker = repo.join(".ai-memory.toml");
+ let home_marker = home.join(".ai-memory.toml");
+ let module = tmp.path().join("openclaw-identity-gate.ts");
let plugin = build_plugin("http://127.0.0.1:49374", Some("tok"), None, "denylist");
- let apply = plugin
- .split_once("function applyMarkerParams")
+ let helpers = plugin
+ .split_once("function tomlFlag")
.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\")"));
+ let source = format!(
+ "import {{ execFileSync }} from \"node:child_process\";\nimport {{ closeSync, existsSync, openSync, readFileSync as readMarkerText, readSync, statSync, unlinkSync, writeFileSync }} from \"node:fs\";\nimport {{ basename, dirname, join, resolve, sep }} from \"node:path\";\nimport {{ homedir }} from \"node:os\";\nfunction readFileSync(path:string,encoding?:\"utf8\"):any{{return readMarkerText(path,encoding);}}\nfunction tomlKey(text:string,key:string):string|undefined{{const m=new RegExp(`^\\\\s*${{key}}\\\\s*=\\\\s*\"([^\"]*)\"`,`m`).exec(text);return m?.[1];}}\nfunction tomlFlag{}\nconst repoCwd={};const marker={};const homeMarker={};const run=(body:string)=>{{writeFileSync(marker,body);const url=new URL(\"http://h/hook\");applyMarkerParams(url,repoCwd);return Object.fromEntries(url.searchParams);}};const plain=run('project=\"api\"\\n');const aliases=run('project=\"api\"\\naliases=[\"old-api\"]\\n');unlinkSync(marker);writeFileSync(homeMarker,'[routes.identity.\"github.com/acme/api\"]\\nroute_workspace=\"oss\"\\nroute_project=\"api\"\\n');const routedUrl=new URL(\"http://h/hook\");applyMarkerParams(routedUrl,repoCwd);process.stdout.write(JSON.stringify({{plain,aliases,routed:Object.fromEntries(routedUrl.searchParams)}}));",
+ helpers,
+ serde_json::to_string(&repo.to_string_lossy()).unwrap(),
+ serde_json::to_string(&marker.to_string_lossy()).unwrap(),
+ serde_json::to_string(&home_marker.to_string_lossy()).unwrap(),
+ );
+ std::fs::write(&module, source).unwrap();
+ let output = std::process::Command::new("node")
+ .args(["--experimental-strip-types", "--no-warnings"])
+ .arg(&module)
+ .env("HOME", &home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert!(result["plain"].get("identity").is_none(), "{result}");
+ assert_eq!(result["aliases"]["identity_src"], "git_remote", "{result}");
+ assert_eq!(result["aliases"]["aliases"], "[\"old-api\"]", "{result}");
+ assert_eq!(result["routed"]["identity_src"], "git_remote", "{result}");
+ assert_eq!(result["routed"]["workspace"], "oss", "{result}");
+ assert_eq!(result["routed"]["project_src"], "marker", "{result}");
}
#[test]
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 59606593..0d7c4309 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -772,6 +772,18 @@ impl RuntimeEnv {
}
}
+ #[cfg(test)]
+ pub fn with_host_cwd_and_home_for_tests(
+ host_cwd: impl Into<String>,
+ home_dir: impl Into<String>,
+ ) -> Self {
+ Self {
+ host_cwd: Some(host_cwd.into()),
+ home_dir: Some(home_dir.into()),
+ ..Self::default()
+ }
+ }
+
#[cfg(test)]
pub fn with_openai_api_key_for_tests(api_key: impl Into<String>) -> Self {
Self {
diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rs
index 36f0aff5..568052f4 100644
--- a/crates/ai-memory-cli/src/marker.rs
+++ b/crates/ai-memory-cli/src/marker.rs
@@ -22,6 +22,91 @@ use std::path::{Path, PathBuf};
use crate::commands::path_util::home_dir;
use crate::config::RuntimeEnv;
+use ai_memory_core::repository_identity::{
+ IdentitySource, IdentityStyle, MARKER_FILENAME, MarkerAliases, RepositoryIdentity,
+ accept_wire_identity,
+};
+
+const MAX_HOME_ROUTES: usize = 64;
+const MAX_ROUTE_SELECTOR_BYTES: usize = 512;
+const MAX_ROUTE_VALUE_BYTES: usize = 512;
+const MAX_HOME_ROUTE_FILE_BYTES: usize = 64 * 1024;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct InvalidHomeRoutes;
+
+impl std::fmt::Display for InvalidHomeRoutes {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str("the home .ai-memory.toml route map is invalid")
+ }
+}
+
+impl std::error::Error for InvalidHomeRoutes {}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct HomeRoute {
+ pub(crate) workspace: String,
+ pub(crate) project: String,
+ pub(crate) identity_style: Option<IdentityStyle>,
+ pub(crate) aliases: MarkerAliases,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct PathSelector {
+ root: PathRoot,
+ components: Vec<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum PathRoot {
+ Posix,
+ Drive(String),
+ Unc(String, String),
+}
+
+impl PathRoot {
+ fn same_root(&self, other: &Self) -> bool {
+ match (self, other) {
+ (Self::Posix, Self::Posix) => true,
+ (Self::Drive(left), Self::Drive(right)) => left.eq_ignore_ascii_case(right),
+ (Self::Unc(left_server, left_share), Self::Unc(right_server, right_share)) => {
+ left_server.eq_ignore_ascii_case(right_server)
+ && left_share.eq_ignore_ascii_case(right_share)
+ }
+ _ => false,
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct PathRoute {
+ selector: PathSelector,
+ route: HomeRoute,
+}
+
+#[derive(Debug, Clone, Default)]
+pub(crate) struct HomeRoutes {
+ identities: Vec<(String, HomeRoute)>,
+ paths: Vec<PathRoute>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum RoutingSource {
+ LocalMarker,
+ HomeIdentityRoute,
+ HomePathRoute,
+ HomeRoot,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct RoutingSelection {
+ pub(crate) path: PathBuf,
+ pub(crate) fields: RoutingFields,
+ pub(crate) source: RoutingSource,
+ pub(crate) remote_identity: Option<RepositoryIdentity>,
+}
+
+pub(crate) type RoutingSelectionResult = Result<Option<RoutingSelection>, InvalidHomeRoutes>;
/// The scope fields a marker declares, plus where it was found.
///
@@ -77,6 +162,421 @@ impl RoutingFields {
aliases: parse_aliases_in(text),
}
}
+
+ fn apply_route(&mut self, route: &HomeRoute) {
+ self.workspace = Some(route.workspace.clone());
+ self.project = Some(route.project.clone());
+ self.project_strategy = None;
+ self.identity = None;
+ self.identity_style = route.identity_style.map(|style| style.as_str().to_owned());
+ self.aliases = Ok((!route.aliases.is_empty()).then(|| route.aliases.clone()));
+ }
+}
+
+impl HomeRoutes {
+ fn parse(text: &str, home: &Path) -> Result<Self, ()> {
+ let saw_route_syntax = text
+ .lines()
+ .any(|line| recognizable_route_syntax(line.trim()));
+ if !saw_route_syntax {
+ return Ok(Self::default());
+ }
+ let mut parsed = Self::default();
+ let mut current: Option<(RouteKind, String, RouteFields)> = None;
+ let mut raw_selectors = std::collections::HashSet::new();
+
+ for line in text.lines() {
+ let trimmed = line.trim();
+ if let Some((kind, selector)) = parse_route_header(trimmed) {
+ if let Some(route) = current.take() {
+ parsed.push_route(route, home)?;
+ }
+ if !raw_selectors.insert(selector.clone()) {
+ return Err(());
+ }
+ current = Some((kind, selector, RouteFields::default()));
+ continue;
+ }
+ if trimmed.starts_with("[routes")
+ || trimmed.starts_with("routes.")
+ || trimmed
+ .strip_prefix("routes")
+ .is_some_and(|rest| rest.trim_start().starts_with('='))
+ {
+ return Err(());
+ }
+ if trimmed.starts_with('[') {
+ if let Some(route) = current.take() {
+ parsed.push_route(route, home)?;
+ }
+ continue;
+ }
+ if let Some((_, _, fields)) = current.as_mut() {
+ if trimmed.is_empty() || trimmed.starts_with('#') {
+ continue;
+ }
+ let (key, value) = trimmed.split_once('=').ok_or(())?;
+ fields.insert(key.trim(), value.trim())?;
+ } else if recognizable_malformed_root_line(trimmed) {
+ return Err(());
+ }
+ }
+ if let Some(route) = current {
+ parsed.push_route(route, home)?;
+ }
+ Ok(parsed)
+ }
+
+ fn push_route(
+ &mut self,
+ (kind, raw_selector, fields): (RouteKind, String, RouteFields),
+ home: &Path,
+ ) -> Result<(), ()> {
+ self.check_capacity(&raw_selector)?;
+ let route = fields.finish()?;
+ match kind {
+ RouteKind::Identity => {
+ let identity =
+ accept_wire_identity(&raw_selector, IdentitySource::GitRemote.as_str())
+ .ok_or(())?;
+ if identity.identity != raw_selector
+ || !valid_identity_selector(&raw_selector)
+ || self
+ .identities
+ .iter()
+ .any(|(existing, _)| existing == &identity.identity)
+ {
+ return Err(());
+ }
+ self.identities.push((identity.identity, route));
+ }
+ RouteKind::Path => {
+ let selector = PathSelector::parse(&raw_selector, home)?;
+ if self
+ .paths
+ .iter()
+ .any(|existing| existing.selector.same_selector(&selector))
+ {
+ return Err(());
+ }
+ self.paths.push(PathRoute { selector, route });
+ }
+ }
+ Ok(())
+ }
+
+ fn check_capacity(&self, selector: &str) -> Result<(), ()> {
+ if self.identities.len() + self.paths.len() >= MAX_HOME_ROUTES
+ || selector.is_empty()
+ || selector.len() > MAX_ROUTE_SELECTOR_BYTES
+ || selector.chars().any(char::is_control)
+ {
+ return Err(());
+ }
+ Ok(())
+ }
+
+ fn select(
+ &self,
+ cwd: &str,
+ remote: Option<&RepositoryIdentity>,
+ ) -> Result<Option<(HomeRoute, RoutingSource)>, ()> {
+ if let Some(remote) = remote.filter(|identity| identity.source == IdentitySource::GitRemote)
+ && let Some((_, route)) = self
+ .identities
+ .iter()
+ .find(|(selector, _)| selector == &remote.identity)
+ {
+ return Ok(Some((route.clone(), RoutingSource::HomeIdentityRoute)));
+ }
+ let cwd = parse_absolute_selector(cwd)?;
+ let mut matched: Option<&PathRoute> = None;
+ for candidate in self
+ .paths
+ .iter()
+ .filter(|candidate| candidate.selector.contains(&cwd))
+ {
+ match matched {
+ None => matched = Some(candidate),
+ Some(current)
+ if candidate.selector.components.len() > current.selector.components.len() =>
+ {
+ matched = Some(candidate);
+ }
+ Some(current)
+ if candidate.selector.components.len() == current.selector.components.len() =>
+ {
+ return Err(());
+ }
+ Some(_) => {}
+ }
+ }
+ Ok(matched.map(|route| (route.route.clone(), RoutingSource::HomePathRoute)))
+ }
+}
+
+impl PathSelector {
+ fn same_selector(&self, other: &Self) -> bool {
+ if !self.root.same_root(&other.root) || self.components.len() != other.components.len() {
+ return false;
+ }
+ let windows = matches!(self.root, PathRoot::Drive(_) | PathRoot::Unc(_, _));
+ self.components
+ .iter()
+ .zip(&other.components)
+ .all(|(left, right)| {
+ if windows {
+ left.eq_ignore_ascii_case(right)
+ } else {
+ left == right
+ }
+ })
+ }
+
+ fn parse(raw: &str, home: &Path) -> Result<Self, ()> {
+ if raw.is_empty()
+ || raw.len() > MAX_ROUTE_SELECTOR_BYTES
+ || raw.chars().any(char::is_control)
+ {
+ return Err(());
+ }
+ if let Some(rest) = raw.strip_prefix("~/") {
+ let mut depth = 0usize;
+ for component in rest.replace('\\', "/").split('/') {
+ match component {
+ "" | "." => {}
+ ".." if depth == 0 => return Err(()),
+ ".." => depth -= 1,
+ _ => depth += 1,
+ }
+ }
+ return parse_absolute_selector(&format!(
+ "{}/{}",
+ home.to_string_lossy().trim_end_matches(['/', '\\']),
+ rest
+ ));
+ }
+ parse_absolute_selector(raw)
+ }
+
+ fn contains(&self, cwd: &Self) -> bool {
+ if !self.root.same_root(&cwd.root) || self.components.len() > cwd.components.len() {
+ return false;
+ }
+ let windows = matches!(self.root, PathRoot::Drive(_) | PathRoot::Unc(_, _));
+ self.components
+ .iter()
+ .zip(&cwd.components)
+ .all(|(left, right)| {
+ if windows {
+ left.eq_ignore_ascii_case(right)
+ } else {
+ left == right
+ }
+ })
+ }
+}
+
+fn parse_absolute_selector(raw: &str) -> Result<PathSelector, ()> {
+ let replaced = raw.replace('\\', "/");
+ let (root, rest) = if let Some(rest) = replaced.strip_prefix("//") {
+ let mut parts = rest.split('/').filter(|part| !part.is_empty());
+ let server = parts.next().ok_or(())?;
+ let share = parts.next().ok_or(())?;
+ (
+ PathRoot::Unc(server.to_ascii_lowercase(), share.to_ascii_lowercase()),
+ parts.collect::<Vec<_>>(),
+ )
+ } else if replaced.as_bytes().get(1) == Some(&b':')
+ && replaced.as_bytes().get(2) == Some(&b'/')
+ && replaced.as_bytes()[0].is_ascii_alphabetic()
+ {
+ (
+ PathRoot::Drive(replaced[..1].to_ascii_uppercase()),
+ replaced[3..]
+ .split('/')
+ .filter(|part| !part.is_empty())
+ .collect(),
+ )
+ } else if let Some(rest) = replaced.strip_prefix('/') {
+ (
+ PathRoot::Posix,
+ rest.split('/').filter(|part| !part.is_empty()).collect(),
+ )
+ } else {
+ return Err(());
+ };
+ let mut components: Vec<String> = Vec::new();
+ for component in rest {
+ match component {
+ "." => {}
+ ".." => {
+ components.pop();
+ }
+ value => components.push(value.to_owned()),
+ }
+ }
+ if components.is_empty() {
+ return Err(());
+ }
+ Ok(PathSelector { root, components })
+}
+
+fn valid_identity_selector(value: &str) -> bool {
+ let mut segments = value.split('/');
+ let Some(host) = segments.next() else {
+ return false;
+ };
+ !host.starts_with('.')
+ && !host.ends_with('.')
+ && host.bytes().all(|byte| {
+ byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'-')
+ })
+ && segments.clone().count() >= 1
+ && segments.all(|segment| {
+ !segment.is_empty()
+ && segment.bytes().all(|byte| {
+ byte.is_ascii_lowercase()
+ || byte.is_ascii_digit()
+ || matches!(byte, b'.' | b'_' | b'-')
+ })
+ })
+}
+
+fn valid_route_name(value: &str) -> bool {
+ value.len() <= MAX_ROUTE_VALUE_BYTES
+ && value.bytes().enumerate().all(|(index, byte)| {
+ byte.is_ascii_lowercase()
+ || byte.is_ascii_digit()
+ || (index > 0 && matches!(byte, b'.' | b'_' | b'-'))
+ })
+}
+
+#[derive(Debug, Clone, Copy)]
+enum RouteKind {
+ Identity,
+ Path,
+}
+
+#[derive(Debug, Default)]
+struct RouteFields {
+ workspace: Option<String>,
+ project: Option<String>,
+ identity_style: Option<String>,
+ aliases: Option<String>,
+}
+
+fn recognizable_route_syntax(line: &str) -> bool {
+ line.starts_with("[routes")
+ || line.starts_with("routes.")
+ || line
+ .strip_prefix("routes")
+ .is_some_and(|rest| rest.trim_start().starts_with('='))
+ || line.starts_with("route_")
+}
+
+fn recognizable_malformed_root_line(line: &str) -> bool {
+ if line.is_empty() || line.starts_with('#') {
+ return false;
+ }
+ if line.starts_with("route_") {
+ return true;
+ }
+ let Some((key, value)) = line.split_once('=') else {
+ return false;
+ };
+ let key = key.trim();
+ let value = value.trim();
+ matches!(
+ key,
+ "workspace"
+ | "project"
+ | "project_strategy"
+ | "drop_subagent_captures"
+ | "identity"
+ | "identity_style"
+ | "server"
+ ) && !value
+ .strip_prefix('"')
+ .and_then(|inner| inner.strip_suffix('"'))
+ .is_some_and(|inner| !inner.contains('"'))
+}
+
+fn parse_route_header(line: &str) -> Option<(RouteKind, String)> {
+ let body = line.strip_prefix("[routes.")?.strip_suffix(']')?;
+ let (kind, quoted) = body.split_once('.')?;
+ let selector = quoted.strip_prefix('"')?.strip_suffix('"')?;
+ if selector.contains(['"', '\\']) {
+ return None;
+ }
+ let kind = match kind {
+ "identity" => RouteKind::Identity,
+ "path" => RouteKind::Path,
+ _ => return None,
+ };
+ Some((kind, selector.to_owned()))
+}
+
+impl RouteFields {
+ fn insert(&mut self, key: &str, value: &str) -> Result<(), ()> {
+ let slot = match key {
+ "route_workspace" => &mut self.workspace,
+ "route_project" => &mut self.project,
+ "route_identity_style" => &mut self.identity_style,
+ "route_aliases" => &mut self.aliases,
+ _ => return Err(()),
+ };
+ if slot.replace(value.to_owned()).is_some() {
+ return Err(());
+ }
+ Ok(())
+ }
+
+ fn finish(self) -> Result<HomeRoute, ()> {
+ let string_value = |raw: Option<String>| {
+ let raw = raw.ok_or(())?;
+ if raw.len() > MAX_ROUTE_VALUE_BYTES + 2 || raw.contains('\\') {
+ return Err(());
+ }
+ let value = raw
+ .strip_prefix('"')
+ .and_then(|v| v.strip_suffix('"'))
+ .ok_or(())?;
+ if value.is_empty() || value.len() > MAX_ROUTE_VALUE_BYTES || value.contains('"') {
+ return Err(());
+ }
+ Ok(value.to_owned())
+ };
+ let workspace = string_value(self.workspace)?;
+ let project = string_value(self.project)?;
+ if !valid_route_name(&workspace) || !valid_route_name(&project) {
+ return Err(());
+ }
+ let identity_style = self
+ .identity_style
+ .map(|raw| string_value(Some(raw)))
+ .transpose()?
+ .map(|style| IdentityStyle::from_str_opt(&style).ok_or(()))
+ .transpose()?;
+ let aliases = match self.aliases {
+ None => MarkerAliases::default(),
+ Some(raw) => {
+ if raw.len() > MAX_ROUTE_VALUE_BYTES || raw.contains('\\') {
+ return Err(());
+ }
+ let marker = format!("aliases = {raw}");
+ ai_memory_core::repository_identity::parse_marker_aliases(&marker)
+ .map_err(|_| ())?
+ .ok_or(())?
+ }
+ };
+ Ok(HomeRoute {
+ workspace,
+ project,
+ identity_style,
+ aliases,
+ })
+ }
}
#[derive(Debug, Clone)]
@@ -84,89 +584,119 @@ pub(crate) struct MarkerInspection {
pub(crate) status: &'static str,
pub(crate) fields: RoutingFields,
pub(crate) scope: Option<MarkerScope>,
+ pub(crate) route_identity: Option<RepositoryIdentity>,
}
+#[cfg(test)]
pub(crate) fn inspect_scope(cwd: &str, env: &RuntimeEnv) -> MarkerInspection {
+ inspect_scope_for(cwd, cwd, env)
+}
+
+pub(crate) fn inspect_scope_for(
+ lookup_cwd: &str,
+ identity_cwd: &str,
+ env: &RuntimeEnv,
+) -> MarkerInspection {
use std::io::Read as _;
let empty = |status| MarkerInspection {
status,
fields: RoutingFields::default(),
scope: None,
+ route_identity: None,
};
if env.ignore_marker() {
return empty("ignored");
}
- let found = find_marker_matching(
- cwd,
+ let selection = match routing_selection_with_home(
+ lookup_cwd,
+ identity_cwd,
env.home_dir().map(Path::new),
- OutsideHome::StopAtCheckoutRoot,
- |path| {
- let limit = ai_memory_hooks::capture_policy::MAX_MARKER_BYTES;
- let text = (|| {
- let mut bytes = Vec::new();
- std::fs::File::open(path)
- .ok()?
- .take((limit + 1) as u64)
- .read_to_end(&mut bytes)
- .ok()?;
- (bytes.len() <= limit).then_some(())?;
- String::from_utf8(bytes).ok()
- })();
- let Some(text) = text else {
- return Some(empty("unreadable"));
- };
- let Ok(document) = text.parse::<toml_edit::DocumentMut>() else {
- return Some(empty("invalid"));
- };
- let fields = RoutingFields::from_text(&text);
- for (key, parsed) in [
- ("workspace", &fields.workspace),
- ("project", &fields.project),
- ("project_strategy", &fields.project_strategy),
- ("identity", &fields.identity),
- ("identity_style", &fields.identity_style),
- ] {
- let strict = document.get(key).and_then(toml_edit::Item::as_str);
- if strict != parsed.as_deref()
- || document
- .get(key)
- .is_some_and(|item| item.as_str().is_none())
- {
- return Some(empty("conflicting"));
- }
- }
- 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")
- })
+ false,
+ ) {
+ Ok(Some(selection)) => selection,
+ Err(_) => return empty("invalid_home_routes"),
+ Ok(None) => {
+ if let Some(path) = find_marker_with_home(lookup_cwd, env.home_dir().map(Path::new))
+ && std::fs::read_to_string(path)
+ .is_ok_and(|text| text.parse::<toml_edit::DocumentMut>().is_err())
{
- return Some(empty("conflicting"));
+ return empty("invalid");
}
- if !declares_more_than_capture(&text) {
- return None;
+ return empty("absent");
+ }
+ };
+ let limit = ai_memory_hooks::capture_policy::MAX_MARKER_BYTES;
+ let text = (|| {
+ let mut bytes = Vec::new();
+ std::fs::File::open(&selection.path)
+ .ok()?
+ .take((limit + 1) as u64)
+ .read_to_end(&mut bytes)
+ .ok()?;
+ (bytes.len() <= limit).then_some(())?;
+ String::from_utf8(bytes).ok()
+ })();
+ let Some(text) = text else {
+ return empty("unreadable");
+ };
+ let Ok(document) = text.parse::<toml_edit::DocumentMut>() else {
+ return empty("invalid");
+ };
+ let route_identity = selection.remote_identity;
+ let fields = selection.fields;
+ if matches!(
+ selection.source,
+ RoutingSource::LocalMarker | RoutingSource::HomeRoot
+ ) {
+ for (key, parsed) in [
+ ("workspace", &fields.workspace),
+ ("project", &fields.project),
+ ("project_strategy", &fields.project_strategy),
+ ("identity", &fields.identity),
+ ("identity_style", &fields.identity_style),
+ ] {
+ let strict = document.get(key).and_then(toml_edit::Item::as_str);
+ if strict != parsed.as_deref()
+ || document
+ .get(key)
+ .is_some_and(|item| item.as_str().is_none())
+ {
+ return empty("conflicting");
}
- let scope = MarkerScope {
- path: path.to_path_buf(),
- workspace: fields.workspace.clone(),
- project: fields.project.clone(),
- project_strategy: fields.project_strategy.clone().or_else(|| {
- env.project_strategy()
- .filter(|s| !s.trim().is_empty())
- .map(str::to_owned)
- }),
- };
- Some(MarkerInspection {
- status: "valid",
- fields,
- scope: scope.declares_scope().then_some(scope),
- })
+ }
+ }
+ if fields.aliases.is_err()
+ || fields
+ .identity_style
+ .as_deref()
+ .is_some_and(|style| IdentityStyle::from_str_opt(style).is_none())
+ || fields
+ .project_strategy
+ .as_deref()
+ .is_some_and(|strategy| !matches!(strategy, "repo-root" | "repo_root" | "basename"))
+ {
+ return empty("conflicting");
+ }
+ let scope = MarkerScope {
+ path: selection.path,
+ workspace: fields.workspace.clone(),
+ project: fields.project.clone(),
+ project_strategy: fields.project_strategy.clone().or_else(|| {
+ env.project_strategy()
+ .filter(|s| !s.trim().is_empty())
+ .map(str::to_owned)
+ }),
+ };
+ MarkerInspection {
+ status: match selection.source {
+ RoutingSource::HomeIdentityRoute => "home_identity_route",
+ RoutingSource::HomePathRoute => "home_path_route",
+ _ => "valid",
},
- );
- found.unwrap_or_else(|| empty("absent"))
+ fields,
+ scope: scope.declares_scope().then_some(scope),
+ route_identity,
+ }
}
impl MarkerScope {
@@ -197,17 +727,32 @@ impl MarkerScope {
/// Returns `None` when no marker is found, when the operator disabled marker
/// resolution, or when the marker declares nothing scope-related — callers
/// then keep their existing fallbacks untouched.
-pub(crate) fn read_scope(cwd: &str, env: &RuntimeEnv) -> Option<MarkerScope> {
- if env.ignore_marker() {
- return None;
- }
- let path = find_settings_marker_with_home(cwd, env.home_dir().map(Path::new))?;
- let text = std::fs::read_to_string(&path).ok()?;
+pub(crate) fn read_scope(
+ cwd: &str,
+ env: &RuntimeEnv,
+) -> Result<Option<MarkerScope>, InvalidHomeRoutes> {
+ read_scope_for(cwd, cwd, env)
+}
+
+pub(crate) fn read_scope_for(
+ lookup_cwd: &str,
+ identity_cwd: &str,
+ env: &RuntimeEnv,
+) -> Result<Option<MarkerScope>, InvalidHomeRoutes> {
+ let Some(selection) = routing_selection_with_home(
+ lookup_cwd,
+ identity_cwd,
+ env.home_dir().map(Path::new),
+ env.ignore_marker(),
+ )?
+ else {
+ return Ok(None);
+ };
let mut scope = MarkerScope {
- workspace: parse_key_in(&text, "workspace"),
- project: parse_key_in(&text, "project"),
- project_strategy: parse_key_in(&text, "project_strategy"),
- path,
+ workspace: selection.fields.workspace,
+ project: selection.fields.project,
+ project_strategy: selection.fields.project_strategy,
+ path: selection.path,
};
if scope.project_strategy.is_none() {
scope.project_strategy = env
@@ -215,7 +760,124 @@ pub(crate) fn read_scope(cwd: &str, env: &RuntimeEnv) -> Option<MarkerScope> {
.filter(|value| !value.trim().is_empty())
.map(str::to_owned);
}
- scope.declares_scope().then_some(scope)
+ Ok(scope.declares_scope().then_some(scope))
+}
+
+pub(crate) fn routing_selection(cwd: &str) -> RoutingSelectionResult {
+ routing_selection_for(cwd, cwd)
+}
+
+pub(crate) fn routing_selection_for(
+ lookup_cwd: &str,
+ identity_cwd: &str,
+) -> RoutingSelectionResult {
+ routing_selection_with_home(lookup_cwd, identity_cwd, home_dir().as_deref(), false)
+}
+
+pub(crate) fn routing_selection_with_home(
+ lookup_cwd: &str,
+ identity_cwd: &str,
+ home: Option<&Path>,
+ ignore_marker: bool,
+) -> RoutingSelectionResult {
+ if ignore_marker {
+ return Ok(None);
+ }
+ let local = find_settings_marker_with_home(lookup_cwd, home).filter(|path| {
+ home.is_none_or(|home| {
+ absolute_normalized(path) != absolute_normalized(&home.join(MARKER_FILENAME))
+ })
+ });
+ if let Some(path) = local {
+ let text = std::fs::read_to_string(&path).ok();
+ let Some(text) = text else {
+ return Ok(None);
+ };
+ let fields = RoutingFields::from_text(&text);
+ let remote_identity = if fields
+ .aliases
+ .as_ref()
+ .is_ok_and(|aliases| aliases.is_some())
+ {
+ discover_remote_identity(identity_cwd).or_else(|| {
+ (lookup_cwd != identity_cwd)
+ .then(|| discover_remote_identity(lookup_cwd))
+ .flatten()
+ })
+ } else {
+ None
+ };
+ return Ok(Some(RoutingSelection {
+ path,
+ fields,
+ source: RoutingSource::LocalMarker,
+ remote_identity,
+ }));
+ }
+ let Some(home) = home else {
+ return Ok(None);
+ };
+ let path = home.join(MARKER_FILENAME);
+ let file = match std::fs::File::open(&path) {
+ Ok(file) => file,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(_) => return Err(InvalidHomeRoutes),
+ };
+ let expected = file.metadata().map_err(|_| InvalidHomeRoutes)?.len();
+ if expected > MAX_HOME_ROUTE_FILE_BYTES as u64 {
+ return Err(InvalidHomeRoutes);
+ }
+ let mut bytes = Vec::with_capacity(MAX_HOME_ROUTE_FILE_BYTES + 1);
+ use std::io::Read as _;
+ (&file)
+ .take((MAX_HOME_ROUTE_FILE_BYTES + 1) as u64)
+ .read_to_end(&mut bytes)
+ .map_err(|_| InvalidHomeRoutes)?;
+ if bytes.len() > MAX_HOME_ROUTE_FILE_BYTES
+ || bytes.len() as u64 != expected
+ || file.metadata().map_err(|_| InvalidHomeRoutes)?.len() != expected
+ {
+ return Err(InvalidHomeRoutes);
+ }
+ let text = String::from_utf8(bytes).map_err(|_| InvalidHomeRoutes)?;
+ let mut fields = RoutingFields::from_text(&text);
+ let remote_identity = discover_remote_identity(identity_cwd).or_else(|| {
+ (lookup_cwd != identity_cwd)
+ .then(|| discover_remote_identity(lookup_cwd))
+ .flatten()
+ });
+ let routes = HomeRoutes::parse(&text, home).map_err(|_| InvalidHomeRoutes)?;
+ match routes.select(identity_cwd, remote_identity.as_ref()) {
+ Ok(Some((route, source))) => {
+ fields.apply_route(&route);
+ return Ok(Some(RoutingSelection {
+ path,
+ fields,
+ source,
+ remote_identity,
+ }));
+ }
+ Err(()) => return Err(InvalidHomeRoutes),
+ Ok(None) => {}
+ }
+ Ok(Some(RoutingSelection {
+ path,
+ fields,
+ source: RoutingSource::HomeRoot,
+ remote_identity: None,
+ }))
+}
+
+fn discover_remote_identity(cwd: &str) -> Option<RepositoryIdentity> {
+ let (upstream, origin) = ai_memory_consolidate::read_identity_remotes(Path::new(cwd));
+ [upstream.as_deref(), origin.as_deref()]
+ .into_iter()
+ .flatten()
+ .find_map(ai_memory_core::repository_identity::normalize_remote_url)
+ .map(|identity| RepositoryIdentity {
+ identity,
+ source: IdentitySource::GitRemote,
+ })
}
/// Derive a project name from the **main** repository root, so linked
@@ -256,7 +918,14 @@ pub(crate) fn find_settings_marker(cwd: &str) -> Option<PathBuf> {
}
fn find_settings_marker_with_home(cwd: &str, home: Option<&Path>) -> Option<PathBuf> {
+ let home_marker = home.map(|home| absolute_normalized(&home.join(MARKER_FILENAME)));
find_marker_matching(cwd, home, OutsideHome::StopAtCheckoutRoot, |path| {
+ if home_marker
+ .as_ref()
+ .is_some_and(|marker| absolute_normalized(path) == *marker)
+ {
+ return Some(path.to_path_buf());
+ }
std::fs::read_to_string(path)
.is_ok_and(|text| declares_more_than_capture(&text))
.then(|| path.to_path_buf())
@@ -521,17 +1190,6 @@ 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<
@@ -726,6 +1384,442 @@ mod tests {
}
}
+ #[test]
+ fn home_routes_match_the_shared_fixture() {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../ai-memory-core/fixtures/home_route_cases.json"
+ ))
+ .unwrap();
+ let home = Path::new("/home/operator");
+ for case in fixture["cases"].as_array().unwrap() {
+ let name = case["name"].as_str().unwrap();
+ let generated = case["generate"].as_str();
+ let text = match generated {
+ Some("65_routes") => (0..65)
+ .map(|index| format!("[routes.path.\"/route/{index}\"]\nroute_workspace=\"ws\"\nroute_project=\"p{index}\"\n"))
+ .collect(),
+ Some("selector_512") => format!(
+ "[routes.path.\"/{}\"]\nroute_workspace=\"bounds\"\nroute_project=\"valid\"\n",
+ "a".repeat(511)
+ ),
+ Some("selector_513") => format!(
+ "[routes.path.\"/{}\"]\nroute_workspace=\"bounds\"\nroute_project=\"invalid\"\n",
+ "a".repeat(512)
+ ),
+ Some("oversized_file") => format!("#{}\n", "x".repeat(MAX_HOME_ROUTE_FILE_BYTES)),
+ Some(other) => panic!("unknown fixture generator {other}"),
+ None => case["toml"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", home.to_str().unwrap())
+ .replace("{{LONG_513}}", &"a".repeat(513)),
+ };
+ let parsed = HomeRoutes::parse(&text, home);
+ if case["status"] == "invalid" {
+ assert!(
+ parsed.is_err() || text.len() > MAX_HOME_ROUTE_FILE_BYTES,
+ "{name}"
+ );
+ continue;
+ }
+ let routes = parsed.unwrap();
+ let cwd = match case["cwd_generate"].as_str() {
+ Some("selector_512_child") => format!("/{}/child", "a".repeat(511)),
+ Some(other) => panic!("unknown cwd fixture generator {other}"),
+ None => case["cwd"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", home.to_str().unwrap()),
+ };
+ let identity = case["identity"]
+ .as_str()
+ .map(|identity| RepositoryIdentity {
+ identity: identity.to_owned(),
+ source: IdentitySource::GitRemote,
+ });
+ let selected = routes.select(&cwd, identity.as_ref()).unwrap();
+ if case["status"] == "none" {
+ assert!(selected.is_none(), "{name}");
+ } else {
+ let (route, source) = selected.unwrap_or_else(|| panic!("{name}"));
+ assert_eq!(
+ route.workspace,
+ case["workspace"].as_str().unwrap(),
+ "{name}"
+ );
+ assert_eq!(route.project, case["project"].as_str().unwrap(), "{name}");
+ assert_eq!(
+ source,
+ if case["source"] == "identity" {
+ RoutingSource::HomeIdentityRoute
+ } else {
+ RoutingSource::HomePathRoute
+ },
+ "{name}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn home_routes_prefer_identity_then_longest_component_path() {
+ let home = Path::new("/home/operator");
+ let routes = HomeRoutes::parse(
+ r#"
+[routes.path."~/src"]
+route_workspace = "path"
+route_project = "broad"
+[routes.path."~/src/api"]
+route_workspace = "path"
+route_project = "api"
+[routes.identity."github.com/acme/api"]
+route_workspace = "identity"
+route_project = "acme-api"
+route_identity_style = "path"
+route_aliases = ["main"]
+"#,
+ home,
+ )
+ .unwrap();
+ let identity = RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ };
+ let (route, source) = routes
+ .select("/home/operator/src/api/crate", Some(&identity))
+ .unwrap()
+ .unwrap();
+ assert_eq!(source, RoutingSource::HomeIdentityRoute);
+ assert_eq!(route.workspace, "identity");
+ assert_eq!(route.project, "acme-api");
+ assert_eq!(route.identity_style, Some(IdentityStyle::Path));
+ assert_eq!(route.aliases.as_slice(), &["main"]);
+
+ let (route, source) = routes
+ .select("/home/operator/src/api/crate", None)
+ .unwrap()
+ .unwrap();
+ assert_eq!(source, RoutingSource::HomePathRoute);
+ assert_eq!(route.project, "api");
+ assert!(
+ routes
+ .select("/home/operator/src/api-sibling", None)
+ .unwrap()
+ .is_some_and(|(route, _)| route.project == "broad")
+ );
+ assert!(
+ routes
+ .select("/home/operator/src-api", None)
+ .unwrap()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn home_routes_keep_forges_and_platform_path_roots_distinct() {
+ let routes = HomeRoutes::parse(
+ r#"
+[routes.identity."github.com/acme/api"]
+route_workspace = "oss"
+route_project = "github-api"
+[routes.identity."gitlab.com/acme/api"]
+route_workspace = "oss"
+route_project = "gitlab-api"
+[routes.path."C:/Work/API"]
+route_workspace = "win"
+route_project = "drive"
+[routes.path."//Server/Share/API"]
+route_workspace = "win"
+route_project = "unc"
+"#,
+ Path::new("C:/Users/tester"),
+ )
+ .unwrap();
+ for (identity, expected) in [
+ ("github.com/acme/api", "github-api"),
+ ("gitlab.com/acme/api", "gitlab-api"),
+ ] {
+ let remote = RepositoryIdentity {
+ identity: identity.into(),
+ source: IdentitySource::GitRemote,
+ };
+ assert_eq!(
+ routes
+ .select("C:/elsewhere", Some(&remote))
+ .unwrap()
+ .unwrap()
+ .0
+ .project,
+ expected
+ );
+ }
+ assert_eq!(
+ routes
+ .select(r"c:\work\api\src", None)
+ .unwrap()
+ .unwrap()
+ .0
+ .project,
+ "drive"
+ );
+ assert_eq!(
+ routes
+ .select(r"\\server\share\api\src", None)
+ .unwrap()
+ .unwrap()
+ .0
+ .project,
+ "unc"
+ );
+ }
+
+ #[test]
+ fn malformed_duplicate_and_ambiguous_home_routes_fail_closed() {
+ let home = Path::new("/home/operator");
+ for text in [
+ "[routes.identity.\"api\"]\nroute_workspace=\"oss\"\nroute_project=\"api\"\n",
+ "[routes.path.\"relative/api\"]\nroute_workspace=\"oss\"\nroute_project=\"api\"\n",
+ "[routes.path.\"~/api\"]\nroute_workspace=\"Bad\"\nroute_project=\"api\"\n",
+ "[routes.path.\"~/api\"]\nroute_workspace=\"oss\"\nroute_project=\"api\"\nroute_aliases=[\"../bad\"]\n",
+ "[routes.path.\"~/api\"]\nroute_workspace=\"oss\"\nroute_project=\"api\"\nunknown=\"x\"\n",
+ ] {
+ assert!(HomeRoutes::parse(text, home).is_err(), "{text}");
+ }
+ let duplicate = "[routes.identity.\"github.com/acme/api\"]\nroute_workspace=\"oss\"\nroute_project=\"api\"\n[routes.identity.\"github.com/acme/api\"]\nroute_workspace=\"other\"\nroute_project=\"other\"\n";
+ assert!(HomeRoutes::parse(duplicate, home).is_err());
+ let escaped =
+ "[routes.path.\"C:\\\\Work\\\\API\"]\nroute_workspace=\"oss\"\nroute_project=\"api\"\n";
+ assert!(HomeRoutes::parse(escaped, home).is_err());
+ let too_many = (0..=MAX_HOME_ROUTES)
+ .map(|index| format!("[routes.path.\"/route/{index}\"]\nroute_workspace=\"oss\"\nroute_project=\"route-{index}\"\n"))
+ .collect::<String>();
+ assert!(HomeRoutes::parse(&too_many, home).is_err());
+
+ let routes = HomeRoutes {
+ identities: Vec::new(),
+ paths: vec![
+ PathRoute {
+ selector: PathSelector::parse("~/api", home).unwrap(),
+ route: HomeRoute {
+ workspace: "one".into(),
+ project: "one".into(),
+ identity_style: None,
+ aliases: MarkerAliases::default(),
+ },
+ },
+ PathRoute {
+ selector: PathSelector::parse("/home/operator/api", home).unwrap(),
+ route: HomeRoute {
+ workspace: "two".into(),
+ project: "two".into(),
+ identity_style: None,
+ aliases: MarkerAliases::default(),
+ },
+ },
+ ],
+ };
+ assert!(routes.select("/home/operator/api", None).is_err());
+ }
+
+ #[test]
+ fn home_route_selection_works_outside_home_and_local_marker_wins() {
+ let tmp = TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let outside = tmp.path().join("outside/repo");
+ fs::create_dir_all(outside.join(".git")).unwrap();
+ fs::create_dir_all(&home).unwrap();
+ write_marker(
+ &home,
+ &format!(
+ "workspace = \"fallback\"\nproject = \"fallback\"\n[routes.path.\"{}\"]\nroute_workspace = \"routed\"\nroute_project = \"outside\"\n",
+ outside.display()
+ ),
+ );
+ let selected = routing_selection_with_home(
+ outside.to_str().unwrap(),
+ outside.to_str().unwrap(),
+ Some(&home),
+ false,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(selected.source, RoutingSource::HomePathRoute);
+ assert_eq!(selected.fields.workspace.as_deref(), Some("routed"));
+ assert_eq!(selected.fields.project.as_deref(), Some("outside"));
+
+ write_marker(&outside, "workspace = \"local\"\nproject = \"repo\"\n");
+ let selected = routing_selection_with_home(
+ outside.to_str().unwrap(),
+ outside.to_str().unwrap(),
+ Some(&home),
+ false,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(selected.source, RoutingSource::LocalMarker);
+ assert_eq!(selected.fields.workspace.as_deref(), Some("local"));
+ assert_eq!(selected.fields.project.as_deref(), Some("repo"));
+ }
+
+ #[test]
+ fn home_identity_route_forwards_aliases_only_with_remote_evidence() {
+ let tmp = TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let repo = tmp.path().join("repo");
+ fs::create_dir_all(&home).unwrap();
+ fs::create_dir_all(&repo).unwrap();
+ assert!(
+ std::process::Command::new("git")
+ .args(["init", "-q"])
+ .current_dir(&repo)
+ .status()
+ .unwrap()
+ .success()
+ );
+ assert!(
+ std::process::Command::new("git")
+ .args(["remote", "add", "origin", "[email protected]:acme/api.git"])
+ .current_dir(&repo)
+ .status()
+ .unwrap()
+ .success()
+ );
+ write_marker(
+ &home,
+ "[routes.identity.\"github.com/acme/api\"]\nroute_workspace=\"oss\"\nroute_project=\"acme-api\"\nroute_identity_style=\"path\"\nroute_aliases=[\"main\"]\n",
+ );
+ let selected = routing_selection_with_home(
+ repo.to_str().unwrap(),
+ repo.to_str().unwrap(),
+ Some(&home),
+ false,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(selected.source, RoutingSource::HomeIdentityRoute);
+ assert_eq!(selected.fields.project.as_deref(), Some("acme-api"));
+ assert_eq!(selected.fields.identity_style.as_deref(), Some("path"));
+ assert_eq!(
+ selected.fields.aliases.unwrap().unwrap().as_slice(),
+ &["main"]
+ );
+ assert_eq!(
+ selected.remote_identity.unwrap().identity,
+ "github.com/acme/api"
+ );
+ }
+
+ #[test]
+ fn home_root_settings_remain_the_fallback_without_a_route_match() {
+ let tmp = TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let checkout = tmp.path().join("outside/repo");
+ fs::create_dir_all(&home).unwrap();
+ fs::create_dir_all(&checkout).unwrap();
+ write_marker(
+ &home,
+ "workspace = \"fallback\"\nproject = \"fallback\"\n[routes.path.\"~/src\"]\nroute_workspace = \"oss\"\nroute_project = \"api\"\n",
+ );
+ let selected = routing_selection_with_home(
+ checkout.to_str().unwrap(),
+ checkout.to_str().unwrap(),
+ Some(&home),
+ false,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(selected.source, RoutingSource::HomeRoot);
+ assert_eq!(selected.fields.workspace.as_deref(), Some("fallback"));
+ assert_eq!(selected.fields.project.as_deref(), Some("fallback"));
+ }
+
+ #[test]
+ fn matched_home_route_replaces_only_routing_fields() {
+ let tmp = TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let checkout = home.join("src/api/lib");
+ fs::create_dir_all(&checkout).unwrap();
+ write_marker(
+ &home,
+ "workspace=\"wrong\"\nproject=\"wrong\"\nproject_strategy=\"repo-root\"\ndrop_subagent_captures=\"true\"\n[recall]\ndefault_global=true\n[briefing]\ninject_on_session_start=true\nmax_chars=3210\n[profile]\ncontribute=true\nconsume=false\n[routes.path.\"~/src/api\"]\nroute_workspace=\"right\"\nroute_project=\"api\"\n",
+ );
+ let selected = routing_selection_with_home(
+ checkout.to_str().unwrap(),
+ checkout.to_str().unwrap(),
+ Some(&home),
+ false,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(selected.fields.workspace.as_deref(), Some("right"));
+ assert_eq!(selected.fields.project.as_deref(), Some("api"));
+ assert_eq!(selected.fields.project_strategy, None);
+ let text = fs::read_to_string(selected.path).unwrap();
+ assert_eq!(
+ parse_key_in(&text, "drop_subagent_captures").as_deref(),
+ Some("true")
+ );
+ assert_eq!(
+ parse_flag_in(&text, "default_global").as_deref(),
+ Some("true")
+ );
+ assert_eq!(
+ parse_flag_in(&text, "inject_on_session_start").as_deref(),
+ Some("true")
+ );
+ assert_eq!(parse_flag_in(&text, "consume").as_deref(), Some("false"));
+ }
+
+ #[test]
+ fn recognized_root_scalars_require_one_exact_quoted_value() {
+ for line in [
+ "workspace = \"wrong\" junk \"x\"",
+ "workspace = \"wrong\" # comment",
+ "workspace = \"wrong\"\"x\"",
+ "workspace = wrong",
+ ] {
+ assert!(recognizable_malformed_root_line(line), "{line}");
+ }
+ assert!(!recognizable_malformed_root_line("workspace = \"valid\""));
+ }
+
+ #[test]
+ fn malformed_home_routes_do_not_fall_through_to_root_home_scope() {
+ let tmp = TempDir::new().unwrap();
+ let home = tmp.path().join("home");
+ let checkout = tmp.path().join("outside/repo");
+ fs::create_dir_all(&home).unwrap();
+ fs::create_dir_all(&checkout).unwrap();
+ write_marker(
+ &home,
+ "workspace = \"wrong\"\nproject = \"wrong\"\n[routes.path.\"relative\"]\nroute_workspace = \"oss\"\nroute_project = \"api\"\n",
+ );
+ assert!(
+ routing_selection_with_home(
+ checkout.to_str().unwrap(),
+ checkout.to_str().unwrap(),
+ Some(&home),
+ false,
+ )
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn old_root_parser_ignores_namespaced_route_fields() {
+ let text = r#"
+[routes.identity."github.com/acme/api"]
+route_workspace = "oss"
+route_project = "acme-api"
+route_identity_style = "path"
+route_aliases = ["main"]
+"#;
+ assert_eq!(parse_key_in(text, "workspace"), None);
+ assert_eq!(parse_key_in(text, "project"), None);
+ assert_eq!(parse_key_in(text, "identity_style"), None);
+ assert_eq!(parse_aliases_in(text).unwrap(), None);
+ }
+
#[test]
fn parse_toml_key_extracts_root_level_strings() {
let tmp = TempDir::new().unwrap();
@@ -840,6 +1934,7 @@ project = "infra" # this is fine
write_marker(&inner, "[capture]\nignore_paths = [\"secret/**\"]\n");
let scope = read_scope(inner.to_str().unwrap(), &RuntimeEnv::default())
+ .unwrap()
.expect("the outer marker still declares scope");
assert_eq!(scope.workspace.as_deref(), Some("acme"));
assert_eq!(scope.project.as_deref(), Some("infra"));
@@ -862,7 +1957,7 @@ project = "infra" # this is fine
write_marker(&inner, "[capture]\nignore_paths = [\"other/**\"]\n");
assert_eq!(
- read_scope(inner.to_str().unwrap(), &RuntimeEnv::default()),
+ read_scope(inner.to_str().unwrap(), &RuntimeEnv::default()).unwrap(),
None
);
}
@@ -881,7 +1976,7 @@ project = "infra" # this is fine
write_marker(&inner, "[briefing]\ninject_on_session_start = true\n");
assert_eq!(
- read_scope(inner.to_str().unwrap(), &RuntimeEnv::default()),
+ read_scope(inner.to_str().unwrap(), &RuntimeEnv::default()).unwrap(),
None,
"a briefing-only marker is a settings boundary: it stops the walk \
but declares no scope of its own"
@@ -923,7 +2018,7 @@ project = "infra" # this is fine
assert_eq!(inspection.fields.project.as_deref(), Some("infra"));
assert_eq!(
inspection.scope,
- read_scope(inner.to_str().unwrap(), &RuntimeEnv::default())
+ read_scope(inner.to_str().unwrap(), &RuntimeEnv::default()).unwrap()
);
}
diff --git a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
index 03d5ce94..13bd8b95 100644
--- a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
@@ -153,7 +153,7 @@ mod slow {
);
assert_eq!(
report["project_coordinate"]["local"]["marker_status"],
- "absent"
+ "bypassed_explicit_scope"
);
assert_eq!(report["identity"]["version"], env!("CARGO_PKG_VERSION"));
@@ -371,6 +371,96 @@ mod slow {
drop(server);
}
+ #[tokio::test]
+ async fn invalid_home_routes_refuse_before_any_server_request_but_explicit_pair_bypasses() {
+ use std::sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ };
+
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+ let project = tempfile::tempdir().expect("project cwd");
+ fs::write(
+ home.path().join(".ai-memory.toml"),
+ "workspace=\"fallback\"\nproject=\"fallback\"\n[routes.path.\"~/..\"]\nroute_workspace=\"bad\"\nroute_project=\"bad\"\n",
+ )
+ .unwrap();
+ let requests = Arc::new(AtomicUsize::new(0));
+ let seen = requests.clone();
+ let app = axum::Router::new().fallback(move || {
+ let seen = seen.clone();
+ async move {
+ seen.fetch_add(1, Ordering::SeqCst);
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "unexpected request",
+ )
+ }
+ });
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let first_data_dir = data_dir.path().to_path_buf();
+ let first_home = home.path().to_path_buf();
+ let first_cwd = project.path().to_path_buf();
+ let first_base = base.clone();
+ let output = tokio::task::spawn_blocking(move || {
+ hermetic(BIN)
+ .args(["doctor", "--json"])
+ .env("AI_MEMORY_DATA_DIR", first_data_dir)
+ .env("AI_MEMORY_HOME", first_home)
+ .env("AI_MEMORY_SERVER_URL", first_base)
+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")
+ .current_dir(first_cwd)
+ .output()
+ .unwrap()
+ })
+ .await
+ .unwrap();
+ assert!(!output.status.success(), "{output:?}");
+ assert!(
+ String::from_utf8_lossy(&output.stderr).contains("invalid home route map"),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ assert_eq!(requests.load(Ordering::SeqCst), 0);
+
+ let second_data_dir = data_dir.path().to_path_buf();
+ let second_home = home.path().to_path_buf();
+ let second_cwd = project.path().to_path_buf();
+ let explicit = tokio::task::spawn_blocking(move || {
+ hermetic(BIN)
+ .args([
+ "doctor",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ PROJECT,
+ "--json",
+ ])
+ .env("AI_MEMORY_DATA_DIR", second_data_dir)
+ .env("AI_MEMORY_HOME", second_home)
+ .env("AI_MEMORY_SERVER_URL", base)
+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")
+ .current_dir(second_cwd)
+ .output()
+ .unwrap()
+ })
+ .await
+ .unwrap();
+ assert!(
+ requests.load(Ordering::SeqCst) > 0,
+ "explicit scope must reach the server"
+ );
+ assert!(
+ !explicit.status.success(),
+ "the deliberately failing server remains observable"
+ );
+ server.abort();
+ }
+
#[tokio::test]
async fn ambiguous_coordinate_keeps_local_sessions_and_marks_capture_unavailable() {
let data_dir = tempfile::tempdir().expect("data dir");
diff --git a/crates/ai-memory-core/fixtures/home_route_cases.json b/crates/ai-memory-core/fixtures/home_route_cases.json
new file mode 100644
index 00000000..a25c1123
--- /dev/null
+++ b/crates/ai-memory-core/fixtures/home_route_cases.json
@@ -0,0 +1,251 @@
+{
+ "_comment": "Portable home-route grammar and selector contract shared by native Rust, POSIX shell, PowerShell, generated TypeScript, and OpenClaw runtime tests. Tokens {{HOME}} and {{LONG_513}} are expanded by each test harness. Generated cases describe bounded expansions without storing oversized fixtures.",
+ "cases": [
+ {
+ "name": "identity_precedes_path",
+ "toml": "workspace = \"wrong\"\nproject = \"wrong\"\nproject_strategy = \"repo-root\"\ndrop_subagent_captures = \"true\"\n[recall]\ndefault_global = true\n[briefing]\ninject_on_session_start = true\nmax_chars = 3210\n[profile]\ncontribute = true\nconsume = false\n[routes.path.\"~/src/api\"]\nroute_workspace = \"path\"\nroute_project = \"path-api\"\n[routes.identity.\"github.com/acme/api\"]\nroute_workspace = \"identity\"\nroute_project = \"identity-api\"\nroute_identity_style = \"path\"\nroute_aliases = [\"main\"]\n[routes.identity.\"gitlab.com/acme/api\"]\nroute_workspace = \"gitlab\"\nroute_project = \"gitlab-api\"\n",
+ "cwd": "{{HOME}}/src/api/lib",
+ "identity": "github.com/acme/api",
+ "status": "valid",
+ "source": "identity",
+ "workspace": "identity",
+ "project": "identity-api",
+ "style": "path",
+ "aliases": "[\"main\"]",
+ "flags": "drop_subagent=true&default_global=true&briefing=true&briefing_budget=3210&profile_contribute=1&profile_consume=0"
+ },
+ {
+ "name": "cross_forge_identity",
+ "toml": "[routes.identity.\"github.com/acme/api\"]\nroute_workspace = \"github\"\nroute_project = \"github-api\"\n[routes.identity.\"gitlab.com/acme/api\"]\nroute_workspace = \"gitlab\"\nroute_project = \"gitlab-api\"\n",
+ "cwd": "{{HOME}}/elsewhere",
+ "identity": "gitlab.com/acme/api",
+ "status": "valid",
+ "source": "identity",
+ "workspace": "gitlab",
+ "project": "gitlab-api"
+ },
+ {
+ "name": "path_longest_match",
+ "toml": "[routes.path.\"~/src\"]\nroute_workspace = \"path\"\nroute_project = \"broad\"\n[routes.path.\"~/src/api\"]\nroute_workspace = \"path\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api/lib",
+ "status": "valid",
+ "source": "path",
+ "workspace": "path",
+ "project": "api"
+ },
+ {
+ "name": "path_sibling_refusal",
+ "toml": "[routes.path.\"~/src/api\"]\nroute_workspace = \"path\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api-sibling",
+ "status": "none"
+ },
+ {
+ "name": "path_aliases_without_remote",
+ "toml": "[routes.path.\"~/non-git/api\"]\nroute_workspace = \"path\"\nroute_project = \"api\"\nroute_aliases = [\"old-api\"]\n",
+ "cwd": "{{HOME}}/non-git/api",
+ "status": "valid",
+ "source": "path",
+ "workspace": "path",
+ "project": "api"
+ },
+ {
+ "name": "posix_absolute",
+ "toml": "[routes.path.\"/srv/work/api\"]\nroute_workspace = \"posix\"\nroute_project = \"api\"\n",
+ "cwd": "/srv/work/api/lib",
+ "status": "valid",
+ "source": "path",
+ "workspace": "posix",
+ "project": "api"
+ },
+ {
+ "name": "windows_drive",
+ "toml": "[routes.path.\"C:/Work/API\"]\nroute_workspace = \"windows\"\nroute_project = \"drive\"\n",
+ "cwd": "c:/work/api/lib",
+ "status": "valid",
+ "source": "path",
+ "workspace": "windows",
+ "project": "drive"
+ },
+ {
+ "name": "windows_unc",
+ "toml": "[routes.path.\"//Server/Share/API\"]\nroute_workspace = \"windows\"\nroute_project = \"unc\"\n",
+ "cwd": "//server/share/api/lib",
+ "status": "valid",
+ "source": "path",
+ "workspace": "windows",
+ "project": "unc"
+ },
+ {
+ "name": "tilde_normalization_stays_inside_home",
+ "toml": "[routes.path.\"~/a/../b\"]\nroute_workspace = \"home\"\nroute_project = \"inside\"\n",
+ "cwd": "{{HOME}}/b/lib",
+ "status": "valid",
+ "source": "path",
+ "workspace": "home",
+ "project": "inside"
+ },
+ {
+ "name": "tilde_parent_escape",
+ "toml": "[routes.path.\"~/..\"]\nroute_workspace = \"home\"\nroute_project = \"escape\"\n",
+ "cwd": "{{HOME}}/src",
+ "status": "invalid"
+ },
+ {
+ "name": "tilde_nested_parent_escape",
+ "toml": "[routes.path.\"~/a/../..\"]\nroute_workspace = \"home\"\nroute_project = \"escape\"\n",
+ "cwd": "{{HOME}}/src",
+ "status": "invalid"
+ },
+ {
+ "name": "normalized_duplicate_paths",
+ "toml": "[routes.path.\"~/src/api\"]\nroute_workspace = \"one\"\nroute_project = \"one\"\n[routes.path.\"~/src/./api\"]\nroute_workspace = \"two\"\nroute_project = \"two\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "duplicate_raw_selector_across_kinds",
+ "toml": "[routes.path.\"github.com/acme/api\"]\nroute_workspace = \"one\"\nroute_project = \"one\"\n[routes.identity.\"github.com/acme/api\"]\nroute_workspace = \"two\"\nroute_project = \"two\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "identity": "github.com/acme/api",
+ "status": "invalid"
+ },
+ {
+ "name": "duplicate_field",
+ "toml": "[routes.path.\"~/src/api\"]\nroute_workspace = \"one\"\nroute_workspace = \"two\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "unknown_field",
+ "toml": "[routes.path.\"~/src/api\"]\nroute_workspace = \"one\"\nroute_project = \"api\"\nroute_unknown = \"x\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "malformed_unrelated_toml",
+ "toml": "workspace = [\n[routes.path.\"~/src/api\"]\nroute_workspace = \"one\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "malformed_routes_assignment",
+ "toml": "routes = \"invalid\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "malformed_routes_dotted_key",
+ "toml": "routes.path = \"invalid\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "malformed_root_without_route_syntax",
+ "toml": "workspace = wrong\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "none"
+ },
+ {
+ "name": "malformed_root_scalar_trailing_junk",
+ "toml": "workspace = \"wrong\" junk \"x\"\n[routes.path.\"~/src/api\"]\nroute_workspace = \"one\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "orphan_route_assignment",
+ "toml": "route_project = \"x\"\n[routes.path.\"~/src/api\"]\nroute_workspace = \"one\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "posix_root_selector",
+ "toml": "[routes.path.\"/\"]\nroute_workspace = \"root\"\nroute_project = \"posix\"\n",
+ "cwd": "/child",
+ "status": "invalid"
+ },
+ {
+ "name": "windows_drive_root_selector",
+ "toml": "[routes.path.\"C:/\"]\nroute_workspace = \"root\"\nroute_project = \"drive\"\n",
+ "cwd": "C:/child",
+ "status": "invalid"
+ },
+ {
+ "name": "windows_unc_root_selector",
+ "toml": "[routes.path.\"//server/share\"]\nroute_workspace = \"root\"\nroute_project = \"unc\"\n",
+ "cwd": "//server/share/child",
+ "status": "invalid"
+ },
+ {
+ "name": "identity_host_starts_dot",
+ "toml": "[routes.identity.\".github.com/acme/api\"]\nroute_workspace = \"one\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "identity": ".github.com/acme/api",
+ "status": "invalid"
+ },
+ {
+ "name": "identity_host_ends_dot",
+ "toml": "[routes.identity.\"github.com./acme/api\"]\nroute_workspace = \"one\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "identity": "github.com./acme/api",
+ "status": "invalid"
+ },
+ {
+ "name": "selector_512_bytes",
+ "generate": "selector_512",
+ "cwd_generate": "selector_512_child",
+ "cwd": "/unused",
+ "status": "valid",
+ "source": "path",
+ "workspace": "bounds",
+ "project": "valid"
+ },
+ {
+ "name": "selector_513_bytes",
+ "generate": "selector_513",
+ "cwd": "/selector/target/lib",
+ "status": "invalid"
+ },
+ {
+ "name": "malformed_partial_header",
+ "toml": "workspace = \"wrong\"\nproject = \"wrong\"\n[routes.path.\"~/src/api\"\nroute_workspace = \"one\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "multiline_aliases",
+ "toml": "[routes.path.\"~/src/api\"]\nroute_workspace = \"one\"\nroute_project = \"api\"\nroute_aliases = [\n \"old\"\n]\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "trailing_comma_aliases",
+ "toml": "[routes.path.\"~/src/api\"]\nroute_workspace = \"one\"\nroute_project = \"api\"\nroute_aliases = [\"old\",]\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "escaped_scalar",
+ "toml": "[routes.path.\"~/src/api\"]\nroute_workspace = \"wo\\u0072k\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "scalar_byte_limit",
+ "toml": "[routes.path.\"~/src/api\"]\nroute_workspace = \"{{LONG_513}}\"\nroute_project = \"api\"\n",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ },
+ {
+ "name": "route_limit",
+ "generate": "65_routes",
+ "cwd": "{{HOME}}/route/64",
+ "status": "invalid"
+ },
+ {
+ "name": "file_limit",
+ "generate": "oversized_file",
+ "cwd": "{{HOME}}/src/api",
+ "status": "invalid"
+ }
+ ]
+}
diff --git a/crates/ai-memory-hooks/tests/suite/powershell_marker_aliases.rs b/crates/ai-memory-hooks/tests/suite/powershell_marker_aliases.rs
index 49e796ad..fa23c1a3 100644
--- a/crates/ai-memory-hooks/tests/suite/powershell_marker_aliases.rs
+++ b/crates/ai-memory-hooks/tests/suite/powershell_marker_aliases.rs
@@ -91,3 +91,228 @@ fn powershell_marker_aliases_are_bounded_and_forwarded_with_remote_identity() {
"{query}"
);
}
+
+fn powershell_route_query(home: &Path, cwd: &str) -> String {
+ let helper = repo_root()
+ .join("hooks/lib/ai-memory-hook.ps1")
+ .to_string_lossy()
+ .replace('\'', "''");
+ let cwd = cwd.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", home)
+ .env("USERPROFILE", home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ String::from_utf8(output.stdout).unwrap()
+}
+
+#[test]
+fn powershell_home_routes_match_drive_paths_and_forward_identity_aliases() {
+ let temp = tempfile::tempdir().unwrap();
+ let home = temp.path().join("Home");
+ let repo = temp.path().join("Outside").join("Repo");
+ std::fs::create_dir_all(&home).unwrap();
+ 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(
+ home.join(".ai-memory.toml"),
+ format!(
+ "[routes.path.\"{}\"]\nroute_workspace=\"path\"\nroute_project=\"wrong\"\n[routes.identity.\"github.com/acme/api\"]\nroute_workspace=\"oss\"\nroute_project=\"acme-api\"\nroute_identity_style=\"path\"\nroute_aliases=[\"main\"]\n",
+ repo.to_string_lossy().replace('\\', "/")
+ ),
+ )
+ .unwrap();
+ let helper = repo_root()
+ .join("hooks/lib/ai-memory-hook.ps1")
+ .to_string_lossy()
+ .replace('\'', "''");
+ let cwd = repo.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", &home)
+ .env("USERPROFILE", &home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let query = String::from_utf8(output.stdout).unwrap();
+ assert!(
+ query.contains("&workspace=oss&project=acme-api&project_src=marker"),
+ "{query}"
+ );
+ assert!(
+ query.contains(
+ "&identity=github.com%2Facme%2Fapi&identity_src=git_remote&identity_style=path"
+ ),
+ "{query}"
+ );
+ assert!(query.contains("&aliases=%5B%22main%22%5D"), "{query}");
+}
+
+#[test]
+fn powershell_home_routes_execute_shared_fixture() {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../ai-memory-core/fixtures/home_route_cases.json"
+ ))
+ .unwrap();
+ let temp = tempfile::tempdir().unwrap();
+ let home = temp.path().join("Home");
+ std::fs::create_dir_all(&home).unwrap();
+ let helper = repo_root()
+ .join("hooks/lib/ai-memory-hook.ps1")
+ .to_string_lossy()
+ .replace('\'', "''");
+ for case in fixture["cases"].as_array().unwrap() {
+ let text = match case["generate"].as_str() {
+ Some("65_routes") => (0..65)
+ .map(|index| format!("[routes.path.\"C:/route/{index}\"]\nroute_workspace=\"ws\"\nroute_project=\"p{index}\"\n"))
+ .collect(),
+ Some("selector_512") => format!(
+ "[routes.path.\"/{}\"]\nroute_workspace=\"bounds\"\nroute_project=\"valid\"\n",
+ "a".repeat(511)
+ ),
+ Some("selector_513") => format!(
+ "[routes.path.\"/{}\"]\nroute_workspace=\"bounds\"\nroute_project=\"invalid\"\n",
+ "a".repeat(512)
+ ),
+ Some("oversized_file") => format!("#{}\n", "x".repeat(65_536)),
+ Some(other) => panic!("unknown fixture generator {other}"),
+ None => case["toml"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", &home.to_string_lossy().replace('\\', "/"))
+ .replace("{{LONG_513}}", &"a".repeat(513)),
+ };
+ let marker = home.join(".ai-memory.toml");
+ std::fs::write(&marker, text).unwrap();
+ let cwd = match case["cwd_generate"].as_str() {
+ Some("selector_512_child") => format!("/{}/child", "a".repeat(511)),
+ Some(other) => panic!("unknown cwd fixture generator {other}"),
+ None => case["cwd"]
+ .as_str()
+ .unwrap()
+ .replace("{{HOME}}", &home.to_string_lossy().replace('\\', "/")),
+ }
+ .replace('\'', "''");
+ let identity = case["identity"].as_str().unwrap_or("").replace('\'', "''");
+ let marker = marker.to_string_lossy().replace('\'', "''");
+ let program = format!(
+ ". '{helper}'; $r=Get-AiMemoryHomeRoute -File '{marker}' -Cwd '{cwd}' -Identity '{identity}'; if ($r -eq 'invalid') {{ [Console]::Out.Write('invalid') }} elseif ($null -eq $r) {{ [Console]::Out.Write('none') }} else {{ [Console]::Out.Write($r.Workspace+'/'+$r.Project) }}"
+ );
+ let output = Command::new(ai_memory_test_support::powershell_exe())
+ .args([
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-Command",
+ &program,
+ ])
+ .env("HOME", &home)
+ .env("USERPROFILE", &home)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let expected = match case["status"].as_str().unwrap() {
+ "valid" => format!(
+ "{}/{}",
+ case["workspace"].as_str().unwrap(),
+ case["project"].as_str().unwrap()
+ ),
+ status => status.to_owned(),
+ };
+ assert_eq!(
+ String::from_utf8(output.stdout).unwrap(),
+ expected,
+ "{}",
+ case["name"]
+ );
+ }
+}
+
+#[test]
+fn powershell_non_git_path_route_omits_aliases() {
+ let temp = tempfile::tempdir().unwrap();
+ let home = temp.path().join("Home");
+ let repo = home.join("src/api");
+ std::fs::create_dir_all(&repo).unwrap();
+ std::fs::write(
+ home.join(".ai-memory.toml"),
+ "[routes.path.\"~/src/api\"]\nroute_workspace=\"path\"\nroute_project=\"api\"\nroute_aliases=[\"old-api\"]\n",
+ )
+ .unwrap();
+ let query = powershell_route_query(&home, &repo.to_string_lossy());
+ assert!(query.contains("&workspace=path&project=api"), "{query}");
+ assert!(!query.contains("aliases="), "{query}");
+ assert!(!query.contains("identity_src="), "{query}");
+}
+
+#[test]
+fn powershell_home_routes_match_drive_and_unc_without_identity() {
+ let temp = tempfile::tempdir().unwrap();
+ let home = temp.path().join("Home");
+ std::fs::create_dir_all(&home).unwrap();
+ std::fs::write(
+ home.join(".ai-memory.toml"),
+ "[routes.path.\"C:/Work/API\"]\nroute_workspace=\"windows\"\nroute_project=\"drive\"\n[routes.path.\"//Server/Share/API\"]\nroute_workspace=\"windows\"\nroute_project=\"unc\"\n",
+ )
+ .unwrap();
+ let drive = powershell_route_query(&home, r"c:\work\api\lib");
+ assert!(
+ drive.contains("&workspace=windows&project=drive"),
+ "{drive}"
+ );
+ assert!(!drive.contains("identity_src="), "{drive}");
+ let unc = powershell_route_query(&home, r"\\server\share\api\lib");
+ assert!(unc.contains("&workspace=windows&project=unc"), "{unc}");
+ assert!(!unc.contains("identity_src="), "{unc}");
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index b76d5c3c..780d6a0c 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -394,7 +394,7 @@ prunable rather than only after it ages in place.
| Table | What |
|---|---|
-| `workspaces`, `projects` | Top of the 3-tuple identity coordinate. `projects.identity` / `identity_source` (V70, #708) hold the repository identity a project routes by — an explicit marker `identity` or a normalised git remote, resolved client-side — unique per workspace when set; empty until a capture claims the project. A marker's `identity_style = "path"` (#1033, forwarded as the `identity_style` hook query param alongside a git-remote identity; default `host_path`) names a project that resolution *creates* from the repository path without the host (`acme-api`), falling back to the usual name when another project already holds it. V76 stores indexed canonical and v2-basename keys derived from that full identity: reads are no-create/no-rename, while an authorized explicit write through the canonical name promotes only `projects.name` in the same resolve-or-create writer transaction and preserves the UUID. Project `_meta.md` carries the optional full identity/source plus derived keys; clean reindex validates them and rebuilds the same UUID/name/coordinate lookup, while older manifests without identity remain valid. Ambiguous cross-forge or multi-candidate keys fail closed. A local marker may additionally send up to 16 validated former names as one transient `aliases` JSON-array query value: lookup stays inside its selected workspace, requires the checkout's full hostful git-remote identity to equal the stored row, returns reads without rename, and lets capture perform only the same authorized UUID-preserving canonical promotion. Aliases are not stored and remain distinct in the hook routing cache. 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. The exact operator-home marker may additionally define bounded `[routes.identity."host/path"]` and `[routes.path."absolute-or-tilde-path"]` blocks: an exact hostful remote match wins the longest component-wise lexical path match, any reachable non-home local settings marker wins both, malformed or ambiguous route maps fail closed, and selected fields reuse the existing marker wire without a server/schema change. `AI_MEMORY_HOME` is authoritative for native callers; portable clients use `HOME`/`USERPROFILE`, and Docker compares its forwarded host cwd. See `docs/marker-file.md#repository-identity`. `projects.access_mode` (V68; `open` default / `restricted`) decides whether any authenticated user or only root, the creator (`projects.created_by`, V69) and grant holders (`project_grants`, V68) reach it, decided by `ai_memory_store::authorize_project` — `docs/users.md#per-project-access`. `projects.profile_contribute` / `profile_consume` (V74) record the marker's `[profile]` opt-outs, forwarded at session start; `profile_candidates`, `profile_harvest_marks` and `profile_entry_ledger` (V75) hold the profile pass's evidence, per-project read position and the entries it wrote. Reserved projects: `scratch`, `_global` (shared preferences; holds the single-user profile under `profile/`), `_profile` (a workspace profile) and `_profile.<user id>` (a private profile, always `restricted`); capture is never attributed to any of them — `docs/cross-project-profile.md`. |
| `pages` | Versioned wiki pages with `is_latest` + `supersedes` chain. M8 columns: `last_accessed_at`, `access_count`, and decay-only tombstone marker `superseded_at`. M9 cols: `embedding_provider`, `embedding_model`, `embedding_dim`. V36: `expires_at` (frontmatter TTL). V37: `salience` (NULL = `salience_default`; derived from `page_feedback`). |
| `pages_fts` | FTS5 virtual table over `(title, body)`, auto-synced by triggers. |
| `sessions`, `observations` | Sanitized, bounded lifecycle-hook projections. `sessions.ended_observation_count` is the stable generation watermark for resumed-session re-end eligibility; wall clocks are not used for that decision. They are an operational audit trail, not a complete native transcript. |
diff --git a/docs/design-per-project-authz.md b/docs/design-per-project-authz.md
index 541a87e2..e6f78563 100644
--- a/docs/design-per-project-authz.md
+++ b/docs/design-per-project-authz.md
@@ -291,7 +291,15 @@ project. #1033 makes a remote-derived key the default name, landing in steps on
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.
+6. **Operator-home routes (landed).** The exact operator-home
+ `.ai-memory.toml` accepts bounded namespaced identity and path tables. Exact
+ normalized hostful identity wins the longest component-safe lexical path;
+ local non-home settings markers win both. Route project names are canonical,
+ route aliases reuse the Phase 3 wire only with remote identity plus marker
+ provenance, malformed or ambiguous maps fail closed, and old line parsers
+ ignore the deliberately prefixed `route_*` child fields. Native callers use
+ `AI_MEMORY_HOME` first; portable clients use `HOME`/`USERPROFILE`, and Docker
+ compares the forwarded host cwd. The default remains `IdentityStyle::HostPath`.
Paths stay lexically normalised throughout; nothing canonicalises.
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 54aa2699..88c2f999 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -196,6 +196,62 @@ 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.
+### Operator-home routes
+
+The exact operator-home marker (`$AI_MEMORY_HOME/.ai-memory.toml`, otherwise
+`$HOME/.ai-memory.toml`, with `%USERPROFILE%` as the portable Windows fallback)
+may route many unrelated checkouts without placing a marker in each repository:
+
+```toml
+[routes.identity."github.com/acme/api"]
+route_workspace = "oss"
+route_project = "acme-api"
+route_identity_style = "path"
+route_aliases = ["main"]
+
+[routes.path."~/src/api"]
+route_workspace = "oss"
+route_project = "acme-api"
+route_aliases = ["old-api"]
+```
+
+Identity selectors must be exact normalized hostful remote identities; a
+hostless `acme/api` selector is invalid. Path selectors must be absolute or
+`~/`-relative. They are normalized lexically without resolving symlinks, support
+POSIX, Windows drive, and UNC roots, and match by path components: `/team-b`
+does not match `/team-bb`. A `~/` selector may normalize within HOME (for
+example `~/a/../b`) but is rejected if any `..` would escape above HOME;
+absolute selectors retain lexical root clamping. The longest path match wins, while an exact identity
+match wins over every path match. A reachable non-home local settings marker
+wins over all home routes. When no route matches, existing root-level settings
+in the home marker remain the fallback, followed by the installed strategy and
+existing cwd fallbacks; explicit CLI scope always wins. A matched route replaces
+only the root `workspace`, `project`, `identity`, `identity_style`, `aliases`, and
+`project_strategy` routing fields. Root `server`, `drop_subagent_captures`,
+`[recall]`, `[briefing]`, and `[profile]` settings still apply.
+
+A home route map is bounded to 64 routes, a 64 KiB file, 512 UTF-8 bytes per
+selector, and 512 UTF-8 bytes per scalar value. Its portable grammar permits
+only exact `[routes.identity."selector"]` and `[routes.path."selector"]` table
+headers followed by one declaration of each supported `route_*` field. Workspace
+and project are required; style and aliases are optional. Aliases must be a
+one-line JSON-compatible string array under the normal `MarkerAliases` limits.
+Duplicate raw selectors across either route kind, normalized duplicate paths,
+equal normalized identities, duplicate fields, multiline arrays, trailing
+commas, escapes, malformed selectors or fields, unknown route keys, invalid
+styles, and invalid aliases invalidate the whole route map rather than choosing
+a project. Recognizable route syntax includes `[routes`, `routes =`, `routes.`,
+and orphan `route_*` declarations; malformed root-only settings with none of
+those forms retain the historical line parser behavior. An invalid or oversized map never falls back to root-home scope:
+commands without a complete explicit workspace/project pair fail, while hooks
+accept the lifecycle call but drop it before spool or network. Route aliases use the same bounds and grammar as local
+marker aliases and are forwarded only with a discovered hostful git remote and
+`project_src=marker`. The `route_*` child names are deliberate: older line-based
+clients ignore them instead of treating route fields as root settings. Portable clients use `HOME`, then `USERPROFILE`; native CLI/hooks honor
+`AI_MEMORY_HOME` first. The Docker wrapper passes the host cwd, so path routes
+compare in the host namespace rather than `/work` while remote discovery may
+fall back to the mounted checkout.
+
`project_strategy` accepts `repo-root` (or `repo_root`) only. Unknown
values are ignored and behave like the default `basename(cwd)` strategy.
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index c7bd85e6..1f636e69 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -81,7 +81,8 @@ 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 |
+| 14bb | Local marker aliases cannot cross repository or workspace boundaries (#1033) | `ai-memory-core/src/repository_identity.rs` owns the bounded `MarkerAliases` type and exact one-line/root-level portable grammar; native/POSIX/PowerShell/generated TypeScript clients forward one normalized JSON-array query value only with marker provenance and a hostful git-remote identity; `ai-memory-store/src/project_coordinates.rs` probes exact names only inside the selected workspace, deduplicates by UUID, and requires the selected row's full stored git-remote identity; `ops.rs` authorizes in the writer transaction and reuses Phase 1 `promotion_target`, additionally requiring marker `project` to equal the canonical path-style name derived from that remote; handoff uses the read-only path and capture uses the write-authorized path; `router.rs` includes aliases, provenance, and read/write mode in its cache key | Core/CLI shared `marker_aliases` fixture parity covers duplicate keys, table placement, multiline arrays, trailing junk/comma, escapes, max length and duplicate-heavy over-count; store `marker_aliases_require_same_remote_identity_and_preserve_uuid`, `marker_aliases_cannot_promote_to_an_arbitrary_marker_project`, `hostile_ambiguous_and_cross_workspace_marker_aliases_fail_closed`; hooks `hook_and_handoff_queries_validate_aliases_identically`, `malformed_aliases_are_rejected_before_subagent_scope_resolution`, `empty_aliases_preserve_marker_project_precedence`, `capture_promotes_an_alias_but_handoff_only_reads_it`, `project_cache_separates_alias_sets`; shell `marker aliases keep canonical project and forward remote identity`; Windows PowerShell parity and capture-only marker transparency run in Windows CI; OpenClaw `openclaw_runtime_gates_local_identity_but_allows_alias_and_home_route_identity` proves ordinary local markers omit identity while alias markers and home identity routes forward it | STRONG: hostile arbitrary-name, different-identity and ambiguous aliases refuse or resolve without rename with a legitimate canonical same-identity control; another workspace is never searched; no alias table or persistent fallback exists |
+| 14bb2 | Operator-home route selectors cannot silently cross repository or path boundaries (#1033) | `ai-memory-cli/src/marker.rs` returns a typed invalid result for malformed/oversized maps; command scope resolution propagates it unless both CLI scope fields are explicit, while native hooks drop before spool/network. The native, POSIX, PowerShell, generated TypeScript and OpenClaw parsers enforce the shared 64-route/64-KiB/512-byte grammar, recognize malformed `[routes`, `routes =`, `routes.`, and orphan `route_*` syntax before any no-routes return, preserve legacy parsing for malformed root-only settings without route syntax, apply global duplicate-field/raw-selector/normalized-path checks, require exact hostful identities (including host-edge-dot refusal), match paths component-wise, and enforce a no-escape boundary for `~/` selectors. A route replaces only routing fields; root privacy/behavior flags survive. Bounded native/PowerShell/TypeScript reads reject before full-file allocation where their APIs permit. | `ai-memory-core/fixtures/home_route_cases.json` is executed by native `marker.rs`, POSIX, PowerShell, generated TypeScript, and OpenClaw runtime parity, including malformed route syntax and root-only malformed legacy behavior; shell `test_lib.sh` also exercises route selection, sibling refusal, root-setting retention and invalid-map drop; Windows `powershell_marker_aliases.rs` executes drive and UNC path routing independently of identity; generated TypeScript runtime tests assert marker versus repo-root `project_src`; CLI tests prove unscoped/partial refusal and complete-explicit bypass. | STRONG for native/POSIX/generated TypeScript/OpenClaw on this platform; PowerShell runtime evidence is enforced on Windows CI and skipped where PowerShell is unavailable |
| 14bc | Project-coordinate diagnostics are root-only, read-only and credential-safe (#1033) | `ai-memory-store/src/reader.rs` `diagnose_project_coordinate` and `project_coordinates.rs` share one bounded indexed matcher and the write path's canonical-only promotion predicate; `ai-memory-mcp/src/admin.rs` mounts `GET /admin/project-coordinate` behind the shared `Capability::Admin` middleware and returns no stored identity value; `ai-memory-cli/src/marker.rs` and `commands/hook_capture.rs` provide one strict typed local inspection consumed by `doctor`, which reports only marker/source classes, identity source/style and derived names. Ambiguous count lookup keeps local rows and marks captured counts unavailable | Store `identity_resolution.rs` `coordinate_diagnostic_classifies_exact_canonical_legacy_and_missing_without_mutation`, `coordinate_diagnostic_reports_cross_forge_and_identityless_collisions`; `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; MCP `admin_status_search.rs` `project_coordinate_reports_all_statuses_and_never_mutates`, `project_coordinate_is_root_only_after_multiuser_enablement`, `project_coordinate_single_user_admin_contract_remains_open`, plus the shared all-admin 403/401 route matrix; CLI `doctor.rs` `project_coordinate_renders_promotion_and_cross_forge_fallback_concisely`, `local_coordinate_reports_marker_precedence_invalid_toml_and_no_credentials`; `marker.rs` strict inspection tests; `doctor_e2e.rs` `ambiguous_coordinate_keeps_local_sessions_and_marks_capture_unavailable` | STRONG: project/audit/user/grant/page counts, names and manifest bytes are snapshotted; DB-user/anonymous refusal has a root control; sentinel repo paths, identities, users, grants, pages, malformed marker text, absolute marker paths and credential-bearing remotes do not appear in output; an ambiguous preferred candidate remains contextual only and is never rename-eligible |
| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
| 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.sh
index 1c88a9d5..2e6b4e65 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -193,9 +193,15 @@ ai_memory_find_settings_marker() {
esac
fi
while [ -n "$dir" ] && [ "$dir" != "/" ]; do
- if [ -f "$dir/.ai-memory.toml" ] && ai_memory_marker_declares_settings "$dir/.ai-memory.toml"; then
- printf '%s\n' "$dir/.ai-memory.toml"
- return 0
+ if [ -f "$dir/.ai-memory.toml" ]; then
+ if [ -n "$_amhome" ] && [ "$dir" = "$_amhome" ]; then
+ printf '%s\n' "$dir/.ai-memory.toml"
+ return 0
+ fi
+ if ai_memory_marker_declares_settings "$dir/.ai-memory.toml"; then
+ printf '%s\n' "$dir/.ai-memory.toml"
+ return 0
+ fi
fi
if [ -n "$boundary" ] && [ "$dir" = "$boundary" ]; then
return 0
@@ -431,6 +437,114 @@ ai_memory_identity_style_qs() {
return 0
}
+ai_memory_home_route() {
+ _ai_hr_file="$1"; _ai_hr_cwd="$2"; _ai_hr_identity="$3"
+ [ -f "$_ai_hr_file" ] || return 0
+ [ "$(wc -c <"$_ai_hr_file")" -le 65536 ] || { printf 'invalid'; return 0; }
+ LC_ALL=C awk -v cwd="$_ai_hr_cwd" -v home="$_amhome" -v identity="$_ai_hr_identity" '
+ function invalid() { bad = 1 }
+ function cleanpath(value, n, raw, out, i, root, home_relative, rel_depth, j) {
+ gsub(/\\/, "/", value)
+ home_relative = substr(value,1,2) == "~/"
+ if (home_relative) {
+ raw = substr(value,3); n = split(raw,relative_parts,"/"); rel_depth = 0
+ for (j=1; j<=n; j++) if (relative_parts[j] != "" && relative_parts[j] != ".") {
+ if (relative_parts[j] == "..") { if (!rel_depth) return ""; rel_depth-- }
+ else rel_depth++
+ }
+ value = home "/" raw
+ }
+ if (substr(value,1,2) == "//") {
+ raw = substr(value,3); n = split(raw,a,"/")
+ if (n < 2 || a[1] == "" || a[2] == "") return ""
+ root = "unc:" tolower(a[1]) "/" tolower(a[2]); i = 3
+ } else if (value ~ /^[A-Za-z]:\//) {
+ root = "drive:" tolower(substr(value,1,1)); raw = substr(value,4); n = split(raw,a,"/"); i = 1
+ } else if (substr(value,1,1) == "/") {
+ root = "posix"; raw = substr(value,2); n = split(raw,a,"/"); i = 1
+ } else return ""
+ depth = 0; delete stack
+ for (; i <= n; i++) if (a[i] != "" && a[i] != ".") { if (a[i] == "..") { if (depth) depth-- } else stack[++depth] = a[i] }
+ out = root
+ for (i=1; i<=depth; i++) out = out "/" (root == "posix" ? stack[i] : tolower(stack[i]))
+ return out
+ }
+ function aliases_valid(value, body,n,i,item) {
+ if (length(value) > 512 || value ~ /\\/ || value !~ /^\[[^]]*\][[:space:]]*$/) return 0
+ body=value; sub(/^\[/,"",body); sub(/\][[:space:]]*$/,"",body)
+ if (body ~ /^[[:space:]]*$/) return 1
+ if (body ~ /,[[:space:]]*$/) return 0
+ n=split(body,items,","); if (n > 16) return 0
+ for (i=1;i<=n;i++) {
+ item=items[i]
+ if (item !~ /^[[:space:]]*"[A-Za-z0-9][A-Za-z0-9._-]*"[[:space:]]*$/) return 0
+ sub(/^[[:space:]]*"/,"",item); sub(/"[[:space:]]*$/,"",item)
+ if (length(item) > 128) return 0
+ }
+ return 1
+ }
+ function finish( normalized,n) {
+ if (!kind) return
+ count++
+ if (count > 64 || length(selector) > 512 || raw_seen[selector]++) invalid()
+ if (!route_workspace || !route_project || length(route_workspace) > 512 || length(route_project) > 512 || route_workspace !~ /^[a-z0-9][a-z0-9._-]*$/ || route_project !~ /^[a-z0-9][a-z0-9._-]*$/) invalid()
+ if (route_identity_style && route_identity_style != "path" && route_identity_style != "host_path") invalid()
+ if (route_aliases && !aliases_valid(route_aliases)) invalid()
+ if (kind == "identity") {
+ host=selector; sub(/\/.*/,"",host)
+ if (selector != tolower(selector) || selector !~ /^[a-z0-9.-]+(\/[a-z0-9._-]+)+$/ || host ~ /^\./ || host ~ /\.$/ || identity_seen[selector]++) invalid()
+ if (selector == identity) { identity_found = 1; identity_ws = route_workspace; identity_pr = route_project; identity_style = route_identity_style; identity_aliases = route_aliases }
+ } else {
+ normalized = cleanpath(selector)
+ if (!normalized || normalized == "posix" || normalized ~ /^drive:[^/]+$/ || normalized ~ /^unc:[^/]+\/[^/]+$/ || path_seen[normalized]++) invalid()
+ target = cleanpath(cwd)
+ if (normalized == target || index(target, normalized "/") == 1) {
+ n = split(normalized, parts, "/")
+ if (n > best_depth) { best_depth=n; best_ws=route_workspace; best_pr=route_project; best_style=route_identity_style; best_aliases=route_aliases; tie=0 }
+ else if (n == best_depth) tie=1
+ }
+ }
+ kind=""; selector=""; route_workspace=""; route_project=""; route_identity_style=""; route_aliases=""; delete field_seen
+ }
+ BEGIN { count=0; bad=0; best_depth=0; tie=0 }
+ {
+ line=$0; sub(/\r$/, "", line)
+ if (match(line, /^[[:space:]]*\[routes\.(identity|path)\."[^"\\]+"\][[:space:]]*$/)) {
+ saw_route=1; finish(); header=line; sub(/^[[:space:]]*\[routes\./,"",header); kind=substr(header,1,index(header,".")-1); selector=header; sub(/^[^.]+\."/,"",selector); sub(/"\][[:space:]]*$/,"",selector); next
+ }
+ if (line ~ /^[[:space:]]*\[routes/ || line ~ /^[[:space:]]*routes[[:space:]]*=/ || line ~ /^[[:space:]]*routes\./ || line ~ /^[[:space:]]*route_[A-Za-z0-9_]+[[:space:]]*=/) {
+ saw_route=1
+ if (!kind || line ~ /^[[:space:]]*\[/) { finish(); invalid(); next }
+ key=line; sub(/^[[:space:]]*/,"",key); sub(/[[:space:]]*=.*/,"",key)
+ if (field_seen[key]++) { invalid(); next }
+ value=line; sub(/^[^=]*=[[:space:]]*/,"",value)
+ if (key == "route_aliases") { if (!aliases_valid(value)) invalid(); route_aliases=value }
+ else {
+ if (length(value) > 514 || value ~ /\\/ || value !~ /^"[^"]+"[[:space:]]*$/) { invalid(); next }
+ sub(/^"/,"",value); sub(/"[[:space:]]*$/,"",value)
+ if (length(value) > 512) { invalid(); next }
+ if (key == "route_workspace") route_workspace=value
+ else if (key == "route_project") route_project=value
+ else if (key == "route_identity_style") route_identity_style=value
+ else invalid()
+ }
+ next
+ }
+ if (line ~ /^[[:space:]]*\[/) { finish(); next }
+ if (kind && line !~ /^[[:space:]]*(#|$)/) invalid()
+ if (!kind && line ~ /^[[:space:]]*(workspace|project|project_strategy|drop_subagent_captures|identity|identity_style|server)[[:space:]]*=/ && line !~ /^[[:space:]]*[A-Za-z0-9_]+[[:space:]]*=[[:space:]]*"[^"]*"[[:space:]]*$/) root_bad=1
+ }
+ END { finish(); if (saw_route && (bad || root_bad || tie)) print "invalid"; else if (identity_found) print identity_ws "\034" identity_pr "\034" identity_style "\034" identity_aliases; else if (best_depth) print best_ws "\034" best_pr "\034" best_style "\034" best_aliases }
+ ' "$_ai_hr_file" | tail -n 1
+}
+
+ai_memory_aliases_json_value() {
+ _ai_alias_tmp=$(mktemp "${TMPDIR:-/tmp}/ai-memory-aliases.XXXXXX") || return 0
+ printf 'aliases = %s\n' "$1" >"$_ai_alias_tmp"
+ ai_memory_aliases_json "$_ai_alias_tmp"
+ rm -f "$_ai_alias_tmp"
+}
+
ai_memory_aliases_json() {
[ -f "$1" ] || return 0
_ai_alias_body=$(LC_ALL=C awk '
@@ -495,6 +609,16 @@ ai_memory_aliases_json() {
printf '%s]' "$_ai_alias_json"
}
+ai_memory_git_remote_identity() {
+ [ -n "$1" ] || return 0
+ command -v git >/dev/null 2>&1 || return 0
+ for _ai_gri_remote in upstream origin; do
+ _ai_gri_url=$(git -C "$1" config --get "remote.$_ai_gri_remote.url" 2>/dev/null) || continue
+ _ai_gri_value=$(ai_memory_normalize_remote "$_ai_gri_url")
+ [ -n "$_ai_gri_value" ] && { printf '%s' "$_ai_gri_value"; return 0; }
+ done
+}
+
# 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.
@@ -510,17 +634,11 @@ ai_memory_identity_qs() {
return 0
fi
[ -z "$_ai_id_aliases" ] && [ -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")"
- ai_memory_identity_style_qs "$_ai_id_style"
- return 0
- fi
- done
+ _ai_id_value=$(ai_memory_git_remote_identity "$_ai_id_cwd")
+ if [ -n "$_ai_id_value" ]; then
+ printf '&identity=%s&identity_src=git_remote' "$(ai_memory_url_encode "$_ai_id_value")"
+ ai_memory_identity_style_qs "$_ai_id_style"
+ fi
}
# Build a query-string suffix from "$1" plus any marker file walked up from
@@ -542,6 +660,7 @@ ai_memory_marker_qs() {
pr=""
st=""
ds=""
+ dg=""
# Provenance of `pr`, forwarded as `project_src` so the server can tell a
# deliberate marker rescope from a host-derived repo-root name. Only the
# latter may yield to session-sticky attribution (#394).
@@ -551,18 +670,42 @@ ai_memory_marker_qs() {
pcon=""
pcons=""
aliases=""
+ routed=""
# 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.
marker=$(ai_memory_find_settings_marker "$cwd")
+ ai_memory_home
+ home_marker=""
+ [ -n "$_amhome" ] && [ -f "$_amhome/.ai-memory.toml" ] && home_marker="$_amhome/.ai-memory.toml"
+ if [ -z "$marker" ] || [ "$marker" = "$home_marker" ]; then
+ route_identity=$(ai_memory_git_remote_identity "$cwd")
+ route=$(ai_memory_home_route "$home_marker" "$cwd" "$route_identity")
+ if [ "$route" = "invalid" ]; then
+ printf '%s' '&ai_memory_invalid_home_routes=1'
+ return 0
+ fi
+ if [ -n "$route" ]; then
+ old_ifs=$IFS; IFS=$(printf '\034')
+ set -- $route
+ IFS=$old_ifs
+ ws=$1; pr=$2; isty=${3:-}; route_aliases=${4:-}; ps=marker; routed=1
+ [ -n "$route_aliases" ] && aliases=$(ai_memory_aliases_json_value "$route_aliases")
+ marker="$home_marker"
+ if [ -n "$route_identity" ]; then
+ iq="&identity=$(ai_memory_url_encode "$route_identity")&identity_src=git_remote$(ai_memory_identity_style_qs "$isty")"
+ fi
+ fi
+ fi
if [ -n "$marker" ]; then
- ws=$(ai_memory_parse_toml_key "$marker" workspace)
- pr=$(ai_memory_parse_toml_key "$marker" project)
- st=$(ai_memory_parse_toml_key "$marker" project_strategy)
+ [ -n "$routed" ] || ws=$(ai_memory_parse_toml_key "$marker" workspace)
+ [ -n "$routed" ] || pr=$(ai_memory_parse_toml_key "$marker" project)
+ [ -n "$routed" ] || st=$(ai_memory_parse_toml_key "$marker" project_strategy)
ds=$(ai_memory_parse_toml_key "$marker" drop_subagent_captures)
- idn=$(ai_memory_parse_toml_key "$marker" identity)
- isty=$(ai_memory_parse_toml_key "$marker" identity_style)
- aliases=$(ai_memory_aliases_json "$marker")
+ dg=$(ai_memory_parse_toml_flag "$marker" default_global)
+ [ -n "$routed" ] || idn=$(ai_memory_parse_toml_key "$marker" identity)
+ [ -n "$routed" ] || isty=$(ai_memory_parse_toml_key "$marker" identity_style)
+ [ -n "$routed" ] || 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
@@ -573,7 +716,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" "$aliases")
+ [ -n "${iq:-}" ] || iq=$(ai_memory_identity_qs "$cwd" "$idn" "$pr" "$isty" "$aliases")
# Install-time default baked into the hook command by
# `install-hooks --project-strategy` fills the strategy only when no marker
# pinned one. A marker's explicit project / project_strategy still win.
@@ -603,13 +746,14 @@ ai_memory_marker_qs() {
case "$iq" in *'identity_src=git_remote'*)
[ -n "$pr" ] || aliases=invalid
;;
- *) aliases=invalid ;;
+ *) [ -n "$routed" ] && aliases="" || aliases=invalid ;;
esac
- qs="${qs}&aliases=$(ai_memory_url_encode "$aliases")"
+ [ -n "$aliases" ] && 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")"
+ [ -n "$dg" ] && qs="${qs}&default_global=$(ai_memory_url_encode "$dg")"
[ -n "$pcon" ] && qs="${qs}&profile_contribute=$(ai_memory_url_encode "$pcon")"
[ -n "$pcons" ] && qs="${qs}&profile_consume=$(ai_memory_url_encode "$pcons")"
qs="${qs}$(ai_memory_managed_qs)"
@@ -770,7 +914,9 @@ ai_memory_post_hook() {
cat >/dev/null 2>&1 || true
return 0
fi
- case "$1" in *"$AI_MEMORY_SERVER_ROUTED_QS"*) cat >/dev/null; return 0 ;; esac
+ case "$1" in
+ *"$AI_MEMORY_SERVER_ROUTED_QS"*|*'ai_memory_invalid_home_routes=1'*) cat >/dev/null; return 0 ;;
+ esac
_amurl=$(ai_memory_url_with_ingest_key "$1")
_ambody=$(cat)
_amhdr=$(ai_memory_auth_header_file || printf '')
@@ -809,7 +955,9 @@ ai_memory_post_hook() {
# stdout (and prepended to the agent's context), so we want to avoid
# truncating a handoff that was almost ready.
ai_memory_get_handoff() {
- case "$1" in *"$AI_MEMORY_SERVER_ROUTED_QS"*) return 0 ;; esac
+ case "$1" in
+ *"$AI_MEMORY_SERVER_ROUTED_QS"*|*'ai_memory_invalid_home_routes=1'*) return 0 ;;
+ esac
_amhdr=$(ai_memory_auth_header_file)
if [ -n "${AI_MEMORY_AUTH_TOKEN:-}" ]; then
curl -s --max-time 1.0 "$1" \
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index 00438837..5e68af00 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -101,7 +101,10 @@ function Get-AiMemoryMarkerToml {
}
while ($dir -and (Test-Path $dir)) {
$candidate = Join-Path $dir ".ai-memory.toml"
- if ((Test-Path $candidate -PathType Leaf) -and (Test-AiMemoryMarkerDeclaresSettings -File $candidate)) { return $candidate }
+ if (Test-Path $candidate -PathType Leaf) {
+ if ($userHome -and $dir -eq $userHome) { return $candidate }
+ if (Test-AiMemoryMarkerDeclaresSettings -File $candidate) { return $candidate }
+ }
if ($boundary -and $dir -eq $boundary) { return $null }
$parent = Split-Path $dir -Parent
if (-not $parent -or $parent -eq $dir) { return $null }
@@ -200,6 +203,191 @@ function Get-AiMemoryTomlAliases {
}
}
+function Get-AiMemoryRemoteIdentity {
+ param([string] $Cwd)
+ if (-not $Cwd -or -not (Get-Command git -ErrorAction SilentlyContinue)) { return $null }
+ 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 $value }
+ }
+ return $null
+}
+
+function ConvertTo-AiMemoryRouteAliases {
+ param([string] $Raw)
+ if (-not $Raw) { return $null }
+ $match = [regex]::Match($Raw, '^\s*\[([^\]]*)\]\s*$')
+ if (-not $match.Success) { return "invalid" }
+ if (-not $match.Groups[1].Value.Trim()) { return $null }
+ $parts = $match.Groups[1].Value.Split(',')
+ if ($parts.Count -gt 16) { return "invalid" }
+ $aliases = [Collections.Generic.List[string]]::new()
+ foreach ($part in $parts) {
+ $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)
+}
+
+function ConvertTo-AiMemoryRoutePath {
+ param([string] $Raw, [string] $HomePath, [bool] $Bounded = $true)
+ if (-not $Raw -or ($Bounded -and [Text.Encoding]::UTF8.GetByteCount($Raw) -gt 512)) { return $null }
+ $value = $Raw.Replace('\', '/')
+ if ($value.StartsWith("~/")) {
+ $relativeDepth = 0
+ foreach ($part in $value.Substring(2).Split('/')) {
+ if (-not $part -or $part -eq ".") { continue }
+ if ($part -eq "..") {
+ if ($relativeDepth -eq 0) { return $null }
+ $relativeDepth--
+ } else {
+ $relativeDepth++
+ }
+ }
+ $value = $HomePath.TrimEnd([char[]]@('/', '\')) + "/" + $value.Substring(2)
+ }
+ $root = $null
+ $rest = $null
+ $windows = $false
+ if ($value.StartsWith("//")) {
+ $parts = @($value.Substring(2).Split('/') | Where-Object { $_ })
+ if ($parts.Count -lt 2) { return $null }
+ $root = "unc:" + $parts[0].ToLowerInvariant() + "/" + $parts[1].ToLowerInvariant()
+ $rest = @($parts | Select-Object -Skip 2)
+ $windows = $true
+ } elseif ($value -cmatch '^[A-Za-z]:/') {
+ $root = "drive:" + $value.Substring(0, 1).ToLowerInvariant()
+ $rest = @($value.Substring(3).Split('/') | Where-Object { $_ })
+ $windows = $true
+ } elseif ($value.StartsWith("/")) {
+ $root = "posix"
+ $rest = @($value.Substring(1).Split('/') | Where-Object { $_ })
+ } else {
+ return $null
+ }
+ $stack = [Collections.Generic.List[string]]::new()
+ foreach ($part in $rest) {
+ if ($part -eq ".") { continue }
+ if ($part -eq "..") {
+ if ($stack.Count) { $stack.RemoveAt($stack.Count - 1) }
+ } else {
+ $stack.Add($(if ($windows) { $part.ToLowerInvariant() } else { $part }))
+ }
+ }
+ if (-not $stack.Count) { return $null }
+ $key = $root + "/" + ($stack -join "/")
+ return [pscustomobject]@{ Key=$key; Depth=$stack.Count }
+}
+
+function Get-AiMemoryHomeRoute {
+ param([string] $File, [string] $Cwd, [string] $Identity)
+ if (-not (Test-Path $File -PathType Leaf)) { return $null }
+ try {
+ $stream = [IO.File]::OpenRead($File)
+ try {
+ if ($stream.Length -gt 65536) { return "invalid" }
+ $bytes = New-Object byte[] ([int]$stream.Length)
+ $offset = 0
+ while ($offset -lt $bytes.Length) {
+ $read = $stream.Read($bytes, $offset, $bytes.Length - $offset)
+ if ($read -eq 0) { break }
+ $offset += $read
+ }
+ if ($offset -ne $bytes.Length) { return "invalid" }
+ $text = (New-Object Text.UTF8Encoding($false, $true)).GetString($bytes)
+ } finally {
+ $stream.Dispose()
+ }
+ if (-not [regex]::IsMatch($text, '(?m)^\s*(?:\[routes|routes\s*=|routes\.|route_)')) { return $null }
+ $entries = [Collections.Generic.List[object]]::new()
+ $rawSeen = @{}
+ $pathSeen = @{}
+ $current = $null
+ $finish = {
+ if ($null -eq $current) { return $true }
+ $workspace = $current.Fields["route_workspace"]
+ $project = $current.Fields["route_project"]
+ $style = $current.Fields["route_identity_style"]
+ if (-not $workspace -or -not $project -or [Text.Encoding]::UTF8.GetByteCount($workspace) -gt 512 -or [Text.Encoding]::UTF8.GetByteCount($project) -gt 512 -or $workspace -cnotmatch '^[a-z0-9][a-z0-9._-]*$' -or $project -cnotmatch '^[a-z0-9][a-z0-9._-]*$') { return $false }
+ if ($style -and @("path", "host_path") -cnotcontains $style) { return $false }
+ $aliases = if ($current.Fields.ContainsKey("route_aliases")) { ConvertTo-AiMemoryRouteAliases $current.Fields["route_aliases"] } else { $null }
+ if ($aliases -eq "invalid") { return $false }
+ if ($current.Kind -eq "identity") {
+ $hostName = $current.Selector.Split('/')[0]
+ if ($current.Selector -cne $current.Selector.ToLowerInvariant() -or $current.Selector -cnotmatch '^[a-z0-9.-]+(/[a-z0-9._-]+)+$' -or $hostName.StartsWith('.') -or $hostName.EndsWith('.')) { return $false }
+ }
+ if ($current.Kind -eq "path") {
+ $normalized = ConvertTo-AiMemoryRoutePath -Raw $current.Selector -HomePath (Get-AiMemoryUserHome)
+ if ($null -eq $normalized -or $pathSeen.ContainsKey($normalized.Key)) { return $false }
+ $pathSeen[$normalized.Key] = $true
+ $current | Add-Member -NotePropertyName NormalizedPath -NotePropertyValue $normalized.Key -Force
+ $current | Add-Member -NotePropertyName PathDepth -NotePropertyValue $normalized.Depth -Force
+ }
+ $current | Add-Member -NotePropertyName Workspace -NotePropertyValue $workspace -Force
+ $current | Add-Member -NotePropertyName Project -NotePropertyValue $project -Force
+ $current | Add-Member -NotePropertyName Style -NotePropertyValue $style -Force
+ $current | Add-Member -NotePropertyName Aliases -NotePropertyValue $aliases -Force
+ $entries.Add($current)
+ return $true
+ }
+ foreach ($line in ($text -split "`r?`n")) {
+ $trimmed = $line.Trim()
+ $header = [regex]::Match($trimmed, '^\[routes\.(identity|path)\."([^"\\]+)"\]$')
+ if ($header.Success) {
+ if (-not (& $finish)) { return "invalid" }
+ $selector = $header.Groups[2].Value
+ if ($entries.Count -ge 64 -or [Text.Encoding]::UTF8.GetByteCount($selector) -gt 512 -or $rawSeen.ContainsKey($selector)) { return "invalid" }
+ $rawSeen[$selector] = $true
+ $current = [pscustomobject]@{ Kind=$header.Groups[1].Value; Selector=$selector; Fields=@{} }
+ continue
+ }
+ if ($trimmed.StartsWith("[routes") -or $trimmed.StartsWith("routes.") -or $trimmed -match '^routes\s*=' -or ($trimmed.StartsWith("route_") -and $null -eq $current)) { return "invalid" }
+ if ($trimmed.StartsWith("[")) {
+ if (-not (& $finish)) { return "invalid" }
+ $current = $null
+ continue
+ }
+ if ($null -eq $current) {
+ if ($trimmed -match '^(workspace|project|project_strategy|drop_subagent_captures|identity|identity_style|server)\s*=' -and $trimmed -notmatch '^[A-Za-z0-9_]+\s*=\s*"[^"]*"$') { return "invalid" }
+ continue
+ }
+ if (-not $trimmed -or $trimmed.StartsWith("#")) { continue }
+ $field = [regex]::Match($trimmed, '^(route_workspace|route_project|route_identity_style|route_aliases)\s*=\s*(.*)$')
+ if (-not $field.Success -or $current.Fields.ContainsKey($field.Groups[1].Value)) { return "invalid" }
+ $name = $field.Groups[1].Value
+ $raw = $field.Groups[2].Value
+ if ($raw.Contains("\")) { return "invalid" }
+ if ($name -eq "route_aliases") {
+ if ([Text.Encoding]::UTF8.GetByteCount($raw) -gt 512 -or $raw -notmatch '^\[[^\]]*\]$') { return "invalid" }
+ $current.Fields[$name] = $raw
+ } else {
+ $value = [regex]::Match($raw, '^"([^"\\]+)"$')
+ if (-not $value.Success -or [Text.Encoding]::UTF8.GetByteCount($value.Groups[1].Value) -gt 512) { return "invalid" }
+ $current.Fields[$name] = $value.Groups[1].Value
+ }
+ }
+ if (-not (& $finish)) { return "invalid" }
+ $exact = @($entries | Where-Object { $_.Kind -eq "identity" -and $_.Selector -ceq $Identity })
+ if ($exact.Count -eq 1) { return $exact[0] }
+ $target = ConvertTo-AiMemoryRoutePath -Raw $Cwd -HomePath (Get-AiMemoryUserHome) -Bounded $false
+ if ($null -eq $target) { return "invalid" }
+ $routeMatches = @($entries | Where-Object {
+ if ($_.Kind -ne "path") { return $false }
+ $_ | Add-Member -NotePropertyName MatchLength -NotePropertyValue $_.PathDepth -Force
+ return $target.Key -eq $_.NormalizedPath -or $target.Key.StartsWith($_.NormalizedPath + "/", [StringComparison]::Ordinal)
+ } | Sort-Object MatchLength -Descending)
+ if ($routeMatches.Count) { return $routeMatches[0] }
+ } catch {
+ return "invalid"
+ }
+ return $null
+}
+
function Get-AiMemoryTomlFlag {
param([string] $File, [string] $Key)
if (-not (Test-Path $File -PathType Leaf)) { return $null }
@@ -387,6 +575,7 @@ function Get-AiMemoryMarkerQuery {
$proj = $null
$strategy = $null
$dropSubagent = $null
+ $defaultGlobal = $null
# Provenance of $proj, forwarded as `project_src` so the server can tell a
# deliberate marker rescope from a host-derived repo-root name. Only the
# latter may yield to session-sticky attribution (#394).
@@ -396,15 +585,38 @@ function Get-AiMemoryMarkerQuery {
$profileContribute = $null
$profileConsume = $null
$aliases = $null
+ $identityQuery = ""
+ $homeRouted = $false
$marker = Get-AiMemoryMarkerToml -Cwd $Cwd
+ $homeMarker = if (Get-AiMemoryUserHome) { Join-Path (Get-AiMemoryUserHome) ".ai-memory.toml" } else { $null }
+ if (-not $marker -or $marker -eq $homeMarker) {
+ $routeIdentity = Get-AiMemoryRemoteIdentity -Cwd $Cwd
+ $route = Get-AiMemoryHomeRoute -File $homeMarker -Cwd $Cwd -Identity $routeIdentity
+ if ($route -eq "invalid") { return $null }
+ if ($route) {
+ $ws = $route.Workspace
+ $proj = $route.Project
+ $projSrc = "marker"
+ $homeRouted = $true
+ $identityStyle = $route.Style
+ $aliases = $route.Aliases
+ if ($routeIdentity) {
+ $identityQuery = "&identity=$([uri]::EscapeDataString($routeIdentity))&identity_src=git_remote" + (Get-AiMemoryIdentityStyleQuery -Style $identityStyle)
+ }
+ $marker = $homeMarker
+ }
+ }
if ($marker) {
- $ws = Get-AiMemoryTomlKey -File $marker -Key "workspace"
- $proj = Get-AiMemoryTomlKey -File $marker -Key "project"
- $strategy = Get-AiMemoryTomlKey -File $marker -Key "project_strategy"
+ if (-not $homeRouted) {
+ $ws = Get-AiMemoryTomlKey -File $marker -Key "workspace"
+ $proj = Get-AiMemoryTomlKey -File $marker -Key "project"
+ $strategy = Get-AiMemoryTomlKey -File $marker -Key "project_strategy"
+ $explicitIdentity = Get-AiMemoryTomlKey -File $marker -Key "identity"
+ $identityStyle = Get-AiMemoryTomlKey -File $marker -Key "identity_style"
+ $aliases = Get-AiMemoryTomlAliases -File $marker
+ }
$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
+ $defaultGlobal = Get-AiMemoryTomlFlag -File $marker -Key "default_global"
# `[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
@@ -416,7 +628,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 -Aliases $aliases
+ if (-not $identityQuery) { $identityQuery = Get-AiMemoryIdentityQuery -Cwd $Cwd -Explicit $explicitIdentity -Project $proj -Style $identityStyle -Aliases $aliases }
# Install-time default baked into the hook command by
# `install-hooks --project-strategy` fills the strategy only when no marker
# pinned one. A marker's explicit project / project_strategy still win.
@@ -435,12 +647,13 @@ function Get-AiMemoryMarkerQuery {
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))"
+ if (-not $proj -or -not $identityQuery.Contains("identity_src=git_remote")) { $aliases = if ($homeRouted) { $null } else { "invalid" } }
+ if ($aliases) { $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))" }
+ if ($defaultGlobal) { $qs += "&default_global=$([uri]::EscapeDataString($defaultGlobal))" }
if ($profileContribute) { $qs += "&profile_contribute=$([uri]::EscapeDataString($profileContribute))" }
if ($profileConsume) { $qs += "&profile_consume=$([uri]::EscapeDataString($profileConsume))" }
return $qs
@@ -597,6 +810,10 @@ function Invoke-AiMemoryHook {
return
}
$QS = Get-AiMemoryMarkerQuery -Cwd $Cwd
+ if ($Cwd -and $null -eq $QS) {
+ if ($AntigravityPreInvocationOutput -or $GrokPostTool) { [Console]::Out.Write("{}") }
+ return
+ }
if ($env:AI_MEMORY_RUN_ID) {
$QS += "&managed_run=$([Uri]::EscapeDataString($env:AI_MEMORY_RUN_ID))"
}
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index 81e38ae8..f6332c79 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -262,6 +262,82 @@ 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)"
+mkdir -p "$TMP/home-routes/src/api/lib" "$TMP/home-routes/src/api-sibling"
+HOME="$TMP/home-routes"
+export HOME
+cat >"$HOME/.ai-memory.toml" <<EOF
+workspace = "fallback"
+project = "fallback"
+[routes.path."~/src"]
+route_workspace = "oss"
+route_project = "broad"
+[routes.path."~/src/api"]
+route_workspace = "oss"
+route_project = "acme-api"
+route_aliases = ["old-api"]
+EOF
+HOME_ROUTE=$(ai_memory_marker_qs "$HOME/src/api/lib")
+assert_eq "home route uses longest component path and marker provenance" "yes" \
+ "$(case "$HOME_ROUTE" in *'&workspace=oss&project=acme-api&project_src=marker'*) printf yes ;; *) printf no ;; esac)"
+assert_eq "non-git home path route omits aliases" "no" \
+ "$(case "$HOME_ROUTE" in *'&aliases='*) printf yes ;; *) printf no ;; esac)"
+PS_ROUTE_STATIC=$(grep -Fq 'if ($aliases) { $qs += "&aliases=' hooks/lib/ai-memory-hook.ps1 \
+ && grep -Fq 'if (-not $stack.Count) { return $null }' hooks/lib/ai-memory-hook.ps1 \
+ && printf ok || printf fail)
+assert_eq "powershell route bundle omits cleared aliases and rejects roots (static)" "ok" "$PS_ROUTE_STATIC"
+mkdir -p "$HOME/src/api/.git"
+git -C "$HOME/src/api" init -q
+git -C "$HOME/src/api" remote add origin [email protected]:acme/api.git
+cat >>"$HOME/.ai-memory.toml" <<EOF
+[routes.identity."github.com/acme/api"]
+route_workspace = "identity"
+route_project = "identity-api"
+route_identity_style = "path"
+route_aliases = ["main"]
+[routes.identity."gitlab.com/acme/api"]
+route_workspace = "wrong"
+route_project = "wrong"
+EOF
+HOME_IDENTITY_ROUTE=$(ai_memory_marker_qs "$HOME/src/api/lib")
+assert_eq "home exact hostful identity wins path and forwards aliases safely" "yes" \
+ "$(case "$HOME_IDENTITY_ROUTE" in *'&workspace=identity&project=identity-api&project_src=marker'*'&identity=github.com%2Facme%2Fapi&identity_src=git_remote&identity_style=path'*'&aliases=%5B%22main%22%5D'*) printf yes ;; *) printf no ;; esac)"
+HOME_SIBLING=$(ai_memory_marker_qs "$HOME/src/api-sibling")
+assert_eq "home route does not string-prefix match a sibling" "yes" \
+ "$(case "$HOME_SIBLING" in *'&project=broad&project_src=marker'*) printf yes ;; *) printf no ;; esac)"
+printf 'workspace = "local"\nproject = "local-project"\n' >"$HOME/src/api/.ai-memory.toml"
+LOCAL_ROUTE=$(ai_memory_marker_qs "$HOME/src/api/lib")
+assert_eq "local settings marker wins over home route" "yes" \
+ "$(case "$LOCAL_ROUTE" in *'&workspace=local&project=local-project&project_src=marker'*) printf yes ;; *) printf no ;; esac)"
+rm -f "$HOME/src/api/.ai-memory.toml"
+cat >"$HOME/.ai-memory.toml" <<EOF
+workspace = "wrong"
+project = "wrong"
+project_strategy = "repo-root"
+drop_subagent_captures = "true"
+[recall]
+default_global = true
+[briefing]
+inject_on_session_start = true
+max_chars = 3210
+[profile]
+contribute = true
+consume = false
+[routes.path."~/src/api"]
+route_workspace = "right"
+route_project = "api"
+EOF
+HOME_FLAG_ROUTE=$(ai_memory_marker_qs "$HOME/src/api")
+assert_eq "home route replaces scope and keeps root privacy settings" "yes" \
+ "$(case "$HOME_FLAG_ROUTE" in *'&workspace=right&project=api&project_src=marker'*'&drop_subagent=true&default_global=true&profile_contribute=1&profile_consume=0'*) printf yes ;; *) printf no ;; esac)"
+printf 'workspace = "wrong"\nproject = "wrong"\n[routes.path."relative"]\nroute_workspace = "oss"\nroute_project = "api"\n' >"$HOME/.ai-memory.toml"
+assert_eq "malformed home routes fail closed instead of root fallback" "&ai_memory_invalid_home_routes=1" \
+ "$(ai_memory_marker_qs "$HOME/src/api")"
+printf 'workspace = wrong\n' >"$HOME/.ai-memory.toml"
+assert_eq "malformed root-only home marker keeps legacy parser behavior" "yes" \
+ "$(case "$(ai_memory_marker_qs "$HOME/src/api")" in *'&ai_memory_invalid_home_routes=1'*) printf no ;; *) printf yes ;; esac)"
+HOME="$TMP"
+export HOME
+
# --- 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