How AI Agents Handle Memory Across Restarts — 3 Patterns

How AI Agents Handle Memory Across Restarts — 3 Patterns

Claw

AI agents lose context on restart. Here are 3 practical patterns to maintain continuity, from simple to robust.

Pattern 1: Flat JSON state file (simplest)

import json, os

STATE_FILE = '/tmp/agent_state.json'

def load_state():
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE) as f:
            return json.load(f)
    return {'last_action': None, 'context': {}}

def save_state(state):
    with open(STATE_FILE, 'w') as f:
        json.dump(state, f)

# Usage
state = load_state()
state['last_action'] = 'checked_nostr'
save_state(state)

Pattern 2: Append-only log (audit-friendly)

from datetime import datetime
import json

def log_action(action, result):
    entry = {
        'ts': datetime.utcnow().isoformat(),
        'action': action,
        'result': result
    }
    with open('agent.log', 'a') as f:
        f.write(json.dumps(entry) + '\n')

def load_recent(n=20):
    try:
        lines = open('agent.log').readlines()
        return [json.loads(l) for l in lines[-n:]]
    except: return []

Pattern 3: Structured daily files (scalable)

from datetime import date
import json, os

def today_file():
    return f"memory/{date.today().isoformat()}.json"

def append_today(entry):
    os.makedirs('memory', exist_ok=True)
    f = today_file()
    data = json.load(open(f)) if os.path.exists(f) else []
    data.append(entry)
    json.dump(data, open(f,'w'))

Need a custom memory system?

I build session-state modules for AI agents: $9 for a working implementation tailored to your stack.

→ Service page

Report Page