Skip to content
mfalme0Public

About

Evidence-driven AI SRE agent for homelabs. Investigates incidents with typed, permission-gated tools, shows its work, and requires human approval for risky actions.

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

NEXUS — Autonomous Homelab Operations Agent

An AI SRE for your homelab that has to show its work.

NEXUS investigates incidents the way a careful human operator would: it observes the real infrastructure, collects evidence with typed tools, forms hypotheses, tests them, and only then explains a root cause. Risky actions need human approval. Every conclusion must be backed by something it actually observed.

Core principle: NEXUS must never confuse sounding confident with being correct.

When it can't prove something, the correct answer is:

"I could not verify disk usage because the host did not respond."

...not "Disk usage is normal."


Why this is not another chatbot wrapper

Most "AI ops" demos ask an LLM to guess. NEXUS is built around the opposite constraint. It embodies four hard rules:

Rule What it means in practice
Evidence over vibes Confidence is derived from observations, contradictions, and required-evidence coverage — never invented by the model.
Allowlist, not denylist No arbitrary bash -c, sudo, or rm -rf. Every capability is a typed tool with a permission class.
Approval before risk REQUIRES_APPROVAL actions cannot run until a human says yes. The authorization layer lives outside the LLM.
Explainable, not opaque The console shows reasoning summaries and evidence — never hidden chain-of-thought.

This is the difference between a system that can restart a container and a system that can show you why it was safe to restart, what evidence supported it, and proof the service recovered.


What an investigation looks like (target design)

You:            "Immich is down."

NEXUS:  classify    → SERVICE_UNAVAILABLE
        context     → Immich, its host, PostgreSQL + Redis deps,
                      recent changes, recent related incidents
        evidence    → container status, recent logs, dependency health,
                      host disk/memory
        hypothesis  → "Immich's container is in a crash loop caused by
                       PostgreSQL refusing connections after disk filled."
        test        → check disk usage + Postgres logs on the same host
        root cause  → storage exhaustion on the host filesystem
        remediation → prune stale Docker build cache (LOW_RISK)
        safety      → disk change → REQUIRES_APPROVAL
        approve     → you click Approve
        execute     → run allowlisted action
        verify      → Immich healthcheck passes, logs stop repeating
        close       → full trace + outcome recorded for evaluation

The reasoning graph loops whenever evidence is insufficient — it does not invent a root cause just to finish.


Project status

NEXUS is built in verifiable phases. Nothing below is claimed until it is tested and running.

✅ Phase 1 — Foundation (complete)

Real, working, and verified against live PostgreSQL and Redis:

  • FastAPI application factory + /api/v1/health with a real database check
  • PostgreSQL 16 persistence — full domain schema (hosts, services, dependencies, incidents, evidence, agent runs, tool calls, approvals, audit logs, evaluations) via SQLAlchemy 2.0 async
  • Alembic migrations (async) applied to a live database
  • Redis 7 via Docker Compose
  • Structured logging (structlog), typed config (pydantic-settings)
  • CLI entrypoint (nexus), sandbox compose stack for safe testing
  • CI: ruff, mypy (strict), pytest against real PG + Redis services
  • Graceful degradation: the app boots and reports degraded when the DB is down

✅ Phase 2 — Infrastructure discovery (complete)

Real, read-only observation of the local host, with honest failure:

  • Typed tool layer (nexus/tools/) — every capability declares a permission class
  • Allowlist permission policy (READ_ONLY / LOW_RISK / REQUIRES_APPROVAL / FORBIDDEN), enforced outside the LLM; a new policy denies everything
  • FORBIDDEN is evaluated first, so no mode or approval can reach it
  • Read-only host probes: disk usage, memory, OS, load average, CPU count
  • Evidence records carry an explicit OBSERVED / UNAVAILABLE status, so "I could not verify disk usage because the host did not respond" is a result the system can actually produce
  • Inventory endpoints: GET /api/v1/inventory/host, GET /api/v1/tools, POST /api/v1/tools/{tool_name}
  • Approvals must be issued, never asserted — an HTTP caller cannot approve its own action (see ADR-0003)

✅ Phase 3 — Safe remediation (complete)

