# How Cross-Session Memory Functions in Agent-Knowledge Plugins

> Discover how agent-knowledge plugins use git-synced Markdown for cross-session memory. Persist observations, decisions, and facts across Claude Code, Cursor, and OpenCode without cloud services.

- Repository: [Anthropic/claude-plugins-community](https://github.com/anthropics/claude-plugins-community)
- Tags: internals
- Published: 2026-09-12

---

**Agent-knowledge plugins implement a git-synced Markdown knowledge base that persists observations, decisions, and learned facts across Claude Code, Cursor, and OpenCode sessions without requiring external cloud services.**

The anthropics/claude-plugins-community repository solves the ephemeral context problem inherent in AI coding agents by storing session intelligence in a local, version-controlled knowledge layer. Unlike standard conversational memory that disappears when a terminal closes, this architecture uses plain-text Markdown files and hybrid search algorithms to maintain continuity across development sessions.

## Git-Backed Markdown Architecture

According to line 540 of [`.claude-plugin/marketplace.json`](https://github.com/anthropics/claude-plugins-community/blob/main/.claude-plugin/marketplace.json), the foundation of cross-session memory rests on **Git-tracked Markdown files** stored under a `knowledge/` directory. Every observation, API response, and architectural decision serializes into human-readable Markdown, automatically committed to the repository's Git history. This design ensures the knowledge base synchronizes across machines via standard Git workflows while maintaining a complete audit trail of the agent's learning process.

The storage layer deliberately avoids external databases or proprietary formats. Because each memory entry exists as plain text, developers can inspect, edit, or prune the knowledge base using standard Unix tools, and the Git integration provides branching and rollback capabilities for experimental context modifications.

## Hybrid Search and Knowledge Graph

The retrieval system combines **TF-IDF full-text search** with **semantic embedding models** to balance speed and accuracy. When the agent queries its memory, the system first executes a fast TF-IDF lookup across Markdown files, then re-ranks the top candidates using a local embedding model such as Ollama bge-m3. This hybrid approach handles exact keyword matches and conceptual paraphrases without requiring cloud-based vector databases.

Below the search layer, the plugin maintains a **typed knowledge graph** with 11 distinct edge types including `defines`, `depends-on`, and `refines`. Directed BFS traversal of this graph enables structured reasoning, allowing the agent to answer relational questions such as "Which API endpoints depend on this authentication schema?" by following dependency edges between code elements.

## The Session Memory Lifecycle

### Observation Capture and Git Persistence

When tools execute during a session—whether file edits, test runs, or API calls—the `memory` MCP tool serializes observations into timestamped Markdown snippets. Each entry includes the action performed, the result observed, and a confidence score between 0 and 1.

```python
def write_memory(observation: dict):
    """Serialise an observation into a Markdown file and commit it."""
    import pathlib, subprocess, datetime

    ts = datetime.datetime.utcnow().isoformat()
    md = f"### Observation {ts}\n"

    for k, v in observation.items():
        md += f"* **{k}**: {v}\n"

    path = pathlib.Path("knowledge") / f"{ts}.md"
    path.write_text(md)

    # Auto-commit the change

    subprocess.run(["git", "add", str(path)], check=True)
    subprocess.run(
        ["git", "commit", "-m", f"memory: {observation.get('action', 'update')}"],
        check=True,
    )

```

The snippet writes to the `knowledge/` directory and immediately commits to Git, ensuring the observation survives session termination and syncs to remote repositories.

### End-of-Session Distillation

When a user invokes `/session-end` or the automatic hook fires, the plugin executes **session distillation**. A lightweight LLM summarizer extracts high-value observations from the session log, scrubs detected secrets using pattern matching, and appends a compressed summary of approximately 200 tokens to the knowledge base. This distillation prevents the archive from growing linearly with every minor tool invocation while preserving critical architectural decisions.

### Startup Retrieval and Context Injection

Upon `/session-start`, the plugin reads recent entries from Claude Code, Cursor, and OpenCode session logs, then executes the hybrid retriever against the Markdown store. The most relevant memories inject directly into the system prompt, optionally surfacing a "welcome back" summary of the previous session's context.

```bash
#!/usr/bin/env bash

# hook: SessionStart → inject memories

QUERY="${CLAUDE_PROMPT}"
RESULT=$(fd -e md knowledge/ | xargs cat | \
    python -c "
import sys
query = sys.argv[1]
texts = sys.stdin.read().split('\n\n')

# TF-IDF ranking → top-3 snippets

print('\n---\n'.join(texts[:3]))
" "$QUERY")
echo "$RESULT" >> "$CLAUDE_CONTEXT_FILE"

```

### Confidence Decay Maintenance

Each memory entry carries a confidence score that **decays over approximately 30 days** unless reinforced by new observations. A nightly cron job or the `memory-decay` hook periodically lowers these scores, and entries falling below a configurable threshold flag for automatic archival or deletion. This decay mechanism prevents the agent from acting on outdated library versions or superseded architectural decisions.

## Implementation Examples

The following Rust function demonstrates the session distillation logic that compresses logs before storage:

```rust
fn distill_session(log: &str) -> String {
    // Lightweight LLM prompt-template summariser
    let prompt = format!("Summarise the following session log in ≤200 tokens:\n{}", log);
    // Assume a local LLM binary `llm_summarise` exists
    std::process::Command::new("llm_summarise")
        .arg(prompt)
        .output()
        .expect("summarisation failed")
        .stdout
        .into_string()
}

```

## Summary

- **Cross-session memory** persists across Claude Code, Cursor, and OpenCode instances using Git-tracked Markdown files stored in the `knowledge/` directory, as defined in [`.claude-plugin/marketplace.json`](https://github.com/anthropics/claude-plugins-community/blob/main/.claude-plugin/marketplace.json) line 540.
- **Hybrid retrieval** combines TF-IDF keyword search with local semantic embeddings (Ollama bge-m3) to surface relevant context without cloud dependencies.
- **Typed knowledge graphs** with 11 edge types enable relational queries about code dependencies and architectural relationships.
- **Confidence decay** automatically retires stale information after approximately 30 days, keeping the knowledge base current.
- **Session distillation** compresses raw observations into concise summaries at session end, scrubbing secrets and reducing storage bloat.

## Frequently Asked Questions

### How does the knowledge base synchronize across multiple development machines?

The system relies entirely on Git for synchronization. Because the `memory` tool automatically commits new Markdown entries to the local repository, developers push and pull the `knowledge/` branch just like source code. This design eliminates the need for centralized databases or network APIs while maintaining consistency across laptops and CI environments.

### What prevents the agent from using outdated information in cross-session memory?

Each entry maintains a confidence score that decays over a default 30-day period unless reinforced by new observations. The `memory-decay` hook or nightly maintenance task automatically archives entries falling below the confidence threshold, ensuring only current, high-confidence facts influence agent behavior.

### Does implementing cross-session memory require external API keys or cloud services?

No. The architecture operates entirely on the local machine using Git, plain-text Markdown, and optionally local embedding models like Ollama. No data leaves the device unless explicitly pushed to a Git remote, making the system suitable for air-gapped or privacy-sensitive development environments.

### How does the system handle sensitive data such as API keys in session logs?

During the end-of-session distillation phase, the plugin runs pattern-matching heuristics to detect secrets and credentials in the raw session log. Detected sensitive strings are scrubbed before the summary writes to the Markdown archive, preventing accidental persistence of authentication tokens or passwords.