Skip to content

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

Rust

feat(doctor): report repository coordinate compatibility (#1033)

AkitaOnRails030d903557d7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b3c31c5d..e15134c1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added read-only project-coordinate diagnostics to `ai-memory doctor` and the
+ root-gated `GET /admin/project-coordinate` endpoint. The report classifies
+ exact, canonical-compatibility, legacy-compatibility, missing, and ambiguous
+ names; shows safe local marker/repository evidence and rename eligibility;
+ and reports collisions without creating, claiming, renaming, or exposing
+ remote credentials or marker paths. Ambiguous results keep local session
+ evidence and mark server capture counts unavailable; any returned preferred
+ project is contextual only, never a unique resolution. (#1033)
- Added the cross-project profile (`docs/cross-project-profile.md`, design in
`docs/design-cross-project-profile.md`): a small set of `profile/` pages
recording how the user usually works, delivered to every project and every
diff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rs
index cd5e2fe3..7b53ac4a 100644
--- a/crates/ai-memory-cli/src/commands/doctor.rs
+++ b/crates/ai-memory-cli/src/commands/doctor.rs
@@ -76,10 +76,10 @@ pub(crate) struct CoverageRow {
agent: String,
local_total: usize,
local_recent: usize,
- captured: u64,
+ captured: Option<u64>,
/// True when the harness ran here recently but captured nothing — the
/// high-confidence "hook is missing" signal.
- uncaptured: bool,
+ uncaptured: Option<bool>,
mixed_capture_sessions: Option<u64>,
}
@@ -112,6 +112,18 @@ struct AgentCount {
mixed_capture_sessions: Option<u64>,
}
+#[derive(Debug, Clone, Serialize)]
+struct ProjectCoordinateReport {
+ local: super::hook_capture::RepositoryCoordinateEvidence,
+ server: Option<ai_memory_store::ProjectCoordinateDiagnostic>,
+ server_problem: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+struct CaptureCoverageProblem {
+ reason: String,
+}
+
#[derive(Debug, Deserialize, Serialize)]
struct OperatorIdentity {
version: String,
@@ -139,6 +151,7 @@ struct DoctorReport {
server: String,
since_days: u32,
rows: Vec<CoverageRow>,
+ capture_coverage_problem: Option<CaptureCoverageProblem>,
/// The agent kinds (kebab form) flagged as uncaptured, for quick scripting.
uncaptured: Vec<String>,
/// Set when the nearest `.ai-memory.toml`'s `[capture]` section is
@@ -149,6 +162,7 @@ struct DoctorReport {
marker_capture_problem: Option<MarkerCaptureProblem>,
capture_owner_active: bool,
identity: Option<OperatorIdentity>,
+ project_coordinate: Option<ProjectCoordinateReport>,
/// Native "memory" stores found for harnesses that keep one, and whether
/// the nearest marker would exclude a read of them (harness-issue
/// #1003). Only Claude Code's location is known today; harnesses with no
@@ -158,8 +172,7 @@ struct DoctorReport {
#[derive(Debug, Clone, Serialize)]
struct MarkerCaptureProblem {
- marker_path: String,
- reason: String,
+ classification: &'static str,
}
#[derive(Debug, Clone, Serialize)]
@@ -213,18 +226,19 @@ pub(crate) fn build_rows(
agent,
local_total,
local_recent,
- captured,
- uncaptured,
+ captured: Some(captured),
+ uncaptured: Some(uncaptured),
mixed_capture_sessions: None,
}
})
- .filter(|row| row.local_total > 0 || row.captured > 0)
+ .filter(|row| row.local_total > 0 || row.captured.is_some_and(|count| count > 0))
.collect();
// Surface the actionable warnings first, then a stable alphabetical order.
rows.sort_by(|a, b| {
b.uncaptured
- .cmp(&a.uncaptured)
+ .unwrap_or(false)
+ .cmp(&a.uncaptured.unwrap_or(false))
.then_with(|| a.agent.cmp(&b.agent))
});
rows
@@ -376,6 +390,49 @@ fn is_recent(updated_at: SystemTime, cutoff: Option<SystemTime>) -> bool {
}
}
+async fn project_coordinate_report(
+ ep: &ServerEndpoint,
+ identity_cwd: &str,
+ marker: &crate::marker::MarkerInspection,
+ workspace: &str,
+ project: &str,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+) -> ProjectCoordinateReport {
+ let inspection = super::hook_capture::inspect_repository_coordinate(
+ identity_cwd,
+ marker,
+ explicit_workspace,
+ explicit_project,
+ );
+ let mut query = vec![("workspace", workspace), ("project", project)];
+ if let Some(repository) = inspection.repository.as_ref() {
+ query.push(("identity", repository.identity.as_str()));
+ query.push(("identity_source", repository.source.as_str()));
+ if let Some(style) = inspection.evidence.identity_style.as_deref() {
+ query.push(("identity_style", style));
+ }
+ }
+ match get_json::<ai_memory_store::ProjectCoordinateDiagnostic>(
+ ep,
+ "/admin/project-coordinate",
+ &query,
+ )
+ .await
+ {
+ Ok(server) => ProjectCoordinateReport {
+ local: inspection.evidence,
+ server: Some(server),
+ server_problem: None,
+ },
+ Err(error) => ProjectCoordinateReport {
+ local: inspection.evidence,
+ server: None,
+ server_problem: Some(ai_memory_core::Sanitizer::builtin().scrub(&error.to_string())),
+ },
+ }
+}
+
/// Run the capture-coverage doctor.
///
/// # Errors
@@ -383,14 +440,39 @@ fn is_recent(updated_at: SystemTime, cutoff: Option<SystemTime>) -> bool {
/// directory is unreadable, or the server cannot be reached / its response
/// cannot be parsed.
pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
- let (workspace, project) =
- super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
-
- let cwd = std::env::current_dir().context("resolving the current working directory")?;
+ 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 scope_marker = marker
+ .scope
+ .clone()
+ .map(|scope| (scope, identity_cwd.clone(), lookup_cwd.clone()));
+ let (workspace, project) = super::resolve_scope_with_marker(
+ config,
+ args.workspace.as_deref(),
+ args.project.as_deref(),
+ scope_marker,
+ false,
+ )?;
+
+ let cwd = PathBuf::from(&identity_cwd);
let home =
super::run::native_home(config).context("locating the local harness session stores")?;
let ep = ServerEndpoint::from_config_resolving_auth(config).await;
+ let project_coordinate = Some(
+ project_coordinate_report(
+ &ep,
+ &identity_cwd,
+ &marker,
+ &workspace,
+ &project,
+ args.workspace.as_deref(),
+ args.project.as_deref(),
+ )
+ .await,
+ );
+ let mut capture_coverage_problem = None;
let captured = match get_json::<ByAgentResponse>(
&ep,
"/admin/sessions/by-agent",
@@ -402,10 +484,13 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
.await
{
Ok(response) => response.by_agent,
- // A project that has never been captured into does not exist
- // server-side yet (404) — that is "nothing captured", not an error, so
- // every local harness correctly reads as uncaptured.
Err(error) if super::is_scope_not_found(&error) => Vec::new(),
+ Err(error) if super::is_scope_ambiguous(&error) => {
+ capture_coverage_problem = Some(CaptureCoverageProblem {
+ reason: "server scope is ambiguous; captured counts are unavailable".to_owned(),
+ });
+ Vec::new()
+ }
Err(error) => {
return Err(error).with_context(|| {
format!("asking the server for captured session counts for {workspace}/{project}")
@@ -414,14 +499,18 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
};
let identity = read_identity(&ep).await;
-
let local = scan_local(&home, &cwd, args.since_days).await;
+
let counts = captured
.iter()
.map(|count| (count.agent.clone(), count.sessions))
.collect();
let mut rows = build_rows(&local, &counts);
for row in &mut rows {
+ if capture_coverage_problem.is_some() {
+ row.captured = None;
+ row.uncaptured = None;
+ }
row.mixed_capture_sessions = captured
.iter()
.find(|count| count.agent == row.agent)
@@ -429,16 +518,13 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
}
let uncaptured: Vec<String> = rows
.iter()
- .filter(|r| r.uncaptured)
+ .filter(|r| r.uncaptured == Some(true))
.map(|r| r.agent.clone())
.collect();
let marker_capture_problem = cwd.to_str().and_then(|cwd| {
- super::hook_capture::capture_config_problem(cwd).map(|(marker_path, reason)| {
- MarkerCaptureProblem {
- marker_path: marker_path.display().to_string(),
- reason,
- }
+ super::hook_capture::capture_config_problem(cwd).map(|_| MarkerCaptureProblem {
+ classification: "settings_marker_invalid",
})
});
@@ -450,10 +536,12 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
server: ep.url.clone(),
since_days: args.since_days,
rows,
+ capture_coverage_problem,
uncaptured,
marker_capture_problem,
capture_owner_active: config.runtime_env.capture_owner_active(),
identity,
+ project_coordinate,
native_memory,
};
@@ -465,6 +553,60 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {
Ok(())
}
+fn render_project_coordinate(coordinate: &ProjectCoordinateReport) -> String {
+ use std::fmt::Write as _;
+ let mut output = String::new();
+ match &coordinate.server {
+ Some(server) => {
+ let current = server.current_name.as_deref().unwrap_or("none");
+ let _ = writeln!(
+ output,
+ " project coordinate: {} (requested {}, current {})",
+ server.status, server.requested_name, current
+ );
+ if server.rename_eligible {
+ output.push_str(" an authorized write can promote this project name in place\n");
+ }
+ if let Some(reason) = &server.collision_reason {
+ let _ = writeln!(output, " collision: {reason}");
+ }
+ }
+ None => {
+ let _ = writeln!(
+ output,
+ " project coordinate: unavailable ({})",
+ coordinate
+ .server_problem
+ .as_deref()
+ .unwrap_or("unknown error")
+ );
+ }
+ }
+ let local = &coordinate.local;
+ let _ = writeln!(
+ output,
+ " local: scope {}, marker {}",
+ local.scope_source, local.marker_status
+ );
+ if let Some(source) = &local.identity_source {
+ let _ = writeln!(
+ output,
+ " repository: source {source}, style {}",
+ local.identity_style.as_deref().unwrap_or("host_path")
+ );
+ }
+ if let Some(canonical) = &local.canonical_candidate {
+ let _ = writeln!(output, " canonical candidate: {canonical}");
+ }
+ if let Some(legacy) = &local.legacy_candidate {
+ let _ = writeln!(output, " legacy candidate: {legacy}");
+ }
+ for message in &local.messages {
+ let _ = writeln!(output, " marker diagnostic: {message}");
+ }
+ output
+}
+
fn render_human(report: &DoctorReport) {
println!(
"Capture coverage for {}/{} (server {})",
@@ -486,6 +628,12 @@ fn render_human(report: &DoctorReport) {
Confirm the external producer is delivering events."
);
}
+ if let Some(coordinate) = &report.project_coordinate {
+ print!("{}", render_project_coordinate(coordinate));
+ }
+ if let Some(problem) = &report.capture_coverage_problem {
+ println!(" capture coverage: unavailable ({})", problem.reason);
+ }
if report.since_days == 0 {
println!(" recent window: all on-disk sessions\n");
} else {
@@ -494,11 +642,11 @@ fn render_human(report: &DoctorReport) {
if let Some(problem) = &report.marker_capture_problem {
println!(
- "⚠ {} has an invalid `[capture]` section: {}\n \
+ "⚠ {}: the settings marker has an invalid `[capture]` section.\n \
It fails closed — file and shell tool content is reduced to metadata there, \
nothing leaks — but its `ignore_paths` exclusions are NOT applying while it stays \
invalid. Fix the TOML and re-run `ai-memory doctor` to confirm.\n",
- problem.marker_path, problem.reason
+ problem.classification
);
}
@@ -512,17 +660,32 @@ fn render_human(report: &DoctorReport) {
}
if report.rows.is_empty() {
- println!(" No local harness sessions found for this project and nothing captured yet.");
+ if report.capture_coverage_problem.is_some() {
+ println!(
+ " No local harness sessions found for this project; server capture counts are unavailable."
+ );
+ } else {
+ println!(
+ " No local harness sessions found for this project and nothing captured yet."
+ );
+ }
return;
}
for row in &report.rows {
- let mark = if row.uncaptured { "⚠" } else { "✓" };
+ let mark = match row.uncaptured {
+ Some(true) => "⚠",
+ Some(false) => "✓",
+ None => "?",
+ };
+ let captured = row
+ .captured
+ .map_or_else(|| "unavailable".to_owned(), |count| count.to_string());
println!(
- " {mark} {:<14} {:>4} local ({} recent) → {:>4} captured",
- row.agent, row.local_total, row.local_recent, row.captured
+ " {mark} {:<14} {:>4} local ({} recent) → {:>11} captured",
+ row.agent, row.local_total, row.local_recent, captured
);
- if row.uncaptured {
+ if row.uncaptured == Some(true) {
if report.capture_owner_active {
println!(
" No captured session: check the external producer and repository policy."
@@ -552,7 +715,9 @@ fn render_human(report: &DoctorReport) {
}
}
- if report.uncaptured.is_empty() {
+ if report.capture_coverage_problem.is_some() {
+ println!("\nCapture verdict unavailable: server capture counts could not be resolved.");
+ } else if report.uncaptured.is_empty() {
println!("\n✓ Every harness that ran in this project recently is captured on the server.");
} else {
let remedy = if report.capture_owner_active {
@@ -572,6 +737,173 @@ fn render_human(report: &DoctorReport) {
mod tests {
use super::*;
+ fn server_coordinate(
+ status: ai_memory_store::ProjectCoordinateStatus,
+ collision_reason: Option<ai_memory_store::ProjectCoordinateCollisionReason>,
+ ) -> ai_memory_store::ProjectCoordinateDiagnostic {
+ ai_memory_store::ProjectCoordinateDiagnostic {
+ workspace: "default".into(),
+ requested_name: "acme-api".into(),
+ status,
+ project_id: Some(ai_memory_core::ProjectId::new()),
+ current_name: Some("api".into()),
+ canonical_candidate: Some("acme-api".into()),
+ legacy_candidate: Some("api".into()),
+ identity_source: Some("git_remote".into()),
+ identity_style: Some("path".into()),
+ rename_eligible: collision_reason.is_none(),
+ collision_reason,
+ candidate_count: 1,
+ }
+ }
+
+ #[test]
+ fn project_coordinate_renders_promotion_and_cross_forge_fallback_concisely() {
+ let local = super::super::hook_capture::RepositoryCoordinateEvidence {
+ marker_status: "valid",
+ scope_source: "marker_or_fallback",
+ identity_source: Some("git_remote".into()),
+ identity_style: Some("path".into()),
+ canonical_candidate: Some("acme-api".into()),
+ legacy_candidate: Some("api".into()),
+ messages: Vec::new(),
+ };
+ let promotion = render_project_coordinate(&ProjectCoordinateReport {
+ local: local.clone(),
+ server: Some(server_coordinate(
+ ai_memory_store::ProjectCoordinateStatus::CanonicalCompat,
+ None,
+ )),
+ server_problem: None,
+ });
+ assert!(promotion.contains("canonical_compat"), "{promotion}");
+ assert!(
+ promotion.contains("promote this project name in place"),
+ "{promotion}"
+ );
+
+ let collision = render_project_coordinate(&ProjectCoordinateReport {
+ local,
+ server: Some(server_coordinate(
+ ai_memory_store::ProjectCoordinateStatus::Ambiguous,
+ Some(ai_memory_store::ProjectCoordinateCollisionReason::CrossForgeCollision),
+ )),
+ server_problem: None,
+ });
+ assert!(collision.contains("cross_forge_collision"), "{collision}");
+ assert!(
+ !collision.contains("promote this project name"),
+ "{collision}"
+ );
+ }
+
+ #[test]
+ fn local_coordinate_reports_marker_precedence_invalid_toml_and_no_credentials() {
+ let tmp = tempfile::tempdir().unwrap();
+ let repo = tmp.path().join("repo");
+ let nested = repo.join("nested");
+ std::fs::create_dir_all(&nested).unwrap();
+ std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(&repo)
+ .status()
+ .unwrap();
+ std::process::Command::new("git")
+ .args(["-C"])
+ .arg(&repo)
+ .args([
+ "remote",
+ "add",
+ "origin",
+ "https://user:[email protected]/acme/api.git",
+ ])
+ .status()
+ .unwrap();
+ std::fs::write(
+ repo.join(".ai-memory.toml"),
+ "workspace = \"marker-ws\"\nproject = \"marker-project\"\nidentity_style = \"path\"\n",
+ )
+ .unwrap();
+ let marker = crate::marker::inspect_scope(
+ &nested.to_string_lossy(),
+ &crate::config::RuntimeEnv::default(),
+ );
+ let evidence = super::super::hook_capture::inspect_repository_coordinate(
+ &nested.to_string_lossy(),
+ &marker,
+ Some("flag-ws"),
+ Some("flag-project"),
+ )
+ .evidence;
+ assert_eq!(evidence.marker_status, "valid");
+ assert_eq!(evidence.scope_source, "cli");
+ assert_eq!(evidence.identity_source.as_deref(), Some("git_remote"));
+ assert_eq!(evidence.identity_style.as_deref(), Some("path"));
+ assert!(evidence.messages.is_empty());
+ let json = serde_json::to_string(&evidence).unwrap();
+ assert!(!json.contains("top-secret"), "{json}");
+ assert!(!json.contains("user@"), "{json}");
+
+ std::fs::write(repo.join(".ai-memory.toml"), "identity_style = \"path\"\n").unwrap();
+ let marker = crate::marker::inspect_scope(
+ &nested.to_string_lossy(),
+ &crate::config::RuntimeEnv::default(),
+ );
+ let remote = super::super::hook_capture::inspect_repository_coordinate(
+ &nested.to_string_lossy(),
+ &marker,
+ Some("default"),
+ Some("api"),
+ )
+ .evidence;
+ assert_eq!(remote.identity_source.as_deref(), Some("git_remote"));
+ assert_eq!(remote.identity_style.as_deref(), Some("path"));
+ assert_eq!(remote.canonical_candidate.as_deref(), Some("acme-api"));
+ let json = serde_json::to_string(&remote).unwrap();
+ assert!(!json.contains("top-secret"), "{json}");
+ assert!(!json.contains("user@"), "{json}");
+
+ std::fs::write(
+ repo.join(".ai-memory.toml"),
+ "workspace = [\nsecret = \"top-secret\"\n",
+ )
+ .unwrap();
+ let marker = crate::marker::inspect_scope(
+ &nested.to_string_lossy(),
+ &crate::config::RuntimeEnv::default(),
+ );
+ let invalid = super::super::hook_capture::inspect_repository_coordinate(
+ &nested.to_string_lossy(),
+ &marker,
+ Some("default"),
+ Some("repo"),
+ )
+ .evidence;
+ assert_eq!(invalid.marker_status, "invalid");
+ assert_eq!(
+ invalid.messages,
+ vec!["invalid marker TOML; marker routing was ignored"]
+ );
+ assert!(
+ !serde_json::to_string(&invalid)
+ .unwrap()
+ .contains("top-secret")
+ );
+ }
+
+ #[test]
+ fn coordinate_server_errors_are_scrubbed_before_output() {
+ let error = crate::http_client::server_response_error_for_test(
+ reqwest::Method::GET,
+ "/admin/project-coordinate",
+ reqwest::StatusCode::INTERNAL_SERVER_ERROR,
+ "Bearer abcdefghijklmnopqrstuvwxyz".into(),
+ );
+ let problem = ai_memory_core::Sanitizer::builtin().scrub(&error.to_string());
+ assert!(!problem.contains("abcdefghijklmnopqrstuvwxyz"), "{problem}");
+ assert!(problem.contains("[REDACTED:bearer_token]"), "{problem}");
+ }
+
#[tokio::test]
async fn identity_diagnostics_degrade_on_server_and_decode_errors() {
for (status, body, available) in [
@@ -645,9 +977,13 @@ mod tests {
let local = vec![scan(AgentKind::KimiCode, 2, 2)];
let rows = build_rows(&local, &captured(&[]));
let kimi = row(&rows, "kimi-code");
- assert!(kimi.uncaptured, "recent local + zero captured must warn");
+ assert_eq!(
+ kimi.uncaptured,
+ Some(true),
+ "recent local + zero captured must warn"
+ );
assert_eq!(kimi.local_recent, 2);
- assert_eq!(kimi.captured, 0);
+ assert_eq!(kimi.captured, Some(0));
}
#[test]
@@ -656,7 +992,7 @@ mod tests {
// in count (resume reuse maps many local files to one server session).
let local = vec![scan(AgentKind::ClaudeCode, 12, 4)];
let rows = build_rows(&local, &captured(&[("claude-code", 3)]));
- assert!(!row(&rows, "claude-code").uncaptured);
+ assert_eq!(row(&rows, "claude-code").uncaptured, Some(false));
}
#[test]
@@ -664,7 +1000,7 @@ mod tests {
// Local sessions exist but none are recent → not actionable.
let local = vec![scan(AgentKind::Codex, 5, 0)];
let rows = build_rows(&local, &captured(&[]));
- assert!(!row(&rows, "codex").uncaptured);
+ assert_eq!(row(&rows, "codex").uncaptured, Some(false));
}
#[test]
@@ -679,7 +1015,7 @@ mod tests {
let kiro = row(&rows, "kiro-cli");
assert_eq!(kiro.local_total, 5);
assert_eq!(kiro.local_recent, 3);
- assert!(kiro.uncaptured);
+ assert_eq!(kiro.uncaptured, Some(true));
}
#[test]
@@ -689,8 +1025,8 @@ mod tests {
let rows = build_rows(&[], &captured(&[("gemini-cli", 4)]));
let gemini = row(&rows, "gemini-cli");
assert_eq!(gemini.local_total, 0);
- assert_eq!(gemini.captured, 4);
- assert!(!gemini.uncaptured);
+ assert_eq!(gemini.captured, Some(4));
+ assert_eq!(gemini.uncaptured, Some(false));
}
#[test]
@@ -710,7 +1046,7 @@ mod tests {
rows[0].agent, "kimi-code",
"the warning must lead: {rows:?}"
);
- assert!(rows[0].uncaptured);
+ assert_eq!(rows[0].uncaptured, Some(true));
}
#[test]
@@ -844,6 +1180,29 @@ mod tests {
assert_eq!(claude.status, "excluded");
}
+ #[test]
+ fn marker_capture_problem_exposes_only_a_safe_classification() {
+ let cwd = tempfile::tempdir().unwrap();
+ let private_path = cwd.path().join("secret-project-name");
+ std::fs::create_dir_all(&private_path).unwrap();
+ std::fs::write(
+ private_path.join(".ai-memory.toml"),
+ "[capture] private-toml-sentinel\nignore_paths = [\"**\"]\n",
+ )
+ .unwrap();
+
+ let problem =
+ super::super::hook_capture::capture_config_problem(private_path.to_str().unwrap())
+ .map(|_| MarkerCaptureProblem {
+ classification: "settings_marker_invalid",
+ })
+ .expect("invalid marker problem");
+ let json = serde_json::to_string(&problem).unwrap();
+ assert_eq!(json, r#"{"classification":"settings_marker_invalid"}"#);
+ assert!(!json.contains(private_path.to_str().unwrap()));
+ assert!(!json.contains("private-toml-sentinel"));
+ }
+
#[test]
fn native_memory_reports_is_marker_invalid_for_a_broken_capture_table() {
let home = tempfile::tempdir().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 275783de..ab9af61c 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -332,6 +332,22 @@ pub struct HookScope {
server_may_remap: bool,
}
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+pub(crate) struct RepositoryCoordinateEvidence {
+ pub(crate) marker_status: &'static str,
+ pub(crate) scope_source: &'static str,
+ pub(crate) identity_source: Option<String>,
+ pub(crate) identity_style: Option<String>,
+ pub(crate) canonical_candidate: Option<String>,
+ pub(crate) legacy_candidate: Option<String>,
+ pub(crate) messages: Vec<String>,
+}
+
+pub(crate) struct RepositoryCoordinateInspection {
+ pub(crate) evidence: RepositoryCoordinateEvidence,
+ pub(crate) repository: Option<ai_memory_core::repository_identity::RepositoryIdentity>,
+}
+
const MAX_SCOPE_HINT_BYTES: usize = 512;
fn serialize_scope_hint<S: serde::Serializer>(
@@ -390,6 +406,68 @@ pub fn hook_scope(cwd: &str, default_strategy: Option<&str>) -> HookScope {
hook_scope_from_marker(cwd, default_strategy, marker.as_deref())
}
+pub(crate) fn inspect_repository_coordinate(
+ identity_cwd: &str,
+ marker: &crate::marker::MarkerInspection,
+ explicit_workspace: Option<&str>,
+ explicit_project: Option<&str>,
+) -> RepositoryCoordinateInspection {
+ let declared_project = if explicit_project.is_some_and(|value| !value.is_empty()) {
+ None
+ } else {
+ marker.fields.project.as_deref()
+ };
+ let repository = 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(
+ || {
+ forwarded_identity_style(marker.fields.identity_style.as_deref())
+ .unwrap_or("host_path")
+ .to_owned()
+ },
+ )
+ });
+ RepositoryCoordinateInspection {
+ evidence: RepositoryCoordinateEvidence {
+ marker_status: marker.status,
+ scope_source: match (
+ explicit_workspace.is_some_and(|value| !value.is_empty()),
+ explicit_project.is_some_and(|value| !value.is_empty()),
+ marker.scope.is_some(),
+ ) {
+ (true, true, _) => "cli",
+ (true, false, _) | (false, true, _) => "cli_and_marker_or_fallback",
+ (false, false, true) => "marker_or_fallback",
+ _ => "fallback",
+ },
+ identity_source: repository
+ .as_ref()
+ .map(|identity| identity.source.as_str().to_owned()),
+ identity_style,
+ canonical_candidate: repository
+ .as_ref()
+ .and_then(ai_memory_core::repository_identity::path_style_name),
+ legacy_candidate: repository
+ .as_ref()
+ .and_then(ai_memory_core::repository_identity::legacy_basename_name),
+ messages: match marker.status {
+ "invalid" => vec!["invalid marker TOML; marker routing was ignored".to_owned()],
+ "unreadable" => vec!["unreadable marker; marker routing was ignored".to_owned()],
+ "conflicting" => {
+ vec!["conflicting marker settings; marker routing was ignored".to_owned()]
+ }
+ "ignored" => vec!["marker ignored by configuration".to_owned()],
+ _ => Vec::new(),
+ },
+ },
+ repository,
+ }
+}
+
fn hook_scope_from_marker(
cwd: &str,
default_strategy: Option<&str>,
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index a607a6d0..ba0228bd 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -17,6 +17,15 @@ pub(crate) fn is_scope_not_found(error: &anyhow::Error) -> bool {
.is_some_and(|response| response.status() == reqwest::StatusCode::NOT_FOUND)
}
+pub(crate) fn is_scope_ambiguous(error: &anyhow::Error) -> bool {
+ error
+ .downcast_ref::<crate::http_client::ServerResponseError>()
+ .is_some_and(|response| {
+ response.status() == reqwest::StatusCode::BAD_REQUEST
+ && response.body().contains("ambiguous")
+ })
+}
+
pub mod api_key;
pub mod apply_shared;
pub mod audit_contamination;
@@ -150,12 +159,27 @@ pub(crate) fn resolve_scope(
) -> Result<(String, String)> {
let explicit_ws = explicit_ws.filter(|s| !s.is_empty());
let explicit_proj = explicit_proj.filter(|s| !s.is_empty());
- // Both halves pinned on the command line: the marker cannot change the
- // answer, so skip the walk and the file reads entirely.
if let (Some(workspace), Some(project)) = (explicit_ws, explicit_proj) {
return Ok((workspace.to_string(), project.to_string()));
}
- let marker = marker_scope(config);
+ resolve_scope_with_marker(
+ config,
+ explicit_ws,
+ explicit_proj,
+ marker_scope(config),
+ true,
+ )
+}
+
+pub(crate) fn resolve_scope_with_marker(
+ config: &Config,
+ explicit_ws: Option<&str>,
+ explicit_proj: Option<&str>,
+ marker: Option<(crate::marker::MarkerScope, String, String)>,
+ announce: bool,
+) -> Result<(String, String)> {
+ let explicit_ws = explicit_ws.filter(|s| !s.is_empty());
+ let explicit_proj = explicit_proj.filter(|s| !s.is_empty());
let mut decided: Vec<&str> = Vec::with_capacity(2);
let workspace = match explicit_ws {
@@ -203,7 +227,7 @@ pub(crate) fn resolve_scope(
}
};
- if let Some((scope, _, _)) = marker.as_ref().filter(|_| !decided.is_empty()) {
+ if announce && let Some((scope, _, _)) = marker.as_ref().filter(|_| !decided.is_empty()) {
// Name only the halves the marker actually decided: an explicit flag
// that was honoured must not read as if the file overrode it.
eprintln!(
@@ -285,6 +309,12 @@ pub(crate) fn resolve_workspace(config: &Config, explicit_ws: Option<&str>) -> S
/// 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))
+}
+
+pub(crate) fn scope_directories(config: &Config) -> Option<(String, String)> {
let identity_cwd = scope_cwd(config)?;
// The Docker wrapper preserves the host cwd for identity but binds the
// checkout at /work. Check the host path when its bounded root is mounted;
@@ -299,8 +329,7 @@ fn marker_scope(config: &Config) -> Option<(crate::marker::MarkerScope, String,
.ok()
.map(|cwd| cwd.to_string_lossy().into_owned())?
};
- let scope = crate::marker::read_scope(&lookup_cwd, &config.runtime_env)?;
- Some((scope, identity_cwd, lookup_cwd))
+ Some((identity_cwd, lookup_cwd))
}
/// The directory marker discovery walks up from.
diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rs
index 2decbb56..30f15cec 100644
--- a/crates/ai-memory-cli/src/marker.rs
+++ b/crates/ai-memory-cli/src/marker.rs
@@ -40,6 +40,115 @@ pub(crate) struct MarkerScope {
pub(crate) project_strategy: Option<String>,
}
+#[derive(Debug, Clone, Default)]
+pub(crate) struct RoutingFields {
+ pub(crate) workspace: Option<String>,
+ pub(crate) project: Option<String>,
+ pub(crate) project_strategy: Option<String>,
+ pub(crate) identity: Option<String>,
+ pub(crate) identity_style: Option<String>,
+}
+
+impl RoutingFields {
+ fn from_text(text: &str) -> Self {
+ Self {
+ workspace: parse_key_in(text, "workspace"),
+ project: parse_key_in(text, "project"),
+ project_strategy: parse_key_in(text, "project_strategy"),
+ identity: parse_key_in(text, "identity"),
+ identity_style: parse_key_in(text, "identity_style"),
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct MarkerInspection {
+ pub(crate) status: &'static str,
+ pub(crate) fields: RoutingFields,
+ pub(crate) scope: Option<MarkerScope>,
+}
+
+pub(crate) fn inspect_scope(cwd: &str, env: &RuntimeEnv) -> MarkerInspection {
+ use std::io::Read as _;
+ let empty = |status| MarkerInspection {
+ status,
+ fields: RoutingFields::default(),
+ scope: None,
+ };
+ if env.ignore_marker() {
+ return empty("ignored");
+ }
+ let found = find_marker_matching(
+ 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.identity_style.as_deref().is_some_and(|style| {
+ ai_memory_core::repository_identity::IdentityStyle::from_str_opt(style).is_none()
+ }) || fields
+ .project_strategy
+ .as_deref()
+ .is_some_and(|strategy| !matches!(strategy, "repo-root" | "repo_root" | "basename"))
+ {
+ return Some(empty("conflicting"));
+ }
+ if !declares_more_than_capture(&text) {
+ return None;
+ }
+ 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),
+ })
+ },
+ );
+ found.unwrap_or_else(|| empty("absent"))
+}
+
impl MarkerScope {
/// Whether this marker declares anything that changes scope resolution.
/// A marker that only carries `[capture]` rules does not.
@@ -73,8 +182,6 @@ pub(crate) fn read_scope(cwd: &str, env: &RuntimeEnv) -> Option<MarkerScope> {
return None;
}
let path = find_settings_marker_with_home(cwd, env.home_dir().map(Path::new))?;
- // One read, three keys: the marker is re-read per key nowhere else on a
- // hot path, but this one runs on every client command.
let text = std::fs::read_to_string(&path).ok()?;
let mut scope = MarkerScope {
workspace: parse_key_in(&text, "workspace"),
@@ -83,8 +190,6 @@ pub(crate) fn read_scope(cwd: &str, env: &RuntimeEnv) -> Option<MarkerScope> {
path,
};
if scope.project_strategy.is_none() {
- // The install-wide `--project-strategy` default, if one was baked into
- // the environment. Empty values are treated as unset.
scope.project_strategy = env
.project_strategy()
.filter(|value| !value.trim().is_empty())
@@ -712,6 +817,45 @@ project = "infra" # this is fine
);
}
+ #[test]
+ fn strict_inspection_rejects_invalid_routing_without_exposing_fields() {
+ let tmp = TempDir::new().unwrap();
+ let inner = tmp.path().join("sub");
+ fs::create_dir_all(&inner).unwrap();
+ write_marker(
+ tmp.path(),
+ "workspace = [\nproject = \"private-project\"\nidentity = \"private/identity\"\n",
+ );
+
+ let inspection = inspect_scope(inner.to_str().unwrap(), &RuntimeEnv::default());
+ assert_eq!(inspection.status, "invalid");
+ assert!(inspection.scope.is_none());
+ assert!(inspection.fields.workspace.is_none());
+ assert!(inspection.fields.project.is_none());
+ assert!(inspection.fields.identity.is_none());
+ }
+
+ #[test]
+ fn strict_inspection_uses_the_same_capture_only_walk_as_scope_resolution() {
+ let tmp = TempDir::new().unwrap();
+ write_marker(
+ tmp.path(),
+ "workspace = \"acme\"\nproject = \"infra\"\nidentity_style = \"path\"\n",
+ );
+ let inner = tmp.path().join("sub");
+ fs::create_dir_all(&inner).unwrap();
+ write_marker(&inner, "[capture]\nignore_paths = [\"secret/**\"]\n");
+
+ let inspection = inspect_scope(inner.to_str().unwrap(), &RuntimeEnv::default());
+ assert_eq!(inspection.status, "valid");
+ assert_eq!(inspection.fields.workspace.as_deref(), Some("acme"));
+ assert_eq!(inspection.fields.project.as_deref(), Some("infra"));
+ assert_eq!(
+ inspection.scope,
+ read_scope(inner.to_str().unwrap(), &RuntimeEnv::default())
+ );
+ }
+
#[test]
fn declares_more_than_capture_is_conservative() {
assert!(!declares_more_than_capture(
diff --git a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
index ca2db8ed..03d5ce94 100644
--- a/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
+++ b/crates/ai-memory-cli/tests/suite/doctor_e2e.rs
@@ -146,6 +146,15 @@ mod slow {
.expect("doctor --json report");
assert_eq!(report["capture_owner_active"], false);
assert_eq!(report["identity"]["level"], "anonymous");
+ assert_eq!(report["project_coordinate"]["server"]["status"], "exact");
+ assert_eq!(
+ report["project_coordinate"]["server"]["requested_name"],
+ PROJECT
+ );
+ assert_eq!(
+ report["project_coordinate"]["local"]["marker_status"],
+ "absent"
+ );
assert_eq!(report["identity"]["version"], env!("CARGO_PKG_VERSION"));
let claude = find_row(&report, "claude-code")
@@ -195,6 +204,10 @@ mod slow {
human.contains("ran here but nothing was captured"),
"doctor must explain the gap in prose: {human}"
);
+ assert!(
+ human.contains("project coordinate: exact"),
+ "doctor must render the coordinate diagnosis: {human}"
+ );
// Import the local history through the same `/hook` ingress live capture
// uses, so the server now has captured sessions for claude-code.
@@ -357,4 +370,209 @@ mod slow {
drop(server);
}
+
+ #[tokio::test]
+ async fn ambiguous_coordinate_keeps_local_sessions_and_marks_capture_unavailable() {
+ let data_dir = tempfile::tempdir().expect("data dir");
+ let home = tempfile::tempdir().expect("home");
+ let project = tempfile::tempdir().expect("project cwd");
+ let cwd = fs::canonicalize(project.path()).expect("canonicalize project cwd");
+ std::process::Command::new("git")
+ .args(["init", "-q"])
+ .arg(&cwd)
+ .status()
+ .expect("initialize git repository");
+ std::process::Command::new("git")
+ .args(["-C"])
+ .arg(&cwd)
+ .args([
+ "remote",
+ "add",
+ "origin",
+ "https://user:[email protected]/acme/api.git",
+ ])
+ .status()
+ .expect("add git remote");
+
+ let encoded = cwd.to_string_lossy().replace('/', "-");
+ let session_dir = home.path().join(".claude").join("projects").join(encoded);
+ fs::create_dir_all(&session_dir).expect("session dir");
+ write_jsonl(
+ &session_dir.join("ambiguous-coordinate.jsonl"),
+ &[json!({
+ "sessionId": "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee",
+ "cwd": cwd.to_string_lossy(),
+ "type": "user",
+ "message": {"role": "user", "content": "Local evidence remains visible."},
+ })],
+ );
+
+ let client = reqwest::Client::new();
+ let (server, base) = start_serve(&client, &data_dir.path().join("serve.log"), |port| {
+ let mut cmd = hermetic(BIN);
+ cmd.args([
+ "serve",
+ "--transport",
+ "http",
+ "--bind",
+ &format!("127.0.0.1:{port}"),
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ "server-default",
+ "--no-watcher",
+ ])
+ .env("AI_MEMORY_DATA_DIR", data_dir.path())
+ .env("AI_MEMORY_HOME", home.path())
+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none");
+ cmd.current_dir(&cwd);
+ cmd
+ })
+ .await;
+
+ for (index, (project_name, identity)) in [
+ ("github-api", "github.com/acme/api"),
+ ("gitlab-api", "gitlab.com/acme/api"),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let response = client
+ .post(format!("{base}/hook"))
+ .query(&[
+ ("event", "session-start"),
+ ("agent", "claude-code"),
+ ("workspace", WORKSPACE),
+ ("project", project_name),
+ ("identity", identity),
+ ("identity_src", "git_remote"),
+ ])
+ .json(&json!({
+ "session_id": format!("00000000-0000-4000-8000-0000000001{index:02x}"),
+ "cwd": cwd,
+ }))
+ .send()
+ .await
+ .expect("send identity hook");
+ assert!(response.status().is_success(), "{response:?}");
+ }
+ for project_name in ["github-api", "gitlab-api"] {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while session_count(&client, &base, WORKSPACE, project_name).await == 0 {
+ assert!(Instant::now() < deadline, "project was not created");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ let output = run_cli(
+ &[
+ "doctor",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ "acme-api",
+ "--since-days",
+ "0",
+ "--json",
+ ],
+ data_dir.path(),
+ home.path(),
+ Some(&cwd),
+ &base,
+ );
+ let report: Value = serde_json::from_str(&output).expect("doctor report");
+ assert_eq!(
+ report["project_coordinate"]["server"]["status"],
+ "ambiguous"
+ );
+ assert_eq!(
+ report["project_coordinate"]["server"]["collision_reason"],
+ "cross_forge_collision"
+ );
+ assert!(
+ report["capture_coverage_problem"]["reason"]
+ .as_str()
+ .is_some_and(|reason| reason.contains("ambiguous"))
+ );
+ let claude = find_row(&report, "claude-code")
+ .unwrap_or_else(|| panic!("local session row disappeared: {report}"));
+ assert!(claude["local_recent"].as_u64().unwrap_or(0) >= 1);
+ assert!(claude["captured"].is_null());
+ assert!(claude["uncaptured"].is_null());
+ assert!(!output.contains("credential-sentinel"), "{output}");
+ assert!(!output.contains("github.com/acme/api"), "{output}");
+
+ let human = run_cli(
+ &[
+ "doctor",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ "acme-api",
+ "--since-days",
+ "0",
+ ],
+ data_dir.path(),
+ home.path(),
+ Some(&cwd),
+ &base,
+ );
+ assert!(human.contains("capture coverage: unavailable"), "{human}");
+ assert!(human.contains("unavailable captured"), "{human}");
+ assert!(human.contains("Capture verdict unavailable"), "{human}");
+ assert!(!human.contains("nothing was captured"), "{human}");
+ assert!(!human.contains("nothing captured yet"), "{human}");
+ assert!(!human.contains("Every harness"), "{human}");
+
+ let marker_path = cwd.join(".ai-memory.toml");
+ fs::write(
+ &marker_path,
+ "[capture] private-toml-sentinel\nignore_paths = [\"**\"]\n",
+ )
+ .expect("write invalid marker");
+ let malformed_json = run_cli(
+ &[
+ "doctor",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ "github-api",
+ "--since-days",
+ "0",
+ "--json",
+ ],
+ data_dir.path(),
+ home.path(),
+ Some(&cwd),
+ &base,
+ );
+ let malformed_report: Value =
+ serde_json::from_str(&malformed_json).expect("malformed-marker doctor report");
+ assert_eq!(
+ malformed_report["marker_capture_problem"]["classification"],
+ "settings_marker_invalid"
+ );
+ assert!(!malformed_json.contains(marker_path.to_str().unwrap()));
+ assert!(!malformed_json.contains("private-toml-sentinel"));
+ let malformed_human = run_cli(
+ &[
+ "doctor",
+ "--workspace",
+ WORKSPACE,
+ "--project",
+ "github-api",
+ "--since-days",
+ "0",
+ ],
+ data_dir.path(),
+ home.path(),
+ Some(&cwd),
+ &base,
+ );
+ assert!(malformed_human.contains("settings_marker_invalid"));
+ assert!(!malformed_human.contains(marker_path.to_str().unwrap()));
+ assert!(!malformed_human.contains("private-toml-sentinel"));
+
+ drop(server);
+ }
}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index d30cbce2..d4986d77 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -9,6 +9,7 @@
//! - `POST /admin/curator` — dry-run or stage a rule-based curator report.
//! - `GET /admin/status` — lifetime counts + server data-dir info.
//! - `GET /admin/projects` — authoritative `(workspace, project)` list.
+//! - `GET /admin/project-coordinate` — read-only exact/compatibility diagnosis.
//! - `GET /admin/open-sessions` — open (not yet ended) sessions for one scope + agent
//! (an exact `session_id` plus `include_ended=true` also matches an ended one).
//! - `GET /admin/sessions/by-agent` — session counts per agent CLI for one scope.
@@ -584,6 +585,7 @@ fn hex_to_sha256(hex: &str) -> Result<[u8; 32], String> {
/// - `POST /admin/curator`
/// - `GET /admin/status`
/// - `GET /admin/projects`
+/// - `GET /admin/project-coordinate`
/// - `GET /admin/open-sessions`
/// - `GET /admin/sessions/by-agent`
/// - `GET /admin/activity/by-client`
@@ -665,6 +667,7 @@ pub fn admin_router_with_sweep_tuning(
)
.route("/admin/status", get(handle_status))
.route("/admin/projects", get(handle_list_projects))
+ .route("/admin/project-coordinate", get(handle_project_coordinate))
.route("/admin/open-sessions", get(handle_open_sessions))
.route("/admin/sessions/by-agent", get(handle_sessions_by_agent))
.route("/admin/activity/by-client", get(handle_activity_by_client))
@@ -1435,6 +1438,76 @@ async fn handle_activity_by_client(
}
}
+#[derive(Debug, Deserialize)]
+struct ProjectCoordinateQuery {
+ workspace: String,
+ project: String,
+ identity: Option<String>,
+ identity_source: Option<String>,
+ identity_style: Option<String>,
+}
+
+async fn handle_project_coordinate(
+ State(state): State<Arc<AdminState>>,
+ Query(query): Query<ProjectCoordinateQuery>,
+) -> impl IntoResponse {
+ if query.workspace.trim().is_empty() || query.project.trim().is_empty() {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "workspace and project must be non-empty"
+ })),
+ );
+ }
+ let repository = match (query.identity.as_deref(), query.identity_source.as_deref()) {
+ (None, None) => None,
+ (Some(identity), Some(source)) => {
+ match ai_memory_core::repository_identity::accept_wire_identity(identity, source) {
+ Some(identity) => Some(identity),
+ None => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({ "error": "invalid repository identity" })),
+ );
+ }
+ }
+ }
+ _ => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "identity and identity_source must be provided together"
+ })),
+ );
+ }
+ };
+ let style = match query.identity_style.as_deref() {
+ None => ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ Some(style) => {
+ match ai_memory_core::repository_identity::IdentityStyle::from_str_opt(style) {
+ Some(style) => style,
+ None => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({ "error": "invalid identity_style" })),
+ );
+ }
+ }
+ }
+ };
+ match state
+ .reader
+ .diagnose_project_coordinate(query.workspace, query.project, repository, style)
+ .await
+ {
+ Ok(diagnostic) => (
+ StatusCode::OK,
+ Json(serde_json::to_value(diagnostic).unwrap_or_else(|_| serde_json::json!({}))),
+ ),
+ Err(error) => internal_err(error.to_string()),
+ }
+}
+
/// Query string for `GET /admin/sessions/by-agent` — how many sessions each
/// agent CLI opened in one scope.
///
@@ -13252,6 +13325,11 @@ mod tests {
serde_json::json!({"workspace": "default", "project": "scratch"}),
),
("GET", "/admin/status", serde_json::Value::Null),
+ (
+ "GET",
+ "/admin/project-coordinate?workspace=default&project=scratch",
+ serde_json::Value::Null,
+ ),
(
"GET",
"/admin/sessions/by-agent?workspace=default&project=scratch",
diff --git a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
index 618f7eb4..f355dad9 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
@@ -4,9 +4,10 @@
//! router: build an `AdminState` over a real on-disk store + wiki,
//! seed a couple of pages, and hit each route.
-use ai_memory_core::{NewPage, PagePath, Tier};
+use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
+use ai_memory_core::{ActorContext, AuthLevel, NewPage, NewUser, PagePath, Tier};
use ai_memory_mcp::{AdminState, admin_router};
-use ai_memory_store::{DecayParams, Store};
+use ai_memory_store::{AccessMode, DecayParams, GrantLevel, Store};
use ai_memory_wiki::Wiki;
use axum::body::Body;
use axum::http::{Request, StatusCode};
@@ -80,6 +81,20 @@ async fn body_bytes(resp: axum::response::Response) -> Vec<u8> {
.to_vec()
}
+async fn coordinate(app: axum::Router, query: &str) -> serde_json::Value {
+ let response = app
+ .oneshot(
+ Request::builder()
+ .uri(format!("/admin/project-coordinate?{query}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::OK);
+ serde_json::from_slice(&body_bytes(response).await).unwrap()
+}
+
#[tokio::test]
async fn status_returns_counts_and_paths() {
let tmp = TempDir::new().unwrap();
@@ -199,6 +214,286 @@ async fn list_projects_returns_workspace_project_pairs() {
);
}
+#[tokio::test]
+async fn project_coordinate_reports_all_statuses_and_never_mutates() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_admin_state(&tmp).await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("coordinates")
+ .await
+ .unwrap();
+ let repository = RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ };
+ let project = store
+ .writer
+ .resolve_project_by_identity(
+ ws,
+ repository,
+ IdentityStyle::HostPath,
+ "checkout-blue",
+ Some("/private/repository/path-sentinel".into()),
+ None,
+ None,
+ )
+ .await
+ .unwrap()
+ .0;
+ let manifest = state.wiki.project_root(ws, project).join("_meta.md");
+ std::fs::create_dir_all(manifest.parent().unwrap()).unwrap();
+ std::fs::write(&manifest, "sentinel manifest\n").unwrap();
+ let manifest_before = std::fs::read(&manifest).unwrap();
+ let snapshot = || {
+ rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row(
+ "SELECT (SELECT COUNT(*) FROM projects), name, \
+ (SELECT COUNT(*) FROM audit_log) FROM projects WHERE id = ?1",
+ [project.as_bytes().to_vec()],
+ |row| {
+ Ok((
+ row.get::<_, i64>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, i64>(2)?,
+ ))
+ },
+ )
+ .unwrap()
+ };
+ let operator = store
+ .writer
+ .create_user(
+ NewUser {
+ username: "operator-sentinel".into(),
+ name: Some("private-user-sentinel".into()),
+ email: Some("[email protected]".into()),
+ },
+ [6; ai_memory_store::TOKEN_HASH_LEN],
+ )
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(project, AccessMode::Restricted)
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(operator, project, GrantLevel::Read, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: project,
+ path: PagePath::new("private/repository-path-sentinel.md").unwrap(),
+ title: "Private page sentinel".into(),
+ body: "private-page-body-sentinel".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: Some(operator),
+ expires_at: None,
+ entities: Vec::new(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+ let before = snapshot();
+ let related_before: (i64, i64, i64) = rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row(
+ "SELECT (SELECT COUNT(*) FROM users), (SELECT COUNT(*) FROM project_grants), \
+ (SELECT COUNT(*) FROM pages)",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .unwrap();
+ let app = admin_router(state.clone()).layer(axum::middleware::from_fn(
+ |mut request: Request<Body>, next: axum::middleware::Next| async move {
+ request.extensions_mut().insert(AuthLevel::Root);
+ request.extensions_mut().insert(ActorContext::anonymous());
+ next.run(request).await
+ },
+ ));
+ for (name, expected, rename_eligible) in [
+ ("checkout-blue", "exact", false),
+ ("acme-api", "canonical_compat", true),
+ ("api", "legacy_compat", false),
+ ("unknown", "missing", false),
+ ] {
+ let body = coordinate(
+ app.clone(),
+ &format!(
+ "workspace=coordinates&project={name}&identity=github.com%2Facme%2Fapi&identity_source=git_remote&identity_style=path"
+ ),
+ )
+ .await;
+ assert_eq!(body["status"], expected, "{body}");
+ assert_eq!(body["rename_eligible"], rename_eligible, "{body}");
+ let rendered = body.to_string();
+ for secret in [
+ "github.com/acme/api",
+ "/private/repository/path-sentinel",
+ "private-user-sentinel",
+ "private/repository-path-sentinel.md",
+ "private-page-body-sentinel",
+ ] {
+ assert!(!rendered.contains(secret), "leaked {secret}: {rendered}");
+ }
+ }
+ assert_eq!(snapshot(), before, "diagnostic calls must not mutate SQL");
+ assert_eq!(
+ rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row(
+ "SELECT (SELECT COUNT(*) FROM users), (SELECT COUNT(*) FROM project_grants), \
+ (SELECT COUNT(*) FROM pages)",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .unwrap(),
+ related_before,
+ "diagnostic calls must not mutate users, grants, or pages",
+ );
+ assert_eq!(std::fs::read(&manifest).unwrap(), manifest_before);
+
+ store
+ .writer
+ .resolve_project_by_identity(
+ ws,
+ RepositoryIdentity {
+ identity: "gitlab.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ },
+ IdentityStyle::HostPath,
+ "gitlab-api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ let before_ambiguous = snapshot();
+ let ambiguous = coordinate(
+ app,
+ "workspace=coordinates&project=acme-api&identity=github.com%2Facme%2Fapi&identity_source=git_remote&identity_style=path",
+ )
+ .await;
+ assert_eq!(ambiguous["status"], "ambiguous");
+ assert_eq!(ambiguous["collision_reason"], "cross_forge_collision");
+ let ambiguous_rendered = ambiguous.to_string();
+ for secret in [
+ "github.com/acme/api",
+ "/private/repository/path-sentinel",
+ "private-user-sentinel",
+ "private/repository-path-sentinel.md",
+ "private-page-body-sentinel",
+ ] {
+ assert!(
+ !ambiguous_rendered.contains(secret),
+ "leaked {secret}: {ambiguous_rendered}"
+ );
+ }
+ assert_eq!(
+ snapshot(),
+ before_ambiguous,
+ "ambiguous diagnosis must not mutate SQL"
+ );
+ assert_eq!(std::fs::read(&manifest).unwrap(), manifest_before);
+ assert_eq!(
+ rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row(
+ "SELECT (SELECT COUNT(*) FROM users), (SELECT COUNT(*) FROM project_grants), \
+ (SELECT COUNT(*) FROM pages)",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .unwrap(),
+ related_before,
+ );
+ let after = snapshot();
+ assert_eq!(after.0, before.0 + 1);
+ assert_eq!(after.1, before.1);
+ assert_eq!(after.2, before.2);
+}
+
+#[tokio::test]
+async fn project_coordinate_single_user_admin_contract_remains_open() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_admin_state(&tmp).await;
+ let response = admin_router(state)
+ .oneshot(
+ Request::builder()
+ .uri("/admin/project-coordinate?workspace=unknown&project=unknown")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::OK);
+ let body: serde_json::Value = serde_json::from_slice(&body_bytes(response).await).unwrap();
+ assert_eq!(body["status"], "missing");
+}
+
+#[tokio::test]
+async fn project_coordinate_is_root_only_after_multiuser_enablement() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_admin_state(&tmp).await;
+ store
+ .writer
+ .create_user(
+ NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ },
+ [7; ai_memory_store::TOKEN_HASH_LEN],
+ )
+ .await
+ .unwrap();
+ let app = admin_router(state).layer(axum::middleware::from_fn(
+ |mut request: Request<Body>, next: axum::middleware::Next| async move {
+ let level = match request
+ .headers()
+ .get("x-level")
+ .and_then(|value| value.to_str().ok())
+ {
+ Some("root") => AuthLevel::Root,
+ Some("user") => AuthLevel::User,
+ _ => AuthLevel::Anonymous,
+ };
+ request.extensions_mut().insert(level);
+ request.extensions_mut().insert(ActorContext::anonymous());
+ next.run(request).await
+ },
+ ));
+ for (level, expected) in [
+ (Some("root"), StatusCode::OK),
+ (Some("user"), StatusCode::FORBIDDEN),
+ (None, StatusCode::UNAUTHORIZED),
+ ] {
+ let mut request =
+ Request::builder().uri("/admin/project-coordinate?workspace=unknown&project=unknown");
+ if let Some(level) = level {
+ request = request.header("x-level", level);
+ }
+ let response = app
+ .clone()
+ .oneshot(request.body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(response.status(), expected, "level {level:?}");
+ }
+}
+
#[tokio::test]
async fn search_returns_matching_hits() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 2c680a77..2e83ae91 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -86,7 +86,8 @@ pub use reader::{
DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding,
GraphVia, HealthDetail, HealthPage, ObservationHit, ObservationOrder, ObservationPage,
ObservationPageResult, ObservationRecord, OpenSession, PageAuthor, PageHit, PageHitWithMeta,
- PageLinks, PageMeta, PageSummary, ProjectSummary, RELATED_WALK_MAX_DEPTH,
+ PageLinks, PageMeta, PageSummary, ProjectCoordinateCollisionReason,
+ ProjectCoordinateDiagnostic, ProjectCoordinateStatus, ProjectSummary, RELATED_WALK_MAX_DEPTH,
RELATED_WALK_MAX_NODES, ReaderPool, ReindexTargetStatus, RelatedNode, RelatedPage,
RrfContributions, ScopeRow, SearchExplain, SessionConsolidationSummary, SessionDependentRows,
SessionEndDisposition, SessionSummary, SettledPage, StatusCounts, StorageStatus,
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index e5192fe1..4ac262ea 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -443,13 +443,10 @@ pub(crate) fn resolve_project_name_for_write(
.authorize(crate::ProjectAccess::Write)
.map_err(|error| StoreError::Forbidden(error.message()))?;
}
- let promote_to = if promote {
- matched
- .canonical_name
- .filter(|canonical| canonical == requested && canonical != &matched.current_name)
- } else {
- None
- };
+ let promote_to = promote
+ .then(|| crate::project_coordinates::promotion_target(&matched, requested))
+ .flatten()
+ .map(str::to_owned);
let promoted_from = if let Some(canonical) = promote_to {
rename_project_in_tx(
&tx,
diff --git a/crates/ai-memory-store/src/project_coordinates.rs b/crates/ai-memory-store/src/project_coordinates.rs
index cc4e0b1c..6947f4bd 100644
--- a/crates/ai-memory-store/src/project_coordinates.rs
+++ b/crates/ai-memory-store/src/project_coordinates.rs
@@ -10,56 +10,150 @@ use crate::{StoreError, StoreResult};
pub(crate) const MAX_COORDINATE_ROWS: usize = 4;
-const MATCH_SQL: &str = "SELECT id, name, NULLIF(canonical_name, '') \
- FROM projects INDEXED BY sqlite_autoindex_projects_2 \
- WHERE workspace_id = ?1 AND name = ?2 \
- UNION ALL \
- SELECT id, name, NULLIF(canonical_name, '') \
- FROM projects INDEXED BY idx_projects_canonical_name \
- WHERE workspace_id = ?1 AND canonical_name = ?2 AND canonical_name <> '' \
- UNION ALL \
- SELECT id, name, NULLIF(canonical_name, '') \
- FROM projects INDEXED BY idx_projects_legacy_name \
- WHERE workspace_id = ?1 AND legacy_name = ?2 AND legacy_name <> '' \
- LIMIT ?3";
+const MATCH_SQL: &str = "WITH \
+ exact AS (SELECT id FROM projects INDEXED BY sqlite_autoindex_projects_2 \
+ WHERE workspace_id = ?1 AND name = ?2), \
+ canonical AS (SELECT id FROM projects INDEXED BY idx_projects_canonical_name \
+ WHERE workspace_id = ?1 AND canonical_name = ?2 AND canonical_name <> '' \
+ ORDER BY rowid LIMIT ?5), \
+ legacy AS (SELECT id FROM projects INDEXED BY idx_projects_legacy_name \
+ WHERE workspace_id = ?1 AND legacy_name = ?2 AND legacy_name <> '' \
+ ORDER BY rowid LIMIT ?5), \
+ identity_match AS (SELECT id FROM projects INDEXED BY idx_projects_identity \
+ WHERE workspace_id = ?1 AND identity = ?3 AND identity <> '' AND ?3 <> ''), \
+ target AS (SELECT id FROM projects INDEXED BY sqlite_autoindex_projects_2 \
+ WHERE workspace_id = ?1 AND name = ?4 AND ?4 <> ''), \
+ target_compat AS (SELECT id FROM projects INDEXED BY idx_projects_canonical_name \
+ WHERE workspace_id = ?1 AND canonical_name = ?4 AND canonical_name <> '' AND ?4 <> '' \
+ ORDER BY rowid LIMIT ?5), \
+ raw_matches AS (\
+ SELECT id, 1 AS exact_match, 0 AS canonical_match, 0 AS legacy_match, \
+ 0 AS identity_match, 0 AS canonical_target FROM exact \
+ UNION ALL SELECT id, 0, 1, 0, 0, 0 FROM canonical \
+ UNION ALL SELECT id, 0, 0, 1, 0, 0 FROM legacy \
+ UNION ALL SELECT id, 0, 0, 0, 1, 0 FROM identity_match \
+ UNION ALL SELECT id, 0, 0, 0, 0, 1 FROM target \
+ UNION ALL SELECT id, 0, 0, 0, 0, 1 FROM target_compat), \
+ unique_matches AS (\
+ SELECT id, MAX(exact_match) AS exact_match, MAX(canonical_match) AS canonical_match, \
+ MAX(legacy_match) AS legacy_match, MAX(identity_match) AS identity_match, \
+ MAX(canonical_target) AS canonical_target \
+ FROM raw_matches GROUP BY id \
+ ORDER BY identity_match DESC, exact_match DESC, \
+ (exact_match OR canonical_match OR legacy_match) DESC, id LIMIT ?5) \
+ SELECT p.id, p.name, NULLIF(p.identity, ''), NULLIF(p.identity_source, ''), \
+ NULLIF(p.canonical_name, ''), NULLIF(p.legacy_name, ''), \
+ m.exact_match, m.canonical_match, m.legacy_match, m.identity_match, m.canonical_target \
+ FROM unique_matches m JOIN projects p ON p.id = m.id AND p.workspace_id = ?1 \
+ ORDER BY m.identity_match DESC, m.exact_match DESC, \
+ (m.exact_match OR m.canonical_match OR m.legacy_match) DESC, m.id";
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub(crate) struct MatchProvenance {
+ pub(crate) exact: bool,
+ pub(crate) canonical_compat: bool,
+ pub(crate) legacy_compat: bool,
+ pub(crate) identity: bool,
+ pub(crate) canonical_target: bool,
+}
+
+impl MatchProvenance {
+ pub(crate) fn requested(self) -> bool {
+ self.exact || self.canonical_compat || self.legacy_compat
+ }
+}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProjectCoordinateMatch {
pub(crate) id: ProjectId,
pub(crate) current_name: String,
+ pub(crate) identity: Option<String>,
+ pub(crate) identity_source: Option<String>,
pub(crate) canonical_name: Option<String>,
+ pub(crate) legacy_name: Option<String>,
+ pub(crate) provenance: MatchProvenance,
}
-pub(crate) fn resolve(
+pub(crate) fn matches(
conn: &Connection,
workspace_id: WorkspaceId,
requested: &str,
-) -> StoreResult<Option<ProjectCoordinateMatch>> {
+ repository: Option<&RepositoryIdentity>,
+) -> StoreResult<Vec<ProjectCoordinateMatch>> {
+ let identity = repository.map_or("", |repository| repository.identity.as_str());
+ let canonical = repository.and_then(path_style_name).unwrap_or_default();
let limit = i64::try_from(MAX_COORDINATE_ROWS).unwrap_or(i64::MAX);
let mut statement = conn.prepare(MATCH_SQL)?;
let rows = statement
- .query_map(params![workspace_id.as_bytes(), requested, limit], |row| {
- Ok((
- row.get::<_, Vec<u8>>(0)?,
- row.get::<_, String>(1)?,
- row.get::<_, Option<String>>(2)?,
- ))
- })?
+ .query_map(
+ params![
+ workspace_id.as_bytes(),
+ requested,
+ identity,
+ canonical,
+ limit
+ ],
+ |row| {
+ Ok((
+ row.get::<_, Vec<u8>>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, Option<String>>(2)?,
+ row.get::<_, Option<String>>(3)?,
+ row.get::<_, Option<String>>(4)?,
+ row.get::<_, Option<String>>(5)?,
+ row.get::<_, i64>(6)?,
+ row.get::<_, i64>(7)?,
+ row.get::<_, i64>(8)?,
+ row.get::<_, i64>(9)?,
+ row.get::<_, i64>(10)?,
+ ))
+ },
+ )?
.collect::<rusqlite::Result<Vec<_>>>()?;
- let mut matches = Vec::with_capacity(rows.len());
- for (raw_id, current_name, canonical_name) in rows {
- let candidate = ProjectCoordinateMatch {
- id: ProjectId::from_slice(&raw_id)?,
- current_name,
- canonical_name,
- };
- if !matches
- .iter()
- .any(|existing: &ProjectCoordinateMatch| existing.id == candidate.id)
- {
- matches.push(candidate);
- }
- }
+ rows.into_iter()
+ .map(
+ |(
+ raw_id,
+ current_name,
+ identity,
+ identity_source,
+ canonical_name,
+ legacy_name,
+ exact,
+ canonical_compat,
+ legacy_compat,
+ identity_match,
+ canonical_target,
+ )| {
+ Ok(ProjectCoordinateMatch {
+ id: ProjectId::from_slice(&raw_id)?,
+ current_name,
+ identity,
+ identity_source,
+ canonical_name,
+ legacy_name,
+ provenance: MatchProvenance {
+ exact: exact != 0,
+ canonical_compat: canonical_compat != 0,
+ legacy_compat: legacy_compat != 0,
+ identity: identity_match != 0,
+ canonical_target: canonical_target != 0,
+ },
+ })
+ },
+ )
+ .collect()
+}
+
+pub(crate) fn resolve(
+ conn: &Connection,
+ workspace_id: WorkspaceId,
+ requested: &str,
+) -> StoreResult<Option<ProjectCoordinateMatch>> {
+ let mut matches = matches(conn, workspace_id, requested, None)?
+ .into_iter()
+ .filter(|candidate| candidate.provenance.requested())
+ .collect::<Vec<_>>();
match matches.len() {
0 => Ok(None),
1 => Ok(matches.pop()),
@@ -67,6 +161,16 @@ pub(crate) fn resolve(
}
}
+pub(crate) fn promotion_target<'a>(
+ candidate: &'a ProjectCoordinateMatch,
+ requested: &str,
+) -> Option<&'a str> {
+ candidate
+ .canonical_name
+ .as_deref()
+ .filter(|canonical| *canonical == requested && *canonical != candidate.current_name)
+}
+
pub(crate) fn backfill(conn: &mut Connection) -> StoreResult<u64> {
let mut updated = 0_u64;
loop {
@@ -111,16 +215,37 @@ mod tests {
use super::*;
#[test]
- fn candidate_query_is_bounded_and_uses_only_coordinate_indexes() {
+ fn shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes() {
let mut conn = Connection::open_in_memory().unwrap();
crate::migrations::run(&mut conn).unwrap();
let workspace = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();
- for index in 0..1_000_u32 {
- crate::ops::get_or_create_project(
- &mut conn,
- &workspace,
- &format!("unrelated-{index}"),
- None,
+ let repository = RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ };
+ crate::ops::resolve_project_by_identity(
+ &mut conn,
+ &workspace,
+ &repository,
+ ai_memory_core::repository_identity::IdentityStyle::Path,
+ "api",
+ None,
+ None,
+ None,
+ crate::AccessMode::Open,
+ )
+ .unwrap();
+ for index in 0..20_u32 {
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, created_at, identity, \
+ identity_source, canonical_name, legacy_name) \
+ VALUES (?1, ?2, ?3, 1, ?4, 'git_remote', 'collision', 'collision')",
+ params![
+ ProjectId::new().as_bytes(),
+ workspace.as_bytes(),
+ format!("collision-{index}"),
+ format!("forge-{index}.example/acme/api")
+ ],
)
.unwrap();
}
@@ -130,6 +255,8 @@ mod tests {
.query_map(
params![
workspace.as_bytes(),
+ "api",
+ repository.identity,
"acme-api",
i64::try_from(MAX_COORDINATE_ROWS).unwrap()
],
@@ -138,64 +265,33 @@ mod tests {
.unwrap()
.collect::<rusqlite::Result<_>>()
.unwrap();
- assert!(MATCH_SQL.contains("LIMIT ?3"));
- let mut statement = conn.prepare(MATCH_SQL).unwrap();
- let mut rows = statement
- .query(params![
- workspace.as_bytes(),
- "absent",
- MAX_COORDINATE_ROWS as i64
- ])
- .unwrap();
- assert!(rows.next().unwrap().is_none());
- drop(rows);
+ assert!(MATCH_SQL.contains("GROUP BY id"));
+ assert!(MATCH_SQL.contains("LIMIT ?5"));
+ let candidates = matches(&conn, workspace, "collision", None).unwrap();
+ assert_eq!(candidates.len(), MAX_COORDINATE_ROWS);
assert_eq!(
- statement.get_status(rusqlite::StatementStatus::FullscanStep),
- 0
+ candidates
+ .iter()
+ .map(|candidate| candidate.id)
+ .collect::<std::collections::HashSet<_>>()
+ .len(),
+ MAX_COORDINATE_ROWS
);
- assert!(statement.get_status(rusqlite::StatementStatus::VmStep) < 100);
- drop(statement);
- for index in 0..20_u32 {
- conn.execute(
- "INSERT INTO projects (id, workspace_id, name, created_at, canonical_name, legacy_name) \
- VALUES (?1, ?2, ?3, 1, 'collision', 'collision')",
- params![ProjectId::new().as_bytes(), workspace.as_bytes(), format!("collision-{index}")],
- ).unwrap();
- }
- let mut statement = conn.prepare(MATCH_SQL).unwrap();
- let count = statement
- .query_map(
- params![
- workspace.as_bytes(),
- "collision",
- MAX_COORDINATE_ROWS as i64
- ],
- |_| Ok(()),
- )
- .unwrap()
- .count();
- assert_eq!(count, MAX_COORDINATE_ROWS);
- assert_eq!(
- statement.get_status(rusqlite::StatementStatus::FullscanStep),
- 0
- );
- assert!(statement.get_status(rusqlite::StatementStatus::VmStep) < 200);
assert!(matches!(
resolve(&conn, workspace, "collision"),
Err(StoreError::ProjectNameAmbiguous(_))
));
- assert!(
- plan.iter()
- .any(|line| line.contains("sqlite_autoindex_projects_2"))
- );
- assert!(
- plan.iter()
- .any(|line| line.contains("idx_projects_canonical_name"))
- );
- assert!(
- plan.iter()
- .any(|line| line.contains("idx_projects_legacy_name"))
- );
+ for index in [
+ "sqlite_autoindex_projects_2",
+ "idx_projects_canonical_name",
+ "idx_projects_legacy_name",
+ "idx_projects_identity",
+ ] {
+ assert!(
+ plan.iter().any(|line| line.contains(index)),
+ "{index}: {plan:?}"
+ );
+ }
assert!(
plan.iter().all(|line| !line.contains("SCAN projects")),
"{plan:?}"
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index b16702ba..2b141b40 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1473,6 +1473,94 @@ pub struct WorkspaceScopeRow {
pub workspace_name: String,
}
+/// How a requested project coordinate relates to stored projects.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ProjectCoordinateStatus {
+ /// The requested name is the project's current stored name.
+ Exact,
+ /// The requested name matched the canonical path-style compatibility key.
+ CanonicalCompat,
+ /// The requested name matched the v2 basename compatibility key.
+ LegacyCompat,
+ /// No workspace/project candidate exists.
+ Missing,
+ /// More than one project UUID matched the requested coordinate.
+ Ambiguous,
+}
+
+impl std::fmt::Display for ProjectCoordinateStatus {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(match self {
+ Self::Exact => "exact",
+ Self::CanonicalCompat => "canonical_compat",
+ Self::LegacyCompat => "legacy_compat",
+ Self::Missing => "missing",
+ Self::Ambiguous => "ambiguous",
+ })
+ }
+}
+
+/// Why a coordinate cannot be safely promoted or adopted.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ProjectCoordinateCollisionReason {
+ /// Different remote identities share one hostless path-style key.
+ CrossForgeCollision,
+ /// Different project UUIDs matched exact/canonical/legacy probes.
+ MultipleProjects,
+ /// The canonical target name is held by another project.
+ CanonicalTargetOccupied,
+ /// The requested exact name is held by a different identity-backed project.
+ CrossIdentityOccupied,
+ /// The exact-name holder has no repository identity and cannot be adopted diagnostically.
+ UnclaimedIdentitylessProject,
+}
+
+impl std::fmt::Display for ProjectCoordinateCollisionReason {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(match self {
+ Self::CrossForgeCollision => "cross_forge_collision",
+ Self::MultipleProjects => "multiple_projects",
+ Self::CanonicalTargetOccupied => "canonical_target_occupied",
+ Self::CrossIdentityOccupied => "cross_identity_occupied",
+ Self::UnclaimedIdentitylessProject => "unclaimed_identityless_project",
+ })
+ }
+}
+
+/// Read-only diagnostic for one requested workspace/project coordinate.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ProjectCoordinateDiagnostic {
+ /// Workspace requested by the caller.
+ pub workspace: String,
+ /// Project name requested by the caller.
+ pub requested_name: String,
+ /// Typed resolution status.
+ pub status: ProjectCoordinateStatus,
+ /// Existing project UUID when one candidate is preferred for context.
+ /// An ambiguous status may prefer the supplied identity's project; this
+ /// does not imply unique resolution or rename eligibility.
+ pub project_id: Option<ProjectId>,
+ /// Current name of the preferred contextual candidate, when present.
+ /// Interpret this together with `status`, never as a successful resolution.
+ pub current_name: Option<String>,
+ /// Canonical path-style candidate when known.
+ pub canonical_candidate: Option<String>,
+ /// Legacy basename candidate when known.
+ pub legacy_candidate: Option<String>,
+ /// Safe identity source, never the identity or remote URL.
+ pub identity_source: Option<String>,
+ /// Naming style implied by the current/canonical relationship.
+ pub identity_style: Option<String>,
+ /// Whether an authorized write through this requested name could rename in place.
+ pub rename_eligible: bool,
+ /// Typed reason that safe promotion/adoption is unavailable.
+ pub collision_reason: Option<ProjectCoordinateCollisionReason>,
+ /// Candidate count after project-UUID deduplication.
+ pub candidate_count: usize,
+}
+
/// One `(workspace, project)` scope with the ids + repo_path needed to write
/// its self-describing `_meta.md` manifest. Returned by
/// [`ReaderPool::list_all_scopes`]; consumed by `Wiki::backfill_scope_manifests`.
@@ -8982,6 +9070,152 @@ impl ReaderPool {
.await
}
+ /// Diagnose a requested project coordinate without creating, claiming, or renaming.
+ ///
+ /// The lookup uses the same bounded exact/canonical/legacy indexes as normal
+ /// compatibility resolution, but retains probe provenance and conflicting
+ /// candidates for operator diagnostics.
+ pub async fn diagnose_project_coordinate(
+ &self,
+ workspace: String,
+ requested_name: String,
+ repository: Option<ai_memory_core::repository_identity::RepositoryIdentity>,
+ requested_style: ai_memory_core::repository_identity::IdentityStyle,
+ ) -> StoreResult<ProjectCoordinateDiagnostic> {
+ let canonical_candidate = repository
+ .as_ref()
+ .and_then(ai_memory_core::repository_identity::path_style_name);
+ let legacy_candidate = repository
+ .as_ref()
+ .and_then(ai_memory_core::repository_identity::legacy_basename_name);
+ let local_source = repository.as_ref().map(|identity| identity.source);
+ let requested = requested_name.clone();
+ let workspace_name = workspace.clone();
+ self.with_conn(move |conn| {
+ let workspace_id = conn
+ .query_row(
+ "SELECT id FROM workspaces WHERE name = ?1",
+ params![workspace_name],
+ |row| row.get::<_, Vec<u8>>(0),
+ )
+ .optional()?
+ .map(|bytes| WorkspaceId::from_slice(&bytes))
+ .transpose()?;
+ let Some(workspace_id) = workspace_id else {
+ return Ok(ProjectCoordinateDiagnostic {
+ workspace,
+ requested_name,
+ status: ProjectCoordinateStatus::Missing,
+ project_id: None,
+ current_name: None,
+ canonical_candidate,
+ legacy_candidate,
+ identity_source: local_source.map(|source| source.as_str().to_owned()),
+ identity_style: local_source.map(|_| requested_style.as_str().to_owned()),
+ rename_eligible: false,
+ collision_reason: None,
+ candidate_count: 0,
+ });
+ };
+
+ let matches = crate::project_coordinates::matches(
+ conn,
+ workspace_id,
+ &requested,
+ repository.as_ref(),
+ )?;
+ let requested_matches = matches
+ .iter()
+ .filter(|candidate| candidate.provenance.requested())
+ .collect::<Vec<_>>();
+ let identity_match = matches
+ .iter()
+ .find(|candidate| candidate.provenance.identity);
+ let exact_match = requested_matches
+ .iter()
+ .copied()
+ .find(|candidate| candidate.provenance.exact);
+ let canonical_collision = identity_match.and_then(|identity| {
+ matches.iter().find(|candidate| {
+ candidate.provenance.canonical_target && candidate.id != identity.id
+ })
+ });
+ let identity_conflict = repository.as_ref().is_some_and(|repository| {
+ exact_match.is_some_and(|candidate| {
+ candidate
+ .identity
+ .as_deref()
+ .is_some_and(|stored| stored != repository.identity)
+ })
+ });
+ let identityless_collision = repository.is_some()
+ && exact_match.is_some_and(|candidate| candidate.identity.is_none());
+ let ambiguous = requested_matches.len() > 1
+ || identity_conflict
+ || identityless_collision
+ || (identity_match.is_some()
+ && exact_match
+ .is_some_and(|exact| Some(exact.id) != identity_match.map(|row| row.id)));
+
+ let primary = identity_match.or_else(|| requested_matches.first().copied());
+ let status = if ambiguous {
+ ProjectCoordinateStatus::Ambiguous
+ } else if let Some(candidate) = requested_matches.first() {
+ if candidate.provenance.exact {
+ ProjectCoordinateStatus::Exact
+ } else if candidate.provenance.canonical_compat {
+ ProjectCoordinateStatus::CanonicalCompat
+ } else {
+ ProjectCoordinateStatus::LegacyCompat
+ }
+ } else {
+ ProjectCoordinateStatus::Missing
+ };
+ let collision_reason = if identityless_collision {
+ Some(ProjectCoordinateCollisionReason::UnclaimedIdentitylessProject)
+ } else if let Some(holder) = canonical_collision {
+ Some(if holder.identity_source.as_deref() == Some("git_remote") {
+ ProjectCoordinateCollisionReason::CrossForgeCollision
+ } else {
+ ProjectCoordinateCollisionReason::CanonicalTargetOccupied
+ })
+ } else if identity_conflict {
+ Some(ProjectCoordinateCollisionReason::CrossIdentityOccupied)
+ } else if requested_matches.len() > 1 && identity_match.is_some() {
+ Some(ProjectCoordinateCollisionReason::CrossForgeCollision)
+ } else if ambiguous {
+ Some(ProjectCoordinateCollisionReason::MultipleProjects)
+ } else {
+ None
+ };
+ let rename_eligible = requested_matches.len() == 1
+ && requested_matches.first().is_some_and(|candidate| {
+ crate::project_coordinates::promotion_target(candidate, &requested).is_some()
+ })
+ && collision_reason.is_none();
+
+ Ok(ProjectCoordinateDiagnostic {
+ workspace,
+ requested_name,
+ status,
+ project_id: primary.map(|candidate| candidate.id),
+ current_name: primary.map(|candidate| candidate.current_name.clone()),
+ canonical_candidate: canonical_candidate
+ .or_else(|| primary.and_then(|candidate| candidate.canonical_name.clone())),
+ legacy_candidate: legacy_candidate
+ .or_else(|| primary.and_then(|candidate| candidate.legacy_name.clone())),
+ identity_source: local_source
+ .map(|source| source.as_str().to_owned())
+ .or_else(|| primary.and_then(|candidate| candidate.identity_source.clone())),
+ identity_style: local_source.map(|_| requested_style.as_str().to_owned()),
+ rename_eligible,
+ collision_reason,
+ candidate_count: matches.len(),
+ })
+ })
+ .await
+ }
+
/// Look up a project id by `(workspace_id, name)` without creating it.
///
/// Returns `None` when no project with the given name exists in the workspace.
diff --git a/crates/ai-memory-store/tests/suite/identity_resolution.rs b/crates/ai-memory-store/tests/suite/identity_resolution.rs
index c2d44d9e..a0792a20 100644
--- a/crates/ai-memory-store/tests/suite/identity_resolution.rs
+++ b/crates/ai-memory-store/tests/suite/identity_resolution.rs
@@ -14,9 +14,10 @@ use ai_memory_core::{
SessionId, Tier, UserId, WorkspaceId,
};
use ai_memory_store::{
- AccessMode, GrantLevel, IdentityResolution, ProjectAccess, ProjectPrincipal, ScopeName,
- ScopeResolutionError, Store, create_explicit_scope_guarded, lookup_existing_scope,
- lookup_existing_scope_guarded, resolve_many_existing_scopes,
+ AccessMode, GrantLevel, IdentityResolution, ProjectAccess, ProjectCoordinateCollisionReason,
+ ProjectCoordinateStatus, ProjectPrincipal, ScopeName, ScopeResolutionError, Store,
+ create_explicit_scope_guarded, lookup_existing_scope, lookup_existing_scope_guarded,
+ resolve_many_existing_scopes,
};
fn remote(identity: &str) -> RepositoryIdentity {
@@ -536,6 +537,253 @@ fn preserved_page(ws: WorkspaceId, project: ProjectId) -> NewPage {
}
}
+#[tokio::test]
+async fn coordinate_diagnostic_classifies_exact_canonical_legacy_and_missing_without_mutation() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let repository = remote("github.com/acme/api");
+ let project = resolve(&store, ws, &repository, "checkout-blue", None)
+ .await
+ .0;
+ let before: (i64, String, i64) = rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row(
+ "SELECT (SELECT COUNT(*) FROM projects), name, \
+ (SELECT COUNT(*) FROM audit_log) FROM projects WHERE id = ?1",
+ [project.as_bytes().to_vec()],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .unwrap();
+
+ for (name, status, rename_eligible) in [
+ ("checkout-blue", ProjectCoordinateStatus::Exact, false),
+ ("acme-api", ProjectCoordinateStatus::CanonicalCompat, true),
+ ("api", ProjectCoordinateStatus::LegacyCompat, false),
+ ] {
+ let diagnostic = store
+ .reader
+ .diagnose_project_coordinate(
+ "default".into(),
+ name.into(),
+ Some(repository.clone()),
+ IdentityStyle::Path,
+ )
+ .await
+ .unwrap();
+ assert_eq!(diagnostic.status, status, "{name}");
+ assert_eq!(diagnostic.project_id, Some(project));
+ assert_eq!(diagnostic.current_name.as_deref(), Some("checkout-blue"));
+ assert_eq!(diagnostic.canonical_candidate.as_deref(), Some("acme-api"));
+ assert_eq!(diagnostic.legacy_candidate.as_deref(), Some("api"));
+ assert_eq!(diagnostic.identity_source.as_deref(), Some("git_remote"));
+ assert_eq!(diagnostic.rename_eligible, rename_eligible);
+ }
+ let no_identity = store
+ .reader
+ .diagnose_project_coordinate(
+ "default".into(),
+ "acme-api".into(),
+ None,
+ IdentityStyle::HostPath,
+ )
+ .await
+ .unwrap();
+ assert_eq!(no_identity.status, ProjectCoordinateStatus::CanonicalCompat);
+ assert_eq!(no_identity.project_id, Some(project));
+ assert!(no_identity.rename_eligible);
+ assert_eq!(no_identity.identity_style, None);
+
+ let missing = store
+ .reader
+ .diagnose_project_coordinate(
+ "default".into(),
+ "unknown".into(),
+ Some(repository),
+ IdentityStyle::Path,
+ )
+ .await
+ .unwrap();
+ assert_eq!(missing.status, ProjectCoordinateStatus::Missing);
+ assert_eq!(missing.project_id, Some(project));
+ assert_eq!(missing.current_name.as_deref(), Some("checkout-blue"));
+ assert_eq!(missing.canonical_candidate.as_deref(), Some("acme-api"));
+ assert!(!missing.rename_eligible);
+
+ let after: (i64, String, i64) = rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row(
+ "SELECT (SELECT COUNT(*) FROM projects), name, \
+ (SELECT COUNT(*) FROM audit_log) FROM projects WHERE id = ?1",
+ [project.as_bytes().to_vec()],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .unwrap();
+ assert_eq!(after, before);
+}
+
+#[tokio::test]
+async fn coordinate_diagnostic_reports_cross_forge_and_identityless_collisions() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let _github = resolve(
+ &store,
+ ws,
+ &remote("github.com/acme/api"),
+ "github-api",
+ None,
+ )
+ .await
+ .0;
+ let gitlab = resolve(
+ &store,
+ ws,
+ &remote("gitlab.com/acme/api"),
+ "gitlab-api",
+ None,
+ )
+ .await
+ .0;
+ let ambiguous = store
+ .reader
+ .diagnose_project_coordinate(
+ "default".into(),
+ "acme-api".into(),
+ Some(remote("gitlab.com/acme/api")),
+ IdentityStyle::Path,
+ )
+ .await
+ .unwrap();
+ assert_eq!(ambiguous.status, ProjectCoordinateStatus::Ambiguous);
+ assert_eq!(
+ ambiguous.collision_reason,
+ Some(ProjectCoordinateCollisionReason::CrossForgeCollision)
+ );
+ assert_eq!(ambiguous.candidate_count, 2);
+ assert_eq!(ambiguous.project_id, Some(gitlab));
+
+ let identityless = store
+ .writer
+ .get_or_create_project(ws, "occupied", None)
+ .await
+ .unwrap();
+ let identity_backed = resolve(
+ &store,
+ ws,
+ &remote("github.com/acme/occupied"),
+ "elsewhere",
+ None,
+ )
+ .await
+ .0;
+ let occupied = store
+ .reader
+ .diagnose_project_coordinate(
+ "default".into(),
+ "occupied".into(),
+ Some(remote("github.com/acme/occupied")),
+ IdentityStyle::Path,
+ )
+ .await
+ .unwrap();
+ assert_eq!(occupied.status, ProjectCoordinateStatus::Ambiguous);
+ assert_eq!(
+ occupied.collision_reason,
+ Some(ProjectCoordinateCollisionReason::UnclaimedIdentitylessProject)
+ );
+ assert_eq!(occupied.candidate_count, 2);
+ assert_eq!(occupied.project_id, Some(identity_backed));
+ assert_ne!(identityless, identity_backed);
+
+ let unclaimed_only = store
+ .writer
+ .get_or_create_project(ws, "unclaimed-only", None)
+ .await
+ .unwrap();
+ let unclaimed = store
+ .reader
+ .diagnose_project_coordinate(
+ "default".into(),
+ "unclaimed-only".into(),
+ Some(remote("github.com/acme/unclaimed-only")),
+ IdentityStyle::Path,
+ )
+ .await
+ .unwrap();
+ assert_eq!(unclaimed.status, ProjectCoordinateStatus::Ambiguous);
+ assert_eq!(unclaimed.project_id, Some(unclaimed_only));
+ assert_eq!(
+ unclaimed.collision_reason,
+ Some(ProjectCoordinateCollisionReason::UnclaimedIdentitylessProject)
+ );
+ assert!(!unclaimed.rename_eligible);
+
+ let holder = resolve(
+ &store,
+ ws,
+ &explicit("another/repository"),
+ "acme-target-taken",
+ None,
+ )
+ .await
+ .0;
+ let intended = resolve(
+ &store,
+ ws,
+ &remote("github.com/acme/target-taken"),
+ "legacy-target",
+ None,
+ )
+ .await
+ .0;
+ let occupied = store
+ .reader
+ .diagnose_project_coordinate(
+ "default".into(),
+ "acme-target-taken".into(),
+ Some(remote("github.com/acme/target-taken")),
+ IdentityStyle::Path,
+ )
+ .await
+ .unwrap();
+ assert_eq!(occupied.status, ProjectCoordinateStatus::Ambiguous);
+ assert_eq!(occupied.project_id, Some(intended));
+ assert_eq!(
+ occupied.collision_reason,
+ Some(ProjectCoordinateCollisionReason::CanonicalTargetOccupied)
+ );
+ assert_eq!(occupied.candidate_count, 2);
+ assert_ne!(holder, intended);
+
+ let foreign = resolve(
+ &store,
+ ws,
+ &remote("github.com/other/occupied-name"),
+ "occupied-name",
+ None,
+ )
+ .await
+ .0;
+ let foreign_occupied = store
+ .reader
+ .diagnose_project_coordinate(
+ "default".into(),
+ "occupied-name".into(),
+ Some(remote("gitlab.com/acme/unrelated")),
+ IdentityStyle::Path,
+ )
+ .await
+ .unwrap();
+ assert_eq!(foreign_occupied.status, ProjectCoordinateStatus::Ambiguous);
+ assert_eq!(foreign_occupied.project_id, Some(foreign));
+ assert_eq!(
+ foreign_occupied.collision_reason,
+ Some(ProjectCoordinateCollisionReason::CrossIdentityOccupied)
+ );
+ assert!(!foreign_occupied.rename_eligible);
+}
+
#[tokio::test]
async fn canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming() {
let tmp = tempfile::TempDir::new().unwrap();
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 30649d30..49edfaa8 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -319,6 +319,18 @@ web UI. `ai-memory doctor` uses it to show caller identity and capture ownership
its per-agent counts flag sessions with multiple capture sources (native events
or distinct extensions, including backfill).
The mixed-source count is computed in the same scoped, owner-filtered SQL query.
+`GET /admin/project-coordinate` is a root/admin read-only diagnostic over the
+same bounded exact/canonical/legacy indexes used by scope resolution. It returns
+typed status and collision metadata but never creates, claims, renames, audits,
+or writes a scope manifest. An `ambiguous` result may include the preferred
+identity-backed candidate's UUID/current name as context; that is not unique
+resolution and never makes the request rename-eligible. The endpoint omits the
+stored identity value and reports only its safe source/style and derived
+candidate names. `doctor` adds a safe marker
+status/source class and credential-stripped repository evidence from one shared
+local inspection before rendering that response. If compatibility resolution is
+ambiguous, local session rows remain visible while captured counts are marked
+unavailable rather than rendered as zero.
Lifecycle bodies have content limits independent of the 10 MiB HTTP request
limit. User prompts and post-compaction summaries are capped UTF-8-safely at
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 1999edb9..6c926d57 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -384,6 +384,16 @@ ai-memory serve # run the server
(removed by hand, a failed first wire), install them by hand: `ai-memory
install-hooks --agent <your-agent> --apply` and `ai-memory install-mcp
--client <client> --apply`. Then check `ai-memory status` / `ai-memory doctor`.
+- **The current checkout resolves to an unexpected project**: run `ai-memory
+ doctor`. Its project-coordinate block shows the effective local marker,
+ credential-stripped repository identity source/style, canonical and legacy
+ candidate names, the server's exact/compatibility/missing/ambiguous result,
+ and whether an authorized write can promote the existing name in place. The
+ check is read-only: an unknown coordinate is reported, never created. If the
+ server coordinate is ambiguous, a returned UUID/current name is only the
+ preferred identity-backed candidate for context, not a unique resolution or
+ rename permission. Local harness rows remain visible and their captured
+ counts are shown as unavailable rather than zero.
- **Only *some* agents are being remembered**: run `ai-memory doctor`. It lists
every harness that has local sessions in this project and whether the server
captured them — so a harness you rotated in without installing its hook (a
diff --git a/docs/design-per-project-authz.md b/docs/design-per-project-authz.md
index d9bd63d2..4db25981 100644
--- a/docs/design-per-project-authz.md
+++ b/docs/design-per-project-authz.md
@@ -267,7 +267,23 @@ project. #1033 makes a remote-derived key the default name, landing in steps on
plus the derived `canonical_name`/`legacy_name` keys. Clean
reindex validates the pair, derives the indexed keys from the identity, and
recreates the original UUID/name; pre-V76 manifests without identity remain
- valid and rebuild an identity-less project.
-4. Marker `aliases`, then 5. identity- or path-keyed blocks in `~/.ai-memory.toml`.
+ valid and rebuild an identity-less project.
+4. **Coordinate diagnostics (landed).** `GET /admin/project-coordinate` and
+ `ai-memory doctor` classify exact, canonical-compatibility,
+ legacy-compatibility, missing, and ambiguous coordinates. They report
+ rename eligibility and collision reasons from read-only indexed store
+ queries; no project, claim, rename, audit entry, or manifest is written.
+ The admin route follows the existing single-user compatibility contract and
+ becomes root-only whenever the deployment distinguishes operators. Stored
+ remote identities are not returned; the CLI parses one typed local marker
+ inspection, honours CLI-over-marker scope precedence, supplies only its
+ normalized credential-free identity, and renders safe marker/source classes,
+ source/style and derived names. Ambiguous server scope leaves local session
+ evidence intact and marks captured counts unavailable rather than zero. An
+ ambiguous result may carry the preferred identity-backed candidate UUID and
+ current name for operator context; it still represents no unique resolution
+ and is never rename-eligible.
+5. Marker `aliases`, then 6. identity- or path-keyed blocks in `~/.ai-memory.toml`.
+
Paths stay lexically normalised throughout; nothing canonicalises.
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 2704ba35..840c364f 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -648,6 +648,16 @@ own name.
- Static CLI/MCP clients still pass only `workspace` + `project`. They may use
the canonical path name (`acme-api`) or the v2 basename (`api`) while it is
unambiguous. A hostless key shared by multiple forges fails closed.
+- `ai-memory doctor` combines the effective local marker and normalized
+ repository evidence with the server's read-only coordinate diagnosis. It
+ reports exact/canonical/legacy compatibility, missing or ambiguous status,
+ rename eligibility, and collision reasons. It parses the routing marker once,
+ honours CLI scope flags before marker names, and reports only a safe marker
+ status/source class; invalid marker TOML is ignored without echoing its
+ contents, raw marker paths are never rendered, and remote credentials never
+ leave the client. An ambiguous result can name the preferred identity-backed
+ candidate UUID/current name for context, but is never a unique resolution or
+ rename-eligible result.
- The UUID-keyed project `_meta.md` persists optional `identity`,
`identity_source`, `canonical_name`, and `legacy_name` fields. A clean
`reindex` restores the original UUID/name and recomputes the indexed keys
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 09cea7f6..2e8def0c 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -81,6 +81,7 @@ boundary not yet built.
| 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |
| 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`; store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory |
| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; under `identity_style = "path"` (#1033) a project it creates takes `path_style_name` only while no project in the workspace holds that name (checked in the same transaction), so the same path on another forge falls back instead of being merged; later static canonical writes may promote that same identity-backed row's name through the separately inventoried scope boundary while keeping its UUID; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`, `the_same_path_on_another_forge_falls_back_instead_of_merging` and `an_unclaimed_project_holding_the_path_name_is_not_taken` (both fail with the free-name check removed; controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |
+| 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 |
| 14e | `memory_write_page` session evidence cites only a session of the target project (#708) | `ai-memory-mcp/src/server.rs` `memory_write_page` — a `session_id` is accepted only when `require_session_in_scope` resolves the session (where its observations landed, else its session row, as `Consolidator::session_target` does) to the same `(workspace_id, project_id)` the write grant was checked against; unknown and foreign ids get one refusal, so the error is no existence oracle; `scope: "global"` with a `session_id` is refused; `refuse_pinned_page_overwrite` keeps a write that cites a session off a pinned page; only a write to `sessions/<id>.md` reconciles the session's queued SessionEnd job | `server.rs` `write_page_refuses_a_session_from_another_project` (a foreign and an unknown session refused, no evidence row written, the foreign job still queued; control: the project's own session accepted), `session_evidence_write_leaves_a_pinned_page_alone` (control: the same write without `session_id` edits the page), `session_evidence_on_another_path_leaves_the_job_queued`, `write_page_rejects_a_malformed_or_global_session_id` — each of the scope check, the pinned check and the session-page-only reconcile proven to fail its test when removed | STRONG |