# entities

entity_id: user_identity
type: user_preference
category: identity
strength: strong
metadata: {}
created_at: 2026-05-13
updated_at: 2026-05-25T22:06:29.765166
content:
  [graph-sync] [user_identity/identity] [P:HIGH] user_name: Grepples, agent_name: Vincent, student_age: 7, student_stage: developing handwriting


entity_id: no_assumptions_rule
type: user_preference
category: communication
strength: strong
metadata: {}
created_at: 2026-05-13
updated_at: 2026-05-25T22:06:29.765166
content:
  [communication_rules] [P:HIGH] Never assume - follow instructions literally. User prefers detailed explanations. Prefers flat memory org (rejected tiers). Wants search + context-aware injection.


entity_id: worksheet_answer_spaces
type: user_preference
category: design
strength: strong
metadata: {}
created_at: 2026-05-13
updated_at: 2026-06-01 15:31:57
content:
  [worksheet_spaces] [P:MEDIUM] Answer spaces: 4-6em short, 6-8em shapes, 8em+ explanations. CSS: .b=3em, .bw=6em, .bl=8em.


entity_id: worksheet_layout_prefs
type: user_preference
category: layout
strength: strong
metadata: {}
created_at: 2026-05-13
updated_at: 2026-06-01 15:31:57
content:
  [worksheet_layout] [P:MEDIUM] Shapes: horizontal flex single row (display:flex; gap:10px) NOT grids. Blanks: padding-top for vertical space. Activities: height dividers. Review: one day at a time.


entity_id: phonics_worksheet_prefs
type: user_preference
category: worksheet_design
strength: strong
metadata: {}
created_at: 2026-05-13
updated_at: 2026-06-01 15:31:57
content:
  [phonics_prefs] [P:MEDIUM] Blanks: 20 underscores. Wed: 2-column fill. Thu: short stories. Fri: passage+Qs top, read+draw bottom, single page.


entity_id: weasyprint_break_fix
type: tool_quirk
category: tool_quirk
strength: strong
metadata: {}
created_at: 2026-05-18
updated_at: 2026-05-27T11:01:32.403243
content:
  [weasyprint_break_fix] CSS: add break-after:avoid to .section-title/.section-note. WP teacher_guide uses *_phonics_explanation param.


entity_id: seedvault_sales_data_seedvault
type: project
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-18
updated_at: 2026-05-25T22:06:29.765166
content:
  [seedvault_sales] 32 products: 24 seeds ($3.12 Mylar), 4 trees, 2 accessories, 1 starter ($32), 1 donation. ~37 orders/yr, $1.4k total, $30 avg. Bitcoin (on-chain + Lightning). All grow guides complete.


entity_id: ent_20260526T084744707543_5cf59285
type: system_info
category: debian/hardware
strength: strong
metadata: {}
created_at: 2026-05-26T08:47:44.707543
updated_at: 2026-05-26T08:47:44.707543
content:
  ## System Hardware
  - **CPU:** AMD Ryzen 9 9900X (12-core/24-thread, 5658 MHz max)
  - **GPU:** NVIDIA GeForce RTX 4090 (24GB VRAM, driver 595.71.05)
  - **RAM:** 60 GB DDR (11G used, 49G available)
  - **Storage:** 
    - NVMe (931.5GB): /boot/efi (976M), / (882.5GB), swap (48GB)
    - SATA (1.8TB): /mnt/storage (backup/data)
    - USB (14.9GB): /media/vincent/20A4-B53D (portable)
  - **Display:** GNOME on Wayland via GDM
  - **Audio:** PipeWire + WirePlumber (replaces PulseAudio)
  - **Shell:** bash (/bin/bash), user: vincent


entity_id: ent_20260526T084744844600_dc85b330
type: os_info
category: debian/os
strength: strong
metadata: {}
created_at: 2026-05-26T08:47:44.844600
updated_at: 2026-05-26T08:47:44.844600
content:
  ## Debian 13 (Trixie) — System Details
  - **OS:** Debian GNU/Linux 13 (trixie), 13.4
  - **Kernel:** 6.12.85+deb13-amd64, PREEMPT_DYNAMIC
  - **Package Manager:** apt/dpkg (Debian stable-ish — Trixie is "testing")
  - **Display Server:** Wayland (GNOME Shell)
  - **Init:** systemd (user + system level services)
  - **NetworkManager** manages network
  - **avahi-daemon** for mDNS/DNS-SD (local network discovery)
  - **fwupd** for firmware updates
  - **ModemManager** for cellular modems
  - **CUPS** + cups-browsed for printing


entity_id: ent_20260526T084744975870_7dba3e73
type: services
category: debian/services
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:44.975870
updated_at: 2026-05-26T08:47:44.975870
content:
  ## System Services — Key Daemons
  ### System-level (systemctl)
  - **apache2** — Apache HTTP Server (hosts websites)
  - **mariadb** — MariaDB 11.8.6 database (WordPress, apps)
  - **docker** + **containerd** — Container runtime
  - **cron** — Scheduled tasks
  - **llama-qwen** — Qwen3.6-27B local inference (CUDA, 64k context)
  - **freqtrade** — Crypto trading bot (systemd user service)
  - **bitcoin-dashboard** — Bitcoin trading bot dashboard
  - **nvidia-persistenced** — NVIDIA GPU persistence
  - **graph-watch** — Watch graph.json for changes, sync to memory
  - **bluetooth** — Bluetooth service
  - **accounts-daemon** — System user accounts
  - **polkit** — Authorization manager
  - **low-memory-monitor** — OOM prevention

  ### User-level (systemctl --user)
  - **freqtrade.service** — Freqtrade trading bot
  - **graph-watch.service** — Memory graph sync
  - **pipewire** + **wireplumber** — Audio/multimedia
  - **gnome-keyring-daemon** — Credential storage
  - **ssh-agent** — SSH key management


entity_id: ent_20260526T084745112918_2f192f6b
type: reference
category: debian/packages
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:45.112918
updated_at: 2026-05-26T08:47:45.112918
content:
  ## Debian Package Management — Key Patterns
  - **apt** primary package manager: `apt install`, `apt remove`, `apt upgrade`
  - **dpkg** low-level: `dpkg -l` (list), `dpkg -s` (status), `dpkg -L` (files)
  - **apt-listbugs** / **apt-listchanges** for release notes
  - System config dirs:
    - `/etc/` — system configuration
    - `/etc/systemd/system/` — custom systemd units
    - `~/.config/systemd/user/` — user-level systemd units
  - **log management:** `journalctl -u service_name`, `journalctl --user -u service_name`
  - **Debian trixie** is "testing" — packages between stable and unstable
  - **/etc/apt/sources.list** — repository configuration
  - **/etc/fstab** — filesystem mount configuration


entity_id: ent_20260526T084745246195_d7042e54
type: reference
category: debian/systemd
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:45.246195
updated_at: 2026-05-26T08:47:45.246195
content:
  ## Debian Service Management — systemd Patterns
  - **System services:** `systemctl enable/disable/start/stop/restart <service>`
  - **User services:** `systemctl --user enable/disable/start/stop/restart <service>`
  - **Status check:** `systemctl status <service>` / `systemctl --user status <service>`
  - **Unit files:** `/etc/systemd/system/` (system), `~/.config/systemd/user/` (user)
  - **Reload daemon:** `systemctl daemon-reload` (system), `systemctl --user daemon-reload` (user)
  - **Logs:** `journalctl -u <service> -f` (follow), `journalctl --user -u <service>`
  - **Failed units:** `systemctl --failed` / `systemctl --user --failed`
  - **Startup order:** Use `After=`, `Requires=`, `Wants=` in unit files
  - **Environment:** `Environment=` in unit, or `environment.d/` drop-in files


entity_id: ent_20260526T084745377414_8e44d838
type: reference
category: debian/docker
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:45.377414
updated_at: 2026-05-26T08:47:45.377414
content:
  ## Docker & Containers — Current Setup
  - **docker.service** and **containerd.service** running system-wide
  - **Apache** (apache2) serves as HTTP frontend
  - **MariaDB** (mariadb) runs as database backend
  - Used for: WordPress/WooCommerce (seedvault.market), local development
  - **Note:** `docker ps` returned empty — containers may be managed by Docker Compose or stopped
  - Container images stored under `/var/lib/docker/`
  - **Docker networking:** bridge (default), host, overlay (swarm)
  - Useful commands: `docker ps -a`, `docker compose -f <file> up -d`


entity_id: ent_20260526T084745508035_f71734f9
type: service_detail
category: debian/ai-inference
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:45.508035
updated_at: 2026-05-26T08:47:45.508035
content:
  ## Local AI Inference — Qwen3.6-27B
  - **Service:** llama-qwen.service (systemd)
  - **Model:** Qwen3.6-27B-UD-Q4_K_XL.gguf (4-bit quantized)
  - **Runtime:** llama.cpp with CUDA acceleration (RTX 4090)
  - **Context:** 64k tokens
  - **Binding:** Local only (127.0.0.1) — not exposed externally
  - **Purpose:** Hermes Agent local LLM provider
  - **GPU memory:** RTX 4090 24GB handles 27B Q4 comfortably (~14GB VRAM)


entity_id: ent_20260526T084745639193_21c3782a
type: system_info
category: debian/storage
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:45.639193
updated_at: 2026-05-26T08:47:45.639193
content:
  ## Storage Layout & Mount Points
  - **Root filesystem:** /dev/nvme0n1p2 (882.5GB, 26% used) mounted on /
  - **Boot:** /dev/nvme0n1p1 (976MB EFI) mounted on /boot/efi
  - **Swap:** /dev/nvme0n1p3 (48GB) — large swap for hibernation/memory overflow
  - **Data:** /dev/sda (1.8TB SATA) mounted on /mnt/storage — backups, media, data
  - **USB:** /dev/sdb1 (14.9GB) mounted on /media/vincent/20A4-B53D — portable drive
  - **Home:** ~ (vincent) on root filesystem (~213GB used of 868GB)
  - **Docker data:** /var/lib/docker/ (on root filesystem)
  - **Brain DB:** ~/.hermes/brain/index/events.db


entity_id: ent_20260526T084745768047_a07445f5
type: reference
category: debian/network
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:45.768047
updated_at: 2026-05-26T08:47:45.768047
content:
  ## Debian Network Configuration
  - **NetworkManager** handles network (Wi-Fi, ethernet, DNS)
  - **nmcli** CLI for management: `nmcli device status`, `nmcli connection show`
  - **avahi-daemon** for mDNS (.local addresses)
  - **/etc/hosts** — local hostname resolution
  - **/etc/resolv.conf** — DNS (managed by NetworkManager)
  - **iptables/nftables** — firewall (check with `nft list ruleset`)
  - Apache binds to port 80/443, llama-qwen on local port only
  - SSH access: check `/etc/ssh/sshd_config` and `ss -tlnp | grep 22`


entity_id: ent_20260526T084745896413_a69d151b
type: reference
category: debian/paths
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:45.896413
updated_at: 2026-05-26T08:47:45.896413
content:
  ## Key Debian Directories & Paths
  - **System config:** /etc/
  - **Systemd units:** /etc/systemd/system/ (system), ~/.config/systemd/user/ (user)
  - **Logs:** journalctl (systemd journal), /var/log/ (traditional)
  - **Cron:** /etc/crontab, /etc/cron.d/, crontab -e (user)
  - **Services:** /usr/lib/systemd/system/ (packages), /etc/systemd/system/ (admin)
  - **Home dirs:** /home/vincent/
  - **Hermes:** ~/.hermes/ (agent config, brain, skills, scripts)
  - **Docker:** /var/lib/docker/ (containers, images, volumes)
  - **Apache:** /etc/apache2/, /var/www/
  - **MariaDB:** /etc/mysql/, /var/lib/mysql/
  - **NVIDIA:** nvidia-smi, nvidia-settings, /etc/modprobe.d/nvidia.conf


entity_id: ent_20260526T084746050264_f900f2ab
type: reference
category: linux/fhs
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:46.050264
updated_at: 2026-05-26T08:47:46.050264
content:
  ## Debian Filesystem Hierarchy Standard (FHS)
  - `/bin`, `/sbin` — essential binaries (merged in modern Debian)
  - `/usr/` — read-only user programs, libs, headers
  - `/etc/` — host-specific configuration
  - `/var/` — variable data (logs, mail, spool, cache)
  - `/tmp/` — temporary files (cleared on reboot)
  - `/dev/` — device files
  - `/proc/` — process/virtual filesystem
  - `/sys/` — kernel/hardware interface
  - `/run/` — runtime data (PIDs, sockets) — volatile, cleared on reboot
  - `/opt/` — optional/third-party software
  - `/srv/` — service data (web, FTP)
  - `/home/` — user home directories
  - `/root/` — root home directory
  - `/boot/` — boot loader files
  - `/lib/`, `/usr/lib/` — shared libraries


entity_id: ent_20260526T084746190473_1347151c
type: reference
category: linux/processes
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:46.190473
updated_at: 2026-05-26T08:47:46.190473
content:
  ## Linux Process Management
  - **ps aux** — list all processes with details
  - **top** / **htop** — interactive process viewer
  - **kill PID** / **kill -9 PID** — terminate (signal 2 / signal 9)
  - **pgrep -a pattern** — find process by name
  - **pkill pattern** — kill by name
  - **nice / renice** — process priority adjustment
  - **systemd-cgtop** — cgroup resource usage
  - **lsof -i :PORT** — find what's using a port
  - **ss -tlnp** — listening sockets with processes
  - **strace -p PID** — trace system calls
  - Process signals: 1(HUP), 2(INT), 3(QUIT), 15(TERM), 9(KILL)
  - **OOM killer:** `dmesg | grep -i oom`, `/proc/sys/vm/oom_score_adj`


entity_id: ent_20260526T084746319781_ee7eaa7a
type: reference
category: linux/disks
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:46.319781
updated_at: 2026-05-26T08:47:46.319781
content:
  ## Linux Disk & Filesystem Management
  - **lsblk** — block device tree
  - **fdisk -l** / **blkid** — disk/partition info
  - **df -h** — filesystem usage
  - **du -sh path** — directory size
  - **mount / umount** — mount/unmount filesystems
  - **/etc/fstab** — persistent mount configuration
  - **mkfs.ext4 / mkfs.btrfs / mkfs.xfs** — create filesystems
  - **fsck** — filesystem check/repair
  - **find** — locate files: `find /path -name "*.py" -type f`
  - **locate** — database file search (updatedb)
  - **fdisk / parted** — partition management
  - **lvm** — logical volume management (pvcreate, vgcreate, lvcreate)
  - **btrfs** — copy-on-write filesystem (snapshots, compression)


entity_id: ent_20260526T084746448100_f99ed657
type: reference
category: linux/network
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:46.448100
updated_at: 2026-05-26T08:47:46.448100
content:
  ## Linux Network Management
  - **ip addr / ip route** — modern network config (replaces ifconfig)
  - **ss** — socket statistics (replaces netstat)
  - **nmcli** — NetworkManager CLI
  - **curl** / **wget** — HTTP transfers
  - **ping** / **traceroute** — connectivity diagnostics
  - **dig** / **nslookup** — DNS queries
  - **nmap** — port scanning
  - **ssh** — secure remote access
  - **scp** / **rsync** — file transfer
  - **iptables** / **nftables** — firewall
  - **tcpdump** — packet capture
  - **/etc/hosts** — local DNS overrides
  - **/etc/resolv.conf** — DNS resolver config
  - **/etc/network/interfaces** — legacy network config


entity_id: ent_20260526T084746577365_f6bdb9ab
type: reference
category: linux/permissions
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:46.577365
updated_at: 2026-05-26T08:47:46.577365
content:
  ## Linux File Permissions & Users
  - **chmod** — change permissions (u/g/o, r/w/x, 0-7)
  - **chown** — change owner/group
  - **useradd / userdel** — user management
  - **groupadd / groupdel** — group management
  - **passwd** — change password
  - **usermod -aG group user** — add user to group
  - **sudo** — execute as superuser
  - **/etc/sudoers** — sudo configuration (visudo)
  - **/etc/passwd** — user accounts
  - **/etc/shadow** — password hashes
  - **/etc/group** — group memberships
  - Permission bits: r=4, w=2, x=1 (user/group/other)
  - Special: SUID=4000, SGID=2000, Sticky=1000
  - **umask** — default permission mask


entity_id: ent_20260526T084746705528_7d6c5308
type: reference
category: debian/apt
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:46.705528
updated_at: 2026-05-26T08:47:46.705528
content:
  ## Debian apt Package Management — Essential Commands
  - **apt update** — refresh package lists
  - **apt upgrade** — upgrade all packages
  - **apt full-upgrade** — upgrade + handle dependencies (may remove packages)
  - **apt install <pkg>** — install package
  - **apt remove <pkg>** — remove package (keep config)
  - **apt purge <pkg>** — remove package + config
  - **apt autoremove** — remove orphaned dependencies
  - **apt search <term>** — search packages
  - **apt show <pkg>** — package details
  - **apt list --installed** — list installed packages
  - **apt list --upgradable** — available upgrades
  - **apt edit-sources** — edit sources.list
  - **dpkg -i file.deb** — install .deb file
  - **apt --fix-broken install** — repair broken dependencies
  - **/var/log/apt/history.log** — apt transaction history


entity_id: ent_20260526T084746836342_f73fdd14
type: reference
category: linux/logging
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:46.836342
updated_at: 2026-05-26T08:47:46.836342
content:
  ## Linux Logging & Diagnostics
  - **journalctl** — systemd log viewer
    - `journalctl -u service` — specific service
    - `journalctl -f` — follow (like tail -f)
    - `journalctl --since "1 hour ago"` — time range
    - `journalctl -p err` — errors and above
    - `journalctl --disk-usage` — log size
    - `journalctl --vacuum-time=7d` — prune old logs
  - **/var/log/** — traditional logs
    - syslog, auth.log, kern.log, dmesg
    - apache2/, mysql/, faillog
  - **dmesg** — kernel ring buffer
  - **lsof** — list open files
  - **vmstat / iostat / mpstat** — system stats
  - **free -h** — memory usage
  - **uptime / who / w** — system uptime and users
  - **htop / atop** — interactive system monitors
  - **/proc/** — process info filesystem
  - **/sys/** — kernel parameters (tunable)


entity_id: ent_20260526T084746966812_9465cb53
type: reference
category: linux/shell
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:46.966812
updated_at: 2026-05-26T08:47:46.966812
content:
  ## Linux Shell Essentials — bash
  - **Aliases:** ~/.bash_aliases (loaded by ~/.bashrc)
  - **Environment:** ~/.bashrc (interactive), ~/.profile (login), /etc/profile (system)
  - **Variables:** export VAR=value, echo $VAR, ${VAR:-default}
  - **Expansion:** ~ (home), $() (command substitution), `` (backticks)
  - **Globbing:** * (any), ? (one char), [abc] (set), {a,b,c} (brace)
  - **Redirection:** > (overwrite), >> (append), < (input), 2> (stderr), &> (both)
  - **Pipes:** | (stdout to stdin), |& (both streams)
  - **Background:** & (background), bg/fg, jobs, ctrl+z (suspend)
  - **History:** history, ctrl+r (search), HISTFILE=~/.bash_history
  - **Functions:** func() { commands; }
  - **Test:** [[ ]] (conditionals), test command
  - **read** — user input
  - **source ~/.bashrc** — reload config


entity_id: ent_20260526T084747094458_962c879d
type: reference
category: linux/cron
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:47.094458
updated_at: 2026-05-26T08:47:47.094458
content:
  ## Linux Cron — Scheduled Tasks
  - **crontab -e** — edit user cron jobs
  - **/etc/crontab** — system cron (with user field)
  - **/etc/cron.d/** — system cron snippets
  - **Format:** minute hour day month weekday command
    - `* * * * *` — every minute
    - `0 */2 * * *` — every 2 hours
    - `0 9 * * 1-5` — weekdays at 9am
    - `@reboot` — on system boot
    - `@daily` / `@weekly` / `@monthly`
  - **Special vars:** MAILTO, PATH, SHELL in crontab
  - **Logging:** cron logs to /var/log/syslog (grep CRON)
  - **systemd timers** — modern alternative to cron
    - timer units + service units
    - More precise, better logging with journalctl


entity_id: ent_20260526T084747218318_41653e1c
type: reference
category: linux/nvidia
strength: moderate
metadata: {}
created_at: 2026-05-26T08:47:47.218318
updated_at: 2026-05-26T08:47:47.218318
content:
  ## NVIDIA GPU — Linux Management
  - **nvidia-smi** — GPU status (memory, processes, temperature, power)
    - `nvidia-smi -l 1` — log every second
    - `nvidia-smi --query-gpu=memory.used,memory.total --format=csv`
  - **nvidia-settings** — GUI configuration
  - **nvidia-persistenced** — keeps driver loaded (systemd service running)
  - **CUDA:** /usr/local/cuda/ (if installed)
  - **Driver:** 595.71.05 (current)
  - **/etc/modprobe.d/nvidia.conf** — kernel module options
  - **Wayland + NVIDIA:** works on driver 535+ (we have 595)
  - **GPU compute:** llama.cpp uses CUDA for local inference


entity_id: ent_20260526T090227778359_a6c4f9a8
type: troubleshooting
category: debian/systemd-troubleshoot
strength: strong
metadata: {}
created_at: 2026-05-26T09:02:27.778359
updated_at: 2026-05-26T09:02:27.778359
content:
  ## Systemd Troubleshooting — Practical Guide
  - **Service won't start:**
    1. `systemctl status <service>` — check status and error
    2. `journalctl -u <service> -n 50 --no-pager` — recent logs
    3. Check unit file: `systemctl cat <service>`
    4. `systemd-analyze verify <service>.service` — syntax check
  - **Reload after config change:** `systemctl daemon-reload` then `systemctl restart <service>`
  - **User vs system service:** `systemctl --user status <service>` vs `systemctl status <service>`
  - **Enable at boot:** `systemctl enable <service>` (creates symlink in .wants)
  - **Check dependencies:** `systemctl list-dependencies <service>`
  - **Failed services:** `systemctl --failed` shows all failed units
  - **Common pitfalls:**
    - WorkingDirectory doesn't exist → service fails
    - ExecStart path wrong → use absolute paths
    - Missing Environment= vars → check env requirements
    - Port already in use → `ss -tlnp | grep :PORT`
    - Permission denied → check User=, Group=, file ownership


entity_id: ent_20260526T090227919122_a3d59ee8
type: troubleshooting
category: debian/docker-troubleshoot
strength: strong
metadata: {}
created_at: 2026-05-26T09:02:27.919122
updated_at: 2026-05-26T09:02:27.919122
content:
  ## Docker Troubleshooting — Common Issues
  - **Container won't start:** `docker logs <container>` for output
  - **Port conflicts:** `docker ps` check port mappings, `ss -tlnp | grep :PORT`
  - **Network issues:** `docker network ls`, `docker network inspect bridge`
  - **Storage issues:** `docker system df` — check disk usage
    - `docker system prune -a` — remove unused containers/images/volumes
  - **Container can't reach host DB:** use `host.docker.internal` or `172.17.0.1`
    - Or: `docker run --network host` for same network stack
  - **Permission denied on bind mounts:** fix host dir permissions or use :z/:Z suffix
  - **Volume persistence:** Named volumes survive container removal
    - `docker volume ls`, `docker volume inspect <name>`
  - **Compose:** `docker compose -f <file> up -d`, `docker compose logs -f`
  - **Debugging:** `docker exec -it <container> bash` — shell into container
  - **Rebuild:** `docker compose up -d --build` (rebuilds images)


entity_id: ent_20260526T090228047191_627eeb0d
type: troubleshooting
category: debian/apache-troubleshoot
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:28.047191
updated_at: 2026-05-26T09:02:28.047191
content:
  ## Apache Troubleshooting — Common Issues
  - **Service checks:** `systemctl status apache2`, `apachectl configtest`
  - **Port 80/443 conflicts:** `ss -tlnp | grep ':80\|:443'`
    - Other process on port? `fuser 80/tcp`, `fuser 443/tcp`
  - **SSL cert issues:** `apachectl ssl` check, verify cert paths in VirtualHost
  - **500 errors:** Check `/var/log/apache2/error.log`
  - **403 Forbidden:** Directory permissions, AllowOverride, Options
  - **Mod not loaded:** `apache2ctl -M` lists loaded modules
    - Enable: `a2enmod <module>`, disable: `a2dismod <module>`
  - **VirtualHost not working:** `a2ensite <site>`, `a2dissite <site>`
  - **Common mods needed:** rewrite, ssl, headers, proxy, proxy_http
  - **Performance:** `mod_cache_disk` enabled (apache-htcacheclean running)
  - **Config test before reload:** ALWAYS run `apachectl configtest` first


entity_id: ent_20260526T090228174104_f3a9a1bb
type: troubleshooting
category: debian/mariadb-troubleshoot
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:28.174104
updated_at: 2026-05-26T09:02:28.174104
content:
  ## MariaDB Troubleshooting — Common Issues
  - **Service:** `systemctl status mariadb`
  - **Can't connect:** Check /etc/mysql/mariadb.conf.d/, socket location
    - `mysqladmin -u root status` — quick health check
    - `mysql -u root -p` — CLI connection test
  - **Authentication:** Debian uses unix_socket auth by default for root
    - `sudo mysql` works, `mysql -u root -p` may not
    - Fix: `ALTER USER 'root'@'localhost' IDENTIFIED BY 'password';`
  - **Remote access:** Bind address in config (0.0.0.0 for all interfaces)
    - Create user with host: `CREATE USER 'user'@'%' IDENTIFIED BY 'pass';`
  - **Disk space:** InnoDB data files in /var/lib/mysql/
    - `SELECT table_schema, ROUND(SUM(data_length+index_length)/1024/1024,1) AS MB FROM information_schema.tables GROUP BY table_schema;`
  - **Slow queries:** Enable slow_query_log in config, check /var/log/mysql/
  - **Backup:** `mysqldump -u root --all-databases > backup.sql`
  - **Import:** `mysql -u root < backup.sql`


entity_id: ent_20260526T090228302764_b403e404
type: troubleshooting
category: linux/disk-management
strength: strong
metadata: {}
created_at: 2026-05-26T09:02:28.302764
updated_at: 2026-05-26T09:02:28.302764
content:
  ## Disk Space Management — Diagnostics & Cleanup
  - **Check usage:** `df -h` (filesystems), `du -sh /*` (top-level dirs)
  - **Find large files:** `find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null | sort -k5 -h`
  - **Journal bloat:** `journalctl --disk-usage`, `journalctl --vacuum-size=500M`
  - **Apt cache:** `apt clean` (removes downloaded .deb files)
  - **Old kernels:** `dpkg -l 'linux-image-*'` → purge old ones
  - **Docker disk usage:** `docker system df` → `docker system prune -a`
  - **Thumbnails:** `rm -rf ~/.cache/thumbnails/*` (safe, regenerates)
  - **Package logs:** `journalctl --vacuum-time=7d`
  - **/tmp cleanup:** files cleared on reboot, or `rm -rf /tmp/*`
  - **Swap usage:** `free -h`, `swapon --show`
  - **Filesystem check:** `sudo fsck -f /dev/sdX` (unmounted only!)
  - **Inode usage:** `df -i` — can run out even with space available


entity_id: ent_20260526T090228431127_816b8ec3
type: reference
category: linux/ssh-security
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:28.431127
updated_at: 2026-05-26T09:02:28.431127
content:
  ## SSH Security — Hardening Checklist
  - **Config:** /etc/ssh/sshd_config
    - `PermitRootLogin no` — disable root login
    - `PasswordAuthentication no` — key-only auth
    - `PubkeyAuthentication yes` — SSH keys
    - `Port 22` — consider non-standard port (security through obscurity)
    - `MaxAuthTries 3` — limit brute force attempts
    - `AllowUsers vincent` — restrict to specific users
    - `ClientAliveInterval 300` — keepalive timeout
  - **Key management:**
    - `ssh-keygen -t ed25519` — modern key generation
    - `ssh-copy-id user@host` — deploy public key
    - `~/.ssh/authorized_keys` — authorized keys file (600 perms)
    - `~/.ssh/config` — client config (Host aliases, keys)
  - **Fail2ban:** `apt install fail2ban` — brute force protection
  - **Check active sessions:** `who`, `w`, `last`
  - **Restart after config:** `systemctl reload sshd` (graceful)
  - **Test before locking yourself out:** keep another terminal open!


entity_id: ent_20260526T090228558625_aa0f8b6f
type: reference
category: linux/firewall
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:28.558625
updated_at: 2026-05-26T09:02:28.558625
content:
  ## Linux Firewall — nftables (Debian 13 default)
  - **View rules:** `sudo nft list ruleset`
  - **Basic setup:**
    - `sudo nft add table inet filter`
    - `sudo nft add chain inet filter input { type filter hook input priority 0 ; policy drop ; }`
    - `sudo nft add rule inet filter input ct state established,related accept`
    - `sudo nft add rule inet filter input iif lo accept`
    - `sudo nft add rule inet filter input tcp dport { 22, 80, 443 } accept`
  - **Persistent:** Save to /etc/nftables.conf
    - `sudo nft list ruleset > /etc/nftables.conf`
    - Enable service: `systemctl enable nftables`
  - **Useful commands:**
    - `sudo nft flush ruleset` — clear all rules (⚠️ drops everything!)
    - `sudo nft add rule inet filter input tcp dport 8080 accept` — add port
    - `sudo nft delete rule inet filter input handle <num>` — remove by handle
  - **Check if firewall active:** `sudo nft list ruleset` (empty = no firewall)
  - **Don't lock yourself out:** always allow SSH port first


entity_id: ent_20260526T090228685653_b9bf49c3
type: troubleshooting
category: linux/wayland-nvidia
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:28.685653
updated_at: 2026-05-26T09:02:28.685653
content:
  ## Wayland + NVIDIA — Known Issues & Fixes
  - **Current setup:** GNOME on Wayland, NVIDIA 4090, driver 595.71.05
  - **Driver 535+** required for proper Wayland support (we have 595 ✅)
  - **Common issues:**
    - Screen tearing: `nvidia-settings -a AllowIndirectGLXProtocol=0` (X11)
    - Black screen on login: fallback to X11 at GDM screen
    - External monitor flicker: check EDID, try `nvidia-drm.modeset=1` kernel param
    - VRAM not showing: `nvidia-smi` still works on Wayland
  - **Kernel params (GRUB):** /etc/default/grub, GRUB_CMDLINE_LINUX
    - `nvidia-drm.modeset=1` — DRM kernel mode setting (recommended)
    - `nvidia.NVreg_PreserveVideoMemoryAllocations=1` — preserve VRAM across suspend
    - After editing: `update-grub`
  - **GPU compute on Wayland:** CUDA apps work fine, EGL streams available
  - **Check:** `echo $XDG_SESSION_TYPE` → should be 'wayland'


entity_id: ent_20260526T090228812537_7caf7aa5
type: reference
category: linux/monitoring
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:28.812537
updated_at: 2026-05-26T09:02:28.812537
content:
  ## System Monitoring — Tools & Commands
  - **CPU:** `top`, `htop`, `mpstat 1`, `/proc/loadavg`
  - **Memory:** `free -h`, `htop`, `/proc/meminfo`
  - **Disk I/O:** `iostat -x 1`, `iotop`, `df -h`
  - **Network:** `ss -s`, `ip -s link`, `nload`, `iftop`
  - **GPU:** `nvidia-smi -l 1`, `nvidia-smi --query-gpu=temperature.gpu,memory.used,memory.total,utilization.gpu --format=csv -l 1`
  - **Processes:** `ps aux --sort=-%mem | head` — top memory consumers
  - **Open files:** `lsof | wc -l`, `cat /proc/sys/fs/file-nr`
  - **Uptime:** `uptime`, `w`
  - **Systemd resources:** `systemd-cgtop` — per-service resource usage
  - **Power:** `sensors` (lm-sensors), `cat /proc/acpi/battery/*`
  - **AMD CPU power:** `sudo cat /sys/class/hwmon/hwmon*/temp1_input`
    - MSR tools for detailed power: `rdmsr`, `wrmsr` (requires root)
  - **Quick health check script:** `cat /proc/loadavg && free -h && df -h / && nvidia-smi --query-gpu=temperature.gpu,memory.used --format=csv`


entity_id: ent_20260526T090228940119_8ef785b2
type: reference
category: linux/bash-scripting
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:28.940119
updated_at: 2026-05-26T09:02:28.940119
content:
  ## Bash Scripting — Essential Patterns for Admin Tasks
  - **Script header:** `#!/bin/bash` + `set -euo pipefail` (fail fast)
  - **Functions:**
    ```bash
    log() { echo "[$(date +%H:%M:%S)] $*"; }
    die() { log "ERROR: $*"; exit 1; }
    check_cmd() { command -v "$1" >/dev/null || die "Need $1"; }
    ```
  - **Argument parsing:** `getopts` or manual shift pattern
  - **File operations:**
    - `[ -f file ]` — exists and is file
    - `[ -d dir ]` — exists and is directory
    - `[ -r file ]` — readable
    - `[ -x file ]` — executable
    - `[ -s file ]` — exists and non-empty
    - `[ file1 -nt file2 ]` — file1 newer than file2
  - **Text processing:** `grep`, `sed`, `awk`, `cut`, `sort`, `uniq`, `wc`
  - **String ops:** `${var%%pattern}`, `${var##pattern}`, `${var/pattern/replacement}`, `${#var}`
  - **Arrays:** `arr=(a b c)`, `${arr[@]}`, `${arr[0]}`, `${#arr[@]}`
  - **Subshells:** `result=$(command)`, `$(< file)` (read file)
  - **Temp files:** `tmp=$(mktemp)`, trap cleanup: `trap 'rm -f $tmp' EXIT`
  - **Parallel:** `xargs -P 4`, `GNU parallel`


entity_id: ent_20260526T090229066813_144d95a1
type: reference
category: linux/backup
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:29.066813
updated_at: 2026-05-26T09:02:29.066813
content:
  ## Backup Strategies — Patterns & Tools
  - **rsync** — incremental sync (best for regular backups)
    - `rsync -avz --delete /source/ /dest/` — mirror directory
    - `rsync -avz --exclude={'*.pyc','__pycache__','.git'} /src/ /dst/`
    - SSH: `rsync -avz -e ssh /src/ user@host:/dst/`
  - **tar** — archive + compress
    - `tar czf backup.tar.gz /path/` — create
    - `tar xzf backup.tar.gz -C /dest/` — extract
    - `tar tzf backup.tar.gz` — list contents
  - **Database:** `mysqldump -u root --all-databases | gzip > db.sql.gz`
  - **Cron backups:** `0 2 * * * rsync -az /important/ /mnt/storage/backup/`
  - **Hermes backup:** ~/VincentBackup/backup_*.py (cron job, daily)
  - **USB backup:** Detect device → rsync → notify
  - **Rotation strategy:** Keep N daily, N weekly, N monthly backups
    - Use date in filename: `backup_$(date +%Y%m%d).tar.gz`
    - Cleanup old: `find /backups/ -name '*.tar.gz' -mtime +30 -delete`


entity_id: ent_20260526T090229194808_6c1a0062
type: reference
category: linux/security
strength: moderate
metadata: {}
created_at: 2026-05-26T09:02:29.194808
updated_at: 2026-05-26T09:02:29.194808
content:
  ## Debian Security — Basics & Hardening
  - **Update regularly:** `apt update && apt upgrade`
  - **Security patches:** Debian Security repository (debian-security)
  - **Check for updates:** `apt list --upgradable 2>/dev/null | grep -i security`
  - **Unattended upgrades:** `apt install unattended-upgrades`, configure in /etc/apt/apt.conf.d/
  - **User permissions:**
    - Principle of least privilege — don't run as root unless needed
    - Sudo for admin tasks (logs everything)
    - Check: `sudo -l` — what can current user sudo
  - **File permissions audit:**
    - `find / -perm -4000 -type f 2>/dev/null` — SUID files
    - `find /home -name '*.pem' -o -name '*.key' 2>/dev/null` — private keys
  - **Network security:**
    - Close unused ports: `ss -tlnp`
    - Firewall: nftables (see linux/firewall)
    - SSH: key-only, no root, fail2ban (see linux/ssh-security)
  - **Audit tools:** `apt install debsums` → `debsums -c` (check package file integrity)


entity_id: ent_20260526T090307816314_3e07961e
type: tool_quirk
category: brain/fts-limitations
strength: strong
metadata: {}
created_at: 2026-05-26T09:03:07.816314
updated_at: 2026-05-26T09:03:07.816314
content:
  ## Brain FTS Search — Known Limitations & Workarounds
  - **Tokenizer:** Standard FTS5 with Porter stemming (trigram NOT available on this system)
  - **Porter tokenizer behavior:**
    - ✅ Stemming works: "running" → "run", "searches" → "search"
    - ✅ Multi-word: all words must be present (AND logic)
    - ❌ Contractions break: "won't", "can't", "it's" → tokenized incorrectly
    - ❌ No fuzzy matching: misspellings won't match ("servce" ≠ "service")
    - ❌ Short words (<3 chars): dropped by Porter tokenizer
  - **Search workarounds:**
    - Instead of "service won't start" → "service start systemd"
    - Instead of "can't connect" → "connect failed" or "connection refused"
    - Instead of "it's not working" → "not working error"
    - Use key terms only: "Docker port conflict" → "Docker port"
    - Longer queries = more restrictive (AND logic)
  - **Improvement options (if SQLite with trigram available):**
    - `CREATE VIRTUAL TABLE entity_fts USING trigram(...)` enables fuzzy matching
    - Handles misspellings, partial words, contractions correctly
    - Requires SQLite compiled with trigram extension
  - **Events FTS:** Also Porter — same limitations apply to event search


entity_id: ent_20260526T121519926156_62367457
type: domain
category: debian
strength: strong
metadata: {}
created_at: 2026-05-26T12:15:19.926156
updated_at: 2026-05-26T12:15:19.926156
content:
  ## Debian — Domain Overview
  Contains 15 sub-entities covering:
  - **ai-inference** (ent_20260526T0847455, moderate)
  - **apache-troubleshoot** (ent_20260526T0902280, moderate)
  - **apt** (ent_20260526T0847467, moderate)
  - **docker** (ent_20260526T0847453, moderate)
  - **docker-troubleshoot** (ent_20260526T0902279, strong)
  - **hardware** (ent_20260526T0847447, strong)
  - **mariadb-troubleshoot** (ent_20260526T0902281, moderate)
  - **network** (ent_20260526T0847457, moderate)
  - **os** (ent_20260526T0847448, strong)
  - **packages** (ent_20260526T0847451, moderate)
  - **paths** (ent_20260526T0847458, moderate)
  - **services** (ent_20260526T0847449, moderate)
  - **storage** (ent_20260526T0847456, moderate)
  - **systemd** (ent_20260526T0847452, moderate)
  - **systemd-troubleshoot** (ent_20260526T0902277, strong)


entity_id: ent_20260526T121520108468_d2ea67a3
type: domain
category: linux
strength: strong
metadata: {}
created_at: 2026-05-26T12:15:20.108468
updated_at: 2026-05-26T12:15:20.108468
content:
  ## Linux — Domain Overview
  Contains 17 sub-entities covering:
  - **backup** (ent_20260526T0902290, moderate)
  - **bash-scripting** (ent_20260526T0902289, moderate)
  - **cron** (ent_20260526T0847470, moderate)
  - **disk-management** (ent_20260526T0902283, strong)
  - **disks** (ent_20260526T0847463, moderate)
  - **fhs** (ent_20260526T0847460, moderate)
  - **firewall** (ent_20260526T0902285, moderate)
  - **logging** (ent_20260526T0847468, moderate)
  - **monitoring** (ent_20260526T0902288, moderate)
  - **network** (ent_20260526T0847464, moderate)
  - **nvidia** (ent_20260526T0847472, moderate)
  - **permissions** (ent_20260526T0847465, moderate)
  - **processes** (ent_20260526T0847461, moderate)
  - **security** (ent_20260526T0902291, moderate)
  - **shell** (ent_20260526T0847469, moderate)
  - **ssh-security** (ent_20260526T0902284, moderate)
  - **wayland-nvidia** (ent_20260526T0902286, moderate)


entity_id: domain_seedvault
type: domain_umbrella
category: seedvault
strength: strong
metadata: {}
created_at: 2026-05-26T14:15:11.117167
updated_at: 2026-05-26T14:15:11.117167
content:
  # SeedVault Market Domain

  All SeedVault Market seed products, planting guides, and related knowledge.


entity_id: seed_bulls-blood-beets
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:11.316677
updated_at: 2026-05-26T14:15:11.316677
content:
  # Bulls Blood Beets

  **Category:** Root Vegetables
  **Variety:** Open-pollinated heirloom
  **Price:** $3.12

  Deep purple open-pollinated heirloom variety. Rich, earthy flavor for roasting, salads, and juicing. Dark green leaves are edible too. Fast-maturing, versatile garden crop.

  **Germination:** 5-10 days at 50-85°F
  **Seed Viability:** 3-4 years cool/dry. Store below 40°F, 25-30% humidity.
  **Soil:** 6.0-7.0, well-drained. Add compost. Remove stones for straight roots.
  **Days to Harvest:** 50-60 days for roots, 30 days for greens

  **Pests:** Aphids, beet armyworm, leaf spots. Rotate with non-chenopods. Ensure good air circulation to prevent mildew.


entity_id: seed_butter-crunch-butterhead-lettuce
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:11.692780
updated_at: 2026-05-26T14:15:11.692780
content:
  # Butter Crunch Butterhead Lettuce

  **Category:** Leafy Greens
  **Variety:** Open-pollinated
  **Price:** $3.12

  Rosette heads averaging 4.5" diameter with dark green and reddish leaves with yellow-white centers. Good heat tolerance with soft, buttery leaves forming a compact head. Ideal for salads, quick-growin
  **Seed Viability:** 2-3 years. Seeds tiny — store in airtight containers below 40°F.
  **Soil:** 6.0-7.0, rich compost, consistent moisture.

  **Pests:** Slugs (beer traps, diatomaceous earth), aphids (blast with water), tipburn (ensure calcium, consistent watering), damping off (improve drainage).


entity_id: seed_california-wonder-sweet-pepper
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:12.056926
updated_at: 2026-05-26T14:15:12.056926
content:
  # California Wonder Sweet Pepper

  **Category:** Fruiting Vegetables
  **Variety:** Open-pollinated heirloom
  **Price:** $3.12

  Classic open-pollinated heirloom sweet pepper. Thick-walled, blocky green peppers that ripen to red. Versatile for cooking, stuffing, or fresh salads.

  **Germination:** 10-20 days at 70-85°F
  **Seed Viability:** 3-5 years cool/dry. Store below 40°F.
  **Soil:** 6.0-6.8, well-drained, rich organic matter. Warm soil critical.
  **Days to Harvest:** 60-80 days from transplant

  **Pests:** Aphids, spider mites, bacterial spot, fruit cracks (water consistency). Rotate every 3 years.


entity_id: seed_catnip-herb
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:12.426302
updated_at: 2026-05-26T14:15:12.426302
content:
  # Catnip Herb

  **Category:** Herbs
  **Variety:** Open-pollinated
  **Price:** $3.12

  Vigorous mint loved by cats. Grayish-green leaves with strong mint-like flavor. Attracts bees, may aid pollination in herb garden. May become invasive — deadhead to prevent self-sowing.

  - **Category:
  **Seed Viability:** 1-2 years. Use fresh seeds. Store cool/dry.
  **Soil:** 6.0-7.5, tolerates poor soils, drought-tolerant once established.

  **Pests:** Very pest-resistant (catmint oils repel many insects). Watch for powdery mildew in humid conditions.


entity_id: seed_chinese-elm
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:12.791546
updated_at: 2026-05-26T14:15:12.791546
content:
  # Chinese Elm (Ulmus parvifolia)

  **Category:** Tree Seeds
  **Variety:** Open-pollinated
  **Price:** $4.44

  Deciduous/semi-deciduous, highly resistant to Dutch elm disease and Elm Leaf Beetle. Attractive exfoliating bark in gray/green/orange/brown. Dark green shiny leaves turn yellowish-reddish purple in fa


entity_id: seed_coriander-cilantro
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:13.157870
updated_at: 2026-05-26T14:15:13.157870
content:
  # Coriander (Cilantro)

  **Category:** Herbs
  **Variety:** Open-pollinated
  **Price:** $3.12

  Versatile — zesty leaves (cilantro) and flavorful spice seeds (coriander) from same plant. Fast-growing annual, 12-24" tall.
  **Seed Viability:** 2-3 years cool/dry. Store below 40°F.
  **Soil:** 6.0-7.0, well-drained. Prefers cool weather.

  **Pests:** Aphids, leaf miner, powdery mildew. Bolts quickly — succession plant every 2-3 weeks for continuous harvest.


entity_id: seed_crimson-sweet-watermelon
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:13.523398
updated_at: 2026-05-26T14:15:13.523398
content:
  # Crimson Sweet Watermelon

  **Category:** Fruiting Vegetables
  **Variety:** Open-pollinated heirloom
  **Price:** $3.12

  Juicy, open-pollinated heirloom variety with deep red flesh. Sweet, seed-free watermelon for hot summer days. Southern garden favorite with high adaptability.

  **Germination:** 7-10 days at 75-85°F
  **Seed Viability:** 4-5 years cool/dry. Store below 40°F.
  **Soil:** 6.0-6.8, warm sandy loam ideal. Heavy feeder — compost.
  **Days to Harvest:** 85-90 days

  **Pests:** Aphids, cucumber beetles, powdery mildew, fusarium wilt, fruit rot (elevate fruit on boards). Rotate 3-4 years.


entity_id: seed_dark-green-zucchini-squash
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:13.887825
updated_at: 2026-05-26T14:15:13.887825
content:
  # Dark Green Zucchini Squash

  **Category:** Fruiting Vegetables
  **Variety:** Open-pollinated
  **Price:** $3.12

  Traditional reliable zucchini, similar to Black Beauty but earlier (50 days). Dark green, straight, ~8" long. Keeps producing.
  **Seed Viability:** 4-5 years cool/dry. Store below 40°F.
  **Soil:** 6.0-6.8, warm, well-drained, rich compost. Heavy feeder.

  **Pests:** Squash vine borer (wrap stems, Bt), powdery mildew (afternoon sun helps), squash bugs (trap with boards), cucumber beetles. Rotate 3 years.


entity_id: seed_heirloom-seed-starter-pack
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:14.248822
updated_at: 2026-05-26T14:15:14.248822
content:
  # Heirloom Seed Starter Pack

  Beginner-friendly starter pack of heirloom, open-pollinated seeds. $32.00 — includes 21 seed packets plus tools.


entity_id: seed_jack-o-lantern-pumpkin
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:14.612614
updated_at: 2026-05-26T14:15:14.612614
content:
  # Jack-o-Lantern Pumpkin

  **Category:** Fruiting Vegetables
  **Variety:** Open-pollinated
  **Price:** $3.12

  Classic carving pumpkin with thick skin, 8-15 lbs. Also makes great pie. Ready in ~100 days.
  **Seed Viability:** 4-5 years cool/dry. Store below 40°F.
  **Soil:** 6.0-6.8, warm, well-drained, rich compost. Heavy feeder.

  **Pests:** Squash vine borer, pumpkin beetles, powdery mildew, aphids, deer/raccoon. Use row covers early, remove for pollination.


entity_id: seed_jalapeno-peppers
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:14.972731
updated_at: 2026-05-26T14:15:14.972731
content:
  # Jalapeño Peppers

  **Category:** Fruiting Vegetables
  **Variety:** Open-pollinated heirloom
  **Price:** $3.12

  Spicy open-pollinated heirloom variety. Versatile hot peppers for fresh salsas, pickling, smoking (chipotle), and cooking.

  **Germination:** 10-20 days at 70-85°F
  **Seed Viability:** 3-5 years cool/dry. Store below 40°F.
  **Soil:** 6.0-6.8, well-drained, rich compost.
  **Days to Harvest:** 70-80 days from transplant

  **Pests:** Aphids, spider mites, blossom end rot, fruit cracks. Same management as sweet peppers.


entity_id: seed_japanese-maple
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:15.333918
updated_at: 2026-05-26T14:15:15.333918
content:
  # Japanese Maple (Acer palmatum)

  **Category:** Tree Seeds
  **Variety:** Open-pollinated
  **Price:** $4.44

  Deciduous tree to 25 ft. Stunning fall color, elegant branching. Native to Japan, Korea, China, Mongolia, Russia. Cultivated since 1800s. Prefers moist, well-drained acidic soil, partial shade. Large


entity_id: seed_large-leaf-basil
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:15.695792
updated_at: 2026-05-26T14:15:15.695792
content:
  # Large Leaf Basil

  **Category:** Herbs
  **Variety:** Open-pollinated
  **Price:** $3.12

  Largest leaves of any basil variety (2-4" long). Sweet, spicy flavor for cooking, fresh use, sauces, and dishes. Essential herb garden staple.
  **Seed Viability:** 2-4 years cool/dry. Store below 40°F.
  **Soil:** 6.0-7.0, well-draining, rich compost. Consistent moisture.

  **Pests:** Aphids, whiteflies, downy mildew (water at base, improve airflow). Avoid wet leaves.


entity_id: seed_long-island-brussels-sprouts
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:16.057935
updated_at: 2026-05-26T14:15:16.057935
content:
  # Long Island Brussels Sprouts

  **Category:** Brassicas
  **Variety:** Open-pollinated heirloom
  **Price:** $3.12

  Most common and widely adapted open-pollinated Brussels Sprout variety for home gardens. Compact heads with tender, sweet sprouts.

  **Germination:** 7-10 days at 50-85°F
  **Seed Viability:** 3-4 years cool/dry. Store below 40°F.
  **Soil:** 6.0-7.5, well-drained, rich compost. Heavy feeder. Long season.
  **Days to Harvest:** 90-110 days from transplant

  **Pests:** Cabbage worms (Bt, row covers), cabbage loopers, flea beetles, clubroot (raise pH, rotate 4 years), aphids.


entity_id: seed_luffa-sponge-gourd
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:16.420817
updated_at: 2026-05-26T14:15:16.420817
content:
  # Luffa Sponge Gourd

  **Category:** Fruiting Vegetables
  **Variety:** Open-pollinated
  **Price:** $3.12

  Grow your own biodegradable sponges. Vigorous vine producing fibrous gourds — peel skin after curing to reveal sponge. Also called Vegetable Sponge or Dishcloth Gourd.
  **Seed Viability:** 3-5 years cool/dry. Store below 40°F.
  **Soil:** 6.0-7.0, well-drained, warm. Moderate feeder.

  **Pests:** Powdery mildew, cucumber beetles, squash bugs. Same family as squash — similar management.


entity_id: seed_parsley
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:16.783521
updated_at: 2026-05-26T14:15:16.783521
content:
  # Parsley

  **Category:** Herbs
  **Variety:** Open-pollinated
  **Price:** $3.12

  Flat leaf parsley — versatile herb for cooking, salads, and garnishes. Slow germination but hardy once established.

  **Germination:** 6-14 days at 70-80°F
  **Seed Viability:** 2-3 years. Hard seed coat slows germination.
  **Soil:** 6.0-7.0, well-drained. Tolerates partial shade.
  **Days to Harvest:** 70-80 days from transplant

  **Pests:** Aphids, parsley webworm, leaf spot. Ensure good drainage and air circulation.


entity_id: seed_pickling-cucumber
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:17.145787
updated_at: 2026-05-26T14:15:17.145787
content:
  # Pickling Cucumber

  **Category:** Fruiting Vegetables
  **Variety:** Open-pollinated
  **Price:** $3.12

  Heavy, continuous yields of 3" and 6" fruits perfect for pickling. Dark green, blunt-ended cucumbers.
  **Seed Viability:** 3-5 years cool/dry. Store below 40°F.
  **Soil:** 5.5-6.8, well-drained, rich organic matter. Warm soil.

  **Pests:** Cucumber beetles (row covers, diatomaceous earth), powdery mildew (resistant varieties, airflow), downy mildew, aphids. Rotate cucurbits 3 years.


entity_id: seed_provider-green-bush-beans
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:17.509600
updated_at: 2026-05-26T14:15:17.509600
content:
  # Provider Green Bush Beans

  **Category:** Legumes
  **Variety:** Open-pollinated
  **Price:** $3.12

  Reliable heirloom green beans. 6" straight green pods with purple seeds. Excellent disease resistance, grows well in various conditions.
  **Seed Viability:** 2-3 years. Viability drops after year 2. Store cool/dry.
  **Soil:** 6.0-6.8, well-drained. Fix own nitrogen — don't fertilize heavily.

  **Pests:** Bean beetles, aphids, powdery mildew, bacterial blight (avoid overhead watering). Rotate every 2-3 years.


entity_id: seed_red-cedar
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:17.873499
updated_at: 2026-05-26T14:15:17.873499
content:
  # Red Cedar (Juniperus virginiana)

  **Category:** Tree Seeds
  **Variety:** Open-pollinated
  **Price:** $4.44

  Eastern Red Cedar — slow-growing evergreen, up to 27m. Reddish-brown fibrous bark, dark green foliage. Important winter food for birds. Famous for fragrant, decay-resistant wood (chests, closets, fenc


entity_id: seed_red-russian-kale
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:18.240626
updated_at: 2026-05-26T14:15:18.240626
content:
  # Red Russian Kale

  **Category:** Leafy Greens
  **Variety:** Open-pollinated
  **Price:** $3.12

  Deep gray-green leaves with purple veins, tenderer than other kale types with mild sweet flavor. Vigorous plants, one of the best kale varieties for beginner gardeners.
  **Seed Viability:** 3-5 years cool/dry. Store below 40°F.
  **Soil:** 6.0-7.5, well-drained. Tolerates heavy soils.

  **Pests:** Cabbage worms (Bt spray), aphids, flea beetles, whiteflies. Sweetens after frost. Rotate brassicas 3 years.


entity_id: seed_roma-tomatoes
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:18.604847
updated_at: 2026-05-26T14:15:18.604847
content:
  # Roma Tomatoes

  **Category:** Fruiting Vegetables
  **Variety:** Open-pollinated heirloom
  **Price:** $3.12

  Open-pollinated heirloom paste tomato. Firm, meaty fruits with few seeds — perfect for sauces, canning, drying & salsa. Disease resistant, heavy producer.

  **Germination:** 6-14 days at 70-80°F
  **Seed Viability:** 4-6 years. One of the most stable vegetable seeds. Store cool/dry.
  **Soil:** 6.0-6.8, rich, well-drained. Heavy feeder — compost and balanced fertilizer.
  **Days to Harvest:** 70-80 days from transplant

  **Pests:** Hornworms (hand-pick, Bt), early/late blight (crop rotation, avoid overhead watering), blossom end rot (calcium deficiency), cracks (consistent watering). Rotate 3 years.


entity_id: seed_scarlett-nantes-carrot
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:18.969819
updated_at: 2026-05-26T14:15:18.969819
content:
  # Scarlett Nantes Carrot

  **Category:** Root Vegetables
  **Variety:** Open-pollinated
  **Price:** $3.12

  Sweet, 6-7 inch cylindrical carrots with crisp texture and no woody cores. Loose-rooted for easy harvesting. Perfect for fresh eating, juicing, or cooking.
  **Seed Viability:** 3-4 years stored cool/dry. Store below 40°F, 25-30% humidity.
  **Soil:** 6.0-6.8, loose sandy loam ideal. Avoid heavy clay.

  **Pests:** Carrot root fly (interplant with onions/rosemary), foliage fleck (downy mildew), slimy root rot (improve drainage). Rotate every 3 years.


entity_id: seed_snowball-turnips
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:19.337930
updated_at: 2026-05-26T14:15:19.337930
content:
  # Snowball Turnips

  **Category:** Root Vegetables
  **Variety:** Open-pollinated
  **Price:** $3.12

  Round, white-fleshed turnips for bunching. Crisp, tender, sweet flesh. Fast-growing cool-season crop, popular in southern areas.
  **Seed Viability:** 3-4 years cool/dry. Store below 40°F.
  **Soil:** 6.0-7.5, well-drained. Tolerates poorer soils than most root vegetables.

  **Pests:** Flea beetles (use row covers), cabbage worms, clubroot (raise pH above 6.5). Rotate brassicas every 3 years.


entity_id: seed_southern-yew
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:19.703025
updated_at: 2026-05-26T14:15:19.703025
content:
  # Southern Yew (Podocarpus macrophyllus)

  **Category:** Tree Seeds
  **Variety:** Open-pollinated
  **Price:** $4.44

  Evergreen conifer to 60 ft. Strap-shaped leaves 6-12 cm. Berry-like cones turn reddish-purple, eaten by birds. Native to S. Japan and China. Popular bonsai. Termite and water resistant wood. State tre


entity_id: seed_sugar-beets
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:20.069862
updated_at: 2026-05-26T14:15:20.069862
content:
  # Sugar Beets

  **Category:** Root Vegetables
  **Variety:** Open-pollinated
  **Price:** $3.12

  Robust OP variety prized for high sugar content and versatility. Large white-fleshed roots, 2-3 pounds, sweet earthy flavor. Ideal for home gardens, sugar production, or livestock feed.

  - **Category:
  **Seed Viability:** 3-4 years cool/dry. Store below 40°F.
  **Soil:** 6.0-7.0, well-drained, stone-free. Consistent moisture for tender roots.

  **Pests:** Aphids, beet armyworm, leaf spots. Rotate with non-chenopods every 2 years.


entity_id: seed_sugar-lace-snap-peas
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:20.439800
updated_at: 2026-05-26T14:15:20.439800
content:
  # Sugar Lace Snap Peas

  **Category:** Legumes
  **Variety:** Semi-leafless, open-pollinated
  **Price:** $3.12

  Sweet, crunchy open-pollinated heirloom snap peas. Eat the whole pod raw or cooked! Cool-season favorite, climbs well on trellises.

  **Germination:** 7-14 days at 40-75°F
  **Seed Viability:** 2-4 years. Store cool/dry below 40°F.
  **Soil:** 6.0-7.0, well-drained. Add nitrogen-fixing compost.
  **Days to Harvest:** 50-60 days

  **Pests:** Pea aphids (wash off, attract ladybugs), powdery mildew (space for airflow), mice (bury baits at planting). Rotate with non-legumes.


entity_id: seed_utah-celery
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:20.807332
updated_at: 2026-05-26T14:15:20.807332
content:
  # Utah Celery

  **Category:** Leafy Greens
  **Variety:** Open-pollinated
  **Price:** $3.12

  Classic OP celery, 18-24" tall. Crisp tender stalks with slightly nutty taste. Requires long growing season.
  **Seed Viability:** 1-2 years. Use fresh seeds. Store cool/dry.
  **Soil:** 6.0-7.5, rich, moisture-retentive. Heavy feeder.

  **Pests:** Celery leaf spot, aphids, carrot root fly (related family). Consistent watering critical. Raised beds for drainage.


entity_id: seed_white-bunching-onion
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:21.176910
updated_at: 2026-05-26T14:15:21.176910
content:
  # White Bunching Onion

  **Category:** Onions
  **Variety:** Open-pollinated
  **Price:** $3.12

  Bulbless variety producing flavorful leek-like stalks. Hardy, overwinters for spring bunching. Use for green bunching and scallions.
  **Seed Viability:** 3-4 years cool/dry. Store below 40°F.
  **Soil:** 6.0-7.0, well-drained. Tolerates partial shade.

  **Pests:** Onion thrips, onion maggot, downy mildew, pink root. Rotate every 3 years, avoid replanting where alliums grew.


entity_id: seed_yellow-dent-corn
type: seed_product
category: seedvault
strength: moderate
metadata: {}
created_at: 2026-05-26T14:15:21.544615
updated_at: 2026-05-26T14:15:21.544615
content:
  # Yellow Dent Corn

  **Category:** Zea Mays
  **Variety:** Open-pollinated
  **Price:** $3.12

  Classic heirloom field corn. High yields, drought tolerant. Versatile for cornmeal, flour, animal feed, silage. Grows 8-12 feet, 9" ears.
  **Seed Viability:** 1-2 years. Use fresh seeds for best germination. Store cool/dry.
  **Soil:** 5.8-7.0, well-drained, rich organic matter. Heavy feeder.

  **Pests:** Corn earworm (Bt, pheromone traps), corn borers, cutworms, birds (netting at silk stage). Rotate with non-grasses.


entity_id: ent_20260526T182106953736_c33ec789
type: memory
category: debian/shell-scripting
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:06.953736
updated_at: 2026-05-26T18:21:06.953736
content:
  ## Debian Shell Scripting & Automation
  ### Bash Fundamentals
  - **Shebang:** `#!/bin/bash` or `#!/usr/bin/env bash`
  - **Variables:** `NAME="value"`, access with `$NAME` or `${NAME}`
  - **Conditionals:** `if [ condition ]; then`, `elif`, `fi`
  - **Loops:** `for i in list`, `while [ condition ]`, `until`

  ### Script Patterns
  - **Error handling:** `set -euo pipefail` (exit on error, undefined vars, pipe failures)
  - **Logging:** `echo "$(date '+%Y-%m-%d %H:%M:%S') - message" >> /var/log/script.log`
  - **User input:** `read -p "Prompt: " variable`
  - **Argument parsing:** `$1`, `$2`, or `getopts` for flags

  ### Useful Built-ins
  - `$(command)` — command substitution
  - `${var:-default}` — default value
  - `${var#pattern}` — remove prefix match
  - `${var%pattern}` — remove suffix match
  - `$?` — last command exit code
  - `$$` — current process PID

  ### Script Locations
  - `/usr/local/bin/` — custom scripts (recommended)
  - `~/bin/` — user scripts (add to PATH)
  - `/etc/profile.d/` — system-wide shell init scripts
  - `/usr/local/sbin/` — admin scripts

  ### Automation Patterns
  - **Cron jobs:** `crontab -e` for scheduling
  - **systemd timers:** More reliable than cron for complex tasks
  - **Watchdog:** Monitor processes with `systemd` or custom scripts


entity_id: ent_20260526T182107156722_5e1cf5de
type: memory
category: debian/networking
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:07.156722
updated_at: 2026-05-26T18:21:07.156722
content:
  ## Debian Networking Tools & Configuration
  ### NetworkManager (Default on Debian)
  - **Status:** `nmcli general status`
  - **Devices:** `nmcli device status`
  - **Connections:** `nmcli connection show`
  - **Wi-Fi scan:** `nmcli dev wifi`
  - **Connect:** `nmcli con up id "connection_name"`

  ### Command Line Tools
  - **ping** — connectivity test
  - **curl** — HTTP requests
  - **wget** — file downloads
  - **ssh** — remote access
  - **scp** — file transfer
  - **rsync** — incremental sync
  - **netcat (nc)** — network debugging
  - **dig** — DNS queries
  - **traceroute** — path tracing

  ### Network Configuration
  - **Interface config:** `/etc/network/interfaces` (legacy) or NetworkManager profiles
  - **DNS:** `/etc/resolv.conf` (managed by NetworkManager)
  - **Hostnames:** `/etc/hostname` and `/etc/hosts`
  - **IP addresses:** `ip addr show` (replaces ifconfig)
  - **Routing:** `ip route show`

  ### Firewall (nftables)
  - **View rules:** `sudo nft list ruleset`
  - **Add rule:** `sudo nft add rule inet filter input tcp dport 80 accept`
  - **Service:** `systemctl status nftables`

  ### Network Monitoring
  - **ss** — socket statistics (replaces netstat)
  - **iftop** — real-time bandwidth by connection
  - **nethogs** — bandwidth by process
  - **tcpdump** — packet capture
  - **Wireshark** — GUI packet analyzer

  ### VPN & Remote Access
  - **OpenVPN:** `apt install openvpn`
  - **WireGuard:** `apt install wireguard`
  - **SSH tunneling:** `ssh -L local_port:remote:remote_port user@host`


entity_id: ent_20260526T182107349860_302e57a7
type: memory
category: debian/development
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:07.349860
updated_at: 2026-05-26T18:21:07.349860
content:
  ## Debian Development Environment Setup
  ### Python
  - **Install:** `apt install python3 python3-pip python3-venv`
  - **Virtual env:** `python3 -m venv myenv && source myenv/bin/activate`
  - **Packages:** `pip install package_name`
  - **System Python:** Don't mix apt and pip packages for system Python

  ### Node.js
  - **Install:** `apt install nodejs npm` or use NodeSource repo
  - **Version manager:** `nvm` (Node Version Manager)
  - **Global packages:** `npm install -g package`

  ### Git
  - **Install:** `apt install git`
  - **Config:** `git config --global user.name "Name"`, `git config --global user.email "email"`
  - **SSH keys:** `ssh-keygen -t ed25519`, add to `~/.ssh/config`
  - **Hooks:** `~/.gitconfig` for global settings

  ### Docker
  - **Install:** Follow Docker's official Debian instructions
  - **Service:** `systemctl status docker`
  - **Non-root access:** `sudo usermod -aG docker $USER`

  ### IDEs & Editors
  - **VS Code:** Download from code.visualstudio.com
  - **Neovim:** `apt install neovim`
  - **Vim:** `apt install vim`

  ### Build Tools
  - **gcc/g++:** `apt install build-essential`
  - **make:** `apt install make`
  - **cmake:** `apt install cmake`
  - **pkg-config:** `apt install pkg-config`

  ### Debugging
  - **gdb:** `apt install gdb`
  - **strace:** `apt install strace` (system call tracing)
  - **valgrind:** `apt install valgrind` (memory debugging)
  - **ltrace:** `apt install ltrace` (library call tracing)


entity_id: ent_20260526T182107546180_af5d1751
type: memory
category: debian/sysadmin
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:07.546180
updated_at: 2026-05-26T18:21:07.546180
content:
  ## Debian System Administration
  ### User Management
  - **Create user:** `sudo adduser username` (interactive) or `sudo useradd -m username`
  - **Set password:** `sudo passwd username`
  - **Add to group:** `sudo usermod -aG groupname username`
  - **Groups:** `/etc/group`
  - **Sudo access:** Add to `sudo` group

  ### Service Management (systemd)
  - **Status:** `systemctl status service_name`
  - **Enable/disable:** `systemctl enable|disable service_name`
  - **Start/stop:** `systemctl start|stop service_name`
  - **Logs:** `journalctl -u service_name -f`

  ### Log Management
  - **journalctl:** `journalctl` (all logs), `-u unit` (specific service), `-f` (follow), `-n 100` (last 100)
  - **Log files:** `/var/log/`
  - **Syslog:** `/var/log/syslog` (general), `/var/log/auth.log` (auth)
  - **Rotate logs:** `logrotate` config in `/etc/logrotate.d/`

  ### Disk Management
  - **Usage:** `df -h` (filesystems), `du -sh /path` (directory sizes)
  - **Partitions:** `lsblk`, `fdisk -l`, `parted -l`
  - **Mount:** `/etc/fstab` for persistent mounts
  - **LVM:** `vgdisplay`, `lvdisplay`, `lvextend`

  ### Backup Strategies
  - **tar:** `tar -czvf backup.tar.gz /path/to/backup`
  - **rsync:** `rsync -avz /source/ user@remote:/dest/`
  - **cron backups:** Schedule with `crontab -e`
  - **Versioned backups:** `cp -a source dest_$(date +%Y%m%d)`

  ### Process Management
  - **Top:** `top` (interactive), `htop` (better)
  - **Kill:** `kill PID`, `kill -9 PID` (force)
  - **Background:** `command &` or `nohup command &`
  - **Priority:** `nice -n priority command`, `renice`

  ### Resource Monitoring
  - **CPU:** `top`, `mpstat` (from sysstat)
  - **Memory:** `free -h`, `vmstat`
  - **I/O:** `iostat` (from sysstat)
  - **Network:** `ifstat`, `sar -n DEV`


entity_id: ent_20260526T182107742712_8f59f767
type: memory
category: debian/security
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:07.742712
updated_at: 2026-05-26T18:21:07.742712
content:
  ## Debian Security Hardening
  ### System Updates
  - **Security updates:** `apt list --upgradable` (check for security patches)
  - **Unattended upgrades:** `apt install unattended-upgrades`
  - **Enable:** `/etc/apt/apt.conf.d/20auto-upgrades`

  ### SSH Hardening
  - **Disable password auth:** `PasswordAuthentication no` in `/etc/ssh/sshd_config`
  - **Change port:** `Port 2222` (non-standard)
  - **Disable root login:** `PermitRootLogin no`
  - **Use keys:** `ssh-keygen -t ed25519`

  ### Firewall
  - **nftables:** Default on Debian 13
  - **Basic rules:** Allow SSH, HTTP/HTTPS, block rest
  - **Persist:** `/etc/nftables.conf`

  ### File Permissions
  - **Ownership:** `chown user:group file`
  - **Permissions:** `chmod 755 dir`, `chmod 600 sensitive_file`
  - **SUID/SGID:** Audit with `find / -perm -4000 -o -perm -2000`

  ### Security Tools
  - **fail2ban:** `apt install fail2ban` (brute force protection)
  - **auditd:** System call auditing
  - **apparmor:** Mandatory access control
  - **clamav:** Antivirus scanning

  ### Monitoring
  - **auth.log:** `/var/log/auth.log` (authentication attempts)
  - **logwatch:** Daily security summary
  - **osquery:** Endpoint security monitoring

  ### Backup Security
  - **Encrypt backups:** `gpg -c backup.tar.gz`
  - **Off-site storage:** External drive or cloud
  - **Test restores:** Regularly verify backup integrity


entity_id: ent_20260526T182107934596_2d495605
type: memory
category: debian/apt-advanced
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:07.934596
updated_at: 2026-05-26T18:21:07.934596
content:
  ## Debian apt Advanced Usage
  ### Package Search
  - **Search:** `apt search keyword`
  - **Show info:** `apt show package_name`
  - **List installed:** `apt list --installed`
  - **Find package for file:** `apt-file search filename`

  ### Package Management
  - **Install:** `apt install package`
  - **Remove:** `apt remove package` (keeps config), `apt purge package` (removes config)
  - **Clean:** `apt autoremove` (orphans), `apt clean` (cache)
  - **Downgrade:** `apt install package=version`

  ### Repository Management
  - **Sources:** `/etc/apt/sources.list` and `/etc/apt/sources.list.d/`
  - **Add repo:** `echo "deb http://repo/ubuntu jammy main" >> /etc/apt/sources.list.d/custom.list`
  - **GPG keys:** `wget -qO- https://keyserver.keyserver.io:443/KEY_ID | gpg --dearmor -o /usr/share/keyrings/repo-keyring.gpg`

  ### Building Packages
  - **Dependencies:** `apt build-dep package`
  - **Source:** `apt source package`
  - **Local .deb:** `dpkg -i package.deb`

  ### Troubleshooting
  - **Broken packages:** `apt --fix-broken install`
  - **Configuration conflicts:** `dpkg --configure -a`
  - **Hold version:** `apt-mark hold package` (prevent upgrade)
  - **Pin version:** `/etc/apt/preferences.d/`

  ### apt vs apt-get
  - **apt:** User-friendly, progress bar, shows upgrades
  - **apt-get:** Script-friendly, stable output, recommended for scripts
  - **apt-cache:** Search and info (replaces apt-cache)


entity_id: ent_20260526T182108128939_8de221bc
type: memory
category: debian/filesystems
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:08.128939
updated_at: 2026-05-26T18:21:08.128939
content:
  ## Debian File System Management
  ### Common File Systems
  - **ext4:** Default Linux filesystem, journaling, good performance
  - **btrfs:** Copy-on-write, snapshots, compression (zstd)
  - **xfs:** High performance, good for large files
  - **FAT32/NTFS:** Windows compatibility

  ### File System Commands
  - **Check usage:** `df -h` (human readable), `df -T` (show type)
  - **Mount:** `mount /dev/sdXN /mount/point`
  - **Unmount:** `umount /mount/point`
  - **Persistent mount:** `/etc/fstab` entries

  ### btrfs Features (if used)
  - **Snapshots:** `btrfs subvolume snapshot /src /dest`
  - **Compression:** `mount -o compress=zstd`
  - **Balance:** `btrfs balance start /mount` (reclaim space)
  - **Scrubs:** `btrfs scrub start /mount` (data integrity)

  ### Disk Encryption
  - **LUKS:** `cryptsetup luksFormat /dev/sdX`
  - **Open:** `cryptsetup open /dev/sdX name`
  - **Mount:** `mount /dev/mapper/name /mount`

  ### Backup File Systems
  - **ZFS:** Enterprise features, snapshots, RAID-Z
  - **LVM:** Logical volume management
  - **mdadm:** Software RAID

  ### File Operations
  - **Find files:** `find /path -name "pattern"`
  - **Search content:** `grep -r "pattern" /path`
  - **Large files:** `find / -type f -size +100M`
  - **Old files:** `find /path -mtime +30` (older than 30 days)


entity_id: ent_20260526T182108321511_88e29baf
type: memory
category: debian/cron
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:08.321511
updated_at: 2026-05-26T18:21:08.321511
content:
  ## Debian Cron & Task Scheduling
  ### Cron Syntax
  - **Format:** `minute hour day month weekday command`
  - **Examples:**
    - `0 * * * *` — every hour
    - `*/5 * * * *` — every 5 minutes
    - `0 2 * * *` — 2 AM daily
    - `0 0 * * 0` — midnight Sunday

  ### Managing Cron Jobs
  - **Edit user crontab:** `crontab -e`
  - **List crontab:** `crontab -l`
  - **Remove:** `crontab -r`
  - **System crons:** `/etc/cron.d/`, `/etc/cron.daily/`, etc.

  ### Best Practices
  - **Use absolute paths:** Commands in cron don't have user PATH
  - **Redirect output:** `command > /var/log/cron.log 2>&1`
  - **Environment:** Set variables at top or use wrapper script
  - **Testing:** Run command manually first

  ### Alternatives
  - **systemd timers:** More reliable, better logging
  - **at:** One-time scheduling (`at now + 1 hour`)
  - **systemd oneshot:** Run once on boot

  ### Cron Log
  - **View:** `grep CRON /var/log/syslog`
  - **Enable logging:** Check `/etc/rsyslog.d/50-default.conf`


entity_id: ent_20260526T182108516472_5fcb6be3
type: memory
category: debian/performance
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:08.516472
updated_at: 2026-05-26T18:21:08.516472
content:
  ## Debian Performance Tuning
  ### CPU
  - **Governor:** `cpupower frequency-set -g performance|powersave`
  - **C-states:** `/sys/devices/system/cpu/cpu*/cpuidle/`
  - **Monitor:** `mpstat -P ALL 1` (per-core stats)

  ### Memory
  - **Swap:** `fallocate -l 4G /swapfile && mkswap /swapfile && swapon /swapfile`
  - **ZRAM:** Compressed RAM swap (good for low-memory systems)
  - **Monitor:** `free -h`, `vmstat 1`

  ### I/O
  - **Scheduler:** `/sys/block/sda/queue/scheduler` (mq-deadline, bfq)
  - **Read-ahead:** `blockdev --setra 256 /dev/sda`
  - **Monitor:** `iostat -x 1`

  ### Network
  - **Buffer sizes:** `/proc/sys/net/core/rmem_max`, `wmem_max`
  - **TCP tuning:** `/etc/sysctl.d/99-tcp-tuning.conf`
  - **DNS:** `/etc/resolv.conf`, `systemd-resolve`

  ### System-wide
  - **sysctl:** Runtime kernel parameters (`sysctl -a` to list)
  - **Persistent:** `/etc/sysctl.d/` files
  - **ulimit:** `ulimit -n 65535` (open files)
  - **Persistent ulimit:** `/etc/security/limits.conf`

  ### Profiling Tools
  - **perf:** `perf record -g command` (CPU profiling)
  - **sysstat:** `sar`, `iostat`, `mpstat` (historical data)
  - **htop:** `apt install htop` (interactive process viewer)
  - **iotop:** `apt install iotop` (I/O by process)


entity_id: ent_20260526T182108708808_18e8c302
type: memory
category: debian/containers
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:08.708808
updated_at: 2026-05-26T18:21:08.708808
content:
  ## Debian Container Management
  ### Docker
  - **Install:** Official Docker repo (not apt version)
  - **Service:** `systemctl status docker`
  - **Non-root:** `sudo usermod -aG docker $USER` (logout/login)

  ### Podman
  - **Alternative:** Rootless containers
  - **Install:** `apt install podman`
  - **Commands:** Same as docker (drop-in replacement)

  ### Container Orchestration
  - **Docker Compose:** `docker-compose up -d`
  - **Kubernetes:** Minikube (local), k3s (lightweight)
  - **Podman compose:** `podman-compose`

  ### Image Management
  - **Build:** `docker build -t image:tag .`
  - **Run:** `docker run -d --name container image`
  - **Exec:** `docker exec -it container bash`
  - **Logs:** `docker logs container`
  - **Remove:** `docker rm -f container`, `docker rmi image`

  ### Volumes & Storage
  - **Named volume:** `-v name:/path`
  - **Bind mount:** `-v /host/path:/container/path`
  - **Persist data:** `docker volume create name`

  ### Networking
  - **Bridge:** Default networking mode
  - **Host:** `--network host` (share host network)
  - **Custom:** `docker network create name`

  ### Security
  - **Non-root:** Run containers as non-root user
  - **Read-only:** `--read-only` flag
  - **Resource limits:** `--memory`, `--cpus`


entity_id: ent_20260526T182108902473_98ed324d
type: memory
category: debian/monitoring
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:08.902473
updated_at: 2026-05-26T18:21:08.902473
content:
  ## Debian System Monitoring
  ### Built-in Tools
  - **top/htop:** Process monitoring
  - **vmstat:** Virtual memory stats
  - **iostat:** Disk I/O stats
  - **netstat/ss:** Network connections
  - **free:** Memory usage
  - **df/du:** Disk usage
  - **uptime/loadavg:** System load

  ### Logging
  - **journalctl:** systemd log viewer
  - **rsyslog:** Centralized logging daemon
  - **Log rotation:** `/etc/logrotate.d/`

  ### Monitoring Daemons
  - **prometheus-node-exporter:** Metrics collection
  - **netdata:** Real-time monitoring dashboard
  - **glances:** Cross-platform system monitor
  - **zabbix-agent:** Enterprise monitoring

  ### Alerting
  - **mailx:** `apt install bsd-mailx` (email alerts)
  - **telegram-bot:** Custom webhook notifications
  - **PagerDuty/OpsGenie:** Enterprise alerting

  ### Performance History
  - **sysstat:** Collects historical performance data
  - **sar:** System Activity Reporter (part of sysstat)
  - **Data retention:** Configurable in `/etc/default/sysstat`

  ### Health Checks
  - **Disk SMART:** `smartctl -a /dev/sda` (drive health)
  - **Temperature:** `sensors` (lm-sensors package)
  - **Uptime:** `uptime` or `last reboot`


entity_id: ent_20260526T182109096409_9453624e
type: memory
category: debian/backup
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:09.096409
updated_at: 2026-05-26T18:21:09.096409
content:
  ## Debian Backup & Recovery
  ### Backup Strategies
  - **3-2-1 Rule:** 3 copies, 2 media types, 1 off-site
  - **Full vs incremental:** Balance speed vs complexity
  - **Testing:** Regularly verify backup integrity

  ### Backup Tools
  - **tar:** `tar -czvf backup.tar.gz /path`
  - **rsync:** `rsync -avz /source/ /dest/` (incremental)
  - **borg:** `borg init --encryption=repokey repo` (deduplication)
  - **restic:** `restic init` (cloud-friendly)
  - **duplicity:** GnuPG encrypted backups

  ### Cron Backups
  - **Daily:** `0 2 * * * /usr/local/bin/backup.sh`
  - **Weekly:** `0 3 * * 0 /usr/local/bin/weekly_backup.sh`
  - **Monthly:** `0 4 1 * * /usr/local/bin/monthly_backup.sh`

  ### Recovery
  - **Test restore:** Regular dry-runs
  - **Documentation:** Record backup locations and procedures
  - **Offline backups:** Air-gapped copies for ransomware protection

  ### Database Backups
  - **MariaDB:** `mariadb-dump --all-databases > backup.sql`
  - **PostgreSQL:** `pg_dump database > backup.sql`
  - **Automated:** Cron jobs with rotation

  ### Off-site Storage
  - **External drives:** USB backup
  - **Cloud:** rclone to S3, Google Drive, etc.
  - **rsync to remote:** `rsync -avz /local/ user@remote:/backup/`


entity_id: ent_20260526T182109288858_14d36924
type: memory
category: debian/local-services
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:09.288858
updated_at: 2026-05-26T18:21:09.288858
content:
  ## Debian Local Services Setup
  ### Web Servers
  - **Apache:** `apt install apache2` (default web server)
  - **Nginx:** `apt install nginx` (reverse proxy, static)
  - **Lighttpd:** Lightweight alternative

  ### Databases
  - **MariaDB:** `apt install mariadb-server`
  - **PostgreSQL:** `apt install postgresql`
  - **SQLite:** Built-in, no server needed
  - **Redis:** `apt install redis-server` (cache, queue)

  ### Application Servers
  - **Gunicorn:** `pip install gunicorn` (Python WSGI)
  - **uWSGI:** `apt install uwsgi` (Python/Python)
  - **Daphne:** ASGI for async Python
  - **Flask/Django:** Python web frameworks

  ### File Sharing
  - **Samba:** `apt install samba` (Windows file sharing)
  - **NFS:** `apt install nfs-kernel-server` (Linux file sharing)
  - **SSHFS:** `apt install sshfs` (mount remote over SSH)

  ### Media Servers
  - **Jellyfin:** Self-hosted media server
  - **Plex:** `apt install plexmediaserver`
  - **Emby:** Alternative media server

  ### Development Services
  - **MySQL/MariaDB:** Local database dev
  - **Redis:** Local cache/queue
  - **Memcached:** `apt install memcached`
  - **RabbitMQ:** Message broker

  ### Service Management
  - **systemd:** `systemctl enable|start|stop service`
  - **Auto-start:** `systemctl enable service`
  - **Logs:** `journalctl -u service -f`


entity_id: ent_20260526T182109482983_caea15b0
type: memory
category: debian/git
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:09.482983
updated_at: 2026-05-26T18:21:09.482983
content:
  ## Debian Git & Version Control
  ### Installation & Setup
  - **Install:** `apt install git`
  - **Config:** `git config --global user.name "Name"`
  - **Editor:** `git config --global core.editor vim`
  - **Aliases:** `git config --global alias.co checkout`

  ### SSH Keys
  - **Generate:** `ssh-keygen -t ed25519 -C "email@example.com"`
  - **Add to agent:** `ssh-add ~/.ssh/id_ed25519`
  - **GitHub/GitLab:** `cat ~/.ssh/id_ed25519.pub`

  ### Common Workflows
  - **Clone:** `git clone url`
  - **Status:** `git status`
  - **Add:** `git add .`, `git add file`
  - **Commit:** `git commit -m "message"`
  - **Push:** `git push origin branch`
  - **Pull:** `git pull origin branch`

  ### Branch Management
  - **Create:** `git checkout -b new-branch`
  - **Switch:** `git checkout branch`
  - **Merge:** `git merge branch`
  - **Delete:** `git branch -d branch`

  ### History & Diff
  - **Log:** `git log --oneline --graph`
  - **Diff:** `git diff`, `git diff --staged`
  - **Stash:** `git stash` (save changes), `git stash pop` (restore)
  - **Reset:** `git reset HEAD~1` (undo last commit)

  ### Git Hooks
  - **Pre-commit:** Run before commit
  - **Post-commit:** Run after commit
  - **Location:** `.git/hooks/` directory


entity_id: ent_20260526T182109678751_778f43a4
type: memory
category: debian/ai-ml
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:09.678751
updated_at: 2026-05-26T18:21:09.678751
content:
  ## Debian AI & Machine Learning Setup
  ### Python ML Stack
  - **Core:** `pip install numpy pandas matplotlib`
  - **ML:** `pip install scikit-learn`
  - **Deep Learning:** `pip install torch tensorflow`
  - **NLP:** `pip install transformers nltk`

  ### LLM Inference
  - **llama.cpp:** Local LLM inference (CPU/GPU)
  - **Ollama:** `curl -fsSL https://ollama.ai/install.sh | sh`
  - **vLLM:** High-throughput serving
  - **Text Generation WebUI:** Gradio-based interface

  ### Development Tools
  - **Jupyter:** `pip install jupyterlab`
  - **VS Code:** With Python extensions
  - **PyCharm:** `apt install pycharm-community`

  ### GPU Acceleration
  - **NVIDIA drivers:** `apt install nvidia-driver`
  - **CUDA:** `apt install nvidia-cuda-toolkit`
  - **cuDNN:** Deep learning library
  - **ROCm:** AMD GPU support

  ### Model Management
  - **Hugging Face:** `pip install huggingface-hub`
  - **Model download:** `huggingface-cli download model`
  - **Quantization:** GPTQ, AWQ, bitsandbytes

  ### Monitoring
  - **GPU:** `nvidia-smi`, `nvtop`
  - **Memory:** `free -h`, `vmstat`
  - **Temperature:** `sensors` (lm-sensors)


entity_id: ent_20260526T182109872153_0691eced
type: memory
category: debian/ssh
strength: moderate
metadata: "{\"source\": \"debian_knowledge_ingest\"}"
created_at: 2026-05-26T18:21:09.872153
updated_at: 2026-05-26T18:21:09.872153
content:
  ## Debian SSH & Remote Access
  ### SSH Server Setup
  - **Install:** `apt install openssh-server`
  - **Service:** `systemctl enable ssh && systemctl start ssh`
  - **Config:** `/etc/ssh/sshd_config`

  ### SSH Client
  - **Connect:** `ssh user@host`
  - **Port:** `ssh -p 2222 user@host`
  - **Key auth:** `ssh -i keyfile user@host`
  - **Tunneling:** `ssh -L local:remote:remote_port user@host`

  ### Security
  - **Disable password:** `PasswordAuthentication no`
  - **Change port:** `Port 2222`
  - **Disable root:** `PermitRootLogin no`
  - **Use keys:** `ssh-keygen -t ed25519`

  ### SSH Config
  - **Location:** `~/.ssh/config`
  - **Aliases:** `Host alias
    HostName host
    User user`
  - **Forwarding:** `ForwardAgent yes`, `ForwardX11 yes`

  ### File Transfer
  - **scp:** `scp file user@host:/path`
  - **rsync:** `rsync -avz /local/ user@host:/remote/`
  - **sftp:** Interactive file transfer

  ### Remote Desktop
  - **VNC:** `apt install tigervnc-standalone-server`
  - **Xrdp:** `apt install xrdp` (RDP server)
  - **NoMachine:** `apt install nomachine`


entity_id: ent_20260526T182935369948_27d33e60
type: memory
category: debian/net-interfaces
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:35.369948
updated_at: 2026-05-26T18:29:35.369948
content:
  ## Debian Network Interface Configuration
  ### Interface Types
  - **Physical:** eth0, enp0s3, ens192 (kernel naming)
  - **Virtual:** docker0, veth*, tap*, tun*
  - **Wireless:** wlan0, wlp2s0
  - **Bonding:** bond0, bond1
  - **Bridge:** br0, br1

  ### NetworkManager (Debian Default)
  ```bash
  # List devices
  nmcli device status

  # List connections
  nmcli connection show

  # Create wired connection
  nmcli connection add type ethernet ifname eth0 con-name eth0-static
  nmcli connection modify eth0-static   ipv4.addresses 192.168.1.100/24   ipv4.gateway 192.168.1.1   ipv4.dns "8.8.8.8,8.8.4.4"   ipv4.method manual

  # Create wireless connection
  nmcli connection add type wifi ifname wlan0 con-name wifi-home   wifi.ssid HomeNetwork   wifi-sec.key-wpa "password"

  # Clone connection
  nmcli connection clone uuid UUID_NAME new-name new-conn
  ```

  ### Traditional /etc/network/interfaces (Legacy)
  ```bash
  # Static IP
  auto eth0
  iface eth0 inet static
      address 192.168.1.100/24
      gateway 192.168.1.1
      dns-nameservers 8.8.8.8 8.8.4.4

  # DHCP
  auto eth0
  iface eth0 inet dhcp

  # VLAN tag
  auto eth0.100
  iface eth0.100 inet static
      vlan-raw-device eth0
      address 10.0.100.1/24
  ```

  ### iproute2 Commands (Modern)
  ```bash
  # Show all interfaces
  ip addr show

  # Show routes
  ip route show

  # Add route
  ip route add 10.0.0.0/8 via 192.168.1.1 dev eth0

  # Show neighbors (ARP)
  ip neigh show

  # Show links
  ip link show

  # Bring interface up/down
  ip link set eth0 up/down
  ```

  ### Interface Naming
  - **Predictable:** eno1, ens1, enp0s3 (kernel-based)
  - **Custom:** `/etc/udev/rules.d/70-persistent-net.rules`
  - **Disable:** `biosdevname=0 net.ifnames=0` kernel params

  ### VLAN Configuration
  ```bash
  # Create VLAN interface
  nmcli connection add type vlan con-name vlan10 ifname eth0.10   dev eth0 id 10
  nmcli connection modify vlan10 ipv4.addresses 10.0.10.1/24 ipv4.method manual
  ```


entity_id: ent_20260526T182935584985_b404a059
type: memory
category: debian/net-bonding
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:35.584985
updated_at: 2026-05-26T18:29:35.584985
content:
  ## Debian Network Bonding
  ### Bonding Modes
  | Mode | Name | Use Case |
  |------|------|----------|
  | 0 | round-robin | Load balancing + fault tolerance |
  | 1 | active-backup | Fault tolerance only |
  | 2 | XOR | Load balancing + fault tolerance |
  | 4 | 802.3ad (LACP) | Load balancing + fault tolerance (switch required) |
  | 6 | balance-alb | Adaptive load balancing |

  ### Setup Bonding (NetworkManager)
  ```bash
  # Create bond
  nmcli connection add type bond con-name bond0 ifname bond0   bond.options "mode=active-backup"

  # Add slave interfaces
  nmcli connection add type bond-slave ifname eth0 master bond0
  nmcli connection add type bond-slave ifname eth1 master bond0

  # Set static IP on bond
  nmcli connection modify bond0 ipv4.addresses 192.168.1.100/24   ipv4.gateway 192.168.1.1 ipv4.method manual
  ```

  ### Setup Bonding (Traditional)
  ```bash
  # Install
  apt install ifenslave

  # /etc/network/interfaces
  auto bond0
  iface bond0 inet static
      address 192.168.1.100/24
      gateway 192.168.1.1
      bond-slaves eth0 eth1
      bond-mode active-backup
      bond-miimon 100

  # Kernel module
  modprobe bonding mode=active-backup miimon=100
  ```

  ### Monitor Bonding
  ```bash
  # Bond status
  cat /proc/net/bonding/bond0

  # Bonding statistics
  ethtool eth0 | grep -i bond
  ethtool eth1 | grep -i bond

  # Kernel messages
  dmesg | grep bond
  ```

  ### LACP (802.3ad) Requirements
  - Switch must support LACP
  - All ports in LAG must have same speed/duplex
  - `bond.options "mode=802.3ad lacp_rate=fast xmit_hash_policy=layer3+4"`


entity_id: ent_20260526T182935782619_13984131
type: memory
category: debian/dns
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:35.782619
updated_at: 2026-05-26T18:29:35.782619
content:
  ## Debian DNS Configuration & Troubleshooting
  ### DNS Resolution Order
  1. `/etc/hosts` (local static entries)
  2. systemd-resolved (DNS resolver)
  3. NetworkManager DNS settings
  4. `/etc/resolv.conf` (symlink to systemd-resolved)

  ### systemd-resolved
  ```bash
  # Check status
  systemd-resolve --status

  # Query DNS
  systemd-resolve example.com

  # Configure DNS
  sudo mkdir -p /etc/systemd/resolved.conf.d/
  sudo nano /etc/systemd/resolved.conf.d/dns.conf
  [Resolve]
  DNS=8.8.8.8 8.8.4.4 1.1.1.1
  FallbackDNS=9.9.9.9

  sudo systemctl restart systemd-resolved
  ```

  ### DNS Troubleshooting
  ```bash
  # Test DNS resolution
  nslookup example.com
  dig example.com
  host example.com

  # Check DNS cache
  systemd-resolve --statistics

  # Flush DNS cache
  sudo systemctl restart systemd-resolved

  # DNSSEC validation
  dig example.com +dnssec
  dig +trust-anchor

  # DNS lookup performance
  dig example.com +stats

  # DNS zone transfer (authorized)
  dig axfr example.com @ns1.example.com

  # DNS record types
  dig example.com A      # IPv4
  dig example.com AAAA   # IPv6
  dig example.com MX     # Mail server
  dig example.com TXT    # Text records
  dig example.com CNAME  # Alias
  dig example.com NS     # Name servers
  dig example.com SOA    # Start of authority
  ```

  ### Local DNS Cache (dnsmasq)
  ```bash
  # Install
  apt install dnsmasq

  # Configure
  nano /etc/dnsmasq.conf
  # server=8.8.8.8
  # server=8.8.4.4
  # cache-size=1000
  # log-queries

  # Local DNS entries
  nano /etc/hosts
  127.0.0.1   localhost.localdomain

  # Restart
  systemctl restart dnsmasq
  ```

  ### DNS Security
  - **DoH (DNS over HTTPS):** `dnscrypt-proxy`
  - **DoT (DNS over TLS):** `getdns`
  - **Private DNS:** `dnsmasq` with local zones
  - **Block ads:** `pi-hole` or `dnsmasq` with blocklists

  ### DNS Performance
  - **Cache size:** `cache-size=1000` (dnsmasq)
  - **Negative caching:** `neg-ttl=3600`
  - **EDNS0:** `edns-packet-max-size=4096`
  - **IPv6 priority:** `no-resolv` + explicit servers


entity_id: ent_20260526T182935981103_1e645163
type: memory
category: debian/net-monitoring
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:35.981103
updated_at: 2026-05-26T18:29:35.981103
content:
  ## Debian Network Monitoring & Analysis
  ### Real-time Monitoring
  ```bash
  # Network traffic
  iftop              # Top connections
  nethogs            # Top processes
  iptraf             # Interface traffic
  ```

  ### Packet Analysis
  ```bash
  # Capture packets
  tcpdump -i eth0 -w capture.pcap
  tcpdump -i eth0 port 80
  tcpdump -i eth0 host 192.168.1.100
  tcpdump -i eth0 'tcp[tcpflags] & (syn|fin|rst|ack) != 0'

  # Analyze capture
  tcpdump -r capture.pcap
  wireshark capture.pcap
  ```

  ### Network Diagnostics
  ```bash
  # Connectivity
  ping -c 10 8.8.8.8
  traceroute 8.8.8.8
  mtr 8.8.8.8           # Continuous traceroute

  # DNS
  nslookup example.com
  dig example.com
  host example.com

  # Port scanning
  nmap -sS 192.168.1.0/24
  nmap -sV 192.168.1.100
  nmap -O 192.168.1.100

  # Network statistics
  ss -tuln              # Listening ports
  ss -s                 # Summary statistics
  netstat -an           # All connections
  ```

  ### Performance Monitoring
  ```bash
  # Bandwidth usage
  vnstat                # Historical stats
  iptraf -g             # Interface traffic
  sar -n DEV 1 10       # Network stats

  # Latency
  ping -c 100 8.8.8.8 | awk '{print $4}' | cut -d'=' -f2 | sort -n | tail -1
  mtr --report 8.8.8.8

  # Packet loss
  ping -c 1000 8.8.8.8 | grep -o 'packet loss'
  ```

  ### Network Security Monitoring
  ```bash
  # Failed connections
  journalctl -u ssh --since "1 hour ago" | grep "Failed password"

  # Port scans
  nmap -sS -O 192.168.1.0/24

  # Suspicious connections
  ss -tuln | grep -E ":(22|80|443|8080)$"

  # Network traffic alerts
  iftop -i eth0 -t -s 300 | grep "total"
  ```

  ### Network Automation
  ```bash
  # Automated monitoring script
  #!/bin/bash
  INTERVAL=60
  LOG=/var/log/network_monitor.log

  while true; do
      echo "=== $(date) ===" >> $LOG
      df -h / >> $LOG
      free -h >> $LOG
      ip addr show >> $LOG
      ss -tuln >> $LOG
      sleep $INTERVAL
  done
  ```


entity_id: ent_20260526T182936178718_60a81555
type: memory
category: debian/net-security
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:36.178718
updated_at: 2026-05-26T18:29:36.178718
content:
  ## Debian Network Security
  ### Firewall Rules (nftables)
  ```bash
  # Basic firewall
  sudo nft add table inet filter
  sudo nft add chain inet filter input '{ type filter hook input priority 0\; policy drop\; }'
  sudo nft add chain inet filter forward '{ type filter hook forward priority 0\; policy drop\; }'
  sudo nft add chain inet filter output '{ type filter hook output priority 0\; policy accept\; }'

  # Allow SSH
  sudo nft add rule inet filter input tcp dport 22 ct state new accept
  sudo nft add rule inet filter input ip protocol icmp accept

  # Allow HTTP/HTTPS
  sudo nft add rule inet filter input tcp dport { 80, 443 } ct state new accept

  # Allow established connections
  sudo nft add rule inet filter input ct state established,related accept

  # Save rules
  sudo nft list ruleset > /etc/nftables.conf
  ```

  ### SSH Hardening
  ```bash
  # /etc/ssh/sshd_config
  Port 2222
  PermitRootLogin no
  PasswordAuthentication no
  PubkeyAuthentication yes
  MaxAuthTries 3
  LoginGraceTime 30
  ClientAliveInterval 300
  ClientAliveCountMax 2
  ```

  ### Network Isolation
  ```bash
  # Network namespaces
  ip netns add testnet
  ip netns exec testnet ip addr add 192.168.100.1/24 dev eth0

  # VLAN segmentation
  nmcli connection add type vlan con-name vlan10 ifname eth0.10 dev eth0 id 10
  ```

  ### VPN Configuration
  ```bash
  # OpenVPN server
  apt install openvpn easy-rsa
  cp -r /usr/share/easy-rsa/ /etc/openvpn/easy-rsa
  cd /etc/openvpn/easy-rsa/easy-rsa
  ./easyrsa init-pki
  ./easyrsa build-ca
  ./easyrsa gen-req server nopass
  ./easyrsa sign-req server server

  # WireGuard server
  apt install wireguard
  wg genkey | tee /etc/wireguard/privatekey | wg pubkey > /etc/wireguard/publickey
  ```

  ### IDS/IPS
  ```bash
  # Fail2ban
  apt install fail2ban
  nano /etc/fail2ban/jail.local
  [sshd]
  enabled = true
  port = 22
  filter = sshd
  logpath = /var/log/auth.log
  maxretry = 5
  bantime = 3600

  # Suricata (IDS)
  apt install suricata
  systemctl enable suricata
  ```

  ### Network Encryption
  ```bash
  # TLS certificates
  apt install certbot
  certbot --nginx -d example.com

  # IPsec VPN
  apt install strongswan
  systemctl start strongswan
  ```


entity_id: ent_20260526T182936374563_ecf2ea57
type: memory
category: debian/load-balancing
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:36.374563
updated_at: 2026-05-26T18:29:36.374563
content:
  ## Debian Load Balancing
  ### HAProxy Configuration
  ```bash
  # Install
  apt install haproxy

  # /etc/haproxy/haproxy.cfg
  global
      log /dev/log local0
      maxconn 4096
      stats socket /run/haproxy/admin.sock

  defaults
      log global
      mode http
      timeout connect 5000ms
      timeout client 50000ms
      timeout server 50000ms

  frontend http_front
      bind *:80
      default_backend http_back

  backend http_back
      balance roundrobin
      server web1 192.168.1.10:80 check
      server web2 192.168.1.11:80 check
      server web3 192.168.1.12:80 check
  ```

  ### Nginx Load Balancing
  ```nginx
  upstream backend {
      least_conn;
      server 192.168.1.10:80 weight=3;
      server 192.168.1.11:80 weight=2;
      server 192.168.1.12:80 backup;
  }

  server {
      listen 80;
      location / {
          proxy_pass http://backend;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
      }
  }
  ```

  ### Keepalived (High Availability)
  ```bash
  # Install
  apt install keepalived

  # /etc/keepalived/keepalived.conf
  vrrp_script chk_http {
      script "/usr/bin/curl -f http://localhost/ || exit 1"
      interval 2
      weight -20
  }

  vrrp_instance VI_1 {
      state MASTER
      interface eth0
      virtual_router_id 51
      priority 100
      advert_int 1
      virtual_ipaddress {
          192.168.1.100/24
      }
      track_script {
          chk_http
      }
  }
  ```

  ### LVS (Linux Virtual Server)
  ```bash
  # Install
  apt install ipvsadm

  # Add virtual server
  ipvsadm -A -t 192.168.1.100:80 -s rr

  # Add real servers
  ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.11:80 -w 1
  ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.12:80 -w 1

  # View configuration
  ipvsadm -L -n
  ```

  ### Health Checking
  ```bash
  # HAProxy health checks
  option httpchk GET /health
  http-check expect status 200

  # Nginx upstream health checks
  upstream backend {
      zone backend 64k;
      server 192.168.1.10:80 max_fails=3 fail_timeout=30s;
  }
  ```


entity_id: ent_20260526T182936569573_4a38fde6
type: memory
category: debian/wireless
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:36.569573
updated_at: 2026-05-26T18:29:36.569573
content:
  ## Debian Wireless Networking
  ### Wireless Interface Setup
  ```bash
  # Check wireless interfaces
  iw dev

  # Scan networks
  sudo iw dev wlan0 scan | grep SSID

  # Connect to network
  nmcli dev wifi connect "SSID" password "password"

  # Check connection
  nmcli dev wifi list
  ```

  ### WPA-Supplicant Configuration
  ```bash
  # /etc/wpa_supplicant/wpa_supplicant.conf
  ctrl_interface=/run/wpa_supplicant
  network={
      ssid="HomeNetwork"
      psk="password"
      key_mgmt=WPA-PSK
      pairwise=CCMP
      group=CCMP
  }
  ```

  ### Access Point Setup
  ```bash
  # Install hostapd
  apt install hostapd

  # /etc/hostapd/hostapd.conf
  interface=wlan0
  driver=nl80211
  ssid=MyAP
  hw_mode=g
  channel=6
  wmm_enabled=1
  wpa=2
  wpa_passphrase=password
  wpa_key_mgmt=WPA-PSK
  wpa_pairwise=CCMP
  rsn_pairwise=CCMP
  ```

  ### Wireless Monitoring
  ```bash
  # Monitor mode
  sudo airmon-ng start wlan0

  # Packet capture
  sudo tcpdump -i wlan0mon -w wireless.pcap

  # Signal strength
  iwconfig wlan0 | grep Signal
  ```

  ### Wireless Security
  - **WPA2/WPA3:** Strong encryption
  - **Hidden SSID:** `ssid_hidden=1` in hostapd
  - **MAC filtering:** `macaddr_acl=1` with `accept_mac_file`
  - **RADIUS:** Enterprise authentication


entity_id: ent_20260526T182936765324_f29d3dda
type: memory
category: debian/net-automation
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:36.765324
updated_at: 2026-05-26T18:29:36.765324
content:
  ## Debian Network Automation
  ### Ansible Network Modules
  ```bash
  # Install
  apt install ansible

  # Network tasks
  - name: Configure interface
    community.general.net_interface:
      name: eth0
      state: up
      ip: 192.168.1.100
      netmask: 255.255.255.0
      gateway: 192.168.1.1

  - name: Add firewall rule
    community.general.nftables:
      table: filter
      chain: input
      rule: 'tcp dport 80 accept'
      state: present
  ```

  ### Python Network Scripts
  ```python
  import subprocess
  import json

  def check_interface(iface='eth0'):
      result = subprocess.run(['ip', 'addr', 'show', iface], 
                            capture_output=True, text=True)
      return result.stdout

  def get_dns_config():
      result = subprocess.run(['systemd-resolve', '--status'], 
                            capture_output=True, text=True)
      return result.stdout

  def monitor_bandwidth(duration=60):
      import psutil
      net_io = psutil.net_io_counters()
      return {
          'bytes_sent': net_io.bytes_sent,
          'bytes_recv': net_io.bytes_recv
      }
  ```

  ### Network Monitoring Scripts
  ```bash
  #!/bin/bash
  # Daily network health check
  INTERFACES="eth0 wlan0"
  LOG="/var/log/network_health.log"

  for iface in $INTERFACES; do
      echo "=== $(date) - $iface ===" >> $LOG
      
      # Link status
      ip link show $iface >> $LOG
      
      # IP address
      ip addr show $iface >> $LOG
      
      # Routes
      ip route show >> $LOG
      
      # DNS resolution
      nslookup google.com >> $LOG 2>&1
  done
  ```

  ### Automated DNS Updates
  ```bash
  # Dynamic DNS update script
  #!/bin/bash
  DOMAIN="mydomain.com"
  API_KEY="your_api_key"

  CURRENT_IP=$(curl -s ifconfig.me)
  SAVED_IP=$(cat /var/run/myip.txt 2>/dev/null)

  if [ "$CURRENT_IP" != "$SAVED_IP" ]; then
      curl -X POST "https://api.dyn.com/update?host=$DOMAIN&apikey=$API_KEY&myip=$CURRENT_IP"
      echo "$CURRENT_IP" > /var/run/myip.txt
  fi
  ```

  ### Network Testing Automation
  ```bash
  # Automated connectivity test
  #!/bin/bash
  SERVERS=("8.8.8.8" "1.1.1.1" "9.9.9.9")
  RESULTS="/tmp/network_test_$(date +%Y%m%d).log"

  for server in "${SERVERS[@]}"; do
      ping -c 3 $server >> $RESULTS 2>&1
      traceroute $server >> $RESULTS 2>&1
  done
  ```


entity_id: ent_20260526T182936961823_c87cded9
type: memory
category: debian/net-troubleshoot
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:36.961823
updated_at: 2026-05-26T18:29:36.961823
content:
  ## Debian Network Troubleshooting Methodology
  ### Systematic Troubleshooting Steps
  1. **Physical Layer:** Check cables, LEDs, interface status
  2. **Data Link Layer:** MAC addresses, switch ports, VLANs
  3. **Network Layer:** IP configuration, routing, ARP
  4. **Transport Layer:** Ports, firewalls, services
  5. **Application Layer:** DNS, HTTP, specific applications

  ### Common Issues & Solutions
  ```bash
  # No network connectivity
  ip addr show                    # Check IP assignment
  ip route show                   # Check routes
  ping 127.0.0.1                 # Loopback test
  ping 192.168.1.1               # Gateway test
  ping 8.8.8.8                   # External test
  nslookup google.com            # DNS test

  # Slow network
  iftop                         # Bandwidth usage
  ping -c 100 8.8.8.8 | awk '{print $4}' | cut -d'=' -f2 | sort -n | tail -1
  # High latency? Check MTU
  ping -M do -s 1472 8.8.8.8    # MTU test
  ethtool eth0 | grep Speed     # Link speed

  # DNS issues
  systemd-resolve --status      # Resolver status
  dig google.com                # DNS query
  host google.com               # Host lookup
  cat /etc/resolv.conf          # DNS config

  # Firewall issues
  sudo nft list ruleset         # Current rules
  ss -tuln                      # Listening ports
  iptables -L -n                # Old iptables (if used)

  # Interface down
  ip link show                  # Link status
  sudo ip link set eth0 up      # Bring up
  sudo nmcli device status      # NetworkManager status
  ```

  ### Network Diagnostics Tools
  ```bash
  # Connectivity
  ping -c 10 8.8.8.8
  traceroute 8.8.8.8
  mtr 8.8.8.8

  # DNS
  nslookup example.com
  dig example.com
  host example.com

  # Ports
  nmap -sS 192.168.1.0/24
  nmap -sV 192.168.1.100

  # Traffic analysis
  tcpdump -i eth0 port 80
  iftop
  nethogs
  ```

  ### Common Error Messages
  - **"Network is unreachable":** Check routing table
  - **"Connection refused":** Port blocked or service down
  - **"No route to host":** Routing issue or firewall
  - **"Temporary failure in name resolution":** DNS problem
  - **"Operation not permitted":** Permission issue


entity_id: ent_20260526T182937156133_93151109
type: memory
category: debian/ipv6
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:37.156133
updated_at: 2026-05-26T18:29:37.156133
content:
  ## Debian IPv6 Configuration
  ### IPv6 Setup
  ```bash
  # Check IPv6 support
  ip -6 addr show

  # Configure static IPv6
  nmcli connection modify eth0   ipv6.addresses 2001:db8::1/64   ipv6.gateway fe80::1   ipv6.method manual

  # Automatic IPv6
  nmcli connection modify eth0 ipv6.method auto

  # Test IPv6 connectivity
  ping6 -c 3 2001:4860:4860::8888
  traceroute6 2001:4860:4860::8888
  ```

  ### IPv6 DNS
  ```bash
  # IPv6 DNS servers
  systemd-resolve --status
  # Look for DNS Servers: 2001:4860:4860::8888

  # Configure IPv6 DNS
  nmcli connection modify eth0 ipv6.dns "2001:4860:4860::8888 2001:4860:4860::8844"
  ```

  ### IPv6 Security
  ```bash
  # IPv6 firewall rules
  sudo nft add rule inet filter input ip6 saddr 2001:db8::/64 accept
  sudo nft add rule inet filter input ip6 saddr ::1 accept  # localhost

  # Disable IPv6 (if needed)
  echo "net.ipv6.conf.all.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf
  sudo sysctl -p
  ```

  ### IPv6 Troubleshooting
  ```bash
  # Check IPv6 status
  ip -6 addr show
  ip -6 route show

  # Test connectivity
  ping6 -c 3 2001:4860:4860::8888
  traceroute6 2001:4860:4860::8888

  # DNS resolution
  dig google.com AAAA
  host -t AAAA google.com
  ```


entity_id: ent_20260526T182937351523_6cc4f18f
type: memory
category: debian/proxy
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:37.351523
updated_at: 2026-05-26T18:29:37.351523
content:
  ## Debian Proxy Servers
  ### Squid Proxy
  ```bash
  # Install
  apt install squid

  # /etc/squid/squid.conf
  http_port 3128
  acl localnet src 192.168.1.0/24
  http_access allow localnet
  http_access deny all
  cache_dir ufs /var/spool/squid 100 16 256
  ```

  ### Nginx Reverse Proxy
  ```nginx
  server {
      listen 80;
      server_name example.com;

      location / {
          proxy_pass http://127.0.0.1:8080;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
      }
  }
  ```

  ### Apache Reverse Proxy
  ```apache
  <VirtualHost *:80>
      ServerName example.com
      
      ProxyPreserveHost On
      ProxyPass / http://127.0.0.1:8080/
      ProxyPassReverse / http://127.0.0.1:8080/
      
      # Security headers
      Header always set X-Frame-Options DENY
      Header always set X-Content-Type-Options nosniff
  </VirtualHost>
  ```

  ### HTTP Proxy Configuration
  ```bash
  # Environment variables
  export http_proxy=http://proxy.example.com:8080
  export https_proxy=http://proxy.example.com:8080

  # APT proxy
  echo 'Acquire::http::Proxy "http://proxy.example.com:8080";' > /etc/apt/apt.conf.d/proxy.conf

  # Git proxy
  git config --global http.proxy http://proxy.example.com:8080
  git config --global https.proxy http://proxy.example.com:8080
  ```


entity_id: ent_20260526T182937547762_2370edeb
type: memory
category: debian/net-perf
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:37.547762
updated_at: 2026-05-26T18:29:37.547762
content:
  ## Debian Network Performance Tuning
  ### TCP Tuning
  ```bash
  # /etc/sysctl.d/99-network-tuning.conf
  # Increase TCP window size
  net.core.rmem_max = 16777216
  net.core.wmem_max = 16777216
  net.ipv4.tcp_rmem = 4096 87380 16777216
  net.ipv4.tcp_wmem = 4096 65536 16777216

  # Enable TCP Fast Open
  net.ipv4.tcp_fastopen = 3

  # TCP window scaling
  net.ipv4.tcp_window_scaling = 1

  # TCP timestamps
  net.ipv4.tcp_timestamps = 1

  # Apply changes
  sysctl -p /etc/sysctl.d/99-network-tuning.conf
  ```

  ### Interface Tuning
  ```bash
  # Jumbo frames
  ip link set eth0 mtu 9000

  # Ring buffer sizes
  ethtool -G eth0 rx 4096 tx 4096

  # Interrupt coalescing
  ethtool -C eth0 rx-usecs 50 tx-usecs 50

  # RSS (Receive Side Scaling)
  ethtool -L eth0 combined 4
  ```

  ### Network Monitoring
  ```bash
  # Real-time traffic
  iftop -i eth0
  nethogs eth0

  # Historical data
  sar -n DEV 1 10
  vnstat

  # Packet loss
  ping -c 1000 8.8.8.8 | grep -o 'packet loss'

  # Latency
  ping -c 100 8.8.8.8 | awk '{print $4}' | cut -d'=' -f2 | sort -n | tail -1
  ```

  ### DNS Performance
  ```bash
  # Cache size
  echo "cache-size=1000" >> /etc/dnsmasq.conf

  # DNS over HTTPS
  apt install dnscrypt-proxy
  systemctl enable dnscrypt-proxy

  # DNSSEC validation
  systemd-resolve --status
  ```


entity_id: ent_20260526T182937745116_4344c544
type: memory
category: debian/snmp
strength: moderate
metadata: "{\"source\": \"debian_networking_deep_dive\"}"
created_at: 2026-05-26T18:29:37.745116
updated_at: 2026-05-26T18:29:37.745116
content:
  ## Debian SNMP & Network Management
  ### SNMP Agent Setup
  ```bash
  # Install
  apt install snmpd

  # /etc/snmp/snmpd.conf
  com2sec notConfigUser  default       public
  group notConfigGroup v2c         notConfigUser
  view all    included  .1           80
  access  notConfigGroup ""      any       noauth    exact  all    none   none
  ```

  ### SNMP Monitoring
  ```bash
  # Check SNMP status
  snmpwalk -v 2c -c public localhost

  # Monitor specific MIBs
  snmpget -v 2c -c public localhost 1.3.6.1.2.1.1.3.0  # Uptime
  snmpget -v 2c -c public localhost 1.3.6.1.2.1.1.5.0  # Hostname

  # Network interface stats
  snmpwalk -v 2c -c public localhost 1.3.6.1.2.1.2.2

  # System resources
  snmpwalk -v 2c -c public localhost 1.3.6.1.2.1.25  # Host resources
  ```

  ### Zabbix Integration
  ```bash
  # Install Zabbix agent
  apt install zabbix-agent

  # /etc/zabbix/zabbix_agentd.conf
  Server=192.168.1.100
  ServerActive=192.168.1.100
  Hostname=debian-server
  ListenPort=10050
  ```

  ### Grafana + Prometheus
  ```bash
  # Install node exporter
  wget https://github.com/prometheus/node_exporter/releases/latest/download/node_exporter-1.7.0.linux-amd64.tar.gz
  tar xvf node_exporter-*.tar.gz

  # Systemd service
  [Unit]
  Description=Node Exporter
  After=network.target

  [Service]
  Type=simple
  ExecStart=/usr/local/bin/node_exporter

  [Install]
  WantedBy=multi-user.target
  ```


entity_id: ent_20260526T183834276468_16725ae4
type: memory
category: debian/dev-environment
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:34.276468
updated_at: 2026-05-26T18:38:34.276468
content:
  ## Debian Development Environment Setup
  ### Base Development Packages
  ```bash
  # Essential dev tools
  sudo apt install build-essential git curl wget unzip tree htop tmux
  sudo apt install gdb valgrind strace ltrace lsof

  # Version control
  sudo apt install git subversion mercurial

  # Text editors
  sudo apt install vim emacs nano micro

  # Python development
  sudo apt install python3 python3-pip python3-venv python3-dev python3-full

  # Node.js
  sudo apt install nodejs npm
  # Or from NodeSource for latest
  curl -fsSL https://deb.nodesource.com/setup_20.x | sudo bash
  sudo apt install nodejs

  # Go
  sudo apt install golang-go golang-doc golang-gofmt

  # Rust
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  source ~/.cargo/env

  # Java
  sudo apt install default-jdk default-jdk-doc maven gradle

  # Rust + Cargo
  sudo apt install rustc cargo

  # .NET
  sudo apt install dotnet-sdk-8.0
  ```

  ### Development Shell Configuration
  ```bash
  # ~/.bashrc additions
  export EDITOR=vim
  export LANG=en_US.UTF-8
  export TERM=xterm-256color

  # Development paths
  export PATH=$HOME/.local/bin:$HOME/go/bin:$HOME/.cargo/bin:$PATH

  # Git aliases
  alias g='git'
  alias gs='git status'
  alias gc='git commit'
  alias gp='git push'
  alias gl='git log --oneline --graph --decorate'
  ```

  ### IDE Setup
  ```bash
  # VS Code
  wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo gpg --dearmor -o /usr/share/keyrings/microsoft-prod.gpg
  echo "deb [arch=amd64 signed-by=/usr/share/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/repos/code stable main" | sudo tee /etc/apt/sources.list.d/vscode.list
  sudo apt update && sudo apt install code

  # JetBrains (IntelliJ, PyCharm, etc.)
  sudo snap install intellij-idea-community --classic
  sudo snap install pycharm-community --classic
  ```

  ### Development Containers
  ```bash
  # Docker + Compose
  sudo apt install docker.io docker-compose-plugin

  # Development workspace
  git clone https://github.com/devcontainers/features
  ```

  ### Package Development
  ```bash
  # Debian packaging tools
  sudo apt install devscripts debhelper dh-make fakeroot build-essential

  # Create Debian package
  dh-make --createorig
  debuild -us -uc
  ```


entity_id: ent_20260526T183834482920_9c7cb650
type: memory
category: debian/build-systems
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:34.482920
updated_at: 2026-05-26T18:38:34.482920
content:
  ## Debian Build Systems
  ### CMake (Modern Standard)
  ```cmake
  cmake_minimum_required(VERSION 3.20)
  project(myproject VERSION 1.0 LANGUAGES C CXX)

  set(CMAKE_C_STANDARD 17)
  set(CMAKE_CXX_STANDARD 20)

  # Compiler flags
  add_compile_options(-Wall -Wextra -Werror)
  add_compile_options(-O2 -g)

  # Source files
  add_executable(myapp src/main.cpp src/utils.cpp)
  target_include_directories(myapp PRIVATE include/)

  # Link libraries
  target_link_libraries(myapp PRIVATE pthread m dl)

  # Testing
  enable_testing()
  add_executable(tests tests/test_main.cpp)
  target_link_libraries(tests PRIVATE gtest gtest_main)
  add_test(NAME myapp_tests COMMAND tests)

  # Installation
  install(TARGETS myapp DESTINATION bin)
  install(DIRECTORY include/ DESTINATION include)
  ```

  Build workflow:
  ```bash
  mkdir build && cd build
  cmake -DCMAKE_BUILD_TYPE=Release ..
  make -j$(nproc)
  make test
  sudo make install
  ```

  ### Meson + Ninja
  ```meson
  project('myproject', 'c',
    version : '1.0',
    default_options : ['buildtype=release', 'c_std=c17'])

  sources = files('src/main.c', 'src/utils.c')
  executable('myapp', sources,
    include_directories : include_directories('include'),
    install : true)

  test('unit', executable('myapp'), args : ['--test'])
  ```

  Build:
  ```bash
  meson setup build
  ninja -C build
  ninja -C build test
  ninja -C build install
  ```

  ### Make (Traditional)
  ```makefile
  CC = gcc
  CFLAGS = -Wall -Wextra -O2 -g
  LDFLAGS = -lm -lpthread

  SRC = $(wildcard src/*.c)
  OBJ = $(SRC:.c=.o)
  TARGET = myapp

  all: $(TARGET)

  $(TARGET): $(OBJ)
      $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)

  %.o: %.c
      $(CC) $(CFLAGS) -c -o $@ $<

  clean:
      rm -f $(OBJ) $(TARGET)

  .PHONY: all clean
  ```

  ### Autotools (Legacy)
  ```bash
  # Generate build system
  aclocal
  autoconf
  automake --add-missing

  # Standard build
  ./configure
  make
  sudo make install
  ```

  ### Cargo (Rust)
  ```toml
  [package]
  name = "myproject"
  version = "0.1.0"
  edition = "2021"

  [dependencies]
  serde = { version = "1.0", features = ["derive"] }
  tokio = { version = "1", features = ["full"] }

  [dev-dependencies]
  criterion = "0.5"

  [[bench]]
  name = "my_bench"
  harness = false
  ```

  ### Gradle (Java)
  ```groovy
  plugins {
      id 'java'
      id 'application'
  }

  repositories { mavenCentral() }

  dependencies {
      implementation 'com.google.guava:guava:33.0.0-jre'
      testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0'
  }

  test { useJUnitPlatform() }
  application {
      mainClass = 'com.example.MyApp'
  }
  ```


entity_id: ent_20260526T183834681241_338e1e6e
type: memory
category: debian/debugging
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:34.681241
updated_at: 2026-05-26T18:38:34.681241
content:
  ## Debian Debugging & Profiling Tools
  ### GDB (GNU Debugger)
  ```bash
  # Compile with debug symbols
  gcc -g -o myapp myapp.c

  # Run GDB
  gdb ./myapp

  # GDB commands
  (gdb) break main          # Set breakpoint
  (gdb) run                 # Start program
  (gdb) next                # Step over
  (gdb) step                # Step into
  (gdb) print variable      # Print value
  (gdb) backtrace           # Stack trace
  (gdb) continue            # Continue execution
  (gdb) info threads        # List threads
  (gdb) thread 2            # Switch to thread 2
  (gdb) watch variable      # Watch variable changes
  ```

  ### Valgrind (Memory Analysis)
  ```bash
  # Compile with debug
  gcc -g -o myapp myapp.c

  # Memory leak detection
  valgrind --leak-check=full --show-leak-kinds=all ./myapp

  # Thread error detection
  valgrind --tool=helgrind ./myapp

  # Cache profiling
  valgrind --tool=cachegrind ./myapp

  # Memory profiler
  valgrind --tool=massif ./myapp
  ms_print massif.out.<pid>
  ```

  ### strace (System Call Tracing)
  ```bash
  # Trace system calls
  strace -f -o trace.log ./myapp

  # Count calls
  strace -c ./myapp

  # Trace specific calls
  strace -e trace=network ./myapp
  strace -e trace=file ./myapp

  # Trace running process
  strace -p <pid>
  ```

  ### Performance Profiling
  ```bash
  # perf (Linux perf)
  sudo perf record -g ./myapp
  sudo perf report

  # gprof
  gcc -pg -o myapp myapp.c
  ./myapp
  gprof myapp gmon.out

  # Flame graphs
  git clone https://github.com/brendangregg/FlameGraph
  sudo perf record -F 99 -g -- ./myapp
  sudo perf script | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl > out.svg
  ```

  ### Static Analysis
  ```bash
  # Clang static analyzer
  sudo apt install clang
  scan-build make

  # cppcheck
  sudo apt install cppcheck
  cppcheck --enable=all --error-exitcode=1 src/

  # SonarQube (server)
  sudo apt install sonarqube
  ```

  ### Debug Logging
  ```python
  # Python logging setup
  import logging
  logging.basicConfig(
      level=logging.DEBUG,
      format='%(asctime)s %(levelname)s %(name)s: %(message)s',
      handlers=[
          logging.FileHandler('app.log'),
          logging.StreamHandler()
      ]
  )
  ```


entity_id: ent_20260526T183834879352_c7454f47
type: memory
category: debian/version-control
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:34.879352
updated_at: 2026-05-26T18:38:34.879352
content:
  ## Debian Version Control
  ### Git Configuration
  ```bash
  # Basic setup
  git config --global user.name "Your Name"
  git config --global user.email "email@example.com"
  git config --global core.editor vim
  git config --global merge.tool vimdiff

  # SSH keys
  ssh-keygen -t ed25519 -C "email@example.com"
  eval "$(ssh-agent -s)"
  ssh-add ~/.ssh/id_ed25519

  # Git aliases
  git config --global alias.st 'status'
  git config --global alias.co 'checkout'
  git config --global alias.br 'branch'
  git config --global alias.ci 'commit'
  git config --global alias.lg "log --oneline --graph --decorate --all"
  ```

  ### Git Workflow
  ```bash
  # Feature branch workflow
  git checkout -b feature/my-feature
  git add .
  git commit -m "feat: add my feature"
  git push origin feature/my-feature

  # Rebase and merge
  git fetch origin
  git rebase origin/main
  git checkout main
  git merge --squash feature/my-feature
  ```

  ### Git Hooks
  ```bash
  # Pre-commit hook
  #!/bin/bash
  # .git/hooks/pre-commit
  flake8 .
  if [ $? -ne 0 ]; then
      echo "Linting failed"
      exit 1
  fi
  ```

  ### Stash & Recovery
  ```bash
  # Stash changes
  git stash save "WIP: feature work"
  git stash list
  git stash pop

  # Cherry-pick commits
  git cherry-pick <commit-hash>
  ```

  ### Subversion
  ```bash
  # Basic SVN
  svn checkout svn://server/project
  svn update
  svn commit -m "message"
  svn diff
  svn log -l 10
  ```


entity_id: ent_20260526T183835080493_5da10125
type: memory
category: debian/dev-packaging
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:35.080493
updated_at: 2026-05-26T18:38:35.080493
content:
  ## Debian Package Management for Development
  ### apt Development Packages
  ```bash
  # Install development headers
  sudo apt install lib<name>-dev

  # Examples
  sudo apt install libssl-dev
  sudo apt install libcurl4-openssl-dev
  sudo apt install libsqlite3-dev
  sudo apt install libpng-dev

  # Find packages
  apt search <keyword>
  apt show <package>
  apt depends <package>
  ```

  ### Python Packaging
  ```bash
  # Create virtual environment
  python3 -m venv myproject_venv
  source myproject_venv/bin/activate

  # pip requirements
  pip install -r requirements.txt
  pip freeze > requirements.txt

  # Build package
  python3 setup.py sdist bdist_wheel
  twine upload dist/*

  # Modern packaging
  pip install build hatch
  ```

  requirements.txt:
  ```
  flask==3.0.0
  sqlalchemy==2.0.0
  pytest==7.4.0
  black==23.12.0
  mypy==1.8.0
  ```

  ### Node.js
  ```bash
  # npm project setup
  npm init -y
  npm install express cors dotenv

  # Package.json scripts
  {
    "scripts": {
      "dev": "nodemon index.js",
      "build": "tsc",
      "start": "node dist/index.js",
      "test": "jest",
      "lint": "eslint src/"
    }
  }
  ```

  ### Rust Cargo
  ```bash
  # Project setup
  cargo new myproject
  cd myproject
  cargo run
  cargo test
  cargo build --release
  cargo publish
  ```

  ### Debian Package Building
  ```bash
  # Create .deb package
  mkdir -p myproject/DEBIAN
  echo -e "Package: myproject
  Version: 1.0.0
  Section: utils
  Priority: optional
  Architecture: amd64
  Maintainer: Me <me@example.com>
  Description: My Project" > myproject/DEBIAN/control

  dpkg-deb --build myproject
  sudo dpkg -i myproject.deb
  ```


entity_id: ent_20260526T183835277777_943d9ff8
type: memory
category: debian/containers
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:35.277777
updated_at: 2026-05-26T18:38:35.277777
content:
  ## Debian Containerization
  ### Docker Development
  ```dockerfile
  # Python app
  FROM python:3.12-slim
  WORKDIR /app
  COPY requirements.txt .
  RUN pip install --no-cache-dir -r requirements.txt
  COPY . .
  CMD ["python", "app.py"]

  # Multi-stage build
  FROM golang:1.21 AS build
  WORKDIR /app
  COPY . .
  RUN go build -o myapp .

  FROM alpine:latest
  COPY --from=build /app/myapp /usr/local/bin/myapp
  ENTRYPOINT ["myapp"]
  ```

  ### Docker Compose
  ```yaml
  version: '3.8'
  services:
    app:
      build: .
      ports:
        - "8080:8080"
      environment:
        - DATABASE_URL=postgresql://app:pass@db/mydb
      depends_on:
        - db
        - redis
      volumes:
        - ./src:/app/src

    db:
      image: postgres:16
      environment:
        POSTGRES_DB: mydb
        POSTGRES_USER: app
        POSTGRES_PASSWORD: pass
      volumes:
        - pgdata:/var/lib/postgresql/data

    redis:
      image: redis:7-alpine
      ports:
        - "6379:6379"

  volumes:
    pgdata:
  ```

  ### Development Container
  ```json
  {
    "name": "Debian Dev",
    "image": "mcr.microsoft.com/devcontainers/base:debian",
    "features": {
      "ghcr.io/devcontainers/features/python:1": {
        "version": "3.12"
      },
      "ghcr.io/devcontainers/features/node:1": {
        "version": "20"
      }
    },
    "postCreateCommand": "pip install -r requirements.txt && npm install"
  }
  ```

  ### Podman (Rootless Alternative)
  ```bash
  sudo apt install podman
  podman run -d --name myapp -p 8080:8080 myimage
  podman ps
  podman exec -it myapp sh
  ```


entity_id: ent_20260526T183835476452_ec6387f5
type: memory
category: debian/testing
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:35.476452
updated_at: 2026-05-26T18:38:35.476452
content:
  ## Debian Testing Frameworks
  ### Python Testing (pytest)
  ```python
  # tests/test_app.py
  import pytest
  from app import calculate

  def test_calculate_addition():
      assert calculate(2, 3, 'add') == 5

  def test_calculate_subtraction():
      assert calculate(5, 3, 'sub') == 2

  @pytest.mark.parametrize("a,b,result", [
      (1, 2, 3),
      (0, 0, 0),
      (-1, 1, 0)
  ])
  def test_parametrized(a, b, result):
      assert calculate(a, b, 'add') == result

  # Test fixtures
  @pytest.fixture
  def sample_data():
      return {"key": "value"}

  def test_fixture(sample_data):
      assert "key" in sample_data
  ```

  Run: `pytest tests/ -v --cov=app`

  ### Jest (JavaScript)
  ```javascript
  // __tests__/app.test.js
  const { calculate } = require('../app');

  describe('calculate', () => {
    test('adds numbers', () => {
      expect(calculate(2, 3, 'add')).toBe(5);
    });

    test('subtracts numbers', () => {
      expect(calculate(5, 3, 'sub')).toBe(2);
    });
  });
  ```

  ### Go Testing
  ```go
  package main

  import "testing"

  func TestCalculate(t *testing.T) {
      if result := calculate(2, 3, "add"); result != 5 {
          t.Errorf("expected 5, got %d", result)
      }
  }

  func BenchmarkCalculate(b *testing.B) {
      for i := 0; i < b.N; i++ {
          calculate(2, 3, "add")
      }
  }
  ```

  ### JUnit (Java)
  ```java
  import org.junit.jupiter.api.Test;
  import static org.junit.jupiter.api.Assertions.assertEquals;

  class CalculatorTest {
      @Test
      void testAdd() {
          assertEquals(5, Calculator.calculate(2, 3, "add"));
      }
  }
  ```

  ### Integration Testing
  ```bash
  # Docker compose for testing
  docker-compose -f docker-compose.test.yml up --abort-on-container-exit

  # Database testing
  pytest --db-url=postgresql://test:test@localhost/test_db
  ```


entity_id: ent_20260526T183835673459_59f70b26
type: memory
category: debian/cicd
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:35.673459
updated_at: 2026-05-26T18:38:35.673459
content:
  ## Debian CI/CD Setup
  ### GitHub Actions
  ```yaml
  # .github/workflows/ci.yml
  name: CI
  on: [push, pull_request]

  jobs:
    test:
      runs-on: ubuntu-latest
      steps:
        - uses: actions/checkout@v4
        - name: Setup Python
          uses: actions/setup-python@v5
          with:
            python-version: '3.12'
        - name: Install deps
          run: pip install -r requirements.txt
        - name: Test
          run: pytest tests/ --cov=app
        - name: Lint
          run: flake8 app/ && black --check app/
  ```

  ### GitLab CI
  ```yaml
  # .gitlab-ci.yml
  stages: [test, build, deploy]

  test:
    stage: test
    script:
      - pip install -r requirements.txt
      - pytest tests/
    artifacts:
      paths: [coverage.html]
  ```

  ### Jenkins
  ```groovy
  // Jenkinsfile
  pipeline {
      agent any
      stages {
          stage('Test') {
              steps {
                  sh 'pip install -r requirements.txt'
                  sh 'pytest tests/'
              }
          }
          stage('Deploy') {
              steps {
                  sh 'ssh deploy@server "cd /app && git pull"'
              }
          }
      }
  }
  ```

  ### Local Development CI
  ```bash
  # Pre-commit hooks
  pip install pre-commit
  pre-commit install

  # .pre-commit-config.yaml
  repos:
    - repo: https://github.com/psf/black
      rev: 23.12.0
      hooks:
        - id: black
    - repo: https://github.com/pycqa/flake8
      rev: 7.0.0
      hooks:
        - id: flake8
  ```


entity_id: ent_20260526T183835871374_52389db1
type: memory
category: debian/db-dev
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:35.871374
updated_at: 2026-05-26T18:38:35.871374
content:
  ## Debian Database Development
  ### PostgreSQL
  ```bash
  # Install
  sudo apt install postgresql postgresql-contrib

  # Create database
  sudo -u postgres psql
  CREATE DATABASE myapp;
  CREATE USER appuser WITH PASSWORD 'password';
  GRANT ALL PRIVILEGES ON DATABASE myapp TO appuser;

  # Connect
  psql -U appuser -d myapp

  # Backup/restore
  pg_dump myapp > backup.sql
  psql myapp < backup.sql
  ```

  ### MySQL/MariaDB
  ```bash
  # Install
  sudo apt install mariadb-server mariadb-client

  # Secure installation
  sudo mysql_secure_installation

  # Create database
  mysql -u root -p
  CREATE DATABASE myapp;
  CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'password';
  GRANT ALL PRIVILEGES ON myapp.* TO 'appuser'@'localhost';
  ```

  ### Redis
  ```bash
  sudo apt install redis-server
  redis-cli SET key value
  redis-cli GET key
  ```

  ### SQLite
  ```bash
  sudo apt install sqlite3
  sqlite3 myapp.db
  CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
  ```

  ### Database Migrations
  ```bash
  # Alembic (Python/SQLAlchemy)
  pip install alembic
  alembic init alembic
  alembic revision --autogenerate -m "create users"
  alembic upgrade head

  # Prisma (Node.js)
  npm install prisma @prisma/client
  npx prisma init
  npx prisma migrate dev --name init
  ```

  ### MongoDB
  ```bash
  # Install from MongoDB repo
  curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
  echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] http://repo.mongodb.org/apt/debian bookworm/mongodb-org/7.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
  sudo apt update && sudo apt install mongodb-org
  ```


entity_id: ent_20260526T183836070248_e3067fcd
type: memory
category: debian/web-dev
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:36.070248
updated_at: 2026-05-26T18:38:36.070248
content:
  ## Debian Web Development Stack
  ### Python Web Frameworks
  ```bash
  # Flask
  pip install flask flask-cors flask-sqlalchemy
  python app.py

  # FastAPI
  pip install fastapi uvicorn[standard]
  uvicorn main:app --reload

  # Django
  pip install django
  django-admin startproject myproject
  python manage.py runserver
  ```

  ### Nginx Configuration
  ```nginx
  server {
      listen 80;
      server_name example.com;

      location / {
          proxy_pass http://127.0.0.1:8080;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
      }

      location /static {
          alias /var/www/static;
          expires 30d;
      }
  }
  ```

  ### Apache Configuration
  ```apache
  <VirtualHost *:80>
      ServerName example.com
      DocumentRoot /var/www/html

      <Directory /var/www/html>
          AllowOverride All
          Require all granted
      </Directory>
  </VirtualHost>
  ```

  ### Node.js Development
  ```bash
  # Express server setup
  npm init -y
  npm install express cors helmet morgan

  # Development
  npm install --save-dev nodemon
  npm run dev

  # TypeScript
  npm install --save-dev typescript @types/node @types/express
  npx tsc --init
  ```

  ### Static Site Generation
  ```bash
  # Hugo
  sudo apt install hugo
  hugo new site mysite
  cd mysite
  hugo server

  # Jekyll
  sudo apt install ruby-full
  gem install jekyll
  jekyll new mysite
  ```

  ### SSL/TLS
  ```bash
  # Let's Encrypt
  sudo apt install certbot python3-certbot-nginx
  sudo certbot --nginx -d example.com
  sudo certbot renew --dry-run
  ```


entity_id: ent_20260526T183836269048_a41b8cf0
type: memory
category: debian/api-dev
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:36.269048
updated_at: 2026-05-26T18:38:36.269048
content:
  ## Debian API Development
  ### REST API with FastAPI
  ```python
  from fastapi import FastAPI, HTTPException
  from pydantic import BaseModel
  from typing import List

  app = FastAPI(title="My API")

  class Item(BaseModel):
      id: int
      name: str
      price: float

  @app.get("/items", response_model=List[Item])
  async def get_items():
      return [{"id": 1, "name": "Widget", "price": 9.99}]

  @app.post("/items")
  async def create_item(item: Item):
      return item

  @app.get("/items/{item_id}")
  async def get_item(item_id: int):
      return {"id": item_id, "name": "Widget"}
  ```

  ### GraphQL
  ```bash
  pip install strawberry-graphql uvicorn

  # server.py
  import strawberry
  import uvicorn

  @strawberry.type
  class Query:
      @strawberry.field
      def hello(self) -> str:
          return "Hello World!"

  schema = strawberry.Schema(query=Query)
  uvicorn.run(strawberry.asgi.GraphQL(schema), host="0.0.0.0", port=8000)
  ```

  ### gRPC
  ```bash
  # Install
  pip install grpcio grpcio-tools

  # Generate from proto
  python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. service.proto

  # Server
  python server.py

  # Client
  python client.py
  ```

  ### API Testing
  ```bash
  # curl
  curl -X POST http://localhost:8000/items \
    -H "Content-Type: application/json" \
    -d '{"name": "Widget", "price": 9.99}'

  # httpie
  pip install httpie
  http POST localhost:8000/items name="Widget" price:=9.99

  # Postman Newman
  npm install -g newman
  newman run collection.json
  ```

  ### API Documentation
  ```bash
  # Swagger/OpenAPI
  pip install drf-yasg

  # Redoc
  pip install fastapi-redoc
  ```


entity_id: ent_20260526T183836470433_11cf8d9b
type: memory
category: debian/sysprog
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:36.470433
updated_at: 2026-05-26T18:38:36.470433
content:
  ## Debian System Programming
  ### C Development
  ```bash
  # Install toolchain
  sudo apt install build-essential gcc g++ gdb valgrind
  sudo apt install libc6-dev linux-headers-$(uname -r)

  # Compile with all warnings
  gcc -Wall -Wextra -Werror -O2 -g -o myapp myapp.c

  # Static analysis
  gcc -fsanitize=address,undefined myapp.c -o myapp
  ./myapp  # Detects memory errors
  ```

  ### Kernel Module Development
  ```bash
  sudo apt install linux-headers-$(uname -r) build-essential

  # Makefile
  obj-m += mymodule.o
  KDIR := /lib/modules/$(shell uname -r)/build

  all:
      make -C $(KDIR) M=$(PWD) modules

  clean:
      make -C $(KDIR) M=$(PWD) clean

  # Load/unload
  sudo insmod mymodule.ko
  sudo rmmod mymodule
  dmesg | tail
  ```

  ### System Calls & Libraries
  ```bash
  # strace system calls
  strace -f ./myapp

  # ltrace library calls
  ltrace -f ./myapp

  # ld.so cache
  ldconfig -p | grep library_name

  # Shared library development
  gcc -shared -fPIC -o libmylib.so mylib.c
  gcc -L. -lmylib -o myapp main.c
  ```

  ### Performance Tools
  ```bash
  # perf profiling
  sudo perf record -g ./myapp
  sudo perf report

  # Flame graphs
  sudo apt install linux-perf
  sudo perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg

  # eBPF (advanced)
  sudo apt install bcc-tools libbcc-examples
  sudo bpftrace -e 'tracepoint:syscalls:sys_enter_open { printf("%s opened %s", comm, str(args.filename)); }'
  ```

  ### Memory Management
  ```c
  // C memory management example
  #include <stdio.h>
  #include <stdlib.h>

  void* safe_malloc(size_t size) {
      void* ptr = malloc(size);
      if (!ptr) {
          fprintf(stderr, "malloc failed: %zu bytes\n", size);
          exit(1);
      }
      return ptr;
  }
  ```


entity_id: ent_20260526T183836667767_e29aa4b2
type: memory
category: debian/editors
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:36.667767
updated_at: 2026-05-26T18:38:36.667767
content:
  ## Debian IDEs & Editors
  ### VS Code Setup
  ```json
  // settings.json
  {
      "editor.formatOnSave": true,
      "editor.defaultFormatter": "esbenp.prettier-vscode",
      "files.autoSave": "afterDelay",
      "terminal.integrated.shell.linux": "/bin/bash",
      "python.defaultInterpreterPath": "/home/user/project/venv/bin/python",
      "go.useLanguageServer": true
  }
  ```

  ### Vim Configuration
  ```vim
  " ~/.vimrc
  set number
  set relativenumber
  set tabstop=4
  set shiftwidth=4
  set expandtab
  set autoindent
  syntax on
  filetype plugin indent on
  set wildmenu
  set wildmode=list:longest

  " Plugins (with vim-plug)
  call plug#begin()
  Plug 'preservim/nerdtree'
  Plug 'vim-airline/vim-airline'
  Plug 'junegunn/fzf'
  call plug#end()
  ```

  ### Neovim (Modern)
  ```lua
  -- ~/.config/nvim/init.lua
  require('lspconfig').pyright.setup{}
  require('lspconfig').gopls.setup{}
  require('lspconfig').ts_ls.setup{}
  ```

  ### Emacs
  ```elisp
  ;; ~/.emacs
  (use-package magit)
  (use-package lsp-mode
    :commands lsp)
  ```

  ### Micro Editor
  ```bash
  sudo apt install micro
  micro -settingsFile  # Config
  ```


entity_id: ent_20260526T183836865856_e0d54fb3
type: memory
category: debian/dev-security
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:36.865856
updated_at: 2026-05-26T18:38:36.865856
content:
  ## Debian Development Security
  ### Secure Coding Practices
  ```python
  # Input validation
  import re

  def validate_email(email: str) -> bool:
      pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
      return bool(re.match(pattern, email))

  # Parameterized queries (prevent SQL injection)
  cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))

  # Hash passwords
  from passlib.hash import bcrypt
  hashed = bcrypt.hash(password)
  bcrypt.verify(password, hashed)
  ```

  ### Security Tools
  ```bash
  # Install security tools
  sudo apt install openssl sslscan nmap nikto burpsuite

  # Dependency scanning
  pip install safety bandit
  safety check
  bandit -r app/

  # JavaScript security
  npm audit
  npm install --save-dev eslint-plugin-security

  # Container scanning
  docker scan myimage
  trivy myimage

  # Secrets detection
  git config core.hooksPath .githooks
  pip install pre-commit
  pre-commit install
  ```

  ### SSL/TLS Development
  ```bash
  # Generate self-signed cert
  openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

  # Generate CSR
  openssl req -new -newkey rsa:4096 -nodes -keyout domain.key -out domain.csr

  # Check certificate
  openssl s_client -connect example.com:443 -servername example.com
  ```

  ### Secure Headers
  ```nginx
  add_header X-Frame-Options "DENY" always;
  add_header X-Content-Type-Options "nosniff" always;
  add_header X-XSS-Protection "1; mode=block" always;
  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
  add_header Content-Security-Policy "default-src 'self'" always;
  ```

  ### Authentication
  ```python
  # JWT tokens
  import jwt

  payload = {
      "user_id": 123,
      "exp": datetime.utcnow() + timedelta(hours=1)
  }
  token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")

  # OAuth2
  pip install authlib
  ```


entity_id: ent_20260526T183837067622_1e5dee90
type: memory
category: debian/devops-dev
strength: moderate
metadata: "{\"source\": \"debian_dev_deep_dive\"}"
created_at: 2026-05-26T18:38:37.067622
updated_at: 2026-05-26T18:38:37.067622
content:
  ## Debian DevOps for Developers
  ### Infrastructure as Code
  ```bash
  # Terraform
  wget https://releases.hashicorp.com/terraform/1.7.0/terraform_1.7.0_linux_amd64.zip
  sudo unzip terraform_1.7.0_linux_amd64.zip -d /usr/local/bin/

  # Ansible
  sudo apt install ansible
  ansible --version
  ```

  ### Monitoring Stack
  ```bash
  # Prometheus + Grafana
  sudo apt install prometheus grafana

  # Node exporter
  wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz

  # Application monitoring
  pip install prometheus-client
  ```

  ### Log Management
  ```bash
  # ELK Stack
  sudo apt install elasticsearch logstash kibana

  # Vector (modern alternative)
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  cargo install vector

  # Loki + Promtail
  sudo apt install loki promtail
  ```

  ### GitOps
  ```bash
  # ArgoCD
  kubectl create namespace argocd
  kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

  # Flux
  flux install
  ```

  ### Developer Dashboard
  ```bash
  # k9s (Kubernetes CLI)
  wget https://github.com/derailed/k9s/releases/latest/download/k9s_Linux_amd64.tar.gz

  # helm
  curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
  ```


entity_id: ent_20260526T184647738038_5f44e4c5
type: memory
category: kernel/architecture
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:47.738038
updated_at: 2026-05-26T18:46:47.738038
content:
  ## Linux Kernel Architecture
  ### Two Execution Domains
  - **User Space:** Applications, libraries (glibc), shell, daemons
  - **Kernel Space:** Kernel core, device drivers, filesystem modules, network stack

  ### Transition Mechanisms
  - **System Calls:** Voluntary (read, write, fork, mmap)
  - **Interrupts:** Involuntary (hardware timer, disk I/O completion)
  - **Exceptions:** Involuntary (page fault, division by zero, segfault)
  - **Traps:** Deliberate exceptions (int 3 for debugging)

  ### Kernel Layout in Memory
  ```
  High Memory
  ┌─────────────────────────┐
  │  User Space (up to ~120GB on x86_64) │  ← 3:1 split (CONFIG_VMSPLIT_3G)
  ├─────────────────────────┤  ← USER_DS boundary (TASK_SIZE)
  │  Kernel Space (~3GB)     │
  │  ┌───────────────────┐   │
  │  │ Module Region      │   │ ← Loadable modules
  │  ├───────────────────┤   │
  │  │ vmalloc Region     │   │ ← Non-contiguous virtual memory
  │  ├───────────────────┤   │
  │  │ Fixed Mappings     │   │ ← PCI, VGA, PKMAP
  │  ├───────────────────┤   │
  │  │ Direct Mapping     │   │ ← 1:1 mapping of physical RAM
  │  └───────────────────┘   │
  └─────────────────────────┘
  Low Memory (0)
  ```

  ### Core Subsystems
  - **VFS:** Virtual Filesystem abstraction layer
  - **Memory Management:** Page allocation, VM, swap, page cache
  - **Process Management:** Tasks, scheduling, signals, namespaces
  - **Networking:** Socket API, TCP/IP stack, netfilter/iptables
  - **Device Drivers:** char, block, network drivers; sysfs/udev
  - **Syscall Interface:** syscall table, seccomp filters, ptrace
  - **Security:** SELinux/AppArmor (LSM), capabilities, seccomp

  ### Monolithic + Loadable Modules
  - Core kernel is monolithic — everything runs in kernel space
  - Loadable modules (`.ko`) loaded with `modprobe`/`insmod`
  - Module lifecycle: `init_module()` → `sys_initcall()` → `cleanup_module()`


entity_id: ent_20260526T184647949240_0cbfe2ba
type: memory
category: kernel/processes
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:47.949240
updated_at: 2026-05-26T18:46:47.949240
content:
  ## Kernel Process Management
  ### The task_struct (Core Kernel Data Structure)
  ```c
  struct task_struct {
      volatile long state;       // TASK_RUNNING, TASK_INTERRUPTIBLE, TASK_UNINTERRUPTIBLE
      struct thread_info *thread_info;
      atomic_t usage;            // Reference count
      unsigned int flags;        // PF_KTHREAD, PF_FORKNOEXEC, etc.
      unsigned int policy;       // SCHED_NORMAL, SCHED_FIFO, SCHED_RR
      cpumask_t cpus_allowed;    // CPU affinity mask
      pid_t pid;                 // Process ID
      pid_t tgid;                // Thread group ID
      struct task_struct *parent;// Parent process
      struct list_head children; // Children processes
      struct mm_struct *mm;      // Memory descriptor (NULL for kernel threads)
      struct signal_struct *signal;
      // ... 300+ more fields (~5KB+ per task)
  };
  ```

  ### Process States
  ```
    fork()
      │
      ▼
  ┌──────────┐    schedule()    ┌──────────────────┐
  │  NEW     │ ──────────────►  │   TASK_RUNNING    │
  └──────────┘                  │  (Ready/Running)  │
                                └──────────────────┘
                                           │
                       ┌───────────────────┼───────────────────┐
                       ▼                   ▼                   ▼
                ┌──────────────┐  ┌──────────────────┐  ┌────────────────┐
                │INTERRUPTIBLE │  │UNINTERRUPTIBLE   │  │   TASK_ZOMBIE  │
                │(waiting I/O) │  │(D state, lock)   │  │  (exit, wait)  │
                └──────────────┘  └──────────────────┘  └────────────────┘
                       │                   │                   ▲
                       └───────────────────┴───────────────────┘
                                           ▼
                                     ┌──────────┐
                                     │ EXITED   │
                                     └──────────┘
  ```

  ### Context Switch Flow
  ```
  1. Scheduler picks next task (pick_next_task)
  2. Save current task state:
     - CPU registers → current->thread
     - MMU context (CR3 = page table base)
     - FPU state (lazy switch)
  3. Update RCU, runqueue accounting
  4. Load next task state:
     - CR3 = next->thread.pgd (switch page tables)
     - Restore registers from next->thread
     - Jump to next task's instruction pointer
  5. RCU quiescent state notification
  ```

  ### PID Namespace Hierarchy
  ```
  Init PID NS:  PID 1 = systemd
    └── Container PID NS: PID 1 = container-init
          ├── PID 2 = process A
          └── PID 3 = process B
  ```
  ```bash
  # View PID namespaces
  ls -l /proc/$$/ns/pid
  # Create PID namespace
  unshare --pid --fork bash
  ```

  ### Process Accounting
  ```bash
  # Per-process resource usage
  ps -eo pid,ppid,user,stat,%cpu,%mem,rss,comm
  # Process tree
  ps auxf
  # Kernel threads vs user processes
  ps -eLf | grep -c 'kernel'
  ```


entity_id: ent_20260526T184648152983_3e6bec33
type: memory
category: kernel/scheduler
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:48.152983
updated_at: 2026-05-26T18:46:48.152983
content:
  ## Linux CPU Scheduler (CFS - Completely Fair Scheduler)
  ### CFS Core Concepts
  - **vruntime:** Virtual runtime — each task accumulates execution time proportional to its share
  - **Priority:** Nice values (-20 to +19) map to weight multipliers
  - **Target latency:** ~24ms default (sched_latency_ns)
  - **Minimum granularity:** ~2ms (sched_min_granularity_ns)

  ### CFS Data Structures
  ```
  root
   └── cfs_rq (per-CPU runqueue)
        ├── rb_root (red-black tree of tasks, sorted by vruntime)
        ├── min_vruntime (fair vruntime baseline)
        ├── nr_running (number of tasks)
        ├── load.weight (total load)
        └── tasks:
             ├── rb_left, rb_right (RB tree nodes)
             └── key = vruntime
  ```

  ### Nice Value → Weight Mapping
  | Nice | Weight | CPU Share (relative) |
  |------|--------|---------------------|
  | -20  | 13954  | ~34x more than +19 |
  | -10  | 3908   | ~9.6x more than 0  |
  |  0   | 1024   | baseline            |
  | +10  | 316    | ~0.3x of baseline   |
  | +19  | 2      | minimum share       |

  ### Scheduling Classes (Priority Order)
  1. **stop:** Preemption stop, hotplug CPU (highest)
  2. **dl:** Deadline scheduler (real-time with deadlines)
  3. **rt:** SCHED_FIFO, SCHED_RR (hard real-time)
  4. **fair:** CFS (normal processes) — DEFAULT
  5. **idle:** SCHED_IDLE (background tasks)

  ### Key Parameters (`/proc/sys/kernel/`)
  ```bash
  # Scheduler tuning
  sysctl kernel.sched_latency_ns       # Target latency (default ~24ms)
  sysctl kernel.sched_min_granularity_ns  # Min time slice
  sysctl kernel.sched_wakeup_granularity_ns
  sysctl kernel.sched_migration_cost_ns   # Task migration cost
  sysctl kernel.sched_tunable_scaling     # 0=none, 1=log, 2=linear

  # CPU capacity (EAS - Energy Aware Scheduling)
  cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_available_frequencies
  ```

  ### Scheduler Tracing
  ```bash
  # Trace scheduling decisions
  echo 1 > /sys/kernel/debug/tracing/events/sched/sched_switch/enable
  cat /sys/kernel/debug/tracing/trace_pipe

  # perf scheduling
  perf sched record
  perf sched latency
  perf sched timehist
  ```


entity_id: ent_20260526T184648355668_bbfa1792
type: memory
category: kernel/memory
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:48.355668
updated_at: 2026-05-26T18:46:48.355668
content:
  ## Kernel Memory Management
  ### Memory Hierarchy
  ```
  CPU Registers (L0)
    └── L1 Cache (per-core, 32-64KB)
         └── L2 Cache (per-core, 256KB-1MB)
              └── L3 Cache (shared, 8-64MB)
                   └── Main RAM (physical pages, 4KB)
                        └── Swap / Page cache (disk)
  ```

  ### Page Frame Allocator (Buddy System)
  ```
  Order 0: 4KB    (single page)
  Order 1: 8KB    (2 pages)
  Order 2: 16KB   (4 pages)
  Order 3: 32KB   (8 pages)
  ...
  Order 10: 4MB   (1024 pages)
  Order 20: 4GB   (1M pages)
  Order MAX_ORDER: 512 pages (depends on config)
  ```
  ```c
  // Allocation API
  struct page *alloc_pages(gfp_t gfp_mask, unsigned int order);
  unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order);
  void free_pages(unsigned long addr, unsigned int order);
  ```

  ### GFP Flags (Get Free Pages)
  | Flag | Meaning |
  |------|---------|
  | `__GFP_WAIT` | May sleep |
  | `__GFP_HIGH` | Access emergency reserves |
  | `__GFP_IO` | May start disk I/O |
  | `__GFP_FS` | May call filesystem |
  | `__GFP_MOVABLE` | Page can be migrated |
  | `__GFP_ZERO` | Zero the page |

  ### Slab Allocator
  ```
  kmalloc() → slab cache (kmalloc-32, kmalloc-64, ..., kmalloc-131072)
  kmem_cache_alloc() → custom slab cache
  vmalloc() → non-contiguous virtual memory (pages allocated separately)

  // Slab statistics
  cat /proc/slabinfo
  ```

  ### Page Cache & Buffer Cache
  ```
  File read flow:
    open() → page cache lookup → 
      HIT: return cached page (page cache hit)
      MISS: buffer cache → read from disk → populate page cache

  // Page cache stats
  cat /proc/meminfo | grep -E "(Page|Cache|Swap)"
  ```

  ### Virtual Memory Management
  ```
  User VMA (Virtual Memory Area) types:
    VM_READ, VM_WRITE, VM_EXEC, VM_SHARED, VM_STACK, VM_IO

  Page fault handling:
    1. CPU triggers page fault (exception)
    2. do_page_fault() → find VMA
    3. do_anonymous_page() or filemap_fault()
    4. Page table entry updated
    5. Faulting instruction restarted
  ```

  ### Memory Cgroups
  ```bash
  # Cgroup v2 memory limits
  echo 1G > /sys/fs/cgroup/memory.limit_in_bytes
  echo 2G > /sys/fs/cgroup/memory.memsw.limit_in_bytes  # memory + swap

  # OOM killer
  cat /proc/sys/vm/overcommit_memory  # 0=heuristic, 1=always, 2=strict
  cat /proc/sys/vm/overcommit_ratio   # For mode 2
  ```


entity_id: ent_20260526T184648561915_1969e631
type: memory
category: kernel/vfs
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:48.561915
updated_at: 2026-05-26T18:46:48.561915
content:
  ## Virtual Filesystem (VFS) Layer
  ### VFS Abstraction
  ```
  Application (open, read, write, lstat, readdir)
      │
      ▼
  ┌─────────────────────────────────────────┐
  │         VFS Layer (Generic)              │
  │  ┌─────────┐ ┌──────────┐ ┌────────┐    │
  │  │ inode   │ │ dentry   │ │ file   │    │
  │  └────┬────┘ └─────┬────┘ └───┬────┘    │
  ├───────┼────────────┼──────────┼─────────┤
  │       ▼            ▼          ▼         │
  │  ┌─────────┐  ┌─────────┐  ┌────────┐  │
  │  │ext4     │  │xfs      │  │btrfs   │  │
  │  │nfs      │  │proc     │  │sysfs   │  │
  │  │tmpfs    │  │debugfs  │  │cgroup  │  │
  │  └─────────┘  └─────────┘  └────────┘  │
  └─────────────────────────────────────────┘
  ```

  ### Core VFS Structures
  ```c
  // inode - on-disk file metadata
  struct inode {
      dev_t i_rdev;           // Device number (char/block devices)
      umode_t i_mode;         // File type + permissions
      uid_t i_uid;            // Owner
      gid_t i_gid;            // Group
      unsigned int i_nlink;   // Hard links
      loff_t i_size;          // File size
      struct timespec i_atime, i_mtime, i_ctime;
      struct super_block *i_sb;  // Filesystem it belongs to
      struct inode_operations *i_op;  // Filesystem-specific ops
      struct file_operations *i_fop;
  };

  // dentry - directory entry (cached path resolution)
  struct dentry {
      struct inode *d_inode;         // NULL if negative
      struct dentry *d_parent;       // Parent directory
      struct qstr d_name;            // Filename
      struct dentry_operations *d_op;
  };

  // file - open file description
  struct file {
      struct inode *f_inode;
      loff_t f_pos;                  // File offset
      struct file_operations *f_op;  // Filesystem-specific ops
      mode_t f_mode;                 // FMODE_READ, FMODE_WRITE
      unsigned int f_flags;          // O_RDONLY, O_WRONLY, O_RDWR
  };
  ```

  ### Filesystem Operations
  ```c
  // super_operations (mount/umount)
  struct super_operations {
      struct inode *(*alloc_inode)(struct super_block *);
      void (*destroy_inode)(struct inode *);
      void (*write_inode)(struct inode *, int);
      void (*drop_inode)(struct inode *);
      int (*statfs)(struct dentry *, struct kstatfs *);
      int (*remount_fs)(struct super_block *, int *, char *);
  };

  // inode_operations (metadata)
  struct inode_operations {
      int (*mkdir)(struct inode *, struct dentry *, umode_t);
      int (*rmdir)(struct inode *, struct dentry *);
      int (*create)(struct inode *, struct dentry *, umode_t, bool);
      int (*unlink)(struct inode *, struct dentry *);
      int (*symlink)(struct inode *, struct dentry *, const char *);
  };

  // file_operations (data access)
  struct file_operations {
      loff_t (*llseek)(struct file *, loff_t, int);
      ssize_t (*read)(struct file *, char __user *, size_t, loff_t *);
      ssize_t (*write)(struct file *, const char __user *, size_t, loff_t *);
      int (*open)(struct inode *, struct file *);
      int (*release)(struct inode *, struct file *);
      long (*unlocked_ioctl)(struct file *, unsigned int, unsigned long);
  };
  ```

  ### Virtual Filesystems
  | VFS | Purpose | Mount Point |
  |-----|---------|-------------|
  | proc | Process info, kernel params | /proc |
  | sysfs | Device/driver hierarchy | /sys |
  | debugfs | Kernel debugging | /sys/kernel/debug |
  | tmpfs | RAM-backed filesystem | /tmp, /run |
  | cgroup | Control groups | /sys/fs/cgroup |
  | devpts | Pseudo-terminals | /dev/pts |
  | fuse | Userspace filesystem | Any |


entity_id: ent_20260526T184648765938_5caeeb0d
type: memory
category: kernel/interrupts
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:48.765938
updated_at: 2026-05-26T18:46:48.765938
content:
  ## Kernel Interrupt Handling
  ### Interrupt Flow
  ```
  Hardware Signal (IRQ)
      │
      ▼
  APIC / PIC (Interrupt Controller)
      │
      ▼
  Exception Table → IDT (Interrupt Descriptor Table)
      │
      ▼
  Top Half (Interrupt Handler) — FAST, atomic, no sleeping
      │
      ├── Run immediately at interrupt context
      ├── Acknowledge hardware
      ├── Disable specific interrupt
      └── Schedule Bottom Half
      
      ▼
  Bottom Half — Can sleep, longer work
      ├── tasklet
      ├── workqueue
      └── softirq
  ```

  ### Bottom Half Mechanisms
  | Type | Preemption | Sleeping | Use Case |
  |------|-----------|----------|----------|
  | Softirq | Disabled | No | Network RX/TX, scheduler |
  | Tasklet | Disabled | No | Driver deferred work |
  | Workqueue | Enabled | Yes | Filesystem, block I/O |

  ### Interrupt Handling Code
  ```c
  // Request interrupt line
  int request_irq(unsigned int irq, irq_handler_t handler,
                  unsigned long flags, const char *name, void *dev_id);

  // Interrupt handler
  irqreturn_t my_handler(int irq, void *dev_id) {
      // Top half — quick, acknowledge hardware
      disable_irq(irq);
      
      // Schedule bottom half
      tasklet_schedule(&my_tasklet);
      // or queue_work(my_wq, &my_work);
      // or raise_softirq(MY_SOFTIRQ);
      
      return IRQ_HANDLED;
  }

  // Tasklet (bottom half)
  void my_tasklet_fn(unsigned long data) {
      // Can do more work, but still no sleeping
      // Re-enable interrupt
      enable_irq(irq);
  }
  ```

  ### Interrupt Monitoring
  ```bash
  # View interrupt counts
  cat /proc/interrupts

  # Softirq statistics
  cat /proc/softirqs

  # IRQ affinity (which CPU handles which IRQ)
  cat /proc/irq/23/smp_affinity

  # Interrupt latency
  cyclictest -p 99 -m -q
  ```

  ### MSI/MSI-X (Message Signaled Interrupts)
  - PCI devices send write to memory-mapped address instead of pin interrupt
  - MSI: Single interrupt vector per device
  - MSI-X: Multiple vectors (up to 2048), per-queue
  - Reduces interrupt contention on multi-core systems


entity_id: ent_20260526T184648971470_d585e64e
type: memory
category: kernel/sync
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:48.971470
updated_at: 2026-05-26T18:46:48.971470
content:
  ## Kernel Synchronization Primitives
  ### Primitive Selection Guide
  ```
  Need to protect data?
  ├── Single CPU, interrupts? → local_irq_save()/local_irq_restore()
  ├── Multiple CPUs, fast critical section?
  │   ├── Read-heavy → RCU (Read-Copy-Update)
  │   ├── Short critical section → spin_lock()
  │   └── Need to sleep → mutex_lock()
  ├── Multiple CPUs, may sleep?
  │   ├── Contended → mutex_lock() or completion
  │   └── Wait for event → wait_queue
  └── Ordering, not mutual exclusion? → memory barriers
  ```

  ### Spinlocks
  ```c
  // Basic spinlock
  spinlock_t my_lock = SPIN_LOCK_UNLOCKED;
  spin_lock(&my_lock);
      // Critical section — NO SLEEPING ALLOWED
  spin_unlock(&my_lock);

  // Variants
  spin_lock_irqsave(&lock, flags);  // Disable IRQs + lock
  spin_lock_bh(&lock);               // Disable bottom halves + lock
  read_lock(&rwlock);                // Multiple readers allowed
  write_lock(&rwlock);               // Exclusive writer
  ```

  ### Mutexes
  ```c
  // Basic mutex (can sleep)
  struct mutex my_mutex;
  mutex_init(&my_mutex);
  mutex_lock(&my_mutex);
      // Critical section — CAN SLEEP
  mutex_unlock(&my_mutex);

  // Non-blocking variant
  int ret = mutex_trylock(&my_mutex);  // Returns 0 if already locked
  ```

  ### RCU (Read-Copy-Update)
  ```c
  // Writer side
  struct my_data *old = rcu_dereference(globals.pointer);
  struct my_data *new = allocate_new_data();
  *new = *old;
  modify(new);
  rcu_assign_pointer(globals.pointer, new);
  synchronize_rcu();  // Wait for all readers to finish
  kfree(old);

  // Reader side (no locking needed!)
  struct my_data *p = rcu_dereference(globals.pointer);
  read_data(p);  // Fast path — no locking
  rcu_read_unlock();
  ```

  ### Atomic Operations
  ```c
  atomic_t count = ATOMIC_INIT(0);
  atomic_inc(&count);
  atomic_dec(&count);
  int val = atomic_read(&count);
  atomic_set(&count, 42);
  bool was_zero = atomic_dec_and_test(&count);  // Returns true if result == 0
  ```

  ### Memory Barriers
  ```c
  barrier();           // Compiler barrier (no CPU reordering)
  smp_rmb();           // Read memory barrier
  smp_wmb();           // Write memory barrier
  smp_mb();            // Full memory barrier
  dma_rmb();           // DMA read barrier
  ```

  ### Completion & Wait Queues
  ```c
  // Completion
  struct completion done;
  init_completion(&done);
      // ... do work ...
  complete(&done);
  wait_for_completion(&done);  // Blocks until complete()

  // Wait queue
  DECLARE_WAIT_QUEUE_HEAD(my_wait);
  wait_event_interruptible(my_wait, condition);
  wake_up_interruptible(&my_wait);
  ```


entity_id: ent_20260526T184649174804_45bede6e
type: memory
category: kernel/network-stack
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:49.174804
updated_at: 2026-05-26T18:46:49.174804
content:
  ## Kernel Networking Stack
  ### Packet Flow (Transmit)
  ```
  Application socket (send())
      │
      ▼
  ┌──────────────────────────────────────────────┐
  │ Socket Layer (AF_INET, AF_UNIX, AF_PACKET)    │
  │   └── sk_buff allocation                     │
  ├──────────────────────────────────────────────┤
  │ Transport Layer (TCP / UDP / SCTP)            │
  │   └── TCP: segmentation, sequencing, retrans │
  │   └── UDP: no processing, just checksum      │
  ├──────────────────────────────────────────────┤
  │ Network Layer (IP, IPsec)                     │
  │   └── IP: routing, fragmentation, TTL        │
  │   └── Routing: fib_lookup() → dst_entry       │
  ├──────────────────────────────────────────────┤
  │ Link Layer (ethernet, 802.1Q, PPP)            │
  │   └── dev_queue_xmit() → netif_tx_queue       │
  ├──────────────────────────────────────────────┤
  │ Device Driver (NIC)                            │
  │   └── Ring buffer → DMA → wire               │
  └──────────────────────────────────────────────┘
  ```

  ### sk_buff Structure (Core Network Packet)
  ```c
  struct sk_buff {
      // Data pointers
      unsigned char *head;    // Start of allocated buffer
      unsigned char *data;    // Start of packet data
      unsigned char *tail;    // End of packet data
      unsigned char *end;     // End of allocated buffer
      
      // Protocol info
      unsigned int len;       // Total packet length
      unsigned int data_len;  // Fragment data length (if any)
      unsigned char protocol; // ETH_P_IP, ETH_P_IPV6, ETH_P_ARP
      
      // Socket info
      struct sock *sk;        // Owning socket
      struct net_device *dev; // Network device
      
      // Queue info
      ktime_t tstamp;         // Timestamp
      struct skb_queue_head *queue;
  };
  ```

  ### Netfilter Hooks (iptables/nftables hooks)
  ```
         ┌──────────────────────────────────────┐
         │          NETWORKING STACK             │
    ┌────▼─────────────────────────────────────▼────┐
    │ PF_INET                                      │
    │                                              │
    │  INPUT    FORWARD    OUTPUT                  │
    │   │          │          │                    │
    │   ▼          ▼          ▼                    │
    │  ┌─────┐  ┌─────┐  ┌─────┐                  │
    │  │hook │  │hook │  │hook │  ← iptables rules │
    │  │1    │  │3    │  │5    │                   │
    │  └──┬──┘  └──┬──┘  └──┬──┘                  │
    │     │        │        │                      │
    │  ┌──▼──┐  ┌─▼───┐  ┌─▼────┐                │
    │  │PRER │  │FWD  │  │POST  │                │
    │  │OUT   │  │     │  │ROUT  │                │
    │  └──┬──┘  └──┬──┘  └──┬──┘                  │
    │     │        │        │                      │
    │  ┌──▼──┐  ┌─▼───┐  ┌─▼────┐                │
    │  │  0  │  │  2  │  │  4   │  ← Hook numbers │
    │  └─────┘  └─────┘  └─────┘                  │
    └──────────────────────────────────────────────┘
  ```

  Hook numbers: 0=PREROUTING, 1=LOCAL_IN, 2=FORWARD, 3=LOCAL_OUT, 4=POSTROUTING

  ### Network Namespaces
  ```bash
  # Create namespace
  ip netns add mynet

  # Create veth pair
  ip link add veth0 type veth peer name veth1
  ip link set veth1 netns mynet
  ip addr add 192.168.100.1/24 dev veth0
  ip netns exec mynet ip addr add 192.168.100.2/24 dev veth1
  ip netns exec mynet ip link set veth1 up

  # Enable forwarding
  echo 1 > /proc/sys/net/ipv4/ip_forward
  ```

  ### TCP State Machine (Kernel)
  ```
  LISTEN → SYN_RECV → ESTABLISHED → FIN_WAIT_1 → FIN_WAIT_2 → TIME_WAIT → CLOSED
                                → CLOSE_WAIT → LAST_ACK → CLOSED
  ```


entity_id: ent_20260526T184649379975_53e1cac5
type: memory
category: kernel/modules
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:49.379975
updated_at: 2026-05-26T18:46:49.379975
content:
  ## Kernel Modules
  ### Module Lifecycle
  ```
  Source (.c) → gcc -c → Object (.o) → modpost → Loadable Module (.ko)
                                                               │
                                                               ▼
                                                       insmod / modprobe
                                                               │
                                                               ▼
                                                       init_module() → module_init()
                                                               │
                                                               ▼
                                                       Running in kernel space
                                                               │
                                                               ▼
                                                       rmmod → cleanup_module() → module_exit()
  ```

  ### Basic Module Template
  ```c
  #include <linux/module.h>
  #include <linux/kernel.h>
  #include <linux/init.h>

  // Module metadata
  MODULE_LICENSE("GPL");
  MODULE_AUTHOR("Author");
  MODULE_DESCRIPTION("Description");
  MODULE_VERSION("1.0");

  // Parameters
  static int my_param = 42;
  module_param(my_param, int, 0644);
  MODULE_PARM_DESC(my_param, "A parameter");

  // Init function (called on insmod)
  static int __init my_module_init(void) {
      printk(KERN_INFO "Module loaded, param=%d\n", my_param);
      return 0;  // 0 = success, -errno = failure
  }

  // Exit function (called on rmmod)
  static void __exit my_module_exit(void) {
      printk(KERN_INFO "Module unloaded\n");
  }

  module_init(my_module_init);
  module_exit(my_module_exit);
  ```

  ### Makefile for Modules
  ```makefile
  obj-m += my_module.o

  KDIR ?= /lib/modules/$(shell uname -r)/build

  all:
  	make -C $(KDIR) M=$(PWD) modules

  clean:
  	make -C $(KDIR) M=$(PWD) clean

  install:
  	make -C $(KDIR) M=$(PWD) modules_install
  ```

  ### Module Management
  ```bash
  # Load module
  sudo insmod my_module.ko
  sudo modprobe my_module  # From /lib/modules

  # Remove module
  sudo rmmod my_module

  # List loaded modules
  lsmod
  cat /proc/modules

  # Module parameters
  cat /sys/module/my_module/parameters/my_param
  sudo modprobe my_module my_param=100

  # Module dependencies
  modinfo my_module.ko
  depmod  # Update module dependency cache
  ```

  ### Module Symbols
  ```c
  // Export symbol for other modules
  EXPORT_SYMBOL(my_function);
  EXPORT_SYMBOL_GPL(my_gpl_function);  // GPL-only modules can use

  // Use symbol from another module
  extern void other_module_func(void);
  // Or via symbol lookup
  void *sym = symbol_get(other_module_func);
  symbol_put(other_module_func);
  ```


entity_id: ent_20260526T184649583796_34514447
type: memory
category: kernel/boot
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:49.583796
updated_at: 2026-05-26T18:46:49.583796
content:
  ## Kernel Boot Process
  ### Complete Boot Sequence
  ```
  1. BIOS/UEFI
     ├── POST (Power-On Self-Test)
     ├── Load bootloader from disk (MBR/GPT)
     └── Transfer control to bootloader

  2. GRUB2 (Bootloader)
     ├── Stage 1: Boot sector
     ├── Stage 2: /boot/grub/grub.cfg
     ├── Load kernel image (vmlinuz)
     ├── Load initrd (initial RAM disk)
     └── Pass command line parameters

  3. Kernel Decompression
     ├── head_64.S entry point
     ├── Decompress kernel (xz/gzip)
     └── start_kernel() in init/main.c

  4. Early Initialization
     ├── setup_arch() — CPU, memory, MMU
     ├── trap_init() — exception handlers
     ├── mm_init() — page allocator, buddy system
     ├── sched_init() — scheduler
     └── rest_init() — create kernel threads

  5. initcall Execution
     ├── core_initcall() — core subsystems
     ├── fs_initcall() — filesystems
     ├── device_initcall() — devices
     ├── subsys_initcall() — subsystems
     └── late_initcall() — final setup

  6. Switch to Init
     ├── mount root filesystem
     ├── Switch to initrd or real root (/)
     └── execve("/sbin/init", ...) → systemd

  7. systemd
     ├── Target: multi-user.target (CLI) or graphical.target
     ├── Load services (.service units)
     ├── Mount filesystems
     └── Start getty, sshd, etc.
  ```

  ### GRUB Configuration
  ```bash
  # /etc/default/grub
  GRUB_DEFAULT=0
  GRUB_TIMEOUT=5
  GRUB_CMDLINE_LINUX="quiet splash"
  GRUB_CMDLINE_LINUX_DEFAULT=""

  # Update GRUB
  sudo update-grub
  ```

  ### Kernel Command Line Parameters
  | Parameter | Purpose |
  |-----------|---------|
  | `root=/dev/sda1` | Root filesystem |
  | `init=/sbin/init` | Init program |
  | `quiet` | Suppress boot messages |
  | `splash` | Boot splash screen |
  | `nomodeset` | Disable kernel mode setting |
  | `single` | Single-user mode |
  | `debug` | Enable kernel debugging |
  | `mem=4G` | Limit usable memory |
  | `maxcpus=2` | Limit CPUs |
  | `pci=noacpi` | Disable PCI ACPI |

  ### Initrd Contents
  ```
  /boot/initrd.img-$(uname -r)
  ├── init (initramfs script)
  ├── bin/ (busybox)
  ├── lib/ (kernel modules for hardware)
  ├── modules/ (device drivers)
  └── etc/ (fstab, modprobe.conf)
  ```

  ### Boot Debugging
  ```bash
  # View kernel messages
  dmesg | head -50
  journalctl -k --boot=-1

  # Boot in recovery mode
  # Add to kernel cmdline: single init=/bin/bash

  # Check initrd contents
  lsinitramfs /boot/initrd.img-$(uname -r)
  ```


entity_id: ent_20260526T184649787271_c68135e7
type: memory
category: kernel/ebpf
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:49.787271
updated_at: 2026-05-26T18:46:49.787271
content:
  ## eBPF (Extended Berkeley Packet Filter)
  ### What is eBPF?
  - In-kernel bytecode VM — runs sandboxed programs
  - Hooks into kernel events without modifying kernel source
  - Verified by BPF verifier before execution (prevents crashes)
  - Used for networking, tracing, security, observability

  ### eBPF Program Types
  | Type | Use Case |
  |------|----------|
  | `BPF_PROG_TYPE_SOCKET_FILTER` | Packet filtering |
  | `BPF_PROG_TYPE_KPROBE` | Trace kernel functions |
  | `BPF_PROG_TYPE_TRACEPOINT` | Trace kernel tracepoints |
  | `BPF_PROG_TYPE_XDP` | Express Data Path (fast networking) |
  | `BPF_PROG_TYPE_CGROUP_SKB` | Filter by cgroup |
  | `BPF_PROG_TYPE_SCHED_CLS` | TC traffic classification |
  | `BPF_PROG_TYPE_PERF_EVENT` | Performance events |

  ### Basic eBPF Program (C)
  ```c
  #include <linux/bpf.h>
  #include <bpf/bpf_helpers.h>

  // Map to store data
  struct {
      __uint(type, BPF_MAP_TYPE_ARRAY);
      __uint(max_entries, 1);
      __type(key, __u32);
      __type(value, __u64);
  } my_map SEC(".maps");

  SEC("kprobe/sys_execve")
  int kprobe_execve(struct pt_regs *ctx) {
      __u32 key = 0;
      __u64 *count = bpf_map_lookup_elem(&my_map, &key);
      if (count)
          *count += 1;
      return 0;
  }

  char LICENSE[] SEC("license") = "GPL";
  ```

  ### eBPF Maps
  | Map Type | Description |
  |----------|-------------|
  | `BPF_MAP_TYPE_ARRAY` | Fixed-size array |
  | `BPF_MAP_TYPE_HASH` | Hash table |
  | `BPF_MAP_TYPE_PERF_EVENT_ARRAY` | Perf event output |
  | `BPF_MAP_TYPE_RINGBUF` | Ring buffer |
  | `BPF_MAP_TYPE_LPM_TRIE` | Longest prefix match |
  | `BPF_MAP_TYPE_CGROUP_ARRAY` | Cgroup array |

  ### Using bpftrace
  ```bash
  # Trace syscalls
  bpftrace -e 'tracepoint:raw_syscalls:sys_enter { printf("%s %d\n", args->filename, args->pid); }'

  # Trace function calls
  bpftrace -e 'kprobe:do_sys_open { printf("open: %s\n", str(args->filename)); }'

  # Count syscalls by process
  bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @calls[comm] = count(); }'

  # Profile kernel CPU time
  bpftrace -e 'profile:hz:99 { @stack[ustack] = count(); }'
  ```

  ### Using BCC/BPF Compiler Collection
  ```bash
  # Install
  apt install bcc-tools linux-headers-$(uname -r)

  # Built-in tools
  ls /usr/share/bcc/tools/
  # Includes: biosnoop, execsnoop, filelife, offcputime, runqlat, tcpconnlat, etc.

  # Example: Trace open() syscalls
  sudo execsnoop
  sudo filelife
  sudo runqlat
  ```

  ### XDP (Express Data Path)
  ```c
  // XDP program — runs before sk_buff allocation (fastest path)
  SEC("xdp")
  int xdp_prog(struct xdp_md *ctx) {
      void *data = (void *)(long)ctx->data;
      void *data_end = (void *)(long)ctx->data_end;
      
      // Process packet at line rate
      struct ethhdr *eth = data;
      if ((void *)eth + sizeof(*eth) <= data_end) {
          if (eth->h_proto == bpf_htons(ETH_P_IP)) {
              // Drop or redirect
              return XDP_DROP;
          }
      }
      return XDP_PASS;
  }
  ```


entity_id: ent_20260526T184649991325_db18d99a
type: memory
category: kernel/debugging
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:49.991325
updated_at: 2026-05-26T18:46:49.991325
content:
  ## Kernel Debugging
  ### Debugging Toolkit
  | Tool | Purpose |
  |------|---------|
  | printk/dmesg | Kernel logging |
  | ftrace | Function tracing |
  | perf | Performance profiling |
  | kprobes | Dynamic kernel probes |
  | eBPF/bpftrace | Safe kernel tracing |
  | kdb/kgdb | Kernel debugger |
  | crash | Crash dump analysis |
  | lockdep | Lock dependency checker |
  | KASAN | Kernel Address Sanitizer |
  | KCSAN | Kernel Concurrency Sanitizer |

  ### printk Log Levels
  ```c
  printk(KERN_EMERG "Emergency - system unusable\n");      // 0
  printk(KERN_ALERT "Alert - action must be taken\n");     // 1
  printk(KERN_CRIT "Critical - critical condition\n");     // 2
  printk(KERN_ERR "Error - error condition\n");            // 3
  printk(KERN_WARNING "Warning - warning condition\n");    // 4
  printk(KERN_NOTICE "Notice - normal but significant\n"); // 5
  printk(KERN_INFO "Info - informational\n");              // 6
  printk(KERN_DEBUG "Debug - debug-level\n");              // 7

  // View messages
  dmesg
  dmesg -T           // Human-readable timestamps
  dmesg -l err,warn  // Filter by level
  ```

  ### ftrace (Function Tracer)
  ```bash
  # Enable ftrace
  mount -t debugfs debugfs /sys/kernel/debug

  # Available tracers
  cat /sys/kernel/debug/tracing/available_tracers
  # Function: function, function_graph, irqsoff, wakeup, etc.

  # Trace a specific function
  echo function > /sys/kernel/debug/tracing/current_tracer
  echo sched_switch > /sys/kernel/debug/tracing/set_ftrace_filter
  echo 1 > /sys/kernel/debug/tracing/tracing_on

  # View trace
  cat /sys/kernel/debug/tracing/trace

  # Function graph tracer (call hierarchy)
  echo function_graph > /sys/kernel/debug/tracing/current_tracer
  echo do_syscall > /sys/kernel/debug/tracing/set_ftrace_filter

  # Latency tracer
  echo latency_format > /sys/kernel/debug/tracing/trace_options
  ```

  ### perf Profiling
  ```bash
  # CPU profiling
  perf record -a sleep 10
  perf report

  # Trace specific function
  perf record -g -e sched:sched_switch sleep 5

  # Hardware counters
  perf stat -e cpu-cycles,instructions,cache-references,cache-misses ./program

  # Kernel + user profiling
  perf record -g -a -- sleep 10
  perf report --show-total-period

  # Flame graph
  perf record -F 99 -ag sleep 30
  perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg
  ```

  ### KASAN (Kernel Address Sanitizer)
  ```bash
  # Enable in kernel config
  CONFIG_KASAN=y
  CONFIG_KASAN_INLINE=y

  # Detects:
  # - Out-of-bounds accesses
  # - Use-after-free
  # - Memory leaks
  # - Double-free

  # Example output:
  # BUG: KASAN: use-after-free in my_function+0x42/0x80
  # Read of size 8 at addr ffff888012345678 by task my_proc/1234
  ```

  ### Lockdep (Lock Dependency Checker)
  ```bash
  # Enable in kernel config
  CONFIG_PROVE_LOCKING=y
  CONFIG_LOCKDEP=y

  # Detects:
  # - Deadlocks (A→B, B→A)
  # - Inconsistent lock ordering
  # - Recursive locking
  # - Lock held while sleeping

  # Runtime: echo 1 > /proc/sys/kernel/lockdep_enabled
  ```

  ### Crash Dump Analysis
  ```bash
  # Configure kdump
  apt install kdump-tools

  # Analyze crash dump
  crash /boot/vmlinuz-$(uname -r) /var/crash/vmcore

  # Inside crash:
  bt              # Backtrace
  ps              # Process list
  vm              # Virtual memory
  locks           # Held locks
  ```


entity_id: ent_20260526T184650195411_fe727820
type: memory
category: kernel/cgroups-namespaces
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:50.195411
updated_at: 2026-05-26T18:46:50.195411
content:
  ## Cgroups & Namespaces (Container Foundation)
  ### Control Groups (cgroups)
  #### cgroup v2 Hierarchy
  ```
  /sys/fs/cgroup/
  ├── cgroup.controllers     # Available controllers
  ├── cgroup.subtree_control # Enabled controllers
  ├── cpu/
  │   ├── cpu.max            # CPU quota (format: quota period)
  │   ├── cpu.weight         # CPU weight (1-10000)
  │   └── cpu.stat
  ├── memory/
  │   ├── memory.max         # Memory limit
  │   ├── memory.low         # Memory low watermark
  │   ├── memory.high        # Memory high watermark (throttle)
  │   └── memory.swap.max    # Swap limit
  ├── io/
  │   ├── io.max             # I/O bandwidth limit
  │   └── io.weight          # I/O weight
  └── pids/
      └── pids.max           # Max processes
  ```

  #### Setting Limits
  ```bash
  # Create cgroup
  mkdir /sys/fs/cgroup/myapp
  echo "+cpu +memory +pids" > /sys/fs/cgroup/cgroup.subtree_control

  # Set CPU limit (50% of one CPU)
  echo "50000 100000" > /sys/fs/cgroup/myapp/cpu.max

  # Set memory limit
  echo 1G > /sys/fs/cgroup/myapp/memory.max

  # Set process limit
  echo 100 > /sys/fs/cgroup/myapp/pids.max

  # Add process to cgroup
  echo $$ > /sys/fs/cgroup/myapp/cgroup.procs
  ```

  ### Namespaces
  | Namespace | Isolates | sysctl |
  |-----------|----------|--------|
  | PID | Process IDs | CLONE_NEWPID |
  | NET | Network stack | CLONE_NEWNET |
  | MNT | Mount points | CLONE_NEWNS |
  | UTS | Hostname/domain | CLONE_NEWUTS |
  | IPC | SysV IPC, POSIX msg | CLONE_NEWIPC |
  | USER | User/group IDs | CLONE_NEWUSER |
  | TIME | Clocks (v5.6+) | CLONE_NEWTIME |

  #### Namespace Operations
  ```bash
  # Create network namespace
  ip netns add mynet
  ip netns exec mynet ip addr add 10.0.0.1/24 dev eth0

  # Create PID namespace
  unshare --pid --fork bash

  # View namespaces
  ls -l /proc/$$/ns/
  # pid, net, mnt, uts, ipc, user, time

  # Share namespace with another process
  nsenter -t PID -n  # Enter network namespace
  nsenter -t PID -m  # Enter mount namespace
  ```

  ### Seccomp (Secure Computing Mode)
  ```c
  // seccomp-bpf filter example
  #include <linux/seccomp.h>
  #include <linux/filter.h>
  #include <sys/prctl.h>

  // Allow only read, write, exit, sigreturn
  struct sock_fprog prog = {
      .len = 6,
      .filter = filters  // BPF filter program
  };
  prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
  prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
  ```

  ### systemd-run with Resources
  ```bash
  # Run command with cgroup limits
  systemd-run --scope -p MemoryMax=1G -p CPUQuota=50% -p TasksMax=100 my_command

  # Check cgroup
  systemctl status scope-my_command
  systemd-cgtop
  ```


entity_id: ent_20260526T184650400222_85569c2a
type: memory
category: kernel/config
strength: moderate
metadata: "{\"source\": \"kernel_internals_deep_dive\"}"
created_at: 2026-05-26T18:46:50.400222
updated_at: 2026-05-26T18:46:50.400222
content:
  ## Kernel Configuration & Building
  ### Kernel Config Options
  ```bash
  # View current config
  zcat /proc/config.gz  # If available
  cat /boot/config-$(uname -r)

  # Kernel config interfaces
  make menuconfig    # Text-based UI
  make xconfig       # Qt GUI (needs Qt)
  make nconfig       # ncurses UI
  make oldconfig     # Update existing config
  make localmodconfig # Minimize to loaded modules
  make localyesconfig # Same but built-in
  ```

  ### Essential Config Options
  | Option | Purpose |
  |--------|---------|
  | `CONFIG_DEBUG_INFO` | Debug symbols |
  | `CONFIG_FRAME_POINTER` | Frame pointers for backtraces |
  | `CONFIG_KPROBES` | Dynamic kernel probes |
  | `CONFIG_FTRACE` | Function tracer |
  | `CONFIG_BPF_SYSCALL` | eBPF support |
  | `CONFIG_CGROUPS` | Control groups |
  | `CONFIG_NET_NS` | Network namespaces |
  | `CONFIG_BLK_DEV_INITRD` | Initrd support |
  | `CONFIG_KASAN` | Address sanitizer |
  | `CONFIG_LOCKDEP` | Lock dependency checker |
  | `CONFIG_PERF_EVENTS` | Perf profiling |
  | `CONFIG_DEBUG_KERNEL` | Debug features umbrella |

  ### Building a Custom Kernel
  ```bash
  # Get kernel source
  apt install build-essential libncurses-dev bison flex libssl-dev libelf-dev
  apt source linux-image-$(uname -r)
  cd linux-*

  # Configure
  cp /boot/config-$(uname -r) .config
  make oldconfig
  make menuconfig  # Modify as needed

  # Build
  make -j$(nproc) deb-pkg  # Build .deb packages

  # Install
  sudo dpkg -i ../linux-*.deb

  # Or build directly
  make -j$(nproc) bzImage
  make -j$(nproc) modules
  sudo make modules_install
  sudo make install
  ```

  ### Module Blacklisting
  ```bash
  # /etc/modprobe.d/blacklist.conf
  blacklist nvidiafb
  blacklist nouveau

  # Prevent loading
  echo "install nvidia /bin/true" > /etc/modprobe.d/blacklist-nvidia.conf
  update-initramfs -u
  ```

  ### Runtime Config (sysctl)
  ```bash
  # View all parameters
  sysctl -a

  # Common tuning
  sysctl vm.swappiness=10           # Less swap usage
  sysctl net.core.somaxconn=65535   # Connection backlog
  sysctl net.ipv4.tcp_max_syn_backlog=65535
  sysctl fs.file-max=2097152        # Max open files
  sysctl kernel.pid_max=65535       # Max PID

  # Persistent config
  echo "vm.swappiness=10" >> /etc/sysctl.d/99-custom.conf
  sysctl -p /etc/sysctl.d/99-custom.conf
  ```


entity_id: ent_20260526T190512273591_090506d0
type: memory
category: debian/process-fundamentals
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:12.273591
updated_at: 2026-05-26T19:05:12.273591
content:
  ## Linux Process Fundamentals
  ### Process Structure
  - **PID:** Process ID (unique integer)
  - **PPID:** Parent Process ID
  - **PGID:** Process Group ID
  - **SID:** Session ID
  - **UID/GID:** User/Group IDs (real, effective, saved)
  - **TID:** Thread ID (for threads)

  ### Process States
  - **R (Running/Runnable):** On CPU or in run queue
  - **S (Interruptible Sleep):** Waiting for event
  - **D (Uninterruptible Sleep):** Usually I/O (disk)
  - **Z (Zombie):** Terminated, not reaped by parent
  - **T (Stopped):** Stopped by signal (SIGSTOP, SIGTSTP)
  - **I (Idle):** Kernel thread sleeping
  - **X (Dead):** Should not appear (transient)

  ### Process Table
  ```bash
  # View all processes
  ps aux
  ps -ef

  # Process tree
  pstree
  pstree -p          # With PIDs
  pstree -u          # With users
  pstree -p -u       # Both

  # Specific user
  ps -u $USER
  ps -U www-data

  # Specific command
  ps aux | grep nginx
  pgrep -a nginx
  ```

  ### /proc Filesystem
  ```bash
  # Process info
  ls /proc/PID/

  # Key files
  cat /proc/PID/status    # Process status
  cat /proc/PID/cmdline   # Command line
  cat /proc/PID/environ   # Environment
  cat /proc/PID/maps      # Memory mappings
  cat /proc/PID/fd/       # Open file descriptors
  cat /proc/PID/io        # I/O statistics
  cat /proc/PID/smaps     # Detailed memory

  # System-wide
  cat /proc/meminfo       # Memory
  cat /proc/cpuinfo       # CPU info
  cat /proc/loadavg       # Load average
  cat /proc/uptime        # System uptime
  ```

  ### Process Limits
  ```bash
  # Current limits
  ulimit -a

  # Specific limits
  ulimit -n    # Max open files
  ulimit -u    # Max user processes
  ulimit -v    # Max virtual memory
  ulimit -f    # Max file size

  # Set limits
  ulimit -n 65536   # Open files
  ulimit -u 4096    # Processes

  # Persistent (limits.conf)
  nano /etc/security/limits.conf
  * soft nofile 65536
  * hard nofile 65536
  * soft nproc 4096
  * hard nproc 4096
  ```


entity_id: ent_20260526T190512486006_e8e728ae
type: memory
category: debian/process-monitoring
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:12.486006
updated_at: 2026-05-26T19:05:12.486006
content:
  ## Process Monitoring Tools
  ### top (Interactive)
  ```bash
  # Launch
  top

  # Commands inside top
  P        # Sort by CPU
  M        # Sort by memory
  T        # Sort by time
  k PID    # Kill process
  r PID    # Renice process
  c        # Toggle command line
  h        # Help
  q        # Quit

  # One-shot mode
  top -bn1 | head -20
  top -bn1 -o %CPU | head -20    # Sort by CPU
  top -bn1 -o %MEM | head -20    # Sort by memory
  ```

  ### htop (Enhanced)
  ```bash
  # Install
  apt install htop

  # Features
  - Tree view (F5)
  - Filter (F4)
  - Kill (F9)
  - Renice (F7/F8)
  - Tree mode shows parent-child relationships
  - Color-coded CPU/memory usage
  ```

  ### Process Accounting
  ```bash
  # Install accounting
  apt install acct

  # View accounting
  lastcomm               # Recent commands
  lastcomm user          # By user
  sa                     # Summary statistics

  # Check for zombies
  ps aux | awk '$8=="Z"'

  # Check for long-running processes
  ps aux --sort=-etime | head -20

  # Find resource hogs
  ps aux --sort=-%cpu | head -10
  ps aux --sort=-%mem | head -10
  ```

  ### iotop (I/O Monitoring)
  ```bash
  # Install
  apt install iotop

  # Usage
  iotop              # Real-time I/O
  iotop -a           # Only active processes
  iotop -o           # Only processes doing I/O
  iotop -b -n 10     # Non-interactive (10 iterations)
  ```

  ### strace (System Call Tracing)
  ```bash
  # Trace process
  strace -p PID
  strace -p PID -e trace=network    # Network calls only
  strace -p PID -e trace=file       # File operations
  strace -p PID -o trace.log        # Output to file

  # Trace new process
  strace -f python3 script.py
  strace -c python3 script.py       # Summary mode
  ```


entity_id: ent_20260526T190512691075_2509d61e
type: memory
category: debian/systemd-services
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:12.691075
updated_at: 2026-05-26T19:05:12.691075
content:
  ## Systemd Service Management
  ### Service Basics
  ```bash
  # Check status
  systemctl status nginx

  # Start/stop/restart
  systemctl start nginx
  systemctl stop nginx
  systemctl restart nginx
  systemctl reload nginx

  # Enable/disable at boot
  systemctl enable nginx
  systemctl disable nginx
  systemctl is-enabled nginx

  # List services
  systemctl list-units --type=service --state=running
  systemctl list-units --type=service --state=failed
  ```

  ### Create Custom Service
  ```ini
  # /etc/systemd/system/myapp.service
  [Unit]
  Description=My Application
  After=network.target
  Wants=network.target

  [Service]
  Type=simple
  User=myuser
  Group=mygroup
  WorkingDirectory=/opt/myapp
  ExecStart=/usr/bin/python3 /opt/myapp/app.py
  Restart=on-failure
  RestartSec=5
  Environment=NODE_ENV=production
  EnvironmentFile=/etc/myapp.env

  # Security hardening
  NoNewPrivileges=true
  ProtectSystem=strict
  ProtectHome=true
  PrivateTmp=true

  [Install]
  WantedBy=multi-user.target
  ```

  ### Service Management Commands
  ```bash
  # Reload systemd config
  systemctl daemon-reload

  # Check service logs
  journalctl -u myapp.service
  journalctl -u myapp.service -f    # Follow
  journalctl -u myapp.service --since "1 hour ago"

  # View service dependencies
  systemctl list-dependencies myapp.service

  # Mask service (prevent starting)
  systemctl mask myapp.service
  systemctl unmask myapp.service
  ```

  ### Service Templates
  ```ini
  # Socket-activated service
  [Socket]
  ListenStream=8080
  Accept=yes

  # Timer-activated service
  [Timer]
  OnCalendar=daily
  Persistent=true

  # Path-activated service
  [Path]
  PathModified=/opt/myapp/data
  ```

  ### Troubleshooting Services
  ```bash
  # Check failed services
  systemctl --failed

  # Check service status
  systemctl is-active myapp.service
  systemctl is-enabled myapp.service

  # View service file
  systemctl cat myapp.service

  # Check unit file path
  systemctl status myapp.service | grep "Loaded:"
  ```


entity_id: ent_20260526T190512894713_576147f6
type: memory
category: debian/process-signals
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:12.894713
updated_at: 2026-05-26T19:05:12.894713
content:
  ## Linux Process Signals
  ### Signal Numbers & Meanings
  | Signal | Number | Default Action | Description |
  |--------|--------|----------------|-------------|
  | SIGHUP | 1 | Terminate | Hangup, terminal closed |
  | SIGINT | 2 | Terminate | Interrupt (Ctrl+C) |
  | SIGQUIT | 3 | Core dump | Quit (Ctrl+\) |
  | SIGILL | 4 | Core dump | Illegal instruction |
  | SIGTRAP | 5 | Core dump | Trace trap |
  | SIGABRT | 6 | Core dump | Abort |
  | SIGBUS | 7 | Core dump | Bus error |
  | SIGFPE | 8 | Core dump | Floating point exception |
  | SIGKILL | 9 | Terminate | Kill (cannot be caught) |
  | SIGUSR1 | 10 | Terminate | User-defined 1 |
  | SIGSEGV | 11 | Core dump | Segmentation fault |
  | SIGUSR2 | 12 | Terminate | User-defined 2 |
  | SIGPIPE | 13 | Terminate | Broken pipe |
  | SIGALRM | 14 | Terminate | Timer expired |
  | SIGTERM | 15 | Terminate | Termination request |
  | SIGCHLD | 17 | Ignore | Child stopped/terminated |
  | SIGCONT | 18 | Continue | Continue if stopped |
  | SIGSTOP | 19 | Stop | Stop (cannot be caught) |
  | SIGTSTP | 20 | Stop | Stop (Ctrl+Z) |
  | SIGTTIN | 21 | Stop | Background read attempt |
  | SIGTTOU | 22 | Stop | Background write attempt |

  ### Signal Commands
  ```bash
  # Send signals
  kill -TERM PID        # Graceful termination
  kill -KILL PID        # Force kill (cannot be caught)
  kill -HUP PID         # Reload config
  kill -STOP PID        # Suspend
  kill -CONT PID        # Resume

  # Signal shortcuts
  kill -9 PID           # SIGKILL
  kill -15 PID          # SIGTERM (default)
  kill -1 PID           # SIGHUP

  # Send to process group
  kill -TERM -PGID

  # Send to all processes of user
  pkill -u username
  pkill -9 -u username  # Kill all user processes
  ```

  ### Signal Handling in Scripts
  ```bash
  #!/bin/bash
  # Trap signals
  trap 'echo "Caught SIGTERM"; cleanup; exit 0' TERM
  trap 'echo "Caught SIGHUP"; reload_config' HUP
  trap 'echo "Caught INT"; cleanup; exit 0' INT

  function cleanup {
      rm -f /tmp/myapp.lock
      echo "Cleanup complete"
  }

  # Main loop
  while true; do
      echo "Running..."
      sleep 1
  done
  ```

  ### Signal Best Practices
  - Always handle SIGTERM for graceful shutdown
  - Never ignore SIGKILL/SIGSTOP (cannot be caught)
  - Use SIGHUP for config reload
  - Handle SIGCHLD to prevent zombies
  - Use SIGUSR1/SIGUSR2 for custom actions


entity_id: ent_20260526T190513100523_785e564a
type: memory
category: debian/job-control
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:13.100523
updated_at: 2026-05-26T19:05:13.100523
content:
  ## Bash Job Control
  ### Basic Job Control
  ```bash
  # Start background job
  command &

  # Suspend current job
  Ctrl+Z

  # Resume in foreground
  fg

  # Resume in background
  bg

  # List jobs
  jobs
  jobs -l          # With PIDs

  # Job references
  %1              # Job number 1
  %nginx          # Job matching nginx
  %+              # Current job
  %-              # Previous job
  ```

  ### Job Control Commands
  ```bash
  # Bring to foreground
  fg %1

  # Send to background
  bg %1

  # Kill job
  kill %1

  # Disown job (detaches from shell)
  disown %1

  # Wait for job
  wait %1
  wait            # Wait for all background jobs
  ```

  ### Background Process Management
  ```bash
  # Run command in background
  python3 script.py &

  # Redirect output
  nohup python3 script.py > output.log 2>&1 &

  # Using setsid (creates new session)
  setsid python3 script.py &

  # Using nohup
  nohup command &

  # Using disown
  command &
  disown -h %1
  ```

  ### tmux/screen Sessions
  ```bash
  # tmux
  tmux new -s session_name
  tmux attach -t session_name
  tmux ls                 # List sessions
  tmux kill-session -t name

  # Detach: Ctrl+B, then D
  # New window: Ctrl+B, then c
  # List windows: Ctrl+B, then w

  # screen
  screen -S session_name
  screen -r session_name
  screen -ls
  screen -X quit

  # Detach: Ctrl+A, then D
  ```

  ### Cron for Scheduled Jobs
  ```bash
  # Edit crontab
  crontab -e

  # Format: minute hour day month weekday command
  */5 * * * * /path/to/script.sh
  0 2 * * 0 /backup.sh      # Sunday 2 AM
  0 */6 * * * /monitor.sh   # Every 6 hours
  ```


entity_id: ent_20260526T190513304357_9a61fe7c
type: memory
category: debian/process-scheduling
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:13.304357
updated_at: 2026-05-26T19:05:13.304357
content:
  ## Process Scheduling & Priorities
  ### Nice Values
  - **Range:** -20 (highest priority) to 19 (lowest)
  - **Default:** 0
  - **Real-time:** 0-99 (SCHED_FIFO, SCHED_RR)

  ### Nice/Renice Commands
  ```bash
  # Start with nice value
  nice -n 10 python3 script.py      # Lower priority
  nice -n -5 python3 script.py      # Higher priority (requires root)

  # Change running process priority
  renice -n 10 -p PID               # By PID
  renice -n 10 -u username          # By user
  renice -n 10 -g PGID              # By process group

  # View priorities
  ps -o pid,ni,comm -p PID
  ps aux | head -1; ps aux | grep -E "^[a-z]" | awk '{print $1, $17, $11}'
  ```

  ### CPU Affinity
  ```bash
  # Set CPU affinity
  taskset -c 0,1 python3 script.py  # Run on CPUs 0,1
  taskset -pc 2 PID                 # Change PID to CPU 2
  taskset -cp PID                   # Show current affinity

  # Check CPU count
  nproc
  lscpu | grep "CPU(s):"
  ```

  ### OOM (Out of Memory)
  ```bash
  # Current OOM score
  cat /proc/PID/oom_score

  # Set OOM score adjustment
  echo -1000 > /proc/PID/oom_score_adj  # Protected from OOM
  echo 1000 > /proc/PID/oom_score_adj   # Kill first

  # Disable OOM killer
  echo 0 > /proc/sys/vm/panic_on_oom

  # View OOM logs
  dmesg | grep -i "out of memory"
  journalctl -k | grep -i "oom"
  ```

  ### Real-time Scheduling
  ```bash
  # Check scheduling policy
  chrt -p PID

  # Set real-time policy
  chrt -f 1 PID    # SCHED_FIFO
  chrt -r 1 PID    # SCHED_RR
  chrt -o 1 PID    # SCHED_OTHER

  # Limit real-time priority
  echo 90 > /proc/sys/kernel/sched_rt_runtime_us
  ```


entity_id: ent_20260526T190513509703_33ed4721
type: memory
category: debian/resource-limits
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:13.509703
updated_at: 2026-05-26T19:05:13.509703
content:
  ## Resource Limits & Cgroups
  ### ulimit (Per-Process Limits)
  ```bash
  # View all limits
  ulimit -a

  # Key limits
  ulimit -n    # Open files
  ulimit -u    # Max processes
  ulimit -v    # Virtual memory (KB)
  ulimit -f    # File size (blocks)
  ulimit -m    # Resident set size
  ulimit -t    # CPU time (seconds)

  # Set limits
  ulimit -n 65536
  ulimit -u 4096

  # Persistent configuration
  # /etc/security/limits.conf
  * soft nofile 65536
  * hard nofile 131072
  * soft nproc 4096
  * hard nproc 8192
  ```

  ### cgroups v2
  ```bash
  # Check cgroup version
  mount | grep cgroup

  # Create cgroup
  mkdir /sys/fs/cgroup/myapp
  echo $$ > /sys/fs/cgroup/myapp/cgroup.procs

  # CPU limit
  echo "50000" > /sys/fs/cgroup/myapp/cpu.weight    # 50% CPU

  # Memory limit
  echo "1G" > /sys/fs/cgroup/myapp/memory.max

  # I/O weight
  echo "100" > /sys/fs/cgroup/myapp/io.weight

  # PID limit
  echo "100" > /sys/fs/cgroup/myapp/pids.max
  ```

  ### systemd Resource Control
  ```ini
  # In service file
  [Service]
  # CPU limits
  CPUQuota=50%
  CPUWeight=100

  # Memory limits
  MemoryMax=1G
  MemoryHigh=768M
  MemoryLow=256M

  # I/O limits
  IOWeight=100
  IODeviceWeight=/dev/sda 100

  # PID limit
  TasksMax=100

  # Device access
  DevicePolicy=strict
  DeviceAllow=/dev/null rw
  ```

  ### System-wide Limits
  ```bash
  # /etc/sysctl.conf
  # Max processes
  kernel.pid_max = 4194304

  # Max open files
  fs.file-max = 2097152

  # Apply
  sysctl -p

  # Check current
  sysctl fs.file-max
  sysctl kernel.pid_max
  ```


entity_id: ent_20260526T190513712194_29649dcf
type: memory
category: debian/process-debugging
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:13.712194
updated_at: 2026-05-26T19:05:13.712194
content:
  ## Process Debugging Tools
  ### strace (System Call Tracing)
  ```bash
  # Trace system calls
  strace -p PID                    # Attach to running process
  strace -f python3 script.py      # Trace new process + children
  strace -e trace=network -p PID   # Only network calls
  strace -e trace=file -p PID      # Only file operations
  strace -c -p PID                 # Summary/count mode
  strace -T -p PID                 # Show time spent
  strace -tt -p PID                # Show timestamps

  # Common traces
  strace -e trace=signal -p PID    # Signal handling
  strace -e trace=process -p PID   # Process creation
  strace -e trace=desc -p PID      # File descriptor ops
  ```

  ### ltrace (Library Call Tracing)
  ```bash
  # Trace library calls
  ltrace -p PID                    # Attach
  ltrace -f python3 script.py      # New process
  ltrace -e malloc,free -p PID     # Specific functions
  ```

  ### perf (Performance Analysis)
  ```bash
  # Record performance data
  perf record -p PID sleep 10
  perf record -g python3 script.py # With call graph

  # View results
  perf report
  perf top                         # Real-time top

  # CPU profiling
  perf stat -p PID sleep 5         # Statistics
  perf c2c -p PID                  # Cache contention
  ```

  ### gdb (GNU Debugger)
  ```bash
  # Attach to process
  gdb -p PID

  # Common commands
  bt                              # Backtrace
  info threads                    # List threads
  thread N                        # Switch to thread N
  continue                        # Continue execution
  next                            # Step over
  step                            # Step into
  break function_name             # Set breakpoint
  info locals                     # Local variables
  print variable                  # Print value

  # Core dump analysis
  gdb /path/to/core /path/to/binary
  ```

  ### lsof (List Open Files)
  ```bash
  # Open files by process
  lsof -p PID

  # Files by user
  lsof -u username

  # Network connections
  lsof -i
  lsof -i :80                     # Port 80
  lsof -i TCP                    # TCP connections

  # Specific file
  lsof /var/log/syslog
  ```


entity_id: ent_20260526T190513915529_53615f63
type: memory
category: debian/process-namespaces
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:13.915529
updated_at: 2026-05-26T19:05:13.915529
content:
  ## Process Namespaces & Isolation
  ### Linux Namespaces
  | Type | Isolation | Description |
  |------|-----------|-------------|
  | PID | Process IDs | Isolated process tree |
  | Network | Network stack | Isolated interfaces, routes |
  | Mount | Mount points | Isolated filesystem hierarchy |
  | UTS | Hostname | Isolated hostname/domain |
  | IPC | IPC objects | Isolated semaphores, shared memory |
  | User | User/Group IDs | Isolated UID/GID mapping |
  | Time | Time | Isolated clock settings |

  ### unshare (Create Namespaces)
  ```bash
  # Create new PID namespace
  unshare --pid --fork bash

  # Create network namespace
  unshare --net bash

  # Multiple namespaces
  unshare --pid --net --mount --fork bash

  # Create network namespace with name
  ip netns add mynet
  ip netns exec mynet bash
  ```

  ### Network Namespaces
  ```bash
  # Create namespace
  ip netns add testnet

  # Configure namespace
  ip netns exec testnet ip link set lo up
  ip netns exec testnet ip addr add 192.168.100.1/24 dev eth0

  # Create veth pair
  ip link add veth0 type veth peer name veth1
  ip link set veth0 netns testnet
  ip addr add 192.168.100.2/24 dev veth1
  ip link set veth0 up
  ip link set veth1 up

  # List namespaces
  ip netns list
  ```

  ### PID Namespaces
  ```bash
  # Create PID namespace
  unshare --pid --fork --mount-proc bash

  # Inside namespace
  ps aux          # Shows isolated process tree
  cat /proc/self/ns/pid

  # View parent PID
  cat /proc/self/status | grep PPid
  ```

  ### User Namespaces
  ```bash
  # Map user IDs
  unshare --user --map-root-user bash

  # Check user mapping
  cat /proc/self/uid_map
  cat /proc/self/gid_map
  ```

  ### systemd --user
  ```bash
  # Start user service
  systemctl --user start myservice

  # List user services
  systemctl --user list-units

  # Enable user service
  systemctl --user enable myservice
  ```


entity_id: ent_20260526T190514120377_a3b9d936
type: memory
category: debian/process-scripts
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:14.120377
updated_at: 2026-05-26T19:05:14.120377
content:
  ## Process Management Scripts & Automation
  ### Health Check Script
  ```bash
  #!/bin/bash
  # Process health monitor
  PROCESSES=("nginx" "mysql" "redis-server" "node")
  ALERT_EMAIL="admin@example.com"

  for proc in "${PROCESSES[@]}"; do
      if ! pgrep -x "$proc" > /dev/null; then
          echo "$(date): $proc is NOT running" | mail -s "Process Down: $proc" "$ALERT_EMAIL"
          systemctl start "${proc}.service"
      else
          pid=$(pgrep -x -n "$proc")
          echo "$(date): $proc running (PID: $pid)"
      fi
  done
  ```

  ### Process Watchdog
  ```bash
  #!/bin/bash
  # Watchdog script
  PROCESS="python3 app.py"
  LOG="/var/log/watchdog.log"
  MAX_RESTARTS=5
  RESTART_COUNT=0

  check_and_restart() {
      if ! pgrep -f "$PROCESS" > /dev/null; then
          if [ $RESTART_COUNT -lt $MAX_RESTARTS ]; then
              echo "$(date): Starting $PROCESS (attempt $((RESTART_COUNT+1)))" >> $LOG
              $PROCESS >> $LOG 2>&1 &
              RESTART_COUNT=$((RESTART_COUNT+1))
          else
              echo "$(date): Max restarts reached. Alerting." >> $LOG
              echo "Process $PROCESS failed $MAX_RESTARTS times" | mail -s "Watchdog Alert" admin@example.com
          fi
      else
          RESTART_COUNT=0
      fi
  }

  while true; do
      check_and_restart
      sleep 30
  done
  ```

  ### Resource Monitor
  ```bash
  #!/bin/bash
  # Monitor system resources
  LOG="/var/log/resource_monitor.log"

  while true; do
      echo "=== $(date) ===" >> $LOG
      
      # Load average
      uptime >> $LOG
      
      # Memory usage
      free -h >> $LOG
      
      # Top processes by CPU
      ps aux --sort=-%cpu | head -6 >> $LOG
      
      # Top processes by memory
      ps aux --sort=-%mem | head -6 >> $LOG
      
      # Disk I/O
      iostat -x 1 1 >> $LOG 2>/dev/null
      
      # Network I/O
      sar -n DEV 1 1 >> $LOG 2>/dev/null
      
      sleep 300  # 5 minutes
  done
  ```

  ### Zombie Process Cleaner
  ```bash
  #!/bin/bash
  # Find and report zombie processes
  echo "=== Zombie Process Report ==="
  echo "Date: $(date)"
  echo ""

  # Find zombies
  ps aux | awk '$8=="Z" {print "Zombie: PID="$2, "PPID="$4, "CMD="$11}'

  # Find parent processes of zombies
  echo ""
  echo "Parent processes of zombies:"
  ps aux | awk '$8=="Z" {print $4}' | sort -u | while read ppid; do
      ps -p $ppid -o pid,comm,stat
  done
  ```

  ### Process Tree Analyzer
  ```bash
  #!/bin/bash
  # Analyze process tree
  PID=${1:-$$}
  echo "Process Tree for PID $PID:"
  echo ""

  # Show tree
  pstree -p $PID

  # Show resource usage
  echo ""
  echo "Resource Usage:"
  ps -p $PID -o pid,ppid,%cpu,%mem,vsz,rss,stat,comm

  # Show open files
  echo ""
  echo "Open Files:"
  lsof -p $PID 2>/dev/null | head -20
  ```


entity_id: ent_20260526T190514324684_3db058ad
type: memory
category: debian/container-processes
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:14.324684
updated_at: 2026-05-26T19:05:14.324684
content:
  ## Container Process Management
  ### Docker Process Management
  ```bash
  # Running processes
  docker ps
  docker ps -a               # All containers
  docker ps -q               # IDs only

  # Process inside container
  docker top container_name
  docker exec -it container_name ps aux
  docker exec -it container_name bash

  # Resource limits
  docker run --cpus=2 --memory=1g image_name
  docker update --cpus=1 container_name

  # Process signals
  docker kill container_name    # SIGKILL
  docker stop container_name    # SIGTERM
  ```

  ### Podman
  ```bash
  # Similar to Docker
  podman ps
  podman exec -it container_name bash
  podman top container_name

  # Rootless containers
  podman run --rootless nginx
  ```

  ### LXC Containers
  ```bash
  # List containers
  lxc-ls
  lxc-ls -f                # Full info

  # Start/stop
  lxc-start -n container_name
  lxc-stop -n container_name

  # Console access
  lxc-console -n container_name
  ```

  ### Systemd-nspawn
  ```bash
  # Run container
  systemd-nspawn -D /path/to/rootfs

  # Create container
  machinectl pull-tar debian-image.tar debian-container
  machinectl start debian-container
  ```

  ### Process Isolation Comparison
  | Method | Isolation Level | Use Case |
  |--------|----------------|----------|
  | Namespaces | Kernel-level | Development, testing |
  | Docker | Application | Deployment, microservices |
  | LXC | System-level | Virtualization alternative |
  | systemd | Service-level | Service management |
  | chroot | Filesystem only | Simple isolation |


entity_id: ent_20260526T190514529307_06bcedf6
type: memory
category: debian/process-forensics
strength: moderate
metadata: "{\"source\": \"debian_process_management_deep_dive\"}"
created_at: 2026-05-26T19:05:14.529307
updated_at: 2026-05-26T19:05:14.529307
content:
  ## Process Forensics & Investigation
  ### Investigating Suspicious Processes
  ```bash
  # Find processes by user
  ps -u suspicious_user -o pid,comm,stat,etime

  # Find processes with specific characteristics
  ps aux | awk '$3 > 80.0'    # High CPU
  ps aux | awk '$6 > 1000000' # High memory

  # Check process binaries
  ls -la /proc/PID/exe        # Binary location
  file /proc/PID/exe          # File type

  # Check network connections
  ss -tulnp | grep PID
  lsof -p PID -i

  # Check open files
  ls -la /proc/PID/fd/
  lsof -p PID
  ```

  ### Process Memory Analysis
  ```bash
  # Memory maps
  cat /proc/PID/maps
  cat /proc/PID/smaps

  # Memory usage breakdown
  pmap -x PID

  # Core dump
  gcore PID                   # Generate core dump
  gdb /path/to/binary core    # Analyze core
  ```

  ### Process Audit
  ```bash
  # Install audit system
  apt install auditd

  # Watch process creation
  auditctl -a always,exit -F arch=b64 -S execve

  # Watch specific binary
  auditctl -w /usr/bin/sudo -p x

  # View audit logs
  ausearch -m EXECVE
  ausearch -k my_key
  ```

  ### Network Process Investigation
  ```bash
  # Find processes with network connections
  ss -tulnp
  netstat -tulnp

  # Find listening ports
  ss -lntp

  # Find established connections
  ss -tnp

  # DNS queries by process
  strace -p PID -e trace=network -e trace=signal
  ```

  ### File System Investigation
  ```bash
  # Files opened by process
  lsof -p PID

  # Recently accessed files
  find /tmp -mmin -60 -type f
  find /var/log -mmin -60 -type f

  # Check for hidden processes
  ls /proc/*/status 2>/dev/null | grep -i "Name" | sort
  ```


entity_id: ent_20260526T191742298641_72a55c6e
type: memory
category: debian/filesystem-types
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:42.298641
updated_at: 2026-05-26T19:17:42.298641
content:
  ## Linux Filesystem Types
  ### Native Linux
  - **ext4:** Default for most Debian installs. Supports 16TB volumes, 64TB files. Features: journaling, extents, delayed allocation, multiblock allocation.
  - **ext3:** ext2 with journaling. Legacy, migrate to ext4.
  - **ext2:** No journaling. Use for small partitions (boot, USB).
  - **btrfs:** Copy-on-write, snapshots, checksums, compression, subvolumes. Enterprise features maturing.
  - **XFS:** High-performance, large file support. Default on RHEL. Scalable to 8EB.
  - **ZFS:** (via openzfs) Copy-on-write, snapshots, RAID-Z, compression, integrity. Not in mainline kernel.
  - **F2FS:** Flash-Friendly File System. Optimized for NAND/eMMC/SD.

  ### Network
  - **NFS:** Network File System. NFSv3 (stateless), NFSv4 (stateful, Kerberos).
  - **CIFS/SMB:** Windows file sharing via `cifs-utils`.
  - **SSHFS:** FUSE-based SSH file mounting.
  - **GlusterFS:** Distributed filesystem.
  - **CephFS:** Ceph distributed filesystem.

  ### Special Purpose
  - **tmpfs:** RAM-backed filesystem. Disappears on reboot.
  - **overlayfs:** Union filesystem. Used by Docker.
  - **squashfs:** Compressed read-only filesystem.
  - **proc / sysfs:** Virtual filesystems for kernel info.
  - **devtmpfs:** Dynamic device node management.

  ### Choosing a Filesystem
  | Use Case | Recommended |
  |----------|-------------|
  | General Debian | ext4 |
  | Large files (>16TB) | XFS |
  | Snapshots + checksums | btrfs |
  | Enterprise ZFS features | ZFS |
  | Embedded/flash | F2FS |
  | RAM temp storage | tmpfs |
  | Container layers | overlayfs |

  ### Create Filesystem
  ```bash
  # ext4 (default)
  mkfs.ext4 /dev/sdb1
  mkfs.ext4 -L mydata /dev/sdb1          # with label
  mkfs.ext4 -O ^has_journal /dev/sdb1    # ext3 without journal

  # btrfs
  mkfs.btrfs /dev/sdb1
  mkfs.btrfs -L mydata /dev/sdb1
  mkfs.btrfs -d single /dev/sdb1         # single disk

  # XFS
  mkfs.xfs /dev/sdb1
  mkfs.xfs -f /dev/sdb1                  # force (overwrite)

  # FAT32 (USB compatibility)
  mkfs.vfat -F 32 /dev/sdb1

  # NTFS (Windows compatibility)
  mkfs.ntfs -f /dev/sdb1
  ```

  ### Filesystem Information
  ```bash
  # Filesystem type
  file -s /dev/sdb1
  blkid /dev/sdb1

  # Filesystem stats
  df -h /dev/sdb1
  dumpe2fs /dev/sdb1 | grep -i "block size\|inode\|feature"

  # btrfs info
  btrfs filesystem show
  btrfs filesystem usage /mnt/btrfs

  # XFS info
  xfs_info /mnt/xfs

  # Mount options
  cat /proc/mounts | grep sdb1
  findmnt /dev/sdb1
  ```


entity_id: ent_20260526T191742529988_a018eed8
type: memory
category: debian/lvm
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:42.529988
updated_at: 2026-05-26T19:17:42.529988
content:
  ## LVM (Logical Volume Manager)
  ### Architecture
  ```
  Physical Disks → Physical Volumes (PV) → Volume Group (VG) → Logical Volumes (LV) → Filesystem
  /dev/sdb       pvcreate                 vgcreate myvg        lvcreate -L 10G mydata   mkfs.ext4
  ```

  ### Setup LVM
  ```bash
  # Install
  apt install lvm2

  # Create Physical Volume
  pvcreate /dev/sdb1
  pvcreate /dev/sdb2 /dev/sdc1

  # Create Volume Group
  vgcreate myvg /dev/sdb1 /dev/sdb2
  vgextend myvg /dev/sdc1               # add disk later

  # Create Logical Volume
  lvcreate -L 50G -n mydata myvg        # fixed size
  lvcreate -l 100%FREE -n mydata myvg   # use all remaining space
  lvcreate -L 50G -n snapvol myvg       # for snapshots

  # Create filesystem on LV
  mkfs.ext4 /dev/myvg/mydata
  mount /dev/myvg/mydata /mnt/data

  # Add to /etc/fstab
  echo '/dev/myvg/mydata /mnt/data ext4 defaults 0 2' >> /etc/fstab
  ```

  ### Resize Operations
  ```bash
  # Extend LV
  lvextend -L +50G /dev/myvg/mydata
  lvextend -l +100%FREE /dev/myvg/mydata   # use all free space

  # Extend filesystem (ext4 - online)
  resize2fs /dev/myvg/mydata

  # XFS (online - extend only)
  xfs_growfs /mnt/data

  # btrfs (online - extend)
  btrfs filesystem resize max /mnt/data

  # Shrink (ext4 only - must unmount!)
  umount /mnt/data
  resize2fs /dev/myvg/mydata 30G
  lvreduce -L 30G /dev/myvg/mydata

  # Shrink with single command (safer)
  lvreduce -r -L 30G /dev/myvg/mydata
  ```

  ### LVM Snapshots
  ```bash
  # Create snapshot
  lvcreate -L 10G -s -n mydata_snap /dev/myvg/mydata

  # Mount snapshot (read-only recommended)
  mount -o ro /dev/myvg/mydata_snap /mnt/snapshot

  # Restore from snapshot
  umount /mnt/data
  lvconvert --merge /dev/myvg/mydata_snap
  mount /dev/myvg/mydata /mnt/data

  # Delete snapshot
  lvremove /dev/myvg/mydata_snap
  ```

  ### LVM Administration
  ```bash
  # Check status
  pvs                     # physical volumes
  vgs                     # volume groups
  lvs                     # logical volumes
  pvdisplay /dev/sdb1     # detailed PV info

  # LVM reports
  lvs -o +devices         # show backing devices
  vgs -o +lv_count,pv_count  # VG details

  # LVM cache (SSD + HDD)
  lvcreate -L 100G -n cachedata myvg
  lvcreate -L 10G -n cachepool myvg
  lvconvert --type cache --poolname myvg/cachepool myvg/cachedata
  ```

  ### LVM Best Practices
  - Keep 20% VG free for snapshots and growth
  - Use `-r` flag with `lvreduce` for safer shrinking
  - Monitor snapshot space — 100% full snapshots are auto-removed
  - Use `pvmove` to migrate data between physical volumes
  - Consider thin provisioning for VMs: `lvcreate --thinpool`


entity_id: ent_20260526T191742739211_dbc6aa39
type: memory
category: debian/raid
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:42.739211
updated_at: 2026-05-26T19:17:42.739211
content:
  ## Software RAID on Debian
  ### RAID Levels
  | Level | Minimum Drives | Redundancy | Usable Space | Use Case |
  |-------|---------------|------------|-------------|----------|
  | RAID 0 | 2 | None | 100% | Speed only (not recommended for data) |
  | RAID 1 | 2 | Full mirror | 50% | Boot drives, critical data |
  | RAID 5 | 3 | Single disk loss | (N-1)/N | Good balance of space + redundancy |
  | RAID 6 | 4 | Double disk loss | (N-2)/N | Large arrays, extra safety |
  | RAID 10 | 4 | Half disks + 1 | 50% | Best performance + redundancy |

  ### Create RAID Array
  ```bash
  # Install
  apt install mdadm

  # Create RAID 1 (mirror)
  mdadm --create /dev/md0 --level=1 --raid-devices=2 /dev/sdb1 /dev/sdc1

  # Create RAID 5
  mdadm --create /dev/md0 --level=5 --raid-devices=3   /dev/sdb1 /dev/sdc1 /dev/sdd1 --spare-devices=1 /dev/sde1

  # Create RAID 10
  mdadm --create /dev/md0 --level=10 --raid-devices=4   /dev/sdb1 /dev/sdc1 /dev/sdd1 /dev/sde1

  # Initialize filesystem
  mkfs.ext4 /dev/md0

  # Save configuration
  mdadm --detail --scan >> /etc/mdadm/mdadm.conf
  update-initramfs -u

  # Mount
  mount /dev/md0 /mnt/raid
  ```

  ### RAID Management
  ```bash
  # Check status
  cat /proc/mdstat
  mdadm --detail /dev/md0

  # Add spare drive
  mdadm --add /dev/md0 /dev/sdf1

  # Replace failed drive
  mdadm --fail /dev/md0 /dev/sdc1          # mark as failed
  mdadm --remove /dev/md0 /dev/sdc1        # remove
  mdadm --add /dev/md0 /dev/sdg1           # add replacement
  cat /proc/mdstat                          # watch rebuild

  # Stop array (maintenance)
  umount /mnt/raid
  mdadm --stop /dev/md0

  # Assemble array (after reboot)
  mdadm --assemble /dev/md0 /dev/sdb1 /dev/sdc1

  # Grow RAID 5 (add disk)
  mdadm --add /dev/md0 /dev/sdf1
  mdadm --grow /dev/md0 --raid-devices=4
  resize2fs /dev/md0                        # resize filesystem
  ```

  ### RAID Monitoring
  ```bash
  # Email alerts on RAID events
  # /etc/mdadm/mdadm.conf
  MAILADDR admin@example.com
  MONITORING_INTERVAL 60

  # Enable monitoring
  systemctl enable --now mdadm-monitor

  # Check rebuild progress
  watch cat /proc/mdstat
  cat /sys/block/md0/md/sync_action
  ```

  ### Hardware vs Software RAID
  - **Software RAID:** Flexible, OS-aware, snapshots work, no extra hardware cost
  - **Hardware RAID:** Better performance, dedicated controller, battery-backed cache
  - **Recommendation:** Software RAID + ZFS for most use cases
  - **Important:** Never mix hardware RAID with ZFS — ZFS needs direct disk access


entity_id: ent_20260526T191742947325_51a9a5e4
type: memory
category: debian/mounting
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:42.947325
updated_at: 2026-05-26T19:17:42.947325
content:
  ## Mounting and fstab
  ### Manual Mounting
  ```bash
  # Basic mount
  mount /dev/sdb1 /mnt/data

  # Mount with options
  mount -o rw,noatime,nodiratime,data=ordered /dev/sdb1 /mnt/data

  # Mount with specific filesystem type
  mount -t ext4 /dev/sdb1 /mnt/data

  # Remount read-only
  mount -o remount,ro /mnt/data

  # Unmount
  umount /mnt/data
  umount -l /mnt/data           # lazy unmount (stuck mount)
  umount -f /mnt/data           # force unmount

  # Network mounts
  mount -t nfs 192.168.1.100:/export /mnt/nfs
  mount -t cifs //server/share /mnt/smb -o username=user,password=pass
  mount -t sshfs user@host:/remote/path /mnt/ssh

  # Loopback mount (ISO files)
  mount -o loop disk.iso /mnt/iso

  # Bind mount
  mount --bind /source/dir /dest/dir

  # tmpfs mount
  mount -t tmpfs -o size=4G tmpfs /mnt/ramdisk
  ```

  ### /etc/fstab Format
  ```
  # <device>  <mountpoint>  <type>  <options>       <dump>  <pass>
  UUID=xxxxx  /              ext4    errors=remount-ro 0      1
  UUID=xxxxx  /boot          ext4    defaults          0      2
  UUID=xxxxx  /home          ext4    defaults          0      2
  UUID=xxxxx  /mnt/data      ext4    defaults,noatime  0      2
  UUID=xxxxx  none           swap    sw                0      0
  # Network mounts
  192.168.1.100:/export /mnt/nfs nfs defaults,noauto,x-systemd.automount 0 0
  ```

  ### Common Mount Options
  | Option | Description |
  |--------|-------------|
  | `defaults` | rw,suid,dev,exec,auto,nouser,async |
  | `noatime` | Don't update access times (performance) |
  | `nodiratime` | Don't update directory access times |
  | `relatime` | Relative access time (default, good balance) |
  | `ro` | Read-only |
  | `rw` | Read-write |
  | `nosuid` | Ignore SUID bits (security) |
  | `noexec` | No executable files (security) |
  | `nodev` | No device files (security) |
  | `nofail` | Don't fail boot if device missing |
  | `x-systemd.automount` | Mount on access (for NFS/USB) |
  | `user` | Allow non-root users to mount |

  ### UUID and LABEL Management
  ```bash
  # Find UUID
  blkid
  ls -l /dev/disk/by-uuid/
  ls -l /dev/disk/by-label/

  # Set label (ext4)
  e2label /dev/sdb1 mydata

  # Set label (XFS)
  xfs_admin -L mydata /dev/sdb1

  # Use label in fstab
  LABEL=mydata /mnt/data ext4 defaults 0 2
  ```

  ### Troubleshooting Mounts
  ```bash
  # Check what's mounted
  findmnt
  findmnt -t ext4                    # specific type
  findmnt -R /mnt/data              # recursive

  # Check if device busy
  lsof +D /mnt/data
  fuser -mv /mnt/data

  # Fix failed mount
  mount -a                           # mount all fstab entries
  fsck /dev/sdb1                     # check filesystem (unmounted!)

  # Emergency: stuck mount
  umount -l /mnt/data               # lazy
  umount -f /mnt/data               # force
  fuser -km /mnt/data               # kill processes using mount
  ```

  ### NFS Mount Options
  ```
  # /etc/fstab NFS entry
  192.168.1.100:/data /mnt/nfs nfs   rw,sync,hard,intr,noatime,_netdev 0 0

  # NFS options explained
  # rw - read/write
  # sync - synchronous writes
  # hard - retry on failure
  # intr - allow interrupting NFS calls
  # _netdev - wait for network before mounting
  ```


entity_id: ent_20260526T191743158664_c678481e
type: memory
category: debian/filesystem-maintenance
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:43.158664
updated_at: 2026-05-26T19:17:43.158664
content:
  ## Filesystem Maintenance & Repair
  ### Filesystem Checking
  ```bash
  # ext4 check
  fsck /dev/sdb1                     # interactive check
  fsck -f /dev/sdb1                  # force check
  fsck -n /dev/sdb1                  # dry run (no changes)
  e2fsck -f /dev/sdb1                # full ext4 check

  # XFS check (filesystem must be unmounted)
  xfs_repair /dev/sdb1
  xfs_repair -n /dev/sdb1            # dry run

  # btrfs check
  btrfs check /dev/sdb1
  btrfs scrub start /dev/sdb1        # scrub (verify checksums)

  # Online fsck (ext4)
  e4fsck -f /dev/sdb1
  tune2fs -l /dev/sdb1 | grep "Last checked"

  # Schedule check
  tune2fs -c 30 /dev/sdb1            # check every 30 mounts
  tune2fs -i 30d /dev/sdb1           # check every 30 days
  ```

  ### Filesystem Tuning
  ```bash
  # ext4 tuning
  tune2fs -o journal_data_writeback /dev/sdb1   # faster, less safe
  tune2fs -o journal_data /dev/sdb1             # safer, slower
  tune2fs -O ^has_journal /dev/sdb1             # disable journal

  # Journal size (larger = better performance)
  tune2fs -J size=256 /dev/sdb1                  # 256MB journal

  # ext4 features
  tune2fs -O metadata_csum /dev/sdb1             # metadata checksums
  tune2fs -O 64bit /dev/sdb1                     # 64-bit mode

  # Inode ratio
  mkfs.ext4 -i 16384 /dev/sdb1                   # 1 inode per 16KB
  mkfs.ext4 -i 4096 /dev/sdb1                    # for many small files
  ```

  ### Disk Space Management
  ```bash
  # Find large files
  find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null
  find / -type f -size +1G -ls 2>/dev/null

  # Disk usage by directory
  du -sh /* 2>/dev/null | sort -rh | head -20
  du -sh /var/* 2>/dev/null | sort -rh

  # Find duplicate files
  fdupes -r /path/to/dir
  rdfind /path/to/dir

  # Clean package cache
  apt clean
  apt autoremove

  # Clean journal logs
  journalctl --vacuum-time=7d
  journalctl --vacuum-size=500M

  # Old kernels
  dpkg -l 'linux-image-*' | grep ^ii
  apt autoremove --purge
  ```

  ### SMART Disk Health
  ```bash
  # Install
  apt install smartmontools

  # Check disk health
  smartctl -a /dev/sda
  smartctl -H /dev/sda              # health status
  smartctl -t short /dev/sda        # short test
  smartctl -t long /dev/sda         # long test
  smartctl -l selftest /dev/sda     # test results

  # Key attributes to monitor
  # Reallocated_Sector_Ct - bad sectors being replaced
  # Current_Pending_Sector - sectors waiting reallocation
  # Offline_Uncorrectable - uncorrectable errors
  # Temperature_Celsius - disk temperature

  # Enable SMART monitoring
  systemctl enable --now smartd
  nano /etc/smartd.conf
  # /dev/sda -a -o on -S on -s (S/../.././02|L/../../6/03) -m admin@example.com
  ```

  ### SSD-Specific
  ```bash
  # TRIM (discard)
  fstrim -v /mnt/data               # manual TRIM
  # Add to fstab: discard option
  # Or cron job:
  0 3 * * 0 fstrim -av /            # weekly TRIM

  # Check SSD health
  smartctl -A /dev/nvme0n1 | grep -i "wear\|percentage\|temperature"

  # NVMe specific
  nvme list
  nvme smart-log /dev/nvme0n1
  ```


entity_id: ent_20260526T191743382239_dc36eb81
type: memory
category: debian/btrfs
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:43.382239
updated_at: 2026-05-26T19:17:43.382239
content:
  ## btrfs Filesystem Deep Dive
  ### Key Features
  - Copy-on-write (CoW) — efficient snapshots and cloning
  - Transparent compression (zstd, lzo, zlib)
  - Subvolumes — hierarchical snapshots
  - Checksums on data and metadata
  - Online resize, defragment, scrub
  - RAID-like profiles (single, raid0, raid1, raid10, dual, dup)

  ### Setup btrfs
  ```bash
  # Create btrfs filesystem
  mkfs.btrfs -L mydata /dev/sdb1
  mkfs.btrfs -d single -m single /dev/sdb1   # single disk
  mkfs.btrfs -d raid1 -m raid1 /dev/sdb1 /dev/sdc1  # dual disk

  # Mount with compression
  mount -o compress=zstd /dev/sdb1 /mnt/btrfs

  # Add to fstab
  UUID=xxxx /mnt/btrfs btrfs defaults,compress=zstd 0 0
  ```

  ### Subvolumes
  ```bash
  # Create subvolume
  btrfs subvolume create /mnt/btrfs/home
  btrfs subvolume create /mnt/btrfs/var

  # List subvolumes
  btrfs subvolume list /mnt/btrfs

  # Delete subvolume
  btrfs subvolume delete /mnt/btrfs/home

  # Mount specific subvolume
  mount -o subvol=home,compress=zstd /dev/sdb1 /home
  ```

  ### Snapshots
  ```bash
  # Create read-write snapshot
  btrfs subvolume snapshot /mnt/btrfs/home /mnt/btrfs/home_snap

  # Create read-only snapshot
  btrfs subvolume snapshot -r /mnt/btrfs/home /mnt/btrfs/home_ro_snap

  # List snapshots
  btrfs subvolume list -r /mnt/btrfs

  # Restore from snapshot
  umount /home
  btrfs subvolume delete /mnt/btrfs/home
  btrfs subvolume snapshot /mnt/btrfs/home_snap /mnt/btrfs/home
  mount -o subvol=home /dev/sdb1 /home

  # Automated snapshots (snapper)
  apt install snapper
  snapper create-config home
  snapper create --description "before update"
  snapper list
  snapper rollback 5
  ```

  ### btrfs Maintenance
  ```bash
  # Check usage
  btrfs filesystem usage /mnt/btrfs
  btrfs filesystem df /mnt/btrfs

  # Scrub (verify checksums)
  btrfs scrub start /mnt/btrfs
  btrfs scrub status /mnt/btrfs

  # Balance (redistribute data across devices)
  btrfs balance start /mnt/btrfs
  btrfs balance start -dusage=0 /mnt/btrfs    # only move 0% usage data

  # Defragment
  btrfs filesystem defragment -r -v /mnt/btrfs
  btrfs filesystem defragment -r -v -czstd /mnt/btrfs

  # Add/remove devices
  btrfs device add /dev/sdc1 /mnt/btrfs
  btrfs device remove /dev/sdc1 /mnt/btrfs

  # Convert RAID levels
  btrfs balance start -dconvert=raid1 /mnt/btrfs
  ```

  ### btrfs RAID Warnings
  - btrfs RAID5/RAID6 are considered **unstable** — avoid for production
  - Use RAID1 or RAID10 for redundancy
  - Single disk btrfs is perfectly fine and widely used
  - Always keep some free space (btrfs needs ~1GB for operations)


entity_id: ent_20260526T191743592003_52dc68e8
type: memory
category: debian/zfs
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:43.592003
updated_at: 2026-05-26T19:17:43.592003
content:
  ## ZFS on Debian
  ### Setup
  ```bash
  # Install
  apt install openzfs-dkms openzfs-utils

  # Create pool
  zpool create tank /dev/sdb
  zpool create tank mirror /dev/sdb /dev/sdc          # mirror
  zpool create tank raidz /dev/sdb /dev/sdc /dev/sdd  # RAID-Z
  zpool create tank raidz2 /dev/sdb /dev/sdc /dev/sdd /dev/sde  # RAID-Z2

  # Create datasets
  zfs create tank/data
  zfs create tank/backups
  zfs create -V 100G tank/vmimg                      # zvol (block device)

  # Set properties
  zfs set compression=zstd tank/data
  zfs set atime=off tank/data
  zfs set recordsize=1M tank/database
  zfs set mountpoint=/data tank/data

  # Mount (automatic via systemd)
  zfs mount tank/data
  ```

  ### ZFS Snapshots
  ```bash
  # Create snapshot
  zfs snapshot tank/data@before-update

  # List snapshots
  zfs list -t snapshot

  # Rollback
  zfs rollback tank/data@before-update

  # Clone (read-writable copy)
  zfs clone tank/data@before-update tank/data_clone

  # Delete snapshot
  zfs destroy tank/data@before-update

  # Automated snapshots
  apt install zfs-auto-snapshot
  systemctl enable zfs-auto-snapshot

  # Send/Receive (replication)
  zfs send tank/data@snap | zfs receive remote:tank/data
  zfs send -i tank/data@snap1 tank/data@snap2 | zfs receive remote:tank/data
  ```

  ### ZFS Pool Management
  ```bash
  # Pool status
  zpool status
  zpool list

  # Add vdev
  zpool add tank mirror /dev/sdd /dev/sde

  # Replace disk
  zpool replace tank /dev/sdb /dev/sdb_new

  # Remove vdev (requires export first)
  zpool offline tank /dev/sdb
  zpool detach tank /dev/sdb

  # Scrub
  zpool scrub tank
  zpool status                          # check progress

  # Pool import/export
  zpool export tank
  zpool import tank
  zpool import -f tank                  # force import

  # Pool properties
  zpool get all tank
  zpool set autoexpand=on tank
  ```

  ### ZFS Performance Tuning
  ```bash
  # ARC cache size
  echo 4294967296 > /sys/module/zfs/parameters/zfs_arc_max   # 4GB

  # Record size tuning
  zfs set recordsize=128K tank/media           # media files
  zfs set recordsize=1M tank/database          # databases
  zfs set recordsize=16K tank/code             # source code

  # Sync modes
  zfs set sync=always tank/data                # default, safest
  zfs set sync=standard tank/data              # fsync honored
  zfs set sync=disabled tank/cache             # cache only

  # Compression
  zfs get compression tank/data
  # zstd is recommended default (good ratio, fast)
  ```

  ### ZFS Monitoring
  ```bash
  # Pool health
  zpool status -x                          # only faulty pools
  zpool iostat 1                           # real-time I/O

  # Dataset usage
  zfs list -o name,used,available,mountpoint
  zfs get all tank/data

  # Scrub results
  zpool status -P
  cat /proc/spl/kstat/zfs/scrub_status

  # ARC cache stats
  arcstat
  cat /proc/spl/kstat/zfs/arcstats | head -20
  ```

  ### ZFS Best Practices
  - Always use `zfs set atime=off` (CoW makes atime pointless and slow)
  - Use `zstd` compression — it's fast and reduces I/O
  - Keep 10-20% pool free for optimal performance
  - Scrub weekly: `zpool scrub tank`
  - Use datasets for different mount points and properties
  - zvol for VM images and swap
  - Never use hardware RAID with ZFS


entity_id: ent_20260526T191743799884_0fbc5584
type: memory
category: debian/partitioning
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:43.799884
updated_at: 2026-05-26T19:17:43.799884
content:
  ## Disk Partitioning
  ### Tools
  - **fdisk:** Traditional, MBR and GPT
  - **parted:** GPT-focused, resizable
  - **cfdisk:** Interactive fdisk
  - **gdisk:** GPT-specific fdisk
  - **sfdisk:** Scriptable fdisk (good for automation)

  ### MBR vs GPT
  | Feature | MBR | GPT |
  |---------|-----|-----|
  | Max partitions | 4 primary | 128 default |
  | Max disk size | 2TB | 18 exabytes |
  | Backup table | No | Yes (LBA) |
  | CRC checksums | No | Yes |
  | EFI support | No | Yes |

  ### Partition with fdisk
  ```bash
  # Interactive partitioning
  fdisk /dev/sdb

  # Common commands in fdisk:
  # n - new partition
  # d - delete partition
  # p - print partition table
  # t - change type
  # w - write and exit
  # q - quit without changes

  # Scriptable (sfdisk)
  sfdisk /dev/sdb <<EOF
  label: gpt
  ,/512M,+1G,type=EF00          # EFI boot
  ,/512G,,type=8300             # Linux root
  ,,type=8300                   # Rest
  EOF
  ```

  ### Partition with parted
  ```bash
  # Create GPT label
  parted /dev/sdb mklabel gpt

  # Create partitions
  parted /dev/sdb mkpart primary ext4 1MiB 513MiB
  parted /dev/sdb mkpart primary ext4 513MiB 512GiB
  parted /dev/sdb mkpart primary linux-swap 512GiB 100%

  # Set boot flag
  parted /dev/sdb set 1 boot on

  # Print partition table
  parted /dev/sdb print

  # Resize partition
  parted /dev/sdb resizepart 2 1000MiB
  ```

  ### Disk Information
  ```bash
  # List all disks
  lsblk
  lsblk -f                         # with filesystem info
  lsblk -o NAME,SIZE,FSTYPE,LABEL,MOUNTPOINT

  # Detailed disk info
  fdisk -l
  blkid
  parted -l

  # Disk geometry
  hdparm -I /dev/sda
  ```

  ### Partition Types
  | Type | Code | Purpose |
  |------|------|---------|
  | EFI System | EF00 | Boot loader (UEFI) |
  | Linux root | 8300 | ext4, btrfs, xfs |
  | Linux swap | 8200 | Swap space |
  | Linux LVM | 8e00 | LVM physical volume |
  | Linux RAID | FD00 | mdadm RAID |
  | Solaris / ZFS | BF01 | ZFS |


entity_id: ent_20260526T191744008726_ab99895e
type: memory
category: debian/swap
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:44.008726
updated_at: 2026-05-26T19:17:44.008726
content:
  ## Swap Management
  ### Create Swap
  ```bash
  # Swap file (recommended for flexibility)
  fallocate -l 4G /swapfile
  chmod 600 /swapfile
  mkswap /swapfile
  swapon /swapfile

  # Add to /etc/fstab
  echo '/swapfile none swap sw 0 0' >> /etc/fstab

  # Swap partition
  mkswap /dev/sdb3
  swapon /dev/sdb3
  # fstab: UUID=xxxx none swap sw 0 0

  # Multiple swap spaces
  swapon -a                                    # enable all
  swapon -p 100 /swapfile                      # set priority
  ```

  ### Swap Configuration
  ```bash
  # swappiness (0-100)
  # 0 = avoid swap, 100 = swap aggressively
  cat /proc/sys/vm/swappiness                  # default: 60
  echo 10 > /proc/sys/vm/swappiness            # temporary
  # Permanent: /etc/sysctl.d/99-swap.conf
  vm.swappiness=10

  # vfs_cache_pressure
  # 100 = default, 50 = keep dentries longer
  echo 50 > /proc/sys/vm/vfs_cache_pressure
  ```

  ### Swap Monitoring
  ```bash
  # Swap usage
  free -h
  swapon --show
  cat /proc/swaps

  # Top swap users
  cat /proc/*/status | grep -B1 VmSwap | grep -v -- -- 2>/dev/null

  # Swap I/O
  vmstat 1 | awk 'NR>2{print $7+$8}'           # swap in+out per second
  iostat -x 1 | grep sda                       # I/O stats
  ```

  ### Swap Best Practices
  - **With SSD:** swappiness=10, use `discard=async` for TRIM
  - **With plenty of RAM:** swappiness=1, small swap for hibernation
  - **Hibernation:** swap must be >= RAM size
  - **Server:** swappiness=10-20, 2-4GB swap minimum
  - **Desktop:** swappiness=60 default is fine
  - Consider `zram` for low-RAM systems


entity_id: ent_20260526T191744216560_8cd1a9d3
type: memory
category: debian/fuse-network-fs
strength: moderate
metadata: "{\"source\": \"debian_filesystems_deep_dive\"}"
created_at: 2026-05-26T19:17:44.216560
updated_at: 2026-05-26T19:17:44.216560
content:
  ## FUSE, SSHFS, and Network Filesystems
  ### SSHFS
  ```bash
  # Install
  apt install sshfs

  # Mount remote filesystem
  sshfs user@remote:/remote/path /mnt/sshfs

  # With options
  sshfs user@remote:/path /mnt/sshfs   -o IdentityFile=~/.ssh/id_rsa   -o reconnect   -o ServerAliveInterval=15   -o CacheTimeout=0

  # Unmount
  umount /mnt/sshfs
  fusermount -u /mnt/sshfs

  # fstab entry
  user@remote:/path /mnt/sshfs fuse.sshfs   identityfile=~/.ssh/id_rsa,reconnect,port=22 0 0
  ```

  ### NFS Server Setup
  ```bash
  # Install server
  apt install nfs-kernel-server

  # Configure exports
  nano /etc/exports
  /mnt/data 192.168.1.0/24(rw,sync,no_subtree_check,no_root_squash)
  /mnt/readonly 192.168.1.0/24(ro,sync)

  # Restart
  systemctl restart nfs-kernel-server

  # Check exports
  showmount -e localhost
  ```

  ### NFS Client
  ```bash
  # Show available exports
  showmount -e 192.168.1.100

  # Mount
  mount -t nfs 192.168.1.100:/mnt/data /mnt/nfs

  # fstab
  192.168.1.100:/mnt/data /mnt/nfs nfs   rw,sync,hard,intr,_netdev,noatime 0 0
  ```

  ### CIFS/SMB
  ```bash
  # Install
  apt install cifs-utils

  # Mount
  mount -t cifs //server/share /mnt/smb   -o username=user,password=pass,vers=3.0

  # fstab
  //server/share /mnt/smb cifs   credentials=/etc/samba/credentials,vers=3.0 0 0

  # Credentials file
  nano /etc/samba/credentials
  username=user
  password=pass
  chmod 600 /etc/samba/credentials
  ```

  ### Encrypted Mounts (cryptsetup)
  ```bash
  # Create encrypted container
  cryptsetup luksFormat /dev/sdb1
  cryptsetup open /dev/sdb1 encrypted_data
  mkfs.ext4 /dev/mapper/encrypted_data
  mount /dev/mapper/encrypted_data /mnt/encrypted

  # Close
  umount /mnt/encrypted
  cryptsetup close encrypted_data
  ```


entity_id: ent_20260526T191746701065_26ab9c8a
type: memory
category: debian/apt-fundamentals
strength: moderate
metadata: "{\"source\": \"debian_package_mgmt_deep_dive\"}"
created_at: 2026-05-26T19:17:46.701065
updated_at: 2026-05-26T19:17:46.701065
content:
  ## APT Fundamentals
  ### APT Architecture
  ```
  Package Repositories → Package Index → Dependency Resolver → dpkg (installer)
                        (apt update)    (apt install)         (under the hood)
  ```

  ### Essential Commands
  ```bash
  # Update package index
  apt update                         # fetch latest package lists
  apt update --allow-releaseinfo-change  # ignore release info warnings

  # Upgrade packages
  apt upgrade                        # upgrade (won't remove packages)
  apt full-upgrade                   # upgrade (may remove/add packages)
  apt dist-upgrade                   # same as full-upgrade (alias)

  # Install packages
  apt install nginx                  # install package
  apt install nginx=1.18.0-1         # specific version
  apt install nginx --install-recommends  # include recommended packages
  apt install nginx --no-install-recommends  # minimal install

  # Remove packages
  apt remove nginx                   # remove package (keep config)
  apt purge nginx                    # remove package + config
  apt autoremove                     # remove orphaned dependencies
  apt autoremove --purge             # remove + clean configs

  # Search packages
  apt search keyword                 # search package names/descriptions
  apt search --names-only nginx      # names only
  apt list --installed               # list installed packages
  apt list --upgradable              # list upgradable packages
  apt list --manual-installed        # explicitly installed (not deps)
  ```

  ### APT Cache
  ```bash
  # Clear cache
  apt clean                          # remove all cached .deb files
  apt autoclean                      # remove obsolete .deb files

  # View cache
  apt show nginx                     # package info
  apt showpkg nginx                  # version relationships
  apt depends nginx                  # dependency tree
  apt rdepends nginx                 # reverse dependencies

  # Cache location
  /var/cache/apt/archives/           # downloaded .deb files
  /var/lib/apt/lists/                # package index files
  ```

  ### APT Configuration
  ```bash
  # Main config
  /etc/apt/apt.conf.d/               # config fragments
  /etc/apt/sources.list              # main repository list
  /etc/apt/sources.list.d/           # additional sources

  # APT preferences (pinning)
  /etc/apt/preferences               # global pinning
  /etc/apt/preferences.d/            # per-package pinning

  # APT sources format (Debian 12+ / Ubuntu 23.10+)
  # /etc/apt/sources.list
  deb http://deb.debian.org/debian bookworm main contrib non-free
  deb http://deb.debian.org/debian bookworm-updates main contrib
  deb http://security.debian.org/debian-security bookworm-security main
  ```

  ### APT Logging
  ```bash
  # History log
  cat /var/log/apt/history.log

  # Terminal output log
  cat /var/log/apt/term.log

  # Recent installs
  grep "Install:" /var/log/apt/history.log | tail -20
  ```


entity_id: ent_20260526T191746926286_66fc34df
type: memory
category: debian/apt-advanced
strength: moderate
metadata: "{\"source\": \"debian_package_mgmt_deep_dive\"}"
created_at: 2026-05-26T19:17:46.926286
updated_at: 2026-05-26T19:17:46.926286
content:
  ## Advanced APT Techniques
  ### Package Pinning
  ```bash
  # /etc/apt/preferences.d/stable-prefs
  Package: nginx
  Pin: version 1.18.0-*
  Pin-Priority: 900

  # Pin entire repository
  Package: *
  Pin: release a=stable
  Pin-Priority: 900

  Package: *
  Pin: release a=testing
  Pin-Priority: 100

  # Pin priority meanings
  # > 1000: install even if it breaks dependencies
  # 1000: exact version
  # 990: stable default
  # 500: normal priority
  # 100: only install if nothing else available
  # -1: refuse to install

  # Check pinning
  apt-cache policy nginx
  ```

  ### Offline Package Management
  ```bash
  # Download packages without installing
  apt download nginx nginx-common
  apt-get install --download-only nginx

  # Install from .deb file
  dpkg -i package.deb
  apt install -f                       # fix broken dependencies

  # Download all dependencies
  apt-get install --print-uris nginx | grep -oP "http[^']+" > urls.txt
  wget -i urls.txt
  ```

  ### APT with Proxy
  ```bash
  # /etc/apt/apt.conf.d/proxy
  Acquire::http::Proxy "http://proxy.example.com:8080";
  Acquire::https::Proxy "http://proxy.example.com:8080";

  # Or environment variable
  export http_proxy=http://proxy.example.com:8080
  apt update
  ```

  ### APT Hold/Unhold
  ```bash
  # Prevent package from being upgraded
  apt-mark hold nginx
  apt-mark hold linux-image-amd64

  # Check held packages
  dpkg --get-selections | grep hold
  apt-mark showhold

  # Remove hold
  apt-mark unhold nginx
  ```

  ### APT and Docker
  ```dockerfile
  # Minimal install
  RUN apt update && apt install -y --no-install-recommends package &&     rm -rf /var/lib/apt/lists/*

  # Multi-stage build
  FROM debian:bookworm AS builder
  RUN apt update && apt install -y build-essential

  FROM debian:bookworm-slim
  COPY --from=builder /usr/local/bin/app /usr/local/bin/app
  ```

  ### APT Hooks
  ```bash
  # /etc/apt/apt.conf.d/99-post-invoke
  DPkg::Post-Invoke { "/usr/local/bin/post-install.sh"; };
  APT::Update::Post-Invoke { "/usr/local/bin/post-update.sh"; };
  APT::Install::Pre-Invoke { "/usr/local/bin/pre-install.sh"; };

  # Example post-install hook
  #!/bin/bash
  # /usr/local/bin/post-install.sh
  apt autoremove -y
  systemctl daemon-reload
  ```

  ### APT Security
  ```bash
  # Verify package signatures
  apt-get --verify-arch update

  # Check package integrity
  dpkg -V package_name

  # GPG key management
  apt-key list                       # list keys (deprecated)
  # Modern approach: add key to /etc/apt/trusted.gpg.d/
  curl -fsSL https://keyserver.example.com/key.gpg   | gpg --dearmor -o /etc/apt/trusted.gpg.d/example.gpg

  # Secure APT transport
  apt install apt-transport-https
  ```


entity_id: ent_20260526T191747138307_e8fc0e0a
type: memory
category: debian/dpkg
strength: moderate
metadata: "{\"source\": \"debian_package_mgmt_deep_dive\"}"
created_at: 2026-05-26T19:17:47.138307
updated_at: 2026-05-26T19:17:47.138307
content:
  ## dpkg — Debian Package Manager
  ### Core dpkg Commands
  ```bash
  # Install .deb
  dpkg -i package.deb
  dpkg -i *.deb                      # install multiple (respects order)
  dpkg -i --force-depends package.deb  # ignore missing deps

  # Remove
  dpkg -r package                    # remove (keep config)
  dpkg --purge package               # remove + config

  # Query
  dpkg -l                            # list all packages
  dpkg -l | grep nginx               # filter by name
  dpkg -s nginx                      # package status/details
  dpkg -L nginx                      # list files in package
  dpkg -S /usr/bin/ls                # which package owns this file
  dpkg -C                            # check for half-configured packages

  # Verify
  dpkg -V                            # verify all packages
  dpkg -V nginx                      # verify specific package
  # Verification flags: .M size, .M mode, .M md5sum, .M user, .M group, .M mtime
  ```

  ### dpkg and File Conflicts
  ```bash
  # Force overwrite conflicting files
  dpkg -i --force-overwrite package.deb

  # Reconfigure package
  dpkg-reconfigure package_name
  dpkg-reconfigure locales           # reconfigure locales
  dpkg-reconfigure tzdata            # reconfigure timezone

  # Extract .deb contents
  dpkg-deb -x package.deb /tmp/extract
  dpkg-deb --info package.deb

  # List .deb contents (no extract)
  dpkg-deb -c package.deb
  ```

  ### dpkg Internals
  ```
  /var/lib/dpkg/
  ├── status              # package database
  ├── info/               # package info (.conffiles, .list, .preinst, etc.)
  ├── available           # available packages (legacy)
  └── diversions          # file diversions
  ```

  ### dpkg Script Hooks
  ```
  .preinst     - Before package unpacking
  .postinst    - After package unpacking
  .prerm       - Before package removal
  .postrm      - After package removal

  # Check hook scripts
  cat /var/lib/dpkg/info/nginx.postinst
  ```

  ### dpkg Best Practices
  - Use `apt` instead of `dpkg` when possible (apt handles dependencies)
  - After `dpkg -i` with broken deps: `apt install -f` to fix
  - `dpkg -S` is faster than `apt-file search` for installed files
  - `dpkg-reconfigure` for package reconfiguration
  - Backup `/var/lib/dpkg/status` before major operations


entity_id: ent_20260526T191747348438_65fc0a4d
type: memory
category: debian/repositories
strength: moderate
metadata: "{\"source\": \"debian_package_mgmt_deep_dive\"}"
created_at: 2026-05-26T19:17:47.348438
updated_at: 2026-05-26T19:17:47.348438
content:
  ## APT Repositories & Sources
  ### Repository Types
  | Type | Description |
  |------|-------------|
  | main | Debian-supported, free software |
  | contrib | Free software, non-free dependencies |
  | non-free | Non-free firmware and drivers |
  | non-free-firmware | Firmware only (Debian 12+) |

  ### Repository Configuration
  ```bash
  # /etc/apt/sources.list (Debian 12)
  deb http://deb.debian.org/debian bookworm main contrib non-free non-free-firmware
  deb http://deb.debian.org/debian bookworm-updates main contrib non-free non-free-firmware
  deb http://security.debian.org/debian-security bookworm-security main contrib non-free non-free-firmware

  # Testing repository
  deb http://deb.debian.org/debian trixie main

  # Backports
  deb http://deb.debian.org/debian bookworm-backports main
  apt install -t bookworm-backports package

  # Source packages (for building)
  deb-src http://deb.debian.org/debian bookworm main
  apt-get source package_name
  ```

  ### Adding Third-Party Repos
  ```bash
  # Method 1: sources.list
  echo "deb https://repo.example.com/debian bookworm main"   | tee /etc/apt/sources.list.d/example.list

  # Method 2: add-apt-repository
  add-apt-repository ppa:developer/ppa     # Ubuntu PPAs only
  add-apt-repository 'deb https://repo.example.com bookworm main'

  # Add GPG key (modern approach)
  curl -fsSL https://repo.example.com/key.gpg   | gpg --dearmor -o /etc/apt/trusted.gpg.d/example.gpg

  # Add repository + key in one command
  curl -fsSL https://repo.example.com/setup.sh | bash

  # Verify key
  apt-key list
  ```

  ### Repository Management
  ```bash
  # List all repositories
  cat /etc/apt/sources.list
  ls /etc/apt/sources.list.d/

  # Disable repository
  # Add # prefix to sources.list line
  # Or rename .list file in sources.list.d/

  # Check repository status
  apt-cache policy
  apt update 2>&1 | grep -E "Hit|Get|Ign|Err"

  # Update only specific repo
  apt-get update -o Dir::Etc::sourcelist="sources.list.d/example.list"
  ```

  ### Docker Registry as APT Repo
  ```bash
  # Docker official repo
  curl -fsSL https://download.docker.com/linux/debian/gpg   | gpg --dearmor -o /etc/apt/trusted.gpg.d/docker.gpg

  echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/trusted.gpg.d/docker.gpg]   https://download.docker.com/linux/debian $(lsb_release -cs) stable"   | tee /etc/apt/sources.list.d/docker.list
  ```

  ### Repository Best Practices
  - Always verify GPG keys before adding repos
  - Use `signed-by` option for key association (not `apt-key add`)
  - Pin third-party repos with lower priority
  - Keep backup of original sources.list
  - Use `apt-cache policy` to verify repo priority


entity_id: ent_20260526T191747560237_5166c63b
type: memory
category: debian/package-building
strength: moderate
metadata: "{\"source\": \"debian_package_mgmt_deep_dive\"}"
created_at: 2026-05-26T19:17:47.560237
updated_at: 2026-05-26T19:17:47.560237
content:
  ## Building Debian Packages
  ### From Source
  ```bash
  # Install build tools
  apt install build-essential devscripts dh-make debhelper

  # Get source package
  apt-get source nginx
  apt-get source --compile nginx       # build from source

  # Build dependencies
  apt-get build-dep nginx
  apt-get source --build-dep nginx

  # Build package
  cd nginx-1.18.0/
  dpkg-buildpackage -us -uc -b         # binary only
  dpkg-buildpackage -us -uc -S         # source only
  dpkg-buildpackage -us -uc            # binary + source

  # Install built package
  dpkg -i ../nginx_1.18.0-1_amd64.deb
  ```

  ### Create .deb from Scratch
  ```bash
  # Directory structure
  mkdir -p mypackage-1.0/{DEBIAN,usr/bin,etc/mypackage}
  echo '#!/bin/bash' > mypackage-1.0/usr/bin/myapp
  chmod +x mypackage-1.0/usr/bin/myapp

  # Create control file
  cat > mypackage-1.0/DEBIAN/control <<EOF
  Package: mypackage
  Version: 1.0-1
  Section: utils
  Priority: optional
  Architecture: amd64
  Depends: bash (>= 5.0)
  Maintainer: Admin <admin@example.com>
  Description: My custom package
   A simple utility package.
  EOF

  # Build
  dpkg-deb --build mypackage-1.0/
  dpkg -i mypackage-1.0.deb
  ```

  ### dh-make (Debian package from tarball)
  ```bash
  # Convert upstream tarball to Debian package
  tar xf myapp-1.0.tar.gz
  cd myapp-1.0/
  dh-make --maintainer "Admin <admin@example.com>" myapp 1.0

  # Edit debian/control, debian/changelog
  # Build
  debuild -us -uc -b
  ```

  ### Local APT Repository
  ```bash
  # Collect .deb files
  mkdir /opt/local-repo
  cp *.deb /opt/local-repo/

  # Create package index
  cd /opt/local-repo
  apt-ftparchive packages . > Packages
  gzip -k Packages
  apt-ftparchive release . > Release

  # Serve via web server
  apt install nginx
  echo 'autoindex on;' >> /etc/nginx/sites-available/default
  ln -s /opt/local-repo /var/www/html/repo

  # Add to sources.list
  echo 'deb http://localhost/repo ./ '   | tee /etc/apt/sources.list.d/local.list

  # Update and install
  apt update
  apt install mypackage
  ```

  ### Chroot Build Environment
  ```bash
  # Clean build environment
  apt install pbuilder
  pbuildер --create --distribution bookworm

  # Build package
  pbuildер mypackage_1.0-1.dsc

  # Or use schroot
  apt install schroot
  schroot -c bookworm-amd64 -d /path/to/source
  ```


entity_id: ent_20260526T191747770950_fde5c082
type: memory
category: debian/snap-flatpak
strength: moderate
metadata: "{\"source\": \"debian_package_mgmt_deep_dive\"}"
created_at: 2026-05-26T19:17:47.770950
updated_at: 2026-05-26T19:17:47.770950
content:
  ## Snap and Flatpak on Debian
  ### Snap
  ```bash
  # Install snapd
  apt install snapd
  systemctl enable --now snapd

  # Install snaps
  snap install nginx                  # latest stable
  snap install nginx --classic        # classic confinement
  snap install firefox --channel=candidate  # specific channel

  # Manage snaps
  snap list                           # list installed snaps
  snap refresh nginx                  # update
  snap refresh --list                 # pending updates
  snap remove nginx                   # remove
  snap disable nginx                  # disable without removing
  snap enable nginx                   # re-enable
  snap revert nginx                   # revert to previous version

  # Snap channels
  # stable → candidate → beta → edge
  snap install code --channel=stable
  snap install code --channel=beta

  # Snap security
  snap connections                    # list interfaces
  snap connect nginx:network         # grant permission
  snap disconnect nginx:network      # revoke permission
  ```

  ### Flatpak
  ```bash
  # Install Flatpak
  apt install flatpak
  flatpak remote-add --if-not-exists flathub   https://flathub.org/repo/flathub.flatpakrepo

  # Install apps
  flatpak install flathub org.gimp.GIMP
  flatpak install flathub org.mozilla.Firefox

  # Manage apps
  flatpak list                        # list installed
  flatpak update                      # update all
  flatpak uninstall org.gimp.GIMP    # remove
  flatpak remove --unused             # remove unused runtimes

  # Run app
  flatpak run org.gimp.GIMP

  # Flatpak permissions
  flatpak permissions                 # list permissions
  flatpak override --user --talk-name=org.freedesktop.NetworkManager org.gimp.GIMP
  ```

  ### Snap vs Flatpak Comparison
  | Feature | Snap | Flatpak |
  |---------|------|---------|
  | Package format | .snap | .flatpak |
  | Repository | Snap Store | Flathub |
  | Update mechanism | Automatic (configurable) | Manual |
  | Disk usage | Higher (bundled runtimes) | Lower (shared runtimes) |
  | Performance | Slightly slower | Slightly faster |
  | Ubuntu default | Yes | No |
  | Debian support | Good | Good |

  ### Recommendation
  - For server packages: use native APT
  - For desktop apps: Flatpak preferred on Debian
  - Snap acceptable but heavier disk footprint
  - Both provide sandboxing and universal compatibility


entity_id: ent_20260526T191747981998_9d8262e8
type: memory
category: debian/package-troubleshooting
strength: moderate
metadata: "{\"source\": \"debian_package_mgmt_deep_dive\"}"
created_at: 2026-05-26T19:17:47.981998
updated_at: 2026-05-26T19:17:47.981998
content:
  ## Package Troubleshooting
  ### Common Issues & Fixes
  ```bash
  # Broken dependencies
  apt --fix-broken install
  apt install -f

  # Lock issues (another process using APT)
  # Wait or kill the blocking process
  fuser /var/lib/dpkg/lock-frontend
  fuser /var/cache/apt/archives/lock
  # Force unlock (last resort)
  rm /var/lib/dpkg/lock-frontend
  rm /var/cache/apt/archives/lock

  # Half-installed packages
  dpkg --configure -a
  dpkg --configure --pending

  # Corrupt dpkg database
  mv /var/lib/dpkg/info /var/lib/dpkg/info_old
  mkdir /var/lib/dpkg/info
  apt update
  dpkg --configure -a
  mv /var/lib/dpkg/info/* /var/lib/dpkg/info_old/
  rm -rf /var/lib/dpkg/info
  mv /var/lib/dpkg/info_old /var/lib/dpkg/info

  # GPG key errors
  # Err: https://repo.example.com InRelease: The following signatures couldn't be verified
  curl -fsSL https://repo.example.com/key.gpg | gpg --dearmor -o /etc/apt/trusted.gpg.d/example.gpg
  apt update

  # Repository 404 errors
  # Check if distribution codename is correct
  lsb_release -cs
  # Update sources.list with correct codename
  ```

  ### Package Conflicts
  ```bash
  # Check for conflicts
  apt install -s conflicting-package  # simulate install

  # Override conflicting package
  dpkg -i --force-overwrite package.deb
  apt install -f

  # Remove conflicting package
  apt purge conflicting-package
  apt install desired-package
  ```

  ### Recovery Procedures
  ```bash
  # Emergency recovery
  mount -o remount,rw /
  apt update
  apt install --reinstall apt dpkg
  apt --fix-broken install
  dpkg --configure -a
  apt clean
  apt update
  apt full-upgrade

  # Reinstall system
  apt-get install --reinstall $(dpkg --get-selections | grep install | awk '{print $1}')
  ```

  ### Debug APT
  ```bash
  # Verbose output
  apt update -o Debug::pkgAcquire::Worker=true
  apt install -d -o Debug::pkgAcquire::Worker=true package

  # Check APT configuration
  apt-config dump
  apt-cache policy

  # Check package integrity
  debsums nginx                    # verify installed package files
  debsums -c                      # check all packages
  ```

  ### Useful Diagnostics
  ```bash
  # What files were modified
  debsums -c | grep "changed"

  # Orphaned packages
  apt autoremove --dry-run

  # Packages not from official repos
  apt list ?not(debian:bookworm) 2>/dev/null

  # Recently modified system files
  find /usr /etc -mtime -1 -type f 2>/dev/null
  ```


entity_id: ent_20260526T191748192603_ee913c97
type: memory
category: debian/system-upgrades
strength: moderate
metadata: "{\"source\": \"debian_package_mgmt_deep_dive\"}"
created_at: 2026-05-26T19:17:48.192603
updated_at: 2026-05-26T19:17:48.192603
content:
  ## Debian System Upgrades
  ### Minor Version Updates
  ```bash
  # Standard upgrade
  apt update
  apt full-upgrade
  apt autoremove --purge

  # Kernel upgrade
  apt install linux-image-amd64 linux-headers-amd64
  # Reboot to apply

  # Verify kernel
  uname -r
  dpkg -l | grep linux-image
  ```

  ### Major Version Upgrade (Bookworm → Trixie)
  ```bash
  # Step 1: Prepare
  apt update && apt full-upgrade
  apt autoremove --purge

  # Backup
  rsync -av /etc/ /backup/etc/
  dpkg --get-selections > /backup/package-selections.txt

  # Step 2: Update sources.list
  # Replace 'bookworm' with 'trixie' everywhere
  sed -i 's/bookworm/trixie/g' /etc/apt/sources.list
  sed -i 's/bookworm/trixie/g' /etc/apt/sources.list.d/*.list

  # Step 3: Update
  apt update
  apt full-upgrade            # base system upgrade
  apt full-upgrade            # second run (catches remaining)

  # Step 4: Clean up
  apt autoremove --purge
  dpkg --configure -a

  # Step 5: Verify
  lsb_release -a
  uname -r
  systemctl list-units --state=failed
  ```

  ### In-Place Upgrade Best Practices
  - Backup everything first
  - Upgrade to latest point release before major upgrade
  - Read Release Notes: https://www.debian.org/releases/
  - Keep third-party repos disabled during upgrade
  - Test in non-production environment first
  - Keep upgrade log: `apt full-upgrade 2>&1 | tee /var/log/upgrade.log`

  ### Rollback After Upgrade
  ```bash
  # If upgrade fails
  # 1. Boot from Live USB
  # 2. Mount root filesystem
  # 3. Fix sources.list (revert to old version)
  # 4. Chroot and downgrade
  mount /dev/sda1 /mnt
  for dir in /dev /dev/pts /proc /sys /run; do
    mount --bind $dir /mnt$dir
  done
  chroot /mnt
  apt update
  apt full-upgrade  # downgrade to previous version
  ```

  ### Automated Updates (unattended-upgrades)
  ```bash
  # Install
  apt install unattended-upgrades

  # Configure
  nano /etc/apt/apt.conf.d/50unattended-upgrades
  # Allowed origins:
  Unattended-Upgrade::Allowed-Origins {
    "Debian bookworm-security";
    "Debian bookworm-updates";
  };

  # Enable
  dpkg-reconfigure unattended-upgrades

  # Check status
  cat /var/log/unattended-upgrades/unattended-upgrades.log

  # Manual run
  unattended-upgrade -v
  ```

  ### APT Proxy for Upgrades
  ```bash
  # /etc/apt/apt.conf.d/01proxy
  Acquire::http::Proxy "http://proxy.internal:3128";
  Acquire::https::Proxy "http://proxy.internal:3128";

  # Or for single command
  apt update -o Acquire::http::Proxy="http://proxy:3128"
  ```


entity_id: ent_20260526T191750596936_259fff56
type: memory
category: debian/firewall-nftables
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:50.596936
updated_at: 2026-05-26T19:17:50.596936
content:
  ## Debian Firewall — nftables
  ### nftables Basics
  ```bash
  # Check current rules
  nft list ruleset

  # Create table and chains
  nft add table inet firewall
  nft add chain inet firewall input '{ type filter hook input priority 0\; policy drop\; }'
  nft add chain inet firewall forward '{ type filter hook forward priority 0\; policy drop\; }'
  nft add chain inet firewall output '{ type filter hook output priority 0\; policy accept\; }'

  # Allow loopback
  nft add rule inet firewall input iifname lo accept
  nft add rule inet firewall output oifname lo accept

  # Allow established/related
  nft add rule inet firewall input ct state established,related accept
  nft add rule inet firewall input ct state invalid drop
  ```

  ### Essential Rules
  ```bash
  # Allow SSH
  nft add rule inet firewall input tcp dport 22 ct state new accept

  # Allow HTTP/HTTPS
  nft add rule inet firewall input tcp dport { 80, 443 } ct state new accept

  # Allow ICMP (ping)
  nft add rule inet firewall input ip protocol icmp accept
  nft add rule inet firewall input ip6 nexthdr icmpv6 accept

  # Allow DNS out
  nft add rule inet firewall output udp dport 53 accept
  nft add rule inet firewall output tcp dport 53 accept

  # Rate limit SSH (brute force protection)
  nft add rule inet firewall input tcp dport 22 ct state new limit rate 5/minute accept
  nft add rule inet firewall input tcp dport 22 ct state new drop
  ```

  ### Advanced nftables
  ```bash
  # Port set (efficient for many ports)
  nft add set inet firewall allowed_ports '{ type inet_service\; }'
  nft add element inet firewall allowed_ports '{ 22, 80, 443, 8080, 8443 }'
  nft add rule inet firewall input tcp dport @allowed_ports ct state new accept

  # GeoIP blocking
  nft add set inet firewall blocked_countries '{ type ipv4_addr\; flags interval\; }'
  # Import GeoIP data
  nft add element inet firewall blocked_countries '{ 10.0.0.0/8, 172.16.0.0/12 }'
  nft add rule inet firewall input ip saddr @blocked_countries drop

  # Port scanning protection
  nft add rule inet firewall input tcp flags syn limit rate 20/second accept
  nft add rule inet firewall input tcp flags syn drop

  # NAT (port forwarding)
  nft add table ip nat
  nft add chain ip nat prerouting '{ type nat hook prerouting priority -100\; }'
  nft add rule ip nat prerouting iifname eth0 tcp dport 8080 dnat to 192.168.1.100:80

  # Masquerade (outbound NAT)
  nft add chain ip nat postrouting '{ type nat hook postrouting priority 100\; }'
  nft add rule ip nat postrouting oifname eth0 masquerade
  ```

  ### Save and Restore
  ```bash
  # Save rules
  nft list ruleset > /etc/nftables.conf

  # Load rules
  nft -f /etc/nftables.conf

  # Enable service
  systemctl enable --now nftables

  # Backup rules
  nft list ruleset > /root/nftables-backup-$(date +%Y%m%d).conf
  ```

  ### nftables Best Practices
  - Default deny policy on input/forward
  - Allow established/related connections early
  - Use sets for managing IP/port lists
  - Rate limit on commonly attacked ports
  - Save rules after every change
  - Test changes carefully — don't lock yourself out


entity_id: ent_20260526T191750808157_1af930d4
type: memory
category: debian/ssh-hardening
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:50.808157
updated_at: 2026-05-26T19:17:50.808157
content:
  ## SSH Hardening
  ### /etc/ssh/sshd_config
  ```
  # Port
  Port 2222

  # Protocol (Debian only ships OpenSSH 7+ which is v2 only)
  # Protocol 2

  # Host keys
  HostKey /etc/ssh/ssh_host_ed25519_key
  HostKey /etc/ssh/ssh_host_rsa_key

  # Authentication
  PermitRootLogin no
  PasswordAuthentication no
  PubkeyAuthentication yes
  AuthorizedKeysFile .ssh/authorized_keys
  AuthenticationMethods publickey

  # Login limits
  MaxAuthTries 3
  MaxSessions 5
  LoginGraceTime 30

  # Keepalive
  ClientAliveInterval 300
  ClientAliveCountMax 2

  # Logging
  LogLevel VERBOSE

  # Banner
  Banner /etc/ssh/banner

  # Restrict users
  AllowUsers admin deploy
  AllowGroups sshusers

  # Disable X11 forwarding (unless needed)
  X11Forwarding no

  # Disable empty passwords
  PermitEmptyPasswords no

  # Disable host-based auth
  HostbasedAuthentication no
  IgnoreRhosts yes

  # Disable tunneling (unless needed)
  PermitTunnel no

  # Use PAM
  UsePAM yes
  ```

  ### Key-Based Authentication
  ```bash
  # Generate key on client
  ssh-keygen -t ed25519 -C "admin@server"
  ssh-keygen -t rsa -b 4096 -C "admin@server"    # RSA alternative

  # Copy key to server
  ssh-copy-id -p 2222 admin@server

  # Test connection
  ssh -p 2222 -o PasswordAuthentication=no admin@server

  # Disable password auth after key works
  nano /etc/ssh/sshd_config
  PasswordAuthentication no
  systemctl reload sshd
  ```

  ### SSH with Multiple Keys
  ```bash
  # ~/.ssh/config
  Host server1
      HostName 192.168.1.10
      Port 2222
      User admin
      IdentityFile ~/.ssh/id_ed25519_server1

  Host server2
      HostName 192.168.1.11
      Port 2222
      User deploy
      IdentityFile ~/.ssh/id_ed25519_server2
  ```

  ### SSH Agent Forwarding
  ```bash
  # Enable on server (if needed)
  AllowAgentForwarding yes

  # Client config
  Host server1
      ForwardAgent yes
  ```

  ### SSH Audit & Monitoring
  ```bash
  # Failed login attempts
  grep "Failed password" /var/log/auth.log | tail -20
  grep "Invalid user" /var/log/auth.log | tail -20

  # Successful logins
  grep "Accepted" /var/log/auth.log | tail -20

  # SSH brute force with fail2ban
  apt install fail2ban
  nano /etc/fail2ban/jail.local
  [sshd]
  enabled = true
  port = 2222
  filter = sshd
  logpath = /var/log/auth.log
  maxretry = 3
  bantime = 3600
  findtime = 600

  # SSH audit commands
  ssh -Q cipher                     # list ciphers
  ssh -Q kex                       # list key exchange
  ssh -Q mac                       # list MAC algorithms
  ```

  ### SSH Tunneling (when needed)
  ```bash
  # Local port forwarding
  ssh -L 8080:localhost:80 server1

  # Remote port forwarding
  ssh -R 8080:localhost:80 server1

  # Dynamic SOCKS proxy
  ssh -D 1080 server1

  # Port forwarding (no shell)
  ssh -N -L 8080:localhost:80 server1
  ```


entity_id: ent_20260526T191751019789_4ea74f10
type: memory
category: debian/kernel-hardening
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:51.019789
updated_at: 2026-05-26T19:17:51.019789
content:
  ## Kernel Hardening — sysctl
  ### /etc/sysctl.d/99-hardening.conf
  ```
  # IP Spoofing protection
  net.ipv4.conf.all.rp_filter = 1
  net.ipv4.conf.default.rp_filter = 1

  # Ignore ICMP broadcast requests
  net.ipv4.icmp_echo_ignore_broadcasts = 1

  # Disable source packet routing
  net.ipv4.conf.all.accept_source_route = 0
  net.ipv6.conf.all.accept_source_route = 0
  net.ipv4.conf.default.accept_source_route = 0
  net.ipv6.conf.default.accept_source_route = 0

  # Ignore send redirects
  net.ipv4.conf.all.send_redirects = 0
  net.ipv4.conf.default.send_redirects = 0

  # Block ICMP redirects
  net.ipv4.conf.all.accept_redirects = 0
  net.ipv4.conf.default.accept_redirects = 0
  net.ipv4.conf.all.secure_redirects = 0
  net.ipv4.conf.default.secure_redirects = 0
  net.ipv6.conf.all.accept_redirects = 0
  net.ipv6.conf.default.accept_redirects = 0

  # Log Martian packets
  net.ipv4.conf.all.log_martians = 1
  net.ipv4.conf.default.log_martians = 1

  # Disable IP forwarding
  net.ipv4.ip_forward = 0
  net.ipv6.conf.all.forwarding = 0

  # SYN flood protection
  net.ipv4.tcp_syncookies = 1
  net.ipv4.tcp_max_syn_backlog = 2048
  net.ipv4.tcp_synack_retries = 2
  net.ipv4.tcp_syn_retries = 5

  # Disable IPv6 (if not needed)
  net.ipv6.conf.all.disable_ipv6 = 1
  net.ipv6.conf.default.disable_ipv6 = 1

  # Protect against Smurf attacks
  net.ipv4.icmp_echo_ignore_broadcasts = 1

  # Limit kernel pointer exposure
  kernel.kptr_restrict = 2
  kernel.dmesg_restrict = 1

  # Restrict core dumps
  fs.suid_dumpable = 0

  # Disable proc filesystem info for unprivileged users
  kernel.yama.ptrace_scope = 1

  # Prevent kernel module loading (after boot)
  kernel.modules_disabled = 1    # Careful with this one

  # Reduce memory exposure
  kernel.randomize_va_space = 2
  ```

  ### Apply Sysctl Settings
  ```bash
  # Apply all settings
  sysctl -p /etc/sysctl.d/99-hardening.conf

  # Apply all config files
  sysctl --system

  # Check specific setting
  sysctl net.ipv4.tcp_syncookies
  sysctl -a | grep "rp_filter"

  # Verify all settings applied
  cat /proc/sys/net/ipv4/tcp_syncookies
  ```

  ### Kernel Module Hardening
  ```bash
  # Blacklist unnecessary modules
  # /etc/modprobe.d/blacklist.conf
  blacklist usb-storage
  blacklist firewire-core
  blacklist bluetooth
  blacklist rfkill

  # Prevent loading blacklisted modules
  echo "install usb-storage /bin/true" >> /etc/modprobe.d/blacklist.conf

  # Check loaded modules
  lsmod
  modinfo module_name
  ```

  ### Kernel Hardening with grsecurity (optional)
  ```bash
  # Not available in Debian repos
  # Requires custom kernel compilation
  # Alternative: use Debian's hardening patches (default in bookworm)
  dpkg -l | grep linux-image
  # Modern Debian kernels include:
  # - Kernel Hardening (KASLR, stack protector, etc.)
  # - GCC hardened flags (-fstack-protector-strong)
  # - RELRO, PIE for system binaries
  ```

  ### Verify Hardening
  ```bash
  # Check kernel hardening level
  cat /proc/sys/kernel/randomize_va_space
  # 2 = full ASLR (good)

  cat /proc/sys/kernel/kptr_restrict
  # 2 = hide kernel pointers (good)

  cat /proc/sys/kernel/dmesg_restrict
  # 1 = restrict dmesg (good)

  # Check compiler hardening flags
  readelf -l /bin/bash | grep "GNU_RELRO"
  readelf -d /bin/bash | grep "FLAGS"
  ```


entity_id: ent_20260526T191751230892_7c1ab1cb
type: memory
category: debian/auditing
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:51.230892
updated_at: 2026-05-26T19:17:51.230892
content:
  ## System Auditing & Monitoring
  ### Audit Framework
  ```bash
  # Install
  apt install auditd audispd-plugins

  # Start audit daemon
  systemctl enable --now auditd

  # Check status
  systemctl status auditd
  ausearch -sc SUCCESS               # successful events
  ausearch -sc FAILED                # failed events
  ```

  ### Common Audit Rules
  ```bash
  # /etc/audit/rules.d/audit.rules

  # Monitor system administration
  -w /etc/ssh/sshd_config -p wa -k sshd_config
  -w /etc/sudoers -p wa -k sudoers
  -w /etc/sudoers.d/ -p wa -k sudoers
  -w /etc/passwd -p wa -k identity
  -w /etc/shadow -p wa -k identity
  -w /etc/group -p wa -k identity

  # Monitor file deletion
  -w /usr/bin/sudo -p x -k privileged_command
  -w /bin/su -p x -k privileged_command

  # Monitor user/group changes
  -w /usr/sbin/useradd -p x -k user_modification
  -w /usr/sbin/userdel -p x -k user_modification
  -w /usr/sbin/groupadd -p x -k group_modification
  -w /usr/sbin/groupdel -p x -k group_modification

  # Monitor network changes
  -w /etc/network/ -p wa -k network_config
  -w /etc/hosts -p wa -k network_config
  -w /etc/resolv.conf -p wa -k network_config

  # Monitor SSH keys
  -w /home/ -p wa -k ssh_keys

  # Monitor cron jobs
  -w /etc/crontab -p wa -k cron
  -w /etc/cron.d/ -p wa -k cron
  -w /var/spool/cron/ -p wa -k cron

  # Monitor login/logout
  -w /var/log/faillog -p wa -k logins
  -w /var/log/lastlog -p wa -k logins

  # Monitor kernel modules
  -w /sbin/insmod -p x -k kernel_modules
  -w /sbin/rmmod -p x -k kernel_modules
  -w /sbin/modprobe -p x -k kernel_modules

  # Monitor file access to sensitive files
  -a always,exit -F arch=b64 -S execve -k exec_commands
  ```

  ### Query Audit Logs
  ```bash
  # Search by key
  ausearch -k sshd_config
  ausearch -k sudoers
  ausearch -k identity

  # Search by user
  ausearch -us 1000                    # UID 1000
  ausearch -us admin                   # username

  # Search by date
  ausearch -ts today
  ausearch -ts yesterday
  ausearch -ts recent-24h

  # Search by event type
  ausearch -sc SUCCESS                 # successful events
  ausearch -sc FAILED                  # failed events

  # Search by syscall
  ausearch -sc execve                   # process execution
  ausearch -sc open                     # file opens
  ausearch -sc connect                  # network connections

  # Format output
  ausearch -k sshd_config -i           # human-readable
  ausearch -k sshd_config --format csv
  ```

  ### File Integrity Monitoring (AIDE)
  ```bash
  # Install
  apt install aide

  # Initialize database
  aide --init

  # Move initial database
  mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

  # Check integrity
  aide --check

  # Schedule daily checks
  # /etc/cron.daily/aide
  #!/bin/bash
  aide --check | mail -s "AIDE Report" admin@example.com
  ```

  ### Log Management
  ```bash
  # Install rsyslog
  apt install rsyslog

  # Configure remote logging
  # /etc/rsyslog.d/50-remote.conf
  *.* @@logserver.example.com:514     # TCP (reliable)
  *.* @logserver.example.com:514      # UDP (faster)

  # Log rotation
  # /etc/logrotate.d/syslog
  /var/log/syslog {
      weekly
      rotate 52
      compress
      delaycompress
      missingok
      notifempty
      create 640 root adm
      postrotate
          systemctl reload rsyslog
      endscript
  }

  # View logs
  journalctl -u sshd --since "1 hour ago"
  journalctl -u sshd --since "today"
  journalctl -p err --since "1 day ago"
  journalctl --disk-usage
  journalctl --vacuum-time=7d
  ```


entity_id: ent_20260526T191751442673_d7783294
type: memory
category: debian/user-security
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:51.442673
updated_at: 2026-05-26T19:17:51.442673
content:
  ## User & Permission Security
  ### User Management Best Practices
  ```bash
  # Create users with proper settings
  useradd -m -s /bin/bash -c "John Doe" johndoe
  passwd johndoe

  # Set password expiry
  chage -M 90 johndoe                 # max 90 days
  chage -m 7 johndoe                  # min 7 days
  chage -W 14 johndoe                 # warn 14 days before
  chage -l johndoe                    # list password policy

  # Lock unused accounts
  usermod -L username                # lock account
  passwd -l username                 # lock password
  passwd -u username                 # unlock

  # Set strong password requirements
  # /etc/pam.d/common-password
  password requisite pam_pwquality.so minlen=12 dcredit=1 ucredit=1 ocredit=1 lcredit=1
  ```

  ### Sudo Configuration
  ```bash
  # /etc/sudoers (use visudo!)
  # Allow specific commands
  admin ALL=(ALL) /usr/bin/apt, /usr/bin/systemctl

  # Allow without password for specific commands
  admin ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx

  # Command aliases
  Cmnd_Alias SERVICES = /usr/bin/systemctl restart *, /usr/bin/systemctl stop *
  admin ALL=(ALL) SERVICES

  # Time-limited sudo
  Defaults:admin timestamp_timeout=5

  # Log all sudo commands
  Defaults logfile="/var/log/sudo.log"
  Defaults log_input, log_output
  ```

  ### File Permissions
  ```bash
  # Critical file permissions
  chmod 600 /etc/shadow
  chmod 644 /etc/passwd
  chmod 700 /root
  chmod 755 /home/username

  # Set UID/GID bits (use sparingly)
  chmod u+s /usr/bin/passwd           # SUID
  chmod g+s /shared/dir               # SGID (inherit group)

  # Sticky bit on /tmp
  chmod +t /tmp

  # Find world-writable files
  find / -type f -perm -o+w ! -path "/proc/*" ! -path "/sys/*" 2>/dev/null

  # Find SUID binaries
  find / -type f -perm -4000 2>/dev/null

  # Find SGID binaries
  find / -type f -perm -2000 2>/dev/null

  # Find files without owner
  find / -type f -nouser 2>/dev/null
  find / -type f -nogroup 2>/dev/null
  ```

  ### Group Management
  ```bash
  # Create groups
  groupadd sshusers
  groupadd developers
  groupadd operators

  # Add users to groups
  usermod -aG sshusers admin
  usermod -aG developers,sshusers developer1

  # Set default group for new files
  usermod -g developers developer1

  # View group membership
  groups username
  id username
  getent group groupname
  ```

  ### PAM Configuration
  ```bash
  # Account lockout after failed attempts
  # /etc/pam.d/common-auth
  auth required pam_faildelay.so delay=2000000
  auth required pam_tally2.so deny=5 unlock_time=900 even_dig

  # Limit concurrent sessions
  # /etc/pam.d/common-session
  session required pam_limits.so
  # /etc/security/limits.d/99-sessions.conf
  * hard maxlogins 10

  # Restrict sudo by time
  # /etc/pam.d/sudo
  auth required pam_time.so
  # /etc/security/time.conf
  sudo;admin;Wk0900-1700;*
  ```

  ### Security Auditing
  ```bash
  # Check for empty passwords
  awk -F: '($2 == "" { print $1 })' /etc/shadow

  # Check for root-level accounts
  awk -F: '($3 == 0) { print $1 }' /etc/passwd

  # Check for world-writable directories
  find / -type d -perm -0002 ! -path "/proc/*" ! -path "/sys/*" 2>/dev/null

  # List all users with login shells
  awk -F: '($7 ~ /bash|sh|zsh/) { print $1, $7 }' /etc/passwd

  # Check password ages
  awk -F: '($5 < 30 || $5 > 90) { print $1, "days:", $5 }' /etc/shadow
  ```


entity_id: ent_20260526T191751653535_c14e5828
type: memory
category: debian/encryption
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:51.653535
updated_at: 2026-05-26T19:17:51.653535
content:
  ## Encryption on Debian
  ### Disk Encryption (LUKS)
  ```bash
  # Install
  apt install cryptsetup

  # Full disk encryption
  cryptsetup luksFormat /dev/sdb1      # WARNING: destroys data
  cryptsetup open /dev/sdb1 encrypted_disk
  mkfs.ext4 /dev/mapper/encrypted_disk
  mount /dev/mapper/encrypted_disk /mnt/encrypted

  # Close
  umount /mnt/encrypted
  cryptsetup close encrypted_disk

  # Add key slot
  cryptsetup luksAddKey /dev/sdb1

  # Remove key slot
  cryptsetup luksDelKey /dev/sdb1 slot_num

  # Check LUKS header
  cryptsetup luksDump /dev/sdb1
  ```

  ### Partition Encryption (boot + root)
  ```bash
  # For new installations
  # During Debian installer, select "Guided - use entire disk with LVM"
  # Then select "Encrypt the new LVM volume group"

  # Post-install check
  cat /etc/crypttab
  # sda5_crypt UUID=xxxxxx none luks

  # fstab entry
  /dev/mapper/sda5_crypt / ext4 errors=remount-ro 0 1
  ```

  ### TLS/SSL with OpenSSL
  ```bash
  # Generate self-signed certificate
  openssl req -x509 -nodes -days 365 -newkey rsa:4096   -keyout /etc/ssl/private/server.key   -out /etc/ssl/certs/server.crt   -subj "/CN=example.com"

  # Generate CSR
  openssl req -new -newkey rsa:4096 -nodes   -keyout /etc/ssl/private/server.key   -out /etc/ssl/certs/server.csr

  # Sign CSR with CA
  openssl x509 -req -days 365   -in /etc/ssl/certs/server.csr   -CA /etc/ssl/certs/ca.crt   -CAkey /etc/ssl/private/ca.key   -CAcreateserial   -out /etc/ssl/certs/server.crt

  # Verify certificate
  openssl x509 -in /etc/ssl/certs/server.crt -text -noout
  openssl s_client -connect example.com:443 -servername example.com

  # Check TLS version
  openssl s_client -connect example.com:443 -tls1_2
  openssl s_client -connect example.com:443 -tls1_3
  ```

  ### GPG Encryption
  ```bash
  # Generate GPG key
  gpg --full-generate-key
  # RSA 4096, no expiry, your name/email

  # List keys
  gpg --list-keys
  gpg --list-secret-keys

  # Encrypt file
  gpg --encrypt --recipient "admin@example.com" file.txt
  # Creates file.txt.gpg

  # Decrypt file
  gpg --decrypt file.txt.gpg

  # Sign file
  gpg --sign file.txt
  gpg --clearsign file.txt         # signed text file
  gpg --detach-sign file.txt       # detached signature

  # Verify signature
  gpg --verify file.txt.sig file.txt

  # Export/import keys
  gpg --export --armor admin@example.com > admin.pub.asc
  gpg --import friend.pub.asc

  # Delete key
  gpg --delete-secret-keys "admin@example.com"
  gpg --delete-keys "admin@example.com"
  ```

  ### SSH Key Encryption
  ```bash
  # Generate encrypted SSH key
  ssh-keygen -t ed25519 -C "admin@server"
  # Enter passphrase for additional security

  # Use ssh-agent
  eval "$(ssh-agent -s)"
  ssh-add ~/.ssh/id_ed25519
  ```

  ### VeraCrypt (for cross-platform)
  ```bash
  # Install
  apt install veracrypt

  # Create encrypted container
  veracrypt -t -c -k "" -p "password" -f /path/to/file.img   --hash sha512 --encryption aes --filesystem ext4   -s 10G

  # Mount
  veracrypt -t --protect-hidden no /path/to/file.img /mnt/veracrypt
  ```


entity_id: ent_20260526T191751864356_3e68febe
type: memory
category: debian/intrusion-detection
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:51.864356
updated_at: 2026-05-26T19:17:51.864356
content:
  ## Intrusion Detection & Prevention
  ### Fail2ban
  ```bash
  # Install
  apt install fail2ban

  # Configuration
  nano /etc/fail2ban/jail.local
  [DEFAULT]
  bantime = 3600
  findtime = 600
  maxretry = 5
  banaction = nftables-multiport

  [sshd]
  enabled = true
  port = 2222
  filter = sshd
  logpath = /var/log/auth.log
  maxretry = 3
  bantime = 7200

  [nginx-http-auth]
  enabled = true
  port = http,https
  filter = nginx-http-auth
  logpath = /var/log/nginx/error.log
  maxretry = 5

  # Restart
  systemctl restart fail2ban
  ```

  ### Check Fail2ban
  ```bash
  # Status
  fail2ban-client status
  fail2ban-client status sshd

  # Unban IP
  fail2ban-client set sshd unbanip 192.168.1.100

  # View logs
  journalctl -u fail2ban -f
  ```

  ### OSSEC (Host-based IDS)
  ```bash
  # Install
  apt install ossec-hids

  # Configure
  nano /var/ossec/etc/ossec.conf
  <!-- Check for rootkits -->
  <rootcheck>
    <enabled>yes</enabled>
    <check_files>yes</check_files>
    <check_trojans>yes</check_trojans>
    <check_devices>yes</check_devices>
    <check_system>yes</check_system>
  </rootcheck>

  <!-- File integrity monitoring -->
  <syscheck>
    <directories check_all="yes">/etc,/usr,/bin</directories>
    <ignore>/etc/mtab</ignore>
    <ignore>/etc/hosts.deny</ignore>
  </syscheck>

  # Start
  systemctl enable --now ossec-hids
  ```

  ### Lynis (Security Auditing)
  ```bash
  # Install
  apt install lynis

  # Run audit
  lynis audit system

  # Run specific tests
  lynis audit system --tests 8112,9234,8654

  # Generate report
  lynis audit system --report

  # Hardening check
  lynis audit system --pentest-mode

  # Scheduled audits
  # /etc/cron.weekly/lynis
  #!/bin/bash
  lynis audit system | mail -s "Weekly Security Audit" admin@example.com
  ```

  ### Tripwire (File Integrity)
  ```bash
  # Install
  apt install tripwire

  # Initialize
  tripwire --init

  # Update policy
  tripwire --update --interactive

  # Check integrity
  tripwire --check

  # View reports
  cat /var/lib/tripwire/report/hostname-$(date +%Y%m%d-%H%M%S).twr
  ```

  ### Network IDS with Suricata
  ```bash
  # Install
  apt install suricata

  # Configure
  nano /etc/suricata/suricata.yaml
  # Set home_net: '192.168.1.0/24'
  # Enable rule-sets

  # Load rules
  suricata-update

  # Start
  systemctl enable --now suricata

  # View alerts
  cat /var/log/suricata/fast.log
  cat /var/log/suricata/eve.json | jq '.alert'
  ```


entity_id: ent_20260526T191752074811_0dba43d2
type: memory
category: debian/apparmor-selinux
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:52.074811
updated_at: 2026-05-26T19:17:52.074811
content:
  ## Mandatory Access Control — AppArmor
  ### AppArmor Basics
  ```bash
  # Install
  apt install apparmor apparmor-utils

  # Check status
  aa-status

  # Profile modes
  # enforce - restrict based on profile
  # complain - log violations but allow
  # disabled - no enforcement

  # List profiles
  aa-status | grep -A100 "profiles are loaded"
  ```

  ### AppArmor Profiles
  ```bash
  # Create profile for application
  aa-genprof /usr/bin/nginx

  # Profile example: /etc/apparmor.d/usr.bin.nginx
  abi <abi/4.0>,
  include <tunables/global>

  /usr/bin/nginx {
    include <abstractions/base>
    include <abstractions/nameservice>
    
    /usr/bin/nginx ix,
    /var/log/nginx/** rw,
    /var/www/html/** r,
    /etc/nginx/** r,
    /run/nginx.pid rw,
    network inet tcp,
    network inet6 tcp,
  }

  # Set profile mode
  aa-enforce /etc/apparmor.d/usr.bin.nginx
  aa-complain /etc/apparmor.d/usr.bin.nginx
  aa-disable /etc/apparmor.d/usr.bin.nginx

  # Reload profile
  apparmor_parser -r /etc/apparmor.d/usr.bin.nginx

  # Check violations
  dmesg | grep apparmor
  grep apparmor /var/log/syslog
  auditctl -l | grep apparmor
  ```

  ### AppArmor Utilities
  ```bash
  # Generate profile
  aa-genprof /usr/bin/application

  # Log profile violations
  aa-logprof

  # Change profile mode
  aa-complain /etc/apparmor.d/profile
  aa-enforce /etc/apparmor.d/profile

  # Confinement status
  aa-status
  aa-is-enabled

  # AppArmor cache
  apparmor_parser -Ka                 # check all profiles for errors
  ```

  ### SELinux Alternative (not default on Debian)
  ```bash
  # Install (optional, not recommended on Debian)
  apt install selinux-basics selinux-policy-default

  # Set default mode
  selinux-config-enforcing             # enforcing mode
  selinux-config-permissive            # permissive mode
  selinux-config-disabled              # disable

  # Check status
  selinux-status
  ```

  ### Recommendation
  - Use AppArmor on Debian (native integration)
  - SELinux is RHEL/CentOS default — avoid mixing
  - Start with complain mode, review logs, then enforce
  - Generate profiles with aa-genprof, then fine-tune


entity_id: ent_20260526T191752286445_193965df
type: memory
category: debian/secrets-management
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:52.286445
updated_at: 2026-05-26T19:17:52.286445
content:
  ## Secrets & Credential Management
  ### Pass (Standard Unix Password Manager)
  ```bash
  # Install
  apt install pass

  # Initialize
  pass init "Your GPG Key ID"

  # Add password
  pass insert work/server1
  pass insert work/server1/ssh_key    # nested

  # Use password
  pass show work/server1              # display
  pass show work/server1 | pbcopy     # copy to clipboard (macOS)
  pass show work/server1 | xclip      # copy (Linux)

  # List passwords
  pass ls

  # Generate password
  pass generate work/newserver 16     # 16 char random password
  pass generate -c work/newserver 20  # with common chars
  ```

  ### Vault (HashiCorp)
  ```bash
  # Download
  curl -fsSL https://releases.hashicorp.com/vault/1.15.0/vault_1.15.0_linux_amd64.zip   | sudo unzip -d /usr/local/bin/

  # Initialize
  vault server -dev                   # dev mode (testing only)
  vault operator init
  vault operator unseal

  # Store secrets
  vault kv put secret/db/password password=supersecret
  vault kv get secret/db/password

  # AppRole auth
  vault write auth/approle/role/myapp   token_ttl=1h token_max_ttl=2h

  # Token management
  vault token create -ttl=1h
  vault token lookup
  ```

  ### Environment Variables
  ```bash
  # ~/.env (not committed to git)
  export DB_PASSWORD="supersecret"
  export API_KEY="sk-xxxx"

  # Load in scripts
  set -a
  source ~/.env
  set +a

  # Docker
  docker run -e DB_PASSWORD="secret" myapp
  docker run --env-file .env myapp
  ```

  ### SSH Key Management
  ```bash
  # Key-based auth for servers
  ssh-keygen -t ed25519 -C "admin@server" -f ~/.ssh/server_ed25519

  # Multiple keys per server
  # ~/.ssh/config
  Host server1
      HostName 192.168.1.10
      IdentityFile ~/.ssh/server1_ed25519

  # Key passphrase with ssh-agent
  eval "$(ssh-agent -s)"
  ssh-add ~/.ssh/server_ed25519
  ssh-add -l                            # list loaded keys
  ```

  ### Secrets Rotation
  ```bash
  # Automated password rotation (example for PostgreSQL)
  #!/bin/bash
  NEW_PASS=$(openssl rand -base64 32)
  pass replace db/main <<< "$NEW_PASS"
  psql -c "ALTER USER appuser WITH PASSWORD '$NEW_PASS';"
  systemctl restart myapp
  ```


entity_id: ent_20260526T191752498726_f968fc78
type: memory
category: debian/automated-hardening
strength: moderate
metadata: "{\"source\": \"debian_security_hardening_deep_dive\"}"
created_at: 2026-05-26T19:17:52.498726
updated_at: 2026-05-26T19:17:52.498726
content:
  ## Automated Security Hardening
  ### Automated Security Check Script
  ```bash
  #!/bin/bash
  # /usr/local/bin/security-check.sh

  echo "=== Security Check Report ==="
  echo "Date: $(date)"
  echo ""

  # Check for empty passwords
  echo "--- Empty Passwords ---"
  awk -F: '($2 == "" { print $1 })' /etc/shadow

  # Check for world-writable files
  echo "--- World-Writable Files ---"
  find / -type f -perm -o+w ! -path "/proc/*" ! -path "/sys/*" 2>/dev/null

  # Check for SUID binaries
  echo "--- SUID Binaries ---"
  find / -type f -perm -4000 2>/dev/null

  # Check SSH config
  echo "--- SSH Settings ---"
  grep -E "^(PermitRootLogin|PasswordAuthentication|X11Forwarding)" /etc/ssh/sshd_config

  # Check firewall
  echo "--- Firewall Rules ---"
  nft list ruleset | head -20

  # Check failed logins
  echo "--- Recent Failed Logins ---"
  grep "Failed password" /var/log/auth.log | tail -10

  echo ""
  echo "=== End Report ==="
  ```

  ### Automated Hardening Checklist
  ```bash
  # 1. Update system
  apt update && apt full-upgrade -y

  # 2. Remove unused packages
  apt autoremove --purge -y

  # 3. Install security tools
  apt install -y fail2ban rkhunter chkrootkit apparmor

  # 4. Configure fail2ban
  systemctl enable --now fail2ban

  # 5. Enable AppArmor
  aa-enforce /etc/apparmor.d/*

  # 6. Configure kernel hardening
  cp /etc/sysctl.d/99-hardening.conf /etc/sysctl.d/99-hardening.conf.bak
  sysctl --system

  # 7. Set up audit framework
  systemctl enable --now auditd

  # 8. Configure log rotation
  apt install -y logrotate

  # 9. Set password policies
  # /etc/login.defs
  PASS_MAX_DAYS   90
  PASS_MIN_DAYS   7
  PASS_WARN_AGE   14
  PASS_MIN_LEN    12

  # 10. Enable automatic security updates
  apt install -y unattended-upgrades
  dpkg-reconfigure -plow unattended-upgrades
  ```

  ### Weekly Security Audit (cron)
  ```bash
  # /etc/cron.weekly/security-audit
  #!/bin/bash

  REPORT="/var/log/security-audit-$(date +%Y%m%d).txt"

  {
    echo "=== Weekly Security Audit ==="
    echo "Date: $(date)"
    echo ""
    
    echo "--- Lynis Audit ---"
    lynis audit system 2>&1 | tail -30
    echo ""
    
    echo "--- Rootkit Check (rkhunter) ---"
    rkhunter --check --skip-keycheck --quiet 2>&1 | tail -20
    echo ""
    
    echo "--- File Integrity (AIDE) ---"
    aide --check 2>&1 | tail -10
    echo ""
    
    echo "--- Failed Login Summary ---"
    grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -10
    
    echo ""
    echo "=== End Report ==="
  } > "$REPORT"

  # Email report
  mail -s "Weekly Security Audit" admin@example.com < "$REPORT"
  ```

  ### Daily Security Tasks (cron)
  ```bash
  # /etc/cron.daily/security-daily
  #!/bin/bash

  # Check for new packages that should be installed
  apt list --upgradable 2>/dev/null | grep security | mail -s "Security Updates Available" admin@example.com

  # Rotate logs
  logrotate /etc/logrotate.conf

  # Update rootkit signatures
  rkhunter --update

  # Check system integrity
  aide --check >> /var/log/aide-daily.log
  ```


entity_id: ent_20260526T195937931031_4eb10217
type: memory
category: debian/mail-postfix
strength: moderate
metadata: "{\"source\": \"debian_phase1_core_infra\"}"
created_at: 2026-05-26T19:59:37.931031
updated_at: 2026-05-26T19:59:37.931031
content:
  ## Mail Server — Postfix
  ### Install & Basic Setup
  ```bash
  apt install postfix
  dpkg-reconfigure postfix  # Interactive setup
  # Choices:
  # - Internet site (send/receive)
  # - System mail name: example.com
  # - Root/postmaster recipient: admin
  # - Other destinations: example.com, localhost
  # - Force synchronous updates: no
  # - Internet protocols: all
  ```

  ### Postfix Configuration
  ```bash
  # /etc/postfix/main.cf
  # Network settings
  inet_interfaces = all
  inet_protocols = all
  myhostname = mail.example.com
  mydomain = example.com
  myorigin = $mydomain
  mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
  mynetworks = 127.0.0.0/8, 192.168.1.0/24
  home_mailbox = Maildir/

  # Relay settings
  relayhost =
  smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination

  # TLS
  smtpd_tls_cert_file = /etc/ssl/certs/mail.example.com.crt
  smtpd_tls_key_file = /etc/ssl/private/mail.example.com.key
  smtpd_tls_security_level = may
  smtp_tls_security_level = may

  # Spam protection
  smtpd_helo_required = yes
  disable_vrfy_command = yes
  smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination
  smtpd_sender_restrictions = permit_mynetworks
  ```

  ### Postfix SASL Authentication
  ```bash
  apt install postfix-sasl sasl2-bin
  # /etc/postfix/sasl/smtpd.conf
  pwcheck_method: PAM
  log_level: 3
  ```

  ### Postfix Administration
  ```bash
  # Restart
  systemctl restart postfix

  # Queue management
  mailq                    # List queue
  postsuper -r ALL         # Retry all deferred
  postsuper -d ALL         # Delete all queued
  postqueue -f             # Flush queue

  # Check status
  postfix status
  postconf -n              # Non-default settings
  postconf                 # All settings

  # Logs
  tail -f /var/log/mail.log
  ```

  ### Virtual Domains
  ```bash
  # Virtual domain configuration
  # /etc/postfix/main.cf
  virtual_mailbox_domains = /etc/postfix/vhosts
  virtual_mailbox_base = /var/mail/vhosts
  virtual_mailbox_maps = hash:/etc/postfix/vmailbox
  virtual_uid_maps = static:5000
  virtual_gid_maps = static:5000

  # /etc/postfix/vhosts
  example.com OK
  another.com OK

  # /etc/postfix/vmailbox
  user@example.com example.com/user/Maildir/
  admin@another.com another.com/admin/Maildir/

  # Compile
  postmap /etc/postfix/vhosts
  postmap /etc/postfix/vmailbox
  ```


entity_id: ent_20260526T195938164555_38f8b7e7
type: memory
category: debian/mail-dovecot
strength: moderate
metadata: "{\"source\": \"debian_phase1_core_infra\"}"
created_at: 2026-05-26T19:59:38.164555
updated_at: 2026-05-26T19:59:38.164555
content:
  ## Mail Server — Dovecot (IMAP/POP3)
  ### Install & Setup
  ```bash
  apt install dovecot-imapd dovecot-pop3d
  ```

  ### Dovecot Configuration
  ```bash
  # /etc/dovecot/dovecot.conf
  protocols = imap pop3 lmtp

  # SSL/TLS
  ssl = required
  ssl_cert = </etc/ssl/certs/dovecot.crt
  ssl_key = </etc/ssl/private/dovecot.key
  ssl_min_protocol = TLSv1.2

  # Authentication
  # /etc/dovecot/conf.d/10-auth.conf
  disable_plaintext_auth = yes
  auth_mechanisms = plain login

  # /etc/dovecot/conf.d/10-mail.conf
  mail_location = maildir:~/Maildir

  # /etc/dovecot/conf.d/10-master.conf
  service imap-login {
    inet_listener imap {
      port = 143
    }
    inet_listener imaps {
      port = 993
      ssl = yes
    }
  }

  service pop3-login {
    inet_listener pop3 {
      port = 110
    }
    inet_listener pop3s {
      port = 995
      ssl = yes
    }
  }

  # LMTP for Postfix delivery
  service lmtp {
    unix_listener /var/spool/postfix/private/dovecot-lmtp {
      mode = 0600
      user = postfix
      group = postfix
    }
  }
  ```

  ### Postfix + Dovecot Integration
  ```bash
  # /etc/postfix/main.cf
  virtual_transport = lmtp:unix:private/dovecot-lmtp

  # Restart
  systemctl restart dovecot
  systemctl restart postfix
  ```

  ### Mailbox Management
  ```bash
  # List mailboxes
  doveadm user list

  # Mailbox stats
  doveadm mailbox status user@example.com INBOX

  # Mailbox quota
  doveadm quota get -u user@example.com

  # Sieve filtering
  doveadm sieve import user@example.com filter.sieve
  ```

  ### IMAP Testing
  ```bash
  # Test IMAP connection
  telnet localhost 143
  # Test IMAPS
  openssl s_client -connect localhost:993
  # Test POP3
  telnet localhost 110
  # Test POP3S
  openssl s_client -connect localhost:995
  ```

  ### Mail Troubleshooting
  ```bash
  # Check mail logs
  grep -i "error" /var/log/mail.log
  grep -i "dovecot" /var/log/mail.log

  # Check permissions
  ls -la ~/Maildir/

  # Test delivery
  echo "Test message" | mail -s "Test" user@example.com
  ```


entity_id: ent_20260526T195938378968_8e36f905
type: memory
category: debian/logging-rsyslog
strength: moderate
metadata: "{\"source\": \"debian_phase1_core_infra\"}"
created_at: 2026-05-26T19:59:38.378968
updated_at: 2026-05-26T19:59:38.378968
content:
  ## Logging Deep — rsyslog & journalctl
  ### rsyslog Configuration
  ```bash
  # Install
  apt install rsyslog rsyslog-gnutls rsyslog-mysql

  # /etc/rsyslog.conf
  # Modules
  module(load="imuxsock")    # System socket
  module(load="imklog")      # Kernel logging
  module(load="imjournal")   # systemd journal

  # Templates
  template(name="LogFormat" type="string"
    string="%timegenerated% %hostname% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n")

  # Files
  local0.*                /var/log/local0.log
  auth,authpriv.*         /var/log/auth.log
  mail.*                  -/var/log/mail.log
  cron.*                  /var/log/cron.log
  *.*;auth,authpriv.none  -/var/log/syslog
  kern.*                  -/var/log/kern.log
  ```

  ### Remote Logging
  ```bash
  # Server — /etc/rsyslog.d/50-remote.conf
  # TCP input
  module(load="imtcp")
  input(type="imtcp" port="514")

  # UDP input
  module(load="imudp")
  input(type="imudp" port="514")

  # Client — /etc/rsyslog.d/50-forward.conf
  # Forward via TCP (reliable)
  *.* @@remote-server:514

  # Forward via UDP (faster)
  *.* @remote-server:514

  # Conditional forwarding
  :programname, isequal, "sshd" @@remote-server:514
  ```

  ### Log Templates & Formats
  ```bash
  # /etc/rsyslog.d/50-templates.conf
  template(name="JSONFormat" type="string"
    string="{"timestamp":"%timegenerated:::date-rfc3339%","hostname":"%hostname%","severity":"%syslogseverity-text%","facility":"%syslogfacility-text%","tag":"%syslogtag%","message":"%msg%"}\n")

  template(name="HighPrecisionFormat" type="string"
    string="%TIMESTAMP:::date-rfc3339% %HOSTNAME% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n")

  # Apply to file
  local7.* /var/log/json.log;JSONFormat
  ```

  ### Log Rotation
  ```bash
  # /etc/logrotate.d/syslog
  /var/log/syslog
  /var/log/mail.log
  /var/log/kern.log
  /var/log/auth.log {
      daily
      rotate 14
      compress
      delaycompress
      missingok
      notifempty
      create 640 root adm
      sharedscripts
      postrotate
          systemctl reload rsyslog >/dev/null 2>&1 || true
      endscript
  }
  ```

  ### journalctl Mastery
  ```bash
  # Basic queries
  journalctl -u sshd                     # Specific unit
  journalctl -u sshd --since "1 hour ago"
  journalctl -u sshd --since today
  journalctl -u sshd --until "2 hours ago"
  journalctl --disk-usage
  journalctl --vacuum-time=7d
  journalctl --vacuum-size=500M

  # Priority filtering
  journalctl -p err                      # Errors and above
  journalctl -p info                     # Info and above
  journalctl -p emerg                    # Only emergencies

  # PID/TID filtering
  journalctl _PID=1234
  journalctl _UID=1000
  journalctl _COMM=bash

  # Boot-specific
  journalctl -b                          # Current boot
  journalctl -b -1                       # Previous boot
  journalctl -b -1 --since "10:00" --until "11:00"
  journalctl --list-boots

  # Output formats
  journalctl -o short                    # Default
  journalctl -o verbose                  # Full details
  journalctl -o json                     # JSON format
  journalctl -o export                   # Export format

  # Real-time monitoring
  journalctl -f                          # Follow all
  journalctl -u nginx -f                # Follow specific unit
  ```

  ### Log Analysis Scripts
  ```bash
  # Failed SSH attempts by IP
  grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -20

  # Top 20 processes by log volume
  journalctl --no-pager | awk '{print $7}' | cut -d']' -f1 | sort | uniq -c | sort -rn | head -20

  # Errors by hour
  grep "error" /var/log/syslog | awk '{print $3}' | cut -d: -f1 | sort | uniq -c

  # Disk usage by log file
  du -sh /var/log/* | sort -rh | head -20
  ```


entity_id: ent_20260526T195938592780_4717185c
type: memory
category: debian/boot-grub
strength: moderate
metadata: "{\"source\": \"debian_phase1_core_infra\"}"
created_at: 2026-05-26T19:59:38.592780
updated_at: 2026-05-26T19:59:38.592780
content:
  ## Init/Boot — GRUB, Kernel, Initramfs
  ### GRUB Configuration
  ```bash
  # /etc/default/grub
  GRUB_DEFAULT=0
  GRUB_TIMEOUT=5
  GRUB_DISTRIBUTOR="Debian GNU/Linux"
  GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
  GRUB_CMDLINE_LINUX=""

  # Advanced options
  GRUB_DISABLE_OS_PROBER=false    # Detect other OSes
  GRUB_TIMEOUT_STYLE=menu         # Show menu
  GRUB_GFXMODE=1920x1080          # Resolution
  GRUB_DISABLE_RECOVERY="false"   # Enable recovery mode
  ```

  ### Kernel Parameters
  ```bash
  # Common GRUB_CMDLINE_LINUX parameters
  quiet              # Reduce boot messages
  splash             # Boot splash screen
  nomodeset          # Disable kernel mode setting
  acpi=off           # Disable ACPI
  nofb               # Disable framebuffer
  text               # Text mode (no splash)
  debug              # Kernel debugging
  earlyprintk        # Early console output
  init=/bin/bash     # Boot to shell (debugging)

  # Apply changes
  update-grub
  ```

  ### GRUB Repair
  ```bash
  # Boot from live USB, then:
  mount /dev/sda1 /mnt
  mount --bind /dev /mnt/dev
  mount --bind /proc /mnt/proc
  mount --bind /sys /mnt/sys
  chroot /mnt

  # Reinstall GRUB
  grub-install /dev/sda
  update-grub

  # For UEFI
  grub-install --target=x86_64-efi --efi-directory=/boot/efi
  ```

  ### GRUB Custom Entries
  ```bash
  # /etc/grub.d/40_custom
  menuentry "Debian with custom kernel params" {
      insmod part_gpt
      insmod ext2
      set root=(hd0,gpt1)
      linux /boot/vmlinuz-6.1 root=/dev/sda1 quiet
      initrd /boot/initrd.img-6.1
  }

  # Add second OS
  menuentry "Windows 11" {
      insmod part_gpt
      insmod fat
      set root=(hd0,gpt2)
      chainloader /EFI/Microsoft/Boot/bootmgfw.efi
  }

  update-grub
  ```

  ### Kernel Management
  ```bash
  # List installed kernels
  dpkg -l | grep linux-image
  ls /boot/vmlinuz-*

  # Install specific kernel
  apt install linux-image-6.1.0-x

  # Remove old kernels
  apt autoremove --purge

  # Boot specific kernel (single boot)
  # Edit GRUB at boot: e to edit, add params to linux line
  ```

  ### Initramfs
  ```bash
  # Rebuild initramfs
  update-initramfs -u
  update-initramfs -u -k all
  update-initramfs -c -k 6.1.0-x

  # List contents
  lsinitramfs /boot/initrd.img-6.1.0-x

  # Add custom modules to initramfs
  # /etc/initramfs-tools/modules
  # Add lines like:
  # my_custom_module

  # Initramfs configuration
  # /etc/initramfs-tools/initramfs.conf
  MODULES=most
  BUSYBOX=y
  KEYMAP=n
  COMPRESS=lz4

  # Update after changes
  update-initramfs -u
  ```

  ### Boot Troubleshooting
  ```bash
  # Boot to single user mode
  # At GRUB: e to edit, add 'single' to linux line, Ctrl+X

  # Boot with specific kernel
  # At GRUB: select recovery mode or edit linux line

  # Check boot logs
  journalctl -b
  dmesg | head -50

  # Check GRUB errors
  cat /var/log/grub.log
  lsblk -f
  ```

  ### systemd Boot Analysis
  ```bash
  # Analyze boot time
  systemd-analyze
  systemd-analyze blame    # Slowest services
  systemd-analyze critical-chain  # Dependency chain

  # Mask/unmask services
  systemctl mask service-name    # Prevent starting
  systemctl unmask service-name  # Re-enable
  ```


entity_id: ent_20260526T195938805925_b6a8fda0
type: memory
category: debian/backup-rsync
strength: moderate
metadata: "{\"source\": \"debian_phase1_core_infra\"}"
created_at: 2026-05-26T19:59:38.805925
updated_at: 2026-05-26T19:59:38.805925
content:
  ## Backup — rsync & dd
  ### rsync Mastery
  ```bash
  # Basic sync
  rsync -av /source/ /destination/

  # Over SSH
  rsync -avz -e ssh /source/ user@remote:/destination/

  # Options breakdown
  -a    # Archive mode (recursive, preserves symlinks, perms, timestamps)
  -v    # Verbose
  -z    # Compress
  -P    # Show progress, partial transfer
  --delete    # Delete files in dest not in source
  --exclude=PATTERN    # Exclude files
  --exclude-from=FILE  # Exclude list file
  --bwlimit=KBPS      # Bandwidth limit
  --partial           # Keep partially transferred files
  --stats             # Show transfer stats
  ```

  ### rsync Backup Script
  ```bash
  #!/bin/bash
  # /usr/local/bin/backup.sh
  SOURCE="/home/"
  DEST="/backup/home-$(date +%Y%m%d)/"
  EXCLUDE="/etc/backup-excludes.txt"
  LOG="/var/log/backup-$(date +%Y%m%d).log"

  mkdir -p "$(dirname $DEST)"

  rsync -avz --delete --progress   --exclude-from="$EXCLUDE"   --log-file="$LOG"   "$SOURCE" "$DEST" 2>&1

  echo "Backup completed: $(date)" >> "$LOG"
  echo "Size: $(du -sh $DEST | cut -f1)" >> "$LOG"
  ```

  ### rsync with Retention
  ```bash
  # Keep 7 daily, 4 weekly, 3 monthly backups
  #!/bin/bash
  BACKUP_DIR="/backup/daily"
  DATE=$(date +%Y%m%d)
  DEST="$BACKUP_DIR/$DATE/"

  rsync -avz /source/ "$DEST"

  # Delete backups older than 7 days
  find "$BACKUP_DIR" -maxdepth 1 -type d -mtime +7 -exec rm -rf {} \;
  ```

  ### rsync over SSH with Key
  ```bash
  # Generate key
  ssh-keygen -t ed25519 -f ~/.ssh/backup_key -N ""

  # Copy key
  ssh-copy-id -i ~/.ssh/backup_key.pub user@remote

  # Use in script
  rsync -avz -e "ssh -i ~/.ssh/backup_key -o BatchMode=yes"   /source/ user@remote:/destination/
  ```

  ### dd Backup
  ```bash
  # Full disk image
  dd if=/dev/sda of=/backup/sda-full.img bs=4M status=progress

  # Compressed disk image
  dd if=/dev/sda bs=4M status=progress | gzip > /backup/sda-full.img.gz

  # Restore disk image
  dd if=/backup/sda-full.img of=/dev/sda bs=4M status=progress

  # Partition backup
  dd if=/dev/sda1 of=/backup/sda1.img bs=4M status=progress

  # With progress (Debian 10+)
  dd if=/dev/sda of=/backup/sda.img bs=4M status=progress
  # Or use pv for progress
  dd if=/dev/sda bs=4M | pv | dd of=/backup/sda.img bs=4M
  ```

  ### rsync vs dd Comparison
  | Feature | rsync | dd |
  |---------|-------|-----|
  | Level | File | Block |
  | Speed | Fast for changes | Full disk only |
  | Space | Only changed files | Full disk size |
  | Recovery | File-level | Full disk restore |
  | Use case | Regular backups | Full disk cloning |


entity_id: ent_20260526T195939017651_619a1cbb
type: memory
category: debian/backup-borg
strength: moderate
metadata: "{\"source\": \"debian_phase1_core_infra\"}"
created_at: 2026-05-26T19:59:39.017651
updated_at: 2026-05-26T19:59:39.017651
content:
  ## Backup — Borg Backup & Restic
  ### Borg Backup
  ```bash
  # Install
  apt install borgbackup

  # Initialize repository
  borg init --encryption=repokey /mnt/backup/repo

  # Create backup
  borg create   --stats   --list   --filter AME   --compression lz4   /mnt/backup/repo::home-{now:%Y-%m-%d_%H:%M:%S}   /home/

  # List backups
  borg list /mnt/backup/repo

  # Restore
  borg extract /mnt/backup/repo::home-2024-01-01_12:00:00

  # Mount backup
  borg mount /mnt/backup/repo /mnt/restore
  cp /mnt/restore/home-2024-01-01/home/user/file.txt /home/user/
  borg umount /mnt/restore

  # Prune old backups (keep 7 daily, 4 weekly, 3 monthly)
  borg prune --keep-daily=7 --keep-weekly=4 --keep-monthly=3   /mnt/backup/repo

  # Check integrity
  borg check /mnt/backup/repo

  # Compact repository
  borg compact /mnt/backup/repo
  ```

  ### Borg Backup Script
  ```bash
  #!/bin/bash
  REPO="/mnt/backup/repo"
  SOURCE="/home/"
  EXCLUDE_FILE="/etc/borg-excludes.txt"
  LOCK_TIMEOUT=7200

  export BORG_RSH="ssh -i /root/.ssh/backup_key"
  export BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK=yes

  borg create   --stats   --filter AME   --compression lz4   --exclude-from="$EXCLUDE_FILE"   --lock-wait $LOCK_TIMEOUT   "$REPO::{now:%Y-%m-%d_%H:%M:%S}"   "$SOURCE"

  borg prune --keep-daily=7 --keep-weekly=4 --keep-monthly=3   --lock-wait $LOCK_TIMEOUT   "$REPO"
  ```

  ### Restic
  ```bash
  # Install
  apt install restic

  # Initialize repository
  restic init --repo /mnt/backup/repo --password-file /root/.restic-pass

  # Backup
  restic backup /home/ --repo /mnt/backup/repo   --password-file /root/.restic-pass   --tag home

  # List snapshots
  restic snapshots --repo /mnt/backup/repo

  # Restore
  restic restore latest --target /mnt/restore   --repo /mnt/backup/repo

  # Prune (delete old snapshots)
  restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 3   --repo /mnt/backup/repo
  restic prune --repo /mnt/backup/repo

  # Check integrity
  restic check --repo /mnt/backup/repo

  # Remote repository (S3)
  export AWS_ACCESS_KEY_ID=xxx
  export AWS_SECRET_ACCESS_KEY=xxx
  restic init --repo s3:s3.amazonaws.com/bucket/path
  restic backup /home/ --repo s3:s3.amazonaws.com/bucket/path
  ```

  ### Backup Monitoring
  ```bash
  # Check backup age
  find /backup/ -name "*.log" -mtime +1 | wc -l

  # Backup size trends
  du -sh /backup/daily/*/ | sort -k2

  # Verify backup integrity
  borg check --repo /mnt/backup/repo 2>&1 | grep -i "error\|corrupt"
  ```


entity_id: ent_20260526T195939230991_f4930099
type: memory
category: debian/backup-automated
strength: moderate
metadata: "{\"source\": \"debian_phase1_core_infra\"}"
created_at: 2026-05-26T19:59:39.230991
updated_at: 2026-05-26T19:59:39.230991
content:
  ## Automated Backup Strategies
  ### Cron-Based Backup Schedule
  ```bash
  # /etc/cron.d/backup-daily
  0 2 * * * root /usr/local/bin/backup-daily.sh >> /var/log/backup-daily.log 2>&1

  # /etc/cron.d/backup-weekly
  0 3 * * 0 root /usr/local/bin/backup-weekly.sh >> /var/log/backup-weekly.log 2>&1
  ```

  ### Backup Retention Policy
  ```bash
  #!/bin/bash
  # /usr/local/bin/backup-rotate.sh
  BACKUP_DIR="/backup/daily"
  RETENTION_DAYS=30

  # Delete old backups
  find "$BACKUP_DIR" -maxdepth 1 -type d -mtime +${RETENTION_DAYS} -exec rm -rf {} \;

  # Weekly backups (keep 8 weeks)
  find "/backup/weekly" -maxdepth 1 -type d -mtime +56 -exec rm -rf {} \;

  # Monthly backups (keep 12 months)
  find "/backup/monthly" -maxdepth 1 -type d -mtime +365 -exec rm -rf {} \;

  echo "Rotation completed: $(date)"
  ```

  ### Backup Notification
  ```bash
  #!/bin/bash
  # /usr/local/bin/backup.sh
  BACKUP_CMD="rsync -avz /source/ /backup/$(date +%Y%m%d)/"
  LOG="/var/log/backup-$(date +%Y%m%d).log"

  $BACKUP_CMD > "$LOG" 2>&1
  STATUS=$?

  if [ $STATUS -eq 0 ]; then
      echo "Backup successful: $(date)" >> "$LOG"
  else
      echo "Backup FAILED with exit code $STATUS: $(date)" >> "$LOG"
      mail -s "Backup FAILED" admin@example.com < "$LOG"
  fi
  ```

  ### Offsite Backup
  ```bash
  # rsync to remote server
  rsync -avz -e ssh /backup/ user@remote:/offsite-backup/

  # rclone to cloud
  apt install rclone
  rclone config  # Interactive setup
  rclone sync /backup remote:backup-bucket

  # Automated rclone
  # /etc/cron.weekly/rclone-sync
  #!/bin/bash
  rclone sync /backup remote:backup-bucket --log-file=/var/log/rclone-sync.log
  ```

  ### Backup Verification
  ```bash
  # Test restore (dry run)
  rsync --dry-run -avz /backup/latest/ /test-restore/

  # Verify backup integrity
  sha256sum /backup/*.img

  # Automated backup test
  #!/bin/bash
  RESTORE_TEST="/tmp/backup-test-$(date +%Y%m%d)"
  mkdir -p "$RESTORE_TEST"

  borg extract --dry-run /mnt/backup/repo::latest
  if [ $? -eq 0 ]; then
      echo "Backup verification passed"
  else
      echo "Backup verification FAILED"
      mail -s "Backup Verification FAILED" admin@example.com
  fi
  ```


entity_id: ent_20260526T204002465809_f6c04032
type: memory
category: debian/web-nginx
strength: moderate
metadata: "{\"source\": \"debian_phase2_services\"}"
created_at: 2026-05-26T20:40:02.465809
updated_at: 2026-05-26T20:40:02.465809
content:
  ## Nginx Web Server
  ### Install & Basic Config
  ```bash
  apt install nginx
  systemctl enable --now nginx
  nginx -t                    # test config
  nginx -T                    # test + dump full config
  ```

  ### Virtual Hosts
  ```nginx
  # /etc/nginx/sites-available/example.com
  server {
      listen 80;
      server_name example.com www.example.com;
      root /var/www/example.com/html;
      index index.html index.htm;

      access_log /var/log/nginx/example.com.access.log;
      error_log /var/log/nginx/example.com.error.log;

      location / {
          try_files $uri $uri/ =404;
      }
  }
  ```

  ### SSL/TLS
  ```nginx
  server {
      listen 443 ssl http2;
      server_name example.com;

      ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
      ssl_protocols TLSv1.2 TLSv1.3;
      ssl_ciphers HIGH:!aNULL:!MD5;
      ssl_prefer_server_ciphers on;
      ssl_session_cache shared:SSL:10m;
      ssl_session_timeout 10m;

      # HTTP Strict Transport Security
      add_header Strict-Transport-Security "max-age=31536000" always;
  }
  ```

  ### Reverse Proxy
  ```nginx
  location / {
      proxy_pass http://127.0.0.1:8080;
      proxy_http_version 1.1;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_connect_timeout 60s;
      proxy_send_timeout 60s;
      proxy_read_timeout 60s;
  }
  ```

  ### Load Balancing
  ```nginx
  upstream backend {
      least_conn;
      server 192.168.1.10:8080 weight=3;
      server 192.168.1.11:8080 weight=2;
      server 192.168.1.12:8080 backup;

      keepalive 32;
  }

  server {
      listen 80;
      location / {
          proxy_pass http://backend;
          proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
      }
  }
  ```

  ### Caching
  ```nginx
  proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
      max_size=1g inactive=60m use_temp_path=off;

  location / {
      proxy_pass http://backend;
      proxy_cache my_cache;
      proxy_cache_valid 200 302 60m;
      proxy_cache_valid 404 1m;
      add_header X-Cache-Status $upstream_cache_status;
  }
  ```

  ### Rate Limiting & Security
  ```nginx
  # In http {} block
  limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
  limit_conn_zone $binary_remote_addr zone=addr:10m;

  location /api/ {
      limit_req zone=api burst=20 nodelay;
      limit_conn addr 10;
      proxy_pass http://backend;
  }

  # Security headers
  add_header X-Frame-Options "SAMEORIGIN" always;
  add_header X-Content-Type-Options "nosniff" always;
  add_header X-XSS-Protection "1; mode=block" always;
  add_header Referrer-Policy "strict-origin-when-cross-origin" always;
  ```

  ### Logging & Monitoring
  ```nginx
  log_format main '$remote_addr - $remote_user [$time_local] '
      '"$request" $status $body_bytes_sent '
      '"$http_referer" "$http_user_agent" '
      '$request_time $upstream_response_time';

  access_log /var/log/nginx/access.log main;
  ```

  ### Nginx Admin
  ```bash
  # Test and reload
  nginx -t && systemctl reload nginx

  # Check status
  systemctl status nginx

  # View logs
  tail -f /var/log/nginx/access.log
  tail -f /var/log/nginx/error.log

  # Nginx status module (stub_status)
  location /nginx_status {
      stub_status;
      allow 127.0.0.1;
      deny all;
  }
  ```


entity_id: ent_20260526T204002686388_e5d8f881
type: memory
category: debian/web-apache
strength: moderate
metadata: "{\"source\": \"debian_phase2_services\"}"
created_at: 2026-05-26T20:40:02.686388
updated_at: 2026-05-26T20:40:02.686388
content:
  ## Apache Web Server
  ### Install & Basic Config
  ```bash
  apt install apache2
  systemctl enable --now apache2
  apache2ctl configtest
  a2enmod modname        # enable module
  a2dismod modname       # disable module
  a2ensite site.conf     # enable site
  a2dissite site.conf    # disable site
  ```

  ### Virtual Host
  ```apache
  <VirtualHost *:80>
      ServerName example.com
      ServerAlias www.example.com
      ServerAdmin webmaster@example.com
      DocumentRoot /var/www/example.com

      <Directory /var/www/example.com>
          Options -Indexes +FollowSymLinks
          AllowOverride All
          Require all granted
      </Directory>

      ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
      CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
  </VirtualHost>
  ```

  ### SSL with mod_ssl
  ```apache
  <VirtualHost *:443>
      ServerName example.com
      DocumentRoot /var/www/example.com

      SSLEngine on
      SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
      SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem

      SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
      SSLCipherSuite HIGH:!aNULL:!MD5
      SSLHonorCipherOrder on

      Header always set Strict-Transport-Security "max-age=31536000"
      Header always set X-Frame-Options SAMEORIGIN
      Header always set X-Content-Type-Options nosniff
  </VirtualHost>
  ```

  ### mod_rewrite
  ```apache
  RewriteEngine On
  # Redirect www to non-www
  RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
  RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

  # Force HTTPS
  RewriteCond %{HTTPS} off
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  # Clean URLs
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
  ```

  ### Reverse Proxy (mod_proxy)
  ```apache
  <VirtualHost *:80>
      ServerName example.com

      ProxyPreserveHost On
      ProxyPass / http://127.0.0.1:8080/
      ProxyPassReverse / http://127.0.0.1:8080/

      # WebSocket support
      ProxyPass /ws ws://127.0.0.1:8080/ws
      ProxyPassReverse /ws ws://127.0.0.1:8080/ws
  </VirtualHost>
  ```

  ### mod_security (WAF)
  ```bash
  apt install libapache2-mod-security2
  cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
  # Edit: SecRuleEngine DetectionOnly → On
  a2enmod security2
  systemctl restart apache2
  ```

  ### Performance Tuning
  ```apache
  # /etc/apache2/mods-enabled/mpm_event.conf
  <IfModule mpm_event_module>
      StartServers             2
      MinSpareThreads          25
      MaxSpareThreads          75
      ThreadLimit              64
      ThreadsPerChild          25
      MaxRequestWorkers        150
      MaxConnectionsPerChild   0
  </IfModule>

  # mod_pagespeed (if installed)
  ModPagespeed on
  ModPagespeedFileCachePath /var/cache/mod_pagespeed/
  ModPagespeedEnableFilters combine_css,combine_js,minify_html
  ```

  ### Apache Admin
  ```bash
  # Test config
  apache2ctl configtest

  # Reload/restart
  systemctl reload apache2
  systemctl restart apache2

  # Check loaded modules
  apache2ctl -M

  # Check running MPM
  apache2ctl -V | grep MPM_NAME

  # View config dump
  apache2ctl -S

  # Log analysis
  tail -f /var/log/apache2/access.log
  tail -f /var/log/apache2/error.log

  # Check for broken symlinks
  find /etc/apache2/sites-enabled/ -type l ! -exec test -e {} \; -print
  ```

  ### .htaccess Essentials
  ```apache
  # Disable directory listing
  Options -Indexes

  # Enable ETags
  FileETag MTime Size

  # Cache control
  <FilesMatch "\.(ico|jpg|jpeg|png|gif|svg|css|js)$">
      Header set Cache-Control "max-age=2592000, public"
  </FilesMatch>

  # Block access to hidden files
  <DirectoryMatch "/\.(git|svn|hg)">
      Require all denied
  </DirectoryMatch>

  # Restrict by IP
  <Directory /var/www/admin>
      Require ip 192.168.1.0/24
      Require ip 10.0.0.0/8
  </Directory>
  ```


entity_id: ent_20260526T204002898894_c7669b92
type: memory
category: debian/db-postgresql
strength: moderate
metadata: "{\"source\": \"debian_phase2_services\"}"
created_at: 2026-05-26T20:40:02.898894
updated_at: 2026-05-26T20:40:02.898894
content:
  ## PostgreSQL Administration
  ### Install & Basics
  ```bash
  apt install postgresql postgresql-contrib
  systemctl status postgresql

  # Connect
  sudo -u postgres psql
  psql -U postgres -d dbname

  # Create database/user
  CREATE DATABASE mydb;
  CREATE USER myuser WITH ENCRYPTED PASSWORD 'password';
  GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
  ```

  ### User & Permission Management
  ```sql
  -- Role creation
  CREATE ROLE reader WITH LOGIN PASSWORD 'pass';
  CREATE ROLE writer WITH LOGIN PASSWORD 'pass';
  CREATE ROLE admin WITH LOGIN PASSWORD 'pass' SUPERUSER;

  -- Grant permissions
  GRANT CONNECT ON DATABASE mydb TO reader;
  GRANT USAGE ON SCHEMA public TO reader;
  GRANT SELECT ON ALL TABLES IN SCHEMA public TO reader;
  GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO writer;

  -- Grant on future tables
  ALTER DEFAULT PRIVILEGES IN SCHEMA public
      GRANT SELECT ON TABLES TO reader;
  ```

  ### Backup & Restore
  ```bash
  # Full database dump
  pg_dump -U postgres -d mydb > mydb.sql
  pg_dump -U postgres -d mydb --format=custom --compress=9 -f mydb.dump

  # Schema only
  pg_dump -U postgres -d mydb --schema-only > schema.sql

  # Specific table
  pg_dump -U postgres -d mydb -t tablename > table.sql

  # All databases
  pg_dumpall -U postgres > all_databases.sql

  # Restore
  psql -U postgres -d mydb < mydb.sql
  pg_restore -U postgres -d mydb mydb.dump

  # Schema-only restore
  psql -U postgres -d mydb < schema.sql
  ```

  ### Performance Tuning
  ```sql
  -- Check table sizes
  SELECT schemaname, tablename, pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename))
  FROM pg_tables WHERE schemaname = 'public' ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;

  -- Index usage
  SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch
  FROM pg_stat_user_indexes ORDER BY idx_scan DESC;

  -- Slow queries
  SELECT query, calls, total_time, mean_time, rows
  FROM pg_stat_statements
  ORDER BY mean_time DESC LIMIT 20;

  -- Connection count
  SELECT datname, count(*) FROM pg_stat_activity GROUP BY datname;

  -- VACUUM status
  SELECT schemaname, relname, last_vacuum, last_autovacuum, last_analyze
  FROM pg_stat_user_tables;

  -- Database size
  SELECT datname, pg_size_pretty(pg_database_size(datname)) FROM pg_database;
  ```

  ### pg_hba.conf (Authentication)
  ```
  # TYPE DATABASE USER ADDRESS METHOD
  local   all   postgres              peer
  local   all   all                   scram-sha-256
  host    all   all   127.0.0.1/32    scram-sha-256
  host    all   all   ::1/128         scram-sha-256
  host    all   all   192.168.1.0/24  scram-sha-256
  ```

  ### Connection Pooling (PgBouncer)
  ```bash
  apt install pgbouncer

  # /etc/pgbouncer/pgbouncer.ini
  [databases]
  mydb = host=127.0.0.1 port=5432 dbname=mydb

  [pgbouncer]
  listen_port = 6432
  listen_addr = 127.0.0.1
  auth_type = scram-sha-256
  auth_file = /etc/pgbouncer/userlist.txt
  pool_mode = transaction
  max_client_conn = 100
  default_pool_size = 20
  ```

  ### Maintenance
  ```bash
  # Vacuum
  VACUUM ANALYZE;
  VACUUM FULL table_name;         # offline, reclaims space

  # Reindex
  REINDEX TABLE table_name;
  REINDEX DATABASE mydb;

  # Check data integrity
  pg_checksums --check /var/lib/postgresql/15/main

  # Auto-vacuum tuning in postgresql.conf
  autovacuum = on
  autovacuum_max_workers = 3
  autovacuum_naptime = 60
  autovacuum_vacuum_threshold = 50
  autovacuum_analyze_threshold = 50
  ```

  ### Monitoring
  ```bash
  # Check PostgreSQL status
  sudo systemctl status postgresql
  sudo -u postgres pg_isready

  # Real-time stats
  sudo -u postgres psql -c "SELECT * FROM pg_stat_activity;"

  # Slow query log
  log_min_duration_statement = 1000    # 1 second threshold

  # Connection monitoring
  watch -n1 "sudo -u postgres psql -c 'SELECT count(*), state FROM pg_stat_activity GROUP BY state;'"
  ```


entity_id: ent_20260526T204003114189_b854b697
type: memory
category: debian/db-mariadb
strength: moderate
metadata: "{\"source\": \"debian_phase2_services\"}"
created_at: 2026-05-26T20:40:03.114189
updated_at: 2026-05-26T20:40:03.114189
content:
  ## MariaDB/MySQL Administration
  ### Install & Basics
  ```bash
  apt install mariadb-server
  systemctl enable --now mariadb
  mysql_secure_installation       # secure default installation

  mysql -u root -p
  ```

  ### User & Permissions
  ```sql
  CREATE USER 'webuser'@'localhost' IDENTIFIED BY 'password';
  CREATE USER 'webuser'@'192.168.1.%' IDENTIFIED BY 'password';

  GRANT SELECT, INSERT, UPDATE, DELETE ON mydb.* TO 'webuser'@'localhost';
  GRANT ALL PRIVILEGES ON mydb.* TO 'admin'@'localhost';
  FLUSH PRIVILEGES;

  -- View grants
  SHOW GRANTS FOR 'webuser'@'localhost';

  -- Revoke
  REVOKE DELETE ON mydb.* FROM 'webuser'@'localhost';
  ```

  ### Backup & Restore
  ```bash
  # Full dump
  mysqldump -u root -p mydb > mydb.sql
  mysqldump -u root -p --all-databases > all_databases.sql

  # Schema only
  mysqldump -u root -p --no-data mydb > schema.sql

  # Single table
  mysqldump -u root -p mydb tablename > table.sql

  # Compressed dump
  mysqldump -u root -p mydb | gzip > mydb.sql.gz

  # Restore
  mysql -u root -p mydb < mydb.sql
  gunzip < mydb.sql.gz | mysql -u root -p mydb

  # Percona XtraBackup (physical backup)
  apt install percona-xtrabackup
  xtrabackup --backup --target-dir=/backup/mariadb/$(date +%Y%m%d)
  xtrabackup --prepare --target-dir=/backup/mariadb/20260101
  xtrabackup --copy-back --target-dir=/backup/mariadb/20260101
  ```

  ### Performance
  ```sql
  -- Slow query log
  SHOW VARIABLES LIKE 'slow_query%';
  SET GLOBAL slow_query_log = 'ON';
  SET GLOBAL long_query_time = 2;

  -- Table sizes
  SELECT table_schema, table_name,
    ROUND(data_length/1024/1024, 2) AS data_mb,
    ROUND(index_length/1024/1024, 2) AS index_mb,
    table_rows
  FROM information_schema.tables
  WHERE table_schema NOT IN ('mysql','information_schema','performance_schema')
  ORDER BY data_length DESC;

  -- Index usage
  SELECT TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX, COLUMN_NAME
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = 'mydb';

  -- Show processlist
  SHOW FULL PROCESSLIST;

  -- Show engine status
  SHOW ENGINE INNODB STATUS;

  -- Check for missing indexes
  SELECT * FROM sys.schema_unused_indexes;
  ```

  ### Replication (Master-Slave)
  ```sql
  -- Master: /etc/mysql/mariadb.conf.d/99-replication.cnf
  [mysqld]
  server-id = 1
  log_bin = /var/log/mysql/mysql-bin
  binlog_format = ROW
  expire_logs_days = 7

  -- Create replication user
  CREATE USER 'repl'@'%' IDENTIFIED BY 'replpass';
  GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';
  FLUSH PRIVILEGES;

  -- Get master position
  SHOW MASTER STATUS;

  -- Slave config
  [mysqld]
  server-id = 2
  relay_log = /var/log/mysql/relay-bin

  -- Start replication
  CHANGE MASTER TO
    MASTER_HOST='192.168.1.10',
    MASTER_USER='repl',
    MASTER_PASSWORD='replpass',
    MASTER_LOG_FILE='mysql-bin.000001',
    MASTER_LOG_POS=1234;
  START SLAVE;
  SHOW SLAVE STATUS\G
  ```

  ### MariaDB Admin
  ```bash
  # Test connection
  mysqladmin -u root -p status
  mysqladmin -u root -p ping

  # Check tables
  mysqlcheck -u root -p --all-databases --check
  mysqlcheck -u root -p --all-databases --optimize

  # Repair tables
  mysqlcheck -u root -p --all-databases --repair

  # Variable tuning
  mysql -e "SHOW VARIABLES LIKE 'max_connections';"
  mysql -e "SHOW VARIABLES LIKE 'innodb_buffer_pool_size';"

  # MariaDB Galera Cluster (multi-master)
  apt install mariadb-galera-server
  ```


entity_id: ent_20260526T204003331636_e85c5ffd
type: memory
category: debian/db-redis
strength: moderate
metadata: "{\"source\": \"debian_phase2_services\"}"
created_at: 2026-05-26T20:40:03.331636
updated_at: 2026-05-26T20:40:03.331636
content:
  ## Redis Administration
  ### Install & Config
  ```bash
  apt install redis-server redis-tools
  systemctl enable --now redis-server

  # /etc/redis/redis.conf
  bind 127.0.0.1
  port 6379
  protected-mode yes
  requirepass yourpassword
  maxmemory 256mb
  maxmemory-policy allkeys-lru
  save 900 1
  save 300 10
  save 60 10000
  ```

  ### Redis CLI
  ```bash
  redis-cli
  redis-cli -a password
  redis-cli -h 127.0.0.1 -p 6379

  # Basic commands
  SET key value
  GET key
  DEL key
  EXPIRE key 3600          # TTL in seconds
  TTL key
  KEYS *                   # dangerous on production!
  DBSIZE

  # Data types
  LPUSH list value
  RPUSH list value
  LRANGE list 0 -1
  HSET hash field value
  HGET hash field
  HMGET hash field1 field2
  SADD set value
  SMEMBERS set
  ZADD sortedset score member

  # Pub/Sub
  PUBLISH channel message
  SUBSCRIBE channel
  ```

  ### Persistence
  ```bash
  # RDB snapshots (default)
  save 900 1                # save after 900s if 1+ keys changed
  save 300 10               # save after 300s if 10+ keys changed
  save 60 10000             # save after 60s if 10000+ keys changed

  # AOF (append only file)
  appendonly yes
  appendfilename "appendonly.aof"
  appendfsync everysec      # everysec recommended

  # Manual save
  redis-cli BGSAVE          # background save
  redis-cli LASTSAVE        # last save timestamp

  # Load RDB
  redis-cli SHUTDOWN        # Redis auto-saves on shutdown
  ```

  ### Redis Sentinel (High Availability)
  ```bash
  # sentinel.conf
  sentinel monitor mymaster 192.168.1.10 6379 2
  sentinel down-after-milliseconds mymaster 5000
  sentinel failover-timeout mymaster 60000
  sentinel parallel-syncs mymaster 1

  redis-sentinel /etc/redis/sentinel.conf
  ```

  ### Clustering
  ```bash
  # Create cluster (6 instances: 3 master, 3 slave)
  redis-cli --cluster create   192.168.1.10:7000 192.168.1.10:7001   192.168.1.11:7002 192.168.1.11:7003   192.168.1.12:7004 192.168.1.12:7005   --cluster-replicas 1

  # Check cluster status
  redis-cli --cluster check 192.168.1.10:7000

  # Cluster info
  redis-cli -c -h 192.168.1.10 -p 7000 CLUSTER INFO
  redis-cli -c -h 192.168.1.10 -p 7000 CLUSTER NODES
  ```

  ### Performance & Monitoring
  ```bash
  # Memory usage
  redis-cli INFO memory
  redis-cli INFO stats
  redis-cli INFO replication

  # Slow log
  redis-cli SLOWLOG GET 10
  redis-cli CONFIG GET slowlog-log-slower-than

  # Connection count
  redis-cli INFO clients

  # Keyspace
  redis-cli INFO keyspace

  # Monitor (live commands)
  redis-cli MONITOR

  # Benchmark
  redis-benchmark -n 100000 -c 50 -q

  # Check for memory leaks
  redis-cli MEMORY DOCTOR
  redis-cli MEMORY STATS
  ```

  ### Security
  ```bash
  # /etc/redis/redis.conf
  requirepass yourpassword
  rename-command FLUSHALL ""
  rename-command FLUSHDB ""
  rename-command DEBUG ""
  rename-command CONFIG "CONFIG_b89d1c9f"

  # TLS
  tls-port 6380
  tls-cert-file /etc/redis/tls/redis.crt
  tls-key-file /etc/redis/tls/redis.key
  tls-ca-cert-file /etc/redis/tls/ca.crt

  # Bind to localhost only
  bind 127.0.0.1
  protected-mode yes
  ```

  ### Redis as Cache
  ```python
  import redis
  r = redis.Redis(host='127.0.0.1', port=6379, db=0, password='password')
  r.set('user:1:name', 'Alice', ex=3600)   # 1 hour TTL
  name = r.get('user:1:name')
  r.delete('user:1:name')
  r.incr('counter')
  ```


entity_id: ent_20260526T204003546500_eedbd557
type: memory
category: debian/dns-server
strength: moderate
metadata: "{\"source\": \"debian_phase2_services\"}"
created_at: 2026-05-26T20:40:03.546500
updated_at: 2026-05-26T20:40:03.546500
content:
  ## DNS Server Configuration
  ### BIND9 (Primary DNS Server)
  ```bash
  apt install bind9 bind9utils bind9-doc
  systemctl enable --now bind9
  ```

  ### Zone File (Forward)
  ```bash
  # /etc/bind/named.conf.local
  zone "example.com" {
      type master;
      file "/etc/bind/zones/example.com.zone";
      allow-transfer { 192.168.1.11; };  # secondary server
      allow-update { none; };
  };

  # /etc/bind/zones/example.com.zone
  $TTL 86400
  @   IN  SOA ns1.example.com. admin.example.com. (
              2026010101  ; Serial
              3600        ; Refresh
              900         ; Retry
              604800      ; Expire
              86400 )     ; Minimum TTL

  ; Name servers
  @       IN  NS  ns1.example.com.
  @       IN  NS  ns2.example.com.

  ; A records
  @           IN  A   192.168.1.10
  ns1         IN  A   192.168.1.10
  ns2         IN  A   192.168.1.11
  www         IN  A   192.168.1.10
  mail        IN  A   192.168.1.20

  ; AAAA records
  @           IN  AAAA ::1

  ; MX records
  @       IN  MX  10  mail.example.com.

  ; TXT records
  @       IN  TXT "v=spf1 mx a:example.com -all"
  _dmarc  IN  TXT "v=DMARC1; p=reject; rua=mailto:dmarc@example.com"
  ```

  ### Reverse Zone
  ```bash
  # /etc/bind/named.conf.local
  zone "1.168.192.in-addr.arpa" {
      type master;
      file "/etc/bind/zones/reverse.example.com.zone";
  };

  # /etc/bind/zones/reverse.example.com.zone
  $TTL 86400
  @   IN  SOA ns1.example.com. admin.example.com. (
              2026010101 3600 900 604800 86400 )
  @       IN  NS  ns1.example.com.
  10      IN  PTR ns1.example.com.
  11      IN  PTR ns2.example.com.
  20      IN  PTR mail.example.com.
  ```

  ### DNSSEC
  ```bash
  # Generate keys
  dnssec-keygen -a RSASHA256 -b 2048 -n ZONE example.com

  # Sign zone
  dnssec-signzone -o example.com -N INCREMENT   /etc/bind/zones/example.com.zone   Kexample.com.+008+12345

  # Add to named.conf
  dnssec-validation auto;
  ```

  ### DNS over TLS
  ```bash
  apt install bind9-dnssec
  # /etc/bind/named.conf.options
  options {
      tls-port 853;
      tls-sign-cert-pem "file:/etc/bind/tls/bind.crt";
      tls-sign-key-pem "file:/etc/bind/tls/bind.key";
      tls-ca-pem "file:/etc/bind/tls/ca.crt";
  };
  ```

  ### BIND9 Admin
  ```bash
  # Test config
  named-checkconf
  named-checkzone example.com /etc/bind/zones/example.com.zone

  # Reload zones
  rndc reload
  rndc reload example.com

  # Flush cache
  rndc flush

  # Check status
  rndc status

  # Query local server
  dig @127.0.0.1 example.com
  dig @127.0.0.1 -x 192.168.1.10    # reverse lookup
  dig @127.0.0.1 example.com MX
  dig @127.0.0.1 example.com TXT
  ```

  ### DNSmasq (Lightweight)
  ```bash
  apt install dnsmasq

  # /etc/dnsmasq.conf
  server=8.8.8.8
  server=1.1.1.1
  cache-size=1000
  local=/example.com/
  address=/local.example.com/192.168.1.10
  log-queries

  # /etc/dnsmasq.d/local-hosts
  192.168.1.100 server1.example.com
  192.168.1.101 server2.example.com
  ```

  ### DNS Troubleshooting
  ```bash
  # Check zone syntax
  named-checkzone example.com /etc/bind/zones/example.com.zone

  # Test resolution
  dig example.com +short
  dig @ns1.example.com example.com AXFR    # zone transfer test

  # Check DNSSEC
  dig example.com +dnssec
  dig +nsid @ns1.example.com

  # DNS propagation check
  dig @8.8.8.8 example.com
  dig @1.1.1.1 example.com

  # Cache stats
  rndc stats
  cat /var/cache/bind/named.stats
  ```


entity_id: ent_20260526T204003759600_1ed7f5eb
type: memory
category: debian/dhcp-server
strength: moderate
metadata: "{\"source\": \"debian_phase2_services\"}"
created_at: 2026-05-26T20:40:03.759600
updated_at: 2026-05-26T20:40:03.759600
content:
  ## DHCP Server Configuration
  ### ISC DHCP Server
  ```bash
  apt install isc-dhcp-server
  systemctl enable --now isc-dhcp-server

  # /etc/default/isc-dhcp-server
  INTERFACESv4="eth0"
  ```

  ### Basic Configuration
  ```bash
  # /etc/dhcp/dhcpd.conf
  # Global options
  option domain-name "example.com";
  option domain-name-servers 8.8.8.8, 1.1.1.1;
  option routers 192.168.1.1;
  default-lease-time 600;
  max-lease-time 7200;
  authoritative;

  # Subnet declaration
  subnet 192.168.1.0 netmask 255.255.255.0 {
      range 192.168.1.100 192.168.1.200;
      option subnet-mask 255.255.255.0;
      option routers 192.168.1.1;
      option domain-name-servers 8.8.8.8, 1.1.1.1;
      option domain-name "example.com";
  }
  ```

  ### Static Leases (MAC-based)
  ```bash
  # Fixed IP for specific device
  host server1 {
      hardware ethernet 00:11:22:33:44:55;
      fixed-address 192.168.1.10;
      option host-name "server1.example.com";
  }

  host printer {
      hardware ethernet AA:BB:CC:DD:EE:FF;
      fixed-address 192.168.1.200;
  }
  ```

  ### Multiple Subnets & VLANs
  ```bash
  subnet 192.168.1.0 netmask 255.255.255.0 {
      range 192.168.1.100 192.168.1.200;
      option routers 192.168.1.1;
  }

  subnet 192.168.10.0 netmask 255.255.255.0 {
      range 192.168.10.100 192.168.10.200;
      option routers 192.168.10.1;
      option domain-name-servers 192.168.1.10;
  }

  # VLAN-specific options
  subnet 192.168.20.0 netmask 255.255.255.0 {
      range 192.168.20.100 192.168.20.200;
      option routers 192.168.20.1;
      option pxelinux.path "pxelinux.0";  # for PXE boot
      next-server 192.168.20.10;
  }
  ```

  ### DHCP with DNS Integration
  ```bash
  # /etc/dhcp/dhcpd.conf
  ddns-update-style interim;
  key "ddns_key" {
      algorithm hmac-sha256;
      secret "your_ddns_key_here";
  };
  zone example.com. {
      primary 192.168.1.10;
      key ddns_key;
  }
  ```

  ### DHCP Failover
  ```bash
  failover peer "dhcp-ha" {
      primary;
      address 192.168.1.10;
      peer address 192.168.1.11;
      port 647;
      peer port 647;
      max-response-delay 30;
      max-unacked-updates 10;
      load balance max seconds 3;
  }
  ```

  ### DHCPv6
  ```bash
  # /etc/dhcp/dhcpd6.conf
  option dhcp6.name-servers 2001:4860:4860::8888;
  option dhcp6.domain-search "example.com";

  subnet6 2001:db8::/64 {
      range6 2001:db8::1000 2001:db8::2000;
      option dhcp6.name-servers 2001:4860:4860::8888;
  }
  ```

  ### DHCP Admin
  ```bash
  # Test config
  dhcpd -t

  # Check leases
  cat /var/lib/dhcp/dhcpd.leases

  # Restart
  systemctl restart isc-dhcp-server

  # View active leases
  grep "binding state active" /var/lib/dhcp/dhcpd.leases

  # Clear leases
  > /var/lib/dhcp/dhcpd.leases
  systemctl restart isc-dhcp-server

  # Client-side (request/renew)
  dhclient -r eth0             # release
  dhclient eth0                # request new
  dhclient -r -v eth0          # verbose release

  # Check DHCP server logs
  tail -f /var/log/syslog | grep dhcpd
  ```

  ### DHCP Troubleshooting
  ```bash
  # Check if DHCP server is running
  ss -ulnp | grep dhcp

  # Test DHCP discovery
  tcpdump -i eth0 port 67 or port 68

  # Check lease conflicts
  grep "conflict" /var/log/syslog | grep dhcp

  # Validate config
  dhcpd -t -cf /etc/dhcp/dhcpd.conf
  ```


entity_id: ent_20260526T210324988616_7b0f444c
type: memory
category: debian/virtualization-kvm-qemu
strength: moderate
metadata: "{\"source\": \"phase3_scale_security\"}"
created_at: 2026-05-26T21:03:24.988616
updated_at: 2026-05-26T21:03:24.988616
content:
  ## Virtualization — KVM/QEMU
  ### Install KVM
  ```bash
  apt install -y qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virt-manager
  systemctl enable --now libvirtd

  # Add user to libvirt group
  usermod -aG libvirt,kvm $USER
  ```

  ### Create Virtual Machine
  ```bash
  # Create disk
  qemu-img create -f qcow2 /var/lib/libvirt/images/vm1.qcow2 20G

  # Install with virt-install
  virt-install --name vm1 --ram 4096 --vcpus 2 \
    --disk /var/lib/libvirt/images/vm1.qcow2,format=qcow2 \
    --network network=default \
    --graphics spice \
    --cdrom /path/to/debian.iso

  # CLI-only (no GUI)
  virt-install --name vm2 --ram 2048 --vcpus 1 \
    --disk size=10,format=qcow2 \
    --network network=default \
    --location http://deb.debian.org/debian/dists/bookworm/main/installer-amd64/ \
    --extra-args "console=ttyS0,115200n8 serial"
  ```

  ### VM Management
  ```bash
  # List VMs
  virsh list --all

  # Start/stop/restart
  virsh start vm1
  virsh shutdown vm1
  virsh destroy vm1    # force off

  # Autostart
  virsh autostart vm1

  # Console access
  virsh console vm1

  # Snapshot
  virsh snapshot-create-as vm1 snapshot1 --description "Before update"
  virsh snapshot-list vm1
  virsh snapshot-revert vm1 snapshot1

  # Clone VM
  virt-clone --original vm1 --name vm1-clone --file /var/lib/libvirt/images/vm1-clone.qcow2
  ```

  ### Networking
  ```bash
  # NAT network (default)
  virsh net-list --all
  virsh net-info default

  # Bridged network
  brctl addbr br0
  ip link set br0 up
  # /etc/network/interfaces
  auto br0
  iface br0 inet dhcp
      bridge_ports eth0

  # VM with bridge
  virt-install ... --network bridge=br0

  # MACVLAN
  ip link add eth0.1 link eth0 type macvlan mode bridge
  ```

  ### Storage
  ```bash
  # List pools
  virsh pool-list --all

  # Create pool
  virsh pool-define-as data-pool dir --target /data/vms
  virsh pool-start data-pool
  virsh pool-autostart data-pool

  # Create volume
  virsh vol-create-as data-pool vm3.qcow2 50G --format qcow2

  # Resize disk
  virsh vol-resize --pool data-pool --vol vm1.qcow2 --new-capacity 30G
  qemu-img resize /var/lib/libvirt/images/vm1.qcow2 +10G
  ```

  ### Live Migration
  ```bash
  # Migrate VM between hosts
  virsh migrate --live vm1 qemu+ssh://remote-host/system

  # Requires:
  # - Shared storage (NFS, iSCSI)
  # - Libvirt configured on both hosts
  # - Network connectivity
  ```

  ### Performance Tuning
  ```bash
  # Pin vCPU to physical CPU
  virsh vcpupin vm1 0 0
  virsh vcpupin vm1 1 1

  # Memory policy
  virsh memtune vm1
  virsh setmem vm1 2097152 --config  # 2GB

  # Huge pages
  echo 1024 > /proc/sys/vm/nr_hugepages
  ```


entity_id: ent_20260526T210325213434_5a935d8d
type: memory
category: debian/monitoring-prometheus
strength: moderate
metadata: "{\"source\": \"phase3_scale_security\"}"
created_at: 2026-05-26T21:03:25.213434
updated_at: 2026-05-26T21:03:25.213434
content:
  ## Monitoring — Prometheus
  ### Install Prometheus
  ```bash
  # Download
  wget https://github.com/prometheus/prometheus/releases/download/v2.50.0/prometheus-2.50.0.linux-amd64.tar.gz
  tar xzf prometheus*.tar.gz
  cd prometheus-2.50.0.linux-amd64/

  # Systemd service
  cat > /etc/systemd/system/prometheus.service << 'EOF'
  [Unit]
  Description=Prometheus Monitoring
  After=network.target

  [Service]
  Type=simple
  User=prometheus
  ExecStart=/opt/prometheus/prometheus \
    --config.file=/etc/prometheus/prometheus.yml \
    --storage.tsdb.path=/var/lib/prometheus/ \
    --web.listen-address=:9090

  [Install]
  WantedBy=multi-user.target
  EOF

  mkdir -p /etc/prometheus /var/lib/prometheus
  cp prometheus.yml /etc/prometheus/
  chown -R prometheus: /var/lib/prometheus /etc/prometheus
  systemctl enable --now prometheus
  ```

  ### Configuration
  ```yaml
  # /etc/prometheus/prometheus.yml
  global:
    scrape_interval: 15s
    evaluation_interval: 15s

  rule_files:
    - "alerts/*.yml"

  alerting:
    alertmanagers:
      - static_configs:
          - targets: ["localhost:9093"]

  scrape_configs:
    - job_name: "prometheus"
      static_configs:
        - targets: ["localhost:9090"]

    - job_name: "node"
      static_configs:
        - targets: ["localhost:9100"]
      metrics_path: /metrics

    - job_name: "nginx"
      static_configs:
        - targets: ["localhost:9113"]
  ```

  ### Node Exporter
  ```bash
  # Install
  wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz
  tar xzf node_exporter*.tar.gz
  cp node_exporter-1.7.0.linux-amd64/node_exporter /usr/local/bin/

  # Service
  cat > /etc/systemd/system/node_exporter.service << 'EOF'
  [Unit]
  Description=Node Exporter
  After=network.target

  [Service]
  ExecStart=/usr/local/bin/node_exporter \
    --collector.systemd \
    --collector.systemd.unit-include=.*

  [Install]
  WantedBy=multi-user.target
  EOF

  systemctl enable --now node_exporter
  ```

  ### Alerts
  ```yaml
  # /etc/prometheus/alerts/node_alerts.yml
  groups:
    - name: node_alerts
      rules:
        - alert: HighCPU
          expr: 100 - (avg by(instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
          for: 5m
          labels:
            severity: warning
          annotations:
            summary: "High CPU usage on {{ $labels.instance }}"

        - alert: DiskFull
          expr: (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100 < 10
          for: 5m
          labels:
            severity: critical
          annotations:
            summary: "Disk almost full on {{ $labels.instance }}"

        - alert: HighMemory
          expr: (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100 > 90
          for: 5m
          labels:
            severity: warning
          annotations:
            summary: "High memory usage on {{ $labels.instance }}"
  ```

  ### Common Metrics
  ```promql
  # CPU usage
  100 - (avg by(instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)

  # Memory usage
  (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100

  # Disk I/O
  rate(node_disk_read_bytes_total[5m])
  rate(node_disk_written_bytes_total[5m])

  # Network
  rate(node_network_receive_bytes_total{device!="lo"}[5m])
  rate(node_network_transmit_bytes_total{device!="lo"}[5m])

  # Load average
  node_load1
  node_load5
  node_load15
  ```

  ### Exporter Ecosystem
  | Exporter | Port | Purpose |
  |----------|------|---------|
  | node_exporter | 9100 | System metrics |
  | nginx_exporter | 9113 | Nginx stats |
  | postgres_exporter | 9187 | PostgreSQL |
  | mysqld_exporter | 9104 | MySQL/MariaDB |
  | redis_exporter | 9121 | Redis |
  | cadvisor | 8080 | Container metrics |
  | blackbox_exporter | 9115 | HTTP/TCP/ICMP probes |


entity_id: ent_20260526T210325431190_7c89553f
type: memory
category: debian/monitoring-grafana
strength: moderate
metadata: "{\"source\": \"phase3_scale_security\"}"
created_at: 2026-05-26T21:03:25.431190
updated_at: 2026-05-26T21:03:25.431190
content:
  ## Monitoring — Grafana
  ### Install Grafana
  ```bash
  # Install
  apt install -y apt-transport-https software-properties-common
  wget -q -O - https://packages.grafana.com/gpg.key | gpg --dearmor > /usr/share/keyrings/grafana.gpg
  echo "deb [signed-by=/usr/share/keyrings/grafana.gpg] https://packages.grafana.com/oss/deb stable main" \
    > /etc/apt/sources.list.d/grafana.list
  apt update && apt install -y grafana

  systemctl enable --now grafana-server
  ```

  ### Data Sources
  ```bash
  # Add Prometheus via API
  curl -X POST http://admin:admin@localhost:3000/api/datasources \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Prometheus",
      "type": "prometheus",
      "url": "http://localhost:9090",
      "access": "proxy",
      "isDefault": true
    }'
  ```

  ### Dashboard: System Overview
  ```json
  {
    "panels": [
      {
        "title": "CPU Usage",
        "type": "timeseries",
        "targets": [{
          "expr": "100 - (avg by(instance)(rate(node_cpu_seconds_total{mode='idle'}[5m])) * 100)",
          "legendFormat": "{{instance}}"
        }],
        "fieldConfig": {
          "defaults": { "unit": "percent" }
        }
      },
      {
        "title": "Memory Usage",
        "type": "timeseries",
        "targets": [{
          "expr": "(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100",
          "legendFormat": "{{instance}}"
        }],
        "fieldConfig": {
          "defaults": { "unit": "percent" }
        }
      },
      {
        "title": "Disk Usage",
        "type": "gauge",
        "targets": [{
          "expr": "(1 - node_filesystem_avail_bytes{mountpoint='/'} / node_filesystem_size_bytes{mountpoint='/'}) * 100",
          "legendFormat": "{{instance}}"
        }],
        "fieldConfig": {
          "defaults": {
            "unit": "percent",
            "max": 100,
            "thresholds": {
              "steps": [
                {"color": "green", "value": null},
                {"color": "yellow", "value": 70},
                {"color": "red", "value": 90}
              ]
            }
          }
        }
      }
    ]
  }
  ```

  ### Import Community Dashboards
  ```bash
  # Popular dashboard IDs
  # 1860 - Node Exporter Full
  # 8919 - Nginx Exporter Stats
  # 12490 - PostgreSQL
  # 7600 - Redis

  curl -X POST http://admin:admin@localhost:3000/api/dashboards/imports \
    -H "Content-Type: application/json" \
    -d '{
      "dashboard": {"id": null, "title": "Node Exporter Full"},
      "inputs": [{"name": "DS_PROMETHEUS", "type": "datasource", "pluginId": "prometheus"}],
      "overwrite": true
    }'
  ```

  ### Alerting
  ```yaml
  # Contact point
  curl -X POST http://admin:admin@localhost:3000/api/alerting/contact-points \
    -H "Content-Type: application/json" \
    -d '{
      "name": "email",
      "type": "email",
      "settings": {
        "addresses": "admin@example.com"
      }
    }'

  # Alert rule
  curl -X POST http://admin:admin@localhost:3000/api/v1/provisioning/alert-rules \
    -H "Content-Type: application/json" \
    -d '{
      "name": "High CPU Alert",
      "for": "5m",
      "conditions": [{
        "query": {
          "model": {
            "query": "100 - (avg by(instance)(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80"
          }
        }
      }]
    }'
  ```

  ### Security
  ```bash
  # /etc/grafana/grafana.ini
  [security]
  admin_user = admin
  admin_password = ${GRAFANA_ADMIN_PASSWORD}
  secret_key = $(openssl rand -base64 32)

  [server]
  http_port = 3000
  domain = monitoring.example.com
  root_url = %(protocol)s://%(domain)s:%(http_port)s/
  protocol = https

  # Nginx reverse proxy for SSL
  server {
      listen 443 ssl;
      server_name monitoring.example.com;
      location / {
          proxy_pass http://127.0.0.1:3000;
          proxy_set_header Host $host;
      }
  }
  ```


entity_id: ent_20260526T210325651106_d3fddc34
type: memory
category: debian/ldap-auth
strength: moderate
metadata: "{\"source\": \"phase3_scale_security\"}"
created_at: 2026-05-26T21:03:25.651106
updated_at: 2026-05-26T21:03:25.651106
content:
  ## LDAP Authentication & Samba
  ### OpenLDAP Server Setup
  ```bash
  # Install
  apt install -y slapd ldap-utils

  # Domain: example.com
  # Admin password: set during install
  dpkg-reconfigure slapd

  # Directory: /etc/ldap/slapd.d/
  # Database: /var/lib/ldap/
  ```

  ### LDAP Configuration
  ```ldif
  # Base DN structure
  dn: dc=example,dc=com
  objectClass: top
  objectClass: dcObject
  objectClass: organization
  o: Example Corp
  dc: example

  # People container
  dn: ou=people,dc=example,dc=com
  objectClass: organizationalUnit
  ou: people

  # Groups container
  dn: ou=groups,dc=example,dc=com
  objectClass: organizationalUnit
  ou: groups
  ```

  ### Add Users/Groups via LDIF
  ```ldif
  # users.ldif
  dn: cn=admin,ou=groups,dc=example,dc=com
  objectClass: groupOfNames
  cn: admin
  member: uid=john,ou=people,dc=example,dc=com

  dn: uid=john,ou=people,dc=example,dc=com
  objectClass: inetOrgPerson
  objectClass: posixAccount
  uid: john
  cn: John Doe
  sn: Doe
  uidNumber: 1000
  gidNumber: 1000
  homeDirectory: /home/john
  loginShell: /bin/bash
  userPassword: {SSHA}hashedpassword
  ```

  ### Load LDIF
  ```bash
  ldapadd -x -D cn=admin,dc=example,dc=com -W -f users.ldif
  ```

  ### Client Configuration (SSSD)
  ```bash
  # Install
  apt install -y sssd libnss-ldap libpam-ldapd

  # /etc/sssd/sssd.conf
  [sssd]
  domains = example.com
  config_file_version = 2

  [domain/example.com]
  id_provider = ldap
  auth_provider = ldap
  ldap_uri = ldap://ldap.example.com
  ldap_search_base = dc=example,dc=com
  ldap_tls_cacertdir = /etc/ssl/certs
  cache_credentials = True

  # PAM integration
  auth-client-config -t sssd -p sssd
  pam-auth-update

  # NSSwitch
  # /etc/nsswitch.conf
  passwd:         files sss
  group:          files sss
  shadow:         files sss
  ```

  ### Samba PDC/LDAP
  ```bash
  # Install
  apt install -y samba

  # /etc/samba/smb.conf
  [global]
     workgroup = EXAMPLE
     server string = Samba Server
     security = user
     passdb backend = ldapsam:ldap://localhost
     ldap suffix = dc=example,dc=com
     ldap user suffix = ou=people
     ldap group suffix = ou=groups
     ldap machine suffix = ou=computers
     ldap admin dn = cn=admin,dc=example,dc=com
     ldap ssl = start tls

  [shares]
     path = /srv/samba/shares
     browseable = yes
     writable = yes
     valid users = @"@admin"
  ```

  ### LDAP Troubleshooting
  ```bash
  # Test connection
  ldapsearch -x -H ldap://localhost -b dc=example,dc=com

  # Test bind
  ldapsearch -x -D cn=admin,dc=example,dc=com -W -b dc=example,dc=com

  # Search user
  ldapsearch -x uid=john -b ou=people,dc=example,dc=com

  # Test SSSD
  sssctl user-show john
  sssctl domain-status example.com

  # Check logs
  journalctl -u slapd -f
  journalctl -u sssd -f
  ```


entity_id: ent_20260526T210325868082_b3ce4c1e
type: memory
category: debian/shell-scripting-deep
strength: moderate
metadata: "{\"source\": \"phase3_scale_security\"}"
created_at: 2026-05-26T21:03:25.868082
updated_at: 2026-05-26T21:03:25.868082
content:
  ## Shell Scripting Deep Dive
  ### Script Structure
  ```bash
  #!/bin/bash
  set -euo pipefail  # Exit on error, undefined var, pipe failure

  # Script header
  readonly SCRIPT_NAME="monitor.sh"
  readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  readonly LOG_FILE="/var/log/${SCRIPT_NAME%.sh}.log"

  # Functions
  log() {
      local level="$1"; shift
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*" | tee -a "$LOG_FILE"
  }

  usage() {
      cat << EOF
  Usage: $SCRIPT_NAME [OPTIONS]

  Options:
    -h    Show this help
    -v    Verbose output
    -n    Dry run
  EOF
      exit "${1:-0}"
  }

  # Main
  main() {
      local verbose=false
      local dry_run=false
      
      while getopts "hvnd:" opt; do
          case $opt in
              h) usage ;;
              v) verbose=true ;;
              n) dry_run=true ;;
              *) usage 1 ;;
          esac
      done
      
      log "INFO" "Script started"
      # ... main logic ...
      log "INFO" "Script completed"
  }

  main "$@"
  ```

  ### Arrays & Associative Arrays
  ```bash
  # Indexed arrays
  declare -a fruits=("apple" "banana" "cherry")
  fruits+=("date")
  echo "${fruits[@]}"        # all elements
  echo "${fruits[0]}"        # first element
  echo "${#fruits[@]}"       # length

  # Associative arrays
  declare -A config
  config[host]="server1.example.com"
  config[port]="22"
  config[user]="admin"

  for key in "${!config[@]}"; do
      echo "$key = ${config[$key]}"
  done
  ```

  ### Process Management in Scripts
  ```bash
  # Check if process running
  if pgrep -x "nginx" > /dev/null; then
      log "INFO" "Nginx is running"
  fi

  # Run command with timeout
  timeout 30 curl -s https://example.com || {
      log "ERROR" "Request timed out"
      exit 1
  }

  # Run in background
  some_command &
  BG_PID=$!
  wait $BG_PID

  # Wait for port
  wait_for_port() {
      local host="$1" port="$2" timeout="${3:-30}"
      for i in $(seq 1 $timeout); do
          if nc -z "$host" "$port" 2>/dev/null; then
              return 0
          fi
          sleep 1
      done
      return 1
  }
  ```

  ### File Operations
  ```bash
  # Safe file operations
  safe_write() {
      local file="$1" content="$2"
      echo "$content" > "${file}.tmp"
      mv "${file}.tmp" "$file"
      chmod 644 "$file"
  }

  # File locking
  exec 200>"$LOG_FILE.lock"
  flock -n 200 || { log "ERROR" "Script already running"; exit 1; }

  # Temp files
  TMPFILE=$(mktemp)
  trap "rm -f $TMPFILE" EXIT
  ```

  ### Network Operations
  ```bash
  # HTTP requests
  http_get() {
      local url="$1"
      curl -sf -o /dev/null -w "%{http_code}" "$url"
  }

  http_code=$(http_get "https://example.com")
  if [[ "$http_code" == "200" ]]; then
      log "INFO" "Site is up"
  fi

  # Check multiple hosts
  check_hosts=(
      "server1.example.com:22"
      "server2.example.com:80"
      "db.example.com:5432"
  )

  for host_port in "${check_hosts[@]}"; do
      IFS=':' read -r host port <<< "$host_port"
      if nc -z "$host" "$port" -w 5; then
          log "INFO" "$host:$port is reachable"
      else
          log "ERROR" "$host:$port is unreachable"
      fi
  done
  ```

  ### Cron Integration
  ```bash
  # Wrapper for cron
  LOCKFILE="/var/lock/$(basename $0).lock"

  if [ -f "$LOCKFILE" ]; then
      PID=$(cat "$LOCKFILE")
      if kill -0 "$PID" 2>/dev/null; then
          log "WARN" "Script already running (PID: $PID)"
          exit 0
      fi
  fi

  echo $$ > "$LOCKFILE"
  trap "rm -f $LOCKFILE" EXIT

  # Run and capture output
  output=$(main "$@" 2>&1)
  log "INFO" "Output: $output"
  ```


entity_id: ent_20260526T210326084406_52ee3f4a
type: memory
category: debian/systemd-deep
strength: moderate
metadata: "{\"source\": \"phase3_scale_security\"}"
created_at: 2026-05-26T21:03:26.084406
updated_at: 2026-05-26T21:03:26.084406
content:
  ## Systemd Deep Dive
  ### Unit Types
  | Type | Extension | Purpose |
  |------|-----------|---------|
  | Service | .service | Long-running processes |
  | Timer | .timer | Cron replacement |
  | Socket | .socket | Socket activation |
  | Mount | .mount | Mount points |
  | Path | .path | File/directory watches |
  | Target | .target | Grouping units |
  | Device | .device | Device files |

  ### Service Unit Example
  ```ini
  # /etc/systemd/system/myapp.service
  [Unit]
  Description=My Application
  After=network.target postgresql.service
  Wants=postgresql.service

  [Service]
  Type=notify
  ExecStart=/opt/myapp/bin/myapp --config /etc/myapp/config.yml
  ExecReload=/bin/kill -HUP $MAINPID
  Restart=on-failure
  RestartSec=5
  User=myapp
  Group=myapp
  Environment=NODE_ENV=production
  EnvironmentFile=/etc/myapp/env

  # Security
  NoNewPrivileges=true
  ProtectSystem=strict
  ProtectHome=read-only
  ReadWritePaths=/var/log/myapp /var/lib/myapp
  PrivateTmp=true

  # Limits
  LimitNOFILE=65536
  LimitNPROC=4096

  # Logging
  StandardOutput=journal
  StandardError=journal
  SyslogIdentifier=myapp

  [Install]
  WantedBy=multi-user.target
  ```

  ### Timers (Cron Replacement)
  ```ini
  # /etc/systemd/system/backup.timer
  [Unit]
  Description=Daily Backup Timer

  [Timer]
  OnCalendar=*-*-* 02:00:00
  RandomizedDelaySec=300
  Persistent=true
  Unit=backup.service

  [Install]
  WantedBy=timers.target

  # /etc/systemd/system/backup.service
  [Unit]
  Description=Daily Backup

  [Service]
  Type=oneshot
  ExecStart=/usr/local/bin/backup.sh
  User=root
  ```

  ```bash
  # Timer management
  systemctl list-timers --all
  systemctl start backup.timer
  systemctl status backup.timer
  journalctl -u backup.timer
  ```

  ### Socket Activation
  ```ini
  # /etc/systemd/system/myapp.socket
  [Unit]
  Description=My App Socket

  [Socket]
  ListenStream=8080
  Accept=false
  SocketMode=0666

  [Install]
  WantedBy=sockets.target

  # Service activated when connection arrives on port 8080
  # /etc/systemd/system/myapp@.service
  [Service]
  ExecStart=/opt/myapp/handler
  ```

  ### Path Activation
  ```ini
  # /etc/systemd/system/process-uploads.path
  [Unit]
  Description=Watch upload directory

  [Path]
  PathExists=/var/uploads/new
  PathModified=/var/uploads/new
  Unit=process-uploads.service

  [Install]
  WantedBy=multi-user.target
  ```

  ### Systemd Analyze
  ```bash
  # Boot time analysis
  systemd-analyze                   # total boot time
  systemd-analyze blame            # services by startup time
  systemd-analyze critical-chain   # dependency chain
  systemd-analyze plot > boot.svg  # visual chart

  # Unit dependency
  systemctl list-dependencies myapp.service
  systemctl show myapp.service

  # Resource usage
  systemd-cgtop                    # like top for cgroups
  systemctl status --no-pager
  ```

  ### Drop-in Overrides
  ```bash
  # Create override directory
  systemctl edit myapp.service

  # /etc/systemd/system/myapp.service.d/override.conf
  [Service]
  Environment=DEBUG=true
  ExecStartPre=/bin/echo "Starting..."

  # Reload and restart
  systemctl daemon-reload
  systemctl restart myapp.service
  ```

  ### Systemd Journal
  ```bash
  # Basic queries
  journalctl -u myapp
  journalctl -u myapp --since "1 hour ago"
  journalctl -u myapp --since "today" --until "now"

  # Priority filtering
  journalctl -p err
  journalctl -p warn..info

  # Disk management
  journalctl --disk-usage
  journalctl --vacuum-size=500M
  journalctl --vacuum-time=7d

  # Persistent logs
  # /etc/systemd/journald.conf
  [Journal]
  Storage=persistent
  SystemMaxUse=1G
  MaxFileSec=1day
  ```


entity_id: ent_20260526T211508234260_d65605d8
type: memory
category: debian/docker-deep
strength: moderate
metadata: "{\"source\": \"phase4_orchestration\"}"
created_at: 2026-05-26T21:15:08.234260
updated_at: 2026-05-26T21:15:08.234260
content:
  ## Docker Deep Dive
  ### Install Docker
  ```bash
  # Add repo
  apt install -y ca-certificates curl gnupg
  install -m 0755 -d /etc/apt/keyrings
  curl -fsSL https://download.docker.com/linux/debian/gpg \
    | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  chmod a+r /etc/apt/keyrings/docker.gpg

  echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
    https://download.docker.com/linux/debian $(lsb_release -cs) stable" \
    > /etc/apt/sources.list.d/docker.list

  apt update && apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

  # Non-root access
  usermod -aG docker $USER
  ```

  ### Dockerfile Best Practices
  ```dockerfile
  # Multi-stage build (Go example)
  FROM golang:1.21-alpine AS builder
  WORKDIR /build
  COPY go.mod go.sum ./
  RUN go mod download
  COPY . .
  RUN CGO_ENABLED=0 go build -o /app

  # Final image — small and clean
  FROM alpine:3.18
  RUN apk add --no-cache ca-certificates
  WORKDIR /app
  COPY --from=builder /app .
  USER nobody
  EXPOSE 8080
  CMD ["./app"]
  ```

  ```dockerfile
  # Multi-stage (Node.js)
  FROM node:20-alpine AS builder
  WORKDIR /app
  COPY package*.json ./
  RUN npm ci --only=production
  COPY . .

  FROM node:20-alpine
  WORKDIR /app
  COPY --from=builder /app .
  USER node
  EXPOSE 3000
  CMD ["node", "server.js"]
  ```

  ### Docker Networking
  ```bash
  # Network types
  docker network ls
  docker network create --driver bridge my-net
  docker network create --driver overlay my-overlay  # swarm only
  docker network create --driver macvlan --subnet=192.168.1.0/24 --gateway=192.168.1.1 -o parent=eth0 macvlan-net

  # Container DNS resolution
  docker run --name web1 --net my-net nginx:alpine
  docker run --name web2 --net my-net nginx:alpine
  # web2 can reach web1 by name

  # Port mapping
  docker run -p 8080:80 nginx:alpine    # host:container
  docker run -p 127.0.0.1:8080:80 nginx:alpine  # localhost only
  docker run -p 8000-8100:80 nginx:alpine  # port range
  ```

  ### Volumes & Data
  ```bash
  # Named volumes
  docker volume create mydata
  docker run -v mydata:/data nginx:alpine

  # Bind mounts
  docker run -v /host/path:/container/path:ro nginx:alpine

  # tmpfs (in-memory)
  docker run -tmpfs /tmp:noexec,nosuid,size=100m nginx:alpine

  # Volume management
  docker volume ls
  docker inspect mydata
  docker volume prune
  ```

  ### Docker Compose
  ```yaml
  # docker-compose.yml
  version: '3.8'

  services:
    web:
      build:
        context: .
        dockerfile: Dockerfile
      ports:
        - "8080:8080"
      environment:
        - DATABASE_URL=postgresql://user:pass@db:5432/mydb
      depends_on:
        db:
          condition: service_healthy
      deploy:
        resources:
          limits:
            cpus: '1.0'
            memory: 512M
      restart: unless-stopped
      networks:
        - app-net

    db:
      image: postgres:16-alpine
      environment:
        - POSTGRES_DB=mydb
        - POSTGRES_USER=user
        - POSTGRES_PASSWORD=pass
      volumes:
        - pgdata:/var/lib/postgresql/data
        - ./init.sql:/docker-entrypoint-initdb.d/init.sql
      healthcheck:
        test: ["CMD-SHELL", "pg_isready -U user -d mydb"]
        interval: 10s
        timeout: 5s
        retries: 5
      networks:
        - app-net

    redis:
      image: redis:7-alpine
      volumes:
        - redis-data:/data
      networks:
        - app-net

  volumes:
    pgdata:
    redis-data:

  networks:
    app-net:
      driver: bridge
  ```

  ### Docker Security
  ```bash
  # Run as non-root (Dockerfile: USER nobody)
  # Read-only root filesystem
  docker run --read-only --tmpfs /tmp nginx:alpine

  # Drop capabilities
  docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE nginx:alpine

  # Seccomp profile
  docker run --security-opt seccomp=/path/to/profile.json nginx:alpine

  # AppArmor
  docker run --security-opt apparmor=docker-default nginx:alpine

  # No new privileges
  docker run --security-opt=no-new-privileges nginx:alpine

  # Resource limits
  docker run --memory=512m --cpus=1.0 --pids-limit=100 nginx:alpine
  ```

  ### Build Cache Optimization
  ```dockerfile
  # Layer caching — order matters!
  FROM node:20-alpine
  WORKDIR /app
  # These rarely change — cache them first
  COPY package.json package-lock.json ./
  RUN npm ci --only=production
  # Source changes more often — cached layer reused
  COPY . .
  RUN npm run build
  CMD ["node", "dist/server.js"]
  ```

  ### Registry & Push
  ```bash
  # Tag and push
  docker tag myapp:latest registry.example.com/myapp:1.0.0
  docker tag myapp:latest registry.example.com/myapp:latest
  docker push registry.example.com/myapp:1.0.0

  # Private registry
  docker login registry.example.com
  # Or with token
  echo "$TOKEN" | docker login registry.example.com -u user --password-stdin
  ```


entity_id: ent_20260526T211508460829_7ac86fff
type: memory
category: debian/kubernetes
strength: moderate
metadata: "{\"source\": \"phase4_orchestration\"}"
created_at: 2026-05-26T21:15:08.460829
updated_at: 2026-05-26T21:15:08.460829
content:
  ## Kubernetes
  ### Install (kubeadm)
  ```bash
  # Prerequisites
  apt install -y containerd
  mkdir -p /etc/containerd
  containerd config default > /etc/containerd/config.toml
  sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
  systemctl restart containerd

  # Install k8s tools
  apt install -y apt-transport-https ca-certificates curl gpg
  curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.29/deb/Release.key \
    | gpg --dearmor -o /etc/apt/keyrings/kubernetes.gpg

  echo "deb [signed-by=/etc/apt/keyrings/kubernetes.gpg] \
    https://pkgs.k8s.io/core:/stable:/v1.29:/deb/ /" \
    > /etc/apt/sources.list.d/kubernetes.list

  apt update
  apt install -y kubelet kubeadm kubectl
  apt-mark hold kubelet kubeadm kubectl

  # Disable swap (required)
  swapoff -a
  sed -i '/swap/d' /etc/fstab
  ```

  ### Initialize Cluster
  ```bash
  # Master node
  kubeadm init --pod-network-cidr=10.244.0.0/16 \
    --apiserver-advertise-address=192.168.1.10

  # Setup kubectl
  mkdir -p $HOME/.kube
  cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  chown $(id -u):$(id -g) $HOME/.kube/config

  # Install CNI (Flannel)
  kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml

  # Worker nodes — run output from kubeadm init
  kubeadm join 192.168.1.10:6443 --token <token> --discovery-token-ca-cert-hash sha256:<hash>
  ```

  ### Core Resources
  ```yaml
  # Deployment (stateless)
  apiVersion: apps/v1
  kind: Deployment
  metadata:
    name: web-app
    labels:
      app: web-app
  spec:
    replicas: 3
    selector:
      matchLabels:
        app: web-app
    strategy:
      type: RollingUpdate
      rollingUpdate:
        maxSurge: 1
        maxUnavailable: 0
    template:
      metadata:
        labels:
          app: web-app
      spec:
        containers:
        - name: app
          image: myapp:1.0
          ports:
          - containerPort: 8080
          resources:
            requests: {cpu: 100m, memory: 128Mi}
            limits: {cpu: 500m, memory: 512Mi}
          livenessProbe:
            httpGet: {path: /health, port: 8080}
            initialDelaySeconds: 15
            periodSeconds: 10
          readinessProbe:
            httpGet: {path: /ready, port: 8080}
            initialDelaySeconds: 5
            periodSeconds: 5
          env:
          - name: DB_HOST
            valueFrom:
              configMapKeyRef:
                name: app-config
                key: db_host
          - name: DB_PASSWORD
            valueFrom:
              secretKeyRef:
                name: app-secrets
                key: db_password
  ---
  # Service (networking)
  apiVersion: v1
  kind: Service
  metadata:
    name: web-app-service
  spec:
    type: ClusterIP
    selector:
      app: web-app
    ports:
    - port: 80
      targetPort: 8080
  ```

  ### Ingress
  ```yaml
  apiVersion: networking.k8s.io/v1
  kind: Ingress
  metadata:
    name: web-ingress
    annotations:
      nginx.ingress.kubernetes.io/ssl-redirect: "true"
      cert-manager.io/cluster-issuer: letsencrypt-prod
  spec:
    ingressClassName: nginx
    tls:
    - hosts:
      - app.example.com
      secretName: app-tls
    rules:
    - host: app.example.com
      http:
        paths:
        - path: /
          pathType: Prefix
          backend:
            service:
              name: web-app-service
              port:
                number: 80
  ```

  ### Persistent Volumes
  ```yaml
  # PersistentVolumeClaim
  apiVersion: v1
  kind: PersistentVolumeClaim
  metadata:
    name: db-pvc
  spec:
    accessModes:
    - ReadWriteOnce
    resources:
      requests:
        storage: 10Gi
    storageClassName: standard

  # StatefulSet (stateful apps)
  apiVersion: apps/v1
  kind: StatefulSet
  metadata:
    name: postgres
  spec:
    serviceName: postgres
    replicas: 1
    selector:
      matchLabels:
        app: postgres
    template:
      spec:
        containers:
        - name: postgres
          image: postgres:16
          ports:
          - containerPort: 5432
          volumeMounts:
          - name: db-data
            mountPath: /var/lib/postgresql/data
          env:
          - name: POSTGRES_PASSWORD
            valueFrom:
              secretKeyRef:
                name: app-secrets
                key: db_password
    volumeClaimTemplates:
    - metadata:
        name: db-data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 10Gi
  ```

  ### ConfigMaps & Secrets
  ```yaml
  # ConfigMap
  apiVersion: v1
  kind: ConfigMap
  metadata:
    name: app-config
  data:
    db_host: "postgres.default.svc.cluster.local"
    redis_host: "redis.default.svc.cluster.local"
    log_level: "info"

  # Secret
  apiVersion: v1
  kind: Secret
  metadata:
    name: app-secrets
  type: Opaque
  data:
    db_password: cGFzc3dvcmQxMjM=  # base64 encoded
  ```

  ### Kubectl Cheat Sheet
  ```bash
  # Get resources
  kubectl get pods -A
  kubectl get svc -n namespace
  kubectl get deployments
  kubectl get nodes

  # Describe (detailed info)
  kubectl describe pod <name>
  kubectl describe node <name>

  # Logs
  kubectl logs <pod-name>
  kubectl logs -f <pod-name>           # follow
  kubectl logs --tail=100 <pod-name>

  # Exec into pod
  kubectl exec -it <pod-name> -- /bin/sh
  kubectl exec -it <pod-name> -c <container> -- /bin/sh

  # Scale
  kubectl scale deployment web-app --replicas=5

  # Rolling update
  kubectl set image deployment/web-app app=myapp:2.0
  kubectl rollout status deployment/web-app
  kubectl rollout history deployment/web-app
  kubectl rollout undo deployment/web-app

  # Delete
  kubectl delete -f deployment.yml
  kubectl delete pod <name>

  # Port-forward
  kubectl port-forward svc/web-app-service 8080:80

  # Apply
  kubectl apply -f config.yml
  kubectl apply -f ./manifests/ -R
  ```

  ### Helm (Package Manager)
  ```bash
  # Install
  apt install -y helm
  # or
  curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash

  # Usage
  helm repo add bitnami https://charts.bitnami.com/bitnami
  helm install my-redis bitnami/redis
  helm list
  helm upgrade my-redis bitnami/redis --set auth.enabled=false
  helm uninstall my-redis
  ```


entity_id: ent_20260526T211508679641_c3dca17f
type: memory
category: debian/terraform
strength: moderate
metadata: "{\"source\": \"phase4_orchestration\"}"
created_at: 2026-05-26T21:15:08.679641
updated_at: 2026-05-26T21:15:08.679641
content:
  ## Terraform — Infrastructure as Code
  ### Install
  ```bash
  # Debian package
  apt install -y gnupg software-properties-common
  wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor \
    | tee /usr/share/keyrings/hashicorp-archive-keyring.gpg > /dev/null

  echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
    https://apt.releases.hashicorp.com $(lsb_release -cs) main" \
    > /etc/apt/sources.list.d/hashicorp.list

  apt update && apt install -y terraform
  ```

  ### Project Structure
  ```
  project/
  ├── main.tf          # Main resources
  ├── variables.tf     # Input variables
  ├── outputs.tf       # Output values
  ├── providers.tf     # Provider config
  ├── terraform.tfvars # Variable values
  ├── environments/
  │   ├── dev/
  │   │   └── backend.tf
  │   └── prod/
  │       └── backend.tf
  └── modules/
      └── vpc/
          ├── main.tf
          ├── variables.tf
          └── outputs.tf
  ```

  ### Provider Config
  ```hcl
  # providers.tf
  terraform {
    required_version = ">= 1.6.0"

    required_providers {
      aws = {
        source  = "hashicorp/aws"
        version = "~> 5.0"
      }
      docker = {
        source  = "kreuzwerker/docker"
        version = "~> 3.0"
      }
    }
  }

  provider "aws" {
    region = var.aws_region
  }

  # variables.tf
  variable "aws_region" {
    default = "us-east-1"
  }

  variable "app_name" {
    default = "myapp"
  }

  variable "instance_count" {
    default = 2
  }

  variable "db_password" {
    type      = string
    sensitive = true
  }
  ```

  ### EC2 Instance Module
  ```hcl
  # modules/ec2/main.tf
  variable "instance_type" {
    default = "t3.micro"
  }

  variable "ami_id" {}

  variable "count" {
    default = 1
  }

  data "aws_ami" "debian" {
    most_recent = true
    owners      = ["debian"]

    filter {
      name   = "name"
      values = ["debian-12-*"]
    }
  }

  resource "aws_instance" "this" {
    count         = var.count
    ami           = var.ami_id
    instance_type = var.instance_type

    tags = {
      Name        = "${var.name}-${count.index + 1}"
      ManagedBy   = "terraform"
    }
  }

  output "instance_ids" {
    value = aws_instance.this[*].id
  }
  ```

  ### Docker Provider
  ```hcl
  # Docker containers
  provider "docker" {}

  resource "docker_image" "app" {
    name = "myapp:latest"
  }

  resource "docker_container" "app" {
    name    = "myapp"
    image   = docker_image.app.latest
    ports {
      internal = 8080
      external = 8080
    }
    env = ["NODE_ENV=production"]
  }
  ```

  ### State Management
  ```hcl
  # Remote backend (S3)
  terraform {
    backend "s3" {
      bucket         = "myapp-terraform-state"
      key            = "prod/terraform.tfstate"
      region         = "us-east-1"
      dynamodb_table = "terraform-locks"
      encrypt        = true
    }
  }

  # Multiple workspaces
  terraform workspace new dev
  terraform workspace new prod
  terraform workspace select prod
  ```

  ### Common Commands
  ```bash
  # Initialize
  terraform init

  # Plan (dry run)
  terraform plan -var-file=terraform.tfvars
  terraform plan -out=tfplan

  # Apply
  terraform apply tfplan
  terraform apply -auto-approve

  # Destroy
  terraform destroy
  terraform destroy -target=aws_instance.this

  # State management
  terraform state list
  terraform state show aws_instance.this
  terraform state mv old.resource new.resource

  # Format & validate
  terraform fmt
  terraform validate

  # Import existing resources
  terraform import aws_instance.this i-1234567890abcdef0

  # Output
  terraform output
  terraform output instance_id
  ```

  ### Workflows
  ```bash
  # CI/CD pipeline
  #!/bin/bash
  set -euo pipefail

  terraform init
  terraform fmt -check || { echo "Format check failed"; exit 1; }
  terraform validate
  terraform plan -out=tfplan -var-file=environments/${ENV}.tfvars

  # Review plan, then apply
  if [ "${AUTO_APPROVE}" = "true" ]; then
      terraform apply tfplan
  fi

  # Destroy old state after migration
  terraform workspace select default
  ```

  ### Security Best Practices
  ```hcl
  # Never hardcode secrets — use environment variables or vault
  variable "api_key" {
    type      = string
    sensitive = true
  }

  # Use data sources for AMIs (auto-update)
  data "aws_ami" "debian" {
    most_recent = true
    owners      = ["debian"]
  }

  # Restrict provider permissions
  provider "aws" {
    region = "us-east-1"
    # Use IAM role with least privilege
  }
  ```


entity_id: ent_20260526T211508896225_f1e1efe2
type: memory
category: debian/cicd
strength: moderate
metadata: "{\"source\": \"phase4_orchestration\"}"
created_at: 2026-05-26T21:15:08.896225
updated_at: 2026-05-26T21:15:08.896225
content:
  ## CI/CD Pipelines
  ### GitHub Actions
  ```yaml
  # .github/workflows/ci.yml
  name: CI/CD Pipeline

  on:
    push:
      branches: [main, develop]
    pull_request:
      branches: [main]

  env:
    REGISTRY: ghcr.io
    IMAGE_NAME: ${{ github.repository }}

  jobs:
    test:
      runs-on: ubuntu-latest
      services:
        postgres:
          image: postgres:16
          env:
            POSTGRES_DB: testdb
            POSTGRES_USER: test
            POSTGRES_PASSWORD: test
          options: >-
            --health-cmd pg_isready
            --health-interval 10s
            --health-timeout 5s
            --health-retries 5
          ports:
            - 5432:5432
        redis:
          image: redis:7-alpine
          ports:
            - 6379:6379

      steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Lint
        run: npm run lint

      - name: Type check
        run: npm run typecheck

      - name: Run tests
        run: npm test
        env:
          DATABASE_URL: postgresql://test:test@localhost:5432/testdb
          REDIS_URL: redis://localhost:6379
          CI: true

      - name: Upload coverage
        uses: codecov/codecov-action@v3
        with:
          fail_ci_if_error: true

    build:
      needs: test
      runs-on: ubuntu-latest
      if: github.ref == 'refs/heads/main'
      permissions:
        contents: read
        packages: write

      steps:
      - uses: actions/checkout@v4

      - name: Login to Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

    deploy:
      needs: build
      runs-on: ubuntu-latest
      if: github.ref == 'refs/heads/main'
      environment: production

      steps:
      - name: Deploy to server
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.DEPLOY_HOST }}
          username: ${{ secrets.DEPLOY_USER }}
          key: ${{ secrets.DEPLOY_KEY }}
          script: |
            cd /opt/myapp
            docker compose pull
            docker compose up -d
            docker image prune -f
  ```

  ### GitLab CI
  ```yaml
  # .gitlab-ci.yml
  stages:
    - test
    - build
    - deploy

  variables:
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: "/certs"

  test:
    stage: test
    image: node:20-alpine
    services:
      - postgres:16-alpine
      - redis:7-alpine
    variables:
      POSTGRES_DB: testdb
      POSTGRES_USER: test
      POSTGRES_PASSWORD: test
    script:
      - npm ci
      - npm run lint
      - npm test
    coverage: '/Lines\s*:\s*(\d+.\d+%)/'

  build:
    stage: build
    image: docker:24-dind
    services:
      - docker:24-dind
    script:
      - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
      - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .
      - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
      - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA $CI_REGISTRY_IMAGE:latest
      - docker push $CI_REGISTRY_IMAGE:latest
    only:
      - main

  deploy:
    stage: deploy
    image: alpine
    script:
      - apk add --no-cache openssh-client
      - mkdir -p ~/.ssh && ssh-keyscan $DEPLOY_HOST >> ~/.ssh/known_hosts
      - ssh $DEPLOY_USER@$DEPLOY_HOST "cd /opt/myapp && docker compose pull && docker compose up -d"
    only:
      - main
    environment:
      name: production
  ```

  ### Jenkins Pipeline
  ```groovy
  // Jenkinsfile
  pipeline {
      agent any

      environment {
          DOCKER_IMAGE = "myapp:${env.BUILD_NUMBER}"
      }

      stages {
          stage('Test') {
              steps {
                  sh 'npm ci && npm run lint && npm test'
              }
          }

          stage('Build') {
              steps {
                  sh "docker build -t ${DOCKER_IMAGE} ."
                  sh "docker tag ${DOCKER_IMAGE} myapp:latest"
              }
          }

          stage('Push') {
              steps {
                  sh 'docker login -u $DOCKER_USER -p $DOCKER_PASS registry.example.com'
                  sh "docker push ${DOCKER_IMAGE}"
              }
          }

          stage('Deploy') {
              steps {
                  sh 'ssh deploy@server "cd /opt/myapp && docker compose pull && docker compose up -d"'
              }
          }
      }

      post {
          success {
              slackSend(channel: '#deployments', message: "Build ${env.BUILD_NUMBER} succeeded ✅")
          }
          failure {
              slackSend(channel: '#alerts', message: "Build ${env.BUILD_NUMBER} failed ❌")
          }
      }
  }
  ```

  ### Deployment Strategies
  ```bash
  # Rolling (zero downtime)
  kubectl set image deployment/web-app app=myapp:2.0
  kubectl rollout status deployment/web-app

  # Blue-Green
  # Deploy to green, switch load balancer
  kubectl apply -f green-env.yml
  kubectl set image ingress/web green=myapp:2.0

  # Canary (gradual rollout)
  kubectl set image deployment/web-app app=myapp:2.0
  kubectl scale deployment/web-app --replicas=4  # 3 old + 1 new

  # Automated rollback on failure
  kubectl rollout undo deployment/web-app
  ```


entity_id: ent_20260526T211509115660_fee40623
type: memory
category: debian/docker-compose-deep
strength: moderate
metadata: "{\"source\": \"phase4_orchestration\"}"
created_at: 2026-05-26T21:15:09.115660
updated_at: 2026-05-26T21:15:09.115660
content:
  ## Docker Compose Advanced
  ### Complex Stack Example
  ```yaml
  # Full production stack
  version: '3.8'

  services:
    # Reverse proxy
    nginx:
      image: nginx:alpine
      ports:
        - "80:80"
        - "443:443"
      volumes:
        - ./nginx/conf.d:/etc/nginx/conf.d
        - ./nginx/certs:/etc/nginx/certs
        - certbot-data:/etc/letsencrypt
      depends_on:
        - web
        - api
      restart: always

    # Frontend
    web:
      build:
        context: ./frontend
        dockerfile: Dockerfile
        args:
          - VITE_API_URL=/api
      environment:
        - NODE_ENV=production
      restart: unless-stopped

    # Backend API
    api:
      build:
        context: ./backend
        target: production
      environment:
        - DATABASE_URL=postgresql://app:${DB_PASSWORD}@db:5432/appdb
        - REDIS_URL=redis://redis:6379
        - JWT_SECRET=${JWT_SECRET}
        - LOG_LEVEL=info
      depends_on:
        db:
          condition: service_healthy
        redis:
          condition: service_started
      deploy:
        resources:
          limits:
            cpus: '2.0'
            memory: 1G
      restart: unless-stopped
      healthcheck:
        test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
        interval: 30s
        timeout: 10s
        retries: 3

    # Database
    db:
      image: postgres:16-alpine
      environment:
        - POSTGRES_DB=appdb
        - POSTGRES_USER=app
        - POSTGRES_PASSWORD=${DB_PASSWORD}
      volumes:
        - pgdata:/var/lib/postgresql/data
        - ./db/init:/docker-entrypoint-initdb.d
      healthcheck:
        test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
        interval: 10s
        timeout: 5s
        retries: 5
      restart: always

    # Cache
    redis:
      image: redis:7-alpine
      command: redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru
      volumes:
        - redis-data:/data
      restart: always

    # Worker (background jobs)
    worker:
      build:
        context: ./backend
        target: production
      environment:
        - DATABASE_URL=postgresql://app:${DB_PASSWORD}@db:5432/appdb
        - REDIS_URL=redis://redis:6379
      depends_on:
        - db
        - redis
      command: ["node", "worker.js"]
      restart: unless-stopped

    # Backup service
    backup:
      image: prodrigestivill/postgres-backup-local:16
      environment:
        - POSTGRES_HOST=db
        - POSTGRES_DB=appdb
        - POSTGRES_USER=app
        - POSTGRES_PASSWORD=${DB_PASSWORD}
        - SCHEDULE="@daily"
        - BACKUP_DIR=/backups
      volumes:
        - backups:/backups
      restart: unless-stopped

    # Certbot (SSL)
    certbot:
      image: certbot/certbot
      volumes:
        - certbot-data:/etc/letsencrypt
        - ./certbot/conf:/etc/nginx/conf.d
      entrypoint: /bin/sh -c "
        certbot certonly --nginx
        -d ${DOMAIN}
        --email ${EMAIL}
        --agree-tos --non-interactive
        || true"

  volumes:
    pgdata:
    redis-data:
    backups:
    certbot-data:

  networks:
    default:
      name: app-network
  ```

  ### Multi-Environment
  ```yaml
  # docker-compose.override.yml (development)
  version: '3.8'

  services:
    web:
      environment:
        - NODE_ENV=development
      volumes:
        - ./frontend/src:/app/src
      command: npm run dev

    api:
      environment:
        - NODE_ENV=development
        - LOG_LEVEL=debug
      volumes:
        - ./backend/src:/app/src
      command: nodemon src/server.js

    db:
      ports:
        - "5432:5432"  # Only expose in dev
  ```

  ### Compose Commands
  ```bash
  # Start/stop
  docker compose up -d           # background
  docker compose up              # foreground with logs
  docker compose down            # stop + remove containers
  docker compose down -v         # also remove volumes
  docker compose down --rmi all  # remove images too

  # Scaling
  docker compose up -d --scale worker=3

  # Logs
  docker compose logs -f api
  docker compose logs --tail=100 api

  # Exec
  docker compose exec api bash
  docker compose exec db psql -U app appdb

  # Build
  docker compose build --no-cache
  docker compose build api

  # Pull updates
  docker compose pull
  docker compose up -d --force-recreate

  # Inspect
  docker compose ps
  docker compose top
  docker compose stats
  ```

  ### Production Checklist
  ```yaml
  # Always in production:
  # 1. Use specific image tags (not :latest)
  # 2. Set resource limits
  # 3. Use restart policies
  # 4. Health checks for dependencies
  # 5. External volumes for data
  # 6. .env file for secrets (gitignored)
  # 7. Logging driver configured
  # 8. Separate networks for isolation
  ```


entity_id: ent_20260526T211509333234_7f3556f6
type: memory
category: debian/nginx-haproxy
strength: moderate
metadata: "{\"source\": \"phase4_orchestration\"}"
created_at: 2026-05-26T21:15:09.333234
updated_at: 2026-05-26T21:15:09.333234
content:
  ## Nginx & HAProxy — Reverse Proxy & Load Balancing
  ### Nginx Configuration
  ```nginx
  # /etc/nginx/nginx.conf
  user www-data;
  worker_processes auto;
  worker_rlimit_nofile 65535;

  events {
      worker_connections 4096;
      multi_accept on;
      use epoll;
  }

  http {
      # Performance
      sendfile on;
      tcp_nopush on;
      tcp_nodelay on;
      keepalive_timeout 65;
      types_hash_max_size 2048;

      # Gzip
      gzip on;
      gzip_vary on;
      gzip_proxied any;
      gzip_comp_level 6;
      gzip_types text/plain text/css application/json application/javascript
                 text/xml application/xml application/xml+rss text/javascript
                 image/svg+xml;
      gzip_min_length 1000;

      # Security headers
      add_header X-Frame-Options "SAMEORIGIN" always;
      add_header X-Content-Type-Options "nosniff" always;
      add_header X-XSS-Protection "1; mode=block" always;

      # Rate limiting
      limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
      limit_conn_zone $binary_remote_addr zone=conn:10m;

      include /etc/nginx/conf.d/*.conf;
  }
  ```

  ### Server Block
  ```nginx
  # /etc/nginx/conf.d/app.conf
  upstream backend {
      server 127.0.0.1:3000;
      server 127.0.0.1:3001;
      server 127.0.0.1:3002;
      keepalive 32;
  }

  server {
      listen 80;
      server_name app.example.com;

      # Redirect HTTP to HTTPS
      return 301 https://$server_name$request_uri;
  }

  server {
      listen 443 ssl http2;
      server_name app.example.com;

      # SSL
      ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;
      ssl_protocols TLSv1.2 TLSv1.3;
      ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
      ssl_prefer_server_ciphers off;
      ssl_session_cache shared:SSL:10m;
      ssl_session_timeout 1d;

      # Rate limiting
      limit_req zone=api burst=20 nodelay;
      limit_conn conn 10;

      # Static files
      location /static/ {
          alias /var/www/app/static/;
          expires 30d;
          add_header Cache-Control "public, immutable";
      }

      # API proxy
      location /api/ {
          proxy_pass http://backend;
          proxy_http_version 1.1;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header Connection "";
          proxy_buffering off;

          # Timeouts
          proxy_connect_timeout 60s;
          proxy_send_timeout 60s;
          proxy_read_timeout 60s;
      }

      # WebSocket support
      location /ws/ {
          proxy_pass http://backend;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
          proxy_set_header Host $host;
          proxy_read_timeout 86400;
      }

      # Health check
      location /health {
          access_log off;
          return 200 "ok
  ";
          add_header Content-Type text/plain;
      }
  }
  ```

  ### Load Balancing Methods
  ```nginx
  # Round robin (default)
  upstream backend {
      server 10.0.1.1:8080;
      server 10.0.1.2:8080;
      server 10.0.1.3:8080;
  }

  # Least connections
  upstream backend {
      least_conn;
      server 10.0.1.1:8080;
      server 10.0.1.2:8080;
  }

  # IP hash (sticky sessions)
  upstream backend {
      ip_hash;
      server 10.0.1.1:8080;
      server 10.0.1.2:8080;
  }

  # Weighted
  upstream backend {
      server 10.0.1.1:8080 weight=5;
      server 10.0.1.2:8080 weight=3;
      server 10.0.1.3:8080 weight=2;
  }

  # With health checks
  upstream backend {
      server 10.0.1.1:8080 max_fails=3 fail_timeout=30s;
      server 10.0.1.2:8080 max_fails=3 fail_timeout=30s;
      server 10.0.1.3:8080 backup;  # only used when others fail
  }
  ```

  ### HAProxy Configuration
  ```ini
  # /etc/haproxy/haproxy.cfg
  global
      log /dev/log local0
      log /dev/log local1 notice
      chroot /var/lib/haproxy
      stats socket /run/haproxy/admin.sock mode 660 level admin
      stats timeout 30s
      user haproxy
      group haproxy
      daemon

      # SSL
      ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
      ssl-default-bind-options no-sslv3 no-tlsv10 no-tlsv11

      # Performance
      tune.ssl.default-dh-param 2048
      maxconn 4096

  defaults
      log global
      mode http
      option httplog
      option dontlognull
      timeout connect 5000
      timeout client 50000
      timeout server 50000
      errorfile 400 /etc/haproxy/errors/400.http
      errorfile 403 /etc/haproxy/errors/403.http
      errorfile 408 /etc/haproxy/errors/408.http
      errorfile 500 /etc/haproxy/errors/500.http
      errorfile 502 /etc/haproxy/errors/502.http
      errorfile 503 /etc/haproxy/errors/503.http
      errorfile 504 /etc/haproxy/errors/504.http

  # Stats page
  listen stats
      bind *:8404
      stats enable
      stats uri /stats
      stats refresh 10s
      stats auth admin:password
      stats admin if LOCALHOST

  # Frontend
  frontend http-in
      bind *:80
      bind *:443 ssl crt /etc/haproxy/certs/app.pem
      redirect scheme https if !{ ssl_fc }
      default_backend servers
      option forwardfor

  # Backend with health checks
  backend servers
      balance roundrobin
      option httpchk GET /health
      http-check expect status 200
      server web1 10.0.1.1:8080 check inter 5s fall 3 rise 2
      server web2 10.0.1.2:8080 check inter 5s fall 3 rise 2
      server web3 10.0.1.3:8080 check inter 5s fall 3 rise 2 backup

  # Application-specific backend
  backend api-servers
      balance leastconn
      option httpchk GET /api/health
      http-check expect status 200
      cookie SERVERID insert indirect nocache
      server api1 10.0.2.1:3000 check cookie api1
      server api2 10.0.2.2:3000 check cookie api2
      server api3 10.0.2.3:3000 check cookie api3
  ```

  ### Nginx Testing
  ```bash
  # Test config
  nginx -t

  # Reload without downtime
  systemctl reload nginx

  # Check active connections
  curl http://localhost/nginx_status

  # Access logs
  tail -f /var/log/nginx/access.log
  tail -f /var/log/nginx/error.log

  # Performance testing
  ab -n 1000 -c 50 http://app.example.com/
  wrk -t12 -c400 -d30s http://app.example.com/
  ```

  ### HAProxy Commands
  ```bash
  # Test config
  haproxy -c -f /etc/haproxy/haproxy.cfg

  # Reload
  systemctl reload haproxy

  # Add server dynamically
  echo "add server backend/web4 10.0.1.4:8080" \
    | socat stdio /run/haproxy/admin.sock

  # Check server status
  echo "show stat" | socat stdio /run/haproxy/admin.sock
  ```


entity_id: ent_20260526T212857832829_15862956
type: memory
category: debian/database-postgresql
strength: moderate
metadata: "{\"source\": \"phase5_gaps\"}"
created_at: 2026-05-26T21:28:57.832829
updated_at: 2026-05-26T21:28:57.832829
content:
  ## PostgreSQL Deep Dive
  ### Installation
  ```bash
  apt install -y postgresql postgresql-contrib

  # Verify
  systemctl status postgresql
  sudo -u postgres psql -c "SELECT version();"

  # Create database and user
  sudo -u postgres createdb mydb
  sudo -u postgres createuser --interactive
  # or SQL:
  sudo -u postgres psql -c "CREATE USER myuser WITH ENCRYPTED PASSWORD 'pass';"
  sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;"
  ```

  ### Configuration
  ```bash
  # /etc/postgresql/16/main/postgresql.conf
  listen_addresses = '*'
  port = 5432
  max_connections = 200
  shared_buffers = 4GB              # 25% of RAM
  effective_cache_size = 12GB       # 75% of RAM
  work_mem = 16MB                   # per-operation memory
  maintenance_work_mem = 1GB
  wal_buffers = 64MB
  checkpoint_completion_target = 0.9
  max_wal_size = 4GB
  min_wal_size = 1GB
  random_page_cost = 1.1            # SSD
  effective_io_concurrency = 200    # SSD

  # Logging
  log_min_duration_statement = 1000 # ms
  log_checkpoints = on
  log_connections = on
  log_disconnections = on
  log_lock_waits = on
  log_temp_files = 0

  # /etc/postgresql/16/main/pg_hba.conf
  # TYPE  DATABASE  USER  ADDRESS       METHOD
  host    all       all   10.0.0.0/8    scram-sha-256
  host    all       all   192.168.0.0/16 scram-sha-256
  local   all       all                     peer
  ```

  ### Replication (Streaming)
  ```bash
  # PRIMARY — postgresql.conf
  wal_level = replica
  max_wal_senders = 3
  wal_keep_size = 1GB
  hot_standby = on

  # Create replication user
  sudo -u postgres psql -c "CREATE ROLE replicator WITH REPLICATION LOGIN ENCRYPTED PASSWORD 'repl_pass';"

  # Add to pg_hba.conf
  host replication replicator 10.0.0.0/8 scram-sha-256

  # STANDBY
  # 1. Base backup from primary
  pg_basebackup -h primary-host -U replicator -D /var/lib/postgresql/16/main/standby -P -R

  # 2. Configure standby.signal
  touch /var/lib/postgresql/16/main/standby/standby.signal

  # 3. postgresql.conf on standby
  hot_standby = on
  primary_conninfo = 'host=primary-host port=5432 user=replicator password=repl_pass application_name=standby1'

  # 4. Start
  systemctl restart postgresql

  # Check replication status (on primary)
  SELECT client_addr, state, sent_lsn, write_lsn, flush_lsn, replay_lsn, sync_state
  FROM pg_stat_replication;
  ```

  ### Patroni (HA Orchestration)
  ```yaml
  # /etc/patroni/patroni.yml
  scope: postgresql-cluster
  namespace: /service/
  name: postgresql-1

  restapi:
    listen: 0.0.0.0:8008
    connect_address: 10.0.0.1:8008

  etcd3:
    hosts: etcd1:2379,etcd2:2379,etcd3:2379

  bootstrap:
    dcs:
      ttl: 30
      loop_wait: 10
      retry_timeout: 10
      maximum_lag_on_failover: 1048576
      postgresql:
        use_pg_rewind: true
        parameters:
          max_connections: 200
          shared_buffers: 4GB

    postgresql:
      parameters:
        wal_level: replica
        hot_standby: "on"
      initdb:
        - encoding: UTF8
        - data-checksums
      users:
        admin:
          password: admin_pass
          options: CREATEROLE CREATEDB

  postgresql:
    listen: 0.0.0.0:5432
    connect_address: 10.0.0.1:5432
    data_dir: /var/lib/postgresql/16/main
    pgpass: /var/lib/postgresql/.pgpass
    authentication:
      replication:
        username: replicator
        password: repl_pass
      superuser:
        username: postgres
    parameters:
      unix_socket_directories: '/var/run/postgresql'

  tags:
    nofailover: false
    noloadbalance: false
    clonefrom: true
    nosync: false
  ```

  ### Performance Tuning
  ```sql
  -- Find slow queries
  CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

  SELECT query, calls, total_exec_time, mean_exec_time, rows
  FROM pg_stat_statements
  ORDER BY mean_exec_time DESC
  LIMIT 10;

  -- Check table bloat
  SELECT schemaname, tablename, n_live_tup, n_dead_tup,
         last_vacuum, last_autovacuum, last_analyze, last_autoanalyze
  FROM pg_stat_user_tables
  ORDER BY n_dead_tup DESC;

  -- Index usage
  SELECT schemaname, relname, indexname, idx_scan, idx_tup_read, idx_tup_fetch
  FROM pg_stat_user_indexes
  ORDER BY idx_scan ASC;

  -- Locks
  SELECT blocked_locks.pid AS blocked_pid,
         blocking_locks.pid AS blocking_pid,
         blocked_activity.query AS blocked_query,
         blocking_activity.query AS blocking_query
  FROM pg_catalog.pg_locks blocked_locks
  JOIN pg_catalog.pg_locks blocking_locks
    ON blocking_locks.locktype = blocked_locks.locktype
    AND blocking_locks.pid != blocked_locks.pid
  JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
  JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid;
  ```

  ### Backup & Restore
  ```bash
  # pg_dump (single database)
  pg_dump -h localhost -U myuser -Fc mydb > backup.dump
  pg_restore -h localhost -U myuser -d mydb backup.dump

  # pg_dumpall (all databases, roles)
  pg_dumpall -U postgres > full_backup.sql
  psql -U postgres -f full_backup.sql

  # Continuous archiving
  # postgresql.conf
  archive_mode = on
  archive_command = 'cp %p /backups/wal/%f'
  archive_timeout = 60

  # pg_basebackup + WAL archiving for PITR
  pg_basebackup -h localhost -U replicator -D /backups/base -Ft -z -P
  # Restore to specific time:
  # 1. Copy base backup
  # 2. Set restore_command in postgresql.conf
  # 3. Create recovery.signal
  # 4. Set recovery_target_time
  ```

  ### Extensions
  ```sql
  -- Full-text search
  SELECT to_tsvector('english', 'The quick brown fox') @@ to_tsquery('quick & fox');

  -- PostGIS (spatial)
  CREATE EXTENSION postgis;

  -- UUID generation
  CREATE EXTENSION pgcrypto;
  SELECT gen_random_uuid();

  -- JSON operations
  SELECT data->>'name' FROM users WHERE data->>'role' = 'admin';
  ```


entity_id: ent_20260526T212858059498_4286e5b2
type: memory
category: debian/database-mysql
strength: moderate
metadata: "{\"source\": \"phase5_gaps\"}"
created_at: 2026-05-26T21:28:58.059498
updated_at: 2026-05-26T21:28:58.059498
content:
  ## MySQL/MariaDB Deep Dive
  ### Installation
  ```bash
  apt install -y mariadb-server mariadb-client

  # Secure install
  mysql_secure_installation
  # - Set root password
  # - Remove anonymous users
  # - Disallow root remote login
  # - Remove test database

  # Verify
  systemctl status mariadb
  mysql -u root -p -e "SELECT version();"
  ```

  ### Configuration
  ```ini
  # /etc/mysql/mariadb.conf.d/99-custom.cnf
  [mysqld]
  # Connection
  bind-address = 0.0.0.0
  port = 3306
  max_connections = 200
  max_connect_errors = 1000

  # InnoDB
  innodb_buffer_pool_size = 8G        # 70-80% of RAM for dedicated DB
  innodb_log_file_size = 1G
  innodb_flush_method = O_DIRECT
  innodb_flush_log_at_trx_commit = 1  # Full ACID
  innodb_file_per_table = 1
  innodb_io_capacity = 2000           # SSD
  innodb_io_capacity_max = 4000
  innodb_read_io_threads = 8
  innodb_write_io_threads = 8

  # Query cache (disabled in MySQL 8.0+)
  query_cache_type = 0
  query_cache_size = 0

  # Logging
  slow_query_log = 1
  slow_query_log_file = /var/log/mysql/slow.log
  long_query_time = 2
  log_error = /var/log/mysql/error.log

  # Binary logging (replication)
  server-id = 1
  log_bin = /var/log/mysql/mysql-bin
  binlog_format = ROW
  expire_logs_days = 7
  max_binlog_size = 100M
  ```

  ### Replication (Master-Slave)
  ```sql
  -- MASTER
  -- my.cnf: server-id=1, log_bin=mysql-bin, binlog_format=ROW
  GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'10.0.0.%' IDENTIFIED BY 'repl_pass';
  FLUSH PRIVILEGES;
  SHOW MASTER STATUS;
  -- Note file and position

  -- SLAVE
  -- my.cnf: server-id=2
  CHANGE MASTER TO
    MASTER_HOST='10.0.0.1',
    MASTER_USER='repl_user',
    MASTER_PASSWORD='repl_pass',
    MASTER_LOG_FILE='mysql-bin.000001',
    MASTER_LOG_POS=154;

  START SLAVE;
  SHOW SLAVE STATUS\G
  -- Check: Slave_IO_Running: Yes, Slave_SQL_Running: Yes
  ```

  ### Galera Cluster (Multi-Master)
  ```ini
  # /etc/mysql/mariadb.conf.d/99-galera.cnf
  [mysqld]
  # Galera settings
  wsrep_on = ON
  wsrep_provider = /usr/lib/galera/libgalera_smm.so
  wsrep_cluster_address = gcomm://10.0.0.1,10.0.0.2,10.0.0.3
  wsrep_cluster_name = mariadb-cluster
  wsrep_node_name = node1
  wsrep_node_address = 10.0.0.1
  wsrep_sst_method = mariabackup
  wsrep_sst_auth = sst_user:sst_pass
  binlog_format = ROW
  default_storage_engine = InnoDB
  innodb_autoinc_lock_mode = 2

  # Bootstrap first node
  galera_new_cluster
  systemctl start mariadb

  # Join other nodes
  systemctl start mariadb
  ```

  ### Performance
  ```sql
  -- Slow query analysis
  mysqldumpslow -s t -t 10 /var/log/mysql/slow.log

  -- Connection pool status
  SHOW STATUS LIKE 'Threads%';
  SHOW VARIABLES LIKE 'max_connections';

  -- Buffer pool hit rate
  SHOW STATUS LIKE 'Innodb_buffer_pool%';
  -- Hit rate = (1 - pool_reads/pool_read_requests) * 100

  -- Table stats
  SELECT table_schema, table_name, engine, table_rows,
         data_length, index_length, data_free
  FROM information_schema.tables
  WHERE table_schema NOT IN ('mysql','information_schema','performance_schema')
  ORDER BY (data_length + index_length) DESC;

  -- InnoDB status
  SHOW ENGINE INNODB STATUS\G

  -- Processlist
  SHOW FULL PROCESSLIST;
  KILL <process_id>;  -- kill long-running query
  ```

  ### Backup
  ```bash
  # mysqldump
  mysqldump -u root -p --all-databases --single-transaction --routines --triggers > full.sql

  # Single database
  mysqldump -u root -p --single-transaction mydb > mydb.sql

  # MariaBackup (physical, hot backup)
  apt install mariadb-backup
  mariabackup --backup --target-dir=/backups/db --user=root --password=pass
  mariabackup --prepare --target-dir=/backups/db
  mariabackup --copy-back --target-dir=/backups/db
  chown -R mysql:mysql /var/lib/mysql
  systemctl restart mariadb

  # xtrabackup (Percona)
  apt install percona-xtrabackup-80
  xtrabackup --backup --target-dir=/backups/db
  xtrabackup --prepare --target-dir=/backups/db
  xtrabackup --copy-back --target-dir=/backups/db
  ```

  ### Security
  ```sql
  -- Create limited user
  CREATE USER 'app_user'@'10.0.0.%' IDENTIFIED BY 'strong_pass';
  GRANT SELECT, INSERT, UPDATE, DELETE ON mydb.* TO 'app_user'@'10.0.0.%';
  FLUSH PRIVILEGES;

  -- Remove default users
  DELETE FROM mysql.user WHERE User='';
  DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost','127.0.0.1','::1');

  -- Enable TLS
  GRANT USAGE ON *.* TO 'app_user'@'10.0.0.%' REQUIRE SSL;
  ```


