Compare commits

...
2 Commits
Author SHA1 Message Date
kiskaadee 61a2798d4f build(nix): unify Python dev environment via .venv symlink and add pyright to scripts/test
- Extract shared pythonEnv in flake.nix and symlink .venv in devShell
  shellHook so IDEs, terminal, and Nix checks share one Python 3.14 env.
- Add pyright static type checking to scripts/test and align pre-commit
  with the unified Nix environment.
- Remove personal domain from flake.nix description and ignore .venv.
2026-10-15 19:27:30 -05:00
kiskaadee 2bf0635ba9 docs(core): rewrite AGENTS.md and README.md for self-contained governance
- Structure AGENTS.md around the 6-section agents.md framework covering
  context discovery hierarchy, Core vs. ~/Sites ownership boundaries,
  anti-tautology TDD rules, verification gates (./scripts/test and pyright),
  declarative-vs-runtime state invariants, and MADR/Git hygiene.
- Redesign README.md into a 5-section instance-agnostic entrypoint explicitly
  scoped to the current CLI baseline, with a pointer to ROADMAP.md for the
  Milestone P4 daemon transition.
- Move the Current Baseline vs. Target Architecture matrix to ROADMAP.md,
  use descriptive phrasing for P1 historical endpoints, and define the
  explicit P4-to-P5 authorization gate handoff.
2026-10-15 19:27:09 -05:00
7 changed files with 231 additions and 349 deletions

No files matched your search

