# Reflection

Synthesise insights from patterns across stored memories.

Reflection is a reasoning operation over the memory store. Unlike retrieval, which surfaces existing facts that match a query, reflection asks SurrealDB Agent Memory to examine a set of memories and draw conclusions from them - to reason about patterns, identify trends, and synthesise insights that do not exist as explicit stored attributes.

> [!NOTE]
> `Spectron` was the project name for SurrealDB Agent Memory. These type names
> will be renamed in a future release.

The result is a synthesised text insight backed by evidence citations. If `persist` is enabled, the synthesised insights are also stored as new experiential memory attributes, making them available to future queries.

## How it works

When you call `memory.reflect()`, SurrealDB Agent Memory:

1. Retrieves the memories most relevant to your query using hybrid retrieval, respecting scope.
2. Sends the retrieved evidence to an LLM with a synthesis prompt instructing it to reason over the material and surface patterns, risks, or insights.
3. Returns the synthesised text alongside the supporting memories.
4. If `persist=True`, writes the synthesised insights as new knowledge-category attributes inside the caller's `memory:write` region.

Reflection is more expensive than retrieval - it always involves an LLM call - but it produces conclusions that no single stored attribute contains.

## Basic usage

```python
out = await memory.reflect(
    query="What patterns do you see in customer complaints this month?",
    persist=False)

print(out.reflection)   # synthesised insight text
print(out.evidence)     # list of supporting memory hits
```

```typescript
import { Spectron } from "@surrealdb/spectron";

const memory = new Spectron({ context: "ctx_01jt4kx...", apiKey: "sk-..." });

const out = await memory.reflect({
    query: "What patterns do you see in customer complaints this month?",
    persist: false });

console.log(out.reflection);
console.log(out.evidence);
```

### REST

```http
POST /api/v1/{context_id}/reflect
Content-Type: application/json

{
  "query": "What patterns do you see in customer complaints this month?",
  "scope": ["org/acme/user/alice"],
  "persist": false
}
```

```json
{
  "reflection": "Three recurring patterns emerged across 47 complaint sessions this month…",
  "evidence": [
    "billing proration came up in 18 sessions",
    "search accuracy complaints clustered after the 3rd deployment"
  ],
  "persistedAttributes": [],
  "traceId": "mZrlXhKPuV1H9S1l"
}
```

## Persisting synthesised insights

Setting `persist=True` instructs SurrealDB Agent Memory to write the synthesised insights back to memory as new attributes. This makes the reflection available to future retrieval queries without repeating the synthesis LLM call.

```python
out = await memory.reflect(
    query="What does this user value most in a development tool?",
    persist=True)

print(out.reflection)
print(out.persisted_attributes)  # list of newly created attribute records
```

```typescript
const out = await memory.reflect({
    query: "What does this user value most in a development tool?",
    persist: true });

console.log(out.reflection);
console.log(out.persistedAttributes);
```

When `persist=True`, the response includes **`persistedAttributes`** listing the attribute records that were written:

```json
{
  "reflection": "Alice consistently prioritises fast feedback loops…",
  "evidence": ["Alice mentioned keyboard shortcuts three times", "…"],
  "persistedAttributes": [
    {
      "entityId": "['person', 'alice']",
      "key": "core_tool_values",
      "value": "Fast feedback loops, keyboard-driven workflows"
    }
  ],
  "traceId": "…"
}
```

Persisted insights are stored as knowledge-category attributes, which carry a decay rate of 0.995 per day. They are available immediately for retrieval and appear in future profile requests.

## Permissions for persist

`persist=True` writes attributes, so it requires **`memory:write`** - and the write
lands inside the caller's write region, never outside it. There is no persist-scope
argument: the region the key holds is the region reflect can write to.

A key granted `memory:write` on `org/acme/*` can persist org-level insights drawn
from across the whole org. A key granted only `org/acme/user/alice` persists at
that path and below, however wide the evidence it reasoned over.

This prevents agents from writing to scopes they do not own. An agent operating for user A cannot persist insights visible to user B, even if the reflection was informed by shared org-level memory.

## Use cases

**Project risk analysis**: A project management agent reflects on all task and decision records for a project to identify risks the team has not explicitly surfaced.

```python
risks = await memory.reflect(
    query="What risks are present in this project that we haven't explicitly discussed?",
    persist=True)
```

**Sales pattern recognition**: A sales coaching agent reflects on call notes and outcome records to identify what approaches correlate with successful closes.

```python
patterns = await memory.reflect(
    query="What conversational patterns appear most often in deals that closed this quarter?",
    persist=True)
```

**Support gap identification**: A support agent reflects on unresolved queries to identify topics where the knowledge base is insufficient.

```python
gaps = await memory.reflect(
    query="Which questions did I fail to answer confidently this week, and what knowledge would have helped?",
    persist=True)
```

## Reflection versus retrieval

| | Retrieval (`memory.query`) | Reflection (`memory.reflect`) |
|---|---|---|
| Operation | Finds existing attributes matching a query | Reasons over retrieved attributes to produce new insights |
| LLM involvement | Only at the `full_context` tier | Always |
| Output | Ranked list of stored facts | Synthesised insight text + evidence |
| Persist option | N/A - retrieval is read-only | Optional - writes new attributes |
| Cost | Low to medium | Higher - always incurs an LLM call |

Use retrieval when you need to surface known facts. Use reflection when you need to reason about patterns, draw conclusions, or produce summaries that span many individual memory records.
