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

# Memory Management API — Save, Recall, Forget, and Export

> REST API endpoints for managing memories: save important context, recall past memories, forget obsolete entries, and export or import your full memory database.

Use these endpoints to directly manage the memory store — save insights explicitly, list stored memories, delete outdated entries, and import or export your full memory database for backup or migration. These endpoints give you precise control over what Agent Memory retains, independent of the automatic hook-capture pipeline.

## POST /agentmemory/remember

Saves an observation or insight to long-term memory. Use this to explicitly capture decisions, patterns, or facts that you want available in future sessions — even if no session hook fired.

Returns `201 Created` on success.

### Request

```bash theme={null}
curl -X POST http://localhost:3111/agentmemory/remember \
  -H "Content-Type: application/json" \
  -d '{
    "content": "The auth service uses JWT tokens with 24-hour expiry, refresh tokens rotate on each use with a 7-day sliding window.",
    "type": "architecture",
    "project": "my-project",
    "concepts": ["auth", "JWT", "refresh-token"],
    "files": ["src/auth/tokens.ts", "src/middleware/auth.ts"],
    "ttlDays": 90
  }'
```

<ParamField body="content" type="string" required>
  The memory content to save. Be specific — Agent Memory uses this text for BM25 keyword indexing and vector embedding, so precise wording improves future recall accuracy.
</ParamField>

<ParamField body="type" type="string">
  Memory classification. One of:

  * `pattern` — a recurring code pattern or approach
  * `preference` — a developer or team preference
  * `architecture` — an architectural decision
  * `bug` — a known bug or gotcha
  * `workflow` — a workflow or process step
  * `fact` — a general factual statement

  Defaults to `fact` if not supplied.
</ParamField>

<ParamField body="project" type="string">
  Project name to scope this memory. If set, the memory is included in project-scoped recalls and profile queries.
</ParamField>

<ParamField body="concepts" type="string[]">
  Concept tags used to improve retrieval. These are indexed separately from the content and used by the BM25 and graph search streams.
</ParamField>

<ParamField body="files" type="string[]">
  Related file paths. Used by the enrichment and file-context endpoints to surface this memory when the agent opens these files.
</ParamField>

<ParamField body="ttlDays" type="number">
  Number of days after which this memory should begin to decay. Agent Memory will set a `forgetAfter` timestamp and evict the memory during the next decay sweep.
</ParamField>

<ParamField body="sourceObservationIds" type="string[]">
  IDs of observations that this memory was derived from. Provides provenance — you can trace any memory back to the raw session event.
</ParamField>

### Response

```json theme={null}
{
  "memoryId": "mem_xyz789",
  "strength": 1.0,
  "version": 1,
  "isLatest": true
}
```

<ResponseField name="memoryId" type="string">
  Unique identifier for the saved memory. Use this to retrieve, evolve, or delete the memory later.
</ResponseField>

<ResponseField name="strength" type="number">
  Initial memory strength between `0.0` and `1.0`. Strength increases each time the memory is recalled and decays over time via the Ebbinghaus curve.
</ResponseField>

***

## POST /agentmemory/forget

Deletes observations or memories. You can delete by `memoryId` (removes a specific long-term memory) or by `sessionId` (removes all observations for a session).

<Warning>
  Forget operations are logged in the audit trail but are not reversible unless you have a snapshot created with `POST /agentmemory/snapshot/create` beforehand.
</Warning>

### Delete a specific memory

```bash theme={null}
curl -X POST http://localhost:3111/agentmemory/forget \
  -H "Content-Type: application/json" \
  -d '{ "memoryId": "mem_xyz789" }'
```

### Delete all observations for a session

```bash theme={null}
curl -X POST http://localhost:3111/agentmemory/forget \
  -H "Content-Type: application/json" \
  -d '{ "sessionId": "sess_abc123" }'
```

You can also pass both `sessionId` and `observationIds` together to delete specific observations within a session:

```json theme={null}
{
  "sessionId": "sess_abc123",
  "observationIds": ["obs_1", "obs_2"]
}
```

<ParamField body="memoryId" type="string">
  ID of a long-term memory to delete. Required unless `sessionId` is provided.
</ParamField>

<ParamField body="sessionId" type="string">
  Session ID to clear. Removes all observations for the session. Required unless `memoryId` is provided.
</ParamField>

<ParamField body="observationIds" type="string[]">
  Specific observation IDs to delete within the given `sessionId`. If omitted, all observations for the session are removed.
</ParamField>

***

## GET /agentmemory/memories

Lists stored long-term memories with optional filtering and pagination. For large corpora, use `limit` and `offset` to page through results.

```bash theme={null}
# Count only (no payload — fastest for dashboards)
curl "http://localhost:3111/agentmemory/memories?count=true"

# Paginated list
curl "http://localhost:3111/agentmemory/memories?limit=50&offset=0&latest=true"
```

| Query param      | Type    | Description                                                                                     |
| ---------------- | ------- | ----------------------------------------------------------------------------------------------- |
| `count`          | boolean | Return only `{ total, latestCount }` — no memory payload. Useful for status checks.             |
| `latest`         | boolean | When `true`, return only the most recent version of each memory (`isLatest=true`).              |
| `limit`          | number  | Max memories to return (capped at 5000).                                                        |
| `offset`         | number  | Pagination offset (default `0`).                                                                |
| `agentId`        | string  | Filter by agent ID. Pass `*` to bypass scope isolation.                                         |
| `includeOrphans` | boolean | When `true`, also return memories with no `agentId` (created before agent scoping was enabled). |

### Response

```json theme={null}
{
  "memories": [
    {
      "id": "mem_xyz789",
      "title": "JWT refresh token rotation",
      "content": "Auth uses JWT with 24-hour expiry; refresh tokens rotate on use.",
      "type": "architecture",
      "concepts": ["auth", "JWT", "refresh-token"],
      "files": ["src/auth/tokens.ts"],
      "strength": 0.91,
      "version": 2,
      "isLatest": true,
      "project": "my-project",
      "createdAt": "2025-01-10T09:00:00.000Z",
      "updatedAt": "2025-01-15T11:00:00.000Z"
    }
  ],
  "total": 847,
  "offset": 0,
  "limit": 50
}
```

***

## GET /agentmemory/memories/:id

Retrieves a single memory by its ID.

```bash theme={null}
curl http://localhost:3111/agentmemory/memories/mem_xyz789
```

Returns `{ "memory": Memory }` or `404` if the memory does not exist.

***

## GET /agentmemory/profile

Returns the memory profile for a project — the top concepts, most-accessed files, learned conventions, and common error patterns that Agent Memory has built up across all sessions for this project.

```bash theme={null}
curl "http://localhost:3111/agentmemory/profile?project=my-project"
```

<ParamField query="project" type="string" required>
  The project name to retrieve the profile for. Returns `400` if omitted.
</ParamField>

### Response

```json theme={null}
{
  "project": "my-project",
  "updatedAt": "2025-01-15T11:00:00.000Z",
  "topConcepts": [
    { "concept": "auth", "frequency": 34 },
    { "concept": "database", "frequency": 21 },
    { "concept": "api", "frequency": 18 }
  ],
  "topFiles": [
    { "file": "src/auth/tokens.ts", "frequency": 19 },
    { "file": "src/db/index.ts", "frequency": 12 }
  ],
  "conventions": [
    "Uses TypeScript strict mode",
    "Postgres with Drizzle ORM",
    "JWT via jose (not jsonwebtoken) for Edge compatibility"
  ],
  "commonErrors": [
    "N+1 queries when fetching user relations"
  ],
  "recentActivity": [
    "Implemented refresh token rotation",
    "Added rate limiting middleware"
  ],
  "sessionCount": 42,
  "totalObservations": 1834,
  "summary": "A TypeScript API with JWT auth, Postgres, and Drizzle ORM."
}
```

***

## POST /agentmemory/evolve

Updates an existing memory with new content while preserving its version history. Use this when you learn that a previous memory was incorrect or incomplete. The old version is retained and marked as superseded.

```bash theme={null}
curl -X POST http://localhost:3111/agentmemory/evolve \
  -H "Content-Type: application/json" \
  -d '{
    "memoryId": "mem_xyz789",
    "newContent": "JWT tokens now use 1-hour expiry (changed from 24h). Refresh tokens still rotate with a 7-day sliding window.",
    "newTitle": "JWT token expiry updated to 1 hour"
  }'
```

<ParamField body="memoryId" type="string" required>
  ID of the memory to evolve.
</ParamField>

<ParamField body="newContent" type="string" required>
  The updated memory content. The previous version is stored and linked as a `supersedes` relation.
</ParamField>

<ParamField body="newTitle" type="string">
  Optional new title for the evolved memory.
</ParamField>

***

## GET /agentmemory/export

Exports all memory data as a single JSON object. Use this to back up your memory store, migrate to a new machine, or inspect raw state.

```bash theme={null}
curl "http://localhost:3111/agentmemory/export" > agentmemory-backup.json
```

For large corpora, paginate using `maxSessions` and `offset`:

```bash theme={null}
# Export 50 sessions at a time
curl "http://localhost:3111/agentmemory/export?maxSessions=50&offset=0"
curl "http://localhost:3111/agentmemory/export?maxSessions=50&offset=50"
```

| Query param   | Type   | Description                                  |
| ------------- | ------ | -------------------------------------------- |
| `maxSessions` | number | Max sessions to include per page.            |
| `offset`      | number | Session offset for pagination (default `0`). |

### Response

The response is an `ExportData` object containing:

```json theme={null}
{
  "version": "0.9.27",
  "exportedAt": "2025-01-15T12:00:00.000Z",
  "sessions": [...],
  "observations": { "sess_abc123": [...] },
  "memories": [...],
  "summaries": [...],
  "profiles": [...],
  "graphNodes": [...],
  "graphEdges": [...],
  "semanticMemories": [...],
  "proceduralMemories": [...],
  "lessons": [...],
  "insights": [...],
  "pagination": {
    "offset": 0,
    "limit": 50,
    "total": 312,
    "hasMore": true
  }
}
```

***

## POST /agentmemory/import

Imports memory data from a previous export. Wrap the `ExportData` object in an `exportData` field:

```bash theme={null}
curl -X POST http://localhost:3111/agentmemory/import \
  -H "Content-Type: application/json" \
  -d '{
    "exportData": { ... },
    "strategy": "merge"
  }'
```

<ParamField body="exportData" type="object" required>
  An `ExportData` object from a previous `GET /agentmemory/export` call.
</ParamField>

<ParamField body="strategy" type="string">
  Import conflict strategy. One of:

  * `merge` (default) — combine imported data with existing data
  * `replace` — replace existing data with the import
  * `skip` — skip any records that already exist
</ParamField>

***

## GET /agentmemory/audit

Returns the full audit trail of memory operations — every `remember`, `forget`, `consolidate`, `evolve`, `import`, `export`, and governance operation, with timestamps, function IDs, target memory IDs, and agent IDs.

```bash theme={null}
curl "http://localhost:3111/agentmemory/audit?limit=50&operation=remember"
```

| Query param | Type   | Description                                                                              |
| ----------- | ------ | ---------------------------------------------------------------------------------------- |
| `limit`     | number | Max audit entries to return (default `50`).                                              |
| `operation` | string | Filter by operation type (e.g. `remember`, `forget`, `consolidate`, `import`, `export`). |

### Response

```json theme={null}
{
  "entries": [
    {
      "id": "audit_001",
      "timestamp": "2025-01-15T11:00:00.000Z",
      "operation": "remember",
      "functionId": "mem::remember",
      "targetIds": ["mem_xyz789"],
      "details": { "project": "my-project", "type": "architecture" },
      "qualityScore": 0.88
    }
  ],
  "success": true
}
```

<Tip>
  Use the audit trail before bulk-deleting memories via `POST /agentmemory/governance/bulk-delete`. The `operation` filter lets you review what Agent Memory has been doing automatically on your behalf.
</Tip>

***

## Governance Endpoints

### DELETE /agentmemory/governance/memories

Bulk-deletes specific memories by ID with a mandatory audit log entry.

```bash theme={null}
curl -X DELETE http://localhost:3111/agentmemory/governance/memories \
  -H "Content-Type: application/json" \
  -d '{
    "memoryIds": ["mem_abc", "mem_def"],
    "reason": "Outdated after auth system rewrite"
  }'
```

### POST /agentmemory/governance/bulk-delete

Bulk-deletes memories matching a filter. Supports `dryRun=true` to preview what would be deleted.

```bash theme={null}
curl -X POST http://localhost:3111/agentmemory/governance/bulk-delete \
  -H "Content-Type: application/json" \
  -d '{
    "type": ["bug"],
    "dateTo": "2024-06-01T00:00:00.000Z",
    "qualityBelow": 0.3,
    "dryRun": true
  }'
```

| Field          | Type      | Description                                                           |
| -------------- | --------- | --------------------------------------------------------------------- |
| `type`         | string\[] | Memory types to delete.                                               |
| `dateFrom`     | string    | ISO date — only delete memories created after this date.              |
| `dateTo`       | string    | ISO date — only delete memories created before this date.             |
| `qualityBelow` | number    | Delete memories with a quality score below this threshold.            |
| `dryRun`       | boolean   | When `true`, returns what would be deleted without actually deleting. |

***

## Memory Consolidation

### POST /agentmemory/consolidate

Manually triggers the 4-tier memory consolidation pipeline. Requires `CONSOLIDATION_ENABLED=true` and a configured LLM provider.

```bash theme={null}
curl -X POST http://localhost:3111/agentmemory/consolidate \
  -H "Content-Type: application/json" \
  -d '{ "project": "my-project", "minObservations": 10 }'
```

Returns `503` with `{ "flag": "CONSOLIDATION_ENABLED", "enableHow": "..." }` if consolidation is not enabled.

### POST /agentmemory/consolidate-pipeline

Runs a specific consolidation tier. Accepts an optional `tier` field (`"working"`, `"episodic"`, `"semantic"`, `"procedural"`).

### POST /agentmemory/evict

Evicts memories that have decayed below the retention threshold. Supports `?dryRun=true` to preview evictions.

```bash theme={null}
curl -X POST "http://localhost:3111/agentmemory/evict?dryRun=true"
```
