Manage persistent agent memory across OpenCode (core memory blocks + Graphiti temporal knowledge graph) and compatible harnesses (Claude Code, Codex). Use when asked to remember, save, recall, forget, audit, compact, or route memory across tiers, resolve stale/contradictory memories, or verify subagent/web claims before persisting.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Structured Memory?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/tkolleh-structured-memory)
---
name: structured-memory
description: >-
Manage persistent agent memory across OpenCode (core memory blocks + Graphiti
temporal knowledge graph) and compatible harnesses (Claude Code, Codex). Use
when asked to remember, save, recall, forget, audit, compact, or route memory
across tiers, resolve stale/contradictory memories, or verify subagent/web
claims before persisting.
metadata:
audience: agent
workflow: memory-management
harnesses: "opencode, claude-code, codex"
---
# Structured Memory
Agent memory degrades fastest from indiscriminate writes, wrong tier placement,
and stale unverified facts. Use this skill to decide **whether** to remember
something, **which tier** owns it, **how** to write and recall it cleanly in
OpenCode (with core memory blocks + Graphiti) and other harnesses, and **how**
to audit or prune it safely.
For exact OpenCode + Graphiti tool signatures and Code Mode recipes, read
[references/graphiti-opencode.md](references/graphiti-opencode.md). For
cross-harness tier mapping (Claude Code, Codex, markdown memory dirs) and the
full routing table, read
[references/portable-harnesses.md](references/portable-harnesses.md). For the
academic and industry evidence behind these rules, read
[references/research-summary.md](references/research-summary.md).
## 1. Memory Tiers & Routing
Route every piece of information to the **narrowest durable tier** that fits —
or do not persist it at all.
| Tier | OpenCode Mechanism | Scope & Lifetime | Put Here | Never Put Here |
| --- | --- | --- | --- | --- |
| **1. Core memory blocks** | `persona`, `human`, `project` (`memory_get`, `memory_set`, `memory_replace`, `memory_list`, `memory_oversized`) | Always in system context; `global` (`persona`, `human`) or `project` (`project`); ~5,000-char soft budget per block | Standing user preferences, communication style, high-signal project commands/architecture/gotchas needed on *every* turn | Incident logs, long histories, raw tool output, facts already in `AGENTS.md`, sprawling prose |
| **2. Temporal knowledge graph** | **Graphiti MCP** (FalkorDB-backed; default `group_id: "opencode"`) | Long-term, searchable, bi-temporal episodic + entity/fact graph across sessions | Cross-session preferences & procedures, tool/environment quirks, decisions with dates, multi-session sagas, relational facts between systems/people/repos | Live scratchpad state, line-number code trivia, secrets/tokens, unverified guesses |
| **3. Repository-tracked docs** | `AGENTS.md`, `CLAUDE.md`, ADRs, `docs/` | Version-controlled, team-shared repo truth | Canonical architecture decisions, build/test commands, repo conventions every contributor/agent should share | Personal preferences, private workflows, machine-local quirks |
| **4. Ephemeral session state** | In-conversation plan, todo list, scratch notes | Current task/session only | In-flight subtask status, temporary hypotheses, current debugging steps | Anything expected to survive into next week's session |
### Never Persist (Any Tier)
- **Cheaply re-derivable codebase state**: file paths, line numbers, symbol
locations, git history/blame, or diff summaries — re-read the codebase or run
`git log` instead. Code memories rot silently.
- **Duplicates of standing repo docs**: if it is already in `AGENTS.md` or
`CLAUDE.md`, do not mirror it into core blocks or Graphiti.
- **Secrets, credentials, or sensitive PII**: never write API keys, tokens,
passwords, private keys, or personal identifiers into any memory tier.
## 2. The Core Loop
Work through these steps in order before writing any memory:
1. **Selectivity gate** — Would this still save time in a future session (or on
an unrelated project)? Selectivity beats exhaustive logging: irrelevant
records dilute retrieval and degrade agent behavior. When marginal, skip the
write.
2. **Classify the memory**:
- **Procedural** (reusable rules, corrections, workflows) — highest value for
coding agents.
- **Semantic** (durable preferences, tool behaviors, standing facts).
- **Episodic** (specific events, investigations, dated decisions — belong in
Graphiti with `reference_time` or a `saga`, not in core blocks).
- **Working** (active task state — keep ephemeral; do not persist).
3. **Choose the tier** — Apply the table in Section 1. If a fact applies only
within one repository and helps all contributors, put it in repo docs
(`AGENTS.md`/ADR) rather than private memory.
4. **Write cleanly** — Follow the tier-specific rules below.
## 3. Core Memory Blocks (OpenCode)
Core blocks are injected into **every prompt**. Treat every character as
expensive real estate:
- **Scopes**: `persona` and `human` are `global`; `project` is `project`-scoped.
- **Soft budget**: ~5,000 chars per block (`over_limit=true` when exceeded).
Check sizes with `memory_list` or `memory_oversized`.
- **Edit surgically**: prefer `memory_replace` (single `oldText`/`newText` or
atomic `edits[]`) over `memory_set` full rewrites. Full rewrites waste output
tokens and cause context collapse over time.
- **Read fresh before editing**: call `memory_get({ label, scope })` when exact
on-disk text is uncertain — the system-prompt snapshot may lag behind recent
updates.
- **Graduate overflow to Graphiti**: if a core block grows past its budget,
distill core blocks down to terse bullets and move detailed histories,
procedures, or multi-project reference facts into Graphiti.
## 4. Graphiti in OpenCode
### Invocation
- **Code Mode enabled** (OpenCode): call `await tools.graphiti.<tool>({ ... })`
inside `execute`. Batch independent read calls with `Promise.allSettled`.
- **Direct MCP tools** (other harnesses): invoke the matching Graphiti MCP tool
directly.
- **Health check**: run `get_status()` when troubleshooting connectivity or
before bulk curation.
### Toolset Overview (13 Tools)
| Category | Tools | Purpose |
| --- | --- | --- |
| **Write** | `add_memory`, `add_triplet` | Ingest rich episodes (`add_memory`, async LLM extraction) or write one exact fact immediately (`add_triplet`, synchronous). |
| **Read / Recall** | `search_nodes`, `search_memory_facts`, `get_episodes`, `get_episode_entities`, `get_entity_edge`, `get_status` | Hybrid semantic + keyword + graph search over entities and temporal facts, inspect recent episodes, trace provenance, check server health. |
| **Synthesize** | `summarize_saga`, `build_communities` | Summarize an ordered narrative (`saga`) or detect entity clusters across a group (`build_communities` is expensive — run intentionally). |
| **Curate / Delete** | `delete_episode`, `delete_entity_edge`, `clear_graph` | Cascade-remove a bad episode, delete one wrong fact edge, or wipe a group (`clear_graph` requires explicit user confirmation). |
Full signatures and recipes live in
[references/graphiti-opencode.md](references/graphiti-opencode.md).
### Configured Entity Types
This Graphiti setup registers nine entity types:
`Preference`, `Requirement`, `Procedure`, `Location`, `Event`, `Organization`,
`Document`, `Topic`, `Object`
Pass exact names to `search_nodes({ entity_types: [...] })` to narrow recall or
to `add_memory({ excluded_entity_types: [...] })` when suppressing noisy
extractions.
### Write Patterns & Operational Rules
- **`add_memory` vs `add_triplet` vs core blocks**:
- Use **core memory blocks** for tiny, high-frequency rules needed on every
turn.
- Use **`add_memory`** as the default Graphiti write for rich notes,
decisions, incidents, procedures, and structured JSON (`source`: `'text'`,
`'json'`, or `'message'`).
- Use **`add_triplet`** (`source_node_name`, `edge_name`, `fact`,
`target_node_name`) when you need a single deterministic relationship
deduplicated, embedded, and queryable **immediately** without LLM
extraction.
- **Respect async extraction**: `add_memory` returns immediately and extracts
entities/facts asynchronously in the background (sequentially per `group_id`
to avoid races). Do **not** assume ingestion failed if `search_nodes` or
`search_memory_facts` run 1 second later does not return the new episode yet.
Use `add_triplet` if immediate read-after-write visibility is required.
- **Keep `group_id` consistent**:
- Default `group_id` is `"opencode"` for cross-session personal and
engineering knowledge.
- Use a dedicated `group_id` (such as a repository name) only when strict
graph isolation is explicitly desired.
- Always pass matching `group_id` on writes and `group_ids` on reads so facts
never silently vanish behind a mismatched group.
- **Write crisp, self-contained episodes**:
- Name entities explicitly (`"diffnotes.nvim uses DuckDB CLI subprocesses"`) —
never use bare pronouns (`"it"`, `"they"`, `"this repo"`) that confuse
entity resolution.
- Provide a descriptive `name` and `source_description` (e.g.,
`"user preference"`, `"architecture decision"`, `"debugging finding"`).
- For `source: "json"`, pass a properly escaped JSON string
(`JSON.stringify(payload)`), never a raw object.
- Group multi-session investigations with `saga` (and
`saga_previous_episode_uuid` when ordering matters), then refresh the
narrative with `summarize_saga`.
- **Bi-temporal hygiene (supersede vs delete)**:
- Graphiti automatically records ingestion time and event time
(`reference_time`), and invalidates (`invalid_at`) outdated facts when a
newer contradicting episode arrives. **Let legitimate changes supersede
naturally** by ingesting the updated fact rather than deleting history.
- Pass ISO-8601 `reference_time` (naive timestamps are UTC) whenever
recording an event or decision that happened in the past.
- Reserve `delete_episode` (cascades entities/facts solely supported by that
episode while preserving shared ones) and `delete_entity_edge` for
**wrong, hallucinated, or sensitive** memories — trace provenance first
with `get_episode_entities`.
## 5. Recall Before Assuming
Check existing memory before re-fetching documentation or re-investigating a
known area:
1. **Core memory blocks** — already in context (use `memory_get` if you need
fresh on-disk contents).
2. **Graphiti** — run `search_memory_facts` and `search_nodes` in parallel for
relevant topics, preferences, or prior decisions. Re-rank around a key
entity with `center_node_uuid` or constrain by `valid_at_*` / `invalid_at_*`
for time-sensitive queries.
3. **Repository docs** — check `AGENTS.md`, `CLAUDE.md`, and `docs/`.
4. **Live inspection / external fetch** — verify live code, run commands, or
fetch external docs when memory is absent or stale.
Remember: a stored memory is a claim about the state of the world *when it was
recorded*. Verify file paths, flags, or API behavior against live code before
acting on stale technical details.
## 6. Epistemic Verification
A claim from a subagent report, web search snippet, or prior session summary is
**not** automatically settled fact:
- **Direct user statements** about their own preferences or workflow can be
persisted directly.
- **External technical claims** (CLI flags, library semantics, benchmarks,
citations, quotes) must be verified against a primary source (official docs,
source code, or a live command) before persisting as settled knowledge.
- If a claim cannot be verified yet, either verify it first or do not persist
it as a confirmed fact.
## 7. Auditing, Curation & Maintenance
When the user asks to audit, clean up, consolidate, or compact memory,
**inspect actual state first and propose concrete actions before mutating**:
1. **Inspect Core Memory Blocks**:
- Call `memory_list()` and `memory_oversized()` to find bloated or
`over_limit` blocks.
- Read candidates with `memory_get()` and identify stale items, repo-doc
duplicates, or entries better moved to Graphiti.
2. **Inspect Graphiti**:
- Check health with `get_status()`.
- Inspect recent ingestion with `get_episodes({ group_ids: ["opencode"], max_episodes: 20 })`
and targeted `search_memory_facts` / `search_nodes` queries.
- Trace suspicious or contradictory facts back to their source episodes with
`get_episode_entities({ episode_uuids })`.
3. **Check Cross-Tier Contradictions**:
- Compare core blocks, Graphiti facts, and repo docs (`AGENTS.md`) for
conflicts or stale rules.
4. **Propose Concrete Cleanup Actions** (wait for approval before executing
destructive changes):
- Compact `over_limit` core blocks via surgical `memory_replace`.
- Supersede outdated Graphiti facts with a fresh `add_memory` episode, or
purge genuinely wrong entries with `delete_episode` / `delete_entity_edge`.
- Run `summarize_saga` for active sagas or `build_communities` only when
broad synthesis is explicitly worthwhile.
- **Never** call `clear_graph` without explicit, confirmed user approval.
5. **Markdown Memory Directories (Portable Harnesses)**:
- When auditing file-based markdown memories (such as Claude Code
auto-memory), run `main.py check-links --memory-dir <path>` to detect
dangling `[[links]]`, malformed frontmatter, and orphan files.
## Further Reading
- [references/graphiti-opencode.md](references/graphiti-opencode.md) — exact
schemas for all 13 Graphiti tools, 5 core memory block tools, configured
entity types, and Code Mode recipes.
- [references/portable-harnesses.md](references/portable-harnesses.md) — tier
mapping for Claude Code / Codex, markdown memory conventions, and full
routing decision table.
- [references/research-summary.md](references/research-summary.md) — primary-
source-checked research behind selectivity, bi-temporal superseding, and
compaction rules.
- `main.py` — read-only `check-links` auditor for markdown memory directories.