Dream Mode
Biologically-inspired nightly cognitive processing for autonomous memory maintenance
Overview
Dream Mode is PiSovereign’s autonomous nightly processing engine, inspired by how the human brain consolidates memories during sleep. When the user is inactive, Dream Mode runs alternating NREM (declarative consolidation) and REM (creative synthesis) cycles — just like biological sleep architecture — to maintain, strengthen, and reorganize the AI’s knowledge base.
Why “Dream”?
During human sleep, the brain performs critical maintenance:
- NREM sleep replays and consolidates daytime memories, pruning weak connections and strengthening important ones.
- REM sleep recombines memories in novel ways, enabling insight, pattern recognition, and creative problem-solving.
Dream Mode applies these same principles to PiSovereign’s memory and knowledge graph.
Key Capabilities
- Memory consolidation — Merge similar memories, archive redundant ones, deduplicate near-duplicates
- Knowledge graph pruning — Remove weak edges, merge equivalent nodes
- Ebbinghaus decay — Apply enhanced forgetting curves to unreinforced memories
- Cross-domain pattern detection — Discover hidden connections across conversations and topics
- Hypothesis generation — Create testable predictions about user behavior and preferences
- Proactive surfacing — Inject confirmed insights as “Did you know?” context during conversation
- Full audit trail — Dream journal with before/after snapshots of every operation
Architecture
Cycle Model
Each dream session runs N cycles (default: 5). Within each cycle, NREM and REM phases alternate with dynamically allocated budgets:
Session: ─── Cycle 1 ─── Cycle 2 ─── Cycle 3 ─── Cycle 4 ─── Cycle 5 ───
│ │ │ │ │
NREM ████ NREM ███ NREM ██ NREM █ NREM █
REM █ REM ██ REM ███ REM ████ REM ████
- Early cycles favor NREM (consolidation dominates)
- Later cycles favor REM (creative synthesis dominates)
- Budget percentages always sum to 100% per cycle (enforced by property tests)
Service Architecture
┌─────────────────────────────────────────────────────────────┐
│ DreamService (orchestrator) │
│ ├── Idle gate check (IdleDetector) │
│ ├── Session lifecycle (create → run → complete/fail) │
│ ├── Cycle loop with phase dispatch │
│ └── Event publishing (DomainEvent bus) │
│ ├── NremPhaseService │
│ │ ├── consolidate_memories (merge similar) │
│ │ ├── archive_redundant (low-importance cleanup) │
│ │ ├── deduplicate_similar (near-duplicate removal) │
│ │ ├── prune_weak_edges (graph maintenance) │
│ │ └── apply_enhanced_decay (Ebbinghaus curves) │
│ └── RemPhaseService │
│ ├── detect_patterns (cross-domain connections) │
│ ├── generate_hypotheses (testable predictions) │
│ └── generate_suggestions (proactive insights) │
└─────────────────────────────────────────────────────────────┘
Layer Mapping
| Layer | Crate | Components |
|---|---|---|
| Domain | domain | DreamSession, DreamInsight, DreamJournalEntry, DreamSessionId, DreamPhase, DreamSessionStatus, InsightType, InsightStatus, JournalOperation |
| Application | application | DreamService, NremPhaseService, RemPhaseService, DreamJournalPort, DreamStatePort |
| Infrastructure | infrastructure | DreamJournalStore, DreamStateStore, DreamAppConfig |
| Presentation | presentation_http | 14 REST endpoints, MetricsCollector dream metrics |
| Frontend | presentation_web | Dream Mode page, store, API client, types |
Domain Entities
DreamSession
Represents a single dream processing session with a state machine lifecycle:
┌─────────┐
│ Pending │
└────┬─────┘
│ start_dream()
▼
┌─────────┐ pause_dream() ┌──────────┐
│ Running │─────────────────────▶│ Paused │
└────┬─────┘ └────┬─────┘
│ │ resume_dream()
│ │
│◀─────────────────────────────────┘
│
┌────┴─────┐
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│Completed │ │ Failed │
└──────────┘ └──────────┘
Key fields: id (UUID), user_id, status, current_cycle, total_cycles, phase, created_at, started_at, completed_at.
DreamInsight
A discovery produced during REM phases. Types:
| Type | Description | Example |
|---|---|---|
Pattern | Recurring theme across conversations | “User asks about weather every Monday morning” |
Connection | Cross-domain link between topics | “User’s interest in cooking and chemistry share molecular understanding” |
Suggestion | Actionable recommendation | “Consider setting a weekly meal planning reminder” |
Hypothesis | Testable prediction awaiting confirmation | “User prefers concise responses in the evening” |
Hypotheses follow a lifecycle: Active → confirmed/expired (controlled by evidence accumulation and a 30-day TTL).
DreamJournalEntry
Audit trail entry recording every operation within a dream cycle. Each entry includes:
cycle_numberandphase(NREM/REM)operation(one of 12 operations:MemoryConsolidated,MemoryArchived,MemoryDeduplicated,EdgePruned,EdgeCreated,EdgeWeightUpdated,NodeMerged,DecayApplied,PatternDetected,HypothesisGenerated,SuggestionCreated,InsightConfirmed)details(JSON metadata)affected_memory_ids,affected_node_ids,affected_edge_ids- Optional
before_snapshotandafter_snapshotfor diff view
Application Services
DreamService
The top-level orchestrator. Injected with Arc<dyn DreamStatePort>, Arc<dyn DreamJournalPort>, Arc<dyn MemoryStore>, Arc<dyn InferencePort>, and Arc<dyn KnowledgeGraphPort>.
| Method | Description |
|---|---|
start_dream(user_id) | Check idle gate → create session → run cycle loop → complete |
pause_dream(session_id) | Pause an active session (user returned) |
resume_dream(session_id) | Resume a paused session after re-idle window |
cancel_dream(session_id) | Cancel and mark session as failed |
get_status(user_id) | Return current/latest session status |
check_idle_gate(user_id) | Check if user has been idle long enough |
NremPhaseService
Runs declarative memory consolidation within a single NREM cycle:
- Consolidate — Find memory pairs above
merge_threshold, merge into a new memory, archive originals - Archive — Move memories with importance below floor to
Archivedtype - Deduplicate — Remove near-duplicate memories (same-content, different timestamps)
- Prune edges — Review knowledge graph edges below weight threshold via LLM
- Enhanced decay — Apply Ebbinghaus curves with Dream Mode’s own
decay_rate
RemPhaseService
Runs creative synthesis within a single REM cycle:
- Detect patterns — Analyze recent memories (within
pattern_window_days) for recurring themes - Generate hypotheses — Create testable predictions with confidence scores
- Generate suggestions — Produce actionable insights for proactive surfacing
API Reference
All endpoints require authentication. Base path: /v1/dream/.
Session Control
| Method | Path | Description |
|---|---|---|
POST | /trigger | Manually trigger a dream session |
POST | /pause | Pause the active session |
POST | /resume | Resume a paused session |
GET | /status | Get current session status |
Session History
| Method | Path | Description |
|---|---|---|
GET | /sessions | List all sessions (paginated) |
GET | /sessions/{id} | Get a specific session |
GET | /sessions/{id}/journal | Get journal entries for a session |
Insights
| Method | Path | Description |
|---|---|---|
GET | /insights | List all insights (filterable by type/status) |
GET | /insights/{id} | Get a specific insight |
PUT | /insights/{id} | Update an insight |
POST | /insights/{id}/confirm | Confirm a hypothesis |
POST | /insights/{id}/dismiss | Dismiss an insight |
POST | /insights/{id}/merge | Merge an insight into the memory system |
Configuration
| Method | Path | Description |
|---|---|---|
GET | /config | Get current dream configuration |
Example: Trigger a Dream Session
curl -X POST http://localhost:3000/v1/dream/trigger \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-d '{"user_id": "default"}'
Response:
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"status": "running",
"current_cycle": 1,
"total_cycles": 5,
"phase": "nrem",
"created_at": "2025-01-15T00:00:00Z",
"started_at": "2025-01-15T00:00:01Z"
}
Example: List Insights
curl http://localhost:3000/v1/dream/insights?type=hypothesis&status=active \
-H "X-API-Key: your-api-key"
Response:
{
"insights": [
{
"id": "...",
"insight_type": "hypothesis",
"title": "Evening brevity preference",
"content": "User tends to prefer shorter responses after 8 PM",
"confidence": 0.72,
"status": "active",
"evidence_count": 5,
"source_memory_ids": ["..."],
"created_at": "2025-01-15T02:15:00Z"
}
],
"total": 1
}
Configuration Reference
All configuration lives under [dream] in config.toml:
[dream] — Top-level
| Key | Type | Default | Description |
|---|---|---|---|
enabled | bool | true | Master switch for Dream Mode |
schedule | string | "0 0 0 * * *" | 6-field cron expression for dream trigger (default: midnight daily) |
idle_threshold_secs | u64 | 7200 | Seconds of inactivity before a dream session may start (2 hours) |
re_idle_secs | u64 | 1800 | Seconds to wait after user interruption before resuming (30 minutes) |
max_cycles | u8 | 5 | Number of NREM/REM cycles per session |
max_duration_hours | u8 | 6 | Safety cap: maximum hours a dream session can run |
[dream.nrem] — NREM Phase
| Key | Type | Default | Description |
|---|---|---|---|
enabled | bool | true | Enable NREM phases |
merge_threshold | f32 | 0.85 | Cosine similarity threshold for merging/deduplicating |
archive_consolidated | bool | true | Archive source memories after consolidation merge |
max_edge_reviews_per_cycle | usize | 20 | Maximum knowledge graph edges to LLM-review per cycle |
edge_prune_threshold | f32 | 0.2 | Edges below this weight are candidates for pruning |
decay_rate | f32 | 0.95 | Ebbinghaus decay factor for unreinforced memories |
[dream.rem] — REM Phase
| Key | Type | Default | Description |
|---|---|---|---|
enabled | bool | true | Enable REM phases |
pattern_window_days | u8 | 7 | Days to look back for pattern detection |
hypothesis_confidence_threshold | f32 | 0.3 | Minimum confidence to keep a generated hypothesis |
max_node_merges_per_cycle | usize | 10 | Maximum graph node merges per cycle |
proactive_surfacing | bool | true | Enable “Did you know?” injections in conversation |
surfacing_similarity_threshold | f32 | 0.5 | Minimum topic relevance for proactive surfacing |
surfacing_confidence_threshold | f32 | 0.5 | Minimum insight confidence for proactive surfacing |
[dream.journal] — Journal
| Key | Type | Default | Description |
|---|---|---|---|
enabled | bool | true | Enable the dream journal audit trail |
store_before_after_snapshots | bool | true | Store before/after snapshots for diff view in UI |
retention_days | u32 | 90 | Days to retain journal entries before automatic cleanup |
Hypothesis Lifecycle
Hypotheses are the most advanced insight type. They represent testable predictions about user behavior that Dream Mode generates during REM phases.
┌──────────────────┐
│ REM phase │
│ generates │
│ hypothesis │
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Active │ confidence ≥ 0.3
│ (awaiting data) │ evidence_count = 0
└────────┬─────────┘
│
┌────┴────┐
│ │
▼ ▼
┌────────┐ ┌────────────┐
│Evidence│ │ No new │
│arrives │ │ evidence │
│(+conf) │ │ in 30 days │
└───┬────┘ └──────┬─────┘
│ │
▼ ▼
┌────────────┐ ┌──────────┐
│ Confirmed │ │ Expired │
│ (merged │ │ (cleaned │
│ into RAG) │ │ up) │
└────────────┘ └──────────┘
- Generation: REM phase detects a pattern and creates a hypothesis (e.g., “User prefers bullet points after 8 PM”)
- Active: The hypothesis is stored with initial confidence and 0 evidence
- Evidence accumulation: Future conversations matching the hypothesis increase
evidence_countandconfidence - Confirmation: When confidence exceeds the confirmation threshold, the user can confirm via the API, merging the insight into the memory system
- Expiry: Hypotheses without supporting evidence for 30 days are automatically expired
- Dismissal: Users can manually dismiss any hypothesis via the API
Proactive Surfacing
When proactive_surfacing is enabled, confirmed Dream Mode insights are injected into the system prompt during conversations:
- Before each LLM call, confirmed insights are checked for topic relevance (cosine similarity ≥
surfacing_similarity_threshold) - Matching insights with confidence ≥
surfacing_confidence_thresholdare formatted as “Did you know?” context - The LLM naturally incorporates these insights when relevant
Example injection:
[Dream Mode Insight] Did you know? Based on your recent conversations,
you tend to discuss cooking topics on weekends. You might enjoy exploring
molecular gastronomy, which connects your interests in cooking and chemistry.
Monitoring
Dream Mode exposes 10 Prometheus metrics (prefix pisovereign_dream_):
| Metric | Type | Labels | Description |
|---|---|---|---|
sessions_total | Counter | status | Dream sessions by outcome |
cycles_total | Counter | phase | Cycles by phase (NREM/REM) |
memories_consolidated_total | Counter | — | Memories merged |
memories_archived_total | Counter | — | Memories archived |
insights_total | Counter | type | Insights by type |
graph_edges_modified_total | Counter | operation | Edge operations (pruned/created/updated) |
graph_nodes_merged_total | Counter | — | Knowledge graph nodes merged |
llm_calls_total | Counter | — | LLM calls made during dreams |
duration_seconds_total | Counter | — | Total dreaming time |
A pre-built Grafana dashboard is available at grafana/dashboards/dream-mode.json with 18 panels across 4 sections.
See Also
- Memory System — How RAG and memory decay work
- Innovation Features — All 30 research-backed features
- Monitoring — Prometheus and Grafana setup
- Configuration Reference — Full
config.tomlreference