docs(plan): align roadmap, ADR-0002, and tasks with MCP gateway and decoupling plan

- Add master implementation plan in docs/plans/p4-refactor-and-decoupling-plan.md
  outlining operator identity migration, dynamic LDAP base DN derivation,
  recursive POSIX ACLs, and host Git safe directory requirements.
- Re-scope Milestone P6 in ROADMAP.md, ADR-0002, and decision index to
  Homelab MCP Gateway, formally deprecating on-server AI deployment compilers
  in favor of external JSON-RPC protocol tools with human-in-the-loop gating.
- Reconcile docs/appctl.md regarding bounded container log snapshots (--tail)
  and Core platform update mechanics via NixOS rebuilds.
- Populate todo.txt with prioritized implementation tasks for the upcoming
  decoupling and control plane hardening work.
This commit is contained in:
kiskaadee committed 2026-10-23 16:54:11 -05:00
1 parent 3230e08bf9
commit ce7ffa8c46
6 files changed
+116 -18

No files matched your search

+9 -9
View File
@@ -46,7 +46,7 @@ It describes the implementation trajectory and phased engineering milestones for
| **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`. | | **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 | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. | | **P4** | **Control Plane Daemon** | API & Dispatch | ✅ **Completed** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), mandatory auth admission gate, thin-client CLI, append-only audit log. |
| **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | LLDAP RBAC group mapping, Authelia ForwardAuth header integration, user-scoped token lifecycle, `SecretProvider` reference resolution. | | **P5** | **Identity & Secrets** | Auth & Providers | 🎯 **Current / Up Next** | 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. | | **P6** | **Homelab MCP Gateway** | Protocol Integration | ⏳ **Planned** | Standardized JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`), client-side human-in-the-loop approvals, deprecation of on-server AI proposal compilers. |
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. | | **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
--- ---
@@ -122,15 +122,15 @@ It describes the implementation trajectory and phased engineering milestones for
--- ---
### Milestone P6: Homelab Deployment Model & AI Authoring Workflow ### Milestone P6: Homelab MCP Gateway (Protocol Tool Integration)
**Status**: ⏳ **Planned** **Status**: ⏳ **Planned** *(Amended: Deprecated on-server `DeploymentProposal` compiler in favor of decoupled Model Context Protocol gateway)*
* **Objective**: Enable safe, human-reviewed workload authoring from upstream repositories. * **Objective**: Expose `appctl` control plane capabilities over standardized JSON-RPC Model Context Protocol (MCP) tools for external AI assistants (Antigravity, Claude Code, Cursor) without running unverified autonomous agents on the appliance host.
* **Key Deliverables**: * **Key Deliverables**:
1. *Platform Capability Catalog*: Machine-readable specification of Core capabilities and security invariants. 1. *Protocol Tool Gateway*: Standardized MCP server wrapping deterministic `appctl` operations (`appctl_status`, `appctl_logs`, `appctl_deploy`, `appctl_audit`) over JSON-RPC.
2. *DeploymentProposal Schema*: Candidate model format produced by AI discovery workflows. 2. *Client-Side Human-in-the-Loop Confirmation*: Native IDE/client confirmation gating for all mutating tools before execution.
3. *DeploymentModel Git Pipeline*: Operator approves proposal into a `DeploymentModel`; the model is committed to the version-controlled deployment repository (Git). 3. *Deprecate On-Server AI Proposal Compiler*: Remove requirements for server-side `DeploymentProposal` $\to$ `DeploymentModel` pipelines; desired state remains standard Git-tracked declarative YAML (`app.yaml` + Compose).
4. *Materialization & Reconciliation*: `appctl` validates the committed model, provisions state roots, compiles platform descriptors (`app.yaml` + Compose), and reconciles running containers. 4. *Schema & Tool Security Guards*: Strict Pydantic parameter validation on incoming MCP tool calls matching `appctl_contracts.py`.
* **Exit Criteria**: Human approval gate strictly enforced; AI possesses zero execution authority; generated workloads conform to all Core invariants. * **Exit Criteria**: External AI clients successfully query status, inspect logs, and request deployments through MCP with strict confirmation gates; Core boundaries remain 100% deterministic with zero autonomous agent code on the host.
--- ---
+8 -4
View File
@@ -116,19 +116,23 @@ Restarts the target stack or individual container:
* `appctl restart core`: Restarts all Core Compose services. * `appctl restart core`: Restarts all Core Compose services.
* `appctl restart traefik`: Restarts only the Traefik container. * `appctl restart traefik`: Restarts only the Traefik container.
#### `appctl update <service|core>` #### `appctl update <service>`
Performs a sequential update workflow: Performs a sequential update workflow for a Sites workload stack:
1. Verifies that the local Git working tree is clean (aborts if uncommitted changes exist). 1. Verifies that the local Git working tree is clean (aborts if uncommitted changes exist).
2. Runs `git pull --ff-only` to fast-forward the current branch. 2. Runs `git pull --ff-only` to fast-forward the current branch.
3. Runs `docker compose pull` to fetch updated container images. 3. Runs `docker compose pull` to fetch updated container images.
4. Runs `docker compose up -d --remove-orphans` to recreate containers. 4. Runs `docker compose up -d --remove-orphans` to recreate containers.
5. Runs `appctl sync` to update the Homepage dashboard. 5. Runs `appctl sync` to update the Homepage dashboard.
> [!NOTE]
> Core platform updates are managed via version-controlled NixOS generations (`git pull` followed by `nixos-rebuild switch`), not through `appctl update core` (as Core is mounted read-only for `homelab-appctl.service`).
#### `appctl pull <service|core>` #### `appctl pull <service|core>`
Pulls latest container images and recreates the target service. Pulls latest container images and recreates the target service.
#### `appctl logs <service|core>` #### `appctl logs <service|core> [--tail N]`
Streams container logs (`docker compose logs -f`). Supports passing specific container names (`appctl logs core traefik` or `appctl logs stalwart`). Fetches a bounded snapshot of container logs (default: `--tail 100`). Supports passing a workload or targeted Core service container (e.g., `appctl logs traefik`).
*(Note: As an HTTP/1.1 request-response API, log streaming `-f` is replaced by bounded snapshots).*
#### `appctl config <service|core>` #### `appctl config <service|core>`
Validates the manifest and renders the resolved Docker Compose configuration with all injected variables. Fails closed if `app.yaml` is missing or invalid. Validates the manifest and renders the resolved Docker Compose configuration with all injected variables. Fails closed if `app.yaml` is missing or invalid.
@@ -95,11 +95,10 @@ Chosen option: **Option 3: Authoritative `homelab-appctl.service` Daemon with Si
* Shell `eval` and `source` are completely eliminated. Subprocess environments are assembled in memory via an inert pure-Python `KEY=VALUE` reader enforcing `ENV_KEY_RE`, `RESERVED_ENV_KEYS`, and canonical domain precedence (`HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN`). * Shell `eval` and `source` are completely eliminated. Subprocess environments are assembled in memory via an inert pure-Python `KEY=VALUE` reader enforcing `ENV_KEY_RE`, `RESERVED_ENV_KEYS`, and canonical domain precedence (`HOMELAB_DOMAIN` $\to$ `DOMAIN_SUFFIX` $\to$ `DOMAIN`).
* Every workload mutation and `workload.config` call enforces path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` pre-flight inspection before invoking Docker Compose. * Every workload mutation and `workload.config` call enforces path containment, `core_manifest.parse_manifest()`, and `validate_compose_security()` pre-flight inspection before invoking Docker Compose.
#### 6. Declarative Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7 Trajectory) #### 6. Declarative Git Truth, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7 Trajectory)
* **Git is Authoritative**: Approved deployment definitions are versioned in Git; `appctl` reconciles desired Git state into running containers. * **Git is Authoritative**: Approved deployment definitions are versioned in Git; `appctl` reconciles desired Git state into running containers.
* **Five-Stage Model Lifecycle (P6)**: * **Architecture Amendment (2026-10-23 — MCP Tool Gateway Supersedes On-Server Authoring)**:
$$\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}$$ The 5-stage on-server AI deployment authoring compiler (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel`) originally planned for Milestone P6 is **deprecated and superseded by a decoupled Model Context Protocol (MCP) Tool Gateway**. Rather than building bespoke AI authoring engines or autonomous agents into the appliance host, platform management operations (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`) will be exposed via standardized JSON-RPC MCP tools consumed by external developer clients (Antigravity, Claude Code, Cursor) with native human-in-the-loop confirmation. The deterministic boundary of `appctl` is preserved, with zero autonomous AI agent code executing inside the appliance host.
* **AI Authoring Boundary (P6)**: AI agents act strictly as upstream `DeploymentProposal` generators with zero execution or mutation authority.
* **Secret Reference Invariant (P5)**: Manifests reference secrets by key (`secretKeyRef`) resolved at runtime via `SecretProvider`, never storing plaintext credentials in Git. * **Secret Reference Invariant (P5)**: Manifests reference secrets by key (`secretKeyRef`) resolved at runtime via `SecretProvider`, never storing plaintext credentials in Git.
* **Client Decoupling (P7)**: Homepage remains a read-only status portal; interactive web management belongs to a dedicated Operations UI client consuming `POST /v1/operations`. * **Client Decoupling (P7)**: Homepage remains a read-only status portal; interactive web management belongs to a dedicated Operations UI client consuming `POST /v1/operations`.
+1 -1
View File
@@ -38,7 +38,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an authenticated SHA-256 Bearer token (`/run/secrets/appctl/tokens.json`); tokenless UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection. 2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an authenticated SHA-256 Bearer token (`/run/secrets/appctl/tokens.json`); tokenless UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection.
3. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: Daemon executes as `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl` and a pre-execution `DISPATCHED` disk guard. 3. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: Daemon executes as `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl` and a pre-execution `DISPATCHED` disk guard.
4. **GitOps Worker Unification & Pure-Python Pre-Flight (`DEC-04`, `DEC-05`)**: `gitops_dispatcher.py` worker delegates `workload.update` to the daemon; shell `source`/`eval` are replaced with pure-Python `.env` parsing and mandatory `validate_compose_security()` pre-flight checks. 4. **GitOps Worker Unification & Pure-Python Pre-Flight (`DEC-04`, `DEC-05`)**: `gitops_dispatcher.py` worker delegates `workload.update` to the daemon; shell `source`/`eval` are replaced with pure-Python `.env` parsing and mandatory `validate_compose_security()` pre-flight checks.
5. **Git Truth, Five-Stage Deployment Model & AI Boundary (P5–P7)**: Git remains authoritative deployment state; separates `ApplicationProfile` $\to$ `DeploymentProposal` (AI) $\to$ `DeploymentModel` (human-approved in Git) $\to$ materialized descriptors; resolves workload secrets via `SecretProvider` (`secretKeyRef`). 5. **Git Truth, Model Context Protocol (MCP) Gateway & AI Boundary (P5–P7)**: Git remains authoritative deployment state; on-server AI proposal compilers deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway with human confirmation gating; resolves workload secrets via `SecretProvider` (`secretKeyRef`).
### [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md) ### [ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model](0001-3tier-architecture-and-provenance.md)
* **Canonical Document**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md) * **Canonical Document**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md)
@@ -0,0 +1,87 @@
# 📋 Implementation Plan: Control Plane Hardening, Instance Decoupling & MCP Alignment
**Document Version**: 1.0
**Status**: 🚀 Approved for Implementation
**Date**: 2026-10-23
**Target Milestone**: P4 Hardening & P6 Deprecation
**Branch**: `refactor/appctl-rework`
---
## 1. Executive Summary & Context
During the pre-merge readiness investigation of the `refactor/appctl-rework` branch, four deployment blockers and several architectural divergences were identified:
1. **Unconfigured Root Domain**: `options.homelab.domain` defaulted to `"example.test"`, which would overwrite live routing templates (`homeserver.env`, `traefik-deployments.env`) upon `nixos-rebuild switch`.
2. **Authelia/LLDAP Base DN Desynchronization**: Compose defaulted `LLDAP_LDAP_BASE_DN` to `dc=example,dc=test`, conflicting with the existing on-host LLDAP database (`dc=<domain-prefix>,dc=<tld>`).
3. **Operator Identity Coupling**: Core configurations referenced legacy operator username literals rather than a generic system operator (`operator`).
4. **POSIX ACL & Git Dubious Ownership**: `tmpfiles.rules` used lowercase `a+` (non-recursive), leaving existing checkouts in `~/Sites` unwriteable to `homelab-appctl`. Furthermore, Git 2.35.2+ lacked `safe.directory` declarations for `homelab-appctl`.
5. **AI Authoring Boundary Evolution**: Earlier architectural planning explored an on-server 5-stage deployment authoring pipeline (`ApplicationProfile` $\to$ `DeploymentProposal` $\to$ `DeploymentModel` compiler). This requirement is formally deprecated in favor of a decoupled Model Context Protocol (MCP) tool gateway.
This plan establishes the concrete implementation work packages to resolve these findings and ensure 100% deployment safety.
---
## 2. Architectural Decisions & Scope
### A. Operator Identity Decoupling (Legacy Operator $\to$ `operator`)
- Standardize the primary platform operator as `operator` with home directory `/home/operator`.
- `config.homelab.operatorUser` defaults to `"operator"`.
- NixOS declares user `operator` (`uid = 1000` or standard user, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`).
- Eliminates hardcoded personal usernames from the Core platform foundation.
### B. Platform Genericism & Instance Profile
- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test`).
- `nixos/configuration.nix` serves as the appliance instance profile where `homelab.domain` and `homelab.operatorUser` are explicitly set (e.g., using the host's configured production domain).
- `LLDAP_LDAP_BASE_DN` is computed dynamically in Nix from `config.homelab.domain` (`domain: example.test` $\implies$ `dc=example,dc=test`), eliminating hardcoded domain strings across templates and Compose files.
### C. Control Plane Security & POSIX Permissions
- **Recursive ACLs**: Change `a+` to uppercase `A+` for `${config.homelab.sitesDir}` and `${config.homelab.coreDir}/config/homepage` in `systemd.tmpfiles.rules`.
- **Git Safe Directory**: Configure `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` for the host.
- **Fail-Closed CLI**: If `/run/homelab/appctl.sock` is unavailable, `scripts/appctl` fails closed with an informative error rather than silently falling back to unauthenticated Bash execution.
- **CLI Status Restoration**: Restore live container inspection (`get_docker_status()`) in `workload.list` and format the `STATUS` column in `scripts/appctl_cli.py`.
### D. Deprecation of On-Server AI Authoring Pipeline (MCP Gateway Adoption)
- As documented in `~/Brain/02-discussions/homelab/mcp-gateway-and-platform-evolution.md`, on-server AI deployment agents (`DeploymentProposal` compilers) are deprecated.
- Milestone P6 is redefined as the **Homelab MCP Gateway**:
- Exposes deterministic `appctl` operations over JSON-RPC Model Context Protocol tools (`appctl_status`, `appctl_deploy`, `appctl_logs`, `appctl_audit`).
- Gated by native client-side human confirmation (Antigravity, Claude Code, Cursor).
- Keeps Core 100% deterministic with zero autonomous agent loops executing on the appliance host.
---
## 3. Work Breakdown Structure (WBS)
### Phase 1: Host Configuration & Identity Migration
- [ ] **Task 1.1**: Update `nixos/configuration.nix` to declare user `operator` and configure `homelab.operatorUser = "operator"` and `homelab.domain` with the configured production domain.
- [ ] **Task 1.2**: Declare `programs.git.config.safe.directory = [ "/home/operator/Sites/*" ]` in `nixos/configuration.nix`.
- [ ] **Task 1.3**: Derive `LLDAP_LDAP_BASE_DN` dynamically from `config.homelab.domain` in `nixos/modules/homeserver.nix` and pass it to `sops.templates."homeserver.env"`.
- [ ] **Task 1.4**: Update `docker-compose.yml` to consume `LLDAP_LDAP_BASE_DN` from `homeserver.env`.
- [ ] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`.
### Phase 2: CLI Hardening & Status Parity
- [ ] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash.
- [ ] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`).
- [ ] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`).
- [ ] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`.
### Phase 3: Architectural Records & Roadmap Synchronization
- [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated).
- [x] **Task 3.2**: Add architectural amendment note to `docs/decisions/0002-appctl-control-plane-architecture.md`.
- [x] **Task 3.3**: Update `docs/decisions/README.md`.
- [x] **Task 3.4**: Update `docs/appctl.md` (clarifying bounded log snapshots and Core update workflow).
- [x] **Task 3.5**: Synchronize `todo.txt` with active implementation tasks.
---
## 4. Verification & Quality Gates
The implementation must pass:
1. **Static Analysis & Linting**: `ruff check .` and `pyright` (0 errors, 0 warnings).
2. **Full Regression Suite**: All 283 existing unit, security, and invariant tests passing.
3. **New Test Coverage**:
- Assert dynamic LDAP base DN computation from domain.
- Assert `scripts/appctl` fails closed when socket is absent.
- Assert `appctl list` output formatting includes container status.
- Assert platform genericism invariants across updated Nix modules.
4. **Hermetic Flake Check**: `nix flake check` builds cleanly.
5. **NixOS Evaluation**: `nix eval .#nixosConfigurations.server.config.system.build.toplevel.drvPath` evaluates without warnings.
+8
View File
@@ -35,3 +35,11 @@ x 2026-10-19 (A) Restore human-readable tabular output, list filter parameters,
x 2026-10-19 (A) Add operatorUser to homelab-operators group and configure daemon systemd sandbox HOME and DOCKER_CONFIG in nixos/modules/homeserver.nix +nixos @p4 x 2026-10-19 (A) Add operatorUser to homelab-operators group and configure daemon systemd sandbox HOME and DOCKER_CONFIG in nixos/modules/homeserver.nix +nixos @p4
x 2026-10-19 (A) Provision SOPS appctl/tokens_json and gitops/appctl_token secrets and wire GITOPS_APPCTL_TOKEN_FILE in nixos/secrets.yaml and nixos/modules/homeserver.nix +secrets @p4 x 2026-10-19 (A) Provision SOPS appctl/tokens_json and gitops/appctl_token secrets and wire GITOPS_APPCTL_TOKEN_FILE in nixos/secrets.yaml and nixos/modules/homeserver.nix +secrets @p4
x 2026-10-19 (B) Reconcile operational documentation and ROADMAP.md with Milestone P4 control plane daemon architecture +docs @p4 x 2026-10-19 (B) Reconcile operational documentation and ROADMAP.md with Milestone P4 control plane daemon architecture +docs @p4
(A) Migrate operator user from kiskaadee to operator in nixos/configuration.nix and homeserver.nix +nixos @core
(A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth
(A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms
(A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git
(B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
(B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
(B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
(C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap