diff --git a/pages/ai-ecosystem.mdx b/pages/ai-ecosystem.mdx index 7e91a9b31..ab86f7dfa 100644 --- a/pages/ai-ecosystem.mdx +++ b/pages/ai-ecosystem.mdx @@ -36,9 +36,9 @@ This section covers: ranking and prompt assembly as one Cypher query, and [Agentic GraphRAG](/ai-ecosystem/graph-rag/agentic-graphrag) lets an agent choose the retrieval pipeline for each question. -- [AI memory](/ai-ecosystem/ai-memory): Store semantic, episodic and procedural - memory (what a system knows, what it did and what it knows how to do) as - one graph that any AI system can query across sessions. +- [AI memory](/ai-ecosystem/ai-memory): Give coding agents a long-term memory + with Context Graph, which records their sessions in Memgraph and serves them + back to every connected agent in later sessions. - [Agentic AI](/ai-ecosystem/agentic-ai): Store an agent's states and actions as a reasoning graph, so the agent plans by traversing scored paths instead of by prompting, and every decision leaves a trace you can inspect. @@ -78,9 +78,8 @@ an API key. - [AI memory](/ai-ecosystem/ai-memory): Sets up Context Graph, which records - your coding agents' sessions in Memgraph as semantic, episodic and - procedural memory. It asks before it changes anything. You need Docker. On - Windows, the command prints the setup command to run in WSL or Git Bash. + your coding agents' sessions in Memgraph and serves them back as memory. It + asks before it changes anything. You need Docker. diff --git a/pages/ai-ecosystem/ai-memory.mdx b/pages/ai-ecosystem/ai-memory.mdx index d1db91f22..0d0fb456c 100644 --- a/pages/ai-ecosystem/ai-memory.mdx +++ b/pages/ai-ecosystem/ai-memory.mdx @@ -1,40 +1,42 @@ --- title: AI memory -description: Store what an AI system knows, did and knows how to do as one graph in Memgraph, and set it up for your coding agents with one command. +description: Give coding agents and custom agents a long-term memory in Memgraph with Context Graph, which records their sessions and serves them back later. --- import { Tabs } from 'nextra/components' # AI memory -AI memory lets an AI system remember across sessions. In Memgraph, memory is a -graph of entities and typed relationships, so recall follows the connections -between what the system knows, what it did and what it knows how to do, not -only what sounds similar to the question. +AI memory lets an AI agent use what happened in earlier sessions: what you +decided, what it did and what it learned about your work. -## How Memgraph stores memory +Context Graph is Memgraph's AI memory. It records the sessions of your coding +agents, such as Claude Code and Codex, as a graph in Memgraph, and serves them +back to every connected agent in later sessions. -Memgraph stores three types of long-term memory in one graph: +It connects to the +[supported agents](/ai-ecosystem/ai-memory/agents) with no code to write. +[Custom agents](/ai-ecosystem/ai-memory/custom-agents), built on the Claude +Agent SDK or the OpenAI Agents SDK, can use the same memory. -| Memory type | What it holds | How it's stored | -| --- | --- | --- | -| **Semantic** | What the system knows, such as facts and preferences | `(:User)-[:HAS_MEMORY]->(:Memory)` | -| **Episodic** | What the system did, such as past interactions | `(:Session)-[:HAS_ACTION]->(:Action)`, in order by `FOLLOWED_BY` | -| **Procedural** | What the system knows how to do, such as workflows | `(:Session)-[:USED_SKILL]->(:Skill)` | +Every connected agent gets: -The `User` and `Session` nodes are shared by all three types, so one traversal -can recall facts, past actions and skills together. +- **Recording.** Hooks in the agent write each session to the graph as it + happens. You use the agent as before. +- **Recall.** A `recall` tool, served over the Model Context Protocol (MCP), + returns what your past sessions hold about a question. Each session also + starts with a short note on where you left off in the current project. +- **Memory**, if you turn it on. A `memory` tool replaces the agent's own + memory, so the notes the agent saves are stored in the graph and shared by + all your agents. -## Set up memory for your coding agents +Context Graph is open source, part of the +[Memgraph AI Toolkit](https://github.com/memgraph/ai-toolkit/tree/main/context-graph). -[Context Graph](https://github.com/memgraph/ai-toolkit/tree/main/context-graph), -part of the Memgraph AI Toolkit, records the sessions of your coding agents in -Memgraph as these three types of memory, so the agents can recall them in -later sessions. It works with Claude Code, Codex, GitHub Copilot CLI, Cursor, -OpenCode, Antigravity CLI and Grok Build. +## Get started -You need [Docker](https://docs.docker.com/get-docker/), unless you already run -Memgraph 3.6 or later, and a terminal. Start the setup: +One command installs Context Graph, finds or starts Memgraph and connects the +agents you choose. It shows its plan and changes nothing until you confirm. @@ -43,80 +45,94 @@ curl -sSL https://install.memgraph.com/ai-memory | bash ``` -Run the setup from WSL or Git Bash. In PowerShell, this command prints the -command to run there: - ```powershell iwr https://install.memgraph.com/ai-memory/windows -useb | iex ``` -The setup shows its plan and changes nothing until you confirm. Then it: - -1. **Finds or starts Memgraph.** It uses the Memgraph in its configuration, - then one on `localhost:7687`, and otherwise starts the - `memgraph/memgraph-mage` image in a container named - `context-graph-memgraph`, with a data volume. If port 7687 is taken, it - picks a free port. -2. **Saves its configuration:** the Memgraph URL and your user ID, which - defaults to your git `user.name`. -3. **Installs the packages:** `uv` if it's missing, the - `memgraph-context-graph` command-line tool and its connectors. -4. **Connects your agents.** Claude Code and Codex get the Context Graph - plugin for your user. The other agents get hooks in the current project - directory. -5. **Checks the setup** and prints the command to rerun for any step that - failed. - -Without a terminal, for example in CI, the command only prints the setup -command to run. Set `AI_MEMORY_SKIP_SETUP=1` to get the same behavior. - -After the setup, every session of a connected agent writes `Memory`, `Action` -and `Skill` nodes to the graph, and the next session reads its memory back. -To manage the setup: - -- `memgraph-context-graph ui` shows what your agents record, in the terminal. -- `memgraph-context-graph setup` changes your choices and skips what's already - done. -- `memgraph-context-graph uninstall` disconnects the agents. The graph and the - configuration stay. - -For the other options and how to look at the graph in Memgraph Lab, see the -[Context Graph guide](https://github.com/memgraph/ai-toolkit/blob/main/context-graph/README.md#getting-started). - -## Query the memory graph - -Because the three types share the `User` and `Session` nodes, one query can -answer a request such as "schedule a follow-up with the client like last -time". This query returns what the system knows about a user, their most -recent session in which a meeting was scheduled, and the skill used in it: - -```cypher template -MATCH (u:User {user_id: "USER_ID"})-[:HAS_MEMORY]->(mem:Memory) -MATCH (u)-[:HAD_SESSION]->(s:Session)-[:HAS_ACTION]->(a:Action {tool_name: "schedule_meeting"}) -WITH u, mem, s, a ORDER BY s.started_at DESC LIMIT 1 -OPTIONAL MATCH (s)-[:USED_SKILL]->(sk:Skill) -RETURN mem.content AS client_facts, s.session_id AS last_session, - a.timestamp AS last_meeting_at, sk.name AS skill, sk.content AS how_to -``` - -`USER_ID` is the user ID from the setup. To see all the labels, relationship -types and properties the memory graph uses, run: - -```cypher -SHOW SCHEMA INFO; -``` - -The Memgraph that the setup starts has schema info enabled. If you use your -own instance, start it with `--schema-info-enabled=true`. - -## Use another memory framework - -If you already use an agent memory framework, you can keep it and store its -memory in Memgraph: - -- [Mem0](/ai-ecosystem/integrations/mem0): Use Memgraph as the backend for Mem0 - graph memory, in Mem0 1.x. -- [Cognee](/ai-ecosystem/integrations/cognee): Use Memgraph as the graph - database for Cognee's knowledge graph. +See [Get started](/ai-ecosystem/ai-memory/get-started) for the prerequisites, +the choices setup offers and how to check that sessions are recorded. + +## How it works + +Context Graph works in three phases, shown in the diagram: during a session, +it records each event and serves recall from Memgraph; after the session, +reconciliation builds a knowledge graph from what was recorded. + +
+ +![Context Graph data flow in three phases: during a session, hooks in the agent send each event through the connectors to Memgraph, and the MCP server serves recall and memory from Memgraph back to the agent; after the session, reconciliation extracts a knowledge graph on your machine](/pages/ai-ecosystem/ai-memory/context-graph-flow.svg) + +
+
+ +![Context Graph data flow in three phases: during a session, hooks in the agent send each event through the connectors to Memgraph, and the MCP server serves recall and memory from Memgraph back to the agent; after the session, reconciliation extracts a knowledge graph on your machine](/pages/ai-ecosystem/ai-memory/context-graph-flow-dark.svg) + +
+ +### During a session + +- **Hooks.** The `memgraph-context-graph` hooks run in the agent, whether a + coding agent or a custom agent, on each event: a prompt, a reply, a tool + call or its result. They drop text marked as private and redact secrets + before anything is stored. +- **Connectors.** The hooks pass each event to the connectors, which write it + to Memgraph. Each one records one part of a session: + - `actions-graph`: prompts, replies, tool calls and their results; + - `skills-graph`: the agent skills a session used; + - `sessions-graph`: the session, its user and project, and the memories the + agent saved; + - `resources-graph`, optional: the GitHub resources a session read. + + On Memgraph Enterprise, `context-graph-spaces` adds + [shared spaces](/ai-ecosystem/ai-memory/shared-spaces) for a team. +- **Memgraph.** Users, sessions, actions, skills and memories form one graph, + and the knowledge graph links to them. See + [The graph](/ai-ecosystem/ai-memory/graph). +- **MCP server.** The MCP server reads Memgraph and serves the `recall` and + `memory` tools to the agent. See + [Recall and memory](/ai-ecosystem/ai-memory/recall-and-memory). + +### After a session + +When a session ends, [reconciliation](/ai-ecosystem/ai-memory/graph#add-a-knowledge-graph) +extracts the people, organizations, projects and other entities it mentions, +and the facts that connect them, into a knowledge graph. It runs on your +machine: + +1. **Ontology.** The ontology is the schema of the knowledge graph: the entity + types and fact types to look for, such as a person who works for an + organization. It's a model in HyGM, the AI Toolkit's graph schema package. + Every user starts with a default ontology, and you can write your own. +2. **Extract.** GLiNER2, a local extraction model, finds the entities and + facts of those types in the session's text. It needs no LLM API key. +3. **Store.** The entities and facts are stored in Memgraph with their + embeddings, linked to the messages they came from. Recall uses them to find + facts spread over many sessions. + +**Ontology learning** is optional. With an Anthropic or OpenAI API key in the +configuration, Context Graph learns new entity and fact types from your +sessions. It's the only part of Context Graph that sends session text off +your machine. + +## In this section + +- [Get started](/ai-ecosystem/ai-memory/get-started): Install Context Graph, + connect your agents and check that sessions are recorded. +- [Recall and memory](/ai-ecosystem/ai-memory/recall-and-memory): How agents + read their past sessions, and how to make Context Graph their memory. +- [The graph](/ai-ecosystem/ai-memory/graph): What your agents recorded, how + to browse and query it, and how to add a knowledge graph of entities and + facts. +- [Privacy](/ai-ecosystem/ai-memory/privacy): What is recorded, how to keep + text out of the graph, and how to delete sessions. +- [Supported agents](/ai-ecosystem/ai-memory/agents): The files setup changes + for each agent, and how the agents differ. +- [Custom agents](/ai-ecosystem/ai-memory/custom-agents): Use the same memory + in an app built on the Claude Agent SDK or the OpenAI Agents SDK. +- [Shared spaces](/ai-ecosystem/ai-memory/shared-spaces): Share memory between + the members of a team, on Memgraph Enterprise. +- [Configuration](/ai-ecosystem/ai-memory/configuration): The configuration + file, recall and extraction settings, your own Memgraph, updating and + uninstalling. diff --git a/pages/ai-ecosystem/ai-memory/_meta.ts b/pages/ai-ecosystem/ai-memory/_meta.ts new file mode 100644 index 000000000..c8adb9688 --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/_meta.ts @@ -0,0 +1,10 @@ +export default { + "get-started": "Get started", + "recall-and-memory": "Recall and memory", + "graph": "The graph", + "privacy": "Privacy", + "agents": "Supported agents", + "custom-agents": "Custom agents", + "shared-spaces": "Shared spaces", + "configuration": "Configuration" +} diff --git a/pages/ai-ecosystem/ai-memory/agents.mdx b/pages/ai-ecosystem/ai-memory/agents.mdx new file mode 100644 index 000000000..94d361925 --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/agents.mdx @@ -0,0 +1,130 @@ +--- +title: Supported agents +description: See what Context Graph setup changes for Claude Code, Codex, GitHub Copilot CLI, Cursor, OpenCode, Antigravity CLI and Grok Build. +--- + +import { Tabs } from 'nextra/components' + +# Supported agents + +Context Graph works with seven coding agents. For each one, setup installs +hooks that record sessions, registers the Model Context Protocol (MCP) server +that serves the `recall` +and `memory` tools, and can turn off the agent's own memory. + +This page lists the files setup changes for each agent, and where the agents +behave differently. For an app you build on an agent SDK, see +[Custom agents](/ai-ecosystem/ai-memory/custom-agents). + +| Agent | Runtime name | How it's connected | Applies to | +| --- | --- | --- | --- | +| Claude Code | `claude-code` | Context Graph plugin | Your user | +| Codex | `codex` | Context Graph plugin | Your user | +| GitHub Copilot CLI | `copilot-cli` | `.github/hooks/memgraph-context-graph.json` | One project | +| Cursor | `cursor` | `.cursor/hooks.json` | One project | +| OpenCode | `opencode` | `.opencode/plugins/memgraph-context-graph/index.js` | One project | +| Antigravity CLI | `antigravity-cli` | `.agents/hooks.json` | One project | +| Grok Build | `grok` | `.grok/hooks/memgraph-context-graph.json` | One project | + +Use the runtime name to choose agents in `memgraph-context-graph setup`, +`update`, `uninstall` and `doctor`. + +Claude Code and Codex sessions are recorded in any directory. For the other +agents, the hook file is in the project directory, never in your home +directory, so only sessions started in a connected project are recorded. +Connect more projects with `--project-dir`. If a hook file already exists, +setup keeps your own hooks in it. + +## MCP server registration + +The `recall` and `memory` tools are served by `memgraph-context-graph mcp`, an +MCP server named `context-graph`. Memory belongs to you, not to one project, +so the server is registered in each agent's user-level configuration: + +| Agent | Where the server is registered | How its tools are allowed | +| --- | --- | --- | +| Claude Code | The plugin | The plugin | +| Codex | The plugin | The plugin | +| GitHub Copilot CLI | `~/.copilot/mcp-config.json` | Copilot CLI has no allow list: approve the tools once, or start it with `--allow-tool=context-graph` | +| Cursor | `~/.cursor/mcp.json` | `Mcp(context-graph:*)` in `~/.cursor/cli-config.json` | +| OpenCode | `mcp.servers` in `~/.config/opencode/opencode.json` | An allow rule in `permissions` | +| Antigravity CLI | `~/.gemini/config/mcp_config.json` | `mcp(context-graph/*)` in `~/.gemini/antigravity-cli/settings.json` | +| Grok Build | `~/.grok/config.toml` | `MCPTool(context-graph__*)` | + +Setup adds the tools to the agent's allow list because an agent that runs +without a person, for example in a script, refuses a tool that needs approval. +Each file setup edits keeps the rest of its content and is backed up once, to +`FILE_NAME.context-graph.bak` next to it. + +## Built-in memory + +When you make Context Graph the agents' memory, setup turns off the agent's +own memory, so the agent doesn't keep two. Some agents have no memory of their +own to turn off. + +| Agent | Built-in memory | What setup changes | +| --- | --- | --- | +| Claude Code | Auto memory | Sets `autoMemoryEnabled: false` in `~/.claude/settings.json` and imports the existing memory files | +| Codex | Memories | Turns off `features.memories`, `memories.use_memories` and `memories.generate_memories` in `~/.codex/config.toml` and imports the existing memory | +| GitHub Copilot CLI | Copilot Memory, stored on GitHub | Sets `"memory": false` in `~/.copilot/settings.json`; the memory stays on GitHub and isn't imported | +| Cursor | None | Nothing | +| OpenCode | None | Nothing | +| Antigravity CLI | None in the CLI | Nothing | +| Grok Build | Topic notes in `~/.grok/memory-v2/` | Sets `[memory_v2] enabled = false` and imports the notes to `/memories/grok/` | + +See [Memory](/ai-ecosystem/ai-memory/recall-and-memory#memory) +for how the import works and how to switch back. + +## Differences between agents + +The agents' hooks don't all expose the same events, so some features work +differently: + +- **Session-start note.** Every agent gets the note on where you left off at + the start of a session. Grok Build's start hooks can't add text for the + model, so it gets the note through the MCP server's instructions instead. + Codex limits hook text to about 2,500 tokens, so a long memory index is cut + from its end. +- **Note before a tool call.** Only Claude Code and Codex can show the agent a + note right before a tool runs, such as that a GitHub issue it's about to + fetch is already in the graph. The other agents' pre-tool hooks can only + allow, block or rewrite the call. +- **End of a session.** Codex, Antigravity CLI and `opencode run` don't report + when a session ends. Their sessions are processed at the end of each turn + instead, so nothing is lost. +- **Antigravity CLI** hooks don't carry the prompt or reply text. Context Graph + reads the turns from the session transcript the agent writes. +- **Cursor:** the session-start note reaches the Cursor CLI. The agent window + in the Cursor editor may not show it to the model. +- **Codex** also reloads the memory index after it compacts the context. + +## Connect an agent manually + +Setup connects agents for you. To install the Claude Code or Codex plugin +yourself, for example on a machine where you manage plugins by hand: + + + +```bash +claude plugin marketplace add memgraph/ai-toolkit --sparse .claude-plugin +claude plugin install context-graph@context-graph-plugins -y +``` + + +```bash +codex plugin marketplace add memgraph/ai-toolkit --sparse .agents/plugins +codex plugin add context-graph@context-graph-plugins +``` + + + +For the per-project agents, the `memgraph-context-graph hook init RUNTIME` +command writes the hook file in the current directory, where `RUNTIME` is the +agent's runtime name: + +```bash +memgraph-context-graph hook init cursor +``` + +The `hook init` command writes only the hooks. Run `memgraph-context-graph setup` for the +MCP server registration and the memory switch. diff --git a/pages/ai-ecosystem/ai-memory/configuration.mdx b/pages/ai-ecosystem/ai-memory/configuration.mdx new file mode 100644 index 000000000..33c9f93a4 --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/configuration.mdx @@ -0,0 +1,304 @@ +--- +title: Configure Context Graph +description: Configure Context Graph's Memgraph connection, identity and what it records, and update or uninstall Context Graph. +--- + +import { Callout } from 'nextra/components' + +# Configure Context Graph + +Context Graph keeps its settings in one configuration file. Setup writes it, +and the `config` command changes it. This page also covers how to +[use your own Memgraph](#use-your-own-memgraph), +[run setup again](#run-setup-again) to change your choices, +[choose what is recorded](#choose-what-is-recorded), and +[update](#update-context-graph) or [uninstall](#uninstall-context-graph) +Context Graph. + +## Configuration file + +Setup writes the configuration to `~/.config/context-graph/config.toml`, +readable only by you. Set the `CONTEXT_GRAPH_CONFIG` environment variable to +use another path. + +The file lists every key under a comment that says what it does. A key you +haven't set is commented out, with its default, so you can see all settings +in one place. Setup and `config set` rewrite the file: they keep your values +and `[redact]` patterns, but not comments you add. + +The hooks read their settings only from this file, not from environment +variables, because agents run hooks without your shell's environment. Change +settings with the `config` command: + +```bash +memgraph-context-graph config show +memgraph-context-graph config get memgraph.url +memgraph-context-graph config set identity.user_id alice +memgraph-context-graph config set recall.turns_k "" +``` + +An empty value, as in the last command, sets a key back to its default. The +exception is `capture.connectors`, where an empty value records nothing. +`config set` checks each value and refuses one that Context Graph can't use, +so a typo doesn't break recording later. It takes these keys: + +| Key | Default | What it sets | +| --- | --- | --- | +| `identity.user_id` | Your git `user.name`, set by setup | Your user ID. Your sessions and memories are filed under it, and recall searches only its sessions. | +| `memgraph.url` | `bolt://localhost:7687` | The Memgraph Bolt URL | +| `memgraph.user` | None | The Memgraph user name | +| `memgraph.password` | None | The Memgraph password. `config set memgraph.password` without a value prompts for it. | +| `memgraph.database` | `memgraph` | The database, on a Memgraph with [multi-tenancy](/database-management/multi-tenancy) | +| `capture.connectors` | `skills-graph, actions-graph, sessions-graph` | What the hooks record. See [Choose what is recorded](#choose-what-is-recorded). | +| `capture.redact` | `true` | Whether secrets are redacted before they're stored. See [Redact secrets](/ai-ecosystem/ai-memory/privacy#redact-secrets). | +| `capture.max_chars` | `100000` | The most characters kept from one text field, such as a tool's output. `0` keeps everything. See [Shorten long text](/ai-ecosystem/ai-memory/privacy#shorten-long-text). | +| `capture.exclude_tools` | None | Tools whose calls and results aren't recorded, by name or glob. See [Exclude tools and projects](/ai-ecosystem/ai-memory/privacy#exclude-tools-and-projects). | +| `capture.exclude_projects` | None | Directories in which nothing is recorded, by path or glob | +| `memory.backend` | `native` | `context-graph` when Context Graph is the agents' [memory](/ai-ecosystem/ai-memory/recall-and-memory#memory), `native` when they keep their own. Set it with setup's `--memory-backend`, which also changes the agents' settings. | +| `session_start.resume` | `true` | Whether a session starts with the [note on where you left off](/ai-ecosystem/ai-memory/recall-and-memory#recall) | +| `recall.*` | See [Recall configuration](#recall-configuration) | The embedding model for recall, which searches run, and how many results each returns | +| `reconcile.auto_reconcile` | `false` | Whether the [knowledge graph](/ai-ecosystem/ai-memory/graph#add-a-knowledge-graph) is built after each session | +| `ontology.path` | The default ontology | An ontology file for the knowledge graph | +| `ontology.derive` | `extend` | Whether Context Graph adds types to your ontology: `extend` or `off` | +| `extraction.*` | See [Extraction configuration](#extraction-configuration) | How sessions are read into the knowledge graph | +| `llm.anthropic_api_key` | None | An Anthropic API key, used only to learn your ontology. Used instead of an OpenAI key when both are set. | +| `llm.openai_api_key` | None | An OpenAI API key, used only to learn your ontology | +| `llm.derive_model` | `claude-sonnet-5-5` with Anthropic, `gpt-5` with OpenAI | The model that learns your ontology | +| `edition` | `community` | `enterprise` to use [shared spaces](/ai-ecosystem/ai-memory/shared-spaces). Set it with `memgraph-context-graph join`. | +| `github.token` | None | A GitHub token for `resources-graph`, used instead of your `gh` login. Prompts for the value. | + +Only `[redact]` patterns are edited in the file directly, because you name +them yourself. See [Redact secrets](/ai-ecosystem/ai-memory/privacy#redact-secrets). + + +The file holds your Memgraph password and API keys in plain text. Setup +creates it with permissions `0600`; keep it that way. + + +### Recall configuration + +The `recall.*` keys set which searches +[recall](/ai-ecosystem/ai-memory/recall-and-memory#what-recall-returns) runs +and how many results each returns: + +```bash +memgraph-context-graph config set recall.turns_k 12 +memgraph-context-graph config set recall.lanes "memories, turns, text" +``` + +| Key | Default | What it sets | +| --- | --- | --- | +| `recall.embedding_model` | `BAAI/bge-small-en-v1.5` | The model Memgraph computes embeddings with | +| `recall.lanes` | All six | The searches to run, as a comma-separated subset of `memories`, `turns`, `text`, `entities`, `facts` and `user_facts` | +| `recall.memories_k` | `5` | Memory files returned | +| `recall.turns_k` | `8` | Messages found by meaning | +| `recall.text_k` | `8` | Messages found by words | +| `recall.entities_k` | `15` | Entities matched | +| `recall.edges_per_entity` | `6` | Facts read from each matched entity | +| `recall.facts_k` | `15` | Facts matched | +| `recall.fact_turns_k` | `8` | Messages added for the matched facts | +| `recall.user_fact_types` | `2` | Fact types gathered in full, for questions that count or list things | +| `recall.user_facts_k` | `30` | Facts returned for those types | +| `recall.turn_chars` | `1500` | Characters shown per message | +| `recall.query_instruction` | Depends on the model | Text added before the question when it's embedded. The English `bge` models get their retrieval instruction; other models get none | + +When you change `recall.embedding_model`, Context Graph computes the +embeddings again with the new model, so embeddings from two models are never +mixed. Memgraph downloads the model on first use. + +### Extraction configuration + +The `extraction.*` keys set how the +[knowledge graph](/ai-ecosystem/ai-memory/graph#add-a-knowledge-graph) reads +your sessions. Reconciliation and ontology learning use the same settings, so +a session is always read the same way. + +```bash +memgraph-context-graph config set extraction.entity_threshold 0.3 +``` + +| Key | Default | What it sets | +| --- | --- | --- | +| `extraction.model` | `fastino/gliner2.5-base-v1` | The GLiNER2 model | +| `extraction.entity_threshold` | GLiNER2's default | The lowest confidence, from 0 to 1, at which an entity is kept | +| `extraction.relation_threshold` | GLiNER2's default | The lowest confidence, from 0 to 1, at which a fact is kept | +| `extraction.chunk_size` | GLiNER2's default | Words per chunk | +| `extraction.chunk_overlap` | GLiNER2's default | Words shared by neighboring chunks | + +## Use your own Memgraph + +By default, setup starts Memgraph in Docker on your machine. To use another +Memgraph, such as a shared server or a +[high availability cluster](/database-management/clustering/high-availability), +pass its URL to setup. If the instance has authentication, set the user and +password first, because setup connects with them: + +```bash +memgraph-context-graph config set memgraph.user alice +memgraph-context-graph config set memgraph.password +memgraph-context-graph setup --memgraph-url bolt://memgraph.example.com:7687 +``` + +For a high availability cluster, use the `neo4j://` scheme with a coordinator's +address, so the client routes writes to the MAIN instance: + +```bash +memgraph-context-graph config set memgraph.url neo4j://coordinator.example.com:7687 +``` + +The instance needs the Memgraph version, MAGE and memory listed in the +[prerequisites](/ai-ecosystem/ai-memory/get-started#prerequisites). To see all +labels and properties with `SHOW SCHEMA INFO`, start it with +`--schema-info-enabled=true`. The Memgraph that setup starts has it enabled. + +Each user on a shared Memgraph should have their own `identity.user_id`. On a +shared Memgraph with Memgraph Enterprise, [shared spaces](/ai-ecosystem/ai-memory/shared-spaces) +give each user a database of their own. + +## Run setup again + +Every choice in setup is also a flag of `memgraph-context-graph setup`. To +change a choice, run setup again with its flag: + +```bash +memgraph-context-graph setup codex --memgraph-url bolt://memgraph.example.com:7687 +``` + +| Flag | What it sets | +| --- | --- | +| `RUNTIME ...` | The [runtime names](/ai-ecosystem/ai-memory/agents) of the agents to connect. The default is every agent on your `PATH`. | +| `--project-dir DIR` | A project to connect the per-project agents in. Repeat it for more projects. The default is the current directory. | +| `--memgraph-url URL` | The Memgraph to use, instead of setup's own container. | +| `--user-id NAME` | Your user ID in the graph. The default is the configured one, then your git `user.name`. | +| `--memory-backend BACKEND` | `context-graph` makes Context Graph the agents' memory; `native` gives memory back to the agent. | +| `--memgraph-container NAME` | Setup's own container, which it finds or starts. The default is `context-graph-memgraph`. | +| `--no-viewer` | Don't install the terminal viewer. | +| `--plan` | Print what setup would do and change nothing. | +| `--no-tui` | Print plain output, even on a terminal. | + +For example, to connect the per-project agents in more projects: + +```bash +memgraph-context-graph setup cursor --project-dir ~/work/billing --project-dir ~/work/crawler +``` + +## Choose what is recorded + +`capture.connectors` lists the packages the hooks send events to. Each one +records one part of a session: + +| Connector | Records | +| --- | --- | +| `actions-graph` | Prompts, replies, tool calls and tool results | +| `skills-graph` | The agent skills a session used | +| `sessions-graph` | The session, its user and project, and memories. Recall needs it. | +| `resources-graph` | The GitHub resources a session read. Off by default. | + +For example, to also remember GitHub resources: + +```bash +memgraph-context-graph config set capture.connectors "skills-graph, actions-graph, sessions-graph, resources-graph" +memgraph-context-graph setup +``` + +Setup installs the connectors the setting names. An empty value records +nothing, without disconnecting the agents. + +## Update Context Graph + +Context Graph doesn't update itself. Upgrading the packages changes the code +the hooks run, but the plugins, hook files and Model Context Protocol (MCP) +registrations that setup wrote stay as they were. The `update` command upgrades both in one step: + +```bash +memgraph-context-graph update +``` + +It runs these steps in order: + +1. **Upgrades the packages:** `memgraph-context-graph` and its connectors. +2. **Updates the Claude Code and Codex plugins** from the Context Graph plugin + marketplace, if they're installed. +3. **Rewrites the hook files and MCP registrations** of the per-project agents, + in the current directory or the `--project-dir` directories. +4. **Creates the indexes and constraints** in Memgraph that are missing. +5. **Checks the setup,** the same way as `doctor`. + +Then restart running agent sessions, because a session keeps the hooks it +started with. + +| Flag | What it does | +| --- | --- | +| `RUNTIME ...` | Update only these agents. The default is every connected agent. | +| `--project-dir DIR` | A project whose per-project agents to update. Repeat it for more projects. The default is the current directory. | +| `--no-upgrade` | Skip the package upgrade, and only refresh the plugins, hook files, registrations, indexes and constraints | + +`update` doesn't change your own hooks, the configuration file or the data in +the graph, and running it twice changes nothing. + +### Update the plugins manually + +If you manage plugins yourself, update the Context Graph plugin with the +agent's own commands. Claude Code updates the plugin in place: + +```bash +claude plugin marketplace update context-graph-plugins +claude plugin update context-graph@context-graph-plugins +``` + +Codex has no update command, so refresh the marketplace and add the plugin +again: + +```bash +codex plugin marketplace upgrade context-graph-plugins +codex plugin add context-graph@context-graph-plugins +``` + +Updating only the plugin doesn't upgrade the packages its hooks run. Run +`memgraph-context-graph update` as well, or upgrade the tool with +`uv tool upgrade memgraph-context-graph`. + +## Uninstall Context Graph + +The `uninstall` command disconnects your agents: it removes the plugins, hook files and MCP +registrations, and [gives the agents' memory back](/ai-ecosystem/ai-memory/recall-and-memory#switch-back). + +```bash +memgraph-context-graph uninstall +``` + +On a terminal, it then asks about each of these, and keeps it unless you +answer yes: + +- **The graph:** the Memgraph container that setup started and its data + volume, with every recorded session and memory. +- **The configuration:** the configuration file and the log of failed + recordings. +- **The tool:** the `memgraph-context-graph` command and its packages. + +To remove everything without questions, for example in a script: + +```bash +memgraph-context-graph uninstall --all +``` + +| Flag | What it does | +| --- | --- | +| `RUNTIME ...` | Disconnect only these agents. The default is every connected agent. | +| `--project-dir DIR` | A project to disconnect the per-project agents from. Repeat it for more projects. The default is the current directory. | +| `--graph` | Also delete the graph: setup's Memgraph container and its volume | +| `--config` | Also delete the configuration file and the log of failed recordings | +| `--tool` | Also uninstall the `memgraph-context-graph` tool | +| `--all` | `--graph`, `--config` and `--tool` together | +| `--memgraph-container NAME` | The container setup started. The default is `context-graph-memgraph`. | +| `--no-tui` | Don't ask; remove the agent connections and what the flags name | + +Without a terminal, `uninstall` removes only the agent connections and what the +flags name. It deletes only the container setup started, by name, never a +Memgraph you run yourself. On Windows, the running tool can't remove itself, +so `uninstall` prints the `uv tool uninstall` command to run afterwards. + + +Deleting the graph deletes everything your agents recorded, including your +memories, and can't be undone. + diff --git a/pages/ai-ecosystem/ai-memory/custom-agents.mdx b/pages/ai-ecosystem/ai-memory/custom-agents.mdx new file mode 100644 index 000000000..a3c932f8f --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/custom-agents.mdx @@ -0,0 +1,149 @@ +--- +title: Custom agents +description: Use Context Graph as the memory of an app built on the Claude Agent SDK or the OpenAI Agents SDK. +--- + +import { Tabs } from 'nextra/components' + +# Custom agents + +An app built on the Claude Agent SDK or the OpenAI Agents SDK can use Context +Graph as its memory. The app gets what hooks and the Model Context Protocol +(MCP) server give a coding agent, inside its own process: + +- **Recording:** the app's sessions are recorded, then embedded and reconciled + like coding-agent sessions. +- **Context:** each session starts with the memory index and + [where the user left off](/ai-ecosystem/ai-memory/recall-and-memory#recall) + in the project. +- **Tools:** the [`recall`](/ai-ecosystem/ai-memory/recall-and-memory#recall) + and [`memory`](/ai-ecosystem/ai-memory/recall-and-memory#how-the-agent-uses-memory) + tools. + +It's the same memory that the user's coding agents use. + +## Install + +The app reads the Memgraph connection, what is recorded and the +[privacy](/ai-ecosystem/ai-memory/privacy) settings from the +[configuration file](/ai-ecosystem/ai-memory/configuration#configuration-file), +the same as the hooks do. Run [setup](/ai-ecosystem/ai-memory/get-started) +first, or write the file with `memgraph-context-graph config set`. + +Install the package with the extra for your SDK, and the packages that record +actions and sessions: + + + +```bash +pip install "memgraph-context-graph[claude]" "sessions-graph[memgraph-context-graph]" "actions-graph[memgraph-context-graph]" +``` + + +```bash +pip install "memgraph-context-graph[openai]" "sessions-graph[memgraph-context-graph]" "actions-graph[memgraph-context-graph]" +``` + + + +## Connect the app + +Create a `ContextGraphMemory` for the user whose memory it is: + +```python +from memgraph_context_graph.sdk import ContextGraphMemory + +memory = ContextGraphMemory(user_id="alice") +``` + +The app passes only `user_id` and `cwd`, the project directory. Without them, +Context Graph uses `identity.user_id` from the configuration file and the +current directory. In an app with many users, pass each user's ID, so that +each one recalls only their own sessions. + +The app gets the `memory` tool whatever `memory.backend` your coding agents +use, because an app has no memory of its own to replace. To leave it out, pass +`memory_tool=False`. + +Both SDKs are async. Each example below is a whole script. + + + +```python +import asyncio + +from claude_agent_sdk import ClaudeSDKClient +from memgraph_context_graph.sdk import ContextGraphMemory +from memgraph_context_graph.sdk.claude import ClaudeAgentMemory + + +async def main(): + claude = ClaudeAgentMemory(ContextGraphMemory(user_id="alice")) + async with ClaudeSDKClient(claude.options(model="claude-sonnet-5-5")) as client: + await client.query("Which package manager does this project use?") + async for message in client.receive_response(): + print(message) + await claude.aend_session() + + +asyncio.run(main()) +``` + +`options()` takes the same arguments as `ClaudeAgentOptions`. It adds the +hooks that record the session, adds the `recall` and `memory` tools and allows +them, and turns off Claude Code's own auto memory. Hooks, MCP servers and +tools you pass are kept. + +The Agent SDK loads your Claude Code user settings, and with them the Context +Graph Claude Code plugin. `options()` turns that plugin off for the session, +so its hooks don't record every event a second time. + + +```python +import asyncio + +from agents import Agent, Runner +from memgraph_context_graph.sdk import ContextGraphMemory +from memgraph_context_graph.sdk.openai import OpenAIAgentsMemory + + +async def main(): + wired = OpenAIAgentsMemory(ContextGraphMemory(user_id="alice"), session_id="chat-42") + agent = Agent( + name="Assistant", + instructions=wired.instructions("Be concise."), + tools=wired.tools(), + ) + result = await Runner.run( + agent, "Which package manager does this project use?", hooks=wired.hooks() + ) + print(result.final_output) + await wired.aend_session() + + +asyncio.run(main()) +``` + +Use one `session_id` per conversation. `instructions()` adds the memory +context to your instructions, `tools()` returns `recall` and `memory` as +function tools, and `hooks()` records the run: the user's message, the model's +replies, tool calls and handoffs. + + + +## End the session + +Neither SDK reports when a session ends, so call `aend_session()`, or +`end_session()` from code that isn't async, when a conversation is over. + +Recall can find each message as soon as its turn ends, because Context Graph +embeds a session's messages at the end of every turn. Ending the session +embeds anything left and marks the session for +[reconciliation](/ai-ecosystem/ai-memory/graph#build-the-knowledge-graph), +which starts at once if `reconcile.auto_reconcile` is on. + +## Behavior when Memgraph is unreachable + +Recording never fails the app. If Context Graph can't reach Memgraph, it stops +recording for 30 seconds before it tries again, so each call doesn't wait for +a connection timeout. If a tool fails, the model gets the error as text. diff --git a/pages/ai-ecosystem/ai-memory/get-started.mdx b/pages/ai-ecosystem/ai-memory/get-started.mdx new file mode 100644 index 000000000..193b5a197 --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/get-started.mdx @@ -0,0 +1,176 @@ +--- +title: Get started with Context Graph +description: Install Context Graph with one command, connect your coding agents to Memgraph, and check that their sessions are recorded and recalled. +--- + +import { Tabs } from 'nextra/components' + +# Get started with Context Graph + +One command installs Context Graph, finds or starts Memgraph, and connects +the coding agents you choose. Setup shows its plan and changes nothing until +you confirm. + +From then on, Context Graph records your prompts, the agent's replies, and +every tool call with its input and output. + +## Prerequisites + +- **Docker, or the latest Memgraph.** By default, setup starts Memgraph with + [Docker](https://docs.docker.com/get-docker/). To use your own Memgraph + instead, pass its URL with `--memgraph-url`. It needs + [MAGE](/advanced-algorithms), as in the `memgraph/memgraph-mage` image, and + at least 2 GiB of memory, so that + [recall](/ai-ecosystem/ai-memory/recall-and-memory#recall) can search by + meaning. +- **At least one [supported agent](/ai-ecosystem/ai-memory/agents)** + on your `PATH`. + +You don't need Python. Setup installs [uv](https://docs.astral.sh/uv/) if it's +missing, and uv installs the rest. + +## 1. Run setup + +Run setup in a terminal, from the project directory you work in. Claude Code +and Codex are connected for your user, in every directory. The other agents +are connected one project at a time, starting with the current directory. + + + +```bash +curl -sSL https://install.memgraph.com/ai-memory | bash +``` + +The command needs a terminal to ask its questions on. Without one, such as in +CI, it prints the install script's command instead of running it. + + +In PowerShell 5.1 or 7: + +```powershell +iwr https://install.memgraph.com/ai-memory/windows -useb | iex +``` + +If Windows blocks the script, allow scripts for the current session first: + +```powershell +Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass +``` + + + +Setup lists what it found and what it will do: + +- **Agents:** the agents on your `PATH`. On a first run, Claude Code and + Codex are ticked, and the per-project agents aren't; tick the ones you want + connected in this project. On a later run, the agents already connected are + ticked. If no agent is ticked, setup fails instead of installing nothing. +- **Memgraph:** the one it will use or start. +- **Name:** your user ID in the graph. Your memories are filed under it. It + defaults to your git `user.name`, or your system user name. +- **Memory:** whether your agents use Context Graph as their memory instead of + their own. Recall works either way. See + [Memory](/ai-ecosystem/ai-memory/recall-and-memory#memory). + +The plan updates as you change your choices. Nothing changes until you press +**Install**. To change your choices later, +[run setup again](/ai-ecosystem/ai-memory/configuration#run-setup-again) with +flags. + +### What setup does + +After you press **Install**, setup runs these steps in order. Each step checks +first, so running setup again only does what's missing. + +1. **Finds or starts Memgraph.** Setup uses the first of these: + - the URL you pass with `--memgraph-url`; + - the URL in its configuration file, unless that's the default + `bolt://localhost:7687`; + - its own container, `context-graph-memgraph`, which it starts if it's + stopped. Without that container, setup starts the + `memgraph/memgraph-mage` image under that name, with a data volume, + listening on `127.0.0.1` only, on port 7687 or a free port if 7687 is + taken. + + Setup never writes to another Memgraph that happens to run on + `localhost:7687`. To use one, pass `--memgraph-url bolt://localhost:7687`. +2. **Saves the configuration:** the Memgraph URL and your user ID, in + `~/.config/context-graph/config.toml`. +3. **Installs the packages:** the `memgraph-context-graph` command, the + packages that record actions, skills and sessions, and the terminal viewer. +4. **Connects your agents.** See [Supported agents](/ai-ecosystem/ai-memory/agents) + for what changes for each one. +5. **Checks the setup,** the same way as + [`memgraph-context-graph doctor`](#2-check-that-your-agents-are-connected). + +The report ends with the command to rerun for any step that failed. + +## 2. Check that your agents are connected + +To make your agents use the new hooks, restart any sessions that were running +during setup; a running session keeps the hooks it started with. Codex and +Grok Build record nothing until you trust the new hooks: in Codex, run +`/hooks` once and accept them; in Grok Build, run `/hooks-trust` once in each +connected project. Then check the setup: + +```bash +memgraph-context-graph doctor --runtime claude-code +``` + +Replace `claude-code` with the +[runtime name](/ai-ecosystem/ai-memory/agents) of the agent +you want to check. Every check starts with `OK` when the setup works: + +```plaintext copy=false +OK memgraph-context-graph executable: ... +OK memgraph-context-graph: ... +OK config: identity.user_id set +OK memgraph: reachable +OK connector:skills-graph: installed=...; memgraph=reachable +OK connector:actions-graph: installed=...; memgraph=reachable +OK connector:sessions-graph: installed=...; memgraph=reachable +OK embeddings: BAAI/bge-small-en-v1.5 (384 dimensions) inside Memgraph +OK mcp: serves recall +OK runtime:claude-code: connectors accept its probe event +OK memory: claude-code's built-in memory (memory.backend native) +OK plugin:claude-code: context-graph@context-graph-plugins installed and enabled +INFO capture-failures: none in the last 24h (...) +``` + +The last line counts the recordings that failed in the last day. + +The `runtime:` check sends a test event to the connectors. For Claude Code and +Codex, the `plugin:` check confirms the agent will call the hooks: it fails if +the agent isn't on your `PATH`, or the plugin isn't installed or is disabled. + +A line that starts with `FAIL` says what failed. On a Memgraph without MAGE, +the `embeddings` check is expected to fail; see +[Recall](/ai-ecosystem/ai-memory/recall-and-memory#recall). + +## 3. Ask about earlier work + +In a new session, ask the agent about earlier work, for example "what did we +decide about the deploy window?". The agent calls the `recall` tool and +answers from your past sessions. You can run the same search yourself: + +```bash +memgraph-context-graph recall "what did we decide about the deploy window?" +``` + +To watch your sessions being recorded, open the +[terminal viewer](/ai-ecosystem/ai-memory/graph#browse-the-graph). + +## Next steps + +- [Recall and memory](/ai-ecosystem/ai-memory/recall-and-memory): + How your agents read their past sessions. +- [The graph](/ai-ecosystem/ai-memory/graph): Look at what your agents + recorded, and add a knowledge graph. +- [Privacy](/ai-ecosystem/ai-memory/privacy): Keep text out of the graph and + delete sessions. +- [Configuration](/ai-ecosystem/ai-memory/configuration): Change your setup + choices, use a remote Memgraph, update Context Graph, or uninstall it. + +If setup fails in a way the report doesn't explain, ask on +[Discord](https://discord.gg/memgraph) or open an issue on +[GitHub](https://github.com/memgraph/ai-toolkit/issues). diff --git a/pages/ai-ecosystem/ai-memory/graph.mdx b/pages/ai-ecosystem/ai-memory/graph.mdx new file mode 100644 index 000000000..0d84a94ca --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/graph.mdx @@ -0,0 +1,258 @@ +--- +title: The graph +description: See what Context Graph stores in Memgraph, browse and query it, and add a knowledge graph of the entities and facts your sessions mention. +--- + +import { Tabs } from 'nextra/components' + +# The graph + +Everything Context Graph records is an ordinary graph in Memgraph. This page +covers [what the graph holds](#what-the-graph-holds), how to +[browse it](#browse-the-graph) and [query it](#query-the-graph), and how to +[add a knowledge graph](#add-a-knowledge-graph) of the entities and facts your +sessions mention. + +## What the graph holds + +Each session is a `Session` node, linked to its `User`. Everything recorded in +the session hangs off that node. The knowledge graph links its entities to the +messages and memory files they came from: + +```plaintext copy=false +(:User)-[:HAD_SESSION]->(:Session) + ├─[:HAS_ACTION]->(:Action) prompts, replies, tool calls and results + ├─[:USED_SKILL]->(:Skill) agent skills the session used + └─[:PRODUCED_MEMORY]->(:Memory) memories the agent saved +(:User)-[:HAS_MEMORY]->(:Memory) +(:Action)-[:HAS_CHUNK]->(:Chunk)<-[:MENTIONED_IN]-(:Person) an entity, labeled by its type +(:Memory)-[:HAS_CHUNK]->(:Chunk) +``` + +| Node | What it is | +| --- | --- | +| `User` | You, by `user_id` | +| `Session` | One agent session, by `session_id`, with its `project_key` and `started_at` | +| `Action` | A prompt, reply, tool call or tool result | +| `Skill` | An agent skill | +| `Memory` | A memory file, by `path` | +| `Project` | A project the memory files are about, by `key` | +| `Chunk` | A piece of a message or memory file that entities were extracted from | +| Entity labels | An extracted entity, with its name in `text`, its type in `entity_type` and a label for the type, such as `Person` | + +To see every label, relationship type and property, run: + +```cypher +SHOW SCHEMA INFO; +``` + +This needs Memgraph started with `--schema-info-enabled=true`; the Memgraph +setup starts has it. + +## Browse the graph + +The terminal viewer shows the graph without a query. It refreshes every few +seconds and never writes to the graph: + +```bash +memgraph-context-graph ui +``` + +With it, you can: + +- **Find a session.** The dashboard lists your sessions. Press `/` to filter + them, `p` to show one project, and `enter` to open a session's timeline, + with each action's input and the subagents under the call that started them. +- **Spot failed recordings.** The dashboard counts failed recordings and the + extraction and embedding work still pending. +- **Browse entities.** Press `k` on the dashboard, or `g` on a session, to list + entities. `enter` on an entity shows its relationships and the text each one + was read from; `enter` on a neighbor moves to it. + +`esc` goes back, `q` quits and `?` shows all keys. The viewer shows your own +sessions. If the dashboard is empty, press `a`: sessions recorded while no +user ID was set belong to no user. + +To see the graph drawn, connect [Memgraph Lab](/memgraph-lab) to the URL that +`memgraph-context-graph config get memgraph.url` prints. In a Lab container, +the Memgraph on your machine isn't at `localhost`: + + + +```bash +docker run -d --name memgraph-lab -p 3000:3000 memgraph/lab:latest +``` + +Open `http://localhost:3000` and connect to host `host.docker.internal`. + + +```bash +docker run -d --name memgraph-lab --network host memgraph/lab:latest +``` + +Open `http://localhost:3000` and connect to host `localhost`. + + + +## Query the graph + +The queries below are templates. Replace `USER_ID` with your user ID from +`memgraph-context-graph config get identity.user_id`. + +Which sessions did I run most recently, and how long were they? + +```cypher template +MATCH (:User {user_id: "USER_ID"})-[:HAD_SESSION]->(s:Session) +OPTIONAL MATCH (s)-[:HAS_ACTION]->(a:Action) +RETURN s.session_id, s.project_key, s.started_at AS started_at, count(a) AS actions +ORDER BY started_at DESC +LIMIT 10; +``` + +Which skills do I use most? + +```cypher template +MATCH (:User {user_id: "USER_ID"})-[:HAD_SESSION]->(:Session)-[:USED_SKILL]->(sk:Skill) +RETURN sk.name, count(*) AS uses +ORDER BY uses DESC; +``` + +Which memory files do my agents keep? + +```cypher template +MATCH (:User {user_id: "USER_ID"})-[:HAS_MEMORY]->(m:Memory) +RETURN m.path, m.updated_at +ORDER BY m.path; +``` + +In which sessions was a tool called? Replace `TOOL_NAME` with the tool's name: + +```cypher template +MATCH (:User {user_id: "USER_ID"})-[:HAD_SESSION]->(s:Session)-[:HAS_ACTION]->(a:Action {tool_name: "TOOL_NAME"}) +RETURN DISTINCT s.session_id; +``` + +What do my sessions mention most? This needs the +[knowledge graph](#add-a-knowledge-graph): + +```cypher template +MATCH (:User {user_id: "USER_ID"})-[:HAD_SESSION]->(:Session)-[:HAS_ACTION]->(:Action) + -[:HAS_CHUNK]->(c:Chunk)<-[:MENTIONED_IN]-(e) +RETURN e.text, e.entity_type, count(DISTINCT c) AS mentions +ORDER BY mentions DESC +LIMIT 20; +``` + +## Add a knowledge graph + +Context Graph can extract the entities your sessions mention, such as people, +organizations, projects and tools, and the facts that connect them. Recall uses +them to find facts spread over many sessions. This process is called +**reconciliation**. It runs on your machine with +[GLiNER2](https://github.com/fastino-ai/GLiNER2), a local extraction model, +and needs no LLM API key. + +### Install the extraction packages + +Setup leaves the extraction model out, because it's large. Add it to the +`memgraph-context-graph` tool, together with the `sessions-graph` command: + +```bash +uv tool install --force 'memgraph-context-graph[mcp]' \ + --with 'skills-graph[memgraph-context-graph]' \ + --with 'actions-graph[memgraph-context-graph]' \ + --with 'sessions-graph[memgraph-context-graph,reconciliation]' \ + --with context-graph-viewer \ + --with-executables-from sessions-graph +``` + +This command replaces the packages installed with the tool. If you turned on +`resources-graph`, add `--with 'resources-graph[memgraph-context-graph]'` and +`--with-executables-from resources-graph`. The first extraction downloads the +model. + +### Build the knowledge graph + +When a session ends, Context Graph marks it as pending reconciliation. To +extract every pending session, or one session by its `session_id`: + +```bash +sessions-graph reconcile --pending +sessions-graph reconcile --session SESSION_ID +``` + +Extraction takes longer than an agent allows a hook to run, so it never runs +inside a hook. Choose how it runs: + +- **After each session,** in a background process: + + ```bash + memgraph-context-graph config set reconcile.auto_reconcile true + ``` + + If the background process stops, the session stays pending, and the next + `reconcile --pending` extracts it. +- **On a schedule,** with `sessions-graph reconcile --pending --limit 50` in + cron or another scheduler. `--limit` caps how many sessions one run + extracts. + +Memory files are extracted too, each time they change. + +### What the knowledge graph adds + +Each entity gets a label for its type from the ontology, such as `Person` or +`Organization`, and facts are relationships between entities, with the +sentence they were read from. + +A person, organization, place or thing +mentioned in several sessions is one node, so its relationships connect those +sessions. Reconciliation also computes the embeddings recall uses for the new +entities and facts. + +To change how sessions are read, such as the confidence an entity needs, see +[Extraction configuration](/ai-ecosystem/ai-memory/configuration#extraction-configuration). + +### Ontology + +Entities are extracted under an **ontology**, the schema of the knowledge +graph: the entity types and relationship types to look for. Every user starts +with a default ontology. It has people, organizations, locations and events, +value types such as dates and amounts, and two catch-all types, `Topic` and +`Artifact`. To see the ontology in use: + +```bash +sessions-graph ontology show +``` + +To extract the types that matter in your work, write an ontology file in the +format of the manual strategy of +[HyGM](https://github.com/memgraph/ai-toolkit/tree/main/hygm), the AI +Toolkit's graph schema package, and set it in the configuration: + +```bash +memgraph-context-graph config set ontology.path ~/schemas/coding.yaml +``` + +The next `sessions-graph reconcile` applies the file, and applies it again +whenever it changes. If the file isn't valid, reconcile reports it and keeps +the current ontology. `ontology.derive` sets what may happen to your ontology +afterwards: + +- **`extend`** (the default): your types are kept as written, together with + the default core types, and Context Graph may add types next to them. +- **`off`:** the ontology is used exactly as written, and no types are added. + +### Learn the ontology from your sessions + +With an Anthropic or OpenAI API key in the configuration, Context Graph adds +new types to the ontology from your sessions. Learning runs on its own as +your sessions accumulate. `config set` prompts for the key. To run it now: + +```bash +memgraph-context-graph config set llm.anthropic_api_key +sessions-graph derive --force +``` + +Learning sends session text to the provider; see +[Privacy](/ai-ecosystem/ai-memory/privacy#where-sessions-are-stored). Without a +key, the ontology doesn't change, and extraction still works. diff --git a/pages/ai-ecosystem/ai-memory/privacy.mdx b/pages/ai-ecosystem/ai-memory/privacy.mdx new file mode 100644 index 000000000..f7698c870 --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/privacy.mdx @@ -0,0 +1,178 @@ +--- +title: Privacy +description: See what Context Graph records from your agent sessions and where it goes, keep secrets and private text out of the graph, and delete sessions. +--- + +# Privacy + +Context Graph records your agent sessions in full. This page covers +[where they are stored](#where-sessions-are-stored), how to +[keep text out of the graph](#keep-text-out-of-the-graph) and how to +[forget sessions](#forget-sessions). + +## Where sessions are stored + +Context Graph stores your agent sessions in the Memgraph in your +[configuration](/ai-ecosystem/ai-memory/configuration#configuration-file). By +default, that's the Memgraph setup started for you in Docker, in a container +named `context-graph-memgraph`. It runs on your machine, and only your machine +can connect to it. + +Recorded sessions are sent nowhere else, with one exception. With an +Anthropic or OpenAI API key, +[ontology learning](/ai-ecosystem/ai-memory/graph#learn-the-ontology-from-your-sessions) +sends that provider the full text of up to 64 recent sessions per run, +including the agent's replies and tool input and output. Without a key, it +doesn't run. + +The hooks use only the keys in the configuration file. A `sessions-graph` +command you run from a shell also uses `ANTHROPIC_API_KEY` or +`OPENAI_API_KEY` from your environment. + +## Keep text out of the graph + +The hooks that setup installs in each agent record prompts, replies, and tool +input and output in full, so a session can contain an API key from a `.env` +file or text you don't want stored. Before anything reaches Memgraph, Context Graph removes what you mark +as private, redacts secrets, and shortens long text. What it removes is never +stored. + +These rules apply to everything the hooks record, for every agent. They don't +apply to memory files the agent writes with the +[`memory` tool](/ai-ecosystem/ai-memory/recall-and-memory#how-the-agent-uses-memory), +which are stored as written. + +### Mark text as private + +Text between `` and `` is removed from prompts, replies and +tool input and output: + +```plaintext +Connect to the staging database. The password is in the team vault under "staging-db". +``` + +Context Graph stores only "Connect to the staging database.". The agent still +gets the whole prompt. If a prompt has nothing outside its private block, it +isn't stored at all. An unclosed `` hides the rest of the text. + +### Redact secrets + +Context Graph replaces known kinds of secrets with `[REDACTED:NAME]`, where +`NAME` says what was removed: + +| Name | What it matches | +| --- | --- | +| `private_key` | PEM private key blocks | +| `aws_access_key` | AWS access key IDs | +| `github_token` | GitHub tokens and fine-grained personal access tokens | +| `anthropic_key` | Anthropic API keys | +| `openai_key` | OpenAI API keys | +| `slack_token` | Slack tokens | +| `stripe_key` | Stripe secret and restricted keys | +| `google_api_key` | Google API keys | +| `jwt` | JSON Web Tokens | +| `url_password` | Passwords in URLs, such as `postgres://user:PASSWORD@host` | +| `config_secret` | The Memgraph password, API keys and GitHub token in the configuration file, if they're at least 6 characters long | + +To redact your own patterns, add a `[redact]` section to the configuration +file. Each key is the name in the replacement, and each value is a +[Python regular expression](https://docs.python.org/3/library/re.html#regular-expression-syntax) +in single quotes: + +```toml +[redact] +ticket = 'ACME-[0-9]+' +customer_email = '[A-Za-z0-9._%+-]+@acme\.com' +``` + +An invalid pattern is ignored and reported as a configuration warning, and +recording continues. + +Redaction matches known shapes of secrets, so it doesn't catch every secret. +Use `` or `capture.exclude_projects` for anything it might miss. + +To turn redaction off, so that only `` blocks are removed: + +```bash +memgraph-context-graph config set capture.redact false +``` + +### Shorten long text + +Each text field, such as a tool's output, is cut after `capture.max_chars` +characters, 100,000 by default, and ends with a note of how many characters +were removed. To change the limit, or to keep everything with `0`: + +```bash +memgraph-context-graph config set capture.max_chars 20000 +``` + +### Exclude tools and projects + +To stop recording some tools' calls and results, list their names. A name can +be a glob, such as `mcp__vault__*` for every tool of one Model Context +Protocol (MCP) server: + +```bash +memgraph-context-graph config set capture.exclude_tools "TodoWrite, mcp__vault__*" +``` + +To record nothing from some projects, list their directories. A session that +starts in one of them, or in a directory inside one, isn't recorded. `~` stands +for your home directory, and a path can be a glob: + +```bash +memgraph-context-graph config set capture.exclude_projects "~/clients/*, ~/personal" +``` + +The agent works as usual in an excluded project, and recall still finds your +other sessions there. + +Setting a list replaces the previous one. To clear it, set an empty value: + +```bash +memgraph-context-graph config set capture.exclude_projects "" +``` + +## Forget sessions + +The `forget` command deletes sessions from your graph for good, with everything recorded in +them and everything extracted from them. Delete sessions by ID: + +```bash +memgraph-context-graph forget session SESSION_ID +``` + +`SESSION_ID` is the session's `session_id`, shown in the +[terminal viewer](/ai-ecosystem/ai-memory/graph#browse-the-graph). +Pass several IDs to delete several sessions. + +To delete every session that ran in a directory or inside it, pass the +directory: + +```bash +memgraph-context-graph forget project ~/work/client-repo +``` + +`forget` lists the matching sessions and asks before it deletes them. Add +`--dry-run` to only list them, and `--yes` to skip the question. Without a +terminal, `--yes` is required. + +For each session, `forget` deletes: + +- its prompts, replies, tool calls and results, its skill uses, and its + records of GitHub resources; +- what reconciliation extracted from it, and every entity no other session or + memory file mentions; +- its lines in the log of failed recordings. + +Entities that other sessions mention, skills, stored GitHub resources and your +memory files stay, including files the session wrote. A forgotten session +leaves only a `ForgottenSession` node with its ID, which stops a hook that is +still running, or a resumed session, from recording it again. + +Only you can forget sessions, from the command line. The agents have no tool +for it. With +[shared spaces](/ai-ecosystem/ai-memory/shared-spaces), `forget` +deletes from your personal space only. + diff --git a/pages/ai-ecosystem/ai-memory/recall-and-memory.mdx b/pages/ai-ecosystem/ai-memory/recall-and-memory.mdx new file mode 100644 index 000000000..2932641b8 --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/recall-and-memory.mdx @@ -0,0 +1,202 @@ +--- +title: Recall and memory +description: Let coding agents recall their past sessions from Memgraph, and make Context Graph their long-term memory shared across agents. +--- + +# Recall and memory + +Context Graph gives your agents two ways to use what earlier sessions left +behind. **Recall** searches everything your sessions recorded and returns what +matches a question. **Memory** is the set of notes the agent chooses to keep, +such as your preferences and project decisions, loaded at the start of every +session. + +Recall works as soon as setup finishes. Memory is opt-in, because it replaces +the agent's own memory. + +## Recall + +When you ask about earlier work, for example "which database did we pick for +the cache?", the agent calls the `recall` tool with the question. You can run +the same search from the terminal, and add `--json` to get the results as +JSON: + +```bash +memgraph-context-graph recall "which database did we pick for the cache?" +``` + +At the start of each session, the agent also gets a short note about the +current project, so it can continue where you left off: + +- that the `recall` tool exists; +- your last session in this project: its date, the agent, your first and last + request, and the agent's last reply; +- your first request in each of the two sessions before it. + +Sessions from every agent count, so a session in Grok Build can continue where +one in Codex stopped. A project is identified by its git `origin` remote, so +all clones of a repository count as one project; without a remote, the +directory name is used. To turn the note off: + +```bash +memgraph-context-graph config set session_start.resume false +``` + +### What recall returns + +Recall returns raw data, not an answer: the dated messages and extracted +facts that match the question, as text. The agent passes them to its model +like any other tool result, and the model answers from them. + +The results +start with a short header that tells the model how to read them, for example +that a later message about the same thing replaces an earlier one. + +Recall combines several searches over your own sessions: + +| Search | What it finds | +| --- | --- | +| Memories | [Memory files](#memory) that match by meaning or by words, shown first | +| Messages by meaning | Messages closest to the question, by vector search | +| Messages by words | Messages that match the question's words, by text search | +| Entities | People, projects and other entities that match, with their facts | +| Facts | Extracted facts that match, with the messages they came from | +| Facts about you | All facts of the types that match, for questions that count or list things | + +Entities and facts come from the +[knowledge graph](/ai-ecosystem/ai-memory/graph#add-a-knowledge-graph). Before +it's built, recall finds messages and memories only. + +The searches by meaning need [MAGE](/advanced-algorithms), which computes the +embeddings inside Memgraph. On Memgraph without MAGE, recall uses text search +only and says so in its results. + +To change how many results each search returns, or to drop a search, see +[Recall configuration](/ai-ecosystem/ai-memory/configuration#recall-configuration). + +## Memory + + +Agents such as Claude Code and Codex keep their own memory: notes they save +and read at the start of a session. You can make Context Graph that memory +instead. Your memories are then stored in Memgraph, shared by all your agents +and searched by recall. + +Turn it on for an agent with setup: + +```bash +memgraph-context-graph setup claude-code --memory-backend context-graph +``` + +The interactive setup offers the same switch as a checkbox. When you turn it +on, setup does three things for each agent: + +1. It imports the agent's existing memory, once. Claude Code's user and + feedback memories go to `/memories/user/` and `/memories/feedback/`, and + project memories go to that project's folder. Codex's memory summary + becomes `/memories/user/codex-memory-summary.md`. A file already in the + graph is never overwritten. +2. It turns off the agent's own memory, as listed in + [Supported agents](/ai-ecosystem/ai-memory/agents#built-in-memory). Setup + backs up each file it edits. +3. It saves the choice as `backend = "context-graph"` in the `[memory]` + section of the configuration file. + +If the import can't run, for example because Memgraph isn't reachable, setup +doesn't turn off the agent's memory. The change shows from the next session, +because agents list their tools when a session starts. + +### How the agent uses memory + +With the switch on, Context Graph's Model Context Protocol (MCP) server also +serves a `memory` tool. It has the +commands of the +[Claude memory tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/memory-tool): +`view`, `create`, `str_replace`, `insert`, `delete` and `rename`, on files +under `/memories`. The agent keeps two kinds of files: + +- **`/memories/`** for what applies everywhere, such as your preferences. +- **`/memories/projects/PROJECT/`** for one codebase, where `PROJECT` is the + project's key, such as `github.com_memgraph_ai-toolkit`. + +Each file is a `Memory` node in your graph. At the start of a session, the +agent gets: + +- an index of the files in `/memories/` and in the current project's folder, + one line per file, up to 200 lines; +- the full text of every file whose frontmatter has `pin: true`; +- the name of the current project's folder. + +The index is built from the graph each time, so it's never out of date. + +### Rules for memory files + +- A file can't be empty or larger than 100 KB. +- An edit applies only if the file still holds the text the edit was made + from. If another session changed the file in between, the edit fails + instead of overwriting that change. +- Context Graph keeps the last 20 versions of each file. Overwriting, editing + or deleting a file saves its previous text first, as a `MemoryVersion` node. + +### Switch back + +To give memory back to the agent: + +```bash +memgraph-context-graph setup claude-code --memory-backend native +``` + +For Claude Code, setup first copies the graph's memories back into Claude +Code's auto memory, so it continues from what the graph learned: + +- A project's files go to each Claude Code project folder for that project, + and `/memories/user/` and `/memories/feedback/` files go to every folder. +- The graph's copy replaces an older copy there, and each folder's + `MEMORY.md` index is rebuilt. +- Files that Claude Code has no folder for stay in the graph only, such as a + project it never opened, another agent's files, or files directly in + `/memories/`. Setup lists them. + +Then it turns the agent's own memory on again. The memories in the graph stay +where they are, and recall still finds them. If Memgraph isn't reachable, +setup changes nothing. + +Codex, GitHub Copilot CLI and Grok Build get nothing copied back, because +their memory is generated or hosted by the agent itself. + +`memgraph-context-graph uninstall` also gives memory back the same way. If +Memgraph isn't reachable, it turns the agent's memory back on with what it +held before the switch, and warns you. + +### Check for a second memory + +A project's `.claude/settings.json` or `.claude/settings.local.json` overrides +your user settings. If one of them sets `autoMemoryEnabled: true`, Claude Code +keeps its own memory in that project next to Context Graph's. +`memgraph-context-graph doctor` fails in that case. Run it from the project: + +```bash +memgraph-context-graph doctor --runtime claude-code +``` + +## Remember external resources + +The optional `resources-graph` package remembers the external resources your +agents read, so they can read them from the graph instead of fetching them +again. It supports public GitHub issues, pull requests and repositories. Turn +it on in +[Configuration](/ai-ecosystem/ai-memory/configuration#choose-what-is-recorded). + +When it's on: + +1. The hooks record which GitHub addresses a session fetched or mentioned. + They never call GitHub. +2. `resources-graph sweep` fetches those addresses and stores them in the + graph. Run it after a session or on a schedule. It uses your `gh` login, or + a token set with `memgraph-context-graph config set github.token`. +3. The agent reads a stored issue or pull request with the `resource` tool, + which returns it with the time it was fetched. The agent decides whether + that's recent enough. + +Claude Code and Codex also get a note right before they fetch something that's +already in the graph. The fetch still runs. diff --git a/pages/ai-ecosystem/ai-memory/shared-spaces.mdx b/pages/ai-ecosystem/ai-memory/shared-spaces.mdx new file mode 100644 index 000000000..795c213b6 --- /dev/null +++ b/pages/ai-ecosystem/ai-memory/shared-spaces.mdx @@ -0,0 +1,139 @@ +--- +title: Shared spaces +description: Run Context Graph for a team on one Memgraph Enterprise instance, with a personal space for each user and shared spaces for team memory. +--- + +import { Callout } from 'nextra/components' + +# Shared spaces Enterprise + +Shared spaces let a team run Context Graph on one Memgraph. Each user gets a +**personal space**, a database only they can read, and teams get **shared +spaces**, databases whose members read and write the same memory files. An +agent can save a decision to a shared space, and every member's agents recall +it. + +Shared spaces need [Memgraph Enterprise](/database-management/enabling-memgraph-enterprise). +Memgraph enforces the isolation between spaces with +[multi-tenancy](/database-management/multi-tenancy), +[role-based access control](/database-management/authentication-and-authorization/role-based-access-control) +and [label-based access control](/database-management/authentication-and-authorization/role-based-access-control#label-based-access-control). +Context Graph itself doesn't filter what a user can read. + +Without shared spaces, Context Graph runs as the **Community** edition: one +user and one database. Nothing changes for Community users when the shared +spaces package is installed. + +## How spaces work + +- **Identity** is your Memgraph login. It replaces `identity.user_id`. +- **Your personal space** is the database `u_LOGIN`. It holds your sessions, + memories and knowledge graph, and only you can read it. +- **A shared space** is the database `space_NAME`. Members can read + everything in it, and write only memory files. +- **Shared memory files** appear to the agent under `/memories/spaces/NAME/`. + The agent writes there only when you want something shared. At the start of + a session, each shared space adds up to 20 files to the memory index. +- **Recall** searches your personal space and every shared space you can read, + in parallel. If a space doesn't answer within 10 seconds, recall returns the + other results and names the space it's missing. + +Your own sessions stay in your personal space. A shared space holds only the +memory files members put there, and the knowledge graph built from them. + +## Set up spaces as an admin + +Declare the members and spaces in a spec file, such as `spaces.toml`: + +```toml +members = ["alice", "bob"] +personal_memory_limit_mb = 2048 + +[spaces.payments] +members = ["alice", "bob"] +memory_limit_mb = 4096 +``` + +- **`members`** at the top lists every user who gets a personal space. +- **`personal_memory_limit_mb`** caps each personal space's memory, with a + [tenant profile](/database-management/tenant-profiles). +- **`[spaces.NAME]`** declares a shared space, its members and its memory cap. + `labels` and `edge_types` set what members may write; the default is memory + files only. + +Install the `context-graph-spaces` package and apply the spec as a Memgraph +admin user: + +```bash +pip install context-graph-spaces +export MEMGRAPH_URL=bolt://memgraph.example.com:7687 +export MEMGRAPH_USER=ADMIN_USER +export MEMGRAPH_PASSWORD=ADMIN_PASSWORD +context-graph-spaces plan spaces.toml +context-graph-spaces apply spaces.toml +``` + +`plan` prints what `apply` would change. `apply` creates what's missing and +prints one-time setup lines for new users, including the password of the +`cg_service` user. Running it again changes nothing. + +`apply` creates and maintains: + +| Object | Name | Access | +| --- | --- | --- | +| Personal database | `u_LOGIN` | Its owner only | +| Shared database | `space_NAME` | Members read everything and write the spec's labels | +| Roles | `cg_u_LOGIN_HASH`, `space_NAME_member_HASH`, `cg_worker_HASH` | Named after what they grant | +| Service user | `cg_service` | Writes the knowledge graph in shared spaces | +| Tenant profiles | `cg_MBmb` | The memory caps from the spec | + +Removing a user from the spec revokes their access, and removing a space +revokes access to it. `apply` drops users and databases only with `--prune`, +and only touches objects whose names start with `u_`, `space_` or `cg_`. + +### Run the shared space worker + +Members can only write memory files to a shared space. The `cg_service` user +builds the knowledge graph there, and the embeddings recall uses. Run the +worker next to `apply`, with the password `apply` printed: + +```bash +export CG_SERVICE_PASSWORD=SERVICE_PASSWORD +context-graph-spaces reconcile spaces.toml --watch +``` + +Every 30 seconds, for each shared space, the worker removes what deleted +files left behind and extracts the changed memory files. It uses no LLM. +Personal spaces are extracted on each user's machine, as in the Community +edition. + + +Without the worker, shared memory files are still stored and read, but recall +can't find them by meaning or through the knowledge graph. + + +## Join as a user + +Each user runs the `join` command with the Memgraph URL and their login: + +```bash +memgraph-context-graph join bolt://memgraph.example.com:7687 alice +``` + +`join` prompts for the password, installs the `context-graph-spaces` package +if it's missing, and sets `edition = "enterprise"`, the URL, the login and the +password in the [configuration file](/ai-ecosystem/ai-memory/configuration#configuration-file). +It then checks the login and prints your personal space and the shared spaces +you can read: + +```plaintext copy=false +Wrote /home/alice/.config/context-graph/config.toml: edition = enterprise, login 'alice'. +Personal space: u_alice. Shared spaces: payments. +``` + +If this machine isn't set up yet, run +[setup](/ai-ecosystem/ai-memory/get-started) next to connect +your agents. + +In the [terminal viewer](/ai-ecosystem/ai-memory/graph#browse-the-graph), +press `w` to switch to the next space you can read. diff --git a/pages/database-management/enabling-memgraph-enterprise.mdx b/pages/database-management/enabling-memgraph-enterprise.mdx index 25b9c5cf7..35a3efd8f 100644 --- a/pages/database-management/enabling-memgraph-enterprise.mdx +++ b/pages/database-management/enabling-memgraph-enterprise.mdx @@ -279,6 +279,13 @@ deployment. You can create, alter, and drop profiles, and use `SHOW MEMORY INFO` and `SHOW STORAGE INFO ON DATABASE` to monitor per-database memory usage. +### Context Graph shared spaces + +[Shared spaces](/ai-ecosystem/ai-memory/shared-spaces) run +Context Graph for a team on one Memgraph instance. Each user gets a personal +database for their coding agents' memory, and teams get shared databases, +isolated with multi-tenancy and role-based access control. + ### CRON snapshot scheduling Memgraph supports [periodic snapshot diff --git a/public/pages/ai-ecosystem/ai-memory/context-graph-flow-dark.svg b/public/pages/ai-ecosystem/ai-memory/context-graph-flow-dark.svg new file mode 100644 index 000000000..376d27eb2 --- /dev/null +++ b/public/pages/ai-ecosystem/ai-memory/context-graph-flow-dark.svg @@ -0,0 +1,209 @@ + + How Context Graph records and recalls agent sessions + During a session, the memgraph-context-graph hooks in the agent, a coding agent or an Agent SDK app, drop private text and redact secrets, and the actions-graph, skills-graph and sessions-graph connectors write the session to Memgraph as a graph of users, sessions, actions, skills and memories. The optional resources-graph connector records GitHub resources, and context-graph-spaces adds shared spaces on Memgraph Enterprise. The MCP server reads Memgraph and serves the recall and memory tools to the agent. After a session, reconciliation filters the text through the HyGM ontology, extracts entities and facts with GLiNER2 and stores them in Memgraph with their embeddings. Only optional ontology learning sends session text to an Anthropic or OpenAI API. + + + + + + + + + + + + + + + + YOUR MACHINE + + + + DURING A SESSION + + IN MEMGRAPH + + AFTER A SESSION + + + + Agent + Claude Code, Codex, Cursor or an Agent SDK app + + MCP server + recall and memory tools + + + + + Capture + Hooks drop <private> text and redact secrets + + memgraph-context-graph + hooks, MCP server, SDK and setup + + + + actions-graph + + skills-graph + + sessions-graph + + + resources-graph + GitHub, off by default + + context-graph-spaces + + ENTERPRISE + + + write + + + + Memgraph + + + + + + + + + + + User + + Memory + + + Session + + + + + Action + + Skill + + + + + + + + + + + + + + + + + + + Knowledge graph + + + + + read + + + pending sessions + + + Reconciliation + Runs locally + + ONTOLOGY + HyGM: entity and fact types + + + Extract entities and facts with GLiNER2 + + + Store them with their embeddings + + + + Ontology learning + + + session text, only with an API key + + Anthropic or OpenAI API + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/pages/ai-ecosystem/ai-memory/context-graph-flow.svg b/public/pages/ai-ecosystem/ai-memory/context-graph-flow.svg new file mode 100644 index 000000000..b451bed64 --- /dev/null +++ b/public/pages/ai-ecosystem/ai-memory/context-graph-flow.svg @@ -0,0 +1,209 @@ + + How Context Graph records and recalls agent sessions + During a session, the memgraph-context-graph hooks in the agent, a coding agent or an Agent SDK app, drop private text and redact secrets, and the actions-graph, skills-graph and sessions-graph connectors write the session to Memgraph as a graph of users, sessions, actions, skills and memories. The optional resources-graph connector records GitHub resources, and context-graph-spaces adds shared spaces on Memgraph Enterprise. The MCP server reads Memgraph and serves the recall and memory tools to the agent. After a session, reconciliation filters the text through the HyGM ontology, extracts entities and facts with GLiNER2 and stores them in Memgraph with their embeddings. Only optional ontology learning sends session text to an Anthropic or OpenAI API. + + + + + + + + + + + + + + + + YOUR MACHINE + + + + DURING A SESSION + + IN MEMGRAPH + + AFTER A SESSION + + + + Agent + Claude Code, Codex, Cursor or an Agent SDK app + + MCP server + recall and memory tools + + + + + Capture + Hooks drop <private> text and redact secrets + + memgraph-context-graph + hooks, MCP server, SDK and setup + + + + actions-graph + + skills-graph + + sessions-graph + + + resources-graph + GitHub, off by default + + context-graph-spaces + + ENTERPRISE + + + write + + + + Memgraph + + + + + + + + + + + User + + Memory + + + Session + + + + + Action + + Skill + + + + + + + + + + + + + + + + + + + Knowledge graph + + + + + read + + + pending sessions + + + Reconciliation + Runs locally + + ONTOLOGY + HyGM: entity and fact types + + + Extract entities and facts with GLiNER2 + + + Store them with their embeddings + + + + Ontology learning + + + session text, only with an API key + + Anthropic or OpenAI API + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/generate-context-graph-flow.py b/scripts/generate-context-graph-flow.py new file mode 100644 index 000000000..07abbc01b --- /dev/null +++ b/scripts/generate-context-graph-flow.py @@ -0,0 +1,264 @@ +"""Generate the Context Graph flow diagram (light and dark SVG).""" +import re +import sys + +OUT = sys.argv[1] +T = 12.0 # animation cycle, seconds +G = 88 # gap between main boxes +g = 40 # gap between reconciliation steps + +MONO = "'Ubuntu Mono', Consolas, monospace" + +# vertical layout +agent_y, agent_h = 96, 64 +cap_y = agent_y + agent_h + G +cap_h = 244 +mg_y = cap_y + cap_h + G +mg_h = 336 +rec_y = mg_y + mg_h + G +onto_y = rec_y + 66 +onto_h = 72 +ext_y = onto_y + onto_h + g +ext_h = 44 +sto_y = ext_y + ext_h + g +sto_h = 44 +rec_h = sto_y + sto_h + 24 - rec_y +mach_bottom = rec_y + rec_h + 24 +sl_y = onto_y + onto_h // 2 - 24 +api_y = mach_bottom + 34 +H = api_y + 48 + 24 + +gy = mg_y + 96 # graph: user row + + +def arrow(pid, d, extra=''): + return f' \n' + + +def hl_rect(cls, x, y, w, h, rx=4): + return f' \n' + + +def hl_path(cls, d, marker=True): + m = ' marker-end="url(#arrow-accent)"' if marker else ' stroke-linejoin="round"' + w = 2 if marker else 2.5 + return f' \n' + + +P = { + 'p1': f'M500,{agent_y + agent_h} V{cap_y - 2}', + 'p3': f'M500,{cap_y + cap_h} V{mg_y - 2}', + 'p4': f'M500,{mg_y + mg_h} V{rec_y - 2}', + 'p5': f'M500,{onto_y + onto_h} V{ext_y - 2}', + 'p6': f'M500,{ext_y + ext_h} V{sto_y - 2}', + 'p7': f'M330,{sto_y + sto_h // 2} H210 V{gy + 184} H248', + 'p8': f'M750,{mg_y + 80} H856 V{agent_y + agent_h + 2}', + 'p9': f'M760,{agent_y + agent_h // 2} H712', +} +onto_d = f'M330,{onto_y} H670 L618,{onto_y + onto_h} H382 Z' + +s = [] +a = s.append +a(f'\n') +a(' How Context Graph records and recalls agent sessions\n') +a(' During a session, the memgraph-context-graph hooks in the agent, a coding agent or an Agent SDK app, drop private text and redact secrets, and the actions-graph, skills-graph and sessions-graph connectors write the session to Memgraph as a graph of users, sessions, actions, skills and memories. The optional resources-graph connector records GitHub resources, and context-graph-spaces adds shared spaces on Memgraph Enterprise. The MCP server reads Memgraph and serves the recall and memory tools to the agent. After a session, reconciliation filters the text through the HyGM ontology, extracts entities and facts with GLiNER2 and stores them in Memgraph with their embeddings. Only optional ontology learning sends session text to an Anthropic or OpenAI API.\n') +a('STYLE') +a(''' + + + + + + + + + + + +''') +a(f' \n') +a(f' \n') +a(' YOUR MACHINE\n\n') + +# phase bands +def band(y1, y2, label, color): + c = (y1 + y2) // 2 + fill = f' fill="{color}"' if color == '#FB6E00' else '' + return (f' \n' + f' {label}\n') +a(' \n') +a(band(agent_y, cap_y + cap_h, 'DURING A SESSION', '#BAB8BB')) +a(band(mg_y, mg_y + mg_h, 'IN MEMGRAPH', '#FB6E00')) +a(band(rec_y, rec_y + rec_h, 'AFTER A SESSION', '#BAB8BB')) +a(' \n\n') + +# coding agent + MCP server +a(f' \n') +a(f' Agent\n') +a(f' Claude Code, Codex, Cursor or an Agent SDK app\n') +a(f' \n') +a(f' MCP server\n') +a(f' recall and memory tools\n') +a(arrow('p9', P['p9'])) +a(arrow('p1', P['p1'])) +a('\n') + +# capture +y = cap_y +a(f' \n') +a(f' Capture\n') +a(f' Hooks drop <private> text and redact secrets\n') +a(f' \n') +a(f' memgraph-context-graph\n') +a(f' hooks, MCP server, SDK and setup\n') +a(f' \n') +a(f' \n') +for x, name in ((306, 'actions-graph'), (438, 'skills-graph'), (570, 'sessions-graph')): + a(f' \n') + a(f' {name}\n') +a(' \n') +a(f' \n') +a(f' resources-graph\n') +a(f' GitHub, off by default\n') +a(f' \n') +a(f' context-graph-spaces\n') +a(f' \n') +a(f' ENTERPRISE\n\n') + +a(arrow('p3', P['p3'])) +a(f' write\n\n') + +# Memgraph +y = mg_y +a(f' \n') +a(f' \n') +a(f' Memgraph\n') + + +def gp(x, dy): + return x, gy + dy + + +ux, uy = 500, gy +a(' \n') +a(f' \n') +for x1, y1, x2, y2 in ((491, 9, 447, 53), (509, 9, 553, 53), (440, 60, 400, 120), (440, 60, 460, 122), + (560, 60, 540, 122), (560, 60, 600, 120), (570, 61, 643, 71)): + a(f' \n') +a(f' \n') +a(f' User\n') +a(f' \n') +a(f' Memory\n') +for cx in (440, 560): + a(f' \n') +a(f' Session\n') +for cx, dy in ((400, 120), (460, 122), (540, 122), (600, 120)): + a(f' \n') +a(f' Action\n') +a(f' \n') +a(f' Skill\n') +a(' \n') +a(' \n') +for x1, y1, x2, y2 in ((400, 127, 418, 167), (460, 129, 478, 156), (600, 127, 588, 161)): + a(f' \n') +a(' \n \n') +for x1, y1, x2, y2 in ((420, 176, 482, 164), (482, 164, 530, 198), (530, 198, 586, 170), + (420, 176, 472, 216), (472, 216, 530, 198)): + a(f' \n') +a(' \n') +for cx, dy, r in ((420, 176, 9), (482, 164, 9), (530, 198, 9), (586, 170, 9), (472, 216, 7)): + a(f' \n') +a(f' Knowledge graph\n') +a(' \n \n\n') + +a(arrow('p8', P['p8'])) +a(f' read\n\n') +a(arrow('p4', P['p4'])) +a(f' pending sessions\n\n') + +# reconciliation +y = rec_y +a(f' \n') +a(f' Reconciliation\n') +a(f' Runs locally\n') +a(f' \n') +a(f' ONTOLOGY\n') +a(f' HyGM: entity and fact types\n') +a(arrow('p5', P['p5'])) +a(f' \n') +a(f' Extract entities and facts with GLiNER2\n') +a(arrow('p6', P['p6'])) +a(f' \n') +a(f' Store them with their embeddings\n') +a(f' \n\n') + +# ontology learning + API +a(f' \n') +a(f' Ontology learning\n') +edge_x = 670 - 52 * 0.5 +a(f' \n') +a(f' \n') +a(f' session text, only with an API key\n') +a(f' \n') +a(f' Anthropic or OpenAI API\n\n') + +# animation: step highlights +a(' \n') +a(hl_rect('h-agent', 290, agent_y, 420, agent_h)) +a(hl_rect('h-capture', 290, cap_y, 420, cap_h)) +a(hl_rect('h-memgraph', 250, mg_y, 500, mg_h, 8)) +a(hl_rect('h-recon', 290, rec_y, 420, rec_h)) +a(hl_path('h-onto', onto_d, marker=False)) +a(hl_rect('h-extract', 330, ext_y, 340, ext_h)) +a(hl_rect('h-store', 330, sto_y, 340, sto_h)) +a(hl_rect('h-mcp', 760, agent_y, 192, agent_h)) + +# animation: dots along the arrows +dots = [('p1', 0.9, 1.7), ('p3', 2.6, 3.4), ('p4', 4.4, 5.2), ('p5', 5.8, 6.4), + ('p6', 6.8, 7.4), ('p7', 7.8, 8.9), ('p8', 9.0, 10.0), ('p9', 10.5, 11.0)] +a(' \n \n') +for pid, t0, t1 in dots: + k0, k1, e = t0 / T, t1 / T, 0.004 + a(f' \n' + f' \n' + f' \n' + f' \n') +a(' \n\n') +svg = ''.join(s) + +# CSS keyframes for highlights and the knowledge graph +def pct(t): + return f'{t / T * 100:.2f}%' + + +def hl(*wins): + fr = [(0, 0)] + for t0, t1 in wins: + fr += [(t0, 0), (t0 + 0.2, 1), (t1 - 0.2, 1), (t1, 0)] + return fr + [(T, 0)] + + +timeline = { + # lit from the recall at the end of one loop through the capture at the start of the next + 'h-agent': [(0, 1), (1.0, 1), (1.2, 0), (10.8, 0), (11.0, 1), (T, 1)], +'h-capture': hl((1.5, 2.8)), 'h-memgraph': hl((3.2, 4.6)), + 'h-recon': hl((5.0, 8.2)), 'h-onto': hl((5.1, 6.0)), 'h-extract': hl((6.2, 7.0)), + 'h-store': hl((7.2, 8.0)), 'h-mcp': hl((9.8, 10.7)), + 'kg': [(0, 0.3), (8.8, 0.3), (9.2, 1), (11.5, 1), (11.9, 0.3), (T, 0.3)], +} +css = [' \n') +svg = svg.replace('STYLE', ''.join(css)) + +open(f'{OUT}/context-graph-flow.svg', 'w').write(svg) +DARK = {'#F9F9F9': '#1A1718', '#FFFFFF': '#231F20', '#E6E6E6': '#3E3A3C', '#BAB8BB': '#646265', + '#231F20': '#F9F9F9', '#646265': '#BAB8BB', '#857F87': '#9A949C', '#FFF4EB': '#3A2414'} +open(f'{OUT}/context-graph-flow-dark.svg', 'w').write( + re.sub(r'#[0-9A-F]{6}', lambda m: DARK.get(m.group(0), m.group(0)), svg)) +print('height', H) diff --git a/styles/globals.css b/styles/globals.css index 705470a25..fbb7c8605 100644 --- a/styles/globals.css +++ b/styles/globals.css @@ -303,4 +303,9 @@ html.dark div.nextra-nav-container { .dark .custom-header::before { color: var(--ash-gray) !important; -} \ No newline at end of file +} +/* Show an image only in the light or only in the dark theme */ +.dark .light-only, +html:not(.dark) .dark-only { + display: none; +}