Skip to main content

agentmux_srv/server/
native_memory_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Native memory RPCs — read/write the agent's `~/.claude/projects/<sanitized>/memory/`
5//! folder that Claude Code uses for autonomous, cross-session fact storage.
6//!
7//! Three commands:
8//!   agent:memory:list       — list *.md files in the memory dir
9//!   agent:memory:read_file  — read one file by filename (no path traversal)
10//!   agent:memory:write_file — write/create one file atomically (tmp→rename)
11//!
12//! Spec: docs/specs/SPEC_AGENT_PANE_MEMORY_IDENTITY_MODALS_2026_06_19.md §7
13//!
14//! All three also write through into `db_agent_native_memory` (via
15//! `state.id_store`) — a durable mirror keyed by the stable
16//! `AgentDefinition.id`, since the live filesystem path above is
17//! channel-relative by design and not the same across channels/instances for
18//! the same logical agent. `list`/`read_file` merge the live-FS view with
19//! the mirror so a file written from one channel stays visible from another.
20//! See docs/specs/SPEC_NATIVE_MEMORY_DURABLE_SYNC_2026_08_07.md.
21
22use std::sync::Arc;
23
24use crate::backend::rpc::engine::WshRpcEngine;
25use crate::backend::rpc_types::{
26    COMMAND_NATIVE_MEMORY_ADOPTION_LIST,
27    COMMAND_NATIVE_MEMORY_CLAIMS,
28    COMMAND_NATIVE_MEMORY_DIFF,
29    COMMAND_NATIVE_MEMORY_HISTORY,
30    COMMAND_NATIVE_MEMORY_LIST,
31    COMMAND_NATIVE_MEMORY_READ_FILE,
32    COMMAND_NATIVE_MEMORY_REVERT,
33    COMMAND_NATIVE_MEMORY_WRITE_FILE,
34    CommandNativeMemoryAdoptionListData,
35    CommandNativeMemoryClaimsData,
36    CommandNativeMemoryDiffData,
37    CommandNativeMemoryHistoryData,
38    CommandNativeMemoryListData,
39    CommandNativeMemoryReadFileData,
40    CommandNativeMemoryRevertData,
41    CommandNativeMemoryWriteFileData,
42    NativeMemoryAdoptionListResult,
43    NativeMemoryDiffResult,
44    NativeMemoryFileMeta,
45    NativeMemoryHistoryResult,
46    NativeMemoryListResult,
47    NativeMemoryReadFileResult,
48    NativeMemoryRevertResult,
49};
50
51use super::AppState;
52pub(crate) use super::native_memory_diff::line_diff;
53use super::native_memory_versions::{version_summary_to_meta, version_to_meta};
54use agentmux_common::tokens::{count_lines, estimate_tokens, tokens_for_chars};
55pub(crate) use crate::backend::memory::native_files::*;
56
57
58type MirroredMeta = std::collections::HashMap<String, (i64, i64)>;
59
60/// Mirrors a live file into `db_agent_native_memory` when it changed since it
61/// was last mirrored, and returns its (tokens, lines) counts when it read the
62/// file. Never upserts on a failed read.
63fn refresh_mirror(
64    id_store: &crate::backend::storage::store::Store,
65    agent_id: &str,
66    name: &str,
67    path: &std::path::Path,
68    size_bytes: u64,
69    modified_at: i64,
70) -> Option<(u64, u64)> {
71    let mut counts = None;
72    // A read failure here (permission change, TOCTOU
73    // delete, AV/NFS lock, concurrent editor) must NOT
74    // upsert an empty string — that would overwrite any
75    // previously-durable mirrored content, destroying the
76    // exact cross-channel durability guarantee this table
77    // exists for on the very first transient read hiccup
78    // (reagent P0 on PR #2459). Skip the upsert entirely
79    // this round instead; it retries on the next list().
80    let full_content_read = {
81        use std::io::Read;
82        std::fs::File::open(path).and_then(|f| {
83            let mut buf = Vec::new();
84            f.take(MAX_MEMORY_FILE_BYTES).read_to_end(&mut buf)?;
85            Ok(buf)
86        })
87    };
88    match full_content_read {
89        Ok(buf) => {
90            let full_content = String::from_utf8_lossy(&buf).into_owned();
91            counts = Some((estimate_tokens(&full_content), count_lines(&full_content)));
92            let full_metadata_type = parse_frontmatter_type(&full_content);
93            if let Err(e) = id_store.agent_native_memory_upsert(
94                agent_id,
95                name,
96                &full_content,
97                full_metadata_type.as_deref(),
98                &path.to_string_lossy(),
99                size_bytes as i64,
100                modified_at,
101            ) {
102                tracing::warn!(agent_id = %agent_id, filename = %name, error = %e, "agent:memory:list: mirror upsert failed (non-fatal)");
103            }
104        }
105        Err(e) => {
106            tracing::warn!(agent_id = %agent_id, filename = %name, error = %e, "agent:memory:list: full-content read failed, skipping mirror upsert this round (non-fatal)");
107        }
108    }
109    counts
110}
111
112/// One entry of the live memory folder as a list row, mirroring it first when it
113/// changed. `None` for anything that isn't a plain `*.md` file (or vanished).
114fn describe_live_entry(
115    id_store: &crate::backend::storage::store::Store,
116    agent_id: &str,
117    mirrored_meta: &MirroredMeta,
118    entry: &std::fs::DirEntry,
119) -> Result<Option<NativeMemoryFileMeta>, String> {
120    let name = entry.file_name().to_string_lossy().into_owned();
121    if !name.ends_with(".md") {
122        return Ok(None);
123    }
124    // Reject symlinks — entry.file_type() does NOT follow symlinks.
125    let file_type = entry
126        .file_type()
127        .map_err(|e| format!("agent:memory:list: file_type {name}: {e}"))?;
128    if !file_type.is_file() {
129        return Ok(None);
130    }
131    // The file may be deleted after read_dir but before metadata —
132    // skip the entry on NotFound rather than aborting the whole listing.
133    let meta = match entry.metadata() {
134        Ok(m) => m,
135        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
136        Err(e) => return Err(format!("agent:memory:list: metadata {name}: {e}")),
137    };
138    let size_bytes = meta.len();
139    let modified_at = meta
140        .modified()
141        .ok()
142        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
143        .map(|d| d.as_millis() as i64)
144        .unwrap_or(0);
145
146    // Read up to 512 bytes for frontmatter type parsing — same
147    // cheap preview the pre-mirror code used. Take + read_to_end
148    // loops internally to fill the buffer.
149    let preview_content = {
150        use std::io::Read;
151        std::fs::File::open(entry.path())
152            .map(|f| {
153                let mut buf = Vec::with_capacity(512);
154                f.take(512).read_to_end(&mut buf).ok();
155                String::from_utf8_lossy(&buf).into_owned()
156            })
157            .unwrap_or_default()
158    };
159    let metadata_type = parse_frontmatter_type(&preview_content);
160    let is_index = name == "MEMORY.md";
161
162    let unchanged_since_last_mirror =
163        mirrored_meta.get(&name) == Some(&(size_bytes as i64, modified_at));
164    let mut counts = None;
165    if !unchanged_since_last_mirror {
166        counts = refresh_mirror(id_store, agent_id, &name, &entry.path(), size_bytes, modified_at);
167    }
168    // Not read above: from the mirror; never mirrored: from its bytes.
169    let counts = counts.or_else(|| id_store.agent_native_memory_counts(agent_id, &name).ok().flatten());
170    let (tokens_est, lines) = counts.unwrap_or((tokens_for_chars(size_bytes), 0));
171
172    Ok(Some(NativeMemoryFileMeta {
173        filename: name,
174        is_index,
175        metadata_type,
176        size_bytes,
177        tokens_est,
178        lines,
179        modified_at,
180    }))
181}
182
183/// Merge in mirror-only files — present in a different channel's
184/// write (or the live folder was wiped) but not on this channel's
185/// live FS. Served transparently, with no distinguishing treatment.
186fn append_mirror_only_files(
187    id_store: &crate::backend::storage::store::Store,
188    agent_id: &str,
189    live_filenames: &std::collections::HashSet<String>,
190    files: &mut Vec<NativeMemoryFileMeta>,
191) {
192    match id_store.agent_native_memory_list_meta(agent_id) {
193        Ok(mirrored) => {
194            for row in mirrored {
195                if live_filenames.contains(&row.filename) {
196                    continue;
197                }
198                let (tokens_est, lines) = id_store
199                    .agent_native_memory_counts(agent_id, &row.filename)
200                    .ok()
201                    .flatten()
202                    .unwrap_or((tokens_for_chars(row.size_bytes as u64), 0));
203                files.push(NativeMemoryFileMeta {
204                    is_index: row.filename == "MEMORY.md",
205                    metadata_type: row.metadata_type,
206                    size_bytes: row.size_bytes as u64,
207                    tokens_est,
208                    lines,
209                    modified_at: row.last_seen_mtime_ms,
210                    filename: row.filename,
211                });
212            }
213        }
214        Err(e) => {
215            tracing::warn!(agent_id = %agent_id, error = %e, "agent:memory:list: mirror list failed (non-fatal)");
216        }
217    }
218}
219
220/// `agent:memory:list`.
221pub(crate) fn native_memory_list(state: &AppState, cmd: CommandNativeMemoryListData) -> Result<NativeMemoryListResult, String> {
222    let mstore = &state.mstore;
223    let id_store = &state.id_store;
224
225    let agent = mstore
226        .agent_def_get(&cmd.agent_id)
227        .map_err(|e| format!("agent:memory:list: store: {e}"))?
228        .ok_or_else(|| format!("agent:memory:list: agent {} not found", cmd.agent_id))?;
229
230    // A blank working_directory is the DEFAULT state, not a
231    // reason to short-circuit: `agent.open` substitutes a real
232    // directory whenever this field is blank, so a blank row
233    // still describes an agent with real memories on disk. The
234    // old inline "blank → Ok(files: [])" here was a duplicate,
235    // un-synced copy of the exact blank-workdir bug
236    // SPEC_FIX_PERSONAL_MEMORY_EMPTY_WORKDIR_2026_09_01.md
237    // (#2901) already fixed once in `memory_dir_for_agent_by_id`
238    // itself — that fix never propagated to this handler (or to
239    // read_file/write_file/revert below), so it silently kept
240    // reporting "no memories" for every agent #2901 was
241    // supposed to have fixed. See
242    // SPEC_MEMORY_RPC_HANDLERS_BLANK_WORKDIR_2026_09_02.md.
243    let resolved = resolve_memory_dir_by_id(mstore, &agent).ok_or_else(|| {
244        format!("agent:memory:list: agent {} has no resolvable memory directory", cmd.agent_id)
245    })?;
246    let unverified = resolved.provenance == MemoryDirProvenance::Unverified;
247    let memory_dir = resolved.path;
248
249    // Existing mirror metadata (no content) for this agent, keyed by
250    // filename — lets the loop below skip the expensive full-content
251    // read+upsert for a file that hasn't changed since it was last
252    // mirrored, instead of doing it unconditionally on every list
253    // call (reagent P1 on PR #2459: `list` fires on every Stash
254    // Bundle tab open/refresh, so an unconditional full read + SQLite
255    // write per file would mean synchronous, potentially many-MB
256    // disk I/O on a call meant to be a lightweight metadata listing).
257    //
258    // Compares BOTH size and mtime, not size alone: a same-byte-length
259    // edit is common (e.g. correcting a typo) and size-only comparison
260    // would silently leave the mirror stale for it. This matters for
261    // exactly the case this table exists for — a channel with no live
262    // copy of a file relies entirely on the mirror (reagent P1 on
263    // PR #2459's first pass: read_file only "always re-reads fresh"
264    // on the channel that still HAS a live copy; a channel that never
265    // did has nothing to self-correct with, so a stale mirror row
266    // there is permanent, not "briefly stale").
267    let mirrored_meta: MirroredMeta = id_store
268        .agent_native_memory_list_meta(&agent.id)
269        .unwrap_or_default()
270        .into_iter()
271        .map(|row| (row.filename, (row.size_bytes, row.last_seen_mtime_ms)))
272        .collect();
273
274    let mut files: Vec<NativeMemoryFileMeta> = Vec::new();
275    let mut live_filenames: std::collections::HashSet<String> = std::collections::HashSet::new();
276    // Only a missing directory (never-yet-written, or wiped after this
277    // channel last had files) is treated as "no live files" — any
278    // other read_dir error (permissions, I/O) propagates, matching the
279    // pre-mirror behavior (reagent P2 on PR #2459: silently swallowing
280    // every error here would hide a real access problem behind what
281    // looks like an empty listing). The mirror merge below still runs
282    // regardless, so a wiped live folder doesn't lose durability for
283    // files it mirrored previously.
284    let entries = match std::fs::read_dir(&memory_dir) {
285        Ok(e) => Some(e),
286        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
287        Err(e) => return Err(format!("agent:memory:list: read_dir: {e}")),
288    };
289
290    if let Some(entries) = entries {
291        for entry in entries {
292            let entry = entry.map_err(|e| format!("agent:memory:list: read_dir entry: {e}"))?;
293            if let Some(file) = describe_live_entry(id_store, &agent.id, &mirrored_meta, &entry)? {
294                live_filenames.insert(file.filename.clone());
295                files.push(file);
296            }
297        }
298    }
299
300    append_mirror_only_files(id_store, &agent.id, &live_filenames, &mut files);
301
302    // MEMORY.md first, then alphabetical
303    files.sort_by(|a, b| {
304        b.is_index.cmp(&a.is_index).then(a.filename.cmp(&b.filename))
305    });
306
307    Ok(NativeMemoryListResult { files, unverified })
308}
309
310/// `agent:memory:read_file`.
311pub(crate) fn native_memory_read_file(state: &AppState, cmd: CommandNativeMemoryReadFileData) -> Result<NativeMemoryReadFileResult, String> {
312    let mstore = &state.mstore;
313    let id_store = &state.id_store;
314
315    validate_filename(&cmd.filename)
316        .map_err(|e| format!("agent:memory:read_file: {e}"))?;
317
318    let agent = mstore
319        .agent_def_get(&cmd.agent_id)
320        .map_err(|e| format!("agent:memory:read_file: store: {e}"))?
321        .ok_or_else(|| format!("agent:memory:read_file: agent {} not found", cmd.agent_id))?;
322
323    // See the identical comment on the list handler above — a
324    // blank working_directory is not "no memory dir".
325    let path = memory_dir_for_agent_by_id(mstore, &agent)
326        .ok_or_else(|| {
327            format!("agent:memory:read_file: agent {} has no resolvable memory directory", cmd.agent_id)
328        })?
329        .join(&cmd.filename);
330
331    // Live FS is the freshest copy when present — Claude may have
332    // written moments ago, before this call's mirror upsert even
333    // runs. Fall back to the mirror only when the live file is
334    // genuinely absent (a different channel's write, or the live
335    // folder was wiped) — a live path that exists but fails to
336    // read for another reason (permissions, non-regular file)
337    // still surfaces as an error rather than silently masking it
338    // with stale mirrored content.
339    // Distinguish "genuinely absent" (fall back to the mirror) from
340    // every other symlink_metadata outcome, matching the
341    // pre-durable-sync behavior exactly: a real access error
342    // (permissions, I/O) must surface as an error, not silently
343    // fall back to possibly-stale mirrored content, and an existing
344    // non-regular-file path must be explicitly rejected, not treated
345    // as "absent" either (reagent P1 on PR #2459, second pass —
346    // collapsing every outcome into "absent" the first time around
347    // could serve stale content or a misleading "not found" for a
348    // path that actually exists but errored or is the wrong type).
349    let content = match std::fs::symlink_metadata(&path) {
350        Ok(live_meta) if live_meta.file_type().is_file() => {
351            let mut buf = Vec::new();
352            std::fs::File::open(&path)
353                .and_then(|f| {
354                    use std::io::Read;
355                    f.take(MAX_MEMORY_FILE_BYTES).read_to_end(&mut buf)
356                })
357                .map_err(|e| format!("agent:memory:read_file: {}: {e}", cmd.filename))?;
358            let content = String::from_utf8_lossy(&buf).into_owned();
359
360            let metadata_type = parse_frontmatter_type(&content);
361            let mtime_ms = live_meta
362                .modified()
363                .ok()
364                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
365                .map(|d| d.as_millis() as i64)
366                .unwrap_or(0);
367            if let Err(e) = id_store.agent_native_memory_upsert(
368                &agent.id,
369                &cmd.filename,
370                &content,
371                metadata_type.as_deref(),
372                &path.to_string_lossy(),
373                live_meta.len() as i64,
374                mtime_ms,
375            ) {
376                tracing::warn!(agent_id = %agent.id, filename = %cmd.filename, error = %e, "agent:memory:read_file: mirror upsert failed (non-fatal)");
377            }
378            content
379        }
380        Ok(_) => {
381            return Err(format!("agent:memory:read_file: {} is not a regular file", cmd.filename));
382        }
383        Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
384            return Err(format!("agent:memory:read_file: {}: {e}", cmd.filename));
385        }
386        Err(_) => match id_store.agent_native_memory_read(&agent.id, &cmd.filename) {
387            Ok(Some(mirrored)) => mirrored,
388            Ok(None) => {
389                return Err(format!("agent:memory:read_file: {}: not found", cmd.filename));
390            }
391            Err(e) => {
392                return Err(format!("agent:memory:read_file: {}: not found on this channel and mirror lookup failed: {e}", cmd.filename));
393            }
394        }
395    };
396
397    Ok(NativeMemoryReadFileResult { content })
398}
399
400/// Writes `content` to `dir/filename` through a per-write temp file, so a
401/// reader never sees a half-written file. `who` is the command's name for errors.
402fn write_memory_file_atomically(dir: &std::path::Path, filename: &str, content: &str, who: &str) -> Result<(), String> {
403    let dest = dir.join(filename);
404    // Per-write UUID suffix prevents concurrent writes to the same
405    // filename from sharing a tmp path and silently corrupting each
406    // other's content (reagent P1 on PR #1588).
407    let tmp = dir.join(format!(".{}.{}.tmp", filename, uuid::Uuid::new_v4()));
408
409    // Clean up tmp on both write failure (partial file) and rename failure.
410    if let Err(e) = std::fs::write(&tmp, content) {
411        let _ = std::fs::remove_file(&tmp);
412        return Err(format!("{who}: write tmp: {e}"));
413    }
414    if let Err(e) = std::fs::rename(&tmp, &dest) {
415        let _ = std::fs::remove_file(&tmp);
416        return Err(format!("{who}: rename: {e}"));
417    }
418    Ok(())
419}
420
421/// Mirrors a file just written to `dest` into `db_agent_native_memory`, from
422/// its real on-disk size and mtime. Non-fatal on failure.
423fn mirror_written_file(
424    id_store: &crate::backend::storage::store::Store,
425    agent_id: &str,
426    dest: &std::path::Path,
427    filename: &str,
428    content: &str,
429    who: &str,
430) {
431    let metadata_type = parse_frontmatter_type(content);
432    // Re-stat the just-written file for its real on-disk size/mtime
433    // rather than deriving them from cmd.content here — keeps this
434    // in exact agreement with what a subsequent list() will compute,
435    // so the size+mtime change check there doesn't spuriously treat
436    // this write as "changed again" due to clock/precision drift.
437    let dest_meta = std::fs::metadata(dest).ok();
438    let size_bytes = dest_meta.as_ref().map(|m| m.len() as i64).unwrap_or(content.len() as i64);
439    let mtime_ms = dest_meta
440        .and_then(|m| m.modified().ok())
441        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
442        .map(|d| d.as_millis() as i64)
443        .unwrap_or(0);
444    if let Err(e) = id_store.agent_native_memory_upsert(
445        agent_id,
446        filename,
447        content,
448        metadata_type.as_deref(),
449        &dest.to_string_lossy(),
450        size_bytes,
451        mtime_ms,
452    ) {
453        tracing::warn!(agent_id = %agent_id, filename = %filename, error = %e, "{who}: mirror upsert failed (non-fatal)");
454    }
455}
456
457/// Records a write in the version history and in the agent's memory record,
458/// ahead of the live-file write.
459fn record_write_history(
460    id_store: &crate::backend::storage::store::Store,
461    agent_id: &str,
462    dir: &std::path::Path,
463    cmd: &CommandNativeMemoryWriteFileData,
464) {
465    // Version history — recorded BEFORE the live-file write below,
466    // not after. reagent P1: the drift detector's fast path
467    // (memory/native_drift.rs) subscribes to fs-watch events on
468    // this same directory; if the version row were inserted AFTER
469    // the write (as an earlier revision of this handler did), a
470    // fs-watch event for the write below can be processed before
471    // this version exists, see a hash that doesn't match anything
472    // recorded yet, and log this legitimate RPC write as a
473    // spurious "external_fs_write". Recording the version first
474    // establishes a real happens-before: the file-modify event
475    // that write can possibly generate cannot fire until the
476    // write below actually executes, by which point this version
477    // already exists to match against. Non-fatal on failure — a
478    // durability/review layer on top of the write, not the write
479    // itself (mirrors the mirror-upsert failure handling below).
480    let (version_source, version_detail) = match &cmd.provenance {
481        Some(p) => (crate::backend::storage::agent_native_memory_versions::source_for_caller(p.source.as_str()), p.detail.to_string()),
482        None => ("agent_inferred", "{}".to_string()),
483    };
484    if let Err(e) = id_store.agent_native_memory_version_insert(
485        agent_id,
486        &cmd.filename,
487        &cmd.content,
488        version_source,
489        &version_detail,
490        "",
491    ) {
492        tracing::warn!(agent_id = %agent_id, filename = %cmd.filename, error = %e, "agent:memory:write_file: version insert failed (non-fatal)");
493    }
494    // And into the agent's memory record, likewise first
495    // (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md §2.1.1).
496    crate::backend::memory::reconcile::record_agentmux_write(
497        agent_id,
498        dir,
499        &cmd.filename,
500        cmd.content.as_bytes(),
501        version_source,
502        &version_detail,
503    );
504}
505
506/// `agent:memory:write_file`.
507pub(crate) fn native_memory_write_file(state: &AppState, cmd: CommandNativeMemoryWriteFileData) -> Result<(), String> {
508    let mstore = &state.mstore;
509    let id_store = &state.id_store;
510
511    validate_filename(&cmd.filename)
512        .map_err(|e| format!("agent:memory:write_file: {e}"))?;
513
514    const MAX_CONTENT_BYTES: usize = 10 * 1024 * 1024; // 10 MiB
515    if cmd.content.len() > MAX_CONTENT_BYTES {
516        return Err(format!(
517            "agent:memory:write_file: content too large ({} bytes, max {})",
518            cmd.content.len(),
519            MAX_CONTENT_BYTES,
520        ));
521    }
522
523    let agent = mstore
524        .agent_def_get(&cmd.agent_id)
525        .map_err(|e| format!("agent:memory:write_file: store: {e}"))?
526        .ok_or_else(|| format!("agent:memory:write_file: agent {} not found", cmd.agent_id))?;
527
528    // See the identical comment on the list handler above — a
529    // blank working_directory is not "no memory dir".
530    let dir = memory_dir_for_write_by_id(mstore, &agent)
531        .map_err(|e| format!("agent:memory:write_file: {e}"))?;
532    std::fs::create_dir_all(&dir)
533        .map_err(|e| format!("agent:memory:write_file: mkdir: {e}"))?;
534
535    // Conditional save (SPEC_MEMORY_FOLLOWS_THE_AGENT_2026_09_24.md
536    // §2.4): a caller that says which content its draft started
537    // from gets a refusal, not an overwrite, when that content
538    // has since moved. Checked before the version row below so a
539    // refused write leaves no trace in history. Not atomic with
540    // the rename further down — a write landing in between still
541    // wins — but it closes the window from minutes (a human
542    // editing) to microseconds, which is the case this exists for.
543    if let Some(base) = cmd.base_sha256.as_deref() {
544        let current = current_memory_content(id_store, &agent.id, &dir.join(&cmd.filename), &cmd.filename)
545            .map_err(|e| format!("agent:memory:write_file: {e}"))?;
546        check_memory_base_sha256(&cmd.filename, base, current.as_deref())
547            .map_err(|e| format!("agent:memory:write_file: {e}"))?;
548    }
549
550    record_write_history(id_store, &agent.id, &dir, &cmd);
551
552    write_memory_file_atomically(&dir, &cmd.filename, &cmd.content, "agent:memory:write_file")?;
553    mirror_written_file(id_store, &agent.id, &dir.join(&cmd.filename), &cmd.filename, &cmd.content, "agent:memory:write_file");
554
555    // Reactive Memory updates (SPEC_ARMORY_REACTIVE_UPDATES_2026_09_02.md):
556    // same event, same `agent:memory:changed:{canonical_uuid}`
557    // naming convention `app_api::mod`'s write/revert already use
558    // for the MemoryWrite MCP tool's own path — keying by
559    // `agent.id` (the canonical UUID this whole file's other
560    // handlers already key by, per `resolve_agent_uuid`'s own
561    // doc comment on why a slug-keyed event here would silently
562    // miss frontend subscribers that only ever have the UUID).
563    state.broker.publish_event_for::<crate::backend::mps_events::AgentMemoryChanged>(&agent.id, &(), vec![], 0);
564
565    tracing::info!(
566        agent_id = %cmd.agent_id,
567        filename = %cmd.filename,
568        bytes = cmd.content.len(),
569        "agent:memory:write_file"
570    );
571    // `register_typed` always sends a `data` field, so this `()`
572    // puts `"data": null` on the wire where the old untyped
573    // `Ok(None)` omitted the key entirely. All three frontend
574    // callers (the memory models' draft `save` and
575    // `createFile`, NativeMemoryFileView.tsx's draft `save`) await
576    // and discard the result, and no other crate invokes this
577    // command, so the difference is unobservable.
578    Ok(())
579}
580
581/// `agent:memory:adoption_list`. Offers only: adopting a listed folder is
582/// `agent:memory:adopt` (`native_memory_adopt_handlers.rs`), the window's only, never
583/// this RPC — every agent holds the key this one is called with.
584pub(crate) async fn native_memory_adoption_list(
585    state: &AppState,
586    cmd: CommandNativeMemoryAdoptionListData,
587) -> Result<NativeMemoryAdoptionListResult, String> {
588    let mstore = state.mstore.clone();
589    let agent = mstore
590        .agent_def_get(&cmd.agent_id)
591        .map_err(|e| format!("agent:memory:adoption_list: store: {e}"))?
592        .ok_or_else(|| format!("agent:memory:adoption_list: agent {} not found", cmd.agent_id))?;
593    let Some(fs) = crate::backend::transcript::damage::global_for(&crate::backend::transcript::damage::memory_zone(&agent.id)) else {
594        return Ok(NativeMemoryAdoptionListResult { list: None });
595    };
596    let list = tokio::task::spawn_blocking(move || crate::backend::memory::adopt::list(&fs, &mstore, &agent))
597        .await
598        .map_err(|e| format!("agent:memory:adoption_list: {e}"))?
599        .map_err(|e| format!("agent:memory:adoption_list: {e}"))?;
600    Ok(NativeMemoryAdoptionListResult { list })
601}
602
603/// `agent:memory:claims`. Offers only, like the adoption list: releasing is
604/// `agent:memory:release`, the window's only.
605pub(crate) async fn native_memory_claims(
606    state: &AppState,
607    cmd: CommandNativeMemoryClaimsData,
608) -> Result<crate::backend::memory::release::ClaimList, String> {
609    let agent = state
610        .mstore
611        .agent_def_get(&cmd.agent_id)
612        .map_err(|e| format!("agent:memory:claims: store: {e}"))?
613        .ok_or_else(|| format!("agent:memory:claims: agent {} not found", cmd.agent_id))?;
614    let fs = crate::backend::transcript::damage::global_for(&crate::backend::transcript::damage::memory_zone(&agent.id))
615        .ok_or_else(|| "agent:memory:claims: memory record store unavailable, or its record is damaged".to_string())?;
616    tokio::task::spawn_blocking(move || crate::backend::memory::release::list(&fs, &agent.id))
617        .await
618        .map_err(|e| format!("agent:memory:claims: {e}"))?
619        .map_err(|e| format!("agent:memory:claims: {e}"))
620}
621
622/// `agent:memory:history`.
623pub(crate) fn native_memory_history(state: &AppState, cmd: CommandNativeMemoryHistoryData) -> Result<NativeMemoryHistoryResult, String> {
624    validate_filename(&cmd.filename)
625        .map_err(|e| format!("agent:memory:history: {e}"))?;
626
627    // Resolve to the same canonical agent.id write_file keys
628    // by, for the same reason app_api::memory_history_impl
629    // does (reagent P1) — cmd.agent_id is expected to already
630    // be that id for this surface (the frontend passes
631    // AgentDefinition.id), but resolving explicitly here
632    // rather than trusting it verbatim matches write_file's
633    // own validation and closes the gap if that assumption
634    // ever stops holding for some caller.
635    let agent = state
636        .mstore
637        .agent_def_get(&cmd.agent_id)
638        .map_err(|e| format!("agent:memory:history: store: {e}"))?
639        .ok_or_else(|| format!("agent:memory:history: agent {} not found", cmd.agent_id))?;
640
641    let versions = state
642        .id_store
643        .agent_native_memory_version_list(&agent.id, &cmd.filename)
644        .map_err(|e| format!("agent:memory:history: store: {e}"))?
645        .into_iter()
646        .map(version_summary_to_meta)
647        .collect();
648
649    Ok(NativeMemoryHistoryResult { versions })
650}
651
652/// `agent:memory:diff`.
653pub(crate) fn native_memory_diff(state: &AppState, cmd: CommandNativeMemoryDiffData) -> Result<NativeMemoryDiffResult, String> {
654    let id_store = &state.id_store;
655    // Resolve to the same canonical agent.id write_file keys by
656    // — see the identical comment on the history handler above.
657    let agent = state
658        .mstore
659        .agent_def_get(&cmd.agent_id)
660        .map_err(|e| format!("agent:memory:diff: store: {e}"))?
661        .ok_or_else(|| format!("agent:memory:diff: agent {} not found", cmd.agent_id))?;
662
663    let from = id_store
664        .agent_native_memory_version_get(&cmd.from_version_id)
665        .map_err(|e| format!("agent:memory:diff: store: {e}"))?
666        .ok_or_else(|| format!("agent:memory:diff: version {} not found", cmd.from_version_id))?;
667    let to = id_store
668        .agent_native_memory_version_get(&cmd.to_version_id)
669        .map_err(|e| format!("agent:memory:diff: store: {e}"))?
670        .ok_or_else(|| format!("agent:memory:diff: version {} not found", cmd.to_version_id))?;
671    // reagent P1: unlike list/read/write/history/revert, this
672    // handler has no other agent-scoping — every caller shares
673    // one instance-wide X-AuthKey, so without this check any
674    // caller could read any other agent's memory content by
675    // version id.
676    if from.agent_id != agent.id || to.agent_id != agent.id {
677        return Err(format!(
678            "agent:memory:diff: one or both versions do not belong to {}",
679            cmd.agent_id
680        ));
681    }
682    // reagent P2: ownership alone isn't enough — from/to must
683    // also be versions of the SAME file, or the "diff" is a
684    // meaningless line-by-line comparison of two unrelated
685    // files with no error to signal that.
686    if from.filename != to.filename {
687        return Err(format!(
688            "agent:memory:diff: from_version_id and to_version_id are versions of different files ({} vs {})",
689            from.filename, to.filename
690        ));
691    }
692
693    let diff = line_diff(&from.content, &to.content);
694    Ok(NativeMemoryDiffResult { diff })
695}
696
697/// `agent:memory:revert`.
698pub(crate) fn native_memory_revert(state: &AppState, cmd: CommandNativeMemoryRevertData) -> Result<NativeMemoryRevertResult, String> {
699    let mstore = &state.mstore;
700    let id_store = &state.id_store;
701
702    validate_filename(&cmd.filename)
703        .map_err(|e| format!("agent:memory:revert: {e}"))?;
704
705    // Resolve to the same canonical agent.id write_file keys by
706    // — see the identical comment on the history handler above.
707    // Resolved BEFORE the ownership check below (not after, as
708    // an earlier revision of this handler did) so that check
709    // compares against the same id the version was actually
710    // stored under, not the raw, possibly-different cmd.agent_id.
711    let agent = mstore
712        .agent_def_get(&cmd.agent_id)
713        .map_err(|e| format!("agent:memory:revert: store: {e}"))?
714        .ok_or_else(|| format!("agent:memory:revert: agent {} not found", cmd.agent_id))?;
715
716    let target = id_store
717        .agent_native_memory_version_get(&cmd.target_version_id)
718        .map_err(|e| format!("agent:memory:revert: store: {e}"))?
719        .ok_or_else(|| format!("agent:memory:revert: version {} not found", cmd.target_version_id))?;
720    if target.agent_id != agent.id || target.filename != cmd.filename {
721        return Err(format!(
722            "agent:memory:revert: version {} does not belong to {}/{}",
723            cmd.target_version_id, cmd.agent_id, cmd.filename
724        ));
725    }
726
727    // Revert is implemented as a NEW write through the same
728    // path as agent:memory:write_file (live file + mirror +
729    // version), not a rewrite of history — this is the
730    // git-revert-not-git-reset guarantee from the spec's §4.3.
731    // See the identical comment on the list handler above — a
732    // blank working_directory is not "no memory dir".
733    let dir = memory_dir_for_write_by_id(mstore, &agent).map_err(|e| {
734        format!("agent:memory:revert: {e}")
735    })?;
736    std::fs::create_dir_all(&dir)
737        .map_err(|e| format!("agent:memory:revert: mkdir: {e}"))?;
738
739    // Version recorded BEFORE the live-file write below — same
740    // fs-watch-race rationale as agent:memory:write_file's own
741    // handler above (reagent P1). Unlike that handler, a failure
742    // here IS fatal: the RPC's whole contract is "return the new
743    // version," so silently reverting the file but not returning
744    // a version would leave the caller with no way to know what
745    // they just reverted to.
746    let detail = serde_json::json!({ "reverted_to": cmd.target_version_id }).to_string();
747    let new_version = id_store
748        .agent_native_memory_version_insert(&agent.id, &cmd.filename, &target.content, "revert", &detail, "")
749        .map_err(|e| format!("agent:memory:revert: version insert: {e}"))?;
750    crate::backend::memory::reconcile::record_agentmux_write(
751        &agent.id,
752        &dir,
753        &cmd.filename,
754        target.content.as_bytes(),
755        "revert",
756        &detail,
757    );
758
759    write_memory_file_atomically(&dir, &cmd.filename, &target.content, "agent:memory:revert")?;
760    mirror_written_file(id_store, &agent.id, &dir.join(&cmd.filename), &cmd.filename, &target.content, "agent:memory:revert");
761
762    // See the identical comment on write_file's own handler above.
763    state.broker.publish_event_for::<crate::backend::mps_events::AgentMemoryChanged>(&agent.id, &(), vec![], 0);
764
765    tracing::info!(
766        agent_id = %cmd.agent_id,
767        filename = %cmd.filename,
768        target_version_id = %cmd.target_version_id,
769        "agent:memory:revert"
770    );
771    Ok(NativeMemoryRevertResult { version: version_to_meta(&new_version) })
772}
773
774pub fn register_native_memory_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
775    super::memory_launch_cost::register(engine, state);
776
777    let s = state.clone();
778    engine.register_typed(COMMAND_NATIVE_MEMORY_LIST, move |cmd: CommandNativeMemoryListData, _ctx| {
779        let s = s.clone();
780        async move { native_memory_list(&s, cmd) }
781    });
782
783    let s = state.clone();
784    engine.register_typed(COMMAND_NATIVE_MEMORY_READ_FILE, move |cmd: CommandNativeMemoryReadFileData, _ctx| {
785        let s = s.clone();
786        async move { native_memory_read_file(&s, cmd) }
787    });
788
789    let s = state.clone();
790    engine.register_typed(COMMAND_NATIVE_MEMORY_WRITE_FILE, move |cmd: CommandNativeMemoryWriteFileData, _ctx| {
791        let s = s.clone();
792        async move { native_memory_write_file(&s, cmd) }
793    });
794
795    let s = state.clone();
796    engine.register_typed(COMMAND_NATIVE_MEMORY_ADOPTION_LIST, move |cmd: CommandNativeMemoryAdoptionListData, _ctx| {
797        let s = s.clone();
798        async move { native_memory_adoption_list(&s, cmd).await }
799    });
800
801    let s = state.clone();
802    engine.register_typed(COMMAND_NATIVE_MEMORY_CLAIMS, move |cmd: CommandNativeMemoryClaimsData, _ctx| {
803        let s = s.clone();
804        async move { native_memory_claims(&s, cmd).await }
805    });
806
807    let s = state.clone();
808    engine.register_typed(COMMAND_NATIVE_MEMORY_HISTORY, move |cmd: CommandNativeMemoryHistoryData, _ctx| {
809        let s = s.clone();
810        async move { native_memory_history(&s, cmd) }
811    });
812
813    let s = state.clone();
814    engine.register_typed(COMMAND_NATIVE_MEMORY_DIFF, move |cmd: CommandNativeMemoryDiffData, _ctx| {
815        let s = s.clone();
816        async move { native_memory_diff(&s, cmd) }
817    });
818
819    let s = state.clone();
820    engine.register_typed(COMMAND_NATIVE_MEMORY_REVERT, move |cmd: CommandNativeMemoryRevertData, _ctx| {
821        let s = s.clone();
822        async move { native_memory_revert(&s, cmd) }
823    });
824}
825
826// Request-shape tests for the six `agent:memory:*` commands.
827//
828// These exist because NOTHING else catches a Req/payload mismatch: `tsc` only
829// checks the frontend against the GENERATED types, and
830// `scripts/check-rpc-bindings.sh` only checks that a generated type exists for
831// each command — neither one ever deserializes a real payload into the Rust
832// struct. A `Req` that cannot parse what the stub sends compiles, typechecks,
833// passes the binding gate, and then fails on every call at runtime. That is
834// exactly the bug found on `bookmarks.list` (`Req = ()` rejects `{}`), so each
835// command below is pinned to the literal JSON its call site actually sends.
836#[cfg(test)]
837#[path = "tests/native_memory_handlers/req_shape_tests.rs"]
838mod req_shape_tests;
839
840#[cfg(test)]
841#[path = "tests/native_memory_handlers/tests.rs"]
842mod tests;
843
844#[cfg(test)]
845#[path = "tests/native_memory_handlers/handler_tests.rs"]
846mod handler_tests;