Skip to content

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

Rust

feat(identity): resolve canonical project keys and promote in place (#1033)

AkitaOnRails0ec409b15038
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05b30ee2..b3c31c5d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -224,6 +224,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
keeps the name it would otherwise get. The default stays `host_path`. (#1033)
### Changed
+- Changed static CLI/MCP project-name resolution to accept an existing
+ repository's canonical hostless path name and its v2 basename compatibility
+ key. Reads remain find-only; an authorized write through the canonical key
+ promotes only `projects.name` in place, preserving the project UUID and all
+ dependent rows. Project scope manifests preserve the optional full hostful
+ identity/source and derived keys so clean reindex reconstructs the same UUID
+ and lookup behavior; older manifests remain valid. MCP, admin, and
+ managed-workstream writes refresh the manifest after promotion and disclose a
+ post-commit refresh failure for startup repair on both success and any later
+ operation error, retaining the first warning across busy retries and lease
+ wait-out; managed-run caller validation happens before promotion.
+ Ambiguous cross-forge keys and target-name conflicts fail
+ closed, and the default identity style remains `host_path`. (#1033)
- Changed the documented precedence between rules and memory: the user's
instructions, then the repository's rules file, then the project's memory,
then the cross-project profile. Where no hard rule exists, agents now use
diff --git a/Cargo.lock b/Cargo.lock
index 82992a9b..65ba584d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -164,6 +164,7 @@ dependencies = [
"axum",
"git2",
"jiff",
+ "rusqlite",
"serde",
"serde_json",
"serde_urlencoded",
diff --git a/crates/ai-memory-cli/src/commands/bootstrap.rs b/crates/ai-memory-cli/src/commands/bootstrap.rs
index 4e7698b5..b81cd820 100644
--- a/crates/ai-memory-cli/src/commands/bootstrap.rs
+++ b/crates/ai-memory-cli/src/commands/bootstrap.rs
@@ -192,6 +192,7 @@ fn local_dry_run(
rationale: "(dry-run; LLM not invoked, no network round-trip)".to_string(),
dry_run: true,
llm_chunks,
+ manifest_warning: None,
}
}
@@ -206,6 +207,9 @@ fn print_human_report(outcome: &BootstrapOutcome, workspace: &str, project: &str
"Bootstrap"
};
println!("\n{kind} complete for {workspace}/{project}\n");
+ if let Some(warning) = &outcome.manifest_warning {
+ eprintln!("ai-memory: warning: {warning}");
+ }
println!("Sources loaded into the LLM:");
let c = &outcome.sources_by_kind;
diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rs
index 7435b935..96bc697c 100644
--- a/crates/ai-memory-cli/src/commands/move_project.rs
+++ b/crates/ai-memory-cli/src/commands/move_project.rs
@@ -73,6 +73,9 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {
let purged = report["source_purged"].as_bool().unwrap_or(false);
let moved_via = report["moved_via"].as_str().unwrap_or("");
let skipped_count = report["pages_skipped"].as_array().map_or(0, |s| s.len());
+ if let Some(warning) = report["manifest_warning"].as_str() {
+ eprintln!("ai-memory: warning: {warning}");
+ }
if (moved_via == "true-move" || purged)
&& let Err(error) = super::project_registry::rekey_scope(
diff --git a/crates/ai-memory-cli/src/commands/move_session.rs b/crates/ai-memory-cli/src/commands/move_session.rs
index 16dee086..ff2b1d08 100644
--- a/crates/ai-memory-cli/src/commands/move_session.rs
+++ b/crates/ai-memory-cli/src/commands/move_session.rs
@@ -66,6 +66,9 @@ pub async fn run(config: &Config, args: MoveSessionArgs) -> Result<()> {
create: args.create,
};
let report: serde_json::Value = post_json(&endpoint, "/admin/move-session", &request).await?;
+ if let Some(warning) = report["manifest_warning"].as_str() {
+ eprintln!("ai-memory: warning: {warning}");
+ }
if request.session_id.is_some() {
print_session_report(&report, args.confirm);
diff --git a/crates/ai-memory-cli/src/commands/rename_project.rs b/crates/ai-memory-cli/src/commands/rename_project.rs
index f98dc24d..be47d4dc 100644
--- a/crates/ai-memory-cli/src/commands/rename_project.rs
+++ b/crates/ai-memory-cli/src/commands/rename_project.rs
@@ -29,6 +29,9 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
});
let summary: serde_json::Value = post_json(&endpoint, "/admin/rename-project", &body).await?;
let pages = summary["pages"].as_u64().unwrap_or(0);
+ if let Some(warning) = summary["manifest_warning"].as_str() {
+ eprintln!("ai-memory: warning: {warning}");
+ }
if let Err(error) = super::project_registry::rekey_scope(
config, &endpoint, &workspace, &from, &workspace, &args.to,
) {
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 5292365f..12b14d7f 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -451,6 +451,9 @@ async fn run_once_with_wiring(
return Err(error);
}
};
+ if let Some(warning) = prepared.manifest_warning.as_deref() {
+ eprintln!("ai-memory: warning: {warning}");
+ }
if let Err(error) = super::project_registry::record_prepared_checkout(
config,
&endpoint,
@@ -2857,6 +2860,50 @@ async fn finish_with_retry(
.context("persisting the managed transcript; the native process has already exited")
}
+struct PrepareRunOutcome {
+ result: Result<PrepareManagedRunResponse>,
+ manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
+}
+
+impl PrepareRunOutcome {
+ fn from_result(result: Result<PrepareManagedRunResponse>) -> Self {
+ let manifest_warning = match &result {
+ Ok(response) => response.manifest_warning.clone(),
+ Err(error) => server_manifest_warning(error),
+ };
+ Self {
+ result,
+ manifest_warning,
+ }
+ }
+
+ fn prefer_warning(
+ mut self,
+ first: Option<ai_memory_core::repository_identity::ManifestWarning>,
+ ) -> Self {
+ self.manifest_warning = first.or(self.manifest_warning);
+ self
+ }
+}
+
+fn complete_prepare_run(
+ outcome: PrepareRunOutcome,
+ output: &mut impl io::Write,
+) -> Result<PrepareManagedRunResponse> {
+ match outcome.result {
+ Ok(mut response) => {
+ response.manifest_warning = outcome.manifest_warning.or(response.manifest_warning);
+ Ok(response)
+ }
+ Err(error) => {
+ if let Some(warning) = outcome.manifest_warning {
+ let _ = writeln!(output, "ai-memory: warning: {warning}");
+ }
+ Err(error)
+ }
+ }
+}
+
async fn prepare_managed_run(
endpoint: &ServerEndpoint,
request: &PrepareManagedRunRequest,
@@ -2864,15 +2911,16 @@ async fn prepare_managed_run(
interrupted: &CancellationToken,
) -> Result<PrepareManagedRunResponse> {
if request.force_unlock {
- return match post_json(endpoint, "/workstream/runs", request).await {
+ let result = match post_json(endpoint, "/workstream/runs", request).await {
Err(error) if is_active_workstream_conflict(&error) => Err(error.context(
"--force-unlock was refused: the active lease belongs to another operator, or \
the server does not support forced lease recovery",
)),
other => other,
};
+ return complete_prepare_run(PrepareRunOutcome::from_result(result), &mut io::stderr());
}
- let result = prepare_managed_run_with_retry(
+ let outcome = prepare_managed_run_with_retry(
endpoint,
request,
PREPARE_BUSY_RETRY_WINDOW,
@@ -2880,22 +2928,22 @@ async fn prepare_managed_run(
true,
)
.await;
- match result {
+ let outcome = if interactive && outcome.result.is_err() {
// Scripts, hooks, and CI keep the short window: they must never hang
// silently for up to a full lease.
- Err(error) if interactive => {
- wait_out_held_lease(
- endpoint,
- request,
- error,
- interrupted,
- HELD_LEASE_EXPIRY_SLACK,
- PREPARE_BUSY_RETRY_WINDOW,
- )
- .await
- }
- other => other,
- }
+ wait_out_held_lease(
+ endpoint,
+ request,
+ outcome,
+ interrupted,
+ HELD_LEASE_EXPIRY_SLACK,
+ PREPARE_BUSY_RETRY_WINDOW,
+ )
+ .await
+ } else {
+ outcome
+ };
+ complete_prepare_run(outcome, &mut io::stderr())
}
/// After the quick retry window, an interactive launch waits out a lease left
@@ -2907,16 +2955,32 @@ async fn prepare_managed_run(
async fn wait_out_held_lease(
endpoint: &ServerEndpoint,
request: &PrepareManagedRunRequest,
- error: anyhow::Error,
+ outcome: PrepareRunOutcome,
interrupted: &CancellationToken,
slack: Duration,
retry_window: Duration,
-) -> Result<PrepareManagedRunResponse> {
+) -> PrepareRunOutcome {
+ let PrepareRunOutcome {
+ result,
+ manifest_warning,
+ } = outcome;
+ let Err(error) = result else {
+ return PrepareRunOutcome {
+ result,
+ manifest_warning,
+ };
+ };
let Some(held) = held_lease(&error) else {
- return Err(error);
+ return PrepareRunOutcome {
+ result: Err(error),
+ manifest_warning,
+ };
};
let Some(wait) = held_lease_wait(held.expires, jiff::Timestamp::now(), slack) else {
- return Err(error);
+ return PrepareRunOutcome {
+ result: Err(error),
+ manifest_warning,
+ };
};
eprintln!(
"ai-memory: the workstream is held by {} until {} — usually a launcher that exited \
@@ -2929,11 +2993,14 @@ async fn wait_out_held_lease(
tokio::select! {
biased;
() = interrupted.cancelled() => {
- return Err(error.context("interrupted while waiting for the workstream lease to lapse"));
+ return PrepareRunOutcome {
+ result: Err(error.context("interrupted while waiting for the workstream lease to lapse")),
+ manifest_warning,
+ };
}
() = tokio::time::sleep(wait) => {}
}
- match prepare_managed_run_with_retry(
+ let retry = prepare_managed_run_with_retry(
endpoint,
request,
retry_window,
@@ -2941,12 +3008,19 @@ async fn wait_out_held_lease(
false,
)
.await
- {
- Err(retry) if held_lease(&retry).is_some() => Err(retry.context(
- "the workstream is still held: its owner renewed the lease, so another launcher \
- is running there; stop it, or pass `--new <name>` for a separate workstream",
- )),
- other => other,
+ .prefer_warning(manifest_warning);
+ match retry.result {
+ Err(error) if held_lease(&error).is_some() => PrepareRunOutcome {
+ result: Err(error.context(
+ "the workstream is still held: its owner renewed the lease, so another launcher \
+ is running there; stop it, or pass `--new <name>` for a separate workstream",
+ )),
+ manifest_warning: retry.manifest_warning,
+ },
+ result => PrepareRunOutcome {
+ result,
+ manifest_warning: retry.manifest_warning,
+ },
}
}
@@ -2990,16 +3064,23 @@ async fn prepare_managed_run_with_retry(
retry_window: Duration,
retry_interval: Duration,
announce_wait: bool,
-) -> Result<PrepareManagedRunResponse> {
+) -> PrepareRunOutcome {
let deadline = tokio::time::Instant::now() + retry_window;
let mut reported_wait = !announce_wait;
+ let mut manifest_warning = None;
loop {
match post_json(endpoint, "/workstream/runs", request).await {
- Ok(response) => return Ok(response),
+ Ok(response) => {
+ return PrepareRunOutcome::from_result(Ok(response))
+ .prefer_warning(manifest_warning);
+ }
Err(error)
if is_active_workstream_conflict(&error)
&& tokio::time::Instant::now() < deadline =>
{
+ if manifest_warning.is_none() {
+ manifest_warning = server_manifest_warning(&error);
+ }
if !reported_wait {
eprintln!(
"ai-memory: another launcher owns this workstream; waiting briefly in case it is finalizing"
@@ -3008,7 +3089,9 @@ async fn prepare_managed_run_with_retry(
}
tokio::time::sleep(retry_interval).await;
}
- Err(error) => return Err(error),
+ Err(error) => {
+ return PrepareRunOutcome::from_result(Err(error)).prefer_warning(manifest_warning);
+ }
}
}
}
@@ -3017,6 +3100,17 @@ fn is_active_workstream_conflict(error: &anyhow::Error) -> bool {
active_workstream_conflict_message(error).is_some()
}
+fn server_manifest_warning(
+ error: &anyhow::Error,
+) -> Option<ai_memory_core::repository_identity::ManifestWarning> {
+ let response = error.downcast_ref::<ServerResponseError>()?;
+ serde_json::from_str::<ai_memory_core::repository_identity::ManifestWarningContext>(
+ response.body(),
+ )
+ .ok()?
+ .manifest_warning
+}
+
fn active_workstream_conflict_message(error: &anyhow::Error) -> Option<String> {
let response = error.downcast_ref::<ServerResponseError>()?;
if response.status() != reqwest::StatusCode::CONFLICT {
@@ -4010,6 +4104,7 @@ mod tests {
sync_after: 0,
sync_through: 0,
may_adopt_existing_session: false,
+ manifest_warning: None,
})
.into_response()
}
@@ -4051,6 +4146,7 @@ mod tests {
true,
)
.await
+ .result
.unwrap();
assert_eq!(prepared.workstream_name, "default");
@@ -4058,6 +4154,156 @@ mod tests {
server.abort();
}
+ #[tokio::test]
+ async fn busy_retry_keeps_first_warning_and_final_error_unchanged() {
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let handler_attempts = Arc::clone(&attempts);
+ let app = Router::new().route(
+ "/workstream/runs",
+ post(move || {
+ let attempt = handler_attempts.fetch_add(1, Ordering::SeqCst);
+ async move {
+ let until = jiff::Timestamp::now() + jiff::SignedDuration::from_secs(60);
+ match attempt {
+ 0 => (
+ StatusCode::CONFLICT,
+ axum::Json(serde_json::json!({
+ "error": format!(
+ "workstream is already active: owned by first until {until}"
+ ),
+ "manifest_warning": "first repair warning"
+ })),
+ )
+ .into_response(),
+ 1 => (
+ StatusCode::CONFLICT,
+ axum::Json(serde_json::json!({
+ "error": format!(
+ "workstream is already active: owned by second until {until}"
+ )
+ })),
+ )
+ .into_response(),
+ _ => (
+ StatusCode::NOT_FOUND,
+ axum::Json(serde_json::json!({
+ "error": "final missing workstream",
+ "manifest_warning": "later repair warning"
+ })),
+ )
+ .into_response(),
+ }
+ }
+ }),
+ );
+ let (endpoint, server) = serve(app).await;
+ let outcome = prepare_managed_run_with_retry(
+ &endpoint,
+ &held_lease_request(),
+ Duration::from_secs(5),
+ Duration::from_millis(1),
+ false,
+ )
+ .await;
+ assert_eq!(attempts.load(Ordering::SeqCst), 3);
+ assert_eq!(
+ outcome.manifest_warning.as_deref(),
+ Some("first repair warning"),
+ "the first warning wins over a later distinct warning"
+ );
+
+ let mut output = Vec::new();
+ let error = complete_prepare_run(outcome, &mut output).expect_err("final 404 is preserved");
+ let response = error.downcast_ref::<ServerResponseError>().unwrap();
+ assert_eq!(response.status(), reqwest::StatusCode::NOT_FOUND);
+ assert!(response.body().contains("final missing workstream"));
+ assert!(response.body().contains("later repair warning"));
+ assert_eq!(
+ String::from_utf8(output).unwrap(),
+ "ai-memory: warning: first repair warning\n"
+ );
+ server.abort();
+ }
+
+ #[tokio::test]
+ async fn busy_retry_returns_first_warning_with_later_success() {
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let handler_attempts = Arc::clone(&attempts);
+ let app = Router::new().route(
+ "/workstream/runs",
+ post(move || {
+ let attempt = handler_attempts.fetch_add(1, Ordering::SeqCst);
+ async move {
+ if attempt == 0 {
+ let until = jiff::Timestamp::now() + jiff::SignedDuration::from_secs(60);
+ return (
+ StatusCode::CONFLICT,
+ axum::Json(serde_json::json!({
+ "error": format!(
+ "workstream is already active: owned by first until {until}"
+ ),
+ "manifest_warning": "first repair warning"
+ })),
+ )
+ .into_response();
+ }
+ axum::Json(PrepareManagedRunResponse {
+ workstream_id: WorkstreamId::new(),
+ workstream_name: "default".into(),
+ run_id: ManagedRunId::new(),
+ resolved_agent: Some(AgentKind::Codex),
+ native_session_id: None,
+ source_cursor: None,
+ sync_after: 0,
+ sync_through: 0,
+ may_adopt_existing_session: false,
+ manifest_warning: None,
+ })
+ .into_response()
+ }
+ }),
+ );
+ let (endpoint, server) = serve(app).await;
+ let outcome = prepare_managed_run_with_retry(
+ &endpoint,
+ &held_lease_request(),
+ Duration::from_secs(5),
+ Duration::from_millis(1),
+ false,
+ )
+ .await;
+ let mut output = Vec::new();
+ let response = complete_prepare_run(outcome, &mut output).unwrap();
+ assert_eq!(attempts.load(Ordering::SeqCst), 2);
+ assert_eq!(
+ response.manifest_warning.as_deref(),
+ Some("first repair warning")
+ );
+ assert!(
+ output.is_empty(),
+ "success returns the warning for one caller print"
+ );
+ server.abort();
+ }
+
+ #[test]
+ fn managed_run_error_extracts_manifest_warning() {
+ let error = crate::http_client::server_response_error_for_test(
+ reqwest::Method::POST,
+ "/workstream/runs",
+ reqwest::StatusCode::NOT_FOUND,
+ serde_json::json!({
+ "error": "managed workstream 'missing' not found",
+ "manifest_warning": "project name promotion committed; repair needed"
+ })
+ .to_string(),
+ );
+ assert_eq!(
+ server_manifest_warning(&error).as_deref(),
+ Some("project name promotion committed; repair needed")
+ );
+ }
+
#[test]
fn held_lease_parses_the_store_busy_message() {
let held = parse_held_lease(
@@ -4129,6 +4375,7 @@ mod tests {
sync_after: 0,
sync_through: 0,
may_adopt_existing_session: false,
+ manifest_warning: None,
})
.into_response()
}
@@ -4179,12 +4426,13 @@ mod tests {
let prepared = wait_out_held_lease(
&endpoint,
&request,
- first,
+ PrepareRunOutcome::from_result(Err(first)),
&CancellationToken::new(),
Duration::ZERO,
Duration::from_millis(50),
)
.await
+ .result
.expect("proceeds once the lease lapsed");
assert_eq!(prepared.workstream_name, "default");
assert!(
@@ -4195,6 +4443,42 @@ mod tests {
server.abort();
}
+ #[tokio::test]
+ async fn wait_out_keeps_the_initial_warning_through_a_successful_retry() {
+ let (app, attempts) = held_lease_server(0, Duration::ZERO);
+ let (endpoint, server) = serve(app).await;
+ let request = held_lease_request();
+ let until = jiff::Timestamp::now() + jiff::SignedDuration::from_millis(10);
+ let first = crate::http_client::server_response_error_for_test(
+ reqwest::Method::POST,
+ "/workstream/runs",
+ reqwest::StatusCode::CONFLICT,
+ serde_json::json!({
+ "error": format!("workstream is already active: owned by first until {until}"),
+ "manifest_warning": "first repair warning"
+ })
+ .to_string(),
+ );
+ let outcome = wait_out_held_lease(
+ &endpoint,
+ &request,
+ PrepareRunOutcome::from_result(Err(first)),
+ &CancellationToken::new(),
+ Duration::ZERO,
+ Duration::from_secs(1),
+ )
+ .await;
+ let mut output = Vec::new();
+ let response = complete_prepare_run(outcome, &mut output).unwrap();
+ assert_eq!(attempts.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ response.manifest_warning.as_deref(),
+ Some("first repair warning")
+ );
+ assert!(output.is_empty());
+ server.abort();
+ }
+
/// Adversarial: a live owner keeps renewing. The waiter must report it, not
/// loop forever and never take the lease.
#[tokio::test]
@@ -4209,12 +4493,13 @@ mod tests {
let error = wait_out_held_lease(
&endpoint,
&request,
- first,
+ PrepareRunOutcome::from_result(Err(first)),
&CancellationToken::new(),
Duration::ZERO,
Duration::from_millis(50),
)
.await
+ .result
.expect_err("a renewing owner is never displaced");
assert!(
format!("{error:#}").contains("renewed the lease"),
@@ -4259,12 +4544,13 @@ mod tests {
let error = wait_out_held_lease(
&endpoint,
&request,
- first,
+ PrepareRunOutcome::from_result(Err(first)),
&interrupted,
Duration::ZERO,
Duration::from_millis(50),
)
.await
+ .result
.expect_err("interrupted");
assert!(started.elapsed() < Duration::from_secs(5));
assert!(format!("{error:#}").contains("interrupted"), "{error:#}");
@@ -5038,6 +5324,7 @@ mod tests {
sync_after: 0,
sync_through: 0,
may_adopt_existing_session: false,
+ manifest_warning: None,
})
}),
)
@@ -5166,6 +5453,7 @@ mod tests {
sync_after: 0,
sync_through: 0,
may_adopt_existing_session: false,
+ manifest_warning: None,
})
}),
)
@@ -5867,6 +6155,7 @@ mod tests {
sync_after: 0,
sync_through: 0,
may_adopt_existing_session: false,
+ manifest_warning: None,
})
}),
)
@@ -6012,6 +6301,7 @@ mod tests {
sync_after: 0,
sync_through: 0,
may_adopt_existing_session: false,
+ manifest_warning: None,
})
}),
)
@@ -6062,6 +6352,7 @@ mod tests {
sync_after: 0,
sync_through: 0,
may_adopt_existing_session: false,
+ manifest_warning: None,
})
}),
)
@@ -7204,6 +7495,7 @@ mod tests {
sync_after: 0,
sync_through: 0,
may_adopt_existing_session: false,
+ manifest_warning: None,
})
}),
)
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 2aa468c6..76bd4f72 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -1527,6 +1527,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
writer: store.writer.clone(),
reader: store.reader.clone(),
sanitizer: sanitizer.clone(),
+ wiki: wiki.clone(),
data_dir: config.data_dir.clone(),
trusted_proxy_identity: trusted_proxy_identity_enabled(&config.auth),
});
@@ -4059,7 +4060,7 @@ mod tests {
.await
.unwrap();
assert_eq!(
- written.as_tuple(),
+ written.scope.as_tuple(),
(workspace_id, scratch),
"the seed must not retarget unscoped writes"
);
diff --git a/crates/ai-memory-cli/src/commands/write_page.rs b/crates/ai-memory-cli/src/commands/write_page.rs
index cf02a0b1..4a01b9c1 100644
--- a/crates/ai-memory-cli/src/commands/write_page.rs
+++ b/crates/ai-memory-cli/src/commands/write_page.rs
@@ -32,6 +32,8 @@ struct WritePageBody {
struct WritePageResponseBody {
page_id: String,
path: String,
+ #[serde(default)]
+ manifest_warning: Option<String>,
}
/// Run the `write-page` subcommand.
@@ -75,6 +77,9 @@ pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {
.await
.context("writing page via server")?;
+ if let Some(warning) = resp.manifest_warning.as_deref() {
+ eprintln!("ai-memory: warning: {warning}");
+ }
let short_id = &resp.page_id[..resp.page_id.len().min(8)];
println!(
"✓ wrote {} (page_id={}) under {}/{}",
diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rs
index 539c6e53..cf8a8796 100644
--- a/crates/ai-memory-cli/src/http_client.rs
+++ b/crates/ai-memory-cli/src/http_client.rs
@@ -71,6 +71,22 @@ fn server_response_error(
.into()
}
+#[cfg(test)]
+pub(crate) fn server_response_error_for_test(
+ method: reqwest::Method,
+ path: &str,
+ status: reqwest::StatusCode,
+ body: String,
+) -> anyhow::Error {
+ ServerResponseError {
+ method,
+ path: path.to_owned(),
+ status,
+ body,
+ }
+ .into()
+}
+
/// Pass a 2xx response through, else consume the body into a
/// [`ServerResponseError`].
///
diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rs
index 53aa0f77..6e096e19 100644
--- a/crates/ai-memory-consolidate/src/bootstrap.rs
+++ b/crates/ai-memory-consolidate/src/bootstrap.rs
@@ -252,6 +252,9 @@ pub struct BootstrapOutcome {
/// Number of LLM calls made (1 when chunking is off or unnecessary).
#[serde(default)]
pub llm_chunks: usize,
+ /// Non-fatal scope-manifest repair warning supplied by the admin transport.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub manifest_warning: Option<String>,
}
/// Bootstrap configuration. Built by the CLI from `BootstrapArgs`
@@ -456,6 +459,7 @@ impl Bootstrap {
pages_written: Vec::new(),
rationale: "(dry-run; LLM not invoked)".to_string(),
dry_run: true,
+ manifest_warning: None,
llm_chunks: plan_bootstrap_chunks(kept.clone(), chunk_budget).len(),
});
}
@@ -664,6 +668,7 @@ impl Bootstrap {
rationale,
dry_run: false,
llm_chunks,
+ manifest_warning: None,
})
}
diff --git a/crates/ai-memory-core/src/repository_identity.rs b/crates/ai-memory-core/src/repository_identity.rs
index 6a85cf28..256c64fa 100644
--- a/crates/ai-memory-core/src/repository_identity.rs
+++ b/crates/ai-memory-core/src/repository_identity.rs
@@ -156,6 +156,87 @@ pub struct RepositoryIdentity {
pub source: IdentitySource,
}
+/// Backward-compatible project scope metadata stored in `_meta.md`.
+///
+/// Identity and source are optional together for manifests created before
+/// identity-aware reindex. Canonical and legacy names are persisted as
+/// consistency assertions and recomputed from the accepted identity on import.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ProjectManifest {
+ /// Human-readable project name.
+ pub project: String,
+ /// Optional checkout path used for local routing.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repo_path: Option<String>,
+ /// Full repository identity, including the host for a remote.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub identity: Option<String>,
+ /// Source of the stored repository identity.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub identity_source: Option<IdentitySource>,
+ /// Optional consistency assertion, never an alias.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub canonical_name: Option<String>,
+ /// Optional consistency assertion, never an alias.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub legacy_name: Option<String>,
+}
+
+/// Operator-visible warning for a committed project-name promotion whose
+/// derived wiki manifest still needs repair.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct ManifestWarning(String);
+
+impl ManifestWarning {
+ /// Build the warning emitted when the SQL promotion committed but the
+ /// `_meta.md` refresh/checkpoint failed.
+ pub fn promotion_refresh_failed(error: impl std::fmt::Display) -> Self {
+ Self(format!(
+ "project name promotion committed, but _meta.md refresh/checkpoint failed and needs startup repair: {error}"
+ ))
+ }
+
+ /// Build the warning emitted when no wiki handle is available to refresh
+ /// the promoted scope.
+ #[must_use]
+ pub fn wiki_unavailable() -> Self {
+ Self(
+ "project name promotion committed; wiki handle unavailable, so _meta.md needs startup repair"
+ .to_owned(),
+ )
+ }
+
+ /// Borrow the stable wire message.
+ #[must_use]
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl std::fmt::Display for ManifestWarning {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(&self.0)
+ }
+}
+
+impl std::ops::Deref for ManifestWarning {
+ type Target = str;
+
+ fn deref(&self) -> &Self::Target {
+ self.as_str()
+ }
+}
+
+/// Stable transport context for an operation that may follow a committed
+/// project-name promotion.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ManifestWarningContext {
+ /// Repair warning when promotion committed before the operation failed.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub manifest_warning: Option<ManifestWarning>,
+}
+
/// Everything the chain needs, gathered by the caller.
///
/// Taking these as data rather than reading git and the filesystem here keeps
@@ -291,6 +372,23 @@ pub fn path_style_name(identity: &RepositoryIdentity) -> Option<String> {
Some(project_name_from(&joined.join("-")))
}
+/// The v2 basename key for a stored git-remote identity.
+///
+/// Before path-style naming, a checkout commonly created its project from the
+/// repository folder (`github.com/acme/api` → `api`). Dual-key lookup keeps
+/// that key readable after an in-place promotion to [`path_style_name`].
+#[must_use]
+pub fn legacy_basename_name(identity: &RepositoryIdentity) -> Option<String> {
+ if identity.source != IdentitySource::GitRemote {
+ return None;
+ }
+ identity
+ .identity
+ .rsplit('/')
+ .find(|segment| !segment.is_empty())
+ .map(project_name_from)
+}
+
/// Characters a project name cannot carry become `-`, runs collapse, and the
/// ends are trimmed; an empty result is `repository`.
fn project_name_from(raw: &str) -> String {
@@ -841,6 +939,22 @@ mod tests {
}
}
+ #[test]
+ fn legacy_basename_is_derived_only_from_remote_identities() {
+ let remote = RepositoryIdentity {
+ identity: "github.com/acme/group/api".into(),
+ source: IdentitySource::GitRemote,
+ };
+ assert_eq!(legacy_basename_name(&remote).as_deref(), Some("api"));
+ assert_eq!(
+ legacy_basename_name(&RepositoryIdentity {
+ identity: "acme/platform".into(),
+ source: IdentitySource::Explicit,
+ }),
+ None
+ );
+ }
+
/// The marker spellings every client forwards: only `path` asks for
/// anything, so a client sends `identity_style=path` exactly when the
/// fixture's `style` is `path`.
diff --git a/crates/ai-memory-core/src/workstream.rs b/crates/ai-memory-core/src/workstream.rs
index 9c63ef2d..3ba736b8 100644
--- a/crates/ai-memory-core/src/workstream.rs
+++ b/crates/ai-memory-core/src/workstream.rs
@@ -288,6 +288,9 @@ pub struct PrepareManagedRunResponse {
/// session. Old servers omit this field, which safely defaults to fresh.
#[serde(default)]
pub may_adopt_existing_session: bool,
+ /// Warning when project-name promotion committed but its wiki manifest did not refresh.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub manifest_warning: Option<crate::repository_identity::ManifestWarning>,
}
/// One-time startup context for harnesses without a SessionStart hook.
@@ -530,6 +533,7 @@ mod tests {
assert!(!response.may_adopt_existing_session);
assert!(response.resolved_agent.is_none());
+ assert!(response.manifest_warning.is_none());
}
#[test]
diff --git a/crates/ai-memory-hooks/Cargo.toml b/crates/ai-memory-hooks/Cargo.toml
index a460025f..4437f17e 100644
--- a/crates/ai-memory-hooks/Cargo.toml
+++ b/crates/ai-memory-hooks/Cargo.toml
@@ -35,6 +35,7 @@ tempfile.workspace = true
git2.workspace = true
ai-memory-llm.workspace = true
async-trait.workspace = true
+rusqlite.workspace = true
[lints]
workspace = true
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index 4b0750a4..3eefa347 100644
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@ -18,6 +18,7 @@ use ai_memory_store::{
StoreError, WorkstreamSelection, WorkstreamSelector, WriterHandle,
create_explicit_scope_guarded, lookup_existing_scope_guarded,
};
+use ai_memory_wiki::Wiki;
use axum::extract::{Path as AxumPath, Query, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
@@ -43,6 +44,8 @@ pub struct WorkstreamState {
pub reader: ReaderPool,
/// Privacy scrubber applied before raw or indexed persistence.
pub sanitizer: Sanitizer,
+ /// Wiki handle for refreshing a scope manifest after name promotion.
+ pub wiki: Wiki,
/// ai-memory data root containing `raw/workstreams`.
pub data_dir: PathBuf,
/// Whether a trusted proxy can distinguish operators without DB users.
@@ -89,15 +92,28 @@ pub fn workstream_router(state: WorkstreamState) -> Router {
#[derive(Debug, Serialize)]
struct ApiError {
error: String,
+ #[serde(flatten)]
+ warning: ai_memory_core::repository_identity::ManifestWarningContext,
}
type ApiFailure = (StatusCode, Json<ApiError>);
fn api_failure(status: StatusCode, message: impl Into<String>) -> ApiFailure {
+ api_failure_with_manifest_warning(status, message, None)
+}
+
+fn api_failure_with_manifest_warning(
+ status: StatusCode,
+ message: impl Into<String>,
+ manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
+) -> ApiFailure {
(
status,
Json(ApiError {
error: message.into(),
+ warning: ai_memory_core::repository_identity::ManifestWarningContext {
+ manifest_warning,
+ },
}),
)
}
@@ -281,7 +297,21 @@ async fn prepare_run(
return error(StatusCode::BAD_REQUEST, format!("{label} is too long"));
}
}
- let scope = match create_explicit_scope_guarded(
+ let selection = match (&request.workstream, &request.new_workstream) {
+ (Some(name), None) => WorkstreamSelection::Named(name.trim().to_string()),
+ (None, Some(name)) => WorkstreamSelection::New(name.trim().to_string()),
+ (None, None) => WorkstreamSelection::Current,
+ (Some(_), Some(_)) => {
+ return error(
+ StatusCode::BAD_REQUEST,
+ "workstream and new_workstream are mutually exclusive",
+ );
+ }
+ };
+ if let Err(failure) = selection.validate() {
+ return store_error_response(failure);
+ }
+ let resolved_scope = match create_explicit_scope_guarded(
&state.reader,
&state.writer,
request.workspace.trim(),
@@ -296,17 +326,34 @@ async fn prepare_run(
}
Err(failure) => return error(StatusCode::BAD_REQUEST, failure.to_string()),
};
- let selection = match (request.workstream, request.new_workstream) {
- (Some(name), None) => WorkstreamSelection::Named(name.trim().to_string()),
- (None, Some(name)) => WorkstreamSelection::New(name.trim().to_string()),
- (None, None) => WorkstreamSelection::Current,
- (Some(_), Some(_)) => {
- return error(
- StatusCode::BAD_REQUEST,
- "workstream and new_workstream are mutually exclusive",
- );
+ let manifest_warning = if resolved_scope.promoted_from.is_some() {
+ match state
+ .wiki
+ .refresh_renamed_scope(
+ resolved_scope.scope.workspace_id,
+ resolved_scope.scope.project_id,
+ )
+ .await
+ {
+ Ok(_) => None,
+ Err(failure) => {
+ warn!(
+ error = %failure,
+ workspace_id = %resolved_scope.scope.workspace_id,
+ project_id = %resolved_scope.scope.project_id,
+ "project name promotion committed; manifest refresh/checkpoint failed; startup backfill can repair"
+ );
+ Some(
+ ai_memory_core::repository_identity::ManifestWarning::promotion_refresh_failed(
+ failure,
+ ),
+ )
+ }
}
+ } else {
+ None
};
+ let scope = resolved_scope.scope;
let identity = actor.and_then(|Extension(actor)| actor.identity_key());
let owner_user = match managed_run_owner_stamp(
&state.reader,
@@ -316,7 +363,14 @@ async fn prepare_run(
.await
{
Ok(owner) => owner,
- Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),
+ Err(failure) => {
+ return api_failure_with_manifest_warning(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ failure.to_string(),
+ manifest_warning,
+ )
+ .into_response();
+ }
};
let force_unlock = request.force_unlock;
let prepared = state
@@ -349,9 +403,10 @@ async fn prepare_run(
sync_after: prepared.sync_after,
sync_through: prepared.sync_through,
may_adopt_existing_session: prepared.may_adopt_existing_session,
+ manifest_warning,
})
.into_response(),
- Err(failure) => store_error_response(failure),
+ Err(failure) => store_error_response_with_manifest_warning(failure, manifest_warning),
}
}
@@ -990,6 +1045,13 @@ fn parse_run_id(raw: &str) -> Result<ManagedRunId, ApiFailure> {
}
fn store_error_response(failure: StoreError) -> Response {
+ store_error_response_with_manifest_warning(failure, None)
+}
+
+fn store_error_response_with_manifest_warning(
+ failure: StoreError,
+ manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
+) -> Response {
let status = match failure {
StoreError::Forbidden(_) => StatusCode::FORBIDDEN,
StoreError::WorkstreamBusy(_)
@@ -999,7 +1061,7 @@ fn store_error_response(failure: StoreError) -> Response {
StoreError::InvalidState(_) => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
- error(status, failure.to_string())
+ api_failure_with_manifest_warning(status, failure.to_string(), manifest_warning).into_response()
}
fn sanitize_events(
@@ -1187,6 +1249,9 @@ mod tests {
writer: store.writer.clone(),
reader: store.reader.clone(),
sanitizer: Sanitizer::default(),
+ wiki: Wiki::new(data_dir, store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone()),
data_dir: data_dir.to_path_buf(),
trusted_proxy_identity: false,
finish_barrier: None,
@@ -1227,6 +1292,452 @@ mod tests {
(workspace_id, project_id)
}
+ #[tokio::test]
+ async fn managed_run_promotion_refreshes_the_scope_manifest() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+ let workspace_id = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let (project_id, _) = store
+ .writer
+ .resolve_project_by_identity(
+ workspace_id,
+ ai_memory_core::repository_identity::RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,
+ },
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ state.wiki.backfill_scope_manifests().await.unwrap();
+ state.wiki.commit_all("fixture baseline").unwrap();
+ let reader = store
+ .writer
+ .create_user(
+ ai_memory_core::NewUser {
+ username: "promotion-reader".into(),
+ name: None,
+ email: None,
+ },
+ [7; ai_memory_store::TOKEN_HASH_LEN],
+ )
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(project_id, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(reader, project_id, ai_memory_store::GrantLevel::Read, None)
+ .await
+ .unwrap();
+ let request = || PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "acme-api".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: None,
+ new_workstream: None,
+ force_unlock: false,
+ lease_owner: "launcher".into(),
+ };
+ let refused = prepare_run(
+ State(state.clone()),
+ Some(Extension(AuthLevel::User)),
+ None,
+ Some(Extension(ai_memory_core::AuthorizedViewer(reader))),
+ Json(request()),
+ )
+ .await;
+ assert_eq!(refused.status(), StatusCode::FORBIDDEN);
+ assert_eq!(
+ store
+ .reader
+ .project_name_by_id(workspace_id, project_id)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("api")
+ );
+ let manifest_path = temp
+ .path()
+ .join("wiki")
+ .join(workspace_id.to_string())
+ .join(project_id.to_string())
+ .join("_meta.md");
+ assert!(
+ std::fs::read_to_string(&manifest_path)
+ .unwrap()
+ .contains("project: api")
+ );
+ let response = prepare_run(
+ State(state.clone()),
+ Some(Extension(AuthLevel::Root)),
+ None,
+ None,
+ Json(request()),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
+ let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();
+ assert!(prepared.manifest_warning.is_none());
+ assert_eq!(
+ store
+ .reader
+ .project_name_by_id(workspace_id, project_id)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("acme-api")
+ );
+ let manifest = std::fs::read_to_string(
+ temp.path()
+ .join("wiki")
+ .join(workspace_id.to_string())
+ .join(project_id.to_string())
+ .join("_meta.md"),
+ )
+ .unwrap();
+ assert!(manifest.contains("project: acme-api"), "{manifest}");
+ }
+
+ #[tokio::test]
+ async fn managed_run_rejects_mutually_exclusive_selection_before_promotion() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+ let workspace_id = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let (project_id, _) = store
+ .writer
+ .resolve_project_by_identity(
+ workspace_id,
+ ai_memory_core::repository_identity::RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,
+ },
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let response = prepare_run(
+ State(state),
+ None,
+ None,
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "acme-api".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: Some("existing".into()),
+ new_workstream: Some("new".into()),
+ force_unlock: false,
+ lease_owner: "launcher".into(),
+ }),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ store
+ .reader
+ .project_name_by_id(workspace_id, project_id)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("api")
+ );
+ }
+
+ #[tokio::test]
+ async fn managed_run_discloses_manifest_failure_after_committed_promotion() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+ let workspace_id = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let (project_id, _) = store
+ .writer
+ .resolve_project_by_identity(
+ workspace_id,
+ ai_memory_core::repository_identity::RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,
+ },
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ state.wiki.backfill_scope_manifests().await.unwrap();
+ let manifest = temp
+ .path()
+ .join("wiki")
+ .join(workspace_id.to_string())
+ .join(project_id.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+
+ let response = prepare_run(
+ State(state),
+ None,
+ None,
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "acme-api".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: None,
+ new_workstream: None,
+ force_unlock: false,
+ lease_owner: "launcher".into(),
+ }),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
+ let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();
+ assert!(
+ prepared
+ .manifest_warning
+ .as_deref()
+ .is_some_and(|warning| warning.contains("committed"))
+ );
+ assert_eq!(
+ store
+ .reader
+ .project_name_by_id(workspace_id, project_id)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("acme-api")
+ );
+ assert!(manifest.is_dir());
+ std::fs::remove_dir(&manifest).unwrap();
+ let restarted = Wiki::new(temp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
+ assert_eq!(restarted.backfill_scope_manifests().await.unwrap(), 1);
+ assert!(
+ std::fs::read_to_string(&manifest)
+ .unwrap()
+ .contains("project: acme-api")
+ );
+ assert_eq!(restarted.backfill_scope_manifests().await.unwrap(), 0);
+ }
+
+ #[tokio::test]
+ async fn managed_run_store_failure_after_promotion_preserves_manifest_warning() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+ let workspace_id = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let (project_id, _) = store
+ .writer
+ .resolve_project_by_identity(
+ workspace_id,
+ ai_memory_core::repository_identity::RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,
+ },
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ state.wiki.backfill_scope_manifests().await.unwrap();
+ let manifest = temp
+ .path()
+ .join("wiki")
+ .join(workspace_id.to_string())
+ .join(project_id.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
+ conn.execute_batch(
+ "CREATE TRIGGER fail_managed_run_insert BEFORE INSERT ON managed_runs \
+ BEGIN SELECT RAISE(ABORT, 'injected managed-run failure'); END;",
+ )
+ .unwrap();
+
+ let response = prepare_run(
+ State(state),
+ None,
+ None,
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "acme-api".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: None,
+ new_workstream: None,
+ force_unlock: false,
+ lease_owner: "launcher".into(),
+ }),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert!(
+ body["error"]
+ .as_str()
+ .is_some_and(|error| error.contains("injected managed-run failure")),
+ "{body}"
+ );
+ assert!(
+ body["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("promotion committed")),
+ "{body}"
+ );
+ assert_eq!(
+ store
+ .reader
+ .project_name_by_id(workspace_id, project_id)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("acme-api")
+ );
+ }
+
+ #[tokio::test]
+ async fn managed_run_downstream_failure_after_promotion_preserves_manifest_warning() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+ let workspace_id = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let (project_id, _) = store
+ .writer
+ .resolve_project_by_identity(
+ workspace_id,
+ ai_memory_core::repository_identity::RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,
+ },
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ state.wiki.backfill_scope_manifests().await.unwrap();
+ let manifest = temp
+ .path()
+ .join("wiki")
+ .join(workspace_id.to_string())
+ .join(project_id.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+
+ let response = prepare_run(
+ State(state),
+ None,
+ None,
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "acme-api".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: Some("missing".into()),
+ new_workstream: None,
+ force_unlock: false,
+ lease_owner: "launcher".into(),
+ }),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::NOT_FOUND);
+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert!(
+ body["error"]
+ .as_str()
+ .is_some_and(|error| error.contains("managed workstream 'missing'")),
+ "{body}"
+ );
+ assert!(
+ body["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("promotion committed")),
+ "{body}"
+ );
+ assert_eq!(
+ store
+ .reader
+ .project_name_by_id(workspace_id, project_id)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("acme-api")
+ );
+ }
+
#[tokio::test]
async fn workstream_provenance_finish_scrubs_before_raw_segment_and_search() {
let temp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 388723a3..d30cbce2 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -72,8 +72,7 @@ use ai_memory_store::{
ApproveAutoImproveProposalResult, AuditLogFilter, AutoImproveProposalOperation,
AutoImproveProposalStatus, DecayParams, NewAutoImproveProposal, PagesMode, ReaderPool,
RejectAutoImproveProposal, ScopeResolutionError, SkippedProposal, StageAutoImproveRun,
- StoreError, WriterHandle, create_explicit_scope, f32_vec_to_bytes, lookup_existing_scope,
- lookup_existing_workspace,
+ StoreError, WriterHandle, f32_vec_to_bytes, lookup_existing_scope, lookup_existing_workspace,
};
use ai_memory_wiki::{
AdmissionContext, AdmissionOp, Markdown, SessionPageFile, Wiki, WikiError, WritePageRequest,
@@ -1851,15 +1850,51 @@ const OPERATOR: Option<ai_memory_core::UserId> = None;
/// Resolve workspace + project IDs, creating them if absent. Returns
/// either the IDs or a ready-to-return error response.
+struct AdminWriteScope {
+ scope: ai_memory_store::ResolvedScope,
+ manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
+}
+
async fn create_ws_proj(
state: &AdminState,
workspace: &str,
project: &str,
-) -> Result<(WorkspaceId, ProjectId), (StatusCode, Json<serde_json::Value>)> {
- create_explicit_scope(&state.writer, workspace, project)
+) -> Result<AdminWriteScope, (StatusCode, Json<serde_json::Value>)> {
+ let resolved = ai_memory_store::create_explicit_scope(&state.writer, workspace, project)
.await
- .map(ai_memory_store::ResolvedScope::as_tuple)
- .map_err(scope_err)
+ .map_err(scope_err)?;
+ let manifest_warning = refresh_promoted_scope(state, &resolved).await;
+ Ok(AdminWriteScope {
+ scope: resolved.scope,
+ manifest_warning,
+ })
+}
+
+async fn refresh_promoted_scope(
+ state: &AdminState,
+ resolved: &ai_memory_store::ResolvedWriteScope,
+) -> Option<ai_memory_core::repository_identity::ManifestWarning> {
+ resolved.promoted_from.as_ref()?;
+ match state
+ .wiki
+ .refresh_renamed_scope(resolved.scope.workspace_id, resolved.scope.project_id)
+ .await
+ {
+ Ok(_) => None,
+ Err(error) => {
+ warn!(
+ error = %error,
+ workspace_id = %resolved.scope.workspace_id,
+ project_id = %resolved.scope.project_id,
+ "project name promotion committed; manifest refresh/checkpoint failed; startup backfill can repair"
+ );
+ Some(
+ ai_memory_core::repository_identity::ManifestWarning::promotion_refresh_failed(
+ error,
+ ),
+ )
+ }
+ }
}
/// Look up workspace + project by name **without** auto-creating them.
@@ -1887,6 +1922,16 @@ async fn lookup_ws_no_create(
.map_err(scope_err)
}
+fn with_manifest_warning(
+ (status, Json(mut body)): (StatusCode, Json<serde_json::Value>),
+ warning: Option<&ai_memory_core::repository_identity::ManifestWarning>,
+) -> (StatusCode, Json<serde_json::Value>) {
+ if let (Some(warning), Some(object)) = (warning, body.as_object_mut()) {
+ object.insert("manifest_warning".into(), serde_json::json!(warning));
+ }
+ (status, Json(body))
+}
+
fn scope_err(err: ScopeResolutionError) -> (StatusCode, Json<serde_json::Value>) {
let status = if err.is_bad_request() {
StatusCode::BAD_REQUEST
@@ -1951,7 +1996,8 @@ async fn handle_bootstrap(
})),
));
}
- let (ws, proj) = create_ws_proj(&state, &req.workspace, &req.project).await?;
+ let target = create_ws_proj(&state, &req.workspace, &req.project).await?;
+ let (ws, proj) = target.scope.as_tuple();
// Serialise live bootstrap runs. Two parallel `process_sources`
// calls would race the wiki's `commit_all` (libgit2 ops on the
@@ -2002,11 +2048,17 @@ async fn handle_bootstrap(
};
match bootstrap.process_sources(&cfg, req.sources).await {
- Ok(outcome) => Ok((
- StatusCode::OK,
- Json(serde_json::to_value(&outcome).unwrap_or_else(|_| serde_json::json!({}))),
+ Ok(mut outcome) => {
+ outcome.manifest_warning = target.manifest_warning.map(|warning| warning.to_string());
+ Ok((
+ StatusCode::OK,
+ Json(serde_json::to_value(&outcome).unwrap_or_else(|_| serde_json::json!({}))),
+ ))
+ }
+ Err(e) => Err(with_manifest_warning(
+ bootstrap_error_response(e),
+ target.manifest_warning.as_ref(),
)),
- Err(e) => Err(bootstrap_error_response(e)),
}
}
@@ -2090,6 +2142,7 @@ fn dry_run_outcome(
rationale: "(dry-run; LLM not invoked)".to_string(),
dry_run: true,
llm_chunks,
+ manifest_warning: None,
};
Ok((
StatusCode::OK,
@@ -5601,6 +5654,9 @@ pub struct RenameProjectSummary {
/// Post-rename checkpoint, if `_meta.md` changed.
#[serde(skip_serializing_if = "Option::is_none")]
pub checkpoint: Option<String>,
+ /// Non-fatal manifest/checkpoint failure after the database rename committed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub manifest_warning: Option<String>,
}
async fn handle_rename_project(
@@ -5662,23 +5718,29 @@ async fn handle_rename_project(
}
};
+ let (checkpoint, manifest_warning) = match state
+ .wiki
+ .refresh_renamed_scope(ws_id, proj_id)
+ .await
+ {
+ Ok(checkpoint) => (checkpoint, None),
+ Err(error) => {
+ warn!(
+ error = %error,
+ workspace_id = %ws_id,
+ project_id = %proj_id,
+ "rename-project committed; manifest refresh/checkpoint failed; startup backfill can repair"
+ );
+ (None, Some(error.to_string()))
+ }
+ };
let summary = RenameProjectSummary {
workspace: req.workspace.clone(),
from: req.from.clone(),
to: req.to.clone(),
pages,
- checkpoint: {
- if let Err(e) = state.wiki.backfill_scope_manifests().await {
- warn!(error = %e, "rename-project: scope-manifest backfill failed after rename");
- }
- checkpoint_or_warn(
- &state.wiki,
- format!(
- "rename-project {}/{} -> {}",
- req.workspace, req.from, req.to
- ),
- )
- },
+ checkpoint,
+ manifest_warning,
};
(
StatusCode::OK,
@@ -5790,6 +5852,9 @@ pub struct MoveProjectReport {
/// Post-move checkpoint, if the move changed the tree.
#[serde(skip_serializing_if = "Option::is_none")]
pub checkpoint: Option<String>,
+ /// Non-fatal manifest/checkpoint failure after destination promotion committed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
}
/// One same-path collision resolved by de-duplicating the source page's path.
@@ -5928,6 +5993,7 @@ async fn true_move_project(
conflicts: Vec::new(),
pre_checkpoint,
checkpoint,
+ manifest_warning: None,
};
Ok(report)
}
@@ -6164,14 +6230,12 @@ async fn move_project_core(
// Detect MERGE: does the destination workspace already hold a same-named
// project? (find_workspace may be None when the dest ws doesn't exist yet.)
- let merged_into_existing = match state.reader.find_workspace(req.to_workspace.clone()).await {
- Ok(Some(dst_ws)) => matches!(
- state.reader.find_project(dst_ws, req.project.clone()).await,
- Ok(Some(_))
- ),
- Ok(None) => false,
- Err(e) => return Err(internal_err(e.to_string())),
- };
+ let merged_into_existing =
+ match lookup_existing_scope(&state.reader, &req.to_workspace, &req.project).await {
+ Ok(_) => true,
+ Err(error) if error.is_not_found() => false,
+ Err(error) => return Err(scope_err(error)),
+ };
let pre_checkpoint = checkpoint_or_500(
&state.wiki,
@@ -6196,8 +6260,10 @@ async fn move_project_core(
// MERGE: the destination already holds a same-named project. Get-or-create
// it (auto-creating the destination workspace) and copy the source's
// latest pages into it, then purge the source.
- let (dst_ws, dst_proj) = create_ws_proj(state, &req.to_workspace, &req.project).await?;
+ let destination = create_ws_proj(state, &req.to_workspace, &req.project).await?;
+ let (dst_ws, dst_proj) = destination.scope.as_tuple();
+ let warning = destination.manifest_warning;
copy_purge_merge(
state,
req,
@@ -6207,8 +6273,10 @@ async fn move_project_core(
dst_proj,
pre_checkpoint,
actor,
+ warning.clone(),
)
.await
+ .map_err(|error| with_manifest_warning(error, warning.as_ref()))
}
// ---------------------------------------------------------------------
@@ -6344,6 +6412,9 @@ pub struct MoveSessionReport {
/// Post-move checkpoint, if the move changed the tree.
#[serde(skip_serializing_if = "Option::is_none")]
pub checkpoint: Option<String>,
+ /// Non-fatal manifest/checkpoint failure after destination promotion committed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
}
/// Wire-format report for the batch form of `POST /admin/move-session`.
@@ -6372,6 +6443,9 @@ pub struct MoveSessionBatchReport {
/// Post-move checkpoint, if the batch changed the tree.
#[serde(skip_serializing_if = "Option::is_none")]
pub checkpoint: Option<String>,
+ /// Non-fatal manifest/checkpoint failure after destination promotion committed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
}
/// One session move, resolved and validated, before any guard runs.
@@ -6398,16 +6472,28 @@ impl MoveSessionPlan {
/// The destination of a move: an existing scope, or (dry run with `create`
/// only) a scope that does not exist yet and would be created on confirm.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
enum MoveTarget {
- Existing((WorkspaceId, ProjectId)),
+ Existing {
+ scope: (WorkspaceId, ProjectId),
+ manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
+ },
WouldCreate,
}
impl MoveTarget {
- fn existing(self) -> Option<(WorkspaceId, ProjectId)> {
+ fn existing(&self) -> Option<(WorkspaceId, ProjectId)> {
match self {
- Self::Existing(scope) => Some(scope),
+ Self::Existing { scope, .. } => Some(*scope),
+ Self::WouldCreate => None,
+ }
+ }
+
+ fn manifest_warning(&self) -> Option<ai_memory_core::repository_identity::ManifestWarning> {
+ match self {
+ Self::Existing {
+ manifest_warning, ..
+ } => manifest_warning.clone(),
Self::WouldCreate => None,
}
}
@@ -6480,10 +6566,16 @@ async fn resolve_move_session_target(
if create && confirm {
return create_ws_proj(state, workspace, project)
.await
- .map(MoveTarget::Existing);
+ .map(|target| MoveTarget::Existing {
+ scope: target.scope.as_tuple(),
+ manifest_warning: target.manifest_warning,
+ });
}
match lookup_existing_scope(&state.reader, workspace, project).await {
- Ok(scope) => Ok(MoveTarget::Existing(scope.as_tuple())),
+ Ok(scope) => Ok(MoveTarget::Existing {
+ scope: scope.as_tuple(),
+ manifest_warning: None,
+ }),
Err(e) if create && e.is_not_found() => Ok(MoveTarget::WouldCreate),
Err(e) => Err(scope_err(e)),
}
@@ -6703,8 +6795,9 @@ async fn move_planned_session(
// Dry run with `create` against an absent destination: nothing exists to
// collide with, and the store cannot re-stamp into a scope that has no
// row, so the counts come from a read-only preview.
- let to = match plan.to {
- MoveTarget::Existing(to) => to,
+ let manifest_warning = plan.to.manifest_warning();
+ let to = match &plan.to {
+ MoveTarget::Existing { scope, .. } => *scope,
MoveTarget::WouldCreate => {
debug_assert!(
!req.confirm,
@@ -6728,6 +6821,7 @@ async fn move_planned_session(
cwd_warning,
pre_checkpoint: None,
checkpoint: None,
+ manifest_warning,
});
}
};
@@ -6774,6 +6868,7 @@ async fn move_planned_session(
cwd_warning,
pre_checkpoint: None,
checkpoint: None,
+ manifest_warning: manifest_warning.clone(),
});
}
@@ -6814,6 +6909,7 @@ async fn move_planned_session(
cwd_warning,
pre_checkpoint: None,
checkpoint: None,
+ manifest_warning,
})
}
@@ -6866,8 +6962,12 @@ async fn move_single_session(
plan.to_label.workspace,
plan.to_label.project
);
- let pre_checkpoint = checkpoint_or_500(&state.wiki, format!("pre-{label}"))?;
- let mut report = move_planned_session(state, req, plan, author_id, &actor).await?;
+ let warning = plan.to.manifest_warning();
+ let pre_checkpoint = checkpoint_or_500(&state.wiki, format!("pre-{label}"))
+ .map_err(|error| with_manifest_warning(error, warning.as_ref()))?;
+ let mut report = move_planned_session(state, req, plan, author_id, &actor)
+ .await
+ .map_err(|error| with_manifest_warning(error, warning.as_ref()))?;
if let Err(e) = state.wiki.backfill_scope_manifests().await {
warn!(error = %e, "move-session: scope-manifest backfill failed after move");
}
@@ -6915,33 +7015,43 @@ async fn move_session_batch(
workspace: to_workspace,
project: req.project.clone(),
};
+ let manifest_warning = to.manifest_warning();
if to.existing() == Some(from) {
- return (
- StatusCode::UNPROCESSABLE_ENTITY,
- Json(serde_json::json!({
- "error": "source and destination scopes are identical"
- })),
+ return with_manifest_warning(
+ (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({
+ "error": "source and destination scopes are identical"
+ })),
+ ),
+ manifest_warning.as_ref(),
)
- .into_response();
+ .into_response();
}
// Same guard as move-project: the project the hook router is writing to
// is not emptied out from under it without an explicit `force`.
if !req.force && state.active_project.contains_project(from.1) {
- return (
- StatusCode::CONFLICT,
- Json(serde_json::json!({
- "error": format!(
- "{}/{} is the active session's project; force the move (--force / \
- force: true) to move its sessions anyway",
- from_label.workspace, from_label.project
- )
- })),
+ return with_manifest_warning(
+ (
+ StatusCode::CONFLICT,
+ Json(serde_json::json!({
+ "error": format!(
+ "{}/{} is the active session's project; force the move (--force / \
+ force: true) to move its sessions anyway",
+ from_label.workspace, from_label.project
+ )
+ })),
+ ),
+ manifest_warning.as_ref(),
)
- .into_response();
+ .into_response();
}
let sessions = match list_scope_sessions(&state.reader, from.0, from.1).await {
Ok(v) => v,
- Err(e) => return internal_err(e.to_string()).into_response(),
+ Err(e) => {
+ return with_manifest_warning(internal_err(e.to_string()), manifest_warning.as_ref())
+ .into_response();
+ }
};
let label = format!(
@@ -6951,7 +7061,9 @@ async fn move_session_batch(
let pre_checkpoint = if req.confirm && !sessions.is_empty() {
match checkpoint_or_500(&state.wiki, format!("pre-{label}")) {
Ok(oid) => oid,
- Err(e) => return e.into_response(),
+ Err(e) => {
+ return with_manifest_warning(e, manifest_warning.as_ref()).into_response();
+ }
}
} else {
None
@@ -6979,7 +7091,7 @@ async fn move_session_batch(
session_id,
from: plan_from,
from_label: plan_from_label,
- to,
+ to: to.clone(),
to_label: to_label.clone(),
row_scope,
cwd,
@@ -7017,6 +7129,9 @@ async fn move_session_batch(
if let Some(oid) = checkpoint {
obj.insert("checkpoint".into(), serde_json::json!(oid));
}
+ if let Some(warning) = manifest_warning.clone() {
+ obj.insert("manifest_warning".into(), serde_json::json!(warning));
+ }
}
return (status, Json(body)).into_response();
}
@@ -7030,6 +7145,7 @@ async fn move_session_batch(
sessions: reports,
pre_checkpoint,
checkpoint,
+ manifest_warning,
};
(StatusCode::OK, Json(json_or_empty(&report))).into_response()
}
@@ -7143,6 +7259,7 @@ async fn copy_purge_merge(
dst_proj: ProjectId,
pre_checkpoint: Option<String>,
actor: ai_memory_core::ActorContext,
+ manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
) -> Result<MoveProjectReport, MoveErr> {
// Enumerate the source's latest pages (authoritative on is_latest).
let summaries = match state
@@ -7380,6 +7497,7 @@ async fn copy_purge_merge(
conflicts,
pre_checkpoint,
checkpoint,
+ manifest_warning: manifest_warning.clone(),
};
return Ok(report);
}
@@ -7510,6 +7628,7 @@ async fn copy_purge_merge(
conflicts,
pre_checkpoint,
checkpoint,
+ manifest_warning,
};
Ok(report)
}
@@ -7732,6 +7851,9 @@ struct WritePageResponse {
/// Post-write checkpoint, if the write changed the tree.
#[serde(skip_serializing_if = "Option::is_none")]
checkpoint: Option<String>,
+ /// Non-fatal committed promotion manifest/checkpoint failure.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ manifest_warning: Option<ai_memory_core::repository_identity::ManifestWarning>,
}
async fn handle_write_page(
@@ -7770,7 +7892,9 @@ async fn handle_write_page(
)
})?;
- let (ws, proj) = create_ws_proj(&state, &req.workspace, &req.project).await?;
+ let target = create_ws_proj(&state, &req.workspace, &req.project).await?;
+ let (ws, proj) = target.scope.as_tuple();
+ let manifest_warning = target.manifest_warning;
let mut fm = metadata;
if let Some(title) = &req.title {
@@ -7834,7 +7958,9 @@ async fn handle_write_page(
evidence: Vec::new(),
})
.await
- .map_err(|e| internal_err(e.to_string()))?;
+ .map_err(|e| {
+ with_manifest_warning(internal_err(e.to_string()), manifest_warning.as_ref())
+ })?;
let checkpoint = checkpoint_or_warn(
&state.wiki,
format!(
@@ -7852,6 +7978,7 @@ async fn handle_write_page(
page_id: page_id.to_string(),
path: path.to_string(),
checkpoint,
+ manifest_warning,
})
.unwrap_or_else(|_| serde_json::json!({})),
),
diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rs
index 565108a8..f5763b6e 100644
--- a/crates/ai-memory-mcp/src/auth.rs
+++ b/crates/ai-memory-mcp/src/auth.rs
@@ -1783,6 +1783,9 @@ mod tests {
writer: store.writer.clone(),
reader: store.reader.clone(),
sanitizer: ai_memory_core::Sanitizer::default(),
+ wiki: ai_memory_wiki::Wiki::new(root, store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone()),
data_dir: root.into(),
trusted_proxy_identity: auth.actor_proxy_bearer().is_some(),
})
@@ -1971,6 +1974,9 @@ mod tests {
writer: store.writer.clone(),
reader: store.reader.clone(),
sanitizer: ai_memory_core::Sanitizer::default(),
+ wiki: ai_memory_wiki::Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone()),
data_dir: tmp.path().into(),
trusted_proxy_identity: false,
})
@@ -2428,6 +2434,9 @@ mod tests {
writer: store.writer.clone(),
reader: store.reader.clone(),
sanitizer: ai_memory_core::Sanitizer::default(),
+ wiki: ai_memory_wiki::Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone()),
data_dir: tmp.path().into(),
trusted_proxy_identity: false,
})
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 2ee1e57d..9714e4d1 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -2086,39 +2086,88 @@ impl AiMemoryServer {
/// `workspace`. Falls back to the baked default only when no `ActiveProject`
/// has been published yet (early startup / no hooks).
/// Legacy single-slot wrapper retained for test fixtures that pre-date
- /// the actor-aware variant. Production tools must use
- /// [`Self::write_target_ids_with_actor`] so per-session/per-actor
- /// isolation modes route the write to the caller's project, not
- /// whichever single-slot value was published last.
+ /// the actor-aware variant. Production tools use
+ /// [`Self::resolve_write_target_with_actor`] so promotion metadata cannot
+ /// be discarded before manifest repair.
#[cfg(test)]
async fn write_target_ids(
&self,
explicit_workspace: Option<&str>,
explicit_project: Option<&str>,
) -> Result<(WorkspaceId, ProjectId), McpError> {
- self.write_target_ids_with_actor(
+ self.resolve_write_target_with_actor(
explicit_workspace,
explicit_project,
&ai_memory_core::ActorKey::default(),
None,
)
.await
+ .map(|resolved| resolved.scope.as_tuple())
}
- async fn write_target_ids_with_actor(
+ async fn resolve_write_target_with_actor(
&self,
explicit_workspace: Option<&str>,
explicit_project: Option<&str>,
actor: &ai_memory_core::ActorKey,
viewer: Option<ai_memory_core::UserId>,
- ) -> Result<(WorkspaceId, ProjectId), McpError> {
+ ) -> Result<ai_memory_store::ResolvedWriteScope, McpError> {
self.scope_resolver_as(viewer)
.resolve_write_args(explicit_workspace, explicit_project, actor)
.await
- .map(ai_memory_store::ResolvedScope::as_tuple)
.map_err(Self::scope_error)
}
+ fn with_manifest_warning(
+ mut error: McpError,
+ warning: Option<&ai_memory_core::repository_identity::ManifestWarning>,
+ ) -> McpError {
+ if let Some(warning) = warning {
+ let context = ai_memory_core::repository_identity::ManifestWarningContext {
+ manifest_warning: Some(warning.clone()),
+ };
+ let mut data = error
+ .data
+ .take()
+ .and_then(|value| value.as_object().cloned())
+ .unwrap_or_default();
+ if let Ok(serde_json::Value::Object(context)) = serde_json::to_value(context) {
+ data.extend(context);
+ }
+ error.data = Some(serde_json::Value::Object(data));
+ }
+ error
+ }
+
+ async fn refresh_promoted_scope(
+ &self,
+ resolved: &ai_memory_store::ResolvedWriteScope,
+ ) -> Option<ai_memory_core::repository_identity::ManifestWarning> {
+ resolved.promoted_from.as_ref()?;
+ let Some(wiki) = self.wiki.as_ref() else {
+ return Some(ai_memory_core::repository_identity::ManifestWarning::wiki_unavailable());
+ };
+ match wiki
+ .refresh_renamed_scope(resolved.scope.workspace_id, resolved.scope.project_id)
+ .await
+ {
+ Ok(_) => None,
+ Err(error) => {
+ tracing::warn!(
+ error = %error,
+ workspace_id = %resolved.scope.workspace_id,
+ project_id = %resolved.scope.project_id,
+ "project name promotion committed; manifest refresh/checkpoint failed; startup backfill can repair"
+ );
+ Some(
+ ai_memory_core::repository_identity::ManifestWarning::promotion_refresh_failed(
+ error,
+ ),
+ )
+ }
+ }
+ }
+
async fn resolve_query_scopes(
&self,
scopes: &[MemoryScopeArg],
@@ -4256,15 +4305,27 @@ impl AiMemoryServer {
let tier: Tier = tier_name
.parse()
.map_err(|_| McpError::internal_error(format!("unknown tier '{tier_name}'"), None))?;
+ if let Some(expires_at) = args
+ .expires_at
+ .as_deref()
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ && ai_memory_core::parse_expires_at_instant(expires_at).is_none()
+ {
+ return Err(McpError::invalid_params(
+ format!("invalid expires_at (want RFC3339 or YYYY-MM-DD): {expires_at}"),
+ None,
+ ));
+ }
if session_id.is_some() && args.scope.as_deref().is_some_and(|s| !s.trim().is_empty()) {
return Err(McpError::invalid_params(
"session_id cannot be combined with scope; a session belongs to one project",
None,
));
}
- let (ws, proj) = match args.scope.as_deref().map(str::trim) {
+ let resolved_scope = match args.scope.as_deref().map(str::trim) {
None | Some("") => {
- self.write_target_ids_with_actor(
+ self.resolve_write_target_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
@@ -4289,7 +4350,7 @@ impl AiMemoryServer {
}
// The same resolver and choke point as an explicit
// `default/_global` write, so both spellings are gated alike.
- self.write_target_ids_with_actor(
+ self.resolve_write_target_with_actor(
Some(ai_memory_core::DEFAULT_WORKSPACE_NAME),
Some(ai_memory_core::GLOBAL_SCOPE_PROJECT),
&aps_actor,
@@ -4312,7 +4373,15 @@ impl AiMemoryServer {
None,
));
}
- self.profile_target_ids(&parts, &aps_actor, true).await?
+ let (workspace_id, project_id) =
+ self.profile_target_ids(&parts, &aps_actor, true).await?;
+ ai_memory_store::ResolvedWriteScope {
+ scope: ai_memory_store::ResolvedScope {
+ workspace_id,
+ project_id,
+ },
+ promoted_from: None,
+ }
}
Some(other) => {
return Err(McpError::internal_error(
@@ -4323,9 +4392,14 @@ impl AiMemoryServer {
));
}
};
+ let (ws, proj) = resolved_scope.scope.as_tuple();
+ let manifest_warning = self.refresh_promoted_scope(&resolved_scope).await;
if let Some(session_id) = session_id {
- self.require_session_in_scope(session_id, ws, proj).await?;
- Self::refuse_pinned_page_overwrite(wiki, ws, proj, &path)?;
+ self.require_session_in_scope(session_id, ws, proj)
+ .await
+ .map_err(|error| Self::with_manifest_warning(error, manifest_warning.as_ref()))?;
+ Self::refuse_pinned_page_overwrite(wiki, ws, proj, &path)
+ .map_err(|error| Self::with_manifest_warning(error, manifest_warning.as_ref()))?;
}
let mut fm = metadata;
@@ -4367,7 +4441,9 @@ impl AiMemoryServer {
let mut body = args.body;
let mut title = args.title;
if let Some(session_id) = session_id.filter(|_| session_page) {
- self.stamp_session_page(&mut fm, session_id).await?;
+ self.stamp_session_page(&mut fm, session_id)
+ .await
+ .map_err(|error| Self::with_manifest_warning(error, manifest_warning.as_ref()))?;
let current =
ai_memory_wiki::derive_title(&serde_json::Value::Object(fm.clone()), &body, &path);
let existing = ai_memory_consolidate::existing_session_page_titles(
@@ -4432,7 +4508,12 @@ impl AiMemoryServer {
.collect(),
})
.await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ .map_err(|e| {
+ Self::with_manifest_warning(
+ McpError::internal_error(e.to_string(), None),
+ manifest_warning.as_ref(),
+ )
+ })?;
let checkpoint = checkpoint_or_warn(wiki, format!("memory_write_page: {}", path.as_str()));
// Only the session page settles the job: evidence on another page
// must not close it while `sessions/<id>.md` is still missing.
@@ -4440,11 +4521,15 @@ impl AiMemoryServer {
self.reconcile_consolidation_job(session_id).await;
}
- ok_json(&serde_json::json!({
+ let mut result = serde_json::json!({
"page_id": page_id.to_string(),
"path": path.to_string(),
"checkpoint": checkpoint
- }))
+ });
+ if let Some(warning) = manifest_warning {
+ result["manifest_warning"] = serde_json::Value::String(warning.to_string());
+ }
+ ok_json(&result)
}
/// Fetch the full body of a single wiki page.
@@ -5001,14 +5086,16 @@ impl AiMemoryServer {
// the project-only `effective_ids_with_actor` here dropped the
// workspace arg, so a cross-workspace handoff landed in whatever project
// the contaminable active-project slot pointed at (the scope-bleed bug).
- let (ws, proj) = self
- .write_target_ids_with_actor(
+ let resolved_scope = self
+ .resolve_write_target_with_actor(
args.workspace.as_deref(),
args.project.as_deref(),
&aps_actor,
Self::viewer_from_parts(Some(&parts)),
)
.await?;
+ let (ws, proj) = resolved_scope.scope.as_tuple();
+ let manifest_warning = self.refresh_promoted_scope(&resolved_scope).await;
let open_questions = cap_handoff_list(
args.open_questions.iter().map(|q| s.scrub(q)),
HANDOFF_ITEM_MAX_CHARS,
@@ -5037,7 +5124,12 @@ impl AiMemoryServer {
let distinguishes = self
.deployment_distinguishes_operators()
.await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ .map_err(|e| {
+ Self::with_manifest_warning(
+ McpError::internal_error(e.to_string(), None),
+ manifest_warning.as_ref(),
+ )
+ })?;
ai_memory_core::owner_stamp(creator.identity_key().as_ref(), distinguishes)
};
let handoff = NewHandoff {
@@ -5065,14 +5157,20 @@ impl AiMemoryServer {
};
let admission = self
.authorize_operation(ws, proj, ai_memory_wiki::AdmissionOp::HandoffBegin, &parts)
- .await?;
- let id = self
- .writer
- .insert_handoff(handoff)
.await
- .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ .map_err(|error| Self::with_manifest_warning(error, manifest_warning.as_ref()))?;
+ let id = self.writer.insert_handoff(handoff).await.map_err(|e| {
+ Self::with_manifest_warning(
+ McpError::internal_error(e.to_string(), None),
+ manifest_warning.as_ref(),
+ )
+ })?;
self.notify_operation_observers(admission.as_ref());
- ok_json(&serde_json::json!({ "handoff_id": id.to_string() }))
+ let mut result = serde_json::json!({ "handoff_id": id.to_string() });
+ if let Some(warning) = manifest_warning {
+ result["manifest_warning"] = serde_json::Value::String(warning.to_string());
+ }
+ ok_json(&result)
}
/// List open handoffs without claiming them.
diff --git a/crates/ai-memory-mcp/tests/suite/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/suite/admin_bootstrap.rs
index 8fda091b..fb8e65a5 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_bootstrap.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_bootstrap.rs
@@ -6,19 +6,49 @@
//! The LLM path is covered by the consolidate-crate unit tests.
use ai_memory_consolidate::{BootstrapOutcome, BootstrapSource, SourceKind};
+use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
+use ai_memory_llm::{ChatRequest, ChatResponse, LlmProvider};
use ai_memory_mcp::{AdminState, admin_router};
use ai_memory_store::{DecayParams, Store};
use ai_memory_wiki::Wiki;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use serde_json::json;
+use std::sync::Arc;
use tempfile::TempDir;
use tower::ServiceExt;
+struct EmptyBootstrapLlm;
+
+#[async_trait::async_trait]
+impl LlmProvider for EmptyBootstrapLlm {
+ fn name(&self) -> &'static str {
+ "empty-bootstrap"
+ }
+
+ fn model(&self) -> &str {
+ "empty-bootstrap"
+ }
+
+ async fn complete(&self, _request: ChatRequest) -> ai_memory_llm::LlmResult<ChatResponse> {
+ unreachable!("bootstrap uses structured completion")
+ }
+
+ async fn complete_structured_raw(
+ &self,
+ _request: ChatRequest,
+ _schema: serde_json::Value,
+ ) -> ai_memory_llm::LlmResult<serde_json::Value> {
+ Ok(json!({ "pages": [], "rationale": "ok" }))
+ }
+}
+
/// Build a minimal `AdminState` backed by a real on-disk store + wiki.
async fn make_admin_state(tmp: &TempDir) -> AdminState {
let store = Store::open(tmp.path()).unwrap();
- let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
let db_path = store.db_path().to_path_buf();
AdminState {
ingest_metrics: std::sync::Arc::new(ai_memory_core::IngestMetrics::default()),
@@ -140,6 +170,63 @@ async fn dry_run_honours_sources_collected_hint() {
/// When no LLM is configured and `dry_run=false`, the server returns
/// 503 with a descriptive error body — not a panic.
+#[tokio::test]
+async fn bootstrap_surfaces_manifest_failure_after_promotion() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_admin_state(&tmp).await;
+ state.llm = Some(Arc::new(EmptyBootstrapLlm));
+ let workspace = state
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let (project, _) = state
+ .writer
+ .resolve_project_by_identity(
+ workspace,
+ RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ },
+ IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ state.wiki.backfill_scope_manifests().await.unwrap();
+ let manifest = tmp
+ .path()
+ .join("wiki")
+ .join(workspace.to_string())
+ .join(project.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+
+ let resp = post_bootstrap(
+ state,
+ json!({
+ "workspace": "default", "project": "acme-api", "sources": synthetic_sources(),
+ "max_input_tokens": 50_000, "dry_run": false, "force": true
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let outcome: BootstrapOutcome = serde_json::from_slice(&bytes).unwrap();
+ assert!(
+ outcome
+ .manifest_warning
+ .as_deref()
+ .is_some_and(|warning| warning.contains("committed"))
+ );
+}
+
#[tokio::test]
async fn non_dry_run_without_llm_returns_503() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/tests/suite/admin_move.rs b/crates/ai-memory-mcp/tests/suite/admin_move.rs
index 30a25a9c..71034204 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_move.rs
@@ -14,6 +14,7 @@
//! (sessions/observations/handoffs) are dropped by the purge.
use super::common::{post, spawn_capture_hook};
+use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
use ai_memory_core::{
AgentKind, NewHandoff, NewObservation, NewSession, ObservationKind, PagePath, Sanitized,
Sanitizer, SessionId, Tier,
@@ -318,6 +319,63 @@ async fn move_project_true_move_into_fresh_dest() {
assert!(!src_dir.exists(), "source dir must be removed after move");
}
+#[tokio::test]
+async fn move_project_merge_surfaces_destination_promotion_manifest_warning() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ seed_page(
+ &store,
+ &state.wiki,
+ "src",
+ "acme-api",
+ "notes/a.md",
+ "body a",
+ )
+ .await;
+ let dst_ws = store.writer.get_or_create_workspace("dst").await.unwrap();
+ let (dst_project, _) = store
+ .writer
+ .resolve_project_by_identity(
+ dst_ws,
+ RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ },
+ IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ state.wiki.backfill_scope_manifests().await.unwrap();
+ let manifest = tmp
+ .path()
+ .join("wiki")
+ .join(dst_ws.to_string())
+ .join(dst_project.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+
+ let resp = post(
+ state,
+ "/admin/move-project",
+ json!({ "from_workspace": "src", "project": "acme-api", "to_workspace": "dst", "confirm": true }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["merged_into_existing"], true, "{body}");
+ assert!(
+ body["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("committed")),
+ "{body}"
+ );
+}
+
/// Without `confirm: true` the server returns 400 and leaves the source intact.
#[tokio::test]
async fn move_project_requires_confirm() {
diff --git a/crates/ai-memory-mcp/tests/suite/admin_move_session.rs b/crates/ai-memory-mcp/tests/suite/admin_move_session.rs
index 04e37386..29bbfa5f 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_move_session.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_move_session.rs
@@ -7,6 +7,7 @@
//! consolidation job) and a `sessions/<id>.md` page written through the wiki
//! so a real file sits on disk.
+use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
use ai_memory_core::{
AgentKind, NewHandoff, NewObservation, NewSession, ObservationKind, PagePath, ProjectId,
Sanitized, Sanitizer, SessionId, Tier, WorkspaceId,
@@ -386,6 +387,57 @@ async fn move_session_restamps_rows_moves_file_and_checkpoints() {
);
}
+#[tokio::test]
+async fn move_session_create_surfaces_destination_promotion_manifest_warning() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let scopes = seed_scopes(&store).await;
+ let sid = seed_session(&store, &state.wiki, scopes.ws, scopes.src, "/repo/src").await;
+ let (destination, _) = store
+ .writer
+ .resolve_project_by_identity(
+ scopes.other_ws,
+ RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ },
+ IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ state.wiki.backfill_scope_manifests().await.unwrap();
+ let manifest = tmp
+ .path()
+ .join("wiki")
+ .join(scopes.other_ws.to_string())
+ .join(destination.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+
+ let resp = post(
+ &state,
+ "/admin/move-session",
+ json!({
+ "session_id": sid.to_string(), "workspace": "other", "project": "acme-api",
+ "create": true, "confirm": true
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert!(
+ body["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("committed")),
+ "{body}"
+ );
+}
+
#[tokio::test]
async fn move_session_across_workspaces_and_regenerate() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/tests/suite/admin_rename.rs b/crates/ai-memory-mcp/tests/suite/admin_rename.rs
index 2be83a48..6bf7c33c 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_rename.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_rename.rs
@@ -21,7 +21,9 @@ use tower::ServiceExt;
async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
let store = Store::open(tmp.path()).unwrap();
- let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
let db_path = store.db_path().to_path_buf();
let state = AdminState {
ingest_metrics: std::sync::Arc::new(ai_memory_core::IngestMetrics::default()),
@@ -125,6 +127,11 @@ async fn rename_project_happy_path() {
1,
"one page under new name: {body}"
);
+ assert!(body["manifest_warning"].is_null(), "{body}");
+ assert!(
+ body["checkpoint"].as_str().is_some(),
+ "manifest refresh must be checkpointed: {body}"
+ );
// Verify the project row was actually renamed in the DB.
let ws = store
@@ -148,10 +155,70 @@ async fn rename_project_happy_path() {
.await
.unwrap();
assert!(new_id.is_some(), "new project name must be findable");
+ let manifest = std::fs::read_to_string(
+ tmp.path()
+ .join("wiki")
+ .join(ws.to_string())
+ .join(new_id.unwrap().to_string())
+ .join("_meta.md"),
+ )
+ .unwrap();
+ assert!(manifest.contains("project: new-name"), "{manifest}");
}
/// Conflict: renaming `default/keep` to `default/doomed` when `doomed`
/// already exists must return 422.
+#[tokio::test]
+async fn rename_project_manifest_failure_is_disclosed_after_commit() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ seed_page(&store, &state.wiki, "old-name").await;
+ let workspace = store
+ .reader
+ .find_workspace("default".into())
+ .await
+ .unwrap()
+ .unwrap();
+ let project = store
+ .reader
+ .find_project(workspace, "old-name".into())
+ .await
+ .unwrap()
+ .unwrap();
+ let manifest = tmp
+ .path()
+ .join("wiki")
+ .join(workspace.to_string())
+ .join(project.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+
+ let resp = post(
+ state,
+ "/admin/rename-project",
+ json!({ "workspace": "default", "from": "old-name", "to": "new-name" }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert!(
+ body["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| !warning.is_empty()),
+ "{body}"
+ );
+ assert!(
+ store
+ .reader
+ .find_project(workspace, "new-name".into())
+ .await
+ .unwrap()
+ .is_some(),
+ "the SQL rename stays committed"
+ );
+}
+
#[tokio::test]
async fn rename_project_conflict_returns_422() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/tests/suite/admin_write_page.rs b/crates/ai-memory-mcp/tests/suite/admin_write_page.rs
index 3d9935e2..91d63de4 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_write_page.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_write_page.rs
@@ -4,6 +4,7 @@
//! verify it appears in `/admin/search` results. Also tests that an
//! unknown tier returns 422.
+use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
use ai_memory_mcp::{AdminState, admin_router};
use ai_memory_store::{DecayParams, Store};
use ai_memory_wiki::Wiki;
@@ -15,7 +16,9 @@ use tower::ServiceExt;
async fn make_state(tmp: &TempDir) -> AdminState {
let store = Store::open(tmp.path()).unwrap();
- let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
let db_path = store.db_path().to_path_buf();
AdminState {
ingest_metrics: std::sync::Arc::new(ai_memory_core::IngestMetrics::default()),
@@ -64,6 +67,33 @@ async fn body_json(resp: axum::response::Response) -> serde_json::Value {
serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
}
+async fn seed_identity_project(
+ state: &AdminState,
+) -> (ai_memory_core::WorkspaceId, ai_memory_core::ProjectId) {
+ let workspace = state
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let (project, _) = state
+ .writer
+ .resolve_project_by_identity(
+ workspace,
+ RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ },
+ IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ (workspace, project)
+}
+
#[tokio::test]
async fn write_page_returns_page_id_and_path() {
let tmp = TempDir::new().unwrap();
@@ -95,6 +125,43 @@ async fn write_page_returns_page_id_and_path() {
);
}
+#[tokio::test]
+async fn write_page_surfaces_manifest_failure_after_promotion() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let (workspace, project) = seed_identity_project(&state).await;
+ state.wiki.backfill_scope_manifests().await.unwrap();
+ let manifest = tmp
+ .path()
+ .join("wiki")
+ .join(workspace.to_string())
+ .join(project.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+
+ let resp = post_json(
+ state,
+ "/admin/write-page",
+ json!({
+ "workspace": "default",
+ "project": "acme-api",
+ "path": "notes/promoted.md",
+ "body": "survives the manifest failure",
+ "tier": "semantic",
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert!(
+ body["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("committed")),
+ "{body}"
+ );
+}
+
#[tokio::test]
async fn write_page_appears_in_search() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/tests/suite/dual_key_scope.rs b/crates/ai-memory-mcp/tests/suite/dual_key_scope.rs
new file mode 100644
index 00000000..f5c83f8f
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/suite/dual_key_scope.rs
@@ -0,0 +1,591 @@
+//! MCP coverage for identity-aware dual-key scope resolution (#1033).
+
+use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
+use ai_memory_core::{ActorContext, AuthorizedViewer, NewPage, NewUser, PagePath, Tier, UserId};
+use ai_memory_mcp::AiMemoryServer;
+use ai_memory_store::{AccessMode, GrantLevel, Store};
+use ai_memory_wiki::{AdmissionChain, AdmissionOp, FailurePolicy, WebhookConfig, Wiki};
+use axum::Router;
+use axum::body::Body;
+use axum::http::Request;
+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
+use serde_json::{Value, json};
+use std::collections::HashMap;
+use std::sync::Arc;
+use tempfile::TempDir;
+use tower::ServiceExt;
+
+struct Harness {
+ router: Router,
+ store: Store,
+ project: ai_memory_core::ProjectId,
+ writer: UserId,
+ wiki_root: std::path::PathBuf,
+ _tmp: TempDir,
+}
+
+async fn user(store: &Store, name: &str, byte: u8) -> UserId {
+ store
+ .writer
+ .create_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ [byte; ai_memory_store::TOKEN_HASH_LEN],
+ )
+ .await
+ .unwrap()
+}
+
+async fn harness() -> Harness {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let baked = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let writer = user(&store, "writer", 1).await;
+ let reader = user(&store, "reader", 2).await;
+ let project = store
+ .writer
+ .resolve_project_by_identity(
+ ws,
+ RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ },
+ IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ Some(writer),
+ )
+ .await
+ .unwrap()
+ .0;
+ store
+ .writer
+ .set_access_mode(project, AccessMode::Restricted)
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(reader, project, GrantLevel::Read, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(NewPage {
+ workspace_id: ws,
+ project_id: project,
+ path: PagePath::new("notes/existing.md").unwrap(),
+ title: "Existing".into(),
+ body: "dual key evidence".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: json!({}),
+ pinned: false,
+ links: vec![],
+ author_id: Some(writer),
+ expires_at: None,
+ entities: vec![],
+ evidence: vec![],
+ })
+ .await
+ .unwrap();
+ let wiki_root = tmp.path().join("wiki");
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
+ wiki.backfill_scope_manifests().await.unwrap();
+ wiki.commit_all("fixture baseline").unwrap();
+ let server =
+ AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, baked).with_wiki(wiki);
+ let service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+ let users = Arc::new(HashMap::from([
+ ("writer".to_owned(), writer),
+ ("reader".to_owned(), reader),
+ ]));
+ let router = Router::new()
+ .nest_service("/mcp", service)
+ .layer(axum::middleware::from_fn(
+ move |mut request: Request<Body>, next: axum::middleware::Next| {
+ let users = users.clone();
+ async move {
+ if let Some(name) = request
+ .headers()
+ .get("x-test-user")
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned)
+ && let Some(user) = users.get(&name).copied()
+ {
+ request.extensions_mut().insert(user);
+ request.extensions_mut().insert(AuthorizedViewer(user));
+ request.extensions_mut().insert(ActorContext {
+ user: Some(name),
+
+ ..ActorContext::default()
+ });
+ }
+ next.run(request).await
+ }
+ },
+ ));
+ Harness {
+ router,
+ store,
+ project,
+ writer,
+ wiki_root,
+ _tmp: tmp,
+ }
+}
+
+async fn rejecting_webhook() -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {
+ let app = Router::new().route(
+ "/reject",
+ axum::routing::post(|| async { (axum::http::StatusCode::CONFLICT, "rejected downstream") }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ (address, server)
+}
+
+fn rejecting_chain(address: std::net::SocketAddr, events: Vec<AdmissionOp>) -> AdmissionChain {
+ AdmissionChain::new(vec![WebhookConfig {
+ name: "reject".into(),
+ url: format!("http://{address}/reject"),
+ timeout_ms: 2_000,
+ failure_policy: FailurePolicy::Reject,
+ events,
+ blocking: true,
+ }])
+ .unwrap()
+}
+
+async fn call(router: &Router, user: &str, tool: &str, arguments: Value) -> Value {
+ let request = Request::builder()
+ .method("POST")
+ .uri("/mcp")
+ .header("host", "localhost")
+ .header("content-type", "application/json")
+ .header("accept", "application/json, text/event-stream")
+ .header("x-test-user", user)
+ .body(Body::from(
+ json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": tool, "arguments": arguments }
+ })
+ .to_string(),
+ ))
+ .unwrap();
+ let response = router.clone().oneshot(request).await.unwrap();
+ let bytes = axum::body::to_bytes(response.into_body(), 4_000_000)
+ .await
+ .unwrap();
+ serde_json::from_slice(&bytes).unwrap()
+}
+
+fn tool_text(response: &Value) -> String {
+ response
+ .pointer("/result/content")
+ .and_then(Value::as_array)
+ .unwrap_or(&vec![])
+ .iter()
+ .filter_map(|part| part.get("text").and_then(Value::as_str))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+fn project_name(h: &Harness) -> String {
+ let conn = rusqlite::Connection::open(h.store.db_path()).unwrap();
+ conn.query_row(
+ "SELECT name FROM projects WHERE id = ?1",
+ [h.project.as_bytes().to_vec()],
+ |row| row.get(0),
+ )
+ .unwrap()
+}
+
+#[tokio::test]
+async fn static_canonical_and_legacy_reads_do_not_promote_and_read_only_write_is_refused() {
+ let h = harness().await;
+ for name in ["api", "acme-api"] {
+ let response = call(
+ &h.router,
+ "reader",
+ "memory_read_page",
+ json!({"workspace":"default", "project":name, "path":"notes/existing.md"}),
+ )
+ .await;
+ assert!(
+ tool_text(&response).contains("dual key evidence"),
+ "{response}"
+ );
+ }
+ let refused = call(
+ &h.router,
+ "reader",
+ "memory_write_page",
+ json!({
+ "workspace":"default", "project":"acme-api", "path":"notes/denied.md",
+ "body":"must not land"
+ }),
+ )
+ .await;
+ assert!(refused.get("error").is_some(), "{refused}");
+ assert!(
+ refused["error"]["message"]
+ .as_str()
+ .is_some_and(|message| message.contains("write access")),
+ "{refused}"
+ );
+ assert_eq!(project_name(&h), "api");
+}
+
+#[tokio::test]
+async fn authorized_static_write_promotes_once_and_legacy_reads_still_work() {
+ let h = harness().await;
+ let response = call(
+ &h.router,
+ "writer",
+ "memory_write_page",
+ json!({
+ "workspace":"default", "project":"acme-api", "path":"notes/promoted.md",
+ "body":"promoted write"
+ }),
+ )
+ .await;
+ assert!(response.get("error").is_none(), "{response}");
+ assert_eq!(
+ response.pointer("/result/isError"),
+ Some(&json!(false)),
+ "{response}"
+ );
+ let result: Value = serde_json::from_str(&tool_text(&response)).unwrap();
+ assert!(
+ result.get("page_id").and_then(Value::as_str).is_some(),
+ "{result}"
+ );
+ assert_eq!(project_name(&h), "acme-api");
+ let manifest = std::fs::read_to_string(
+ h.wiki_root
+ .join(
+ h.store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap()
+ .to_string(),
+ )
+ .join(h.project.to_string())
+ .join("_meta.md"),
+ )
+ .unwrap();
+ assert!(manifest.contains("project: acme-api"), "{manifest}");
+ assert!(h.wiki_root.join(".git").is_dir());
+ let legacy = call(
+ &h.router,
+ "reader",
+ "memory_read_page",
+ json!({"workspace":"default", "project":"api", "path":"notes/promoted.md"}),
+ )
+ .await;
+ assert!(tool_text(&legacy).contains("promoted write"), "{legacy}");
+}
+
+#[tokio::test]
+async fn promotion_manifest_failure_is_disclosed_and_repaired_without_undoing_sql() {
+ let h = harness().await;
+ let ws = h
+ .store
+ .reader
+ .find_workspace("default".into())
+ .await
+ .unwrap()
+ .unwrap();
+ let manifest = h
+ .wiki_root
+ .join(ws.to_string())
+ .join(h.project.to_string())
+ .join("_meta.md");
+ assert!(
+ std::fs::read_to_string(&manifest)
+ .unwrap()
+ .contains("project: api")
+ );
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+ let response = call(&h.router, "writer", "memory_write_page", json!({
+ "workspace":"default", "project":"acme-api", "path":"notes/partial.md", "body":"surviving write"
+ })).await;
+ assert!(response.get("error").is_none(), "{response}");
+ let result: Value = serde_json::from_str(&tool_text(&response)).unwrap();
+ assert!(result["page_id"].as_str().is_some(), "{result}");
+ assert!(
+ result["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("committed")),
+ "{result}"
+ );
+ assert_eq!(project_name(&h), "acme-api");
+ assert!(manifest.is_dir());
+ std::fs::remove_dir(&manifest).unwrap();
+ let wiki = Wiki::new(h._tmp.path(), h.store.writer.clone())
+ .unwrap()
+ .with_store_reader(h.store.reader.clone());
+ assert!(
+ wiki.refresh_renamed_scope(ws, h.project)
+ .await
+ .unwrap()
+ .is_some()
+ );
+ assert!(
+ std::fs::read_to_string(&manifest)
+ .unwrap()
+ .contains("project: acme-api")
+ );
+ assert!(
+ wiki.refresh_renamed_scope(ws, h.project)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ let legacy = call(
+ &h.router,
+ "reader",
+ "memory_read_page",
+ json!({
+ "workspace":"default", "project":"api", "path":"notes/partial.md"
+ }),
+ )
+ .await;
+ assert!(tool_text(&legacy).contains("surviving write"), "{legacy}");
+}
+
+#[tokio::test]
+async fn page_write_failure_after_promotion_preserves_manifest_warning() {
+ let h = harness().await;
+ let ws = h
+ .store
+ .reader
+ .find_workspace("default".into())
+ .await
+ .unwrap()
+ .unwrap();
+ let manifest = h
+ .wiki_root
+ .join(ws.to_string())
+ .join(h.project.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+ let (address, webhook) = rejecting_webhook().await;
+ let wiki = Wiki::new(h._tmp.path(), h.store.writer.clone())
+ .unwrap()
+ .with_store_reader(h.store.reader.clone())
+ .with_admission_chain(rejecting_chain(address, vec![AdmissionOp::WritePage]));
+ let server = AiMemoryServer::new(
+ h.store.reader.clone(),
+ h.store.writer.clone(),
+ ws,
+ h.project,
+ )
+ .with_wiki(wiki);
+ let service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+ let router = Router::new().nest_service("/mcp", service);
+
+ let response = call(
+ &router,
+ "",
+ "memory_write_page",
+ json!({
+ "workspace":"default", "project":"acme-api",
+ "path":"notes/rejected.md", "body":"must not land"
+ }),
+ )
+ .await;
+ assert_eq!(response["error"]["code"], json!(-32603), "{response}");
+ assert!(
+ response["error"]["message"]
+ .as_str()
+ .is_some_and(|message| message.contains("admission webhook")),
+ "{response}"
+ );
+ assert!(
+ response["error"]["data"]["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("promotion committed")),
+ "{response}"
+ );
+ assert_eq!(project_name(&h), "acme-api");
+ assert!(
+ h.store
+ .reader
+ .page_meta("default", "acme-api", "notes/rejected.md")
+ .await
+ .unwrap()
+ .is_none()
+ );
+ webhook.abort();
+}
+
+#[tokio::test]
+async fn handoff_failure_after_promotion_preserves_manifest_warning() {
+ let h = harness().await;
+ let ws = h
+ .store
+ .reader
+ .find_workspace("default".into())
+ .await
+ .unwrap()
+ .unwrap();
+ let manifest = h
+ .wiki_root
+ .join(ws.to_string())
+ .join(h.project.to_string())
+ .join("_meta.md");
+ std::fs::remove_file(&manifest).unwrap();
+ std::fs::create_dir(&manifest).unwrap();
+ let (address, webhook) = rejecting_webhook().await;
+ let wiki = Wiki::new(h._tmp.path(), h.store.writer.clone())
+ .unwrap()
+ .with_store_reader(h.store.reader.clone())
+ .with_admission_chain(rejecting_chain(address, vec![AdmissionOp::HandoffBegin]));
+ let server = AiMemoryServer::new(
+ h.store.reader.clone(),
+ h.store.writer.clone(),
+ ws,
+ h.project,
+ )
+ .with_wiki(wiki);
+ let service = StreamableHttpService::new(
+ move || Ok(server.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(false)
+ .with_json_response(true),
+ );
+ let router = Router::new().nest_service("/mcp", service);
+
+ let response = call(
+ &router,
+ "",
+ "memory_handoff_begin",
+ json!({
+ "workspace":"default", "project":"acme-api",
+ "summary":"must not land"
+ }),
+ )
+ .await;
+ assert_eq!(response["error"]["code"], json!(-32600), "{response}");
+ assert!(
+ response["error"]["message"]
+ .as_str()
+ .is_some_and(|message| message.contains("admission webhook")),
+ "{response}"
+ );
+ assert!(
+ response["error"]["data"]["manifest_warning"]
+ .as_str()
+ .is_some_and(|warning| warning.contains("promotion committed")),
+ "{response}"
+ );
+ assert_eq!(project_name(&h), "acme-api");
+ assert!(
+ h.store
+ .reader
+ .open_handoffs_for_project(ws, h.project, 10)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ webhook.abort();
+}
+
+#[tokio::test]
+async fn foreign_workspace_and_cross_forge_keys_fail_closed() {
+ let h = harness().await;
+ let foreign_ws = h
+ .store
+ .writer
+ .get_or_create_workspace("foreign")
+ .await
+ .unwrap();
+ let foreign = h
+ .store
+ .writer
+ .get_or_create_project(foreign_ws, "acme-api", None)
+ .await
+ .unwrap();
+ h.store
+ .writer
+ .set_access_mode(foreign, AccessMode::Restricted)
+ .await
+ .unwrap();
+ let foreign_response = call(
+ &h.router,
+ "reader",
+ "memory_read_page",
+ json!({"workspace":"foreign", "project":"acme-api", "path":"notes/existing.md"}),
+ )
+ .await;
+ assert!(
+ foreign_response.get("error").is_some(),
+ "{foreign_response}"
+ );
+
+ let ws = h
+ .store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ h.store
+ .writer
+ .resolve_project_by_identity(
+ ws,
+ RepositoryIdentity {
+ identity: "gitlab.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ },
+ IdentityStyle::HostPath,
+ "gitlab-api",
+ None,
+ None,
+ Some(h.writer),
+ )
+ .await
+ .unwrap();
+ let ambiguous = call(
+ &h.router,
+ "reader",
+ "memory_read_page",
+ json!({"workspace":"default", "project":"acme-api", "path":"notes/existing.md"}),
+ )
+ .await;
+ assert!(ambiguous.get("error").is_some(), "{ambiguous}");
+}
diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rs
index 2e75ae24..c25575cf 100644
--- a/crates/ai-memory-mcp/tests/suite/mod.rs
+++ b/crates/ai-memory-mcp/tests/suite/mod.rs
@@ -24,6 +24,7 @@ mod admin_write_page;
mod agent_messages_briefing;
mod agent_messages_tools;
mod autoscope_multiuser;
+mod dual_key_scope;
mod handoff_admission;
mod handoff_identity;
mod mcp_stateless_http;
diff --git a/crates/ai-memory-store/migrations/V76__project_coordinate_keys.sql b/crates/ai-memory-store/migrations/V76__project_coordinate_keys.sql
new file mode 100644
index 00000000..037ef651
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V76__project_coordinate_keys.sql
@@ -0,0 +1,23 @@
+-- V76: indexed derived project-name keys for identity-aware static scope resolution (#1033).
+--
+-- The full hostful repository identity remains authoritative. These two columns
+-- are derived lookup keys, not user aliases: canonical_name is the hostless
+-- path spelling and legacy_name is the v2 repository basename. Existing rows
+-- are backfilled by the bounded Rust startup pass before traffic is accepted.
+
+ALTER TABLE projects ADD COLUMN canonical_name TEXT NOT NULL DEFAULT '';
+ALTER TABLE projects ADD COLUMN legacy_name TEXT NOT NULL DEFAULT '';
+
+CREATE INDEX idx_projects_canonical_name
+ ON projects(workspace_id, canonical_name)
+ WHERE canonical_name <> '';
+
+CREATE INDEX idx_projects_legacy_name
+ ON projects(workspace_id, legacy_name)
+ WHERE legacy_name <> '';
+
+CREATE INDEX idx_projects_coordinate_backfill
+ ON projects(identity_source)
+ WHERE identity_source = 'git_remote'
+ AND identity <> ''
+ AND (canonical_name = '' OR legacy_name = '');
diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rs
index 8f7c8ded..471cdc6c 100644
--- a/crates/ai-memory-store/src/api_credentials.rs
+++ b/crates/ai-memory-store/src/api_credentials.rs
@@ -411,7 +411,7 @@ mod tests {
|row| row.get(0),
)
.unwrap();
- assert_eq!(version, 75, "update the pin when adding a migration");
+ assert_eq!(version, 76, "update the pin when adding a migration");
let cols: i64 = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'token_hash'",
diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rs
index 3b130c24..764ff640 100644
--- a/crates/ai-memory-store/src/error.rs
+++ b/crates/ai-memory-store/src/error.rs
@@ -71,6 +71,10 @@ pub enum StoreError {
#[error("project name '{0}' is already taken in this workspace")]
ProjectNameTaken(String),
+ /// More than one project in a workspace matched a compatibility name.
+ #[error("project name '{0}' is ambiguous in this workspace")]
+ ProjectNameAmbiguous(String),
+
/// The supplied project name failed validation (empty, slash, etc.).
#[error("invalid project name: {0}")]
InvalidProjectName(String),
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index bd2ff344..2c680a77 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -27,6 +27,7 @@ mod ops;
pub mod password;
mod profile;
mod project_authz;
+mod project_coordinates;
mod reader;
mod retrieval_tuning;
mod scope;
@@ -93,12 +94,12 @@ pub use reader::{
};
pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};
pub use scope::{
- PRIVATE_PROFILE_NEEDS_USER, ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver,
- ScopeSource, WORKSPACE_PROJECT_PAIR_REQUIRED, authorize_scope_for, create_explicit_scope,
- create_explicit_scope_guarded, create_global_scope, create_profile_scope,
- lookup_existing_scope, lookup_existing_scope_guarded, lookup_existing_workspace,
- lookup_global_scope, lookup_profile_scope, resolve_many_existing_scopes,
- resolve_many_existing_scopes_guarded,
+ PRIVATE_PROFILE_NEEDS_USER, ResolvedScope, ResolvedWriteScope, ScopeName, ScopeResolutionError,
+ ScopeResolver, ScopeSource, WORKSPACE_PROJECT_PAIR_REQUIRED, authorize_scope_for,
+ create_explicit_scope, create_explicit_scope_guarded, create_global_scope,
+ create_profile_scope, lookup_existing_scope, lookup_existing_scope_guarded,
+ lookup_existing_workspace, lookup_global_scope, lookup_profile_scope,
+ resolve_many_existing_scopes, resolve_many_existing_scopes_guarded,
};
pub use session_consolidation::{SESSION_CONSOLIDATION_MAX_ATTEMPTS, SessionConsolidationJob};
pub use users::{
@@ -188,6 +189,13 @@ impl Store {
// before the server accepts traffic. A store already backfilled (every
// page has a non-NULL `valid_from`) is a fast no-op.
ops::backfill_page_windows(&mut conn)?;
+ let coordinate_keys = project_coordinates::backfill(&mut conn)?;
+ if coordinate_keys > 0 {
+ tracing::info!(
+ projects = coordinate_keys,
+ "project coordinate keys backfilled"
+ );
+ }
let writer = WriterHandle::spawn(conn);
let reader = ReaderPool::new(&db_path, READER_POOL_SOFT_CAP)?;
diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rs
index c38c56f6..95560885 100644
--- a/crates/ai-memory-store/src/migrations.rs
+++ b/crates/ai-memory-store/src/migrations.rs
@@ -1142,6 +1142,46 @@ mod tests {
assert!(!after.contains("supersedes IS NULL"), "{after}");
}
+ #[test]
+ fn project_coordinate_keys_upgrade_and_backfill_without_changing_project_ids() {
+ let coordinate_version = migrations::runner()
+ .get_migrations()
+ .iter()
+ .find(|migration| migration.name() == "project_coordinate_keys")
+ .map(refinery::Migration::version)
+ .unwrap();
+ let mut conn = Connection::open_in_memory().unwrap();
+ run_to(&mut conn, coordinate_version - 1).unwrap();
+ let workspace_id = [8_u8; 16];
+ let project_id = [9_u8; 16];
+ conn.execute(
+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'acme', 1)",
+ params![workspace_id.as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, created_at, identity, identity_source) \
+ VALUES (?1, ?2, 'api', 1, 'github.com/acme/group/api', 'git_remote')",
+ params![project_id.as_slice(), workspace_id.as_slice()],
+ )
+ .unwrap();
+
+ run(&mut conn).unwrap();
+ assert_eq!(crate::project_coordinates::backfill(&mut conn).unwrap(), 1);
+ let row: (Vec<u8>, String, String, String) = conn
+ .query_row(
+ "SELECT id, name, canonical_name, legacy_name FROM projects",
+ [],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
+ )
+ .unwrap();
+ assert_eq!(row.0, project_id);
+ assert_eq!(row.1, "api");
+ assert_eq!(row.2, "acme-group-api");
+ assert_eq!(row.3, "api");
+ assert_eq!(crate::project_coordinates::backfill(&mut conn).unwrap(), 0);
+ }
+
/// Upstream's `UNIQUE (workspace_id, name)` is case-sensitive, so one
/// workspace may hold both `API` and `api`. The identity index is on
/// case-folded values, and backfilling `lower(name)` into it failed the
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 3dfdea91..e5192fe1 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -412,6 +412,125 @@ impl IdentityResolution {
matches!(self, Self::Created | Self::Split)
}
}
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ProjectNameWriteResolution {
+ pub project_id: ai_memory_core::ProjectId,
+ pub promoted_from: Option<String>,
+ pub authorization_error: Option<ai_memory_core::AuthzError>,
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn resolve_project_name_for_write(
+ conn: &mut Connection,
+ workspace_id: &ai_memory_core::WorkspaceId,
+ requested: &str,
+ principal: Option<&crate::ProjectPrincipal>,
+ distinguishes_operators: bool,
+ promote: bool,
+ new_project_mode: crate::AccessMode,
+) -> StoreResult<ProjectNameWriteResolution> {
+ let tx = conn.transaction()?;
+ let matched = crate::project_coordinates::resolve(&tx, *workspace_id, requested)?;
+ if let Some(matched) = matched {
+ if let Some(principal) = principal {
+ crate::project_authz::resolve_project_authz(
+ &tx,
+ *workspace_id,
+ matched.id,
+ principal,
+ distinguishes_operators,
+ )?
+ .authorize(crate::ProjectAccess::Write)
+ .map_err(|error| StoreError::Forbidden(error.message()))?;
+ }
+ let promote_to = if promote {
+ matched
+ .canonical_name
+ .filter(|canonical| canonical == requested && canonical != &matched.current_name)
+ } else {
+ None
+ };
+ let promoted_from = if let Some(canonical) = promote_to {
+ rename_project_in_tx(
+ &tx,
+ workspace_id,
+ &matched.id,
+ Some(&matched.current_name),
+ &canonical,
+ principal.and_then(|principal| principal.user_id),
+ "promote_project_name",
+ )?;
+ Some(matched.current_name)
+ } else {
+ None
+ };
+ tx.commit()?;
+ return Ok(ProjectNameWriteResolution {
+ project_id: matched.id,
+ promoted_from,
+ authorization_error: None,
+ });
+ }
+
+ let also_in = project_name_in_other_workspaces(&tx, workspace_id, requested)?;
+ let id = insert_project_with_identityless_name(
+ &tx,
+ workspace_id,
+ requested,
+ None,
+ initial_access_mode(requested, new_project_mode),
+ principal.and_then(|principal| principal.user_id),
+ Timestamp::now().as_microsecond(),
+ )?;
+ let authorization_error = match principal {
+ Some(principal) => crate::project_authz::resolve_project_authz(
+ &tx,
+ *workspace_id,
+ id,
+ principal,
+ distinguishes_operators,
+ )?
+ .authorize(crate::ProjectAccess::Write)
+ .err(),
+ None => None,
+ };
+ tx.commit()?;
+ if scheduler_state_table_exists(conn)? {
+ crate::auto_improve::ensure_scheduler_state(conn, *workspace_id, id)?;
+ }
+ warn_project_name_in_other_workspaces(requested, &also_in);
+ Ok(ProjectNameWriteResolution {
+ project_id: id,
+ promoted_from: None,
+ authorization_error,
+ })
+}
+
+fn insert_project_with_identityless_name(
+ tx: &rusqlite::Transaction<'_>,
+ workspace_id: &ai_memory_core::WorkspaceId,
+ name: &str,
+ repo_path: Option<&str>,
+ mode: crate::AccessMode,
+ creator: Option<ai_memory_core::UserId>,
+ now: i64,
+) -> StoreResult<ai_memory_core::ProjectId> {
+ let id = ai_memory_core::ProjectId::new();
+ tx.execute(
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at, access_mode, created_by) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
+ params![
+ id.as_bytes(),
+ workspace_id.as_bytes(),
+ name,
+ repo_path,
+ now,
+ mode.as_str(),
+ creator.map(|creator| creator.as_bytes().to_vec()),
+ ],
+ )?;
+ Ok(id)
+}
/// Resolve the project a repository identity routes to, creating it if
/// needed, in one transaction (#708).
@@ -544,9 +663,22 @@ pub fn resolve_project_by_identity(
.is_ok(),
};
if may_write {
+ let canonical_name =
+ ai_memory_core::repository_identity::path_style_name(identity)
+ .unwrap_or_default();
+ let legacy_name =
+ ai_memory_core::repository_identity::legacy_basename_name(identity)
+ .unwrap_or_default();
tx.execute(
- "UPDATE projects SET identity = ?1, identity_source = ?2 WHERE id = ?3",
- params![identity.identity, identity.source.as_str(), id.as_bytes()],
+ "UPDATE projects SET identity = ?1, identity_source = ?2, \
+ canonical_name = ?3, legacy_name = ?4 WHERE id = ?5",
+ params![
+ identity.identity,
+ identity.source.as_str(),
+ canonical_name,
+ legacy_name,
+ id.as_bytes()
+ ],
)?;
(id, IdentityResolution::Claimed)
} else {
@@ -602,11 +734,15 @@ fn insert_project_with_identity(
now: i64,
) -> StoreResult<ai_memory_core::ProjectId> {
let id = ai_memory_core::ProjectId::new();
+ let canonical_name =
+ ai_memory_core::repository_identity::path_style_name(identity).unwrap_or_default();
+ let legacy_name =
+ ai_memory_core::repository_identity::legacy_basename_name(identity).unwrap_or_default();
tx.execute(
"INSERT INTO projects \
(id, workspace_id, name, repo_path, created_at, identity, identity_source, access_mode, \
- created_by) \
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
+ created_by, canonical_name, legacy_name) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
params![
id.as_bytes(),
workspace_id.as_bytes(),
@@ -617,6 +753,8 @@ fn insert_project_with_identity(
identity.source.as_str(),
mode.as_str(),
creator.map(|creator| creator.as_bytes().to_vec()),
+ canonical_name,
+ legacy_name,
],
)?;
Ok(id)
@@ -806,18 +944,32 @@ pub fn ensure_project_with_id(
workspace_id: ai_memory_core::WorkspaceId,
name: &str,
repo_path: Option<&str>,
+ identity: Option<&ai_memory_core::repository_identity::RepositoryIdentity>,
) -> StoreResult<()> {
let repo_path = repo_path.map(normalize_repo_path_key);
+ let identity_value = identity.map(|value| value.identity.as_str()).unwrap_or("");
+ let identity_source = identity.map(|value| value.source.as_str()).unwrap_or("");
+ let canonical_name = identity
+ .and_then(ai_memory_core::repository_identity::path_style_name)
+ .unwrap_or_default();
+ let legacy_name = identity
+ .and_then(ai_memory_core::repository_identity::legacy_basename_name)
+ .unwrap_or_default();
let tx = conn.transaction()?;
let inserted = tx.execute(
- "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
- VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT(id) DO NOTHING",
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at, \
+ identity, identity_source, canonical_name, legacy_name) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(id) DO NOTHING",
params![
id.as_bytes(),
workspace_id.as_bytes(),
name,
repo_path.as_deref(),
- Timestamp::now().as_microsecond()
+ Timestamp::now().as_microsecond(),
+ identity_value,
+ identity_source,
+ canonical_name,
+ legacy_name
],
)?;
let also_in = if inserted > 0 {
@@ -825,28 +977,64 @@ pub fn ensure_project_with_id(
} else {
Vec::new()
};
- type ProjectRow = (Vec<u8>, String, Option<String>);
+ type ProjectRow = (
+ Vec<u8>,
+ String,
+ Option<String>,
+ String,
+ String,
+ String,
+ String,
+ );
let existing: Option<ProjectRow> = tx
.query_row(
- "SELECT workspace_id, name, repo_path FROM projects WHERE id = ?1",
+ "SELECT workspace_id, name, repo_path, identity, identity_source, \
+ canonical_name, legacy_name FROM projects WHERE id = ?1",
params![id.as_bytes()],
- |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ |row| {
+ Ok((
+ row.get(0)?,
+ row.get(1)?,
+ row.get(2)?,
+ row.get(3)?,
+ row.get(4)?,
+ row.get(5)?,
+ row.get(6)?,
+ ))
+ },
)
.optional()?;
match existing {
- Some((existing_ws, existing_name, existing_repo_path))
- if existing_ws.as_slice() == workspace_id.as_bytes()
- && existing_name == name
- && existing_repo_path.as_deref() == repo_path.as_deref() =>
+ Some((
+ existing_ws,
+ existing_name,
+ existing_repo_path,
+ existing_identity,
+ existing_source,
+ existing_canonical,
+ existing_legacy,
+ )) if existing_ws.as_slice() == workspace_id.as_bytes()
+ && existing_name == name
+ && existing_repo_path.as_deref() == repo_path.as_deref()
+ && existing_identity == identity_value
+ && existing_source == identity_source
+ && existing_canonical == canonical_name
+ && existing_legacy == legacy_name =>
{
Ok(())
}
- Some((existing_ws, existing_name, existing_repo_path)) => {
- Err(StoreError::Duplicate(format!(
- "project id {id} already exists with workspace_id bytes length {}, name='{existing_name}', repo_path={existing_repo_path:?}; manifest has workspace={workspace_id}, name='{name}', repo_path={repo_path:?}",
- existing_ws.len(),
- )))
- }
+ Some((
+ existing_ws,
+ existing_name,
+ existing_repo_path,
+ existing_identity,
+ existing_source,
+ existing_canonical,
+ existing_legacy,
+ )) => Err(StoreError::Duplicate(format!(
+ "project id {id} already exists with workspace_id bytes length {}, name='{existing_name}', repo_path={existing_repo_path:?}, identity={existing_identity:?}, identity_source={existing_source:?}, canonical_name={existing_canonical:?}, legacy_name={existing_legacy:?}; manifest has workspace={workspace_id}, name='{name}', repo_path={repo_path:?}, identity={identity_value:?}, identity_source={identity_source:?}, canonical_name={canonical_name:?}, legacy_name={legacy_name:?}",
+ existing_ws.len(),
+ ))),
None => Err(StoreError::NotFound(format!(
"project id {id} was not inserted"
))),
@@ -4857,26 +5045,7 @@ pub fn reorg_sessions(
})
}
-/// Rename a project within its workspace.
-///
-/// Only the `name` column is updated — all pages, sessions, observations,
-/// and handoffs remain associated with the same `project_id`. No files
-/// move on disk (the wiki is flat: every page from every project lives
-/// under `wiki/`; only the `project_id` foreign key distinguishes them).
-///
-/// # Errors
-/// - [`StoreError::InvalidProjectName`] when `new_name` is empty,
-/// contains a `/` character, or is all whitespace.
-/// - [`StoreError::ProjectNameTaken`] when a project with `new_name`
-/// already exists in the same workspace.
-/// - [`StoreError::Sqlite`] on any other SQL failure.
-pub fn rename_project(
- conn: &mut Connection,
- workspace_id: &WorkspaceId,
- project_id: &ProjectId,
- new_name: &str,
- author_id: Option<ai_memory_core::UserId>,
-) -> StoreResult<()> {
+fn validate_project_rename<'a>(current_name: &str, new_name: &'a str) -> StoreResult<&'a str> {
let trimmed = new_name.trim();
if trimmed.is_empty() {
return Err(StoreError::InvalidProjectName(
@@ -4888,74 +5057,111 @@ pub fn rename_project(
"project name must not contain '/' (it appears in URL paths)".into(),
));
}
- // A profile project is found by its name (and a private one's owner is
- // its name), so renaming one away orphans it and renaming a project onto
- // a profile name hands someone else's pages to that profile.
if ai_memory_core::profile::is_profile_project(trimmed) {
return Err(StoreError::InvalidProjectName(format!(
"{trimmed} is reserved for the cross-project profile"
)));
}
- let current: Option<String> = conn
- .query_row(
- "SELECT name FROM projects WHERE id = ?1 AND workspace_id = ?2",
- params![project_id.as_bytes(), workspace_id.as_bytes()],
- |row| row.get(0),
- )
- .optional()?;
- if current
- .as_deref()
- .is_some_and(ai_memory_core::profile::is_profile_project)
- {
+ if ai_memory_core::profile::is_profile_project(current_name) {
return Err(StoreError::InvalidProjectName(
"a cross-project profile project cannot be renamed".into(),
));
}
+ Ok(trimmed)
+}
- // Wrap the UPDATE + audit row in one transaction so the trail can never
- // diverge from the rename it records (on any error the tx drops without
- // commit, rolling both back).
- let tx = conn.transaction()?;
+fn rename_project_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ workspace_id: &WorkspaceId,
+ project_id: &ProjectId,
+ current_name: Option<&str>,
+ new_name: &str,
+ author_id: Option<ai_memory_core::UserId>,
+ audit_op: &str,
+) -> StoreResult<()> {
+ let current = match current_name {
+ Some(current) => current.to_owned(),
+ None => tx
+ .query_row(
+ "SELECT name FROM projects WHERE id = ?1 AND workspace_id = ?2",
+ params![project_id.as_bytes(), workspace_id.as_bytes()],
+ |row| row.get(0),
+ )
+ .optional()?
+ .ok_or_else(|| {
+ StoreError::NotFound(format!(
+ "project id {project_id} no longer exists in workspace {workspace_id} \
+ (race with concurrent purge or delete)"
+ ))
+ })?,
+ };
+ let trimmed = validate_project_rename(&current, new_name)?;
let rows = tx.execute(
"UPDATE projects SET name = ?1 WHERE id = ?2 AND workspace_id = ?3",
params![trimmed, project_id.as_bytes(), workspace_id.as_bytes()],
);
-
match rows {
- // Zero rows affected means the project row vanished between the
- // admin handler's `lookup_ws_proj_no_create` and this UPDATE —
- // the classic shape is a concurrent `purge-project` racing the
- // rename. Without this check, the rename would happily return
- // `Ok(())` and the admin handler would respond `200 OK` for an
- // operation that touched nothing, contradicting the purge's
- // (also `200 OK`) destruction of the same row.
Ok(0) => Err(StoreError::NotFound(format!(
"project id {project_id} no longer exists in workspace {workspace_id} \
- (race with concurrent purge or delete)",
+ (race with concurrent purge or delete)"
))),
Ok(_) => {
- audit(
- &tx,
- "rename_project",
+ let detail = serde_json::json!({ "from": current, "to": trimmed }).to_string();
+ audit_with_detail(
+ tx,
+ audit_op,
Some(workspace_id.as_bytes()),
Some(project_id.as_bytes()),
None,
author_id.as_ref().map(ai_memory_core::UserId::as_bytes),
Timestamp::now().as_microsecond(),
- )?;
- tx.commit()?;
- Ok(())
+ &detail,
+ )
}
- Err(rusqlite::Error::SqliteFailure(err, _))
- if err.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE
- || err.code == rusqlite::ErrorCode::ConstraintViolation =>
+ Err(rusqlite::Error::SqliteFailure(error, _))
+ if error.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE
+ || error.code == rusqlite::ErrorCode::ConstraintViolation =>
{
- Err(StoreError::ProjectNameTaken(trimmed.to_string()))
+ Err(StoreError::ProjectNameTaken(trimmed.to_owned()))
}
- Err(e) => Err(StoreError::Sqlite(e)),
+ Err(error) => Err(StoreError::Sqlite(error)),
}
}
+/// Rename a project within its workspace.
+///
+/// Only the `name` column is updated — all pages, sessions, observations,
+/// and handoffs remain associated with the same `project_id`. No files
+/// move on disk (the wiki is flat: every page from every project lives
+/// under `wiki/`; only the `project_id` foreign key distinguishes them).
+///
+/// # Errors
+/// - [`StoreError::InvalidProjectName`] when `new_name` is empty,
+/// contains a `/` character, or is all whitespace.
+/// - [`StoreError::ProjectNameTaken`] when a project with `new_name`
+/// already exists in the same workspace.
+/// - [`StoreError::Sqlite`] on any other SQL failure.
+pub fn rename_project(
+ conn: &mut Connection,
+ workspace_id: &WorkspaceId,
+ project_id: &ProjectId,
+ new_name: &str,
+ author_id: Option<ai_memory_core::UserId>,
+) -> StoreResult<()> {
+ let tx = conn.transaction()?;
+ rename_project_in_tx(
+ &tx,
+ workspace_id,
+ project_id,
+ None,
+ new_name,
+ author_id,
+ "rename_project",
+ )?;
+ tx.commit()?;
+ Ok(())
+}
+
/// Record a successfully-applied wiki-structure migration.
///
/// Uses `INSERT OR IGNORE` so re-running the same name is a no-op
@@ -7291,7 +7497,7 @@ pub(crate) mod tests {
let id = ProjectId::new();
let logs = capture_warnings(|| {
- ensure_project_with_id(&mut conn, id, ws_b, "shared", None).unwrap();
+ ensure_project_with_id(&mut conn, id, ws_b, "shared", None, None).unwrap();
});
assert!(
logs.contains("already exists in other workspace")
@@ -7301,7 +7507,7 @@ pub(crate) mod tests {
);
let logs = capture_warnings(|| {
- ensure_project_with_id(&mut conn, id, ws_b, "shared", None).unwrap();
+ ensure_project_with_id(&mut conn, id, ws_b, "shared", None, None).unwrap();
});
assert!(
!logs.contains("already exists in other workspace"),
@@ -7316,10 +7522,10 @@ pub(crate) mod tests {
let ws_b = get_or_create_workspace(&mut conn, "beta").unwrap();
get_or_create_project(&mut conn, &ws_a, "shared", None).unwrap();
let id = ProjectId::new();
- ensure_project_with_id(&mut conn, id, ws_b, "other", None).unwrap();
+ ensure_project_with_id(&mut conn, id, ws_b, "other", None, None).unwrap();
let logs = capture_warnings(|| {
- let err = ensure_project_with_id(&mut conn, id, ws_b, "shared", None)
+ let err = ensure_project_with_id(&mut conn, id, ws_b, "shared", None, None)
.expect_err("same id with different name must fail validation");
assert!(
matches!(err, StoreError::Duplicate(_)),
@@ -13637,9 +13843,9 @@ pub(crate) mod tests {
let (_tmp, mut conn, ws, _proj) = fresh_db();
let id = ProjectId::new();
- ensure_project_with_id(&mut conn, id, ws, "from-manifest", Some("/repo/a")).unwrap();
- let err =
- ensure_project_with_id(&mut conn, id, ws, "renamed", Some("/repo/a")).unwrap_err();
+ ensure_project_with_id(&mut conn, id, ws, "from-manifest", Some("/repo/a"), None).unwrap();
+ let err = ensure_project_with_id(&mut conn, id, ws, "renamed", Some("/repo/a"), None)
+ .unwrap_err();
assert!(
matches!(err, StoreError::Duplicate(_)),
diff --git a/crates/ai-memory-store/src/project_coordinates.rs b/crates/ai-memory-store/src/project_coordinates.rs
new file mode 100644
index 00000000..cc4e0b1c
--- /dev/null
+++ b/crates/ai-memory-store/src/project_coordinates.rs
@@ -0,0 +1,204 @@
+//! Private indexed matching for static workspace/project coordinates.
+
+use ai_memory_core::repository_identity::{
+ IdentitySource, RepositoryIdentity, legacy_basename_name, path_style_name,
+};
+use ai_memory_core::{ProjectId, WorkspaceId};
+use rusqlite::{Connection, params};
+
+use 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";
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ProjectCoordinateMatch {
+ pub(crate) id: ProjectId,
+ pub(crate) current_name: String,
+ pub(crate) canonical_name: Option<String>,
+}
+
+pub(crate) fn resolve(
+ conn: &Connection,
+ workspace_id: WorkspaceId,
+ requested: &str,
+) -> StoreResult<Option<ProjectCoordinateMatch>> {
+ 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)?,
+ ))
+ })?
+ .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);
+ }
+ }
+ match matches.len() {
+ 0 => Ok(None),
+ 1 => Ok(matches.pop()),
+ _ => Err(StoreError::ProjectNameAmbiguous(requested.to_owned())),
+ }
+}
+
+pub(crate) fn backfill(conn: &mut Connection) -> StoreResult<u64> {
+ let mut updated = 0_u64;
+ loop {
+ let tx = conn.transaction()?;
+ let rows = {
+ let mut statement = tx.prepare(
+ "SELECT id, identity FROM projects INDEXED BY idx_projects_coordinate_backfill \
+ WHERE identity_source = 'git_remote' AND identity <> '' \
+ AND (canonical_name = '' OR legacy_name = '') LIMIT 256",
+ )?;
+ statement
+ .query_map([], |row| {
+ Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, String>(1)?))
+ })?
+ .collect::<rusqlite::Result<Vec<_>>>()?
+ };
+ if rows.is_empty() {
+ return Ok(updated);
+ }
+ for (raw_id, identity) in rows {
+ let remote = RepositoryIdentity {
+ identity,
+ source: IdentitySource::GitRemote,
+ };
+ let canonical_name = path_style_name(&remote).ok_or_else(|| {
+ StoreError::MalformedRecord("remote has no canonical name".into())
+ })?;
+ let legacy_name = legacy_basename_name(&remote)
+ .ok_or_else(|| StoreError::MalformedRecord("remote has no basename".into()))?;
+ updated += u64::try_from(tx.execute(
+ "UPDATE projects SET canonical_name = ?1, legacy_name = ?2 WHERE id = ?3",
+ params![canonical_name, legacy_name, raw_id],
+ )?)
+ .unwrap_or(0);
+ }
+ tx.commit()?;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn candidate_query_is_bounded_and_uses_only_coordinate_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,
+ )
+ .unwrap();
+ }
+ let plan: Vec<String> = conn
+ .prepare(&format!("EXPLAIN QUERY PLAN {MATCH_SQL}"))
+ .unwrap()
+ .query_map(
+ params![
+ workspace.as_bytes(),
+ "acme-api",
+ i64::try_from(MAX_COORDINATE_ROWS).unwrap()
+ ],
+ |row| row.get(3),
+ )
+ .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_eq!(
+ statement.get_status(rusqlite::StatementStatus::FullscanStep),
+ 0
+ );
+ 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"))
+ );
+ 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 fad5e019..b16702ba 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1488,6 +1488,14 @@ pub struct ScopeRow {
pub project_name: String,
/// Filesystem path the project's cwd-based routing resolves to, if any.
pub repo_path: Option<String>,
+ /// Stable hostful repository identity, when the project has one.
+ pub identity: Option<String>,
+ /// Source spelling for `identity`, when present.
+ pub identity_source: Option<String>,
+ /// Canonical path-style compatibility key derived from the identity.
+ pub canonical_name: Option<String>,
+ /// Legacy basename compatibility key derived from the identity.
+ pub legacy_name: Option<String>,
}
/// One row per workspace with aggregate stats.
@@ -7933,31 +7941,62 @@ impl ReaderPool {
workspace_id: WorkspaceId,
project_id: ProjectId,
) -> StoreResult<Option<ScopeRow>> {
- // (ws_name, proj_name, repo_path) — the ids are already known.
- type RawScope = (String, String, Option<String>);
+ type RawScope = (
+ String,
+ String,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ );
let raw: Option<RawScope> = self
.with_conn(move |conn| {
let row = conn
.query_row(
- "SELECT w.name, p.name, p.repo_path \
+ "SELECT w.name, p.name, p.repo_path, NULLIF(p.identity, ''), \
+ NULLIF(p.identity_source, ''), NULLIF(p.canonical_name, ''), \
+ NULLIF(p.legacy_name, '') \
FROM projects p JOIN workspaces w ON w.id = p.workspace_id \
WHERE p.id = ?1 AND p.workspace_id = ?2",
params![project_id.as_bytes(), workspace_id.as_bytes()],
- |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ |row| {
+ Ok((
+ row.get(0)?,
+ row.get(1)?,
+ row.get(2)?,
+ row.get(3)?,
+ row.get(4)?,
+ row.get(5)?,
+ row.get(6)?,
+ ))
+ },
)
.optional()?;
Ok(row)
})
.await?;
- Ok(
- raw.map(|(workspace_name, project_name, repo_path)| ScopeRow {
+ Ok(raw.map(
+ |(
+ workspace_name,
+ project_name,
+ repo_path,
+ identity,
+ identity_source,
+ canonical_name,
+ legacy_name,
+ )| ScopeRow {
workspace_id,
workspace_name,
project_id,
project_name,
repo_path,
- }),
- )
+ identity,
+ identity_source,
+ canonical_name,
+ legacy_name,
+ },
+ ))
}
/// Return every `(workspace, project)` scope with its ids, names and
@@ -7968,12 +8007,23 @@ impl ReaderPool {
/// # Errors
/// Propagates any SQL or pool error.
pub async fn list_all_scopes(&self) -> StoreResult<Vec<ScopeRow>> {
- // (ws_id, ws_name, proj_id, proj_name, repo_path) as raw SQL columns.
- type RawScope = (Vec<u8>, String, Vec<u8>, String, Option<String>);
+ type RawScope = (
+ Vec<u8>,
+ String,
+ Vec<u8>,
+ String,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ );
let raw: Vec<RawScope> = self
.with_conn(|conn| {
let mut stmt = conn.prepare(
- "SELECT w.id, w.name, p.id, p.name, p.repo_path \
+ "SELECT w.id, w.name, p.id, p.name, p.repo_path, \
+ NULLIF(p.identity, ''), NULLIF(p.identity_source, ''), \
+ NULLIF(p.canonical_name, ''), NULLIF(p.legacy_name, '') \
FROM projects p JOIN workspaces w ON w.id = p.workspace_id",
)?;
let rows = stmt.query_map([], |row| {
@@ -7983,6 +8033,10 @@ impl ReaderPool {
row.get(2)?,
row.get(3)?,
row.get(4)?,
+ row.get(5)?,
+ row.get(6)?,
+ row.get(7)?,
+ row.get(8)?,
))
})?;
let out: rusqlite::Result<Vec<_>> = rows.collect();
@@ -7990,15 +8044,21 @@ impl ReaderPool {
})
.await?;
raw.into_iter()
- .map(|(wi, wn, pi, pn, rp)| {
- Ok(ScopeRow {
- workspace_id: WorkspaceId::from_slice(&wi)?,
- workspace_name: wn,
- project_id: ProjectId::from_slice(&pi)?,
- project_name: pn,
- repo_path: rp,
- })
- })
+ .map(
+ |(wi, wn, pi, pn, rp, identity, identity_source, canonical_name, legacy_name)| {
+ Ok(ScopeRow {
+ workspace_id: WorkspaceId::from_slice(&wi)?,
+ workspace_name: wn,
+ project_id: ProjectId::from_slice(&pi)?,
+ project_name: pn,
+ repo_path: rp,
+ identity,
+ identity_source,
+ canonical_name,
+ legacy_name,
+ })
+ },
+ )
.collect()
}
@@ -8951,6 +9011,20 @@ impl ReaderPool {
.await
}
+ /// Resolve an existing project by its exact, canonical path-style, or v2
+ /// legacy basename key without creating or renaming anything.
+ pub(crate) async fn resolve_existing_project_name(
+ &self,
+ workspace_id: WorkspaceId,
+ name: String,
+ ) -> StoreResult<Option<ProjectId>> {
+ self.with_conn(move |conn| {
+ crate::project_coordinates::resolve(conn, workspace_id, &name)
+ .map(|matched| matched.map(|matched| matched.id))
+ })
+ .await
+ }
+
/// Find the existing project whose `repo_path` is the longest
/// prefix of `cwd`, if any. Used by the hook router before
/// auto-creating a new project from `basename(cwd)` so an event
@@ -11137,6 +11211,10 @@ mod tests {
assert_eq!(row.workspace_name, "acme");
assert_eq!(row.project_name, "webapp");
assert_eq!(row.repo_path.as_deref(), Some("/repo/webapp"));
+ assert!(row.identity.is_none());
+ assert!(row.identity_source.is_none());
+ assert!(row.canonical_name.is_none());
+ assert!(row.legacy_name.is_none());
assert!(
store
diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rs
index 147622d9..2214e610 100644
--- a/crates/ai-memory-store/src/scope.rs
+++ b/crates/ai-memory-store/src/scope.rs
@@ -55,6 +55,15 @@ pub struct ResolvedScope {
pub project_id: ProjectId,
}
+/// Result of write-scope resolution, including a committed name promotion.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ResolvedWriteScope {
+ /// Stable workspace/project ids selected for the write.
+ pub scope: ResolvedScope,
+ /// Previous name when this resolution promoted the row in place.
+ pub promoted_from: Option<String>,
+}
+
impl ResolvedScope {
/// Return the ids as the tuple used by existing reader/writer APIs.
#[must_use]
@@ -167,6 +176,13 @@ pub enum ScopeResolutionError {
/// Project name supplied by the caller.
project: String,
},
+ /// A compatibility key matched more than one project in the workspace.
+ ProjectNameAmbiguous {
+ /// Workspace name supplied by the caller.
+ workspace: String,
+ /// Project name supplied by the caller.
+ project: String,
+ },
/// A project-only read did not resolve in either the actor's active
/// workspace or the server's default workspace.
ProjectNotFoundInActiveOrDefault {
@@ -196,6 +212,7 @@ impl ScopeResolutionError {
| ScopeResolutionError::ScopeWorkspaceEmpty
| ScopeResolutionError::ScopeProjectEmpty
| ScopeResolutionError::TooManyScopes { .. }
+ | ScopeResolutionError::ProjectNameAmbiguous { .. }
| ScopeResolutionError::AmbiguousUnscopedWrite
)
}
@@ -242,6 +259,12 @@ impl fmt::Display for ScopeResolutionError {
"project '{project}' not found in workspace '{workspace}'"
)
}
+ ScopeResolutionError::ProjectNameAmbiguous { workspace, project } => {
+ write!(
+ f,
+ "project '{project}' is ambiguous in workspace '{workspace}'"
+ )
+ }
ScopeResolutionError::ProjectNotFoundInActiveOrDefault { project } => {
write!(
f,
@@ -265,6 +288,19 @@ impl From<StoreError> for ScopeResolutionError {
}
}
+fn project_lookup_error(error: StoreError, workspace: &str, project: &str) -> ScopeResolutionError {
+ match error {
+ StoreError::ProjectNameAmbiguous(_) => ScopeResolutionError::ProjectNameAmbiguous {
+ workspace: workspace.to_owned(),
+ project: project.to_owned(),
+ },
+ StoreError::Forbidden(message) => ScopeResolutionError::Forbidden(format!(
+ "not authorized for {project}: this needs write access. {message}"
+ )),
+ other => other.into(),
+ }
+}
+
/// Resolves workspace/project names according to the policy requested by the
/// caller. Construct per request; it only borrows existing handles.
pub struct ScopeResolver<'a> {
@@ -294,8 +330,9 @@ pub async fn lookup_existing_scope(
) -> Result<ResolvedScope, ScopeResolutionError> {
let workspace_id = lookup_existing_workspace(reader, workspace).await?;
let project_id = reader
- .find_project(workspace_id, project.to_owned())
- .await?
+ .resolve_existing_project_name(workspace_id, project.to_owned())
+ .await
+ .map_err(|error| project_lookup_error(error, workspace, project))?
.ok_or_else(|| ScopeResolutionError::ProjectNotFoundInWorkspace {
workspace: workspace.to_owned(),
project: project.to_owned(),
@@ -330,14 +367,18 @@ pub async fn create_explicit_scope(
writer: &WriterHandle,
workspace: &str,
project: &str,
-) -> Result<ResolvedScope, ScopeResolutionError> {
+) -> Result<ResolvedWriteScope, ScopeResolutionError> {
let workspace_id = writer.get_or_create_workspace(workspace.to_owned()).await?;
- let project_id = writer
- .get_or_create_project(workspace_id, project.to_owned(), None)
- .await?;
- Ok(ResolvedScope {
- workspace_id,
- project_id,
+ let resolved = writer
+ .resolve_project_name_for_write(workspace_id, project.to_owned(), None, false)
+ .await
+ .map_err(|error| project_lookup_error(error, workspace, project))?;
+ Ok(ResolvedWriteScope {
+ scope: ResolvedScope {
+ workspace_id,
+ project_id: resolved.project_id,
+ },
+ promoted_from: resolved.promoted_from,
})
}
@@ -469,6 +510,8 @@ pub async fn lookup_existing_scope_guarded(
}
/// [`create_explicit_scope`] on behalf of `viewer`, authorized for a write.
+/// Returns promotion metadata that the runtime caller must use to refresh the
+/// scope manifest after the SQL transaction commits.
///
/// A project this call creates records `viewer` as its creator in the same
/// transaction, and the choke point admits a creator, so they can write to and
@@ -485,10 +528,11 @@ pub async fn create_explicit_scope_guarded(
workspace: &str,
project: &str,
viewer: Option<UserId>,
-) -> Result<ResolvedScope, ScopeResolutionError> {
+) -> Result<ResolvedWriteScope, ScopeResolutionError> {
+ let _ = reader;
refuse_foreign_profile_name(Some(workspace), project, viewer)?;
let workspace_id = writer.get_or_create_workspace(workspace.to_owned()).await?;
- create_project_in_workspace_guarded(reader, writer, workspace_id, project, viewer).await
+ create_project_in_workspace_guarded(writer, workspace_id, project, viewer, true).await
}
/// Refusal for an explicit write that names a profile project it does not own.
@@ -528,20 +572,47 @@ fn refuse_foreign_profile_name(
/// [`create_explicit_scope_guarded`] for a workspace already resolved by id.
async fn create_project_in_workspace_guarded(
- reader: &ReaderPool,
writer: &WriterHandle,
workspace_id: WorkspaceId,
project: &str,
viewer: Option<UserId>,
-) -> Result<ResolvedScope, ScopeResolutionError> {
- let (project_id, _) = writer
- .get_or_create_project_as(workspace_id, project.to_owned(), None, viewer)
- .await?;
+ promote: bool,
+) -> Result<ResolvedWriteScope, ScopeResolutionError> {
+ let principal = viewer.map(ProjectPrincipal::user);
+ let resolved = if promote {
+ writer
+ .resolve_project_name_for_write(
+ workspace_id,
+ project.to_owned(),
+ principal,
+ viewer.is_some(),
+ )
+ .await
+ } else {
+ writer
+ .resolve_project_name_for_write_without_promotion(
+ workspace_id,
+ project.to_owned(),
+ principal,
+ viewer.is_some(),
+ )
+ .await
+ }
+ .map_err(|error| project_lookup_error(error, "the resolved workspace", project))?;
let scope = ResolvedScope {
workspace_id,
- project_id,
+ project_id: resolved.project_id,
};
- authorize_scope_for(reader, Some(writer), scope, viewer, ProjectAccess::Write).await
+ if let Some(error) = resolved.authorization_error {
+ return Err(ScopeResolutionError::Forbidden(format!(
+ "not authorized for {project}: this needs write access. {}",
+ error.message()
+ )));
+ }
+ Ok(ResolvedWriteScope {
+ scope,
+ promoted_from: resolved.promoted_from,
+ })
}
/// Refusal for a private-profile request that carries no database user: a
@@ -619,7 +690,7 @@ pub async fn lookup_profile_scope(
/// private profile is requested without a database user; store failures
/// otherwise.
pub async fn create_profile_scope(
- reader: &ReaderPool,
+ _reader: &ReaderPool,
writer: &WriterHandle,
share: ai_memory_core::profile::EffectiveProfileShare,
workspace_id: WorkspaceId,
@@ -628,39 +699,46 @@ pub async fn create_profile_scope(
use ai_memory_core::profile::{EffectiveProfileShare, WORKSPACE_PROFILE_PROJECT};
match share {
EffectiveProfileShare::Global => {
- create_explicit_scope_guarded(
- reader,
- writer,
- ai_memory_core::DEFAULT_WORKSPACE_NAME,
- ai_memory_core::GLOBAL_SCOPE_PROJECT,
- viewer,
- )
- .await
- }
- EffectiveProfileShare::Workspace => {
+ let workspace_id = writer
+ .get_or_create_workspace(ai_memory_core::DEFAULT_WORKSPACE_NAME.to_owned())
+ .await?;
create_project_in_workspace_guarded(
- reader,
writer,
workspace_id,
- WORKSPACE_PROFILE_PROJECT,
+ ai_memory_core::GLOBAL_SCOPE_PROJECT,
viewer,
+ false,
)
.await
+ .map(|resolved| resolved.scope)
}
+ EffectiveProfileShare::Workspace => create_project_in_workspace_guarded(
+ writer,
+ workspace_id,
+ WORKSPACE_PROFILE_PROJECT,
+ viewer,
+ false,
+ )
+ .await
+ .map(|resolved| resolved.scope),
EffectiveProfileShare::User => {
let Some(viewer) = viewer else {
return Err(ScopeResolutionError::Forbidden(
PRIVATE_PROFILE_NEEDS_USER.to_owned(),
));
};
- create_explicit_scope_guarded(
- reader,
+ let workspace_id = writer
+ .get_or_create_workspace(ai_memory_core::DEFAULT_WORKSPACE_NAME.to_owned())
+ .await?;
+ create_project_in_workspace_guarded(
writer,
- ai_memory_core::DEFAULT_WORKSPACE_NAME,
+ workspace_id,
&ai_memory_core::profile::user_profile_project(viewer),
Some(viewer),
+ false,
)
.await
+ .map(|resolved| resolved.scope)
}
}
}
@@ -735,12 +813,22 @@ pub async fn lookup_global_scope(
pub async fn create_global_scope(
writer: &WriterHandle,
) -> Result<ResolvedScope, ScopeResolutionError> {
- create_explicit_scope(
- writer,
- ai_memory_core::DEFAULT_WORKSPACE_NAME,
- ai_memory_core::GLOBAL_SCOPE_PROJECT,
- )
- .await
+ let workspace = ai_memory_core::DEFAULT_WORKSPACE_NAME;
+ let project = ai_memory_core::GLOBAL_SCOPE_PROJECT;
+ let workspace_id = writer.get_or_create_workspace(workspace.to_owned()).await?;
+ let resolved = writer
+ .resolve_project_name_for_write_without_promotion(
+ workspace_id,
+ project.to_owned(),
+ None,
+ false,
+ )
+ .await
+ .map_err(|error| project_lookup_error(error, workspace, project))?;
+ Ok(ResolvedScope {
+ workspace_id,
+ project_id: resolved.project_id,
+ })
}
/// Resolve and de-duplicate explicit multi-scope names without creating
@@ -858,6 +946,29 @@ impl<'a> ScopeResolver<'a> {
lookup_existing_scope(self.reader, workspace, project).await
}
+ async fn resolve_named_in_workspace(
+ &self,
+ workspace_id: WorkspaceId,
+ workspace: &str,
+ project: &str,
+ need: ProjectAccess,
+ ) -> Result<Option<ResolvedScope>, ScopeResolutionError> {
+ let project_id = self
+ .reader
+ .resolve_existing_project_name(workspace_id, project.to_owned())
+ .await
+ .map_err(|error| project_lookup_error(error, workspace, project))?;
+ let Some(project_id) = project_id else {
+ return Ok(None);
+ };
+ let scope = ResolvedScope {
+ workspace_id,
+ project_id,
+ };
+ self.authorize_scope(scope, need).await?;
+ Ok(Some(scope))
+ }
+
/// Resolve MCP-style read arguments: explicit pair if both names are
/// provided, reject partial pair, otherwise use project-only lookup or the
/// current-project/default fallback chain.
@@ -926,8 +1037,14 @@ impl<'a> ScopeResolver<'a> {
trimmed_opt(explicit_project),
) {
(Some(workspace), Some(project)) => {
- let scope = self.lookup_existing(workspace, project).await?;
- self.authorize_scope(scope, need).await?;
+ let workspace_id = lookup_existing_workspace(self.reader, workspace).await?;
+ let scope = self
+ .resolve_named_in_workspace(workspace_id, workspace, project, need)
+ .await?
+ .ok_or_else(|| ScopeResolutionError::ProjectNotFoundInWorkspace {
+ workspace: workspace.to_owned(),
+ project: project.to_owned(),
+ })?;
Ok((scope, ScopeSource::Explicit))
}
(Some(_), None) => Err(ScopeResolutionError::WorkspaceProjectPairRequired),
@@ -975,29 +1092,22 @@ impl<'a> ScopeResolver<'a> {
let active = pointer.ids();
if let Some(project) = trimmed_opt(explicit_project) {
if let Some((active_ws, _)) = active
- && let Some(project_id) = self
- .reader
- .find_project(active_ws, project.to_owned())
+ && let Some(scope) = self
+ .resolve_named_in_workspace(active_ws, "the active workspace", project, need)
.await?
{
- let scope = ResolvedScope {
- workspace_id: active_ws,
- project_id,
- };
- self.authorize_scope(scope, need).await?;
return Ok((scope, ScopeSource::Explicit));
}
if active.map(|(ws, _)| ws) != Some(self.default_workspace_id)
- && let Some(project_id) = self
- .reader
- .find_project(self.default_workspace_id, project.to_owned())
+ && let Some(scope) = self
+ .resolve_named_in_workspace(
+ self.default_workspace_id,
+ "the default workspace",
+ project,
+ need,
+ )
.await?
{
- let scope = ResolvedScope {
- workspace_id: self.default_workspace_id,
- project_id,
- };
- self.authorize_scope(scope, need).await?;
return Ok((scope, ScopeSource::Explicit));
}
return Err(ScopeResolutionError::ProjectNotFoundInActiveOrDefault {
@@ -1021,7 +1131,7 @@ impl<'a> ScopeResolver<'a> {
explicit_workspace: Option<&str>,
explicit_project: Option<&str>,
actor: &ActorKey,
- ) -> Result<ResolvedScope, ScopeResolutionError> {
+ ) -> Result<ResolvedWriteScope, ScopeResolutionError> {
let Some(project) = trimmed_opt(explicit_project) else {
if trimmed_opt(explicit_workspace).is_some() {
return Err(ScopeResolutionError::WorkspaceProjectPairRequired);
@@ -1048,7 +1158,10 @@ impl<'a> ScopeResolver<'a> {
project_id,
};
self.authorize_scope(scope, ProjectAccess::Write).await?;
- return Ok(scope);
+ return Ok(ResolvedWriteScope {
+ scope,
+ promoted_from: None,
+ });
};
let Some(writer) = self.writer else {
return Err(ScopeResolutionError::WriterRequired);
@@ -1060,20 +1173,37 @@ impl<'a> ScopeResolver<'a> {
.map(|(workspace_id, _)| workspace_id)
.unwrap_or(self.default_workspace_id),
};
- // A project this call creates records the caller as its creator, whom
- // the choke point below then admits; one that already existed is
- // decided like any other write, so "create" is never a way in.
let creator = self.authz.as_ref().and_then(|principal| principal.user_id);
refuse_foreign_profile_name(trimmed_opt(explicit_workspace), project, creator)?;
- let (project_id, _) = writer
- .get_or_create_project_as(workspace_id, project.to_owned(), None, creator)
- .await?;
+ let resolved = writer
+ .resolve_project_name_for_write(
+ workspace_id,
+ project.to_owned(),
+ self.authz.clone(),
+ self.distinguishes_operators,
+ )
+ .await
+ .map_err(|error| {
+ project_lookup_error(
+ error,
+ trimmed_opt(explicit_workspace).unwrap_or("the active workspace"),
+ project,
+ )
+ })?;
let scope = ResolvedScope {
workspace_id,
- project_id,
+ project_id: resolved.project_id,
};
- self.authorize_scope(scope, ProjectAccess::Write).await?;
- Ok(scope)
+ if let Some(error) = resolved.authorization_error {
+ return Err(ScopeResolutionError::Forbidden(format!(
+ "not authorized for {project}: this needs write access. {}",
+ error.message()
+ )));
+ }
+ Ok(ResolvedWriteScope {
+ scope,
+ promoted_from: resolved.promoted_from,
+ })
}
/// Resolve and de-duplicate an explicit multi-scope list, every scope
@@ -1284,12 +1414,12 @@ mod tests {
// A project that does not exist yet is created with Bob as its
// creator, who is admitted without any grant.
let fresh = create("brand-new", bob).await.unwrap();
- assert_eq!(fresh.workspace_id, ws);
- assert_eq!(created_by(&store, fresh.project_id), Some(bob));
+ assert_eq!(fresh.scope.workspace_id, ws);
+ assert_eq!(created_by(&store, fresh.scope.project_id), Some(bob));
assert!(
store
.reader
- .grants_for(bob, fresh.project_id)
+ .grants_for(bob, fresh.scope.project_id)
.await
.unwrap()
.is_empty(),
@@ -1308,7 +1438,7 @@ mod tests {
// A second "create" of the same name by someone else is a write to an
// existing project: refused, and it does not make them its creator.
assert!(create("brand-new", alice).await.unwrap_err().is_forbidden());
- assert_eq!(created_by(&store, fresh.project_id), Some(bob));
+ assert_eq!(created_by(&store, fresh.scope.project_id), Some(bob));
}
/// With no viewer — root, or an install with no database users — a created
@@ -1327,7 +1457,7 @@ mod tests {
)
.await
.unwrap();
- assert_eq!(created_by(&store, fresh.project_id), None);
+ assert_eq!(created_by(&store, fresh.scope.project_id), None);
}
/// The MCP write path creates through the resolver, not the free function,
@@ -1344,7 +1474,7 @@ mod tests {
.resolve_write_args(Some("default"), Some("bobs-repo"), &actor)
.await
.unwrap();
- assert_eq!(created_by(&store, created.project_id), Some(bob));
+ assert_eq!(created_by(&store, created.scope.project_id), Some(bob));
as_bob
.resolve_write_args(Some("default"), Some("bobs-repo"), &actor)
.await
@@ -1532,7 +1662,7 @@ mod tests {
.resolve_write_args(None, Some("new-project"), &actor)
.await
.unwrap();
- assert_eq!(created.workspace_id, active_ws);
+ assert_eq!(created.scope.workspace_id, active_ws);
assert!(
store
.reader
@@ -1548,7 +1678,7 @@ mod tests {
.find_project(active_ws, "new-project".into())
.await
.unwrap(),
- Some(created.project_id)
+ Some(created.scope.project_id)
);
}
@@ -1866,7 +1996,7 @@ mod tests {
lookup_existing_scope(&store.reader, "ghost", "app")
.await
.unwrap(),
- created
+ created.scope
);
// Multi-scope resolution keeps same-named projects in their own
@@ -1995,7 +2125,7 @@ mod tests {
.resolve_write_args(None, None, &ActorKey::default())
.await
.unwrap();
- assert_eq!(scope.as_tuple(), (team_ws, team_proj));
+ assert_eq!(scope.scope.as_tuple(), (team_ws, team_proj));
}
#[tokio::test]
@@ -2021,7 +2151,7 @@ mod tests {
.resolve_write_args(None, None, &actor)
.await
.unwrap();
- assert_eq!(scope.as_tuple(), (default_ws, default_proj));
+ assert_eq!(scope.scope.as_tuple(), (default_ws, default_proj));
}
#[tokio::test]
@@ -2044,7 +2174,7 @@ mod tests {
.resolve_write_args(None, None, &actor)
.await
.unwrap();
- assert_eq!(scope.as_tuple(), (team_ws, team_proj));
+ assert_eq!(scope.scope.as_tuple(), (team_ws, team_proj));
}
#[tokio::test]
@@ -2117,7 +2247,7 @@ mod tests {
.await
.unwrap();
assert_eq!(
- write.as_tuple(),
+ write.scope.as_tuple(),
(default_ws, default_proj),
"write target must be exactly what it was before the seed existed"
);
diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rs
index cba4bbac..87227430 100644
--- a/crates/ai-memory-store/src/workstream.rs
+++ b/crates/ai-memory-store/src/workstream.rs
@@ -30,6 +30,16 @@ pub enum WorkstreamSelection {
New(String),
}
+impl WorkstreamSelection {
+ /// Validate caller-controlled selection data before any scope mutation.
+ pub fn validate(&self) -> StoreResult<()> {
+ match self {
+ Self::Current => Ok(()),
+ Self::Named(name) | Self::New(name) => validate_workstream_name(name),
+ }
+ }
+}
+
/// Authenticated authority for a managed-run mutation: finish (its preflight
/// and its import transaction), cancel, heartbeat, native-session link and
/// context acceptance.
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 96df9c5c..a5369124 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -109,6 +109,14 @@ pub(crate) enum WriteCmd {
creator: Option<ai_memory_core::UserId>,
reply: oneshot::Sender<StoreResult<(ProjectId, ops::IdentityResolution)>>,
},
+ ResolveProjectNameForWrite {
+ workspace_id: WorkspaceId,
+ name: String,
+ principal: Option<crate::ProjectPrincipal>,
+ distinguishes_operators: bool,
+ promote: bool,
+ reply: oneshot::Sender<StoreResult<ops::ProjectNameWriteResolution>>,
+ },
EnsureProjectWorkspace {
workspace_id: WorkspaceId,
project_id: ProjectId,
@@ -124,6 +132,7 @@ pub(crate) enum WriteCmd {
workspace_id: WorkspaceId,
name: String,
repo_path: Option<String>,
+ identity: Option<ai_memory_core::repository_identity::RepositoryIdentity>,
reply: oneshot::Sender<StoreResult<()>>,
},
ScopeIsPurged {
@@ -1072,6 +1081,61 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ pub(crate) async fn resolve_project_name_for_write(
+ &self,
+ workspace_id: WorkspaceId,
+ name: impl Into<String>,
+ principal: Option<crate::ProjectPrincipal>,
+ distinguishes_operators: bool,
+ ) -> StoreResult<ops::ProjectNameWriteResolution> {
+ self.resolve_project_name_for_write_mode(
+ workspace_id,
+ name,
+ principal,
+ distinguishes_operators,
+ true,
+ )
+ .await
+ }
+
+ pub(crate) async fn resolve_project_name_for_write_without_promotion(
+ &self,
+ workspace_id: WorkspaceId,
+ name: impl Into<String>,
+ principal: Option<crate::ProjectPrincipal>,
+ distinguishes_operators: bool,
+ ) -> StoreResult<ops::ProjectNameWriteResolution> {
+ self.resolve_project_name_for_write_mode(
+ workspace_id,
+ name,
+ principal,
+ distinguishes_operators,
+ false,
+ )
+ .await
+ }
+
+ async fn resolve_project_name_for_write_mode(
+ &self,
+ workspace_id: WorkspaceId,
+ name: impl Into<String>,
+ principal: Option<crate::ProjectPrincipal>,
+ distinguishes_operators: bool,
+ promote: bool,
+ ) -> StoreResult<ops::ProjectNameWriteResolution> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::ResolveProjectNameForWrite {
+ workspace_id,
+ name: name.into(),
+ principal,
+ distinguishes_operators,
+ promote,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Assert that a project still belongs to the supplied workspace.
///
/// # Errors
@@ -1125,6 +1189,7 @@ impl WriterHandle {
workspace_id: WorkspaceId,
name: impl Into<String>,
repo_path: Option<String>,
+ identity: Option<ai_memory_core::repository_identity::RepositoryIdentity>,
) -> StoreResult<()> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::EnsureProjectWithId {
@@ -1132,6 +1197,7 @@ impl WriterHandle {
workspace_id,
name: name.into(),
repo_path,
+ identity,
reply: tx,
})
.await?;
@@ -3458,6 +3524,25 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
);
send_or_warn(reply, result, "resolve_project_by_identity");
}
+ WriteCmd::ResolveProjectNameForWrite {
+ workspace_id,
+ name,
+ principal,
+ distinguishes_operators,
+ promote,
+ reply,
+ } => {
+ let result = ops::resolve_project_name_for_write(
+ &mut conn,
+ &workspace_id,
+ &name,
+ principal.as_ref(),
+ distinguishes_operators,
+ promote,
+ new_project_mode,
+ );
+ send_or_warn(reply, result, "resolve_project_name_for_write");
+ }
WriteCmd::EnsureProjectWorkspace {
workspace_id,
project_id,
@@ -3475,6 +3560,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
workspace_id,
name,
repo_path,
+ identity,
reply,
} => {
let result = ops::ensure_project_with_id(
@@ -3483,6 +3569,7 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
workspace_id,
&name,
repo_path.as_deref(),
+ identity.as_ref(),
);
send_or_warn(reply, result, "ensure_project_with_id");
}
diff --git a/crates/ai-memory-store/tests/suite/identity_resolution.rs b/crates/ai-memory-store/tests/suite/identity_resolution.rs
index e5fee4e2..c2d44d9e 100644
--- a/crates/ai-memory-store/tests/suite/identity_resolution.rs
+++ b/crates/ai-memory-store/tests/suite/identity_resolution.rs
@@ -9,9 +9,14 @@
//! who may not write to it cannot take its identity.
use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
-use ai_memory_core::{NewUser, ProjectId, UserId, WorkspaceId};
+use ai_memory_core::{
+ AgentKind, NewHandoff, NewPage, NewSession, NewUser, OwnerFilter, PagePath, ProjectId,
+ SessionId, Tier, UserId, WorkspaceId,
+};
use ai_memory_store::{
- AccessMode, GrantLevel, IdentityResolution, ProjectAccess, ProjectPrincipal, Store,
+ AccessMode, GrantLevel, IdentityResolution, ProjectAccess, ProjectPrincipal, ScopeName,
+ ScopeResolutionError, Store, create_explicit_scope_guarded, lookup_existing_scope,
+ lookup_existing_scope_guarded, resolve_many_existing_scopes,
};
fn remote(identity: &str) -> RepositoryIdentity {
@@ -513,6 +518,468 @@ async fn the_path_style_leaves_a_declared_identity_named_as_sent() {
assert_eq!(row(&store, id).0, "platform");
}
+fn preserved_page(ws: WorkspaceId, project: ProjectId) -> NewPage {
+ NewPage {
+ workspace_id: ws,
+ project_id: project,
+ path: PagePath::new("notes/preserved.md").unwrap(),
+ title: "Preserved".into(),
+ body: "preserved page".into(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: Vec::new(),
+ author_id: None,
+ expires_at: None,
+ entities: Vec::new(),
+ evidence: Vec::new(),
+ }
+}
+
+#[tokio::test]
+async fn canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let project = resolve(&store, ws, &remote("github.com/acme/api"), "api", None)
+ .await
+ .0;
+ for name in ["api", "acme-api"] {
+ assert_eq!(
+ lookup_existing_scope(&store.reader, "default", name)
+ .await
+ .unwrap()
+ .project_id,
+ project
+ );
+ }
+ assert_eq!(row(&store, project).0, "api");
+
+ let deduplicated = resolve_many_existing_scopes(
+ &store.reader,
+ &[
+ ScopeName::new("default", "api"),
+ ScopeName::new("default", "acme-api"),
+ ],
+ 10,
+ )
+ .await
+ .unwrap();
+ assert_eq!(deduplicated.len(), 1);
+ assert_eq!(deduplicated[0].project_id, project);
+}
+
+#[tokio::test]
+async fn authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let owner = user(&store, "promotion-owner", 7).await;
+ let project = resolve(
+ &store,
+ ws,
+ &remote("github.com/acme/api"),
+ "api",
+ Some(owner),
+ )
+ .await
+ .0;
+ store
+ .writer
+ .upsert_page(preserved_page(ws, project))
+ .await
+ .unwrap();
+ let session = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ occurred_at: None,
+ id: session,
+ workspace_id: ws,
+ project_id: project,
+ agent_kind: AgentKind::Codex,
+ cwd: Some("/clone/api".into()),
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(owner, project, GrantLevel::Write, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: project,
+ from_session_id: Some(session),
+ from_agent: AgentKind::Codex,
+ to_agent: None,
+ cwd: Some("/clone/api".into()),
+ summary: "continue".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+
+ let promoted = create_explicit_scope_guarded(
+ &store.reader,
+ &store.writer,
+ "default",
+ "acme-api",
+ Some(owner),
+ )
+ .await
+ .unwrap();
+ assert_eq!(promoted.scope.project_id, project);
+ assert_eq!(row(&store, project).0, "acme-api");
+ let audit: (i64, Option<Vec<u8>>, String) = rusqlite::Connection::open(store.db_path())
+ .unwrap()
+ .query_row(
+ "SELECT COUNT(*), MAX(author_id), MAX(detail) FROM audit_log \
+ WHERE op = 'promote_project_name' AND project_id = ?1",
+ [project.as_bytes().to_vec()],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ )
+ .unwrap();
+ assert_eq!(audit.0, 1);
+ assert_eq!(audit.1.as_deref(), Some(owner.as_bytes().as_slice()));
+ assert!(audit.2.contains("\"from\":\"api\""));
+ assert!(audit.2.contains("\"to\":\"acme-api\""));
+ assert!(
+ store
+ .reader
+ .page_body_by_ids(ws, project, "notes/preserved.md")
+ .await
+ .unwrap()
+ .is_some()
+ );
+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
+ for table in ["sessions", "project_grants", "handoffs"] {
+ let count: i64 = conn
+ .query_row(
+ &format!("SELECT COUNT(*) FROM {table} WHERE project_id = ?1"),
+ [project.as_bytes().to_vec()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(count, 1, "{table}");
+ }
+ assert_eq!(
+ store
+ .reader
+ .list_handoffs(ws, project, None, OwnerFilter::Any, 10)
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert_eq!(
+ lookup_existing_scope(&store.reader, "default", "api")
+ .await
+ .unwrap()
+ .project_id,
+ project
+ );
+}
+
+#[tokio::test]
+async fn distinct_current_canonical_and_legacy_keys_resolve_without_guessing_checkout_names() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let project = resolve(
+ &store,
+ ws,
+ &remote("gitlab.com/acme/group/api"),
+ "checkout-blue",
+ None,
+ )
+ .await
+ .0;
+ for key in ["checkout-blue", "acme-group-api", "api"] {
+ assert_eq!(
+ lookup_existing_scope(&store.reader, "default", key)
+ .await
+ .unwrap()
+ .project_id,
+ project
+ );
+ }
+ assert_eq!(row(&store, project).0, "checkout-blue");
+ for key in ["group-api", "checkout-red"] {
+ assert!(
+ lookup_existing_scope(&store.reader, "default", key)
+ .await
+ .unwrap_err()
+ .is_not_found()
+ );
+ }
+ let foreign = store
+ .writer
+ .get_or_create_workspace("foreign")
+ .await
+ .unwrap();
+ for key in ["checkout-blue", "acme-group-api", "api"] {
+ assert!(
+ lookup_existing_scope(&store.reader, "foreign", key)
+ .await
+ .unwrap_err()
+ .is_not_found()
+ );
+ assert!(
+ store
+ .reader
+ .find_project(foreign, key.to_owned())
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+}
+
+#[tokio::test]
+async fn read_only_user_cannot_promote_a_legacy_name() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let owner = user(&store, "promotion-owner", 8).await;
+ let reader = user(&store, "promotion-reader", 9).await;
+ let project = resolve(
+ &store,
+ ws,
+ &remote("github.com/acme/api"),
+ "api",
+ Some(owner),
+ )
+ .await
+ .0;
+ store
+ .writer
+ .set_access_mode(project, AccessMode::Restricted)
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(reader, project, GrantLevel::Read, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ lookup_existing_scope_guarded(
+ &store.reader,
+ "default",
+ "acme-api",
+ Some(reader),
+ ProjectAccess::Read,
+ )
+ .await
+ .unwrap()
+ .project_id,
+ project
+ );
+ assert!(
+ create_explicit_scope_guarded(
+ &store.reader,
+ &store.writer,
+ "default",
+ "acme-api",
+ Some(reader),
+ )
+ .await
+ .unwrap_err()
+ .is_forbidden()
+ );
+ assert_eq!(row(&store, project).0, "api");
+}
+
+#[tokio::test]
+async fn canonical_target_conflict_rolls_back_the_promotion() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let legacy = resolve(&store, ws, &remote("github.com/acme/api"), "api", None)
+ .await
+ .0;
+ let conflict = store
+ .writer
+ .get_or_create_project(ws, "acme-api", None)
+ .await
+ .unwrap();
+ let error =
+ create_explicit_scope_guarded(&store.reader, &store.writer, "default", "acme-api", None)
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ ScopeResolutionError::ProjectNameAmbiguous { .. }
+ ));
+ assert_eq!(row(&store, legacy).0, "api");
+ assert_eq!(row(&store, conflict).0, "acme-api");
+}
+
+#[tokio::test]
+async fn audit_failure_rolls_back_promotion_and_keeps_the_writer_alive() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let project = resolve(&store, ws, &remote("github.com/acme/api"), "api", None)
+ .await
+ .0;
+ store
+ .writer
+ .upsert_page(preserved_page(ws, project))
+ .await
+ .unwrap();
+ let owner = user(&store, "rollback-owner", 31).await;
+ store
+ .writer
+ .grant_memory(owner, project, GrantLevel::Write, None)
+ .await
+ .unwrap();
+ let session = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: session,
+ workspace_id: ws,
+ project_id: project,
+ agent_kind: AgentKind::Other,
+ cwd: Some("/rollback/api".into()),
+ actor_user: None,
+ occurred_at: None,
+ })
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: project,
+ from_session_id: Some(session),
+ from_agent: AgentKind::Other,
+ to_agent: None,
+ cwd: None,
+ summary: "rollback baton".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ owner_user: None,
+ })
+ .await
+ .unwrap();
+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
+ let snapshot = || {
+ ["pages", "sessions", "project_grants", "handoffs"].map(|table| {
+ let mut statement = conn
+ .prepare(&format!("SELECT * FROM {table} WHERE project_id = ?1"))
+ .unwrap();
+ let columns = statement.column_count();
+ statement
+ .query_map([project.as_bytes().to_vec()], |row| {
+ (0..columns)
+ .map(|column| row.get::<_, rusqlite::types::Value>(column))
+ .collect::<rusqlite::Result<Vec<_>>>()
+ })
+ .unwrap()
+ .collect::<rusqlite::Result<Vec<_>>>()
+ .unwrap()
+ })
+ };
+ let before = snapshot();
+ assert!(before.iter().all(|rows| !rows.is_empty()));
+ conn.execute_batch(
+ "CREATE TRIGGER fail_promotion_audit BEFORE INSERT ON audit_log \
+ WHEN NEW.op = 'promote_project_name' \
+ BEGIN SELECT RAISE(ABORT, 'forced promotion audit failure'); END;",
+ )
+ .unwrap();
+
+ assert!(
+ create_explicit_scope_guarded(&store.reader, &store.writer, "default", "acme-api", None,)
+ .await
+ .is_err()
+ );
+ assert_eq!(row(&store, project).0, "api");
+ let audit_count: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM audit_log WHERE op = 'promote_project_name'",
+ [],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(audit_count, 0);
+ assert_eq!(snapshot(), before, "every dependent row is unchanged");
+ assert!(
+ store
+ .reader
+ .page_body_by_ids(ws, project, "notes/preserved.md")
+ .await
+ .unwrap()
+ .is_some()
+ );
+ conn.execute_batch("DROP TRIGGER fail_promotion_audit")
+ .unwrap();
+ let later = store
+ .writer
+ .get_or_create_project(ws, "writer-still-alive", None)
+ .await
+ .unwrap();
+ assert_ne!(later, project);
+}
+
+#[tokio::test]
+async fn exact_name_that_is_another_forges_canonical_key_fails_closed() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let exact = resolve(
+ &store,
+ ws,
+ &remote("github.com/unrelated/tool"),
+ "acme-api",
+ None,
+ )
+ .await
+ .0;
+ let canonical = resolve(
+ &store,
+ ws,
+ &remote("gitlab.com/acme/api"),
+ "gitlab-api",
+ None,
+ )
+ .await
+ .0;
+ assert_ne!(exact, canonical);
+ let error = lookup_existing_scope(&store.reader, "default", "acme-api")
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ ScopeResolutionError::ProjectNameAmbiguous { .. }
+ ));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = workspace(&store).await;
+ let project = resolve(&store, ws, &remote("github.com/acme/api"), "api", None)
+ .await
+ .0;
+ let resolve =
+ |name| create_explicit_scope_guarded(&store.reader, &store.writer, "default", name, None);
+ let (a, b) = tokio::join!(resolve("api"), resolve("acme-api"));
+ assert_eq!(a.unwrap().scope.project_id, project);
+ assert_eq!(b.unwrap().scope.project_id, project);
+ assert_eq!(row(&store, project).0, "acme-api");
+}
+
/// Naming a project differently changes nothing about reads: a lookup is
/// still no-create, and the folder name a static client might guess resolves
/// to nothing rather than to a fresh project.
diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rs
index e274397e..48116ca2 100644
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@ -164,6 +164,140 @@ async fn two_operators_on_two_clones_of_one_repository_share_its_path_named_proj
assert!(seen.body.contains("alice's note"));
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers() {
+ use ai_memory_core::repository_identity::{IdentitySource, IdentityStyle, RepositoryIdentity};
+ use ai_memory_core::{ActiveProject, ActiveProjectMode, ActorKey};
+ use ai_memory_store::{ProjectPrincipal, ScopeResolver};
+ use std::time::Duration;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("acme".to_string())
+ .await
+ .unwrap();
+ let repo = RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: IdentitySource::GitRemote,
+ };
+ store
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let project = store
+ .writer
+ .resolve_project_by_identity(
+ ws,
+ repo,
+ IdentityStyle::HostPath,
+ "api",
+ Some("/home/alice/api".into()),
+ None,
+ None,
+ )
+ .await
+ .unwrap()
+ .0;
+ let alice = store
+ .writer
+ .create_user(
+ NewUser {
+ username: "alice-promotion".into(),
+ name: None,
+ email: None,
+ },
+ [41; ai_memory_store::TOKEN_HASH_LEN],
+ )
+ .await
+ .unwrap();
+ let bob = store
+ .writer
+ .create_user(
+ NewUser {
+ username: "bob-promotion".into(),
+ name: None,
+ email: None,
+ },
+ [42; ai_memory_store::TOKEN_HASH_LEN],
+ )
+ .await
+ .unwrap();
+ let active = ActiveProject::with_config(
+ ActiveProjectMode::PerActor,
+ Duration::from_secs(60),
+ ai_memory_core::DEFAULT_MAX_ENTRIES,
+ );
+ let alice_actor = ActorKey {
+ user: Some("user:alice-promotion".into()),
+ session_id: Some("alice-clone".into()),
+ };
+ let bob_actor = ActorKey {
+ user: Some("user:bob-promotion".into()),
+ session_id: Some("bob-clone".into()),
+ };
+ active.set_for(&alice_actor, ws, project, false);
+ active.set_for(&bob_actor, ws, project, false);
+ store
+ .writer
+ .grant_memory(alice, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(bob, project, ai_memory_store::GrantLevel::Read, None)
+ .await
+ .unwrap();
+ let resolve = |viewer, actor: ActorKey| {
+ let reader = store.reader.clone();
+ let writer = store.writer.clone();
+ let active = active.clone();
+ async move {
+ ScopeResolver::new(&reader, ws, project)
+ .with_writer(&writer)
+ .with_active_project(&active)
+ .with_project_authz(ProjectPrincipal::user(viewer), true)
+ .resolve_write_args(Some("acme"), Some("acme-api"), &actor)
+ .await
+ }
+ };
+ let (alice_scope, bob_write) = tokio::join!(
+ resolve(alice, alice_actor.clone()),
+ resolve(bob, bob_actor.clone())
+ );
+ let alice_scope = alice_scope.unwrap();
+ assert!(bob_write.unwrap_err().is_forbidden());
+ let bob_scope = ScopeResolver::new(&store.reader, ws, project)
+ .with_active_project(&active)
+ .with_project_authz(ProjectPrincipal::user(bob), true)
+ .resolve_read_args(Some("acme"), Some("api"), &bob_actor)
+ .await
+ .unwrap();
+ assert_eq!(alice_scope.scope.project_id, project);
+ assert_eq!(bob_scope.project_id, project);
+ assert_eq!(active.get_for(&alice_actor), Some((ws, project)));
+ assert_eq!(active.get_for(&bob_actor), Some((ws, project)));
+
+ let mut authored = page(
+ ws,
+ alice_scope.scope.project_id,
+ "notes/promoted.md",
+ "Promoted",
+ "alice wrote after promotion",
+ );
+ authored.author_id = Some(alice);
+ store.writer.upsert_page(authored).await.unwrap();
+ let shared = store
+ .reader
+ .page_body_by_ids(ws, bob_scope.project_id, "notes/promoted.md")
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(shared.body.contains("alice wrote after promotion"));
+}
+
/// The collaboration guarantee, and the reason a team can use one server:
/// what Alice writes, Carol reads.
///
diff --git a/crates/ai-memory-wiki/src/watcher.rs b/crates/ai-memory-wiki/src/watcher.rs
index 3a0693de..715f005b 100644
--- a/crates/ai-memory-wiki/src/watcher.rs
+++ b/crates/ai-memory-wiki/src/watcher.rs
@@ -910,7 +910,8 @@ fn is_tempfile(path: &Path) -> bool {
}
/// `_meta.md` is the per-scope manifest the engine writes (workspace/project
-/// name + repo_path) so the wiki tree is self-describing. It describes the
+/// name, repo path, and optional repository identity coordinates) so the wiki
+/// tree is self-describing. It describes the
/// scope, it is never a wiki page.
fn is_manifest_filename(page_path: &PagePath) -> bool {
page_path
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index be7eeb17..0d413d32 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -12,7 +12,7 @@ use ai_memory_llm::Embedder;
use ai_memory_store::{
ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, AutoImproveProposalDetail,
FailAutoImproveProposal, MoveSessionSummary, MoveSummary, PagesMode, PurgeSessionSummary,
- ReaderPool, WriterHandle, artifact_path_for, f32_vec_to_bytes,
+ ReaderPool, ScopeRow, WriterHandle, artifact_path_for, f32_vec_to_bytes,
};
use tokio::sync::RwLock;
@@ -671,15 +671,16 @@ impl Wiki {
}
};
let ws_dir = self.root.join(workspace_id.to_string());
- let mut project_fm = serde_json::json!({ "project": scope.project_name });
- if let Some(repo_path) = scope.repo_path {
- project_fm["repo_path"] = serde_json::Value::String(repo_path);
- }
+ let workspace_name = scope.workspace_name.clone();
+ let project_fm = match Self::project_scope_frontmatter(scope) {
+ Ok(frontmatter) => frontmatter,
+ Err(e) => {
+ tracing::warn!(error = %e, "scope-manifest identity is invalid (non-fatal)");
+ return;
+ }
+ };
let written = self
- .write_scope_manifest(
- &ws_dir,
- serde_json::json!({ "workspace": scope.workspace_name }),
- )
+ .write_scope_manifest(&ws_dir, serde_json::json!({ "workspace": workspace_name }))
.and_then(|_| {
self.write_scope_manifest(&ws_dir.join(project_id.to_string()), project_fm)
});
@@ -1821,6 +1822,48 @@ impl Wiki {
Ok((id, pending_embed))
}
+ fn project_scope_frontmatter(scope: ScopeRow) -> WikiResult<serde_json::Value> {
+ let project_id = scope.project_id;
+ let identity = match (scope.identity.as_deref(), scope.identity_source.as_deref()) {
+ (Some(identity), Some(source)) => Some(
+ ai_memory_core::repository_identity::accept_wire_identity(identity, source)
+ .ok_or_else(|| {
+ WikiError::Io(std::io::Error::other(format!(
+ "project {} has an invalid identity/source pair",
+ scope.project_id
+ )))
+ })?,
+ ),
+ (None, None) => None,
+ _ => {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "project {} has an incomplete identity/source pair",
+ scope.project_id
+ ))));
+ }
+ };
+ let canonical_name = identity
+ .as_ref()
+ .and_then(ai_memory_core::repository_identity::path_style_name);
+ let legacy_name = identity
+ .as_ref()
+ .and_then(ai_memory_core::repository_identity::legacy_basename_name);
+ if scope.canonical_name != canonical_name || scope.legacy_name != legacy_name {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "project {project_id} has coordinate keys inconsistent with its identity"
+ ))));
+ }
+ let manifest = ai_memory_core::repository_identity::ProjectManifest {
+ project: scope.project_name,
+ repo_path: scope.repo_path,
+ identity: identity.as_ref().map(|value| value.identity.clone()),
+ identity_source: identity.map(|value| value.source),
+ canonical_name,
+ legacy_name,
+ };
+ serde_json::to_value(manifest).map_err(WikiError::from)
+ }
+
/// Read a `_meta.md` scope-manifest's frontmatter from `dir`.
fn read_scope_meta(dir: &Path) -> WikiResult<serde_json::Value> {
let path = dir.join("_meta.md");
@@ -1852,8 +1895,9 @@ impl Wiki {
/// Rebuild the **entire** store index from the on-disk wiki tree — the
/// "DB is rebuildable from files" guarantee made concrete. Walks every
- /// `<ws-uuid>/<proj-uuid>/` directory, recreates the workspace/project rows
- /// from each dir's self-describing `_meta.md` manifest (preserving the ids
+ /// `<ws-uuid>/<proj-uuid>/` directory, recreates workspace/project rows and
+ /// optional repository identity from each self-describing `_meta.md`
+ /// manifest (preserving the ids
/// the tree is keyed by, via [`WriterHandle::ensure_workspace_with_id`] /
/// [`ensure_project_with_id`]), then reindexes every page. Pages are
/// detected by content (a frontmatter file named `log.md` is a page; the
@@ -1918,21 +1962,58 @@ impl Wiki {
}
let meta = Self::read_scope_meta(&proj_root)?;
- let name = meta
+ if meta
.get("project")
- .and_then(|v| v.as_str())
- .ok_or_else(|| {
- WikiError::Io(std::io::Error::other(format!(
- "{}/_meta.md is missing the `project` name",
+ .and_then(|value| value.as_str())
+ .is_none()
+ {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "{}/_meta.md is missing the `project` name",
+ proj_root.display()
+ ))));
+ }
+ let manifest: ai_memory_core::repository_identity::ProjectManifest =
+ serde_json::from_value(meta)?;
+ let identity = match (manifest.identity.as_deref(), manifest.identity_source) {
+ (Some(identity), Some(source)) => Some(
+ ai_memory_core::repository_identity::accept_wire_identity(
+ identity,
+ source.as_str(),
+ )
+ .ok_or_else(|| {
+ WikiError::Io(std::io::Error::other(format!(
+ "{}/_meta.md has an invalid repository identity/source pair",
+ proj_root.display()
+ )))
+ })?,
+ ),
+ (None, None) => None,
+ _ => {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "{}/_meta.md must provide identity and identity_source together",
proj_root.display()
- )))
- })?;
- let repo_path = meta
- .get("repo_path")
- .and_then(|v| v.as_str())
- .map(String::from);
+ ))));
+ }
+ };
+ let derived_canonical = identity
+ .as_ref()
+ .and_then(ai_memory_core::repository_identity::path_style_name);
+ let derived_legacy = identity
+ .as_ref()
+ .and_then(ai_memory_core::repository_identity::legacy_basename_name);
+ let has_coordinate_assertion =
+ manifest.canonical_name.is_some() || manifest.legacy_name.is_some();
+ if has_coordinate_assertion
+ && (manifest.canonical_name != derived_canonical
+ || manifest.legacy_name != derived_legacy)
+ {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "{}/_meta.md repository coordinate keys do not match its identity",
+ proj_root.display()
+ ))));
+ }
self.writer
- .ensure_project_with_id(proj, ws, name, repo_path)
+ .ensure_project_with_id(proj, ws, manifest.project, manifest.repo_path, identity)
.await?;
summary.projects += 1;
@@ -2014,11 +2095,52 @@ impl Wiki {
Ok(true)
}
+ /// Refresh one committed renamed scope from its current store row and checkpoint it.
+ ///
+ /// # Errors
+ /// Returns [`WikiError`] for store, filesystem, or checkpoint errors.
+ pub async fn refresh_renamed_scope(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> WikiResult<Option<String>> {
+ let reader = self.store_reader.as_ref().ok_or_else(|| {
+ WikiError::Io(std::io::Error::other(
+ "scope refresh requires a store reader",
+ ))
+ })?;
+ let _guard = self.mutation_lock.write().await;
+ self.manifested_scopes
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .remove(&(workspace_id, project_id));
+ let scope = reader
+ .scope_row_by_ids(workspace_id, project_id)
+ .await?
+ .ok_or_else(|| {
+ WikiError::Io(std::io::Error::other("renamed scope no longer exists"))
+ })?;
+ let ws_dir = self.root.join(workspace_id.to_string());
+ self.write_scope_manifest(
+ &ws_dir,
+ serde_json::json!({ "workspace": scope.workspace_name }),
+ )?;
+ let project_fm = Self::project_scope_frontmatter(scope)?;
+ self.write_scope_manifest(&ws_dir.join(project_id.to_string()), project_fm)?;
+ let checkpoint = self
+ .commit_all(&format!("rename-project {workspace_id}/{project_id}"))?
+ .map(|oid| oid.to_string());
+ self.manifested_scopes
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ .insert((workspace_id, project_id));
+ Ok(checkpoint)
+ }
+
/// Ensure every workspace/project scope has its self-describing `_meta.md`
- /// manifest on disk (`workspace`/`project` name + `repo_path`), so the wiki
- /// tree alone is enough to rebuild the index via [`Self::reindex_all`] —
- /// the "DB is rebuildable from files" guarantee. Idempotent; safe to run on
- /// every startup. No-op without a store reader. Returns the count written.
+ /// manifest on disk (names, `repo_path`, and optional repository identity
+ /// coordinates). Idempotent, safe at startup, and a no-op without a store
+ /// reader.
///
/// # Errors
/// Returns [`WikiError`] for store or filesystem errors.
@@ -2041,11 +2163,9 @@ impl Wiki {
}
for s in scopes {
let ws_dir = self.root().join(s.workspace_id.to_string());
- let mut fm = serde_json::json!({ "project": s.project_name });
- if let Some(rp) = s.repo_path {
- fm["repo_path"] = serde_json::Value::String(rp);
- }
- if self.write_scope_manifest(&ws_dir.join(s.project_id.to_string()), fm)? {
+ let project_dir = ws_dir.join(s.project_id.to_string());
+ let fm = Self::project_scope_frontmatter(s)?;
+ if self.write_scope_manifest(&project_dir, fm)? {
written += 1;
}
}
@@ -6463,6 +6583,341 @@ mod tests {
drop(s2);
}
+ #[tokio::test]
+ async fn promoted_identity_round_trips_through_manifest_and_clean_reindex() {
+ let src = TempDir::new().unwrap();
+ let source = Store::open(src.path()).unwrap();
+ let workspace = source
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let identity = ai_memory_core::repository_identity::RepositoryIdentity {
+ identity: "github.com/acme/platform/api".into(),
+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,
+ };
+ let (project, _) = source
+ .writer
+ .resolve_project_by_identity(
+ workspace,
+ identity.clone(),
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ "api",
+ Some("/src/api".into()),
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ let wiki = Wiki::new(src.path(), source.writer.clone())
+ .unwrap()
+ .with_store_reader(source.reader.clone());
+ wiki.write_page(req(
+ workspace,
+ project,
+ "notes/history.md",
+ "history survives reindex",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+ let promoted =
+ ai_memory_store::create_explicit_scope(&source.writer, "default", "acme-platform-api")
+ .await
+ .unwrap();
+ assert_eq!(promoted.scope.project_id, project);
+ assert_eq!(promoted.promoted_from.as_deref(), Some("api"));
+ assert!(
+ wiki.refresh_renamed_scope(workspace, project)
+ .await
+ .unwrap()
+ .is_some()
+ );
+ let manifest_path = src
+ .path()
+ .join("wiki")
+ .join(workspace.to_string())
+ .join(project.to_string())
+ .join("_meta.md");
+ let manifest = std::fs::read_to_string(&manifest_path).unwrap();
+ assert!(
+ manifest.contains("project: acme-platform-api"),
+ "{manifest}"
+ );
+ assert!(
+ manifest.contains("identity: github.com/acme/platform/api"),
+ "{manifest}"
+ );
+ assert!(
+ manifest.contains("identity_source: git_remote"),
+ "{manifest}"
+ );
+ assert!(
+ manifest.contains("canonical_name: acme-platform-api"),
+ "{manifest}"
+ );
+ assert!(manifest.contains("legacy_name: api"), "{manifest}");
+ let source_history = wiki.recent_checkpoints(10).unwrap();
+ assert!(
+ source_history
+ .iter()
+ .any(|checkpoint| checkpoint.summary.contains("rename-project"))
+ );
+ drop(source);
+
+ let dst = TempDir::new().unwrap();
+ copy_tree(&src.path().join("wiki"), &dst.path().join("wiki"));
+ let rebuilt = Store::open(dst.path()).unwrap();
+ let rebuilt_wiki = Wiki::new(dst.path(), rebuilt.writer.clone()).unwrap();
+ let summary = rebuilt_wiki.reindex_all().await.unwrap();
+ assert_eq!(summary.projects, 1);
+ assert_eq!(summary.pages, 1);
+ let restored_history = rebuilt_wiki.recent_checkpoints(10).unwrap();
+ assert_eq!(
+ restored_history
+ .iter()
+ .map(|checkpoint| &checkpoint.oid)
+ .collect::<Vec<_>>(),
+ source_history
+ .iter()
+ .map(|checkpoint| &checkpoint.oid)
+ .collect::<Vec<_>>()
+ );
+ assert_eq!(
+ rebuilt
+ .reader
+ .project_name_by_id(workspace, project)
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("acme-platform-api")
+ );
+ let rebuilt_scope = rebuilt
+ .reader
+ .scope_row_by_ids(workspace, project)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ rebuilt_scope.identity.as_deref(),
+ Some("github.com/acme/platform/api")
+ );
+ assert_eq!(rebuilt_scope.identity_source.as_deref(), Some("git_remote"));
+ assert_eq!(
+ rebuilt_scope.canonical_name.as_deref(),
+ Some("acme-platform-api")
+ );
+ assert_eq!(rebuilt_scope.legacy_name.as_deref(), Some("api"));
+ assert!(
+ rebuilt
+ .reader
+ .page_body_by_ids(workspace, project, "notes/history.md")
+ .await
+ .unwrap()
+ .unwrap()
+ .body
+ .contains("history survives reindex")
+ );
+ for key in ["acme-platform-api", "api"] {
+ assert_eq!(
+ ai_memory_store::lookup_existing_scope(&rebuilt.reader, "default", key)
+ .await
+ .unwrap()
+ .project_id,
+ project
+ );
+ }
+ let (captured, resolution) = rebuilt
+ .writer
+ .resolve_project_by_identity(
+ workspace,
+ identity,
+ ai_memory_core::repository_identity::IdentityStyle::Path,
+ "another-checkout",
+ Some("/other/api".into()),
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(captured, project);
+ assert_eq!(resolution, ai_memory_store::IdentityResolution::Matched);
+ let count: i64 = rebuilt
+ .reader
+ .with_conn(|conn| {
+ Ok(conn.query_row("SELECT COUNT(*) FROM projects", [], |row| row.get(0))?)
+ })
+ .await
+ .unwrap();
+ assert_eq!(count, 1, "capture must not create a second project UUID");
+ }
+
+ #[tokio::test]
+ async fn reindex_rejects_project_coordinate_fields_that_do_not_match_identity() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let workspace = WorkspaceId::new();
+ let project = ProjectId::new();
+ let workspace_dir = tmp.path().join("wiki").join(workspace.to_string());
+ let project_dir = workspace_dir.join(project.to_string());
+ std::fs::create_dir_all(&project_dir).unwrap();
+ std::fs::write(
+ workspace_dir.join("_meta.md"),
+ "---\nworkspace: default\ntype: Scope Manifest\n---\n",
+ )
+ .unwrap();
+ std::fs::write(
+ project_dir.join("_meta.md"),
+ "---\nproject: acme-api\nidentity: github.com/acme/api\nidentity_source: git_remote\ncanonical_name: forged-api\nlegacy_name: api\ntype: Scope Manifest\n---\n",
+ )
+ .unwrap();
+
+ let error = wiki.reindex_all().await.unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("coordinate keys do not match its identity"),
+ "{error}"
+ );
+ assert!(
+ store
+ .reader
+ .scope_row_by_ids(workspace, project)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+
+ #[tokio::test]
+ async fn identity_manifest_without_derived_keys_reindexes_and_derives_them() {
+ let src = TempDir::new().unwrap();
+ let source = Store::open(src.path()).unwrap();
+ let wiki = Wiki::new(src.path(), source.writer.clone())
+ .unwrap()
+ .with_store_reader(source.reader.clone());
+ let workspace = source
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let (project, _) = source
+ .writer
+ .resolve_project_by_identity(
+ workspace,
+ ai_memory_core::repository_identity::RepositoryIdentity {
+ identity: "github.com/acme/api".into(),
+ source: ai_memory_core::repository_identity::IdentitySource::GitRemote,
+ },
+ ai_memory_core::repository_identity::IdentityStyle::HostPath,
+ "api",
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ wiki.write_page(req(
+ workspace,
+ project,
+ "notes/a.md",
+ "identity history",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+ let manifest_path = src
+ .path()
+ .join("wiki")
+ .join(workspace.to_string())
+ .join(project.to_string())
+ .join("_meta.md");
+ std::fs::write(
+ &manifest_path,
+ "---\nproject: api\nidentity: github.com/acme/api\nidentity_source: git_remote\ntype: Scope Manifest\n---\n",
+ ).unwrap();
+ drop(source);
+
+ let dst = TempDir::new().unwrap();
+ copy_tree(&src.path().join("wiki"), &dst.path().join("wiki"));
+ let rebuilt = Store::open(dst.path()).unwrap();
+ Wiki::new(dst.path(), rebuilt.writer.clone())
+ .unwrap()
+ .reindex_all()
+ .await
+ .unwrap();
+ let scope = rebuilt
+ .reader
+ .scope_row_by_ids(workspace, project)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(scope.canonical_name.as_deref(), Some("acme-api"));
+ assert_eq!(scope.legacy_name.as_deref(), Some("api"));
+ }
+
+ #[tokio::test]
+ async fn old_project_manifest_without_identity_still_reindexes() {
+ let src = TempDir::new().unwrap();
+ let source = Store::open(src.path()).unwrap();
+ let wiki = Wiki::new(src.path(), source.writer.clone())
+ .unwrap()
+ .with_store_reader(source.reader.clone());
+ let workspace = source
+ .writer
+ .get_or_create_workspace("legacy")
+ .await
+ .unwrap();
+ let project = source
+ .writer
+ .get_or_create_project(workspace, "old-format", Some("/legacy".into()))
+ .await
+ .unwrap();
+ wiki.write_page(req(
+ workspace,
+ project,
+ "notes/legacy.md",
+ "legacy manifest history",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+ let manifest_path = src
+ .path()
+ .join("wiki")
+ .join(workspace.to_string())
+ .join(project.to_string())
+ .join("_meta.md");
+ std::fs::write(
+ &manifest_path,
+ "---\nproject: old-format\nrepo_path: /legacy\ntype: Scope Manifest\n---\n",
+ )
+ .unwrap();
+ drop(source);
+
+ let dst = TempDir::new().unwrap();
+ copy_tree(&src.path().join("wiki"), &dst.path().join("wiki"));
+ let rebuilt = Store::open(dst.path()).unwrap();
+ Wiki::new(dst.path(), rebuilt.writer.clone())
+ .unwrap()
+ .reindex_all()
+ .await
+ .unwrap();
+ let row = rebuilt
+ .reader
+ .scope_row_by_ids(workspace, project)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(row.project_name, "old-format");
+ assert_eq!(row.repo_path.as_deref(), Some("/legacy"));
+ assert!(row.identity.is_none());
+ assert!(row.identity_source.is_none());
+ assert!(row.canonical_name.is_none());
+ assert!(row.legacy_name.is_none());
+ }
+
#[tokio::test]
async fn backfill_writes_manifest_for_empty_workspace() {
let tmp = TempDir::new().unwrap();
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 21a9683d..30649d30 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -375,7 +375,7 @@ prunable rather than only after it ages in place.
| Table | What |
|---|---|
-| `workspaces`, `projects` | Top of the 3-tuple identity coordinate. `projects.identity` / `identity_source` (V70, #708) hold the repository identity a project routes by — an explicit marker `identity` or a normalised git remote, resolved client-side — unique per workspace when set; empty until a capture claims the project. A marker's `identity_style = "path"` (#1033, forwarded as the `identity_style` hook query param alongside a git-remote identity; default `host_path`) names a project that resolution *creates* from the repository path without the host (`acme-api`), falling back to the usual name when another project already holds it; it never renames or re-keys an existing project. See `docs/marker-file.md#repository-identity`. `projects.access_mode` (V68; `open` default / `restricted`) decides whether any authenticated user or only root, the creator (`projects.created_by`, V69) and grant holders (`project_grants`, V68) reach it, decided by `ai_memory_store::authorize_project` — `docs/users.md#per-project-access`. `projects.profile_contribute` / `profile_consume` (V74) record the marker's `[profile]` opt-outs, forwarded at session start; `profile_candidates`, `profile_harvest_marks` and `profile_entry_ledger` (V75) hold the profile pass's evidence, per-project read position and the entries it wrote. Reserved projects: `scratch`, `_global` (shared preferences; holds the single-user profile under `profile/`), `_profile` (a workspace profile) and `_profile.<user id>` (a private profile, always `restricted`); capture is never attributed to any of them — `docs/cross-project-profile.md`. |
+| `workspaces`, `projects` | Top of the 3-tuple identity coordinate. `projects.identity` / `identity_source` (V70, #708) hold the repository identity a project routes by — an explicit marker `identity` or a normalised git remote, resolved client-side — unique per workspace when set; empty until a capture claims the project. A marker's `identity_style = "path"` (#1033, forwarded as the `identity_style` hook query param alongside a git-remote identity; default `host_path`) names a project that resolution *creates* from the repository path without the host (`acme-api`), falling back to the usual name when another project already holds it. V76 stores indexed canonical and v2-basename keys derived from that full identity: reads are no-create/no-rename, while an authorized explicit write through the canonical name promotes only `projects.name` in the same resolve-or-create writer transaction and preserves the UUID. Project `_meta.md` carries the optional full identity/source plus derived keys; clean reindex validates them and rebuilds the same UUID/name/coordinate lookup, while older manifests without identity remain valid. Ambiguous cross-forge or multi-candidate keys fail closed. See `docs/marker-file.md#repository-identity`. `projects.access_mode` (V68; `open` default / `restricted`) decides whether any authenticated user or only root, the creator (`projects.created_by`, V69) and grant holders (`project_grants`, V68) reach it, decided by `ai_memory_store::authorize_project` — `docs/users.md#per-project-access`. `projects.profile_contribute` / `profile_consume` (V74) record the marker's `[profile]` opt-outs, forwarded at session start; `profile_candidates`, `profile_harvest_marks` and `profile_entry_ledger` (V75) hold the profile pass's evidence, per-project read position and the entries it wrote. Reserved projects: `scratch`, `_global` (shared preferences; holds the single-user profile under `profile/`), `_profile` (a workspace profile) and `_profile.<user id>` (a private profile, always `restricted`); capture is never attributed to any of them — `docs/cross-project-profile.md`. |
| `pages` | Versioned wiki pages with `is_latest` + `supersedes` chain. M8 columns: `last_accessed_at`, `access_count`, and decay-only tombstone marker `superseded_at`. M9 cols: `embedding_provider`, `embedding_model`, `embedding_dim`. V36: `expires_at` (frontmatter TTL). V37: `salience` (NULL = `salience_default`; derived from `page_feedback`). |
| `pages_fts` | FTS5 virtual table over `(title, body)`, auto-synced by triggers. |
| `sessions`, `observations` | Sanitized, bounded lifecycle-hook projections. `sessions.ended_observation_count` is the stable generation watermark for resumed-session re-end eligibility; wall clocks are not used for that decision. They are an operational audit trail, not a complete native transcript. |
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index b61006e3..6baab471 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -54,8 +54,18 @@ Scope resolution is centralized in `ai_memory_store::ScopeResolver` and its
explicit helpers:
- `lookup_existing_scope` for read, search, maintenance, retention, embed, and
- destructive paths. It never creates workspaces or projects.
-- `create_explicit_scope` for explicit write/create paths only.
+ destructive paths. It never creates workspaces, projects, or renames. Within
+ the named workspace it accepts an exact project name, the canonical
+ path-style name derived from a stored hostful git identity, or the v2
+ basename only when that compatibility key identifies one UUID.
+- `create_explicit_scope` for explicit write/create paths only. Existing
+ identity-backed rows are authorized and may be promoted to the canonical
+ name inside one writer transaction; unrelated or ambiguous candidates are
+ never merged. The promoting APIs return `ResolvedWriteScope` metadata rather
+ than silently discarding it; runtime callers ask Wiki to refresh/checkpoint
+ that scope's `_meta.md` after the SQL commit, and disclose failures for
+ startup manifest repair. Reserved profile/global helpers use a no-promotion
+ resolver because those names cannot be repository compatibility keys.
- `resolve_many_existing_scopes` for multi-project search scopes, with
deduplication and max-scope validation.
- `ScopeResolver::resolve_read_args` and `resolve_write_args` for MCP tools
diff --git a/docs/design-per-project-authz.md b/docs/design-per-project-authz.md
index 11c315d6..d9bd63d2 100644
--- a/docs/design-per-project-authz.md
+++ b/docs/design-per-project-authz.md
@@ -250,10 +250,24 @@ project. #1033 makes a remote-derived key the default name, landing in steps on
2. **Default naming chain** (`upstream` → `origin` → folder) for **new**
projects without opting in, with marker `project`/`identity` still
outranking remotes and the same collision fallback.
-3. **Dual-key resolve and in-place rename** (UUID foreign keys kept, no alias
- table) until v3, so existing basename projects are renamed toward their
- canonical key rather than split. Two operators on different clones of one
- repository must land in one project (`multi_session.rs`).
+3. **Dual-key resolve and in-place name promotion (landed).** Static callers
+ still pass only `workspace` + `project`. Within that workspace, exact stored
+ name, the canonical path-style name derived from a stored full hostful git
+ identity, and the v2 repository basename resolve to one UUID only when the
+ candidate set is unique. Reads are no-create and never rename. An existing
+ write path resolves, authorizes at `ProjectAccess::Write`, and promotes only
+ `projects.name` in one writer transaction with its audit row; UUID foreign
+ keys stay put. A target-name conflict, two forges sharing the hostless key,
+ or multiple candidates fails closed. The legacy basename remains readable
+ after promotion through v2. No alias table was added. V76 stores the two
+ deterministic keys derived from V70's full `projects.identity` and indexes
+ them so hot reads/writes use three bounded equality probes instead of
+ scanning a workspace; startup backfills pre-V76 identity rows before traffic.
+ Project `_meta.md` stores optional typed `identity` and `identity_source`
+ 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`.
Paths stay lexically normalised throughout; nothing canonicalises.
diff --git a/docs/install.md b/docs/install.md
index ab508891..80954989 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -2519,7 +2519,10 @@ chunks it plans reflect the margin.
manifest (at `<wiki>/<workspace>/<project>/bootstrap.md`) listing every
page generated + a one-paragraph rationale. Re-running without `--force`
errors out. Delete the manifest (and the generated pages) if you want a
-clean re-bootstrap.
+clean re-bootstrap. If canonical scope resolution promotes a legacy project but
+its `_meta.md` refresh/checkpoint fails, the result includes `manifest_warning`
+and the CLI prints it; the name change is committed and startup backfill can
+repair the scope manifest.
**Dry-run first.** Always worth doing before the real call to see
which sources would actually be sent + how many tokens that
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index f8db2abe..272fb1e9 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -199,7 +199,7 @@ Every project's data lives under an isolated, UUID-keyed root on disk:
│ ├── gotchas/
│ ├── sessions/
│ ├── _rules/
-│ ├── _meta.md # project name + repo_path for rebuilds
+│ ├── _meta.md # project name, path, optional identity keys
│ ├── log-YYYY-MM.md # rolling event log, one file per month
│ └── bootstrap.md
└── <other_workspace_id>/
@@ -351,7 +351,9 @@ What happens:
whitespace. 422 on bad input.
3. `UPDATE projects SET name = ? WHERE id = ?`. UNIQUE-violation on
the `(workspace_id, name)` index → 422 with "name taken".
-4. Return `{workspace, from, to, pages}`.
+4. Refresh the UUID-keyed project's `_meta.md` and checkpoint the wiki.
+5. Return `{workspace, from, to, pages, checkpoint}` plus
+ `manifest_warning` when the post-commit refresh failed.
Zero files move on disk because the disk path is keyed by
`project_id`, not name. The web UI URL `/web/w/<ws>/<proj-name>/…`
@@ -370,6 +372,15 @@ Failure modes:
- **`to` name already exists in this workspace** → 422.
- **`to` invalid (empty, slash, whitespace)** → 422.
- **Source `from` not found** → 404.
+- **Manifest refresh/checkpoint failed after commit** → 200 with
+ `manifest_warning`; the SQL rename remains committed and startup manifest
+ backfill can repair the disk metadata. The bootstrap, write-page,
+ move-project merge, move-session create, and managed-run responses surface
+ the same warning shape when their scope resolution performed the promotion.
+ The warning is retained if the promoted operation later fails: MCP puts it at
+ `error.data.manifest_warning`, while HTTP admin/managed-run errors keep the
+ top-level `manifest_warning`. Their CLI commands print it to stderr; API
+ callers receive it in JSON.
### `/admin/rename-workspace`
@@ -565,7 +576,10 @@ at the same path):
Every conflict (overwrite/duplicate) is listed in the response `conflicts`
array (`path` → `moved_to`). Set the policy via `--on-conflict` on the CLI
or `"on_conflict": "block" | "overwrite" | "duplicate"` in the JSON body
-for direct `/admin/move-project` callers.
+for direct `/admin/move-project` callers. If resolving an existing identity-backed
+destination promotes its legacy name first, the response includes
+`manifest_warning` when that committed promotion's manifest refresh/checkpoint
+fails; the CLI prints it.
**What does NOT migrate (merge case only):** in the `copy-purge` path the
source's `sessions`, `observations`, and `handoffs` (the raw episodic
@@ -712,9 +726,11 @@ Response (`MoveSessionReport`): `session_id`, `dry_run`, `session_moved`
sit in the destination | `none` when the session has no page anywhere),
`cwd`, `cwd_warning`, `would_create_project` (dry run with `create` only),
`pre_checkpoint` (only when the wiki tree had uncommitted changes before the
-move), `checkpoint` (only when the move changed the tree). The batch wraps
-them in `{dry_run, would_create_project?, from, to, total, moved, sessions:
-[...]}`.
+move), `checkpoint` (only when the move changed the tree), and
+`manifest_warning` when `--create --confirm` resolves an identity-backed legacy
+destination, commits its promotion, but cannot refresh/checkpoint `_meta.md`.
+The batch surfaces the same warning and wraps reports in `{dry_run,
+would_create_project?, from, to, total, moved, sessions: [...]}`.
Failure modes:
@@ -1046,7 +1062,10 @@ SQLite migration lineage:
What is rebuilt:
- Workspaces and projects from `_meta.md`, preserving the UUIDs encoded in the
- wiki directory names.
+ wiki directory names. Project manifests optionally carry the full hostful
+ repository identity and its source; the manifest also records
+ `canonical_name` and `legacy_name` as consistency assertions. Reindex validates the pair and
+ assertions, then derives the indexed compatibility keys from the identity.
- Latest page rows, page links, and FTS from markdown files.
What is not rebuilt:
@@ -1055,11 +1074,14 @@ What is not rebuilt:
and embeddings. Those are DB-only state; keep a backup if you need them.
Every scope directory carries the `_meta.md` manifest `reindex` reads its
-workspace/project name from. The manifest is written with the scope's first
-page, so a project that first appears while the server is running is
-rebuildable from that moment on — no restart required. The startup backfill
-still runs on every boot and repairs a tree written by an older release, or one
-whose manifests were removed by hand. If `reindex` reports a missing manifest,
+workspace/project name from. Identity-backed project manifests also carry
+optional typed `identity`, `identity_source`, `canonical_name`, and
+`legacy_name` fields. Older manifests without those
+fields remain valid and rebuild identity-less projects. The manifest is written
+with the scope's first page, so a project that first appears while the server is
+running is rebuildable from that moment on — no restart required. The startup
+backfill still runs on every boot and repairs a tree written by an older release,
+or one whose manifests were removed by hand. If `reindex` reports a missing manifest,
start the server once against that data directory and let the backfill write
it, then stop the server and reindex again.
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index eebdde05..2cc75017 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -389,9 +389,17 @@ resume, continue, session, or fork selector.
## What happens on each run
1. The host client resolves the normal workspace/project scope and a stable
- repository plus worktree fingerprint. It opens a 90-second renewable lease.
- One writer may own a workstream at a time, so two terminals cannot silently
- race its native-session pointers or delivery cursors.
+ repository plus worktree fingerprint. If an identity-backed project still
+ carries its legacy basename, this authorized write promotes the same UUID to
+ its canonical path name and refreshes the wiki scope manifest before opening
+ the lease; a post-commit manifest failure is returned as
+ `manifest_warning` on either success or a later prepare error, retaining the
+ first warning across busy retries and lease wait-out, printed once by the CLI,
+ and left for startup repair. Pure request validation, including mutually
+ exclusive workstream selectors, runs before promotion. It opens a 90-second
+ renewable lease. One writer may own a workstream at a time, so
+ two terminals cannot silently race its native-session pointers
+ or delivery cursors.
2. Bare mode resolves the correct available harness. For an empty workstream,
an explicit interactive adapter can offer matching local sessions for
one-time adoption. Otherwise the adapter passes native arguments through in
diff --git a/docs/marker-file.md b/docs/marker-file.md
index fa979b0e..2704ba35 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -90,8 +90,9 @@ identity = "acme/platform"
# Optional. "path" names a NEW remote-backed project from its repository
# path without the host ("acme-api" for github.com/acme/api) instead of the
-# folder name. Default "host_path". Never renames an existing project. See
-# "Naming new projects by repository path" below.
+# folder name. Default "host_path". Existing identity-backed projects can be
+# promoted in place only by an authorized write through that canonical name.
+# See "Naming new projects by repository path" below.
identity_style = "path"
# Optional. Opt this project into drop_subagent_captures: set it to "true"
@@ -632,16 +633,26 @@ route by the full identity (`github.com/acme/api`), and the style rides along
only with a remote identity — a declared `project` or `identity` keeps its
own name.
-- **Existing projects are never renamed or re-keyed.** A repository that
- already has a project, claimed or not, resolves exactly as before.
+- **Existing projects keep their UUID.** Reads by the canonical path name or
+ the v2 basename are find-only and never rename. An authorized write that
+ explicitly uses the canonical path name promotes only `projects.name` in one
+ transaction; pages, sessions, grants, handoffs and every other dependent row
+ remain attached to the same UUID. The v2 basename remains readable after
+ promotion.
- **Another forge is never merged in.** When the path name is already held by
a different repository — typically the same path on another forge
(`gitlab.com/acme/api` after `github.com/acme/api`) — the newcomer falls
back to the name it would get without the style.
- Put it in `~/.ai-memory.toml` to apply it to every checkout under `$HOME`
that has no nearer marker, like any other marker key.
-- Static MCP clients still resolve by name, so pass the path name (`acme-api`)
- as `project`.
+- 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.
+- 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
+ from the validated identity. Older manifests without these fields remain
+ valid and rebuild an identity-less project.
### Single workspace, no per-repo overrides
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 87dc75b0..09cea7f6 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -56,7 +56,7 @@ boundary not yet built.
| 8c | Messaging: pop-exactly-once | `ai-memory-store/src/ops.rs` `pop_message_in_transaction` atomic CAS `WHERE state='pending'` | `agent_messages.rs` — sequential **and** `tokio::join!` concurrent double-pop yields exactly one `Some` | STRONG |
| 8d | Messaging: inferred-scope read is diagnosed (#854) | `scope.rs` `is_inferred`; `server.rs` `inferred_scope_hint` on empty pop/list | `agent_messages_briefing.rs` `no_scope_pop_that_misses_the_mail_is_diagnosed_not_a_silent_null` | STRONG |
| 8e | Messaging: admission is the same for MCP and admin sends (#756) | `ai-memory-mcp/src/admin.rs` `handle_send_message` runs `Wiki::authorize_operation(.., AdmissionOp::MessageSend, ..)` at the recipient scope before `insert_message` (a refusal is 403 and stores nothing) and calls `notify_operation_observers` only after a successful commit; skipping webhooks needs `Capability::SkipAdmissionChain` (`skip_webhooks_for_admin_request`); the MCP path is `server.rs` `memory_message_send` | `admin.rs` `admin_message_send_reject_leaves_inbox_empty` (a rejecting webhook gets 403 and an empty inbox; fails with the admission call removed), controls `admin_message_send_observer_sees_commit_without_blocking_response` and `admin_message_send_full_inbox_does_not_notify_observer` | STRONG |
-| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; create only via `create_explicit_scope`. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG |
+| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; identity-aware lookup accepts exact/canonical/v2-basename keys only when they deduplicate to one UUID; `ops.rs` `resolve_project_name_for_write` performs write authorization, optional name-only promotion, and audit in one writer transaction; create only via `create_explicit_scope`. `ProjectNameAmbiguous` refuses cross-forge/multi-candidate keys before mutation; an audit failure after the name UPDATE rolls the transaction back. V76's derived-key indexes bound hot lookup to exact/canonical/legacy equality probes with at most four rows. Promoting public APIs return `ResolvedWriteScope` metadata (no untraced promotion API); MCP, admin, and managed-workstream write entry points make Wiki refresh/checkpoint the committed scope manifest after promotion and surface `manifest_warning` on success or any later operation failure; pure managed-run input validation precedes promotion. Project manifests persist the typed full identity/source and derived keys so clean reindex restores the same UUID and lookup behavior. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` `read_resolution_table_driven`, `multi_scope_resolution_deduplicates_and_validates`, no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `dual_key_scope.rs` `page_write_failure_after_promotion_preserves_manifest_warning`, `handoff_failure_after_promotion_preserves_manifest_warning`; `workstream.rs` `managed_run_rejects_mutually_exclusive_selection_before_promotion`, `managed_run_downstream_failure_after_promotion_preserves_manifest_warning`; `identity_resolution.rs` `canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming`, `authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup`, `read_only_user_cannot_promote_a_legacy_name`, `canonical_target_conflict_rolls_back_the_promotion`, `audit_failure_rolls_back_promotion_and_keeps_the_writer_alive`, `exact_name_that_is_another_forges_canonical_key_fails_closed`, `concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid`; `project_coordinates.rs` `candidate_query_is_bounded_and_uses_only_coordinate_indexes`; wiki `promoted_identity_round_trips_through_manifest_and_clean_reindex`, `old_project_manifest_without_identity_still_reindexes`, `reindex_rejects_project_coordinate_fields_that_do_not_match_identity`; admin `write_page_surfaces_manifest_failure_after_promotion`, `bootstrap_surfaces_manifest_failure_after_promotion`, `move_project_merge_surfaces_destination_promotion_manifest_warning`, `move_session_create_surfaces_destination_promotion_manifest_warning`; `multi_session.rs` `two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers`; MCP `dual_key_scope.rs`; hooks `workstream.rs` `managed_run_promotion_refreshes_the_scope_manifest`, `managed_run_discloses_manifest_failure_after_committed_promotion` static read/write/authz/cross-workspace/cross-forge cases; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG |
| 10 | Destructive-op live-process refusal + confirm flags (invariant #9); `purge-project`'s `dry_run` always wins over `confirm` so a preview request can never become destructive | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project`; `admin.rs` `handle_purge_project` checks `req.dry_run` unconditionally, before `req.confirm`, mirroring `reclaim-ledger-versions` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir; `admin_purge.rs` `purge_project_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing (the regression this row now also covers); `ops.rs` `purge_project_dry_run_changes_nothing` — every project-scoped row count, the `purged_scopes` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_project_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — a purge of project P collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project Q (via `sessions` cascading out of P), and both the preview and the confirmed report count it | STRONG |
| 10b | Session purge is scope+owner-bound (no cross-session/project over-delete); `purge-session`'s `dry_run` always wins over `confirm`, same as `purge-project` | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; whole op in one transaction; `admin.rs` `handle_purge_session` checks `req.dry_run` unconditionally, before `req.confirm` | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862); `admin_purge.rs` `purge_session_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing; `ops.rs` `purge_session_dry_run_changes_nothing` — every table a session purge touches, the `purged_sessions` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_session_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — purging session S collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project (via `S`'s own id cascading), and both the preview and the confirmed report count it; `admin_purge.rs` `purge_session_dry_run_refuses_a_session_outside_its_named_scope` — the same session previewed under a different real project (same workspace) or a different real workspace whose project shares the name both 404 with no counts in the body, with the session's own scope as the 200 control | STRONG |
| 10c | Ledger reclaim is content-gated, not filename-gated (invariant #16) | `ai-memory-store/src/ops.rs` `reclaim_ledger_versions` — a candidate row must pass `ai_memory_core::log_ledger::body_opens_with_log_ledger` on its own `body`, and only `is_latest=0 AND superseded_at IS NULL` rows are eligible, so decay-owned rows stay with `forget-sweep`; confirm gate in `admin.rs` `handle_reclaim_ledger_versions` | `reclaim_ledger_versions.rs` `a_prose_page_wearing_the_ledger_name_keeps_its_whole_version_chain`, `an_ordinary_page_chain_in_another_project_is_untouched`, `a_decay_tombstone_stays_with_the_sweep_that_owns_it`; `admin_reclaim_ledger_versions.rs` `deleting_without_confirm_is_refused_and_changes_nothing` (with dry-run and confirmed controls) | STRONG |
@@ -80,7 +80,7 @@ boundary not yet built.
| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |
| 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, and no existing project is renamed or claimed differently; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`, `the_same_path_on_another_forge_falls_back_instead_of_merging` and `an_unclaimed_project_holding_the_path_name_is_not_taken` (both fail with the free-name check removed; controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |
+| 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 |
| 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 |