+7 -9
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env bash
set -e
set -euo pipefail
# ==============================================================================
# Homelab Core Pre-Commit Invariant & Quality Gate Hook
# Runs linter (Ruff) and architecture & security test suite (Pytest)
# Runs linter (Ruff), static type checker (Pyright), and test suite (Pytest)
# ==============================================================================
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -13,26 +13,24 @@ echo "🔍 [pre-commit] Executing Homelab Core invariant checks..."
# 1. Run Ruff Linter
echo " ↳ Linting repository with Ruff..."
if command -v uv >/dev/null 2>&1; then
uv run ruff check .
elif command -v ruff >/dev/null 2>&1; then
if command -v ruff >/dev/null 2>&1; then
ruff check .
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
nix develop --command ruff check .
else
echo "⚠️ [pre-commit] Neither uv, ruff, nor nix found; skipping ruff"
echo "⚠️ [pre-commit] Neither ruff nor nix found; skipping ruff"
fi
# 2. Run Pytest Suite
echo " ↳ Running structural and security test suite with Pytest..."
if command -v uv >/dev/null 2>&1; then
uv run --with pytest --with pyyaml pytest tests/
if [ -x ".venv/bin/pytest" ]; then
.venv/bin/pytest tests/
elif command -v pytest >/dev/null 2>&1; then
pytest tests/
elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then
nix develop --command pytest tests/
else
echo "⚠️ [pre-commit] Neither uv, pytest, nor nix found; skipping pytest"
echo "⚠️ [pre-commit] Neither pytest nor nix found; skipping pytest"
fi
echo "✅ [pre-commit] All repository checks passed successfully!"
+1
View File
@@ -5,6 +5,7 @@ secrets.txt
backup.zip
.envrc
.direnv
.venv
# SSL / ACME Certificates & Keys
config/letsencrypt/*
+59 -141
View File
@@ -1,173 +1,91 @@
# Homelab Core — Agent Guidelines
This repository defines the host foundation and Core platform for the
`roadtotech.me` homelab.
## 1. Project Overview & Architectural Boundaries
It contains NixOS configuration, shared infrastructure services, orchestration
tools, security policy, and operational configuration.
**Homelab Core** defines the declarative NixOS host foundation, shared platform infrastructure services, security boundaries, and the `appctl` operational control plane. Independent application workloads live in `~/Sites/<app>` and integrate through declarative `app.yaml` manifests and workload-scoped Docker Compose files.
Independent application workloads live in `~/Sites` and are integrated with
Core through their application manifests and Docker Compose configuration.
### Core vs. `~/Sites` Ownership
- **Core owns**: NixOS host configuration, shared platform services (edge ingress, SSO/LDAP, mail, log/update monitors), platform-level ports and security policy, and orchestration/deployment mechanics.
- **`~/Sites` owns**: Independently deployed application workloads, workload-specific `docker-compose.yml` topologies, and workload intent (`app.yaml`).
- **Boundary Rule**: Never hardcode *workload-specific* domains, ports, containers, environment variables, or deployment policies in Core (`scripts/appctl*`, GitOps, or Core `docker-compose.yml`), and never move Core platform services into `~/Sites`. When ownership is ambiguous, consult [`docs/architecture.md`](docs/architecture.md) before changing the boundary.
### Context Discovery Hierarchy
Before proposing or implementing changes, establish context in this order:
1. **Architectural Decisions (`docs/decisions/`)**: Check [`docs/decisions/README.md`](docs/decisions/README.md) and local ADRs for binding design commitments.
2. **Runtime Contracts (`docs/`)**: Consult [`docs/architecture.md`](docs/architecture.md), [`docs/appctl.md`](docs/appctl.md), [`docs/gitops.md`](docs/gitops.md), and [`docs/secrets-and-state.md`](docs/secrets-and-state.md) for current behavior.
3. **Trajectory & Active Work (`ROADMAP.md`, `todo.txt`, `git log`)**: Verify whether a capability belongs to the current baseline or a planned milestone before modifying code.
When a requested change conflicts with an architectural invariant or accepted ADR, **stop and surface the conflict** before implementing a workaround.
---
## Architectural Invariants
## 2. Build, Lint & Verification Commands
### 1. Core / Sites Boundary
The Python environment (`python3`, `pytest`, `pydantic`, `pyyaml`, `types-pyyaml`) and static analysis tools (`ruff`, `pyright`) are provisioned hermetically by `flake.nix` and automatically symlinked to `.venv` via the Nix `devShell` hook (`.envrc`). Do not create separate `uv` or `pip` virtual environments that split from the Nix store environment.
**Core owns:**
- NixOS host configuration and system services
- Shared platform and infrastructure services
- Ingress, identity, security boundaries, and host-level policy
- Orchestration and deployment mechanics
**`~/Sites` owns:**
- Independently deployed application workloads
- Application-specific Docker Compose configuration
- Application-specific `app.yaml` metadata and workload intent
Do not move workload-specific configuration into Core merely because Core
consumes or manages the workload.
Do not move Core-owned platform services into `~/Sites`.
When ownership is unclear, consult current architecture documentation before
changing the boundary.
### 2. Workload Manifests
Every `~/Sites` workload is self-describing through its `app.yaml`.
Do not hardcode workload-specific domains, ports, environment variables,
containers, or deployment configuration inside `scripts/appctl`,
`scripts/appctl_engine.py`, or GitOps logic.
`app.yaml` describes workload identity, integration metadata, and deployment
intent. Core owns deployment mechanics.
Never introduce arbitrary command execution, host filesystem paths,
privileged operations, or Docker control capabilities into workload manifests.
### 3. GitOps Trust Boundary
GitOps must remain a constrained deployment mechanism.
- Webhook authentication is mandatory.
- Repository identity is resolved through trusted Core logic.
- Filesystem paths must never be selected directly by webhook payloads.
- Deployment execution must remain closed and explicitly allowlisted.
- Repository-controlled configuration must never become arbitrary shell input.
- Deployment serialization and superseding behavior must be preserved.
Do not weaken these constraints for convenience.
### 4. Docker Isolation
- `socket-proxy` is the only Core Compose service that may mount
`/var/run/docker.sock`.
- The socket proxy must expose only explicitly approved read-only Docker API capabilities; state-changing and command-execution endpoints must remain disabled.
- Do not add `privileged: true` without an explicit architectural decision.
- Workload containers must not gain direct access to the Docker socket.
### 5. Secrets & Persistent State
Never commit plaintext secrets, credentials, password hashes, private keys,
certificates, runtime databases, or other generated/persistent state.
Secrets are managed through SOPS and projected to runtime paths under
`/run/secrets/`.
Do not move secrets into application manifests or source code.
### 6. Declarative Configuration vs Runtime State
Git contains declarative configuration and reproducible definitions.
Persistent runtime state belongs in the appropriate state directories or
Docker volumes and must remain excluded from version control.
Do not convert runtime state into committed configuration merely to simplify
development or recovery.
### 7. Core Service Ownership
Core Compose is the execution boundary for Core-owned platform services.
Workload-specific services belong in `~/Sites` unless an explicit architectural
decision establishes them as Core-owned.
Do not introduce application-specific deployment policy into the Core stack.
Do not make Core orchestration depend on implementation details of a workload
when the workload's declared contract can be used instead.
### 8. Platform Genericism & Domain Decoupling
Core platform code, templates, and documentation must remain strictly instance-agnostic.
- Instance-specific domains (e.g. personal domain names), operator usernames, and deployment topologies must never be hardcoded into Core platform definitions.
- All routing and service identities must be injected declaratively at runtime via environment variables (`HOMELAB_DOMAIN`, `DOMAIN_SUFFIX`) and local configuration overlays.
- Example manifests, tests, and documentation must use RFC-compliant generic placeholders (e.g. `example.com`, `example.org`, `example.test`).
### 9. License
Preserve The Unlicense across Core and related Sites repositories.
---
## Verification & Architectural Integrity
When a requested change conflicts with an invariant, stop and resolve the
architectural conflict before implementing a workaround.
Before committing architectural or security-sensitive changes:
Every implementation step must close with the automated verification gate before proposing a commit:
```bash
# Full verification gate: Ruff + Pyright + Pytest (124+ tests) + nix flake check + NixOS drv eval
./scripts/test
nix flake check
# Targeted fast iteration commands (inside direnv / nix develop, or via .venv)
ruff check .
pyright
.venv/bin/pytest tests/
```
Run additional validation appropriate to the change, such as:
When modifying container or Compose definitions, also validate Compose syntax:
```bash
docker compose config -q
```
Architectural invariants should be encoded as tests whenever practical.
---
Do not bypass failing invariant tests by weakening or removing the invariant
unless the architecture itself has intentionally changed.
## 3. Code Style & Contract Guidelines
- **Fail-Closed Validation (`scripts/core_manifest.py`)**: All external inputs (`app.yaml` manifests, webhook payloads, CLI arguments, daemon payloads) must be validated through strict Pydantic v2 models (`ConfigDict(extra="forbid")`).
- **Explicit Error Handling**: Never swallow diagnostic `stderr` silently (e.g., avoid blind `2>/dev/null` on engine or manifest commands). Surface actionable validation errors while redacting sensitive material.
- **Platform Genericism**: Keep all code, templates, tests, and documentation strictly instance-agnostic:
- Inject routing and service identities at runtime via environment variables (`HOMELAB_DOMAIN`, `DOMAIN_SUFFIX`).
- Use RFC 2606 placeholders (`example.com`, `example.org`, `example.test`) in tests and configuration examples—never personal domains or operator usernames.
- In historical documentation or milestone records, use descriptive phrasing (e.g., *"the configured `smtp.<domain>` endpoint"*) rather than fabricating placeholder domains as historical facts.
---
## Documentation
## 4. Testing Instructions (TDD)
Use the repository's current architecture and operational documentation as the
source of truth for ownership, protocols, and system behavior.
Record significant architectural decisions in the appropriate ADR or Brain
documentation rather than expanding this file into an architecture manual.
All documentation must remain GitHub-flavored Markdown compatible with Obsidian
and the live documentation viewer.
- **TDD-First**: Write or update failing unit, structural, or security tests in `tests/` before or alongside implementation changes.
- **No Tautological Tests**: Every test must import and execute real production modules or scripts (`core_manifest`, `appctl_engine`, `gitops_dispatcher`, `scripts/appctl`) and assert on observable outcomes. Never write tests that only inspect local mock strings, hardcode expected outputs into the fixture under test, or continue passing when the production invariant is broken.
- **Protect Invariants**: Do not bypass failing tests by weakening or deleting an invariant assertion unless the architecture itself has intentionally changed via an approved ADR.
---
## Architectural & Engineering Knowledge Preservation
## 5. Security & State Invariants
When engineering changes in Core yield durable architectural insights, security posture shifts, non-obvious root causes, or transferable operational heuristics, knowledge preservation is governed by the global skill **`documentation-router`**:
- Architectural commitments are recorded in ADRs (`03-records/decisions/`).
- Exploratory design inquiries and trade-offs are recorded in Discussions (`02-discussions/`).
- Empirical incident RCAs are recorded in Debug Records (`03-records/debug/`).
- Implementation roadmaps are recorded in Plans (`01-plans/`).
- Routine maintenance, configuration adjustments, and self-explanatory fixes require no external documentation.
- Preserve repository-local documentation (`docs/`, inline comments, commit rationale) as the primary source of truth for runtime behavior.
1. **Workload Manifests (`app.yaml`)**: Describe declarative workload identity, routing metadata, and deployment intent only. Never introduce arbitrary command execution, host filesystem paths, privileged flags, or Docker control capabilities into `app.yaml`.
2. **GitOps Trust Boundary (`scripts/gitops_dispatcher.py`)**:
- Webhook admission requires cryptographic authentication (HMAC-SHA256).
- Repository identity and filesystem paths must be resolved strictly through trusted Core configuration (`config/deployments.yaml`)—never directly from webhook payloads.
- Execution must remain allowlisted, serialized (`flock`), pre-validated by the Compose AST security checker, and free of shell interpolation (`shell=False`, no `eval`).
3. **Docker & Privilege Isolation**:
- `socket-proxy` is the **only** service permitted to mount `/var/run/docker.sock` (strictly `:ro`, read-only API capabilities only; `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`).
- Never add `privileged: true`, host namespace sharing, or direct Docker socket mounts to workload or control-plane containers.
4. **Declarative Configuration vs. Secrets & Runtime State**:
- Git stores declarative configuration and reproducible definitions only. Never commit plaintext secrets, keys, password hashes, certificates, or runtime databases.
- Host secrets are managed via SOPS (`sops-nix`) and projected to `/run/secrets/`.
- Persistent mutable runtime state belongs in dedicated host state directories (`~/var/lib/homelab/<app>/`) or Docker volumes excluded from version control.
---
## Live Task Tracking (`todo.txt`)
For multi-step engineering milestones and complex refactors:
- Maintain a standard, comment-free `todo.txt` in the repository root formatted for `tuxedo` / `todo.sh`.
- Prioritize deliverables using standard priorities (`(A)`, `(B)`, `(C)`), projects (`+<component>`), and contexts (`@<area>`).
- Keep `todo.txt` synchronized with code reality: when a deliverable is implemented and verified, mark it completed (`x YYYY-MM-DD ...`) immediately. Never leave verified work marked as pending or untracked.
## 6. Documentation, Task Tracking & Git Workflow
- **Synchronize Documentation (`docs/`)**: Update repository documentation alongside code changes that alter behavior, contracts, or operations. Keep all Markdown formatted in GitHub-Flavored Markdown compatible with both Obsidian and the live documentation viewer.
- **Architecture Decision Records (`docs/decisions/`)**: Record binding repository-level architectural decisions in MADR 4.0 format (`NNNN-slug.md`) and register them in [`docs/decisions/README.md`](docs/decisions/README.md).
- **Live Task Tracking (`todo.txt`)**: Maintain a comment-free root `todo.txt` formatted for `tuxedo` / `todo.sh` (`(A)`–`(C)` priorities, `+<project>`, `@<context>`) reflecting the current milestone. Mark verified deliverables completed (`x YYYY-MM-DD ...`) immediately.
- **Git & Commits**:
- Never commit directly to `main`/`master`.
- Never run destructive Git commands (`reset --hard`, `restore`, `clean -fd`, `push --force`) without explicit user confirmation.
- Stage atomic changes and use Conventional Commits (`feat`, `fix`, `refactor`, `test`, `docs`, `chore`), waiting for user approval before committing.
- Preserve [The Unlicense](UNLICENSE) across the repository.
+104 -161
View File
@@ -1,96 +1,19 @@
# 🏛️ Homelab Core & Appctl Operational Control Plane
# Homelab Core
**Homelab Core** defines the host foundation, platform infrastructure services, security boundaries, and operational control plane for the `roadtotech.me` homelab appliance.
**Homelab Core** is the declarative NixOS host foundation, shared platform infrastructure stack, and `appctl` operational control plane for a self-hosted homelab appliance.
This repository serves two primary roles:
1. **The Host Platform & Infrastructure Appliance**: Declarative NixOS operating system definitions, edge ingress routing, wildcard TLS certificates, identity/SSO directory services, mail routing, and Docker socket isolation.
2. **The Appctl Operational Control Plane**: The centralized engine governing workload lifecycle management, continuous GitOps deployment, source provenance tracking, and dashboard synchronization across independent application workloads in `~/Sites`.
It is designed around a strict two-tier boundary:
1. **Homelab Core (this repository)**: Owns NixOS operating system configuration, edge TLS ingress, SSO/LDAP directory identity, mail routing, read-only Docker socket isolation, and orchestration/deployment mechanics.
2. **Workload Repositories (`~/Sites/<app>`)**: Independently deployed application stacks that integrate with Core through self-describing `app.yaml` manifests and workload-scoped `docker-compose.yml` definitions.
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
> [!NOTE]
> **Current Implementation Baseline vs. Target Architecture**: This README documents the **currently implemented CLI and runtime baseline (Milestone P3)**. Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` is transitioning from a host CLI orchestrator into a dedicated daemon service (`homelab-appctl.service`) exposing a unified logical API across local Unix socket and HTTP transports. See [`ROADMAP.md`](ROADMAP.md) for the full baseline-to-target matrix.
---
## 🧭 Architectural Direction & Mental Model
Under the approved architectural baseline ([`ADR: Homelab Operational Control Plane`](docs/decisions/README.md#homelab-operational-control-plane--deployment-model-architecture) and [`ADR: 3-Tier Architecture & Provenance`](docs/decisions/README.md#homelab-3-tier-architecture--deployment-provenance-model)), `appctl` is evolving from a local procedural CLI wrapper into the **authoritative operational control plane service for Homelab Core**.
### The Core Architectural Spine
```text
Human Operator / Automation
│
┌───────────────────┴───────────────────┐
│ │
Operations UI CLI (Local & Remote)
│ │
└───────────────────┬───────────────────┘
│
appctl Control Plane API
(One Logical API across Transports)
│
┌────────────┴────────────┐
│ │
Unix Socket HTTP Listener
(Host Clients) (Remote/LAN Clients)
│ │
└────────────┬────────────┘
│
┌───────────────────────────┼───────────────────────────┐
│ │ │
Authentication Deployment Model Operations
& Authorization Plane Execution
│ │ │
Token Validation & ┌──────┴──────┐ Docker Compose
LLDAP Directory RBAC │ │ Traefik Routing
AI Investigation Human Host Secrets
│ Approval Reconciliation
▼ │
DeploymentProposal │
│ ▼
└─────▶ DeploymentModel
│
▼ (Committed to Git)
Deployment Repository
(Git Truth)
│
▼ (appctl validates & materializes)
Deployment Definition
(Sites app.yaml + compose)
│
▼
Runtime Reconciliation
```
### Core Architectural Invariants
* **Single Operational Truth**: Exactly one implementation of every operational action (`deploy`, `restart`, `inspect`, `sync`, `validate`) exists in the platform. Clients (local CLI, remote CLI, web UI, GitOps) invoke the exact same logical API contract.
* **Host Access Does Not Confer Authority**: Entering the server via SSH is merely host access; it does not grant Appctl privileges. **Every mutating operation requires an explicit, authenticated user-scoped token**, regardless of transport. Unix socket peer credentials identify the transport context, not user authority.
* **Git is the Authoritative Source of Deployment State**: Approved workload configurations are versioned in Git. `appctl` reconciles desired Git state into running containers, preserving immutable revision history, commit provenance, peer reviews, and atomic rollbacks (`git revert`).
* **Five-Stage Model Lifecycle (Intent vs. Implementation)**:
$$\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Containers}$$
* `DeploymentModel`: The operator-selected, implementation-agnostic representation of intent (ports, domains, volumes, dependencies, secret references). Free of Compose syntax and Traefik label boilerplate.
* `Deployment Definition`: Concrete platform descriptors (`app.yaml` + `docker-compose.yml`) materialized and enforced by `appctl`.
* **AI Authoring Boundary**: AI agents act strictly as upstream proposal generators with **zero execution or mutation authority**. The AI analyzes repositories and drafts `DeploymentProposals`. After human approval into a `DeploymentModel`, the AI is completely out of the loop.
* **Secret Reference Invariant**: Deployment definitions contain secret references (`secretKeyRef`), never secret material. References are resolved at runtime through a defined `SecretProvider` interface. Host platform secrets remain declarative in `sops-nix`.
* **Clean State Root**: Mutable application data lives strictly under `~/var/lib/homelab/<app>/`, isolated from Git deployment repositories.
---
## 🔍 Current Implementation Baseline vs. Target Architecture
To maintain clarity during development, this repository explicitly separates what is **currently implemented** from what is **planned in the roadmap**:
| Architectural Area | Current Implementation Baseline (Milestone P0) | Target Architecture (Roadmap v5) |
| :--- | :--- | :--- |
| **`appctl` Architecture** | Bash CLI wrapper (`scripts/appctl`) driving local subprocesses (`docker compose`, `git`) and metadata engines. | Dedicated daemon service (`homelab-appctl.service`) exposing one logical API over Unix socket and HTTP. |
| **Operational Auth** | Sudo / Unix user permissions on the host. Sourcing secrets from `/run/secrets/`. | LLDAP directory identity. Explicit user-scoped API tokens for all mutating actions; Authelia ForwardAuth for Web. |
| **Metadata Engine** | Authoritative dataclass engine (`scripts/appctl_engine.py`) with two-axis inspection and schema v1.0 parser (`core_manifest.py`). | Single unified engine (`core_manifest.py` / `appctl_engine.py`) embedded directly within the control plane daemon. |
| **Deployment Model** | Manual authoring of `app.yaml` and `docker-compose.yml` directly in `~/Sites/<app>/`. | 5-stage lifecycle: AI/human `DeploymentProposal` $\to$ operator-approved `DeploymentModel` committed to Git $\to$ `appctl` materialization. |
| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) listening on port 9000 with HMAC-SHA256 authentication and flock serialization. | Fully integrated into control-plane admission, calling central reconciliation endpoints. |
| **Secret Distribution** | Static Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected at runtime via `SecretProvider`. |
| **Dashboard** | `appctl sync` statically compiles `config/homepage/services.yaml`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for interactive management. |
---
## 🗺️ System Topology & Runtime Layers
## System Architecture at a Glance
```text
Internet
@@ -98,129 +21,149 @@ To maintain clarity during development, this repository explicitly separates wha
▼
┌───────────────────────────────┐
│ Traefik Edge Proxy (:443) │
│ Wildcard TLS (*.roadtotech.me)│
│ Wildcard TLS (*.example.com) │
└───────┬───────────────┬───────┘
│ │
Public Traffic │ │ ForwardAuth Protected
(e.g., mail, landing) │ │ (authelia-auth@docker)
(e.g., SMTP, public) │ │ (authelia-auth@docker)
▼ ▼
[ Public Services ] [ Authelia SSO / 2FA ]
│ │ (LDAP -> LLDAP)
│ │
▼ ▼
┌───────────────────────────────┐
│ Docker proxy-net │
│ Docker proxy-net │
├───────────────────────────────┤
│ • Core Services (Homepage, │
│ Dozzle, etc.) │
│ Dozzle, Stalwart, etc.) │
│ • Workload Apps (~/Sites/*) │
└───────────────────────────────┘
│
(Protected API via TCP:2375)
└───────────────┬───────────────┘
│ (Read-Only API via TCP:2375)
▼
┌───────────────────────────────┐
│ Docker socket-proxy │
│ (socket-net, Read-Only) │
│ Docker socket-proxy │
│ (socket-net, Read-Only) │
└───────────────┬───────────────┘
│ (read-only mount)
│ (read-only mount :ro)
▼
/var/run/docker.sock
▲
│ (Host Orchestration & CD)
┌───────────────┴───────────────┐
│ Host Control Plane Baseline │
│ • appctl CLI + Engine │
│ • homelab-gitops.service │
└───────────────────────────────┘
```
### Core Services (`docker-compose.yml`)
| Service | Domain / Ingress | Function | Auth Policy |
For detailed runtime layers, network segmentation, and the P4 control-plane transport architecture, see [`docs/architecture.md`](docs/architecture.md) and [`ROADMAP.md`](ROADMAP.md).
### Core Platform Services (`docker-compose.yml`)
| Service | Default Endpoint | Role | Access Policy |
| :--- | :--- | :--- | :--- |
| **`traefik`** | `traefik.roadtotech.me` | Edge reverse proxy, Dynu DNS-01 ACME TLS | Authelia Guard |
| **`socket-proxy`** | Internal (`socket-net:2375`) | Read-only Docker API gateway barrier | Internal Only |
| **`lldap`** | `users.roadtotech.me` | LDAP directory & user database | Authelia Guard |
| **`authelia`** | `auth.roadtotech.me` | Single Sign-On (SSO) & ForwardAuth middleware | Public (Bypass) |
| **`stalwart`** | `mail.roadtotech.me` | Mail Server (SMTP/IMAP/JMAP/Sieve) *(Moving to smtp in P1)* | Native / LLDAP |
| **`homepage`** | `dashboard.roadtotech.me` | Service portal & system dashboard | Authelia Guard |
| **`dozzle`** | `logs.roadtotech.me` | Container log viewer (via socket-proxy) | Authelia Guard |
| **`traefik`** | `traefik.${HOMELAB_DOMAIN}` | Edge reverse proxy & DNS-01 ACME wildcard TLS | Authelia Guard |
| **`socket-proxy`** | Internal (`socket-net:2375`) | Read-only Docker API security barrier (`POST=0`, `DELETE=0`) | Internal Only |
| **`lldap`** | `users.${HOMELAB_DOMAIN}` | Central LDAP user directory | Authelia Guard |
| **`authelia`** | `auth.${HOMELAB_DOMAIN}` | Single Sign-On (SSO), 2FA & ForwardAuth | Public (Auth Endpoint) |
| **`stalwart`** | `smtp.${HOMELAB_DOMAIN}` | Mail server (SMTP/IMAP/JMAP/Sieve) | Native / LLDAP |
| **`homepage`** | `dashboard.${HOMELAB_DOMAIN}` | Service portal dynamically synced via `appctl` | Authelia Guard |
| **`dozzle`** | `logs.${HOMELAB_DOMAIN}` | Real-time container log viewer (via `socket-proxy`) | Authelia Guard |
| **`watchtower`** | Internal | Automated container image updater | Internal Only |
| **`diun`** | Internal | Container image update notifier | Internal Only |
---
## ⚡ Quick Start & Operator Workflows (Current Baseline)
## Repository Structure
```text
.
├── flake.nix # NixOS host configuration, devShell (.venv symlink), and CI checks
├── docker-compose.yml # Core platform service stack
├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml)
├── scripts/
│ ├── appctl # Operational CLI entrypoint and Compose environment orchestrator
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync engine
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for workload app.yaml
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST security validation
│ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
├── tests/ # Unit, structural, and security invariant test suites
└── docs/ # Architecture references, operational runbooks, and MADR decisions
```
---
## Quickstart & Operations (Current CLI Baseline)
### Development & Verification
Entering the directory via `direnv` (`use flake`) or `nix develop` provisions the hermetic Nix Python environment and symlinks `.venv` for IDE static analysis:
### Host & System Operations
```bash
# Rebuild and switch NixOS configuration
sudo nixos-rebuild switch --flake ~/Core#server
# or use the built-in shell alias:
nix-switch
# Run full automated verification (Ruff + Pyright + Pytest + nix flake check + NixOS drv eval)
./scripts/test
# Inspect systemd platform services
systemctl status homeserver-core.service # Core Compose stack
systemctl status homelab-gitops.service # GitOps webhook engine
systemctl status dynu-monitor.service # Smart DDNS IP monitor
systemctl status dynu-monitor.timer # DDNS timer (every 30m)
# Run individual checks directly
ruff check .
pyright
.venv/bin/pytest tests/
```
### Workload Management (`appctl` CLI)
```bash
# List all application stacks with container health, Git tracking, and provenance status
# List all workloads with container health and local Git checkout status
appctl list
# Fetch upstream changes across all repos and inspect with SSL certificates
# Include upstream Git provenance (--fetch), TLS certificate expiry (--ssl), and Core services (--core)
appctl list --fetch --ssl --core
# Inspect full diagnostic metadata for a service
appctl info jellyfin
# Inspect detailed manifest, provenance, and container diagnostics for a workload
appctl info <service>
# Start, stop, or restart an application or Core service
appctl up docs
appctl down mongodb
appctl restart traefik
# Manage workload or Core service lifecycle (executes docker compose locally in the current baseline)
appctl up <service|core>
appctl down <service|core>
appctl restart <service|core>
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
appctl update docs
appctl update core
# Full stack update (clean tree check -> git pull --ff-only -> compose pull -> recreate -> sync)
appctl update <service|core>
# Recompile Homepage services.yaml from active app.yaml manifests
# Recompile Homepage dashboard configuration from discovered app.yaml manifests
appctl sync
```
### Testing & Verification
```bash
# Run the complete test suite (Ruff linter + Pytest invariants + Nix flake check)
./scripts/test
### Host System Management
# Run pure Nix flake evaluation and checks
nix flake check
```bash
# Rebuild and activate the NixOS host configuration
sudo nixos-rebuild switch --flake .#server
# Inspect platform systemd units
systemctl status homeserver-core.service
systemctl status homelab-gitops.service
systemctl status dynu-monitor.service
```
---
## 📚 Documentation Navigation & Ownership
## Documentation Index
| Document | Ownership & Epistemic Role |
| Document | Scope |
| :--- | :--- |
| [**`ROADMAP.md`**](ROADMAP.md) | **Implementation Trajectory**: Phased milestones (P0 through P7), active status, and deliverables based on Roadmap v5. |
| [**ADR Index**](docs/decisions/README.md) | **Architectural Decisions**: Navigation index to authoritative ADRs governing the control plane and 3-tier provenance. |
| [**Architecture Reference**](docs/architecture.md) | **Runtime Architecture**: Deep-dive into runtime layers, network segmentation, and component boundaries. |
| [**Appctl Reference**](docs/appctl.md) | **Current CLI Implementation**: Command syntax, arguments, resolution rules, and `app.yaml` fields consumed today. |
| [**GitOps Engine**](docs/gitops.md) | **Current CD Implementation**: Webhook admission pipeline, HMAC verification, and lock serialization. |
| [**Secrets & State**](docs/secrets-and-state.md) | **Current Runtime Secrets**: SOPS encryption, tmpfs projections, and persistent state roots. |
| [**Operator Runbook**](docs/operations.md) | **Operational Runbook**: Host maintenance, updates, garbage collection, and recovery procedures. |
| [**Setup & Provisioning**](docs/setup_guide.md) | **Host Provisioning**: Bare-metal NixOS installation and platform bootstrapping. |
| [**Agent Guidelines**](AGENTS.md) | **Agent Invariants**: Hard rules, trust boundaries, Core/Sites boundaries, and testing rules. |
| [**Security Policy**](SECURITY.md) | **Security Controls**: Docker socket isolation, threat models, and hardening checklists. |
| [**`docs/architecture.md`**](docs/architecture.md) | Runtime layers, network segmentation, and Core / `~/Sites` boundaries. |
| [**`docs/decisions/README.md`**](docs/decisions/README.md) | Architecture Decision Records (MADR 4.0) governing platform evolution. |
| [**`ROADMAP.md`**](ROADMAP.md) | Phased engineering milestones (P0–P7) and baseline-to-target architecture matrix. |
| [**`docs/appctl.md`**](docs/appctl.md) | Current `appctl` CLI commands, resolution hierarchy, and `app.yaml` schema v1.0 contract. |
| [**`docs/gitops.md`**](docs/gitops.md) | Webhook admission pipeline, HMAC verification, Compose AST validation, and locking. |
| [**`docs/secrets-and-state.md`**](docs/secrets-and-state.md) | SOPS secret management, `/run/secrets/` projections, and persistent state paths. |
| [**`docs/operations.md`**](docs/operations.md) | Day-2 operational runbook, updates, backups, and recovery procedures. |
| [**`docs/setup_guide.md`**](docs/setup_guide.md) | Bare-metal NixOS installation and host bootstrapping guide. |
| [**`SECURITY.md`**](SECURITY.md) | Security controls, Docker socket isolation, and threat model. |
| [**`AGENTS.md`**](AGENTS.md) | Architectural invariants, TDD rules, and verification gates for contributors and agents. |
---
## 🧠 Governance & Knowledge Architecture
Durable architectural decisions, exploratory design trade-offs, and master execution roadmaps are governed in the operator's central knowledge vault under standard epistemic taxonomy:
* **Architectural Decisions**: Captured in MADR 4.0 format under `03-records/decisions/`.
* **Execution Roadmaps**: Phased engineering blueprints under `01-plans/`.
* **System Discussions**: Exploratory trade-off analyses under `02-discussions/`.
The repository documentation reflects the accepted architectural state and serves as the operational guide for the implementation.
---
## 📄 License
## License
This repository is released into the public domain under [The Unlicense](UNLICENSE).
+35 -24
View File
@@ -4,11 +4,7 @@ This document serves as the repository-facing projection of the authoritative **
It describes the implementation trajectory and phased engineering milestones for transitioning Homelab Core into a unified platform driven by the `appctl` Operational Control Plane.
> **Authoritative Master Roadmap**: `01-plans/homelab/consolidation/architecture-consolidation-roadmap-v5.md` in the central knowledge vault.
>
> **Governing Architectural Decisions**:
> - `homelab-appctl-control-plane-architecture.md` (Operational Control Plane & Deployment Model)
> - `homelab-3tier-architecture-and-provenance.md` (3-Tier Architecture & Provenance)
> **Governing Architectural Decisions**: See [`docs/decisions/README.md`](docs/decisions/README.md) for the authoritative ADR index (Control Plane Architecture, 3-Tier Provenance Model, and Pydantic v2 Runtime Validation).
---
@@ -24,16 +20,30 @@ It describes the implementation trajectory and phased engineering milestones for
---
## 🔍 Current Implementation Baseline vs. Target Architecture
| Architectural Area | Current Implementation Baseline (Milestone P3) | Target Architecture (Roadmap v5) |
| :--- | :--- | :--- |
| **`appctl` Architecture** | Bash CLI wrapper (`scripts/appctl`) driving local subprocesses (`docker compose`, `git`) and Python engine. | Dedicated daemon service (`homelab-appctl.service`) exposing one logical API over Unix socket and HTTP. |
| **Operational Auth** | Host Unix permissions; sourcing runtime secrets from `/run/secrets/`. | Mandatory auth middleware in daemon (P4 admission gate); LLDAP directory RBAC, user-scoped API tokens, and Authelia ForwardAuth (P5). |
| **Metadata & Schema Engine** | Unified engine (`scripts/appctl_engine.py`) with two-axis provenance and fail-closed Pydantic v2 schema v1.0 parser (`scripts/core_manifest.py`). | Control-plane daemon invokes `core_manifest.py` / `appctl_engine.py` through a stable internal Python interface. |
| **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites/<app>/`. | 5-stage lifecycle (planned in P6): `DeploymentProposal` $\to$ operator-approved `DeploymentModel` in Git $\to$ `appctl` materialization. |
| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) with HMAC-SHA256 auth, Compose AST security validator, and `flock` serialization. | Integrated into control-plane admission, invoking central reconciliation endpoints. |
| **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). |
| **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). |
---
## 📊 Milestone Overview
| Milestone | Title | Focus Area | Status | Deliverables Summary |
| :--- | :--- | :--- | :--- | :--- |
| **P0** | **Baseline Consolidation** | Git & Architecture | ✅ **Completed** | Synchronized `refactor/appctl-rework` with `main`, recorded control plane ADR, scaffolded v2 metadata engine. |
| **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Move Stalwart to `smtp.roadtotech.me`; migrate SnappyMail to `~/Sites/snappymail` with zero data loss. |
| **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Re-homed Stalwart to the dedicated `smtp.` subdomain; migrated SnappyMail to `~/Sites/snappymail` with zero data loss. |
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. |
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0, authoritative `core_manifest.py` library, two-axis status inspection, engine promotion. |
| **P4** | **Control Plane Daemon** | API & Dispatch | 🎯 **Current / Up Next** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), thin-client CLI, append-only audit log. |
| **P5** | **Identity & Secrets** | Auth & Providers | ⏳ **Planned** | ForwardAuth header parsing, user-scoped API tokens, `SecretProvider` reference resolution. |
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 fail-closed models (`core_manifest.py`), two-axis status inspection, unified `appctl_engine.py`. |
| **P4** | **Control Plane Daemon** | API & Dispatch | 🎯 **Current / Up Next** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
| **P5** | **Identity & Secrets** | Auth & Providers | ⏳ **Planned** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. |
| **P6** | **Deployment Model & AI**| Intent Authoring | ⏳ **Planned** | Capability catalog, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. |
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
@@ -44,9 +54,9 @@ It describes the implementation trajectory and phased engineering milestones for
### Milestone P0: Baseline Consolidation
**Status**: ✅ **Completed**
* Merged `refactor/appctl-rework` and `main` into a unified architectural baseline (commit `2297cd5`).
* Modernized metadata engine (`scripts/appctl_engine_v2.py`) with strongly-typed dataclasses (`SitesApp`, `CoreService`, `SourceConfig`) and Docker status inspection.
* Formalized the control-plane ADR and Roadmap v5 in the central knowledge vault; marked legacy roadmaps as superseded.
* Verified test suite (47 tests passing) and NixOS flake sandbox evaluation.
* Modernized metadata engine with strongly-typed models (`SitesApp`, `CoreService`, `SourceConfig`) and Docker status inspection.
* Formalized the control-plane ADR and Roadmap v5; marked legacy roadmaps as superseded.
* Verified test suite and NixOS flake sandbox evaluation.
---
@@ -57,8 +67,8 @@ It describes the implementation trajectory and phased engineering milestones for
1. *State Freeze & Verified Snapshot*: Generate timestamped, SHA256-verified backup archive of `Core/config/snappymail/data`.
2. *Workload Provisioning*: Scaffold `~/Sites/snappymail/` (Class B Image-Only workload) and provision persistent state root at `~/var/lib/homelab/snappymail/`.
3. *Zero-Data-Loss State Replication*: Copy data using `cp -a` and prove byte parity (`diff -r`).
4. *Stalwart Re-homing*: Update Stalwart public endpoint in `Core/docker-compose.yml` to `smtp.roadtotech.me`; remove SnappyMail from Core stack.
5. *Live Verification*: Verify webmail at `mail.roadtotech.me`, user logins, address books, IMAP/SMTP routing, and Diun SMTPS delivery on port 465.
4. *Stalwart Re-homing*: Updated Stalwart public endpoint in `Core/docker-compose.yml` to the configured `smtp.<domain>` subdomain; removed SnappyMail from Core stack.
5. *Live Verification*: Verified webmail at the configured `mail.<domain>` endpoint, user logins, address books, IMAP/SMTP routing, and Diun SMTPS delivery on port 465.
* **Exit Criteria**: 100% of user data survives cutover; mail flow and Diun alert delivery confirmed.
---
@@ -79,31 +89,32 @@ It describes the implementation trajectory and phased engineering milestones for
**Status**: ✅ **Completed**
* **Objective**: Establish a single authoritative manifest schema and two-axis inspection engine across the platform.
* **Key Deliverables**:
1. *Schema v1.0 & Parser Library (`core_manifest.py`)*: Strongly-typed manifest parsing, transport scheme validation (`https://`, `ssh://`, `git@`), and explicit ref semantics (moving branches vs. pinned tags vs. commit SHAs).
1. *Schema v1.0 & Parser Library (`core_manifest.py`)*: Fail-closed Pydantic v2 manifest validation (`ConfigDict(extra="forbid")`), transport scheme validation (`https://`, `ssh://`, `git@`), and explicit ref semantics (moving branches vs. pinned tags vs. commit SHAs).
2. *Two-Axis Inspection*: Local deployment checkout state (`✓ Synced`, `* Dirty`) evaluated independently of upstream software provenance (resolved via `git ls-remote` bounded by a 10s timeout during `--fetch`).
3. *Engine Promotion*: Promote `scripts/appctl_engine_v2.py` to `scripts/appctl_engine.py` with complete behavioral test coverage.
3. *Engine Promotion & Cleanup*: Promoted unified engine to `scripts/appctl_engine.py`, retired `scripts/appctl_engine_v2.py` shim, and achieved zero Pyright static analysis warnings.
* **Exit Criteria**: Manifest validation active in CI; all provenance resolution tests passing.
---
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API
**Status**: 🎯 **Current / Up Next**
* **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon.
* **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon while enforcing authorization gates from day one.
* **Key Deliverables**:
1. *Daemon Service (`homelab-appctl.service`)*: Systemd daemon exposing one logical API across dual transports: Unix domain socket (`/run/homelab/appctl.sock`) on host and HTTP listener for network clients.
2. *Command-Oriented Operational Router*: Strongly-typed endpoints (`POST /operations/deploy`, `POST /operations/restart`, `POST /operations/pull`, `GET /workloads`, `GET /workloads/{id}/status`, `POST /operations/sync`).
3. *Thin-Client CLI*: Re-implement `scripts/appctl` as a lightweight dispatch client communicating with the local daemon socket.
4. *Append-Only Audit Log*: Record every mutating command to `~/.local/state/homelab/appctl/audit.jsonl` with restricted `0600` permissions. Telemetry captures `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`.
* **Exit Criteria**: Hermetic API test suite passing; local socket and HTTP transport tests passing; audit log correctly capturing multi-dimensional telemetry.
2. *Mandatory Authorization Gate*: Establish the authentication/authorization middleware interface before exposing mutating routes; reject unauthenticated mutations across both Unix socket and HTTP transports.
3. *Command-Oriented Operational Router*: Strongly-typed endpoints (`POST /operations/deploy`, `POST /operations/restart`, `POST /operations/pull`, `GET /workloads`, `GET /workloads/{id}/status`, `POST /operations/sync`) invoking `core_manifest.py` and `appctl_engine.py` via internal interfaces.
4. *Thin-Client CLI*: Re-implement `scripts/appctl` as a lightweight dispatch client communicating with the local daemon socket.
5. *Append-Only Audit Log*: Record every mutating command to `~/.local/state/homelab/appctl/audit.jsonl` with restricted `0600` permissions. Telemetry captures `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`.
* **Exit Criteria**: Hermetic API test suite passing; unauthenticated mutation attempts rejected across both transports; audit log capturing multi-dimensional telemetry.
---
### Milestone P5: Identity, RBAC & SecretProvider Interface
**Status**: ⏳ **Planned**
* **Objective**: Implement least-privilege identity boundaries and dynamic secret projection.
* **Objective**: Expand the P4 authorization gate with directory-backed RBAC identity providers and dynamic secret projection.
* **Key Deliverables**:
1. *Authentication Gateway*: Accept trusted identity headers from Traefik/Authelia (`Remote-User`, `Remote-Groups`) for web requests; validate explicit user-scoped API tokens for all CLI requests (local and remote); validate HMAC signatures for GitOps webhooks.
2. *Role-Based Authorization Engine*: Enforce group-based access control (`homelab-admin`, `homelab-operator`, `homelab-viewer`).
1. *Identity Provider Integration*: Plug Traefik/Authelia trusted headers (`Remote-User`, `Remote-Groups`) for web requests, LLDAP user-scoped API token lifecycle for CLI requests, and HMAC-SHA256 verification for GitOps webhooks into the P4 authorization middleware.
2. *Role-Based Authorization Engine*: Enforce LLDAP group-based access control (`homelab-admin`, `homelab-operator`, `homelab-viewer`).
3. *SecretProvider Interface*: Control plane resolves secret references (`secretKeyRef`) at container runtime, eliminating Git history pollution for workload credentials.
* **Exit Criteria**: RBAC permission matrix verified by automated tests; secret references correctly materialized into runtime environments.
+13 -11
View File
@@ -1,5 +1,5 @@
{
description = "Homelab Core — Turnkey Declarative NixOS Appliance for roadtotech.me";
description = "Homelab Core — Turnkey Declarative NixOS Appliance";
inputs = {
nixpkgs.url = "https://channels.nixos.org/nixos-unstable/nixexprs.tar.zst";
@@ -14,6 +14,12 @@
let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
pythonEnv = pkgs.python3.withPackages (ps: with ps; [
pyyaml
types-pyyaml
pytest
pydantic
]);
in
{
nixosConfigurations.server = nixpkgs.lib.nixosSystem {
@@ -27,17 +33,16 @@
devShells.${system}.default = pkgs.mkShell {
buildInputs = with pkgs; [
(python3.withPackages (ps: with ps; [
pyyaml
types-pyyaml
pytest
pydantic
]))
pythonEnv
pyright
ruff
];
shellHook = ''
git config core.hooksPath .githooks 2>/dev/null || true
if [ -d .venv ] && [ ! -L .venv ]; then
rm -rf .venv
fi
ln -sfn ${pythonEnv} .venv
'';
};
@@ -45,10 +50,7 @@
test-suite = pkgs.runCommand "core-tests" {
nativeBuildInputs = with pkgs; [
git
python3
python3Packages.pytest
python3Packages.pyyaml
python3Packages.pydantic
pythonEnv
ruff
];
} ''
+12 -3
View File
@@ -8,14 +8,23 @@ echo "🔍 Running code linters (ruff)..."
if command -v ruff &>/dev/null; then
ruff check .
else
nix-shell -p ruff --run "ruff check ."
nix develop --command ruff check .
fi
echo "🔎 Running static type analysis (pyright)..."
if command -v pyright &>/dev/null; then
pyright
else
nix develop --command pyright
fi
echo "🧪 Running architecture & security test suite (pytest)..."
if command -v pytest &>/dev/null; then
if [ -x ".venv/bin/pytest" ]; then
.venv/bin/pytest tests/
elif command -v pytest &>/dev/null; then
pytest tests/
else
nix-shell -p python3Packages.pytest python3Packages.pyyaml python3Packages.pydantic --run "pytest tests/"
nix develop --command pytest tests/
fi
echo "❄️ Verifying NixOS flake & sandbox checks..."