Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Revert "Merge PR #911 into main"
AkitaOnRails42467259c356
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b7599878..ae943599 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,13 +18,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0mean latency instead of 20.2 s — in that run the hosted mean sat on theserver's 20 s completion timeout, which made the reranker stall everyquery before falling back. (#873)-- `ai-memory status --workspace <name> --project <name>` scopes the `links`- line, and its `typed edges` detail, to one project instead of the whole- store. `GET /admin/status` accepts the same optional pair and answers with a- new `links_scope` object (`ScopeLinkStatus`); naming only one of the two is- a `400`, an unknown scope the usual `404`. Without the pair the response and- the human output are byte-identical to before, so the endpoint stays a plain- health probe. (#911)- `ai-memory status` (text and `--json`) and `GET /admin/status` report theserver's HTTP exposure, so an unauthenticated bind is pollable by a monitor.The verdict is admin-gated at parity with the existing `bind`/`data_dir`@@ -323,11 +316,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0both sat in `links` with `to_page_id = NULL` and were visible only as`unresolved:` in `ai-memory status`. Both routes now skip a directorytarget, or a stem-less `.md`, with the existing warning. (#915)-- `memory_lint` now reports unresolved same-project links. Only cross-project- dangling edges (`DanglingCrossLink`) were reported, so a link to a missing- page in the same project stayed invisible outside the status counter;- `ReaderPool::dangling_internal_links` now feeds the same `broken_link`- findings. (#911)## [2.4.0] - 2026-09-21diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex fd93502f..22f3ac38 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1377,13 +1377,6 @@ pub struct StatusArgs {/// Emit the report as JSON instead of human-readable text.#[arg(long)]pub json: bool,- /// Workspace name. Together with `--project`, the `links` line reports- /// only that scope instead of the whole store.- #[arg(long)]- pub workspace: Option<String>,- /// Project name within the workspace (paired with `--workspace`).- #[arg(long)]- pub project: Option<String>,}/// Arguments for `backfill`.diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rsindex a73e22bc..7a499e2d 100644--- a/crates/ai-memory-cli/src/commands/status.rs+++ b/crates/ai-memory-cli/src/commands/status.rs@@ -41,10 +41,6 @@ struct Report {/// Derived-index diagnostics.#[serde(default)]derived: Derived,- /// Link counters for the scope named with `--workspace`/`--project`- /// (absent from servers that predate the scoped links line).- #[serde(default)]- links_scope: Option<ScopeLinks>,/// Physical storage figures (absent from pre-#549 servers).#[serde(default)]storage: Storage,@@ -102,17 +98,6 @@ struct Derived {stale_links_from_latest_pages: u64,}-/// Mirror of the server's scoped link counters for the `links` line-/// (`ai_memory_store::ScopeLinkStatus`).-#[derive(Debug, Default, Deserialize, Serialize)]-struct ScopeLinks {- links_from_latest_pages: u64,- unresolved_links_from_latest_pages: u64,- stale_links_from_latest_pages: u64,- #[serde(default)]- typed_links_from_latest_pages: Vec<(String, u64)>,-}-/// Suggest compaction only above this share of the file. Below it the/// exclusive lock costs more than the space is worth, and SQLite will reuse/// those pages on its own as the store grows.@@ -215,17 +200,7 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {// situation that prompts it.let spool = spool_health(&spool_dir(&config.data_dir));- // The `links` line can be scoped to one project: pass the names through- // and let `/admin/status` own the pair rule (400 when only one is given).- let mut query: Vec<(&str, &str)> = Vec::new();- if let Some(workspace) = args.workspace.as_deref() {- query.push(("workspace", workspace));- }- if let Some(project) = args.project.as_deref() {- query.push(("project", project));- }-- let report: Report = match get_json::<Report>(&ep, "/admin/status", &query).await {+ let report: Report = match get_json::<Report>(&ep, "/admin/status", &[]).await {Ok(report) => report,Err(err) => {report_offline_spool(&spool, args.json);@@ -248,7 +223,6 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {"observations": report.counts.observations,},"derived": report.derived,- "links_scope": report.links_scope,"storage": report.storage,"providers": report.providers,"spool": spool,@@ -324,32 +298,16 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {);}}- // The scoped figures replace the store-wide ones when a scope was- // named, so the line never mixes one project's links with another's.- let (links, unresolved, stale, typed_links) = match &report.links_scope {- Some(scope) => (- scope.links_from_latest_pages,- scope.unresolved_links_from_latest_pages,- scope.stale_links_from_latest_pages,- &scope.typed_links_from_latest_pages,- ),- None => (- report.derived.links_from_latest_pages,- report.derived.unresolved_links_from_latest_pages,- report.derived.stale_links_from_latest_pages,- &report.derived.typed_links_from_latest_pages,- ),- };- let scope_label = match (report.links_scope.is_some(), &args.workspace, &args.project) {- (true, Some(workspace), Some(project)) => format!(" [{workspace}/{project}]"),- _ => String::new(),- };println!(- " links: {links} latest-page links (unresolved: {unresolved}, stale: {stale})\- {scope_label}"+ " links: {} latest-page links (unresolved: {}, stale: {})",+ report.derived.links_from_latest_pages,+ report.derived.unresolved_links_from_latest_pages,+ report.derived.stale_links_from_latest_pages);- if !typed_links.is_empty() {- let typed: Vec<String> = typed_links+ if !report.derived.typed_links_from_latest_pages.is_empty() {+ let typed: Vec<String> = report+ .derived+ .typed_links_from_latest_pages.iter().map(|(k, v)| format!("{k}: {v}")).collect();diff --git a/crates/ai-memory-consolidate/src/lint.rs b/crates/ai-memory-consolidate/src/lint.rsindex c1603d31..7671c8a2 100644--- a/crates/ai-memory-consolidate/src/lint.rs+++ b/crates/ai-memory-consolidate/src/lint.rs@@ -227,26 +227,6 @@ pub async fn run_lint(});}- // Dangling same-project links: a plain body link or wikilink that never- // resolved. Lower signal than a broken cross-project dependency, but the- // status counter alone never names the page or the missing target.- for dangling in reader- .dangling_internal_links(workspace_id, project_id)- .await?- {- findings.push(LintFinding {- kind: "broken_link".into(),- severity: "warning".into(),- message: format!(- "Page {} links to {} but that page does not exist in this project \- (missing, renamed, or deleted) — a broken internal link",- dangling.from_path, dangling.path,- ),- pages: vec![dangling.from_path],- detail: None,- });- }-// Declared contradictions (typed `contradicts` edges, 2.0 item 3):// an author or the consolidator explicitly said two pages disagree —// the highest-signal zero-LLM contradiction finding possible.diff --git a/crates/ai-memory-consolidate/tests/suite/typed_edges.rs b/crates/ai-memory-consolidate/tests/suite/typed_edges.rsindex bc89ff7f..d48c5f1e 100644--- a/crates/ai-memory-consolidate/tests/suite/typed_edges.rs+++ b/crates/ai-memory-consolidate/tests/suite/typed_edges.rs@@ -144,76 +144,6 @@ async fn a_declared_contradiction_is_a_lint_finding_without_an_llm() {);}-#[tokio::test]-async fn an_unresolved_same_project_link_is_a_broken_link_finding() {- let tmp = TempDir::new().unwrap();- let store = Store::open(tmp.path()).unwrap();- let (ws, proj) = scope(&store).await;- let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();-- wiki.write_page(req(- ws,- proj,- "notes/dangling.md",- "points at [[notes/missing.md]]",- serde_json::json!({}),- ))- .await- .unwrap();- // Control: a link that resolves is not reported.- wiki.write_page(req(- ws,- proj,- "notes/present.md",- "the target",- serde_json::json!({}),- ))- .await- .unwrap();- wiki.write_page(req(- ws,- proj,- "notes/resolved.md",- "see [[notes/present.md]]",- serde_json::json!({}),- ))- .await- .unwrap();-- let report = run_lint(- &store.reader,- &wiki,- None,- ws,- proj,- LintOptions {- dry_run: true,- use_llm: false,- decay_lambda: 0.02,- embedding: None,- },- )- .await- .unwrap();-- let broken: Vec<_> = report- .findings- .iter()- .filter(|f| f.kind == "broken_link")- .collect();- assert_eq!(- broken.len(),- 1,- "only the unresolved same-project link is reported: {broken:?}"- );- assert_eq!(broken[0].pages, vec!["notes/dangling.md"]);- assert!(- broken[0].message.contains("notes/missing.md"),- "{}",- broken[0].message- );-}-#[tokio::test]async fn a_contradiction_to_a_deleted_page_reports_the_stale_declaration() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 98e8440e..2051632a 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -1137,11 +1137,6 @@ pub struct StatusReport {pub counts: ai_memory_store::StatusCounts,/// Derived-index and retrieval-readiness diagnostics.pub derived: ai_memory_store::DerivedIndexStatus,- /// Link counters for the scope named in the query string, when one was- /// given (`ai-memory status --workspace/--project`). `None` for every- /// caller that names none — the response then carries exactly the fields- /// it always has.- pub links_scope: Option<ai_memory_store::ScopeLinkStatus>,/// Physical storage figures — file size and reclaimable free pages — so an/// operator can decide whether a `VACUUM` is worth its exclusive lock.pub storage: ai_memory_store::StorageStatus,@@ -1188,46 +1183,7 @@ async fn handle_list_projects(State(state): State<Arc<AdminState>>) -> impl Into}}-/// Query string for `GET /admin/status`: the optional scope whose own link-/// counters the report should carry (`ai-memory status-/// --workspace/--project`). Without a scope the report is the store-wide one-/// it has always been — this endpoint is also the health probe, so nothing-/// about the unscoped response may change.-#[derive(Debug, Deserialize)]-struct StatusScopeQuery {- /// Workspace name.- workspace: Option<String>,- /// Project name within the workspace.- project: Option<String>,-}--async fn handle_status(- State(state): State<Arc<AdminState>>,- Query(scope): Query<StatusScopeQuery>,-) -> impl IntoResponse {- // Additive only: the scoped figures are computed when a scope was named,- // and never for the plain health probe.- let links_scope = match (- trimmed_opt(scope.workspace.as_deref()),- trimmed_opt(scope.project.as_deref()),- ) {- (Some(ws), Some(proj)) => match lookup_ws_proj_no_create(&state, ws, proj).await {- Ok((ws, proj)) => match state.reader.link_status_for_scope(ws, proj).await {- Ok(status) => Some(status),- Err(e) => return internal_err(e.to_string()),- },- Err(e) => return e,- },- (Some(_), None) | (None, Some(_)) => {- return (- StatusCode::BAD_REQUEST,- Json(serde_json::json!({- "error": "workspace and project must be provided together"- })),- );- }- _ => None,- };+async fn handle_status(State(state): State<Arc<AdminState>>) -> impl IntoResponse {match state.reader.status_counts().await {Ok(counts) => match state.reader.derived_index_status().await {Ok(derived) => {@@ -1249,7 +1205,6 @@ async fn handle_status(db_path: state.db_path.display().to_string(),counts,derived,- links_scope,storage,providers: state.provider_health.snapshot(),ingest: state.ingest_metrics.snapshot(),diff --git a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs b/crates/ai-memory-mcp/tests/suite/admin_status_search.rsindex b98a68d7..1e258882 100644--- a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs@@ -70,52 +70,6 @@ async fn seed_page(store: &Store, title: &str, path: &str, body: &str) {store.writer.upsert_page(page).await.unwrap();}-/// Seed one page (with the given outgoing same-project links) into an explicit-/// scope, so a test can drive the scoped `links` figures that-/// `GET /admin/status?workspace=&project=` reports.-async fn seed_linked_page(- store: &Store,- workspace: &str,- project: &str,- path: &str,- links: &[&str],-) {- let ws = store- .writer- .get_or_create_workspace(workspace.to_string())- .await- .unwrap();- let proj = store- .writer- .get_or_create_project(ws, project.to_string(), None)- .await- .unwrap();- let page = NewPage {- workspace_id: ws,- project_id: proj,- path: PagePath::new(path).unwrap(),- title: path.to_string(),- body: "seeded".to_string(),- tier: Tier::Semantic,- frontmatter_json: serde_json::json!({}),- pinned: false,- links: links- .iter()- .map(|target| ai_memory_core::LinkTarget {- workspace: None,- project: None,- path: PagePath::new(*target).unwrap(),- relation: None,- })- .collect(),- author_id: None,- expires_at: None,- entities: Vec::new(),- evidence: Vec::new(),- };- store.writer.upsert_page(page).await.unwrap();-}-async fn body_bytes(resp: axum::response::Response) -> Vec<u8> {use axum::body::to_bytes;to_bytes(resp.into_body(), 1_000_000)@@ -243,219 +197,6 @@ async fn list_projects_returns_workspace_project_pairs() {);}-/// A partial scope pair is refused on `/admin/status` too, and the full pair-/// answers with this project's figures (adversarial + control, per `AGENTS.md`-/// "Security-boundary tests are adversarial and mandatory").-#[tokio::test]-async fn status_scoped_links_rejects_partial_scope() {- let tmp = TempDir::new().unwrap();- let (state, store) = make_admin_state(&tmp).await;- seed_linked_page(- &store,- "default",- "app",- "notes/one.md",- &["notes/missing.md"],- )- .await;- let app = admin_router(state);-- for uri in [- "/admin/status?workspace=default",- "/admin/status?project=app",- ] {- let resp = app- .clone()- .oneshot(- Request::builder()- .method("GET")- .uri(uri)- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{uri}");- let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();- assert!(- body["error"]- .as_str()- .unwrap_or("")- .contains("workspace and project must be provided together"),- "unexpected error body for {uri}: {body}"- );- }-- // Control: the full pair is answered and carries the scoped object.- let resp = app- .oneshot(- Request::builder()- .method("GET")- .uri("/admin/status?workspace=default&project=app")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(resp.status(), StatusCode::OK);- let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();- assert_eq!(- body["links_scope"]["links_from_latest_pages"].as_u64(),- Some(1),- "{body}"- );- assert_eq!(- body["links_scope"]["unresolved_links_from_latest_pages"].as_u64(),- Some(1),- "{body}"- );-}--/// An unknown scope is refused and stays refused: the route resolves through-/// the no-create lookup, so the first 404 cannot have minted the scope.-#[tokio::test]-async fn status_scoped_links_fails_closed_on_an_unknown_scope() {- let tmp = TempDir::new().unwrap();- let (state, store) = make_admin_state(&tmp).await;- seed_linked_page(- &store,- "default",- "app",- "notes/one.md",- &["notes/missing.md"],- )- .await;- let app = admin_router(state);-- for uri in [- "/admin/status?workspace=default&project=ghost",- "/admin/status?workspace=ghost&project=app",- ] {- let resp = app- .clone()- .oneshot(- Request::builder()- .method("GET")- .uri(uri)- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{uri}");- }-- // Adversarial half: a creating path would answer 200 on this retry.- let resp = app- .clone()- .oneshot(- Request::builder()- .method("GET")- .uri("/admin/status?workspace=default&project=ghost")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(- resp.status(),- StatusCode::NOT_FOUND,- "the refused scope must not have been created"- );-- // Control: the scope that does exist answers.- let resp = app- .oneshot(- Request::builder()- .method("GET")- .uri("/admin/status?workspace=default&project=app")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(resp.status(), StatusCode::OK);-}--/// Same-named projects in two workspaces stay isolated in the scoped figures.-#[tokio::test]-async fn status_scoped_links_do_not_leak_across_workspaces() {- let tmp = TempDir::new().unwrap();- let (state, store) = make_admin_state(&tmp).await;- seed_linked_page(- &store,- "default",- "app",- "notes/one.md",- &["notes/missing.md"],- )- .await;- seed_linked_page(&store, "other", "app", "notes/one.md", &[]).await;- seed_linked_page(- &store,- "other",- "app",- "notes/two.md",- &["notes/missing.md", "notes/also-missing.md"],- )- .await;- let app = admin_router(state);-- let resp = app- .clone()- .oneshot(- Request::builder()- .method("GET")- .uri("/admin/status?workspace=default&project=app")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(resp.status(), StatusCode::OK);- let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();- assert_eq!(- body["links_scope"]["links_from_latest_pages"].as_u64(),- Some(1),- "default/app must not include the same-named project in `other`: {body}"- );- assert_eq!(- body["links_scope"]["unresolved_links_from_latest_pages"].as_u64(),- Some(1),- "{body}"- );- // Store-wide both workspaces count, so the scoped figure is a real subset.- assert_eq!(- body["derived"]["links_from_latest_pages"].as_u64(),- Some(3),- "{body}"- );-- // Control: the other workspace's own figures (2 links, both unresolved).- let resp = app- .oneshot(- Request::builder()- .method("GET")- .uri("/admin/status?workspace=other&project=app")- .body(Body::empty())- .unwrap(),- )- .await- .unwrap();- assert_eq!(resp.status(), StatusCode::OK);- let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();- assert_eq!(- body["links_scope"]["links_from_latest_pages"].as_u64(),- Some(2),- "{body}"- );- assert_eq!(- body["links_scope"]["unresolved_links_from_latest_pages"].as_u64(),- Some(2),- "{body}"- );-}-#[tokio::test]async fn search_returns_matching_hits() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex e691cf11..4d9685ee 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -71,9 +71,9 @@ pub use reader::{ObservationPageResult, ObservationRecord, OpenSession, PageAuthor, PageHit, PageHitWithMeta,PageLinks, PageMeta, PageSummary, ProjectSummary, RELATED_WALK_MAX_DEPTH,RELATED_WALK_MAX_NODES, ReaderPool, ReindexTargetStatus, RelatedNode, RelatedPage,- RrfContributions, ScopeLinkStatus, ScopeRow, SearchExplain, SessionDependentRows,- SessionEndDisposition, SessionSummary, SettledPage, StatusCounts, StorageStatus,- StoredEmbedding, StoredPageBody, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,+ RrfContributions, ScopeRow, SearchExplain, SessionDependentRows, SessionEndDisposition,+ SessionSummary, SettledPage, StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody,+ WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,};pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};pub use scope::{@@ -7828,75 +7828,6 @@ mod tests {);}- /// The scoped links line counts one project, not the whole store.- #[tokio::test]- async fn link_status_for_scope_counts_only_the_named_project() {- let tmp = TempDir::new().unwrap();- let store = Store::open(tmp.path()).unwrap();- let ws = store- .writer- .get_or_create_workspace("default")- .await- .unwrap();- let app = store- .writer- .get_or_create_project(ws, "app", None)- .await- .unwrap();- let infra = store- .writer- .get_or_create_project(ws, "infra", None)- .await- .unwrap();- let mut app_page = sample_page(ws, app, "notes/a.md", "body");- app_page.links = vec![- ai_memory_core::LinkTarget {- workspace: None,- project: None,- path: ai_memory_core::PagePath::new("notes/b.md").unwrap(),- relation: Some(ai_memory_core::Relation::Fixes),- },- ai_memory_core::LinkTarget {- workspace: None,- project: None,- path: ai_memory_core::PagePath::new("notes/missing.md").unwrap(),- relation: None,- },- ];- store.writer.upsert_page(app_page).await.unwrap();- // The target page exists by the time the counts are read, so the- // `fixes` edge resolves and only the missing target stays- // unresolved (a new page repoints incoming links:- // `refresh_incoming_links_for_path`).- store- .writer- .upsert_page(sample_page(ws, app, "notes/b.md", "target body"))- .await- .unwrap();- let mut infra_page = sample_page(ws, infra, "notes/c.md", "body");- infra_page.links = vec![ai_memory_core::LinkTarget {- workspace: None,- project: None,- path: ai_memory_core::PagePath::new("notes/missing.md").unwrap(),- relation: None,- }];- store.writer.upsert_page(infra_page).await.unwrap();-- let scoped = store.reader.link_status_for_scope(ws, app).await.unwrap();- assert_eq!(scoped.links_from_latest_pages, 2);- assert_eq!(scoped.unresolved_links_from_latest_pages, 1);- assert_eq!(scoped.stale_links_from_latest_pages, 0);- assert_eq!(- scoped.typed_links_from_latest_pages,- vec![("fixes".to_string(), 1)]- );-- // Store-wide, both projects are counted — the whole point of the- // scoped call.- let global = store.reader.derived_index_status().await.unwrap();- assert_eq!(global.links_from_latest_pages, 3);- }-#[tokio::test]async fn entity_stream_finds_and_weights_pages() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 7b75d9dd..c8ddeaf0 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -1103,23 +1103,6 @@ impl ReindexTargetStatus {}}-/// Link counters for one project — the scoped counterpart of-/// [`DerivedIndexStatus`]'s four link figures. `GET /admin/status` carries-/// them when the caller names a scope, so `ai-memory status-/// --workspace/--project` can show a project's own link health instead of-/// the store-wide aggregate.-#[derive(Debug, Clone, Default, Serialize)]-pub struct ScopeLinkStatus {- /// Outgoing links whose source page is latest.- pub links_from_latest_pages: u64,- /// Latest-page outgoing links whose target path has not resolved yet.- pub unresolved_links_from_latest_pages: u64,- /// Latest-page outgoing links pointing at a non-latest target row.- pub stale_links_from_latest_pages: u64,- /// Typed relation edges (`link_type != 'references'`) by relation.- pub typed_links_from_latest_pages: Vec<(String, u64)>,-}-/// Derived-index health counters surfaced by admin status.#[derive(Debug, Clone, Default, Serialize)]pub struct DerivedIndexStatus {@@ -1534,17 +1517,6 @@ pub struct DanglingCrossLink {pub project_exists: bool,}-/// An unresolved same-project link — a latest page's own `to_page_id IS-/// NULL` edge with no cross-project scope. Surfaced by `memory_lint` as a-/// broken internal link.-#[derive(Debug, Clone, Serialize)]-pub struct DanglingInternalLink {- /// Path of the page that authored the link (in the queried project).- pub from_path: String,- /// Target page path as declared; unresolved, so nothing lives there.- pub path: String,-}-/// A page related to another through the link graph — used by the/// page-view "references / referenced by" panel. Body is omitted; just/// enough to render a clickable row.@@ -7131,46 +7103,6 @@ impl ReaderPool {.await}- /// Unresolved same-project links: every latest page in the queried- /// project whose bare (no cross-project scope) target is still- /// `to_page_id = NULL`. `memory_lint` reports each as a `broken_link`- /// finding — the raw counter in `ai-memory status` never names the page- /// or the missing target.- ///- /// # Errors- /// Propagates any SQL or pool error.- pub async fn dangling_internal_links(- &self,- workspace_id: WorkspaceId,- project_id: ProjectId,- ) -> StoreResult<Vec<DanglingInternalLink>> {- self.with_conn(move |conn| {- let mut stmt = conn.prepare(- "SELECT fp.path, l.to_path \- FROM links l \- JOIN pages fp ON fp.id = l.from_page_id \- AND fp.workspace_id = ?1 AND fp.project_id = ?2 AND fp.is_latest = 1 \- WHERE l.to_page_id IS NULL AND l.to_project IS NULL \- ORDER BY fp.path, l.to_path",- )?;- let rows = stmt.query_map(- params![workspace_id.as_bytes(), project_id.as_bytes()],- |row| {- Ok(DanglingInternalLink {- from_path: row.get(0)?,- path: row.get(1)?,- })- },- )?;- let mut out = Vec::new();- for r in rows {- out.push(r?);- }- Ok(out)- })- .await- }-/// Cross-session pass cadence probe: completed sessions newer than/// the pass's last run for this scope (docs/experience.md).///@@ -8769,75 +8701,6 @@ impl ReaderPool {.await}- /// Link counters scoped to one project — the four figures- /// [`Self::derived_index_status`] reports store-wide, restricted to the- /// latest pages of the queried scope. `GET /admin/status` carries them- /// when the caller names a scope, so `ai-memory status- /// --workspace/--project` can show a project's own link health instead- /// of an aggregate that mixes every scope in the store.- ///- /// # Errors- /// Propagates any SQL or pool error.- pub async fn link_status_for_scope(- &self,- workspace_id: WorkspaceId,- project_id: ProjectId,- ) -> StoreResult<ScopeLinkStatus> {- self.with_conn(move |conn| {- let typed_links_from_latest_pages = {- let mut stmt = conn.prepare(- "SELECT l.link_type, COUNT(*) FROM links l \- JOIN pages fp ON fp.id = l.from_page_id \- WHERE fp.is_latest = 1 \- AND fp.workspace_id = ?1 AND fp.project_id = ?2 \- AND l.link_type != 'references' \- GROUP BY l.link_type ORDER BY l.link_type",- )?;- let rows: Vec<(String, i64)> = stmt- .query_map(- params![workspace_id.as_bytes(), project_id.as_bytes()],- |row| Ok((row.get(0)?, row.get(1)?)),- )?- .collect::<Result<_, _>>()?;- rows.into_iter()- .map(|(k, v)| (k, u64::try_from(v).unwrap_or(0)))- .collect()- };- Ok(ScopeLinkStatus {- typed_links_from_latest_pages,- links_from_latest_pages: count_bound(- conn,- "SELECT COUNT(*) FROM links l \- JOIN pages fp ON fp.id = l.from_page_id \- WHERE fp.is_latest = 1 \- AND fp.workspace_id = ?1 AND fp.project_id = ?2",- &[workspace_id.as_bytes(), project_id.as_bytes()],- )?,- unresolved_links_from_latest_pages: count_bound(- conn,- "SELECT COUNT(*) FROM links l \- JOIN pages fp ON fp.id = l.from_page_id \- WHERE fp.is_latest = 1 \- AND fp.workspace_id = ?1 AND fp.project_id = ?2 \- AND l.to_page_id IS NULL",- &[workspace_id.as_bytes(), project_id.as_bytes()],- )?,- stale_links_from_latest_pages: count_bound(- conn,- "SELECT COUNT(*) FROM links l \- JOIN pages fp ON fp.id = l.from_page_id \- LEFT JOIN pages tp ON tp.id = l.to_page_id \- WHERE fp.is_latest = 1 \- AND fp.workspace_id = ?1 AND fp.project_id = ?2 \- AND l.to_page_id IS NOT NULL \- AND COALESCE(tp.is_latest, 0) != 1",- &[workspace_id.as_bytes(), project_id.as_bytes()],- )?,- })- })- .await- }-/// Return aggregate counts scoped to one project.////// # Errorsdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex d4c55ce9..ac3b7024 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -35,7 +35,7 @@ boundary not yet built.| 8b | Messaging: cancel-own-only | `ai-memory-store/src/ops.rs` `cancel_messages` (AND-gated on `from_*` sender coordinate) | `agent_messages.rs` — whole-outbox **and** a foreign **specific-id** cancel refused | STRONG || 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 |-| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; create only via `create_explicit_scope`; `ai-memory-mcp/src/admin.rs` `handle_status` resolves an optional `?workspace=&project=` pair through `lookup_ws_proj_no_create` (never `create_ws_proj`), so a scoped status read cannot mint a scope | `scope.rs` no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `admin_status_search.rs` `status_scoped_links_rejects_partial_scope`, `status_scoped_links_fails_closed_on_an_unknown_scope`, `status_scoped_links_do_not_leak_across_workspaces` | STRONG |+| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; create only via `create_explicit_scope` | `scope.rs` no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors` | STRONG || 10 | Destructive-op live-process refusal + confirm flags (invariant #9) | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir | STRONG || 10b | Session purge is scope+owner-bound (no cross-session/project over-delete) | `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 | `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) | STRONG || 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |