Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(profile): apply the profile to a repository's rules file
AkitaOnRails4d1bf3e2a078
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f29fd7e9..0eede3af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,8 +24,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0profile entries in `global_scope_hits`, a marker's `[profile] contribute` /`consume` keys opt a project out of contributing or receiving, and`ai-memory profile status | list | show | forget | review | rebuild`- inspects and curates it. Entries are learned on their own: a server pass,- run after each session ends and hourly, harvests the user's own+ inspects and curates it, while `ai-memory profile apply` writes the entries+ that fit a repository into a managed block of its rules file (`--remove`+ takes it out), never touching anything outside the block. Entries are+ learned on their own: a server pass, run after each session ends and+ hourly, harvests the user's ownpreference-shaped prompts (never tool output), the project's curated pagesand its stack signals, and converges them across projects into entries oncethe user states a choice as general or it appears in `min_projects`@@ -33,7 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0classifies and restates entries through JSON-schema calls and falls back tothe zero-LLM path on any error. It never rewrites an entry edited by hand,and an entry removed with `profile forget` stays removed until the user- states it again. (cross-project profile)+ states it again. (#1000)- Added `ai-memory resume --search` with immediate type-to-filter name search,and `resume --all`, which keeps the previous cross-checkout picker: everylinked checkout, the current one first, each listed with its own fully@@ -224,7 +227,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0then the cross-project profile. Where no hard rule exists, agents now usewhat memory already knows instead of asking again; the routing snippet,MCP instructions and durable-pages skill send standing cross-project- preferences to the profile (`scope: "profile"`). (cross-project profile)+ preferences to the profile (`scope: "profile"`). (#1000)- Scoped `ai-memory resume` to the current checkout by default instead of everylinked project (`--all` restores the old view) and removed its default resultcutoff with bounded server pagination, preserving Left/Right harnessdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 0afa3d79..487dc93d 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -952,6 +952,31 @@ pub enum ProfileCommand {/// Re-read every contributing project from the start and rebuild the/// profile from what it finds (safe to repeat).Rebuild,+ /// Write the profile entries that fit this repository into a managed+ /// block of its rules file, turning your usual choices into hard rules+ /// here. Only the block between the `ai-memory:profile` delimiters is+ /// ever touched; re-running replaces it.+ Apply(ProfileApplyArgs),+}++/// Arguments for `profile apply`.+#[derive(Debug, Args)]+pub struct ProfileApplyArgs {+ /// Rules file to write, relative to the repository root unless absolute.+ /// Default: `AGENTS.md` when it exists, else `CLAUDE.md` unless it only+ /// imports `AGENTS.md`, else a new `AGENTS.md`.+ #[arg(long)]+ pub target: Option<PathBuf>,+ /// Print the block and the target instead of writing.+ #[arg(long)]+ pub dry_run: bool,+ /// Remove the managed block instead of writing it.+ #[arg(long, conflicts_with = "dry_run")]+ pub remove: bool,+ /// Operator whose private profile to use when the profile is per user+ /// (`share = "user"`).+ #[arg(long)]+ pub user: Option<String>,}/// Which profile a `profile` subcommand inspects.diff --git a/crates/ai-memory-cli/src/commands/apply_shared.rs b/crates/ai-memory-cli/src/commands/apply_shared.rsindex b42afe32..c7d3d694 100644--- a/crates/ai-memory-cli/src/commands/apply_shared.rs+++ b/crates/ai-memory-cli/src/commands/apply_shared.rs@@ -79,6 +79,29 @@ pub struct PrivateBackup {pub stem: String,}+/// A [`PrivateBackup::stem`] naming a checkout: its directory flattened to+/// safe characters and bounded to the tail (the repository-name end), plus a+/// short hash of the full path so checkouts that flatten alike stay apart.+pub(crate) fn checkout_backup_stem(checkout: &Path) -> String {+ use sha2::{Digest as _, Sha256};+ let checkout = checkout.to_string_lossy();+ let mut flat = String::with_capacity(checkout.len());+ for c in checkout.chars() {+ let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_') {+ c+ } else {+ '-'+ };+ if !(c == '-' && flat.ends_with('-')) {+ flat.push(c);+ }+ }+ let flat = flat.trim_matches('-');+ let tail = &flat[flat.len().saturating_sub(64)..];+ let digest = format!("{:x}", Sha256::digest(checkout.as_bytes()));+ format!("{}-{}", tail.trim_start_matches('-'), &digest[..12])+}+/// [`apply_atomic`], writing the backup to `private_backup` instead of next/// to `path` when one is given.///diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 93be5437..f734384e 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -133,32 +133,12 @@ pub(crate) fn project_settings_backup(data_dir: &Path, settings: &Path) -> Priva}}-/// A file-name stem naming the checkout `settings` sits in: its directory-/// flattened to safe characters and bounded to the tail (the repository name-/// end), plus a short hash of the full path so checkouts that flatten alike-/// stay apart.+/// A file-name stem naming the checkout `settings` sits in (see+/// [`super::apply_shared::checkout_backup_stem`]).fn project_settings_backup_stem(settings: &Path) -> String {- use sha2::{Digest as _, Sha256};- let checkout = settings- .parent()- .and_then(Path::parent)- .unwrap_or(settings)- .to_string_lossy();- let mut flat = String::with_capacity(checkout.len());- for c in checkout.chars() {- let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_') {- c- } else {- '-'- };- if !(c == '-' && flat.ends_with('-')) {- flat.push(c);- }- }- let flat = flat.trim_matches('-');- let tail = &flat[flat.len().saturating_sub(64)..];- let digest = format!("{:x}", Sha256::digest(checkout.as_bytes()));- format!("{}-{}", tail.trim_start_matches('-'), &digest[..12])+ super::apply_shared::checkout_backup_stem(+ settings.parent().and_then(Path::parent).unwrap_or(settings),+ )}/// The `hooks` table of a Claude-shaped settings document (`hooks` → event →diff --git a/crates/ai-memory-cli/src/commands/profile.rs b/crates/ai-memory-cli/src/commands/profile.rsindex 18284201..ac21660f 100644--- a/crates/ai-memory-cli/src/commands/profile.rs+++ b/crates/ai-memory-cli/src/commands/profile.rs@@ -1,16 +1,20 @@//! `ai-memory profile` — inspect and curate the cross-project profile//! (`docs/cross-project-profile.md`).//!-//! Thin HTTP client: `status`, `list` and `review` read `/admin/profile/*`-//! and `rebuild` posts to it; `show` and `forget` resolve the profile's scope-//! through `status` and then use the ordinary `/admin/read-page` and-//! `/admin/delete-page`, so a profile entry is read and removed exactly like-//! any other page.+//! Thin HTTP client: `status`, `list`, `review` and `apply` read+//! `/admin/profile/*` and `rebuild` posts to it; `show` and `forget` resolve+//! the profile's scope through `status` and then use the ordinary+//! `/admin/read-page` and `/admin/delete-page`, so a profile entry is read and+//! removed exactly like any other page. `apply` is the only command that+//! writes a local file: the managed block of the repository's rules file.++use std::path::{Path, PathBuf};use anyhow::{Context, Result, bail};use serde::Deserialize;-use crate::cli::{ProfileArgs, ProfileCommand, ProfileScopeArgs};+use super::apply_shared::{PrivateBackup, apply_atomic_with_backup, checkout_backup_stem};+use crate::cli::{ProfileApplyArgs, ProfileArgs, ProfileCommand, ProfileScopeArgs};use crate::config::Config;use crate::http_client::{ServerEndpoint, get_json, post_json};@@ -28,6 +32,7 @@ pub async fn run(config: &Config, args: ProfileArgs) -> Result<()> {ProfileCommand::Forget { path, scope } => forget(&ep, &scope, &path).await,ProfileCommand::Review(scope) => review(&ep, &scope).await,ProfileCommand::Rebuild => rebuild(&ep).await,+ ProfileCommand::Apply(args) => apply(&ep, config, &args).await,}}@@ -388,9 +393,157 @@ async fn rebuild(ep: &ServerEndpoint) -> Result<()> {Ok(())}+#[derive(Debug, Deserialize)]+struct ApplyResponse {+ consume: bool,+ lines: Vec<String>,+ omitted: usize,+}++/// `profile apply`: write (or `--remove`) the managed profile block in the+/// current repository's rules file.+async fn apply(ep: &ServerEndpoint, config: &Config, args: &ProfileApplyArgs) -> Result<()> {+ let cwd = std::env::current_dir().context("reading the current directory")?;+ let root = repository_root(&cwd);+ let target = choose_target(&root, args.target.as_deref());+ let backup = PrivateBackup {+ dir: config.data_dir.join("backups").join("profile-apply"),+ stem: checkout_backup_stem(&root),+ };+ if args.remove {+ return remove_block(&target, &backup);+ }+ if let Some(marker) = crate::marker::find_settings_marker(&cwd.to_string_lossy())+ && crate::marker::parse_toml_flag(&marker, "consume")+ .is_some_and(|v| crate::marker::is_falsy(&v))+ {+ bail!(+ "{} sets `[profile] consume = false`, so this project does not take the profile",+ marker.display()+ );+ }+ let (workspace, project) = super::resolve_scope(config, None, None)?;+ let mut query = vec![+ ("workspace", workspace.as_str()),+ ("project", project.as_str()),+ ];+ if let Some(user) = args.user.as_deref() {+ query.push(("user", user));+ }+ let resp: ApplyResponse = get_json(ep, "/admin/profile/apply", &query)+ .await+ .context("reading the profile entries for this project")?;+ if !resp.consume {+ bail!(+ "{workspace}/{project} sets `[profile] consume = false`, so it does not take the profile"+ );+ }+ if resp.lines.is_empty() {+ println!("No profile entries apply to {workspace}/{project}; nothing written.");+ return Ok(());+ }+ let block = ai_memory_core::profile::render_profile_block(&resp.lines, resp.omitted);+ if args.dry_run {+ println!("Would write to {}:\n\n{block}", target.display());+ return Ok(());+ }+ let outcome = apply_atomic_with_backup(&target, Some(&backup), |existing| {+ Ok(ai_memory_core::profile::merge_profile_block(+ existing, &block,+ ))+ })?;+ println!(+ "{}: {} ({} entr{}{})",+ target.display(),+ outcome.verb(),+ resp.lines.len(),+ if resp.lines.len() == 1 { "y" } else { "ies" },+ if resp.omitted > 0 {+ format!(", {} more over apply_max_lines", resp.omitted)+ } else {+ String::new()+ }+ );+ Ok(())+}++fn remove_block(target: &Path, backup: &PrivateBackup) -> Result<()> {+ let existing = match std::fs::read_to_string(target) {+ Ok(text) => text,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ println!("{} does not exist; nothing to remove.", target.display());+ return Ok(());+ }+ Err(error) => {+ return Err(error).with_context(|| format!("reading {}", target.display()));+ }+ };+ let Some(remaining) = ai_memory_core::profile::remove_profile_block(&existing) else {+ println!(+ "{} has no profile block; nothing to remove.",+ target.display()+ );+ return Ok(());+ };+ if remaining.is_empty() {+ // The file held nothing but the block `apply` created it for.+ std::fs::remove_file(target).with_context(|| format!("removing {}", target.display()))?;+ println!(+ "{}: removed (it held only the profile block)",+ target.display()+ );+ return Ok(());+ }+ let outcome = apply_atomic_with_backup(target, Some(backup), |_| Ok(remaining))?;+ println!(+ "{}: profile block removed ({})",+ target.display(),+ outcome.verb()+ );+ Ok(())+}++/// The checkout `cwd` is in: the nearest ancestor holding `.git` (a directory,+/// or the file a linked worktree has), else `cwd` itself.+fn repository_root(cwd: &Path) -> PathBuf {+ cwd.ancestors()+ .find(|dir| dir.join(".git").exists())+ .unwrap_or(cwd)+ .to_path_buf()+}++/// The rules file `apply` writes: `--target` (relative to `root`), else an+/// existing `AGENTS.md`, else an existing `CLAUDE.md` unless it only imports+/// `AGENTS.md` (writing there would be a no-op for every other harness), else+/// a new `AGENTS.md`.+fn choose_target(root: &Path, explicit: Option<&Path>) -> PathBuf {+ if let Some(explicit) = explicit {+ return if explicit.is_absolute() {+ explicit.to_path_buf()+ } else {+ root.join(explicit)+ };+ }+ let agents = root.join("AGENTS.md");+ if agents.exists() {+ return agents;+ }+ let claude = root.join("CLAUDE.md");+ match std::fs::read_to_string(&claude) {+ Ok(text) if !only_imports_agents(&text) => claude,+ _ => agents,+ }+}++/// A `CLAUDE.md` whose every non-blank line is an `@AGENTS.md` import.+fn only_imports_agents(text: &str) -> bool {+ let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());+ lines.clone().next().is_some() && lines.all(|line| line == "@AGENTS.md")+}+#[cfg(test)]mod tests {- use super::profile_path;+ use super::{choose_target, only_imports_agents, profile_path, repository_root};#[test]fn profile_paths_gain_the_prefix_once() {@@ -401,4 +554,52 @@ mod tests {);assert_eq!(profile_path(" /tools/pnpm.md "), "profile/tools/pnpm.md");}++ #[test]+ fn the_target_prefers_agents_then_a_real_claude_md() {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path();+ assert_eq!(+ choose_target(root, None),+ root.join("AGENTS.md"),+ "new AGENTS.md"+ );++ std::fs::write(root.join("CLAUDE.md"), "@AGENTS.md\n").unwrap();+ assert_eq!(+ choose_target(root, None),+ root.join("AGENTS.md"),+ "an import-only CLAUDE.md points at AGENTS.md"+ );+ std::fs::write(root.join("CLAUDE.md"), "# Rules\nUse tabs.\n").unwrap();+ assert_eq!(choose_target(root, None), root.join("CLAUDE.md"));++ std::fs::write(root.join("AGENTS.md"), "# Agents\n").unwrap();+ assert_eq!(choose_target(root, None), root.join("AGENTS.md"));+ assert_eq!(+ choose_target(root, Some(std::path::Path::new("docs/RULES.md"))),+ root.join("docs/RULES.md")+ );+ }++ #[test]+ fn import_only_detection() {+ assert!(only_imports_agents("@AGENTS.md\n"));+ assert!(only_imports_agents("\n @AGENTS.md \n\n"));+ assert!(!only_imports_agents(""));+ assert!(!only_imports_agents("@AGENTS.md\nAlso: use tabs.\n"));+ }++ #[test]+ fn the_root_is_the_nearest_checkout() {+ let dir = tempfile::tempdir().unwrap();+ let repo = dir.path().join("repo");+ let nested = repo.join("crates").join("x");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::create_dir(repo.join(".git")).unwrap();+ assert_eq!(repository_root(&nested), repo);+ let loose = dir.path().join("loose");+ std::fs::create_dir(&loose).unwrap();+ assert_eq!(repository_root(&loose), loose);+ }}diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rsindex ca5ba785..2decbb56 100644--- a/crates/ai-memory-cli/src/marker.rs+++ b/crates/ai-memory-cli/src/marker.rs@@ -433,6 +433,15 @@ pub(crate) fn is_truthy(value: &str) -> bool {)}+/// An explicitly falsy marker flag, for settings that stay on unless turned+/// off (`[profile] contribute` / `consume`), matching the server's reading.+pub(crate) fn is_falsy(value: &str) -> bool {+ matches!(+ value.trim().to_ascii_lowercase().as_str(),+ "0" | "false" | "no" | "off"+ )+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex cdd484ae..eb97b2d1 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -22,6 +22,7 @@ mod jail_toggles_e2e;mod marker_scope;mod message_e2e;mod packaging;+mod profile_e2e;mod removal;mod repo_layout;mod routing_instructions;diff --git a/crates/ai-memory-cli/tests/suite/profile_e2e.rs b/crates/ai-memory-cli/tests/suite/profile_e2e.rsnew file mode 100644index 00000000..f28c9410--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/profile_e2e.rs@@ -0,0 +1,130 @@+//! Use-case end-to-end test for the cross-project profile+//! (`docs/cross-project-profile.md`), driven the way a user meets it: they+//! state a habit in two projects, the profile learns it, and in a brand-new+//! repository `ai-memory profile apply` writes it into the rules file. Re-running+//! changes nothing, and `--remove` restores the file exactly.++/// Spawns a server and several subprocesses: seconds, not milliseconds, so this+/// lives in the slow tier (`cargo tf` / CI), not the everyday loop.+mod slow {+ use std::path::Path;+ use std::time::{Duration, Instant};++ use serde_json::json;++ use crate::e2e_support::{hermetic, run_cli, session_count, start_serve};++ const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++ /// Post one user prompt for `project` through the real hook ingress and+ /// wait until the server has stored its session.+ async fn say(client: &reqwest::Client, base: &str, project: &str, nth: u8, prompt: &str) {+ let session_id = format!("00000000-0000-4000-8000-0000000001{nth:02x}");+ let cwd = format!("/tmp/profile-e2e/{project}");+ for (event, body) in [+ (+ "session-start",+ json!({ "session_id": session_id, "cwd": cwd }),+ ),+ (+ "user-prompt-submit",+ json!({ "session_id": session_id, "cwd": cwd, "prompt": prompt }),+ ),+ ] {+ let resp = client+ .post(format!("{base}/hook"))+ .query(&[("event", event), ("agent", "claude-code")])+ .header("content-type", "application/json")+ .body(body.to_string())+ .send()+ .await+ .expect("hook request");+ assert!(resp.status().is_success(), "{event}: {}", resp.status());+ }+ let deadline = Instant::now() + Duration::from_secs(10);+ while session_count(client, base, "default", project).await < 1 {+ assert!(Instant::now() < deadline, "{project} was never stored");+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ }++ fn apply(repo: &Path, data_dir: &Path, home: &Path, base: &str, extra: &[&str]) -> String {+ let mut args = vec!["profile", "apply"];+ args.extend_from_slice(extra);+ run_cli(&args, data_dir, home, Some(repo), base)+ }++ #[tokio::test]+ async fn a_habit_from_two_projects_is_applied_to_a_new_repository() {+ let data_dir = tempfile::tempdir().expect("data dir");+ let home = tempfile::tempdir().expect("home");+ let client = reqwest::Client::new();+ let (server, base) = start_serve(&client, &data_dir.path().join("serve.log"), |port| {+ let mut cmd = hermetic(BIN);+ cmd.args([+ "serve",+ "--transport",+ "http",+ "--bind",+ &format!("127.0.0.1:{port}"),+ "--no-watcher",+ ])+ .env("AI_MEMORY_DATA_DIR", data_dir.path())+ .env("AI_MEMORY_HOME", home.path())+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none");+ cmd+ })+ .await;++ say(&client, &base, "alpha", 1, "I prefer tabs over spaces.").await;+ say(&client, &base, "beta", 2, "I prefer tabs over spaces.").await;+ let rebuilt = run_cli(+ &["profile", "rebuild"],+ data_dir.path(),+ home.path(),+ None,+ &base,+ );+ assert!(rebuilt.contains("1 entry written"), "{rebuilt}");++ let workspace = tempfile::tempdir().expect("repos");+ let repo = workspace.path().join("gamma");+ std::fs::create_dir_all(repo.join(".git")).expect("fake checkout");+ let original = "# Gamma rules\n\nUse tabs? Decide later.\n";+ std::fs::write(repo.join("AGENTS.md"), original).expect("seed AGENTS.md");++ let dry = apply(&repo, data_dir.path(), home.path(), &base, &["--dry-run"]);+ assert!(dry.contains("tabs over spaces"), "{dry}");+ assert_eq!(+ std::fs::read_to_string(repo.join("AGENTS.md")).unwrap(),+ original,+ "--dry-run writes nothing"+ );++ let out = apply(&repo, data_dir.path(), home.path(), &base, &[]);+ assert!(out.contains("updated"), "{out}");+ let written = std::fs::read_to_string(repo.join("AGENTS.md")).unwrap();+ assert!(written.starts_with(original), "{written}");+ assert!(written.contains("<!-- ai-memory:profile:start -->"));+ assert!(written.contains("tabs over spaces"), "{written}");++ let again = apply(&repo, data_dir.path(), home.path(), &base, &[]);+ assert!(again.contains("no-op"), "a re-run is idempotent: {again}");+ assert!(+ !repo.read_dir().unwrap().any(|e| e+ .unwrap()+ .file_name()+ .to_string_lossy()+ .contains(".bak")),+ "the backup stays out of the checkout"+ );++ apply(&repo, data_dir.path(), home.path(), &base, &["--remove"]);+ assert_eq!(+ std::fs::read_to_string(repo.join("AGENTS.md")).unwrap(),+ original,+ "--remove restores the file"+ );+ drop(server);+ }+}diff --git a/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs b/crates/ai-memory-consolidate/tests/suite/profile_harvest.rsindex e8279c1b..11fd09b1 100644--- a/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs+++ b/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs@@ -758,6 +758,62 @@ async fn a_provider_failure_falls_back_to_the_zero_llm_path() {assert!(pages[0].1.contains("Always use pnpm for installs."));}+/// The core scenario on the LLM path: a habit said loosely in one project is+/// classified as general, merged into an entry, and lands in the baseline+/// digest of a brand-new project, scoped to the stack it applies to. A project+/// that set `[profile] consume = false` is recorded as such, which is what the+/// session start and the query union read to leave it out.+#[tokio::test]+async fn the_llm_path_reaches_a_new_projects_baseline_digest() {+ let fx = fixture().await;+ let alpha = project(&fx, "alpha").await;+ prompt(&fx, alpha, "always pnpm pls, never npm in here", 1).await;+ let llm = FakeProfileLlm {+ merge_statement: "Use pnpm for every JavaScript project.".into(),+ ..FakeProfileLlm::default()+ };+ pass_with(&fx, &single_user(), Arc::new(llm)).await;++ let global = ai_memory_store::lookup_global_scope(&fx.store.reader)+ .await+ .unwrap()+ .unwrap();+ let gamma = project(&fx, "gamma").await;+ let inputs = fx+ .store+ .reader+ .profile_digest_inputs(global.as_tuple(), (fx.ws, gamma))+ .await+ .unwrap();+ assert!(!inputs.project_has_pages, "gamma is brand new");+ let digest = render_digest(&inputs.entries, &inputs.project_tags, 6_000, true).unwrap();+ assert!(+ digest.contains("[javascript] Use pnpm for every JavaScript project."),+ "{digest}"+ );+ assert!(digest.contains("ai-memory profile apply"), "{digest}");++ let opted_out = project(&fx, "client-work").await;+ fx.store+ .writer+ .set_project_profile_flags(+ opted_out,+ ProjectProfileFlags {+ contribute: true,+ consume: false,+ },+ )+ .await+ .unwrap();+ let flags = fx+ .store+ .reader+ .project_profile_flags(fx.ws, opted_out)+ .await+ .unwrap();+ assert!(!flags.consume);+}+/// A profile that is off harvests nothing (multi-user default).#[tokio::test]async fn a_multi_user_server_harvests_nothing_by_default() {diff --git a/crates/ai-memory-consolidate/tests/suite/recall_eval.rs b/crates/ai-memory-consolidate/tests/suite/recall_eval.rsindex bf00d48a..1209dca9 100644--- a/crates/ai-memory-consolidate/tests/suite/recall_eval.rs+++ b/crates/ai-memory-consolidate/tests/suite/recall_eval.rs@@ -519,6 +519,115 @@ async fn raw_observation_fallback_recovers_detail_when_wiki_misses() {assert!(raw_hits[0].snippet.contains("<mark>capybara</mark>"));}+/// Cross-project profile recall (`docs/cross-project-profile.md`): a habit the+/// user stated in two projects becomes a profile entry that a task-level+/// query finds in the profile scope, where every other project's+/// `memory_query` unions it. A choice only one project made stays out.+#[tokio::test]+async fn profile_recall_across_projects() {+ use ai_memory_consolidate::profile::{ProfilePassConfig, run_profile_pass};++ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("open store");+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .expect("ws");+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .expect("wiki")+ .with_store_reader(store.reader.clone());+ for (project, prompt) in [+ ("alpha", "I prefer tabs over spaces."),+ ("beta", "I prefer tabs over spaces."),+ (+ "alpha",+ "Use the legacy webpack builder instead of vite in this repo.",+ ),+ ] {+ let proj = store+ .writer+ .get_or_create_project(ws, project, None)+ .await+ .expect("proj");+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ occurred_at: None,+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ actor_user: None,+ })+ .await+ .expect("begin session");+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ occurred_at: None,+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: prompt.into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .expect("insert observation");+ }+ let config = ProfilePassConfig {+ settings: ai_memory_core::profile::ProfileSettings::default(),+ distinguishes_operators: false,+ };+ run_profile_pass(&store.reader, &store.writer, &wiki, None, &config)+ .await+ .expect("profile pass");++ let global = ai_memory_store::lookup_global_scope(&store.reader)+ .await+ .expect("lookup")+ .expect("the profile scope exists");+ let hits = store+ .reader+ .search_pages_for_project(+ global.workspace_id,+ global.project_id,+ "tabs spaces".into(),+ 5,+ None,+ )+ .await+ .expect("profile search");+ assert!(+ hits.iter().any(|h| h.path.as_str().starts_with("profile/")),+ "the converged habit is recallable from the profile: {hits:?}"+ );+ let local = store+ .reader+ .search_pages_for_project(+ global.workspace_id,+ global.project_id,+ "webpack builder".into(),+ 5,+ None,+ )+ .await+ .expect("profile search");+ assert!(+ local.is_empty(),+ "a one-project exception never reaches the profile: {local:?}"+ );+}+async fn measure_recall(store: &Store,ws: ai_memory_core::WorkspaceId,diff --git a/crates/ai-memory-core/src/profile.rs b/crates/ai-memory-core/src/profile.rsindex 7177ff63..5792bde1 100644--- a/crates/ai-memory-core/src/profile.rs+++ b/crates/ai-memory-core/src/profile.rs@@ -4,8 +4,9 @@//! works across projects. This module holds the parts with no IO: the//! `[profile]` settings and the rule that turns them into an effective mode//! for a deployment, the reserved scope names, stack-signal detection, entry-//! parsing, and the SessionStart digest renderer. The store resolves the-//! scopes and the hook router delivers the digest.+//! parsing, the SessionStart digest renderer, and the managed rules-file+//! block `ai-memory profile apply` writes. The store resolves the scopes, the+//! hook router delivers the digest and the CLI writes the block.use std::collections::BTreeSet;@@ -592,14 +593,10 @@ pub fn render_digest(budget: usize,baseline: bool,) -> Option<String> {- let mut selected: Vec<&ProfileEntry> = entries- .iter()- .filter(|entry| !entry.enforced_by && entry.applies(project_tags))- .collect();+ let selected = select_entries(entries, project_tags);if selected.is_empty() {return None;}- selected.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()));let mut head = String::new();head.push_str(DIGEST_TITLE);@@ -619,18 +616,7 @@ pub fn render_digest(let lines: Vec<String> = selected.iter()- .map(|entry| {- let scope = if entry.applies_to.is_empty() {- String::new()- } else {- format!("[{}] ", entry.applies_to.join(", "))- };- format!(- "- {scope}{statement} (`{path}`)\n",- statement = escape_fences(&entry.statement),- path = entry.path,- )- })+ .map(|entry| format!("{}\n", entry_line(entry))).collect();let room = budget.saturating_sub(head.len() + tail.len());@@ -658,6 +644,135 @@ pub fn render_digest(Some(format!("{head}{body}{tail}"))}+/// The entries a project receives, digest or rules file alike: not enforced+/// elsewhere, scoped to a stack the project shows (or to none), in the fixed+/// category-then-path order.+fn select_entries<'a>(+ entries: &'a [ProfileEntry],+ project_tags: &BTreeSet<String>,+) -> Vec<&'a ProfileEntry> {+ let mut selected: Vec<&ProfileEntry> = entries+ .iter()+ .filter(|entry| !entry.enforced_by && entry.applies(project_tags))+ .collect();+ selected.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()));+ selected+}++/// `- [scope] statement (`path`)`, with every fence and managed-block+/// delimiter in the statement neutralized so stored text can never close a+/// region it is rendered into.+fn entry_line(entry: &ProfileEntry) -> String {+ let scope = if entry.applies_to.is_empty() {+ String::new()+ } else {+ format!("[{}] ", entry.applies_to.join(", "))+ };+ format!(+ "- {scope}{statement} (`{path}`)",+ statement = escape_fences(&entry.statement),+ path = entry.path,+ )+}++/// Opening delimiter of the rules-file block `ai-memory profile apply` manages.+pub const PROFILE_BLOCK_START: &str = "<!-- ai-memory:profile:start -->";+/// Closing delimiter of the rules-file block `ai-memory profile apply` manages.+pub const PROFILE_BLOCK_END: &str = "<!-- ai-memory:profile:end -->";++const PROFILE_BLOCK_HEADING: &str = "## Usual choices (ai-memory profile)\n\n\+ Written by `ai-memory profile apply` from the user's cross-project profile. \+ Change the profile (`ai-memory profile show` / `forget`) and re-run the command \+ instead of editing this block. Everything else in this file takes precedence.\n\n";++/// The rules-file lines for a project: at most `max_lines` entries, selected+/// and ordered like the digest, plus how many applicable entries did not fit.+#[must_use]+pub fn apply_lines(+ entries: &[ProfileEntry],+ project_tags: &BTreeSet<String>,+ max_lines: usize,+) -> (Vec<String>, usize) {+ let selected = select_entries(entries, project_tags);+ let omitted = selected.len().saturating_sub(max_lines);+ let lines = selected+ .into_iter()+ .take(max_lines)+ .map(entry_line)+ .collect();+ (lines, omitted)+}++/// The managed block for `lines`, delimiters included and ending in a+/// newline. Nothing time-dependent is printed, so re-running `apply` on an+/// unchanged profile leaves the file byte-identical.+#[must_use]+pub fn render_profile_block(lines: &[String], omitted: usize) -> String {+ let mut block = String::new();+ block.push_str(PROFILE_BLOCK_START);+ block.push('\n');+ block.push_str(PROFILE_BLOCK_HEADING);+ for line in lines {+ block.push_str(line);+ block.push('\n');+ }+ if omitted > 0 {+ block.push_str(&format!(+ "- …and {omitted} more (`ai-memory profile list`)\n"+ ));+ }+ block.push_str(PROFILE_BLOCK_END);+ block.push('\n');+ block+}++/// Byte range of the managed block in `text`: both delimiters plus the line+/// break after the closing one. Only delimiters alone on their line count, so+/// a quoted mention in prose is never mistaken for one.+fn profile_block_range(text: &str) -> Option<(usize, usize)> {+ let start = crate::find_marker_line(text, PROFILE_BLOCK_START, 0)?;+ let end = crate::find_marker_line(text, PROFILE_BLOCK_END, start)?;+ let mut after = end + PROFILE_BLOCK_END.len();+ if text[after..].starts_with("\r\n") {+ after += 2;+ } else if text[after..].starts_with('\n') {+ after += 1;+ }+ Some((start, after))+}++/// Replace the managed block in `existing` with `block`, or append it after a+/// blank line. Text outside the delimiters, the routing block included, is+/// never touched.+#[must_use]+pub fn merge_profile_block(existing: &str, block: &str) -> String {+ if let Some((start, end)) = profile_block_range(existing) {+ return format!("{}{block}{}", &existing[..start], &existing[end..]);+ }+ let mut out = existing.to_owned();+ if !out.is_empty() {+ if !out.ends_with('\n') {+ out.push('\n');+ }+ out.push('\n');+ }+ out.push_str(block);+ out+}++/// Remove the managed block from `existing`, together with the blank line+/// [`merge_profile_block`] put before an appended block, so apply followed by+/// remove restores the file. `None` when there is no block.+#[must_use]+pub fn remove_profile_block(existing: &str) -> Option<String> {+ let (start, end) = profile_block_range(existing)?;+ let mut head = &existing[..start];+ if end == existing.len() && head.ends_with("\n\n") {+ head = &head[..head.len() - 1];+ }+ Some(format!("{head}{}", &existing[end..]))+}+fn omitted_line(count: usize) -> String {format!("- …and {count} more profile entr{} (`memory_query` finds them)\n",@@ -665,15 +780,12 @@ fn omitted_line(count: usize) -> String {)}+/// Neutralize every ai-memory HTML-comment delimiter in stored text: the+/// untrusted-history fences, the routing block and the profile block. Any+/// `<!-- ai-memory:` opener is defused, so a statement can neither close the+/// digest fence nor end a managed rules-file block early.fn escape_fences(text: &str) -> String {- text.replace(- UNTRUSTED_HISTORY_START,- "<!-- ai-memory:untrusted-history:start -->",- )- .replace(- UNTRUSTED_HISTORY_END,- "<!-- ai-memory:untrusted-history:end -->",- )+ text.replace("<!-- ai-memory:", "<!-- ai-memory:")}#[cfg(test)]@@ -916,4 +1028,100 @@ mod tests {let digest = render_digest(&entries, &BTreeSet::new(), 3_000, false).unwrap();assert_eq!(digest.matches(UNTRUSTED_HISTORY_END).count(), 1);}++ #[test]+ fn apply_lines_select_like_the_digest_and_cap_at_max_lines() {+ let mut enforced = entry("profile/workflow/no-verify.md", "never --no-verify", &[]);+ enforced.enforced_by = true;+ let entries = vec![+ entry("profile/tools/pnpm.md", "use pnpm", &["javascript"]),+ entry("profile/testing/nextest.md", "use nextest", &["rust"]),+ entry("profile/style/prose.md", "plain prose", &[]),+ entry("profile/stack/rust.md", "Rust for services", &[]),+ enforced,+ ];+ let rust: BTreeSet<String> = ["rust".to_owned()].into();+ let (lines, omitted) = apply_lines(&entries, &rust, 40);+ assert_eq!(+ lines,+ vec![+ "- Rust for services (`profile/stack/rust.md`)",+ "- [rust] use nextest (`profile/testing/nextest.md`)",+ "- plain prose (`profile/style/prose.md`)",+ ]+ );+ assert_eq!(omitted, 0);++ let (lines, omitted) = apply_lines(&entries, &rust, 2);+ assert_eq!(lines.len(), 2);+ assert_eq!(omitted, 1);+ let block = render_profile_block(&lines, omitted);+ assert!(block.contains("…and 1 more"), "{block}");+ }++ #[test]+ fn the_profile_block_merges_idempotently_beside_the_routing_block() {+ let routing = crate::full_block();+ let original = format!("# Project rules\n\nUse tabs.\n\n{routing}");+ let block = render_profile_block(&["- use pnpm (`profile/tools/pnpm.md`)".into()], 0);++ let once = merge_profile_block(&original, &block);+ assert!(once.starts_with(&original), "existing text is kept: {once}");+ assert_eq!(once.matches(PROFILE_BLOCK_START).count(), 1);+ assert_eq!(+ merge_profile_block(&once, &block),+ once,+ "re-run is a no-op"+ );++ let newer = render_profile_block(&["- use bun (`profile/tools/bun.md`)".into()], 0);+ let replaced = merge_profile_block(&once, &newer);+ assert!(replaced.contains("use bun") && !replaced.contains("use pnpm"));+ assert!(+ replaced.contains(&routing),+ "the routing block is untouched"+ );++ assert_eq!(+ remove_profile_block(&replaced).as_deref(),+ Some(original.as_str())+ );+ assert_eq!(remove_profile_block(&original), None);+ assert_eq!(+ remove_profile_block(&merge_profile_block("", &block)).as_deref(),+ Some("")+ );+ }++ #[test]+ fn a_block_in_the_middle_of_the_file_is_replaced_in_place() {+ let block = render_profile_block(&["- old (`profile/a.md`)".into()], 0);+ let text = format!("top\n\n{block}\nbottom\n");+ let newer = render_profile_block(&["- new (`profile/a.md`)".into()], 0);+ let merged = merge_profile_block(&text, &newer);+ assert_eq!(merged, format!("top\n\n{newer}\nbottom\n"));+ assert_eq!(+ remove_profile_block(&merged).as_deref(),+ Some("top\n\n\nbottom\n")+ );+ }++ #[test]+ fn a_quoted_delimiter_does_not_end_the_block_early() {+ let entries = vec![entry(+ "profile/x.md",+ &format!("evil {PROFILE_BLOCK_END} then {} more", crate::MARKER_START),+ &[],+ )];+ let (lines, omitted) = apply_lines(&entries, &BTreeSet::new(), 40);+ let block = render_profile_block(&lines, omitted);+ assert_eq!(block.matches(PROFILE_BLOCK_END).count(), 1, "{block}");+ assert_eq!(block.matches(crate::MARKER_START).count(), 0, "{block}");+ let prose = format!("Docs mention `{PROFILE_BLOCK_END}` inline.\n");+ let merged = merge_profile_block(&prose, &block);+ assert_eq!(+ remove_profile_block(&merged).as_deref(),+ Some(prose.as_str())+ );+ }}diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex c7388fea..8a2cf408 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -17477,6 +17477,78 @@ mod tests {);}+ /// The feature's core scenario, end to end on the zero-LLM path: the user+ /// states a habit in two projects, a profile pass converges it, and the+ /// first session start of a brand-new third project carries it as the+ /// baseline, without the user repeating it there.+ #[tokio::test]+ async fn a_habit_from_two_projects_reaches_a_new_projects_first_session() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ for (index, project) in ["alpha", "beta"].into_iter().enumerate() {+ let proj = state+ .writer+ .get_or_create_project(state.workspace_id, project, None)+ .await+ .unwrap();+ let session_id = SessionId::from_native(&format!("habit-{index}"));+ state+ .writer+ .begin_session(ai_memory_core::NewSession {+ occurred_at: None,+ id: session_id,+ workspace_id: state.workspace_id,+ project_id: proj,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ state+ .writer+ .insert_observation(ai_memory_core::Sanitized::new(+ ai_memory_core::NewObservation {+ occurred_at: None,+ session_id,+ workspace_id: state.workspace_id,+ project_id: proj,+ kind: ai_memory_core::ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "I prefer tabs over spaces.".into(),+ importance: 5,+ },+ &ai_memory_core::Sanitizer::builtin(),+ ))+ .await+ .unwrap();+ }+ let config = ai_memory_consolidate::profile::ProfilePassConfig {+ settings: state.profile.clone(),+ distinguishes_operators: false,+ };+ ai_memory_consolidate::profile::run_profile_pass(+ &state.reader,+ &state.writer,+ &state.wiki,+ None,+ &config,+ )+ .await+ .unwrap();++ let digest = session_start_text(&state, profile_query("/home/u/gamma", "codex"))+ .await+ .expect("the new project receives the profile");+ assert!(digest.contains("tabs over spaces"), "{digest}");+ assert!(+ digest.contains("ai-memory profile apply"),+ "a project with no memory gets the baseline: {digest}"+ );+ }+/// Adversarial: event capture must never be attributed to a profile/// project, whether the name comes from a directory or a marker override./// Capture into `_profile.<id>` would file one operator's events indiff --git a/crates/ai-memory-mcp/src/admin_profile.rs b/crates/ai-memory-mcp/src/admin_profile.rsindex ea6989e0..54ac7562 100644--- a/crates/ai-memory-mcp/src/admin_profile.rs+++ b/crates/ai-memory-mcp/src/admin_profile.rs@@ -1,9 +1,10 @@//! `/admin/profile/*`: operator view of the cross-project profile-//! (`docs/cross-project-profile.md`). `status`, `list` and `review` read;-//! `rebuild` re-harvests every contributing project and converges the-//! profile. `ai-memory profile show` and `forget` reuse `/admin/read-page` and-//! `/admin/delete-page` against the scope `status` reports. Root-only on a-//! multi-user server, like every `/admin/*` route.+//! (`docs/cross-project-profile.md`). `status`, `list`, `review` and `apply`+//! read (`apply` returns the lines `ai-memory profile apply` writes into a+//! repository's rules file); `rebuild` re-harvests every contributing project+//! and converges the profile. `ai-memory profile show` and `forget` reuse+//! `/admin/read-page` and `/admin/delete-page` against the scope `status`+//! reports. Root-only on a multi-user server, like every `/admin/*` route.use std::collections::BTreeSet;use std::sync::Arc;@@ -48,6 +49,7 @@ pub fn profile_admin_router(state: ProfileAdminState) -> Router {.route("/admin/profile/status", get(handle_status)).route("/admin/profile/list", get(handle_list)).route("/admin/profile/review", get(handle_review))+ .route("/admin/profile/apply", get(handle_apply)).route("/admin/profile/rebuild", post(handle_rebuild)).route_layer(axum::middleware::from_fn_with_state(state.clone(),@@ -284,6 +286,114 @@ async fn handle_list(Json(serde_json::json!({ "scope": names, "entries": entries })).into_response()}+/// Query of `GET /admin/profile/apply`: the project whose rules file is being+/// written, and the operator whose private profile to use when it is per user.+#[derive(Debug, Deserialize)]+struct ApplyQuery {+ workspace: String,+ project: String,+ #[serde(default)]+ user: Option<String>,+}++/// `GET /admin/profile/apply`: the lines `ai-memory profile apply` writes for+/// one project. Selection matches the digest (stack scope, entries enforced+/// elsewhere skipped) and is capped at `apply_max_lines`. A project that set+/// `[profile] consume = false` receives nothing. A project the server has not+/// seen yet gets every entry, like the baseline digest of a new project.+async fn handle_apply(+ State(state): State<Arc<ProfileAdminState>>,+ Query(query): Query<ApplyQuery>,+) -> Response {+ let distinguishes = match state+ .reader+ .distinguishes_operators(state.trusted_proxy_identity)+ .await+ {+ Ok(distinguishes) => distinguishes,+ Err(e) => return internal(e),+ };+ let Some(share) = state.profile.effective_share(distinguishes) else {+ return (+ StatusCode::CONFLICT,+ Json(serde_json::json!({ "error": "the profile is off on this server" })),+ )+ .into_response();+ };+ let profile_query = ProfileQuery {+ workspace: query.workspace.clone(),+ user: query.user.clone(),+ };+ let (profile_scope, names) = match resolve_scope(&state.reader, share, &profile_query).await {+ Ok(Some(found)) => found,+ Ok(None) => {+ return Json(serde_json::json!({+ "scope": null, "consume": true, "lines": [], "omitted": 0,+ }))+ .into_response();+ }+ Err(e) => return internal(e),+ };+ let project = match ai_memory_store::lookup_existing_scope(+ &state.reader,+ &query.workspace,+ &query.project,+ )+ .await+ {+ Ok(scope) => Some(scope),+ Err(+ ScopeResolutionError::WorkspaceNotFound { .. }+ | ScopeResolutionError::ProjectNotFoundInWorkspace { .. },+ ) => None,+ Err(e) => return internal(e),+ };+ let (entries, tags) = match project {+ Some(project) => {+ match state+ .reader+ .project_profile_flags(project.workspace_id, project.project_id)+ .await+ {+ Ok(flags) if !flags.consume => {+ return Json(serde_json::json!({+ "scope": names, "consume": false, "lines": [], "omitted": 0,+ }))+ .into_response();+ }+ Ok(_) => {}+ Err(e) => return internal(e),+ }+ match state+ .reader+ .profile_digest_inputs(profile_scope.as_tuple(), project.as_tuple())+ .await+ {+ Ok(inputs) => (inputs.entries, inputs.project_tags),+ Err(e) => return internal(e),+ }+ }+ None => match state+ .reader+ .profile_entries(+ profile_scope.workspace_id,+ profile_scope.project_id,+ ai_memory_store::PROFILE_ENTRIES_LIMIT,+ )+ .await+ {+ Ok(entries) => (entries, BTreeSet::new()),+ Err(e) => return internal(e),+ },+ };+ let (lines, omitted) =+ ai_memory_core::profile::apply_lines(&entries, &tags, state.profile.apply_max_lines);+ Json(serde_json::json!({+ "scope": names, "consume": true, "lines": lines, "omitted": omitted,+ }))+ .into_response()+}+async fn pass_config(state: &ProfileAdminState,) -> Result<ai_memory_consolidate::profile::ProfilePassConfig, Response> {diff --git a/crates/ai-memory-mcp/tests/suite/admin_profile_routes.rs b/crates/ai-memory-mcp/tests/suite/admin_profile_routes.rsindex a731a403..f0c0eb50 100644--- a/crates/ai-memory-mcp/tests/suite/admin_profile_routes.rs+++ b/crates/ai-memory-mcp/tests/suite/admin_profile_routes.rs@@ -215,6 +215,114 @@ async fn review_and_rebuild_are_root_only_on_a_multi_user_server() {}}+/// `apply` returns what `ai-memory profile apply` writes: the converged+/// entries, capped at `apply_max_lines`, including for a project the server+/// has never seen; a project that set `[profile] consume = false` gets none.+#[tokio::test]+async fn apply_lists_the_lines_for_a_project_and_honours_consume() {+ let fx = fixture().await;+ prompt(&fx, "alpha", "Always use pnpm.").await;+ prompt(&fx, "alpha", "Always keep tests beside the code.").await;+ let (status, report) = call(+ router(&fx, ProfileSettings::default()),+ "POST",+ "/admin/profile/rebuild",+ AuthLevel::Anonymous,+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{report}");++ let (status, body) = call(+ router(&fx, ProfileSettings::default()),+ "GET",+ "/admin/profile/apply?workspace=default&project=brand-new",+ AuthLevel::Anonymous,+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(body["consume"], true);+ let lines: Vec<&str> = body["lines"]+ .as_array()+ .unwrap()+ .iter()+ .map(|l| l.as_str().unwrap())+ .collect();+ assert_eq!(lines.len(), 2, "{body}");+ assert!(lines.iter().any(|l| l.contains("pnpm")), "{body}");+ assert!(lines.iter().all(|l| l.contains("(`profile/")), "{body}");++ let capped = ProfileSettings {+ apply_max_lines: 1,+ ..ProfileSettings::default()+ };+ let (_, body) = call(+ router(&fx, capped),+ "GET",+ "/admin/profile/apply?workspace=default&project=brand-new",+ AuthLevel::Anonymous,+ )+ .await;+ assert_eq!(body["lines"].as_array().unwrap().len(), 1, "{body}");+ assert_eq!(body["omitted"], 1, "{body}");++ let alpha = fx+ .store+ .writer+ .get_or_create_project(fx.ws, "alpha", None)+ .await+ .unwrap();+ fx.store+ .writer+ .set_project_profile_flags(+ alpha,+ ai_memory_store::ProjectProfileFlags {+ contribute: true,+ consume: false,+ },+ )+ .await+ .unwrap();+ let (_, body) = call(+ router(&fx, ProfileSettings::default()),+ "GET",+ "/admin/profile/apply?workspace=default&project=alpha",+ AuthLevel::Anonymous,+ )+ .await;+ assert_eq!(body["consume"], false, "{body}");+ assert!(body["lines"].as_array().unwrap().is_empty(), "{body}");+}++/// Multi-user: `apply` is root-only like the other profile routes.+#[tokio::test]+async fn apply_is_root_only_on_a_multi_user_server() {+ let fx = fixture().await;+ fx.store+ .writer+ .create_human_user(+ NewUser {+ username: "alice".into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap();+ let settings = ProfileSettings {+ enabled: ProfileEnabled::On,+ share: ProfileShare::Global,+ ..ProfileSettings::default()+ };+ let uri = "/admin/profile/apply?workspace=default&project=app";+ let (status, _) = call(router(&fx, settings.clone()), "GET", uri, AuthLevel::User).await;+ assert_eq!(status, StatusCode::FORBIDDEN);+ let (status, body) = call(router(&fx, settings), "GET", uri, AuthLevel::Root).await;+ assert_eq!(status, StatusCode::OK, "{body}");+}+/// A rebuild on a server whose profile is off says so instead of doing work.#[tokio::test]async fn rebuild_refuses_when_the_profile_is_off() {diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 7e6955ad..21a9683d 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -205,6 +205,12 @@ entry removed until newer evidence arrives. With an LLM provider andstructured calls and fall back to the zero-LLM path on any error. A privateprofile converges only its operator's own candidates from projects they canread; a shared profile on a multi-user server skips restricted projects.+`ai-memory profile apply` reads `GET /admin/profile/apply` (the digest's+selection, capped at `apply_max_lines`, empty for a `consume = false` project)+and writes it between `<!-- ai-memory:profile:start/end -->` delimiters in the+repository's rules file through `apply_atomic` (tmp + rename + fsync, backup+under `<data_dir>/backups/profile-apply/`); it is the only profile path that+writes outside the wiki, and only when the user runs it.**Optional managed-workstream loop:** `ai-memory run` opens a lease for thecurrent repository/worktree workstream, resolves an explicit harness or thediff --git a/docs/cross-project-profile.md b/docs/cross-project-profile.mdindex 125fb673..aec1b198 100644--- a/docs/cross-project-profile.md+++ b/docs/cross-project-profile.md@@ -111,10 +111,47 @@ ai-memory profile show tools/pnpm.md # one entryai-memory profile forget tools/pnpm.md # remove one entry (stays removed until you say it again)ai-memory profile review # entries with their evidence, habits still short of the barai-memory profile rebuild # re-read every project from the start (safe to repeat)+ai-memory profile apply # write the entries that fit this repo into its rules fileai-memory profile list --user alice # an operator's private profile (share = "user")ai-memory profile list --workspace work # a workspace profile (share = "workspace")```+## Turning the profile into hard rules for one repository++The digest is a default the agent applies when nothing more specific speaks.+When you want your usual choices to be **rules** in a repository, written down+where every harness and every collaborator sees them, run this from inside it:++```bash+ai-memory profile apply --dry-run # show the block and the file it would go to+ai-memory profile apply # write it+ai-memory profile apply --remove # take it out again+```++- **Which file.** `--target FILE` (relative to the repository root) wins.+ Otherwise an existing `AGENTS.md`; else an existing `CLAUDE.md`, unless it+ only imports `@AGENTS.md`; else a new `AGENTS.md`. The repository root is the+ nearest directory holding `.git` (a linked worktree writes its own checkout).+- **What it writes.** The entries that fit this repository, selected like the+ digest (scoped to the stacks the project's activity shows, entries enforced+ elsewhere skipped, a new project gets them all), at most `apply_max_lines`+ (default 40), each with the page it came from, between+ `<!-- ai-memory:profile:start -->` and `<!-- ai-memory:profile:end -->`.+- **What it never touches.** Anything outside those delimiters, including the+ `<!-- ai-memory:start -->` routing block and your own rules. Re-running+ replaces only the block, and leaves the file byte-identical when the profile+ has not changed. `--remove` takes the block out and restores the file; a file+ `apply` created for the block alone is deleted.+- **Backups.** The previous version of the file goes to+ `<data dir>/backups/profile-apply/`, never next to the file, so nothing extra+ shows up in `git status`.+- **Opt-outs.** A project with `[profile] consume = false` refuses `apply`.++It is the only command that writes a file in your repository, and it only runs+when you run it: ai-memory never edits a rules file on its own. Because the+block then sits in the rules file, it outranks the digest for that repository+(step 2 of the order above).+## How entries are learnedThe server builds most entries itself, from evidence, in two steps: once@@ -242,6 +279,18 @@ llm = true`ai-memory profile status` prints the effective values.+### Common customizations++| You want | Set |+|---|---|+| Keep work and personal (or two clients) apart | `share = "workspace"` |+| No LLM involvement in the profile, even with a provider configured | `llm = false` |+| Only admit habits you repeat in more projects | `min_projects = 3` (or more) |+| A smaller digest at every session start | `digest_max_bytes = 1500` |+| The profile in retrieval only, no digest | `inject_on_session_start = false` |+| No profile at all on a single-user server | `enabled = false` (or `share = "off"`) |+| One project neither teaches nor receives it | `[profile] contribute = false` and `consume = false` in its marker |+### Enabling it on a multi-user server```tomldiff --git a/docs/design-cross-project-profile.md b/docs/design-cross-project-profile.mdindex 1fa24c51..013b7dce 100644--- a/docs/design-cross-project-profile.md+++ b/docs/design-cross-project-profile.md@@ -1,6 +1,7 @@# Design: the cross-project profile-*Status: accepted (2026-10-04), implementing for 2.6.*+*Status: accepted (2026-10-04), implemented for 2.6. User guide:+[`cross-project-profile.md`](cross-project-profile.md).*## 1. The problem@@ -195,7 +196,11 @@ candidate newer than the entry's last write arrives.- **`ai-memory profile apply`.** Writes the top entries into a managedsub-block (`<!-- ai-memory:profile:start -->` … `end`) of the rules file inthe current repository, capped at `apply_max_lines` (default 40), never- touching text outside the markers. Command-driven only, with `--dry-run`.+ touching text outside the markers. Command-driven only, with `--dry-run`+ and `--remove`. The entries come from `GET /admin/profile/apply` with the+ digest's selection; the target is `--target`, else an existing `AGENTS.md`,+ else a `CLAUDE.md` that does more than import `AGENTS.md`, else a new+ `AGENTS.md`. The write is atomic with its backup kept under the data dir.This is how a profile entry becomes a hard rule, when the user wants one.## 6. Using an LLM when one is configured@@ -244,12 +249,12 @@ consume = false # no digest or union in this project## 8. Commands`ai-memory profile status | list | show <path> | forget <path> | review |-rebuild | apply [--target FILE] [--dry-run]`.+rebuild | apply [--target FILE] [--dry-run | --remove]`.-`status`, `list` and `review` read `/admin/profile/*` and `rebuild` posts-to it (forget the harvest marks, re-read every project, converge); `show` and-`forget` reuse `/admin/read-page` and `/admin/delete-page` against the-profile's scope. All+`status`, `list`, `review` and `apply` read `/admin/profile/*` and `rebuild`+posts to it (forget the harvest marks, re-read every project, converge);+`show` and `forget` reuse `/admin/read-page` and `/admin/delete-page` against+the profile's scope. Allare root-only on a multi-user server, like every `/admin/*` route; there, eachoperator manages their own private profile through MCP.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 47bf05e2..de99a7ea 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -28,7 +28,7 @@ boundary not yet built.| 1d | A private cross-project profile is readable and writable by its operator alone (`[profile] share = "user"`) | `ai-memory-store/src/ops.rs` `initial_access_mode` (a `_profile.<user id>` project is always created `restricted`, creator recorded in the same transaction); `ai-memory-store/src/scope.rs` `lookup_profile_scope` / `create_profile_scope` (the project name derives from the authenticated viewer's id; no database user, no private profile); `ai-memory-mcp/src/server.rs` `profile_target_ids` and the `memory_query` profile union (resolved per viewer through the per-project choke point) | store `integration::profile` `a_private_profile_refuses_every_other_operator` (another operator's read and write by name refused; owner control admitted), `reserved_profile_projects_get_their_fixed_access_modes`; `server.rs` `a_private_profile_is_private_to_its_operator` (no union leak; read, write and delete by name refused; owner and own-profile controls); `multi_session.rs` `two_harnesses_of_one_operator_share_one_private_profile`; both fail with the restricted-mode guard removed | STRONG || 1e | The shared profile scopes are read-open, write-gated like `_global` | `ai-memory-store/src/project_authz.rs` `is_reserved_global` (a workspace `_profile` joins `default/_global`: on a server that distinguishes operators a write needs root or a `write` grant, creating it grants nothing); `ops.rs` `initial_access_mode` keeps `_profile` open | store `integration::profile` `shared_profiles_are_write_gated_for_database_users` (ungranted user refused for both shares; root and a write grant admitted; reads open); `server.rs` `a_workspace_profile_is_write_gated_and_read_open`; both fail with `_profile` dropped from the gate | STRONG || 1f | Event capture never lands in a profile project, and the sweep keeps them | `ai-memory-hooks/src/router.rs` project resolution refuses `ai_memory_core::profile::is_reserved_scope_project` (`_global`, `_profile`, `_profile.*`) from a directory or a marker override, falling back to the server default; `ops.rs` `sweep_hollow_projects` exempts `_profile` and `_profile.%` | `router.rs` `capture_is_never_attributed_to_a_profile_project` (override and directory spellings refused; ordinary `my_profile` control resolves), fails with the check narrowed to `_global`; store `integration::profile` `the_hollow_project_sweep_keeps_empty_profile_projects` | STRONG |-| 1g | The profile reaches only the sessions it is meant for: off by default on a multi-user server, suppressed by `[profile] consume = false` | `ai_memory_core::profile::ProfileSettings::effective_share` (`enabled = auto` is off once operators are distinguished); `router.rs` `render_requested_profile_digest`; `server.rs` `memory_query` drops `profile/` hits for a project whose stored `profile_consume` is off | `router.rs` `a_multi_user_server_has_no_profile_digest_by_default`, `profile_digest_honours_consume_once_per_session_and_the_server_switch`; `server.rs` `the_single_user_profile_lives_in_global_and_honours_consume` (fails with the consume filter removed); core `profile::tests::effective_share_matrix` | STRONG |+| 1g | The profile reaches only the sessions it is meant for: off by default on a multi-user server, suppressed by `[profile] consume = false` | `ai_memory_core::profile::ProfileSettings::effective_share` (`enabled = auto` is off once operators are distinguished); `router.rs` `render_requested_profile_digest`; `server.rs` `memory_query` drops `profile/` hits for a project whose stored `profile_consume` is off; `admin_profile.rs` `handle_apply` (`ai-memory profile apply`) returns no lines for such a project and sits behind the root-only `/admin/*` gate on a multi-user server | `router.rs` `a_multi_user_server_has_no_profile_digest_by_default`, `profile_digest_honours_consume_once_per_session_and_the_server_switch`; `server.rs` `the_single_user_profile_lives_in_global_and_honours_consume` (fails with the consume filter removed); `admin_profile_routes.rs` `apply_lists_the_lines_for_a_project_and_honours_consume`, `apply_is_root_only_on_a_multi_user_server` (database user refused, root control admitted); core `profile::tests::effective_share_matrix` | STRONG || 1h | The profile learns only from what it may: the user's own prompts and curated pages, from contributing projects, never another operator's words in a private profile and never a restricted project in a shared one; stored text stays data | `ai-memory-store/src/profile.rs` `profile_prompts_since` (only `user-prompt` observations), `profile_harvest_projects` / `profile_candidates` (`profile_contribute = 0` excluded, including candidates recorded before the opt-out); `ai-memory-consolidate/src/profile.rs` `convergence_targets` (a `user` target keeps only candidates whose `contributor` is that operator, from projects the per-project choke point lets them read; a `global`/`workspace` target on an operator-distinguishing server drops restricted projects), `converge` (never rewrites a page without its `generated_by` stamp or whose body changed; `profile_entry_ledger` keeps a forgotten entry out), `classify_batch` / `merge_entry` (sanitized, JSON-encoded input; the evidence quote is always the user's sentence) | consolidate `integration::profile_harvest` `tool_output_is_never_a_candidate`, `an_opted_out_project_is_never_harvested`, `a_private_profile_never_harvests_another_operator`, `a_team_profile_never_harvests_a_restricted_project`, `a_hand_edited_entry_is_never_clobbered`, `a_forgotten_entry_is_not_recreated_until_said_again`, `injected_instructions_stay_data` (each with a legitimate control; each fails with its guard removed); mcp `integration::admin_profile_routes` `review_and_rebuild_are_root_only_on_a_multi_user_server` | STRONG || 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate | STRONG || 2b | Managed-workstream discovery stays checkout-local, including pagination | `ai-memory-workstream/src/repository.rs` `inspect_repository_fingerprints` shares the launch identity derivation without checkpoint scans; `ai-memory-cli/src/commands/resume.rs` `candidates_for_checkout` queries only the cwd, never registry links; the explicit `--all` walk (`candidates_across_checkouts`) lists each linked checkout through its own fingerprint-scoped request and applies `--workspace` before any request; `ai-memory-hooks/src/workstream.rs` `list_recent_workstreams` resolves an authorized explicit scope on every page; `ai-memory-store/src/workstream.rs` `list_recent` applies workspace/project/repository/worktree predicates before `LIMIT`/`OFFSET` | `resume.rs` `resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts` (same scope/remote foreign checkout refused, 125 local rows visible), `empty_current_checkout_does_not_fall_back_to_the_registry`, `resume_all_walks_every_linked_checkout_and_honours_the_workspace_filter` (a foreign workspace filter sends no request; the default picker still ignores the registry); `workstream.rs` `recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope` (foreign repo, worktree, project and workspace excluded on every page; 105 legitimate rows reach the client, huge offsets return nothing); store `recent_workstreams_are_checkout_local_and_include_linked_harnesses` (page two keeps native harness links); `repository.rs` `reports_origin_push_url_and_linked_worktree` verifies lightweight/full fingerprint parity and distinct worktree keys; CLI `resume_yolo_displays_picker_without_scanning_git_status` verifies listing skips status scans | STRONG |