Skip to content

A 3-layer memory-powered agent system: Lifeline UI → EchoForge decision/memory API → Continuity self-evolving core, built on MemMachine + Neo4j graph reasoning.

Notifications You must be signed in to change notification settings

wildhash/continuity-stack

Repository files navigation

Continuity Stack

A 3-layer memory-powered agent system demonstrating self-reflection and learning capabilities.

Lifeline UI (Next.js) → EchoForge API (FastAPI) → Continuity Core (Self-evolving agent)

Built with MemMachine (persistent memory) + Neo4j (knowledge graph) for Identity, Decisions, and Agent Version tracking.

⚡ NEW: AGI Runtime Mode

Continuity now includes an optional AGI Runtime - a structured, auditable, and measurable agent execution system:

export CONTINUITY_AGI_RUNTIME=1  # Enable AGI Runtime

AGI Runtime Features:

  • 🔗 Hash-Chained Cycles: Tamper-evident append-only audit log
  • 🛡️ Safety Gates: Tool allowlisting, injection detection, tripwires
  • 📊 Eval Harness: Automated quality scoring per cycle
  • 🧠 3-Tier Memory: Episodic, semantic, and procedural memory
  • 🌍 World Model: Lightweight belief state tracking
  • Deterministic Mode: Fully functional without API keys

See: docs/agi_runtime.md for complete documentation.

🎯 Demo Highlights

This full-stack demo showcases a production-ready self-evolving agent system:

  1. Agent fails on a task it hasn't encountered before
  2. Agent reflects on the failure using LLM or deterministic analysis
  3. Agent stores lesson in both MemMachine (persistent memory) and Neo4j (knowledge graph)
  4. Agent evolves by gaining new capabilities and incrementing version
  5. Agent succeeds when retrying the same task, citing learned knowledge

Key Features

Self-Reflection Loop: Think → Act → Observe → Reflect → Store → Evolve
Deterministic Fallback: Works without OpenAI API (demo mode)
Multi-Layer Storage: MemMachine + Neo4j for redundancy
Version Control: Each learning event increments agent version
Knowledge Citation: Agent explicitly cites recalled lessons
Graph Reasoning: Cypher queries for complex relationship analysis
Audit Trail: Every decision tracked with full context

Demo Time: 2-4 minutes | See: DEMO_SCRIPT.md

🏗️ Architecture

Three-Layer System

┌─────────────────────────────────────────┐
│         Lifeline UI (Next.js)           │
│  - Chat Interface                       │
│  - Profile Timeline                     │
│  - Demo Scenario Runner                 │
└─────────────────┬───────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────┐
│       EchoForge API (FastAPI)           │
│  - Team Memory Layer                    │
│  - Decision Tracking                    │
│  - Agent State Management               │
└────┬──────────────────────┬─────────────┘
     │                      │
     ▼                      ▼
┌──────────────┐   ┌─────────────────────┐
│  MemMachine  │   │   Continuity Core   │
│  (Persistent │   │  (Self-reflecting   │
│   Memory)    │   │    Agent Loop)      │
└──────────────┘   └──────────┬──────────┘
                              │
                              ▼
                   ┌──────────────────────┐
                   │   Neo4j Knowledge    │
                   │       Graph          │
                   │  - Identities        │
                   │  - Decisions         │
                   │  - Agent Versions    │
                   │  - Learned Lessons   │
                   └──────────────────────┘

🚀 Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local frontend development)
  • Python 3.11+ (for local backend development)

Installation & Setup

  1. Clone the repository:

    git clone https://github.com/wildhash/continuity-stack.git
    cd continuity-stack
  2. Start the entire stack with Docker Compose:

    docker-compose up --build

    This will start:

    • Neo4j database (ports 7474, 7687)
    • FastAPI backend (port 8000)
    • Next.js frontend (port 3000)
  3. Access the interfaces:

Alternative: Local Development

Backend (FastAPI)

cd backend
pip install -r requirements.txt

# Start Neo4j first (or use docker-compose up neo4j)
# Then run the backend
uvicorn main:app --reload --port 8000

Frontend (Next.js)

cd frontend
npm install
npm run dev

📖 Usage Guide

Quick Demo (Automated)

The fastest way to see the agent in action:

# Start all services
./start.sh

# Wait 30 seconds for Neo4j to initialize
# Then run the automated demo
./run-demo.sh

