дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 17:21:13 +02:00
refactor(agents): replace per-file memory controls with native-only auto-memory controls
Цей коміт міститься в:
1 джерело
b747e81cb6
коміт
189e4ee370
32 files changed
+1014
-1686
No files matched your search
@@ -2357,7 +2357,7 @@ impl AgentManager {
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides, None);
|
||||
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
|
||||
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
|
||||
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
|
||||
let memory_delivery = source.memory_delivery(live.driver, &provider_id);
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
.peer
|
||||
@@ -3299,7 +3299,6 @@ impl AgentManager {
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let _ = std::fs::remove_dir_all(task.turn_dir());
|
||||
skills::remove_farm(&self.shared.paths.store_dir, id);
|
||||
memory::remove_farm(&self.shared.paths.store_dir, id);
|
||||
let saved = task.state.lock().saved.clone();
|
||||
if let Some(saved) = saved
|
||||
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
|
||||
@@ -3683,17 +3682,11 @@ impl AgentManager {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sets the session's memory overrides (auto-memory mode and per-entry modes); like MCP
|
||||
/// and skill overrides, an idle resumable session recycles so the next turn starts with
|
||||
/// the updated delivery.
|
||||
/// Sets the session's auto-memory override; like MCP and skill overrides, an idle resumable
|
||||
/// session recycles so the next turn starts with the updated delivery.
|
||||
pub fn set_memory_overrides(&self, id: &str, overrides: AgentMemoryOverrides) -> IdeResult<AgentTask> {
|
||||
let task = self.task(id)?;
|
||||
let cleaned_entries: BTreeMap<String, AgentMemoryMode> = overrides
|
||||
.entries
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
|
||||
.collect();
|
||||
let cleaned = AgentMemoryOverrides { auto_memory: overrides.auto_memory, entries: cleaned_entries };
|
||||
let cleaned = AgentMemoryOverrides { auto_memory: overrides.auto_memory };
|
||||
let next_boxed = (!cleaned.is_empty()).then(|| Box::new(cleaned));
|
||||
let (changed, busy, has_bg, out) = {
|
||||
let mut s = task.state.lock();
|
||||
@@ -3837,42 +3830,17 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves and stages the session's memory delivery (`_meta.openidea.memory`).
|
||||
async fn stage_memory(&self, provider: &str, cwd: &Path) -> Option<memory::Delivery> {
|
||||
let (policy, overrides, home, roots) = {
|
||||
let shared = &self.shared;
|
||||
let mut policy = shared.memory_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
let (overrides, task_root) = {
|
||||
let s = self.state.lock();
|
||||
(s.task.memory_overrides.as_deref().cloned(), s.task.project_root.as_ref().map(|p| p.0.clone()))
|
||||
};
|
||||
let mut roots = Vec::new();
|
||||
if let Some(tr) = task_root {
|
||||
roots.push(tr);
|
||||
}
|
||||
roots.extend(policy.workspace_roots.iter().cloned());
|
||||
roots.push(shared.paths.project_root.clone());
|
||||
policy.workspace_roots = roots.clone();
|
||||
(policy, overrides, shared.paths.home_dir.clone(), roots)
|
||||
};
|
||||
let farm = memory::farm_dir(&self.shared.paths.store_dir, &self.id);
|
||||
let out_cwd = cwd.to_path_buf();
|
||||
let provider = provider.to_owned();
|
||||
match blocking(move || {
|
||||
let entries = memory::discover_memories(&roots, home.as_deref());
|
||||
let states = memory::resolve_entries(entries, overrides.as_ref(), &policy);
|
||||
let (auto_mode, _) = memory::resolve_provider_auto_memory(&provider, overrides.as_ref(), &policy);
|
||||
memory::stage(&farm, &provider, &states, auto_mode, &out_cwd, home.as_deref())
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(delivery) => Some(delivery),
|
||||
Err(e) => {
|
||||
tracing::warn!("agent task {}: staging its memory failed: {e}", self.id);
|
||||
None
|
||||
}
|
||||
/// Resolves the session's auto-memory delivery (`_meta.openidea.memory`) for native drivers
|
||||
/// that enforce it (`claude`, `codex`).
|
||||
fn memory_delivery(&self, driver: provider::Driver, provider: &str) -> Option<memory::Delivery> {
|
||||
let driver_key = stage_key(driver);
|
||||
if !matches!(driver_key, "claude" | "codex") {
|
||||
return None;
|
||||
}
|
||||
let policy = self.shared.memory_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
let overrides = self.state.lock().task.memory_overrides.as_deref().cloned();
|
||||
let (auto_mode, _) = memory::resolve_provider_auto_memory(provider, overrides.as_ref(), &policy);
|
||||
memory::build_delivery(driver_key, auto_mode)
|
||||
}
|
||||
|
||||
/// A task whose conversation is at hand (a new task, a copy).
|
||||
@@ -5070,6 +5038,8 @@ impl Task {
|
||||
/// Drops an idle resumable live session so the next turn reloads it.
|
||||
fn recycle_resumable_session(&self) {
|
||||
self.mcp_reload_pending.store(false, Ordering::Release);
|
||||
self.skills_reload_pending.store(false, Ordering::Release);
|
||||
self.memory_reload_pending.store(false, Ordering::Release);
|
||||
let live = {
|
||||
let mut live = self.live.lock();
|
||||
if live.as_ref().is_some_and(|l| l.resumable && !l.peer.is_closed()) { live.take() } else { None }
|
||||
@@ -5678,25 +5648,13 @@ impl Task {
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
return Err(SessionOpenError { message: "The agent manager shut down.".into(), allow_acp_fallback: false });
|
||||
}
|
||||
let memory_delivery = self.stage_memory(provider_id, cwd).await;
|
||||
let memory_delivery = self.memory_delivery(spec.driver, provider_id);
|
||||
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
|
||||
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
|
||||
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
|
||||
spec.args.push("--disable-mcp-server".into());
|
||||
spec.args.push(name);
|
||||
}
|
||||
if let Some(mem) = memory_delivery.as_ref() {
|
||||
if mem.copilot_enable_memory == Some(true) {
|
||||
spec.args.push("--enable-memory".into());
|
||||
}
|
||||
if mem.copilot_exclude_store_memory {
|
||||
spec.args.push("--excluded-tools".into());
|
||||
spec.args.push("store_memory".into());
|
||||
}
|
||||
if mem.copilot_disable_custom_instructions {
|
||||
spec.args.push("--no-custom-instructions".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.stderr.lock().clear();
|
||||
self.config_sent.lock().clear();
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
//! 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.
|
||||
//! Unified Agent Rules & Memory hub: discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across coding agents (`claude`, `codex`,
|
||||
//! `copilot`, `cursor`, `gemini`, `hermes`, and custom ACP agents), deduplicates symlinks
|
||||
//! and `@AGENTS.md` wrapper imports, resolves per-provider auto-memory policies under
|
||||
//! Workspace Trust, and builds native per-session `_meta.openidea.memory` payloads only
|
||||
//! for drivers that enforce them (`claude`, `codex`).
|
||||
|
||||
use crate::{
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryEntryPolicy,
|
||||
AgentMemoryKind, AgentMemoryMode, AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource,
|
||||
AgentMemoryState, AutoMemoryMode, CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryKind,
|
||||
AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource, AutoMemoryMode,
|
||||
CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
};
|
||||
use ide_core::output_encoding::strip_ansi;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -21,7 +21,11 @@ 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 CLAUDE_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
const CODEX_AUTO_MODES: &[AutoMemoryMode] =
|
||||
&[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::ReadOnly, AutoMemoryMode::Off];
|
||||
const HERMES_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
|
||||
const SKIP_MONOREPO_DIRS: &[&str] =
|
||||
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
|
||||
@@ -46,56 +50,43 @@ impl Default for MemoryPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-session memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory`.
|
||||
/// Per-session auto-memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory` for native drivers that enforce it (`claude`, `codex`).
|
||||
#[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
|
||||
/// Normalizes a provider id to its auto-memory policy key.
|
||||
/// Native `claude` and `codex` keep their exact ids (distinct from `claude-acp` / `codex-acp`,
|
||||
/// whose external ACP adapters do not consume `_meta.openidea.memory`); Hermes profiles collapse
|
||||
/// onto `"hermes"`.
|
||||
pub fn provider_key(provider: &str) -> &str {
|
||||
let trimmed = provider.trim();
|
||||
if trimmed == "hermes" || trimmed.starts_with("hermes-") { "hermes" } else { trimmed }
|
||||
}
|
||||
|
||||
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;
|
||||
/// Auto-memory modes enforced by `provider`. Empty means the agent manages auto-memory itself.
|
||||
pub fn supported_auto_memory_modes(provider: &str) -> &'static [AutoMemoryMode] {
|
||||
match provider_key(provider) {
|
||||
"claude" => CLAUDE_AUTO_MODES,
|
||||
"codex" => CODEX_AUTO_MODES,
|
||||
"hermes" => HERMES_AUTO_MODES,
|
||||
_ => &[],
|
||||
}
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
||||
/// True when `provider`'s auto-memory mode is persisted directly in its own native config file
|
||||
/// (e.g. `~/.hermes/config.yaml`) rather than per-project settings or per-session overrides.
|
||||
pub fn is_native_config_auto_memory(provider: &str) -> bool {
|
||||
provider_key(provider) == "hermes"
|
||||
}
|
||||
|
||||
fn source_key(source: AgentMemorySource) -> &'static str {
|
||||
@@ -473,7 +464,7 @@ pub fn discover_memories_with_plugins(
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (discovered entries + per-provider auto-memory statuses)
|
||||
/// against `policy` and optional per-session `session_overrides`.
|
||||
pub fn resolve_catalog(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
@@ -481,105 +472,45 @@ pub fn resolve_catalog(
|
||||
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 }
|
||||
let providers = build_provider_statuses(&entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries, providers, workspace_trusted: policy.workspace_trusted }
|
||||
}
|
||||
|
||||
/// 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.).
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` that supports OpenIDEA-managed
|
||||
/// settings/session overrides (`claude`, `codex`).
|
||||
/// Precedence: `Session Override > Workspace Settings (when trusted or Off) > User Settings > Inherit`.
|
||||
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) {
|
||||
let supported = supported_auto_memory_modes(provider);
|
||||
if supported.is_empty() || is_native_config_auto_memory(provider) {
|
||||
return (AutoMemoryMode::Inherit, AgentMemoryOrigin::None);
|
||||
}
|
||||
let accepts = |mode: AutoMemoryMode| mode != AutoMemoryMode::Inherit && supported.contains(&mode);
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory)
|
||||
&& accepts(mode)
|
||||
{
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let key = normalize_provider_id(provider);
|
||||
let key = provider_key(provider);
|
||||
if let Some(ws_prov) = policy.workspace.providers.get(key)
|
||||
&& ws_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
&& accepts(ws_prov.auto_memory)
|
||||
&& (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
|
||||
&& accepts(user_prov.auto_memory)
|
||||
{
|
||||
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],
|
||||
entries: &[AgentMemoryEntry],
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
@@ -587,11 +518,9 @@ fn build_provider_statuses(
|
||||
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) {
|
||||
for e in entries.iter().filter(|e| e.source == src) {
|
||||
count += 1;
|
||||
if s.mode != AgentMemoryMode::Off {
|
||||
tokens = tokens.saturating_add(s.entry.approx_tokens);
|
||||
}
|
||||
tokens = tokens.saturating_add(e.approx_tokens);
|
||||
}
|
||||
(count, tokens)
|
||||
};
|
||||
@@ -614,19 +543,12 @@ fn build_provider_statuses(
|
||||
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);
|
||||
let (hermes_mode, hermes_origin) = match hermes_root(home).and_then(|root| read_hermes_config_memory_mode(&root)) {
|
||||
Some(cfg_mode) => (cfg_mode, AgentMemoryOrigin::Native),
|
||||
None => (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native),
|
||||
};
|
||||
|
||||
vec![
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -634,12 +556,12 @@ fn build_provider_statuses(
|
||||
label: "Claude Code".into(),
|
||||
mode: claude_mode,
|
||||
origin: claude_origin,
|
||||
supported_modes: CLAUDE_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
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 {
|
||||
@@ -647,295 +569,81 @@ fn build_provider_statuses(
|
||||
label: "Codex".into(),
|
||||
mode: codex_mode,
|
||||
origin: codex_origin,
|
||||
supported_modes: CODEX_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
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,
|
||||
supported_modes: HERMES_AUTO_MODES.to_vec(),
|
||||
native_config_only: true,
|
||||
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)
|
||||
/// Builds the per-session [`Delivery`] payload (`_meta.openidea.memory`) for a native driver
|
||||
/// (`"claude"` or `"codex"`). Returns `None` when `auto_memory` is `Inherit` or the driver
|
||||
/// does not consume `_meta.openidea.memory`.
|
||||
pub fn build_delivery(driver_key: &str, auto_memory: AutoMemoryMode) -> Option<Delivery> {
|
||||
if auto_memory == AutoMemoryMode::Inherit {
|
||||
return None;
|
||||
}
|
||||
match driver_key {
|
||||
"claude" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(true), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(false), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Inherit | AutoMemoryMode::ReadOnly => None,
|
||||
},
|
||||
"codex" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(true),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::ReadOnly => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Off => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(false),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Inherit => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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),
|
||||
_ => {}
|
||||
/// Explicitly updates Hermes's native `config.yaml` (`memory_enabled` and `user_profile_enabled`).
|
||||
/// Never called during session startup — only when the user changes Hermes's setting directly.
|
||||
pub fn set_hermes_auto_memory(provider: &str, mode: AutoMemoryMode, home: Option<&Path>) -> Result<(), String> {
|
||||
if !matches!(mode, AutoMemoryMode::ReadWrite | AutoMemoryMode::Off) {
|
||||
return Err("Hermes auto-memory supports only On (readWrite) or Off".into());
|
||||
}
|
||||
|
||||
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()
|
||||
let root = hermes_root(home).ok_or("Home directory is unavailable")?;
|
||||
let prof_home = hermes::profile_home(&root, provider).unwrap_or(root);
|
||||
write_hermes_config_memory_mode(&prof_home, mode).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ─── File Operations: Create, Promote, Delete & Reset ───────────────────────────────
|
||||
@@ -1064,9 +772,7 @@ pub fn promote_memory(
|
||||
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()
|
||||
);
|
||||
return Err("Curated instruction and rule files cannot be deleted here; open the file in the editor.".into());
|
||||
}
|
||||
match std::fs::remove_file(&entry.path.0) {
|
||||
Ok(()) => Ok(()),
|
||||
@@ -1079,7 +785,7 @@ pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), Strin
|
||||
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) {
|
||||
match provider_key(provider) {
|
||||
"claude" => {
|
||||
for dir in claude_auto_memory_dirs(&home.join(".claude"), home, workspaces) {
|
||||
for f in markdown_files(&dir, 2) {
|
||||
@@ -1134,19 +840,6 @@ fn validate_slug(raw: &str) -> Result<String, String> {
|
||||
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,
|
||||
@@ -1201,17 +894,6 @@ fn format_cursor_mdc(description: Option<&str>, globs: &[String], always_apply:
|
||||
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();
|
||||
@@ -1899,111 +1581,112 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_resolution_enforces_workspace_trust_and_precedence() {
|
||||
fn policy_resolution_enforces_workspace_trust_and_provider_capabilities() {
|
||||
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");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\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 mut ws_settings = AgentMemorySettings::default();
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("claude".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite });
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("codex".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::Off });
|
||||
|
||||
let untrusted = MemoryPolicy {
|
||||
user: AgentMemorySettings::default(),
|
||||
workspace: ws_settings.clone(),
|
||||
workspace: ws_settings,
|
||||
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);
|
||||
assert!(!cat.workspace_trusted);
|
||||
// Untrusted workspace cannot enable Claude auto-memory, but can turn Codex auto-memory off.
|
||||
let claude = cat.providers.iter().find(|p| p.provider == "claude").unwrap();
|
||||
assert_eq!((claude.mode, claude.origin), (AutoMemoryMode::Inherit, AgentMemoryOrigin::None));
|
||||
assert_eq!(claude.supported_modes, [AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off]);
|
||||
let codex = cat.providers.iter().find(|p| p.provider == "codex").unwrap();
|
||||
assert_eq!((codex.mode, codex.origin), (AutoMemoryMode::Off, AgentMemoryOrigin::Workspace));
|
||||
let hermes = cat.providers.iter().find(|p| p.provider == "hermes").unwrap();
|
||||
assert!(hermes.native_config_only);
|
||||
assert_eq!((hermes.mode, hermes.origin), (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native));
|
||||
|
||||
// Session override wins in a trusted workspace
|
||||
// Session override wins in a trusted workspace, and unsupported modes are ignored.
|
||||
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));
|
||||
let session_ro = AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) };
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("claude", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Workspace)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("codex", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session)
|
||||
);
|
||||
// External ACP adapters and unsupported providers never report OpenIDEA auto-memory control.
|
||||
assert!(supported_auto_memory_modes("claude-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("codex-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("copilot").is_empty());
|
||||
assert!(supported_auto_memory_modes("cursor").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stages_per_driver_delivery_for_claude_codex_copilot_and_hermes() {
|
||||
fn builds_delivery_only_for_native_claude_and_codex_and_keeps_hermes_explicit() {
|
||||
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));
|
||||
// Claude: Inherit -> None, ReadWrite -> true, Off -> false, ReadOnly -> None
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Inherit), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadOnly), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadWrite).unwrap().claude_auto_memory, Some(true));
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Off).unwrap().claude_auto_memory, Some(false));
|
||||
|
||||
// 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"),
|
||||
// Codex: ReadWrite / ReadOnly / Off
|
||||
assert_eq!(build_delivery("codex", AutoMemoryMode::Inherit), None);
|
||||
let codex_ro = build_delivery("codex", AutoMemoryMode::ReadOnly).unwrap();
|
||||
assert_eq!(codex_ro.codex_use_memories, Some(true));
|
||||
assert_eq!(codex_ro.codex_generate_memories, Some(false));
|
||||
let codex_off = build_delivery("codex", AutoMemoryMode::Off).unwrap();
|
||||
assert_eq!(codex_off.codex_use_memories, Some(false));
|
||||
assert_eq!(codex_off.codex_generate_memories, Some(false));
|
||||
|
||||
// Copilot, ACP, Hermes produce no session delivery and never touch Hermes config.yaml
|
||||
assert_eq!(build_delivery("copilot", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("acp", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("hermes", AutoMemoryMode::Off), None);
|
||||
assert!(!home.join(".hermes/config.yaml").exists());
|
||||
|
||||
// Explicit Hermes toggle updates config.yaml directly and rejects unsupported modes
|
||||
assert!(set_hermes_auto_memory("hermes", AutoMemoryMode::ReadOnly, Some(&home)).is_err());
|
||||
set_hermes_auto_memory("hermes", AutoMemoryMode::Off, Some(&home)).unwrap();
|
||||
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_and_overrides_deserialize_cleanly() {
|
||||
let legacy_settings: AgentMemorySettings = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "readOnly",
|
||||
"providers": { "codex": { "autoMemory": "off" } },
|
||||
"entries": { "workspace::AGENTS.md": { "mode": "off" } }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(staged_rule, "Use async IPC for disk ops.\n");
|
||||
assert!(farm.join(".claude/rules/geminiuser-gemini-md.md").is_file());
|
||||
assert_eq!(legacy_settings.providers["codex"].auto_memory, AutoMemoryMode::Off);
|
||||
|
||||
// 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));
|
||||
let legacy_overrides: AgentMemoryOverrides = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "off",
|
||||
"entries": { "workspace::AGENTS.md": "off" }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(legacy_overrides.auto_memory, Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1107,8 +1107,8 @@ fn default_true() -> bool {
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
|
||||
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
|
||||
AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
@@ -1174,7 +1174,7 @@ impl AgentMemorySource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
|
||||
/// Which layer decided a provider's effective [`AutoMemoryMode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryOrigin {
|
||||
@@ -1183,8 +1183,8 @@ pub enum AgentMemoryOrigin {
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
/// Configured directly in the agent's own native config file (e.g. `~/.hermes/config.yaml`).
|
||||
Native,
|
||||
}
|
||||
|
||||
/// One discovered instruction file, rule file, or learned auto-memory note.
|
||||
@@ -1231,18 +1231,6 @@ pub struct AgentMemoryEntry {
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryState {
|
||||
pub entry: AgentMemoryEntry,
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
}
|
||||
|
||||
/// Live auto-memory status and capability summary for one agent family.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1251,41 +1239,43 @@ pub struct AgentAutoMemoryStatus {
|
||||
pub label: String,
|
||||
pub mode: AutoMemoryMode,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
/// Auto-memory modes this provider enforces (empty when the agent manages auto-memory itself).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub supported_modes: Vec<AutoMemoryMode>,
|
||||
/// True when changing the mode edits the agent's own global config (e.g. `~/.hermes/config.yaml`)
|
||||
/// rather than a project or per-session override.
|
||||
#[serde(default)]
|
||||
pub native_config_only: bool,
|
||||
pub note_count: u32,
|
||||
pub rollout_count: u32,
|
||||
pub approx_tokens: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub storage_path: Option<IpcPath>,
|
||||
pub supports_auto_control: bool,
|
||||
pub supports_file_exclusion: bool,
|
||||
pub supports_reset: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
|
||||
/// Full catalog returned to Settings › Agents › Rules & Memory and the Composer `MemoryPicker`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryCatalog {
|
||||
pub entries: Vec<AgentMemoryState>,
|
||||
pub entries: Vec<AgentMemoryEntry>,
|
||||
pub providers: Vec<AgentAutoMemoryStatus>,
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
pub auto_memory_origin: AgentMemoryOrigin,
|
||||
pub workspace_trusted: bool,
|
||||
}
|
||||
|
||||
/// Per-session memory overrides stored on an [`AgentTask`].
|
||||
/// Per-session auto-memory override stored on an [`AgentTask`] or automation.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryOverrides {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub auto_memory: Option<AutoMemoryMode>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub entries: BTreeMap<String, AgentMemoryMode>,
|
||||
}
|
||||
|
||||
impl AgentMemoryOverrides {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.auto_memory.is_none() && self.entries.is_empty()
|
||||
self.auto_memory.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -174,13 +174,9 @@ struct Session {
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
|
||||
memory_add_dir: Option<PathBuf>,
|
||||
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
|
||||
additional_dirs_claude_md: bool,
|
||||
/// The workspace's other roots, each passed as `--add-dir`.
|
||||
additional_dirs: Vec<String>,
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`).
|
||||
cli_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
@@ -400,11 +396,6 @@ impl Shim {
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs_claude_md: memory
|
||||
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
additional_dirs: additional_dirs(params),
|
||||
cli_settings,
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
@@ -774,11 +765,6 @@ impl Session {
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if let Some(dir) = &self.memory_add_dir
|
||||
&& self.skills_add_dir.as_ref() != Some(dir)
|
||||
{
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
for dir in &self.additional_dirs {
|
||||
args.extend(["--add-dir".to_owned(), dir.clone()]);
|
||||
}
|
||||
@@ -789,12 +775,7 @@ impl Session {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let mut env = shim.config.env.clone();
|
||||
if self.additional_dirs_claude_md
|
||||
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
|
||||
{
|
||||
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
|
||||
}
|
||||
let env = shim.config.env.clone();
|
||||
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
|
||||
let io = shim
|
||||
.cli
|
||||
@@ -1657,8 +1638,8 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
|
||||
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with
|
||||
/// `autoMemoryEnabled` from `_meta.openidea.memory` into one `--settings` JSON.
|
||||
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
|
||||
let mut root = skills
|
||||
.and_then(|s| s.get("claudeSettings"))
|
||||
@@ -1666,27 +1647,8 @@ fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<
|
||||
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(mem) = memory {
|
||||
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
|
||||
let clean: Vec<Value> =
|
||||
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
|
||||
if !clean.is_empty() {
|
||||
root.insert("claudeMdExcludes".into(), Value::Array(clean));
|
||||
}
|
||||
}
|
||||
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
root.insert(
|
||||
"pluginConfigs".into(),
|
||||
json!({
|
||||
"cc-plugin-agents-md@builtin": {
|
||||
"options": { "instructionFiles": inst }
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(auto) = memory.and_then(|m| m.get("claudeAutoMemory")).and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
|
||||
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
|
||||
|
||||
@@ -1553,7 +1553,7 @@ async fn an_ephemeral_session_is_not_saved() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
|
||||
async fn session_merges_skills_and_auto_memory_into_claude_settings() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
@@ -1569,45 +1569,8 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
|
||||
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
|
||||
},
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"claudeAutoMemory": false,
|
||||
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md",
|
||||
"claudeAddDir": "/tmp/farm-memory",
|
||||
"claudeAdditionalDirsClaudeMd": true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md"
|
||||
"autoMemory": "off",
|
||||
"claudeAutoMemory": false
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
}
|
||||
@@ -1615,12 +1578,12 @@ async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_inje
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
|
||||
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
assert!(parsed["pluginConfigs"]["azure"].is_null());
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert!(parsed.get("claudeMdExcludes").is_none());
|
||||
assert!(parsed.get("pluginConfigs").is_none());
|
||||
}
|
||||
@@ -385,18 +385,25 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
if let Some(mem) = params.pointer("/_meta/openidea/memory")
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
let use_m = mem.get("codexUseMemories").and_then(Value::as_bool);
|
||||
let gen_m = mem.get("codexGenerateMemories").and_then(Value::as_bool);
|
||||
let mut mem_cfg = serde_json::Map::new();
|
||||
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("use_memories".into(), json!(use_m));
|
||||
if let Some(v) = use_m {
|
||||
mem_cfg.insert("use_memories".into(), json!(v));
|
||||
}
|
||||
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("generate_memories".into(), json!(gen_m));
|
||||
if let Some(v) = gen_m {
|
||||
mem_cfg.insert("generate_memories".into(), json!(v));
|
||||
}
|
||||
if !mem_cfg.is_empty() {
|
||||
map.insert("memories".into(), Value::Object(mem_cfg));
|
||||
}
|
||||
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
map.insert("developer_instructions".into(), json!(dev));
|
||||
// Codex's `memories` feature flag defaults to `false`; turn it on whenever the user
|
||||
// explicitly asks to read or generate memories.
|
||||
if use_m == Some(true) || gen_m == Some(true) {
|
||||
let features = map.entry("features".to_owned()).or_insert_with(|| Value::Object(serde_json::Map::new()));
|
||||
if let Some(f) = features.as_object_mut() {
|
||||
f.insert("memories".into(), json!(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
|
||||
@@ -2226,8 +2226,7 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
|
||||
"memory": {
|
||||
"codexUseMemories": true,
|
||||
"codexGenerateMemories": false,
|
||||
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2235,8 +2234,27 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
&mut mem_req,
|
||||
);
|
||||
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
|
||||
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
|
||||
assert_eq!(mem_req["config"]["features"]["memories"], true);
|
||||
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
|
||||
|
||||
let mut off_req = json!({});
|
||||
apply_thread_config(
|
||||
&json!({
|
||||
"cwd": "/w/api",
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"codexUseMemories": false,
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
&mut off_req,
|
||||
);
|
||||
assert_eq!(off_req["config"]["memories"], json!({ "use_memories": false, "generate_memories": false }));
|
||||
assert!(off_req["config"].get("features").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -471,38 +471,6 @@ fn apply_skills(params: &Value, req: &mut Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
|
||||
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
|
||||
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
|
||||
fn apply_memory(params: &Value, req: &mut Value) {
|
||||
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
|
||||
return;
|
||||
};
|
||||
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
|
||||
let mut excluded: Vec<String> = req
|
||||
.get("excludedTools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if !excluded.iter().any(|t| t == "store_memory") {
|
||||
excluded.push("store_memory".into());
|
||||
}
|
||||
req["excludedTools"] = json!(excluded);
|
||||
}
|
||||
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
|
||||
req["customInstructions"] = json!(false);
|
||||
}
|
||||
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
req["systemMessage"] = json!({
|
||||
"mode": "append",
|
||||
"content": sys,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
error(codes::INVALID_PARAMS, message)
|
||||
}
|
||||
@@ -630,7 +598,6 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -701,7 +668,6 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
|
||||
|
||||
@@ -953,56 +953,6 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let meta = json!({
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"copilotExcludeStoreMemory": true,
|
||||
"copilotDisableCustomInstructions": true,
|
||||
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
|
||||
}
|
||||
}
|
||||
});
|
||||
let _: Value =
|
||||
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
for method in ["session.create", "session.resume"] {
|
||||
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
|
||||
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
|
||||
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
|
||||
assert_eq!(
|
||||
params["systemMessage"],
|
||||
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
|
||||
"{method}: {params}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_context_attribution_without_double_counting_parent_rollups() {
|
||||
let payload = json!({
|
||||
|
||||
@@ -6592,25 +6592,28 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cursor_and_hermes() {
|
||||
async fn per_session_memory_overrides_deliver_only_for_native_claude_and_codex() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::write(root.join("AGENTS.md"), "# Workspace Rules\nRun vitest first.\n").unwrap();
|
||||
std::fs::write(root.join("CLAUDE.local.md"), "Noisy local draft\n").unwrap();
|
||||
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(root, agent.clone());
|
||||
mgr.set_memory_policy_hook(Box::new({
|
||||
let root = root.to_path_buf();
|
||||
move || memory::MemoryPolicy {
|
||||
user: AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() },
|
||||
user: AgentMemorySettings {
|
||||
providers: BTreeMap::from([
|
||||
("claude".into(), AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite }),
|
||||
("codex".into(), AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite }),
|
||||
]),
|
||||
},
|
||||
workspace: AgentMemorySettings::default(),
|
||||
workspace_trusted: true,
|
||||
workspace_roots: vec![root.clone()],
|
||||
}
|
||||
}));
|
||||
|
||||
// 1. Claude task with initial `ReadOnly` + muted `CLAUDE.local.md`, then updated while idle, forked, and deleted.
|
||||
// 1. Native Claude task with initial `Off`, then updated while idle, then forked.
|
||||
let claude_task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -6621,10 +6624,7 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
memory_overrides: Some(AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off)]),
|
||||
}),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
@@ -6635,51 +6635,63 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/new");
|
||||
let mem = payload.unwrap();
|
||||
assert_eq!(mem["autoMemory"], "readOnly");
|
||||
assert_eq!(mem["autoMemory"], "off");
|
||||
assert_eq!(mem["claudeAutoMemory"], false);
|
||||
assert!(
|
||||
mem["claudeMdExcludes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|v| v.as_str().is_some_and(|s| s.ends_with("CLAUDE.local.md")))
|
||||
);
|
||||
}
|
||||
|
||||
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `Off`.
|
||||
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `ReadWrite`.
|
||||
let updated = mgr
|
||||
.set_memory_overrides(
|
||||
&claude_task.id,
|
||||
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
|
||||
)
|
||||
.set_memory_overrides(&claude_task.id, AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadWrite) })
|
||||
.unwrap();
|
||||
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
|
||||
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::ReadWrite));
|
||||
mgr.prompt(&claude_task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
|
||||
{
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/load");
|
||||
assert_eq!(payload.unwrap()["autoMemory"], "off");
|
||||
let mem = payload.unwrap();
|
||||
assert_eq!(mem["autoMemory"], "readWrite");
|
||||
assert_eq!(mem["claudeAutoMemory"], true);
|
||||
}
|
||||
|
||||
// Forking carries `memory_overrides` onto the forked task and sends `_meta.openidea.memory` on `session/fork`.
|
||||
let forked = mgr.fork(&claude_task.id, None).await.unwrap();
|
||||
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
|
||||
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::ReadWrite));
|
||||
{
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/fork");
|
||||
assert_eq!(payload.unwrap()["autoMemory"], "off");
|
||||
assert_eq!(payload.unwrap()["autoMemory"], "readWrite");
|
||||
}
|
||||
mgr.delete(&claude_task.id, false).await.unwrap();
|
||||
assert!(!memory::farm_dir(&mgr.shared.paths.store_dir, &claude_task.id).exists());
|
||||
|
||||
// 2. Codex, Copilot, Cursor (ACP), and Hermes (ACP) each receive their normalized `_meta.openidea.memory`.
|
||||
for (provider, expected_field) in [
|
||||
("codex", Some("codexUseMemories")),
|
||||
("copilot", Some("copilotEnableMemory")),
|
||||
("cursor", None),
|
||||
("hermes", None),
|
||||
] {
|
||||
// 2. Native Codex delivers `codexUseMemories` / `codexGenerateMemories`.
|
||||
let codex_task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "codex".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &codex_task.id, AgentStatus::Ready).await;
|
||||
{
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/new");
|
||||
let mem = payload.unwrap();
|
||||
assert_eq!(mem["autoMemory"], "readOnly");
|
||||
assert_eq!(mem["codexUseMemories"], true);
|
||||
assert_eq!(mem["codexGenerateMemories"], false);
|
||||
}
|
||||
|
||||
// 3. ACP and non-native providers (copilot, cursor, hermes, claude-acp) receive NO `_meta.openidea.memory`.
|
||||
for provider in ["copilot", "cursor", "hermes", "claude-acp"] {
|
||||
let t = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -6690,10 +6702,7 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
memory_overrides: Some(AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::new(),
|
||||
}),
|
||||
memory_overrides: Some(AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }),
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
})
|
||||
@@ -6702,11 +6711,7 @@ async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cu
|
||||
wait_for(&mgr, &t.id, AgentStatus::Ready).await;
|
||||
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
|
||||
assert_eq!(method, "session/new", "provider {provider}");
|
||||
let mem = payload.expect("memory delivery present");
|
||||
assert_eq!(mem["autoMemory"], "readOnly", "provider {provider}");
|
||||
if let Some(field) = expected_field {
|
||||
assert!(mem.get(field).is_some(), "provider {provider} missing {field}: {mem}");
|
||||
}
|
||||
assert!(payload.is_none(), "provider {provider} should not receive memory delivery: {payload:?}");
|
||||
}
|
||||
|
||||
mgr.shutdown();
|
||||
@@ -7620,12 +7625,8 @@ async fn metadata_edits_do_not_bump_updated_ms() {
|
||||
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
|
||||
assert_eq!(after_skill.updated_ms, fixed_ms);
|
||||
|
||||
let after_memory = mgr
|
||||
.set_memory_overrides(
|
||||
&task.id,
|
||||
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
|
||||
)
|
||||
.unwrap();
|
||||
let after_memory =
|
||||
mgr.set_memory_overrides(&task.id, AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off) }).unwrap();
|
||||
assert_eq!(after_memory.updated_ms, fixed_ms);
|
||||
}
|
||||
|
||||
|
||||
@@ -312,20 +312,7 @@ impl Default for AgentSkillPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryMode {
|
||||
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
|
||||
#[default]
|
||||
Auto,
|
||||
/// Force-load into every session regardless of path scoping.
|
||||
Always,
|
||||
/// Exclude from sessions where the harness supports it.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutoMemoryMode {
|
||||
@@ -340,24 +327,6 @@ pub enum AutoMemoryMode {
|
||||
Off,
|
||||
}
|
||||
|
||||
/// One memory or instruction entry's policy in Settings › Agents › Memory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryEntryPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemoryMode)]
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Agent provider ids this entry applies to; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMemoryEntryPolicy {
|
||||
fn default() -> Self {
|
||||
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -371,18 +340,10 @@ pub struct AgentProviderMemoryPolicy {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemorySettings {
|
||||
/// Default cross-session auto-memory policy across agents.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutoMemoryMode)]
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
/// Per-provider cross-session auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
|
||||
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
|
||||
/// Per-entry modes (`[agents.memory.entries.<id>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// One agent plugin bundle's policy in Settings › Agents › Plugins
|
||||
|
||||
@@ -7,12 +7,12 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView,
|
||||
AgentCliInstallResult, AgentCliOffer, AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry,
|
||||
AgentEvent, AgentLoginEvent, AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy,
|
||||
AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog,
|
||||
AgentPluginPreview, AgentPluginSettings, AgentProbe, AgentPrompt, AgentProvider, AgentProviderMemoryPolicy,
|
||||
AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode,
|
||||
AutomationRun, AutomationRunsPage, AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus,
|
||||
CreateAgentMemoryInput, CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
|
||||
AgentEvent, AgentLoginEvent, AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryOverrides,
|
||||
AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog, AgentPluginPreview, AgentPluginSettings, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
|
||||
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage,
|
||||
AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput,
|
||||
CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
|
||||
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult,
|
||||
McpRegistryPage, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
|
||||
@@ -1773,7 +1773,7 @@ fn memory_settings_layers(
|
||||
}
|
||||
|
||||
fn is_default_memory_settings(s: &AgentMemorySettings) -> bool {
|
||||
s.auto_memory == AutoMemoryMode::Inherit && s.providers.is_empty() && s.entries.is_empty()
|
||||
s.providers.is_empty()
|
||||
}
|
||||
|
||||
fn persist_memory_settings(
|
||||
@@ -1834,82 +1834,51 @@ pub async fn agent_memory_list(host: &Host, window: &str) -> IdeResult<AgentMemo
|
||||
current_memory_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Sets how memory entry `id` runs in `scope` (`settings.toml` vs `.openidea/settings.toml`),
|
||||
/// never modifying the file on disk.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_memory_set_mode(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
scope: McpScope,
|
||||
mode: AgentMemoryMode,
|
||||
agents: Vec<String>,
|
||||
) -> IdeResult<AgentMemoryCatalog> {
|
||||
let id = id.trim().to_owned();
|
||||
if id.is_empty() {
|
||||
return Err(IdeError::invalid("a memory entry needs an id"));
|
||||
}
|
||||
let clean_agents: Vec<String> = agents.into_iter().map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()).collect();
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
|
||||
let apply = |layer: &mut AgentMemorySettings| -> bool {
|
||||
if mode == AgentMemoryMode::Auto && clean_agents.is_empty() {
|
||||
layer.entries.remove(&id).is_some()
|
||||
} else {
|
||||
let next = AgentMemoryEntryPolicy { mode, agents: clean_agents.clone() };
|
||||
layer.entries.insert(id.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
};
|
||||
match scope {
|
||||
McpScope::User => {
|
||||
if apply(&mut user) {
|
||||
persist_memory_settings(host, None, scope, &user)?;
|
||||
}
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let ws =
|
||||
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
|
||||
if apply(ws) {
|
||||
let updated = ws.clone();
|
||||
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
current_memory_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Sets the cross-session auto-memory policy (`Inherit`, `ReadWrite`, `ReadOnly`, `Off`)
|
||||
/// globally or for one `provider` in `scope`.
|
||||
/// Sets the cross-session auto-memory policy for one `provider` in `scope`.
|
||||
/// For native-config providers (Hermes), writes the agent's own config file directly.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_memory_set_auto(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
scope: McpScope,
|
||||
provider: Option<String>,
|
||||
provider: String,
|
||||
mode: AutoMemoryMode,
|
||||
) -> IdeResult<AgentMemoryCatalog> {
|
||||
let raw_provider = provider.trim();
|
||||
if raw_provider.is_empty() {
|
||||
return Err(IdeError::invalid("a provider id is required to configure auto-memory"));
|
||||
}
|
||||
let supported = ide_agent::memory::supported_auto_memory_modes(raw_provider);
|
||||
if supported.is_empty() {
|
||||
return Err(IdeError::invalid(format!("Auto-memory control is not supported for `{raw_provider}`")));
|
||||
}
|
||||
if !supported.contains(&mode) {
|
||||
return Err(IdeError::invalid(format!("Auto-memory mode `{mode:?}` is not supported for `{raw_provider}`")));
|
||||
}
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
|
||||
if ide_agent::memory::is_native_config_auto_memory(raw_provider) {
|
||||
let provider_owned = raw_provider.to_owned();
|
||||
let home = host.home_dir();
|
||||
blocking(move || {
|
||||
ide_agent::memory::set_hermes_auto_memory(&provider_owned, mode, home.as_deref()).map_err(IdeError::invalid)
|
||||
})
|
||||
.await?;
|
||||
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
|
||||
for p in host.projects() {
|
||||
p.sink.emit(event.clone());
|
||||
}
|
||||
return current_memory_catalog(host, project.as_deref()).await;
|
||||
}
|
||||
|
||||
let key = ide_agent::memory::provider_key(raw_provider).to_owned();
|
||||
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
|
||||
let prov_key = provider
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| ide_agent::memory::normalize_provider_id(s).to_owned());
|
||||
let apply = |layer: &mut AgentMemorySettings| -> bool {
|
||||
match &prov_key {
|
||||
None => {
|
||||
let changed = layer.auto_memory != mode;
|
||||
layer.auto_memory = mode;
|
||||
changed
|
||||
}
|
||||
Some(key) => {
|
||||
if mode == AutoMemoryMode::Inherit {
|
||||
layer.providers.remove(key).is_some()
|
||||
} else {
|
||||
let next = AgentProviderMemoryPolicy { auto_memory: mode };
|
||||
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
}
|
||||
if mode == AutoMemoryMode::Inherit {
|
||||
layer.providers.remove(&key).is_some()
|
||||
} else {
|
||||
let next = AgentProviderMemoryPolicy { auto_memory: mode };
|
||||
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
|
||||
}
|
||||
};
|
||||
match scope {
|
||||
@@ -2946,7 +2915,6 @@ ide_command::domain!(
|
||||
agent_memory_promote,
|
||||
agent_memory_reset_provider,
|
||||
agent_memory_set_auto,
|
||||
agent_memory_set_mode,
|
||||
agent_plugins_add_marketplace,
|
||||
agent_plugins_browse_marketplace,
|
||||
agent_plugins_install,
|
||||
|
||||
@@ -2480,7 +2480,7 @@ async fn agent_plugins_ipc_installs_for_a_harness_and_projects_native_children()
|
||||
assert!(cloud_mcp.args.iter().any(|a| a == "--region=us-west-2"));
|
||||
|
||||
let mems = ide_host::ops::agent::agent_memory_list(&h.host, "main").await.unwrap();
|
||||
assert!(mems.entries.iter().any(|e| e.entry.plugin_id.as_deref() == Some(plug_id.as_str())));
|
||||
assert!(mems.entries.iter().any(|e| e.plugin_id.as_deref() == Some(plug_id.as_str())));
|
||||
|
||||
// 3. Disabling the parent bundle atomically drops its projected skill, MCP server, and rule!
|
||||
ide_host::ops::agent::agent_plugins_set_enabled(
|
||||
@@ -2503,11 +2503,12 @@ async fn agent_plugins_ipc_installs_for_a_harness_and_projects_native_children()
|
||||
);
|
||||
assert!(!ide_host::ops::agent::agent_mcp_list(&h.host, "main").unwrap().iter().any(|m| m.name == "cloud-mcp"));
|
||||
assert!(
|
||||
!ide_host::ops::agent::agent_memory_list(&h.host, "main").await.unwrap().entries.iter().any(|e| e
|
||||
.entry
|
||||
.plugin_id
|
||||
.as_deref()
|
||||
== Some(plug_id.as_str()))
|
||||
!ide_host::ops::agent::agent_memory_list(&h.host, "main")
|
||||
.await
|
||||
.unwrap()
|
||||
.entries
|
||||
.iter()
|
||||
.any(|e| e.plugin_id.as_deref() == Some(plug_id.as_str()))
|
||||
);
|
||||
|
||||
// 4. Approving capabilities other than the ones shown is refused.
|
||||
|
||||
@@ -160,8 +160,8 @@ In the composer, `/skills` (or the **Add Context** menu) opens the per-session p
|
||||
|
||||
**Settings › Agents › Rules & Memory** brings together instruction files (`AGENTS.md`, `CLAUDE.md`, `.github/copilot-instructions.md`, `GEMINI.md`), path-scoped rules (`.claude/rules`, `.github/instructions`, `.cursor/rules`) and cross-session auto-memories (Claude Code's `~/.claude/projects/…/memory`, Codex's `~/.codex/memories`, Hermes' `MEMORY.md` and `USER.md`), deduplicating symlinks and `@AGENTS.md` wrapper imports without modifying tracked repository files.
|
||||
|
||||
- **Auto-Memory policy (`Inherit`, `Read & Write`, `Read Only`, `Off`)**: set globally or per workspace, or overridden per task in the composer's **Memory** picker (`/memory` or `/memories` in the composer, or **Memory…** in the **+** menu). **Read Only** recalls past notes without saving new ones from exploratory conversations.
|
||||
- **Per-file modes (`Auto`, `Always`, `Off`)**: `Off` keeps a file out of new sessions; `Always` also passes another agent's file to every agent (for example a Cursor rule to Claude Code).
|
||||
- **Rules & Instructions**: inspect which agent natively loads each file, spot size or unresolved `@import` warnings, create new instruction or rule files, and jump straight to the editor. Each agent loads its own native instruction files directly.
|
||||
- **Per-provider Auto-Memory**: configure cross-session auto-memory using the modes each native driver enforces — **Default / On / Off** for Claude Code, **Default / Read & Write / Read Only / Off** for Codex (saved globally, per workspace, or overridden per task in the composer's **Memory** picker via `/memory` or `/memories`), and **On / Off** for Hermes Agent (saved directly in `~/.hermes/config.yaml`). Other agents manage auto-memory in their own settings.
|
||||
- **Promote to AGENTS.md**: move a learned auto-memory note into `AGENTS.md`, under a heading of your choice, so every agent reads it.
|
||||
|
||||
### Agent plugins
|
||||
|
||||
@@ -160,8 +160,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
**设置 › 智能体 › 规则与记忆** 汇总管理指令文件(`AGENTS.md`、`CLAUDE.md`、`.github/copilot-instructions.md`、`GEMINI.md`)、按路径生效的规则(`.claude/rules`、`.github/instructions`、`.cursor/rules`)以及跨会话自动记忆(Claude Code 的 `~/.claude/projects/…/memory`、Codex 的 `~/.codex/memories`、Hermes 的 `MEMORY.md` 与 `USER.md`),合并符号链接与 `@AGENTS.md` 导入包装且从不改动受跟踪的仓库文件。
|
||||
|
||||
- **自动记忆策略(`继承`、`读写`、`只读`、`关`)**:可按全局或工作区配置,也可在输入框的 **记忆** 选择器(输入 `/memory` 或 `/memories`,或点 **+** 菜单中的 **记忆…**)中仅对当前任务覆盖。**只读** 会读取已有记忆而不记录探索性对话产生的新内容。
|
||||
- **单个文件的模式(`自动`、`始终`、`关闭`)**:`关闭` 让该文件不进入新会话;`始终` 还会把其他智能体的文件交给所有智能体(例如把 Cursor 规则交给 Claude Code)。
|
||||
- **规则与指令**:查看每个文件会被哪些智能体原生加载,检查超长或失效的 `@import` 告警,创建新的指令或规则文件,并一键在编辑器中打开。各智能体直接读取其原生指令文件。
|
||||
- **按智能体配置自动记忆**:按各原生驱动实际支持的能力控制跨会话自动记忆——Claude Code 支持 **默认 / 开 / 关**,Codex 支持 **默认 / 读写 / 只读 / 关**(可按全局或工作区配置,也可在输入框的 **记忆** 选择器通过 `/memory` 或 `/memories` 仅对当前任务覆盖),Hermes Agent 支持 **开 / 关**(直接写入 `~/.hermes/config.yaml`)。其他智能体在各自设置中自行管理自动记忆。
|
||||
- **提升到 AGENTS.md**:把自动学到的记忆笔记移入 `AGENTS.md`(可指定标题),让所有智能体都能读到。
|
||||
|
||||
### 智能体插件
|
||||
|
||||
@@ -111,8 +111,7 @@ async function installAutomationDesktopHarness(page: import("@playwright/test").
|
||||
handlers.agent_memory_list = () => ({
|
||||
entries: [],
|
||||
providers: [],
|
||||
autoMemory: "inherit",
|
||||
autoMemoryOrigin: "none",
|
||||
workspaceTrusted: true,
|
||||
});
|
||||
handlers.mcp_list = () => ({ servers: [], external: [] });
|
||||
handlers.vcs_branch_info = () => ({ head: "main" });
|
||||
|
||||
@@ -55,7 +55,6 @@ agent_memory_list always project_host bin
|
||||
agent_memory_promote trusted project_host bindings async
|
||||
agent_memory_reset_provider always project_host bindings async
|
||||
agent_memory_set_auto always project_host bindings async
|
||||
agent_memory_set_mode always project_host bindings async
|
||||
agent_plugins_add_marketplace always project_host bindings async
|
||||
agent_plugins_browse_marketplace always project_host bindings async
|
||||
agent_plugins_install always project_host bindings async
|
||||
|
||||
+33
-87
@@ -156,15 +156,10 @@ export const commands = {
|
||||
/** Clears local auto-memory files for `provider` (`claude`, `codex`, or `hermes`). */
|
||||
agentMemoryResetProvider: (provider: string) => typedError<AgentMemoryCatalog_Serialize, IdeError>(__TAURI_INVOKE("agent_memory_reset_provider", { provider })),
|
||||
/**
|
||||
* Sets the cross-session auto-memory policy (`Inherit`, `ReadWrite`, `ReadOnly`, `Off`)
|
||||
* globally or for one `provider` in `scope`.
|
||||
* Sets the cross-session auto-memory policy for one `provider` in `scope`.
|
||||
* For native-config providers (Hermes), writes the agent's own config file directly.
|
||||
*/
|
||||
agentMemorySetAuto: (scope: McpScope, provider: string | null, mode: AutoMemoryMode) => typedError<AgentMemoryCatalog_Serialize, IdeError>(__TAURI_INVOKE("agent_memory_set_auto", { scope, provider, mode })),
|
||||
/**
|
||||
* Sets how memory entry `id` runs in `scope` (`settings.toml` vs `.openidea/settings.toml`),
|
||||
* never modifying the file on disk.
|
||||
*/
|
||||
agentMemorySetMode: (id: string, scope: McpScope, mode: AgentMemoryMode, agents: string[]) => typedError<AgentMemoryCatalog_Serialize, IdeError>(__TAURI_INVOKE("agent_memory_set_mode", { id, scope, mode, agents })),
|
||||
agentMemorySetAuto: (scope: McpScope, provider: string, mode: AutoMemoryMode) => typedError<AgentMemoryCatalog_Serialize, IdeError>(__TAURI_INVOKE("agent_memory_set_auto", { scope, provider, mode })),
|
||||
/** Registers a marketplace source (`owner/repo[#ref]`, GitHub URL, or local path) in `scope`. */
|
||||
agentPluginsAddMarketplace: (scope: McpScope, source: string) => typedError<AgentPluginCatalog_Serialize, IdeError>(__TAURI_INVOKE("agent_plugins_add_marketplace", { scope, source })),
|
||||
/** Browses installable plugins inside a marketplace (`owner/repo[#ref]`, GitHub URL, or local directory/manifest). */
|
||||
@@ -3254,12 +3249,17 @@ export type AgentAutoMemoryStatus_Deserialize = {
|
||||
label: string,
|
||||
mode: AutoMemoryMode,
|
||||
origin: AgentMemoryOrigin,
|
||||
/** Auto-memory modes this provider enforces (empty when the agent manages auto-memory itself). */
|
||||
supportedModes?: AutoMemoryMode[],
|
||||
/**
|
||||
* True when changing the mode edits the agent's own global config (e.g. `~/.hermes/config.yaml`)
|
||||
* rather than a project or per-session override.
|
||||
*/
|
||||
nativeConfigOnly?: boolean,
|
||||
noteCount: number,
|
||||
rolloutCount: number,
|
||||
approxTokens: number,
|
||||
storagePath?: IpcPath | null,
|
||||
supportsAutoControl: boolean,
|
||||
supportsFileExclusion: boolean,
|
||||
supportsReset: boolean,
|
||||
};
|
||||
|
||||
@@ -3269,12 +3269,17 @@ export type AgentAutoMemoryStatus_Serialize = {
|
||||
label: string,
|
||||
mode: AutoMemoryMode,
|
||||
origin: AgentMemoryOrigin,
|
||||
/** Auto-memory modes this provider enforces (empty when the agent manages auto-memory itself). */
|
||||
supportedModes?: AutoMemoryMode[],
|
||||
/**
|
||||
* True when changing the mode edits the agent's own global config (e.g. `~/.hermes/config.yaml`)
|
||||
* rather than a project or per-session override.
|
||||
*/
|
||||
nativeConfigOnly: boolean,
|
||||
noteCount: number,
|
||||
rolloutCount: number,
|
||||
approxTokens: number,
|
||||
storagePath?: IpcPath | null,
|
||||
supportsAutoControl: boolean,
|
||||
supportsFileExclusion: boolean,
|
||||
supportsReset: boolean,
|
||||
};
|
||||
|
||||
@@ -3933,23 +3938,21 @@ export type AgentMcpServer_Serialize = {
|
||||
registryUrl?: string | null,
|
||||
};
|
||||
|
||||
/** Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`. */
|
||||
/** Full catalog returned to Settings › Agents › Rules & Memory and the Composer `MemoryPicker`. */
|
||||
export type AgentMemoryCatalog = AgentMemoryCatalog_Serialize | AgentMemoryCatalog_Deserialize;
|
||||
|
||||
/** Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`. */
|
||||
/** Full catalog returned to Settings › Agents › Rules & Memory and the Composer `MemoryPicker`. */
|
||||
export type AgentMemoryCatalog_Deserialize = {
|
||||
entries: AgentMemoryState_Deserialize[],
|
||||
entries: AgentMemoryEntry_Deserialize[],
|
||||
providers: AgentAutoMemoryStatus_Deserialize[],
|
||||
autoMemory: AutoMemoryMode,
|
||||
autoMemoryOrigin: AgentMemoryOrigin,
|
||||
workspaceTrusted: boolean,
|
||||
};
|
||||
|
||||
/** Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`. */
|
||||
/** Full catalog returned to Settings › Agents › Rules & Memory and the Composer `MemoryPicker`. */
|
||||
export type AgentMemoryCatalog_Serialize = {
|
||||
entries: AgentMemoryState_Serialize[],
|
||||
entries: AgentMemoryEntry_Serialize[],
|
||||
providers: AgentAutoMemoryStatus_Serialize[],
|
||||
autoMemory: AutoMemoryMode,
|
||||
autoMemoryOrigin: AgentMemoryOrigin,
|
||||
workspaceTrusted: boolean,
|
||||
};
|
||||
|
||||
/** Target format when creating a new memory or instruction file from Settings › Agents › Memory. */
|
||||
@@ -3966,23 +3969,6 @@ export type AgentMemoryCreateTarget =
|
||||
/** One discovered instruction file, rule file, or learned auto-memory note. */
|
||||
export type AgentMemoryEntry = AgentMemoryEntry_Serialize | AgentMemoryEntry_Deserialize;
|
||||
|
||||
/** One memory or instruction entry's policy in Settings › Agents › Memory. */
|
||||
export type AgentMemoryEntryPolicy = AgentMemoryEntryPolicy_Serialize | AgentMemoryEntryPolicy_Deserialize;
|
||||
|
||||
/** One memory or instruction entry's policy in Settings › Agents › Memory. */
|
||||
export type AgentMemoryEntryPolicy_Deserialize = {
|
||||
mode?: AgentMemoryMode,
|
||||
/** Agent provider ids this entry applies to; empty means all agents. */
|
||||
agents?: string[],
|
||||
};
|
||||
|
||||
/** One memory or instruction entry's policy in Settings › Agents › Memory. */
|
||||
export type AgentMemoryEntryPolicy_Serialize = {
|
||||
mode: AgentMemoryMode,
|
||||
/** Agent provider ids this entry applies to; empty means all agents. */
|
||||
agents?: string[],
|
||||
};
|
||||
|
||||
/** One discovered instruction file, rule file, or learned auto-memory note. */
|
||||
export type AgentMemoryEntry_Deserialize = {
|
||||
/** Stable identifier (`"<source>::<rel_key>"`). */
|
||||
@@ -4054,33 +4040,22 @@ export type AgentMemoryKind =
|
||||
/** Agent-authored cross-session memory note (`MEMORY.md`, Claude topic files, Codex summaries, Hermes `USER.md`). */
|
||||
"autoNote";
|
||||
|
||||
/** How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`). */
|
||||
export type AgentMemoryMode =
|
||||
/** Load according to its native rules (always for instructions, matching files for path-scoped rules). */
|
||||
"auto" |
|
||||
/** Force-load into every session regardless of path scoping. */
|
||||
"always" |
|
||||
/** Exclude from sessions where the harness supports it. */
|
||||
"off";
|
||||
|
||||
/** Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`]. */
|
||||
/** Which layer decided a provider's effective [`AutoMemoryMode`]. */
|
||||
export type AgentMemoryOrigin = "none" | "session" | "workspace" | "user" |
|
||||
/** Locked `Off` because the workspace is untrusted. */
|
||||
"trust";
|
||||
/** Configured directly in the agent's own native config file (e.g. `~/.hermes/config.yaml`). */
|
||||
"native";
|
||||
|
||||
/** Per-session memory overrides stored on an [`AgentTask`]. */
|
||||
/** Per-session auto-memory override stored on an [`AgentTask`] or automation. */
|
||||
export type AgentMemoryOverrides = AgentMemoryOverrides_Serialize | AgentMemoryOverrides_Deserialize;
|
||||
|
||||
/** Per-session memory overrides stored on an [`AgentTask`]. */
|
||||
/** Per-session auto-memory override stored on an [`AgentTask`] or automation. */
|
||||
export type AgentMemoryOverrides_Deserialize = {
|
||||
autoMemory?: AutoMemoryMode | null,
|
||||
entries?: { [key in string]: AgentMemoryMode },
|
||||
};
|
||||
|
||||
/** Per-session memory overrides stored on an [`AgentTask`]. */
|
||||
/** Per-session auto-memory override stored on an [`AgentTask`] or automation. */
|
||||
export type AgentMemoryOverrides_Serialize = {
|
||||
autoMemory?: AutoMemoryMode | null,
|
||||
entries?: { [key in string]: AgentMemoryMode },
|
||||
};
|
||||
|
||||
/** Agent memory settings (`[agents.memory]`). */
|
||||
@@ -4088,22 +4063,14 @@ export type AgentMemorySettings = AgentMemorySettings_Serialize | AgentMemorySet
|
||||
|
||||
/** Agent memory settings (`[agents.memory]`). */
|
||||
export type AgentMemorySettings_Deserialize = {
|
||||
/** Default cross-session auto-memory policy across agents. */
|
||||
autoMemory?: AutoMemoryMode,
|
||||
/** Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`). */
|
||||
/** Per-provider cross-session auto-memory overrides (`[agents.memory.providers.<provider>]`). */
|
||||
providers?: { [key in string]: AgentProviderMemoryPolicy_Deserialize },
|
||||
/** Per-entry modes (`[agents.memory.entries.<id>]`). */
|
||||
entries?: { [key in string]: AgentMemoryEntryPolicy_Deserialize },
|
||||
};
|
||||
|
||||
/** Agent memory settings (`[agents.memory]`). */
|
||||
export type AgentMemorySettings_Serialize = {
|
||||
/** Default cross-session auto-memory policy across agents. */
|
||||
autoMemory: AutoMemoryMode,
|
||||
/** Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`). */
|
||||
/** Per-provider cross-session auto-memory overrides (`[agents.memory.providers.<provider>]`). */
|
||||
providers?: { [key in string]: AgentProviderMemoryPolicy_Serialize },
|
||||
/** Per-entry modes (`[agents.memory.entries.<id>]`). */
|
||||
entries?: { [key in string]: AgentMemoryEntryPolicy_Serialize },
|
||||
};
|
||||
|
||||
/** Which workspace, user, or CLI store a memory entry was discovered in. */
|
||||
@@ -4133,27 +4100,6 @@ export type AgentMemorySource =
|
||||
/** `<hermes_profile>/memories/{MEMORY.md,USER.md}`. */
|
||||
"hermesAuto";
|
||||
|
||||
/** A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin. */
|
||||
export type AgentMemoryState = AgentMemoryState_Serialize | AgentMemoryState_Deserialize;
|
||||
|
||||
/** A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin. */
|
||||
export type AgentMemoryState_Deserialize = {
|
||||
entry: AgentMemoryEntry_Deserialize,
|
||||
mode: AgentMemoryMode,
|
||||
/** Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents. */
|
||||
agents?: string[],
|
||||
origin: AgentMemoryOrigin,
|
||||
};
|
||||
|
||||
/** A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin. */
|
||||
export type AgentMemoryState_Serialize = {
|
||||
entry: AgentMemoryEntry_Serialize,
|
||||
mode: AgentMemoryMode,
|
||||
/** Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents. */
|
||||
agents?: string[],
|
||||
origin: AgentMemoryOrigin,
|
||||
};
|
||||
|
||||
/** Authoritative choices for new tasks, independent of any running session's settings. */
|
||||
export type AgentModelCatalog = {
|
||||
provider: string,
|
||||
@@ -5598,7 +5544,7 @@ export type AutoImportSettings = {
|
||||
importsOnPaste?: ImportsOnPaste,
|
||||
};
|
||||
|
||||
/** How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`). */
|
||||
/** How an agent's automatic cross-session memory runs (`[agents.memory.providers.<id>]`). */
|
||||
export type AutoMemoryMode =
|
||||
/** Leave the agent's own configuration untouched. */
|
||||
"inherit" |
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
.policyStrip {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.policyTop {
|
||||
.policyHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
@@ -29,55 +29,63 @@
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.providerChips {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
.providerChip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
border-radius: var(--radius-toolbar-button);
|
||||
background: var(--bg-control);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
font-size: var(--fs-tiny);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
|
||||
.resetInline {
|
||||
padding: 0 2px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--link);
|
||||
font: inherit;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.resetInline:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.nativeHint {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
.policyHint {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.modeSelect {
|
||||
min-width: 112px;
|
||||
.providerRows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-control);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.providerRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
padding: 5px 10px;
|
||||
}
|
||||
|
||||
.providerRow + .providerRow {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.providerRowInfo {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
color: var(--fg-strong);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.providerMeta {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-tiny);
|
||||
}
|
||||
|
||||
.providerRowControls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.providerSelect {
|
||||
width: 128px;
|
||||
}
|
||||
|
||||
.dialogBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
gap: var(--space-2-5, 10px);
|
||||
padding: 12px 16px;
|
||||
min-width: min(480px, 84vw);
|
||||
}
|
||||
@@ -143,7 +151,7 @@
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
/* Auto-memory rows of the memory picker (MemoryPicker.tsx). */
|
||||
/* Auto-memory row of the memory picker (MemoryPicker.tsx). */
|
||||
.autoRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -2,10 +2,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type {
|
||||
AgentMemoryCatalog,
|
||||
AgentMemoryEntry,
|
||||
AgentMemoryKind,
|
||||
AgentMemoryMode,
|
||||
AgentMemorySource,
|
||||
AgentMemoryState,
|
||||
AutoMemoryMode,
|
||||
CreateAgentMemoryInput,
|
||||
McpScope,
|
||||
@@ -22,45 +21,38 @@ function makeEntry(
|
||||
title: string,
|
||||
source: AgentMemorySource,
|
||||
kind: AgentMemoryKind,
|
||||
mode: AgentMemoryMode = "auto",
|
||||
extra: Partial<AgentMemoryState["entry"]> = {},
|
||||
origin: AgentMemoryState["origin"] = "none",
|
||||
): AgentMemoryState {
|
||||
extra: Partial<AgentMemoryEntry> = {},
|
||||
): AgentMemoryEntry {
|
||||
return {
|
||||
entry: {
|
||||
id,
|
||||
title,
|
||||
description: `${title} guidance`,
|
||||
kind,
|
||||
source,
|
||||
path: `/repo/${title}`,
|
||||
approxTokens: 120,
|
||||
lineCount: 40,
|
||||
byteLen: 480,
|
||||
writable: kind === "autoNote",
|
||||
valid: true,
|
||||
...extra,
|
||||
},
|
||||
mode,
|
||||
origin,
|
||||
id,
|
||||
title,
|
||||
description: `${title} guidance`,
|
||||
kind,
|
||||
source,
|
||||
path: `/repo/${title}`,
|
||||
approxTokens: 120,
|
||||
lineCount: 40,
|
||||
byteLen: 480,
|
||||
writable: kind === "autoNote",
|
||||
valid: true,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
const INITIAL_CATALOG: AgentMemoryCatalog = {
|
||||
autoMemory: "inherit",
|
||||
autoMemoryOrigin: "none",
|
||||
workspaceTrusted: true,
|
||||
providers: [
|
||||
{
|
||||
provider: "claude",
|
||||
label: "Claude Code",
|
||||
mode: "readWrite",
|
||||
mode: "inherit",
|
||||
origin: "none",
|
||||
supportedModes: ["inherit", "readWrite", "off"],
|
||||
nativeConfigOnly: false,
|
||||
noteCount: 2,
|
||||
rolloutCount: 0,
|
||||
approxTokens: 240,
|
||||
storagePath: "/home/.claude/projects/repo/memory",
|
||||
supportsAutoControl: true,
|
||||
supportsFileExclusion: true,
|
||||
supportsReset: true,
|
||||
},
|
||||
{
|
||||
@@ -68,62 +60,61 @@ const INITIAL_CATALOG: AgentMemoryCatalog = {
|
||||
label: "Codex",
|
||||
mode: "readOnly",
|
||||
origin: "workspace",
|
||||
supportedModes: ["inherit", "readWrite", "readOnly", "off"],
|
||||
nativeConfigOnly: false,
|
||||
noteCount: 1,
|
||||
rolloutCount: 3,
|
||||
approxTokens: 120,
|
||||
storagePath: "/home/.codex/memories",
|
||||
supportsAutoControl: true,
|
||||
supportsFileExclusion: false,
|
||||
supportsReset: true,
|
||||
},
|
||||
{
|
||||
provider: "hermes",
|
||||
label: "Hermes Agent",
|
||||
mode: "readWrite",
|
||||
origin: "native",
|
||||
supportedModes: ["readWrite", "off"],
|
||||
nativeConfigOnly: true,
|
||||
noteCount: 0,
|
||||
rolloutCount: 0,
|
||||
approxTokens: 0,
|
||||
storagePath: "/home/.hermes/memories",
|
||||
supportsReset: true,
|
||||
},
|
||||
],
|
||||
entries: [
|
||||
makeEntry("workspace::AGENTS.md", "AGENTS.md", "workspace", "instruction", "auto", {
|
||||
makeEntry("workspace::AGENTS.md", "AGENTS.md", "workspace", "instruction", {
|
||||
alsoIn: ["claudeWorkspace"],
|
||||
}),
|
||||
makeEntry("claudeAuto::feedback_tests.md", "feedback_tests.md", "claudeAuto", "autoNote", "auto", {
|
||||
makeEntry("claudeAuto::feedback_tests.md", "feedback_tests.md", "claudeAuto", "autoNote", {
|
||||
category: "feedback",
|
||||
}),
|
||||
makeEntry("claudeAuto::MEMORY.md", "MEMORY.md", "claudeAuto", "autoNote", "auto", {
|
||||
makeEntry("claudeAuto::MEMORY.md", "MEMORY.md", "claudeAuto", "autoNote", {
|
||||
valid: false,
|
||||
warnings: ["`MEMORY.md` exceeds Claude Code's startup limit"],
|
||||
}),
|
||||
makeEntry("cursorWorkspace::react.mdc", "react.mdc", "cursorWorkspace", "rule", "auto", {
|
||||
makeEntry("cursorWorkspace::react.mdc", "react.mdc", "cursorWorkspace", "rule", {
|
||||
paths: ["src/**/*.tsx"],
|
||||
}),
|
||||
makeEntry(
|
||||
"copilotUser::legacy.instructions.md",
|
||||
"legacy.instructions.md",
|
||||
"copilotUser",
|
||||
"rule",
|
||||
"off",
|
||||
{},
|
||||
"user",
|
||||
),
|
||||
makeEntry("copilotUser::legacy.instructions.md", "legacy.instructions.md", "copilotUser", "rule"),
|
||||
],
|
||||
};
|
||||
|
||||
function createBackend() {
|
||||
let state: AgentMemoryCatalog = structuredClone(INITIAL_CATALOG);
|
||||
const setModeCalls: Array<{ id: string; scope: McpScope; mode: AgentMemoryMode }> = [];
|
||||
const setAutoCalls: Array<{ scope: McpScope; provider: string | null; mode: AutoMemoryMode }> = [];
|
||||
const setAutoCalls: Array<{ scope: McpScope; provider: string; mode: AutoMemoryMode }> = [];
|
||||
const createCalls: CreateAgentMemoryInput[] = [];
|
||||
const promoteCalls: PromoteAgentMemoryInput[] = [];
|
||||
const resetCalls: string[] = [];
|
||||
|
||||
const backend: MemoryBackend = {
|
||||
list: vi.fn(async () => state),
|
||||
setMode: vi.fn(async (id, scope, mode) => {
|
||||
setModeCalls.push({ id, scope, mode });
|
||||
state = {
|
||||
...state,
|
||||
entries: state.entries.map((e) => (e.entry.id === id ? { ...e, mode } : e)),
|
||||
};
|
||||
return state;
|
||||
}),
|
||||
setAuto: vi.fn(async (scope, provider, mode) => {
|
||||
setAutoCalls.push({ scope, provider, mode });
|
||||
state = { ...state, autoMemory: mode };
|
||||
state = {
|
||||
...state,
|
||||
providers: state.providers.map((p) => (p.provider === provider ? { ...p, mode } : p)),
|
||||
};
|
||||
return state;
|
||||
}),
|
||||
create: vi.fn(async (input) => {
|
||||
@@ -138,12 +129,12 @@ function createBackend() {
|
||||
promoteCalls.push(input);
|
||||
state = {
|
||||
...state,
|
||||
entries: input.removeSource ? state.entries.filter((e) => e.entry.id !== input.sourceId) : state.entries,
|
||||
entries: input.removeSource ? state.entries.filter((e) => e.id !== input.sourceId) : state.entries,
|
||||
};
|
||||
return state;
|
||||
}),
|
||||
remove: vi.fn(async (id) => {
|
||||
state = { ...state, entries: state.entries.filter((e) => e.entry.id !== id) };
|
||||
state = { ...state, entries: state.entries.filter((e) => e.id !== id) };
|
||||
return state;
|
||||
}),
|
||||
resetProvider: vi.fn(async (provider) => {
|
||||
@@ -152,7 +143,7 @@ function createBackend() {
|
||||
}),
|
||||
};
|
||||
|
||||
return { backend, setModeCalls, setAutoCalls, createCalls, promoteCalls, resetCalls };
|
||||
return { backend, setAutoCalls, createCalls, promoteCalls, resetCalls };
|
||||
}
|
||||
|
||||
function makeForm(scope: "global" | "project"): SettingsForm {
|
||||
@@ -179,7 +170,7 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("MemoryPage (Rules & Memory)", () => {
|
||||
it("splits Rules & Instructions and Auto-Memory into header tabs with Master-Detail search", async () => {
|
||||
it("splits Rules & Instructions and Auto-Memory into header tabs with Master-Detail search and no fake entry modes", async () => {
|
||||
const { backend } = createBackend();
|
||||
render(<MemoryPage backend={backend} />);
|
||||
|
||||
@@ -189,6 +180,8 @@ describe("MemoryPage (Rules & Memory)", () => {
|
||||
expect(screen.getByRole("region", { name: "GitHub Copilot (User)" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("region", { name: "Claude Code (Auto Memory)" })).toBeNull();
|
||||
expect(screen.getByRole("heading", { name: "AGENTS.md" })).toBeInTheDocument();
|
||||
expect(screen.getByText("All coding agents")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /Mode for/ })).toBeNull();
|
||||
|
||||
// Search filters rules by path glob
|
||||
fireEvent.change(screen.getByPlaceholderText("Search rules & instructions..."), { target: { value: "tsx" } });
|
||||
@@ -202,7 +195,7 @@ describe("MemoryPage (Rules & Memory)", () => {
|
||||
expect(screen.getByRole("heading", { name: "feedback_tests.md" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("updates auto-memory policy, provider reset, and entry modes using active Settings scope", async () => {
|
||||
it("exposes per-provider auto-memory controls tailored to each driver and provider reset", async () => {
|
||||
useProject.setState({
|
||||
project: { name: "openidea", root: "/repo", trusted: true, workspace: false } as unknown as ProjectInfo,
|
||||
});
|
||||
@@ -214,16 +207,32 @@ describe("MemoryPage (Rules & Memory)", () => {
|
||||
);
|
||||
|
||||
await screen.findByRole("heading", { name: "AGENTS.md" });
|
||||
pick("Mode for AGENTS.md", "Off");
|
||||
fireEvent.click(screen.getByRole("tab", { name: /Auto-Memory/ }));
|
||||
|
||||
// Claude offers Default / On / Off (no Read Only)
|
||||
fireEvent.click(screen.getByRole("button", { name: "Auto-memory mode for Claude Code" }));
|
||||
const claudeListbox = screen.getByRole("listbox", { name: "Auto-memory mode for Claude Code" });
|
||||
expect(within(claudeListbox).queryByText("Read Only")).toBeNull();
|
||||
fireEvent.click(within(claudeListbox).getByText("Off"));
|
||||
await waitFor(() => expect(spy.setAutoCalls).toEqual([{ scope: "workspace", provider: "claude", mode: "off" }]));
|
||||
|
||||
// Codex offers Read & Write / Read Only / Off / Default
|
||||
pick("Auto-memory mode for Codex", "Read & Write");
|
||||
await waitFor(() =>
|
||||
expect(spy.setModeCalls).toEqual([{ id: "workspace::AGENTS.md", scope: "workspace", mode: "off" }]),
|
||||
expect(spy.setAutoCalls).toEqual([
|
||||
{ scope: "workspace", provider: "claude", mode: "off" },
|
||||
{ scope: "workspace", provider: "codex", mode: "readWrite" },
|
||||
]),
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("tab", { name: /Auto-Memory/ }));
|
||||
pick("Auto-memory mode", "Read Only");
|
||||
await waitFor(() => expect(spy.setAutoCalls).toEqual([{ scope: "workspace", provider: null, mode: "readOnly" }]));
|
||||
// Hermes displays Native config badge and toggles On / Off
|
||||
expect(screen.getByText("Native config")).toBeInTheDocument();
|
||||
pick("Auto-memory mode for Hermes Agent", "Off");
|
||||
await waitFor(() => expect(spy.setAutoCalls[2]).toEqual({ scope: "workspace", provider: "hermes", mode: "off" }));
|
||||
|
||||
const resetButtons = screen.getAllByRole("button", { name: "Reset" });
|
||||
expect(resetButtons).toHaveLength(3);
|
||||
expect(resetButtons[2]).toBeDisabled();
|
||||
fireEvent.click(resetButtons[0]!);
|
||||
await waitFor(() => expect(spy.resetCalls).toEqual(["claude"]));
|
||||
});
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
/**
|
||||
* Settings › Agents › Rules & Memory: JetBrains Master-Detail view split cleanly
|
||||
* into two header tabs — Rules & Instructions (CLAUDE.md, AGENTS.md, path-scoped
|
||||
* rules) and Auto-Memory (cross-session agent memory policy and learned notes) —
|
||||
* honoring the Settings dialog's native Global / This project ScopeSwitch.
|
||||
* Settings › Agents › Rules & Memory: JetBrains Master-Detail view split into two tabs —
|
||||
* Rules & Instructions (unified discovery, health diagnostics, and editing for AGENTS.md,
|
||||
* CLAUDE.md, path-scoped rules) and Auto-Memory (per-provider auto-memory controls matching
|
||||
* each native driver's real capabilities, plus learned notes with promote/delete/reset).
|
||||
*/
|
||||
import clsx from "clsx";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type {
|
||||
AgentMemoryCatalog,
|
||||
AgentMemoryCreateTarget,
|
||||
AgentMemoryMode,
|
||||
AgentMemoryEntry,
|
||||
AgentMemorySource,
|
||||
AgentMemoryState,
|
||||
AutoMemoryMode,
|
||||
McpScope,
|
||||
} from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
@@ -46,9 +44,12 @@ import { AGENT_PLUGINS_PAGE, providerIcon } from "./model";
|
||||
import {
|
||||
EMPTY_MEMORY_CATALOG,
|
||||
MEMORY_SOURCE_GROUPS,
|
||||
autoMemoryModeLabel,
|
||||
defaultMemoryBackend,
|
||||
isDiscoveredMemorySource,
|
||||
isWorkspaceMemorySource,
|
||||
memoryGroupTitle,
|
||||
nativeReadersLabel,
|
||||
useMemoryCatalog,
|
||||
type MemoryBackend,
|
||||
} from "./memoryModel";
|
||||
@@ -59,31 +60,12 @@ export { defaultMemoryBackend, type MemoryBackend };
|
||||
type MainTab = "rules" | "auto";
|
||||
type SourceFilter = "all" | "workspace" | "user" | "cli";
|
||||
|
||||
const ENTRY_MODE_OPTIONS: ReadonlyArray<{ value: AgentMemoryMode; label: string }> = [
|
||||
{ value: "auto", label: "Auto" },
|
||||
{ value: "always", label: "Always" },
|
||||
{ value: "off", label: "Off" },
|
||||
];
|
||||
|
||||
const AUTO_MEMORY_OPTIONS: ReadonlyArray<{ value: AutoMemoryMode; label: string }> = [
|
||||
{ value: "inherit", label: "Inherit" },
|
||||
{ value: "readWrite", label: "Read & Write" },
|
||||
{ value: "readOnly", label: "Read Only" },
|
||||
{ value: "off", label: "Off" },
|
||||
];
|
||||
|
||||
function matchesSourceFilter(source: AgentMemorySource, filter: SourceFilter): boolean {
|
||||
switch (filter) {
|
||||
case "all":
|
||||
return true;
|
||||
case "workspace":
|
||||
return (
|
||||
source === "workspace" ||
|
||||
source === "claudeWorkspace" ||
|
||||
source === "githubWorkspace" ||
|
||||
source === "cursorWorkspace" ||
|
||||
source === "geminiWorkspace"
|
||||
);
|
||||
return isWorkspaceMemorySource(source);
|
||||
case "user":
|
||||
return source === "claudeUser" || source === "copilotUser" || source === "codexUser" || source === "geminiUser";
|
||||
case "cli":
|
||||
@@ -91,10 +73,6 @@ function matchesSourceFilter(source: AgentMemorySource, filter: SourceFilter): b
|
||||
}
|
||||
}
|
||||
|
||||
function modeLabel(mode: AgentMemoryMode, tx: (s: string) => string): string {
|
||||
return tx(ENTRY_MODE_OPTIONS.find((o) => o.value === mode)?.label ?? mode);
|
||||
}
|
||||
|
||||
export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: MemoryBackend }) {
|
||||
const tx = useTx();
|
||||
const hasTrustedProject = useProject((s) => !!s.project?.root && !!s.project?.trusted);
|
||||
@@ -114,7 +92,7 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busyKey, setBusyKey] = useState<string | null>(null);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [promoting, setPromoting] = useState<AgentMemoryState | null>(null);
|
||||
const [promoting, setPromoting] = useState<AgentMemoryEntry | null>(null);
|
||||
|
||||
const syncCatalog = useCallback(
|
||||
(next: AgentMemoryCatalog) => {
|
||||
@@ -164,33 +142,32 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
}, []);
|
||||
|
||||
const rulesCount = useMemo(
|
||||
() => catalog.entries.filter((e) => e.entry.kind === "instruction" || e.entry.kind === "rule").length,
|
||||
() => catalog.entries.filter((e) => e.kind === "instruction" || e.kind === "rule").length,
|
||||
[catalog.entries],
|
||||
);
|
||||
const autoCount = useMemo(() => catalog.entries.filter((e) => e.entry.kind === "autoNote").length, [catalog.entries]);
|
||||
const autoCount = useMemo(() => catalog.entries.filter((e) => e.kind === "autoNote").length, [catalog.entries]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return catalog.entries.filter((s) => {
|
||||
const matchesKind =
|
||||
tab === "rules" ? s.entry.kind === "instruction" || s.entry.kind === "rule" : s.entry.kind === "autoNote";
|
||||
return catalog.entries.filter((e) => {
|
||||
const matchesKind = tab === "rules" ? e.kind === "instruction" || e.kind === "rule" : e.kind === "autoNote";
|
||||
if (!matchesKind) return false;
|
||||
if (tab === "rules" && !matchesSourceFilter(s.entry.source, sourceFilter)) return false;
|
||||
if (tab === "rules" && !matchesSourceFilter(e.source, sourceFilter)) return false;
|
||||
if (!q) return true;
|
||||
return (
|
||||
s.entry.title.toLowerCase().includes(q) ||
|
||||
s.entry.description.toLowerCase().includes(q) ||
|
||||
s.entry.path.toLowerCase().includes(q) ||
|
||||
(s.entry.paths ?? []).some((p) => p.toLowerCase().includes(q))
|
||||
e.title.toLowerCase().includes(q) ||
|
||||
e.description.toLowerCase().includes(q) ||
|
||||
e.path.toLowerCase().includes(q) ||
|
||||
(e.paths ?? []).some((p) => p.toLowerCase().includes(q))
|
||||
);
|
||||
});
|
||||
}, [catalog.entries, tab, sourceFilter, query]);
|
||||
|
||||
const grouped = useMemo(() => {
|
||||
const order = Object.keys(MEMORY_SOURCE_GROUPS) as AgentMemorySource[];
|
||||
const out: Array<[AgentMemorySource, AgentMemoryState[]]> = [];
|
||||
const out: Array<[AgentMemorySource, AgentMemoryEntry[]]> = [];
|
||||
for (const source of order) {
|
||||
const items = filtered.filter((s) => s.entry.source === source);
|
||||
const items = filtered.filter((e) => e.source === source);
|
||||
if (items.length > 0) out.push([source, items]);
|
||||
}
|
||||
return out;
|
||||
@@ -198,7 +175,7 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
|
||||
const flatFiltered = useMemo(() => grouped.flatMap(([, items]) => items), [grouped]);
|
||||
const selectedEntry = useMemo(
|
||||
() => flatFiltered.find((s) => s.entry.id === selectedId) ?? flatFiltered[0] ?? null,
|
||||
() => flatFiltered.find((e) => e.id === selectedId) ?? flatFiltered[0] ?? null,
|
||||
[flatFiltered, selectedId],
|
||||
);
|
||||
|
||||
@@ -228,46 +205,78 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
const autoMemoryStrip =
|
||||
tab === "auto" ? (
|
||||
<div className={styles.policyStrip}>
|
||||
<div className={styles.policyTop}>
|
||||
<div className={styles.policyHeader}>
|
||||
<div className={styles.policyTitleGroup}>
|
||||
<span className={styles.policyTitle}>
|
||||
<T>Cross-Session Auto-Memory</T>
|
||||
</span>
|
||||
{catalog.autoMemoryOrigin === "workspace" && (
|
||||
<span className={clsx(masterStyles.pill, masterStyles.pillAccent)}>
|
||||
<T>Project override</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Select
|
||||
aria-label={tx("Auto-memory mode")}
|
||||
value={catalog.autoMemory}
|
||||
disabled={busyKey === "auto"}
|
||||
options={AUTO_MEMORY_OPTIONS.map((o) => ({ value: o.value, label: tx(o.label) }))}
|
||||
onChange={(mode) => void runMutation("auto", () => backend.setAuto(settingsScope, null, mode))}
|
||||
/>
|
||||
<span className={styles.policyHint}>
|
||||
<T>Other agents manage cross-session auto-memory in their own settings.</T>
|
||||
</span>
|
||||
</div>
|
||||
{catalog.providers.some((p) => p.supportsAutoControl) && (
|
||||
<div className={styles.providerChips}>
|
||||
{catalog.providers
|
||||
.filter((p) => p.supportsAutoControl)
|
||||
.map((p) => (
|
||||
<span key={p.provider} className={styles.providerChip}>
|
||||
<span className={clsx(masterStyles.statusDot, p.mode !== "off" && masterStyles.statusDotOn)} />
|
||||
<span>{p.label}</span>
|
||||
{p.noteCount > 0 && <span>· {p.noteCount}</span>}
|
||||
{p.supportsReset && (p.noteCount > 0 || p.rolloutCount > 0) && backend.resetProvider && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.resetInline}
|
||||
disabled={busyKey === `reset:${p.provider}`}
|
||||
onClick={() => void runMutation(`reset:${p.provider}`, () => backend.resetProvider!(p.provider))}
|
||||
>
|
||||
<T>Reset</T>
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
{catalog.providers.length > 0 && (
|
||||
<div className={styles.providerRows}>
|
||||
{catalog.providers.map((p) => {
|
||||
const supported = p.supportedModes ?? [];
|
||||
const hasControl = supported.length > 0;
|
||||
return (
|
||||
<div key={p.provider} className={styles.providerRow}>
|
||||
<div className={styles.providerRowInfo}>
|
||||
<span className={clsx(masterStyles.statusDot, p.mode !== "off" && masterStyles.statusDotOn)} />
|
||||
<Icon name={providerIcon(p.provider)} size={14} />
|
||||
<span>{p.label}</span>
|
||||
{(p.noteCount > 0 || p.rolloutCount > 0) && (
|
||||
<span className={styles.providerMeta}>
|
||||
{formatMessage(tx("{count} notes"), { count: p.noteCount })}
|
||||
</span>
|
||||
)}
|
||||
{p.origin === "workspace" && (
|
||||
<span className={clsx(masterStyles.pill, masterStyles.pillAccent)}>
|
||||
<T>Project override</T>
|
||||
</span>
|
||||
)}
|
||||
{p.nativeConfigOnly && (
|
||||
<span
|
||||
className={masterStyles.pill}
|
||||
title={tx("Saved directly in this agent's native config file")}
|
||||
>
|
||||
<T>Native config</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.providerRowControls}>
|
||||
{hasControl && (
|
||||
<Select
|
||||
className={styles.providerSelect}
|
||||
aria-label={formatMessage(tx("Auto-memory mode for {provider}"), { provider: p.label })}
|
||||
value={p.mode}
|
||||
disabled={busyKey === `auto:${p.provider}`}
|
||||
options={supported.map((mode) => ({
|
||||
value: mode,
|
||||
label: autoMemoryModeLabel(mode, supported, tx),
|
||||
}))}
|
||||
onChange={(mode) =>
|
||||
void runMutation(`auto:${p.provider}`, () => backend.setAuto(settingsScope, p.provider, mode))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{p.supportsReset && backend.resetProvider && (
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
disabled={busyKey === `reset:${p.provider}` || (p.noteCount === 0 && p.rolloutCount === 0)}
|
||||
onClick={() =>
|
||||
void runMutation(`reset:${p.provider}`, () => backend.resetProvider!(p.provider))
|
||||
}
|
||||
>
|
||||
<T>Reset</T>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -280,7 +289,13 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
headerControls={headerControls}
|
||||
topStrip={autoMemoryStrip}
|
||||
error={error}
|
||||
footerNote={tx("Mode changes apply immediately without modifying tracked repository files.")}
|
||||
footerNote={
|
||||
tab === "rules"
|
||||
? tx(
|
||||
"Instruction and rule files are loaded directly by each agent. Edit or remove files to change what an agent reads.",
|
||||
)
|
||||
: tx("Auto-memory settings apply to new or idle sessions for agents that support them.")
|
||||
}
|
||||
listToolbar={
|
||||
<>
|
||||
<div className={masterStyles.toolbarRow}>
|
||||
@@ -341,16 +356,15 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
titleTooltip={group.paths}
|
||||
onToggle={() => setCollapsed((prev) => ({ ...prev, [source]: !prev[source] }))}
|
||||
>
|
||||
{items.map((state) => {
|
||||
const { entry } = state;
|
||||
{items.map((entry) => {
|
||||
const kindLabel =
|
||||
entry.kind === "autoNote" ? tx("Auto") : entry.kind === "rule" ? tx("Rule") : tx("Instruction");
|
||||
const hasWarn = (entry.warnings?.length ?? 0) > 0 || state.origin === "trust";
|
||||
const untrusted = !catalog.workspaceTrusted && isWorkspaceMemorySource(entry.source);
|
||||
const hasWarn = (entry.warnings?.length ?? 0) > 0 || untrusted;
|
||||
return (
|
||||
<MasterRow
|
||||
key={entry.id}
|
||||
selected={selectedEntry?.entry.id === entry.id}
|
||||
disabled={state.mode === "off"}
|
||||
selected={selectedEntry?.id === entry.id}
|
||||
icon={<Icon name={group.agent ? providerIcon(group.agent) : "file-md"} size={14} />}
|
||||
title={entry.title}
|
||||
subtitle={[
|
||||
@@ -368,14 +382,8 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
title={entry.warnings?.join("; ") || tx("Untrusted workspace")}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className={clsx(
|
||||
masterStyles.pill,
|
||||
state.origin === "workspace" && masterStyles.pillAccent,
|
||||
)}
|
||||
>
|
||||
{modeLabel(state.mode, tx)}
|
||||
</span>
|
||||
{(entry.paths?.length ?? 0) > 0 && <span className={masterStyles.pill}>paths</span>}
|
||||
{entry.category && <span className={masterStyles.pill}>{entry.category}</span>}
|
||||
</>
|
||||
}
|
||||
onSelect={() => setSelectedId(entry.id)}
|
||||
@@ -390,20 +398,14 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
detailContent={
|
||||
selectedEntry ? (
|
||||
<MemoryDetail
|
||||
state={selectedEntry}
|
||||
activeScope={settingsScope}
|
||||
hasTrustedProject={hasTrustedProject}
|
||||
busy={busyKey === selectedEntry.entry.id}
|
||||
canPromote={selectedEntry.entry.kind === "autoNote" && !!backend.promote && hasTrustedProject}
|
||||
canDelete={selectedEntry.entry.writable && !!backend.remove}
|
||||
onModeChange={(mode) =>
|
||||
void runMutation(selectedEntry.entry.id, () =>
|
||||
backend.setMode(selectedEntry.entry.id, settingsScope, mode),
|
||||
)
|
||||
}
|
||||
onOpenFile={() => openFile(selectedEntry.entry.path)}
|
||||
entry={selectedEntry}
|
||||
workspaceTrusted={catalog.workspaceTrusted}
|
||||
busy={busyKey === selectedEntry.id}
|
||||
canPromote={selectedEntry.kind === "autoNote" && !!backend.promote && hasTrustedProject}
|
||||
canDelete={selectedEntry.writable && !!backend.remove}
|
||||
onOpenFile={() => openFile(selectedEntry.path)}
|
||||
onPromote={() => setPromoting(selectedEntry)}
|
||||
onDelete={() => void runMutation(selectedEntry.entry.id, () => backend.remove!(selectedEntry.entry.id))}
|
||||
onDelete={() => void runMutation(selectedEntry.id, () => backend.remove!(selectedEntry.id))}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
@@ -436,7 +438,7 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
|
||||
{promoting && backend.promote && (
|
||||
<PromoteMemoryDialog
|
||||
state={promoting}
|
||||
entry={promoting}
|
||||
backend={backend}
|
||||
onPromoted={(next) => {
|
||||
syncCatalog(next);
|
||||
@@ -450,34 +452,29 @@ export function MemoryPage({ backend = defaultMemoryBackend }: { backend?: Memor
|
||||
}
|
||||
|
||||
function MemoryDetail({
|
||||
state,
|
||||
activeScope,
|
||||
hasTrustedProject,
|
||||
entry,
|
||||
workspaceTrusted,
|
||||
busy,
|
||||
canPromote,
|
||||
canDelete,
|
||||
onModeChange,
|
||||
onOpenFile,
|
||||
onPromote,
|
||||
onDelete,
|
||||
}: {
|
||||
state: AgentMemoryState;
|
||||
activeScope: McpScope;
|
||||
hasTrustedProject: boolean;
|
||||
entry: AgentMemoryEntry;
|
||||
workspaceTrusted: boolean;
|
||||
busy: boolean;
|
||||
canPromote: boolean;
|
||||
canDelete: boolean;
|
||||
onModeChange: (mode: AgentMemoryMode) => void;
|
||||
onOpenFile: () => void;
|
||||
onPromote: () => void;
|
||||
onDelete: () => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const { entry } = state;
|
||||
const group = MEMORY_SOURCE_GROUPS[entry.source];
|
||||
const kindLabel =
|
||||
entry.kind === "autoNote" ? tx("Auto-Memory") : entry.kind === "rule" ? tx("Rule") : tx("Instruction");
|
||||
const untrusted = state.origin === "trust" && !hasTrustedProject;
|
||||
const untrusted = !workspaceTrusted && isWorkspaceMemorySource(entry.source);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -486,11 +483,7 @@ function MemoryDetail({
|
||||
<div className={masterStyles.detailTitleLine}>
|
||||
<h3 className={masterStyles.detailTitle}>{entry.title}</h3>
|
||||
<span className={masterStyles.pill}>{kindLabel}</span>
|
||||
{state.origin === "workspace" && (
|
||||
<span className={clsx(masterStyles.pill, masterStyles.pillAccent)}>
|
||||
<T>Project override</T>
|
||||
</span>
|
||||
)}
|
||||
{entry.category && <span className={masterStyles.pill}>{entry.category}</span>}
|
||||
</div>
|
||||
<div className={masterStyles.detailMeta}>
|
||||
{group.agent && <Icon name={providerIcon(group.agent)} size={13} />}
|
||||
@@ -509,23 +502,13 @@ function MemoryDetail({
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={masterStyles.detailActions}>
|
||||
<Select
|
||||
className={styles.modeSelect}
|
||||
aria-label={tx`Mode for ${entry.title}`}
|
||||
value={state.mode}
|
||||
disabled={busy || untrusted}
|
||||
options={ENTRY_MODE_OPTIONS.map((o) => ({ value: o.value, label: tx(o.label) }))}
|
||||
onChange={onModeChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{state.origin === "trust" && (
|
||||
{untrusted && (
|
||||
<div className={clsx(masterStyles.callout, masterStyles.calloutWarn)}>
|
||||
<Icon name="warning" size={14} />
|
||||
<span>
|
||||
<T>Untrusted workspace: trust this project before changing workspace instruction modes.</T>
|
||||
<T>Untrusted workspace: agents do not run in this project until you trust it.</T>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -545,11 +528,9 @@ function MemoryDetail({
|
||||
</h4>
|
||||
<div className={masterStyles.metaGrid}>
|
||||
<span className={masterStyles.metaLabel}>
|
||||
<T>Editing scope</T>
|
||||
</span>
|
||||
<span className={masterStyles.metaValue}>
|
||||
{activeScope === "workspace" ? tx("This project") : tx("Global")}
|
||||
<T>Loaded by</T>
|
||||
</span>
|
||||
<span className={masterStyles.metaValue}>{nativeReadersLabel(entry, tx)}</span>
|
||||
{entry.pluginId && (
|
||||
<>
|
||||
<span className={masterStyles.metaLabel}>
|
||||
@@ -589,18 +570,6 @@ function MemoryDetail({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isDiscoveredMemorySource(entry.source) && group.agent && group.agent !== "claude" && (
|
||||
<span className={styles.nativeHint}>
|
||||
<Icon name={providerIcon(group.agent)} size={12} />
|
||||
<span>
|
||||
<T>
|
||||
This agent loads its own instruction files directly; Always additionally bridges the content to other
|
||||
agents.
|
||||
</T>
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={masterStyles.actionBar}>
|
||||
@@ -799,12 +768,12 @@ function CreateMemoryDialog({
|
||||
}
|
||||
|
||||
function PromoteMemoryDialog({
|
||||
state,
|
||||
entry,
|
||||
backend,
|
||||
onPromoted,
|
||||
onClose,
|
||||
}: {
|
||||
state: AgentMemoryState;
|
||||
entry: AgentMemoryEntry;
|
||||
backend: MemoryBackend;
|
||||
onPromoted: (next: AgentMemoryCatalog) => void;
|
||||
onClose: () => void;
|
||||
@@ -821,7 +790,7 @@ function PromoteMemoryDialog({
|
||||
setError(null);
|
||||
try {
|
||||
const next = await backend.promote({
|
||||
sourceId: state.entry.id,
|
||||
sourceId: entry.id,
|
||||
heading: heading.trim() || null,
|
||||
removeSource,
|
||||
});
|
||||
@@ -862,7 +831,7 @@ function PromoteMemoryDialog({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{state.entry.writable && (
|
||||
{entry.writable && (
|
||||
<Checkbox
|
||||
checked={removeSource}
|
||||
onChange={setRemoveSource}
|
||||
|
||||
@@ -33,19 +33,18 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
});
|
||||
|
||||
const CATALOG: AgentMemoryCatalog = {
|
||||
autoMemory: "inherit",
|
||||
autoMemoryOrigin: "none",
|
||||
workspaceTrusted: true,
|
||||
providers: [
|
||||
{
|
||||
provider: "claude",
|
||||
label: "Claude Code",
|
||||
mode: "readWrite",
|
||||
origin: "none",
|
||||
supportedModes: ["inherit", "readWrite", "off"],
|
||||
nativeConfigOnly: false,
|
||||
noteCount: 1,
|
||||
rolloutCount: 0,
|
||||
approxTokens: 100,
|
||||
supportsAutoControl: true,
|
||||
supportsFileExclusion: true,
|
||||
supportsReset: true,
|
||||
},
|
||||
{
|
||||
@@ -53,142 +52,111 @@ const CATALOG: AgentMemoryCatalog = {
|
||||
label: "Codex",
|
||||
mode: "inherit",
|
||||
origin: "none",
|
||||
supportedModes: ["inherit", "readWrite", "readOnly", "off"],
|
||||
nativeConfigOnly: false,
|
||||
noteCount: 1,
|
||||
rolloutCount: 2,
|
||||
approxTokens: 150,
|
||||
supportsAutoControl: true,
|
||||
supportsFileExclusion: false,
|
||||
supportsReset: true,
|
||||
},
|
||||
{
|
||||
provider: "copilot",
|
||||
label: "GitHub Copilot",
|
||||
mode: "inherit",
|
||||
origin: "none",
|
||||
noteCount: 0,
|
||||
provider: "hermes",
|
||||
label: "Hermes Agent",
|
||||
mode: "readWrite",
|
||||
origin: "native",
|
||||
supportedModes: ["readWrite", "off"],
|
||||
nativeConfigOnly: true,
|
||||
noteCount: 1,
|
||||
rolloutCount: 0,
|
||||
approxTokens: 0,
|
||||
supportsAutoControl: true,
|
||||
supportsFileExclusion: false,
|
||||
supportsReset: false,
|
||||
},
|
||||
{
|
||||
provider: "acp",
|
||||
label: "Cursor / Gemini / ACP",
|
||||
mode: "inherit",
|
||||
origin: "none",
|
||||
noteCount: 0,
|
||||
rolloutCount: 0,
|
||||
approxTokens: 0,
|
||||
supportsAutoControl: false,
|
||||
supportsFileExclusion: false,
|
||||
supportsReset: false,
|
||||
approxTokens: 60,
|
||||
supportsReset: true,
|
||||
},
|
||||
],
|
||||
entries: [
|
||||
{
|
||||
entry: {
|
||||
id: "workspace::AGENTS.md",
|
||||
title: "AGENTS.md",
|
||||
description: "Shared repo rules",
|
||||
kind: "instruction",
|
||||
source: "workspace",
|
||||
path: "/repo/AGENTS.md",
|
||||
approxTokens: 400,
|
||||
lineCount: 80,
|
||||
byteLen: 1600,
|
||||
writable: false,
|
||||
valid: true,
|
||||
},
|
||||
mode: "auto",
|
||||
origin: "none",
|
||||
id: "workspace::AGENTS.md",
|
||||
title: "AGENTS.md",
|
||||
description: "Shared repo rules",
|
||||
kind: "instruction",
|
||||
source: "workspace",
|
||||
path: "/repo/AGENTS.md",
|
||||
approxTokens: 400,
|
||||
lineCount: 80,
|
||||
byteLen: 1600,
|
||||
writable: false,
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
entry: {
|
||||
id: "claudeWorkspace::CLAUDE.local.md",
|
||||
title: "CLAUDE.local.md",
|
||||
description: "Local Claude notes",
|
||||
kind: "instruction",
|
||||
source: "claudeWorkspace",
|
||||
path: "/repo/CLAUDE.local.md",
|
||||
approxTokens: 120,
|
||||
lineCount: 25,
|
||||
byteLen: 480,
|
||||
writable: false,
|
||||
valid: true,
|
||||
},
|
||||
mode: "auto",
|
||||
origin: "none",
|
||||
id: "claudeWorkspace::CLAUDE.local.md",
|
||||
title: "CLAUDE.local.md",
|
||||
description: "Local Claude notes",
|
||||
kind: "instruction",
|
||||
source: "claudeWorkspace",
|
||||
path: "/repo/CLAUDE.local.md",
|
||||
approxTokens: 120,
|
||||
lineCount: 25,
|
||||
byteLen: 480,
|
||||
writable: false,
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
entry: {
|
||||
id: "claudeAuto::MEMORY.md",
|
||||
title: "MEMORY.md",
|
||||
description: "Claude auto index",
|
||||
kind: "autoNote",
|
||||
source: "claudeAuto",
|
||||
path: "/home/.claude/projects/repo/memory/MEMORY.md",
|
||||
approxTokens: 100,
|
||||
lineCount: 20,
|
||||
byteLen: 400,
|
||||
writable: true,
|
||||
valid: true,
|
||||
},
|
||||
mode: "auto",
|
||||
origin: "none",
|
||||
id: "claudeAuto::MEMORY.md",
|
||||
title: "MEMORY.md",
|
||||
description: "Claude auto index",
|
||||
kind: "autoNote",
|
||||
source: "claudeAuto",
|
||||
path: "/home/.claude/projects/repo/memory/MEMORY.md",
|
||||
approxTokens: 100,
|
||||
lineCount: 20,
|
||||
byteLen: 400,
|
||||
writable: true,
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
entry: {
|
||||
id: "cursorWorkspace::react.mdc",
|
||||
title: "react.mdc",
|
||||
description: "Cursor TSX rules",
|
||||
kind: "rule",
|
||||
source: "cursorWorkspace",
|
||||
path: "/repo/.cursor/rules/react.mdc",
|
||||
paths: ["src/**/*.tsx"],
|
||||
approxTokens: 90,
|
||||
lineCount: 18,
|
||||
byteLen: 360,
|
||||
writable: false,
|
||||
valid: true,
|
||||
},
|
||||
mode: "auto",
|
||||
origin: "none",
|
||||
},
|
||||
{
|
||||
entry: {
|
||||
id: "workspace::untrusted.md",
|
||||
title: "untrusted.md",
|
||||
description: "Locked by workspace trust",
|
||||
kind: "instruction",
|
||||
source: "workspace",
|
||||
path: "/repo/untrusted.md",
|
||||
approxTokens: 50,
|
||||
lineCount: 10,
|
||||
byteLen: 200,
|
||||
writable: true,
|
||||
valid: true,
|
||||
},
|
||||
mode: "off",
|
||||
origin: "trust",
|
||||
id: "cursorWorkspace::react.mdc",
|
||||
title: "react.mdc",
|
||||
description: "Cursor TSX rules",
|
||||
kind: "rule",
|
||||
source: "cursorWorkspace",
|
||||
path: "/repo/.cursor/rules/react.mdc",
|
||||
paths: ["src/**/*.tsx"],
|
||||
approxTokens: 90,
|
||||
lineCount: 18,
|
||||
byteLen: 360,
|
||||
writable: false,
|
||||
valid: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function Harness({ provider }: { provider: string }) {
|
||||
const [overrides, setOverrides] = useState<AgentMemoryOverrides>({ autoMemory: null, entries: {} });
|
||||
function Harness({
|
||||
provider,
|
||||
catalog = CATALOG,
|
||||
onOpenFile,
|
||||
}: {
|
||||
provider: string;
|
||||
catalog?: AgentMemoryCatalog;
|
||||
onOpenFile?: (path: string) => void;
|
||||
}) {
|
||||
const [overrides, setOverrides] = useState<AgentMemoryOverrides>({ autoMemory: null });
|
||||
return (
|
||||
<MemoryPicker provider={provider} overrides={overrides} onChange={setOverrides} testData={{ catalog: CATALOG }} />
|
||||
<MemoryPicker
|
||||
provider={provider}
|
||||
overrides={overrides}
|
||||
onChange={setOverrides}
|
||||
onOpenFile={onOpenFile}
|
||||
testData={{ catalog }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe("MemoryPicker", () => {
|
||||
it("filters relevant entries for Claude, overrides Auto Memory and individual files, and resets", async () => {
|
||||
render(<Harness provider="claude" />);
|
||||
it("lists natively loaded files read-only (with Open) and lets native Claude override Auto Memory", async () => {
|
||||
const opened: string[] = [];
|
||||
render(<Harness provider="claude" onOpenFile={(p) => opened.push(p)} />);
|
||||
|
||||
const trigger = screen.getByRole("button", { name: "Memory" });
|
||||
// Claude sees workspace (2: AGENTS.md active, untrusted.md off), claudeWorkspace (1), claudeAuto (1) -> 3/4 active
|
||||
expect(trigger).toHaveTextContent("Memory3/4");
|
||||
expect(trigger).toHaveTextContent("Memory3");
|
||||
|
||||
fireEvent.click(trigger);
|
||||
expect(await screen.findByText("Session Memory")).toBeInTheDocument();
|
||||
@@ -196,25 +164,28 @@ describe("MemoryPicker", () => {
|
||||
expect(screen.getByText("CLAUDE.local.md")).toBeInTheDocument();
|
||||
expect(screen.getByText("MEMORY.md")).toBeInTheDocument();
|
||||
expect(screen.queryByText("react.mdc")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Untrusted workspace")).toBeInTheDocument();
|
||||
// No fake per-file switches
|
||||
expect(screen.queryByRole("switch")).not.toBeInTheDocument();
|
||||
|
||||
// Override Auto Memory to Read Only
|
||||
// Override Auto Memory to Off (Claude exposes Default / On / Off, not Read Only)
|
||||
const autoSelect = screen.getByRole("button", { name: "Session auto-memory mode" });
|
||||
fireEvent.click(autoSelect);
|
||||
fireEvent.click(within(screen.getByRole("listbox", { name: "Session auto-memory mode" })).getByText("Read Only"));
|
||||
const listbox = screen.getByRole("listbox", { name: "Session auto-memory mode" });
|
||||
expect(within(listbox).queryByText("Read Only")).not.toBeInTheDocument();
|
||||
fireEvent.click(within(listbox).getByText("Off"));
|
||||
expect(screen.getByText("Session")).toBeInTheDocument();
|
||||
|
||||
// Mute CLAUDE.local.md for this session
|
||||
fireEvent.click(screen.getByRole("switch", { name: "Enable CLAUDE.local.md for this session" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Memory" })).toHaveTextContent("Memory2/4"));
|
||||
expect(screen.getAllByText("Session")).toHaveLength(2);
|
||||
|
||||
// Reset clears both overrides
|
||||
// Reset clears auto-memory override
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Memory" })).toHaveTextContent("Memory3/4"));
|
||||
expect(screen.queryByText("Session")).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.queryByText("Session")).not.toBeInTheDocument());
|
||||
|
||||
// Clicking Open opens the file directly
|
||||
const openLinks = screen.getAllByRole("button", { name: "Open" });
|
||||
fireEvent.click(openLinks[0]!);
|
||||
expect(opened).toEqual(["/repo/AGENTS.md"]);
|
||||
});
|
||||
|
||||
it("shows Cursor rules and the ACP capability note when running an ACP provider without native auto-memory control", async () => {
|
||||
it("shows Cursor rules without auto-memory dropdown and with an honest footer note", async () => {
|
||||
render(<Harness provider="cursor" />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Memory" }));
|
||||
@@ -223,114 +194,95 @@ describe("MemoryPicker", () => {
|
||||
expect(screen.getByText("react.mdc")).toBeInTheDocument();
|
||||
expect(screen.queryByText("CLAUDE.local.md")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Session auto-memory mode" })).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("This agent manages its own memory. Set a file to Always in Settings to pass it to this agent."),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("Instruction files are loaded directly by this agent.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("resolves provider-specific entries across Codex, Copilot (including CLAUDE.md), Gemini, OpenCode, and Hermes profiles", () => {
|
||||
it("marks workspace files as Untrusted workspace when the project is untrusted", async () => {
|
||||
render(<Harness provider="claude" catalog={{ ...CATALOG, workspaceTrusted: false }} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Memory" }));
|
||||
expect(await screen.findAllByText("Untrusted workspace")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("enables per-session auto-memory control only for native claude and codex (not ACP adapters, copilot, or hermes)", () => {
|
||||
const extended: AgentMemoryCatalog = {
|
||||
...CATALOG,
|
||||
providers: [
|
||||
...CATALOG.providers,
|
||||
{
|
||||
provider: "hermes",
|
||||
label: "Hermes Agent",
|
||||
mode: "readWrite",
|
||||
origin: "none",
|
||||
noteCount: 2,
|
||||
rolloutCount: 0,
|
||||
approxTokens: 80,
|
||||
supportsAutoControl: true,
|
||||
supportsFileExclusion: false,
|
||||
supportsReset: true,
|
||||
},
|
||||
],
|
||||
entries: [
|
||||
...CATALOG.entries,
|
||||
{
|
||||
entry: {
|
||||
id: "codexAuto::memory_summary.md",
|
||||
title: "memory_summary.md",
|
||||
description: "Codex summary",
|
||||
kind: "autoNote",
|
||||
source: "codexAuto",
|
||||
path: "/home/.codex/memories/memory_summary.md",
|
||||
approxTokens: 150,
|
||||
lineCount: 30,
|
||||
byteLen: 600,
|
||||
writable: true,
|
||||
valid: true,
|
||||
},
|
||||
mode: "auto",
|
||||
origin: "none",
|
||||
id: "codexAuto::memory_summary.md",
|
||||
title: "memory_summary.md",
|
||||
description: "Codex summary",
|
||||
kind: "autoNote",
|
||||
source: "codexAuto",
|
||||
path: "/home/.codex/memories/memory_summary.md",
|
||||
approxTokens: 150,
|
||||
lineCount: 30,
|
||||
byteLen: 600,
|
||||
writable: true,
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
entry: {
|
||||
id: "geminiWorkspace::GEMINI.md",
|
||||
title: "GEMINI.md",
|
||||
description: "Gemini workspace rules",
|
||||
kind: "instruction",
|
||||
source: "geminiWorkspace",
|
||||
path: "/repo/GEMINI.md",
|
||||
approxTokens: 70,
|
||||
lineCount: 15,
|
||||
byteLen: 280,
|
||||
writable: false,
|
||||
valid: true,
|
||||
},
|
||||
mode: "auto",
|
||||
origin: "none",
|
||||
id: "geminiWorkspace::GEMINI.md",
|
||||
title: "GEMINI.md",
|
||||
description: "Gemini workspace rules",
|
||||
kind: "instruction",
|
||||
source: "geminiWorkspace",
|
||||
path: "/repo/GEMINI.md",
|
||||
approxTokens: 70,
|
||||
lineCount: 15,
|
||||
byteLen: 280,
|
||||
writable: false,
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
entry: {
|
||||
id: "hermesAuto::work/USER.md",
|
||||
title: "work/USER.md",
|
||||
description: "Hermes profile note",
|
||||
kind: "autoNote",
|
||||
source: "hermesAuto",
|
||||
path: "/home/.hermes/profiles/work/memories/USER.md",
|
||||
approxTokens: 60,
|
||||
lineCount: 12,
|
||||
byteLen: 240,
|
||||
writable: true,
|
||||
valid: true,
|
||||
},
|
||||
mode: "auto",
|
||||
origin: "none",
|
||||
id: "hermesAuto::work/USER.md",
|
||||
title: "work/USER.md",
|
||||
description: "Hermes profile note",
|
||||
kind: "autoNote",
|
||||
source: "hermesAuto",
|
||||
path: "/home/.hermes/profiles/work/memories/USER.md",
|
||||
approxTokens: 60,
|
||||
lineCount: 12,
|
||||
byteLen: 240,
|
||||
writable: true,
|
||||
valid: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Copilot natively reads `claudeWorkspace` (`CLAUDE.local.md`) + `workspace` (`AGENTS.md`), not `codexAuto` or `geminiWorkspace`.
|
||||
// Native Codex has per-session Read & Write / Read Only / Off control.
|
||||
const codex = resolveSessionMemory(extended, "codex");
|
||||
expect(codex.supportsSessionAutoControl).toBe(true);
|
||||
expect(codex.supportedModes).toEqual(["inherit", "readWrite", "readOnly", "off"]);
|
||||
expect(codex.groups.flatMap((g) => g.items.map((i) => i.id))).toContain("codexAuto::memory_summary.md");
|
||||
|
||||
// External ACP adapters (`codex-acp`, `claude-acp`) still see their native files, but have NO fake session control.
|
||||
const codexAcp = resolveSessionMemory(extended, "codex-acp");
|
||||
expect(codexAcp.supportsSessionAutoControl).toBe(false);
|
||||
expect(codexAcp.groups.flatMap((g) => g.items.map((i) => i.id))).toContain("codexAuto::memory_summary.md");
|
||||
|
||||
const claudeAcp = resolveSessionMemory(extended, "claude-acp");
|
||||
expect(claudeAcp.supportsSessionAutoControl).toBe(false);
|
||||
expect(claudeAcp.groups.flatMap((g) => g.items.map((i) => i.id))).toContain("claudeWorkspace::CLAUDE.local.md");
|
||||
|
||||
// Copilot sees `CLAUDE.local.md` + `AGENTS.md`, without fake session auto-memory control.
|
||||
const copilot = resolveSessionMemory(extended, "copilot");
|
||||
expect(copilot.supportsAutoControl).toBe(true);
|
||||
expect(copilot.supportsSessionAutoControl).toBe(false);
|
||||
const copilotIds = copilot.groups.flatMap((g) => g.items.map((i) => i.id));
|
||||
expect(copilotIds).toContain("workspace::AGENTS.md");
|
||||
expect(copilotIds).toContain("claudeWorkspace::CLAUDE.local.md");
|
||||
expect(copilotIds).not.toContain("codexAuto::memory_summary.md");
|
||||
|
||||
// Codex sees `codexAuto` (`codex-acp` normalizes to `codex`).
|
||||
const codex = resolveSessionMemory(extended, "codex-acp");
|
||||
expect(codex.supportsAutoControl).toBe(true);
|
||||
expect(codex.groups.flatMap((g) => g.items.map((i) => i.id))).toContain("codexAuto::memory_summary.md");
|
||||
|
||||
// Gemini sees `GEMINI.md` and lacks native auto-memory toggle (`supportsAutoControl: false`).
|
||||
// Gemini sees `GEMINI.md` without session auto-memory control.
|
||||
const gemini = resolveSessionMemory(extended, "gemini");
|
||||
expect(gemini.supportsAutoControl).toBe(false);
|
||||
expect(gemini.supportsSessionAutoControl).toBe(false);
|
||||
expect(gemini.groups.flatMap((g) => g.items.map((i) => i.id))).toContain("geminiWorkspace::GEMINI.md");
|
||||
|
||||
// OpenCode (generic ACP) sees portable `workspace::AGENTS.md` only.
|
||||
const opencode = resolveSessionMemory(extended, "opencode");
|
||||
expect(opencode.supportsAutoControl).toBe(false);
|
||||
expect(opencode.groups.flatMap((g) => g.items.map((i) => i.id))).toEqual([
|
||||
"workspace::AGENTS.md",
|
||||
"workspace::untrusted.md",
|
||||
]);
|
||||
|
||||
// Named Hermes profile (`hermes-work`) normalizes to `hermes` and sees `hermesAuto` with auto-memory control!
|
||||
// Hermes (`hermes-work`) sees `hermesAuto`, marked nativeConfigOnly (no session override).
|
||||
const hermes = resolveSessionMemory(extended, "hermes-work");
|
||||
expect(hermes.supportsAutoControl).toBe(true);
|
||||
expect(hermes.supportsSessionAutoControl).toBe(false);
|
||||
expect(hermes.nativeConfigOnly).toBe(true);
|
||||
expect(hermes.groups.flatMap((g) => g.items.map((i) => i.id))).toContain("hermesAuto::work/USER.md");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
/**
|
||||
* Per-session memory picker for the New Task and Session composers: shows cross-session
|
||||
* Auto-Memory control plus discovered instruction files, path-scoped rules, and learned
|
||||
* memory notes, lets the user override them for this session only, reset overrides, or
|
||||
* jump to Settings › Agents › Memory.
|
||||
* Per-session memory inspector & auto-memory override for New Task, Session, and Automation
|
||||
* composers: shows the instruction files, path-scoped rules, and learned auto-memory notes
|
||||
* natively loaded by the selected agent (with one-click open), plus a per-session Auto-Memory
|
||||
* selector only for native drivers that enforce it (Claude Code, Codex).
|
||||
*/
|
||||
import { useMemo } from "react";
|
||||
import type { AgentMemoryCatalog, AgentMemoryOverrides, AutoMemoryMode } from "@/bindings";
|
||||
import { formatMessage, useTx } from "@/platform/i18n";
|
||||
import { Select, T } from "@/ui";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { MEMORY_PAGE } from "./model";
|
||||
import {
|
||||
MEMORY_SOURCE_GROUPS,
|
||||
memoryGroupTitle,
|
||||
autoMemoryModeLabel,
|
||||
defaultMemoryBackend,
|
||||
memoryGroupTitle,
|
||||
nextAutoMemoryOverride,
|
||||
nextMemoryEntryOverrides,
|
||||
refreshMemoryCatalog,
|
||||
resolveSessionMemory,
|
||||
useMemoryCatalog,
|
||||
@@ -26,10 +27,10 @@ import {
|
||||
import {
|
||||
PickerEmpty,
|
||||
PickerGroupLabel,
|
||||
PickerInlineLink,
|
||||
PickerPill,
|
||||
PickerRow,
|
||||
PickerSessionPill,
|
||||
PickerToggle,
|
||||
SessionPicker,
|
||||
} from "./SessionPicker";
|
||||
import styles from "./MemoryPage.module.css";
|
||||
@@ -43,18 +44,12 @@ export interface MemoryPickerProps {
|
||||
openRequest?: number;
|
||||
hideTrigger?: boolean;
|
||||
backend?: MemoryBackend;
|
||||
onOpenFile?: (filePath: string) => void;
|
||||
testData?: {
|
||||
catalog: AgentMemoryCatalog;
|
||||
};
|
||||
}
|
||||
|
||||
const AUTO_MEMORY_OPTIONS: ReadonlyArray<{ value: AutoMemoryMode; label: string }> = [
|
||||
{ value: "inherit", label: "Inherit" },
|
||||
{ value: "readWrite", label: "Read & Write" },
|
||||
{ value: "readOnly", label: "Read Only" },
|
||||
{ value: "off", label: "Off" },
|
||||
];
|
||||
|
||||
export function MemoryPicker({
|
||||
provider,
|
||||
overrides,
|
||||
@@ -64,6 +59,7 @@ export function MemoryPicker({
|
||||
openRequest = 0,
|
||||
hideTrigger = false,
|
||||
backend = defaultMemoryBackend,
|
||||
onOpenFile,
|
||||
testData,
|
||||
}: MemoryPickerProps) {
|
||||
const tx = useTx();
|
||||
@@ -73,61 +69,77 @@ export function MemoryPicker({
|
||||
|
||||
const resolved = useMemo(() => resolveSessionMemory(catalog, provider, overrides), [catalog, provider, overrides]);
|
||||
|
||||
const handleToggleItem = (item: Pick<SessionMemoryItem, "id" | "defaultMode">, nextEnabled: boolean) => {
|
||||
onChange(nextMemoryEntryOverrides(overrides, item, nextEnabled));
|
||||
const handleAutoMemory = (nextMode: AutoMemoryMode) => {
|
||||
onChange(nextAutoMemoryOverride(resolved.defaultAutoMemory, nextMode));
|
||||
};
|
||||
|
||||
const handleAutoMemory = (nextMode: AutoMemoryMode) => {
|
||||
onChange(nextAutoMemoryOverride(overrides, resolved.defaultAutoMemory, nextMode));
|
||||
const openFile = (filePath: string, close: () => void) => {
|
||||
close();
|
||||
if (onOpenFile) {
|
||||
onOpenFile(filePath);
|
||||
} else {
|
||||
void editorService().openFile(filePath, { focus: true });
|
||||
}
|
||||
};
|
||||
|
||||
const footerLead = resolved.supportsSessionAutoControl ? (
|
||||
busy ? (
|
||||
<T>Changes apply on the next message.</T>
|
||||
) : (
|
||||
<T>Auto-memory override applies to this session only.</T>
|
||||
)
|
||||
) : (
|
||||
<T>Instruction files are loaded directly by this agent.</T>
|
||||
);
|
||||
|
||||
return (
|
||||
<SessionPicker
|
||||
icon="history"
|
||||
brand="Memory"
|
||||
triggerTitles={{
|
||||
plain: tx("Memory ({active}/{total} active)"),
|
||||
withOverrides: tx("Memory ({active}/{total} active · {overrides} session overrides)"),
|
||||
plain: tx("Memory ({total} files)"),
|
||||
withOverrides: tx("Memory ({total} files · auto-memory overridden)"),
|
||||
}}
|
||||
triggerAriaLabel={tx("Memory")}
|
||||
popupTitle={tx("Session Memory")}
|
||||
settingsTitle={tx("Memory…")}
|
||||
settingsPage={MEMORY_PAGE}
|
||||
counts={{ active: resolved.activeCount, total: resolved.totalCount, overrides: resolved.overrideCount }}
|
||||
counts={{ active: resolved.totalCount, total: resolved.totalCount, overrides: resolved.overrideCount }}
|
||||
search={{ placeholder: tx("Filter memories…"), ariaLabel: tx("Filter memories"), shown: resolved.totalCount > 5 }}
|
||||
disabled={disabled}
|
||||
busy={busy}
|
||||
openRequest={openRequest}
|
||||
hideTrigger={hideTrigger}
|
||||
refresh={testData ? undefined : () => void refreshMemoryCatalog(backend)}
|
||||
onReset={() => onChange({ autoMemory: null, entries: {} })}
|
||||
onReset={() => onChange({ autoMemory: null })}
|
||||
footerLead={footerLead}
|
||||
footerNote={
|
||||
<>
|
||||
{resolved.activeTokens > 0 && (
|
||||
<span>{formatMessage(tx("~{tokens} tokens active"), { tokens: resolved.activeTokens })}</span>
|
||||
{resolved.approxTokens > 0 && (
|
||||
<span>{formatMessage(tx("~{tokens} tokens"), { tokens: resolved.approxTokens })}</span>
|
||||
)}
|
||||
{!resolved.supportsAutoControl && (
|
||||
{resolved.nativeConfigOnly && (
|
||||
<span>
|
||||
<T>This agent manages its own memory. Set a file to Always in Settings to pass it to this agent.</T>
|
||||
<T>Configure Hermes auto-memory in Settings › Agents › Rules & Memory.</T>
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{(query) => {
|
||||
{(query, controls) => {
|
||||
const q = query.trim().toLowerCase();
|
||||
const matchesQuery = (item: SessionMemoryItem) =>
|
||||
!q ||
|
||||
item.state.entry.title.toLowerCase().includes(q) ||
|
||||
item.state.entry.description.toLowerCase().includes(q) ||
|
||||
item.state.entry.path.toLowerCase().includes(q);
|
||||
item.entry.title.toLowerCase().includes(q) ||
|
||||
item.entry.description.toLowerCase().includes(q) ||
|
||||
item.entry.path.toLowerCase().includes(q);
|
||||
const groups = resolved.groups
|
||||
.map((group) => ({ ...group, items: group.items.filter(matchesQuery) }))
|
||||
.filter((group) => group.items.length > 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
{resolved.supportsAutoControl && (
|
||||
{resolved.supportsSessionAutoControl && (
|
||||
<div className={styles.autoRow}>
|
||||
<div className={styles.autoInfo}>
|
||||
<span className={styles.autoTitle}>
|
||||
@@ -141,7 +153,10 @@ export function MemoryPicker({
|
||||
<Select
|
||||
aria-label={tx("Session auto-memory mode")}
|
||||
value={resolved.autoMemory}
|
||||
options={AUTO_MEMORY_OPTIONS.map((o) => ({ value: o.value, label: tx(o.label) }))}
|
||||
options={resolved.supportedModes.map((mode) => ({
|
||||
value: mode,
|
||||
label: autoMemoryModeLabel(mode, resolved.supportedModes, tx),
|
||||
}))}
|
||||
onChange={handleAutoMemory}
|
||||
/>
|
||||
</div>
|
||||
@@ -152,7 +167,7 @@ export function MemoryPicker({
|
||||
key={group.source}
|
||||
source={group.source}
|
||||
items={group.items}
|
||||
onToggle={handleToggleItem}
|
||||
onOpen={(path) => openFile(path, controls.close)}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -171,11 +186,11 @@ export function MemoryPicker({
|
||||
function MemoryGroupRows({
|
||||
source,
|
||||
items,
|
||||
onToggle,
|
||||
onOpen,
|
||||
}: {
|
||||
source: ResolvedSessionMemory["groups"][number]["source"];
|
||||
items: readonly SessionMemoryItem[];
|
||||
onToggle: (item: SessionMemoryItem, enabled: boolean) => void;
|
||||
onOpen: (filePath: string) => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const group = MEMORY_SOURCE_GROUPS[source];
|
||||
@@ -183,15 +198,15 @@ function MemoryGroupRows({
|
||||
<>
|
||||
<PickerGroupLabel title={group.paths}>{memoryGroupTitle(source, tx)}</PickerGroupLabel>
|
||||
{items.map((item) => (
|
||||
<SessionMemoryRow key={item.id} item={item} onToggle={(on) => onToggle(item, on)} />
|
||||
<SessionMemoryRow key={item.id} item={item} onOpen={() => onOpen(item.entry.path)} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SessionMemoryRow({ item, onToggle }: { item: SessionMemoryItem; onToggle: (enabled: boolean) => void }) {
|
||||
function SessionMemoryRow({ item, onOpen }: { item: SessionMemoryItem; onOpen: () => void }) {
|
||||
const tx = useTx();
|
||||
const { entry } = item.state;
|
||||
const { entry } = item;
|
||||
return (
|
||||
<PickerRow
|
||||
name={entry.title}
|
||||
@@ -203,22 +218,19 @@ function SessionMemoryRow({ item, onToggle }: { item: SessionMemoryItem; onToggl
|
||||
</PickerPill>
|
||||
)}
|
||||
{(entry.paths?.length ?? 0) > 0 && <PickerPill>paths</PickerPill>}
|
||||
{item.overridden && <PickerSessionPill />}
|
||||
</>
|
||||
}
|
||||
sub={entry.description || undefined}
|
||||
subTitle={entry.paths?.length ? `${entry.description} · ${entry.paths.join(", ")}` : entry.description}
|
||||
controls={
|
||||
item.locked ? (
|
||||
item.untrusted ? (
|
||||
<PickerPill>
|
||||
<T>Untrusted workspace</T>
|
||||
</PickerPill>
|
||||
) : (
|
||||
<PickerToggle
|
||||
enabled={item.mode !== "off"}
|
||||
ariaLabel={formatMessage(tx("Enable {name} for this session"), { name: entry.title })}
|
||||
onChange={onToggle}
|
||||
/>
|
||||
<PickerInlineLink title={formatMessage(tx("Open {file}"), { file: entry.path })} onClick={onOpen}>
|
||||
<T>Open</T>
|
||||
</PickerInlineLink>
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -40,7 +40,9 @@ interface SessionPickerProps {
|
||||
/** Reloads the catalog whenever the popup opens; omit when the data is supplied. */
|
||||
refresh?: () => void;
|
||||
onReset: () => void;
|
||||
/** Extra footer lines below the "applies to this session" note. */
|
||||
/** Replaces the default "Toggles here apply to this session only." line when provided. */
|
||||
footerLead?: ReactNode;
|
||||
/** Extra footer lines below the lead note. */
|
||||
footerNote?: ReactNode;
|
||||
/** Receives the popup's filter query and controls. */
|
||||
children: (query: string, controls: SessionPickerControls) => ReactNode;
|
||||
@@ -61,6 +63,7 @@ export function SessionPicker({
|
||||
hideTrigger,
|
||||
refresh,
|
||||
onReset,
|
||||
footerLead,
|
||||
footerNote,
|
||||
children,
|
||||
settingsPage,
|
||||
@@ -180,7 +183,8 @@ export function SessionPicker({
|
||||
|
||||
<div className={styles.footer}>
|
||||
<span>
|
||||
{busy ? <T>Changes apply on the next message.</T> : <T>Toggles here apply to this session only.</T>}
|
||||
{footerLead ??
|
||||
(busy ? <T>Changes apply on the next message.</T> : <T>Toggles here apply to this session only.</T>)}
|
||||
</span>
|
||||
{footerNote}
|
||||
</div>
|
||||
|
||||
@@ -34,9 +34,7 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
|
||||
mcpRegistryUrl: "",
|
||||
skills: {},
|
||||
memory: {
|
||||
autoMemory: "inherit",
|
||||
providers: {},
|
||||
entries: {},
|
||||
},
|
||||
plugins: {
|
||||
marketplaces: [],
|
||||
|
||||
@@ -124,8 +124,7 @@ beforeEach(() => {
|
||||
data: {
|
||||
entries: [],
|
||||
providers: [],
|
||||
autoMemory: "inherit",
|
||||
autoMemoryOrigin: "none",
|
||||
workspaceTrusted: true,
|
||||
},
|
||||
});
|
||||
clipboardImage.mockReset().mockResolvedValue({
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
/**
|
||||
* Shared agent-memory model behind Settings › Agents › Memory and the composer MemoryPicker:
|
||||
* Shared agent-memory model behind Settings › Agents › Rules & Memory and the composer MemoryPicker:
|
||||
* discovered instruction files, path-scoped rules, and learned auto-memories across agents,
|
||||
* plus per-session overrides (`AgentTask.memoryOverrides`).
|
||||
* plus per-provider and per-session auto-memory policy for native drivers that enforce it.
|
||||
*/
|
||||
import { useEffect } from "react";
|
||||
import { create } from "zustand";
|
||||
import type {
|
||||
AgentMemoryCatalog,
|
||||
AgentMemoryMode,
|
||||
AgentMemoryEntry,
|
||||
AgentMemoryOverrides,
|
||||
AgentMemorySource,
|
||||
AgentMemoryState,
|
||||
AutoMemoryMode,
|
||||
CreateAgentMemoryInput,
|
||||
McpScope,
|
||||
@@ -18,19 +17,17 @@ import type {
|
||||
} from "@/bindings";
|
||||
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { matchesAgentProvider, normalizeProviderId } from "./mcpModel";
|
||||
import { normalizeProviderId } from "./mcpModel";
|
||||
|
||||
export const EMPTY_MEMORY_CATALOG: AgentMemoryCatalog = {
|
||||
entries: [],
|
||||
providers: [],
|
||||
autoMemory: "inherit",
|
||||
autoMemoryOrigin: "none",
|
||||
workspaceTrusted: true,
|
||||
};
|
||||
|
||||
export interface MemoryBackend {
|
||||
list(): Promise<AgentMemoryCatalog>;
|
||||
setMode(id: string, scope: McpScope, mode: AgentMemoryMode, agents?: string[]): Promise<AgentMemoryCatalog>;
|
||||
setAuto(scope: McpScope, provider: string | null, mode: AutoMemoryMode): Promise<AgentMemoryCatalog>;
|
||||
setAuto(scope: McpScope, provider: string, mode: AutoMemoryMode): Promise<AgentMemoryCatalog>;
|
||||
create?(input: CreateAgentMemoryInput): Promise<AgentMemoryCatalog>;
|
||||
promote?(input: PromoteAgentMemoryInput): Promise<AgentMemoryCatalog>;
|
||||
remove?(id: string): Promise<AgentMemoryCatalog>;
|
||||
@@ -42,7 +39,6 @@ export const defaultMemoryBackend: MemoryBackend = {
|
||||
isTauri() && typeof commands.agentMemoryList === "function"
|
||||
? call(commands.agentMemoryList())
|
||||
: Promise.resolve(useMemoryCatalog.getState().catalog),
|
||||
setMode: (id, scope, mode, agents = []) => call(commands.agentMemorySetMode(id, scope, mode, agents)),
|
||||
setAuto: (scope, provider, mode) => call(commands.agentMemorySetAuto(scope, provider, mode)),
|
||||
create: (input) => call(commands.agentMemoryCreate(input)),
|
||||
promote: (input) => call(commands.agentMemoryPromote(input)),
|
||||
@@ -59,6 +55,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: string;
|
||||
agent: string | null;
|
||||
isAuto: boolean;
|
||||
isWorkspace: boolean;
|
||||
}
|
||||
> = {
|
||||
workspace: {
|
||||
@@ -67,6 +64,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "AGENTS.md · AGENTS.override.md",
|
||||
agent: null,
|
||||
isAuto: false,
|
||||
isWorkspace: true,
|
||||
},
|
||||
claudeWorkspace: {
|
||||
label: "Claude Code",
|
||||
@@ -74,6 +72,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "CLAUDE.md · CLAUDE.local.md · .claude/rules",
|
||||
agent: "claude",
|
||||
isAuto: false,
|
||||
isWorkspace: true,
|
||||
},
|
||||
claudeUser: {
|
||||
label: "Claude Code",
|
||||
@@ -81,6 +80,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "~/.claude/CLAUDE.md · ~/.claude/rules",
|
||||
agent: "claude",
|
||||
isAuto: false,
|
||||
isWorkspace: false,
|
||||
},
|
||||
claudeAuto: {
|
||||
label: "Claude Code",
|
||||
@@ -88,6 +88,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "~/.claude/projects/…/memory",
|
||||
agent: "claude",
|
||||
isAuto: true,
|
||||
isWorkspace: false,
|
||||
},
|
||||
githubWorkspace: {
|
||||
label: "GitHub Copilot",
|
||||
@@ -95,6 +96,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: ".github/copilot-instructions.md · .github/instructions",
|
||||
agent: "copilot",
|
||||
isAuto: false,
|
||||
isWorkspace: true,
|
||||
},
|
||||
copilotUser: {
|
||||
label: "GitHub Copilot",
|
||||
@@ -102,6 +104,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "~/.copilot/copilot-instructions.md · ~/.copilot/instructions",
|
||||
agent: "copilot",
|
||||
isAuto: false,
|
||||
isWorkspace: false,
|
||||
},
|
||||
codexUser: {
|
||||
label: "Codex",
|
||||
@@ -109,6 +112,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "~/.codex/AGENTS.md",
|
||||
agent: "codex",
|
||||
isAuto: false,
|
||||
isWorkspace: false,
|
||||
},
|
||||
codexAuto: {
|
||||
label: "Codex",
|
||||
@@ -116,6 +120,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "~/.codex/memories",
|
||||
agent: "codex",
|
||||
isAuto: true,
|
||||
isWorkspace: false,
|
||||
},
|
||||
cursorWorkspace: {
|
||||
label: "Cursor",
|
||||
@@ -123,6 +128,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: ".cursor/rules · .cursorrules",
|
||||
agent: "cursor",
|
||||
isAuto: false,
|
||||
isWorkspace: true,
|
||||
},
|
||||
geminiWorkspace: {
|
||||
label: "Gemini CLI",
|
||||
@@ -130,6 +136,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "GEMINI.md",
|
||||
agent: "gemini",
|
||||
isAuto: false,
|
||||
isWorkspace: true,
|
||||
},
|
||||
geminiUser: {
|
||||
label: "Gemini CLI",
|
||||
@@ -137,6 +144,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "~/.gemini/GEMINI.md",
|
||||
agent: "gemini",
|
||||
isAuto: false,
|
||||
isWorkspace: false,
|
||||
},
|
||||
hermesAuto: {
|
||||
label: "Hermes Agent",
|
||||
@@ -144,6 +152,7 @@ export const MEMORY_SOURCE_GROUPS: Record<
|
||||
paths: "~/.hermes/memories",
|
||||
agent: "hermes",
|
||||
isAuto: true,
|
||||
isWorkspace: false,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -153,46 +162,78 @@ export function memoryGroupTitle(source: AgentMemorySource, tx: (text: string) =
|
||||
return qualifier ? `${tx(label)} (${tx(qualifier)})` : tx(label);
|
||||
}
|
||||
|
||||
/** Label for an auto-memory mode tailored to what that provider supports. */
|
||||
export function autoMemoryModeLabel(
|
||||
mode: AutoMemoryMode,
|
||||
supportedModes: readonly AutoMemoryMode[],
|
||||
tx: (text: string) => string,
|
||||
): string {
|
||||
switch (mode) {
|
||||
case "inherit":
|
||||
return tx("Default");
|
||||
case "readWrite":
|
||||
return supportedModes.includes("readOnly") ? tx("Read & Write") : tx("On");
|
||||
case "readOnly":
|
||||
return tx("Read Only");
|
||||
case "off":
|
||||
return tx("Off");
|
||||
}
|
||||
}
|
||||
|
||||
/** Human-readable list of which agents natively load `entry`. */
|
||||
export function nativeReadersLabel(entry: AgentMemoryEntry, tx: (text: string) => string): string {
|
||||
if (entry.source === "workspace") return tx("All coding agents");
|
||||
if (entry.source === "claudeWorkspace") return `${tx("Claude Code")} · ${tx("GitHub Copilot")}`;
|
||||
return tx(MEMORY_SOURCE_GROUPS[entry.source].label);
|
||||
}
|
||||
|
||||
/** Normalizes a provider id for discovering which files that agent family reads natively. */
|
||||
export function normalizeMemoryProvider(provider: string): string {
|
||||
const norm = normalizeProviderId(provider);
|
||||
return norm === "hermes" || norm.startsWith("hermes-") ? "hermes" : norm;
|
||||
}
|
||||
|
||||
/** Exact provider key for auto-memory control (keeps `claude-acp` / `codex-acp` distinct from native drivers). */
|
||||
export function autoMemoryControlKey(provider: string): string {
|
||||
const trimmed = provider.trim();
|
||||
return trimmed === "hermes" || trimmed.startsWith("hermes-") ? "hermes" : trimmed;
|
||||
}
|
||||
|
||||
export function isDiscoveredMemorySource(source: AgentMemorySource): boolean {
|
||||
return source !== "workspace";
|
||||
}
|
||||
|
||||
/** Whether `entry` applies to a session running `provider` unless explicitly forced on. */
|
||||
export function appliesToProvider(state: AgentMemoryState, provider: string): boolean {
|
||||
if (!matchesAgentProvider(state.agents, provider)) return false;
|
||||
const group = MEMORY_SOURCE_GROUPS[state.entry.source];
|
||||
export function isWorkspaceMemorySource(source: AgentMemorySource): boolean {
|
||||
return MEMORY_SOURCE_GROUPS[source].isWorkspace;
|
||||
}
|
||||
|
||||
/** Whether `entry` is natively loaded by a session running `provider`. */
|
||||
export function appliesToProvider(entry: AgentMemoryEntry, provider: string): boolean {
|
||||
const group = MEMORY_SOURCE_GROUPS[entry.source];
|
||||
if (!group.agent) return true;
|
||||
const norm = normalizeMemoryProvider(provider);
|
||||
// Copilot also reads `CLAUDE.md` natively; Claude reads `AGENTS.md`.
|
||||
if (norm === "copilot" && state.entry.source === "claudeWorkspace") return true;
|
||||
// Copilot also reads `CLAUDE.md` natively.
|
||||
if (norm === "copilot" && entry.source === "claudeWorkspace") return true;
|
||||
return group.agent === norm;
|
||||
}
|
||||
|
||||
export interface SessionMemoryItem {
|
||||
id: string;
|
||||
state: AgentMemoryState;
|
||||
defaultMode: AgentMemoryMode;
|
||||
mode: AgentMemoryMode;
|
||||
overridden: boolean;
|
||||
locked: boolean;
|
||||
entry: AgentMemoryEntry;
|
||||
untrusted: boolean;
|
||||
}
|
||||
|
||||
export interface ResolvedSessionMemory {
|
||||
groups: Array<{ source: AgentMemorySource; items: SessionMemoryItem[] }>;
|
||||
supportedModes: AutoMemoryMode[];
|
||||
defaultAutoMemory: AutoMemoryMode;
|
||||
autoMemory: AutoMemoryMode;
|
||||
autoMemoryOverridden: boolean;
|
||||
supportsAutoControl: boolean;
|
||||
supportsFileExclusion: boolean;
|
||||
activeCount: number;
|
||||
supportsSessionAutoControl: boolean;
|
||||
nativeConfigOnly: boolean;
|
||||
totalCount: number;
|
||||
overrideCount: number;
|
||||
activeTokens: number;
|
||||
approxTokens: number;
|
||||
}
|
||||
|
||||
export function resolveSessionMemory(
|
||||
@@ -200,92 +241,63 @@ export function resolveSessionMemory(
|
||||
provider: string,
|
||||
overrides?: AgentMemoryOverrides | null,
|
||||
): ResolvedSessionMemory {
|
||||
const norm = normalizeMemoryProvider(provider);
|
||||
const provStatus =
|
||||
catalog.providers.find((p) => p.provider === norm) ?? catalog.providers.find((p) => p.provider === "acp");
|
||||
const defaultAutoMemory = provStatus?.mode ?? catalog.autoMemory;
|
||||
const explicitAuto = overrides?.autoMemory ?? undefined;
|
||||
const controlKey = autoMemoryControlKey(provider);
|
||||
const provStatus = catalog.providers.find((p) => p.provider === controlKey);
|
||||
const supportedModes = provStatus?.supportedModes ?? [];
|
||||
const nativeConfigOnly = provStatus?.nativeConfigOnly ?? false;
|
||||
const supportsSessionAutoControl = !nativeConfigOnly && supportedModes.length > 0;
|
||||
const defaultAutoMemory = provStatus?.mode ?? "inherit";
|
||||
const rawExplicit = overrides?.autoMemory ?? undefined;
|
||||
const explicitAuto =
|
||||
supportsSessionAutoControl && rawExplicit && supportedModes.includes(rawExplicit) ? rawExplicit : undefined;
|
||||
const autoMemory = explicitAuto ?? defaultAutoMemory;
|
||||
const autoMemoryOverridden = explicitAuto !== undefined && explicitAuto !== defaultAutoMemory;
|
||||
|
||||
const entryOverrides = overrides?.entries ?? {};
|
||||
const relevant = catalog.entries.filter(
|
||||
(s) => appliesToProvider(s, provider) || entryOverrides[s.entry.id] !== undefined,
|
||||
);
|
||||
|
||||
const items = relevant.map<SessionMemoryItem>((state) => {
|
||||
const locked = state.origin === "trust";
|
||||
const explicit = entryOverrides[state.entry.id];
|
||||
const mode = locked ? "off" : (explicit ?? state.mode);
|
||||
return {
|
||||
id: state.entry.id,
|
||||
state,
|
||||
defaultMode: state.mode,
|
||||
mode,
|
||||
overridden: !locked && explicit !== undefined && explicit !== state.mode,
|
||||
locked,
|
||||
};
|
||||
});
|
||||
const relevant = catalog.entries.filter((entry) => appliesToProvider(entry, provider));
|
||||
const items = relevant.map<SessionMemoryItem>((entry) => ({
|
||||
id: entry.id,
|
||||
entry,
|
||||
untrusted: !catalog.workspaceTrusted && isWorkspaceMemorySource(entry.source),
|
||||
}));
|
||||
|
||||
const groups: ResolvedSessionMemory["groups"] = [];
|
||||
const seen = new Set<AgentMemorySource>();
|
||||
for (const item of items) {
|
||||
const src = item.state.entry.source;
|
||||
const src = item.entry.source;
|
||||
if (seen.has(src)) continue;
|
||||
seen.add(src);
|
||||
groups.push({
|
||||
source: src,
|
||||
items: items.filter((i) => i.state.entry.source === src),
|
||||
items: items.filter((i) => i.entry.source === src),
|
||||
});
|
||||
}
|
||||
|
||||
const activeItems = items.filter((i) => i.mode !== "off");
|
||||
const activeTokens = activeItems.reduce(
|
||||
(sum, i) => sum + ((i.state.entry.paths?.length ?? 0) > 0 && i.mode !== "always" ? 0 : i.state.entry.approxTokens),
|
||||
0,
|
||||
);
|
||||
const overrideCount = items.filter((i) => i.overridden).length + (autoMemoryOverridden ? 1 : 0);
|
||||
const approxTokens = items.reduce((sum, i) => {
|
||||
if (i.untrusted) return sum;
|
||||
if ((i.entry.paths?.length ?? 0) > 0) return sum;
|
||||
return sum + i.entry.approxTokens;
|
||||
}, 0);
|
||||
|
||||
return {
|
||||
groups,
|
||||
supportedModes,
|
||||
defaultAutoMemory,
|
||||
autoMemory,
|
||||
autoMemoryOverridden,
|
||||
supportsAutoControl: provStatus?.supportsAutoControl ?? false,
|
||||
supportsFileExclusion: provStatus?.supportsFileExclusion ?? false,
|
||||
activeCount: activeItems.length,
|
||||
supportsSessionAutoControl,
|
||||
nativeConfigOnly,
|
||||
totalCount: items.length,
|
||||
overrideCount,
|
||||
activeTokens,
|
||||
};
|
||||
}
|
||||
|
||||
export function nextMemoryEntryOverrides(
|
||||
current: AgentMemoryOverrides | null | undefined,
|
||||
item: Pick<SessionMemoryItem, "id" | "defaultMode">,
|
||||
nextEnabled: boolean,
|
||||
): AgentMemoryOverrides {
|
||||
const entries = { ...(current?.entries ?? {}) };
|
||||
const defaultEnabled = item.defaultMode !== "off";
|
||||
if (nextEnabled === defaultEnabled) {
|
||||
delete entries[item.id];
|
||||
} else {
|
||||
entries[item.id] = nextEnabled ? "auto" : "off";
|
||||
}
|
||||
return {
|
||||
autoMemory: current?.autoMemory ?? null,
|
||||
entries,
|
||||
overrideCount: autoMemoryOverridden ? 1 : 0,
|
||||
approxTokens,
|
||||
};
|
||||
}
|
||||
|
||||
export function nextAutoMemoryOverride(
|
||||
current: AgentMemoryOverrides | null | undefined,
|
||||
defaultAutoMemory: AutoMemoryMode,
|
||||
nextMode: AutoMemoryMode,
|
||||
): AgentMemoryOverrides {
|
||||
return {
|
||||
autoMemory: nextMode === defaultAutoMemory ? null : nextMode,
|
||||
entries: { ...(current?.entries ?? {}) },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1932,7 +1932,7 @@ export function setDraftSkillOverrides(skillOverrides: Record<string, AgentSkill
|
||||
}
|
||||
|
||||
export function setDraftMemoryOverrides(memoryOverrides: AgentMemoryOverrides) {
|
||||
const isEmpty = memoryOverrides.autoMemory == null && Object.keys(memoryOverrides.entries ?? {}).length === 0;
|
||||
const isEmpty = memoryOverrides.autoMemory == null;
|
||||
updateDraft({ memoryOverrides: isEmpty ? undefined : memoryOverrides });
|
||||
}
|
||||
|
||||
@@ -1963,7 +1963,7 @@ export async function setTaskSkillOverrides(task: string, overrides: Record<stri
|
||||
}
|
||||
|
||||
export async function setTaskMemoryOverrides(task: string, overrides: AgentMemoryOverrides): Promise<void> {
|
||||
const isEmpty = overrides.autoMemory == null && Object.keys(overrides.entries ?? {}).length === 0;
|
||||
const isEmpty = overrides.autoMemory == null;
|
||||
const prev = useAgents.getState().tasks.get(task);
|
||||
if (prev) {
|
||||
useAgents.setState((s) => ({
|
||||
|
||||
@@ -32,9 +32,7 @@ describe("agent chat settings", () => {
|
||||
mcpRegistryUrl: "",
|
||||
skills: {},
|
||||
memory: {
|
||||
autoMemory: "inherit",
|
||||
providers: {},
|
||||
entries: {},
|
||||
},
|
||||
plugins: {
|
||||
marketplaces: [],
|
||||
|
||||
@@ -312,9 +312,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
mcpRegistryUrl: "",
|
||||
skills: {},
|
||||
memory: {
|
||||
autoMemory: "inherit",
|
||||
providers: {},
|
||||
entries: {},
|
||||
},
|
||||
plugins: {
|
||||
marketplaces: [],
|
||||
@@ -414,27 +412,12 @@ function agentSkillPolicies(v: unknown): Required<AgentSettings>["skills"] {
|
||||
function agentMemorySettings(v: unknown): Required<AgentSettings>["memory"] {
|
||||
const m = obj(v);
|
||||
const autoModes = ["inherit", "readWrite", "readOnly", "off"] as const;
|
||||
const entryModes = ["auto", "always", "off"] as const;
|
||||
const providers: NonNullable<Required<AgentSettings>["memory"]["providers"]> = {};
|
||||
for (const [id, raw] of Object.entries(obj(m.providers))) {
|
||||
if (!id.trim()) continue;
|
||||
providers[id] = { autoMemory: oneOf(obj(raw).autoMemory, autoModes, "inherit") };
|
||||
}
|
||||
const entries: NonNullable<Required<AgentSettings>["memory"]["entries"]> = {};
|
||||
for (const [id, raw] of Object.entries(obj(m.entries))) {
|
||||
if (!id.trim()) continue;
|
||||
const r = obj(raw);
|
||||
const agents = stringList(r.agents);
|
||||
entries[id] = {
|
||||
mode: oneOf(r.mode, entryModes, "auto"),
|
||||
...(agents.length ? { agents } : {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
autoMemory: oneOf(m.autoMemory, autoModes, "inherit"),
|
||||
providers,
|
||||
entries,
|
||||
};
|
||||
return { providers };
|
||||
}
|
||||
|
||||
function agentPluginSettings(v: unknown): Required<AgentSettings>["plugins"] {
|
||||
|
||||
@@ -4875,14 +4875,11 @@
|
||||
"fillfactor=70, autovacuum_enabled=false": "fillfactor=70, autovacuum_enabled=false",
|
||||
"Configure memory and instructions for this session": "Configure memory and instructions for this session",
|
||||
"Memory…": "Memory…",
|
||||
"Inherit": "Inherit",
|
||||
"Read & Write": "Read & Write",
|
||||
"Read Only": "Read Only",
|
||||
"Cross-Session Auto-Memory": "Cross-Session Auto-Memory",
|
||||
"Auto-memory mode": "Auto-memory mode",
|
||||
"Auto Memory": "Auto Memory",
|
||||
"Rule": "Rule",
|
||||
"This agent loads its own instruction files directly; Always additionally bridges the content to other agents.": "This agent loads its own instruction files directly; Always additionally bridges the content to other agents.",
|
||||
"Open in Editor": "Open in Editor",
|
||||
"Promote to AGENTS.md…": "Promote to AGENTS.md…",
|
||||
"Claude Rule (.claude/rules)": "Claude Rule (.claude/rules)",
|
||||
@@ -4894,13 +4891,9 @@
|
||||
"Section heading (optional)": "Section heading (optional)",
|
||||
"Conventions": "Conventions",
|
||||
"Remove original auto-memory note after promoting": "Remove original auto-memory note after promoting",
|
||||
"Memory ({active}/{total} active)": "Memory ({active}/{total} active)",
|
||||
"Memory ({active}/{total} active · {overrides} session overrides)": "Memory ({active}/{total} active · {overrides} session overrides)",
|
||||
"Session Memory": "Session Memory",
|
||||
"Filter memories…": "Filter memories…",
|
||||
"Filter memories": "Filter memories",
|
||||
"~{tokens} tokens active": "~{tokens} tokens active",
|
||||
"This agent manages its own memory. Set a file to Always in Settings to pass it to this agent.": "This agent manages its own memory. Set a file to Always in Settings to pass it to this agent.",
|
||||
"Cross-session learning for this task": "Cross-session learning for this task",
|
||||
"Session auto-memory mode": "Session auto-memory mode",
|
||||
"No memory files found.": "No memory files found.",
|
||||
@@ -5516,11 +5509,9 @@
|
||||
"No rule or instruction selected": "No rule or instruction selected",
|
||||
"No auto-memory note selected": "No auto-memory note selected",
|
||||
"Add Rule…": "Add Rule…",
|
||||
"Untrusted workspace: trust this project before changing workspace instruction modes.": "Untrusted workspace: trust this project before changing workspace instruction modes.",
|
||||
"Editing scope": "Editing scope",
|
||||
"Applies to": "Applies to",
|
||||
"Add Rule or Instruction": "Add Rule or Instruction",
|
||||
"Mode changes apply immediately without modifying tracked repository files.": "Mode changes apply immediately without modifying tracked repository files.",
|
||||
"Search skills...": "Search skills...",
|
||||
"Agent Plugins": "Agent Plugins",
|
||||
"No skill selected": "No skill selected",
|
||||
@@ -5664,5 +5655,20 @@
|
||||
"plugin {pluginId}: {e}": "plugin {pluginId}: {e}",
|
||||
"This build of {display} has expired and stops working soon. Choose a newer build in Language Servers.": "This build of {display} has expired and stops working soon. Choose a newer build in Language Servers.",
|
||||
"This build of {display} has expired and stops working soon. Update it to the latest release?": "This build of {display} has expired and stops working soon. Update it to the latest release?",
|
||||
"This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}.": "This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}."
|
||||
"This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}.": "This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}.",
|
||||
"Other agents manage cross-session auto-memory in their own settings.": "Other agents manage cross-session auto-memory in their own settings.",
|
||||
"{count} notes": "{count} notes",
|
||||
"Saved directly in this agent's native config file": "Saved directly in this agent's native config file",
|
||||
"Native config": "Native config",
|
||||
"Auto-memory mode for {provider}": "Auto-memory mode for {provider}",
|
||||
"Instruction and rule files are loaded directly by each agent. Edit or remove files to change what an agent reads.": "Instruction and rule files are loaded directly by each agent. Edit or remove files to change what an agent reads.",
|
||||
"Auto-memory settings apply to new or idle sessions for agents that support them.": "Auto-memory settings apply to new or idle sessions for agents that support them.",
|
||||
"Untrusted workspace: agents do not run in this project until you trust it.": "Untrusted workspace: agents do not run in this project until you trust it.",
|
||||
"Loaded by": "Loaded by",
|
||||
"Auto-memory override applies to this session only.": "Auto-memory override applies to this session only.",
|
||||
"Instruction files are loaded directly by this agent.": "Instruction files are loaded directly by this agent.",
|
||||
"Memory ({total} files)": "Memory ({total} files)",
|
||||
"Memory ({total} files · auto-memory overridden)": "Memory ({total} files · auto-memory overridden)",
|
||||
"Configure Hermes auto-memory in Settings › Agents › Rules & Memory.": "Configure Hermes auto-memory in Settings › Agents › Rules & Memory.",
|
||||
"All coding agents": "All coding agents"
|
||||
}
|
||||
@@ -11630,14 +11630,11 @@
|
||||
"Open Module Settings": "打开模块设置",
|
||||
"Configure memory and instructions for this session": "为此会话配置记忆与指令",
|
||||
"Memory…": "记忆…",
|
||||
"Inherit": "继承",
|
||||
"Read & Write": "读写",
|
||||
"Read Only": "只读",
|
||||
"Cross-Session Auto-Memory": "跨会话自动记忆",
|
||||
"Auto-memory mode": "自动记忆模式",
|
||||
"Auto Memory": "自动记忆",
|
||||
"Rule": "规则",
|
||||
"This agent loads its own instruction files directly; Always additionally bridges the content to other agents.": "该智能体直接加载其自身指令文件;设为“始终”还会将内容桥接给其他智能体。",
|
||||
"Open in Editor": "在编辑器中打开",
|
||||
"Promote to AGENTS.md…": "提升到 AGENTS.md…",
|
||||
"Claude Rule (.claude/rules)": "Claude 规则(.claude/rules)",
|
||||
@@ -11649,13 +11646,9 @@
|
||||
"Section heading (optional)": "章节标题(可选)",
|
||||
"Conventions": "约定",
|
||||
"Remove original auto-memory note after promoting": "提升后移除原自动记忆笔记",
|
||||
"Memory ({active}/{total} active)": "记忆({active}/{total} 已启用)",
|
||||
"Memory ({active}/{total} active · {overrides} session overrides)": "记忆({active}/{total} 已启用 · {overrides} 项会话覆盖)",
|
||||
"Session Memory": "会话记忆",
|
||||
"Filter memories…": "筛选记忆…",
|
||||
"Filter memories": "筛选记忆",
|
||||
"~{tokens} tokens active": "约 {tokens} 个 token 已启用",
|
||||
"This agent manages its own memory. Set a file to Always in Settings to pass it to this agent.": "此智能体自行管理记忆。在设置中把文件设为“始终”即可交给它。",
|
||||
"Cross-session learning for this task": "此任务的跨会话学习策略",
|
||||
"Session auto-memory mode": "会话自动记忆模式",
|
||||
"No memory files found.": "未找到记忆文件。",
|
||||
@@ -12414,11 +12407,9 @@
|
||||
"No rule or instruction selected": "未选择规则或指令",
|
||||
"No auto-memory note selected": "未选择自动记忆笔记",
|
||||
"Add Rule…": "添加规则…",
|
||||
"Untrusted workspace: trust this project before changing workspace instruction modes.": "不受信任的工作区:更改工作区指令模式前请先信任此项目。",
|
||||
"Editing scope": "编辑范围",
|
||||
"Applies to": "适用于",
|
||||
"Add Rule or Instruction": "添加规则或指令",
|
||||
"Mode changes apply immediately without modifying tracked repository files.": "模式更改会立即生效,不会修改受版本控制的仓库文件。",
|
||||
"Search skills...": "搜索 Skills...",
|
||||
"Agent Plugins": "Agent 插件",
|
||||
"No skill selected": "未选择 Skill",
|
||||
@@ -12567,5 +12558,20 @@
|
||||
"plugin {pluginId}: {e}": "插件 {pluginId}:{e}",
|
||||
"This build of {display} has expired and stops working soon. Choose a newer build in Language Servers.": "此版本的 {display} 已过期,很快将停止工作。请在“语言服务器”中选择更新的版本。",
|
||||
"This build of {display} has expired and stops working soon. Update it to the latest release?": "此版本的 {display} 已过期,很快将停止工作。要更新到最新版本吗?",
|
||||
"This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}.": "此版本的 {display} 已过期,很快将停止工作。要为 IDE 安装最新版本吗?安装后将代替 {path} 使用。"
|
||||
"This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}.": "此版本的 {display} 已过期,很快将停止工作。要为 IDE 安装最新版本吗?安装后将代替 {path} 使用。",
|
||||
"Other agents manage cross-session auto-memory in their own settings.": "其他智能体在各自设置中自行管理跨会话自动记忆。",
|
||||
"{count} notes": "{count} 条笔记",
|
||||
"Saved directly in this agent's native config file": "直接保存在该智能体的原生配置文件中",
|
||||
"Native config": "原生配置",
|
||||
"Auto-memory mode for {provider}": "{provider} 的自动记忆模式",
|
||||
"Instruction and rule files are loaded directly by each agent. Edit or remove files to change what an agent reads.": "指令与规则文件由各智能体直接加载。如需调整读取内容,请编辑或删除对应文件。",
|
||||
"Auto-memory settings apply to new or idle sessions for agents that support them.": "自动记忆设置会应用于支持该能力的智能体的新建或空闲会话。",
|
||||
"Untrusted workspace: agents do not run in this project until you trust it.": "不受信任的工作区:信任此项目后智能体才会运行。",
|
||||
"Loaded by": "加载方",
|
||||
"Auto-memory override applies to this session only.": "自动记忆覆盖仅对当前会话生效。",
|
||||
"Instruction files are loaded directly by this agent.": "指令文件由该智能体直接加载。",
|
||||
"Memory ({total} files)": "记忆({total} 个文件)",
|
||||
"Memory ({total} files · auto-memory overridden)": "记忆({total} 个文件 · 已覆盖自动记忆)",
|
||||
"Configure Hermes auto-memory in Settings › Agents › Rules & Memory.": "请在「设置 › 智能体 › 规则与记忆」中配置 Hermes 自动记忆。",
|
||||
"All coding agents": "所有编程智能体"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача