Files
second-brain/01-plans/homelab/appctl/appctl-engine-v2-refactoring.md
T
kiskaadee f0f4c31811 plan(homelab): define architecture consolidation and control plane roadmap v5
- Add comprehensive v5 roadmap unifying appliance baseline and phases P0-P4 for the appctl control plane.
- Mark superseded plans (roadmap v4, implementation guide v3, appctl engine v2, and smart deployment pipeline) with forward references to roadmap v5.
2026-10-08 00:04:59 -05:00

15 KiB

type, status, project, date, tags
type status project date tags
plan superseded homelab 2026-09-21
operations
architecture
homelab
appctl
python
refactoring
testing
pytest

🚀 appctl Engine V2: Architectural Modernization & Type-Safe Refactoring Plan

Superseded by: Architecture Consolidation & Control Plane Roadmap v5 (specifically Phases P0, P3, and P4). Engine modernization code has been integrated into the consolidated baseline and control-plane architecture.

1. Executive Summary & Intent

The appctl control utility is the central metadata, discovery, and inspection engine for the roadtotech.me homelab. It derives operational views (Docker status, Git sync status, SSL/TLS validation, Homepage dashboard generation, shell completion) from application manifests (Sites/*/app.yaml) and Core platform definitions.

This plan modernizes the engine from a procedural ~900-line script with a hand-rolled YAML parser into a clean, strongly-typed, test-driven Python engine (appctl_engine_v2.py) with zero breaking changes to the bash caller interface (scripts/appctl).


2. Problem Statement & Motivation

Issue in V1 Engine Architectural Risk V2 Solution
Handmade YAML Parser (parse_yaml_simple) Fragile indentation parser; silently mishandled complex structures, quotes, multiline strings, or standard YAML types. Replace with standard yaml.safe_load() via PyYAML (flake.nix & nixos).
Silent Error Suppression (contextlib.suppress) Swallowed all YAML errors; syntax mistakes in app.yaml silently degraded into empty defaults without operator notification. Define class ManifestError(Exception) and capture errors into app.manifest_error for explicit reporting.
Stringly-Typed Dictionaries Unstructured dict[str, Any] passed everywhere with loose key lookups (app["domain"], app["name"]). Strict @dataclass hierarchy: App, SitesApp, CoreService, HomepageConfig, SSLCertResult.
Domain Hardcoding Hardcoded roadtotech.me strings throughout code, violating portability and open-source reusability. Dynamic HOMELAB_DOMAIN = os.environ.get("HOMELAB_DOMAIN") + fail-fast validate_environment().
Zero Test Coverage No automated tests for resolution precedence, manifest parsing, or Homepage compilation. Comprehensive TDD test suite in tests/unit/test_appctl_engine_v2.py with AppFactory fixture.

3. Architecture & Domain Model

┌─────────────────────────────────────────────────────────────┐
│                    scripts/appctl (Bash)                    │
│           (Mutation: up, down, restart, update, logs)       │
└──────────────────────────────┬──────────────────────────────┘
                               │ JSON via `resolve` & stdout
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                scripts/appctl_engine_v2.py                  │
│          (Inspection, Metadata, Discovery & Sync)           │
├─────────────────────────────────────────────────────────────┤
│ 1. Domain Hierarchy                                         │
│    ├── SourceConfig (Provenance: type, url, ref)            │
│    ├── App (Base: name, description, domain, dir_path)     │
│    ├── SitesApp (Sites: source, aliases, visible, auth)     │
│    └── CoreService (Core: container, weight, icon)          │
├─────────────────────────────────────────────────────────────┤
│ 2. Ingestion & Normalization                                │
│    ├── load_manifest() -> raw dict (PyYAML)                 │
│    └── sites_app_from_manifest() -> SitesApp (Pure Seam)    │
├─────────────────────────────────────────────────────────────┤
│ 3. Inspection Engines                                       │
│    ├── Docker Status & OCI Image Label Inspection           │
│    ├── Deployment Git Status (local Sites repository)       │
│    ├── Source Provenance Resolver (git ls-remote --fetch)   │
│    └── TLS/SSL Validation (stdlib socket/ssl via ThreadPool)│
├─────────────────────────────────────────────────────────────┤
│ 4. CLI Dispatch Layer                                       │
│    ├── cmd_list / cmd_status (polymorphic table rendering)  │
│    ├── cmd_info (unified diagnostics & provenance view)     │
│    ├── cmd_ssl (TLS overview across apps and Core)          │
│    ├── cmd_resolve (JSON emitter for bash caller)           │
│    ├── cmd_sync_homepage (compiles services.yaml)           │
│    └── cmd_complete (bash autocomplete generator)           │
└─────────────────────────────────────────────────────────────┘

4. Deliverables & Execution Roadmap

Deliverable 1: Domain Model, Manifest Ingestion & TDD Scaffold (COMPLETE / GREEN)

  • Create isolated Git worktree at ~/Projects/active/appctl-refactor.
  • Configure Pyright and Nix devShell (python3.withPackages [ pyyaml types-pyyaml pytest ruff pyright ]).
  • Implement @dataclass class SourceConfig(type, url, ref) with explicit ref semantics.
  • Implement @dataclass class App, SitesApp(source: SourceConfig | None), CoreService, and HomepageConfig.
  • Implement load_manifest(manifest_path) with ManifestError.
  • Implement pure normalization seam sites_app_from_manifest(app_dir, manifest, manifest_error).
  • Implement dynamic discovery get_sites_apps(sites_dir) and resolve_app(query, apps).
  • Implement typed Core registry get_core_services(core_dir).
  • Implement validate_environment() for fail-fast domain and path verification.
  • Scaffold test suite in tests/unit/test_appctl_engine_v2.py with mock_sites_dir, mock_core_dir, and AppFactory.

Deliverable 2: Inspection Layer (IN PROGRESS)

  • Docker Inspection Engine:
    • Implement get_docker_status(dir_path: Path | str, container_name: str | None = None) -> str.
    • Handle Compose directory inspection (docker compose ps -q + inspect).
    • Handle Core single container inspection (docker inspect -f '{{.State.Running}}' <name>).
    • Return standardized status badges (🟢 Running (N), 🟡 Degraded (M/N), 🔴 Stopped, ⚪ Not Stack, ❓ Unknown).
    • Extract container image labels: specifically org.opencontainers.image.revision for software provenance.
  • Two-Axis Git & Source Provenance Engine:
    • Axis 1: Deployment Git Status:
      • Implement get_deployment_git_status(dir_path: Path | str) -> str.
      • Parse git status --porcelain and git rev-list --left-right --count HEAD...@{u}.
      • Return standardized badges (✓ Synced, ⬆ N Ahead, ⬇ N Behind, ⚡ N⬆ M⬇, ⚪ Untracked, * dirty indicator).
    • Axis 2: Source Provenance Resolver:
      • Implement get_source_provenance_status(app: SitesApp, fetch_remote: bool = False) -> str.
      • If app.source is None: return ⚪ Image Only (display container image tag).
      • If app.source.ref is a pinned tag or commit SHA: return 📌 Pinned (<ref>).
      • Extract running container's org.opencontainers.image.revision (deployed SHA).
      • If fetch_remote=True: resolve remote ref SHA via git ls-remote <url> refs/heads/<ref>.
      • Compare revisions:
        • Remote SHA == Deployed SHA: ✓ Up to date (<sha>)
        • Remote SHA != Deployed SHA: ⚡ Revision Changed
    • Implement get_git_diagnostics(dir_path: Path | str, app: SitesApp | None = None) -> dict[str, Any] | None.
  • SSL / TLS Inspection Engine:
    • Define @dataclass class SSLCertResult.
    • Implement check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> SSLCertResult.
    • Implement check_all_ssl_certs(domains: list[str]) -> dict[str, SSLCertResult] with ThreadPoolExecutor.
  • Concurrent Remote Fetching:
    • Implement fetch_all_repositories(apps: list[SitesApp], include_core: bool = True) with worker pool.
    • Concurrently resolves git fetch for local deployment repositories and git ls-remote for source-backed workloads.

Deliverable 3: Presentation & CLI Dispatch Layer

  • cmd_list / cmd_status:
    • Support --core / -c, --fetch / -f, --ssl / -s, and --all / -a flags.
    • Polymorphic table formatting for both SitesApp and CoreService.
    • Display two-axis status: Deployment checkout state + Upstream revision badge.
    • Render manifest warning indicators if app.manifest_error is populated.
  • cmd_info:
    • Formatted deep diagnostic view for a single application or Core service.
    • Display metadata, Authelia guard status, Compose status, Git diagnostics, and TLS certificate info.
    • Display dedicated Source Provenance Block: Upstream Git URL, Tracking Ref, Deployed Commit SHA, and Remote HEAD SHA.
  • cmd_ssl:
    • Formatted TLS certificate table for all public domains or deep inspection of a single target.
  • cmd_resolve:
    • Emit JSON payload via app.to_dict() ensuring 100% compatibility with scripts/appctl.
  • cmd_sync_homepage:
    • Compile SitesApp cards and CoreService definitions into Core/config/homepage/services.yaml.
    • Group by homepage.group, sort by homepage.weight, and resolve local SVG/PNG icons from icons/.
  • cmd_complete:
    • Generate bash autocompletion candidates for commands, apps, aliases, and Core services.

Deliverable 4: Verification, Cutover & Documentation

  • Run full automated test suite: pytest tests/ (100% Green).
  • Run code linter: ruff check . with zero errors.
  • Run type checker: pyright with zero errors.
  • Topology Synchronization (Roadmap v4 P1 alignment):
    • Update scripts/appctl_engine_v2.py get_core_services():
      • stalwart: domain smtp.${HOMELAB_DOMAIN}.
      • Remove snappymail (discovered dynamically in ~/Sites/snappymail).
      • Remove deprecated portainer.
  • Manifest Engine Convergence (Roadmap v4 P3 alignment):
    • In ~/Projects/active/appctl-refactor, cherry-pick the atomic commit from main that introduces Core/scripts/core_manifest.py.
    • Refactor appctl_engine_v2.py to ingest manifests via core_manifest.py in place of standalone load_manifest().
    • Update unit test fixtures in tests/unit/test_appctl_engine_v2.py to validate against schema v1.0 models.
  • Promote scripts/appctl_engine_v2.py to scripts/appctl_engine.py within refactor/appctl-rework.
  • Merge refactor/appctl-rework into main.
  • Run ./scripts/test and live verification (appctl list, appctl info, appctl sync) on main.
  • Update docs/appctl.md with V2 architecture and developer documentation.

4.5 Cross-Track Coordination with Architecture Roadmap v3

The appctl-v2 refactor operates as Track B (modernizing implementation in worktree ~/Projects/active/appctl-refactor on branch refactor/appctl-rework), running parallel to the Homelab Architecture Consolidation Roadmap v3 (Track A on main).

Track B: appctl-v2 (refactor/appctl-rework)
    │  (internal modernizations: dataclasses, PyYAML, TDD)
    │
    │ integration seam (cherry-pick core_manifest.py commit from main)
    ▼
Track A: Homelab Architecture (main)
    ├── P1: Mail topology (minimal compatibility patch to legacy engine on main)
    ├── P2: GitOps authority (independent of appctl)
    └── P3: Manifest convergence (DELIBERATE JOIN POINT where Track B merges to main)

Branch Operating Rules

  1. Isolated Development: refactor/appctl-rework is NOT rebased or merged into main during P1 or P2. Frequent cross-merging between active branches is strictly avoided.
  2. Minimal Legacy Patching: P1 modifies legacy appctl_engine.py on main strictly to update the stalwart domain and remove snappymail. Track B applies the identical semantic change directly to its typed CoreService definitions without merging git branches.
  3. P3 Controlled Convergence Direction:
    • core_manifest.py originates on main (tested with GitOps and existing platform tests).
    • Track B brings that specific commit into refactor/appctl-rework via git cherry-pick.
    • appctl-v2 adapts its normalization seam to core_manifest.py and confirms all unit tests pass in its worktree.
    • On refactor/appctl-rework, scripts/appctl_engine_v2.py is promoted to scripts/appctl_engine.py.
    • The tested, compliant refactor/appctl-rework branch is then merged into main.

5. Invariants & Acceptance Criteria

  1. Zero Breaking Changes to Bash Contract: scripts/appctl must function identically with appctl list, appctl info <app>, appctl up <app>, appctl sync, and autocompletions without requiring syntax or argument changes.
  2. Deterministic Test Suite: Unit tests in tests/unit/test_appctl_engine_v2.py must run hermetically without requiring a live Docker daemon, live network access, or mutating the user's real ~/Sites or ~/Core.
  3. The Unlicense Integrity: All new files and refactored code preserve public domain status under The Unlicense.
  4. Architectural Seams Preserved for Roadmap v3: appctl_engine_v2.py must preserve the 5 architectural seams until convergence at P3:
    • CLI Syntax: Invocation syntax, subcommands, and flags unchanged.
    • resolve JSON Contract: Emits exact keys required by scripts/appctl: required name, dir_path, type ("app" or "core_service"), domain, plus contextual container and env. Backed by an automated test fixture.
    • Canonical Identity: Service identifiers remain stable within the systems that own them; Core services and Sites workloads use their canonical names consistently.
    • Core vs. Sites Taxonomy: Platform capabilities in Core vs. independent workloads in Sites strictly maintained.
    • Homepage Sync Semantics: services.yaml compilation matches existing schema.