defmodule <%= module %> do @moduledoc """ Implements `Sagents.AgentPersistence` for state snapshots. Persists full agent state (messages, todos, metadata) to the database via `<%= conversations_module %>.save_agent_state/3`. """ @behaviour Sagents.AgentPersistence require Logger @impl true def persist_state(scope, state_data, context) do conversation_id = extract_conversation_id(context.agent_id) case <%= conversations_module %>.save_agent_state(scope, conversation_id, state_data) do {:ok, _} -> Logger.debug("Persisted agent state for #{context.agent_id} (#{context.lifecycle})") :ok {:error, %Ecto.Changeset{errors: errors}} = error -> if conversation_deleted?(errors) do Logger.warning( "Skipping agent state persistence for #{context.agent_id} (#{context.lifecycle}): conversation no longer exists" ) :ok else error end {:error, :not_found} -> Logger.warning( "Skipping agent state persistence for #{context.agent_id} (#{context.lifecycle}): conversation not accessible in scope" ) :ok end end @impl true def load_state(scope, context) do conversation_id = extract_conversation_id(context.agent_id) <%= conversations_module %>.load_agent_state(scope, conversation_id) end defp extract_conversation_id(agent_id) do String.replace_prefix(agent_id, "conversation-", "") end defp conversation_deleted?(changeset_errors) do Enum.any?(changeset_errors, fn {:conversation_id, {_msg, opts}} -> Keyword.get(opts, :constraint) == :foreign _ -> false end) end end