# Engagement DB Tracker — Implementation Plan (Plan 2)
> **For agentic workers:** executed inline (ultracode). TDD where it pays: real DB-cycle tests.
**Goal:** SQLite-backed engagement tracker (`htb-newbox`/`creds`/`flags`/`findings`/`note`/`database`) at `~/.pentest/engagements.db`, lazy-initialized, SQL-injection-safe, with backup/restore/export and an active-target file the prompt + tmux read.
**Architecture:** `config/database.zsh` defines functions only (no DB I/O at shell startup — perf). First command calls `_pdb_init` which creates `~/.pentest` (0700), runs `scripts/db-init.sql`, chmods the db 0600. Active target persisted to `~/.pentest/.active` (`name|ip`) + exported `$PENTEST_TARGET`/`$PENTEST_TARGET_IP`. All string inputs escaped (`'` → `''`).
**Tech Stack:** zsh, sqlite3, tar.
---
## File structure
- `config/database.zsh` — all tracker functions + lazy init + active-target helpers.
- `scripts/db-init.sql` — schema (idempotent `CREATE TABLE IF NOT EXISTS`).
- `scripts/db-backup.sh` — cron-able tar.gz of `~/.pentest`, prunes old.
- `scripts/tests/db.test.zsh` — full lifecycle test against a temp `PENTEST_DIR`.
`.zshrc` already sources `config/database.zsh` if present (Plan 1 orchestrator).
## Env contract (testability)
- `PENTEST_DIR` (default `$HOME/.pentest`), `PENTEST_DB` (default `$PENTEST_DIR/engagements.db`).
Tests override `PENTEST_DIR` to a tmpdir — never touch real loot.
## Commands
- `htb-newbox <name> <ip>` — insert target (UNIQUE name; reuse if exists), make box dir tree under `${HTB_BASE:-$HOME/htb}/<name>/{nmap,loot,exploits,www}`, set active.
- `htb-list` — table of targets.
- `htb-select <name>` — set active (file + env). Errors if unknown.
- `creds add <user> <pass> [service] [notes]` / `creds list` — active target; first-add prints plaintext-loot warning once (`~/.pentest/.warned`).
- `flags add <value> [user|root]` (default user) / `flags list`.
- `findings add <title> <severity> <description> [evidence]` / `findings list`.
- `note add <text...>` / `note list`.
- `database show|backup [name]|restore <file>|export|delete`.
- `backup` → `~/.pentest/backups/<name|ts>.tar.gz`. `export` → markdown to `~/.pentest/reports/`.
- `delete` → typed `DELETE` confirm + auto-backup first.
## Schema (scripts/db-init.sql)
targets / credentials / flags(user|root) / findings / notes — FKs `ON DELETE CASCADE`, `PRAGMA foreign_keys=ON` per connection. (full DDL in the file)
## Tests (lifecycle, temp DIR)
newbox×2 → list shows 2 → select → creds add×2 + list count 2 → flags add user+root → findings add → note add → export writes md containing creds → backup writes tar.gz → delete (piped `DELETE`) empties targets but backup exists → injection test: name with `'` doesn't corrupt/inject.
## Security
db 0600, dir 0700, gitignored, escape all inputs, warn on first cred, auto-backup before delete.