Enterprise AI Brain
On-premise enterprise AI agent where every write passes an approval gate.
- Multi-agent systems
- Security & governance
- Role
- Architect and engineer, consulting engagement
- Client
- Enterprise client (confidential)
- Timeline
- May 2026
- Status
- Prototype
No public screens for this system. The interactive architecture below walks through how it works.
- tests passing, up from 178 before the review fixes
- 277
- tests passing, up from 178 before the review fixes
- critical wiring gaps found by independent review, all closed
- 7
- critical wiring gaps found by independent review, all closed
- lines of source / test Python
- 4,817 / 6,311
- lines of source / test Python
- commits in the 4-day build window
- 179
- commits in the 4-day build window
The problem
The client wanted an AI layer that reads live operational data from its own databases and APIs, understands the company's vocabulary, raises alerts on its own and proposes actions. The data could not leave the company's servers, so a hosted LLM product was out.
An agent that can write to business systems also needs authorisation and an audit trail. Generic agent frameworks offer neither data sovereignty nor governance by default.
Architecture
Ask in plain language
The operator asks a question in the CLI. The prompt builder injects the company's semantic memory and only the top-K tools retrieved by embedding, which keeps the prompt small.
- Service
- Data
- AI model
- External
Hard problems I solved
A gate that code cannot route around
Governance only holds if no code path reaches a tool without the gate. One new helper that calls the tool registry directly would skip approval and audit, and nothing would notice.
Approach. A static-analysis test walks the syntax tree of every source file and fails CI on any call to the registry's dispatch outside an allowlist of (file, function) pairs, and on any aliasing of it. Falsification tests plant a bypass in a temp folder to prove the scanner actually fires. The read-only dispatcher refuses mutating tools loudly instead of silently.
Tamper-evident audit under concurrent writers
Each audit row hashes the previous row's hash. Two writers that read the same previous hash at the same time fork the chain, and verify_chain() then reports tampering that never happened.
Approach. The append opens with BEGIN IMMEDIATE, which takes SQLite's write lock up front so the select-then-insert pair is atomic. An interleaved-writer test covers the race, and a source guard fails if the BEGIN IMMEDIATE is ever removed.
Letting a model touch SQL and HTTP safely
The first read-only check used a regex, which CTE-wrapped writes and leading comments slipped past. The review also found SQL injection through table and column names generated by the model and interpolated into queries.
Approach. Write detection now walks the sqlglot AST of every statement for insert, update, delete, DDL and merge nodes; ATTACH and PRAGMA writes are matched separately, and anything unparseable counts as a write. Identifiers go through validate_identifier. The REST connector denies private, loopback, link-local and cloud-metadata ranges and resolves the hostname before the IP check, so a DNS name pointing inside cannot slip through.
The demo passed with zero alerts
The first monitor ran one gap detector across all items. A stoppage planted on a single item was invisible in the aggregate, and the demo still reported success with 0 alerts fired.
Approach. Detection now runs per partition. The demo script fails on zero alerts, every alert must carry its event IDs, and a parameterised test checks the detectors on nominal data.
Zero false positives on 1,000 nominal samples, asserted in the test suite.
Built, tested, and not wired
After the first build every module passed its unit tests, but an independent review traced the production call paths and found 7 critical disconnects: the approval queue never received packets, chat ran without the gate, memory, retriever or connectors, the policy file was never loaded, memory edits never changed the file, agent creation never spawned anything, the monitor could not see the anomaly, and model-supplied identifiers were open to SQL injection.
Approach. A 37-unit remediation plan in 5 chunks, with a reviewer checkpoint after each chunk told to verify each fix from the production entry point, plus a 13-item backlog. The limitations document was rewritten to match what is really built.
Tests went from 178 to 277 passing, with ruff and mypy --strict clean.
Onboarding a schema the model has never seen
The agent has to map unknown tables to business processes. A confident wrong mapping would quietly poison the memory every later answer depends on.
Approach. The model states its confidence as high, medium or low; values outside that set are coerced to low with the rationale amended. The operator confirms low-confidence mappings first, and if more than 40% are low the tool flags that a sector adapter pack is needed. Later memory edits from the reflector are proposals, de-duplicated by content hash, that the operator approves or rejects.
Code
The verdict is audited before anything executes, and only ALLOW reaches the registry. REQUIRE_APPROVAL raises so the loop can queue the packet for a human.
async def gated_dispatch(packet: IntentPacket, registry: ToolRegistry, gate: Gate,
audit: AuditLog | None = None) -> ToolResult:
"""Dispatch a mutating tool call through the governance gate."""
decision = gate.evaluate(packet)
if audit is not None:
await audit.append(kind="tool_call", payload={
"tool": packet.tool, "args": packet.args,
"verdict": decision.verdict, "reason": decision.reason,
"caller": packet.caller, "caller_channel": packet.caller_channel,
})
if decision.verdict == "ALLOW":
return await registry._dispatch(packet.tool, packet.args)
if decision.verdict == "REQUIRE_APPROVAL":
raise GatePendingApproval(decision, packet) # loop pushes it to the PendingQueue
raise GateDenied(decision)# (file, function) pairs allowed to call ToolRegistry._dispatch / dispatch directly.
ALLOWED: set[tuple[str, str]] = {
("core/dispatch.py", "gated_dispatch"),
("core/dispatch.py", "non_mutating_dispatch"),
}
def _scan_dispatch_callers(root: pathlib.Path) -> list[str]:
offenders: list[str] = []
for path in root.rglob("*.py"):
rel = path.relative_to(root).as_posix()
if rel in SKIP_FILES:
continue
tree = ast.parse(path.read_text(), filename=str(path))
for node in ast.walk(tree):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
if node.func.attr in TARGET_METHOD_NAMES:
fn = _find_enclosing_function(tree, node)
fn_name = fn.name if fn else "<module-level>"
if (rel, fn_name) not in ALLOWED:
offenders.append(f"{rel}:{node.lineno} in {fn_name}")
return offenders
def test_scanner_flags_synthetic_dispatch_caller(tmp_path: pathlib.Path) -> None:
(tmp_path / "sneaky.py").write_text("async def evil(registry):\n return await registry._dispatch('do_thing', {})\n")
assert any("sneaky.py" in o and "evil" in o for o in _scan_dispatch_callers(tmp_path))def _compute_hash(prev_hash: str, payload_json: str, ts: str) -> str:
raw = prev_hash + "|" + payload_json + "|" + ts
return hashlib.sha256(raw.encode()).hexdigest()
async def append(self, kind: str, payload: dict[str, Any]) -> AuditEvent:
payload_json = json.dumps(payload, sort_keys=True)
ts = datetime.now(timezone.utc).isoformat()
# BEGIN IMMEDIATE grabs the SQLite RESERVED lock up-front so the
# SELECT-then-INSERT executes as a single atomic transaction.
await self._db.execute("BEGIN IMMEDIATE")
try:
async with self._db.execute(
"SELECT hash FROM audit_events ORDER BY id DESC LIMIT 1") as cur:
row = await cur.fetchone()
prev_hash = row[0] if row else "GENESIS"
h = _compute_hash(prev_hash, payload_json, ts)
await self._db.execute(
"INSERT INTO audit_events(kind, payload_json, prev_hash, hash, ts) VALUES(?,?,?,?,?)",
(kind, payload_json, prev_hash, h, ts))
await self._db.commit()
except Exception:
await self._db.rollback()
raise
...What I built
Agent runtime
- Single tool-calling loop with no agent framework, OpenAI function format through a local LiteLLM proxy
- Read-only tools dispatch directly; mutating tools only through the governance gate
- Stop conditions (iterations, wall-clock, manual halt) and graceful handling of malformed tool JSON
- Background agents created from a plain-language instruction, with a kill switch under 5 s
Governance
- Three-check gate: JSON-schema params, default-deny policy with role allowlist, sliding-window rate limit
- Approval queue; 'approve next --execute' re-runs the call through the same gate
- SHA-256 hash-chained audit log with a verify_chain() replay
- Read-only SQL guard on the sqlglot AST and an SSRF-safe REST connector
Memory and onboarding
- Schema scan plus LLM mapping of tables to business processes, with verbalised confidence
- Operator confirms low-confidence mappings first; a default-deny policy file is written
- 4 memory tiers: context window, SQLite FTS5 episodic, human-approved semantic file, markdown skills
- Reflector proposes memory edits; the operator approves or rejects, with history kept
Monitoring
- Gap detector on the trailing p98 inter-event gap, computed per partition
- ADWIN drift detector and k-sigma count detector against a historical baseline
- One-paragraph LLM explanation per alert, degrading gracefully if the model is down
- Telegram alerts; monitor-proposed actions go through the same gate
Stack
Runtime
- Python 3.12
- asyncio
- click + rich CLI
- pydantic
Models
- LiteLLM proxy (swappable model)
- MiniMax-M2.7
- fastembed (bge-small-en-v1.5)
Data and governance
- SQLite (WAL, FTS5)
- aiosqlite
- sqlglot
- jsonschema
Monitoring
- river (ADWIN)
- Gap and k-sigma detectors
- Telegram Bot API
Quality
- pytest
- hypothesis (property tests)
- ruff
- mypy --strict
How it was built
Built in four days with Claude Code from a written plan: a 179-unit test-driven execution queue, one unit per subagent, followed by an independent code-reviewer agent pass on the whole build. I wrote the plans, the remediation after the review and the limitations document, and verified each fix against the production call path; 34 of the 181 commits carry a Claude co-author trailer.
Built under NDA for an enterprise client: the client, its sector, its data and the source repository are withheld, and code is shown only as short excerpts.