agentmux_srv_core/backend/memory/native_files.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where an agent's native memory files live on disk, and the rules for reading
5//! and writing them: the folder for a working directory, an agent or a spawn, the
6//! filename and frontmatter checks, and the mirror refresh into
7//! `db_agent_native_memory`.
8//!
9//! Moved here from `server/native_memory_handlers.rs` (task #1350, architecture
10//! cleanup stage 2) so that `backend/` memory code no longer names `server/`.
11//! The RPC handlers stay there and re-export these names.
12
13use std::path::PathBuf;
14
15use crate::backend::base::expand_home_dir_safe;
16
17
18/// Compute `$CLAUDE_CONFIG_DIR/projects/<sanitized>/memory/` for the given
19/// working directory and Claude config dir.
20///
21/// `claude_config_dir` is the value of `CLAUDE_CONFIG_DIR` from the agent's
22/// stored env blob. When empty, falls back to
23/// `~/.agentmux/shared/providers/claude/` — the default isolated home that
24/// `app_api/agent_open.rs` sets at agent spawn time. We never write to the global
25/// `~/.claude/projects/` because AgentMux always sets `CLAUDE_CONFIG_DIR`.
26///
27/// The project folder is named by the CLI's own rules: after the directory
28/// memory is keyed by ([`crate::backend::claude_layout::memory_project_root`]
29/// — the repository's main checkout, for a subdirectory or a linked
30/// worktree), sanitized by [`crate::backend::claude_layout::project_dir_name`].
31pub fn memory_dir_for_cwd(claude_config_dir: &str, working_directory: &str) -> PathBuf {
32 memory_dir_for_cwd_with(
33 claude_config_dir,
34 working_directory,
35 &crate::backend::fs_ops::container_folders::written_by_a_container_agent,
36 )
37}
38
39/// [`memory_dir_for_cwd`], with `written` saying whether a container agent can
40/// write a folder: such a folder is named after its own path alone
41/// ([`crate::backend::claude_layout::memory_project_root_with`]).
42pub fn memory_dir_for_cwd_with(
43 claude_config_dir: &str,
44 working_directory: &str,
45 written: &dyn Fn(&std::path::Path) -> bool,
46) -> PathBuf {
47 // Claude names the project folder from the absolute cwd, so `~` must be
48 // expanded first — a spawn segment records the block's `cmd:cwd`
49 // unexpanded (`~/.agentmux/agents/<slug>` for an agent.open default),
50 // and `--agentmux-agents-…` is a folder Claude never writes (#3603).
51 let working_directory = expand_home_dir_safe(working_directory);
52 let root = crate::backend::claude_layout::memory_project_root_with(&working_directory, written);
53 let folder_name = crate::backend::claude_layout::project_dir_name(&root.to_string_lossy());
54
55 let base = if claude_config_dir.is_empty() {
56 expand_home_dir_safe("~/.agentmux/shared/providers/claude")
57 } else {
58 expand_home_dir_safe(claude_config_dir)
59 };
60 base.join("projects").join(folder_name).join("memory")
61}
62
63/// Extract `CLAUDE_CONFIG_DIR` from a `KEY=VALUE\n…` env blob.
64pub fn parse_claude_config_dir(env_blob: &str) -> String {
65 for line in env_blob.lines() {
66 if let Some(val) = line.strip_prefix("CLAUDE_CONFIG_DIR=") {
67 return val.to_string();
68 }
69 }
70 String::new()
71}
72
73/// The identity stores (`id_store`, `identity_store`), attached once at boot,
74/// so memory resolution can find the account an agent is linked to — the
75/// directory its spawn actually runs Claude in. Its callers hold only the
76/// channel store. Unattached (tests): the linked-account step is skipped.
77static IDENTITY_STORES: std::sync::OnceLock<(
78 std::sync::Arc<crate::backend::storage::store::Store>,
79 std::sync::Arc<crate::backend::storage::store::Store>,
80)> = std::sync::OnceLock::new();
81
82pub fn attach_identity_stores(
83 id_store: std::sync::Arc<crate::backend::storage::store::Store>,
84 identity_store: std::sync::Arc<crate::backend::storage::store::Store>,
85) {
86 let _ = IDENTITY_STORES.set((id_store, identity_store));
87}
88
89/// The Claude config dir an agent runs in, as its spawn decides it: the
90/// config dir of the Claude OAuth account it is linked to — the spawn sets
91/// `CLAUDE_CONFIG_DIR` to it over any env value (`resolver::inject`) — else
92/// its env override, else `""`, the shared default. #3603: an agent with no
93/// env override and a linked account resolved to the shared default, so
94/// `MemoryList` listed nothing while its memories sat in the account's dir.
95pub fn agent_claude_config_dir(mstore: &crate::backend::storage::store::Store, agent_id: &str) -> String {
96 let linked = IDENTITY_STORES.get().and_then(|(id_store, identity_store)| {
97 // Only an agent with a binding — its own, or its template's (the
98 // spawn's fallback) — reaches the resolver, which logs a warning for
99 // an unbound one; memory is read every sweep.
100 crate::identity::resolver::agent_has_identity_binding(mstore, identity_store, agent_id)
101 .then(|| {
102 crate::identity::resolver::resolve_bound_claude_config_dir_for_agent(
103 mstore, id_store, identity_store, agent_id,
104 )
105 })
106 .flatten()
107 });
108 if let Some(dir) = linked {
109 return dir.to_string_lossy().into_owned();
110 }
111 mstore
112 .agent_content_get(agent_id, "env")
113 .ok()
114 .flatten()
115 .map(|c| parse_claude_config_dir(&c.content))
116 .unwrap_or_default()
117}
118
119/// The account a Dreams pass of an agent's memory runs on.
120#[derive(Debug, Clone, PartialEq)]
121pub enum DreamAccount {
122 /// The config folder of the agent's own account.
123 Dir(String),
124 /// The agent has no account recorded: the machine's default sign-in.
125 Default,
126 /// The agent has an account recorded but it cannot be resolved (its row was deleted, it is not a Claude account, or it
127 /// is the machine's own sign-in): the pass is held, never run on another account. The text says why.
128 Unresolved(String),
129}
130
131/// The decision of [`agent_dream_account`] from what was found: `bound` is `None` when the agent has no account
132/// recorded, else what resolving it gave; `env_dir` is the agent's own `CLAUDE_CONFIG_DIR` override (or empty).
133pub fn dream_account_from(bound: Option<Option<String>>, env_dir: String) -> DreamAccount {
134 match bound {
135 Some(Some(dir)) => DreamAccount::Dir(dir),
136 Some(None) => DreamAccount::Unresolved("the agent's account could not be resolved".to_string()),
137 None if env_dir.trim().is_empty() => DreamAccount::Default,
138 None => DreamAccount::Dir(env_dir),
139 }
140}
141
142/// The account a pass of this agent's memory runs on: its recorded account's config folder, else its own config
143/// override, else (nothing recorded) the machine's default sign-in. An agent whose recorded account does not resolve is
144/// not given the default: `agent_claude_config_dir` answers `""` for it, which would mean another account.
145pub fn agent_dream_account(mstore: &crate::backend::storage::store::Store, agent_id: &str) -> DreamAccount {
146 let bound = IDENTITY_STORES.get().and_then(|(id_store, identity_store)| {
147 crate::identity::resolver::agent_has_identity_binding(mstore, identity_store, agent_id).then(|| {
148 crate::identity::resolver::resolve_bound_claude_config_dir_for_agent(mstore, id_store, identity_store, agent_id)
149 .map(|d| d.to_string_lossy().into_owned())
150 })
151 });
152 let env_dir = mstore.agent_content_get(agent_id, "env").ok().flatten().map(|c| parse_claude_config_dir(&c.content)).unwrap_or_default();
153 dream_account_from(bound, env_dir)
154}
155
156/// Resolve the memory directory for `agent_id`. Reads the agent definition and
157/// its stored env blob to find `CLAUDE_CONFIG_DIR`. Returns an error only if
158/// the agent cannot be resolved at all — an instance row with a blank
159/// `working_directory` falls through to the registry rather than failing (see
160/// the inline note below; that short-circuit was a real bug).
161///
162/// Shared by `native_memory_handlers` and the `memory.*` MuxAPI handlers.
163pub fn memory_dir_for_agent(
164 mstore: &crate::backend::storage::store::Store,
165 agent_id: &str,
166) -> Result<std::path::PathBuf, String> {
167 // agent_id arriving from MuxAPI is the agent slug (AGENTMUX_AGENT_ID /
168 // bus:register id), not a UUID and not the literal display name — use
169 // instance_get_by_slug (agent_def_get queries by UUID and would always
170 // return None here; instance_get_by_name matches the display name, a
171 // different namespace — see that function's own doc comment).
172 if let Some(instance) = mstore
173 .instance_get_by_slug(agent_id)
174 .map_err(|e| format!("memory: store: {e}"))?
175 {
176 // The agent's own latest spawn knows its directory for certain
177 // (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.2).
178 if let Ok(Some(def)) = mstore.agent_def_get(&instance.id) {
179 let gfs = crate::backend::agent_session::global_transcript_store().map(|a| a.as_ref());
180 if let Some(dir) = memory_dir_from_latest_segment(gfs, &def.id) {
181 return Ok(dir);
182 }
183 }
184 // Only trust the instance row when it actually carries a working
185 // directory. An empty one is NOT an error and must NOT short-circuit:
186 // `agent.open` substitutes a default (`~/.agentmux/agents/<slug>`)
187 // whenever `working_directory` is blank, so a blank row describes an
188 // agent that is nonetheless running — and writing memories — in a
189 // real directory. The registry fallback below is what knows that
190 // real directory (`source_agents_base` + `working_dir`).
191 //
192 // Returning Err here instead made Memory → Personal and the
193 // MemoryList MCP tool fail with "agent <x> has no working directory"
194 // for every such agent, while its memory files sat on disk perfectly
195 // intact — the common case, since `working_directory` is blank by
196 // default. See SPEC_FIX_PERSONAL_MEMORY_EMPTY_WORKDIR_2026_09_01.md.
197 if !instance.working_directory.is_empty() {
198 let config_dir = agent_claude_config_dir(mstore, &instance.id);
199 return Ok(memory_dir_for_cwd(&config_dir, &instance.working_directory));
200 }
201 // Resolve through the DEFINITION, not the instance row: `db_agents`
202 // stores `instance_name` as its own column, distinct from the
203 // definition's `name`, and it is empty for a definition-only row —
204 // so reading the name off `instance` here silently yielded "" and
205 // fell through to a not-found. `instance.id` IS the definition id in
206 // this consolidated table (see the note above).
207 if let Ok(Some(def)) = mstore.agent_def_get(&instance.id) {
208 if let Some(dir) =
209 memory_dir_for_blank_working_dir(mstore, &def.id, &def.name, &def.slug)
210 {
211 return Ok(dir);
212 }
213 }
214 }
215
216 // No persisted db_agents instance row. Running agents are tracked in the
217 // global named-agent registry, not db_agents (launching an agent does not
218 // create an instance row there), so the slug lookup above misses every live
219 // agent. Fall back to the registry, which records the slug → working_dir +
220 // identity binding needed to locate the agent's isolated memory dir.
221 // See issue #1836.
222 memory_dir_from_registry(agent_id)
223 .ok_or_else(|| format!("memory: agent {agent_id} not found"))
224}
225
226/// Resolve `agent_id` — the agent SLUG, per the App-API convention (see
227/// [`memory_dir_for_agent`]'s own doc comment) — to the same stable,
228/// canonical identifier (`AgentDefinition.id` / `db_agents.id`) the
229/// WebSocket RPC surface (`agent:memory:write_file` et al., which receives
230/// this id directly from the caller and resolves it via `agent_def_get`)
231/// already keys `db_agent_native_memory_versions` by.
232///
233/// reagent P1: without this, a version written through this App-API/MCP
234/// surface (previously slug-keyed, verbatim) lived in a disjoint keyspace
235/// from one written through the WS RPC surface for the exact same logical
236/// agent whenever `slug != id` — a version written via the `MemoryWrite`
237/// MCP tool was invisible to a WS-RPC-based `MemoryHistory`/`MemoryDiff`/
238/// `MemoryRevert` call and vice versa, silently defeating the point of
239/// having version history at all.
240///
241/// Mirrors `memory_dir_for_agent`'s own slug → instance → registry
242/// resolution order, but returns the id instead of a filesystem path:
243/// - Primary path (`instance_get_by_slug`): `db_agents` is the
244/// consolidated definition+instance table (Phase 3a) — its own query
245/// selects `id, id AS def_id`, i.e. the row's `id` already IS the
246/// definition id in this model, not a separate instance-only identity.
247/// - Registry fallback (a live agent not yet persisted to `db_agents`):
248/// the registry record's `definition_id` field is the one that matches
249/// `agent_def_get`'s namespace — its sibling `instance_id` is a
250/// different, launch-scoped identity, not what `write_file` keys by.
251pub fn resolve_agent_uuid(
252 mstore: &crate::backend::storage::store::Store,
253 agent_id: &str,
254) -> Result<String, String> {
255 crate::backend::agent_resolve::resolve_agent_id(mstore, agent_id)
256}
257
258/// Find the global named-agent registry's active record for `agent_id` —
259/// the `AGENTMUX_AGENT_ID` routing slug (`derive_slug(display_name)`),
260/// NOT the record's own `instance_name` (which keeps the original
261/// display casing, e.g. "AgentY"). Matching by raw string equality here
262/// used to mean this — and every App-API self-lookup endpoint that falls
263/// back to it (`memory.*`, and `bundle.self.get` once it's wired to use
264/// this too) — silently 404'd for any agent whose name wasn't already
265/// all-lowercase. `derive_slug` on both sides makes the comparison
266/// consistent with how the slug was actually derived in the first place.
267/// Shared so callers outside this module (e.g. `app_api::mod::
268/// bundle_self_get_impl`) don't reimplement the same lookup.
269pub fn find_active_registry_record_by_slug(
270 agent_id: &str,
271) -> Option<crate::registry::NamedAgentRecord> {
272 // Thin alias. The implementation moved to
273 // `backend::agent_registry_lookup` so `backend::history` could share it
274 // rather than keep a second copy of the slug-matching rules (reagentx P2,
275 // PR #3480). Kept as a named function here because this module's callers
276 // and its own tests refer to it, and the name says what it is at those
277 // call sites.
278 crate::backend::agent_registry_lookup::find_active_record_by_slug(agent_id)
279}
280
281/// Resolve a memory dir for `agent_id` from the global named-agent registry.
282///
283/// Each live agent is recorded by `instance_name` with a `working_dir` relative
284/// to `source_agents_base` (the channel/dev instance it lives in) and an
285/// `identity_id` that determines its `CLAUDE_CONFIG_DIR` root. Returns `None`
286/// when the registry is unavailable or no active record matches the slug.
287pub fn memory_dir_from_registry(agent_id: &str) -> Option<std::path::PathBuf> {
288 let rec = find_active_registry_record_by_slug(agent_id)?;
289 memory_dir_for_registry_record(&rec)
290}
291
292/// Resolve the memory dir for an agent whose persisted `working_directory`
293/// is blank — the DEFAULT state, so this is the common path, not an edge.
294///
295/// Two stages, in this order:
296///
297/// 1. **A registry record bound to this exact definition.** The registry
298/// records the working dir an agent was really launched with, which beats
299/// re-deriving it. `definition_id` is required to match: the plain
300/// slug lookup keys off `derive_slug(instance_name)` alone, so two agents
301/// whose display names slugify identically collide — and resolving the
302/// WRONG agent's memory dir would let list/read/write operations touch
303/// another agent's files (Codex P1, PR #2901).
304/// 2. **The derived default**, `default_agent_working_dir(name)` — the same
305/// path `agent.open` itself substitutes for a blank field. Needed because
306/// `agent.open` does NOT create a registry record, so stage 1 misses
307/// entirely for a freshly defined agent, which is exactly the case this
308/// whole fix targets (Codex P1, PR #2901).
309/// Takes the three identity fields explicitly rather than a struct: the two
310/// callers hold different types (`AgentInstance` from `instance_get_by_slug`,
311/// `AgentDefinition` from the by-id path) which don't share these field
312/// names. `definition_id` is the id the registry's own `definition_id`
313/// records — for `db_agents`, the consolidated definition+instance table,
314/// the instance row's `id` already IS that id (see `memory_dir_for_agent`'s
315/// own note).
316pub fn memory_dir_for_blank_working_dir(
317 mstore: &crate::backend::storage::store::Store,
318 definition_id: &str,
319 agent_name: &str,
320 slug: &str,
321) -> Option<std::path::PathBuf> {
322 if !slug.is_empty() {
323 // Disambiguates by definition_id *inside* the lookup rather than
324 // filtering after it. Same result when the slug is unique, but under a
325 // collision the slug-only lookup now refuses to guess and returns None
326 // (reagentx P1 on #3480) — this caller knows exactly which agent it
327 // means, so it can still resolve.
328 if let Some(rec) =
329 crate::backend::agent_registry_lookup::find_active_record_by_slug_and_definition(
330 slug,
331 definition_id,
332 )
333 {
334 if let Some(dir) = memory_dir_for_registry_record(&rec) {
335 return Some(dir);
336 }
337 }
338 }
339 if agent_name.is_empty() {
340 return None;
341 }
342 let config_dir = agent_claude_config_dir(mstore, definition_id);
343 // Claude records the absolute cwd, so the default `~/.agentmux/agents/…`
344 // must be expanded before it is turned into a project-folder name — the
345 // unexpanded form named a folder (`--agentmux-agents-…`) Claude never
346 // writes (#3603 review).
347 let work_dir = crate::backend::base::expand_home_dir_safe(
348 &crate::backend::storage::agents::default_agent_working_dir(agent_name),
349 );
350 Some(memory_dir_for_cwd(&config_dir, &work_dir.to_string_lossy()))
351}
352
353/// Reconstruct one registry record's absolute memory dir directly (no slug
354/// lookup) — shared by [`memory_dir_from_registry`] (single record, found by
355/// slug) and [`list_all_memory_targets`] (every active record, for the
356/// fs-watch drift detector's enumeration).
357///
358/// The working directory comes from
359/// [`crate::backend::agent_registry_lookup::working_dir_from_record`].
360pub fn memory_dir_for_registry_record(rec: &crate::registry::NamedAgentRecord) -> Option<std::path::PathBuf> {
361 let working_directory = crate::backend::agent_registry_lookup::working_dir_from_record(rec)?;
362
363 let config_dir = claude_config_dir_for_identity(rec.data.identity_id.as_deref());
364 Some(memory_dir_for_cwd(&config_dir, &working_directory))
365}
366
367/// Every agent whose memory directory is verified — found from its own
368/// spawn or its explicit working directory — for the drift detector and the
369/// first-sight backfill (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.2,
370/// phase M1).
371///
372/// Unverified guesses (the registry record, the name-derived default for a
373/// blank working directory) are left out: a stale registry `identity_id`
374/// once made this list attribute one agent's files to another. A directory
375/// two agents resolve to is left out too — its files can't be attributed to
376/// either — until the memory record's claims decide it (phase M3).
377pub fn list_all_memory_targets(
378 mstore: &crate::backend::storage::store::Store,
379) -> Vec<(String, std::path::PathBuf)> {
380 let gfs = crate::backend::agent_session::global_transcript_store().map(|a| a.as_ref());
381 list_memory_targets_with(mstore, gfs)
382}
383
384pub fn list_memory_targets_with(
385 mstore: &crate::backend::storage::store::Store,
386 segments_fs: Option<&crate::backend::storage::filestore::FileStore>,
387) -> Vec<(String, std::path::PathBuf)> {
388 let Ok(agents) = mstore.agent_def_list() else {
389 return Vec::new();
390 };
391 let mut targets: Vec<(String, std::path::PathBuf)> = Vec::new();
392 let mut seen = std::collections::HashSet::new();
393 for agent in &agents {
394 if !seen.insert(agent.id.clone()) {
395 continue;
396 }
397 if let Some(r) = resolve_memory_dir_with(mstore, agent, segments_fs) {
398 if r.provenance != MemoryDirProvenance::Unverified {
399 targets.push((agent.id.clone(), r.path));
400 }
401 }
402 }
403 let key = |p: &std::path::PathBuf| p.canonicalize().unwrap_or_else(|_| p.clone());
404 let mut owners: std::collections::HashMap<std::path::PathBuf, usize> = std::collections::HashMap::new();
405 for (_, dir) in &targets {
406 *owners.entry(key(dir)).or_default() += 1;
407 }
408 targets.retain(|(agent_id, dir)| {
409 let shared = owners.get(&key(dir)).copied().unwrap_or(0) > 1;
410 if shared {
411 tracing::debug!(agent_id, dir = %dir.display(), "memory: directory resolved by more than one agent; not attributed");
412 }
413 !shared
414 });
415 targets
416}
417
418/// Compute the `CLAUDE_CONFIG_DIR` root for an agent bound to `identity_id`,
419/// mirroring the spawn-time isolated-home layout (`OAuthConfigDir`):
420/// - unbound / "default" → `<shared>/providers/claude` (the default home;
421/// returned as an empty string so `memory_dir_for_cwd` applies its own
422/// identical fallback)
423/// - an account → `<shared>/identities/<id>/claude`
424pub fn claude_config_dir_for_identity(identity_id: Option<&str>) -> String {
425 match identity_id {
426 Some(id) if !id.is_empty() && id != "default" => {
427 let shared = std::env::var_os("AGENTMUX_SHARED_DIR")
428 .map(PathBuf::from)
429 .or_else(|| dirs::home_dir().map(|h| h.join(".agentmux").join("shared")));
430 match shared {
431 Some(s) => s
432 .join("identities")
433 .join(id)
434 .join("claude")
435 .to_string_lossy()
436 .to_string(),
437 None => String::new(),
438 }
439 }
440 _ => String::new(),
441 }
442}
443
444/// Validate a memory filename.
445pub fn validate_memory_filename(filename: &str) -> Result<(), String> {
446 validate_filename(filename)
447}
448
449/// Parse `metadata.type` from YAML frontmatter (re-exported for MuxAPI).
450pub fn parse_memory_frontmatter_type(content: &str) -> Option<String> {
451 parse_frontmatter_type(content)
452}
453
454/// Validate a filename: alphanumeric + `-_`, must end with `.md`, no path separators.
455pub fn validate_filename(filename: &str) -> Result<(), String> {
456 if filename.is_empty() {
457 return Err("filename must not be empty".to_string());
458 }
459 if !filename.ends_with(".md") {
460 return Err(format!("filename must end with .md, got: {filename}"));
461 }
462 if filename.contains('/') || filename.contains('\\') || filename.contains("..") {
463 return Err(format!("filename must not contain path separators: {filename}"));
464 }
465 let stem = &filename[..filename.len() - 3];
466 if stem.is_empty() {
467 return Err("filename stem must not be empty (.md is not a valid name)".to_string());
468 }
469 // Tmp path is ".{filename}.{uuid}.tmp" (+42 chars); cap stem at 200 to stay
470 // well under the 255-byte filesystem limit and avoid ENAMETOOLONG.
471 if stem.len() > 200 {
472 return Err(format!("filename stem too long ({} chars, max 200)", stem.len()));
473 }
474 if !stem.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
475 return Err(format!(
476 "filename stem must be alphanumeric + '-_', got: {stem}"
477 ));
478 }
479 Ok(())
480}
481
482/// Extract `metadata.type` from YAML frontmatter.
483/// Claude Code memory files nest the type under `metadata:`:
484/// metadata:
485/// type: user
486/// A top-level `type:` key is NOT the correct field.
487pub fn parse_frontmatter_type(content: &str) -> Option<String> {
488 let content = content.trim_start();
489 if !content.starts_with("---") {
490 return None;
491 }
492 let rest = content.strip_prefix("---")?.trim_start_matches('\n');
493 let end = rest.find("\n---")?;
494 let frontmatter = &rest[..end];
495 let mut in_metadata = false;
496 for line in frontmatter.lines() {
497 let trimmed = line.trim_end();
498 if trimmed == "metadata:" {
499 in_metadata = true;
500 continue;
501 }
502 if in_metadata {
503 // A non-indented, non-empty line exits the metadata block.
504 if !line.starts_with(' ') && !line.starts_with('\t') && !trimmed.is_empty() {
505 break;
506 }
507 if let Some(val) = line.trim_start().strip_prefix("type:") {
508 let val = val.trim().trim_matches('"').trim_matches('\'');
509 if !val.is_empty() {
510 return Some(val.to_string());
511 }
512 }
513 }
514 }
515 None
516}
517
518/// Cap for both live-FS reads and mirror upserts — one shared limit so a
519/// file that's readable stays within the size the mirror can also store.
520pub const MAX_MEMORY_FILE_BYTES: u64 = 10 * 1024 * 1024;
521
522/// Refresh `db_agent_native_memory` from the live filesystem for `agent_id`
523/// — the same read-then-upsert-if-changed logic `agent:memory:list`
524/// performs inline (compare each live file's size+mtime against the
525/// mirror, and upsert only when it's actually changed). This is a NEW,
526/// standalone function with the same shape, not a shared implementation
527/// `list`'s handler was refactored to call — reagent P2, PR #2527
528/// (second round): `list`'s own inline copy (this file, `~agent:memory:
529/// list`'s handler) still exists separately and has already diverged in
530/// one detail (it hard-errors on a `file_type()` failure; this function
531/// silently skips the entry instead). Deduplicating the two into one
532/// shared implementation is a legitimate follow-up, not done here to
533/// keep this PR's diff scoped to what ABF v0.2 §2.3 actually needs.
534///
535/// ABF v0.2 §2.3 (`bundle.export_for_agent`) needs this: `list`/`read_file`
536/// only sync the mirror on a Stash Bundle tab open, so exporting straight
537/// from `db_agent_native_memory` without refreshing first would silently
538/// omit anything Claude wrote autonomously since the tab was last opened
539/// (or if it was never opened at all) — see
540/// `SPEC_ABF_V0_2_PROVIDER_AWARE_COMPONENTS_AND_NATIVE_MEMORY_2026_08_10.md`
541/// §2.3's second revision note.
542///
543/// Errors only on a genuine `read_dir` failure (permissions, I/O) — a
544/// missing directory (never written, or wiped) is not an error, matching
545/// `list`'s own treatment. A per-file upsert failure is logged and
546/// swallowed (non-fatal), same as `list`.
547///
548/// Returns the filenames of any file whose real on-disk size exceeded
549/// [`MAX_MEMORY_FILE_BYTES`] — reagent P2, PR #2527: `list`'s original
550/// inline version of this logic silently truncates via
551/// `take(MAX_MEMORY_FILE_BYTES)` with no signal that it happened, so an
552/// export→import round trip through `bundle.export_for_agent` could
553/// permanently lose the tail of a large file with no warning anywhere.
554/// This function still truncates the same way (the cap itself is
555/// unchanged — still generous for any legitimate memory file), but now
556/// reports which files it happened to, so a caller that surfaces
557/// warnings (like `bundle.export_for_agent`) can tell the user.
558pub fn refresh_memory_mirror_from_live_fs(
559 agent_id: &str,
560 memory_dir: &std::path::Path,
561 id_store: &crate::backend::storage::store::Store,
562) -> Result<Vec<String>, String> {
563 let mirrored_meta: std::collections::HashMap<String, (i64, i64)> = id_store
564 .agent_native_memory_list_meta(agent_id)
565 .unwrap_or_default()
566 .into_iter()
567 .map(|row| (row.filename, (row.size_bytes, row.last_seen_mtime_ms)))
568 .collect();
569
570 let entries = match std::fs::read_dir(memory_dir) {
571 Ok(e) => e,
572 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
573 Err(e) => return Err(format!("refresh_memory_mirror_from_live_fs: read_dir: {e}")),
574 };
575
576 let mut truncated_files: Vec<String> = Vec::new();
577 for entry in entries {
578 let entry = entry.map_err(|e| format!("refresh_memory_mirror_from_live_fs: read_dir entry: {e}"))?;
579 let name = entry.file_name().to_string_lossy().into_owned();
580 if !name.ends_with(".md") {
581 continue;
582 }
583 let file_type = match entry.file_type() {
584 Ok(t) => t,
585 Err(_) => continue, // TOCTOU-deleted between read_dir and here; skip, not fatal.
586 };
587 if !file_type.is_file() {
588 continue;
589 }
590 let meta = match entry.metadata() {
591 Ok(m) => m,
592 Err(_) => continue,
593 };
594 let size_bytes = meta.len();
595 let modified_at = meta
596 .modified()
597 .ok()
598 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
599 .map(|d| d.as_millis() as i64)
600 .unwrap_or(0);
601
602 // reagent P2, PR #2527 (second round): checked BEFORE the
603 // unchanged-since-last-mirror short-circuit below — an oversized
604 // file that hasn't changed since it was last mirrored still
605 // exports/imports its truncated content on every subsequent
606 // call, so the warning must fire every time too, not just on the
607 // one call that actually re-reads and re-upserts it.
608 if size_bytes > MAX_MEMORY_FILE_BYTES {
609 truncated_files.push(name.clone());
610 }
611
612 let unchanged_since_last_mirror = mirrored_meta.get(&name) == Some(&(size_bytes as i64, modified_at));
613 if unchanged_since_last_mirror {
614 continue;
615 }
616 let full_content_read = {
617 use std::io::Read;
618 std::fs::File::open(entry.path()).and_then(|f| {
619 let mut buf = Vec::new();
620 f.take(MAX_MEMORY_FILE_BYTES).read_to_end(&mut buf)?;
621 Ok(buf)
622 })
623 };
624 match full_content_read {
625 Ok(buf) => {
626 let full_content = String::from_utf8_lossy(&buf).into_owned();
627 let full_metadata_type = parse_frontmatter_type(&full_content);
628 if let Err(e) = id_store.agent_native_memory_upsert(
629 agent_id,
630 &name,
631 &full_content,
632 full_metadata_type.as_deref(),
633 &entry.path().to_string_lossy(),
634 size_bytes as i64,
635 modified_at,
636 ) {
637 tracing::warn!(agent_id, filename = %name, error = %e, "refresh_memory_mirror_from_live_fs: mirror upsert failed (non-fatal)");
638 }
639 }
640 Err(e) => {
641 tracing::warn!(agent_id, filename = %name, error = %e, "refresh_memory_mirror_from_live_fs: full-content read failed, skipping this round (non-fatal)");
642 }
643 }
644 }
645 Ok(truncated_files)
646}
647
648/// Resolve the live memory directory for an agent identified by its
649/// `AgentDefinition.id` (UUID) — the same identifier convention
650/// `agent:memory:list`/`read_file`/`write_file` use (as opposed to
651/// [`memory_dir_for_agent`]'s slug-based lookup, used by different, App-API
652/// callers). Shared by those three handlers and `bundle.export_for_agent`/
653/// `bundle.import_for_agent` (ABF v0.2 §2.3) so all five resolve identically.
654pub fn memory_dir_for_agent_by_id(
655 mstore: &crate::backend::storage::store::Store,
656 agent: &crate::backend::storage::AgentDefinition,
657) -> Option<std::path::PathBuf> {
658 resolve_memory_dir_by_id(mstore, agent).map(|r| r.path)
659}
660
661/// How an agent's memory directory was found
662/// (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.2, phase M1).
663#[derive(Clone, Copy, Debug, PartialEq, Eq)]
664pub enum MemoryDirProvenance {
665 /// The config dir and working dir the agent's own latest spawn used,
666 /// from its continuity segment.
667 Spawn,
668 /// The agent's explicit working directory under its linked account.
669 WorkingDirectory,
670 /// A blank working directory with no spawn on record: the registry
671 /// record or the name-derived default. A guess — the stale registry
672 /// `identity_id` behind it once read another agent's files — so it is
673 /// read-only and never swept for drift.
674 Unverified,
675}
676
677pub struct ResolvedMemoryDir {
678 pub path: std::path::PathBuf,
679 pub provenance: MemoryDirProvenance,
680}
681
682/// The memory dir of the agent's latest Claude spawn, from its continuity
683/// segments in the global transcript store.
684pub fn memory_dir_from_latest_segment(
685 fs: Option<&crate::backend::storage::filestore::FileStore>,
686 agent_uid: &str,
687) -> Option<std::path::PathBuf> {
688 let latest = crate::backend::continuity_segments::segments(fs?, agent_uid)
689 .into_iter()
690 .filter(|s| s.start.provider == "claude" && !s.start.cwd.is_empty())
691 .max_by_key(|s| s.start.started_at_ms)?;
692 Some(memory_dir_for_cwd(latest.start.config_dir.as_deref().unwrap_or(""), &latest.start.cwd))
693}
694
695/// Resolve an agent's memory dir with how it was found: its latest spawn
696/// first, then its explicit working directory, then the blank-working-dir
697/// guess (read-only).
698pub fn resolve_memory_dir_by_id(
699 mstore: &crate::backend::storage::store::Store,
700 agent: &crate::backend::storage::AgentDefinition,
701) -> Option<ResolvedMemoryDir> {
702 let gfs = crate::backend::agent_session::global_transcript_store().map(|a| a.as_ref());
703 resolve_memory_dir_with(mstore, agent, gfs)
704}
705
706pub fn resolve_memory_dir_with(
707 mstore: &crate::backend::storage::store::Store,
708 agent: &crate::backend::storage::AgentDefinition,
709 segments_fs: Option<&crate::backend::storage::filestore::FileStore>,
710) -> Option<ResolvedMemoryDir> {
711 if let Some(path) = memory_dir_from_latest_segment(segments_fs, &agent.id) {
712 return Some(ResolvedMemoryDir { path, provenance: MemoryDirProvenance::Spawn });
713 }
714 legacy_memory_dir_by_id(mstore, agent).map(|(path, provenance)| ResolvedMemoryDir { path, provenance })
715}
716
717/// The memory dir of `agent_uid`'s latest spawn, if one is on record — for a
718/// caller that knows the agent's id but has no local row for it.
719pub fn memory_dir_from_spawn(agent_uid: &str) -> Option<std::path::PathBuf> {
720 let gfs = crate::backend::agent_session::global_transcript_store().map(|a| a.as_ref());
721 memory_dir_from_latest_segment(gfs, agent_uid)
722}
723
724/// The memory dir an AgentMux write may go to: never an unverified guess.
725pub fn memory_dir_for_write_by_id(
726 mstore: &crate::backend::storage::store::Store,
727 agent: &crate::backend::storage::AgentDefinition,
728) -> Result<std::path::PathBuf, String> {
729 match resolve_memory_dir_by_id(mstore, agent) {
730 Some(r) if r.provenance != MemoryDirProvenance::Unverified => Ok(r.path),
731 Some(_) => Err(format!(
732 "agent {} has no verified memory directory yet (no working directory and no spawn on record); \
733 it becomes writable after the agent's next launch",
734 agent.id
735 )),
736 None => Err(format!("agent {} has no resolvable memory directory", agent.id)),
737 }
738}
739
740/// Today's resolution without spawn records: explicit working directory,
741/// else the blank-working-dir guess.
742pub fn legacy_memory_dir_by_id(
743 mstore: &crate::backend::storage::store::Store,
744 agent: &crate::backend::storage::AgentDefinition,
745) -> Option<(std::path::PathBuf, MemoryDirProvenance)> {
746 // Same blank-working_directory fallthrough as `memory_dir_for_agent`
747 // (see its own note) — a blank field is "this row can't answer", not
748 // "there is no memory dir". `agent.open` substitutes a default whenever
749 // it's blank, so such an agent still has memories on disk in a directory
750 // only the registry knows.
751 //
752 // Short-circuiting to None here was worse than the sibling's early Err,
753 // because both callers read None as a benign "no memory dir" rather than
754 // a failure (ReAgent P1, PR #2901):
755 // - `bundle.rs`'s export_for_agent silently exports an EMPTY memory
756 // file list, losing the agent's memories from the bundle;
757 // - `bundle.rs`'s import_for_agent silently skips the live-fs mirror
758 // refresh that exists specifically to avoid overwriting unmirrored
759 // memory (reagent P0, PR #2527) — i.e. the blank-workdir case
760 // bypassed a data-loss guard.
761 // Both for the common case, since `working_directory` is blank by default.
762 if !agent.working_directory.is_empty() {
763 let config_dir = agent_claude_config_dir(mstore, &agent.id);
764 return Some((
765 memory_dir_for_cwd(&config_dir, &agent.working_directory),
766 MemoryDirProvenance::WorkingDirectory,
767 ));
768 }
769 memory_dir_for_blank_working_dir(mstore, &agent.id, &agent.name, &agent.slug)
770 .map(|dir| (dir, MemoryDirProvenance::Unverified))
771}
772
773/// The content `agent:memory:read_file` would return for `path` right now —
774/// live FS first (lossy UTF-8, capped at [`MAX_MEMORY_FILE_BYTES`]), the
775/// durable mirror only when the live file is genuinely absent — WITHOUT
776/// that handler's mirror-upsert side effect. `Ok(None)` means the file
777/// exists in neither place. Used by `agent:memory:write_file`'s
778/// `base_sha256` check, which must hash exactly what the caller's draft was
779/// based on (the frontend hashes the `read_file` response), or every
780/// conditional save of a large or non-UTF-8 file would look like a conflict.
781pub fn current_memory_content(
782 id_store: &crate::backend::storage::store::Store,
783 agent_id: &str,
784 path: &std::path::Path,
785 filename: &str,
786) -> Result<Option<String>, String> {
787 match std::fs::symlink_metadata(path) {
788 Ok(meta) if meta.file_type().is_file() => {
789 let mut buf = Vec::new();
790 std::fs::File::open(path)
791 .and_then(|f| {
792 use std::io::Read;
793 f.take(MAX_MEMORY_FILE_BYTES).read_to_end(&mut buf)
794 })
795 .map_err(|e| format!("{filename}: {e}"))?;
796 Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
797 }
798 Ok(_) => Err(format!("{filename} is not a regular file")),
799 Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("{filename}: {e}")),
800 Err(_) => id_store
801 .agent_native_memory_read(agent_id, filename)
802 .map_err(|e| format!("{filename}: mirror lookup failed: {e}")),
803 }
804}
805
806/// The optimistic-concurrency check behind `base_sha256`
807/// (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.4): `Ok` when `current`
808/// still hashes to `base`, otherwise an error starting `conflict:` — the
809/// marker the frontend keys its "changed since you started editing" banner
810/// on. A file that no longer exists is a conflict too: the draft's base is
811/// gone, and silently re-creating it would undo someone else's delete.
812pub fn check_memory_base_sha256(filename: &str, base: &str, current: Option<&str>) -> Result<(), String> {
813 match current {
814 None => Err(format!(
815 "conflict: {filename} no longer exists (your edit was based on {base}); not written"
816 )),
817 Some(content) => {
818 let current_hash = crate::backend::storage::agent_native_memory_versions::content_hash(content);
819 if current_hash.eq_ignore_ascii_case(base) {
820 Ok(())
821 } else {
822 Err(format!(
823 "conflict: {filename} changed since your edit began (base {base}, current {current_hash}); not written"
824 ))
825 }
826 }
827 }
828}