Skip to content
kazma.
ع Star 6 Get Started

Kazma — Architecture & System Map

Map of production-wired modules (invariants live in AGENTS.md)
Version: 0.10.x
Date: 2026-09-02
Binding industrial audit: docs/audits/AUDIT_DEEP_2026-09-01_EXEC.md (waves 0–8 shipped — do not follow dump Part 6)
Earlier deep audits: docs/audits/AUDIT_DEEP_STRUCTURE_2026-08-19.md, docs/audits/AUDIT_INDUSTRY_STACK_2026-08-25.md
Companion docs: docs/docs/ops/diagnosis-map.md, docs/docs/guide/architecture.md, AGENTS.md

Honesty note: This map prioritizes production-wired paths and catalogs all source modules under main packages. Generated artifacts (docs/node_modules, docs/build, __pycache__, .venv) are excluded. Library-only modules are labeled [LIBRARY].


Kazma is a multi-platform autonomous agent framework: one LangGraph supervisor brain, many mouths (Telegram/Discord/Slack/Web/TUI/kazma ask/kazma acp), one IDE/tool execution layer, and optional swarm multi-worker orchestration. Platform IDs never enter LangGraph state. Danger tools require HITL (three execution paths: graph interrupt, swarm bus, pipeline checkpoint) plus one gate registry (hitl_gates.db). Swarm FanOut is tri-state, not first-wins. Config is runtime-mutable via ConfigStore (SQLite or Postgres). There is no kazma-memory package.

RequirementNotes
Python3.11–3.14
Default datakazma-data/ SQLite WAL
Optional RAG[rag] → ChromaDB + sentence-transformers
Optional multi-replica[postgres] + KAZMA_DATABASE_URL
Default bindLoopback preferred; Docker 0.0.0.0 with secret
  • Single-operator trusted host by default.
  • Production profile: KAZMA_PRODUCTION=1 (Docker code_exec, YOLO off, vault key required, workspace root required).
  • Multi-user SaaS foundation: platform RBAC + OIDC + opaque sessions + Postgres cutover.
  • Not: multi-primary multi-region write DBs without external DB product.
┌──────────────────────────────────────────────────────────────────────────────┐
│ CLIENT INPUTS │
│ Web UI / SSE (graph) / WS (telemetry) CLI TUI Gateway adapters │
│ Telegram/Discord/Slack GitHub OAuth/webhooks MCP IDE bridge │
└───────────────────────────────┬──────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ EDGE: FastAPI lifespan (app.py) │
│ Auth middleware (secret / opaque session / API token / OIDC session) │
│ Tenant middleware (prod: ignore spoofed X-Tenant-ID; JWT or default) │
│ CORS · i18n · static · health/live · health/ready (DB ping) │
└───────────────────────────────┬──────────────────────────────────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
SessionManager Gateway SessionStore Swarm Task APIs
(chat threads) (platform isolation) (TaskStore)
│ │ │
└─────────────────────┼─────────────────────┘
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ AGENT BRAIN │
│ KazmaAgent / agent_runner → build_supervisor_graph (wires nodes) │
│ graph_supervisor / graph_tool_worker / graph_respond │
│ Checkpointer: AsyncSqliteSaver | AsyncPostgresSaver │
│ Interrupt HITL + hitl_gates.db · turn_input · context integrity trim │
│ SubAgentManager → build_child_graph (auto-deny danger) │
└───────────────────────────────┬──────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ TOOLS & SANDBOX │
│ LocalToolRegistry (SoT) · UnifiedToolExecutor (local + MCP force_danger) │
│ shell_exec (allowlist + env scrub) · python_exec (Docker jail / blocklist)│
│ IdeService → same tools + HITL · native skills (kazma-skills) │
└───────────────────────────────┬──────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ SWARM ENGINE │
│ dispatch / broadcast / pipeline / fanout / consult │
│ handoff_guards (depth 5, visits 2) · ReliabilityRegistry (breakers/retry) │
│ FanOutBus tri-state HITL · NullBus fail-closed │
│ TaskStore (SQLite|Postgres) · SSE bridge · checkpoint_manager │
└───────────────────────────────┬──────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────────┐
│ DATASTORES │
│ ConfigStore (settings / vault / Soul) · SessionManager · checkpoints │
│ hitl_gates.db · turn journal / agent_artifacts.db │
│ TaskStore · cron.db · memory_state.db + memory_ops.db (split, do not merge) │
│ WorkspaceStore · optional Postgres (KAZMA_PG_TABLES, not whole-DB) │
└──────────────────────────────────────────────────────────────────────────────┘

kazma/
├── serve.py # Alternate WebUI entry (hardened secrets)
├── pyproject.toml # Workspace package + extras [rag,postgres,…]
├── kazma.yaml # Product defaults
├── kazma.local.yaml.example # Local overrides template
├── docker-compose.yml # Single-node container
├── docker-compose.postgres.yml
├── docker-compose.ha.yml # Multi-replica + optional nginx
├── Dockerfile # [rag,postgres] image
├── deploy/nginx-ha.conf
├── scripts/ # backup, restore, migrate, smoke, entrypoint
├── docs/ # Docusaurus site + audits + ops + this map
├── tests/ # Root regression suite
├── loadtests/ # k6/locust
├── examples/ # Sample skills + demos
├── kazma-core/ # Brain, swarm, tools, safety, db
├── kazma-ui/ # FastAPI web + static + SSE
├── kazma-gateway/ # Platform adapters + slash + routers
├── kazma-tui/ # Textual dashboard/IDE
├── kazma-cli/ # `kazma` CLI
├── kazma-skills/ # Native skill packages + YAML manifests
├── kazma-data/ # Runtime DBs (local; do not commit secrets)

2.2 Package: kazma-core/kazma_core/ (brain)

Section titled “2.2 Package: kazma-core/kazma_core/ (brain)”
ModulePurpose
__init__.pyPackage exports
agent_runner.pyKazmaAgent lifecycle, graph ensure, turn timeout, Postgres/SQLite checkpointer
audit_logger.pyStructured security/ops audit events
authority.pyContext authority / compaction threshold helpers
authorization_flow.py[LIBRARY] Cross-division approval flows
compaction.pyMessage history compaction
config_loader.pyMerged YAML (kazma.yaml + kazma.local.yaml)
config_schema.pyPydantic config models
config_store.pyRuntime settings SoT (SQLite or Postgres)
constants.pyShared constants (danger tool lists — prefer CANONICAL)
cost_breaker.pySession budget circuit breaker
cultural_context.py / cultural_context_enrichment.pyCultural prompt enrichment
dialect_detector.pyArabic dialect detection
division_sandbox.py[LIBRARY] Division-scoped sandbox
exceptions.pyShared exception types
git_identity.pyBot git author identity for commits
google_llm.pyGoogle/Vertex LLM paths
http_pool.pyShared httpx client pool
kuwaiti_tokenizer.py / msa_tokenizer.pyArabic tokenization helpers
language_lock.pyResponse language lock
llm_provider.pyOpenAI-compatible LLM client, retries, reconfigure aclose
logging_config.pyLogging setup
majlis.py[LIBRARY] Cultural orchestrator shell
mcp_client.pyLegacy/alternate MCP client helpers
metrics.pyMetrics helpers
model_registry.py / model_registry_store.pyProvider/model resolution + persistence
pacing.pyReply pacing for gateways
paths.pyData path resolution
permissions.py[LIBRARY] YAML permission manager
personalities.pyPersonality prompts
providers.pyProvider catalog helpers
rbac.pyDivision RBAC engine (enterprise)
retry.pyGeneric retry utilities
router.py / routing_engine.pyRouting helpers / unified worker routing
service_container.pyDI container
settings_manager.py / settings_mcp.pySettings facades
shutdown.pyGlobal graceful-shutdown flag
state.pyAgent state types
summarizer.pySummarization utility
telemetry.pyTelemetry collection
tenant_context.pyContextVar tenant_id
time_travel.pyCheckpoint time-travel helpers
token_counter.py / tokenizer.pyToken counting
tone_adapter.pyTone adaptation for platforms
tracing.pyLangfuse/tracer integration
url_utils.pyURL helpers
agent/
agent/graph_builder.pyWires the graph; does not contain HITL/retry bodies
agent/graph_supervisor.pySupervisor node + _call_llm_with_retry (transient only)
agent/graph_tool_worker.pyCommitment gate + HITL interrupt() + execute
agent/graph_respond.pyRespond node; skips synthesis on turn_failed
agent/hitl_supersede.pyCancel pending HITL on new turn
agent/artifacts.pyDurable proposals/scratchpad (not graph state)
agent/nonstop.pyNonStopConfig schema & settings layer
agent/pipeline_schema.pyPipeline-related schemas
agent/resilient_chat.pyResilient chat wrapper with retries, failover & ledger
agent/state.pySupervisor state / NodeName; scratchpad merge reducer
agent/sub_agent.pySubAgentManager spawn + auto_deny HITL
agent/supervisor_watchdog.pySupervised execution envelope & stall watchdog
agent/tool_registry.pyLocalToolRegistry SoT + built-in tools (file_append)
agent/turn_input.pyBuild messages from checkpointer + user turn
agent_skills/Agent Skills install/discover/parse
cron/scheduler.py SQLite cron + concurrency + shutdown
db/Postgres backend selection + pool + helpers
delegation/[LIBRARY] Parallel multi-agent design
docs/[LIBRARY] Doc generator
hub/Skill hub API/CLI/registry/validator
ide/IdeService, env_context, workspace_scope
mcp/AsyncMCPManager + UnifiedToolExecutor + classify_mcp_tool
memory/V2 cognitive engine (recall.py, memory_state.db / memory_ops.db, worker_bootstrap.py — eight schedulers)
models/Provider discovery (SSRF-guarded), model router
observability/ops_alerts, daily digest, firing ledger
safety/hitl, hitl_gates.py, commitment/, yolo, prompt_fence
security/ssrf, ssrf_pin.py (pin-IP), vault, web_sessions, platform_rbac, oidc
stores/workspaces, bookmarks
swarm/Full orchestration (see §3.3)
system/installer, maintenance, runtime_manager
tools/Standalone tool implementations + swarm ShellTool registry
voice/STT/TTS/VAD
chaos/Chaos testing hooks
cli/Wizard helpers
ModulePurpose
app.pyFastAPI factory, lifespan, gateway/cron/swarm boot, router mount
auth.pySecret/session/API-token auth, tenant middleware, RBAC path gates
saas_api.pyMulti-user + tenants admin API
session_manager.pyChat sessions (SQLite|Postgres)
sse_chat/Primary SSE chat stream + YOLO intercept + HITL frames (package)
turn_runtime.py / turn_document.pyTurn Delivery V2 — close_turn is the only closer
hitl_status.py / hitl_gate_bridge.pyGate registry readers for Web
sse_utils.pySSE framing helpers
chat.pyChat page + WebSocket chat path
ide_api.py/api/ide/* file/run/git/swarm
workspace_api.pyWorkspace web routes
settings.pySettings HTML/API (masked secrets)
dashboard.pyDashboard + session list APIs
swarm_panel/*Swarm UI APIs (tasks/workers/metrics)
swarm_sse.pySwarm task event streams
agents.py / mcp_ui.py / skills_ui.pyFeature pages + APIs
providers.py / models_route.py / models.pyProvider/model management UI
health.pylive/ready public; /health/details sensitive (L-1)
metrics.pyPrometheus metrics
routes_direct/Login, approve, system, gateway wiring, OIDC, many APIs
routes_voice.py / routes_voice_ws.pySTT/TTS REST + WS
routes_chaos.pyChaos UI APIs
telemetry_route.pyTelemetry SSE/snapshot
gateway_monitor.pyGateway status start/stop
hitl_approval.pyHITL API helpers
i18n/en/ar translations (one catalog module per UI section)
services.pyService status helpers
static/js/*Alpine/UI modules (chat, ide, swarm, settings, streaming)
templates/*Jinja pages (chat, ide, swarm, settings, login, …)
ModulePurpose
gateway.pyAdapter orchestration queue
adapters/telegram*.pyTelegram bot + bus + callbacks + STT
adapters/discord*.py / slack*.pyDiscord/Slack adapters + HITL buses
agent_handler/graph.pyInbound message → agent graph
agent_handler/hitl.pyGateway HITL ownership fail-closed
agent_handler/commands.pySlash + /ide commands
agent_handler/store.pyPlatform session isolation
agent_handler/swarm_*.pySwarm dispatch/output from gateway
routers/github*.pyGitHub OAuth, clone, API
routers/workspaces.py / workspace.pyWorkspace CRUD + prod root confine
routers/git.py / bookmarks.py / pipeline.pyGit ops, bookmarks, pipelines
stores/checkpoint.pyCheckpointManager + Postgres/SQLite saver
stores/sqlite.pyGateway session SQLite store
mcp_server.pyIDE MCP server bridge
slash_commands.py / suggestions.pyCommand catalog / UX
swarm_notify.pyOpt-in Telegram notify (maybe_notify_dispatch when SWARM_BOT_TOKEN is set)
telegram_format.py / typing_keepalive.py / rate_feedback.pyPlatform UX helpers

kazma-cli: main (serve/wizard/status), gateway, swarm, update, project, completions, banner, migrate.

kazma-tui: Textual app, chat/dashboard/editor/files/swarm screens, widgets (HITL modal, palette, toasts).

kazma-skills/native/*: Packaged skills (git, cron, crawler, vault, health, code-review, …) + YAML manifests.

No kazma-memory package. Arabic tokenizer is kazma_core/msa_tokenizer.py; V2 memory is kazma_core.memory.

PathPurpose
scripts/backup_kazma.py / restore_kazma.pyDR zip backup/restore
scripts/migrate_sqlite_to_postgres.pyFull store migration
scripts/smoke_production.pyProduction smoke suite
scripts/docker-entrypoint.shOptional auto-migrate then uvicorn
deploy/nginx-ha.confMulti-replica reverse proxy sample

ConcernLocationBehavior
Graph buildgraph_builder.py wires; bodies in graph_supervisor / graph_tool_worker / graph_respondReAct loop; max tool iterations
HITL interruptgraph_tool_worker.tool_worker_node + hitl_configDanger tools interrupt(); registry row in hitl_gates.db
ResumePOST /api/approve/{thread_id}, gateway /hitlClaim registry + Command(resume=…)
Double-gate prevent_hitl_approved_ctx ContextVarexecute() must not mint a second web gate (H-8)
Turn assemblyturn_input.pyCheckpointer history + user message
Sub-agentssub_agent.py + build_child_graphAuto-deny danger, timeout, tool filter
Persistenceagent_runner / stores/checkpoint.pySQLite or AsyncPostgresSaver
HITL supersedehitl_supersede.pyNew user message cancels stale interrupt
PathModuleNotes
Agent toolsLocalToolRegistryfile_, shell_exec, python_exec, memory_, config_*, spawn_agent(s), context_info
MCPmcp/manager.pyforce_danger=True; prod HITL for non-allowlist
code_exectools/code_exec.pyDocker network=none preferred; import blocklist local
shell_exectool_registryshlex + asyncio.to_thread(subprocess…) (Windows SelectorEventLoop — never bare create_subprocess_exec); _EXEC_CAPABLE_ARGS; env scrub; HITL
IDEide/service.pyAll mutations via registry execute

Danger SoT: safety/hitl.CANONICAL_DANGER_TOOLS → swarm _EXTENDED_DANGER.

ComponentModule
Orchestratorswarm/engine.py
Patternspatterns.py, broadcast.py, consultation.py
Handoff limitshandoff_guards.py (depth 5, visits 2)
Reliabilityreliability.py, reliability_registry.py
Dispatchworker_dispatch.py, dispatch_inner.py
Persistencetask_store.py (SQLite|Postgres)
Lifecycletask_lifecycle.py, task_control.py
HITL pipelinecheckpoint.py, checkpoint_manager.py
Busbus.py + platform adapters; FanOut tri-state HITL
Autoscalerautoscaler.py (maybe_scale only on NoCapableWorkersError)
Gate registrycheckpoint_manager._gate_register_pipeline / _gate_settle_pipeline
MemoryV2 recall.search via phonebook (fenced); not a 4-layer adapter
ServiceModuleCycle
Swarm message busswarm/bus.pyPub approval/report/alerts; FanOut tri-state
Cron schedulercron/scheduler.pyMust have graph_builder=; delivery_target at schedule time
Memory workermemory/worker_bootstrap.pyEight schedulers (6h backup, 6h sleep, 24h reconsolidation, 15m GC, digest, ledger, drill, session purge)
SSE telemetrytelemetry_route.pyStream until is_shutting_down
SSE chatsse_chat/ packagePer-turn stream; journal projection
Swarm SSEswarm_sse.py / panelTask events
Gateway queuegateway.pyAdapter inbound → handler
Ops alertsobservability/ops_alerts.pyIn-app FanOut + Telegram-direct; Guard is a separate process
Shutdown signalshutdown.pyGlobal flag for loops
StoreBackendNotes
ConfigStoreSQLite WAL / Postgres kazma_settingsVault refs; Soul key self_improvement.agent_evolution
SessionManagerSQLite / kazma_chat_sessionsLRU warm cache + lock
TaskStoreSQLite / Postgres tablesWAL + json_each workers filter
Checkpointsaiosqlite / AsyncPostgresSaverHITL execution truth
HITL gateshitl_gates.db (SQLite WAL)HITL decision truth; single-process
Artifactsagent_artifacts.dbDurable proposals; graph is read-through
V2 memory hotmemory_state.dbBeliefs, episodes, entities — do not merge with ops
V2 memory opsmemory_ops.dbDurable queue + audit
Croncron.dbReminders; not SessionStore at fire time
FTS5SQLite + lockKeyword memory (V2)
Vector / KBsqlite-vec / pgvector / Chroma optionalIsolated from chat recall
WorkspaceStoreSQLiteRepo identity columns
SurfaceTech
App factoryFastAPI + lifespan shutdown drain
AuthSecret / opaque session / API token / OIDC
ChatSSE is the only turn transport (/api/chat/stream); WS is telemetry / cursor only; client projects TurnDocument
IDE/ide page + /api/ide/* + CodeMirror ide.js
Swarm panel/swarm + /api/swarm/*
SettingsAlpine + mask_deep + kazmaConfirm/kazmaPrompt
Health/health/live + /health/ready public; /health/details auth (L-1); /health/deep canary

Auth scope: Open = always open; Secret = KAZMA_SECRET / session / token when secret set; Admin = platform role admin (multi-user).

MethodEndpoint PathAuth ScopeHITL / DangerDescription & Module
GET/healthOpen—Basic health (routes_direct)
GET/health/liveOpen—LB liveness (health.py)
GET/health/readyOpen—Readiness + DB ping (health.py)
GET/health/detailsSecret—Debug details — not public (Wave 8 L-1; leaks model/MCP) (health.py)
GET/health/deepOpen—Real roundtrip canary, TTL 30s (health.py)
GET/api/statusOpen—App status
GET/api/telemetryOpen—Light telemetry
GET/loginOpen—Multi-mode login page
GET/POST/api/auth/*Open (login/status/oidc)—Auth bootstrap (routes_direct)
GET/api/auth/meSecret—Principal
POST/api/chat/streamSecretGraph HITLSSE agent chat (sse_chat)
WS/ws/chat (if mounted)SecretGraph HITLWS chat (chat.py)
POST/api/approve/{thread_id}SecretResume interruptHITL approve/deny/yolo scope
GET/POST/api/ide/*SecretBus HITL on mutateIDE backend (ide_api)
GET/POST/api/swarm/*SecretPipeline HITLSwarm control panel
GET/api/swarm/tasks/{id}/streamSecret—Task SSE
CRUD/api/settings/*Secret/Admin—Settings (settings.py)
CRUD/api/saas/*Admin—Users/tenants (saas_api)
GET/POST/api/mcp/*Secret/AdminMCP force_dangerMCP server mgmt
GET/POST/api/skills/*Secret—Skills UI
GET/POST/api/agents/*Secret—Agents status/traces
GET/POST/api/models/*, /api/providers/*SecretSSRF on discoveryModels/providers
GET/POST/api/workspace*, /api/workspaces*SecretPath confineWorkspaces
GET/POST/api/github/*Mixed (OAuth open callback)—GitHub OAuth/API
GET/POST/api/git/*Secretshell HITLGit ops
POST/api/voice/*Secret—STT/TTS
GET/api/gateway/*Secret—Gateway monitor
GET/metricsSecret—Prometheus
POST/api/webhooks/telegramWebhook secretAgent toolsTelegram webhook
GET/, /chat, /ide, /swarm, …Pages: shells open; data via API—SPA-like pages
GET/settings, /dashboardSecret (HTML gated)—Admin pages

/health/details is in SENSITIVE_PREFIXES. /health/live and /health/ready stay public.

Tool / Command NameTypeDefault DangerSandboxModule
file_read / file_list / file_search / codebase_searchLocalsafeWorkspace scopetool_registry + code_index
file_write / file_deleteLocaldangerWorkspace + HITLtool_registry
shell_execLocaldangerAllowlist + env scrub + HITLtool_registry
python_exec / code_execLocaldangerDocker jail / blocklist + HITLcode_exec
memory_search / memory_storeLocalsafe / writeVector/FTStool_registry
config_read / config_saveLocalsecrets masked / blocked sensitiveConfigStoretool_registry
spawn_agent / spawn_agentsLocaldanger (swarm extended)SubAgentManagertool_registry / sub_agent
current_datetime / context_infoLocalsafe—tool_registry
read_url / web_searchLocal tools pkgSSRF + pin-IPvalidate_url + PinHostAsyncTransport (no proxy); assert_peer_publictools/read_url, security/ssrf_pin.py
MCP tools (dynamic)MCPdanger/unknown force HITL; prod non-allowlist HITLMCP server processmcp/manager
kazma serveCLI—Auth required non-loopbackkazma_cli/main
kazma gateway *CLI—HTTP to UIgateway.py
kazma swarm *CLIdispatch may HITLHTTP APIswarm.py
kazma update / project / docsCLI—localCLI modules
/ide * slashGateway cmddanger via toolsIdeServicecommands.py
/yoloChat/SSEbypass HITL if allowedyolo.pysse_chat / gateway
/hitl approve|denyGatewayresumehitl.pyagent_handler

Section 5: Configuration & Environment Master Reference

Section titled “Section 5: Configuration & Environment Master Reference”
Variable NameDefaultRequired in ProdPurpose & Security Scope
KAZMA_SECRETgenerated (loopback)Yes (non-loopback)Shared admin secret / API auth
KAZMA_HOST127.0.0.1 (CLI/serve)Set explicitlyBind address
KAZMA_PORT9090 CLI / 8000 DockerNoListen port
KAZMA_TRUST_LAN0Keep 0LAN auto-cookie
KAZMA_PRODUCTIONunsetYes (1)Force Docker code_exec, YOLO off, vault required, workspace root
KAZMA_VAULT_KEYauto-dev onlyYesEncrypt secrets at rest
KAZMA_ALLOW_YOLOunsetNo (off)Opt-in YOLO under production
KAZMA_YOLO_TTL_SECONDS1hNoYOLO expiry
KAZMA_CODE_EXEC_DOCKERautoforcecode_exec jail policy
KAZMA_CODE_EXEC_IMAGEpython:3.12-slimNoJail image
KAZMA_WORKSPACEdata/workspaceNoDefault workspace pin
KAZMA_WORKSPACE_ROOTunsetYes if prodConfine workspace paths
KAZMA_CLONE_DIR~/kazma-reposNoClone root
KAZMA_DATABASE_URLunsetMulti-replicaPostgres shared state
KAZMA_DB_BACKENDautoOptional forcepostgres / sqlite
KAZMA_PG_POOL_MIN/MAX1 / 10NoPool sizing
KAZMA_PG_POOL_TIMEOUT5NoSeconds to wait for a free pool connection
KAZMA_PUBLIC_URLunsetOAuth/OIDCFixed public base URL
KAZMA_JWT_SECRETunsetMulti-tenant JWTVerified tenant claims
KAZMA_CORS_ORIGINSlocalhost listProd: your originCORS allowlist
KAZMA_OPAQUE_SESSIONS1Keep onOpaque browser sessions
KAZMA_SESSION_TTL_SECONDS14dNoSession cookie TTL
KAZMA_TURN_TIMEOUT_SECONDS600NoGraph wall timeout
KAZMA_MCP_SAFE_ALLOWLISTemptyOptionalMCP tools skip HITL (prod)
KAZMA_ALLOW_PRIVATE_LLMunsetNoPrivate URL discovery opt-in
KAZMA_MULTI_USERunsetSaaSForce multi-user mode
KAZMA_OIDC_*unsetSaaS SSOOIDC issuer/client/secret/redirect/role claim (id_token verified; no unverified fallback)
KAZMA_PGVECTORauto on Postgres DSNNo0 keeps sqlite-vec; unset auto-selects pgvector for dense recall
KAZMA_E2B_API_KEY / E2B_API_KEYunsetUntrusted codeFirecracker python_exec; KAZMA_E2B=0 kill-switch
KAZMA_TEMPORAL_HOSTunsetMulti-hour swarmTemporal wrap of swarm dispatch; KAZMA_TEMPORAL=0 kill-switch
KAZMA_CODE_INDEXonNo0 disables symbol index / codebase_search
KAZMA_PROVIDER / KAZMA_MODELunsetNoBoot provider/model
KAZMA_API_KEY / OPENAI_API_KEYunsetProviderLLM keys (prefer ConfigStore/vault)
TELEGRAM_BOT_TOKENunsetTelegramAdapter
TELEGRAM_WEBHOOK_SECRETgenerated if emptyWebhookInbound authenticity
DISCORD_BOT_TOKEN / SLACK_*unsetPlatformAdapters
GITHUB_TOKEN / GITHUB_OAUTH_*unsetGitHub featuresPAT / OAuth app
KAZMA_VECTOR_*path/collection/modelRAGVector memory
KAZMA_EMBED_API_KEYunsetRemote embedEmbeddings
KAZMA_BOT_NAME / EMAILdefaultsNoGit identity
KAZMA_DEMO_MODEunsetNoDemo shortcuts
KAZMA_CHAOS_ENABLEDunsetNoChaos routes
KAZMA_ENVunsetproduction for error redactionError detail policy
KAZMA_AUTO_MIGRATE0NoDocker entrypoint migrate
KAZMA_SMOKE_BASElocalhost:9090NoSmoke script base URL
SWARM_BOT_TOKEN / SWARM_CHAT_IDunsetOptionalSwarm notify bot

Section 6: Production Readiness Verification (Remediation Alignment)

Section titled “Section 6: Production Readiness Verification (Remediation Alignment)”

Cross-reference: docs/audits/REMEDIATION_PLAN_2026-07-21.md (all WP 0.x–4.x marked complete in code).

WPTarget filesStatus
0.1 serve secretserve.pyRemediated — no assign of known secret; refuse bad; generate/loopback
0.2 CLI bindkazma-cli/kazma_cli/main.pyRemediated — default 127.0.0.1; non-loopback needs secret
0.3 composedocker-compose.yml, DockerfileRemediated — /health, vector path, prod env
WPTarget filesStatus
1.1 shutdownkazma_ui/app.py _on_shutdownRemediated
1.2 reject activeswarm/engine.py reject_checkpointRemediated
1.3 cancel finalizetask_control.py, engine._finalize_taskRemediated
1.4 breaker probereliability.py, worker_dispatch.pyRemediated
1.5 LLM aclosellm_provider.py reconfigureRemediated
1.6 NullBusswarm/bus.pyRemediated (False)
1.7 YOLO prodsafety/yolo.py, SSE/routesRemediated (+ KAZMA_ALLOW_YOLO)
WPTarget filesStatus
2.1 discovery SSRFmodels/discovery.pyRemediated
2.2 code_exectools/code_exec.pyHardened
2.3 shell policyagent/tool_registry.pyHardened
2.4 auth default-denyauth.pyRemediated
2.5 croncron/scheduler.pyRemediated
2.6 HITL ownershipagent_handler/hitl.py, routes_directRemediated
2.7 workspace rootrouters/workspaces.pyRemediated
AreaTargetsStatus
Opaque sessions / RBAC / OIDCweb_sessions.py, platform_rbac.py, oidc.py, saas_api.pyShipped
Postgres cutoverconfig_store.py, session_manager.py, task_store.py, checkpoint.py, agent_runner.pyShipped
DR / HA / smokescripts/*, docker-compose.ha.yml, docs/ops/*Shipped

Open residual risks (not unfixed blockers — residual by design)

Section titled “Open residual risks (not unfixed blockers — residual by design)”
RiskSeverityNotes
Post-HITL shell/code still powerfulHigh residualIntended after human approve; YOLO amplifies
Untrusted MCP trust: trustedMediumOperator footgun
Empty secret open mode on loopbackLow–MediumDocumented DX
Dual docs trees / unwired librariesLow maintainabilityCleanup plan
Multi-primary multi-region DBN/AInfra product, not app
Terminal window
# Security-critical automated sample
& .venv\Scripts\python.exe -m pytest tests/test_auth_middleware.py tests/test_hitl_wiring.py tests/test_mcp_hitl.py tests/test_pg_store_dual_backend.py -q
# Live smoke (server running)
& .venv\Scripts\python.exe scripts\smoke_production.py --base http://127.0.0.1:9090 --secret $env:KAZMA_SECRET

Section 7: Feature Inventory Highlights (including recent)

Section titled “Section 7: Feature Inventory Highlights (including recent)”
Feature areaModules / surfaces
Command Center / swarm liveswarm.html, swarm.js, swarm_panel/*, swarm_sse.py
IDE CodeMirror editoride.html, ide.js, ide_api.py, ide/service.py, tools/file_apply_patch.py
SSE streaming chatsse_chat/ package, chat.js projector, turn_runtime.close_turn
HITL Gate Registrysafety/hitl_gates.py, hitl_status.py, chat.js _serverGates
WebSocket voiceroutes_voice_ws.py, voice.js
Document Intelligencedocuments/*, documents_api.py, documents.html/js, gateway /documents, document_platform skill, TUI DocumentsPanel, scripts/certify_documents.py
Guardian healthhealth.py, cron, circuit breakers, cost_breaker
Cultural/Arabicdialect, tokenizers, i18n ar, tone/pacing, majlis library
Multi-agentSwarmEngine live; delegation/* library-only
SaaS multi-userlogin multi-mode, /api/saas, header principal
Postgres multi-replicadb/*, dual stores, HA compose; document jobs + catalog on KAZMA_PG_TABLES when that backend is in use

DocRole
AGENTS.mdBuild contract (invariants §1–§33)
docs/docs/guide/architecture.mdNarrative architecture
docs/docs/guide/swarm-orchestration.mdSwarm patterns + HITL bus
docs/audits/AUDIT_DEEP_2026-09-01_EXEC.mdBinding industrial audit (waves 0–8)
docs/audits/AUDIT_DEEP_STRUCTURE_2026-08-19.mdDeep-structure audit
docs/audits/AUDIT_PRODUCTION_READINESS_2026-07-21.mdHistorical production audit
docs/audits/AUDIT_DOCUMENT_CERTIFICATION.mdDocument Intelligence cert report
docs/docs/guide/document-intelligence.mdDocument product guide
docs/audits/UNWIRED_INVENTORY.mdLibrary-only packages
docs/docs/ops/diagnosis-map.mdMulti-path diagnosis
docs/plans/GUARD_OPS_ALERTING_CAUSE_QUALITY.mdDeferred Guard/ops alerting

Refreshed 2026-09-02. Invariants live in AGENTS.md; this file is the module map. Do not list a kazma-memory package.