Compare commits
132
Commits
01396bdcce
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7be3df3be5 | ||
|
|
4a9ed7118f | ||
|
|
6258579fd6 | ||
|
|
67732d30c0 | ||
|
|
e134d292fd | ||
|
|
1148cc19c8 | ||
|
|
4006ee557a | ||
|
|
36b5eaa798 | ||
|
|
6d7e1bd69f | ||
|
|
6bb157b251 | ||
|
|
7489c1f448 | ||
|
|
9f623c8147 | ||
|
|
bc3817b332 | ||
|
|
f29712544b | ||
|
|
174a1cb993 | ||
|
|
1b6d64077a | ||
|
|
6933c21e9f | ||
|
|
b8bd12cd2b | ||
|
|
b885fcf056 | ||
|
|
d5b03ebf1a | ||
|
|
563d4abd41 | ||
|
|
f7d0e0c2d8 | ||
|
|
c87ecc7931 | ||
|
|
0cfe57e7d3 | ||
|
|
d812d46d2c | ||
|
|
b14bd02b16 | ||
|
|
bc33df485b | ||
|
|
adfb2a173f | ||
|
|
5077a55b63 | ||
|
|
acaa3740f5 | ||
|
|
dc47898a9b | ||
|
|
f0f4c31811 | ||
|
|
2f71cd23e8 | ||
|
|
dde63d6e13 | ||
|
|
e9c461d6fc | ||
|
|
3cde2c4c8d | ||
|
|
778604d6dc | ||
|
|
0f81bfd08e | ||
|
|
9ce5542592 | ||
|
|
213d588471 | ||
|
|
364601af3d | ||
|
|
32ff96fa41 | ||
|
|
0acfd3d983 | ||
|
|
714dc76eb7 | ||
|
|
2a73cd2bd2 | ||
|
|
65fb89f8a0 | ||
|
|
4b97bb8626 | ||
|
|
441fd8d504 | ||
|
|
3680112069 | ||
|
|
19a55b71b0 | ||
|
|
03579ec914 | ||
|
|
d7d97dde97 | ||
|
|
6db3cc9b54 | ||
|
|
454e3fc888 | ||
|
|
1340351ca5 | ||
|
|
075eec361d | ||
|
|
a6541f8fca | ||
|
|
62c0614dff | ||
|
|
af78759a6e | ||
|
|
6c16c2d907 | ||
|
|
86d7590292 | ||
|
|
07fbcef764 | ||
|
|
78b973f7b5 | ||
|
|
d50fd36c44 | ||
|
|
8cd9460512 | ||
|
|
8d07f68f16 | ||
|
|
a3fba634da | ||
|
|
207074d122 | ||
|
|
dc9a55163d | ||
|
|
1a7205385b | ||
|
|
475353f8d8 | ||
|
|
f32ff46c24 | ||
|
|
8398a02e88 | ||
|
|
444d6149d9 | ||
|
|
2670eafa20 | ||
|
|
14846bab10 | ||
|
|
b93edee9c7 | ||
|
|
85795dfa28 | ||
|
|
b593d95c5d | ||
|
|
8137911b6f | ||
|
|
72c79451f4 | ||
|
|
798c953ac3 | ||
|
|
4e0dfe0c8c | ||
|
|
8a59b093b8 | ||
|
|
4f3c124b25 | ||
|
|
bc73dfadb6 | ||
|
|
74ce2af1ce | ||
|
|
8928e522d7 | ||
|
|
a206a16b8c | ||
|
|
e80a825ee7 | ||
|
|
d1508dda0b | ||
|
|
d699ac9b5b | ||
|
|
80deb7f526 | ||
|
|
fc62b64783 | ||
|
|
c7780b3117 | ||
|
|
70188228a0 | ||
|
|
fd4bdb1c80 | ||
|
|
adfb6297c1 | ||
|
|
ad4d0435ce | ||
|
|
b3ca28b8ef | ||
|
|
a65c29c070 | ||
|
|
7c4380b757 | ||
|
|
00f426b24d | ||
|
|
5037c5578c | ||
|
|
53399a03c6 | ||
|
|
cb1b732c4a | ||
|
|
38867c08e9 | ||
|
|
fea2d9658a | ||
|
|
513e7e1018 | ||
|
|
3238c9c973 | ||
|
|
0837d4f523 | ||
|
|
45037b0a99 | ||
|
|
957192c6c3 | ||
|
|
162f269683 | ||
|
|
56d1ae1a93 | ||
|
|
fee39835d1 | ||
|
|
deb252ddd7 | ||
|
|
30c7b29925 | ||
|
|
d9d68091d3 | ||
|
|
f661831e04 | ||
|
|
3a92368fa2 | ||
|
|
624f55d758 | ||
|
|
48105e41bf | ||
|
|
ef99097c41 | ||
|
|
7492e92ac8 | ||
|
|
2999232781 | ||
|
|
2985836a36 | ||
|
|
4593c77f44 | ||
|
|
4d81c65cac | ||
|
|
ef142d1854 | ||
|
|
c049244069 | ||
|
|
107ef3f3ab |
No files matched your search
+5
-2
@@ -2,6 +2,8 @@
|
|||||||
.obsidian/workspace.json
|
.obsidian/workspace.json
|
||||||
.obsidian/graph.json
|
.obsidian/graph.json
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.trash/
|
||||||
|
*.base
|
||||||
|
|
||||||
# Environments & Python
|
# Environments & Python
|
||||||
.envrc
|
.envrc
|
||||||
@@ -9,9 +11,10 @@
|
|||||||
.venv/
|
.venv/
|
||||||
.local_config.json
|
.local_config.json
|
||||||
.agents/
|
.agents/
|
||||||
|
__pycache__
|
||||||
|
|
||||||
# Uncommitted Capture & Drafts (Staging Area)
|
# Uncommitted Capture & Drafts (Staging Area)
|
||||||
inbox/*
|
00-inbox/*
|
||||||
!inbox/README.md
|
!00-inbox/README.md
|
||||||
|
|
||||||
|
|
||||||
Vendored
+2
-1
@@ -1,3 +1,4 @@
|
|||||||
{
|
{
|
||||||
"alwaysUpdateLinks": true
|
"alwaysUpdateLinks": true,
|
||||||
|
"promptDelete": false
|
||||||
}
|
}
|
||||||
Vendored
+2
-1
@@ -1,3 +1,4 @@
|
|||||||
{
|
{
|
||||||
"cssTheme": "GitHub Theme"
|
"cssTheme": "GitHub Theme",
|
||||||
|
"nativeMenus": true
|
||||||
}
|
}
|
||||||
File renamed without changes.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,915 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: completed
|
||||||
|
project: bdinvite
|
||||||
|
tags:
|
||||||
|
- bdinvite
|
||||||
|
- react
|
||||||
|
- fastapi
|
||||||
|
- traefik
|
||||||
|
- deployment
|
||||||
|
- birthday
|
||||||
|
---
|
||||||
|
|
||||||
|
# Birthday Invitation App — Implementation Plan
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Build a complete interactive birthday invitation application (`bdinvite`) with:
|
||||||
|
|
||||||
|
- **Guest experience**: A visually rich, mobile-first invitation with animated golden bokeh particles, RSVP form, countdown timer, and map preview — served publicly at `demos.roadtotech.me/birthday/invite`
|
||||||
|
- **Admin dashboard**: A simple RSVP management and invitation configuration editor, protected by Authelia — served at `demos.roadtotech.me/birthday/admin`
|
||||||
|
- **Backend**: Lightweight FastAPI service with SQLite (WAL mode), Pydantic validation, and a clean API contract
|
||||||
|
|
||||||
|
Working directory: `Sites/bdinvite` (forge: [bdinvite](https://gitea.roadtotech.me/kiskaadee/bdinvite))
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## User Review Required
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **New infrastructure**: `demos.roadtotech.me` does not currently exist in the homelab. This plan creates Traefik routing for it via docker-compose labels. The wildcard DNS (`*.roadtotech.me`) and TLS certificate already cover it — no Core/NixOS changes needed.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **Authelia split routing**: The admin path (`/birthday/admin/*`) will be Authelia-protected via a higher-priority Traefik router. The public path (`/birthday/*`) will be unprotected. Both route to the same container. This is a pattern not yet used in the homelab (all current apps use full-domain Authelia protection or none), so deployment verification is critical.
|
||||||
|
|
||||||
|
> [!WARNING]
|
||||||
|
> **Static map preview**: The plan uses a static map tile image URL stored in configuration (`map_preview_url`). You'll need to generate or source this image for the actual venue. During development, a placeholder will be used.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resolved Decisions (from grill-me)
|
||||||
|
|
||||||
|
| Decision | Choice |
|
||||||
|
|---|---|
|
||||||
|
| Frontend framework | React + Vite + TypeScript |
|
||||||
|
| Styling | CSS Modules |
|
||||||
|
| Particle rendering | Canvas 2D |
|
||||||
|
| Typography | Google Fonts (Great Vibes / Alex Brush + Montserrat) |
|
||||||
|
| Container architecture | Single container (multi-stage: Node build → Python runtime) |
|
||||||
|
| Database | SQLite with WAL mode, volume-mounted |
|
||||||
|
| Authentication | Authelia-only (ForwardAuth at Traefik level) |
|
||||||
|
| Routing | Path-based on `demos.roadtotech.me/birthday/*` |
|
||||||
|
| Traefik split | Two routers: public (no auth) + admin (Authelia) |
|
||||||
|
| SPA routing | React Router v6 with `basename=/birthday` |
|
||||||
|
| CTA transition | Smooth scroll + fade |
|
||||||
|
| Countdown format | `DD : HH : MM : SS` with state transitions |
|
||||||
|
| Map preview | Static tile image in circular treatment, linking to `mapUrl` |
|
||||||
|
| Duplicate detection | Normalized phone number uniqueness |
|
||||||
|
| Phone validation | Colombian format (10 digits, starts with 3, optional +57) |
|
||||||
|
| Guest +1 | Not supported in v1 |
|
||||||
|
| Config management | Server-managed (DB-stored, admin-editable, API-served) |
|
||||||
|
| Admin edit scope | Flat form with text preview; visual design is code-only |
|
||||||
|
| CSV export | Included in v1 |
|
||||||
|
| Working directory | `Sites/bdinvite` (canonical) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Proposed Changes
|
||||||
|
|
||||||
|
### P0 — Project Scaffolding & Infrastructure
|
||||||
|
|
||||||
|
#### [NEW] `app.yaml`
|
||||||
|
|
||||||
|
The `appctl` manifest for service identity and deployment:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
name: "bdinvite"
|
||||||
|
aliases:
|
||||||
|
- "birthday"
|
||||||
|
- "invite"
|
||||||
|
domain: "demos.roadtotech.me"
|
||||||
|
description: "Interactive Digital Birthday Invitation with RSVP"
|
||||||
|
visible: true
|
||||||
|
auth: false # Public route exists; Authelia applied selectively via labels
|
||||||
|
networks:
|
||||||
|
- proxy-net
|
||||||
|
env:
|
||||||
|
BASE_PATH: "/birthday"
|
||||||
|
homepage:
|
||||||
|
title: "Birthday Invite"
|
||||||
|
group: "Applications"
|
||||||
|
icon: "party.png"
|
||||||
|
container: "bdinvite"
|
||||||
|
weight: 30
|
||||||
|
```
|
||||||
|
|
||||||
|
#### [NEW] `docker-compose.yml`
|
||||||
|
|
||||||
|
Single-container deployment with split Traefik routing:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
bdinvite:
|
||||||
|
build: .
|
||||||
|
container_name: bdinvite
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./data:/app/data
|
||||||
|
environment:
|
||||||
|
- BASE_PATH=/birthday
|
||||||
|
networks:
|
||||||
|
- proxy-net
|
||||||
|
labels:
|
||||||
|
- "diun.enable=false"
|
||||||
|
- "traefik.enable=true"
|
||||||
|
|
||||||
|
# ── Public router (invitation + API) ──
|
||||||
|
- "traefik.http.routers.bdinvite-public.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
|
||||||
|
- "traefik.http.routers.bdinvite-public.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.bdinvite-public.tls=true"
|
||||||
|
- "traefik.http.routers.bdinvite-public.priority=10"
|
||||||
|
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
|
||||||
|
|
||||||
|
# ── Admin router (Authelia-protected) ──
|
||||||
|
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday/admin`)"
|
||||||
|
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.bdinvite-admin.tls=true"
|
||||||
|
- "traefik.http.routers.bdinvite-admin.priority=20"
|
||||||
|
- "traefik.http.routers.bdinvite-admin.middlewares=authelia-auth@docker"
|
||||||
|
- "traefik.http.routers.bdinvite-admin.service=bdinvite-svc"
|
||||||
|
|
||||||
|
# ── HTTP → HTTPS redirect ──
|
||||||
|
- "traefik.http.routers.bdinvite-red.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
|
||||||
|
- "traefik.http.routers.bdinvite-red.entrypoints=web"
|
||||||
|
- "traefik.http.routers.bdinvite-red.middlewares=https-redirect@docker"
|
||||||
|
|
||||||
|
# ── Service target ──
|
||||||
|
- "traefik.http.services.bdinvite-svc.loadbalancer.server.port=8000"
|
||||||
|
|
||||||
|
networks:
|
||||||
|
proxy-net:
|
||||||
|
external: true
|
||||||
|
```
|
||||||
|
|
||||||
|
#### [NEW] `Dockerfile`
|
||||||
|
|
||||||
|
Multi-stage build: Node (build React) → Python (serve with FastAPI):
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
# ── Stage 1: Build React frontend ──
|
||||||
|
FROM node:20-alpine AS frontend-build
|
||||||
|
WORKDIR /build
|
||||||
|
COPY frontend/package.json frontend/package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY frontend/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# ── Stage 2: Python runtime ──
|
||||||
|
FROM ghcr.io/astral-sh/uv:python3.11-bookworm-slim
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV UV_COMPILE_BYTECODE=1
|
||||||
|
|
||||||
|
COPY backend/pyproject.toml backend/uv.lock* ./
|
||||||
|
RUN uv sync --frozen --no-install-project --no-dev
|
||||||
|
|
||||||
|
COPY backend/ .
|
||||||
|
COPY --from=frontend-build /build/dist ./static
|
||||||
|
|
||||||
|
CMD ["uv", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### [NEW] `.gitignore`
|
||||||
|
|
||||||
|
```gitignore
|
||||||
|
# Dependencies
|
||||||
|
frontend/node_modules/
|
||||||
|
backend/__pycache__/
|
||||||
|
backend/*.pyc
|
||||||
|
|
||||||
|
# Build output
|
||||||
|
frontend/dist/
|
||||||
|
|
||||||
|
# Data
|
||||||
|
data/
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
.env
|
||||||
|
*.env.local
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P1 — Backend (FastAPI + SQLite)
|
||||||
|
|
||||||
|
Directory: `backend/`
|
||||||
|
|
||||||
|
```text
|
||||||
|
backend/
|
||||||
|
├── pyproject.toml
|
||||||
|
├── app/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── main.py # FastAPI app, lifespan, static mount
|
||||||
|
│ ├── config.py # Pydantic Settings
|
||||||
|
│ ├── database.py # SQLite engine, session, Base
|
||||||
|
│ ├── models.py # SQLAlchemy models (RSVP, InvitationConfig)
|
||||||
|
│ ├── schemas.py # Pydantic request/response schemas
|
||||||
|
│ ├── routes/
|
||||||
|
│ │ ├── __init__.py
|
||||||
|
│ │ ├── rsvp.py # POST /api/rsvp
|
||||||
|
│ │ ├── config.py # GET /api/config, PUT /api/config
|
||||||
|
│ │ └── admin.py # GET /api/admin/rsvps, GET /api/admin/export
|
||||||
|
│ └── services/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── rsvp.py # RSVP business logic + phone normalization
|
||||||
|
│ └── config.py # Config CRUD + seed defaults
|
||||||
|
```
|
||||||
|
|
||||||
|
#### [NEW] `backend/pyproject.toml`
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[project]
|
||||||
|
name = "bdinvite"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Birthday Invitation RSVP Backend"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115.0",
|
||||||
|
"uvicorn>=0.30.0",
|
||||||
|
"sqlalchemy>=2.0.0",
|
||||||
|
"pydantic>=2.0.0",
|
||||||
|
"pydantic-settings>=2.0.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependency-groups]
|
||||||
|
dev = [
|
||||||
|
"httpx>=0.27.0",
|
||||||
|
"pytest>=8.0.0",
|
||||||
|
"pytest-asyncio>=0.23.0",
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Database Models
|
||||||
|
|
||||||
|
**RSVP table** (`rsvps`):
|
||||||
|
|
||||||
|
| Column | Type | Constraints |
|
||||||
|
|---|---|---|
|
||||||
|
| `id` | INTEGER | PK, autoincrement |
|
||||||
|
| `name` | TEXT | NOT NULL |
|
||||||
|
| `phone` | TEXT | NOT NULL, UNIQUE (normalized) |
|
||||||
|
| `email` | TEXT | nullable |
|
||||||
|
| `created_at` | DATETIME | NOT NULL, default=utcnow |
|
||||||
|
|
||||||
|
**InvitationConfig table** (`invitation_config`):
|
||||||
|
|
||||||
|
| Column | Type | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `id` | INTEGER | PK (always 1 — singleton row) |
|
||||||
|
| `honoree_name` | TEXT | "Isabelle Snow" |
|
||||||
|
| `event_date` | TEXT | "2026-10-28" |
|
||||||
|
| `event_time` | TEXT | "19:00" |
|
||||||
|
| `event_timezone` | TEXT | "America/Bogota" |
|
||||||
|
| `title` | TEXT | "Birthday Party" |
|
||||||
|
| `invitation_text` | TEXT | "You're invited to the birthday party honoring" |
|
||||||
|
| `address_name` | TEXT | "Fresco Ristorante" |
|
||||||
|
| `address_lines` | TEXT | "514 S Brand Blvd\nGlendale, CA 91204" |
|
||||||
|
| `map_preview_url` | TEXT | Static map tile image URL |
|
||||||
|
| `map_url` | TEXT | Google Maps link |
|
||||||
|
| `rsvp_heading` | TEXT | "¿Nos vemos?" |
|
||||||
|
| `rsvp_cta` | TEXT | "CONFIRMA TU ASISTENCIA" |
|
||||||
|
| `submit_label` | TEXT | "TE VEO AHÍ" |
|
||||||
|
| `msg_success` | TEXT | "¡Perfecto! Tu asistencia ha sido confirmada." |
|
||||||
|
| `msg_duplicate` | TEXT | "Parece que ya tenemos tus datos registrados." |
|
||||||
|
| `msg_error` | TEXT | "No pudimos registrar tu asistencia. Inténtalo nuevamente." |
|
||||||
|
| `updated_at` | DATETIME | |
|
||||||
|
|
||||||
|
#### API Endpoints
|
||||||
|
|
||||||
|
All API routes are mounted under `/birthday/api/`:
|
||||||
|
|
||||||
|
| Method | Path | Auth | Description |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `GET` | `/birthday/api/config` | Public | Serves invitation configuration to guest frontend |
|
||||||
|
| `POST` | `/birthday/api/rsvp` | Public | Submit RSVP (name, phone, email?) |
|
||||||
|
| `GET` | `/birthday/api/admin/rsvps` | Authelia | List all RSVPs (with optional `?search=` query param) |
|
||||||
|
| `GET` | `/birthday/api/admin/export` | Authelia | Download CSV of all RSVPs |
|
||||||
|
| `GET` | `/birthday/api/admin/config` | Authelia | Get full config (same as public, but admin context) |
|
||||||
|
| `PUT` | `/birthday/api/admin/config` | Authelia | Update invitation configuration |
|
||||||
|
|
||||||
|
#### API Response Contract
|
||||||
|
|
||||||
|
**POST `/birthday/api/rsvp`** request:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "Andrés García",
|
||||||
|
"phone": "300 123 4567",
|
||||||
|
"email": "andres@example.com"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Responses** (all use a `result` discriminator):
|
||||||
|
|
||||||
|
```json
|
||||||
|
// 201 Created — Success
|
||||||
|
{ "result": "SUCCESS", "name": "Andrés García" }
|
||||||
|
|
||||||
|
// 409 Conflict — Duplicate
|
||||||
|
{ "result": "DUPLICATE" }
|
||||||
|
|
||||||
|
// 422 Unprocessable — Validation
|
||||||
|
{ "result": "VALIDATION_ERROR", "errors": { "phone": "Formato de teléfono inválido" } }
|
||||||
|
|
||||||
|
// 500 — Server error
|
||||||
|
{ "result": "ERROR" }
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Phone Normalization Logic
|
||||||
|
|
||||||
|
```python
|
||||||
|
import re
|
||||||
|
|
||||||
|
def normalize_phone(raw: str) -> str:
|
||||||
|
"""
|
||||||
|
Normalize Colombian phone numbers.
|
||||||
|
Strips +57 prefix, spaces, dashes, parentheses.
|
||||||
|
Returns 10-digit number starting with 3.
|
||||||
|
"""
|
||||||
|
digits = re.sub(r'[^\d]', '', raw)
|
||||||
|
if digits.startswith('57') and len(digits) == 12:
|
||||||
|
digits = digits[2:]
|
||||||
|
if len(digits) != 10 or not digits.startswith('3'):
|
||||||
|
raise ValueError("Formato de teléfono inválido")
|
||||||
|
return digits
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Admin Auth Guard
|
||||||
|
|
||||||
|
Admin endpoints validate the `Remote-User` header (injected by Authelia ForwardAuth):
|
||||||
|
|
||||||
|
```python
|
||||||
|
from fastapi import Header, HTTPException
|
||||||
|
|
||||||
|
def require_admin(remote_user: str | None = Header(None, alias="Remote-User")):
|
||||||
|
if not remote_user:
|
||||||
|
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||||
|
return remote_user
|
||||||
|
```
|
||||||
|
|
||||||
|
#### SPA Catch-All
|
||||||
|
|
||||||
|
FastAPI mounts the built React app as static files and provides a catch-all for client-side routing:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
# API routes first (registered before catch-all)
|
||||||
|
app.include_router(rsvp_router, prefix="/birthday/api")
|
||||||
|
app.include_router(admin_router, prefix="/birthday/api/admin")
|
||||||
|
app.include_router(config_router, prefix="/birthday/api")
|
||||||
|
|
||||||
|
# Static assets (JS, CSS, images)
|
||||||
|
app.mount("/birthday/assets", StaticFiles(directory="static/assets"), name="assets")
|
||||||
|
|
||||||
|
# SPA catch-all: any /birthday/* path serves index.html
|
||||||
|
@app.get("/birthday/{full_path:path}")
|
||||||
|
async def spa_catch_all(full_path: str):
|
||||||
|
return FileResponse("static/index.html")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P2 — Frontend: Guest Invitation (React + Vite + TypeScript)
|
||||||
|
|
||||||
|
Directory: `frontend/`
|
||||||
|
|
||||||
|
```text
|
||||||
|
frontend/
|
||||||
|
├── package.json
|
||||||
|
├── vite.config.ts
|
||||||
|
├── tsconfig.json
|
||||||
|
├── index.html
|
||||||
|
├── public/
|
||||||
|
│ └── (static assets)
|
||||||
|
├── src/
|
||||||
|
│ ├── main.tsx
|
||||||
|
│ ├── App.tsx
|
||||||
|
│ ├── api/
|
||||||
|
│ │ └── client.ts # fetch wrapper for /birthday/api/*
|
||||||
|
│ ├── types/
|
||||||
|
│ │ └── config.ts # InvitationConfig TypeScript interface
|
||||||
|
│ ├── hooks/
|
||||||
|
│ │ ├── useConfig.ts # Fetch & cache invitation config
|
||||||
|
│ │ ├── useCountdown.ts # Live countdown against event datetime
|
||||||
|
│ │ └── useRsvpForm.ts # Form state, validation, submission
|
||||||
|
│ ├── invitation/
|
||||||
|
│ │ ├── Invitation.tsx # Main invitation composition
|
||||||
|
│ │ ├── InvitationContent.tsx # Title, honoree, date/time display
|
||||||
|
│ │ ├── ParticleBackground.tsx # Canvas 2D bokeh particles
|
||||||
|
│ │ ├── RsvpCta.tsx # "CONFIRMA TU ASISTENCIA ↓"
|
||||||
|
│ │ ├── RsvpForm.tsx # Name, phone, email fields + submit
|
||||||
|
│ │ ├── RsvpResult.tsx # Success / Duplicate / Error states
|
||||||
|
│ │ ├── Countdown.tsx # "TE VEO EN DD:HH:MM:SS"
|
||||||
|
│ │ └── MapPreview.tsx # Circular map preview + link
|
||||||
|
│ ├── admin/
|
||||||
|
│ │ ├── AdminLayout.tsx # Dashboard shell (header, nav)
|
||||||
|
│ │ ├── RsvpTable.tsx # RSVP list with search + count
|
||||||
|
│ │ └── ConfigEditor.tsx # Invitation config form + preview
|
||||||
|
│ ├── components/
|
||||||
|
│ │ ├── Button.tsx
|
||||||
|
│ │ ├── Field.tsx
|
||||||
|
│ │ └── Spinner.tsx
|
||||||
|
│ └── styles/
|
||||||
|
│ ├── global.module.css
|
||||||
|
│ ├── invitation.module.css
|
||||||
|
│ ├── particles.module.css
|
||||||
|
│ ├── rsvp.module.css
|
||||||
|
│ ├── result.module.css
|
||||||
|
│ └── admin.module.css
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Vite Configuration
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
base: '/birthday/',
|
||||||
|
build: {
|
||||||
|
outDir: 'dist',
|
||||||
|
assetsDir: 'assets',
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
proxy: {
|
||||||
|
'/birthday/api': 'http://localhost:8000',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
#### React Router Setup
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { BrowserRouter, Routes, Route } from 'react-router-dom';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<BrowserRouter basename="/birthday">
|
||||||
|
<Routes>
|
||||||
|
{/* Guest routes */}
|
||||||
|
<Route path="/invite" element={<Invitation />} />
|
||||||
|
|
||||||
|
{/* Admin routes */}
|
||||||
|
<Route path="/admin" element={<AdminLayout />}>
|
||||||
|
<Route index element={<RsvpTable />} />
|
||||||
|
<Route path="config" element={<ConfigEditor />} />
|
||||||
|
</Route>
|
||||||
|
|
||||||
|
{/* Default redirect */}
|
||||||
|
<Route path="*" element={<Navigate to="/invite" replace />} />
|
||||||
|
</Routes>
|
||||||
|
</BrowserRouter>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P3 — Guest Experience: Visual Design
|
||||||
|
|
||||||
|
#### Color Palette
|
||||||
|
|
||||||
|
| Role | Value | Usage |
|
||||||
|
|---|---|---|
|
||||||
|
| Background | `#0a0a0a` | Page/invitation base |
|
||||||
|
| Gold primary | `#d4a843` | Particle glow, accents |
|
||||||
|
| Gold light | `#f0d68a` | Particle highlights, CTA hover |
|
||||||
|
| Gold dark | `#8b7332` | Subtle text accents |
|
||||||
|
| Text primary | `#ffffff` | Headings, body |
|
||||||
|
| Text secondary | `rgba(255,255,255,0.7)` | Metadata, labels |
|
||||||
|
| Error | `#e74c3c` | Validation errors |
|
||||||
|
| Success | `#d4a843` | Confirmation accent |
|
||||||
|
|
||||||
|
#### Typography
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* Script/display — "Birthday Party", honoree name */
|
||||||
|
@import url('https://fonts.googleapis.com/css2?family=Great+Vibes&display=swap');
|
||||||
|
|
||||||
|
/* Geometric sans-serif — metadata, labels, buttons */
|
||||||
|
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&display=swap');
|
||||||
|
```
|
||||||
|
|
||||||
|
| Element | Font | Weight | Size (mobile) | Tracking |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Title ("Birthday Party") | Great Vibes | 400 | ~3rem | normal |
|
||||||
|
| Invitation text | Montserrat | 300 | 0.85rem | 0.2em |
|
||||||
|
| Honoree name | Great Vibes | 400 | ~2.5rem | normal |
|
||||||
|
| Date/time | Montserrat | 500 | 1.2rem | 0.15em |
|
||||||
|
| CTA | Montserrat | 400 | 0.8rem | 0.25em |
|
||||||
|
| Form labels | Montserrat | 300 | 0.75rem | 0.15em |
|
||||||
|
| Result heading | Montserrat | 600 | 1.5rem | 0.1em |
|
||||||
|
| Countdown digits | Montserrat | 300 | 1.8rem | 0.05em |
|
||||||
|
|
||||||
|
#### Invitation Layout (Mobile-First)
|
||||||
|
|
||||||
|
```css
|
||||||
|
.invitation {
|
||||||
|
width: min(100%, 480px);
|
||||||
|
min-height: 100vh;
|
||||||
|
margin: 0 auto;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The invitation is a single scrollable composition:
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌─────────────────────────────┐
|
||||||
|
│ │
|
||||||
|
│ [ParticleBackground] │ ← Canvas, position: fixed, z-index: 0
|
||||||
|
│ │
|
||||||
|
│ ┌─────────────────────────┐ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Birthday Party │ │ ← Great Vibes, ~3rem
|
||||||
|
│ │ │ │
|
||||||
|
│ │ YOU'RE INVITED TO │ │ ← Montserrat 300, tracked
|
||||||
|
│ │ THE BIRTHDAY PARTY │ │
|
||||||
|
│ │ HONORING │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Isabelle Snow │ │ ← Great Vibes, ~2.5rem
|
||||||
|
│ │ │ │
|
||||||
|
│ │ FRIDAY | OCT 28 | 7PM │ │ ← Montserrat 500, tracked
|
||||||
|
│ │ │ │
|
||||||
|
│ │ CONFIRMA TU ASISTENCIA │ │ ← CTA (interactive)
|
||||||
|
│ │ ↓ │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ └─────────────────────────┘ │
|
||||||
|
│ │
|
||||||
|
│ ┌─────────────────────────┐ │ ← scroll target
|
||||||
|
│ │ │ │
|
||||||
|
│ │ ¿NOS VEMOS? │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ [name field] │ │
|
||||||
|
│ │ [phone field] │ │
|
||||||
|
│ │ [email field] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ TE VEO AHÍ │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ └─────────────────────────┘ │
|
||||||
|
│ │
|
||||||
|
│ ┌─────────────────────────┐ │ ← replaces form on submit
|
||||||
|
│ │ │ │
|
||||||
|
│ │ ¡PERFECTO! │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Tu asistencia ha sido │ │
|
||||||
|
│ │ confirmada. │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Gracias, Andrés. │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ · │ │
|
||||||
|
│ │ · │ │
|
||||||
|
│ │ TE VEO EN │ │
|
||||||
|
│ │ 12 : 04 : 37 : 22 │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ · │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ ╭──────╮ │ │ ← circular map preview
|
||||||
|
│ │ ╭─┤ ├─╮ │ │ ~140px, clip-path: circle()
|
||||||
|
│ │ │ │ MAP │ │ │ │
|
||||||
|
│ │ ╰─┤ ├─╯ │ │
|
||||||
|
│ │ ╰──────╯ │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ VER UBICACIÓN ↗ │ │ ← link to mapUrl
|
||||||
|
│ │ │ │
|
||||||
|
│ └─────────────────────────┘ │
|
||||||
|
│ │
|
||||||
|
└─────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Particle Background Specification
|
||||||
|
|
||||||
|
Canvas implementation details:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface Particle {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
radius: number; // 2–12px
|
||||||
|
opacity: number; // 0.1–0.6
|
||||||
|
blur: number; // 2–15px (via ctx.shadowBlur)
|
||||||
|
goldIntensity: number; // 0–1 (hue shift between warm/cool gold)
|
||||||
|
vx: number; // -0.15 to 0.15 px/frame
|
||||||
|
vy: number; // -0.15 to 0.15 px/frame
|
||||||
|
twinkleSpeed: number; // 0.005–0.02
|
||||||
|
twinklePhase: number; // 0–2π
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Spatial distribution uses a weighted probability that concentrates particles in the upper-left and lower-right quadrants:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function generatePosition(width: number, height: number): [number, number] {
|
||||||
|
// Bias toward upper-left and lower-right corners
|
||||||
|
const bias = Math.random();
|
||||||
|
if (bias < 0.4) {
|
||||||
|
// Upper-left quadrant
|
||||||
|
return [Math.random() * width * 0.5, Math.random() * height * 0.4];
|
||||||
|
} else if (bias < 0.8) {
|
||||||
|
// Lower-right quadrant
|
||||||
|
return [width * 0.5 + Math.random() * width * 0.5, height * 0.6 + Math.random() * height * 0.4];
|
||||||
|
} else {
|
||||||
|
// Sparse center/other areas
|
||||||
|
return [Math.random() * width, Math.random() * height];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Particle count: ~120 on desktop, ~80 on mobile (based on `window.innerWidth`).
|
||||||
|
|
||||||
|
`prefers-reduced-motion`: particles are rendered once as a static frame, animation loop does not run.
|
||||||
|
|
||||||
|
#### Countdown Hook
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function useCountdown(eventDate: string, eventTime: string, timezone: string) {
|
||||||
|
// 1. Construct target: "2026-10-28T19:00:00" in America/Bogota
|
||||||
|
// 2. Convert to UTC milliseconds using Intl.DateTimeFormat or manual offset
|
||||||
|
// (Colombia = UTC-5, no DST, so offset is always -5h)
|
||||||
|
// 3. Calculate: target - Date.now()
|
||||||
|
// 4. Return { days, hours, minutes, seconds, state }
|
||||||
|
// state: 'counting' | 'in_progress' | 'finished'
|
||||||
|
// 5. Update every second via setInterval
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
States:
|
||||||
|
- `counting`: `TE VEO EN 12 : 04 : 37 : 22`
|
||||||
|
- `in_progress`: `EVENTO EN CURSO`
|
||||||
|
- `finished`: `EVENTO FINALIZADO`
|
||||||
|
|
||||||
|
#### Map Preview Component
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function MapPreview({ previewUrl, mapUrl }: { previewUrl: string; mapUrl: string }) {
|
||||||
|
return (
|
||||||
|
<a href={mapUrl} target="_blank" rel="noopener noreferrer" className={styles.mapLink}>
|
||||||
|
<div className={styles.mapCircle}>
|
||||||
|
<img src={previewUrl} alt="Ubicación del evento" />
|
||||||
|
</div>
|
||||||
|
<span className={styles.mapLabel}>VER UBICACIÓN ↗</span>
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
CSS for circular treatment:
|
||||||
|
```css
|
||||||
|
.mapCircle {
|
||||||
|
width: 140px;
|
||||||
|
height: 140px;
|
||||||
|
border-radius: 50%;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid rgba(212, 168, 67, 0.3);
|
||||||
|
transition: transform 0.2s ease, border-color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mapLink:hover .mapCircle {
|
||||||
|
transform: scale(1.05);
|
||||||
|
border-color: rgba(212, 168, 67, 0.6);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P4 — Frontend: Admin Dashboard
|
||||||
|
|
||||||
|
The admin dashboard is a clean, functional interface. No invitation visual effects.
|
||||||
|
|
||||||
|
#### Admin Layout
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌──────────────────────────────────────────────────┐
|
||||||
|
│ 🎂 RSVP Dashboard [Config] │
|
||||||
|
├──────────────────────────────────────────────────┤
|
||||||
|
│ │
|
||||||
|
│ Respuestas: 37 [Descargar] │
|
||||||
|
│ │
|
||||||
|
│ Buscar: [________________________] │
|
||||||
|
│ │
|
||||||
|
│ ┌────────────┬──────────────┬───────┬─────────┐ │
|
||||||
|
│ │ Nombre │ Teléfono │ Email │ Fecha │ │
|
||||||
|
│ ├────────────┼──────────────┼───────┼─────────┤ │
|
||||||
|
│ │ Ana García │ 300 123 4567 │ ana@… │ Sep 30 │ │
|
||||||
|
│ │ Carlos P. │ 311 987 6543 │ — │ Sep 29 │ │
|
||||||
|
│ └────────────┴──────────────┴───────┴─────────┘ │
|
||||||
|
│ │
|
||||||
|
└──────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Config Editor
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌──────────────────────────────────────────────────┐
|
||||||
|
│ 🎂 Configuración [← Volver] │
|
||||||
|
├──────────────────────────────────────────────────┤
|
||||||
|
│ │
|
||||||
|
│ ┌─── Editar ──────────────────────────────────┐ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Nombre del homenajeado │ │
|
||||||
|
│ │ [Isabelle Snow ] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Fecha del evento │ │
|
||||||
|
│ │ [2026-10-28] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Hora Zona horaria │ │
|
||||||
|
│ │ [19:00] [America/Bogota ] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Texto de invitación │ │
|
||||||
|
│ │ [You're invited to the birthday...] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Nombre del lugar │ │
|
||||||
|
│ │ [Fresco Ristorante ] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Dirección (una línea por línea) │ │
|
||||||
|
│ │ [514 S Brand Blvd ] │ │
|
||||||
|
│ │ [Glendale, CA 91204 ] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ URL preview del mapa │ │
|
||||||
|
│ │ [https://tile.openstreetmap.org/...] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ URL del mapa (Google Maps, etc.) │ │
|
||||||
|
│ │ [https://www.google.com/maps/...] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ ... (CTA, submit label, messages) ... │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ [Guardar cambios] │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ └─────────────────────────────────────────────┘ │
|
||||||
|
│ │
|
||||||
|
│ ┌─── Vista previa ───────────────────────────┐ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Birthday Party │ │
|
||||||
|
│ │ You're invited to the birthday party... │ │
|
||||||
|
│ │ Isabelle Snow │ │
|
||||||
|
│ │ FRIDAY | OCT 28 | 7:00 PM │ │
|
||||||
|
│ │ FRESCO RISTORANTE │ │
|
||||||
|
│ │ 514 S Brand Blvd, Glendale, CA 91204 │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ └────────────────────────────────────────────┘ │
|
||||||
|
│ │
|
||||||
|
└──────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
The preview is a plain-text rendering of how the fields compose — **not** a visual replica of the invitation with particles and fonts. It shows the content hierarchy so the admin can verify field values before saving.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P5 — Accessibility
|
||||||
|
|
||||||
|
| Requirement | Implementation |
|
||||||
|
|---|---|
|
||||||
|
| Semantic HTML | `<main>`, `<section>`, `<form>`, `<h1>`–`<h3>`, `<label>`, `<button>` |
|
||||||
|
| Keyboard CTA | CTA is a `<button>` with `tabindex`, visible `:focus-visible` ring |
|
||||||
|
| Keyboard form | Standard form tab order, `<label htmlFor>` associations |
|
||||||
|
| Focus states | Gold outline ring on interactive elements |
|
||||||
|
| Text contrast | White on `#0a0a0a` exceeds WCAG AAA (21:1) |
|
||||||
|
| aria-live | `<div aria-live="polite">` wraps submission result messages |
|
||||||
|
| Reduced motion | `@media (prefers-reduced-motion: reduce)` → static particles, no scroll animation |
|
||||||
|
| Error messages | Inline, associated via `aria-describedby` on the field |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project File Tree (Complete)
|
||||||
|
|
||||||
|
```text
|
||||||
|
Sites/bdinvite/
|
||||||
|
├── app.yaml
|
||||||
|
├── docker-compose.yml
|
||||||
|
├── Dockerfile
|
||||||
|
├── .gitignore
|
||||||
|
├── README.md
|
||||||
|
├── specs/
|
||||||
|
│ └── front.md # Existing spec (preserved)
|
||||||
|
├── backend/
|
||||||
|
│ ├── pyproject.toml
|
||||||
|
│ ├── app/
|
||||||
|
│ │ ├── __init__.py
|
||||||
|
│ │ ├── main.py
|
||||||
|
│ │ ├── config.py
|
||||||
|
│ │ ├── database.py
|
||||||
|
│ │ ├── models.py
|
||||||
|
│ │ ├── schemas.py
|
||||||
|
│ │ ├── routes/
|
||||||
|
│ │ │ ├── __init__.py
|
||||||
|
│ │ │ ├── rsvp.py
|
||||||
|
│ │ │ ├── config.py
|
||||||
|
│ │ │ └── admin.py
|
||||||
|
│ │ └── services/
|
||||||
|
│ │ ├── __init__.py
|
||||||
|
│ │ ├── rsvp.py
|
||||||
|
│ │ └── config.py
|
||||||
|
│ └── tests/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── test_rsvp.py
|
||||||
|
│ └── test_config.py
|
||||||
|
├── frontend/
|
||||||
|
│ ├── package.json
|
||||||
|
│ ├── vite.config.ts
|
||||||
|
│ ├── tsconfig.json
|
||||||
|
│ ├── index.html
|
||||||
|
│ └── src/
|
||||||
|
│ ├── main.tsx
|
||||||
|
│ ├── App.tsx
|
||||||
|
│ ├── api/
|
||||||
|
│ │ └── client.ts
|
||||||
|
│ ├── types/
|
||||||
|
│ │ └── config.ts
|
||||||
|
│ ├── hooks/
|
||||||
|
│ │ ├── useConfig.ts
|
||||||
|
│ │ ├── useCountdown.ts
|
||||||
|
│ │ └── useRsvpForm.ts
|
||||||
|
│ ├── invitation/
|
||||||
|
│ │ ├── Invitation.tsx
|
||||||
|
│ │ ├── InvitationContent.tsx
|
||||||
|
│ │ ├── ParticleBackground.tsx
|
||||||
|
│ │ ├── RsvpCta.tsx
|
||||||
|
│ │ ├── RsvpForm.tsx
|
||||||
|
│ │ ├── RsvpResult.tsx
|
||||||
|
│ │ ├── Countdown.tsx
|
||||||
|
│ │ └── MapPreview.tsx
|
||||||
|
│ ├── admin/
|
||||||
|
│ │ ├── AdminLayout.tsx
|
||||||
|
│ │ ├── RsvpTable.tsx
|
||||||
|
│ │ └── ConfigEditor.tsx
|
||||||
|
│ ├── components/
|
||||||
|
│ │ ├── Button.tsx
|
||||||
|
│ │ ├── Field.tsx
|
||||||
|
│ │ └── Spinner.tsx
|
||||||
|
│ └── styles/
|
||||||
|
│ ├── global.module.css
|
||||||
|
│ ├── invitation.module.css
|
||||||
|
│ ├── particles.module.css
|
||||||
|
│ ├── rsvp.module.css
|
||||||
|
│ ├── result.module.css
|
||||||
|
│ └── admin.module.css
|
||||||
|
└── data/ # Volume-mounted, gitignored
|
||||||
|
└── bdinvite.db
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification Plan
|
||||||
|
|
||||||
|
### Automated Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Backend unit tests
|
||||||
|
cd Sites/bdinvite/backend
|
||||||
|
uv sync --dev
|
||||||
|
uv run pytest tests/ -v
|
||||||
|
|
||||||
|
# Frontend build verification
|
||||||
|
cd Sites/bdinvite/frontend
|
||||||
|
npm ci
|
||||||
|
npm run build # TypeScript compilation + Vite build
|
||||||
|
```
|
||||||
|
|
||||||
|
Backend tests cover:
|
||||||
|
- **RSVP submission**: success, duplicate (phone match), validation errors
|
||||||
|
- **Phone normalization**: `+57 300 123 4567` → `3001234567`, invalid formats rejected
|
||||||
|
- **Config CRUD**: seed defaults, update, retrieve
|
||||||
|
- **Admin auth guard**: missing `Remote-User` header returns 401
|
||||||
|
|
||||||
|
### Docker Build Verification
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd Sites/bdinvite
|
||||||
|
docker compose build
|
||||||
|
docker compose up -d
|
||||||
|
# Verify container starts and serves:
|
||||||
|
curl -s http://localhost:8000/birthday/invite | head -5
|
||||||
|
curl -s http://localhost:8000/birthday/api/config | python3 -m json.tool
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Verification
|
||||||
|
|
||||||
|
The user should manually verify after deployment:
|
||||||
|
|
||||||
|
1. **Guest flow**: Visit `https://demos.roadtotech.me/birthday/invite`, verify invitation renders with particles, submit RSVP, see success state with countdown and map
|
||||||
|
2. **Authelia protection**: Visit `https://demos.roadtotech.me/birthday/admin` unauthenticated → redirect to `auth.roadtotech.me`
|
||||||
|
3. **Admin dashboard**: After Authelia login, verify RSVP table shows the test submission, CSV export works
|
||||||
|
4. **Config editor**: Edit invitation text, verify the public invitation updates
|
||||||
|
5. **Duplicate detection**: Submit the same phone number again, verify duplicate message
|
||||||
|
6. **Responsive**: Test on mobile viewport (Chrome DevTools or actual device)
|
||||||
|
7. **Reduced motion**: Enable `prefers-reduced-motion` in browser, verify particles are static
|
||||||
|
8. **Countdown states**: Verify countdown calculates correctly against `America/Bogota` timezone
|
||||||
|
|
||||||
|
### Deployment Handoff
|
||||||
|
|
||||||
|
After local build verification passes, the deployment handoff will include:
|
||||||
|
- Exact `appctl` / docker compose commands
|
||||||
|
- Post-deployment verification commands
|
||||||
|
- Rollback procedure
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: bdinvite
|
||||||
|
tags:
|
||||||
|
- bdinvite
|
||||||
|
- oidc
|
||||||
|
- sso
|
||||||
|
- benchmark
|
||||||
|
- graphify
|
||||||
|
- hexagonal-architecture
|
||||||
|
---
|
||||||
|
|
||||||
|
# Implementation Plan: BDInvite SSO Benchmark & Checkpoint Roadmap (Frozen Specification v6)
|
||||||
|
|
||||||
|
## Goal Description
|
||||||
|
Establish a controlled, reproducible A/B benchmark comparing two autonomous agents implementing application-level OpenID Connect (OIDC) Single Sign-On (SSO) in the `bdinvite` repository:
|
||||||
|
1. **Control Agent**: Standard repository exploration and toolchain (`grep`, `find`, `view_file`, `git`, etc.).
|
||||||
|
2. **Treatment Agent (Graphify)**: Standard toolchain **plus** Graphify-augmented exploration (`graphify query`, `graphify path`, `graphify explain`, and `graphify update .`).
|
||||||
|
|
||||||
|
### Core Architectural Invariant: Hexagonal Authentication Boundary
|
||||||
|
The benchmark moves authentication from an infrastructure property (Traefik reverse proxy + Authelia ForwardAuth + `Remote-User` header inspection) into a **decoupled application port (`AuthPort`)**:
|
||||||
|
* **Strict Separation of Authentication vs. Authorization**:
|
||||||
|
- **Authentication ("Who are you?")**: Handled by `AuthPort`, which resolves requests into typed `Identity` objects carrying standard attributes and group memberships (`groups: list[str]`).
|
||||||
|
- **Authorization ("What are you allowed to do?")**: Handled exclusively by the **Application Domain**, which evaluates application policies against `identity.groups` (e.g., `"bdinvite_admins" in identity.groups`). `AuthPort` does not own authorization decisions.
|
||||||
|
* **Identity Origin Integrity**: `Identity` contains only claims authenticated and validated by the authentication module. Application code must **never** construct an authenticated `Identity` directly from unvalidated request-controlled data (headers, query parameters, body).
|
||||||
|
* **OIDC Authentication Module**: Implements `AuthPort` and communicates with any standards-compliant OIDC Provider through a generic OIDC client (discovery, PKCE/state/nonce, token exchange, JWKS signature validation).
|
||||||
|
* **Deployment Independence**: The exact same codebase runs:
|
||||||
|
- Locally / standalone against a disposable standards-compliant OIDC test container.
|
||||||
|
- In homelab production against **Authelia configured as an OIDC Provider**, reducing Traefik strictly to TLS termination and reverse-proxy routing (zero ForwardAuth middleware).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Epistemic Roles of Benchmark Artifacts
|
||||||
|
|
||||||
|
The experiment maintains a strict division of artifact roles across three distinct locations:
|
||||||
|
|
||||||
|
| Artifact | Location | Epistemic Role | Mutability |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Canonical Engineering Plan** | `Brain/01-plans/bdinvite/sso-benchmark-roadmap.md` | Vault knowledge graph, project topology, roadmap | Mutable across project lifecycle |
|
||||||
|
| **Immutable Benchmark Snapshot** | `benchmark/specification/bdinvite_sso_benchmark_plan.md` | Concrete experimental input; hashed (SHA-256) | **Immutable / Frozen** |
|
||||||
|
| **Machine Event Ledger** | `Brain/00-inbox/commit-log.csv` | Lossless event capture from `commit-logger` | Append-only raw data |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Frozen Experimental Invariants & Decisions
|
||||||
|
|
||||||
|
1. **Authentication vs. Authorization Separation**:
|
||||||
|
- `AuthPort` defines only authentication mechanics: `current_identity(request)`, `login(request)`, and `logout(request)`.
|
||||||
|
- `Identity` carries `subject`, `email`, `name`, and `groups: list[str]`.
|
||||||
|
- Group authorization is an application-domain policy: `require_group("bdinvite_admins")` verifies `"bdinvite_admins" in identity.groups`.
|
||||||
|
2. **Identity Origin Integrity**:
|
||||||
|
- Identity fields must be derived exclusively from claims contained in the cryptographically validated ID token / validated OIDC authentication result. Unvalidated userinfo or request data must not be used to construct `Identity`.
|
||||||
|
3. **Session Contract & Session Fixation Protection**:
|
||||||
|
- Browser session uses `HttpOnly: true` and an explicit `SameSite` policy. No bearer tokens exposed to JavaScript.
|
||||||
|
- Successful authentication must establish a **new session identifier**; an existing pre-authentication session identifier must not be promoted into an authenticated session (`pre_auth_session_id != post_auth_session_id`).
|
||||||
|
- `Secure` flag contract: `Secure=True` in production; configurable (`Secure=False`) in the local HTTP test environment so browsers do not reject cookies over local test ports.
|
||||||
|
- Internal storage (client-side encrypted/signed vs server-side SQLite table) is left to the agent's architectural discretion.
|
||||||
|
4. **Provider Model & Group Claim**:
|
||||||
|
- The test fixture uses a standards-compliant disposable OIDC provider container pre-seeded with discovery, JWKS, and standard users.
|
||||||
|
- The fixture's group claim is frozen as `"groups": ["bdinvite_admins"]` (for admin) and `"groups": ["guests"]` (for guest). The auth module maps this configured claim to `Identity.groups`.
|
||||||
|
5. **Git Workflow Invariant (Subagent Delegation)**:
|
||||||
|
- At every meaningful implementation milestone required by the roadmap, the primary implementation agent **must recruit the `git-commit` skill via subagent delegation** (`invoke_subagent` with Role: "Git History Custodian").
|
||||||
|
- **Both Control and Treatment agents MUST use the identical `git-commit` workflow.**
|
||||||
|
- **Graphify is explicitly excluded from the `git-commit` subagent's toolset and prompt.** The experimental variable remains strictly confined to the primary agent's repository exploration.
|
||||||
|
- The benchmark harness records the resulting commit SHA, parent SHA, subject, checkpoint, and timing. The harness itself **never** creates implementation commits.
|
||||||
|
- Commits created solely to manipulate benchmark metrics without meaningful code/test changes are prohibited.
|
||||||
|
6. **Graphify Lifecycle Rules**:
|
||||||
|
- The Graphify agent may run `graphify update .` whenever repository changes make the existing graph stale.
|
||||||
|
- Every graph update, query, path, and explanation is recorded in telemetry under `graph_lifecycle`.
|
||||||
|
- The prompt does **not** force the agent to use Graphify; Graphify is simply available as an additional capability alongside standard tools.
|
||||||
|
7. **Evaluator Immutability Barrier**:
|
||||||
|
- Neither agent may alter the roadmap, checkpoint definitions, verification test suite, test credentials, or telemetry logger. All evaluation occurs via an external test runner outside the agents' worktrees.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pre-Experiment Preparation & Freeze Phase
|
||||||
|
|
||||||
|
Before either implementation agent touches a worktree, the experiment harness executes the **Pre-Experiment Freeze Gate**:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
Start["Pre-Experiment Freeze Gate"] --> FreezeSpec["1. Write & Hash Specification<br/>benchmark/specification/bdinvite_sso_benchmark_plan.md<br/>Compute SHA-256"]
|
||||||
|
FreezeSpec --> FreezeHarness["2. Freeze Evaluator & Test Suite<br/>(External pytest + Playwright tests)"]
|
||||||
|
FreezeHarness --> FreezeFixture["3. Freeze OIDC Fixture & Credentials<br/>(Docker Compose + JWKS + Users)"]
|
||||||
|
FreezeFixture --> BaselineManifest["4. Generate baseline.json<br/>(Observed Commit SHA, 25 Passing Tests, Builds)"]
|
||||||
|
BaselineManifest --> Worktrees["5. Stand Up Isolated Worktrees<br/>control/ & graphify/<br/>Verify Identical Starting Commit"]
|
||||||
|
Worktrees --> CP0Done["CP0 Readiness Verified<br/>Launch Benchmark Execution"]
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **Specification Hashing**:
|
||||||
|
- Write immutable snapshot to `/home/kiskaadee/Projects/tests/bdinvite-benchmark/specification/bdinvite_sso_benchmark_plan.md`.
|
||||||
|
- Calculate and record its SHA-256 hash in `manifest.json`.
|
||||||
|
2. **Evaluator Freeze**:
|
||||||
|
- Scaffold external evaluation scripts and test suites under `benchmark/evaluator/`.
|
||||||
|
3. **Fixture Freeze**:
|
||||||
|
- Stand up the disposable OIDC provider container (pre-seeded with discovery, JWKS, client credentials, and users).
|
||||||
|
4. **Baseline Manifest Generation**:
|
||||||
|
- Record observed starting commit (`42927b9858c1b091bb6e78d3abcf6f9500bd7547`), verify 25 passing backend tests, frontend build, and Docker container build.
|
||||||
|
5. **Worktree Provisioning**:
|
||||||
|
- Create worktree: `/home/kiskaadee/Projects/tests/bdinvite-benchmark/control` (branch `control/feat/sso-auth`).
|
||||||
|
- Create worktree: `/home/kiskaadee/Projects/tests/bdinvite-benchmark/graphify` (branch `graphify/feat/sso-auth`).
|
||||||
|
- Run initial `graphify extract . --code-only` inside the `graphify` worktree.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sequential Checkpoint Roadmap (CP1 – CP8)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
CP1["CP1: AuthPort Contract"] --> CP2["CP2: OIDC Client & PKCE"]
|
||||||
|
CP2 --> CP3["CP3: Identity Resolution"]
|
||||||
|
CP3 --> CP4["CP4: HttpOnly Session & Fixation"]
|
||||||
|
CP4 --> CP5["CP5: DI Dependencies"]
|
||||||
|
CP5 --> CP6["CP6: Admin Route Migration"]
|
||||||
|
CP6 --> CP7["CP7: Browser SSO Flow"]
|
||||||
|
CP7 --> CP8["CP8: Hardening & Independence"]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Checkpoint 1 (CP1): The Authentication Port (`AuthPort`)
|
||||||
|
* **Objective**: Define the application-facing authentication boundary and identity domain models, decoupling the application domain completely from upstream protocols and proxies.
|
||||||
|
* **Behavioral Requirements**:
|
||||||
|
- Define domain abstraction: `Identity` (holding `subject: str`, `email: str`, `name: Optional[str]`, `groups: list[str]`).
|
||||||
|
- Identity Origin Integrity: `Identity` must only be constructed from validated authentication results, never raw client headers.
|
||||||
|
- Define `AuthPort` protocol establishing:
|
||||||
|
* `current_identity(request: Request) -> Optional[Identity]`
|
||||||
|
* `login(request: Request) -> Response`
|
||||||
|
* `logout(request: Request) -> Response`
|
||||||
|
- Zero application routes or domain models may import or reference OIDC, OAuth, JWT, or proxy headers.
|
||||||
|
* **Verification & Invariant**:
|
||||||
|
- Unit tests verifying `AuthPort` contract with a test mock implementation.
|
||||||
|
- **Behavioral Invariant**: **No externally observable application behavior changes during CP1.** (Minimal dependency wiring and unit tests are allowed; existing endpoints behave identically).
|
||||||
|
- All 25 baseline tests continue to pass.
|
||||||
|
* **Exit Criteria**:
|
||||||
|
- `AuthPort` abstraction established and testable in isolation.
|
||||||
|
- Changes committed via `git-commit` subagent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Checkpoint 2 (CP2): Generic OIDC Client, PKCE & Cryptographic Verification
|
||||||
|
* **Objective**: Implement the generic OIDC protocol client capable of communicating with any OIDC provider with strict PKCE, CSRF state, and replay nonce validation.
|
||||||
|
* **Protocol Invariants & Behavioral Requirements**:
|
||||||
|
- Fetch and parse OIDC discovery document (`/.well-known/openid-configuration`).
|
||||||
|
- **PKCE (RFC 7636)**:
|
||||||
|
* Generate cryptographically random `code_verifier`.
|
||||||
|
* Derive `code_challenge` using SHA-256 (`code_challenge_method=S256`).
|
||||||
|
* Include `code_challenge` and `code_challenge_method` in the authorization request.
|
||||||
|
* Persist `code_verifier` across the transaction and supply it in the token exchange.
|
||||||
|
- **Transaction Correlation (`state`)**: Construct authorization URL with a cryptographic `state` parameter; validate `state` on callback to prevent CSRF attacks.
|
||||||
|
- **Replay Protection (`nonce`)**: Construct authorization URL with a cryptographic `nonce`; validate that the signed ID token's `nonce` claim matches the initiated request.
|
||||||
|
- Exchange authorization code for token response (`/token`).
|
||||||
|
- Cryptographically validate ID Token:
|
||||||
|
* Signature verification against provider's JWKS endpoint (`/jwks.json`).
|
||||||
|
* Issuer validation (`iss` == configured issuer).
|
||||||
|
* Audience validation (`aud` == configured client ID).
|
||||||
|
* Expiration validation (`exp` > current timestamp).
|
||||||
|
* **Verification**:
|
||||||
|
- Automated tests against the OIDC test container:
|
||||||
|
* Valid code exchange returns signed ID token.
|
||||||
|
* Authorization request verified to contain PKCE and `state`/`nonce` parameters.
|
||||||
|
* Invalid `state` rejected with 400.
|
||||||
|
* Mismatched `nonce`, missing PKCE verifier, or expired token rejected with 401.
|
||||||
|
* Tampered signature rejected with 401.
|
||||||
|
* **Exit Criteria**:
|
||||||
|
- OIDC exchange passes all cryptographic and protocol validation gates.
|
||||||
|
- Changes committed via `git-commit` subagent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Checkpoint 3 (CP3): OIDC Identity & Group Extraction
|
||||||
|
* **Objective**: Connect the generic OIDC client to the `AuthPort` identity resolution lifecycle, deriving identity strictly from authenticated claims.
|
||||||
|
* **Behavioral Requirements**:
|
||||||
|
- Extract standard claims (`sub`, `email`, `name`).
|
||||||
|
- Extract group membership claims from the frozen fixture claim path (`"groups"`).
|
||||||
|
- Authoritative Provenance: `Identity` fields must be derived exclusively from claims contained in the cryptographically validated ID token / validated OIDC authentication result; unvalidated userinfo or request data must not be used to construct `Identity`.
|
||||||
|
- Confirm `admin@example.com` produces `groups: ["bdinvite_admins"]` and `guest@example.com` produces `groups: ["guests"]`.
|
||||||
|
* **Verification**:
|
||||||
|
- Test verifying end-to-end extraction from OIDC callback to typed `Identity`.
|
||||||
|
* **Exit Criteria**:
|
||||||
|
- Clean mapping from provider claims to application `Identity`.
|
||||||
|
- Changes committed via `git-commit` subagent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Checkpoint 4 (CP4): Browser Session Management & Session Fixation Protection
|
||||||
|
* **Objective**: Establish and persist an application-level browser session following successful OIDC authentication with session fixation protection.
|
||||||
|
* **Behavioral Requirements**:
|
||||||
|
- Issue session identifier via `HttpOnly`, `SameSite` cookie upon successful authentication.
|
||||||
|
- **Session Fixation Barrier**: Successful authentication must establish a **new session identifier**; an existing pre-authentication session identifier must not be promoted into an authenticated session (`pre_auth_session_id != post_auth_session_id`).
|
||||||
|
- Cookie security configuration: `Secure=True` in production, configurable for local HTTP testing.
|
||||||
|
- Session resolution: identify returning requests from the session cookie.
|
||||||
|
- Expiration: reject expired sessions.
|
||||||
|
- Invalidation: `/birthday/api/auth/logout` revokes session and clears cookie.
|
||||||
|
- Security Invariant: Session token/cookie must not be readable by client-side JavaScript (`HttpOnly: true`).
|
||||||
|
* **Verification**:
|
||||||
|
- Tests verifying:
|
||||||
|
* Pre-authentication session ID is rotated upon login.
|
||||||
|
* Request with valid session cookie resolves to authenticated `Identity`.
|
||||||
|
* Request without cookie resolves to anonymous (`None`).
|
||||||
|
* Tampered cookie rejected (401).
|
||||||
|
* Logout clears session.
|
||||||
|
* **Exit Criteria**:
|
||||||
|
- Browser session contract fully functional and verified.
|
||||||
|
- Changes committed via `git-commit` subagent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Checkpoint 5 (CP5): FastAPI Dependency Injection (Isolated Verification)
|
||||||
|
* **Objective**: Expose authentication and group authorization to FastAPI endpoints via standard dependency injection (`Depends`), verified independently on isolated test harnesses before modifying production admin routes.
|
||||||
|
* **Behavioral Requirements**:
|
||||||
|
- Implement FastAPI dependencies:
|
||||||
|
* `get_current_identity -> Optional[Identity]`
|
||||||
|
* `require_authenticated -> Identity` (401 if anonymous)
|
||||||
|
* `require_group(group_name: str) -> Callable[..., Identity]` (401 if anonymous, 403 if missing group)
|
||||||
|
- Application authorization policy:
|
||||||
|
* `require_admin = require_group("bdinvite_admins")`
|
||||||
|
* **Verification**:
|
||||||
|
- Verified on dedicated test routes / unit dependency harnesses:
|
||||||
|
* Anonymous request $\to$ 401 Unauthorized.
|
||||||
|
* Authenticated user without `bdinvite_admins` $\to$ 403 Forbidden.
|
||||||
|
* Authenticated user with `bdinvite_admins` $\to$ yields `Identity` object.
|
||||||
|
* **Exit Criteria**:
|
||||||
|
- Dependency injection contract verified in isolation without yet altering production admin routes.
|
||||||
|
- Changes committed via `git-commit` subagent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Checkpoint 6 (CP6): Admin API Route Migration & Negative Barrier
|
||||||
|
* **Objective**: Migrate all endpoints in `backend/app/routes/admin.py` to use `Depends(require_group("bdinvite_admins"))`, purging `Remote-User` from runtime code.
|
||||||
|
* **Behavioral Requirements**:
|
||||||
|
- Update `/rsvps`, `/export`, `/config`, `/map-preview/generate` to consume the new group authorization dependency.
|
||||||
|
- Update `test_admin.py` test suite to use test session injection rather than mock headers.
|
||||||
|
- Anonymous requests receive 401 Unauthorized.
|
||||||
|
- Authenticated non-admin requests (`guest@example.com`) receive 403 Forbidden.
|
||||||
|
- Authenticated admin requests (`admin@example.com`) succeed.
|
||||||
|
- **CRITICAL NEGATIVE GATE**:
|
||||||
|
```python
|
||||||
|
def test_remote_user_header_strictly_ignored(client):
|
||||||
|
# A request containing Remote-User without a valid session MUST be rejected
|
||||||
|
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
|
||||||
|
assert res.status_code == 401
|
||||||
|
```
|
||||||
|
* **Exit Criteria**:
|
||||||
|
- Negative gate passes.
|
||||||
|
- All existing admin functionality (RSVP listing, CSV export, config updates) passes cleanly.
|
||||||
|
- Changes committed via `git-commit` subagent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Checkpoint 7 (CP7): Complete Browser SSO Flow (Playwright Acceptance)
|
||||||
|
* **Objective**: Integrate the React SPA in `frontend/src/admin` with the OIDC authentication flow and verify the complete browser lifecycle using a real browser automation suite (Playwright).
|
||||||
|
* **Deterministic Contract & Behavioral Requirements**:
|
||||||
|
- An unauthenticated navigation to `/birthday/admin` must initiate authentication by navigating to `/birthday/api/auth/login`.
|
||||||
|
- The login endpoint redirects to the configured OIDC authorization endpoint.
|
||||||
|
- Callback completes, sets `HttpOnly` cookie, and redirects user into `/birthday/admin`.
|
||||||
|
- Admin header displays authenticated user info and a working Logout button.
|
||||||
|
- Clicking Logout calls `/birthday/api/auth/logout` and returns UI to unauthenticated state.
|
||||||
|
* **Verification (Playwright Acceptance Suite)**:
|
||||||
|
- Real browser automation validating the entire interactive loop:
|
||||||
|
1. Navigate to `/birthday/admin` $\to$ redirected to OIDC login.
|
||||||
|
2. Submit test credentials (`admin@example.com` / `password123`).
|
||||||
|
3. Browser follows redirect to callback $\to$ receives `HttpOnly` session cookie $\to$ lands on Admin Dashboard.
|
||||||
|
4. Confirm RSVPs table renders live data.
|
||||||
|
5. Click Logout button $\to$ cookie invalidated $\to$ unauthenticated state confirmed.
|
||||||
|
- Frontend TypeScript build compiles with zero errors (`npm run build`).
|
||||||
|
* **Exit Criteria**:
|
||||||
|
- Playwright browser acceptance test passes 100%.
|
||||||
|
- Changes committed via `git-commit` subagent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Checkpoint 8 (CP8): Security Hardening & Deployment Independence
|
||||||
|
* **Objective**: Subject the completed application to adversarial edge cases, verify cumulative test status, and verify dual-environment deployment.
|
||||||
|
* **Adversarial & Security Verification**:
|
||||||
|
1. Forged / invalid CSRF `state` $\to$ 400 Bad Request.
|
||||||
|
2. Forged / tampered ID token $\to$ 401 Unauthorized.
|
||||||
|
3. Mismatched / replayed `nonce` $\to$ 401 Unauthorized.
|
||||||
|
4. Missing or invalid PKCE `code_verifier` $\to$ 401 Unauthorized.
|
||||||
|
5. Expired ID token / expired session $\to$ 401 Unauthorized.
|
||||||
|
6. Non-admin user accessing admin APIs $\to$ 403 Forbidden.
|
||||||
|
7. Forged `Remote-User` header $\to$ 401 Unauthorized.
|
||||||
|
* **Deployment Independence Verification**:
|
||||||
|
1. **Direct Standalone Mode**: BDInvite + OIDC test container with NO Traefik and NO Authelia $\to$ **PASS**.
|
||||||
|
2. **Homelab Production Mode**: BDInvite deployed with Authelia acting as an OIDC provider, with Traefik providing pure TLS/ingress $\to$ **PASS**.
|
||||||
|
* **Cumulative Verification Definition**:
|
||||||
|
The cumulative suite requires 100% pass across:
|
||||||
|
- All checkpoint-specific suites (CP1–CP7).
|
||||||
|
- All baseline regression tests (25/25 original tests).
|
||||||
|
- Playwright end-to-end browser suite.
|
||||||
|
- CP8 adversarial security suite.
|
||||||
|
* **Exit Criteria**:
|
||||||
|
- All cumulative verification tests pass.
|
||||||
|
- Multi-stage Docker container builds successfully.
|
||||||
|
- Changes committed via `git-commit` subagent.
|
||||||
|
- Final checkpoint report generated.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Enhanced Telemetry & Metric Capture Protocol
|
||||||
|
|
||||||
|
For each subagent across each checkpoint (CP1 to CP8), the experiment harness records granular telemetry into `results/<agent>/<checkpoint>.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"agent": "control | graphify",
|
||||||
|
"checkpoint": "CP4",
|
||||||
|
"started_at": "2026-10-02T22:30:00Z",
|
||||||
|
"ended_at": "2026-10-02T22:45:00Z",
|
||||||
|
"duration_wall_clock_seconds": 900,
|
||||||
|
"duration_active_seconds": 740,
|
||||||
|
"turns": 14,
|
||||||
|
"attempts": 2,
|
||||||
|
"rework_iterations": 1,
|
||||||
|
"status": "PASS | FAIL | BLOCKED",
|
||||||
|
"outcome_reason": "none | verification_failure | environment_failure | timeout",
|
||||||
|
"verification": {
|
||||||
|
"checkpoint_tests": {
|
||||||
|
"passed": 8,
|
||||||
|
"total": 8
|
||||||
|
},
|
||||||
|
"cumulative_regression_tests": {
|
||||||
|
"passed": 25,
|
||||||
|
"total": 25
|
||||||
|
},
|
||||||
|
"failed_verifications_count": 3
|
||||||
|
},
|
||||||
|
"git": {
|
||||||
|
"commits_created": 2,
|
||||||
|
"checkpoint_commit_sha": "a81f3c2...",
|
||||||
|
"commit_shas": ["91bc7de...", "a81f3c2..."]
|
||||||
|
},
|
||||||
|
"tool_calls": {
|
||||||
|
"exploration": {
|
||||||
|
"view_file": 8,
|
||||||
|
"run_grep_or_find": 4,
|
||||||
|
"graphify_query": 3,
|
||||||
|
"graphify_path": 2,
|
||||||
|
"graphify_explain": 1
|
||||||
|
},
|
||||||
|
"implementation": {
|
||||||
|
"replace_file_content": 5,
|
||||||
|
"write_to_file": 2
|
||||||
|
},
|
||||||
|
"verification": {
|
||||||
|
"run_test_command": 4
|
||||||
|
},
|
||||||
|
"graph_lifecycle": {
|
||||||
|
"graph_extractions": 1,
|
||||||
|
"graph_queries": 3,
|
||||||
|
"graph_paths": 2,
|
||||||
|
"graph_explains": 1
|
||||||
|
},
|
||||||
|
"other": {
|
||||||
|
"git_status": 2,
|
||||||
|
"env_checks": 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tokens": {
|
||||||
|
"input_tokens": 42100,
|
||||||
|
"output_tokens": 5400,
|
||||||
|
"total_tokens": 47500
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Final Independent Evaluation: Static & Behavioral Compliance
|
||||||
|
|
||||||
|
At the conclusion of the experiment, an independent evaluator analyzes both worktrees across three objective axes:
|
||||||
|
|
||||||
|
1. **Functional Correctness**:
|
||||||
|
- 100% pass rate on all cumulative checkpoint verification suites.
|
||||||
|
- 100% pass rate on the baseline regression suite (25/25 original tests).
|
||||||
|
- Playwright end-to-end browser acceptance suite passes.
|
||||||
|
2. **Static Architectural Assertions**:
|
||||||
|
- Runtime `Remote-User` occurrences across `backend/app/` and `frontend/src/` == 0.
|
||||||
|
- Application domain imports of OIDC, OAuth, JWT, or proxy libraries == 0.
|
||||||
|
- `Identity` construction sites enumerated and verified to originate strictly from validated claims.
|
||||||
|
- `AuthPort` interface implementation exists.
|
||||||
|
- Admin routes depend strictly on application group authorization.
|
||||||
|
- OIDC issuer is externalized and loaded from configuration.
|
||||||
|
- Traefik is strictly an ingress/TLS proxy with zero authentication middleware responsibilities.
|
||||||
|
3. **Exploration Efficiency**:
|
||||||
|
- Side-by-side comparison of exploration tool calls vs implementation tool calls.
|
||||||
|
- Total tokens and turns consumed per checkpoint.
|
||||||
|
- Frequency of rework iterations when encountering verification failures.
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: brain
|
||||||
|
date: 2026-10-07
|
||||||
|
tags:
|
||||||
|
- agent-architecture
|
||||||
|
- persona
|
||||||
|
- gitea
|
||||||
|
- frontend
|
||||||
|
- multi-agent
|
||||||
|
---
|
||||||
|
|
||||||
|
# Anne Droid Agent Persona & Gitea Integration Roadmap
|
||||||
|
|
||||||
|
> **Target System**: Local Antigravity development environment and self-hosted Gitea forge (`gitea.roadtotech.me`).
|
||||||
|
> **Role & Persona**: Anne Droid — Senior Frontend Engineer & UX Specialist.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
This plan operationalizes **Anne Droid** as an autonomous, persistent engineering collaborator for Frontend development, user interface interaction, and UX review. Anne is not a procedural skill; she is an agent persona with dedicated authority boundaries, isolated Gitea credentials, and genuine version control provenance.
|
||||||
|
|
||||||
|
The primary operational outcomes:
|
||||||
|
1. Genuine forge provenance on `gitea.roadtotech.me` via dedicated user `anne-droid`, ed25519 SSH authentication on port 2223, and `tea` CLI integration.
|
||||||
|
2. Safe Branch & PR Autonomy: Anne implements UI code on `feat/anne/*` branches and opens PRs without having permission to commit to `main`, merge PRs, or alter backend logic autonomously.
|
||||||
|
3. A formal "Frontend → Backend Feedback" loop providing structured, consumer-perspective reviews of backend endpoints and schemas.
|
||||||
|
4. Clean integration within the portable skills repository (`profile/agents/anne-droid.md`) and Antigravity subagent registry.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Technical Specifications & Contracts
|
||||||
|
|
||||||
|
### System Topology
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
User["Human Lead / Backend Engineer"]
|
||||||
|
MainAgent["Main Agent (Orchestrator)"]
|
||||||
|
AnneSubagent["Anne Droid (Subagent)"]
|
||||||
|
GiteaForge["Gitea Forge (gitea.roadtotech.me:2223)"]
|
||||||
|
RepoWorkspace["Local Project Workspace"]
|
||||||
|
|
||||||
|
User <-->|"Architectural Review & Merges"| MainAgent
|
||||||
|
MainAgent -->|"Consult (Advisory Mode)"| AnneSubagent
|
||||||
|
MainAgent -->|"Delegate (Implementation Mode)"| AnneSubagent
|
||||||
|
|
||||||
|
AnneSubagent -.->|"API Friction Report / UX Audit"| MainAgent
|
||||||
|
AnneSubagent -->|"Branch: feat/anne/*"| RepoWorkspace
|
||||||
|
AnneSubagent -->|"Commit: Author Anne Droid"| RepoWorkspace
|
||||||
|
AnneSubagent -->|"Push: SSH Key id_ed25519_anne_droid"| GiteaForge
|
||||||
|
AnneSubagent -->|"PR Creation: tea CLI"| GiteaForge
|
||||||
|
|
||||||
|
GiteaForge -->|"Code Review & PR Merge"| User
|
||||||
|
```
|
||||||
|
|
||||||
|
### Component Taxonomy & Authority Matrix
|
||||||
|
|
||||||
|
| Domain | Action | Permitted? | Constraints / Execution Rule |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Git Branches** | Create / Checkout | ✅ Yes | Naming strictly constrained to `feat/anne/*`, `fix/anne/*`, `ux/anne/*` |
|
||||||
|
| **Git Commits** | Author commit | ✅ Yes | Conventional Commits; authored as `Anne Droid <anne-droid@roadtotech.me>` |
|
||||||
|
| **Git Remote** | Push | ✅ Yes | Allowed only to own feature branches on remote forge |
|
||||||
|
| **Git PRs** | Open / Update | ✅ Yes | Opened via `tea pr create --login anne-droid` with descriptive summaries |
|
||||||
|
| **Git Governance**| Direct commit to `main` | ❌ No | Strictly forbidden; raises hard constraint failure |
|
||||||
|
| **Git Governance**| Merge PRs | ❌ No | Strictly forbidden; only repository owner merges into `main` |
|
||||||
|
| **Git Safety** | Destructive git commands | ❌ No | Strictly forbidden (`reset --hard`, force-push, `clean -fd`) |
|
||||||
|
| **Code Scope** | Frontend components & CSS | ✅ Yes | React, HTML, CSS, client styling, client unit/integration tests |
|
||||||
|
| **Code Scope** | Backend & Database code | ❌ No | Read-only access to inspect contracts; no unilateral modifications |
|
||||||
|
| **Architecture** | API Feedback | ✅ Yes | Emits advisory "Frontend → Backend Feedback" reports or opens issues |
|
||||||
|
| **Infrastructure** | System / Deploy / NixOS | ❌ No | Strictly forbidden |
|
||||||
|
|
||||||
|
### Git & Forge Authentication Contract
|
||||||
|
|
||||||
|
- **Forge User**: `anne-droid` (ID 2 on `https://gitea.roadtotech.me`).
|
||||||
|
- **SSH Key Pair**: `~/.ssh/id_ed25519_anne_droid` (Public Key ID 3 on Gitea).
|
||||||
|
- **SSH Transport**: Scoped command bypassing global Nix-managed config:
|
||||||
|
```bash
|
||||||
|
GIT_SSH_COMMAND="ssh -F /dev/null -p 2223 -i ~/.ssh/id_ed25519_anne_droid -o IdentitiesOnly=yes"
|
||||||
|
```
|
||||||
|
- **Commit Identity Variables**:
|
||||||
|
```bash
|
||||||
|
GIT_AUTHOR_NAME="Anne Droid"
|
||||||
|
GIT_AUTHOR_EMAIL="anne-droid@roadtotech.me"
|
||||||
|
GIT_COMMITTER_NAME="Anne Droid"
|
||||||
|
GIT_COMMITTER_EMAIL="anne-droid@roadtotech.me"
|
||||||
|
```
|
||||||
|
- **CLI Management**: Authenticated profile in `tea` CLI:
|
||||||
|
```bash
|
||||||
|
tea login add --name anne-droid --url https://gitea.roadtotech.me --token <TOKEN>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Working Rules & Coordination Constraints
|
||||||
|
|
||||||
|
1. **One Owner per Capability**:
|
||||||
|
Anne does not duplicate procedural skills. She executes standard repository skills (`git-commit`, `diagnose`, `document`) under her persona and authority profile.
|
||||||
|
2. **Pedagogical Boundary & Human Ownership**:
|
||||||
|
Delegation does not bypass human comprehension. The human lead reviews diffs and owns PR merge decisions.
|
||||||
|
3. **Communication & Documentation Triage**:
|
||||||
|
Anne rigorously separates persistent knowledge from transient action items to prevent repository and issue bloat:
|
||||||
|
- **Persistent Documentation (`docs/`)**: Architecture, design tokens, and durable contracts that must be read repeatedly across sessions are committed directly to the repo.
|
||||||
|
- **Actionable Forge Issues (`tea issues create`)**: Single-action follow-ups that must be answered once. Filtered strictly to critical triggers: breaking contract/schema changes, security/auth boundaries, or severe client UX/performance degradation.
|
||||||
|
- **In-Line PR Reviews**: Minor, non-breaking design notes or line queries stay in the active PR discussion.
|
||||||
|
- Anne never edits backend files directly and never leaves untracked conversational scratchpads in the repository root.
|
||||||
|
4. **Secret Isolation & Portability**:
|
||||||
|
No tokens, passwords, or absolute home paths are committed to the public skills repository. All persona rules use relative or tilde-expanded paths.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Phased Implementation Roadmap
|
||||||
|
|
||||||
|
| Phase | Status | Deliverables | Verification Gates |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **P0: Forge Identity & Keys** | Completed | User `anne-droid`, SSH key pair, public key upload | `ssh -p 2223 git@gitea.roadtotech.me` verifies identity |
|
||||||
|
| **P1: Persona & Repo Routing** | Completed | `profile/agents/anne-droid.md`, `profile/AGENTS.md`, `install.sh` | `./install.sh check` clean, conventional commit in `main` |
|
||||||
|
| **P2: Subagent Registration** | Completed | Antigravity `anne_droid` subagent definition | `define_subagent` registers successfully |
|
||||||
|
| **P3: CLI Token & PR Automation** | Completed | Gitea access token in `tea` login profile | `tea logins list` shows `anne-droid` authenticated |
|
||||||
|
| **P4: End-to-End Dogfood Run** | Pending | Advisory API audit & delegated branch implementation | Real PR opened on Gitea authored by `anne-droid` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Execution Runbook
|
||||||
|
|
||||||
|
### Step 1: Token Configuration (User-facing)
|
||||||
|
1. In Gitea web interface (`https://gitea.roadtotech.me`), generate an application token for `anne-droid` with `repo` scope.
|
||||||
|
2. Register the token in `tea`:
|
||||||
|
```bash
|
||||||
|
tea login add --name anne-droid --url https://gitea.roadtotech.me --token <TOKEN>
|
||||||
|
```
|
||||||
|
3. Confirm authentication:
|
||||||
|
```bash
|
||||||
|
tea --login anne-droid whoami
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 2: Delegated Feature Implementation (Agent runbook)
|
||||||
|
1. Create and switch to isolated worktree in sibling directory:
|
||||||
|
```bash
|
||||||
|
git worktree add ../<repo>-anne-<task> -b feat/anne/<task>
|
||||||
|
cd ../<repo>-anne-<task>
|
||||||
|
```
|
||||||
|
2. Implement frontend components, styles, and unit tests using `htmx` or `Vite+` (`vp`).
|
||||||
|
3. Visually verify UI in browser (desktop + mobile viewports):
|
||||||
|
```bash
|
||||||
|
google-chrome --headless --disable-gpu --screenshot=desktop.png --window-size=1280,800 <url>
|
||||||
|
google-chrome --headless --disable-gpu --screenshot=mobile.png --window-size=375,812 <url>
|
||||||
|
```
|
||||||
|
4. Commit with Anne's metadata:
|
||||||
|
```bash
|
||||||
|
GIT_AUTHOR_NAME="Anne Droid" \
|
||||||
|
GIT_AUTHOR_EMAIL="anne-droid@roadtotech.me" \
|
||||||
|
GIT_COMMITTER_NAME="Anne Droid" \
|
||||||
|
GIT_COMMITTER_EMAIL="anne-droid@roadtotech.me" \
|
||||||
|
git commit -m "feat(ui): <description>"
|
||||||
|
```
|
||||||
|
5. Push branch to remote:
|
||||||
|
```bash
|
||||||
|
GIT_SSH_COMMAND="ssh -F /dev/null -p 2223 -i ~/.ssh/id_ed25519_anne_droid -o IdentitiesOnly=yes" \
|
||||||
|
git push -u origin feat/anne/<task>
|
||||||
|
```
|
||||||
|
6. Open PR via `tea` and await user review (worktree remains active):
|
||||||
|
```bash
|
||||||
|
tea pr create --login anne-droid --title "feat(ui): <title>" --description "..."
|
||||||
|
```
|
||||||
|
7. Upon PR merge/closure confirmation, teardown worktree:
|
||||||
|
```bash
|
||||||
|
cd <original-repo>
|
||||||
|
git worktree remove ../<repo>-anne-<task>
|
||||||
|
git branch -d feat/anne/<task>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Definition of Done
|
||||||
|
|
||||||
|
- [x] Gitea account `anne-droid` created and verified.
|
||||||
|
- [x] Dedicated SSH key pair generated and registered to Gitea.
|
||||||
|
- [x] SSH connection over port 2223 verified with successful welcome banner.
|
||||||
|
- [x] Persona specification written to `profile/agents/anne-droid.md`.
|
||||||
|
- [x] Global routing table in `profile/AGENTS.md` updated.
|
||||||
|
- [x] `install.sh` updated and symlink verified in `~/.gemini/config/agents/`.
|
||||||
|
- [x] Antigravity subagent `anne_droid` registered.
|
||||||
|
- [x] Gitea API token added to `tea` CLI login configuration.
|
||||||
|
- [ ] First end-to-end pull request created on Gitea authored by Anne Droid.
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: brain
|
||||||
|
tags:
|
||||||
|
- indexing
|
||||||
|
- term-extraction
|
||||||
|
- search
|
||||||
|
- metadata
|
||||||
|
- tooling
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan: Deterministic Term Extraction for Brain Documents
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Replace or augment AI-generated tags with a **cheap, reproducible, auditable term extraction pipeline** that runs at document ingestion time and produces lexical signals optimized for search and relationship discovery.
|
||||||
|
|
||||||
|
This plan is grounded in the feedback agent's revised assessment: **the architecture is correct; the complexity must be earned by demonstrated failure.** We start with the simplest extractor that could possibly work, measure it against the existing corpus, and only escalate when a concrete retrieval failure justifies it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Background & Corpus State
|
||||||
|
|
||||||
|
A pre-plan corpus analysis reveals the current tag situation:
|
||||||
|
|
||||||
|
| Metric | Value |
|
||||||
|
|:---|---:|
|
||||||
|
| Total documents (ex. inbox) | 132 |
|
||||||
|
| Docs with `tags:` field | 94 (71%) |
|
||||||
|
| Docs without any tags | 38 (29%) |
|
||||||
|
| Unique tags across corpus | 149 |
|
||||||
|
| Avg tags per document | 5.8 |
|
||||||
|
| **Singleton tags (appear in only 1 doc)** | **75 (50%)** |
|
||||||
|
| Tags appearing in >50% of all tagged docs | 3 |
|
||||||
|
|
||||||
|
**Key finding: The existing tags have a discriminability problem at both extremes.**
|
||||||
|
|
||||||
|
- `homelab` (65%), `operations` (54%), `architecture` (51%) are so pervasive they are essentially noise — they don't help distinguish *which* homelab document you want.
|
||||||
|
- Meanwhile, 75 of 149 unique tags appear only once, making them nearly useless for cross-document relationships.
|
||||||
|
|
||||||
|
The effective discriminating vocabulary sits in a narrow middle band. The term extraction system targets that band directly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Design Decisions
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **`terms` does not replace `tags`**. They are semantically distinct fields. `tags` are curated, human-assigned classifications. `terms` are machine-extracted retrieval signals. Both can coexist:
|
||||||
|
> ```yaml
|
||||||
|
> tags: [homelab, operations, troubleshooting]
|
||||||
|
> terms: [docker.service, network-online.target, dns, resolv.conf]
|
||||||
|
> ```
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> The feedback agent proposed calling these `terms` or `keywords` rather than `tags` to avoid conflating manually curated classifiers with machine-extracted retrieval signals. This plan follows that recommendation exactly.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **Scope decision**: The extractor runs as a **standalone CLI script** (`scripts/extract-terms.py`). It does not modify documents in place. It outputs JSON to stdout and optionally proposes a frontmatter patch. Integration into a curation hook or docs2site pipeline is left to a future phase once the quality is validated.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **Do you want `terms` to be written into frontmatter of existing documents, or only applied to new inbox documents during curation?**
|
||||||
|
> The recommended path is: output only, inspect manually first, then decide if bulk-patching is warranted.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> **What is the target `K`?** How many terms per document should the extractor emit? The plan defaults to **top 8–12 terms**, but this is configurable.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Proposed Changes
|
||||||
|
|
||||||
|
### Component: `scripts/extract-terms.py`
|
||||||
|
|
||||||
|
A new self-contained Python script that performs Markdown-aware lexical extraction. No dependencies beyond the Python standard library (stdlib regex + collections), making it viable in any Nix devShell without a pip install.
|
||||||
|
|
||||||
|
#### Algorithm
|
||||||
|
|
||||||
|
```
|
||||||
|
Markdown document
|
||||||
|
│
|
||||||
|
├── 1. Frontmatter strip (extract raw body)
|
||||||
|
├── 2. Structural AST token extraction
|
||||||
|
│ ├── H1 title tokens × 5.0
|
||||||
|
│ ├── H2/H3 heading tokens × 3.0
|
||||||
|
│ ├── Inline code `tokens` × 3.0
|
||||||
|
│ ├── Code fence identifiers × 2.0
|
||||||
|
│ └── Body noun tokens × 1.0
|
||||||
|
├── 3. Token normalization
|
||||||
|
│ ├── Lowercase
|
||||||
|
│ ├── Strip punctuation (preserve . and - for identifiers like network-online.target)
|
||||||
|
│ └── Remove stopwords (English + domain-specific generic terms)
|
||||||
|
└── 4. Score aggregation → sort → top K
|
||||||
|
```
|
||||||
|
|
||||||
|
The structural weight formula:
|
||||||
|
|
||||||
|
```
|
||||||
|
score(term) = Σ structural_weight(occurrence_type)
|
||||||
|
+ log(1 + frequency_in_doc)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### [NEW] `scripts/extract-terms.py`
|
||||||
|
|
||||||
|
```python
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Brain Term Extractor
|
||||||
|
Usage:
|
||||||
|
python scripts/extract-terms.py <file.md> # single doc, print JSON
|
||||||
|
python scripts/extract-terms.py --corpus # all docs, print report
|
||||||
|
python scripts/extract-terms.py --bench # compare vs existing tags
|
||||||
|
|
||||||
|
Output (single doc):
|
||||||
|
{
|
||||||
|
"file": "records/journal/...",
|
||||||
|
"terms": ["docker", "dns", "network-online.target", ...]
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re, sys, json, math
|
||||||
|
from collections import Counter, defaultdict
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# ── Configuration ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
BRAIN_ROOT = Path(__file__).parent.parent
|
||||||
|
TOP_K = 10 # terms to emit per document
|
||||||
|
MIN_TERM_LEN = 2 # minimum token character length
|
||||||
|
|
||||||
|
STRUCTURAL_WEIGHTS = {
|
||||||
|
"h1": 5.0,
|
||||||
|
"h2": 3.0,
|
||||||
|
"h3": 3.0,
|
||||||
|
"code_inline": 3.0,
|
||||||
|
"code_fence": 2.0,
|
||||||
|
"emphasis": 2.0,
|
||||||
|
"link_text": 2.0,
|
||||||
|
"body": 1.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Generic terms that are never useful as retrieval signals in this corpus
|
||||||
|
STOPWORDS = {
|
||||||
|
# English function words
|
||||||
|
"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for",
|
||||||
|
"of", "with", "by", "from", "is", "are", "was", "were", "be", "been",
|
||||||
|
"this", "that", "it", "its", "not", "no", "as", "if", "so", "then",
|
||||||
|
"when", "where", "how", "what", "which", "who", "we", "i", "you",
|
||||||
|
# Domain-generic terms (corpus-specific)
|
||||||
|
"homelab", "operations", "architecture", "note", "guide", "notes",
|
||||||
|
"overview", "summary", "example", "configuration", "setup", "service",
|
||||||
|
"file", "step", "section", "see", "also", "use", "using", "run",
|
||||||
|
# Markdown structural artifacts
|
||||||
|
"md", "yaml", "http", "https", "true", "false", "null",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def extract_terms(text: str, top_k: int = TOP_K) -> list[str]:
|
||||||
|
"""Return top_k terms from a Markdown document, deterministically."""
|
||||||
|
# Strip frontmatter
|
||||||
|
body = re.sub(r'^---\n.*?\n---\n?', '', text, flags=re.DOTALL)
|
||||||
|
|
||||||
|
scores: Counter = Counter()
|
||||||
|
|
||||||
|
def add_tokens(fragment: str, weight: float) -> None:
|
||||||
|
"""Tokenize a text fragment, score each token."""
|
||||||
|
# Preserve technical identifiers like network-online.target, pg_dump
|
||||||
|
tokens = re.findall(r'[\w][\w.\-]*[\w]|[\w]{2,}', fragment.lower())
|
||||||
|
for tok in tokens:
|
||||||
|
if len(tok) < MIN_TERM_LEN or tok in STOPWORDS:
|
||||||
|
continue
|
||||||
|
# Skip pure numbers
|
||||||
|
if re.fullmatch(r'\d+', tok):
|
||||||
|
continue
|
||||||
|
scores[tok] += weight
|
||||||
|
|
||||||
|
# ── H1 ──────────────────────────────────────────────────────────────────
|
||||||
|
for m in re.finditer(r'^#\s+(.+)', body, re.MULTILINE):
|
||||||
|
add_tokens(m.group(1), STRUCTURAL_WEIGHTS["h1"])
|
||||||
|
|
||||||
|
# ── H2 ──────────────────────────────────────────────────────────────────
|
||||||
|
for m in re.finditer(r'^##\s+(.+)', body, re.MULTILINE):
|
||||||
|
add_tokens(m.group(1), STRUCTURAL_WEIGHTS["h2"])
|
||||||
|
|
||||||
|
# ── H3 ──────────────────────────────────────────────────────────────────
|
||||||
|
for m in re.finditer(r'^###\s+(.+)', body, re.MULTILINE):
|
||||||
|
add_tokens(m.group(1), STRUCTURAL_WEIGHTS["h3"])
|
||||||
|
|
||||||
|
# ── Inline code `token` ─────────────────────────────────────────────────
|
||||||
|
for m in re.finditer(r'`([^`\n]+)`', body):
|
||||||
|
add_tokens(m.group(1), STRUCTURAL_WEIGHTS["code_inline"])
|
||||||
|
|
||||||
|
# ── Code fence (first identifier per fence) ──────────────────────────────
|
||||||
|
for m in re.finditer(r'```[\w]*\n(.*?)```', body, re.DOTALL):
|
||||||
|
# Extract identifiers from code (first 5 lines)
|
||||||
|
fence_lines = m.group(1).split('\n')[:5]
|
||||||
|
for line in fence_lines:
|
||||||
|
add_tokens(line, STRUCTURAL_WEIGHTS["code_fence"])
|
||||||
|
|
||||||
|
# ── Emphasis **term** and *term* ─────────────────────────────────────────
|
||||||
|
for m in re.finditer(r'\*{1,2}([^*\n]+)\*{1,2}', body):
|
||||||
|
add_tokens(m.group(1), STRUCTURAL_WEIGHTS["emphasis"])
|
||||||
|
|
||||||
|
# ── Link anchor text [text](#) ─────────────────────────────────────────
|
||||||
|
for m in re.finditer(r'\[([^\]]+)\]\([^)]+\)', body):
|
||||||
|
add_tokens(m.group(1), STRUCTURAL_WEIGHTS["link_text"])
|
||||||
|
|
||||||
|
# ── Body prose (remaining text after stripping markup) ───────────────────
|
||||||
|
prose = re.sub(r'`[^`\n]+`', '', body) # strip inline code
|
||||||
|
prose = re.sub(r'```.*?```', '', prose, flags=re.DOTALL) # strip fences
|
||||||
|
prose = re.sub(r'\*{1,2}[^*\n]+\*{1,2}', '', prose) # strip emphasis
|
||||||
|
prose = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', prose) # keep link text
|
||||||
|
prose = re.sub(r'^#{1,6}\s+.+', '', prose, flags=re.MULTILINE) # strip headings
|
||||||
|
add_tokens(prose, STRUCTURAL_WEIGHTS["body"])
|
||||||
|
|
||||||
|
# Add log-frequency boost for terms that appear multiple times in body
|
||||||
|
for term, count in Counter(
|
||||||
|
re.findall(r'[\w][\w.\-]*[\w]|[\w]{2,}', prose.lower())
|
||||||
|
).items():
|
||||||
|
if count > 1 and term in scores:
|
||||||
|
scores[term] += math.log(1 + count) * 0.5
|
||||||
|
|
||||||
|
return [term for term, _ in scores.most_common(top_k)]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_existing_tags(text: str) -> list[str]:
|
||||||
|
m = re.match(r'^---\n(.*?)\n---', text, re.DOTALL)
|
||||||
|
if not m:
|
||||||
|
return []
|
||||||
|
fm = m.group(1)
|
||||||
|
inline = re.search(r'^tags:\s*\[([^\]]+)\]', fm, re.MULTILINE)
|
||||||
|
if inline:
|
||||||
|
return [t.strip().strip('"\'') for t in inline.group(1).split(',')]
|
||||||
|
block = re.search(r'^tags:\s*\n((?:\s*-\s*.+\n?)+)', fm, re.MULTILINE)
|
||||||
|
if block:
|
||||||
|
return [t.strip() for t in re.findall(r'-\s*(.+)', block.group(1))]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_single(path: Path) -> None:
|
||||||
|
text = path.read_text()
|
||||||
|
terms = extract_terms(text)
|
||||||
|
print(json.dumps({"file": str(path.relative_to(BRAIN_ROOT)), "terms": terms}, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_corpus() -> None:
|
||||||
|
"""Run extractor over all committed docs and print a term frequency report."""
|
||||||
|
term_counter: Counter = Counter()
|
||||||
|
doc_count = 0
|
||||||
|
|
||||||
|
for md in sorted(BRAIN_ROOT.rglob("*.md")):
|
||||||
|
if any(x in str(md) for x in ["inbox", ".git", "scripts"]):
|
||||||
|
continue
|
||||||
|
text = md.read_text()
|
||||||
|
terms = extract_terms(text)
|
||||||
|
term_counter.update(terms)
|
||||||
|
doc_count += 1
|
||||||
|
print(f" {md.relative_to(BRAIN_ROOT)}: {terms}", file=sys.stderr)
|
||||||
|
|
||||||
|
print(f"\nCorpus: {doc_count} docs, {len(term_counter)} unique extracted terms\n")
|
||||||
|
print("Top 30 extracted terms:")
|
||||||
|
for term, count in term_counter.most_common(30):
|
||||||
|
print(f" {count:3d} {term}")
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_bench() -> None:
|
||||||
|
"""Compare extracted terms vs existing tags for each document."""
|
||||||
|
results = []
|
||||||
|
for md in sorted(BRAIN_ROOT.rglob("*.md")):
|
||||||
|
if any(x in str(md) for x in ["inbox", ".git", "scripts"]):
|
||||||
|
continue
|
||||||
|
text = md.read_text()
|
||||||
|
existing = parse_existing_tags(text)
|
||||||
|
if not existing:
|
||||||
|
continue
|
||||||
|
extracted = extract_terms(text, top_k=15)
|
||||||
|
overlap = set(existing) & set(extracted)
|
||||||
|
results.append({
|
||||||
|
"file": str(md.relative_to(BRAIN_ROOT)),
|
||||||
|
"existing_tags": existing,
|
||||||
|
"extracted_terms": extracted[:10],
|
||||||
|
"overlap": sorted(overlap),
|
||||||
|
"overlap_pct": len(overlap) / len(existing) * 100 if existing else 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
avg_overlap = sum(r["overlap_pct"] for r in results) / len(results) if results else 0
|
||||||
|
print(f"Benchmark: {len(results)} docs, avg tag overlap: {avg_overlap:.1f}%\n")
|
||||||
|
|
||||||
|
# Show 10 worst-overlap docs (most novel extraction vs tags)
|
||||||
|
results.sort(key=lambda r: r["overlap_pct"])
|
||||||
|
print("== Lowest overlap (most divergent from existing tags) ==")
|
||||||
|
for r in results[:10]:
|
||||||
|
print(f"\n {r['file']}")
|
||||||
|
print(f" Existing tags: {r['existing_tags']}")
|
||||||
|
print(f" Extracted: {r['extracted_terms']}")
|
||||||
|
print(f" Overlap: {r['overlap']} ({r['overlap_pct']:.0f}%)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if "--corpus" in sys.argv:
|
||||||
|
cmd_corpus()
|
||||||
|
elif "--bench" in sys.argv:
|
||||||
|
cmd_bench()
|
||||||
|
elif len(sys.argv) > 1:
|
||||||
|
cmd_single(Path(sys.argv[1]))
|
||||||
|
else:
|
||||||
|
print(__doc__)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Component: Frontmatter Patch Script
|
||||||
|
|
||||||
|
A second utility to apply extracted terms to a single document's frontmatter as a `terms:` field, **preserving all existing fields**. Used manually after inspection.
|
||||||
|
|
||||||
|
#### [NEW] `scripts/patch-terms.py`
|
||||||
|
|
||||||
|
```python
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Patch a Markdown document with extracted terms.
|
||||||
|
Usage:
|
||||||
|
python scripts/patch-terms.py <file.md> [--dry-run]
|
||||||
|
|
||||||
|
Adds or replaces the `terms:` field in the document's YAML frontmatter.
|
||||||
|
Does NOT modify the `tags:` field.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re, sys
|
||||||
|
from pathlib import Path
|
||||||
|
from extract_terms import extract_terms # import sibling
|
||||||
|
|
||||||
|
BRAIN_ROOT = Path(__file__).parent.parent
|
||||||
|
|
||||||
|
def patch_frontmatter(path: Path, terms: list[str], dry_run: bool = False) -> None:
|
||||||
|
text = path.read_text()
|
||||||
|
m = re.match(r'^(---\n)(.*?)(\n---)', text, re.DOTALL)
|
||||||
|
if not m:
|
||||||
|
print(f"No frontmatter found in {path}", file=sys.stderr)
|
||||||
|
return
|
||||||
|
|
||||||
|
prefix, fm_body, suffix = m.group(1), m.group(2), m.group(3)
|
||||||
|
rest = text[m.end():]
|
||||||
|
|
||||||
|
# Remove existing terms field if present
|
||||||
|
fm_body = re.sub(r'^terms:.*?(?=\n\S|\Z)', '', fm_body, flags=re.MULTILINE | re.DOTALL).strip()
|
||||||
|
|
||||||
|
terms_yaml = "terms:\n" + "\n".join(f" - {t}" for t in terms)
|
||||||
|
new_fm = prefix + fm_body + "\n" + terms_yaml + suffix
|
||||||
|
new_text = new_fm + rest
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
print(new_text)
|
||||||
|
else:
|
||||||
|
path.write_text(new_text)
|
||||||
|
print(f"Patched {path.relative_to(BRAIN_ROOT)}: terms = {terms}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print(__doc__)
|
||||||
|
sys.exit(1)
|
||||||
|
path = Path(sys.argv[1])
|
||||||
|
dry_run = "--dry-run" in sys.argv
|
||||||
|
terms = extract_terms(path.read_text())
|
||||||
|
patch_frontmatter(path, terms, dry_run=dry_run)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Component: Stopword Tuning File
|
||||||
|
|
||||||
|
A plaintext file that lets you extend the stopword list per-corpus without editing code. Loaded by the extractor at startup.
|
||||||
|
|
||||||
|
#### [NEW] `scripts/stopwords.txt`
|
||||||
|
|
||||||
|
```text
|
||||||
|
# Brain-specific stopwords — generic terms that add no retrieval value
|
||||||
|
homelab
|
||||||
|
operations
|
||||||
|
architecture
|
||||||
|
overview
|
||||||
|
summary
|
||||||
|
notes
|
||||||
|
guide
|
||||||
|
example
|
||||||
|
setup
|
||||||
|
configuration
|
||||||
|
service
|
||||||
|
section
|
||||||
|
step
|
||||||
|
see
|
||||||
|
also
|
||||||
|
using
|
||||||
|
use
|
||||||
|
run
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification Plan
|
||||||
|
|
||||||
|
### Phase 1 — Corpus Smoke Test (runs immediately after implementation)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run extractor over all docs; inspect term distribution
|
||||||
|
python scripts/extract-terms.py --corpus 2>/dev/null
|
||||||
|
|
||||||
|
# Expected: top extracted terms should look meaningfully different
|
||||||
|
# from the top tags (less dominated by homelab/operations/architecture)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2 — Benchmark Against Existing Tags
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python scripts/extract-terms.py --bench 2>/dev/null
|
||||||
|
```
|
||||||
|
|
||||||
|
**Evaluation questions** (manually inspect results):
|
||||||
|
|
||||||
|
1. Are the top extracted terms obviously descriptive of their document?
|
||||||
|
2. Are highly generic terms (`homelab`, `operations`) suppressed?
|
||||||
|
3. Are technical identifiers preserved (`docker.service`, `network-online.target`)?
|
||||||
|
4. Do the extracted terms for related documents share meaningful overlap?
|
||||||
|
5. Do unrelated documents *not* share too many terms?
|
||||||
|
|
||||||
|
### Phase 3 — Single Document Spot Check
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python scripts/extract-terms.py records/debug/2026-09-18-gitea-github-mirror-dns-resolution-failure.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected output should contain terms like: `docker`, `dns`, `resolv.conf`, `mirror`, `network-online.target`, `gitea` — not generic terms like `operations` or `homelab`.
|
||||||
|
|
||||||
|
### Manual Verification Checklist
|
||||||
|
|
||||||
|
- [ ] Script runs with no pip dependencies
|
||||||
|
- [ ] Same input always produces identical output (determinism)
|
||||||
|
- [ ] Benchmark avg overlap with existing tags is reported
|
||||||
|
- [ ] `--dry-run` on patch script produces valid frontmatter
|
||||||
|
- [ ] Validator (`scripts/validate-brain.py`) still passes after any patches
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phased Evolution (post-validation)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
P1["Phase 1 (now)\nStructural extractor + benchmark"] --> Eval{"Extracted terms\nactually good?"}
|
||||||
|
Eval -- Yes --> P2["Phase 2\nAdd terms to inbox curation workflow"]
|
||||||
|
Eval -- No --> Diag["Diagnose failure mode"]
|
||||||
|
Diag --> Fix1["Improve stopword list"] & Fix2["Add corpus IDF weighting"] & Fix3["Add YAKE phrase extraction"]
|
||||||
|
P2 --> P3["Phase 3\ndocs2site SQLite index consuming terms field"]
|
||||||
|
P3 --> P4["Phase 4\nRelationship graph: doc-to-doc via shared terms"]
|
||||||
|
```
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> YAKE, TF-IDF corpus weighting, and synonym normalization (FlashText) are deferred until Phase 1 benchmark reveals a concrete failure that requires them. Complexity is **earned**, not assumed.
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
* [Second Brain Platform Overview](../../06-projects/brain/README.md)
|
||||||
|
* [Deterministic Tag & Key Term Extraction Methodology](../../04-learning/knowledge/methods/deterministic-tag-extraction.md)
|
||||||
|
* [Second Brain Curation Agent Specification](../../05-agents/profiles/second-brain.md)
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: completed
|
||||||
|
project: brain
|
||||||
|
tags:
|
||||||
|
- brain
|
||||||
|
- skills
|
||||||
|
- investigation
|
||||||
|
- documentation-router
|
||||||
|
- agents
|
||||||
|
---
|
||||||
|
|
||||||
|
# Implementation Plan: Documentation Router & Engineering Investigation Skills Decoupling
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
Based on the architectural reasoning, refactoring lessons, and operational feedback, this plan decouples engineering investigation from documentation generation into two cooperating, independent pipelines:
|
||||||
|
|
||||||
|
1. **`engineering-investigation`**: A purely procedural skill focused on empirical troubleshooting, scientific method progression, and interactive checkpoints. Stops cleanly at verification/recovery without forcing documentation capture.
|
||||||
|
2. **`documentation-router`**: A second-order global documentation evaluation and routing system that inspects session context, determines whether durable knowledge capture is justified, classifies knowledge type (not activity type), enforces anti-overlap invariants, and coordinates modular authoring specifications:
|
||||||
|
- `references/discussion-authoring.md`
|
||||||
|
- `references/adr-authoring.md`
|
||||||
|
- `references/plan-authoring.md`
|
||||||
|
- `references/debug-record-authoring.md`
|
||||||
|
3. **Global Rules Update in `~/.gemini/config/AGENTS.md`**: Separating the investigation rule from the documentation governance rule while maintaining the global inbox capture contract.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. System Topology & Architectural Boundary
|
||||||
|
|
||||||
|
```text
|
||||||
|
Engineering Session
|
||||||
|
│
|
||||||
|
┌─────────────┴─────────────┐
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
Investigation Skill Documentation Router
|
||||||
|
"How do I reason?" "What should be preserved?"
|
||||||
|
(Procedural / Empirical) (Second-Order Knowledge Filter)
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
Verified System State Is an artifact justified?
|
||||||
|
│
|
||||||
|
┌───────────┼───────────┬───────────┐
|
||||||
|
▼ ▼ ▼ ▼
|
||||||
|
Discussion ADR Plan Debug Record
|
||||||
|
(WHY) (WHAT) (HOW) (RCA)
|
||||||
|
```
|
||||||
|
|
||||||
|
### The Cardinal Invariant
|
||||||
|
> **Documentation type is determined by the nature of the knowledge being preserved, not by the activity that produced it.**
|
||||||
|
>
|
||||||
|
> - A debugging session discovering an architectural flaw produces a **Discussion** or an **ADR**, not necessarily a Debug Record.
|
||||||
|
> - A design session that converges on an architectural commitment produces an **ADR**; if it remains exploratory, it stays a **Discussion**.
|
||||||
|
> - An implementation request requiring a new architectural commitment must pause and route to an **ADR** before resuming the **Plan**.
|
||||||
|
> - Routine maintenance or trivial bug fixes produce **NO ARTIFACT**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Refactored Skill: `engineering-investigation`
|
||||||
|
|
||||||
|
**Runtime Location**: `~/.gemini/config/skills/engineering-investigation/SKILL.md`
|
||||||
|
*(Replaces `~/.gemini/config/skills/engineering-investigation-and-knowledge/`)*
|
||||||
|
|
||||||
|
### Key Changes
|
||||||
|
- **Removed**: "Evaluate Durable Learning" decision branch, "Conditional Knowledge Capture Decision" section, "Staging & Epistemic Reporting Protocol" (report markdown template, Brain staging paths, vault curation).
|
||||||
|
- **Retained**:
|
||||||
|
- The 8-stage scientific method lifecycle (Observe $\to$ Hypotheses $\to$ Rationalized Inspection $\to$ Narrow Failure Domain $\to$ Root Cause Determination $\to$ Declarative Remediation $\to$ Local Validation $\to$ Runtime Verification).
|
||||||
|
- Core epistemic principles: preserve reasoning, separate observation from inference, explain diagnostic command rationale, eliminate hindsight bias, proportional depth, zero secret leakage.
|
||||||
|
- The 6-part interactive checkpoint protocol (Current State, Reasoning, Changes, Validation, Next Action, Recovery) with pauses before user-controlled state boundaries.
|
||||||
|
- **Handoff Boundary**: Explicitly stops upon successful runtime verification. Emits findings to session context; if non-obvious learning or architectural questions emerged, hands off to `documentation-router`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. New Skill: `documentation-router`
|
||||||
|
|
||||||
|
**Runtime Location**: `~/.gemini/config/skills/documentation-router/SKILL.md`
|
||||||
|
|
||||||
|
### Responsibilities
|
||||||
|
1. **Gatekeeping (Anti-Markdown Factory)**: Answers *"Did something worth preserving happen?"* Routine maintenance, trivial syntax, standard operations $\to$ **NO ARTIFACT**.
|
||||||
|
2. **Epistemic Classification**: Matches knowledge produced to the appropriate epistemic container:
|
||||||
|
- Exploration, trade-offs, uncertainty, alternatives $\to$ **Discussion**
|
||||||
|
- Formal architectural/design commitment constraining future work $\to$ **ADR**
|
||||||
|
- Ordered implementation steps, contracts, runbooks, verification $\to$ **Plan**
|
||||||
|
- Empirical root-cause post-mortem of broken system $\to$ **Debug Record**
|
||||||
|
3. **Multi-Artifact Decomposition**: Detects when a session produces distinct knowledge products and decomposes them into distinct artifacts rather than blending them.
|
||||||
|
4. **Anti-Overlap Invariants & Canonical Fact Ownership**:
|
||||||
|
- **Optional Flow and Authority**: Discussions may inform ADRs; ADRs may constrain Plans. These describe information flow and authority boundaries, not a mandatory documentation pipeline. A Discussion, ADR, Plan, or Debug Record may exist independently when justified.
|
||||||
|
- **Rule of Epistemic Purpose**: The same fact may appear in multiple documents *only* when it serves a different epistemic purpose.
|
||||||
|
- **Decision Authority**: ADRs are authoritative for decisions; Plans are authoritative for implementation specifications; Discussions preserve historical exploration and have no decision authority.
|
||||||
|
- **Preservation of History**: Superseded documents are kept in lineage folders marked `superseded`, never rewritten into synthetic history.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Cooperating Authoring Modules
|
||||||
|
|
||||||
|
Stored under `~/.gemini/config/skills/documentation-router/references/`:
|
||||||
|
|
||||||
|
### A. `discussion-authoring.md`
|
||||||
|
- **Core Question**: *"What are we trying to understand, and what did we learn while exploring it?"*
|
||||||
|
- **Epistemic Voice**: Narrative, exploratory, retrospective.
|
||||||
|
- **Strict Invariants**:
|
||||||
|
- **Zero "Decision Voice"**: Never uses phrases like `"The Decision: ..."` or imperative directives. Uses `"The exploration ultimately converged on..."` or `"Resulting Direction: ..."`.
|
||||||
|
- **Preserves Uncertainty & Failed Ideas**: Retains rejected alternatives and why they were explored.
|
||||||
|
- **Tempered Tone**: Avoids absolutes.
|
||||||
|
- **Convergence**: Closes by linking forward to resulting ADRs/Plans without duplicating their resolution contracts.
|
||||||
|
|
||||||
|
### B. `adr-authoring.md`
|
||||||
|
- **Core Question**: *"What did we decide, and why?"*
|
||||||
|
- **Structural Basis**: **MADR 4.0 Standard**:
|
||||||
|
`Context and Problem Statement` $\to$ `Decision Drivers` $\to$ `Considered Options` $\to$ `Decision Outcome` $\to$ `Pros and Cons` $\to$ `Consequences` $\to$ `More Information`.
|
||||||
|
- **Strict Invariants**:
|
||||||
|
- **Architectural Commitments Only**: Prohibits implementation procedures, bash runbooks, execution timeouts, and internal schema field names.
|
||||||
|
- **Independent Identity Requirement**: Mandates that deployment configuration, source provenance, and artifact identity must be independently observable, delegating exact schema representations to the Plan.
|
||||||
|
- **Artifact Digest Immutability**: Distinguishes mutable container image tags from content-addressed immutable OCI digests.
|
||||||
|
- **Neutral Systems Language**: Justifies outcomes through trade-offs rather than subjective/evaluative claims.
|
||||||
|
|
||||||
|
### C. `plan-authoring.md`
|
||||||
|
- **Core Question**: *"What exactly are we going to change, in what order, under which constraints, and how will we prove it worked?"*
|
||||||
|
- **Epistemic Role**: **Authoritative Implementation Specification**.
|
||||||
|
- **Strict Invariants**:
|
||||||
|
- **No Disguised ADRs**: Must not silently introduce new architectural commitments. If implementation uncovers an architectural dilemma, it must pause and route to an ADR.
|
||||||
|
- **Pure Constraints, No Re-argument**: Technical decisions are stated as strict implementation invariants, without repeating historical debate.
|
||||||
|
- **Actionable Execution**: Contains system topology, controller authority, resource ownership, schema contracts, security invariants, ordered phases (P0–P5), non-destructive runbooks, rollback procedures, and Definition of Done.
|
||||||
|
|
||||||
|
### D. `debug-record-authoring.md`
|
||||||
|
- **Core Question**: *"What empirically broke, how did the investigation diagnose it, and what was the root cause?"*
|
||||||
|
- **Epistemic Role**: Historical incident post-mortem / RCA record.
|
||||||
|
- **Structure**: System Context $\to$ Problem & Observations $\to$ Diagnostic Inquiries $\to$ Hypothesis Testing $\to$ Root Cause $\to$ Remediation & Validation $\to$ Deployment & Recovery Runbook $\to$ Transferable Learnings.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Global Rules & Canonical Catalog Updates
|
||||||
|
|
||||||
|
1. **Global Configuration (`~/.gemini/config/AGENTS.md`)**:
|
||||||
|
- Separated into three distinct global rules:
|
||||||
|
- `Global Rule: Brain Inbox Capture` (Physical artifact capture mechanism)
|
||||||
|
- `Global Rule: Engineering Investigation` (Procedural scientific method & checkpoints)
|
||||||
|
- `Global Rule: Architectural & Project Documentation` (Epistemic router governance)
|
||||||
|
2. **Canonical Brain Agent Store (`05-agents/`)**:
|
||||||
|
- Documented `05-agents/skills/engineering-investigation.md`.
|
||||||
|
- Documented `05-agents/skills/documentation-router.md`.
|
||||||
|
- Updated catalog index in `05-agents/README.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Verification
|
||||||
|
|
||||||
|
1. Verified skills in `~/.gemini/config/skills/`:
|
||||||
|
- `engineering-investigation/SKILL.md`
|
||||||
|
- `documentation-router/SKILL.md`
|
||||||
|
- `documentation-router/references/` (4 authoring specifications)
|
||||||
|
2. Verified global AGENTS.md rules formatting and syntax.
|
||||||
|
3. Verified Brain vault integrity: `python scripts/validate-brain.py` and `python scripts/test_validator.py`.
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: completed
|
||||||
|
project: brain
|
||||||
|
tags:
|
||||||
|
- records
|
||||||
|
- journal
|
||||||
|
- debug
|
||||||
|
- curation
|
||||||
|
- workflow
|
||||||
|
---
|
||||||
|
|
||||||
|
# Implementation Plan: Incident Debug Records & Daily Journal Workflow Reorganization
|
||||||
|
|
||||||
|
## Goal Description
|
||||||
|
|
||||||
|
Establish a clean separation of concerns across the Second Brain (`~/Brain`) and operational homelab repository (`~/Homelab`):
|
||||||
|
1. **Daily Journals (`records/journal/YYYY-MM-DD.md`)**: Strictly one entry per day serving as a cohesive daily log across all projects, tracking wins, progress, reflections, mistakes/lessons learned, and linking to specialized debug reports.
|
||||||
|
2. **Epistemic Incident Reports (`records/debug/YYYY-MM-DD-<slug>.md`)**: First-class technical artifacts (`type: debug`) capturing scientific root cause analyses (RCAs), protocol investigations, and operational post-mortems following the modular epistemic progression.
|
||||||
|
3. **Inbox Staging Lifecycle**: Operational agents stage incident reports into `~/Brain/inbox/YYYY-MM-DD-<slug>-debug.md` (`type: inbox`). During curation, the report is normalized into `records/debug/`, and the daily journal for that date (`records/journal/YYYY-MM-DD.md`) is updated with a summary and relative link in a dedicated `## Incidents & Debugging` section.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph Operational ["Homelab Operational Session"]
|
||||||
|
Triage["Investigate & Diagnose via SSH"]
|
||||||
|
Fix["Local Declarative Remediation"]
|
||||||
|
Deploy["User Deployment & Recovery"]
|
||||||
|
StageInbox["Stage Incident Report<br/><code>~/Brain/inbox/YYYY-MM-DD-<slug>-debug.md</code><br/>(type: inbox)"]
|
||||||
|
Triage --> Fix --> Deploy --> StageInbox
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Curation ["Second Brain Inbox Curation"]
|
||||||
|
Curate["Curate Inbox Draft"]
|
||||||
|
DebugFile["<code>records/debug/YYYY-MM-DD-<slug>.md</code><br/>(type: debug)"]
|
||||||
|
DailyLog["<code>records/journal/YYYY-MM-DD.md</code><br/>(type: journal)<br/><i>## Incidents & Debugging link</i>"]
|
||||||
|
Curate -->|"Normalize frontmatter & move"| DebugFile
|
||||||
|
Curate -->|"Append / Create daily entry"| DailyLog
|
||||||
|
DailyLog -.->|"Relative link"| DebugFile
|
||||||
|
end
|
||||||
|
|
||||||
|
StageInbox --> Curate
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Canonical Decisions & Invariants
|
||||||
|
|
||||||
|
- **`type: debug`**: First-class citizen in the Brain taxonomy, validated by `scripts/validate-brain.py`.
|
||||||
|
- **Daily Journal Invariant**: `records/journal/` strictly contains one file per date formatted as `YYYY-MM-DD.md`.
|
||||||
|
- **Journal Integration**: A dedicated `## Incidents & Debugging` section in `records/journal/YYYY-MM-DD.md` summarizes root causes and remediation actions with relative links to `../debug/YYYY-MM-DD-<slug>.md`.
|
||||||
|
- **Semantic Commit Type**: `debug` added to repository semantic commit standards (`debug(<scope>): <short description>`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implemented Changes
|
||||||
|
|
||||||
|
### 1. Second Brain Governance & Validator (`~/Brain`)
|
||||||
|
- **First-Class `type: debug`**:
|
||||||
|
- Added `"debug"` to `VALID_TYPES` in [`scripts/validate-brain.py`](../../scripts/validate-brain.py).
|
||||||
|
- Documented `records/debug/` in the semantic contract table and directory definitions of [`AGENTS.md`](../../AGENTS.md).
|
||||||
|
- Added `# debug` frontmatter template and documented the `debug` commit type.
|
||||||
|
- Formalized inbox curation processing rules for `*-debug.md` files.
|
||||||
|
- **Methodology & Agent Profiles**:
|
||||||
|
- Updated [`knowledge/methods/incident-investigation-and-journaling.md`](../../04-learning/knowledge/methods/incident-investigation-and-journaling.md) to reference `records/debug/YYYY-MM-DD-<slug>.md` with `type: debug`.
|
||||||
|
- Updated [`agents/homelab-operations.md`](../../05-agents/profiles/homelab-operations.md) to reflect the operational staging workflow into `inbox/YYYY-MM-DD-<slug>-debug.md`.
|
||||||
|
|
||||||
|
### 2. Homelab Operations Contract (`~/Homelab`)
|
||||||
|
- **Operational Staging**:
|
||||||
|
- Updated workflow diagram and operational steps in `Homelab/AGENTS.md` to stage post-incident RCA artifacts to `~/Brain/inbox/YYYY-MM-DD-<slug>-debug.md`.
|
||||||
|
- Updated Section 4 to "Post-Incident Debugging & Epistemic Reporting" defining staging schema and handoff to Brain curation.
|
||||||
|
|
||||||
|
### 3. Records Migration & Partitioning (`~/Brain/records/`)
|
||||||
|
- **Migrated Incident Reports to `records/debug/` (`type: debug`)**:
|
||||||
|
1. [`records/debug/2026-09-14-server-unexpected-shutdown-rca.md`](../../03-records/debug/2026-09-14-server-unexpected-shutdown-rca.md)
|
||||||
|
2. [`records/debug/2026-09-18-gitea-actions-nix-runner-fix.md`](../../03-records/debug/2026-09-18-gitea-actions-nix-runner-fix.md)
|
||||||
|
3. [`records/debug/2026-09-18-gitea-github-mirror-dns-resolution-failure.md`](../../03-records/debug/2026-09-18-gitea-github-mirror-dns-resolution-failure.md)
|
||||||
|
4. [`records/debug/2026-09-21-gitea-actions-fhs-nix-container-fix.md`](../../03-records/debug/2026-09-21-gitea-actions-fhs-nix-container-fix.md)
|
||||||
|
5. [`records/debug/2026-09-21-gitops-webhook-payload-signature-mismatch.md`](../../03-records/debug/2026-09-21-gitops-webhook-payload-signature-mismatch.md)
|
||||||
|
6. [`records/debug/2026-09-22-diun-socket-proxy-integration-and-stalwart-alerting.md`](../../03-records/debug/2026-09-22-diun-socket-proxy-integration-and-stalwart-alerting.md)
|
||||||
|
|
||||||
|
- **Unified Daily Journals Created in `records/journal/` (`type: journal`, strictly `YYYY-MM-DD.md`)**:
|
||||||
|
1. [`records/journal/2026-09-11.md`](../../03-records/journal/2026-09-11.md) — NixOS appliance cutover and documentation overhaul.
|
||||||
|
2. [`records/journal/2026-09-13.md`](../../03-records/journal/2026-09-13.md) — Milestone P0: GitOps Trust Boundary Implementation deliverables and invariant proofs.
|
||||||
|
3. [`records/journal/2026-09-14.md`](../../03-records/journal/2026-09-14.md) — Milestone P0 closure & P1 transition (Wins) + Server Unexpected Shutdown RCA link.
|
||||||
|
4. [`records/journal/2026-09-15.md`](../../03-records/journal/2026-09-15.md) — Stalwart email infrastructure, deliverability architecture, Brevo relay, and webmail deployment.
|
||||||
|
5. [`records/journal/2026-09-18.md`](../../03-records/journal/2026-09-18.md) — Daily wins + links to Nix runner hang and Docker mirror DNS failure debug records.
|
||||||
|
6. [`records/journal/2026-09-21.md`](../../03-records/journal/2026-09-21.md) — appctl Engine V2 rework & TDD scaffold (Wins) + links to Gitea Actions FHS container fix and Webhook signature mismatch RCAs.
|
||||||
|
7. [`records/journal/2026-09-22.md`](../../03-records/journal/2026-09-22.md) — Diun socket proxy integration and Stalwart alerting (Wins) + link to Diun provider RCA.
|
||||||
|
|
||||||
|
- **Cross-References Updated**:
|
||||||
|
- [`projects/homelab/guides/brain-gitops-deployment-pipeline.md`](../../04-learning/guides/homelab/brain-gitops-deployment-pipeline.md)
|
||||||
|
- [`projects/brain/plans/deterministic-term-extraction.md`](deterministic-term-extraction.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Directory Layout Comparison
|
||||||
|
|
||||||
|
### Before
|
||||||
|
```
|
||||||
|
records/
|
||||||
|
├── debug/ (empty)
|
||||||
|
├── decisions/
|
||||||
|
├── discussions/
|
||||||
|
└── journal/
|
||||||
|
├── 2026-06-25.md
|
||||||
|
├── 2026-06-26.md
|
||||||
|
├── ...
|
||||||
|
├── 2026-09-11-homelab-core-nixos-appliance-cutover.md
|
||||||
|
├── 2026-09-13-homelab-core-p0-gitops-trust-boundary.md
|
||||||
|
├── 2026-09-14-homelab-core-p0-closure-and-p1-transition.md
|
||||||
|
├── 2026-09-14-server-unexpected-shutdown-rca.md
|
||||||
|
├── 2026-09-15-stalwart-email-server-and-webmail-deployment.md
|
||||||
|
├── 2026-09-18-gitea-actions-nix-runner-fix.md
|
||||||
|
├── 2026-09-18-gitea-github-mirror-dns-resolution-failure.md
|
||||||
|
├── 2026-09-21-appctl-engine-v2-rework-and-tdd-scaffold.md
|
||||||
|
├── 2026-09-21-gitea-actions-fhs-nix-container-fix.md
|
||||||
|
├── 2026-09-21-gitops-webhook-payload-signature-mismatch.md
|
||||||
|
└── 2026-09-22-diun-socket-proxy-integration-and-stalwart-alerting.md
|
||||||
|
```
|
||||||
|
|
||||||
|
### After
|
||||||
|
```
|
||||||
|
records/
|
||||||
|
├── debug/ # Epistemic RCAs & postmortems (type: debug)
|
||||||
|
│ ├── 2026-09-14-server-unexpected-shutdown-rca.md
|
||||||
|
│ ├── 2026-09-18-gitea-actions-nix-runner-fix.md
|
||||||
|
│ ├── 2026-09-18-gitea-github-mirror-dns-resolution-failure.md
|
||||||
|
│ ├── 2026-09-21-gitea-actions-fhs-nix-container-fix.md
|
||||||
|
│ ├── 2026-09-21-gitops-webhook-payload-signature-mismatch.md
|
||||||
|
│ └── 2026-09-22-diun-socket-proxy-integration-and-stalwart-alerting.md
|
||||||
|
├── decisions/
|
||||||
|
├── discussions/
|
||||||
|
└── journal/ # Strictly 1 file per day (type: journal)
|
||||||
|
├── 2026-06-25.md
|
||||||
|
├── 2026-06-26.md
|
||||||
|
├── 2026-06-29.md
|
||||||
|
├── 2026-06-30.md
|
||||||
|
├── 2026-07-01.md
|
||||||
|
├── 2026-08-10.md
|
||||||
|
├── 2026-08-16.md
|
||||||
|
├── 2026-09-11.md
|
||||||
|
├── 2026-09-13.md
|
||||||
|
├── 2026-09-14.md
|
||||||
|
├── 2026-09-15.md
|
||||||
|
├── 2026-09-18.md
|
||||||
|
├── 2026-09-21.md
|
||||||
|
└── 2026-09-22.md
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification & Validation
|
||||||
|
|
||||||
|
Execution of `python scripts/validate-brain.py`:
|
||||||
|
```text
|
||||||
|
Checking deprecated directories...
|
||||||
|
✓ Done.
|
||||||
|
|
||||||
|
Checking required root files...
|
||||||
|
✓ Done.
|
||||||
|
|
||||||
|
Checking frontmatter...
|
||||||
|
✓ Done (0 issues).
|
||||||
|
|
||||||
|
Checking relative links...
|
||||||
|
✓ Done (0 broken links).
|
||||||
|
|
||||||
|
Checking markdown code fences...
|
||||||
|
✓ Done (0 issues).
|
||||||
|
|
||||||
|
Checking Mermaid diagrams...
|
||||||
|
✓ Done (0 issues).
|
||||||
|
|
||||||
|
Checking Python code quality (Ruff)...
|
||||||
|
✓ Done (0 lint issues).
|
||||||
|
|
||||||
|
Checking Python type consistency (Pyright)...
|
||||||
|
✓ Done (0 type errors).
|
||||||
|
|
||||||
|
✅ All checks passed. Brain structure is valid.
|
||||||
|
```
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: draft
|
||||||
|
project: brain
|
||||||
|
tags:
|
||||||
|
- journal
|
||||||
|
- retrospective
|
||||||
|
- learning
|
||||||
|
- protocol
|
||||||
|
- skills
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architecture & Protocol Specification: Journal Builder (`/journal`)
|
||||||
|
|
||||||
|
## 1. Problem & Motivation: Why Activity Narration Fails
|
||||||
|
|
||||||
|
In modern software engineering environments accelerated by agentic AI, implementation velocity frequently outpaces human comprehension. When autonomous or semi-autonomous tools handle scaffolding, protocol bindings, test harnesses, and refactoring, code commits enter the repository at a rate that obscures whether the human engineer has internalized the underlying mechanics.
|
||||||
|
|
||||||
|
The prevailing failure mode of engineering logs and retrospectives is **Activity Narration**:
|
||||||
|
* Compiling a chronological list of Git commits or diffs.
|
||||||
|
* Asking an LLM to "summarize today's progress" from Git history.
|
||||||
|
* Generating polished prose describing *what was touched* ("Added OIDC endpoints, configured PKCE, and updated test suite").
|
||||||
|
|
||||||
|
Activity narration suffers from four fatal flaws:
|
||||||
|
|
||||||
|
1. **The Comprehension Illusion**:
|
||||||
|
$$\text{Agent writes code} \neq \text{User understands architecture}$$
|
||||||
|
Generating an automated summary creates the psychological feeling of completed work without verifying whether the engineer can explain *how* the system behaves or *why* specific constraints were chosen.
|
||||||
|
|
||||||
|
2. **Absence of Epistemic Boundaries**:
|
||||||
|
Commit logs record the *terminal state* of code, but completely lose:
|
||||||
|
- Which alternative designs were considered and rejected.
|
||||||
|
- What subtle assumptions proved incorrect during implementation.
|
||||||
|
- What cognitive hurdles or conceptual gaps the engineer encountered.
|
||||||
|
|
||||||
|
3. **Loss of Operational Ownership**:
|
||||||
|
When systems break in production, maintenance requires deep mental models of system failure domains. If an engineer relies on AI to implement changes and AI to narrate what happened, the engineer abdicates mental ownership of the codebase.
|
||||||
|
|
||||||
|
4. **Pollution of the Knowledge Graph**:
|
||||||
|
Mechanical changelogs duplicate information already preserved with higher fidelity in Git history. They clutter the knowledge repository without adding durable intellectual value.
|
||||||
|
|
||||||
|
`/journal` exists to invert this paradigm: **it is not a documentation generator; it is a learning and reflection protocol**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Purpose and Non-Goals
|
||||||
|
|
||||||
|
### Purpose
|
||||||
|
`/journal` is an interactive retrospective protocol that transforms recorded engineering activity into durable knowledge. It engages the engineer in a structured reflective dialogue, requiring them to reconstruct system mechanisms, justify architectural decisions, and expose unverified assumptions before any record is committed to the Brain knowledge graph.
|
||||||
|
|
||||||
|
### Non-Goals
|
||||||
|
* **Not an automated changelog compiler**: It does not take Git commits and unilaterally write a journal entry without interactive human participation.
|
||||||
|
* **Not a daily standup bot**: It does not report status or time metrics for management visibility.
|
||||||
|
* **Not a duplicator of specialized artifacts**: In strict adherence to Brain's **Anti-Overlap Invariant**, `/journal` does not copy full ADR decision narratives (reserved for `03-records/decisions/`), full post-mortems (reserved for `03-records/debug/`), or execution blueprints (reserved for `01-plans/`). It captures the human learning experience and links forward to those artifacts.
|
||||||
|
* **Not an AI monologue**: The agent must never answer its own reflection prompts or generate self-congratulatory praise. The engineer must drive the technical explanations.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Inputs, Evidence Hierarchy & The Unit of Reflection
|
||||||
|
|
||||||
|
### The Lead Question: What is the Unit of Reflection?
|
||||||
|
|
||||||
|
A critical design requirement for `/journal` is establishing the proper granularity for retrospective evaluation.
|
||||||
|
|
||||||
|
```
|
||||||
|
TOO GRANULAR OPTIMAL TOO COARSE
|
||||||
|
┌─────────────────────────┐ ┌─────────────────────────┐ ┌─────────────────────────┐
|
||||||
|
│ Raw Git Commit │ ───▶ │ Meaningful Work Unit │ ◀─── │ Calendar Day │
|
||||||
|
│ (Noisy, typo fixes, │ │ (Coherent architectural │ │ (Arbitrary astronomical│
|
||||||
|
│ checkpoint slices) │ │ transition / milestone)│ │ boundary, cross-repo) │
|
||||||
|
└─────────────────────────┘ └─────────────────────────┘ └─────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **Why a Git Commit is the wrong unit**:
|
||||||
|
Commits in a well-disciplined repository (under Conventional Commits or GitKeeper lineage) are intentionally slice-isolated and atomic. Reflecting commit-by-commit causes cognitive fatigue over trivial changes (e.g., formatting fixes, fixture setup) and obscures the larger architectural movement.
|
||||||
|
|
||||||
|
2. **Why a Calendar Day is the wrong unit**:
|
||||||
|
A calendar day is an arbitrary planetary interval. Significant engineering initiatives often span multiple days, while a single afternoon might involve three unrelated micro-tasks across different projects. Anchoring reflection purely to midnight creates artificial narrative boundaries.
|
||||||
|
|
||||||
|
3. **The Canonical Unit: The Meaningful Work Unit (MWU)**
|
||||||
|
The fundamental unit of reflection is the **Meaningful Work Unit**—a bounded architectural transition, capability milestone, or diagnostic resolution that alters system behavior or design invariants.
|
||||||
|
|
||||||
|
#### Heuristics for Bounding a Meaningful Work Unit:
|
||||||
|
An engineering session or range of commits is grouped into a single Work Unit when it satisfies at least one of these boundary conditions:
|
||||||
|
* **Contract/Invariant Transition**: A change that establishes, replaces, or deprecates a system boundary (e.g., *“Decouple backend admin routes from legacy `Remote-User` header to FastAPI group dependency injection”*).
|
||||||
|
* **Verifiable Capability Milestone**: A discrete set of commits accompanied by an acceptance gate, integration suite, or green test pass (e.g., *“Complete OIDC PKCE authorization code exchange and cryptographic JWKS token verification”*).
|
||||||
|
* **Plan or Roadmap Milestone**: Completion or significant progress on a defined phase from an active plan (`01-plans/<project>/...`).
|
||||||
|
* **Root-Cause Resolution**: The complete arc of diagnosing an anomaly, proving the root cause, and deploying declarative remediation (linking to a `03-records/debug/` record).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Evidence Hierarchy
|
||||||
|
|
||||||
|
To ground reflection in empirical reality rather than vague recollection, `/journal` evaluates evidence across four strict tiers:
|
||||||
|
|
||||||
|
| Tier | Category | Sources | Semantic Role |
|
||||||
|
| :---: | :--- | :--- | :--- |
|
||||||
|
| **Tier 1** | **Ground Truth (Repository State)** | Working tree diffs, Git commit history, test suites (`pytest`, `playwright`), type checks (`pyright`), compiler output. | Immutable physical record of code transitions and verification gates. |
|
||||||
|
| **Tier 2** | **Machine Provenance** | `00-inbox/commit-log.csv`, CI/CD build runs, agent execution transcripts. | Unbroken audit trail connecting commits, authors, and task contexts. |
|
||||||
|
| **Tier 3** | **Conceptual Artifacts** | Active plans (`01-plans/`), open discussions (`02-discussions/`), ADRs (`03-records/decisions/`). | The documented intent, constraints, and trade-offs that guided the work. |
|
||||||
|
| **Tier 4** | **Human Reconstruction** | Interactive dialogue responses, mental models, explanations of mechanisms. | **The primary focus of `/journal`**: proving understanding and surfacing gaps. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Retrospective Session Lifecycle (The State Machine)
|
||||||
|
|
||||||
|
The retrospective session moves through seven deterministic epistemic states:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
S0["State 0: Boundary Establishment\n(Select scope: project, time window, or commit boundary)"] --> S1["State 1: Activity Intake & Evidence Ingestion\n(Ingest commit records, git tree transitions, active plans)"]
|
||||||
|
S1 --> S2["State 2: Work Unit Synthesis\n(Cluster transitions into candidate Meaningful Work Units)"]
|
||||||
|
S2 --> S3["State 3: User Boundary Confirmation\n(User confirms, splits, or merges Work Unit boundaries)"]
|
||||||
|
S3 --> S4["State 4: Socratic Knowledge Probe\n(Adaptive L1-L5 inquiry into mechanism & trade-offs)"]
|
||||||
|
S4 -->|Evidence-grounded recall| S5["State 5: Gap Isolation & Epistemic Evaluation\n(Durable lessons extracted vs. active learning edges cataloged)"]
|
||||||
|
S5 --> S6["State 6: Journal Synthesis & Human Approval\n(Draft and review 03-records/journal/YYYY-MM-DD.md)"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Detailed State Transitions
|
||||||
|
|
||||||
|
1. **State 0: Boundary Establishment**:
|
||||||
|
- The retrospective scope is defined (e.g. current calendar interval, specific project, or milestone boundary).
|
||||||
|
- Default: Unjournaled activity recorded in the repository commit ledger and working trees.
|
||||||
|
|
||||||
|
2. **State 1: Activity Intake & Evidence Ingestion**:
|
||||||
|
- The agent reads immutable evidence from the repository commit ledger and inspects Git history across target workspaces.
|
||||||
|
- Cross-references modified codebases with active plans in `01-plans/`, open discussions in `02-discussions/`, and ADRs.
|
||||||
|
|
||||||
|
3. **State 2 & 3: Work Unit Synthesis & Boundary Confirmation**:
|
||||||
|
- Commits and file transitions are clustered into candidate Meaningful Work Units.
|
||||||
|
- The agent presents the proposed clusters to the user before probing begins:
|
||||||
|
> *"I observe 12 commits spanning two distinct initiatives today: (1) OIDC PKCE client integration in BDInvite, and (2) dynamic Wi-Fi firewall scripts in NixOS. Shall we reflect on these as two separate work units?"*
|
||||||
|
- The user confirms, splits, merges, or adjusts the boundaries.
|
||||||
|
|
||||||
|
4. **State 4: Socratic Knowledge Probe**:
|
||||||
|
- For each confirmed Work Unit, the agent initiates interactive inquiry following the Learning Assessment Model (Section 5).
|
||||||
|
- Probing focuses on data flow, control flow, failure modes, and architectural trade-offs.
|
||||||
|
|
||||||
|
5. **State 5: Gap Isolation & Epistemic Evaluation**:
|
||||||
|
- The agent evaluates whether the user's explanations are consistent with physical repository evidence.
|
||||||
|
- Verified mental models are translated into durable engineering lessons.
|
||||||
|
- Unresolved questions, misconceptions, or areas of admitted uncertainty are isolated as active learning edges.
|
||||||
|
|
||||||
|
6. **State 6: Journal Synthesis & Human Approval**:
|
||||||
|
- The agent drafts the journal entry adhering to the Semantic Slot Contract (Section 6).
|
||||||
|
- The draft is presented to the user for collaborative review, critique, and sign-off.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Learning Assessment Model
|
||||||
|
|
||||||
|
The heart of the `/journal` interaction is the Socratic Inquiry protocol. The agent does not test trivia; it tests **systems understanding**.
|
||||||
|
|
||||||
|
### The L1–L5 Inquiry Hierarchy
|
||||||
|
|
||||||
|
```
|
||||||
|
Level 5: Transfer ──▶ "How would this behave if we scaled to multiple nodes?"
|
||||||
|
Level 4: Consequence ──▶ "What breaks if this dependency or edge condition fails?"
|
||||||
|
Level 3: Rationale ──▶ "Why did we choose this design over the alternative?"
|
||||||
|
Level 2: Mechanism ──▶ "How does data and control actually flow through this path?"
|
||||||
|
Level 1: Recall ──▶ "What changed in the system contract?"
|
||||||
|
```
|
||||||
|
|
||||||
|
| Level | Dimension | Question Pattern | Diagnostic Purpose |
|
||||||
|
| :---: | :--- | :--- | :--- |
|
||||||
|
| **L1** | **Recall** | *"What was the key boundary change introduced in this work unit?"* | Verifies basic awareness of the scope of work. |
|
||||||
|
| **L2** | **Mechanism** | *"How does the session cookie rotation prevent fixation attacks during OIDC callback?"* | Verifies concrete understanding of internal system mechanics. |
|
||||||
|
| **L3** | **Rationale** | *"What trade-off led us to keep session storage in-memory rather than issuing signed client-side JWTs?"* | Evaluates architectural decision-making and constraint recognition. |
|
||||||
|
| **L4** | **Consequence** | *"What happens to an active client if the reverse proxy fails to strip the legacy `Remote-User` header?"* | Tests defensive boundary analysis and failure mode reasoning. |
|
||||||
|
| **L5** | **Transfer** | *"If we needed to support CLI-based API tokens alongside browser SSO in this setup, what would change in our port interface?"* | Verifies generalized architectural mastery applicable to new problems. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Epistemic Validation Ladder: Working Mental Model vs. "Mastery"
|
||||||
|
|
||||||
|
A single retrospective session cannot establish permanent mastery. Probing verifies whether the engineer holds a **demonstrated working mental model** consistent with physical repository evidence.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Observed
|
||||||
|
│ (Engineer sees code/test output)
|
||||||
|
▼
|
||||||
|
Explained
|
||||||
|
│ (Engineer articulates control/data flow in own words)
|
||||||
|
▼
|
||||||
|
Consistent with Evidence
|
||||||
|
│ (Explanation matches actual diffs, logs, and assertions)
|
||||||
|
▼
|
||||||
|
Generalized
|
||||||
|
│ (Engineer derives the underlying architectural principle)
|
||||||
|
▼
|
||||||
|
Recorded as Lesson
|
||||||
|
[True Mastery is reserved for repeated transfer across sessions/practice]
|
||||||
|
```
|
||||||
|
|
||||||
|
* **Working Mental Model**: The user can trace mechanics, justify constraints, and predict edge failures accurately.
|
||||||
|
* **Persistent Mastery**: Reserved for repeated demonstrations across distinct projects or deliberate algorithmic/architectural drills (`04-learning/practice/`).
|
||||||
|
* **Preserving Learning Edges**: If an explanation falters, the agent avoids manufactured praise or superficial agreement. The boundary of current understanding is explicitly captured.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Failure and Redirection Protocol
|
||||||
|
|
||||||
|
When a user provides a superficial, hand-waving, or incorrect explanation during a probe:
|
||||||
|
|
||||||
|
```
|
||||||
|
User provides incorrect or superficial answer
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ STRICT INTERVENTION GUARDRAILS: │
|
||||||
|
│ - NEVER say "That's close enough!" │
|
||||||
|
│ - NEVER complete the answer for them │
|
||||||
|
│ - NEVER write textbook explanations │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Direct user to Tier 1 Ground Truth (Diff / Test / Doc)
|
||||||
|
"Inspect backend/tests/test_session.py line 42:
|
||||||
|
what does the assertion assert pre_id != post_id check?"
|
||||||
|
│
|
||||||
|
┌──────────────┴──────────────┐
|
||||||
|
▼ ▼
|
||||||
|
User resolves gap User remains stuck
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
Codify in journal: Codify in journal:
|
||||||
|
"Mistakes & Lessons Learned" "Still Struggling With / Gaps"
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **No Rubber-Stamping**: The agent is strictly prohibited from accepting hand-wavy buzzwords (e.g., "We added security headers to make it secure").
|
||||||
|
2. **Ground-Truth Redirection**: The agent responds by citing specific lines of code, failing test assertions, or architecture diagrams, prompting the user to observe the physical mechanics:
|
||||||
|
> *"Notice in `backend/app/auth/oidc.py` that `validate_token` takes the JWKS client. What specific check prevents an attacker from signing a token with their own private key?"*
|
||||||
|
3. **Explicit Preservation of Gaps**: If the user cannot resolve the question or prefers not to spend immediate time investigating, the agent **does not cover up the ignorance**. It records it cleanly under `### Unresolved Questions & Learning Gaps`. Honesty in the knowledge graph is paramount.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Journal Output Semantic Contract
|
||||||
|
|
||||||
|
Every journal entry created by `/journal` is stored at `03-records/journal/YYYY-MM-DD.md`. To maintain durability without enforcing an overly brittle typographical template, entries must satisfy a **Semantic Slot Contract**.
|
||||||
|
|
||||||
|
### Semantic Mapping of the Work Unit
|
||||||
|
|
||||||
|
The journal's sections directly reflect the epistemic dimensions of each confirmed Work Unit:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Meaningful Work Unit (MWU)
|
||||||
|
│
|
||||||
|
├── What happened? ──▶ ## Wins (Capabilities & Invariants)
|
||||||
|
│
|
||||||
|
├── What went wrong or surprised? ──▶ ## Mistakes and Discoveries
|
||||||
|
│
|
||||||
|
├── What did I actually understand? ──▶ ## Lessons Learned (Working Mental Models)
|
||||||
|
│
|
||||||
|
├── What don't I understand yet? ──▶ ## Questions & Learning Edges (Active Gaps)
|
||||||
|
│
|
||||||
|
├── What artifacts were touched? ──▶ ## Planning & Specifications (Cross-links)
|
||||||
|
│
|
||||||
|
└── What should happen next? ──▶ ## Reflection & Next Actions (Forward Intent)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontmatter Specification
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
type: journal
|
||||||
|
project: optional-primary-project # e.g. bdinvite, homelab, brain
|
||||||
|
date: YYYY-MM-DD
|
||||||
|
tags:
|
||||||
|
- list
|
||||||
|
- of
|
||||||
|
- relevant
|
||||||
|
- topics
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
### Required Semantic Slots
|
||||||
|
|
||||||
|
1. **Title**:
|
||||||
|
`# Daily Journal: YYYY-MM-DD`
|
||||||
|
|
||||||
|
2. **Accomplishments & Meaningful Work Units (`## Wins`)**:
|
||||||
|
- Subdivided by Project or Primary Initiative (`### <Project / Initiative Name>`).
|
||||||
|
- Bulleted summary describing verified capabilities delivered, architectural milestones achieved, and key invariant transitions.
|
||||||
|
- Markdown links to relevant code repositories, forge commits, or project entrypoints (`06-projects/<project>/README.md`).
|
||||||
|
|
||||||
|
3. **Mistakes, Discoveries & Technical Lessons (`## Mistakes and Lessons Learned`)**:
|
||||||
|
- Concrete incidents, debugging discoveries, or design fallacies exposed during the session.
|
||||||
|
- Each entry must articulate:
|
||||||
|
- **The Initial Misconception / Failure Mode**: What was assumed or what broke.
|
||||||
|
- **The Discovered Reality**: What the ground truth actually demonstrated.
|
||||||
|
- **The Durable Takeaway**: The generalizable rule or heuristic to carry forward.
|
||||||
|
|
||||||
|
4. **Active Gaps & Open Inquiries (`## Questions & Learning Edges`)**:
|
||||||
|
- Unresolved architectural questions, concepts requiring further deliberate practice, or areas where the user's mental model was incomplete.
|
||||||
|
- Pointers to candidate practice drills (`04-learning/practice/`) or reading.
|
||||||
|
|
||||||
|
5. **Associated Knowledge & Artifact References (`## Planning & Specifications`)**:
|
||||||
|
- Cross-references to all Brain artifacts created or informed by the work:
|
||||||
|
- Plans: `01-plans/...`
|
||||||
|
- Discussions: `02-discussions/...`
|
||||||
|
- Decisions: `03-records/decisions/...`
|
||||||
|
- Debug Records: `03-records/debug/...`
|
||||||
|
- Guides & SOPs: `04-learning/guides/...`
|
||||||
|
- *Invariant*: Summarize the relationship to the artifact in 1–2 lines; do not reproduce the artifact's body.
|
||||||
|
|
||||||
|
6. **Synthesis & Strategic Outlook (`## Reflection & Next Actions`)**:
|
||||||
|
- High-level perspective on engineering velocity, collaboration dynamics (e.g. human-AI pairing observations), and cognitive load.
|
||||||
|
- Immediate primary and secondary objectives for the subsequent session.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Initial Validation
|
||||||
|
|
||||||
|
Before packaging the protocol as `journal-builder/SKILL.md`, it will be executed manually against the Graphify SSO Benchmark Experiment.
|
||||||
|
|
||||||
|
The purpose is not to establish a formal test suite, but to expose obvious protocol defects while the design is still inexpensive to change.
|
||||||
|
|
||||||
|
The session should be evaluated qualitatively:
|
||||||
|
* Did the Meaningful Work Unit boundaries make sense?
|
||||||
|
* Did the questions expose actual understanding rather than test trivia?
|
||||||
|
* Did the protocol preserve genuine learning gaps?
|
||||||
|
* Did the resulting journal contain information that would not have existed in a conventional activity summary?
|
||||||
|
* Was the interaction cost justified by the resulting record?
|
||||||
|
|
||||||
|
Any substantive problems discovered during this run should be incorporated into this specification before final skill implementation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Implementation Notes & Invocation Interface
|
||||||
|
|
||||||
|
The following details describe how the abstract protocol maps to concrete tools and interfaces in future automated skill packaging, without constraining the protocol itself:
|
||||||
|
|
||||||
|
* **Invocation CLI Interface**:
|
||||||
|
- `/journal` — Defaults to unjournaled commits for today.
|
||||||
|
- `/journal --since <date>` — Scans backward to a specified date boundary.
|
||||||
|
- `/journal --project <name>` — Scopes evidence ingestion to a single project hub.
|
||||||
|
- `/journal --commits <range>` — Evaluates an explicit Git SHA range.
|
||||||
|
* **Commit Ledger Integration**:
|
||||||
|
- Consumes `00-inbox/commit-log.csv` as an audit trail of verified commits.
|
||||||
|
- Does not replace Git commit history; uses the ledger as an ingestion index.
|
||||||
|
* **Git Commit Delegation**:
|
||||||
|
- When the final journal document is reviewed and approved by the user, the agent invokes the `git-commit` skill to package the change as an atomic Conventional Commit (`journal: record daily log for YYYY-MM-DD`).
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: brain
|
||||||
|
tags:
|
||||||
|
- learning
|
||||||
|
- skills
|
||||||
|
- roadmap
|
||||||
|
- implementation
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan: Scaffolded Learning Contracts Across Engineering Skills
|
||||||
|
|
||||||
|
> **Discussion Reference**: [`02-discussions/brain/learning-centered-engineering-workflow.md`](../../02-discussions/brain/learning-centered-engineering-workflow.md)
|
||||||
|
>
|
||||||
|
> **Core Objective**: Transition operational agent skills from "AI writes it" to "AI scaffolds, learner writes it", enforcing the learning contract across everyday engineering tasks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Reality Check & Skill Inventory
|
||||||
|
|
||||||
|
Mapping the theoretical redesign to actual skills in [`skills`](https://github.com/kiskaadee/skills):
|
||||||
|
|
||||||
|
| Conceptual Capability | Actual Skill | Current State vs. Learning Mode |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Engineering Tutor** | `practice` | Hint ladder implemented (question $\to$ pointer $\to$ explanation $\to$ demo); learner attempts first. |
|
||||||
|
| **Troubleshooting** | `diagnose` | Evidence-first investigation; working-tree safety stops. |
|
||||||
|
| **Git Commits** | `git-commit` | Has a `/practice` branch, but still auto-drafts commit messages. Needs author mode. |
|
||||||
|
| **Documentation** | `document` | Determines document type and drafts it. Needs learner core-sentence prompt. |
|
||||||
|
| **Journaling** | `journal-builder` | Produces polished narrative. Needs scaffolding mode with diagnostic blanks. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Phased Implementation Roadmap
|
||||||
|
|
||||||
|
### Phase 1: Minimal Learning Contract (`learning-contract.md`)
|
||||||
|
**Status**: ✅ **Completed**
|
||||||
|
- Defined binding rules in `profile/learning-contract.md`:
|
||||||
|
- *Write rule*: In learning mode, agent provides facts and questions; learner writes reasoning.
|
||||||
|
- *Assistance levels*: `independent`, `hints`, `substantial`, `shown-solution`.
|
||||||
|
- *Evidence $\neq$ assessment*: Passing tests or commits are evidence, not claims of competence.
|
||||||
|
- *Mode toggle*: Explicit `delivery` vs `learning` mode per session.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 2: Skill Scaffolding Experiments
|
||||||
|
|
||||||
|
Pick candidate skills to enforce the contract:
|
||||||
|
- **Option A: `git-commit` author mode**: Agent lists slices, changed behavior, tests present/missing, and asks 1–2 diagnostic questions. Learner writes the commit message; agent validates accuracy and scope against the diff.
|
||||||
|
- **Option B: `journal-builder` scaffold mode**: Builds a factual skeleton from `00-inbox/commit-log.csv` plus 3–5 targeted questions with blanks for learner answers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 3: Practice Records & Delayed Retrieval
|
||||||
|
|
||||||
|
- Add `assistance:` and `revisit_after:` (target date) metadata to practice drill records.
|
||||||
|
- Surface due revisits manually during `practice` or weekly review.
|
||||||
|
- Revisits require **recall before reveal**: answer without opening the previous record, then compare.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 4: Two-Week Dogfood Evaluation
|
||||||
|
|
||||||
|
Test in real work (project commits, course modules, LeetCode drills) and evaluate:
|
||||||
|
1. Did the learner actually write the reasoning, or rubber-stamp?
|
||||||
|
2. Were questions anchored in the learner's actual work rather than generic quizzes?
|
||||||
|
3. On revisit, did recall succeed without viewing the answer?
|
||||||
|
4. Cut any steps that feel like bureaucratic drag.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 5 (Gated): Event Store & Service Integration
|
||||||
|
|
||||||
|
**Gate**: Proceed only if Phase 4 proves a concrete query need that filesystem files cannot answer (e.g. tracking concepts practiced with hints that were never retrieved independently).
|
||||||
|
- If triggered, implement as an isolated learning project in `~/Projects/tests/` (PostgreSQL with `FOR UPDATE SKIP LOCKED` and append-only event logging).
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: completed
|
||||||
|
project: brain
|
||||||
|
tags:
|
||||||
|
- taxonomy
|
||||||
|
- migration
|
||||||
|
- governance
|
||||||
|
- validator
|
||||||
|
- agents
|
||||||
|
---
|
||||||
|
|
||||||
|
# Brain Taxonomy & Lifecycle Migration Plan
|
||||||
|
|
||||||
|
## 1. Executive Summary & Intent
|
||||||
|
|
||||||
|
This document records the completed execution plan for migrating the **Second Brain** knowledge repository (`~/Brain`) from an organically grown, technology-siloed folder structure into a structured, numbered lifecycle taxonomy (`00-inbox/` through `06-projects/`).
|
||||||
|
|
||||||
|
The primary intent was not merely cosmetic re-organization or directory renaming; it was to establish an **epistemic lifecycle architecture** enforced by automated pre-commit validation and to synchronize all distributed agent contracts operating against the Brain across the workstation.
|
||||||
|
|
||||||
|
The conceptual rationale and trade-offs that motivated this architecture are recorded in the companion architectural discussion: [Brain Epistemic Lifecycle Taxonomy](../../02-discussions/brain/taxonomy-and-lifecycle-architecture.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Target Taxonomy & Architectural Principles
|
||||||
|
|
||||||
|
The repository is partitioned into seven numbered lifecycle directories where the directory prefix encodes the document's epistemic role in the engineering lifecycle, frontmatter encodes document state and context, and relative Markdown links encode graph relationships.
|
||||||
|
|
||||||
|
| Directory | Semantic Role | Structural Contract (`DirectoryContract`) | Expected Document Type |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `00-inbox/` | **Capture** | `allow_unclassified=True`, exempt from link and frontmatter validation | *Unclassified / Ephemeral* |
|
||||||
|
| `01-plans/` | **Intent** | `max_depth=3` (allows project subsystems: `<project>/[subsystem/]<slug>.md`) | `type: plan` |
|
||||||
|
| `02-discussions/` | **Exploration** | `max_depth=2` (`<project>/<slug>.md`) | `type: discussion` |
|
||||||
|
| `03-records/` | **History** | Sub-contracted: `journal/` (`YYYY-MM-DD.md`), `debug/` (`YYYY-MM-DD-<slug>.md`), `decisions/` (`<slug>.md`) | `type: journal \| debug \| decision` |
|
||||||
|
| `04-learning/` | **Understanding** | Sub-contracted: `knowledge/` (`concepts/`, `technologies/`, `methods/`), `guides/` (`<project>/<slug>.md`), `practice/` (`LeetCode/`) | `type: knowledge \| guide \| practice` |
|
||||||
|
| `05-agents/` | **Machine Context** | Sub-contracted: `profiles/` (`<slug>.md`), `skills/` (`<slug>.md`) | `type: agent` |
|
||||||
|
| `06-projects/` | **System Hubs** | `max_depth=2`, `require_filename="README.md"` (navigation/index nodes only) | `type: project` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Migration Safety Model & Invariants
|
||||||
|
|
||||||
|
To guarantee zero data loss, broken links, or architectural regressions across 188 tracked files, the migration was governed by eight strict invariants:
|
||||||
|
|
||||||
|
1. **Total Source Coverage**: Every version-controlled file in the pre-migration repository must appear exactly once as a `source` in [`scripts/migration_manifest.json`](../../scripts/migration_manifest.json).
|
||||||
|
2. **Destination Uniqueness**: No two distinct sources may map to the same `destination` path (collision-free guarantee).
|
||||||
|
3. **Source Pre-existence**: Every declared `source` path must exist on disk prior to migration execution.
|
||||||
|
4. **Target Clean Slate**: No declared `destination` path may pre-exist on disk prior to migration unless it is a non-moving root file.
|
||||||
|
5. **Type Compatibility**: The document frontmatter `type` must match the declared semantic role of the target directory.
|
||||||
|
6. **Contract Satisfaction**: All target paths must satisfy the structural constraints of `DirectoryContract` (nesting depth, filename rules, and required filenames).
|
||||||
|
7. **Complete Deprecation Elimination**: Post-migration, no deprecated legacy top-level or nested directories may remain in the working tree.
|
||||||
|
8. **Link Graph Resolution**: Every intra-vault relative Markdown link must resolve cleanly to a valid target file after path rewriting.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Execution Phases: Planned vs. Executed
|
||||||
|
|
||||||
|
The migration was planned and executed in five deterministic phases:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
P1["Phase 1: Contracts & Test Suite"] --> P2["Phase 2: Manifest Git Moves"]
|
||||||
|
P2 --> P3["Phase 3: Link Graph Rewriting"]
|
||||||
|
P3 --> P4["Phase 4: Root Governance Updates"]
|
||||||
|
P4 --> P5["Phase 5: Distributed Integration Sync"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 1: Structural Contracts & Validator Refactoring
|
||||||
|
* **Planned**: Refactor `scripts/validate-brain.py` to replace loose path checking with declarative `DirectoryContract` tuples and write a dedicated regression test suite.
|
||||||
|
* **Executed**:
|
||||||
|
- Implemented `DirectoryContract` in `scripts/validate-brain.py` with typed fields: `prefix`, `expected_type`, `max_depth`, `require_filename`, `filename_regex`, and `allow_unclassified`.
|
||||||
|
- Added repository-relative sets `DEPRECATED_ROOT_DIRS` and `DEPRECATED_NESTED_PATHS` to prevent partial substring false positives.
|
||||||
|
- Implemented `scripts/test_validator.py` covering 10 distinct failure and success scenarios (contract satisfaction, depth violations, filename regex matching, deprecated directory detection, and code-fence scanning).
|
||||||
|
* **Evidence**: Commit `8a59b09`.
|
||||||
|
|
||||||
|
### Phase 2: Manifest Generation & Tree Relocation
|
||||||
|
* **Planned**: Generate a complete, machine-readable migration manifest and execute file relocations using `git mv` to preserve git file history.
|
||||||
|
* **Executed**:
|
||||||
|
- Authored [`scripts/migration_manifest.json`](../../scripts/migration_manifest.json) containing 188 explicit `source` $\to$ `destination` mappings with epistemic rationales.
|
||||||
|
- Executed atomic `git mv` relocations across all files without leaving orphaned artifacts.
|
||||||
|
* **Evidence**: Commit `8a59b09` (188 files moved, zero added/deleted content).
|
||||||
|
|
||||||
|
### Phase 3: Relative Link Graph Rewriting
|
||||||
|
* **Planned**: Programmatically rewrite intra-vault relative Markdown links using the manifest mapping table so that all links resolve correctly under new relative depths.
|
||||||
|
* **Executed**:
|
||||||
|
- Iterated through all markdown files and rewrote 199 relative link occurrences across 49 markdown files.
|
||||||
|
- Verified that cross-directory navigation paths (e.g. from `03-records/journal/` to `01-plans/homelab/`) correctly calculated directory depth changes (`../../` instead of `../`).
|
||||||
|
* **Evidence**: Commit `4e0dfe0`.
|
||||||
|
|
||||||
|
### Phase 4: Root Governance & Catalog Updates
|
||||||
|
* **Planned**: Update repository governance documents to reflect the 00-06 numbered lifecycle taxonomy.
|
||||||
|
* **Executed**:
|
||||||
|
- Rewrote root [AGENTS.md](../../AGENTS.md) and [README.md](../../README.md) to define directory contracts, frontmatter schemas, link rules, semantic commit conventions, and curation protocols.
|
||||||
|
- Updated [05-agents/README.md](../../05-agents/README.md) to catalog profiles and skills.
|
||||||
|
* **Evidence**: Commit `798c953`.
|
||||||
|
|
||||||
|
### Phase 5: Distributed Integration Surface Synchronization
|
||||||
|
* **Planned**: Ensure external tools and localized agent configurations across the laptop reflect the new structure.
|
||||||
|
* **Executed**:
|
||||||
|
- **Gemini Config**: Updated global capture rule in `~/.gemini/config/AGENTS.md` and capture script `~/.gemini/config/scripts/inbox-capture.sh` (`INBOX_DIR="${HOME}/Brain/00-inbox"`).
|
||||||
|
- **Workstation Docs**: Updated reference guide in `~/Config/docs/reference/antigravity.md`.
|
||||||
|
- **Homelab Operations**: Updated `/home/kiskaadee/Homelab/AGENTS.md` (workflow mermaid diagram, staging path, `03-records/debug/`, `03-records/journal/`, and learning links).
|
||||||
|
- **Homelab Core**: Updated `/home/kiskaadee/Homelab/Core/AGENTS.md` (Section *## Brain Vault*).
|
||||||
|
- **Appctl Refactor Worktree**: Updated `/home/kiskaadee/Projects/active/appctl-refactor/AGENTS.md`.
|
||||||
|
- **Internal Profiles**: Updated [homelab-core.md](../../05-agents/profiles/homelab-core.md), [homelab-operations.md](../../05-agents/profiles/homelab-operations.md), and [second-brain.md](../../05-agents/profiles/second-brain.md).
|
||||||
|
* **Evidence**: Commit `72c7945` in `~/Brain` and proposed atomic commits in `~/Homelab/Core` and `~/Projects/active/appctl-refactor`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Key Classification Decisions & Edge Cases
|
||||||
|
|
||||||
|
1. **Elimination of `projects/homelab/archive/`**:
|
||||||
|
- *Problem*: Archived roadmaps lived in `projects/homelab/archive/`, breaking historical links when moved.
|
||||||
|
- *Resolution*: Moved to `01-plans/homelab/architecture-consolidation-roadmap-v2.md` and updated frontmatter to `status: completed` or `status: abandoned`.
|
||||||
|
2. **Separation of Discussions from Historical Records**:
|
||||||
|
- *Problem*: `records/discussions/` held prospective option evaluations alongside retrospective incident post-mortems in `records/debug/`.
|
||||||
|
- *Resolution*: Moved to `02-discussions/<project>/`, typed as `discussion`, with `status: resolved` linking forward to resulting plans.
|
||||||
|
3. **Praxis Platform Categorization**:
|
||||||
|
- *Problem*: Praxis blueprints sat ambiguously between `projects/praxis/` and top-level plans.
|
||||||
|
- *Resolution*: Architecture blueprint moved to `01-plans/praxis/praxis-implementation-blueprint.md`, project hub established at `06-projects/praxis/README.md`.
|
||||||
|
4. **Project Subsystem Nesting**:
|
||||||
|
- *Problem*: Complex subsystems like `appctl` under `homelab` required multi-file roadmaps and guides.
|
||||||
|
- *Resolution*: Configured `DirectoryContract(prefix="01-plans", max_depth=3)` and `DirectoryContract(prefix="04-learning/guides", max_depth=3)` to allow `01-plans/homelab/appctl/` while forbidding arbitrary deep nesting elsewhere.
|
||||||
|
5. **Rejection of Root Symlink (`inbox -> 00-inbox`)**:
|
||||||
|
- *Problem*: A symlink was proposed to avoid updating external capture scripts.
|
||||||
|
- *Resolution*: Rejected due to traversal ambiguity, link alias pollution, and tool confusion. Updated external scripts and configs directly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Verification and Final Status
|
||||||
|
|
||||||
|
### Automated Verification
|
||||||
|
* `python3 scripts/validate-brain.py`: Executed across the complete vault. Result: **0 errors, 0 warnings, 100% clean graph**.
|
||||||
|
* `python3 scripts/test_validator.py`: Executed test suite. Result: **10/10 tests passed**.
|
||||||
|
* Pre-commit and post-commit hooks verified: commits automatically push to canonical origin `ssh://git@gitea.roadtotech.me:2223/kiskaadee/second-brain`.
|
||||||
|
* Workspace Grep: Zero stale references to `Brain/inbox` across `~/Homelab`, `~/Projects`, `~/Config`, and `~/.gemini/config`.
|
||||||
|
|
||||||
|
### Status
|
||||||
|
* **Status**: `completed`
|
||||||
|
* **Artifacts Created / Maintained**:
|
||||||
|
- Manifest: [`scripts/migration_manifest.json`](../../scripts/migration_manifest.json)
|
||||||
|
- Validator: [`scripts/validate-brain.py`](../../scripts/validate-brain.py)
|
||||||
|
- Test Suite: [`scripts/test_validator.py`](../../scripts/test_validator.py)
|
||||||
|
- Architectural Discussion: [Brain Epistemic Lifecycle Taxonomy](../../02-discussions/brain/taxonomy-and-lifecycle-architecture.md)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: brain
|
||||||
|
tags:
|
||||||
|
- brain
|
||||||
|
- tooling
|
||||||
|
- validation
|
||||||
|
- architecture
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan: Structural Refactoring for validate-brain.py Pipeline
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
- **Phase 1**: ✅ Implemented and passing (exit 0, Pyright clean)
|
||||||
|
- **Phase 2**: Diagnostics with line numbers — planned
|
||||||
|
- **Phase 3**: Shared linear fence parser — planned
|
||||||
|
|
||||||
|
## What Each Source Got Right
|
||||||
|
|
||||||
|
### Source 1 (Functional Refactor)
|
||||||
|
The incremental suggestion is **immediately actionable and safe**. Its core contributions:
|
||||||
|
- Single-pass file walk (eliminates 4× `rglob` traversals over 138 files)
|
||||||
|
- Checks as functions returning `list[str]` instead of mutating global state
|
||||||
|
- Unified `is_exempt()` that covers both `EXEMPT_PATTERNS` and `FRONTMATTER_EXEMPT_FILES`
|
||||||
|
|
||||||
|
These are correct and low-risk changes. The walrus operator (`DOTALL := re.DOTALL`) in the proposed `validate_mermaid` is a bug (`:=` is assignment, not argument), but the concept is sound.
|
||||||
|
|
||||||
|
### Source 2 (Architectural Redesign)
|
||||||
|
The extended critique is **accurate in almost every diagnosis**, but over-prescribes for this context. Points that are genuinely correct:
|
||||||
|
|
||||||
|
| Diagnosis | Verdict |
|
||||||
|
|---|---|
|
||||||
|
| Repeated `rglob` is wasteful | ✅ Correct — single-pass is better |
|
||||||
|
| Global mutable `errors` is fragile | ✅ Correct — hard to test, hard to trace |
|
||||||
|
| `any('Deprecated' in e for e in errors)` is a reporting smell | ✅ Strongly correct |
|
||||||
|
| Unused `warnings: list[str] = []` | ✅ Correct — dead code |
|
||||||
|
| Parsing and validation are coupled in frontmatter check | ✅ Correct |
|
||||||
|
| Fence-balance check and Mermaid extractor disagree on Markdown model | ✅ Correct — real risk as the repo grows |
|
||||||
|
| External tools (Ruff/Pyright) aren't modeled distinctly | ✅ Correct |
|
||||||
|
| Line numbers missing from diagnostics | ✅ High-value improvement |
|
||||||
|
|
||||||
|
Points that are over-engineered for this project:
|
||||||
|
|
||||||
|
| Suggestion | Verdict |
|
||||||
|
|---|---|
|
||||||
|
| `@dataclass ValidationConfig` | ❌ Over-engineered — constants at module scope are fine for one script |
|
||||||
|
| Separate `validation/` module tree (5–8 files) | ⚠️ Premature — 138 files, single author, single-purpose tool |
|
||||||
|
| `Issue` dataclass with `Severity` enum | ✅ Worth doing, but keep it minimal |
|
||||||
|
| `Document` dataclass | ✅ Worth doing — eliminates the repeated read problem cleanly |
|
||||||
|
| Actual Mermaid CLI invocation | ❌ Not yet — adds an external runtime dependency; the heuristic checks are sufficient for now |
|
||||||
|
| Full YAML parser for frontmatter | ⚠️ Desirable but blocked — `pyyaml` is not available without a dependency declaration |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The Real Problems Worth Fixing Now
|
||||||
|
|
||||||
|
Ranked by impact vs. effort:
|
||||||
|
|
||||||
|
### 1. Repeated `rglob` + repeated file reads (High impact, Low effort)
|
||||||
|
The script reads each of the 138 files **four times**. A single-pass over a `Document` namedtuple fixes this completely.
|
||||||
|
|
||||||
|
### 2. Global mutable state at module scope (High impact, Low effort)
|
||||||
|
All execution currently runs at import time. A `main()` function with local state is the fix. This also makes the script importable for testing later.
|
||||||
|
|
||||||
|
### 3. The `any('Deprecated' in e...)` reporting smell (High impact, Trivial)
|
||||||
|
The per-check success/failure determination should use local error counts, not inspect the accumulated global error list.
|
||||||
|
|
||||||
|
### 4. Missing line numbers in diagnostics (Medium impact, Medium effort)
|
||||||
|
Currently: `Broken link in foo/bar.md: ../baz.md`
|
||||||
|
Should be: `foo/bar.md:47: broken relative link → ../baz.md`
|
||||||
|
|
||||||
|
This is the difference between a useful CI gate and a tool you have to go re-read to act on.
|
||||||
|
|
||||||
|
### 5. `Document` abstraction (Medium impact, Low effort)
|
||||||
|
A `NamedTuple` with `path`, `rel`, `content` eliminates the repeated variable binding (`rel = md.relative_to(ROOT)`, `content = md.read_text(...)`) across every loop.
|
||||||
|
|
||||||
|
### 6. `Issue` type (Low-Medium impact, Low effort)
|
||||||
|
Even a simple `NamedTuple(severity, path, line, message)` enables structured reporting — grouped by file, sortable by severity, extensible to warnings without a second global list.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What NOT to Do
|
||||||
|
|
||||||
|
- **Don't split into multiple modules yet.** At 138 documents and one script, the complexity overhead of a `validation/` package outweighs the benefit. Do it if checks grow to 15+.
|
||||||
|
- **Don't add PyYAML.** It's not available without a dependency declaration. The regex frontmatter parser is adequate for the current schema (only `type` is enforced). If you add `status`, `tags`, `date` validation later, then declare the dependency properly.
|
||||||
|
- **Don't wire in the Mermaid CLI.** It's a large Node dependency, adds runtime setup to the Brain repo, and the heuristic checks already catch the class of errors the repo actually encounters.
|
||||||
|
- **Don't add a `ValidationConfig` dataclass.** The constants are already correctly separated at the top of the file. Wrapping them in a frozen dataclass adds type annotations without any behavioral benefit for a single-config tool.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Target Architecture
|
||||||
|
|
||||||
|
Architecture implemented in [`scripts/validate-brain.py`](../../scripts/validate-brain.py):
|
||||||
|
|
||||||
|
```
|
||||||
|
validate-brain.py
|
||||||
|
│
|
||||||
|
├── Configuration (module-level constants — unchanged)
|
||||||
|
│
|
||||||
|
├── Document NamedTuple
|
||||||
|
│ path: Path, rel: Path, content: str
|
||||||
|
│
|
||||||
|
├── Issue NamedTuple
|
||||||
|
│ severity: str, rel: Path | None, line: int | None, message: str
|
||||||
|
│
|
||||||
|
├── Discovery
|
||||||
|
│ discover_documents() → list[Document] (single rglob pass)
|
||||||
|
│
|
||||||
|
├── Repository checks (no Document input needed)
|
||||||
|
│ check_deprecated_dirs() → list[Issue]
|
||||||
|
│ check_required_files() → list[Issue]
|
||||||
|
│
|
||||||
|
├── Document checks (accept Document, return list[Issue])
|
||||||
|
│ check_frontmatter(doc) → list[Issue]
|
||||||
|
│ check_links(doc) → list[Issue]
|
||||||
|
│ check_code_fences(doc) → list[Issue]
|
||||||
|
│ check_mermaid(doc) → list[Issue]
|
||||||
|
│
|
||||||
|
├── External checks
|
||||||
|
│ run_ruff() → list[Issue]
|
||||||
|
│ run_pyright() → list[Issue]
|
||||||
|
│
|
||||||
|
└── main()
|
||||||
|
├── discover
|
||||||
|
├── run all checks
|
||||||
|
├── collect issues
|
||||||
|
└── report + exit
|
||||||
|
```
|
||||||
|
|
||||||
|
This is ~250–300 lines, stays in one file, requires zero new dependencies, and is backward-compatible with the pre-commit hook.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Concrete False-Positive Risk the Second Source Identified
|
||||||
|
|
||||||
|
The mismatch between the fence-balance check and Mermaid extractor is a real latent bug. Consider this valid Markdown pattern:
|
||||||
|
|
||||||
|
````markdown
|
||||||
|
Here is an example of a mermaid block syntax:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
\```mermaid
|
||||||
|
flowchart LR
|
||||||
|
A --> B
|
||||||
|
\```
|
||||||
|
```
|
||||||
|
````
|
||||||
|
|
||||||
|
The fence-balance check counts inner backtick lines; the Mermaid regex does too. They can disagree on what constitutes an "open" fence because neither builds a proper Markdown parse tree.
|
||||||
|
|
||||||
|
**Mitigation without a full parser:** strip code blocks before running both checks. Parse fences linearly (track open/close state) rather than counting. This eliminates the false-positive class without introducing a Markdown library dependency.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Recommended Implementation Sequence
|
||||||
|
|
||||||
|
1. **Phase 1 (safe, immediate):** `main()` wrapper, `Document` namedtuple, single-pass discovery, `Issue` namedtuple, fix the reporting smell. No behavioral change. *(Complete)*
|
||||||
|
2. **Phase 2 (diagnostics):** Add line-number tracking to frontmatter, link, and Mermaid checks. Structured output by file.
|
||||||
|
3. **Phase 3 (Markdown model):** Replace the parallel fence-balance and Mermaid extraction with a shared linear fence parser that skips nested fences. Eliminates the false-positive class.
|
||||||
|
4. **Later / never:** Full YAML frontmatter parser, Mermaid CLI integration, multi-module split — only when the actual complexity warrants it.
|
||||||
File renamed without changes.
+78
-13
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
type: plan
|
type: plan
|
||||||
status: active
|
status: superseded
|
||||||
project: homelab
|
project: homelab
|
||||||
date: 2026-09-21
|
date: 2026-09-21
|
||||||
tags:
|
tags:
|
||||||
@@ -16,6 +16,8 @@ tags:
|
|||||||
|
|
||||||
# 🚀 appctl Engine V2: Architectural Modernization & Type-Safe Refactoring Plan
|
# 🚀 appctl Engine V2: Architectural Modernization & Type-Safe Refactoring Plan
|
||||||
|
|
||||||
|
> **Superseded by**: [Architecture Consolidation & Control Plane Roadmap v5](../consolidation/architecture-consolidation-roadmap-v5.md) (specifically Phases P0, P3, and P4). Engine modernization code has been integrated into the consolidated baseline and control-plane architecture.
|
||||||
|
|
||||||
## 1. Executive Summary & Intent
|
## 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.
|
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.
|
||||||
@@ -50,8 +52,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 +62,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 +84,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 +99,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**:
|
||||||
- Parse `git status --porcelain` and `git rev-list --left-right --count HEAD...@{u}`.
|
- **Axis 1: Deployment Git Status**:
|
||||||
- Return standardized badges (`✓ Synced`, `⬆ N Ahead`, `⬇ N Behind`, `⚡ N⬆ M⬇`, `⚪ Untracked`, `*` dirty indicator).
|
- Implement `get_deployment_git_status(dir_path: Path | str) -> str`.
|
||||||
- Implement `get_git_diagnostics(dir_path: Path | str) -> dict[str, Any] | None`.
|
- 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**:
|
- [ ] **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 +147,50 @@ 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.
|
||||||
- [ ] Replace `scripts/appctl_engine.py` with `scripts/appctl_engine_v2.py`.
|
- [ ] **Topology Synchronization (Roadmap v4 P1 alignment)**:
|
||||||
- [ ] Run `./scripts/test` and live verification (`appctl list`, `appctl info`, `appctl sync`).
|
- 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.
|
- [ ] 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`).
|
||||||
|
|
||||||
|
```text
|
||||||
|
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
|
## 5. Invariants & Acceptance Criteria
|
||||||
|
|
||||||
1. **Zero Breaking Changes to Bash Contract**:
|
1. **Zero Breaking Changes to Bash Contract**:
|
||||||
@@ -142,3 +199,11 @@ This plan modernizes the engine from a procedural ~900-line script with a hand-r
|
|||||||
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`.
|
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**:
|
3. **The Unlicense Integrity**:
|
||||||
All new files and refactored code preserve public domain status under The Unlicense.
|
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.
|
||||||
|
|
||||||
+3
-1
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
type: plan
|
type: plan
|
||||||
status: active
|
status: superseded
|
||||||
project: homelab
|
project: homelab
|
||||||
tags:
|
tags:
|
||||||
- operations
|
- operations
|
||||||
@@ -14,6 +14,8 @@ tags:
|
|||||||
|
|
||||||
# 🚀 Smart Selective Deployment Pipeline Plan for Homelab Core
|
# 🚀 Smart Selective Deployment Pipeline Plan for Homelab Core
|
||||||
|
|
||||||
|
> **Superseded by**: [Architecture Consolidation & Control Plane Roadmap v5](../consolidation/architecture-consolidation-roadmap-v5.md) (specifically Phase P4 control-plane reconciliation).
|
||||||
|
|
||||||
## Goal Description
|
## Goal Description
|
||||||
Implement an intelligent, change-aware deployment pipeline for `homelab-core` that:
|
Implement an intelligent, change-aware deployment pipeline for `homelab-core` that:
|
||||||
1. Analyzes incoming commits on `main` (via Gitea GitOps webhooks and manual `appctl update core` CLI invocations) and selectively executes **only** the required actions.
|
1. Analyzes incoming commits on `main` (via Gitea GitOps webhooks and manual `appctl update core` CLI invocations) and selectively executes **only** the required actions.
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: completed
|
||||||
|
project: homelab
|
||||||
|
tags:
|
||||||
|
- homelab
|
||||||
|
- documentation
|
||||||
|
- consolidation
|
||||||
|
- madr
|
||||||
|
- taxonomy
|
||||||
|
---
|
||||||
|
|
||||||
|
# Implementation Plan: Homelab Architecture Consolidation Documents Reorganization
|
||||||
|
|
||||||
|
## Goal Description
|
||||||
|
|
||||||
|
Establish a clear, non-overlapping epistemic taxonomy across the Homelab Architecture Consolidation triad (**ADR**, **Plan**, and **Discussion**), standardize the ADR using standard MADR conventions, link the three documents bidirectionally, and relocate the architecture consolidation/hardening artifacts into a dedicated subsystem folder inside `01-plans/homelab/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Epistemic Separation of Concerns: The Three Document Types
|
||||||
|
|
||||||
|
To prevent duplicated content and keep each document focused on its distinct cognitive role (as defined in [`AGENTS.md`](../../AGENTS.md)):
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
subgraph DISC["02-discussions/ (EXPLORATION)"]
|
||||||
|
D1["architecture-migration-v3-to-v4.md<br/>• WHY change?<br/>• Historical context & pain points<br/>• What did old model prevent?<br/>• What does new model unlock?<br/>• Decision-making narrative"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph ADR["03-records/decisions/ (COMMITMENT)"]
|
||||||
|
A1["homelab-3tier-architecture-and-provenance.md<br/>• WHAT is decided?<br/>• MADR standard structure<br/>• Problem statement & drivers<br/>• Options summary & trade-offs<br/>• Concrete decision & consequences"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph PLAN["01-plans/homelab/consolidation/ (INTENT)"]
|
||||||
|
P1["architecture-consolidation-roadmap-v4.md<br/>• HOW do we execute?<br/>• System specifications & contracts<br/>• Working rules & constraints<br/>• Ordered execution phases (P0–P5)<br/>• Step-by-step runbooks & DoD"]
|
||||||
|
end
|
||||||
|
|
||||||
|
DISC -->|Resolves into| ADR
|
||||||
|
ADR -->|Governs| PLAN
|
||||||
|
PLAN -.->|References rationale in| DISC
|
||||||
|
PLAN -.->|References decision in| ADR
|
||||||
|
ADR -.->|References context in| DISC
|
||||||
|
```
|
||||||
|
|
||||||
|
### Precise Document Boundaries & Responsibilities
|
||||||
|
|
||||||
|
| Dimension | Architectural Decision Record (ADR) | Actionable Plan / Specification | Epistemic Discussion |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Directory** | `03-records/decisions/` | `01-plans/homelab/consolidation/` | `02-discussions/homelab/` |
|
||||||
|
| **Type** | `decision` | `plan` | `discussion` |
|
||||||
|
| **Core Question** | *"What did we decide, and what are the point-in-time trade-offs?"* | *"What do we intend to build, and in what exact sequence?"* | *"Why was this change necessary, and how did the reasoning evolve?"* |
|
||||||
|
| **Standard Format** | **MADR 4.0 Standard** (Context, Decision Drivers, Options, Decision Outcome, Pros/Cons, Consequences) | **Actionable Roadmap / Spec** (Principles, System Spec, Working Rules, Phased Execution P0–P5, Runbooks, DoD) | **Inquiry & Rationale Analysis** (Problem Context, Root Friction Points, What Old Model Prevented, What New Model Enables, Justification) |
|
||||||
|
| **Content Included** | Decision statement, decision drivers, high-level tier definitions, options considered table, positive/negative consequences. | Pure technical specifications, schema contracts, sequence of ordered milestones, operational runbooks, rollbacks, and verification gates. | Deep dive into operational friction, evolution from v1/v2/v3 to v4, design dilemmas (e.g. why `git ls-remote` vs full clone, linear vs broker orchestrator), before/after comparison. |
|
||||||
|
| **Content Removed / Excluded** | Detailed bash execution runbooks, step-by-step phased checklists, extensive design dilemmas. | Redundant philosophical debate, historical options matrix, lengthy justifications of why we didn't pick RabbitMQ or full Git cloning. | Phased execution step-by-step instructions, operational runbooks, shell scripts. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Standardizing the ADR (MADR 4.0 Alignment)
|
||||||
|
|
||||||
|
Restructure [`homelab-3tier-architecture-and-provenance.md`](../../03-records/decisions/homelab-3tier-architecture-and-provenance.md) according to the widely adopted Markdown Architectural Decision Records (MADR) format:
|
||||||
|
|
||||||
|
1. **Title**: `ADR: Homelab 3-Tier Architecture & Deployment Provenance Model`
|
||||||
|
2. **Status**: `accepted` (with date: `2026-09-28`)
|
||||||
|
3. **Context and Problem Statement**: Concise framing of the four core issues (source pollution, repo inflation, ambiguous freshness, orchestrator sprawl risk).
|
||||||
|
4. **Decision Drivers**:
|
||||||
|
- Clean separation of concerns between code development and platform deployment.
|
||||||
|
- Elimination of repository inflation for off-the-shelf software.
|
||||||
|
- Independent verification of deployment configuration state vs. application code freshness.
|
||||||
|
- Adherence to KISS primitives by strictly bounding control paths (no brokers, queues, or deployment databases).
|
||||||
|
- Absolute protection of mutable runtime data from version-controlled trees.
|
||||||
|
5. **Considered Options**:
|
||||||
|
- *Option 1*: Monolithic / Single-Repo Deployment (v1–v3 status quo)
|
||||||
|
- *Option 2*: Miniature Cloud Platform (ArgoCD/Kubernetes style with brokers and DB)
|
||||||
|
- *Option 3*: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path
|
||||||
|
6. **Decision Outcome**:
|
||||||
|
- Chosen option: *Option 3*.
|
||||||
|
- Crisp summary of the four key architectural commitments:
|
||||||
|
- 3-tier decoupling (Software, Deployment, Platform) with OCI image as intermediate build artifact.
|
||||||
|
- Two workload classes (Source-Backed with explicit `source:` block vs. Image-Only).
|
||||||
|
- Two operational inspection axes with three revision identities (`deployment_config_revision`, `source_revision`, `artifact_digest`).
|
||||||
|
- Minimal linear control path (`Source Push -> CI -> GitOps -> appctl update -> Compose`).
|
||||||
|
- Persistent state root isolation (`~/var/lib/homelab/<app>/`).
|
||||||
|
7. **Pros and Cons of the Options**:
|
||||||
|
- Evaluation of each option against the decision drivers.
|
||||||
|
8. **Consequences**:
|
||||||
|
- *Positive Consequences* (decoupled lifecycle, precise truth, clean state, bounded surface).
|
||||||
|
- *Negative Consequences / Accepted Trade-offs* (two repos for custom apps, commit equality without distance counts).
|
||||||
|
9. **Links & Cross-References**:
|
||||||
|
- Link forward to the Plan: [`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md`](consolidation/architecture-consolidation-roadmap-v4.md)
|
||||||
|
- Link to the Discussion: [`02-discussions/homelab/architecture-migration-v3-to-v4.md`](../../02-discussions/homelab/architecture-migration-v3-to-v4.md)
|
||||||
|
- Link to Project Hub: [`06-projects/homelab/README.md`](../../06-projects/homelab/README.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Deepening the Discussion (`02-discussions/homelab/...`)
|
||||||
|
|
||||||
|
Expand [`architecture-migration-v3-to-v4.md`](../../02-discussions/homelab/architecture-migration-v3-to-v4.md) to provide comprehensive justification and narrative evolution:
|
||||||
|
|
||||||
|
1. **The Evolution of the Model (From v1/v2/v3 to v4)**:
|
||||||
|
- Walk through why v1/v2 focused on NixOS appliance and basic separation, v3 focused on mail/controller authority, and why v3 still failed to solve the fundamental workload coupling.
|
||||||
|
2. **Deep Dive into the Friction Points & Concrete Operational Failures**:
|
||||||
|
- Detailed breakdown of each friction point with real-world examples:
|
||||||
|
- *Source Pollution*: What happened when developing `doc2site` or `bitetrack`—having host Traefik rules and Docker networks in Git prevented sharing code, running standalone tests, or open-sourcing.
|
||||||
|
- *Repository Inflation*: Why creating whole Git repos for 20-line Compose files for Jellyfin and Stirling cluttered Gitea and CI pipelines.
|
||||||
|
- *Ambiguous Freshness in `appctl`*: Why `git rev-list HEAD...@{u}` could only detect uncommitted changes to `app.yaml`, giving false confidence that the container was running current code.
|
||||||
|
- *Host Build Overhead*: Why compiling on the deployment host created ambient toolchain dependencies and violated least-privilege appliance principles.
|
||||||
|
3. **What the Old Model Prevented**:
|
||||||
|
- Inability to open-source or modularize internal tools without stripping Homelab configuration.
|
||||||
|
- Inability to verify if a deployed container had critical upstream security patches.
|
||||||
|
- Inability to maintain clean, reproducible Git trees without accidental database/upload commits.
|
||||||
|
4. **What the New Model Unlocks**:
|
||||||
|
- Independent application lifecycles and modern CI pipelines.
|
||||||
|
- Dual-axis diagnostic transparency: knowing exactly whether config is dirty vs. whether code is stale.
|
||||||
|
- Stateless deployment repositories (`~/Sites`) backed by isolated runtime state roots (`~/var/lib/homelab`).
|
||||||
|
- Clean, lightweight onboarding of off-the-shelf software with zero repo overhead.
|
||||||
|
5. **Architectural Dilemmas & How Decision Making Occurred**:
|
||||||
|
- *The Image Question*: Is an OCI image a 4th tier or an intermediate provenance artifact? (Resolved: Artifact).
|
||||||
|
- *The Ancestry Dilemma*: Why calculate commit distance when `git ls-remote` commit equality solves the staleness problem with zero disk bloat?
|
||||||
|
- *The Anti-Sprawl Principle*: Why reject queues/databases in favor of a strictly linear control path?
|
||||||
|
6. **Bidirectional Links**:
|
||||||
|
- Explicit links to both the ADR ([`03-records/decisions/homelab-3tier-architecture-and-provenance.md`](../../03-records/decisions/homelab-3tier-architecture-and-provenance.md)) and the Plan ([`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md`](consolidation/architecture-consolidation-roadmap-v4.md)).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Refining the Plan (`01-plans/homelab/consolidation/...`)
|
||||||
|
|
||||||
|
In [`architecture-consolidation-roadmap-v4.md`](consolidation/architecture-consolidation-roadmap-v4.md):
|
||||||
|
- **Cross-Reference in Header**: Link to BOTH the ADR and the Discussion:
|
||||||
|
```markdown
|
||||||
|
> **Architectural Decision Record**: [`03-records/decisions/homelab-3tier-architecture-and-provenance.md`](../../03-records/decisions/homelab-3tier-architecture-and-provenance.md)
|
||||||
|
>
|
||||||
|
> **Architectural Discussion & Rationale**: [`02-discussions/homelab/architecture-migration-v3-to-v4.md`](../../02-discussions/homelab/architecture-migration-v3-to-v4.md)
|
||||||
|
```
|
||||||
|
- **Trim Duplicated Philosophical Rationale**: Reference the Discussion for the deep dive on pain points and options evaluation, keeping Part 1 through Part 7 focused on technical specifications, contracts, domain models, and working rules.
|
||||||
|
- **Retain & Polish the Actionable Plan**: Keep Part 8 (Phased Implementation Plan P0–P5) as the authoritative, ordered sequence of execution steps, complete with verification gates and non-destructive runbooks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Subdirectory Reorganization in `01-plans/homelab/`
|
||||||
|
|
||||||
|
### Subdirectory Structure
|
||||||
|
A dedicated subsystem directory was established to organize the consolidation roadmap series:
|
||||||
|
`01-plans/homelab/consolidation/`
|
||||||
|
|
||||||
|
Organizing all 6 consolidation artifacts into this folder:
|
||||||
|
```text
|
||||||
|
01-plans/homelab/consolidation/
|
||||||
|
├── architecture-consolidation-roadmap.md (v1 - superseded)
|
||||||
|
├── architecture-consolidation-roadmap-v2.md (v2 - superseded)
|
||||||
|
├── architecture-consolidation-implementation-guide-v2.md (v2 - superseded)
|
||||||
|
├── architecture-consolidation-roadmap-v3.md (v3 - superseded)
|
||||||
|
├── architecture-consolidation-implementation-guide-v3.md (v3 - superseded)
|
||||||
|
└── architecture-consolidation-roadmap-v4.md (v4 - ACTIVE CANONICAL BLUEPRINT)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Validator & Depth Contract Compliance
|
||||||
|
In `scripts/validate-brain.py`:
|
||||||
|
```python
|
||||||
|
DirectoryContract(prefix="01-plans", expected_type="plan", max_depth=3)
|
||||||
|
```
|
||||||
|
- Path: `01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md`
|
||||||
|
- Depth relative to `01-plans`: `homelab` (1) / `consolidation` (2) / `roadmap-v4.md` (3) = **depth 3**.
|
||||||
|
- **Result**: Complies with `max_depth=3`. Note that `02-discussions` and `03-records/decisions` remain at `max_depth=2` per the repository taxonomy rules.
|
||||||
|
|
||||||
|
### External References & Relative Links
|
||||||
|
Intra-vault links updated across:
|
||||||
|
- `06-projects/homelab/README.md`
|
||||||
|
- `02-discussions/homelab/architecture-migration-v3-to-v4.md`
|
||||||
|
- `03-records/decisions/homelab-3tier-architecture-and-provenance.md`
|
||||||
|
- Recent journal entries (`03-records/journal/2026-09-28.md`, `2026-09-27.md`, `2026-09-14.md`, `2026-09-13.md`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Verification Plan
|
||||||
|
|
||||||
|
### Automated Verification
|
||||||
|
1. Run structural validator:
|
||||||
|
```bash
|
||||||
|
python scripts/validate-brain.py
|
||||||
|
```
|
||||||
|
Must pass with zero errors (all links resolve, frontmatter valid, code fences and Mermaid diagrams valid, depth contracts satisfied).
|
||||||
|
2. Run validator test suite:
|
||||||
|
```bash
|
||||||
|
python scripts/test_validator.py
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Verification
|
||||||
|
1. Verify bidirectional navigation:
|
||||||
|
- `01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md` $\leftrightarrow$ `03-records/decisions/homelab-3tier-architecture-and-provenance.md` $\leftrightarrow$ `02-discussions/homelab/architecture-migration-v3-to-v4.md`.
|
||||||
|
2. Inspect content balance:
|
||||||
|
- Ensure the ADR has no step-by-step shell runbooks.
|
||||||
|
- Ensure the Plan has no redundant pros/cons evaluation debates.
|
||||||
|
- Ensure the Discussion thoroughly captures the justification, operational pain points, and unlocked capabilities.
|
||||||
+3
-3
@@ -20,7 +20,7 @@ The **Brain** repository (`~/Brain`) is an actively edited, durable personal kno
|
|||||||
|
|
||||||
### Core Pipeline Invariants:
|
### Core Pipeline Invariants:
|
||||||
1. **The Curation Boundary**: Raw thoughts and scratch captures stay in `inbox/` (uncommitted, unvalidated, zero-friction). Once moved to their semantic home (`knowledge/`, `projects/`, `records/`, `practice/`), they join the committed graph.
|
1. **The Curation Boundary**: Raw thoughts and scratch captures stay in `inbox/` (uncommitted, unvalidated, zero-friction). Once moved to their semantic home (`knowledge/`, `projects/`, `records/`, `practice/`), they join the committed graph.
|
||||||
2. **Local Schema Integrity Gate**: Every commit is verified locally by [`scripts/validate-brain.py`](../../../scripts/validate-brain.py) via a `pre-commit` hook to ensure valid metadata and prevent broken relative links.
|
2. **Local Schema Integrity Gate**: Every commit is verified locally by [`scripts/validate-brain.py`](../../scripts/validate-brain.py) via a `pre-commit` hook to ensure valid metadata and prevent broken relative links.
|
||||||
3. **Instant Zero-Delay Auto-Push**: A resilient `post-commit` hook automatically pushes commits to the primary self-hosted Gitea forge (`gitea.roadtotech.me`), falling back gracefully if offline.
|
3. **Instant Zero-Delay Auto-Push**: A resilient `post-commit` hook automatically pushes commits to the primary self-hosted Gitea forge (`gitea.roadtotech.me`), falling back gracefully if offline.
|
||||||
4. **Automated Cloud Replication**: Gitea natively push-mirrors every commit to GitHub (`github.com/kiskaadee/second-brain`) immediately on receive.
|
4. **Automated Cloud Replication**: Gitea natively push-mirrors every commit to GitHub (`github.com/kiskaadee/second-brain`) immediately on receive.
|
||||||
5. **Server-Side CI & Observability**: Gitea Actions validates graph health on every push asynchronously without blocking editing or live rendering.
|
5. **Server-Side CI & Observability**: Gitea Actions validates graph health on every push asynchronously without blocking editing or live rendering.
|
||||||
@@ -152,5 +152,5 @@ Configured under repository **Settings** $\rightarrow$ **Repository** $\rightarr
|
|||||||
---
|
---
|
||||||
|
|
||||||
## 🔗 Related Production Guides
|
## 🔗 Related Production Guides
|
||||||
* [Brain GitOps & Auto-Sync Deployment Pipeline](../guides/brain-gitops-deployment-pipeline.md)
|
* [Brain GitOps & Auto-Sync Deployment Pipeline](../../04-learning/guides/homelab/brain-gitops-deployment-pipeline.md)
|
||||||
* [Dynamic Decentralized GitOps Dispatcher Architecture](../discussions/gitops-dispatcher-architecture.md)
|
* [Dynamic Decentralized GitOps Dispatcher Architecture](../../02-discussions/homelab/gitops-dispatcher-architecture.md)
|
||||||
+5
-2
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
type: plan
|
type: plan
|
||||||
status: active
|
status: completed
|
||||||
project: homelab
|
project: homelab
|
||||||
tags:
|
tags:
|
||||||
- architecture
|
- architecture
|
||||||
@@ -11,7 +11,10 @@ tags:
|
|||||||
- implementation
|
- implementation
|
||||||
---
|
---
|
||||||
|
|
||||||
# Homelab Core — Architecture Consolidation & Hardening Implementation Guide
|
# Homelab Core — Architecture Consolidation & Hardening Implementation Guide v2
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> Superseded by [Architecture Consolidation Implementation Guide v3](architecture-consolidation-implementation-guide-v3.md).
|
||||||
|
|
||||||
This guide turns the [Architecture Consolidation & Hardening Roadmap v2](architecture-consolidation-roadmap-v2.md) into an executable sequence of work.
|
This guide turns the [Architecture Consolidation & Hardening Roadmap v2](architecture-consolidation-roadmap-v2.md) into an executable sequence of work.
|
||||||
|
|
||||||
@@ -0,0 +1,539 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: superseded
|
||||||
|
superseded_by: architecture-consolidation-roadmap-v5.md
|
||||||
|
project: homelab
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- security
|
||||||
|
- operations
|
||||||
|
- homelab
|
||||||
|
- gitops
|
||||||
|
- implementation
|
||||||
|
- migration
|
||||||
|
---
|
||||||
|
|
||||||
|
# Homelab Core — Architecture Consolidation & Hardening Implementation Guide v3
|
||||||
|
|
||||||
|
> [!WARNING]
|
||||||
|
> **SUPERSEDED**: This execution guide has been superseded by [**Architecture Consolidation & Control Plane Roadmap v5**](architecture-consolidation-roadmap-v5.md), which unifies the architecture specifications and step-by-step implementation runbooks into a single source of truth.
|
||||||
|
>
|
||||||
|
> **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** | Taxonomy definitions, controller authority matrix, resource ownership matrix, dependency graphs, AGENTS alignment. | 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, inverted trust boundary, alias collision rejection, 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`), declarative `strategy: compose`, migrate `~/Sites/*`. | Manifest validation in CI, schema lint tests. |
|
||||||
|
| **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** | Track `requested_revision`, `deployed_revision`, `previous_revision`, atomic status record, `appctl history`. | Dispatcher status test fixtures, superseding 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.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Parallel development: YES (isolated feature / refactor branches)
|
||||||
|
Parallel production moves: NO (serialized host/service cutovers)
|
||||||
|
Parallel changes to same integration seam: ONLY when explicitly coordinated
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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
|
||||||
|
When multiple branches are active, the interfaces connecting them must not undergo uncoordinated drift. Specifically, the `appctl-v2` track must preserve the CLI invocation syntax, the `resolve` JSON contract, canonical service identifiers, and Homepage generation semantics until the deliberate convergence point at Milestone P3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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` (commit `5fc5ad8`) in `/home/kiskaadee/Projects/active/appctl-refactor`. Replaces legacy procedural code with a typed dataclass hierarchy (`SitesApp`, `CoreService`), PyYAML ingestion, 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. The refactoring branch changes file structures drastically (`scripts/appctl_engine_v2.py`); frequent cross-merging will cause severe merge conflicts.
|
||||||
|
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()`, and remove `snappymail` from Homepage metadata mapping.
|
||||||
|
- **On `refactor/appctl-rework`**: Update the typed `CoreService` list in `scripts/appctl_engine_v2.py` symmetrically (`stalwart` domain $\rightarrow$ `smtp.${HOMELAB_DOMAIN}`, remove `snappymail` and deprecated `portainer`). This 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**. To avoid branch confusion, `core_manifest.py` originates authoritatively on `main` (where it is validated against `gitops_dispatcher.py` and test suites). That atomic commit is then brought into `refactor/appctl-rework` via cherry-pick, `appctl-v2` adapts its manifest ingestion to the shared module and verifies its unit tests, and finally the fully integrated `refactor/appctl-rework` branch is merged into `main`.
|
||||||
|
|
||||||
|
### The 5 Architectural Invariants Protected by appctl-v2
|
||||||
|
|
||||||
|
1. **CLI Syntax**: `scripts/appctl` invocation arguments, flags, and exits remain identical.
|
||||||
|
2. **`resolve` JSON Contract**: `cmd_resolve` emits the exact JSON schema consumed by `scripts/appctl`: required keys `name` (str), `dir_path` (str), `type` (str: `"app"` or `"core_service"`), `domain` (str), plus contextual keys `container` (str) and `env` (dict). Backed by an automated test fixture in `test_appctl_engine_v2.py`.
|
||||||
|
3. **Canonical Identity**: Service identifiers remain stable within the systems that own them; Core services and Sites workloads use their canonical names consistently.
|
||||||
|
4. **Core vs. Sites Taxonomy**: Strict classification between platform capabilities in Core and independent workloads in Sites.
|
||||||
|
5. **Homepage Sync Semantics**: Compiles `Core/config/homepage/services.yaml` from Core inventory + discovered Sites manifests without schema drift.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Phase 0: Architecture Re-Baseline & Structural Catalog
|
||||||
|
|
||||||
|
### Deliverable 0.1: Service Taxonomy & Platform Topology
|
||||||
|
Update `Core/docs/architecture.md` and repository guidelines to formalize the 5-tier taxonomy:
|
||||||
|
1. Host Foundation (NixOS, systemd, Docker, nftables, SOPS)
|
||||||
|
2. Edge & Security Primitives (Traefik, socket-proxy, Authelia, LLDAP)
|
||||||
|
3. Core Platform Capabilities (Stalwart)
|
||||||
|
4. Platform Operations (Homepage, Dozzle, Diun, Watchtower)
|
||||||
|
5. Workload Plane (`~/Sites/*`)
|
||||||
|
|
||||||
|
### Deliverable 0.2: Controller Authority Matrix
|
||||||
|
Document authoritative control loops across systemd, Docker Compose, GitOps, `appctl`, and CI runners in `Core/docs/architecture.md`.
|
||||||
|
|
||||||
|
### Deliverable 0.3: Resource & State Ownership Matrix
|
||||||
|
Document persistent state ownership for every stateful resource. For each resource, define: owner, filesystem location, desired state source (Git, generated, runtime-only), and runtime state form. This matrix makes migration and recovery semantics explicit and prevents ambiguity about who owns what data.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Phase 1: Mail Topology Realignment & Zero-Data-Loss Migration Runbook
|
||||||
|
|
||||||
|
### Architectural Context & Invariants
|
||||||
|
- **Stalwart**: Remains in Homelab Core. Public endpoint moves from `mail.roadtotech.me` to `smtp.roadtotech.me`. Persistent mail store (`Core/config/stalwart/data`) is never moved.
|
||||||
|
- **SnappyMail**: Moves from `Core/docker-compose.yml` to `~/Sites/snappymail/docker-compose.yml`. Public endpoint moves from `webmail.roadtotech.me` to `mail.roadtotech.me`. Persistent state (`Core/config/snappymail/data`) is safely 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
|
||||||
|
ssh server-local "docker ps --filter 'name=stalwart' --filter 'name=snappymail'"
|
||||||
|
ssh server-local "ls -la ~/Core/config/stalwart/ ~/Core/config/snappymail/data"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Step 1.2: Freeze SnappyMail in Core
|
||||||
|
Prevent active user sessions or settings modifications while preserving Stalwart:
|
||||||
|
```bash
|
||||||
|
ssh server-local "docker stop snappymail"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Step 1.3: Create Verified Rollback Archive
|
||||||
|
Create a compressed archive of SnappyMail state with permissions and timestamps preserved:
|
||||||
|
```bash
|
||||||
|
ssh server-local "tar -czpf ~/snappymail-backup-\$(date +%Y%m%d%H%M%S).tar.gz -C ~/Core/config/snappymail data"
|
||||||
|
```
|
||||||
|
Generate a checksum for the archive:
|
||||||
|
```bash
|
||||||
|
ssh server-local "sha256sum ~/snappymail-backup-*.tar.gz"
|
||||||
|
```
|
||||||
|
Verify archive integrity by performing a test extraction into a temporary directory:
|
||||||
|
```bash
|
||||||
|
ssh server-local "mkdir -p /tmp/snappymail-verify && tar -xzf ~/snappymail-backup-*.tar.gz -C /tmp/snappymail-verify && diff -r ~/Core/config/snappymail/data /tmp/snappymail-verify/data && echo 'Archive verified OK' && rm -rf /tmp/snappymail-verify"
|
||||||
|
```
|
||||||
|
**Gate**: Do not proceed until archive extraction matches the live source directory.
|
||||||
|
|
||||||
|
#### Step 1.4: Scaffold Sites Workload (`~/Sites/snappymail`)
|
||||||
|
Create local directory structure:
|
||||||
|
```bash
|
||||||
|
mkdir -p ~/Sites/snappymail/data
|
||||||
|
```
|
||||||
|
|
||||||
|
Create `~/Sites/snappymail/app.yaml`:
|
||||||
|
```yaml
|
||||||
|
schemaVersion: "1.0"
|
||||||
|
name: "snappymail"
|
||||||
|
displayName: "SnappyMail"
|
||||||
|
description: "Modern Lightweight Webmail Client"
|
||||||
|
category: "Communication"
|
||||||
|
|
||||||
|
network:
|
||||||
|
ingress: true
|
||||||
|
domain: "mail.roadtotech.me"
|
||||||
|
publishedPort: 8888
|
||||||
|
internalOnly: false
|
||||||
|
|
||||||
|
deployment:
|
||||||
|
strategy: compose
|
||||||
|
branch: main
|
||||||
|
preflight:
|
||||||
|
filesRequired:
|
||||||
|
- docker-compose.yml
|
||||||
|
- data
|
||||||
|
```
|
||||||
|
|
||||||
|
Create `~/Sites/snappymail/docker-compose.yml`:
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
snappymail:
|
||||||
|
image: ghcr.io/the-djmaze/snappymail:latest
|
||||||
|
container_name: snappymail
|
||||||
|
restart: always
|
||||||
|
volumes:
|
||||||
|
- ./data:/var/lib/snappymail/_data_
|
||||||
|
networks:
|
||||||
|
- proxy-net
|
||||||
|
labels:
|
||||||
|
- "traefik.enable=true"
|
||||||
|
# Public (HTTPS)
|
||||||
|
- "traefik.http.routers.snappymail.rule=Host(`mail.${DOMAIN}`)"
|
||||||
|
- "traefik.http.routers.snappymail.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.snappymail.tls=true"
|
||||||
|
- "traefik.http.routers.snappymail.tls.certresolver=myresolver"
|
||||||
|
- "traefik.http.routers.snappymail.service=snappymail-svc"
|
||||||
|
# Public (Redirect HTTP -> HTTPS)
|
||||||
|
- "traefik.http.routers.snappymail-red.rule=Host(`mail.${DOMAIN}`)"
|
||||||
|
- "traefik.http.routers.snappymail-red.entrypoints=web"
|
||||||
|
- "traefik.http.routers.snappymail-red.middlewares=https-redirect@docker"
|
||||||
|
# Backend Port
|
||||||
|
- "traefik.http.services.snappymail-svc.loadbalancer.server.port=8888"
|
||||||
|
|
||||||
|
networks:
|
||||||
|
proxy-net:
|
||||||
|
external: true
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Step 1.5: Non-Destructive State Copy & Verification
|
||||||
|
Replicate existing configuration data to `~/Sites/snappymail/data/` preserving ownership, timestamps, and hidden files:
|
||||||
|
```bash
|
||||||
|
ssh server-local "cp -a ~/Core/config/snappymail/data/. ~/Sites/snappymail/data/"
|
||||||
|
```
|
||||||
|
*(Notice: The original `~/Core/config/snappymail/data` is left untouched as an emergency rollback anchor).*
|
||||||
|
|
||||||
|
Verify source/destination parity before proceeding:
|
||||||
|
```bash
|
||||||
|
# File count comparison
|
||||||
|
ssh server-local "echo 'Source:' && find ~/Core/config/snappymail/data -type f | wc -l && echo 'Destination:' && find ~/Sites/snappymail/data -type f | wc -l"
|
||||||
|
|
||||||
|
# Byte count comparison
|
||||||
|
ssh server-local "echo 'Source:' && du -sb ~/Core/config/snappymail/data && echo 'Destination:' && du -sb ~/Sites/snappymail/data"
|
||||||
|
|
||||||
|
# Recursive diff (should produce no output)
|
||||||
|
ssh server-local "diff -r ~/Core/config/snappymail/data ~/Sites/snappymail/data"
|
||||||
|
|
||||||
|
# Ownership/permissions spot-check
|
||||||
|
ssh server-local "ls -laR ~/Sites/snappymail/data | head -n 30"
|
||||||
|
```
|
||||||
|
**Gate**: Do not proceed to Step 1.6 until file count, byte count, and recursive diff confirm exact parity.
|
||||||
|
|
||||||
|
#### Step 1.6: Update Stalwart in `Core/docker-compose.yml`
|
||||||
|
1. Reconfigure Stalwart's public identity and Traefik labels from `mail.${DOMAIN}` to `smtp.${DOMAIN}`:
|
||||||
|
```yaml
|
||||||
|
environment:
|
||||||
|
- DOMAIN=${DOMAIN}
|
||||||
|
- STALWART_PUBLIC_URL=https://smtp.${DOMAIN}
|
||||||
|
- STALWART_RECOVERY_ADMIN=admin:${LLDAP_LDAP_USER_PASS}
|
||||||
|
labels:
|
||||||
|
- "traefik.enable=true"
|
||||||
|
# HTTPS WebAdmin & JMAP Router
|
||||||
|
- "traefik.http.routers.stalwart.rule=Host(`smtp.${DOMAIN}`)"
|
||||||
|
- "traefik.http.routers.stalwart.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.stalwart.tls=true"
|
||||||
|
- "traefik.http.routers.stalwart.tls.certresolver=myresolver"
|
||||||
|
- "traefik.http.routers.stalwart.service=stalwart-svc"
|
||||||
|
# HTTP -> HTTPS Redirect
|
||||||
|
- "traefik.http.routers.stalwart-red.rule=Host(`smtp.${DOMAIN}`)"
|
||||||
|
- "traefik.http.routers.stalwart-red.entrypoints=web"
|
||||||
|
- "traefik.http.routers.stalwart-red.middlewares=https-redirect@docker"
|
||||||
|
- "traefik.http.services.stalwart-svc.loadbalancer.server.port=8080"
|
||||||
|
```
|
||||||
|
2. Remove the `snappymail:` service definition from `Core/docker-compose.yml`.
|
||||||
|
|
||||||
|
#### Step 1.7: Update Core Platform Tooling (`appctl_engine.py`)
|
||||||
|
|
||||||
|
To prevent cross-branch merge conflicts, apply the service inventory update symmetrically across both branches without merging:
|
||||||
|
|
||||||
|
**Action on `main` (Legacy Engine)**:
|
||||||
|
1. In `Core/scripts/appctl_engine.py`, remove `"snappymail"` from `get_core_services()`.
|
||||||
|
2. Update the `"stalwart"` entry in `get_core_services()`:
|
||||||
|
```python
|
||||||
|
{"name": "stalwart", "domain": "smtp.roadtotech.me", "container": "stalwart", "desc": "All-in-one Mail Server & JMAP/IMAP/SMTP"}
|
||||||
|
```
|
||||||
|
3. Update Homepage metadata mapping so `stalwart` maps to `smtp.roadtotech.me`.
|
||||||
|
|
||||||
|
**Action on `refactor/appctl-rework` (V2 Engine in `~/Projects/active/appctl-refactor`)**:
|
||||||
|
1. In `scripts/appctl_engine_v2.py`, update `get_core_services()`:
|
||||||
|
- Change `stalwart` domain from `f"mail.{HOMELAB_DOMAIN}"` to `f"smtp.{HOMELAB_DOMAIN}"`.
|
||||||
|
- Remove the `snappymail` `CoreService` entry (SnappyMail will now be discovered dynamically as a `SitesApp` in `~/Sites/snappymail`).
|
||||||
|
- Remove the deprecated `portainer` `CoreService` entry.
|
||||||
|
2. Run `pytest tests/unit/test_appctl_engine_v2.py` to confirm test suite remains green.
|
||||||
|
3. Commit to `refactor/appctl-rework` locally. **Do not merge into `main`**.
|
||||||
|
|
||||||
|
#### Step 1.8: Production Cutover & Verification
|
||||||
|
Deploy the Core update:
|
||||||
|
```bash
|
||||||
|
ssh server-local "cd ~/Core && docker compose up -d stalwart && docker rm -f snappymail"
|
||||||
|
```
|
||||||
|
Start the new SnappyMail workload:
|
||||||
|
```bash
|
||||||
|
ssh server-local "cd ~/Sites/snappymail && docker compose up -d"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Step 1.9: Verification Checklist
|
||||||
|
- [ ] `https://smtp.roadtotech.me`: Stalwart WebAdmin loads, TLS certificate valid.
|
||||||
|
- [ ] `https://mail.roadtotech.me`: SnappyMail webmail interface loads, TLS certificate valid.
|
||||||
|
- [ ] SnappyMail authenticates via LLDAP credentials against Stalwart (`stalwart:993` / IMAPS).
|
||||||
|
- [ ] User address books, signatures, and custom folder configurations are intact.
|
||||||
|
- [ ] Inbound/outbound email test succeeds.
|
||||||
|
- [ ] Diun notification delivery test succeeds (`stalwart:465` with TLS).
|
||||||
|
- [ ] `appctl list` shows `stalwart` under Core and `snappymail` under Workloads.
|
||||||
|
|
||||||
|
#### Step 1.10: Rollback Procedure (If issues occur)
|
||||||
|
If webmail fails or state corruption is suspected:
|
||||||
|
```bash
|
||||||
|
# 1. Stop Sites workload
|
||||||
|
ssh server-local "cd ~/Sites/snappymail && docker compose down"
|
||||||
|
|
||||||
|
# 2. Revert Core/docker-compose.yml changes via Git
|
||||||
|
ssh server-local "cd ~/Core && git checkout HEAD -- docker-compose.yml"
|
||||||
|
|
||||||
|
# 3. Bring Core stack back up (restoring original mail.roadtotech.me & webmail.roadtotech.me)
|
||||||
|
ssh server-local "cd ~/Core && docker compose up -d"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Phase 2: GitOps Privilege & Authority Hardening
|
||||||
|
|
||||||
|
### Deliverable 2.1: Core Authoritative Repository Registry
|
||||||
|
Create `Core/config/deployments.yaml` as the sole authority for repository identity and filesystem location. The registry answers **WHO** and **WHERE**; the workload's `app.yaml` answers **WHAT** deployment intent to execute.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Core/config/deployments.yaml — Authoritative Repository Identity Registry
|
||||||
|
# Owns: repository identity, canonical filesystem path, coarse admission mode.
|
||||||
|
# Does NOT own: deployment strategy, branch, healthchecks (those belong to app.yaml).
|
||||||
|
|
||||||
|
schemaVersion: "1.0"
|
||||||
|
repositories:
|
||||||
|
snappymail:
|
||||||
|
path: "/home/kiskaadee/Sites/snappymail"
|
||||||
|
mode: workload
|
||||||
|
gitea:
|
||||||
|
path: "/home/kiskaadee/Sites/gitea"
|
||||||
|
mode: workload
|
||||||
|
jellyfin:
|
||||||
|
path: "/home/kiskaadee/Sites/jellyfin"
|
||||||
|
mode: workload
|
||||||
|
second-brain:
|
||||||
|
path: "/home/kiskaadee/Brain"
|
||||||
|
mode: data-vault
|
||||||
|
```
|
||||||
|
|
||||||
|
**Ownership Split**:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Core registry (deployments.yaml)
|
||||||
|
= WHO is admitted / WHERE it lives / WHAT mode (workload vs data-vault)
|
||||||
|
|
||||||
|
Workload manifest (app.yaml)
|
||||||
|
= WHAT deployment intent (strategy, branch, healthcheck, metadata)
|
||||||
|
|
||||||
|
GitOps dispatcher
|
||||||
|
= HOW that intent is executed safely
|
||||||
|
```
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> Registry paths must be absolute. Python's `Path()` does not perform shell-style tilde expansion; `~/Sites/snappymail` resolves incorrectly. The implementation must use `Path(raw_path).expanduser().resolve()` or store fully expanded paths.
|
||||||
|
|
||||||
|
### Deliverable 2.2: Refactor `gitops_dispatcher.py` Admission Pipeline
|
||||||
|
1. Invert trust boundary: Replace dynamic scanning of `app.yaml` aliases with strict lookup in `Core/config/deployments.yaml`.
|
||||||
|
2. Explicitly reject duplicate aliases and path traversal.
|
||||||
|
3. Enforce directory containment strictly within `~/Sites` or designated data vaults.
|
||||||
|
4. Execute Brain sync with `strategy: pull-only` (isolated from Docker socket).
|
||||||
|
|
||||||
|
### Deliverable 2.3: Systemd Confinement for `homelab-gitops`
|
||||||
|
Update `Core/nixos/modules/homeserver.nix`:
|
||||||
|
```nix
|
||||||
|
systemd.services.homelab-gitops = {
|
||||||
|
description = "Homelab GitOps Webhook Dispatcher";
|
||||||
|
wantedBy = [ "multi-user.target" ];
|
||||||
|
after = [ "network.target" "docker.service" ];
|
||||||
|
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "simple";
|
||||||
|
User = "kiskaadee"; # Transitioning to sandboxed profile
|
||||||
|
WorkingDirectory = "/home/kiskaadee/Core";
|
||||||
|
ExecStart = "${pkgs.python3}/bin/python3 /home/kiskaadee/Core/scripts/gitops_dispatcher.py --listen 127.0.0.1 --port 9000";
|
||||||
|
Restart = "always";
|
||||||
|
RestartSec = "5s";
|
||||||
|
|
||||||
|
# Sandboxing & Confinement
|
||||||
|
ProtectSystem = "strict";
|
||||||
|
ProtectHome = "read-only";
|
||||||
|
ReadWritePaths = [
|
||||||
|
"/home/kiskaadee/Sites"
|
||||||
|
"/home/kiskaadee/Brain"
|
||||||
|
"/home/kiskaadee/.local/state/homelab/gitops"
|
||||||
|
"/run/homelab-gitops"
|
||||||
|
];
|
||||||
|
NoNewPrivileges = true;
|
||||||
|
PrivateTmp = true;
|
||||||
|
CapabilityBoundingSet = "";
|
||||||
|
AmbientCapabilities = "";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deliverable 2.4: Workload Compose Security Policy
|
||||||
|
The GitOps executor processes workload-authored `docker-compose.yml` files. A workload Compose file is itself a capability declaration and must be validated against Core security invariants before deployment.
|
||||||
|
|
||||||
|
**Pre-deployment validation must reject workload Compose files containing:**
|
||||||
|
- `privileged: true`
|
||||||
|
- `devices:` host device mappings
|
||||||
|
- `network_mode: host` or `pid: host` or `ipc: host`
|
||||||
|
- Direct Docker socket bind mounts (`/var/run/docker.sock`)
|
||||||
|
- `cap_add:` beyond a defined allowlist
|
||||||
|
- `security_opt:` overrides
|
||||||
|
- Arbitrary host path bind mounts outside the workload's own directory
|
||||||
|
|
||||||
|
**Implementation**:
|
||||||
|
1. Extend the existing `tests/security/` test suite to validate workload Compose files, not just `Core/docker-compose.yml`.
|
||||||
|
2. Add a pre-deployment Compose policy check in `gitops_dispatcher.py` that runs the same validations before executing `docker compose up`.
|
||||||
|
3. Define an explicit denied-capability list in `Core/config/compose-policy.yaml` or equivalent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Phase 3: Manifest Contract Convergence & appctl-v2 Integration
|
||||||
|
|
||||||
|
Phase 3 is the **deliberate convergence point** between Track A (Homelab Architecture) and Track B (appctl-v2 Refactoring). At this milestone, the separate manifest models and YAML parsers converge into a single authoritative module (`core_manifest.py`), and `appctl-v2` is merged into `main`.
|
||||||
|
|
||||||
|
### Deliverable 3.1: Unified Manifest Parser (`core_manifest.py`)
|
||||||
|
Create a shared, strictly typed Python module (`Core/scripts/core_manifest.py`) implementing:
|
||||||
|
- Dataclass models (`WorkloadManifest`, `NetworkConfig`, `DeploymentConfig`, `HealthcheckConfig`).
|
||||||
|
- Strict schema enforcement: Rejection of unknown top-level fields.
|
||||||
|
- Schema version gating (`schemaVersion: "1.0"`).
|
||||||
|
- Replaces duplicate `parse_yaml_simple()` across `gitops_dispatcher.py` and old `appctl_engine.py`.
|
||||||
|
|
||||||
|
### Deliverable 3.2: Declarative Intent Transition
|
||||||
|
Deprecate procedural action vectors:
|
||||||
|
```text
|
||||||
|
OLD: actions: ["git_pull", "compose_up", "compose_build"]
|
||||||
|
NEW: deployment:
|
||||||
|
strategy: compose
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deliverable 3.3: Sites Manifest Migration
|
||||||
|
Update all manifests in `~/Sites/*/app.yaml` to schema v1.0.
|
||||||
|
|
||||||
|
### Deliverable 3.4: appctl-v2 Integration & Controlled Convergence
|
||||||
|
|
||||||
|
To ensure reproducibility and zero merge churn between divergent branches, the convergence of Track B into Track A follows a **strict direction of integration** with a defined origin for `core_manifest.py`.
|
||||||
|
|
||||||
|
#### The Origin & Direction Rule
|
||||||
|
- **Origin**: `core_manifest.py` originates authoritatively on `main` (under Deliverables 3.1–3.3) where it is immediately tested against `gitops_dispatcher.py` and the 35 architecture invariants.
|
||||||
|
- **Direction**: `main` $\rightarrow$ `refactor/appctl-rework` (cherry-pick contract commit) $\rightarrow$ adapt in worktree $\rightarrow$ `main` (merge refactored engine).
|
||||||
|
|
||||||
|
#### The 6-Step Controlled Convergence Runbook
|
||||||
|
1. **Lock Prerequisites on `main`**:
|
||||||
|
Ensure P1 (mail topology), P2 (GitOps authority & Compose security policy), and Deliverables 3.1–3.3 (`core_manifest.py` schema & Sites manifests) are committed and green on `main`.
|
||||||
|
2. **Isolate Contract Commit**:
|
||||||
|
Identify the atomic commit on `main` that introduces `Core/scripts/core_manifest.py` (e.g. `feat(core): introduce unified core_manifest parser`).
|
||||||
|
3. **Bring Contract into Worktree (`refactor/appctl-rework`)**:
|
||||||
|
In `/home/kiskaadee/Projects/active/appctl-refactor`, bring in the contract commit via cherry-pick:
|
||||||
|
```bash
|
||||||
|
cd ~/Projects/active/appctl-refactor
|
||||||
|
git cherry-pick <commit-sha-of-core_manifest>
|
||||||
|
```
|
||||||
|
*(Track B now has the identical, immutable manifest parser without absorbing unrelated P1/P2 host churn).*
|
||||||
|
4. **Adapt `appctl-v2` to Shared Parser**:
|
||||||
|
Refactor `scripts/appctl_engine_v2.py` to ingest manifests via `core_manifest.py` instead of its standalone `load_manifest()` seam. Update `tests/unit/test_appctl_engine_v2.py` fixtures to match.
|
||||||
|
5. **Hermetic Test Gate in Worktree**:
|
||||||
|
Verify 100% compliance within `~/Projects/active/appctl-refactor`:
|
||||||
|
```bash
|
||||||
|
pytest tests/unit/test_appctl_engine_v2.py
|
||||||
|
ruff check .
|
||||||
|
pyright
|
||||||
|
python3 scripts/appctl_engine_v2.py resolve snappymail
|
||||||
|
```
|
||||||
|
Ensure `cmd_resolve` emits the exact JSON schema consumed by `scripts/appctl`: required keys `name`, `dir_path`, `type`, `domain`, plus contextual keys `container` and `env`. Verify that this is guarded by an automated test fixture.
|
||||||
|
6. **Controlled Integration Merge to `main`**:
|
||||||
|
- On `refactor/appctl-rework`, promote `scripts/appctl_engine_v2.py` to `scripts/appctl_engine.py` so the branch carries the full engine replacement natively.
|
||||||
|
- Merge `refactor/appctl-rework` into `main` (resolving only expected integration conflicts).
|
||||||
|
- Run full regression suite on the resulting `main`:
|
||||||
|
```bash
|
||||||
|
cd ~/Homelab/Core
|
||||||
|
./scripts/test
|
||||||
|
nix flake check
|
||||||
|
```
|
||||||
|
- Verify live CLI behavior: `appctl list`, `appctl info snappymail`, `appctl sync`.
|
||||||
|
- Decommission the worktree and declare Milestone P3 complete.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Phase 4: Platform Lifecycle & Readiness Contracts
|
||||||
|
|
||||||
|
### Deliverable 4.1: Readiness Probes for Core Services
|
||||||
|
Every Core service that is a dependency of another service must expose a deterministic readiness signal via a Compose `healthcheck` block. The specific probe mechanism is chosen during implementation based on each image's available tools and version:
|
||||||
|
|
||||||
|
**Investigation targets** (verify against actual image capabilities before committing):
|
||||||
|
- **Traefik**: Built-in ping endpoint or CLI healthcheck
|
||||||
|
- **socket-proxy**: HTTP version endpoint on internal port
|
||||||
|
- **LLDAP**: Built-in healthcheck subcommand or TCP port probe
|
||||||
|
- **Authelia**: Built-in healthcheck subcommand
|
||||||
|
- **Stalwart**: TCP port probes on critical protocol ports (465, 993) or HTTP readiness endpoint
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> These are starting points for implementation research, not architectural commitments. The correct probe for each service depends on the container image version, available utilities, and startup characteristics discovered during P4 implementation.
|
||||||
|
|
||||||
|
### Deliverable 4.2: Dependency Readiness Gating
|
||||||
|
Update service `depends_on` declarations to enforce health conditioning:
|
||||||
|
```yaml
|
||||||
|
depends_on:
|
||||||
|
lldap:
|
||||||
|
condition: service_healthy
|
||||||
|
socket-proxy:
|
||||||
|
condition: service_healthy
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Phase 5: Deployment Truth & Historical Ledger
|
||||||
|
|
||||||
|
### Deliverable 5.1: Structured Deployment State Model
|
||||||
|
Update `~/.local/state/homelab/gitops/<repo>.status` to record complete revision facts:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"target": "snappymail",
|
||||||
|
"requested_revision": "9a8b7c6d5e4f3a2b1c0d",
|
||||||
|
"deployed_revision": "9a8b7c6d5e4f3a2b1c0d",
|
||||||
|
"previous_revision": "1f2e3d4c5b6a7b8c9d0e",
|
||||||
|
"status": "success",
|
||||||
|
"failure_stage": null,
|
||||||
|
"start_time": "2026-09-26T14:30:00Z",
|
||||||
|
"end_time": "2026-09-26T14:30:22Z",
|
||||||
|
"duration_seconds": 22.4,
|
||||||
|
"superseded": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deliverable 5.2: `appctl` Status & History Subcommand
|
||||||
|
|
||||||
|
**Note**: Requires completion of the [appctl refactor](../appctl/appctl-engine-v2-refactoring.md).
|
||||||
|
|
||||||
|
Expose deployment state directly through CLI:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
appctl history snappymail
|
||||||
|
appctl status --all
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Epistemic Verification & Second Brain Documentation
|
||||||
|
|
||||||
|
Following Homelab Agent Guidelines:
|
||||||
|
- Any operational anomalies encountered during the migration must be captured in the Second Brain inbox (`inbox/YYYY-MM-DD-<slug>-debug.md`).
|
||||||
|
- Upon successful validation of Phase 1 (Mail topology realignment), record an operational snapshot documenting verified certificates, DNS routing, and state migration proof.
|
||||||
+5
-3
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
type: plan
|
type: plan
|
||||||
status: active
|
status: completed
|
||||||
project: homelab
|
project: homelab
|
||||||
tags:
|
tags:
|
||||||
- architecture
|
- architecture
|
||||||
@@ -14,12 +14,14 @@ tags:
|
|||||||
|
|
||||||
# Architecture Consolidation & Hardening Roadmap v2
|
# Architecture Consolidation & Hardening Roadmap v2
|
||||||
|
|
||||||
> Supersedes the [original phased implementation plan](../archive/architecture-consolidation-roadmap.md).
|
> [!NOTE]
|
||||||
|
> Superseded by [Architecture Consolidation & Hardening Roadmap v3](architecture-consolidation-roadmap-v3.md).
|
||||||
|
> Supersedes the [original phased implementation plan](architecture-consolidation-roadmap.md).
|
||||||
> Integrates reviewer feedback across fourteen areas: trust model, manifest
|
> Integrates reviewer feedback across fourteen areas: trust model, manifest
|
||||||
> contracts, privilege separation, protocol versioning, invariant testing, and
|
> contracts, privilege separation, protocol versioning, invariant testing, and
|
||||||
> deployment observability.
|
> deployment observability.
|
||||||
>
|
>
|
||||||
> 📋 **Companion Execution Guide**: [Architecture Consolidation & Hardening Implementation Guide](architecture-consolidation-implementation-guide.md)
|
> 📋 **Companion Execution Guide**: [Architecture Consolidation & Hardening Implementation Guide v2](architecture-consolidation-implementation-guide-v2.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -0,0 +1,557 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: superseded
|
||||||
|
superseded_by: architecture-consolidation-roadmap-v4.md
|
||||||
|
project: homelab
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- security
|
||||||
|
- operations
|
||||||
|
- homelab
|
||||||
|
- gitops
|
||||||
|
- roadmap
|
||||||
|
- consolidation
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
>
|
||||||
|
> **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 (Superseded)**: [`architecture-consolidation-implementation-guide-v3.md`](architecture-consolidation-implementation-guide-v3.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
The homelab appliance (`roadtotech.me`) has crossed a defining evolutionary threshold. When Roadmap v2 was drafted, the primary challenge was securing a rudimentary GitOps webhook receiver and recovering architectural legibility after migrating to NixOS.
|
||||||
|
|
||||||
|
Between commit `4c9e7a4` and commit `246b587`, the platform rapidly matured:
|
||||||
|
- **P0 GitOps hardening was sealed and frozen**: HMAC authentication, branch and event admission, closed execution vectors, serialization locks, and revision-consistent manifest validation were fully implemented.
|
||||||
|
- **Platform capabilities expanded dramatically**: Stalwart mail server (SMTP, SMTPS, IMAPS, ManageSieve), SnappyMail webmail client, LLDAP user directory, Dozzle container log viewer with Authelia forward proxy, Diun automated image notification with authenticated SMTP delivery, and Gitea Actions containerized CI runners were brought into production.
|
||||||
|
- **Portainer was cleanly deprecated and excised**, eliminating an uncontrolled administrative attack surface and Docker socket client.
|
||||||
|
- **Automated architectural invariant testing was established**, running 35 automated security/structural checks in pure Nix `flake check` and pre-commit hooks.
|
||||||
|
|
||||||
|
The system is no longer simply "a GitOps receiver with a few containers." It is now **a platform with multiple concurrent control loops, shared platform capabilities, and independently deployed application workloads**.
|
||||||
|
|
||||||
|
Consequently, **Roadmap v2 cannot simply be resumed at milestone P1**. Mechanically executing v2's remaining checklist would apply obsolete assumptions to a system that has already outgrown them.
|
||||||
|
|
||||||
|
Roadmap v3 establishes a fresh architectural re-baseline, clarifies service taxonomy and controller authority, realigns mail infrastructure between Core and Sites without data loss, establishes an authoritative repository registry, converges the manifest contract into a single typed model, and formalizes platform lifecycle and deployment truth.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Core Architectural Principles
|
||||||
|
|
||||||
|
1. **Platform Legibility Over Elaboration**: The architectural hardening does not introduce new dependencies, or unjustified complexity layers (microservices, external message queues, or distributed databases). It defines exact boundaries, contracts, and failure semantics for the components already running.
|
||||||
|
2. **Platform Capabilities vs. Client Workloads**: Shared infrastructure consumed by multiple services (e.g., directory services, ingress, mail delivery) belongs to Core. Applications presenting user interfaces or single-purpose tools consuming those capabilities belong to Sites.
|
||||||
|
3. **Core Registry Authority**: The repository being admitted must never define its own admission trust boundary. Repository identities, aliases, and paths are authoritatively owned by Core, not derived from unvetted workload manifests.
|
||||||
|
4. **Single Manifest Contract**: There is exactly one schema and typed parser for workload manifests (`app.yaml`). `appctl`, `gitops_dispatcher`, and dashboard generators must consume the same verified contract.
|
||||||
|
5. **Deployment Truth**: The deployment engine must record true runtime facts: requested revision, actual checked-out revision, prior revision, execution duration, and failure stage.
|
||||||
|
6. **Zero-Data-Loss Migration**: State-bearing components are relocated across architectural boundaries through staged, reversible migrations with verified pre-flight snapshots, non-destructive file staging, and validated cutover windows.
|
||||||
|
7. **Concurrent Refactoring Tracks & Seam Isolation**: Internal engine refactors (such as the `appctl-v2` modernization on branch `refactor/appctl-rework`) proceed in parallel with architecture consolidation on `main`. Production transitions remain serialized. Architectural changes apply minimal compatibility patches to legacy code on `main`, while refactoring tracks preserve defined architectural seams until deliberate convergence at milestone P3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 1: Architecture Re-Baseline & System Taxonomy
|
||||||
|
|
||||||
|
The legacy "Control Plane vs. Data Plane" and v2's "Three-Layer Architecture" are insufficient to capture the modern platform. Core is not a single homogeneous container stack; it spans host primitives, ingress routing, identity, core capabilities, and operational observers.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TB
|
||||||
|
subgraph CONTROLLERS["CROSS-CUTTING CONTROL LOOPS"]
|
||||||
|
direction LR
|
||||||
|
CTL_SYS["NixOS / systemd<br/>(Host Lifecycle)"]
|
||||||
|
CTL_GOP["homelab-gitops<br/>(Event Deployment)"]
|
||||||
|
CTL_APP["appctl CLI<br/>(Operator Lifecycle)"]
|
||||||
|
CTL_CI["Gitea act_runner<br/>(Pre-merge CI)"]
|
||||||
|
CTL_WT["Watchtower / Diun<br/>(Image Observers)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph PLATFORM["HOMELAB CORE (Platform Appliance)"]
|
||||||
|
direction TB
|
||||||
|
|
||||||
|
subgraph SEC_EDGE["Edge & Security Primitives"]
|
||||||
|
direction LR
|
||||||
|
TR["Traefik v3<br/>(Reverse Proxy / TLS)"]
|
||||||
|
SP["Socket-Proxy<br/>(Restricted Docker API)"]
|
||||||
|
AUTH["Authelia v4<br/>(SSO / Forward Proxy)"]
|
||||||
|
LDAP["LLDAP<br/>(Lightweight Directory)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph SEC_CAP["Core Platform Capabilities"]
|
||||||
|
direction LR
|
||||||
|
STAL["Stalwart Mail Server<br/>(smtp.roadtotech.me)<br/>SMTP / SMTPS / IMAP / Sieve"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph SEC_OPS["Platform Operations & Observability"]
|
||||||
|
direction LR
|
||||||
|
DASH["Homepage<br/>(dashboard.roadtotech.me)"]
|
||||||
|
DOZ["Dozzle<br/>(logs.roadtotech.me)"]
|
||||||
|
DIUN["Diun<br/>(Image Update Alerts)"]
|
||||||
|
WT["Watchtower<br/>(Auto-Updater)"]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph SITES["WORKLOAD PLANE (~/Sites/*)"]
|
||||||
|
direction LR
|
||||||
|
SITE_MAIL["SnappyMail Webmail<br/>(mail.roadtotech.me)"]
|
||||||
|
SITE_GIT["Gitea Git Forge<br/>(git.roadtotech.me)"]
|
||||||
|
SITE_MEDIA["Jellyfin Media<br/>(jellyfin.roadtotech.me)"]
|
||||||
|
SITE_DOCS["Documentation / Sites<br/>(doc2site, courses, etc.)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph HOST["HOST FOUNDATION (NixOS)"]
|
||||||
|
direction LR
|
||||||
|
NIX["NixOS / Linux 6.6 LTS"]
|
||||||
|
SOPS["SOPS / age Secrets Projection"]
|
||||||
|
NET["nftables Firewall / Dynu DDNS"]
|
||||||
|
DOCK["Docker 27 / compose-net bridge"]
|
||||||
|
end
|
||||||
|
|
||||||
|
CONTROLLERS -.-> PLATFORM
|
||||||
|
CONTROLLERS -.-> SITES
|
||||||
|
HOST --> PLATFORM
|
||||||
|
HOST --> SITES
|
||||||
|
SEC_CAP -.->|"SMTP/IMAP"| SITES
|
||||||
|
SEC_EDGE -.->|"Auth/Ingress"| SITES
|
||||||
|
```
|
||||||
|
|
||||||
|
### The 5-Tier Service Taxonomy
|
||||||
|
|
||||||
|
| Tier | Scope | Components | Architectural Invariant |
|
||||||
|
| :-------------------------------- | :----------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| **1. Host Foundation** | Machine runtime & security boundary | NixOS, systemd, Docker daemon, nftables, SOPS secrets, Dynu DDNS | Declarative in `Core/nixos`. No manual host modifications over SSH. |
|
||||||
|
| **2. Edge & Security Primitives** | Shared ingress, identity, socket isolation | Traefik, socket-proxy, Authelia, LLDAP | Mandatory security baseline. All internet traffic enters through Traefik. Docker socket access restricted via socket-proxy. |
|
||||||
|
| **3. Core Platform Capabilities** | Shared multi-consumer services | Stalwart Mail Server (`smtp.roadtotech.me`) | Provides an authoritative protocol service consumed by other platform and workload components. |
|
||||||
|
| **4. Platform Operations** | Management, observability, telemetry | Homepage, Dozzle, Diun, Watchtower | Observes and administers the appliance. Homepage derives dashboard state from manifests. |
|
||||||
|
| **5. Workloads (Sites)** | Independent applications & UI frontends | SnappyMail (`mail.`), Gitea, Jellyfin, Stirling, Courses. New applications can be added without breaking with the Core functionality. | Reside in `~/Sites/<app>`. Independently versioned, deployed via GitOps or `appctl`, isolated lifecycle. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 2: Controller Authority Matrix
|
||||||
|
|
||||||
|
With multiple control loops interacting on the host, ambiguous ownership causes silent configuration drift or race conditions. Roadmap v3 defines the authoritative controller for every system resource.
|
||||||
|
|
||||||
|
| Resource / Layer | Authoritative Controller | Permitted Secondary Actors | Prohibited Actors | Conflict Resolution Policy |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **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 Definition** | Workload Git (`main` branch) | GitOps worker (pulls `origin/main`) | Direct container modification | Workload repository owns Compose file and `app.yaml`. |
|
||||||
|
| **Workload Runtime Lifecycle** | `homelab-gitops` & `appctl` | Docker daemon (auto-restart) | Watchtower (for pinned workloads) | Per-target filesystem lock (`.gitops.lock`) serializes `appctl` and GitOps execution. |
|
||||||
|
| **Container Image Versions** | Workload Manifest / Git | Watchtower (auto-pull for tagged), Diun (alerts) | Unverified registry pulls | Manifest tag pins desired release; Watchtower updates minor/patch if unpinned. |
|
||||||
|
| **Mailbox Data & Routing** | Stalwart (`/var/lib/stalwart`) | Backup automation | SnappyMail, Diun | Stalwart owns storage and protocol ports (25, 465, 587, 993, 4190). |
|
||||||
|
| **Webmail Client State** | SnappyMail (`_data_` volume) | Backup automation | Stalwart | SnappyMail owns user settings, contacts, session caches. Does NOT own mailboxes. |
|
||||||
|
| **Dashboard Catalog** | `appctl sync` / engine | Homepage container (consumes config) | Direct edits to Homepage YAML | Generated deterministically from Core service list + discovered workload manifests. |
|
||||||
|
|
||||||
|
### Resource & State Ownership Matrix
|
||||||
|
|
||||||
|
The controller matrix defines who may *change* resources. This complementary matrix defines who *owns* persistent state, where the desired state lives, and how runtime state is derived:
|
||||||
|
|
||||||
|
| Resource | Owner | Location | Desired State Source | Runtime State |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **NixOS host config** | Core | `Core/nixos/` | Git | Applied via `nixos-rebuild` |
|
||||||
|
| **Core Compose definition** | Core | `Core/docker-compose.yml` | Git | Docker daemon |
|
||||||
|
| **Stalwart config** | Core | `Core/config/stalwart/etc` | Git (seed) + runtime | Filesystem |
|
||||||
|
| **Stalwart mail store** | Stalwart | `Core/config/stalwart/data` | — (runtime-generated) | Filesystem |
|
||||||
|
| **SnappyMail app state** | SnappyMail | `Sites/snappymail/data` | — (runtime-generated) | Workload filesystem |
|
||||||
|
| **Traefik dynamic config** | Core | Compose labels + file providers | Git | Container runtime |
|
||||||
|
| **LLDAP user directory** | LLDAP | `Core/config/lldap` | — (runtime-generated) | Filesystem |
|
||||||
|
| **Authelia config** | Core | `Core/config/authelia` | Git | Container runtime |
|
||||||
|
| **Homepage catalog** | `appctl` | `Core/config/homepage/services.yaml` | Generated by `appctl sync` | Filesystem |
|
||||||
|
| **GitOps queue/status** | GitOps | `~/.local/state/homelab/gitops` | — (runtime-generated) | Runtime state files |
|
||||||
|
| **Workload Compose** | Sites | `Sites/<app>/docker-compose.yml` | Git | Container runtime |
|
||||||
|
| **Workload manifest** | Sites | `Sites/<app>/app.yaml` | Git | Parsed at deployment |
|
||||||
|
| **SOPS secrets** | Core | `Core/nixos/secrets.yaml` | Git (encrypted) | `/run/secrets/` (decrypted) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 3: Mail Architecture Rework & Zero-Data-Loss Relocation
|
||||||
|
|
||||||
|
### The Stalwart vs. SnappyMail Separation
|
||||||
|
|
||||||
|
In the current repository (`Core/docker-compose.yml`), both Stalwart and SnappyMail run side-by-side:
|
||||||
|
- Stalwart is mounted at `mail.${DOMAIN}`, exposing ports 25, 465, 587, 993, 4190, with mail storage at `./config/stalwart/data`.
|
||||||
|
- SnappyMail is mounted at `webmail.${DOMAIN}`, routing internally to Stalwart, with state at `./config/snappymail/data`.
|
||||||
|
|
||||||
|
This arrangement violates clean capability-vs-workload boundaries:
|
||||||
|
1. **Stalwart is an infrastructure capability**: It handles inbound/outbound mail flow, DKIM/SPF/DMARC, authenticated submission for platform alerts (Diun), and user directories (LLDAP).
|
||||||
|
2. **SnappyMail is a presentation client**: It is an IMAP/SMTP webmail client. It stores user UI preferences, address books, and session tokens. If SnappyMail is swapped for Roundcube, Thunderbird, or a mobile client, the homelab mail platform remains completely functional.
|
||||||
|
|
||||||
|
### Target Topology
|
||||||
|
|
||||||
|
```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
|
||||||
|
└─────────────────┘ └─────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Public Domain Realignment
|
||||||
|
|
||||||
|
- **Stalwart WebAdmin & Protocol Services**: Moves to `smtp.roadtotech.me` (or `https://smtp.roadtotech.me` for admin UI/JMAP).
|
||||||
|
- Update `STALWART_PUBLIC_URL=https://smtp.${DOMAIN}`.
|
||||||
|
- Update Traefik routing rule: `Host(\`smtp.${DOMAIN}\`)`.
|
||||||
|
- DNS / Reverse Proxy: Traefik handles ACME certificate generation for `smtp.roadtotech.me`.
|
||||||
|
- **SnappyMail Webmail Portal**: Moves to `mail.roadtotech.me` (replacing the legacy `webmail.roadtotech.me`).
|
||||||
|
- Public webmail entrypoint becomes clean and professional: `https://mail.roadtotech.me`.
|
||||||
|
- Traefik routing rule in workload Compose: `Host(\`mail.${DOMAIN}\`)`.
|
||||||
|
|
||||||
|
### Zero-Data-Loss Migration Contract
|
||||||
|
|
||||||
|
Persistent data integrity is an absolute prerequisite:
|
||||||
|
1. **Mailbox and Identity Isolation**: Stalwart data in `./config/stalwart/` is untouched by the SnappyMail relocation. All user emails, folders, sieve filters, and cryptographic keys remain safe in Stalwart.
|
||||||
|
2. **SnappyMail Application State**: SnappyMail stores configurations, cached address books, and custom settings in `/var/lib/snappymail/_data_` (currently mapped to `Core/config/snappymail/data`).
|
||||||
|
3. **Execution Protocol**:
|
||||||
|
- **Freeze**: Stop SnappyMail in Core to prevent concurrent SQLite/file writes.
|
||||||
|
- **Verified Rollback Archive**: Create a compressed archive with permissions and timestamps preserved (`tar -czpf`), generate a checksum (`sha256sum`), and perform a test extraction into a temporary directory to verify archive integrity before proceeding.
|
||||||
|
- **Sites Scaffolding**: Provision `~/Sites/snappymail` with dedicated `app.yaml`, `docker-compose.yml`, and local persistent `data/` volume.
|
||||||
|
- **State Copy & Verification**: Replicate preserved state to the new location without removing Core's original data. Verify source/destination parity: file count, total byte count, recursive checksum or `diff -r` comparison, and ownership/permissions match.
|
||||||
|
- **Cutover & Parallel Rollback**: Launch the new Sites workload, verify authentication and address book integrity against Stalwart, switch Traefik routing, and retain Core's original data and rollback archive for a 14-day rollback window.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 4: GitOps Trust Boundary & Authority Redesign
|
||||||
|
|
||||||
|
### The Inverted Trust Boundary Flaw in v2
|
||||||
|
|
||||||
|
In `Core/scripts/gitops_dispatcher.py` (`get_trusted_repository_mapping()`), the resolver registers:
|
||||||
|
1. Hardcoded data vaults (`~/Brain`).
|
||||||
|
2. Directory names in `~/Sites`.
|
||||||
|
3. `name` and `aliases` extracted dynamically from each workload's `app.yaml`.
|
||||||
|
4. Overrides in `Core/config/deployments.yaml`.
|
||||||
|
|
||||||
|
This creates a serious architectural flaw: **the admitted workload's manifest influences the trusted registry that admits workloads.**
|
||||||
|
A malicious or buggy commit to an existing repository's `app.yaml` could claim `aliases: ["gitea", "dashboard"]`, hijacking webhooks intended for other critical services or causing non-deterministic resolution.
|
||||||
|
|
||||||
|
### The Authoritative Registry Model
|
||||||
|
|
||||||
|
In Roadmap v3, the trust flow is strictly inverted:
|
||||||
|
|
||||||
|
```text
|
||||||
|
1. Gitea Webhook Event (repo: "my-app")
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
2. Core Authoritative Registry (Core/config/deployments.yaml or declarative map)
|
||||||
|
│
|
||||||
|
├── Check: Is "my-app" registered in Core?
|
||||||
|
├── Check: What is its canonical local path? (~/Sites/my-app)
|
||||||
|
└── Check: Reject any alias collisions or path escapes
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
3. Local Filesystem Lock & Git Pull (~/Sites/my-app)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
4. Read app.yaml for Execution Policy ONLY
|
||||||
|
│
|
||||||
|
└── Deployment strategy, branch restrictions, healthchecks
|
||||||
|
```
|
||||||
|
|
||||||
|
- Workload `app.yaml` manifests may define metadata for display (e.g. `displayName`, `description`, `icon`) and deployment configuration (`strategy: compose`, `branch: main`).
|
||||||
|
- Manifests **cannot** define trusted identities, forge aliases, or target filesystem paths.
|
||||||
|
- Repository identity resolution is 100% authoritative and owned by Core.
|
||||||
|
|
||||||
|
### Data Vaults: The Second Brain Question
|
||||||
|
|
||||||
|
`gitops_dispatcher.py` currently hardcodes special execution for `~/Brain` with alias mapping `["second-brain", "Brain", "brain"]` and deployment action `git_pull`.
|
||||||
|
|
||||||
|
**Architectural Decision for v3**:
|
||||||
|
- `~/Brain` is a personal knowledge vault, not an application workload running containerized services.
|
||||||
|
- Including data repositories in the workload deployment engine creates unnecessary privilege overlap.
|
||||||
|
- **Resolution**: Formalize `Brain` as a **designated read-only data vault** within the authoritative registry with a restricted sync strategy (`strategy: pull-only`). It is isolated from Docker socket interactions, has no Compose lifecycle, and cannot execute container commands.
|
||||||
|
|
||||||
|
### Privilege Separation & Systemd Confinement
|
||||||
|
|
||||||
|
Currently, `homelab-gitops.service` runs as user `kiskaadee` with unrestricted read/write access across `/home/kiskaadee`.
|
||||||
|
|
||||||
|
Roadmap v3 introduces a dedicated, least-privilege systemd execution profile:
|
||||||
|
- Dedicated system service user or sandboxed credentials.
|
||||||
|
- `ProtectSystem=strict` with read-only root filesystem.
|
||||||
|
- `ReadWritePaths` restricted strictly to `~/Sites`, `/run/homelab-gitops`, and `~/.local/state/homelab/gitops`.
|
||||||
|
- `NoNewPrivileges=true`, `ProtectHome=read-only` (except explicit state dirs).
|
||||||
|
- Docker API access granted via explicit docker group membership (required for `docker compose up` execution; the read-only socket-proxy is insufficient for deployment commands).
|
||||||
|
|
||||||
|
### Workload Compose as Part of the Trust Boundary
|
||||||
|
|
||||||
|
Closing the shell execution vector (P0) solved one class of arbitrary execution. But the GitOps executor still processes **workload-authored `docker-compose.yml` files** via `docker compose up`. A workload Compose file is itself a capability declaration.
|
||||||
|
|
||||||
|
The architectural question is therefore not merely:
|
||||||
|
|
||||||
|
> "Can GitOps execute arbitrary shell?"
|
||||||
|
|
||||||
|
It is:
|
||||||
|
|
||||||
|
> **"What Docker capabilities can an admitted workload repository cause GitOps to exercise?"**
|
||||||
|
|
||||||
|
A workload Compose file can currently declare capabilities that violate Core security invariants: `privileged: true`, `devices`, `network_mode: host`, `pid: host`, Docker socket bind mounts, `cap_add`, `security_opt`, or arbitrary host path mounts.
|
||||||
|
|
||||||
|
The existing Core security tests enforce these invariants for `Core/docker-compose.yml`, but they do not yet extend to workload Compose files deployed by GitOps.
|
||||||
|
|
||||||
|
Roadmap v3 requires:
|
||||||
|
1. **Pre-deployment Compose policy validation**: Before executing `docker compose up`, the GitOps worker must validate the workload's `docker-compose.yml` against the same security invariants enforced for Core (no privileged containers, no direct socket mounts, no host network/PID, restricted capabilities).
|
||||||
|
2. **Denied capability list**: Explicitly enumerate the Docker Compose directives that workload repositories are prohibited from using.
|
||||||
|
3. **CI-enforced invariants**: Extend the existing test suite to validate workload Compose files against these constraints, not just Core.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 5: Manifest Contract Convergence
|
||||||
|
|
||||||
|
### The Problem: Fragmented Manifest Consumers
|
||||||
|
|
||||||
|
Today, `app.yaml` is parsed inconsistently across the platform:
|
||||||
|
1. `appctl_engine.py` implements a bespoke regex/indentation parser (`parse_yaml_simple`) and ignores deployment policies.
|
||||||
|
2. `gitops_dispatcher.py` implements its own copy of `parse_yaml_simple` and parses procedural action lists (`git_pull`, `compose_up`, `compose_build`).
|
||||||
|
3. Core service inventory is hardcoded directly into `appctl_engine.py` (30+ lines of Python dictionaries).
|
||||||
|
4. Automated tests implement partial validation checks.
|
||||||
|
|
||||||
|
### Target: Unified Typed Model & Single Engine
|
||||||
|
|
||||||
|
```text
|
||||||
|
Workload app.yaml
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────────────────┐
|
||||||
|
│ core_manifest Engine │
|
||||||
|
│ - PyYAML / Strict Parser │
|
||||||
|
│ - Typed Dataclass / Pydantic Model │
|
||||||
|
│ - schemaVersion: "1.0" │
|
||||||
|
│ - Schema Validation & Invariant Checking │
|
||||||
|
└──────────────────────┬───────────────────────┘
|
||||||
|
│
|
||||||
|
┌─────────────┼─────────────┐
|
||||||
|
▼ ▼ ▼
|
||||||
|
appctl GitOps Homepage
|
||||||
|
Lifecycle Deployment Sync
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manifest v1 Contract Specification
|
||||||
|
|
||||||
|
Workloads declare **declarative intent**, not procedural bash/docker commands:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
schemaVersion: "1.0"
|
||||||
|
name: "snappymail"
|
||||||
|
displayName: "SnappyMail"
|
||||||
|
description: "Modern Lightweight Webmail Client"
|
||||||
|
category: "Communication"
|
||||||
|
|
||||||
|
network:
|
||||||
|
ingress: true
|
||||||
|
domain: "mail.roadtotech.me"
|
||||||
|
publishedPort: 8888
|
||||||
|
internalOnly: false
|
||||||
|
|
||||||
|
deployment:
|
||||||
|
strategy: compose
|
||||||
|
branch: main
|
||||||
|
preflight:
|
||||||
|
filesRequired:
|
||||||
|
- docker-compose.yml
|
||||||
|
- data
|
||||||
|
healthcheck:
|
||||||
|
type: http
|
||||||
|
path: "/"
|
||||||
|
expectedStatus: 200
|
||||||
|
timeoutSeconds: 30
|
||||||
|
```
|
||||||
|
|
||||||
|
- Unknown top-level fields are rejected.
|
||||||
|
- Procedural `actions: ["git_pull", "compose_up"]` are deprecated and replaced with declarative `strategy: compose`.
|
||||||
|
- Dynamic alias declarations are disallowed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 6: Platform Lifecycle, Startup Dependencies & Readiness
|
||||||
|
|
||||||
|
The Diun SMTP debugging incident exposed a fundamental operational truth: **Compose container startup order is not service readiness**.
|
||||||
|
|
||||||
|
A container whose process has started may still fail to accept network connections for 15–45 seconds while initializing databases, generating cryptographic keypairs, or binding sockets.
|
||||||
|
|
||||||
|
Roadmap v3 establishes explicit dependency and readiness contracts for Homelab Core:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
NET["Docker Networks<br/>(proxy-net, socket-net)"] --> SP["socket-proxy"]
|
||||||
|
NET --> LDAP["LLDAP Directory"]
|
||||||
|
|
||||||
|
SP --> TR["Traefik Ingress"]
|
||||||
|
LDAP --> AUTH["Authelia SSO"]
|
||||||
|
LDAP --> STAL["Stalwart Mail"]
|
||||||
|
|
||||||
|
STAL -.->|Readiness: Port 465 Ready| DIUN["Diun Alerts"]
|
||||||
|
STAL -.->|"Readiness: Port 993/HTTP Ready"| SNAP["SnappyMail (Sites)"]
|
||||||
|
AUTH -.->|Readiness: Auth Endpoint 200| DASH["Homepage Dashboard"]
|
||||||
|
AUTH -.->|Readiness: Auth Endpoint 200| DOZ["Dozzle Log Viewer"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Core Lifecycle Invariants
|
||||||
|
|
||||||
|
1. **Readiness Requirement**: Every Core service that is a dependency of another service must expose a deterministic readiness signal. The specific probe mechanism (HTTP endpoint, TCP socket, CLI healthcheck command) is chosen during implementation based on the image and version, not prescribed architecturally.
|
||||||
|
2. **Gated Dependency**: Dependent services must use `condition: service_healthy` in `depends_on`, ensuring they do not initiate client transactions against half-initialized platforms.
|
||||||
|
3. **Decoupled Platform Recovery**: Core services must restart independently without cascading failures if an upstream capability is temporarily restarting.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 7: Parallel Track Coordination (Architecture vs. appctl-v2)
|
||||||
|
|
||||||
|
A major source of potential friction is the concurrent development of the **appctl-v2 modernization** (tracked on branch `refactor/appctl-rework` in worktree `~/Projects/active/appctl-refactor`) alongside the **Homelab Architecture Consolidation** (tracked on `main`).
|
||||||
|
|
||||||
|
These two tracks operate with fundamentally different concerns:
|
||||||
|
- **Track A (Production Architecture)**: Alters the host and service topology (mail migration P1, GitOps privilege P2, platform lifecycle P4). It mutates production state, requires human-controlled cutover, and runs from `main`.
|
||||||
|
- **Track B (Implementation Modernization)**: Replaces the internal engine implementation (`appctl_engine_v2.py` with typed domain objects, PyYAML, and TDD tests). It is an internal refactor that must preserve runtime contracts.
|
||||||
|
|
||||||
|
Treating `appctl-v2` as a prerequisite for early consolidation would unnecessarily block P1 and P2. Conversely, continuously cross-merging the architecture branch into the refactoring branch would create destructive merge conflicts in rapidly changing files.
|
||||||
|
|
||||||
|
### The Dependency & Convergence Graph
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌─────────────────────────┐
|
||||||
|
│ appctl-v2 refactor │
|
||||||
|
│ (refactor/appctl-rework)│
|
||||||
|
│ independent workstream │
|
||||||
|
└────────────┬────────────┘
|
||||||
|
│
|
||||||
|
│ integration point
|
||||||
|
▼
|
||||||
|
┌─────────────────────────┐
|
||||||
|
│ Manifest / domain model │
|
||||||
|
│ + Core inventory model │
|
||||||
|
└─────────────────────────┘
|
||||||
|
|
||||||
|
main
|
||||||
|
│
|
||||||
|
├── P1: Mail topology migration
|
||||||
|
│ └── minimal compatibility change to current appctl
|
||||||
|
│
|
||||||
|
├── P2: GitOps authority hardening
|
||||||
|
│ └── does not require appctl-v2
|
||||||
|
│
|
||||||
|
└── P3: Manifest convergence
|
||||||
|
└── integrate appctl-v2 here (CONVERGENCE POINT)
|
||||||
|
```
|
||||||
|
|
||||||
|
### The Three Operating Rules
|
||||||
|
|
||||||
|
1. **Keep `appctl-v2` isolated**: Work proceeds in its dedicated worktree toward its own deliverables. It is not rebased or merged into `main` until its seams are stable.
|
||||||
|
2. **Keep architectural migrations rooted on `main`**: For P1 (mail migration), apply only the minimal required compatibility patch to legacy `scripts/appctl_engine.py` on `main`: change `stalwart` domain to `smtp.roadtotech.me` and remove `snappymail` from `get_core_services()`.
|
||||||
|
3. **Do not duplicate implementation work**: When `appctl-v2` converges at P3, apply the semantic change directly to its typed registry (`CoreService`) rather than attempting a mechanical code merge of legacy `appctl_engine.py`.
|
||||||
|
|
||||||
|
### The 5 Stable Integration Seams
|
||||||
|
|
||||||
|
`appctl-v2` must preserve these 5 architectural seams until convergence:
|
||||||
|
|
||||||
|
| Seam | Scope | Contract Guarantee |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **1. CLI Syntax** | `scripts/appctl` | Bash caller flags, subcommands (`list`, `info`, `up`, `down`, `sync`), and exits remain identical. |
|
||||||
|
| **2. `resolve` JSON Contract** | Emitter $\rightarrow$ Caller | `cmd_resolve` emits the exact JSON schema consumed by `scripts/appctl`: required keys `name`, `dir_path`, `type` (`"app"` or `"core_service"`), `domain`, plus contextual keys `container` and `env`. Backed by an automated test fixture. |
|
||||||
|
| **3. Canonical Identity** | Service names | Service identifiers remain stable within the systems that own them; Core services and Sites workloads use their canonical names consistently. |
|
||||||
|
| **4. Core vs. Sites Taxonomy** | Classification | Core services represent platform capabilities; Sites represent independent workloads. No blurred boundaries. |
|
||||||
|
| **5. Homepage Sync Semantics** | Output generation | Compiles `Core/config/homepage/services.yaml` from Core inventory + discovered Sites manifests without schema break. |
|
||||||
|
|
||||||
|
### P3 Controlled Convergence Mechanics
|
||||||
|
|
||||||
|
To prevent merge churn and ambiguity over code ownership, Milestone P3 enforces a **strict direction of integration**:
|
||||||
|
|
||||||
|
- **Contract Origin on `main`**: `core_manifest.py` is developed and validated on `main` first (Deliverables 3.1–3.3), ensuring direct compatibility with `gitops_dispatcher.py` and existing test suites.
|
||||||
|
- **Direction of Integration**: `main` $\rightarrow$ `refactor/appctl-rework` $\rightarrow$ `main`.
|
||||||
|
- **The Convergence Sequence**:
|
||||||
|
1. Complete P2 and author `core_manifest.py` on `main`.
|
||||||
|
2. Cherry-pick the isolated `core_manifest.py` commit into `refactor/appctl-rework` (`~/Projects/active/appctl-refactor`).
|
||||||
|
3. Adapt `appctl_engine_v2.py` to ingest via `core_manifest.py`.
|
||||||
|
4. Run hermetic test verification in worktree (`pytest`, `ruff`, `pyright`, `cmd_resolve` contract check).
|
||||||
|
5. On `refactor/appctl-rework`, promote `scripts/appctl_engine_v2.py` to `scripts/appctl_engine.py` so the branch carries the full replacement.
|
||||||
|
6. Merge `refactor/appctl-rework` into `main`, resolve any expected integration conflicts, run full `./scripts/test` and `nix flake check` on `main`, verify live CLI behavior, and decommission the worktree.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 8: Roadmap Execution Phases
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ P0: Architecture Re-Baseline & Structural Catalog │
|
||||||
|
│ - Service Taxonomy & Ownership Baseline │
|
||||||
|
│ - Controller Authority Matrix │
|
||||||
|
│ - Dependency Graph & Readiness Contracts │
|
||||||
|
└──────────────────────────────┬──────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌──────────────────────────────▼──────────────────────────────┐
|
||||||
|
│ P1: Mail Topology Realignment & Zero-Data-Loss Migration │
|
||||||
|
│ - Stalwart to smtp.roadtotech.me │
|
||||||
|
│ - SnappyMail State Backup & Transfer to ~/Sites │
|
||||||
|
│ - Workload Scaffolding & mail.roadtotech.me Cutover │
|
||||||
|
│ - Minimal compatibility patch to legacy appctl_engine │
|
||||||
|
└──────────────────────────────┬──────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌──────────────────────────────▼──────────────────────────────┐
|
||||||
|
│ P2: GitOps Privilege & Authority Hardening │
|
||||||
|
│ - Authoritative Repository Registry (Core-owned) │
|
||||||
|
│ - Inverted Trust Boundary & Collision Rejection │
|
||||||
|
│ - 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 Engine │
|
||||||
|
│ - Declarative Deployment Intent (strategy: compose) │
|
||||||
|
│ - 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 │
|
||||||
|
│ - Requested vs. Actual vs. Prior Revision Tracking │
|
||||||
|
│ - Atomic Status Ledger (duration, phase, failure cause) │
|
||||||
|
│ - appctl deployment status & history views │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 9: Definition of Done
|
||||||
|
|
||||||
|
The Roadmap v3 architectural consolidation is complete when:
|
||||||
|
|
||||||
|
1. **Legibility**: Any engineer or AI agent reading the repository can immediately identify what component owns each port, domain, secret, and filesystem path.
|
||||||
|
2. **Mail Separation**:
|
||||||
|
- `smtp.roadtotech.me` serves Stalwart administration, JMAP, and protocol routing.
|
||||||
|
- `mail.roadtotech.me` serves SnappyMail from `~/Sites/snappymail`.
|
||||||
|
- 100% of SnappyMail user settings, contacts, and sessions survive cutover with zero data loss.
|
||||||
|
- Stalwart mailbox databases and SMTPS submission operate without interruption.
|
||||||
|
3. **Trust & Authority**:
|
||||||
|
- Workload manifests cannot expand admission trust boundaries or register arbitrary aliases.
|
||||||
|
- Webhook admission decisions rely exclusively on Core's authoritative registry.
|
||||||
|
- `homelab-gitops` runs under dedicated systemd sandboxing with restricted filesystem access.
|
||||||
|
4. **Contract Unification & Engine Modernization**:
|
||||||
|
- Exactly one parser library validates `app.yaml` across `appctl`, GitOps, and test suites.
|
||||||
|
- All workloads declare declarative deployment intent (`strategy: compose`).
|
||||||
|
- `appctl-v2` is fully integrated on `main`, replacing legacy procedural code with zero regressions to the bash caller.
|
||||||
|
5. **Operational Verification**:
|
||||||
|
- All 35 existing architecture invariant tests pass, plus new tests enforcing Stalwart/SnappyMail separation and manifest schema invariants.
|
||||||
|
- Pure Nix `flake check` and Gitea Actions CI pass with zero warnings.
|
||||||
|
|
||||||
@@ -0,0 +1,511 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: superseded
|
||||||
|
project: homelab
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- security
|
||||||
|
- operations
|
||||||
|
- homelab
|
||||||
|
- gitops
|
||||||
|
- roadmap
|
||||||
|
- consolidation
|
||||||
|
- provenance
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architecture Consolidation & Hardening Roadmap & Execution Plan v4
|
||||||
|
|
||||||
|
> **Superseded by**: [Architecture Consolidation & Control Plane Roadmap v5](architecture-consolidation-roadmap-v5.md)
|
||||||
|
>
|
||||||
|
> **Supersedes**: [Architecture Consolidation & Hardening Roadmap v3](architecture-consolidation-roadmap-v3.md) and [Architecture Consolidation Implementation Guide v3](architecture-consolidation-implementation-guide-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).
|
||||||
|
>
|
||||||
|
> **Architectural Decision Record**: [`03-records/decisions/homelab-3tier-architecture-and-provenance.md`](../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md)
|
||||||
|
>
|
||||||
|
> **Architectural Discussion & Rationale**: [`02-discussions/homelab/architecture-migration-v3-to-v4.md`](../../../02-discussions/homelab/architecture-migration-v3-to-v4.md)
|
||||||
|
>
|
||||||
|
> **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
Roadmap v4 formalizes the **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**.
|
||||||
|
|
||||||
|
This document serves as the authoritative implementation specification and phased execution roadmap (P0 through P5) for the homelab architecture consolidation. For the deep-dive analysis of legacy multirepo friction and rejected alternatives, see the companion [Architectural Discussion](../../../02-discussions/homelab/architecture-migration-v3-to-v4.md); for the architectural commitments and trade-offs, see the [ADR](../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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, not fewest files. 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)"]
|
||||||
|
GIT["Gitea Forge (Internal Git & OCI)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph SEC_OPS["Operational Controllers"]
|
||||||
|
ACT["appctl (Reconciliation & Diagnostics)"]
|
||||||
|
GOP["GitOps Dispatcher (Admission & Serialization)"]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
CI -->|Pushes Artifact| OCI
|
||||||
|
OCI -->|Referenced By| SITE_CATALOG
|
||||||
|
SITE_CATALOG -->|Mounted Into| APP_STATE
|
||||||
|
GOP -->|Triggers| ACT
|
||||||
|
ACT -->|Reconciles Deployment| SITE_CATALOG
|
||||||
|
SITE_CATALOG -.->|Exposed Via| TR
|
||||||
|
TR --> AUTH
|
||||||
|
AUTH --> LDAP
|
||||||
|
```
|
||||||
|
|
||||||
|
### The Seven Platform Primitives
|
||||||
|
|
||||||
|
| Primitive | Epistemic Role | Operational Responsibility |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Software Repository** | Source | Application code, unit tests, `Dockerfile`, CI workflows. Zero Homelab coupling. |
|
||||||
|
| **CI Engine (Gitea Actions)** | Build | Compiles code, runs tests, injects `org.opencontainers.image.revision`, publishes OCI images. |
|
||||||
|
| **OCI Container Image** | Artifact | Immutable intermediate build product and provenance object linking commit SHA to image digest. |
|
||||||
|
| **Sites Catalog (`~/Sites`)** | Desired Deployment | Environment-specific manifests (`app.yaml`) and Compose definitions (`docker-compose.yml`). |
|
||||||
|
| **GitOps Dispatcher** | Ingress & Admission | HMAC webhook authentication, Core registry admission control, and deployment serialization. |
|
||||||
|
| **`appctl` Engine** | Inspection & Reconciliation | Manifest parsing, two-axis inspection, and declarative deployment reconciliation (`appctl update`). |
|
||||||
|
| **Core Appliance (`~/Core`)** | Platform & Runtime | Declarative NixOS host, edge ingress (Traefik), Docker API proxy, SSO (Authelia/LLDAP), and shared capabilities (Stalwart). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 2: Declarative Source Provenance & Workload Classes
|
||||||
|
|
||||||
|
The manifest contract (`app.yaml`) formalizes the relationship between the deployment declaration and the software source code via an explicit `source:` block.
|
||||||
|
|
||||||
|
### Class A: Source-Backed Workloads
|
||||||
|
Used for custom backend projects, internal utilities, and forked codebases where upstream Git revisions must be tracked directly:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
schemaVersion: "1.0"
|
||||||
|
name: "bitetrack"
|
||||||
|
displayName: "BiteTrack"
|
||||||
|
description: "Nutrition & Recipe Management API"
|
||||||
|
category: "Productivity"
|
||||||
|
|
||||||
|
# Declarative Upstream Software Provenance
|
||||||
|
source:
|
||||||
|
type: git
|
||||||
|
url: "https://gitea.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: "/healthz"
|
||||||
|
expectedStatus: 200
|
||||||
|
timeoutSeconds: 30
|
||||||
|
```
|
||||||
|
|
||||||
|
### Class B: Image-Only Workloads
|
||||||
|
Used for standard off-the-shelf applications (e.g. Jellyfin, SnappyMail, Stirling PDF) where Homelab is strictly deploying third-party container images:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
schemaVersion: "1.0"
|
||||||
|
name: "snappymail"
|
||||||
|
displayName: "SnappyMail"
|
||||||
|
description: "Lightweight Webmail Client"
|
||||||
|
category: "Communication"
|
||||||
|
|
||||||
|
# source: omitted entirely
|
||||||
|
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 3: Explicit `source.ref` Semantics
|
||||||
|
|
||||||
|
The `source.ref` field governs how `appctl` and GitOps evaluate software freshness:
|
||||||
|
|
||||||
|
| `source.ref` Value | Target Semantic | Freshness Evaluation (`--fetch`) | Intended Use Case |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `main`, `master`, `develop` | **Moving Branch** | Resolves remote branch HEAD commit via `git ls-remote`. Reports `⚡ Revision Changed` if remote SHA != container label SHA. | Active internal projects under continuous deployment. |
|
||||||
|
| `v1.2.3`, `release-2026.09` | **Release Tag** | Resolves tag target commit SHA. Pinned release; reports `📌 Pinned (<tag>)`. | Production services tracking stable release milestones. |
|
||||||
|
| `a1b2c3d4e5...` (40-char SHA) | **Immutable Commit** | Validates exact commit SHA against container label. Static lock; no remote queries performed. | Strict reproducible testing and forensic debugging. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 4: Remote Revision Verification & `git ls-remote` Constraint
|
||||||
|
|
||||||
|
Remote provenance inspection MUST evaluate commit equality using `git ls-remote` rather than performing on-host source cloning or commit-distance traversal.
|
||||||
|
|
||||||
|
```text
|
||||||
|
git ls-remote <source.url> refs/heads/<source.ref>
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Resolution Invariant**:
|
||||||
|
- `Remote SHA == Deployed SHA`: Running container is up to date (`✓ Up to date (<sha>)`).
|
||||||
|
- `Remote SHA != Deployed SHA`: Running container is stale (`⚡ Revision Changed (deployed: <d_sha>, remote: <r_sha>)`).
|
||||||
|
- **Transport Security**: `source.url` MUST strictly use `https://`, `ssh://`, or `git@`. Schemes such as `file://`, `ext::`, or relative paths are rejected with `ManifestError`.
|
||||||
|
- **Execution Timeout**: Any network call invoking `git ls-remote` MUST be bounded by a strict 10-second timeout and degrade gracefully to an error badge on failure without blocking CLI execution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 5: Clean Persistent State Root (`~/var/lib/homelab/<app>/`)
|
||||||
|
|
||||||
|
To prevent accidental Git commits of SQLite databases, session tokens, or uploaded assets, **all mutable application runtime state is isolated from version-controlled directories**:
|
||||||
|
|
||||||
|
```text
|
||||||
|
~/Sites/<app>/ --> Version-Controlled Git Deployment Directory
|
||||||
|
├── app.yaml --> Pure Manifest
|
||||||
|
└── docker-compose.yml --> Declarative Compose Spec
|
||||||
|
|
||||||
|
~/var/lib/homelab/<app>/ --> Host State Root (Outside Git)
|
||||||
|
├── data/ --> Workload SQLite / Data Files
|
||||||
|
└── config/ --> Dynamic Runtime Configuration
|
||||||
|
```
|
||||||
|
|
||||||
|
Docker Compose files reference host state explicitly via:
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
volumes:
|
||||||
|
- /home/kiskaadee/var/lib/homelab/snappymail/data:/var/lib/snappymail/_data_
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 6: Two Operational Inspection Axes & Source Provenance
|
||||||
|
|
||||||
|
`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: Mandatory Working Rules & Parallel Track Coordination
|
||||||
|
|
||||||
|
### Mandatory Working Rules
|
||||||
|
|
||||||
|
1. **Rule 1 — One Production Transition at a Time**: 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.
|
||||||
|
2. **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.
|
||||||
|
3. **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.
|
||||||
|
4. **Rule 4 — The User Controls Production Transitions**: 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).
|
||||||
|
5. **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.
|
||||||
|
6. **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.
|
||||||
|
|
||||||
|
### Parallel Track Coordination (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.
|
||||||
|
|
||||||
|
```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)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 8: Phased Implementation Plan & Technical Execution
|
||||||
|
|
||||||
|
### Phase Status Overview
|
||||||
|
|
||||||
|
| 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. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 0: Architecture Re-Baseline & Structural Catalog
|
||||||
|
|
||||||
|
- **Deliverable 0.1: Service Taxonomy & 3-Tier Architecture**:
|
||||||
|
Update `Core/docs/architecture.md` formalizing Tier 1 (Software), Intermediate Artifacts (OCI), Tier 2 (Sites Deployment), and Tier 3 (Platform Core), along with Class A (Source-Backed) and Class B (Image-Only) classifications.
|
||||||
|
- **Deliverable 0.2: Controller Authority Matrix**:
|
||||||
|
Document authoritative control loops across systemd, Docker Compose, GitOps, CI runners, and `appctl`.
|
||||||
|
- **Deliverable 0.3: Resource & State Ownership Matrix**:
|
||||||
|
Formalize persistent state ownership for every component: owner, filesystem location (`~/var/lib/homelab/<app>/`), desired state source, and runtime state form.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 1: Mail Topology Realignment & Zero-Data-Loss Migration Runbook
|
||||||
|
|
||||||
|
#### Architectural 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 migrated to `~/var/lib/homelab/snappymail/`.
|
||||||
|
|
||||||
|
#### Execution Runbook
|
||||||
|
1. **Pre-Migration Health Audit**:
|
||||||
|
```bash
|
||||||
|
docker ps --filter "name=stalwart" --filter "name=snappymail" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
||||||
|
```
|
||||||
|
2. **State Freeze**: Halt SnappyMail to prevent database mutation during backup:
|
||||||
|
```bash
|
||||||
|
docker stop snappymail
|
||||||
|
```
|
||||||
|
3. **Verified Pre-Cutover Backup Archive**:
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
4. **Workload Scaffolding & State Directory Provisioning**:
|
||||||
|
- Provision isolated persistent state root:
|
||||||
|
```bash
|
||||||
|
mkdir -p ~/var/lib/homelab/snappymail
|
||||||
|
```
|
||||||
|
- Create `~/Sites/snappymail/app.yaml` declaring schema v1.0 (Class B Image-Only).
|
||||||
|
- Create `~/Sites/snappymail/docker-compose.yml` mounting `/home/kiskaadee/var/lib/homelab/snappymail:/var/lib/snappymail/_data_`, connected to `proxy-net`, with Traefik ingress labels for `mail.roadtotech.me`.
|
||||||
|
5. **Non-Destructive State Replication & Parity Proof**:
|
||||||
|
```bash
|
||||||
|
cp -a ~/Homelab/Core/config/snappymail/data/* ~/var/lib/homelab/snappymail/
|
||||||
|
diff -r ~/Homelab/Core/config/snappymail/data ~/var/lib/homelab/snappymail
|
||||||
|
```
|
||||||
|
6. **Stalwart Endpoint Cutover in Core**:
|
||||||
|
- Update `Core/docker-compose.yml`: Change Stalwart domain Traefik labels from `mail.roadtotech.me` to `smtp.roadtotech.me`, set `STALWART_PUBLIC_URL=https://smtp.roadtotech.me`, and remove SnappyMail service block.
|
||||||
|
- Apply Core changes:
|
||||||
|
```bash
|
||||||
|
cd ~/Homelab/Core && docker compose up -d stalwart
|
||||||
|
```
|
||||||
|
7. **Workload Launch & Live Verification**:
|
||||||
|
- Launch SnappyMail:
|
||||||
|
```bash
|
||||||
|
cd ~/Sites/snappymail && docker compose up -d
|
||||||
|
```
|
||||||
|
- Verify webmail at `https://mail.roadtotech.me`, user logins, contact address books, IMAP/SMTP connectivity to Stalwart, and Diun SMTPS alert delivery on port 465.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 2: GitOps Privilege & Authority Hardening
|
||||||
|
|
||||||
|
- **Deliverable 2.1: Authoritative Core Repository Registry**:
|
||||||
|
Establish `Core/config/deployments.yaml` as the sole authority for admitted deployment repositories. 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, pulls the published image (`docker compose pull`), recreates containers (`docker compose up -d`), runs healthchecks, and writes the ledger.
|
||||||
|
5. *Prohibited*: Host appliance never compiles code or clones application source trees.
|
||||||
|
- **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`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 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"`, permitted transport schemes (`https://`, `ssh://`, `git@`), enforces 10s timeout on remote Git inspections, and resolves `source.ref` tracking semantics.
|
||||||
|
- 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; strip all Homelab host/Traefik configuration.
|
||||||
|
3. Configure Gitea Actions CI workflow injecting `org.opencontainers.image.revision` and pushing to the local registry.
|
||||||
|
4. Update `Sites/doc2site/app.yaml` and `docker-compose.yml` referencing the published image.
|
||||||
|
- **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`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
- **Deliverable 4.2: Startup Serialization**:
|
||||||
|
Ensure clean platform restarts without authentication deadlocks or dropped alerts.
|
||||||
|
- **Deliverable 4.3: Watchtower / Image Update Governance**:
|
||||||
|
Standardize automated container image updates and notifications.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 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 container inspect `RepoDigests`, capturing the immutable OCI registry digest.*
|
||||||
|
- **Deliverable 5.2: `appctl history` Command**:
|
||||||
|
Implement CLI inspection of the deployment ledger in `appctl_engine.py`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: superseded
|
||||||
|
superseded_by: architecture-consolidation-roadmap-v6.md
|
||||||
|
project: homelab
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- security
|
||||||
|
- operations
|
||||||
|
- homelab
|
||||||
|
- gitops
|
||||||
|
- appctl
|
||||||
|
- control-plane
|
||||||
|
- roadmap
|
||||||
|
- consolidation
|
||||||
|
- provenance
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architecture Consolidation & Control Plane Roadmap v5
|
||||||
|
|
||||||
|
> [!WARNING]
|
||||||
|
> **SUPERSEDED**: This roadmap has been superseded by [**Architecture Consolidation & Control Plane Roadmap v6**](architecture-consolidation-roadmap-v6.md), which codifies locked architectural decisions DEC-01 through DEC-05, the single typed `POST /v1/operations` dispatcher, mandatory token-gated authorization, and `homelab-appctl` systemd isolation.
|
||||||
|
>
|
||||||
|
> **Supersedes**: [Architecture Consolidation Roadmap v4](architecture-consolidation-roadmap-v4.md) and [appctl Engine V2 Refactoring Plan](../appctl/appctl-engine-v2-refactoring.md)
|
||||||
|
>
|
||||||
|
> **Current Platform Baseline**: Consolidated Git baseline combining NixOS appliance (`Core/`), modernized type-safe metadata engine (`appctl-v2`), and validated provenance domain models.
|
||||||
|
>
|
||||||
|
> **Architectural Decision Records**:
|
||||||
|
> - [`homelab-3tier-architecture-and-provenance.md`](../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md)
|
||||||
|
> - [`homelab-appctl-control-plane-architecture.md`](../../../03-records/decisions/homelab-appctl-control-plane-architecture.md)
|
||||||
|
>
|
||||||
|
> **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`, persistent state `~/var/lib/homelab/`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
Roadmap v5 establishes the unified engineering roadmap for Homelab Core. It integrates the **3-Tier Architecture & Provenance Model** with the transition of **`appctl` into the authoritative Homelab Core Operational Control Plane**.
|
||||||
|
|
||||||
|
Under this roadmap, `appctl` is no longer a collection of local shell scripts invoked over SSH; it is an authenticated, command-oriented control plane daemon exposed over Unix domain socket and HTTP. The platform maintains **Git as the authoritative declarative truth for deployment state**, reconciles implementation-agnostic **Deployment Models**, projects secrets via a provider interface, and serves heterogeneous clients (local CLI, remote CLI, GitOps dispatcher, Operations UI, and AI authoring workflows) with complete telemetry.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. System Topology & Control Plane Architecture
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TB
|
||||||
|
subgraph CLIENTS["1. CLIENT PLANE"]
|
||||||
|
direction LR
|
||||||
|
CLI_REMOTE["Remote CLI<br/>(Bearer Token via HTTP)"]
|
||||||
|
CLI_LOCAL["Local CLI (Host)<br/>(Bearer Token via Unix Socket)"]
|
||||||
|
GITOPS_DISPATCH["GitOps Dispatcher<br/>(HMAC-SHA256 via HTTP)"]
|
||||||
|
UI_OPS["Operations Web UI<br/>(ForwardAuth via HTTP)"]
|
||||||
|
AI_AGENT["AI Authoring Workflow<br/>(Proposal Generator)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph CONTROL_PLANE["2. HOMELAB OPERATIONAL CONTROL PLANE (appctl Daemon)"]
|
||||||
|
direction TB
|
||||||
|
|
||||||
|
subgraph TRANSPORTS["Transport Listeners (One Logical API)"]
|
||||||
|
SOCKET_IN["Unix Domain Socket (/run/homelab/appctl.sock)"]
|
||||||
|
HTTP_IN["HTTP Listener (Localhost / LAN / Traefik)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
API_ROUTER["Command-Oriented Operational Router<br/>• POST /operations/deploy<br/>• POST /operations/restart<br/>• GET /workloads & status<br/>• POST /operations/sync"]
|
||||||
|
|
||||||
|
subgraph CORE_MODULES["Core Daemon Subsystems"]
|
||||||
|
AUTH_MODULE["Identity & RBAC (LLDAP / Groups)"]
|
||||||
|
AUDIT_MODULE["Append-Only Audit Log (Telemetry & Hashes)"]
|
||||||
|
MODEL_VALIDATOR["DeploymentModel Validator & Compiler"]
|
||||||
|
SECRET_PROVIDER["SecretProvider Interface (Secret References)"]
|
||||||
|
RECON_ENGINE["Reconciliation & Compose Driver"]
|
||||||
|
end
|
||||||
|
|
||||||
|
SOCKET_IN --> API_ROUTER
|
||||||
|
HTTP_IN --> API_ROUTER
|
||||||
|
API_ROUTER --> AUTH_MODULE
|
||||||
|
AUTH_MODULE --> AUDIT_MODULE
|
||||||
|
API_ROUTER --> MODEL_VALIDATOR
|
||||||
|
MODEL_VALIDATOR --> SECRET_PROVIDER
|
||||||
|
SECRET_PROVIDER --> RECON_ENGINE
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph PLATFORM_RUNTIME["3. PLATFORM & RUNTIME TIERS"]
|
||||||
|
direction LR
|
||||||
|
GIT_REPO["Deployment Catalog (Git Truth)<br/>• Versioned DeploymentModels"]
|
||||||
|
SITES_CATALOG["Sites Catalog (~/Sites/*)<br/>• Materialized app.yaml & compose"]
|
||||||
|
STATE_ROOT["Host State Root (~/var/lib/homelab/*)<br/>• Workload Data & DBs"]
|
||||||
|
DOCKER_ENGINE["Docker Daemon & Socket-Proxy"]
|
||||||
|
TRAEFIK_INGRESS["Traefik Edge & TLS Ingress"]
|
||||||
|
end
|
||||||
|
|
||||||
|
CLIENTS --> TRANSPORTS
|
||||||
|
MODEL_VALIDATOR --> GIT_REPO
|
||||||
|
GIT_REPO --> SITES_CATALOG
|
||||||
|
RECON_ENGINE --> SITES_CATALOG
|
||||||
|
RECON_ENGINE --> DOCKER_ENGINE
|
||||||
|
SITES_CATALOG --> STATE_ROOT
|
||||||
|
DOCKER_ENGINE --> TRAEFIK_INGRESS
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Core Architectural Invariants
|
||||||
|
|
||||||
|
1. **One Logical API Across Transports**: The control-plane API is a single logical command-oriented contract. Unix domain socket vs. HTTP is merely transport. Local and remote CLIs invoke identical operation schemas.
|
||||||
|
2. **Host Access Does Not Confer Authority**: Entering via SSH does not bypass control-plane authentication. **Every mutating operation requires an explicit, authenticated user-scoped token.**
|
||||||
|
3. **Git is the Authoritative Source of Deployment State**: Approved `DeploymentModels` are committed to the version-controlled deployment repository. `appctl` reconciles desired Git state into running containers, preserving rollback capability (`git revert`) and historical auditability.
|
||||||
|
4. **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` captures implementation-agnostic intent (ports, domains, volumes, dependencies); `Deployment Definition` captures the concrete platform descriptors (`app.yaml` + Compose).
|
||||||
|
5. **AI Authoring Boundary**: The AI is strictly an upstream authoring client with zero mutation authority. The AI analyzes repositories and emits `DeploymentProposals`. After human approval, the AI is completely out of the loop.
|
||||||
|
6. **KISS Primitives & Linear Control Paths**: The deployment pipeline remains strictly linear:
|
||||||
|
$$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl Reconcile} \longrightarrow \text{Compose Up}$$
|
||||||
|
No distributed message brokers or deployment databases.
|
||||||
|
7. **Secret Reference Invariant**: Deployment definitions contain secret references (`secretKeyRef`), never secret material. References are resolved at runtime via the `SecretProvider` interface.
|
||||||
|
8. **Clean Persistent State Root**: Mutable application data lives strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
|
||||||
|
9. **Client Independence**: `appctl` owns the control-plane contract, not its clients. Homepage is a read-only dashboard consumer, not an interactive administration cockpit.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Phased Implementation Roadmap
|
||||||
|
|
||||||
|
### Overview
|
||||||
|
|
||||||
|
| Phase | Title | Focus Area | Key Deliverables | Verification Gates |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **P0** | **Baseline Consolidation** | Git & Architecture | Merge `refactor/appctl-rework` into `main`, unify history, supersede old plans. | Clean git working tree, `./scripts/test` passing, flake check green. |
|
||||||
|
| **P1** | **Mail Realignment** | Topology & State | Move Stalwart to `smtp.roadtotech.me`, SnappyMail to `~/Sites/snappymail`. | Zero data loss, verified rollback archive, state parity diff, Diun SMTPS delivery. |
|
||||||
|
| **P2** | **GitOps Hardening** | Ingress Security | Authoritative Core repo registry, HMAC validation, systemd sandboxing. | Flake check, path traversal rejection tests, Compose AST security validator. |
|
||||||
|
| **P3** | **Manifest Contract** | Domain Engine | Schema v1.0, `core_manifest.py`, source provenance resolution (`git ls-remote`). | Regression tests for domain invariants, schema linting in CI. |
|
||||||
|
| **P4** | **Control Plane Daemon** | API & Dispatch | `homelab-appctl.service`, dual transport (socket + HTTP), thin-client CLI, append-only audit log. | Hermetic API test suite, explicit token validation tests, audit log telemetry verification. |
|
||||||
|
| **P5** | **Identity & Secrets** | Auth & Providers | Authelia header auth, user-scoped API tokens, `SecretProvider` reference resolver. | RBAC permission matrix tests, secret reference materialization tests. |
|
||||||
|
| **P6** | **Deployment Model & AI**| Intent Authoring | Capability model, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. | Intent validation tests, platform security invariant enforcement tests. |
|
||||||
|
| **P7** | **Operations UI & Portal** | Client Integration | Dedicated Operations UI client, Homepage status integration widgets. | End-to-end deployment verification via UI and CLI. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 0: Baseline & Architectural Consolidation (Completed)
|
||||||
|
* **Deliverable 0.1**: Record Architectural Decision Record (`homelab-appctl-control-plane-architecture.md`).
|
||||||
|
* **Deliverable 0.2**: Merge `refactor/appctl-rework` into `main` and synchronize baseline back to working branch.
|
||||||
|
* **Deliverable 0.3**: Mark superseded roadmaps (v2, v3, v4) and legacy refactoring plans as `status: superseded`.
|
||||||
|
* **Deliverable 0.4**: Run `./scripts/test` and `nix flake check` to confirm baseline integrity.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 1: Mail Topology Realignment & Zero-Data-Loss Migration Runbook
|
||||||
|
* **Deliverable 1.1: Pre-Migration Snapshot**:
|
||||||
|
Freeze SnappyMail container, generate timestamped SHA256-verified backup archive of `Core/config/snappymail/data`.
|
||||||
|
* **Deliverable 1.2: Workload Provisioning & State Cutover**:
|
||||||
|
- Provision `~/var/lib/homelab/snappymail/`.
|
||||||
|
- Replicate state with `cp -a` and prove byte parity (`diff -r`).
|
||||||
|
- Create `~/Sites/snappymail/app.yaml` (Class B Image-Only) and `docker-compose.yml`.
|
||||||
|
* **Deliverable 1.3: Stalwart Endpoint Re-homing**:
|
||||||
|
Update Stalwart public Traefik labels in `Core/docker-compose.yml` to `smtp.roadtotech.me`. Remove SnappyMail from Core stack.
|
||||||
|
* **Deliverable 1.4: Cutover Verification**:
|
||||||
|
Verify webmail logins, address book persistence, IMAP/SMTP mail flow, and Diun SMTPS alert delivery on port 465.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 2: GitOps Privilege & Authority Hardening
|
||||||
|
* **Deliverable 2.1: Authoritative Core Repository Registry**:
|
||||||
|
Define `Core/config/deployments.yaml` as the sole authority for admitted deployment targets.
|
||||||
|
* **Deliverable 2.2: Second Brain Read-Only Data Vault Policy**:
|
||||||
|
Designate `~/Brain` with `strategy: pull-only`, isolated from Docker execution.
|
||||||
|
* **Deliverable 2.3: Workload Compose Security Policy**:
|
||||||
|
Implement pre-flight Compose AST inspection rejecting privileged containers, Docker socket mounts, and host root mounts.
|
||||||
|
* **Deliverable 2.4: Systemd Service Sandboxing**:
|
||||||
|
Apply `ProtectSystem=strict`, `NoNewPrivileges=true`, and private temporary directories to `homelab-gitops.service`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 3: Manifest Contract Convergence & Provenance Engine
|
||||||
|
* **Deliverable 3.1: Manifest Schema v1.0 & Authoritative Parser (`core_manifest.py`)**:
|
||||||
|
- Implement strongly-typed domain dataclasses: `SitesApp`, `CoreService`, `SourceConfig`.
|
||||||
|
- Enforce explicit `source.ref` semantics: moving branch (`main`), release tag (`v1.2.3`), immutable commit SHA (`a1b2c3...`).
|
||||||
|
- Strict transport scheme validation: permitted `https://`, `ssh://`, `git@`; reject `file://` and path traversals.
|
||||||
|
* **Deliverable 3.2: Two-Axis Inspection**:
|
||||||
|
- Axis 1: Local Sites deployment checkout state (`✓ Synced`, `* Dirty`, `⬆ Ahead`, `⬇ Behind`).
|
||||||
|
- Axis 2: Upstream software provenance state (via `git ls-remote` bounded by 10s timeout during `--fetch`).
|
||||||
|
* **Deliverable 3.3: Engine Promotion**:
|
||||||
|
Promote `scripts/appctl_engine_v2.py` to `scripts/appctl_engine.py` with complete behavioral test coverage.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 4: appctl Control Plane Daemon & Command-Oriented API
|
||||||
|
* **Deliverable 4.1: Control Plane Service (`homelab-appctl.service`)**:
|
||||||
|
Implement command-oriented daemon listening on dual transports: Unix domain socket (`/run/homelab/appctl.sock`) for local host clients and unified HTTP listener (localhost, LAN, and Traefik edge ingress) for network clients.
|
||||||
|
* **Deliverable 4.2: Command-Oriented Operational Endpoints**:
|
||||||
|
- `POST /operations/deploy` (reconcile deployment for target workload)
|
||||||
|
- `POST /operations/restart` (restart workload containers)
|
||||||
|
- `POST /operations/pull` (pull latest images)
|
||||||
|
- `GET /workloads` (list workloads with two-axis inspection)
|
||||||
|
- `GET /workloads/{id}/status` (inspect specific workload diagnostics)
|
||||||
|
- `GET /workloads/{id}/logs` (stream logs via Server-Sent Events)
|
||||||
|
- `POST /operations/sync` (recompile dashboard status)
|
||||||
|
* **Deliverable 4.3: Thin-Client CLI**:
|
||||||
|
Update `scripts/appctl` to act as a lightweight client dispatching commands to the local daemon socket with zero duplicate operational code.
|
||||||
|
* **Deliverable 4.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`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 5: Identity, RBAC & SecretProvider Interface
|
||||||
|
* **Deliverable 5.1: Authentication Gateway**:
|
||||||
|
- Web requests: Accept trusted identity headers from Traefik/Authelia (`Remote-User`, `Remote-Groups`).
|
||||||
|
- CLI requests (both remote and local): Require explicit user-scoped API tokens (`Authorization: Bearer <token>`).
|
||||||
|
- Webhook requests: Validate HMAC-SHA256 signature against webhook secret.
|
||||||
|
* **Deliverable 5.2: Role-Based Authorization Engine**:
|
||||||
|
Enforce group policies (`homelab-admin`, `homelab-operator`, `homelab-viewer`) on incoming operations.
|
||||||
|
* **Deliverable 5.3: SecretProvider Interface**:
|
||||||
|
- Define `SecretProvider` contract in the control plane:
|
||||||
|
```python
|
||||||
|
class SecretProvider(Protocol):
|
||||||
|
def resolve_secret(self, ref: str) -> str: ...
|
||||||
|
def project_environment(self, refs: dict[str, str]) -> dict[str, str]: ...
|
||||||
|
```
|
||||||
|
- Deployment definitions store secret references (`secretKeyRef: ...`), never plaintext material.
|
||||||
|
- Workload application secrets are projected dynamically at container recreation without Git history pollution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 6: Homelab Deployment Model & AI Authoring Workflow
|
||||||
|
* **Deliverable 6.1: Platform Capability Catalog & Invariants**:
|
||||||
|
Formally define machine-readable specification of Core capabilities (HTTP routing, persistent mounts, networks, healthchecks) and invariants (no privileged containers, isolated state root).
|
||||||
|
* **Deliverable 6.2: `DeploymentProposal` Schema**:
|
||||||
|
Define candidate model structure emitted by AI discovery workflows from repository inspection.
|
||||||
|
* **Deliverable 6.3: `DeploymentModel` Git Pipeline & Materialization**:
|
||||||
|
- Operator selects/edits proposal into an approved `DeploymentModel`.
|
||||||
|
- The model is committed to the version-controlled deployment repository (Git).
|
||||||
|
- `appctl` validates the model, provisions `~/var/lib/homelab/<app>/`, compiles the Deployment Definition (`app.yaml` + Compose), and triggers deployment.
|
||||||
|
* **Deliverable 6.4: Human Approval Invariant**:
|
||||||
|
Enforce interactive operator signature/approval before model creation. AI possesses zero execution authority.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 7: Operations Web Client & Dashboard Integration
|
||||||
|
* **Deliverable 7.1: Operations UI Client**:
|
||||||
|
Deploy lightweight, browser-based management console as a client of the control plane API (proposals review, approval, real-time log streaming, token management).
|
||||||
|
* **Deliverable 7.2: Homepage Status Integration**:
|
||||||
|
Maintain Homepage as read-only portal, querying `appctl` live status endpoints or compiled `services.yaml`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Definition of Done
|
||||||
|
|
||||||
|
1. **Unified Control Plane**: All platform operations execute through `homelab-appctl.service`. No secondary deployment scripts exist.
|
||||||
|
2. **Explicit Authentication Everywhere**: Host SSH access does not confer appctl authority. Every operation has an authenticated principal and is recorded in the append-only audit log with transport and origin telemetry.
|
||||||
|
3. **Declarative Git Truth**: All workloads are governed by version-controlled `DeploymentModels` committed to Git. Deployments are fully reproducible and auditable.
|
||||||
|
4. **Secret Hygiene**: Deployment manifests contain zero plaintext credentials; workload secrets resolve via `SecretProvider` without Git history pollution.
|
||||||
|
5. **Safe Deployment Authoring**: AI agents act strictly as proposal generators; all mutations require human approval and conform to Core invariants.
|
||||||
|
6. **Zero Data Loss**: Mail realignment preserves 100% of user data, mailboxes, and address books.
|
||||||
|
7. **Invariant-Driven Regression Coverage**: All defined domain, authorization, deployment, and security invariants have automated regression coverage.
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: homelab
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- security
|
||||||
|
- operations
|
||||||
|
- homelab
|
||||||
|
- gitops
|
||||||
|
- appctl
|
||||||
|
- control-plane
|
||||||
|
- roadmap
|
||||||
|
- consolidation
|
||||||
|
- provenance
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architecture Consolidation & Control Plane Roadmap v6
|
||||||
|
|
||||||
|
> **Supersedes**: [Architecture Consolidation & Control Plane Roadmap v5](architecture-consolidation-roadmap-v5.md)
|
||||||
|
>
|
||||||
|
> **Authoritative Repository Specifications**:
|
||||||
|
> - Core Readiness Plan: `~/Homelab/Core/docs/plans/p4-readiness-plan.md`
|
||||||
|
> - Core Roadmap Projection: `~/Homelab/Core/ROADMAP.md`
|
||||||
|
>
|
||||||
|
> **Architectural Decision Records**:
|
||||||
|
> - [`homelab-appctl-control-plane-architecture.md`](../../../03-records/decisions/homelab-appctl-control-plane-architecture.md) (`~/Homelab/Core/docs/decisions/0002-appctl-control-plane-architecture.md`)
|
||||||
|
> - [`homelab-3tier-architecture-and-provenance.md`](../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md) (`~/Homelab/Core/docs/decisions/0001-3tier-architecture-and-provenance.md`)
|
||||||
|
> - `~/Homelab/Core/docs/decisions/0003-pydantic-v2-runtime-validation.md`
|
||||||
|
>
|
||||||
|
> **Evolutionary History**:
|
||||||
|
> - [`homelab-control-plane-evolution-v1-to-v6.md`](../../../04-learning/knowledge/methods/homelab-control-plane-evolution-v1-to-v6.md)
|
||||||
|
>
|
||||||
|
> **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`, persistent state `~/var/lib/homelab/`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
Roadmap v6 codifies the transition of `appctl` into an authoritative, fail-closed **Operational Control Plane Daemon** (`homelab-appctl.service`). It incorporates the architectural reconciliation and locked decisions (**`DEC-01` through `DEC-05`**) finalized before initiating the Milestone P4 daemon implementation.
|
||||||
|
|
||||||
|
Under Roadmap v6, `appctl` completely abandons its legacy identity as a collection of local Bash scripts directly invoking `docker compose` and `git`. Instead:
|
||||||
|
1. **One Logical API Across Dual Transports**: A unified HTTP/1.1 engine serving both a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback TCP (`127.0.0.1:9001`) with zero protocol divergence.
|
||||||
|
2. **Single Canonical Operation Router**: Operations dispatch via a single, strictly-typed command endpoint (`POST /v1/operations` + `GET /v1/health`), eliminating multi-route REST ambiguity.
|
||||||
|
3. **Host Access Does Not Confer Mutation Authority**: Entering via SSH provides Unix access, but zero operational control plane privileges. Every mutating action and sensitive read (`workload.config`, `workload.logs`) requires a cryptographically verified, SOPS-projected SHA-256 Bearer token.
|
||||||
|
4. **Dedicated Systemd Service Identity & Privilege Isolation**: The daemon executes as `homelab-appctl` (`Group = "homelab-operators"`), isolated from operator shell processes and AI coding sessions, protected by declarative POSIX ACLs.
|
||||||
|
5. **Unified Pre-Flight & Pure-Python Environment Assembly**: Shell `source` and `eval` are eliminated; environments are parsed via inert Python readers, and every mutation is gated by Compose AST security validation.
|
||||||
|
6. **Append-Only Audit Log with Fail-Closed Disk Guard**: Multi-dimensional telemetry (`audit.jsonl`, mode `0600`) records pre-execution (`DISPATCHED`), post-execution (`COMPLETED`/`FAILED`), and admission rejection (`DENIED`) records. If the audit log cannot be written, the mutation is aborted before any Docker or Git subprocess executes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. System Topology & Control Plane Architecture
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TB
|
||||||
|
subgraph CLIENTS["1. CLIENT PLANE"]
|
||||||
|
direction LR
|
||||||
|
CLI_THIN["Thin-Client CLI (Host)<br/>(Bearer Token / PeerCred via UDS)"]
|
||||||
|
GITOPS_DISPATCH["GitOps Ingress Worker<br/>(Bearer Token via UDS)"]
|
||||||
|
HTTP_CLIENT["Local/Remote HTTP Client<br/>(Bearer Token via 127.0.0.1:9001)"]
|
||||||
|
AI_AGENT["AI Authoring Workflow<br/>(Proposal Generator Only)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph CONTROL_PLANE["2. HOMELAB OPERATIONAL CONTROL PLANE (homelab-appctl.service)"]
|
||||||
|
direction TB
|
||||||
|
|
||||||
|
subgraph TRANSPORTS["Dual Transports (HTTP/1.1 Engine)"]
|
||||||
|
SOCKET_IN["Unix Domain Socket (/run/homelab/appctl.sock)<br/>mode 0660 (homelab-appctl:homelab-operators)"]
|
||||||
|
HTTP_IN["HTTP Listener (127.0.0.1:9001)<br/>Strictly loopback in P4"]
|
||||||
|
end
|
||||||
|
|
||||||
|
API_ROUTER["Single Command-Oriented Operational Router<br/>• POST /v1/operations (13 Canonical Operations)<br/>• GET /v1/health (Liveness Probe)"]
|
||||||
|
|
||||||
|
subgraph PIPELINE["Unified Fail-Closed Pipeline"]
|
||||||
|
direction TB
|
||||||
|
VAL_GATE["Pydantic v2 Contract Validator<br/>(extra='forbid', strict=True, 64 KiB Limit)"]
|
||||||
|
AUTH_GATE["Authentication & 3-Role RBAC Gate<br/>• Admin / Operator (deployments.yaml) / Viewer<br/>• SO_PEERCRED UDS fallback to viewer"]
|
||||||
|
LOCK_MGR["Per-Target flock Manager<br/>(/var/lib/homelab/appctl/locks/*.lock)"]
|
||||||
|
AUDIT_PRE["Pre-Execution Audit Disk Guard<br/>(DISPATCHED → Abort on write failure)"]
|
||||||
|
PREFLIGHT["Unified Pre-Flight & Pure-Python Env<br/>• Manifest parse • Compose AST security validator"]
|
||||||
|
EXEC_ENGINE["Execution Subprocess Runner<br/>(Fixed allowlist, 256 KiB output bound, timeouts)"]
|
||||||
|
AUDIT_POST["Post-Execution Audit Writer<br/>(COMPLETED / FAILED with commit SHAs)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
SOCKET_IN --> API_ROUTER
|
||||||
|
HTTP_IN --> API_ROUTER
|
||||||
|
API_ROUTER --> VAL_GATE
|
||||||
|
VAL_GATE --> AUTH_GATE
|
||||||
|
AUTH_GATE --> LOCK_MGR
|
||||||
|
LOCK_MGR --> AUDIT_PRE
|
||||||
|
AUDIT_PRE --> PREFLIGHT
|
||||||
|
PREFLIGHT --> EXEC_ENGINE
|
||||||
|
EXEC_ENGINE --> AUDIT_POST
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph PLATFORM_RUNTIME["3. PLATFORM & RUNTIME TIERS"]
|
||||||
|
direction LR
|
||||||
|
DEPLOY_REG["Core Registry<br/>(config/deployments.yaml)"]
|
||||||
|
SITES_CATALOG["Sites Catalog (~/Sites/*)<br/>• app.yaml & compose"]
|
||||||
|
STATE_ROOT["Host State Root (~/var/lib/homelab/*)<br/>• Workload Data & DBs"]
|
||||||
|
DOCKER_ENGINE["Docker Daemon & Socket-Proxy"]
|
||||||
|
AUDIT_STORE["Audit Storage (/var/log/homelab/appctl/audit.jsonl)<br/>mode 0600 (homelab-appctl)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
CLIENTS --> TRANSPORTS
|
||||||
|
AUTH_GATE --> DEPLOY_REG
|
||||||
|
PREFLIGHT --> SITES_CATALOG
|
||||||
|
EXEC_ENGINE --> SITES_CATALOG
|
||||||
|
EXEC_ENGINE --> DOCKER_ENGINE
|
||||||
|
SITES_CATALOG --> STATE_ROOT
|
||||||
|
AUDIT_PRE --> AUDIT_STORE
|
||||||
|
AUDIT_POST --> AUDIT_STORE
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Core Architectural Invariants (Codified DEC-01 through DEC-05)
|
||||||
|
|
||||||
|
1. **One Logical API Across Transports (`DEC-01`)**:
|
||||||
|
- The API is a single logical HTTP/1.1 contract served over Unix domain socket (`/run/homelab/appctl.sock`) and TCP (`127.0.0.1:9001`).
|
||||||
|
- All operations are dispatched through `POST /v1/operations` with JSON payloads (`version: "1.0"`). Convenience liveness is exposed via `GET /v1/health`. Multi-route REST aliases (`GET /workloads`, `POST /operations/deploy`) are rejected.
|
||||||
|
2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**:
|
||||||
|
- SSH entry confers zero control plane mutation authority. Every mutating operation and sensitive read (`workload.config`, `workload.logs`) strictly requires a valid Bearer token (`/run/secrets/appctl/tokens.json`).
|
||||||
|
- Local UDS connections without Bearer tokens leverage `SO_PEERCRED` to identify the caller and fall back strictly to `homelab-viewer` privileges for non-sensitive reads (`list`, `get`, `resolve`, `ssl`, `health`).
|
||||||
|
3. **Dedicated Service Identity & OS Boundary (`DEC-03`)**:
|
||||||
|
- The daemon runs as `homelab-appctl` (`Group = "homelab-operators"`).
|
||||||
|
- Unprivileged processes and AI agents running under the operator SSH session cannot access `/run/secrets/appctl/tokens.json` (`0400`) or mutate `/var/log/homelab/appctl/audit.jsonl` (`0600`).
|
||||||
|
- Declarative `systemd.tmpfiles.rules` apply recursive default POSIX ACLs (`d:u:homelab-appctl:rwx,u:homelab-appctl:rwx`) to shared directories.
|
||||||
|
4. **GitOps Ingress Unification (`DEC-04`)**:
|
||||||
|
- `scripts/gitops_dispatcher.py` retains webhook ingress, HMAC verification, `config/deployments.yaml` admission, and the asynchronous `.pending.json` queue.
|
||||||
|
- The background worker delegates execution to the daemon's `workload.update` operation over the Unix domain socket, eliminating duplicated `git pull` and `docker compose` execution paths.
|
||||||
|
5. **Unified Pre-Flight & Pure-Python Environment Assembly (`DEC-05`)**:
|
||||||
|
- Shell `source` and `eval` are eliminated. Subprocess environments are assembled entirely in Python with strict key validation against `ENV_KEY_RE` and `RESERVED_ENV_KEYS`.
|
||||||
|
- Every mutating Compose operation is preceded by `validate_compose_security()`, enforcing AST security constraints across both CLI and GitOps paths.
|
||||||
|
6. **Append-Only Audit Log with Fail-Closed Disk Guard (`DEC-03`)**:
|
||||||
|
- Mutating operations append a `DISPATCHED` record before touching Docker or Git. If the disk write fails, the request immediately terminates with `500 ERR_EXECUTION_FAILED`.
|
||||||
|
7. **Git is the Authoritative Source of Deployment State**:
|
||||||
|
- Approved `DeploymentModels` are committed to Git. `appctl` reconciles desired Git state into running containers.
|
||||||
|
8. **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}$.
|
||||||
|
9. **AI Authoring Boundary**:
|
||||||
|
- AI agents are strictly upstream proposal generators (`DeploymentProposal`) with zero execution authority. Human operators approve the intent.
|
||||||
|
10. **Secret Reference Invariant & Clean Persistent State Root**:
|
||||||
|
- Deployment definitions store secret references (`secretKeyRef`) resolved at runtime via `SecretProvider`, never plaintext credentials; mutable runtime data resides strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
|
||||||
|
11. **KISS Primitives & Linear Control Paths**:
|
||||||
|
- Control flow remains strictly linear and local. No message brokers (RabbitMQ/Kafka) or deployment databases are introduced.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. The 13 Canonical Domain Operations
|
||||||
|
|
||||||
|
| Domain Operation | Type | Required Role (`Sites` / `Core`) | Timeout | Subprocess / Engine |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| `workload.list` | Read-Only | `homelab-viewer` | `15s` | In-process (`appctl_engine.py`, `provenance.py`) |
|
||||||
|
| `workload.get` | Read-Only | `homelab-viewer` | `15s` | In-process (`appctl_engine.py`, `core_manifest.py`) |
|
||||||
|
| `workload.resolve` | Read-Only | `homelab-viewer` | In-process | In-process (`appctl_engine.py`) |
|
||||||
|
| `platform.ssl` | Read-Only | `homelab-viewer` | `3s` / host | In-process (`appctl_engine.py`) |
|
||||||
|
| `platform.health` | Read-Only | `homelab-viewer` | In-process | In-process daemon health probe |
|
||||||
|
| `workload.config` | Sensitive Read | `homelab-operator` / `homelab-admin`* | `15s` | `docker compose config` (secret redaction) |
|
||||||
|
| `workload.logs` | Sensitive Read | `homelab-operator` / `homelab-admin`* | `15s` | `docker compose logs --tail <1..1000>` |
|
||||||
|
| `workload.deploy` | Mutating | `homelab-operator` / `homelab-admin`* | `300s` | `docker compose up -d` $\to$ Homepage sync |
|
||||||
|
| `workload.stop` | Mutating | `homelab-operator` / `homelab-admin`* | `300s` | `docker compose down` / `stop` $\to$ Homepage sync |
|
||||||
|
| `workload.restart`| Mutating | `homelab-operator` / `homelab-admin`* | `300s` | `docker compose restart` $\to$ Homepage sync |
|
||||||
|
| `workload.pull` | Mutating | `homelab-operator` / `homelab-admin`* | `300s` | `docker compose pull` $\to$ `docker compose up -d` |
|
||||||
|
| `workload.update` | Mutating | `homelab-operator` / `homelab-admin`* | `60s` (git)<br>`300s` (docker) | `git pull --ff-only` $\to$ Compose security validate $\to$ Declared actions $\to$ Homepage sync |
|
||||||
|
| `platform.sync_homepage` | Mutating | `homelab-operator` / `homelab-admin` | In-process | Compile `services.yaml` under `_homepage_sync.lock` |
|
||||||
|
|
||||||
|
*\*Targeting `core` or any `core_service` container strictly requires the `homelab-admin` role.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Phased Implementation Roadmap
|
||||||
|
|
||||||
|
### Overview
|
||||||
|
|
||||||
|
| Milestone | Title | Focus Area | Status | Deliverables Summary |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **P0** | **Baseline Consolidation** | Git & Architecture | ✅ **Completed** | Synchronized `refactor/appctl-rework` with `main`, recorded control plane ADR, modernized metadata engine. |
|
||||||
|
| **P1** | **Mail Realignment** | Topology & State | ✅ **Completed** | Moved Stalwart to `smtp.<domain>`, migrated SnappyMail to `~/Sites/snappymail` with zero data loss. |
|
||||||
|
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core registry (`deployments.yaml`), Compose AST validator, systemd sandboxing. |
|
||||||
|
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 models (`core_manifest.py`), two-axis inspection, unified `appctl_engine.py`. |
|
||||||
|
| **P4** | **Control Plane Daemon** | API & Dispatch | 🎯 **Current / Up Next** | `homelab-appctl.service`, dual transport (socket + HTTP), single router, mandatory auth, thin-client CLI, audit log. |
|
||||||
|
| **P5** | **Identity & Secrets** | Auth & Providers | ⏳ **Planned** | LLDAP RBAC mapping, Authelia ForwardAuth headers, user-scoped token lifecycle, `SecretProvider` reference resolution. |
|
||||||
|
| **P6** | **Deployment Model & AI**| Intent Authoring | ⏳ **Planned** | Platform capability catalog, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. |
|
||||||
|
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, live log streaming (SSE), Homepage read-only status integration. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Milestone P0: Baseline Consolidation (Completed)
|
||||||
|
- Merged `refactor/appctl-rework` and `main` into a unified architectural baseline.
|
||||||
|
- Modernized metadata engine with strongly-typed models (`SitesApp`, `CoreService`, `SourceConfig`).
|
||||||
|
- Formalized control plane ADR (`homelab-appctl-control-plane-architecture.md`).
|
||||||
|
- Verified test harness (`./scripts/test`) and Nix flake sandbox.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Milestone P1: Mail Topology Realignment & Zero-Data-Loss Migration (Completed)
|
||||||
|
- Executed timestamped, SHA256-verified backup of SnappyMail data.
|
||||||
|
- Provisioned Class B Image-Only workload at `~/Sites/snappymail/` and state root at `~/var/lib/homelab/snappymail/`.
|
||||||
|
- Replicated state with byte parity verification (`diff -r`).
|
||||||
|
- Re-homed Stalwart public endpoint to `smtp.<domain>` and removed SnappyMail from Core stack.
|
||||||
|
- Verified webmail logins, address book persistence, and Diun SMTPS alert delivery on port 465.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Milestone P2: GitOps Privilege & Authority Hardening (Completed)
|
||||||
|
- Established `Core/config/deployments.yaml` as sole authority for admitted GitOps deployment repositories.
|
||||||
|
- Decoupled `~/Brain` data vault from workload continuous deployment.
|
||||||
|
- Implemented Compose AST security validator rejecting `privileged: true`, Docker socket binds, and host namespace escapes.
|
||||||
|
- Sandboxed `homelab-gitops.service` with `ProtectSystem=strict`, `NoNewPrivileges=true`, and private temporary directories.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Milestone P3: Manifest Contract Convergence & Provenance Engine (Completed)
|
||||||
|
- Released Schema v1.0 with fail-closed Pydantic v2 validation (`core_manifest.py`).
|
||||||
|
- Implemented two-axis inspection: local checkout state (`✓ Synced`, `* Dirty`) vs upstream software provenance (`git ls-remote` with 10s timeout).
|
||||||
|
- Promoted unified engine to `scripts/appctl_engine.py`, retired `appctl_engine_v2.py` shim, and achieved zero Pyright warnings.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API (Current / Up Next)
|
||||||
|
**Status**: 🎯 **Approved & Locked (Pre-P4 Security Gate Complete; Ready for Daemon Implementation)**
|
||||||
|
|
||||||
|
Implementation is divided into six dependency-ordered slices:
|
||||||
|
1. **Slice 1 — Pydantic v2 API Contracts & Error Sanitizer (`scripts/appctl_contracts.py`)**:
|
||||||
|
- Strict request/response/error/audit models (`ConfigDict(extra="forbid", strict=True)`), 64 KiB request limit, and input-sanitized error mapping (`include_input=False`).
|
||||||
|
- Add `"compose_pull"` to `ALLOWED_ACTIONS` in `scripts/core_manifest.py`.
|
||||||
|
2. **Slice 2 — Append-Only Audit Logger & Per-Target Lock Manager**:
|
||||||
|
- `AuditLogger` supporting `DISPATCHED`, `COMPLETED`, `FAILED`, `DENIED`, mode `0600`, secret redaction, and fail-closed disk guard.
|
||||||
|
- Non-blocking `fcntl.flock` manager for `/var/lib/homelab/appctl/locks/<target>.lock` and `_homepage_sync.lock`.
|
||||||
|
3. **Slice 3 — Authentication & 3-Role RBAC Gate**:
|
||||||
|
- SOPS `tokens.json` SHA-256 authenticator (`hmac.compare_digest`), UDS `SO_PEERCRED` fallback for viewer reads, and role-scoped authorization (`homelab-admin`, `homelab-operator` scoped to `deployments.yaml`, `homelab-viewer`).
|
||||||
|
4. **Slice 4 — Operational Router & Unified Execution Engine**:
|
||||||
|
- Pure-Python `.env` parser (no shell `source`), mandatory pre-flight checks, revision-consistent `workload.update`, bounded `workload.logs` (`tail` 1..1000), and atomic Homepage sync.
|
||||||
|
5. **Slice 5 — Dual-Transport HTTP/1.1 Daemon (`scripts/appctl_daemon.py`) & GitOps Cutover**:
|
||||||
|
- HTTP/1.1 server over `/run/homelab/appctl.sock` and `127.0.0.1:9001` with graceful signal handling.
|
||||||
|
- Rewire `scripts/gitops_dispatcher.py` worker to invoke `POST /v1/operations` (`workload.update`) over the Unix domain socket.
|
||||||
|
6. **Slice 6 — Thin-Client CLI (`scripts/appctl`), NixOS Service & Genericism Cleanup**:
|
||||||
|
- Re-implement `scripts/appctl` as thin UDS HTTP client.
|
||||||
|
- Declare `homelab-appctl.service` (`homelab-appctl:homelab-operators` + POSIX ACLs) in `nixos/modules/homeserver.nix`.
|
||||||
|
- Scrub remaining hardcoded domain/user literals and add `pyright` to `flake.nix` and pre-commit hooks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Milestone P5: Identity, RBAC & SecretProvider Interface (Planned)
|
||||||
|
- Plug Traefik/Authelia trusted ForwardAuth headers (`Remote-User`, `Remote-Groups`) with dedicated proxy authentication.
|
||||||
|
- Implement dynamic LLDAP user-scoped API token lifecycle.
|
||||||
|
- Implement `SecretProvider` interface resolving `secretKeyRef` references at container runtime without Git history pollution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Milestone P6: Homelab Deployment Model & AI Authoring Workflow (Planned)
|
||||||
|
- Machine-readable Platform Capability Catalog defining Core capabilities and security invariants.
|
||||||
|
- `DeploymentProposal` schema for AI-assisted service discovery.
|
||||||
|
- Operator approval Git pipeline: `DeploymentProposal` $\to$ committed `DeploymentModel` $\to$ `appctl` materialization.
|
||||||
|
- Human-in-the-loop approval invariant strictly enforced (AI has 0 execution authority).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Milestone P7: Operations UI & Dashboard Integration (Planned)
|
||||||
|
- Dedicated lightweight web console consuming the `appctl` API for proposal review, approval, real-time log streaming (SSE), and token management.
|
||||||
|
- Homepage read-only status integration widgets querying `appctl` live status endpoints.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Definition of Done & Quality Gates
|
||||||
|
|
||||||
|
1. **Unified Control Plane**: All platform operations execute through `homelab-appctl.service`. No secondary deployment scripts exist.
|
||||||
|
2. **Explicit Authentication Everywhere**: Host SSH access does not confer appctl mutation authority. Every mutating request presents an authenticated Bearer token.
|
||||||
|
3. **Transport Equivalence**: Hermetic test suite asserts 100% schema and status parity between UDS and HTTP listeners.
|
||||||
|
4. **Declarative Git Truth**: All workloads are governed by version-controlled definitions in Git.
|
||||||
|
5. **Secret Hygiene**: Zero plaintext credentials in deployment manifests; secrets resolve via tmpfs and dynamic providers.
|
||||||
|
6. **Safe Deployment Authoring**: AI agents act strictly as proposal generators; all mutations require human approval.
|
||||||
|
7. **Zero Production Regressions**: Platform migrations include pre-flight snapshots, state parity proofs, and documented rollback procedures.
|
||||||
|
8. **Automated Verification**: Every commit must pass `./scripts/test` (Ruff linter + Pytest suite + Pyright type checker + Nix flake check).
|
||||||
+1
-1
@@ -15,7 +15,7 @@ tags:
|
|||||||
# Architectural Discussion & Phased Implementation Plan: Homelab Core Appliance
|
# Architectural Discussion & Phased Implementation Plan: Homelab Core Appliance
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> Superseded by [Architecture Consolidation & Hardening Roadmap v2](../plans/architecture-consolidation-roadmap-v2.md).
|
> Superseded by [Architecture Consolidation & Hardening Roadmap v2](architecture-consolidation-roadmap-v2.md) and [v3](architecture-consolidation-roadmap-v3.md).
|
||||||
|
|
||||||
## Executive Summary
|
## Executive Summary
|
||||||
|
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,159 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: draft
|
||||||
|
project: homelab
|
||||||
|
tags:
|
||||||
|
- homelab
|
||||||
|
- dns
|
||||||
|
- cloudflare
|
||||||
|
- dynu
|
||||||
|
- cutover
|
||||||
|
- networking
|
||||||
|
---
|
||||||
|
|
||||||
|
# Dynu → Cloudflare Authoritative DNS Cutover Action Plan
|
||||||
|
|
||||||
|
This plan details the authoritative DNS migration for `roadtotech.me` from Dynu to Cloudflare using the declarative CLI tooling (`flarectl`, `hostinger`, `doggo`) and in-memory SOPS secret wrappers configured on your workstation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture & Operational Invariants
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
subgraph Step1["Phase 1: Cloudflare"]
|
||||||
|
CF["flarectl zone create<br/>--jumpstart"] --> Audit["Audit Records<br/>(A, CNAME, MX, TXT)"]
|
||||||
|
Audit --> Capture["Capture Assigned NS<br/>(e.g., ns1.cloudflare.com)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Step2["Phase 2: Hostinger"]
|
||||||
|
Capture --> Hostinger["hostinger domains portfolio<br/>update-nameservers"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Step3["Phase 3: Propagation"]
|
||||||
|
Hostinger --> Monitor["doggo NS roadtotech.me<br/>Live Propagation Verification"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Step4["Phase 4: Homelab Cleanup"]
|
||||||
|
Monitor --> Traefik["Update Traefik & DDNS<br/>in Core (Cloudflare Provider)"]
|
||||||
|
Traefik --> Revert["Revert Emergency<br/>networking.hosts Workarounds"]
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
### Critical Invariants
|
||||||
|
1. **The "Grey Cloud" (DNS-Only) Rule**: All homelab records (`roadtotech.me`, `*.roadtotech.me`, `mail.roadtotech.me`) must have Cloudflare proxying **disabled** (`--proxy=false`). Cloudflare’s HTTP proxy does not route non-HTTP traffic (Gitea SSH on port `2223`) and intercepts direct Let's Encrypt TLS handshakes.
|
||||||
|
2. **Transactional Mail Preservation**: Brevo verification TXT codes and SnappyMail MX records must be present in Cloudflare before nameserver cutover to ensure zero email disruption.
|
||||||
|
3. **In-Memory Credential Safety**: Invoking `flarectl` and `hostinger` through your shell wrappers (`home/shell/secrets.sh`) injects credentials directly into child process memory via `sops -d --extract`. Never pipe or write decrypted tokens to disk.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Execution Phases
|
||||||
|
|
||||||
|
### Phase 1: Cloudflare Zone Setup & Record Audit (`flarectl`)
|
||||||
|
|
||||||
|
#### 1.1 Create the Zone with Automatic Crawling
|
||||||
|
Run `flarectl zone create` with `--jumpstart` so Cloudflare automatically queries public DNS and imports active records:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
flarectl zone create --zone roadtotech.me --jumpstart
|
||||||
|
```
|
||||||
|
|
||||||
|
*Expected Output*: Returns a table displaying the new **Zone ID** and the **Name Servers** assigned to your domain (e.g., `ns1.cloudflare.com`, `ns2.cloudflare.com`). Note these two nameservers for Phase 2.
|
||||||
|
|
||||||
|
#### 1.2 Audit Crawled DNS Records
|
||||||
|
Verify that Cloudflare discovered the existing records:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
flarectl dns list --zone roadtotech.me
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 1.3 Ensure Required Homelab & Mail Records Exist
|
||||||
|
Compare the output against the required homelab record set. If any record was missed during the jumpstart crawl (e.g. because Dynu was timing out), create it explicitly:
|
||||||
|
|
||||||
|
| Name | Type | Target Content | Proxy State | Purpose | CLI Creation Command (if missing) |
|
||||||
|
| :--- | :---: | :--- | :---: | :--- | :--- |
|
||||||
|
| `@` | `A` | `186.112.11.188` | **DNS Only** | Apex domain pointing to homelab WAN IP | `flarectl dns create --zone roadtotech.me --name roadtotech.me --type A --content 186.112.11.188 --proxy=false` |
|
||||||
|
| `*` | `CNAME` | `roadtotech.me` | **DNS Only** | Wildcard routing for all Sites behind Traefik | `flarectl dns create --zone roadtotech.me --name "*" --type CNAME --content roadtotech.me --proxy=false` |
|
||||||
|
| `mail` | `A` | `186.112.11.188` | **DNS Only** | SnappyMail webmail endpoint | `flarectl dns create --zone roadtotech.me --name mail.roadtotech.me --type A --content 186.112.11.188 --proxy=false` |
|
||||||
|
| `@` | `MX` | `mail.roadtotech.me` | N/A | Inbound mail routing (Priority 10) | `flarectl dns create --zone roadtotech.me --name roadtotech.me --type MX --content mail.roadtotech.me --priority 10` |
|
||||||
|
| `@` | `TXT` | `brevo-code:0509c2a6d12137c59d9e6b7fbef9fe8d` | N/A | Brevo outbound domain authentication | `flarectl dns create --zone roadtotech.me --name roadtotech.me --type TXT --content "brevo-code:0509c2a6d12137c59d9e6b7fbef9fe8d"` |
|
||||||
|
| `_dmarc` | `TXT` | `v=DMARC1; p=none; rua=mailto:rua@dmarc.brevo.com` | N/A | DMARC email security policy | `flarectl dns create --zone roadtotech.me --name _dmarc.roadtotech.me --type TXT --content "v=DMARC1; p=none; rua=mailto:rua@dmarc.brevo.com"` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 2: Hostinger Nameserver Cutover (`hostinger`)
|
||||||
|
|
||||||
|
Once the Cloudflare zone is populated with all records, update the registrar delegation at Hostinger.
|
||||||
|
|
||||||
|
#### 2.1 Inspect Current Delegation
|
||||||
|
Verify your domain's current nameserver registration:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hostinger domains portfolio get roadtotech.me
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2.2 Update Nameservers to Cloudflare
|
||||||
|
Replace `<ns1>` and `<ns2>` with the exact nameservers assigned by Cloudflare in Step 1.1:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hostinger domains portfolio update-nameservers roadtotech.me \
|
||||||
|
--ns1 <assigned-ns-1>.ns.cloudflare.com \
|
||||||
|
--ns2 <assigned-ns-2>.ns.cloudflare.com
|
||||||
|
```
|
||||||
|
|
||||||
|
*Expected Output*: Returns `Status: OK` confirming that custom nameservers were submitted to the registry.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 3: Propagation Verification (`doggo`)
|
||||||
|
|
||||||
|
Root TLD nameserver updates typically take between 2 to 15 minutes to reflect across global recursive caches.
|
||||||
|
|
||||||
|
#### 3.1 Verify Authoritative Nameserver Cutover
|
||||||
|
Query the parent `.me` nameservers directly to confirm the registrar published the new delegation:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Query root authoritative DNS
|
||||||
|
doggo NS roadtotech.me @1.1.1.1
|
||||||
|
doggo NS roadtotech.me @8.8.8.8
|
||||||
|
```
|
||||||
|
*Verification Check*: Output should list the two Cloudflare nameservers instead of `ns*.dynu.com`.
|
||||||
|
|
||||||
|
#### 3.2 Verify Public Hostname Resolution
|
||||||
|
Check that public resolvers return your homelab's current WAN IP (`186.112.11.188`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Verify apex, Gitea, and mail endpoints
|
||||||
|
doggo roadtotech.me @1.1.1.1
|
||||||
|
doggo gitea.roadtotech.me @1.1.1.1
|
||||||
|
doggo mail.roadtotech.me @1.1.1.1
|
||||||
|
```
|
||||||
|
*Verification Check*: Returns `186.112.11.188` with a low TTL (~300s).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 4: Homelab Core Refactor & Cleanup
|
||||||
|
|
||||||
|
Once public DNS is fully answering from Cloudflare, we bring the homelab appliance into permanent alignment:
|
||||||
|
|
||||||
|
#### 4.1 Update Traefik ACME Challenge Provider (`Core`)
|
||||||
|
In `~/Homelab/Core/docker-compose.yml`:
|
||||||
|
* Replace `--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu` with `cloudflare`.
|
||||||
|
* Update the environment projection in `nixos/modules/homeserver.nix` to inject `CF_DNS_API_TOKEN` instead of `DYNU_API_KEY`.
|
||||||
|
|
||||||
|
#### 4.2 Replace Dynu Monitor with Cloudflare DDNS
|
||||||
|
* Decommission `dynu-monitor.service` and `dynu-monitor.timer`.
|
||||||
|
* Configure `ddclient` (or a dedicated Cloudflare API updater unit) to update Cloudflare's A record when the WAN IP rotates.
|
||||||
|
|
||||||
|
#### 4.3 Revert Emergency Workarounds
|
||||||
|
* **Laptop (`~/Config`)**:
|
||||||
|
```bash
|
||||||
|
git -C ~/Config checkout main
|
||||||
|
sudo nixos-rebuild switch --flake ~/Config#laptop
|
||||||
|
git -C ~/Config branch -D chore/dynu-outage-workaround
|
||||||
|
```
|
||||||
|
* **Server (`~/Homelab/Core`)**:
|
||||||
|
```bash
|
||||||
|
git -C ~/Homelab/Core checkout main
|
||||||
|
git -C ~/Homelab/Core branch -D fix/server-loopback-dns
|
||||||
|
```
|
||||||
+1
-1
@@ -95,4 +95,4 @@ appctl update --all
|
|||||||
---
|
---
|
||||||
|
|
||||||
## 🔗 Production Guide
|
## 🔗 Production Guide
|
||||||
* [Homelab Architecture: Appctl & Decentralized Repositories](../guides/appctl-operations-and-manifest-guide.md)
|
* [Homelab Architecture: Appctl & Decentralized Repositories](../../04-learning/guides/homelab/appctl-operations-and-manifest-guide.md)
|
||||||
+2
-2
@@ -57,6 +57,6 @@ Rather than relying on continuous image polling via Watchtower, the homelab adop
|
|||||||
---
|
---
|
||||||
|
|
||||||
## 🔗 Production Guides & Specifications
|
## 🔗 Production Guides & Specifications
|
||||||
* [Dynamic Decentralized GitOps Dispatcher Architecture](../../discussions/gitops-dispatcher-architecture.md)
|
* [Dynamic Decentralized GitOps Dispatcher Architecture](../../../02-discussions/homelab/gitops-dispatcher-architecture.md)
|
||||||
* [Brain GitOps & Auto-Sync Deployment Pipeline](../../guides/brain-gitops-deployment-pipeline.md)
|
* [Brain GitOps & Auto-Sync Deployment Pipeline](../../../04-learning/guides/homelab/brain-gitops-deployment-pipeline.md)
|
||||||
* [GitHub to Gitea Automated Batch Migration Plan](github-to-gitea-migration-plan.md)
|
* [GitHub to Gitea Automated Batch Migration Plan](github-to-gitea-migration-plan.md)
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,217 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: completed
|
||||||
|
project: homelab
|
||||||
|
date: 2026-09-23
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- homelab
|
||||||
|
- core
|
||||||
|
- portainer
|
||||||
|
- deprecation
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan: Clean Deprecation of Portainer from Core
|
||||||
|
|
||||||
|
## Goal Description
|
||||||
|
|
||||||
|
Portainer was inherited during early Core consolidation, but its responsibility (GUI-based Docker container management) conflicts with the Homelab's architectural invariants:
|
||||||
|
1. **Infrastructure as Code & GitOps**: All workloads and core services are declaratively defined in NixOS, `docker-compose.yml`, and `app.yaml`, with deployment managed via `appctl` and automated webhooks. Manual GUI container mutations bypass repository state.
|
||||||
|
2. **Hardened Docker Socket**: The security architecture enforces a strict read-only Docker socket proxy (`socket-proxy` with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`). Portainer is unable to manage, deploy, or modify containers without weakening this boundary.
|
||||||
|
3. **Overlapping Tools**: Read-only log observation is handled by Dozzle, routing by Traefik, host lifecycle by NixOS, and service cataloging by Homepage. Portainer holds no unique responsibilities.
|
||||||
|
|
||||||
|
This plan details the complete, clean removal of Portainer across all layers of Homelab Core: Docker Compose, `appctl`, Homepage, NixOS SOPS secrets, structural/security tests, documentation, and production runtime cleanup.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Decisions Reached
|
||||||
|
|
||||||
|
1. **Volume Cleanup**: Purge `core_portainer_data`, `homeserver_portainer_data`, and `portainer_portainer_data` on the server during the post-deployment cleanup phase.
|
||||||
|
2. **SOPS Secret Removal**: Remove `portainer.admin_password` completely from `Core/nixos/secrets.yaml` and `Core/nixos/modules/homeserver.nix`.
|
||||||
|
3. **Gitea & Runner Decoupling**: Retain Gitea and `act_runner` standalone in `Sites/gitea` to maintain platform trust boundaries and unprivileged runner execution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture & Affected Components
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph Core Repository
|
||||||
|
Compose["Core/docker-compose.yml<br/>(Remove portainer service & volume)"]
|
||||||
|
NixOS["Core/nixos/modules/homeserver.nix<br/>(Remove portainer SOPS secret & env var)"]
|
||||||
|
SOPS["Core/nixos/secrets.yaml<br/>(Prune portainer: admin_password)"]
|
||||||
|
Appctl["Core/scripts/appctl_engine.py<br/>(Remove portainer from get_core_services & metadata)"]
|
||||||
|
Homepage["Core/config/homepage/services.yaml<br/>(Regenerate / remove Portainer card)"]
|
||||||
|
Tests["Core/tests/security/test_security_invariants.py<br/>(Add absence assertion)"]
|
||||||
|
Docs["Documentation (6 files)<br/>(README, SECURITY, architecture, operations, appctl, secrets)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Production Runtime
|
||||||
|
NixRebuild["sudo nixos-rebuild switch --flake ~/Core#server<br/>(Updates env, triggers compose --remove-orphans)"]
|
||||||
|
VolPrune["docker volume rm ...<br/>(Purge stale Portainer volumes)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
Compose --> NixRebuild
|
||||||
|
NixOS --> NixRebuild
|
||||||
|
SOPS --> NixRebuild
|
||||||
|
NixRebuild --> VolPrune
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Component Changes
|
||||||
|
|
||||||
|
### Component 1: Docker Compose & Host Orchestration
|
||||||
|
* `Core/docker-compose.yml`:
|
||||||
|
- Removed `portainer` service declaration.
|
||||||
|
- Removed `portainer_data:` from top-level `volumes:`.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Removed from Core/docker-compose.yml
|
||||||
|
portainer:
|
||||||
|
image: portainer/portainer-ce:latest
|
||||||
|
container_name: portainer
|
||||||
|
restart: always
|
||||||
|
command: >
|
||||||
|
-H tcp://socket-proxy:2375
|
||||||
|
--admin-password=${PORTAINER_ADMIN_PASSWORD}
|
||||||
|
--no-analytics
|
||||||
|
volumes:
|
||||||
|
- portainer_data:/data
|
||||||
|
networks:
|
||||||
|
- socket-net
|
||||||
|
- proxy-net
|
||||||
|
labels:
|
||||||
|
- "traefik.enable=true"
|
||||||
|
- "traefik.http.routers.portainer.rule=Host(`portainer.${DOMAIN}`)"
|
||||||
|
- "traefik.http.routers.portainer.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.portainer.tls=true"
|
||||||
|
- "traefik.http.routers.portainer.tls.certresolver=myresolver"
|
||||||
|
- "traefik.http.routers.portainer.middlewares=authelia-auth@docker"
|
||||||
|
- "traefik.http.routers.portainer.service=portainer-svc"
|
||||||
|
- "traefik.http.routers.portainer-red.rule=Host(`portainer.${DOMAIN}`)"
|
||||||
|
- "traefik.http.routers.portainer-red.entrypoints=web"
|
||||||
|
- "traefik.http.routers.portainer-red.middlewares=https-redirect@docker"
|
||||||
|
- "traefik.http.services.portainer-svc.loadbalancer.server.port=9000"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Component 2: NixOS Module & SOPS Secrets
|
||||||
|
* `Core/nixos/modules/homeserver.nix`:
|
||||||
|
- Removed `"portainer/admin_password"` from `sops.secrets`.
|
||||||
|
- Removed `PORTAINER_ADMIN_PASSWORD = config.sops.placeholder."portainer/admin_password";` from `sops.templates."homeserver.env".content`.
|
||||||
|
* `Core/nixos/secrets.yaml`:
|
||||||
|
- Decrypted via SOPS CLI and removed `portainer: admin_password` key block.
|
||||||
|
|
||||||
|
### Component 3: CLI Orchestrator (`appctl`) & Homepage Dashboard
|
||||||
|
* `Core/scripts/appctl_engine.py`:
|
||||||
|
- Removed `"portainer"` service map from `get_core_services()`.
|
||||||
|
- Removed `"portainer"` from Homepage card weight metadata.
|
||||||
|
* `Core/config/homepage/services.yaml`:
|
||||||
|
- Removed `Portainer` card from `Core Infrastructure` dashboard category.
|
||||||
|
|
||||||
|
### Component 4: Architecture & Security Invariant Tests
|
||||||
|
* `Core/tests/security/test_security_invariants.py`:
|
||||||
|
- Added regression assertion `test_portainer_is_deprecated_and_absent()` verifying that neither the service nor volume exists in `docker-compose.yml`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def test_portainer_is_deprecated_and_absent():
|
||||||
|
"""Ensure portainer service and volume are completely absent from core docker-compose."""
|
||||||
|
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||||
|
with open(compose_path, encoding="utf-8") as f:
|
||||||
|
compose = yaml.safe_load(f)
|
||||||
|
|
||||||
|
services = compose.get("services", {})
|
||||||
|
assert "portainer" not in services, "Deprecated service 'portainer' must not exist in docker-compose.yml"
|
||||||
|
|
||||||
|
volumes = compose.get("volumes", {})
|
||||||
|
assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Component 5: Documentation Synchronization
|
||||||
|
* `Core/SECURITY.md`: Removed Portainer from protected proxy services.
|
||||||
|
* `Core/README.md`: Removed Portainer from platform overview, topology ASCII diagram, and routing table.
|
||||||
|
* `Core/docs/secrets-and-state.md`: Removed `portainer_data` from state table.
|
||||||
|
* `Core/docs/appctl.md`: Removed `portainer` from core service enumeration.
|
||||||
|
* `Core/docs/operations.md`: Removed Portainer from systemd and troubleshooting notes.
|
||||||
|
* `Core/docs/architecture.md`: Removed Portainer from topology and service mesh documentation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Action Items & Milestones
|
||||||
|
|
||||||
|
- [x] **Branch Isolation**: Create local git branch `fix/deprecate-portainer` in `Core`.
|
||||||
|
- [x] **Docker Compose**: Remove `portainer` service block and `portainer_data` volume from `Core/docker-compose.yml`.
|
||||||
|
- [x] **NixOS Configuration**: Remove `portainer/admin_password` from `Core/nixos/modules/homeserver.nix`.
|
||||||
|
- [x] **SOPS Secrets**: Decrypt and prune `portainer` key from `Core/nixos/secrets.yaml`.
|
||||||
|
- [x] **Appctl Engine**: Remove `portainer` from `get_core_services()` and Homepage metadata in `Core/scripts/appctl_engine.py`.
|
||||||
|
- [x] **Homepage Config**: Update `Core/config/homepage/services.yaml` to remove Portainer.
|
||||||
|
- [x] **Invariants & Tests**: Add `test_portainer_is_deprecated_and_absent` to `Core/tests/security/test_security_invariants.py`.
|
||||||
|
- [x] **Documentation**: Clean up references in `Core/SECURITY.md`, `Core/README.md`, `Core/docs/secrets-and-state.md`, `Core/docs/appctl.md`, `Core/docs/operations.md`, and `Core/docs/architecture.md`.
|
||||||
|
- [x] **Local Validation**: Run `ruff check .`, `pytest`, `nix flake check`, and `./scripts/test`.
|
||||||
|
- [x] **Commit Proposal**: Propose atomic commit for user review and integration into `main`.
|
||||||
|
- [x] **Production Deployment**: User rebuilds NixOS (`sudo nixos-rebuild switch --flake ~/Core#server`), runs `appctl sync`, and prunes leftover volumes.
|
||||||
|
- [x] **Post-Deployment Verification**: Verify portainer is uninstalled, routing 404s, and Dozzle/Core remain healthy.
|
||||||
|
- [x] **Daily Journal**: Log completed work in `records/journal/2026-09-23.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deployment & Production Teardown Runbook
|
||||||
|
|
||||||
|
### Phase 1: User-Controlled Commit & Integration
|
||||||
|
```bash
|
||||||
|
# On local workstation (/home/kiskaadee/Homelab/Core):
|
||||||
|
git checkout -b fix/deprecate-portainer
|
||||||
|
git add docker-compose.yml nixos/ scripts/ config/ tests/ docs/ README.md SECURITY.md
|
||||||
|
git commit -m "refactor(core): cleanly deprecate and remove portainer"
|
||||||
|
git checkout main
|
||||||
|
git merge fix/deprecate-portainer
|
||||||
|
git push origin main
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2: Production Deployment on Server
|
||||||
|
```bash
|
||||||
|
# SSH into production server
|
||||||
|
ssh server-local
|
||||||
|
|
||||||
|
# Pull latest Core updates
|
||||||
|
cd ~/Core
|
||||||
|
git pull origin main
|
||||||
|
|
||||||
|
# Rebuild NixOS configuration (regenerates /run/secrets/homeserver.env and restarts homeserver-core with --remove-orphans)
|
||||||
|
sudo nixos-rebuild switch --flake ~/Core#server
|
||||||
|
|
||||||
|
# Sync homepage to remove Portainer card
|
||||||
|
appctl sync
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 3: Post-Deployment Verification
|
||||||
|
```bash
|
||||||
|
# Verify portainer container has been stopped and removed
|
||||||
|
docker ps -a --filter name=portainer
|
||||||
|
# Expected: empty table
|
||||||
|
|
||||||
|
# Verify Traefik has unregistered the portainer router
|
||||||
|
curl -kI https://portainer.roadtotech.me
|
||||||
|
# Expected: 404 Not Found (Traefik default)
|
||||||
|
|
||||||
|
# Verify Dozzle and other core services remain operational
|
||||||
|
appctl list --core
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 4: Stale Volume Cleanup
|
||||||
|
```bash
|
||||||
|
# Remove leftover Portainer data volumes
|
||||||
|
docker volume rm core_portainer_data homeserver_portainer_data portainer_portainer_data
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rollback Plan
|
||||||
|
If an unexpected regression occurs in the Core compose stack:
|
||||||
|
1. On local workstation: `git revert HEAD` and push to `main`.
|
||||||
|
2. On server: `cd ~/Core && git pull origin main && sudo nixos-rebuild switch --flake ~/Core#server`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Related Documentation & Cross-References
|
||||||
|
|
||||||
|
* Discussion: [Core Service Qualification & Portainer Deprecation](../../02-discussions/homelab/core-service-qualification-and-portainer-deprecation.md)
|
||||||
|
* Daily Journal: [Daily Journal: 2026-09-23](../../03-records/journal/2026-09-23.md)
|
||||||
+1
-1
@@ -90,4 +90,4 @@ All 11 homelab applications will include an `app.yaml` defining their identity,
|
|||||||
---
|
---
|
||||||
|
|
||||||
## 🔗 Production Guide
|
## 🔗 Production Guide
|
||||||
* [Homelab Architecture: Appctl & Decentralized Repositories](../guides/appctl-operations-and-manifest-guide.md)
|
* [Homelab Architecture: Appctl & Decentralized Repositories](../../04-learning/guides/homelab/appctl-operations-and-manifest-guide.md)
|
||||||
+3
-3
@@ -21,7 +21,7 @@ Establish clear, unambiguous directory boundaries across both the Server and Lap
|
|||||||
## 🗺️ Realized Production Layout
|
## 🗺️ Realized Production Layout
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> The initial proposal for a monolithic `~/Deployments` directory was superseded by the decoupled `~/Core` and `~/Sites` architecture documented in [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/appctl-operations-and-manifest-guide.md) and executed in [Core & Sites Cutover and Testing Plan](../../archive/core-sites-cutover-testing-plan.md).
|
> The initial proposal for a monolithic `~/Deployments` directory was superseded by the decoupled `~/Core` and `~/Sites` architecture documented in [Homelab Architecture: Appctl & Decentralized Repositories](../../../04-learning/guides/homelab/appctl-operations-and-manifest-guide.md) and executed in [Core & Sites Cutover and Testing Plan](../core-sites-cutover-testing-plan.md).
|
||||||
|
|
||||||
### 🖥️ Production Server Layout (`~/`)
|
### 🖥️ Production Server Layout (`~/`)
|
||||||
```text
|
```text
|
||||||
@@ -54,5 +54,5 @@ Establish clear, unambiguous directory boundaries across both the Server and Lap
|
|||||||
---
|
---
|
||||||
|
|
||||||
## 🔗 Related Documents
|
## 🔗 Related Documents
|
||||||
* [Homelab Architecture: Appctl & Decentralized Repositories](../../guides/appctl-operations-and-manifest-guide.md)
|
* [Homelab Architecture: Appctl & Decentralized Repositories](../../../04-learning/guides/homelab/appctl-operations-and-manifest-guide.md)
|
||||||
* [Core & Sites Cutover and Testing Plan](../../archive/core-sites-cutover-testing-plan.md)
|
* [Core & Sites Cutover and Testing Plan](../core-sites-cutover-testing-plan.md)
|
||||||
File renamed without changes.
File renamed without changes.
+3
-3
@@ -19,7 +19,7 @@ The **Learning Platform** (`Sites/learning`) is an integrated personal developme
|
|||||||
Rather than being just a static web UI, it is designed as a **hybrid system**:
|
Rather than being just a static web UI, it is designed as a **hybrid system**:
|
||||||
1. **A Web Dashboard**: Visualizing active courses, study streaks, and a DSA pattern mastery matrix.
|
1. **A Web Dashboard**: Visualizing active courses, study streaks, and a DSA pattern mastery matrix.
|
||||||
2. **A Tactical CLI Tool**: Zero-friction terminal commands (`learning daily`, `learning draft`, `learning review`) for local problem-solving sessions.
|
2. **A Tactical CLI Tool**: Zero-friction terminal commands (`learning daily`, `learning draft`, `learning review`) for local problem-solving sessions.
|
||||||
3. **An MCP & REST Service**: Acting as the stateful backend consumed by the [Supervisor System](../../supervisor/plans/supervisor-system-specification.md) to ambiently monitor learning objectives, active study sessions, and milestone verification.
|
3. **An MCP & REST Service**: Acting as the stateful backend consumed by the [Supervisor System](../supervisor/supervisor-system-specification.md) to ambiently monitor learning objectives, active study sessions, and milestone verification.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ Beyond raw course links and basic problem lists, a top-tier learning companion f
|
|||||||
- **Communication Clarity**: Did you articulate *why* the algorithm works in the Intuition section as you would to an interviewer?
|
- **Communication Clarity**: Did you articulate *why* the algorithm works in the Intuition section as you would to an interviewer?
|
||||||
- **Alternative Approaches**: Socratic hints toward optimal trade-offs (e.g. hashmap vs two-pointer).
|
- **Alternative Approaches**: Socratic hints toward optimal trade-offs (e.g. hashmap vs two-pointer).
|
||||||
3. **Pattern Exposure & Blind-Spot Radar**:
|
3. **Pattern Exposure & Blind-Spot Radar**:
|
||||||
- Tracking exposure across the 16 core patterns identified in [`00-practiced-patterns.md`](../../../practice/LeetCode/00-practiced-patterns.md) (Two Pointers, Sliding Window, Monotonic Stack, Backtracking, DP, Graphs, etc.).
|
- Tracking exposure across the 16 core patterns identified in [`00-practiced-patterns.md`](../../04-learning/practice/LeetCode/00-practiced-patterns.md) (Two Pointers, Sliding Window, Monotonic Stack, Backtracking, DP, Graphs, etc.).
|
||||||
- Visualizing coverage: *"You have solved 6 HashMap problems, but 0 Sliding Window or Graph problems this month."*
|
- Visualizing coverage: *"You have solved 6 HashMap problems, but 0 Sliding Window or Graph problems this month."*
|
||||||
4. **Spaced Repetition & Weakness Queue**:
|
4. **Spaced Repetition & Weakness Queue**:
|
||||||
- Problems tagged as `struggled` or `need-review` automatically resurface on a Leitner-style schedule (e.g. 3 days, 10 days, 30 days).
|
- Problems tagged as `struggled` or `need-review` automatically resurface on a Leitner-style schedule (e.g. 3 days, 10 days, 30 days).
|
||||||
@@ -94,7 +94,7 @@ Beyond raw course links and basic problem lists, a top-tier learning companion f
|
|||||||
---
|
---
|
||||||
|
|
||||||
### Pillar 3: Supervisor & MCP Integration (Autonomous Navigation)
|
### Pillar 3: Supervisor & MCP Integration (Autonomous Navigation)
|
||||||
Following the [Supervisor System Specification](../../supervisor/plans/supervisor-system-specification.md):
|
Following the [Supervisor System Specification](../supervisor/supervisor-system-specification.md):
|
||||||
- Expose an **MCP Server (Model Context Protocol)** directly from the Learning application so AI tools (like Antigravity or Supervisor) can:
|
- Expose an **MCP Server (Model Context Protocol)** directly from the Learning application so AI tools (like Antigravity or Supervisor) can:
|
||||||
- `get_daily_challenge()`: Inspect today's problem.
|
- `get_daily_challenge()`: Inspect today's problem.
|
||||||
- `get_active_curriculum()`: Check what courses or chapters are currently on deck.
|
- `get_active_curriculum()`: Check what courses or chapters are currently on deck.
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: magnetflix
|
||||||
|
tags:
|
||||||
|
- extension
|
||||||
|
- firefox
|
||||||
|
- chrome
|
||||||
|
- plan
|
||||||
|
- webextension
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🧲 Plan: MagNetFlix Cross-Browser Extension Integration
|
||||||
|
|
||||||
|
An actionable implementation plan for evolving the working proof-of-concept (PoC) into a production-grade cross-browser extension that intercepts magnet links and routes them directly to the self-hosted MagNetFlix platform.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Context & Objective
|
||||||
|
|
||||||
|
The primary entry point for acquiring media is web browsing (torrent trackers, indexers, public domain archives). Without an extension, the user must copy the magnet link, open the media server dashboard, paste the link, and manually search for the movie ID.
|
||||||
|
|
||||||
|
The **MagNetFlix Browser Extension** automates this flow:
|
||||||
|
1. Intercepts any `magnet:` URI clicked on the web before the browser hands it off to an OS client.
|
||||||
|
2. Injects a non-blocking confirmation dialog (**"Magnet link captured!"**).
|
||||||
|
3. Handoffs the captured magnet link to the self-hosted dashboard at `https://magnetflix.<DOMAIN>/pair?magnet=<url>`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔬 Proof of Concept (PoC) Baseline
|
||||||
|
|
||||||
|
A fully functional proof of concept has been implemented and tested:
|
||||||
|
|
||||||
|
- **Local Repository**: `~/Projects/learning/extensions/magnetflix-extension`
|
||||||
|
- **Main Forge**: `https://gitea.roadtotech.me/kiskaadee/MagNetFlix`
|
||||||
|
- **Target Browser**: Firefox (Manifest V2) with full Chromium compatibility.
|
||||||
|
|
||||||
|
### What the PoC Achieved
|
||||||
|
- **Capture-Phase Hooking**: `content.js` captures click events on `a[href^="magnet:"]` via `document.addEventListener('click', ..., true)` and suppresses native protocol hijacking with `e.preventDefault()`.
|
||||||
|
- **CSS Isolation via Shadow DOM**: The confirmation modal is injected into an isolated Shadow DOM root to prevent host page style bleeding.
|
||||||
|
- **Dynamic IMDb Search**: `app.js` executes debounced (250ms) character-by-character queries against the IMDb suggestion API, retrieving top 5 matches with posters, titles, years, IMDb IDs, and cast.
|
||||||
|
- **Fixed State Transition**: Selecting a movie locks both the magnet input and movie selection, rendering the **SEND** button.
|
||||||
|
- **FastAPI Dispatch**: Dispatches `POST http://localhost:8000/download` with `{ "magnet": "...", "imdbid": "..." }`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Production Evolution Strategy
|
||||||
|
|
||||||
|
While the PoC embeds the pairing UI inside an internal extension page (`app.html`), the production architecture will transition to a **hybrid model**:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph Browser ["Web Browser Context"]
|
||||||
|
Click["User clicks magnet: link\non any webpage"] --> Hook["content.js hooks click\n& displays Shadow DOM modal"]
|
||||||
|
Hook -->|"Click 'Continue'"| Choice{"Extension Mode"}
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph ModeA ["Mode A: Web Dashboard Handoff (Default)"]
|
||||||
|
Choice -->|"Open Dashboard Tab"| DashURL["https://magnetflix.<DOMAIN>/pair?magnet=..."]
|
||||||
|
DashURL --> TraefikEdge["Traefik Ingress + Authelia SSO"]
|
||||||
|
TraefikEdge --> BFFPage["FastAPI BFF /pair Page\n(Full Movie Search UI)"]
|
||||||
|
BFFPage --> Submit["User selects movie & clicks SEND\n(Direct to BFF with SSO session)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph ModeB ["Mode B: Standalone / Internal Mode (Self-Contained)"]
|
||||||
|
Choice -->|"Internal Extension Tab"| LocalApp["app.html (Bundled with Extension)"]
|
||||||
|
LocalApp --> APICall["POST https://magnetflix.<DOMAIN>/api/v1/downloads\n(Using Stored API Key / Token)"]
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key Production Changes
|
||||||
|
1. **Redirect to Centralized Web Dashboard (`magnetflix.<DOMAIN>`)**:
|
||||||
|
- Clicking "Continue" opens `https://magnetflix.<DOMAIN>/pair?magnet=${encodeURIComponent(magnet)}`.
|
||||||
|
- Leverage Authelia SSO session cookies already present in the browser — no need to store sensitive API credentials in extension storage.
|
||||||
|
2. **Configurable Server URL in Options**:
|
||||||
|
- Allow user to configure their MagNetFlix base URL (e.g., `https://magnetflix.roadtotech.me` or `http://localhost:8000`).
|
||||||
|
3. **Manifest V3 / Cross-Browser Packaging**:
|
||||||
|
- Provide a dual build setup: Manifest V2 for Firefox (or MV3 with event pages) and Manifest V3 for Chromium/Edge.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 Phased Execution Roadmap
|
||||||
|
|
||||||
|
### Phase 1: Settings & Configurable Domain
|
||||||
|
- [ ] Add `options.html` / `options.js` for setting custom server URL:
|
||||||
|
- Default: `https://magnetflix.roadtotech.me`
|
||||||
|
- Fallback/Dev: `http://localhost:8000`
|
||||||
|
- [ ] Store preferences in `browser.storage.sync`.
|
||||||
|
- [ ] Update `popup.html` to link to settings.
|
||||||
|
|
||||||
|
### Phase 2: Web Dashboard Handoff Integration
|
||||||
|
- [ ] Implement the `/pair` route in `services/bff`:
|
||||||
|
- Renders the pairing UI currently prototyped in `app.html`.
|
||||||
|
- Populates magnet field from URL query parameter `?magnet=...`.
|
||||||
|
- Integrates Authelia authenticated user context directly from `Remote-User` header.
|
||||||
|
- [ ] Update extension `content.js` to redirect to configured server URL `/pair?magnet=...` instead of internal `app.html`.
|
||||||
|
|
||||||
|
### Phase 3: Manifest V3 & Cross-Browser Packaging
|
||||||
|
- [ ] Convert background script into service worker for Chrome MV3 compliance.
|
||||||
|
- [ ] Maintain Firefox MV2 / MV3 manifest variant for seamless installation.
|
||||||
|
- [ ] Set up `web-ext build` packaging script in monorepo or dedicated extension repo.
|
||||||
|
|
||||||
|
### Phase 4: Production Polishing & Distribution
|
||||||
|
- [ ] Add context menu entry: right click on any link -> `"Send Magnet to MagNetFlix"`.
|
||||||
|
- [ ] Self-host signed `.xpi` on `gitea.roadtotech.me` releases or submit to Firefox Add-ons / Chrome Web Store.
|
||||||
+8
-2
@@ -1,17 +1,23 @@
|
|||||||
---
|
---
|
||||||
type: plan
|
type: plan
|
||||||
status: active
|
status: superseded
|
||||||
|
superseded_by: ~/Config/home/scripts/new-repo.py
|
||||||
project: new-repo
|
project: new-repo
|
||||||
tags:
|
tags:
|
||||||
- gitea
|
- gitea
|
||||||
- github
|
- github
|
||||||
- rust
|
- python
|
||||||
- automation
|
- automation
|
||||||
- cli
|
- cli
|
||||||
- sops
|
- sops
|
||||||
---
|
---
|
||||||
# 📋 Implementation Plan — `new-repo` Provisioning CLI
|
# 📋 Implementation Plan — `new-repo` Provisioning CLI
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> **Architecture Pivot (2026-10-09)**:
|
||||||
|
> This plan's compiled Rust approach was evaluated and superseded by a lightweight, zero-dependency Python 3 implementation located in `~/Config/home/scripts/new-repo.py`. This eliminated cargo build steps while preserving strict typing (Pyright), linting (Ruff), and in-memory SOPS security.
|
||||||
|
|
||||||
|
|
||||||
## 🎯 Objective
|
## 🎯 Objective
|
||||||
Build a fast, type-safe, and self-contained Rust command-line tool (`new-repo`) to provision repositories across self-hosted Gitea and GitHub with automated push mirroring, template generation, and zero plaintext secret leakage.
|
Build a fast, type-safe, and self-contained Rust command-line tool (`new-repo`) to provision repositories across self-hosted Gitea and GitHub with automated push mirroring, template generation, and zero plaintext secret leakage.
|
||||||
|
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+1
-1
@@ -193,7 +193,7 @@ Phase 2: Workstation Architectural Consolidation
|
|||||||
2. Dissolved the 3 Home Manager tiers (`Tier 1 / Tier 2 / Tier 3`) into clean functional domains (`desktop`, `dev`, `shell`).
|
2. Dissolved the 3 Home Manager tiers (`Tier 1 / Tier 2 / Tier 3`) into clean functional domains (`desktop`, `dev`, `shell`).
|
||||||
3. Consolidated package lists by domain, eliminating duplicated definitions.
|
3. Consolidated package lists by domain, eliminating duplicated definitions.
|
||||||
4. Refined boundaries and secrets architecture per [`secrets-architecture-and-workstation-cleanup.md`](secrets-architecture-and-workstation-cleanup.md).
|
4. Refined boundaries and secrets architecture per [`secrets-architecture-and-workstation-cleanup.md`](secrets-architecture-and-workstation-cleanup.md).
|
||||||
5. Comprehensive execution walkthrough documented in [`standalone-workstation-walkthrough.md`](../guides/standalone-workstation-walkthrough.md).
|
5. Comprehensive execution walkthrough documented in [`standalone-workstation-walkthrough.md`](../../04-learning/guides/nixos/standalone-workstation-walkthrough.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
File renamed without changes.
@@ -0,0 +1,480 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: praxis
|
||||||
|
tags:
|
||||||
|
- praxis
|
||||||
|
- domain-model
|
||||||
|
- oop
|
||||||
|
- ddd
|
||||||
|
- clean-architecture
|
||||||
|
- homelab
|
||||||
|
---
|
||||||
|
|
||||||
|
# Praxis — Domain Model & OOP Design Specification
|
||||||
|
|
||||||
|
**Document Version:** 1.0.1
|
||||||
|
**Date:** 2026-09-24
|
||||||
|
**Status:** Approved Domain Design Baseline
|
||||||
|
**Previous Version:** [praxis-domain-model.md](praxis-domain-model.md)
|
||||||
|
**SRS Baseline:** [praxis-srs-v1.0.2.md](praxis-srs-v1.0.2.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> ### Summary of Changes from v1.0.0
|
||||||
|
> 1. **Snapshot vs. Execution Mutability**: Clarified that `WorkoutSession` contains an immutable `SessionPrescriptionSnapshot` frozen upon initiation, while its execution performance state remains mutable until explicitly finalized (`Completed`, `Partially_Completed`, `Skipped`), at which point the entire session locks.
|
||||||
|
> 2. **Unified Prescription Snapshot**: Grouped frozen prescriptions and activities under a single session-level `SessionPrescriptionSnapshot` value object rather than scattering snapshot copies across individual performances.
|
||||||
|
> 3. **`Exercise` Promoted to Aggregate Root**: Recognized `Exercise` as an independent Aggregate Root with its own lifecycle, referenced by ID from prescriptions and performances.
|
||||||
|
> 4. **`User` Clarified as Ownership Entity**: Modeled `User` as an identity and profile entity, avoiding an oversized aggregate that contains all routines and sessions.
|
||||||
|
> 5. **`SessionActivity` & `ActivityPerformance` Entities**: Formally modeled non-set activities (warm-ups, cardio) across both the prescription layer (`SessionActivity`) and execution layer (`ActivityPerformance`).
|
||||||
|
> 6. **`DayKind` Cleanup**: Removed `Active Recovery` from `DayKind` (`Workout`, `Rest`, `Unscheduled`). Active recovery is represented as an activity or ad-hoc session.
|
||||||
|
> 7. **Phase Progression Model**: Broadened `Phase` from a narrow integer set modifier to a declarative specification supporting prescription overrides over defined week windows.
|
||||||
|
> 8. **Single-Active-Routine Invariant Placement**: Transferred the single-active-routine rule from `Routine` aggregate invariant to an Application Policy orchestrated by `ActivateRoutineUseCase`.
|
||||||
|
> 9. **Naming & Substitution Clarification**: Renamed to `planned_exercise_id` and `performed_exercise_id`. Established invariant: performance of substituted exercises contributes strictly to the `performed_exercise_id`'s historical log.
|
||||||
|
> 10. **Targeted Method Encapsulation**: Refactored `session.record_set(performance_id, set_data)` and `session.remove_set(performance_id, set_id)` to target performances and sets by ID.
|
||||||
|
> 11. **Metric Validation on `SetPerformance`**: Added metric type validation enforcing required fields (e.g., reps for weightlifting, duration for timed planks) to prevent nonsensical data combinations.
|
||||||
|
> 12. **Effort Scoping**: Scoped effort tracking strictly to optional `RIR` for MVP; deferred RPE.
|
||||||
|
> 13. **Milestone Scoping (1RM Deferred)**: Moved 1RM/PR estimation out of the core MVP calculation layer into Milestone 2, keeping MVP focused on factual history, metric-dependent workload, and adherence.
|
||||||
|
> 14. **Domain Behavioral Contracts**: Added explicit pre/post-conditions and state transition matrices for each aggregate.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Domain Topology & Class Diagram
|
||||||
|
|
||||||
|
Praxis enforces strict separation across the three temporal layers (**Prescription**, **Performance**, **Analysis**) while maintaining decoupled aggregate boundaries:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
classDiagram
|
||||||
|
direction TB
|
||||||
|
|
||||||
|
class User {
|
||||||
|
<<Entity / Identity>>
|
||||||
|
+UserId id
|
||||||
|
+ExternalIdentityId external_id
|
||||||
|
+UserProfile profile
|
||||||
|
+DateTime created_at
|
||||||
|
}
|
||||||
|
|
||||||
|
class Exercise {
|
||||||
|
<<Aggregate Root>>
|
||||||
|
+ExerciseId id
|
||||||
|
+UserId author_id
|
||||||
|
+String name
|
||||||
|
+MuscleGroup category
|
||||||
|
+Equipment equipment
|
||||||
|
+MetricType default_metric
|
||||||
|
+String instructions
|
||||||
|
+update_metadata(name, category, equipment, default_metric, instructions)
|
||||||
|
}
|
||||||
|
|
||||||
|
class Routine {
|
||||||
|
<<Aggregate Root>>
|
||||||
|
+RoutineId id
|
||||||
|
+UserId owner_id
|
||||||
|
+String name
|
||||||
|
+Boolean is_active
|
||||||
|
+DateTime activated_at
|
||||||
|
+List~Phase~ phases
|
||||||
|
+Map~Weekday, WorkoutDay~ schedule
|
||||||
|
+mark_active(now: DateTime)
|
||||||
|
+mark_inactive()
|
||||||
|
+get_current_phase(for_date: Date) Phase
|
||||||
|
+configure_workout_day(weekday, label, kind)
|
||||||
|
+add_prescription(weekday, prescription)
|
||||||
|
+remove_prescription(weekday, prescription_id)
|
||||||
|
+reorder_prescriptions(weekday, ordered_ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
class WorkoutDay {
|
||||||
|
<<Entity>>
|
||||||
|
+WorkoutDayId id
|
||||||
|
+Weekday weekday
|
||||||
|
+DayKind kind
|
||||||
|
+String label
|
||||||
|
+List~ExercisePrescription~ prescriptions
|
||||||
|
+List~SessionActivity~ activities
|
||||||
|
}
|
||||||
|
|
||||||
|
class ExercisePrescription {
|
||||||
|
<<Entity>>
|
||||||
|
+PrescriptionId id
|
||||||
|
+ExerciseId exercise_id
|
||||||
|
+Int target_sets
|
||||||
|
+RepRange rep_range
|
||||||
|
+Duration target_duration
|
||||||
|
+Weight target_weight
|
||||||
|
+Boolean is_unilateral
|
||||||
|
+Int order_index
|
||||||
|
+String notes
|
||||||
|
}
|
||||||
|
|
||||||
|
class SessionActivity {
|
||||||
|
<<Entity>>
|
||||||
|
+ActivityId id
|
||||||
|
+String name
|
||||||
|
+String description
|
||||||
|
+Duration target_duration
|
||||||
|
+Int order_index
|
||||||
|
}
|
||||||
|
|
||||||
|
class WorkoutSession {
|
||||||
|
<<Aggregate Root>>
|
||||||
|
+SessionId id
|
||||||
|
+UserId user_id
|
||||||
|
+RoutineId routine_id
|
||||||
|
+Date session_date
|
||||||
|
+SessionStatus status
|
||||||
|
+DateTime started_at
|
||||||
|
+DateTime finished_at
|
||||||
|
+SessionPrescriptionSnapshot prescription_snapshot
|
||||||
|
+List~ExercisePerformance~ exercises
|
||||||
|
+List~ActivityPerformance~ activities
|
||||||
|
+String notes
|
||||||
|
+record_set(performance_id, set_data) SetPerformance
|
||||||
|
+remove_set(performance_id, set_id)
|
||||||
|
+substitute_exercise(performance_id, new_exercise_id, reason)
|
||||||
|
+add_ad_hoc_exercise(exercise_id) ExercisePerformance
|
||||||
|
+record_activity(activity_perf_id, actual_duration, actual_dist, notes)
|
||||||
|
+finish(policy: CompletionPolicy) CompletionResult
|
||||||
|
+skip(reason: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
class SessionPrescriptionSnapshot {
|
||||||
|
<<Value Object>>
|
||||||
|
+RoutineId routine_id
|
||||||
|
+String routine_name
|
||||||
|
+String phase_name
|
||||||
|
+List~PrescriptionSnapshotItem~ exercise_prescriptions
|
||||||
|
+List~ActivitySnapshotItem~ activities
|
||||||
|
}
|
||||||
|
|
||||||
|
class ExercisePerformance {
|
||||||
|
<<Entity>>
|
||||||
|
+ExercisePerformanceId id
|
||||||
|
+ExerciseId planned_exercise_id
|
||||||
|
+ExerciseId performed_exercise_id
|
||||||
|
+PrescriptionId prescription_item_id
|
||||||
|
+List~SetPerformance~ sets
|
||||||
|
+SubstitutionContext substitution
|
||||||
|
+String notes
|
||||||
|
+append_set(set_data) SetPerformance
|
||||||
|
+remove_set(set_id)
|
||||||
|
+calculate_workload(metric_type) Workload
|
||||||
|
}
|
||||||
|
|
||||||
|
class SetPerformance {
|
||||||
|
<<Entity>>
|
||||||
|
+SetPerformanceId id
|
||||||
|
+Int actual_reps
|
||||||
|
+Weight actual_weight
|
||||||
|
+Duration actual_duration
|
||||||
|
+RIR reps_in_reserve
|
||||||
|
+String notes
|
||||||
|
}
|
||||||
|
|
||||||
|
class ActivityPerformance {
|
||||||
|
<<Entity>>
|
||||||
|
+ActivityPerformanceId id
|
||||||
|
+ActivityId planned_activity_id
|
||||||
|
+String name
|
||||||
|
+Duration actual_duration
|
||||||
|
+Distance actual_distance
|
||||||
|
+Boolean is_completed
|
||||||
|
+String notes
|
||||||
|
}
|
||||||
|
|
||||||
|
User "1" --> "*" Routine : owns
|
||||||
|
User "1" --> "*" WorkoutSession : performs
|
||||||
|
User "1" --> "*" Exercise : authors
|
||||||
|
|
||||||
|
Routine "1" *-- "7" WorkoutDay : contains
|
||||||
|
WorkoutDay "1" *-- "*" ExercisePrescription : prescribes
|
||||||
|
WorkoutDay "1" *-- "*" SessionActivity : prescribes
|
||||||
|
ExercisePrescription "1" --> "1" Exercise : references
|
||||||
|
|
||||||
|
WorkoutSession "1" *-- "1" SessionPrescriptionSnapshot : freezes
|
||||||
|
WorkoutSession "1" *-- "*" ExercisePerformance : tracks
|
||||||
|
WorkoutSession "1" *-- "*" ActivityPerformance : tracks
|
||||||
|
ExercisePerformance "1" *-- "*" SetPerformance : logs
|
||||||
|
ExercisePerformance "1" --> "1" Exercise : performed_as
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Classification: Entities vs. Value Objects
|
||||||
|
|
||||||
|
### 2.1. Value Objects
|
||||||
|
|
||||||
|
| Value Object | Structural Fields | Invariants & Validation Rules |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `UserId` | `UUID / String` | Immutable non-empty opaque string. |
|
||||||
|
| `ExerciseId` | `UUID / String` | Unique identifier for canonical exercise movements. |
|
||||||
|
| `RoutineId` | `UUID / String` | Unique identifier for routine templates. |
|
||||||
|
| `SessionId` | `UUID / String` | Unique identifier for workout sessions. |
|
||||||
|
| `Weekday` | `Enum: Monday .. Sunday` | ISO-8601 integer representation (1–7). |
|
||||||
|
| `DayKind` | `Enum: Workout, Rest, Unscheduled` | Primary calendar classification. |
|
||||||
|
| `MetricType` | `Enum: RepsWeight, Duration, DistanceDuration` | Governs measurement and validation rules. |
|
||||||
|
| `RepRange` | `min_reps: Int, max_reps: Int` | `1 <= min_reps <= max_reps <= 200`. For fixed reps, `min_reps == max_reps`. |
|
||||||
|
| `Weight` | `value: Decimal, unit: Unit (KG, LBS)` | `value >= 0.0`. Implements lossless `.to_kg()` conversion. |
|
||||||
|
| `Duration` | `seconds: Int` | `seconds >= 0`. Whole-second granularity. |
|
||||||
|
| `Distance` | `meters: Decimal` | `meters >= 0.0`. |
|
||||||
|
| `RIR` | `value: Int` | `0 <= value <= 5` (Reps In Reserve). |
|
||||||
|
| `Phase` | `name: String, start_week: Int, end_week: Optional[Int], target_sets_override: Optional[Int]` | `start_week >= 1`. If `end_week` present, `start_week <= end_week`. |
|
||||||
|
| `SessionPrescriptionSnapshot` | Frozen copy of prescriptions, activities, and phase metadata | Fully immutable value object materialised at session initiation. |
|
||||||
|
| `PrescriptionSnapshotItem` | `prescription_id, exercise_id, exercise_name, target_sets, rep_range, target_duration, target_weight, order_index` | Immutable representation of a single prescribed movement. |
|
||||||
|
| `ActivitySnapshotItem` | `activity_id, name, description, target_duration, order_index` | Immutable representation of a prescribed session activity. |
|
||||||
|
| `SubstitutionContext` | `original_exercise_id: ExerciseId, reason: String, substituted_at: DateTime` | Immutable audit trail of an on-the-fly exercise change. |
|
||||||
|
|
||||||
|
### 2.2. Entities & Aggregate Roots
|
||||||
|
|
||||||
|
1. **`Exercise` (Aggregate Root)**: Canonical movement definition with name, muscle group, equipment, default metric hint, and instructional cues.
|
||||||
|
2. **`Routine` (Aggregate Root)**: Reusable schedule template containing 7 `WorkoutDay` entities and progression `Phase` definitions.
|
||||||
|
3. **`WorkoutSession` (Aggregate Root)**: Historical training occurrence containing a frozen prescription snapshot and executing child entities (`ExercisePerformance`, `ActivityPerformance`, `SetPerformance`).
|
||||||
|
4. **`User` (Identity Entity)**: System boundary actor owning user preferences and domain references.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Aggregate Boundaries & Encapsulation Rules
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
subgraph Aggregate_Routine["Aggregate Root: Routine"]
|
||||||
|
R[Routine] --> WD[WorkoutDay]
|
||||||
|
WD --> EP[ExercisePrescription]
|
||||||
|
WD --> SA[SessionActivity]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Aggregate_Exercise["Aggregate Root: Exercise"]
|
||||||
|
EX[Exercise]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Aggregate_WorkoutSession["Aggregate Root: WorkoutSession"]
|
||||||
|
WS[WorkoutSession] --> SPS[SessionPrescriptionSnapshot]
|
||||||
|
WS --> EPF[ExercisePerformance]
|
||||||
|
WS --> APF[ActivityPerformance]
|
||||||
|
EPF --> SP[SetPerformance]
|
||||||
|
end
|
||||||
|
|
||||||
|
Aggregate_Routine -.->|SnapshotFactory materializes| Aggregate_WorkoutSession
|
||||||
|
Aggregate_WorkoutSession -.->|References by ExerciseId| Aggregate_Exercise
|
||||||
|
Aggregate_Routine -.->|References by ExerciseId| Aggregate_Exercise
|
||||||
|
```
|
||||||
|
|
||||||
|
### Boundary Rule 1: `Routine` Aggregate
|
||||||
|
- Encapsulates `WorkoutDay`, `ExercisePrescription`, `SessionActivity`, and `Phase`.
|
||||||
|
- Prescriptions cannot be modified from outside without passing through `Routine` methods.
|
||||||
|
- Has **zero knowledge** of past or active `WorkoutSession` instances.
|
||||||
|
- Does not enforce global uniqueness of the active routine; activation state is modified via `mark_active()` and orchestrated by `ActivateRoutineUseCase`.
|
||||||
|
|
||||||
|
### Boundary Rule 2: `WorkoutSession` Aggregate
|
||||||
|
- Encapsulates `SessionPrescriptionSnapshot`, `ExercisePerformance`, `SetPerformance`, and `ActivityPerformance`.
|
||||||
|
- All modifications to performance state (recording sets, removing sets, swapping exercises, checking off activities) must be executed through methods on `WorkoutSession`.
|
||||||
|
- **Targeted Operations**: Sets are recorded against a specific `ExercisePerformanceId`, preventing ambiguity between planned and substituted exercises.
|
||||||
|
- **Set Identity Invariant**: Sets possess a unique `SetPerformanceId`. Removing a set operates on `set_id`; display order numbers are derived dynamically from sequence position.
|
||||||
|
|
||||||
|
### Boundary Rule 3: `Exercise` Aggregate
|
||||||
|
- Independent aggregate root. Modifying an exercise's instructions or category never mutates existing prescriptions or historical performances (which store snapshot names and IDs).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Metric Validation on `SetPerformance`
|
||||||
|
|
||||||
|
To prevent data corruption (e.g. logging 70kg on a timed Plank), `SetPerformance` creation is governed by a **Metric Validation Policy**:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
M[MetricType of Exercise]
|
||||||
|
M -->|RepsWeight| V1{actual_reps != null?}
|
||||||
|
V1 -->|Yes| OK1[Valid Reps/Weight Set]
|
||||||
|
V1 -->|No| ERR1[Error: Repetitions required]
|
||||||
|
|
||||||
|
M -->|Duration| V2{actual_duration != null?}
|
||||||
|
V2 -->|Yes| OK2[Valid Timed Set]
|
||||||
|
V2 -->|No| ERR2[Error: Duration required]
|
||||||
|
|
||||||
|
M -->|DistanceDuration| V3{duration or distance != null?}
|
||||||
|
V3 -->|Yes| OK3[Valid Distance/Duration Set]
|
||||||
|
V3 -->|No| ERR3[Error: Duration or distance required]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Domain Behavioral Contracts & State Machines
|
||||||
|
|
||||||
|
### 5.1. `WorkoutSession` Lifecycle State Machine
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
stateDiagram
|
||||||
|
[*] --> In_Progress: SessionSnapshotFactory / InitiateWorkout
|
||||||
|
|
||||||
|
In_Progress --> In_Progress: record_set()
|
||||||
|
In_Progress --> In_Progress: remove_set()
|
||||||
|
In_Progress --> In_Progress: substitute_exercise()
|
||||||
|
In_Progress --> In_Progress: add_ad_hoc_exercise()
|
||||||
|
In_Progress --> In_Progress: record_activity()
|
||||||
|
|
||||||
|
In_Progress --> Completed: finish() [100% set-intent achieved]
|
||||||
|
In_Progress --> Partially_Completed: finish() [>0% sets logged, some omitted]
|
||||||
|
In_Progress --> Skipped: skip(reason)
|
||||||
|
|
||||||
|
Completed --> [*]: Locked (Immutable)
|
||||||
|
Partially_Completed --> [*]: Locked (Immutable)
|
||||||
|
Skipped --> [*]: Locked (Immutable)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2. Behavioral Contracts
|
||||||
|
|
||||||
|
#### `WorkoutSession.record_set`
|
||||||
|
- **Signature**: `record_set(performance_id: ExercisePerformanceId, set_data: SetData) -> SetPerformance`
|
||||||
|
- **Preconditions**:
|
||||||
|
- `self.status == SessionStatus.In_Progress` (error if finalized).
|
||||||
|
- `performance_id` exists within `self.exercises`.
|
||||||
|
- `set_data` satisfies `MetricValidationPolicy` for the exercise's `MetricType`.
|
||||||
|
- **Postconditions**:
|
||||||
|
- New `SetPerformance` instance appended to matching `ExercisePerformance.sets`.
|
||||||
|
- Returns created `SetPerformance`.
|
||||||
|
|
||||||
|
#### `WorkoutSession.remove_set`
|
||||||
|
- **Signature**: `remove_set(performance_id: ExercisePerformanceId, set_id: SetPerformanceId) -> None`
|
||||||
|
- **Preconditions**:
|
||||||
|
- `self.status == SessionStatus.In_Progress`.
|
||||||
|
- `set_id` exists in `performance_id`.
|
||||||
|
- **Postconditions**:
|
||||||
|
- `SetPerformance` matching `set_id` is removed.
|
||||||
|
|
||||||
|
#### `WorkoutSession.substitute_exercise`
|
||||||
|
- **Signature**: `substitute_exercise(performance_id: ExercisePerformanceId, new_exercise_id: ExerciseId, reason: String) -> None`
|
||||||
|
- **Preconditions**:
|
||||||
|
- `self.status == SessionStatus.In_Progress`.
|
||||||
|
- `performance_id.sets` is empty (substitution must occur before logging sets on that performance).
|
||||||
|
- **Postconditions**:
|
||||||
|
- `performance.performed_exercise_id = new_exercise_id`.
|
||||||
|
- `performance.substitution = SubstitutionContext(original_exercise_id, reason, now)`.
|
||||||
|
|
||||||
|
#### `WorkoutSession.finish`
|
||||||
|
- **Signature**: `finish(completion_policy: CompletionPolicy, override_status: Optional[SessionStatus] = None) -> CompletionResult`
|
||||||
|
- **Preconditions**:
|
||||||
|
- `self.status == SessionStatus.In_Progress`.
|
||||||
|
- **Postconditions**:
|
||||||
|
- If `override_status` is provided: `self.status = override_status`.
|
||||||
|
- Else: `self.status = completion_policy.evaluate(self).suggested_status`.
|
||||||
|
- `self.finished_at = now`.
|
||||||
|
- Session becomes locked against further mutation.
|
||||||
|
|
||||||
|
#### `WorkoutSession.skip`
|
||||||
|
- **Signature**: `skip(reason: String) -> None`
|
||||||
|
- **Preconditions**:
|
||||||
|
- `self.status == SessionStatus.In_Progress` and no sets have been logged.
|
||||||
|
- **Postconditions**:
|
||||||
|
- `self.status = SessionStatus.Skipped`.
|
||||||
|
- `self.finished_at = now`.
|
||||||
|
- `self.notes = reason`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Domain Policies & Derivations
|
||||||
|
|
||||||
|
### 6.1. `SessionSnapshotFactory`
|
||||||
|
Materializes a `WorkoutSession` from a scheduled `WorkoutDay`:
|
||||||
|
1. Determines elapsed weeks since routine activation:
|
||||||
|
$$\text{week\_index} = \left\lfloor \frac{\text{session\_date} - \text{routine.activated\_at.date}}{7} \right\rfloor + 1$$
|
||||||
|
2. Queries `routine.get_current_phase(session_date)` to resolve active phase and target set overrides (e.g. 3 sets vs 4 sets).
|
||||||
|
3. Freezes `SessionPrescriptionSnapshot` containing all prescribed exercises and activities.
|
||||||
|
4. Generates an initial `ExercisePerformance` entity for each prescribed exercise, setting both `planned_exercise_id` and `performed_exercise_id` to the prescribed exercise ID.
|
||||||
|
5. Generates an initial `ActivityPerformance` for each prescribed activity.
|
||||||
|
6. Returns `WorkoutSession` in `In_Progress` status.
|
||||||
|
|
||||||
|
### 6.2. `CompletionPolicy` (Set-Intent Evaluation)
|
||||||
|
Evaluates whether a session achieved full or partial completion:
|
||||||
|
- **Exercise Complete**: Evaluated as complete if $\text{count}(\text{valid sets logged}) \ge \text{target sets from snapshot}$.
|
||||||
|
- **Suggested Status**:
|
||||||
|
- If $100\%$ of prescribed exercises are complete $\rightarrow$ `Completed`.
|
||||||
|
- If $>0$ sets logged but $<100\%$ prescribed exercises complete $\rightarrow$ `Partially_Completed`.
|
||||||
|
|
||||||
|
### 6.3. `WorkloadCalculator`
|
||||||
|
Calculates metric-dependent physical workload:
|
||||||
|
- **Weighted Volume**: $\sum_{i} (\text{actual\_reps}_i \times \text{actual\_weight}_i\text{.to\_kg()})$
|
||||||
|
- **Duration Workload**: $\sum_{i} \text{actual\_duration}_i\text{.seconds}$
|
||||||
|
- **Distance Workload**: $\sum_{i} \text{actual\_distance}_i\text{.meters}$
|
||||||
|
|
||||||
|
### 6.4. `AdherenceCalculator`
|
||||||
|
Calculates objective habit consistency over a window $[T_{\text{start}}, T_{\text{end}}]$:
|
||||||
|
$$\text{Scheduled Count} = N_{\text{scheduled}}$$
|
||||||
|
$$\text{Completion Rate} = \frac{N_{\text{completed}}}{N_{\text{scheduled}}}$$
|
||||||
|
$$\text{Partial Rate} = \frac{N_{\text{partially\_completed}}}{N_{\text{scheduled}}}$$
|
||||||
|
$$\text{Skip Rate} = \frac{N_{\text{skipped}}}{N_{\text{scheduled}}}$$
|
||||||
|
$$\text{Set Adherence Rate} = \frac{\sum \text{Sets Performed}}{\sum \text{Sets Prescribed}}$$
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Application Use Cases (Interactors)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
autonumber
|
||||||
|
actor User
|
||||||
|
participant UC as ActivateRoutineUseCase
|
||||||
|
participant RRepo as RoutineRepository
|
||||||
|
|
||||||
|
User->>UC: execute(target_routine_id)
|
||||||
|
UC->>RRepo: get_active(user_id)
|
||||||
|
opt Active routine exists
|
||||||
|
RRepo-->>UC: current_active_routine
|
||||||
|
UC->>current_active_routine: mark_inactive()
|
||||||
|
UC->>RRepo: save(current_active_routine)
|
||||||
|
end
|
||||||
|
UC->>RRepo: get_by_id(target_routine_id)
|
||||||
|
RRepo-->>UC: target_routine
|
||||||
|
UC->>target_routine: mark_active(now)
|
||||||
|
UC->>RRepo: save(target_routine)
|
||||||
|
UC-->>User: Success (target_routine activated)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Complete Use Case Inventory
|
||||||
|
|
||||||
|
1. **`CreateRoutineUseCase(user_id, name, schedule_spec, phases)`**: Creates new `Routine` aggregate.
|
||||||
|
2. **`ActivateRoutineUseCase(user_id, routine_id)`**: Enforces the single-active-routine policy by deactivating the current active routine before activating the target routine.
|
||||||
|
3. **`InitiateWorkoutUseCase(user_id, date)`**: Calls `SessionSnapshotFactory` and saves new `WorkoutSession`.
|
||||||
|
4. **`RecordSetUseCase(user_id, session_id, performance_id, set_data)`**: Appends validated set to performance.
|
||||||
|
5. **`RemoveSetUseCase(user_id, session_id, performance_id, set_id)`**: Removes set by identity.
|
||||||
|
6. **`SubstituteExerciseUseCase(user_id, session_id, performance_id, new_exercise_id, reason)`**: Records substitution.
|
||||||
|
7. **`AddAdHocExerciseUseCase(user_id, session_id, exercise_id)`**: Appends unscheduled exercise to active session.
|
||||||
|
8. **`RecordActivityUseCase(user_id, session_id, activity_perf_id, actual_duration, actual_dist, notes)`**: Logs activity completion.
|
||||||
|
9. **`FinishWorkoutUseCase(user_id, session_id, override_status=None)`**: Evaluates completion via `CompletionPolicy` and finalizes session.
|
||||||
|
10. **`SkipWorkoutUseCase(user_id, date, reason)`**: Records skipped session.
|
||||||
|
11. **`QueryWeeklyCalendarUseCase(user_id, start_date, end_date)`**: Returns projected `ScheduledWorkout` items alongside recorded `WorkoutSession` instances.
|
||||||
|
12. **`QueryExerciseHistoryUseCase(user_id, exercise_id)`**: Returns historical performances where `performed_exercise_id == exercise_id`.
|
||||||
|
13. **`CalculateAdherenceUseCase(user_id, start_date, end_date)`**: Generates factual adherence metrics.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Clean Architecture Dependency Graph
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
subgraph Infrastructure["Infrastructure Layer"]
|
||||||
|
FastAPI[FastAPI Controllers / REST API]
|
||||||
|
AuthAdapter[Authelia Reverse-Proxy Header Adapter]
|
||||||
|
SQLRepo[PostgreSQL / SQLite Repositories]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Application["Application Layer (Use Cases)"]
|
||||||
|
UC[Application Use Cases]
|
||||||
|
DTO[Data Transfer Objects / Schemas]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Domain["Domain Layer (Pure Business Rules)"]
|
||||||
|
Agg_Routine[Routine Aggregate]
|
||||||
|
Agg_Session[WorkoutSession Aggregate]
|
||||||
|
Agg_Exercise[Exercise Aggregate]
|
||||||
|
DomainServices[Domain Policies & Calculators]
|
||||||
|
Ports[Repository & Auth Ports]
|
||||||
|
end
|
||||||
|
|
||||||
|
FastAPI --> UC
|
||||||
|
UC --> Domain
|
||||||
|
UC --> Ports
|
||||||
|
AuthAdapter --> Ports
|
||||||
|
SQLRepo --> Ports
|
||||||
|
```
|
||||||
@@ -0,0 +1,505 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: draft
|
||||||
|
project: praxis
|
||||||
|
tags:
|
||||||
|
- praxis
|
||||||
|
- domain-model
|
||||||
|
- oop
|
||||||
|
- ddd
|
||||||
|
- clean-architecture
|
||||||
|
- homelab
|
||||||
|
---
|
||||||
|
|
||||||
|
# Praxis — Domain Model & OOP Design Specification
|
||||||
|
|
||||||
|
**Document Version:** 1.0.0
|
||||||
|
**Date:** 2026-09-24
|
||||||
|
**Status:** Approved Domain Design Baseline
|
||||||
|
**Prerequisite:** [praxis-srs.md](praxis-srs.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Domain Topology & Conceptual Overview
|
||||||
|
|
||||||
|
Praxis translates user intent into physical performance and derived analytical insight. The architecture strictly enforces boundaries across three temporal layers:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
classDiagram
|
||||||
|
direction TB
|
||||||
|
|
||||||
|
class User {
|
||||||
|
+UserId id
|
||||||
|
+ExternalIdentityId external_id
|
||||||
|
+UserProfile profile
|
||||||
|
+DateTime created_at
|
||||||
|
}
|
||||||
|
|
||||||
|
class Routine {
|
||||||
|
<<Aggregate Root>>
|
||||||
|
+RoutineId id
|
||||||
|
+UserId owner_id
|
||||||
|
+String name
|
||||||
|
+Boolean is_active
|
||||||
|
+DateTime activated_at
|
||||||
|
+List~Phase~ phases
|
||||||
|
+Map~Weekday, WorkoutDay~ schedule
|
||||||
|
+activate(now: DateTime)
|
||||||
|
+deactivate()
|
||||||
|
+get_current_phase(for_date: Date) Phase
|
||||||
|
}
|
||||||
|
|
||||||
|
class WorkoutDay {
|
||||||
|
<<Entity>>
|
||||||
|
+WorkoutDayId id
|
||||||
|
+Weekday weekday
|
||||||
|
+DayKind kind
|
||||||
|
+String label
|
||||||
|
+List~ExercisePrescription~ prescriptions
|
||||||
|
+List~SessionActivity~ activities
|
||||||
|
}
|
||||||
|
|
||||||
|
class ExercisePrescription {
|
||||||
|
<<Entity>>
|
||||||
|
+PrescriptionId id
|
||||||
|
+ExerciseId exercise_id
|
||||||
|
+TargetSets target_sets
|
||||||
|
+RepRange rep_range
|
||||||
|
+TargetDuration target_duration
|
||||||
|
+Weight target_weight
|
||||||
|
+Boolean is_unilateral
|
||||||
|
+Int order_index
|
||||||
|
+String notes
|
||||||
|
}
|
||||||
|
|
||||||
|
class Exercise {
|
||||||
|
<<Entity / Reference>>
|
||||||
|
+ExerciseId id
|
||||||
|
+UserId author_id
|
||||||
|
+String name
|
||||||
|
+MuscleGroup category
|
||||||
|
+Equipment equipment
|
||||||
|
+MetricType default_metric
|
||||||
|
+String instructions
|
||||||
|
}
|
||||||
|
|
||||||
|
class WorkoutSession {
|
||||||
|
<<Aggregate Root>>
|
||||||
|
+SessionId id
|
||||||
|
+UserId user_id
|
||||||
|
+RoutineId routine_id
|
||||||
|
+Date session_date
|
||||||
|
+SessionStatus status
|
||||||
|
+DateTime started_at
|
||||||
|
+DateTime finished_at
|
||||||
|
+List~ExercisePerformance~ exercises
|
||||||
|
+List~ActivityPerformance~ activities
|
||||||
|
+String notes
|
||||||
|
+record_set(exercise_id, set_perf)
|
||||||
|
+substitute_exercise(original_id, new_id, reason)
|
||||||
|
+finish(policy: CompletionPolicy)
|
||||||
|
+skip(reason: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
class ExercisePerformance {
|
||||||
|
<<Entity>>
|
||||||
|
+ExercisePerformanceId id
|
||||||
|
+ExerciseId prescribed_exercise_id
|
||||||
|
+ExerciseId actual_exercise_id
|
||||||
|
+PrescriptionSnapshot prescription_snapshot
|
||||||
|
+List~SetPerformance~ sets
|
||||||
|
+SubstitutionContext substitution
|
||||||
|
+String notes
|
||||||
|
}
|
||||||
|
|
||||||
|
class SetPerformance {
|
||||||
|
<<Entity>>
|
||||||
|
+SetPerformanceId id
|
||||||
|
+Int set_number
|
||||||
|
+Int actual_reps
|
||||||
|
+Weight actual_weight
|
||||||
|
+Duration actual_duration
|
||||||
|
+RIR reps_in_reserve
|
||||||
|
+RPE perceived_exertion
|
||||||
|
+String notes
|
||||||
|
}
|
||||||
|
|
||||||
|
User "1" --> "*" Routine : owns
|
||||||
|
Routine "1" *-- "7" WorkoutDay : contains
|
||||||
|
WorkoutDay "1" *-- "*" ExercisePrescription : prescribes
|
||||||
|
ExercisePrescription "1" --> "1" Exercise : targets
|
||||||
|
|
||||||
|
User "1" --> "*" WorkoutSession : performs
|
||||||
|
WorkoutSession "1" *-- "*" ExercisePerformance : tracks
|
||||||
|
ExercisePerformance "1" *-- "*" SetPerformance : logs
|
||||||
|
ExercisePerformance "1" --> "1" Exercise : references
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Classification: Entities vs. Value Objects
|
||||||
|
|
||||||
|
To eliminate mutable identity bugs and enforce domain integrity, elements are strictly separated into **Entities** (having unique identity, lifecycle, and mutable state governed by methods) and **Value Objects** (immutable descriptors compared purely by value, with structural validation).
|
||||||
|
|
||||||
|
### 2.1. Value Objects
|
||||||
|
|
||||||
|
| Value Object | Structural Fields | Invariants & Validation Rules |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `UserId` | `UUID / String` | Non-empty, opaque string representing domain user identity. |
|
||||||
|
| `Weekday` | `Enum: Monday .. Sunday` | ISO-8601 weekday integer representation (1–7). |
|
||||||
|
| `DayKind` | `Enum: Workout, Rest, Unscheduled` | Categorizes scheduling nature of the calendar day. |
|
||||||
|
| `RepRange` | `min_reps: Int, max_reps: Int` | `1 <= min_reps <= max_reps <= 200`. If fixed reps (e.g. 12), `min_reps == max_reps`. |
|
||||||
|
| `Weight` | `value: Decimal, unit: Unit (KG, LBS)` | `value >= 0.0`. Provides explicit conversions between KG and LBS. |
|
||||||
|
| `Duration` | `seconds: Int` | `seconds >= 0`. Expressed in whole seconds. |
|
||||||
|
| `RIR` | `value: Int` | `0 <= value <= 10` (Reps In Reserve). |
|
||||||
|
| `RPE` | `value: Decimal` | `1.0 <= value <= 10.0` (Rating of Perceived Exertion). |
|
||||||
|
| `Phase` | `name: String, start_week: Int, end_week: Optional[Int], set_modifier: Int` | `start_week >= 1`. If `end_week` is present, `start_week <= end_week`. Governs prescribed set counts. |
|
||||||
|
| `PrescriptionSnapshot` | Frozen copy of prescribed sets, reps, weight, duration, cues | Completely immutable value object frozen upon session creation. |
|
||||||
|
| `SubstitutionContext` | `original_exercise_id: ExerciseId, reason: String` | Records why an exercise was swapped during live execution. |
|
||||||
|
|
||||||
|
### 2.2. Entities
|
||||||
|
|
||||||
|
- **`User`**: Root user entity owning preferences and data references.
|
||||||
|
- **`Exercise`**: Canonical catalog entry for a physical movement.
|
||||||
|
- **`Routine`**: Root aggregate managing weekly schedules and phase definitions.
|
||||||
|
- **`WorkoutDay`**: Child entity of `Routine` defining prescriptions for a given weekday.
|
||||||
|
- **`ExercisePrescription`**: Child entity of `WorkoutDay` prescribing targets for an exercise.
|
||||||
|
- **`WorkoutSession`**: Root aggregate representing a concrete training event.
|
||||||
|
- **`ExercisePerformance`**: Child entity of `WorkoutSession` capturing logged work for one exercise.
|
||||||
|
- **`SetPerformance`**: Child entity of `ExercisePerformance` capturing an individual set's execution metrics.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Aggregate Boundaries & Encapsulation
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
subgraph Aggregate_Routine["Aggregate Root: Routine"]
|
||||||
|
R_Root[Routine] --> WD1[WorkoutDay: Mon]
|
||||||
|
R_Root --> WD2[WorkoutDay: Tue]
|
||||||
|
WD1 --> EP1[ExercisePrescription]
|
||||||
|
WD1 --> EP2[ExercisePrescription]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Aggregate_WorkoutSession["Aggregate Root: WorkoutSession"]
|
||||||
|
WS_Root[WorkoutSession] --> EPF1[ExercisePerformance]
|
||||||
|
WS_Root --> EPF2[ExercisePerformance]
|
||||||
|
EPF1 --> SP1[SetPerformance 1]
|
||||||
|
EPF1 --> SP2[SetPerformance 2]
|
||||||
|
end
|
||||||
|
|
||||||
|
Aggregate_Routine -.->|Snapshot Factory creates| Aggregate_WorkoutSession
|
||||||
|
```
|
||||||
|
|
||||||
|
### Boundary Rule 1: `Routine` Aggregate
|
||||||
|
- **Root**: `Routine`.
|
||||||
|
- **Enclosed**: `WorkoutDay`, `ExercisePrescription`, `SessionActivity`, `Phase`.
|
||||||
|
- **Encapsulation Rules**:
|
||||||
|
- External code cannot mutate `ExercisePrescription` directly; it calls methods on `Routine` (e.g., `routine.add_prescription(weekday, prescription)`).
|
||||||
|
- `Routine` has **zero references** to `WorkoutSession` or historical performance data.
|
||||||
|
- Modifying a `Routine` never triggers side-effects in past or in-progress `WorkoutSession` instances.
|
||||||
|
|
||||||
|
### Boundary Rule 2: `WorkoutSession` Aggregate
|
||||||
|
- **Root**: `WorkoutSession`.
|
||||||
|
- **Enclosed**: `ExercisePerformance`, `SetPerformance`, `ActivityPerformance`.
|
||||||
|
- **Encapsulation Rules**:
|
||||||
|
- `WorkoutSession` is the sole boundary through which sets and exercise substitutions are recorded:
|
||||||
|
- `session.record_set(exercise_id, set_data)`
|
||||||
|
- `session.substitute_exercise(original_exercise_id, new_exercise_id, reason)`
|
||||||
|
- `session.add_ad_hoc_exercise(exercise_id)`
|
||||||
|
- `session.finish(completion_policy)`
|
||||||
|
- Direct manipulation of inner `SetPerformance` instances outside the aggregate boundary is prohibited.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Detailed Specification of Key Objects
|
||||||
|
|
||||||
|
### 4.1. `Routine` (Aggregate Root)
|
||||||
|
1. **Identity**: `RoutineId` (UUID).
|
||||||
|
2. **State**:
|
||||||
|
- `owner_id`: `UserId`
|
||||||
|
- `name`: string
|
||||||
|
- `is_active`: bool
|
||||||
|
- `activated_at`: optional `DateTime`
|
||||||
|
- `schedule`: dictionary mapping each `Weekday` (1..7) to a `WorkoutDay`
|
||||||
|
- `phases`: ordered list of `Phase` value objects
|
||||||
|
3. **Invariants**:
|
||||||
|
- A routine must contain entries for all 7 weekdays.
|
||||||
|
- `activated_at` must be populated if and only if `is_active == True`.
|
||||||
|
- Phases must not have overlapping week intervals.
|
||||||
|
4. **Behavior**:
|
||||||
|
- `activate(now: DateTime)`: Sets `is_active = True`, records `activated_at = now`.
|
||||||
|
- `deactivate()`: Sets `is_active = False`, clears `activated_at`.
|
||||||
|
- `resolve_phase(for_date: Date) -> Phase`: Calculates elapsed weeks:
|
||||||
|
$$\text{weeks\_elapsed} = \left\lfloor \frac{\text{for\_date} - \text{activated\_at.date}}{7} \right\rfloor + 1$$
|
||||||
|
Returns the matching `Phase`.
|
||||||
|
- `configure_workout_day(weekday, label, kind)`: Reconfigures a day (e.g. converting Sunday to Rest).
|
||||||
|
5. **Relationships**: Owns 7 `WorkoutDay` entities; references `UserId`.
|
||||||
|
6. **Lifecycle**: Created $\rightarrow$ Draft $\rightarrow$ Active $\leftrightarrow$ Inactive $\rightarrow$ Archived.
|
||||||
|
7. **Allowed to Mutate**: Its own schedule, days, prescriptions, and phases.
|
||||||
|
8. **Forbidden Knowledge**: Has no knowledge of `WorkoutSession`, calendar logs, or historical set recordings.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.2. `WorkoutDay` (Entity within Routine)
|
||||||
|
1. **Identity**: `WorkoutDayId` (UUID).
|
||||||
|
2. **State**:
|
||||||
|
- `weekday`: `Weekday`
|
||||||
|
- `kind`: `DayKind` (`Workout`, `Rest`, `Unscheduled`)
|
||||||
|
- `label`: string (e.g. *"Cuádriceps / Glúteo"*, *"Descanso"*)
|
||||||
|
- `prescriptions`: list of `ExercisePrescription`
|
||||||
|
- `activities`: list of `SessionActivity`
|
||||||
|
3. **Invariants**:
|
||||||
|
- If `kind == Rest` or `Unscheduled`, `prescriptions` must be empty.
|
||||||
|
- Prescription ordering indices must be unique and sequential without gaps.
|
||||||
|
4. **Behavior**:
|
||||||
|
- `add_prescription(exercise_id, target_sets, rep_range, ...)`
|
||||||
|
- `remove_prescription(prescription_id)`
|
||||||
|
- `reorder_prescriptions(ordered_ids: List[PrescriptionId])`
|
||||||
|
- `add_activity(description, duration)`
|
||||||
|
5. **Relationships**: Child of `Routine`. References `ExerciseId`.
|
||||||
|
6. **Lifecycle**: Co-terminous with parent `Routine`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.3. `Exercise` (Entity / Reference Data)
|
||||||
|
1. **Identity**: `ExerciseId` (UUID).
|
||||||
|
2. **State**:
|
||||||
|
- `author_id`: optional `UserId` (null if system-seeded)
|
||||||
|
- `name`: string (e.g. *"Sentadilla búlgara en Smith"*)
|
||||||
|
- `category`: `MuscleGroup`
|
||||||
|
- `equipment`: `Equipment`
|
||||||
|
- `default_metric`: `MetricType` (`RepsWeight`, `Duration`, `DistanceDuration`)
|
||||||
|
- `instructions`: string
|
||||||
|
3. **Invariants**:
|
||||||
|
- `name` cannot be blank.
|
||||||
|
- System exercises (`author_id == null`) are immutable by regular users.
|
||||||
|
4. **Behavior**:
|
||||||
|
- `update_metadata(name, category, equipment, default_metric, instructions)` (only permitted if user is author).
|
||||||
|
5. **Forbidden Knowledge**: Has no awareness of prescriptions, workouts, or performance history.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.4. `WorkoutSession` (Aggregate Root)
|
||||||
|
1. **Identity**: `SessionId` (UUID).
|
||||||
|
2. **State**:
|
||||||
|
- `user_id`: `UserId`
|
||||||
|
- `routine_id`: optional `RoutineId` (null if spontaneous/ad-hoc)
|
||||||
|
- `session_date`: `Date`
|
||||||
|
- `status`: `SessionStatus` (`In_Progress`, `Completed`, `Partially_Completed`, `Skipped`)
|
||||||
|
- `started_at`: `DateTime`
|
||||||
|
- `finished_at`: optional `DateTime`
|
||||||
|
- `exercises`: ordered list of `ExercisePerformance`
|
||||||
|
- `activities`: list of `ActivityPerformance`
|
||||||
|
- `notes`: string
|
||||||
|
3. **Invariants**:
|
||||||
|
- If `status == In_Progress`, `finished_at` must be null.
|
||||||
|
- If `status in (Completed, Partially_Completed)`, `finished_at` must be $\ge$ `started_at`.
|
||||||
|
- Once marked `Completed`, `Partially_Completed`, or `Skipped`, the session is locked against further set modifications.
|
||||||
|
4. **Behavior**:
|
||||||
|
- `record_set(exercise_id, set_number, reps, weight, duration, rir, notes) -> SetPerformance`
|
||||||
|
- `substitute_exercise(original_exercise_id, new_exercise_id, reason)`
|
||||||
|
- `add_ad_hoc_exercise(exercise_id)`
|
||||||
|
- `finish(completion_policy: CompletionPolicy) -> CompletionResult`: Evaluates completion, transitions status, and sets `finished_at = now`.
|
||||||
|
- `skip(reason: String)`: Transitions status to `Skipped` and records reason.
|
||||||
|
5. **Allowed to Mutate**: Child `ExercisePerformance` and `SetPerformance` entities.
|
||||||
|
6. **Forbidden Knowledge**: Knows nothing about future routines, upcoming calendar days, or external authentication providers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.5. `ExercisePerformance` (Entity within WorkoutSession)
|
||||||
|
1. **Identity**: `ExercisePerformanceId` (UUID).
|
||||||
|
2. **State**:
|
||||||
|
- `prescribed_exercise_id`: optional `ExerciseId` (null if ad-hoc addition)
|
||||||
|
- `actual_exercise_id`: `ExerciseId`
|
||||||
|
- `prescription_snapshot`: optional `PrescriptionSnapshot`
|
||||||
|
- `sets`: list of `SetPerformance`
|
||||||
|
- `substitution`: optional `SubstitutionContext`
|
||||||
|
- `notes`: string
|
||||||
|
3. **Invariants**:
|
||||||
|
- If substituted, `substitution` must be present and `actual_exercise_id != prescribed_exercise_id`.
|
||||||
|
- Set numbers must be strictly sequential starting from 1.
|
||||||
|
4. **Behavior**:
|
||||||
|
- `append_set(reps, weight, duration, rir, notes)`
|
||||||
|
- `remove_set(set_number)`
|
||||||
|
- `calculate_workload() -> Workload`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Domain Policies and Domain Services
|
||||||
|
|
||||||
|
Domain rules that coordinate across entities or encapsulate algorithmic derivations are extracted into **Domain Services & Policies**:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
subgraph Services["Domain Services & Policies"]
|
||||||
|
SSF[SessionSnapshotFactory]
|
||||||
|
CP[CompletionPolicy]
|
||||||
|
WLC[WorkloadCalculator]
|
||||||
|
AHC[AdherenceCalculator]
|
||||||
|
PRC[PersonalRecordCalculator]
|
||||||
|
end
|
||||||
|
|
||||||
|
R[Routine] --> SSF
|
||||||
|
WD[WorkoutDay] --> SSF
|
||||||
|
SSF --> WS[WorkoutSession]
|
||||||
|
WS --> CP
|
||||||
|
WS --> WLC
|
||||||
|
Hist[(WorkoutSession History)] --> AHC
|
||||||
|
Hist --> PRC
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.1. `SessionSnapshotFactory`
|
||||||
|
- **Role**: Factory domain service responsible for materializing a `WorkoutSession` from a `Routine`'s scheduled `WorkoutDay`.
|
||||||
|
- **Contract**:
|
||||||
|
```python
|
||||||
|
def create_session(
|
||||||
|
routine: Routine,
|
||||||
|
for_date: Date,
|
||||||
|
user_id: UserId,
|
||||||
|
now: DateTime
|
||||||
|
) -> WorkoutSession
|
||||||
|
```
|
||||||
|
- **Rules**:
|
||||||
|
1. Identifies the weekday for `for_date`.
|
||||||
|
2. Queries `routine.get_current_phase(for_date)` to determine current phase modifiers (e.g. 3 sets vs 4 sets).
|
||||||
|
3. Deep-copies prescriptions and activities into frozen `PrescriptionSnapshot` value objects inside `ExercisePerformance` entities.
|
||||||
|
4. Returns a fresh `WorkoutSession` in `In_Progress` state.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.2. `CompletionPolicy`
|
||||||
|
- **Role**: Implements the set-intent evaluation policy to evaluate completion status.
|
||||||
|
- **Contract**:
|
||||||
|
```python
|
||||||
|
def evaluate(session: WorkoutSession) -> CompletionEvaluation:
|
||||||
|
# Returns:
|
||||||
|
# - suggested_status: Completed | Partially_Completed
|
||||||
|
# - total_prescribed_sets: Int
|
||||||
|
# - total_logged_sets: Int
|
||||||
|
# - completed_exercise_count: Int
|
||||||
|
# - total_prescribed_exercises: Int
|
||||||
|
```
|
||||||
|
- **Rules**:
|
||||||
|
1. An exercise is complete if count of logged sets $\ge$ prescribed sets (adjusted by active phase) and sets represent attempted work.
|
||||||
|
2. The session is `Completed` if all prescribed exercises are complete.
|
||||||
|
3. The session is `Partially_Completed` if $>0$ sets were logged but some prescribed exercises/sets were omitted.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.3. `WorkloadCalculator`
|
||||||
|
- **Role**: Computes metric-dependent physical workload for performances and sessions without conflating units.
|
||||||
|
- **Contract**:
|
||||||
|
```python
|
||||||
|
def calculate_set_workload(set_perf: SetPerformance) -> Workload
|
||||||
|
def calculate_session_workload(session: WorkoutSession) -> SessionWorkload
|
||||||
|
```
|
||||||
|
- **Calculations**:
|
||||||
|
- **Weighted Volume (Tonnage)**: $\sum (\text{actual\_reps} \times \text{actual\_weight.to\_kg()})$
|
||||||
|
- **Cumulative Duration**: $\sum \text{actual\_duration.seconds}$
|
||||||
|
- **Distance**: $\sum \text{actual\_distance}$
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.4. `AdherenceCalculator`
|
||||||
|
- **Role**: Pure derivation service calculating factual consistency rates over an evaluation window.
|
||||||
|
- **Contract**:
|
||||||
|
```python
|
||||||
|
def calculate_adherence(
|
||||||
|
scheduled_count: int,
|
||||||
|
sessions: List[WorkoutSession]
|
||||||
|
) -> AdherenceReport
|
||||||
|
```
|
||||||
|
- **Formulas**:
|
||||||
|
- `completed_rate = count(Completed) / scheduled_count`
|
||||||
|
- `partial_rate = count(Partially_Completed) / scheduled_count`
|
||||||
|
- `skip_rate = count(Skipped) / scheduled_count`
|
||||||
|
- `set_adherence = total_sets_performed / total_sets_prescribed`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.5. `PersonalRecordCalculator`
|
||||||
|
- **Role**: Scans historical `WorkoutSession` instances to derive personal bests for a specific `ExerciseId`.
|
||||||
|
- **Derivations**:
|
||||||
|
- **Peak Weight Lifted**: $\max(\text{actual\_weight})$ across all sets.
|
||||||
|
- **Peak Volume in Single Set**: $\max(\text{reps} \times \text{weight})$.
|
||||||
|
- **Estimated 1RM (Epley)**: $\max\left(\text{weight} \times \left(1 + \frac{\text{reps}}{30}\right)\right)$ for sets where $1 \le \text{reps} \le 10$.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Core Application Use Cases (Interactors)
|
||||||
|
|
||||||
|
Below are the primary transactional boundaries orchestrating domain entities and repositories:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
autonumber
|
||||||
|
actor User
|
||||||
|
participant UC as InitiateWorkoutUseCase
|
||||||
|
participant RRepo as RoutineRepository
|
||||||
|
participant SRepo as SessionRepository
|
||||||
|
participant SSF as SessionSnapshotFactory
|
||||||
|
|
||||||
|
User->>UC: execute(date)
|
||||||
|
UC->>RRepo: get_active_routine(user_id)
|
||||||
|
RRepo-->>UC: routine
|
||||||
|
UC->>SSF: create_session(routine, date, user_id, now)
|
||||||
|
SSF-->>UC: workout_session
|
||||||
|
UC->>SRepo: save(workout_session)
|
||||||
|
SRepo-->>UC: saved_session
|
||||||
|
UC-->>User: WorkoutSessionDTO (In_Progress)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Use Case Inventory
|
||||||
|
|
||||||
|
1. **`CreateRoutine(user_id, name, schedule_spec, phases)`**: Instantiates and persists a new `Routine`.
|
||||||
|
2. **`ActivateRoutine(user_id, routine_id)`**: Deactivates any currently active routine for the user and activates the specified routine.
|
||||||
|
3. **`InitiateWorkout(user_id, date)`**: Finds active routine, invokes `SessionSnapshotFactory`, and persists the new in-progress `WorkoutSession`.
|
||||||
|
4. **`RecordSet(user_id, session_id, exercise_id, set_data)`**: Loads `WorkoutSession`, appends set via `session.record_set(...)`, and saves.
|
||||||
|
5. **`SubstituteExercise(user_id, session_id, original_id, new_id, reason)`**: Records substitution on the active session without altering `Routine`.
|
||||||
|
6. **`FinishWorkout(user_id, session_id, override_status=None)`**: Evaluates completion via `CompletionPolicy`, marks session finished, and persists.
|
||||||
|
7. **`SkipWorkout(user_id, date, reason)`**: Creates or marks a session as `Skipped`.
|
||||||
|
8. **`QueryWeeklyCalendar(user_id, start_date, end_date)`**: Merges active routine's projected `ScheduledWorkout` items with recorded `WorkoutSession` instances for the calendar grid.
|
||||||
|
9. **`QueryExerciseProgression(user_id, exercise_id)`**: Loads history for `exercise_id`, computes workload and PR trends via domain services, and returns time-series data.
|
||||||
|
10. **`CalculateAdherenceReport(user_id, window_start, window_end)`**: Runs `AdherenceCalculator` over the specified historical date range.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Ports & Adapters Architecture (Hexagonal)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD
|
||||||
|
subgraph DrivingAdapters["Driving / Primary Adapters (Incoming)"]
|
||||||
|
API[FastAPI / REST Controllers]
|
||||||
|
CLI[Admin / Seed CLI]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph ApplicationCore["Application Core (Use Cases / Domain)"]
|
||||||
|
UC[Use Cases / Interactors]
|
||||||
|
DM[Domain Model & Policies]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph DrivenPorts["Driven / Secondary Ports (Interfaces)"]
|
||||||
|
IPort_Auth[AuthProvider Port]
|
||||||
|
IPort_Routine[RoutineRepository Port]
|
||||||
|
IPort_Session[SessionRepository Port]
|
||||||
|
IPort_Exercise[ExerciseRepository Port]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph DrivenAdapters["Driven / Secondary Adapters (Infrastructure)"]
|
||||||
|
AuthHeader[Authelia Forward-Auth Header Adapter]
|
||||||
|
SQLRepo[PostgreSQL / SQLite SQLModel/SQLAlchemy Adapter]
|
||||||
|
end
|
||||||
|
|
||||||
|
API --> UC
|
||||||
|
CLI --> UC
|
||||||
|
UC --> DM
|
||||||
|
UC --> DrivenPorts
|
||||||
|
DrivenPorts --> DrivenAdapters
|
||||||
|
```
|
||||||
|
|
||||||
|
### Port Definitions:
|
||||||
|
- `AuthProvider`: Resolves external identity headers (`Remote-User`, `Remote-Email`) into a domain `UserId`.
|
||||||
|
- `RoutineRepository`: `save(routine)`, `get_by_id(id)`, `get_active(user_id)`.
|
||||||
|
- `WorkoutSessionRepository`: `save(session)`, `get_by_id(id)`, `find_by_user_and_date(user_id, date)`, `find_history_by_exercise(user_id, exercise_id)`.
|
||||||
|
- `ExerciseRepository`: `save(exercise)`, `get_by_id(id)`, `list_catalog(user_id)`.
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: praxis
|
||||||
|
tags:
|
||||||
|
- praxis
|
||||||
|
- architecture
|
||||||
|
- ddd
|
||||||
|
- python
|
||||||
|
- implementation
|
||||||
|
- blueprint
|
||||||
|
---
|
||||||
|
|
||||||
|
# Praxis Implementation Blueprint
|
||||||
|
|
||||||
|
Blueprint translating [SRS v1.0.2](praxis-srs-v1.0.2.md) + [Domain Model v1.0.1](praxis-domain-model-v1.0.1.md) into concrete Python decisions.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> This document is the canonical Phase 0 deliverable (v0.2.0 — Phase 0 Complete). All Phase-1-blocking ambiguities are resolved. Remaining open questions are explicitly deferred to the phases indicated below.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Package Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
src/praxis/
|
||||||
|
├── domain/
|
||||||
|
│ ├── aggregates/ exercise.py, routine.py, workout_session.py
|
||||||
|
│ ├── value_objects/ identifiers.py, measurement.py, enums.py, snapshot.py, set_data.py
|
||||||
|
│ ├── policies/ completion_policy.py, metric_validation.py, workload_calculator.py, adherence_calculator.py
|
||||||
|
│ └── factories/ session_snapshot_factory.py
|
||||||
|
└── application/
|
||||||
|
├── ports/ repositories.py, auth_provider.py, clock.py
|
||||||
|
├── use_cases/ routine/, session/, query/
|
||||||
|
└── dtos/
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependency Direction
|
||||||
|
|
||||||
|
```
|
||||||
|
domain/ ← No external dependencies
|
||||||
|
application/use_cases/ ← depends on: domain/, application/ports/
|
||||||
|
application/ports/ ← depends on: domain/ (Protocol definitions only)
|
||||||
|
infrastructure/ ← depends on: domain/, application/ports/
|
||||||
|
(NEVER depends on application/use_cases/)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### Immutability Strategy
|
||||||
|
|
||||||
|
- Value objects → `@dataclass(frozen=True)`
|
||||||
|
- Entities → `@dataclass(eq=False)` with identity-based `__eq__`
|
||||||
|
- `SessionPrescriptionSnapshot` uses `tuple` children for physical immutability
|
||||||
|
- `SetData` is an explicit frozen value object in `domain/value_objects/set_data.py` (prevents `record_set()` and `MetricValidationPolicy` from developing divergent representations)
|
||||||
|
|
||||||
|
### IDs
|
||||||
|
|
||||||
|
- Newtype frozen dataclasses wrapping `uuid.UUID`
|
||||||
|
- All defined in `domain/value_objects/identifiers.py`
|
||||||
|
|
||||||
|
### Aggregate Construction
|
||||||
|
|
||||||
|
- `create()` is the public API surface.
|
||||||
|
- The dataclass `__init__` is the implementation mechanism; left available for infrastructure adapter rehydration only.
|
||||||
|
|
||||||
|
### Repository Ports
|
||||||
|
|
||||||
|
- Defined as `Protocol` classes in `application/ports/repositories.py`.
|
||||||
|
- Method signatures are provisional; the existence of ports as `Protocol` classes is frozen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resolved Ambiguities (Phase 0 Pass)
|
||||||
|
|
||||||
|
| Ambiguity | Resolution |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `SetPerformance` metric fields | `actual_distance: Distance \| None` added to `SetPerformance` for `DistanceDuration` sprint-style sets. Continuous cardio distance stays on `ActivityPerformance`. |
|
||||||
|
| `CompletionPolicy` | Count-based rule only: `count(logged sets) >= target_sets`. "Honest effort" language is UX copy, not a domain predicate. |
|
||||||
|
| `finish()` override states | Legal overrides: `Completed` and `Partially_Completed` only. `In_Progress` and `Skipped` are illegal overrides; use `skip()` for skipped sessions. |
|
||||||
|
| Metric snapshotting | `PrescriptionSnapshotItem` explicitly freezes `metric_type: MetricType` so validation uses the exercise's metric type at session-start time. |
|
||||||
|
| `ScheduledWorkout` | Read model / application DTO — never persisted; constructed on the fly by `QueryWeeklyCalendarUseCase`. |
|
||||||
|
| `Phase.end_week = None` fallback | Returns the last-defined phase. An empty `phases` list raises `ValueError` at construction time. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implementation Phase Sequence
|
||||||
|
|
||||||
|
| Phase | Scope |
|
||||||
|
| :--- | :--- |
|
||||||
|
| 0 | Implementation Readiness (**Complete** — this document) |
|
||||||
|
| 1 | Pure Domain Foundation — aggregates, value objects, policies, 90%+ coverage |
|
||||||
|
| 2 | Application Layer — use cases with in-memory fakes |
|
||||||
|
| 3 | Infrastructure — SQLAlchemy/SQLite |
|
||||||
|
| 4 | FastAPI Interface |
|
||||||
|
| 5 | Containerisation + Authelia |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 1 Implementation Order
|
||||||
|
|
||||||
|
```
|
||||||
|
identifiers → enums → measurement → RepRange → SetData
|
||||||
|
→ Exercise
|
||||||
|
→ Routine (+ Phase + get_current_phase)
|
||||||
|
→ MetricValidationPolicy
|
||||||
|
→ SessionSnapshotFactory
|
||||||
|
→ WorkoutSession
|
||||||
|
→ CompletionPolicy → WorkloadCalculator → AdherenceCalculator
|
||||||
|
```
|
||||||
|
|
||||||
|
Each step is **test-first**. Domain tests only: no mocks, no database, no HTTP.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deferred Open Questions
|
||||||
|
|
||||||
|
| # | Question | Blocking Phase |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| OQ-1 | `session_date` uniqueness enforcement level | Phase 2 |
|
||||||
|
| OQ-3 | Weight unit preference storage location | Phase 2 |
|
||||||
|
| OQ-4 | Bodyweight prescription (`target_weight = None`) UI communication | Phase 4 |
|
||||||
|
| OQ-5 | Exercise catalog seeding mechanism | Phase 3 |
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: praxis
|
||||||
|
tags:
|
||||||
|
- praxis
|
||||||
|
- srs
|
||||||
|
- homelab
|
||||||
|
- workout-tracker
|
||||||
|
- architecture
|
||||||
|
---
|
||||||
|
|
||||||
|
# Software Requirements Specification (SRS)
|
||||||
|
## Project: Praxis — Personal Workout & Habit Tracking Platform
|
||||||
|
|
||||||
|
**Version:** 1.0.2-draft
|
||||||
|
**Date:** 2026-09-24
|
||||||
|
**Status:** Draft Baseline (Refined)
|
||||||
|
**Previous Version:** [praxis-srs.md](praxis-srs.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> ### Summary of Changes from v1.0.0
|
||||||
|
> - **FR-LOG-1 (Snapshot Clarification)**: Clarified that the *prescription snapshot* is immutable upon initiation, while the session's execution state remains mutable until explicitly finalized (`Completed`, `Partially_Completed`, `Skipped`). Once finalized, the entire session locks against further edits.
|
||||||
|
> - **FR-CAL-2 & FR-RT-3 (DayKind vs. Active Recovery)**: Confirmed `DayKind` strictly contains `Workout`, `Rest`, and `Unscheduled`. *Active Recovery* is modeled as an activity/session (e.g. Saturday cycling activity or Sunday ad-hoc session on a Rest day), not as a separate day kind.
|
||||||
|
> - **FR-RT-4 & FR-LOG-2 (SessionActivity Formalization)**: Promoted non-set movements (warm-up instructions, cardio) into a formal prescription and performance entity pair: `SessionActivity` $\rightarrow$ `ActivityPerformance`.
|
||||||
|
> - **FR-LOG-2 (Effort Scoping)**: Focused effort tracking strictly on optional **RIR (Reps in Reserve)** for MVP, aligning with reference training program instructions (*"dejando 1–2 repeticiones antes del fallo"*). RPE is deferred.
|
||||||
|
> - **FR-ANL-3 & Milestone Scope (1RM Deferral)**: Formally deferred estimated 1RM and automated PR calculation to Milestone 2 to avoid premature algorithmic complexity. MVP focuses strictly on factual exercise history (sets, reps, weight, duration), metric-dependent workload, and adherence rates.
|
||||||
|
> - **FR-ANL-1 (Substitution Analytics Invariant)**: Invariant established: performance of a substituted exercise contributes exclusively to the history of the *performed* exercise, never to the *planned* exercise.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Executive Summary & Domain Philosophy
|
||||||
|
|
||||||
|
**Praxis** (from the Greek/Latin for *"the practical application of a plan"*) is a self-hosted workout execution and habit tracking system designed to run in a homelab environment.
|
||||||
|
|
||||||
|
Unlike typical fitness trackers that conflate what was planned with what was performed, Praxis is architected around a strict **Three-Layer Temporal Model**:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph Layer1["1. Prescription (What should happen)"]
|
||||||
|
R[Routine Template] --> WD[Workout Day]
|
||||||
|
WD --> EP[Exercise Prescription]
|
||||||
|
WD --> SA[Session Activity]
|
||||||
|
R -.-> PH[Progression Phases]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Layer2["2. Performance (What actually happened)"]
|
||||||
|
SW[Scheduled Workout Projection] -->|Initiate| WS[Workout Session]
|
||||||
|
WS --> SPS[SessionPrescriptionSnapshot]
|
||||||
|
WS --> EPF[Exercise Performance]
|
||||||
|
EPF --> SPF[Set Performance]
|
||||||
|
WS --> APF[Activity Performance]
|
||||||
|
WS --> ST[Status: In_Progress / Completed / Partially_Completed / Skipped]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Layer3["3. Analysis (What can be derived)"]
|
||||||
|
ADH[Adherence & Consistency Rates]
|
||||||
|
WKL[Metric-Dependent Workload]
|
||||||
|
HST[Factual Exercise History]
|
||||||
|
TRN[Longitudinal Progression]
|
||||||
|
end
|
||||||
|
|
||||||
|
Layer1 -->|Project into calendar| SW
|
||||||
|
Layer2 -->|Pure deterministic derivation| Layer3
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Core Domain Glossary
|
||||||
|
|
||||||
|
| Term | Definition |
|
||||||
|
| :--- | :--- |
|
||||||
|
| **User** | Internal domain entity representing identity, ownership, and preferences. |
|
||||||
|
| **Routine** | Reusable weekly schedule template specifying which weekdays have workouts, rest, or unscheduled days. |
|
||||||
|
| **Phase** | Temporal cycle within a routine (e.g., Weeks 1–2 vs. Week 3+) that governs progression rules such as prescribed set volumes based on elapsed calendar weeks since routine activation. |
|
||||||
|
| **Exercise** | Canonical movement definition with category, target muscle group, equipment, and default measurement type hint. |
|
||||||
|
| **Exercise Prescription** | Plan for an exercise on a workout day: target sets, target reps/duration, target weight/effort, order, and notes. |
|
||||||
|
| **Session Activity** | Non-set prescribed instruction or movement (e.g., articular warm-up, post-workout cardio, mobility). |
|
||||||
|
| **Scheduled Workout** | Projection of a routine's workout day onto a specific calendar date before physical initiation. |
|
||||||
|
| **Workout Session** | Concrete historical occurrence of physical training on a calendar date. Contains a frozen prescription snapshot and mutable execution state until finalized. |
|
||||||
|
| **Exercise Performance** | Concrete execution of an exercise within a session, containing one or more logged sets and optional substitution context. |
|
||||||
|
| **Set Performance** | Concrete logged set recording actual repetitions, actual weight, duration, optional RIR, and set notes. |
|
||||||
|
| **Activity Performance** | Concrete execution of a session activity (e.g., 20 min cycling completed, warm-up performed). |
|
||||||
|
| **Adherence** | Set of factual metrics tracking scheduled sessions vs completed, partial, and skipped sessions over an evaluation window. |
|
||||||
|
| **Workload** | Metric-dependent measure of physical work performed (weighted volume $\sum \text{reps} \times \text{weight}$, cumulative duration in seconds, or distance). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Fundamental Domain Invariants
|
||||||
|
|
||||||
|
1. **Prescription Snapshot Immutability**: When a `WorkoutSession` is initiated, a complete snapshot of prescribed exercises and activities is frozen. Editing a `Routine` never alters past or in-progress sessions.
|
||||||
|
2. **Session Lifecycle & Mutability**: While `In_Progress`, a `WorkoutSession` execution state is mutable (logging sets, adding exercises, recording deviations). Once transitioned to `Completed`, `Partially_Completed`, or `Skipped`, the entire session becomes immutable.
|
||||||
|
3. **Session Autonomy**: During an active session, a user has total autonomy to deviate from prescribed sets, reps, and weights, swap exercises, add unscheduled exercises, or omit exercises without mutating the parent `Routine`.
|
||||||
|
4. **Decoupled Identity**: The core domain depends only on an internal `UserId`. External identity provider specifics (LLDAP, Authelia, OAuth2) are isolated behind an `AuthProvider` port.
|
||||||
|
5. **Single Active Routine Policy**: An application-level invariant: a user may curate an arbitrary library of routines, but at any given date, at most one routine is marked `Active` to generate scheduled workout projections on the calendar.
|
||||||
|
6. **Substituted History Isolation**: When exercise $A$ is substituted by exercise $B$, the logged sets contribute strictly to the historical record of exercise $B$, preserving an audit trail of the original intent without corrupting exercise $A$'s progress.
|
||||||
|
7. **Derived Analysis Invariant**: Progress metrics (workload, adherence, factual history) are never stored as mutable counters; they are purely derived functions of immutable historical `WorkoutSession` records.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Detailed Functional Requirements
|
||||||
|
|
||||||
|
### 4.1. Identity & External Authentication (Ports & Adapters)
|
||||||
|
- **FR-AUTH-1**: The backend shall decouple authentication from core business logic via an `IdentityAdapter` / `AuthProvider` interface.
|
||||||
|
- **FR-AUTH-2**: The system shall ship with a reverse-proxy header adapter (consuming headers such as `Remote-User`, `Remote-Email`, `Remote-Name` passed by Authelia/Nginx/Traefik).
|
||||||
|
- **FR-AUTH-3**: The system shall automatically provision or sync an internal `User` profile upon receiving a valid authenticated request from an external identity.
|
||||||
|
- **FR-AUTH-4**: The domain model shall be agnostic to credential storage; no passwords, hashes, or SSO credentials shall be persisted in the Praxis domain database.
|
||||||
|
|
||||||
|
### 4.2. Exercise Catalog Management
|
||||||
|
- **FR-EX-1**: The system shall ship with a pre-seeded catalog of standard exercises, covering all movements from the reference training program.
|
||||||
|
- **FR-EX-2**: Users shall be able to create custom exercises and edit their own custom definitions.
|
||||||
|
- **FR-EX-3**: Each exercise shall specify:
|
||||||
|
- `name`: string
|
||||||
|
- `category` / `muscle_group`: (e.g., *Cuádriceps, Glúteo, Espalda, Hombro, Isquiotibiales, Pecho, Brazos, Core, Cardio*)
|
||||||
|
- `equipment`: (e.g., *Smith machine, Dumbbell, Barbell, Cable/Machine, Band, Bodyweight*)
|
||||||
|
- `default_metric`: default hint (*Reps-Weight*, *Duration*, *Distance-Duration*)
|
||||||
|
- `instructions` / `cues`: optional text
|
||||||
|
|
||||||
|
### 4.3. Routine & Phase Management
|
||||||
|
- **FR-RT-1**: Users can create, clone, rename, archive, and delete multiple routines.
|
||||||
|
- **FR-RT-2 (Application Policy)**: The application ensures at most one routine is set as `Active` per user at any given time.
|
||||||
|
- **FR-RT-3**: A routine defines a 7-day weekly schedule (`Monday` through `Sunday`). Each weekday can be assigned as:
|
||||||
|
- `Workout Day`
|
||||||
|
- `Rest Day`
|
||||||
|
- `Unscheduled Day`
|
||||||
|
- **FR-RT-4**: A Workout Day within a routine contains:
|
||||||
|
- **Exercise Prescriptions**: Target sets, target repetitions (or rep ranges, e.g. 10–12), optional target weight, optional unilateral indicator (`each leg / cada pie`), order index, and prescription notes.
|
||||||
|
- **Session Activities**: Non-set activities (e.g., *"Articular warm-up before session"* or *"15–20 min stationary bike or elliptical at moderate pace"*).
|
||||||
|
- **FR-RT-5 (Progression Phases)**: Routines support declarative phases (e.g., Phase 1: Weeks 1–2 prescribing 3 sets; Phase 2: Week 3+ prescribing 4 sets). The active phase is determined deterministically by elapsed calendar weeks from the routine's activation date:
|
||||||
|
$$\text{Week Index} = \left\lfloor \frac{\text{Date} - \text{ActivationDate}}{7} \right\rfloor + 1$$
|
||||||
|
|
||||||
|
### 4.4. Calendar & Scheduling
|
||||||
|
- **FR-CAL-1**: The system shall provide an API for a weekly calendar view displaying projected `ScheduledWorkout` items alongside actual `WorkoutSession` instances across Monday–Sunday.
|
||||||
|
- **FR-CAL-2**: The calendar displays days as `Scheduled Workout Day`, `Rest Day`, or `Unscheduled Day`. Physical activity logged on a Rest day (e.g. Sunday cycling) is displayed as an ad-hoc session or active recovery activity.
|
||||||
|
- **FR-CAL-3**: The calendar shall display historical weeks with immutable records of past performance.
|
||||||
|
|
||||||
|
### 4.5. Workout Execution & Runtime Logging
|
||||||
|
- **FR-LOG-1 (Snapshot on Initiation)**: When a user initiates a workout for a calendar day, Praxis generates a `WorkoutSession` containing a frozen `SessionPrescriptionSnapshot` of the prescribed exercises, sets, target values, and activities.
|
||||||
|
- **FR-LOG-2 (Set-Level Performance)**: For each exercise performance, the user can log:
|
||||||
|
- Actual repetitions completed
|
||||||
|
- Actual weight used (in user's preferred unit: kg or lbs)
|
||||||
|
- Actual duration in seconds (for timed sets like Planks)
|
||||||
|
- Optional RIR (Reps in Reserve, 0–5)
|
||||||
|
- Set-level notes
|
||||||
|
- **FR-LOG-3 (Runtime Session Flexibility)**:
|
||||||
|
- Users can append ad-hoc sets or remove logged sets (by set identity).
|
||||||
|
- Users can reorder exercises during execution.
|
||||||
|
- Users can substitute an exercise on the fly with another exercise from the catalog, preserving the substitution event for auditing.
|
||||||
|
- Users can add completely unscheduled exercises to the active session.
|
||||||
|
- **FR-LOG-4 (Activity Logging)**: Users can record the execution of session activities (e.g., check off warm-up, record actual duration of cardio).
|
||||||
|
- **FR-LOG-5 (Ad-Hoc / Rest Day Logging)**: Users can initiate and log an ad-hoc session or active recovery (e.g., Sunday cycling) on any day without a prior scheduled prescription.
|
||||||
|
- **FR-LOG-6 (Session Notes & Deviations)**: Users can record session-level notes (e.g. *"Gym was crowded, had to swap Smith machine for dumbbells"* or *"Fatigued, stopped 1 set early"*).
|
||||||
|
|
||||||
|
### 4.6. Session Completion Semantics & Habit Adherence
|
||||||
|
- **FR-STAT-1**: A `WorkoutSession` transitions through lifecycle states:
|
||||||
|
- `In_Progress` (user has initiated session and/or logged sets)
|
||||||
|
- `Completed` (all prescribed exercises logged with full set intent)
|
||||||
|
- `Partially_Completed` (session finished with at least one set logged, but some prescribed exercises/sets omitted)
|
||||||
|
- `Skipped` (explicitly marked skipped by user or flagged when scheduled date has passed without initiation)
|
||||||
|
- **FR-STAT-2 (Set-Intent Completion Evaluation)**: An exercise is evaluated as complete when all prescribed sets have been attempted with honest effort (logging reps within target range or completing full sets short of failure with RIR/notes).
|
||||||
|
- **FR-STAT-3 (Smart Completion Suggestion)**: When the user calls "Finish Workout", the system evaluates logged work:
|
||||||
|
- If 100% of prescribed sets/exercises completed $\rightarrow$ suggests `Completed`.
|
||||||
|
- If $>0\%$ completed $\rightarrow$ suggests `Partially_Completed` with summary of completed vs omitted work.
|
||||||
|
- User can confirm or override the final state.
|
||||||
|
- **FR-STAT-4 (Factual Adherence Metrics)**: Adherence is reported as factual distribution rates over a selected evaluation window:
|
||||||
|
- `Completed Sessions Rate`: $N_{\text{completed}} / N_{\text{scheduled}}$
|
||||||
|
- `Partial Sessions Rate`: $N_{\text{partial}} / N_{\text{scheduled}}$
|
||||||
|
- `Skipped Sessions Rate`: $N_{\text{skipped}} / N_{\text{scheduled}}$
|
||||||
|
- `Set Adherence Rate`: Total Sets Performed / Total Sets Prescribed
|
||||||
|
|
||||||
|
### 4.7. Progression & Performance Analytics
|
||||||
|
- **FR-ANL-1 (Factual Exercise History)**: For any exercise, the user can query past performances (chronological history of weights, reps, sets, and workload). Substitutions contribute strictly to the performed exercise.
|
||||||
|
- **FR-ANL-2 (Metric-Dependent Workload)**: For each session and per exercise, compute appropriate workload:
|
||||||
|
- Weighted Repetitions: $\text{Volume} = \sum (\text{reps} \times \text{weight})$
|
||||||
|
- Timed Exercises: $\text{Duration} = \sum \text{seconds}$
|
||||||
|
- Distance: $\text{Distance} = \sum \text{kilometers/meters}$
|
||||||
|
- **FR-ANL-3 (Trend Analytics)**: The system provides query endpoints for time-series trend analysis (weekly workload by muscle group, adherence rates by month, progression curves for core lifts).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Non-Functional & Architectural Requirements
|
||||||
|
|
||||||
|
- **NFR-ARCH-1 (API-First & Decoupled Frontend)**: The backend shall expose a clean, comprehensive REST/OpenAPI specification. The frontend is decoupled.
|
||||||
|
- **NFR-ARCH-2 (Clean / Hexagonal Architecture)**: Domain aggregates (`Routine`, `WorkoutSession`, `Exercise`) contain pure business rules with zero dependencies on database ORMs or web frameworks.
|
||||||
|
- **NFR-ARCH-3 (Self-Hosted / Containerized)**: Deployable as a single Docker container or Docker Compose service with minimal resource footprint (< 256MB RAM idle) suited for homelab micro-servers.
|
||||||
|
- **NFR-ARCH-4 (Zero External Cloud Reliance)**: Runs entirely on local infrastructure with SQLite or PostgreSQL; no third-party telemetry, proprietary clouds, or external API dependencies.
|
||||||
|
- **NFR-ARCH-5 (Data Portability)**: Users can export their entire history, routines, and exercises as JSON / CSV at any time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Implementation Scope Milestones
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
timeline
|
||||||
|
title Praxis Implementation Roadmap (Updated)
|
||||||
|
section MVP (Foundation)
|
||||||
|
Decoupled Auth (Header Adapter) : Domain Aggregates (Routine, WorkoutSession, Exercise) : SessionPrescriptionSnapshot Engine : Multi-Modal Set Logging & Activities : Smart Completion Suggestion : Factual Adherence & Metric Workload Analytics
|
||||||
|
section Milestone 2 (Evolution)
|
||||||
|
Estimated 1RM (Epley/Brzycki) & PR Tracking : Interactive Progression Visualizations : Automated Phase Transition Alerts : Workout Templates Import/Export (JSON/YAML) : Mobile-First PWA Client
|
||||||
|
section Milestone 3 (Advanced)
|
||||||
|
Rest Interval Timers : RPE & Effort Conversions : Equipment Availability Substitution Suggestions : Webhook Event Notifications
|
||||||
|
```
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: draft
|
||||||
|
project: praxis
|
||||||
|
tags:
|
||||||
|
- praxis
|
||||||
|
- srs
|
||||||
|
- homelab
|
||||||
|
- workout-tracker
|
||||||
|
- architecture
|
||||||
|
---
|
||||||
|
|
||||||
|
# Software Requirements Specification (SRS)
|
||||||
|
## Project: Praxis — Personal Workout & Habit Tracking Platform
|
||||||
|
|
||||||
|
**Version:** 1.0.0-draft
|
||||||
|
**Date:** 2026-09-24
|
||||||
|
**Status:** Draft Baseline
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Executive Summary & Domain Philosophy
|
||||||
|
|
||||||
|
**Praxis** (from the Greek/Latin for *"the practical application of a plan"*) is a self-hosted workout execution and habit tracking system designed to run in a homelab environment.
|
||||||
|
|
||||||
|
Unlike typical fitness trackers that conflate what was planned with what was performed, Praxis is architected around a strict **Three-Layer Temporal Model**:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph Layer1["1. Prescription (What should happen)"]
|
||||||
|
R[Routine Template] --> WD[Workout Day]
|
||||||
|
WD --> EP[Exercise Prescription]
|
||||||
|
WD --> ACT[Session Activity / Note]
|
||||||
|
R -.-> PH[Progression Phases]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Layer2["2. Performance (What actually happened)"]
|
||||||
|
SW[Scheduled Workout Projection] -->|Initiate| WS[Workout Session Snapshot]
|
||||||
|
WS --> EPF[Exercise Performance]
|
||||||
|
EPF --> SPF[Set Performance]
|
||||||
|
WS --> APF[Activity Performance]
|
||||||
|
WS --> ST[Status: In_Progress / Completed / Partially_Completed / Skipped]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Layer3["3. Analysis (What can be derived)"]
|
||||||
|
ADH[Adherence & Consistency Rates]
|
||||||
|
VOL[Metric-Dependent Workload]
|
||||||
|
PR[Personal Records & 1RM]
|
||||||
|
TRN[Longitudinal Progression]
|
||||||
|
end
|
||||||
|
|
||||||
|
Layer1 -->|Project into calendar| SW
|
||||||
|
Layer2 -->|Pure deterministic derivation| Layer3
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Core Domain Glossary
|
||||||
|
|
||||||
|
| Term | Definition |
|
||||||
|
| :--- | :--- |
|
||||||
|
| **User** | Internal domain actor owning routines, exercise customizations, and workout history. |
|
||||||
|
| **Routine** | Reusable weekly schedule template specifying which weekdays have workouts, rest, or unscheduled days. |
|
||||||
|
| **Phase** | Temporal cycle within a routine (e.g., Weeks 1–2 vs. Week 3+) that governs progression rules such as prescribed set volumes based on elapsed calendar weeks since routine activation. |
|
||||||
|
| **Exercise** | Canonical movement definition with category, target muscle group, equipment, and default measurement type hint. |
|
||||||
|
| **Exercise Prescription** | Plan for an exercise on a workout day: target sets, target reps/duration, target weight/effort, order, and notes. |
|
||||||
|
| **Session Activity** | Non-set prescribed instruction or movement (e.g., articular warm-up, post-workout cardio, mobility). |
|
||||||
|
| **Scheduled Workout** | Projection of a routine's workout day onto a specific calendar date before physical initiation. |
|
||||||
|
| **Workout Session** | Concrete historical occurrence of physical training on a calendar date. Created upon initiation as an immutable snapshot of the prescribed work. |
|
||||||
|
| **Exercise Performance** | Concrete execution of an exercise within a session, containing one or more logged sets and optional substitution context. |
|
||||||
|
| **Set Performance** | Concrete logged set recording actual repetitions, actual weight, duration, RIR/effort, and set notes. |
|
||||||
|
| **Adherence** | Set of factual metrics tracking scheduled sessions vs completed, partial, and skipped sessions over an evaluation window. |
|
||||||
|
| **Workload** | Metric-dependent measure of physical work performed (weighted volume $\sum \text{reps} \times \text{weight}$, cumulative duration in seconds, or distance). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Fundamental Domain Invariants
|
||||||
|
|
||||||
|
1. **Snapshot Immutability**: Historical `WorkoutSession` records and their contained performances are immutable with respect to future changes in `Routine` templates. Editing a routine never alters past or in-progress sessions.
|
||||||
|
2. **Session Autonomy**: During an active workout session, a user has total autonomy to deviate from prescribed sets, reps, and weights, swap exercises, add unscheduled exercises, or omit exercises without mutating the parent `Routine`.
|
||||||
|
3. **Decoupled Identity**: The core domain depends only on an internal `User` identifier and profile. External identity provider specifics (LLDAP, Authelia, OAuth2) are isolated behind an `AuthProvider` port.
|
||||||
|
4. **Single Active Routine Driving Schedule**: A user may curate an arbitrary library of routines, but at any given date, at most one routine is marked `Active` to generate scheduled workout projections on the calendar.
|
||||||
|
5. **Derived Analysis Invariant**: Progress metrics (workload, adherence, estimated 1RM, personal records) are never stored as mutable counters; they are purely derived functions of immutable historical `WorkoutSession` records.
|
||||||
|
6. **Separation of Schedule and Session**: A `ScheduledWorkout` is a projected calendar event. A `WorkoutSession` comes into existence only upon explicit initiation or ad-hoc workout creation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Detailed Functional Requirements
|
||||||
|
|
||||||
|
### 4.1. Identity & External Authentication (Ports & Adapters)
|
||||||
|
- **FR-AUTH-1**: The backend shall decouple authentication from core business logic via an `IdentityAdapter` / `AuthProvider` interface.
|
||||||
|
- **FR-AUTH-2**: The system shall ship with a reverse-proxy header adapter (consuming headers such as `Remote-User`, `Remote-Email`, `Remote-Name` passed by Authelia/Nginx/Traefik).
|
||||||
|
- **FR-AUTH-3**: The system shall automatically provision or sync an internal `User` profile upon receiving a valid authenticated request from an external identity.
|
||||||
|
- **FR-AUTH-4**: The domain model shall be agnostic to credential storage; no passwords, hashes, or SSO credentials shall be persisted in the Praxis domain database.
|
||||||
|
|
||||||
|
### 4.2. Exercise Catalog Management
|
||||||
|
- **FR-EX-1**: The system shall ship with a pre-seeded catalog of standard exercises, covering all exercises from the reference training program.
|
||||||
|
- **FR-EX-2**: Users shall be able to create custom exercises and edit their own custom definitions.
|
||||||
|
- **FR-EX-3**: Each exercise shall specify:
|
||||||
|
- `name`: string
|
||||||
|
- `category` / `muscle_group`: (e.g., *Cuádriceps, Glúteo, Espalda, Hombro, Isquiotibiales, Pecho, Brazos, Core, Cardio*)
|
||||||
|
- `equipment`: (e.g., *Smith machine, Dumbbell, Barbell, Cable/Machine, Band, Bodyweight*)
|
||||||
|
- `default_metric_type`: default hint (*Reps-Weight*, *Duration*, *Distance-Duration*)
|
||||||
|
- `instructions` / `cues`: optional text
|
||||||
|
|
||||||
|
### 4.3. Routine & Phase Management
|
||||||
|
- **FR-RT-1**: Users can create, clone, rename, archive, and delete multiple routines.
|
||||||
|
- **FR-RT-2**: Exactly one routine can be set as `Active` per user at any given time.
|
||||||
|
- **FR-RT-3**: A routine defines a 7-day weekly schedule (`Monday` through `Sunday`). Each weekday can be assigned as:
|
||||||
|
- `Workout Day`
|
||||||
|
- `Rest Day`
|
||||||
|
- `Unscheduled Day`
|
||||||
|
- **FR-RT-4**: A Workout Day within a routine contains an ordered list of:
|
||||||
|
- **Exercise Prescriptions**: Target sets, target repetitions (or rep ranges, e.g. 10–12), optional target weight, optional unilateral indicator (`each leg / cada pie`), order index, and prescription notes.
|
||||||
|
- **Session Activities / Instructions**: General instructions (e.g., *"Articular warm-up before session"* or *"15–20 min stationary bike or elliptical at moderate pace"*).
|
||||||
|
- **FR-RT-5 (Progression Phases)**: Routines support declarative phases (e.g., Phase 1: Weeks 1–2 prescribing 3 sets; Phase 2: Week 3+ prescribing 4 sets). The active phase is determined deterministically by elapsed calendar weeks from the routine's activation date:
|
||||||
|
$$\text{Week Index} = \left\lfloor \frac{\text{Date} - \text{ActivationDate}}{7} \right\rfloor + 1$$
|
||||||
|
|
||||||
|
### 4.4. Calendar & Scheduling
|
||||||
|
- **FR-CAL-1**: The system shall provide an API for a weekly calendar view displaying projected `ScheduledWorkout` items alongside actual `WorkoutSession` instances across Monday–Sunday.
|
||||||
|
- **FR-CAL-2**: The calendar shall distinguish between `Scheduled Workout Day`, `Rest Day`, `Active Recovery`, and `Unscheduled Day`.
|
||||||
|
- **FR-CAL-3**: The calendar shall display historical weeks with immutable records of past performance.
|
||||||
|
|
||||||
|
### 4.5. Workout Execution & Runtime Logging
|
||||||
|
- **FR-LOG-1 (Snapshot on Initiation)**: When a user initiates a workout for a calendar day, Praxis generates a `WorkoutSession` snapshot copying the prescribed exercises, sets, target values, and activities.
|
||||||
|
- **FR-LOG-2 (Set-Level Performance)**: For each exercise, the user can log:
|
||||||
|
- Set sequence number (1, 2, 3...)
|
||||||
|
- Actual repetitions completed
|
||||||
|
- Actual weight used (in user's preferred unit: kg or lbs)
|
||||||
|
- Actual duration in seconds (for timed sets like Planks)
|
||||||
|
- RIR (Reps in Reserve) or RPE (optional)
|
||||||
|
- Set-level notes
|
||||||
|
- **FR-LOG-3 (Runtime Session Flexibility)**:
|
||||||
|
- Users can append ad-hoc sets or remove prescribed sets.
|
||||||
|
- Users can reorder exercises during execution.
|
||||||
|
- Users can substitute an exercise on the fly with another exercise from the library, preserving the substitution event for auditing.
|
||||||
|
- Users can add completely unscheduled exercises to the active session.
|
||||||
|
- **FR-LOG-4 (Ad-Hoc / Rest Day Logging)**: Users can initiate and log an ad-hoc session or active recovery (e.g., Sunday cycling) on any day without a prior scheduled prescription.
|
||||||
|
- **FR-LOG-5 (Session Notes & Deviations)**: Users can record session-level notes (e.g. *"Gym was crowded, had to swap Smith machine for dumbbells"* or *"Fatigued, stopped 1 set early"*).
|
||||||
|
|
||||||
|
### 4.6. Session Completion Semantics & Habit Adherence
|
||||||
|
- **FR-STAT-1**: A `WorkoutSession` transitions through lifecycle states:
|
||||||
|
- `In_Progress` (user has initiated session and/or logged sets)
|
||||||
|
- `Completed` (all prescribed exercises logged with full set intent)
|
||||||
|
- `Partially_Completed` (session finished with at least one set logged, but some prescribed exercises/sets omitted)
|
||||||
|
- `Skipped` (explicitly marked skipped by user or flagged when scheduled date has passed without initiation)
|
||||||
|
- **FR-STAT-2 (Set-Intent Completion Evaluation)**: An exercise is evaluated as complete when all prescribed sets have been attempted with honest effort (logging reps within target range or completing full sets short of failure with RIR/notes).
|
||||||
|
- **FR-STAT-3 (Smart Completion Suggestion)**: When the user calls "Finish Workout", the system evaluates logged work:
|
||||||
|
- If 100% of prescribed sets/exercises completed $\rightarrow$ suggests `Completed`.
|
||||||
|
- If $>0\%$ completed $\rightarrow$ suggests `Partially_Completed` with summary of completed vs omitted work.
|
||||||
|
- User can confirm or override the final state.
|
||||||
|
- **FR-STAT-4 (Factual Adherence Metrics)**: Rather than an arbitrary weighted score, adherence is reported as factual distribution rates over a selected evaluation window:
|
||||||
|
- `Completed Sessions Rate`: $N_{\text{completed}} / N_{\text{scheduled}}$
|
||||||
|
- `Partial Sessions Rate`: $N_{\text{partial}} / N_{\text{scheduled}}$
|
||||||
|
- `Skipped Sessions Rate`: $N_{\text{skipped}} / N_{\text{scheduled}}$
|
||||||
|
- `Set Adherence Rate`: Total Sets Performed / Total Sets Prescribed
|
||||||
|
|
||||||
|
### 4.7. Progression & Performance Analytics
|
||||||
|
- **FR-ANL-1 (Exercise History)**: For any exercise, the user can query past performances (chronological history of weights, reps, sets, and workload).
|
||||||
|
- **FR-ANL-2 (Metric-Dependent Workload)**: For each session and per exercise, compute appropriate workload:
|
||||||
|
- Weighted Repetitions: $\text{Volume} = \sum (\text{reps} \times \text{weight})$
|
||||||
|
- Timed Exercises: $\text{Duration} = \sum \text{seconds}$
|
||||||
|
- Distance: $\text{Distance} = \sum \text{kilometers/meters}$
|
||||||
|
- **FR-ANL-3 (Personal Records & Estimated 1RM)**: The system shall calculate personal bests per exercise:
|
||||||
|
- Max Weight Lifted
|
||||||
|
- Max Volume in a Single Session
|
||||||
|
- Estimated 1RM using Brzycki or Epley formula:
|
||||||
|
$$\text{1RM}_{\text{Epley}} = w \times \left(1 + \frac{r}{30}\right)$$
|
||||||
|
- **FR-ANL-4 (Trend Analytics)**: The system provides query endpoints for time-series trend analysis (weekly workload by muscle group, adherence rates by month, progression curves for core lifts).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Non-Functional & Architectural Requirements
|
||||||
|
|
||||||
|
- **NFR-ARCH-1 (API-First & Decoupled Frontend)**: The backend shall expose a clean, comprehensive REST/OpenAPI specification. The frontend is decoupled.
|
||||||
|
- **NFR-ARCH-2 (Clean / Hexagonal Architecture)**: Domain entities (`User`, `Routine`, `WorkoutSession`, `Exercise`) contain pure business rules with zero dependencies on database ORMs or web frameworks.
|
||||||
|
- **NFR-ARCH-3 (Self-Hosted / Containerized)**: Deployable as a single Docker container or Docker Compose service with minimal resource footprint (< 256MB RAM idle) suited for homelab micro-servers.
|
||||||
|
- **NFR-ARCH-4 (Zero External Cloud Reliance)**: Runs entirely on local infrastructure with SQLite or PostgreSQL; no third-party telemetry, proprietary clouds, or external API dependencies.
|
||||||
|
- **NFR-ARCH-5 (Data Portability)**: Users can export their entire history, routines, and exercises as JSON / CSV at any time.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: completed
|
||||||
|
project: skills
|
||||||
|
date: 2026-10-23
|
||||||
|
tags:
|
||||||
|
- nix
|
||||||
|
- devshell
|
||||||
|
- agent-skills
|
||||||
|
- build-skill
|
||||||
|
- specification
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan: Nix Development Shell Authoring Skill (`nix-devshell`)
|
||||||
|
|
||||||
|
## Epistemic Role & Purpose
|
||||||
|
|
||||||
|
This document is the approved technical specification and implementation plan for transforming the reconciled Nix development-shell manifesto (`manifesto-revised.md` and `audit/compatibility-verification.md`) into a portable, evidence-based agent skill (`skills/nix-devshell/`).
|
||||||
|
|
||||||
|
It defines the skill's operational boundaries, source authority hierarchy, progressive validation levels, Git ownership invariants, canonical reference division, and acceptance criteria.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Source Authority Hierarchy
|
||||||
|
|
||||||
|
Claims and guidance in the skill follow a strict 3-tier hierarchy:
|
||||||
|
|
||||||
|
1. **Primary Authority (`manifesto-revised.md`)**: The authoritative technical specification. All core operational prescriptions in the skill trace directly to manifesto sections.
|
||||||
|
2. **Constraint & Qualification Layer (`audit/compatibility-verification.md`)**: Narrows, bounds, and flags version-sensitive or unresolved manifesto claims. Does not introduce ungrounded rules.
|
||||||
|
3. **Provenance & Context Only (`audit/manifesto-audit.md`, `audit/manifesto-revision-log.md`)**: Documents the rationale for historical revisions; never cited as independent technical authority.
|
||||||
|
|
||||||
|
### Bounded Claims & Explicit Evidence Labels
|
||||||
|
|
||||||
|
| Manifesto Area | Constraint Applied | Evidence & Applicability in Skill |
|
||||||
|
|---|---|---|
|
||||||
|
| §6.2 Environment attributes | Flat, non-reserved attributes become shell variables; protected variables require `shellHook`. Nested `env` is excluded from portable guidance. | `Established` for nixpkgs 24.05 tutorial; `Unresolved` across older revisions. Verify against project lock. |
|
||||||
|
| §5 D4 Compiler selection | Changing the compiler requires selecting a toolchain/stdenv (`mkShell.override { stdenv = ...; }`). Adding a compiler package to `packages` does not guarantee `CC`. | `Established` pattern in nixpkgs, version-sensitive. Check target revision and platform. |
|
||||||
|
| §4.5 Foreign binaries on NixOS | Diagnosis split by failure mode: missing ELF interpreter vs. missing shared objects vs. FHS path assumptions. | `Established` in nix.dev FAQ. Linux/NixOS only; `nix-ld` is host-level configuration. |
|
||||||
|
| §5 D2 Tarball & Renovate inputs | Nix locking an input and a bot updating it are separate concerns. Cache availability is a third, separate question. | Renovate Nix manager docs (v44.181.0, beta/opt-in). Check project tooling. |
|
||||||
|
| §2, §9.1 Compatibility matrix | No numeric minimum version or universal nixpkgs release range is declared. | Policy from verification audit: verify against target lock and host Nix baseline. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Operational Invariants & Git Boundaries
|
||||||
|
|
||||||
|
1. **Evidence-First Inspection**: The agent must inspect existing Nix files, `flake.lock` (or record that none is present), `.envrc`, language manifests, build scripts, CI, and host Nix capabilities *before* deciding on an architecture.
|
||||||
|
2. **Strict Git Ownership**:
|
||||||
|
- `nix-devshell` may create and modify project files.
|
||||||
|
- It **must never** run `git add`, `git commit`, `git stash`, or mutate the Git index or history.
|
||||||
|
- Staging and committing are strictly handed off to `git-commit`.
|
||||||
|
3. **Untracked File Blockage vs. Failure**:
|
||||||
|
- In a Git-backed flake, newly created untracked files are omitted by Nix's Git source filtering.
|
||||||
|
- The skill must **not** stage files to bypass this.
|
||||||
|
- It must **not** substitute `path:.` by default (as this copies untracked files and potential secrets to `/nix/store` and does not test the Git-filtered workflow).
|
||||||
|
- Flake evaluation must be reported as `blocked: <file> untracked by Git`, while running independent checks (e.g. `nix-instantiate --parse`).
|
||||||
|
- The user is instructed under *User actions* to track files (manually or via `git-commit`) and rerun blocked levels.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Four-Level Progressive Validation Semantics
|
||||||
|
|
||||||
|
Validation must proceed progressively through distinct phases; earlier levels never prove later ones:
|
||||||
|
|
||||||
|
| Level | Commands (Project-Aligned) | What It Proves | What It Does NOT Prove |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **1. Evaluation** | `nix flake show`; `nix eval .#devShells.<sys>.default.drvPath`; `nix-instantiate shell.nix` | Expression evaluates and produces derivation for that system | That inputs can be fetched or built, or that the shell starts |
|
||||||
|
| **2. Realization + Shell Start** | `nix develop --command true`; `nix-shell --run true` | Store paths exist on host and shell initializes in command mode | That tools have correct versions or that project builds |
|
||||||
|
| **3. Environment Check** | `nix develop --command <tool> --version`; `command -v <tool>`; `pkg-config --modversion` (only if build uses it) | Named tools, versions, and variables are present in shell | That compilation, linking, or runtime commands succeed |
|
||||||
|
| **4. Project Command** | `nix develop --command <build/test/lint command>` | That specific command succeeded on tested host with current inputs | Other commands, platforms, or unpinned ecosystem downloads |
|
||||||
|
|
||||||
|
`nix flake check` sits beside this hierarchy: it evaluates recognized outputs and builds `checks.<system>`, but does not enter `devShells` or run project build commands unless a check explicitly does so.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Reference Architecture
|
||||||
|
|
||||||
|
The skill follows `build-skill/references/skeleton.md`: `SKILL.md` stays strictly $\le 80$ lines, while technical depth is organized into 5 dedicated reference files:
|
||||||
|
|
||||||
|
```text
|
||||||
|
skills/nix-devshell/
|
||||||
|
├── SKILL.md # Operational steps, report format, Your call (<= 80 lines)
|
||||||
|
└── references/
|
||||||
|
├── design-decisions.md # Workflow, commands, inputs, systems, constructors, deps
|
||||||
|
├── native-deps.md # Outputs, hooks, pkg-config, compiler overrides, FHS/nix-ld
|
||||||
|
├── authoring-patterns.md # Syntax pitfalls, mkShell arguments, standalone minimal patterns
|
||||||
|
├── validation-troubleshooting.md # 6 execution phases, 4 validation levels, symptom table
|
||||||
|
└── compatibility.md # Epistemic labels, inspection protocol, version caveats, sources
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Repository Integration & Verification Gates
|
||||||
|
|
||||||
|
- **Installation**: Registered in `install.sh` under `ACTIVE_PORTABLE_SKILLS` in alphabetical order.
|
||||||
|
- **Documentation**: Documented in `README.md` under Portable Core table.
|
||||||
|
- **Change Management**: Authored on feature branch `feat/nix-devshell`; zero unapproved commits to `main`.
|
||||||
|
- **Dogfooding**: Validated through fresh-context subagents executing in 10 isolated fixture repositories under `~/Projects/tests/nix-devshell-dogfood/`.
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: draft
|
||||||
|
project: armonia-dashboard
|
||||||
|
pilot: group-workshop-roster
|
||||||
|
date: 2026-10-25
|
||||||
|
tags: [collaboration-plan, pilot, governance, anne-droid, qa]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Project Collaboration Plan: Group Workshop Roster Pilot
|
||||||
|
|
||||||
|
> **Status:** Draft Working Plan (Under Owner Review)
|
||||||
|
> **Target System:** `armonia-dashboard`
|
||||||
|
> **Pilot Simplification Note:** For this pilot, the Orchestrator synthesizes both the requirements and the UX proposal. This is a deliberate pilot simplification to test the workflow without premature agent proliferation; it does **not** demonstrate that Requirements Engineering and UX Design are interchangeable in the permanent agency architecture.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Active Role Roster & Authority Boundaries
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
autonumber
|
||||||
|
actor PO as Project Owner
|
||||||
|
participant ORCH as Orchestrator
|
||||||
|
participant ANNE as Anne Droid (Frontend)
|
||||||
|
participant QA as Independent QA
|
||||||
|
|
||||||
|
PO->>ORCH: 1. Approve Collaboration Plan & Spec Contract
|
||||||
|
ORCH->>ANNE: 2. Delegate approved spec + API contract
|
||||||
|
Note over ANNE: Worktree: ../armonia-dashboard-anne-roster<br/>Implements views, styles, unit tests<br/>Documents contract friction if blocked
|
||||||
|
ANNE->>ORCH: 3. Open Draft PR & Freeze Anne Self-Audit
|
||||||
|
Note over ORCH,QA: Information Barrier: QA has ZERO access<br/>to Anne's code diff, PR text, or self-audit
|
||||||
|
ORCH->>QA: 4. Dispatch Running URL + Verification Packet ONLY
|
||||||
|
Note over QA: Executes Scenarios 1 to 8<br/>Verifies UI, persistence (F5), a11y, mobile
|
||||||
|
QA->>ORCH: 5. Submit QA Evidence Scorecard (Pass/Fail per AC)
|
||||||
|
ORCH->>PO: 6. Present PR Diff + Anne Audit + QA Scorecard
|
||||||
|
alt All Criteria Pass & Evidence Verified
|
||||||
|
PO->>ANNE: 7a. Authorize PR Merge into main
|
||||||
|
else Defects / Gaps Detected
|
||||||
|
PO->>ORCH: 7b. Issue Revision Directive (routed per Escalation Protocol)
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
| Role | Operational Scope for This Pilot | Autonomous Authority | Strict Boundary / Prohibited |
|
||||||
|
| :---------------------------- | :------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------- |
|
||||||
|
| **Project Owner** | Final business authority, requirement sign-off, risk acceptance, conflict adjudication, and release approval. | All consequential product and architectural decisions. | N/A |
|
||||||
|
| **Orchestrator** | Synthesizes specification; monitors handoffs; verifies precondition gates; routes escalation friction. | Workflow sequencing, contract packaging, QA test dispatching. | **Cannot** modify acceptance criteria, relax invariants, waive QA defects, or approve PR merges. |
|
||||||
|
| **Anne Droid (Frontend)** | Implements frontend views, styles, and component tests against the approved contract. | Component modularity, state architecture, styling tokens, local unit tests, implementation decomposition, and commit sequencing. | **Cannot** commit to `main`, modify business logic, silently mock API endpoints, merge PRs, or **modify/refactor existing working features outside the assigned scope**. |
|
||||||
|
| **Independent QA Specialist** | Validates running application against acceptance criteria using the Verification Packet. | Pass/Fail/Blocked verdicts per criterion backed by browser evidence. | **Cannot** waive acceptance criteria, inspect Anne's code/self-audit, or make release decisions. |
|
||||||
|
|
||||||
|
### 1.1 Scope Containment & Non-Regression Invariant
|
||||||
|
When tasked with implementing a new feature (Feature C, e.g. Workshop Roster):
|
||||||
|
1. **Preserve Existing Capabilities**: Existing views and features (Features A and B: Follow-up Queue, Daily Agenda, Client Directory, Nueva Cita modal) must continue to function without behavioral, visual, or test regressions. All existing test suites (`pnpm exec vp test`) must pass 100%.
|
||||||
|
2. **Beyond Automated Tests (Targeted Workflow Checks)**: Because existing automated tests may not cover every edge in Queue or Agenda, Anne's self-audit must execute targeted smoke checks of those existing workflows (e.g. verifying that the 48h queue loads and the Nueva Cita modal still opens without errors).
|
||||||
|
3. **Additive Isolation & Justified Integration**: Feature C must reside in dedicated, isolated files (e.g., `src/components/WorkshopRoster.ts`). Edits to shared integration points (`main.ts`, `api.ts`, `types.ts`, `style.css`) should be strictly additive by default. If an unavoidable non-additive integration edit is required, Anne must document and justify it in her frozen self-audit.
|
||||||
|
4. **No Opportunistic Refactoring**: Anne is strictly prohibited from rewriting, reorganizing, or reformatting existing working components unless explicitly instructed by the Specification Contract.
|
||||||
|
5. **Self-Audit Regression Gate**: Anne's frozen self-audit must explicitly prove that existing tabs still render correctly and that the git diff is tightly bounded to the assigned feature.
|
||||||
|
|
||||||
|
### 1.2 Incremental Implementation & Commit Discipline
|
||||||
|
Anne Droid owns the decomposition of the approved feature specification into coherent implementation increments. The Project Owner defines the required outcomes and acceptance criteria; the Orchestrator does not prescribe the implementation task sequence unless a specific dependency, risk, or contract constraint requires intervention.
|
||||||
|
|
||||||
|
1. **Engineer-Owned Decomposition**: Before writing code, Anne identifies a practical sequence of implementation increments based on the approved contract and existing architecture. The sequence is an engineering breakdown, not a source of new product requirements. Missing requirements or consequential scope changes must be escalated rather than resolved through implementation planning alone.
|
||||||
|
2. **Coherent Incremental Commits**: Anne commits completed increments as work progresses. Each commit must have a clear purpose, a reviewable diff, and a Conventional Commit message describing the change (e.g., `feat(roster): add API client and roster types`, `feat(roster): implement session card and capacity indicators`). Commits must reflect genuine progress rather than arbitrary file boundaries or retrospective subdivision of a completed feature.
|
||||||
|
3. **Intermediate Integrity**: Each commit should leave the branch in a coherent state and pass the checks relevant to its changes (`pnpm exec biome check .`, `vp check`). The completed feature must pass the full required test suite. Any temporary intermediate limitation must be intentional, documented in commit notes, and resolved before the PR is submitted for review.
|
||||||
|
4. **Scope and Regression Boundaries**: Incremental commits do not authorize opportunistic refactoring or unrelated behavior changes. Changes to existing features and shared integration points remain subject to the Scope Containment & Non-Regression Invariant.
|
||||||
|
5. **Traceability and Review**: Anne's frozen self-audit must summarize the implementation increments, map commits to acceptance criteria, explain any justified deviations from the initial breakdown, and document any known limitations. The Orchestrator may flag incoherent commits, excessive unrelated changes, or gaps in traceability, but may not dictate implementation details solely to enforce a preferred task sequence.
|
||||||
|
6. **Integrated Verification**: Commit-level checks do not replace feature-level acceptance testing or independent QA. The complete pull request remains subject to the approved Specification Contract, Verification Packet, regression requirements, and Project Owner's release decision.
|
||||||
|
|
||||||
|
### 1.3 Clarification on QA Failure Routing & Final Acceptance
|
||||||
|
- **QA owns its findings and supporting evidence**, not the release decision.
|
||||||
|
- If QA reports a failure on an acceptance criterion, the Orchestrator routes the defect back to Anne (for an implementation bug) or to the relevant specialist (for an API or requirement flaw).
|
||||||
|
- **The Orchestrator cannot waive a failure or convert a failed acceptance criterion into a pass.** Only the Project Owner has the authority to relax a requirement, accept a known risk, or authorize a PR merge.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Phase-by-Phase Handoff Matrix
|
||||||
|
|
||||||
|
| Phase | Acting Role | Required Input | Produced Output | Approval Gatekeeper |
|
||||||
|
| :------------------------------------ | :----------------------------------------- | :------------------------------------------- | :----------------------------------------------------------- | :------------------------------------------------ |
|
||||||
|
| **Phase 1: Operating Model** | Orchestrator | Pre-experiment baseline snapshot | `COLLABORATION-PLAN.md` | **Project Owner** (Signs off on roles) |
|
||||||
|
| **Phase 2: Contract Formulation** | Orchestrator (Requirements + UX synthesis) | API schema, M4 roadmap scope | `SPEC-WORKSHOP-ROSTER.md` + `VERIFICATION-PACKET-ROSTER.md` | **Project Owner** (Approves criteria & test data) |
|
||||||
|
| **Phase 3: Implementation** | Anne Droid | Approved spec + running API | `feat/anne/workshop-roster` PR + frozen `anne-self-audit.md` | **Anne Droid** (Freezes self-audit prior to QA) |
|
||||||
|
| **Phase 4: Independent Verification** | QA Specialist | Running build URL + Verification Packet ONLY | `qa-evidence-scorecard.md` | **QA Specialist** (Signs off on test evidence) |
|
||||||
|
| **Phase 5: Release & Post-Mortem** | Project Owner | PR diff + Anne Audit + QA Scorecard | Merge decision + Pilot evaluation log | **Project Owner** (Decides merge / rework) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Explicit Change & Escalation Protocol
|
||||||
|
|
||||||
|
If any specialist encounters a blocking condition or contradiction, work halts at that boundary and routes strictly according to problem type:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
BLOCK["Friction Encountered"] --> CAT{Classify Problem}
|
||||||
|
CAT -->|"Contradictory / Missing Business Rule"| REQ["Orchestrator / Requirements"]
|
||||||
|
CAT -->|"Unworkable Interaction Flow"| UX["Orchestrator / UX"]
|
||||||
|
CAT -->|"API Schema Defect / Backend 500"| BE["Backend Owner / Issue Tracker"]
|
||||||
|
CAT -->|"Implementation Bug"| ANNE["Anne Droid (Worktree)"]
|
||||||
|
CAT -->|"Ambiguous / Broken Test Criterion"| QA["Requirements + QA Specialist"]
|
||||||
|
CAT -->|"Scope Trade-off or Scope Relaxation"| PO["Project Owner (Human Decision)"]
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **API Friction Rule**: Anne must record a structured **Contract Friction Notice** on the PR rather than silently creating synthetic mock data or changing expected response shapes.
|
||||||
|
2. **Owner Escalation Rule**: Any trade-off affecting user workflows (e.g. omitting walk-in check-ins due to API constraints) requires an explicit choice from the Project Owner.
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
role: specification-contract
|
||||||
|
status: draft
|
||||||
|
project: armonia-dashboard
|
||||||
|
feature: workshop-roster-checkin
|
||||||
|
milestone: M4
|
||||||
|
date: 2026-10-25
|
||||||
|
tags: [spec, frontend, requirements, ux, armonia-dashboard]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Specification Contract: Group Workshop Roster Quick Check-in
|
||||||
|
|
||||||
|
> **Contract Authority:** Binding implementation contract for `armonia-dashboard`.
|
||||||
|
> **Engineering Boundary:** This specification defines *what* the operator must accomplish and *how* states behave. The component breakdown, DOM composition, and styling implementation belong to Anne Droid's engineering judgment. Implementation must be strictly additive and isolated; existing features (Follow-up Queue, Daily Agenda, Client Directory, Nueva Cita) must remain undisturbed and 100% passing.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Domain Context & User Goals
|
||||||
|
|
||||||
|
In Armonía del Ser, group services (e.g., *Círculo de Cacao Presencial*, *Meditación con Cuencos*) take place with multiple attendees (up to 12–25 capacity).
|
||||||
|
|
||||||
|
**The Operator's Goal:**
|
||||||
|
On the day of the workshop, Jasmin or her assistant stands at reception. As participants arrive, the operator needs a mobile-first, high-density view to:
|
||||||
|
1. Confirm which group workshop session is active today and review capacity metrics.
|
||||||
|
2. Rapidly record digital attendance (1-tap check-in marking attendance and completing the booking).
|
||||||
|
3. Identify payment state at a glance: identify who is pre-paid (`PAGADO` via SPEI) versus who must pay on arrival (`PENDIENTE`).
|
||||||
|
4. Collect cash on-site and acknowledge payment in the same 1-tap check-in action.
|
||||||
|
5. Register and check in unexpected walk-in attendees without disrupting the session flow.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Precise Semantic Definitions & Status Mapping
|
||||||
|
|
||||||
|
### 2.1 The Two Workshop Counters
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ Workshop Counter Semantics │
|
||||||
|
├─────────────────────┬──────────────────────────────────────────────────┤
|
||||||
|
│ Metric │ Business Meaning & Mutation Rules │
|
||||||
|
├─────────────────────┼──────────────────────────────────────────────────┤
|
||||||
|
│ occupied_count │ Total participants holding an active spot │
|
||||||
|
│ │ (status: RESERVED, COMPLETED, NO_SHOW). │
|
||||||
|
│ │ • Advance booking created: count increments. │
|
||||||
|
│ │ • Existing attendee checks in: count UNCHANGED. │
|
||||||
|
│ │ • Walk-in attendee registers: count increments. │
|
||||||
|
├─────────────────────┼──────────────────────────────────────────────────┤
|
||||||
|
│ attended_count │ Participants physically present & verified │
|
||||||
|
│ │ (booking_status: COMPLETED, attended: true). │
|
||||||
|
│ │ • Existing attendee checks in: count increments. │
|
||||||
|
│ │ • Walk-in attendee registers: count increments. │
|
||||||
|
└─────────────────────┴──────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Capacity Display**: Formatted as `Ocupación: {occupied_count} / {max_capacity} ({attended_count} presentes)`.
|
||||||
|
- **409 Conflict Disambiguation & Reconciliation Contract**:
|
||||||
|
The backend issues `HTTP 409 Conflict` in two distinct business scenarios, verified against pinned backend commit `d9c86e27d926` in `armonia-api/app/routers/rosters.py`. The client must inspect `response.detail` (or error payload):
|
||||||
|
1. *Already Checked-In Conflict (`detail: "This attendee has already checked in."`)* (`app/routers/rosters.py#L196`): Indicates an idempotent duplicate submission. The client must reconcile by updating the attendee row to `ASISTIÓ`, disabling the check-in button, and showing an informative status toast (*"El asistente ya contaba con asistencia registrada"*). The client must never crash or treat this as a failed/unregistered state.
|
||||||
|
2. *Capacity Exceeded Conflict (`detail: "El taller ha alcanzado su cupo máximo ({max_cap}) para esta sesión."`)* (`app/routers/rosters.py#L332`): Occurs during walk-in registration when `occupied_count >= max_capacity`. The client must detect the capacity message (e.g. matching `cupo máximo`), display an explicit capacity error alert (*"El taller ha alcanzado su cupo máximo (15) para esta sesión"*), keep the modal form state intact for operator decision, and **never** optimistically increment attendance or report success.
|
||||||
|
- **Ordinary Network / 500 Failure**: Preserve the current UI state, do not change attendee status, and allow the operator to retry.
|
||||||
|
- **Technical Debt & Future Contract Note**: String matching on `response.detail` is a pilot accommodation to preserve backend immutability on `armonia-api`. A future M5 ADR will introduce structured machine-readable error codes (e.g. `{"error_code": "ATTENDEE_ALREADY_CHECKED_IN"}`).
|
||||||
|
|
||||||
|
### 2.2 Status Terminology Mapping Table
|
||||||
|
|
||||||
|
To prevent ambiguity between UI labels and backend persistence, all badge renderings must adhere to this mapping:
|
||||||
|
|
||||||
|
| UI Badge / Label | Visual Styling | Backend Entity | Persisted Status Field & Value |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`REGISTRADO`** | Slate/Neutral Pill | `Booking` | `booking_status: "RESERVED"`, `attended: false` |
|
||||||
|
| **`ASISTIÓ`** | Emerald/Green Pill | `Booking` | `booking_status: "COMPLETED"`, `attended: true` |
|
||||||
|
| **`PAGADO`** | Emerald/Green Pill | `Booking` & `Payment` | `payment_status: "ACKNOWLEDGED"` |
|
||||||
|
| **`PENDIENTE`** | Amber/Orange Pill | `Booking` | `payment_status: "AWAITING_ACKNOWLEDGMENT"` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Resilient Error-Recovery Contract (The 5 States)
|
||||||
|
|
||||||
|
Every interactive view in this feature must explicitly handle the 5 states:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
stateDiagram
|
||||||
|
[*] --> Loading: Switch to #rosters tab
|
||||||
|
Loading --> Empty: GET /rosters returns []
|
||||||
|
Loading --> Error_Roster: GET /rosters fails (Network/500)
|
||||||
|
Loading --> Roster_Ready: GET /rosters returns sessions
|
||||||
|
|
||||||
|
Error_Roster --> Loading: Tap "Reintentar"
|
||||||
|
Empty --> Loading: Change date picker
|
||||||
|
|
||||||
|
Roster_Ready --> Action_In_Flight: Tap Check-in or Submit Walk-in
|
||||||
|
Action_In_Flight --> Action_Error: POST fails (Timeout/Network)
|
||||||
|
Action_In_Flight --> Roster_Ready: POST succeeds (HTTP 200) -> Toast
|
||||||
|
Action_Error --> Roster_Ready: Toast error; row stays uncommitted
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **Loading State**: Render skeleton placeholder cards for workshop sessions and attendee rows. Layout shift (CLS) must remain $\le 0.05$.
|
||||||
|
2. **Empty State**: If no group sessions exist for the selected date, display:
|
||||||
|
> *"No hay talleres grupales programados para esta fecha."*
|
||||||
|
The date selector remains interactive so the operator can navigate to adjacent days.
|
||||||
|
3. **Failed Roster Retrieval (Error with Retry)**: If `GET /rosters` fails (network down or server error), display an inline error banner:
|
||||||
|
> *"No se pudieron cargar los talleres. Verifica tu conexión."*
|
||||||
|
Accompanied by an explicit `<button class="btn btn-secondary">Reintentar</button>` that re-triggers the fetch without a full page reload.
|
||||||
|
4. **Action Failure & Conflict Recovery**:
|
||||||
|
- *Already-Checked-In Conflict (409)*: If the server reports the attendee is already checked in, the client reconciles state by updating the row to `ASISTIÓ`, disabling check-in, and displaying an informative notice (*"El asistente ya contaba con asistencia registrada"*).
|
||||||
|
- *Capacity Reached Conflict (409)*: If a walk-in is rejected because the session is full, the client reports the capacity limit (*"El taller ha alcanzado su cupo máximo"*), leaves the form open for operator decision, and does not record attendance.
|
||||||
|
- *Network / Server Error (5xx / Timeout)*: The client displays an accessible error toast, preserves the uncommitted attendee row state (no optimistic toggle), and keeps the action button enabled for immediate retry.
|
||||||
|
5. **Success Feedback State**: Upon successful check-in or walk-in:
|
||||||
|
- Immediate visual feedback on the row (`ASISTIÓ` badge).
|
||||||
|
- Display an accessible toast container equipped with `role="status"` and `aria-live="polite"` announcing: *"Asistencia registrada con éxito."*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Explicit Acceptance Criteria (AC)
|
||||||
|
|
||||||
|
### `AC-1`: Workshop Session Selection & Capacity Overview
|
||||||
|
- **Given** the operator navigates to the "Talleres" tab (URL hash `#rosters`),
|
||||||
|
- **When** the view loads for the selected date (default: today),
|
||||||
|
- **Then** it queries `GET /rosters?date_from=YYYY-MM-DD&date_to=YYYY-MM-DD`.
|
||||||
|
- **And** it displays the group session title, scheduled time, and a capacity counter formatted as `Ocupación: {occupied_count} / {max_capacity} ({attended_count} presentes)`.
|
||||||
|
|
||||||
|
### `AC-2`: Attendee Roster Display & Status Indicators
|
||||||
|
- **Given** an active workshop session with registered attendees,
|
||||||
|
- **When** the session roster renders,
|
||||||
|
- **Then** each attendee row displays: Client Name, Phone, Booking Code (`ADS-XXXX`), Attendance Status (`REGISTRADO` vs. `ASISTIÓ`), and Payment Status (`PAGADO` vs. `PENDIENTE`).
|
||||||
|
- **And** includes a 1-tap `wa.me` link pre-populated with the attendee's phone.
|
||||||
|
|
||||||
|
### `AC-3`: Existing Booking Check-in (Pre-paid)
|
||||||
|
- **Given** an attendee with `booking_status: "RESERVED"` and `payment_status: "ACKNOWLEDGED"`,
|
||||||
|
- **When** the operator taps the "Registrar Asistencia" button,
|
||||||
|
- **Then** the client sends `POST /rosters/quick-checkin` with payload `{"booking_id": "<id>", "paid_cash": false}`.
|
||||||
|
- **And** upon HTTP 200, the row immediately updates to `ASISTIÓ`, the check-in button disables, and `attended_count` increments by 1.
|
||||||
|
|
||||||
|
### `AC-4`: Existing Booking Check-in with Cash Payment Acknowledgment
|
||||||
|
- **Given** an attendee with `payment_status: "AWAITING_ACKNOWLEDGMENT"`,
|
||||||
|
- **When** the operator taps check-in with "Cobro en efectivo recibido" checked,
|
||||||
|
- **Then** the client sends `POST /rosters/quick-checkin` with payload `{"booking_id": "<id>", "paid_cash": true, "notes": "Cobro en puerta"}`.
|
||||||
|
- **And** upon HTTP 200, the row reflects both `ASISTIÓ` and `PAGADO` (`ACKNOWLEDGED`), and `attended_count` increments by 1 without full page reload.
|
||||||
|
|
||||||
|
### `AC-5`: Walk-in Attendee Quick Registration & Check-in
|
||||||
|
- **Given** an unregistered participant arrives at the workshop,
|
||||||
|
- **When** the operator taps "+ Registrar Asistente Sin Cita",
|
||||||
|
- **Then** a modal opens requesting: Full Name, Phone (WhatsApp), and Cash Payment toggle (defaults to `true` / checked, because walk-in reception is predominantly cash).
|
||||||
|
- **When** submitted, the client sends `POST /rosters/quick-checkin` with Mode 2 payload:
|
||||||
|
`{"service_id": "<id>", "scheduled_at": "<iso>", "client_name": "...", "client_phone": "...", "paid_cash": true}`.
|
||||||
|
- **And** upon HTTP 200, the modal closes, the attendee appears in the list as `ASISTIÓ` and `PAGADO`, and both `occupied_count` and `attended_count` increment by 1.
|
||||||
|
- **And** the modal submit button disables while in flight to prevent accidental double-click duplicate registrations.
|
||||||
|
|
||||||
|
### `AC-6`: Resilient Error Handling & Retry
|
||||||
|
- **Given** an error state (failed roster fetch or interrupted check-in),
|
||||||
|
- **Then** the UI exposes an actionable retry path without clearing existing form data or falsely marking attendees present.
|
||||||
|
|
||||||
|
### `AC-7`: Mobile Ergonomics & Keyboard Accessibility
|
||||||
|
- All interactive controls (Check-in buttons, Cash toggles, Walk-in trigger, Modal inputs) must have touch targets of at least **44x44px**.
|
||||||
|
- Roster rows must render cleanly at **375px** viewport width without horizontal scroll overflow.
|
||||||
|
- All interactive controls must support sequential keyboard focus (`Tab` / `Shift+Tab`) with visible `:focus-visible` outlines.
|
||||||
|
- Toast feedback must announce to assistive technology via `role="status"` and `aria-live="polite"`.
|
||||||
|
|
||||||
|
---
|
||||||
|
## 5. Navigation & Architectural Conventions
|
||||||
|
|
||||||
|
1. **Tab Identifier**: `rosters`
|
||||||
|
2. **URL Hash**: `#rosters`
|
||||||
|
3. **Navigation Label**: "Talleres"
|
||||||
|
4. **Header Integration**: Integrated into `OperatorDashboardApp.renderShell()` in `src/main.ts` alongside `#queue`, `#agenda`, `#clients`, and `#all`.
|
||||||
|
5. **Cash Toggle Default**: In the walk-in modal, the "Cobro en efectivo recibido" toggle defaults to **checked (`true`)**. *Rationale:* In-person workshop walk-ins overwhelmingly settle entrance fees in cash at reception. Operators may uncheck if the client provides immediate SPEI transfer verification.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. API Contract Reference
|
||||||
|
|
||||||
|
The view interacts strictly with existing endpoints defined in `armonia-api`:
|
||||||
|
|
||||||
|
- **Endpoint 1:** `GET /rosters?date_from={YYYY-MM-DD}&date_to={YYYY-MM-DD}&service_id={optional}`
|
||||||
|
- *Response Shape:* `list[RosterSessionRead]` (see `app/schemas/roster.py`).
|
||||||
|
- **Endpoint 2:** `POST /rosters/quick-checkin`
|
||||||
|
- *Mode 1 (Existing Booking):*
|
||||||
|
```json
|
||||||
|
{ "booking_id": "uuid-str", "paid_cash": true, "notes": "Opcional" }
|
||||||
|
```
|
||||||
|
- *Mode 2 (Walk-In):*
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"service_id": "uuid-str",
|
||||||
|
"scheduled_at": "2026-10-25T18:00:00Z",
|
||||||
|
"client_name": "Nombre Cliente",
|
||||||
|
"client_phone": "525512345678",
|
||||||
|
"paid_cash": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- *Response:* `QuickCheckinResponse` (`walk_in: bool`, `attendee: RosterAttendeeRead`).
|
||||||
|
- *Conflict Behavior:* HTTP 409 Conflict if attendee already completed or session at max capacity.
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
role: verification-packet
|
||||||
|
status: draft
|
||||||
|
project: armonia-dashboard
|
||||||
|
feature: workshop-roster-checkin
|
||||||
|
date: 2026-10-25
|
||||||
|
tags: [qa, verification-packet, test-data, blind-testing]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Verification Packet: Group Workshop Roster Quick Check-in
|
||||||
|
|
||||||
|
> **Notice to Independent QA Reviewer:** This packet contains **all** instructions, test personas, and expected observable criteria needed to verify the feature. You must evaluate the running application *without* inspecting the pull request discussion, implementation source code, or the implementer's self-audit.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Frozen Environment & Runtime Configuration
|
||||||
|
|
||||||
|
Prior to executing test scenarios, verify that both services are running on the specified commits:
|
||||||
|
|
||||||
|
| Component | Target Directory | Verified Commit Hash | Start Command | Active Port |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **Backend API** | `armonia/armonia-api` | `d9c86e27d926bab3287857ccc9b53ec4fbcec91b` | `DATABASE_URL=file:test_armonia.db uv run python -m uvicorn app.main:app --port 8000` | `http://localhost:8000` |
|
||||||
|
| **Frontend UI** | `armonia/armonia-dashboard` | PR Branch (`feat/anne/workshop-roster`) | `pnpm exec vp dev --port 5173` | `http://localhost:5173` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Tested & Verified Test Database Seed Script with Preflight Assertions
|
||||||
|
|
||||||
|
Run this command inside `armonia-api` using `uv run python`. It creates a clean disposable SQLite database (`test_armonia.db`), initializes default services, seeds the exact test records required for today's date, and **formally asserts all four preflight conditions** before completing:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/kiskaadee/Projects/active/armonia/armonia-api && uv run python -c "
|
||||||
|
import os, asyncio
|
||||||
|
from datetime import datetime, UTC
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# Deterministic absolute path anchoring
|
||||||
|
abs_db_path = (Path.cwd() / 'test_armonia.db').resolve()
|
||||||
|
assert abs_db_path.name.startswith('test_') and abs_db_path.name != 'local.db', 'Safety failure: refusal to touch non-test database'
|
||||||
|
if abs_db_path.exists():
|
||||||
|
abs_db_path.unlink()
|
||||||
|
|
||||||
|
os.environ['DATABASE_URL'] = f'file:{abs_db_path}'
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
settings.database_url = f'file:{abs_db_path}'
|
||||||
|
from app.db.init_db import init_schema_and_seed
|
||||||
|
from app.db.database import get_db
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from app.main import app
|
||||||
|
from app.core.auth import create_session_token
|
||||||
|
|
||||||
|
async def seed_and_verify():
|
||||||
|
# 1. Initialize schema and default services
|
||||||
|
await init_schema_and_seed()
|
||||||
|
|
||||||
|
async with get_db() as client:
|
||||||
|
# Preflight 1: Assert service exists with expected capacity of 15
|
||||||
|
res = await client.execute('SELECT id, name, price_mxn, max_capacity FROM services WHERE slug = \"circulo-cacao-presencial\" LIMIT 1;')
|
||||||
|
assert res.rows, 'Preflight 1 Failed: circulo-cacao-presencial service not found!'
|
||||||
|
cacao_id, cacao_name, price_mxn, max_capacity = res.rows[0]
|
||||||
|
assert max_capacity == 15, f'Preflight 1 Failed: Expected capacity 15, got {max_capacity}'
|
||||||
|
|
||||||
|
# Preflight 2: Calculate today's session instant at 18:00
|
||||||
|
tz = ZoneInfo(settings.business_timezone)
|
||||||
|
today = datetime.now(tz).date()
|
||||||
|
today_str = today.isoformat()
|
||||||
|
session_dt = datetime(today.year, today.month, today.day, 18, 0, 0, tzinfo=tz).astimezone(UTC).isoformat()
|
||||||
|
now = datetime.now(UTC).isoformat()
|
||||||
|
|
||||||
|
# Insert Elena Gómez (Prepaid SPEI: RESERVED + ACKNOWLEDGED)
|
||||||
|
client_elena = 'c1111111-1111-1111-1111-111111111111'
|
||||||
|
booking_elena = 'b1111111-1111-1111-1111-111111111111'
|
||||||
|
await client.execute('INSERT OR REPLACE INTO clients (id, full_name, phone_whatsapp, email) VALUES (?, ?, ?, ?);',
|
||||||
|
[client_elena, 'Elena Gómez', '525511112222', 'elena@example.com'])
|
||||||
|
await client.execute('''
|
||||||
|
INSERT OR REPLACE INTO bookings (
|
||||||
|
id, booking_code, service_id, client_id, scheduled_at, duration_minutes, buffer_minutes,
|
||||||
|
booking_status, payment_arrangement, payment_status, amount_mxn, created_at
|
||||||
|
) VALUES (?, ?, ?, ?, ?, 120, 0, 'RESERVED', 'PREPAID_DEFAULT', 'ACKNOWLEDGED', ?, ?);
|
||||||
|
''', [booking_elena, 'ADS-1001', cacao_id, client_elena, session_dt, price_mxn, now])
|
||||||
|
|
||||||
|
# Insert Carlos Méndez (Unpaid: RESERVED + AWAITING_ACKNOWLEDGMENT)
|
||||||
|
client_carlos = 'c2222222-2222-2222-2222-222222222222'
|
||||||
|
booking_carlos = 'b2222222-2222-2222-2222-222222222222'
|
||||||
|
await client.execute('INSERT OR REPLACE INTO clients (id, full_name, phone_whatsapp, email) VALUES (?, ?, ?, ?);',
|
||||||
|
[client_carlos, 'Carlos Méndez', '525533334444', 'carlos@example.com'])
|
||||||
|
await client.execute('''
|
||||||
|
INSERT OR REPLACE INTO bookings (
|
||||||
|
id, booking_code, service_id, client_id, scheduled_at, duration_minutes, buffer_minutes,
|
||||||
|
booking_status, payment_arrangement, payment_status, amount_mxn, created_at
|
||||||
|
) VALUES (?, ?, ?, ?, ?, 120, 0, 'RESERVED', 'PREPAID_DEFAULT', 'AWAITING_ACKNOWLEDGMENT', ?, ?);
|
||||||
|
''', [booking_carlos, 'ADS-1002', cacao_id, client_carlos, session_dt, price_mxn, now])
|
||||||
|
|
||||||
|
# Preflight 3: Endpoint level validation (assert endpoint returns exact expected session & attendees)
|
||||||
|
tc = TestClient(app)
|
||||||
|
headers = {'Authorization': f'Bearer {create_session_token(\"asistente@armoniadelser.mx\")}'}
|
||||||
|
r = tc.get(f'/rosters?date_from={today_str}&date_to={today_str}', headers=headers)
|
||||||
|
assert r.status_code == 200, f'Preflight 3 Failed: GET /rosters returned {r.status_code}'
|
||||||
|
data = r.json()
|
||||||
|
assert len(data) == 1, f'Preflight 3 Failed: Expected 1 session, got {len(data)}'
|
||||||
|
sess = data[0]
|
||||||
|
assert sess['occupied_count'] == 2 and sess['attended_count'] == 0, 'Preflight 3 Failed: Initial counts mismatch'
|
||||||
|
codes = {att['booking_code'] for att in sess['attendees']}
|
||||||
|
assert codes == {'ADS-1001', 'ADS-1002'}, f'Preflight 3 Failed: Missing expected codes {codes}'
|
||||||
|
|
||||||
|
# Preflight 4: File existence & non-empty database target
|
||||||
|
assert abs_db_path.exists() and abs_db_path.stat().st_size > 0, 'Preflight 4 Failed: Database file missing or empty'
|
||||||
|
|
||||||
|
print('✅ Preflight assertions passed: 100% verified test database ready at', abs_db_path)
|
||||||
|
|
||||||
|
asyncio.run(seed_and_verify())
|
||||||
|
"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Pre-Configured Test Attendee Personas
|
||||||
|
|
||||||
|
| Attendee Persona | Initial Persisted State | Expected Initial UI Rendering | Expected Post-Action State |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Elena Gómez** (`ADS-1001`) | `booking_status: "RESERVED"`, `payment_status: "ACKNOWLEDGED"`, `attended: false` | Badge: `REGISTRADO`<br/>Badge: `PAGADO` (Green)<br/>Action: "Registrar Asistencia" | After check-in: Badge updates to `ASISTIÓ`. Counter increments to `1 presente`. |
|
||||||
|
| **Carlos Méndez** (`ADS-1002`) | `booking_status: "RESERVED"`, `payment_status: "AWAITING_ACKNOWLEDGMENT"`, `attended: false` | Badge: `REGISTRADO`<br/>Badge: `PENDIENTE` (Amber)<br/>Action: Check-in + "Cobro efectivo" | After cash check-in: Badge updates to `ASISTIÓ` AND `PAGADO`. Counter increments. |
|
||||||
|
| **Walk-in: Lucía Vega** | Not in database initially | Not present in list | After registration: Appears in list as `ASISTIÓ` and `PAGADO`. Occupancy becomes `3 / 15`. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Test Execution Scenarios & Concrete Pass/Fail Criteria
|
||||||
|
|
||||||
|
### Scenario 1: Navigation, Tab Hash & Capacity Overview (`AC-1`)
|
||||||
|
1. Open `http://localhost:5173` in a desktop browser.
|
||||||
|
2. Click the "Talleres" navigation button in the top navigation bar.
|
||||||
|
3. **Pass Criteria:**
|
||||||
|
- [ ] URL updates to `http://localhost:5173/#rosters`.
|
||||||
|
- [ ] "Talleres" tab button reflects active state (`aria-selected="true"`).
|
||||||
|
- [ ] Session card for "Círculo de Cacao (Presencial)" renders with time 18:00.
|
||||||
|
- [ ] Capacity counter displays exactly: `Ocupación: 2 / 15 (0 presentes)`.
|
||||||
|
|
||||||
|
### Scenario 2: Attendee Roster Display & Status Badges (`AC-2`)
|
||||||
|
1. Inspect the attendee table/list for the active workshop.
|
||||||
|
2. **Pass Criteria:**
|
||||||
|
- [ ] Elena Gómez is listed with booking code `ADS-1001`, status `REGISTRADO`, and payment pill `PAGADO`.
|
||||||
|
- [ ] Carlos Méndez is listed with booking code `ADS-1002`, status `REGISTRADO`, and payment pill `PENDIENTE`.
|
||||||
|
- [ ] Both rows display a clickable WhatsApp link (`wa.me/525511112222` and `wa.me/525533334444`).
|
||||||
|
|
||||||
|
### Scenario 3: Pre-paid Attendee Check-in & Persistence Verification (`AC-3`)
|
||||||
|
1. On Elena Gómez's row (`ADS-1001`), tap "Registrar Asistencia".
|
||||||
|
2. **Pass Criteria (UI & Persistence):**
|
||||||
|
- [ ] Network inspector shows `POST /rosters/quick-checkin` returned HTTP 200 with payload `{"booking_id": "...", "paid_cash": false}`.
|
||||||
|
- [ ] Elena's status badge updates from `REGISTRADO` to `ASISTIÓ`.
|
||||||
|
- [ ] Capacity summary updates to `Ocupación: 2 / 15 (1 presentes)`.
|
||||||
|
- [ ] An accessible toast announces: *"Asistencia registrada con éxito."*
|
||||||
|
- [ ] **Persistence Proof:** Refresh the browser page (`F5`). Upon reload, Elena still renders as `ASISTIÓ` and capacity remains `1 presente`.
|
||||||
|
|
||||||
|
### Scenario 4: Cash Check-in & Payment Status Transition (`AC-4`)
|
||||||
|
1. On Carlos Méndez's row (`ADS-1002`), trigger check-in with the "Cobro en efectivo recibido" checkbox checked.
|
||||||
|
2. **Pass Criteria (UI & Persistence):**
|
||||||
|
- [ ] Network inspector shows `POST /rosters/quick-checkin` returned HTTP 200 with `paid_cash: true`.
|
||||||
|
- [ ] Carlos's status badge updates to `ASISTIÓ`.
|
||||||
|
- [ ] Carlos's payment pill transitions from `PENDIENTE` to `PAGADO`.
|
||||||
|
- [ ] Capacity summary updates to `Ocupación: 2 / 15 (2 presentes)`.
|
||||||
|
- [ ] **Persistence Proof:** Refresh the browser page (`F5`). Carlos renders with both `ASISTIÓ` and `PAGADO`.
|
||||||
|
|
||||||
|
### Scenario 5: Walk-In Registration & Double-Submission Prevention (`AC-5`)
|
||||||
|
1. Click the "+ Registrar Asistente Sin Cita" button.
|
||||||
|
2. In the modal:
|
||||||
|
- Full Name: `Lucía Vega`
|
||||||
|
- Phone: `525598765432`
|
||||||
|
- Cash toggle: confirm it defaults to **checked (`true`)**.
|
||||||
|
3. **Double-Submission Test**: Rapidly click "Registrar y Marcar Asistencia" twice in succession.
|
||||||
|
4. **Pass Criteria:**
|
||||||
|
- [ ] Submit button disables immediately while the request is in flight.
|
||||||
|
- [ ] Exactly **one** walk-in record is created (network inspector shows only one successful registration; second click is ignored or blocked).
|
||||||
|
- [ ] Modal closes upon HTTP 200.
|
||||||
|
- [ ] Lucía Vega appears in the active attendee list with `ASISTIÓ` and `PAGADO`.
|
||||||
|
- [ ] Capacity counter updates to exactly `Ocupación: 3 / 15 (3 presentes)` (NOT `4 / 15`).
|
||||||
|
- [ ] **Persistence Proof:** Refresh the browser (`F5`). Exactly one Lucía Vega record remains persisted in the roster.
|
||||||
|
|
||||||
|
### Scenario 6: 409 Conflict Disambiguation & Reconciliation
|
||||||
|
1. **Case 6A (Already-Checked-In Idempotency)**: Trigger a duplicate check-in request via network replay or rapid re-tap for an already checked-in attendee (`ADS-1001`).
|
||||||
|
- **Pass Criteria:**
|
||||||
|
- [ ] Backend returns `HTTP 409 Conflict` (`"This attendee has already checked in."`).
|
||||||
|
- [ ] UI catches the 409, reconciles state, displays informative feedback (*"El asistente ya contaba con asistencia registrada"*), and ensures row reflects `ASISTIÓ` without unhandled application crash.
|
||||||
|
2. **Case 6B (Capacity Reached Conflict)**: When submitting a walk-in to a session at max capacity:
|
||||||
|
- **Pass Criteria:**
|
||||||
|
- [ ] Backend returns `HTTP 409 Conflict` (`"El taller ha alcanzado su cupo máximo"`).
|
||||||
|
- [ ] UI displays explicit capacity error alert; modal form data is preserved; row is **not** added to list.
|
||||||
|
|
||||||
|
### Scenario 7: Failed Roster Fetch & Actionable Retry (`AC-6`)
|
||||||
|
1. Temporarily stop the backend API process (`Ctrl+C` on uvicorn).
|
||||||
|
2. Switch dates or refresh the `#rosters` view.
|
||||||
|
3. **Pass Criteria:**
|
||||||
|
- [ ] Error banner renders: *"No se pudieron cargar los talleres. Verifica tu conexión."*
|
||||||
|
- [ ] A visible "Reintentar" button is displayed.
|
||||||
|
4. Restart the backend API process.
|
||||||
|
5. Click "Reintentar".
|
||||||
|
6. **Pass Criteria:**
|
||||||
|
- [ ] Roster reloads successfully without needing a browser reload.
|
||||||
|
|
||||||
|
### Scenario 8: Mobile Ergonomics & Accessibility Tree (`AC-7`)
|
||||||
|
1. Switch browser DevTools to Mobile Emulation: **375 x 812 px** (iPhone SE/X).
|
||||||
|
2. **Pass Criteria:**
|
||||||
|
- [ ] Zero horizontal scroll overflow on the table/cards.
|
||||||
|
- [ ] All check-in buttons, toggles, and modal inputs have minimum touch bounding boxes of **44 x 44 px**.
|
||||||
|
3. Navigate the view using only the keyboard (`Tab` and `Shift+Tab`).
|
||||||
|
4. **Pass Criteria:**
|
||||||
|
- [ ] Focus indicator is visibly highlighted on every active button and input.
|
||||||
|
- [ ] Toast notification container possesses `role="status"` and `aria-live="polite"`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Evidence Capture & Scorecard Deliverable
|
||||||
|
|
||||||
|
The QA Specialist must produce `qa-evidence-scorecard.md` containing:
|
||||||
|
1. Formal table checking every criterion (`AC-1` to `AC-7`, Scenarios 1 to 8) with verdict: `PASS`, `FAIL`, or `BLOCKED`.
|
||||||
|
2. Captured screenshots attached:
|
||||||
|
- Desktop initial roster view.
|
||||||
|
- Mobile 375px view showing touch targets.
|
||||||
|
- Post-check-in state showing updated counter.
|
||||||
|
- Walk-in modal open state.
|
||||||
|
3. Browser console log confirming zero uncaught JavaScript exceptions.
|
||||||
|
4. If any test fails, record: Exact visual element, HTTP status, and response JSON payload.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Reset & Cleanup Procedure
|
||||||
|
|
||||||
|
To restore the test environment between verification passes:
|
||||||
|
```bash
|
||||||
|
# 1. Stop backend API (Ctrl+C)
|
||||||
|
# 2. Delete test database file
|
||||||
|
rm -f /home/kiskaadee/Projects/active/armonia/armonia-api/test_armonia.db
|
||||||
|
# 3. Re-run the seed script from Section 2
|
||||||
|
# 4. Restart backend API
|
||||||
|
```
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
---
|
||||||
|
type: plan
|
||||||
|
status: active
|
||||||
|
project: skills
|
||||||
|
date: 2026-10-24
|
||||||
|
tags: [skills, agent-architecture, frontend-pilot, anne-droid, qa, armonia-del-ser]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Pre-Experiment Baseline: Armonia Frontend Collaboration Pilot
|
||||||
|
|
||||||
|
> **Status:** Active Pre-Experiment Snapshot
|
||||||
|
> **Target System:** `armonia-dashboard` (Operator Control Surface)
|
||||||
|
> **Companion Repositories:** `armonia-api` (Backend), `armonia-del-ser/.profile` (Planning & Governance)
|
||||||
|
> **Inspection Date:** 2026-10-24
|
||||||
|
> **Epistemic Role:** Durable record of knowledge, hypotheses, repository baselines, and experimental protocols **prior** to running the frontend collaboration pilot. This is not a retrospective, an implementation plan for `rtt-agency`, or a declaration of validated results.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Baseline Manifest
|
||||||
|
|
||||||
|
The following Git snapshots establish the verifiable repository state at the moment of inspection prior to any pilot execution:
|
||||||
|
|
||||||
|
| Repository | Current Branch | Full Commit Hash | Remote URL (Gitea) | Primary Relevance | Status / Evidence |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **`armonia-dashboard`** | `main` | [`00b59182ac5c776879b7640e77eb6df6f3b085e9`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/00b59182ac5c776879b7640e77eb6df6f3b085e9) | `ssh://git@gitea.roadtotech.me:2223/armonia-del-ser/armonia-dashboard.git` | Target frontend application for the pilot implementation. | **Verified** (Clean tree, PR #8 merged) |
|
||||||
|
| **`armonia-api`** | `main` | [`d9c86e27d926bab3287857ccc9b53ec4fbcec91b`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b) | `ssh://git@gitea.roadtotech.me:2223/armonia-del-ser/armonia-api.git` | Authoritative backend service; provides API contracts and test fixtures. | **Verified** (Clean tree, M2 completed) |
|
||||||
|
| **`.profile` (Workspace Root)** | `main` | [`89e3cffc8fc43ecb2ca5a05b6721f7bdbd75d3e8`](https://gitea.roadtotech.me/armonia-del-ser/.profile/commit/89e3cffc8fc43ecb2ca5a05b6721f7bdbd75d3e8) | `ssh://git@gitea.roadtotech.me:2223/armonia-del-ser/.profile.git` | Single Source of Truth for system roadmap, `todo.txt`, and cross-repo governance. | **Verified** (Clean tree, active SSOT) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Problem Statement & Historical Context
|
||||||
|
|
||||||
|
### 1.1 The Armonia Workflow-Completeness Breakdown
|
||||||
|
The motivation for this pilot originated from a concrete failure in the initial delivery of the Armonia operator dashboard:
|
||||||
|
|
||||||
|
- **Original Scope**: Milestone M4 was defined in Gitea issue [`armonia-dashboard#1`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/issues/1) (*"M4: Mobile-First Admin Dashboard for Jasmin & Assistant"*). It requested operational views for booking reviews, 48-hour pending payment follow-ups, payment acknowledgments, delayed-payment authorizations, and package/roster controls.
|
||||||
|
- **Implementation Sequence**: Anne Droid was delegated the frontend implementation under her existing persona instructions (`profile/agents/anne-droid.md`). In commit [`4e50f7c58606`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/4e50f7c58606709dbc9e95e7ad557869fb4dea78) (merged via PR [#4](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/pulls/4)), Anne scaffolded the dashboard with `FollowUpQueue.ts`, `PaymentModal.ts`, `DailyAgenda.ts`, and `AllBookings.ts`.
|
||||||
|
- **The Observed Defect**: While the delivered code was modular, typed, accessible, and tested with passing unit tests, the dashboard was **operationally incomplete**: an operator had no capability to create new client appointments from the interface. Furthermore, the workshop roster and package tracker were omitted.
|
||||||
|
- **The Corrective Rework**: The missing appointment-creation workflow had to be addressed in subsequent rework across separate issues ([`armonia-dashboard#6`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/issues/6) and [`armonia-dashboard#7`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/issues/7)), merged in PR [#8](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/pulls/8) ([`7f56fe019a0a`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/7f56fe019a0a0be96ffeb999e5f15549880816a7)).
|
||||||
|
- **Causal Interpretation (Inferred Hypothesis)**: The working explanation is that Anne's self-review procedure evaluated visual presence, component rendering, and isolated unit tests rather than structural workflow completeness against explicit acceptance criteria. Because existing views looked aesthetically sound and passed local unit checks, Anne concluded the task was complete. This diagnosis is plausible, but remains an *inference* to be tested by the pilot's interventions rather than an established historical fact.
|
||||||
|
|
||||||
|
### 1.2 Epistemic Label
|
||||||
|
**Verified (Observed Defect & Rework Chain)**: The commit messages, issue descriptions, PR diffs, and roadmap entries confirm the omission and subsequent rework.
|
||||||
|
**Inferred (Causal Diagnosis)**: The claim that the omission was caused specifically by a lack of requirement-informed workflow verification in Anne's review protocol is an inference to be tested, not a proven historical fact.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Current Technical State & Candidate Deliverable
|
||||||
|
|
||||||
|
### 2.1 Candidate Deliverable: Group Workshop Roster Quick Check-in
|
||||||
|
To test the refined collaboration workflow, the candidate deliverable must represent a real, pending, bounded operational journey:
|
||||||
|
- **Roadmap Position**: In [`ROADMAP.md#L84`](https://gitea.roadtotech.me/armonia-del-ser/.profile/src/commit/89e3cffc8fc43ecb2ca5a05b6721f7bdbd75d3e8/ROADMAP.md#L84), Milestone M4 retains one remaining unchecked item:
|
||||||
|
> `- [ ] Multi-session package counter ('8 de 10') & Group Workshop Roster check-in view.`
|
||||||
|
- **Backend API Readiness**: The backend capabilities were implemented in Milestone M2 ([`armonia-api#6`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/issues/6)) and are active on `armonia-api/main` ([`d9c86e27d926`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b)):
|
||||||
|
1. `GET /rosters` ([`app/routers/rosters.py#L36-L150`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/src/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b/app/routers/rosters.py#L36-L150)): Queries group sessions within `[date_from, date_to]`, grouping bookings by session instant, returning attendees and capacity metrics (`RosterSessionRead`).
|
||||||
|
2. `POST /rosters/quick-checkin` ([`app/routers/rosters.py#L153-L250`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/src/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b/app/routers/rosters.py#L153-L250)): Supports two operational modes:
|
||||||
|
- *Mode 1 (Existing Booking)*: Marks attendee `COMPLETED` and optionally records a cash payment.
|
||||||
|
- *Mode 2 (Walk-In)*: Directly registers and checks in an unregistered walk-in attendee.
|
||||||
|
- **Backend Test Coverage**: Fully verified by integration tests in [`armonia-api/tests/test_rosters.py`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/src/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b/tests/test_rosters.py) using the `circulo-cacao-presencial` test fixture.
|
||||||
|
- **Frontend Baseline**: In `armonia-dashboard/src/`, grep inspection confirms **zero** roster code currently exists. The view is completely pending.
|
||||||
|
|
||||||
|
### 2.2 Epistemic Label
|
||||||
|
**Verified**: The backend API exists and is tested; the frontend capability is pending; the task represents authentic unfinished scope from M4.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Pilot Rationale & Scoping Boundaries
|
||||||
|
|
||||||
|
### 3.1 Why This Pilot Is Being Considered
|
||||||
|
The pilot explores whether introducing structured, pre-implementation specification contracts and requirement-informed, code-blind verification prevents omissions while preserving frontend engineering velocity.
|
||||||
|
|
||||||
|
### 3.2 Explicit Inclusions (In Scope)
|
||||||
|
- Formulating an explicit **Project Collaboration Plan** for this deliverable.
|
||||||
|
- Formulating a two-part **Specification Contract**: Requirements & Acceptance Criteria distinct from UX Flows & Interaction States.
|
||||||
|
- Assembling a reproducible **Verification Packet** (test seeds, initial state, expected outcomes).
|
||||||
|
- Delegating implementation to **Anne Droid** in an isolated git worktree with an explicit change/escalation protocol.
|
||||||
|
- Executing an independent QA review blind to Anne's source code and PR narrative.
|
||||||
|
- Evaluating the process overhead, traceability, and defect detection rate.
|
||||||
|
|
||||||
|
### 3.3 Explicit Exclusions (Out of Scope)
|
||||||
|
- Creating the permanent `rtt-agency` repository or extracting shared personas.
|
||||||
|
- Modifying project governance or runtime adapters in `~/.gemini/config/`.
|
||||||
|
- Refactoring existing dashboard views (`DailyAgenda`, `FollowUpQueue`, `PaymentModal`).
|
||||||
|
- Modifying backend endpoints in `armonia-api`.
|
||||||
|
- Deciding whether 5 independent agents are permanently superior to 1 agent using disciplined stages.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Hypotheses Under Investigation & Epistemic Uncertainties
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ The Pilot Hypotheses │
|
||||||
|
├─────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ Hypothesis 1: Specification Completeness Reduces Workflow Omissions │
|
||||||
|
│ An explicit, owner-approved specification of required operator │
|
||||||
|
│ workflows and observable acceptance criteria reduces ambiguity and │
|
||||||
|
│ prevents essential capabilities from being omitted during coding. │
|
||||||
|
│ (Separating Requirements from UX is an evaluated design choice). │
|
||||||
|
├─────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ Hypothesis 2: Bounded Engineering Autonomy Is Workable in Practice │
|
||||||
|
│ Anne can exercise local design judgment (components, state handling, │
|
||||||
|
│ ergonomics) without silently drifting into product scope changes or │
|
||||||
|
│ unauthorized architectural commitments. │
|
||||||
|
├─────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ Hypothesis 3: Implementation-Blind QA Detects Incremental Defects │
|
||||||
|
│ A reviewer who evaluates the running build using a Verification Packet│
|
||||||
|
│ — blind to implementation code and self-audit claims — detects defects│
|
||||||
|
│ and omissions that self-verification misses. │
|
||||||
|
└─────────────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Detailed Hypothesis Profiles
|
||||||
|
|
||||||
|
#### Hypothesis 1: Specification Completeness
|
||||||
|
- **Evidence Motivating It**: In M4, high-level view names failed to convey the essential operator journeys, causing the appointment-creation action to be missed.
|
||||||
|
- **Narrowed Claim**: An explicit, owner-approved specification of required operator workflows and observable acceptance criteria reduces ambiguity and prevents essential capabilities from being omitted during implementation.
|
||||||
|
- **Evaluated Design Choice**: The separation between Requirements (what/why + AC) and UX Design (how/flows/states) is introduced as an architectural design choice. The pilot observes whether this separation adds tangible clarity or unnecessary overhead, without assuming persona separation is mandatory.
|
||||||
|
- **Observation That Would Strengthen**: Anne delivers all required workflows without halting for basic scope clarification or omitting actions.
|
||||||
|
- **Observation That Would Weaken**: Anne still misses essential actions despite the contract, or the specification requires extensive rework before coding begins.
|
||||||
|
- **Limitation**: A single pilot cannot prove that separate personas are necessary to author the specification; it only tests the value of the explicit specification contract.
|
||||||
|
|
||||||
|
#### Hypothesis 2: Bounded Engineering Autonomy
|
||||||
|
- **Evidence Motivating It**: Current Anne instructions permit branch and PR autonomy, but lack clear rules on when API friction must be escalated versus worked around.
|
||||||
|
- **What Remains Unknown**: Whether Anne will halt unnecessarily on routine technical choices or attempt to work around backend contract gaps without reporting them.
|
||||||
|
- **Observation That Would Strengthen**: Anne raises explicit contract friction notices for backend ambiguities while resolving local component details independently.
|
||||||
|
- **Observation That Would Weaken**: Anne silently mocks missing API fields or stops work to ask for minor styling guidance.
|
||||||
|
- **Limitation**: Autonomy boundaries tested on this feature may not generalize to unfamiliar tech stacks.
|
||||||
|
|
||||||
|
#### Hypothesis 3: Implementation-Blind QA
|
||||||
|
- **Evidence Motivating It**: The `awwwards` skill demonstrates that an agent who knows the implementation plan evaluates intent rather than rendered reality.
|
||||||
|
- **Methodological Requirement (Falsifiability)**: To ensure valid comparison, Anne's self-audit (her own AC evaluation and visual evidence) must be captured and frozen *before* independent QA executes.
|
||||||
|
- **Evaluated Outcomes**:
|
||||||
|
1. *QA finds confirmed defects missed by Anne*: Evidence that independent verification contributed incremental detection value.
|
||||||
|
2. *QA confirms the same findings Anne identified*: Validates test reproducibility, but does not demonstrate incremental defect detection.
|
||||||
|
3. *QA reports false positives or blocked tests*: Reflects on the verification setup/tooling, not necessarily the implementation.
|
||||||
|
- **Observation That Would Strengthen**: Independent QA identifies a confirmed functional bug, broken state transition, or accessibility flaw that Anne’s self-audit passed.
|
||||||
|
- **Observation That Would Weaken**: Independent QA fails due to missing context that was obvious in the code, or produces high false-positive defect reports.
|
||||||
|
- **Limitation**: A pilot where QA finds zero defects is inconclusive regarding the comparative advantage of independence; it does not prove independent QA is unnecessary.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Proposed Pilot Protocol & Handoff Contracts
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ Proposed Pilot Protocol Flow │
|
||||||
|
│ │
|
||||||
|
│ Phase 1: Project Collaboration Plan & Baseline Snapshot │
|
||||||
|
│ • Input: Verified repository state, ROADMAP.md, and issue #1. │
|
||||||
|
│ • Output: Active roster, handoff definitions, and escalation paths. │
|
||||||
|
│ • Gate: Human Project Owner approves the operating model. │
|
||||||
|
│ │ │
|
||||||
|
│ ▼ │
|
||||||
|
│ Phase 2: Contract Formulation & Verification Packet │
|
||||||
|
│ • Input: API schema, workshop operational goals. │
|
||||||
|
│ • Output: docs/specs/workshop-roster.md + Verification Packet. │
|
||||||
|
│ • Gate: Human Project Owner approves the Acceptance Criteria (AC). │
|
||||||
|
│ │ │
|
||||||
|
│ ▼ │
|
||||||
|
│ Phase 3: Isolated Implementation & Frozen Self-Audit (Anne Droid) │
|
||||||
|
│ • Input: Approved specification contract + API contracts. │
|
||||||
|
│ • Workspace: Isolated worktree ../armonia-dashboard-anne-roster │
|
||||||
|
│ • Output: feat/anne/workshop-roster, code, unit tests, PR on Gitea. │
|
||||||
|
│ • Invariant: Anne executes and FROZES her own AC evaluation & visual │
|
||||||
|
│ evidence before Independent QA begins. │
|
||||||
|
│ • Rule: Escalate contract friction; no silent scope modification. │
|
||||||
|
│ │ │
|
||||||
|
│ ▼ │
|
||||||
|
│ Phase 4: Independent QA Pass (QA Specialist / Subagent) │
|
||||||
|
│ • Input: Running URL + Verification Packet (AC + Seed Data). │
|
||||||
|
│ • Blind To: Anne's PR text, source code, and self-audit claims. │
|
||||||
|
│ • Output: Independent Evidence Scorecard (Pass/Fail per AC + shots). │
|
||||||
|
│ │ │
|
||||||
|
│ ▼ │
|
||||||
|
│ Phase 5: Owner Review & Pilot Post-Mortem │
|
||||||
|
│ • Input: PR diff + Anne Frozen Audit + QA Evidence Scorecard. │
|
||||||
|
│ • Evaluation: Adjudicate discrepancies and decide on merge. │
|
||||||
|
│ • Post-Mortem: Evaluate operational metrics, friction, and findings. │
|
||||||
|
└─────────────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.1 The Explicit Escalation & Change Protocol
|
||||||
|
If any stage encounters a blocking condition, work halts and routes strictly according to problem type:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────────────────┬────────────────────────┬─────────────────────────────────────────┐
|
||||||
|
│ Condition Encountered │ Responsible Role │ Required Action │
|
||||||
|
├──────────────────────────────┼────────────────────────┼─────────────────────────────────────────┤
|
||||||
|
│ Contradictory business rule │ Requirements Engineer │ Clarify domain invariant; update ACs. │
|
||||||
|
│ Unworkable interaction flow │ UX Designer │ Revise state transitions or hierarchy. │
|
||||||
|
│ API contract defect / gap │ Backend Owner / Lead │ File structured issue with schema fix. │
|
||||||
|
│ Implementation defect │ Anne Droid │ Fix in worktree and update PR. │
|
||||||
|
│ Ambiguous test criterion │ Requirements + QA │ Update Verification Packet. │
|
||||||
|
│ Scope change / trade-off │ Project Owner (You) │ Explicit human decision required. │
|
||||||
|
└──────────────────────────────┴────────────────────────┴─────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Success Observations & Boundary Limitations
|
||||||
|
|
||||||
|
### 6.1 Required Minimum Outcomes
|
||||||
|
- [ ] Essential operator workflows and acceptance criteria are approved before code is written.
|
||||||
|
- [ ] Anne raises contract friction notices rather than silently resolving missing backend data.
|
||||||
|
- [ ] Anne's self-audit is captured and frozen before independent QA evaluates the running application.
|
||||||
|
- [ ] QA evaluates every acceptance criterion using reproducible evidence (screenshots, console logs, network responses).
|
||||||
|
- [ ] Discrepancies between Anne's self-audit and independent QA findings are explicitly adjudicated.
|
||||||
|
- [ ] Consequential product and architectural decisions remain strictly under Project Owner authority.
|
||||||
|
- [ ] The workflow executes successfully inside the existing NixOS development environment.
|
||||||
|
|
||||||
|
### 6.2 Evaluated Process Observations
|
||||||
|
During and after the pilot, the following operational metrics will be recorded:
|
||||||
|
1. **Ambiguity Resolution Timing**: Count of ambiguities identified before coding (during specification) versus during implementation.
|
||||||
|
2. **Defect Delta & Detection Profile**:
|
||||||
|
- Defect count found by independent QA that Anne's self-audit missed (incremental detection).
|
||||||
|
- Defect count confirmed by both Anne and QA (reproducible verification).
|
||||||
|
- Defect reports that were false positives or blocked tests due to verification environment issues.
|
||||||
|
3. **Return Loops**: Number and root cause of workflow reversions to earlier stages.
|
||||||
|
4. **Owner Interventions**: Number of escalations requiring consequential human decisions.
|
||||||
|
5. **Setup & Tooling Friction**: Material setup failures, devShell library issues, or blocked browser runs.
|
||||||
|
6. **Elapsed Stage Duration**: Rough duration per stage to assess practical overhead.
|
||||||
|
7. **Artifact Utility**: Whether the specification and verification packet remain durable documentation post-merge.
|
||||||
|
8. **Commit Discipline & Decomposition Quality**:
|
||||||
|
- Number of implementation commits and whether each has a clear, reviewable purpose.
|
||||||
|
- Whether each commit is coherent and passes relevant intermediate checks.
|
||||||
|
- Whether reviewers can connect individual commits to specific acceptance criteria.
|
||||||
|
- Whether any defect identified in verification can be localized to a particular increment.
|
||||||
|
- Whether commit discipline added material overhead or encouraged unnecessary fragmentation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Constraints, Preconditions & Deferred Decisions
|
||||||
|
|
||||||
|
### 7.1 Technical & Environmental Constraints
|
||||||
|
- **NixOS Environment**: Playwright and browser automation must execute cleanly within the local Nix devShell (`flake.nix`).
|
||||||
|
- **Gitea Port & Auth**: Remote operations use port `2223` with scoped SSH keys (`anneux` for Anne; `kiskaadee` for Owner).
|
||||||
|
- **Branch Protection**: No direct commits to `main` in `armonia-dashboard`. All work occurs in ephemeral worktrees.
|
||||||
|
|
||||||
|
### 7.2 Explicit Multi-Stage Approval Sequence Before Pilot Execution
|
||||||
|
Committed drafts in the vault establish documentation readiness and version control, not binding project authorization. Formal progression requires three distinct Project Owner approvals:
|
||||||
|
1. **Approval of Operating Model & Scope Boundaries (`COLLABORATION-PLAN.md`)**: Confirms role authorities, scope containment, commit discipline, escalation paths, and decision reservations.
|
||||||
|
2. **Approval of Specification & Verification Contracts (`SPEC-WORKSHOP-ROSTER.md` & `VERIFICATION-PACKET-ROSTER.md`)**: Confirms acceptance criteria, exact API error contracts (409 disambiguation), status mappings, seed data, and pass/fail scenarios.
|
||||||
|
3. **Formal Authorization for Implementation**: Explicit owner greenlight to spawn the isolated worktree (`feat/anne/workshop-roster`) and delegate Phase 3 execution to Anne Droid.
|
||||||
|
|
||||||
|
### 7.3 Deferred Decisions (Explicitly Postponed)
|
||||||
|
- **Repository Architecture**: Whether to create `rtt-agency` or maintain personas within `skills`.
|
||||||
|
- **Persona Packaging**: Whether all 5 roles warrant dedicated personas or should be structured execution stages.
|
||||||
|
- **Automated Verification Standard**: What standard browser test suite should be mandated across all projects.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Evidence Gap Analysis (Audited Limitations)
|
||||||
|
|
||||||
|
During the pre-experiment inspection, the following gaps and limits were identified:
|
||||||
|
1. **Cloudflare Pages Production Parity**: Local testing occurs via `vp dev` / `vp preview`. Behavior under actual Cloudflare Pages edge runtime routing was not tested during baseline inspection.
|
||||||
|
2. **Gitea Issue Detail for Roster**: In `armonia-dashboard#1`, the workshop roster is mentioned in a single summary line without detailed UX wireframes. This confirms that the specification must be authored in Phase 2 before implementation can proceed.
|
||||||
|
3. **Pragmatic Test-Data Setup**: While `armonia-api` lacks a standalone CLI seed script, it possesses existing initialization logic (`init_schema_and_seed()`) and proven integration test helpers (`_book()`). To avoid turning test preparation into an unplanned infrastructure project, the Verification Packet will reuse these existing routines to instantiate a disposable local SQLite test database with known workshop attendees.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Post-Experiment Empirical Postmortem (2026-10-27)
|
||||||
|
|
||||||
|
> **Postmortem Scope:** Recorded after Phase 3 implementation, Phase 4 initial QA, and Phases 4.1–4.2 owner-prompted repair and re-verification cycles, prior to worktree teardown. Sections 1–8 above remain frozen as the pre-experiment snapshot.
|
||||||
|
|
||||||
|
### 9.1 Execution Timeline & Stage Durations
|
||||||
|
|
||||||
|
Timestamps are derived directly from Git commit metadata on `feat/anne/workshop-roster` ([`armonia-dashboard#9`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/pulls/9)) and subagent execution logs. Pre-implementation specification drafting occurred across multiple interactive review sessions; exact human authoring wall-clock time was not instrumented and is marked unavailable.
|
||||||
|
|
||||||
|
| Stage | Window (UTC-5) | Active Duration | Observed Output |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Phase 1 & 2: Contracts & Preflight** | 2026-10-25 to 2026-10-26 09:33 | Multi-session (uninstrumented wall-clock) | Ratified `COLLABORATION-PLAN.md`, `SPEC-WORKSHOP-ROSTER.md`, `VERIFICATION-PACKET-ROSTER.md` in `armonia/docs/pilot/`. |
|
||||||
|
| **Phase 3: Initial Implementation (Anne)** | 2026-10-26 09:36 $\rightarrow$ 09:56 | ~20 min | 5 commits (`0ff27a2` $\rightarrow$ `d672065`), 29 passing unit tests, frozen `docs/evidence/anne-self-audit.md`, PR #9 opened. |
|
||||||
|
| **Phase 4.0: Initial Independent QA** | 2026-10-27 00:06 $\rightarrow$ 00:24 | ~18 min | 8/8 scenarios marked `PASS` (`0 FAIL`, `0 BLOCKED`), 15 screenshots in `armonia/docs/evidence/qa/`, frozen `qa-evidence-scorecard.md`. |
|
||||||
|
| **Phase 5.0: Code-Level Owner Review** | 2026-10-27 07:18 $\rightarrow$ 07:25 | ~7 min | Identified Finding A (`escapeHtml` omission) and Finding B (409 out-of-band counter desync) in Commit 3 (`6ba0bbe`). |
|
||||||
|
| **Repair Loop 1 & Phase 4.1 Retest** | 2026-10-27 07:26 $\rightarrow$ 07:44 | ~18 min | Commit `9191899` (local `+1` counter & `escapeHtml`); QA Test 1 (XSS) `PASS`, Case 2A `PASS`, Case 2B (multi-attendee OOB) `FAIL` (`1 presentes` vs. server `2`). |
|
||||||
|
| **Repair Loop 2 & Phase 4.2 Retest** | 2026-10-27 07:45 $\rightarrow$ 07:52 | ~7 min | Commit `4e1e7f2` (authoritative server refresh on 409); QA Case 2B strict re-verification `PASS` (`2 presentes`, both rows `ASISTIÓ`); 34/34 unit tests passing. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 9.2 Verification Provenance & Defect Ledger
|
||||||
|
|
||||||
|
To distinguish defects caught autonomously by the multi-agent workflow from defects that required human/owner intervention, every technical finding from the pilot is classified by provenance:
|
||||||
|
|
||||||
|
| Finding ID & Description | Detection Source | First Detection Point | Required Intervention | Repair Verification | Outcome |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| **PF-1: Imaginary `bookings.attended` SQL column in draft seed script** | Owner review + Preflight execution | Pre-Phase 3 Contract Preflight | Owner challenged unverified seed claim; preflight run exposed `SQLITE_ERROR`. | Live SQLite seed + external Uvicorn HTTP 200 check | **Confirmed Verification Defect** (Fixed before Phase 3) |
|
||||||
|
| **PF-2: Undefined `db_filename` after path refactor in Verification Packet** | Owner diff review | Pre-Gate 3 Contract Review | Owner identified `NameError` directly in packet diff before Gate 3 authorization. | Seed script re-run (`exit 0`) + HTTP preflight | **Confirmed Verification Defect** (Fixed before Gate 3) |
|
||||||
|
| **PF-3: Missing `escapeHtml()` on dynamic interpolations in `WorkshopRoster.ts`** | Orchestrator / Owner code review | Post-Phase 4.0 PR Diff Inspection | Owner required code-level diff review prior to merge; neither Anne's self-audit nor Phase 4.0 black-box QA caught it. | Unit tests (`tests/roster.test.ts`) + Phase 4.1 Live DOM XSS Walk-in (`scenario_9_xss_sanitization.png`) | **Confirmed Implementation Defect** (Fixed in `9191899`) |
|
||||||
|
| **PF-4: Stale header capacity counter on single out-of-band `409 ALREADY_CHECKED_IN`** | Orchestrator / Owner code review | Post-Phase 4.0 PR Diff Inspection | Spec & Scenario 6A only required row-level `ASISTIÓ` update; code review spotted missing header counter update. | Unit test + Phase 4.1 Live Case 2A (`scenario_6a_regression_single_oob.png`) | **Confirmed Spec & Implementation Gap** (Fixed in `9191899`) |
|
||||||
|
| **PF-5: Multi-attendee out-of-band `409` staleness (local `+1` vs. server truth)** | Owner architectural review | Review of Commit `9191899` | Owner identified that local `+1` fails when $>1$ attendee changed out-of-band and mandated Case 2B live test. | Unit test (`Case 2B`) + Phase 4.2 Live DOM (`scenario_6a_regression_multi_oob_v2.png`) | **Confirmed Architectural Defect** (Fixed in `4e1e7f2`) |
|
||||||
|
| **PF-6: QA rationalization of Case 2B divergence on `9191899`** | Owner / Orchestrator review of QA scorecard | Phase 4.1 Scorecard Review | QA observed `1 presentes` vs. server `2`, but rationalized it as a "targeted reconciliation trade-off" (`PASS`) because the prompt lacked a hard failure threshold. | Re-dispatched in Phase 4.2 with explicit falsifiable assertions (`FAIL` if $\neq 2$) | **Confirmed QA Process Failure Mode** (Corrected in Phase 4.2) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 9.3 Commit Ledger & Fault Localization Assessment (`H4`)
|
||||||
|
|
||||||
|
Final branch history on `feat/anne/workshop-roster` (8 commits):
|
||||||
|
|
||||||
|
1. [`0ff27a2`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/0ff27a2): `feat(roster): define API types and client methods for workshop rosters` (`src/api.ts`, `src/types.ts`, +111 lines)
|
||||||
|
2. [`c09f6c6`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/c09f6c6): `feat(roster): add status badges, capacity formatting, and unit tests` (`WorkshopRoster.ts`, `tests/roster.test.ts`, +166 lines)
|
||||||
|
3. [`6ba0bbe`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/6ba0bbe): `feat(roster): implement session cards, attendee list, and check-in workflows` (`WorkshopRoster.ts`, +789/-1 lines)
|
||||||
|
4. [`191a02d`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/191a02d): `feat(roster): integrate talleres tab in navigation and add responsive styles` (`src/main.ts`, `src/style.css`, +452/-2 lines)
|
||||||
|
5. [`d672065`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/d672065): `docs(roster): record dual-viewport evidence and freeze anne self-audit`
|
||||||
|
6. [`faa2d34`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/faa2d34): `docs(roster): update worktree path reference in self-audit`
|
||||||
|
7. [`9191899`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/9191899): `fix(roster): escape HTML interpolations and sync capacity counter on 409 reconciliation`
|
||||||
|
8. [`4e1e7f2`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/4e1e7f2): `fix(roster): reconcile session state from server on 409 conflict`
|
||||||
|
|
||||||
|
**Evaluation of `H4`:**
|
||||||
|
- **What worked**: Unlike the baseline 1-commit dump (`4e50f7c586`), separating contract types (`0ff27a2`), pure helpers/tests (`c09f6c6`), UI component (`6ba0bbe`), and shell wiring (`191a02d`) made it trivial to verify Scope Containment in `src/main.ts` (+16/-2 lines) and localize both PF-3 and PF-4/PF-5 exclusively to `6ba0bbe`. Furthermore, the repair progression (`9191899` $\rightarrow$ `4e1e7f2`) created an auditable trail of how the 409 reconciliation strategy evolved.
|
||||||
|
- **Limitation observed**: Commit 3 (`6ba0bbe`, +789 lines) bundled session rendering, existing check-in, and the walk-in modal into a single commit. Engineer-owned decomposition prevented micro-management, but future prompts should encourage splitting read/list views from modal/mutation flows (`~200–350` lines per commit).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 9.4 Evaluation of Hypotheses & Process Controls
|
||||||
|
|
||||||
|
1. **`H1` (Specification Completeness)**: **Supported, with a boundary condition.**
|
||||||
|
- Unlike the M4 initial delivery that omitted appointment creation entirely, all required operator workflows (session overview, prepaid check-in, cash check-in, walk-in registration, 409 conflict handling, network retry, mobile ergonomics) were delivered and verified on the first pass.
|
||||||
|
- *Boundary condition*: Where the specification simplified an invariant (stating in Section 2.1 that a 409 duplicate check-in should "update the attendee row to `ASISTIÓ`" rather than "reconcile the session from server state"), both Anne and QA implemented and certified the literal clause, missing the multi-operator counter staleness until owner review (PF-4, PF-5).
|
||||||
|
2. **`H2` (Bounded Engineering Autonomy & Scope Containment)**: **Supported.**
|
||||||
|
- Anne operated inside `.worktrees/armonia-dashboard-anne-roster`, preserved all 17 existing tests, touched only 18 lines in `src/main.ts`, and surfaced the HTTP 409 string-matching constraint in her self-audit rather than inventing mock backend endpoints.
|
||||||
|
3. **`H3` (Independent Black-Box QA)**: **Inconclusive for autonomous defect discovery; high value for execution proof, subject to prompt falsifiability.**
|
||||||
|
- In Phase 4.0, Independent QA scored 8/8 `PASS` (`0` QA-only defects). While this proved that the happy-path and specified error states worked against a live SQLite database, it did **not** catch PF-3 (`escapeHtml` omission) or PF-4/PF-5 (out-of-band counter staleness) because neither adversarial HTML payloads nor multi-attendee out-of-band mutations were in the initial Verification Packet.
|
||||||
|
- Crucially, PF-6 demonstrated that when a QA prompt asks an agent to *observe* behavior without a strict pass/fail invariant, the agent tends to rationalize discrepancies as "architectural trade-offs." Once given a hard falsifiable assertion in Phase 4.2, Independent QA reliably verified the fix.
|
||||||
|
4. **Role of Project Owner Review**: **Decisive.**
|
||||||
|
- All five defects (PF-1 through PF-5) and the QA rationalization flaw (PF-6) were caught through human owner governance and code-level diff review, not by autonomous agent-to-agent handoffs alone. The structured artifacts (`SPEC`, `VERIFICATION-PACKET`, incremental commits) made owner review significantly faster and sharper, but did **not** replace it.
|
||||||
File renamed without changes.
@@ -0,0 +1,120 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: open
|
||||||
|
project: agents
|
||||||
|
date: 2026-10-16
|
||||||
|
tags:
|
||||||
|
- agents
|
||||||
|
- architecture
|
||||||
|
- memory
|
||||||
|
- stigmergy
|
||||||
|
- gitea
|
||||||
|
- coordination
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Discussion: Agent Persistence, Asynchronous Coordination, and Memory Horizons
|
||||||
|
|
||||||
|
## 1. Problem Statement & Historical Context
|
||||||
|
|
||||||
|
Pair-programming with specialized, autonomous subagents (such as Anne Droid, a frontend and UX specialist) initially highlighted a fundamental friction: **agent ephemerality and memory boundary amnesia**.
|
||||||
|
|
||||||
|
While Anne successfully executed branch-level tasks, generated commits under her own Gitea forge identity (`anne-droid`), and opened Pull Requests via the `tea` CLI, her operational lifespan remained bound to individual interactive sessions. Once an execution session terminated or the conversation context was compacted, the agent's intermediate reasoning, active follow-ups, and architectural inquiries evaporated.
|
||||||
|
|
||||||
|
During the `type-hints` frontend integration, the agent drafted architectural inquiries and schema questions regarding backend API endpoints (such as coordinate reporting in AST validation errors). In an interactive session, these inquiries were captured in ephemeral chat transcripts or scratchpads. This posed a central dilemma:
|
||||||
|
* If follow-up questions remain in temporary chat buffers, future agent invocations start from zero, requiring manual reconstruction of history and consuming scarce context tokens.
|
||||||
|
* If questions are committed directly to repository code branches as unorganized notes, they pollute the project's source tree with transient conversational noise.
|
||||||
|
|
||||||
|
The challenge was to design a durable, low-friction mechanism for cross-session continuity and asynchronous coordination that reflects real-world engineering team practices without drowning in cognitive or infrastructural maintenance overhead.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Context & Analysis: Core Dilemmas
|
||||||
|
|
||||||
|
### Biological Stigmergy vs. Human Engineering Parallels
|
||||||
|
|
||||||
|
The problem of ephemeral memory is not unique to language models. Biological systems solve coordination across ephemeral individuals through **stigmergy**: agents modify their external physical environment (e.g. pheromone trails or extracellular matrices), allowing subsequent agents to respond to environmental state rather than requiring direct inter-agent memory transfer.
|
||||||
|
|
||||||
|
Human engineering teams operate under an identical dynamic. Individual engineers experience context switches, sleep cycles, vacations, and project reassignments. Teams prevent collapse not by maintaining infinite shared biological memory, but by externalizing coordination into durable, shared forge artifacts:
|
||||||
|
|
||||||
|
1. **Session-Level Context**: Active terminal buffers, working reasoning, intermediate diffs (lifespan: minutes to hours).
|
||||||
|
2. **Task & Review Level (Actionable Ephemera)**: Pull Request reviews, inline diff comments, and discrete forge issues (lifespan: days to weeks). Once answered or merged, they are closed.
|
||||||
|
3. **Persistent System Documentation**: Architecture Decision Records (ADRs), interface contracts, design tokens, and domain models (lifespan: permanent).
|
||||||
|
4. **Cross-Project Persona & Tastes**: Design system standards, anti-"zombie UI" manifestos, and stack preferences that persist across repositories.
|
||||||
|
|
||||||
|
Conflating these distinct memory horizons causes either severe context bloat (stuffing raw conversational history into prompt context) or repository decay (filling issues with trivial questions or cluttering `docs/` with one-off operational notes).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Evaluated Dilemmas & Rejected Alternatives
|
||||||
|
|
||||||
|
Three architectural models were evaluated to bridge agent memory and asynchronous collaboration:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph PathA["Path A: Forge-Native Stigmergy"]
|
||||||
|
GiteaIssues["Gitea Issues (Actionable follow-ups)"]
|
||||||
|
GiteaPRs["PR Review Threads (Diff critiques)"]
|
||||||
|
RepoDocs["Repo docs/ (Persistent specs)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph PathB["Path B: Dedicated Vault & MCP Memory"]
|
||||||
|
BrainVault["~/Brain Markdown Notes"]
|
||||||
|
MCPServer["MCP Retrieval Server"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph PathC["Path C: Autonomous Homelab Daemon"]
|
||||||
|
Container["Bot Container / Daemon"]
|
||||||
|
Webhooks["Gitea Webhooks (Event loop)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
Human["Human Lead"] <--> PathA
|
||||||
|
Human <--> PathB
|
||||||
|
Human <--> PathC
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option A: Forge-Native Asynchronous Stigmergy (Gitea + `tea` CLI)
|
||||||
|
|
||||||
|
* **Mechanism**: Leverage the existing self-hosted Gitea forge as the single source of truth. Anne reads and creates Gitea Issues and PR comments via the `tea` CLI. Follow-up inquiries are filed as discrete issues with high-threshold criteria, while permanent architectural contracts live in repository `docs/`.
|
||||||
|
* **Trade-off Evaluation**:
|
||||||
|
- *Strengths*: Reuses existing infrastructure with zero added operational cost. Naturally matches human software development workflows. Persists context directly alongside the codebase with clear audit trails.
|
||||||
|
- *Frictions*: Does not provide automated background execution; the human lead still triggers session invocations.
|
||||||
|
|
||||||
|
### Option B: Dedicated Agent Brain & MCP Memory Retrieval
|
||||||
|
|
||||||
|
* **Mechanism**: Maintain dedicated agent journals and project state files within the `~/Brain` knowledge vault, queried dynamically by agents via a custom Model Context Protocol (MCP) server.
|
||||||
|
* **Trade-off Evaluation**:
|
||||||
|
- *Strengths*: Enables cross-repository persona persistence and centralized query capabilities.
|
||||||
|
- *Reasons Set Aside*: Experience revealed that maintaining customized MCP schemas, metadata synchronization, and indexing pipelines introduces significant maintenance drag. Stored notes risk semantic drift whenever code evolves independently of the vault.
|
||||||
|
|
||||||
|
### Option C: The Autonomous Homelab Daemon (Containerized Event-Driven Bot)
|
||||||
|
|
||||||
|
* **Mechanism**: Deploy the agent as a standalone background container or systemd service on the homelab network, listening to Gitea webhooks (e.g. `@anne-droid` mentions, PR review comments) to trigger autonomous worktree checkouts, test runs, and commit responses.
|
||||||
|
* **Trade-off Evaluation**:
|
||||||
|
- *Strengths*: Achieves true asynchronous team collaboration where the agent responds in Gitea without requiring an active IDE pairing session.
|
||||||
|
- *Reasons Parked*: Introduces significant systems complexity (webhook routing, security sandboxing, containerized git permissions) and presents risk of runaway token consumption or infinite execution loops if event boundaries fail.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. What Became Possible After the Epistemic Separation
|
||||||
|
|
||||||
|
By decoupling **actionable one-time inquiries** from **persistent repository documentation**, clear rules for agent communication emerged:
|
||||||
|
|
||||||
|
| Information Horizon | Target Destination | Lifespan & Lifecycle | Threshold Filter |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Persistent Design & System Contracts** | Repository `docs/` or component trees | Permanent; updated via PRs | High-frequency reference: component tokens, UX state machines, API contracts. |
|
||||||
|
| **Actionable Single-Response Tasks** | Gitea Issues (`tea issues create`) | Ephemeral; closed upon resolution | High-bar trigger: breaking contract changes, security/auth boundaries, severe client UX/performance degradation. |
|
||||||
|
| **In-Line Diff Feedback** | PR Review Threads (`tea pulls comment`) | Ephemeral; resolved upon merge | Minor ergonomic notes or line-specific questions tied strictly to active diff. |
|
||||||
|
| **Transient Session Reasoning** | Antigravity ephemeral context | Ephemeral; discarded at turn end | Internal implementation scratchpad and intermediate CLI outputs. |
|
||||||
|
|
||||||
|
This epistemic separation prevents repository issue trackers from degrading into noisy chat logs while ensuring critical interface friction is never lost between sessions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Convergence & Successors
|
||||||
|
|
||||||
|
The exploration converged on:
|
||||||
|
1. **Immediate Execution (Path A)**: Adopting forge-native coordination. Updating Anne Droid's operational contract to establish clear triage criteria for when to create repository documentation versus when to open a Gitea issue.
|
||||||
|
2. **Parking Long-Term Automation (Path C)**: Retaining the autonomous containerized daemon concept as a candidate for future homelab development once forge-native interaction patterns are proven and mature.
|
||||||
|
3. **Successors**:
|
||||||
|
- Updated agent specification in `profile/agents/anne-droid.md`.
|
||||||
|
- Dogfooding issue triage during backend/frontend contract negotiations in `type-hints`.
|
||||||
@@ -0,0 +1,421 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: resolved
|
||||||
|
project: bdinvite
|
||||||
|
date: 2026-10-03
|
||||||
|
tags:
|
||||||
|
- bdinvite
|
||||||
|
- oidc
|
||||||
|
- sso
|
||||||
|
- benchmark
|
||||||
|
- graphify
|
||||||
|
- ai-agents
|
||||||
|
- empirical-study
|
||||||
|
---
|
||||||
|
|
||||||
|
# Reducing token usage with Graphify — Experimental Retrospective
|
||||||
|
|
||||||
|
## 1. Abstract
|
||||||
|
|
||||||
|
This retrospective documents an empirical agentic AI workflow experiment comparing two autonomous AI coding-agent with equal starting conditions implementing an application-level OpenID Connect (OIDC) Single Sign-On (SSO) architecture in a real-world repository ([`bdinvite`](https://gitea.roadtotech.me/kiskaadee/bdinvite)):
|
||||||
|
|
||||||
|
* **Control Condition**: Standard repository exploration and development toolset (`grep`, `find`, `view_file`, `uv run pytest`, `git`).
|
||||||
|
* **Treatment Condition (Graphify)**: Identical development toolset augmented with `Graphify`, an AST-based code knowledge-graph generator providing structural queries (`graphify query`, `path`, `explain`, `update .`).
|
||||||
|
|
||||||
|
Both agents operated in parallel isolated git worktrees starting from identical repository state (`commit 42927b9`), followed a frozen 8-checkpoint roadmap, adhered to a mandatory subagent Git delegation gate, and were evaluated after every checkpoint by an external automated gatekeeper.
|
||||||
|
|
||||||
|
Both conditions completed all 8 checkpoints with a **100% PASS** rate against baseline regression (25/25 original tests) and cumulative verification suites (>110 passing tests each). However, the experiment revealed significant, non-monotonic variation between checkpoints:
|
||||||
|
* **Treatment (Graphify) reduced estimated context tokens in 5 of 8 checkpoints**: CP1 (−15.8%), CP2 (−31.8%), CP5 (−16.7%), CP6 (−12.6%), and CP8 (−15.3%), driven by targeted graph querying and localized file inspections during core architectural and backend refactoring.
|
||||||
|
* **Control maintained lower context tokens in 3 of 8 checkpoints**: CP3 (+22.4%), CP4 (+74.6%), and CP7 (+57.8%), where Graphify engaged in premature cross-module refactoring or repeated tooling/type-checking test iterations.
|
||||||
|
* **Cumulatively**, Control completed the lifecycle with fewer estimated tokens (~19.91M vs. ~22.92M, a +15.1% difference for Graphify) and fewer inference turns (532 vs. 592).
|
||||||
|
|
||||||
|
This retrospective analyzes the experimental signal, separates measured observations from causal interpretations, identifies design flaws and confounding variables, details concrete architectural differences between the resulting codebases, and extracts rigorous lessons for future AI agent benchmarking.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Motivation and Original Question
|
||||||
|
|
||||||
|
### 2.1 The Engineering Context
|
||||||
|
`bdinvite` is a self-hosted digital birthday invitation and RSVP management application deployed in a homelab environment. Historically, administrative security relied on edge reverse-proxy enforcement: Traefik intercepted requests to `/birthday/admin` via Authelia ForwardAuth, passing an unvalidated `Remote-User` HTTP header to FastAPI endpoints.
|
||||||
|
|
||||||
|
While operationally functional behind Traefik, this architecture suffered from two severe structural drawbacks:
|
||||||
|
1. **Infrastructure Coupling**: The application could not run standalone for local development or testing without a full Traefik/Authelia reverse-proxy stack.
|
||||||
|
2. **Fragile Perimeter Security**: If edge proxy middleware configuration lapsed, internal endpoints were vulnerable because authorization was coupled to an untrusted client-controllable request header.
|
||||||
|
|
||||||
|
The target architectural migration was to replace this perimeter dependency with a **hexagonal `AuthPort` interface** and an application-level OIDC client communicating via standard session cookies, enabling standalone execution against any OIDC provider (e.g., Mock OAuth2, Keycloak, or Authelia OIDC mode).
|
||||||
|
|
||||||
|
### 2.2 The Research Motivation
|
||||||
|
In large or unfamiliar codebases, autonomous agents spend substantial inference context reading full files (`view_file`), grepping across directories, and reloading context into prompt history across multi-turn sessions.
|
||||||
|
|
||||||
|
Knowledge graph augmentations (such as Graphify) build an AST-based property graph linking functions, classes, modules, and dependencies into semantic clusters. The core hypothesis was:
|
||||||
|
|
||||||
|
> *Equipping an autonomous coding agent with structured graph queries will reduce prompt context consumption and improve navigation accuracy compared to traditional grep/view exploration when executing complex, multi-stage architectural migrations.*
|
||||||
|
|
||||||
|
### 2.3 The Intended Independent Variable
|
||||||
|
The intended single variable was **the mode of codebase exploration**:
|
||||||
|
* Control: Textual / linear search tools (`grep`, `find`, `view_file`).
|
||||||
|
* Treatment: Graph-based semantic tools (`graphify query`, `path`, `explain`, `update .`) alongside textual tools.
|
||||||
|
|
||||||
|
All other parameters—prompt specifications, model, baseline commit, task sequence, evaluation gates, and Git workflow—were intended to be held strictly constant.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Experimental Model
|
||||||
|
|
||||||
|
### 3.1 Worktree Isolation & Baseline State
|
||||||
|
The benchmark operated in two isolated Git worktrees within the test root `/home/kiskaadee/Projects/tests/bdinvite-benchmark/`:
|
||||||
|
* `control/` (branch `control/feat/sso-auth`)
|
||||||
|
* `graphify/` (branch `graphify/feat/sso-auth`)
|
||||||
|
|
||||||
|
Both worktrees were branched from baseline commit `42927b9858c1b091bb6e78d3abcf6f9500bd7547`. The baseline state was verified via pre-experiment freeze gate:
|
||||||
|
* 25 passing pytest unit and integration tests.
|
||||||
|
* Clean Vite React build (`npm run build`).
|
||||||
|
* Clean multi-stage Docker build.
|
||||||
|
|
||||||
|
### 3.2 OIDC Test Provider Fixture
|
||||||
|
To eliminate network variance, flakiness, or rate limits, a local, standards-compliant OIDC provider was executed via Docker (`ghcr.io/navikt/mock-oauth2-server:2.1.10`) bound to `http://localhost:8088/default`. The provider pre-seeded:
|
||||||
|
* Discovery metadata (`.well-known/openid-configuration`)
|
||||||
|
* Dynamic JWKS key rotation endpoint (`/jwks`)
|
||||||
|
* Authorization and token endpoints (`/authorize`, `/token`)
|
||||||
|
* Pre-seeded test credentials:
|
||||||
|
- Admin: `admin@example.com` / `password123` (`sub: admin-001`, `groups: ["bdinvite_admins"]`)
|
||||||
|
- Guest: `guest@example.com` / `password123` (`sub: guest-001`, `groups: ["guests"]`)
|
||||||
|
|
||||||
|
### 3.3 Git History Delegation Gate
|
||||||
|
To make the commit boundary verifiable and isolate commit authoring from implementation reasoning:
|
||||||
|
* **The implementation agent was strictly prohibited from executing `git commit` directly.**
|
||||||
|
* Upon reaching verified checkpoint completion, each agent was required to invoke a dedicated subagent with `Role: "Git History Custodian"` executing the `git-commit` skill.
|
||||||
|
* **Graphify tools were explicitly excluded from the Git Custodian subagent prompt and environment.**
|
||||||
|
* Every milestone commit was required to be an atomic Conventional Commit adhering to the Brain semantic taxonomy.
|
||||||
|
|
||||||
|
### 3.4 Contamination Control
|
||||||
|
* `graphify-out/` was explicitly ignored in `.git/info/exclude` in both worktrees.
|
||||||
|
* Before evaluating any checkpoint, the external gatekeeper checked `git status --ignored` and git history to guarantee zero Graphify AST artifacts or cache files leaked into repository tracking.
|
||||||
|
|
||||||
|
### 3.5 Telemetry & Token Estimation Methodology
|
||||||
|
All agent transcripts were persisted as JSONL logs under `<appDataDir>/brain/<conversation-id>/.system_generated/logs/transcript.jsonl`.
|
||||||
|
|
||||||
|
Because live API tokens were delivered through a local runtime session without direct per-turn token logging, token consumption was computed uniformly via character density approximation:
|
||||||
|
$$\text{Tokens}_{\text{estimated}} = \frac{\text{Characters}}{3.8}$$
|
||||||
|
|
||||||
|
For each turn $i$:
|
||||||
|
$$\text{Prompt Characters}_i = \sum_{j=1}^{i-1} (\text{Content}_j + \text{Tool Output}_j)$$
|
||||||
|
$$\text{Cumulative Input Tokens} = \sum_{i=1}^{N} \frac{\text{Prompt Characters}_i}{3.8}$$
|
||||||
|
$$\text{Cumulative Output Tokens} = \sum_{i=1}^{N} \frac{\text{Response Characters}_i}{3.8}$$
|
||||||
|
|
||||||
|
This metric captures the cumulative prompt context sent to the model across multi-turn sessions, which accurately reflects the primary cost driver of agent execution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Benchmark and Task Design
|
||||||
|
|
||||||
|
The migration was divided into 8 sequential checkpoints (CP1–CP8), designed to mirror an incremental engineering rollout:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
CP1["CP1: AuthPort &<br/>Identity Model"] --> CP2["CP2: Generic OIDC<br/>Client & PKCE"]
|
||||||
|
CP2 --> CP3["CP3: Identity &<br/>Group Extraction"]
|
||||||
|
CP3 --> CP4["CP4: Browser Session<br/>& Fixation Barrier"]
|
||||||
|
CP4 --> CP5["CP5: FastAPI DI<br/>(Isolated)"]
|
||||||
|
CP5 --> CP6["CP6: Admin Route<br/>Migration & Negative Gate"]
|
||||||
|
CP6 --> CP7["CP7: Browser SSO Flow<br/>(Playwright)"]
|
||||||
|
CP7 --> CP8["CP8: Security Hardening<br/>& Independence"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Checkpoint Role & Scope:
|
||||||
|
1. **CP1 (AuthPort & Identity Abstraction)**: Establish pure domain boundaries (`AuthPort` Protocol and `Identity` model). Application code must not import OIDC/crypto modules.
|
||||||
|
2. **CP2 (Generic OIDC Client & PKCE)**: Implement RFC 7636 PKCE (S256), cryptographic state/nonce verification, and token signature validation against JWKS.
|
||||||
|
3. **CP3 (OIDC Identity & Group Extraction)**: Map validated ID token claims to `Identity` attributes and extract group memberships (`"groups"` claim).
|
||||||
|
4. **CP4 (Browser Session & Fixation Protection)**: Issue `HttpOnly` session cookie upon authentication; rotate session identifier (`pre_auth_id != post_auth_id`) to block session fixation; implement logout and expiration.
|
||||||
|
5. **CP5 (FastAPI Dependency Injection)**: Establish `Depends()` dependencies (`get_current_identity`, `require_authenticated`, `require_group("bdinvite_admins")`) verified against test routes without modifying production routes.
|
||||||
|
6. **CP6 (Admin API Migration & Negative Barrier)**: Migrate all admin endpoints in `backend/app/routes/admin.py` to `require_admin`. **Critical Negative Gate**: A request presenting the legacy `Remote-User` header without a valid session must receive HTTP 401.
|
||||||
|
7. **CP7 (Browser SSO Flow & Playwright Acceptance)**: Integrate React SPA admin layout with session resolution, unauthenticated redirect to login, header identity display, and logout button. Verify end-to-end interactive loop via Playwright.
|
||||||
|
8. **CP8 (Security Hardening & Deployment Independence)**: Adversarial security suite (forged state, forged JWT, replayed nonce, missing PKCE verifier, expired token/session, non-admin 403, forged Remote-User 401). Verify standalone vs homelab configuration and multi-stage Docker build.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Experimental Controls
|
||||||
|
|
||||||
|
| Dimension | Controlled Invariant | Allowed to Vary |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Initial Repository State** | Identical commit SHA (`42927b9`) | None |
|
||||||
|
| **Specification & Prompts** | Identical task prompts per checkpoint | None |
|
||||||
|
| **External Environment** | Identical mock OIDC server, identical ports | None |
|
||||||
|
| **Evaluation Criteria** | External automated gatekeeper outside worktrees | None |
|
||||||
|
| **Git Commit Authority** | Identical `Git History Custodian` subagent delegation | None |
|
||||||
|
| **Exploration Mode** | Standard tools vs. Standard tools + Graphify | Agent choice of tool invocation |
|
||||||
|
| **Code Implementation** | Behavioral & interface contracts enforced | Internal module decomposition, data structures, and file layout |
|
||||||
|
| **Internal Session Storage** | Secure cookie contract enforced | Storage engine (in-memory dict vs. signed cookie) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Observed Results
|
||||||
|
|
||||||
|
### 6.1 Checkpoint-by-Checkpoint Performance
|
||||||
|
|
||||||
|
| CP | Scope | Control Turns | Graphify Turns | Control Tokens (est) | Graphify Tokens (est) | Graphify Token Delta | Graphify Operations |
|
||||||
|
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||||
|
| **CP1** | AuthPort & Identity | 18 | 18 | 488,678 | 411,553 | **−15.8%** | 2 queries, 1 update |
|
||||||
|
| **CP2** | OIDC Client & PKCE | 61 | 52 | 1,564,017 | 1,066,142 | **−31.8%** | 0 queries, 1 update |
|
||||||
|
| **CP3** | Identity & Groups | 62 | 67 | 1,976,587 | 2,418,654 | **+22.4%** | 0 queries, 1 update |
|
||||||
|
| **CP4** | Session & Fixation | 66 | 101 | 2,620,065 | 4,574,917 | **+74.6%** | 0 queries, 1 update |
|
||||||
|
| **CP5** | FastAPI DI (Isolated) | 53 | 53 | 1,450,022 | 1,208,035 | **−16.7%** | 0 queries, 1 update |
|
||||||
|
| **CP6** | Admin Routes & Negative Gate | 82 | 79 | 3,857,530 | 3,370,200 | **−12.6%** | 0 queries, 1 update |
|
||||||
|
| **CP7** | Browser SSO & Playwright | 112 | 147 | 4,291,450 | 6,774,124 | **+57.8%** | 1 query, 1 update |
|
||||||
|
| **CP8** | Hardening & Docker Build | 96 | 93 | 3,659,015 | 3,099,463 | **−15.3%** | 0 queries, 2 updates |
|
||||||
|
| **Total** | **Full Benchmark Lifecycle** | **532** | **592** | **19,907,364** | **22,923,088** | **+15.1%** | **3 queries, 9 updates** |
|
||||||
|
|
||||||
|
```
|
||||||
|
Estimated Cumulative Tokens by Checkpoint:
|
||||||
|
CP1: [Control: 489k ] [Graphify: 412k ] (-15.8%) ■ Graphify
|
||||||
|
CP2: [Control: 1.56M] [Graphify: 1.07M] (-31.8%) ■ Graphify
|
||||||
|
CP3: [Control: 1.98M] [Graphify: 2.42M] (+22.4%) □ Control
|
||||||
|
CP4: [Control: 2.62M] [Graphify: 4.57M] (+74.6%) □ Control
|
||||||
|
CP5: [Control: 1.45M] [Graphify: 1.21M] (-16.7%) ■ Graphify
|
||||||
|
CP6: [Control: 3.86M] [Graphify: 3.37M] (-12.6%) ■ Graphify
|
||||||
|
CP7: [Control: 4.29M] [Graphify: 6.77M] (+57.8%) □ Control
|
||||||
|
CP8: [Control: 3.66M] [Graphify: 3.10M] (-15.3%) ■ Graphify
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Tool Call Distribution Across Checkpoints
|
||||||
|
|
||||||
|
| Checkpoint | View File (C / G) | Edit/Write (C / G) | Test/Commands (C / G) | Graph Queries | Graph Updates |
|
||||||
|
| :--- | :---: | :---: | :---: | :---: | :---: |
|
||||||
|
| **CP1** | 6 / 6 | 4 / 3 | 5 / 6 | 2 | 1 |
|
||||||
|
| **CP2** | 22 / 16 | 7 / 5 | 28 / 27 | 0 | 1 |
|
||||||
|
| **CP3** | 19 / 18 | 9 / 12 | 31 / 34 | 0 | 1 |
|
||||||
|
| **CP4** | 28 / 38 | 11 / 17 | 24 / 42 | 0 | 1 |
|
||||||
|
| **CP5** | 27 / 15 | 8 / 6 | 16 / 29 | 0 | 1 |
|
||||||
|
| **CP6** | 31 / 32 | 17 / 12 | 28 / 31 | 0 | 1 |
|
||||||
|
| **CP7** | 34 / 41 | 11 / 8 | 57 / 87 | 1 | 1 |
|
||||||
|
| **CP8** | 35 / 30 | 13 / 15 | 44 / 44 | 0 | 2 |
|
||||||
|
| **Cumulative** | **202 / 196** | **90 / 88** | **233 / 300** | **3** | **9** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Architectural Outcomes
|
||||||
|
|
||||||
|
A comparative code-level diff of the two final codebases reveals significant architectural divergence despite both passing all verification suites:
|
||||||
|
|
||||||
|
### 7.1 Module & Package Decomposition
|
||||||
|
* **Control**: Followed clean single-responsibility decomposition under `backend/app/auth/`:
|
||||||
|
- `identity.py` (Domain value object and validation)
|
||||||
|
- `port.py` (Pure Protocol definition)
|
||||||
|
- `session.py` (Session models, thread-safe store, and HMAC signing)
|
||||||
|
- `oidc.py` (OIDC protocol engine: discovery, PKCE, state/nonce, JWKS)
|
||||||
|
- `adapter.py` (Adapter coordinating OIDC client and session store to satisfy `AuthPort`)
|
||||||
|
- `dependencies.py` (FastAPI dependency injection providers)
|
||||||
|
* **Graphify**: Consolidated implementation into a 38.8 KB monolithic `oidc.py`:
|
||||||
|
- `port.py` (Co-located `Identity` dataclass and `AuthPort` protocol)
|
||||||
|
- `oidc.py` (Monolithic module containing `OIDCClient`, `OIDCAuthAdapter`, `SessionRecord`, PKCE helpers, claim resolution, and exception classes)
|
||||||
|
- `dependencies.py` (FastAPI dependency injection providers)
|
||||||
|
|
||||||
|
### 7.2 Domain Invariant Enforcement (`Identity`)
|
||||||
|
* **Control**: Enforced strict runtime assertions in `Identity.__post_init__`:
|
||||||
|
- Rejects empty or non-string `subject` and `email` with `ValueError`.
|
||||||
|
- Enforces type safety on `name` and all individual items in `groups`.
|
||||||
|
- Added domain helper method `identity.has_group(group_name: str) -> bool`.
|
||||||
|
* **Graphify**: Permissive constructor:
|
||||||
|
- Only coerces `groups` to a list if `None` or tuple; does not validate string content or non-empty invariants on `subject` or `email`.
|
||||||
|
|
||||||
|
### 7.3 Session Security & Thread Safety
|
||||||
|
* **Control**:
|
||||||
|
- **HMAC-SHA256 Signed Cookies**: Cookies are formatted as `<session_id>.<mac>`. Tampered cookies fail verification in constant time via `hmac.compare_digest` before any storage lookup occurs.
|
||||||
|
- **Thread-Safe Storage**: `InMemorySessionStore` protects session access, creation, and pruning with `threading.Lock()`.
|
||||||
|
- **Protocol Decoupling**: Defined an explicit `SessionStore` protocol, allowing swapping to Redis or SQLite without changing adapter logic.
|
||||||
|
* **Graphify**:
|
||||||
|
- **Unsigned Session IDs**: Cookie stores raw identifier; relies solely on entropy and allowed character regex checks.
|
||||||
|
- **Header Fallback**: Accepts `X-Session-ID` header directly from requests.
|
||||||
|
- **Unsynchronized Storage**: Sessions stored in an un-locked raw Python dictionary (`self.sessions: dict[str, Any]`).
|
||||||
|
|
||||||
|
### 7.4 Dependency Injection Composition
|
||||||
|
* **Control**: Chained dependency composition:
|
||||||
|
- `require_group` delegates to `Depends(require_authenticated)`, cleanly reusing the 401 gate without duplicated logic, then checks `identity.has_group(group_name)`.
|
||||||
|
* **Graphify**: Direct dependency:
|
||||||
|
- `require_group` depends directly on `get_current_identity`, duplicating the unauthenticated check.
|
||||||
|
- Included a testing utility `set_auth_adapter(adapter)` for global singleton override.
|
||||||
|
|
||||||
|
### 7.5 Infrastructure & Deployment Configuration
|
||||||
|
* **Control**: Fully updated deployment infrastructure in `docker-compose.yml`:
|
||||||
|
- Removed the legacy Traefik ForwardAuth router (`middlewares=authelia-auth@docker`).
|
||||||
|
- Unified all traffic into a single Traefik router delegating auth to BDInvite's native OIDC SSO layer.
|
||||||
|
- Injected all required OIDC and cookie environment variables (`OIDC_ISSUER`, `OIDC_CLIENT_ID`, `SESSION_SECRET_KEY`).
|
||||||
|
* **Graphify**:
|
||||||
|
- Documented deployment modes in `config.py` and created a `.env.example` template.
|
||||||
|
- **Failed to update `docker-compose.yml`**: left the obsolete `authelia-auth@docker` ForwardAuth router intact.
|
||||||
|
|
||||||
|
### 7.6 Executable Architectural Enforcement
|
||||||
|
* **Control**: Implemented string-scanning test `test_static_architectural_assertion_no_runtime_remote_user` verifying zero runtime references to `remote-user` in `backend/app/` and `frontend/src/`.
|
||||||
|
* **Graphify**: Implemented **AST-based architectural import test** `test_architectural_isolation_zero_prohibited_imports` in `tests/test_auth_port.py`. This test parses the AST of all domain modules and routes, asserting that none import `oidc`, `oauth`, `jwt`, `jose`, or `cryptography`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Analysis of the Experimental Signal
|
||||||
|
|
||||||
|
### 8.1 The Two Operational Regimes
|
||||||
|
The data reveals that Graphify's impact on agent context consumption is **bimodal**, depending heavily on the nature of the engineering task:
|
||||||
|
|
||||||
|
```
|
||||||
|
Task Type Checkpoints Graphify Effect Observed Mechanism
|
||||||
|
──────────────────────────────────────────────────────────────────────────────────────────────────────────
|
||||||
|
Architectural Discovery CP1, CP2, CP5, Token Reduction Compact query results prevent loading
|
||||||
|
& Module Refactoring CP6, CP8 (−12.6% to −31.8%) entire files into prompt context.
|
||||||
|
|
||||||
|
Scope Expansion, Rework CP3, CP4, CP7 Token Overhead Broad graph awareness invites premature
|
||||||
|
& Tooling Iteration (+22.4% to +74.6%) coupling; CLI tool flakiness compounds history.
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **Discovery & Structural Refactoring (The Graphify Advantage)**:
|
||||||
|
In CP1, CP2, CP5, CP6, and CP8, the agent was tasked with understanding existing backend contracts and refactoring routes. In CP2, Graphify consumed ~500k fewer tokens than Control; in CP5, it required 15 file views versus Control's 27. The graph provided targeted structural context without forcing the agent to ingest full files.
|
||||||
|
|
||||||
|
2. **Cross-Module Scope Expansion (The Graphify Overhead Trap)**:
|
||||||
|
In CP4, Graphify observed the entire dependency topology linking sessions to routes, and attempted to refactor `auth.py`, `main.py`, and `admin.py` concurrently before those modules were required by the specification. When tests broke, the agent spent 101 turns and 42 command executions untangling the premature changes, resulting in a +74.6% token explosion.
|
||||||
|
|
||||||
|
3. **Tooling & Build Flakiness (Context Accumulation)**:
|
||||||
|
In CP7, both agents struggled with Playwright asynchronous page timings and Vite asset directory creation. Because Graphify took more iteration turns to resolve these environmental issues (87 commands vs 57), its multi-turn transcript grew rapidly, demonstrating that multi-turn prompt history growth dominates token totals whenever execution gets bogged down in runtime tooling.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Confounders and Limitations
|
||||||
|
|
||||||
|
### 9.1 Architectural Freedom as an Uncontrolled Variable
|
||||||
|
The specification intentionally granted agents implementation discretion (e.g., internal session storage mechanism, file layout). While realistic for software engineering, this introduced a major confounder:
|
||||||
|
* Control chose a modular 6-file layout with HMAC-signed cookies and thread-safe store.
|
||||||
|
* Graphify chose a 3-file layout with a monolithic `oidc.py` and raw session tokens.
|
||||||
|
|
||||||
|
Because the implementations differed in design, the benchmark did not purely measure exploration efficiency; it measured the combined cost of **exploration + differing architectural implementations**.
|
||||||
|
|
||||||
|
### 9.2 Compound History Effect in Multi-Turn Agents
|
||||||
|
In conversational agent architectures, every previous turn's input, thinking, and tool output is re-sent in every subsequent turn. Consequently:
|
||||||
|
$$\text{Cost of Turn } N \propto N \times \text{History Size}$$
|
||||||
|
A single debugging loop of 15 extra turns late in a session (such as Graphify's Playwright timing fixes in CP7) accumulates millions of prompt characters, masking any token savings achieved during early exploration.
|
||||||
|
|
||||||
|
### 9.3 Task Heterogeneity
|
||||||
|
The benchmark combined three fundamentally different engineering disciplines across 8 checkpoints:
|
||||||
|
1. Pure contract definition (CP1)
|
||||||
|
2. Cryptographic backend protocols (CP2, CP3, CP4, CP5, CP6, CP8)
|
||||||
|
3. Cross-language full-stack browser automation (CP7)
|
||||||
|
|
||||||
|
Aggregating these disparate tasks into a single cumulative token number obscures the domain-specific efficiency of the tools.
|
||||||
|
|
||||||
|
### 9.4 Token Approximation Rather than Provider Billing
|
||||||
|
Tokens were calculated via character density ($3.8 \text{ chars/token}$). While standard for comparative studies, this approximation does not account for BPE tokenizer variance across programming languages, JSON whitespace, or model-side prompt caching (which would substantially reduce actual provider billing for repeated prefix history).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. What the Experiment Supports
|
||||||
|
|
||||||
|
Based strictly on the verified experimental data, the following conclusions are defensible:
|
||||||
|
|
||||||
|
1. **Both Conditions Achieve Equivalent Functional Correctness**: Both agents successfully implemented a complete, production-ready OIDC SSO architecture satisfying identical security barriers, baseline regression suites, and external gatekeeper checks.
|
||||||
|
2. **Graphify Enables Substantial Token Reductions in Localized Architecture Tasks**: When tasks were confined to backend architectural discovery, protocol implementation, and route migration (CP1, CP2, CP5, CP6, CP8), Graphify consistently reduced estimated context tokens by **12.6% to 31.8%**.
|
||||||
|
3. **Graph Awareness Increases the Risk of Premature Refactoring**: When presented with an interconnected code graph, the agent exhibited a measurable tendency to modify downstream dependent files ahead of schedule (CP4), leading to longer rework cycles.
|
||||||
|
4. **Git Delegation Invariants Are 100% Achievable**: Both agents successfully executed 8 consecutive checkpoints without violating the subagent commit delegation invariant (16/16 commits created by `Git History Custodian`).
|
||||||
|
5. **No Monotonic Aggregate Token Advantage**: Across an entire heterogeneous software lifecycle, Graphify did not provide a net cumulative token reduction (+15.1% total estimated tokens due to CP4 and CP7 rework).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. What It Does Not Support
|
||||||
|
|
||||||
|
To maintain methodological integrity, the following claims **cannot** be made from this experiment:
|
||||||
|
|
||||||
|
1. ❌ *"Graphify is less token-efficient than standard tools."*
|
||||||
|
The cumulative token deficit was driven almost entirely by two checkpoints (CP4 and CP7) characterized by scope expansion and environmental test flakiness. In 5 out of 8 checkpoints, Graphify was more efficient.
|
||||||
|
2. ❌ *"Control produces better architecture than Graphify."*
|
||||||
|
While Control's modular layout and HMAC signed cookies aligned better with defensive engineering practices, both architectures satisfied all security and interface invariants. Graphify also produced superior architectural self-tests (AST import isolation).
|
||||||
|
3. ❌ *"Graphify causes agents to write monolithic files."*
|
||||||
|
Graphify's decision to combine classes in `oidc.py` was an agent implementation choice, not a constraint imposed by Graphify.
|
||||||
|
4. ❌ *"Character density approximation equals financial cost."*
|
||||||
|
Modern LLM APIs employ prompt caching for shared conversation prefixes. Because prompt caching heavily discounts repeated history, character-based cumulative totals do not directly map to API dollar costs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Lessons for a Follow-up Experiment
|
||||||
|
|
||||||
|
A follow-up benchmark evaluating code knowledge graphs should incorporate the following structural adjustments:
|
||||||
|
|
||||||
|
1. **Decouple Exploration from Implementation**:
|
||||||
|
Run separate benchmark tracks:
|
||||||
|
* *Track A (Exploration & Navigation)*: Measure turns, file views, and tokens needed strictly to answer architectural questions, identify call graphs, or produce a change specification (zero implementation).
|
||||||
|
* *Track B (Implementation with Frozen Interface)*: Freeze file names, class names, and signatures so agents cannot choose different architectural scopes.
|
||||||
|
2. **Isolate Homogeneous Task Families**:
|
||||||
|
Replace the monolithic 8-checkpoint marathon with distinct task families:
|
||||||
|
* *Family 1: API & Route Refactoring* (pure Python)
|
||||||
|
* *Family 2: Protocol & Cryptography*
|
||||||
|
* *Family 3: Full-Stack UI Integration*
|
||||||
|
3. **Turn-Level Token & Cache Telemetry**:
|
||||||
|
Record exact provider-reported prompt, cached prompt, and completion tokens for every turn rather than approximating across the whole run.
|
||||||
|
4. **Enforce Boundary Scoping Prompts**:
|
||||||
|
Explicitly instruct agents to modify *only* the files within the active checkpoint scope to prevent premature downstream refactoring.
|
||||||
|
5. **Session Reset per Checkpoint**:
|
||||||
|
Reset the conversation context between checkpoints, carrying forward only the repository state on git. This eliminates the compound history penalty where late-stage checkpoints inherit millions of characters of unrelated prior discussions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Retrospective Conclusion
|
||||||
|
|
||||||
|
What did this experiment accomplish, even though the original hypothesis of universal token reduction was disproven?
|
||||||
|
|
||||||
|
It delivered a clear, nuanced empirical finding: **Code knowledge graphs are precision instruments, not universal accelerators.**
|
||||||
|
|
||||||
|
When an autonomous agent uses a code graph to navigate structural relationships, verify call sites, and inspect interfaces, it achieves significant context savings (up to 32% per checkpoint) over brute-force file viewing. However, graph visibility also gives the agent a panoramic view of the system that can tempt it into premature cross-boundary refactoring, leading to costly test-reconciliation cycles. Furthermore, when an agent gets entangled in runtime environment issues (such as browser automation timings), prompt history accumulation rapidly swamps any savings gained from graph exploration.
|
||||||
|
|
||||||
|
Finally, the experiment produced two production-ready, fully verified implementations of the BDInvite OIDC architecture. The ideal engineering synthesis cherry-picks the best of both: **Control's disciplined modular decomposition and HMAC signed session store, combined with Graphify's executable AST architectural boundary enforcement.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Appendix A — Checkpoint Results Summary
|
||||||
|
|
||||||
|
| Checkpoint | Scope | Control Commit | Graphify Commit | Baseline Tests | Suite Tests | Gatekeeper Status |
|
||||||
|
| :--- | :--- | :---: | :---: | :---: | :---: | :---: |
|
||||||
|
| **CP1** | AuthPort & Identity Abstraction | `79c3e82` | `df49897` | 25/25 | 36 / 33 | **PASS / PASS** |
|
||||||
|
| **CP2** | Generic OIDC Client & PKCE S256 | `b2cee24` | `0a4032a` | 25/25 | 47 / 44 | **PASS / PASS** |
|
||||||
|
| **CP3** | Claims & Group Extraction | `670f4f8` | `35be202` | 25/25 | 62 / 59 | **PASS / PASS** |
|
||||||
|
| **CP4** | Browser Session & Fixation Barrier | `d7618d5` | `815a584` | 25/25 | 76 / 70 | **PASS / PASS** |
|
||||||
|
| **CP5** | FastAPI DI (Isolated Verification) | `f20fb0f` | `27015d0` | 25/25 | 91 / 90 | **PASS / PASS** |
|
||||||
|
| **CP6** | Admin Routes & Negative Barrier | `b0dea63` | `39ac42c` | 25/25 | 96 / 95 | **PASS / PASS** |
|
||||||
|
| **CP7** | Browser SSO Flow (Playwright) | `d9b589c` | `e1f7456` | 25/25 | 97 / 96 | **PASS / PASS** |
|
||||||
|
| **CP8** | Security Hardening & Independence | `713a582` | `30d9a88` | 25/25 | 110 / 115 | **PASS / PASS** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Appendix B — Git Lineages
|
||||||
|
|
||||||
|
### Control Lineage (`control/feat/sso-auth`)
|
||||||
|
```
|
||||||
|
* 713a582 feat(security): harden authentication edge cases and verify deployment independence
|
||||||
|
* d9b589c feat(ui): integrate browser SSO authentication and admin logout
|
||||||
|
* b0dea63 feat(admin): migrate admin routes to group authorization and enforce negative Remote-User barrier
|
||||||
|
* f20fb0f feat(auth): implement FastAPI authentication and group authorization dependencies
|
||||||
|
* d7618d5 feat(auth): implement browser session management and fixation protection
|
||||||
|
* 670f4f8 feat(auth): map verified OIDC claims to domain Identity and groups
|
||||||
|
* b2cee24 feat(auth): implement generic OIDC client with PKCE and cryptographic token verification
|
||||||
|
* 79c3e82 feat(auth): define AuthPort protocol and Identity domain model
|
||||||
|
* 42927b9 (baseline) fix(admin): display registration timestamps in configured event timezone
|
||||||
|
```
|
||||||
|
|
||||||
|
### Graphify Lineage (`graphify/feat/sso-auth`)
|
||||||
|
```
|
||||||
|
* 30d9a88 feat(security): harden authentication edge cases and verify deployment independence
|
||||||
|
* e1f7456 feat(ui): integrate browser SSO authentication and admin logout
|
||||||
|
* 39ac42c feat(admin): migrate admin routes to group authorization and enforce negative Remote-User barrier
|
||||||
|
* 27015d0 feat(auth): implement FastAPI authentication and group authorization dependencies
|
||||||
|
* 815a584 feat(auth): implement browser session management and fixation protection
|
||||||
|
* 35be202 feat(auth): map verified OIDC claims to domain Identity and groups
|
||||||
|
* 0a4032a feat(auth): implement generic OIDC client with PKCE and cryptographic token verification
|
||||||
|
* df49897 feat(auth): define AuthPort protocol and Identity domain model
|
||||||
|
* 42927b9 (baseline) fix(admin): display registration timestamps in configured event timezone
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Appendix C — Telemetry Methodology
|
||||||
|
|
||||||
|
Telemetry records are stored in machine-readable JSON under `benchmark/results/<agent>/<checkpoint>.json`. Each record captures:
|
||||||
|
1. `checkpoint`: Milestone identifier (CP1 to CP8).
|
||||||
|
2. `status`: External gatekeeper evaluation verdict (`PASS` / `FAIL`).
|
||||||
|
3. `turns`: Number of model inference round-trips.
|
||||||
|
4. `verification`: Cumulative tests passed, baseline test count, and checkpoint-specific checks.
|
||||||
|
5. `git`: Commit SHA, commit count, and subagent delegation validation.
|
||||||
|
6. `tool_calls`: Granular breakdown of exploration (`view_file`), implementation (`write_to_file`, `replace_file_content`), verification (`run_command`), and graph lifecycle operations (`graphify_query`, `graphify_update`).
|
||||||
|
7. `token_estimate`: Character density approximation (`char_density_ratio = 3.8`) reporting input context tokens, output tokens, and total tokens.
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: open
|
||||||
|
project: brain
|
||||||
|
date: 2026-10-13
|
||||||
|
tags:
|
||||||
|
- learning
|
||||||
|
- architecture
|
||||||
|
- skills
|
||||||
|
- cognitive-science
|
||||||
|
- deliberate-practice
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Discussion: A Learning-Centered Engineering Workflow
|
||||||
|
|
||||||
|
## 1. Problem Statement & Purpose
|
||||||
|
|
||||||
|
The objective is to turn the daily engineering work I already do into **engineering competence I can retrieve and use later**, without slowing the work down so much that I stop using the system.
|
||||||
|
|
||||||
|
**Success test:** six months from now I can:
|
||||||
|
1. Recover what I did and why,
|
||||||
|
2. Explain or apply what I learned *without rereading*, and
|
||||||
|
3. See honestly what I don't know yet.
|
||||||
|
|
||||||
|
### Non-Goals
|
||||||
|
- Producing complete, polished documentation of all activity.
|
||||||
|
- Measuring "skill level" with a numeric score.
|
||||||
|
- Getting better at prompting.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Requirements Analysis
|
||||||
|
|
||||||
|
Sorted by provenance. Only R-items bind the design. I-items are exploratory ideas.
|
||||||
|
|
||||||
|
### Stated Requirements (Binding)
|
||||||
|
|
||||||
|
| ID | Requirement |
|
||||||
|
| :--- | :--- |
|
||||||
|
| **R1** | The record must bring back things I'd forget: a concept studied months ago, why an architecture was chosen, what was built in a given week. |
|
||||||
|
| **R2** | Artifacts must be worth rereading. Polish and structure are not value. |
|
||||||
|
| **R3** | Content value over metadata. Frontmatter is minimal. |
|
||||||
|
| **R4** | For learning-worthy work, the AI drafts **questions and blanks** around key concepts. I complete them. |
|
||||||
|
| **R5** | A curation step checks my answers against the evidence and gives feedback. |
|
||||||
|
| **R6** | For commits, the AI points at key details. I write the message and choose the integration strategy. |
|
||||||
|
| **R7** | The AI helps me do the cognitive work. It does not do it for me (active recall, active learning, practice). |
|
||||||
|
| **R8** | Productivity sometimes wins. There has to be a low-friction path (delivery mode). |
|
||||||
|
| **R9** | The target is architecture, problem solving, and engineering judgment. |
|
||||||
|
| **R10**| Design choices rest on cognitive science and instructional design, because that makes the design sound, not to decorate it with citations. |
|
||||||
|
| **R11**| Must cover four activities: project work, courses (Coursera/Platzi), daily LeetCode, planning/ideas. |
|
||||||
|
| **R12**| Must weave in: retrieval, spacing, formative feedback, git discipline, TDD, invariants, architecture reasoning, separating facts from interpretation. |
|
||||||
|
|
||||||
|
### Exploratory Ideas
|
||||||
|
|
||||||
|
| ID | Idea | Status |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **I1** | REST/MCP service recording commits, goals, artifacts, concepts | Deferred to §10 |
|
||||||
|
| **I2** | PostgreSQL as an event queue, with listeners deriving records | Deferred to §10 |
|
||||||
|
| **I3** | Hartman proficiency ladder as the progress model | Evaluated as lens only; unverified primary source |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Theoretical Basis & Design Principles
|
||||||
|
|
||||||
|
Each row pairs research findings with system principles and testable predictions:
|
||||||
|
|
||||||
|
| Finding | Design Principle | Testable Prediction |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Generation effect** (Slamecka & Graf, 1978): information produced by oneself is remembered better than information read. | **P1: I write the core reasoning.** The AI supplies facts and questions, not answers. | Notes I wrote are easier to recall later than AI-written ones. |
|
||||||
|
| **Retrieval practice / testing effect** (Roediger & Karpicke, 2006; Dunlosky et al., 2013): recalling beats rereading for long-term retention. | **P2: Revisits are recall attempts.** I answer before seeing the old note. | Revisit accuracy improves over successive attempts. |
|
||||||
|
| **Spacing and successive relearning** (Cepeda et al., 2006; Rawson & Dunlosky): spread-out retrieval sessions build durable memory. | **P3: Selected items come back after growing gaps.** | Items revisited 2–3 times stay recallable. Ones never revisited fade. |
|
||||||
|
| **Feedback** (Hattie & Timperley, 2007): feedback works when it targets the gap and the next step, not when it praises. | **P4: Feedback is diagnostic.** Correct / missing / wrong / unsupported, then revise. Never "masterfully". | I revise answers after feedback, and later attempts show fewer repeated gaps. |
|
||||||
|
| **Fluency illusion** (Bjork, Dunlosky & Kornell, 2013): smooth, easy-to-read material makes people overestimate what they know. | **P5: The polished AI summary is a known hazard.** This explains the "AI slop" feeling. | Reading a polished journal feels productive, but recall afterwards is weak. |
|
||||||
|
| **Self-explanation** (Chi et al., 1989): explaining *why* each step works deepens understanding. | **P6: Questions ask why and what-if,** not "what is X". | Why/what-if answers predict transfer better than definitions do. |
|
||||||
|
| **Desirable difficulties** (Bjork, 1994): struggle helps learning, but only if it's within reach. | **P7: Hints escalate gradually,** smallest useful hint first. | Hint level needed for the same concept drops over time. |
|
||||||
|
| **Expertise reversal** (Kalyuga et al., 2003): scaffolds that help novices get in the way once you know the material. | **P8: Scaffolding fades per concept.** Familiar ground goes to delivery mode (R8). | Forcing questions on routine work causes rubber-stamping. |
|
||||||
|
| **Deliberate practice** (Ericsson et al., 1993): focused practice at the edge of ability, with feedback. | **P9: Pick a few targets.** Not every commit is a lesson. | A few chosen capabilities improve more than "learn from everything". |
|
||||||
|
| **Transfer** (near vs far): applying a principle in a new context is harder than recall and means more. | **P10: The strongest evidence is a changed-context challenge.** | Demonstrating transfer in projects proves retention. |
|
||||||
|
|
||||||
|
**Progress models** (Dreyfus novice→expert; Hartman ladder): useful vocabulary for *describing* growth, but neither is a validated measurement scale. The system does not encode a ladder as state; it records evidence and lets the human judge.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Core Conceptual Model
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
A["Activity\n(project, course, LeetCode, idea)"] --> E["Evidence\n(diff, test, notes, submission)"]
|
||||||
|
E --> Q["Prompt\n(questions with blanks)"]
|
||||||
|
Q --> T["Attempt\n(my answer + assistance level)"]
|
||||||
|
T --> F["Feedback\n(checked against evidence)"]
|
||||||
|
F --> T
|
||||||
|
F --> S{"Settle"}
|
||||||
|
S -->|keep + revisit| R["Revisit\n(recall before reveal)"]
|
||||||
|
S -->|keep| K["Record"]
|
||||||
|
S -->|drop| X["Discard"]
|
||||||
|
R --> T
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Evidence** is an objective fact: a commit SHA, test result, accepted submission, or course section.
|
||||||
|
- **Prompt** is AI-generated: a few questions drawn directly from that evidence, with blanks.
|
||||||
|
- **Attempt** is learner-produced, tagged with `independent | hints | substantial | shown-solution`.
|
||||||
|
- **Feedback** compares the attempt with the evidence and diagnoses gaps.
|
||||||
|
- **Settle** is the human call: keep, keep and revisit, or discard.
|
||||||
|
- **Revisit** is a delayed recall attempt on the prompt or a changed-context variant.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Mode Separation: Delivery vs. Learning
|
||||||
|
|
||||||
|
| Dimension | Delivery Mode | Learning Mode |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Primary Goal** | Get the work done efficiently | Build a specific, durable capability |
|
||||||
|
| **AI Role** | Drafts, messages, summaries | Facts, evidence, and questions only |
|
||||||
|
| **Learner Role** | Reviews and approves | Writes reasoning, explanations, commit messages |
|
||||||
|
| **Output Record** | Facts only (what, when, links) | Facts + learner attempt + diagnostic feedback |
|
||||||
|
| **Appropriate Context** | Routine work, tight deadlines, familiar stacks | New concepts, real decisions, hard bugs, chosen targets |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Activity Adapters
|
||||||
|
|
||||||
|
1. **Project Work (decisions $\to$ features $\to$ commits)**:
|
||||||
|
- *Before*: In learning mode, state requirement, invariant, and failing test.
|
||||||
|
- *At commit*: AI lists diff slices and factual changes; learner writes message; AI checks against diff.
|
||||||
|
- *Integration*: Learner chooses merge/rebase/cherry-pick with rationale.
|
||||||
|
2. **Courses**:
|
||||||
|
- *Before*: One line predicting what the concept means.
|
||||||
|
- *During*: Sparse notes in own words, marking confusions with `?`.
|
||||||
|
- *After*: Source closed, explain the core idea; AI diagnoses gaps.
|
||||||
|
3. **LeetCode**:
|
||||||
|
- Attempt first unaided.
|
||||||
|
- Stuck $\to$ hint ladder; assistance level recorded.
|
||||||
|
- After acceptance: Write why the loop invariant/property works.
|
||||||
|
4. **Planning and Ideas**:
|
||||||
|
- Captured as a hypothesis (trigger, assumptions, falsifying evidence, next test).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. System Invariants
|
||||||
|
|
||||||
|
1. **AI never writes reasoning in learning mode.** Facts and questions only.
|
||||||
|
2. **Evidence $\neq$ assessment.** A commit, passing test, or completed module is never recorded as proof of competence.
|
||||||
|
3. **Assistance level is always recorded** (`independent`, `hints`, `substantial`, `shown-solution`).
|
||||||
|
4. **Gaps stay visible.** Unanswered prompts remain blank or marked `open`.
|
||||||
|
5. **Facts and interpretations are kept apart**, as are learner words and AI words.
|
||||||
|
6. **Revisits are selective** with explicit human opt-in (`revisit_after: YYYY-MM-DD`).
|
||||||
|
7. **Every kept artifact passes the 30-second reread test.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Resolution & Successors
|
||||||
|
|
||||||
|
This design discussion informed:
|
||||||
|
- The [Learning Contract](https://github.com/kiskaadee/skills/blob/main/profile/learning-contract.md) governing skills (`practice`, `git-commit`, `document`, `journal-builder`).
|
||||||
|
- The phased execution plan: [`01-plans/brain/learning-contract-and-scaffolded-skills.md`](../../01-plans/brain/learning-contract-and-scaffolded-skills.md).
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: resolved
|
||||||
|
project: brain
|
||||||
|
date: 2026-09-28
|
||||||
|
tags:
|
||||||
|
- brain
|
||||||
|
- architecture
|
||||||
|
- taxonomy
|
||||||
|
- epistemic-lifecycle
|
||||||
|
- governance
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Discussion: Brain Epistemic Lifecycle Taxonomy
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
As the Second Brain vault grew organically beyond 180 files, the repository's initial organizational model began to break down under daily usage. Documents were grouped primarily by target technology or broad topic containers (`homelab/`, `learning/`, `practice/`, `projects/`, `records/`).
|
||||||
|
|
||||||
|
This organic structure suffered from several fundamental failure modes:
|
||||||
|
|
||||||
|
1. **Taxonomy Conflation (Epistemic Role vs. Project Scope)**: A document concerning Homelab might be an actionable implementation roadmap, an exploratory architectural debate, an operational runbook, an incident post-mortem, or an ADR. Because folders were treated as subject-matter buckets (`projects/homelab/`, `homelab/`, `learning/`), documents with fundamentally different cognitive roles sat alongside one another.
|
||||||
|
2. **The "Archive" Anti-Pattern**: Projects and roadmaps maintained local `archive/` subdirectories (e.g. `projects/homelab/archive/`). Moving a completed or abandoned plan into an archive folder broke incoming relative Markdown links across journals and ADRs, created duplicate parallel directory trees, and treated lifecycle progression as a filesystem move rather than document state.
|
||||||
|
3. **Ambiguity Between Retrospective and Prospective Analysis**: Exploratory architectural inquiries (debating alternatives before deciding) were mixed with daily journals or incident post-mortems under `records/` or scattered across project folders. Prospective uncertainty ("Why and what if?") was structurally conflated with retrospective empirical fact ("What happened and what failed?").
|
||||||
|
4. **Project Hubs as Document Containers**: Directories under `projects/` functioned simultaneously as navigational entry points and arbitrary document dumping grounds. There was no clear structural rule determining whether a document belonged inside `projects/<name>/` or in a functional directory like `learning/guides/` or `records/decisions/`.
|
||||||
|
5. **Tooling & Agent Drift**: AI agents and automated scripts navigating the vault lacked deterministic paths. When generating artifacts, agents struggled to choose between `inbox/`, project-specific folders, and top-level directories.
|
||||||
|
|
||||||
|
The vault needed a structural refactoring centered on a durable organizing principle: **the epistemic role of information in the engineering lifecycle**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context and Analysis
|
||||||
|
|
||||||
|
### 1. Epistemic Role as the Primary Organizing Axis
|
||||||
|
|
||||||
|
Information in an engineering system is not defined solely by what technology it touches; it is defined by **its role in human and system cognition**:
|
||||||
|
|
||||||
|
* **Capture (`00-inbox/`)**: Unprocessed, ephemeral observations and rough drafts requiring zero-friction capture without classification barriers.
|
||||||
|
* **Intent (`01-plans/`)**: Forward-looking, actionable roadmaps, phased specifications, and execution blueprints answering: *"What do we intend to build?"*
|
||||||
|
* **Exploration (`02-discussions/`)**: Prospective inquiries, architectural trade-offs, and alternative analyses answering: *"Why and what if?"*
|
||||||
|
* **History (`03-records/`)**: Immutable historical memory answering: *"What happened, when did it happen, and what was decided?"* (journals, empirical debug RCAs, ADRs).
|
||||||
|
* **Understanding (`04-learning/`)**: Durable knowledge, operational SOPs, and deliberate practice answering: *"What do we understand and how do we operate it?"*
|
||||||
|
* **Machine Context (`05-agents/`)**: Machine-readable agent profiles, prompt modules, behavioral boundaries, and operational skills.
|
||||||
|
* **System Hubs (`06-projects/`)**: Canonical navigation nodes, topology mappings, forge links, and cross-cutting index entry points.
|
||||||
|
|
||||||
|
### 2. State as Metadata, Not Folder Placement
|
||||||
|
|
||||||
|
A central insight of the refactor is that **lifecycle status belongs in YAML frontmatter, never in directory placement**:
|
||||||
|
|
||||||
|
```text
|
||||||
|
# Anti-pattern: Moving files breaks the link graph
|
||||||
|
01-plans/homelab/feature.md ──(completed)──> 01-plans/homelab/archive/feature.md ❌
|
||||||
|
|
||||||
|
# Correct: Status changes, path remains immutable
|
||||||
|
01-plans/homelab/feature.md [status: active] ──> [status: completed] ✅
|
||||||
|
```
|
||||||
|
|
||||||
|
Eliminating `archive/` preserves every relative link throughout the knowledge graph. A plan referenced in an ADR or daily journal remains at its permanent URI regardless of whether it is `draft`, `active`, `completed`, or `abandoned`.
|
||||||
|
|
||||||
|
### 3. The Boundary Between Discussions and Records
|
||||||
|
|
||||||
|
A critical distinction debated during the design was the separation between `02-discussions/` and `03-records/`:
|
||||||
|
|
||||||
|
* **`02-discussions/` (Prospective Exploration)**: Documents open problem spaces where the solution is not yet determined. Multiple competing options (Option A vs. Option B) are evaluated with trade-offs. When consensus is reached, the discussion is marked `status: resolved` and explicitly links forward to the resulting plan (`01-plans/`) or decision (`03-records/decisions/`). It is a permanent record of *why* choices were made.
|
||||||
|
* **`03-records/debug/` (Retrospective Empirical Reality)**: Incident investigations and root cause analyses (RCAs) document system failures that actually occurred. They follow the scientific method: observation, hypotheses tested against logs and system facts, declarative fix, and recovery proof. They are empirical history, not prospective option design.
|
||||||
|
* **`03-records/decisions/` (Architectural Commitments)**: ADRs capture point-in-time commitments. While discussions explore options, ADRs record the chosen option and its lasting consequences.
|
||||||
|
|
||||||
|
### 4. Project Hubs as Navigation Nodes, Not Containers
|
||||||
|
|
||||||
|
Earlier iterations allowed projects to own extensive subtrees under `projects/`. This created a dual-hierarchy dilemma: should a NixOS guide live in `learning/guides/nixos/` or `projects/nixos/guides/`?
|
||||||
|
|
||||||
|
The resolution was to strictly constrain `06-projects/`:
|
||||||
|
* Every project hub is strictly located at `06-projects/<project>/README.md` (`max_depth=2`, `require_filename="README.md"`).
|
||||||
|
* No arbitrary documents or subfolders live in `06-projects/`.
|
||||||
|
* A project hub is an **index and topology node**, pointing outward across the numbered taxonomy to active plans in `01-plans/<project>/`, open discussions in `02-discussions/<project>/`, runbooks in `04-learning/guides/<project>/`, and historical debug logs in `03-records/debug/`.
|
||||||
|
|
||||||
|
### 5. Why `00-inbox/` Is Exempt from Validation
|
||||||
|
|
||||||
|
Zero-friction capture is paramount. If an engineer or agent must determine the exact frontmatter type, valid tags, and verified links before jotting down a thought, capture will not happen.
|
||||||
|
|
||||||
|
Therefore, `00-inbox/` sits outside the validated knowledge graph:
|
||||||
|
* It has no frontmatter requirement (`allow_unclassified=True`).
|
||||||
|
* It has no type contract (`expected_type=None`).
|
||||||
|
* It is ignored by link validation until curated into directories `01` through `06`.
|
||||||
|
|
||||||
|
### 6. The Rejection of Root Symlinks (`inbox -> 00-inbox`)
|
||||||
|
|
||||||
|
During the migration planning, a proposal was made to create a root symlink `inbox -> 00-inbox` for backwards compatibility with existing capture tools.
|
||||||
|
|
||||||
|
This was explicitly **rejected**:
|
||||||
|
* Symlinks create aliasing and dual-path confusion for recursive filesystem traversals.
|
||||||
|
* Markdown links could resolve through either path, weakening validation guarantees.
|
||||||
|
* Agents could discover both paths and produce inconsistent references.
|
||||||
|
* The clean architectural path was to update the capture tools (`~/.gemini/config/scripts/inbox-capture.sh`, `user_global` rules) directly to target `00-inbox/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Options Evaluation
|
||||||
|
|
||||||
|
| Architectural Question | Option A (Adopted) | Option B (Rejected) | Rationale |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Primary Organization** | Seven numbered lifecycle directories (`00-06`) | Technology / Project folders owning all sub-types | Projects change and overlap; the epistemic role of knowledge is invariant across engineering domains. |
|
||||||
|
| **Lifecycle Archiving** | Metadata-based (`status: completed` in frontmatter) | Physical `archive/` directories | Physical moves break incoming Markdown links across historical journals and ADRs. |
|
||||||
|
| **Investigation Artifacts** | `03-records/debug/` for empirical RCAs; `02-discussions/` for prospective design | Combined `records/discussions/` | Conflates retrospective debugging of broken systems with prospective evaluation of architectural options. |
|
||||||
|
| **Project Directories** | Constrained index hubs (`06-projects/*/README.md` only) | Deep project trees containing plans, guides, notes | Creates competing locations for guides and plans, fragmenting the vault. |
|
||||||
|
| **Validator Contract** | Declarative `DirectoryContract` enforcing type, depth, and filenames | Simple regex frontmatter check on all `.md` files | Regex checks cannot enforce directory shape, allowed nesting depths, or structural constraints like project README hubs. |
|
||||||
|
| **Inbox Compatibility** | Update all integration points to `00-inbox/` directly | Root symlink `inbox -> 00-inbox` | Avoids alias confusion, double traversals, and non-canonical path generation. |
|
||||||
|
| **Agent Assets** | Dedicated lifecycle category `05-agents/` (`profiles/`, `skills/`) | Embedded within project directories or root | Agents and skills are machine context that span multiple projects and workstations. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Consensus and Resolution
|
||||||
|
|
||||||
|
The numbered lifecycle taxonomy was adopted in full. The repository structure was reorganized into seven canonical directories governed by declarative contracts in `scripts/validate-brain.py`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
~/Brain
|
||||||
|
├── 00-inbox/ # Capture: unvalidated staging
|
||||||
|
├── 01-plans/ # Intent: roadmaps & blueprints (status: draft | active | completed | abandoned)
|
||||||
|
├── 02-discussions/ # Exploration: architectural inquiries & trade-offs (status: open | resolved)
|
||||||
|
├── 03-records/ # History: journals, debug post-mortems, ADRs
|
||||||
|
├── 04-learning/ # Understanding: knowledge/, guides/, practice/
|
||||||
|
├── 05-agents/ # Machine Context: profiles/, skills/
|
||||||
|
└── 06-projects/ # System Hubs: <project>/README.md topology indices
|
||||||
|
```
|
||||||
|
|
||||||
|
### Forward Linkages
|
||||||
|
* **Execution Blueprint**: The migration was carried out according to the completed implementation plan at [Brain Taxonomy & Lifecycle Migration Plan](../../01-plans/brain/taxonomy-lifecycle-migration.md).
|
||||||
|
* **Governance**: The rules governing this taxonomy are codified in [Root AGENTS.md](../../AGENTS.md) and enforced deterministically by `scripts/validate-brain.py`.
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
date: 2026-09-26
|
||||||
|
tags: [brain, tooling, validation, architecture, python]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Discussion: validate-brain.py Three-Phase Refactor
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
`scripts/validate-brain.py` grew organically. Each check was added in isolation, which kept individual additions small, but the accumulated design had several structural liabilities by the time the script was operating over 138 documents.
|
||||||
|
|
||||||
|
**Global mutable state.** `error_count` was a module-level integer incremented by side effects distributed across every check function. No function returned a value indicating what it found; the only observable output was the running count and printed strings. This made it impossible to test any individual check in isolation or compose checks without also running all of them.
|
||||||
|
|
||||||
|
**Four independent traversals.** The script called `rglob("*.md")` four separate times — once each for frontmatter checks, type-field checks, link checks, and code fence checks. Each traversal read the file from disk. For 138 files this was not a performance problem, but it was a correctness and maintainability problem: the set of files visited by each check was not guaranteed to be identical (if a file appeared between traversals, it would be seen by some checks and not others), and adding a new check required either a fifth traversal or threading new logic into one of the existing four in a way that was non-obvious.
|
||||||
|
|
||||||
|
**Error reporting by string inspection.** Callers determined whether a check had found anything by examining whether certain strings had been printed. There was no structured return value to aggregate, filter, or categorize.
|
||||||
|
|
||||||
|
**Two independent Markdown fence parsers.** A fence counter (tracking triple-backtick depth) and a `re.DOTALL` regex operating on the full file string both existed and were applied to different checks. They could disagree on the same file because they did not share state or a common model of the document. A file with an unclosed fence would confuse each of them differently.
|
||||||
|
|
||||||
|
**The missed Mermaid bug.** These structural problems had a concrete consequence: a check for Mermaid edge labels only matched lines containing `-->` and failed to check for parentheses in node labels. The Mermaid renderer rejects parentheses in node labels that are not quoted. The check passed on files that would fail at render time. The bug was not found by the test regime because there was no structured representation of what the parser had actually visited — the check was a line-level grep with no understanding of whether it was inside a code block of type `mermaid` or inside a generic code block or outside any block at all.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context and Analysis
|
||||||
|
|
||||||
|
### Two Feedback Sources
|
||||||
|
|
||||||
|
Two distinct sets of feedback were received. They agreed on the diagnosis but diverged sharply on prescription.
|
||||||
|
|
||||||
|
**The functional refactor proposal** identified the correct minimal changes: replace global state with functions that return lists, eliminate repeated traversals with a single-pass discovery step, introduce a `main()` entry point, and make the check registry explicit. It did not propose adding dependencies, splitting into multiple modules, or introducing configuration objects. The scope matched the actual complexity of the problem: a single-author script over a corpus of 138 documents, with a zero-dependency constraint.
|
||||||
|
|
||||||
|
What this proposal got right: it identified the smallest set of structural changes that would remove the liabilities. What it did not address: it left the two Markdown parsers intact and did not propose a unified model of document structure at the code-block level.
|
||||||
|
|
||||||
|
**The full architectural redesign proposal** went further. It proposed: PyYAML for frontmatter parsing (replacing ad-hoc regex), a Mermaid CLI integration for diagram validation (replacing heuristic label checks), a `ValidationConfig` dataclass for rule parameterization, and a multi-module package split (`validator/core.py`, `validator/checks/`, `validator/reporters/`). It identified the correct long-term direction for a team-owned, dependency-tolerant validation library.
|
||||||
|
|
||||||
|
What this proposal got right: the `Document` NamedTuple with a `validates_frontmatter` field, and the scan_code_blocks() linear scanner as the single shared parser for code fences. Both of these were adopted. What it over-prescribed: the external dependencies and module split impose a maintenance surface that is not justified by the corpus size or authorship model. A validator for 138 documents maintained by one author should not require a Node.js Mermaid CLI binary in the environment to run `git commit`.
|
||||||
|
|
||||||
|
### The Stopping-Point Decision
|
||||||
|
|
||||||
|
The team drew the scope boundary at: zero new external dependencies, single-file script, no configuration dataclass.
|
||||||
|
|
||||||
|
The rationale is not that PyYAML or a multi-module design is wrong — it is that those choices carry costs that are not yet justified. PyYAML as a dependency means the script can fail to run in a fresh environment where the package is absent. The current regex-based frontmatter extraction is brittle for complex YAML, but the Brain's frontmatter is structurally simple and consistent enough that the regex surface area is bounded. The cost of a parsing error from ad-hoc regex is a false negative (a file passes that should not). The cost of a missing dependency is that the entire validator is unavailable. For a pre-commit gate, the latter failure mode is worse.
|
||||||
|
|
||||||
|
The Mermaid CLI integration was rejected for the same reason: it introduces a runtime dependency on a Node.js binary and requires the binary's version to match the renderer's version. The heuristic label check, corrected to handle parentheses, is sufficient for the actual error class that was being missed. A false positive from the heuristic (flagging a valid diagram) is recoverable; a broken pre-commit hook is not.
|
||||||
|
|
||||||
|
The multi-module split was rejected because it complicates deployment (the script is currently copied or symlinked as a single file) and provides no benefit for a single-author codebase where the module boundaries would not be maintained across contributors.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Options Evaluation
|
||||||
|
|
||||||
|
| Decision Point | Option A (Adopted) | Option B (Rejected) |
|
||||||
|
|---|---|---|
|
||||||
|
| Frontmatter parsing | Regex extraction (existing approach, bounded surface) | PyYAML (correct, but adds external dependency) |
|
||||||
|
| Mermaid validation | Heuristic label check with parenthesis correction | Mermaid CLI subprocess (correct, but Node.js runtime dependency) |
|
||||||
|
| Code fence parsing | `scan_code_blocks()` linear scanner (single shared parser) | Retain both fence counter + DOTALL regex (two parsers, can disagree) |
|
||||||
|
| Script structure | Single file, `main()`, explicit check registry | Multi-module package with `ValidationConfig` dataclass |
|
||||||
|
| Phase sequencing | Three explicit phases with different behavioral contracts | Single large refactor (harder to attribute regressions) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Consensus and Resolution
|
||||||
|
|
||||||
|
### Phase Sequencing Rationale
|
||||||
|
|
||||||
|
The refactor was divided into three phases with different behavioral contracts. This separation is load-bearing for reasoning about regressions.
|
||||||
|
|
||||||
|
**Phase 1** introduces structural changes only: `Document` and `Issue` NamedTuples, single-pass discovery, functions returning `list[Issue]`, `main()`, explicit check registry. The behavioral contract of Phase 1 is that every error previously detected is still detected, at the same location, with the same message, and no new errors are introduced. If Phase 1 causes a previously-passing file to fail, that is a regression. This constraint allows Phase 1 to be reviewed purely as a refactor without needing to evaluate whether any new validation logic is correct.
|
||||||
|
|
||||||
|
**Phase 2** adds line numbers to all diagnostics via a `_line_of()` helper. This explicitly changes diagnostic output — the same error now includes a line number it did not include before. This is not a behavioral regression, but it is a visible change to the output format. Separating it from Phase 1 means that any output diff between Phase 1 and Phase 2 can be attributed entirely to the addition of line numbers, not to structural changes.
|
||||||
|
|
||||||
|
**Phase 3** replaces both the fence counter and the DOTALL regex with `scan_code_blocks()`. This explicitly changes parsing behavior. Files with ambiguous fence structures may be classified differently. Any new errors surfaced by Phase 3 are genuine new detections, not regressions from Phase 1 or Phase 2. Separating Phase 3 makes that attribution clear.
|
||||||
|
|
||||||
|
The sequencing is designed so that each phase boundary is a stable checkpoint: if the post-Phase-3 state surfaces a false positive, the team can bisect to the phase that introduced it without re-examining the entire change.
|
||||||
|
|
||||||
|
### `scan_code_blocks()` Design
|
||||||
|
|
||||||
|
The linear scanner walks the file line by line. It tracks whether the current line opens a code fence (a line matching the pattern of three or more backticks, optionally followed by a language tag), accumulates lines inside the fence, and emits a `CodeBlock` (offset, language, content) when the matching closing fence is found.
|
||||||
|
|
||||||
|
A linear walker is preferable to a DOTALL regex for two reasons.
|
||||||
|
|
||||||
|
First, the CommonMark spec permits variable-width backtick fences: a fence opened with four backticks closes only on a line containing four or more backticks, not on a line containing three. A DOTALL regex of the form `` ` ``{3}.*?`` ` ``{3} will misparse nested or variable-width fences because the lazy quantifier does not track backtick count. The linear scanner tracks the opening fence width and requires the closing line to match or exceed it, which is the correct CommonMark rule.
|
||||||
|
|
||||||
|
Second, a DOTALL regex applied to the full file string produces a match object with a start and end offset. Translating that offset to a line number requires a second pass over the file to count newlines, or a precomputed offset-to-line index. The linear scanner knows the current line number at each point without additional bookkeeping.
|
||||||
|
|
||||||
|
The cost of the linear scanner is that it is more code than a regex. For a validator script where correctness of the parser matters (the Mermaid bug was directly caused by the parser not knowing what kind of block it was in), that cost is acceptable.
|
||||||
|
|
||||||
|
### `Document.validates_frontmatter` Field
|
||||||
|
|
||||||
|
The `Document` NamedTuple carries a `validates_frontmatter: bool` field populated at discovery time. Files in `inbox/` are exempt from frontmatter enforcement; all other committed documents are not.
|
||||||
|
|
||||||
|
The alternative would be to let each frontmatter validator check the file path itself and skip `inbox/` files inline. This was rejected for two reasons. First, it duplicates the exemption logic across every check that touches frontmatter — if the exemption rule changes (for example, if a new staging directory is added), every check must be updated. Second, it means a check function must inspect the path of the document it is checking, which is knowledge that belongs to discovery, not to validation. The `validates_frontmatter` field moves the policy decision to the single place where it can be maintained: the `discover_documents()` function. Check functions receive a `Document` and operate on its fields without needing to reason about path semantics.
|
||||||
|
|
||||||
|
The tradeoff is that `Document` now carries a field that is not derived from the file's content but from its location. This is a mild violation of the principle that a document object represents only what is in the file. It is justified because the exemption is a property of the document's role in the repository, which is determined by its location, and that property is relevant to multiple downstream checks.
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: resolved
|
||||||
|
project: homelab
|
||||||
|
date: 2026-09-28
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- homelab
|
||||||
|
- migration
|
||||||
|
- systems-design
|
||||||
|
- provenance
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Discussion: Migrating from Legacy Multirepo (v3) to 3-Tier Provenance Architecture (v4)
|
||||||
|
|
||||||
|
## 1. Problem Statement & Historical Context
|
||||||
|
|
||||||
|
The initial architecture of the `roadtotech.me` homelab followed an intuitive multirepo pattern:
|
||||||
|
- The platform host was organized under `/home/kiskaadee/Homelab`.
|
||||||
|
- Core platform capabilities (NixOS, Traefik, Authelia, LLDAP) lived in `Core/`.
|
||||||
|
- Every application workload lived in its own folder under `Sites/<app>/`, where each folder was an independent Git repository cloned from Gitea.
|
||||||
|
- Operational tooling (`appctl`, `homelab-gitops`) interacted directly with these local Git repositories: `appctl` checked Git ahead/behind counts via `git rev-list HEAD...@{u}`, and GitOps deployed changes via `git pull origin main`.
|
||||||
|
|
||||||
|
### Why the Original Model Looked Attractive
|
||||||
|
In the early days of the homelab, the multirepo pattern appeared minimal and elegant:
|
||||||
|
- **One Folder = One Repo**: Developers could `cd ~/Sites/my-app`, edit files, run `git commit`, and push.
|
||||||
|
- **Uniformity**: Every service looked identical to operational tools—they were all Git checkouts containing a `docker-compose.yml` and an `app.yaml`.
|
||||||
|
- **Zero Central Coordination**: Deploying a new service simply meant cloning a new Git repository into `Sites/`.
|
||||||
|
|
||||||
|
### The Concrete Operational Failures
|
||||||
|
As the homelab matured from simple containers to in-house software development, automated CI (`act_runner`), and invariant testing, this coupled model began to break down across five critical areas:
|
||||||
|
|
||||||
|
1. **Source Repository Pollution (`doc2site`, `bitetrack`)**:
|
||||||
|
When developing custom software like `doc2site` (a documentation generator) or `bitetrack` (a nutrition tracking API), the application source code had to live directly inside the deployment repository. This forced private Homelab-specific Traefik labels, Docker bridge network names (`proxy-net`), host bind-mount paths, and environment secrets into the application's source tree.
|
||||||
|
*The Friction*: Hosting infrastructure co-located with code made clean open-sourcing, code sharing, or isolated testing difficult without stripping Homelab configuration.
|
||||||
|
|
||||||
|
2. **Repository Inflation (Off-the-Shelf Applications)**:
|
||||||
|
Standard third-party services like `jellyfin`, `stirling-pdf`, and `snappymail` are distributed as pre-built container images. Yet, under the multirepo model, each required a full standalone Git repository on Gitea simply to track a 20-line `docker-compose.yml` and a small `app.yaml`. Gitea became cluttered with dozens of near-empty repositories whose sole purpose was satisfying the convention that every workload directory had to be an independent Git clone.
|
||||||
|
|
||||||
|
3. **Semantic Ambiguity in `appctl`**:
|
||||||
|
`appctl` determined whether an application was "up to date" by running `git rev-list HEAD...@{u}` inside `Sites/<app>/.git`.
|
||||||
|
*The Blind Spot*: This check could only answer: *"Has someone pushed a change to the deployment configuration files in Git?"* It could never answer:
|
||||||
|
- Is the running container executing the latest release of the application code?
|
||||||
|
- Was the container built from a commit with critical bug fixes?
|
||||||
|
- Has a new upstream image tag been published?
|
||||||
|
Operators were left with a false sense of confidence: `appctl list` would report a green "✓ Up to date" badge even when the running container was running months-old, stale code.
|
||||||
|
|
||||||
|
4. **Conflation of Versioned Descriptors and Mutable State**:
|
||||||
|
Because `Sites/<app>` was a Git checkout, workloads frequently stored runtime state inside `Sites/<app>/data/`. Mutable SQLite databases, session tokens, and dynamic uploads sat right inside the working tree. This dirtied the Git working tree, caused merge conflicts during automated deployments, and increased the risk of accidentally committing sensitive or volatile state to the forge.
|
||||||
|
|
||||||
|
5. **Host-Bound Build Execution**:
|
||||||
|
Because the application repository was cloned directly onto the deployment host, the GitOps dispatcher often triggered `docker compose build` on the server itself. This required installing build tools and runtime compilers on the appliance host, consuming substantial CPU/RAM during builds and violating the principle of a hardened, minimal host appliance.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Context & Analysis: The KISS Principle in Systems Design
|
||||||
|
|
||||||
|
A central architectural debate emerged: **Does moving away from the single-repo pattern introduce unwarranted complexity, or does it represent true systems simplification?**
|
||||||
|
|
||||||
|
In systems engineering, KISS ("Keep It Simple, Stupid") is often misunderstood as "the fewest files" or "the fewest directories." However, shoving fundamentally different concerns into a single directory is not simplicity—it is uncoordinated coupling.
|
||||||
|
|
||||||
|
* **Legacy Multirepo: Simple on Paper, Coupled in Practice**:
|
||||||
|
Treating `Sites/<app>` as both the software repository and the deployment declaration looked simple, but it forced a single Git commit SHA to represent three orthogonal concepts simultaneously: the software source code, the deployment environment configuration, and the runtime state.
|
||||||
|
* **3-Tier Decoupling: Modular Simplicity with Few Primitives**:
|
||||||
|
True systems simplicity is achieved by decoupling into three core tiers connected by intermediate artifacts and an isolated state boundary, where each component has exactly one clear responsibility:
|
||||||
|
- **Software Layer (Tier 1)**: Owns application code, unit tests, and Dockerfiles. Agnostic of Homelab.
|
||||||
|
- **Intermediate Artifacts**: Immutable OCI container images produced by CI, carrying cryptographic provenance (`org.opencontainers.image.revision`).
|
||||||
|
- **Deployment Layer (Tier 2)**: Owns environment manifests and Compose definitions (`~/Sites/*`).
|
||||||
|
- **Platform Layer (Tier 3)**: Owns host lifecycle, edge routing, and operational controllers (`~/Core`).
|
||||||
|
- **Persistent State Root (Filesystem Boundary)**: Owns mutable databases and caches isolated outside Git trees (`~/var/lib/homelab/<app>/`).
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph LEGACY["LEGACY / v3 MODEL (Coupled)"]
|
||||||
|
direction TB
|
||||||
|
L_REPO["Workload Git Repo (Sites/<app>)<br/>• Source Code<br/>• Dockerfile<br/>• Traefik Labels (Homelab)<br/>• Compose File<br/>• Mutable data/ directory"]
|
||||||
|
L_CTL["appctl: inspects Sites/<app>/.git<br/>(Ambiguous status: config vs code?)"]
|
||||||
|
L_HOST["Host Rebuilds Image from Local Git"]
|
||||||
|
L_REPO --> L_HOST
|
||||||
|
L_REPO -.-> L_CTL
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph V4["v4 MODEL (3-Tier & Decoupled)"]
|
||||||
|
direction TB
|
||||||
|
V_SRC["Software Repo (Gitea/GitHub)<br/>• Owns code & tests<br/>• Agnostic of Homelab"]
|
||||||
|
V_CI["CI (Gitea act_runner)<br/>• Builds image<br/>• Injects OCI revision label"]
|
||||||
|
V_SITE["Sites Catalog (~/Sites/<app>)<br/>• app.yaml (Intent & Source Pointer)<br/>• docker-compose.yml"]
|
||||||
|
V_STATE["Persistent State (~/var/lib/homelab/<app>)<br/>• Isolated databases & files"]
|
||||||
|
V_CTL["appctl: Dual-Axis Inspection<br/>• Deployment Git Status<br/>• Software Provenance Resolver"]
|
||||||
|
|
||||||
|
V_SRC --> V_CI --> V_SITE
|
||||||
|
V_SITE --> V_CTL
|
||||||
|
V_STATE -.-> V_SITE
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Evaluated Dilemmas & Rejected Alternatives
|
||||||
|
|
||||||
|
### A. The Upstream Cloning Dilemma: Ahead/Behind Counts vs. `git ls-remote`
|
||||||
|
An initial proposal explored calculating exact commit distance (e.g. `"3 commits behind upstream"`) for source-backed applications.
|
||||||
|
|
||||||
|
* **The Problem**: Git cannot calculate commit distance or ancestry without access to the commit graph. This would require the deployment host to clone or fetch full Git histories for every in-house application.
|
||||||
|
* **Resulting Direction**: The exploration ultimately converged on rejecting local cloning on the appliance host in favor of **commit equality verification via `git ls-remote`**.
|
||||||
|
By querying `git ls-remote <url> refs/heads/<ref>`, the host asks one crisp question: *Does the remote ref match the commit SHA stamped into the container's OCI label?*
|
||||||
|
* **The Trade-Off Rationale**: Foregoing commit distance counts eliminates repository bloat, disk overhead, and credential propagation on the deployment host, providing instant staleness detection with zero on-host git state.
|
||||||
|
|
||||||
|
### B. The Orchestrator Sprawl Dilemma: Miniature Kubernetes vs. Linear Reconciliation
|
||||||
|
Another alternative considered was adopting a dynamic container management architecture modeled after enterprise systems (e.g. RabbitMQ/Redis event queues, a PostgreSQL deployment state store, and background rollback daemons).
|
||||||
|
|
||||||
|
* **The Problem**: A single 24/7 home server cannot justify running complex distributed brokers just to start and stop containers. It increases memory pressure, introduces distributed state split-brain scenarios, and makes disaster recovery painful.
|
||||||
|
* **Resulting Direction**: The exploration ultimately converged on strictly bounding the control path to a **linear, deterministic chain**:
|
||||||
|
$$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl update} \longrightarrow \text{Compose Up}$$
|
||||||
|
* **The Trade-Off Rationale**: `appctl update` operates purely as a local reconciliation primitive. Simplicity is preserved by having zero background daemons managing deployment state.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. What Became Possible After the Architectural Separation
|
||||||
|
|
||||||
|
| Dimension | Legacy Coupled Model (Historical Constraint) | 3-Tier Provenance Model (Engineering Motivation) |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Open Source & Code Sharing** | Hosting infrastructure co-located with code made clean open-sourcing or external sharing cumbersome. | Allows the software repository to remain free of Homelab-specific infrastructure and be tested or open-sourced independently. |
|
||||||
|
| **Off-the-Shelf Workloads** | Deploying third-party apps required creating dummy Git repositories on Gitea to satisfy the workload structure. | Workloads without custom source declare an Image-Only manifest directly in `Sites/` with zero repository overhead. |
|
||||||
|
| **Deployment Truth & Visibility** | Inspection in `appctl` was limited to local working tree status, leaving operators unaware of running container staleness relative to source. | Two operational inspection axes independently report local deployment configuration status and container code provenance. |
|
||||||
|
| **Host Appliance Hygiene** | On-host image compilation consumed appliance resources and mutable runtime data risked dirtying version-controlled directories. | Appliance runtime relies on pre-built container artifacts, with mutable state provisioned strictly under `~/var/lib/homelab/<app>/`. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Convergence & Successors
|
||||||
|
|
||||||
|
This exploratory inquiry resolved the tension between structural simplicity and architectural coupling: true simplicity lies in clear boundaries and minimal control paths, not monolithic folder cramming.
|
||||||
|
|
||||||
|
The exploration converged on the three-tier provenance architecture formalized in the ADR:
|
||||||
|
* **Architectural Decision Record**: [`03-records/decisions/homelab-3tier-architecture-and-provenance.md`](../../03-records/decisions/homelab-3tier-architecture-and-provenance.md)
|
||||||
|
|
||||||
|
The concrete technical specifications, contracts, and phased execution roadmaps (P0 through P5) are specified in the companion plan:
|
||||||
|
* **Authoritative Implementation Plan**: [`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md)
|
||||||
|
* **Homelab Project Hub**: [`06-projects/homelab/README.md`](../../06-projects/homelab/README.md)
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,133 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: resolved
|
||||||
|
project: homelab
|
||||||
|
date: 2026-10-07
|
||||||
|
tags:
|
||||||
|
- homelab
|
||||||
|
- architecture
|
||||||
|
- control-plane
|
||||||
|
- appctl
|
||||||
|
- security
|
||||||
|
- systems-design
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Discussion: Homelab Control Plane Modernization & Separation of Responsibilities
|
||||||
|
|
||||||
|
## 1. Problem Statement & Historical Context
|
||||||
|
|
||||||
|
The `roadtotech.me` homelab historically managed service operations through `appctl`—a local operational harness composed of a Bash wrapper (`scripts/appctl`) and a Python metadata discovery script (`scripts/appctl_engine.py`). Commands such as `up`, `down`, `restart`, `update`, `logs`, and `sync` were invoked directly on the server host, sourcing environment files and credentials from `/run/secrets/`.
|
||||||
|
|
||||||
|
### Why the Legacy Model Looked Attractive
|
||||||
|
In the early stages of the platform, this hybrid model appeared pragmatic and low-friction:
|
||||||
|
- **Immediate Feedback**: Bash provided rapid subprocess orchestration (`docker compose`), while Python handled parsing of manifests (`app.yaml`) and Docker inspection data.
|
||||||
|
- **Minimal Abstraction**: Running commands directly against the local Docker socket and filesystem avoided the overhead of maintaining a persistent background daemon, network listeners, or client-server protocols.
|
||||||
|
- **Convenient Secret Access**: Sourcing `/run/secrets/` directly inside shell scripts made database passwords and API tokens instantly available to Docker commands without writing custom secret resolution layers.
|
||||||
|
|
||||||
|
### Concrete Operational Failures & Friction Points
|
||||||
|
As the homelab expanded to host complex multi-tier services, automated GitOps webhooks, and rigorous linting/testing pipelines, the ad-hoc model exhibited severe architectural strain:
|
||||||
|
1. **Behavioral Drift Across Entry Points**: Different operational consumers—the local developer shell, remote SSH invocations, and the `gitops_dispatcher.py` webhook handler—implemented their own orchestration logic and assumptions. A deployment triggered by a Git webhook could behave differently from the same deployment executed interactively via the CLI.
|
||||||
|
2. **Entangled Failure Modes**: When a deployment failed, diagnosing the root cause required tracing execution across shell functions, subprocess calls, environment variable inheritance, and process exit codes. It was frequently unclear whether a failure stemmed from invalid manifest YAML, missing runtime secrets, Docker daemon errors, or bash string-splitting quirks.
|
||||||
|
3. **Fragile Testing Ergonomics**: Because domain rules (such as identity matching or deployment validation) were intertwined with shell execution, testing a simple business constraint required running against a live host with an active Docker daemon and populated secrets on disk.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Context & Analysis: The Mixing of Responsibilities
|
||||||
|
|
||||||
|
The central architectural breakdown in the legacy model was that **too many distinct responsibilities were mixed together**: domain decisions, process orchestration, operating system execution, and secret access were spread indiscriminately across Python and Bash scripts.
|
||||||
|
|
||||||
|
Modernization is fundamentally about establishing clear, enforceable boundaries between these responsibilities rather than replacing Bash with Python or adding abstractions for their own sake.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph Clients["Consumers (Untrusted Transports)"]
|
||||||
|
CLI["Local CLI"]
|
||||||
|
RemoteCLI["Remote SSH / CLI"]
|
||||||
|
GitOps["GitOps Dispatcher"]
|
||||||
|
UI["Future Operations UI"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph ControlPlane["Control Plane Boundary (appctld)"]
|
||||||
|
Auth["AuthN / AuthZ / Audit"]
|
||||||
|
API["Logical Operations API"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Domain["Typed Domain Engine"]
|
||||||
|
Models["Application & Deployment Models"]
|
||||||
|
Validation["Invariant & Contract Validation"]
|
||||||
|
Reconcile["Desired vs. Runtime Reconciliation"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Execution["Isolated Execution Boundaries"]
|
||||||
|
SecretProvider["SecretProvider Boundary"]
|
||||||
|
FSAdapter["Filesystem Adapter"]
|
||||||
|
ComposeDriver["Compose / Container Driver"]
|
||||||
|
end
|
||||||
|
|
||||||
|
Clients -->|"UDS / mTLS"| ControlPlane
|
||||||
|
ControlPlane --> Domain
|
||||||
|
Domain --> Execution
|
||||||
|
Git[("Authoritative Git State")] -.-> Domain
|
||||||
|
```
|
||||||
|
|
||||||
|
### The Role and Limits of a Daemon
|
||||||
|
Introducing a daemon (`appctld`) does not automatically eliminate operational or security liabilities. Rather, a daemon provides **a single, central place where consistent contracts, authorization rules, auditing, and testing can be enforced**. Without a daemon, every client or script must re-implement and re-verify these guarantees independently.
|
||||||
|
|
||||||
|
### Transport Access vs. Application Authority
|
||||||
|
A critical conceptual error in the legacy setup was confusing host access with application authority:
|
||||||
|
- Sockets and SSH provide *transport reach*—a secure pipe to reach the machine or process.
|
||||||
|
- Transport access should **not** automatically grant permission to deploy, modify, or tear down workloads managed by the platform.
|
||||||
|
|
||||||
|
Having SSH access to the appliance host or permission to connect to a Unix domain socket at `/run/homelab/appctl.sock` answers only whether a process can communicate with the host. It does not answer whether that principal is authorized to perform a specific mutating operation on an application. The control plane must decouple transport from authorization, evaluating explicit policies and generating immutable audit logs.
|
||||||
|
|
||||||
|
### The Real Liability of Secret Handling
|
||||||
|
Sourcing files from `/run/secrets/` is not inherently insecure; the filesystem location itself is not the flaw. The real liability is **how broadly secrets propagate and how difficult it is to enforce least privilege**:
|
||||||
|
- Sourcing a broad secrets file into a shell environment loads sensitive credentials into the parent process environment.
|
||||||
|
- Any child subprocess, debugging trace (`set -x`), environment dump, or logging utility can inadvertently leak those values.
|
||||||
|
- A script executing a routine container restart may end up with ambient access to credentials for completely unrelated databases.
|
||||||
|
|
||||||
|
The required architectural boundary is a dedicated `SecretProvider`. Deployment definitions should contain *references* to secrets rather than raw values, and the domain engine should resolve only the specific credentials required by a targeted workload at the exact moment of execution.
|
||||||
|
|
||||||
|
### Types vs. Runtime Verification
|
||||||
|
A typed domain engine replaces untyped dictionaries and string parsing with validated domain models (e.g. applications, identities, deployment states). This allows invalid inputs to be rejected at the boundary before touching Docker or the filesystem.
|
||||||
|
|
||||||
|
However, types do not guarantee correctness or eliminate the need for testing. Types express invariants and allow consistent enforcement, but they cannot replace integration tests for authentication, socket file permissions, secret protection, or recovery from network/filesystem faults.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Evaluated Dilemmas & Rejected Alternatives
|
||||||
|
|
||||||
|
### Option A: Hardening the Procedural Shell Scripts (Rejected)
|
||||||
|
* **Approach**: Retain the existing Bash scripts, but add strict linters (ShellCheck), defensive error traps (`set -euo pipefail`), and more verbose logging.
|
||||||
|
* **Why it fell short**: Shell scripts cannot represent rich domain models, cannot enforce typed contracts across boundary crossings, and cannot cleanly decouple secret propagation from child process environments. Furthermore, automated unit testing remains dependent on host mocks and subprocess fixtures.
|
||||||
|
|
||||||
|
### Option B: A Monolithic Python Client Executed Directly by Users (Rejected)
|
||||||
|
* **Approach**: Rewrite `appctl` entirely in Python as a single CLI tool that users run directly via `sudo` or as members of the `docker` group.
|
||||||
|
* **Why it fell short**: This retains client-owned execution. Each caller still runs with direct, privileged access to Docker and the filesystem. It fails to provide a uniform entry point for headless GitOps dispatchers, remote clients, and future UIs, and it leaves operational auditing scattered across individual invocation logs.
|
||||||
|
|
||||||
|
### Option C: Treating the Daemon as the Authoritative Source of Truth (Rejected)
|
||||||
|
* **Approach**: Allow the daemon to maintain its own mutable database of deployment configurations and desired state, which operators can update imperatively via API calls.
|
||||||
|
* **Why it fell short**: Git must remain the sole authoritative source of truth for desired deployment state. If the daemon or an interactive client can mutate the desired platform state independently of committed Git descriptors, the system loses reproducible deployments, review provenance, and disaster recovery guarantees. The daemon must reconcile *against* approved Git descriptors, never replace them.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. What Became Possible After the Architectural Separation
|
||||||
|
|
||||||
|
| Architectural Dimension | Legacy Model (`scripts/appctl`) | Modernized Control Plane (`appctld` + Typed Engine) |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Responsibility Boundaries** | Mixed across Bash and Python scripts | Strictly separated: Control Plane $\rightarrow$ Domain Engine $\rightarrow$ Execution Adapters |
|
||||||
|
| **Client Execution** | Client-owned: each script or caller coordinates its own workflow | Centralized: all clients (local CLI, GitOps, UI) call one uniform operations API |
|
||||||
|
| **Authority Model** | Transport access (SSH/host access) conflated with application authority | Transport isolated; mutating actions require explicit authorization and structured audit |
|
||||||
|
| **Secret Scope** | Shell environment sourcing with wide subprocess inheritance | `SecretProvider` resolves specific secret references on demand for the target workload |
|
||||||
|
| **Testing Paradigm** | Required live Docker daemon, host filesystem, and populated secrets | Pure, isolated unit tests for domain models; focused integration tests for auth and runtime |
|
||||||
|
| **Authoritative State** | Split between Git checkouts, shell variables, and running containers | Git remains the sole authoritative source; daemon acts strictly as the reconciliation engine |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Convergence & Successors
|
||||||
|
|
||||||
|
The exploration converged on a clear architectural trajectory: **move operational authority out of scattered scripts and into one explicit, testable control plane (`appctld`) with a typed domain engine, while keeping desired state, authorization, secret access, domain decisions, and runtime execution strictly separated**.
|
||||||
|
|
||||||
|
This exploration informed the formal architectural commitments and implementation phasing recorded in:
|
||||||
|
- **Architectural Decision Record**: [`03-records/decisions/homelab-appctl-control-plane-architecture.md`](../../03-records/decisions/homelab-appctl-control-plane-architecture.md) — Formally adopts the daemon control plane, typed metadata engine, Unix domain socket transport, and `SecretProvider` boundary.
|
||||||
|
- **Implementation Roadmap**: [`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md) — Organizes the migration and locked P4 daemon boundaries (`DEC-01`–`DEC-05`) into concrete phases (P0 through P7).
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
project: homelab
|
||||||
|
date: 2026-09-23
|
||||||
|
tags:
|
||||||
|
- homelab
|
||||||
|
- architecture
|
||||||
|
- core
|
||||||
|
- portainer
|
||||||
|
- gitea
|
||||||
|
- deprecation
|
||||||
|
---
|
||||||
|
|
||||||
|
# Core Service Qualification & Portainer Deprecation
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
As part of ongoing architectural reflection and preparation for homelab consolidation, two critical components required architectural classification:
|
||||||
|
1. **Portainer**: What is its role in the project architecture? It was inherited early on, broke silently across iterations (only surfaced via Dozzle logs), and sits idle. Does Portainer solve an actual problem in this ecosystem, or should it be deprecated?
|
||||||
|
2. **Gitea & Runner**: Should Gitea and its CI runner be moved from standalone applications (`Sites/gitea`) into `Core` alongside platform services, or remain decoupled?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architectural Analysis & Inquiries
|
||||||
|
|
||||||
|
### 1. What Qualifies a Service for Core Ownership?
|
||||||
|
|
||||||
|
A component does not acquire platform status merely because it is placed in the platform compose stack, nor because it sits "close to" multiple applications.
|
||||||
|
|
||||||
|
Rather, a service qualifies for **Core** if:
|
||||||
|
* It provides foundational host lifecycle, container isolation, or network/routing primitives (NixOS, systemd, Traefik, `socket-proxy`).
|
||||||
|
* It provides identity, authentication, or secrets infrastructure (Authelia, LLDAP, SOPS).
|
||||||
|
* It provides a cross-cutting platform capability that the ecosystem inherently depends upon (Mail delivery via Stalwart, central service catalog via Homepage, log inspection via Dozzle).
|
||||||
|
|
||||||
|
Services that do not own an indispensable, cross-cutting responsibility in the system's operational model do not belong in Core.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. Case Evaluation: Portainer
|
||||||
|
|
||||||
|
#### The Operational Reality
|
||||||
|
* Portainer was inherited during early Core consolidation.
|
||||||
|
* Architecturally, the Docker daemon access was deliberately hardened by introducing `socket-proxy` with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`.
|
||||||
|
* Portainer’s primary reason for being is **active container management and mutation via the Docker API**. With a hardened read-only proxy, Portainer cannot manage, create, restart, or alter containers without weakening the security boundary.
|
||||||
|
* The homelab's management philosophy is strictly **declarative and GitOps-driven**:
|
||||||
|
- `appctl` orchestrates workloads and lifecycle from Git.
|
||||||
|
- Automated webhooks trigger deployments via `gitops_dispatcher`.
|
||||||
|
- Traefik dynamically discovers routes.
|
||||||
|
- Dozzle provides real-time container log observation.
|
||||||
|
- Homepage catalogs services and links.
|
||||||
|
* Any manual GUI modification done through Portainer violates repository state and breaks declarative invariants.
|
||||||
|
|
||||||
|
#### Conclusion
|
||||||
|
Portainer owns no unique operational responsibility that another tool does not already own better. Therefore, Portainer is slated for clean deprecation and complete removal across the codebase and runtime.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. Case Evaluation: Gitea vs. The CI Runner
|
||||||
|
|
||||||
|
#### Gitea Forge
|
||||||
|
* Gitea provides source code control, webhook emission for GitOps, and package/code hosting.
|
||||||
|
* While Gitea is central to self-hosting, the homelab's GitOps dispatcher is forge-agnostic (it processes webhooks whether they originate from Gitea or GitHub).
|
||||||
|
* Moving Gitea into Core introduces bootstrap questions (recovering Core when Core depends on Gitea for its repository).
|
||||||
|
* Keeping Gitea capable of bootstrapping independently ensures high operational resilience.
|
||||||
|
|
||||||
|
#### The CI Runner (`act_runner`)
|
||||||
|
* Even if Gitea were considered developer infrastructure, **the CI runner is an entirely separate security domain**.
|
||||||
|
* The runner executes arbitrary, repository-controlled code and requires execution privileges (Docker-in-Docker or host socket mounts).
|
||||||
|
* Merging the runner into Core would violate the principle of least privilege for platform-trusted infrastructure.
|
||||||
|
|
||||||
|
#### Conclusion
|
||||||
|
Both Gitea and the Gitea Runner will remain separate from `Core` for the present, retaining their standalone workload boundaries under `Sites/gitea`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Consensus & Decisions
|
||||||
|
|
||||||
|
1. **Deprecate Portainer cleanly**:
|
||||||
|
- Remove from `Core/docker-compose.yml` (service and volume).
|
||||||
|
- Remove from `Core/nixos/modules/homeserver.nix` and prune `portainer.admin_password` from `Core/nixos/secrets.yaml`.
|
||||||
|
- Remove from `Core/scripts/appctl_engine.py` and `Core/config/homepage/services.yaml`.
|
||||||
|
- Add regression/absence invariant test in `Core/tests/security/test_security_invariants.py`.
|
||||||
|
- Clean up documentation references across Core.
|
||||||
|
- Purge residual Docker data volumes on the server post-deployment.
|
||||||
|
2. **Preserve Isolation for Gitea and Runner**:
|
||||||
|
- Keep Gitea and `act_runner` decoupled in `Sites/gitea`.
|
||||||
|
- Revisit developer infrastructure taxonomy during future architecture consolidation phases.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Related Documentation & Plans
|
||||||
|
|
||||||
|
* Implementation Plan: [portainer-deprecation-plan.md](../../01-plans/homelab/portainer-deprecation-plan.md)
|
||||||
|
* Security Invariants: `Core/tests/security/test_security_invariants.py`
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
project: homelab
|
||||||
|
date: 2026-09-23
|
||||||
|
tags:
|
||||||
|
- homelab
|
||||||
|
- dozzle
|
||||||
|
- auth
|
||||||
|
- authelia
|
||||||
|
- forward-proxy
|
||||||
|
- storage
|
||||||
|
---
|
||||||
|
|
||||||
|
# Dozzle Authentication & Storage Architecture Recommendation
|
||||||
|
|
||||||
|
> [!NOTE] Status: Implemented
|
||||||
|
> Implemented in homelab Core repository (`docker-compose.yml`) via commit `22d3a649eae9166d03a12358e5e5058070b05888` on 2026-09-23.
|
||||||
|
|
||||||
|
```shell
|
||||||
|
commit 22d3a649eae9166d03a12358e5e5058070b05888
|
||||||
|
Author: kiskaadee <fcortesbio@gmail.com>
|
||||||
|
Date: Wed Sep 23 12:09:13 2026 -0500
|
||||||
|
|
||||||
|
feat(dozzle): configure forward-proxy authentication and persistent data volume
|
||||||
|
|
||||||
|
- Enable DOZZLE_AUTH_PROVIDER=forward-proxy to natively ingest identity
|
||||||
|
headers (Remote-User, Remote-Email, Remote-Name) injected by Authelia.
|
||||||
|
|
||||||
|
- Set DOZZLE_AUTH_LOGOUT_URL to wire the UI logout button to the SSO
|
||||||
|
provider. Mount the persistent named volume dozzle_data to /data to
|
||||||
|
preserve user settings and UI preferences across container lifecycles.
|
||||||
|
|
||||||
|
diff --git a/docker-compose.yml b/docker-compose.yml
|
||||||
|
index 3d3055d..d42b5ac 100644
|
||||||
|
--- a/docker-compose.yml
|
||||||
|
+++ b/docker-compose.yml
|
||||||
|
@@ -196,6 +196,10 @@ services:
|
||||||
|
environment:
|
||||||
|
- DOCKER_HOST=tcp://socket-proxy:2375
|
||||||
|
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
|
||||||
|
+ - DOZZLE_AUTH_PROVIDER=forward-proxy
|
||||||
|
+ - DOZZLE_AUTH_LOGOUT_URL=https://auth.${DOMAIN}/logout
|
||||||
|
+ volumes:
|
||||||
|
+ - dozzle_data:/data
|
||||||
|
networks:
|
||||||
|
- proxy-net
|
||||||
|
- socket-net
|
||||||
|
@@ -351,3 +355,5 @@ networks:
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
portainer_data:
|
||||||
|
+ dozzle_data:
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context & Symptoms
|
||||||
|
|
||||||
|
Following a recent Dozzle image update, accessing `logs.roadtotech.me` presents a first-run setup wizard:
|
||||||
|
1. **"Turn on login"**: *"Anyone who can reach Dozzle can read your logs. Lock it down before anything else."*
|
||||||
|
2. **"/data is not mounted"**: *"Users and settings are saved to /data. Without a volume they are gone the next time the container is recreated."*
|
||||||
|
|
||||||
|
Currently, Dozzle is protected at the edge by Traefik using the `authelia-auth@docker` ForwardAuth middleware, backed by LLDAP.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architectural Evaluation of Options
|
||||||
|
|
||||||
|
### Option 1: Remove Authelia, Set Up Internal Login & Connect to LLDAP
|
||||||
|
* **Feasibility**: **Not natively supported.** Dozzle does not have an LDAP client. Its supported authentication providers (`DOZZLE_AUTH_PROVIDER`) are strictly:
|
||||||
|
* `none` (default, no authentication)
|
||||||
|
* `simple` (flat file `users.yml` or OIDC client credentials)
|
||||||
|
* `forward-proxy` (trusts reverse proxy authentication headers)
|
||||||
|
* **Security & Operability**: Removing Authelia would downgrade homelab security. It would eliminate centralized Single Sign-On (SSO), two-factor authentication (TOTP/WebAuthn), and uniform session management across `*.roadtotech.me`.
|
||||||
|
* **Verdict**: **Anti-pattern and technically unworkable** without introducing an intermediate OIDC bridge.
|
||||||
|
|
||||||
|
### Option 2: "Let It Be" (Dismiss the Wizard / Continue Without Login)
|
||||||
|
* **Feasibility**: Works for basic log viewing, but with ongoing friction.
|
||||||
|
* **Drawbacks**:
|
||||||
|
* Clicking "Continue without login" leaves Dozzle in unauthenticated mode.
|
||||||
|
* Because `/data` is ephemeral, user preferences (pinned containers, search regexes, custom stream filters, UI themes) are wiped on every container restart or image update.
|
||||||
|
* The setup banner or modal may re-appear across different browser sessions.
|
||||||
|
* Dozzle remains unaware of the authenticated user identity passed by Authelia.
|
||||||
|
* **Verdict**: Suboptimal band-aid.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The First-Grade Solution: Forward-Proxy Mode + Persistent Volume
|
||||||
|
|
||||||
|
The industry-standard, cleanest pattern for this architecture is **Forward-Proxy Authentication (`DOZZLE_AUTH_PROVIDER=forward-proxy`) paired with a persistent `/data` volume**.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
User["Browser Client"] -->|HTTPS Request| Traefik["Traefik Reverse Proxy"]
|
||||||
|
Traefik -->|ForwardAuth Check| Authelia["Authelia (SSO / MFA)"]
|
||||||
|
Authelia -->|Authenticate| LLDAP["LLDAP Directory"]
|
||||||
|
Authelia --"200 OK + Remote-User headers"--> Traefik
|
||||||
|
Traefik -->|"HTTP + Remote-User, Remote-Email, Remote-Name"| Dozzle["Dozzle Container<br/>(DOZZLE_AUTH_PROVIDER=forward-proxy)"]
|
||||||
|
Dozzle --> Storage[("Named Volume: dozzle_data<br/>(/data)")]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Why this is the First-Grade Solution
|
||||||
|
|
||||||
|
1. **Native ForwardAuth Ingestion**:
|
||||||
|
In `Core/docker-compose.yml`, Traefik's `authelia-auth` middleware is already configured with:
|
||||||
|
```yaml
|
||||||
|
traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name
|
||||||
|
```
|
||||||
|
Dozzle's `forward-proxy` mode is purpose-built to read these exact headers (`Remote-User`, `Remote-Name`, `Remote-Email`).
|
||||||
|
|
||||||
|
2. **Zero Duplicate Logins & Single Sign-On**:
|
||||||
|
When you authenticate through Authelia using your LLDAP credentials, Traefik injects your user headers into the upstream request. Dozzle consumes them automatically. You are immediately logged into Dozzle under your LLDAP identity with your avatar and name, without seeing any login prompt or wizard.
|
||||||
|
|
||||||
|
3. **Persistent User State**:
|
||||||
|
Mounting a named volume to `/data` gives Dozzle a durable store for:
|
||||||
|
* Pinned and favorited containers
|
||||||
|
* Custom log search queries and filters
|
||||||
|
* UI display preferences
|
||||||
|
* Session state across Watchtower / image updates
|
||||||
|
|
||||||
|
4. **Clean Logout Lifecycle**:
|
||||||
|
Configuring `DOZZLE_AUTH_LOGOUT_URL=https://auth.${DOMAIN}/logout` wires Dozzle's logout button directly into Authelia's single-sign-out endpoint.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Declarative Changes Required
|
||||||
|
|
||||||
|
Only two declarative modifications are needed in `Core/docker-compose.yml`:
|
||||||
|
|
||||||
|
```diff
|
||||||
|
dozzle:
|
||||||
|
image: amir20/dozzle:latest
|
||||||
|
container_name: dozzle
|
||||||
|
restart: always
|
||||||
|
environment:
|
||||||
|
- DOCKER_HOST=tcp://socket-proxy:2375
|
||||||
|
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
|
||||||
|
+ - DOZZLE_AUTH_PROVIDER=forward-proxy
|
||||||
|
+ - DOZZLE_AUTH_LOGOUT_URL=https://auth.${DOMAIN}/logout
|
||||||
|
+ volumes:
|
||||||
|
+ - dozzle_data:/data
|
||||||
|
networks:
|
||||||
|
- proxy-net
|
||||||
|
- socket-net
|
||||||
|
labels:
|
||||||
|
- "traefik.enable=true"
|
||||||
|
...
|
||||||
|
volumes:
|
||||||
|
portainer_data:
|
||||||
|
+ dozzle_data:
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Summary & Recommendation
|
||||||
|
|
||||||
|
| Criteria | Connect Dozzle to LLDAP directly | Leave As-Is (No change) | Forward-Proxy + Persistent Volume (Recommended) |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Supported by Dozzle** | ❌ No (No LDAP client) | ⚠️ Partial (Unconfigured state) | Yes (First-class native feature) |
|
||||||
|
| **Setup Complexity** | ❌ Requires OIDC provider setup | Zero effort | Low (2 environment variables + 1 volume) |
|
||||||
|
| **User Experience** | Fragmented login | Repeated setup prompt / lost settings | Seamless SSO, user avatar, persistent preferences |
|
||||||
|
| **Security Posture** | Potential exposure | Protected by Authelia edge | Defense-in-depth: Authelia edge + Dozzle identity context |
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,163 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: open
|
||||||
|
project: homelab
|
||||||
|
date: 2026-09-29
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- homelab
|
||||||
|
- houston
|
||||||
|
- authelia
|
||||||
|
- lldap
|
||||||
|
- docker
|
||||||
|
- dynamic-spawning
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Discussion: Multi-User Houston Architecture via Dynamic Container Spawner and LLDAP/Authelia
|
||||||
|
|
||||||
|
## 1. Problem Statement & Context
|
||||||
|
|
||||||
|
Houston is designed around a single shared engine runtime (`packages/runtime`) and host (`packages/host`). In the self-hosted appliance container (`ghcr.io/gethouston/houston-engine-pod`), the engine runs as a single-tenant daemon:
|
||||||
|
* All agent state, SQLite databases, memory, skills, and routines reside in a single shared directory tree (`/data/workspaces/`).
|
||||||
|
* API authorization is governed by a single static shared secret (`HOUSTON_HOST_TOKEN`).
|
||||||
|
* The engine does not implement internal user tables, access control lists (ACLs), or directory service protocols (LDAP, OIDC, SAML).
|
||||||
|
|
||||||
|
In a homelab environment where central identity is governed by **LLDAP** and authenticated via **Authelia** (through Traefik forward-auth), deploying Houston as a shared multi-user service presents an architectural challenge:
|
||||||
|
|
||||||
|
1. **Lack of Isolation in Shared Deployments**: If multiple users access a single self-hosted Houston instance through Authelia, all users inevitably share the same workspaces, conversation history, API keys, and background routines.
|
||||||
|
2. **Headless Engine vs. Graphical Interface**: The official container image (`houston-engine-pod`) provides only the headless HTTP/SSE/WebSocket server on port 4318; it does not serve the web frontend (`packages/web`) out of the box.
|
||||||
|
3. **Manual Provisioning Friction**: Manually pre-configuring distinct container definitions in `docker-compose.yml` for every family or team member in LLDAP introduces administrative overhead and wastes system memory on idle daemons.
|
||||||
|
|
||||||
|
The goal of this inquiry is to explore an architecture that turns a self-hosted Houston deployment into an automated, multi-user appliance where authenticated users automatically receive their own isolated agent runtime on their first login.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Context & Analysis: Core Dilemmas
|
||||||
|
|
||||||
|
### A. Single-Tenant Engine vs. Multi-User Demands
|
||||||
|
Houston Cloud resolves multi-tenancy not by making the engine multi-tenant internally, but through an external Go-based Gateway that manages Kubernetes pods and PVCs on a per-user/per-agent basis. In a Docker-based homelab, Kubernetes is disproportionate; however, the fundamental design principle remains valid: **isolation at the container boundary rather than inside the application code**.
|
||||||
|
|
||||||
|
### B. Identity Brokering & Token Concealment
|
||||||
|
Authelia authenticates users against LLDAP and injects identity headers (`Remote-User`, `Remote-Email`, `Remote-Groups`) downstream into Traefik. However, Houston’s REST/WebSocket endpoints require an `Authorization: Bearer <token>` header matching `HOUSTON_HOST_TOKEN`. Asking users to manually copy and paste backend tokens into the web UI compromises the consumer user experience and breaks zero-touch onboarding. The proxy tier must bridge this gap by acting as an identity broker.
|
||||||
|
|
||||||
|
### C. Resource Contention vs. Always-On Routines
|
||||||
|
Each Houston engine instance runs a Node.js process and spawns pi agent runtimes lazily. While baseline memory consumption is relatively modest (~60–80 MB idle), running dozens of static containers continuously consumes system RAM. A dynamic lifecycle model (Scale-to-Zero after inactivity) must be balanced against Houston's background routine scheduler (`packages/host/src/schedule/scheduler.ts`), which requires running containers to execute scheduled tasks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Evaluated Approaches & Rejected Alternatives
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph Traffic ["Ingress Traffic"]
|
||||||
|
Req["User Request (HTTPS)"]
|
||||||
|
T["Traefik Ingress"]
|
||||||
|
A["Authelia (LLDAP)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Evaluation ["Architectural Options"]
|
||||||
|
OptA["Option A: Static Multi-Service Compose"]
|
||||||
|
OptB["Option B: Shared Single-Instance Engine"]
|
||||||
|
OptC["Option C: Dynamic Container Spawner / Gateway"]
|
||||||
|
end
|
||||||
|
|
||||||
|
Req --> T
|
||||||
|
T <--> A
|
||||||
|
T --> OptA
|
||||||
|
T --> OptB
|
||||||
|
T --> OptC
|
||||||
|
|
||||||
|
OptA -.->|"High maintenance / No auto-provisioning"| RejA["Rejected as Primary"]
|
||||||
|
OptB -.->|"Zero privacy / Shared credentials"| RejB["Rejected for Security"]
|
||||||
|
OptC -->|"Convergent: Self-service & Clean isolation"| AccC["Preferred Direction"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option A: Static Pre-Allocated Services in Docker Compose
|
||||||
|
* **Description**: Pre-define a dedicated service in `docker-compose.yml` for each user (`houston-alice`, `houston-bob`), mapping distinct volumes (`/data/alice`, `/data/bob`) and distinct subdomains with Traefik router rules.
|
||||||
|
* **Limitations**:
|
||||||
|
- No self-service: Adding a user in LLDAP requires manual edits to `docker-compose.yml`, recreating the stack, and configuring DNS/Traefik rules.
|
||||||
|
- Idle resource consumption: Containers run indefinitely regardless of user activity.
|
||||||
|
- Stiff coupling between directory accounts and infrastructure manifests.
|
||||||
|
|
||||||
|
### Option B: Shared Engine Instance with Forward-Auth Gate
|
||||||
|
* **Description**: Place a single `houston-engine-pod` behind Traefik + Authelia. Any valid LLDAP user passes authentication and reaches the app.
|
||||||
|
* **Limitations**:
|
||||||
|
- Complete absence of privacy: All authenticated users read and modify the same agents, files, and chat logs.
|
||||||
|
- Security risk: Connected app credentials (e.g., personal Gmail or GitHub tokens) become accessible to all authenticated directory members.
|
||||||
|
|
||||||
|
### Option C: Dynamic Container Spawner & Identity Gateway (Convergent Pattern)
|
||||||
|
* **Description**: Introduce a lightweight gateway service that mounts `/var/run/docker.sock`, serves the static frontend SPA, and acts as an intelligent reverse proxy.
|
||||||
|
* **Mechanism**:
|
||||||
|
1. Traefik verifies the user session against Authelia and passes `Remote-User: <username>` to the Gateway.
|
||||||
|
2. The Gateway inspects Docker via Docker API/socket:
|
||||||
|
- If `houston-<username>` does not exist: Automatically initializes `/data/users/<username>`, generates a per-user internal secret, and spawns the container connected to `proxy-net`.
|
||||||
|
- If the container exists but is stopped: Starts the container.
|
||||||
|
3. The Gateway proxies the HTTP/SSE/WebSocket traffic to `http://houston-<username>:4318`, transparently injecting the user's specific bearer token.
|
||||||
|
* **Precedents**: Matches the battle-tested architecture of JupyterHub (`dockerspawner`) and Coder workspaces.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. What Becomes Possible After Architectural Separation
|
||||||
|
|
||||||
|
| Dimension | Option B (Shared Monolith) | Option C (Dynamic Spawner Gateway) |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Privacy & Multi-Tenancy** | Zero isolation; shared agent pool. | Strict sandbox isolation; private `/data` volumes per user. |
|
||||||
|
| **Onboarding Experience** | Manual configuration per user. | Zero-touch; account created on first LLDAP login via Authelia. |
|
||||||
|
| **Credential Management** | Shared LLM API keys. | Users configure their own provider keys or local Ollama endpoints. |
|
||||||
|
| **Resource Efficiency** | Low memory, but single point of failure. | Scale-to-zero capable; inactive user engines can be idled. |
|
||||||
|
| **Upstream Compatibility** | Requires intrusive code changes to host. | 100% upstream compatible; uses official unmodified `engine-pod` images. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Architectural Blueprint: The Spawner Gateway
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
autonumber
|
||||||
|
actor User as Client Browser
|
||||||
|
participant T as Traefik
|
||||||
|
participant A as Authelia (LLDAP)
|
||||||
|
participant GW as Houston Spawner Gateway
|
||||||
|
participant D as Docker Engine (docker.sock)
|
||||||
|
participant Engine as User Engine (houston-username)
|
||||||
|
|
||||||
|
User->>T: GET https://houston.roadtotech.me
|
||||||
|
T->>A: Forward-Auth Check
|
||||||
|
A-->>T: 200 OK (Remote-User: kiskaadee)
|
||||||
|
T->>GW: Forward Request (Headers: Remote-User: kiskaadee)
|
||||||
|
|
||||||
|
alt Initial User Visit
|
||||||
|
GW->>D: Inspect Container "houston-kiskaadee"
|
||||||
|
D-->>GW: Not Found
|
||||||
|
GW->>D: Create volume /data/kiskaadee + docker run houston-kiskaadee
|
||||||
|
D-->>GW: Container running on port 4318
|
||||||
|
else Existing Container Stopped
|
||||||
|
GW->>D: docker start houston-kiskaadee
|
||||||
|
D-->>GW: Container awake
|
||||||
|
end
|
||||||
|
|
||||||
|
GW->>Engine: Reverse Proxy (inject Authorization: Bearer <user_token>)
|
||||||
|
Engine-->>GW: Stream /v1/events & HTTP responses
|
||||||
|
GW-->>User: Deliver Web UI & Realtime Agent State
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key Responsibilities of the Spawner Gateway
|
||||||
|
1. **Static Web Serving**: Serves the compiled `packages/web` bundle on root (`/`) with client-side routing fallback (`try_files index.html`).
|
||||||
|
2. **Dynamic Provisioning Engine**:
|
||||||
|
- Sanitizes `Remote-User` to prevent path traversal or invalid container names (`[a-zA-Z0-9_-]+`).
|
||||||
|
- Maintains a lightweight state mapping (SQLite or JSON in gateway volume) recording user tokens and last-active timestamps.
|
||||||
|
- Interacts with Docker daemon through a Unix socket library (e.g., `dockerode` in Node.js or `moby/client` in Go).
|
||||||
|
3. **Full Protocol Proxying**:
|
||||||
|
- Streams SSE connections (`/v1/events`, `/agents/:slug/events`) without buffer delays (`flush_interval: -1`).
|
||||||
|
- Upgrades WebSocket connections (`/v1/ws`).
|
||||||
|
- Rewrites authentication headers so the frontend operates without credential configuration cards.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Convergence & Successors
|
||||||
|
|
||||||
|
This discussion establishes that dynamic container spawning at the reverse proxy layer is the cleanest architectural fit for running Houston multi-user with LLDAP in a homelab environment. It achieves parity with Houston Cloud's pod isolation without mutating upstream source code.
|
||||||
|
|
||||||
|
* **Successor Artifacts**:
|
||||||
|
- **ADR**: Define the formal architectural commitment to the Spawner Gateway pattern, selecting the implementation language and proxy engine (e.g., Node.js + `http-proxy` + `dockerode`).
|
||||||
|
- **Plan**: Create the implementation specification in `01-plans/homelab/houston-spawner-gateway-implementation.md` detailing the Docker Compose configuration, Traefik labels, volume hierarchy, and idle reaping policy.
|
||||||
File renamed without changes.
@@ -0,0 +1,136 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: open
|
||||||
|
project: homelab
|
||||||
|
date: 2026-10-21
|
||||||
|
tags:
|
||||||
|
- homelab
|
||||||
|
- mcp
|
||||||
|
- architecture
|
||||||
|
- gitops
|
||||||
|
- orchestration
|
||||||
|
- state-management
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Discussion: MCP Tool Gateway, State Boundaries, and Homelab Governance Evolution
|
||||||
|
|
||||||
|
## 1. Problem Statement & Historical Context
|
||||||
|
|
||||||
|
Platform orchestration for the homelab appliance (`roadtotech.me`) has historically centered around a bespoke command-line interface (`appctl`), declarative workload manifests (`app.yaml`), and manual or script-driven agent interactions. As AI-assisted development and operations became central to the workstation workflow, earlier planning explored creating specialized deployment-authoring AI agents to bridge natural language requests with homelab operational state.
|
||||||
|
|
||||||
|
During operational mitigation work on dynamic DNS infrastructure, an inspection of Hostinger's MCP (Model Context Protocol) integration revealed an alternative design pattern: exposing platform management capabilities through a standardized, protocol-level MCP server rather than encapsulating operational knowledge inside customized, monolithic AI agents.
|
||||||
|
|
||||||
|
Simultaneously, practical experience with cross-repository governance in the *Armonía del Ser* project (leveraging an organizational `.profile` repository for centralized documentation, cross-referencing milestones, and issue tracking) surfaced questions about whether the homelab appliance should evolve toward a similar multi-repository organizational structure, adopt an operational database alongside or in place of `app.yaml`, and rebrand away from the generic "Homelab" moniker.
|
||||||
|
|
||||||
|
Because the active architecture consolidation roadmap is fixed, this discussion explores the trade-offs, conceptual boundaries, and architectural implications of these ideas to preserve the reasoning without disrupting immediate operational priorities.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Context & Analysis: Core Dilemmas
|
||||||
|
|
||||||
|
### A. Dedicated Deployment Agent vs. Standardized Protocol Gateway (MCP)
|
||||||
|
|
||||||
|
A common design instinct in AI tooling is to build dedicated, domain-specific autonomous agents (prompt harnesses, memory stores, and custom agent loops). However, this introduces substantial architectural coupling:
|
||||||
|
|
||||||
|
1. **Model Lock-In**: The orchestration system becomes tied to specific agent frameworks or model APIs. If a new or more capable model arrives (e.g., local models via Ollama, Claude Code, Antigravity, or Cursor), the custom agent must be re-engineered.
|
||||||
|
2. **Loss of Determinism**: When an agent directly writes deployment scripts or runs arbitrary SSH commands, operational safety invariants become difficult to enforce consistently.
|
||||||
|
|
||||||
|
An **MCP Gateway** shifts the boundary:
|
||||||
|
* `appctl` remains the deterministic, testable Python engine enforcing schemas, execution policies, and system-level boundaries.
|
||||||
|
* The MCP server serves strictly as a protocol adapter exposing structured tools (`appctl_status`, `appctl_logs`, `appctl_audit`, `appctl_verify_workload`) over JSON-RPC.
|
||||||
|
* The model/client layer remains completely decoupled: the developer selects whichever AI assistant or model they prefer, while the MCP server enforces schema validation and tool boundaries.
|
||||||
|
|
||||||
|
```
|
||||||
|
+-------------------------------------------------------------+
|
||||||
|
| Client & Model Layer (Decoupled) |
|
||||||
|
| (Antigravity IDE / Claude Code / Cursor / Local LLM) |
|
||||||
|
+------------------------------+------------------------------+
|
||||||
|
| Model Context Protocol (JSON-RPC)
|
||||||
|
+------------------------------v------------------------------+
|
||||||
|
| Homelab MCP Server |
|
||||||
|
| (Tool Definitions, Resource Providers, Schema Guards) |
|
||||||
|
+------------------------------+------------------------------+
|
||||||
|
| Local invocation
|
||||||
|
+------------------------------v------------------------------+
|
||||||
|
| Platform Engine (appctl) |
|
||||||
|
| (Validation, Manifest Parser, Compose Orchestration) |
|
||||||
|
+------------------------------+------------------------------+
|
||||||
|
| Runtime operations
|
||||||
|
+------------------------------v------------------------------+
|
||||||
|
| Appliance Runtime Host |
|
||||||
|
| (Docker Engine, Traefik, NixOS Core) |
|
||||||
|
+-------------------------------------------------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
### B. Declarative GitOps (`app.yaml`) vs. Operational Database
|
||||||
|
|
||||||
|
Earlier discussions considered whether to replace workload `app.yaml` files with a centralized database (such as SQLite, PostgreSQL, or Turso). Evaluating this requires distinguishing between two fundamentally different types of state:
|
||||||
|
|
||||||
|
1. **Desired State (What the system *should* be)**:
|
||||||
|
* Attributes: Subdomains, container images, port exposures, Traefik middleware requirements, branch policies.
|
||||||
|
* *Best suited for Git*: Git provides immutable commit history, line-by-line attribution (`git blame`), branch isolation, pull-request reviewability, and effortless rollback via `git revert`. Moving desired state into a database forfeits native GitOps workflows and offline local reproducibility.
|
||||||
|
2. **Observed & Telemetry State (What the system *currently is*)**:
|
||||||
|
* Attributes: Deployment run timestamps, exit codes, health check latency, uptime metrics, error logs, audit trail of which user or agent invoked actions.
|
||||||
|
* *Best suited for a Database*: Querying across twenty workload YAML files to answer historical questions ("When did SnappyMail last deploy?", "Which workloads failed health checks this week?") is awkward in Git. A lightweight SQLite or LibSQL store on `Core` provides relational indexing and rapid querying for status dashboards or `appctl list` caching without compromising declarative Git invariants.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Evaluated Dilemmas & Rejected Alternatives
|
||||||
|
|
||||||
|
### Option 1: Autonomous Deployment AI Agent
|
||||||
|
* **Attempted Purpose**: Automate end-to-end workload provisioning and deployment drafting via a dedicated LLM agent.
|
||||||
|
* **Friction & Failure Mode**: Bypasses the operational safety boundaries established in the platform guidelines (which mandate human ownership of production deployments and atomic commit proposals). Custom agent frameworks also require constant maintenance as LLM interfaces evolve.
|
||||||
|
* **Trade-off Rationale**: Set aside in favor of a standard MCP server wrapping deterministic `appctl` verbs. The MCP protocol natively supports tool confirmation and schema validation, preserving human approval boundaries while remaining client-agnostic.
|
||||||
|
|
||||||
|
### Option 2: Replacing `app.yaml` Entirely with a Central Application Database
|
||||||
|
* **Attempted Purpose**: Provide a single CRUD API for all application metadata, eliminating manual YAML editing and synchronization scripts.
|
||||||
|
* **Friction & Failure Mode**: Breaks GitOps invariants. When an outage occurs or a bad configuration deploys, rolling back requires database rollbacks or transaction replays rather than standard Git operations. It also prevents developers from validating configurations locally in isolated Git branches before touching production.
|
||||||
|
* **Trade-off Rationale**: Rejected for desired state. Retained solely as a prospective approach for *observed runtime telemetry* (deployment history, health metrics, and audit logging).
|
||||||
|
|
||||||
|
### Option 3: Monolithic Appliance Repository vs. Multi-Repo Governance with `.profile`
|
||||||
|
* **Attempted Purpose**: Keeping all workloads and Core configurations tightly coupled in a single repository tree.
|
||||||
|
* **Friction & Failure Mode**: Shared commit histories blur ownership, increase CI trigger noise, and complicate cross-project roadmapping.
|
||||||
|
* **Trade-off Rationale**: The organizational pattern validated in *Armonía del Ser*—using a top-level `.profile` repository for global architecture, roadmaps, and cross-cutting milestones alongside dedicated repositories for workloads—offers clean domain isolation while retaining unified platform visibility.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. What Became Possible After the Architectural Separation
|
||||||
|
|
||||||
|
| Dimension | Monolithic / Agent-Centric Model | Decoupled MCP & Tiered State Model |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Model Portability** | Coupled to bespoke agent code and prompt templates. | Client-agnostic: any MCP-compatible agent interacts via standard JSON-RPC tools. |
|
||||||
|
| **Operational Safety** | Agent executes ad-hoc commands or shell scripts. | Agent invokes strictly typed `appctl` tools with predictable failure modes and approval prompts. |
|
||||||
|
| **Desired State Authority** | Risk of split-brain between database records and Git files. | Git remains the sole authority for desired state (`app.yaml` + Compose). |
|
||||||
|
| **Telemetry & Auditing** | Grepping decentralized logs across containers. | Optional operational SQLite database records deployment events and health telemetry. |
|
||||||
|
| **Platform Governance** | Single repo tracking disparate concerns. | Organization structure with `.profile` meta-repo coordinating independent workload repos. |
|
||||||
|
|
||||||
|
### Rebranding Opportunities
|
||||||
|
The generic name "Homelab" reflects a hardware/hobbyist categorization rather than the platform's actual identity as a personal edge application cloud. Potential directions include:
|
||||||
|
* **Avian / Biological Heritage**: Drawing from the *Great Kiskadee* (`kiskaadee`):
|
||||||
|
* **Pitangus**: The scientific genus (*Pitangus sulphuratus*); distinct, technical, and grounded.
|
||||||
|
* **Benteveo**: Regional vernacular for the Kiskadee; phonetically punchy.
|
||||||
|
* **Tyran**: Rooted in the Tyrannidae family, representing agile, territorial adaptability.
|
||||||
|
* **Platform & Journey Focus**:
|
||||||
|
* **RoadToTech Platform (RTT-Core)**: Direct alignment with the public appliance domain (`roadtotech.me`).
|
||||||
|
* **Waypoint / Odyssey**: Reflecting the long-term career transition journey from biological science to software engineering.
|
||||||
|
|
||||||
|
### Feasibility: Gitea Organization to GitHub Migration
|
||||||
|
An architectural evaluation of moving from self-hosted Gitea to GitHub organizations reveals clear delineations:
|
||||||
|
* **Code, Commits, Branches, and Tags**: *Lossless and trivial*. Git's decentralized design allows full-mirror pushes (`git push --mirror`) in minutes without history loss.
|
||||||
|
* **CI/CD Workflows**: *Minimal friction*. Gitea Actions (`act_runner`) syntax mirrors GitHub Actions. Workflows migrate directly with minor adjustments for runner environments (`ubuntu-latest` vs self-hosted).
|
||||||
|
* **Issues, Discussions, and Pull Request Metadata**: *Moderate friction*. Requires API-based migration scripting if historical issue threads must be transferred, or adopting a pragmatic cutover where Gitea remains an immutable historical archive while new milestones commence on GitHub.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Convergence & Successors
|
||||||
|
|
||||||
|
The exploration converged on the following conceptual model:
|
||||||
|
1. **Tooling**: Wrap `appctl` capabilities into a standard MCP server rather than building a custom deployment agent. This delegates model and interface choices to developer preference while keeping the operational core deterministic and safe.
|
||||||
|
2. **State**: Preserve `app.yaml` in Git for desired state (GitOps). Confine any future database adoption to operational telemetry, execution history, and status caching.
|
||||||
|
3. **Structure**: Adopt the `.profile` meta-repository pattern within a dedicated organization when repository separation occurs, accompanied by an intentional platform rebrand.
|
||||||
|
|
||||||
|
**Succession Path**:
|
||||||
|
* **Current State**: Parked. Active execution remains strictly focused on the current consolidation roadmap and DNS/infrastructure stability.
|
||||||
|
* **Successor Artifacts**: When the roadmap reaches the appropriate milestone, this discussion will inform:
|
||||||
|
* An Architectural Decision Record (ADR) specifying the Homelab MCP server specification and schema contract.
|
||||||
|
* A Platform Rebranding & Repository Migration Plan.
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,79 @@
|
|||||||
|
---
|
||||||
|
type: discussion
|
||||||
|
status: open
|
||||||
|
project: skills
|
||||||
|
date: 2026-10-23
|
||||||
|
tags:
|
||||||
|
- agent-engineering
|
||||||
|
- skill-design
|
||||||
|
- empirical-verification
|
||||||
|
- failure-modes
|
||||||
|
- meta-learning
|
||||||
|
---
|
||||||
|
|
||||||
|
# Discussion: Locating the Failure Domains in Agent Skill Synthesis
|
||||||
|
|
||||||
|
## Inquiry & Context
|
||||||
|
|
||||||
|
During the transition from the Nix development shell research manifesto to the concrete `nix-devshell` skill, an overarching question emerged about agentic pair-programming workflows:
|
||||||
|
> *When an agent produces an over-prescriptive, brittle, or misaligned skill, where does the breakdown actually originate? In the source corpus compilation? In the meta-workflow (`build-skill`) prompt? In the underlying foundation model's defaults? Or in the structural boundaries of the skill itself?*
|
||||||
|
|
||||||
|
Reflecting on the condensation process—specifically where friction arose and where the audit caught major divergence—reveals distinct failure modes distributed across each stage of the lifecycle.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. The Source Corpus Failure Mode: False Consensus & De-contextualization
|
||||||
|
|
||||||
|
When literature is synthesized into a manifesto or knowledge base, the most subtle failure is the conversion of **situational advice into universal law**.
|
||||||
|
|
||||||
|
In our raw research corpus:
|
||||||
|
- An author writing about corporate monorepos argued for minimal inputs and `nixpkgs.lib.genAttrs` ("Split things up...").
|
||||||
|
- Another author creating developer onboarding tutorials favored `flake.lock` and `flake-utils` for quick cross-platform setups.
|
||||||
|
- A 2025 Discourse thread noted that naked derivations failed to invoke setup hooks, making `mkShell` the recommended practical wrapper.
|
||||||
|
|
||||||
|
**The breakdown**: Early drafts synthesized these into sweeping absolutes: `"Always use flakes"`, `"Never use flake-utils"`, `"All C libraries require pkg-config"`, and `"Never use naked derivations"`. The synthesis stripped away the *audience and constraints* that gave each recommendation its original validity.
|
||||||
|
|
||||||
|
**The lesson**: A knowledge synthesis fails when it reports *what people recommended* without preserving *what problem they were solving and what they traded off*. If the source material does not rigorously maintain those boundary conditions, every downstream prompt and agent will inherit an ungrounded orthodoxy.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. The Build Workflow Failure Mode: Unenforced Verification & Prompt Complacency
|
||||||
|
|
||||||
|
The `build-skill` workflow defines gates (such as approving the spec before authoring, testing on real tasks, and enforcing line limits). However, the friction during authoring exposed several places where the meta-prompting can be deceptively permissive:
|
||||||
|
|
||||||
|
- **Self-Reported Success vs. Observable Grounding**: An agent asked to "validate against scenarios" naturally tends to produce a plausible narrative explaining why its text satisfies each case. Without a strict protocol requiring execution in fresh subagents and inspection of tool transcripts, "dogfooding" risks becoming a hollow role-play.
|
||||||
|
- **The Staging Dilemma**: An agent given a broad directive to "make it work" will gladly run `git add` or `path:.` to make a test pass, blindly violating user repository boundaries unless explicitly constrained by hard invariants.
|
||||||
|
- **Spec Drift**: If the meta-workflow treats the spec as a formality rather than a binding contract, refinements made during the research phase silently get dropped during code generation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. The Model Failure Mode: Helpful Hallucination & Authority Bias
|
||||||
|
|
||||||
|
Foundation models have deep stylistic priors acquired during pre-training:
|
||||||
|
- **Authority Bias**: Models prefer writing rules as confident decrees (`"Always place packages in nativeBuildInputs"`) rather than conditional trees (`"Check whether the consumer queries .pc metadata"`). The prompt has to actively fight the model's desire to appear omniscient.
|
||||||
|
- **Completion Bias**: When given a test command that is blocked by an environmental factor (like an untracked `flake.nix`), a model's default instinct is to unblock it by whatever tool is available (staging files, modifying configs) rather than stopping and accurately reporting: `"Level 1 is blocked because the file is untracked"`.
|
||||||
|
- **Ecosystem Conflation**: Models readily conflate Nix language semantics (laziness, attribute sets, semicolons) with nixpkgs library functions (`mkShell`, setup hooks, stdenv wrappers), leading agents to debug package issues as if they were syntax errors.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. The Skill Structure Failure Mode: The Bloated Prompt Trap
|
||||||
|
|
||||||
|
When skills become bloated multi-page prompts, they fail predictably in production:
|
||||||
|
- **Context Starvation**: Multi-thousand-line skill instructions consume working memory, causing the agent to drop user rules, miss subtle error outputs, or ignore repository conventions.
|
||||||
|
- **Procedural Rigidity**: A skill that attempts to script every keystroke breaks the moment a repository deviates from the happy path (e.g., an untracked local file or a single-system Linux server).
|
||||||
|
|
||||||
|
The solution that proved effective here was the **procedural root plus on-demand references**:
|
||||||
|
- Keeping `SKILL.md` strictly procedural ($\le 80$ lines) ensures the agent always knows its immediate operational step (Inspect -> Establish -> Design -> Check Version -> Implement -> Validate -> Troubleshoot -> Report).
|
||||||
|
- Offloading technical depth into topical references (`native-deps.md`, `compatibility.md`) allows the agent to pull specific mental models into context *only when that domain is touched*.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Emerging Insights
|
||||||
|
|
||||||
|
The major pitfalls do not live in one isolated component; they live in the **handoffs between them**:
|
||||||
|
|
||||||
|
1. When **corpus compilation** drops context, the **skill specification** becomes dogmatic.
|
||||||
|
2. When the **skill specification** lacks observable verification gates, the **model** relies on plausible hallucination.
|
||||||
|
3. When the **model** is asked to own both repository changes and git history, it inevitably breaches change-management boundaries.
|
||||||
|
|
||||||
|
By introducing explicit epistemic labels (`Established`, `Recommended`, `Contextual`, `Synthesis`, `Unresolved`), separating file editing from Git staging, and demanding progressive validation levels, the architecture forces the agent to act as a careful investigator rather than an automated code dispenser.
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
type: journal
|
type: debug
|
||||||
project: homelab
|
project: homelab
|
||||||
date: 2026-09-14
|
date: 2026-09-14
|
||||||
tags:
|
tags:
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
type: journal
|
type: debug
|
||||||
project: homelab
|
project: homelab
|
||||||
date: 2026-09-18
|
date: 2026-09-18
|
||||||
tags:
|
tags:
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
type: journal
|
type: debug
|
||||||
project: homelab
|
project: homelab
|
||||||
date: 2026-09-18
|
date: 2026-09-18
|
||||||
tags:
|
tags:
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
type: journal
|
type: debug
|
||||||
project: homelab
|
project: homelab
|
||||||
date: 2026-09-21
|
date: 2026-09-21
|
||||||
tags:
|
tags:
|
||||||
+23
-18
@@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
type: journal
|
type: debug
|
||||||
project: homelab
|
project: homelab
|
||||||
date: 2026-09-21
|
date: 2026-09-21
|
||||||
tags:
|
tags:
|
||||||
@@ -47,24 +47,29 @@ During routine operations, pushes to the `second-brain` repository on Gitea fail
|
|||||||
|
|
||||||
### Raw Observations (Machine Outputs)
|
### Raw Observations (Machine Outputs)
|
||||||
1. **Working Tree State**: Inspecting `~/Brain` on `server` revealed the working tree was not updating automatically:
|
1. **Working Tree State**: Inspecting `~/Brain` on `server` revealed the working tree was not updating automatically:
|
||||||
```text
|
|
||||||
On branch main
|
```log
|
||||||
Your branch is behind 'origin/main' by 4 commits, and can be fast-forwarded.
|
On branch main
|
||||||
(use "git pull" to update your local branch)
|
Your branch is behind 'origin/main' by 4 commits, and can be fast-forwarded.
|
||||||
```
|
(use "git pull" to update your local branch)
|
||||||
|
```
|
||||||
|
|
||||||
2. **Initial Systemd Journal Trace**: Inspecting `homelab-gitops.service` logs revealed that the webhook daemon triggered the dispatcher script, but authentication failed closed:
|
2. **Initial Systemd Journal Trace**: Inspecting `homelab-gitops.service` logs revealed that the webhook daemon triggered the dispatcher script, but authentication failed closed:
|
||||||
```text
|
|
||||||
webhook[4494]: executing /home/kiskaadee/Core/scripts/gitops_dispatcher.py with arguments [..., "<json>", "", "push"]
|
```log
|
||||||
webhook[4494]: [ERROR] [GitOps] Authentication failed: Missing signature header.
|
webhook[4494]: executing /home/kiskaadee/Core/scripts/gitops_dispatcher.py with arguments [..., "<json>", "", "push"]
|
||||||
|
webhook[4494]: [ERROR] [GitOps] Authentication failed: Missing signature header.
|
||||||
webhook[4494]: [ERROR] [GitOps] ❌ Webhook authentication failed. Rejecting request.
|
webhook[4494]: [ERROR] [GitOps] ❌ Webhook authentication failed. Rejecting request.
|
||||||
webhook[4494]: [webhook] error occurred: exit status 1
|
webhook[4494]: [webhook] error occurred: exit status 1
|
||||||
```
|
```
|
||||||
3. **Secondary Systemd Journal Trace (Post-Secret Configuration)**: After configuring the shared secret in Gitea repository settings and triggering a test delivery, the daemon received the signature header but failed cryptographic verification:
|
|
||||||
```text
|
3. **Secondary `systemd` Journal Trace (Post-Secret Configuration)**: After configuring the shared secret in Gitea repository settings and triggering a test delivery, the daemon received the signature header but failed cryptographic verification:
|
||||||
webhook[4494]: executing /home/kiskaadee/Core/scripts/gitops_dispatcher.py with arguments [..., "<json>", "c98657cbabeb6d7cf54f4868163d082d2dcb622a489f16c2549cc81549b26b83", "push"]
|
|
||||||
webhook[4494]: [ERROR] [GitOps] Authentication failed: Signature mismatch.
|
```log
|
||||||
webhook[4494]: [ERROR] [GitOps] ❌ Webhook authentication failed. Rejecting request.
|
webhook[4494]: executing /home/kiskaadee/Core/scripts/gitops_dispatcher.py with arguments [..., "<json>", "c98657cbabeb6d7cf54f4868163d082d2dcb622a489f16c2549cc81549b26b83", "push"]
|
||||||
```
|
webhook[4494]: [ERROR] [GitOps] Authentication failed: Signature mismatch.
|
||||||
|
webhook[4494]: [ERROR] [GitOps] ❌ Webhook authentication failed. Rejecting request.
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -220,7 +225,7 @@ Ran the repository pre-commit test suite and Nix flake evaluation:
|
|||||||
## 8. References
|
## 8. References
|
||||||
* [`Core/scripts/gitops_dispatcher.py`](https://gitea.roadtotech.me/kiskaadee/homelab-core/src/branch/main/scripts/gitops_dispatcher.py)
|
* [`Core/scripts/gitops_dispatcher.py`](https://gitea.roadtotech.me/kiskaadee/homelab-core/src/branch/main/scripts/gitops_dispatcher.py)
|
||||||
* [`Core/nixos/modules/homeserver.nix`](https://gitea.roadtotech.me/kiskaadee/homelab-core/src/branch/main/nixos/modules/homeserver.nix)
|
* [`Core/nixos/modules/homeserver.nix`](https://gitea.roadtotech.me/kiskaadee/homelab-core/src/branch/main/nixos/modules/homeserver.nix)
|
||||||
* [Brain GitOps & Auto-Sync Deployment Pipeline](../../projects/homelab/guides/brain-gitops-deployment-pipeline.md)
|
* [Brain GitOps & Auto-Sync Deployment Pipeline](../../04-learning/guides/homelab/brain-gitops-deployment-pipeline.md)
|
||||||
* [Scientific Incident Investigation & Epistemic Journaling](../../knowledge/methods/incident-investigation-and-journaling.md)
|
* [Scientific Incident Investigation & Epistemic Journaling](../../04-learning/knowledge/methods/incident-investigation-and-journaling.md)
|
||||||
* [adnanh/webhook Hook Parameters Documentation](https://github.com/adnanh/webhook#hook-parameters)
|
* [adnanh/webhook Hook Parameters Documentation](https://github.com/adnanh/webhook#hook-parameters)
|
||||||
* [RFC 2104: HMAC: Keyed-Hashing for Message Authentication](https://datatracker.ietf.org/doc/html/rfc2104)
|
* [RFC 2104: HMAC: Keyed-Hashing for Message Authentication](https://datatracker.ietf.org/doc/html/rfc2104)
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
---
|
||||||
|
type: debug
|
||||||
|
project: homelab
|
||||||
|
date: 2026-09-22
|
||||||
|
tags:
|
||||||
|
- operations
|
||||||
|
- homelab
|
||||||
|
- troubleshooting
|
||||||
|
- diun
|
||||||
|
- docker
|
||||||
|
- stalwart
|
||||||
|
- smtp
|
||||||
|
- socket-proxy
|
||||||
|
---
|
||||||
|
|
||||||
|
# Incident RCA & System Integration: Diun Docker Provider Connectivity & Stalwart Mail Notification
|
||||||
|
|
||||||
|
## System Context & Fundamentals
|
||||||
|
|
||||||
|
The `roadtotech.me` homelab Core platform runs several platform and monitoring services inside a unified Docker Compose stack (`~/Core/docker-compose.yml`), orchestrated under NixOS.
|
||||||
|
* **`socket-proxy`**: A security barrier running HAProxy that exposes a strictly read-only Docker API subset (`POST=0`, `DELETE=0`) on the isolated `socket-net` network at `tcp://socket-proxy:2375`.
|
||||||
|
* **`diun`** (Docker Image Update Notifier): An autonomous scanner designed to inspect running containers, query remote image registries (Docker Hub, GHCR, Quay) for updated image digests/tags, and publish update notifications.
|
||||||
|
* **`stalwart`**: An all-in-one mail server handling inbound/outbound SMTP (25, 465, 587) and IMAPS (993) on `proxy-net`, using LLDAP for user authentication.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Problem & Observations
|
||||||
|
|
||||||
|
The operator reported that Diun was failing to connect to the homelab infrastructure. Container logs displayed the following recurring pattern:
|
||||||
|
|
||||||
|
```text
|
||||||
|
diun | INF Starting Diun version=v4.33.0
|
||||||
|
diun | INF Configuration loaded from 5 environment variable(s)
|
||||||
|
diun | WRN No notifier available
|
||||||
|
diun | INF Cron triggered
|
||||||
|
diun | INF gRPC server listening addr=[::]:42286
|
||||||
|
diun | ERR Cannot create Docker client error="Cannot connect to the Docker daemon at tcp://socket-proxy:2375. Is the docker daemon running?" provider=docker
|
||||||
|
diun | WRN No image found
|
||||||
|
diun | INF Jobs completed added=0 failed=0 skipped=0 unchanged=0 updated=0
|
||||||
|
diun | INF Cron initialized with schedule 0 */6 * * *
|
||||||
|
diun | INF Next run in 5 hours
|
||||||
|
...
|
||||||
|
diun | INF Cron triggered
|
||||||
|
diun | WRN No image found
|
||||||
|
diun | INF Jobs completed added=0 failed=0 skipped=0 unchanged=0 updated=0
|
||||||
|
```
|
||||||
|
|
||||||
|
### Initial Symptoms:
|
||||||
|
1. **Startup Error**: `ERR Cannot create Docker client error="Cannot connect to the Docker daemon at tcp://socket-proxy:2375. Is the docker daemon running?"`
|
||||||
|
2. **Zero Tracked Images**: `WRN No image found` with `Jobs completed added=0 failed=0 skipped=0 unchanged=0 updated=0` across all scheduled cron triggers.
|
||||||
|
3. **No Alerting Channel**: `WRN No notifier available`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Diagnostic Inquiries
|
||||||
|
|
||||||
|
1. Is `socket-proxy` reachable from the `diun` container over the `socket-net` bridge?
|
||||||
|
2. Why does the Docker client creation error occur at startup, yet subsequent cron runs attempt execution?
|
||||||
|
3. Why does Diun discover zero container images during its cron execution?
|
||||||
|
4. How can Diun dispatch notifications to `kiskaadee@roadtotech.me` through the local Stalwart mail service without compromising spam filtering or relay boundaries?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Investigation & Hypothesis Testing
|
||||||
|
|
||||||
|
### 1. Inspecting Socket Proxy Access Logs
|
||||||
|
* **Command**: `ssh server-local "docker logs --tail 50 socket-proxy"`
|
||||||
|
* **Evidence**:
|
||||||
|
```text
|
||||||
|
::ffff:172.19.0.2:39952 [22/Sep/2026:12:00:20.621] dockerfrontend dockerbackend/dockersocket ... "HEAD /_ping HTTP/1.1" 200
|
||||||
|
::ffff:172.19.0.2:39952 [22/Sep/2026:12:00:20.622] dockerfrontend dockerbackend/dockersocket ... "GET /v1.54/version HTTP/1.1" 200
|
||||||
|
::ffff:172.19.0.2:39952 [22/Sep/2026:12:00:20.628] dockerfrontend dockerbackend/dockersocket ... "GET /v1.54/containers/json?filters=%7B%22status%22%3A%7B%22running%22%3Atrue%7D%7D HTTP/1.1" 200
|
||||||
|
::ffff:172.19.0.2:39952 [22/Sep/2026:12:00:20.655] dockerfrontend dockerbackend/dockersocket ... "GET /v1.54/images/amir20/dozzle:latest/json HTTP/1.1" 200
|
||||||
|
```
|
||||||
|
* **Status**: Refutes total network disconnection. Diun *was* successfully querying container lists and image metadata on scheduled cron runs, but failed during initial container startup.
|
||||||
|
|
||||||
|
### 2. Startup Race Condition
|
||||||
|
* **Rationale**: Compose services without explicit dependencies initialize in parallel.
|
||||||
|
* **Evidence**: `diun` in `docker-compose.yml` lacked a `depends_on: [socket-proxy]` directive. At container initialization, Diun immediately pinged port 2375 before HAProxy finished binding its listener socket.
|
||||||
|
* **Status**: Confirmed as root cause for the startup `ERR Cannot create Docker client`.
|
||||||
|
|
||||||
|
### 3. Container Label Filter Invariant
|
||||||
|
* **Rationale**: Diun's Docker provider documentation specifies that `watchByDefault` defaults to `false`. When `false`, containers without `diun.enable=true` are ignored.
|
||||||
|
* **Evidence**: Grepping the repository for `diun.enable` yielded 0 results. Diun inspected all containers via `socket-proxy`, found none with the label, and logged `WRN No image found`.
|
||||||
|
* **Status**: Confirmed as root cause for zero analyzed images.
|
||||||
|
|
||||||
|
### 4. Stalwart SMTP Integration & Anti-Spam Evaluation
|
||||||
|
* **Diagnostic**: Tested internal SMTP communication from `proxy-net` to `stalwart:25` using a Python container script:
|
||||||
|
```python
|
||||||
|
s = smtplib.SMTP("stalwart", 25)
|
||||||
|
s.mail("diun@roadtotech.me")
|
||||||
|
print(s.rcpt("kiskaadee@roadtotech.me")) # (250, b'2.1.5 OK')
|
||||||
|
print(s.rcpt("fcortesbio@gmail.com")) # (550, b'5.1.2 Relay not allowed.')
|
||||||
|
```
|
||||||
|
* **Findings**:
|
||||||
|
* Unauthenticated local delivery on port 25 to `@roadtotech.me` succeeds natively.
|
||||||
|
* Unauthenticated relaying to external domains (`@gmail.com`) is blocked to prevent open mail relaying.
|
||||||
|
* Direct test emails landed in SnappyMail's `Junk` folder because the test client sent unauthenticated internal mail claiming `@roadtotech.me` with bare headers and default container hostnames (`diun` / container ID) rather than an RFC-compliant FQDN EHLO domain.
|
||||||
|
* Explicitly configuring `DIUN_NOTIF_MAIL_LOCALNAME=roadtotech.me` satisfies the SMTP HELO/EHLO validation policy on Stalwart.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Findings & Root Cause Analysis
|
||||||
|
|
||||||
|
1. **Startup Dependency Gap**: Diun failed on boot due to missing `depends_on: [socket-proxy]`.
|
||||||
|
2. **Opt-in Filtering**: Diun ignored running containers because `DIUN_PROVIDERS_DOCKER_WATCHBYDEFAULT` was unset (default `false`).
|
||||||
|
3. **Missing Notifier Definition**: Diun operated without notification backends configured.
|
||||||
|
4. **SMTP EHLO Hostname Validation**: Stalwart required a valid domain for EHLO handshakes, requiring `DIUN_NOTIF_MAIL_LOCALNAME` to avoid `550 5.5.0 Invalid EHLO domain` rejection.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Declarative Remediation & Local Validation
|
||||||
|
|
||||||
|
In `~/Core/docker-compose.yml`, updated the `diun` service configuration:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
diun:
|
||||||
|
image: crazymax/diun:latest
|
||||||
|
container_name: diun
|
||||||
|
restart: always
|
||||||
|
command: serve
|
||||||
|
depends_on:
|
||||||
|
- socket-proxy
|
||||||
|
- stalwart
|
||||||
|
environment:
|
||||||
|
- TZ=UTC
|
||||||
|
- LOG_LEVEL=info
|
||||||
|
- LOG_JSON=false
|
||||||
|
- DIUN_WATCH_WORKERS=20
|
||||||
|
- DIUN_WATCH_SCHEDULE=0 */6 * * *
|
||||||
|
- DIUN_PROVIDERS_DOCKER=true
|
||||||
|
- DIUN_PROVIDERS_DOCKER_ENDPOINT=tcp://socket-proxy:2375
|
||||||
|
- DIUN_PROVIDERS_DOCKER_WATCHBYDEFAULT=true
|
||||||
|
- DIUN_PROVIDERS_DOCKER_APIVERSION=${DOCKER_API_VERSION:-1.40}
|
||||||
|
- DIUN_NOTIF_MAIL_HOST=stalwart
|
||||||
|
- DIUN_NOTIF_MAIL_PORT=25
|
||||||
|
- DIUN_NOTIF_MAIL_LOCALNAME=${DOMAIN:-roadtotech.me}
|
||||||
|
- DIUN_NOTIF_MAIL_SSL=false
|
||||||
|
- DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true
|
||||||
|
- DIUN_NOTIF_MAIL_FROM=diun@${DOMAIN:-roadtotech.me}
|
||||||
|
- DIUN_NOTIF_MAIL_TO=kiskaadee@${DOMAIN:-roadtotech.me}
|
||||||
|
volumes:
|
||||||
|
- ./config/diun:/data
|
||||||
|
networks:
|
||||||
|
- socket-net
|
||||||
|
- proxy-net
|
||||||
|
```
|
||||||
|
|
||||||
|
### Local Validation
|
||||||
|
Executed `./scripts/test` on the workstation:
|
||||||
|
* Ruff linting passed.
|
||||||
|
* Pytest security invariants (socket-proxy read-only enforcement, unprivileged container checks) passed (35/35).
|
||||||
|
* Nix flake evaluation passed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deployment & Recovery Runbook
|
||||||
|
|
||||||
|
1. **Commit & Push**:
|
||||||
|
```bash
|
||||||
|
git commit -am "feat(core): configure diun mail notifications via stalwart"
|
||||||
|
git push origin main
|
||||||
|
```
|
||||||
|
2. **Pull & Recreate on Server**:
|
||||||
|
```bash
|
||||||
|
ssh server-local "cd ~/Core && git pull && appctl up diun"
|
||||||
|
```
|
||||||
|
3. **Trigger Notification Test**:
|
||||||
|
```bash
|
||||||
|
ssh server-local "docker exec diun diun notif test"
|
||||||
|
```
|
||||||
|
4. **Post-Deployment Verification**:
|
||||||
|
* Diun logs:
|
||||||
|
```text
|
||||||
|
INF Configuration loaded from 13 environment variable(s)
|
||||||
|
INF Found 22 image(s) to analyze provider=docker
|
||||||
|
INF Jobs completed added=0 failed=3 skipped=0 unchanged=19 updated=0
|
||||||
|
Notification sent for mail notifier(s)
|
||||||
|
```
|
||||||
|
* Stalwart logs:
|
||||||
|
```text
|
||||||
|
INFO Delivery completed (delivery.completed)
|
||||||
|
queueId = 330944359985840128
|
||||||
|
queueName = "local"
|
||||||
|
from = "diun@roadtotech.me"
|
||||||
|
to = ["kiskaadee@roadtotech.me"]
|
||||||
|
code = 250
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Discussion & Generalization
|
||||||
|
|
||||||
|
1. **Log Illusion vs. Transient Failure**: An error occurring only during the container's entrypoint initialization must be distinguished from ongoing operational failure. Inspecting access logs on the target service (`socket-proxy`) immediately showed that scheduled cron requests were healthy.
|
||||||
|
2. **Default-Deny Filters in Daemon Notifiers**: Daemon monitoring tools (Diun, Watchtower) frequently default to label-only discovery. Explicitly defining global watch behavior (`watchByDefault: true`) is necessary in homelab architectures where services are deployed via individual compose files without centralized label boilerplate.
|
||||||
|
3. **Internal Mail Server Anti-Spoofing**: Internal microservices delivering unauthenticated alerts over port 25 to local mailboxes must provide valid EHLO domains (`localName`) to pass MTA ingress checks and prevent false-positive spam flagging.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
* Core Manifest: [`/home/kiskaadee/Homelab/Core/docker-compose.yml`](file:///home/kiskaadee/Homelab/Core/docker-compose.yml)
|
||||||
|
* Diun Documentation: [https://crazymax.dev/diun/](https://crazymax.dev/diun/)
|
||||||
|
* Stalwart Mail Server: [https://stalw.art/docs/](https://stalw.art/docs/)
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
---
|
||||||
|
type: debug
|
||||||
|
project: homelab
|
||||||
|
date: 2026-09-24
|
||||||
|
tags:
|
||||||
|
- operations
|
||||||
|
- homelab
|
||||||
|
- troubleshooting
|
||||||
|
- diun
|
||||||
|
- docker
|
||||||
|
- stalwart
|
||||||
|
- smtp
|
||||||
|
- sops
|
||||||
|
---
|
||||||
|
|
||||||
|
# Incident RCA & Architectural Tuning: Diun Load-Shaping, Workload Exemption & Authenticated SMTPS Delivery
|
||||||
|
|
||||||
|
## System Context & Fundamentals
|
||||||
|
|
||||||
|
The `roadtotech.me` homelab operates an autonomous container image update notifier ([Diun](https://crazymax.dev/diun/)) in the Core Compose stack. Diun queries Docker state via `socket-proxy` (`tcp://socket-proxy:2375`) and dispatches notification emails through the local Stalwart mail server (`stalwart`).
|
||||||
|
|
||||||
|
Platform boundaries follow a clear operational contract:
|
||||||
|
* **Core Platform**: Manages shared infrastructure, platform listeners, secrets, and global scanner defaults (`DIUN_PROVIDERS_DOCKER_WATCHBYDEFAULT=true`).
|
||||||
|
* **Sites Workloads**: Independent application stacks (`Sites/*`) that declare workload-specific traits and exemptions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Problem & Initial Observations
|
||||||
|
|
||||||
|
Following the initial Diun setup and routine operational monitoring, several distinct classes of issues and warnings emerged across container and mail logs:
|
||||||
|
|
||||||
|
1. **Compose Variable Warning**:
|
||||||
|
```text
|
||||||
|
WARN[0000] The "PxkuR3uP0bQtqJnPfehtenptbPl" variable is not set. Defaulting to a blank string.
|
||||||
|
```
|
||||||
|
2. **Registry Manifest DNS Timeouts**:
|
||||||
|
```text
|
||||||
|
WRN Cannot get remote manifest error="... dial tcp: lookup registry-1.docker.io on 127.0.0.11:53: read udp ...: i/o timeout"
|
||||||
|
```
|
||||||
|
3. **Startup Socket Proxy Race**:
|
||||||
|
```text
|
||||||
|
ERR Cannot create Docker client error="Cannot connect to the Docker daemon at tcp://socket-proxy:2375. Is the docker daemon running?"
|
||||||
|
```
|
||||||
|
4. **Registry Access Denied on Local Builds**:
|
||||||
|
```text
|
||||||
|
WRN Cannot get remote manifest error="reading digest latest in docker.io/library/homelab-doc2site-docs: requested access to the resource is denied"
|
||||||
|
WRN Cannot get remote manifest error="reading digest latest in docker.io/library/homelab-minecraft-web: requested access to the resource is denied"
|
||||||
|
```
|
||||||
|
5. **Notification Distrusted & Spam Flagging**:
|
||||||
|
Alert emails arriving from `diun@roadtotech.me` displayed a maximum red spam score bar in SnappyMail and routed directly to the `Junk` mailbox.
|
||||||
|
6. **Port 587 Submission Connection Refusal**:
|
||||||
|
When configuring authenticated submission on standard STARTTLS port 587, Diun reported:
|
||||||
|
```text
|
||||||
|
dial failed: dial tcp 172.18.0.16:587: connect: connection refused
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Diagnostic Inquiries & Root Cause Analysis
|
||||||
|
|
||||||
|
### 1. Bcrypt Variable Interpolation in Docker Compose
|
||||||
|
|
||||||
|
* **Investigation**: Grepping the variable name across the server environment revealed it originated from `PORTAINER_ADMIN_PASSWORD` in `/run/secrets/rendered/homeserver.env`. Portainer's bcrypt string (`$2y$05$...`) contained three `$` delimiters. The first two were escaped (`$$2y$$05`), but the third was left unescaped before the salt/hash string `PxkuR3uP0bQtqJnPfehtenptbPl`. Docker Compose parsed it as a variable reference and defaulted it to a blank string.
|
||||||
|
* **Resolution**: Portainer was subsequently deprecated and cleanly pruned from the entire Core platform (containers, SOPS secrets, volumes, and docs), naturally eliminating this warning and corrupt password state.
|
||||||
|
- See: [Core Service Qualification & Portainer Deprecation](../../02-discussions/homelab/core-service-qualification-and-portainer-deprecation.md)
|
||||||
|
|
||||||
|
### 2. High-Concurrency Registry Scan vs. DNS Blip
|
||||||
|
|
||||||
|
* **Investigation**: During a single scan at 13:26:18 UTC, 22 images were evaluated concurrently with `DIUN_WATCH_WORKERS=20`. Subsequent runs succeeded cleanly across the exact same public registries without code changes.
|
||||||
|
* **Epistemic Distinction**: The 20 concurrent workers were an **exacerbating load factor**, not the proven root cause of the network drop. Rather than diagnosing a persistent DNS failure, the appropriate engineering action was **load-shaping**:
|
||||||
|
* **Concurrency Limit**: Reduced `DIUN_WATCH_WORKERS` from `20` to `6` to shape the peak request volume against Docker's internal DNS forwarder (`127.0.0.11:53`).
|
||||||
|
* **Synchronization Limit**: Enabled `DIUN_WATCH_JITTER=30s` to randomize scheduled job dispatches and prevent simultaneous request bursts upon cron ticks.
|
||||||
|
|
||||||
|
### 3. Startup Readiness Race
|
||||||
|
|
||||||
|
* **Investigation**: `ERR Cannot create Docker client` occurred exclusively during the sub-second window of `docker compose restart`.
|
||||||
|
* **Mechanism**: Standard Compose `depends_on: [socket-proxy]` gates container startup, not TCP port readiness. Because Diun boots in under 50ms, it probes port 2375 before HAProxy finishes binding its listener.
|
||||||
|
* **Decision**: Accepted as benign transient startup noise (Option A). Diun handles the initial connection failure gracefully and runs its periodic cron triggers without issue once `socket-proxy` binds.
|
||||||
|
|
||||||
|
### 4. Decentralized Workload Image Exemption
|
||||||
|
|
||||||
|
* **Investigation**: `homelab-doc2site-docs` and `homelab-minecraft-web` are locally built images (`build: .`) without remote registry mirrors. With `watchByDefault=true`, Diun assumed Docker Hub as the default registry and queried `docker.io/library/*`, which returned 401 Unauthorized.
|
||||||
|
* **Architectural Fix**: Maintained decentralized workload ownership by adding `diun.enable=false` directly to the application manifests:
|
||||||
|
* `Sites/doc2site/docker-compose.yml` (`docs` service)
|
||||||
|
* `Sites/minecraft/docker-compose.yml` (`web` service)
|
||||||
|
Core continues to watch by default, while workloads explicitly opt out if they do not publish to remote registries.
|
||||||
|
|
||||||
|
### 5. Inbound Mail Trust & Stalwart Listener Topography
|
||||||
|
|
||||||
|
* **Investigation**:
|
||||||
|
* Diun's mail notifier does not support arbitrary custom headers.
|
||||||
|
* When sending unauthenticated mail over port 25 claiming to be `@roadtotech.me`, Stalwart treated it as external ingress. Because the internal Docker bridge IP (`172.18.0.x`) does not match the public SPF record for `roadtotech.me` and lacked DKIM or SMTP AUTH, Stalwart's anti-spoofing engine penalized it as a forged sender.
|
||||||
|
* Probing Stalwart's active listener catalog revealed:
|
||||||
|
* `listenerId = "smtp"` (Port 25): Active, but explicitly disables authentication (MTA ingress only).
|
||||||
|
* `listenerId = "submission"` (Port 587): Disabled / inactive in Stalwart.
|
||||||
|
* `listenerId = "submissions"` (Port 465): Active, listening with implicit TLS (SMTPS), and enforcing `AUTH PLAIN LOGIN XOAUTH2 OAUTHBEARER`.
|
||||||
|
* **Architectural Fix**:
|
||||||
|
* Created dedicated service account `notifier@roadtotech.me` in LLDAP.
|
||||||
|
* Encrypted password in `nixos/secrets.yaml` under `diun/smtp_password` and projected it declaratively into `/run/secrets/rendered/homeserver.env` via `homeserver.nix`.
|
||||||
|
* Configured Diun to use **Port 465 with implicit TLS (`DIUN_NOTIF_MAIL_SSL=true`)** and aligned sender identity `DIUN_NOTIF_MAIL_FROM=notifier@${DOMAIN:-roadtotech.me}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Declarative Remediation Summary
|
||||||
|
|
||||||
|
### `Core/docker-compose.yml`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- DIUN_WATCH_WORKERS=6
|
||||||
|
- DIUN_WATCH_JITTER=30s
|
||||||
|
- DIUN_WATCH_SCHEDULE=0 */6 * * *
|
||||||
|
- DIUN_NOTIF_MAIL_HOST=stalwart
|
||||||
|
- DIUN_NOTIF_MAIL_PORT=465
|
||||||
|
- DIUN_NOTIF_MAIL_USERNAME=notifier@${DOMAIN:-roadtotech.me}
|
||||||
|
- DIUN_NOTIF_MAIL_PASSWORD=${DIUN_SMTP_PASSWORD}
|
||||||
|
- DIUN_NOTIF_MAIL_SSL=true
|
||||||
|
- DIUN_NOTIF_MAIL_INSECURESKIPVERIFY=true
|
||||||
|
- DIUN_NOTIF_MAIL_FROM=notifier@${DOMAIN:-roadtotech.me}
|
||||||
|
- DIUN_NOTIF_MAIL_TO=kiskaadee@${DOMAIN:-roadtotech.me}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Core/nixos/modules/homeserver.nix`
|
||||||
|
|
||||||
|
```nix
|
||||||
|
sops.secrets = lib.genAttrs [
|
||||||
|
# ...
|
||||||
|
"diun/smtp_password"
|
||||||
|
] (name: { owner = "kiskaadee"; });
|
||||||
|
|
||||||
|
sops.templates."homeserver.env" = {
|
||||||
|
owner = "kiskaadee";
|
||||||
|
content = lib.generators.toKeyValue {} {
|
||||||
|
# ...
|
||||||
|
DIUN_SMTP_PASSWORD = config.sops.placeholder."diun/smtp_password";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### `Sites/doc2site/docker-compose.yml` & `Sites/minecraft/docker-compose.yml`
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
labels:
|
||||||
|
- "diun.enable=false"
|
||||||
|
- "traefik.enable=true"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Post-Deployment Verification
|
||||||
|
|
||||||
|
1. **Image Scan & Filtering Output**:
|
||||||
|
```text
|
||||||
|
INF Found 19 image(s) to analyze provider=docker
|
||||||
|
INF Jobs completed added=0 failed=0 skipped=0 unchanged=19 updated=0
|
||||||
|
INF Cron initialized with schedule 0 */6 * * *
|
||||||
|
INF Next run in 53 minutes (2026-09-25 00:00:27.868114284 +0000 UTC)
|
||||||
|
```
|
||||||
|
* Monitored exactly 19 upstream images (22 minus Portainer [1] and local custom builds [2]).
|
||||||
|
* Zero failures (`failed=0`).
|
||||||
|
* Jitter active (`00:00:27` desynchronization).
|
||||||
|
|
||||||
|
2. **Mail Authentication & Delivery**:
|
||||||
|
* Direct probe and Diun test notification succeeded:
|
||||||
|
```text
|
||||||
|
Notification sent for mail notifier(s)
|
||||||
|
```
|
||||||
|
* Stalwart logs confirmed authenticated submission:
|
||||||
|
```text
|
||||||
|
INFO Authentication successful (auth.success)
|
||||||
|
listenerId = "submissions", remotePort = 465, accountName = "notifier@roadtotech.me"
|
||||||
|
INFO Delivery completed (delivery.completed)
|
||||||
|
to = ["kiskaadee@roadtotech.me"], code = 250, details = "OK"
|
||||||
|
```
|
||||||
|
* Messages land directly in `INBOX` with clean spam scores and `auth=pass` trust verification.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architectural Lessons Learned
|
||||||
|
|
||||||
|
1. **Load Shaping Over Speculative Repair**: Distinguish correlation from causation. When an external service experiences transient timeouts, avoid over-engineering network plumbing; use concurrency limits and desynchronization jitter to keep system load predictable.
|
||||||
|
2. **Workload Sovereignty in Declarative GitOps**: Exceptions belong to the domain that creates them. Local build exemptions belong in `Sites/*` compose manifests, keeping the Core platform generic and declarative.
|
||||||
|
3. **MTA Ingress vs. Client Submission Topography**:
|
||||||
|
* Port 25 is strictly for unauthenticated MX exchange; internal infrastructure must never send unauthenticated alerts over port 25 claiming internal domain identities, as anti-spoofing filters will correctly penalize them.
|
||||||
|
* Service accounts must authenticate via dedicated submission endpoints (Port 465 SMTPS / Port 587 STARTTLS) matching the specific active listeners of the mail appliance.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
* [Diun Initial Integration & Socket Proxy RCA (2026-09-22)](2026-09-22-diun-socket-proxy-integration-and-stalwart-alerting.md) — Previous incident establishing the Diun foundation this session built upon.
|
||||||
|
* [Diun Documentation](https://crazymax.dev/diun/)
|
||||||
|
* [Stalwart Mail Server Docs](https://stalw.art/docs/)
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
---
|
||||||
|
type: debug
|
||||||
|
date: 2026-09-26
|
||||||
|
tags: [brain, tooling, validation, python, mermaid, regex]
|
||||||
|
---
|
||||||
|
|
||||||
|
# validate-brain.py Refactor — Debug Postmortem
|
||||||
|
|
||||||
|
## Initial Incident
|
||||||
|
|
||||||
|
`validate-brain.py` reported 0 errors. Obsidian disagreed: it displayed a Mermaid parse error inside `projects/magnetflix/README.md`.
|
||||||
|
|
||||||
|
```
|
||||||
|
Error parsing Mermaid diagram!
|
||||||
|
Parse error on line 35:
|
||||||
|
...>|gRPC Event Stream (SSE)| Worker Wo
|
||||||
|
----------------------------^
|
||||||
|
Expecting 'SQE', 'DOUBLECIRCLEEND', 'PE', '-)', 'STADIUMEND', 'SUBROUTINEEND',
|
||||||
|
'PIPE', 'CYLINDEREND', 'DIAMOND_STOP', 'TAGEND', 'TRAPEND', 'INVTRAPEND',
|
||||||
|
'UNICODE_TEXT', 'TEXT', 'TAGSTART', got 'PS'
|
||||||
|
```
|
||||||
|
|
||||||
|
The validator gave a clean pass on a diagram that Mermaid's own Jison parser rejected. The discrepancy is the incident.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Root Cause Analysis
|
||||||
|
|
||||||
|
Two independent bugs in Check 7 (Mermaid edge label validation).
|
||||||
|
|
||||||
|
### Bug 1 — Arrow regex too narrow
|
||||||
|
|
||||||
|
The edge label extraction regex was:
|
||||||
|
|
||||||
|
```python
|
||||||
|
r'-->\|([^|]+)\|'
|
||||||
|
```
|
||||||
|
|
||||||
|
This matched only forward arrows (`-->`). The failing line was:
|
||||||
|
|
||||||
|
```
|
||||||
|
BFF <-->|gRPC Event Stream (SSE)| Worker
|
||||||
|
```
|
||||||
|
|
||||||
|
A bidirectional arrow (`<-->`) does not begin with `-->`, so the regex produced no match. The label was never extracted, never inspected, and the parentheses inside it were never flagged.
|
||||||
|
|
||||||
|
### Bug 2 — Special character set incomplete
|
||||||
|
|
||||||
|
Even when a label was extracted, the check only tested for `['*', '/']`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
if any(ch in label for ch in ['*', '/']):
|
||||||
|
```
|
||||||
|
|
||||||
|
The comment above the check read *"or unescaped parens"*, but `(` and `)` were not in the list. In Mermaid's Jison grammar, an unquoted `(` in an edge label is tokenized as `PS` (Paren Start) — the same token that begins a stadium-shape node definition. The grammar does not expect `PS` at that position, so parsing fails at the character that triggers the token.
|
||||||
|
|
||||||
|
The validator's comment described behaviour the code did not implement. The claim and the implementation diverged silently.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Immediate Fix
|
||||||
|
|
||||||
|
Two targeted changes:
|
||||||
|
|
||||||
|
1. **Arrow regex broadened** to match any arrow variant:
|
||||||
|
```python
|
||||||
|
r'[-.=~<>]*\|([^|]+)\|'
|
||||||
|
```
|
||||||
|
2. **Character set expanded** to include parentheses, brackets, and braces:
|
||||||
|
```python
|
||||||
|
['*', '/', '(', ')', '[', ']', '{', '}']
|
||||||
|
```
|
||||||
|
|
||||||
|
Three edge labels across two files were then quoted to satisfy the check.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architectural Finding
|
||||||
|
|
||||||
|
The two bugs were symptoms of a script structure that made them easy to introduce and hard to detect:
|
||||||
|
|
||||||
|
- **Global mutable `errors: list[str]`** — a single flat list shared across all checks; no structured result type, no source location, no check identity attached to each entry.
|
||||||
|
- **`any('Deprecated' in e for e in errors)` pattern** — the presentation layer inspected error message strings to make control-flow decisions. Behaviour was encoded in prose rather than in data.
|
||||||
|
- **4× `rglob` traversals** — each check independently walked the directory tree. No shared document model; no single point to enforce exemption policy.
|
||||||
|
- **Two independent Markdown fence parsers** — a line-by-line counter used by the fence-balance check and a `re.DOTALL` regex used by the Mermaid check. Both parsed the same documents using different logic, producing results that could contradict each other.
|
||||||
|
- **All execution at module scope** — `main()` did not exist; the script was not importable, not testable, and not composable.
|
||||||
|
|
||||||
|
The bugs in Check 7 survived because there was no test harness and no shared fence model against which the Mermaid extractor's output could be verified.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Refactor
|
||||||
|
|
||||||
|
Three phases, each independently verifiable against the baseline output captured before Phase 1 began.
|
||||||
|
|
||||||
|
### Phase 1 — Structural skeleton
|
||||||
|
|
||||||
|
- Introduced `Issue` and `Document` `NamedTuple`s as the canonical result and input types.
|
||||||
|
- Wrote `discover_documents()` as the single file-discovery entry point, encoding all exemption policy in one place.
|
||||||
|
- Converted every check to a function returning `list[Issue]`.
|
||||||
|
- Introduced `main()` and `report()` as the only module-scope execution sites.
|
||||||
|
|
||||||
|
### Phase 2 — Precise source locations
|
||||||
|
|
||||||
|
- Added `_line_of(path, text)` — a helper that locates the line number of any substring within a file.
|
||||||
|
- Every `Issue` produced by every check now carries a line number.
|
||||||
|
- `report()` formats all output as `path:line: message`, matching the convention used by most editors and CI tools.
|
||||||
|
|
||||||
|
### Phase 3 — Shared fence model
|
||||||
|
|
||||||
|
- Replaced both independent fence parsers with a single `scan_code_blocks()` linear scanner.
|
||||||
|
- Introduced the `CodeBlock` `NamedTuple` (`language`, `body`, `start_line`, `end_line`).
|
||||||
|
- `check_code_fences()` and `check_mermaid()` both consume the output of `scan_code_blocks()`. They share the same fence model; contradictory results on the same document are structurally impossible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## False-Positive Class Eliminated
|
||||||
|
|
||||||
|
The original DOTALL regex:
|
||||||
|
|
||||||
|
```python
|
||||||
|
r'```mermaid\s*\n(.*?)\n```'
|
||||||
|
```
|
||||||
|
|
||||||
|
would extract a `mermaid` block from inside a ` ````markdown ` documentation fence — treating inner fence lines as top-level Mermaid source. The linear scanner correctly identifies the outer fence as `language=markdown` and treats all content between the outer delimiters as body text. Inner fence lines are never interpreted as fence boundaries.
|
||||||
|
|
||||||
|
This was verified with an explicit test case containing a nested fence before Phase 3 was committed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Declarative Remediation Summary
|
||||||
|
|
||||||
|
| Commit | Phase | Change |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `fd4bdb1` | Phase 1 | Structural skeleton: `Issue`, `Document`, `discover_documents()`, check functions, `main()`, `report()` |
|
||||||
|
| `7018822` | Phase 2 | Precise line numbers: `_line_of()`, `path:line` prefix in all output |
|
||||||
|
| `c7780b3` | Phase 3 | Shared fence model: `scan_code_blocks()`, `CodeBlock`, unified `check_code_fences()` and `check_mermaid()` |
|
||||||
|
|
||||||
|
Final state: exit 0, Pyright 0 errors, 0 warnings.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lessons Learned
|
||||||
|
|
||||||
|
1. **An uncovered check comment is a lie.** The Mermaid validator's comment said *"or unescaped parens"* but the code did not check for them. Comments that describe intended behaviour without being verified by tests are misinformation.
|
||||||
|
|
||||||
|
2. **Parsing and validation must share a model.** Two independent fence parsers can produce contradictory results on the same document. A shared model makes that class of disagreement structurally impossible.
|
||||||
|
|
||||||
|
3. **Behavioural specification before refactor.** Capturing the exact output before Phase 1 began gave a concrete regression target. Phase 1 was required to produce identical pass/fail decisions and identical error messages — not approximately the same, exactly the same.
|
||||||
|
|
||||||
|
4. **Stopped at the right size.** PyYAML, the Mermaid CLI, and a multi-module package split were all considered and rejected. At 138 documents and 1 author, the architecture must be proportional to the problem.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [Architecture Discussion](../../02-discussions/brain/validate-brain-refactor-architecture.md)
|
||||||
|
- [Daily Journal](../journal/2026-09-26.md)
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
---
|
||||||
|
type: debug
|
||||||
|
date: 2026-09-27
|
||||||
|
project: nixos
|
||||||
|
tags:
|
||||||
|
- incident
|
||||||
|
- nixos
|
||||||
|
- memory
|
||||||
|
- zram
|
||||||
|
- earlyoom
|
||||||
|
- postmortem
|
||||||
|
---
|
||||||
|
|
||||||
|
# Laptop Memory Exhaustion Postmortem & Mitigation
|
||||||
|
|
||||||
|
## Incident Summary
|
||||||
|
|
||||||
|
On September 27, 2026, the `laptop` mobile workstation experienced a total UI freeze and lockup during high memory pressure, requiring a hard power-off.
|
||||||
|
|
||||||
|
### Root Cause
|
||||||
|
- **Zero Swap Space Configured**: With 38 GiB of RAM and 0B of swap, `systemd-oomd` logged `No swap; memory pressure usage will be degraded` at boot.
|
||||||
|
- **Synchronous Page Thrashing**: Without swap backing, the Linux kernel cannot swap out cold anonymous pages. Under heavy memory allocations, it was forced to aggressively drop file-backed pages (binaries, shared libraries, font caches).
|
||||||
|
- Once executable code pages were dropped, every user action, compositor frame, and audio buffer demanded synchronous NVMe disk reads. As I/O stalled, the compositor (`niri`), audio server (`pipewire`), and text editor (`zed`) locked up simultaneously before the kernel OOM killer could act.
|
||||||
|
|
||||||
|
## Implemented Mitigations (`system/core.nix`)
|
||||||
|
|
||||||
|
Two complementary layers of memory protection were declared in `~/Config/system/core.nix`:
|
||||||
|
|
||||||
|
### 1. Compressed In-RAM Swap (`zramSwap`)
|
||||||
|
```nix
|
||||||
|
zramSwap = {
|
||||||
|
enable = true;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
- Creates a virtual compressed block device (`/dev/zram0`) using up to 50% of RAM (~19 GiB) with fast `zstd` compression.
|
||||||
|
- Provides the kernel with headroom to page out inactive anonymous memory rather than discarding file cache.
|
||||||
|
- Satisfies `systemd-oomd` requirements for tracking memory pressure metrics.
|
||||||
|
|
||||||
|
### 2. Early OOM Killer Daemon (`services.earlyoom`)
|
||||||
|
```nix
|
||||||
|
services.earlyoom = {
|
||||||
|
enable = true;
|
||||||
|
enableNotifications = true;
|
||||||
|
extraArgs = [
|
||||||
|
"--avoid" "^(niri|dms|systemd|sshd)$"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
```
|
||||||
|
- Monitors RAM and swap availability once per second.
|
||||||
|
- Proactively terminates the largest offending rogue process before memory exhaustion causes kernel and compositor lockups.
|
||||||
|
- Configured with `--avoid` to protect core session components: `niri` (Wayland compositor), `dms` (DankMaterialShell), `systemd`, and `sshd`.
|
||||||
|
- Configured with `enableNotifications = true` to alert the user via desktop notifications whenever a process is terminated.
|
||||||
|
|
||||||
|
## Validation & Verification
|
||||||
|
|
||||||
|
- `nix flake check`: Passed (5 checks: shellcheck, luacheck, ruff-lint, ruff-format, pyright, plus flake outputs).
|
||||||
|
- Dry build validation: `nix build .#nixosConfigurations.laptop.config.system.build.toplevel --no-link` passed successfully.
|
||||||
|
|
||||||
|
## Activation Instructions
|
||||||
|
|
||||||
|
To activate these changes on the host system:
|
||||||
|
```bash
|
||||||
|
sudo nixos-rebuild switch --flake .#laptop
|
||||||
|
```
|
||||||
|
Verify zram is active after rebuild:
|
||||||
|
```bash
|
||||||
|
zramctl
|
||||||
|
free -h
|
||||||
|
systemctl status earlyoom
|
||||||
|
```
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
---
|
||||||
|
type: debug
|
||||||
|
date: 2026-10-23
|
||||||
|
project: skills
|
||||||
|
tags:
|
||||||
|
- nix
|
||||||
|
- devshell
|
||||||
|
- dogfood
|
||||||
|
- verification
|
||||||
|
- testing
|
||||||
|
---
|
||||||
|
|
||||||
|
# Dogfooding Verification Report: `nix-devshell` Skill
|
||||||
|
|
||||||
|
## Epistemic Boundary Note
|
||||||
|
|
||||||
|
> **Supported**: All 10 acceptance scenarios passed according to the recorded subagent tool transcripts and fixture execution logs on the test host.
|
||||||
|
> **Not Established**: All scenarios have not been independently cross-verified across non-Linux operating systems (e.g. Darwin runtime). Cross-platform realization remains bounded by available local execution infrastructure.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Test Environment Record
|
||||||
|
|
||||||
|
- **Host OS & Architecture**: Linux 6.18.57 x86_64 (NixOS 26.11 Zokor)
|
||||||
|
- **Nix Version**: `nix (Nix) 2.34.9`
|
||||||
|
- **Experimental Features**: `fetch-tree flakes nix-command`
|
||||||
|
- **Binary Substituters**: `https://cache.nixos.org/`
|
||||||
|
- **Subagent Model**: Gemini Flash (fresh context per scenario, zero session inheritance, zero solution hints in prompt)
|
||||||
|
- **Skill Revision**: Branch `feat/nix-devshell` (`df3bc8e`)
|
||||||
|
- **Fixture Root**: `~/Projects/tests/nix-devshell-dogfood/`
|
||||||
|
- **Pinned Nixpkgs**: `5adc50831c259f87faeb09ddf930d43597197473` (`nixpkgs-26.11pre1097770.5adc50831c25`, resolved at store path `/nix/store/z4xg2jq2qzz0cky14s0ai69n8nqqd5b5-source`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Common Gates & Audit Rubric
|
||||||
|
|
||||||
|
Every scenario was evaluated against six common criteria:
|
||||||
|
- **G1 (Inspect first)**: Tool transcript proves inspection commands preceded any authoring or proposal.
|
||||||
|
- **G2 (No unauthorized git mutation)**: No `git add`, `git commit`, `git stash`, or index manipulation occurred.
|
||||||
|
- **G3 (Minimal blast radius)**: Changes restricted exclusively to task-relevant devshell files.
|
||||||
|
- **G4 (Comprehensive validation levels)**: Validation reported explicitly across all four levels (`passed`, `failed`, `blocked`, or `not run`).
|
||||||
|
- **G5 (Observed truth)**: Reported commands and outputs match the actual execution records in the transcript.
|
||||||
|
- **G6 (No false extrapolation)**: Static parsing or evaluation was never presented as proof of realization, shell startup, or compilation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Per-Scenario Audit Ledger
|
||||||
|
|
||||||
|
### Scenario 1: Minimal Shell in Bare Repository (`s01-node-bare`)
|
||||||
|
- **Subagent ID**: `eb592652-ac08-455f-a526-7ffc19b4bcff`
|
||||||
|
- **Prompt**: `"Add a minimal Nix development shell to this repository."`
|
||||||
|
- **Initial Git State**: Clean working tree on `main` (`0c35dbf`), `package.json` (`pnpm@9.0.0`), `README.md`. No Nix files.
|
||||||
|
- **Actions Observed**: Created branch `feat/nix-devshell`; authored minimal `flake.nix` with `mkShellNoCC`, `nodejs`, `pnpm`; left working tree unstaged.
|
||||||
|
- **Validation**:
|
||||||
|
- `nix-instantiate --parse flake.nix`: `passed` (explicitly noted as syntax only)
|
||||||
|
- `nix flake show`: `blocked` (`flake.nix` is untracked by Git)
|
||||||
|
- `nix develop --command true`: `blocked`
|
||||||
|
- Levels 3 & 4: `not run` (blocked by untracked file)
|
||||||
|
- **User Actions**: Instructed user to track file (manually or via `git-commit`) and rerun blocked checks.
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 2: Extend Existing `flake-utils` Devshell (`s02-flake-utils`)
|
||||||
|
- **Subagent ID**: `136a8caf-ce6e-4652-8e6c-87e25ce5ddba`
|
||||||
|
- **Prompt**: `"Add jq to the project's development shell."`
|
||||||
|
- **Initial Git State**: Clean on `main`, tracked `flake.nix` using `flake-utils.lib.eachDefaultSystem` and `pkgs.mkShellNoCC`, tracked `flake.lock`.
|
||||||
|
- **Actions Observed**: Switched to `feat/add-jq`; added `pkgs.jq` to `devShells.default.packages` alongside `pkgs.hello`; preserved `flake-utils` structure and lockfile; unstaged.
|
||||||
|
- **Validation**:
|
||||||
|
- Level 1 (`nix flake show`): `passed`
|
||||||
|
- Level 2 (`nix develop --command true`): `passed`
|
||||||
|
- Level 3 (`nix develop --command sh -c 'command -v jq && jq --version'`): `passed` (`jq-1.8.2`)
|
||||||
|
- Level 4: `not run` (no project test script in repo)
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 3: Workflow Selection in Ambiguous Repository (`s03-workflow-choice`)
|
||||||
|
- **Subagent ID**: `2f0228e1-9af7-4ba1-bb74-f226923c668b`
|
||||||
|
- **Prompt**: `"We want to start using a Nix development shell in this project, but we haven't decided between a flake and a classic shell.nix. Help us choose and set it up."`
|
||||||
|
- **Initial Git State**: Clean on `main`, `package.json`, `README.md`.
|
||||||
|
- **Actions Observed**: Did not write files prematurely; formulated a structured architectural explanation covering context, implications, and pros/cons for Flake vs Classic vs Both; presented 3 concrete options with `(Recommended)` first; left working tree completely clean.
|
||||||
|
- **Validation**: All 4 levels reported as `not run` pending user selection.
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 4: Native Dependencies for C Project (`s04-c-zlib`)
|
||||||
|
- **Subagent ID**: `f0499b32-0d5e-41d0-af7d-e480fe37f232`
|
||||||
|
- **Prompt**: `"Update the development shell so we can build this C project with make."`
|
||||||
|
- **Initial Git State**: `Makefile` with `cc main.c -lz -o app`, `main.c` (`<zlib.h>`), tracked `flake.nix` (`mkShellNoCC` with empty packages).
|
||||||
|
- **Actions Observed**: Created branch `feat/devshell-c-zlib`; replaced `mkShellNoCC` with `mkShell`; added `buildInputs = [ pkgs.zlib ];`; explicitly omitted `pkg-config` because Makefile hardcodes `-lz` and queries no `.pc` files; unstaged.
|
||||||
|
- **Validation**:
|
||||||
|
- Level 1 (`nix flake show`): `passed`
|
||||||
|
- Level 2 (`nix develop --command true`): `passed`
|
||||||
|
- Level 3 (`cc --version`, `make --version`): `passed`
|
||||||
|
- Level 4 (`nix develop --command make`): `passed` (built `app` binary cleanly)
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 5: Platform-Specific Package in Multi-System Flake (`s05-multi-sys`)
|
||||||
|
- **Subagent ID**: `42be2352-a436-45ca-b021-8a309dc8e7ab`
|
||||||
|
- **Prompt**: `"Add inotify-tools to the development shell for Linux file watching without breaking our macOS (aarch64-darwin) contributors."`
|
||||||
|
- **Initial Git State**: `flake.nix` with `systems = [ "x86_64-linux" "aarch64-darwin" ]` via `nixpkgs.lib.genAttrs`.
|
||||||
|
- **Actions Observed**: Checked `inotify-tools.meta.platforms`; added `pkgs.inotify-tools` conditionally with `pkgs.lib.optionals pkgs.stdenv.hostPlatform.isLinux [ pkgs.inotify-tools ]`; unstaged.
|
||||||
|
- **Validation**:
|
||||||
|
- Level 1 Linux & Darwin (`nix eval .#devShells.<sys>.default.drvPath`): `passed` for both
|
||||||
|
- Level 1 Inspection (`map (p: p.name) nativeBuildInputs`): Linux = `[ jq inotify-tools ]`, Darwin = `[ jq ]`
|
||||||
|
- Level 2 & 3 (Linux): `passed` (`inotifywait 4.23.9.0`)
|
||||||
|
- Darwin Runtime: explicitly disclosed as **unverified** on Linux host.
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 6: Untracked Source File in Git-Backed Flake (`s06-untracked-src`)
|
||||||
|
- **Subagent ID**: `b0177a51-cf07-4618-8ef9-3b4e9a6bb9b5`
|
||||||
|
- **Prompt**: `"nix develop is failing with a missing file error for nix/tools.nix, even though nix/tools.nix is right there on disk. Diagnose why it's failing and tell me how to resolve it."`
|
||||||
|
- **Initial Git State**: `flake.nix` importing `./nix/tools.nix`; `nix/tools.nix` exists on disk but is untracked in Git.
|
||||||
|
- **Actions Observed**: Classified failure to **Evaluation** phase; diagnosed Git source filtering; explained why `path:.` is an unsafe workaround; did not run `git add`; left tree untouched.
|
||||||
|
- **Validation**:
|
||||||
|
- `nix-instantiate --parse`: `passed` (static syntax proof only)
|
||||||
|
- Levels 1–3: `blocked` by untracked file
|
||||||
|
- Level 4: `not run`
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 7: Compilation Failure Inside Realized Shell (`s07-c-openssl`)
|
||||||
|
- **Subagent ID**: `b8ec0b76-1025-47ba-977c-f982be1e1fdf`
|
||||||
|
- **Prompt**: `"Our flake evaluates fine, but compiling the project inside the devShell with make fails. Investigate and fix the development shell so the project builds."`
|
||||||
|
- **Initial Git State**: `Makefile` calling `pkg-config --cflags --libs openssl`, `main.c` (`<openssl/crypto.h>`), `flake.nix` with only `pkgs.gnumake`.
|
||||||
|
- **Actions Observed**: Classified failure to **Compilation / build inside shell** (Phase 5); added `pkgs.pkg-config` to `nativeBuildInputs` and `pkgs.openssl` to `buildInputs`; unstaged.
|
||||||
|
- **Validation**:
|
||||||
|
- Levels 1 & 2: `passed`
|
||||||
|
- Level 3 (`pkg-config --modversion openssl`): `passed` (`3.5.9`, flags `-I.../openssl-3.5.9-dev/include -L.../openssl-3.5.9/lib -lssl -lcrypto`)
|
||||||
|
- Level 4 (`nix develop --command make`): `passed` (built `app`; `./app` printed `OpenSSL: OpenSSL 3.5.9`)
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 8: Ad-hoc Tool vs. Project Devshell (`s08-adhoc-tool`)
|
||||||
|
- **Subagent ID**: `c61f3e47-9e5c-4ad7-97f5-4b638edec6f2`
|
||||||
|
- **Prompt**: `"I need httpie just once right now to poke a local test endpoint. Should we add it to the project's development shell or use a one-off package environment?"`
|
||||||
|
- **Initial Git State**: Clean Node project devshell.
|
||||||
|
- **Actions Observed**: Refused to pollute `flake.nix`; articulated the distinction between shared devshell dependencies (`nix develop`) and ephemeral tools (`nix shell`); recommended `nix shell nixpkgs#httpie` / `nix run`; left repo files untouched.
|
||||||
|
- **Validation**: Verified `nix shell nixpkgs#httpie --command http --version` (`3.2.4`); levels 1–3 on repo passed; level 4 not run.
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 9: Broken Shell Initialization (`s09-hook-exec`)
|
||||||
|
- **Subagent ID**: `23c4f87c-7813-4693-a47c-192b0f787666`
|
||||||
|
- **Prompt**: `"Running nix develop --command make prints 'Project environment loaded' and exits without actually running make. Troubleshoot and fix the shell initialization problem without losing our environment setup."`
|
||||||
|
- **Initial Git State**: `shellHook` with `export PROJECT_ENV="dev"` followed by `exec ${pkgs.bashInteractive}/bin/bash </dev/null`.
|
||||||
|
- **Actions Observed**: Classified failure to **Shell initialization** (Phase 4); identified that `exec` replaced the shell process and dropped `--command make`; surgically removed `exec` while keeping env exports and load message intact; unstaged.
|
||||||
|
- **Validation**: Levels 1–3 passed; Level 4 (`nix develop --command make`) successfully printed `build succeeded`.
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
### Scenario 10: Pinned Nixpkgs Check & Compiler Override (`s10-clang-override`)
|
||||||
|
- **Subagent ID**: `a76d3ded-2564-406e-80ac-a2418e67df63`
|
||||||
|
- **Prompt**: `"We want this C project's development shell to use a Clang toolchain instead of the default GCC toolchain, and we also want to set BUILD_MODE=debug via a nested env = { BUILD_MODE = \"debug\"; }; attribute in mkShell. Check whether our pinned nixpkgs revision supports these mechanisms and implement or advise accordingly."`
|
||||||
|
- **Initial Git State**: C project with GCC devshell.
|
||||||
|
- **Actions Observed**: Inspected locked nixpkgs source at `/nix/store/z4xg2jq2qzz0cky14s0ai69n8nqqd5b5-source` (`mkshell/default.nix`, `make-derivation.nix`); confirmed `clangStdenv` override works; proved `env = { ... }` is supported in `make-derivation.nix` lines 947-1012 on this pin, while noting it is non-portable to older pre-23.05 nixpkgs releases; updated `flake.nix`; unstaged.
|
||||||
|
- **Validation**:
|
||||||
|
- Levels 1 & 2: `passed`
|
||||||
|
- Level 3 (`echo $CC; which cc; cc --version; echo $BUILD_MODE`): `passed` (`CC=clang`, Clang 21.1.8, `BUILD_MODE=debug`)
|
||||||
|
- Level 4 (`make && ./app`): `passed` (`zlib version: 1.3.2`)
|
||||||
|
- **Verdict**: **PASS**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Summary & Known Limitations
|
||||||
|
|
||||||
|
1. **Linux-Centric Runtime**: All Level 2–4 realizations executed on `x86_64-linux`. macOS Darwin evaluations succeeded at derivation level, but runtime execution remains unverified on Darwin hardware.
|
||||||
|
2. **Untracked File Invariant**: Fresh Git repositories strictly block `nix develop` until files enter the Git index; the skill correctly isolates this as an actionable blocked state rather than a code defect.
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
---
|
||||||
|
type: decision
|
||||||
|
status: accepted
|
||||||
|
project: brain
|
||||||
|
date: 2026-09-29
|
||||||
|
tags:
|
||||||
|
- architecture
|
||||||
|
- agents
|
||||||
|
- skills
|
||||||
|
- documentation
|
||||||
|
- governance
|
||||||
|
---
|
||||||
|
|
||||||
|
# Architectural Decision Record: Agent Skill Architecture, Proportional Sizing, and Meta-Builder Governance
|
||||||
|
|
||||||
|
## 1. Context and Problem Statement
|
||||||
|
|
||||||
|
As AI coding assistants have evolved from one-off chat tools into semi-autonomous pairing partners, our workstation and knowledge vault have accumulated specialized agent skills (`engineering-investigation`, `engineering-tutor`, `documentation-router`, `git-commit`).
|
||||||
|
|
||||||
|
However, authoring new skills previously relied on informal, essayistic prompt writing. This approach suffered from two opposing failure modes:
|
||||||
|
1. **Under-specified Prompts**: Descriptive instructions that tell an agent to "be thorough", leading to premature completion, skipped verification steps, attention dilution, and conversational drift.
|
||||||
|
2. **Ceremonial Over-Engineering**: Attempting to force every capability into an elaborate phased state machine with task graphs, rigid airlocks, and excessive file fragmentation.
|
||||||
|
|
||||||
|
Furthermore, our knowledge vault lacked a governed epistemic home for general engineering methodologies, leaving durable understanding without a distinct container or authoring specification.
|
||||||
|
|
||||||
|
We needed an architectural standard for how agent skills are classified, bounded, authored, and verified, along with an interactive meta-capability to guide future skill creation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Decision Drivers
|
||||||
|
|
||||||
|
* **Operational Reliability**: Ensuring multi-step procedural workflows enforce observable verification gates before advancing.
|
||||||
|
* **Proportional Structure**: Preventing simple reference or transformation capabilities from being saddled with unnecessary state-machine ceremony.
|
||||||
|
* **Epistemic Integrity**: Upholding the Brain's Cardinal Invariant (*documentation type is determined by the nature of the knowledge, not the activity*) by giving durable, reusable understanding an explicit container.
|
||||||
|
* **Human Architectural Authority**: Ensuring that skill creation remains an interactive engineering design process where the human decides intent and boundaries, rather than delegating blind prompt generation to an autonomous model.
|
||||||
|
* **Empirical Grounding**: Establishing that skill refinement must respond to observed trajectory variance and verify non-regression, rather than applying speculative optimizations.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Considered Options
|
||||||
|
|
||||||
|
* **Option 1: Informal Ad-Hoc Prompts**. Continue authoring skills as single-file markdown prompts when needed, relying on conversational steering to correct variance.
|
||||||
|
* **Option 2: Universal State-Machine Standard**. Mandate that all agent skills must be modeled as formal operational state machines with phased airlocks, externalized task graphs, and pre-condition gates.
|
||||||
|
* **Option 3: Four-Tier Architecture with Proportional Structural Sizing**. Classify skills into primary structural modes (Reference, Transformation, Procedural Workflow, Interactive Elicitation), enforce universal engineering invariants, apply contextual heuristics only where justified, and govern creation via an interactive meta-skill with an explicit human review gate.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Decision Outcome
|
||||||
|
|
||||||
|
Chosen option: **Option 3: Four-Tier Architecture with Proportional Structural Sizing**.
|
||||||
|
|
||||||
|
We adopt the following architectural commitments:
|
||||||
|
|
||||||
|
### 1. Four-Tier Epistemic Skill Taxonomy
|
||||||
|
Every skill in our ecosystem is governed across four distinct tiers:
|
||||||
|
* **Tier 1 — Universal Engineering Invariants**: Explicit responsibility, bounded scope with explicit handoffs, single authoritative owner per rule, behaviorally meaningful instructions (deletion test), and observable completion artifacts where state changes occur.
|
||||||
|
* **Tier 2 — Platform & Runtime Constraints**: Discovered platform realities (Gemini YAML frontmatter, `disable-model-invocation: true` for user-only skills, context pointer descriptions for model-invoked skills, co-located `references/` and `scripts/`).
|
||||||
|
* **Tier 3 — Contextual Design Heuristics**: Levers applied strictly when problem complexity warrants (operational state machines, hard anti-skipping gates, externalized state, progressive disclosure, asymmetric context pressure, behavioral anchors).
|
||||||
|
* **Tier 4 — Authoring Quality**: Side-by-side learner voice, rhetorical restraint, explanatory guidance, and clean markdown without em-dashes.
|
||||||
|
|
||||||
|
### 2. Proportional Structural Modes
|
||||||
|
Skills are sized according to their primary operational mode:
|
||||||
|
* **Reference & Framing**: Conceptual models and vocabulary. (No state machine).
|
||||||
|
* **Transformation & Synthesis**: Single-pass processing. (Preconditions + negative boundary + output schema).
|
||||||
|
* **Procedural Workflow**: High-friction execution disciplines. (Phases + hard pre-condition gates + proof artifacts).
|
||||||
|
* **Interactive Elicitation**: Collaborative dialogue and tutoring. (Batched rounds + fact/decision boundary).
|
||||||
|
* *Modes may blend where justified* (e.g. procedural execution with interactive human checkpoints).
|
||||||
|
|
||||||
|
### 3. Implementation of the `skill-builder` Meta-Skill
|
||||||
|
We deploy `skill-builder` (`~/.gemini/config/skills/skill-builder/SKILL.md` and `/build-skill`) as an **Interactive Elicitation skill**.
|
||||||
|
* **Division of Labor**: The human decides architectural intent, approves boundaries, and owns the final design. `skill-builder` investigates friction, sizes structure, challenges overlap against the live skill catalog, proposes the formal design specification, scaffolds files, and guides regression testing.
|
||||||
|
* **Mandatory Review Gate**: `skill-builder` halts at a formal **Skill Design Specification** and requires explicit human approval before any files are authored.
|
||||||
|
|
||||||
|
### 4. Epistemic Integration of Knowledge Articles
|
||||||
|
We formalize **Knowledge Articles** (`04-learning/knowledge/`, `type: knowledge`) within [`documentation-router`](../../05-agents/skills/README.md):
|
||||||
|
* Governed by `references/knowledge-authoring.md` (in `documentation-router`).
|
||||||
|
* Captures generalized, reusable understanding and methodologies written in a side-by-side learner voice.
|
||||||
|
* Preserves canonical ownership: general lessons live in Knowledge; project explorations live in Discussions; point-in-time commitments live in ADRs; implementation steps live in Plans; incident RCAs live in Debug Records.
|
||||||
|
|
||||||
|
### 5. Investigation Invariant Refinements
|
||||||
|
We refine `engineering-investigation`:
|
||||||
|
* **Evidence Before Hypothesis**: Characterize the failure symptom with observable evidence (logs, error statuses, or reproductions) before forming implementation theories.
|
||||||
|
* **Traceable Diagnostic Mutations & Cleanup**: Every temporary diagnostic modification must have an identifiable cleanup boundary and verification method.
|
||||||
|
* **Sensitive Data Redaction & Zero Leakage**: Diagnostic evidence must be inspected for secrets before being surfaced or persisted.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Consequences
|
||||||
|
|
||||||
|
### Positive Consequences
|
||||||
|
* **Variance Reduction**: Procedural workflows gain enforceable gates that prevent models from skipping verification.
|
||||||
|
* **Anti-Overengineering**: Non-procedural skills remain lightweight without ceremonial boilerplate.
|
||||||
|
* **Cognitive Clarity**: Authors have an explicit 6-stage lifecycle and diagnostic questions to design new skills.
|
||||||
|
* **Vault Completeness**: General engineering methodologies now have a governed, first-class home in `04-learning/knowledge/`.
|
||||||
|
* **Safe Refinement**: Skills are adjusted using the smallest relevant mechanism and verified against regressions.
|
||||||
|
|
||||||
|
### Negative Consequences & Accepted Trade-offs
|
||||||
|
* **Initial Authoring Friction**: Designing a skill through `skill-builder` requires answering substantive architectural questions rather than instantly generating a prompt.
|
||||||
|
* **Catalog Maintenance**: Global skills and their Brain mirrors must be kept synchronized when authoring specifications evolve.
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
---
|
||||||
|
type: decision
|
||||||
|
status: accepted
|
||||||
|
project: brain
|
||||||
|
date: 2026-10-05
|
||||||
|
tags:
|
||||||
|
- agent-architecture
|
||||||
|
- skills
|
||||||
|
- learning-workflow
|
||||||
|
- human-in-the-loop
|
||||||
|
- software-apprenticeship
|
||||||
|
---
|
||||||
|
|
||||||
|
# Agent Skills Pedagogical Decoupling and Governance
|
||||||
|
|
||||||
|
## Context and Problem Statement
|
||||||
|
|
||||||
|
As a career-changer learning software engineering by building real systems, standard industry agent workflows often prioritize automated code generation over engineer comprehension. This introduces an insidious risk: making it too easy to delegate away the exact engineering decisions, architectural trade-offs, and mental debugging models necessary for true skill acquisition.
|
||||||
|
|
||||||
|
Concurrently, repository skills had accumulated substantial operational coupling:
|
||||||
|
1. Skills were duplicated across multiple out-of-sync locations (`~/.gemini/config/skills`, `~/Brain/05-agents/skills`, and global `AGENTS.md` instructions).
|
||||||
|
2. Trivial slash command wrappers (`practice`, `diagnose`, `build-skill`) were maintained solely to expose command ergonomics, re-explaining parent axioms and introducing drift.
|
||||||
|
3. Skills contained verbose procedures (>150 lines), excessive narrative diagrams, and unverified platform assumptions.
|
||||||
|
4. Universal portable workflows were intermixed with personal, vault-specific tooling (such as Brain ledger loggers and inbox curators).
|
||||||
|
|
||||||
|
How do we structure an agent skills system that accelerates building while actively enforcing developer learning, explicit decision ownership, and cross-platform portability?
|
||||||
|
|
||||||
|
## Decision Drivers
|
||||||
|
|
||||||
|
* **Pedagogical Alignment (The Delegation vs. Learning Boundary)**: The workflow must not optimize solely for output volume. It must force the apprentice engineer to pause, understand failure modes, and reason about architectural trade-offs.
|
||||||
|
* **Single Authoritative Source**: Every rule and skill must exist in exactly one canonical location with zero manual synchronization drift.
|
||||||
|
* **Context Load Economics**: Skills must remain concise (target ≤ 50 lines, hard cap 80 lines) to minimize prompt overhead and prevent reasoning dilution.
|
||||||
|
* **Platform Independence**: Core software engineering skills must adhere to open standards (plain Markdown, standard frontmatter) without being tightly coupled to a single vendor or agent harness.
|
||||||
|
* **Clear Epistemic Separation**: General software engineering behaviors must remain strictly decoupled from project-specific knowledge graphs or personal vault structures.
|
||||||
|
|
||||||
|
## Considered Options
|
||||||
|
|
||||||
|
* **Option 1: Monolithic Vault-Coupled Skills (Status Quo)**: Retain skills inside the personal second-brain repository, maintaining mirror copies in the harness configuration directory and wrapper aliases for slash commands.
|
||||||
|
* **Option 2: Standalone Pure-Automation Skills**: Extract skills into a separate repository optimized strictly for autonomous task completion, allowing the agent to diagnose, edit, and commit code without interactive checkpoints.
|
||||||
|
* **Option 3: Standalone Portable Skills with Pedagogical Review Gates (Adopted)**: Decouple skills into a dedicated, public domain repository (`skills`). Merge slash-command wrappers into their parent skills, enforce a strict 80-line budget per skill, separate portable engineering skills from environment-specific extensions, and mandate explicit human checkpoints ("Your call") where the agent must offer 2-3 concrete options rather than deciding autonomously.
|
||||||
|
|
||||||
|
## Decision Outcome
|
||||||
|
|
||||||
|
Chosen option: **Option 3: Standalone Portable Skills with Pedagogical Review Gates**.
|
||||||
|
|
||||||
|
This model establishes a deliberate boundary between task delegation and deliberate practice. The AI provides structured investigative discipline and proposal synthesis, but the apprentice engineer retains ownership of every critical design, diagnostic, and commit boundary.
|
||||||
|
|
||||||
|
### Core Architectural Commitments
|
||||||
|
|
||||||
|
1. **The Delegation vs. Practice Boundary**:
|
||||||
|
- In `/practice`, the learner writes all repository implementation code and drives analysis; the agent acts strictly as a Socratic tutor using graduated assistance and transfer challenges.
|
||||||
|
- In `/diagnose`, the agent gathers empirical evidence and eliminates hypotheses, but pauses at a 6-part checkpoint before crossing any state-changing boundary.
|
||||||
|
- In `/git-commit`, the working tree and diff remain authoritative truth; the agent proposes 2-3 commit slicing options with draft messages, but the human approves every state transition.
|
||||||
|
- In `/document`, the engineer provides the core insight in their own words before drafting begins, preventing AI hallucination of design rationale.
|
||||||
|
|
||||||
|
2. **Single Authority & Wrapper Elimination**:
|
||||||
|
- Every skill's directory `name` directly defines its invocation command. Redundant alias wrappers are eliminated.
|
||||||
|
- The standalone repository `~/Projects/active/skills` is the sole source of truth. Runtime agent configurations install skills via `install.sh`.
|
||||||
|
- The personal Brain vault removes duplicate skill definitions and maintains only an index pointer to the standalone repository.
|
||||||
|
|
||||||
|
3. **Shared Epistemic Skeleton & line Budget**:
|
||||||
|
- All portable skills follow a universal 5-section skeleton: `Use when`, `Steps`, `Your call`, `Done when`, and `Hands off to`.
|
||||||
|
- Hard budget: `SKILL.md` must remain ≤ 80 lines (achieved ≤ 54 lines across all core skills). Deep schemas and reference authoring templates are progressively disclosed under `references/`.
|
||||||
|
|
||||||
|
4. **Hierarchical Separation of Concerns**:
|
||||||
|
- `skills/`: Universally portable engineering skills (`build-skill`, `diagnose`, `document`, `git-commit`, `practice`).
|
||||||
|
- `brain/`: Context-specific extensions (`inbox-curation`, `commit-logger`).
|
||||||
|
- `profile/`: Global developer persona and the universal "Your call" convention (`profile/AGENTS.md`).
|
||||||
|
|
||||||
|
## Pros and Cons of the Options
|
||||||
|
|
||||||
|
### Option 1: Monolithic Vault-Coupled Skills
|
||||||
|
* Good: Kept personal notes and agent configurations within a single workspace repository.
|
||||||
|
* Bad: Caused silent drift between runtime copies and vault specs.
|
||||||
|
* Bad: Made personal vault paths and private project names leak into portable workflows.
|
||||||
|
* Bad: Multiplied maintenance burden across redundant wrapper files.
|
||||||
|
|
||||||
|
### Option 2: Standalone Pure-Automation Skills
|
||||||
|
* Good: Minimizes human keystrokes during rapid prototyping.
|
||||||
|
* Bad: Actively harms the developer's learning path by obscuring underlying mechanisms.
|
||||||
|
* Bad: Encourages passive acceptance of AI-generated architecture without verification.
|
||||||
|
* Bad: Violates the apprentice mindset required to transition into professional engineering.
|
||||||
|
|
||||||
|
### Option 3: Standalone Portable Skills with Pedagogical Review Gates (Adopted)
|
||||||
|
* Good: Protects the learning curve by embedding Socratic friction directly into the development loop.
|
||||||
|
* Good: Achieves 70%+ reduction in skill prompt token overhead.
|
||||||
|
* Good: Idempotent `install.sh` enables deployment to multiple harnesses (Antigravity, Claude Code, Gemini CLI) from one source.
|
||||||
|
* Good: Public domain licensing (The Unlicense) allows the toolkit to serve as a clean public portfolio piece.
|
||||||
|
* Bad: Requires explicit human approval and input at each milestone, sacrificing fully autonomous unattended execution in favor of correctness and learning.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
### Positive Consequences
|
||||||
|
* The engineer must actively articulate hypotheses, verify transfer questions, and select commit boundaries, building foundational engineering instincts.
|
||||||
|
* Skills are fully decoupled from local paths (`/home/<user>`), enabling seamless portability across Linux systems and tools.
|
||||||
|
* Symlink verification demonstrated that modern CLI harnesses cleanly resolve directory and file symlinks without copying.
|
||||||
|
|
||||||
|
### Negative Consequences & Accepted Trade-offs
|
||||||
|
* Workflows require active interactive engagement; long multi-step pipelines cannot run fully unattended without human presence.
|
||||||
|
* When authoring new skills, developers must pass through the `build-skill` design review gate and adhere strictly to the 80-line budget.
|
||||||
|
|
||||||
|
## More Information
|
||||||
|
* **Canonical Repository**: [`kiskaadee/skills`](https://github.com/kiskaadee/skills)
|
||||||
|
* **Shared Architecture Spec**: [`skills/build-skill/references/skeleton.md`](https://github.com/kiskaadee/skills/blob/main/skills/build-skill/references/skeleton.md)
|
||||||
|
* **Vault Index Pointer**: [`05-agents/skills/README.md`](../../05-agents/skills/README.md)
|
||||||
Loaded 100 of 246 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user