> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cognee.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Codex

> Give Codex persistent memory with the Cognee plugin.

Add persistent memory to Codex with the **Cognee memory plugin** — no code and no `pip install`. It works in the Codex CLI and can also be activated through the Codex IDE plugin. The plugin hooks into Codex's lifecycle, so it:

* captures your prompts, tool traces, and assistant responses into session memory
* injects relevant context on every prompt submit
* syncs the session into your knowledge graph on session end

Sessions are disposable; your memory isn't.

## Install

The Cognee memory plugin depends on Codex lifecycle hooks. Enable hooks before installing it.

<Tabs>
  <Tab title="CLI">
    Enable hooks, then install from the Codex marketplace with the Codex CLI:

    ```bash theme={null}
    codex features enable hooks
    codex plugin marketplace add topoteretes/cognee-integrations --ref main
    codex plugin add cognee@cognee
    ```
  </Tab>

  <Tab title="Manual">
    If you prefer to manage Codex config directly, add this to `~/.codex/config.toml`:

    ```toml theme={null}
    [features]
    hooks = true

    [marketplaces.cognee]
    source_type = "git"
    source = "https://github.com/topoteretes/cognee-integrations.git"
    ref = "main"

    [plugins."cognee@cognee"]
    enabled = true
    ```
  </Tab>
</Tabs>

<Info>
  Make sure Cognee hooks are enabled for both the Codex CLI and the Codex IDE plugin. If Codex asks you to review hooks, open `/hooks` and allow or trust the Cognee hooks. Until hooks are enabled and trusted, Codex will not call the plugin on prompt submit, tool use, stop, compaction, or session end.
</Info>

On startup the status line shows `cognee: <dataset> · <mode>` to confirm the plugin is active.

## Configure your backend

Set environment variables in the shell that launches Codex.

<Tabs>
  <Tab title="Cognee Cloud / remote">
    Point the plugin at [Cognee Cloud](/cognee-cloud/overview) or a remote server by setting both:

    ```bash theme={null}
    export COGNEE_BASE_URL="https://your-tenant.aws.cognee.ai"
    export COGNEE_API_KEY="ck_..."
    ```
  </Tab>

  <Tab title="Local (default)">
    When `COGNEE_BASE_URL` is unset, the plugin bootstraps a local Cognee API at `http://localhost:8011`. Only an LLM key is required — `COGNEE_API_KEY` is auto-minted if absent:

    ```bash theme={null}
    export LLM_API_KEY="sk-..."
    ```
  </Tab>
</Tabs>

<Note>
  **Cognee's LLM calls do not run through Codex.** Your Codex plan pays only for your conversation with the model. Everything Cognee does on its own — entity and relationship extraction during cognify, summarization, embeddings, and search-time completions — happens inside the Cognee backend against the LLM provider configured *there*, and is billed by that provider. In local mode you configure it with `LLM_API_KEY`; in Cloud/remote mode your tenant holds the key server-side, so no local LLM key is needed.
</Note>

In local mode, the single `LLM_API_KEY` above covers extraction, summarization, and embeddings: Cognee defaults to `openai/gpt-5-mini` for the LLM and `openai/text-embedding-3-large` for embeddings, and embeddings reuse `LLM_API_KEY` when `EMBEDDING_API_KEY` is unset. To use another provider, set `LLM_PROVIDER`, `LLM_MODEL`, and — for Azure, Ollama, or OpenAI-compatible endpoints — `LLM_ENDPOINT`. Changing only the LLM leaves embeddings on OpenAI, so also set the `EMBEDDING_*` variables or set `EMBEDDING_API_KEY` to an OpenAI key so the default embeddings keep working. See [LLM providers](/setup-configuration/llm-providers) and [embedding providers](/setup-configuration/embedding-providers).

You can also persist settings in `~/.cognee-plugin/config.json`:

```json theme={null}
{
  "base_url": "https://your-tenant.aws.cognee.ai",
  "dataset": "agent_sessions"
}
```

## Use it

Use Codex as usual — memory is captured and recalled automatically. To verify, end a session with `/exit` (which syncs it into Cognee), then start a fresh session and ask: *"What do you know from cognee?"* Answering from a clean session proves it's recalling from your memory.

## Sessions & datasets

* **Sessions** — set `COGNEE_SESSION_ID` before launching Codex to resume or share a named live session across terminals. If you do not set it, the plugin chooses a session id from its configured session strategy.
* **Datasets** — all writes and recall are scoped to one dataset (`agent_sessions` by default). Set `COGNEE_PLUGIN_DATASET` to use a custom one. The Codex and Claude Code plugins share the default dataset, so memory carries across both.

## How It Works

The plugin registers Codex lifecycle hooks:

| Hook               | Fires                     | What it does                                                                                                         |
| ------------------ | ------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `SessionStart`     | Session launch            | Selects local or remote mode, sets up session identity, prepares the dataset, and starts the background idle watcher |
| `UserPromptSubmit` | Each prompt you submit    | Recalls relevant context from Cognee and injects it, then stages the prompt in session memory in the background      |
| `PostToolUse`      | After each tool call      | Stores the tool call as a trace entry in session memory, without blocking the tool                                   |
| `Stop`             | Turn end                  | Stores the assistant's answer in session memory, paired with the prompt it answered                                  |
| `PreCompact`       | Before context compaction | Builds a memory anchor so relevant context survives the compacted history                                            |
| `SessionEnd`       | Session exit              | Starts a detached worker that runs the final sync of the session into your knowledge graph                           |

A background idle watcher persists the session cache after periods of inactivity, and a final sync on session end bridges the session into the permanent graph.

## Session distillation (self-improvement)

The Cognee coding-agent plugins (Claude Code, Codex) run session distillation for you — you never call `improve()` by hand. A distillation pass fires on three triggers:

| Trigger                | When it fires                | How                                                                                                                                                                                                                                                                            |
| ---------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Session end**        | You quit the agent           | The `SessionEnd` hook drains buffered turns into the server session cache, then fires `POST /api/v1/improve` for the session id in the background. A launch-exit watcher covers exits where the hook never fires — a hard exit, or Codex CLI shutdowns that skip `SessionEnd`. |
| **Every N tool calls** | Long sessions, incrementally | A per-session counter fires an improve every `COGNEE_AUTO_IMPROVE_EVERY` stored tool calls/stops (default **150**), so a long session bridges into the graph without waiting for the end.                                                                                      |
| **On idle**            | The session goes quiet       | A background idle watcher polls every `COGNEE_IDLE_POLL` seconds and fires an improve after `COGNEE_IDLE_THRESHOLD` seconds of inactivity, then waits at least `COGNEE_IMPROVE_COOLDOWN` seconds before the next idle run.                                                     |

<Note>
  Overlapping triggers are safe. A per-session improve **lock** on the server serializes concurrent runs, and unchanged session content **dedups server-side by content hash** — so a repeat improve over content that hasn't changed is a cheap no-op, not duplicated work.
</Note>

### Configuration

All triggers are tuned through environment variables read by the plugin. The defaults are chosen so distillation stays out of your way; you rarely need to change them.

| Variable                        | Default                             | What it controls                                                                                                                                                                                   |
| ------------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `COGNEE_AUTO_IMPROVE_EVERY`     | `150`                               | Stored tool calls/stops between automatic mid-session improves                                                                                                                                     |
| `COGNEE_IDLE_THRESHOLD`         | `60`                                | Seconds of inactivity before an idle improve fires                                                                                                                                                 |
| `COGNEE_IMPROVE_COOLDOWN`       | `600`                               | Minimum seconds between idle improve runs                                                                                                                                                          |
| `COGNEE_IDLE_POLL`              | `10`                                | How often the idle watcher checks for inactivity                                                                                                                                                   |
| `COGNEE_IMPROVE_SUBMIT_TIMEOUT` | `420` (Claude Code) / `180` (Codex) | Read timeout for the improve POST (distillation runs inside the request). The Claude Code plugin raises this to `420` at startup to clear cognee's LLM-retry floor; Codex uses the `180` fallback. |
| `COGNEE_IDLE_DISABLED`          | *unset*                             | Set to `1` / `true` to turn off the idle-watcher trigger entirely                                                                                                                                  |

<Tip>
  The plugin READMEs document additional advanced knobs — timing (poll deadlines, busy-retry intervals for a held session lock), session-sync retries, and the update-notification variables (`COGNEE_UPDATE_CHECK`, `COGNEE_UPDATE_CHECK_INTERVAL`). You almost never need them — reach for the table above first.
</Tip>

### Turning it down or off

* **Stop idle-triggered improves:** set `COGNEE_IDLE_DISABLED=1` before launching the agent. Session-end and per-turn improves still run.
* **Reduce mid-session improves:** raise `COGNEE_AUTO_IMPROVE_EVERY` to a large value so the per-turn trigger effectively never fires within a session.
* **Session-end distillation always runs** when the plugin is active — it's how a finished session reaches permanent memory.

### Confirming it happened

* **Cloud UI:** the **Self-improvement** card at the top of a session on the [Sessions page](/cognee-cloud/ui/sessions#self-improvement) shows the status of the last graph enrichment and the dataset it wrote to.
* **Plugin hook log:** each automatic run emits an `improve_fired` event you can grep for when debugging (in local SDK mode, where the plugin calls the library directly instead of the HTTP endpoint, look for `auto_improve_fired` instead).
* **`improve-unsupported.json` marker:** if this file appears in the plugin's shared state directory (24h TTL), the server rejected the improve endpoint and the plugin fell back to the legacy `remember` bridge for that window — a signal the server predates session-aware improve.

## Debugging & Resuming Sessions

Hooks are callbacks from Codex, not a durable job queue: events that happen while hooks are disabled or untrusted, or while the plugin cannot reach the backend, are not replayed later. When memory does not appear, check these layers first:

| Layer            | What it controls                                                                             | How to verify                                                                                                                                               |
| ---------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Codex hooks      | Whether Codex calls the plugin on prompt submit, tool use, stop, compaction, and session end | Run `codex features enable hooks`, then open `/hooks` if Codex asks you to review or trust hooks                                                            |
| Cognee backend   | Where the plugin writes session memory and recalls graph context                             | In Cloud/remote mode, confirm `COGNEE_BASE_URL` and `COGNEE_API_KEY`; in local mode, confirm `LLM_API_KEY` is set so the plugin-managed local API can start |
| Session identity | Which live session receives staged prompts, traces, and answers                              | Keep the same `COGNEE_SESSION_ID` and `COGNEE_PLUGIN_DATASET` when you expect a resumed terminal to continue the same session                               |

A resumed or second terminal continues the same live session only when the session id and dataset match: set `COGNEE_SESSION_ID` before launching Codex and keep `COGNEE_PLUGIN_DATASET` unchanged, otherwise the resumed work lands in a new session. After changing hook trust, credentials, dataset, or session id, restart Codex so `SessionStart` can run with the new state.

<Note>
  Hook commands run with `python3`, falling back to `python` if `python3` isn't found. If neither resolves on `PATH` — most commonly on Windows, where the python.org installer doesn't always register a `python3` alias — every hook fails with a "hook failure" error and no session is ever created. Run `python3 --version` or `python --version` in the same shell that launches Codex to confirm one is available, or reinstall Python with "Add python.exe to PATH" checked.
</Note>

Exit Codex normally (for example with `/exit`) when you want `SessionEnd` to trigger the final graph sync. If the process is killed instead, recent session cache entries may exist, but the final session-to-graph sync may not have run yet.

## Configuration Reference

Precedence: environment variables → `~/.cognee-plugin/config.json` → defaults.

| Setting          | Env var                    | Default                 | Notes                                                      |
| ---------------- | -------------------------- | ----------------------- | ---------------------------------------------------------- |
| Dataset          | `COGNEE_PLUGIN_DATASET`    | `agent_sessions`        | Dataset for writes and recall                              |
| Session ID       | `COGNEE_SESSION_ID`        | strategy-derived        | Override the configured strategy to resume a named session |
| Session strategy | `COGNEE_SESSION_STRATEGY`  | `per-directory`         | `per-directory`, `git-branch`, `static`                    |
| Base URL         | `COGNEE_BASE_URL`          | unset                   | Set to use a managed/remote endpoint                       |
| API key          | `COGNEE_API_KEY`           | unset                   | Auto-minted if absent in local mode                        |
| Local API URL    | `COGNEE_LOCAL_API_URL`     | `http://localhost:8011` | Local API base URL                                         |
| Local LLM        | `LLM_API_KEY`, `LLM_MODEL` | unset                   | Required for local mode                                    |

## Update or Remove

Reinstall to pull a new plugin version:

```bash theme={null}
codex plugin remove cognee@cognee
codex plugin add cognee@cognee
```

***

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/topoteretes/cognee-integrations/tree/main/integrations/codex">
    View source code and the full configuration reference
  </Card>

  <Card title="Claude Code plugin" icon="bot" href="/integrations/claude-code-integration">
    The same memory plugin for Claude Code
  </Card>
</CardGroup>