This runs the complete fail → reflect → learn → succeed cycle and shows:

  • ❌ First attempt fails (missing capability)
  • 🧠 Agent reflects and learns a lesson
  • ✨ Agent gains new capability
  • 📈 Agent version increments (1.0.0 → 1.0.1)
  • ✅ Second attempt succeeds (using learned capability)

Output URLs:

Running the Demo Scenario

  1. Open Lifeline UI at http://localhost:3000
  2. Navigate to the "Demo Scenario" tab
  3. Click "Run Demo Scenario"
  4. Watch the execution log showing:
    • Initial task failure
    • Reflection and lesson learning
    • Capability acquisition
    • Graph database update
    • Successful retry

Using the Chat Interface

Try these commands in the chat:

  • "Execute a validation task" - Run a task that demonstrates learning
  • "Show me your status" - View agent capabilities and stats
  • "What have you learned?" - See all learned lessons
  • "Show me your history" - View task execution history

Viewing the Profile Timeline

The Profile & Timeline tab shows:

  • Current agent version and statistics
  • Chronological timeline of all events
  • Tasks executed (success/failure)
  • Reflections and learned lessons
  • Acquired capabilities

🔌 API Endpoints

Agent & Tasks

  • POST /api/tasks/execute - Execute a task through the agent (returns steps, citations, graph_summary)
  • GET /api/agent/status - Get current agent status and capabilities
  • GET /api/agent/history - Get task execution history
  • GET /api/agent/reflections - Get all reflections

Memory (MemMachine)

  • POST /api/memory/store - Store a memory (old interface)
  • POST /api/memory/write - Write memory (new client interface)
  • POST /api/memory/search - Search memories by text query
  • GET /api/memory/list - List memories with filtering
  • GET /api/memory/summary - Get memory statistics

Graph Operations (Neo4j)

  • POST /api/graph/upsert_identity_event - Create/update identity event
  • POST /api/graph/log_decision - Log a decision in a run
  • POST /api/graph/log_lesson - Log a lesson from an outcome
  • GET /api/graph/insights - Get comprehensive learning analytics
  • GET /api/graph/timeline - Get timeline of all events
  • GET /api/graph/version-evolution - Get agent version evolution chain
  • GET /api/graph/decision-impact/{id} - Analyze decision impact

Decisions (Neo4j)

  • POST /api/decisions/create - Create a decision record
  • GET /api/decisions/list - List decisions
  • PUT /api/decisions/{id}/status - Update decision status

Graph Analysis

  • GET /api/graph/version-evolution - Get agent evolution chain
  • GET /api/graph/decision-impact/{id} - Analyze decision impact

Demo

  • POST /api/demo/run-scenario - Run the complete demo scenario

🧪 Testing

Backend Tests

cd backend
pytest test_continuity_core.py -v
pytest test_memmachine.py -v

Running All Tests

cd backend
pytest -v

🗄️ Data Storage

MemMachine

File-based persistent storage in ./memmachine_data/:

  • memories.json - All stored memories
  • decisions.json - Decision records
  • agent_state.json - Agent state history

Neo4j Graph Database

Graph data stored in ./neo4j_data/ with:

Node Types:

  • Identity - System identities (users, agents)
  • Decision - Decisions made in the system
  • AgentVersion - Different versions of the agent
  • Lesson - Learned lessons

Relationship Types:

  • MADE - Identity made a Decision
  • LEARNED - AgentVersion learned a Lesson
  • FROM_DECISION - Lesson came from a Decision
  • EVOLVED_TO - AgentVersion evolved to another version

📊 Key Cypher Queries

View All Agent Versions and Evolution

MATCH (a:AgentVersion)
OPTIONAL MATCH (a)-[:EVOLVED_TO]->(next:AgentVersion)
RETURN a, next
ORDER BY a.created_at

See Lessons Learned

MATCH (a:AgentVersion)-[:LEARNED]->(l:Lesson)
RETURN a.version as version, collect(l.content) as lessons

Decision Impact Analysis

MATCH (d:Decision)<-[:FROM_DECISION]-(l:Lesson)<-[:LEARNED]-(a:AgentVersion)
RETURN d.title as decision, 
       collect(DISTINCT a.version) as affected_versions,
       collect(l.content) as lessons

Identity Influence

MATCH (i:Identity)-[:MADE]->(d:Decision)
OPTIONAL MATCH (d)<-[:FROM_DECISION]-(l:Lesson)
RETURN i.name as identity,
       count(DISTINCT d) as decisions,
       count(DISTINCT l) as lessons_generated

