phi-drift / README.md
crexs's picture
sync: update README.md
d0bf3e9 verified
|
Raw
History Blame Contribute Delete
9.99 kB
metadata
title: PHI // DRIFT
emoji: 🧠
colorFrom: red
colorTo: blue
sdk: static
pinned: true
license: other
short_description: Homeostatic cognitive architecture for AI companions

LOCKDOWN NOTICE: This bot and repository have been locked down and secured for security reasons. The source code is under a strict proprietary license. Public access is restricted to read-only viewing for demonstration purposes. Running, cloning, or modifying this codebase is prohibited.

PHI // DRIFT β€” Cognitive Architecture

DRIFT wordmark

License Python 3.12+ CI DOI

PHI // DRIFT (Distributed Response & Integrated Functional Thought) is a homeostatic cognitive architecture with persistent state, salience-weighted memory, and falsifiable behavioral continuity metrics. It gives a language model a persistent inner life: emotion, memory, needs, shadow, consciousness, and distributed cognition β€” all assembled into the prompt on every turn.

πŸ“„ Read the paper β†’

The LLM does not secretly execute arbitrary code. Distinct behavior comes from what is assembled into the prompt, what is retrieved from memory, and what structured state is updated before and after each turn.


Architecture

User Input
    β”‚
    β–Ό
Security Scan ──── blocked? β†’ refusal
    β”‚
    β–Ό
Prompt Assembly (CognitiveOrchestrator)
    β”‚
    β”œβ”€β”€ Being (mood, energy, curiosity, attachment)
    β”œβ”€β”€ Homeostasis (needs: rest, connection, purpose, stimulation)
    β”œβ”€β”€ Shadow (suppressed archetypes, integration level)
    β”œβ”€β”€ Global Workspace (spotlight β†’ active β†’ preconscious β†’ archived)
    β”œβ”€β”€ Hive Mind (consensus threads, council votes)
    β”œβ”€β”€ Memory (semantic + episodic, DMU re-ranked)
    └── Logic Chain (previously-tried approaches)
    β”‚
    β–Ό
LLM Router
    β”œβ”€β”€ Gemini (primary)
    β”œβ”€β”€ Groq / Kimi (cloud fallback)
    └── Ollama (local offline fallback)
    β”‚
    β–Ό
Response + State Update

Layer map

Layer Modules Purpose
Interface interfaces/api.py, interfaces/main.py, interfaces/web_app.py REST API, CLI loop, Web UI
Orchestration core/cognitive_orchestrator.py, core/brain.py Prompt assembly, LLM routing, tool execution
Cognition core/being.py, core/homeostasis.py, core/shadow.py Emotional state, physiological needs, Jungian shadow
Consciousness core/global_workspace.py Tiered attention: spotlight β†’ active β†’ preconscious bands β†’ SQLite archive
Distributed Cognition hive_mind/, core/hive/, core/coordination.py Consensus engine, council of voices, Elysium deliberation
Memory core/memory.py, core/unified_memory.py, core/logic_chain.py ChromaDB semantic recall, episodic store, reasoning traces
Safety core/security_defense.py, core/guardrails.py Input scanning, scope rails, secret scrubbing

Key Subsystems

Global Workspace (Tiered Attention)

Each cycle all active items compete by salience. The winner becomes the spotlight (what the bot is consciously attending to). Runners-up fill the active workspace and feed directly into the prompt. Items below the active threshold are retained in preconscious bands (strong / moderate / faint / trace). Anything below the archive threshold is logged to SQLite and evicted.

Spotlight (rank 1) β†’ most salient item right now
Active (ranks 2–5) β†’ consciously available, included in prompt
Preconscious bands  β†’ retained below threshold, not yet forgotten
Archived            β†’ logged to SQLite, evicted from memory

Hive Mind (Distributed Cognition)

A lightweight consensus engine for multi-voice deliberation. Nodes propose thoughts, cast votes, and resolve threads. Safety vetoes are hardwired β€” any proposal touching backdoors or guardrail bypasses is immediately TABLED.

# What happens when you /hive propose ...
engine.propose(msg)                          # open a thread
engine.vote(thread_id, "lantern-4", "BLOCK") # safety node votes
engine.resolve(thread_id, Resolution.TABLED) # thread closed

The Elysium engine (in core/hive/) runs deeper async deliberations with a persistent Nexus self-model and 7 council voices (Aura, Logic, Meme, Vibe, Ethos, Pulse, Nexus).

Shadow (Jungian Integration)

Suppressed archetypes accumulate depth over time. High-stress turns can surface them into conscious awareness. The bot can run active imagination dialogues to integrate shadow content. Unintegrated archetypes influence tone through format_prompt_snippet.

Homeostasis

Five tracked needs (rest, connection, purpose, stimulation, safety) decay over time and create pressure on the bot's behavior. Allostatic load and a crisis_mode flag affect response tone. Decay rates are configurable via env vars.


Getting Started

1. Clone

git clone https://github.com/timeless-hayoka/infj-bot.git
cd infj-bot

2. Install

python3.12 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install -e .

Torch (~2 GB) is required for local embeddings and the full server. On CPU-only machines:

pip install torch --index-url https://download.pytorch.org/whl/cpu

3. Configure

cp .env.example .env
# Add your keys:
#   API_KEY=your_gemini_key        (primary LLM)
#   GROQ_API_KEY=your_groq_key     (fallback)
#   KIMI_API_KEY=your_kimi_key     (fallback)

4. Run

# CLI chat loop
python interfaces/main.py

# REST API  β†’  http://127.0.0.1:8765
uvicorn infj_bot.interfaces.api:app --host 127.0.0.1 --port 8765 --reload

# Web UI  β†’  http://127.0.0.1:5000
python interfaces/web_app.py

Commands

Command What it does
/mode companion|engineer|critic|coach|clarity|researcher|bughunter|quiet|drift Switch persona mode
/memory <query> Search long-term memory
/memory learn <name>: <desc> Store a concept
/hive Show Hive Mind status and active consensus threads
/hive propose <thought> Submit a thought for collective review
/hive nexus decide <goal> Run Elysium council deliberation on a goal
/hive reflect Trigger a council reflection
/hive council status Show each council voice's energy and win count
/workspace status Show the conscious attention workspace
/workspace focus <content> Move spotlight to a specific item
/workspace reflect Generate a metacognitive reflection
/chain list Show active reasoning chains
/chain mark <query> fail Mark an approach as dead-end
/security status Show security scanner state
/security test <text> Scan arbitrary text
/health Check model, memory, and system status
/reset Clear session history and brain context
/todo add <title> Add a goal

API Endpoints

Endpoint Method Description
/api/health GET System health, memory count, turn count
/api/chat POST Single-turn chat
/api/chat/stream POST Server-sent events streaming
/api/tools GET Available tool inventory
/api/observer GET Full real-time cognitive state (being, needs, shadow, workspace, DII)
/api/dii GET Dynamic Integration Index trend
/api/phi GET PHI council status and subjective state
/api/hive GET Hive Mind status
/api/command POST Execute a slash command

Tests

# Full suite (requires torch)
pytest tests/ -q

# Without torch
pytest tests/ -q \
  --ignore=tests/test_bot.py \
  --ignore=tests/test_stress.py \
  --ignore=tests/test_upgrade_infrastructure.py

# Specific suites
pytest tests/test_shadow.py tests/test_elysium.py tests/test_temporal.py -v

CI checks: lint (ruff), typecheck (mypy), test (pytest) β€” all green on every push.


Ablation Results (May 2026)

6-condition test measuring the impact of removing each subsystem. Run on live Ollama qwen3:4b (CPU).

Condition Change Finding
A β€” No Council Elysium stubbed Latency neutral β€” council is background-only
B β€” No Shadow Shadow tick disabled Latency neutral β€” shadow operates via cache
C β€” No Homeostasis Needs flattened Latency neutral β€” state still initialized
D β€” Cosine-only RAG DMU re-ranking removed Prompt ↓ 221 chars (7.7%) β€” DMU injects meaningful context
E β€” Local LLM only Cloud providers off Baseline latency
F β€” Full stack No changes 3095-char avg prompt, 62.9s latency

Removing DMU re-ranking (D) is the most measurable signal β€” the 221-character gap is the difference between simple cosine top-N and salience-weighted dynamic recall.

Re-run: python tests/ablation_suite.py --conditions A,B,C,D,E,F --prompts 50 --live


Citation

PHI // DRIFT: A Homeostatic Cognitive Architecture for Persistent, State-Aware AI Companionship

Zenodo: https://doi.org/10.5281/zenodo.20350249 PDF: DRIFT_paper_v4.pdf


License

Apache 2.0 β€” see LICENSE.