Class FileMemoryStore

java.lang.Object
com.tnsai.memory.AbstractMemoryStore
com.tnsai.memory.FileMemoryStore
All Implemented Interfaces:
MemoryStore

public class FileMemoryStore extends AbstractMemoryStore
File-based persistent memory store. Saves conversation history to a JSON file.

Uses AbstractMemoryStore for common functionality and adds file persistence. History is automatically saved after each modification and loaded on init.

On-disk format:

  • Current format is a versioned envelope: {"version": 1, "messages": [...]}
  • Legacy plain-array files ([...]) written by older versions are still readable; they are rewritten in the envelope format on the next save

Crash safety:

  • Writes go to a sibling .tmp file followed by an atomic Files.move(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...) with StandardCopyOption.ATOMIC_MOVE, so the on-disk JSON is always either the previous good state or the new full state — never a half-written file
  • Filesystems without atomic-move support (NFS, some FUSE) fall back to a plain replace; the store lock still prevents interleaved saves
  • If a file cannot be parsed on load it is preserved as <name>.json.corrupt-<timestamp> instead of being overwritten, and the store starts empty

Filename derivation:

  • Agent IDs are encoded as URL-safe Base64 (no padding) of their UTF-8 bytes — collision-free and safe for any characters, including / and .. (same approach as Sona's ScopedIdFilename)
  • The resolved path is normalized and verified to stay inside the storage directory as defense-in-depth
  • Files written before this encoding (raw <agentId>.json) are still picked up on load as a read-only fallback

Thread safety:

  • All operations are synchronized via AbstractMemoryStore
  • File operations are atomic (temp file + atomic move)

Error handling: save failures throw IllegalStateException (unchecked), matching the constructor's initialization-failure contract.

Suitable for:

  • Production environments requiring conversation persistence
  • Long-running agents that need to resume conversations
  • Multi-session scenarios
See Also:
  • Constructor Details

    • FileMemoryStore

      public FileMemoryStore()
    • FileMemoryStore

      public FileMemoryStore(String storageDirPath)
  • Method Details

    • init

      public void init(String agentId)
      Description copied from interface: MemoryStore
      Initializes the memory store for a specific agent.
      Specified by:
      init in interface MemoryStore
      Overrides:
      init in class AbstractMemoryStore
      Parameters:
      agentId - The unique ID of the agent
    • getAgentFile

      public Path getAgentFile()
      Returns the path to the agent's memory file. Useful for debugging and monitoring.
      Returns:
      path to the JSON file, or null if not initialized