🛠️ Technology Stack

Backend

  • FastAPI - Modern Python web framework
  • Neo4j - Graph database for knowledge representation
  • Pydantic - Data validation
  • Uvicorn - ASGI server

Frontend

  • Next.js 14 - React framework
  • TypeScript - Type-safe JavaScript
  • Tailwind CSS - Utility-first CSS
  • Axios - HTTP client

Infrastructure

  • Docker & Docker Compose - Containerization
  • Neo4j 5.13 - Graph database

🔧 Configuration

Environment Variables

Backend (Required)

# Neo4j Configuration
NEO4J_URI=bolt://localhost:7687
NEO4J_USER=neo4j
NEO4J_PASSWORD=continuity123

# MemMachine Mode (choose one)
# Option 1: Local file-based storage (default)
LOCAL_FAKE_MEMORY=1
MEMMACHINE_PATH=./memmachine_data

# Option 2: External MemMachine API
# MEMMACHINE_API_KEY=your_api_key
# MEMMACHINE_BASE_URL=https://api.memmachine.ai
# MEMMACHINE_NAMESPACE=continuity-stack-demo

Backend (Optional - LLM Integration)

# LLM Provider (uses deterministic mode if not set)
OPENAI_API_KEY=sk-your-openai-api-key
LLM_MODEL=gpt-4  # or gpt-3.5-turbo

Backend (Optional - AGI Runtime)

# Enable AGI Runtime mode (default: off)
CONTINUITY_AGI_RUNTIME=1

# AGI Runtime environment (affects safety gates)
# Options: production, staging, development
AGI_ENVIRONMENT=production  # default

# AGI Runtime uses existing MemMachine and Neo4j configs

AGI Runtime Behavior:

  • When CONTINUITY_AGI_RUNTIME=0 (default): Uses legacy continuity_core.py
  • When CONTINUITY_AGI_RUNTIME=1: Uses new structured AGI runtime with:
    • Append-only cycle logs in runs/agi_runtime/YYYY-MM-DD/cycles.jsonl
    • SHA-256 hash chains for tamper detection
    • Safety gates and eval harness
    • Three-tier memory system

See: docs/agi_runtime.md for full details.

Frontend

# API URL
NEXT_PUBLIC_API_URL=http://localhost:8000

Important: Copy .env.example to .env in each directory and customize as needed.

cp .env.example .env
cp backend/.env.example backend/.env
cp frontend/.env.example frontend/.env

🐛 Troubleshooting

Neo4j Connection Issues

If you see "Neo4j not available" errors:

  1. Check Neo4j is running: docker-compose ps
  2. Wait for Neo4j to fully start (can take 30-60 seconds)
  3. Verify connection at http://localhost:7474

Backend Not Starting

# Check logs
docker-compose logs backend

# Restart backend
docker-compose restart backend

Frontend Build Issues

cd frontend
rm -rf node_modules .next
npm install
npm run dev

📝 Seed Data

The system initializes with:

  • Default agent_system identity
  • Initial agent version 1.0.0 with basic capabilities
  • Empty knowledge graph ready for learning

🎓 Learning Flow Example

1. User: "Execute a validation task"
   └─> Agent attempts task without validation capability
       └─> FAILS with "Missing capability: handle_validation_task"

2. Agent reflects on failure
   └─> Analyzes error: validation required
       └─> Learns: "Input validation is required before processing"
           └─> Gains capability: handle_validation_task

3. Agent stores in graph
   └─> Creates Lesson node
       └─> Links to AgentVersion
           └─> Records in MemMachine

4. User: "Execute a validation task" (retry)
   └─> Agent has capability
       └─> SUCCESS ✓

🤝 Contributing

This is a demonstration project showing self-evolving agent architecture. Feel free to:

  • Extend the learning capabilities
  • Add more sophisticated reflection logic
  • Implement additional graph queries
  • Enhance the UI with more visualizations

📄 License

MIT License - see LICENSE file for details

🙏 Acknowledgments

Built to demonstrate:

  • Self-reflecting AI agents
  • Knowledge graph reasoning
  • Persistent memory systems
  • Full-stack AI application architecture

About

A 3-layer memory-powered agent system: Lifeline UI → EchoForge decision/memory API → Continuity self-evolving core, built on MemMachine + Neo4j graph reasoning.

Resources

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •