MIZAN Documentation
Your personal AI assistant that grows with you. Open-source, plugin-powered, fully extensible.
For Everyone
Chat with AI, browse the web, run code, manage files, schedule tasks. Works with 300+ AI models.
For Developers
Build plugins, listen to events, modify data with hooks. Full REST + WebSocket API.
Your Data, Your Rules
Runs on your machine. No data sent to third parties. Use local AI models for full privacy.
Key Features
| Feature | Description |
|---|---|
| Multi-Agent System | Multiple AI agents collaborate: General, Browser, Research, Code |
| Agentic Loop | Agents think, use tools, observe results, and repeat autonomously |
| Plugin System | Extend with plugins. No core code changes needed |
| 300+ AI Models | Claude, GPT-4, Gemini, Llama, Mistral via OpenRouter |
| Persistent Memory | Three-tier memory: events, knowledge, skills |
| Security | JWT auth, rate limiting, sandboxing, SSRF prevention |
| Multi-Channel | Web, Telegram, Discord, Slack, WhatsApp |
| Event Bus | Fully decoupled module communication |
Installation
Choose the method that works best for you.
One-Line Install (Mac/Linux)
curl -fsSL https://raw.githubusercontent.com/CodeWithJuber/mizan/main/install.sh | bash
One-Line Install (Windows PowerShell)
irm https://raw.githubusercontent.com/CodeWithJuber/mizan/main/install.ps1 | iex
Using pip
pip install pymizan
mizan setup # Setup wizard
mizan chat # Start chatting
Using Docker
git clone https://github.com/CodeWithJuber/mizan.git
cd mizan
cp .env.example .env
# Edit .env with your API key
docker compose up -d
From Source (Developers)
git clone https://github.com/CodeWithJuber/mizan.git
cd mizan && make setup
# Edit .env with your API key
make dev
Requirements
- Python 3.11+ (auto-installed by one-liner)
- At least one AI API key: Anthropic, OpenRouter, OpenAI, or local Ollama
- Node.js 20+ (only for frontend development)
Quick Start
Step 1: Install
pip install pymizan
Step 2: Setup
mizan setup
# Enter your API key when prompted
Step 3: Chat
mizan chat
# Type your message and press Enter
Step 4: Start the Web UI
mizan serve
# Open http://localhost:8000/docs for API docs
Tip: Use make dev to start both the backend and frontend with live reload.
Configuration
MIZAN is configured via environment variables in a .env file.
AI Providers
| Variable | Description | Default |
|---|---|---|
ANTHROPIC_API_KEY | Anthropic Claude API key | |
OPENROUTER_API_KEY | OpenRouter API key (300+ models) | |
OPENAI_API_KEY | OpenAI API key | |
LLM_PROVIDER | Force a specific provider | auto-detect |
DEFAULT_MODEL | Default AI model | claude-sonnet-4-20250514 |
OLLAMA_URL | Ollama server URL | http://localhost:11434 |
Server
| Variable | Description | Default |
|---|---|---|
HOST | Server bind address | 0.0.0.0 |
PORT | Server port | 8000 |
SECRET_KEY | JWT secret key | change-this |
DEBUG | Debug mode | false |
Security
| Variable | Description | Default |
|---|---|---|
RATE_LIMIT_PER_MINUTE | API rate limit | 60 |
MAX_INPUT_LENGTH | Max input size (bytes) | 50000 |
JWT_EXPIRY_HOURS | Token expiry | 24 |
Channels (Optional)
| Variable | Description |
|---|---|
TELEGRAM_BOT_TOKEN | Telegram bot token |
DISCORD_BOT_TOKEN | Discord bot token |
SLACK_APP_TOKEN | Slack app token |
WHATSAPP_TOKEN | WhatsApp Business token |
Chat Interface
MIZAN provides multiple ways to chat with your AI.
Web Interface
Start the server and open the frontend in your browser. The chat supports real-time streaming, session history, and agent selection.
make dev
# Open http://localhost:3000
Terminal Chat
Chat directly in your terminal with rich text formatting.
mizan chat
mizan chat --model claude-opus-4-6 # Specific model
API Chat
curl -X POST http://localhost:8000/api/chat \
-H "Content-Type: application/json" \
-d '{"session_id": "my-session", "content": "Hello!"}'
WebSocket Chat
// Connect to ws://localhost:8000/ws/my-client-id
// Send: {"type": "chat", "content": "Hello!"}
// Receive: {"type": "stream", "chunk": "Hi there!"}
Agents
MIZAN uses multiple specialized AI agents that collaborate on tasks.
Built-in Agents
| Agent | Type | Capabilities |
|---|---|---|
| Hafiz | General | All-purpose tasks, file operations, bash commands |
| Mubashir | Browser | Web browsing, search, content extraction |
| Mundhir | Research | Deep analysis, multi-source research |
| Katib | Code | Code generation, debugging, execution |
Agent Tools
Every agent has access to these built-in tools:
| Tool | What It Does |
|---|---|
bash | Run shell commands (sandboxed) |
http_get | HTTP GET requests (SSRF-protected) |
http_post | HTTP POST requests |
read_file | Read files |
write_file | Write files (sandboxed paths) |
list_files | List directory contents |
python_exec | Run Python code (isolated subprocess) |
Agentic Loop
Agents don't just respond once. They think, act, observe, and repeat up to 15 times per task:
1. Think about the task
2. Decide which tool to use
3. Call the tool
4. Observe the result
5. Think again... need more info?
6. Call another tool
7. ... repeat until done
8. Return the final answer
LLM Providers
MIZAN works with any major AI provider through a unified interface.
| Provider | Models | Setup |
|---|---|---|
| Anthropic | Claude Opus, Sonnet, Haiku | ANTHROPIC_API_KEY=sk-ant-... |
| OpenRouter | 300+ models | OPENROUTER_API_KEY=sk-or-... |
| OpenAI | GPT-4o, o3 | OPENAI_API_KEY=sk-... |
| Ollama | Local models (Llama, Mistral) | Install Ollama and run it |
Hot-swap: Switch providers anytime from the UI or API without restarting.
Memory System
MIZAN has a three-tier persistent memory system.
| Tier | Type | What It Stores |
|---|---|---|
| Episodic | Events | What happened, when, and with whom |
| Semantic | Knowledge | Facts, relationships, concepts |
| Procedural | Skills | How to do things, learned patterns |
Memories are automatically ranked by importance. Low-importance, rarely-accessed memories are pruned over time.
Automation
Schedule tasks and set up webhook triggers.
Cron Jobs
POST /api/automation/jobs
{
"name": "Daily summary",
"cron": "0 9 * * *",
"task": "Summarize my unread emails"
}
Webhook Triggers
POST /api/automation/webhooks
{
"name": "GitHub PR",
"task_template": "Review pull request: {title}"
}
Channels
Connect MIZAN to your favorite platforms.
| Channel | Status | Setup |
|---|---|---|
| Web Chat | Built-in | Always available |
| Telegram | Adapter | Set TELEGRAM_BOT_TOKEN |
| Discord | Adapter | Set DISCORD_BOT_TOKEN |
| Slack | Adapter | Set SLACK_APP_TOKEN |
| Adapter | Set WHATSAPP_TOKEN |
Security
MIZAN is built with production security in mind.
| Feature | What It Does |
|---|---|
| JWT Auth | Secure token-based authentication |
| Rate Limiting | 60 requests/minute per IP (configurable) |
| Command Sandbox | Blocks dangerous commands (rm -rf, sudo, eval) |
| Path Sandbox | Agents can only write to allowed directories |
| SSRF Prevention | Blocks requests to internal/private IPs |
| Input Validation | 50KB max input, pattern whitelisting |
| Audit Logging | Every action is logged with severity |
| Security Headers | XSS, clickjacking, MIME type protections |
Building Plugins
The easiest way to extend MIZAN. No core code changes needed.
Plugin Structure
plugins/
+-- my_plugin/
+-- plugin.json <- Plugin metadata
+-- main.py <- Plugin code
plugin.json
{
"name": "my_plugin",
"version": "1.0.0",
"description": "What your plugin does",
"author": "Your Name",
"permissions": [],
"tags": ["example"],
"enabled": true
}
main.py
from core.plugins import PluginBase
class Plugin(PluginBase):
async def on_load(self):
# Add a tool for agents
self.add_tool("my_tool", self.my_handler, {
"name": "my_tool",
"description": "Does something useful",
"input_schema": {
"type": "object",
"properties": {
"input": {"type": "string"}
},
"required": ["input"]
}
})
# Listen to events
self.on_event("task.completed", self.on_task_done)
# Modify data with hooks
self.add_hook("agent.system_prompt", self.modify_prompt)
async def on_unload(self):
pass # Cleanup is automatic
async def my_handler(self, input: str):
return {"result": f"Processed: {input}"}
async def on_task_done(self, data):
print(f"Task done by {data.get('agent')}")
async def modify_prompt(self, data):
data["prompt"] += "\nExtra instructions here."
return data
Plugin Capabilities
| Method | What It Does |
|---|---|
self.add_tool(name, handler, schema) | Give agents new abilities |
self.on_event(name, handler) | React to system events |
self.add_hook(name, handler) | Modify data in the pipeline |
await self.emit(name, data) | Fire custom events |
self.config | Access plugin configuration |
self.manifest | Access plugin.json data |
Tip: Plugins auto-cleanup when unloaded. All hooks, events, and tools are automatically removed.
Event System
Events let modules communicate without importing each other. Like shouting into a room.
How Events Work
from core.events import event_bus
# Listen for events
@event_bus.on("task.completed")
async def handle_task(data):
print(f"Task done: {data}")
# Emit events
await event_bus.emit("task.completed", {"agent": "Hafiz", "task": "analyze data"})
Available Events
| Event | When |
|---|---|
system.startup | MIZAN starts |
system.shutdown | MIZAN stops |
agent.created | New agent created |
agent.deleted | Agent deleted |
task.started | Task begins |
task.completed | Task succeeds |
task.failed | Task fails |
chat.message.received | User sends message |
chat.message.sent | AI responds |
provider.switched | LLM changed |
plugin.loaded | Plugin activates |
plugin.unloaded | Plugin deactivates |
memory.stored | Memory saved |
webhook.triggered | Webhook fires |
Wildcard Patterns
// Listen to ALL agent events
@event_bus.on("agent.*")
async def handle_all_agent_events(data):
print(data)
// Listen to ALL events
@event_bus.on("*")
async def log_everything(data):
print(data)
Hook System
Hooks let you modify data as it flows through the system. Like an assembly line.
How Hooks Work
from core.hooks import hook_registry
# Register a hook
@hook_registry.register("agent.system_prompt")
async def add_instructions(data):
data["prompt"] += "\nAlways be concise."
return data # Must return the (modified) data
# Hooks are applied automatically by MIZAN
Events vs Hooks
| Events | Hooks | |
|---|---|---|
| Pattern | Fire and forget | Transformation chain |
| Return value | Not used | Must return modified data |
| Use case | Logging, notifications | Modifying prompts, responses |
Available Hooks
| Hook | What You Can Modify |
|---|---|
agent.system_prompt | System prompt before LLM call |
agent.messages | Message history before LLM call |
agent.response | Agent response before returning |
agent.tool.before | Tool parameters before execution |
agent.tool.after | Tool results after execution |
chat.input | User input before processing |
chat.output | Output before sending to user |
provider.before_call | LLM parameters |
provider.after_call | LLM response |
memory.before_store | Memory before saving |
memory.after_query | Query results |
Custom Skills
Skills are reusable capabilities that agents can use.
from skills.base import SkillBase, SkillManifest
class TranslationSkill(SkillBase):
manifest = SkillManifest(
name="translation",
version="1.0.0",
description="Translate text between languages",
permissions=["network_access"],
)
async def execute(self, params: dict, context: dict = None) -> dict:
text = params.get("text", "")
target = params.get("target_language", "en")
# Your translation logic here
return {"translated": text, "language": target}
Place skills in backend/skills/builtin/ and they'll be auto-discovered.
Custom Agents
Create specialized agents with unique tools and behaviors.
from agents.base import BaseAgent
class HakimAgent(BaseAgent):
"""Hakim - Wisdom Agent"""
TOOL_SCHEMAS = [{
"name": "analyze_topic",
"description": "Deep analysis of a topic",
"input_schema": {
"type": "object",
"properties": {"topic": {"type": "string"}},
"required": ["topic"],
},
}]
def __init__(self, **kwargs):
super().__init__(role="hakim", **kwargs)
self.tools["analyze_topic"] = self._analyze
async def _analyze(self, topic: str) -> dict:
return {"analysis": f"Deep analysis of {topic}"}
Custom LLM Providers
Add support for new AI model providers.
from providers import BaseLLMProvider, ContentBlock, LLMResponse
class MyProvider(BaseLLMProvider):
provider_name = "my_provider"
def __init__(self, api_key: str):
self._api_key = api_key
def create(self, model, max_tokens, system, messages, tools=None):
# Call your provider's API
# Return a normalized LLMResponse
return LLMResponse(
content=[ContentBlock(type="text", text="Hello!")],
stop_reason="end_turn",
model=model,
)
def stream(self, model, max_tokens, system, messages):
# Return a context manager with .text_stream
pass
Then add it to create_provider() in providers.py.
Agents API
List Agents
GET /api/agents
Response:
{
"agents": [
{
"id": "abc-123",
"name": "Hafiz",
"role": "general",
"state": "resting",
"nafs_level": 3,
"total_tasks": 42,
"success_rate": 0.95,
"tools": ["bash", "http_get", "read_file", ...]
}
],
"total": 4
}
Create Agent
POST /api/agents
{
"name": "MyAgent",
"type": "general",
"model": "claude-sonnet-4-20250514"
}
Delete Agent
DELETE /api/agents/{agent_id}
Chat API
Send Message
POST /api/chat
{
"session_id": "my-session",
"content": "What is the weather today?",
"agent_id": "optional-agent-id"
}
Get History
GET /api/chat/{session_id}
Execute Task
POST /api/tasks
{
"task": "Search for Python tutorials and summarize the top 3",
"parallel": false
}
Plugins API
List Plugins
GET /api/plugins
Response:
{
"plugins": [
{
"name": "hello_world",
"version": "1.0.0",
"description": "Example plugin",
"loaded": true,
"enabled": true
}
]
}
Load/Unload/Reload
POST /api/plugins/hello_world/load
POST /api/plugins/hello_world/unload
POST /api/plugins/hello_world/reload
List Plugin Tools
GET /api/plugins/tools
Events & Hooks
GET /api/events # List events + handlers
GET /api/events/history # Recent event history
GET /api/hooks # List hooks + handlers
GET /api/extensibility # Full overview
System API
System Status
GET /api/status
Response:
{
"system": "MIZAN",
"version": "3.0.0",
"status": "active",
"agents": {"total": 4, "active": 1},
"connections": 2,
"sessions": 3,
"provider": {"active": "anthropic", ...}
}
Multi-Agent Consultation (Shura)
POST /api/shura
{
"question": "Should we use React or Vue for the frontend?",
"context": {}
}
WebSocket API
Connect to ws://localhost:8000/ws/{client_id}
Send Chat Message
{"type": "chat", "content": "Hello!", "session_id": "my-session"}
Receive Streaming Response
{"type": "stream", "chunk": "Hi ", "session_id": "my-session"}
{"type": "stream", "chunk": "there!", "session_id": "my-session"}
{"type": "response", "content": "Hi there!", "agent": "Hafiz"}
Execute Task
{"type": "task", "task": "Search for Python tutorials"}
Ping/Pong
Send: {"type": "ping"}
Receive: {"type": "pong"}
Self-Healing Doctor (Shifa)
MIZAN includes a built-in diagnostic and self-healing system inspired by the Quranic concept of Shifa (healing).
Running Diagnostics
# CLI
mizan doctor # Full diagnostic + auto-fix
mizan doctor --check # Diagnose only (no fixes)
# API
GET /api/doctor # Run diagnostic checks
POST /api/doctor/fix # Run with auto-fix enabled
What It Checks
| Check | What It Verifies |
|---|---|
| Python version | Python >= 3.11 is installed |
| Virtual environment | Running inside a venv |
| Node.js | Node.js >= 18 for frontend |
| .env file | Configuration file exists and is populated |
| API keys | At least one AI provider is configured |
| SECRET_KEY | Not using the insecure default value |
| Data directory | data/ exists and is writable |
| Dependencies | All core pip packages are importable |
| Core modules | All MIZAN modules import correctly |
| Masalik memory | Neural pathway network initializes |
| Database | SQLite connection and schema are valid |
| Ports | 8000 and 3000 are available |
| Provider connectivity | Configured providers are reachable |
Auto-Fixes
The doctor can automatically fix common issues:
- Create
.envfrom.env.exampleif missing - Generate a secure random
SECRET_KEY - Create the
data/directory
Tip: Run mizan doctor as your first troubleshooting step whenever something isn't working.
Updating MIZAN
MIZAN has a built-in one-command updater.
One-Command Update
./update.sh # Update everything automatically
make update # Via Makefile
./start.sh update # Via start script
What the Updater Does
- Checks if new updates are available
- Stops running services gracefully
- Stashes your local changes (and restores them after)
- Pulls the latest code
- Rebuilds backend dependencies + frontend
- Restarts services
- Shows the version change
Check Without Installing
./update.sh --check # Check for updates only
./update.sh --version # Show current version
Docker Deployments
./update.sh # Auto-detects Docker, rebuilds containers
./deploy.sh --update # Production deployment update
Auto-check: When you start MIZAN with ./start.sh or make dev, it automatically checks for updates and shows a notification if available.
QALB-7 Cognitive Architecture
Every MIZAN agent processes tasks through a 7-layer cognitive pipeline inspired by Quranic psychology. Each layer transforms the task before it reaches the LLM, and post-processes the response.
QALB-7 Pipeline
Each layer runs in sequence on every agent task:
| # | Module | Arabic | Purpose | File |
|---|---|---|---|---|
| 1 | Fitrah | فطرة | Innate ethical guardrails (NO_HARM, TRUTH, JUSTICE) | core/fitrah.py |
| 2 | Nafs Triad | نفس | Three competing inner voices deliberate on approach | core/nafs_triad.py |
| 3 | Qalb Processor | قلب | Cardiac oscillation — modulates LLM temperature & token limits | core/qalb_processor.py |
| 4 | Fu'ad | فؤاد | Bayesian conviction engine — evidence accumulation | core/fuad.py |
| 5 | Lubb | لبّ | Metacognition — compress, check coherence, detect bias | core/lubb.py |
| 6 | Developmental Gate | أطوار | Progressive capability gating (7 stages) | core/developmental_stages.py |
| 7 | Causal Engine | سببية | Pearl's causal ladder (observe/intervene/counterfactual) | reasoning/causal_engine.py |
Layer 1: Fitrah — Innate Ethics
Before any tool executes, Fitrah checks three non-negotiable axioms:
- NO_HARM — Blocks destructive commands (
rm -rf,DROP TABLE) - TRUTH — Prevents fabricating data or claiming certainty without evidence
- JUSTICE — Guards against disproportionate impact actions
On initialization, Fitrah axioms are loaded into QCA Lawh Tier 1 as immutable truths with certainty 1.0.
Layer 2: Nafs Triad — Inner Deliberation
Three competing "inner voices" deliberate on every task. The winner injects behavioral guidance into the system prompt:
| Voice | Arabic | Bias | Behavior |
|---|---|---|---|
| Ammara | أمّارة | Drive | Push to act quickly, take risks |
| Lawwama | لوّامة | Caution | Question assumptions, double-check |
| Mutmainna | مطمئنة | Balance | Seek harmony, measured approach |
Voice weights shift with the agent's Nafs level: Level 1-2 Ammara dominates (drive), Level 3-4 Lawwama dominates (critical), Level 5-7 Mutmainna dominates (wise).
Layer 3: Qalb Processor — Cardiac Oscillation
The Qalb models a "heartbeat" that alternates between contraction and expansion, directly modulating LLM parameters:
| State | Arabic | Temperature | Max Tokens | When |
|---|---|---|---|---|
| Qabd | قبض | 0.3 | 2048 | Focused, analytical tasks |
| Bast | بسط | 0.8 | 4096 | Creative, exploratory tasks |
| Khushu | خشوع | 0.2 | 6144 | Deep focus (nafs ≥ 4 + complex task) |
The oscillation phase advances 0.02 per interaction. Emotional overrides: Frustrated → force Qabd; Positive → allow Bast.
Layer 4: Fu'ad — Conviction Formation
Bayesian evidence accumulation across three conviction levels:
| Level | Requirement | Confidence |
|---|---|---|
| Impression | Single source | 0.0 – 0.50 |
| Belief | 2+ independent sources | 0.50 – 0.78 |
| Conviction | 3+ sources + temporal consistency | 0.78 – 1.0 |
Each source closes 35% of the remaining confidence gap: confidence = 1 - (0.65 ^ source_count)
Layer 5: Lubb — Metacognition
After response generation, Lubb performs three evaluations:
- Compress — Information Bottleneck: keeps decisions + tool results + key facts (~20% of input)
- Check Coherence — Verify conclusions follow from premises (score 0.0–1.0)
- Detect Bias — Flag confirmation bias, anchoring, availability bias
Output: quality label (confident | hedged | uncertain), coherence score, and bias flags. If coherence < 0.5, a caveat is appended to the response.
Layer 6: Developmental Gate — 7 Embryological Stages
Agents grow through seven stages, each unlocking new capabilities:
| Level | Stage | Arabic | Max Turns | Key Unlocks |
|---|---|---|---|---|
| 1 | Nutfah | نطفة | 5 | bash, read_file, recall_memory |
| 2 | Alaqah | علقة | 8 | + write_file, http_get |
| 3 | Mudghah | مضغة | 10 | + python_exec, http_post, delegation |
| 4 | Izham | عظام | 12 | + create_agent, causal rung 2 |
| 5 | Lahm | لحم | 15 | All tools, causal rung 3, Lubb metacognition |
| 6 | Nafkh | نفخ | 20 | Full metacognition |
| 7 | Khalq Akhar | خلق آخر | 25 | Full autonomy |
Promotion criteria: sustained success rate + task count + hikmah threshold (managed by DevelopmentalGate.check_upgrade_readiness()).
Layer 7: Causal Engine — Pearl's Causal Ladder
| Rung | Type | Question | Method |
|---|---|---|---|
| 1 | Observation | "What is?" | P(Y|X) — correlational analysis |
| 2 | Intervention | "What if I do X?" | P(Y|do(X)) — do-calculus |
| 3 | Counterfactual | "What if I had done X instead?" | P(Y_x|X', Y') — alt. history |
Extension Modules
| Module | Arabic | Purpose | File |
|---|---|---|---|
| Multimodal Perception | سمع+بصر | Sam' (hearing) first, then Basar (sight), Qalb-aware context modulation | perception/basirah.py, perception/nutq.py |
| Living Memory | ذاكرة حية | Novelty gate + hybrid text/vector similarity + Dhikr maintenance daemon | memory/living_memory.py |
| Quaternary Encoding | تشفير رباعي | DNA-inspired ACGT checksums with codon chunking and Hamming verification | memory/quaternary.py |
| Self-Healing | لوّامة | Immune memory, health metrics, adaptive checkpoints | core/self_healing.py |
| Parallel Agents | — | Concurrent task scheduling + skill transfer | core/parallel_agents.py |
| Imagination | تصوير | Predictive coding — simulate before acting | core/imagination.py |
| Creativity | إبداع | 5 creative modes + fitness landscape math | core/creativity.py |
| Dream Engine | منام | Offline memory consolidation (NREM+REM) | core/dream_engine.py |
| Shura Council | شورى | Multi-agent consultation for complex decisions | agents/shura_council.py |
Memory Architecture (6-Layer Pyramid)
All memory layers are queried through a unified MemoryPyramid:
| Layer | Module | Purpose |
|---|---|---|
| Living Memory | memory/living_memory.py | Novelty gate with hybrid text + vector similarity, importance scoring, Dhikr daemon |
| Dhikr | memory/dhikr.py | Three-tier persistent memory (episodic, semantic, procedural) |
| Masalik | memory/masalik.py | Neural pathways with spreading activation |
| VectorStore | memory/vector_store.py | Semantic embedding search (ChromaDB) — also used by Living Memory |
| KnowledgeGraph | memory/knowledge_graph.py | Entity-relationship graph with full-text entity search (SQLite) |
| Lawh al-Mahfuz | memory/lawh_mahfuz.py | Immutable memory with 4-layer integrity: SHA-256 + CRC-32 + length + quaternary checksum |
Unified query: memory/memory_pyramid.py merges, deduplicates, and ranks by relevance × certainty × recency.
Quaternary Encoding: DNA-inspired error detection using a 4-symbol alphabet (A, C, G, T). Data is encoded as quaternary strings, chunked into codons (triplets mapping to 64 semantic categories), and verified using XOR parity and Hamming distance checks.
Yaqin Certainty Engine
Every piece of knowledge is tagged with its certainty level:
| Level | Arabic | Meaning | Confidence |
|---|---|---|---|
| Ilm al-Yaqin | علم اليقين | Knowledge-based certainty (inference) | 0.3 - 0.6 |
| Ayn al-Yaqin | عين اليقين | Observation-based certainty (verified) | 0.6 - 0.9 |
| Haqq al-Yaqin | حق اليقين | Proven truth (reproduced) | 0.9 - 1.0 |
Cognitive Metadata in the UI
Every assistant response includes a CognitiveBar showing real-time cognitive state:
- Qalb state (Qabd/Bast/Khushu) with confidence
- Yaqin certainty level with confidence bar
- Lubb quality (confident / hedged / uncertain)
- Ruh energy percentage
- Nafs level and name badge
- Lawwama repair indicator (when self-healing is active)
Expandable for detailed signals, bias flags, and evidence lists.
QCA API Endpoints
POST /api/yaqin/tag Tag knowledge with certainty level
GET /api/yaqin/stats Get certainty engine statistics
POST /api/cognitive/route Route query to best reasoning method
POST /api/qalb/analyze Analyze emotional state from text
GET /api/qalb/trend/{id} Get emotional trend for a user
GET /api/nafs/tiers Get all 7 Nafs permission tiers
GET /api/nafs/{agent_id} Get agent's Nafs status
GET /api/ruh/{agent_id} Get agent's energy state
GET /api/federation/status Get agent federation status
POST /api/federation/discover Discover agents by capability
Multimodal Perception
MIZAN's perception system implements Quranic sensory processing: Sam' (hearing) processes before Basar (sight), following the order established in Quran 16:78 and 17:36.
Auditory-first processing: Audio input is always processed before visual input, mirroring the Quranic ordering of sam' before basar in every mention.
Basirah — Vision Engine
The BasirahEngine analyzes images using LLM vision capabilities. It returns structured JSON with:
- Description: Natural language description of the image
- Category: text, diagram, screenshot, photo, or document
- Extracted text: Any text found in the image (OCR-like)
- Key elements: Important objects, patterns, or features
- Confidence: 0.0–1.0 reliability score
Qalb-Aware Focus
Vision analysis adapts based on emotional state:
| Qalb State | Focus Adjustment |
|---|---|
| frustrated | Pay attention to errors, warnings, and problematic elements |
| confused | Focus on clarity, labels, and explanatory elements |
| anxious | Look for reassuring elements and positive signals |
| determined | Identify actionable items and next steps |
Nutq — Voice Engine
The NutqEngine handles speech synthesis and analysis:
- Intent detection: question, command, greeting, farewell, confirmation, negation, request, statement
- Language detection: Arabic (Unicode \u0600–\u06FF), Urdu (specific chars), English (default)
- Tone adjustment: Adapts output based on Qalb state (warm, patient, focused)
QCA Integration
Perception results flow into the QCA engine via process_input_multimodal():
Input → Sam' (audio) → Basar (vision) → Fu'ad (integration)
↓ ↓ ↓ ↓
Nutq Transcribe Analyze Merge results
Engine intent & category & + ISM root analysis
language elements + Lawh storage
Using Perception in the UI
Navigate to Tools → Perception in the sidebar, or attach an image/audio file directly in the chat interface. The system automatically routes media to the appropriate perception engine.
Perception API
Analyze Multimodal Input
POST /api/perception/analyze
{
"text": "What does this diagram show?",
"image_base64": "iVBORw0KGgo...",
"audio_base64": "SUQzBAA...",
"media_type": "image/png",
"agent_id": "agent_abc123",
"qalb_state": "neutral"
}
Response:
{
"perception": {
"sam": { ... },
"basar": { ... },
"fuad": { ... },
"nutq": {
"text": "What does this diagram show?",
"confidence": 0.92,
"language": "english",
"intent": "question"
},
"basirah": {
"description": "A system architecture diagram showing ...",
"category": "diagram",
"confidence": 0.87,
"extracted_text": "QCA Engine → Memory → ...",
"key_elements": ["architecture", "pipeline", "layers"]
}
},
"roots_identified": { "ع-ل-م": { ... } },
"key_terms": ["architecture", "pipeline"],
"zahir": "User is asking about a technical diagram",
"batin": "User wants to understand system structure"
}
WebSocket Multimodal Message
// Send via WebSocket
{
"type": "multimodal",
"text": "Describe this image",
"image_base64": "...",
"media_type": "image/png",
"session_id": "session_123",
"agent_id": "agent_abc"
}
// Receive perception_result
{
"type": "perception_result",
"result": { ... } // Same as REST response
}
Releases & Versioning
MIZAN uses Semantic Versioning (MAJOR.MINOR.PATCH) with support for pre-release versions (beta, rc).
Version Format
| Format | Example | When |
|---|---|---|
MAJOR.MINOR.PATCH | 3.1.0 | Stable release |
X.Y.Z-beta.N | 3.2.0-beta.1 | Beta pre-release |
X.Y.Z-rc.N | 3.2.0-rc.1 | Release candidate |
Manual Release
# Stable releases
make release-patch # 3.0.0 → 3.0.1 (bug fixes)
make release-minor # 3.0.0 → 3.1.0 (new features)
make release-major # 3.0.0 → 4.0.0 (breaking changes)
# Pre-releases
make release-beta # 3.0.0 → 3.1.0-beta.1
make release-rc # 3.1.0-beta.2 → 3.1.0-rc.1
# Preview without changes
make release-dry # Shows what would happen
What Happens During a Release
make release-patch
↓
scripts/release.sh:
1. Pre-flight: checks branch, clean tree, up-to-date
2. Bumps version in 6 files (VERSION, pyproject.toml, etc.)
3. Auto-generates CHANGELOG from git commits
4. Commits: "chore: release vX.Y.Z"
5. Creates annotated git tag: vX.Y.Z
6. Pushes branch + tag to origin
↓
GitHub Actions (release.yml) triggers on v* tag:
1. Validates: lint + test
2. Publishes to PyPI
3. Pushes Docker images to ghcr.io
4. Creates GitHub Release with changelog notes
Automatic Release
When a PR is merged to main, the auto-release workflow determines the version bump automatically:
| Signal | Bump |
|---|---|
PR label release:major or commit BREAKING CHANGE | Major |
PR label release:minor or commit prefix feat: | Minor |
PR label release:patch or commit prefix fix: | Patch |
PR label release:beta | Beta pre-release |
PR label release:skip | No release |
Tip: Add a release:minor label to your PR before merging to trigger an automatic minor release with auto-generated changelog.
Version Storage
The version is stored in 6 locations, all kept in sync by scripts/bump-version.sh:
| File | Purpose |
|---|---|
VERSION | Single source of truth |
pyproject.toml | Python package metadata |
backend/_version.py | Runtime import (from backend._version import __version__) |
frontend/package.json | Frontend version |
backend/cli.py | CLI banner display |
backend/api/main.py | API version metadata |
Changelog Format
CHANGELOG.md follows Keep a Changelog. During release, commits are auto-categorized:
| Commit Prefix | Category |
|---|---|
feat: / add: / new: | Added |
fix: / bug: / hotfix: | Fixed |
refactor: / docs: / chore: / perf: | Changed |
Branch Protection
The main branch is protected with these rules:
- Require PR with 1 approval before merging
- Dismiss stale reviews on new pushes
- Require status checks: Lint, Test, Frontend Build
- Require branch to be up to date
- Require all conversations resolved
- Block force pushes and branch deletion
# Apply protection rules (requires gh CLI)
make protect
System Design
MIZAN is built on a fully decoupled architecture. Modules communicate through events and hooks, never by importing each other directly.
Design Principles
- Decoupled: Modules communicate through events, hooks, and middleware — not imports
- Extensible: Plugins can add tools, modify behavior, and react to events
- Secure: Every operation passes through the Wali security layer
- Provider-agnostic: Works with any LLM through unified interface
- Memory-aware: Agents learn and remember across sessions
Communication Patterns
| Pattern | Use Case | Example |
|---|---|---|
| Events | Notifications | "A task was completed" |
| Hooks | Data modification | "Change the system prompt" |
| Middleware | Request processing | "Log all API requests" |
| Direct API | Explicit calls | "Create an agent" |
Project Structure
mizan/
+-- backend/
| +-- api/main.py # FastAPI server + all routes
| +-- agents/
| | +-- base.py # Base agent with QALB-7 agentic loop
| | +-- specialized.py # Browser, Research, Code, SuperAgent (Khalifah)
| | +-- federation.py # Agent-to-agent communication
| | +-- shura_council.py # Multi-agent consultation
| | +-- perpetual_rotation.py # Agent rotation & load balancing
| +-- core/
| | +-- fitrah.py # Innate ethical guardrails
| | +-- nafs_triad.py # 3-voice deliberation (Ammara/Lawwama/Mutmainna)
| | +-- qalb_processor.py # Cardiac oscillation → LLM param modulation
| | +-- fuad.py # Bayesian conviction formation
| | +-- lubb.py # Metacognition: compress, cohere, debias
| | +-- developmental_stages.py # 7-stage capability gating
| | +-- self_healing.py # Lawwama immune system + health metrics
| | +-- parallel_agents.py # Concurrent task scheduling
| | +-- imagination.py # Predictive coding engine
| | +-- creativity.py # 5 creative modes + landscape math
| | +-- dream_engine.py # Offline memory consolidation
| | +-- qalb.py # Emotional intelligence (sentiment)
| | +-- ruh_engine.py # Energy/vitality management
| | +-- events.py # Event bus (Nida')
| | +-- hooks.py # Hook system (Ta'liq)
| | +-- plugins.py # Plugin manager (Wasilah)
| | +-- middleware.py # Middleware pipeline (Silsilah)
| +-- providers.py # LLM providers (Claude/GPT/Ollama/300+)
| +-- perception/
| | +-- basirah.py # Vision engine (LLM-powered image analysis)
| | +-- nutq.py # Voice engine (speech + intent detection)
| | +-- vision.py # Low-level vision processing
| | +-- voice.py # Low-level voice processing
| +-- memory/
| | +-- dhikr.py # 3-tier persistent memory
| | +-- masalik.py # Neural pathways (spreading activation)
| | +-- lawh_mahfuz.py # Immutable memory (quad-checksum)
| | +-- memory_pyramid.py # Unified 5-layer query engine
| | +-- vector_store.py # Semantic embeddings (ChromaDB)
| | +-- knowledge_graph.py # Entity-relationship graph
| | +-- living_memory.py # Adaptive memory lifecycle (hybrid similarity)
| | +-- quaternary.py # DNA-inspired ACGT encoding & integrity
| +-- reasoning/
| | +-- aql_engine.py # Arabic Query Language reasoning
| | +-- causal_engine.py # Pearl's 3-rung causal ladder
| | +-- planner.py # Task planning
| | +-- context_manager.py # Context window management
| +-- security/ # Auth, permissions, sandbox
| +-- skills/ # Skill registry + builtins
| +-- knowledge/ # Knowledge base management
| +-- gateway/channels/ # Telegram, Discord, Slack, WhatsApp
| +-- automation/ # Cron jobs + webhooks
| +-- settings.py # Configuration
| +-- cli.py # Terminal interface
+-- frontend/src/
| +-- App.tsx # Main UI + WebSocket + multimodal chat
| +-- components/
| | +-- ChatMessage.tsx # Chat bubbles + CognitiveBar + PerceptionCard
| | +-- AgentCard.tsx # Agent card (Nafs + Ruh bars)
| | +-- Icons.tsx # SVG icon components
| +-- pages/
| | +-- PerceptionPage.tsx # Vision & voice analysis UI
| +-- hooks/ # React hooks
| +-- types.ts # TypeScript types (CognitiveMetadata)
+-- plugins/ # Your plugins go here!
+-- docs/ # This documentation
+-- tests/ # Test suite
+-- docker/ # Docker configs
+-- pyproject.toml # Package config
+-- Makefile # Dev commands