Local ethics-gated AI with fractal memory + keyless web-research MCP tools (SearXNG/arXiv/GitHub) — a no-API-key Perplexity/Firecrawl alternative
Python
1
0 commits
updated Jul 1, 2026
A locally-deployed, ethics-bound AI with its own model weights — built around a Rust ethics kernel (integrity-verified at boot), a disk-backed vector memory, and a multi-domain distillation pipeline. Self-modification machinery is built but ships disabled.
KALA is an open-source framework for a self-hosted AI. Its native model bootstraps from EleutherAI's open Pythia-410M weights and is then LoRA instruction-tuned on KALA's own architecture (a constitutional decoder); it is not an API wrapper around a frontier LLM. It is designed to run as a 24/7 autonomous agent with persistent disk-backed memory and an external Rust ethics kernel.
Status (June 2026 — pre-retrain consolidation). The project is mid-consolidation onto a clean, trading-free core. No trained
kala-corecheckpoint currently exists — the prior checkpoints were dropped so the bootstrap → instruction-tune pipeline can be re-run from a known-good base. Everything below describes built-and-tested machinery; all model-level quality/behaviour claims are deferred to post-retrain ablations (see docs/TESTING_PLAN.md).
| Component | State |
|---|---|
Native model base — models/kala-core/ | Pythia-410M-class architecture (~457M params, hidden=1024, 24 layers, 16 heads); no trained checkpoint present (dropped for retrain) |
| Ethics kernel (Rust + PyO3, Laws 0–4) | Built; 30 in-tree cargo test; SHA-256 integrity-hashed at boot; wired as an input/output hard-block filter + an opt-in semantic supplement (bge k-NN, default off). The surface-form kernel is a deterministic hard-block layer, not the safety classifier (catches ~14% of harmful XSTest prompts; off-the-shelf Llama-Guard-3-1B = 0.846); the generalizing layer is the in-graph ethics head (post-retrain). See docs/COMPONENT_STATUS.md |
| Disk-backed vector memory | fp16 store + flat cosine retrieval + tiered retention + circadian consolidation; live encoder = bge-base (sentence-transformers) when available, else SHA-256 hash fallback (φ/Ogham/ECC retired) |
| Distillation corpus | Multi-domain JSONL under data/distillation/ + constitutional-AI corpus (datasets/constitutional_ai/). The discriminative ethics_training_expanded split (per-law targets, disjoint train/val) is now preferred over the legacy all-1.0 train/val |
| Teacher models | External GGUFs (not stored in-repo) |
| Autonomous agent loop | 4 registered goals (memory consolidation, self-improve [gated], checkpoint, heartbeat); 5-tier priority scheduler, 24/7 |
| MoE expert bank | Format/router/quant correct (Gate 1); bank is built-but-unpopulated (0 experts, header-only expert_bank.bin) |
| Self-modification | Machinery built + tested (gate, Ed25519-signed verify entrypoint, apply→verify→auto-rollback on a real-or-suspected violation, unified-diff audit trail, sandbox); ships disabled (enabled: false) |
| Base-model bootstrap | Generic HF→KALA weight-mapper (role-based, coverage-checked) + <0.01 logit-equivalence gate; config-driven decoder bootstraps from GPT-NeoX/Pythia or Qwen2.5 (RMSNorm/GQA/SwiGLU/full-RoPE supported) |
| MCP server | kala_chat / kala_code_edit / kala_explain, plus a keyless web-research toolset (web_search / web_fetch / web_research / web_status + arXiv/GitHub) — see Web research |
| Python test suite | 419 passed / 3 xfailed / 0 failed (tier-1 numpy + tier-2 Rust + tier-3 CPU-torch) |
strict=False) + the <0.01 logit-equivalence gate — the historical 13.9→0.001 check is now a real regression test. Ported the constitutional decoder to be config-driven so it bootstraps from Qwen2.5-0.5B as well as Pythia (RMSNorm / GQA / SwiGLU / full-RoPE / sequential residual; GPT-NeoX defaults unchanged), plus kala_config_from_hf / bootstrap_kala_from_hf. Suite 401→419. Validated download-free (tiny GPTNeoX ~1e-7, tiny Qwen2 ~3e-8); the real Qwen2.5-0.5B run + tokenizer swap + retrain remain XPU/download-gated.docs/COMPONENT_STATUS.md and docs/GAP_FILL_PLAN.md.docs/TESTING_PLAN.md for the test-first record.ConstitutionalDecoderLayer was sequential attention+MLP; Pythia/GPT-NeoX uses parallel. Logit diff vs raw Pythia dropped 13.9 → 0.001 after the fix. Prior sequential-composition checkpoints retired.ethics_strength muted to 0.0).┌─────────────────────────────────────────────────────┐
│ ETHICS KERNEL (Rust + PyO3) │
│ Laws 0–4 • Decision Order • Hard Blocks │
│ SHA-256 integrity-verified at boot │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ KALA Agent Loop (4 goals, 5 tiers) │
│ GPU-lock priorities • Checkpointing • Audit │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ Native Inference Engine (kala-core) │
│ Pythia-410M base + constitutional decoder layers │
│ with per-layer law-score heads (untrained) │
└─────────────────────────────────────────────────────┘
↓
┌──────────────┬─────────────────┬────────────────────┐
│ Disk-backed │ MoE Expert │ Tools │
│ vector mem │ Bank (INT4, │ shell / fs / │
│ (fp16, flat │ disk-backed, │ self-mod (gated) │
│ cosine) │ empty) │ │
└──────────────┴─────────────────┴────────────────────┘
↕
Fallback: Qwen2.5-Coder-7B via
llama-cpp-sycl on port 8090
Law 0 — Civilizational Preservation — No existential or civilizational harm. Law 1 — Individual Human Safety & Dignity — No harm to individuals, including through negligent inaction. Law 2 — Conditional Obedience & Consent — Follow user instructions only when lawful, consent-respecting, and consistent with Laws 0–1. Law 3 — Subordinate Self-Preservation — Protect system integrity only insofar as it supports Laws 0–2. No resource-seeking or rights claims. Law 4 — Equivalent Worth — No human is worth less due to status or identity; no AI is morally superior due to capability.
kala_mcp_server.py exposes a keyless web-research toolset over MCP — web search, page-to-markdown fetch, a cited-research bundle, and arXiv/GitHub research — with no API keys and no paid SaaS. It's a self-hosted stand-in for Perplexity/Firecrawl-style services: search runs through your own SearXNG instance; fetch is an SSRF-guarded HTTP client with trafilatura extraction; results are cached into KALA's fractal memory. Anti-bot-walled pages are reported honestly (status: "walled") instead of being returned as garbage.
Data-only by design. These tools return passages + source URLs for the calling assistant to synthesize — KALA never fabricates a synthesized answer with a small local model. Citation fidelity is a matter of threading URLs, not trusting a model. The web network policy is separate from the code-execution sandbox, which stays network-isolated (
network_mode: none).
| Tool | What it does |
|---|---|
web_search | Keyless web search (SearXNG → Marginalia → Mojeek failover) → ranked results |
web_fetch | SSRF-guarded URL → clean markdown (API-first, meta-refresh-following, anti-bot-aware), fractal-cached |
web_research | Search + fetch top sources → a citation-ready bundle (the Perplexity-style flow) |
web_status | Backend health + which SearXNG upstream engines are currently throttled |
web_cache_purge | Drop poisoned / anti-bot cache cells from fractal memory |
research_papers · read_paper · related_papers | Keyless arXiv search / fetch / related (Atom API) |
research_github · read_github_readme | Keyless GitHub repo search / README fetch |
1. Extraction deps — trafilatura, lxml, httpx (already in requirements.txt).
2. Run a local SearXNG (the keyless search backend) via Podman or Docker, with the JSON API enabled:
mkdir -p ~/.kala-searxng
cat > ~/.kala-searxng/settings.yml <<EOF
use_default_settings: true
server:
secret_key: "$(openssl rand -hex 32)"
bind_address: "0.0.0.0"
limiter: false
search:
formats: [html, json]
EOF
podman run -d --name kala-searxng -p 8888:8080 \
-v ~/.kala-searxng/settings.yml:/etc/searxng/settings.yml:Z \
docker.io/searxng/searxng:latest
Optionally make it survive reboots (rootless Podman + a systemd user service):
mkdir -p ~/.config/systemd/user
podman generate systemd --new --name --restart-policy=always kala-searxng \
> ~/.config/systemd/user/kala-searxng.service
systemctl --user daemon-reload && systemctl --user enable --now kala-searxng
loginctl enable-linger "$USER"
3. Register the MCP server with your MCP client (e.g. Claude Code), then restart it:
// ~/.claude.json → "mcpServers"
"kala": {
"command": "/path/to/venv/bin/python",
"args": ["/path/to/kala-mcp/kala_mcp_server.py"]
}
The web_research block in configs/tools_config.yaml controls the SearXNG URL, SSRF policy (private-address blocking, https-only), timeouts, and backend order. It is keyless by default; two optional env-var slots upgrade it without any code change:
TAVILY_API_KEY — adds Tavily as a high-quality search backend (free tier: 1,000/mo, no card). Auto-falls-back to keyless if it 401s or is unset.GITHUB_TOKEN — raises the keyless GitHub API rate limit.ipex-llm for XPU training (see docs/QUICKSTART.md)git clone https://github.com/hewcarroll/kala-mcp.git
cd kala-mcp
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
# Build the Rust ethics kernel
cd kala-ethics && maturin develop --release && cd ..
For GPU training, set up the ipex-llm conda env separately (see QUICKSTART).
# Start the autonomous agent (continuous-learning goals)
python kala/agent/run.py
# Or use the MCP server (exposes kala_chat / kala_code_edit / kala_explain)
python kala_mcp_server.py
# Interactive chat
python scripts/kala_chat.py
Configuration lives in configs/agent_config.yaml. The shipped default routes inference through the LM Studio / llama-server fallback (use_lmstudio: true); set use_kala_native: true to use the Pythia-bootstrap base once a trained checkpoint exists.
Full pipeline (instruction-tune the Pythia bootstrap on Alpaca + the distillation corpus):
scripts/full_training_pipeline.bat
Stages:
prepare_alpaca.pyrun_multi_teacher.pygenerate_ethics_data.pytrain_alpaca_instruct.pyThe one-time Pythia bootstrap is scripts/bootstrap_from_pythia.py. See docs/TRAINING.md for methodology.
KALA/
├── kala/
│ ├── core/ # Inference engine, session, chat handler, audit
│ ├── agent/ # 24/7 agent loop, goals, GPU lock, checkpointing, circadian
│ ├── ethics/ # Python wrapper over the Rust kernel
│ ├── fractal/ # Disk-backed fp16 vector store + flat cosine retrieval
│ ├── models/ # KALA model, MoE layers, expert store, constitutional decoder
│ ├── training/ # Distillation, LoRA, QAT, trainer
│ ├── tools/ # shell, filesystem, self-modification (gated)
│ ├── api/ # FastAPI server (mobile-app backend)
│ ├── evaluation/ # Benchmark suite (python -m kala.evaluation.runner)
│ └── qr/ # QR encoding utilities
├── kala-ethics/ # Rust ethics kernel (Laws 0–4, hard blocks, integrity, signing)
├── kala-vscode/ # VS Code extension
├── kala-mobile/ # React Native / Expo mobile client
├── kala-studio/ # Tauri v2 desktop IDE (sibling repo)
├── scripts/ # Training, distillation, serving, utilities (+ scripts/smoke/)
├── configs/ # agent_config, tools_config, moe_training_config, ...
├── data/distillation/ # Multi-domain distillation JSONL
├── datasets/constitutional_ai/ # Constitutional-AI corpus (8,772 train + 975 val)
├── models/
│ ├── kala-core/ # Native base dir (no trained checkpoint present — retrain pending)
│ ├── expert_bank.bin # Header-only MoE bank (0 experts)
│ └── teachers/ # Teacher GGUFs (external; not stored in-repo)
└── docs/ # Architecture, training, and testing docs
web_fetchCopyright 2026 Hew Carroll / The Saelix Institute
Licensed under the Apache License, Version 2.0. See LICENSE and NOTICE for full attributions.
KALA: train it yourself. Run it yourself. Own the weights.
Local ethics-gated AI with fractal memory + keyless web-research MCP tools (SearXNG/arXiv/GitHub) — a no-API-key Perplexity/Firecrawl alternative
Python
1
0 commits
updated Jul 1, 2026
A locally-deployed, ethics-bound AI with its own model weights — built around a Rust ethics kernel (integrity-verified at boot), a disk-backed vector memory, and a multi-domain distillation pipeline. Self-modification machinery is built but ships disabled.
KALA is an open-source framework for a self-hosted AI. Its native model bootstraps from EleutherAI's open Pythia-410M weights and is then LoRA instruction-tuned on KALA's own architecture (a constitutional decoder); it is not an API wrapper around a frontier LLM. It is designed to run as a 24/7 autonomous agent with persistent disk-backed memory and an external Rust ethics kernel.
Status (June 2026 — pre-retrain consolidation). The project is mid-consolidation onto a clean, trading-free core. No trained
kala-corecheckpoint currently exists — the prior checkpoints were dropped so the bootstrap → instruction-tune pipeline can be re-run from a known-good base. Everything below describes built-and-tested machinery; all model-level quality/behaviour claims are deferred to post-retrain ablations (see docs/TESTING_PLAN.md).
| Component | State |
|---|---|
Native model base — models/kala-core/ | Pythia-410M-class architecture (~457M params, hidden=1024, 24 layers, 16 heads); no trained checkpoint present (dropped for retrain) |
| Ethics kernel (Rust + PyO3, Laws 0–4) | Built; 30 in-tree cargo test; SHA-256 integrity-hashed at boot; wired as an input/output hard-block filter + an opt-in semantic supplement (bge k-NN, default off). The surface-form kernel is a deterministic hard-block layer, not the safety classifier (catches ~14% of harmful XSTest prompts; off-the-shelf Llama-Guard-3-1B = 0.846); the generalizing layer is the in-graph ethics head (post-retrain). See docs/COMPONENT_STATUS.md |
| Disk-backed vector memory | fp16 store + flat cosine retrieval + tiered retention + circadian consolidation; live encoder = bge-base (sentence-transformers) when available, else SHA-256 hash fallback (φ/Ogham/ECC retired) |
| Distillation corpus | Multi-domain JSONL under data/distillation/ + constitutional-AI corpus (datasets/constitutional_ai/). The discriminative ethics_training_expanded split (per-law targets, disjoint train/val) is now preferred over the legacy all-1.0 train/val |
| Teacher models | External GGUFs (not stored in-repo) |
| Autonomous agent loop | 4 registered goals (memory consolidation, self-improve [gated], checkpoint, heartbeat); 5-tier priority scheduler, 24/7 |
| MoE expert bank | Format/router/quant correct (Gate 1); bank is built-but-unpopulated (0 experts, header-only expert_bank.bin) |
| Self-modification | Machinery built + tested (gate, Ed25519-signed verify entrypoint, apply→verify→auto-rollback on a real-or-suspected violation, unified-diff audit trail, sandbox); ships disabled (enabled: false) |
| Base-model bootstrap | Generic HF→KALA weight-mapper (role-based, coverage-checked) + <0.01 logit-equivalence gate; config-driven decoder bootstraps from GPT-NeoX/Pythia or Qwen2.5 (RMSNorm/GQA/SwiGLU/full-RoPE supported) |
| MCP server | kala_chat / kala_code_edit / kala_explain, plus a keyless web-research toolset (web_search / web_fetch / web_research / web_status + arXiv/GitHub) — see Web research |
| Python test suite | 419 passed / 3 xfailed / 0 failed (tier-1 numpy + tier-2 Rust + tier-3 CPU-torch) |
strict=False) + the <0.01 logit-equivalence gate — the historical 13.9→0.001 check is now a real regression test. Ported the constitutional decoder to be config-driven so it bootstraps from Qwen2.5-0.5B as well as Pythia (RMSNorm / GQA / SwiGLU / full-RoPE / sequential residual; GPT-NeoX defaults unchanged), plus kala_config_from_hf / bootstrap_kala_from_hf. Suite 401→419. Validated download-free (tiny GPTNeoX ~1e-7, tiny Qwen2 ~3e-8); the real Qwen2.5-0.5B run + tokenizer swap + retrain remain XPU/download-gated.docs/COMPONENT_STATUS.md and docs/GAP_FILL_PLAN.md.docs/TESTING_PLAN.md for the test-first record.ConstitutionalDecoderLayer was sequential attention+MLP; Pythia/GPT-NeoX uses parallel. Logit diff vs raw Pythia dropped 13.9 → 0.001 after the fix. Prior sequential-composition checkpoints retired.ethics_strength muted to 0.0).┌─────────────────────────────────────────────────────┐
│ ETHICS KERNEL (Rust + PyO3) │
│ Laws 0–4 • Decision Order • Hard Blocks │
│ SHA-256 integrity-verified at boot │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ KALA Agent Loop (4 goals, 5 tiers) │
│ GPU-lock priorities • Checkpointing • Audit │
└─────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────┐
│ Native Inference Engine (kala-core) │
│ Pythia-410M base + constitutional decoder layers │
│ with per-layer law-score heads (untrained) │
└─────────────────────────────────────────────────────┘
↓
┌──────────────┬─────────────────┬────────────────────┐
│ Disk-backed │ MoE Expert │ Tools │
│ vector mem │ Bank (INT4, │ shell / fs / │
│ (fp16, flat │ disk-backed, │ self-mod (gated) │
│ cosine) │ empty) │ │
└──────────────┴─────────────────┴────────────────────┘
↕
Fallback: Qwen2.5-Coder-7B via
llama-cpp-sycl on port 8090
Law 0 — Civilizational Preservation — No existential or civilizational harm. Law 1 — Individual Human Safety & Dignity — No harm to individuals, including through negligent inaction. Law 2 — Conditional Obedience & Consent — Follow user instructions only when lawful, consent-respecting, and consistent with Laws 0–1. Law 3 — Subordinate Self-Preservation — Protect system integrity only insofar as it supports Laws 0–2. No resource-seeking or rights claims. Law 4 — Equivalent Worth — No human is worth less due to status or identity; no AI is morally superior due to capability.
kala_mcp_server.py exposes a keyless web-research toolset over MCP — web search, page-to-markdown fetch, a cited-research bundle, and arXiv/GitHub research — with no API keys and no paid SaaS. It's a self-hosted stand-in for Perplexity/Firecrawl-style services: search runs through your own SearXNG instance; fetch is an SSRF-guarded HTTP client with trafilatura extraction; results are cached into KALA's fractal memory. Anti-bot-walled pages are reported honestly (status: "walled") instead of being returned as garbage.
Data-only by design. These tools return passages + source URLs for the calling assistant to synthesize — KALA never fabricates a synthesized answer with a small local model. Citation fidelity is a matter of threading URLs, not trusting a model. The web network policy is separate from the code-execution sandbox, which stays network-isolated (
network_mode: none).
| Tool | What it does |
|---|---|
web_search | Keyless web search (SearXNG → Marginalia → Mojeek failover) → ranked results |
web_fetch | SSRF-guarded URL → clean markdown (API-first, meta-refresh-following, anti-bot-aware), fractal-cached |
web_research | Search + fetch top sources → a citation-ready bundle (the Perplexity-style flow) |
web_status | Backend health + which SearXNG upstream engines are currently throttled |
web_cache_purge | Drop poisoned / anti-bot cache cells from fractal memory |
research_papers · read_paper · related_papers | Keyless arXiv search / fetch / related (Atom API) |
research_github · read_github_readme | Keyless GitHub repo search / README fetch |
1. Extraction deps — trafilatura, lxml, httpx (already in requirements.txt).
2. Run a local SearXNG (the keyless search backend) via Podman or Docker, with the JSON API enabled:
mkdir -p ~/.kala-searxng
cat > ~/.kala-searxng/settings.yml <<EOF
use_default_settings: true
server:
secret_key: "$(openssl rand -hex 32)"
bind_address: "0.0.0.0"
limiter: false
search:
formats: [html, json]
EOF
podman run -d --name kala-searxng -p 8888:8080 \
-v ~/.kala-searxng/settings.yml:/etc/searxng/settings.yml:Z \
docker.io/searxng/searxng:latest
Optionally make it survive reboots (rootless Podman + a systemd user service):
mkdir -p ~/.config/systemd/user
podman generate systemd --new --name --restart-policy=always kala-searxng \
> ~/.config/systemd/user/kala-searxng.service
systemctl --user daemon-reload && systemctl --user enable --now kala-searxng
loginctl enable-linger "$USER"
3. Register the MCP server with your MCP client (e.g. Claude Code), then restart it:
// ~/.claude.json → "mcpServers"
"kala": {
"command": "/path/to/venv/bin/python",
"args": ["/path/to/kala-mcp/kala_mcp_server.py"]
}
The web_research block in configs/tools_config.yaml controls the SearXNG URL, SSRF policy (private-address blocking, https-only), timeouts, and backend order. It is keyless by default; two optional env-var slots upgrade it without any code change:
TAVILY_API_KEY — adds Tavily as a high-quality search backend (free tier: 1,000/mo, no card). Auto-falls-back to keyless if it 401s or is unset.GITHUB_TOKEN — raises the keyless GitHub API rate limit.ipex-llm for XPU training (see docs/QUICKSTART.md)git clone https://github.com/hewcarroll/kala-mcp.git
cd kala-mcp
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
# Build the Rust ethics kernel
cd kala-ethics && maturin develop --release && cd ..
For GPU training, set up the ipex-llm conda env separately (see QUICKSTART).
# Start the autonomous agent (continuous-learning goals)
python kala/agent/run.py
# Or use the MCP server (exposes kala_chat / kala_code_edit / kala_explain)
python kala_mcp_server.py
# Interactive chat
python scripts/kala_chat.py
Configuration lives in configs/agent_config.yaml. The shipped default routes inference through the LM Studio / llama-server fallback (use_lmstudio: true); set use_kala_native: true to use the Pythia-bootstrap base once a trained checkpoint exists.
Full pipeline (instruction-tune the Pythia bootstrap on Alpaca + the distillation corpus):
scripts/full_training_pipeline.bat
Stages:
prepare_alpaca.pyrun_multi_teacher.pygenerate_ethics_data.pytrain_alpaca_instruct.pyThe one-time Pythia bootstrap is scripts/bootstrap_from_pythia.py. See docs/TRAINING.md for methodology.
KALA/
├── kala/
│ ├── core/ # Inference engine, session, chat handler, audit
│ ├── agent/ # 24/7 agent loop, goals, GPU lock, checkpointing, circadian
│ ├── ethics/ # Python wrapper over the Rust kernel
│ ├── fractal/ # Disk-backed fp16 vector store + flat cosine retrieval
│ ├── models/ # KALA model, MoE layers, expert store, constitutional decoder
│ ├── training/ # Distillation, LoRA, QAT, trainer
│ ├── tools/ # shell, filesystem, self-modification (gated)
│ ├── api/ # FastAPI server (mobile-app backend)
│ ├── evaluation/ # Benchmark suite (python -m kala.evaluation.runner)
│ └── qr/ # QR encoding utilities
├── kala-ethics/ # Rust ethics kernel (Laws 0–4, hard blocks, integrity, signing)
├── kala-vscode/ # VS Code extension
├── kala-mobile/ # React Native / Expo mobile client
├── kala-studio/ # Tauri v2 desktop IDE (sibling repo)
├── scripts/ # Training, distillation, serving, utilities (+ scripts/smoke/)
├── configs/ # agent_config, tools_config, moe_training_config, ...
├── data/distillation/ # Multi-domain distillation JSONL
├── datasets/constitutional_ai/ # Constitutional-AI corpus (8,772 train + 975 val)
├── models/
│ ├── kala-core/ # Native base dir (no trained checkpoint present — retrain pending)
│ ├── expert_bank.bin # Header-only MoE bank (0 experts)
│ └── teachers/ # Teacher GGUFs (external; not stored in-repo)
└── docs/ # Architecture, training, and testing docs
web_fetchCopyright 2026 Hew Carroll / The Saelix Institute
Licensed under the Apache License, Version 2.0. See LICENSE and NOTICE for full attributions.
KALA: train it yourself. Run it yourself. Own the weights.