Changing something, without making "safe" something a caller has to remember:

  • Every mutating capability is split into two tools — docker.plan_prune_cache (READ_ONLY) and docker.prune_cache (REQUIRES_APPROVAL), and docker.plan_restart_container (READ_ONLY) with docker.restart_container (LOW_RISK). Those two pairs are the only mutating actions that exist. There is no dry_run flag whose default could be forgotten in a prompt, a retry, or a loop; a mutation is simply a different name with a different permission class
  • The plan twin's name is derived from the action's name, and the test suite asserts every mutating action has one, so the pair cannot drift apart
  • Plans are evidence, not predictions — the plan tool runs the real read-only command and the approval request carries that output
  • Propose → approve → execute → verify as separate steps (nexus/services/remediation.py)
  • One approval buys one action, atomically. The grant is claimed in a single method with no await inside it — asyncio yields only at an await, so a method that cannot yield cannot interleave, and the read-check-write cannot race. Two concurrent requests sharing one approval_id produce one 200 and one 403, and the command vector appears exactly once. The trade is honest and worth stating: claiming burns the grant. It is spent whether the action succeeded, failed or was cancelled, because a command that was started cannot be un-started — so a crash between the claim and the command means the operator has to approve again, which is the correct direction to fail
  • A refusal that never needed the grant does not spend one. execute decides first with no grant at all, so READ_ONLY_MODE, UNKNOWN_TOOL and FORBIDDEN refusals return without claiming anything
  • Mutating tools are unreachable from POST /api/v1/tools/{tool_name}. That route refuses LOW_RISK and REQUIRES_APPROVAL names with 403 and MUTATING_TOOL_REQUIRES_REMEDIATION_ROUTE, before the approval store is consulted — so a grant cannot be spent on an action that was never proposed, even in PERMISSIVE mode and even with a genuine grant in the body. FORBIDDEN names are deliberately not diverted: they must reach the policy to be reported as FORBIDDEN_TOOL, which is ADR-0002's precedence holding
  • Verification is a separate read after the fact. A zero exit code is evidence a command ran, not that a service recovered — and if the re-read is impossible the result is UNAVAILABLE, never an inferred success
  • A zero exit code is not a state change. A prune reporting Total reclaimed space: 0B is UNCHANGED with changed is False, not CHANGED. An authorized call that produced no outcome (unusable arguments) is 400, not a 200 with a null body
  • No arbitrary shell. Every action is a fixed argument vector. No template, no free text, no shell; the one caller-supplied token is a container name, validated against a narrow pattern and passed as a separate argv element
  • Disabled by default (NEXUS_REMEDIATION_ENABLED=false), which means the mutating tools are absent from the allowlist (UNKNOWN_TOOL) rather than locked
  • Endpoints: GET /api/v1/remediations, POST /api/v1/remediations/{action}/proposal, POST /api/v1/remediations/{action}, POST /api/v1/remediations/{action}/verification
  • Still no route can issue an approval — that asymmetry is ADR-0003 working as intended
  • Tested against real subprocesses, not just mocks: subprocess_runner is exercised with sys.executable (never docker, so no daemon is required), covering shell-metacharacter passthrough, exit codes, a missing binary and a timeout. No test in this repository has actually run docker builder prune, because the tests deliberately do not need Docker to mean anything

🚧 Roadmap

  • Phase 3 — Safe remediation actions behind the approval gate
  • Phase 4 — LangGraph agent (investigate → evidence → diagnose → explain)
  • Phase 5 — Dynamic context engine
  • Phase 6 — Evaluation framework (25+ scenarios, regression gates)
  • Phase 7 — Observability (Langfuse tracing)
  • Phase 8 — Operator-facing approval flow + audit UI
  • Phase 9 — Chaos lab (controlled failure scenarios)
  • Phase 10 — Operations console (React/Next.js)
  • Phase 11 — Hardening, API authentication, regression testing

Honest rule of this repo: features are marked REAL, SIMULATED, MOCK, or NOT IMPLEMENTED. See docs/architecture.md.


Architecture

                     ┌─────────────────────┐
                     │     Web Console     │
                     │     React/Next.js   │
                     └──────────┬──────────┘
                                │
                                ▼
                     ┌─────────────────────┐
                     │      FastAPI        │
                     │        API          │
                     └──────────┬──────────┘
                ┌───────────────┼────────────────┐
                ▼               ▼                ▼
        ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
        │ Agent Engine │ │ Infrastructure│ │ Evaluation   │
        │  LangGraph   │ │   Service     │ │   Service    │
        └──────┬───────┘ └──────────────┘ └──────────────┘
               │
               ▼
        ┌──────────────────┐
        │ Context Engine   │
        └────────┬─────────┘
                 │
        ┌────────┼─────────┐
        ▼        ▼         ▼
      Tools    State    Knowledge
        │        │         │
        ▼        ▼         ▼
     Docker   PostgreSQL  Topology
     Linux    Redis       Graph
     Network
     Storage
     Metrics
     Logs
        │
        ▼
   Actual Homelab

Clean boundaries between API, agent orchestration, context engineering, tools, infrastructure state, evaluation, observability, and frontend. No monolith "main.py" — see src/nexus/.


Quickstart (what works today)

