Skip to content

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

Rust

fix(wiki): drop directory targets from link extraction

Caminhar2e8a90fa9cb6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4bfd236d..ca57f544 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
mean latency instead of 20.2 s — in that run the hosted mean sat on the
server's 20 s completion timeout, which made the reranker stall every
query 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)
### Changed
- Quieted the default server log: the reconciliation-pass summary that fired
@@ -247,6 +254,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
instead of `%C3%A9`. An accented cwd reached the server as a different
path, and Cursor events and the session-start handoff lookup both use the
query `cwd`. (#877)
+- Link extraction no longer mints a permanently unresolved row from a
+ directory target. A `relations:` value whose final component is empty
+ (`sessions/`) had the extension appended to nothing and was stored as the
+ literal `sessions/.md`; the same target in a body link or wikilink
+ (`[notes/](notes/)`) stayed extension-less. No page path can match either —
+ page paths carry `.md` and `latest_page_id_for_link` matches exactly — so
+ both sat in `links` with `to_page_id = NULL` and were visible only as
+ `unresolved:` in `ai-memory status`. Both routes now skip a directory
+ target, or a stem-less `.md`, with the existing warning. Unresolved
+ same-project links are reported by `memory_lint` now too: it only knew
+ cross-project dangling edges, so a broken internal link stayed invisible
+ outside the counter. (#911)
## [2.4.0] - 2026-09-21
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 22f3ac38..fd93502f 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1377,6 +1377,13 @@ 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.rs
index 7a499e2d..a73e22bc 100644
--- a/crates/ai-memory-cli/src/commands/status.rs
+++ b/crates/ai-memory-cli/src/commands/status.rs
@@ -41,6 +41,10 @@ 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,
@@ -98,6 +102,17 @@ 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.
@@ -200,7 +215,17 @@ pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {
// situation that prompts it.
let spool = spool_health(&spool_dir(&config.data_dir));
- let report: Report = match get_json::<Report>(&ep, "/admin/status", &[]).await {
+ // 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 {
Ok(report) => report,
Err(err) => {
report_offline_spool(&spool, args.json);
@@ -223,6 +248,7 @@ 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,
@@ -298,16 +324,32 @@ 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: {} 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
+ " links: {links} latest-page links (unresolved: {unresolved}, stale: {stale})\
+ {scope_label}"
);
- if !report.derived.typed_links_from_latest_pages.is_empty() {
- let typed: Vec<String> = report
- .derived
- .typed_links_from_latest_pages
+ if !typed_links.is_empty() {
+ let typed: Vec<String> = typed_links
.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.rs
index 7671c8a2..c1603d31 100644
--- a/crates/ai-memory-consolidate/src/lint.rs
+++ b/crates/ai-memory-consolidate/src/lint.rs
@@ -227,6 +227,26 @@ 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-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index fa00baa1..9d1f040c 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1137,6 +1137,11 @@ 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,
@@ -1183,7 +1188,46 @@ async fn handle_list_projects(State(state): State<Arc<AdminState>>) -> impl Into
}
}
-async fn handle_status(State(state): State<Arc<AdminState>>) -> impl IntoResponse {
+/// 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,
+ };
match state.reader.status_counts().await {
Ok(counts) => match state.reader.derived_index_status().await {
Ok(derived) => {
@@ -1205,6 +1249,7 @@ async fn handle_status(State(state): State<Arc<AdminState>>) -> impl IntoRespons
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-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 58365e34..336ee905 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, ScopeRow, SearchExplain, SessionDependentRows, SessionEndDisposition,
- SessionSummary, SettledPage, StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody,
- WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
+ RrfContributions, ScopeLinkStatus, 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::{
@@ -7803,6 +7803,75 @@ 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.rs
index 2d02dc17..63c9e712 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1103,6 +1103,23 @@ 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 {
@@ -1517,6 +1534,17 @@ 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.
@@ -7103,6 +7131,46 @@ 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).
///
@@ -8701,6 +8769,75 @@ 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.
///
/// # Errors
diff --git a/crates/ai-memory-wiki/src/markdown.rs b/crates/ai-memory-wiki/src/markdown.rs
index 837fe2c0..61cfc01f 100644
--- a/crates/ai-memory-wiki/src/markdown.rs
+++ b/crates/ai-memory-wiki/src/markdown.rs
@@ -177,6 +177,18 @@ fn log_bounded(value: &str) -> String {
ai_memory_core::truncate_utf8_bytes(value, RELATION_LOG_FIELD_MAX_BYTES)
}
+/// Whether a link target's final path segment can name a page.
+///
+/// A directory target (trailing `/`, so an empty last segment) and a
+/// stem-less `.md` cannot: the first used to normalize to the literal
+/// `notes/.md` in `relations:` frontmatter, the second to an
+/// extension-less path — both permanently unresolved `links` rows that no
+/// page write could ever repoint.
+fn last_segment_names_a_page(target: &str) -> bool {
+ let last = target.rsplit_once('/').map_or(target, |(_, s)| s);
+ !last.is_empty() && last != ".md"
+}
+
/// Extract typed relation edges from a page's `relations:` frontmatter
/// (2.0 item 3):
///
@@ -212,17 +224,18 @@ pub fn extract_relation_links(frontmatter: &serde_json::Value) -> Vec<LinkTarget
},
};
// Same terminal normalization as wikilinks: extension-less
- // targets gain `.md`; anything with a non-md extension is
- // not a page and is skipped.
+ // targets gain `.md`; a directory target, a stem-less `.md`, and
+ // anything with a non-md extension are not pages and are skipped.
let raw_path = raw_path.trim();
let last = raw_path.rsplit_once('/').map_or(raw_path, |(_, s)| s);
+ let names_a_page = last_segment_names_a_page(raw_path)
+ && (!last.contains('.') || raw_path.ends_with(".md"));
+ if !names_a_page {
+ tracing::warn!(target = %log_bounded(target), "relation target is not a page; skipping");
+ continue;
+ }
let normalized = if last.contains('.') {
- if raw_path.ends_with(".md") {
- raw_path.to_string()
- } else {
- tracing::warn!(target = %log_bounded(target), "relation target is not a page; skipping");
- continue;
- }
+ raw_path.to_string()
} else {
format!("{raw_path}.md")
};
@@ -355,13 +368,20 @@ fn normalize_link_target(raw: &str, page_path: &PagePath, wikilink: bool) -> Opt
return None;
}
+ // A directory target (`notes/`) is not a page: kept, it minted an
+ // extension-less `to_path` (or, for a wikilink, the literal
+ // `notes/.md`) that no page write could ever resolve.
+ if !last_segment_names_a_page(target) {
+ return None;
+ }
+
let mut target = target.to_string();
let last_segment = target.rsplit_once('/').map_or(target.as_str(), |(_, s)| s);
if last_segment.contains('.') {
if !target.ends_with(".md") {
return None;
}
- } else if wikilink || !last_segment.is_empty() {
+ } else {
target.push_str(".md");
}
@@ -483,6 +503,21 @@ mod tests {
assert_eq!(links[0].path.as_str(), "notes/ok.md");
}
+ #[test]
+ fn directory_and_stemless_targets_are_not_pages() {
+ // `sessions/` used to normalize to the literal `sessions/.md` — a
+ // link no page write could ever resolve; the same trailing-slash
+ // form in the body stayed extension-less, which cannot match a page
+ // path either. Both are dropped now.
+ let fm = serde_json::json!({
+ "relations": {"fixes": ["sessions/", "sessions/.md"]}
+ });
+ assert!(extract_relation_links(&fm).is_empty());
+
+ assert!(extract_links("- [notes/](notes/)\n", &page()).is_empty());
+ assert!(extract_links("- [[notes/]]\n", &page()).is_empty());
+ }
+
#[test]
fn pages_without_relations_extract_nothing() {
assert!(extract_relation_links(&serde_json::json!({})).is_empty());
diff --git a/docs/typed-edges.md b/docs/typed-edges.md
index f25f74ee..87e684d1 100644
--- a/docs/typed-edges.md
+++ b/docs/typed-edges.md
@@ -66,7 +66,8 @@ gain `.md`.
## Who writes them
- **You**, in any page's frontmatter (the wiki files are plain
- markdown — edit and `reindex`, or let the watcher pick it up).
+ markdown — edit them and let the watcher reindex the page; `ai-memory
+ reindex` only rebuilds a clean store from the markdown).
- **The consolidator**, sparingly: both single-page consolidation and
`memory_consolidate` with `multi_page=true` can preserve a relation
when the session's evidence states it plainly (a fix