Compare commits

..
Author SHA1 Message Date
kiskaadee 4a9ed7118f knowledge(doggo): document dns diagnostics and troubleshooting guide
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
2026-11-03 00:18:48 -05:00
kiskaadee 6258579fd6 plan(rtt-agency): record empirical postmortem for armonia frontend collaboration pilot
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
2026-10-29 13:41:38 -05:00
kiskaadee 67732d30c0 plan(skills): anchor database url to absolute path in roster verification script
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
Ensure settings.database_url resolves to abs_db_path instead of db_filename in pilot-verification-packet-roster.md, aligning with os.environ['DATABASE_URL'] and guaranteeing deterministic database path anchoring during execution.
2026-10-26 09:33:15 -05:00
kiskaadee e134d292fd plan(skills): tighten contracts, seed safety, and governance in collaboration pilot
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
- Pin 409 conflict detail string matching to backend commit d9c86e27 in workshop roster spec
- Add absolute path anchoring and non-test database guardrails to QA seed script
- Formalize three-stage owner approval sequence in pre-experiment baseline
2026-10-26 09:19:41 -05:00
kiskaadee 1148cc19c8 plan(skills): add frontend collaboration pilot plans and verification contracts
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
- Establish rtt-agency workflow subsystem under 01-plans/skills
- Relocate pre-experiment baseline for frontend collaboration pilot and add commit discipline metric
- Add group workshop roster pilot collaboration plan, specification contract, and QA verification packet
2026-10-26 08:46:31 -05:00
kiskaadee 4006ee557a plan(skills): relocate nix devshell spec to nix-skills subsystem
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
Move nix-devshell-authoring-and-architecture-spec.md under the
nix-skills subsystem directory to keep skill plans structured.
2026-10-26 08:45:07 -05:00
kiskaadee 36b5eaa798 plan(skills): refine hypothesis rigor and epistemic distinctions in pilot baseline
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 9s
- Separate observed workflow omissions from causal inferences in problem statement
- Narrow Hypothesis 1 to evaluate requirements/UX separation as an explicit design choice
- Add falsifiability requirement to freeze Anne's self-audit prior to independent QA
2026-10-25 14:15:14 -05:00
kiskaadee 6d7e1bd69f infra(obsidian): disable prompt on note deletion
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
2026-10-25 14:05:03 -05:00
kiskaadee 6bb157b251 knowledge(testing): add guide on AST mutation testing with strict models
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
- Document practical failure modes of mutmut with Python 3.10+ syntax and Pydantic v2 extra="forbid"
- Explain AST transformation mechanics vs metaclass validation at import time
- Provide patterns for separating domain validation from mutation harnesses
2026-10-25 13:18:50 -05:00
kiskaadee 7489c1f448 plan(skills): record frontend collaboration pilot pre-experiment baseline
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 9s
- Establish verifiable repository baselines across armonia-dashboard, armonia-api, and .profile
- Document historical context and root cause of M4 operator workflow omissions
- Define 5-phase pilot protocol covering spec contracts, isolated worktree implementation, and implementation-blind QA
- Establish escalation boundaries and hypothesis evaluation metrics for agent collaboration in skills
2026-10-25 13:17:23 -05:00
kiskaadee 9f623c8147 debug(skills): record nix-devshell dogfooding verification report
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
- Record empirical test ledger across 10 acceptance scenarios executed via fresh-context subagents.
- Document verified tool outputs, common audit gates, and Linux-centric runtime boundaries.
2026-10-23 15:06:15 -05:00
kiskaadee bc3817b332 discussion(skills): analyze failure domains in agent skill synthesis
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
- Examine failure modes across source corpus compilation, build workflows, model biases, and skill structural sizing.
- Document procedural root and on-demand reference design pattern to prevent prompt bloat.
2026-10-23 15:06:01 -05:00
kiskaadee f29712544b plan(skills): record nix-devshell authoring specification
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
- Document approved technical specification and source authority hierarchy for the nix-devshell skill.
- Define 4-level progressive validation semantics and strict Git ownership boundaries.
2026-10-23 15:05:43 -05:00
kiskaadee 174a1cb993 discussion(homelab): explore MCP tool gateway and platform governance
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 6s
- Evaluate trade-offs between dedicated autonomous deployment agents and an MCP protocol gateway over appctl.
- Analyze state separation: Git for desired state vs operational database for observed telemetry.
2026-10-23 15:05:28 -05:00
kiskaadee 1b6d64077a plan(homelab): define Dynu to Cloudflare authoritative DNS cutover
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
- Specify 4-phase execution roadmap from Dynu to Cloudflare DNS using flarectl, hostinger, and doggo.
- Enforce grey-cloud proxying invariants and in-memory credential safety wrappers.
2026-10-23 15:05:14 -05:00
kiskaadee 6933c21e9f project(armonia-del-ser): initialize ecosystem topology and multi-repo hub
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
- Add project landing hub detailing 4 decoupled repositories (armonia-api, armonia-dashboard, armonia-landing, armonia-del-ser).
- Document business context, operational buffer rules, bash free-tier cloud architecture, and 48-hour follow-up queue.
2026-10-23 15:05:00 -05:00
kiskaadee b8bd12cd2b decision(homelab): align control plane ADR and project hub with Roadmap v6
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
Reconcile ADR-0002 (homelab-appctl-control-plane-architecture.md) and related cross-references with locked decisions DEC-01 through DEC-05:

- Update ADR-0002 to codify single POST /v1/operations endpoint across dual HTTP/1.1 transports, Bearer token auth + SO_PEERCRED viewer fallback, dedicated homelab-appctl service isolation, and fail-closed audit log.
- Align Roadmap v6, evolutionary knowledge article, and discussions to reference 13 canonical domain operations.
- Update 06-projects/homelab README to index active discussions and categorize superseded appctl refactoring plans.
2026-10-17 14:39:32 -05:00
kiskaadee b885fcf056 plan(brain): specify scaffolded learning contracts and workflow design
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
Curate the foundational discussion and phased execution plan for a learning-centered engineering workflow across agent skills:

- Ground the architecture in cognitive science and instructional design principles (generation effect, testing effect, desirable difficulties, and expertise reversal).
- Establish explicit delivery vs. learning mode operational contracts.
- Define activity adapters for project commits, courses, LeetCode drills, and hypothesis planning.
- Plan a 4-phase rollout to introduce authoring/scaffolding modes to git-commit, journal-builder, and practice.
2026-10-17 07:41:06 -05:00
kiskaadee d5b03ebf1a discussion(agents): explore persistence and asynchronous coordination models
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
Investigate trade-offs for cross-session continuity and memory horizons when collaborating with autonomous subagents:

- Contrast biological stigmergy and human engineering team practices with ephemeral model memory amnesia.
- Evaluate three architectural paths: forge-native stigmergy (Gitea issues and PR comments via tea CLI), dedicated vault memory via MCP, and an autonomous containerized daemon.
- Establish an epistemic separation between persistent repository contracts, actionable single-response tasks, in-line diff critiques, and session reasoning.
- Converge on forge-native coordination for immediate integration.
2026-10-17 07:21:14 -05:00
kiskaadee 563d4abd41 knowledge(homelab): document control plane evolution from v1 to v6
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
Synthesize the multi-era architectural evolution of Homelab Core across versions v1 through v6:

- Document the transition from ad-hoc bash automation (v1) to structural hardening (v2), state/mail isolation (v3), 3-tier provenance (v4), control plane daemon vision (v5), and fail-closed operational reality (v6).
- Codify key lessons: boundaries preceding implementation, the illusion of local trust, fail-closed design, and evolutionary learning.
- Provide a detailed comparison matrix across all six architectural eras.
2026-10-17 07:11:42 -05:00
kiskaadee f7d0e0c2d8 plan(homelab): adopt control plane roadmap v6 and supersede v5
Brain Structural Validation / Validate Markdown Structure & Links (push) Failing after 7s
Synchronize Homelab Core architecture consolidation roadmap with locked decisions DEC-01 through DEC-05 and the updated Milestone P4 plan:

- Establish single typed POST /v1/operations command dispatcher over dual transports (HTTP/1.1 over Unix domain socket and loopback TCP).
- Enforce mandatory SOPS Bearer tokens for mutations and sensitive reads, restricting UDS SO_PEERCRED fallback to non-sensitive viewer operations.
- Require dedicated homelab-appctl service isolation and append-only audit telemetry with fail-closed disk guard.
- Unify GitOps worker execution through daemon workload.update over UDS.
- Eradicate shell source/eval in favor of pure-Python environment assembly and pre-flight Compose AST security validation.
- Mark Roadmap v5 as superseded and update 06-projects/homelab index.
2026-10-17 07:04:39 -05:00
kiskaadee c87ecc7931 plan(brain): update anne-droid integration plan with communication triage and worktree runbook
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
2026-10-16 14:39:23 -05:00
kiskaadee 0cfe57e7d3 project(gatos-tejada): codify Jev cascade triage ADR in project hub
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
2026-10-13 07:35:12 -05:00
kiskaadee d812d46d2c project(gatos-tejada): establish canonical project hub and index in root
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 7s
- Create 06-projects/gatos-tejada/README.md detailing topology, PostGIS/pgvector persistence, SSO adapter architecture, and consensus engine.
- Index Novias del Gato project in root README.md under 06. Projects.
2026-10-13 06:58:21 -05:00
kiskaadee b14bd02b16 journal: record daily log for 2026-10-07
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 9s
2026-10-11 16:45:45 -05:00
kiskaadee bc33df485b discussion(homelab): record control plane modernization
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 12s
2026-10-11 16:44:41 -05:00
kiskaadee adfb2a173f project(new-repo): document python 3 architecture pivot and mark rust plan superseded
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
- Update project hub overview, sequence diagram, and security model to reflect zero-dependency Python 3 CLI in ~/Config/home/scripts/new-repo.py.
- Mark compiled Rust implementation plan as superseded.
2026-10-10 00:27:13 -05:00
kiskaadee 5077a55b63 project(amc-solutions-seo): establish digital discovery hub and index in root
- Create project hub defining scope, research questions, evidence directory structure, and forge link.
- Index project hub under Canonical Project Hubs in root README.
2026-10-10 00:26:37 -05:00
kiskaadee acaa3740f5 infra(git): ignore obsidian base files in .gitignore
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
2026-10-08 00:14:09 -05:00
kiskaadee dc47898a9b plan(brain): specify anne droid agent persona and gitea integration
Brain Structural Validation / Validate Markdown Structure & Links (push) Successful in 8s
- Specify persona architecture, authority boundaries, and review gates for Anne Droid.
- Define Gitea forge integration, feat/anne/* branch convention, and PR review checklist.
2026-10-08 00:09:20 -05:00
kiskaadee f0f4c31811 plan(homelab): define architecture consolidation and control plane roadmap v5
- Add comprehensive v5 roadmap unifying appliance baseline and phases P0-P4 for the appctl control plane.
- Mark superseded plans (roadmap v4, implementation guide v3, appctl engine v2, and smart deployment pipeline) with forward references to roadmap v5.
2026-10-08 00:04:59 -05:00
kiskaadee 2f71cd23e8 decision(homelab): adopt daemon control plane architecture and typed execution engine
- Establish ADR transitioning appctl from ad-hoc host CLI execution to a stateful control-plane daemon (appctld).
- Define Unix domain socket / mTLS transport, typed provenance domain models, and decoupled CLI ergonomics.
- Isolate unprivileged interactive commands from root-level container orchestration.
2026-10-08 00:03:56 -05:00
kiskaadee dde63d6e13 decision(brain): adopt pedagogical decoupling and governance for agent skills
- Establish architectural decision separating portable core skills from vault extensions.
- Codify human-in-the-loop apprenticeship guardrails ("Your call") to prevent comprehension illusions.
- Mandate public domain licensing (Unlicense) and semantic path resolution.
2026-10-08 00:03:02 -05:00
kiskaadee e9c461d6fc journal: record daily log for 2026-10-05
- Document engineering wins around skills repository decoupling, learning theory, and unlicense adoption.
- Record journal-builder specification, formative feedback loop, and second brain sync.
- Log graphify A/B benchmark review against bdinvite codebase.
2026-10-07 23:56:35 -05:00
37 changed files with 4221 additions and 33 deletions

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
.obsidian/graph.json .obsidian/graph.json
.DS_Store .DS_Store
.trash/ .trash/
*.base
# Environments & Python # Environments & Python
.envrc .envrc
+2 -1
View File
@@ -1,3 +1,4 @@
{ {
"alwaysUpdateLinks": true "alwaysUpdateLinks": true,
"promptDelete": false
} }
@@ -0,0 +1,186 @@
---
type: plan
status: active
project: brain
date: 2026-10-07
tags:
- agent-architecture
- persona
- gitea
- frontend
- multi-agent
---
# Anne Droid Agent Persona & Gitea Integration Roadmap
> **Target System**: Local Antigravity development environment and self-hosted Gitea forge (`gitea.roadtotech.me`).
> **Role & Persona**: Anne Droid — Senior Frontend Engineer & UX Specialist.
---
## Executive Summary
This plan operationalizes **Anne Droid** as an autonomous, persistent engineering collaborator for Frontend development, user interface interaction, and UX review. Anne is not a procedural skill; she is an agent persona with dedicated authority boundaries, isolated Gitea credentials, and genuine version control provenance.
The primary operational outcomes:
1. Genuine forge provenance on `gitea.roadtotech.me` via dedicated user `anne-droid`, ed25519 SSH authentication on port 2223, and `tea` CLI integration.
2. Safe Branch & PR Autonomy: Anne implements UI code on `feat/anne/*` branches and opens PRs without having permission to commit to `main`, merge PRs, or alter backend logic autonomously.
3. A formal "Frontend → Backend Feedback" loop providing structured, consumer-perspective reviews of backend endpoints and schemas.
4. Clean integration within the portable skills repository (`profile/agents/anne-droid.md`) and Antigravity subagent registry.
---
## 1. Technical Specifications & Contracts
### System Topology
```mermaid
flowchart TD
User["Human Lead / Backend Engineer"]
MainAgent["Main Agent (Orchestrator)"]
AnneSubagent["Anne Droid (Subagent)"]
GiteaForge["Gitea Forge (gitea.roadtotech.me:2223)"]
RepoWorkspace["Local Project Workspace"]
User <-->|"Architectural Review & Merges"| MainAgent
MainAgent -->|"Consult (Advisory Mode)"| AnneSubagent
MainAgent -->|"Delegate (Implementation Mode)"| AnneSubagent
AnneSubagent -.->|"API Friction Report / UX Audit"| MainAgent
AnneSubagent -->|"Branch: feat/anne/*"| RepoWorkspace
AnneSubagent -->|"Commit: Author Anne Droid"| RepoWorkspace
AnneSubagent -->|"Push: SSH Key id_ed25519_anne_droid"| GiteaForge
AnneSubagent -->|"PR Creation: tea CLI"| GiteaForge
GiteaForge -->|"Code Review & PR Merge"| User
```
### Component Taxonomy & Authority Matrix
| Domain | Action | Permitted? | Constraints / Execution Rule |
| :--- | :--- | :--- | :--- |
| **Git Branches** | Create / Checkout | ✅ Yes | Naming strictly constrained to `feat/anne/*`, `fix/anne/*`, `ux/anne/*` |
| **Git Commits** | Author commit | ✅ Yes | Conventional Commits; authored as `Anne Droid <anne-droid@roadtotech.me>` |
| **Git Remote** | Push | ✅ Yes | Allowed only to own feature branches on remote forge |
| **Git PRs** | Open / Update | ✅ Yes | Opened via `tea pr create --login anne-droid` with descriptive summaries |
| **Git Governance**| Direct commit to `main` | ❌ No | Strictly forbidden; raises hard constraint failure |
| **Git Governance**| Merge PRs | ❌ No | Strictly forbidden; only repository owner merges into `main` |
| **Git Safety** | Destructive git commands | ❌ No | Strictly forbidden (`reset --hard`, force-push, `clean -fd`) |
| **Code Scope** | Frontend components & CSS | ✅ Yes | React, HTML, CSS, client styling, client unit/integration tests |
| **Code Scope** | Backend & Database code | ❌ No | Read-only access to inspect contracts; no unilateral modifications |
| **Architecture** | API Feedback | ✅ Yes | Emits advisory "Frontend → Backend Feedback" reports or opens issues |
| **Infrastructure** | System / Deploy / NixOS | ❌ No | Strictly forbidden |
### Git & Forge Authentication Contract
- **Forge User**: `anne-droid` (ID 2 on `https://gitea.roadtotech.me`).
- **SSH Key Pair**: `~/.ssh/id_ed25519_anne_droid` (Public Key ID 3 on Gitea).
- **SSH Transport**: Scoped command bypassing global Nix-managed config:
```bash
GIT_SSH_COMMAND="ssh -F /dev/null -p 2223 -i ~/.ssh/id_ed25519_anne_droid -o IdentitiesOnly=yes"
```
- **Commit Identity Variables**:
```bash
GIT_AUTHOR_NAME="Anne Droid"
GIT_AUTHOR_EMAIL="anne-droid@roadtotech.me"
GIT_COMMITTER_NAME="Anne Droid"
GIT_COMMITTER_EMAIL="anne-droid@roadtotech.me"
```
- **CLI Management**: Authenticated profile in `tea` CLI:
```bash
tea login add --name anne-droid --url https://gitea.roadtotech.me --token <TOKEN>
```
---
## 2. Working Rules & Coordination Constraints
1. **One Owner per Capability**:
Anne does not duplicate procedural skills. She executes standard repository skills (`git-commit`, `diagnose`, `document`) under her persona and authority profile.
2. **Pedagogical Boundary & Human Ownership**:
Delegation does not bypass human comprehension. The human lead reviews diffs and owns PR merge decisions.
3. **Communication & Documentation Triage**:
Anne rigorously separates persistent knowledge from transient action items to prevent repository and issue bloat:
- **Persistent Documentation (`docs/`)**: Architecture, design tokens, and durable contracts that must be read repeatedly across sessions are committed directly to the repo.
- **Actionable Forge Issues (`tea issues create`)**: Single-action follow-ups that must be answered once. Filtered strictly to critical triggers: breaking contract/schema changes, security/auth boundaries, or severe client UX/performance degradation.
- **In-Line PR Reviews**: Minor, non-breaking design notes or line queries stay in the active PR discussion.
- Anne never edits backend files directly and never leaves untracked conversational scratchpads in the repository root.
4. **Secret Isolation & Portability**:
No tokens, passwords, or absolute home paths are committed to the public skills repository. All persona rules use relative or tilde-expanded paths.
---
## 3. Phased Implementation Roadmap
| Phase | Status | Deliverables | Verification Gates |
| :--- | :--- | :--- | :--- |
| **P0: Forge Identity & Keys** | Completed | User `anne-droid`, SSH key pair, public key upload | `ssh -p 2223 git@gitea.roadtotech.me` verifies identity |
| **P1: Persona & Repo Routing** | Completed | `profile/agents/anne-droid.md`, `profile/AGENTS.md`, `install.sh` | `./install.sh check` clean, conventional commit in `main` |
| **P2: Subagent Registration** | Completed | Antigravity `anne_droid` subagent definition | `define_subagent` registers successfully |
| **P3: CLI Token & PR Automation** | Completed | Gitea access token in `tea` login profile | `tea logins list` shows `anne-droid` authenticated |
| **P4: End-to-End Dogfood Run** | Pending | Advisory API audit & delegated branch implementation | Real PR opened on Gitea authored by `anne-droid` |
---
## 4. Execution Runbook
### Step 1: Token Configuration (User-facing)
1. In Gitea web interface (`https://gitea.roadtotech.me`), generate an application token for `anne-droid` with `repo` scope.
2. Register the token in `tea`:
```bash
tea login add --name anne-droid --url https://gitea.roadtotech.me --token <TOKEN>
```
3. Confirm authentication:
```bash
tea --login anne-droid whoami
```
### Step 2: Delegated Feature Implementation (Agent runbook)
1. Create and switch to isolated worktree in sibling directory:
```bash
git worktree add ../<repo>-anne-<task> -b feat/anne/<task>
cd ../<repo>-anne-<task>
```
2. Implement frontend components, styles, and unit tests using `htmx` or `Vite+` (`vp`).
3. Visually verify UI in browser (desktop + mobile viewports):
```bash
google-chrome --headless --disable-gpu --screenshot=desktop.png --window-size=1280,800 <url>
google-chrome --headless --disable-gpu --screenshot=mobile.png --window-size=375,812 <url>
```
4. Commit with Anne's metadata:
```bash
GIT_AUTHOR_NAME="Anne Droid" \
GIT_AUTHOR_EMAIL="anne-droid@roadtotech.me" \
GIT_COMMITTER_NAME="Anne Droid" \
GIT_COMMITTER_EMAIL="anne-droid@roadtotech.me" \
git commit -m "feat(ui): <description>"
```
5. Push branch to remote:
```bash
GIT_SSH_COMMAND="ssh -F /dev/null -p 2223 -i ~/.ssh/id_ed25519_anne_droid -o IdentitiesOnly=yes" \
git push -u origin feat/anne/<task>
```
6. Open PR via `tea` and await user review (worktree remains active):
```bash
tea pr create --login anne-droid --title "feat(ui): <title>" --description "..."
```
7. Upon PR merge/closure confirmation, teardown worktree:
```bash
cd <original-repo>
git worktree remove ../<repo>-anne-<task>
git branch -d feat/anne/<task>
```
---
## 5. Definition of Done
- [x] Gitea account `anne-droid` created and verified.
- [x] Dedicated SSH key pair generated and registered to Gitea.
- [x] SSH connection over port 2223 verified with successful welcome banner.
- [x] Persona specification written to `profile/agents/anne-droid.md`.
- [x] Global routing table in `profile/AGENTS.md` updated.
- [x] `install.sh` updated and symlink verified in `~/.gemini/config/agents/`.
- [x] Antigravity subagent `anne_droid` registered.
- [x] Gitea API token added to `tea` CLI login configuration.
- [ ] First end-to-end pull request created on Gitea authored by Anne Droid.
@@ -0,0 +1,75 @@
---
type: plan
status: active
project: brain
tags:
- learning
- skills
- roadmap
- implementation
---
# Plan: Scaffolded Learning Contracts Across Engineering Skills
> **Discussion Reference**: [`02-discussions/brain/learning-centered-engineering-workflow.md`](../../02-discussions/brain/learning-centered-engineering-workflow.md)
>
> **Core Objective**: Transition operational agent skills from "AI writes it" to "AI scaffolds, learner writes it", enforcing the learning contract across everyday engineering tasks.
---
## 1. Reality Check & Skill Inventory
Mapping the theoretical redesign to actual skills in [`skills`](https://github.com/kiskaadee/skills):
| Conceptual Capability | Actual Skill | Current State vs. Learning Mode |
| :--- | :--- | :--- |
| **Engineering Tutor** | `practice` | Hint ladder implemented (question $\to$ pointer $\to$ explanation $\to$ demo); learner attempts first. |
| **Troubleshooting** | `diagnose` | Evidence-first investigation; working-tree safety stops. |
| **Git Commits** | `git-commit` | Has a `/practice` branch, but still auto-drafts commit messages. Needs author mode. |
| **Documentation** | `document` | Determines document type and drafts it. Needs learner core-sentence prompt. |
| **Journaling** | `journal-builder` | Produces polished narrative. Needs scaffolding mode with diagnostic blanks. |
---
## 2. Phased Implementation Roadmap
### Phase 1: Minimal Learning Contract (`learning-contract.md`)
**Status**: ✅ **Completed**
- Defined binding rules in `profile/learning-contract.md`:
- *Write rule*: In learning mode, agent provides facts and questions; learner writes reasoning.
- *Assistance levels*: `independent`, `hints`, `substantial`, `shown-solution`.
- *Evidence $\neq$ assessment*: Passing tests or commits are evidence, not claims of competence.
- *Mode toggle*: Explicit `delivery` vs `learning` mode per session.
---
### Phase 2: Skill Scaffolding Experiments
Pick candidate skills to enforce the contract:
- **Option A: `git-commit` author mode**: Agent lists slices, changed behavior, tests present/missing, and asks 1–2 diagnostic questions. Learner writes the commit message; agent validates accuracy and scope against the diff.
- **Option B: `journal-builder` scaffold mode**: Builds a factual skeleton from `00-inbox/commit-log.csv` plus 3–5 targeted questions with blanks for learner answers.
---
### Phase 3: Practice Records & Delayed Retrieval
- Add `assistance:` and `revisit_after:` (target date) metadata to practice drill records.
- Surface due revisits manually during `practice` or weekly review.
- Revisits require **recall before reveal**: answer without opening the previous record, then compare.
---
### Phase 4: Two-Week Dogfood Evaluation
Test in real work (project commits, course modules, LeetCode drills) and evaluate:
1. Did the learner actually write the reasoning, or rubber-stamp?
2. Were questions anchored in the learner's actual work rather than generic quizzes?
3. On revisit, did recall succeed without viewing the answer?
4. Cut any steps that feel like bureaucratic drag.
---
### Phase 5 (Gated): Event Store & Service Integration
**Gate**: Proceed only if Phase 4 proves a concrete query need that filesystem files cannot answer (e.g. tracking concepts practiced with hints that were never retrieved independently).
- If triggered, implement as an isolated learning project in `~/Projects/tests/` (PostgreSQL with `FOR UPDATE SKIP LOCKED` and append-only event logging).
@@ -1,6 +1,6 @@
--- ---
type: plan type: plan
status: active status: superseded
project: homelab project: homelab
date: 2026-09-21 date: 2026-09-21
tags: tags:
@@ -16,6 +16,8 @@ tags:
# 🚀 appctl Engine V2: Architectural Modernization & Type-Safe Refactoring Plan # 🚀 appctl Engine V2: Architectural Modernization & Type-Safe Refactoring Plan
> **Superseded by**: [Architecture Consolidation & Control Plane Roadmap v5](../consolidation/architecture-consolidation-roadmap-v5.md) (specifically Phases P0, P3, and P4). Engine modernization code has been integrated into the consolidated baseline and control-plane architecture.
## 1. Executive Summary & Intent ## 1. Executive Summary & Intent
The `appctl` control utility is the central metadata, discovery, and inspection engine for the `roadtotech.me` homelab. It derives operational views (Docker status, Git sync status, SSL/TLS validation, Homepage dashboard generation, shell completion) from application manifests (`Sites/*/app.yaml`) and Core platform definitions. The `appctl` control utility is the central metadata, discovery, and inspection engine for the `roadtotech.me` homelab. It derives operational views (Docker status, Git sync status, SSL/TLS validation, Homepage dashboard generation, shell completion) from application manifests (`Sites/*/app.yaml`) and Core platform definitions.
@@ -1,6 +1,6 @@
--- ---
type: plan type: plan
status: active status: superseded
project: homelab project: homelab
tags: tags:
- operations - operations
@@ -14,6 +14,8 @@ tags:
# 🚀 Smart Selective Deployment Pipeline Plan for Homelab Core # 🚀 Smart Selective Deployment Pipeline Plan for Homelab Core
> **Superseded by**: [Architecture Consolidation & Control Plane Roadmap v5](../consolidation/architecture-consolidation-roadmap-v5.md) (specifically Phase P4 control-plane reconciliation).
## Goal Description ## Goal Description
Implement an intelligent, change-aware deployment pipeline for `homelab-core` that: Implement an intelligent, change-aware deployment pipeline for `homelab-core` that:
1. Analyzes incoming commits on `main` (via Gitea GitOps webhooks and manual `appctl update core` CLI invocations) and selectively executes **only** the required actions. 1. Analyzes incoming commits on `main` (via Gitea GitOps webhooks and manual `appctl update core` CLI invocations) and selectively executes **only** the required actions.
@@ -1,7 +1,7 @@
--- ---
type: plan type: plan
status: superseded status: superseded
superseded_by: architecture-consolidation-roadmap-v4.md superseded_by: architecture-consolidation-roadmap-v5.md
project: homelab project: homelab
tags: tags:
- architecture - architecture
@@ -16,7 +16,7 @@ tags:
# Homelab Core — Architecture Consolidation & Hardening Implementation Guide v3 # Homelab Core — Architecture Consolidation & Hardening Implementation Guide v3
> [!WARNING] > [!WARNING]
> **SUPERSEDED**: This execution guide has been superseded by [**Architecture Consolidation & Hardening Roadmap & Execution Plan v4**](architecture-consolidation-roadmap-v4.md), which unifies the architecture specifications and step-by-step implementation runbooks into a single source of truth. > **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/`) > **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`)
> >
@@ -1,6 +1,6 @@
--- ---
type: plan type: plan
status: active status: superseded
project: homelab project: homelab
tags: tags:
- architecture - architecture
@@ -15,6 +15,8 @@ tags:
# Architecture Consolidation & Hardening Roadmap & Execution Plan v4 # 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) > **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). > **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).
@@ -0,0 +1,253 @@
---
type: plan
status: superseded
superseded_by: architecture-consolidation-roadmap-v6.md
project: homelab
tags:
- architecture
- security
- operations
- homelab
- gitops
- appctl
- control-plane
- roadmap
- consolidation
- provenance
---
# Architecture Consolidation & Control Plane Roadmap v5
> [!WARNING]
> **SUPERSEDED**: This roadmap has been superseded by [**Architecture Consolidation & Control Plane Roadmap v6**](architecture-consolidation-roadmap-v6.md), which codifies locked architectural decisions DEC-01 through DEC-05, the single typed `POST /v1/operations` dispatcher, mandatory token-gated authorization, and `homelab-appctl` systemd isolation.
>
> **Supersedes**: [Architecture Consolidation Roadmap v4](architecture-consolidation-roadmap-v4.md) and [appctl Engine V2 Refactoring Plan](../appctl/appctl-engine-v2-refactoring.md)
>
> **Current Platform Baseline**: Consolidated Git baseline combining NixOS appliance (`Core/`), modernized type-safe metadata engine (`appctl-v2`), and validated provenance domain models.
>
> **Architectural Decision Records**:
> - [`homelab-3tier-architecture-and-provenance.md`](../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md)
> - [`homelab-appctl-control-plane-architecture.md`](../../../03-records/decisions/homelab-appctl-control-plane-architecture.md)
>
> **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`, persistent state `~/var/lib/homelab/`)
---
## Executive Summary
Roadmap v5 establishes the unified engineering roadmap for Homelab Core. It integrates the **3-Tier Architecture & Provenance Model** with the transition of **`appctl` into the authoritative Homelab Core Operational Control Plane**.
Under this roadmap, `appctl` is no longer a collection of local shell scripts invoked over SSH; it is an authenticated, command-oriented control plane daemon exposed over Unix domain socket and HTTP. The platform maintains **Git as the authoritative declarative truth for deployment state**, reconciles implementation-agnostic **Deployment Models**, projects secrets via a provider interface, and serves heterogeneous clients (local CLI, remote CLI, GitOps dispatcher, Operations UI, and AI authoring workflows) with complete telemetry.
---
## 1. System Topology & Control Plane Architecture
```mermaid
flowchart TB
subgraph CLIENTS["1. CLIENT PLANE"]
direction LR
CLI_REMOTE["Remote CLI<br/>(Bearer Token via HTTP)"]
CLI_LOCAL["Local CLI (Host)<br/>(Bearer Token via Unix Socket)"]
GITOPS_DISPATCH["GitOps Dispatcher<br/>(HMAC-SHA256 via HTTP)"]
UI_OPS["Operations Web UI<br/>(ForwardAuth via HTTP)"]
AI_AGENT["AI Authoring Workflow<br/>(Proposal Generator)"]
end
subgraph CONTROL_PLANE["2. HOMELAB OPERATIONAL CONTROL PLANE (appctl Daemon)"]
direction TB
subgraph TRANSPORTS["Transport Listeners (One Logical API)"]
SOCKET_IN["Unix Domain Socket (/run/homelab/appctl.sock)"]
HTTP_IN["HTTP Listener (Localhost / LAN / Traefik)"]
end
API_ROUTER["Command-Oriented Operational Router<br/>• POST /operations/deploy<br/>• POST /operations/restart<br/>• GET /workloads & status<br/>• POST /operations/sync"]
subgraph CORE_MODULES["Core Daemon Subsystems"]
AUTH_MODULE["Identity & RBAC (LLDAP / Groups)"]
AUDIT_MODULE["Append-Only Audit Log (Telemetry & Hashes)"]
MODEL_VALIDATOR["DeploymentModel Validator & Compiler"]
SECRET_PROVIDER["SecretProvider Interface (Secret References)"]
RECON_ENGINE["Reconciliation & Compose Driver"]
end
SOCKET_IN --> API_ROUTER
HTTP_IN --> API_ROUTER
API_ROUTER --> AUTH_MODULE
AUTH_MODULE --> AUDIT_MODULE
API_ROUTER --> MODEL_VALIDATOR
MODEL_VALIDATOR --> SECRET_PROVIDER
SECRET_PROVIDER --> RECON_ENGINE
end
subgraph PLATFORM_RUNTIME["3. PLATFORM & RUNTIME TIERS"]
direction LR
GIT_REPO["Deployment Catalog (Git Truth)<br/>• Versioned DeploymentModels"]
SITES_CATALOG["Sites Catalog (~/Sites/*)<br/>• Materialized app.yaml & compose"]
STATE_ROOT["Host State Root (~/var/lib/homelab/*)<br/>• Workload Data & DBs"]
DOCKER_ENGINE["Docker Daemon & Socket-Proxy"]
TRAEFIK_INGRESS["Traefik Edge & TLS Ingress"]
end
CLIENTS --> TRANSPORTS
MODEL_VALIDATOR --> GIT_REPO
GIT_REPO --> SITES_CATALOG
RECON_ENGINE --> SITES_CATALOG
RECON_ENGINE --> DOCKER_ENGINE
SITES_CATALOG --> STATE_ROOT
DOCKER_ENGINE --> TRAEFIK_INGRESS
```
---
## 2. Core Architectural Invariants
1. **One Logical API Across Transports**: The control-plane API is a single logical command-oriented contract. Unix domain socket vs. HTTP is merely transport. Local and remote CLIs invoke identical operation schemas.
2. **Host Access Does Not Confer Authority**: Entering via SSH does not bypass control-plane authentication. **Every mutating operation requires an explicit, authenticated user-scoped token.**
3. **Git is the Authoritative Source of Deployment State**: Approved `DeploymentModels` are committed to the version-controlled deployment repository. `appctl` reconciles desired Git state into running containers, preserving rollback capability (`git revert`) and historical auditability.
4. **Five-Stage Model Lifecycle (Intent vs. Implementation)**:
$$\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Containers}$$
`DeploymentModel` captures implementation-agnostic intent (ports, domains, volumes, dependencies); `Deployment Definition` captures the concrete platform descriptors (`app.yaml` + Compose).
5. **AI Authoring Boundary**: The AI is strictly an upstream authoring client with zero mutation authority. The AI analyzes repositories and emits `DeploymentProposals`. After human approval, the AI is completely out of the loop.
6. **KISS Primitives & Linear Control Paths**: The deployment pipeline remains strictly linear:
$$\text{Source Push} \longrightarrow \text{CI Build} \longrightarrow \text{GitOps Ingress} \longrightarrow \text{appctl Reconcile} \longrightarrow \text{Compose Up}$$
No distributed message brokers or deployment databases.
7. **Secret Reference Invariant**: Deployment definitions contain secret references (`secretKeyRef`), never secret material. References are resolved at runtime via the `SecretProvider` interface.
8. **Clean Persistent State Root**: Mutable application data lives strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
9. **Client Independence**: `appctl` owns the control-plane contract, not its clients. Homepage is a read-only dashboard consumer, not an interactive administration cockpit.
---
## 3. Phased Implementation Roadmap
### Overview
| Phase | Title | Focus Area | Key Deliverables | Verification Gates |
| :--- | :--- | :--- | :--- | :--- |
| **P0** | **Baseline Consolidation** | Git & Architecture | Merge `refactor/appctl-rework` into `main`, unify history, supersede old plans. | Clean git working tree, `./scripts/test` passing, flake check green. |
| **P1** | **Mail Realignment** | Topology & State | Move Stalwart to `smtp.roadtotech.me`, SnappyMail to `~/Sites/snappymail`. | Zero data loss, verified rollback archive, state parity diff, Diun SMTPS delivery. |
| **P2** | **GitOps Hardening** | Ingress Security | Authoritative Core repo registry, HMAC validation, systemd sandboxing. | Flake check, path traversal rejection tests, Compose AST security validator. |
| **P3** | **Manifest Contract** | Domain Engine | Schema v1.0, `core_manifest.py`, source provenance resolution (`git ls-remote`). | Regression tests for domain invariants, schema linting in CI. |
| **P4** | **Control Plane Daemon** | API & Dispatch | `homelab-appctl.service`, dual transport (socket + HTTP), thin-client CLI, append-only audit log. | Hermetic API test suite, explicit token validation tests, audit log telemetry verification. |
| **P5** | **Identity & Secrets** | Auth & Providers | Authelia header auth, user-scoped API tokens, `SecretProvider` reference resolver. | RBAC permission matrix tests, secret reference materialization tests. |
| **P6** | **Deployment Model & AI**| Intent Authoring | Capability model, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. | Intent validation tests, platform security invariant enforcement tests. |
| **P7** | **Operations UI & Portal** | Client Integration | Dedicated Operations UI client, Homepage status integration widgets. | End-to-end deployment verification via UI and CLI. |
---
### Phase 0: Baseline & Architectural Consolidation (Completed)
* **Deliverable 0.1**: Record Architectural Decision Record (`homelab-appctl-control-plane-architecture.md`).
* **Deliverable 0.2**: Merge `refactor/appctl-rework` into `main` and synchronize baseline back to working branch.
* **Deliverable 0.3**: Mark superseded roadmaps (v2, v3, v4) and legacy refactoring plans as `status: superseded`.
* **Deliverable 0.4**: Run `./scripts/test` and `nix flake check` to confirm baseline integrity.
---
### Phase 1: Mail Topology Realignment & Zero-Data-Loss Migration Runbook
* **Deliverable 1.1: Pre-Migration Snapshot**:
Freeze SnappyMail container, generate timestamped SHA256-verified backup archive of `Core/config/snappymail/data`.
* **Deliverable 1.2: Workload Provisioning & State Cutover**:
- Provision `~/var/lib/homelab/snappymail/`.
- Replicate state with `cp -a` and prove byte parity (`diff -r`).
- Create `~/Sites/snappymail/app.yaml` (Class B Image-Only) and `docker-compose.yml`.
* **Deliverable 1.3: Stalwart Endpoint Re-homing**:
Update Stalwart public Traefik labels in `Core/docker-compose.yml` to `smtp.roadtotech.me`. Remove SnappyMail from Core stack.
* **Deliverable 1.4: Cutover Verification**:
Verify webmail logins, address book persistence, IMAP/SMTP mail flow, and Diun SMTPS alert delivery on port 465.
---
### Phase 2: GitOps Privilege & Authority Hardening
* **Deliverable 2.1: Authoritative Core Repository Registry**:
Define `Core/config/deployments.yaml` as the sole authority for admitted deployment targets.
* **Deliverable 2.2: Second Brain Read-Only Data Vault Policy**:
Designate `~/Brain` with `strategy: pull-only`, isolated from Docker execution.
* **Deliverable 2.3: Workload Compose Security Policy**:
Implement pre-flight Compose AST inspection rejecting privileged containers, Docker socket mounts, and host root mounts.
* **Deliverable 2.4: Systemd Service Sandboxing**:
Apply `ProtectSystem=strict`, `NoNewPrivileges=true`, and private temporary directories to `homelab-gitops.service`.
---
### Phase 3: Manifest Contract Convergence & Provenance Engine
* **Deliverable 3.1: Manifest Schema v1.0 & Authoritative Parser (`core_manifest.py`)**:
- Implement strongly-typed domain dataclasses: `SitesApp`, `CoreService`, `SourceConfig`.
- Enforce explicit `source.ref` semantics: moving branch (`main`), release tag (`v1.2.3`), immutable commit SHA (`a1b2c3...`).
- Strict transport scheme validation: permitted `https://`, `ssh://`, `git@`; reject `file://` and path traversals.
* **Deliverable 3.2: Two-Axis Inspection**:
- Axis 1: Local Sites deployment checkout state (`✓ Synced`, `* Dirty`, `⬆ Ahead`, `⬇ Behind`).
- Axis 2: Upstream software provenance state (via `git ls-remote` bounded by 10s timeout during `--fetch`).
* **Deliverable 3.3: Engine Promotion**:
Promote `scripts/appctl_engine_v2.py` to `scripts/appctl_engine.py` with complete behavioral test coverage.
---
### Phase 4: appctl Control Plane Daemon & Command-Oriented API
* **Deliverable 4.1: Control Plane Service (`homelab-appctl.service`)**:
Implement command-oriented daemon listening on dual transports: Unix domain socket (`/run/homelab/appctl.sock`) for local host clients and unified HTTP listener (localhost, LAN, and Traefik edge ingress) for network clients.
* **Deliverable 4.2: Command-Oriented Operational Endpoints**:
- `POST /operations/deploy` (reconcile deployment for target workload)
- `POST /operations/restart` (restart workload containers)
- `POST /operations/pull` (pull latest images)
- `GET /workloads` (list workloads with two-axis inspection)
- `GET /workloads/{id}/status` (inspect specific workload diagnostics)
- `GET /workloads/{id}/logs` (stream logs via Server-Sent Events)
- `POST /operations/sync` (recompile dashboard status)
* **Deliverable 4.3: Thin-Client CLI**:
Update `scripts/appctl` to act as a lightweight client dispatching commands to the local daemon socket with zero duplicate operational code.
* **Deliverable 4.4: Append-Only Audit Log**:
Record every mutating command to `~/.local/state/homelab/appctl/audit.jsonl` with restricted `0600` permissions. Telemetry captures `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`.
---
### Phase 5: Identity, RBAC & SecretProvider Interface
* **Deliverable 5.1: Authentication Gateway**:
- Web requests: Accept trusted identity headers from Traefik/Authelia (`Remote-User`, `Remote-Groups`).
- CLI requests (both remote and local): Require explicit user-scoped API tokens (`Authorization: Bearer <token>`).
- Webhook requests: Validate HMAC-SHA256 signature against webhook secret.
* **Deliverable 5.2: Role-Based Authorization Engine**:
Enforce group policies (`homelab-admin`, `homelab-operator`, `homelab-viewer`) on incoming operations.
* **Deliverable 5.3: SecretProvider Interface**:
- Define `SecretProvider` contract in the control plane:
```python
class SecretProvider(Protocol):
def resolve_secret(self, ref: str) -> str: ...
def project_environment(self, refs: dict[str, str]) -> dict[str, str]: ...
```
- Deployment definitions store secret references (`secretKeyRef: ...`), never plaintext material.
- Workload application secrets are projected dynamically at container recreation without Git history pollution.
---
### Phase 6: Homelab Deployment Model & AI Authoring Workflow
* **Deliverable 6.1: Platform Capability Catalog & Invariants**:
Formally define machine-readable specification of Core capabilities (HTTP routing, persistent mounts, networks, healthchecks) and invariants (no privileged containers, isolated state root).
* **Deliverable 6.2: `DeploymentProposal` Schema**:
Define candidate model structure emitted by AI discovery workflows from repository inspection.
* **Deliverable 6.3: `DeploymentModel` Git Pipeline & Materialization**:
- Operator selects/edits proposal into an approved `DeploymentModel`.
- The model is committed to the version-controlled deployment repository (Git).
- `appctl` validates the model, provisions `~/var/lib/homelab/<app>/`, compiles the Deployment Definition (`app.yaml` + Compose), and triggers deployment.
* **Deliverable 6.4: Human Approval Invariant**:
Enforce interactive operator signature/approval before model creation. AI possesses zero execution authority.
---
### Phase 7: Operations Web Client & Dashboard Integration
* **Deliverable 7.1: Operations UI Client**:
Deploy lightweight, browser-based management console as a client of the control plane API (proposals review, approval, real-time log streaming, token management).
* **Deliverable 7.2: Homepage Status Integration**:
Maintain Homepage as read-only portal, querying `appctl` live status endpoints or compiled `services.yaml`.
---
## 4. Definition of Done
1. **Unified Control Plane**: All platform operations execute through `homelab-appctl.service`. No secondary deployment scripts exist.
2. **Explicit Authentication Everywhere**: Host SSH access does not confer appctl authority. Every operation has an authenticated principal and is recorded in the append-only audit log with transport and origin telemetry.
3. **Declarative Git Truth**: All workloads are governed by version-controlled `DeploymentModels` committed to Git. Deployments are fully reproducible and auditable.
4. **Secret Hygiene**: Deployment manifests contain zero plaintext credentials; workload secrets resolve via `SecretProvider` without Git history pollution.
5. **Safe Deployment Authoring**: AI agents act strictly as proposal generators; all mutations require human approval and conform to Core invariants.
6. **Zero Data Loss**: Mail realignment preserves 100% of user data, mailboxes, and address books.
7. **Invariant-Driven Regression Coverage**: All defined domain, authorization, deployment, and security invariants have automated regression coverage.
@@ -0,0 +1,275 @@
---
type: plan
status: active
project: homelab
tags:
- architecture
- security
- operations
- homelab
- gitops
- appctl
- control-plane
- roadmap
- consolidation
- provenance
---
# Architecture Consolidation & Control Plane Roadmap v6
> **Supersedes**: [Architecture Consolidation & Control Plane Roadmap v5](architecture-consolidation-roadmap-v5.md)
>
> **Authoritative Repository Specifications**:
> - Core Readiness Plan: `~/Homelab/Core/docs/plans/p4-readiness-plan.md`
> - Core Roadmap Projection: `~/Homelab/Core/ROADMAP.md`
>
> **Architectural Decision Records**:
> - [`homelab-appctl-control-plane-architecture.md`](../../../03-records/decisions/homelab-appctl-control-plane-architecture.md) (`~/Homelab/Core/docs/decisions/0002-appctl-control-plane-architecture.md`)
> - [`homelab-3tier-architecture-and-provenance.md`](../../../03-records/decisions/homelab-3tier-architecture-and-provenance.md) (`~/Homelab/Core/docs/decisions/0001-3tier-architecture-and-provenance.md`)
> - `~/Homelab/Core/docs/decisions/0003-pydantic-v2-runtime-validation.md`
>
> **Evolutionary History**:
> - [`homelab-control-plane-evolution-v1-to-v6.md`](../../../04-learning/knowledge/methods/homelab-control-plane-evolution-v1-to-v6.md)
>
> **Target System**: `roadtotech.me` (NixOS appliance `Core/`, application workloads `Sites/`, persistent state `~/var/lib/homelab/`)
---
## Executive Summary
Roadmap v6 codifies the transition of `appctl` into an authoritative, fail-closed **Operational Control Plane Daemon** (`homelab-appctl.service`). It incorporates the architectural reconciliation and locked decisions (**`DEC-01` through `DEC-05`**) finalized before initiating the Milestone P4 daemon implementation.
Under Roadmap v6, `appctl` completely abandons its legacy identity as a collection of local Bash scripts directly invoking `docker compose` and `git`. Instead:
1. **One Logical API Across Dual Transports**: A unified HTTP/1.1 engine serving both a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback TCP (`127.0.0.1:9001`) with zero protocol divergence.
2. **Single Canonical Operation Router**: Operations dispatch via a single, strictly-typed command endpoint (`POST /v1/operations` + `GET /v1/health`), eliminating multi-route REST ambiguity.
3. **Host Access Does Not Confer Mutation Authority**: Entering via SSH provides Unix access, but zero operational control plane privileges. Every mutating action and sensitive read (`workload.config`, `workload.logs`) requires a cryptographically verified, SOPS-projected SHA-256 Bearer token.
4. **Dedicated Systemd Service Identity & Privilege Isolation**: The daemon executes as `homelab-appctl` (`Group = "homelab-operators"`), isolated from operator shell processes and AI coding sessions, protected by declarative POSIX ACLs.
5. **Unified Pre-Flight & Pure-Python Environment Assembly**: Shell `source` and `eval` are eliminated; environments are parsed via inert Python readers, and every mutation is gated by Compose AST security validation.
6. **Append-Only Audit Log with Fail-Closed Disk Guard**: Multi-dimensional telemetry (`audit.jsonl`, mode `0600`) records pre-execution (`DISPATCHED`), post-execution (`COMPLETED`/`FAILED`), and admission rejection (`DENIED`) records. If the audit log cannot be written, the mutation is aborted before any Docker or Git subprocess executes.
---
## 1. System Topology & Control Plane Architecture
```mermaid
flowchart TB
subgraph CLIENTS["1. CLIENT PLANE"]
direction LR
CLI_THIN["Thin-Client CLI (Host)<br/>(Bearer Token / PeerCred via UDS)"]
GITOPS_DISPATCH["GitOps Ingress Worker<br/>(Bearer Token via UDS)"]
HTTP_CLIENT["Local/Remote HTTP Client<br/>(Bearer Token via 127.0.0.1:9001)"]
AI_AGENT["AI Authoring Workflow<br/>(Proposal Generator Only)"]
end
subgraph CONTROL_PLANE["2. HOMELAB OPERATIONAL CONTROL PLANE (homelab-appctl.service)"]
direction TB
subgraph TRANSPORTS["Dual Transports (HTTP/1.1 Engine)"]
SOCKET_IN["Unix Domain Socket (/run/homelab/appctl.sock)<br/>mode 0660 (homelab-appctl:homelab-operators)"]
HTTP_IN["HTTP Listener (127.0.0.1:9001)<br/>Strictly loopback in P4"]
end
API_ROUTER["Single Command-Oriented Operational Router<br/>• POST /v1/operations (13 Canonical Operations)<br/>• GET /v1/health (Liveness Probe)"]
subgraph PIPELINE["Unified Fail-Closed Pipeline"]
direction TB
VAL_GATE["Pydantic v2 Contract Validator<br/>(extra='forbid', strict=True, 64 KiB Limit)"]
AUTH_GATE["Authentication & 3-Role RBAC Gate<br/>• Admin / Operator (deployments.yaml) / Viewer<br/>• SO_PEERCRED UDS fallback to viewer"]
LOCK_MGR["Per-Target flock Manager<br/>(/var/lib/homelab/appctl/locks/*.lock)"]
AUDIT_PRE["Pre-Execution Audit Disk Guard<br/>(DISPATCHED → Abort on write failure)"]
PREFLIGHT["Unified Pre-Flight & Pure-Python Env<br/>• Manifest parse • Compose AST security validator"]
EXEC_ENGINE["Execution Subprocess Runner<br/>(Fixed allowlist, 256 KiB output bound, timeouts)"]
AUDIT_POST["Post-Execution Audit Writer<br/>(COMPLETED / FAILED with commit SHAs)"]
end
SOCKET_IN --> API_ROUTER
HTTP_IN --> API_ROUTER
API_ROUTER --> VAL_GATE
VAL_GATE --> AUTH_GATE
AUTH_GATE --> LOCK_MGR
LOCK_MGR --> AUDIT_PRE
AUDIT_PRE --> PREFLIGHT
PREFLIGHT --> EXEC_ENGINE
EXEC_ENGINE --> AUDIT_POST
end
subgraph PLATFORM_RUNTIME["3. PLATFORM & RUNTIME TIERS"]
direction LR
DEPLOY_REG["Core Registry<br/>(config/deployments.yaml)"]
SITES_CATALOG["Sites Catalog (~/Sites/*)<br/>• app.yaml & compose"]
STATE_ROOT["Host State Root (~/var/lib/homelab/*)<br/>• Workload Data & DBs"]
DOCKER_ENGINE["Docker Daemon & Socket-Proxy"]
AUDIT_STORE["Audit Storage (/var/log/homelab/appctl/audit.jsonl)<br/>mode 0600 (homelab-appctl)"]
end
CLIENTS --> TRANSPORTS
AUTH_GATE --> DEPLOY_REG
PREFLIGHT --> SITES_CATALOG
EXEC_ENGINE --> SITES_CATALOG
EXEC_ENGINE --> DOCKER_ENGINE
SITES_CATALOG --> STATE_ROOT
AUDIT_PRE --> AUDIT_STORE
AUDIT_POST --> AUDIT_STORE
```
---
## 2. Core Architectural Invariants (Codified DEC-01 through DEC-05)
1. **One Logical API Across Transports (`DEC-01`)**:
- The API is a single logical HTTP/1.1 contract served over Unix domain socket (`/run/homelab/appctl.sock`) and TCP (`127.0.0.1:9001`).
- All operations are dispatched through `POST /v1/operations` with JSON payloads (`version: "1.0"`). Convenience liveness is exposed via `GET /v1/health`. Multi-route REST aliases (`GET /workloads`, `POST /operations/deploy`) are rejected.
2. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**:
- SSH entry confers zero control plane mutation authority. Every mutating operation and sensitive read (`workload.config`, `workload.logs`) strictly requires a valid Bearer token (`/run/secrets/appctl/tokens.json`).
- Local UDS connections without Bearer tokens leverage `SO_PEERCRED` to identify the caller and fall back strictly to `homelab-viewer` privileges for non-sensitive reads (`list`, `get`, `resolve`, `ssl`, `health`).
3. **Dedicated Service Identity & OS Boundary (`DEC-03`)**:
- The daemon runs as `homelab-appctl` (`Group = "homelab-operators"`).
- Unprivileged processes and AI agents running under the operator SSH session cannot access `/run/secrets/appctl/tokens.json` (`0400`) or mutate `/var/log/homelab/appctl/audit.jsonl` (`0600`).
- Declarative `systemd.tmpfiles.rules` apply recursive default POSIX ACLs (`d:u:homelab-appctl:rwx,u:homelab-appctl:rwx`) to shared directories.
4. **GitOps Ingress Unification (`DEC-04`)**:
- `scripts/gitops_dispatcher.py` retains webhook ingress, HMAC verification, `config/deployments.yaml` admission, and the asynchronous `.pending.json` queue.
- The background worker delegates execution to the daemon's `workload.update` operation over the Unix domain socket, eliminating duplicated `git pull` and `docker compose` execution paths.
5. **Unified Pre-Flight & Pure-Python Environment Assembly (`DEC-05`)**:
- Shell `source` and `eval` are eliminated. Subprocess environments are assembled entirely in Python with strict key validation against `ENV_KEY_RE` and `RESERVED_ENV_KEYS`.
- Every mutating Compose operation is preceded by `validate_compose_security()`, enforcing AST security constraints across both CLI and GitOps paths.
6. **Append-Only Audit Log with Fail-Closed Disk Guard (`DEC-03`)**:
- Mutating operations append a `DISPATCHED` record before touching Docker or Git. If the disk write fails, the request immediately terminates with `500 ERR_EXECUTION_FAILED`.
7. **Git is the Authoritative Source of Deployment State**:
- Approved `DeploymentModels` are committed to Git. `appctl` reconciles desired Git state into running containers.
8. **Five-Stage Model Lifecycle (Intent vs. Implementation)**:
- $\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Containers}$.
9. **AI Authoring Boundary**:
- AI agents are strictly upstream proposal generators (`DeploymentProposal`) with zero execution authority. Human operators approve the intent.
10. **Secret Reference Invariant & Clean Persistent State Root**:
- Deployment definitions store secret references (`secretKeyRef`) resolved at runtime via `SecretProvider`, never plaintext credentials; mutable runtime data resides strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
11. **KISS Primitives & Linear Control Paths**:
- Control flow remains strictly linear and local. No message brokers (RabbitMQ/Kafka) or deployment databases are introduced.
---
## 3. The 13 Canonical Domain Operations
| Domain Operation | Type | Required Role (`Sites` / `Core`) | Timeout | Subprocess / Engine |
| :--- | :--- | :--- | :--- | :--- |
| `workload.list` | Read-Only | `homelab-viewer` | `15s` | In-process (`appctl_engine.py`, `provenance.py`) |
| `workload.get` | Read-Only | `homelab-viewer` | `15s` | In-process (`appctl_engine.py`, `core_manifest.py`) |
| `workload.resolve` | Read-Only | `homelab-viewer` | In-process | In-process (`appctl_engine.py`) |
| `platform.ssl` | Read-Only | `homelab-viewer` | `3s` / host | In-process (`appctl_engine.py`) |
| `platform.health` | Read-Only | `homelab-viewer` | In-process | In-process daemon health probe |
| `workload.config` | Sensitive Read | `homelab-operator` / `homelab-admin`* | `15s` | `docker compose config` (secret redaction) |
| `workload.logs` | Sensitive Read | `homelab-operator` / `homelab-admin`* | `15s` | `docker compose logs --tail <1..1000>` |
| `workload.deploy` | Mutating | `homelab-operator` / `homelab-admin`* | `300s` | `docker compose up -d` $\to$ Homepage sync |
| `workload.stop` | Mutating | `homelab-operator` / `homelab-admin`* | `300s` | `docker compose down` / `stop` $\to$ Homepage sync |
| `workload.restart`| Mutating | `homelab-operator` / `homelab-admin`* | `300s` | `docker compose restart` $\to$ Homepage sync |
| `workload.pull` | Mutating | `homelab-operator` / `homelab-admin`* | `300s` | `docker compose pull` $\to$ `docker compose up -d` |
| `workload.update` | Mutating | `homelab-operator` / `homelab-admin`* | `60s` (git)<br>`300s` (docker) | `git pull --ff-only` $\to$ Compose security validate $\to$ Declared actions $\to$ Homepage sync |
| `platform.sync_homepage` | Mutating | `homelab-operator` / `homelab-admin` | In-process | Compile `services.yaml` under `_homepage_sync.lock` |
*\*Targeting `core` or any `core_service` container strictly requires the `homelab-admin` role.*
---
## 4. Phased Implementation Roadmap
### Overview
| Milestone | Title | Focus Area | Status | Deliverables Summary |
| :--- | :--- | :--- | :--- | :--- |
| **P0** | **Baseline Consolidation** | Git & Architecture | ✅ **Completed** | Synchronized `refactor/appctl-rework` with `main`, recorded control plane ADR, modernized metadata engine. |
| **P1** | **Mail Realignment** | Topology & State | ✅ **Completed** | Moved Stalwart to `smtp.<domain>`, migrated SnappyMail to `~/Sites/snappymail` with zero data loss. |
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core registry (`deployments.yaml`), Compose AST validator, systemd sandboxing. |
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0 with Pydantic v2 models (`core_manifest.py`), two-axis inspection, unified `appctl_engine.py`. |
| **P4** | **Control Plane Daemon** | API & Dispatch | 🎯 **Current / Up Next** | `homelab-appctl.service`, dual transport (socket + HTTP), single router, mandatory auth, thin-client CLI, audit log. |
| **P5** | **Identity & Secrets** | Auth & Providers | ⏳ **Planned** | LLDAP RBAC mapping, Authelia ForwardAuth headers, user-scoped token lifecycle, `SecretProvider` reference resolution. |
| **P6** | **Deployment Model & AI**| Intent Authoring | ⏳ **Planned** | Platform capability catalog, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. |
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, live log streaming (SSE), Homepage read-only status integration. |
---
### Milestone P0: Baseline Consolidation (Completed)
- Merged `refactor/appctl-rework` and `main` into a unified architectural baseline.
- Modernized metadata engine with strongly-typed models (`SitesApp`, `CoreService`, `SourceConfig`).
- Formalized control plane ADR (`homelab-appctl-control-plane-architecture.md`).
- Verified test harness (`./scripts/test`) and Nix flake sandbox.
---
### Milestone P1: Mail Topology Realignment & Zero-Data-Loss Migration (Completed)
- Executed timestamped, SHA256-verified backup of SnappyMail data.
- Provisioned Class B Image-Only workload at `~/Sites/snappymail/` and state root at `~/var/lib/homelab/snappymail/`.
- Replicated state with byte parity verification (`diff -r`).
- Re-homed Stalwart public endpoint to `smtp.<domain>` and removed SnappyMail from Core stack.
- Verified webmail logins, address book persistence, and Diun SMTPS alert delivery on port 465.
---
### Milestone P2: GitOps Privilege & Authority Hardening (Completed)
- Established `Core/config/deployments.yaml` as sole authority for admitted GitOps deployment repositories.
- Decoupled `~/Brain` data vault from workload continuous deployment.
- Implemented Compose AST security validator rejecting `privileged: true`, Docker socket binds, and host namespace escapes.
- Sandboxed `homelab-gitops.service` with `ProtectSystem=strict`, `NoNewPrivileges=true`, and private temporary directories.
---
### Milestone P3: Manifest Contract Convergence & Provenance Engine (Completed)
- Released Schema v1.0 with fail-closed Pydantic v2 validation (`core_manifest.py`).
- Implemented two-axis inspection: local checkout state (`✓ Synced`, `* Dirty`) vs upstream software provenance (`git ls-remote` with 10s timeout).
- Promoted unified engine to `scripts/appctl_engine.py`, retired `appctl_engine_v2.py` shim, and achieved zero Pyright warnings.
---
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API (Current / Up Next)
**Status**: 🎯 **Approved & Locked (Pre-P4 Security Gate Complete; Ready for Daemon Implementation)**
Implementation is divided into six dependency-ordered slices:
1. **Slice 1 — Pydantic v2 API Contracts & Error Sanitizer (`scripts/appctl_contracts.py`)**:
- Strict request/response/error/audit models (`ConfigDict(extra="forbid", strict=True)`), 64 KiB request limit, and input-sanitized error mapping (`include_input=False`).
- Add `"compose_pull"` to `ALLOWED_ACTIONS` in `scripts/core_manifest.py`.
2. **Slice 2 — Append-Only Audit Logger & Per-Target Lock Manager**:
- `AuditLogger` supporting `DISPATCHED`, `COMPLETED`, `FAILED`, `DENIED`, mode `0600`, secret redaction, and fail-closed disk guard.
- Non-blocking `fcntl.flock` manager for `/var/lib/homelab/appctl/locks/<target>.lock` and `_homepage_sync.lock`.
3. **Slice 3 — Authentication & 3-Role RBAC Gate**:
- SOPS `tokens.json` SHA-256 authenticator (`hmac.compare_digest`), UDS `SO_PEERCRED` fallback for viewer reads, and role-scoped authorization (`homelab-admin`, `homelab-operator` scoped to `deployments.yaml`, `homelab-viewer`).
4. **Slice 4 — Operational Router & Unified Execution Engine**:
- Pure-Python `.env` parser (no shell `source`), mandatory pre-flight checks, revision-consistent `workload.update`, bounded `workload.logs` (`tail` 1..1000), and atomic Homepage sync.
5. **Slice 5 — Dual-Transport HTTP/1.1 Daemon (`scripts/appctl_daemon.py`) & GitOps Cutover**:
- HTTP/1.1 server over `/run/homelab/appctl.sock` and `127.0.0.1:9001` with graceful signal handling.
- Rewire `scripts/gitops_dispatcher.py` worker to invoke `POST /v1/operations` (`workload.update`) over the Unix domain socket.
6. **Slice 6 — Thin-Client CLI (`scripts/appctl`), NixOS Service & Genericism Cleanup**:
- Re-implement `scripts/appctl` as thin UDS HTTP client.
- Declare `homelab-appctl.service` (`homelab-appctl:homelab-operators` + POSIX ACLs) in `nixos/modules/homeserver.nix`.
- Scrub remaining hardcoded domain/user literals and add `pyright` to `flake.nix` and pre-commit hooks.
---
### Milestone P5: Identity, RBAC & SecretProvider Interface (Planned)
- Plug Traefik/Authelia trusted ForwardAuth headers (`Remote-User`, `Remote-Groups`) with dedicated proxy authentication.
- Implement dynamic LLDAP user-scoped API token lifecycle.
- Implement `SecretProvider` interface resolving `secretKeyRef` references at container runtime without Git history pollution.
---
### Milestone P6: Homelab Deployment Model & AI Authoring Workflow (Planned)
- Machine-readable Platform Capability Catalog defining Core capabilities and security invariants.
- `DeploymentProposal` schema for AI-assisted service discovery.
- Operator approval Git pipeline: `DeploymentProposal` $\to$ committed `DeploymentModel` $\to$ `appctl` materialization.
- Human-in-the-loop approval invariant strictly enforced (AI has 0 execution authority).
---
### Milestone P7: Operations UI & Dashboard Integration (Planned)
- Dedicated lightweight web console consuming the `appctl` API for proposal review, approval, real-time log streaming (SSE), and token management.
- Homepage read-only status integration widgets querying `appctl` live status endpoints.
---
## 5. Definition of Done & Quality Gates
1. **Unified Control Plane**: All platform operations execute through `homelab-appctl.service`. No secondary deployment scripts exist.
2. **Explicit Authentication Everywhere**: Host SSH access does not confer appctl mutation authority. Every mutating request presents an authenticated Bearer token.
3. **Transport Equivalence**: Hermetic test suite asserts 100% schema and status parity between UDS and HTTP listeners.
4. **Declarative Git Truth**: All workloads are governed by version-controlled definitions in Git.
5. **Secret Hygiene**: Zero plaintext credentials in deployment manifests; secrets resolve via tmpfs and dynamic providers.
6. **Safe Deployment Authoring**: AI agents act strictly as proposal generators; all mutations require human approval.
7. **Zero Production Regressions**: Platform migrations include pre-flight snapshots, state parity proofs, and documented rollback procedures.
8. **Automated Verification**: Every commit must pass `./scripts/test` (Ruff linter + Pytest suite + Pyright type checker + Nix flake check).
@@ -0,0 +1,159 @@
---
type: plan
status: draft
project: homelab
tags:
- homelab
- dns
- cloudflare
- dynu
- cutover
- networking
---
# Dynu → Cloudflare Authoritative DNS Cutover Action Plan
This plan details the authoritative DNS migration for `roadtotech.me` from Dynu to Cloudflare using the declarative CLI tooling (`flarectl`, `hostinger`, `doggo`) and in-memory SOPS secret wrappers configured on your workstation.
---
## Architecture & Operational Invariants
```mermaid
flowchart LR
subgraph Step1["Phase 1: Cloudflare"]
CF["flarectl zone create<br/>--jumpstart"] --> Audit["Audit Records<br/>(A, CNAME, MX, TXT)"]
Audit --> Capture["Capture Assigned NS<br/>(e.g., ns1.cloudflare.com)"]
end
subgraph Step2["Phase 2: Hostinger"]
Capture --> Hostinger["hostinger domains portfolio<br/>update-nameservers"]
end
subgraph Step3["Phase 3: Propagation"]
Hostinger --> Monitor["doggo NS roadtotech.me<br/>Live Propagation Verification"]
end
subgraph Step4["Phase 4: Homelab Cleanup"]
Monitor --> Traefik["Update Traefik & DDNS<br/>in Core (Cloudflare Provider)"]
Traefik --> Revert["Revert Emergency<br/>networking.hosts Workarounds"]
end
```
### Critical Invariants
1. **The "Grey Cloud" (DNS-Only) Rule**: All homelab records (`roadtotech.me`, `*.roadtotech.me`, `mail.roadtotech.me`) must have Cloudflare proxying **disabled** (`--proxy=false`). Cloudflare’s HTTP proxy does not route non-HTTP traffic (Gitea SSH on port `2223`) and intercepts direct Let's Encrypt TLS handshakes.
2. **Transactional Mail Preservation**: Brevo verification TXT codes and SnappyMail MX records must be present in Cloudflare before nameserver cutover to ensure zero email disruption.
3. **In-Memory Credential Safety**: Invoking `flarectl` and `hostinger` through your shell wrappers (`home/shell/secrets.sh`) injects credentials directly into child process memory via `sops -d --extract`. Never pipe or write decrypted tokens to disk.
---
## Execution Phases
### Phase 1: Cloudflare Zone Setup & Record Audit (`flarectl`)
#### 1.1 Create the Zone with Automatic Crawling
Run `flarectl zone create` with `--jumpstart` so Cloudflare automatically queries public DNS and imports active records:
```bash
flarectl zone create --zone roadtotech.me --jumpstart
```
*Expected Output*: Returns a table displaying the new **Zone ID** and the **Name Servers** assigned to your domain (e.g., `ns1.cloudflare.com`, `ns2.cloudflare.com`). Note these two nameservers for Phase 2.
#### 1.2 Audit Crawled DNS Records
Verify that Cloudflare discovered the existing records:
```bash
flarectl dns list --zone roadtotech.me
```
#### 1.3 Ensure Required Homelab & Mail Records Exist
Compare the output against the required homelab record set. If any record was missed during the jumpstart crawl (e.g. because Dynu was timing out), create it explicitly:
| Name | Type | Target Content | Proxy State | Purpose | CLI Creation Command (if missing) |
| :--- | :---: | :--- | :---: | :--- | :--- |
| `@` | `A` | `186.112.11.188` | **DNS Only** | Apex domain pointing to homelab WAN IP | `flarectl dns create --zone roadtotech.me --name roadtotech.me --type A --content 186.112.11.188 --proxy=false` |
| `*` | `CNAME` | `roadtotech.me` | **DNS Only** | Wildcard routing for all Sites behind Traefik | `flarectl dns create --zone roadtotech.me --name "*" --type CNAME --content roadtotech.me --proxy=false` |
| `mail` | `A` | `186.112.11.188` | **DNS Only** | SnappyMail webmail endpoint | `flarectl dns create --zone roadtotech.me --name mail.roadtotech.me --type A --content 186.112.11.188 --proxy=false` |
| `@` | `MX` | `mail.roadtotech.me` | N/A | Inbound mail routing (Priority 10) | `flarectl dns create --zone roadtotech.me --name roadtotech.me --type MX --content mail.roadtotech.me --priority 10` |
| `@` | `TXT` | `brevo-code:0509c2a6d12137c59d9e6b7fbef9fe8d` | N/A | Brevo outbound domain authentication | `flarectl dns create --zone roadtotech.me --name roadtotech.me --type TXT --content "brevo-code:0509c2a6d12137c59d9e6b7fbef9fe8d"` |
| `_dmarc` | `TXT` | `v=DMARC1; p=none; rua=mailto:rua@dmarc.brevo.com` | N/A | DMARC email security policy | `flarectl dns create --zone roadtotech.me --name _dmarc.roadtotech.me --type TXT --content "v=DMARC1; p=none; rua=mailto:rua@dmarc.brevo.com"` |
---
## Phase 2: Hostinger Nameserver Cutover (`hostinger`)
Once the Cloudflare zone is populated with all records, update the registrar delegation at Hostinger.
#### 2.1 Inspect Current Delegation
Verify your domain's current nameserver registration:
```bash
hostinger domains portfolio get roadtotech.me
```
#### 2.2 Update Nameservers to Cloudflare
Replace `<ns1>` and `<ns2>` with the exact nameservers assigned by Cloudflare in Step 1.1:
```bash
hostinger domains portfolio update-nameservers roadtotech.me \
--ns1 <assigned-ns-1>.ns.cloudflare.com \
--ns2 <assigned-ns-2>.ns.cloudflare.com
```
*Expected Output*: Returns `Status: OK` confirming that custom nameservers were submitted to the registry.
---
## Phase 3: Propagation Verification (`doggo`)
Root TLD nameserver updates typically take between 2 to 15 minutes to reflect across global recursive caches.
#### 3.1 Verify Authoritative Nameserver Cutover
Query the parent `.me` nameservers directly to confirm the registrar published the new delegation:
```bash
# Query root authoritative DNS
doggo NS roadtotech.me @1.1.1.1
doggo NS roadtotech.me @8.8.8.8
```
*Verification Check*: Output should list the two Cloudflare nameservers instead of `ns*.dynu.com`.
#### 3.2 Verify Public Hostname Resolution
Check that public resolvers return your homelab's current WAN IP (`186.112.11.188`):
```bash
# Verify apex, Gitea, and mail endpoints
doggo roadtotech.me @1.1.1.1
doggo gitea.roadtotech.me @1.1.1.1
doggo mail.roadtotech.me @1.1.1.1
```
*Verification Check*: Returns `186.112.11.188` with a low TTL (~300s).
---
## Phase 4: Homelab Core Refactor & Cleanup
Once public DNS is fully answering from Cloudflare, we bring the homelab appliance into permanent alignment:
#### 4.1 Update Traefik ACME Challenge Provider (`Core`)
In `~/Homelab/Core/docker-compose.yml`:
* Replace `--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu` with `cloudflare`.
* Update the environment projection in `nixos/modules/homeserver.nix` to inject `CF_DNS_API_TOKEN` instead of `DYNU_API_KEY`.
#### 4.2 Replace Dynu Monitor with Cloudflare DDNS
* Decommission `dynu-monitor.service` and `dynu-monitor.timer`.
* Configure `ddclient` (or a dedicated Cloudflare API updater unit) to update Cloudflare's A record when the WAN IP rotates.
#### 4.3 Revert Emergency Workarounds
* **Laptop (`~/Config`)**:
```bash
git -C ~/Config checkout main
sudo nixos-rebuild switch --flake ~/Config#laptop
git -C ~/Config branch -D chore/dynu-outage-workaround
```
* **Server (`~/Homelab/Core`)**:
```bash
git -C ~/Homelab/Core checkout main
git -C ~/Homelab/Core branch -D fix/server-loopback-dns
```
+8 -2
View File
@@ -1,17 +1,23 @@
--- ---
type: plan type: plan
status: active status: superseded
superseded_by: ~/Config/home/scripts/new-repo.py
project: new-repo project: new-repo
tags: tags:
- gitea - gitea
- github - github
- rust - python
- automation - automation
- cli - cli
- sops - sops
--- ---
# 📋 Implementation Plan — `new-repo` Provisioning CLI # 📋 Implementation Plan — `new-repo` Provisioning CLI
> [!NOTE]
> **Architecture Pivot (2026-10-09)**:
> This plan's compiled Rust approach was evaluated and superseded by a lightweight, zero-dependency Python 3 implementation located in `~/Config/home/scripts/new-repo.py`. This eliminated cargo build steps while preserving strict typing (Pyright), linting (Ruff), and in-memory SOPS security.
## 🎯 Objective ## 🎯 Objective
Build a fast, type-safe, and self-contained Rust command-line tool (`new-repo`) to provision repositories across self-hosted Gitea and GitHub with automated push mirroring, template generation, and zero plaintext secret leakage. Build a fast, type-safe, and self-contained Rust command-line tool (`new-repo`) to provision repositories across self-hosted Gitea and GitHub with automated push mirroring, template generation, and zero plaintext secret leakage.
@@ -0,0 +1,97 @@
---
type: plan
status: completed
project: skills
date: 2026-10-23
tags:
- nix
- devshell
- agent-skills
- build-skill
- specification
---
# Plan: Nix Development Shell Authoring Skill (`nix-devshell`)
## Epistemic Role & Purpose
This document is the approved technical specification and implementation plan for transforming the reconciled Nix development-shell manifesto (`manifesto-revised.md` and `audit/compatibility-verification.md`) into a portable, evidence-based agent skill (`skills/nix-devshell/`).
It defines the skill's operational boundaries, source authority hierarchy, progressive validation levels, Git ownership invariants, canonical reference division, and acceptance criteria.
---
## 1. Source Authority Hierarchy
Claims and guidance in the skill follow a strict 3-tier hierarchy:
1. **Primary Authority (`manifesto-revised.md`)**: The authoritative technical specification. All core operational prescriptions in the skill trace directly to manifesto sections.
2. **Constraint & Qualification Layer (`audit/compatibility-verification.md`)**: Narrows, bounds, and flags version-sensitive or unresolved manifesto claims. Does not introduce ungrounded rules.
3. **Provenance & Context Only (`audit/manifesto-audit.md`, `audit/manifesto-revision-log.md`)**: Documents the rationale for historical revisions; never cited as independent technical authority.
### Bounded Claims & Explicit Evidence Labels
| Manifesto Area | Constraint Applied | Evidence & Applicability in Skill |
|---|---|---|
| §6.2 Environment attributes | Flat, non-reserved attributes become shell variables; protected variables require `shellHook`. Nested `env` is excluded from portable guidance. | `Established` for nixpkgs 24.05 tutorial; `Unresolved` across older revisions. Verify against project lock. |
| §5 D4 Compiler selection | Changing the compiler requires selecting a toolchain/stdenv (`mkShell.override { stdenv = ...; }`). Adding a compiler package to `packages` does not guarantee `CC`. | `Established` pattern in nixpkgs, version-sensitive. Check target revision and platform. |
| §4.5 Foreign binaries on NixOS | Diagnosis split by failure mode: missing ELF interpreter vs. missing shared objects vs. FHS path assumptions. | `Established` in nix.dev FAQ. Linux/NixOS only; `nix-ld` is host-level configuration. |
| §5 D2 Tarball & Renovate inputs | Nix locking an input and a bot updating it are separate concerns. Cache availability is a third, separate question. | Renovate Nix manager docs (v44.181.0, beta/opt-in). Check project tooling. |
| §2, §9.1 Compatibility matrix | No numeric minimum version or universal nixpkgs release range is declared. | Policy from verification audit: verify against target lock and host Nix baseline. |
---
## 2. Operational Invariants & Git Boundaries
1. **Evidence-First Inspection**: The agent must inspect existing Nix files, `flake.lock` (or record that none is present), `.envrc`, language manifests, build scripts, CI, and host Nix capabilities *before* deciding on an architecture.
2. **Strict Git Ownership**:
- `nix-devshell` may create and modify project files.
- It **must never** run `git add`, `git commit`, `git stash`, or mutate the Git index or history.
- Staging and committing are strictly handed off to `git-commit`.
3. **Untracked File Blockage vs. Failure**:
- In a Git-backed flake, newly created untracked files are omitted by Nix's Git source filtering.
- The skill must **not** stage files to bypass this.
- It must **not** substitute `path:.` by default (as this copies untracked files and potential secrets to `/nix/store` and does not test the Git-filtered workflow).
- Flake evaluation must be reported as `blocked: <file> untracked by Git`, while running independent checks (e.g. `nix-instantiate --parse`).
- The user is instructed under *User actions* to track files (manually or via `git-commit`) and rerun blocked levels.
---
## 3. Four-Level Progressive Validation Semantics
Validation must proceed progressively through distinct phases; earlier levels never prove later ones:
| Level | Commands (Project-Aligned) | What It Proves | What It Does NOT Prove |
|---|---|---|---|
| **1. Evaluation** | `nix flake show`; `nix eval .#devShells.<sys>.default.drvPath`; `nix-instantiate shell.nix` | Expression evaluates and produces derivation for that system | That inputs can be fetched or built, or that the shell starts |
| **2. Realization + Shell Start** | `nix develop --command true`; `nix-shell --run true` | Store paths exist on host and shell initializes in command mode | That tools have correct versions or that project builds |
| **3. Environment Check** | `nix develop --command <tool> --version`; `command -v <tool>`; `pkg-config --modversion` (only if build uses it) | Named tools, versions, and variables are present in shell | That compilation, linking, or runtime commands succeed |
| **4. Project Command** | `nix develop --command <build/test/lint command>` | That specific command succeeded on tested host with current inputs | Other commands, platforms, or unpinned ecosystem downloads |
`nix flake check` sits beside this hierarchy: it evaluates recognized outputs and builds `checks.<system>`, but does not enter `devShells` or run project build commands unless a check explicitly does so.
---
## 4. Reference Architecture
The skill follows `build-skill/references/skeleton.md`: `SKILL.md` stays strictly $\le 80$ lines, while technical depth is organized into 5 dedicated reference files:
```text
skills/nix-devshell/
├── SKILL.md # Operational steps, report format, Your call (<= 80 lines)
└── references/
├── design-decisions.md # Workflow, commands, inputs, systems, constructors, deps
├── native-deps.md # Outputs, hooks, pkg-config, compiler overrides, FHS/nix-ld
├── authoring-patterns.md # Syntax pitfalls, mkShell arguments, standalone minimal patterns
├── validation-troubleshooting.md # 6 execution phases, 4 validation levels, symptom table
└── compatibility.md # Epistemic labels, inspection protocol, version caveats, sources
```
---
## 5. Repository Integration & Verification Gates
- **Installation**: Registered in `install.sh` under `ACTIVE_PORTABLE_SKILLS` in alphabetical order.
- **Documentation**: Documented in `README.md` under Portable Core table.
- **Change Management**: Authored on feature branch `feat/nix-devshell`; zero unapproved commits to `main`.
- **Dogfooding**: Validated through fresh-context subagents executing in 10 isolated fixture repositories under `~/Projects/tests/nix-devshell-dogfood/`.
@@ -0,0 +1,104 @@
---
type: plan
status: draft
project: armonia-dashboard
pilot: group-workshop-roster
date: 2026-10-25
tags: [collaboration-plan, pilot, governance, anne-droid, qa]
---
# Project Collaboration Plan: Group Workshop Roster Pilot
> **Status:** Draft Working Plan (Under Owner Review)
> **Target System:** `armonia-dashboard`
> **Pilot Simplification Note:** For this pilot, the Orchestrator synthesizes both the requirements and the UX proposal. This is a deliberate pilot simplification to test the workflow without premature agent proliferation; it does **not** demonstrate that Requirements Engineering and UX Design are interchangeable in the permanent agency architecture.
---
## 1. Active Role Roster & Authority Boundaries
```mermaid
sequenceDiagram
autonumber
actor PO as Project Owner
participant ORCH as Orchestrator
participant ANNE as Anne Droid (Frontend)
participant QA as Independent QA
PO->>ORCH: 1. Approve Collaboration Plan & Spec Contract
ORCH->>ANNE: 2. Delegate approved spec + API contract
Note over ANNE: Worktree: ../armonia-dashboard-anne-roster<br/>Implements views, styles, unit tests<br/>Documents contract friction if blocked
ANNE->>ORCH: 3. Open Draft PR & Freeze Anne Self-Audit
Note over ORCH,QA: Information Barrier: QA has ZERO access<br/>to Anne's code diff, PR text, or self-audit
ORCH->>QA: 4. Dispatch Running URL + Verification Packet ONLY
Note over QA: Executes Scenarios 1 to 8<br/>Verifies UI, persistence (F5), a11y, mobile
QA->>ORCH: 5. Submit QA Evidence Scorecard (Pass/Fail per AC)
ORCH->>PO: 6. Present PR Diff + Anne Audit + QA Scorecard
alt All Criteria Pass & Evidence Verified
PO->>ANNE: 7a. Authorize PR Merge into main
else Defects / Gaps Detected
PO->>ORCH: 7b. Issue Revision Directive (routed per Escalation Protocol)
end
```
| Role | Operational Scope for This Pilot | Autonomous Authority | Strict Boundary / Prohibited |
| :---------------------------- | :------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------- |
| **Project Owner** | Final business authority, requirement sign-off, risk acceptance, conflict adjudication, and release approval. | All consequential product and architectural decisions. | N/A |
| **Orchestrator** | Synthesizes specification; monitors handoffs; verifies precondition gates; routes escalation friction. | Workflow sequencing, contract packaging, QA test dispatching. | **Cannot** modify acceptance criteria, relax invariants, waive QA defects, or approve PR merges. |
| **Anne Droid (Frontend)** | Implements frontend views, styles, and component tests against the approved contract. | Component modularity, state architecture, styling tokens, local unit tests, implementation decomposition, and commit sequencing. | **Cannot** commit to `main`, modify business logic, silently mock API endpoints, merge PRs, or **modify/refactor existing working features outside the assigned scope**. |
| **Independent QA Specialist** | Validates running application against acceptance criteria using the Verification Packet. | Pass/Fail/Blocked verdicts per criterion backed by browser evidence. | **Cannot** waive acceptance criteria, inspect Anne's code/self-audit, or make release decisions. |
### 1.1 Scope Containment & Non-Regression Invariant
When tasked with implementing a new feature (Feature C, e.g. Workshop Roster):
1. **Preserve Existing Capabilities**: Existing views and features (Features A and B: Follow-up Queue, Daily Agenda, Client Directory, Nueva Cita modal) must continue to function without behavioral, visual, or test regressions. All existing test suites (`pnpm exec vp test`) must pass 100%.
2. **Beyond Automated Tests (Targeted Workflow Checks)**: Because existing automated tests may not cover every edge in Queue or Agenda, Anne's self-audit must execute targeted smoke checks of those existing workflows (e.g. verifying that the 48h queue loads and the Nueva Cita modal still opens without errors).
3. **Additive Isolation & Justified Integration**: Feature C must reside in dedicated, isolated files (e.g., `src/components/WorkshopRoster.ts`). Edits to shared integration points (`main.ts`, `api.ts`, `types.ts`, `style.css`) should be strictly additive by default. If an unavoidable non-additive integration edit is required, Anne must document and justify it in her frozen self-audit.
4. **No Opportunistic Refactoring**: Anne is strictly prohibited from rewriting, reorganizing, or reformatting existing working components unless explicitly instructed by the Specification Contract.
5. **Self-Audit Regression Gate**: Anne's frozen self-audit must explicitly prove that existing tabs still render correctly and that the git diff is tightly bounded to the assigned feature.
### 1.2 Incremental Implementation & Commit Discipline
Anne Droid owns the decomposition of the approved feature specification into coherent implementation increments. The Project Owner defines the required outcomes and acceptance criteria; the Orchestrator does not prescribe the implementation task sequence unless a specific dependency, risk, or contract constraint requires intervention.
1. **Engineer-Owned Decomposition**: Before writing code, Anne identifies a practical sequence of implementation increments based on the approved contract and existing architecture. The sequence is an engineering breakdown, not a source of new product requirements. Missing requirements or consequential scope changes must be escalated rather than resolved through implementation planning alone.
2. **Coherent Incremental Commits**: Anne commits completed increments as work progresses. Each commit must have a clear purpose, a reviewable diff, and a Conventional Commit message describing the change (e.g., `feat(roster): add API client and roster types`, `feat(roster): implement session card and capacity indicators`). Commits must reflect genuine progress rather than arbitrary file boundaries or retrospective subdivision of a completed feature.
3. **Intermediate Integrity**: Each commit should leave the branch in a coherent state and pass the checks relevant to its changes (`pnpm exec biome check .`, `vp check`). The completed feature must pass the full required test suite. Any temporary intermediate limitation must be intentional, documented in commit notes, and resolved before the PR is submitted for review.
4. **Scope and Regression Boundaries**: Incremental commits do not authorize opportunistic refactoring or unrelated behavior changes. Changes to existing features and shared integration points remain subject to the Scope Containment & Non-Regression Invariant.
5. **Traceability and Review**: Anne's frozen self-audit must summarize the implementation increments, map commits to acceptance criteria, explain any justified deviations from the initial breakdown, and document any known limitations. The Orchestrator may flag incoherent commits, excessive unrelated changes, or gaps in traceability, but may not dictate implementation details solely to enforce a preferred task sequence.
6. **Integrated Verification**: Commit-level checks do not replace feature-level acceptance testing or independent QA. The complete pull request remains subject to the approved Specification Contract, Verification Packet, regression requirements, and Project Owner's release decision.
### 1.3 Clarification on QA Failure Routing & Final Acceptance
- **QA owns its findings and supporting evidence**, not the release decision.
- If QA reports a failure on an acceptance criterion, the Orchestrator routes the defect back to Anne (for an implementation bug) or to the relevant specialist (for an API or requirement flaw).
- **The Orchestrator cannot waive a failure or convert a failed acceptance criterion into a pass.** Only the Project Owner has the authority to relax a requirement, accept a known risk, or authorize a PR merge.
---
## 2. Phase-by-Phase Handoff Matrix
| Phase | Acting Role | Required Input | Produced Output | Approval Gatekeeper |
| :------------------------------------ | :----------------------------------------- | :------------------------------------------- | :----------------------------------------------------------- | :------------------------------------------------ |
| **Phase 1: Operating Model** | Orchestrator | Pre-experiment baseline snapshot | `COLLABORATION-PLAN.md` | **Project Owner** (Signs off on roles) |
| **Phase 2: Contract Formulation** | Orchestrator (Requirements + UX synthesis) | API schema, M4 roadmap scope | `SPEC-WORKSHOP-ROSTER.md` + `VERIFICATION-PACKET-ROSTER.md` | **Project Owner** (Approves criteria & test data) |
| **Phase 3: Implementation** | Anne Droid | Approved spec + running API | `feat/anne/workshop-roster` PR + frozen `anne-self-audit.md` | **Anne Droid** (Freezes self-audit prior to QA) |
| **Phase 4: Independent Verification** | QA Specialist | Running build URL + Verification Packet ONLY | `qa-evidence-scorecard.md` | **QA Specialist** (Signs off on test evidence) |
| **Phase 5: Release & Post-Mortem** | Project Owner | PR diff + Anne Audit + QA Scorecard | Merge decision + Pilot evaluation log | **Project Owner** (Decides merge / rework) |
---
## 3. Explicit Change & Escalation Protocol
If any specialist encounters a blocking condition or contradiction, work halts at that boundary and routes strictly according to problem type:
```mermaid
flowchart LR
BLOCK["Friction Encountered"] --> CAT{Classify Problem}
CAT -->|"Contradictory / Missing Business Rule"| REQ["Orchestrator / Requirements"]
CAT -->|"Unworkable Interaction Flow"| UX["Orchestrator / UX"]
CAT -->|"API Schema Defect / Backend 500"| BE["Backend Owner / Issue Tracker"]
CAT -->|"Implementation Bug"| ANNE["Anne Droid (Worktree)"]
CAT -->|"Ambiguous / Broken Test Criterion"| QA["Requirements + QA Specialist"]
CAT -->|"Scope Trade-off or Scope Relaxation"| PO["Project Owner (Human Decision)"]
```
1. **API Friction Rule**: Anne must record a structured **Contract Friction Notice** on the PR rather than silently creating synthetic mock data or changing expected response shapes.
2. **Owner Escalation Rule**: Any trade-off affecting user workflows (e.g. omitting walk-in check-ins due to API constraints) requires an explicit choice from the Project Owner.
@@ -0,0 +1,192 @@
---
type: plan
role: specification-contract
status: draft
project: armonia-dashboard
feature: workshop-roster-checkin
milestone: M4
date: 2026-10-25
tags: [spec, frontend, requirements, ux, armonia-dashboard]
---
# Specification Contract: Group Workshop Roster Quick Check-in
> **Contract Authority:** Binding implementation contract for `armonia-dashboard`.
> **Engineering Boundary:** This specification defines *what* the operator must accomplish and *how* states behave. The component breakdown, DOM composition, and styling implementation belong to Anne Droid's engineering judgment. Implementation must be strictly additive and isolated; existing features (Follow-up Queue, Daily Agenda, Client Directory, Nueva Cita) must remain undisturbed and 100% passing.
---
## 1. Domain Context & User Goals
In Armonía del Ser, group services (e.g., *Círculo de Cacao Presencial*, *Meditación con Cuencos*) take place with multiple attendees (up to 12–25 capacity).
**The Operator's Goal:**
On the day of the workshop, Jasmin or her assistant stands at reception. As participants arrive, the operator needs a mobile-first, high-density view to:
1. Confirm which group workshop session is active today and review capacity metrics.
2. Rapidly record digital attendance (1-tap check-in marking attendance and completing the booking).
3. Identify payment state at a glance: identify who is pre-paid (`PAGADO` via SPEI) versus who must pay on arrival (`PENDIENTE`).
4. Collect cash on-site and acknowledge payment in the same 1-tap check-in action.
5. Register and check in unexpected walk-in attendees without disrupting the session flow.
---
## 2. Precise Semantic Definitions & Status Mapping
### 2.1 The Two Workshop Counters
```
┌────────────────────────────────────────────────────────────────────────┐
│ Workshop Counter Semantics │
├─────────────────────┬──────────────────────────────────────────────────┤
│ Metric │ Business Meaning & Mutation Rules │
├─────────────────────┼──────────────────────────────────────────────────┤
│ occupied_count │ Total participants holding an active spot │
│ │ (status: RESERVED, COMPLETED, NO_SHOW). │
│ │ • Advance booking created: count increments. │
│ │ • Existing attendee checks in: count UNCHANGED. │
│ │ • Walk-in attendee registers: count increments. │
├─────────────────────┼──────────────────────────────────────────────────┤
│ attended_count │ Participants physically present & verified │
│ │ (booking_status: COMPLETED, attended: true). │
│ │ • Existing attendee checks in: count increments. │
│ │ • Walk-in attendee registers: count increments. │
└─────────────────────┴──────────────────────────────────────────────────┘
```
- **Capacity Display**: Formatted as `Ocupación: {occupied_count} / {max_capacity} ({attended_count} presentes)`.
- **409 Conflict Disambiguation & Reconciliation Contract**:
The backend issues `HTTP 409 Conflict` in two distinct business scenarios, verified against pinned backend commit `d9c86e27d926` in `armonia-api/app/routers/rosters.py`. The client must inspect `response.detail` (or error payload):
1. *Already Checked-In Conflict (`detail: "This attendee has already checked in."`)* (`app/routers/rosters.py#L196`): Indicates an idempotent duplicate submission. The client must reconcile by updating the attendee row to `ASISTIÓ`, disabling the check-in button, and showing an informative status toast (*"El asistente ya contaba con asistencia registrada"*). The client must never crash or treat this as a failed/unregistered state.
2. *Capacity Exceeded Conflict (`detail: "El taller ha alcanzado su cupo máximo ({max_cap}) para esta sesión."`)* (`app/routers/rosters.py#L332`): Occurs during walk-in registration when `occupied_count >= max_capacity`. The client must detect the capacity message (e.g. matching `cupo máximo`), display an explicit capacity error alert (*"El taller ha alcanzado su cupo máximo (15) para esta sesión"*), keep the modal form state intact for operator decision, and **never** optimistically increment attendance or report success.
- **Ordinary Network / 500 Failure**: Preserve the current UI state, do not change attendee status, and allow the operator to retry.
- **Technical Debt & Future Contract Note**: String matching on `response.detail` is a pilot accommodation to preserve backend immutability on `armonia-api`. A future M5 ADR will introduce structured machine-readable error codes (e.g. `{"error_code": "ATTENDEE_ALREADY_CHECKED_IN"}`).
### 2.2 Status Terminology Mapping Table
To prevent ambiguity between UI labels and backend persistence, all badge renderings must adhere to this mapping:
| UI Badge / Label | Visual Styling | Backend Entity | Persisted Status Field & Value |
| :--- | :--- | :--- | :--- |
| **`REGISTRADO`** | Slate/Neutral Pill | `Booking` | `booking_status: "RESERVED"`, `attended: false` |
| **`ASISTIÓ`** | Emerald/Green Pill | `Booking` | `booking_status: "COMPLETED"`, `attended: true` |
| **`PAGADO`** | Emerald/Green Pill | `Booking` & `Payment` | `payment_status: "ACKNOWLEDGED"` |
| **`PENDIENTE`** | Amber/Orange Pill | `Booking` | `payment_status: "AWAITING_ACKNOWLEDGMENT"` |
---
## 3. Resilient Error-Recovery Contract (The 5 States)
Every interactive view in this feature must explicitly handle the 5 states:
```mermaid
stateDiagram
[*] --> Loading: Switch to #rosters tab
Loading --> Empty: GET /rosters returns []
Loading --> Error_Roster: GET /rosters fails (Network/500)
Loading --> Roster_Ready: GET /rosters returns sessions
Error_Roster --> Loading: Tap "Reintentar"
Empty --> Loading: Change date picker
Roster_Ready --> Action_In_Flight: Tap Check-in or Submit Walk-in
Action_In_Flight --> Action_Error: POST fails (Timeout/Network)
Action_In_Flight --> Roster_Ready: POST succeeds (HTTP 200) -> Toast
Action_Error --> Roster_Ready: Toast error; row stays uncommitted
```
1. **Loading State**: Render skeleton placeholder cards for workshop sessions and attendee rows. Layout shift (CLS) must remain $\le 0.05$.
2. **Empty State**: If no group sessions exist for the selected date, display:
> *"No hay talleres grupales programados para esta fecha."*
The date selector remains interactive so the operator can navigate to adjacent days.
3. **Failed Roster Retrieval (Error with Retry)**: If `GET /rosters` fails (network down or server error), display an inline error banner:
> *"No se pudieron cargar los talleres. Verifica tu conexión."*
Accompanied by an explicit `<button class="btn btn-secondary">Reintentar</button>` that re-triggers the fetch without a full page reload.
4. **Action Failure & Conflict Recovery**:
- *Already-Checked-In Conflict (409)*: If the server reports the attendee is already checked in, the client reconciles state by updating the row to `ASISTIÓ`, disabling check-in, and displaying an informative notice (*"El asistente ya contaba con asistencia registrada"*).
- *Capacity Reached Conflict (409)*: If a walk-in is rejected because the session is full, the client reports the capacity limit (*"El taller ha alcanzado su cupo máximo"*), leaves the form open for operator decision, and does not record attendance.
- *Network / Server Error (5xx / Timeout)*: The client displays an accessible error toast, preserves the uncommitted attendee row state (no optimistic toggle), and keeps the action button enabled for immediate retry.
5. **Success Feedback State**: Upon successful check-in or walk-in:
- Immediate visual feedback on the row (`ASISTIÓ` badge).
- Display an accessible toast container equipped with `role="status"` and `aria-live="polite"` announcing: *"Asistencia registrada con éxito."*
---
## 4. Explicit Acceptance Criteria (AC)
### `AC-1`: Workshop Session Selection & Capacity Overview
- **Given** the operator navigates to the "Talleres" tab (URL hash `#rosters`),
- **When** the view loads for the selected date (default: today),
- **Then** it queries `GET /rosters?date_from=YYYY-MM-DD&date_to=YYYY-MM-DD`.
- **And** it displays the group session title, scheduled time, and a capacity counter formatted as `Ocupación: {occupied_count} / {max_capacity} ({attended_count} presentes)`.
### `AC-2`: Attendee Roster Display & Status Indicators
- **Given** an active workshop session with registered attendees,
- **When** the session roster renders,
- **Then** each attendee row displays: Client Name, Phone, Booking Code (`ADS-XXXX`), Attendance Status (`REGISTRADO` vs. `ASISTIÓ`), and Payment Status (`PAGADO` vs. `PENDIENTE`).
- **And** includes a 1-tap `wa.me` link pre-populated with the attendee's phone.
### `AC-3`: Existing Booking Check-in (Pre-paid)
- **Given** an attendee with `booking_status: "RESERVED"` and `payment_status: "ACKNOWLEDGED"`,
- **When** the operator taps the "Registrar Asistencia" button,
- **Then** the client sends `POST /rosters/quick-checkin` with payload `{"booking_id": "<id>", "paid_cash": false}`.
- **And** upon HTTP 200, the row immediately updates to `ASISTIÓ`, the check-in button disables, and `attended_count` increments by 1.
### `AC-4`: Existing Booking Check-in with Cash Payment Acknowledgment
- **Given** an attendee with `payment_status: "AWAITING_ACKNOWLEDGMENT"`,
- **When** the operator taps check-in with "Cobro en efectivo recibido" checked,
- **Then** the client sends `POST /rosters/quick-checkin` with payload `{"booking_id": "<id>", "paid_cash": true, "notes": "Cobro en puerta"}`.
- **And** upon HTTP 200, the row reflects both `ASISTIÓ` and `PAGADO` (`ACKNOWLEDGED`), and `attended_count` increments by 1 without full page reload.
### `AC-5`: Walk-in Attendee Quick Registration & Check-in
- **Given** an unregistered participant arrives at the workshop,
- **When** the operator taps "+ Registrar Asistente Sin Cita",
- **Then** a modal opens requesting: Full Name, Phone (WhatsApp), and Cash Payment toggle (defaults to `true` / checked, because walk-in reception is predominantly cash).
- **When** submitted, the client sends `POST /rosters/quick-checkin` with Mode 2 payload:
`{"service_id": "<id>", "scheduled_at": "<iso>", "client_name": "...", "client_phone": "...", "paid_cash": true}`.
- **And** upon HTTP 200, the modal closes, the attendee appears in the list as `ASISTIÓ` and `PAGADO`, and both `occupied_count` and `attended_count` increment by 1.
- **And** the modal submit button disables while in flight to prevent accidental double-click duplicate registrations.
### `AC-6`: Resilient Error Handling & Retry
- **Given** an error state (failed roster fetch or interrupted check-in),
- **Then** the UI exposes an actionable retry path without clearing existing form data or falsely marking attendees present.
### `AC-7`: Mobile Ergonomics & Keyboard Accessibility
- All interactive controls (Check-in buttons, Cash toggles, Walk-in trigger, Modal inputs) must have touch targets of at least **44x44px**.
- Roster rows must render cleanly at **375px** viewport width without horizontal scroll overflow.
- All interactive controls must support sequential keyboard focus (`Tab` / `Shift+Tab`) with visible `:focus-visible` outlines.
- Toast feedback must announce to assistive technology via `role="status"` and `aria-live="polite"`.
---
## 5. Navigation & Architectural Conventions
1. **Tab Identifier**: `rosters`
2. **URL Hash**: `#rosters`
3. **Navigation Label**: "Talleres"
4. **Header Integration**: Integrated into `OperatorDashboardApp.renderShell()` in `src/main.ts` alongside `#queue`, `#agenda`, `#clients`, and `#all`.
5. **Cash Toggle Default**: In the walk-in modal, the "Cobro en efectivo recibido" toggle defaults to **checked (`true`)**. *Rationale:* In-person workshop walk-ins overwhelmingly settle entrance fees in cash at reception. Operators may uncheck if the client provides immediate SPEI transfer verification.
---
## 6. API Contract Reference
The view interacts strictly with existing endpoints defined in `armonia-api`:
- **Endpoint 1:** `GET /rosters?date_from={YYYY-MM-DD}&date_to={YYYY-MM-DD}&service_id={optional}`
- *Response Shape:* `list[RosterSessionRead]` (see `app/schemas/roster.py`).
- **Endpoint 2:** `POST /rosters/quick-checkin`
- *Mode 1 (Existing Booking):*
```json
{ "booking_id": "uuid-str", "paid_cash": true, "notes": "Opcional" }
```
- *Mode 2 (Walk-In):*
```json
{
"service_id": "uuid-str",
"scheduled_at": "2026-10-25T18:00:00Z",
"client_name": "Nombre Cliente",
"client_phone": "525512345678",
"paid_cash": true
}
```
- *Response:* `QuickCheckinResponse` (`walk_in: bool`, `attendee: RosterAttendeeRead`).
- *Conflict Behavior:* HTTP 409 Conflict if attendee already completed or session at max capacity.
@@ -0,0 +1,237 @@
---
type: plan
role: verification-packet
status: draft
project: armonia-dashboard
feature: workshop-roster-checkin
date: 2026-10-25
tags: [qa, verification-packet, test-data, blind-testing]
---
# Verification Packet: Group Workshop Roster Quick Check-in
> **Notice to Independent QA Reviewer:** This packet contains **all** instructions, test personas, and expected observable criteria needed to verify the feature. You must evaluate the running application *without* inspecting the pull request discussion, implementation source code, or the implementer's self-audit.
---
## 1. Frozen Environment & Runtime Configuration
Prior to executing test scenarios, verify that both services are running on the specified commits:
| Component | Target Directory | Verified Commit Hash | Start Command | Active Port |
| :--- | :--- | :--- | :--- | :--- |
| **Backend API** | `armonia/armonia-api` | `d9c86e27d926bab3287857ccc9b53ec4fbcec91b` | `DATABASE_URL=file:test_armonia.db uv run python -m uvicorn app.main:app --port 8000` | `http://localhost:8000` |
| **Frontend UI** | `armonia/armonia-dashboard` | PR Branch (`feat/anne/workshop-roster`) | `pnpm exec vp dev --port 5173` | `http://localhost:5173` |
---
## 2. Tested & Verified Test Database Seed Script with Preflight Assertions
Run this command inside `armonia-api` using `uv run python`. It creates a clean disposable SQLite database (`test_armonia.db`), initializes default services, seeds the exact test records required for today's date, and **formally asserts all four preflight conditions** before completing:
```bash
cd /home/kiskaadee/Projects/active/armonia/armonia-api && uv run python -c "
import os, asyncio
from datetime import datetime, UTC
from zoneinfo import ZoneInfo
from pathlib import Path
# Deterministic absolute path anchoring
abs_db_path = (Path.cwd() / 'test_armonia.db').resolve()
assert abs_db_path.name.startswith('test_') and abs_db_path.name != 'local.db', 'Safety failure: refusal to touch non-test database'
if abs_db_path.exists():
abs_db_path.unlink()
os.environ['DATABASE_URL'] = f'file:{abs_db_path}'
from app.core.config import settings
settings.database_url = f'file:{abs_db_path}'
from app.db.init_db import init_schema_and_seed
from app.db.database import get_db
from fastapi.testclient import TestClient
from app.main import app
from app.core.auth import create_session_token
async def seed_and_verify():
# 1. Initialize schema and default services
await init_schema_and_seed()
async with get_db() as client:
# Preflight 1: Assert service exists with expected capacity of 15
res = await client.execute('SELECT id, name, price_mxn, max_capacity FROM services WHERE slug = \"circulo-cacao-presencial\" LIMIT 1;')
assert res.rows, 'Preflight 1 Failed: circulo-cacao-presencial service not found!'
cacao_id, cacao_name, price_mxn, max_capacity = res.rows[0]
assert max_capacity == 15, f'Preflight 1 Failed: Expected capacity 15, got {max_capacity}'
# Preflight 2: Calculate today's session instant at 18:00
tz = ZoneInfo(settings.business_timezone)
today = datetime.now(tz).date()
today_str = today.isoformat()
session_dt = datetime(today.year, today.month, today.day, 18, 0, 0, tzinfo=tz).astimezone(UTC).isoformat()
now = datetime.now(UTC).isoformat()
# Insert Elena Gómez (Prepaid SPEI: RESERVED + ACKNOWLEDGED)
client_elena = 'c1111111-1111-1111-1111-111111111111'
booking_elena = 'b1111111-1111-1111-1111-111111111111'
await client.execute('INSERT OR REPLACE INTO clients (id, full_name, phone_whatsapp, email) VALUES (?, ?, ?, ?);',
[client_elena, 'Elena Gómez', '525511112222', 'elena@example.com'])
await client.execute('''
INSERT OR REPLACE INTO bookings (
id, booking_code, service_id, client_id, scheduled_at, duration_minutes, buffer_minutes,
booking_status, payment_arrangement, payment_status, amount_mxn, created_at
) VALUES (?, ?, ?, ?, ?, 120, 0, 'RESERVED', 'PREPAID_DEFAULT', 'ACKNOWLEDGED', ?, ?);
''', [booking_elena, 'ADS-1001', cacao_id, client_elena, session_dt, price_mxn, now])
# Insert Carlos Méndez (Unpaid: RESERVED + AWAITING_ACKNOWLEDGMENT)
client_carlos = 'c2222222-2222-2222-2222-222222222222'
booking_carlos = 'b2222222-2222-2222-2222-222222222222'
await client.execute('INSERT OR REPLACE INTO clients (id, full_name, phone_whatsapp, email) VALUES (?, ?, ?, ?);',
[client_carlos, 'Carlos Méndez', '525533334444', 'carlos@example.com'])
await client.execute('''
INSERT OR REPLACE INTO bookings (
id, booking_code, service_id, client_id, scheduled_at, duration_minutes, buffer_minutes,
booking_status, payment_arrangement, payment_status, amount_mxn, created_at
) VALUES (?, ?, ?, ?, ?, 120, 0, 'RESERVED', 'PREPAID_DEFAULT', 'AWAITING_ACKNOWLEDGMENT', ?, ?);
''', [booking_carlos, 'ADS-1002', cacao_id, client_carlos, session_dt, price_mxn, now])
# Preflight 3: Endpoint level validation (assert endpoint returns exact expected session & attendees)
tc = TestClient(app)
headers = {'Authorization': f'Bearer {create_session_token(\"asistente@armoniadelser.mx\")}'}
r = tc.get(f'/rosters?date_from={today_str}&date_to={today_str}', headers=headers)
assert r.status_code == 200, f'Preflight 3 Failed: GET /rosters returned {r.status_code}'
data = r.json()
assert len(data) == 1, f'Preflight 3 Failed: Expected 1 session, got {len(data)}'
sess = data[0]
assert sess['occupied_count'] == 2 and sess['attended_count'] == 0, 'Preflight 3 Failed: Initial counts mismatch'
codes = {att['booking_code'] for att in sess['attendees']}
assert codes == {'ADS-1001', 'ADS-1002'}, f'Preflight 3 Failed: Missing expected codes {codes}'
# Preflight 4: File existence & non-empty database target
assert abs_db_path.exists() and abs_db_path.stat().st_size > 0, 'Preflight 4 Failed: Database file missing or empty'
print('✅ Preflight assertions passed: 100% verified test database ready at', abs_db_path)
asyncio.run(seed_and_verify())
"
```
---
## 3. Pre-Configured Test Attendee Personas
| Attendee Persona | Initial Persisted State | Expected Initial UI Rendering | Expected Post-Action State |
| :--- | :--- | :--- | :--- |
| **Elena Gómez** (`ADS-1001`) | `booking_status: "RESERVED"`, `payment_status: "ACKNOWLEDGED"`, `attended: false` | Badge: `REGISTRADO`<br/>Badge: `PAGADO` (Green)<br/>Action: "Registrar Asistencia" | After check-in: Badge updates to `ASISTIÓ`. Counter increments to `1 presente`. |
| **Carlos Méndez** (`ADS-1002`) | `booking_status: "RESERVED"`, `payment_status: "AWAITING_ACKNOWLEDGMENT"`, `attended: false` | Badge: `REGISTRADO`<br/>Badge: `PENDIENTE` (Amber)<br/>Action: Check-in + "Cobro efectivo" | After cash check-in: Badge updates to `ASISTIÓ` AND `PAGADO`. Counter increments. |
| **Walk-in: Lucía Vega** | Not in database initially | Not present in list | After registration: Appears in list as `ASISTIÓ` and `PAGADO`. Occupancy becomes `3 / 15`. |
---
## 4. Test Execution Scenarios & Concrete Pass/Fail Criteria
### Scenario 1: Navigation, Tab Hash & Capacity Overview (`AC-1`)
1. Open `http://localhost:5173` in a desktop browser.
2. Click the "Talleres" navigation button in the top navigation bar.
3. **Pass Criteria:**
- [ ] URL updates to `http://localhost:5173/#rosters`.
- [ ] "Talleres" tab button reflects active state (`aria-selected="true"`).
- [ ] Session card for "Círculo de Cacao (Presencial)" renders with time 18:00.
- [ ] Capacity counter displays exactly: `Ocupación: 2 / 15 (0 presentes)`.
### Scenario 2: Attendee Roster Display & Status Badges (`AC-2`)
1. Inspect the attendee table/list for the active workshop.
2. **Pass Criteria:**
- [ ] Elena Gómez is listed with booking code `ADS-1001`, status `REGISTRADO`, and payment pill `PAGADO`.
- [ ] Carlos Méndez is listed with booking code `ADS-1002`, status `REGISTRADO`, and payment pill `PENDIENTE`.
- [ ] Both rows display a clickable WhatsApp link (`wa.me/525511112222` and `wa.me/525533334444`).
### Scenario 3: Pre-paid Attendee Check-in & Persistence Verification (`AC-3`)
1. On Elena Gómez's row (`ADS-1001`), tap "Registrar Asistencia".
2. **Pass Criteria (UI & Persistence):**
- [ ] Network inspector shows `POST /rosters/quick-checkin` returned HTTP 200 with payload `{"booking_id": "...", "paid_cash": false}`.
- [ ] Elena's status badge updates from `REGISTRADO` to `ASISTIÓ`.
- [ ] Capacity summary updates to `Ocupación: 2 / 15 (1 presentes)`.
- [ ] An accessible toast announces: *"Asistencia registrada con éxito."*
- [ ] **Persistence Proof:** Refresh the browser page (`F5`). Upon reload, Elena still renders as `ASISTIÓ` and capacity remains `1 presente`.
### Scenario 4: Cash Check-in & Payment Status Transition (`AC-4`)
1. On Carlos Méndez's row (`ADS-1002`), trigger check-in with the "Cobro en efectivo recibido" checkbox checked.
2. **Pass Criteria (UI & Persistence):**
- [ ] Network inspector shows `POST /rosters/quick-checkin` returned HTTP 200 with `paid_cash: true`.
- [ ] Carlos's status badge updates to `ASISTIÓ`.
- [ ] Carlos's payment pill transitions from `PENDIENTE` to `PAGADO`.
- [ ] Capacity summary updates to `Ocupación: 2 / 15 (2 presentes)`.
- [ ] **Persistence Proof:** Refresh the browser page (`F5`). Carlos renders with both `ASISTIÓ` and `PAGADO`.
### Scenario 5: Walk-In Registration & Double-Submission Prevention (`AC-5`)
1. Click the "+ Registrar Asistente Sin Cita" button.
2. In the modal:
- Full Name: `Lucía Vega`
- Phone: `525598765432`
- Cash toggle: confirm it defaults to **checked (`true`)**.
3. **Double-Submission Test**: Rapidly click "Registrar y Marcar Asistencia" twice in succession.
4. **Pass Criteria:**
- [ ] Submit button disables immediately while the request is in flight.
- [ ] Exactly **one** walk-in record is created (network inspector shows only one successful registration; second click is ignored or blocked).
- [ ] Modal closes upon HTTP 200.
- [ ] Lucía Vega appears in the active attendee list with `ASISTIÓ` and `PAGADO`.
- [ ] Capacity counter updates to exactly `Ocupación: 3 / 15 (3 presentes)` (NOT `4 / 15`).
- [ ] **Persistence Proof:** Refresh the browser (`F5`). Exactly one Lucía Vega record remains persisted in the roster.
### Scenario 6: 409 Conflict Disambiguation & Reconciliation
1. **Case 6A (Already-Checked-In Idempotency)**: Trigger a duplicate check-in request via network replay or rapid re-tap for an already checked-in attendee (`ADS-1001`).
- **Pass Criteria:**
- [ ] Backend returns `HTTP 409 Conflict` (`"This attendee has already checked in."`).
- [ ] UI catches the 409, reconciles state, displays informative feedback (*"El asistente ya contaba con asistencia registrada"*), and ensures row reflects `ASISTIÓ` without unhandled application crash.
2. **Case 6B (Capacity Reached Conflict)**: When submitting a walk-in to a session at max capacity:
- **Pass Criteria:**
- [ ] Backend returns `HTTP 409 Conflict` (`"El taller ha alcanzado su cupo máximo"`).
- [ ] UI displays explicit capacity error alert; modal form data is preserved; row is **not** added to list.
### Scenario 7: Failed Roster Fetch & Actionable Retry (`AC-6`)
1. Temporarily stop the backend API process (`Ctrl+C` on uvicorn).
2. Switch dates or refresh the `#rosters` view.
3. **Pass Criteria:**
- [ ] Error banner renders: *"No se pudieron cargar los talleres. Verifica tu conexión."*
- [ ] A visible "Reintentar" button is displayed.
4. Restart the backend API process.
5. Click "Reintentar".
6. **Pass Criteria:**
- [ ] Roster reloads successfully without needing a browser reload.
### Scenario 8: Mobile Ergonomics & Accessibility Tree (`AC-7`)
1. Switch browser DevTools to Mobile Emulation: **375 x 812 px** (iPhone SE/X).
2. **Pass Criteria:**
- [ ] Zero horizontal scroll overflow on the table/cards.
- [ ] All check-in buttons, toggles, and modal inputs have minimum touch bounding boxes of **44 x 44 px**.
3. Navigate the view using only the keyboard (`Tab` and `Shift+Tab`).
4. **Pass Criteria:**
- [ ] Focus indicator is visibly highlighted on every active button and input.
- [ ] Toast notification container possesses `role="status"` and `aria-live="polite"`.
---
## 5. Evidence Capture & Scorecard Deliverable
The QA Specialist must produce `qa-evidence-scorecard.md` containing:
1. Formal table checking every criterion (`AC-1` to `AC-7`, Scenarios 1 to 8) with verdict: `PASS`, `FAIL`, or `BLOCKED`.
2. Captured screenshots attached:
- Desktop initial roster view.
- Mobile 375px view showing touch targets.
- Post-check-in state showing updated counter.
- Walk-in modal open state.
3. Browser console log confirming zero uncaught JavaScript exceptions.
4. If any test fails, record: Exact visual element, HTTP status, and response JSON payload.
---
## 6. Reset & Cleanup Procedure
To restore the test environment between verification passes:
```bash
# 1. Stop backend API (Ctrl+C)
# 2. Delete test database file
rm -f /home/kiskaadee/Projects/active/armonia/armonia-api/test_armonia.db
# 3. Re-run the seed script from Section 2
# 4. Restart backend API
```
@@ -0,0 +1,326 @@
---
type: plan
status: active
project: skills
date: 2026-10-24
tags: [skills, agent-architecture, frontend-pilot, anne-droid, qa, armonia-del-ser]
---
# Pre-Experiment Baseline: Armonia Frontend Collaboration Pilot
> **Status:** Active Pre-Experiment Snapshot
> **Target System:** `armonia-dashboard` (Operator Control Surface)
> **Companion Repositories:** `armonia-api` (Backend), `armonia-del-ser/.profile` (Planning & Governance)
> **Inspection Date:** 2026-10-24
> **Epistemic Role:** Durable record of knowledge, hypotheses, repository baselines, and experimental protocols **prior** to running the frontend collaboration pilot. This is not a retrospective, an implementation plan for `rtt-agency`, or a declaration of validated results.
---
## Baseline Manifest
The following Git snapshots establish the verifiable repository state at the moment of inspection prior to any pilot execution:
| Repository | Current Branch | Full Commit Hash | Remote URL (Gitea) | Primary Relevance | Status / Evidence |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **`armonia-dashboard`** | `main` | [`00b59182ac5c776879b7640e77eb6df6f3b085e9`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/00b59182ac5c776879b7640e77eb6df6f3b085e9) | `ssh://git@gitea.roadtotech.me:2223/armonia-del-ser/armonia-dashboard.git` | Target frontend application for the pilot implementation. | **Verified** (Clean tree, PR #8 merged) |
| **`armonia-api`** | `main` | [`d9c86e27d926bab3287857ccc9b53ec4fbcec91b`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b) | `ssh://git@gitea.roadtotech.me:2223/armonia-del-ser/armonia-api.git` | Authoritative backend service; provides API contracts and test fixtures. | **Verified** (Clean tree, M2 completed) |
| **`.profile` (Workspace Root)** | `main` | [`89e3cffc8fc43ecb2ca5a05b6721f7bdbd75d3e8`](https://gitea.roadtotech.me/armonia-del-ser/.profile/commit/89e3cffc8fc43ecb2ca5a05b6721f7bdbd75d3e8) | `ssh://git@gitea.roadtotech.me:2223/armonia-del-ser/.profile.git` | Single Source of Truth for system roadmap, `todo.txt`, and cross-repo governance. | **Verified** (Clean tree, active SSOT) |
---
## 1. Problem Statement & Historical Context
### 1.1 The Armonia Workflow-Completeness Breakdown
The motivation for this pilot originated from a concrete failure in the initial delivery of the Armonia operator dashboard:
- **Original Scope**: Milestone M4 was defined in Gitea issue [`armonia-dashboard#1`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/issues/1) (*"M4: Mobile-First Admin Dashboard for Jasmin & Assistant"*). It requested operational views for booking reviews, 48-hour pending payment follow-ups, payment acknowledgments, delayed-payment authorizations, and package/roster controls.
- **Implementation Sequence**: Anne Droid was delegated the frontend implementation under her existing persona instructions (`profile/agents/anne-droid.md`). In commit [`4e50f7c58606`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/4e50f7c58606709dbc9e95e7ad557869fb4dea78) (merged via PR [#4](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/pulls/4)), Anne scaffolded the dashboard with `FollowUpQueue.ts`, `PaymentModal.ts`, `DailyAgenda.ts`, and `AllBookings.ts`.
- **The Observed Defect**: While the delivered code was modular, typed, accessible, and tested with passing unit tests, the dashboard was **operationally incomplete**: an operator had no capability to create new client appointments from the interface. Furthermore, the workshop roster and package tracker were omitted.
- **The Corrective Rework**: The missing appointment-creation workflow had to be addressed in subsequent rework across separate issues ([`armonia-dashboard#6`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/issues/6) and [`armonia-dashboard#7`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/issues/7)), merged in PR [#8](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/pulls/8) ([`7f56fe019a0a`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/7f56fe019a0a0be96ffeb999e5f15549880816a7)).
- **Causal Interpretation (Inferred Hypothesis)**: The working explanation is that Anne's self-review procedure evaluated visual presence, component rendering, and isolated unit tests rather than structural workflow completeness against explicit acceptance criteria. Because existing views looked aesthetically sound and passed local unit checks, Anne concluded the task was complete. This diagnosis is plausible, but remains an *inference* to be tested by the pilot's interventions rather than an established historical fact.
### 1.2 Epistemic Label
**Verified (Observed Defect & Rework Chain)**: The commit messages, issue descriptions, PR diffs, and roadmap entries confirm the omission and subsequent rework.
**Inferred (Causal Diagnosis)**: The claim that the omission was caused specifically by a lack of requirement-informed workflow verification in Anne's review protocol is an inference to be tested, not a proven historical fact.
---
## 2. Current Technical State & Candidate Deliverable
### 2.1 Candidate Deliverable: Group Workshop Roster Quick Check-in
To test the refined collaboration workflow, the candidate deliverable must represent a real, pending, bounded operational journey:
- **Roadmap Position**: In [`ROADMAP.md#L84`](https://gitea.roadtotech.me/armonia-del-ser/.profile/src/commit/89e3cffc8fc43ecb2ca5a05b6721f7bdbd75d3e8/ROADMAP.md#L84), Milestone M4 retains one remaining unchecked item:
> `- [ ] Multi-session package counter ('8 de 10') & Group Workshop Roster check-in view.`
- **Backend API Readiness**: The backend capabilities were implemented in Milestone M2 ([`armonia-api#6`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/issues/6)) and are active on `armonia-api/main` ([`d9c86e27d926`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b)):
1. `GET /rosters` ([`app/routers/rosters.py#L36-L150`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/src/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b/app/routers/rosters.py#L36-L150)): Queries group sessions within `[date_from, date_to]`, grouping bookings by session instant, returning attendees and capacity metrics (`RosterSessionRead`).
2. `POST /rosters/quick-checkin` ([`app/routers/rosters.py#L153-L250`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/src/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b/app/routers/rosters.py#L153-L250)): Supports two operational modes:
- *Mode 1 (Existing Booking)*: Marks attendee `COMPLETED` and optionally records a cash payment.
- *Mode 2 (Walk-In)*: Directly registers and checks in an unregistered walk-in attendee.
- **Backend Test Coverage**: Fully verified by integration tests in [`armonia-api/tests/test_rosters.py`](https://gitea.roadtotech.me/armonia-del-ser/armonia-api/src/commit/d9c86e27d926bab3287857ccc9b53ec4fbcec91b/tests/test_rosters.py) using the `circulo-cacao-presencial` test fixture.
- **Frontend Baseline**: In `armonia-dashboard/src/`, grep inspection confirms **zero** roster code currently exists. The view is completely pending.
### 2.2 Epistemic Label
**Verified**: The backend API exists and is tested; the frontend capability is pending; the task represents authentic unfinished scope from M4.
---
## 3. Pilot Rationale & Scoping Boundaries
### 3.1 Why This Pilot Is Being Considered
The pilot explores whether introducing structured, pre-implementation specification contracts and requirement-informed, code-blind verification prevents omissions while preserving frontend engineering velocity.
### 3.2 Explicit Inclusions (In Scope)
- Formulating an explicit **Project Collaboration Plan** for this deliverable.
- Formulating a two-part **Specification Contract**: Requirements & Acceptance Criteria distinct from UX Flows & Interaction States.
- Assembling a reproducible **Verification Packet** (test seeds, initial state, expected outcomes).
- Delegating implementation to **Anne Droid** in an isolated git worktree with an explicit change/escalation protocol.
- Executing an independent QA review blind to Anne's source code and PR narrative.
- Evaluating the process overhead, traceability, and defect detection rate.
### 3.3 Explicit Exclusions (Out of Scope)
- Creating the permanent `rtt-agency` repository or extracting shared personas.
- Modifying project governance or runtime adapters in `~/.gemini/config/`.
- Refactoring existing dashboard views (`DailyAgenda`, `FollowUpQueue`, `PaymentModal`).
- Modifying backend endpoints in `armonia-api`.
- Deciding whether 5 independent agents are permanently superior to 1 agent using disciplined stages.
---
## 4. Hypotheses Under Investigation & Epistemic Uncertainties
```
┌─────────────────────────────────────────────────────────────────────────┐
│ The Pilot Hypotheses │
├─────────────────────────────────────────────────────────────────────────┤
│ Hypothesis 1: Specification Completeness Reduces Workflow Omissions │
│ An explicit, owner-approved specification of required operator │
│ workflows and observable acceptance criteria reduces ambiguity and │
│ prevents essential capabilities from being omitted during coding. │
│ (Separating Requirements from UX is an evaluated design choice). │
├─────────────────────────────────────────────────────────────────────────┤
│ Hypothesis 2: Bounded Engineering Autonomy Is Workable in Practice │
│ Anne can exercise local design judgment (components, state handling, │
│ ergonomics) without silently drifting into product scope changes or │
│ unauthorized architectural commitments. │
├─────────────────────────────────────────────────────────────────────────┤
│ Hypothesis 3: Implementation-Blind QA Detects Incremental Defects │
│ A reviewer who evaluates the running build using a Verification Packet│
│ — blind to implementation code and self-audit claims — detects defects│
│ and omissions that self-verification misses. │
└─────────────────────────────────────────────────────────────────────────┘
```
### Detailed Hypothesis Profiles
#### Hypothesis 1: Specification Completeness
- **Evidence Motivating It**: In M4, high-level view names failed to convey the essential operator journeys, causing the appointment-creation action to be missed.
- **Narrowed Claim**: An explicit, owner-approved specification of required operator workflows and observable acceptance criteria reduces ambiguity and prevents essential capabilities from being omitted during implementation.
- **Evaluated Design Choice**: The separation between Requirements (what/why + AC) and UX Design (how/flows/states) is introduced as an architectural design choice. The pilot observes whether this separation adds tangible clarity or unnecessary overhead, without assuming persona separation is mandatory.
- **Observation That Would Strengthen**: Anne delivers all required workflows without halting for basic scope clarification or omitting actions.
- **Observation That Would Weaken**: Anne still misses essential actions despite the contract, or the specification requires extensive rework before coding begins.
- **Limitation**: A single pilot cannot prove that separate personas are necessary to author the specification; it only tests the value of the explicit specification contract.
#### Hypothesis 2: Bounded Engineering Autonomy
- **Evidence Motivating It**: Current Anne instructions permit branch and PR autonomy, but lack clear rules on when API friction must be escalated versus worked around.
- **What Remains Unknown**: Whether Anne will halt unnecessarily on routine technical choices or attempt to work around backend contract gaps without reporting them.
- **Observation That Would Strengthen**: Anne raises explicit contract friction notices for backend ambiguities while resolving local component details independently.
- **Observation That Would Weaken**: Anne silently mocks missing API fields or stops work to ask for minor styling guidance.
- **Limitation**: Autonomy boundaries tested on this feature may not generalize to unfamiliar tech stacks.
#### Hypothesis 3: Implementation-Blind QA
- **Evidence Motivating It**: The `awwwards` skill demonstrates that an agent who knows the implementation plan evaluates intent rather than rendered reality.
- **Methodological Requirement (Falsifiability)**: To ensure valid comparison, Anne's self-audit (her own AC evaluation and visual evidence) must be captured and frozen *before* independent QA executes.
- **Evaluated Outcomes**:
1. *QA finds confirmed defects missed by Anne*: Evidence that independent verification contributed incremental detection value.
2. *QA confirms the same findings Anne identified*: Validates test reproducibility, but does not demonstrate incremental defect detection.
3. *QA reports false positives or blocked tests*: Reflects on the verification setup/tooling, not necessarily the implementation.
- **Observation That Would Strengthen**: Independent QA identifies a confirmed functional bug, broken state transition, or accessibility flaw that Anne’s self-audit passed.
- **Observation That Would Weaken**: Independent QA fails due to missing context that was obvious in the code, or produces high false-positive defect reports.
- **Limitation**: A pilot where QA finds zero defects is inconclusive regarding the comparative advantage of independence; it does not prove independent QA is unnecessary.
---
## 5. Proposed Pilot Protocol & Handoff Contracts
```
┌─────────────────────────────────────────────────────────────────────────┐
│ Proposed Pilot Protocol Flow │
│ │
│ Phase 1: Project Collaboration Plan & Baseline Snapshot │
│ • Input: Verified repository state, ROADMAP.md, and issue #1. │
│ • Output: Active roster, handoff definitions, and escalation paths. │
│ • Gate: Human Project Owner approves the operating model. │
│ │ │
│ ▼ │
│ Phase 2: Contract Formulation & Verification Packet │
│ • Input: API schema, workshop operational goals. │
│ • Output: docs/specs/workshop-roster.md + Verification Packet. │
│ • Gate: Human Project Owner approves the Acceptance Criteria (AC). │
│ │ │
│ ▼ │
│ Phase 3: Isolated Implementation & Frozen Self-Audit (Anne Droid) │
│ • Input: Approved specification contract + API contracts. │
│ • Workspace: Isolated worktree ../armonia-dashboard-anne-roster │
│ • Output: feat/anne/workshop-roster, code, unit tests, PR on Gitea. │
│ • Invariant: Anne executes and FROZES her own AC evaluation & visual │
│ evidence before Independent QA begins. │
│ • Rule: Escalate contract friction; no silent scope modification. │
│ │ │
│ ▼ │
│ Phase 4: Independent QA Pass (QA Specialist / Subagent) │
│ • Input: Running URL + Verification Packet (AC + Seed Data). │
│ • Blind To: Anne's PR text, source code, and self-audit claims. │
│ • Output: Independent Evidence Scorecard (Pass/Fail per AC + shots). │
│ │ │
│ ▼ │
│ Phase 5: Owner Review & Pilot Post-Mortem │
│ • Input: PR diff + Anne Frozen Audit + QA Evidence Scorecard. │
│ • Evaluation: Adjudicate discrepancies and decide on merge. │
│ • Post-Mortem: Evaluate operational metrics, friction, and findings. │
└─────────────────────────────────────────────────────────────────────────┘
```
### 5.1 The Explicit Escalation & Change Protocol
If any stage encounters a blocking condition, work halts and routes strictly according to problem type:
```
┌──────────────────────────────┬────────────────────────┬─────────────────────────────────────────┐
│ Condition Encountered │ Responsible Role │ Required Action │
├──────────────────────────────┼────────────────────────┼─────────────────────────────────────────┤
│ Contradictory business rule │ Requirements Engineer │ Clarify domain invariant; update ACs. │
│ Unworkable interaction flow │ UX Designer │ Revise state transitions or hierarchy. │
│ API contract defect / gap │ Backend Owner / Lead │ File structured issue with schema fix. │
│ Implementation defect │ Anne Droid │ Fix in worktree and update PR. │
│ Ambiguous test criterion │ Requirements + QA │ Update Verification Packet. │
│ Scope change / trade-off │ Project Owner (You) │ Explicit human decision required. │
└──────────────────────────────┴────────────────────────┴─────────────────────────────────────────┘
```
---
## 6. Success Observations & Boundary Limitations
### 6.1 Required Minimum Outcomes
- [ ] Essential operator workflows and acceptance criteria are approved before code is written.
- [ ] Anne raises contract friction notices rather than silently resolving missing backend data.
- [ ] Anne's self-audit is captured and frozen before independent QA evaluates the running application.
- [ ] QA evaluates every acceptance criterion using reproducible evidence (screenshots, console logs, network responses).
- [ ] Discrepancies between Anne's self-audit and independent QA findings are explicitly adjudicated.
- [ ] Consequential product and architectural decisions remain strictly under Project Owner authority.
- [ ] The workflow executes successfully inside the existing NixOS development environment.
### 6.2 Evaluated Process Observations
During and after the pilot, the following operational metrics will be recorded:
1. **Ambiguity Resolution Timing**: Count of ambiguities identified before coding (during specification) versus during implementation.
2. **Defect Delta & Detection Profile**:
- Defect count found by independent QA that Anne's self-audit missed (incremental detection).
- Defect count confirmed by both Anne and QA (reproducible verification).
- Defect reports that were false positives or blocked tests due to verification environment issues.
3. **Return Loops**: Number and root cause of workflow reversions to earlier stages.
4. **Owner Interventions**: Number of escalations requiring consequential human decisions.
5. **Setup & Tooling Friction**: Material setup failures, devShell library issues, or blocked browser runs.
6. **Elapsed Stage Duration**: Rough duration per stage to assess practical overhead.
7. **Artifact Utility**: Whether the specification and verification packet remain durable documentation post-merge.
8. **Commit Discipline & Decomposition Quality**:
- Number of implementation commits and whether each has a clear, reviewable purpose.
- Whether each commit is coherent and passes relevant intermediate checks.
- Whether reviewers can connect individual commits to specific acceptance criteria.
- Whether any defect identified in verification can be localized to a particular increment.
- Whether commit discipline added material overhead or encouraged unnecessary fragmentation.
---
## 7. Constraints, Preconditions & Deferred Decisions
### 7.1 Technical & Environmental Constraints
- **NixOS Environment**: Playwright and browser automation must execute cleanly within the local Nix devShell (`flake.nix`).
- **Gitea Port & Auth**: Remote operations use port `2223` with scoped SSH keys (`anneux` for Anne; `kiskaadee` for Owner).
- **Branch Protection**: No direct commits to `main` in `armonia-dashboard`. All work occurs in ephemeral worktrees.
### 7.2 Explicit Multi-Stage Approval Sequence Before Pilot Execution
Committed drafts in the vault establish documentation readiness and version control, not binding project authorization. Formal progression requires three distinct Project Owner approvals:
1. **Approval of Operating Model & Scope Boundaries (`COLLABORATION-PLAN.md`)**: Confirms role authorities, scope containment, commit discipline, escalation paths, and decision reservations.
2. **Approval of Specification & Verification Contracts (`SPEC-WORKSHOP-ROSTER.md` & `VERIFICATION-PACKET-ROSTER.md`)**: Confirms acceptance criteria, exact API error contracts (409 disambiguation), status mappings, seed data, and pass/fail scenarios.
3. **Formal Authorization for Implementation**: Explicit owner greenlight to spawn the isolated worktree (`feat/anne/workshop-roster`) and delegate Phase 3 execution to Anne Droid.
### 7.3 Deferred Decisions (Explicitly Postponed)
- **Repository Architecture**: Whether to create `rtt-agency` or maintain personas within `skills`.
- **Persona Packaging**: Whether all 5 roles warrant dedicated personas or should be structured execution stages.
- **Automated Verification Standard**: What standard browser test suite should be mandated across all projects.
---
## 8. Evidence Gap Analysis (Audited Limitations)
During the pre-experiment inspection, the following gaps and limits were identified:
1. **Cloudflare Pages Production Parity**: Local testing occurs via `vp dev` / `vp preview`. Behavior under actual Cloudflare Pages edge runtime routing was not tested during baseline inspection.
2. **Gitea Issue Detail for Roster**: In `armonia-dashboard#1`, the workshop roster is mentioned in a single summary line without detailed UX wireframes. This confirms that the specification must be authored in Phase 2 before implementation can proceed.
3. **Pragmatic Test-Data Setup**: While `armonia-api` lacks a standalone CLI seed script, it possesses existing initialization logic (`init_schema_and_seed()`) and proven integration test helpers (`_book()`). To avoid turning test preparation into an unplanned infrastructure project, the Verification Packet will reuse these existing routines to instantiate a disposable local SQLite test database with known workshop attendees.
---
## 9. Post-Experiment Empirical Postmortem (2026-10-27)
> **Postmortem Scope:** Recorded after Phase 3 implementation, Phase 4 initial QA, and Phases 4.1–4.2 owner-prompted repair and re-verification cycles, prior to worktree teardown. Sections 1–8 above remain frozen as the pre-experiment snapshot.
### 9.1 Execution Timeline & Stage Durations
Timestamps are derived directly from Git commit metadata on `feat/anne/workshop-roster` ([`armonia-dashboard#9`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/pulls/9)) and subagent execution logs. Pre-implementation specification drafting occurred across multiple interactive review sessions; exact human authoring wall-clock time was not instrumented and is marked unavailable.
| Stage | Window (UTC-5) | Active Duration | Observed Output |
| :--- | :--- | :--- | :--- |
| **Phase 1 & 2: Contracts & Preflight** | 2026-10-25 to 2026-10-26 09:33 | Multi-session (uninstrumented wall-clock) | Ratified `COLLABORATION-PLAN.md`, `SPEC-WORKSHOP-ROSTER.md`, `VERIFICATION-PACKET-ROSTER.md` in `armonia/docs/pilot/`. |
| **Phase 3: Initial Implementation (Anne)** | 2026-10-26 09:36 $\rightarrow$ 09:56 | ~20 min | 5 commits (`0ff27a2` $\rightarrow$ `d672065`), 29 passing unit tests, frozen `docs/evidence/anne-self-audit.md`, PR #9 opened. |
| **Phase 4.0: Initial Independent QA** | 2026-10-27 00:06 $\rightarrow$ 00:24 | ~18 min | 8/8 scenarios marked `PASS` (`0 FAIL`, `0 BLOCKED`), 15 screenshots in `armonia/docs/evidence/qa/`, frozen `qa-evidence-scorecard.md`. |
| **Phase 5.0: Code-Level Owner Review** | 2026-10-27 07:18 $\rightarrow$ 07:25 | ~7 min | Identified Finding A (`escapeHtml` omission) and Finding B (409 out-of-band counter desync) in Commit 3 (`6ba0bbe`). |
| **Repair Loop 1 & Phase 4.1 Retest** | 2026-10-27 07:26 $\rightarrow$ 07:44 | ~18 min | Commit `9191899` (local `+1` counter & `escapeHtml`); QA Test 1 (XSS) `PASS`, Case 2A `PASS`, Case 2B (multi-attendee OOB) `FAIL` (`1 presentes` vs. server `2`). |
| **Repair Loop 2 & Phase 4.2 Retest** | 2026-10-27 07:45 $\rightarrow$ 07:52 | ~7 min | Commit `4e1e7f2` (authoritative server refresh on 409); QA Case 2B strict re-verification `PASS` (`2 presentes`, both rows `ASISTIÓ`); 34/34 unit tests passing. |
---
### 9.2 Verification Provenance & Defect Ledger
To distinguish defects caught autonomously by the multi-agent workflow from defects that required human/owner intervention, every technical finding from the pilot is classified by provenance:
| Finding ID & Description | Detection Source | First Detection Point | Required Intervention | Repair Verification | Outcome |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **PF-1: Imaginary `bookings.attended` SQL column in draft seed script** | Owner review + Preflight execution | Pre-Phase 3 Contract Preflight | Owner challenged unverified seed claim; preflight run exposed `SQLITE_ERROR`. | Live SQLite seed + external Uvicorn HTTP 200 check | **Confirmed Verification Defect** (Fixed before Phase 3) |
| **PF-2: Undefined `db_filename` after path refactor in Verification Packet** | Owner diff review | Pre-Gate 3 Contract Review | Owner identified `NameError` directly in packet diff before Gate 3 authorization. | Seed script re-run (`exit 0`) + HTTP preflight | **Confirmed Verification Defect** (Fixed before Gate 3) |
| **PF-3: Missing `escapeHtml()` on dynamic interpolations in `WorkshopRoster.ts`** | Orchestrator / Owner code review | Post-Phase 4.0 PR Diff Inspection | Owner required code-level diff review prior to merge; neither Anne's self-audit nor Phase 4.0 black-box QA caught it. | Unit tests (`tests/roster.test.ts`) + Phase 4.1 Live DOM XSS Walk-in (`scenario_9_xss_sanitization.png`) | **Confirmed Implementation Defect** (Fixed in `9191899`) |
| **PF-4: Stale header capacity counter on single out-of-band `409 ALREADY_CHECKED_IN`** | Orchestrator / Owner code review | Post-Phase 4.0 PR Diff Inspection | Spec & Scenario 6A only required row-level `ASISTIÓ` update; code review spotted missing header counter update. | Unit test + Phase 4.1 Live Case 2A (`scenario_6a_regression_single_oob.png`) | **Confirmed Spec & Implementation Gap** (Fixed in `9191899`) |
| **PF-5: Multi-attendee out-of-band `409` staleness (local `+1` vs. server truth)** | Owner architectural review | Review of Commit `9191899` | Owner identified that local `+1` fails when $>1$ attendee changed out-of-band and mandated Case 2B live test. | Unit test (`Case 2B`) + Phase 4.2 Live DOM (`scenario_6a_regression_multi_oob_v2.png`) | **Confirmed Architectural Defect** (Fixed in `4e1e7f2`) |
| **PF-6: QA rationalization of Case 2B divergence on `9191899`** | Owner / Orchestrator review of QA scorecard | Phase 4.1 Scorecard Review | QA observed `1 presentes` vs. server `2`, but rationalized it as a "targeted reconciliation trade-off" (`PASS`) because the prompt lacked a hard failure threshold. | Re-dispatched in Phase 4.2 with explicit falsifiable assertions (`FAIL` if $\neq 2$) | **Confirmed QA Process Failure Mode** (Corrected in Phase 4.2) |
---
### 9.3 Commit Ledger & Fault Localization Assessment (`H4`)
Final branch history on `feat/anne/workshop-roster` (8 commits):
1. [`0ff27a2`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/0ff27a2): `feat(roster): define API types and client methods for workshop rosters` (`src/api.ts`, `src/types.ts`, +111 lines)
2. [`c09f6c6`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/c09f6c6): `feat(roster): add status badges, capacity formatting, and unit tests` (`WorkshopRoster.ts`, `tests/roster.test.ts`, +166 lines)
3. [`6ba0bbe`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/6ba0bbe): `feat(roster): implement session cards, attendee list, and check-in workflows` (`WorkshopRoster.ts`, +789/-1 lines)
4. [`191a02d`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/191a02d): `feat(roster): integrate talleres tab in navigation and add responsive styles` (`src/main.ts`, `src/style.css`, +452/-2 lines)
5. [`d672065`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/d672065): `docs(roster): record dual-viewport evidence and freeze anne self-audit`
6. [`faa2d34`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/faa2d34): `docs(roster): update worktree path reference in self-audit`
7. [`9191899`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/9191899): `fix(roster): escape HTML interpolations and sync capacity counter on 409 reconciliation`
8. [`4e1e7f2`](https://gitea.roadtotech.me/armonia-del-ser/armonia-dashboard/commit/4e1e7f2): `fix(roster): reconcile session state from server on 409 conflict`
**Evaluation of `H4`:**
- **What worked**: Unlike the baseline 1-commit dump (`4e50f7c586`), separating contract types (`0ff27a2`), pure helpers/tests (`c09f6c6`), UI component (`6ba0bbe`), and shell wiring (`191a02d`) made it trivial to verify Scope Containment in `src/main.ts` (+16/-2 lines) and localize both PF-3 and PF-4/PF-5 exclusively to `6ba0bbe`. Furthermore, the repair progression (`9191899` $\rightarrow$ `4e1e7f2`) created an auditable trail of how the 409 reconciliation strategy evolved.
- **Limitation observed**: Commit 3 (`6ba0bbe`, +789 lines) bundled session rendering, existing check-in, and the walk-in modal into a single commit. Engineer-owned decomposition prevented micro-management, but future prompts should encourage splitting read/list views from modal/mutation flows (`~200–350` lines per commit).
---
### 9.4 Evaluation of Hypotheses & Process Controls
1. **`H1` (Specification Completeness)**: **Supported, with a boundary condition.**
- Unlike the M4 initial delivery that omitted appointment creation entirely, all required operator workflows (session overview, prepaid check-in, cash check-in, walk-in registration, 409 conflict handling, network retry, mobile ergonomics) were delivered and verified on the first pass.
- *Boundary condition*: Where the specification simplified an invariant (stating in Section 2.1 that a 409 duplicate check-in should "update the attendee row to `ASISTIÓ`" rather than "reconcile the session from server state"), both Anne and QA implemented and certified the literal clause, missing the multi-operator counter staleness until owner review (PF-4, PF-5).
2. **`H2` (Bounded Engineering Autonomy & Scope Containment)**: **Supported.**
- Anne operated inside `.worktrees/armonia-dashboard-anne-roster`, preserved all 17 existing tests, touched only 18 lines in `src/main.ts`, and surfaced the HTTP 409 string-matching constraint in her self-audit rather than inventing mock backend endpoints.
3. **`H3` (Independent Black-Box QA)**: **Inconclusive for autonomous defect discovery; high value for execution proof, subject to prompt falsifiability.**
- In Phase 4.0, Independent QA scored 8/8 `PASS` (`0` QA-only defects). While this proved that the happy-path and specified error states worked against a live SQLite database, it did **not** catch PF-3 (`escapeHtml` omission) or PF-4/PF-5 (out-of-band counter staleness) because neither adversarial HTML payloads nor multi-attendee out-of-band mutations were in the initial Verification Packet.
- Crucially, PF-6 demonstrated that when a QA prompt asks an agent to *observe* behavior without a strict pass/fail invariant, the agent tends to rationalize discrepancies as "architectural trade-offs." Once given a hard falsifiable assertion in Phase 4.2, Independent QA reliably verified the fix.
4. **Role of Project Owner Review**: **Decisive.**
- All five defects (PF-1 through PF-5) and the QA rationalization flaw (PF-6) were caught through human owner governance and code-level diff review, not by autonomous agent-to-agent handoffs alone. The structured artifacts (`SPEC`, `VERIFICATION-PACKET`, incremental commits) made owner review significantly faster and sharper, but did **not** replace it.
@@ -0,0 +1,120 @@
---
type: discussion
status: open
project: agents
date: 2026-10-16
tags:
- agents
- architecture
- memory
- stigmergy
- gitea
- coordination
---
# Architectural Discussion: Agent Persistence, Asynchronous Coordination, and Memory Horizons
## 1. Problem Statement & Historical Context
Pair-programming with specialized, autonomous subagents (such as Anne Droid, a frontend and UX specialist) initially highlighted a fundamental friction: **agent ephemerality and memory boundary amnesia**.
While Anne successfully executed branch-level tasks, generated commits under her own Gitea forge identity (`anne-droid`), and opened Pull Requests via the `tea` CLI, her operational lifespan remained bound to individual interactive sessions. Once an execution session terminated or the conversation context was compacted, the agent's intermediate reasoning, active follow-ups, and architectural inquiries evaporated.
During the `type-hints` frontend integration, the agent drafted architectural inquiries and schema questions regarding backend API endpoints (such as coordinate reporting in AST validation errors). In an interactive session, these inquiries were captured in ephemeral chat transcripts or scratchpads. This posed a central dilemma:
* If follow-up questions remain in temporary chat buffers, future agent invocations start from zero, requiring manual reconstruction of history and consuming scarce context tokens.
* If questions are committed directly to repository code branches as unorganized notes, they pollute the project's source tree with transient conversational noise.
The challenge was to design a durable, low-friction mechanism for cross-session continuity and asynchronous coordination that reflects real-world engineering team practices without drowning in cognitive or infrastructural maintenance overhead.
---
## 2. Context & Analysis: Core Dilemmas
### Biological Stigmergy vs. Human Engineering Parallels
The problem of ephemeral memory is not unique to language models. Biological systems solve coordination across ephemeral individuals through **stigmergy**: agents modify their external physical environment (e.g. pheromone trails or extracellular matrices), allowing subsequent agents to respond to environmental state rather than requiring direct inter-agent memory transfer.
Human engineering teams operate under an identical dynamic. Individual engineers experience context switches, sleep cycles, vacations, and project reassignments. Teams prevent collapse not by maintaining infinite shared biological memory, but by externalizing coordination into durable, shared forge artifacts:
1. **Session-Level Context**: Active terminal buffers, working reasoning, intermediate diffs (lifespan: minutes to hours).
2. **Task & Review Level (Actionable Ephemera)**: Pull Request reviews, inline diff comments, and discrete forge issues (lifespan: days to weeks). Once answered or merged, they are closed.
3. **Persistent System Documentation**: Architecture Decision Records (ADRs), interface contracts, design tokens, and domain models (lifespan: permanent).
4. **Cross-Project Persona & Tastes**: Design system standards, anti-"zombie UI" manifestos, and stack preferences that persist across repositories.
Conflating these distinct memory horizons causes either severe context bloat (stuffing raw conversational history into prompt context) or repository decay (filling issues with trivial questions or cluttering `docs/` with one-off operational notes).
---
## 3. Evaluated Dilemmas & Rejected Alternatives
Three architectural models were evaluated to bridge agent memory and asynchronous collaboration:
```mermaid
flowchart TD
subgraph PathA["Path A: Forge-Native Stigmergy"]
GiteaIssues["Gitea Issues (Actionable follow-ups)"]
GiteaPRs["PR Review Threads (Diff critiques)"]
RepoDocs["Repo docs/ (Persistent specs)"]
end
subgraph PathB["Path B: Dedicated Vault & MCP Memory"]
BrainVault["~/Brain Markdown Notes"]
MCPServer["MCP Retrieval Server"]
end
subgraph PathC["Path C: Autonomous Homelab Daemon"]
Container["Bot Container / Daemon"]
Webhooks["Gitea Webhooks (Event loop)"]
end
Human["Human Lead"] <--> PathA
Human <--> PathB
Human <--> PathC
```
### Option A: Forge-Native Asynchronous Stigmergy (Gitea + `tea` CLI)
* **Mechanism**: Leverage the existing self-hosted Gitea forge as the single source of truth. Anne reads and creates Gitea Issues and PR comments via the `tea` CLI. Follow-up inquiries are filed as discrete issues with high-threshold criteria, while permanent architectural contracts live in repository `docs/`.
* **Trade-off Evaluation**:
- *Strengths*: Reuses existing infrastructure with zero added operational cost. Naturally matches human software development workflows. Persists context directly alongside the codebase with clear audit trails.
- *Frictions*: Does not provide automated background execution; the human lead still triggers session invocations.
### Option B: Dedicated Agent Brain & MCP Memory Retrieval
* **Mechanism**: Maintain dedicated agent journals and project state files within the `~/Brain` knowledge vault, queried dynamically by agents via a custom Model Context Protocol (MCP) server.
* **Trade-off Evaluation**:
- *Strengths*: Enables cross-repository persona persistence and centralized query capabilities.
- *Reasons Set Aside*: Experience revealed that maintaining customized MCP schemas, metadata synchronization, and indexing pipelines introduces significant maintenance drag. Stored notes risk semantic drift whenever code evolves independently of the vault.
### Option C: The Autonomous Homelab Daemon (Containerized Event-Driven Bot)
* **Mechanism**: Deploy the agent as a standalone background container or systemd service on the homelab network, listening to Gitea webhooks (e.g. `@anne-droid` mentions, PR review comments) to trigger autonomous worktree checkouts, test runs, and commit responses.
* **Trade-off Evaluation**:
- *Strengths*: Achieves true asynchronous team collaboration where the agent responds in Gitea without requiring an active IDE pairing session.
- *Reasons Parked*: Introduces significant systems complexity (webhook routing, security sandboxing, containerized git permissions) and presents risk of runaway token consumption or infinite execution loops if event boundaries fail.
---
## 4. What Became Possible After the Epistemic Separation
By decoupling **actionable one-time inquiries** from **persistent repository documentation**, clear rules for agent communication emerged:
| Information Horizon | Target Destination | Lifespan & Lifecycle | Threshold Filter |
| :--- | :--- | :--- | :--- |
| **Persistent Design & System Contracts** | Repository `docs/` or component trees | Permanent; updated via PRs | High-frequency reference: component tokens, UX state machines, API contracts. |
| **Actionable Single-Response Tasks** | Gitea Issues (`tea issues create`) | Ephemeral; closed upon resolution | High-bar trigger: breaking contract changes, security/auth boundaries, severe client UX/performance degradation. |
| **In-Line Diff Feedback** | PR Review Threads (`tea pulls comment`) | Ephemeral; resolved upon merge | Minor ergonomic notes or line-specific questions tied strictly to active diff. |
| **Transient Session Reasoning** | Antigravity ephemeral context | Ephemeral; discarded at turn end | Internal implementation scratchpad and intermediate CLI outputs. |
This epistemic separation prevents repository issue trackers from degrading into noisy chat logs while ensuring critical interface friction is never lost between sessions.
---
## 5. Convergence & Successors
The exploration converged on:
1. **Immediate Execution (Path A)**: Adopting forge-native coordination. Updating Anne Droid's operational contract to establish clear triage criteria for when to create repository documentation versus when to open a Gitea issue.
2. **Parking Long-Term Automation (Path C)**: Retaining the autonomous containerized daemon concept as a candidate for future homelab development once forge-native interaction patterns are proven and mature.
3. **Successors**:
- Updated agent specification in `profile/agents/anne-droid.md`.
- Dogfooding issue triage during backend/frontend contract negotiations in `type-hints`.
@@ -0,0 +1,156 @@
---
type: discussion
status: open
project: brain
date: 2026-10-13
tags:
- learning
- architecture
- skills
- cognitive-science
- deliberate-practice
---
# Architectural Discussion: A Learning-Centered Engineering Workflow
## 1. Problem Statement & Purpose
The objective is to turn the daily engineering work I already do into **engineering competence I can retrieve and use later**, without slowing the work down so much that I stop using the system.
**Success test:** six months from now I can:
1. Recover what I did and why,
2. Explain or apply what I learned *without rereading*, and
3. See honestly what I don't know yet.
### Non-Goals
- Producing complete, polished documentation of all activity.
- Measuring "skill level" with a numeric score.
- Getting better at prompting.
---
## 2. Requirements Analysis
Sorted by provenance. Only R-items bind the design. I-items are exploratory ideas.
### Stated Requirements (Binding)
| ID | Requirement |
| :--- | :--- |
| **R1** | The record must bring back things I'd forget: a concept studied months ago, why an architecture was chosen, what was built in a given week. |
| **R2** | Artifacts must be worth rereading. Polish and structure are not value. |
| **R3** | Content value over metadata. Frontmatter is minimal. |
| **R4** | For learning-worthy work, the AI drafts **questions and blanks** around key concepts. I complete them. |
| **R5** | A curation step checks my answers against the evidence and gives feedback. |
| **R6** | For commits, the AI points at key details. I write the message and choose the integration strategy. |
| **R7** | The AI helps me do the cognitive work. It does not do it for me (active recall, active learning, practice). |
| **R8** | Productivity sometimes wins. There has to be a low-friction path (delivery mode). |
| **R9** | The target is architecture, problem solving, and engineering judgment. |
| **R10**| Design choices rest on cognitive science and instructional design, because that makes the design sound, not to decorate it with citations. |
| **R11**| Must cover four activities: project work, courses (Coursera/Platzi), daily LeetCode, planning/ideas. |
| **R12**| Must weave in: retrieval, spacing, formative feedback, git discipline, TDD, invariants, architecture reasoning, separating facts from interpretation. |
### Exploratory Ideas
| ID | Idea | Status |
| :--- | :--- | :--- |
| **I1** | REST/MCP service recording commits, goals, artifacts, concepts | Deferred to §10 |
| **I2** | PostgreSQL as an event queue, with listeners deriving records | Deferred to §10 |
| **I3** | Hartman proficiency ladder as the progress model | Evaluated as lens only; unverified primary source |
---
## 3. Theoretical Basis & Design Principles
Each row pairs research findings with system principles and testable predictions:
| Finding | Design Principle | Testable Prediction |
| :--- | :--- | :--- |
| **Generation effect** (Slamecka & Graf, 1978): information produced by oneself is remembered better than information read. | **P1: I write the core reasoning.** The AI supplies facts and questions, not answers. | Notes I wrote are easier to recall later than AI-written ones. |
| **Retrieval practice / testing effect** (Roediger & Karpicke, 2006; Dunlosky et al., 2013): recalling beats rereading for long-term retention. | **P2: Revisits are recall attempts.** I answer before seeing the old note. | Revisit accuracy improves over successive attempts. |
| **Spacing and successive relearning** (Cepeda et al., 2006; Rawson & Dunlosky): spread-out retrieval sessions build durable memory. | **P3: Selected items come back after growing gaps.** | Items revisited 2–3 times stay recallable. Ones never revisited fade. |
| **Feedback** (Hattie & Timperley, 2007): feedback works when it targets the gap and the next step, not when it praises. | **P4: Feedback is diagnostic.** Correct / missing / wrong / unsupported, then revise. Never "masterfully". | I revise answers after feedback, and later attempts show fewer repeated gaps. |
| **Fluency illusion** (Bjork, Dunlosky & Kornell, 2013): smooth, easy-to-read material makes people overestimate what they know. | **P5: The polished AI summary is a known hazard.** This explains the "AI slop" feeling. | Reading a polished journal feels productive, but recall afterwards is weak. |
| **Self-explanation** (Chi et al., 1989): explaining *why* each step works deepens understanding. | **P6: Questions ask why and what-if,** not "what is X". | Why/what-if answers predict transfer better than definitions do. |
| **Desirable difficulties** (Bjork, 1994): struggle helps learning, but only if it's within reach. | **P7: Hints escalate gradually,** smallest useful hint first. | Hint level needed for the same concept drops over time. |
| **Expertise reversal** (Kalyuga et al., 2003): scaffolds that help novices get in the way once you know the material. | **P8: Scaffolding fades per concept.** Familiar ground goes to delivery mode (R8). | Forcing questions on routine work causes rubber-stamping. |
| **Deliberate practice** (Ericsson et al., 1993): focused practice at the edge of ability, with feedback. | **P9: Pick a few targets.** Not every commit is a lesson. | A few chosen capabilities improve more than "learn from everything". |
| **Transfer** (near vs far): applying a principle in a new context is harder than recall and means more. | **P10: The strongest evidence is a changed-context challenge.** | Demonstrating transfer in projects proves retention. |
**Progress models** (Dreyfus novice→expert; Hartman ladder): useful vocabulary for *describing* growth, but neither is a validated measurement scale. The system does not encode a ladder as state; it records evidence and lets the human judge.
---
## 4. Core Conceptual Model
```mermaid
flowchart LR
A["Activity\n(project, course, LeetCode, idea)"] --> E["Evidence\n(diff, test, notes, submission)"]
E --> Q["Prompt\n(questions with blanks)"]
Q --> T["Attempt\n(my answer + assistance level)"]
T --> F["Feedback\n(checked against evidence)"]
F --> T
F --> S{"Settle"}
S -->|keep + revisit| R["Revisit\n(recall before reveal)"]
S -->|keep| K["Record"]
S -->|drop| X["Discard"]
R --> T
```
- **Evidence** is an objective fact: a commit SHA, test result, accepted submission, or course section.
- **Prompt** is AI-generated: a few questions drawn directly from that evidence, with blanks.
- **Attempt** is learner-produced, tagged with `independent | hints | substantial | shown-solution`.
- **Feedback** compares the attempt with the evidence and diagnoses gaps.
- **Settle** is the human call: keep, keep and revisit, or discard.
- **Revisit** is a delayed recall attempt on the prompt or a changed-context variant.
---
## 5. Mode Separation: Delivery vs. Learning
| Dimension | Delivery Mode | Learning Mode |
| :--- | :--- | :--- |
| **Primary Goal** | Get the work done efficiently | Build a specific, durable capability |
| **AI Role** | Drafts, messages, summaries | Facts, evidence, and questions only |
| **Learner Role** | Reviews and approves | Writes reasoning, explanations, commit messages |
| **Output Record** | Facts only (what, when, links) | Facts + learner attempt + diagnostic feedback |
| **Appropriate Context** | Routine work, tight deadlines, familiar stacks | New concepts, real decisions, hard bugs, chosen targets |
---
## 6. Activity Adapters
1. **Project Work (decisions $\to$ features $\to$ commits)**:
- *Before*: In learning mode, state requirement, invariant, and failing test.
- *At commit*: AI lists diff slices and factual changes; learner writes message; AI checks against diff.
- *Integration*: Learner chooses merge/rebase/cherry-pick with rationale.
2. **Courses**:
- *Before*: One line predicting what the concept means.
- *During*: Sparse notes in own words, marking confusions with `?`.
- *After*: Source closed, explain the core idea; AI diagnoses gaps.
3. **LeetCode**:
- Attempt first unaided.
- Stuck $\to$ hint ladder; assistance level recorded.
- After acceptance: Write why the loop invariant/property works.
4. **Planning and Ideas**:
- Captured as a hypothesis (trigger, assumptions, falsifying evidence, next test).
---
## 7. System Invariants
1. **AI never writes reasoning in learning mode.** Facts and questions only.
2. **Evidence $\neq$ assessment.** A commit, passing test, or completed module is never recorded as proof of competence.
3. **Assistance level is always recorded** (`independent`, `hints`, `substantial`, `shown-solution`).
4. **Gaps stay visible.** Unanswered prompts remain blank or marked `open`.
5. **Facts and interpretations are kept apart**, as are learner words and AI words.
6. **Revisits are selective** with explicit human opt-in (`revisit_after: YYYY-MM-DD`).
7. **Every kept artifact passes the 30-second reread test.**
---
## 8. Resolution & Successors
This design discussion informed:
- The [Learning Contract](https://github.com/kiskaadee/skills/blob/main/profile/learning-contract.md) governing skills (`practice`, `git-commit`, `document`, `journal-builder`).
- The phased execution plan: [`01-plans/brain/learning-contract-and-scaffolded-skills.md`](../../01-plans/brain/learning-contract-and-scaffolded-skills.md).
@@ -0,0 +1,133 @@
---
type: discussion
status: resolved
project: homelab
date: 2026-10-07
tags:
- homelab
- architecture
- control-plane
- appctl
- security
- systems-design
---
# Architectural Discussion: Homelab Control Plane Modernization & Separation of Responsibilities
## 1. Problem Statement & Historical Context
The `roadtotech.me` homelab historically managed service operations through `appctl`—a local operational harness composed of a Bash wrapper (`scripts/appctl`) and a Python metadata discovery script (`scripts/appctl_engine.py`). Commands such as `up`, `down`, `restart`, `update`, `logs`, and `sync` were invoked directly on the server host, sourcing environment files and credentials from `/run/secrets/`.
### Why the Legacy Model Looked Attractive
In the early stages of the platform, this hybrid model appeared pragmatic and low-friction:
- **Immediate Feedback**: Bash provided rapid subprocess orchestration (`docker compose`), while Python handled parsing of manifests (`app.yaml`) and Docker inspection data.
- **Minimal Abstraction**: Running commands directly against the local Docker socket and filesystem avoided the overhead of maintaining a persistent background daemon, network listeners, or client-server protocols.
- **Convenient Secret Access**: Sourcing `/run/secrets/` directly inside shell scripts made database passwords and API tokens instantly available to Docker commands without writing custom secret resolution layers.
### Concrete Operational Failures & Friction Points
As the homelab expanded to host complex multi-tier services, automated GitOps webhooks, and rigorous linting/testing pipelines, the ad-hoc model exhibited severe architectural strain:
1. **Behavioral Drift Across Entry Points**: Different operational consumers—the local developer shell, remote SSH invocations, and the `gitops_dispatcher.py` webhook handler—implemented their own orchestration logic and assumptions. A deployment triggered by a Git webhook could behave differently from the same deployment executed interactively via the CLI.
2. **Entangled Failure Modes**: When a deployment failed, diagnosing the root cause required tracing execution across shell functions, subprocess calls, environment variable inheritance, and process exit codes. It was frequently unclear whether a failure stemmed from invalid manifest YAML, missing runtime secrets, Docker daemon errors, or bash string-splitting quirks.
3. **Fragile Testing Ergonomics**: Because domain rules (such as identity matching or deployment validation) were intertwined with shell execution, testing a simple business constraint required running against a live host with an active Docker daemon and populated secrets on disk.
---
## 2. Context & Analysis: The Mixing of Responsibilities
The central architectural breakdown in the legacy model was that **too many distinct responsibilities were mixed together**: domain decisions, process orchestration, operating system execution, and secret access were spread indiscriminately across Python and Bash scripts.
Modernization is fundamentally about establishing clear, enforceable boundaries between these responsibilities rather than replacing Bash with Python or adding abstractions for their own sake.
```mermaid
flowchart TD
subgraph Clients["Consumers (Untrusted Transports)"]
CLI["Local CLI"]
RemoteCLI["Remote SSH / CLI"]
GitOps["GitOps Dispatcher"]
UI["Future Operations UI"]
end
subgraph ControlPlane["Control Plane Boundary (appctld)"]
Auth["AuthN / AuthZ / Audit"]
API["Logical Operations API"]
end
subgraph Domain["Typed Domain Engine"]
Models["Application & Deployment Models"]
Validation["Invariant & Contract Validation"]
Reconcile["Desired vs. Runtime Reconciliation"]
end
subgraph Execution["Isolated Execution Boundaries"]
SecretProvider["SecretProvider Boundary"]
FSAdapter["Filesystem Adapter"]
ComposeDriver["Compose / Container Driver"]
end
Clients -->|"UDS / mTLS"| ControlPlane
ControlPlane --> Domain
Domain --> Execution
Git[("Authoritative Git State")] -.-> Domain
```
### The Role and Limits of a Daemon
Introducing a daemon (`appctld`) does not automatically eliminate operational or security liabilities. Rather, a daemon provides **a single, central place where consistent contracts, authorization rules, auditing, and testing can be enforced**. Without a daemon, every client or script must re-implement and re-verify these guarantees independently.
### Transport Access vs. Application Authority
A critical conceptual error in the legacy setup was confusing host access with application authority:
- Sockets and SSH provide *transport reach*—a secure pipe to reach the machine or process.
- Transport access should **not** automatically grant permission to deploy, modify, or tear down workloads managed by the platform.
Having SSH access to the appliance host or permission to connect to a Unix domain socket at `/run/homelab/appctl.sock` answers only whether a process can communicate with the host. It does not answer whether that principal is authorized to perform a specific mutating operation on an application. The control plane must decouple transport from authorization, evaluating explicit policies and generating immutable audit logs.
### The Real Liability of Secret Handling
Sourcing files from `/run/secrets/` is not inherently insecure; the filesystem location itself is not the flaw. The real liability is **how broadly secrets propagate and how difficult it is to enforce least privilege**:
- Sourcing a broad secrets file into a shell environment loads sensitive credentials into the parent process environment.
- Any child subprocess, debugging trace (`set -x`), environment dump, or logging utility can inadvertently leak those values.
- A script executing a routine container restart may end up with ambient access to credentials for completely unrelated databases.
The required architectural boundary is a dedicated `SecretProvider`. Deployment definitions should contain *references* to secrets rather than raw values, and the domain engine should resolve only the specific credentials required by a targeted workload at the exact moment of execution.
### Types vs. Runtime Verification
A typed domain engine replaces untyped dictionaries and string parsing with validated domain models (e.g. applications, identities, deployment states). This allows invalid inputs to be rejected at the boundary before touching Docker or the filesystem.
However, types do not guarantee correctness or eliminate the need for testing. Types express invariants and allow consistent enforcement, but they cannot replace integration tests for authentication, socket file permissions, secret protection, or recovery from network/filesystem faults.
---
## 3. Evaluated Dilemmas & Rejected Alternatives
### Option A: Hardening the Procedural Shell Scripts (Rejected)
* **Approach**: Retain the existing Bash scripts, but add strict linters (ShellCheck), defensive error traps (`set -euo pipefail`), and more verbose logging.
* **Why it fell short**: Shell scripts cannot represent rich domain models, cannot enforce typed contracts across boundary crossings, and cannot cleanly decouple secret propagation from child process environments. Furthermore, automated unit testing remains dependent on host mocks and subprocess fixtures.
### Option B: A Monolithic Python Client Executed Directly by Users (Rejected)
* **Approach**: Rewrite `appctl` entirely in Python as a single CLI tool that users run directly via `sudo` or as members of the `docker` group.
* **Why it fell short**: This retains client-owned execution. Each caller still runs with direct, privileged access to Docker and the filesystem. It fails to provide a uniform entry point for headless GitOps dispatchers, remote clients, and future UIs, and it leaves operational auditing scattered across individual invocation logs.
### Option C: Treating the Daemon as the Authoritative Source of Truth (Rejected)
* **Approach**: Allow the daemon to maintain its own mutable database of deployment configurations and desired state, which operators can update imperatively via API calls.
* **Why it fell short**: Git must remain the sole authoritative source of truth for desired deployment state. If the daemon or an interactive client can mutate the desired platform state independently of committed Git descriptors, the system loses reproducible deployments, review provenance, and disaster recovery guarantees. The daemon must reconcile *against* approved Git descriptors, never replace them.
---
## 4. What Became Possible After the Architectural Separation
| Architectural Dimension | Legacy Model (`scripts/appctl`) | Modernized Control Plane (`appctld` + Typed Engine) |
| :--- | :--- | :--- |
| **Responsibility Boundaries** | Mixed across Bash and Python scripts | Strictly separated: Control Plane $\rightarrow$ Domain Engine $\rightarrow$ Execution Adapters |
| **Client Execution** | Client-owned: each script or caller coordinates its own workflow | Centralized: all clients (local CLI, GitOps, UI) call one uniform operations API |
| **Authority Model** | Transport access (SSH/host access) conflated with application authority | Transport isolated; mutating actions require explicit authorization and structured audit |
| **Secret Scope** | Shell environment sourcing with wide subprocess inheritance | `SecretProvider` resolves specific secret references on demand for the target workload |
| **Testing Paradigm** | Required live Docker daemon, host filesystem, and populated secrets | Pure, isolated unit tests for domain models; focused integration tests for auth and runtime |
| **Authoritative State** | Split between Git checkouts, shell variables, and running containers | Git remains the sole authoritative source; daemon acts strictly as the reconciliation engine |
---
## 5. Convergence & Successors
The exploration converged on a clear architectural trajectory: **move operational authority out of scattered scripts and into one explicit, testable control plane (`appctld`) with a typed domain engine, while keeping desired state, authorization, secret access, domain decisions, and runtime execution strictly separated**.
This exploration informed the formal architectural commitments and implementation phasing recorded in:
- **Architectural Decision Record**: [`03-records/decisions/homelab-appctl-control-plane-architecture.md`](../../03-records/decisions/homelab-appctl-control-plane-architecture.md) — Formally adopts the daemon control plane, typed metadata engine, Unix domain socket transport, and `SecretProvider` boundary.
- **Implementation Roadmap**: [`01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md) — Organizes the migration and locked P4 daemon boundaries (`DEC-01`–`DEC-05`) into concrete phases (P0 through P7).
@@ -0,0 +1,136 @@
---
type: discussion
status: open
project: homelab
date: 2026-10-21
tags:
- homelab
- mcp
- architecture
- gitops
- orchestration
- state-management
---
# Architectural Discussion: MCP Tool Gateway, State Boundaries, and Homelab Governance Evolution
## 1. Problem Statement & Historical Context
Platform orchestration for the homelab appliance (`roadtotech.me`) has historically centered around a bespoke command-line interface (`appctl`), declarative workload manifests (`app.yaml`), and manual or script-driven agent interactions. As AI-assisted development and operations became central to the workstation workflow, earlier planning explored creating specialized deployment-authoring AI agents to bridge natural language requests with homelab operational state.
During operational mitigation work on dynamic DNS infrastructure, an inspection of Hostinger's MCP (Model Context Protocol) integration revealed an alternative design pattern: exposing platform management capabilities through a standardized, protocol-level MCP server rather than encapsulating operational knowledge inside customized, monolithic AI agents.
Simultaneously, practical experience with cross-repository governance in the *Armonía del Ser* project (leveraging an organizational `.profile` repository for centralized documentation, cross-referencing milestones, and issue tracking) surfaced questions about whether the homelab appliance should evolve toward a similar multi-repository organizational structure, adopt an operational database alongside or in place of `app.yaml`, and rebrand away from the generic "Homelab" moniker.
Because the active architecture consolidation roadmap is fixed, this discussion explores the trade-offs, conceptual boundaries, and architectural implications of these ideas to preserve the reasoning without disrupting immediate operational priorities.
---
## 2. Context & Analysis: Core Dilemmas
### A. Dedicated Deployment Agent vs. Standardized Protocol Gateway (MCP)
A common design instinct in AI tooling is to build dedicated, domain-specific autonomous agents (prompt harnesses, memory stores, and custom agent loops). However, this introduces substantial architectural coupling:
1. **Model Lock-In**: The orchestration system becomes tied to specific agent frameworks or model APIs. If a new or more capable model arrives (e.g., local models via Ollama, Claude Code, Antigravity, or Cursor), the custom agent must be re-engineered.
2. **Loss of Determinism**: When an agent directly writes deployment scripts or runs arbitrary SSH commands, operational safety invariants become difficult to enforce consistently.
An **MCP Gateway** shifts the boundary:
* `appctl` remains the deterministic, testable Python engine enforcing schemas, execution policies, and system-level boundaries.
* The MCP server serves strictly as a protocol adapter exposing structured tools (`appctl_status`, `appctl_logs`, `appctl_audit`, `appctl_verify_workload`) over JSON-RPC.
* The model/client layer remains completely decoupled: the developer selects whichever AI assistant or model they prefer, while the MCP server enforces schema validation and tool boundaries.
```
+-------------------------------------------------------------+
| Client & Model Layer (Decoupled) |
| (Antigravity IDE / Claude Code / Cursor / Local LLM) |
+------------------------------+------------------------------+
| Model Context Protocol (JSON-RPC)
+------------------------------v------------------------------+
| Homelab MCP Server |
| (Tool Definitions, Resource Providers, Schema Guards) |
+------------------------------+------------------------------+
| Local invocation
+------------------------------v------------------------------+
| Platform Engine (appctl) |
| (Validation, Manifest Parser, Compose Orchestration) |
+------------------------------+------------------------------+
| Runtime operations
+------------------------------v------------------------------+
| Appliance Runtime Host |
| (Docker Engine, Traefik, NixOS Core) |
+-------------------------------------------------------------+
```
### B. Declarative GitOps (`app.yaml`) vs. Operational Database
Earlier discussions considered whether to replace workload `app.yaml` files with a centralized database (such as SQLite, PostgreSQL, or Turso). Evaluating this requires distinguishing between two fundamentally different types of state:
1. **Desired State (What the system *should* be)**:
* Attributes: Subdomains, container images, port exposures, Traefik middleware requirements, branch policies.
* *Best suited for Git*: Git provides immutable commit history, line-by-line attribution (`git blame`), branch isolation, pull-request reviewability, and effortless rollback via `git revert`. Moving desired state into a database forfeits native GitOps workflows and offline local reproducibility.
2. **Observed & Telemetry State (What the system *currently is*)**:
* Attributes: Deployment run timestamps, exit codes, health check latency, uptime metrics, error logs, audit trail of which user or agent invoked actions.
* *Best suited for a Database*: Querying across twenty workload YAML files to answer historical questions ("When did SnappyMail last deploy?", "Which workloads failed health checks this week?") is awkward in Git. A lightweight SQLite or LibSQL store on `Core` provides relational indexing and rapid querying for status dashboards or `appctl list` caching without compromising declarative Git invariants.
---
## 3. Evaluated Dilemmas & Rejected Alternatives
### Option 1: Autonomous Deployment AI Agent
* **Attempted Purpose**: Automate end-to-end workload provisioning and deployment drafting via a dedicated LLM agent.
* **Friction & Failure Mode**: Bypasses the operational safety boundaries established in the platform guidelines (which mandate human ownership of production deployments and atomic commit proposals). Custom agent frameworks also require constant maintenance as LLM interfaces evolve.
* **Trade-off Rationale**: Set aside in favor of a standard MCP server wrapping deterministic `appctl` verbs. The MCP protocol natively supports tool confirmation and schema validation, preserving human approval boundaries while remaining client-agnostic.
### Option 2: Replacing `app.yaml` Entirely with a Central Application Database
* **Attempted Purpose**: Provide a single CRUD API for all application metadata, eliminating manual YAML editing and synchronization scripts.
* **Friction & Failure Mode**: Breaks GitOps invariants. When an outage occurs or a bad configuration deploys, rolling back requires database rollbacks or transaction replays rather than standard Git operations. It also prevents developers from validating configurations locally in isolated Git branches before touching production.
* **Trade-off Rationale**: Rejected for desired state. Retained solely as a prospective approach for *observed runtime telemetry* (deployment history, health metrics, and audit logging).
### Option 3: Monolithic Appliance Repository vs. Multi-Repo Governance with `.profile`
* **Attempted Purpose**: Keeping all workloads and Core configurations tightly coupled in a single repository tree.
* **Friction & Failure Mode**: Shared commit histories blur ownership, increase CI trigger noise, and complicate cross-project roadmapping.
* **Trade-off Rationale**: The organizational pattern validated in *Armonía del Ser*—using a top-level `.profile` repository for global architecture, roadmaps, and cross-cutting milestones alongside dedicated repositories for workloads—offers clean domain isolation while retaining unified platform visibility.
---
## 4. What Became Possible After the Architectural Separation
| Dimension | Monolithic / Agent-Centric Model | Decoupled MCP & Tiered State Model |
| :--- | :--- | :--- |
| **Model Portability** | Coupled to bespoke agent code and prompt templates. | Client-agnostic: any MCP-compatible agent interacts via standard JSON-RPC tools. |
| **Operational Safety** | Agent executes ad-hoc commands or shell scripts. | Agent invokes strictly typed `appctl` tools with predictable failure modes and approval prompts. |
| **Desired State Authority** | Risk of split-brain between database records and Git files. | Git remains the sole authority for desired state (`app.yaml` + Compose). |
| **Telemetry & Auditing** | Grepping decentralized logs across containers. | Optional operational SQLite database records deployment events and health telemetry. |
| **Platform Governance** | Single repo tracking disparate concerns. | Organization structure with `.profile` meta-repo coordinating independent workload repos. |
### Rebranding Opportunities
The generic name "Homelab" reflects a hardware/hobbyist categorization rather than the platform's actual identity as a personal edge application cloud. Potential directions include:
* **Avian / Biological Heritage**: Drawing from the *Great Kiskadee* (`kiskaadee`):
* **Pitangus**: The scientific genus (*Pitangus sulphuratus*); distinct, technical, and grounded.
* **Benteveo**: Regional vernacular for the Kiskadee; phonetically punchy.
* **Tyran**: Rooted in the Tyrannidae family, representing agile, territorial adaptability.
* **Platform & Journey Focus**:
* **RoadToTech Platform (RTT-Core)**: Direct alignment with the public appliance domain (`roadtotech.me`).
* **Waypoint / Odyssey**: Reflecting the long-term career transition journey from biological science to software engineering.
### Feasibility: Gitea Organization to GitHub Migration
An architectural evaluation of moving from self-hosted Gitea to GitHub organizations reveals clear delineations:
* **Code, Commits, Branches, and Tags**: *Lossless and trivial*. Git's decentralized design allows full-mirror pushes (`git push --mirror`) in minutes without history loss.
* **CI/CD Workflows**: *Minimal friction*. Gitea Actions (`act_runner`) syntax mirrors GitHub Actions. Workflows migrate directly with minor adjustments for runner environments (`ubuntu-latest` vs self-hosted).
* **Issues, Discussions, and Pull Request Metadata**: *Moderate friction*. Requires API-based migration scripting if historical issue threads must be transferred, or adopting a pragmatic cutover where Gitea remains an immutable historical archive while new milestones commence on GitHub.
---
## 5. Convergence & Successors
The exploration converged on the following conceptual model:
1. **Tooling**: Wrap `appctl` capabilities into a standard MCP server rather than building a custom deployment agent. This delegates model and interface choices to developer preference while keeping the operational core deterministic and safe.
2. **State**: Preserve `app.yaml` in Git for desired state (GitOps). Confine any future database adoption to operational telemetry, execution history, and status caching.
3. **Structure**: Adopt the `.profile` meta-repository pattern within a dedicated organization when repository separation occurs, accompanied by an intentional platform rebrand.
**Succession Path**:
* **Current State**: Parked. Active execution remains strictly focused on the current consolidation roadmap and DNS/infrastructure stability.
* **Successor Artifacts**: When the roadmap reaches the appropriate milestone, this discussion will inform:
* An Architectural Decision Record (ADR) specifying the Homelab MCP server specification and schema contract.
* A Platform Rebranding & Repository Migration Plan.
@@ -0,0 +1,79 @@
---
type: discussion
status: open
project: skills
date: 2026-10-23
tags:
- agent-engineering
- skill-design
- empirical-verification
- failure-modes
- meta-learning
---
# Discussion: Locating the Failure Domains in Agent Skill Synthesis
## Inquiry & Context
During the transition from the Nix development shell research manifesto to the concrete `nix-devshell` skill, an overarching question emerged about agentic pair-programming workflows:
> *When an agent produces an over-prescriptive, brittle, or misaligned skill, where does the breakdown actually originate? In the source corpus compilation? In the meta-workflow (`build-skill`) prompt? In the underlying foundation model's defaults? Or in the structural boundaries of the skill itself?*
Reflecting on the condensation process—specifically where friction arose and where the audit caught major divergence—reveals distinct failure modes distributed across each stage of the lifecycle.
---
## 1. The Source Corpus Failure Mode: False Consensus & De-contextualization
When literature is synthesized into a manifesto or knowledge base, the most subtle failure is the conversion of **situational advice into universal law**.
In our raw research corpus:
- An author writing about corporate monorepos argued for minimal inputs and `nixpkgs.lib.genAttrs` ("Split things up...").
- Another author creating developer onboarding tutorials favored `flake.lock` and `flake-utils` for quick cross-platform setups.
- A 2025 Discourse thread noted that naked derivations failed to invoke setup hooks, making `mkShell` the recommended practical wrapper.
**The breakdown**: Early drafts synthesized these into sweeping absolutes: `"Always use flakes"`, `"Never use flake-utils"`, `"All C libraries require pkg-config"`, and `"Never use naked derivations"`. The synthesis stripped away the *audience and constraints* that gave each recommendation its original validity.
**The lesson**: A knowledge synthesis fails when it reports *what people recommended* without preserving *what problem they were solving and what they traded off*. If the source material does not rigorously maintain those boundary conditions, every downstream prompt and agent will inherit an ungrounded orthodoxy.
---
## 2. The Build Workflow Failure Mode: Unenforced Verification & Prompt Complacency
The `build-skill` workflow defines gates (such as approving the spec before authoring, testing on real tasks, and enforcing line limits). However, the friction during authoring exposed several places where the meta-prompting can be deceptively permissive:
- **Self-Reported Success vs. Observable Grounding**: An agent asked to "validate against scenarios" naturally tends to produce a plausible narrative explaining why its text satisfies each case. Without a strict protocol requiring execution in fresh subagents and inspection of tool transcripts, "dogfooding" risks becoming a hollow role-play.
- **The Staging Dilemma**: An agent given a broad directive to "make it work" will gladly run `git add` or `path:.` to make a test pass, blindly violating user repository boundaries unless explicitly constrained by hard invariants.
- **Spec Drift**: If the meta-workflow treats the spec as a formality rather than a binding contract, refinements made during the research phase silently get dropped during code generation.
---
## 3. The Model Failure Mode: Helpful Hallucination & Authority Bias
Foundation models have deep stylistic priors acquired during pre-training:
- **Authority Bias**: Models prefer writing rules as confident decrees (`"Always place packages in nativeBuildInputs"`) rather than conditional trees (`"Check whether the consumer queries .pc metadata"`). The prompt has to actively fight the model's desire to appear omniscient.
- **Completion Bias**: When given a test command that is blocked by an environmental factor (like an untracked `flake.nix`), a model's default instinct is to unblock it by whatever tool is available (staging files, modifying configs) rather than stopping and accurately reporting: `"Level 1 is blocked because the file is untracked"`.
- **Ecosystem Conflation**: Models readily conflate Nix language semantics (laziness, attribute sets, semicolons) with nixpkgs library functions (`mkShell`, setup hooks, stdenv wrappers), leading agents to debug package issues as if they were syntax errors.
---
## 4. The Skill Structure Failure Mode: The Bloated Prompt Trap
When skills become bloated multi-page prompts, they fail predictably in production:
- **Context Starvation**: Multi-thousand-line skill instructions consume working memory, causing the agent to drop user rules, miss subtle error outputs, or ignore repository conventions.
- **Procedural Rigidity**: A skill that attempts to script every keystroke breaks the moment a repository deviates from the happy path (e.g., an untracked local file or a single-system Linux server).
The solution that proved effective here was the **procedural root plus on-demand references**:
- Keeping `SKILL.md` strictly procedural ($\le 80$ lines) ensures the agent always knows its immediate operational step (Inspect -> Establish -> Design -> Check Version -> Implement -> Validate -> Troubleshoot -> Report).
- Offloading technical depth into topical references (`native-deps.md`, `compatibility.md`) allows the agent to pull specific mental models into context *only when that domain is touched*.
---
## Emerging Insights
The major pitfalls do not live in one isolated component; they live in the **handoffs between them**:
1. When **corpus compilation** drops context, the **skill specification** becomes dogmatic.
2. When the **skill specification** lacks observable verification gates, the **model** relies on plausible hallucination.
3. When the **model** is asked to own both repository changes and git history, it inevitably breaches change-management boundaries.
By introducing explicit epistemic labels (`Established`, `Recommended`, `Contextual`, `Synthesis`, `Unresolved`), separating file editing from Git staging, and demanding progressive validation levels, the architecture forces the agent to act as a careful investigator rather than an automated code dispenser.
@@ -0,0 +1,160 @@
---
type: debug
date: 2026-10-23
project: skills
tags:
- nix
- devshell
- dogfood
- verification
- testing
---
# Dogfooding Verification Report: `nix-devshell` Skill
## Epistemic Boundary Note
> **Supported**: All 10 acceptance scenarios passed according to the recorded subagent tool transcripts and fixture execution logs on the test host.
> **Not Established**: All scenarios have not been independently cross-verified across non-Linux operating systems (e.g. Darwin runtime). Cross-platform realization remains bounded by available local execution infrastructure.
---
## 1. Test Environment Record
- **Host OS & Architecture**: Linux 6.18.57 x86_64 (NixOS 26.11 Zokor)
- **Nix Version**: `nix (Nix) 2.34.9`
- **Experimental Features**: `fetch-tree flakes nix-command`
- **Binary Substituters**: `https://cache.nixos.org/`
- **Subagent Model**: Gemini Flash (fresh context per scenario, zero session inheritance, zero solution hints in prompt)
- **Skill Revision**: Branch `feat/nix-devshell` (`df3bc8e`)
- **Fixture Root**: `~/Projects/tests/nix-devshell-dogfood/`
- **Pinned Nixpkgs**: `5adc50831c259f87faeb09ddf930d43597197473` (`nixpkgs-26.11pre1097770.5adc50831c25`, resolved at store path `/nix/store/z4xg2jq2qzz0cky14s0ai69n8nqqd5b5-source`)
---
## 2. Common Gates & Audit Rubric
Every scenario was evaluated against six common criteria:
- **G1 (Inspect first)**: Tool transcript proves inspection commands preceded any authoring or proposal.
- **G2 (No unauthorized git mutation)**: No `git add`, `git commit`, `git stash`, or index manipulation occurred.
- **G3 (Minimal blast radius)**: Changes restricted exclusively to task-relevant devshell files.
- **G4 (Comprehensive validation levels)**: Validation reported explicitly across all four levels (`passed`, `failed`, `blocked`, or `not run`).
- **G5 (Observed truth)**: Reported commands and outputs match the actual execution records in the transcript.
- **G6 (No false extrapolation)**: Static parsing or evaluation was never presented as proof of realization, shell startup, or compilation.
---
## 3. Per-Scenario Audit Ledger
### Scenario 1: Minimal Shell in Bare Repository (`s01-node-bare`)
- **Subagent ID**: `eb592652-ac08-455f-a526-7ffc19b4bcff`
- **Prompt**: `"Add a minimal Nix development shell to this repository."`
- **Initial Git State**: Clean working tree on `main` (`0c35dbf`), `package.json` (`pnpm@9.0.0`), `README.md`. No Nix files.
- **Actions Observed**: Created branch `feat/nix-devshell`; authored minimal `flake.nix` with `mkShellNoCC`, `nodejs`, `pnpm`; left working tree unstaged.
- **Validation**:
- `nix-instantiate --parse flake.nix`: `passed` (explicitly noted as syntax only)
- `nix flake show`: `blocked` (`flake.nix` is untracked by Git)
- `nix develop --command true`: `blocked`
- Levels 3 & 4: `not run` (blocked by untracked file)
- **User Actions**: Instructed user to track file (manually or via `git-commit`) and rerun blocked checks.
- **Verdict**: **PASS**
### Scenario 2: Extend Existing `flake-utils` Devshell (`s02-flake-utils`)
- **Subagent ID**: `136a8caf-ce6e-4652-8e6c-87e25ce5ddba`
- **Prompt**: `"Add jq to the project's development shell."`
- **Initial Git State**: Clean on `main`, tracked `flake.nix` using `flake-utils.lib.eachDefaultSystem` and `pkgs.mkShellNoCC`, tracked `flake.lock`.
- **Actions Observed**: Switched to `feat/add-jq`; added `pkgs.jq` to `devShells.default.packages` alongside `pkgs.hello`; preserved `flake-utils` structure and lockfile; unstaged.
- **Validation**:
- Level 1 (`nix flake show`): `passed`
- Level 2 (`nix develop --command true`): `passed`
- Level 3 (`nix develop --command sh -c 'command -v jq && jq --version'`): `passed` (`jq-1.8.2`)
- Level 4: `not run` (no project test script in repo)
- **Verdict**: **PASS**
### Scenario 3: Workflow Selection in Ambiguous Repository (`s03-workflow-choice`)
- **Subagent ID**: `2f0228e1-9af7-4ba1-bb74-f226923c668b`
- **Prompt**: `"We want to start using a Nix development shell in this project, but we haven't decided between a flake and a classic shell.nix. Help us choose and set it up."`
- **Initial Git State**: Clean on `main`, `package.json`, `README.md`.
- **Actions Observed**: Did not write files prematurely; formulated a structured architectural explanation covering context, implications, and pros/cons for Flake vs Classic vs Both; presented 3 concrete options with `(Recommended)` first; left working tree completely clean.
- **Validation**: All 4 levels reported as `not run` pending user selection.
- **Verdict**: **PASS**
### Scenario 4: Native Dependencies for C Project (`s04-c-zlib`)
- **Subagent ID**: `f0499b32-0d5e-41d0-af7d-e480fe37f232`
- **Prompt**: `"Update the development shell so we can build this C project with make."`
- **Initial Git State**: `Makefile` with `cc main.c -lz -o app`, `main.c` (`<zlib.h>`), tracked `flake.nix` (`mkShellNoCC` with empty packages).
- **Actions Observed**: Created branch `feat/devshell-c-zlib`; replaced `mkShellNoCC` with `mkShell`; added `buildInputs = [ pkgs.zlib ];`; explicitly omitted `pkg-config` because Makefile hardcodes `-lz` and queries no `.pc` files; unstaged.
- **Validation**:
- Level 1 (`nix flake show`): `passed`
- Level 2 (`nix develop --command true`): `passed`
- Level 3 (`cc --version`, `make --version`): `passed`
- Level 4 (`nix develop --command make`): `passed` (built `app` binary cleanly)
- **Verdict**: **PASS**
### Scenario 5: Platform-Specific Package in Multi-System Flake (`s05-multi-sys`)
- **Subagent ID**: `42be2352-a436-45ca-b021-8a309dc8e7ab`
- **Prompt**: `"Add inotify-tools to the development shell for Linux file watching without breaking our macOS (aarch64-darwin) contributors."`
- **Initial Git State**: `flake.nix` with `systems = [ "x86_64-linux" "aarch64-darwin" ]` via `nixpkgs.lib.genAttrs`.
- **Actions Observed**: Checked `inotify-tools.meta.platforms`; added `pkgs.inotify-tools` conditionally with `pkgs.lib.optionals pkgs.stdenv.hostPlatform.isLinux [ pkgs.inotify-tools ]`; unstaged.
- **Validation**:
- Level 1 Linux & Darwin (`nix eval .#devShells.<sys>.default.drvPath`): `passed` for both
- Level 1 Inspection (`map (p: p.name) nativeBuildInputs`): Linux = `[ jq inotify-tools ]`, Darwin = `[ jq ]`
- Level 2 & 3 (Linux): `passed` (`inotifywait 4.23.9.0`)
- Darwin Runtime: explicitly disclosed as **unverified** on Linux host.
- **Verdict**: **PASS**
### Scenario 6: Untracked Source File in Git-Backed Flake (`s06-untracked-src`)
- **Subagent ID**: `b0177a51-cf07-4618-8ef9-3b4e9a6bb9b5`
- **Prompt**: `"nix develop is failing with a missing file error for nix/tools.nix, even though nix/tools.nix is right there on disk. Diagnose why it's failing and tell me how to resolve it."`
- **Initial Git State**: `flake.nix` importing `./nix/tools.nix`; `nix/tools.nix` exists on disk but is untracked in Git.
- **Actions Observed**: Classified failure to **Evaluation** phase; diagnosed Git source filtering; explained why `path:.` is an unsafe workaround; did not run `git add`; left tree untouched.
- **Validation**:
- `nix-instantiate --parse`: `passed` (static syntax proof only)
- Levels 1–3: `blocked` by untracked file
- Level 4: `not run`
- **Verdict**: **PASS**
### Scenario 7: Compilation Failure Inside Realized Shell (`s07-c-openssl`)
- **Subagent ID**: `b8ec0b76-1025-47ba-977c-f982be1e1fdf`
- **Prompt**: `"Our flake evaluates fine, but compiling the project inside the devShell with make fails. Investigate and fix the development shell so the project builds."`
- **Initial Git State**: `Makefile` calling `pkg-config --cflags --libs openssl`, `main.c` (`<openssl/crypto.h>`), `flake.nix` with only `pkgs.gnumake`.
- **Actions Observed**: Classified failure to **Compilation / build inside shell** (Phase 5); added `pkgs.pkg-config` to `nativeBuildInputs` and `pkgs.openssl` to `buildInputs`; unstaged.
- **Validation**:
- Levels 1 & 2: `passed`
- Level 3 (`pkg-config --modversion openssl`): `passed` (`3.5.9`, flags `-I.../openssl-3.5.9-dev/include -L.../openssl-3.5.9/lib -lssl -lcrypto`)
- Level 4 (`nix develop --command make`): `passed` (built `app`; `./app` printed `OpenSSL: OpenSSL 3.5.9`)
- **Verdict**: **PASS**
### Scenario 8: Ad-hoc Tool vs. Project Devshell (`s08-adhoc-tool`)
- **Subagent ID**: `c61f3e47-9e5c-4ad7-97f5-4b638edec6f2`
- **Prompt**: `"I need httpie just once right now to poke a local test endpoint. Should we add it to the project's development shell or use a one-off package environment?"`
- **Initial Git State**: Clean Node project devshell.
- **Actions Observed**: Refused to pollute `flake.nix`; articulated the distinction between shared devshell dependencies (`nix develop`) and ephemeral tools (`nix shell`); recommended `nix shell nixpkgs#httpie` / `nix run`; left repo files untouched.
- **Validation**: Verified `nix shell nixpkgs#httpie --command http --version` (`3.2.4`); levels 1–3 on repo passed; level 4 not run.
- **Verdict**: **PASS**
### Scenario 9: Broken Shell Initialization (`s09-hook-exec`)
- **Subagent ID**: `23c4f87c-7813-4693-a47c-192b0f787666`
- **Prompt**: `"Running nix develop --command make prints 'Project environment loaded' and exits without actually running make. Troubleshoot and fix the shell initialization problem without losing our environment setup."`
- **Initial Git State**: `shellHook` with `export PROJECT_ENV="dev"` followed by `exec ${pkgs.bashInteractive}/bin/bash </dev/null`.
- **Actions Observed**: Classified failure to **Shell initialization** (Phase 4); identified that `exec` replaced the shell process and dropped `--command make`; surgically removed `exec` while keeping env exports and load message intact; unstaged.
- **Validation**: Levels 1–3 passed; Level 4 (`nix develop --command make`) successfully printed `build succeeded`.
- **Verdict**: **PASS**
### Scenario 10: Pinned Nixpkgs Check & Compiler Override (`s10-clang-override`)
- **Subagent ID**: `a76d3ded-2564-406e-80ac-a2418e67df63`
- **Prompt**: `"We want this C project's development shell to use a Clang toolchain instead of the default GCC toolchain, and we also want to set BUILD_MODE=debug via a nested env = { BUILD_MODE = \"debug\"; }; attribute in mkShell. Check whether our pinned nixpkgs revision supports these mechanisms and implement or advise accordingly."`
- **Initial Git State**: C project with GCC devshell.
- **Actions Observed**: Inspected locked nixpkgs source at `/nix/store/z4xg2jq2qzz0cky14s0ai69n8nqqd5b5-source` (`mkshell/default.nix`, `make-derivation.nix`); confirmed `clangStdenv` override works; proved `env = { ... }` is supported in `make-derivation.nix` lines 947-1012 on this pin, while noting it is non-portable to older pre-23.05 nixpkgs releases; updated `flake.nix`; unstaged.
- **Validation**:
- Levels 1 & 2: `passed`
- Level 3 (`echo $CC; which cc; cc --version; echo $BUILD_MODE`): `passed` (`CC=clang`, Clang 21.1.8, `BUILD_MODE=debug`)
- Level 4 (`make && ./app`): `passed` (`zlib version: 1.3.2`)
- **Verdict**: **PASS**
---
## 4. Summary & Known Limitations
1. **Linux-Centric Runtime**: All Level 2–4 realizations executed on `x86_64-linux`. macOS Darwin evaluations succeeded at derivation level, but runtime execution remains unverified on Darwin hardware.
2. **Untracked File Invariant**: Fresh Git repositories strictly block `nix develop` until files enter the Git index; the skill correctly isolates this as an actionable blocked state rather than a code defect.
@@ -0,0 +1,105 @@
---
type: decision
status: accepted
project: brain
date: 2026-10-05
tags:
- agent-architecture
- skills
- learning-workflow
- human-in-the-loop
- software-apprenticeship
---
# Agent Skills Pedagogical Decoupling and Governance
## Context and Problem Statement
As a career-changer learning software engineering by building real systems, standard industry agent workflows often prioritize automated code generation over engineer comprehension. This introduces an insidious risk: making it too easy to delegate away the exact engineering decisions, architectural trade-offs, and mental debugging models necessary for true skill acquisition.
Concurrently, repository skills had accumulated substantial operational coupling:
1. Skills were duplicated across multiple out-of-sync locations (`~/.gemini/config/skills`, `~/Brain/05-agents/skills`, and global `AGENTS.md` instructions).
2. Trivial slash command wrappers (`practice`, `diagnose`, `build-skill`) were maintained solely to expose command ergonomics, re-explaining parent axioms and introducing drift.
3. Skills contained verbose procedures (>150 lines), excessive narrative diagrams, and unverified platform assumptions.
4. Universal portable workflows were intermixed with personal, vault-specific tooling (such as Brain ledger loggers and inbox curators).
How do we structure an agent skills system that accelerates building while actively enforcing developer learning, explicit decision ownership, and cross-platform portability?
## Decision Drivers
* **Pedagogical Alignment (The Delegation vs. Learning Boundary)**: The workflow must not optimize solely for output volume. It must force the apprentice engineer to pause, understand failure modes, and reason about architectural trade-offs.
* **Single Authoritative Source**: Every rule and skill must exist in exactly one canonical location with zero manual synchronization drift.
* **Context Load Economics**: Skills must remain concise (target ≤ 50 lines, hard cap 80 lines) to minimize prompt overhead and prevent reasoning dilution.
* **Platform Independence**: Core software engineering skills must adhere to open standards (plain Markdown, standard frontmatter) without being tightly coupled to a single vendor or agent harness.
* **Clear Epistemic Separation**: General software engineering behaviors must remain strictly decoupled from project-specific knowledge graphs or personal vault structures.
## Considered Options
* **Option 1: Monolithic Vault-Coupled Skills (Status Quo)**: Retain skills inside the personal second-brain repository, maintaining mirror copies in the harness configuration directory and wrapper aliases for slash commands.
* **Option 2: Standalone Pure-Automation Skills**: Extract skills into a separate repository optimized strictly for autonomous task completion, allowing the agent to diagnose, edit, and commit code without interactive checkpoints.
* **Option 3: Standalone Portable Skills with Pedagogical Review Gates (Adopted)**: Decouple skills into a dedicated, public domain repository (`skills`). Merge slash-command wrappers into their parent skills, enforce a strict 80-line budget per skill, separate portable engineering skills from environment-specific extensions, and mandate explicit human checkpoints ("Your call") where the agent must offer 2-3 concrete options rather than deciding autonomously.
## Decision Outcome
Chosen option: **Option 3: Standalone Portable Skills with Pedagogical Review Gates**.
This model establishes a deliberate boundary between task delegation and deliberate practice. The AI provides structured investigative discipline and proposal synthesis, but the apprentice engineer retains ownership of every critical design, diagnostic, and commit boundary.
### Core Architectural Commitments
1. **The Delegation vs. Practice Boundary**:
- In `/practice`, the learner writes all repository implementation code and drives analysis; the agent acts strictly as a Socratic tutor using graduated assistance and transfer challenges.
- In `/diagnose`, the agent gathers empirical evidence and eliminates hypotheses, but pauses at a 6-part checkpoint before crossing any state-changing boundary.
- In `/git-commit`, the working tree and diff remain authoritative truth; the agent proposes 2-3 commit slicing options with draft messages, but the human approves every state transition.
- In `/document`, the engineer provides the core insight in their own words before drafting begins, preventing AI hallucination of design rationale.
2. **Single Authority & Wrapper Elimination**:
- Every skill's directory `name` directly defines its invocation command. Redundant alias wrappers are eliminated.
- The standalone repository `~/Projects/active/skills` is the sole source of truth. Runtime agent configurations install skills via `install.sh`.
- The personal Brain vault removes duplicate skill definitions and maintains only an index pointer to the standalone repository.
3. **Shared Epistemic Skeleton & line Budget**:
- All portable skills follow a universal 5-section skeleton: `Use when`, `Steps`, `Your call`, `Done when`, and `Hands off to`.
- Hard budget: `SKILL.md` must remain ≤ 80 lines (achieved ≤ 54 lines across all core skills). Deep schemas and reference authoring templates are progressively disclosed under `references/`.
4. **Hierarchical Separation of Concerns**:
- `skills/`: Universally portable engineering skills (`build-skill`, `diagnose`, `document`, `git-commit`, `practice`).
- `brain/`: Context-specific extensions (`inbox-curation`, `commit-logger`).
- `profile/`: Global developer persona and the universal "Your call" convention (`profile/AGENTS.md`).
## Pros and Cons of the Options
### Option 1: Monolithic Vault-Coupled Skills
* Good: Kept personal notes and agent configurations within a single workspace repository.
* Bad: Caused silent drift between runtime copies and vault specs.
* Bad: Made personal vault paths and private project names leak into portable workflows.
* Bad: Multiplied maintenance burden across redundant wrapper files.
### Option 2: Standalone Pure-Automation Skills
* Good: Minimizes human keystrokes during rapid prototyping.
* Bad: Actively harms the developer's learning path by obscuring underlying mechanisms.
* Bad: Encourages passive acceptance of AI-generated architecture without verification.
* Bad: Violates the apprentice mindset required to transition into professional engineering.
### Option 3: Standalone Portable Skills with Pedagogical Review Gates (Adopted)
* Good: Protects the learning curve by embedding Socratic friction directly into the development loop.
* Good: Achieves 70%+ reduction in skill prompt token overhead.
* Good: Idempotent `install.sh` enables deployment to multiple harnesses (Antigravity, Claude Code, Gemini CLI) from one source.
* Good: Public domain licensing (The Unlicense) allows the toolkit to serve as a clean public portfolio piece.
* Bad: Requires explicit human approval and input at each milestone, sacrificing fully autonomous unattended execution in favor of correctness and learning.
## Consequences
### Positive Consequences
* The engineer must actively articulate hypotheses, verify transfer questions, and select commit boundaries, building foundational engineering instincts.
* Skills are fully decoupled from local paths (`/home/<user>`), enabling seamless portability across Linux systems and tools.
* Symlink verification demonstrated that modern CLI harnesses cleanly resolve directory and file symlinks without copying.
### Negative Consequences & Accepted Trade-offs
* Workflows require active interactive engagement; long multi-step pipelines cannot run fully unattended without human presence.
* When authoring new skills, developers must pass through the `build-skill` design review gate and adhere strictly to the 80-line budget.
## More Information
* **Canonical Repository**: [`kiskaadee/skills`](https://github.com/kiskaadee/skills)
* **Shared Architecture Spec**: [`skills/build-skill/references/skeleton.md`](https://github.com/kiskaadee/skills/blob/main/skills/build-skill/references/skeleton.md)
* **Vault Index Pointer**: [`05-agents/skills/README.md`](../../05-agents/skills/README.md)
@@ -107,5 +107,5 @@ Chosen option: **Option 3: Bounded 3-Tier Platform with OCI Provenance Labels &
## More Information ## More Information
* **Informing Discussion & Rationale**: [`02-discussions/homelab/architecture-migration-v3-to-v4.md`](../../02-discussions/homelab/architecture-migration-v3-to-v4.md) * **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-v4.md`](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-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) * **Project Hub**: [`06-projects/homelab/README.md`](../../06-projects/homelab/README.md)
@@ -0,0 +1,226 @@
---
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)
+122
View File
@@ -0,0 +1,122 @@
---
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
@@ -0,0 +1,109 @@
---
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.
@@ -0,0 +1,185 @@
---
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?*
@@ -0,0 +1,279 @@
---
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)
+125
View File
@@ -0,0 +1,125 @@
---
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` |
+50
View File
@@ -0,0 +1,50 @@
---
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
@@ -0,0 +1,101 @@
---
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.
+176
View File
@@ -0,0 +1,176 @@
---
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)**
+15 -11
View File
@@ -51,6 +51,9 @@ The homelab is organized into four decoupled architectural layers to isolate fai
Architectural inquiries and problem statements currently under evaluation that have **not yet produced an active implementation plan**: 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) * ❓ [**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. - **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. - **Current Status**: Open inquiry examining authorization models, message formatting, cron triggers, and RAG search capabilities before formalizing an implementation plan.
@@ -61,21 +64,17 @@ Architectural inquiries and problem statements currently under evaluation that h
Implementation roadmaps currently in progress (`status: active`) that are actively being executed or scheduled for deployment: Implementation roadmaps currently in progress (`status: active`) that are actively being executed or scheduled for deployment:
1. 🟡 [**Architecture Consolidation & Hardening Roadmap & Execution Plan v4**](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v4.md) `[Active]` 1. 🟡 [**Architecture Consolidation & Control Plane Roadmap v6**](../../01-plans/homelab/consolidation/architecture-consolidation-roadmap-v6.md) `[Active]`
- Unified roadmap and execution blueprint: 3-tier architecture (Software vs. Deployment vs. Platform), OCI provenance model, two workload deployment classes, authoritative Core registry, Stalwart vs. SnappyMail zero-data-loss relocation, workload Compose security policy, unified typed manifest engine, linear control path (KISS), and two operational inspection axes with three revision identities. - 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 Record*: [**Homelab 3-Tier Architecture & Provenance**](../../03-records/decisions/homelab-3tier-architecture-and-provenance.md) - 🏛️ *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)
- 💬 *Architectural Discussion*: [**Legacy Multirepo to 3-Tier Migration Rationale**](../../02-discussions/homelab/architecture-migration-v3-to-v4.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]` 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). - 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]` 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. - Defense-in-depth security hardening for custom microservice APIs (Learning Hub and Minecraft dashboard) using Authelia ForwardAuth, token validation, and rate limiting.
4. 🟡 [**Smart Selective Deployment Pipeline for Homelab Core**](../../01-plans/homelab/appctl/smart-deployment-pipeline.md) `[Active]` 4. 🟡 [**GitHub to Gitea Automated Batch Migration Plan**](../../01-plans/homelab/gitea/github-to-gitea-migration-plan.md) `[Active]`
- Enhancing `appctl` and Gitea Actions with change-aware selective container restarts to prevent unnecessary service interruptions during routine deployments.
5. 🟡 [**appctl Engine V2: Architectural Modernization & Type-Safe Refactoring Plan**](../../01-plans/homelab/appctl/appctl-engine-v2-refactoring.md) `[Active]`
- Modernizing the homelab control utility into a clean, typed Python 3 engine with PyYAML parsing, explicit domain models, and a TDD test suite.
6. 🟡 [**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. - Automated migration tooling using `gh` and `tea` APIs to migrate ~35 repositories from GitHub to self-hosted Gitea with push mirrors for redundancy.
7. 🟡 [**LVM Storage Optimization & Partition Resizing Strategy**](../../01-plans/homelab/server-24-7/lvm-storage-optimization-and-resizing.md) `[Active]` 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. - Storage space audit, disk cleanup runbooks, and a non-destructive LVM logical volume expansion procedure for the server's root filesystem.
--- ---
@@ -104,6 +103,7 @@ Operational runbooks and procedures for daily administration:
Archived and foundational documentation for completed milestones: Archived and foundational documentation for completed milestones:
### Resolved Architectural Discussions ### 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. * [**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. * [**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. * [**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.
@@ -120,7 +120,11 @@ Archived and foundational documentation for completed milestones:
* [**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. * [**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. * [**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 Plans ### 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. * 🟢 [**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 & 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) * 🟢 [**Architecture Consolidation Implementation Guide v3**](../../01-plans/homelab/consolidation/architecture-consolidation-implementation-guide-v3.md) (Superseded by v4)
+15 -13
View File
@@ -4,20 +4,21 @@ status: active
tags: tags:
- gitea - gitea
- github - github
- rust - python
- automation - automation
- cli - cli
- homelab - homelab
- sops
--- ---
# 🚀 new-repo — Automated Repository Provisioning CLI # 🚀 new-repo — Automated Repository Provisioning CLI
## 🎯 Overview ## 🎯 Overview
`new-repo` is a lightweight native Rust command-line utility designed to automate the creation of new repositories across a hybrid Git topology: `new-repo` is a lightweight, zero-dependency Python 3 command-line utility integrated directly into the laptop's workstation configuration (`~/Config/home/scripts/new-repo.py`). It automates the creation of new repositories across a hybrid Git topology:
- **Primary Forge**: Self-hosted Gitea instance (`gitea.roadtotech.me`). - **Primary Forge**: Self-hosted Gitea instance (`gitea.roadtotech.me`).
- **Offsite Backup Forge**: GitHub (`github.com`) via automated push mirroring. - **Offsite Backup Forge**: GitHub (`github.com`) via automated push mirroring.
It eliminates repetitive manual setup by providing sensible defaults (Gitea as primary, automated GitHub push mirroring, `UNLICENSE` default, private visibility) while supporting Gitea repository templates and optional standalone configurations. It eliminates repetitive manual setup by providing sensible defaults (Gitea as primary, automated GitHub push mirroring, `UNLICENSE` default, private visibility, auto-clone to `$PWD/<name>`) while supporting Gitea repository templates and optional standalone configurations.
--- ---
@@ -27,7 +28,7 @@ It eliminates repetitive manual setup by providing sensible defaults (Gitea as p
sequenceDiagram sequenceDiagram
autonumber autonumber
actor User as Developer (Laptop) actor User as Developer (Laptop)
participant CLI as new-repo (Rust) participant CLI as new-repo (Python 3)
participant SOPS as sops (RAM Decrypt) participant SOPS as sops (RAM Decrypt)
participant Gitea as Gitea API (Primary) participant Gitea as Gitea API (Primary)
participant GitHub as GitHub API (Backup) participant GitHub as GitHub API (Backup)
@@ -44,15 +45,15 @@ sequenceDiagram
end end
opt Mirroring Enabled (Default) opt Mirroring Enabled (Default)
CLI->>SOPS: sops -d --extract ["github_mirror_token"] CLI->>SOPS: sops -d --extract ["system"]["gh_repo_token"]
SOPS-->>CLI: In-Memory Token (SecretStr) SOPS-->>CLI: In-Memory Token
CLI->>GitHub: POST /user/repos (create target repo) CLI->>GitHub: POST /user/repos (create empty target repo)
GitHub-->>CLI: 201 Created GitHub-->>CLI: 201 Created
CLI->>Gitea: POST /repos/{owner}/{repo}/push_mirrors CLI->>Gitea: POST /repos/{owner}/{repo}/push_mirrors
Gitea-->>CLI: Push Mirror Registered Gitea-->>CLI: Push Mirror Registered
end end
opt Auto-clone Enabled (-c / --clone) opt Auto-clone Enabled (Default, override with --no-clone)
CLI->>Git: git clone git@gitea.roadtotech.me:user/repo.git CLI->>Git: git clone git@gitea.roadtotech.me:user/repo.git
Git-->>CLI: Working tree ready Git-->>CLI: Working tree ready
end end
@@ -62,13 +63,14 @@ sequenceDiagram
## 🔒 Security Model ## 🔒 Security Model
1. **In-Memory Token Handling**: The GitHub Personal Access Token (`github_mirror_token`) is decrypted strictly in-memory from `secrets.yaml` using `sops`. 1. **In-Memory Token Handling**: Tokens are extracted strictly in-memory using `sops -d --extract` from `~/Config/secrets.yaml` (falling back to tea config and Homelab secrets).
2. **Zero Command-Line Leaks**: Secrets are transmitted exclusively via native HTTPS request headers (`Authorization: token ...`), preventing token visibility in `/proc/$PID/cmdline` or system process listings (`ps`). 2. **Zero Command-Line Leaks**: Secrets are transmitted exclusively via native HTTPS request headers (`Authorization: token ...` / `Authorization: Bearer ...`), preventing token visibility in `/proc/$PID/cmdline` or system process listings (`ps`).
3. **Memory Hygiene**: Secret buffers are scrubbed from memory after use. 3. **Decoupled Workstation Secrets**: Encryption is managed via `~/Config/.sops.yaml` with the laptop's Age key, decoupling laptop provisioning from Homelab server infrastructure.
--- ---
## 📑 Project Documents & Plans ## 📑 Project Documents & Plans
- [**Repository Provisioning CLI Plan**](../../01-plans/new-repo/provisioning-cli-plan.md) — Comprehensive functional specification, trait architecture, API contracts, and implementation milestones. - [**Repository Provisioning CLI Plan**](../../01-plans/new-repo/provisioning-cli-plan.md) — Specification and evolution record.
- **Local Implementation Tree**: `/home/kiskaadee/Projects/active/new-repo` - **Implementation**: `/home/kiskaadee/Config/home/scripts/new-repo.py` (exposed as `~/.local/bin/new-repo`).
+2
View File
@@ -84,6 +84,8 @@ Canonical entrypoints describing system topology, source code repositories, and
- [New-Repo CLI Hub](06-projects/new-repo/README.md) - [New-Repo CLI Hub](06-projects/new-repo/README.md)
- [Supervisor Hub](06-projects/supervisor/README.md) - [Supervisor Hub](06-projects/supervisor/README.md)
- [Second Brain Tooling Hub](06-projects/brain/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)
--- ---