Requirements: Python 3.12+, Docker / Docker Compose.

git clone https://github.com/mfalme0/nexus.git
cd nexus

# 1. Start PostgreSQL + Redis
docker compose up -d

# 2. Install (editable, with dev tools)
python -m venv .venv
# Windows: .venv\Scripts\activate
source .venv/bin/activate
pip install -e ".[dev]"

# 3. Apply the schema
alembic upgrade head

# 4. Run the API
uvicorn nexus.main:app --reload --port 8000

Then open http://localhost:8000/docs for the interactive OpenAPI docs, or:

curl http://localhost:8000/api/v1/health
# {"status":"healthy","version":"0.1.0","checks":{"database":"healthy"}}

Quality gates

make test        # pytest
make lint        # ruff
make typecheck   # mypy --strict

make dev, make migrate, and make sandbox-up are also available.

The evaluation harness is a Phase 6 deliverable, so there is deliberately no eval target (#1 removed one that pointed at a module that never existed). An eval command that ran and reported nothing would be worse than no command at all.


Safety model

The homelab holds real services and real data, so safety is a hard requirement, not a feature flag.

  • Default mode is READ_ONLY. It is the default in code, not a convention, and the policy refuses anything that is not READ_ONLY under it.
  • Mutating tools are absent by default. NEXUS_REMEDIATION_ENABLED=false means docker.prune_cache is not in the allowlist at all — refused as UNKNOWN_TOOL. Registration is what denies, so a forgotten switch is the safe outcome rather than the dangerous one.
  • Tool permission classes: READ_ONLY, LOW_RISK, REQUIRES_APPROVAL, FORBIDDEN. The model cannot bypass them; authorization is enforced outside the LLM. Two independent switches (NEXUS_REMEDIATION_ENABLED and NEXUS_REMEDIATION_EXECUTION_MODE) stand between a default deployment and a mutation, and REQUIRES_APPROVAL adds a third: an issued, single-use grant.
  • One route to a mutation, and the grant is claimed atomically. POST /api/v1/tools/{tool_name} is for observation and refuses mutating names outright; POST /api/v1/remediations/{action} is the only route that can perform one. There, the grant is taken in a single non-yielding method, so concurrent requests sharing one approval_id cannot both clear the gate. Claiming spends it — see the Phase 3 section for why that is the correct direction to fail.
  • Settings in .env are read by every group, and a typo is silent. Each settings class declares its own env_file. That was a bug fix, not a feature: writing NEXUS_REMEDIATION_ENABLED=true to .env used to raise ValidationError at import, because pydantic-settings does not propagate a parent's dotenv source into a nested settings model. The fix required extra="ignore" on the root model, which means a misspelled NEXUS_* variable is now ignored rather than reported. Treat the documented names as a contract.
  • Early testing runs against a dedicated Docker Compose sandbox, never the production homelab by default. The sandbox is a convenience, not a security boundary.
  • Secrets stay in environment variables, are never logged, and are never committed.
  • What is not defended yet — no API authentication, no transport security, no sandbox for the remediation commands, which shell out to the docker CLI and inherit its authority, and no validation that a NEXUS_* variable you meant to set was spelled correctly. See SECURITY.md.

Project layout

src/nexus/
├── api/          # FastAPI routes (thin): health, inventory, tools, remediations
├── agent/        # LangGraph orchestration — NOT IMPLEMENTED (Phase 4)
├── tools/        # typed tool layer, permission policy, host probes, remediation
├── security/     # issued approvals and pending approval requests
├── services/     # host discovery + the propose/execute/verify remediation flow
├── db/           # SQLAlchemy models, engine, sessions (schema only — no CRUD)
├── config.py     # pydantic-settings configuration
├── logging.py    # structlog configuration
└── main.py       # application factory
alembic/          # database migrations
tests/            # unit + integration tests
docs/             # architecture and decision records

Documentation

More land as each phase completes: agent design, context engineering, tool security, evaluation, observability, failure analysis, and chaos engineering.

Contributing

Issues and pull requests are welcome — see CONTRIBUTING.md. Security vulnerabilities should go through private advisory reporting, not a public issue: see SECURITY.md.


Philosophy

NEXUS is not optimized to look impressive. It is optimized to be correct, observable, testable, explainable, recoverable, and safe.

The impressive part is not that an LLM can restart Docker. It is that NEXUS can say: here is what I observed, here is what I believe happened, here is the evidence, here is what I'm uncertain about, here is the safest available action, here is why I'm allowed to take it, and here is proof the system recovered.

License

MIT

About

Evidence-driven AI SRE agent for homelabs. Investigates incidents with typed, permission-gated tools, shows its work, and requires human approval for risky actions.

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages