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

# Dreaming

> How ByteRover automatically consolidates, synthesizes, and prunes your context tree

Dreaming is ByteRover's background maintenance system for the context tree. It runs three LLM-driven operations — consolidate, synthesize, and prune — to keep your knowledge base organized, cross-linked, and lean without manual effort.

Dreams trigger automatically when an agent goes idle, or on demand via `brv dream`. All changes are flagged for [review](/review/overview) before they can be pushed to your team.

## Operations

Each dream runs three operations in sequence. Any operation can produce changes independently — a partial run still logs and surfaces its completed work.

<Info>
  When a dream rewrites a context file, the order of frontmatter fields (`title`, `summary`, `tags`, `keywords`, `related`, `createdAt`, `updatedAt`) is preserved, and array fields like `tags` and `related` are emitted flow-style (`tags: [a, b, c]`) to match `brv curate`. `brv vc diff` only surfaces real content changes — not field reorderings or bracket reflows.
</Info>

| Operation       | What It Does                                                                                                        |
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
| **Consolidate** | Merges related files, updates content with temporal context, and adds cross-references between connected knowledge. |
| **Synthesize**  | Detects cross-domain patterns and generates new knowledge files documenting insights that span multiple domains.    |
| **Prune**       | Archives stale or low-value files and suggests merges for content with significant overlap.                         |

### Consolidate

Consolidate groups files that changed since the last dream by domain, then uses BM25 search and sibling-file analysis to find related content. A single LLM call per domain classifies relationships and decides on an action:

| Action               | When                                                                 |         Review Required        |
| -------------------- | -------------------------------------------------------------------- | :----------------------------: |
| **MERGE**            | Two or more files cover the same topic                               |             Always             |
| **TEMPORAL\_UPDATE** | A file needs narrative updates reflecting recent changes             |     When confidence \< 0.7     |
| **CROSS\_REFERENCE** | Files are related but distinct — adds `related` links to frontmatter | Only for `core` maturity files |
| **SKIP**             | Files are unrelated                                                  |                —               |

Merged files receive `consolidated_at` and `consolidated_from` metadata in their frontmatter, preserving lineage. Source files are deleted after the merge.

### Synthesize

Synthesize reads `_index.md` domain summaries to identify patterns that span multiple domains. It skips if fewer than two domains exist. Candidates are deduplicated against existing synthesis files using BM25 (threshold: 0.5) to avoid repeating insights already captured.

Novel syntheses are written as draft knowledge files with `type: synthesis` in the frontmatter:

```markdown theme={null}
---
confidence: 0.85
sources: [api/_index.md, security/_index.md]
synthesized_at: "2025-04-15T10:00:00Z"
type: synthesis
title: "Authentication Patterns Across Services"
summary: "Common access-token verification, session handling, and refresh patterns shared across the API and security domains"
tags: [auth, patterns, cross-domain]
related: []
keywords: [oauth, session, jwt, refresh]
createdAt: "2025-04-15T10:00:00Z"
updatedAt: "2025-04-15T10:00:00Z"
---
```

The four synthesis markers (`confidence`, `sources`, `synthesized_at`, `type`) come first — they match the on-disk shape of pre-existing synthesized files so re-generating an old file does not produce a mechanical reorder diff. The seven semantic fields below mirror the order regular `brv save` files use, so the dashboard's context cards render full title, summary, and tags. `related` is left empty because synthesized files use `sources` for provenance.

Synthesis files with confidence below 0.7 are flagged for review.

### Prune

Prune identifies files that have become stale or low-value using two signals:

| Signal               | Threshold                                                                                                                |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| **Importance decay** | Decayed importance below 35 (same threshold as the [archive system](/context-tree/local-space-structure#archive-system)) |
| **Mtime staleness**  | `draft`: 60 days, `validated`: 120 days, `core`: never pruned by staleness                                               |

Candidates are capped at 20 per dream (stalest first). The LLM reviews each candidate with a content preview and decides:

| Decision        | Effect                                                                                                               |
| --------------- | -------------------------------------------------------------------------------------------------------------------- |
| **ARCHIVE**     | Moved to `.brv/archives/` with a searchable stub. Always requires review.                                            |
| **KEEP**        | Bumps mtime to reset the staleness clock.                                                                            |
| **MERGE\_INTO** | Defers a merge suggestion to the next dream's consolidate phase (see [Cross-Cycle Behavior](#cross-cycle-behavior)). |

## When Dreaming Triggers

Before a dream can run, it must pass four sequential eligibility gates:

| Gate         | Check                                           | Default          | Skipped by `--force` |
| ------------ | ----------------------------------------------- | ---------------- | :------------------: |
| **Time**     | Hours since last dream                          | 12 hours minimum |          Yes         |
| **Activity** | Curations since last dream                      | 3 minimum        |          Yes         |
| **Queue**    | Agent task queue is empty                       | —                |          Yes         |
| **Lock**     | No other dream is running (PID-based lock file) | —                |          No          |

The daemon checks gates 1–3 before dispatching. The agent process acquires the lock (gate 4) at execution time. Stale locks older than 30 minutes are automatically reclaimed.

When a gate fails, `brv dream` reports the reason:

```
Dream skipped: Too recent (2.5h < 12h)
```

## Commands

```bash theme={null}
# Run a dream (must pass all eligibility gates)
brv dream

# Skip time, activity, and queue gates
brv dream --force

# Queue the dream and return immediately
brv dream --detach

# Cancel a running dream by task ID (e.g., one started with --detach)
brv dream --cancel drm-1739700001000

# Revert the last dream
brv dream --undo
```

<Note>In the foreground, press `Ctrl+C` once to gracefully cancel a running dream (stderr shows `Cancelling task... (Ctrl-C again to force exit)`); a second press hard-exits with code 130. Inside the REPL, `Ctrl+Q` cancels the active curate, query, or dream task.</Note>

## Dream State

ByteRover tracks dream metadata in `dream-state.json`:

| Field                 | Description                                                            |
| --------------------- | ---------------------------------------------------------------------- |
| `curationsSinceDream` | Counter incremented by each curate, reset to 0 after a dream completes |
| `lastDreamAt`         | ISO 8601 timestamp of the last completed dream                         |
| `totalDreams`         | Lifetime dream count                                                   |
| `pendingMerges`       | Cross-cycle merge suggestions from prune (see below)                   |

All writes to this file are serialized by a per-file mutex to prevent concurrent curate tasks from losing counter increments.

## Dream Logs

Each dream is logged to `.brv/dream-log/drm-{timestamp}.json` with a status, the full list of operations, and a summary:

| Status      | Meaning                                                    |
| ----------- | ---------------------------------------------------------- |
| `completed` | All three operations finished successfully                 |
| `partial`   | One or more operations completed before a timeout or error |
| `error`     | The dream failed before any operations completed           |
| `undone`    | A completed dream was reverted via `--undo`                |

The summary section provides quick counts:

```
Dream completed (drm-1713364200000)
3 consolidated | 1 synthesized | 2 pruned
4 operations flagged for review
```

Dreams have a 5-minute total budget. If the budget is exceeded mid-operation, completed work is preserved under status `partial`.

## Cross-Cycle Behavior

Prune may suggest merging file A into file B, but consolidate has already run in the current cycle. These suggestions are stored as `pendingMerges` entries in `dream-state.json` and consumed by consolidate in the **next** dream:

1. Consolidate reads `pendingMerges` as non-binding hints
2. Adds suggested source files to its changed-file set (if they still exist on disk)
3. Passes the hints to the LLM alongside its own analysis
4. Clears `pendingMerges` regardless of whether the LLM acted on them

This ensures merge suggestions are never lost between cycles, while giving the LLM freedom to override them.

## Undo

`brv dream --undo` reverts the most recent dream. It restores all modified, merged, or deleted files from backups and dream log data:

| Operation              | Undo Effect                                                |
| ---------------------- | ---------------------------------------------------------- |
| MERGE                  | Restores source files, reverts target to pre-merge content |
| TEMPORAL\_UPDATE       | Restores original file content                             |
| CROSS\_REFERENCE       | Reverts frontmatter to pre-change state                    |
| Synthesis (CREATE)     | Deletes the generated synthesis file                       |
| ARCHIVE                | Restores from `.brv/archives/` stub                        |
| MERGE\_INTO suggestion | Removes the entry from `pendingMerges`                     |

After undo, the dream log is marked `undone`, the dream counter is decremented, and any associated review entries are marked as rejected.

## Review Integration

All dream operations that modify the context tree are dual-written as review entries, making them visible in `brv review pending` alongside regular curation changes. Each entry includes the operation type and reasoning:

```
[dream/consolidate] Merged api/auth.md and api/oauth.md — overlapping OAuth flow content
[dream/synthesize] Generated cross-domain synthesis: authentication patterns across services
[dream/prune] Archived notes/deprecated-oauth.md — importance decayed below threshold
```

Approving a dream review entry keeps the change. Rejecting restores the original content from backup — the same approve/reject flow as [regular curation reviews](/review/overview#review-lifecycle).
