Файли
openidea/crates/ide-agent/src/memory.rs
T
Deng Liuтаdengliu 35a6bec1c2 feat(agents): implement unified Agent Plugins Hub across harnesses (#6877)
Adds a Plugins page under Settings > Agents for the plugin bundles each agent harness installs natively (Claude Code, GitHub Copilot, Codex, Gemini CLI).

- Rows are grouped by harness and scope with counts and paths. Toggles change only the harness's own enablement record, and row ids are stable and owner-qualified, so a toggle never reaches another project's row.
- Enabled plugins project their skills, MCP servers and memory files into Skills, MCP Connections and Memory; a workspace override decides what a globally enabled plugin projects in that workspace.
- Marketplaces can be browsed, previewed and installed from, with pinned git installs. Installs are written into each harness's native store without following symlinks, including at the store root.
- Plugins that run local MCP processes or lifecycle hooks need capability consent. Previews and installed folders resolve capabilities the same way, and consent is tied to the capability hash the user was shown: an install or enable whose capabilities differ is refused.

Closes #6872

Co-authored-by: dengliu <[email protected]>
2026-12-02 09:32:33 +08:00

2064 рядки
81 KiB
Rust
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
//! Unified Agent Memory hub (#6810): discovers curated instruction files, path-scoped
//! rules, and cross-session learned auto-memories across every coding agent (`claude`,
//! `codex`, `copilot`, `cursor`, `gemini`, `hermes`, `opencode`, and custom ACP agents),
//! deduplicates symlinks and `@AGENTS.md` imports, resolves `[agents.memory]` policies
//! under Workspace Trust without mutating tracked repository files, stages per-session
//! `_meta.openidea.memory` delivery for each driver.
use crate::{
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryEntryPolicy,
AgentMemoryKind, AgentMemoryMode, AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource,
AgentMemoryState, AutoMemoryMode, CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
};
use ide_core::output_encoding::strip_ansi;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
const MAX_DESCRIPTION_CHARS: usize = 200;
const CLAUDE_MEMORY_INDEX_LINE_CAP: u32 = 200;
const CLAUDE_MEMORY_INDEX_WARN_LINES: u32 = 180;
const CLAUDE_MEMORY_INDEX_BYTE_CAP: u64 = 25 * 1024;
const CLAUDE_MEMORY_INDEX_WARN_BYTES: u64 = 22 * 1024;
const INSTRUCTION_WARN_LINES: u32 = 200;
const MAX_STAGED_SYSTEM_BYTES: usize = 32 * 1024;
const SKIP_MONOREPO_DIRS: &[&str] =
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
/// Both global and workspace `[agents.memory]` settings plus workspace roots and trust.
#[derive(Clone, Debug)]
pub struct MemoryPolicy {
pub user: AgentMemorySettings,
pub workspace: AgentMemorySettings,
pub workspace_trusted: bool,
pub workspace_roots: Vec<PathBuf>,
}
impl Default for MemoryPolicy {
fn default() -> Self {
Self {
user: AgentMemorySettings::default(),
workspace: AgentMemorySettings::default(),
workspace_trusted: true,
workspace_roots: Vec::new(),
}
}
}
/// Per-session memory payload attached to `session/new`, `session/load`, and `session/fork`
/// at `_meta.openidea.memory`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Delivery {
pub auto_memory: AutoMemoryMode,
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_auto_memory: Option<bool>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub claude_md_excludes: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_instruction_files: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_add_dir: Option<PathBuf>,
#[serde(skip_serializing_if = "is_false")]
pub claude_additional_dirs_claude_md: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub codex_use_memories: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub codex_generate_memories: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub codex_developer_instructions: Option<String>,
#[serde(skip_serializing_if = "is_false")]
pub copilot_exclude_store_memory: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub copilot_enable_memory: Option<bool>,
#[serde(skip_serializing_if = "is_false")]
pub copilot_disable_custom_instructions: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub copilot_system_message: Option<String>,
}
fn is_false(b: &bool) -> bool {
!*b
}
pub fn normalize_provider_id(provider: &str) -> &str {
let base = provider.strip_suffix("-acp").unwrap_or(provider);
if base == "hermes" || base.starts_with("hermes-") { "hermes" } else { base }
}
pub fn matches_agent_filter(agents: &[String], provider: &str) -> bool {
if agents.is_empty() {
return true;
}
let target = normalize_provider_id(provider);
agents.iter().any(|raw| {
let trimmed = raw.trim();
trimmed.eq_ignore_ascii_case(provider) || normalize_provider_id(trimmed).eq_ignore_ascii_case(target)
})
}
fn source_key(source: AgentMemorySource) -> &'static str {
match source {
AgentMemorySource::Workspace => "workspace",
AgentMemorySource::ClaudeWorkspace => "claudeWorkspace",
AgentMemorySource::ClaudeUser => "claudeUser",
AgentMemorySource::ClaudeAuto => "claudeAuto",
AgentMemorySource::GithubWorkspace => "githubWorkspace",
AgentMemorySource::CopilotUser => "copilotUser",
AgentMemorySource::CodexUser => "codexUser",
AgentMemorySource::CodexAuto => "codexAuto",
AgentMemorySource::CursorWorkspace => "cursorWorkspace",
AgentMemorySource::GeminiWorkspace => "geminiWorkspace",
AgentMemorySource::GeminiUser => "geminiUser",
AgentMemorySource::HermesAuto => "hermesAuto",
}
}
/// Builds a deterministic entry ID (`"<source>::<rel_key>"` with forward slashes).
pub fn entry_id(source: AgentMemorySource, rel: &str) -> String {
let clean = rel.replace('\\', "/");
let clean = clean.trim_start_matches('/');
format!("{}::{clean}", source_key(source))
}
/// Resolves Hermes' root directory, honoring an isolated `home` override (such as tests or
/// custom sandboxes) before falling back to `%LOCALAPPDATA%\hermes` on Windows.
fn hermes_root(home: Option<&Path>) -> Option<PathBuf> {
if let Some(h) = home {
let dot_hermes = h.join(".hermes");
if dot_hermes.exists() {
return Some(dot_hermes);
}
#[cfg(windows)]
if std::env::var_os("USERPROFILE").as_deref() != Some(h.as_os_str()) {
return Some(dot_hermes);
}
}
hermes::root(home)
}
/// Discovers all instruction files, path-scoped rules, and local auto-memory notes across
/// `workspaces` (including 2-level nested monorepo packages) and `home`.
/// Symlinked copies and thin `@AGENTS.md` wrapper files collapse onto the canonical entry,
/// recording secondary locations in [`AgentMemoryEntry::also_in`].
pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<AgentMemoryEntry> {
let mut out: Vec<AgentMemoryEntry> = Vec::new();
let mut path_index: BTreeMap<PathBuf, usize> = BTreeMap::new();
let mut seen_workspaces: HashSet<PathBuf> = HashSet::new();
let mut all_workspaces: Vec<(PathBuf, Option<String>)> = Vec::new();
for ws in workspaces {
let canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.clone());
if seen_workspaces.insert(canon) {
all_workspaces.push((ws.clone(), None));
}
}
let multi_ws = all_workspaces.len() > 1;
let base_workspaces: Vec<PathBuf> = all_workspaces.iter().map(|(w, _)| w.clone()).collect();
for ws in &base_workspaces {
for sub in monorepo_subdirs(ws, 2) {
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
if seen_workspaces.insert(sub_canon) {
let prefix =
sub.strip_prefix(ws).ok().map(|p| p.to_string_lossy().replace('\\', "/")).filter(|s| !s.is_empty());
all_workspaces.push((sub, prefix));
}
}
}
let mut push = |mut entry: AgentMemoryEntry| {
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
entry.path = canon.clone().into();
if let Some(&idx) = path_index.get(&canon) {
let existing = &mut out[idx];
if existing.source != entry.source && !existing.also_in.contains(&entry.source) {
existing.also_in.push(entry.source);
}
return;
}
// Collapse a thin `CLAUDE.md` wrapper whose sole body is `@AGENTS.md` onto the sibling `AGENTS.md`.
if matches!(entry.source, AgentMemorySource::ClaudeWorkspace)
&& let Some(imported) = sole_import_target(&canon)
&& let Some(&idx) = path_index.get(&imported)
{
let existing = &mut out[idx];
if !existing.also_in.contains(&entry.source) {
existing.also_in.push(entry.source);
}
return;
}
let idx = out.len();
path_index.insert(canon, idx);
out.push(entry);
};
for (ws, sub_prefix) in &all_workspaces {
let ws_prefix = if multi_ws && sub_prefix.is_none() { file_name(ws) } else { sub_prefix.clone() };
let qualify = |rel: &str| match &ws_prefix {
Some(p) => format!("{p}/{rel}"),
None => rel.to_owned(),
};
// 1. Portable Workspace instructions
for file in ["AGENTS.md", "AGENTS.override.md"] {
let p = ws.join(file);
if p.is_file()
&& let Some(e) = parse_entry(
&p,
&qualify(file),
AgentMemorySource::Workspace,
Some(AgentMemoryKind::Instruction),
false,
Some(ws),
)
{
push(e);
}
}
// 2. Claude Code workspace instructions & rules
for rel in ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"] {
let p = ws.join(rel);
if p.is_file()
&& let Some(e) = parse_entry(
&p,
&qualify(rel),
AgentMemorySource::ClaudeWorkspace,
Some(AgentMemoryKind::Instruction),
false,
Some(ws),
)
{
push(e);
}
}
for p in markdown_files(&ws.join(".claude/rules"), 4) {
let rel = rel_from(ws, &p);
if let Some(e) = parse_entry(&p, &qualify(&rel), AgentMemorySource::ClaudeWorkspace, None, false, Some(ws))
{
push(e);
}
}
// 3. GitHub Copilot repository instructions
let copilot_main = ws.join(".github/copilot-instructions.md");
if copilot_main.is_file()
&& let Some(e) = parse_entry(
&copilot_main,
&qualify(".github/copilot-instructions.md"),
AgentMemorySource::GithubWorkspace,
Some(AgentMemoryKind::Instruction),
false,
Some(ws),
)
{
push(e);
}
for p in files_matching_suffix(&ws.join(".github/instructions"), ".instructions.md", 4) {
let rel = rel_from(ws, &p);
if let Some(e) = parse_entry(
&p,
&qualify(&rel),
AgentMemorySource::GithubWorkspace,
Some(AgentMemoryKind::Rule),
false,
Some(ws),
) {
push(e);
}
}
// 4. Cursor rules
for p in files_matching_suffix(&ws.join(".cursor/rules"), ".mdc", 4) {
let rel = rel_from(ws, &p);
if let Some(e) = parse_cursor_mdc(&p, &qualify(&rel)) {
push(e);
}
}
let cursorrules = ws.join(".cursorrules");
if cursorrules.is_file()
&& let Some(e) = parse_entry(
&cursorrules,
&qualify(".cursorrules"),
AgentMemorySource::CursorWorkspace,
Some(AgentMemoryKind::Instruction),
false,
Some(ws),
)
{
push(e);
}
// 5. Gemini CLI workspace instruction
let gemini_md = ws.join("GEMINI.md");
if gemini_md.is_file()
&& let Some(e) = parse_entry(
&gemini_md,
&qualify("GEMINI.md"),
AgentMemorySource::GeminiWorkspace,
Some(AgentMemoryKind::Instruction),
false,
Some(ws),
)
{
push(e);
}
}
if let Some(home) = home {
// Claude User (`~/.claude/CLAUDE.md`, `~/.claude/rules/**`)
let claude_home = home.join(".claude");
let claude_user_md = claude_home.join("CLAUDE.md");
if claude_user_md.is_file()
&& let Some(e) = parse_entry(
&claude_user_md,
"CLAUDE.md",
AgentMemorySource::ClaudeUser,
Some(AgentMemoryKind::Instruction),
false,
Some(&claude_home),
)
{
push(e);
}
for p in markdown_files(&claude_home.join("rules"), 4) {
let rel = rel_from(&claude_home, &p);
if let Some(e) = parse_entry(&p, &rel, AgentMemorySource::ClaudeUser, None, false, Some(&claude_home)) {
push(e);
}
}
// Claude Auto Memory (`~/.claude/projects/<escaped>/memory/**` or user `autoMemoryDirectory`)
for mem_dir in claude_auto_memory_dirs(&claude_home, home, &base_workspaces) {
for p in markdown_files(&mem_dir, 2) {
let rel = rel_from(&mem_dir, &p);
if let Some(e) = parse_claude_auto_note(&p, &rel) {
push(e);
}
}
}
// Copilot User (`~/.copilot/copilot-instructions.md`, `~/.copilot/instructions/**/*.instructions.md`)
let copilot_home = home.join(".copilot");
let copilot_user_md = copilot_home.join("copilot-instructions.md");
if copilot_user_md.is_file()
&& let Some(e) = parse_entry(
&copilot_user_md,
"copilot-instructions.md",
AgentMemorySource::CopilotUser,
Some(AgentMemoryKind::Instruction),
false,
Some(&copilot_home),
)
{
push(e);
}
for p in files_matching_suffix(&copilot_home.join("instructions"), ".instructions.md", 4) {
let rel = rel_from(&copilot_home, &p);
if let Some(e) = parse_entry(
&p,
&rel,
AgentMemorySource::CopilotUser,
Some(AgentMemoryKind::Rule),
false,
Some(&copilot_home),
) {
push(e);
}
}
// Codex User (`~/.codex/AGENTS.md`, `AGENTS.override.md`) & Auto (`~/.codex/memories*`)
let codex_home = home.join(".codex");
for file in ["AGENTS.md", "AGENTS.override.md"] {
let p = codex_home.join(file);
if p.is_file()
&& let Some(e) = parse_entry(
&p,
file,
AgentMemorySource::CodexUser,
Some(AgentMemoryKind::Instruction),
false,
Some(&codex_home),
)
{
push(e);
}
}
if let Some(codex_mem_root) = active_codex_memory_dir(&codex_home) {
for file in ["MEMORY.md", "memory_summary.md"] {
let p = codex_mem_root.join(file);
if p.is_file()
&& let Some(e) =
parse_entry(&p, file, AgentMemorySource::CodexAuto, Some(AgentMemoryKind::AutoNote), true, None)
{
push(e);
}
}
for p in markdown_files(&codex_mem_root.join("rollout_summaries"), 1) {
let rel = rel_from(&codex_mem_root, &p);
if let Some(e) =
parse_entry(&p, &rel, AgentMemorySource::CodexAuto, Some(AgentMemoryKind::AutoNote), true, None)
{
push(e);
}
}
}
// Gemini User (`~/.gemini/GEMINI.md`)
let gemini_user_md = home.join(".gemini/GEMINI.md");
if gemini_user_md.is_file()
&& let Some(e) = parse_entry(
&gemini_user_md,
"GEMINI.md",
AgentMemorySource::GeminiUser,
Some(AgentMemoryKind::Instruction),
false,
None,
)
{
push(e);
}
// Hermes profiles (`<hermes_root>/memories/{MEMORY.md,USER.md}` and `<hermes_root>/profiles/*/memories/*`)
if let Some(hermes_root) = hermes_root(Some(home)) {
for profile in hermes::profiles(&hermes_root) {
let prof_home = if profile == "default" {
hermes_root.clone()
} else {
hermes_root.join("profiles").join(&profile)
};
for (fname, cat) in [("MEMORY.md", "memory"), ("USER.md", "profile")] {
let p = prof_home.join("memories").join(fname);
if !p.is_file() {
continue;
}
let rel = if profile == "default" { fname.to_owned() } else { format!("{profile}/{fname}") };
if let Some(mut e) = parse_entry(
&p,
&rel,
AgentMemorySource::HermesAuto,
Some(AgentMemoryKind::AutoNote),
true,
None,
) {
e.category = Some(cat.to_owned());
push(e);
}
}
}
}
}
out
}
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
pub fn discover_memories_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
projected: Vec<AgentMemoryEntry>,
) -> Vec<AgentMemoryEntry> {
let mut out = discover_memories(workspaces, home);
let mut seen: HashSet<PathBuf> =
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
for mut entry in projected {
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
entry.path = canon.clone().into();
if seen.insert(canon) {
out.push(entry);
}
}
out
}
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
/// against `policy` and optional per-session `session_overrides`.
pub fn resolve_catalog(
entries: Vec<AgentMemoryEntry>,
session_overrides: Option<&AgentMemoryOverrides>,
policy: &MemoryPolicy,
home: Option<&Path>,
) -> AgentMemoryCatalog {
let resolved_entries = resolve_entries(entries, session_overrides, policy);
let (auto_memory, auto_memory_origin) = resolve_global_auto_memory(session_overrides, policy);
let providers = build_provider_statuses(&resolved_entries, session_overrides, policy, home);
AgentMemoryCatalog { entries: resolved_entries, providers, auto_memory, auto_memory_origin }
}
/// Resolves every discovered memory entry's effective [`AgentMemoryMode`] with precedence:
/// `Workspace Trust > Session Override > Workspace Settings > User Settings > Default (Auto)`.
pub fn resolve_entries(
entries: Vec<AgentMemoryEntry>,
session_overrides: Option<&AgentMemoryOverrides>,
policy: &MemoryPolicy,
) -> Vec<AgentMemoryState> {
let mut out = Vec::with_capacity(entries.len());
for entry in entries {
if entry.source.is_workspace() && !policy.workspace_trusted {
out.push(AgentMemoryState {
entry,
mode: AgentMemoryMode::Off,
agents: Vec::new(),
origin: AgentMemoryOrigin::Trust,
});
continue;
}
let ws_pol = lookup_entry_policy(&policy.workspace.entries, &entry.id)
.filter(|p| policy.workspace_trusted || p.mode == AgentMemoryMode::Off);
let user_pol = lookup_entry_policy(&policy.user.entries, &entry.id);
let agents = ws_pol
.filter(|p| !p.agents.is_empty())
.or_else(|| user_pol.filter(|p| !p.agents.is_empty()))
.map(|p| p.agents.clone())
.unwrap_or_default();
let (mode, origin) =
if let Some(chosen) = session_overrides.and_then(|s| lookup_session_entry(&s.entries, &entry.id)) {
(chosen, AgentMemoryOrigin::Session)
} else if let Some(ws) = ws_pol {
(ws.mode, AgentMemoryOrigin::Workspace)
} else if let Some(us) = user_pol {
(us.mode, AgentMemoryOrigin::User)
} else {
(AgentMemoryMode::Auto, AgentMemoryOrigin::None)
};
out.push(AgentMemoryState { entry, mode, agents, origin });
}
out
}
pub fn resolve_global_auto_memory(
session_overrides: Option<&AgentMemoryOverrides>,
policy: &MemoryPolicy,
) -> (AutoMemoryMode, AgentMemoryOrigin) {
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
return (mode, AgentMemoryOrigin::Session);
}
let ws_mode = policy.workspace.auto_memory;
if ws_mode != AutoMemoryMode::Inherit && (policy.workspace_trusted || ws_mode == AutoMemoryMode::Off) {
return (ws_mode, AgentMemoryOrigin::Workspace);
}
if policy.user.auto_memory != AutoMemoryMode::Inherit {
return (policy.user.auto_memory, AgentMemoryOrigin::User);
}
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
}
/// Resolves the effective [`AutoMemoryMode`] for one `provider` (`claude`, `codex`, `copilot`, `hermes`, etc.).
pub fn resolve_provider_auto_memory(
provider: &str,
session_overrides: Option<&AgentMemoryOverrides>,
policy: &MemoryPolicy,
) -> (AutoMemoryMode, AgentMemoryOrigin) {
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
return (mode, AgentMemoryOrigin::Session);
}
let key = normalize_provider_id(provider);
if let Some(ws_prov) = policy.workspace.providers.get(key)
&& ws_prov.auto_memory != AutoMemoryMode::Inherit
&& (policy.workspace_trusted || ws_prov.auto_memory == AutoMemoryMode::Off)
{
return (ws_prov.auto_memory, AgentMemoryOrigin::Workspace);
}
if policy.workspace.auto_memory != AutoMemoryMode::Inherit
&& (policy.workspace_trusted || policy.workspace.auto_memory == AutoMemoryMode::Off)
{
return (policy.workspace.auto_memory, AgentMemoryOrigin::Workspace);
}
if let Some(user_prov) = policy.user.providers.get(key)
&& user_prov.auto_memory != AutoMemoryMode::Inherit
{
return (user_prov.auto_memory, AgentMemoryOrigin::User);
}
if policy.user.auto_memory != AutoMemoryMode::Inherit {
return (policy.user.auto_memory, AgentMemoryOrigin::User);
}
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
}
fn build_provider_statuses(
states: &[AgentMemoryState],
session_overrides: Option<&AgentMemoryOverrides>,
policy: &MemoryPolicy,
home: Option<&Path>,
) -> Vec<AgentAutoMemoryStatus> {
let stats_for = |src: AgentMemorySource| -> (u32, u32) {
let mut count = 0u32;
let mut tokens = 0u32;
for s in states.iter().filter(|s| s.entry.source == src) {
count += 1;
if s.mode != AgentMemoryMode::Off {
tokens = tokens.saturating_add(s.entry.approx_tokens);
}
}
(count, tokens)
};
let (claude_notes, claude_tokens) = stats_for(AgentMemorySource::ClaudeAuto);
let claude_dir = home.and_then(|h| {
claude_auto_memory_dirs(&h.join(".claude"), h, &policy.workspace_roots).into_iter().next().or_else(|| {
policy
.workspace_roots
.first()
.map(|ws| h.join(".claude/projects").join(crate::native::claude::history::escape(ws)).join("memory"))
})
});
let (claude_mode, claude_origin) = resolve_provider_auto_memory("claude", session_overrides, policy);
let (codex_notes, codex_tokens) = stats_for(AgentMemorySource::CodexAuto);
let codex_dir =
home.and_then(|h| active_codex_memory_dir(&h.join(".codex")).or_else(|| Some(h.join(".codex/memories"))));
let codex_rollouts =
codex_dir.as_ref().map(|d| markdown_files(&d.join("rollout_summaries"), 1).len() as u32).unwrap_or(0);
let (codex_mode, codex_origin) = resolve_provider_auto_memory("codex", session_overrides, policy);
let (copilot_mode, copilot_origin) = resolve_provider_auto_memory("copilot", session_overrides, policy);
let (hermes_notes, hermes_tokens) = stats_for(AgentMemorySource::HermesAuto);
let hermes_dir = hermes_root(home).map(|r| r.join("memories"));
let (mut hermes_mode, hermes_origin) = resolve_provider_auto_memory("hermes", session_overrides, policy);
if hermes_mode == AutoMemoryMode::Inherit
&& let Some(root) = hermes_root(home)
&& let Some(cfg_mode) = read_hermes_config_memory_mode(&root)
{
hermes_mode = cfg_mode;
}
let (acp_mode, acp_origin) = resolve_provider_auto_memory("acp", session_overrides, policy);
vec![
AgentAutoMemoryStatus {
provider: "claude".into(),
label: "Claude Code".into(),
mode: claude_mode,
origin: claude_origin,
note_count: claude_notes,
rollout_count: 0,
approx_tokens: claude_tokens,
storage_path: claude_dir.map(Into::into),
supports_auto_control: true,
supports_file_exclusion: true,
supports_reset: true,
},
AgentAutoMemoryStatus {
provider: "codex".into(),
label: "Codex".into(),
mode: codex_mode,
origin: codex_origin,
note_count: codex_notes,
rollout_count: codex_rollouts,
approx_tokens: codex_tokens,
storage_path: codex_dir.map(Into::into),
supports_auto_control: true,
supports_file_exclusion: false,
supports_reset: true,
},
AgentAutoMemoryStatus {
provider: "copilot".into(),
label: "GitHub Copilot".into(),
mode: copilot_mode,
origin: copilot_origin,
note_count: 0,
rollout_count: 0,
approx_tokens: 0,
storage_path: home.map(|h| h.join(".copilot").into()),
supports_auto_control: true,
supports_file_exclusion: false,
supports_reset: false,
},
AgentAutoMemoryStatus {
provider: "hermes".into(),
label: "Hermes Agent".into(),
mode: hermes_mode,
origin: hermes_origin,
note_count: hermes_notes,
rollout_count: 0,
approx_tokens: hermes_tokens,
storage_path: hermes_dir.map(Into::into),
supports_auto_control: true,
supports_file_exclusion: false,
supports_reset: true,
},
AgentAutoMemoryStatus {
provider: "acp".into(),
label: "Cursor / Gemini / ACP".into(),
mode: acp_mode,
origin: acp_origin,
note_count: 0,
rollout_count: 0,
approx_tokens: 0,
storage_path: None,
supports_auto_control: false,
supports_file_exclusion: false,
supports_reset: false,
},
]
}
/// Directory under `<store_dir>/session-memory/<task_id>` holding per-session staged rules.
pub fn farm_dir(store_dir: &Path, task_id: &str) -> PathBuf {
store_dir.join("session-memory").join(task_id)
}
/// Removes a deleted task's staged memory folder, if any.
pub fn remove_farm(store_dir: &Path, task_id: &str) {
let _ = std::fs::remove_dir_all(farm_dir(store_dir, task_id));
}
/// Computes the per-session [`Delivery`] payload (`_meta.openidea.memory`) for `provider`,
/// staging non-native rules into `farm` where needed (e.g. Claude `.claude/rules/`).
pub fn stage(
farm: &Path,
provider: &str,
states: &[AgentMemoryState],
auto_memory: AutoMemoryMode,
cwd: &Path,
home: Option<&Path>,
) -> std::io::Result<Delivery> {
let norm = normalize_provider_id(provider);
let mut out = Delivery { auto_memory, ..Delivery::default() };
let claude_rules_dir = farm.join(".claude/rules");
match std::fs::remove_dir_all(&claude_rules_dir) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
_ => {}
}
match norm {
"claude" => {
out.claude_auto_memory = match auto_memory {
AutoMemoryMode::Inherit => None,
AutoMemoryMode::ReadWrite => Some(true),
// Claude Code has one boolean (`autoMemoryEnabled`): ReadOnly and Off both stop background writes;
// existing `MEMORY.md` entries that remain `Auto`/`Always` can still be staged as read-only rules.
AutoMemoryMode::ReadOnly | AutoMemoryMode::Off => Some(false),
};
let mut agents_md_active = false;
let mut agents_md_off = false;
let mut claude_md_active = false;
for state in states {
let effective_on = state.mode != AgentMemoryMode::Off && matches_agent_filter(&state.agents, provider);
let p = state.entry.path.0.as_path();
let fname = file_name(p).unwrap_or_default();
if matches!(state.entry.source, AgentMemorySource::Workspace) && fname == "AGENTS.md" {
if effective_on {
agents_md_active = true;
} else {
agents_md_off = true;
}
}
if matches!(state.entry.source, AgentMemorySource::ClaudeWorkspace)
&& matches!(fname.as_str(), "CLAUDE.md" | "CLAUDE.local.md")
&& effective_on
{
claude_md_active = true;
}
if !effective_on {
if !state.entry.source.is_auto() {
out.claude_md_excludes.push(p.to_string_lossy().replace('\\', "/"));
}
continue;
}
// Stage `Always` rules from other agents, or a `ReadOnly` `ClaudeAuto` `MEMORY.md`,
// into `<farm>/.claude/rules/`.
let stage_into_claude = (auto_memory == AutoMemoryMode::ReadOnly
&& state.entry.source == AgentMemorySource::ClaudeAuto
&& fname == "MEMORY.md")
|| (state.mode == AgentMemoryMode::Always
&& !matches!(
state.entry.source,
AgentMemorySource::ClaudeWorkspace | AgentMemorySource::ClaudeUser
));
if stage_into_claude {
stage_claude_rule(&claude_rules_dir, state)?;
}
}
if agents_md_active && claude_md_active {
out.claude_instruction_files = Some("claude-md-and-agents-md".into());
} else if agents_md_off {
out.claude_instruction_files = Some("claude-md".into());
}
if claude_rules_dir.exists() {
out.claude_add_dir = Some(farm.to_path_buf());
out.claude_additional_dirs_claude_md = true;
}
}
"codex" => {
match auto_memory {
AutoMemoryMode::Inherit => {}
AutoMemoryMode::ReadWrite => {
out.codex_use_memories = Some(true);
out.codex_generate_memories = Some(true);
}
AutoMemoryMode::ReadOnly => {
out.codex_use_memories = Some(true);
out.codex_generate_memories = Some(false);
}
AutoMemoryMode::Off => {
out.codex_use_memories = Some(false);
out.codex_generate_memories = Some(false);
}
}
let extra = collect_staged_text(states, provider, cwd, home, |s| {
s.mode == AgentMemoryMode::Always
&& !matches!(s.entry.source, AgentMemorySource::CodexUser | AgentMemorySource::CodexAuto)
});
if !extra.is_empty() {
out.codex_developer_instructions = Some(extra);
}
}
"copilot" => {
match auto_memory {
AutoMemoryMode::Inherit => {}
AutoMemoryMode::ReadWrite => {
out.copilot_enable_memory = Some(true);
}
AutoMemoryMode::ReadOnly => {
out.copilot_enable_memory = Some(true);
out.copilot_exclude_store_memory = true;
}
AutoMemoryMode::Off => {
out.copilot_enable_memory = Some(false);
out.copilot_exclude_store_memory = true;
}
}
let native_instructions: Vec<&AgentMemoryState> = states
.iter()
.filter(|s| {
matches!(
s.entry.source,
AgentMemorySource::Workspace
| AgentMemorySource::ClaudeWorkspace
| AgentMemorySource::GithubWorkspace
| AgentMemorySource::CopilotUser
)
})
.collect();
if !native_instructions.is_empty()
&& native_instructions
.iter()
.all(|s| s.mode == AgentMemoryMode::Off || !matches_agent_filter(&s.agents, provider))
{
out.copilot_disable_custom_instructions = true;
}
let extra = collect_staged_text(states, provider, cwd, home, |s| {
s.mode == AgentMemoryMode::Always
&& !matches!(s.entry.source, AgentMemorySource::GithubWorkspace | AgentMemorySource::CopilotUser)
});
if !extra.is_empty() {
out.copilot_system_message = Some(extra);
}
}
"hermes" => {
if auto_memory != AutoMemoryMode::Inherit
&& let Some(root) = hermes_root(home)
&& let Some(prof_home) = hermes::profile_home(&root, provider)
{
let _ = write_hermes_config_memory_mode(&prof_home, auto_memory);
}
}
_ => {}
}
Ok(out)
}
fn stage_claude_rule(rules_dir: &Path, state: &AgentMemoryState) -> std::io::Result<()> {
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
return Ok(());
};
std::fs::create_dir_all(rules_dir)?;
let fm = Frontmatter::parse(&raw);
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
if body.is_empty() {
return Ok(());
}
let slug = sanitize_slug(&state.entry.id);
let out_text = if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
let mut header = String::from("---\npaths:\n");
for p in &state.entry.paths {
header.push_str(&format!(" - \"{}\"\n", p.replace('"', "\\\"")));
}
header.push_str("---\n\n");
header.push_str(body);
header.push('\n');
header
} else {
format!("{body}\n")
};
std::fs::write(rules_dir.join(format!("{slug}.md")), out_text)
}
fn collect_staged_text<F>(
states: &[AgentMemoryState],
provider: &str,
_cwd: &Path,
_home: Option<&Path>,
include: F,
) -> String
where
F: Fn(&AgentMemoryState) -> bool,
{
let mut buf = String::new();
for state in states {
if state.mode == AgentMemoryMode::Off || !matches_agent_filter(&state.agents, provider) {
continue;
}
if !include(state) {
continue;
}
// Path-scoped rules only enter un-scoped system prompts when explicitly set to `Always`.
if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
continue;
}
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
continue;
};
let fm = Frontmatter::parse(&raw);
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
if body.is_empty() {
continue;
}
let chunk = format!("## Memory ({})\n{}\n\n", state.entry.title, body);
if buf.len() + chunk.len() > MAX_STAGED_SYSTEM_BYTES {
break;
}
buf.push_str(&chunk);
}
buf.trim().to_owned()
}
// ─── File Operations: Create, Promote, Delete & Reset ───────────────────────────────
/// Creates a new instruction or rule file on disk and returns its path.
pub fn create_memory(
input: &CreateAgentMemoryInput,
workspace_root: Option<&Path>,
home: Option<&Path>,
) -> Result<PathBuf, String> {
let body = input.content.trim();
if body.is_empty() {
return Err("Memory content cannot be empty".into());
}
let clean_paths: Vec<String> = input.paths.iter().map(|p| p.trim().to_owned()).filter(|p| !p.is_empty()).collect();
let desc = input.description.as_deref().map(str::trim).filter(|d| !d.is_empty());
let (dest, formatted) = match (input.scope, input.target) {
(McpScope::Workspace, AgentMemoryCreateTarget::AgentsMd) => {
let ws = workspace_root.ok_or("Open a project to create workspace instructions")?;
let dest = ws.join("AGENTS.md");
let next = if dest.is_file() {
let existing = std::fs::read_to_string(&dest).map_err(|e| e.to_string())?;
format!("{}\n\n{body}\n", existing.trim_end())
} else {
format!("{body}\n")
};
(dest, next)
}
(McpScope::User, AgentMemoryCreateTarget::AgentsMd) => {
let h = home.ok_or("Home directory is unavailable")?;
let dest = h.join(".codex/AGENTS.md");
let next = if dest.is_file() {
let existing = std::fs::read_to_string(&dest).map_err(|e| e.to_string())?;
format!("{}\n\n{body}\n", existing.trim_end())
} else {
format!("{body}\n")
};
(dest, next)
}
(scope, target) => {
let slug = validate_slug(&input.name)?;
let base = match scope {
McpScope::Workspace => workspace_root.ok_or("Open a project to create workspace memory")?,
McpScope::User => home.ok_or("Home directory is unavailable")?,
};
match target {
AgentMemoryCreateTarget::ClaudeRule => {
let dest = base.join(".claude/rules").join(format!("{slug}.md"));
(dest, format_markdown_with_frontmatter(desc, "paths", &clean_paths, None, body))
}
AgentMemoryCreateTarget::CopilotInstruction => {
let dir = if scope == McpScope::Workspace {
base.join(".github/instructions")
} else {
base.join(".copilot/instructions")
};
let dest = dir.join(format!("{slug}.instructions.md"));
let globs = if clean_paths.is_empty() { vec!["**".into()] } else { clean_paths };
(dest, format_copilot_instruction(desc, &globs, body))
}
AgentMemoryCreateTarget::CursorRule => {
if scope != McpScope::Workspace {
return Err("Cursor `.mdc` rules live in a workspace (`.cursor/rules`)".into());
}
let dest = base.join(".cursor/rules").join(format!("{slug}.mdc"));
let always_apply = clean_paths.is_empty() && desc.is_none();
(dest, format_cursor_mdc(desc, &clean_paths, always_apply, body))
}
AgentMemoryCreateTarget::AgentsMd => unreachable!(),
}
}
};
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
std::fs::write(&dest, formatted).map_err(|e| e.to_string())?;
Ok(dest)
}
/// Promotes a learned auto-memory note into `<workspace>/AGENTS.md`, optionally removing the
/// source note afterwards.
pub fn promote_memory(
input: &PromoteAgentMemoryInput,
entries: &[AgentMemoryEntry],
workspace_root: &Path,
) -> Result<PathBuf, String> {
let source = entries
.iter()
.find(|e| e.id == input.source_id)
.ok_or_else(|| format!("Memory entry `{}` was not found", input.source_id))?;
let raw = std::fs::read_to_string(&source.path.0).map_err(|e| e.to_string())?;
let fm = Frontmatter::parse(&raw);
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
if body.is_empty() {
return Err("Source memory note is empty".into());
}
let dest = workspace_root.join("AGENTS.md");
let heading = input
.heading
.as_deref()
.map(str::trim)
.filter(|h| !h.is_empty())
.map(|h| if h.starts_with('#') { h.to_owned() } else { format!("## {h}") });
let block = match heading {
Some(h) => format!("{h}\n\n{body}\n"),
None => format!("{body}\n"),
};
let next = if dest.is_file() {
let existing = std::fs::read_to_string(&dest).map_err(|e| e.to_string())?;
if existing.trim().is_empty() { block } else { format!("{}\n\n{block}", existing.trim_end()) }
} else {
block
};
std::fs::write(&dest, next).map_err(|e| e.to_string())?;
if input.remove_source && source.writable {
let _ = std::fs::remove_file(&source.path.0);
}
Ok(dest)
}
/// Deletes a writable memory entry (learned auto-memory notes).
pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), String> {
let entry = entries.iter().find(|e| e.id == id).ok_or_else(|| format!("Memory entry `{id}` was not found"))?;
if !entry.writable {
return Err(
"Curated instruction and rule files cannot be deleted here; open the file or set its mode to Off.".into()
);
}
match std::fs::remove_file(&entry.path.0) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.to_string()),
}
}
/// Clears local auto-memory files for `provider` (`claude`, `codex`, or `hermes`).
pub fn reset_provider_memory(provider: &str, workspaces: &[PathBuf], home: Option<&Path>) -> Result<u32, String> {
let home = home.ok_or("Home directory is unavailable")?;
let mut removed = 0u32;
match normalize_provider_id(provider) {
"claude" => {
for dir in claude_auto_memory_dirs(&home.join(".claude"), home, workspaces) {
for f in markdown_files(&dir, 2) {
if std::fs::remove_file(f).is_ok() {
removed += 1;
}
}
}
}
"codex" => {
for rel in [".codex/memories", ".codex/memories_v2"] {
let root = home.join(rel);
if !root.is_dir() {
continue;
}
for f in markdown_files(&root, 2) {
if std::fs::remove_file(f).is_ok() {
removed += 1;
}
}
}
}
"hermes" => {
if let Some(root) = hermes_root(Some(home)) {
let target_home = hermes::profile_home(&root, provider).unwrap_or(root);
for fname in ["MEMORY.md", "USER.md"] {
let p = target_home.join("memories").join(fname);
if p.is_file() && std::fs::remove_file(p).is_ok() {
removed += 1;
}
}
}
}
other => return Err(format!("Local auto-memory reset is not supported for `{other}`")),
}
Ok(removed)
}
// ─── Internal Helpers: Parsing, Validation & Discovery ───────────────────────────────
fn validate_slug(raw: &str) -> Result<String, String> {
let trimmed = raw.trim().trim_end_matches(".instructions.md").trim_end_matches(".mdc").trim_end_matches(".md");
if trimmed.is_empty() || trimmed.len() > 80 {
return Err("Memory name must be 1–80 characters (letters, digits, hyphens, or underscores)".into());
}
if trimmed.contains("..") || trimmed.contains('/') || trimmed.contains('\\') {
return Err("Memory name must not contain path separators or `..`".into());
}
if !trimmed.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
return Err(format!("Memory name `{trimmed}` may only contain ASCII letters, digits, `-`, or `_`"));
}
Ok(trimmed.to_owned())
}
fn sanitize_slug(raw: &str) -> String {
let mut out = String::new();
for ch in raw.chars() {
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
out.push(ch.to_ascii_lowercase());
} else if !out.ends_with('-') {
out.push('-');
}
}
let trimmed = out.trim_matches('-');
if trimmed.is_empty() { "memory".into() } else { trimmed.to_owned() }
}
fn format_markdown_with_frontmatter(
description: Option<&str>,
paths_key: &str,
paths: &[String],
category: Option<&str>,
body: &str,
) -> String {
if description.is_none() && paths.is_empty() && category.is_none() {
return format!("{body}\n");
}
let mut out = String::from("---\n");
if let Some(cat) = category {
out.push_str(&format!("type: \"{}\"\n", cat.replace('"', "\\\"")));
}
if let Some(desc) = description {
out.push_str(&format!("description: \"{}\"\n", desc.replace('"', "\\\"")));
}
if !paths.is_empty() {
out.push_str(&format!("{paths_key}:\n"));
for p in paths {
out.push_str(&format!(" - \"{}\"\n", p.replace('"', "\\\"")));
}
}
out.push_str("---\n\n");
out.push_str(body);
out.push('\n');
out
}
fn format_copilot_instruction(description: Option<&str>, globs: &[String], body: &str) -> String {
let mut out = String::from("---\n");
if let Some(desc) = description {
out.push_str(&format!("description: \"{}\"\n", desc.replace('"', "\\\"")));
}
let joined = globs.join(", ");
out.push_str(&format!("applyTo: \"{}\"\n", joined.replace('"', "\\\"")));
out.push_str("---\n\n");
out.push_str(body);
out.push('\n');
out
}
fn format_cursor_mdc(description: Option<&str>, globs: &[String], always_apply: bool, body: &str) -> String {
let mut out = String::from("---\n");
if let Some(desc) = description {
out.push_str(&format!("description: \"{}\"\n", desc.replace('"', "\\\"")));
}
if !globs.is_empty() {
out.push_str(&format!("globs: {}\n", globs.join(", ")));
}
out.push_str(&format!("alwaysApply: {always_apply}\n---\n\n{body}\n"));
out
}
fn lookup_entry_policy<'a>(
map: &'a BTreeMap<String, AgentMemoryEntryPolicy>,
id: &str,
) -> Option<&'a AgentMemoryEntryPolicy> {
map.get(id).or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| v))
}
fn lookup_session_entry(map: &BTreeMap<String, AgentMemoryMode>, id: &str) -> Option<AgentMemoryMode> {
map.get(id).copied().or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| *v))
}
fn claude_auto_memory_dirs(claude_home: &Path, home: &Path, workspaces: &[PathBuf]) -> Vec<PathBuf> {
let mut dirs = Vec::new();
let mut seen = HashSet::new();
let mut push = |p: PathBuf| {
if p.is_dir() {
let canon = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone());
if seen.insert(canon) {
dirs.push(p);
}
}
};
// Custom `autoMemoryDirectory` in `~/.claude/settings.json`
if let Ok(text) = std::fs::read_to_string(claude_home.join("settings.json"))
&& let Ok(val) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Some(raw_dir) = val.get("autoMemoryDirectory").and_then(serde_json::Value::as_str).map(str::trim)
&& !raw_dir.is_empty()
{
let resolved =
if let Some(rest) = raw_dir.strip_prefix("~/") { home.join(rest) } else { PathBuf::from(raw_dir) };
if resolved.is_absolute() {
push(resolved);
}
}
let projects_root = claude_home.join("projects");
for ws in workspaces {
let canon_ws = dunce::canonicalize(ws).unwrap_or_else(|_| ws.clone());
for candidate_ws in [ws.as_path(), canon_ws.as_path()] {
let key = crate::native::claude::history::escape(candidate_ws);
push(projects_root.join(key).join("memory"));
}
}
dirs
}
fn active_codex_memory_dir(codex_home: &Path) -> Option<PathBuf> {
let v2 = codex_home.join("memories_v2");
if v2.is_dir() {
return Some(v2);
}
let v1 = codex_home.join("memories");
v1.is_dir().then_some(v1)
}
fn read_hermes_config_memory_mode(profile_home: &Path) -> Option<AutoMemoryMode> {
let text = std::fs::read_to_string(profile_home.join("config.yaml")).ok()?;
let mut in_memory = false;
let mut mem_enabled: Option<bool> = None;
let mut prof_enabled: Option<bool> = None;
for line in text.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if !line.starts_with([' ', '\t']) {
in_memory = trimmed == "memory:";
continue;
}
if !in_memory {
continue;
}
if let Some(v) = trimmed.strip_prefix("memory_enabled:") {
mem_enabled = parse_yaml_bool(v);
} else if let Some(v) = trimmed.strip_prefix("user_profile_enabled:") {
prof_enabled = parse_yaml_bool(v);
}
}
match (mem_enabled, prof_enabled) {
(Some(false), Some(false)) | (Some(false), None) => Some(AutoMemoryMode::Off),
(Some(true), _) | (_, Some(true)) => Some(AutoMemoryMode::ReadWrite),
_ => None,
}
}
fn write_hermes_config_memory_mode(profile_home: &Path, mode: AutoMemoryMode) -> std::io::Result<()> {
let enabled = match mode {
AutoMemoryMode::Inherit => return Ok(()),
AutoMemoryMode::ReadWrite | AutoMemoryMode::ReadOnly => true,
AutoMemoryMode::Off => false,
};
std::fs::create_dir_all(profile_home)?;
let cfg_path = profile_home.join("config.yaml");
let existing = std::fs::read_to_string(&cfg_path).unwrap_or_default();
let updated = upsert_hermes_memory_block(&existing, enabled);
std::fs::write(cfg_path, updated)
}
fn upsert_hermes_memory_block(existing: &str, enabled: bool) -> String {
let mut out = Vec::new();
let mut in_memory = false;
let mut saw_memory_section = false;
let mut wrote_mem = false;
let mut wrote_prof = false;
for line in existing.lines() {
let trimmed = line.trim();
if !line.starts_with([' ', '\t']) && !trimmed.is_empty() && !trimmed.starts_with('#') {
if in_memory {
if !wrote_mem {
out.push(format!(" memory_enabled: {enabled}"));
}
if !wrote_prof {
out.push(format!(" user_profile_enabled: {enabled}"));
}
}
in_memory = trimmed == "memory:";
if in_memory {
saw_memory_section = true;
}
out.push(line.to_owned());
continue;
}
if in_memory {
if trimmed.starts_with("memory_enabled:") {
out.push(format!(" memory_enabled: {enabled}"));
wrote_mem = true;
continue;
}
if trimmed.starts_with("user_profile_enabled:") {
out.push(format!(" user_profile_enabled: {enabled}"));
wrote_prof = true;
continue;
}
}
out.push(line.to_owned());
}
if in_memory {
if !wrote_mem {
out.push(format!(" memory_enabled: {enabled}"));
}
if !wrote_prof {
out.push(format!(" user_profile_enabled: {enabled}"));
}
} else if !saw_memory_section {
if !out.is_empty() && !out.last().is_some_and(|l| l.is_empty()) {
out.push(String::new());
}
out.push("memory:".into());
out.push(format!(" memory_enabled: {enabled}"));
out.push(format!(" user_profile_enabled: {enabled}"));
}
let mut joined = out.join("\n");
joined.push('\n');
joined
}
fn parse_yaml_bool(raw: &str) -> Option<bool> {
let v = raw.split('#').next()?.trim().trim_matches(['"', '\'']);
if v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes") {
Some(true)
} else if v.eq_ignore_ascii_case("false") || v.eq_ignore_ascii_case("no") {
Some(false)
} else {
None
}
}
fn parse_claude_auto_note(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
let mut entry = parse_entry(path, rel, AgentMemorySource::ClaudeAuto, Some(AgentMemoryKind::AutoNote), true, None)?;
if file_name(path).as_deref() == Some("MEMORY.md") {
if entry.line_count > CLAUDE_MEMORY_INDEX_LINE_CAP || entry.byte_len > CLAUDE_MEMORY_INDEX_BYTE_CAP {
entry.valid = false;
entry.warnings.push(format!(
"`MEMORY.md` exceeds Claude Code's startup limit ({} lines / {} bytes; cap is {CLAUDE_MEMORY_INDEX_LINE_CAP} lines or 25 KB)",
entry.line_count, entry.byte_len
));
} else if entry.line_count >= CLAUDE_MEMORY_INDEX_WARN_LINES || entry.byte_len >= CLAUDE_MEMORY_INDEX_WARN_BYTES
{
entry.warnings.push(format!(
"`MEMORY.md` is near Claude Code's 200-line / 25 KB startup truncation cap ({} lines)",
entry.line_count
));
}
}
Some(entry)
}
fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
let text = std::fs::read_to_string(path).ok()?;
let meta = std::fs::metadata(path).ok()?;
let fm = Frontmatter::parse(&text);
let always_apply = fm.get("alwaysApply").is_some_and(|v| v.eq_ignore_ascii_case("true"));
let paths = if always_apply { Vec::new() } else { parse_globs(&fm) };
let kind = if always_apply { AgentMemoryKind::Instruction } else { AgentMemoryKind::Rule };
let title = fm
.get("name")
.map(|n| strip_ansi(n).trim().to_owned())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| rel.to_owned());
let description = fm.description(&text);
let line_count = count_lines(&text);
let byte_len = meta.len();
let modified_ms = modified_millis(&meta);
let mut warnings = Vec::new();
if !always_apply && paths.is_empty() && fm.get("description").is_none_or(|d| d.trim().is_empty()) {
warnings.push(
"Manual Cursor rule (`alwaysApply: false` with no `globs` or `description`): only loads when `@`-mentioned"
.into(),
);
}
Some(AgentMemoryEntry {
id: entry_id(AgentMemorySource::CursorWorkspace, rel),
title,
description,
kind,
source: AgentMemorySource::CursorWorkspace,
also_in: Vec::new(),
path: path.to_path_buf().into(),
paths,
category: None,
approx_tokens: estimate_tokens(&text),
line_count,
byte_len,
modified_ms,
writable: false,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
fn parse_entry(
path: &Path,
rel: &str,
source: AgentMemorySource,
forced_kind: Option<AgentMemoryKind>,
writable: bool,
import_boundary: Option<&Path>,
) -> Option<AgentMemoryEntry> {
let text = std::fs::read_to_string(path).ok()?;
let meta = std::fs::metadata(path).ok()?;
let fm = Frontmatter::parse(&text);
let paths = parse_globs(&fm);
let kind =
forced_kind.unwrap_or(if paths.is_empty() { AgentMemoryKind::Instruction } else { AgentMemoryKind::Rule });
let title = fm
.get("name")
.map(|n| strip_ansi(n).trim().to_owned())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| rel.to_owned());
let description = fm.description(&text);
let category = fm
.get("type")
.or_else(|| fm.get("category"))
.map(|c| strip_ansi(c).trim().to_owned())
.filter(|c| !c.is_empty());
let line_count = count_lines(&text);
let byte_len = meta.len();
let modified_ms = modified_millis(&meta);
let mut warnings = Vec::new();
if kind == AgentMemoryKind::Instruction && line_count > INSTRUCTION_WARN_LINES {
warnings.push(format!(
"{line_count} lines (over {INSTRUCTION_WARN_LINES}-line recommendation; consider moving procedures into path-scoped rules or skills)"
));
}
if let Some(boundary) = import_boundary
&& matches!(
source,
AgentMemorySource::Workspace
| AgentMemorySource::ClaudeWorkspace
| AgentMemorySource::ClaudeUser
| AgentMemorySource::GithubWorkspace
| AgentMemorySource::CopilotUser
)
{
for broken in broken_imports(path, fm.body_text(&text), boundary) {
warnings.push(format!("Unresolved `@{broken}` import"));
}
}
Some(AgentMemoryEntry {
id: entry_id(source, rel),
title,
description,
kind,
source,
also_in: Vec::new(),
path: path.to_path_buf().into(),
paths,
category,
approx_tokens: estimate_tokens(&text),
line_count,
byte_len,
modified_ms,
writable,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
/// Detects when a `CLAUDE.md` file contains only a single `@AGENTS.md` (or `@./AGENTS.md`)
/// import and no additional instructions, returning the canonical target path so the two
/// collapse into one unified row.
fn sole_import_target(path: &Path) -> Option<PathBuf> {
let text = std::fs::read_to_string(path).ok()?;
let trimmed = text.trim();
if trimmed.lines().count() != 1 {
return None;
}
let rel = trimmed.strip_prefix('@')?.trim();
if rel.is_empty() || rel.contains(char::is_whitespace) {
return None;
}
let target = path.parent()?.join(rel);
dunce::canonicalize(target).ok()
}
/// Checks `@path` imports outside Markdown fenced code blocks and inline code spans,
/// returning relative targets with a `.md` / `.mdc` / `.txt` / `.json` extension (or explicit `./` / `../`)
/// that do not exist on disk.
fn broken_imports(file_path: &Path, body: &str, _boundary: &Path) -> Vec<String> {
let Some(base_dir) = file_path.parent() else { return Vec::new() };
let mut missing = Vec::new();
let mut seen = HashSet::new();
let mut in_fence = false;
for raw_line in body.lines() {
let trimmed = raw_line.trim_start();
if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
in_fence = !in_fence;
continue;
}
if in_fence {
continue;
}
for token in outside_inline_code_tokens(raw_line) {
let Some(after_at) = token.strip_prefix('@') else { continue };
let candidate = after_at.trim_end_matches([',', '.', ';', ')', ']']);
if candidate.is_empty() || candidate.contains("://") || candidate.starts_with('~') {
continue;
}
let looks_like_import = candidate.starts_with("./")
|| candidate.starts_with("../")
|| candidate.ends_with(".md")
|| candidate.ends_with(".mdc")
|| candidate.ends_with(".txt");
if !looks_like_import {
continue;
}
let resolved =
if Path::new(candidate).is_absolute() { PathBuf::from(candidate) } else { base_dir.join(candidate) };
if !resolved.exists() && seen.insert(candidate.to_owned()) {
missing.push(candidate.to_owned());
}
}
}
missing
}
fn outside_inline_code_tokens(line: &str) -> Vec<&str> {
let mut non_code = Vec::new();
for (idx, part) in line.split('`').enumerate() {
if idx % 2 == 0 {
non_code.extend(part.split_whitespace());
}
}
non_code
}
fn estimate_tokens(text: &str) -> u32 {
let chars = text.chars().count();
if chars == 0 { 0 } else { (chars.div_ceil(4)) as u32 }
}
fn count_lines(text: &str) -> u32 {
if text.is_empty() { 0 } else { text.lines().count() as u32 }
}
fn modified_millis(meta: &std::fs::Metadata) -> Option<f64> {
let mtime = meta.modified().ok()?;
let dur = mtime.duration_since(std::time::UNIX_EPOCH).ok()?;
Some(dur.as_millis() as f64)
}
fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
if max_depth == 0 {
return Vec::new();
}
let mut out = Vec::new();
for dir in sorted_entries(root) {
let Some(name) = file_name(&dir) else { continue };
if SKIP_MONOREPO_DIRS.contains(&name.as_str()) {
continue;
}
let Ok(meta) = std::fs::symlink_metadata(&dir) else { continue };
if !meta.file_type().is_dir() {
continue;
}
let has_memory = dir.join("AGENTS.md").is_file()
|| dir.join("CLAUDE.md").is_file()
|| dir.join("GEMINI.md").is_file()
|| dir.join(".claude/rules").is_dir()
|| dir.join(".cursor/rules").is_dir();
if has_memory {
out.push(dir.clone());
}
if max_depth > 1 {
out.extend(monorepo_subdirs(&dir, max_depth - 1));
}
}
out
}
fn markdown_files(root: &Path, max_depth: usize) -> Vec<PathBuf> {
files_matching_suffix(root, ".md", max_depth)
}
fn files_matching_suffix(root: &Path, suffix: &str, max_depth: usize) -> Vec<PathBuf> {
if max_depth == 0 || !root.is_dir() {
return Vec::new();
}
let mut out = Vec::new();
for path in sorted_entries(root) {
if path.is_dir() {
if max_depth > 1 {
out.extend(files_matching_suffix(&path, suffix, max_depth - 1));
}
} else if file_name(&path).is_some_and(|n| n.ends_with(suffix)) {
out.push(path);
}
}
out
}
fn sorted_entries(dir: &Path) -> Vec<PathBuf> {
let mut paths: Vec<_> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| file_name(p).is_some_and(|n| !n.starts_with('.')))
.collect();
paths.sort();
paths
}
fn file_name(path: &Path) -> Option<String> {
path.file_name()?.to_str().map(str::to_owned)
}
fn rel_from(base: &Path, path: &Path) -> String {
path.strip_prefix(base).unwrap_or(path).to_string_lossy().replace('\\', "/")
}
fn truncate(s: &str) -> String {
match s.char_indices().nth(MAX_DESCRIPTION_CHARS) {
Some((i, _)) => format!("{}…", s[..i].trim_end()),
None => s.to_owned(),
}
}
fn unquote(value: &str) -> &str {
for q in ['"', '\''] {
if let Some(inner) = value.strip_prefix(q).and_then(|v| v.strip_suffix(q)) {
return inner;
}
}
value
}
struct Frontmatter {
fields: Vec<(String, String)>,
lists: Vec<(String, Vec<String>)>,
body: usize,
}
impl Frontmatter {
fn parse(text: &str) -> Self {
let stripped = text.strip_prefix('\u{feff}').unwrap_or(text);
let bom_len = text.len() - stripped.len();
let mut lines = stripped.split_inclusive('\n');
let mut offset = bom_len;
let mut fields: Vec<(String, String)> = Vec::new();
let mut lists: Vec<(String, Vec<String>)> = Vec::new();
match lines.next() {
Some(first) if first.trim_end() == "---" => offset += first.len(),
_ => return Self { fields, lists, body: bom_len },
}
for line in lines {
offset += line.len();
let line = line.trim_end();
if line == "---" {
return Self { fields, lists, body: offset };
}
let unindented_list_item = (line == "-" || line.starts_with("- ") || line.starts_with("-\t"))
&& fields.last().is_some_and(|(_, v)| v.is_empty());
if line.starts_with([' ', '\t']) || unindented_list_item {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix('-')
&& (rest.is_empty() || rest.starts_with([' ', '\t']))
&& let Some((key, _)) = fields.last()
{
let item = unquote(rest.trim());
if !item.is_empty() {
if let Some((_, existing)) = lists.iter_mut().find(|(k, _)| k == key) {
existing.push(item.to_owned());
} else {
lists.push((key.clone(), vec![item.to_owned()]));
}
}
if unindented_list_item {
continue;
}
}
if let Some((_, value)) = fields.last_mut() {
if !value.is_empty() {
value.push(' ');
}
value.push_str(trimmed);
}
continue;
}
if let Some((key, value)) = line.split_once(':') {
let value = value.trim();
let value = if matches!(value, ">" | "|" | ">-" | "|-") { "" } else { unquote(value) };
fields.push((key.trim().to_owned(), value.to_owned()));
}
}
Self { fields: Vec::new(), lists: Vec::new(), body: bom_len }
}
fn get(&self, key: &str) -> Option<&str> {
self.fields.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_str())
}
fn list(&self, key: &str) -> Option<&[String]> {
self.lists.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_slice())
}
fn body_text<'a>(&self, text: &'a str) -> &'a str {
text.get(self.body..).unwrap_or_default()
}
fn description(&self, text: &str) -> String {
let raw =
self.get("description").map(|d| strip_ansi(d).trim().to_owned()).filter(|d| !d.is_empty()).unwrap_or_else(
|| {
self.body_text(text)
.lines()
.map(strip_ansi)
.map(|l| l.trim().trim_start_matches(['#', '-', '*']).trim().to_owned())
.find(|l| !l.is_empty() && !l.starts_with("<!--"))
.unwrap_or_default()
},
);
truncate(&raw)
}
}
fn parse_globs(meta: &Frontmatter) -> Vec<String> {
for key in ["paths", "applyTo", "globs"] {
if let Some(items) = meta.list(key) {
let cleaned: Vec<String> =
items.iter().map(|s| strip_ansi(s).trim().to_owned()).filter(|s| !s.is_empty()).collect();
if !cleaned.is_empty() {
return cleaned;
}
}
if let Some(raw) = meta.get(key) {
let trimmed = strip_ansi(raw);
let inner = trimmed.trim().strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(trimmed.trim());
let cleaned: Vec<String> =
inner.split(',').map(|p| unquote(p.trim()).trim().to_owned()).filter(|p| !p.is_empty()).collect();
if !cleaned.is_empty() {
return cleaned;
}
}
}
Vec::new()
}
#[cfg(test)]
mod tests {
use super::*;
fn write(path: &Path, content: &str) {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(path, content).unwrap();
}
#[test]
fn discovers_multi_agent_memories_normalizes_globs_and_deduplicates_imports_and_symlinks() {
let tmp = tempfile::tempdir().unwrap();
let ws = tmp.path().join("repo");
let home = tmp.path().join("home");
write(&ws.join("AGENTS.md"), "# Repo Rules\nAlways run targeted tests first.\n");
// Thin `@AGENTS.md` wrapper in `CLAUDE.md` collapses onto `AGENTS.md`.
write(&ws.join("CLAUDE.md"), "@AGENTS.md\n");
write(
&ws.join(".claude/rules/api.md"),
"---\npaths:\n - \"crates/**/*.rs\"\n---\nValidate all RPC arguments.\n",
);
write(
&ws.join(".github/instructions/ts.instructions.md"),
"---\ndescription: \"TypeScript UI standards\"\napplyTo: \"src/**/*.ts, src/**/*.tsx\"\n---\nUse CSS modules.\n",
);
write(
&ws.join(".cursor/rules/react.mdc"),
"---\ndescription: React conventions\nglobs: src/features/**/*.tsx\nalwaysApply: false\n---\nPrefer named exports.\n",
);
write(&ws.join("GEMINI.md"), "Use concise summaries.\n");
write(&ws.join("packages/sub/AGENTS.md"), "Subpackage build note.\n");
// Claude auto-memory + near-cap `MEMORY.md`
let escaped = crate::native::claude::history::escape(&dunce::canonicalize(&ws).unwrap());
let claude_mem = home.join(".claude/projects").join(escaped).join("memory");
let long_index = (0..205).map(|i| format!("- item {i}")).collect::<Vec<_>>().join("\n");
write(&claude_mem.join("MEMORY.md"), &long_index);
write(
&claude_mem.join("feedback_tests.md"),
"---\ntype: feedback\ndescription: Run targeted vitest first\n---\nAvoid running full suite on single-file edits.\n",
);
// Codex auto-memory + Hermes profile memory + Gemini user instructions
write(&home.join(".codex/memories/MEMORY.md"), "Codex consolidated index\n");
write(&home.join(".codex/memories/rollout_summaries/r1.md"), "Rollout 1 summary\n");
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
write(&home.join(".hermes/memories/MEMORY.md"), "Hermes agent note\n");
write(&home.join(".hermes/memories/USER.md"), "Hermes user profile\n");
write(&home.join(".gemini/GEMINI.md"), "\x1b[31mPrefer dark mode mocks\x1b[0m\n");
let found = discover_memories(std::slice::from_ref(&ws), Some(&home));
// `CLAUDE.md` collapsed onto `AGENTS.md`
let agents_md = found.iter().find(|e| e.id == "workspace::AGENTS.md").unwrap();
assert!(agents_md.also_in.contains(&AgentMemorySource::ClaudeWorkspace));
assert!(!found.iter().any(|e| e.id == "claudeWorkspace::CLAUDE.md"));
// Glob normalization across Claude (`paths`), Copilot (`applyTo`), and Cursor (`globs`)
let claude_rule = found.iter().find(|e| e.id == "claudeWorkspace::.claude/rules/api.md").unwrap();
assert_eq!(claude_rule.kind, AgentMemoryKind::Rule);
assert_eq!(claude_rule.paths, ["crates/**/*.rs"]);
let copilot_rule =
found.iter().find(|e| e.id == "githubWorkspace::.github/instructions/ts.instructions.md").unwrap();
assert_eq!(copilot_rule.paths, ["src/**/*.ts", "src/**/*.tsx"]);
assert_eq!(copilot_rule.description, "TypeScript UI standards");
let cursor_rule = found.iter().find(|e| e.id == "cursorWorkspace::.cursor/rules/react.mdc").unwrap();
assert_eq!(cursor_rule.kind, AgentMemoryKind::Rule);
assert_eq!(cursor_rule.paths, ["src/features/**/*.tsx"]);
// Monorepo subpackage discovered
assert!(found.iter().any(|e| e.id == "workspace::packages/sub/AGENTS.md"));
// Claude `MEMORY.md` cap warning & feedback category
let claude_idx = found.iter().find(|e| e.id == "claudeAuto::MEMORY.md").unwrap();
assert!(!claude_idx.valid);
assert!(claude_idx.warnings.iter().any(|w| w.contains("exceeds Claude Code's startup limit")));
let feedback = found.iter().find(|e| e.id == "claudeAuto::feedback_tests.md").unwrap();
assert_eq!(feedback.category.as_deref(), Some("feedback"));
assert!(feedback.writable);
// ANSI stripped on the user's Gemini instructions
let personal = found.iter().find(|e| e.id == "geminiUser::GEMINI.md").unwrap();
assert_eq!(personal.description, "Prefer dark mode mocks");
// Codex & Hermes discovered
assert!(found.iter().any(|e| e.id == "codexAuto::MEMORY.md"));
assert!(found.iter().any(|e| e.id == "hermesAuto::USER.md"));
}
#[test]
fn broken_imports_ignore_markdown_code_fences_and_inline_spans() {
let tmp = tempfile::tempdir().unwrap();
let ws = tmp.path();
write(&ws.join("docs/real.md"), "Real doc\n");
write(
&ws.join("CLAUDE.md"),
"See @docs/real.md and `@docs/inline-ignored.md`.\n```md\n@docs/fence-ignored.md\n```\nAlso @docs/missing.md\n",
);
let found = discover_memories(&[ws.to_path_buf()], None);
let entry = found.iter().find(|e| e.id == "claudeWorkspace::CLAUDE.md").unwrap();
assert_eq!(entry.warnings, ["Unresolved `@docs/missing.md` import"]);
}
#[test]
fn policy_resolution_enforces_workspace_trust_and_precedence() {
let tmp = tempfile::tempdir().unwrap();
let ws = tmp.path().join("ws");
let home = tmp.path().join("home");
write(&ws.join("AGENTS.md"), "Workspace instructions\n");
write(&home.join(".claude/CLAUDE.md"), "User memory\n");
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
let mut ws_settings = AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() };
// Untrusted workspace tries to turn user memory `Always` on (ignored!) and another `Off` (honored).
ws_settings.entries.insert(
"claudeUser::CLAUDE.md".into(),
AgentMemoryEntryPolicy { mode: AgentMemoryMode::Always, agents: Vec::new() },
);
let untrusted = MemoryPolicy {
user: AgentMemorySettings::default(),
workspace: ws_settings.clone(),
workspace_trusted: false,
workspace_roots: vec![ws.clone()],
};
let cat = resolve_catalog(entries.clone(), None, &untrusted, Some(&home));
// Workspace entry locked `Off` by Trust
let ws_state = cat.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
assert_eq!((ws_state.mode, ws_state.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Trust));
// Untrusted workspace could NOT escalate `claudeUser::CLAUDE.md` or `autoMemory`
let user_state = cat.entries.iter().find(|s| s.entry.id == "claudeUser::CLAUDE.md").unwrap();
assert_eq!((user_state.mode, user_state.origin), (AgentMemoryMode::Auto, AgentMemoryOrigin::None));
assert_eq!(cat.auto_memory, AutoMemoryMode::Inherit);
// Session override wins in a trusted workspace
let trusted = MemoryPolicy { workspace_trusted: true, ..untrusted };
let session = AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::from([("workspace::AGENTS.md".into(), AgentMemoryMode::Off)]),
};
let cat2 = resolve_catalog(entries, Some(&session), &trusted, Some(&home));
assert_eq!((cat2.auto_memory, cat2.auto_memory_origin), (AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session));
let ws_state2 = cat2.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
assert_eq!((ws_state2.mode, ws_state2.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Session));
}
#[test]
fn stages_per_driver_delivery_for_claude_codex_copilot_and_hermes() {
let tmp = tempfile::tempdir().unwrap();
let ws = tmp.path().join("ws");
let home = tmp.path().join("home");
let farm = tmp.path().join("farm");
write(&ws.join("AGENTS.md"), "Shared workspace rule\n");
write(&ws.join("CLAUDE.md"), "Claude-specific rule\n");
write(&ws.join("CLAUDE.local.md"), "Noisy local note\n");
write(
&ws.join(".github/instructions/ipc.instructions.md"),
"---\napplyTo: \"crates/**/*.rs\"\n---\nUse async IPC for disk ops.\n",
);
write(&home.join(".gemini/GEMINI.md"), "Keep PRs focused.\n");
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
let session = AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::from([
("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off),
// `Always` delivers another agent's files to every agent, path scope dropped.
("githubWorkspace::.github/instructions/ipc.instructions.md".into(), AgentMemoryMode::Always),
("geminiUser::GEMINI.md".into(), AgentMemoryMode::Always),
]),
};
let policy = MemoryPolicy { workspace_roots: vec![ws.clone()], workspace_trusted: true, ..Default::default() };
let cat = resolve_catalog(entries, Some(&session), &policy, Some(&home));
// 1. Claude delivery
let claude = stage(&farm, "claude", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
assert_eq!(claude.claude_auto_memory, Some(false));
assert_eq!(claude.claude_instruction_files.as_deref(), Some("claude-md-and-agents-md"));
assert!(claude.claude_md_excludes.iter().any(|p| p.ends_with("CLAUDE.local.md")));
assert!(claude.claude_add_dir.is_some());
assert!(claude.claude_additional_dirs_claude_md);
let staged_rule = std::fs::read_to_string(
farm.join(".claude/rules/githubworkspace-github-instructions-ipc-instructions-md.md"),
)
.unwrap();
assert_eq!(staged_rule, "Use async IPC for disk ops.\n");
assert!(farm.join(".claude/rules/geminiuser-gemini-md.md").is_file());
// 2. Codex delivery
let codex = stage(&farm, "codex", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
assert_eq!(codex.codex_use_memories, Some(true));
assert_eq!(codex.codex_generate_memories, Some(false));
assert!(codex.codex_developer_instructions.as_deref().unwrap().contains("Keep PRs focused."));
// 3. Copilot delivery
let copilot = stage(&farm, "copilot", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
assert_eq!(copilot.copilot_enable_memory, Some(true));
assert!(copilot.copilot_exclude_store_memory);
let copilot_message = copilot.copilot_system_message.as_deref().unwrap();
assert!(copilot_message.contains("Keep PRs focused."));
// Copilot reads `.github/instructions` natively: not repeated in the system message.
assert!(!copilot_message.contains("Use async IPC"));
// 4. Hermes delivery updates config.yaml
let _ = stage(&farm, "hermes", &cat.entries, AutoMemoryMode::Off, &ws, Some(&home)).unwrap();
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
}
#[test]
fn create_promote_delete_and_reset_roundtrip() {
let tmp = tempfile::tempdir().unwrap();
let ws = tmp.path().join("ws");
let home = tmp.path().join("home");
std::fs::create_dir_all(&ws).unwrap();
// Reject path traversal in a new rule's name
assert!(
create_memory(
&CreateAgentMemoryInput {
scope: McpScope::Workspace,
target: AgentMemoryCreateTarget::ClaudeRule,
name: "../evil".into(),
description: None,
paths: Vec::new(),
content: "bad".into(),
},
Some(&ws),
Some(&home),
)
.is_err()
);
// Simulate Claude auto-memory note and promote it into `AGENTS.md` with source cleanup
let escaped = crate::native::claude::history::escape(&dunce::canonicalize(&ws).unwrap());
let note_path = home.join(".claude/projects").join(escaped).join("memory/feedback_lint.md");
write(&note_path, "---\ntype: feedback\n---\nRun `pnpm lint` before pushing.\n");
let found = discover_memories(std::slice::from_ref(&ws), Some(&home));
let promoted = promote_memory(
&PromoteAgentMemoryInput {
source_id: "claudeAuto::feedback_lint.md".into(),
heading: Some("Verification".into()),
remove_source: true,
},
&found,
&ws,
)
.unwrap();
assert_eq!(promoted, ws.join("AGENTS.md"));
assert!(!note_path.exists());
let agents_text = std::fs::read_to_string(ws.join("AGENTS.md")).unwrap();
assert!(agents_text.contains("## Verification\n\nRun `pnpm lint` before pushing."));
// Curated `AGENTS.md` refuses `delete_memory`
let found2 = discover_memories(std::slice::from_ref(&ws), Some(&home));
assert!(delete_memory("workspace::AGENTS.md", &found2).is_err());
// Provider reset clears Codex memories
write(&home.join(".codex/memories/MEMORY.md"), "stale\n");
assert_eq!(reset_provider_memory("codex", std::slice::from_ref(&ws), Some(&home)).unwrap(), 1);
assert!(!home.join(".codex/memories/MEMORY.md").exists());
}
}