·

Real World Workflow Memory Strategy For Long Running Agents

Walk through a real production workflow that uses Memory MCP so your AI agent can persist and recall context across sessions end to end.

Everything in this module so far covered one client at a time. Real teams run agents across several of these tools against the same repo — someone on Cursor, someone on Claude Code CLI, a CI job driving OpenCode headlessly. Without a deliberate strategy, that produces four divergent, partially-overlapping memory files instead of one shared source of accumulated project knowledge. This topic is the workflow that keeps a memory graph useful six months in, not just in the first excited week after setup.


Workflow Overview: Memory Lifecycle from Capture to Recall to Pruning

Think of memory MCP not as a feature you turn on once, but as a lifecycle with three recurring stages, each needing its own discipline:

CAPTURE  ──────────▶  RECALL  ──────────▶  PRUNE
(write facts at        (search/open         (audit, correct,
 task boundaries)        before work)         delete stale entries)
     ▲                                              │
     └──────────────────────────────────────────────┘
         (pruned graph feeds the next capture cycle)

Skip capture discipline and the graph stays empty — you've paid the setup cost in earlier topics for nothing. Skip recall discipline and a well-populated graph sits unused while the agent re-derives facts it already knows, because nobody prompted it to look. Skip pruning and the graph actively degrades — old, wrong, or superseded facts get returned by search_nodes with the same confidence as current ones, and eventually someone stops trusting memory results at all, which defeats the entire investment.

The three steps below map onto these three stages, in the order a team should actually implement them: first agree on structure (so capture is consistent across tools and people), then automate capture (so it doesn't rely on everyone remembering to do it manually), then build the audit habit (so the graph doesn't rot silently).

Tips
- Treat capture, recall, and prune as three separate disciplines needing separate habits — a team that nails capture but skips pruning ends up worse off than one that never started.
- The pruned output of one cycle is the trusted input of the next — an audit isn't a one-time cleanup, it's what keeps future capture worth doing.
- If you can only start with one discipline, start with pruning conventions (Step 3) even before volume builds up — it's much cheaper to enforce from day one than to retrofit onto a year of unaudited entries.


Step 1: Defining Memory Categories and Naming Conventions for a Team

Before any tool writes a single entity, put a short, versioned convention document somewhere the whole team (and every agent) reads — a docs/memory-conventions.md checked into the repo, referenced from each tool's CLAUDE.md/GEMINI.md/system prompt equivalent so agents pick it up automatically.


## Entity Types (fixed vocabulary — do not invent new ones without updating this doc)
- decision    — architectural/process choice + reasoning
- constraint  — a hard limit (infra, API, business rule)
- convention  — repo-specific naming/style rule
- component   — a service, module, or major file/directory
- incident    — a bug/outage and its fix

## Naming Rules
- Entity names: kebab-case, no spaces, match the primary file/module name
  where one exists (e.g. "topic-fixture-pipeline", not "Topic Fixture Pipeline").
- Incident entities: suffix with the ISO date, e.g. "conn-pool-exhaustion-2026-08".
- Relation types: active-voice verb, snake_case: depends_on, writes_to, owns,
  blocks, supersedes, revealed, follows_convention.

## Storage
- Single shared file: /Users/{you}/agent-memory/english-grammar-platform.json
- Every tool (Claude Code, Cursor, Gemini CLI, OpenCode) points MEMORY_FILE_PATH
  at this same file for this repo. No per-tool memory files.

## What Never Goes In
- Secrets, credentials, PII, unverified speculation stated as fact.

This single document is what makes memory MCP a team asset instead of four people's four private notebooks. Without it, one developer's Claude Code session creates entityType: "arch-decision" while another's Cursor session creates entityType: "decision" for the same category of fact, and search_nodes results start looking inconsistent in ways that erode trust in the tool faster than any technical limitation would.

Point every client's config at the same file, per this module's earlier topics:

{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-memory"],
      "env": { "MEMORY_FILE_PATH": "/Users/dat/agent-memory/english-grammar-platform.json" }
    }
  }
}

For OpenCode's different schema, the same path goes under environment instead of env (see Topic 3 of this module) — the convention doc should call that out explicitly since it's the one client where the config key names genuinely differ.

Tips
- Write the conventions doc before the first entity gets created, not after inconsistency has already accumulated — retrofitting a naming scheme means manual graph surgery later.
- Reference the conventions doc from every tool's own memory/context file (CLAUDE.md, GEMINI.md, etc.) so agents apply it without a human re-explaining it each session.
- Call out client-specific config differences (OpenCode's environment vs everyone else's env) explicitly in the doc — this is the most common source of "why isn't memory shared" support questions on a team.


Step 2: Automating Memory Capture at Task Boundaries

Manual "remember this" prompts work, but they depend on someone thinking to issue them, every time, which decays under deadline pressure exactly when the decisions being made are most worth capturing. Move capture to a task-boundary habit baked into how the team closes out work, not an optional extra step.

The most reliable trigger point is the same moment you'd write a good commit message or PR description — you already have to summarize what changed and why, so extending that habit into a memory write is close to free:

End-of-task prompt template (put this in a team snippet/alias):

  Before finishing, do this:
  1. Summarize what changed and why, in 2-4 sentences.
  2. If this involved a decision, constraint, or non-obvious fix,
     store it as a memory entity per docs/memory-conventions.md.
  3. If it corrects or supersedes an existing memory entity, update
     that entity (add_observations/delete_observations) instead of
     creating a duplicate.
  4. Tell me exactly what you stored, or explicitly say "nothing
     memory-worthy this session" if that's the case.

Point 4 matters as much as points 1-3 — a habit that only ever reports successes trains you to stop checking, and silent no-ops (the agent deciding nothing was worth storing, correctly or not) should be visible, not invisible.

For CI-driven or headless agent runs (an OpenCode job in a pipeline, for instance), wire the same prompt into the task's closing step programmatically rather than relying on an interactive session ending cleanly:

opencode run --prompt "$(cat prompts/close-out-task.md)" \
  --session-id "$CI_JOB_ID" \
  --non-interactive
<!-- prompts/close-out-task.md -->
Summarize this automated task's outcome. If it revealed a constraint,
fixed a non-obvious bug, or made an architectural choice, store it as
a memory entity per docs/memory-conventions.md, entityType "incident"
if it was a fix, "decision" if it was a choice. Otherwise, take no
memory action.

This is where memory MCP genuinely earns its place over a human-maintained CLAUDE.md — a CI job can write structured facts into the graph without a person in the loop at all, something a manually-edited markdown file structurally can't do without someone reviewing and merging a PR for every entry.

Tips
- Attach memory capture to the same moment you write a commit message or close a PR — piggybacking on an existing habit beats inventing a new one people forget.
- Make "nothing memory-worthy this session" an explicit, visible output, not a silent default — otherwise you can't tell a correct no-op from a missed capture.
- Automated/CI agent runs are a strong fit for programmatic memory capture since there's no human "did I remember to do this" step to rely on or forget.


Step 3: Auditing Memory Quality and Preventing Context Poisoning

This is the step teams skip, and it's the one that determines whether the graph is trustworthy a year from now. Context poisoning — wrong or stale facts treated as authoritative because they're sitting in the same structure as correct ones — compounds silently. An agent that reads a poisoned entity doesn't flag it as suspect; it reasons from it exactly as confidently as it would from a verified fact, and may write new observations that build on the wrong premise, making the next audit harder.

Run a scheduled audit — every two to four weeks for an active project, more often right after a major refactor — with a prompt that separates finding candidates from acting on them:

Audit prompt:

  Read the full memory graph (read_graph). For each entity, check:
  1. Does it reference a file path that still exists in the current repo?
  2. Does it describe behavior that still matches the current code
     (spot-check 2-3 of the highest-traffic entities by actually
     reading the referenced file)?
  3. Does it contain anything that looks like a secret, credential,
     or PII (grep-style check: "password", "token", "key=", "@" email
     patterns)?

  Produce a report: entities to update, entities to delete, and any
  security concern to flag immediately. Do NOT delete or modify
  anything yet — just report.

The explicit "do NOT delete or modify anything yet" instruction is the safeguard against the audit itself becoming a poisoning vector — an agent's judgment about what's stale is inference, not ground truth, and giving it unsupervised delete authority over the team's shared memory just moves the risk rather than removing it.

Follow up on the report with targeted human-approved fixes:

Follow-up: I've reviewed the report. Go ahead and delete the
"legacy-auth-flow" and "old-caching-layer" entities — confirmed
obsolete. For "rate-limiter", update it per the report's suggested
correction. Leave everything else as-is for now.

Add a lightweight automated check as a second line of defense, independent of any agent's judgment — a plain script run in CI or a cron job that flags obvious credential patterns without needing an LLM call at all:

#!/usr/bin/env bash
MEMORY_FILE="${MEMORY_FILE_PATH:-$HOME/agent-memory/english-grammar-platform.json}"
grep -inE 'password|secret|api[_-]?key|token\s*[:=]|-----BEGIN' "$MEMORY_FILE" \
  && { echo "WARNING: possible secret found in memory file"; exit 1; } \
  || echo "OK: no obvious secret patterns in $MEMORY_FILE"

Running this on a schedule (or as a pre-commit hook if the memory file happens to be checked into the repo) catches the worst-case outcome — a credential accidentally persisted — even if the periodic LLM-driven audit misses it or hasn't run yet.

Tips
- Separate "find candidates" from "act on candidates" into two explicit steps with a human approval gate in between — never give an agent unsupervised delete authority over shared team memory.
- Spot-check a handful of high-traffic entities against the actual current code during each audit, not just a metadata scan — this is what catches "technically still there but behaviorally wrong" staleness.
- Back the LLM-driven audit with a plain, non-AI script that greps for secret-like patterns — a deterministic safety net costs almost nothing and doesn't depend on the audit prompt catching everything.


Tips

Tips
- Model memory as a three-stage lifecycle — capture, recall, prune — and build a separate habit for each; strength in one doesn't compensate for neglecting another.
- Write and share a naming/entity-type convention doc before volume builds up, and point every tool at the same MEMORY_FILE_PATH so the graph is genuinely shared, not fragmented per tool.
- Automate capture at natural task-boundary moments (commit, PR close, CI job end) rather than relying on someone remembering to prompt for it.
- Schedule recurring audits with a human approval gate before any deletion, and back them with a simple deterministic secret-pattern scan independent of any LLM judgment call.