plan(homelab): formalize architecture consolidation roadmap v4 and provenance model
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 9s

This commit is contained in:
kiskaadee committed 2026-09-28 21:29:00 -05:00
1 parent 2670eafa20
commit 444d6149d9
5 files changed
+794 -14

No files matched your search

@@ -50,8 +50,9 @@ This plan modernizes the engine from a procedural ~900-line script with a hand-r
│ (Inspection, Metadata, Discovery & Sync) │ │ (Inspection, Metadata, Discovery & Sync) │
├─────────────────────────────────────────────────────────────┤ ├─────────────────────────────────────────────────────────────┤
│ 1. Domain Hierarchy │ │ 1. Domain Hierarchy │
│ ├── SourceConfig (Provenance: type, url, ref) │
│ ├── App (Base: name, description, domain, dir_path) │ │ ├── App (Base: name, description, domain, dir_path) │
│ ├── SitesApp (Sites: aliases, visible, auth, env, etc.) │ │ ├── SitesApp (Sites: source, aliases, visible, auth) │
│ └── CoreService (Core: container, weight, icon) │ │ └── CoreService (Core: container, weight, icon) │
├─────────────────────────────────────────────────────────────┤ ├─────────────────────────────────────────────────────────────┤
│ 2. Ingestion & Normalization │ │ 2. Ingestion & Normalization │
@@ -59,13 +60,14 @@ This plan modernizes the engine from a procedural ~900-line script with a hand-r
│ └── sites_app_from_manifest() -> SitesApp (Pure Seam) │ │ └── sites_app_from_manifest() -> SitesApp (Pure Seam) │
├─────────────────────────────────────────────────────────────┤ ├─────────────────────────────────────────────────────────────┤
│ 3. Inspection Engines │ │ 3. Inspection Engines │
│ ├── Docker Status (Compose ps -q & inspect Running) │ │ ├── Docker Status & OCI Image Label Inspection │
│ ├── Git Sync Status (plumbing porcelain & rev-list) │ │ ├── Deployment Git Status (local Sites repository) │
│ ├── Source Provenance Resolver (git ls-remote --fetch) │
│ └── TLS/SSL Validation (stdlib socket/ssl via ThreadPool)│ │ └── TLS/SSL Validation (stdlib socket/ssl via ThreadPool)│
├─────────────────────────────────────────────────────────────┤ ├─────────────────────────────────────────────────────────────┤
│ 4. CLI Dispatch Layer │ │ 4. CLI Dispatch Layer │
│ ├── cmd_list / cmd_status (polymorphic table rendering) │ │ ├── cmd_list / cmd_status (polymorphic table rendering) │
│ ├── cmd_info (unified diagnostics view) │ │ ├── cmd_info (unified diagnostics & provenance view) │
│ ├── cmd_ssl (TLS overview across apps and Core) │ │ ├── cmd_ssl (TLS overview across apps and Core) │
│ ├── cmd_resolve (JSON emitter for bash caller) │ │ ├── cmd_resolve (JSON emitter for bash caller) │
│ ├── cmd_sync_homepage (compiles services.yaml) │ │ ├── cmd_sync_homepage (compiles services.yaml) │
@@ -80,7 +82,8 @@ This plan modernizes the engine from a procedural ~900-line script with a hand-r
### Deliverable 1: Domain Model, Manifest Ingestion & TDD Scaffold (COMPLETE / GREEN) ### Deliverable 1: Domain Model, Manifest Ingestion & TDD Scaffold (COMPLETE / GREEN)
- [x] Create isolated Git worktree at `~/Projects/active/appctl-refactor`. - [x] Create isolated Git worktree at `~/Projects/active/appctl-refactor`.
- [x] Configure Pyright and Nix devShell (`python3.withPackages [ pyyaml types-pyyaml pytest ruff pyright ]`). - [x] Configure Pyright and Nix devShell (`python3.withPackages [ pyyaml types-pyyaml pytest ruff pyright ]`).
- [x] Implement `@dataclass class App`, `SitesApp`, `CoreService`, and `HomepageConfig`. - [x] Implement `@dataclass class SourceConfig(type, url, ref)` with explicit ref semantics.
- [x] Implement `@dataclass class App`, `SitesApp(source: SourceConfig | None)`, `CoreService`, and `HomepageConfig`.
- [x] Implement `load_manifest(manifest_path)` with `ManifestError`. - [x] Implement `load_manifest(manifest_path)` with `ManifestError`.
- [x] Implement pure normalization seam `sites_app_from_manifest(app_dir, manifest, manifest_error)`. - [x] Implement pure normalization seam `sites_app_from_manifest(app_dir, manifest, manifest_error)`.
- [x] Implement dynamic discovery `get_sites_apps(sites_dir)` and `resolve_app(query, apps)`. - [x] Implement dynamic discovery `get_sites_apps(sites_dir)` and `resolve_app(query, apps)`.
@@ -94,26 +97,40 @@ This plan modernizes the engine from a procedural ~900-line script with a hand-r
- Handle Compose directory inspection (`docker compose ps -q` + inspect). - Handle Compose directory inspection (`docker compose ps -q` + inspect).
- Handle Core single container inspection (`docker inspect -f '{{.State.Running}}' <name>`). - Handle Core single container inspection (`docker inspect -f '{{.State.Running}}' <name>`).
- Return standardized status badges (`🟢 Running (N)`, `🟡 Degraded (M/N)`, `🔴 Stopped`, `⚪ Not Stack`, `❓ Unknown`). - Return standardized status badges (`🟢 Running (N)`, `🟡 Degraded (M/N)`, `🔴 Stopped`, `⚪ Not Stack`, `❓ Unknown`).
- [ ] **Git Sync & Diagnostics Engine**: - Extract container image labels: specifically `org.opencontainers.image.revision` for software provenance.
- Implement `get_git_sync_status(dir_path: Path | str) -> str`. - [ ] **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}`. - 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). - Return standardized badges (`✓ Synced`, `⬆ N Ahead`, `⬇ N Behind`, `⚡ N⬆ M⬇`, `⚪ Untracked`, `*` dirty indicator).
- Implement `get_git_diagnostics(dir_path: Path | str) -> dict[str, Any] | None`. - **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**: - [ ] **SSL / TLS Inspection Engine**:
- Define `@dataclass class SSLCertResult`. - Define `@dataclass class SSLCertResult`.
- Implement `check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> 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`. - Implement `check_all_ssl_certs(domains: list[str]) -> dict[str, SSLCertResult]` with `ThreadPoolExecutor`.
- [ ] **Concurrent Remote Fetching**: - [ ] **Concurrent Remote Fetching**:
- Implement `fetch_all_repositories(apps: list[SitesApp], include_core: bool = True)` with worker pool. - 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 ### Deliverable 3: Presentation & CLI Dispatch Layer
- [ ] **`cmd_list` / `cmd_status`**: - [ ] **`cmd_list` / `cmd_status`**:
- Support `--core` / `-c`, `--fetch` / `-f`, `--ssl` / `-s`, and `--all` / `-a` flags. - Support `--core` / `-c`, `--fetch` / `-f`, `--ssl` / `-s`, and `--all` / `-a` flags.
- Polymorphic table formatting for both `SitesApp` and `CoreService`. - 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. - Render manifest warning indicators if `app.manifest_error` is populated.
- [ ] **`cmd_info`**: - [ ] **`cmd_info`**:
- Formatted deep diagnostic view for a single application or Core service. - 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 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`**: - [ ] **`cmd_ssl`**:
- Formatted TLS certificate table for all public domains or deep inspection of a single target. - Formatted TLS certificate table for all public domains or deep inspection of a single target.
- [ ] **`cmd_resolve`**: - [ ] **`cmd_resolve`**:
@@ -128,12 +145,12 @@ This plan modernizes the engine from a procedural ~900-line script with a hand-r
- [ ] Run full automated test suite: `pytest tests/` (100% Green). - [ ] Run full automated test suite: `pytest tests/` (100% Green).
- [ ] Run code linter: `ruff check .` with zero errors. - [ ] Run code linter: `ruff check .` with zero errors.
- [ ] Run type checker: `pyright` with zero errors. - [ ] Run type checker: `pyright` with zero errors.
- [ ] **Topology Synchronization (Roadmap v3 P1 alignment)**: - [ ] **Topology Synchronization (Roadmap v4 P1 alignment)**:
- Update `scripts/appctl_engine_v2.py` `get_core_services()`: - Update `scripts/appctl_engine_v2.py` `get_core_services()`:
* `stalwart`: domain `smtp.${HOMELAB_DOMAIN}`. * `stalwart`: domain `smtp.${HOMELAB_DOMAIN}`.
* Remove `snappymail` (discovered dynamically in `~/Sites/snappymail`). * Remove `snappymail` (discovered dynamically in `~/Sites/snappymail`).
* Remove deprecated `portainer`. * Remove deprecated `portainer`.
- [ ] **Manifest Engine Convergence (Roadmap v3 P3 alignment)**: - [ ] **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`. - 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()`. - 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. - Update unit test fixtures in `tests/unit/test_appctl_engine_v2.py` to validate against schema v1.0 models.
@@ -1,6 +1,7 @@
--- ---
type: plan type: plan
status: active status: superseded
superseded_by: architecture-consolidation-implementation-guide-v4.md
project: homelab project: homelab
tags: tags:
- architecture - architecture
@@ -14,7 +15,10 @@ tags:
# Homelab Core — Architecture Consolidation & Hardening Implementation Guide v3 # Homelab Core — Architecture Consolidation & Hardening Implementation Guide v3
> **Companion Architecture Roadmap**: [`architecture-consolidation-roadmap-v3.md`](architecture-consolidation-roadmap-v3.md) > [!WARNING]
> **SUPERSEDED**: This execution guide has been superseded by [**Homelab Core — Architecture Consolidation & Hardening Implementation Guide v4**](architecture-consolidation-implementation-guide-v4.md).
>
> **Companion Architecture Roadmap**: [`architecture-consolidation-roadmap-v4.md`](architecture-consolidation-roadmap-v4.md)
> >
> **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`) > **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`)
> >
@@ -0,0 +1,312 @@
---
type: plan
status: active
project: homelab
tags:
- architecture
- security
- operations
- homelab
- gitops
- implementation
- migration
- provenance
---
# Homelab Core — Architecture Consolidation & Hardening Implementation Guide v4
> **Companion Architecture Roadmap**: [`architecture-consolidation-roadmap-v4.md`](architecture-consolidation-roadmap-v4.md)
>
> **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`)
>
> **Execution Philosophy**: Local-first investigation, zero unverified state mutations, reversible staged migrations, atomic commit proposals.
---
## 1. Implementation Status & Execution Progress
| Phase / Workstream | Status | Target Scope / Key Deliverables | Verification Gates |
| :--- | :--- | :--- | :--- |
| **P0: Architecture Re-Baseline** | **📐 DRAFTED** | 3-Tier taxonomy, source vs image-only workload classes, controller authority matrix, resource ownership matrix, dependency graphs. | Documentation reviews, structural linting. |
| **P1: Mail Topology Realignment** | **🎯 UP NEXT** | Move Stalwart to `smtp.roadtotech.me`; move SnappyMail to `~/Sites/snappymail` (`mail.roadtotech.me`) with zero data loss. | Verified rollback archive, state parity proof, IMAP/SMTP auth, address book survival, Diun delivery test. |
| **P2: GitOps Privilege & Authority** | **⏳ PENDING** | Authoritative Core repository registry, decoupled CI vs deploy webhook routing, Brain pull-only policy, workload Compose security policy, systemd sandboxing. | Flake check, unit tests for admission and containment, path traversal tests, Compose policy validation tests. |
| **P3: Manifest Convergence** | **⏳ PENDING** | Schema v1.0, single typed parser library (`core_manifest.py`), `SourceConfig` domain model & ref semantics, integrate `appctl-v2`. | Manifest validation in CI, schema lint tests, unit tests for `SourceConfig`. |
| **P4: Platform Lifecycle & Health** | **⏳ PENDING** | Service readiness probes in Core Compose, `condition: service_healthy` startup gating, image update policy. | Docker health inspects, dependency startup ordering tests. |
| **P5: Deployment Truth & Ledger** | **⏳ PENDING** | Two operational inspection axes with three revision identities (`deployment_config_revision`, `source_revision`, `artifact_digest`), atomic status record, `appctl history`. | Dispatcher status test fixtures, ledger serialization accuracy tests. |
---
## 2. Mandatory Working Rules
### Rule 1 — One Production Transition at a Time (Parallel Refactoring Permitted)
Never combine mail infrastructure relocation, GitOps privilege modifications, and manifest schema refactors into single sweeping production changes. Keep each architectural phase isolated on dedicated git branches.
However, independent internal implementation refactors (specifically `appctl-v2` on branch `refactor/appctl-rework`) **may proceed concurrently in an isolated worktree**, provided they do not trigger production cutovers and strictly preserve the established architectural integration seams.
### Rule 2 — Absolute Preservation of Application State
State-bearing workloads must never be modified using destructive commands (`rm -rf`, `docker compose down -v`, or unverified moves). State directory migrations require an explicit pre-flight freeze, recursive archive with preserved timestamps/permissions, and parallel staging before live cutover.
### Rule 3 — Single Source of Truth
Never duplicate service definitions or trust boundaries across disparate files. Core owns the platform catalog; the authoritative registry owns admission paths; `core_manifest.py` owns workload manifest parsing.
### Rule 4 — The User Controls Production Transitions
Per Homelab Agent Guidelines: The agent investigates, crafts local code changes, and verifies tests locally. The user reviews atomic commit proposals, merges to `main`, and runs production deployments (`nixos-rebuild switch`, container recreation).
### Rule 5 — Immutable Integration Seams Across Tracks
The interfaces connecting Track A (`main`) and Track B (`appctl-v2`) must not undergo uncoordinated drift: CLI syntax, `resolve` JSON contract, canonical service identifiers, and Homepage generation semantics remain stable until Milestone P3 convergence.
### Rule 6 — Minimal Control Path & Orchestrator Restraint (KISS)
The deployment delivery pipeline must remain strictly linear and minimal:
$$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl update} \longrightarrow \text{Compose Up}$$
Do not introduce secondary orchestration systems, message brokers, queues, deployment databases, or rollback controllers around `appctl`. `appctl update` operates strictly as a declarative, standalone deployment reconciliation primitive.
---
## 2.1 Concurrent Track Coordination: Homelab Architecture vs. appctl-v2
Two major engineering tracks are active concurrently:
- **Track A (Production Architecture)**: Based on `main` in `/home/kiskaadee/Homelab/Core`. Owns host configuration, service topology (P1 mail migration), GitOps privilege separation (P2), and platform readiness (P4).
- **Track B (Implementation Modernization)**: Based on `refactor/appctl-rework` in `/home/kiskaadee/Projects/active/appctl-refactor`. Implements typed domain hierarchy (`SitesApp`, `CoreService`, `SourceConfig`), PyYAML ingestion, Docker label inspection, and TDD unit tests.
### Operating Protocol Between Tracks
1. **Seam Isolation (Do Not Cross-Merge Branches Early)**:
Do not continuously merge `main` into `refactor/appctl-rework` or vice versa.
2. **Phase 1 Coordination (Mail Topology)**:
- **On `main`**: Apply the minimal required compatibility patch to legacy `scripts/appctl_engine.py`: change `stalwart` domain to `smtp.roadtotech.me`, remove `snappymail` from `get_core_services()`.
- **On `refactor/appctl-rework`**: Update typed `CoreService` in `scripts/appctl_engine_v2.py` symmetrically. Requires zero branch merging.
3. **Phase 2 Coordination (GitOps Authority)**:
Phase 2 operates on `Core/nixos` systemd units and `Core/scripts/gitops_dispatcher.py`. It has zero dependencies on `appctl` and can execute without touching Track B.
4. **Phase 3 Convergence (The Controlled Integration Seam)**:
Phase 3 is the deliberate join point. `core_manifest.py` originates authoritatively on `main` (validated against `gitops_dispatcher.py`). That atomic commit is cherry-picked into `refactor/appctl-rework`, `appctl-v2` adapts its manifest ingestion to the shared module and verifies its unit tests, and finally `refactor/appctl-rework` merges into `main`.
---
## 3. Phase 0: Architecture Re-Baseline & Structural Catalog
### Deliverable 0.1: Service Taxonomy & 3-Tier Architecture
Update `Core/docs/architecture.md` and repository guidelines to formalize:
1. **Tier 1: Software Layer**: Application source repositories (Gitea/GitHub).
2. **Intermediate Artifacts**: OCI images tagged with `org.opencontainers.image.revision`.
3. **Tier 2: Deployment Layer**: `~/Sites/*` catalog owning `app.yaml` and `docker-compose.yml`.
4. **Tier 3: Platform Layer**: Homelab Core appliance (NixOS, Traefik, Authelia, LLDAP, Stalwart, controllers).
5. **Workload Classification**:
- Class A: Source-Backed (`source:` block present in `app.yaml`).
- Class B: Image-Only (`source:` block omitted).
### Deliverable 0.2: Controller Authority Matrix
Document authoritative control loops across systemd, Docker Compose, GitOps, CI runners, and `appctl` in `Core/docs/architecture.md`.
### Deliverable 0.3: Resource & State Ownership Matrix
Formalize persistent state ownership for every component: owner, filesystem location, desired state source, and runtime state form.
---
## 4. Phase 1: Mail Topology Realignment & Zero-Data-Loss Migration Runbook
### Architectural Context & Invariants
- **Stalwart**: Remains in Core as platform capability. Public endpoint moves to `smtp.roadtotech.me`. Persistent mail store (`Core/config/stalwart/data`) is never moved.
- **SnappyMail**: Moves from `Core/docker-compose.yml` to `~/Sites/snappymail` as an **Image-Only Class B Workload** (`mail.roadtotech.me`). Persistent state (`Core/config/snappymail/data`) is copied to `~/Sites/snappymail/data`.
### Step-by-Step Migration Execution
#### Step 1.1: Pre-Migration Health Audit
Verify existing Stalwart and SnappyMail containers and note running IDs:
```bash
docker ps --filter "name=stalwart" --filter "name=snappymail" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
```
#### Step 1.2: State Freeze
Halt SnappyMail to prevent database mutation during backup:
```bash
docker stop snappymail
```
#### Step 1.3: Verified Pre-Cutover Backup Archive
Create a compressed archive with permissions and timestamps preserved, generate a SHA-256 hash, and verify test extraction:
```bash
mkdir -p ~/backups/pre-mail-cutover-$(date +%F)
tar -czpf ~/backups/pre-mail-cutover-$(date +%F)/snappymail-data.tar.gz -C ~/Homelab/Core/config/snappymail data
sha256sum ~/backups/pre-mail-cutover-$(date +%F)/snappymail-data.tar.gz > ~/backups/pre-mail-cutover-$(date +%F)/snappymail-data.tar.gz.sha256
tar -tzf ~/backups/pre-mail-cutover-$(date +%F)/snappymail-data.tar.gz | head -n 10
```
#### Step 1.4: Workload Scaffolding & State Directory Provisioning
1. Provision isolated persistent state root outside the Git repository:
```bash
mkdir -p ~/var/lib/homelab/snappymail
```
2. Create `~/Sites/snappymail/app.yaml`:
```yaml
schemaVersion: "1.0"
name: "snappymail"
displayName: "SnappyMail"
description: "Lightweight Webmail Client"
category: "Communication"
network:
ingress: true
domain: "mail.roadtotech.me"
publishedPort: 8888
internalOnly: false
deployment:
strategy: compose
preflight:
filesRequired:
- docker-compose.yml
healthcheck:
type: http
path: "/"
expectedStatus: 200
timeoutSeconds: 30
```
3. Create `~/Sites/snappymail/docker-compose.yml` configured to connect to Stalwart via `proxy-net`, mount `~/var/lib/homelab/snappymail:/var/lib/snappymail/_data_`, and expose Traefik labels for `mail.roadtotech.me`.
#### Step 1.5: Non-Destructive State Replication & Parity Proof
Copy state from Core to `~/var/lib/homelab/snappymail/` and verify file count and parity:
```bash
cp -a ~/Homelab/Core/config/snappymail/data/* ~/var/lib/homelab/snappymail/
diff -r ~/Homelab/Core/config/snappymail/data ~/var/lib/homelab/snappymail
```
#### Step 1.6: Stalwart Endpoint Cutover in Core
1. Update `Core/docker-compose.yml`:
- Change Stalwart domain Traefik labels from `mail.roadtotech.me` to `smtp.roadtotech.me`.
- Update `STALWART_PUBLIC_URL=https://smtp.roadtotech.me`.
- Remove SnappyMail service block entirely.
2. Apply Core changes:
```bash
cd ~/Homelab/Core && docker compose up -d stalwart
```
#### Step 1.7: Workload Launch & Live Verification
1. Launch SnappyMail:
```bash
cd ~/Sites/snappymail && docker compose up -d
```
2. Verify:
- Public webmail at `https://mail.roadtotech.me` is accessible.
- User logins and address books intact.
- IMAP/SMTP connectivity between SnappyMail and Stalwart functional.
- Diun alert delivery over SMTPS (port 465) functional.
3. Retain Core backup archive for 14 days before storage cleanup.
---
## 5. Phase 2: GitOps Privilege & Authority Hardening
### Deliverable 2.1: Authoritative Core Repository Registry
1. Establish `Core/config/deployments.yaml` as the sole authority for admitted deployment repositories.
2. Manifests in `Sites` **cannot** declare aliases or alter admission paths.
### Deliverable 2.2: The CI-to-Deployment Reconciliation Pipeline
Formalize the authoritative event flow from software build to live runtime:
1. Pushes to Application Source repositories trigger Gitea Actions CI to test and build container images, embedding `org.opencontainers.image.revision`.
2. On successful image publishing, CI emits an authenticated deployment event to GitOps (`POST /webhook/deploy/<app>`).
3. GitOps verifies HMAC admission against Core's registry, acquires `.gitops.lock`, and invokes `appctl update <app>`.
4. `appctl update` reconciles the deployment:
- Pulls Sites deployment descriptors.
- Runs `docker compose pull` to retrieve the newly published image.
- Recreates containers with `docker compose up -d`.
- Runs healthchecks and records the 3-axis truth ledger.
- **Prohibited**: Host never compiles code or clones application source.
### Deliverable 2.3: Second Brain Read-Only Data-Vault Policy
Designate `~/Brain` as a read-only vault with `strategy: pull-only`, isolated from Docker socket access.
### Deliverable 2.4: Workload Compose Security Policy
Implement pre-flight Compose AST validation in `Core/scripts/gitops_dispatcher.py` to reject:
- `privileged: true`
- Direct Docker socket bind mounts (`/var/run/docker.sock`)
- `network_mode: host` or `pid: host`
- Host root mounts outside `~/var/lib/homelab/<app>/`
### Deliverable 2.5: Systemd Service Sandboxing
Update `Core/nixos/modules/gitops.nix` with strict systemd execution constraints (`ProtectSystem=strict`, `NoNewPrivileges=true`, restricted `ReadWritePaths`).
---
## 6. Phase 3: Manifest Contract Convergence & appctl-v2 Integration
### Deliverable 3.1: Manifest Schema v1.0 & Parser Library (`core_manifest.py`)
Implement the single authoritative parser on `main`:
- Strongly-typed parsing using PyYAML and `@dataclass`.
- Implements `SourceConfig(type, url, ref)`:
- Validates `source.type == "git"`.
- Validates `source.url` format and enforces permitted transports (`https://`, `ssh://`, `git@`); rejects `file://` or relative paths.
- Enforces 10-second timeout on remote Git inspections (`git ls-remote`).
- Resolves `source.ref` tracking semantics (Branch vs Tag vs Commit SHA).
- Rejects unknown top-level keys.
### Deliverable 3.2: Workload Catalog Migration
Audit all `~/Sites/*/app.yaml` files:
- Source-backed apps (`doc2site`, `courses`): declare `source: { type: git, url: ..., ref: main }`.
- Image-only apps (`snappymail`, `jellyfin`, `stirling`): omit `source:` block.
### Deliverable 3.3: In-House Application Source Migration Runbook
For workloads where source code was previously co-located with deployment configs (e.g. `doc2site`):
1. Create standalone upstream Git repository on Gitea (e.g., `git.roadtotech.me/kiskaadee/doc2site`).
2. Move application source, `Dockerfile`, and tests to the new repo; remove all Homelab Traefik/network files.
3. Configure Gitea Actions CI workflow:
```yaml
name: Build and Publish Image
on:
push:
branches: [main]
jobs:
build:
runs-on: nixos-act-runner
steps:
- uses: actions/checkout@v4
- name: Build OCI Image
run: |
docker build \
--label "org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}" \
--label "org.opencontainers.image.revision=${{ github.sha }}" \
-t registry.roadtotech.me/kiskaadee/doc2site:latest .
docker push registry.roadtotech.me/kiskaadee/doc2site:latest
```
4. Update `Sites/doc2site/`:
- `app.yaml`: declare `source: { type: git, url: "https://git.roadtotech.me/kiskaadee/doc2site.git", ref: "main" }`.
- `docker-compose.yml`: reference `registry.roadtotech.me/kiskaadee/doc2site:latest`.
### Deliverable 3.4: appctl-v2 Convergence
1. Cherry-pick `core_manifest.py` from `main` into `refactor/appctl-rework`.
2. Connect `appctl_engine_v2.py` to `core_manifest.py`.
3. Verify test suite passes (`pytest`, `ruff`, `pyright`).
4. Promote `appctl_engine_v2.py` to `appctl_engine.py` on `refactor/appctl-rework` and merge into `main`.
---
## 7. Phase 4: Platform Lifecycle & Readiness Contracts
### Deliverable 4.1: Service Healthchecks & Dependency Gating
Add deterministic healthchecks in `Core/docker-compose.yml` and enforce `condition: service_healthy` across dependent chains:
- Traefik depends on socket-proxy healthy.
- Authelia depends on LLDAP healthy.
- Diun depends on Stalwart healthy.
- Dozzle/Homepage depend on Authelia healthy.
---
## 8. Phase 5: Deployment Truth & Historical Ledger
### Deliverable 5.1: Two Operational Inspection Axes & Three Revision Identities in GitOps Dispatcher
Record true deployment facts in `~/.local/state/homelab/gitops/ledger/<app>.json`:
```json
{
"workload": "bitetrack",
"deployment_config_revision": "c8f12a4",
"source_revision": "e4a81b2",
"artifact_digest": "sha256:7b9c45e812a...",
"deployed_at": "2026-09-28T20:25:00Z",
"duration_seconds": 12.4,
"status": "success",
"failure_stage": null
}
```
*Note: `artifact_digest` is extracted directly from the container inspect `RepoDigests` field, capturing the immutable OCI registry digest.*
### Deliverable 5.2: `appctl history` Command
Implement CLI inspection of the deployment ledger in `appctl_engine.py`.
@@ -1,6 +1,7 @@
--- ---
type: plan type: plan
status: active status: superseded
superseded_by: architecture-consolidation-roadmap-v4.md
project: homelab project: homelab
tags: tags:
- architecture - architecture
@@ -14,11 +15,14 @@ tags:
# Architecture Consolidation & Hardening Roadmap v3 # Architecture Consolidation & Hardening Roadmap v3
> [!WARNING]
> **SUPERSEDED**: This roadmap has been superseded by [**Architecture Consolidation & Hardening Roadmap v4**](architecture-consolidation-roadmap-v4.md), which establishes the 3-Tier Architecture (Software vs. Deployment vs. Platform), OCI artifact provenance, and dual-axis deployment truth.
>
> **Supersedes**: [Architecture Consolidation & Hardening Roadmap v2](architecture-consolidation-roadmap-v2.md) > **Supersedes**: [Architecture Consolidation & Hardening Roadmap v2](architecture-consolidation-roadmap-v2.md)
> >
> **Current Platform Baseline**: Commit `246b587` (NixOS standalone appliance, consolidated docs, Portainer deprecated, Stalwart mail & SMTPS submission, Dozzle auth, Diun jitter/worker pool, Gitea Actions CI). > **Current Platform Baseline**: Commit `246b587` (NixOS standalone appliance, consolidated docs, Portainer deprecated, Stalwart mail & SMTPS submission, Dozzle auth, Diun jitter/worker pool, Gitea Actions CI).
> >
> 📋 **Companion Execution Guide**: [`architecture-consolidation-implementation-guide-v3.md`](architecture-consolidation-implementation-guide-v3.md) > 📋 **Companion Execution Guide (Superseded)**: [`architecture-consolidation-implementation-guide-v3.md`](architecture-consolidation-implementation-guide-v3.md)
--- ---
@@ -0,0 +1,443 @@
---
type: plan
status: active
project: homelab
tags:
- architecture
- security
- operations
- homelab
- gitops
- roadmap
- consolidation
- provenance
---
# Architecture Consolidation & Hardening Roadmap v4
> **Supersedes**: [Architecture Consolidation & Hardening Roadmap v3](architecture-consolidation-roadmap-v3.md)
>
> **Current Platform Baseline**: Commit `246b587` (NixOS standalone appliance, consolidated docs, Portainer deprecated, Stalwart mail & SMTPS submission, Dozzle auth, Diun jitter/worker pool, Gitea Actions CI).
>
> 📋 **Companion Execution Guide**: [`architecture-consolidation-implementation-guide-v4.md`](architecture-consolidation-implementation-guide-v4.md)
---
## Executive Summary
Roadmap v3 established a rigorous operational baseline: clarifying controller authority, inverting GitOps trust boundaries, isolating mail capabilities, and establishing parallel seams for the `appctl-v2` modernization.
However, Roadmap v3 still inherited an obsolete assumption from early homelab prototypes: **it treated each workload directory in `~/Sites/<app>` as an individual Git repository cloned directly from Gitea**.
This coupled model created three fundamental architectural liabilities:
1. **Source Repository Pollution**: In-house applications (e.g., `doc2site`, `bitetrack`) carried Homelab-specific Traefik labels, Docker bridge network names, and host path mounts directly inside their application source trees.
2. **Repository Inflation**: Off-the-shelf applications (e.g., `jellyfin`, `stirling`) required their own standalone Git repositories merely to store a 20-line `docker-compose.yml` and a minimal `app.yaml`.
3. **Ambiguous Freshness Semantics**: `appctl`'s Git status inspection was coupled to `Sites/<app>/.git`. It could only report whether local deployment files had uncommitted edits or differed from their origin branch; it could not report whether the running container was built from the latest upstream source code.
**Roadmap v4 decouples software development from deployment configuration and platform orchestration.** It formalizes a clean **3-Tier Architecture**, introduces **declarative source provenance**, defines **two workload deployment classes** (Source-Backed vs. Image-Only), and establishes **two operational inspection axes with three independent revision identities**.
---
## Core Architectural Principles
1. **3-Tier Separation of Concerns**:
- **Software Layer (Application Repositories)**: Owns code, tests, Dockerfiles, and CI workflows. Completely agnostic of Homelab infrastructure.
- **Deployment Layer (Sites Workload Plane)**: Owns deployment declarations (`app.yaml`), Compose definitions (`docker-compose.yml`), Traefik ingress labels, and environment secrets bindings.
- **Platform Layer (Homelab Core & NixOS Appliance)**: Owns host lifecycle, networking, edge security, shared capabilities, and operational engines (`appctl`, GitOps receiver).
2. **Artifact as an Intermediate Provenance Object**: The container image is not an independent architectural tier; it is an intermediate build product / provenance artifact produced by the Software Layer (via CI) and consumed by the Platform Runtime.
3. **Pure Git Provenance Over Forge Coupling**: Manifests declare canonical Git URLs and refs (`source.url`, `source.ref`). Manifests remain forge-agnostic; platform-level forge integrations (API tokens, webhooks) belong strictly to Core.
4. **Explicit Ref Semantics**: Moving branches (e.g. `ref: main`) track upstream development; pinned tags (`ref: v1.4.2`) or commit SHAs declare intentional release locks.
5. **Two Workload Deployment Classes**: Source-backed workloads declare upstream provenance; off-the-shelf workloads declare no `source` block and rely on registry image tags/digests.
6. **Platform Legibility Over Elaboration (Minimal Control Paths & KISS)**: Simplicity is defined by the fewest independent concepts and control paths. Delivery remains strictly linear (`source push -> CI -> GitOps -> appctl update -> Compose`), avoiding secondary orchestration subsystems, message queues, or deployment databases.
7. **Core Registry Authority**: The repository being admitted must never define its own admission trust boundary. Core authoritatively owns admission paths and alias resolution.
8. **Single Manifest Contract**: Exactly one typed schema and parser (`core_manifest.py`) is consumed across `appctl`, `gitops_dispatcher`, and dashboard sync tooling.
9. **Two Operational Inspection Axes with Three Revision Identities**: Operational inspection is evaluated across two orthogonal axes: **Deployment Configuration State** (Sites checkout freshness) and **Software Provenance State** (upstream source vs. deployed container). The system ledger records three distinct, independent identity facts: `deployment_config_revision` (Sites commit SHA), `source_revision` (upstream source commit SHA), and `artifact_digest` (immutable OCI image SHA256 digest).
10. **Zero-Data-Loss Migration**: State-bearing components are relocated across architectural boundaries through staged, reversible migrations with verified pre-flight snapshots and non-destructive cutovers.
---
## Part 1: The 3-Tier Architecture & System Taxonomy
The platform decouples into three clean layers connected by intermediate artifacts:
```mermaid
flowchart TB
subgraph TIER1["1. SOFTWARE LAYER (Upstream Repositories)"]
direction LR
SRC_APP["In-House Application Repos<br/>(kiskaadee/bitetrack, docs2site)<br/>• Owns code, Dockerfile, unit tests<br/>• Agnostic of Homelab"]
SRC_OTS["Upstream Open Source<br/>(Jellyfin, Stalwart, Stirling)<br/>• Third-party releases"]
CI["CI Engine (Gitea Actions / GitHub Actions)<br/>• Injects org.opencontainers.image.revision<br/>• Publishes OCI Images"]
SRC_APP --> CI
end
subgraph ARTIFACTS["INTERMEDIATE PROVENANCE OBJECTS"]
direction LR
OCI["OCI Container Registries<br/>(ghcr.io, Docker Hub, Gitea Registry)<br/>• Immutable Image Digests<br/>• Revision Metadata Labels"]
end
subgraph TIER2["2. DEPLOYMENT LAYER (Sites Workload Plane)"]
direction LR
SITE_CATALOG["Homelab Sites Catalog (~/Sites/*)<br/>• app.yaml (Intent & Source Pointer)<br/>• docker-compose.yml (Ingress, mounts, env)"]
end
subgraph STATE["PERSISTENT STATE ROOT (~/var/lib/homelab/*)"]
direction LR
APP_STATE["Workload Runtime State (~/var/lib/homelab/<app>/)<br/>• SQLite / Postgres databases<br/>• Configuration caches / uploads<br/>• Isolated from Git deployment descriptors"]
end
subgraph TIER3["3. PLATFORM LAYER (Homelab Core Appliance)"]
direction TB
subgraph SEC_EDGE["Edge & Security Primitives"]
direction LR
TR["Traefik v3 (Ingress / TLS)"]
SP["Socket-Proxy (Docker API Guard)"]
AUTH["Authelia v4 (SSO / Forward Proxy)"]
LDAP["LLDAP (Directory)"]
end
subgraph SEC_CAP["Core Capabilities"]
STAL["Stalwart Mail Server (smtp.roadtotech.me)"]
end
subgraph SEC_OPS["Operations & Controllers"]
direction LR
CTL_SYS["NixOS / systemd (Host)"]
CTL_GOP["homelab-gitops (Deployer)"]
CTL_APP["appctl CLI (Reconciliation & Diagnostics)"]
CTL_OBS["Diun / Watchtower / Dozzle"]
end
end
CI --> OCI
SRC_OTS --> OCI
OCI -.->|"Image Pull"| TIER3
SITE_CATALOG -->|"Deployment Intent"| CTL_GOP
SITE_CATALOG -.->|"Metadata & Ingress"| CTL_APP
STATE -.->|"Bind Mount"| TIER3
CTL_APP -.->|"Inspects Labels"| TIER3
```
### The Two Workload Deployment Classes
| Workload Class | Manifest Contract (`app.yaml`) | Upstream Tracking Strategy | Freshness Indicator | Example Workloads |
| :--- | :--- | :--- | :--- | :--- |
| **Class A: Source-Backed** | `source:` block present (`type: git`, `url`, `ref`) | `git ls-remote <url> <ref>` compared against container OCI label `org.opencontainers.image.revision` | Exact match vs. Remote Revision Changed | `bitetrack`, `doc2site`, `courses` |
| **Class B: Image-Only (Off-the-shelf)** | `source:` block omitted | Image tag and SHA256 digest tracked via Docker daemon and Diun/Watchtower | Registry tag update / Digest drift | `jellyfin`, `stirling`, `snappymail`, `mongodb` |
---
## Part 2: Controller Authority Matrix
With decoupled software repositories and deployment descriptors, the controller matrix explicitly defines authority across the entire build, admission, and deployment lifecycle:
| Resource / Lifecycle Stage | Authoritative Controller | Permitted Secondary Actors | Prohibited Actors | Conflict Resolution Policy |
| :--- | :--- | :--- | :--- | :--- |
| **Application Software & Tests** | Developer Git (`main`) | CI Runner (`act_runner`) | GitOps, `appctl` | Software repo is source of truth. Homelab cannot alter source code. |
| **Container Image Building** | CI Engine (Gitea Actions) | Operator manual `docker build` | Runtime GitOps receiver | CI publishes immutable tagged image with OCI revision label. |
| **Host System Configuration** | NixOS (`configuration.nix`) | Manual `nixos-rebuild` by operator | `appctl`, GitOps, containers | Git repository is desired state; local rebuild applies. Direct editing of `/etc` prohibited. |
| **Host Secrets** | SOPS (`secrets.yaml`) | `sops` CLI with host age key | Unprivileged users, CI runners | Secrets decrypted directly to `/run/secrets/` via `sops-nix`. |
| **Core Compose Stack** | Core Git (`main` branch) | Operator via `appctl --core` / `docker compose` | GitOps webhook (auto-deploy disabled for Core) | Core updates require human operator validation. |
| **Workload Deployment Intent** | Sites Git (`main` branch) | Operator via `appctl` | Direct container modification over SSH | Sites repository owns Compose and `app.yaml`. |
| **Workload Runtime Execution** | `homelab-gitops` & `appctl` | Docker daemon (auto-restart) | Watchtower (for pinned workloads) | Per-target filesystem lock (`.gitops.lock`) serializes `appctl` and GitOps. |
| **Workload Persistent State** | Workload Container / System | Backup automation | Git tracking | Runtime state lives in `~/var/lib/homelab/<app>/`; excluded from Sites Git. |
| **Dashboard Catalog** | `appctl sync` / engine | Homepage container (consumes config) | Direct edits to Homepage YAML | Generated deterministically from Core inventory + discovered Sites manifests. |
### Resource & State Ownership Matrix
| Resource | Owner | Location | Desired State Source | Runtime State Form |
| :--- | :--- | :--- | :--- | :--- |
| **Application Source** | Dev / Git | External Git repo | Upstream Git | Git commit graph |
| **Application Artifact** | Registry | OCI Registry / Local Cache | CI build of Source | Docker image with `org.opencontainers.image.revision` |
| **Deployment Compose** | Sites | `Sites/<app>/docker-compose.yml` | Sites Git | Container runtime |
| **Workload Manifest** | Sites | `Sites/<app>/app.yaml` | Sites Git | Parsed by `core_manifest.py` at deployment |
| **Workload Persistent State** | Workload | `~/var/lib/homelab/<app>/` | — (runtime-generated) | Filesystem / persistent storage |
| **Stalwart mail store** | Stalwart | `Core/config/stalwart/data` | — (runtime-generated) | Filesystem |
| **SnappyMail client state**| SnappyMail | `~/var/lib/homelab/snappymail/` | — (runtime-generated) | Workload filesystem |
| **NixOS host config** | Core | `Core/nixos/` | Core Git | Applied via `nixos-rebuild` |
| **SOPS secrets** | Core | `Core/nixos/secrets.yaml` | Core Git (encrypted) | `/run/secrets/` (decrypted) |
---
## Part 3: Mail Architecture Rework & Zero-Data-Loss Relocation
### Topology Separation
Stalwart remains in Core as a platform capability (`smtp.roadtotech.me`); SnappyMail moves to `~/Sites/snappymail` as an **Image-Only Class B Workload** (`mail.roadtotech.me`).
```text
HOMELAB CORE
│
┌───────▼────────┐
│ Stalwart │
│ Mail Platform │
│ smtp.roadtotech.me
└───────┬────────┘
│
┌────────────────┴────────────────┐
│ (SMTP 465 / SMTPS) │ (IMAP 993 / TLS)
▼ ▼
HOMELAB CORE SITES WORKLOAD
┌─────────────────┐ ┌─────────────────┐
│ Diun │ │ SnappyMail │
│ Platform Alerts │ │ Webmail Client │
│ │ │ mail.roadtotech.me
└─────────────────┘ └─────────────────┘
```
Persistent mailbox data (`Core/config/stalwart/data`) remains in Core. SnappyMail user settings (`/var/lib/snappymail/_data_`) migrate to `~/var/lib/homelab/snappymail/` under verified pre-flight archive, hash verification, and a 14-day rollback retention window.
---
## Part 4: GitOps Trust Boundary, CI Triggers & Deployment Reconciliation
### The Source-Build $\to$ Deployment Reconciliation Pipeline
Under the decoupled 3-tier model, the platform formalizes an authoritative end-to-end event chain from software commit to running container:
```mermaid
flowchart TD
subgraph CI_FLOW["1. SOFTWARE BUILD LIFECYCLE (Developer & CI)"]
SRC_PUSH["Push to Upstream Source<br/>(e.g., git.roadtotech.me/kiskaadee/bitetrack:main)"]
CI_JOB["Gitea Actions CI (act_runner)<br/>• Run tests & linters<br/>• Build OCI image<br/>• Embed org.opencontainers.image.revision<br/>• Push image to OCI registry"]
SRC_PUSH --> CI_JOB
end
subgraph TRIGGER["2. DEPLOYMENT TRIGGER"]
HOOK["CI Deployment Webhook<br/>(Authenticated POST /webhook/deploy/<app>)"]
CI_JOB -->|"On Image Publish Success"| HOOK
end
subgraph RECONCILE["3. DEPLOYMENT RECONCILIATION (GitOps & appctl)"]
GOP["homelab-gitops Dispatcher<br/>• Verify HMAC & Core registry<br/>• Acquire .gitops.lock<br/>• Delegate execution"]
UPDATE["appctl update <app><br/>• Pull Sites deployment state<br/>• docker compose pull (latest published artifact)<br/>• docker compose up -d (recreate container)<br/>• Verify health readiness<br/>• Record deployment truth ledger"]
HOOK --> GOP --> UPDATE
end
```
### The Invariant Contract for `appctl update`
`appctl update` is authoritatively defined as a **Deployment Reconciliation Operation**:
- **Role**: Reconciles a deployed workload with its declared desired state and the newest available container artifact.
- **Actions Performed**:
1. Pulls the latest deployment configuration from the Sites repository.
2. Executes `docker compose pull` to retrieve the latest published container image.
3. Executes `docker compose up -d` to recreate containers with updated images/configurations.
4. Runs post-deployment health probes.
5. Records the 3-axis deployment truth ledger (`deployment_config_revision`, `source_revision`, `artifact_digest`).
- **Prohibited Behavior**: `appctl update` **never** clones application source code or compiles software on the Homelab appliance host. All source code compilation belongs 100% to CI runners (`act_runner`).
### Trust Boundary Invariants
1. **Inverted Registry Authority**: Workload manifests cannot expand admission trust boundaries or register arbitrary aliases. All routing decisions rely strictly on Core's authoritative registry (`Core/config/deployments.yaml`).
2. **Systemd Sandboxing**: `homelab-gitops.service` runs under dedicated sandboxing (`ProtectSystem=strict`, `NoNewPrivileges=true`, restricted `ReadWritePaths`).
3. **Pre-Deployment Compose Policy**: GitOps validates `docker-compose.yml` against strict security invariants (no privileged mode, no host networking, no Docker socket mounts) before execution.
---
## Part 5: Manifest Contract Convergence (Schema v1.0)
### Manifest Specification
`app.yaml` declares workload metadata, source provenance, and deployment policy:
```yaml
schemaVersion: "1.0"
name: "bitetrack"
displayName: "BiteTrack"
description: "Nutritional tracking and pantry inventory"
category: "Productivity"
# Optional: Present for Source-Backed workloads, omitted for Image-Only
source:
type: git
url: "https://git.roadtotech.me/kiskaadee/bitetrack.git"
ref: "main"
network:
ingress: true
domain: "bitetrack.roadtotech.me"
publishedPort: 8080
internalOnly: false
deployment:
strategy: compose
preflight:
filesRequired:
- docker-compose.yml
healthcheck:
type: http
path: "/api/health"
expectedStatus: 200
timeoutSeconds: 30
```
### Explicit `source.ref` Tracking Semantics
| `source.ref` Pattern | Semantic Meaning | `appctl` Remote Inspection Behavior |
| :--- | :--- | :--- |
| **Branch** (`main`, `stable`, `refs/heads/*`) | Moving upstream line of development | Queries remote ref SHA on `--fetch` via `git ls-remote`. Compares with deployed container's revision label. |
| **Tag** (`v1.4.2`, `refs/tags/*`) | Pinned release tag | Treated as a pinned version. Deployed container revision must match the tag's commit SHA; moving branch HEADs are ignored. |
| **Commit SHA** (40-char hex string) | Immutable commit pin | Static pin. No remote network checks needed. |
### Transport Security & Remote Timeout Invariants
To prevent protocol injection, SSRF, or denial of service during inspection:
1. **Permitted Git Transport Schemes**: `source.url` must strictly match one of:
- `https://` (e.g. `https://git.roadtotech.me/user/repo.git`)
- `ssh://` (e.g. `ssh://git@git.roadtotech.me:2223/user/repo.git`)
- `git@` (SCP syntax, e.g. `git@git.roadtotech.me:user/repo.git`)
2. **Prohibited Schemes**: `file://`, `ext::`, custom helper schemes, or relative filesystem paths are rejected with `ManifestError`.
3. **Execution Timeout**: Any network call invoking `git ls-remote` must be wrapped in a strict timeout (maximum 10 seconds). Failure to reach remote upstream degrades gracefully to an error badge without hanging the CLI.
---
## Part 6: Two Operational Inspection Axes & Source Provenance
### The Inspection Contract in `appctl`
`appctl` separates local deployment configuration checks from upstream software provenance checks:
```text
Axis 1: Deployment Configuration State (Local Sites Repository)
git status --porcelain & git rev-list HEAD...@{u}
--> ✓ Synced | ⬆ Ahead | ⬇ Behind | * Dirty
Axis 2: Software Provenance State (Upstream Source vs. Runtime Container)
If source is omitted:
--> ⚪ Image Only (displays image tag)
If source is declared:
Deployed Revision SHA (from container label org.opencontainers.image.revision)
Remote Ref SHA (from git ls-remote <source.url> refs/heads/<source.ref>, gated behind --fetch)
Comparison:
• Remote SHA == Deployed SHA --> ✓ Up to date (<sha>)
• Remote SHA != Deployed SHA --> ⚡ Revision Changed (deployed: <d_sha>, remote: <r_sha>)
• Without --fetch --> 🏷 Deployed: <d_sha> (cached runtime state)
```
> [!IMPORTANT]
> **Performance Invariant**: `git ls-remote` is **never** executed during default `appctl list`. It is strictly gated behind `appctl list --fetch` / `-f` or `appctl info <app>`.
---
## Part 7: Parallel Track Coordination (Architecture vs. appctl-v2)
Track A (Architecture Consolidation on `main`) and Track B (`appctl-v2` in worktree `~/Projects/active/appctl-refactor` on `refactor/appctl-rework`) coordinate via five stable integration seams:
```text
┌─────────────────────────┐
│ appctl-v2 refactor │
│ (refactor/appctl-rework)│
│ Models SourceConfig & │
│ Provenance Engine │
└────────────┬────────────┘
│
│ integration point
▼
┌─────────────────────────┐
│ Manifest / domain model │
│ + Core inventory model │
└─────────────────────────┘
main
│
├── P1: Mail topology migration
│ └── minimal compatibility patch to legacy appctl
│
├── P2: GitOps authority hardening
│ └── does not require appctl-v2
│
└── P3: Manifest convergence
└── integrate appctl-v2 here (CONVERGENCE POINT)
```
### The 5 Stable Seams
1. **CLI Invocation Syntax**: Preserved identically.
2. **`resolve` JSON Contract**: `cmd_resolve` output schema unchanged.
3. **Canonical Identity**: Workload identifiers remain stable.
4. **Taxonomy**: Strict classification between Core platform capabilities and Sites workloads.
5. **Homepage Sync Semantics**: Compiles `services.yaml` from Core inventory + discovered Sites manifests without schema breaks.
---
## Part 8: Roadmap Execution Phases
```text
┌─────────────────────────────────────────────────────────────┐
┌ P0: Architecture Re-Baseline & 3-Tier Separation │
│ - Formalize 3-Tier Taxonomy & Ownership Matrices │
│ - Define Source-Backed vs Image-Only Workload Classes │
│ - Establish Provenance Contract & OCI Label Standard │
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────┐
│ P1: Mail Topology Realignment & Zero-Data-Loss Migration │
│ - Stalwart to smtp.roadtotech.me (Core Platform) │
│ - SnappyMail State Backup & Transfer to ~/Sites │
│ - SnappyMail as Image-Only Class B Workload │
│ - Minimal compatibility patch to legacy appctl_engine │
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────┐
│ P2: GitOps Privilege & Authority Hardening │
│ - Authoritative Repository Registry (Core-owned) │
│ - Decoupled CI Build Webhooks vs GitOps Deploy Webhooks │
│ - Second Brain Read-Only Data-Vault Policy │
│ - Workload Compose Security Policy Enforcement │
│ - Systemd Service Confinement & Sandboxing │
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────┐
│ P3: Manifest Contract Convergence & appctl-v2 Integration │
│ - Schema v1.0 & Single Typed Parser (core_manifest.py) │
│ - SourceConfig Domain Model & Manifest Validation │
│ - CONVERGENCE: appctl-v2 replaces legacy engine on main │
│ - Core Service Inventory Normalization │
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────┐
│ P4: Platform Lifecycle & Readiness Contracts │
│ - Service Healthchecks & condition: service_healthy │
│ - Diun / Stalwart / LLDAP Startup Serialization │
│ - Watchtower / Image Update Governance │
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────┐
│ P5: Deployment Truth & Historical Ledger │
│ - Two Inspection Axes & Three Revision Identities: │
│ * deployment_config_revision (Sites Git commit) │
│ * source_revision (org.opencontainers.image.revision) │
│ * artifact_digest (immutable OCI RepoDigest sha256) │
│ - Atomic Status Ledger (duration, phase, failure cause) │
│ - appctl deployment status & history views │
└─────────────────────────────────────────────────────────────┘
```
> [!NOTE]
> **Authoritative Definition of `artifact_digest`**:
> `artifact_digest` is defined as the immutable OCI registry digest (`sha256:...`) of the exact image manifest from which the running container was created. In Docker inspect, it corresponds to the container image's `RepoDigests` entry, distinctly separating it from local daemon image IDs or mutable release tags.
---
## Part 9: Definition of Done
1. **3-Tier Separation & Clean State Isolation**:
- In-house software projects maintain independent Git repositories free of Homelab infrastructure configuration.
- `~/Sites` maintains clean deployment descriptors referencing software sources or off-the-shelf container images.
- Mutable application runtime state resides strictly under `~/var/lib/homelab/<app>/`, isolated from version-controlled Git deployment trees.
2. **Mail Separation**:
- `smtp.roadtotech.me` serves Stalwart administration, JMAP, and protocol routing.
- `mail.roadtotech.me` serves SnappyMail from `~/Sites/snappymail`.
- 100% of user settings, contacts, and sessions survive cutover with zero data loss.
3. **Trust & Admission**:
- Webhook admission decisions rely exclusively on Core's authoritative registry.
- Workload Compose definitions are validated against security invariants before execution.
- `homelab-gitops` runs under restricted systemd sandboxing.
- `appctl update` operates strictly as a deployment reconciliation primitive, never compiling source code on the appliance host.
4. **Contract Unification & Provenance**:
- `core_manifest.py` authoritatively parses and validates Schema v1.0 manifests across `appctl`, GitOps, and tests, enforcing permitted transport schemes (`https://`, `ssh://`, `git@`).
- `appctl-v2` cleanly resolves local deployment status and remote upstream source provenance without breaking CLI caller contracts.
5. **Operational Verification**:
- All architecture invariant tests pass, plus new tests enforcing provenance validation and Compose security invariants.
- Pure Nix `flake check` and Gitea Actions CI pass with zero warnings.