Overview
Junkie implements a sophisticated context management system that:- Caches Discord messages in PostgreSQL
- Builds context-aware prompts with recent conversation history
- Handles message edits and deletions
- Backfills historical messages on startup
- Formats timestamps with relative time indicators
Architecture
Database Schema
Messages are stored with optimized indexing:database.py:36-62
Index Strategy:
idx_messages_channel_createduses DESC order for fast “latest N messages” queriesmessage_idprimary key for fast upserts
Message Retrieval
Two-Tier Strategy
context_cache.py:83-110
Advantages:
- Fast - PostgreSQL is much faster than Discord API
- Persistent - Survives bot restarts
- Reliable - No API rate limits for cached data
Database Query
database.py:106-126
Query Optimization:
- Fetch with
ORDER BY created_at DESCfor index efficiency - Reverse results to chronological order for display
- Uses connection pool for performance
Message Storage
Upsert Strategy
database.py:66-90
ON CONFLICT handles:
- New messages → INSERT
- Edited messages → UPDATE content
Real-time Updates
chat_handler.py:105-213
Timestamp Formatting
Relative Time Display
context_cache.py:43-76
Examples:
[just now]- Less than 1 minute[5m ago]- 5 minutes ago[2h ago]- 2 hours ago[3d ago]- 3 days ago[Jan 15, 14:30]- More than 7 days
Timezone Support
context_cache.py:31-60
Context Prompt Building
Format
context_cache.py:245-308
Example Output
Backfill System
On bot startup, historical messages are backfilled:chat_handler.py:53-95
Backfill Strategy
- Identify gaps - Check if channel is fully backfilled
- Fetch from API - Paginate through Discord history
- Store in DB - Upsert messages
- Mark complete - Update
channel_statustable
Channel Status Tracking
database.py:176-203
API Fetch and Cache
context_cache.py:149-238
Features:
- Includes messages with content, attachments, or embeds
- 20% buffer over requested limit
- Capped at
BACKFILL_MAX_FETCH_LIMIT(default: 1000) - Handles pagination with
afterandbefore
Configuration
CACHE_TTL- Cache time-to-live (unused in PostgreSQL mode)CONTEXT_AGENT_MAX_MESSAGES- Max messages in contextTEAM_LEADER_CONTEXT_LIMIT- Context limit for team leaderDISCORD_TIMEZONE- Timezone for timestamps (default: Asia/Kolkata)MESSAGE_SYNC_LIMIT- Messages to sync on startup (default: 200)BACKFILL_MAX_FETCH_LIMIT- Max messages per backfill fetch (default: 1000)