diff --git a/AGENTS.md b/AGENTS.md index 84bc86e..57b7438 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,11 +34,28 @@ Sub-directories: Knowledge documents do not become the canonical location for project-specific information. A knowledge document describes *what something is*; a project document describes *how this project uses it*. ### `projects/` -Each project lives in its own sub-folder (e.g., `projects/homelab/`, `projects/magnetflix/`). The canonical entrypoint and landing page for any project must always be named `README.md` (e.g., `projects/homelab/README.md`) so that documentation renderers (such as `doc2site`) automatically compile it as the directory's index/landing page. Do not use `overview.md`. +Each project lives in its own sub-folder (e.g., `projects/homelab/`, `projects/nixos/`, `projects/magnetflix/`). The canonical entrypoint and landing page for any project must always be named `README.md` (e.g., `projects/homelab/README.md`) so that documentation renderers (such as `doc2site`) automatically compile it as the directory's index/landing page. Do not use `overview.md`. -Projects may have their own `plans/`, `guides/`, `decisions/`, or `research/` sub-directories. +#### Standard Project Directory Structure +Every project follows a three-part lifecycle structure under its folder: -The folder establishes context (ownership/locality). The document's `type` field establishes its semantic role. +1. **`discussions/` — "Why & What If?"** + - Architectural inquiries, problem statements, exploratory trade-off analyses, and evaluation of alternative paths (Model A vs. Model B). + - *Format*: Problem Statement → Context & Analysis → Options Evaluation (Pros & Cons) → Consensus / Resolution / Open Questions. + - *Role*: The foundation from which actionable plans originate. + - *Frontmatter*: `type: discussion`, `project: `, `date: YYYY-MM-DD`. + +2. **`plans/` — "How & When?"** + - Actionable implementation roadmaps, milestone breakdowns, and phased technical executions. + - *Prerequisite*: A plan should ideally be the concrete output of a resolved discussion. + - *Frontmatter*: `type: plan`, `status: draft | active | completed | abandoned`, `project: `. + +3. **`guides/` — "How to Use & Operate?"** + - Practical, operational runbooks and user-facing standard operating procedures (SOPs). + - *Content*: Answers concrete operational questions: *How to deploy a new service*, *How to rotate secrets*, *How to troubleshoot WAN rotation*. A guide explains how to **use and maintain** existing capabilities, not how to architect or implement new ones. + - *Frontmatter*: `type: guide`, `project: `. + +The folder establishes context (ownership/locality). The document's `type` field establishes its semantic role. Projects may reference documents in other projects via relative links. ### `records/` Historical artifacts. The original messy thinking is worth preserving — often what you want to recover later is not just the conclusion, but *why* you reached it. diff --git a/projects/homelab/discussions/chatbot-assistant-design.md b/projects/homelab/discussions/chatbot-assistant-design.md new file mode 100644 index 0000000..6549a09 --- /dev/null +++ b/projects/homelab/discussions/chatbot-assistant-design.md @@ -0,0 +1,88 @@ +--- +type: discussion +project: homelab +date: 2026-09-08 +tags: + - homelab + - ai + - chatbot + - telegram +--- + +# 🤖 WhatsApp & Telegram AI Assistant Backend Architecture + +## 🎯 Motivation & Objectives +Create a lightweight, self-hosted chatbot backend running on the `roadtotech.me` homelab cluster that serves as a personal AI assistant over messaging channels (Telegram / WhatsApp). + +### Primary Capabilities: +1. **Routine Reminders & Scheduled Alerts**: Cron-based triggers for study blocks, habits, and daily check-ins. +2. **AI Engineering Coach & Job Advice**: Context-aware guidance drawing from the resident's curriculum notes (`~/Brain/knowledge`, `~/Brain/journal`, `~/Brain/practice`). +3. **Quick Thought & Note Ingestion**: Send a text or voice memo to the bot to automatically append notes into `~/Brain/journal/` or `~/Brain/knowledge/parking-lot.md`. + +--- + +## 🏛️ System Architecture + +``` +┌─────────────────────────────────────────────────────────┐ +│ COMMUNICATION CLIENTS │ +│ [ Telegram Mobile App ] / [ WhatsApp Web/App ]│ +│ │ │ │ +└───────────────────┼─────────────────────────┼───────────┘ + │ (Webhook over HTTPS) │ + ▼ ▼ +┌─────────────────────────────────────────────────────────┐ +│ TRAEFIK EDGE REVERSE PROXY (:443) │ +│ https://bot.roadtotech.me (Wildcard TLS) │ +└───────────────────────────┬─────────────────────────────┘ + │ (proxy-net) + ▼ +┌─────────────────────────────────────────────────────────┐ +│ HOMELAB ASSISTANT BACKEND (FastAPI / Python) │ +│ ~/Sites/homelab-assistant │ +│ │ +│ ┌────────────────────────┐ ┌────────────────────────┐ │ +│ │ APScheduler (Cron/Jobs)│ │ Auth & User Whitelist │ │ +│ │ - Daily Coaching (8am) │ │ - Reject unknown IDs │ │ +│ │ - Evening Journal Promp│ │ - Single-user security │ │ +│ └────────────────────────┘ └────────────────────────┘ │ +│ │ +│ ┌────────────────────────────────────────────────────┐ │ +│ │ Brain Vault Integration & LLM RAG │ │ +│ │ - Read access to ~/Brain │ │ +│ │ - LLM Engine: Ollama / Anthropic Claude / OpenAI │ │ +│ │ - Tool Use: Read notes, add to journal │ │ +│ └────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────┘ +``` + +--- + +## ⚖️ Telegram Bot API vs. WhatsApp Cloud API + +| Metric | Telegram Bot API 🌟 *(Recommended)* | WhatsApp (Cloud API / Baileys) | +| :--- | :--- | :--- | +| **Setup Friction** | ⚡ **30 Seconds**: Chat with `@BotFather`, get API token | ⚠️ High: Requires Meta Developer Account, Business Verification | +| **Cost & Quotas** | 🆓 **100% Free**, unlimited messages | ⚠️ Paid conversation tiers after free monthly threshold | +| **Formatting** | Full Markdown, inline buttons, audio, custom keyboards | Limited markdown, strict template rules for outbound messages | +| **Outbound Cron Messages** | Send messages anytime without pre-approved templates | Requires pre-approved WhatsApp message templates | +| **Security** | Simple user ID whitelist (only responds to your Telegram ID)| Phone number whitelist | + +--- + +## 🚀 Step-by-Step Implementation Roadmap + +### Phase 1: Microservice Scaffolding (`~/Sites/homelab-assistant`) +* FastAPI application with `python-telegram-bot` (or `aiogram`). +* Secure webhook endpoint: `POST https://bot.roadtotech.me/webhook/telegram`. +* User ID whitelist middleware: Ignore and drop any message not originating from your authorized Telegram User ID. + +### Phase 2: APScheduler Proactive Notifications +* Schedule recurring cron jobs: + - **08:00 AM**: Daily focus milestone + morning coaching question. + - **09:00 PM**: Evening reflection reminder. + +### Phase 3: Brain Vault Tools & RAG +* Connect the assistant with read/write access to `/home/kiskaadee/Brain`: + - `/note `: Appends entry to `~/Brain/journal/daily/YYYY-MM-DD.md`. + - `/ask `: RAG search across `~/Brain/knowledge` to answer questions about past study notes. diff --git a/records/discussions/2026-09-gitea-git-helper-and-backup-strategy.md b/projects/homelab/discussions/gitea-credentials-and-backup-strategy.md similarity index 100% rename from records/discussions/2026-09-gitea-git-helper-and-backup-strategy.md rename to projects/homelab/discussions/gitea-credentials-and-backup-strategy.md diff --git a/projects/homelab/discussions/gitops-dispatcher-architecture.md b/projects/homelab/discussions/gitops-dispatcher-architecture.md new file mode 100644 index 0000000..b478045 --- /dev/null +++ b/projects/homelab/discussions/gitops-dispatcher-architecture.md @@ -0,0 +1,167 @@ +--- +type: discussion +project: homelab +date: 2026-09-08 +tags: + - homelab + - gitops + - webhook + - gitea + - appctl + - automation + - architecture +--- + +# 🚀 Dynamic Decentralized GitOps Dispatcher Architecture + +## 🎯 Motivation & Core Invariants + +In a modular homelab containing multiple containerized web applications (`~/Sites/*`), infrastructure control planes (`~/Core`), and data vaults (`~/Brain`), traditional centralized CI/CD configurations create unnecessary friction and blast radius. + +The **Dynamic GitOps Dispatcher** is built around four fundamental architectural invariants: + +1. **Zero Core Restarts (Decoupled Control Plane)**: + Deploying a new application, onboarding a service, or updating deployment routines must **never require restarting or modifying Core infrastructure services** (Traefik, Authelia, Webhook daemon). +2. **Decentralized Manifests (`app.yaml`)**: + Each application repository in `~/Sites` owns and declares its own deployment lifecycle directly within its local `app.yaml` manifest. +3. **Zero Schema Drift**: + There are no centralized deployment tables or static hardcoded lists. The dispatcher discovers target directories and deployment strategies dynamically at runtime. +4. **Graceful Data Vault Fallbacks**: + Repositories without Docker Compose stacks (e.g. `second-brain` data vault) automatically execute clean fast-forward Git pulls (`git pull --ff-only origin `). + +--- + +## 🏛️ System Architecture & Components + +```mermaid +flowchart TD + subgraph GitForge["1. Git Forge (Gitea)"] + Push["Developer Git Push"] + Webhook["HTTP POST (JSON Payload)\nhttp://192.168.1.36:9000/hooks/deploy"] + Push --> Webhook + end + + subgraph CoreDaemon["2. Homelab Control Plane (NixOS systemd)"] + Daemon["homelab-gitops.service\n(pkgs.webhook on port 9000)"] + Engine["gitops_dispatcher.py\n(Dynamic Python 3 Engine)"] + Webhook --> Daemon + Daemon -->|Pipes JSON via stdin| Engine + end + + subgraph Discovery["3. Dynamic Target Resolution Engine"] + Engine --> CheckType{"Resolve Payload"} + CheckType -->|"second-brain"| BrainTarget["Target: ~/Brain\nAction: git pull --ff-only"] + CheckType -->|"homelab- / "| SiteTarget["Target: ~/Sites/\nRead local app.yaml"] + CheckType -->|"Override Registry"| CustomTarget["Target: ~/.config/homelab/deployments.yaml"] + end + + subgraph Execution["4. Deployment Execution Lifecycle"] + SiteTarget --> ReadManifest["Parse app.yaml (deployment block)"] + ReadManifest --> Actions{"Execute Actions"} + Actions -->|git_pull| GitPull["git pull --ff-only origin main"] + Actions -->|compose_up| ComposeUp["docker compose up -d --remove-orphans"] + Actions -->|compose_build| ComposeBuild["docker compose build && up -d"] + Actions -->|compose_restart| ComposeRestart["docker compose restart"] + Actions -->|custom| CustomCmd["Execute shell command"] + end + + subgraph LiveRuntime["5. Live Application State"] + GitPull --> LiveApps["Container / Vault Updated Live (<2s)"] + ComposeUp --> LiveApps + ComposeBuild --> LiveApps + CustomCmd --> LiveApps + BrainTarget --> LiveApps + end +``` + +--- + +## 🧩 Key System Components + +### 1. The Declarative Webhook Daemon (`pkgs.webhook`) +The webhook listener is declared immutably via NixOS in [`Config/hosts/server/homeserver.nix`](file:///home/kiskaadee/Config/hosts/server/homeserver.nix): +- **Port**: `9000` (Internal LAN / Tailscale only). +- **Service Name**: `homelab-gitops.service`. +- **Payload Handling**: Configured with `pass-arguments-to-command = [ { source = "entire-payload"; } ]`, passing the complete Gitea JSON event payload directly into the Python dispatcher arguments. + +### 2. The Dynamic Dispatcher Engine ([`gitops_dispatcher.py`](file:///home/kiskaadee/Projects/active/homelab/homelab-core/scripts/gitops_dispatcher.py)) +A zero-dependency Python 3 engine executing on the server host: +- Parses the repository name and ref (`branch`) from standard input. +- Dynamically locates the target directory in `~/Sites` (matching ``, `homelab-`, or data vaults). +- Parses `app.yaml` using a built-in lightweight YAML parser. +- Sequentially executes declared deployment actions. + +### 3. Application Manifest Standard (`app.yaml`) +Placed in the root of each application repository in `~/Sites//app.yaml`: + +```yaml +name: "doc2site" +aliases: + - "docs" +domain: "docs.roadtotech.me" +description: "Documentation portal" +visible: true +auth: false + +# Deployment Lifecycle Specification +deployment: + branch: "main" # Target branch to trigger on + actions: + - git_pull # 1. Pull latest commit via --ff-only + - compose_up # 2. Run docker compose up -d --remove-orphans +``` + +#### Available Deployment Actions: +| Action | Execution Command | Use Case | +| :--- | :--- | :--- | +| `git_pull` | `git -C pull --ff-only origin ` | Standard for code/content updates | +| `compose_up` | `docker compose -f up -d --remove-orphans` | Recreate containers with new config/env | +| `compose_build` | `docker compose build && docker compose up -d` | Applications with local Dockerfiles | +| `compose_restart`| `docker compose restart` | Quick container restart without recreation | +| `custom: ""`| `subprocess.run(cmd, shell=True)` | Custom database migrations or build scripts | + +--- + +## 🛠️ End-to-End Onboarding Guide for New Services + +To onboard any new service into the automated GitOps deployment pipeline: + +### Step 1: Create the Application Repository +Create your repository on Gitea (e.g. `homelab-myapp` or `myapp`). + +### Step 2: Add `app.yaml` Manifest +In the root of your application repository, create `app.yaml`: +```yaml +name: "myapp" +domain: "myapp.roadtotech.me" +description: "My new homelab application" +visible: true +auth: true + +deployment: + branch: "main" + actions: + - git_pull + - compose_up +``` + +### Step 3: Clone to Server Host +Clone the repository into `~/Sites` on the server: +```bash +git clone ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-myapp.git ~/Sites/homelab-myapp +``` + +### Step 4: Configure Webhook in Gitea +1. In Gitea, navigate to **Repository Settings** $\rightarrow$ **Webhooks** $\rightarrow$ **Add Webhook** $\rightarrow$ **Gitea**. +2. **Target URL**: `http://192.168.1.36:9000/hooks/deploy` +3. **HTTP Method**: `POST` +4. **Trigger On**: `Push Events` +5. Click **Add Webhook**. + +### Step 5: Test & Verify +Push a commit from your workstation: +```bash +git commit -m "feat: initial feature release" +git push origin main +``` +The Gitea webhook fires $\rightarrow$ `gitops_dispatcher.py` pulls the update $\rightarrow$ Docker recreates containers $\rightarrow$ Service is updated live with zero manual SSH commands required. diff --git a/records/discussions/2026-09-11-nixos-homelab-core-migration-inventory.md b/projects/homelab/discussions/nixos-monorepo-decoupling.md similarity index 100% rename from records/discussions/2026-09-11-nixos-homelab-core-migration-inventory.md rename to projects/homelab/discussions/nixos-monorepo-decoupling.md diff --git a/records/discussions/2026-09-nixos-monorepo-vs-multirepo-architecture.md b/projects/homelab/discussions/nixos-monorepo-vs-multirepo.md similarity index 99% rename from records/discussions/2026-09-nixos-monorepo-vs-multirepo-architecture.md rename to projects/homelab/discussions/nixos-monorepo-vs-multirepo.md index de769c8..4d79f7f 100644 --- a/records/discussions/2026-09-nixos-monorepo-vs-multirepo-architecture.md +++ b/projects/homelab/discussions/nixos-monorepo-vs-multirepo.md @@ -1,6 +1,6 @@ --- type: discussion -project: nixos +project: homelab tags: - nixos - architecture diff --git a/projects/nixos/README.md b/projects/nixos/README.md index 293616b..38b8089 100644 --- a/projects/nixos/README.md +++ b/projects/nixos/README.md @@ -68,7 +68,8 @@ graph TD ## 🏛️ Architectural Discussions & Records -* [Discussion: NixOS Monorepo vs. Multi-Repo Architecture for Homelab & Workstations](../../records/discussions/2026-09-nixos-monorepo-vs-multirepo-architecture.md) +* [Discussion: NixOS Monorepo vs. Multi-Repo Architecture for Homelab & Workstations](../homelab/discussions/nixos-monorepo-vs-multirepo.md) +* [Discussion: Decoupling `nixos-config` and `homelab-core`](../homelab/discussions/nixos-monorepo-decoupling.md) ---