Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(profile): set applies_to and enforced_by from memory_write_page and write-page
Felipe Neves Ricardoeed3f79b0429
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b4aee91..549688e9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -101,6 +101,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0summaries without an API key. The default model is `cursor-grok-4.6-high`("Grok 4.6"). `AI_MEMORY_CURSOR_AGENT` overrides the binary. The provider never passes`--yolo` or `--force`, because the prompt is captured session text. (#1127)+- Added `applies_to` and `enforced_by` arguments to `memory_write_page`, and+ `--applies-to` / `--enforced-by` to `ai-memory write-page`, for profile+ entries. Both fields were documented as profile-entry frontmatter, but no+ tool could set them, so scoping an entry to a stack or keeping it out of the+ digest meant editing the wiki file by hand, and the next tool rewrite of the+ entry dropped the value. (#1178)### Changed- Changed `ai-memory-wikisync` files to carry a small frontmatter (`title`,diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 78d767dd..c539985c 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -3312,6 +3312,15 @@ pub struct WritePageArgs {/// Pin the page so the future decay sweep skips it.#[arg(long)]pub pinned: bool,+ /// Profile entries only (`profile/...` paths): repeatable stack tag+ /// (`rust`, `typescript`, ...) limiting the entry to projects on that+ /// stack.+ #[arg(long = "applies-to")]+ pub applies_to: Vec<String>,+ /// Profile entries only: what already enforces the entry (e.g.+ /// `pre-push hook`), which keeps it out of the session-start digest.+ #[arg(long = "enforced-by")]+ pub enforced_by: Option<String>,/// Workspace name (auto-created if absent).#[arg(long)]pub workspace: Option<String>,@@ -3327,6 +3336,30 @@ mod tests {use clap::{CommandFactory, Parser};use std::collections::BTreeSet;+ #[test]+ fn write_page_takes_the_profile_entry_fields() {+ let parsed = Cli::try_parse_from([+ "ai-memory",+ "write-page",+ "--path",+ "profile/style/types.md",+ "--body",+ "Never cast.",+ "--applies-to",+ "rust",+ "--applies-to",+ "typescript",+ "--enforced-by",+ "pre-push hook",+ ])+ .expect("write-page profile args parse");+ let Command::WritePage(args) = parsed.command else {+ panic!("expected write-page command");+ };+ assert_eq!(args.applies_to, ["rust", "typescript"]);+ assert_eq!(args.enforced_by.as_deref(), Some("pre-push hook"));+ }+#[test]fn serve_api_only_flag_does_not_enable_the_web_ui() {let parsed =diff --git a/crates/ai-memory-cli/src/commands/write_page.rs b/crates/ai-memory-cli/src/commands/write_page.rsindex 4a01b9c1..9300f2ef 100644--- a/crates/ai-memory-cli/src/commands/write_page.rs+++ b/crates/ai-memory-cli/src/commands/write_page.rs@@ -26,6 +26,10 @@ struct WritePageBody {tier: String,tags: Vec<String>,pinned: bool,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ applies_to: Vec<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ enforced_by: Option<String>,}#[derive(Deserialize)]@@ -72,6 +76,8 @@ pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {tier: args.tier,tags: args.tag,pinned: args.pinned,+ applies_to: args.applies_to,+ enforced_by: args.enforced_by,},).awaitdiff --git a/crates/ai-memory-core/src/page.rs b/crates/ai-memory-core/src/page.rsindex d9324a10..d1f11168 100644--- a/crates/ai-memory-core/src/page.rs+++ b/crates/ai-memory-core/src/page.rs@@ -168,6 +168,12 @@ pub const MAX_PAGE_ABSTRACT_LEN: usize = 1024;pub const MAX_PAGE_RELATIONS: usize = 32;/// Maximum raw characters in one relation target, including its scope qualifier.pub const MAX_PAGE_RELATION_TARGET_LEN: usize = 1024;+/// Maximum `applies_to` tags in one write.+pub const MAX_PAGE_APPLIES_TO: usize = 16;+/// Maximum raw characters in one `applies_to` tag, before trimming.+pub const MAX_PAGE_APPLIES_TO_TAG_LEN: usize = 32;+/// Maximum raw characters in `enforced_by`, before trimming.+pub const MAX_PAGE_ENFORCED_BY_LEN: usize = 256;/// Editable metadata shared by public page-write surfaces.///@@ -196,6 +202,18 @@ pub struct PageWriteMetadata {/// `workspace/project:path`) requires already-trimmed scope components.#[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.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ #[schemars(length(max = 16))]+ pub applies_to: Vec<String>,+ /// Profile entries only: what already enforces the entry (`pre-push+ /// hook`), which keeps it out of the session-start digest. At most 256 raw+ /// characters, then trimmed. Empty means absent.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(length(max = 256))]+ pub enforced_by: Option<String>,}impl PageWriteMetadata {@@ -219,6 +237,7 @@ impl PageWriteMetadata {for (key, value, max) in [("kind", self.kind, MAX_PAGE_KIND_LEN),("abstract", self.abstract_text, MAX_PAGE_ABSTRACT_LEN),+ ("enforced_by", self.enforced_by, MAX_PAGE_ENFORCED_BY_LEN),] {if let Some(value) = value {if !valid_text(&value, max) {@@ -288,6 +307,24 @@ impl PageWriteMetadata {if !self.relations.is_empty() {fm.insert("relations".into(), serde_json::json!(self.relations));}+ if self.applies_to.len() > MAX_PAGE_APPLIES_TO+ || self+ .applies_to+ .iter()+ .any(|tag| !valid_text(tag, MAX_PAGE_APPLIES_TO_TAG_LEN))+ {+ 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();+ if !applies_to.is_empty() {+ fm.insert("applies_to".into(), serde_json::json!(applies_to));+ }Ok(fm)}}@@ -702,6 +739,57 @@ mod tests {}}+ #[test]+ fn page_write_metadata_profile_fields_normalize_like_the_digest_reads_them() {+ let metadata: PageWriteMetadata = serde_json::from_value(serde_json::json!({+ "applies_to": [" TypeScript ", "rust", "typescript", ""],+ "enforced_by": " pre-push hook ",+ }))+ .unwrap();+ let fm = metadata.into_frontmatter().unwrap();+ assert_eq!(fm["applies_to"], serde_json::json!(["rust", "typescript"]));+ assert_eq!(fm["enforced_by"], "pre-push hook");+ // What the write stores, the digest reads back unchanged.+ let entry = crate::profile::ProfileEntry::from_page(+ "profile/style/types.md",+ "Types",+ "Never cast.",+ &serde_json::Value::Object(fm),+ )+ .unwrap();+ assert_eq!(entry.applies_to, ["rust", "typescript"]);+ assert!(entry.enforced_by);++ let blank: PageWriteMetadata = serde_json::from_value(serde_json::json!({+ "applies_to": [" "], "enforced_by": " ",+ }))+ .unwrap();+ assert!(blank.into_frontmatter().unwrap().is_empty());+ }++ #[test]+ fn page_write_metadata_profile_fields_refuse_oversized_input() {+ for bad in [+ 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"]}),+ serde_json::json!({"enforced_by": "x".repeat(MAX_PAGE_ENFORCED_BY_LEN + 1)}),+ serde_json::json!({"enforced_by": "hook\u{7}"}),+ ] {+ let metadata: PageWriteMetadata = serde_json::from_value(bad.clone()).unwrap();+ assert!(metadata.into_frontmatter().is_err(), "{bad}");+ }+ for bad in [+ serde_json::json!({"applies_to": "rust"}),+ serde_json::json!({"enforced_by": true}),+ ] {+ assert!(+ serde_json::from_value::<PageWriteMetadata>(bad.clone()).is_err(),+ "{bad}"+ );+ }+ }+#[test]fn tier_round_trips() {for t in [diff --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 7b4a8813..180bf31f 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; optional frontmatter `applies_to` (e.g. `rust`) scopes it to projects on that stack. 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; 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/server.rs b/crates/ai-memory-mcp/src/server.rsindex 5322a2c8..53ec3542 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -339,7 +339,8 @@ should be proposed from a completed session, or at explicit wrap-up \fact is a standing user/team preference that should apply to EVERY \project ('always use pnpm', 'never force-push', code style rules), \pass `scope: \"profile\"` so it joins the cross-project profile \- (stored under `profile/`, delivered to every project as a default); \+ (stored under `profile/`, delivered to every project as a default), \+ optionally with `applies_to` stack tags and `enforced_by`; \`scope: \"global\"` writes the shared `_global` scope directly. When \the user explicitly wants a \time-bounded note, pass `expires_at` as RFC3339 or `YYYY-MM-DD`; the \@@ -4289,8 +4290,11 @@ impl AiMemoryServer {`scope: \"profile\"` — the page joins the cross-project profile \under `profile/` (its path gains that prefix), reaches every \project's session start as a default, and default memory_query \- calls surface it. `scope: \"global\"` writes the reserved \- `_global` scope directly. \+ 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 \+ reserved `_global` scope directly. \\Optional `kind`, `entities`, `abstract`, and `relations` carry bounded \metadata. This replaces the whole page; omitted metadata is cleared. \@@ -15598,6 +15602,83 @@ mod tests {.expect_err("scope: profile is refused while the profile is off");}+ /// `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).+ #[tokio::test]+ async fn memory_write_page_sets_profile_applies_to_and_enforced_by() {+ 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 wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, app)+ .with_wiki(wiki.clone());+ let with_fields = |applies_to: &[&str], enforced_by: Option<&str>| {+ let mut args = profile_entry("style/types.md", Some("profile"));+ args.metadata.applies_to = applies_to.iter().map(|t| (*t).to_owned()).collect();+ args.metadata.enforced_by = enforced_by.map(str::to_owned);+ args+ };++ server+ .memory_write_page(+ Parameters(with_fields(&["TypeScript"], Some("pre-push hook"))),+ OptionalParts(test_parts_default()),+ )+ .await+ .expect("a profile entry takes both fields");+ let global = store+ .writer+ .get_or_create_project(ws, ai_memory_core::GLOBAL_SCOPE_PROJECT, None)+ .await+ .unwrap();+ let path = PagePath::new("profile/style/types.md").unwrap();+ let read = |wiki: &Wiki| {+ let md = wiki.read_page(ws, global, &path).unwrap();+ ai_memory_core::profile::ProfileEntry::from_page(+ path.as_str(),+ "",+ &md.body,+ &md.frontmatter,+ )+ .unwrap()+ };+ let entry = read(&wiki);+ assert_eq!(entry.applies_to, ["typescript"]);+ assert!(entry.enforced_by);++ server+ .memory_write_page(+ Parameters(with_fields(&["typescript"], Some("pre-push hook"))),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let entry = read(&wiki);+ assert_eq!(entry.applies_to, ["typescript"], "passed again, kept");+ assert!(entry.enforced_by);++ server+ .memory_write_page(+ Parameters(with_fields(&[], None)),+ OptionalParts(test_parts_default()),+ )+ .await+ .unwrap();+ let entry = read(&wiki);+ assert!(entry.applies_to.is_empty(), "omitted on rewrite, cleared");+ assert!(!entry.enforced_by);+ }+/// The finding that started #708, as a test.////// Two `role=user` accounts on upstream 2.1.1: alice writes a page into herdiff --git a/crates/ai-memory-mcp/tests/suite/admin_write_page.rs b/crates/ai-memory-mcp/tests/suite/admin_write_page.rsindex 91d63de4..a4096034 100644--- a/crates/ai-memory-mcp/tests/suite/admin_write_page.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_write_page.rs@@ -718,3 +718,36 @@ async fn write_page_metadata_store_failure_rolls_back_and_recovers() {original_id);}++/// The route `ai-memory write-page` posts to sets a profile entry's+/// `applies_to` and `enforced_by`.+#[tokio::test]+async fn write_page_sets_profile_fields() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let request = json!({+ "workspace": "default", "project": "_global", "path": "profile/style/types.md",+ "body": "# Types\n\nNever cast.", "applies_to": ["TypeScript"],+ "enforced_by": "pre-push hook"+ });+ assert_eq!(+ post_json(state.clone(), "/admin/write-page", request)+ .await+ .status(),+ StatusCode::OK+ );+ let ws = state+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let global = state+ .writer+ .get_or_create_project(ws, "_global", None)+ .await+ .unwrap();+ let path = ai_memory_core::PagePath::new("profile/style/types.md").unwrap();+ 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");+}diff --git a/docs/cookbook.md b/docs/cookbook.mdindex 4366b22b..bb59aac2 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -78,7 +78,9 @@ say nothing. A brand-new repository gets the whole baseline, plus a pointer toforget tools/pnpm.md` (it stays dropped until you say it again).- Keep a client project out of it: `[profile] contribute = false` in thatrepository's `.ai-memory.toml`; keep the digest out of one: `consume = false`.-- Scope an entry to a stack with frontmatter `applies_to: [rust]`.+- Scope an entry to a stack with `applies_to: ["rust"]` on `memory_write_page`+ (`--applies-to rust` on `write-page`), or mark it `enforced_by` to keep it+ out of the digest.- On by default for a single user (one profile across every workspace). On ashared server it is off until the operator sets `[profile] enabled = true`,and then each person gets a private profile.diff --git a/docs/cross-project-profile.md b/docs/cross-project-profile.mdindex b8a40151..46f944a3 100644--- a/docs/cross-project-profile.md+++ b/docs/cross-project-profile.md@@ -99,6 +99,13 @@ folder: `stack`, `architecture`, `workflow`, `testing`, `tools`, `style` or| `applies_to` | Stack tags the entry is scoped to, e.g. `[rust]` or `typescript`. || `enforced_by` | Something already enforces it (e.g. `pre-push hook`); kept out of the digest. |+`memory_write_page` and `ai-memory write-page` set the last two directly:+`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.+Entries are ordinary wiki pages, markdown in git: edit them by hand, and everychange is versioned. `memory_delete_page` with `scope: "profile"` removes one(git keeps its history). Most entries, though, are learned on their own; see