Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(profile): refuse applies_to tags no project has, and both fields off the profile
Felipe Neves Ricardo5410fe86bbdd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 549688e9..33ef8931 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -106,7 +106,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0entries. Both fields were documented as profile-entry frontmatter, but notool could set them, so scoping an entry to a stack or keeping it out of thedigest meant editing the wiki file by hand, and the next tool rewrite of the- entry dropped the value. (#1178)+ entry dropped the value. A tag the profile cannot detect in any project+ (`typscript`) is refused instead of silently hiding the entry, and both+ arguments are refused on any page the digest does not read: one outside+ `profile/`, or a `profile/` path in an ordinary project. (#1178)### Changed- Changed `ai-memory-wikisync` files to carry a small frontmatter (`title`,diff --git a/crates/ai-memory-core/src/page.rs b/crates/ai-memory-core/src/page.rsindex d1f11168..0d06dcd5 100644--- a/crates/ai-memory-core/src/page.rs+++ b/crates/ai-memory-core/src/page.rs@@ -203,8 +203,8 @@ pub struct PageWriteMetadata {#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]pub relations: std::collections::BTreeMap<Relation, Vec<String>>,/// Profile entries only: stack tags (`rust`, `typescript`, ...) that limit- /// the entry to projects on that stack. Up to 16; lowercased and- /// deduplicated.+ /// the entry to projects on that stack. Up to 16, each a tag the profile+ /// detects; lowercased and deduplicated.#[serde(default, skip_serializing_if = "Vec::is_empty")]#[schemars(length(max = 16))]pub applies_to: Vec<String>,@@ -315,13 +315,24 @@ impl PageWriteMetadata {{return Err(invalid("applies_to"));}- // The same normalization `ProfileEntry::from_page` applies on read.- let applies_to: std::collections::BTreeSet<String> = self- .applies_to- .iter()- .map(|tag| tag.trim().to_ascii_lowercase())- .filter(|tag| !tag.is_empty())- .collect();+ // The same normalization `ProfileEntry::from_page` applies on read,+ // plus a check the reader cannot make: a tag no project can be+ // detected with would hide the entry from every project with activity.+ let known = crate::profile::detectable_stack_tags();+ let mut applies_to = std::collections::BTreeSet::new();+ for tag in &self.applies_to {+ let tag = tag.trim().to_ascii_lowercase();+ if tag.is_empty() {+ continue;+ }+ if !known.contains(tag.as_str()) {+ return Err(crate::MemoryError::MalformedRecord(format!(+ "unknown applies_to tag '{tag}'; known stack tags: {}",+ known.into_iter().collect::<Vec<_>>().join(", ")+ )));+ }+ applies_to.insert(tag);+ }if !applies_to.is_empty() {fm.insert("applies_to".into(), serde_json::json!(applies_to));}@@ -329,6 +340,39 @@ impl PageWriteMetadata {}}+/// Refuse the profile-only keys (`applies_to`, `enforced_by`) on a page the+/// digest never reads, where the caller's intent would silently do nothing:+/// one outside `profile/`, or one written to a project that cannot hold a+/// profile. `profile_scope` says whether the write targets the profile+/// (`scope: "profile"`, or `_global` or a reserved profile project by name);+/// the caller decides it from the request, before any scope is created.+///+/// # Errors+/// Returns `MalformedRecord` naming the first such key.+pub fn ensure_profile_metadata_placement(+ frontmatter: &serde_json::Map<String, serde_json::Value>,+ path: &PagePath,+ profile_scope: bool,+) -> Result<(), crate::MemoryError> {+ if profile_scope+ && path+ .as_str()+ .starts_with(crate::profile::PROFILE_PATH_PREFIX)+ {+ return Ok(());+ }+ match ["applies_to", "enforced_by"]+ .into_iter()+ .find(|key| frontmatter.contains_key(*key))+ {+ Some(key) => Err(crate::MemoryError::MalformedRecord(format!(+ "{key} applies only to profile entries: write with scope \"profile\", \+ or under a `profile/` path in `_global` or a profile project"+ ))),+ None => Ok(()),+ }+}+/// Normalise one entity name for storage and matching: trim, collapse/// internal whitespace, lowercase. Returns `None` when the result is/// empty, contains control characters, or is longer than@@ -768,8 +812,10 @@ mod tests {}#[test]- fn page_write_metadata_profile_fields_refuse_oversized_input() {+ fn page_write_metadata_profile_fields_refuse_unknown_and_oversized_input() {for bad in [+ serde_json::json!({"applies_to": ["rsut"]}),+ serde_json::json!({"applies_to": ["rust", "react"]}),serde_json::json!({"applies_to": ["x".repeat(MAX_PAGE_APPLIES_TO_TAG_LEN + 1)]}),serde_json::json!({"applies_to": vec!["rust"; MAX_PAGE_APPLIES_TO + 1]}),serde_json::json!({"applies_to": ["ru\0st"]}),@@ -790,6 +836,37 @@ mod tests {}}+ #[test]+ fn profile_metadata_is_refused_outside_profile_pages() {+ let fm = serde_json::from_value::<PageWriteMetadata>(serde_json::json!({+ "applies_to": ["rust"]+ }))+ .unwrap()+ .into_frontmatter()+ .unwrap();+ let profile = PagePath::new("profile/tools/cargo.md").unwrap();+ let note = PagePath::new("notes/cargo.md").unwrap();+ assert!(ensure_profile_metadata_placement(&fm, &profile, true).is_ok());+ assert!(ensure_profile_metadata_placement(&fm, ¬e, true).is_err());+ // A `profile/` path in an ordinary project is never read either.+ assert!(ensure_profile_metadata_placement(&fm, &profile, false).is_err());+ let enforced = serde_json::from_value::<PageWriteMetadata>(serde_json::json!({+ "enforced_by": "hook"+ }))+ .unwrap()+ .into_frontmatter()+ .unwrap();+ assert!(ensure_profile_metadata_placement(&enforced, ¬e, true).is_err());+ // Ordinary metadata stays allowed everywhere.+ let plain = serde_json::from_value::<PageWriteMetadata>(serde_json::json!({+ "kind": "rule"+ }))+ .unwrap()+ .into_frontmatter()+ .unwrap();+ assert!(ensure_profile_metadata_placement(&plain, ¬e, false).is_ok());+ }+#[test]fn tier_round_trips() {for t in [diff --git a/crates/ai-memory-core/src/profile.rs b/crates/ai-memory-core/src/profile.rsindex e6f87601..c810465c 100644--- a/crates/ai-memory-core/src/profile.rs+++ b/crates/ai-memory-core/src/profile.rs@@ -391,6 +391,18 @@ const EXTENSION_TAGS: &[(&str, &str)] = &[(".dart", "dart"),];+/// Every stack tag [`stack_tags_in`] can detect in a project. An entry's+/// `applies_to` tag outside this set matches no project that has activity, so+/// the entry would only ever show in projects with none.+#[must_use]+pub fn detectable_stack_tags() -> BTreeSet<&'static str> {+ MANIFEST_TAGS+ .iter()+ .flat_map(|(_, tags)| tags.iter().copied())+ .chain(EXTENSION_TAGS.iter().map(|(_, tag)| *tag))+ .collect()+}+/// Stack tags named by the file paths mentioned in `text` (observation/// titles, tool summaries). Tokens are split on whitespace and punctuation/// that never appears inside a path, and only a token's file name isdiff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.mdindex 180bf31f..7c6036c9 100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md@@ -90,4 +90,4 @@ Pinned pages are exempt from retention decay and curation, and the auto-improvem## Standing user/team preferences go to the cross-project profile-When the fact is a standing preference that should apply to EVERY project — technology choices ("always use pnpm workspaces"), code style ("prefer composition over inheritance"), personal conventions ("never `--force` without asking") — call `memory_write_page` with `scope: "profile"` instead of the current project. The page joins the cross-project profile under `profile/` (pass a path like `tools/pnpm.md`; it is stored as `profile/tools/pnpm.md`), every project's session start lists it as a default, and default memory reads surface it as `global_scope_hits`. Start the body with a `# Title` and one imperative line; pass `applies_to` (e.g. `["rust"]`) to scope it to projects on that stack, and `enforced_by` (e.g. `"pre-push hook"`) when something already enforces it, which keeps it out of the session-start digest; a rewrite that omits them clears them. Remove one with `memory_delete_page` and `scope: "profile"`. `scope: "global"` still writes the shared `_global` scope directly. Neither scope can be combined with workspace/project arguments. Use it only for genuinely cross-project preferences; project-specific rules stay in the project (or its instruction file, per the section above). A rules file always wins over the profile: the profile is the default for what the repository does not say.+When the fact is a standing preference that should apply to EVERY project — technology choices ("always use pnpm workspaces"), code style ("prefer composition over inheritance"), personal conventions ("never `--force` without asking") — call `memory_write_page` with `scope: "profile"` instead of the current project. The page joins the cross-project profile under `profile/` (pass a path like `tools/pnpm.md`; it is stored as `profile/tools/pnpm.md`), every project's session start lists it as a default, and default memory reads surface it as `global_scope_hits`. Start the body with a `# Title` and one imperative line; pass `applies_to` (e.g. `["rust"]`) to scope it to projects on that stack, and `enforced_by` (e.g. `"pre-push hook"`) when something already enforces it, which keeps it out of the session-start digest; both are accepted only for profile entries, and a rewrite that omits them clears them. Remove one with `memory_delete_page` and `scope: "profile"`. `scope: "global"` still writes the shared `_global` scope directly. Neither scope can be combined with workspace/project arguments. Use it only for genuinely cross-project preferences; project-specific rules stay in the project (or its instruction file, per the section above). A rules file always wins over the profile: the profile is the default for what the repository does not say.diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 3daed612..f869cc10 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -7984,6 +7984,17 @@ async fn handle_write_page(Json(serde_json::json!({ "error": format!("invalid path: {e}") })),)})?;+ ai_memory_core::page::ensure_profile_metadata_placement(+ &metadata,+ &path,+ ai_memory_core::profile::is_reserved_scope_project(req.project.trim()),+ )+ .map_err(|e| {+ (+ StatusCode::UNPROCESSABLE_ENTITY,+ Json(serde_json::json!({ "error": e.to_string() })),+ )+ })?;let target = create_ws_proj(&state, &req.workspace, &req.project).await?;let (ws, proj) = target.scope.as_tuple();diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 53ec3542..01505801 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -4293,7 +4293,7 @@ impl AiMemoryServer {calls surface it. A profile entry also takes `applies_to` (stack \tags such as `rust`, limiting it to projects on that stack) and \`enforced_by` (what already enforces it, which keeps it out of the \- digest). `scope: \"global\"` writes the \+ digest); other pages refuse both. `scope: \"global\"` writes the \reserved `_global` scope directly. \\Optional `kind`, `entities`, `abstract`, and `relations` carry bounded \@@ -4347,11 +4347,23 @@ impl AiMemoryServer {path.ensure_portable().map_err(|e| McpError::internal_error(format!("invalid path: {e}"), None))?;let path = self.place_slot_write(path, &parts).await?;- let path = if args.scope.as_deref().map(str::trim) == Some("profile") {+ let profile_scope = args.scope.as_deref().map(str::trim) == Some("profile");+ let path = if profile_scope {profile_page_path(path)?} else {path};+ ai_memory_core::page::ensure_profile_metadata_placement(+ &metadata,+ &path,+ profile_scope+ || args+ .project+ .as_deref()+ .map(str::trim)+ .is_some_and(ai_memory_core::profile::is_reserved_scope_project),+ )+ .map_err(|e| McpError::invalid_params(e.to_string(), None))?;let session_page =session_id.is_some_and(|id| path.as_str() == format!("sessions/{id}.md"));// Consolidation writes the session page as episodic; keep that@@ -15604,7 +15616,10 @@ mod tests {/// `applies_to` and `enforced_by` reach a profile entry's frontmatter/// through the tool, in the shape the digest reads; a rewrite keeps them- /// only when it passes them again (writes replace all metadata).+ /// only when it passes them again (writes replace all metadata); an+ /// unknown tag, or either key on a page outside `profile/` or on a+ /// `profile/` path in an ordinary project, is refused before anything is+ /// written.#[tokio::test]async fn memory_write_page_sets_profile_applies_to_and_enforced_by() {let tmp = TempDir::new().unwrap();@@ -15667,6 +15682,61 @@ mod tests {assert_eq!(entry.applies_to, ["typescript"], "passed again, kept");assert!(entry.enforced_by);+ let err = server+ .memory_write_page(+ Parameters(with_fields(&["typscript"], None)),+ OptionalParts(test_parts_default()),+ )+ .await+ .expect_err("a tag no project is detected with is refused");+ assert!(err.message.contains("typscript"), "{}", err.message);+ assert_eq!(+ read(&wiki).applies_to,+ ["typescript"],+ "refused write left it"+ );++ let mut stray = with_fields(&["rust"], None);+ stray.scope = None;+ stray.path = "notes/types.md".into();+ stray.workspace = Some("fresh".into());+ stray.project = Some("fresh".into());+ let err = server+ .memory_write_page(Parameters(stray), OptionalParts(test_parts_default()))+ .await+ .expect_err("applies_to is refused outside profile/");+ assert!(err.message.contains("profile"), "{}", err.message);+ assert!(+ store+ .reader+ .find_workspace("fresh".into())+ .await+ .unwrap()+ .is_none(),+ "refused before the scope is created"+ );++ // A `profile/` path in an ordinary project is not a profile entry:+ // the digest never reads it.+ let mut stray = with_fields(&["rust"], None);+ stray.scope = None;+ stray.path = "profile/style/types.md".into();+ stray.workspace = Some("fresh".into());+ stray.project = Some("fresh".into());+ server+ .memory_write_page(Parameters(stray), OptionalParts(test_parts_default()))+ .await+ .expect_err("applies_to is refused on a profile/ path outside the profile");+ assert!(+ store+ .reader+ .find_workspace("fresh".into())+ .await+ .unwrap()+ .is_none(),+ "refused before the scope is created"+ );+server.memory_write_page(Parameters(with_fields(&[], None)),diff --git a/crates/ai-memory-mcp/tests/suite/admin_write_page.rs b/crates/ai-memory-mcp/tests/suite/admin_write_page.rsindex a4096034..35c0985b 100644--- a/crates/ai-memory-mcp/tests/suite/admin_write_page.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_write_page.rs@@ -720,9 +720,11 @@ async fn write_page_metadata_store_failure_rolls_back_and_recovers() {}/// The route `ai-memory write-page` posts to sets a profile entry's-/// `applies_to` and `enforced_by`.+/// `applies_to` and `enforced_by`, refuses an unknown tag with 422, and+/// refuses both keys on a page outside `profile/`, or on a `profile/` path in+/// an ordinary project, before creating its scope.#[tokio::test]-async fn write_page_sets_profile_fields() {+async fn write_page_sets_profile_fields_and_refuses_them_elsewhere() {let tmp = TempDir::new().unwrap();let state = make_state(&tmp).await;let request = json!({@@ -731,7 +733,7 @@ async fn write_page_sets_profile_fields() {"enforced_by": "pre-push hook"});assert_eq!(- post_json(state.clone(), "/admin/write-page", request)+ post_json(state.clone(), "/admin/write-page", request.clone()).await.status(),StatusCode::OK@@ -750,4 +752,38 @@ async fn write_page_sets_profile_fields() {let md = state.wiki.read_page(ws, global, &path).unwrap();assert_eq!(md.frontmatter["applies_to"], json!(["typescript"]));assert_eq!(md.frontmatter["enforced_by"], "pre-push hook");++ let mut unknown = request.clone();+ unknown["applies_to"] = json!(["typscript"]);+ let resp = post_json(state.clone(), "/admin/write-page", unknown).await;+ assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);+ assert!(+ body_json(resp).await["error"]+ .as_str()+ .unwrap()+ .contains("typscript")+ );++ let ws = state+ .reader+ .find_workspace("default".into())+ .await+ .unwrap()+ .unwrap();+ for path in ["notes/types.md", "profile/style/types.md"] {+ let mut stray = request.clone();+ stray["project"] = json!("fresh");+ stray["path"] = json!(path);+ let resp = post_json(state.clone(), "/admin/write-page", stray).await;+ assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY, "{path}");+ assert!(+ state+ .reader+ .find_project(ws, "fresh".into())+ .await+ .unwrap()+ .is_none(),+ "{path}: refused before the project is created"+ );+ }}diff --git a/docs/cross-project-profile.md b/docs/cross-project-profile.mdindex 46f944a3..c7d907a8 100644--- a/docs/cross-project-profile.md+++ b/docs/cross-project-profile.md@@ -103,8 +103,12 @@ folder: `stack`, `architecture`, `workflow`, `testing`, `tools`, `style` or`applies_to: ["rust"]` and `enforced_by: "pre-push hook"` in the tool call,or `--applies-to rust --enforced-by "pre-push hook"` on the command line(with `--workspace default --project _global --path profile/...` in the-default deployment). Like the other metadata, a rewrite that omits them-clears them.+default deployment). A tag must be one the profile detects in a project+(`rust`, `typescript`, `python`, ...); an unknown tag is refused rather than+silently hiding the entry. Like the other metadata, a rewrite that omits them+clears them. Both are refused on a page the digest does not read: one outside+`profile/`, or a `profile/` path in a project other than `_global` or a+profile project.Entries are ordinary wiki pages, markdown in git: edit them by hand, and everychange is versioned. `memory_delete_page` with `scope: "profile"` removes one