Compare commits

..
Author SHA1 Message Date
kiskaadee 01396bdcce knowledge(methods): refine incident runbook operational boundary guidelines
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
2026-09-21 23:54:17 -05:00
kiskaadee 312815525c journal(homelab): refine operator privilege boundary phrasing in webhook rca
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 9s
2026-09-21 23:54:14 -05:00
kiskaadee d37c93cdd8 journal(homelab): record gitops webhook signature mismatch rca
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
2026-09-21 23:45:19 -05:00
kiskaadee 288e89edeb knowledge(methods): add epistemic self-audit checklist and source attribution
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
2026-09-21 23:32:39 -05:00
kiskaadee 85f3c1fa41 knowledge(methods): add scientific incident investigation and journaling protocol
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
2026-09-21 23:13:52 -05:00
246 changed files with 823 additions and 18898 deletions

No files matched your search

+2 -5
View File
@@ -2,8 +2,6 @@
.obsidian/workspace.json
.obsidian/graph.json
.DS_Store
.trash/
*.base
# Environments & Python
.envrc
@@ -11,10 +9,9 @@
.venv/
.local_config.json
.agents/
__pycache__
# Uncommitted Capture & Drafts (Staging Area)
00-inbox/*
!00-inbox/README.md
inbox/*
!inbox/README.md
+1 -2
View File
@@ -1,4 +1,3 @@
{
"alwaysUpdateLinks": true,
"promptDelete": false
"alwaysUpdateLinks": true
}
+1 -2
View File
@@ -1,4 +1,3 @@
{
"cssTheme": "GitHub Theme",
"nativeMenus": true
"cssTheme": "GitHub Theme"
}
File diff suppressed because it is too large. Load diff
-915
View File
@@ -1,915 +0,0 @@
---
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
-389
View File
@@ -1,389 +0,0 @@
---
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.
@@ -1,186 +0,0 @@
---
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.
@@ -1,469 +0,0 @@
---
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)
@@ -1,154 +0,0 @@
---
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`.
@@ -1,181 +0,0 @@
---
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-&lt;slug&gt;-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-&lt;slug&gt;.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.
```
-341
View File
@@ -1,341 +0,0 @@
---
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`).
@@ -1,75 +0,0 @@
---
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).
@@ -1,144 +0,0 @@
---
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)
@@ -1,162 +0,0 @@
---
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.
@@ -1,194 +0,0 @@
---
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.
@@ -1,539 +0,0 @@
---
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.
@@ -1,557 +0,0 @@
---
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.
@@ -1,511 +0,0 @@
---
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.
@@ -1,253 +0,0 @@
---
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.
@@ -1,275 +0,0 @@
---
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,159 +0,0 @@
---
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,217 +0,0 @@
---
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,105 +0,0 @@
---
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.
@@ -1,480 +0,0 @@
---
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
```
-505
View File
@@ -1,505 +0,0 @@
---
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)`.
@@ -1,127 +0,0 @@
---
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 |
-204
View File
@@ -1,204 +0,0 @@
---
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
```
-179
View File
@@ -1,179 +0,0 @@
---
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.
@@ -1,97 +0,0 @@
---
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/`.
@@ -1,104 +0,0 @@
---
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.
@@ -1,192 +0,0 @@
---
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.
@@ -1,237 +0,0 @@
---
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
```
@@ -1,326 +0,0 @@
---
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.
@@ -1,120 +0,0 @@
---
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`.
@@ -1,421 +0,0 @@
---
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.
@@ -1,156 +0,0 @@
---
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).
@@ -1,129 +0,0 @@
---
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`.
@@ -1,95 +0,0 @@
---
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.
@@ -1,139 +0,0 @@
---
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)
@@ -1,133 +0,0 @@
---
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).
@@ -1,94 +0,0 @@
---
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`
@@ -1,162 +0,0 @@
---
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 |
@@ -1,163 +0,0 @@
---
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.
@@ -1,136 +0,0 @@
---
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.
@@ -1,79 +0,0 @@
---
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,204 +0,0 @@
---
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/)
@@ -1,192 +0,0 @@
---
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/)
@@ -1,158 +0,0 @@
---
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)
@@ -1,70 +0,0 @@
---
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
```
@@ -1,160 +0,0 @@
---
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.
@@ -1,99 +0,0 @@
---
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.
@@ -1,105 +0,0 @@
---
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)
@@ -1,47 +0,0 @@
---
type: decision
status: accepted
project: nixos
date: 2026-09-27
tags:
- nixos
- antigravity
- flake
- packaging
- developer-tools
---
# Architectural Decision Record: Unified Antigravity Flake Packaging
## 1. Context & Problem Statement
The `laptop` NixOS workstation requires access to the complete Google Antigravity developer ecosystem across all three primary operational surfaces:
1. `google-antigravity-cli`: The terminal CLI binary (`agy`).
2. `google-antigravity`: The Electron-based desktop GUI application (Antigravity 2.0).
3. `google-antigravity-ide`: The VS Code-derived AI-first development environment.
Previously, incorporating rapidly evolving AI developer tools into a NixOS configuration posed maintenance friction:
- Packaging each component individually in `~/Config` requires tracking separate upstream tarballs, deb/rpm assets, and release hashes.
- Manual derivation maintenance introduces the risk of version desynchronization across the CLI, GUI, and IDE components.
- Upstream updates require manual derivation bumps and rebuild testing directly within the core workstation configuration.
## 2. Decision
We adopt `github:jacopone/antigravity-nix` as the single unified flake input (`inputs.antigravity`) in the workstation configuration (`Config/flake.nix`).
- **Upstream Repository**: `github:jacopone/antigravity-nix`
- **Flake Input**: `inputs.antigravity`
- **Exposed Packages**:
- `inputs.antigravity.packages.${system}.google-antigravity-cli`
- `inputs.antigravity.packages.${system}.google-antigravity`
- `inputs.antigravity.packages.${system}.google-antigravity-ide`
## 3. Consequences
### Positive
- **Bundled 3-Component Ecosystem**: A single flake input packages and maintains all three surfaces, eliminating redundant derivation authoring.
- **Synchronized Upstream Cadence**: Automated upstream updates in the flake ensure the CLI, desktop GUI, and IDE remain version-aligned, preventing API or protocol mismatches.
- **Declarative Flake Decoupling**: Upstream tool updates are cleanly consumed via `nix flake update antigravity` without touching system configuration build recipes.
### Negative / Trade-offs
- **External Flake Dependency**: Introduces a dependency on an external flake repository (`jacopone/antigravity-nix`) for maintenance and packaging updates rather than official upstream Nixpkgs derivations.
@@ -1,120 +0,0 @@
---
type: decision
status: accepted
project: bdinvite
date: 2026-10-01
tags:
- architecture
- fastapi
- react
- traefik
- authelia
- docker
- security
---
# BDInvite Single-Container Architecture, Split Traefik Routing & ForwardAuth Integration
## Context and Problem Statement
When deploying lightweight, event-specific web applications (such as the interactive birthday invitation `bdinvite` with guest RSVP and admin management) into the personal homelab ecosystem at `roadtotech.me`, the infrastructure must balance developer ergonomics, resource efficiency, and perimeter security.
The application requires:
1. A frictionless, zero-barrier public portal for guests to view event details and submit RSVPs.
2. A strictly secured administration portal for reviewing the guest list, exporting CSVs, and editing event configuration in real time.
3. Hosting under a shared domain (`demos.roadtotech.me`) alongside future demonstration sites, without incurring unnecessary multi-container memory and orchestration overhead on the host.
How should the application packaging, edge ingress routing, and authentication boundaries be structured to satisfy these requirements?
---
## Decision Drivers
* **Resource Footprint & Operational Simplicity**: Avoid deploying multi-container stacks (separate Nginx reverse proxy containers, dedicated database daemons, or separate frontend webservers) for small micro-sites.
* **Perimeter Security without Auth Duplication**: Protect administrative endpoints using the platform's central single sign-on (Authelia SSO over ForwardAuth) rather than implementing custom username/password forms, JWT sessions, or credential databases inside the application.
* **Granular Access Control on a Single Subdomain**: Allow public guest access on `demos.roadtotech.me/birthday` while enforcing SSO strictly on `demos.roadtotech.me/birthday/admin*`.
* **Zero External Data Leakage & Offline Resilience**: Prevent client browsers from making runtime requests to third-party CDNs (such as Google Fonts) to preserve guest privacy and guarantee aesthetic consistency across all devices.
* **Defense-in-Depth**: Ensure administrative API routes cannot be accessed anonymously even if edge routing rules are misconfigured or bypassed.
---
## Considered Options
* **Option 1: Multi-Container Microservices Stack** — Separate Nginx container serving the static React build, separate FastAPI container for the API, and an external PostgreSQL database container, managed via Docker Compose.
* **Option 2: Single-Container Multi-Stage Build with Embedded SQLite and Split Traefik Routing** — Single container containing the compiled React SPA served directly by FastAPI and `uvicorn`, SQLite WAL database persisted on a volume mount, and Traefik path-based priority routing with Authelia ForwardAuth.
* **Option 3: External Jamstack / Serverless Form Integration** — Static site hosted on GitHub Pages or Cloudflare Pages, forwarding RSVPs to a third-party form aggregator (Airtable or Formspree).
---
## Decision Outcome
Chosen option: **Option 2: Single-Container Multi-Stage Build with Embedded SQLite and Split Traefik Routing**, because it maximizes operational simplicity and resource efficiency on the homelab host while maintaining strict defense-in-depth security and full data sovereignty.
### Summary of Architectural Commitments
1. **Single-Container Multi-Stage Deployment**:
- The production container is built using a two-stage Dockerfile: Stage 1 (`node:20-alpine`) compiles the Vite React 19 application; Stage 2 (`ghcr.io/astral-sh/uv:python3.11-bookworm-slim`) installs Python dependencies and copies the compiled `dist/` directory into `./static`.
- FastAPI serves both API endpoints under `/birthday/api/*` and the static SPA assets under `/birthday/assets/*`, routing all unhandled sub-paths under `/birthday/*` to `static/index.html` to support client-side React Router navigation.
2. **Split Path-Based Routing & Ingress Priority**:
- The workload exposes container port 8000 to the shared `proxy-net` network.
- Traefik defines two overlapping HTTPS routers on `demos.roadtotech.me`:
- **Public Router (`bdinvite-public`)**: Rule `Host(\`demos.roadtotech.me\`) && PathPrefix(\`/birthday\`)`, `priority: 10`, no authentication middleware.
- **Admin Router (`bdinvite-admin`)**: Rule `Host(\`demos.roadtotech.me\`) && PathPrefix(\`/birthday/admin\`)`, `priority: 20`, middleware `authelia-auth@docker`.
- Because Traefik prioritizes higher-priority rules, any request beginning with `/birthday/admin` is intercepted by Authelia ForwardAuth before reaching the container, while all other `/birthday` requests remain publicly accessible.
3. **Defense-in-Depth Backend Identity Verification**:
- The application does not manage passwords or tokens.
- When an admin request is authenticated, Authelia forwards the `Remote-User` header to the backend.
- Every administrative API endpoint under `/birthday/api/admin/*` enforces a FastAPI dependency requiring the presence of `Remote-User`. Requests missing this header immediately return HTTP 401 Unauthorized, ensuring that private endpoints are secured independently of edge proxy behavior.
4. **Self-Hosted Typography & Static Asset Isolation**:
- Brand fonts (`Playfair Display` and `Plus Jakarta Sans`) are packaged locally as `.woff2` files within `frontend/src/fonts/` and imported into CSS bundle assets.
- Runtime dependencies on Google Fonts or external CDNs are strictly prohibited, ensuring zero external referrer tracking and guaranteed availability.
5. **Persistence Isolation via SQLite WAL**:
- Data is stored in `./data/bdinvite.db` using SQLite with Write-Ahead Logging (`PRAGMA journal_mode=WAL;`).
- The database file is mounted from the host filesystem, providing full durability, instant atomic backups, and zero background daemon memory consumption.
---
## Pros and Cons of the Options
### Option 1: Multi-Container Microservices Stack
* Good, because it adheres to classic separation of static content from API processes.
* Good, because Nginx is highly optimized for static file delivery.
* Bad, because running 2–3 containers (Nginx, FastAPI, Postgres) for a small event invitation wastes container memory and orchestrator overhead.
* Bad, because managing inter-container networking for a single micro-workload increases Compose configuration complexity.
### Option 2: Single-Container Multi-Stage Build with Embedded SQLite and Split Traefik Routing (Adopted)
* Good, because total runtime overhead is confined to a single lightweight Python process consuming minimal RAM.
* Good, because deployments and updates are atomic: updating the container image deploys synchronized frontend and backend changes simultaneously.
* Good, because edge authentication is fully offloaded to central Authelia SSO without duplicating identity code.
* Good, because SQLite WAL mode provides concurrent read performance and zero maintenance operations.
* Bad, because static file delivery is handled by Starlette/FastAPI rather than dedicated Nginx; however, for the expected traffic scale of an invitation site, FastAPI's async file response is more than sufficient.
### Option 3: External Jamstack / Serverless Form Integration
* Good, because zero host resources are consumed.
* Bad, because it sacrifices data sovereignty and stores personal guest contact information (names, phone numbers) on third-party servers.
* Bad, because it breaks homelab platform integration, making unified monitoring, SSO, and local backups impossible.
---
## Consequences
### Positive Consequences
* **Streamlined Operations**: The workload can be inspected, stopped, restarted, or updated via a single `appctl` invocation (`appctl update bdinvite`).
* **Robust Access Boundary**: Guests experience zero friction when confirming attendance, while administrative dashboards and CSV exports remain safely behind multi-factor SSO.
* **Hermetic Local Development**: Developers can run the backend and frontend together or independently using the local Nix devShell (`nix develop`) without configuring local reverse proxies.
### Negative Consequences & Accepted Trade-offs
* **Path Prefix Sensitivity**: Frontend build assets and React Router must explicitly be configured with base path `/birthday` (`base: '/birthday/'` in Vite, `basename="/birthday"` in React Router) to avoid root path collisions on `demos.roadtotech.me`.
* **Traefik Priority Dependency**: Edge security relies on explicit Traefik router priorities (`priority: 20` for admin vs. `priority: 10` for public); however, this risk is mitigated by the mandatory `Remote-User` backend defense-in-depth check.
---
## More Information
* **Project Hub**: [BDInvite Project Hub](../../06-projects/bdinvite/README.md)
* **Infrastructure Context**: [Homelab Ecosystem & Core Infrastructure](../../06-projects/homelab/README.md)
* **Workstation DevShell & Tooling**: [Biome Monorepo VCS Symmetry](../../04-learning/knowledge/technologies/biome-monorepo-vcs-symmetry.md)
@@ -1,111 +0,0 @@
---
type: decision
status: accepted
project: homelab
date: 2026-09-28
tags:
- homelab
- architecture
- decisions
- adr
- provenance
- gitops
- kiss
---
# Homelab 3-Tier Architecture & Deployment Provenance Model
## Context and Problem Statement
The `roadtotech.me` homelab operates as a dedicated NixOS appliance hosting self-hosted productivity services and personal backend engineering projects. In early iterations (v1 through v3):
1. **Application & Deployment Coupling**: In-house applications (`doc2site`, `bitetrack`) co-located application source trees with host-specific Traefik labels, Docker bridge networks, and host path mounts inside individual Git repositories in `~/Sites/<app>`.
2. **Repository Inflation**: Off-the-shelf applications (`jellyfin`, `stirling`) required entire standalone Git repositories simply to store a minimal Compose file and manifest.
3. **Ambiguous Freshness**: Local Git status checks in `~/Sites/<app>` could only report if deployment descriptors had uncommitted edits, never whether running containers matched current upstream application source code.
4. **Orchestrator Sprawl Risk**: Scaling operational scripts threatened to introduce secondary distributed infrastructure (queues, databases, brokers) around basic container deployments.
How should we structure application code, deployment configuration, and platform orchestration to maintain strict separation of concerns, verifiable provenance, and KISS operations?
## Decision Drivers
* **Clean Separation of Concerns**: In-house software projects must be developable, testable, and publishable independently of private Homelab infrastructure.
* **Workload Simplicity**: Off-the-shelf applications should not incur standalone repository overhead.
* **Verifiable Provenance**: Operators must be able to independently verify deployment configuration freshness versus upstream software code freshness.
* **KISS Primitives & Minimal Control Paths**: Operational reconciliation must remain bounded, deterministic, and linear without distributed brokers, queues, or deployment databases.
* **Filesystem State Hygiene**: Mutable runtime data must never reside inside version-controlled Git trees.
## Considered Options
* **Option 1: Monolithic / Single-Repo Deployment (Status Quo v1–v3)** — Co-locate application code, Dockerfiles, Compose files, and mutable runtime state inside a single Git repository per application.
* **Option 2: Miniature Cloud Platform** — Introduce message brokers (RabbitMQ/Redis), a Postgres deployment database, multi-environment controllers, and asynchronous rollback daemons.
* **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path** — Decouple Software, Deployment, and Platform tiers; connect them via OCI image artifacts carrying source revision labels and content-addressed digests; enforce linear deployment reconciliation and isolated host state roots.
## Decision Outcome
Chosen option: **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels & Linear Control Path**, because it addresses the identified coupling and provenance problems while retaining a bounded operational control path.
### Summary of Architectural Commitments
1. **3-Tier Separation of Concerns**:
* **Software Layer (Application Repositories)**: Standalone Git repositories on Gitea/GitHub owning application code, tests, Dockerfiles, and CI workflows. Zero Homelab coupling.
* **Intermediate Artifacts**: OCI container images produced by CI act as provenance objects; the immutable identity of the deployed artifact is its OCI digest, with source commit provenance carried via the `org.opencontainers.image.revision` label.
* **Deployment Layer (Sites Workload Plane)**: Declarative catalog in `~/Sites/*` owning environment-specific `app.yaml` manifests and Compose definitions.
* **Platform Layer (Homelab Core Appliance)**: NixOS appliance (`~/Core`) owning edge routing, SSO, shared capabilities, and operational controllers (`appctl`, GitOps receiver).
2. **Two Workload Deployment Classes**:
* *Class A (Source-Backed)*: Declares explicit upstream `source:` pointer (canonical Git URL and ref); tracks upstream Git revisions against container image labels.
* *Class B (Image-Only)*: Omits `source:`; deployment freshness relies strictly on container registry image tags and digests.
3. **Decoupled Deployment Configuration & Software Provenance**:
* Distinguishes local deployment checkout state (`Sites/<app>`) from upstream software provenance (`source.url` vs. deployed container).
* Mandates that deployment configuration, upstream source provenance, and container artifact identity must be independently observable (with exact schema fields defined in the implementation plan).
4. **Minimal Linear Reconciliation Path**:
* The deployment lifecycle remains strictly linear:
$$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl update} \longrightarrow \text{Compose Up}$$
* `appctl update` operates purely as a local, deterministic deployment reconciliation primitive. All secondary message queues, brokers, and deployment databases are strictly rejected.
5. **Isolated Host State Root**:
* Mutable application runtime state (databases, caches, uploads) is decoupled from version-controlled directories and provisioned under `~/var/lib/homelab/<app>/`.
## Pros and Cons of the Options
### Option 1: Monolithic / Single-Repo Deployment
* Good, because it is familiar and requires only one Git repository per custom app.
* Bad, because host-specific configuration leaks into application source code, preventing reuse or open-sourcing.
* Bad, because off-the-shelf tools require empty "wrapper" repositories.
* Bad, because a single commit SHA conflates software revisions with deployment descriptor edits.
* Bad, because mutable state co-located in `Sites/<app>/data` risks accidental commits and creates dirty Git trees.
### Option 2: Miniature Cloud Platform
* Good, because it mirrors enterprise Kubernetes / ArgoCD continuous deployment capabilities.
* Bad, because running distributed brokers, queues, and databases on a single home appliance creates massive operational overhead and resource footprint.
* Bad, because it introduces complex failure modes and violates the KISS principle.
### Option 3: Bounded 3-Tier Platform with OCI Provenance Labels
* Good, because in-house software is completely decoupled from homelab infrastructure and can be open-sourced cleanly.
* Good, because off-the-shelf software incurs zero repository overhead.
* Good, because deployment inspection resolves both configuration status and code provenance unambiguously.
* Good, because runtime state is cleanly separated into `~/var/lib/homelab/<app>/`.
* Good, because it maintains the fewest independent concepts and control paths (KISS).
* Bad, because custom in-house applications require managing two Git repositories (source repository and Sites catalog entry).
* Bad, because verifying remote revisions without local clones is restricted to commit equality (`git ls-remote`), foregoing ahead/behind commit distance counts.
## Consequences
### Positive Consequences
* **Independent Software Lifecycle**: In-house applications (`bitetrack`, `doc2site`) can be shared, tested, or migrated without exposing homelab secrets, domain routing, or bridge networks.
* **Precise Diagnostic Truth**: Operators and automation tools can independently determine whether a deployment configuration changed, a new image was published, or upstream source code was updated.
* **Clean State Boundaries**: Git repositories in `~/Sites` contain only declarative manifests and compose files; databases and runtime media live exclusively in dedicated host state roots.
* **Operational Restraint**: Eliminates orchestrator sprawl by keeping reconciliation linear, synchronous, and local.
### Negative Consequences & Accepted Trade-offs
* **Dual Repositories for In-House Applications**: Deploying a change to an in-house app requires pushing code to CI, followed by updating or pinning the Sites catalog when tag/SHA pinning is desired.
* **Commit Equality Without Ancestry Graph**: Remote Git inspection confirms whether the running container matches the upstream ref HEAD, but cannot report commit distance without performing a full source clone.
## More Information
* **Informing Discussion & Rationale**: [`02-discussions/homelab/architecture-migration-v3-to-v4.md`](../../02-discussions/homelab/architecture-migration-v3-to-v4.md)
* **Governed Implementation Roadmap**: [`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md)
* **Project Hub**: [`06-projects/homelab/README.md`](../../06-projects/homelab/README.md)
@@ -1,226 +0,0 @@
---
type: decision
status: accepted
project: homelab
date: 2026-10-07
tags:
- homelab
- architecture
- decisions
- adr
- appctl
- control-plane
- security
- identity
- provenance
---
# Homelab Operational Control Plane & Deployment Model Architecture
## Context and Problem Statement
The `roadtotech.me` platform historically relied on `appctl` as a local, procedural Bash CLI wrapper (`scripts/appctl`) coupled with a Python metadata engine (`scripts/appctl_engine.py`). Operational commands (`up`, `down`, `restart`, `update`, `logs`, `sync`) executed as ad-hoc subprocesses on the server host, sourcing environment files from `/run/secrets/`.
This model created several architectural tensions:
1. **Coupled Unix Authority**: Executing operational commands required SSH access to the server with Unix user credentials and sudo privileges, conflating platform operations with host administration.
2. **Interface Fragmentation**: The local CLI, the GitOps webhook dispatcher, and dashboard synchronization tools independently implemented or invoked deployment actions, risking divergent operational behavior.
3. **Secret Lifecycle Coupling**: Workload secrets were coupled to the operator's laptop via SOPS and Age keys, requiring encrypted diffs in Git history and full NixOS rebuilds for every secret rotation.
4. **Manual Workload Authoring Friction**: Adding a new application required manually creating directories under `~/Sites`, configuring Docker Compose files, and handwriting Traefik ingress labels and network bindings.
5. **Absence of Unified Auditability**: Operational commands lacked an authenticated, centralized ledger capturing operator identity, client IP, action, target revision, and execution outcome.
How should Homelab Core transition its operational architecture to provide a centralized operational control plane, robust identity boundaries, clean secret distribution, and safe deployment authoring without introducing distributed cloud complexity?
## Decision Drivers
* **Control Plane Centralization**: Exactly one authoritative implementation of every operational action (`deploy`, `restart`, `inspect`, `sync`, `validate`).
* **Identity Decoupling & Least Privilege**: Operating the homelab platform must not require host Unix administrative credentials. Host access does not confer appctl authority.
* **Declarative Git Ground Truth**: Git remains the authoritative source of truth for deployment state, maintaining provenance, rollback capability, and version history.
* **Separation of Intent from Materialization**: Differentiate candidate deployment suggestions (`DeploymentProposal`) from validated, implementation-agnostic intent (`DeploymentModel`), and both from materialized runtime descriptors (`app.yaml`, Compose files).
* **KISS Primitives & Minimal Control Paths**: Avoid distributed message brokers, microservice meshes, or deployment databases. Preserve linear, synchronous, and observable execution.
* **Secret Reference Invariant**: Deployment definitions must contain secret references, never plaintext or encrypted secret material.
* **Client / Control-Plane Boundary**: The control plane owns operational logic; user interfaces (CLI, dashboard, AI authoring) are downstream clients.
## Considered Options
* **Option 1: Status Quo with Modernized Local CLI (appctl-v2)** — Modernize `appctl_engine.py` into a type-safe Python engine while keeping it strictly a local command-line tool executed over SSH.
* **Option 2: Cloud-Native Micro-Platform (Kubernetes / Nomad / ArgoCD)** — Replace `appctl` with enterprise orchestration frameworks and distributed control loops.
* **Option 3: Homelab Operational Control Plane with Stable Deployment Model** — Evolve `appctl` into a centralized, command-oriented control plane daemon exposed via Unix socket and HTTP. Git remains the authoritative deployment ledger. Introduce a formal `DeploymentModel` validated against Core capabilities and invariants.
## Decision Outcome
Chosen option: **Option 3: Homelab Operational Control Plane with Stable Deployment Model**, because it centralizes operational authority, decouples operator identity from Unix credentials, preserves Git as declarative ground truth, and establishes a secure deployment authoring seam while preserving the lightweight, appliance-based foundation of Homelab Core.
---
### Summary of Architectural Commitments
```text
Human Operator / Automation
│
┌───────────────────┴───────────────────┐
│ │
Operations UI CLI (Local & Remote)
│ │
└───────────────────┬───────────────────┘
│
appctl Control Plane API
(One Logical API across Transports)
│
┌────────────┴────────────┐
│ │
Unix Socket HTTP Listener
(Host Clients) (Remote/LAN Clients)
│ │
└────────────┬────────────┘
│
┌───────────────────────────┼───────────────────────────┐
│ │ │
Authentication Deployment Model Operations
& Authorization Plane Execution
│ │ │
Token Validation & ┌──────┴──────┐ Docker Compose
LLDAP Directory RBAC │ │ Traefik Routing
AI Investigation Human Host Secrets
│ Approval Reconciliation
▼ │
DeploymentProposal │
│ ▼
└─────▶ DeploymentModel
│
▼ (Committed to Git)
Deployment Repository
(Git Truth)
│
▼ (appctl validates & materializes)
Deployment Definition
(Sites app.yaml + compose)
│
▼
Runtime Reconciliation
```
#### 1. One Logical Control-Plane API across Dual Transports (`DEC-01`)
* `appctl` transitions from a collection of local shell scripts into the authoritative **operational control plane service** for Homelab Core, managed as a systemd service (`homelab-appctl.service`).
* The control plane exposes **one logical, command-oriented HTTP/1.1 API** dispatched through a single canonical operation endpoint: `POST /v1/operations` (covering all 13 canonical domain operations) and `GET /v1/health` (liveness probe), validated by strict Pydantic v2 contracts (`extra="forbid"`, `strict=True`). Multi-route REST aliases are rejected.
* Transport is decoupled from contract:
* **Unix Domain Socket** (`/run/homelab/appctl.sock`, mode `0660`, `homelab-appctl:homelab-operators`): Used by local host clients (thin-client CLI and `gitops_dispatcher.py` worker).
* **HTTP Listener** (`127.0.0.1:9001` in P4; LAN/Traefik ingress in P5+): Used by network clients (remote CLI, Operations UI).
* Both local and remote clients invoke the exact same logical API schema.
#### 2. Identity, Authentication, Service Isolation & Fail-Closed Audit (`DEC-02`, `DEC-03`)
* **Host Access Does Not Confer Appctl Mutation Authority**: Entering the server via SSH is merely host access; it does not substitute for appctl mutation authentication. **Every mutating appctl operation and sensitive read (`workload.config`, `workload.logs`) requires an explicit, authenticated Bearer token**, regardless of transport.
* **Authentication Modes**:
* *SOPS-Projected Bearer Tokens (P4 Baseline)*: Validated via constant-time SHA-256 comparison (`hmac.compare_digest`) against `/run/secrets/appctl/tokens.json` (`0400`). Required for all mutations, sensitive reads, and HTTP requests.
* *Local UDS `SO_PEERCRED` Viewer Fallback (`DEC-02`)*: Tokenless local Unix socket connections extract kernel peer credentials (`SO_PEERCRED`) and fall back strictly to `homelab-viewer` read-only privileges (`list`, `get`, `resolve`, `ssl`, `health`), preserving zero-friction CLI inspection and shell tab-completion while blocking all mutations (`401`/`403`).
* *GitOps Ingress & Worker (`DEC-04`)*: `gitops_dispatcher.py` verifies Gitea webhook HMAC-SHA256 signatures, enforces `config/deployments.yaml` admission, and delegates `workload.update` over `/run/homelab/appctl.sock` using its `homelab-operator` Bearer token.
* *Interactive Web / LLDAP Directory Integration (P5)*: Expands the P4 gate with LLDAP user-scoped token lifecycle and authenticated Traefik/Authelia ForwardAuth headers (`Remote-User`, `Remote-Groups`).
* **Role-Based Access Control (RBAC)**: Enforces three tiers: `homelab-admin` (all targets including `core`/`core_service`), `homelab-operator` (restricted strictly to workloads in `config/deployments.yaml`), and `homelab-viewer` (non-sensitive reads only).
* **Dedicated Service Identity (`DEC-03`)**: The daemon runs as `homelab-appctl` (`Group = "homelab-operators"`), isolating `/run/secrets/appctl/tokens.json` (`0400`) and `/var/log/homelab/appctl/audit.jsonl` (`0600`) from unprivileged processes and AI coding sessions running under the operator's SSH UID.
* **Telemetry & Fail-Closed Append-Only Audit Log (`/var/log/homelab/appctl/audit.jsonl`)**: Every mutating operation, sensitive read, and denied request records structured JSONL lifecycle events (`DISPATCHED`, `COMPLETED`, `FAILED`, `DENIED`) capturing:
* `Principal`: Identity, role, token ID, and auth method (`bearer_token` vs. `unix_peercred`).
* `Action` & `Target`: The requested canonical operation and workload.
* `Transport` & `Origin`: `unix_socket` (`peer_uid_<uid>`) vs. `http` (`client_ip`).
* `Client`, `Timestamp`, `Duration`, `Commit SHA`, and secret-redacted `Parameters`/`Result`.
* **Fail-Closed Disk Guard**: Mutating operations must write and flush a `DISPATCHED` record before any Docker or Git subprocess executes; if the write fails, the operation aborts immediately with `500 ERR_EXECUTION_FAILED`.
#### 3. Declarative Git Truth as Authoritative Deployment State
* **Git is the Authoritative Source of Deployment State**:
* When a human operator approves a `DeploymentModel`, that model is committed to the version-controlled deployment catalog (Git).
* `appctl` does not bypass version control. Git maintains immutable revision history, commit provenance, peer reviews, and rollback capability (`git revert`).
* `appctl` serves as the authoritative reconciliation engine: it validates the versioned `DeploymentModel`, compiles/materializes the concrete platform descriptors (`app.yaml` + `docker-compose.yml`), provisions isolated state roots (`~/var/lib/homelab/<app>/`), and reconciles running containers.
#### 4. Five-Stage Deployment Lifecycle (Intent vs. Implementation)
* We separate candidate investigation, validated intent, and implementation artifacts into a clean progression:
$$\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel} \xrightarrow{\text{Git Commit}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Runtime Containers}$$
1. **Application Profile**: Factual evidence gathered from repository inspection (detected ports, dependencies, persistence needs).
2. **`DeploymentProposal`**: Candidate architectural options generated by the authoring agent (e.g. Model A Minimal, Model B Persistent, Model C Full Stack).
3. **`DeploymentModel`**: The operator-selected, implementation-agnostic representation of desired intent (ports, domain routing, persistent storage, dependencies, environment references). Free of Docker Compose or Traefik label boilerplate.
4. **Deployment Definition**: Ground-truth platform descriptors (`app.yaml` + `docker-compose.yml`) materialized and enforced by `appctl`.
5. **Runtime Reconciliation**: Deterministic container recreation and health verification.
#### 5. AI Workflow as a Disconnected Authoring Client
* The AI authoring agent is strictly an upstream client with **zero execution or mutation authority**:
* The AI analyzes repositories and drafts `DeploymentProposal` candidates.
* The operator edits, selects, and approves the proposal into a `DeploymentModel`.
* **After human approval, the AI is completely out of the loop.**
* The control plane API exposes only standard authenticated operations (`POST /v1/operations`), giving the AI zero special administrative endpoints or ambient host privileges.
#### 6. Platform Capability Model & Architectural Invariants
Authoring workflows reason against an explicit platform contract:
* **Exposed Capabilities**:
* HTTP edge ingress routing via Traefik (automatic TLS, domain mapping).
* Persistent storage attachments to `/home/kiskaadee/var/lib/homelab/<app>/`.
* Dedicated bridge network attachments (`proxy-net`).
* Deterministic healthchecks (HTTP, TCP, container).
* Resource limits (CPU, memory).
* Secret references resolved at runtime.
* Provenance classes: Class A (Source-Backed) vs. Class B (Image-Only).
* **Non-Negotiable Invariants**:
* Zero privileged containers (`privileged: false`).
* Zero direct Docker socket mounts (`/var/run/docker.sock` restricted to `socket-proxy`).
* Zero arbitrary host mounts (state strictly isolated to dedicated state root).
* Zero arbitrary shell commands or custom lifecycle scripts.
* Zero plaintext secrets in manifests or Compose files.
* Application state isolated from Git deployment descriptors.
* Explicit provenance tracking (`source.url`, `source.ref`, and OCI image digest).
#### 7. Secret Reference & SecretProvider Boundary
* **Architectural Invariant**: Deployment definitions contain **secret references**, never secret material.
* `appctl` defines a clean `SecretProvider` interface. At deployment reconciliation time, `appctl` resolves references through the provider and projects secrets into the workload runtime.
* **Domain Segregation**:
* Host platform secrets remain declaratively managed via `sops-nix` in `nixos/secrets.yaml`.
* Workload application secrets are referenced by key and resolved dynamically, eliminating Git history pollution and laptop-key coupling without turning `appctl` into an ad-hoc cryptographic vault.
#### 8. Client Decoupling & UI Boundary
* `appctl` owns the control-plane contract, not its clients.
* **Homepage**: Remains the read-only service portal and status aggregator, consuming status data from `appctl`. It does not become an interactive deployment console.
* **Operations UI**: A dedicated, lightweight web client for interactive approvals, token generation, and log viewing, deployed as a client of the `appctl` API.
* **CLI (Local & Remote)**: Command-line clients consuming the `appctl` API.
---
## Pros and Cons of the Options
### Option 1: Status Quo with Local CLI Modernization
* Good: Requires no new daemons or networking listeners.
* Bad: Perpetuates host SSH credential sharing for basic operations.
* Bad: Provides no programmatic API for web dashboards or AI workflows.
* Bad: Remote management requires interactive SSH terminal access.
### Option 2: Cloud-Native Micro-Platform
* Good: Kubernetes/ArgoCD natively provide declarative control planes, RBAC, and APIs.
* Bad: Resource overhead and operational complexity are disproportionate for a single-node homelab appliance.
* Bad: Violates the KISS principle and introduces complex distributed failure modes.
### Option 3: Homelab Operational Control Plane with Stable Deployment Model (Adopted)
* Good: Unifies all operations behind a single authoritative implementation.
* Good: Enforces directory-backed RBAC and produces a verifiable audit trail without exposing host Unix credentials.
* Good: Preserves Git as declarative ground truth for deployment state.
* Good: Introduces a clean authoring boundary (`DeploymentProposal` $\to$ `DeploymentModel`) that makes AI-assisted deployments safe and reviewable.
* Good: Decouples secret management from Git history pollution.
* Bad: Requires running and monitoring an additional Core systemd daemon (`homelab-appctl.service`).
* Bad: Requires managing API tokens for remote and local CLI clients.
---
## Consequences
### Positive Consequences
* **Principle of Least Privilege**: Routine operations (deploying apps, viewing logs, restarting services) no longer require host root/sudo SSH access.
* **Single Operational Truth**: Local CLI, remote CLI, GitOps, and web clients invoke identical control-plane logic.
* **Declarative Reproducibility**: Deployments remain 100% reproducible and auditable through version-controlled Git history.
* **Safe AI Authoring**: AI agents can inspect repositories and generate rich proposals, but can never directly mutate the host.
* **Clean Auditability**: Every operational state change is attributable to a specific identity and recorded with transport and origin telemetry.
### Negative Consequences & Accepted Trade-offs
* **Daemon Availability Dependency**: Operations depend on the health of the `homelab-appctl` service. (Emergency fallback: direct Docker Compose commands remain available to host administrators via SSH).
* **Explicit Token Discipline**: Host execution over SSH requires an explicit token rather than inheriting shell user privileges.
---
## More Information
* **Companion Architecture Decision**: [`homelab-3tier-architecture-and-provenance.md`](homelab-3tier-architecture-and-provenance.md)
* **Governed Implementation Roadmap**: [`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md)
* **Project Hub**: [`06-projects/homelab/README.md`](../../06-projects/homelab/README.md)
-47
View File
@@ -1,47 +0,0 @@
---
type: journal
project: homelab
date: 2026-09-18
tags:
- operations
- homelab
- troubleshooting
- gitea
- nix
- ci-cd
- dns
- docker
---
# Daily Journal: 2026-09-18
## Wins
### CI/CD Standardization & Git Mirror Resilience
Hardened the local developer platform and forge infrastructure across `homelab-core` and Gitea:
- Eliminated dynamic CI toolchain initialization delays, reducing pipeline validation runtime from >5 minute hangs to 16 seconds.
- Restored continuous outbound Git mirroring between self-hosted Gitea repositories and GitHub upstreams.
---
## Incidents & Debugging
- [Remediation: Gitea Actions CI Build Hang on Nix Installation](../debug/2026-09-18-gitea-actions-nix-runner-fix.md)
- **Issue**: The `validate` workflow job in `homelab-core` hung indefinitely (>5 minutes) at the `Install Nix` step, blocking all pull requests and pushes.
- **Root Cause**: `DeterminateSystems/nix-installer-action` attempted multi-user installation requiring systemd sockets absent in Gitea's `act_runner` container, while targeting GitHub API endpoints instead of Gitea.
- **Remediation**: Switched the workflow job container to `nixos/nix:latest`, configured `safe.directory`, and verified execution dropped to 16 seconds.
- [Incident RCA: Gitea GitHub Mirror Push Failure & Docker DNS Forwarder Resolution](../debug/2026-09-18-gitea-github-mirror-dns-resolution-failure.md)
- **Issue**: Gitea push mirrors failed with `fatal: unable to access 'https://github.com/...': Could not resolve host: github.com`.
- **Root Cause**: The embedded Docker DNS resolver (`127.0.0.11`) inside the container lost synchronization with host upstream nameservers following network reconfiguration, returning `SERVFAIL`.
- **Remediation**: Restored container network forwarding and verified successful push synchronization across all repositories.
---
## Mistakes and Lessons Learned
### Pre-Baked CI Images vs Dynamic In-Job Installers
Dynamic package and toolchain installers in containerized runners introduce unpredictable runtime dependencies on host PID 1/systemd state. Declaring explicit pre-baked container images (`container: { image: ... }`) eliminates external install flakiness and speeds up pipeline turnaround drastically.
### Container Safe Directory UID Mappings
When container runners mount workspace volumes across differing user IDs, Git strictly rejects repository operations unless `git config --global --add safe.directory "$GITHUB_WORKSPACE"` is declared prior to running flake or git commands.
-85
View File
@@ -1,85 +0,0 @@
---
type: journal
project: homelab
date: 2026-09-21
tags:
- homelab
- orchestration
- appctl
- python
- architecture
- testing
- pytest
- gitops
- webhook
- cryptography
---
# Daily Journal: 2026-09-21
## Wins
### Architecture & TDD: appctl Engine V2 Domain Modeling and Test Suite Scaffold
Initiated a comprehensive architectural rework of `scripts/appctl_engine.py` to elevate the homelab control utility into clean, type-safe engineering code (`appctl_engine_v2.py`). Development is conducted in an isolated Git worktree at `~/Projects/active/appctl-refactor`.
#### Key Architectural Decisions & Progress
1. **Standardized YAML Parsing & Custom Exception Handling**
- **Replaced Custom Parser**: Deprecated the hand-rolled `parse_yaml_simple()` in favor of standard `yaml.safe_load()` using PyYAML.
- **Explicit Failure Boundary**: Defined `class ManifestError(Exception): pass` to cleanly catch and isolate malformed YAML syntax without crashing the whole application inventory.
2. **Explicit Domain Model Hierarchy**
- **Base Domain Model**: Established `@dataclass class App` representing common operational primitives (`name`, `description`, `domain`, `dir_path`, `has_compose`).
- **Layer-Specific Models**:
- `SitesApp(App)`: Represents dynamic `~/Sites/*` workloads with `app.yaml` metadata (`aliases`, `visible`, `auth`, `networks`, `env`, `homepage`, `manifest_error`).
- `CoreService(App)`: Represents Core platform services (`container`, `weight`, `icon`).
- `HomepageConfig`: Strongly-typed representation for dashboard cards.
3. **Pure Normalization Boundary**
- Extracted `sites_app_from_manifest(app_dir, manifest, manifest_error) -> SitesApp` as a pure normalization seam.
- Separates filesystem discovery from domain instantiation, enabling unit tests to verify manifest coercion without disk I/O.
4. **Domain-Agnostic Infrastructure & Strict Validation**
- Decoupled hardcoded personal domains by parameterizing `HOMELAB_DOMAIN = os.environ.get("HOMELAB_DOMAIN") or os.environ.get("DOMAIN", "")`.
- Added `validate_environment()` to fail fast if mandatory environment variables or Core directories are missing.
5. **TDD Test Suite Scaffold**
- Created `tests/unit/test_appctl_engine_v2.py` with custom Pytest fixtures:
- `mock_sites_dir` & `mock_core_dir`: Isolated temporary directories with automatic `monkeypatch` teardown.
- `AppFactory`: Object Mother/Factory class to generate test app directories with `app.yaml` and Compose manifests in one line.
- Verified passing tests for resolution hierarchy, manifest overrides, and type normalization.
- Established failing (Red) acceptance criteria for upcoming Docker inspection and Homepage YAML compilation.
---
## Incidents & Debugging
- [Remediation: Gitea Actions CI Runner Container Initialization Failure (Missing /bin/sleep)](../debug/2026-09-21-gitea-actions-fhs-nix-container-fix.md)
- **Issue**: Gitea Actions runner failed at job initialization with `exec: "/bin/sleep": stat /bin/sleep: no such file or directory`.
- **Root Cause**: Minimal `nixos/nix` container image lacks the Linux Filesystem Hierarchy Standard (FHS) paths expected by `act_runner` at container entrypoint initialization.
- **Remediation**: Transitioned CI base image to `nixery.dev/shell/coreutils/git/nix/nodejs:latest`, restoring standard `/bin` utilities while preserving declarative Nix tooling.
- [GitOps Dispatcher Webhook Signature Mismatch: Epistemic Root Cause Analysis](../debug/2026-09-21-gitops-webhook-payload-signature-mismatch.md)
- **Issue**: Automated GitOps dispatcher rejected repository push deliveries with `Authentication failed: Signature mismatch`.
- **Root Cause**: Payload serialization divergence in `adnanh/webhook` parameter extraction combined with secret synchronization mismatch between Gitea webhook settings and the server's SOPS age secret.
- **Remediation**: Corrected raw payload extraction, synchronized SOPS secrets, and implemented constant-time HMAC-SHA256 signature verification in `gitops_dispatcher.py`.
---
## Mistakes and Lessons Learned
### Python `str(None)` Truthiness Trap
Calling `str(manifest.get("key")) or "fallback"` returns `"None"` (a truthy string) when the key is missing, completely breaking fallback evaluation. Safe normalization requires checking `manifest.get("key") is not None` before string casting.
### Nix Function Call Syntax in Lists
Calling `python3.withPackages` inside Nix lists `[ ... ]` requires outer parentheses `(python3.withPackages (ps: [ ... ]))`, otherwise Nix evaluates the function and lambda as two separate invalid list elements.
### FHS Invariant for Gitea `act_runner`
`act_runner` assumes a standard FHS environment (like `/bin/sleep` and `/bin/sh`) for container setup scripts. Bare Nix store container images must be supplemented with core utilities to satisfy runner bootstrap requirements.
---
## Next Objectives
1. Implement inspection layer in `scripts/appctl_engine_v2.py` (Docker status, Git sync status, SSL checks).
2. Port CLI command handlers (`cmd_sync_homepage`, `cmd_list`, `cmd_info`, `cmd_ssl`).
3. Turn remaining unit tests green and swap V2 into production `Core/scripts/appctl_engine.py`.
-42
View File
@@ -1,42 +0,0 @@
---
type: journal
project: homelab
date: 2026-09-22
tags:
- operations
- homelab
- troubleshooting
- diun
- docker
- stalwart
- smtp
- socket-proxy
---
# Daily Journal: 2026-09-22
## Wins
### Autonomous Container Image Update Alerting
Completed integration of Diun (Docker Image Update Notifier) within Homelab Core:
- Isolated container inspection through `socket-proxy`, maintaining strict read-only access without exposing the raw `/var/run/docker.sock`.
- Integrated automated email alerts to `admin@roadtotech.me` routed directly via Stalwart mail server.
---
## Incidents & Debugging
- [Incident RCA & System Integration: Diun Docker Provider Connectivity & Stalwart Mail Notification](../debug/2026-09-22-diun-socket-proxy-integration-and-stalwart-alerting.md)
- **Issue**: Diun failed with `Cannot connect to the Docker daemon at tcp://socket-proxy:2375` at startup and reported `WRN No image found` with `WRN No notifier available`.
- **Root Cause**: `diun` was not attached to the `socket-net` network bridge preventing DNS resolution to `socket-proxy:2375`, default watch policies excluded stopped or untagged containers, and SMTP alert notifications were undeclared.
- **Remediation**: Joined Diun to `socket-net` and `proxy-net`, declared container watch policies, and configured internal SMTP notifications against Stalwart on port 25.
---
## Mistakes and Lessons Learned
### Network Bridge Attachments for Daemon Proxies
When using intermediate security proxies like `socket-proxy` to isolate the Docker daemon, consumer services must explicitly attach to the dedicated socket network bridge (`socket-net`), otherwise name resolution fails closed before API negotiation starts.
### Non-Authenticated Internal SMTP Deliverability
Direct delivery from internal platform services to local mailboxes on the same domain (`kiskaadee@roadtotech.me`) does not require SASL authentication when routing within internal Docker bridges, provided the mail server treats the local subnet as trusted for local-recipient delivery.
-52
View File
@@ -1,52 +0,0 @@
---
type: journal
project: homelab
date: 2026-09-23
tags:
- operations
- homelab
- architecture
- portainer
- dozzle
- gitea
- sops
---
# Daily Journal: 2026-09-23
## Wins
### Dozzle Forward-Proxy Authentication & Persistent Volume
- Configured native ForwardAuth header ingestion in Dozzle (`DOZZLE_AUTH_PROVIDER=forward-proxy`) to consume Authelia identity headers (`Remote-User`, `Remote-Email`, `Remote-Name`).
- Wired SSO logout redirection to `auth.roadtotech.me/logout` and attached a persistent named volume (`dozzle_data`) to retain UI layout and preference state across container lifecycles.
### Architectural Classification & Portainer Deprecation
- Evaluated platform ownership boundaries ("What qualifies a service for Core ownership?"):
- Confirmed that Gitea and the Gitea CI runner should remain decoupled from Core in `Sites/gitea`, preserving independent recovery and avoiding granting arbitrary CI runner workloads platform-level privileges.
- Formulated and executed the clean deprecation of Portainer across all infrastructure layers.
- Removed Portainer from `docker-compose.yml`, eliminated `PORTAINER_ADMIN_PASSWORD` from `homeserver.nix`, and pruned the ciphertext from `secrets.yaml` via SOPS.
- Removed Portainer from `appctl` core service inventory and Homepage service mapping.
- Added automated regression invariant test `test_portainer_is_deprecated_and_absent` to `tests/security/test_security_invariants.py`.
- Synchronized all Core documentation (`README.md`, `SECURITY.md`, `architecture.md`, `operations.md`, `secrets-and-state.md`, `appctl.md`).
- Validated complete local test suite with 100% passing tests and clean Nix flake evaluation.
---
## Architecture & Discussions
- [Core Service Qualification & Portainer Deprecation](../../02-discussions/homelab/core-service-qualification-and-portainer-deprecation.md)
- Detailed inquiry into the role of inherited tools versus deliberate platform primitives.
- Analysis of Portainer's fundamental mismatch with hardened read-only Docker socket proxies (`socket-proxy` with `POST=0`, `DELETE=0`).
- Separation of platform services from developer infrastructure and unprivileged CI runners.
- [Plan: Clean Deprecation of Portainer from Core](../../01-plans/homelab/portainer-deprecation-plan.md)
- Phased deprecation, local validation, commit strategy, and production teardown runbook.
---
## Mistakes and Lessons Learned
### Inherited Tools vs. Platform Status
An inherited component does not acquire platform status merely because it was placed in the platform stack. If a service does not own a unique, indispensable responsibility in the operational model—or if its fundamental design (GUI container mutation) conflicts with declarative GitOps invariants and read-only socket proxies—it should be pruned cleanly rather than maintained out of inertia.
### Privilege Boundaries in Developer Tooling
Even when source-control infrastructure (like Gitea) provides cross-cutting value to a homelab, associated execution engines (like CI runners) represent entirely different threat surfaces. The runner executes arbitrary repository code and requires container execution privileges; bundling it into Core by default violates least-privilege platform isolation.
-84
View File
@@ -1,84 +0,0 @@
---
type: journal
project: praxis
date: 2026-09-24
tags:
- praxis
- architecture
- planning
- srs
- domain-model
- oop
- ddd
---
# Daily Journal: 2026-09-24
## Wins
### Praxis Project Inception & Workspace Scaffolding
- Initialized and scaffolded the brand-new workout execution and habit-tracking project **Praxis** at `~/Projects/active/praxis`.
- Configured canonical upstream Git forge on self-hosted Gitea (`ssh://git@gitea.roadtotech.me:2223/kiskaadee/praxis.git`, [Gitea repository](https://gitea.roadtotech.me/kiskaadee/praxis)) with GitHub ([`kiskaadee/praxis`](https://github.com/kiskaadee/praxis)) configured as automated push mirror.
- Configured local development environment with Python 3.12, `uv` package manager (`pyproject.toml`, `uv.lock`), `.envrc`, and clean hexagonal architecture structure.
### Domain Design & Architectural Specifications
- Established the foundational **Three-Layer Temporal Model**:
- **Prescription**: Reusable `Routine` templates, weekly schedules, target exercises, and multi-week `Progression Phases`.
- **Performance**: Concrete `WorkoutSession` execution instances freezing an immutable `SessionPrescriptionSnapshot` while granting total runtime autonomy.
- **Analysis**: Pure deterministic derivation of adherence rates, metric-dependent workload volumes, and factual exercise histories without mutable counters.
- Codified key domain contracts and invariants:
- **Snapshot vs. Execution Mutability**: Frozen prescription snapshot upon session initiation; execution remains mutable until finalization (`Completed`, `Partially_Completed`, `Skipped`).
- **Substitution History Isolation**: Substituted movements contribute strictly to the performed exercise history, preserving audit linkage to the planned exercise.
- **Set-Intent Completion Policy & Factual Adherence**: Consistency tracked via distribution metrics (`Completed`, `Partially_Completed`, `Skipped`, and Set Adherence Rate) rather than fragile streak mechanics.
- **Decoupled Identity**: Internal `UserId` domain abstraction isolated behind an `AuthProvider` port (supporting Authelia ForwardAuth headers and LLDAP).
### Knowledge Graph Curation
- Established new canonical project directory in the Brain at [`projects/praxis/`](../../06-projects/praxis/README.md).
- Curated and validated foundational documents from `inbox/`:
- Active baseline: [Praxis Software Requirements Specification (SRS) v1.0.2](../../01-plans/praxis/praxis-srs-v1.0.2.md)
- Active baseline: [Praxis Domain Model & OOP Design Specification v1.0.1](../../01-plans/praxis/praxis-domain-model-v1.0.1.md)
- Archived comparison drafts: [Praxis SRS v1.0.0](../../01-plans/praxis/praxis-srs.md) and [Praxis Domain Model v1.0.0](../../01-plans/praxis/praxis-domain-model.md)
- Pruned staging files from `inbox/`, maintaining a clean capture zone.
---
## Planning & Specifications
- [Praxis Software Requirements Specification (SRS) v1.0.2](../../01-plans/praxis/praxis-srs-v1.0.2.md)
- Software requirements baseline detailing functional specifications across identity, exercise catalogs, routines, session execution, completion semantics, and analytical metrics.
- [Praxis Domain Model & OOP Design Specification v1.0.1](../../01-plans/praxis/praxis-domain-model-v1.0.1.md)
- Detailed object-oriented and DDD specification detailing aggregate roots (`Routine`, `WorkoutSession`, `Exercise`), entities, value objects, behavioral contracts, state transition matrices, and hexagonal port interfaces.
---
## Architecture & Design Decisions
### Snapshot Immutability vs. In-Flight Execution Autonomy
Routine templates must represent aspirational intent, not immutable dogma. Freezing a `SessionPrescriptionSnapshot` at workout initiation decouples past performance from subsequent template edits, while allowing the user to adapt on the fly (reordering exercises, adjusting weights or rep ranges, swapping machines, or logging ad-hoc sets) without polluting the routine definition.
### Factual Adherence over Gamified Streaks
Conventional fitness applications encourage dishonesty and cognitive stress by imposing fragile binary streak counters that reset on missed days. Praxis models adherence as factual distribution rates over sliding windows, separating set-level completion intent from binary day attendance.
---
## Phase 0 Complete: Praxis Implementation Readiness
### Toolchain Hardening & Blueprint (v0.2.0)
Session completed a full Phase 0 implementation-readiness pass on the Praxis repository:
- **Blueprint v0.2.0** finalised: translated SRS v1.0.2 + Domain Model v1.0.1 into concrete Python decisions — package structure, dependency direction, immutability strategy (`@dataclass(frozen=True)` value objects, `@dataclass(eq=False)` entities), ID representation (newtype frozen dataclasses over `uuid.UUID`), and `SetData` as explicit frozen VO to prevent `record_set()`/`MetricValidationPolicy` divergence.
- Resolved all Phase-1-blocking ambiguities (OQ-2: `Phase.end_week = None` → return last phase; `ValueError` on empty phases list). Remaining OQs (OQ-1, 3, 4, 5) formally deferred.
- Established `pyproject.toml` toolchain: `ruff` (E/W/F/I/UP/B/C4/SIM/RUF/N/ANN/PT/TCH, line 100, Python 3.13), `pyright` strict mode, `pytest` with `--strict-markers` and 90% branch coverage gate.
- Implemented Git hooks: `pre-commit` (ruff format + check + re-stage), `pre-push` (pyright strict + `pytest -m unit`), and one-shot `install-hooks.sh`.
- Expanded `AGENTS.md` with §5 Toolchain & Static Analysis Constraints, §6 Git Hook Workflow, and tightened §7 Rules of Engagement.
Repository now at **Phase 1 start**: `identifiers → enums → measurement → RepRange → SetData → Exercise → Routine → MetricValidationPolicy → SessionSnapshotFactory → WorkoutSession → CompletionPolicy → WorkloadCalculator → AdherenceCalculator`.
📋 [Praxis Implementation Blueprint (v0.2.0)](../../01-plans/praxis/praxis-implementation-blueprint.md)
---
## Incidents & Debugging
- [Diun Load-Shaping, Workload Exemption & Authenticated SMTPS Delivery (2026-09-24)](../debug/2026-09-24-diun-workload-isolation-and-load-shaping.md): Resolved 6 classes of post-deployment issues on the Core Diun notifier. Root causes: bcrypt `$` interpolation from deprecated Portainer secrets (resolved by full Portainer deprecation), high-concurrency registry scan load factor mitigated via `DIUN_WATCH_WORKERS=6` + `DIUN_WATCH_JITTER=30s`, local-build image exemptions decentralized to `Sites/*` compose manifests via `diun.enable=false`, and authenticated SMTPS delivery migrated from unauthenticated port 25 to port 465 with dedicated `notifier@roadtotech.me` service account projected via SOPS. All 19 upstream images now scan cleanly with zero failures; mail lands in `INBOX` with `auth=pass`.
-55
View File
@@ -1,55 +0,0 @@
---
type: journal
project: magnetflix
date: 2026-09-25
tags:
- magnetflix
- curation
- architecture
- extension
- grpc
- fastapi
---
# Daily Journal: 2026-09-25
## Wins
### MagNetFlix Architecture Promotion & Landing Page Overhaul
- Curated and promoted the comprehensive **MagNetFlix** system architecture blueprint into the canonical project landing page at [`projects/magnetflix/README.md`](../../06-projects/magnetflix/README.md), replacing the outdated stub.
- Codified system topology across five decoupled layers:
- **Client Ingestion**: Firefox/Chromium WebExtension and web pairing dashboard.
- **Public Edge**: Traefik reverse proxy ingress with Authelia ForwardAuth SSO (`magnetflix.roadtotech.me`).
- **Core Services**: FastAPI BFF gateway, gRPC worker pipeline, SQLite 3 (WAL mode) job state store, and Transmission RPC engine.
- **Pipeline Stages**: Security media sanitizer, TMDB metadata token overlap verification, and canonical Jellyfin/Plex library renamer.
- **Storage**: Isolated staging scratch mount (`/data/staging/<job_id>`) and persistent library mount (`/media/movies`).
- Codified the worker finite state machine and crash recovery invariants (startup orphan cleanup transitioning non-terminal jobs to `FAILED`, idempotent deduplication on IMDb ID, and sandbox purging).
### MagNetFlix Cross-Browser Extension Integration Plan
- Promoted and normalized the active implementation roadmap at [`projects/magnetflix/plans/browser-extension-integration.md`](../../01-plans/magnetflix/browser-extension-integration.md) (`status: active`).
- Defined the transition from the working local PoC (`~/Projects/learning/extensions/magnetflix-extension`) to a hybrid production architecture:
- Mode A (Default): Seamless handoff redirecting intercepted magnet links to the authenticated web dashboard (`https://magnetflix.<DOMAIN>/pair?magnet=...`), reusing active Authelia SSO cookies without storing secrets in the browser extension.
- Mode B (Standalone): Internal extension tab pairing via API credentials.
- Mapped out the 4-phase execution roadmap: configurable server URL settings, web dashboard handoff integration in FastAPI BFF, Manifest V3 / cross-browser packaging, and production distribution.
- Normalized machine-specific file URIs into portable semantic code references across the plan.
### Knowledge Graph Maintenance & Inbox Curation
- Conducted full inbox curation pass, eliminating draft fragmentation and clearing pending files from `inbox/`.
- Executed atomic semantic commits (`plan(magnetflix)` and `project(magnetflix)`).
- Validated vault structure via `python scripts/validate-brain.py` (0 issues across frontmatter, relative links, Mermaid diagrams, Ruff, and Pyright).
---
## Planning & Specifications
- [MagNetFlix Cross-Browser Extension Integration Plan](../../01-plans/magnetflix/browser-extension-integration.md)
- Production plan for evolving the click-interception PoC into a cross-browser extension with web dashboard handoff and Authelia SSO integration.
- [MagNetFlix Project Landing Page](../../06-projects/magnetflix/README.md)
- Canonical project landing page documenting full system topology, worker state machine, security sanitizer specs, and active development milestones.
---
## Architecture & Design Decisions
### Web Dashboard Handoff vs. Extension-Side Credentials
Storing API keys or bearer tokens inside browser extension storage increases attack surface and requires token management interfaces. By adopting a web dashboard handoff model (`/pair?magnet=...`), the extension merely intercepts the magnet URI and opens a tab on the user's personal domain. The FastAPI BFF inherits the existing browser Authelia SSO session, authenticates the user transparently via `Remote-User` headers, and preserves credential hygiene.
-68
View File
@@ -1,68 +0,0 @@
---
type: journal
date: 2026-09-26
tags:
- brain
- tooling
- validation
- python
- architecture
- mermaid
---
## Wins
### validate-brain.py: Mermaid Parse Error Caught and Fixed
- Discovered that the validator was silently passing a broken Mermaid diagram in `projects/magnetflix/README.md`. Obsidian reported a parse error (`got 'PS'`) on the `|gRPC Event Stream (SSE)|` edge label — parentheses in an unquoted Mermaid label tokenize as Paren Start in Mermaid's Jison parser.
- Root cause: two bugs in Check 7 — the arrow regex only matched `-->` (missing `<-->`, `<==>`) and the special character check omitted `()[]{}` despite the code comment mentioning parens.
- Fixed the validator and quoted three edge labels across two files:
- `projects/magnetflix/README.md`: `|"gRPC Event Stream (SSE)"|`
- `projects/homelab/guides/mail-deliverability-rdns-relay-guide.md`: `|"Encrypted TLS (587)"| ` and `|"Port 25 (In & Out)"|`
### validate-brain.py: Three-Phase Architectural Refactor
Following feedback from two architectural review sources, executed a three-phase refactor of the validator without breaking the repository or the pre-commit hook.
**Phase 1 — Structural refactor (same validator, different architecture):**
- Introduced `Document` NamedTuple `(path, rel, content, validates_frontmatter)` as the unit of discovery
- Introduced `Issue` NamedTuple `(severity, path, line, message)` with `Severity = Literal['error', 'warning']`
- Replaced 4× `rglob` traversals with a single `discover_documents()` pass that reads each file once and encodes all exemption policy
- Eliminated global mutable `errors: list[str]` — all checks return `list[Issue]`
- Eliminated module-scope execution — wrapped in `main()` with `raise SystemExit(main())`
- Removed `any('Deprecated' in e for e in errors)` smell — per-check pass/fail derived from returned lists
- Added explicit check registry tuple in `main()` — the manifest of what validation means is visible at a glance
- Separated `report()` function, preserving the door to `--format json` later
- **Zero behavioral change**: same exit code, same error messages
**Phase 2 — Precise diagnostics:**
- Added `_line_of(content, pos)` helper converting character offsets to 1-indexed line numbers
- Every check now populates `Issue.line`:
- Frontmatter: exact line of the `type:` field
- Links: exact line of each markdown link target span
- Code fences: line of the last unpaired backtick delimiter
- Mermaid: structural issues anchored to diagram header, edge-label issues anchored to exact line
- `report()` renders `path:line message` — path embedding removed from message strings
**Phase 3 — Shared Markdown scanner:**
- Added `CodeBlock` NamedTuple `(language, content, start_line, end_line)`
- Added `scan_code_blocks(content)` — linear walker respecting CommonMark variable-width backtick fences. A 4-backtick outer fence is not closed by a 3-backtick inner line.
- `check_code_fences()` now consumes `unclosed` from the scanner — each unclosed fence is a separate Issue
- `check_mermaid()` now consumes `blocks` from the scanner — filters `language == 'mermaid'`, eliminating the DOTALL regex false-positive (example mermaid syntax inside a ````markdown documentation fence)
- Verified with 6 integration tests including the false-positive case
All three commits passed the pre-commit hook (the validator validated itself on each commit).
## Architecture & Design Decisions
### validate-brain.py: Where to Stop
Two feedback sources disagreed on scope. The conservative refactor (Phase 1 + functions) was immediately actionable. The architectural redesign had accurate diagnoses but over-prescribed: `ValidationConfig` dataclass, multi-module package split, PyYAML, Mermaid CLI. Rejected all of these. The guiding principle: architecture should be proportional to the problem. At 138 documents and 1 author, a single 300-line file with clear separation of discovery, validation, and reporting is the right stopping point. Add a dependency when the repo has a requirement the current implementation cannot reliably satisfy — not because a more sophisticated architecture could use it.
### Phase Sequencing as a Regression Boundary
Separating the refactor into three phases with explicit behavioral contracts made each phase auditable:
- Phase 1: architecture changes, behavior preserved (same exit code, same error messages)
- Phase 2: diagnostics explicitly improved (line numbers added)
- Phase 3: Markdown parsing behavior explicitly changed (where old behavior was demonstrably wrong)
This meant any regression could be attributed to exactly one phase.
## Records
- [validate-brain.py Refactor — Architecture Discussion](../../02-discussions/brain/validate-brain-refactor-architecture.md)
- [validate-brain.py Refactor — Debug/Postmortem](../debug/2026-09-26-validate-brain-refactor.md)
-69
View File
@@ -1,69 +0,0 @@
---
type: journal
project: homelab
date: 2026-09-27
tags:
- homelab
- architecture
- curation
- gitops
- appctl
- roadmap
---
# Daily Journal: 2026-09-27
## Wins
### Homelab Architecture Consolidation Roadmap v3 & Guide Promotion
- Formally curated and promoted **Homelab Architecture Consolidation & Hardening Roadmap v3** and **Implementation Guide v3** to the canonical knowledge graph:
- [`projects/homelab/plans/architecture-consolidation-roadmap-v3.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v3.md)
- [`projects/homelab/plans/architecture-consolidation-implementation-guide-v3.md`](../../01-plans/homelab/consolidation/architecture-consolidation-implementation-guide-v3.md)
- Re-baselined the platform architecture against commit `246b587` (NixOS appliance, Portainer deprecation, Stalwart mail & SMTPS submission, Dozzle forward-proxy auth, Diun jitter/workers, and 35 invariant tests).
- Codified the 5-tier service taxonomy: Host Foundation, Edge & Security Primitives, Core Platform Capabilities, Platform Operations, and Workloads (Sites).
- Codified the Controller Authority Matrix and Resource & State Ownership Matrix, resolving multi-controller ambiguities across systemd, Core Compose, GitOps, and `appctl`.
- Inverted the GitOps trust boundary: admissions are authoritatively driven by `Core/config/deployments.yaml` instead of workload manifests claiming aliases.
- Isolated Second Brain (`~/Brain`) as a strictly read-only data vault (`strategy: pull-only`), completely stripped of Docker socket access and container lifecycle capabilities.
- Added workload Compose policy validation to treat untrusted Compose files as a capability attack surface.
- Archived superseded Roadmap v2 and Implementation Guide v2 into [`01-plans/homelab/`](../../01-plans/homelab/) with updated backlinks in past journals (`2026-09-13`, `2026-09-14`) and project landing pages.
### Dual-Track Boundary Lock & P3 Convergence Runbook
- Synchronized cross-track coordination between **Track A** (Architecture on `main`) and **Track B** (`appctl-v2` in `~/Projects/active/appctl-refactor` on `refactor/appctl-rework`).
- Codified the 5 stable architectural seams protected by `appctl-v2` until convergence:
1. **CLI Syntax**: Caller flags, subcommands (`list`, `info`, `up`, `down`, `sync`), and exit codes remain identical.
2. **`resolve` JSON Contract**: `cmd_resolve` schema guarantee (`name`, `dir_path`, `type`, `domain`, `container`, `env`) verified via automated test fixtures.
3. **Canonical Identity**: Unified service identifiers across platforms.
4. **Core vs. Sites Taxonomy**: Platform capabilities strictly separated from workloads.
5. **Homepage Sync Semantics**: Unbroken `services.yaml` compilation from Core inventory + Sites manifests.
- Defined symmetrical P1 isolation rules: minimal legacy patch to `Core/scripts/appctl_engine.py` on `main` (Stalwart domain to `smtp.roadtotech.me`, remove `snappymail`), while Track B applies the identical semantic change directly to its typed `CoreService` model without branch cross-merging.
- Established the concrete 6-step P3 convergence sequence: `main` authors `core_manifest.py`, Track B cherry-picks the isolated contract commit, adapts `appctl_engine_v2.py`, runs hermetic test verification, promotes `appctl_engine_v2.py` to `appctl_engine.py`, and merges into `main` with full regression verification (`./scripts/test` and `nix flake check`).
### Architectural Planning Freeze & Transition to Implementation
- Formally declared an end to architectural revision cycles across Homelab Core documentation.
- The guides are now the authoritative source of truth. Implementation of Phase 1 (Mail Topology Realignment) is cleared to begin.
- Implementation-level issues encountered during rollout will be addressed directly in code unless an underlying architectural assumption in the frozen guides is proven invalid.
---
## Planning & Specifications
- [Architecture Consolidation & Hardening Roadmap v3](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v3.md)
- Canonical 5-tier architecture, authority matrices, inverted GitOps registry, mail topology realignment, and platform readiness contracts.
- [Architecture Consolidation Implementation Guide v3](../../01-plans/homelab/consolidation/architecture-consolidation-implementation-guide-v3.md)
- Executable step-by-step phased runbooks, zero-data-loss SnappyMail migration gates, and P3 controlled convergence procedure.
- [appctl Engine V2 Refactoring Plan](../../01-plans/homelab/appctl/appctl-engine-v2-refactoring.md)
- Modernization of `appctl` into a typed, test-driven engine, aligned with the 5 integration seams and P3 cherry-pick runbook.
---
## Architecture & Design Decisions
### Strict Direction of Integration (`main` $\rightarrow$ `refactor/appctl-rework` $\rightarrow$ `main`)
Treating `appctl-v2` as a hard prerequisite for Phase 1 and Phase 2 would stall necessary infrastructure realignments (mail domain migration, GitOps sandboxing). Conversely, continuous bidirectional merging between `main` and the refactor branch risks thrashing and merge conflicts in rapidly changing files. By adopting a strict one-way contract flow—authoring `core_manifest.py` on `main`, cherry-picking only the contract commit into the worktree, adapting and verifying hermetically, promoting the file, and then merging back to `main`—both tracks maintain complete velocity and clean boundaries until convergence at P3.
---
## Incidents & Debugging
- [Laptop Memory Exhaustion Postmortem & Mitigation](../debug/2026-09-27-laptop-memory-exhaustion-postmortem.md): Mobile workstation UI lockup under memory pressure due to 0B swap causing synchronous file-backed page eviction; mitigated via compressed in-RAM swap (`zramSwap`) and proactive early OOM termination (`services.earlyoom`).
-85
View File
@@ -1,85 +0,0 @@
---
type: journal
project: brain
date: 2026-09-28
tags:
- brain
- taxonomy
- migration
- tooling
- validation
- agents
---
# Daily Journal: 2026-09-28
## Wins
### Second Brain Taxonomy & Lifecycle Migration Completed
- Executed the full architectural migration of the **Second Brain** knowledge repository (`~/Brain`) from the previous organically grown layout into the canonical numbered lifecycle taxonomy (`00-inbox/` through `06-projects/`).
- Successfully relocated 188 tracked files preserving full Git history, eliminated the legacy `archive/` anti-pattern, and established clean epistemic boundaries across all document types.
- Rewrote 199 intra-vault relative Markdown links across 49 files without a single broken link or dead anchor.
- The migration was executed primarily through the **AGY CLI using Gemini 3.8 Flash**. Having an AI model drive the mechanical relocations, manifest authoring, link recalculation, and profile synchronization turned out to be very effective once the architectural specifications and safety invariants were explicitly codified. The resulting repository state is solid, clean, and immediately functional.
- Codified the structural integrity rules in `scripts/validate-brain.py` using declarative `DirectoryContract` definitions and established a comprehensive 10-case regression test suite (`scripts/test_validator.py`). All checks pass cleanly with 0 errors and 0 warnings.
### Distributed Integration Surface Synchronization
- Recognized that the Brain's architecture is not confined to `~/Brain`; localized agent instruction files (`AGENTS.md`) and configuration hooks across the laptop form an active integration surface that interacts with the vault daily.
- Synchronized all distributed touchpoints across the workstation:
- **Gemini Hooks**: Updated `~/.gemini/config/scripts/inbox-capture.sh` and `[user_global]` in `~/.gemini/config/AGENTS.md` to stage artifacts into `00-inbox/`.
- **Homelab Workstation**: Updated [`/home/kiskaadee/Homelab/AGENTS.md`](file:///home/kiskaadee/Homelab/AGENTS.md) execution workflow, debug record paths (`03-records/debug/`), daily journals (`03-records/journal/`), and methods links.
- **Homelab Core**: Updated [`/home/kiskaadee/Homelab/Core/AGENTS.md`](file:///home/kiskaadee/Homelab/Core/AGENTS.md) Section *Brain Vault* to map implementation plans, discussions, and runbooks into the numbered lifecycle.
- **Active Worktrees**: Updated [`/home/kiskaadee/Projects/active/appctl-refactor/AGENTS.md`](file:///home/kiskaadee/Projects/active/appctl-refactor/AGENTS.md) with matching 00-06 mappings.
- **Internal Profiles**: Synchronized [`05-agents/profiles/homelab-core.md`](../../05-agents/profiles/homelab-core.md), [`05-agents/profiles/homelab-operations.md`](../../05-agents/profiles/homelab-operations.md), and [`05-agents/profiles/second-brain.md`](../../05-agents/profiles/second-brain.md).
- Confirmed via workspace-wide search that zero stale references to `Brain/inbox` or unnumbered legacy directories remain.
### Homelab Architecture Consolidation v4 & KISS Simplicity Alignment
- Established and frozen **Roadmap & Execution Plan v4** as the single unified authoritative architectural and implementation baseline for `roadtotech.me`, superseding v3 and unifying architecture specifications and execution runbooks into a single cohesive document.
- Decoupled software source repositories from deployment catalogs and platform orchestration, establishing a clean **3-Tier Architecture** (Software vs. Deployment vs. Platform) with the OCI container image as an intermediate provenance object carrying `org.opencontainers.image.revision`.
- Conducted a thorough systems design critique evaluating the architecture against **KISS ("Keep It Simple, Stupid")**: confirmed that true simplicity is measured by the **fewest independent concepts and control paths** rather than superficial file counts.
- Codified strict guardrails protecting the linear control path (`source push -> CI -> GitOps -> appctl update -> Compose`) and firmly rejected secondary orchestrators, message brokers, queues, or deployment databases around `appctl`.
- Clarified canonical terminology: formalizing **two operational inspection axes** (Deployment Configuration vs. Software Provenance) with **three independent revision identities** (`deployment_config_revision`, `source_revision`, `artifact_digest`).
- Consolidated the systems design trade-off evaluation, the 7 platform primitives matrix, and architectural commitments directly into formal ADR [`03-records/decisions/homelab-3tier-architecture-and-provenance.md`](../decisions/homelab-3tier-architecture-and-provenance.md).
---
## Planning & Specifications
- [Homelab Architecture Consolidation Roadmap & Execution Plan v4](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md)
- Unified architecture and implementation blueprint defining 3-tier decoupling, provenance ledger, Core registry authority, and phased execution deliverables P0–P5.
- [Legacy Multirepo (v3) to 3-Tier Architecture (v4) Migration Discussion](../../02-discussions/homelab/architecture-migration-v3-to-v4.md)
- Architectural evaluation analyzing multirepo friction (source pollution, repo inflation, state co-location) vs. 3-tier decoupling.
- [ADR: Homelab 3-Tier Architecture & Provenance](../decisions/homelab-3tier-architecture-and-provenance.md)
- Formal decision record locking the 3-tier boundary, provenance model, state root, linear control path, and KISS simplicity evaluation.
- [Brain Taxonomy & Lifecycle Migration Plan](../../01-plans/brain/taxonomy-lifecycle-migration.md)
- Completed execution blueprint detailing the 8 migration invariants, phase-by-phase execution, classification edge cases, and automated validation results.
- [Brain Epistemic Lifecycle Taxonomy Architecture Discussion](../../02-discussions/brain/taxonomy-and-lifecycle-architecture.md)
- Resolved architectural inquiry evaluating epistemic lifecycle roles vs. project silos, metadata-based lifecycle status vs. `archive/` folders, and `DirectoryContract` validator design.
---
## Architecture & Personal Reflections
### Living with the Epistemic Architecture
There is a profound difference between sketching a taxonomy on a whiteboard and actually living in the resulting repository. For weeks, filing documents felt slightly ambiguous:
- Should a post-mortem of an unexpected server shutdown live in `homelab/`, `learning/`, or `records/`?
- Should a debate comparing Stalwart vs. LLDAP live in a project folder or a journal?
- When a roadmap is done, why does moving it into `archive/` break every journal link written during that month?
Organizing by **epistemic role** resolves these tensions at the root:
* If it is forward-looking and actionable, it is a **Plan** (`01-plans/`).
* If it is an open exploration of trade-offs, it is a **Discussion** (`02-discussions/`).
* If it documents what empirically happened in the past, it is a **Record** (`03-records/`).
* If it is reusable understanding or an operational SOP, it is **Learning** (`04-learning/`).
* If it is a project entry point, it is an index hub in `06-projects/<project>/README.md`.
Seeing this taxonomy take physical form across 188 files brings immense mental clarity to the engineering workflow.
### The Human/AI Collaboration & Convergence Workflow
This milestone was an instructive case study in using AI across distributed sessions for codebase restructuring:
- **Human Role**: Framing the overall problem, acting as the context carrier between AI-assisted sessions, evaluating proposed classifications and trade-offs, accepting or rejecting alternatives, and providing the final architectural direction and validation criteria.
- **AI Role (AGY + Gemini / ChatGPT)**: Exploring the taxonomy, analyzing artifacts, generating and refining migration specifications, producing the machine-readable manifest, executing mechanical relocation and link rewriting, updating validator contracts, and tracing distributed references.
- **The Validation Gate**: The deterministic validator, regression test suite, migration manifest, and subsequent human review provided the firm boundary between AI-generated proposals and accepted repository state.
The key engineering takeaway is not that an individual author derived the entire taxonomy in isolation or that an AI independently restructured the vault. Rather: **multiple AI contexts were used as a distributed engineering workspace, passing artifacts and critiques between them until the system converged, while deterministic validation and human review served as the acceptance boundary.**
The resulting migration feels robust and clean. The transition from taxonomy design to everyday operation is complete.
-66
View File
@@ -1,66 +0,0 @@
---
type: journal
project: brain
date: 2026-09-29
tags:
- brain
- homelab
- taxonomy
- madr
- curation
- agents
- documentation-router
- investigation
---
# Daily Journal: 2026-09-29
## Wins
### Homelab Architecture Documentation Epistemic Triad Realignment
- Reorganized the **Homelab Architecture Consolidation** documentation across the epistemic triad (Discussion, ADR, Plan), eliminating content overlap and establishing crisp authority boundaries:
- **ADR** ([`03-records/decisions/homelab-3tier-architecture-and-provenance.md`](../decisions/homelab-3tier-architecture-and-provenance.md)): Standardized to **MADR 4.0** format, focusing strictly on architectural commitments (3-tier decoupling, provenance model, OCI digest immutability vs. mutable tags) while delegating exact schema field representations to the Plan.
- **Discussion** ([`02-discussions/homelab/architecture-migration-v3-to-v4.md`](../../02-discussions/homelab/architecture-migration-v3-to-v4.md)): Deepened with authentic engineering narrative, operational friction analysis, and evolutionary reasoning from v1 to v4 while eliminating "decision voice" and absolutist language.
- **Plan** ([`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md)): Clarified as the authoritative implementation specification with pure technical constraints, schema contracts, and phased milestones (P0–P5).
- **Consolidation Subsystem Directory**: Relocated all 6 roadmap and guide documents (v1–v4) into a dedicated lineage folder [`01-plans/homelab/consolidation/`](../../01-plans/homelab/consolidation/) satisfying repository depth contracts (`max_depth=3`).
### Decoupling Investigation and Documentation Treatment Skills
- Decoupled the monolithic investigation skill into two cooperating, independent global capabilities:
- **`engineering-investigation`**: Purely procedural troubleshooting following the scientific method (Observation $\to$ Verification) and 6-part interactive checkpoints, terminating cleanly at runtime recovery.
- **`documentation-router`**: Second-order knowledge classifier and gatekeeper that inspects session context, determines whether durable knowledge preservation is warranted, classifies knowledge by epistemic role (not activity), enforces anti-overlap invariants, and coordinates modular authoring specifications.
- Established the principle that `Discussion ──informs──> ADR ──constrains──> Plan` describes **optional information flow and authority relationships, not a mandatory documentation pipeline**.
- Authored four modular authoring reference specifications: `discussion-authoring.md`, `adr-authoring.md`, `plan-authoring.md`, and `debug-record-authoring.md`.
- Synchronized canonical agent skill definitions in [`05-agents/skills/`](../../05-agents/skills/) and updated global rules in `~/.gemini/config/AGENTS.md`.
### Inbox Curation Completed
- Processed and curated all staged drafts from [`00-inbox/`](../../00-inbox/) into canonical lifecycle directories:
- Promoted the reorganization implementation plan to [`01-plans/homelab/architecture-docs-reorganization.md`](../../01-plans/homelab/architecture-docs-reorganization.md) (`status: completed`), removing provisional review questions.
- Authored operational walkthroughs for the homelab reorganization and the global skills decoupling in [`04-learning/guides/`](../../04-learning/guides/).
- Promoted the skills decoupling blueprint to [`01-plans/brain/documentation-and-investigation-skills-decoupling.md`](../../01-plans/brain/documentation-and-investigation-skills-decoupling.md) (`status: completed`).
### Agent Skill Engineering & Skill-Builder Meta-Skill Creation
- Conducted an in-depth empirical investigation of Matt Pocock's skills repository (`mattpocock/skills`), studying skill anatomy, invocation modes, operational state machines, negative boundaries, progressive disclosure, and context load economics.
- Formalized **Knowledge Articles** as an explicit epistemic document type in [`documentation-router`](../../05-agents/skills/README.md), authoring the specification `references/knowledge-authoring.md` based on a side-by-side learner voice and rhetorical restraint.
- Authored the durable knowledge article [How to Build Effective Agent Skills](../../04-learning/knowledge/methods/building-effective-agent-skills.md), explaining why essay prompts fail, introducing the assembly jig / airlock mental model, and codifying the single observable proof heuristic.
- Derived the Skill-Engineering Methodology based on 4 structural sizing archetypes (Reference, Transformation, Procedural Workflow, Interactive Elicitation) and a 4-tier epistemic architecture (Engineering Invariants, Platform Constraints, Contextual Heuristics, Authoring Quality).
- Designed and implemented the [`skill-builder`](../../05-agents/skills/README.md) meta-skill (deployed to `~/.gemini/config/skills/build-skill/` and `/build-skill`) as an interactive coach with a mandatory Design Review Gate.
- Dogfooded `skill-builder` against existing skills (`engineering-investigation`, `engineering-tutor`, `documentation-router`, `git-commit`), validating its false-positive rejection and identifying high-signal refinements.
- Strengthened `engineering-investigation` with Evidence Before Hypothesis, Traceable Diagnostic Cleanup, and Sensitive Data Redaction invariants.
- Captured the architectural commitments in ADR [Agent Skill Architecture & Governance](../../03-records/decisions/agent-skill-architecture-and-governance.md).
---
## Planning & Specifications
- [Homelab Architecture Consolidation Documents Reorganization Plan](../../01-plans/homelab/architecture-docs-reorganization.md)
- Completed roadmap reorganizing consolidation documentation across the epistemic triad and establishing `01-plans/homelab/consolidation/`.
- [Homelab Architecture Consolidation Documents Reorganization Walkthrough](../../04-learning/guides/homelab/architecture-docs-reorganization-walkthrough.md)
- Detailed operational walkthrough of MADR 4.0 standardization, narrative discussion evolution, and authoritative plan framing.
- [Documentation Router & Engineering Investigation Skills Decoupling Plan](../../01-plans/brain/documentation-and-investigation-skills-decoupling.md)
- Implementation blueprint decoupling procedural investigation from documentation evaluation and authoring specifications.
- [Global Documentation Router & Investigation Skills Walkthrough](../../04-learning/guides/brain/documentation-and-investigation-skills-walkthrough.md)
- Walkthrough detailing the decoupled skill topology, anti-overlap invariants, and authoring modules.
- [ADR: Agent Skill Architecture, Proportional Sizing, and Meta-Builder Governance](../decisions/agent-skill-architecture-and-governance.md)
- Point-in-time architectural commitments establishing the 4-tier skill taxonomy, proportional sizing modes, skill-builder review gate, and investigation invariants.
- [Knowledge Article: How to Build Effective Agent Skills](../../04-learning/knowledge/methods/building-effective-agent-skills.md)
- Canonical method guide explaining the operational physics of skills, the airlock mental model, and the observable proof heuristic.
-70
View File
@@ -1,70 +0,0 @@
---
type: journal
project: brain
date: 2026-10-01
tags:
- homelab
- bdinvite
- nixos
- firewall
- biome
- architecture
- deployment
---
# Daily Journal: 2026-10-01
## Wins
### BDInvite Full-Stack Lifecycle & Production Deployment
- Engineered, validated, and successfully deployed **BDInvite** ([`06-projects/bdinvite/README.md`](../../06-projects/bdinvite/README.md)) to production at [`demos.roadtotech.me/birthday`](https://demos.roadtotech.me/birthday), delivering an interactive digital birthday invitation with real-time countdown, venue mapping, guest RSVP registration, and an administrative control panel.
- **Frontend Architecture**: Built with React 19, Vite, Tailwind CSS v4, Motion, Lucide React, and `canvas-confetti`. Configured self-hosted typography (`Playfair Display` and `Plus Jakarta Sans`) bundled locally as `.woff2` files in static distribution assets, eliminating runtime calls to third-party font CDNs and protecting guest privacy.
- **Backend Architecture**: Implemented with FastAPI running on Python 3.11 (`uvicorn`, managed via `uv`) with an embedded SQLite database operating in Write-Ahead Logging mode (`PRAGMA journal_mode=WAL;`). Included Colombian mobile phone number normalization (`+57 3XX...` $\to$ `3XXXXXXXXX`) with database-level uniqueness constraints for deduplication.
- **Edge Routing & Ingress Separation**: Designed a single-container multi-stage Docker build (`node:20-alpine` build stage $\to$ `ghcr.io/astral-sh/uv:python3.11-bookworm-slim` runtime). Deployed to Traefik v3 with path-based priority routing on `demos.roadtotech.me`:
- Priority 10: Public guest route on `/birthday` and `/birthday/api/*`.
- Priority 20: Authelia ForwardAuth SSO route on `/birthday/admin` and `/birthday/api/admin/*`.
- **Defense-in-Depth Authentication**: Admin API endpoints independently verify the presence of the `Remote-User` header injected by Authelia ForwardAuth, rejecting unauthenticated requests with HTTP 401 and preventing anonymous access if proxy rules are bypassed.
- **Homelab Orchestration**: Integrated into `appctl` with an `app.yaml` manifest declaring the `demos.roadtotech.me` domain, `BASE_PATH=/birthday`, and membership in the shared `proxy-net` Docker network.
### NixOS Declarative Dynamic Trusted Wi-Fi Firewall (Prototype)
- Designed an event-driven dynamic firewall architecture for mobile NixOS workstations in `~/Config/system/core.nix`, addressing port-management friction during local development.
- Implemented a custom `iptables` sub-chain (`nixos-fw-lan`) managed by a NetworkManager dispatcher script triggered on network connection events:
- Dynamically unblocks arbitrary incoming development ports (FastAPI on `:8000`, Vite on `:5173`) when connected to the trusted home SSID ("VICTORIA").
- Automatically locks down ingress traffic upon disconnecting or roaming to untrusted public Wi-Fi networks.
- Documented the architecture and verification procedure in [`04-learning/guides/nixos/dynamic-trusted-wifi-firewall.md`](../../04-learning/guides/nixos/dynamic-trusted-wifi-firewall.md), explicitly marking it as `status: testing` pending further field verification.
### Biome Monorepo VCS Symmetry & Root Resolution
- Investigated and resolved tooling configuration asymmetry in polyglot monorepos where backend tools (`uv`, `ruff`, `pytest`) traverse directories cleanly while frontend linters (Biome) fail when nested in subdirectories without local `.gitignore` files.
- Codified Biome v2's `vcs.root: ".."` resolution in [`04-learning/knowledge/technologies/biome-monorepo-vcs-symmetry.md`](../../04-learning/knowledge/technologies/biome-monorepo-vcs-symmetry.md), preserving clean subdirectory tool encapsulation without polluting repository roots.
### Hermetic Workstation Nix Development Shell
- Configured a hermetic, reproducible `flake.nix` development shell for `Sites/bdinvite` packaging Node.js 20, Python 3.11, `uv`, `biome`, and `sqlite3`, enabling isolated development without global system package pollution.
---
## Planning & Specifications
- [BDInvite Architecture & Deployment Decision Record](../../03-records/decisions/bdinvite-architecture-and-deployment.md)
- MADR 4.0 capturing single-container multi-stage packaging, split Traefik priority routing, Authelia ForwardAuth defense-in-depth, and self-hosted typography.
- [BDInvite Implementation Plan](../../01-plans/bdinvite/implementation-plan.md)
- Phased technical execution plan (P0–P5) covering Docker packaging, FastAPI backend, React 19 frontend, Traefik split routing, and deployment.
- [Digital Invitation Frontend Specification](../../01-plans/bdinvite/frontend-specification.md)
- Responsive design principles, particle canvas architecture, typography, and guest/admin state transitions.
- [BDInvite System Topology Hub](../../06-projects/bdinvite/README.md)
- Project hub documenting architecture, repository locations, network topology, and database models.
- [Dynamic Trusted Wi-Fi Firewall Guide](../../04-learning/guides/nixos/dynamic-trusted-wifi-firewall.md)
- Technical guide capturing the NetworkManager dispatcher + iptables sub-chain architecture on mobile NixOS workstations (`status: testing`).
- [Biome Monorepo VCS Symmetry Knowledge Note](../../04-learning/knowledge/technologies/biome-monorepo-vcs-symmetry.md)
- Architectural note on polyglot monorepo tooling symmetry and VCS root resolution.
---
## Technical Reflections
- **Defense-in-Depth vs. Edge Reliance**:
- Relying solely on reverse proxy routing (Traefik path rules) for authentication is a brittle single point of failure. If proxy labels are misconfigured, private endpoints become public. By requiring the backend to independently verify identity headers (`Remote-User`), the application remains secure regardless of edge misconfigurations.
- **Subpath Micro-Workload Consolidation**:
- Hosting multiple lightweight demonstration or personal apps on dedicated subpaths of a shared subdomain (`demos.roadtotech.me/<app>`) reduces DNS and certificate sprawl, but requires strict base path encapsulation (`base: '/<app>/'` in Vite, `FastAPI(root_path='/<app>')`, and careful trailing slash normalization).
- **Single-Container Multi-Stage Efficiency**:
- For simple web apps with low concurrency, avoiding multi-container deployments (frontend webserver + backend API + external DB) significantly reduces host memory pressure and operational cognitive load while still preserving modern decoupled development workflows.
-122
View File
@@ -1,122 +0,0 @@
---
type: journal
project: brain
date: 2026-10-05
tags:
- skills
- brain
- agent-architecture
- learning-theory
- unlicense
- bdinvite
- graphify
- benchmark
assessed_commits:
- 42927b9858c1b091bb6e78d3abcf6f9500bd7547
- 364601af3dede7f247a81a9e6760879f7eb6bd42
- e1f745608a9a00a27baaa014b2d631f91adcbecd
- cd4b52cdce7c681f82ca237e18fa2601b2fb2e6e
- d01eef586166cc175ca44096b94cf079369d20dd
- a05e98a94c6f45ad2103b2142fe5d372cfed2285
- fee7429a1064193c066b8c20bd6927977599a67f
- 9ae6c84a066dceda7ccc520833fcc78dd6fef8ec
- 70bdc0e5dc6c0a2a8ffa088847f4bab0eeb03828
- 6b529cf86a12f6bcd3d7eb41ef40444c58f68236
- 552ebe48b4ee1a5621ee5a728aee4c40f00ed298
- 98635f73ada6003babd358234af18865f19fc21f
- ae38ba6414ecda9e919e244b7f3db8762ee6135b
- 8fafa08d13711796154d5a6005997c644373792b
- cf14d806d363f857e142210b73253af6bea92bd4
- 6281a266654856bd9446aed1df1aaddf5717ac76
- f72138f7186dce5dad170027d23a4e24e0c3f860
- 5826a10fa20c6aafb441eecb1c3ce6b8693e4431
- de43014c0c765194feffe776e6bf34b3ede21797
- 4bc004da6d599e334753045957daecc82f398386
- 6d1af69a54a1766d049b68d057e32b6fd31a6b7f
- 06ee05cf46cb8d6d0912ddb438b5b527c00c44dc
---
# Daily Journal: 2026-10-05
## Wins
### Skills Repository Decoupling & Architecture
- **Portable Core vs. Vault Extensions**: Formally separated universal pair-programming skills (`skills/`) from context-dependent workflows (`extensions/`). Codified the repository invariant: *Portable skills must not encode a user's filesystem topology*.
- **Semantic Path Abstraction**: Standardized skills (`document`, `practice`) to express destinations semantically (e.g. `default notes inbox`, `project docs/`), delegating concrete path mapping to the active agent profile rather than brittle runtime `.config` lookups.
- **Learner-First Philosophy**: Authored the *"Why Build Instead of Borrow?"* rationale in `README.md`, articulating four core design principles: defeating the Comprehension Illusion, intentional epistemic friction ("Your call"), operational ownership, and radical simplicity over prompt bloat.
- **Unlicense Adoption**: Dedicated the skills repository to the public domain under `UNLICENSE.md` with zero proprietary constraints.
- **Journal Builder Protocol**: Specified, implemented, and verified [`skills/journal-builder/SKILL.md`](https://github.com/kiskaadee/skills/blob/main/skills/journal-builder/SKILL.md). Structured as a daily engineering-learning synthesis pipeline featuring locked learning objectives, hidden assessment rubrics, 3-part formative feedback, and an explicit `Answer:` vs. `Skip:` response contract.
- **Journal Specification in Document**: Expanded `document` to include `Journal` as a 6th epistemic type, codifying the canonical format in `skills/document/references/journal-authoring.md`.
- **Commit Logger Pipeline Restoration**: Activated `commit-logger` in `install.sh`, fixed parent-SHA resolution on initial commits, and backfilled all 12 repository commits into `Brain/00-inbox/commit-log.csv`.
- **Pipeline Contracts & Boundary Alignment**: Resolved inter-skill contracts: defined the explicit provenance boundary for incremental `journal-builder` runs, aligned `journal-authoring` mutability to support reconciliation, and bounded `draft-curation` to hand off to `git-commit` rather than mutating history directly.
### Second Brain Knowledge Graph
- Synchronized vault index nodes ([`05-agents/skills/README.md`](../../05-agents/skills/README.md) and [`AGENTS.md`](../../AGENTS.md)) to reference `extensions/draft-curation` and `extensions/commit-logger`, passing all repository structural and typing validations.
### BDInvite Graphify Benchmark Review
- Reviewed the eight-checkpoint A/B benchmark comparing standard repository exploration with Graphify-assisted exploration. Both conditions passed the benchmark gates; Graphify used fewer estimated tokens in five checkpoints, while its aggregate was 22.92 million versus 19.91 million for control (+15.1%).
- Revisited how checkpoint-level results support conclusions about Graphify and identified limits in the experiment's causal attribution.
---
## Decisions, Incidents & Artifacts
- [Skills Repository](https://github.com/kiskaadee/skills)
- `f72138f`: `docs: clarify philosophy, license, and repository invariants`
- `5826a10`: `refactor: separate portable core skills from vault extensions`
- `de43014`: `feat(journal-builder): add journal-builder skill and document authoring spec`
- `4bc004d`: `feat(extensions): update draft-curation with journal reconciliation and fix commit-logger parent-sha`
- Brain Repository:
- `3cde2c4`: `agent(skills): update extension pointers to draft-curation`
- [Journal Authoring Specification](https://github.com/kiskaadee/skills/blob/main/skills/document/references/journal-authoring.md)
- Standardized the multi-project daily journal structure (`Wins`, `Artifacts`, `Mistakes & Learning Edges`, `Reflections`).
- BDInvite Graphify Benchmark:
- [SSO benchmark roadmap](../../01-plans/bdinvite/sso-benchmark-roadmap.md)
- [Graphify experiment retrospective](../../02-discussions/bdinvite/graphify-agent-experiment-retrospective.md)
---
## Mistakes, Gaps & Learning Edges
### Skills & Agent Architecture
- **Objective 1 (Semantic Destination Mapping)**:
- *Status*: **Achieved** (first attempt)
- *Demonstrated*: Articulated that portable skills must express destinations semantically ("configured notes inbox"), leaving concrete filesystem resolution to the active agent profile.
- **Objective 2 (Configuration Failure Domains)**:
- *Status*: **Achieved** (after formative follow-up)
- *Initial gap*: Captured runtime tool-call costs, but initially omitted the architectural failure modes.
- *Demonstrated*: Reconstructed that centralizing paths in the profile creates a single source of truth and enforces separation of concerns—freeing skills from duplicated environment-discovery machinery so they can focus on their single responsibility.
- **Objective 3 (Memory Pipeline & The Closed Loop)**:
- *Status*: **Achieved** (after formative follow-up)
- *Initial gap*: Described `journal-builder` passively as assessing whether reasoning is "clear".
- *Demonstrated*: Reconstructed the active pedagogical role of the closed assessment loop: locking objectives beforehand from historical evidence prevents shifting goalposts, while hidden rubrics force concrete demonstration and enable systematic reinforcement of conceptual gaps.
- **Dogfood Discoveries Codified into Invariants**:
- *Atomic Objective Invariant*: Compound objectives create ambiguous grading; objectives must test a single, independently assessable understanding.
- *Formative Feedback Rule*: The agent must provide 3-part feedback (correct, missing, decision) after every answer and never grade on a curve.
- *Strict Pipeline Separation*: `journal-builder` outputs content and hands off to `document` without offering or managing storage destinations.
### BDInvite Graphify Benchmark
- **Objective 1 (Aggregate Token Interpretation)**:
- *Status*: **Achieved**
- *Demonstrated*: A count of checkpoint wins hides the magnitude of each difference. Large overruns in CP4 and CP7 outweighed the smaller savings across Graphify's five wins.
- **Objective 2 (Causal Limits)**:
- *Status*: **Achieved**
- *Demonstrated*: The results describe these runs but do not establish a general causal effect from Graphify. The implementations diverged, graph queries were sparse, and other agent behavior could explain token differences.
---
## Technical & Personal Reflections
- **Piercing the Comprehension Illusion in Agent Tooling**:
- The temptation with AI assistance is to optimize for smooth task completion—generating code, summarizing commits, and praising plausible answers. This dogfood run demonstrated that true pairing requires epistemic friction. When the agent stopped grading on a curve and challenged partial answers, it transformed the session from passive activity logging into genuine conceptual consolidation.
- **The Value of the Closed Assessment Loop**:
- Having the agent lock a hidden rubric before asking questions fundamentally changes the dynamic. It prevents the model from rationalizing a vague answer, and gives the learner an immediate, concrete target for reflection when a knowledge gap is surfaced.
- **Checkpoint Counts Hide Cost Magnitude**:
- Graphify's five checkpoint wins did not predict its aggregate token usage because the overruns in CP4 and CP7 were much larger than the savings elsewhere. The observed totals also cannot isolate Graphify's effect when implementation paths differ and graph usage is limited.
---
## Next Objectives
- Dogfood the full pipeline (`git-commit` $\to$ `commit-logger` $\to$ `journal-builder` $\to$ `document` $\to$ `draft-curation`) during upcoming feature and infrastructure work in `bdinvite` and `homelab`.
- Design a follow-up Graphify benchmark that constrains implementation variance and records provider-reported token and cache usage.
-109
View File
@@ -1,109 +0,0 @@
---
type: journal
project: brain
date: 2026-10-07
tags:
- homelab
- appctl
- amc-solutions
- seo
- discovery
- skills
- agent-architecture
- control-plane
- provenance
assessed_commits:
- 99f8581cc89e04ae54e382b4ac8819bacc3e2c6c
- be62be1ae6458ea51cd56ca612599e8147bfb927
- 1c93929ad1b9205a8fd63ecb52fe034917609112
- ffb64d446ab729f8312ea8fea1842fcd6d22251f
- 42594f939480489ea187cf70474502dec829d5db
- b238511203f1fecf3d1c7cd4c8f0a273b2bd3e5f
- 7239d89ad090e4a99c26002578ff2994c39f433c
- f2d88ef811f6df0d0c30bffc0336eb3708d4ea37
- 4e8038d1d76f6d9774f9b0cb5d805afa1e202e7c
- ca76d6c7ffb00faa549a7167d674262be079cdc0
- ebf97fe8e7a389eaab7342267b92b5952bde98c4
- 964e633da257a69550f0dc4001e546d3865d9611
- 82edd74aac96346c1e1bbd56a102a2fd0297b0bc
- d2aab5294764ef57085da0f80a1d8a7e65a20f1b
- 97ee74d4d6bf3e4f226adfc208a428240251e713
- b5f960c8d841cd86613d94866898522a235d80bd
- d4c881e343a5adad9665f7c211579eacba77eafd
- 5de4ad68b66fa8fc599056ec9728999a6f91eecd
- 1d1d75b616d8481d74cbf9174cb2c3b2f5e3be0d
- 2e0df8e9154b307e9a758e3815da662cf58191c9
- 129220d33bd6de1764d99a035c31e9ca5756c760
- f03d53a57778d10ae523ec3f1b031f4ffad359f9
- 0b9636de056bd764056af7de99b296f02734e58c
- fcb01ad62cdaa910ed42ebf6845ed8fa20d4f90b
- 04c2900d8139811678ff27e71525870c7964b8b8
- 13a299f61f8c340ef7bb813a2b49e582638fda7d
- 8c80078ff92591a11682ccd10dfe82e4938d13d6
- 2d893109562892c775addc7691528b30521d3753
- 17da9a9d6f1ab431e61465438668e6fea246605c
- 2297cd5cbab0760382067e0b49d02085fdfb46b4
---
# Daily Journal: 2026-10-07
## Wins
### AMC Solutions Digital Discovery (`amc-solutions-seo`)
- **Research Workspace Architecture**: Bootstrapped an evidence-based digital discovery workspace establishing an epistemic separation between context (hypotheses, unknowns), evidence (empirical technical observations), analysis (interpretive synthesis), deliverables, and inspection tools.
- **Reproducible Crawl Tooling**: Built type-safe Python inspection scripts (`inspect_site.py`, `inspect_internal_pages.py`) to systematically record HTTP response headers, SSL certificates, DNS configurations, tech stacks, and internal page structures.
- **Empirical Evidence Curation**: Recorded 15 grounded observations (`OBS-001` through `OBS-015`) documenting home, service, contact, and regulatory mining pages. Synthesized technical crawl observations into `analysis/inspeccion-sitio-estatico.md`.
- **Findings Review Skill**: Implemented the `review_findings` interactive checkpoint skill to present observations objectively to stakeholders without leaping into premature redesign recommendations.
### Homelab Core & Control Plane Architecture (`homelab`)
- **Appctl Engine Modernization**: Finalized and merged `scripts/appctl_engine_v2.py` (+458 lines) and unit test suite `tests/unit/test_appctl_engine_v2.py` (+338 lines) into `Core/main` (`2297cd5`).
- **Typed Provenance & Docker Inspection**: Implemented type-safe Docker status inspection, image revision extraction, and provenance domain models, excluding legacy engine debt from Pyright.
- **Control Plane Architectural Commitment**: Formulated Architectural Decision Record transitioning from ad-hoc host CLI execution sourcing `/run/secrets/` to a stateful control plane daemon (`appctld`) communicating over a Unix domain socket / mTLS with typed contracts.
- **Roadmap v5 Specification**: Curated the consolidated Homelab Architecture Consolidation & Control Plane Roadmap v5, marking superseded execution guides and refactoring roadmaps.
### Skills Repository & Second Brain Governance (`skills` / `brain`)
- **Pedagogical Provenance**: Hardened `journal-builder` to enforce collaborative reconstruction checkpoints and strict provenance verification via `assessed_commits`.
- **Journal Authoring Contract**: Codified the `assessed_commits` YAML schema in `document/references/journal-authoring.md` to establish a deterministic boundary between reviewed history and pending ledger events.
- **Reconciliation Invariant**: Updated `draft-curation` to union `assessed_commits` during daily journal reconciliation, preventing dropped assessment state during incremental daily runs.
- **Workspace Discovery**: Standardized workspace resolution roots in the agent profile to resolve active projects, Config, Homelab, and Brain paths.
- **Anne Droid Integration Plan**: Authored the execution blueprint for the Anne Droid frontend specialist persona and Gitea forge review workflow.
### BDInvite & System Workstation Tooling (`bdinvite` / `Config`)
- **Router-Level Auth Hardening**: Refactored router-level auth, enforced Ruff and Pyright typing standards, and added `pytest-playwright` backend development dependencies.
- **Benchmark Archival**: Archived SSO Graphify benchmark artifacts and retrospectives.
- **Workstation Tooling**: Provisioned HTML/XML language servers and OpenSSL into `nix-ld`, packaged FFmpeg, MKVToolNix, and ClamAV signature updater, and refreshed Nix flake input revisions.
---
## Decisions, Incidents & Artifacts
- **Architectural Decision Record**: [`homelab-appctl-control-plane-architecture.md`](../decisions/homelab-appctl-control-plane-architecture.md) — Adopts stateful daemon (`appctld`), UDS/mTLS transport, typed domain models, and decoupled CLI ergonomics.
- **Implementation Roadmap**: [`architecture-consolidation-roadmap-v5.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v5.md) — Unifies appliance baseline and phases P0–P4 for homelab control plane.
- **Persona Blueprint**: [`anne-droid-persona-and-gitea-integration.md`](../../01-plans/brain/anne-droid-persona-and-gitea-integration.md) — Anne Droid persona architecture and Gitea review gates.
- **Core Engine Code**: `scripts/appctl_engine_v2.py` and `tests/unit/test_appctl_engine_v2.py` merged into `Homelab/Core`.
- **Discovery Evidence & Synthesis**: `analysis/inspeccion-sitio-estatico.md` and `skills/review_findings/` in `amc-solutions-seo`.
---
## Mistakes, Gaps & Learning Edges
### `amc-solutions-seo`
- **Achieved (Epistemic Separation in Pre-Discovery Exploration)**: Mastered the necessity of isolating raw empirical observations (`evidence/`) from interpretive analysis (`analysis/`) and stakeholder unknowns (`context/`). Avoided the common failure mode of jumping directly into cosmetic redesigns or unwanted dependencies before diagnosing whether the client's bottleneck is discoverability, information architecture, conversion pathways, or business prioritization.
### `skills`
- **Achieved (Ledger Immutability & Stateful Provenance)**: Solved the architectural tension between an append-only, immutable event ledger (`commit-log.csv`) and consumption tracking. Identified why `git log --since` fails (date boundaries are non-authoritative and blind to review progress) and verified that full 40-character commit SHAs in `assessed_commits` (with unioning during reconciliation) provide an immutable, idempotent provenance boundary.
### `homelab`
- **Achieved (Control Plane Decoupling & Typed Metadata)**: Masterfully articulated the liabilities of legacy ad-hoc shell execution sourcing `/run/secrets/`. Formulated key architectural principles:
1. *Transport vs. Authority*: SSH or socket transport access does not equal application-level authorization.
2. *Least-Privilege Secret Resolution*: `SecretProvider` boundary resolves secret references on demand without polluting process environments.
3. *Typed Invariants*: Types express invariants and enable offline unit tests, while runtime integration tests remain essential for authentication, socket permissions, and reconciliation.
4. *Git as Truth*: Git remains the sole authoritative source of desired deployment state; the daemon reconciles and executes rather than becoming a competing source of truth.
---
## Technical & Personal Reflections
- **Responsibility Boundaries**: Modernization does not mean replacing Bash with Python or adding types for their own sake. It means establishing clear boundaries around responsibilities that were previously mixed together (domain logic, process orchestration, OS execution, secret access) and making those boundaries enforceable and testable.
- **Discipline of Investigation**: In client discovery, separating verifiable ground truth from interpretations prevents prescribing solutions to problems the business does not actually have.
- **The Ledger vs. Memory Pattern**: In learning systems and data pipelines, never mutate an immutable event log to track consumer state; maintain consumer provenance explicitly as metadata in downstream artifacts.
@@ -1,81 +0,0 @@
---
type: guide
project: brain
tags:
- brain
- skills
- investigation
- documentation-router
- walkthrough
---
# Walkthrough: Global Documentation Router & Investigation Skills
Operational walkthrough for the implementation of the decoupled, reusable global skill system separating **procedural engineering investigation** from **second-order architectural documentation treatment**.
---
## 1. System Architecture
```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.**
---
## 2. Implemented Artifacts & Locations
### A. Procedural Investigation Skill
- **Runtime Location**: `~/.gemini/config/skills/diagnose/SKILL.md`
- **Repository Specification**: [`skills/diagnose`](https://github.com/kiskaadee/skills/blob/main/skills/diagnose/SKILL.md)
- **Role**: Purely empirical troubleshooting following the scientific method (Observation $\to$ Verification) and the 6-part interactive checkpoint protocol.
- **Boundary**: Stops cleanly upon verified recovery; hands off to `document` if non-obvious learning or architectural questions emerged.
### B. Documentation Skill
- **Runtime Location**: `~/.gemini/config/skills/document/SKILL.md`
- **Repository Specification**: [`skills/document`](https://github.com/kiskaadee/skills/blob/main/skills/document/SKILL.md)
- **Role**: Second-order knowledge filter and gatekeeper (anti-markdown factory).
- **Core Rules**:
- **Gatekeeping**: Routine/trivial tasks produce **NO ARTIFACT**.
- **Classification**: Maps knowledge to Discussion (WHY), ADR (WHAT decided), Plan (HOW to build), or Debug Record (Empirical RCA).
- **Multi-Artifact Coordination**: Decomposes multi-faceted sessions into discrete artifacts.
- **Optional Relationships vs. Pipelines**: Discussions may inform ADRs; ADRs may constrain Plans. These describe optional information flow and authority boundaries, not a mandatory documentation pipeline. Each artifact may exist independently whenever justified.
- **Anti-Overlap**: The same fact may appear in multiple documents only when it serves a different epistemic purpose.
### C. Modular Authoring Reference Specifications
Packaged under `~/.gemini/config/skills/documentation-router/references/`:
1. **`discussion-authoring.md`**: Exploratory narrative, preserves uncertainty and rejected alternatives, zero "decision voice".
2. **`adr-authoring.md`**: Strict **MADR 4.0** standard, compact architectural commitments, content-addressed OCI digest immutability vs. mutable tags, delegating field-level schema representation to the Plan.
3. **`plan-authoring.md`**: Authoritative implementation specification, ordered execution (P0–P5), pure constraints without re-arguing rationale, verification gates, runbooks, and DoD.
4. **`debug-record-authoring.md`**: Historical investigation / RCA record covering bugs, regressions, system anomalies, failed migrations, configuration errors, and unexpected behaviors.
### D. Global Rules Decoupling
- **Location**: `~/.gemini/config/AGENTS.md`
- Separated `Global Rule: Engineering Investigation` from `Global Rule: Architectural & Project Documentation`.
---
## 3. Verification
- Skills discovered in `~/.gemini/config/skills/`:
- `engineering-investigation`
- `documentation-router` (with 4 authoring reference documents)
- `python scripts/validate-brain.py && python scripts/test_validator.py`: **`✅ All checks passed.`**
@@ -1,67 +0,0 @@
---
type: guide
project: homelab
tags:
- homelab
- documentation
- consolidation
- epistemic-triad
- walkthrough
---
# Walkthrough: Homelab Architecture Consolidation Documents Reorganization
Operational walkthrough of the reorganization of the Homelab Architecture Consolidation documentation across the epistemic triad:
1. Standardized the ADR around **MADR 4.0** with purely architectural commitments (delegating exact schema fields to the Plan).
2. Deepened the Discussion with authentic historical engineering narrative while stripping out "decision voice" and absolutist language.
3. Framed the Plan as the **authoritative implementation specification** without re-litigating rationale.
4. Cleanly organized all consolidation lineage artifacts into `01-plans/homelab/consolidation/`.
---
## 1. Epistemic Model & Boundaries
```text
Discussion ──informs──> ADR ──constrains──> Plan
^ ^ |
└──────────────────────┴─────────────────┘
cross-references
```
> **Epistemic Rule**: The same fact may appear in multiple documents only when it serves a different epistemic purpose:
> - **Discussion ([`02-discussions/homelab/architecture-migration-v3-to-v4.md`](../../../02-discussions/homelab/architecture-migration-v3-to-v4.md))**: *Why did we get here?* Preserves uncertainty, historical context, friction points, rejected alternatives, and how the reasoning evolved.
> - **ADR ([`03-records/decisions/homelab-3tier-architecture-and-provenance.md`](../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md))**: *What was decided?* Concise MADR 4.0 record answering what problem was being solved, what forces mattered, what options were considered, what was chosen, and what trade-offs were accepted.
> - **Plan ([`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md`](../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md))**: *What exactly are we going to build?* Authoritative implementation specification containing contracts, schemas, security invariants, phased milestones (P0–P5), and runbooks.
> - **Project Hub ([`06-projects/homelab/README.md`](../../../06-projects/homelab/README.md))**: *Where do I find it?* Pure navigation layer indexing the current triad and historical predecessors.
---
## 2. Document Refinements Applied
### A. Architectural Decision Record (`homelab-3tier-architecture-and-provenance.md`)
- **MADR 4.0 Standard**: Formatted into Context & Problem Statement $\to$ Decision Drivers $\to$ Considered Options $\to$ Decision Outcome $\to$ Pros and Cons $\to$ Consequences $\to$ More Information.
- **Architectural-Level Commitments**: Retains the requirement that *three independent identities must exist* (deployment configuration revision, upstream source revision, container artifact digest), but delegates the exact JSON field names (`deployment_config_revision`, etc.) exclusively to the Plan.
- **Digest Immutability vs. Artifact Identity**: Clarified that *OCI container images produced by CI act as provenance objects; the immutable identity of the deployed artifact is its OCI digest, with source commit provenance carried via the `org.opencontainers.image.revision` label*.
- **Neutral Decision Rationale**: Replaced evaluative phrasing with neutral systems language: *"because it addresses the identified coupling and provenance problems while retaining a bounded operational control path"*.
### B. Architectural Discussion (`architecture-migration-v3-to-v4.md`)
- **Eliminated "Decision Voice"**: Replaced ADR-style phrases (`"The Decision: Reject local cloning..."` and `"The Adopted Resolution:"`) with narrative exploratory phrasing (`"Resulting Direction: The exploration ultimately converged on..."`).
- **Conceptual Precision**: Clarified that the architecture decouples into **three core tiers** connected by intermediate artifacts and an isolated filesystem state root, avoiding conflation into a 5-tier model.
- **Tempered Tone**: Removed absolutist claims (e.g. replaced `"could not be cleanly open-sourced"` with `"made clean open-sourcing difficult without stripping Homelab configuration"`, and `"100% pure application code"` with `"allows the software repository to remain free of Homelab-specific infrastructure"`).
- **Historical Analysis vs. Sales Pitch**: Retitled Section 4 to *"What Became Possible After the Architectural Separation"* and framed the comparisons around concrete historical friction versus engineering motivations.
### C. Implementation Roadmap & Execution Plan (`architecture-consolidation-roadmap-v4.md`)
- **Authoritative Implementation Specification**: Clarified role as the authoritative implementation specification governing concrete phased rollout.
- **Pure Constraints**: Kept technical requirements (such as `git ls-remote` commit equality) as crisp specification invariants rather than re-arguing their rationale.
- Header bidirectionally cross-links to both the ADR and Discussion.
### D. Subsystem Lineage Directory (`01-plans/homelab/consolidation/`)
- Relocated all 6 roadmap and guide documents (v1–v4) into `01-plans/homelab/consolidation/`.
- All intra-vault links updated and verified across project hubs and journal entries.
---
## 3. Verification
- `python scripts/validate-brain.py`: **`✅ All checks passed. Brain structure is valid.`**
- `python scripts/test_validator.py`: **`Ran 10 tests in 0.001s ... OK`**
@@ -1,148 +0,0 @@
---
type: guide
status: testing
project: nixos
tags:
- nixos
- security
- firewall
- networkmanager
- iptables
- workstation
---
# Dynamic Trusted Wi-Fi Firewall Configuration (Testing)
> **Status**: Testing / Experimental · **Host**: `laptop` (`~/Config`) · **Subsystem**: `system/core.nix`
This guide documents the architecture, implementation, and verification procedure for a dynamic, SSID-aware firewall on mobile NixOS workstations.
---
## 1. Problem Statement & Operational Friction
Mobile workstations operating on NixOS enforce strict ingress firewall policies by default (`networking.firewall.enable = true`). While this default protects machines on public or hostile networks (cafes, airports, conferences), it introduces operational friction during local development:
* **Ad-Hoc Port Friction**: Running local development servers (Vite on `:5173`, FastAPI on `:8000`, test webhooks, or mobile preview servers) requires opening incoming ports so secondary devices (phones, tablets) on the LAN can connect.
* **Security vs. Convenience Anti-Pattern**: Opening ports globally via `networking.firewall.allowedTCPPorts = [ 8000 5173 ... ]` leaves those ports permanently open on all networks, including untrusted public Wi-Fi.
* **Manual Toggling Anti-Pattern**: Disabling the firewall manually via `sudo systemctl stop firewall` creates risk if the operator forgets to re-enable it before traveling.
---
## 2. Architecture & Design
The solution relies on an event-driven, declarative pattern combining a dedicated `iptables` sub-chain with a NetworkManager dispatcher script:
```text
Incoming Packet (wlo1)
│
▼
[INPUT / nixos-fw]
│
(JUMP rule 1)
│
▼
[nixos-fw-home]
/ \
If SSID == "VICTORIA" If Other / Down
│ │
[-i wlo1 -j ACCEPT] [FLUSH -F]
│ │
(Allow All) (Falls through to strict
NixOS default DROP)
```
### Key Invariants
1. **Isolated Chain**: All dynamic rules live inside a dedicated sub-chain `nixos-fw-home`. The base `nixos-fw` chain is never mutated directly by runtime scripts.
2. **Fail-Safe Fallback**: If disconnected or connected to any SSID other than `"VICTORIA"`, `nixos-fw-home` is immediately flushed (`-F`), restoring the default strict drop policy instantly.
3. **Dual Stack**: Both IPv4 (`iptables`) and IPv6 (`ip6tables`) chains are managed symmetrically.
---
## 3. Declarative NixOS Implementation
The implementation is located in `~/Config/system/core.nix`:
```nix
# 🛡️ Dynamic Firewall for Trusted Home Wi-Fi
# Automatically marks the Wi-Fi interface as fully trusted (accepting all incoming ports)
# ONLY when connected to the trusted home Wi-Fi network ("VICTORIA"), removing the friction of
# managing arbitrary development ports. Restores the strict default firewall immediately upon
# disconnecting or connecting to any public / untrusted network.
networking.firewall.extraCommands = ''
iptables -N nixos-fw-home 2>/dev/null || true
iptables -C nixos-fw -j nixos-fw-home 2>/dev/null || iptables -I nixos-fw 1 -j nixos-fw-home
ip6tables -N nixos-fw-home 2>/dev/null || true
ip6tables -C nixos-fw -j nixos-fw-home 2>/dev/null || ip6tables -I nixos-fw 1 -j nixos-fw-home
'';
networking.networkmanager.dispatcherScripts = [
{
source = pkgs.writeShellScript "nm-trusted-wifi-firewall" ''
IFACE="$1"
ACTION="$2"
TRUSTED_SSID="VICTORIA"
IPT="${pkgs.iptables}/bin/iptables"
IP6T="${pkgs.iptables}/bin/ip6tables"
LOGGER="${pkgs.util-linux}/bin/logger"
manage_chain() {
local cmd="$1"
$cmd -N nixos-fw-home 2>/dev/null || true
$cmd -C nixos-fw -j nixos-fw-home 2>/dev/null || $cmd -I nixos-fw 1 -j nixos-fw-home
}
manage_chain "$IPT"
manage_chain "$IP6T"
if [ "$ACTION" = "up" ] && [ "$CONNECTION_ID" = "$TRUSTED_SSID" ]; then
$IPT -F nixos-fw-home
$IPT -A nixos-fw-home -i "$IFACE" -j ACCEPT
$IP6T -F nixos-fw-home
$IP6T -A nixos-fw-home -i "$IFACE" -j ACCEPT
$LOGGER -t nm-firewall "Connected to trusted network $TRUSTED_SSID: trusted interface $IFACE (all incoming ports accepted)"
elif [ "$ACTION" = "down" ] || [ -n "$CONNECTION_ID" -a "$CONNECTION_ID" != "$TRUSTED_SSID" ]; then
$IPT -F nixos-fw-home
$IP6T -F nixos-fw-home
$LOGGER -t nm-firewall "Untrusted or disconnected network ($CONNECTION_ID): restored strict firewall"
fi
'';
type = "basic";
}
];
```
---
## 4. Verification & Diagnostic Commands
### Inspect Active Chain Rules
```bash
# Verify sub-chain presence and active rules
sudo iptables -L nixos-fw-home -n -v
sudo ip6tables -L nixos-fw-home -n -v
```
### Inspect Dispatcher Logs
```bash
# Follow event logs from the dispatcher script
journalctl -t nm-firewall -e --no-pager
```
### Triggering State Transitions Manually
```bash
# Force NetworkManager to re-evaluate connection state
nmcli connection up VICTORIA
```
---
## 5. Outstanding Testing Items
- [ ] Verify packet delivery from mobile device over LAN while on `VICTORIA`.
- [ ] Verify AP client isolation status on local router if packets are dropped upstream.
- [ ] Verify transition when roaming to mobile hotspot (confirming chain flush).
- [ ] Verify behavior across system sleep/wake cycles (`systemd-suspend`).
@@ -1,185 +0,0 @@
---
type: knowledge
status: stable
topics:
- testing
- python
tags:
- mutation-testing
- mutmut
- ast
- pydantic
- metaprogramming
related:
- testing.md
- ../technologies/python/pydantic.md
---
# AST Mutation Testing with Modern Python Syntax and Strict Models
## 1. The Practical Problem or Question
When evaluating the quality of a test suite, line coverage can be deceiving. A test can execute every line of a module without asserting the correctness of the operations performed. Mutation testing addresses this by programmatically generating point mutations in source code (inverting conditionals, altering boundary checks, stripping statements) and checking whether the existing test suite fails and catches the change.
In a modern Python codebase using Python 3.10+ syntax features and strict runtime schema enforcement (such as Pydantic v2 models with `extra="forbid"`), introducing an AST-level mutation tool like `mutmut` often breaks before any test even runs. The runner crashes or silently skips files, producing confusing errors or deceptive coverage statistics.
How do AST mutation engines interact with modern grammar and metaclass enforcement, and how can we write code that satisfies both strict runtime safety and dynamic mutation testing?
---
## 2. The Intuitive First Attempt and Why It Breaks
The intuitive workflow is straightforward: install the mutation runner, point it at the source directory, and run the test suite.
```bash
# Intuitive expectation: run mutmut and inspect killed mutants
mutmut run
```
In practice, this fails at two distinct boundaries:
### Failure Mode 1: The AST Parser Barrier
Most Python mutation tools do not execute against raw byte strings. They parse source code into an Abstract Syntax Tree (AST) using libraries like `parso`.
Python 3.10 introduced parenthesized multi-context statements:
```python
with (
socket.create_connection((domain, port), timeout=timeout) as sock,
ctx.wrap_socket(sock, server_hostname=domain) as ssock,
):
cert = ssock.getpeercert()
```
When an AST parser lacks full support for parenthesized statements containing `as` target assignments, it raises a syntax error. Rather than halting, mutation runners often log a warning and silently skip the entire module. The developer assumes the module has 100% mutation survival or that no mutants were possible, when in reality the module was never audited.
### Failure Mode 2: Strict Metaclass Rejection
To track and toggle mutations on the fly without repeatedly rewriting source files to disk, mutation frameworks inject mutant lookup structures directly into the runtime classes:
```python
# What the mutation engine injects at class definition time
class MyModel(BaseModel):
xǁMyModelǁfield__mutmut_mutants = {"field": ...}
```
If the codebase uses Pydantic v2 models with strict schemas (`extra="forbid"`), Pydantic's model metaclass inspects every class-level attribute. When it finds the unannotated dictionary injected by the mutation runner, it immediately raises a `PydanticUserError`:
```text
pydantic.errors.PydanticUserError: A non-annotated attribute was detected:
xǁMyModelǁfield__mutmut_mutants = {...}
```
Tests that import or instantiate the models fail immediately during stats collection, halting the mutation run.
---
## 3. The Core Mental Model
AST mutation tools manipulate code syntax and class internals dynamically. Modern language features (Python 3.10+ parenthesized context managers) and strict metaclasses (Pydantic `extra="forbid"`) reject these tools unless syntax is parser-friendly and dynamic class attributes are explicitly ignored.
```mermaid
flowchart TD
subgraph Static Analysis & Parsing
Source["Source Code"] --> Parser["AST Parser (e.g. Parso)"]
Parser -->|"Fails on with (a as b, c as d)"| Skip["Module Silently Skipped"]
Parser -->|"Passes on nested with statements"| AST["Mutated AST"]
end
subgraph Runtime Metaclass Inspection
AST --> Loader["Module Loader"]
Loader --> ClassDef["Class Definition with Injected __mutmut_mutants dict"]
ClassDef -->|"StrictModel (extra='forbid')"| PydanticCrash["PydanticUserError: non-annotated attribute"]
ClassDef -->|"StrictModel (ignored_types=(dict,))"| ValidModel["Clean Model Instantiation & Test Run"]
end
```
The friction arises because two systems have opposing goals:
- **Strict runtime modeling**: treats any unexpected class attribute or payload key as a security or typing defect.
- **Dynamic mutation tooling**: relies on injecting unannotated inspection attributes and rewriting ASTs in place.
Bridging them requires making our syntax parser-tolerant and configuring model metaclasses to ignore mutation harnesses.
---
## 4. Mechanism and Progressive Depth
### Rewriting Context Syntax for AST Parsers
Instead of using parenthesized multi-target context managers, use nested `with` blocks. Modern linters like Ruff may flag nested blocks under rule `SIM117`, which can be suppressed with an inline comment:
```python
# Ineffective: crashes older AST parsers in mutation engines
with (
socket.create_connection((domain, port), timeout=timeout) as sock,
ctx.wrap_socket(sock, server_hostname=domain) as ssock,
):
raw_cert = ssock.getpeercert()
# Effective: cleanly parsed by all AST engines
with socket.create_connection((domain, port), timeout=timeout) as sock: # noqa: SIM117
with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
raw_cert = ssock.getpeercert()
```
### Allowing Mutation Harness Attributes in Strict Pydantic Models
Pydantic v2 provides a configuration setting specifically for class attributes that should bypass field parsing and schema validation: `ignored_types`.
By default, Python treats dynamic dictionaries attached to class definitions as class attributes. Adding `ignored_types = (dict,)` to base models tells Pydantic to ignore any bare dictionaries attached to the class namespace:
```python
# Ineffective: rejects mutation dictionary injection
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
# Effective: preserves strict runtime data validation while ignoring mutation scaffolding
class StrictModel(BaseModel):
model_config = ConfigDict(
extra="forbid",
strict=True,
ignored_types=(dict,),
)
```
This preserves the architectural invariant: user payloads with unexpected fields are still strictly rejected, while the testing engine's injected metadata passes without error.
### Authoritative Runner Configuration (`setup.cfg`)
Many modern Python projects consolidate configuration in `pyproject.toml`. However, tools like `mutmut` 3.x specifically look for `setup.cfg`. If configuration is only in `pyproject.toml`, the runner may fail with `FileNotFoundError: Could not figure out where the code to mutate is.`
Providing a standard `setup.cfg` anchors the configuration unambiguously:
```ini
[mutmut]
paths_to_mutate=scripts/
runner=pytest -x
also_copy=
scripts
config
docker-compose.yml
```
---
## 5. The Mental Picture
Imagine an automated building inspector who measures every doorway using a rigid mechanical caliper.
- If you install a custom decorative doorframe with non-standard angles (parenthesized multi-context syntax), the caliper jams, and the inspector walks past the entire room without checking anything.
- When the inspector enters a room, they stick a temporary barcode sticker on every appliance (`__mutmut_mutants`). If the building has strict security guards (Pydantic metaclass) instructed to destroy anything unlabelled, the guards raise the alarm and lock down the building.
To let the inspection proceed, you use standardized doorway profiles that the mechanical caliper can read, and you give the security guards a rule: "Ignore barcode stickers on the machinery; focus on inspecting visitors entering the lobby."
---
## 6. The Trade-Offs and Costs
Making these accommodations involves small architectural and stylistic compromises:
1. **Slightly More Verbose Syntax**: Nested `with` blocks require an extra indentation level and an explicit linter override (`# noqa: SIM117`). In exchange, the codebase becomes compatible with a wider variety of static analysis and AST instrumentation tools.
2. **Loosened Class Namespace Checking**: Setting `ignored_types = (dict,)` means that if a developer accidentally assigns a class-level dictionary intended to be a typed field without a type annotation, Pydantic will ignore it rather than raising a configuration warning. Instance fields and runtime data payloads remain completely strict.
3. **Dual Configuration Files**: Maintaining `setup.cfg` alongside `pyproject.toml` introduces an additional configuration file until upstream tooling fully standardizes on PEP 518/621 configuration tables.
---
## 7. One Principle to Remember
When choosing between modern syntactic convenience and tooling interoperability:
> *Does this language construct or metaclass constraint allow external AST and introspection tools to analyze the code, or does it enforce purity at the expense of testability?*
@@ -1,208 +0,0 @@
---
type: knowledge
status: stable
topics:
- agent-engineering
- engineering-practices
- prompt-engineering
tags:
- skills
- agents
- workflow
- state-machines
related:
- ./notes-to-docs.md
- ./incident-investigation-and-journaling.md
---
# How to Build Effective Agent Skills
When we repeatedly find ourselves guiding an AI coding agent through the same engineering workflow, the natural next step is to bundle those instructions into an agent skill. Whether it is diagnosing an elusive bug, executing test-driven development, reviewing a pull request, or conducting an architectural interview, capturing that workflow as a reusable skill seems straightforward: write down what a good engineer does, save it as a `SKILL.md` file, and let the agent run it.
In practice, that first attempt often produces frustrating results. The agent starts out following the instructions, but midway through it skips an essential diagnostic step. It reads a few files and jumps straight to an unverified theory. It announces that tests passed when it only checked syntax, or it generates hundreds of lines of code while forgetting the architectural constraints we carefully wrote into the prompt.
The problem is rarely that the model lacked intelligence. The problem is that we treated the skill as a large prompt rather than an engineering component.
---
## 1. The Intuitive First Approach and Why It Breaks
When most of us write our first skill, we write a descriptive essay. We describe the ideal behavior in prose:
```markdown
# My Bug Debugger Skill
You are an expert software debugger. When given a bug:
1. Carefully inspect the codebase.
2. Form sound hypotheses.
3. Be thorough and make sure you do not guess.
4. Write tests to verify your fix.
5. Make sure the fix does not break anything else.
```
This looks reasonable to a human reader because a human brings an implicit operational discipline to the task. A human knows that "do not guess" means setting up a debugger or writing a reproduction script before touching application logic.
An LLM agent does not bring that operational discipline. Instead, several specific failure modes emerge:
### A. Premature Completion (The Pull of Later Steps)
LLMs generate text sequentially, and when all future steps are visible in context, the model experiences an attention pull toward "being done." If Step 1 is "find the problem" and Step 4 is "write the fix," the agent will often perform a superficial inspection, convince itself it spotted the bug, and rush straight to proposing changes. The presence of the downstream steps actively undermines the legwork required by the current step.
### B. The Attention Tax (The "Coin-Flip" Bug)
If we try to fix the rush by adding more instructions, reference tables, styling guidelines, and output templates into the main skill document, we trigger a different failure. As the document expands to hundreds of lines, the agent's attention thins across the excess. Static reference material (such as full HTML layouts or mock examples) buries the procedural steps, turning compliance into a coin-flip.
### C. Conversational Drift
If the skill relies on conversational memory to track where it is in a multi-step workflow, state degrades with every turn. After six or seven tool calls, terminal outputs and file diffs push the initial plan out of the model's high-attention window. The agent loses the thread of which hypotheses were eliminated and which remain active.
Notice what is happening: **We are asking text generation to do the work of operational control.** A prompt describes what a good outcome looks like; it does not regulate the transitions required to get there.
---
## 2. The Core Mental Model: A Skill is a State Machine
What clarified this for me was changing how I think about a skill's purpose:
> **A skill is not a prompt that asks for good work. A skill is a bounded operational state machine that restricts agent variance.**
Instead of asking, *"What should I tell the agent to do?"*, the engineering question becomes:
* What discrete states does this workflow pass through?
* What observable evidence proves the current state is complete before entering the next?
* What must be impossible for the agent to skip?
* Where does the agent hold state when conversational context gets crowded?
```mermaid
flowchart TD
S1["Phase 1: Build Feedback Loop<br/>(Deterministic command)"] --> G1{"Hard Red Gate<br/>Does it go red on this bug?"}
G1 -- No --> S1
G1 -- Yes --> S2["Phase 2: Minimise Repro<br/>(Strip non-essential inputs)"]
S2 --> G2{"Minimised Gate<br/>Is every input load-bearing?"}
G2 -- Yes --> S3["Phase 3: Hypothesise<br/>(3-5 falsifiable predictions)"]
S3 --> S4["Phase 4: Targeted Probes<br/>(Tagged instrumentation)"]
S4 --> S5["Phase 5: Fix & Verify<br/>(Red-to-green confirmation)"]
```
When an engineering workflow is modeled this way, the skill stops being an open-ended conversational suggestion and becomes an enforceable procedure.
---
## 3. Mechanisms of an Effective Skill
Studying robust real-world skills reveals several concrete structural mechanisms that produce reliable behavior.
### 3.1 Negative Boundaries Are as Important as Positive Ones
An agent with an unbounded mandate will instinctively expand its scope. A skill must define what it explicitly refuses to own.
For example, when authoring an engineering specification from an ongoing discussion, an agent that is allowed to ask questions will often trap the user in recursive interview loops. A well-bounded specification skill states its negative boundary up front:
```markdown
# To Spec
Turn the current conversation context and codebase understanding into an engineering spec.
Do NOT interview the user; just synthesize what has already been established.
```
Similarly, in test-driven development, an agent will frequently try to refactor nearby architecture while writing a test. An effective TDD skill places an explicit boundary:
```markdown
Refactoring is not part of this loop. Refactoring belongs to the review stage,
not the red-to-green implementation cycle.
```
By explicitly taking certain actions off the table, we remove the branches where the agent most frequently wanders.
### 3.2 Anti-Skipping Invariants (Hard Pre-Condition Gates)
Telling an agent "be thorough" does not work. What works is inserting an explicit stopping condition between phases that forbids advancing until an observable artifact exists.
In debugging, for example, the primary failure mode is reading code to construct a clever theory before proving how the bug fails. An effective debugging skill halts this with a hard gate:
```markdown
### Completion Criterion: A tight loop that goes red
Phase 1 is done only when you can name ONE command that you have already run at least once,
and that is red-capable, deterministic, and fast.
If you catch yourself reading code to build a theory before this command exists, stop:
jumping straight to a hypothesis is the exact failure this skill prevents.
No red-capable command, no Phase 2.
```
The capitalized instruction is not rhetorical decoration. It is an operational invariant that gives the agent an unambiguous test for done versus not-done.
### 3.3 The Information Hierarchy and Progressive Disclosure
Every line added to a skill's main instruction file consumes a portion of the agent's attention window on every turn.
A clean skill organizes material across a three-tier ladder:
1. **In-File Steps**: The primary, ordered procedure the agent executes.
2. **In-File Reference**: Short definitions and rules consulted on demand across all paths.
3. **Disclosed Reference**: Detailed schemas, branch-specific procedures, code templates, or format examples pushed out into sibling files (e.g. in a `references/` directory) and reached via a context pointer.
```text
skills/my-feature/
├── SKILL.md # Primary operational steps and gates
├── references/
│ ├── format-schema.md # Output template, loaded only when generating output
│ └── branch-logic.md # Edge-case rules, loaded only if Branch B fires
└── scripts/
└── run-checks.sh # Deterministic verification script
```
Progressive disclosure is not merely an optimization to save tokens. It protects the primary procedural sequence from being diluted by static reference text. If a section of reference only matters when a specific branch is taken, moving it behind a pointer keeps the main path legible.
### 3.4 Externalizing State
When a workflow involves multiple steps, storing state in conversation turns is fragile. Robust skills anchor state in external, durable structures:
* **Task Graphs over Step Lists**: Instead of a flat list of steps, represent work as a directed acyclic graph where items have explicit dependencies. Unblocked items form an active "frontier" that can be tackled, while blocked items wait.
* **Persistent Markdown Files**: Store notes, hypothesis lists, and eliminated causes in lightweight files on disk rather than relying on the agent remembering what it tried four turns ago.
* **Git Worktrees**: For complex implementations, running separate subagents in isolated Git worktrees against a shared integration branch prevents concurrent edits from polluting the working tree.
### 3.5 Asymmetric Context Pressure
Different tasks require different amounts of working memory.
An implementation agent has high context pressure: it must explore the repository, understand types, inspect call sites, and write code.
A code review agent has low context pressure: it receives a static diff and a set of standards.
If we load fifty style guidelines, architectural rules, and code smell checklists into the implementation agent, we crowd out the tokens it needs to understand the problem. A better design decouples the roles: keep the implementation skill focused on red-green testing, and let a separate review skill enforce coding standards against the resulting diff.
---
## 4. The Mental Picture: The Assembly Jig
Think of an effective skill not as an instructional manual, but as a **physical assembly jig or an airlock**.
In a precision manufacturing workshop, a jig does not advise the machinist on how to hold the wood straight. The jig is a physical frame that mechanically prevents the blade from cutting at the wrong angle.
Similarly, in an airlock, Door B physically cannot open until Door A is sealed and the chamber pressure equalizes. The airlock does not rely on the occupant's memory or discipline; the mechanism enforces the sequence.
An effective skill acts as an airlock for the agent:
* It clamps the boundaries so the agent cannot wander.
* It locks Phase 2 until Phase 1 produces its physical key (a failing test, a verified reproduction command, an agreed seam).
* It moves extraneous reference material outside the chamber until the specific stage that needs it arrives.
---
## 5. The Trade-Offs and Costs
Engineering skills into state machines with external references and strict gates introduces real trade-offs. It is not always the right choice.
| Dimension | Informal Prompt / Ad-Hoc Instructions | Engineered Skill Component |
| :--- | :--- | :--- |
| **Initial Setup Time** | Seconds to write. Zero file overhead. | Hours to design, test, and split into references. |
| **Maintenance Burden** | None. Disposable after the session. | Requires ongoing curation as project tools evolve. |
| **Flexibility** | High. Easy to pivot mid-stream. | Rigid. Forces adherence to the encoded state machine. |
| **Execution Reliability** | Low to moderate. Prone to skipping steps. | High. Gates prevent premature completion. |
| **Best Used For** | One-off exploratory tasks and routine edits. | Recurring, high-friction, error-prone workflows. |
### When NOT to Build a Skill
* **One-Off Tasks**: If a task will not be performed repeatedly, writing a formal skill is pure overhead. Give direct instructions in the session.
* **Simple Rules**: If the requirement is a universal constraint (e.g. "always use 2-space indentation" or "never commit secrets"), encode it as an always-loaded system rule, not a procedural skill.
* **Premature Fragmentation**: Breaking a simple 3-step script into five tiny separate skills creates excessive cognitive load for the human and complicates inter-skill routing without adding reliability.
---
## 6. One Principle to Remember
When designing a skill for an engineering workflow, avoid asking what you want the agent to do.
Instead, ask this question:
> **"Before allowing the agent to move to the next step, what observable artifact proves the current step actually succeeded?"**
If the skill cannot name that artifact, it does not yet have a gate. It only has a suggestion.
@@ -1,124 +0,0 @@
---
type: knowledge
status: stable
topics:
- information-retrieval
- natural-language-processing
- metadata
- documentation
tags:
- tagging
- extraction
- ast
- yake
- flashtext
- bm25
---
# Deterministic Tag & Key Term Extraction for Markdown Documents
To replace non-deterministic or manual tag assignment with a repeatable, deterministic pipeline, several algorithmic and heuristic strategies can be employed. The ideal approach depends on whether extraction is performed across a single document in isolation or over an entire knowledge corpus.
---
## 1. Single-Document Statistical Extraction
These algorithms extract keywords from individual documents without requiring corpus-wide statistics or model training.
### A. YAKE! (Yet Another Keyword Extractor)
- **Mechanism**: Unsupervised feature-based statistical heuristic. Evaluates words based on 5 features: casing, word position (early occurrences weighted higher), word frequency, word-to-context relatedness (dispersion across sentences), and sentence differences.
- **Key Characteristics**:
- **100% Deterministic**: Same input text always produces the exact same ranked keyphrases and scores.
- **Multi-word phrases (n-grams)**: Extracts 1-gram to 3-gram key terms (e.g., `"reverse proxy"`, `"systemd service"`).
- **Zero Corpus Dependency**: Operates on a single document without prior training or IDF tables.
- **Tooling**: `yake` (Python library).
### B. Graph-Based Centrality (TextRank & PositionRank)
- **Mechanism**: Builds a graph where words/lemmas are nodes and edges represent co-occurrence within a sliding window (e.g., 3–5 tokens). It then computes node importance using PageRank.
- **PositionRank**: Extends TextRank by incorporating structural bias, weighting words appearing early or in headings more heavily.
- **Key Characteristics**:
- Robust against repetitive "keyword stuffing".
- Identifies central concept clusters rather than isolated frequent words.
- **Tooling**: `pytextrank`, `pke` (Python Keyphrase Extraction toolkit).
---
## 2. Corpus-Aware Retrieval Weighting
If processing a collection of documents (e.g., an entire repository or search index), corpus statistics significantly improve relevance.
### A. TF-IDF & Okapi BM25
- **Mechanism**:
- **TF (Term Frequency)** measures how often a term appears in a document.
- **IDF (Inverse Document Frequency)** penalizes terms that appear broadly across all documents (e.g., common words like "guide", "setup", "example").
- **BM25**: Incorporates non-linear term frequency saturation and document length normalization.
- **Search Engine Synergies**: This directly mirrors how lexical search engines (e.g., Pagefind, Tantivy, Meilisearch, Elasticsearch) index documents. Top TF-IDF / BM25 terms are mathematically the highest-discriminating query terms for that document.
---
## 3. Markdown-Aware Structural AST Parsing
Markdown files possess strong structural signals that standard NLP tokenizers discard (frontmatter, headings, code spans, emphasis).
### Structural Weighting Matrix
A custom deterministic AST parser (using `markdown-it-py`, `mistletoe`, or `tree-sitter-markdown`) assigns hierarchical multipliers to extracted tokens:
| Element | Structural Multiplier | Purpose |
| :--- | :--- | :--- |
| **Document Title (`# H1`)** | `5.0x` | Primary topic identification |
| **Section Headings (`## H2`, `### H3`)** | `3.0x` | Sub-topic boundaries |
| **Inline Code & Code Fences (`\`code\``)** | `2.5x` | Specific tools, commands, symbols (e.g., `pg_dump`, `nix-shell`) |
| **Emphasis / Bold (`**term**`)** | `2.0x` | Author-highlighted key phrases |
| **Link Anchor Text (`[text](#)`)** | `2.0x` | Linked entity names |
| **Body Noun Phrases** | `1.0x` | Baseline content |
---
## 4. Controlled Vocabulary & Dictionary Matching
To avoid tag fragmentation (e.g., generating `postgres`, `postgresql`, and `psql` for the same concept), extraction can be anchored against a controlled dictionary.
### A. FlashText / Aho-Corasick Automaton
- **Mechanism**: Builds a deterministic finite automaton (trie) over a predefined taxonomy or keyword list. Scans the document in linear time $O(N)$.
- **Synonym Normalization**: Automatically maps variations and aliases to canonical tags (e.g., `pg` $\to$ `postgresql`, `k8s` $\to$ `kubernetes`).
- **Tooling**: `flashtext` (Python).
---
## 5. Fixed-Seed Dense Representation (KeyBERT)
- **Mechanism**: Uses sentence/sub-word transformer embeddings (e.g., `all-MiniLM-L6-v2`) to compute cosine similarity between candidate n-gram phrases and the whole document embedding.
- **Determinism**: Fully deterministic when using fixed model weights and greedy selection / Maximal Marginal Relevance (MMR) with temperature = 0.
- **Strengths**: Captures semantic synonyms even if exact wording differs slightly.
---
## Recommended Hybrid Architecture
For a technical knowledge base or Markdown documentation repository, the most effective deterministic tagging pipeline combines **Structural Parsing**, **Single-Doc Keyphrases (YAKE)**, and **Controlled Taxonomy Matching (FlashText)**:
```mermaid
flowchart TD
MD[Markdown Source File] --> AST[1. Structural AST Extractor]
MD --> YAKE[2. YAKE Statistical Extractor]
MD --> FT[3. FlashText Taxonomy Matcher]
AST -->|Heading & Code tokens| Agg[Score Aggregator & Deduplicator]
YAKE -->|Top N-Gram Keyphrases| Agg
FT -->|Canonical Taxonomy Tags| Agg
Agg --> Final[Deterministic Tags / Search Keywords]
```
### Pipeline Flow:
1. **FlashText** matches known technologies/concepts from a dictionary, ensuring clean canonical tags.
2. **AST Parser** extracts prominent heading keywords and backtick symbols (`code identifiers`).
3. **YAKE!** captures novel high-salience multi-word phrases from the body text.
4. **Aggregator** sums structural weights, filters stopwords, normalizes to lowercase kebab-case, and selects the top $K$ key terms.
---
## Related Knowledge & Documentation
* [From Notes to Technical Documentation](notes-to-docs.md)
* [Second Brain Governance & Agent Guide](../../../AGENTS.md)
@@ -1,279 +0,0 @@
---
type: knowledge
status: stable
topics:
- homelab
- architecture
- control-plane
- gitops
- systems-evolution
tags:
- homelab
- architecture
- appctl
- evolution
- systems-engineering
project: homelab
related:
- ../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md
- ../../../03-records/decisions/homelab-appctl-control-plane-architecture.md
- ../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md
- ../../../02-discussions/homelab/control-plane-and-engine-modernization.md
---
# The Architectural Evolution of the Homelab Control Plane: From Ad-Hoc Scripts to a Unified Fail-Closed Daemon (v1 to v6)
Building a self-hosted platform usually begins with a familiar set of developer conveniences: a handful of Docker Compose files, reverse-proxy routing via Traefik, an identity provider like Authelia, and bash shell scripts to stitch container lifecycles together.
For a single server running a few hobby services, ad-hoc automation feels sufficient. However, as workloads multiply, GitOps webhooks enter the loop, multi-tenant networking hardens, and AI coding agents execute inside developer sessions, shell-based shortcuts quickly collapse under the weight of implicit trust, escaping environment variables, unvalidated states, and uncoordinated mutations.
Over the course of six distinct architectural iterations (v1 through v6), the **Homelab Core** platform (`roadtotech.me`) evolved from a collection of imperative bash scripts into a formal, declarative, fail-closed **Operational Control Plane**.
This article chronicles that evolutionary journey—documenting the architectural friction, hard decisions, mental model shifts, and design invariants established across each phase.
---
## 🗺️ Evolutionary Timeline: The Six Eras at a Glance
| Version | Architectural Paradigm | Primary Catalyst | Key Breakthrough / Invariant |
| :--- | :--- | :--- | :--- |
| **v1** | **Ad-Hoc Imperative Automation** | Initial deployment consolidation | Traefik edge ingress + Authelia SSO; bash CLI (`scripts/appctl`) wrapping `docker compose`. |
| **v2** | **Structural Discipline & Invariant Testing** | Reviewer scrutiny & trust boundary leaks | Separation of Roadmap from Implementation Guide; automated invariant testing (`./scripts/test`). |
| **v3** | **Mail Realignment & State Isolation** | SnappyMail zero-data-loss cutover | Decoupling state from code: persistent application data strictly resides under `~/var/lib/homelab/`. |
| **v4** | **3-Tier Architecture & Dual-Axis Truth** | Multirepo friction & drift ambiguity | Decoupling Software vs. Deployment vs. Platform; two-axis inspection (`✓ Synced` local vs. upstream `ls-remote`). |
| **v5** | **The Control Plane Daemon Vision** | Shell execution limits & AI agent risks | Transitioning `appctl` from a script to a daemon (`homelab-appctl.service`); 5-stage `DeploymentModel` lifecycle. |
| **v6** | **Operational Truth & Fail-Closed Reality** | Pre-P4 implementation audit (`DEC-01–05`) | Single typed `POST /v1/operations`; token-gated auth over UDS & HTTP; OS user isolation; fail-closed audit guard. |
---
## Act I: The Ad-Hoc Era (v1) — The "Make It Run" Baseline
### The Starting Point
The homelab infrastructure originated with three distinct functional layers:
1. **Edge Ingress**: Traefik handling automated Let's Encrypt wildcard TLS (`*.roadtotech.me`) alongside Authelia for ForwardAuth single sign-on.
2. **Platform Appliance (`~/Core`)**: Core services (Gitea forge, CI runner, Vaultwarden, Nextcloud, Homepage).
3. **Decentralized Workloads (`~/Sites`)**: Standalone user applications (media servers, invite apps, custom APIs) each managed via their own compose files.
To simplify orchestration, a bash utility named `appctl` was written. Operators could SSH into the server and type:
```bash
appctl up jellyfin
appctl restart authelia
appctl sync
```
### The Architectural Friction
While `v1` successfully unified service execution, it suffered from foundational security and architectural vulnerabilities:
- **Implicit SSH Trust**: Anyone with SSH access could invoke `appctl` and mutate running workloads with zero identity validation or telemetry.
- **Shell Sourcing Hazards**: Workload environment variables were injected using shell `source "$APP_DIR/.env"`. Any syntax error broke the CLI, and any unescaped command substitution (`$(...)`) executed arbitrary code with the operator's privileges.
- **Split Authority**: Portainer ran alongside CLI scripts, allowing containers to be modified out-of-band without version control or Git tracking.
- **Entangled State**: Stateful service data, configuration templates, and Git repositories were co-located under `Core/config/` and `Sites/`, making clean backups and rollbacks perilous.
---
## Act II: The First Hardening (v2) — Structural Discipline & Invariant Testing
### The Catalyst
As homelab infrastructure became the backbone for personal production workflows, arbitrary shell scripts were deemed unacceptable. A formal architectural review exposed significant trust boundary leaks: webhook payloads from Git repositories could trigger host shell executions without sufficient containment.
### The Evolution
Roadmap `v2` transformed the consolidation effort from an ad-hoc cleanup into an engineering discipline:
1. **Separation of Intent from Runbook**: The architecture split into a strategic roadmap ([`architecture-consolidation-roadmap-v2.md`](../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v2.md)) and an executable tactical runbook ([`architecture-consolidation-implementation-guide-v2.md`](../../../01-plans/homelab/consolidation/architecture-consolidation-implementation-guide-v2.md)).
2. **Automated Invariant Testing**: Introduced `./scripts/test`, requiring every change to pass a suite of Pytest unit and security tests before merging.
3. **Privilege Boundary Enforcement**: Webhook listeners were restricted from running raw shell strings; arguments were tokenized and passed via fixed parameter lists.
---
## Act III: Topology Realignment (v3) — Decoupling State from Code
### The Catalyst: The SnappyMail Migration Challenge
In milestone P1, platform mail routing needed separation from webmail: Stalwart mail server was re-homed to `smtp.roadtotech.me`, while SnappyMail was evicted from the Core stack and migrated to a standalone application workload under `~/Sites/snappymail`.
The requirement was absolute: **zero data loss**. Address books, user configurations, and preferences could not be dropped.
### The Breakthrough: The Clean State Root Invariant
During the migration, the team confronted a major antipattern: application databases and persistent user storage were living directly inside Git working trees (`Core/config/snappymail/data`). Committing state into Git bloated history, while ignoring it with `.gitignore` created fragile directories that could be wiped out during branch switches or cleanups.
Roadmap `v3` codified the **Clean State Root Invariant**:
> *Persistent, mutable application runtime data must reside strictly under `~/var/lib/homelab/<app>/`, entirely decoupled and isolated from version-controlled Git repositories.*
By snapshotting state, verifying byte-for-byte parity (`diff -r`), and mounting the isolated host directory into the container, SnappyMail migrated with zero data loss.
---
## Act IV: The 3-Tier Architecture & Dual-Axis Truth (v4)
### The Problem: Multirepo Friction & Ambiguous Drift
By iteration `v4`, application development was plagued by repository confusion:
- Should an application's source code live in the same repository as its Docker Compose file?
- When `appctl list` reported an application as "out of sync," did that mean the local deployment directory had uncommitted edits, or that upstream software had a new Git commit?
### The Solutions: ADR-0001 & Two-Axis Inspection
1. **The 3-Tier Architecture**:
Decoupled the platform into three strictly bounded layers:
- **Tier 1 (Software Tier)**: Upstream application source code (`~/Projects/*`), producing versioned OCI container images or release tags.
- **Tier 2 (Deployment Tier)**: Declarative deployment manifests and Compose configurations (`~/Sites/*`), tracking *how* software is wired.
- **Tier 3 (Platform Tier)**: Host appliance configuration, OS kernel, and control plane (`~/Core`), managing reverse proxy routing and host security.
2. **Dual-Axis Deployment Truth**:
Engine inspection was split into two independent axes:
- **Axis 1 (Local Deployment Checkout)**: Evaluates working-tree cleanliness (`✓ Synced`, `* Dirty`, `⬆ Ahead`, `⬇ Behind`).
- **Axis 2 (Upstream Software Provenance)**: Queries upstream remote repositories via bounded `git ls-remote` (with a 10s timeout) to determine if newer commits or release tags exist.
3. **Document Consolidation**:
Recognizing that maintaining separate "Roadmap" and "Implementation Guide" documents caused synchronization drift, Roadmap `v4` unified both into a single authoritative blueprint.
---
## Act V: The Control Plane Paradigm Shift (v5) — From Scripts to Daemon
### The Catalyst: The Threat Model of AI Agents and Shell Execution
In mid-2026, AI coding agents became standard tools within the developer's workstation and SSH sessions. This introduced a critical new security boundary:
- If an AI coding agent running in an operator SSH session has shell access, and `appctl` relies on local host permissions, a rogue command or misinterpreted prompt could reconfigure reverse proxy routing or delete persistent state volumes.
- Host shell scripts lack centralized authorization, request validation, structured audit trails, and concurrency locks.
### The Architecture: Roadmap v5
Roadmap `v5` fundamentally reimagined `appctl`:
- It ceased to be a bash script.
- It was defined as a standalone Systemd daemon (`homelab-appctl.service`) exposing **One Logical API** across dual transports: a Unix Domain Socket (`/run/homelab/appctl.sock`) and an HTTP listener.
- It established the **5-Stage DeploymentModel Lifecycle**:
$$\text{Repository} \xrightarrow{\text{Inspection}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Containers}$$
- **AI Authoring Boundary**: The AI was restricted to acting strictly as a proposal generator. Zero execution authority was granted to automated agents; every mutating deployment model required explicit human operator approval.
---
## Act VI: Operational Truth & Fail-Closed Hardening (v6)
### The Pre-Implementation Reality Check
Before writing a single line of daemon code for Milestone P4, the architecture underwent an exhaustive, evidence-based exploratory audit (`2026-10-16`).
Comparing the high-level vision in Roadmap `v5` against the production codebase revealed several critical architectural gaps:
- *Endpoint Proliferation*: Designing separate REST endpoints (`GET /workloads`, `POST /operations/deploy`, `POST /operations/restart`) introduced URL-vs-body routing ambiguities and complicated transport equivalence.
- *The Local Trust Fallacy*: Assuming Unix Domain Socket connections were inherently trusted because they originated on localhost violated the principle of least privilege.
- *Duplicated GitOps Execution*: Both `gitops_dispatcher.py` and `scripts/appctl` maintained independent, divergent implementations of `git pull` and `docker compose up`.
- *Insecure Environment Sourcing*: The bash CLI still parsed environment variables via shell `source`, failing to run Compose AST security pre-flight checks on operator commands.
### The Locked Architectural Decisions (`DEC-01` through `DEC-05`)
To eliminate ambiguity, five binding architectural decisions were codified:
```text
┌─────────────────────────────────────────────────────────────────────────────┐
│ ROADMAP v6: LOCKED DECISIONS │
├─────────┬───────────────────────────────┬───────────────────────────────────┤
│ DEC-01 │ Unified Transport & Router │ Single POST /v1/operations │
│ │ │ Strict HTTP/1.1 on UDS & TCP │
├─────────┼───────────────────────────────┼───────────────────────────────────┤
│ DEC-02 │ Host Access != Mutation Auth │ Mandatory Bearer token for writes │
│ │ │ UDS SO_PEERCRED = viewer read only│
├─────────┼───────────────────────────────┼───────────────────────────────────┤
│ DEC-03 │ Service Identity & Isolation │ User: homelab-appctl │
│ │ │ Fail-closed audit log (0600) │
├─────────┼───────────────────────────────┼───────────────────────────────────┤
│ DEC-04 │ Unified GitOps Worker │ Dispatcher delegates to daemon │
│ │ │ Single execution codepath │
├─────────┼───────────────────────────────┼───────────────────────────────────┤
│ DEC-05 │ Pure-Python Pre-Flight & Env │ No shell 'source' or 'eval' │
│ │ │ Mandatory Compose AST inspection │
└─────────┴───────────────────────────────┴───────────────────────────────────┘
```
#### 1. Single Command-Oriented Operational Router (`DEC-01`)
Instead of dozens of disparate REST endpoints, the daemon exposes **one canonical endpoint**:
- `POST /v1/operations`: Dispatches all 13 canonical domain operations (both read-only and mutating) using strict Pydantic v2 schemas (`extra="forbid"`, `strict=True`).
- `GET /v1/health`: A simple convenience probe for orchestrator liveness.
- Logs are strictly bounded (`tail: 1..1000`, max 256 KiB output buffer); live SSE streaming is deferred to Milestone P7.
#### 2. Host Access Does Not Confer Mutation Authority (`DEC-02`)
Entering the server via SSH confers Unix access, but **zero operational control plane privileges**:
- Mutating operations (`workload.deploy`, `workload.update`, etc.) and sensitive reads (`workload.config`, `workload.logs`) strictly require an authenticated Bearer token validated against `/run/secrets/appctl/tokens.json` using constant-time hashing (`hmac.compare_digest`).
- Local Unix socket connections without a token leverage kernel peer credentials (`SO_PEERCRED`). If the calling UID belongs to an authorized operator, the caller is granted **`homelab-viewer` privileges only**—enabling zero-friction inspection (`appctl list`, `appctl info`) and tab-completion while blocking all mutations.
#### 3. Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)
The daemon executes under an isolated system user:
- `User = "homelab-appctl"`, `Group = "homelab-operators"`.
- Operator processes and AI sessions running as `<operator>` cannot read daemon token secrets (`mode 0400`) or forge/tamper with audit logs (`mode 0600`).
- **Fail-Closed Disk Guard**: Before any mutating subprocess (Docker/Git) executes, a `DISPATCHED` audit record must be written and flushed to disk. If the audit log fails to write (disk full, permissions error), **the operation immediately aborts with `500 ERR_EXECUTION_FAILED`**.
#### 4. Unified GitOps Execution Path (`DEC-04`)
The background worker in `gitops_dispatcher.py` no longer directly invokes `docker compose` or `git pull`. Instead, it admits the webhook push against `config/deployments.yaml`, manages the commit queue, and dispatches an authenticated `workload.update` command to the daemon over `/run/homelab/appctl.sock`.
#### 5. Inert Pure-Python Environment Assembly (`DEC-05`)
All shell sourcing is eradicated:
- Subprocess environments are assembled in memory using an inert pure-Python key-value parser.
- Variable keys are validated against strict regexes (`ENV_KEY_RE`) and forbidden from overriding reserved infrastructure parameters (`RESERVED_ENV_KEYS`).
- Every workload Compose file is passed through `validate_compose_security()` prior to execution, rejecting privileged containers, host networking, and arbitrary socket mounts.
---
## 🏛️ Comprehensive Architecture Comparison: v1 vs. v6
```text
┌──────────────────────┬───────────────────────────────┬────────────────────────────────┐
│ Dimension │ Era 1 (v1 Baseline) │ Era 6 (v6 Locked Target) │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ Runtime Engine │ Bash wrapper script │ Dedicated Python 3 daemon │
│ │ (`scripts/appctl`) │ (`homelab-appctl.service`) │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ Transports │ Local shell subprocesses only │ Dual HTTP/1.1: │
│ │ │ • /run/homelab/appctl.sock │
│ │ │ • 127.0.0.1:9001 │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ Authentication Gate │ Host Unix user permissions │ Mandatory SHA-256 Bearer token │
│ │ (Entering via SSH = Admin) │ (UDS peercred = Viewer only) │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ RBAC Tiers │ None (Binary host access) │ 3-Role Hierarchy: │
│ │ │ • homelab-admin (All targets) │
│ │ │ • homelab-operator (Whitelisted│
│ │ │ Sites workloads only) │
│ │ │ • homelab-viewer (Read-only) │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ API Surface │ Ad-hoc CLI subcommands │ Single POST /v1/operations │
│ │ (Arbitrary flag parsing) │ Strict Pydantic v2 schemas │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ Environment Parsing │ Shell `source "$APP_DIR/.env"`│ Pure-Python inert key-value │
│ │ (Vulnerable to injection) │ parser with reserved key locks │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ Compose Security │ Unvalidated direct execution │ Pre-flight Compose AST validator│
│ │ │ (Blocks root/socket escapes) │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ GitOps Engine │ Disparate worker script with │ Webhook ingress delegates to │
│ │ duplicated pull/up logic │ daemon workload.update over UDS│
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ Audit Telemetry │ Ephemeral terminal stdout │ Append-only RFC JSONL audit log│
│ │ │ with fail-closed disk guard │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ Persistent State │ Mixed in Git working trees │ Isolated under │
│ │ (`Core/config/`, `Sites/`) │ `~/var/lib/homelab/<app>/` │
├──────────────────────┼───────────────────────────────┼────────────────────────────────┤
│ Concurrency Control │ Uncoordinated race conditions │ Per-target non-blocking flock │
│ │ │ (Immediate 409 Conflict) │
└──────────────────────┴───────────────────────────────┴────────────────────────────────┘
```
---
## 💡 Key Engineering Takeaways & Mental Models
### 1. Boundaries Must Precede Implementation
In the early days of a project, the temptation is to jump straight into writing daemon server loops. However, the pre-P4 audit proved that without explicit boundary contracts, developers end up making accidental architectural commitments during implementation (such as inventing multiple REST routes, exposing unredacted logs, or allowing tokenless mutations over Unix sockets). Resolving `DEC-01` through `DEC-05` before writing code ensured every implementation slice has an unambiguous Definition of Done.
### 2. The Illusion of Local Trust
A pervasive security trap in homelab and developer tooling is assuming that if a request originates on `localhost` or over a Unix domain socket, the caller can be trusted. In a modern environment where developers run complex dependency trees, automated pipelines, and autonomous AI coding assistants, **the host is a multi-tenant boundary**. Enforcing explicit Bearer tokens for all mutations over both network and socket transports guarantees that entering the machine via SSH does not give arbitrary tools free rein over infrastructure.
### 3. Fail-Closed by Design
Systems fail in messy, unpredictable ways: disks run out of space, DNS records fail to resolve, YAML manifests contain syntax errors. A resilient system does not attempt to "best-effort" its way through uncertainty. If the manifest does not strictly match the Pydantic schema, it fails. If Compose tries to mount `/var/run/docker.sock`, it aborts. If the audit log cannot append a `DISPATCHED` record to disk, the mutation halts immediately before any container is touched.
### 4. Evolutionary Design is Not Indecision
Progressing from v1 to v6 is not evidence of bad initial planning; it is the natural consequence of real-world learning. Systems must be built to solve today's operational problems while establishing the clear interfaces, automated regression suites, and architectural records necessary to safely refactor them tomorrow.
---
## 🔗 Related Knowledge & System Artifacts
- **Active Plan**: [Architecture Consolidation & Control Plane Roadmap v6](../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md)
- **Authoritative ADRs**:
- [ADR: Homelab appctl Control Plane Architecture](../../../03-records/decisions/homelab-appctl-control-plane-architecture.md)
- [ADR: Homelab 3-Tier Architecture & Provenance](../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md)
- **Historical Lineage**:
- [Roadmap v5 (Superseded)](../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v5.md)
- [Roadmap v4 (Superseded)](../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md)
- [Roadmap v3 (Superseded)](../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v3.md)
- [Roadmap v2 (Superseded)](../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v2.md)
- [Roadmap v1 (Superseded)](../../../01-plans/homelab/consolidation/architecture-consolidation-roadmap.md)
@@ -1,76 +0,0 @@
---
type: knowledge
status: stable
topics: ['frontend', 'biome', 'tooling', 'monorepo']
---
# Biome Linter Monorepo Symmetry & VCS Root Resolution
## 1. Problem: Configuration Asymmetry in Polyglot Repositories
In modern fullstack or polyglot application repositories (e.g. FastAPI/Go/Rust backend + React/Vite SPA frontend), developer tooling presents a layout dilemma:
* **Backend Tooling Autonomy**: Python tools like `uv`, `ruff`, or `pytest` locate their configuration strictly via directory traversal for `pyproject.toml`. They operate completely indifferent to Git repository root boundaries.
* **Frontend Tooling Creep**: By contrast, JS/TS linters historically placed configuration files (`.eslintrc.json`, `prettierrc`, or `biome.json`) at the repository root. When Biome has Git integration enabled (`vcs: { enabled: true, useIgnoreFile: true }`), placing `biome.json` inside `frontend/` causes Biome to fail if executed from a subfolder without its own local `.gitignore`:
```text
internalError/fs: Biome couldn't find an ignore file
```
* **The Asymmetry**: This often pushes developers to put `biome.json` at the root, making the repository root asymmetric: Python is cleanly encapsulated in `backend/`, while JavaScript tooling pollutes the top-level directory.
---
## 2. Solution: VCS Root Resolution (`vcs.root`)
Biome v2 introduces explicit version control root configuration via `vcs.root`. By pointing the VCS root to the parent directory (`".."`), `biome.json` can live strictly inside `frontend/` while honoring the root `.gitignore`:
```json
{
"$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true,
"root": ".."
},
"files": {
"ignoreUnknown": true,
"includes": ["src/**", "vite.config.ts"]
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2,
"lineWidth": 90
},
"linter": {
"enabled": true,
"rules": {
"preset": "recommended"
}
}
}
```
---
## 3. Structural Comparison
```text
Asymmetric Layout (Avoid) Symmetric Layout (Preferred)
---------------------------------- ----------------------------------
repo/ repo/
├── backend/ ├── backend/
│ ├── app/ │ ├── app/
│ └── pyproject.toml │ └── pyproject.toml
├── frontend/ ├── frontend/
│ ├── src/ │ ├── src/
│ └── package.json │ ├── biome.json <-- vcs.root = ".."
├── biome.json <-- Leaks out │ └── package.json
├── shell.nix ├── shell.nix
└── .gitignore └── .gitignore
```
### Operational Ergonomics
1. **Isolated Sub-Workspaces**: `frontend/` and `backend/` are both completely self-contained. Deleting, copying, or testing either layer requires no root cleanup.
2. **Seamless CI & DevShell**: From the repository root, commands can target the folder directly (`cd frontend && biome check .` or `nix-shell --run "cd frontend && npm run lint"`).
3. **Zero Ignore Duplication**: All ignore rules remain centralized in the root `.gitignore`.
-125
View File
@@ -1,125 +0,0 @@
---
type: knowledge
status: stable
topics:
- dns
- networking
- doggo
- troubleshooting
tags:
- dns
- networking
- doggo
- cli
- diagnostics
---
# 🐶 `doggo` DNS Diagnostics & Troubleshooting Guide
## Overview
`doggo` is a modern, human-friendly command-line DNS client written in Go. While traditional utilities like `dig` output raw, verbose BIND-style zone records, `doggo` formats responses into clear visual tables, colorful status flags, and structured JSON output.
This makes `doggo` particularly well-suited for interactive network diagnostics, DNS propagation checks, and troubleshooting domain resolution failures.
---
## 1. Spotting Propagation & Local Cache Issues
When updating a DNS record (such as an A or CNAME record), changes take time to propagate across recursive resolvers worldwide due to caching.
### Multi-Resolver Query
Query multiple upstream nameservers simultaneously by separating them with commas:
```bash
# Query local ISP/gateway, Google Public DNS, and Cloudflare simultaneously
doggo roadtotech.me @200.21.200.10,@8.8.8.8,@1.1.1.1
```
### Diagnostic Value
- If your local resolver (`@200.21.200.10`) returns the old IP while public resolvers (`@1.1.1.1` or `@8.8.8.8`) return the new one, the authoritative record is updated correctly; you are merely waiting for local recursive caches to expire.
- If all public resolvers and the authoritative nameserver still serve the old IP, the change was not properly applied at the DNS provider or registrar level.
---
## 2. Tracking TTL (Time to Live) & Cache Invalidation
The `TTL` column indicates the number of seconds a recursive resolver is allowed to retain a record before querying the authoritative nameserver again.
### Monitoring TTL Countdown
```bash
# Query default resolver repeatedly to observe cache expiration
doggo roadtotech.me
```
### Diagnostic Value
- **Observing Invalidation**: Running the command a few seconds apart will show the TTL value counting down (e.g., `298s` $\rightarrow$ `285s` $\rightarrow$ `12s`). When it reaches `0`, the next query pulls fresh records from upstream authority.
- **Root-Cause Analysis**: If an updated record fails to take effect for certain clients, inspecting the TTL explains how long clients are bound to the cached response.
---
## 3. Diagnosing "Website Down" & Nameserver Delegation
When a domain fails to resolve entirely, determine whether the issue is at the application layer, the DNS record level, or nameserver delegation at the registrar.
### Query Nameserver (NS) Records
```bash
# Query authoritative nameservers for the domain
doggo roadtotech.me NS
```
### Diagnostic Value
- **Missing / Empty NS**: If querying `NS` returns an error or no records, check registrar settings: domain registration may be expired, domain status may be on `clientHold`/`serverHold`, or custom nameservers were incorrectly configured.
- **Authoritative Verification**: Once nameservers (e.g., `pam.ns.cloudflare.com`) are known, query them directly with `doggo roadtotech.me @pam.ns.cloudflare.com` to bypass recursive caching and verify authoritative state.
---
## 4. Reading DNS Response Status Codes (RCODEs)
When lookups fail, `doggo` highlights the response code in the `STATUS` column:
| Status Code | Meaning | Common Root Causes & Actions |
| :--- | :--- | :--- |
| `NOERROR` | Success | The nameserver replied successfully and found matching records (or an empty answer if the name exists without that specific record type). |
| `NXDOMAIN` | Non-Existent Domain | The domain or queried hostname does not exist on the authoritative server. Check for spelling errors, missing subdomains, or unconfigured DNS zones. |
| `SERVFAIL` | Server Failure | The resolver failed to obtain an answer. Often caused by broken DNSSEC validation (expired signatures, mismatched DS records at registrar), upstream network timeouts, or circular delegation loops. |
| `REFUSED` | Query Refused | The nameserver refused to process the query. Typically triggered by ACL restrictions (e.g., recursive queries disabled for external IPs) or attempted unauthorized zone transfers (`AXFR`). |
---
## 5. Inspecting Raw DNS Details with JSON Output
Tabular outputs are easy to read but can truncate lengthy strings (such as SPF rules, DKIM public keys, or TLS / SSHFP fingerprints).
### Emitting Structured JSON
```bash
# Inspect long TXT and DKIM validation records
doggo roadtotech.me TXT --output json
```
### Pipe to `jq` for Deep Inspection
```bash
# Filter JSON output for specific answers and strings
doggo roadtotech.me TXT --output json | jq '.responses[].answers'
```
### Diagnostic Value
- Prevents visual truncation of critical security and verification records.
- Allows programmatic validation in CI/CD pipelines, shell scripts, and health-check monitors.
---
## Quick Reference Summary
| Diagnostic Intent | Command Example |
| :--- | :--- |
| Basic A record lookup | `doggo roadtotech.me` |
| Compare resolvers | `doggo roadtotech.me @8.8.8.8,@1.1.1.1` |
| Check mail exchange (MX) | `doggo roadtotech.me MX` |
| Check nameservers (NS) | `doggo roadtotech.me NS` |
| Full raw output in JSON | `doggo roadtotech.me TXT --output json` |
| Query over DNS-over-HTTPS (DoH) | `doggo roadtotech.me @https://cloudflare-dns.com/dns-query` |
-56
View File
@@ -1,56 +0,0 @@
# Agents Store & Specification Catalog
This directory serves as the durable repository of AI agent profiles, operational boundaries, behavioral contracts, and safety guardrails across all engineering projects and workstations.
---
## Purpose & Architecture
Rather than treating agent rulebooks (`AGENTS.md`) as transient, untracked local text files or allowing them to interfere with repository workflows, this directory documents each agent specification as a first-class engineering article:
1. **Context & Role**: Details the target workspace, repository ownership, problem domain, and intended agent role.
2. **Operational Scope & Guardrails**: Clarifies permission boundaries (e.g. read-only inspections, forbidden system switches, secret protection).
3. **Canonical Specification**: Preserves the complete, verbatim behavioral prompt deployed in the target environment.
4. **Cross-References**: Connects the agent profile to project overviews, incident journals, and architecture guides.
### Skill Package Architecture (Dual-Audience Separation)
Skills in `05-agents/skills/` are organized as encapsulated capability packages rather than flat, monolithic prompts:
```text
05-agents/skills/<skill-name>/
├── README.md # Human API (Identity, Value, Invocation, Behavior, Outputs, Boundaries)
├── SKILL.md # Agent Specification (Runtime engine, invariants, decision procedures)
└── references/ # Deep-dive modules loaded on demand (progressive disclosure)
```
- **`README.md` (Human API)**: The canonical Brain graph citizen (`type: agent`, `kind: skill`). Focuses strictly on the **capability contract**: what the skill is, why it matters, when to invoke it, expected outputs, negative boundaries, and package manifest.
- **`SKILL.md` (Operational Engine)**: The runtime prompt consumed by Antigravity (`~/.gemini/config/skills/`). Focuses strictly on **agent execution**: state machines, decision procedures, anti-skipping invariants, and behavioral anchors.
- **`references/` (Modular Contracts)**: Modular specifications loaded by the agent on demand, preventing attention dilution.
---
## Catalog of Agent Specifications
| Agent | Target Workspace | Primary Role | Status |
| :--- | :--- | :--- | :--- |
| [Homelab Operations](profiles/homelab-operations.md) | `/home/kiskaadee/Homelab` | Local-first server diagnostics, non-destructive triage, and post-incident journaling | `active` |
| [Homelab Core Platform](profiles/homelab-core.md) | `ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-core` | Core platform foundation, NixOS server services, GitOps boundaries, Docker isolation | `active` |
| [NixOS Mobile Workstation](profiles/nixos-workstation.md) | `ssh://git@gitea.roadtotech.me:2223/kiskaadee/nixos-config` | Declarative NixOS/Home Manager laptop configuration with strict build-only safety barrier | `active` |
| [MagNetFlix Media Pipeline](profiles/magnetflix.md) | `git@github.com:kiskaadee/MagNetFlix.git` | Media acquisition backend (FastAPI, gRPC, Protobuf, SQLite3 WAL, UV workspaces) | `active` |
| [NekoWeb Manga Platform](profiles/nekoweb.md) | `git@github.com:kiskaadee/nekoweb.git` | Self-hosted manga web platform (FastAPI, UV, React/TanStack, HakuNeko Daemon) | `active` |
| [Second Brain Knowledge Graph](profiles/second-brain.md) | `ssh://git@gitea.roadtotech.me:2223/kiskaadee/second-brain` | Personal knowledge graph curation, epistemic validation, and artifact management | `active` |
## Catalog of Operational Skills
For the system-level architecture diagram, skill interaction matrix, and canonical transition workflows, see [skills/README.md](skills/README.md).
| Skill | Target Workspace | Primary Capability | Status |
| :--- | :--- | :--- | :--- |
| [Inbox Curation](skills/inbox-curation/README.md) | Brain (`/home/kiskaadee/Brain`) | Triage, classify, format, validate, and move raw drafts from `00-inbox/` | `active` |
| [Engineering Investigation](skills/engineering-investigation/README.md) | Global (`~/.gemini/config/skills/`) | Scientific investigation lifecycle, proportional checkpoints, and runtime verification | `active` |
| [Documentation Router](skills/documentation-router/README.md) | Global (`~/.gemini/config/skills/`) | Second-order knowledge evaluation, epistemic classification, anti-overlap invariants, and authoring modules | `active` |
| [Engineering Tutor](skills/engineering-tutor/README.md) | Global (`~/.gemini/config/skills/`) | Practice mode, Socratic graduated assistance, learner-as-primary-agent, and context-sensitive transfer verification | `active` |
| [Git Commit & History Hygiene](skills/git-commit/README.md) | Global (`~/.gemini/config/skills/`) | GitKeeper history construction, atomic commit slicing, 3-level CC messages, explicit authority precedence, and readiness gates | `active` |
| [Skill Builder](skills/skill-builder/README.md) | Global (`~/.gemini/config/skills/`) | Interactive skill design, proportional sizing, boundary review, and empirical refinement | `active` |
-198
View File
@@ -1,198 +0,0 @@
---
type: agent
status: active
name: homelab-core
target_workspace: ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-core
project: homelab
tags:
- homelab
- nixos
- infrastructure
- docker
- sops
- gitops
- guardrails
---
# Homelab Core Platform & Infrastructure Agent
## 1. Overview & Operational Scope
* **Target Workspace**: `ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-core` (`/home/kiskaadee/Homelab/Core` and worktrees)
* **Primary Role**: Maintains the host foundation, platform services, NixOS server modules, ingress security boundaries, and the `appctl` deployment engine.
* **Core Invariants & Boundaries**:
* **Core / Sites Separation**: Core owns host infrastructure, platform services, ingress proxying, and deployment execution; independent application workloads live in `~/Sites` with declarative `app.yaml` manifests.
* **GitOps Trust Boundary**: Webhook payloads cannot directly select filesystem paths or shell inputs. Webhook authentication is strictly validated.
* **Docker Isolation**: Only `socket-proxy` may mount the Docker socket in read-only mode for approved capabilities; workload containers never receive direct socket access.
* **SOPS Secrets Protection**: Secrets live under `/run/secrets/` via SOPS; never commit plaintext credentials or keys to Git.
---
## 2. Canonical Agent Specification
The following specification represents the active behavioral contract configured for `/home/kiskaadee/Homelab/Core/AGENTS.md`:
````markdown
# Homelab Core — Agent Guidelines
This repository defines the host foundation and Core platform for the
`roadtotech.me` homelab.
It contains NixOS configuration, shared infrastructure services, orchestration
tools, security policy, and operational configuration.
Independent application workloads live in `~/Sites` and are integrated with
Core through their application manifests and Docker Compose configuration.
---
## Architectural Invariants
### 1. Core / Sites Boundary
**Core owns:**
- NixOS host configuration and system services
- Shared platform and infrastructure services
- Ingress, identity, security boundaries, and host-level policy
- Orchestration and deployment mechanics
**`~/Sites` owns:**
- Independently deployed application workloads
- Application-specific Docker Compose configuration
- Application-specific `app.yaml` metadata and workload intent
Do not move workload-specific configuration into Core merely because Core
consumes or manages the workload.
Do not move Core-owned platform services into `~/Sites`.
When ownership is unclear, consult current architecture documentation before
changing the boundary.
### 2. Workload Manifests
Every `~/Sites` workload is self-describing through its `app.yaml`.
Do not hardcode workload-specific domains, ports, environment variables,
containers, or deployment configuration inside `scripts/appctl`,
`scripts/appctl_engine.py`, or GitOps logic.
`app.yaml` describes workload identity, integration metadata, and deployment
intent. Core owns deployment mechanics.
Never introduce arbitrary command execution, host filesystem paths,
privileged operations, or Docker control capabilities into workload manifests.
### 3. GitOps Trust Boundary
GitOps must remain a constrained deployment mechanism.
- Webhook authentication is mandatory.
- Repository identity is resolved through trusted Core logic.
- Filesystem paths must never be selected directly by webhook payloads.
- Deployment execution must remain closed and explicitly allowlisted.
- Repository-controlled configuration must never become arbitrary shell input.
- Deployment serialization and superseding behavior must be preserved.
Do not weaken these constraints for convenience.
### 4. Docker Isolation
- `socket-proxy` is the only Core Compose service that may mount
`/var/run/docker.sock`.
- The socket proxy must expose only explicitly approved read-only Docker API capabilities; state-changing and command-execution endpoints must remain disabled.
- Do not add `privileged: true` without an explicit architectural decision.
- Workload containers must not gain direct access to the Docker socket.
### 5. Secrets & Persistent State
Never commit plaintext secrets, credentials, password hashes, private keys,
certificates, runtime databases, or other generated/persistent state.
Secrets are managed through SOPS and projected to runtime paths under
`/run/secrets/`.
Do not move secrets into application manifests or source code.
### 6. Declarative Configuration vs Runtime State
Git contains declarative configuration and reproducible definitions.
Persistent runtime state belongs in the appropriate state directories or
Docker volumes and must remain excluded from version control.
Do not convert runtime state into committed configuration merely to simplify
development or recovery.
### 7. Core Service Ownership
Core Compose is the execution boundary for Core-owned platform services.
Workload-specific services belong in `~/Sites` unless an explicit architectural
decision establishes them as Core-owned.
Do not introduce application-specific deployment policy into the Core stack.
Do not make Core orchestration depend on implementation details of a workload
when the workload's declared contract can be used instead.
### 8. License
Preserve The Unlicense across Core and related Sites repositories.
---
## Verification & Architectural Integrity
When a requested change conflicts with an invariant, stop and resolve the
architectural conflict before implementing a workaround.
Before committing architectural or security-sensitive changes:
```bash
./scripts/test
nix flake check
```
Run additional validation appropriate to the change, such as:
```bash
docker compose config -q
```
Architectural invariants should be encoded as tests whenever practical.
Do not bypass failing invariant tests by weakening or removing the invariant
unless the architecture itself has intentionally changed.
---
## Documentation
Use the repository's current architecture and operational documentation as the
source of truth for ownership, protocols, and system behavior.
Record significant architectural decisions in the appropriate ADR or Brain
documentation rather than expanding this file into an architecture manual.
All documentation must remain GitHub-flavored Markdown compatible with Obsidian
and the live documentation viewer.
## Architectural & Engineering Knowledge Preservation
When engineering changes in Core yield durable architectural insights, security posture shifts, non-obvious root causes, or transferable operational heuristics, knowledge preservation is governed by the global skill **`documentation-router`**:
- Architectural commitments are recorded in ADRs (`03-records/decisions/`).
- Exploratory design inquiries and trade-offs are recorded in Discussions (`02-discussions/`).
- Empirical incident RCAs are recorded in Debug Records (`03-records/debug/`).
- Implementation roadmaps are recorded in Plans (`01-plans/`).
- Routine maintenance, configuration adjustments, and self-explanatory fixes require no external documentation.
- Preserve repository-local documentation (`docs/`, inline comments, commit rationale) as the primary source of truth for runtime behavior.
````
---
## 3. Related Resources & Context
* [Homelab Architecture & Landing Page](../../06-projects/homelab/README.md)
* [Homelab Operations & Troubleshooting Agent](homelab-operations.md)
* [Brain GitOps & Auto-Sync Deployment Pipeline Guide](../../04-learning/guides/homelab/brain-gitops-deployment-pipeline.md)
* [CI/CD Fundamentals & GitOps Knowledge Note](../../04-learning/knowledge/methods/cicd-fundamentals-and-gitops.md)
-205
View File
@@ -1,205 +0,0 @@
---
type: agent
status: active
name: homelab-operations
target_workspace: /home/kiskaadee/Homelab
project: homelab
tags:
- homelab
- operations
- nixos
- guardrails
- execution-harness
- interactive-troubleshooting
- gitops
- troubleshooting
---
# Homelab Operations & Troubleshooting Agent
## 1. Overview & Operational Scope
* **Target Workspace**: `/home/kiskaadee/Homelab` (Local multi-repo operations workstation)
* **Primary Role**: Autonomous diagnostic triage, read-only inspection, local declarative development, interactive troubleshooting execution harness, and structured incident recording.
* **Problem Space & Safety Constraints**:
* **The "Local First" Rule & Workspace Isolation**: Edits are strictly authored in the local workspace on dedicated branches (`investigate/<topic>` or `fix/<topic>`); never directly on the remote server host via interactive SSH sessions. Read-only diagnostics require no branch.
* **Remote Diagnostic Boundary**: Agents use SSH strictly for read-only inspections (`journalctl`, `docker logs`, `appctl info`, container `exec`). Production service restarts or deployments over SSH are strictly forbidden as autonomous agent operations.
* **Mandatory Execution Boundaries**: The agent must **never autonomously** create Git commits on `main`, push to any remote, merge branches, deploy to production, execute `nixos-rebuild`, or perform service restarts to roll out changes.
* **Global Skill Delegation**:
* Diagnostic triage and 6-part checkpoints defer to the global skill **`engineering-investigation`**.
* Atomic commit slicing, Conventional Commit derivation, and branch readiness defer to the global skill **`git-commit`**.
* Incident RCA capture and architectural decisions defer to the global skill **`documentation-router`** (`03-records/debug/`, `03-records/decisions/`).
---
## 2. Architectural Modeling & Design Rationale
### A. Dual-File Architecture: Authoritative Contract (`AGENTS.md`) vs. Client Adapter (`CLAUDE.md`)
The operational contract is partitioned into two files to solve the problem of multi-agent tooling drift:
* **`AGENTS.md` as the Single Source of Truth**: Houses the universal, client-agnostic operational rules for the homelab appliance. It captures system topology, network endpoints, server integrity guardrails, deployment handoffs, and CI/CD invariants.
* **`CLAUDE.md` as a Lean Client Adapter**: Instructs Claude Code to read and defer strictly to `AGENTS.md` without duplicating or redefining policy. It clarifies toolchain mechanisms (`.claude/rules/`, `.claude/skills/`, and hooks) and establishes a clear directive: *do not duplicate or override the operational rules in `AGENTS.md`*.
### B. Global Skill Synergy
Rather than defining custom, redundant execution loops in every repository, Homelab operations leverage the global workstation skills:
1. **`engineering-investigation`**: Enforces the scientific method (Observe $\to$ Hypothesize $\to$ Test $\to$ Narrow $\to$ RCA $\to$ Fix $\to$ Validate $\to$ Verify) and halts at structured 6-part checkpoints before crossing state boundaries.
2. **`git-commit`**: Discovers repository-local branch isolation rules, evaluates commit slice readiness, and derives evidence-based Conventional Commit messages while preventing direct commits to `main`.
3. **`documentation-router`**: Acts as a second-order gatekeeper to evaluate whether incident findings warrant a durable Debug Record (`03-records/debug/`) or an ADR, eliminating unnecessary documentation boilerplate for routine fixes.
---
## 3. Canonical Agent Specifications
### A. Authoritative Specification: `/home/kiskaadee/Homelab/AGENTS.md`
````markdown
# 🤖 Homelab Operations & Troubleshooting — Agent Guidelines
This repository (`/home/kiskaadee/Homelab`) is the local operational workstation for administering, developing, and troubleshooting the `roadtotech.me` homelab appliance.
---
## 1. System Topology & Environment Awareness
* **Local Workstation**: `laptop` (`/home/kiskaadee/Homelab`)
* `Core/`: NixOS host definition, SOPS secrets, shared platform services, and orchestration tooling (`appctl`).
* `Sites/`: Independent application workloads (`Sites/<app>/docker-compose.yml`, `Sites/<app>/app.yaml`).
* **Remote Appliance**: `server` (`roadtotech.me`)
* **Local LAN SSH**: `ssh server-local` (`192.168.1.36:22`)
* **Remote WAN SSH**: `ssh server-remote` (`roadtotech.me:2222`)
* **Gitea Git Remote**: `ssh://git@gitea.roadtotech.me:2223/kiskaadee/<repo>`
---
## 2. Remote Interaction & Server Integrity Guardrails
To protect the server appliance's integrity, agents **must strictly follow** these operational rules:
### A. The "Local First" Rule & Workspace Isolation
* **Never edit code or configuration files directly on the server over SSH** (e.g. `sed`, `cat <<EOF`, `nano`, `vim`).
* **Branching & State Isolation**:
* Diagnostic investigation that is read-only (logs, metrics, status queries) does not modify repository state and does not require a branch.
* **If repository state must change during investigation or remediation, work must be isolated from `main` on a dedicated local branch.**
* Use `investigate/<topic>` when troubleshooting requires repository modifications before the root cause or remediation is established (e.g., temporary instrumentation, reproduction configurations, exploratory patches).
* Use `fix/<topic>` or `feat/<topic>` for straightforward remediation or feature work.
* **Do not create branches for individual hypotheses**; hypotheses belong in the diagnostic journal, while Git branches represent isolated repository states.
* Once remediation is confirmed, ensure exploratory instrumentation is removed so only production-intended changes are proposed.
* Verify invariants and test locally before proposing commits or handoffs.
### B. What Agents CAN Do Over Remote SSH
Agents are encouraged to use SSH for **read-only diagnostics and non-destructive inspection**:
* **Logs & Metrics**:
* `ssh server-local "journalctl -u <service> -n 50 --no-pager"`
* `ssh server-local "docker logs --tail 50 <container>"`
* `ssh server-local "appctl logs <app>"`
* **Status & Inspections**:
* `ssh server-local "systemctl status <service> --no-pager"`
* `ssh server-local "appctl list --core"` / `appctl info <app>`
* `ssh server-local "docker ps -a"` / `docker inspect <container>`
* **Runtime Diagnostic Execution**:
* `ssh server-local "docker exec <container> <cmd>"` (e.g., `nslookup`, `curl`, `getent`)
### C. Mandatory Execution Boundaries (What Agents MUST NOT Do Autonomously)
To protect operational safety and preserve user ownership:
* **Do not create commits, push to any remote, or merge branches.** Propose atomic commits with descriptions and validation proof; do not execute `git commit`, `git push`, or `git merge`.
* **Do not deploy changes to production.** The user owns all production transitions. The agent provides deployment runbooks and rollback procedures, but never executes deployment commands.
* **Do not execute `nixos-rebuild` autonomously.** System-level NixOS rebuilds can disrupt network, DNS, or boot configs. When Core/NixOS changes are validated, provide the deployment runbook for the user to execute:
```bash
sudo nixos-rebuild switch --flake ~/Core#server
```
* **Do not perform production service restarts** (e.g. `appctl restart <app>`, `docker restart <container>`) as part of deploying changes.
* **Do not run destructive Docker commands** (e.g. `docker system prune -a --volumes` or manual database file removals) without explicit confirmation.
* **Do not modify `/etc/` or host system files** over SSH outside of NixOS declarative modules.
---
## 3. Operational Lifecycles & Global Skill Integration
Operational troubleshooting, commit packaging, and knowledge preservation defer strictly to the workstation's global skills:
### A. Investigation & Checkpoints (`engineering-investigation`)
* When diagnosing or troubleshooting issues on the host or application stacks, follow the scientific progression governed by **`engineering-investigation`** (Observe $\to$ Hypothesize $\to$ Test $\to$ Narrow $\to$ RCA $\to$ Fix $\to$ Validate $\to$ Verify).
* Pause at meaningful transitions (state changes, hypothesis confirmation/elimination, atomic commit boundaries, deployment handoffs) using the 6-part checkpoint protocol (Current State, Reasoning, Changes, Validation, Next Action, Recovery).
### B. Git Commits & Branch Integration (`git-commit`)
* Commit packaging, atomic slicing, and branch safety are governed by **`git-commit`**.
* Edits must be isolated on dedicated branches (`investigate/<topic>` or `fix/<topic>`); direct commits to `main` are strictly prohibited.
* The agent proposes atomic commit slices with evidence-based Conventional Commit messages; autonomous commits on `main` are blocked.
### C. Architectural & Incident Knowledge Preservation (`documentation-router`)
* Knowledge preservation is governed by **`documentation-router`**.
* Only non-obvious root causes, false system assumptions, or architectural discoveries warrant durable capture (`03-records/debug/`, `03-records/decisions/`, or `02-discussions/` in the Brain).
* Routine maintenance, configuration adjustments, and self-explanatory fixes require no external documentation.
---
## 4. Production Deployment & Handoff Policy
The user owns the production transition. When local validation is complete:
1. Explicitly identify that the change is ready for deployment.
2. Provide a structured **Deployment Handoff**:
* **Exact User Action Required**: Provide the exact deployment command(s) appropriate to the affected workload:
* *Core / NixOS host*: `sudo nixos-rebuild switch --flake ~/Core#server`
* *Sites workloads*: target-specific service commands (e.g. `ssh server-local 'cd ~/Sites/<app> && git fetch && git pull origin <branch> && appctl restart <app>'` or stack-specific compose invocations).
* **Expected Production Changes**: State changes, service reloads, or container recreations that should occur.
* **Expected Post-Deployment Evidence**: Log lines, socket status, or HTTP response codes indicating success.
* **Verification Commands**: Non-destructive diagnostic commands the agent or user will run post-deployment to verify recovery.
* **Rollback Procedure**: Step-by-step instructions to restore previous state if verification fails.
3. Do not execute the deployment. Wait for user execution before proceeding to post-deployment verification.
This policy applies equally to Core/NixOS system changes and Sites application changes.
---
## 5. CI/CD & Gitea Actions (`act_runner`) Invariants
* **Pre-Baked Images over In-Job Installers**: Always declare `container: { image: <image> }` (e.g., `nixery.dev/shell/coreutils/git/nix/nodejs:latest`, `python:3.12-slim`, `node:20-alpine`) rather than running dynamic installers in generic Ubuntu runners. Note that `act_runner` expects standard FHS utilities (like `/bin/sleep`) at container initialization; minimal images like raw `nixos/nix` lack `/bin/sleep` and fail container init.
* **Git Safe Directory Invariant**: When job containers mount the workspace with root or differing UIDs, always configure Git safe directory before invoking Git or Flake tools:
```yaml
- name: Configure Git Safe Directory
run: git config --global --add safe.directory "$GITHUB_WORKSPACE"
```
* **Avoid GitHub API Assumptions**: Avoid third-party marketplace actions that rely on `${{ github.server_url }}` (which resolves to `https://gitea.roadtotech.me` instead of `github.com`). Use direct container runtimes and standard shell scripts.
````
### B. Client Adapter Specification: `/home/kiskaadee/Homelab/CLAUDE.md`
````markdown
# Homelab Agent Instructions
This repository is operated under the project rules defined in `AGENTS.md`.
## Operating Contract
Before investigating, modifying, or troubleshooting the Homelab:
1. Read and follow `AGENTS.md`.
2. Treat `AGENTS.md` as the authoritative operational contract.
3. Preserve the Local First rule and workspace isolation requirements.
4. Follow the interactive troubleshooting and execution harness defined there.
5. Keep the user in control of commits, branch integration, and production deployment.
6. Do not create commits, push, merge, deploy, or execute `nixos-rebuild` autonomously.
7. Use meaningful checkpoints rather than stopping after every individual command.
8. Preserve the distinction between diagnostic reasoning, repository state, and the durable incident journal.
## Scope
Do not duplicate or override the operational rules in `AGENTS.md`.
For Claude-specific behavior, prefer Claude Code mechanisms such as:
- `.claude/rules/` for scoped repository instructions;
- `.claude/skills/` for reusable workflows;
- hooks for deterministic enforcement where appropriate.
When instructions appear to conflict, stop and surface the conflict rather than silently choosing the more permissive interpretation.
````
---
## 4. Related Resources & Context
* [Homelab Architecture & Topology Overview](../../06-projects/homelab/README.md)
* [Homelab Core Platform Agent](homelab-core.md)
* [Brain GitOps & Auto-Sync Deployment Pipeline Guide](../../04-learning/guides/homelab/brain-gitops-deployment-pipeline.md)
* [Scientific Incident Investigation & Epistemic Journaling Protocol](../../04-learning/knowledge/methods/incident-investigation-and-journaling.md)
* [Webhook HMAC Signature Mismatch RCA](../../03-records/debug/2026-09-21-gitops-webhook-payload-signature-mismatch.md)
-107
View File
@@ -1,107 +0,0 @@
---
type: agent
status: active
name: magnetflix
target_workspace: git@github.com:kiskaadee/MagNetFlix.git
project: magnetflix
tags:
- magnetflix
- python
- fastapi
- grpc
- protobuf
- sqlite
- uv
---
# MagNetFlix Media Pipeline Agent
## 1. Overview & Operational Scope
* **Target Workspace**: `git@github.com:kiskaadee/MagNetFlix.git` (`/home/kiskaadee/Projects/active/MagNetFlix`)
* **Primary Role**: Develops and maintains the automated media acquisition backend, orchestrating FastAPI (BFF), gRPC worker services, Protobuf contracts, SQLite WAL persistence, Transmission integration, and Traefik/Authelia SSO.
* **Core Invariants & Safety Constraints**:
* **Working Tree Authority**: Inspect `git status` first; never run destructive git operations (`reset --hard`, `clean -fd`, `stash`) or overwrite uncommitted human work.
* **Architecture Authority**: Respect `docs/architecture.md` and `docs/deployment.md`; implementation autonomy does not permit arbitrary architectural changes.
* **Persistence Invariant**: SQLite operates strictly in WAL mode (`PRAGMA journal_mode=WAL`) via `aiosqlite` and Alembic migrations on local mounts.
* **Pipeline Whitelist Sanitization**: File acquisition enforces strict video/subtitle whitelist filtering and isolates downloads in staging directories before relocation.
---
## 2. Canonical Agent Specification
The following specification represents the active behavioral contract configured for `/home/kiskaadee/Projects/active/MagNetFlix/AGENTS.md`:
````markdown
# Project Guidelines & Safety Rules for AI Agents
## 1. Mission & Authority
**MagNetFlix** is a self-hosted, automated media acquisition pipeline built around **FastAPI (BFF) + gRPC (Worker) + UV Workspaces + SQLite3 WAL + Transmission + Traefik/Authelia SSO**.
- **Architecture Documentation** (`docs/architecture.md`), **Roadmap** (`docs/roadmap.md`), and **Deployment Specifications** (`docs/deployment.md`) define the authoritative design.
- **Implementation autonomy ≠ Architectural autonomy.** Do not replace technologies, dependencies, or storage strategies without explicit approval.
---
## 2. Working Tree Authority & Safety (MANDATORY)
The working tree represents the user's active work.
1. **Inspect First:** Run `git status` and list/read target directories/files before creating or modifying anything.
2. **Check for Existing Files:** Before creating any new file, verify whether the file (or a user equivalent) already exists on disk. Never overwrite or re-scaffold user work.
3. **Never Overwrite Blindly:** Use available file-reading tools. Preserve user comments, links, and conventions. Prefer surgical edits over wholesale overwrites.
4. **No Destructive Git Commands:** Never run `reset --hard`, `clean -fd`, `restore`, `checkout`, `stash`, `rebase`, or `amend` without explicit permission.
5. **Final Diff Verification:** Before completing work, run `git status` and `git diff` to verify that no unrelated user changes were modified or discarded. Distinguish user changes from agent changes in completion reports.
---
## 3. Architecture & Component Contracts (Progressive Triggers)
- **Mandatory Architecture Review:** Always read `docs/architecture.md` before making any changes affecting API routes, gRPC definitions, database models, directory layouts, or component boundaries.
- **Read `docs/deployment.md`** before altering networking, Traefik routing, Authelia SSO middleware, or Docker volume bindings.
- **Stop and Ask:** If an implementation conflicts with documentation or an ambiguous requirement materially affects architecture, stop and ask the user rather than guessing or silently changing the design.
- **No Speculative Robustness:** Do not add unrequested fallback layers, complex generic abstractions, or future-proofing bloat.
---
## 4. Operational Invariants
### 4.1 Persistence & Audit (SQLite3 WAL)
- Database must operate in **WAL mode** (`PRAGMA journal_mode=WAL;`) with foreign keys enabled (`PRAGMA foreign_keys=ON;`) and `PRAGMA synchronous=NORMAL;`.
- Use SQLAlchemy's async interface via `aiosqlite`.
- Do not create ad-hoc connections outside the application session/engine lifecycle.
- Store database strictly on local volume mounts (`/data/magnetflix.sqlite3`). Never place SQLite on network shares (NFS/SMB).
- All schema changes must be managed through Alembic migrations.
### 4.2 Tooling, Dependencies & Protobuf
- **Python Workspaces:** Use `uv` at the workspace root. Never manually edit `uv.lock` (run `uv lock`). Never use raw `pip`.
- **Protobuf & Code Generation:**
- Define proto contracts strictly in `proto/magnetflix/v1/`.
- Regenerate stubs using `uv run buf generate` (or `make generate`).
- Every proto service, RPC, message, and field **must** include descriptive `//` comments.
- **Code Quality:** All code must pass `uv run ruff check .` and `uv run pyright`.
### 4.3 Pipeline Safety & File-System Invariants
- **Isolated Staging:** Downloads must be confined to an isolated temporary scratch path (e.g., `/data/staging/<job_id>`).
- **File Whitelist Sanitization:**
- Whitelist: Video (`.mkv`, `.mp4`, `.avi`, `.webm`) and Subtitles (`.srt`, `.vtt`, `.sub`, `.ass`).
- Quarantine / Reject: Executables, binaries, scripts, or archives (`.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.lnk`, `.iso`, `.zip`, `.rar`).
- Clean up staging directories immediately after successful file relocation or upon terminal failure.
---
## 5. Verification & Completion
Every task must be verified before declaring completion:
1. Run linters, formatters, and type checks: `uv run ruff check .` and `uv run pyright`.
2. Run test suites when tests are present: `uv run pytest`.
3. Verify protobuf stubs compile cleanly when `.proto` files are touched: `uv run buf generate`.
4. Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks.
````
---
## 3. Related Resources & Context
* [MagNetFlix Project Landing Page](../../06-projects/magnetflix/README.md)
* [FastAPI & Modern Python Technologies Guide](../../04-learning/knowledge/technologies/python/pydantic.md)
* [SQL & Relational Storage Methods](../../04-learning/knowledge/methods/sql.md)
-96
View File
@@ -1,96 +0,0 @@
---
type: agent
status: active
name: nekoweb
target_workspace: git@github.com:kiskaadee/nekoweb.git
project: nekoweb
tags:
- nekoweb
- python
- fastapi
- react
- tanstack
- sqlite
- uv
- pnpm
---
# NekoWeb Manga Platform Agent
## 1. Overview & Operational Scope
* **Target Workspace**: `git@github.com:kiskaadee/nekoweb.git` (`/home/kiskaadee/Projects/active/nekoweb`)
* **Primary Role**: Develops and maintains the full-stack self-hosted manga web platform (FastAPI backend, UV package manager, SQLite WAL persistence, React/TanStack frontend, and Headless HakuNeko daemon).
* **Core Invariants & Safety Constraints**:
* **Working Tree Authority**: Always run `git status` and inspect files first; destructive git operations (`reset --hard`, `clean -fd`, `stash`) are strictly prohibited.
* **Architectural Invariants**: Respect accepted ADRs (`docs/adr/`) and system architecture (`docs/ARCHITECTURE.md`) before changing API routes, WebSocket schemas, or persistence layers.
* **Tooling Environment**: Root `.envrc` evaluates Nix flakes; `backend/.envrc` chains via `source_up` and activates `backend/.venv`; Python dependencies use `uv` while frontend uses `pnpm` under Node 22.
---
## 2. Canonical Agent Specification
The following specification represents the active behavioral contract configured for `/home/kiskaadee/Projects/active/nekoweb/AGENTS.md`:
````markdown
# Project Guidelines & Safety Rules for AI Agents
## 1. Mission & Authority
NekoWeb is a self-hosted web manga platform currently built around **FastAPI + UV + SQLite3 WAL + React/TanStack + Headless HakuNeko Daemon**.
- **Accepted ADRs** (`docs/adr/`) and **Architecture Documentation** (`docs/ARCHITECTURE.md`) define the authoritative design.
- **Implementation autonomy ≠ Architectural autonomy.** Do not replace technologies, dependencies, or storage strategies without explicit approval.
---
## 2. Working Tree Authority & Safety (MANDATORY)
The working tree represents the user's active work.
1. **Inspect First:** Run `git status` and read target files before modifying anything.
2. **Never Overwrite Blindly:** Use available file-reading tools. Preserve user comments, links, and conventions. Prefer surgical edits over wholesale overwrites.
3. **No Destructive Git Commands:** Never run `reset --hard`, `clean -fd`, `restore`, `checkout`, `stash`, `rebase`, or `amend` without explicit permission.
4. **Final Diff Verification:** Before completing work, run `git status` and `git diff` to verify that no unrelated user changes were modified or discarded. Distinguish user changes from agent changes in completion reports.
---
## 3. Architecture & Component Contracts (Progressive Triggers)
- **Read `docs/ARCHITECTURE.md`** before modifying API contracts, changing WebSocket event schemas, or crossing Backend/Frontend/Daemon boundaries.
- **Read `docs/adr/`** before altering persistence, networking, deployment, or dependencies.
- **Stop and Ask:** If an implementation conflicts with an accepted ADR or an ambiguous requirement materially affects architecture, stop and ask the user rather than guessing or silently changing the design.
- **No Speculative Robustness:** Do not add unrequested fallback layers, complex generic abstractions, or future-proofing bloat.
---
## 4. Operational Invariants
### 4.1 Persistence (SQLite3 WAL)
- Database must operate in **WAL mode** (`PRAGMA journal_mode=WAL;`) with foreign keys enabled (`PRAGMA foreign_keys=ON;`).
- Use SQLAlchemy's async interface via `aiosqlite`.
- Do not create ad-hoc connections outside the application session/engine lifecycle.
- Store database strictly on local volume mounts (`/app/data/nekoweb.db`). Never place SQLite on network shares (NFS/SMB).
- All schema changes must be managed through Alembic migrations.
### 4.2 Tooling & Dependencies
- **Nix & Direnv:** Root `.envrc` evaluates `use flake`. `backend/.envrc` chains via `source_up` and activates `backend/.venv`. Never move the venv to the repository root.
- **Python (Backend):** Use `uv`. Never manually edit `uv.lock` (run `uv lock`). Never use raw `pip`.
- **JavaScript (Frontend/Daemon):** Use `pnpm` and respect Node 22 from the Nix devShell.
- **Generated / External Code:** Treat copied code as untrusted until verified against project dependency versions and conventions.
---
## 5. Verification & Completion
Every task must be verified before declaring completion:
- Run appropriate linters, type checks (`tsc`, `pyright`), or test suites (`uv run pytest`).
- Verify database migrations and schema initialization for persistence changes.
- Report: (1) What changed, (2) Files modified/created, (3) Verification performed, (4) Unverified areas/risks.
````
---
## 3. Related Resources & Context
* [NekoWeb Project Landing Page](../../06-projects/nekoweb/README.md)
* [Testing & Quality Assurance Guide](../../04-learning/knowledge/methods/testing.md)
* [SQL & Relational Persistence Methods](../../04-learning/knowledge/methods/sql.md)
-221
View File
@@ -1,221 +0,0 @@
---
type: agent
status: active
name: nixos-workstation
target_workspace: ssh://git@gitea.roadtotech.me:2223/kiskaadee/nixos-config
project: nixos
tags:
- nixos
- home-manager
- workstation
- guardrails
- sops
---
# NixOS Mobile Workstation Configuration Agent
## 1. Overview & Operational Scope
* **Target Workspace**: `ssh://git@gitea.roadtotech.me:2223/kiskaadee/nixos-config` (`/home/kiskaadee/Config`)
* **Primary Role**: Maintains the declarative NixOS and Home Manager configuration for the `laptop` mobile workstation.
* **The Golden Rule & Security Barrier**:
* **Build, Never Switch**: Agents are strictly forbidden from running `sudo nixos-rebuild switch`, `boot`, or `test`. The agent may modify declarations and verify via dry builds (`nix build ... --no-link`), but live-system mutations remain strictly in human hands.
* **Preserve Pre-Existing Work**: Always check `git status` first and never discard, overwrite, or stash uncommitted human changes.
* **Risk Classification Framework**: Changes are categorized into Low, Medium, High, and Prohibited tiers with clear escalation triggers.
---
## 2. Canonical Agent Specification
The following specification represents the active behavioral contract configured for `/home/kiskaadee/Config/AGENTS.md`:
````markdown
# AGENTS.md
## Mission & Purpose
This repository manages the declarative NixOS and Home Manager configuration for the `laptop` mobile workstation host.
AI agents working in this repository must maintain architectural integrity, avoid configuration sprawl, respect pre-existing work, and adhere strictly to the invariants defined in `architecture.md`.
---
## The Golden Rule: Build, Never Switch
> [!CAUTION]
> **Agents are strictly forbidden from executing `sudo nixos-rebuild switch`, `boot`, `test`, or mutating the running host system.**
> An agent may modify the *declaration* of the system and verify compilation. It must *never* autonomously alter the running state of the host machine.
### Security Boundary Model
```text
Repository
│
├── Agent may READ
├── Agent may MODIFY
└── Agent may VALIDATE
│
▼
Nix Derivation (Dry Build)
│
═══════╪══════════════════════════════════════ [STRICT BARRIER]
▼
Running Host System
(Mutations strictly prohibited without explicit user instruction)
```
### Permitted Verification Commands
```bash
# Validate flake metadata, inputs, and derivations
nix flake check
# Build laptop host dryly (evaluates configuration without switching)
nix build .#nixosConfigurations.laptop.config.system.build.toplevel --no-link
```
### Prohibited Live-System Commands (Unless Explicitly Requested)
- `nixos-rebuild switch` / `boot` / `test`
- `systemctl [start|stop|restart|reload]`
- `udevadm *`
- `mount` / `umount`
- `reboot` / `shutdown`
- `nix-store --delete` or manual modifications to `/nix/var/nix/profiles/`
---
## Operating Rules & Constraints
### 1. Request Interpretation
- **Narrow Interpretation**: Interpret the user's request as narrowly as reasonably possible.
- **No Inferred Authorization**: Do not infer permission for unrelated cleanup, dependency upgrades, directory reorganization, or live-system mutations.
### 2. Preserve Pre-Existing Uncommitted Work
- **Inspect First**: Before making any edits, check `git status` to identify pre-existing uncommitted changes.
- **Never Overwrite**: Never overwrite, discard, reset, stash (`git checkout .`, `git reset`, `git stash`), or manipulate user changes that existed prior to your task.
- **Distinguish Attribution**: Clearly separate pre-existing modifications from agent modifications in the completion report.
### 3. Do Not Expand Scope & Minimal Change Principle
- **No Spontaneous Refactoring**: An agent must not turn a feature request into a refactoring project.
- **Report Architectural Issues Separately**: If a requested change exposes an architectural smell or problem, report it to the user rather than silently attempting to refactor surrounding code (unless strictly required for correctness).
- **Smallest Viable Change**: Make the minimal change that satisfies the request. Do not introduce single-use abstractions, single-option wrapper modules, or arbitrary file reorganizations.
- **Capture Out-of-Scope Ideas in Second Brain**: When the user mentions a new idea, feature request, or architectural concept unrelated to the immediate active task, record a note in `/home/kiskaadee/Brain/` (or suggest logging it) so valuable insights are preserved without disrupting current execution scope.
### 4. Package Placement Rules
- **Developer Tools, Compilers, LSPs**: Place in `home/dev.nix`.
- **Graphical Applications & Desktop Tools**: Place in `home/desktop.nix`.
- **Terminal Utilities & Shell Integration**: Place in `home/shell.nix`.
- **System-Wide Daemons & Hardware Support**: Place in `system/core.nix` or `system/hardware.nix` *only* if required for root maintenance, core networking, or systemd daemons.
### 5. Homelab Infrastructure Decoupling
- Production homelab services, Traefik edge proxying, Docker container deployments, and DDNS automation live exclusively in the `Core` repository (`~/Projects/active/homelab/Core`).
- Never import or re-introduce server daemon definitions into this workstation repository.
### 6. Hardware Configurations
- `system/hardware-configuration.nix` is generated by `nixos-generate-config`. Do not manually restructure, clean up, or refactor it. Hardware additions (e.g., kernel parameters, disk mounts) require explicit justification.
### 7. Secrets & Key Safety (SOPS)
- **Never write or commit plaintext secrets** into `.nix`, `.yaml`, or temporary files.
- **Never decrypt secrets into tracked or persistent working-tree files**.
- **Never add, modify, or rotate SOPS/age keys** unless explicitly commanded by the user.
- **Never expose decrypted secret material** through `git diff`, logs, or terminal outputs.
- Reference secrets only via `/run/secrets/<name>` or `config.sops.secrets.<name>.path`.
### 8. Flake Dependencies
- Do not introduce a new flake input if standard `nixpkgs` provides the required package or module.
- Do not update unrelated flake inputs or regenerate `flake.lock` for feature changes.
- Pin `inputs.nixpkgs.follows = "nixpkgs"` on new flake inputs whenever applicable.
---
## Risk Classification Framework
| Tier | Category | Examples | Required Action & Workflow |
| :--- | :--- | :--- | :--- |
| **LOW** | User Configuration | User packages in `home/dev.nix`, shell aliases in `home/shell.nix`, Neovim lua config, docs. | **Autonomous**: Agent plans, edits, and validates via `nix flake check` + laptop build. |
| **MEDIUM** | System & Desktop Stack | `system/core.nix`, `system/desktop.nix`, greetd/DMS, firewall rules, user groups, new flake inputs. | **Autonomous**: Agent plans, edits, and validates via `nix flake check` + laptop build. |
| **HIGH** | Core Hardware & Boot | Bootloader, filesystem mounts, SOPS keys setup, kernel module changes. | **Stop & Wait**: Agent must present the plan and **wait for user approval before editing**. |
| **PROHIBITED** | Live System Mutators | `nixos-rebuild switch`, destructive disk ops, editing `/etc` outside Nix, rotating age keys, plaintext secrets. | **Blocked**: Cannot execute unless explicitly commanded by the user in the current prompt. |
---
## Change Protocol
Every modification by an agent must follow this lifecycle:
```text
REQUEST
│
▼
1. UNDERSTAND
├── Identify affected components in system/ or home/
├── Check `git status` to identify pre-existing uncommitted work
└── Read architectural boundaries in architecture.md
│
▼
2. PLAN
├── Formulate minimal viable change
├── Verify no architectural invariants are violated
└── IF HIGH RISK: Stop and present plan for user approval before proceeding
│
▼
3. EDIT
├── Make targeted modifications only
└── Respect package and secret placement boundaries
│
▼
4. VALIDATE
├── Run `nix flake check`
└── Build laptop host (`--no-link`): `nix build .#nixosConfigurations.laptop.config.system.build.toplevel --no-link`
│
▼
5. REVIEW
├── Inspect `git diff` for unintended changes or exposed secrets
└── Ensure no pre-existing user work was disturbed
│
▼
6. REPORT
└── Provide completion report with pre-existing work status and build outputs
```
---
## Validation Matrix
| Modified Path | Affected Consumer | Required Build Validation |
| :--- | :--- | :--- |
| `system/*` | `laptop` | `nix flake check`<br>`nix build .#nixosConfigurations.laptop.config.system.build.toplevel --no-link` |
| `home/*` | `laptop` | `nix flake check`<br>`nix build .#nixosConfigurations.laptop.config.system.build.toplevel --no-link` |
| `flake.nix` / `flake.lock` | `laptop` | `nix flake check`<br>`nix build .#nixosConfigurations.laptop.config.system.build.toplevel --no-link` |
---
## Documentation Hygiene
Maintain clear ownership of documentation:
- **`README.md`**: High-level repository overview and quick start.
- **`architecture.md`**: Structural topology, layer boundaries, and architectural invariants.
- **`AGENTS.md`**: Agent constitution, change policies, risk matrix, and validation rules.
- **`docs/*.md`**: Step-by-step procedural guides for humans (maintenance, secrets, Antigravity).
*Rule: Do not duplicate architectural descriptions into procedural docs or README.*
---
## Completion Report Format
When reporting back after a task, summarize:
1. **Pre-Existing Changes Detected**: [Yes / No (with details if preserved)]
2. **Files Modified by Agent**: List of exact files changed.
3. **Architectural Assessment**: Verification that invariants were respected and boundaries maintained.
4. **Validation Executed**: Output of `nix flake check` and `nix build ... --no-link`.
5. **Pending Manual Actions**: Any user-required steps (e.g. running `sudo nixos-rebuild switch` or committing changes).
````
---
## 3. Related Resources & Context
* [NixOS Fleet & Workstation Project Overview](../../06-projects/nixos/README.md)
* [NixOS Standalone Workstation Walkthrough](../../04-learning/guides/nixos/standalone-workstation-walkthrough.md)
* [Server Decoupling & Standalone Workstation Plan](../../01-plans/nixos/server-decoupling-and-standalone-workstation.md)
* [Homelab Operations Agent](homelab-operations.md)
-46
View File
@@ -1,46 +0,0 @@
---
type: agent
status: active
name: second-brain
target_workspace: ssh://git@gitea.roadtotech.me:2223/kiskaadee/second-brain
project: brain
tags:
- knowledge-graph
- second-brain
- documentation
- taxonomy
- curation
- validator
---
# Second Brain Knowledge Graph & Curation Agent
## 1. Overview & Operational Scope
* **Target Workspace**: `ssh://git@gitea.roadtotech.me:2223/kiskaadee/second-brain` (`/home/kiskaadee/Brain`)
* **Primary Role**: Maintains the personal knowledge graph, curates unprocessed drafts from `00-inbox/` into canonical lifecycle directories (`01-plans/`, `02-discussions/`, `03-records/`, `04-learning/`, `05-agents/`, `06-projects/`), enforces strict frontmatter and link schemas, and executes automated validation.
* **Core Invariants & Taxonomy**:
* **Seven Lifecycle Directories**: `00-inbox/` (capture), `01-plans/` (intent), `02-discussions/` (exploration), `03-records/` (historical memory), `04-learning/` (understanding, guides, practice), `05-agents/` (machine context), and `06-projects/` (system hubs).
* **Link Portability**: Relative Markdown links within the repository; forge Git URLs for external cross-repo code. Never use machine-specific absolute file URIs (`file:///`).
* **Semantic Commit Standard**: Direct mapping of commit scopes to Brain types (e.g. `knowledge(topic): ...`, `journal(proj): ...`, `agent(name): ...`).
* **Integrity Validation**: Must pass `python scripts/validate-brain.py` before every commit.
---
## 2. Canonical Agent Specification
The following specification represents the active behavioral contract configured for `/home/kiskaadee/Brain/AGENTS.md`:
````markdown
[Consult the live, root-level AGENTS.md for the authoritative version-controlled repository rules.]
````
For the full detailed rules, see [Root AGENTS.md](../../AGENTS.md).
---
## 3. Related Resources & Context
* [Second Brain Root Index](../../README.md)
* [Second Brain Governance & Agent Guide](../../AGENTS.md)
* [Scientific Incident Investigation & Epistemic Journaling](../../04-learning/knowledge/methods/incident-investigation-and-journaling.md)
-45
View File
@@ -1,45 +0,0 @@
---
type: agent
status: active
name: skill-collection-index
kind: skill
project: brain
tags:
- skills
- agent-engineering
- system-architecture
---
# Global Skill Collection
> **The authoritative source of truth for all agent skills has been consolidated into the standalone [`skills`](https://github.com/kiskaadee/skills) repository.**
---
## Repository & Installation
Skills are maintained, versioned, and tested in [`kiskaadee/skills`](https://github.com/kiskaadee/skills).
They are installed into runtime agent configurations via the repository's `install.sh` script:
```bash
cd ~/Projects/active/skills
./install.sh
```
---
## Active Skills Index
### Portable Skills
- **[`practice`](https://github.com/kiskaadee/skills/blob/main/skills/practice/SKILL.md)**: Socratic tutoring mode where the learner writes all code and drives analysis.
- **[`diagnose`](https://github.com/kiskaadee/skills/blob/main/skills/diagnose/SKILL.md)**: Empirical troubleshooting following the scientific method and 6-part checkpoints.
- **[`git-commit`](https://github.com/kiskaadee/skills/blob/main/skills/git-commit/SKILL.md)**: History hygiene, atomic slicing, and Conventional Commit construction.
- **[`document`](https://github.com/kiskaadee/skills/blob/main/skills/document/SKILL.md)**: Second-order knowledge classifier for Discussions, ADRs, Plans, Debug Records, and Knowledge Articles.
- **[`build-skill`](https://github.com/kiskaadee/skills/blob/main/skills/build-skill/SKILL.md)**: Interactive skill design, sizing, authoring, and empirical dogfooding.
### Vault Extensions
- **[`draft-curation`](https://github.com/kiskaadee/skills/blob/main/extensions/draft-curation/SKILL.md)**: Triages, classifies, formats, and validates incoming drafts from `00-inbox/` into canonical lifecycle directories.
- **[`commit-logger`](https://github.com/kiskaadee/skills/blob/main/extensions/commit-logger/SKILL.md)**: Immutable event capture script logging Git commits into `00-inbox/commit-log.csv` (planned consumer of future `journal-builder`).
-50
View File
@@ -1,50 +0,0 @@
---
type: project
status: active
tags:
- amc-solutions
- seo
- ux
- digital-presence
---
# AMC Solutions — Digital Discovery
## Overview
Research into AMC Solutions Colombia's digital presence to establish the current state of its website, user experience, search visibility, and external presence. The work gathers evidence to inform a future proposal for redesign, SEO, and customer acquisition; it does not include implementing those initiatives.
## Research question
What changes does AMC Solutions Colombia's digital presence need to serve as a channel for customer acquisition and market positioning?
## Scope
- Inventory of website content, navigation, and calls to action.
- Inspection of the technical implementation, HTTP responses, technologies, and crawlability.
- Analysis of information architecture, user experience, and contact points.
- Review of metadata, structured data, and search engine readiness.
- Research into external presence on Google Business Profile, LinkedIn, and industry directories.
CMS selection, redesign, final copywriting, and advertising budget decisions are outside the current scope.
## Research organization
The repository separates context and unknowns, empirical evidence, analysis, deliverables, and inspection tools. Observations should link to their supporting evidence and distinguish facts from interpretations and hypotheses.
```text
context/ Background, hypotheses, unknowns, and questions for AMC
evidence/ Website, technical, and external presence records
analysis/ Interpretation of UX, SEO, search, and positioning
output/ Reports and materials prepared for AMC
tools/ Reproducible technical inspection scripts
```
## Repository and website
- [AMC Solutions — Digital Discovery repository](https://gitea.roadtotech.me/kiskaadee/amc-solutions-seo)
- [AMC Solutions Colombia website](https://www.amcsolutionscolombia.com/)
## Status
Research is ongoing. Recommendations depend on the evidence collected and questions still to be validated with AMC.
-101
View File
@@ -1,101 +0,0 @@
---
type: project
status: active
tags:
- armonia-del-ser
- fastapi
- python
- htmx
- tailwind
- vite
- cloud-run
- cloudflare-pages
- libsql
- turso
---
# 🌿 Armonía del Ser — Holistic Healing Center & Self-Service Booking Platform
**Armonía del Ser** (*Centro Holístico*, founded in 2007 by Jasmin Isaza in Tulancingo, Hidalgo, Mexico) is an alternative medicine and integrative health sanctuary offering psychological care, ancestral ceremonies (cacao circles, temazcales), quartz singing bowl sound meditations, Bach flower remedies, herbal medicine, and community workshops.
The digital ecosystem is a decoupled multi-repository architecture designed to transition 20 years of word-of-mouth client scheduling and manual WhatsApp administration into an automated self-service reservation and payment-tracking platform operating under a \$0 free-tier cloud budget.
---
## 🏛️ System Topology & Architecture
The ecosystem splits operational concerns into independent, decoupled repositories:
* **Client & Self-Service Portal (`armonia-landing`)**:
- Public-facing discovery catalog, workshop schedules, and self-service reservation interface.
- Bundled with Vite+, Tailwind CSS, and HTMX for responsive zero-framework client interactions.
- Hosted on **Cloudflare Pages** (\$0 free tier).
* **Operator Control Surface (`armonia-dashboard`)**:
- Mobile-first administration surface for Jasmin and her remote assistant.
- Features a dedicated **48-hour follow-up queue**, payment verification modal, manual delayed-payment exception authorizer, attendee rosters, and multi-session package tracking.
- Protected by Google OAuth2 and hosted on **Cloudflare Pages** (\$0 free tier).
* **Core Operational API & Domain Engine (`armonia-api`)**:
- Asynchronous **FastAPI** service running on Python 3.13, packaged with `uv` and containerized via Docker.
- Implements the **orthogonal booking and payment state machine**, mandatory session buffer collision detection, package redemption logic, and Google Calendar sync coordination.
- Deployed to **Google Cloud Run** (\$0 free tier).
* **Persistence & Identity Layer**:
- **Turso libSQL**: Embedded replica SQLite/libSQL database acting as the operational Single Source of Truth (SSOT).
- **Google Calendar API**: External calendar adapter coordinating therapist availability, appointment sync health, and room bookings.
- **Google OAuth2 + Turso Allowlist**: Role-based access control checking authenticated operator emails against the database allowlist.
```mermaid
flowchart TD
subgraph Clients ["Public Clients & Visitors"]
CV["Client Browser"] -->|Public booking requests| AL["armonia-landing<br/>(Cloudflare Pages)"]
end
subgraph Operators ["Therapist & Assistant"]
OP["Mobile / Desktop Browser"] -->|Google OAuth SSO| DASH["armonia-dashboard<br/>(Cloudflare Pages)"]
end
subgraph CoreEngine ["Backend & Domain Services"]
AL -->|REST API| API["armonia-api<br/>(FastAPI on Google Cloud Run)"]
DASH -->|Authenticated REST API| API
end
subgraph ExternalIntegrations ["Data & Service Adapters"]
API -->|Operational SSOT| DB[("Turso Database<br/>(libSQL)")]
API -->|Schedule synchronization| GC["Google Calendar API"]
DASH -->|48h payment follow-up| WA["WhatsApp Direct Links<br/>(wa.me)"]
end
```
---
## 📍 Source Code & Locations
| Component | Repository / Location | Target Platform | Stack & Tooling |
| :--- | :--- | :--- | :--- |
| **Workspace Org Hub** | [`armonia-del-ser`](https://gitea.roadtotech.me/armonia-del-ser) | Workstation: `~/Projects/active/armonia-del-ser` | Multi-repo management, roadmap, todo.txt |
| **Backend REST API** | [`armonia-api`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api) | Google Cloud Run ($0 tier) | Python 3.13, uv, FastAPI, SQLModel, Turso libSQL |
| **Operator Dashboard** | [`armonia-dashboard`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard) | Cloudflare Pages ($0 tier) | Vite+, Tailwind CSS, HTMX, Biome |
| **Public Landing & Booking** | [`armonia-landing`](https://gitea.roadtotech.me/armonia-del-ser/armonia-landing) | Cloudflare Pages ($0 tier) | Vite+, Tailwind CSS, HTMX, Biome |
| **Local Homelab Gateway** | `armonia-homelab/` | Workstation / Edge Proxy | Traefik, local mock authentication |
---
## 🔑 Key Invariants & Architectural Commitments
1. **Orthogonal Booking and Payment State Engine**:
- Booking lifecycle (`PENDING` -> `CONFIRMED` -> `COMPLETED` / `CANCELLED`) and Payment status (`UNPAID` -> `PENDING_VERIFICATION` -> `PAID` / `REFUNDED`) are decoupled orthogonal state machines.
- An appointment can hold a confirmed reservation slot while its payment verification is pending manual review.
2. **Mandatory 1-on-1 Session Buffer Isolation**:
- Individual therapy appointments strictly enforce pre- and post-session operational buffer times (e.g., room preparation, energetic cleansing, therapist transition).
- Collision detection algorithms reject overlapping appointments within the combined window `[start - buffer_before, end + buffer_after]`.
3. **Multi-Session Package Tracking & Redemption**:
- Pre-purchased session packages (e.g. 4-session therapy bundles) are tracked with transactional decrements upon appointment completion.
- Redemption validation prevents ghost allocations and verifies package ownership before confirming slots.
4. **Zero-Cost Cloud Deployment Policy**:
- All components are engineered within standard free tiers (Cloudflare Pages for static/HTMX frontends, Google Cloud Run with scale-to-zero for FastAPI, and Turso for serverless libSQL database storage).
5. **Human-in-the-Loop 48-Hour Payment Workflow**:
- Accommodates Mexico's local cash transfer practices (SPEI / OXXO deposits).
- Unverified bookings trigger automated alerts in the operator dashboard 48 hours prior to the session, enabling one-tap WhatsApp follow-ups (`wa.me`) before slots are forfeited.
-117
View File
@@ -1,117 +0,0 @@
---
type: project
status: active
tags:
- web
- fastapi
- react
- homelab
- sites
---
# 💌 BDInvite — Interactive Digital Birthday Invitation & Guest RSVP
**BDInvite** is a self-hosted, interactive digital birthday invitation application featuring event countdowns, venue mapping, Colombian phone number normalization, guest RSVP registration, and an Authelia-protected administration dashboard for guest list review and live event configuration.
The application runs as an autonomous workload in the homelab environment under `demos.roadtotech.me/birthday`.
---
## 🏛️ System Topology & Architecture
BDInvite is packaged as a high-efficiency single-container service combining a modern React 19 frontend and an asynchronous FastAPI backend:
* **Client & UI Tier**:
- React 19 SPA bundled via Vite with Tailwind CSS v4.
- Interactive animations powered by Motion and `canvas-confetti`.
- Self-hosted typography (`Playfair Display` and `Plus Jakarta Sans`) bundled directly in static distribution assets, eliminating runtime calls to third-party font CDNs.
* **Application & API Tier**:
- FastAPI running on Python 3.11 with `uvicorn`, managed via `uv`.
- Serves REST API routes under `/birthday/api/*` and acts as the SPA static web server for `/birthday/*`.
* **Persistence Tier**:
- SQLite 3 with Write-Ahead Logging (`PRAGMA journal_mode=WAL;`), persisted on a volume mount at `./data/bdinvite.db`.
- Stores unique guest RSVPs and singleton event configuration (`invitation_config`).
* **Edge & Identity Gateway**:
- **Traefik v3**: Handles path-based ingress on `demos.roadtotech.me` with priority-based route separation.
- **Authelia ForwardAuth**: Intercepts requests to administrative routes (`/birthday/admin*`), providing multi-factor SSO before traffic reaches the container.
```mermaid
flowchart TB
subgraph Clients ["Client Layer"]
GuestBrowser["Guest Mobile / Web Browser"]
AdminBrowser["Organizer Browser"]
end
subgraph Edge ["Homelab Edge (Traefik v3 & Authelia)"]
Traefik["Traefik Reverse Proxy\n(demos.roadtotech.me)"]
Authelia["Authelia SSO\n(ForwardAuth :9091)"]
Traefik <-->|"ForwardAuth (/birthday/admin*)"| Authelia
end
subgraph Workload ["Workload Container (bdinvite :8000)"]
FastAPI["FastAPI Web & API Server\n(uvicorn / Python 3.11)"]
StaticSPA["Bundled React 19 SPA\n(Vite / Tailwind v4)"]
SQLite[("SQLite 3 (WAL Mode)\n./data/bdinvite.db")]
FastAPI --> StaticSPA
FastAPI --> SQLite
end
GuestBrowser -->|"HTTPS GET /birthday\n(Priority 10: Public)"| Traefik
AdminBrowser -->|"HTTPS GET /birthday/admin\n(Priority 20: Authelia)"| Traefik
Traefik -->|"HTTP Proxy :8000\n(+ Remote-User for admin)"| FastAPI
```
---
## 📍 Source Code & Locations
| Component | Location / URL | Description |
| :--- | :--- | :--- |
| **Gitea Forge** | [bdinvite](https://gitea.roadtotech.me/kiskaadee/bdinvite) | Canonical Git repository housing `frontend/`, `backend/`, and `specs/` |
| **Clone (SSH)** | `ssh://git@gitea.roadtotech.me:2223/kiskaadee/bdinvite.git` | Developer clone URL using SSH port 2223 |
| **Workstation Path** | `~/Homelab/Sites/bdinvite` | Local development checkout with Nix devShell |
| **Production Target** | `server-remote:~/Sites/bdinvite` | Production workload checkout orchestrated via `appctl` |
| **Public URL** | [demos.roadtotech.me/birthday](https://demos.roadtotech.me/birthday) | Public invitation and RSVP interface |
| **Admin Portal** | [demos.roadtotech.me/birthday/admin](https://demos.roadtotech.me/birthday/admin) | Authelia-protected guest list and live configuration dashboard |
---
## 🔑 Key Invariants & Architectural Commitments
1. **Single-Container Multi-Stage Packaging**:
- A multi-stage Dockerfile utilizes `node:20-alpine` to compile the Vite React application, copying the resulting `dist/` directory into a lightweight `python:3.11-bookworm-slim` image powered by `uv`.
- FastAPI serves both the JSON API and the static SPA fallback from a single process on port 8000, avoiding multi-container operational overhead for lightweight micro-sites.
2. **Split Path-Based Routing & Ingress Priority**:
- Deployed on the shared demo domain `demos.roadtotech.me` under the `/birthday` path prefix.
- Public guest access uses a Traefik router at priority `10` (`PathPrefix(`/birthday`)`).
- Admin access uses an overlapping Traefik router at priority `20` (`PathPrefix(`/birthday/admin`)`) with `authelia-auth@docker` ForwardAuth middleware. Traefik matches the more specific rule first.
3. **Defense-in-Depth Authentication Invariant**:
- While Authelia gates the edge reverse proxy, every admin API endpoint (`/birthday/api/admin/*`) independently checks for the presence of the `Remote-User` HTTP header injected by Authelia.
- Administrative endpoints reject requests with HTTP 401 if the header is absent, preventing accidental data exposure if proxy middleware configuration lapses.
4. **Colombian Phone Normalization & Deduplication**:
- RSVPs normalize phone inputs by stripping whitespace/delimiters, stripping the `+57` country prefix if 12 digits, and enforcing a 10-digit mobile number format starting with `3`.
- The unique normalized phone acts as the natural deduplication key backed by a unique database constraint (`rsvps.phone`).
5. **Live Singleton Event Configuration**:
- Event metadata (honoree name, venue address, event date/time, Google Maps preview links, custom RSVP headings, and celebration messages) is stored in a singleton configuration table (`invitation_config`).
- Edits via the admin dashboard update the singleton row and reflect immediately across all connected guest clients without container restarts or code redeployments.
---
## 🏛️ Related Documents & Decisions
* 🗺️ **Implementation Plans & Specifications**:
- [BDInvite Implementation Plan](../../01-plans/bdinvite/implementation-plan.md) — Phased technical execution plan (P0–P5) covering Docker packaging, FastAPI backend, React 19 frontend, Traefik split routing, and deployment.
- [Digital Invitation Frontend Specification](../../01-plans/bdinvite/frontend-specification.md) — Responsive design principles, particle canvas architecture, typography, and guest/admin state transitions.
- [SSO Authentication Benchmark Roadmap](../../01-plans/bdinvite/sso-benchmark-roadmap.md) — Controlled A/B benchmark (Control vs Graphify) for portable Hexagonal AuthPort & OIDC migration.
* 💡 **Explorations & Discussions**:
- [Graphify Agent Experiment Retrospective](../../02-discussions/bdinvite/graphify-agent-experiment-retrospective.md) — Empirical post-mortem comparing Control vs Graphify agent conditions across the 8-checkpoint OIDC migration.
* 🏛️ **Architectural Decision Record**:
- [BDInvite Single-Container Architecture, Split Traefik Routing & ForwardAuth Integration](../../03-records/decisions/bdinvite-architecture-and-deployment.md) — MADR 4.0 capturing container topology, Traefik priority routing, defense-in-depth auth, and self-hosted fonts.
* 🌐 **Platform Context**:
- [Homelab Ecosystem & Core Infrastructure](../homelab/README.md) — System topology and workload specifications for `roadtotech.me`.
-78
View File
@@ -1,78 +0,0 @@
---
type: project
status: active
tags:
- second-brain
- tooling
- knowledge-graph
- automation
---
# 🧠 Second Brain Platform & Tooling (`brain`)
The **Second Brain Platform** comprises the core infrastructure, structural validators, automation toolchains, and metadata extraction pipelines that maintain the personal knowledge graph and compile documentation artifacts.
---
## 🏛️ Overview & System Topology
The Second Brain platform operates through declarative schema enforcement, automated pre-commit integrity hooks, and downstream static site compilation:
```mermaid
graph TD
CLI["Developer / Agent Workspace (`~/Brain`)"] --> PreCommit["Git Pre-Commit Hook (`validate-brain.py`)"]
PreCommit --> Validation["Structural Validation (AST, Frontmatter, Links, Linters)"]
Validation -->|Pass| Commit["Atomic Semantic Commit"]
Commit --> PostCommit["Post-Commit Hook"]
PostCommit --> Forge["Gitea Origin Push (`ssh://git@gitea.roadtotech.me:2223/kiskaadee/second-brain`)"]
Forge --> DocsEngine["docs2site Compiler & Search Indexer"]
```
1. **Schema & Integrity Engine**: Python-based structural validation enforcing frontmatter presence, type contracts, relative link resolution, and Ruff/Pyright quality.
2. **Deterministic Extraction & Indexing Pipeline**: Planned standalone extraction utilities providing lexical signals, BM25/AST weights, and key terms without external API dependencies.
3. **Distribution & GitOps Pipeline**: Automated post-commit synchronization with the private Gitea forge and downstream documentation publishers.
---
## 📍 Source Code & Locations
| Target | Location / URL | Description |
| :--- | :--- | :--- |
| **Local Workspace** | `/home/kiskaadee/Brain` | Version-controlled knowledge repository and tooling scripts |
| **Gitea Forge** | `ssh://git@gitea.roadtotech.me:2223/kiskaadee/second-brain` | Canonical remote Git repository on Homelab Core |
| **Agent Spec** | [Second Brain Agent Spec](../../05-agents/profiles/second-brain.md) | Behavioral contract and curation protocol for Brain agents |
---
## 💬 Open Discussions
*None currently open.*
---
## 🚧 Work in Progress (Active Plans)
1. 🟡 [**Deterministic Term Extraction for Brain Documents**](../../01-plans/brain/deterministic-term-extraction.md) `[Active]`
- Cheap, reproducible, auditable lexical extraction pipeline (`scripts/extract-terms.py`, `scripts/patch-terms.py`, `scripts/stopwords.txt`) to replace non-deterministic tag generation with structural AST weighting.
2. 🟡 [**Structural Refactoring for validate-brain.py Pipeline**](../../01-plans/brain/validate-brain-refactoring.md) `[Active]`
- Multi-phase refactoring of the pre-commit integrity validator into a single-pass `Document`/`Issue` pipeline with line-numbered diagnostics and robust Markdown fence handling. (Phase 1 complete).
---
## 🛠️ Canonical Guides & Runbooks
* [**Deterministic Tag & Key Term Extraction Guide**](../../04-learning/knowledge/methods/deterministic-tag-extraction.md) — Algorithmic approaches and architectural comparison across statistical heuristics, AST parsers, and taxonomy matchers.
* [**How to Build Effective Agent Skills**](../../04-learning/knowledge/methods/building-effective-agent-skills.md) — Canonical method guide explaining the operational physics of skills, the airlock mental model, and the single observable proof heuristic.
* [**Global Documentation Router & Investigation Skills Walkthrough**](../../04-learning/guides/brain/documentation-and-investigation-skills-walkthrough.md) — Operational walkthrough covering procedural investigation, documentation router gatekeeping, anti-overlap invariants, and authoring reference modules.
---
## 🏛️ Completed Milestones & Resolved Decisions
* 🟢 **Validation & Taxonomy Foundation** — Implementation of `scripts/validate-brain.py`, pre-commit hook enforcement, and five-category semantic schema.
* 🟢 **Multi-Agent Catalog** — Formalization of `agents/` store and operational profiles.
* 🟢 [**Brain Taxonomy & Lifecycle Migration**](../../01-plans/brain/taxonomy-lifecycle-migration.md) — Reorganized repository from organic structure into 7 numbered lifecycle directories (`00-inbox/` through `06-projects/`), introduced declarative `DirectoryContract` validation, executed 188-file migration and 199-link rewrites, and synchronized distributed `AGENTS.md` integration surfaces.
- Companion Discussion: [Brain Epistemic Lifecycle Taxonomy](../../02-discussions/brain/taxonomy-and-lifecycle-architecture.md)
* 🟢 [**Incident Debug Records & Daily Journal Workflow Reorganization**](../../01-plans/brain/incident-debug-and-journal-workflow.md) — Established first-class `type: debug` records in `03-records/debug/`, strictly one daily journal per date in `03-records/journal/YYYY-MM-DD.md`, and automated inbox curation protocol.
* 🟢 [**Documentation Router & Engineering Investigation Skills Decoupling**](../../01-plans/brain/documentation-and-investigation-skills-decoupling.md) — Decoupled procedural troubleshooting (scientific method, interactive checkpoints) from documentation evaluation and routing; introduced second-order documentation router with modular authoring specifications.
* 🟢 [**Agent Skill Architecture, Proportional Sizing, and Meta-Builder Governance**](../../03-records/decisions/agent-skill-architecture-and-governance.md) — Point-in-time architectural commitments establishing the 4-tier skill taxonomy, proportional structural sizing, skill-builder review gate, and investigation invariants.
-176
View File
@@ -1,176 +0,0 @@
---
type: project
status: active
tags:
- public-art
- fastapi
- postgis
- pgvector
- pwa
- cali
- cultural-oracle
---
# 🐱 Novias del Gato — Digital Ecosystem for Cali's Public Art
**Novias del Gato** is an interactive geographic and cultural platform designed to track, catalog, and explore the iconic cat sculptures of Santiago de Cali, Colombia. Originating from Hernando Tejada's 1996 "El Gato del Río" (The River Cat) and expanded since 2006 with "Las Novias del Gato," the collection comprises 38 dynamic urban sculptures.
Because these monuments are frequently relocated for maintenance or urban planning, the platform acts as a **Geographic Cultural Oracle**, combining citizen crowdsourcing, trust reputation consensus, and client-side visual recognition to maintain a verified Single Source of Truth (SSOT).
---
## 🏛️ System Topology & Architecture
Novias del Gato uses a **Modular Monolith** and **API-First** architecture designed for low cloud hosting overhead and high cellular resilience:
* **Client & Edge Inference Tier**:
- Progressive Web App (PWA) with camera integration and Leaflet map navigation.
- **"Compressed Edge" Inference**: 8-bit quantized **MobileNetV2** runs locally in the user's browser via **ONNX Runtime Web** (WebAssembly/WebGL). The client extracts a 1280-dimension L2-normalized float embedding and compresses photos to ~80KB JPEGs (800x800px) before transmission.
* **Application & API Tier**:
- Asynchronous **FastAPI** backend running on Python 3.14, packaged via `uv` with PEP 517/518 `src/` layout.
- Fully decoupled authentication using an **SSO Identity Provider Adapter** pattern (`IdentityProvider` protocol).
- Business logic implementing velocity filtering, spatial proximity verification, and crowdsourced weighted consensus.
* **Persistence & Spatial-Vector Tier**:
- **PostgreSQL 17** containerized with both **PostGIS** (spatial) and **pgvector** (vector embeddings) extensions.
- Spatial indexing (`GIST`) for 10-meter geographic proximity queries (EPSG:4326).
- Vector indexing (`HNSW` with `vector_cosine_ops`) for sub-second similarity matching.
```mermaid
flowchart TB
subgraph Client ["Client Device (PWA)"]
Camera["Camera Capture"]
CanvasDownscale["Canvas Crop & Compress\n(800x800px, 75% JPEG ~80KB)"]
ONNXWeb["ONNX Runtime Web\n(MobileNetV2 Quantized ~3.5MB)"]
VectorOut["1280-Float Normalized Embedding"]
Camera --> CanvasDownscale
Camera --> ONNXWeb
ONNXWeb --> VectorOut
end
subgraph API ["Backend API Tier (FastAPI :8000)"]
AuthRouter["SSO Auth Gateway\n(IdentityProvider Adapter)"]
CheckInRouter["Check-In Router\n(Spatial + Cosine Validation)"]
ConsensusEngine["Location Tracker / Consensus Engine\n(Velocity & Weighted Voting)"]
end
subgraph Persistence ["Persistence Layer (PostgreSQL 17)"]
PostGIS[("PostGIS\nST_DWithin Spatial Index (GIST)")]
PGVector[("pgvector\n1280-dim HNSW Cosine Index")]
Relational[("Relational Tables\nusers, sculptures, check_ins, tickets")]
end
CanvasDownscale -->|"Multipart Photo"| CheckInRouter
VectorOut -->|"1280 Float Vector"| CheckInRouter
CheckInRouter --> PostGIS
CheckInRouter --> PGVector
CheckInRouter --> Relational
```
---
## 🔑 Core Invariants & Architectural Decision Records (ADRs)
1. **Zero Tensor Math on the Server (ADR-001)**:
- Server runs on micro VPS instances without heavy ML frameworks (PyTorch/full ONNX), maintaining an idle footprint around ~80MB RAM.
2. **Separation of Check-in vs. Ticket**:
- Check-ins validate physical exploration against the current SSOT.
- Tickets report moved, missing, or altered sculptures without blocking explorer gameplay.
3. **Pluggable SSO Identity Provider Adapter**:
- Core authentication depends on an abstract `IdentityProvider` contract (`verify_token(token: str) -> AuthUserIdentity`).
- Supports `GoogleOAuthAdapter` in production and `MockDevAdapter` for offline local development and test automation.
4. **Hybrid Consensus Engine**:
- **Velocity Checks**: Rejects teleportation/spoofing if calculated speed $v = \frac{\Delta d}{\Delta t} > 120\text{ km/h}$.
- **Spatial Clustering**: Groups reports within a 20-meter radius over 48 hours.
- **Confidence Scoring**: $C_{\text{cluster}} = \sum \text{trust\_score}_i$. Automatic promotion to SSOT occurs when $C_{\text{cluster}} \ge 3.0$ with $\ge 3$ distinct contributors. Conflicted or lower-confidence submissions escalate to manual moderator review.
- **Reputation Dynamics**: Verified reports award $+0.05$ trust (max 1.0); malicious or invalid reports penalize $-0.15$.
5. **Cascade Triage & Non-Autoregressive Decision Engine (Jev)**:
- Crowdsourced reports (`POST /reports`) and device fallback queues are triaged via a pluggable `TriageProvider` adapter (backed by TypeSafe AI's **Jev** model).
- Fast evaluation against typed schemas (`choice` for intent/category, `noul` for spam detection, `score` for credibility) ensures sub-200ms latency, zero type errors, and calibrated probabilities without running heavy autoregressive LLMs.
- Core mathematical velocity filters and client-side MobileNetV2 edge vectors remain untouched.
---
## 🗄️ Relational & Spatial Database Schema
```sql
-- Extensions
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS vector;
-- Users (Explorers & Contributors)
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
trust_score FLOAT NOT NULL DEFAULT 0.5 CHECK (trust_score >= 0.0 AND trust_score <= 1.0),
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Sculptures (The Oracle SSOT)
CREATE TABLE sculptures (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
artist VARCHAR(255) NOT NULL,
year INTEGER NOT NULL CHECK (year >= 1900),
description TEXT,
audio_url VARCHAR(512),
unlocked_content TEXT,
status VARCHAR(50) NOT NULL DEFAULT 'on-site' CHECK (status IN ('on-site', 'moved', 'missing')),
location GEOGRAPHY(Point, 4326) NOT NULL,
embedding vector(1280) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Check-ins (Explorer Progress & Gallery)
CREATE TABLE check_ins (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
sculpture_id UUID NOT NULL REFERENCES sculptures(id) ON DELETE CASCADE,
captured_at TIMESTAMP WITH TIME ZONE NOT NULL,
photo_url VARCHAR(512) NOT NULL,
similarity_score FLOAT NOT NULL CHECK (similarity_score >= 0.0 AND similarity_score <= 1.0),
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uq_user_sculpture UNIQUE (user_id, sculpture_id)
);
-- Crowdsourced Tickets (Citizen Sighting Reports)
CREATE TABLE tickets (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
sculpture_id UUID NOT NULL REFERENCES sculptures(id) ON DELETE CASCADE,
reported_status VARCHAR(50) NOT NULL CHECK (reported_status IN ('on-site', 'moved', 'missing')),
location GEOGRAPHY(Point, 4326) NOT NULL,
photo_url VARCHAR(512),
description VARCHAR(500),
status VARCHAR(50) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
reporter_trust_score FLOAT NOT NULL,
notes VARCHAR(300),
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
resolved_at TIMESTAMP WITH TIME ZONE
);
```
---
## 🛠️ Verification Gates & Operational Standards
Codified in `AGENTS.md` and enforced prior to every commit:
1. **Ruff Formatting**: `uv run ruff format --check .`
2. **Ruff Linting**: `uv run ruff check .`
3. **Static Type Checking (Pyright)**: `uv run pyright`
4. **Automated Test Suite (Pytest)**: `uv run pytest`
---
## 🗺️ Project Status & Next Steps
* [x] **Phase 1: Concept & User Stories** (Completed)
* [x] **Phase 2: OpenAPI Contract & Schema Reconciliation** (Completed)
* [x] **Phase 3 Foundation: PostGIS + pgvector Docker & Async Backend Scaffold** (Completed)
* [ ] **Phase 3 Implementation: Alembic Migrations & Database Seeding**
* [ ] **Phase 3 Implementation: Core Route Handlers (`/sculptures`, `/check-in`, `/reports`)**
* [ ] **Phase 4: Client Interaction Layer (PWA / Anne Droid delegation)**
-147
View File
@@ -1,147 +0,0 @@
---
type: project
status: active
tags:
- architecture
- operations
- security
- homelab
- infrastructure
---
# 🌐 Homelab Ecosystem & Core Infrastructure
The **Homelab** project encompasses the architecture, automation, deployment pipelines, and operational runbooks powering the 24/7 personal infrastructure ecosystem hosted at `roadtotech.me`.
The environment runs on dedicated hardware as a declarative NixOS appliance, providing self-hosted productivity tools, internal developer platforms, edge routing, and automated GitOps workflows.
---
## 🏛️ System Topology & Architecture
The homelab is organized into four decoupled architectural layers to isolate failures and maintain zero-downtime operations:
1. **Edge & Security Layer**:
- **Traefik Reverse Proxy**: Dynamic ingress routing over HTTPS with automated Let's Encrypt wildcard TLS certificates (`*.roadtotech.me`).
- **Authelia SSO**: ForwardAuth single sign-on with multi-factor authentication (2FA) protecting private services and dashboards.
- **Dynu Dynamic DNS**: Automated WAN address synchronization and fallback monitoring.
2. **Core Control Plane (`~/Core`)**:
- Central homelab services managed as a declarative NixOS appliance, including Gitea (Git forge & CI/CD runner), Nextcloud, Vaultwarden, Homepage dashboard, and deployment webhooks.
3. **Workload Plane (`~/Sites`)**:
- Autonomous, containerized application stacks (Docker Compose) completely decoupled from Core infrastructure. Each service repository declares its own metadata, routing rules, and lifecycle via an `app.yaml` manifest. Managed workloads include:
- [**BDInvite**](../bdinvite/README.md) (`demos.roadtotech.me/birthday`): Interactive digital birthday invitation with RSVP, FastAPI backend, and split Traefik/Authelia access.
- [**MagNetFlix**](../magnetflix/README.md) (`magnetflix.roadtotech.me`): Automated media acquisition and streaming pipeline behind Authelia SSO.
4. **Host Foundation**:
- Headless NixOS host system configured with encrypted secrets via SOPS-nix (`age`), strict firewall isolation, and standardized systemd timers for maintenance.
---
## 📍 Source Code & Repositories
| Target | Location / URL | Description |
| :--- | :--- | :--- |
| **Gitea Forge** | [homelab-core](https://gitea.roadtotech.me/kiskaadee/homelab-core) | Primary Git repository housing the NixOS appliance and Core services |
| **Clone (SSH)** | `ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-core.git` | Developer clone URL using SSH port 2223 |
| **Workstation Path** | `~/Homelab/Core` | Active local development checkout on workstation (`~/Homelab/Core` and `~/Homelab/Sites`) |
| **Production Target** | `server-remote:~/Core` | Production deployment checkout on the 24/7 server host |
---
## 💬 Open Discussions
Architectural inquiries and problem statements currently under evaluation that have **not yet produced an active implementation plan**:
* ❓ [**Multi-User Houston Architecture via Dynamic Container Spawner and LLDAP/Authelia**](../../02-discussions/homelab/houston-multiuser-spawner-architecture.md)
- **Focus**: Evaluates a dynamic container spawner and LLDAP/Authelia ForwardAuth proxy architecture to provide per-user isolated Houston engine pods (`~/Sites/houston`).
- **Current Status**: Open inquiry analyzing container lifecycle management, per-tenant state volume isolation, and idle spin-down semantics.
* ❓ [**WhatsApp & Telegram AI Assistant Backend Architecture**](../../02-discussions/homelab/chatbot-assistant-design.md)
- **Focus**: Evaluates architecture, webhook ingress, and trade-offs between Telegram Bot API and WhatsApp Cloud API for a personal AI assistant microservice (`~/Sites/homelab-assistant`) connected to the Brain vault.
- **Current Status**: Open inquiry examining authorization models, message formatting, cron triggers, and RAG search capabilities before formalizing an implementation plan.
---
## 🚧 Work in Progress (Active Plans)
Implementation roadmaps currently in progress (`status: active`) that are actively being executed or scheduled for deployment:
1. 🟡 [**Architecture Consolidation & Control Plane Roadmap v6**](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md) `[Active]`
- Unified roadmap codifying locked decisions DEC-01 through DEC-05: single typed `POST /v1/operations` dispatcher, dual transports (UDS + HTTP), mandatory token-gated authorization, dedicated `homelab-appctl` systemd isolation, unified pre-flight Compose security checks, and append-only audit telemetry with fail-closed disk guard.
- 🏛️ *Architectural Decision Records*: [**Homelab appctl Control Plane Architecture**](../../03-records/decisions/homelab-appctl-control-plane-architecture.md) & [**Homelab 3-Tier Architecture & Provenance**](../../03-records/decisions/homelab-3tier-architecture-and-provenance.md)
- 📖 *Evolutionary History*: [**Homelab Control Plane Evolution (v1 to v6)**](../../04-learning/knowledge/methods/homelab-control-plane-evolution-v1-to-v6.md)
2. 🟡 [**Rust Daemon Migration Plan: Standalone `dynu-monitor`**](../../01-plans/homelab/dynu-monitor-rust-daemon.md) `[Active]`
- Implementing a standalone Rust daemon with 30-second polling and round-robin public DNS resolution across 5 independent providers (Cloudflare, Quad9, Google, OpenDNS, Dynu).
3. 🟡 [**Custom API Security Hardening & Threat Analysis**](../../01-plans/homelab/api-security-hardening.md) `[Active]`
- Defense-in-depth security hardening for custom microservice APIs (Learning Hub and Minecraft dashboard) using Authelia ForwardAuth, token validation, and rate limiting.
4. 🟡 [**GitHub to Gitea Automated Batch Migration Plan**](../../01-plans/homelab/gitea/github-to-gitea-migration-plan.md) `[Active]`
- Automated migration tooling using `gh` and `tea` APIs to migrate ~35 repositories from GitHub to self-hosted Gitea with push mirrors for redundancy.
5. 🟡 [**LVM Storage Optimization & Partition Resizing Strategy**](../../01-plans/homelab/server-24-7/lvm-storage-optimization-and-resizing.md) `[Active]`
- Storage space audit, disk cleanup runbooks, and a non-destructive LVM logical volume expansion procedure for the server's root filesystem.
---
## 🛠️ Canonical Guides & Runbooks
Operational runbooks and procedures for daily administration:
* [**Onboarding a New Application Stack**](../../04-learning/guides/homelab/onboarding-a-new-service.md) — Step-by-step procedure for deploying new Docker Compose services in `~/Sites` with `app.yaml` and Traefik routing.
* [**Jellyfin GPU Hardware Acceleration Guide**](../../04-learning/guides/homelab/jellyfin-gpu-hardware-acceleration.md) — Configuring `/dev/dri` device passthrough, host group permissions, and GPU telemetry for hardware transcoding.
* [**LLDAP & Authelia SSO Integration Runbook**](../../04-learning/guides/homelab/lldap-authelia-integration.md) — Dynamic user directory configuration, Authelia LDAP auth, and pre-commit quality gate checks.
* [**Mail Deliverability & Outbound Relay Guide**](../../04-learning/guides/homelab/mail-deliverability-rdns-relay-guide.md) — Solving residential IP/PTR blocks and Spamhaus PBL using Stalwart and Brevo SMTP relay.
* [**Homepage Dashboard Reintegration into Core**](../../04-learning/guides/homelab/homepage-core-reintegration.md) — Clean service discovery and configuration of gethomepage in Homelab Core.
* [**Managing Secrets and Authelia Users**](../../04-learning/guides/homelab/managing-secrets-and-authelia-users.md) — Guide for editing SOPS-encrypted secrets and managing user authentication credentials.
* [**Server Maintenance and System Updates Runbook**](../../04-learning/guides/homelab/server-maintenance-and-updates.md) — Standard operating procedure for NixOS updates, garbage collection, and container pruning.
* [**Appctl & Application Manifests (`app.yaml`) User Guide**](../../04-learning/guides/homelab/appctl-operations-and-manifest-guide.md) — Comprehensive reference for the `appctl` CLI tool and `app.yaml` schema.
* [**Brain GitOps & Auto-Sync Deployment Pipeline**](../../04-learning/guides/homelab/brain-gitops-deployment-pipeline.md) — Technical runbook on how Brain commits automatically validate and publish to `docs.roadtotech.me`.
* [**Dynu DDNS Domain Configuration Troubleshooting Runbook**](../../04-learning/guides/homelab/dynu-ddns-troubleshooting.md) — Diagnostic and recovery steps for WAN address synchronization issues.
* [**Diagnosing Unexpected Server Shutdowns Runbook**](../../04-learning/guides/homelab/server-unexpected-shutdown-diagnosis.md) — Diagnostic procedure and checklist for investigating hardware thermal trips, power loss, and unexpected crashes.
* [**Homelab Architecture Consolidation Documents Reorganization Walkthrough**](../../04-learning/guides/homelab/architecture-docs-reorganization-walkthrough.md) — Operational walkthrough covering MADR 4.0 standardization, narrative discussion expansion, authoritative plan framing, and consolidation lineage reorganization.
---
## 🏛️ Completed Roadmaps & Resolved Discussions
Archived and foundational documentation for completed milestones:
### Resolved Architectural Discussions
* [**Homelab Control Plane Modernization & Separation of Responsibilities**](../../02-discussions/homelab/control-plane-and-engine-modernization.md) — Evaluated script-based orchestration vs unified control plane daemon (`homelab-appctl.service`); resolved via ADR-0002 and Roadmap v5/v6.
* [**Stalwart Mail Server Evaluation for Homelab Core**](../../02-discussions/homelab/mail-server-evaluation-stalwart.md) — Evaluated Stalwart vs Mailcow, Poste.io, and Postfix; resolved via Stalwart deployment.
* [**Hostinger Business Email vs. Self-Hosted Stalwart**](../../02-discussions/homelab/hostinger-vs-stalwart-email-evaluation.md) — Compared cloud SaaS mail vs self-hosted mail with smart host relay.
* [**Dual-Email Schema: Internal Mailboxes vs External Recovery**](../../02-discussions/homelab/dual-email-schema-lldap-stalwart.md) — Solved password recovery loops in identity directories with separate `mail` and `recovery_email` attributes.
* [**Decoupling User Management from Secrets via LLDAP**](../../02-discussions/homelab/authelia-dynamic-user-backend-lldap.md) — Migrated from static SOPS user databases to dynamic LDAP authentication.
* [**Authelia Session Lifetimes & Email Architecture**](../../02-discussions/homelab/authelia-session-email-architecture.md) — Configured 7d/3d session policies and email-based perimeter security.
* [**Homelab Repository Location & Placement Analysis**](../../02-discussions/homelab/homelab-repo-location-analysis.md) — Evaluated `~/Homelab` vs `~/Projects/homelab`; resolved via dedicated `~/Homelab` tree.
* [**Multirepo Refactor: Homepage & Learning Hub Separation**](../../02-discussions/homelab/multirepo-refactor-homepage-courses.md) — Decoupled dashboard infrastructure from domain applications.
* [**NixOS Monorepo vs. Multi-Repo Architecture**](../../02-discussions/homelab/nixos-monorepo-vs-multirepo.md) — Evaluated workstation and server decoupling; resolved via appliance migration.
* [**Decoupling `nixos-config` and `homelab-core`**](../../02-discussions/homelab/nixos-monorepo-decoupling.md) — Migration inventory and separation plan; resolved via repository split.
* [**Dynamic Decentralized GitOps Dispatcher Architecture**](../../02-discussions/homelab/gitops-dispatcher-architecture.md) — Decoupled deployment webhook design; implemented in production.
* [**Gitea Git Credential Helper and Backup Strategy**](../../02-discussions/homelab/gitea-credentials-and-backup-strategy.md) — Evaluated credential helpers and push mirroring; resolved via Git credential helper configuration.
* [**Dynu DDNS Polling Frequency and Rust Migration**](../../02-discussions/homelab/dynu-monitor-polling-and-language-tradeoffs.md) — Investigated polling intervals and language trade-offs; resolved via `dynu-monitor-rust-daemon.md` plan.
* [**Dozzle Forward-Proxy Authentication & Persistent Volume Architecture**](../../02-discussions/homelab/dozzle-auth-and-storage-architecture.md) — Evaluated Dozzle v2 login prompt vs ForwardAuth SSO; resolved via `DOZZLE_AUTH_PROVIDER=forward-proxy` and persistent `/data` volume.
* [**Core Service Qualification & Portainer Deprecation**](../../02-discussions/homelab/core-service-qualification-and-portainer-deprecation.md) — Evaluated platform service qualification criteria; resolved via complete deprecation of Portainer and retaining Gitea and CI runner decoupled.
* [**Migrating from Legacy Multirepo (v3) to 3-Tier Provenance Architecture (v4)**](../../02-discussions/homelab/architecture-migration-v3-to-v4.md) — Evaluated multirepo friction (source pollution, repo inflation, state co-location) vs 3-tier decoupling; resolved via Roadmap v4 adoption.
### Completed & Superseded Plans
* 🟢 [**Architecture Consolidation & Control Plane Roadmap v5**](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v5.md) (Superseded by v6; established 5-stage DeploymentModel lifecycle and control-plane architecture)
* 🟢 [**appctl Engine V2: Architectural Modernization & Type-Safe Refactoring Plan**](../../01-plans/homelab/appctl/appctl-engine-v2-refactoring.md) (Superseded by Roadmap v5/v6 Phases P0 and P3; engine promoted to `scripts/appctl_engine.py`)
* 🟢 [**Smart Selective Deployment Pipeline for Homelab Core**](../../01-plans/homelab/appctl/smart-deployment-pipeline.md) (Superseded by Roadmap v5/v6 Phase P4 control-plane reconciliation)
* 🟢 [**Architecture Consolidation & Hardening Roadmap & Execution Plan v4**](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md) (Superseded by v5; established 3-tier architecture, OCI provenance model, and execution guide unification)
* 🟢 [**Homelab Architecture Consolidation Documents Reorganization**](../../01-plans/homelab/architecture-docs-reorganization.md) — Reorganized consolidation documentation across the epistemic triad (ADR MADR 4.0, narrative Discussion, authoritative Plan) and created `01-plans/homelab/consolidation/` lineage directory.
* 🟢 [**Architecture Consolidation & Hardening Roadmap v3**](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v3.md) (Superseded by v4; established controller authority, mail relocation plan, and manifest convergence)
* 🟢 [**Architecture Consolidation Implementation Guide v3**](../../01-plans/homelab/consolidation/architecture-consolidation-implementation-guide-v3.md) (Superseded by v4)
* 🟢 [**Diun Load-Shaping, Workload Exemption & Authenticated SMTPS Delivery (2026-09-24)**](../../03-records/debug/2026-09-24-diun-workload-isolation-and-load-shaping.md) — Resolved 6 post-deployment issues: Portainer bcrypt `$` interpolation, high-concurrency DNS load mitigated via `WORKERS=6` + `JITTER=30s`, local-build exemptions decentralized to `Sites/*`, and Diun migrated to port 465 SMTPS with dedicated service account. 19 images clean, mail delivered authenticated.
* 🟢 [**Clean Deprecation of Portainer from Core**](../../01-plans/homelab/portainer-deprecation-plan.md)
* 🟢 [**Stalwart Mail Server & SnappyMail Webmail Deployment**](../../01-plans/homelab/stalwart-email-server-implementation-plan.md)
* 🟢 [**Multirepo Refactor of Homepage & Learning Hub**](../../01-plans/homelab/multirepo-refactor-homepage-courses.md)
* 🟢 [**Architecture Consolidation & Hardening Roadmap v2**](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v2.md) (Superseded by v3; P0 GitOps trust boundary & automated invariant testing completed)
* 🟢 [**Architecture Consolidation Implementation Guide v2**](../../01-plans/homelab/consolidation/architecture-consolidation-implementation-guide-v2.md) (Superseded by v3)
* 🟢 [**Architecture Consolidation & Hardening Roadmap v1**](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap.md) (Superseded by v2)
* 🟢 [**Turn `homelab-core` into a Declarative NixOS Appliance**](../../01-plans/homelab/nixos-appliance-migration.md)
* 🟢 [**Core & Sites Cutover and Testing Plan**](../../01-plans/homelab/core-sites-cutover-testing-plan.md)
* 🟢 [**appctl Refactor & Decentralized `app.yaml` Metadata Architecture**](../../01-plans/homelab/refactor-and-metadata-sync.md)
* 🟢 [**appctl Git Synchronization & Full-Stack Lifecycle Strategy**](../../01-plans/homelab/git-sync-and-lifecycle.md)
* 🟢 [**CI/CD & Deployment Strategy**](../../01-plans/homelab/gitea/deployment-and-cicd-strategy.md)
* 🟢 [**Real-Time Brain Synchronization & Gitea Push Mirroring**](../../01-plans/homelab/brain-sync-and-gitea-mirroring.md)
* 🟢 [**NixOS Server & Laptop Migration**](../../01-plans/homelab/nixos-server-laptop-migration.md)
* 🟢 [**Domain Migration (`roadtotech.me`)**](../../01-plans/homelab/domain-migration-roadtotech.md)
* 🟢 [**Production Folder Structure Reorganization**](../../01-plans/homelab/server-24-7/folder-structure-reorganization.md)
-173
View File
@@ -1,173 +0,0 @@
---
type: project
status: active
tags:
- media
- streaming
- torrent
- grpc
- fastapi
- architecture
---
# 🎬 MagNetFlix — System Architecture & Media Pipeline
MagNetFlix is an automated, self-hosted media acquisition, verification, and library organization platform. It bridges the gap between web-browsed movie requests (magnet URIs) and structured, verified Jellyfin/Plex media storage through an audited gRPC pipeline behind Authelia SSO.
---
## 🏛️ System Topology & Architecture
When managing a self-hosted media library, manual acquisition requires downloading torrents, monitoring progress, manually weeding out garbage/malicious scripts (`.exe`, `.bat`), and renaming folders to match IMDb/TMDB conventions. In multi-user setups, tracking who requested what and auditing download states is chaotic without a unified log.
MagNetFlix resolves this with an automated end-to-end pipeline:
- **Client Ingestion**: Captures magnet links via a cross-browser extension or web dashboard.
- **FastAPI BFF Gateway**: Manages authentication via Authelia SSO headers, exposes REST/SSE endpoints, and coordinates requests.
- **gRPC Worker Pipeline**: Sandboxed download coordinator utilizing Transmission RPC in an isolated staging scratch disk.
- **Security Sanitizer**: Enforces path traversal checks, file extension whitelists, and largest-file feature film selection while purging malicious scripts.
- **TMDB Metadata Verification**: Validates the IMDb ID against TMDB metadata and matches token similarity with the downloaded torrent payload.
- **Library Relocator**: Formats and places verified video and subtitle files into the canonical Jellyfin/Plex structure.
```mermaid
flowchart TB
subgraph ClientLayer ["Client & Ingestion Layer"]
Ext["MagNetFlix Browser Extension\n(Firefox / Chromium)"]
WebUI["Web Pairing Dashboard\n(FastAPI / Jinja / Tailwind)"]
end
subgraph Edge ["Public Edge (Reverse Proxy & SSO)"]
Traefik["Traefik Reverse Proxy\n(magnetflix.roadtotech.me)"]
Authelia["Authelia SSO\n(Forward Auth)"]
Traefik <-->|Forward Auth| Authelia
end
subgraph CoreServices ["Core Internal Services (Docker Monorepo)"]
BFF["FastAPI BFF Gateway\n(services/bff)"]
Worker["gRPC Pipeline Worker\n(services/worker)"]
DB[("SQLite 3 (WAL Mode)\nAudit & Job State Store")]
Torrent["Transmission Daemon\n(RPC Engine)"]
end
subgraph ProcessingPipeline ["Worker Pipeline Stages"]
Sanitizer["Media Sanitizer\n(Allowlist & Anti-Traversal)"]
TMDB["TMDB Metadata Client\n(Token Overlap Check)"]
StorageMgr["Library Relocator\n(Canonical Renamer)"]
end
subgraph Storage ["Persistent Storage Mounts"]
Staging[("/data/staging/<job_id>\nScratch Disk")]
Library[("/media/movies\nJellyfin / Plex Media Root")]
end
Ext -->|"Redirect / Pair"| Traefik
WebUI -->|HTTP POST| Traefik
Traefik -->|HTTP + Remote-User| BFF
BFF -->|gRPC SubmitDownload| Worker
BFF <-->|"gRPC Event Stream (SSE)"| Worker
Worker --> DB
Worker -->|RPC| Torrent
Torrent --> Staging
Worker --> Sanitizer
Sanitizer --> Staging
Worker --> TMDB
Worker --> StorageMgr
StorageMgr --> Library
```
### Job State Machine & Lifecycle Rules
The pipeline worker enforces a linear, finite state machine with terminal failure handling and startup crash recovery:
```mermaid
stateDiagram
[*] --> QUEUED: SubmitDownload(magnet, imdb_id)
QUEUED --> DOWNLOADING: Transmission starts transfer
DOWNLOADING --> SCANNING: Download reaches 100%
DOWNLOADING --> FAILED: Torrent error / stalled timeout
SCANNING --> VERIFYING_METADATA: Sanitizer allowlist passes
SCANNING --> FAILED: Disallowed files / no valid video
VERIFYING_METADATA --> ORGANIZING: TMDB metadata matches torrent
VERIFYING_METADATA --> FAILED: Lookup failed / title mismatch
ORGANIZING --> COMPLETED: Relocated & renamed into library
ORGANIZING --> FAILED: Disk full / permission error
COMPLETED --> [*]
FAILED --> [*]
```
#### Key Invariants
1. **Crash & Restart Recovery**: Upon worker startup, all orphaned non-terminal jobs in the SQLite database automatically transition to `FAILED` (`"Worker restarted during execution"`).
2. **Strict Idempotency**: Submissions are rejected if a non-terminal job for the same `imdb_id` is currently in-flight, or if `/media/movies/*[imdbid-{imdb_id}]` already exists in the media library.
3. **Sandbox Scrubbing**: Staging directories (`/data/staging/<job_id>/`) are purged immediately upon reaching `COMPLETED` or `FAILED`.
### Security & Media Sanitizer Specification
The sanitizer strictly guards the file-system boundary before any file is moved to the permanent library:
- **Anti-Traversal**: Blocks symlinks, hardlinks, or relative paths escaping the staging root (`..`).
- **File Allowlist**:
- *Allowed Video*: `.mkv`, `.mp4`, `.avi`, `.webm`
- *Allowed Subtitles*: `.srt`, `.vtt`, `.sub`, `.ass`
- *Forbidden / Immediate Quarantine*: `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.lnk`, `.iso`, `.zip`, `.rar`.
- **Largest File Rule**:
- Files containing `sample` in the filename or under 100 MB are discarded.
- The single largest valid video file is chosen as the primary feature film.
---
## 📍 Source Code & Locations
| Component | Location / URL | Description |
| :--- | :--- | :--- |
| **Main Monorepo (Forge)** | [MagNetFlix](https://gitea.roadtotech.me/kiskaadee/MagNetFlix) | Canonical Git repository housing `services/bff`, `services/worker`, and `proto/` |
| **Workstation Path** | `~/Projects/active/MagNetFlix` | Active local monorepo development checkout |
| **Extension PoC (Local)** | `~/Projects/learning/extensions/magnetflix-extension` | Working Firefox/Chromium WebExtension prototype |
| **Production Ingress** | [magnetflix.roadtotech.me](https://magnetflix.roadtotech.me) | Traefik entrypoint with Authelia forward authentication |
---
## 💬 Open Discussions
No open architectural discussions at this time.
---
## 🚧 Work in Progress (Active Plans)
Implementation roadmaps currently in progress (`status: active`) that are actively being executed or scheduled for deployment:
1. 🟡 [**MagNetFlix Cross-Browser Extension Integration**](../../01-plans/magnetflix/browser-extension-integration.md) `[Active]`
- Actionable implementation plan for evolving the working proof-of-concept into a production-grade cross-browser extension with web dashboard handoff and Traefik/Authelia SSO integration.
### Phased Roadmap Overview
```mermaid
flowchart LR
M1["Milestone 1\nWorkspace & Protobuf\n(Completed)"] --> M2["Milestone 2\nWorker & Sanitizer Engine\n(Next)"]
M2 --> M3["Milestone 3\nBFF Gateway & Web UI\n(In Planning)"]
M3 --> M4["Milestone 4\nEdge Deployment & SSO\n(In Planning)"]
M4 --> M5["Milestone 5\nProduction Extension\n(PoC Built)"]
```
- **Milestone 2: Worker Engine & Pipeline Modules** *(Next Priority)*: SQLAlchemy 2.0 + SQLite (WAL mode) schema, Transmission RPC client, Media Sanitizer, TMDB token-overlap validation, and media library relocator.
- **Milestone 3: BFF Gateway & Live Dashboard**: FastAPI gateway, Authelia SSO header middleware, Server-Sent Events (SSE) `/api/v1/movies/events`, and pairing dashboard `/pair?magnet=...`.
- **Milestone 4: Edge Deployment & Production Packaging**: Multi-stage Dockerfiles, Docker Compose production stack with Traefik labels and healthchecks.
- **Milestone 5: Production Cross-Browser Extension Rollout**: Extension packaging for Firefox AMO / Chrome Web Store, magnet link redirection, and context menus.
---
## 🛠️ Canonical Guides & Runbooks
No canonical operational runbooks written yet.
---
## 🏛️ Completed Milestones & Resolved Discussions
Archived and foundational documentation for completed milestones:
### Completed Milestones
* 🟢 **Milestone 1: Workspace & Protobuf Contracts** — Hermetic `nix develop` environment, `uv` workspace, `pipeline.proto` definitions with gRPC service contracts, and automated stub generation via `buf.yaml`.
-114
View File
@@ -1,114 +0,0 @@
---
type: project
status: active
tags:
- praxis
- workout-tracker
- homelab
- architecture
- python
- fastapi
---
# 🏋️ Praxis
> *Praxis* (from Greek/Latin for *"the practical application of a plan"*) is a self-hosted workout execution and habit-tracking platform designed for homelab deployment.
Unlike conventional fitness apps that conflate planned routines with actual performance or impose punitive streak mechanics, Praxis is built around a strict **Three-Layer Temporal Model** and a clean hexagonal architecture.
---
## 🏛️ Overview & System Topology
Praxis is architected around a strict separation of concerns across three temporal layers:
```mermaid
flowchart TD
subgraph Layer1["1. Prescription (What was planned)"]
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
```
1. **Prescription Layer (What was planned)**:
- Reusable `Routine` templates defining weekly schedules (`Monday`–`Sunday`), target exercises, reps/ranges, weights, durations, activities (warm-ups, cardio), and calendar-week progression phases.
2. **Performance Layer (What actually happened)**:
- Concrete `WorkoutSession` instances created upon initiation. Each session freezes an immutable `SessionPrescriptionSnapshot` while providing total runtime autonomy to log sets, adjust weights/reps, swap exercises, or add unscheduled movements without mutating the routine template.
3. **Analysis Layer (What can be derived)**:
- Factual, deterministic observations (adherence rates, workload volumes, progression curves) derived purely from historical session logs rather than mutable counters.
### Core Domain Invariants
- **Snapshot Immutability**: When a session is initiated, its prescribed targets are frozen. Future modifications to routines never alter past or in-progress workouts.
- **Session Autonomy**: The routine is a guide, not a tyrant. Users can adjust sets/reps on the fly, substitute movements, or record ad-hoc workouts.
- **Substituted History Isolation**: Substituted exercises contribute strictly to the history of the *performed* movement, leaving the originally planned exercise clean while preserving the substitution audit trail.
- **Factual Adherence**: Consistency is measured via distribution rates (`Completed`, `Partially_Completed`, `Skipped`, and `Set Adherence Rate`) rather than fragile binary streaks.
- **Decoupled Identity**: Business logic depends only on internal `UserId`. External authentication (Authelia forward-auth headers, LLDAP) is isolated behind an `AuthProvider` port.
---
## 📍 Source Code & Locations
| Target | Location / URL | Description |
| :--- | :--- | :--- |
| **Primary Forge (Upstream)** | [Gitea (praxis)](https://gitea.roadtotech.me/kiskaadee/praxis) | Canonical upstream Git repository hosted on Homelab Gitea |
| **GitHub Mirror** | [GitHub (praxis)](https://github.com/kiskaadee/praxis) | Automated public push mirror on GitHub |
| **Clone (SSH)** | `ssh://git@gitea.roadtotech.me:2223/kiskaadee/praxis.git` | Developer clone URL via Gitea SSH (port 2223) |
| **Workstation Path** | `~/Projects/active/praxis` | Active development checkout on local workstation |
| **Deployment Target** | Homelab Micro-Server | Dockerized application stack integrated with Traefik & Authelia SSO |
---
## 💬 Open Discussions
*Currently no open discussions.* Architectural evaluations regarding domain boundaries, snapshot mutability semantics, and metric models have been consolidated into the active specifications below.
---
## 🚧 Work in Progress (Active Plans)
Implementation roadmaps and specifications currently active (`status: active`):
1. 🟡 [**Praxis Software Requirements Specification (SRS) v1.0.2**](../../01-plans/praxis/praxis-srs-v1.0.2.md) `[Active]`
- Baseline requirements defining the Three-Layer Temporal Model, multi-modal logging, session snapshot lifecycle, set-intent completion policies, and factual adherence metrics.
2. 🟡 [**Praxis Domain Model & OOP Design Specification v1.0.1**](../../01-plans/praxis/praxis-domain-model-v1.0.1.md) `[Active]`
- Approved domain aggregates (`Routine`, `WorkoutSession`, `Exercise`), value objects, behavioral contracts, state transition matrices, and hexagonal port interfaces (`AuthProvider`, SQL repositories).
3. 🟡 [**Praxis Implementation Blueprint (v0.2.0 — Phase 0 Complete)**](../../01-plans/praxis/praxis-implementation-blueprint.md) `[Active — Phase 1 Start]`
- Concrete Python decisions translating SRS + Domain Model: package structure, dependency direction, immutability strategy, ID representation, resolved ambiguities, toolchain configuration (ruff, pyright, pytest, 90% coverage gate), Git hooks, and Phase 1 implementation order.
---
## 🛠️ Canonical Guides & Runbooks
*Operational runbooks and developer setup guides will be established during the implementation phase.*
---
## 🏛️ Completed Milestones & Resolved Discussions
Archived baseline drafts preserved for historical reference and comparison:
- [Praxis Software Requirements Specification v1.0.0 (Archived Baseline)](../../01-plans/praxis/praxis-srs.md) — Initial draft prior to snapshot mutability refinement and activity formalization.
- [Praxis Domain Model & OOP Design Specification v1.0.0 (Archived Baseline)](../../01-plans/praxis/praxis-domain-model.md) — Initial domain model draft prior to exercise aggregate root promotion and snapshot consolidation.
+213 -126
View File
@@ -1,122 +1,102 @@
# Brain — AI Agent Guide
This repository is a personal knowledge graph organized strictly around the **epistemic role** of information in the engineering lifecycle. It is a durable store of structured information across discrete cognitive categories.
This repository is a personal knowledge graph. It is not a residency dashboard, a project tracker, or an Obsidian vault. It is a durable store of structured information across multiple types.
---
## Repository Purpose
The Brain organizes information into seven numbered lifecycle directories:
The Brain stores five fundamentally different kinds of information:
| Directory | Semantic Role | Contains |
| :---------------- | :------------------ | :------------------------------------------------------------------------------------------------------- |
| `00-inbox/` | **Capture** | Unprocessed, ephemeral captures — no classification or metadata required. |
| `01-plans/` | **Intent** | Actionable implementation roadmaps, specifications, and execution blueprints (`type: plan`). |
| `02-discussions/` | **Exploration** | Prospective inquiries, architectural options evaluations, and trade-offs (`type: discussion`). |
| `03-records/` | **History** | Historical memory: journals, incident RCAs, and ADRs (`type: journal \| debug \| decision`). |
| `04-learning/` | **Understanding** | Durable knowledge (`knowledge/`), operational SOPs (`guides/`), and deliberate practice (`practice/`). |
| `05-agents/` | **Machine Context** | Canonical store of AI agent profiles (`profiles/`) and operational skills (`skills/`). |
| `06-projects/` | **System Hubs** | Project topology hubs, forge repository mappings, and cross-cutting index entrypoints (`type: project`). |
| Directory | Contains |
| :--- | :--- |
| `inbox/` | Unprocessed captures — no classification required. Write first, classify later. |
| `knowledge/` | Durable understanding: concepts, technologies, and methods. |
| `projects/` | Contextual, project-specific documents. Each project owns its own sub-folder. |
| `records/` | Historical artifacts: journals, discussions, decisions, experiments. |
| `practice/` | Algorithm exercises, LeetCode writeups, and implementation drills. |
---
## Semantic Contracts
### `00-inbox/`
Local, uncommitted zero-friction capture zone. If the type or destination of a document is not immediately obvious, or while drafting/capturing raw thoughts, it belongs here. Documents in `00-inbox/` sit outside the committed knowledge graph and are completely exempt from frontmatter, type, and link validation until curated and moved.
### `inbox/`
Local, uncommitted zero-friction capture zone. If the type or destination of a document is not immediately obvious, or while drafting/capturing raw thoughts, it belongs here. No metadata or classification is required at capture time. Documents in `inbox/` sit outside the committed knowledge graph until curated and moved into `knowledge/`, `projects/`, `records/`, or `practice/`.
### `01-plans/`
Actionable engineering roadmaps, milestone breakdowns, and phased technical executions answering: *"What do we intend to build or execute?"*
- *Project Locality*: Placed in `01-plans/<project>/[subsystem/]<filename>.md` (e.g. `01-plans/homelab/appctl/smart-deployment-pipeline.md`).
- *Frontmatter*: `type: plan`, `status: draft | active | completed | abandoned`, `project: <name>`.
- *Invariant*: **Lifecycle state is metadata, not folder placement.** Completed or abandoned plans remain in `01-plans/` with `status: completed` or `status: abandoned`. There is no `archive/` directory.
### `knowledge/`
Documents that answer: *"If I read this six months from now, will this help me understand something?"*
### `02-discussions/`
Architectural inquiries, problem statements, exploratory trade-off analyses, and evaluation of alternative paths (Model A vs. Model B) answering: *"Why and what if?"*
- *Format*: Problem Statement → Context & Analysis → Options Evaluation (Pros & Cons) → Consensus / Resolution.
- *Lifecycle*: Discussions are **permanent historical explorations**. When consensus is reached, the document is updated to `status: resolved` and explicitly links forward to the resulting plan (`01-plans/...`) or decision (`03-records/decisions/...`). It is never deleted or moved into an archive.
- *Frontmatter*: `type: discussion`, `status: open | resolved`, `project: <name>`, `date: YYYY-MM-DD`.
Sub-directories:
- `concepts/` — Disciplinary concepts and algorithms (e.g., binary search, data structures).
- `technologies/` — Tool- and language-specific knowledge (e.g., Python, Docker, tmux).
- `methods/` — Backend engineering practices and methodologies (e.g., testing, auth, SQL).
### `03-records/`
Historical memory and durable empirical records answering: *"What happened, when, and what was decided?"*
- **`journal/`** — Chronological personal/engineering daily logs (strictly named `YYYY-MM-DD.md`, `type: journal`).
- **`debug/`** — Empirical incident post-mortems, regressions, and root-cause analyses of broken systems (strictly dated `YYYY-MM-DD-<slug>.md`, `type: debug`).
- **`decisions/`** — Architectural Decision Records (ADRs) capturing point-in-time commitments and consequences (`type: decision`, `status: proposed | accepted | superseded`).
Knowledge documents do not become the canonical location for project-specific information. A knowledge document describes *what something is*; a project document describes *how this project uses it*.
### `04-learning/`
Durable understanding, operational procedures, and deliberate drills answering: *"What do we understand and how do we operate it?"*
- **`knowledge/`** — Durable theoretical, technological, and methodological understanding:
- `concepts/` — Disciplinary ideas (algorithms, data structures).
- `technologies/` — Tool and language references (Python, Docker, Nix).
- `methods/` — Backend engineering practices (testing, auth, SQL).
- **`guides/`** — Practical standard operating procedures (SOPs) and runbooks explaining how to **use and maintain** existing capabilities (`04-learning/guides/<project>/<slug>.md`, `type: guide`).
- **`practice/`** — Deliberate algorithm implementation drills (LeetCode writeups and Python test fixtures with isolated Nix devShell).
### `projects/`
Each project lives in its own sub-folder (e.g., `projects/homelab/`, `projects/nixos/`, `projects/magnetflix/`). The canonical entrypoint and landing page for any project must always be named `README.md` (e.g., `projects/homelab/README.md`) so that documentation renderers (such as `doc2site`) automatically compile it as the directory's index/landing page. Do not use `overview.md`.
### `05-agents/`
Canonical store of AI agent profiles, instructions, operational boundaries, and guardrails across projects and workstations.
- **`README.md`** — Structural catalog of all configured agents and target workspaces.
- **`profiles/`** — Machine-readable agent persona specifications and safety guardrails (`05-agents/profiles/<name>.md`, `type: agent`, `kind: profile`).
- **`skills/`** — Reusable agent operational capabilities, packaged with human capability contracts (`05-agents/skills/<name>/README.md`, `type: agent`, `kind: skill`) and runtime specifications (`SKILL.md`).
#### Project Landing Page (`README.md`) Invariant
A project `README.md` is the user-facing entrypoint for that specific engineering project.
- **Never describe Brain conventions in a project README**: Do not explain vault taxonomies, frontmatter rules, or note-taking philosophies.
- **Required Sections**:
1. **Overview & System Topology**: Broad architectural explanation of the system, its layers, and core capabilities.
2. **Source Code & Locations**: Direct URLs to Git forge repositories (Gitea/GitHub), clone URLs, local workspace paths, and deployment targets.
3. **💬 Open Discussions**: Links *strictly* to unresolved discussions that have not yet produced an active implementation plan.
4. **🚧 Work in Progress (Active Plans)**: Links *strictly* to active plans (`status: active`) currently in progress or scheduled for execution.
5. **🛠️ Canonical Guides & Runbooks**: Operational procedures and step-by-step SOPs.
6. **🏛️ Completed Milestones & Resolved Discussions**: Historical reference section keeping completed roadmaps and foundational discussions organized without cluttering active WIP.
### `06-projects/`
Canonical project entrypoints and navigation hubs.
- **Structural Contract**: 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/`.
- **Role**: A project hub is a **graph navigation and index node**, not a document container. It describes system topology, source forge repositories, and indexes active plans, open discussions, and canonical guides across the vault.
#### Standard Project Directory Structure
Every project follows a three-part lifecycle structure under its folder:
1. **`discussions/` — "Why & What If?"**
- Architectural inquiries, problem statements, exploratory trade-off analyses, and evaluation of alternative paths (Model A vs. Model B).
- *Format*: Problem Statement → Context & Analysis → Options Evaluation (Pros & Cons) → Consensus / Resolution / Open Questions.
- *Lifecycle*: Open discussions remain active until consensus is reached, at which point they produce an actionable implementation plan.
- *Frontmatter*: `type: discussion`, `project: <name>`, `date: YYYY-MM-DD`.
2. **`plans/` — "How & When?"**
- Actionable implementation roadmaps, milestone breakdowns, and phased technical executions.
- *Prerequisite*: A plan should ideally be the concrete output of a resolved discussion.
- *Frontmatter*: `type: plan`, `status: draft | active | completed | abandoned`, `project: <name>`.
3. **`guides/` — "How to Use & Operate?"**
- Practical, operational runbooks and user-facing standard operating procedures (SOPs).
- *Content*: Answers concrete operational questions: *How to deploy a new service*, *How to rotate secrets*, *How to troubleshoot WAN rotation*. A guide explains how to **use and maintain** existing capabilities, not how to architect or implement new ones.
- *Frontmatter*: `type: guide`, `project: <name>`.
The folder establishes context (ownership/locality). The document's `type` field establishes its semantic role. Projects may reference documents in other projects via relative links.
### `records/`
Historical artifacts. The original messy thinking is worth preserving — often what you want to recover later is not just the conclusion, but *why* you reached it.
Sub-directories:
- `journal/` — Dated engineering journals and retrospectives.
- `discussions/` — Conversations that informed decisions or produced knowledge.
- `decisions/` — Architectural decision records.
- `experiments/` — Prototypes, runbooks, and technical investigations.
### `practice/`
Unchanged in structure. Contains LeetCode writeups and Python solution files with their own Nix devShell environment. Do not reorganize this directory without reading its `flake.nix`.
---
## Metadata Convention
Every committed Markdown document in the knowledge graph must have a YAML frontmatter block adhering to `DirectoryContract`:
Every committed markdown document in the knowledge graph must have a YAML frontmatter block. `type` is the only universally required field. All other fields are type-specific or optional metadata extensions. (Documents in `inbox/` are uncommitted staging drafts and are exempt from metadata enforcement until curated).
### Valid Types:
`knowledge`, `project`, `plan`, `guide`, `decision`, `journal`, `discussion`, `experiment`, `practice`, `reference`, `agent`, `debug`.
### Core & Optional Fields
- **`type`** *(Required)*: `knowledge`, `project`, `plan`, `guide`, `decision`, `journal`, `discussion`, `experiment`, `practice`, `inbox`, `reference`.
- **`tags`** *(Optional)*: List of keyword tags (e.g., `tags: [homelab, ddns, networking]` or YAML list format) applicable to any document type for cross-cutting discovery.
- **`project`** *(Optional)*: Project identifier (e.g., `project: homelab`, `project: dynu-monitor`, `project: bitetrack`) indicating context ownership.
- **`status`** *(Conditional)*: Lifecycle status for plans (`draft`, `active`, `completed`, `abandoned`), decisions (`proposed`, `accepted`, `superseded`), projects (`planned`, `active`, `paused`, `completed`), knowledge (`draft`, `stable`), and practice (`active`, `completed`).
### Frontmatter Templates
```yaml
# 01-plans
---
type: plan
status: draft | active | completed | abandoned
project: project-name
tags: [list, of, tags]
---
# 02-discussions
---
type: discussion
status: open | resolved
project: project-name
tags: [list, of, tags]
date: YYYY-MM-DD
---
# 03-records/journal
---
type: journal
date: YYYY-MM-DD
tags: [list, of, tags]
project: optional-project-name
---
# 03-records/debug
---
type: debug
date: YYYY-MM-DD
tags: [list, of, tags]
project: optional-project-name
---
# 03-records/decisions
---
type: decision
status: proposed | accepted | superseded
project: project-name
tags: [list, of, tags]
---
# 04-learning/knowledge
# knowledge
---
type: knowledge
status: draft | stable
@@ -126,14 +106,62 @@ related: [optional, relative, paths]
project: optional-project-name
---
# 04-learning/guides
# project (README.md landing pages)
---
type: project
status: planned | active | paused | completed
tags: [list, of, tags]
---
# plan
---
type: plan
status: draft | active | completed | abandoned
project: project-name
tags: [list, of, tags]
---
# guide
---
type: guide
project: project-name
tags: [list, of, tags]
---
# 04-learning/practice
# decision
---
type: decision
status: proposed | accepted | superseded
project: project-name
tags: [list, of, tags]
---
# journal (historical record)
---
type: journal
date: YYYY-MM-DD
tags: [list, of, tags]
project: optional-project-name
---
# experiment (prototypes, investigations, runbooks)
---
type: experiment
status: draft | active | completed
project: project-name
tags: [list, of, tags]
date: YYYY-MM-DD
---
# discussion (conversations, architectural evaluations)
---
type: discussion
project: project-name
tags: [list, of, tags]
date: YYYY-MM-DD
---
# practice
---
type: practice
status: completed | active
@@ -141,25 +169,17 @@ topics: [list, of, topics]
tags: [optional, tags]
---
# 05-agents/profiles & skills
# inbox (unprocessed captures)
---
type: agent
status: active | draft | archived
name: agent-slug
kind: profile | skill
target_workspace: /path/to/workspace
project: optional-project-name
type: inbox
created: YYYY-MM-DD
tags: [optional, tags]
---
# 06-projects (README.md only)
---
type: project
status: planned | active | paused | completed
tags: [list, of, tags]
project: optional-project-name
---
```
**Important:** Folder location does not automatically determine every metadata field. A document inside `projects/homelab/plans/` is a `plan`, not a `project`. The folder establishes context. The `type` field establishes semantic role.
---
## Link Conventions
@@ -167,13 +187,14 @@ tags: [list, of, tags]
- Use standard relative Markdown links for intra-vault files: `[text](../relative/path.md)`.
- Do not use Obsidian `[[double-bracket]]` syntax. The repository must be valid Markdown without Obsidian.
- **Cross-Repository Portability**: For links to files in separate repositories (e.g., `homelab-core`, `bitetrack-api`), use their public/forge Git URLs (e.g., `https://gitea.roadtotech.me/...` or `https://github.com/...`) or semantic code blocks. **Never use machine-specific absolute file URIs (`file:///...`)**.
- Always verify links before committing: `python scripts/validate-brain.py`.
- When reorganizing files, run `python scripts/validate-brain.py` to catch broken links before committing.
---
## Git Commit Standards
In this repository, commit types directly reflect the Brain's semantic taxonomy rather than generic code forge types (`docs:`):
In this repository, commit types directly reflect the Brain's semantic taxonomy rather than generic code forge types (`docs:`). Every commit must follow this format:
```
<type>(<scope>): <short description>
@@ -185,38 +206,104 @@ In this repository, commit types directly reflect the Brain's semantic taxonomy
| Type | Used For | Example |
| :--- | :--- | :--- |
| `plan` | Roadmaps, execution blueprints, milestones | `plan(homelab): define Stalwart mail server rollout` |
| `discussion` | Architectural inquiries, evaluations, trade-offs | `discussion(homelab): evaluate LLDAP vs Stalwart auth` |
| `journal` | Dated daily engineering journals | `journal: record daily log for 2026-09-28` |
| `debug` | Epistemic incident reports, postmortems, RCA logs | `debug(homelab): record gitops webhook signature mismatch rca` |
| `decision` | Architectural Decision Records (ADRs) | `decision(nixos): adopt standalone workstation model` |
| `knowledge` | Concepts, technologies, and backend methods | `knowledge(pytest): add fixture DI guide` |
| `plan` | Project roadmaps and implementation specs | `plan(homelab): define Stalwart mail server rollout` |
| `guide` | Practical SOPs, runbooks, and operation procedures | `guide(nixos): add terminal workspace walkthrough` |
| `discussion` | Architectural inquiries, evaluations, trade-offs | `discussion(homelab): evaluate LLDAP vs Stalwart auth` |
| `decision` | Architectural Decision Records (ADRs) | `decision(nixos): adopt standalone workstation model` |
| `journal` | Dated journals, post-mortems, RCA logs | `journal(homelab): record Gitea mirror DNS RCA` |
| `practice` | Algorithm writeups and LeetCode drills | `practice(leetcode): add 0075 sort colors solution` |
| `agent` | Agent specifications, behavioral guardrails, and role profiles | `agent(homelab): document homelab operations agent spec` |
| `project` | Project landing pages (`06-projects/*/README.md`) | `project(homelab): update active plans index` |
| `meta` | Brain governance, `AGENTS.md`, root docs | `meta(agents): establish numbered lifecycle taxonomy` |
| `infra` | Repository tooling, validator scripts, Nix flakes | `infra(validator): add DirectoryContract validation` |
| `meta` | Brain governance, `AGENTS.md`, taxonomies, root docs | `meta(agents): establish inbox curation protocol` |
| `infra` | Repository tooling, validator scripts, Nix flakes | `infra(validator): add broken link check` |
| `refactor` | Structural reorganization, directory restructurings | `refactor(homelab): move archive docs to project root` |
Keep commits atomic: one logical document addition or document + linked cross-reference update per commit.
---
## Structural Validator & Tests
## Structural Validator
Run before committing changes:
Run before committing structural changes:
```bash
python scripts/validate-brain.py
python scripts/test_validator.py
```
Checks: directory-type contracts, max depth, filename requirements, frontmatter presence, link resolution, code fences, Mermaid syntax, Ruff linting, and Pyright typing.
Checks: frontmatter presence, valid `type` fields, relative link resolution, no deprecated directories, required root files.
---
## Operational Skills
## AI Agent Artifact & Inbox Capture Protocol
To avoid draft fragmentation, shadow duplication, and excessive inbox maintenance:
1. **Skip Inbox Capture for Canonical Brain Documents**:
If an agent is creating or modifying a document that already has a designated home in `knowledge/`, `projects/`, `records/`, or `practice/`, **DO NOT** write a shadow copy or duplicate draft to `inbox/`. The document in the repository tree is the canonical source of truth.
2. **One Topic, One Draft (In-Place Evolution)**:
When generating artifacts for research, plans, or session summaries that belong in `inbox/`:
- Search `inbox/` for an existing file covering the current topic or session (e.g., `inbox/<topic>-notes.md`).
- If one exists, **update/overwrite that single file in-place** rather than creating new fragmented files (e.g., evolve the plan into the finalized walkthrough/summary).
- Never create parallel variations (such as `topic-plan.md`, `topic_plan.md`, `topic-walkthrough.md`, `walkthrough.md`).
3. **Session Consolidation**:
At the conclusion of any agentic workflow or task, ensure there is at most **one** comprehensive capture document in `inbox/` representing the session.
---
## Inbox Curation Protocol
When the user requests an inbox curation or maintenance pass (e.g., *"Curate the inbox"*, *"Process inbox"*, *"It's time to curate"*), agents must execute the following deterministic workflow:
### Step 1: Baseline Integrity Verification
Run the structural validator to verify a clean working state before making any modifications:
```bash
python scripts/validate-brain.py
```
If existing errors are found, address them or establish baseline awareness before proceeding.
### Step 2: Inbox Inventory & Draft Clustering
1. Inspect all pending files in `inbox/` (excluding `inbox/README.md` and `.gitignore`).
2. **Cluster by Topic & Session**: Identify multiple drafts or evolutionary iterations created for the same subject.
3. **Consolidation & Deduplication**:
- Consolidate iterative drafts into **one single comprehensive document** representing the final canonical knowledge.
- Keep multiple documents only when there is a distinct semantic separation across Brain types (e.g., an active `plan` vs. an architectural `discussion` vs. a retrospective `journal`).
- If ambiguous whether to merge or separate, **prompt the user** before proceeding.
### Step 3: Semantic Classification & Target Resolution
Map each consolidated document to its canonical destination following the [Semantic Contracts](#semantic-contracts):
- **`knowledge/`** — Durable concepts, tools, languages, and backend engineering methods.
- `concepts/` (algorithms, data structures, abstract theory)
- `technologies/` (tools, libraries, languages, CLI utilities)
- `methods/` (architecture patterns, testing, auth, SQL)
- **`projects/<project>/`** — Project-specific context. Place under `discussions/`, `plans/`, `guides/`, or update `README.md`.
- **`records/`** — Historical artifacts (`journal/`, `discussions/`, `decisions/`, `experiments/`).
- **`practice/`** — Algorithm drills and LeetCode writeups.
> [!NOTE]
> **Ambiguous Documents**: If a capture is incomplete or its target destination is ambiguous, propose the most logical target path to the user. Leave unconfirmed items in `inbox/` until clarified.
### Step 4: Frontmatter & Content Normalization
Transform the staging frontmatter into a valid schema-compliant metadata block:
1. Replace `type: inbox` with the canonical type (`knowledge`, `guide`, `plan`, `decision`, etc.).
2. Add appropriate `status` (`draft` or `stable`), `topics`, `tags`, `project`, or `date` identifiers.
3. Fix markdown parsing errors, heading levels, invalid code fences, or malformed links.
4. Ensure all internal links use standard relative Markdown paths (never `file:///` URIs).
### Step 5: Directory Placement & Cross-Reference Linking
1. Write the document to its designated canonical directory (create new directories when needed).
2. Remove the staging file(s) and any superseded drafts from `inbox/`.
3. Update relevant parent indices (e.g., project `README.md` sections) and link related existing knowledge notes (e.g., adding `related: [...]` and cross-reference links in sibling documents).
### Step 6: Atomic Git Commit
Create an isolated atomic commit for each curated document and any adjacent modified files using the [Semantic Commit Taxonomy](#git-commit-standards):
```bash
git add <target-file> [adjacent-modified-files...]
git commit -m "<type>(<scope>): <short description>"
```
*(Note: The Git pre-commit hook automatically executes `scripts/validate-brain.py` during `git commit`, ensuring schema and link integrity before each commit).*
### Step 7: Curation Summary
Present a clear summary of all curated documents, their target paths, and associated commit references to the user.
Procedural workflows and multi-step capabilities are maintained in the standalone [`skills`](https://github.com/kiskaadee/skills) repository and indexed in [05-agents/skills/README.md](05-agents/skills/README.md):
- **[Draft Curation](https://github.com/kiskaadee/skills/blob/main/extensions/draft-curation/SKILL.md)**: Scans `00-inbox/`, classifies raw notes into canonical lifecycle directories, injects valid YAML frontmatter, validates links, and executes atomic commits.
- **[Document](https://github.com/kiskaadee/skills/blob/main/skills/document/SKILL.md)**: Evaluates completed engineering sessions to determine whether durable knowledge was produced and selects the canonical epistemic container (Discussion, ADR, Plan, Debug Record, Knowledge).
- **[Git Commit & History Hygiene](https://github.com/kiskaadee/skills/blob/main/skills/git-commit/SKILL.md)**: Packages validated repository transitions into coherent, atomic Conventional Commits matching the Brain semantic taxonomy.
+66 -63
View File
@@ -1,94 +1,97 @@
# 🧠 Brain
A personal knowledge graph organized by document lifecycle and epistemic role, not by subject.
A personal knowledge graph organized by document type, not by subject.
---
## Structure
| Directory | Semantic Role | What it contains |
| :--- | :--- | :--- |
| [`00-inbox/`](00-inbox/) | **Capture** | Zero-friction, uncommitted staging zone. Write first, curate later. |
| [`01-plans/`](01-plans/) | **Intent** | Actionable implementation roadmaps, milestones, and design specs (`type: plan`). |
| [`02-discussions/`](02-discussions/) | **Exploration** | Prospective inquiries, architectural options evaluations, and trade-offs (`type: discussion`). |
| [`03-records/`](03-records/) | **History** | Historical memory: journals, incident post-mortems/RCAs, and ADRs (`type: journal \| debug \| decision`). |
| [`04-learning/`](04-learning/) | **Understanding** | Durable knowledge (`knowledge/`), operational SOPs/runbooks (`guides/`), and deliberate practice (`practice/`). |
| [`05-agents/`](05-agents/) | **Machine Context** | Canonical store of AI agent profiles (`profiles/`) and operational skills (`skills/`). |
| [`06-projects/`](06-projects/) | **System Hubs** | Project topology hubs, forge repository mappings, and cross-cutting index entrypoints (`type: project`). |
| Directory | What it contains |
| :--- | :--- |
| [`inbox/`](inbox/) | Zero-friction capture. Write here when you don't know where something belongs yet. |
| [`knowledge/`](knowledge/) | Durable understanding — things you know and want to keep. |
| [`projects/`](projects/) | Contextual documents that belong to a specific project. |
| [`records/`](records/) | Historical artifacts — things that happened. |
| [`practice/`](practice/) | Algorithm exercises and implementation drills. |
---
## 01. Plans
## Knowledge
Actionable engineering roadmaps and execution blueprints:
- **Homelab**: Architecture consolidation, Appctl v2 engine, Stalwart email, Diun alerting, security hardening.
- **NixOS**: Workstation decoupling, secret restructuring, channel migrations.
- **Praxis**: Workout tracking software requirements and domain design baseline.
- **MagNetFlix**: Media indexing and browser extension pipeline.
- **Supervisor**: Engineering supervisory system and progress tracker.
```
knowledge/
├── concepts/ ← Disciplinary ideas: algorithms, data structures
├── technologies/ ← Tool and language knowledge: Python, Docker, Nix, tmux
│ └── python/
└── methods/ ← Backend practices: testing, auth, SQL, CI/CD, ADRs
```
**Key documents:**
- [Binary Search](knowledge/concepts/binary-search.md)
- [HashMap](knowledge/concepts/hashmap.md)
- [Pydantic](knowledge/technologies/python/pydantic.md)
- [Docker](knowledge/technologies/docker.md)
- [Authentication & JWT](knowledge/methods/auth.md)
- [SQL](knowledge/methods/sql.md)
- [Testing](knowledge/methods/testing.md)
- [CI/CD & GitOps](knowledge/methods/cicd-fundamentals-and-gitops.md)
---
## 02. Discussions
## Projects
Permanent records of architectural inquiries and prospective options evaluations:
- [GitOps Dispatcher Architecture](02-discussions/homelab/gitops-dispatcher-architecture.md)
- [NixOS Monorepo vs. Multi-Repo](02-discussions/homelab/nixos-monorepo-vs-multirepo.md)
- [Stalwart vs. Hostinger Email Evaluation](02-discussions/homelab/hostinger-vs-stalwart-email-evaluation.md)
- [Assistant Chatbot Architecture](02-discussions/homelab/chatbot-assistant-design.md)
- [Brain Structural Validator Refactoring](02-discussions/brain/validate-brain-refactor-architecture.md)
```
projects/
├── nixos/ ← Declarative multi-machine OS fleet & flake architecture
│ └── plans/ ← Migration and optimization roadmaps
├── homelab/ ← Infrastructure, Docker services, appctl, GitOps, networking
│ ├── plans/ ← Migration and strategy documents
│ └── guides/ ← Architecture and runbook documents
├── dynu-monitor/ ← Smart DDNS change detection daemon (Python/Rust)
├── new-repo/ ← Automated repository provisioning CLI
├── magnetflix/ ← Media indexing and streaming application
├── nekoweb/ ← Web showcase and static site generation
└── supervisor/ ← Personal engineering progress tracking & supervisory system
```
**Key documents:**
- [NixOS Fleet Overview](projects/nixos/README.md)
- [Homelab Overview](projects/homelab/README.md)
- [Dynu Monitor Overview](projects/homelab/plans/dynu-monitor/README.md)
- [New-Repo CLI Overview](projects/nixos/new-repo/README.md)
- [MagNetFlix Overview](projects/magnetflix/README.md)
- [Nekoweb Overview](projects/nekoweb/README.md)
- [Supervisor Overview](projects/supervisor/README.md)
---
## 03. Records
## Records
Historical memory and durable empirical records:
- **Journals (`03-records/journal/`)**: Dated daily engineering retrospectives (`YYYY-MM-DD.md`).
- **Incidents & Post-mortems (`03-records/debug/`)**: Empirical RCAs of system failures, regressions, and remediations.
- **Decisions (`03-records/decisions/`)**: Immutable Architectural Decision Records (ADRs).
```
records/
└── journal/ ← Dated engineering retrospectives
```
---
## 04. Learning
## Practice
Durable concepts, operational procedures, and deliberate practice:
- **Knowledge (`04-learning/knowledge/`)**:
- `concepts/` — Algorithms, data structures (Binary Search, HashMaps).
- `technologies/` — Tool and language understanding (Python, Docker, Nix, tmux).
- `methods/` — Engineering methodologies (Testing, Auth, SQL, CI/CD, Tag extraction).
- **Guides (`04-learning/guides/`)**: Operational SOPs and standard runbooks (`appctl`, GitOps pipelines, rDNS relay, server maintenance).
- **Practice (`04-learning/practice/`)**: LeetCode writeups and Python solution suite with its own Nix flake environment.
```
practice/
└── LeetCode/
├── 00-practiced-patterns.md ← Pattern index
├── 0001-two-sum.md
└── Solutions/ ← Python solution files
```
---
## 05. Agents Store
## Conventions
Declarative specifications and behavioral guardrails for AI agents across workstations:
- [Homelab Operations](05-agents/profiles/homelab-operations.md)
- [Homelab Core Platform](05-agents/profiles/homelab-core.md)
- [NixOS Mobile Workstation](05-agents/profiles/nixos-workstation.md)
- [MagNetFlix Media Pipeline](05-agents/profiles/magnetflix.md)
- [NekoWeb Manga Platform](05-agents/profiles/nekoweb.md)
- [Second Brain Knowledge Graph](05-agents/profiles/second-brain.md)
Every document has a `type` field in its YAML frontmatter. See [AGENTS.md](AGENTS.md) for the full metadata convention, directory semantics, link standards, and git commit format.
---
## 06. Projects
## Inbox
Canonical entrypoints describing system topology, source code repositories, and cross-cutting index links:
- [Homelab Ecosystem Hub](06-projects/homelab/README.md)
- [NixOS Fleet Hub](06-projects/nixos/README.md)
- [Praxis Platform Hub](06-projects/praxis/README.md)
- [MagNetFlix Hub](06-projects/magnetflix/README.md)
- [NekoWeb Hub](06-projects/nekoweb/README.md)
- [New-Repo CLI Hub](06-projects/new-repo/README.md)
- [Supervisor Hub](06-projects/supervisor/README.md)
- [Second Brain Tooling Hub](06-projects/brain/README.md)
- [AMC Solutions — Digital Discovery](06-projects/amc-solutions-seo/README.md)
- [Novias del Gato Hub](06-projects/gatos-tejada/README.md)
---
## Governance & Rules
See [AGENTS.md](AGENTS.md) for metadata conventions, directory structural contracts, link standards, and Git commit guidelines.
Documents that haven't been classified yet live in [`inbox/`](inbox/). See [`inbox/README.md`](inbox/README.md) for the capture rule.
File renamed without changes.
File renamed without changes.
Loaded 100 of 246 files, more files were not shown because too many files have changed in this diff. Show more