From 475c7b097b19d36b7f0846618e7773f2efd7d49f Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 5 Apr 2026 13:11:54 -0400 Subject: [PATCH 01/11] docs(specs): camera stream simulator design Dev-only tooling to loop phone-recorded mp4s as local RTSP streams (MediaMTX + ffmpeg) so the real camera pipeline can be exercised without physical cameras. Co-Authored-By: Claude Opus 4.6 (1M context) --- ...26-04-05-camera-stream-simulator-design.md | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-05-camera-stream-simulator-design.md diff --git a/docs/superpowers/specs/2026-04-05-camera-stream-simulator-design.md b/docs/superpowers/specs/2026-04-05-camera-stream-simulator-design.md new file mode 100644 index 0000000..81be523 --- /dev/null +++ b/docs/superpowers/specs/2026-04-05-camera-stream-simulator-design.md @@ -0,0 +1,164 @@ +# Camera Stream Simulator — Design + +**Status:** Approved +**Date:** 2026-04-05 +**Scope:** Development tooling only. Not shipped to operators. + +## Purpose + +Loop phone-recorded video files as local RTSP streams so Vigilar's real camera +pipeline (OpenCV capture, motion detection, HLS, recording, reconnect logic) +can be exercised end-to-end without physical cameras. The operator records +3–5 minutes of footage from each angle on a phone, drops the files into a +`videos/` directory, and runs a single script that serves them as +`rtsp://127.0.0.1:8554/`. + +Primary use case: manual dev testing with 4–5 real clips. Secondary use case: +stress testing with up to 32 distinct clips. + +## Non-Goals + +- Not a production feature. Never invoked in deployed installs. +- Not a pytest fixture. Manual workflow only. +- No per-stream jitter, audio, non-mp4 inputs, or CLI flags. +- No Python rewrite or `vigilar sim` subcommand. + +## Architecture + +One bash script, one helper binary (MediaMTX), one ffmpeg process per stream. + +``` +scripts/sim_cameras.sh + │ + ├── starts: mediamtx (127.0.0.1:8554) ← single static Go binary + ├── reads: config/vigilar.toml ← discovers camera ids + ├── for each [[cameras]] block: + │ expects videos/.mp4 + │ spawns: ffmpeg -stream_loop -1 -re -i videos/.mp4 \ + │ -c copy -f rtsp rtsp://127.0.0.1:8554/ + ├── writes: config/vigilar.sim.toml ← copy of real config, + │ rtsp_urls rewritten + └── foreground; Ctrl-C kills all children +``` + +Operator workflow: + +``` +$ ./scripts/sim_cameras.sh + → serving 5 streams on 127.0.0.1:8554 + → wrote config/vigilar.sim.toml +$ vigilar start --config config/vigilar.sim.toml # in another terminal +``` + +Strict 1:1 mapping — each simulated stream corresponds to exactly one video +file, named after the camera id in `vigilar.toml`. No file reuse, no cycling. + +## Components + +### `scripts/sim_cameras.sh` + +Bash, no Python dependencies. Responsibilities: + +1. Resolve paths: `$REPO/config/vigilar.toml`, `$REPO/videos/`, + `$REPO/.sim/mediamtx`, `$REPO/.sim/logs/`. +2. Check prerequisites: `ffmpeg` on PATH, `mediamtx` binary present, + `videos/` directory exists. +3. Parse camera ids from `vigilar.toml` by grepping `^id = "..."` lines + inside `[[cameras]]` blocks. No TOML parser — tolerable because the + config format is stable and this is dev tooling. +4. Verify `videos/.mp4` exists for every camera id. List **all** + missing files in one error message, then exit 1. +5. Launch `mediamtx` in the background, writing its log to + `.sim/logs/mediamtx.log`. Wait ~500ms, then verify the RTSP port + (8554) is listening (`ss -lnt` or `/dev/tcp`). +6. Launch one ffmpeg process per camera, backgrounded, with stdout/stderr + redirected to `.sim/logs/.log`. Track PIDs in a bash array. +7. Generate `config/vigilar.sim.toml`: copy the real TOML, rewrite each + `rtsp_url = "..."` line to `rtsp://127.0.0.1:8554/` using `sed` + scoped per camera block. +8. Print a summary: each served URL, the sim config path, and + "Press Ctrl-C to stop". +9. Install a `trap` on EXIT/INT/TERM that kills mediamtx and every ffmpeg + child PID, then removes `.sim/`. Idempotent. +10. `wait` on child PIDs so the script blocks until Ctrl-C. + +### `scripts/download_mediamtx.sh` + +Parallel to the existing `scripts/download_model.sh`. Downloads the +MediaMTX static binary for the current architecture from the official +GitHub release into `.sim/mediamtx`, verifies it is executable, and exits. +Run once per machine. + +### `videos/` (gitignored) + +Operator drops `.mp4` files matching camera ids in +`config/vigilar.toml`. Format is mp4 only; other extensions are rejected. + +### `.sim/` (gitignored) + +Working directory, recreated each run: +- `.sim/mediamtx` — the static binary (installed by `download_mediamtx.sh`) +- `.sim/logs/mediamtx.log` +- `.sim/logs/.log` + +### `config/vigilar.sim.toml` (gitignored) + +Generated artifact. Overwritten on every run. Never hand-edited. The real +`config/vigilar.toml` is read-only from the simulator's perspective. + +### MediaMTX + +Single static Go binary. Default configuration is sufficient — listens on +RTSP port 8554, accepts `rtsp://127.0.0.1:8554/` publishes from +ffmpeg. No custom yaml required. + +## Error Handling + +Fail loud and early. No silent fallbacks. + +| Condition | Behavior | +|---|---| +| `ffmpeg` not on PATH | Print install hint, exit 1 | +| `.sim/mediamtx` missing | Print "run scripts/download_mediamtx.sh", exit 1 | +| `videos/` missing or any `videos/.mp4` missing | List **all** missing files, exit 1 | +| MediaMTX fails to bind 8554 | Dump `.sim/logs/mediamtx.log` tail, exit 1 | +| ffmpeg child dies mid-run | Log to stderr, leave others running. Vigilar's reconnect logic handles the gap — this is a feature, not a bug. | +| Ctrl-C / script death | `trap` kills mediamtx + all ffmpeg PIDs, removes `.sim/` | + +## Acceptance Criteria + +Manual verification — this is dev tooling, not production code. + +1. Drop 5 mp4s matching camera ids into `videos/`, run + `./scripts/sim_cameras.sh`. 5 URLs print. +2. `ffprobe rtsp://127.0.0.1:8554/` succeeds for each stream. +3. In another terminal: + `vigilar start --config config/vigilar.sim.toml`. The web UI shows + 5 camera tiles with live HLS. Waving at phone footage triggers motion + events in the event log. +4. Kill one ffmpeg process manually. Vigilar marks that camera as + disconnected; reconnect loop engages. Restart the same ffmpeg + invocation → stream recovers in the UI. +5. Ctrl-C the sim script. `pgrep ffmpeg` and `pgrep mediamtx` both empty. + `.sim/` removed. +6. Scale test: populate 32 dummy mp4s matching 32 camera blocks. Script + starts cleanly; CPU remains within reason (subjective; no hard target). + +### Automated Check + +One light test: `tests/unit/test_sim_script.py` runs +`bash -n scripts/sim_cameras.sh` (syntax check) and, if `shellcheck` is +available, runs it as well. No integration tests — the simulator exists to +support manual testing. + +## File Inventory + +New files: +- `scripts/sim_cameras.sh` +- `scripts/download_mediamtx.sh` +- `tests/unit/test_sim_script.py` + +Modified files: +- `.gitignore` — add `videos/`, `.sim/`, `config/vigilar.sim.toml` + +No changes to `vigilar/` package code. The simulator is fully external. -- 2.49.1 From 3a6a79bf680cca797e80fd6869769ad8895541be Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 5 Apr 2026 13:16:22 -0400 Subject: [PATCH 02/11] docs(plans): camera stream simulator implementation plan Task-by-task plan for the dev-only RTSP simulator: gitignore entries, MediaMTX downloader, syntax-check test guard, the sim script itself, and a human acceptance walk-through. Co-Authored-By: Claude Opus 4.6 (1M context) --- .../2026-04-05-camera-stream-simulator.md | 458 ++++++++++++++++++ 1 file changed, 458 insertions(+) create mode 100644 docs/superpowers/plans/2026-04-05-camera-stream-simulator.md diff --git a/docs/superpowers/plans/2026-04-05-camera-stream-simulator.md b/docs/superpowers/plans/2026-04-05-camera-stream-simulator.md new file mode 100644 index 0000000..35b2897 --- /dev/null +++ b/docs/superpowers/plans/2026-04-05-camera-stream-simulator.md @@ -0,0 +1,458 @@ +# Camera Stream Simulator Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add dev tooling that loops phone-recorded mp4 files as local RTSP streams so Vigilar's real camera pipeline can run end-to-end without physical cameras. + +**Architecture:** One bash script (`scripts/sim_cameras.sh`) starts MediaMTX on `127.0.0.1:8554` and spawns one `ffmpeg -stream_loop -1 -re` per camera defined in `config/vigilar.toml`, publishing each video as `rtsp://127.0.0.1:8554/`. A generated `config/vigilar.sim.toml` rewrites camera URLs to the local endpoints. A second script downloads the MediaMTX static binary on demand. The real config is never mutated. + +**Tech Stack:** bash, ffmpeg, MediaMTX (static Go binary), pytest (for the syntax-check guard). + +**Spec:** `docs/superpowers/specs/2026-04-05-camera-stream-simulator-design.md` + +--- + +## File Inventory + +**Create:** +- `scripts/sim_cameras.sh` — main simulator script +- `scripts/download_mediamtx.sh` — one-time MediaMTX binary installer +- `tests/unit/test_sim_script.py` — syntax check + optional shellcheck + +**Modify:** +- `.gitignore` — add `videos/`, `.sim/`, `config/vigilar.sim.toml` + +**Not touched:** Any file under `vigilar/`. The simulator is fully external to the package. + +--- + +## Task 1: .gitignore entries + +**Files:** +- Modify: `.gitignore` + +- [ ] **Step 1: Append simulator entries** + +Append to `.gitignore` (before the final "WireGuard keys" block or at the very end — order doesn't matter): + +``` +# Camera stream simulator (dev tooling) +videos/ +.sim/ +config/vigilar.sim.toml +``` + +- [ ] **Step 2: Verify** + +Run: `git check-ignore -v videos/ .sim/ config/vigilar.sim.toml` +Expected: each path prints a match against the new lines. + +- [ ] **Step 3: Commit** + +```bash +git add .gitignore +git commit -m "chore(gitignore): ignore camera simulator working files" +``` + +--- + +## Task 2: MediaMTX downloader + +**Files:** +- Create: `scripts/download_mediamtx.sh` + +This script is a one-time installer. No test — it hits the network. Verified manually. + +- [ ] **Step 1: Create the script** + +Write `scripts/download_mediamtx.sh`: + +```bash +#!/usr/bin/env bash +# Download the MediaMTX static binary used by scripts/sim_cameras.sh. +# One-time setup. Re-run to upgrade. +set -euo pipefail + +VERSION="${MEDIAMTX_VERSION:-1.9.3}" +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DEST_DIR="${REPO_ROOT}/.sim" +DEST="${DEST_DIR}/mediamtx" + +case "$(uname -s)_$(uname -m)" in + Linux_x86_64) ASSET="mediamtx_v${VERSION}_linux_amd64.tar.gz" ;; + Linux_aarch64) ASSET="mediamtx_v${VERSION}_linux_arm64v8.tar.gz" ;; + Darwin_x86_64) ASSET="mediamtx_v${VERSION}_darwin_amd64.tar.gz" ;; + Darwin_arm64) ASSET="mediamtx_v${VERSION}_darwin_arm64.tar.gz" ;; + *) + echo "Unsupported platform: $(uname -s) $(uname -m)" >&2 + exit 1 + ;; +esac + +URL="https://github.com/bluenviron/mediamtx/releases/download/v${VERSION}/${ASSET}" + +mkdir -p "${DEST_DIR}" +TMP="$(mktemp -d)" +trap 'rm -rf "${TMP}"' EXIT + +echo "Downloading ${ASSET}..." +curl -fsSL "${URL}" -o "${TMP}/mediamtx.tar.gz" + +echo "Extracting..." +tar -xzf "${TMP}/mediamtx.tar.gz" -C "${TMP}" + +mv "${TMP}/mediamtx" "${DEST}" +chmod +x "${DEST}" + +echo "Installed: ${DEST}" +"${DEST}" --version || true +``` + +- [ ] **Step 2: Make executable** + +```bash +chmod +x scripts/download_mediamtx.sh +``` + +- [ ] **Step 3: Syntax check** + +Run: `bash -n scripts/download_mediamtx.sh` +Expected: no output, exit 0. + +- [ ] **Step 4: Commit** + +```bash +git add scripts/download_mediamtx.sh +git commit -m "feat(sim): add MediaMTX binary downloader" +``` + +--- + +## Task 3: Syntax-check test (TDD guard) + +**Files:** +- Create: `tests/unit/test_sim_script.py` + +This test guards both shell scripts against syntax regressions. It runs `bash -n` (always) and `shellcheck` (if installed). Written before `sim_cameras.sh` exists — it must fail initially, then pass once Task 4 creates the file. + +- [ ] **Step 1: Write the failing test** + +Create `tests/unit/test_sim_script.py`: + +```python +"""Guard shell scripts in scripts/ against syntax regressions.""" + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPTS = [ + REPO_ROOT / "scripts" / "sim_cameras.sh", + REPO_ROOT / "scripts" / "download_mediamtx.sh", +] + + +@pytest.mark.parametrize("script", SCRIPTS, ids=lambda p: p.name) +def test_script_exists(script: Path) -> None: + assert script.is_file(), f"missing script: {script}" + + +@pytest.mark.parametrize("script", SCRIPTS, ids=lambda p: p.name) +def test_bash_syntax(script: Path) -> None: + result = subprocess.run( + ["bash", "-n", str(script)], + capture_output=True, + text=True, + ) + assert result.returncode == 0, f"bash -n failed:\n{result.stderr}" + + +@pytest.mark.parametrize("script", SCRIPTS, ids=lambda p: p.name) +def test_shellcheck(script: Path) -> None: + if shutil.which("shellcheck") is None: + pytest.skip("shellcheck not installed") + result = subprocess.run( + ["shellcheck", "--severity=warning", str(script)], + capture_output=True, + text=True, + ) + assert result.returncode == 0, f"shellcheck failed:\n{result.stdout}\n{result.stderr}" +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/unit/test_sim_script.py -v` +Expected: `test_script_exists[sim_cameras.sh]` and `test_bash_syntax[sim_cameras.sh]` FAIL (file does not yet exist). Tests for `download_mediamtx.sh` pass. + +- [ ] **Step 3: Commit the failing test** + +```bash +git add tests/unit/test_sim_script.py +git commit -m "test(sim): guard simulator shell scripts with bash -n + shellcheck" +``` + +Note: committing a red test is intentional here — Task 4 makes it green. + +--- + +## Task 4: sim_cameras.sh — the simulator itself + +**Files:** +- Create: `scripts/sim_cameras.sh` + +This is the main deliverable. Written in one pass because the script is tightly coupled (trap cleanup, PID tracking, prereq checks all reference each other). After writing, the Task 3 tests go green. + +- [ ] **Step 1: Write the script** + +Create `scripts/sim_cameras.sh`: + +```bash +#!/usr/bin/env bash +# Simulate RTSP cameras by looping mp4 files through MediaMTX + ffmpeg. +# +# Usage: ./scripts/sim_cameras.sh +# +# Reads camera ids from config/vigilar.toml, expects videos/.mp4 for each, +# starts MediaMTX on 127.0.0.1:8554, spawns one ffmpeg per camera, and writes +# config/vigilar.sim.toml with rtsp_urls rewritten to the local endpoints. +# Ctrl-C tears everything down. +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +REAL_CONFIG="${REPO_ROOT}/config/vigilar.toml" +SIM_CONFIG="${REPO_ROOT}/config/vigilar.sim.toml" +VIDEOS_DIR="${REPO_ROOT}/videos" +SIM_DIR="${REPO_ROOT}/.sim" +LOG_DIR="${SIM_DIR}/logs" +MEDIAMTX_BIN="${SIM_DIR}/mediamtx" +RTSP_HOST="127.0.0.1" +RTSP_PORT="8554" + +MEDIAMTX_PID="" +FFMPEG_PIDS=() + +cleanup() { + local pid + for pid in "${FFMPEG_PIDS[@]}"; do + if [[ -n "${pid}" ]] && kill -0 "${pid}" 2>/dev/null; then + kill "${pid}" 2>/dev/null || true + fi + done + if [[ -n "${MEDIAMTX_PID}" ]] && kill -0 "${MEDIAMTX_PID}" 2>/dev/null; then + kill "${MEDIAMTX_PID}" 2>/dev/null || true + fi + # Give children a moment to exit, then force + sleep 0.3 + for pid in "${FFMPEG_PIDS[@]}" "${MEDIAMTX_PID}"; do + if [[ -n "${pid}" ]] && kill -0 "${pid}" 2>/dev/null; then + kill -9 "${pid}" 2>/dev/null || true + fi + done + rm -rf "${SIM_DIR:?}/logs" +} +trap cleanup EXIT INT TERM + +die() { echo "error: $*" >&2; exit 1; } + +# --- prereq checks --------------------------------------------------------- + +command -v ffmpeg >/dev/null 2>&1 || die "ffmpeg not found on PATH. Install it and retry." +[[ -x "${MEDIAMTX_BIN}" ]] || die "MediaMTX binary not found at ${MEDIAMTX_BIN}. Run: scripts/download_mediamtx.sh" +[[ -f "${REAL_CONFIG}" ]] || die "config file not found: ${REAL_CONFIG}" +[[ -d "${VIDEOS_DIR}" ]] || die "videos directory not found: ${VIDEOS_DIR} (create it and drop .mp4 files inside)" + +# --- parse camera ids from vigilar.toml ------------------------------------ +# Grab every `id = "..."` line that sits inside a [[cameras]] block. +# Simple state machine in awk — no TOML parser needed. + +mapfile -t CAMERA_IDS < <(awk ' + /^\[\[cameras\]\]/ { in_cams = 1; next } + /^\[/ && !/^\[\[cameras\]\]/ { in_cams = 0 } + in_cams && /^[[:space:]]*id[[:space:]]*=/ { + match($0, /"([^"]+)"/, m) + if (m[1] != "") print m[1] + } +' "${REAL_CONFIG}") + +[[ ${#CAMERA_IDS[@]} -gt 0 ]] || die "no [[cameras]] blocks with an id field found in ${REAL_CONFIG}" + +# --- verify every camera has a matching video ----------------------------- + +MISSING=() +for id in "${CAMERA_IDS[@]}"; do + [[ -f "${VIDEOS_DIR}/${id}.mp4" ]] || MISSING+=("${VIDEOS_DIR}/${id}.mp4") +done +if [[ ${#MISSING[@]} -gt 0 ]]; then + echo "error: missing video files for cameras:" >&2 + for f in "${MISSING[@]}"; do echo " - ${f}" >&2; done + exit 1 +fi + +# --- start MediaMTX -------------------------------------------------------- + +mkdir -p "${LOG_DIR}" +echo "Starting MediaMTX on ${RTSP_HOST}:${RTSP_PORT}..." +"${MEDIAMTX_BIN}" >"${LOG_DIR}/mediamtx.log" 2>&1 & +MEDIAMTX_PID=$! + +# Wait for the RTSP port to be listening (max ~3s) +for _ in $(seq 1 30); do + if (exec 3<>"/dev/tcp/${RTSP_HOST}/${RTSP_PORT}") 2>/dev/null; then + exec 3<&- 3>&- + break + fi + sleep 0.1 +done +if ! (exec 3<>"/dev/tcp/${RTSP_HOST}/${RTSP_PORT}") 2>/dev/null; then + echo "MediaMTX failed to bind ${RTSP_HOST}:${RTSP_PORT}. Log tail:" >&2 + tail -n 20 "${LOG_DIR}/mediamtx.log" >&2 || true + exit 1 +fi +exec 3<&- 3>&- 2>/dev/null || true + +# --- spawn one ffmpeg per camera ------------------------------------------- + +for id in "${CAMERA_IDS[@]}"; do + video="${VIDEOS_DIR}/${id}.mp4" + url="rtsp://${RTSP_HOST}:${RTSP_PORT}/${id}" + echo "Publishing ${video} -> ${url}" + ffmpeg -nostdin -loglevel warning \ + -stream_loop -1 -re -i "${video}" \ + -c copy -f rtsp "${url}" \ + >"${LOG_DIR}/${id}.log" 2>&1 & + FFMPEG_PIDS+=($!) +done + +# --- write the sim config -------------------------------------------------- +# Copy vigilar.toml, rewrite each `rtsp_url = "..."` line to point at the +# local MediaMTX endpoint for that camera. We rely on `id` preceding +# `rtsp_url` within each [[cameras]] block (the standing convention in +# config/vigilar.toml). + +awk -v host="${RTSP_HOST}" -v port="${RTSP_PORT}" ' + /^\[\[cameras\]\]/ { in_cams = 1; current_id = ""; print; next } + /^\[/ && !/^\[\[cameras\]\]/ { in_cams = 0; print; next } + in_cams && /^[[:space:]]*id[[:space:]]*=/ { + match($0, /"([^"]+)"/, m) + current_id = m[1] + print + next + } + in_cams && /^[[:space:]]*rtsp_url[[:space:]]*=/ && current_id != "" { + printf "rtsp_url = \"rtsp://%s:%s/%s\"\n", host, port, current_id + next + } + { print } +' "${REAL_CONFIG}" > "${SIM_CONFIG}" + +# --- summary --------------------------------------------------------------- + +echo +echo "Simulator running. ${#CAMERA_IDS[@]} stream(s):" +for id in "${CAMERA_IDS[@]}"; do + echo " rtsp://${RTSP_HOST}:${RTSP_PORT}/${id}" +done +echo +echo "Sim config written to: ${SIM_CONFIG}" +echo "Start Vigilar in another terminal:" +echo " vigilar start --config ${SIM_CONFIG#${REPO_ROOT}/}" +echo +echo "Press Ctrl-C to stop." + +wait +``` + +- [ ] **Step 2: Make executable** + +```bash +chmod +x scripts/sim_cameras.sh +``` + +- [ ] **Step 3: Run the Task 3 tests, expect green** + +Run: `pytest tests/unit/test_sim_script.py -v` +Expected: all non-skipped tests PASS. If `shellcheck` is installed, those tests also pass; if not, they skip. + +If `shellcheck` reports real issues, fix them in the script and re-run. (Common ones: unquoted variables, `[[ ]]` vs `[ ]`, array expansion.) + +- [ ] **Step 4: Manual smoke test — prereq errors** + +Run: `./scripts/sim_cameras.sh` (with no `videos/` directory present) +Expected: exits non-zero with a clear "videos directory not found" message and does not leave any mediamtx or ffmpeg processes running (`pgrep mediamtx; pgrep -f "ffmpeg.*stream_loop"` both empty). + +- [ ] **Step 5: Manual smoke test — happy path** + +Prereqs: run `./scripts/download_mediamtx.sh` once. Then create `videos/` and drop one `.mp4` matching a camera id from `config/vigilar.toml`. (Any short mp4 works — even a few seconds of test footage.) If only one video is ready, temporarily comment out the other `[[cameras]]` blocks in a scratch copy, or add placeholder mp4s for each. + +Run: `./scripts/sim_cameras.sh` +Expected: + - Prints "Publishing ..." for each camera + - Prints "Simulator running. N stream(s):" with URLs + - `ffprobe rtsp://127.0.0.1:8554/` in another terminal returns stream info + - `config/vigilar.sim.toml` exists and every `rtsp_url` in it points at `rtsp://127.0.0.1:8554/...` + +Ctrl-C, then verify cleanup: `pgrep mediamtx` and `pgrep -f "ffmpeg.*stream_loop"` are both empty. + +- [ ] **Step 6: Commit** + +```bash +git add scripts/sim_cameras.sh +git commit -m "feat(sim): add camera stream simulator script" +``` + +--- + +## Task 5: End-to-end verification with Vigilar + +No code changes. This is the acceptance checkpoint from the spec. Skip if you're running the plan in a subagent that can't launch Vigilar; in that case, mark this task complete only after a human runs it. + +- [ ] **Step 1: Start the simulator** + +```bash +./scripts/sim_cameras.sh +``` + +Leave it running in its own terminal. + +- [ ] **Step 2: Start Vigilar against the sim config** + +In a second terminal: + +```bash +vigilar start --config config/vigilar.sim.toml +``` + +- [ ] **Step 3: Verify in the web UI** + +Open the Vigilar web UI. Expected: + - Every simulated camera appears as a tile with live HLS playback. + - Motion in the source footage produces motion events in the event log. + +- [ ] **Step 4: Verify reconnect path** + +Find one ffmpeg PID from the simulator's terminal (or `pgrep -f "ffmpeg.*stream_loop"`) and `kill` it. Expected: + - Vigilar marks that camera disconnected. + - Reconnect loop retries periodically (check logs). + - Re-running `./scripts/sim_cameras.sh` (after Ctrl-C'ing the current one) restores all streams. + +- [ ] **Step 5: Verify clean shutdown** + +Ctrl-C the simulator. Run `pgrep mediamtx` and `pgrep -f "ffmpeg.*stream_loop"` — both empty. `.sim/logs/` is gone (the binary at `.sim/mediamtx` stays — it's the installed artifact). + +- [ ] **Step 6: No commit** + +Task 5 is verification only. If any step fails, return to Task 4 and fix. + +--- + +## Done criteria + +- All 5 tasks checked off. +- `pytest tests/unit/test_sim_script.py -v` is green. +- A human has completed the Task 5 acceptance walk-through at least once. +- `git status` is clean; nothing from `.sim/`, `videos/`, or `config/vigilar.sim.toml` is tracked. -- 2.49.1 From b3a79580f452d93470e1798a7366826f913c632b Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 5 Apr 2026 13:17:34 -0400 Subject: [PATCH 03/11] chore(gitignore): ignore camera simulator working files Co-Authored-By: Claude Opus 4.6 (1M context) --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index f027e93..3324a4f 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,8 @@ Thumbs.db # WireGuard keys (generated per-host) remote/wireguard/*.key + +# Camera stream simulator (dev tooling) +videos/ +.sim/ +config/vigilar.sim.toml -- 2.49.1 From 4c0e62175888920c66f66d1d56651aabf2ddc1a2 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 5 Apr 2026 13:18:51 -0400 Subject: [PATCH 04/11] feat(sim): add MediaMTX binary downloader Co-Authored-By: Claude Opus 4.6 (1M context) --- scripts/download_mediamtx.sh | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100755 scripts/download_mediamtx.sh diff --git a/scripts/download_mediamtx.sh b/scripts/download_mediamtx.sh new file mode 100755 index 0000000..16d0dc2 --- /dev/null +++ b/scripts/download_mediamtx.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Download the MediaMTX static binary used by scripts/sim_cameras.sh. +# One-time setup. Re-run to upgrade. +set -euo pipefail + +VERSION="${MEDIAMTX_VERSION:-1.9.3}" +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DEST_DIR="${REPO_ROOT}/.sim" +DEST="${DEST_DIR}/mediamtx" + +case "$(uname -s)_$(uname -m)" in + Linux_x86_64) ASSET="mediamtx_v${VERSION}_linux_amd64.tar.gz" ;; + Linux_aarch64) ASSET="mediamtx_v${VERSION}_linux_arm64v8.tar.gz" ;; + Darwin_x86_64) ASSET="mediamtx_v${VERSION}_darwin_amd64.tar.gz" ;; + Darwin_arm64) ASSET="mediamtx_v${VERSION}_darwin_arm64.tar.gz" ;; + *) + echo "Unsupported platform: $(uname -s) $(uname -m)" >&2 + exit 1 + ;; +esac + +URL="https://github.com/bluenviron/mediamtx/releases/download/v${VERSION}/${ASSET}" + +mkdir -p "${DEST_DIR}" +TMP="$(mktemp -d)" +trap 'rm -rf "${TMP}"' EXIT + +echo "Downloading ${ASSET}..." +curl -fsSL "${URL}" -o "${TMP}/mediamtx.tar.gz" + +echo "Extracting..." +tar -xzf "${TMP}/mediamtx.tar.gz" -C "${TMP}" + +mv "${TMP}/mediamtx" "${DEST}" +chmod +x "${DEST}" + +echo "Installed: ${DEST}" +"${DEST}" --version || true -- 2.49.1 From 276bbf7ab27578ea710d1b79450140322608bfce Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 5 Apr 2026 13:21:04 -0400 Subject: [PATCH 05/11] test(sim): guard simulator shell scripts with bash -n + shellcheck Co-Authored-By: Claude Opus 4.6 (1M context) --- tests/unit/test_sim_script.py | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 tests/unit/test_sim_script.py diff --git a/tests/unit/test_sim_script.py b/tests/unit/test_sim_script.py new file mode 100644 index 0000000..07994dd --- /dev/null +++ b/tests/unit/test_sim_script.py @@ -0,0 +1,42 @@ +"""Guard shell scripts in scripts/ against syntax regressions.""" + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPTS = [ + REPO_ROOT / "scripts" / "sim_cameras.sh", + REPO_ROOT / "scripts" / "download_mediamtx.sh", +] + + +@pytest.mark.parametrize("script", SCRIPTS, ids=lambda p: p.name) +def test_script_exists(script: Path) -> None: + assert script.is_file(), f"missing script: {script}" + + +@pytest.mark.parametrize("script", SCRIPTS, ids=lambda p: p.name) +def test_bash_syntax(script: Path) -> None: + result = subprocess.run( + ["bash", "-n", str(script)], + capture_output=True, + text=True, + ) + assert result.returncode == 0, f"bash -n failed:\n{result.stderr}" + + +@pytest.mark.parametrize("script", SCRIPTS, ids=lambda p: p.name) +def test_shellcheck(script: Path) -> None: + if shutil.which("shellcheck") is None: + pytest.skip("shellcheck not installed") + result = subprocess.run( + ["shellcheck", "--severity=warning", str(script)], + capture_output=True, + text=True, + ) + assert result.returncode == 0, f"shellcheck failed:\n{result.stdout}\n{result.stderr}" -- 2.49.1 From 07e0d82f1d0579bbbbe17c25d1988025a4e5bafc Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sun, 5 Apr 2026 13:24:42 -0400 Subject: [PATCH 06/11] feat(sim): add camera stream simulator script Loops phone-recorded mp4 files as local RTSP streams via MediaMTX + ffmpeg so Vigilar's camera pipeline can be exercised end-to-end without physical cameras. Reads camera ids from vigilar.toml, expects videos/.mp4 for each, writes a vigilar.sim.toml with rtsp_urls rewritten to the local endpoints. Co-Authored-By: Claude Opus 4.6 (1M context) --- scripts/sim_cameras.sh | 150 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100755 scripts/sim_cameras.sh diff --git a/scripts/sim_cameras.sh b/scripts/sim_cameras.sh new file mode 100755 index 0000000..9653f1f --- /dev/null +++ b/scripts/sim_cameras.sh @@ -0,0 +1,150 @@ +#!/usr/bin/env bash +# Simulate RTSP cameras by looping mp4 files through MediaMTX + ffmpeg. +# +# Usage: ./scripts/sim_cameras.sh +# +# Reads camera ids from config/vigilar.toml, expects videos/.mp4 for each, +# starts MediaMTX on 127.0.0.1:8554, spawns one ffmpeg per camera, and writes +# config/vigilar.sim.toml with rtsp_urls rewritten to the local endpoints. +# Ctrl-C tears everything down. +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +REAL_CONFIG="${REPO_ROOT}/config/vigilar.toml" +SIM_CONFIG="${REPO_ROOT}/config/vigilar.sim.toml" +VIDEOS_DIR="${REPO_ROOT}/videos" +SIM_DIR="${REPO_ROOT}/.sim" +LOG_DIR="${SIM_DIR}/logs" +MEDIAMTX_BIN="${SIM_DIR}/mediamtx" +RTSP_HOST="127.0.0.1" +RTSP_PORT="8554" + +MEDIAMTX_PID="" +FFMPEG_PIDS=() + +cleanup() { + local pid + for pid in "${FFMPEG_PIDS[@]}"; do + if [[ -n "${pid}" ]] && kill -0 "${pid}" 2>/dev/null; then + kill "${pid}" 2>/dev/null || true + fi + done + if [[ -n "${MEDIAMTX_PID}" ]] && kill -0 "${MEDIAMTX_PID}" 2>/dev/null; then + kill "${MEDIAMTX_PID}" 2>/dev/null || true + fi + sleep 0.3 + for pid in "${FFMPEG_PIDS[@]}" "${MEDIAMTX_PID}"; do + if [[ -n "${pid}" ]] && kill -0 "${pid}" 2>/dev/null; then + kill -9 "${pid}" 2>/dev/null || true + fi + done + rm -rf "${SIM_DIR:?}/logs" +} +trap cleanup EXIT INT TERM + +die() { echo "error: $*" >&2; exit 1; } + +# --- prereq checks --------------------------------------------------------- + +command -v ffmpeg >/dev/null 2>&1 || die "ffmpeg not found on PATH. Install it and retry." +[[ -x "${MEDIAMTX_BIN}" ]] || die "MediaMTX binary not found at ${MEDIAMTX_BIN}. Run: scripts/download_mediamtx.sh" +[[ -f "${REAL_CONFIG}" ]] || die "config file not found: ${REAL_CONFIG}" +[[ -d "${VIDEOS_DIR}" ]] || die "videos directory not found: ${VIDEOS_DIR} (create it and drop .mp4 files inside)" + +# --- parse camera ids from vigilar.toml ------------------------------------ +# Grab every `id = "..."` line that sits inside a [[cameras]] block. + +mapfile -t CAMERA_IDS < <(awk ' + /^\[\[cameras\]\]/ { in_cams = 1; next } + /^\[/ && !/^\[\[cameras\]\]/ { in_cams = 0 } + in_cams && /^[[:space:]]*id[[:space:]]*=/ { + match($0, /"([^"]+)"/, m) + if (m[1] != "") print m[1] + } +' "${REAL_CONFIG}") + +[[ ${#CAMERA_IDS[@]} -gt 0 ]] || die "no [[cameras]] blocks with an id field found in ${REAL_CONFIG}" + +# --- verify every camera has a matching video ----------------------------- + +MISSING=() +for id in "${CAMERA_IDS[@]}"; do + [[ -f "${VIDEOS_DIR}/${id}.mp4" ]] || MISSING+=("${VIDEOS_DIR}/${id}.mp4") +done +if [[ ${#MISSING[@]} -gt 0 ]]; then + echo "error: missing video files for cameras:" >&2 + for f in "${MISSING[@]}"; do echo " - ${f}" >&2; done + exit 1 +fi + +# --- start MediaMTX -------------------------------------------------------- + +mkdir -p "${LOG_DIR}" +echo "Starting MediaMTX on ${RTSP_HOST}:${RTSP_PORT}..." +"${MEDIAMTX_BIN}" >"${LOG_DIR}/mediamtx.log" 2>&1 & +MEDIAMTX_PID=$! + +for _ in $(seq 1 30); do + if (exec 3<>"/dev/tcp/${RTSP_HOST}/${RTSP_PORT}") 2>/dev/null; then + exec 3<&- 3>&- + break + fi + sleep 0.1 +done +if ! (exec 3<>"/dev/tcp/${RTSP_HOST}/${RTSP_PORT}") 2>/dev/null; then + echo "MediaMTX failed to bind ${RTSP_HOST}:${RTSP_PORT}. Log tail:" >&2 + tail -n 20 "${LOG_DIR}/mediamtx.log" >&2 || true + exit 1 +fi +exec 3<&- 3>&- 2>/dev/null || true + +# --- spawn one ffmpeg per camera ------------------------------------------- + +for id in "${CAMERA_IDS[@]}"; do + video="${VIDEOS_DIR}/${id}.mp4" + url="rtsp://${RTSP_HOST}:${RTSP_PORT}/${id}" + echo "Publishing ${video} -> ${url}" + ffmpeg -nostdin -loglevel warning \ + -stream_loop -1 -re -i "${video}" \ + -c copy -f rtsp "${url}" \ + >"${LOG_DIR}/${id}.log" 2>&1 & + FFMPEG_PIDS+=($!) +done + +# --- write the sim config -------------------------------------------------- +# Copy vigilar.toml, rewrite each `rtsp_url = "..."` line inside a +# [[cameras]] block to point at the local MediaMTX endpoint for that camera. +# Relies on `id` preceding `rtsp_url` within each block (the standing +# convention in config/vigilar.toml). + +awk -v host="${RTSP_HOST}" -v port="${RTSP_PORT}" ' + /^\[\[cameras\]\]/ { in_cams = 1; current_id = ""; print; next } + /^\[/ && !/^\[\[cameras\]\]/ { in_cams = 0; print; next } + in_cams && /^[[:space:]]*id[[:space:]]*=/ { + match($0, /"([^"]+)"/, m) + current_id = m[1] + print + next + } + in_cams && /^[[:space:]]*rtsp_url[[:space:]]*=/ && current_id != "" { + printf "rtsp_url = \"rtsp://%s:%s/%s\"\n", host, port, current_id + next + } + { print } +' "${REAL_CONFIG}" > "${SIM_CONFIG}" + +# --- summary --------------------------------------------------------------- + +echo +echo "Simulator running. ${#CAMERA_IDS[@]} stream(s):" +for id in "${CAMERA_IDS[@]}"; do + echo " rtsp://${RTSP_HOST}:${RTSP_PORT}/${id}" +done +echo +echo "Sim config written to: ${SIM_CONFIG}" +echo "Start Vigilar in another terminal:" +echo " vigilar start --config ${SIM_CONFIG#"${REPO_ROOT}"/}" +echo +echo "Press Ctrl-C to stop." + +wait -- 2.49.1 From 6754f8101925097fa97722b5deefced12071ad56 Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 27 Jun 2026 13:03:53 -0400 Subject: [PATCH 07/11] chore(plugin): scaffold code-review-tea plugin manifest Co-Authored-By: Claude Opus 4.8 (1M context) --- .../.claude-plugin/commands/.gitkeep | 0 .../code-review-tea/.claude-plugin/plugin.json | 17 +++++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 .claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep create mode 100644 .claude/plugins/code-review-tea/.claude-plugin/plugin.json diff --git a/.claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep b/.claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.claude/plugins/code-review-tea/.claude-plugin/plugin.json b/.claude/plugins/code-review-tea/.claude-plugin/plugin.json new file mode 100644 index 0000000..12eebfd --- /dev/null +++ b/.claude/plugins/code-review-tea/.claude-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "name": "code-review-tea", + "description": "Automated code review for Gitea pull requests (tea CLI) using multiple specialized agents with confidence-based scoring. Fork of Anthropic's code-review plugin, adapted from gh to tea.", + "version": "1.0.0", + "author": { + "name": "Vigilar", + "email": "noreply@adlee.work" + }, + "contributors": [ + { + "name": "Boris Cherny", + "email": "boris@anthropic.com", + "note": "Original code-review plugin (claude-plugins-official). This plugin forks its review design." + } + ], + "homepage": "https://git.adlee.work/alee/vigilar" +} -- 2.49.1 From 03925e3e11ef640b6858f805b4cf58a2c08dc88c Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 27 Jun 2026 13:27:00 -0400 Subject: [PATCH 08/11] docs(plan): correct code-review-tea plan with verified tea facts Incorporate findings from Task 2 verification: - -F (typed field) reads @-/@file; -f posts literal '@-'. Use -F. - Endpoint requires /repos/ prefix: /repos/{owner}/{repo}/... - tea pulls --fields diff returns empty in tea 0.14.1 -> use git diff - SHA must be remote-present (PR headSha); local-only SHA 404s - tea api prints JSON to stdout; -o is file-output not format Co-Authored-By: Claude Opus 4.8 (1M context) --- .../2026-06-27-code-review-tea-plugin.md | 585 ++++++++++++++++++ 1 file changed, 585 insertions(+) create mode 100644 docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md diff --git a/docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md b/docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md new file mode 100644 index 0000000..4958377 --- /dev/null +++ b/docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md @@ -0,0 +1,585 @@ +# code-review-tea Plugin Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Port Anthropic's `code-review` plugin from the GitHub CLI (`gh`) to the Gitea CLI (`tea`) as a project-local plugin named `code-review-tea`, so it works against this Gitea-hosted repository, and smoke-test it end-to-end against a real Gitea pull request. + +**Architecture:** The upstream plugin is a single command file (`commands/code-review.md`) written entirely around `gh`: its `allowed-tools` list, PR-eligibility checks, diff source, and comment-posting step all call `gh`. We fork that command file into a project-local plugin (`.claude/plugins/code-review-tea/`), rewrite the five `gh`→`tea` contact points, and change code-link URLs from GitHub's `blob/SHA/path#L` format to Gitea's `src/commit/SHA/path#L` format. The review *pattern* itself (parallel agents → confidence scoring → 80 threshold filter) is unchanged. Credit to the original Anthropic plugin (by Boris Cherny) is preserved in `plugin.json`, the README, and the command file header. + +**Tech Stack:** Gitea (`git.adlee.work`, SSH `:2222`), `tea` CLI v0.14.1 (already installed + logged in as `alee`), the Anthropic `code-review` plugin command spec, Markdown command files. + +**Credit:** This plugin is a fork of Anthropic's `code-review` plugin (author: Boris Cherny, `boris@anthropic.com`), sourced from the `claude-plugins-official` marketplace. The upstream is GitHub/`gh`-only; this fork adapts it to Gitea/`tea`. All credit for the review design (5 parallel agents, confidence scoring, false-positive filtering) belongs to the original. + +--- + +## Context & Verified Facts + +These were confirmed by probing the live `tea` 0.14.1 binary during planning — the plan depends on them being accurate: + +- **Remote**: `ssh://git@git.adlee.work:2222/alee/vigilar.git` → owner `alee`, repo `vigilar`, web host `https://git.adlee.work`. +- **Login**: `tea login list` shows one login `alee` at `https://git.adlee.work` (NOT marked default). Commands need `--remote origin` to auto-resolve context (fall back to `--login alee`). +- **`tea pulls `** — shows a PR's detail. Use `--fields state,draft,head,base,mergeable,title,body,diff -o json` for machine-readable metadata. +- **`tea pulls ls --state all`** — lists PRs. Repo has used indexes 4–7 (all merged, by A.D.Lee, 2026-04-05). Open PRs: currently none. +- **`tea pulls review-comments `** — lists existing review comments with fields `id,body,reviewer,path,line,resolver`. Used for the "already reviewed?" eligibility check (scan `body` for the `### Code review` marker line). +- **`tea comment `** — "Add a comment to an issue / pr", but takes body as a trailing arg (fragile for large multi-line Markdown). The robust post-back path is `tea api` (below). +- **`tea api `** — raw authenticated API. Endpoint gets `/api/v1/` prefix unless it starts with `/api` or `http(s)://`; `{owner}`/`{repo}` placeholders are substituted from repo context. `-f` for string fields, `-F` for typed; `@` reads from file, `@-` from stdin. Post-back endpoint: `{owner}/{repo}/issues//comments` with `-f body=@-`. +- **Gitea code link format** (replaces GitHub `blob/` format): `https://git.adlee.work/alee/vigilar/src/commit//#L-L`. Use full SHA, never `$(git rev-parse HEAD)` substituted into the rendered comment. +- **Diff source**: prefer local `git diff origin/...origin/` (fast, no API round-trip); needs base/head from `tea pulls `. Fallback: `tea api {owner}/{repo}/pulls/` and read `.diff`, or `tea api .../pulls/.diff`. +- **The original upstream command file** lives at `~/.claude/plugins/marketplaces/claude-plugins-official/plugins/code-review/commands/code-review.md` (read during planning). We fork it; we do not edit the marketplace original. + +### The five `gh`→`tea` contact points in the original + +| # | Step in original | `gh` call | `tea` replacement | +|---|---|---|---| +| 1 | Eligibility (closed / draft / trivial / already-reviewed) | `gh pr view`, `gh pr list` | `tea pulls --fields state,draft,title,mergeable -o json`; already-reviewed = `tea pulls review-comments ` scan for marker | +| 2 | Gather CLAUDE.md paths | (local fs) | unchanged — local fs | +| 3 | Summarize the PR | `gh pr view`, `gh pr diff` | `tea pulls --fields title,body,diff -o json` + `git diff origin/...origin/` | +| 4 | Parallel review agents | (no git tool — reads diff/files already fetched) | unchanged | +| 5 | Post comment | `gh pr comment --body ...` | `tea api /repos/{owner}/{repo}/issues//comments -F body=@-` (stdin; `-F` typed field reads `@-`, `-f` would post literal `@-`; `/repos/` prefix required) | + +--- + +## File Structure + +``` +.claude/plugins/code-review-tea/ +├── .claude-plugin/ +│ ├── plugin.json # the manifest (credits Anthropic/Boris Cherny) +│ └── commands/ +│ ├── code-review.md # the forked, tea-rewritten command +│ └── RESOLVED_INVOCATION.md # verified tea call notes (from Task 2) +└── README.md # what this fork is, why, how it differs +``` + +Rationale: a project-local plugin under `.claude/plugins/` is version-controlled with the repo and applies only here (this is a Gitea-only repo; a global install would mis-fire on the user's GitHub-hosted repos). The name `code-review-tea` is distinct from the upstream `code-review` so it never shadows or confuses the GitHub plugin if that ever gets enabled elsewhere. + +We create **no** Python source changes and **no** test files — this is a tooling-only change. The `allowed-tools` substitution and command-file rewrite are the entire substance. + +--- + +## Task 1: Scaffold the project-local plugin + +**Files:** +- Create: `.claude/plugins/code-review-tea/.claude-plugin/plugin.json` +- Create: `.claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep` + +- [ ] **Step 1: Create the plugin manifest** + +Create `.claude/plugins/code-review-tea/.claude-plugin/plugin.json`: + +```json +{ + "name": "code-review-tea", + "description": "Automated code review for Gitea pull requests (tea CLI) using multiple specialized agents with confidence-based scoring. Fork of Anthropic's code-review plugin, adapted from gh to tea.", + "version": "1.0.0", + "author": { + "name": "Vigilar", + "email": "noreply@adlee.work" + }, + "contributors": [ + { + "name": "Boris Cherny", + "email": "boris@anthropic.com", + "note": "Original code-review plugin (claude-plugins-official). This plugin forks its review design." + } + ], + "homepage": "https://git.adlee.work/alee/vigilar" +} +``` + +(The `contributors[].note` field is non-standard metadata — kept for provenance. If Claude Code's plugin loader rejects unknown JSON keys, drop `note` and rely on README/README credit instead; Task 6 step 3 verifies loading.) + +- [ ] **Step 2: Create the commands directory placeholder** + +Create `.claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep` as an empty file so the directory is tracked by git. + +- [ ] **Step 3: Verify the directory tree** + +Run: +```bash +find .claude/plugins/code-review-tea -type f +``` +Expected: two files — `plugin.json` and `commands/.gitkeep`. + +- [ ] **Step 4: Commit** + +```bash +git add .claude/plugins/code-review-tea +git commit -m "chore(plugin): scaffold code-review-tea plugin manifest" +``` + +--- + +## Task 2: Resolve the exact `tea` comment-posting invocation + +Before writing the command file in Task 3, nail down the one uncertain API surface: how to post a large multi-paragraph Markdown review body to a Gitea PR. `tea comment ` takes the body as a trailing arg (shell-quoting a long Markdown body with backticks and `#` headers is fragile). Confirm the robust `tea api` path works against this Gitea instance. + +**Files:** +- No permanent file changes. Verification task whose result is recorded in `RESOLVED_INVOCATION.md` (Task 6 integrates it; here we just verify and note the result). + +- [ ] **Step 1: Confirm PR #7 metadata is readable via tea** + +Run: +```bash +tea pulls 7 --remote origin --fields index,state,draft,title,mergeable,base,head,body,diff -o json 2>&1 | head -40 +``` +Expected: JSON object with `state: "closed"` (it's merged), `title` starting "fix: unify PIN hashing", non-empty `diff`. If `--remote origin` fails to resolve context, retry with `--login alee` and record which flag is required (it becomes the default in the command file). + +- [ ] **Step 2: Create a scratch issue as the comment round-trip target** + +```bash +tea issue create --remote origin --title "code-review-tea smoke test (delete me)" --description "scratch target for verifying tea comment posting; safe to delete" -o json 2>&1 +``` +Expected: JSON with the new issue's `index` (a number). Record it as `$SCRATCH`. + +If `tea issue create` needs a different flag form, fall back to: +```bash +tea issues create --remote origin --title "code-review-tea smoke test (delete me)" +``` +and read the created index from output or `tea issues ls --state open`. + +- [ ] **Step 3: Post a multi-line Markdown body via tea api stdin** + +Run (replace `$SCRATCH` with the real index): +```bash +printf '### Code review smoke test\n\nFound 1 issue:\n\n1. Placeholder finding for `tea` round-trip verification.\n\nhttps://git.adlee.work/alee/vigilar/src/commit/%s/vigilar/cli/__init__.py#L1-L3\n' "$(git rev-parse HEAD)" \ + | tea api --remote origin "{owner}/{repo}/issues/$SCRATCH/comments" -f body=@- +``` +Expected: a JSON response containing the posted comment's `body` and `id`. If `-f body=@-` is rejected, fall back to writing the body to `/tmp/review-tea-body.md` and running `tea api --remote origin "{owner}/{repo}/issues/$SCRATCH/comments" -f body=@/tmp/review-tea-body.md`. Record which variant worked — it's the canonical post-back invocation for the command file in Task 3. + +- [ ] **Step 4: Verify the Gitea code-link format renders** + +Run: +```bash +tea api --remote origin "{owner}/{repo}/issues/$SCRATCH/comments" -o json 2>&1 | head -40 +``` +Expected: the posted comment present with the `src/commit//...#L1-L3` URL intact. Open the URL in a browser (or `tea open` the issue) to confirm it resolves to the file at that commit. If Gitea requires a different path segment than `src/commit`, correct the link format used in Task 3's command file. + +- [ ] **Step 5: Clean up the scratch issue** + +```bash +tea issue close --remote origin "$SCRATCH" +``` +Expected: issue closed. (Gitea keeps the index; that's fine — it's marked closed and titled "delete me".) + +- [ ] **Step 6: Record the verified invocation (provenance for Task 3 + Task 5)** + +Make a mental/scratch note of: (a) which login-context flag worked (`--remote origin` vs `--login alee`), (b) which post-back variant worked (stdin `-f body=@-` vs file `-f body=@/tmp/...`), (c) the confirmed Gitea link path segment (`src/commit`). These three values are baked into the command file (Task 3) and documented in the README (Task 5). No file written in this task. + +--- + +## Task 3: Write the `tea`-adapted command file + +The substantive change. Fork the upstream command, substitute the five `gh` contact points and the link format, keep the parallel-agent + confidence-score + 80-threshold logic identical, and add a header crediting the original. + +**Files:** +- Create: `.claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md` + +- [ ] **Step 1: Read the upstream command file for reference** + +Run: +```bash +cat ~/.claude/plugins/marketplaces/claude-plugins-official/plugins/code-review/commands/code-review.md +``` +Expected: the 93-line original. Keep it open; this is the template to fork. + +- [ ] **Step 2: Write the command file** + +Create `.claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md`. The full content: + +````markdown +--- +allowed-tools: Bash(tea pulls:*), Bash(tea pulls review-comments:*), Bash(tea comment:*), Bash(tea api:*), Bash(tea issue create:*), Bash(tea issue close:*), Bash(git diff:*), Bash(git rev-parse:*), Bash(git config:*), Bash(git remote get-url:*), Bash(git remote:*) +description: Code review a Gitea pull request (tea CLI) +disable-model-invocation: false +--- + + + +Provide a code review for the given Gitea pull request. + +You are operating on a Gitea-hosted repository (not GitHub). All Gitea interaction goes through the `tea` CLI (NOT `gh`). The git remote is `ssh://git@git.adlee.work:2222/alee/vigilar.git`; the web host is `https://git.adlee.work`. The `alee` tea login is configured but is NOT the default, so always pass `--remote origin` to resolve repo context (fall back to `--login alee` only if that fails). + +**tea api gotchas (verified):** Use `-F` (typed field) — NOT `-f` (string field) — when reading body from a file or stdin. `-f key=@file` posts the literal string `@file`; only `-F key=@file` / `-F key=@-` reads the file/stdin. Endpoints addressing a repo resource require the `/repos/` prefix after the version: `/repos/{owner}/{repo}/...` (NOT `{owner}/{repo}/...`, which 404s). `tea api` already prints JSON to stdout — do NOT pass `-o json` (that writes the body to a file named `json`). + +First, make a todo list of these steps, then execute them precisely: + +1. Take the PR index from the user (ask if not provided). Use a Haiku agent to fetch `tea pulls --remote origin --fields index,state,draft,title,mergeable,base,head,body -o json` and check if the PR (a) is closed/merged, (b) is a draft, (c) does not need a review (trivial/automated), or (d) already has a code review from you. For (d), run `tea pulls review-comments --remote origin -o json` and scan each comment's `body` for the marker line `### Code review` generated by a `code-review-tea` run (check `reviewer` is the bot/your account). If any of a–d, do not proceed. (Note: in tea v0.14.1 the `diff`/`patch` fields come back empty even when requested — fetch the diff separately in step 3.) + +2. Use another Haiku agent to give you a list of file paths to (but not the contents of) any relevant CLAUDE.md files from the codebase: the root `CLAUDE.md`, plus any `CLAUDE.md` in the directories whose files the PR modified. Determine modified dirs from the diff obtained in step 1 (parse the `+++ b/` and `--- a/` headers). + +3. Use a Haiku agent to summarize the change from the diff. Fetch the diff locally — it is the reliable source in this tea build: `git diff origin/...origin/` (where `base`/`head` are the PR's branch names from step 1's JSON, e.g. `origin/main...origin/fix/issue-2-pin-unification`). Ensure both refs are fetched first (`git fetch origin` if needed). + +4. Then, launch 5 parallel Sonnet agents to independently code review the change. The agents should do the following, then return a list of issues and the reason each issue was flagged (eg. CLAUDE.md adherence, bug, historical git context, etc.): + a. Agent #1: Audit the changes to make sure they comply with the CLAUDE.md. Note that CLAUDE.md is guidance for Claude as it writes code, so not all instructions will be applicable during code review. + b. Agent #2: Read the file changes in the pull request, then do a shallow scan for obvious bugs. Avoid reading extra context beyond the changes, focusing just on the changes themselves. Focus on large bugs, and avoid small issues and nitpicks. Ignore likely false positives. + c. Agent #3: Read the git blame and history of the code modified, to identify any bugs in light of that historical context. + d. Agent #4: Read previous pull requests that touched these files (`tea pulls ls --state all --remote origin` then cross-reference file paths), and check for any comments on those pull requests (`tea pulls review-comments --remote origin`) that may also apply to the current pull request. + e. Agent #5: Read code comments in the modified files, and make sure the changes in the pull request comply with any guidance in the comments. +5. For each issue found in #4, launch a parallel Haiku agent that takes the PR index, issue description, and list of CLAUDE.md files (from step 2), and returns a score to indicate the agent's level of confidence for whether the issue is real or false positive. To do that, the agent should score each issue on a scale from 0-100, indicating its level of confidence. For issues that were flagged due to CLAUDE.md instructions, the agent should double check that the CLAUDE.md actually calls out that issue specifically. The scale is (give this rubric to the agent verbatim): + a. 0: Not confident at all. This is a false positive that doesn't stand up to light scrutiny, or is a pre-existing issue. + b. 25: Somewhat confident. This might be a real issue, but may also be a false positive. The agent wasn't able to verify that it's a real issue. If the issue is stylistic, it is one that was not explicitly called out in the relevant CLAUDE.md. + c. 50: Moderately confident. The agent was able to verify this is a real issue, but it might be a nitpick or not happen very often in practice. Relative to the rest of the PR, it's not very important. + d. 75: Highly confident. The agent double checked the issue, and verified that it is very likely it is a real issue that will be hit in practice. The existing approach in the PR is insufficient. The issue is very important and will directly impact the code's functionality, or it is an issue that is directly mentioned in the relevant CLAUDE.md. + e. 100: Absolutely certain. The agent double checked the issue, and confirmed that it is definitely a real issue, that will happen frequently in practice. The evidence directly confirms this. +6. Filter out any issues with a score less than 80. If there are no issues that meet this criteria, do not proceed. +7. Use a Haiku agent to repeat the eligibility check from #1, to make sure that the pull request is still eligible for code review. +8. Finally, post the result back to the Gitea PR as a single comment using: + ```bash + printf '%s' "$BODY" | tea api --remote origin "/repos/{owner}/{repo}/issues//comments" -F body=@- + ``` + where `` is the PR index and `{owner}/{repo}` are substituted by `tea api` from repo context. Note the **`-F`** (typed field, reads stdin via `@-`) — NOT `-f`, which would post the literal string `@-`. Note the **`/repos/`** prefix on the endpoint. If stdin body is rejected, write `$BODY` to `/tmp/review-tea-body.md` and use `-F body=@/tmp/review-tea-body.md`. When writing `$BODY`, keep in mind that you must: + a. Keep your output brief + b. Avoid emojis + c. Link and cite relevant code, files, and URLs — using the **Gitea** link format (NOT GitHub): + `https://git.adlee.work/alee/vigilar/src/commit//#L-L` + Use the PR's head SHA (from step 1's JSON `headSha`), which is present on the remote. Never use a local-only / unpushed SHA — a commit not on the remote yields a 404 link even on a public repo. Never bash-substitute `$(git rev-parse HEAD)` into the rendered Markdown. Gitea uses `src/commit`, not `blob`. + +Examples of false positives, for steps 4 and 5: + +- Pre-existing issues +- Something that looks like a bug but is not actually a bug +- Pedantic nitpicks that a senior engineer wouldn't call out +- Issues that a linter, typechecker, or compiler would catch (eg. missing or incorrect imports, type errors, broken tests, formatting issues, pedantic style issues like newlines). No need to run these build steps yourself -- it is safe to assume that they will be run separately as part of CI. +- General code quality issues (eg. lack of test coverage, general security issues, poor documentation), unless explicitly required in CLAUDE.md +- Issues that are called out in CLAUDE.md, but explicitly silenced in the code (eg. due to a lint ignore comment) +- Changes in functionality that are likely intentional or are directly related to the broader change +- Real issues, but on lines that the user did not modify in their pull request + +Notes: + +- Do not check build signal or attempt to build or typecheck the app. These will run separately, and are not relevant to your code review. +- Use `tea` (NOT `gh`) to interact with Gitea (eg. to fetch a pull request, or to create comments), never web fetch. +- Make a todo list first +- You must cite and link each bug (eg. if referring to a CLAUDE.md, you must link it) +- For your final comment, follow the following format precisely (assuming for this example that you found 3 issues): + +--- + +### Code review + +Found 3 issues: + +1. (CLAUDE.md says "<...>") + +https://git.adlee.work/alee/vigilar/src/commit//#L13-L17 + +2. (some/other/CLAUDE.md says "<...>") + +https://git.adlee.work/alee/vigilar/src/commit//#L23-L28 + +3. (bug due to ) + +https://git.adlee.work/alee/vigilar/src/commit//#L44-L50 + +🤖 Generated with [Claude Code](https://claude.ai/code) + +- If this code review was useful, please react with 👍. Otherwise, react with 👎. + +--- + +- Or, if you found no issues: + +--- + +### Code review + +No issues found. Checked for bugs and CLAUDE.md compliance. + +🤖 Generated with [Claude Code](https://claude.ai/code) + +--- + +- When linking to code, follow this Gitea format precisely, otherwise the Markdown preview won't render correctly: `https://git.adlee.work/alee/vigilar/src/commit//#L-L` + - Requires the full git sha of a **remote-present** commit (the PR head SHA from step 1's JSON `headSha`). Never `$(git rev-parse HEAD)` substituted into the rendered comment, and never a local-only/unpushed SHA — those 404 even on a public repo + - Repo path must be `alee/vigilar` (matches the git remote) + - `#L` sign after the file name + - Line range format is `-` (Gitea uses `L1-L3`, same as GitHub but under `src/commit`) + - Provide at least 1 line of context before and after, centered on the line you are commenting about (eg. if commenting about lines 5-6, link to `L4-L7`) +```` + +- [ ] **Step 3: Sanity-check the command file frontmatter** + +Run: +```bash +head -6 .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md +``` +Expected: the `---` fence, `allowed-tools:` line containing only `Bash(tea ...:*), Bash(git ...:*)` entries (NO `gh`), then `description:` and `disable-model-invocation: false`, then closing `---`. + +- [ ] **Step 4: Grep to confirm no gh references leaked in** + +Run: +```bash +grep -nE '\bgh\b|github\.com|/blob/' .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md || echo "clean: no gh/github/blob references" +``` +Expected: `clean: no gh/github/blob references`. If anything matches, fix it before committing. (Note: the credit comment intentionally mentions "GitHub/gh-only" to describe the upstream — that line references `gh` as a word, so adjust the grep if it fires on the credit line; the credit line is correct and should stay. The grep is meant to catch *operational* `gh` calls, which would look like `gh pr` or `gh issue`.) + +A more precise check: +```bash +grep -nE 'gh pr|gh issue|gh search|gh api|github\.com/alee/vigilar/blob|/blob/<' .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md || echo "clean: no operational gh calls or blob links" +``` +Expected: `clean: no operational gh calls or blob links`. + +- [ ] **Step 5: Commit** + +```bash +git add .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md +git commit -m "feat(plugin): gitea/tea port of code-review command" +``` + +--- + +## Task 4: Enable the plugin in this project's settings + +**Files:** +- Modify: `.claude/settings.json` + +- [ ] **Step 1: Read the current settings** + +Run: +```bash +cat .claude/settings.json +``` +Expected: +```json +{ + "enabledPlugins": { + "superpowers@claude-plugins-official": true + } +} +``` + +- [ ] **Step 2: Add the new plugin to enabledPlugins** + +Change `.claude/settings.json` to: + +```json +{ + "enabledPlugins": { + "superpowers@claude-plugins-official": true, + "code-review-tea@vigilar": true + } +} +``` + +The `@vigilar` suffix denotes a project-local (non-marketplace) plugin discovered from `.claude/plugins/code-review-tea/`. If Claude Code resolves local plugins by bare directory name (no `@source` suffix), drop it to `"code-review-tea": true`. Step 3 verifies which form is accepted. + +- [ ] **Step 3: Verify the plugin is discoverable** + +Restart/reload Claude Code for this project and run `/code-review-tea`. If the command is not found, Claude Code's local-plugin resolution may need the bare plugin name — change settings to `"code-review-tea": true` and re-verify. If still not found, confirm the plugin is discovered at all by checking whether `/code-review-tea` appears in the command list (if not, the loader may not scan `.claude/plugins/` — in that case, the plugin can still be invoked by directly reading the command file; document this fallback in the README). + +- [ ] **Step 4: Commit** + +```bash +git add .claude/settings.json +git commit -m "chore(plugin): enable project-local code-review-tea plugin" +``` + +--- + +## Task 5: Document the plugin (README + RESOLVED_INVOCATION + CLAUDE.md note) + +**Files:** +- Create: `.claude/plugins/code-review-tea/README.md` +- Create: `.claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md` +- Modify: `CLAUDE.md` — append a short "## Code Review" subsection + +- [ ] **Step 1: Write the verified invocation notes** + +Create `.claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md`. Fill in with the variants verified in Task 2 (replace `` placeholders with the actually-confirmed values): + +```markdown +# Resolved tea post-back invocation (verified via Task 2 smoke run) + +Gitea comment posting that survives large multi-line Markdown bodies: + + tea api --remote origin "{owner}/{repo}/issues//comments" -f body=@- # body via stdin + # fallback: -f body=@/tmp/review-tea-body.md # body via file + +Code link format (verify it renders in Gitea web): + https://git.adlee.work/alee/vigilar/src/commit//#L-L # path segment confirms src/commit + +Eligibility metadata fetch: + tea pulls --remote origin --fields state,draft,title,mergeable,base,head,body,diff -o json + +Diff source (preferred, local): + git diff origin/...origin/ + +Login context: the `alee` tea login is NOT default (tea login list shows default=false). +``` + +- [ ] **Step 2: Write the plugin README** + +Create `.claude/plugins/code-review-tea/README.md`: + +````markdown +# code-review-tea + +Project-local fork of Anthropic's `code-review` plugin, adapted from the GitHub CLI (`gh`) to the Gitea CLI (`tea`). + +## Credit + +This plugin is a fork of **Anthropic's `code-review` plugin** (author: **Boris Cherny**, `boris@anthropic.com`), from the `claude-plugins-official` marketplace. The upstream plugin is GitHub/`gh`-only. All credit for the review design — the 5 parallel specialized agents, confidence-based scoring, and false-positive filtering — belongs to the original. This fork changes only the Gitea contact points. + +## Why a fork + +Vigilar is hosted on a self-hosted Gitea instance (`git.adlee.work`), not GitHub. The upstream `code-review` plugin is hard-wired to `gh` (its `allowed-tools`, PR-fetching, and comment-posting all call `gh`), so it cannot run against this repo as-is. This fork substitutes the five `gh` contact points with `tea` equivalents and changes code-link URLs from GitHub's `blob/SHA/path#L` format to Gitea's `src/commit/SHA/path#L` format. + +## Usage + +On a branch with an open Gitea pull request against `main`: + + /code-review-tea + +Claude will: +- Verify the PR is reviewable (skip closed/draft/trivial/already-reviewed) +- Gather relevant CLAUDE.md files +- Summarize the change +- Launch 5 parallel review agents (CLAUDE.md compliance, bug scan, git-history context, prior-PR comments, in-code-comment compliance) +- Score each finding 0–100 for confidence +- Filter to findings ≥80 +- Post a single review comment back to the Gitea PR via `tea api` + +## Requirements + +- `tea` CLI (v0.14.1+) installed and logged in as `alee` against `https://git.adlee.work` +- The `alee` login need NOT be the default — the command passes `--remote origin` to resolve context +- An open Gitea pull request to review + +## Differences from upstream + +| Area | Upstream (GitHub) | This fork (Gitea) | +|---|---|---| +| CLI | `gh` | `tea` | +| PR metadata | `gh pr view` | `tea pulls --fields ... -o json` | +| Diff | `gh pr diff` | `git diff origin/...origin/` (local) | +| Comment post | `gh pr comment --body` | `tea api {owner}/{repo}/issues//comments -f body=@-` | +| Code link | `github.com/o/r/blob/SHA/path#L` | `git.adlee.work/alee/vigilar/src/commit/SHA/path#L` | +| Inline line comments | (upstream posts one summary comment) | NOT attempted — single summary comment only (Gitea inline-comment API needs `tea api` review endpoints; out of scope) | + +See `.claude-plugin/commands/RESOLVED_INVOCATION.md` for the verified `tea` calls. +```` + +- [ ] **Step 3: Append a Code Review subsection to CLAUDE.md** + +Append to `CLAUDE.md`, as a new `## Code Review` section near the existing `## Commands` section: + +```markdown +## Code Review +- `/code-review-tea` — review the current Gitea PR (project-local fork of Anthropic's code-review plugin, adapted from `gh` to `tea`; credit: Boris Cherny). See `.claude/plugins/code-review-tea/README.md`. +``` + +- [ ] **Step 4: Commit** + +```bash +git add .claude/plugins/code-review-tea/README.md .claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md CLAUDE.md +git commit -m "docs(plugin): document code-review-tea fork and CLAUDE.md note" +``` + +--- + +## Task 6: Smoke-test the command against a scratch PR + +End-to-end verification that the full pipeline (eligibility → CLAUDE.md gather → summarize → 5 parallel agents → score → filter → post) works through `tea` against a real Gitea PR. Use a throwaway PR with a deliberately obvious bug so the pipeline has something to find and post. + +**Files:** +- No permanent file changes. The scratch PR is closed and its branch deleted after. + +- [ ] **Step 1: Create a scratch branch with an obvious bug** + +```bash +git checkout -b scratch/review-smoke main +``` +Introduce an obvious bug in a low-risk spot — e.g. in `vigilar/constants.py` swap a comparison, or create a trivial `vigilar/_scratch_review.py`: +```python +def is_armed(state): + # BUG: assignment instead of comparison + if state = "armed": + return True + return False +``` +Minimal change — the point is to exercise the pipeline, not to ship. + +- [ ] **Step 2: Push and open a PR via tea** + +```bash +git add -A +git commit -m "scratch: review smoke test (do not merge)" +git push -u origin scratch/review-smoke +tea pulls create --remote origin --base main --head scratch/review-smoke \ + --title "scratch: code-review-tea smoke test (do not merge)" \ + --description "Throwaway PR to verify the code-review-tea pipeline end-to-end. Safe to close." +``` +Expected: a new PR index. Record it as `$SMOKE`. + +- [ ] **Step 3: Run the adapted command against the scratch PR** + +Run `/code-review-tea` and provide `$SMOKE` as the PR index. Watch for each stage: +- eligibility fetch via `tea pulls` ✓ +- CLAUDE.md gather ✓ +- summary ✓ +- 5 parallel agents return ✓ +- each finding scored ✓ +- ≥80 findings (or graceful "No issues" path) ✓ +- comment posted via `tea api` ✓ + +If any stage fails, capture the error and fix the command file (Task 3) — this smoke test exists to catch exactly that. + +- [ ] **Step 4: Verify the posted comment on Gitea** + +```bash +tea api --remote origin "{owner}/{repo}/issues/$SMOKE/comments" -o json 2>&1 | head -60 +``` +Expected: a comment whose `body` starts with `### Code review`, contains Gitea `src/commit//...#L...` links (NOT github.com/blob), and (if the bug was obvious) lists it under "Found N issues". Open the PR in a browser to confirm the links render and resolve. + +- [ ] **Step 5: Close the scratch PR and delete the branch** + +```bash +tea pulls close --remote origin "$SMOKE" +git push origin --delete scratch/review-smoke +git checkout main +git branch -D scratch/review-smoke +``` +Expected: PR closed, remote branch deleted, back on `main`, local branch gone. + +- [ ] **Step 6: Clean up the scratch source file** + +```bash +git rm vigilar/_scratch_review.py 2>/dev/null && git commit -m "chore: remove review smoke-test scratch file" || echo "nothing to clean" +``` + +- [ ] **Step 7: Update RESOLVED_INVOCATION.md with the end-to-end confirmation** + +Edit `.claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md` to replace each `` placeholder with the actual confirmed result from this smoke run (stdin worked vs file fallback, `--remote origin` resolved, `src/commit` rendered). Commit: +```bash +git add .claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md +git commit -m "docs(plugin): confirm resolved tea invocation from smoke test" +``` + +--- + +## Self-Review (run after all tasks written) + +1. **Spec coverage** — The user asked: make the `code-review` plugin work on Gitea (`tea`), name it `code-review-tea`, give credit to the original. → Tasks 1–6: scaffold, resolve invocation, write command, enable, document, smoke-test. Credit appears in `plugin.json` (contributors), command file header comment, and README. ✓ No hot-path review (dropped per revised scope). ✓ +2. **Placeholder scan** — Command file content is verbatim in Task 3 (full file with 4-backtick fence preserving inner 3-backtick fences). Test bodies are concrete (`is_armed` scratch bug). The only "verify which form" items (Task 4 Step 3 plugin discovery; Task 5 RESOLVED_INVOCATION `` placeholders) are real, intentional verifications — each has a concrete fallback and a step that resolves it, not an unfilled "TBD". +3. **Name consistency** — `code-review-tea` used consistently in directory, `plugin.json` `name`, settings key, README title, CLAUDE.md note, and `/code-review-tea` invocation. No leftover `supertea` or `code-review-gitea`. +4. **Credit correctness** — Original author Boris Cherny / Anthropic credited in `plugin.json` contributors, command file header comment, and README "Credit" section. Fork relationship stated (upstream = GitHub/gh-only). +5. **Uncertainty surfaced honestly** — `tea comment` vs `tea api` posting (Task 2 verifies, fallback documented); local-plugin `enabledPlugins` key form (Task 4 Step 3 verifies); Gitea `src/commit` path segment (Task 2/6 verifies render); `plugin.json` unknown-key tolerance (Task 1 Step 1 note + Task 6 smoke exercises loading). None silently assumed. +``` + +--- + +## Execution Handoff + +**Plan complete and saved to `docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md`.** Two execution options: + +**1. Subagent-Driven (recommended)** — I dispatch a fresh subagent per task, review between tasks, fast iteration. + +**2. Inline Execution** — Execute tasks in this session using executing-plans, batch execution with checkpoints. + +**Which approach?** + +Task 2 and Task 6 make live `tea` calls against your Gitea instance (creating a scratch issue and a scratch PR that are closed immediately after). Those are the only outward-facing actions; everything else is local file edits. If you'd rather skip the live smoke test (Task 6) and just have the plugin built + documented for you to test manually later, say so and I'll execute Tasks 1–5 only. -- 2.49.1 From 47c0da59591f8e65f693b0dfae2f8d0acba90c3d Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 27 Jun 2026 13:30:44 -0400 Subject: [PATCH 09/11] feat(plugin): gitea/tea port of code-review command Co-Authored-By: Claude Opus 4.8 (1M context) --- .../.claude-plugin/commands/code-review.md | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md diff --git a/.claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md b/.claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md new file mode 100644 index 0000000..580c4cf --- /dev/null +++ b/.claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md @@ -0,0 +1,111 @@ +--- +allowed-tools: Bash(tea pulls:*), Bash(tea pulls review-comments:*), Bash(tea comment:*), Bash(tea api:*), Bash(tea issue create:*), Bash(tea issue close:*), Bash(git diff:*), Bash(git rev-parse:*), Bash(git config:*), Bash(git remote get-url:*), Bash(git remote:*) +description: Code review a Gitea pull request (tea CLI) +disable-model-invocation: false +--- + + + +Provide a code review for the given Gitea pull request. + +You are operating on a Gitea-hosted repository (not GitHub). All Gitea interaction goes through the `tea` CLI (NOT `gh`). The git remote is `ssh://git@git.adlee.work:2222/alee/vigilar.git`; the web host is `https://git.adlee.work`. The `alee` tea login is configured but is NOT the default, so always pass `--remote origin` to resolve repo context (fall back to `--login alee` only if that fails). + +**tea api gotchas (verified):** Use `-F` (typed field) — NOT `-f` (string field) — when reading body from a file or stdin. `-f key=@file` posts the literal string `@file`; only `-F key=@file` / `-F key=@-` reads the file/stdin. Endpoints addressing a repo resource require the `/repos/` prefix after the version: `/repos/{owner}/{repo}/...` (NOT `{owner}/{repo}/...`, which 404s). `tea api` already prints JSON to stdout — do NOT pass `-o json` (that writes the body to a file named `json`). + +First, make a todo list of these steps, then execute them precisely: + +1. Take the PR index from the user (ask if not provided). Use a Haiku agent to fetch `tea pulls --remote origin --fields index,state,draft,title,mergeable,base,head,body -o json` and check if the PR (a) is closed/merged, (b) is a draft, (c) does not need a review (trivial/automated), or (d) already has a code review from you. For (d), run `tea pulls review-comments --remote origin -o json` and scan each comment's `body` for the marker line `### Code review` generated by a `code-review-tea` run (check `reviewer` is the bot/your account). If any of a–d, do not proceed. (Note: in tea v0.14.1 the `diff`/`patch` fields come back empty even when requested — fetch the diff separately in step 3.) + +2. Use another Haiku agent to give you a list of file paths to (but not the contents of) any relevant CLAUDE.md files from the codebase: the root `CLAUDE.md`, plus any `CLAUDE.md` in the directories whose files the PR modified. Determine modified dirs from the diff obtained in step 1 (parse the `+++ b/` and `--- a/` headers). + +3. Use a Haiku agent to summarize the change from the diff. Fetch the diff locally — it is the reliable source in this tea build: `git diff origin/...origin/` (where `base`/`head` are the PR's branch names from step 1's JSON, e.g. `origin/main...origin/fix/issue-2-pin-unification`). Ensure both refs are fetched first (`git fetch origin` if needed). + +4. Then, launch 5 parallel Sonnet agents to independently code review the change. The agents should do the following, then return a list of issues and the reason each issue was flagged (eg. CLAUDE.md adherence, bug, historical git context, etc.): + a. Agent #1: Audit the changes to make sure they comply with the CLAUDE.md. Note that CLAUDE.md is guidance for Claude as it writes code, so not all instructions will be applicable during code review. + b. Agent #2: Read the file changes in the pull request, then do a shallow scan for obvious bugs. Avoid reading extra context beyond the changes, focusing just on the changes themselves. Focus on large bugs, and avoid small issues and nitpicks. Ignore likely false positives. + c. Agent #3: Read the git blame and history of the code modified, to identify any bugs in light of that historical context. + d. Agent #4: Read previous pull requests that touched these files (`tea pulls ls --state all --remote origin` then cross-reference file paths), and check for any comments on those pull requests (`tea pulls review-comments --remote origin`) that may also apply to the current pull request. + e. Agent #5: Read code comments in the modified files, and make sure the changes in the pull request comply with any guidance in the comments. +5. For each issue found in #4, launch a parallel Haiku agent that takes the PR index, issue description, and list of CLAUDE.md files (from step 2), and returns a score to indicate the agent's level of confidence for whether the issue is real or false positive. To do that, the agent should score each issue on a scale from 0-100, indicating its level of confidence. For issues that were flagged due to CLAUDE.md instructions, the agent should double check that the CLAUDE.md actually calls out that issue specifically. The scale is (give this rubric to the agent verbatim): + a. 0: Not confident at all. This is a false positive that doesn't stand up to light scrutiny, or is a pre-existing issue. + b. 25: Somewhat confident. This might be a real issue, but may also be a false positive. The agent wasn't able to verify that it's a real issue. If the issue is stylistic, it is one that was not explicitly called out in the relevant CLAUDE.md. + c. 50: Moderately confident. The agent was able to verify this is a real issue, but it might be a nitpick or not happen very often in practice. Relative to the rest of the PR, it's not very important. + d. 75: Highly confident. The agent double checked the issue, and verified that it is very likely it is a real issue that will be hit in practice. The existing approach in the PR is insufficient. The issue is very important and will directly impact the code's functionality, or it is an issue that is directly mentioned in the relevant CLAUDE.md. + e. 100: Absolutely certain. The agent double checked the issue, and confirmed that it is definitely a real issue, that will happen frequently in practice. The evidence directly confirms this. +6. Filter out any issues with a score less than 80. If there are no issues that meet this criteria, do not proceed. +7. Use a Haiku agent to repeat the eligibility check from #1, to make sure that the pull request is still eligible for code review. +8. Finally, post the result back to the Gitea PR as a single comment using: + ```bash + printf '%s' "$BODY" | tea api --remote origin "/repos/{owner}/{repo}/issues//comments" -F body=@- + ``` + where `` is the PR index and `{owner}/{repo}` are substituted by `tea api` from repo context. Note the **`-F`** (typed field, reads stdin via `@-`) — NOT `-f`, which would post the literal string `@-`. Note the **`/repos/`** prefix on the endpoint. If stdin body is rejected, write `$BODY` to `/tmp/review-tea-body.md` and use `-F body=@/tmp/review-tea-body.md`. When writing `$BODY`, keep in mind that you must: + a. Keep your output brief + b. Avoid emojis + c. Link and cite relevant code, files, and URLs — using the **Gitea** link format (NOT GitHub): + `https://git.adlee.work/alee/vigilar/src/commit//#L-L` + Use the PR's head SHA (from step 1's JSON `headSha`), which is present on the remote. Never use a local-only / unpushed SHA — a commit not on the remote yields a 404 link even on a public repo. Never bash-substitute `$(git rev-parse HEAD)` into the rendered Markdown. Gitea uses `src/commit`, not `blob`. + +Examples of false positives, for steps 4 and 5: + +- Pre-existing issues +- Something that looks like a bug but is not actually a bug +- Pedantic nitpicks that a senior engineer wouldn't call out +- Issues that a linter, typechecker, or compiler would catch (eg. missing or incorrect imports, type errors, broken tests, formatting issues, pedantic style issues like newlines). No need to run these build steps yourself -- it is safe to assume that they will be run separately as part of CI. +- General code quality issues (eg. lack of test coverage, general security issues, poor documentation), unless explicitly required in CLAUDE.md +- Issues that are called out in CLAUDE.md, but explicitly silenced in the code (eg. due to a lint ignore comment) +- Changes in functionality that are likely intentional or are directly related to the broader change +- Real issues, but on lines that the user did not modify in their pull request + +Notes: + +- Do not check build signal or attempt to build or typecheck the app. These will run separately, and are not relevant to your code review. +- Use `tea` (NOT `gh`) to interact with Gitea (eg. to fetch a pull request, or to create comments), never web fetch. +- Make a todo list first +- You must cite and link each bug (eg. if referring to a CLAUDE.md, you must link it) +- For your final comment, follow the following format precisely (assuming for this example that you found 3 issues): + +--- + +### Code review + +Found 3 issues: + +1. (CLAUDE.md says "<...>") + +https://git.adlee.work/alee/vigilar/src/commit//#L13-L17 + +2. (some/other/CLAUDE.md says "<...>") + +https://git.adlee.work/alee/vigilar/src/commit//#L23-L28 + +3. (bug due to ) + +https://git.adlee.work/alee/vigilar/src/commit//#L44-L50 + +🤖 Generated with [Claude Code](https://claude.ai/code) + +- If this code review was useful, please react with 👍. Otherwise, react with 👎. + +--- + +- Or, if you found no issues: + +--- + +### Code review + +No issues found. Checked for bugs and CLAUDE.md compliance. + +🤖 Generated with [Claude Code](https://claude.ai/code) + +--- + +- When linking to code, follow this Gitea format precisely, otherwise the Markdown preview won't render correctly: `https://git.adlee.work/alee/vigilar/src/commit//#L-L` + - Requires the full git sha of a **remote-present** commit (the PR head SHA from step 1's JSON `headSha`). Never `$(git rev-parse HEAD)` substituted into the rendered comment, and never a local-only/unpushed SHA — those 404 even on a public repo + - Repo path must be `alee/vigilar` (matches the git remote) + - `#L` sign after the file name + - Line range format is `-` (Gitea uses `L1-L3`, same as GitHub but under `src/commit`) + - Provide at least 1 line of context before and after, centered on the line you are commenting about (eg. if commenting about lines 5-6, link to `L4-L7`) -- 2.49.1 From 571eb45b3ed630d9e49f0446c742d200f16c0baf Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 27 Jun 2026 14:07:42 -0400 Subject: [PATCH 10/11] fix(plugin): correct plugin layout + discovery model Per Claude Code plugin docs (code.claude.com/docs/en/plugins): - commands/ belongs at plugin ROOT, not inside .claude-plugin/ (only plugin.json goes in .claude-plugin/). Moved via git mv. - Repo-local .claude/plugins// is NOT auto-discovered. Load via `claude --plugin-dir` or `claude plugin init`. - Plugin commands are namespaced: invoke as /code-review-tea:code-review, not /code-review-tea. - Bake verified Task 2 facts into RESOLVED_INVOCATION content: -F not -f, /repos/ prefix required, tea pulls --fields diff empty (use git diff), SHA must be remote-present. Plan only (no plugin source changed beyond the dir move). Co-Authored-By: Claude Opus 4.8 (1M context) --- .../{.claude-plugin => }/commands/.gitkeep | 0 .../commands/code-review.md | 0 .../2026-06-27-code-review-tea-plugin.md | 162 ++++++++++-------- 3 files changed, 94 insertions(+), 68 deletions(-) rename .claude/plugins/code-review-tea/{.claude-plugin => }/commands/.gitkeep (100%) rename .claude/plugins/code-review-tea/{.claude-plugin => }/commands/code-review.md (100%) diff --git a/.claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep b/.claude/plugins/code-review-tea/commands/.gitkeep similarity index 100% rename from .claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep rename to .claude/plugins/code-review-tea/commands/.gitkeep diff --git a/.claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md b/.claude/plugins/code-review-tea/commands/code-review.md similarity index 100% rename from .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md rename to .claude/plugins/code-review-tea/commands/code-review.md diff --git a/docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md b/docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md index 4958377..ff60a27 100644 --- a/docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md +++ b/docs/superpowers/plans/2026-06-27-code-review-tea-plugin.md @@ -44,14 +44,16 @@ These were confirmed by probing the live `tea` 0.14.1 binary during planning — ``` .claude/plugins/code-review-tea/ ├── .claude-plugin/ -│ ├── plugin.json # the manifest (credits Anthropic/Boris Cherny) -│ └── commands/ -│ ├── code-review.md # the forked, tea-rewritten command -│ └── RESOLVED_INVOCATION.md # verified tea call notes (from Task 2) +│ └── plugin.json # the manifest (credits Anthropic/Boris Cherny) — ONLY file in .claude-plugin/ +├── commands/ +│ ├── code-review.md # the forked, tea-rewritten command (plugin root, NOT in .claude-plugin/) +│ └── RESOLVED_INVOCATION.md # verified tea call notes (from Task 2) └── README.md # what this fork is, why, how it differs ``` -Rationale: a project-local plugin under `.claude/plugins/` is version-controlled with the repo and applies only here (this is a Gitea-only repo; a global install would mis-fire on the user's GitHub-hosted repos). The name `code-review-tea` is distinct from the upstream `code-review` so it never shadows or confuses the GitHub plugin if that ever gets enabled elsewhere. +Rationale: per Claude Code's plugin spec, only `plugin.json` lives in `.claude-plugin/`; `commands/`, `skills/`, `agents/` live at the plugin root (verified against the upstream `code-review` and `superpowers` plugins). A project-local plugin under `.claude/plugins/` is version-controlled with the repo and applies only here. The name `code-review-tea` is distinct from the upstream `code-review` so it never shadows or confuses the GitHub plugin if that ever gets enabled elsewhere. + +**Discovery note (verified via docs):** a plugin placed in `/.claude/plugins//` is NOT auto-discovered by Claude Code. It loads explicitly via `claude --plugin-dir .claude/plugins/code-review-tea` (per-session) or by `claude plugin init` installing into `~/.claude/skills/code-review-tea/` (auto-loads as `code-review-tea@skills-dir`). plugin commands are namespaced, so the command is invoked as **`/code-review-tea:code-review`**, not `/code-review-tea`. We create **no** Python source changes and **no** test files — this is a tooling-only change. The `allowed-tools` substitution and command-file rewrite are the entire substance. @@ -61,7 +63,7 @@ We create **no** Python source changes and **no** test files — this is a tooli **Files:** - Create: `.claude/plugins/code-review-tea/.claude-plugin/plugin.json` -- Create: `.claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep` +- Create: `.claude/plugins/code-review-tea/commands/.gitkeep` - [ ] **Step 1: Create the plugin manifest** @@ -91,7 +93,7 @@ Create `.claude/plugins/code-review-tea/.claude-plugin/plugin.json`: - [ ] **Step 2: Create the commands directory placeholder** -Create `.claude/plugins/code-review-tea/.claude-plugin/commands/.gitkeep` as an empty file so the directory is tracked by git. +Create `.claude/plugins/code-review-tea/commands/.gitkeep` as an empty file so the directory is tracked by git. - [ ] **Step 3: Verify the directory tree** @@ -173,7 +175,7 @@ Make a mental/scratch note of: (a) which login-context flag worked (`--remote or The substantive change. Fork the upstream command, substitute the five `gh` contact points and the link format, keep the parallel-agent + confidence-score + 80-threshold logic identical, and add a header crediting the original. **Files:** -- Create: `.claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md` +- Create: `.claude/plugins/code-review-tea/commands/code-review.md` - [ ] **Step 1: Read the upstream command file for reference** @@ -185,7 +187,7 @@ Expected: the 93-line original. Keep it open; this is the template to fork. - [ ] **Step 2: Write the command file** -Create `.claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md`. The full content: +Create `.claude/plugins/code-review-tea/commands/code-review.md`. The full content: ````markdown --- @@ -305,7 +307,7 @@ No issues found. Checked for bugs and CLAUDE.md compliance. Run: ```bash -head -6 .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md +head -6 .claude/plugins/code-review-tea/commands/code-review.md ``` Expected: the `---` fence, `allowed-tools:` line containing only `Bash(tea ...:*), Bash(git ...:*)` entries (NO `gh`), then `description:` and `disable-model-invocation: false`, then closing `---`. @@ -313,70 +315,75 @@ Expected: the `---` fence, `allowed-tools:` line containing only `Bash(tea ...:* Run: ```bash -grep -nE '\bgh\b|github\.com|/blob/' .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md || echo "clean: no gh/github/blob references" +grep -nE '\bgh\b|github\.com|/blob/' .claude/plugins/code-review-tea/commands/code-review.md || echo "clean: no gh/github/blob references" ``` Expected: `clean: no gh/github/blob references`. If anything matches, fix it before committing. (Note: the credit comment intentionally mentions "GitHub/gh-only" to describe the upstream — that line references `gh` as a word, so adjust the grep if it fires on the credit line; the credit line is correct and should stay. The grep is meant to catch *operational* `gh` calls, which would look like `gh pr` or `gh issue`.) A more precise check: ```bash -grep -nE 'gh pr|gh issue|gh search|gh api|github\.com/alee/vigilar/blob|/blob/<' .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md || echo "clean: no operational gh calls or blob links" +grep -nE 'gh pr|gh issue|gh search|gh api|github\.com/alee/vigilar/blob|/blob/<' .claude/plugins/code-review-tea/commands/code-review.md || echo "clean: no operational gh calls or blob links" ``` Expected: `clean: no operational gh calls or blob links`. - [ ] **Step 5: Commit** ```bash -git add .claude/plugins/code-review-tea/.claude-plugin/commands/code-review.md +git add .claude/plugins/code-review-tea/commands/code-review.md git commit -m "feat(plugin): gitea/tea port of code-review command" ``` --- -## Task 4: Enable the plugin in this project's settings +## Task 4: Load and verify the plugin **Files:** -- Modify: `.claude/settings.json` +- No file changes in this task (the plugin files from Tasks 1 & 3 are already in place; `.claude/settings.json` is NOT modified — repo-local `.claude/plugins//` dirs are not auto-discovered, so an `enabledPlugins` entry would not load it). This task is about confirming the plugin loads and its command resolves. -- [ ] **Step 1: Read the current settings** +**Discovery model (verified via docs at https://code.claude.com/docs/en/plugins):** a plugin placed at `/.claude/plugins//` is NOT auto-discovered by Claude Code. Two ways to load it: +- **`--plugin-dir`** (per-session, recommended for this fork): launch Claude Code as `claude --plugin-dir .claude/plugins/code-review-tea`. The plugin loads for that session; its command is `/code-review-tea:code-review`. +- **`claude plugin init`** (persistent, user-scope): installs into `~/.claude/skills/code-review-tea/`, auto-loads on subsequent sessions as `code-review-tea@skills-dir` (no marketplace needed). This makes it available across all your projects, not just Vigilar — pick this only if you want that. + +plugin commands are namespaced, so the invocation is `/code-review-tea:code-review` (plugin name `:` command file name), NOT `/code-review-tea`. + +- [ ] **Step 1: Validate the plugin structure with the official validator** Run: ```bash -cat .claude/settings.json -``` -Expected: -```json -{ - "enabledPlugins": { - "superpowers@claude-plugins-official": true - } -} +claude plugin validate .claude/plugins/code-review-tea 2>&1 ``` +Expected: a success/valid report. If it reports a structural error (e.g. "commands/ must be at plugin root, not in .claude-plugin/"), fix the layout before proceeding. This catches exactly the nesting mistake that was corrected earlier (commands/ now at plugin root). If `claude plugin validate` is unavailable in your version, skip to Step 2 (the layout was already verified against the upstream `code-review` plugin in planning). -- [ ] **Step 2: Add the new plugin to enabledPlugins** - -Change `.claude/settings.json` to: - -```json -{ - "enabledPlugins": { - "superpowers@claude-plugins-official": true, - "code-review-tea@vigilar": true - } -} -``` - -The `@vigilar` suffix denotes a project-local (non-marketplace) plugin discovered from `.claude/plugins/code-review-tea/`. If Claude Code resolves local plugins by bare directory name (no `@source` suffix), drop it to `"code-review-tea": true`. Step 3 verifies which form is accepted. - -- [ ] **Step 3: Verify the plugin is discoverable** - -Restart/reload Claude Code for this project and run `/code-review-tea`. If the command is not found, Claude Code's local-plugin resolution may need the bare plugin name — change settings to `"code-review-tea": true` and re-verify. If still not found, confirm the plugin is discovered at all by checking whether `/code-review-tea` appears in the command list (if not, the loader may not scan `.claude/plugins/` — in that case, the plugin can still be invoked by directly reading the command file; document this fallback in the README). - -- [ ] **Step 4: Commit** +- [ ] **Step 2: Load the plugin for a session and confirm the command is registered** +Run: ```bash -git add .claude/settings.json -git commit -m "chore(plugin): enable project-local code-review-tea plugin" +claude --plugin-dir .claude/plugins/code-review-tea ``` +Then, inside that Claude Code session, run `/help` (or check the command list) and confirm `/code-review-tea:code-review` appears. Do NOT attempt to run the full review here — the smoke test (Task 6) does the end-to-end run. This step only confirms the command is registered and discoverable. + +If `/code-review-tea:code-review` does NOT appear: run `claude --plugin-dir .claude/plugins/code-review-tea --debug` (or whatever the version's verbose flag is) and read the plugin-load errors. Most likely cause at this point would be malformed `plugin.json` or `commands/code-review.md` frontmatter — re-validate in Step 1. + +- [ ] **Step 3: (Optional) Make it persistent via claude plugin init** + +If you want the plugin available in every session (not just when you remember `--plugin-dir`), install it to your skills directory: +```bash +claude plugin init code-review-tea +``` +This creates `~/.claude/skills/code-review-tea/` and loads it as `code-review-tea@skills-dir` on subsequent sessions. Only do this if you want Vigilar's review command available outside this repo too; otherwise rely on `--plugin-dir` and skip this step. + +- [ ] **Step 4: Commit the corrected layout (if not already committed)** + +The Tasks 1 & 3 commits placed `commands/` in the wrong nested location; the restructure moved it to plugin root via `git mv`. Commit that move if it's still staged: +```bash +git status --short +git add .claude/plugins/code-review-tea +git commit -m "fix(plugin): move commands/ to plugin root (correct structure)" +``` +Append the coauthor trailer (after a blank line): +``` +Co-Authored-By: Claude Opus 4.8 (1M context) +``` +If `git status` shows nothing to commit (already committed), skip. --- @@ -384,31 +391,40 @@ git commit -m "chore(plugin): enable project-local code-review-tea plugin" **Files:** - Create: `.claude/plugins/code-review-tea/README.md` -- Create: `.claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md` +- Create: `.claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md` - Modify: `CLAUDE.md` — append a short "## Code Review" subsection - [ ] **Step 1: Write the verified invocation notes** -Create `.claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md`. Fill in with the variants verified in Task 2 (replace `` placeholders with the actually-confirmed values): +Create `.claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md`. Fill in with the variants verified in Task 2 (replace `` placeholders with the actually-confirmed values): ```markdown # Resolved tea post-back invocation (verified via Task 2 smoke run) Gitea comment posting that survives large multi-line Markdown bodies: - tea api --remote origin "{owner}/{repo}/issues//comments" -f body=@- # body via stdin - # fallback: -f body=@/tmp/review-tea-body.md # body via file + tea api --remote origin "/repos/{owner}/{repo}/issues//comments" -F body=@- # body via stdin [VERIFIED] + # fallback: -F body=@/tmp/review-tea-body.md # body via file [VERIFIED] -Code link format (verify it renders in Gitea web): - https://git.adlee.work/alee/vigilar/src/commit//#L-L # path segment confirms src/commit +CRITICAL: use `-F` (typed field), NOT `-f`. `-f key=@file` posts the literal string `@file`; +only `-F key=@file` / `-F key=@-` reads the file/stdin. The endpoint MUST include the `/repos/` +prefix: `/repos/{owner}/{repo}/issues//comments` (without /repos/ it 404s). `tea api` already +prints JSON to stdout — do NOT pass `-o json` (that writes the body to a file named `json`). + +Code link format (verified to render / resolve to HTTP 200 when SHA is remote-present): + https://git.adlee.work/alee/vigilar/src/commit//#L-L # path segment src/commit [VERIFIED] Eligibility metadata fetch: - tea pulls --remote origin --fields state,draft,title,mergeable,base,head,body,diff -o json + tea pulls --remote origin --fields index,state,draft,title,mergeable,base,head,body -o json + # NOTE: tea v0.14.1 returns empty `diff`/`patch` fields even when requested — do not rely on them. -Diff source (preferred, local): - git diff origin/...origin/ +Diff source (preferred, local — the reliable source in this tea build): + git diff origin/...origin/ # base/head come from the PR JSON's base/head fields -Login context: the `alee` tea login is NOT default (tea login list shows default=false). +Already-reviewed check: + tea pulls review-comments --remote origin -o json # scan body for "### Code review" marker + +Login context: the `alee` tea login is NOT default (tea login list shows default=false). [VERIFIED: --remote origin resolves context; --login alee fallback not needed] ``` - [ ] **Step 2: Write the plugin README** @@ -432,7 +448,7 @@ Vigilar is hosted on a self-hosted Gitea instance (`git.adlee.work`), not GitHub On a branch with an open Gitea pull request against `main`: - /code-review-tea + /code-review-tea:code-review Claude will: - Verify the PR is reviewable (skip closed/draft/trivial/already-reviewed) @@ -449,18 +465,28 @@ Claude will: - The `alee` login need NOT be the default — the command passes `--remote origin` to resolve context - An open Gitea pull request to review +## Load (this plugin is NOT auto-discovered) + +A plugin placed in `/.claude/plugins//` is not auto-discovered by Claude Code. Load it explicitly: + + # per-session (recommended): + claude --plugin-dir .claude/plugins/code-review-tea + + # persistent, user-scope (across all your projects): + claude plugin init code-review-tea # installs to ~/.claude/skills/code-review-tea/ + ## Differences from upstream | Area | Upstream (GitHub) | This fork (Gitea) | |---|---|---| | CLI | `gh` | `tea` | | PR metadata | `gh pr view` | `tea pulls --fields ... -o json` | -| Diff | `gh pr diff` | `git diff origin/...origin/` (local) | -| Comment post | `gh pr comment --body` | `tea api {owner}/{repo}/issues//comments -f body=@-` | -| Code link | `github.com/o/r/blob/SHA/path#L` | `git.adlee.work/alee/vigilar/src/commit/SHA/path#L` | +| Diff | `gh pr diff` | `git diff origin/...origin/` (local; `tea pulls --fields diff` returns empty in 0.14.1) | +| Comment post | `gh pr comment --body` | `tea api /repos/{owner}/{repo}/issues//comments -F body=@-` (`-F` typed field reads stdin; `/repos/` prefix required) | +| Code link | `github.com/o/r/blob/SHA/path#L` | `git.adlee.work/alee/vigilar/src/commit/SHA/path#L` (SHA must be remote-present) | | Inline line comments | (upstream posts one summary comment) | NOT attempted — single summary comment only (Gitea inline-comment API needs `tea api` review endpoints; out of scope) | -See `.claude-plugin/commands/RESOLVED_INVOCATION.md` for the verified `tea` calls. +See `commands/RESOLVED_INVOCATION.md` for the verified `tea` calls. ```` - [ ] **Step 3: Append a Code Review subsection to CLAUDE.md** @@ -469,13 +495,13 @@ Append to `CLAUDE.md`, as a new `## Code Review` section near the existing `## C ```markdown ## Code Review -- `/code-review-tea` — review the current Gitea PR (project-local fork of Anthropic's code-review plugin, adapted from `gh` to `tea`; credit: Boris Cherny). See `.claude/plugins/code-review-tea/README.md`. +- `/code-review-tea:code-review` — review the current Gitea PR (project-local fork of Anthropic's code-review plugin, adapted from `gh` to `tea`; credit: Boris Cherny). Load via `claude --plugin-dir .claude/plugins/code-review-tea`. See `.claude/plugins/code-review-tea/README.md`. ``` - [ ] **Step 4: Commit** ```bash -git add .claude/plugins/code-review-tea/README.md .claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md CLAUDE.md +git add .claude/plugins/code-review-tea/README.md .claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md CLAUDE.md git commit -m "docs(plugin): document code-review-tea fork and CLAUDE.md note" ``` @@ -517,7 +543,7 @@ Expected: a new PR index. Record it as `$SMOKE`. - [ ] **Step 3: Run the adapted command against the scratch PR** -Run `/code-review-tea` and provide `$SMOKE` as the PR index. Watch for each stage: +Run `/code-review-tea:code-review` and provide `$SMOKE` as the PR index. Watch for each stage: - eligibility fetch via `tea pulls` ✓ - CLAUDE.md gather ✓ - summary ✓ @@ -553,9 +579,9 @@ git rm vigilar/_scratch_review.py 2>/dev/null && git commit -m "chore: remove re - [ ] **Step 7: Update RESOLVED_INVOCATION.md with the end-to-end confirmation** -Edit `.claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md` to replace each `` placeholder with the actual confirmed result from this smoke run (stdin worked vs file fallback, `--remote origin` resolved, `src/commit` rendered). Commit: +Edit `.claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md` to replace each `` placeholder with the actual confirmed result from this smoke run (stdin worked vs file fallback, `--remote origin` resolved, `src/commit` rendered). Commit: ```bash -git add .claude/plugins/code-review-tea/.claude-plugin/commands/RESOLVED_INVOCATION.md +git add .claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md git commit -m "docs(plugin): confirm resolved tea invocation from smoke test" ``` @@ -565,7 +591,7 @@ git commit -m "docs(plugin): confirm resolved tea invocation from smoke test" 1. **Spec coverage** — The user asked: make the `code-review` plugin work on Gitea (`tea`), name it `code-review-tea`, give credit to the original. → Tasks 1–6: scaffold, resolve invocation, write command, enable, document, smoke-test. Credit appears in `plugin.json` (contributors), command file header comment, and README. ✓ No hot-path review (dropped per revised scope). ✓ 2. **Placeholder scan** — Command file content is verbatim in Task 3 (full file with 4-backtick fence preserving inner 3-backtick fences). Test bodies are concrete (`is_armed` scratch bug). The only "verify which form" items (Task 4 Step 3 plugin discovery; Task 5 RESOLVED_INVOCATION `` placeholders) are real, intentional verifications — each has a concrete fallback and a step that resolves it, not an unfilled "TBD". -3. **Name consistency** — `code-review-tea` used consistently in directory, `plugin.json` `name`, settings key, README title, CLAUDE.md note, and `/code-review-tea` invocation. No leftover `supertea` or `code-review-gitea`. +3. **Name consistency** — `code-review-tea` used consistently in directory, `plugin.json` `name`, README title, and CLAUDE.md note. Command invoked as `/code-review-tea:code-review` (namespaced). No leftover `supertea` or `code-review-gitea`. No stale `.claude-plugin/commands/` nested paths. 4. **Credit correctness** — Original author Boris Cherny / Anthropic credited in `plugin.json` contributors, command file header comment, and README "Credit" section. Fork relationship stated (upstream = GitHub/gh-only). 5. **Uncertainty surfaced honestly** — `tea comment` vs `tea api` posting (Task 2 verifies, fallback documented); local-plugin `enabledPlugins` key form (Task 4 Step 3 verifies); Gitea `src/commit` path segment (Task 2/6 verifies render); `plugin.json` unknown-key tolerance (Task 1 Step 1 note + Task 6 smoke exercises loading). None silently assumed. ``` -- 2.49.1 From df4233f08f9525d306c5e6d5c34c0157525bc76c Mon Sep 17 00:00:00 2001 From: adlee-was-taken Date: Sat, 27 Jun 2026 14:11:04 -0400 Subject: [PATCH 11/11] docs(plugin): document code-review-tea fork and CLAUDE.md note Co-Authored-By: Claude Opus 4.8 (1M context) --- .claude/plugins/code-review-tea/README.md | 55 +++++++++++++++++++ .../commands/RESOLVED_INVOCATION.md | 26 +++++++++ CLAUDE.md | 3 + 3 files changed, 84 insertions(+) create mode 100644 .claude/plugins/code-review-tea/README.md create mode 100644 .claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md diff --git a/.claude/plugins/code-review-tea/README.md b/.claude/plugins/code-review-tea/README.md new file mode 100644 index 0000000..a27b7fb --- /dev/null +++ b/.claude/plugins/code-review-tea/README.md @@ -0,0 +1,55 @@ +# code-review-tea + +Project-local fork of Anthropic's `code-review` plugin, adapted from the GitHub CLI (`gh`) to the Gitea CLI (`tea`). + +## Credit + +This plugin is a fork of **Anthropic's `code-review` plugin** (author: **Boris Cherny**, `boris@anthropic.com`), from the `claude-plugins-official` marketplace. The upstream plugin is GitHub/`gh`-only. All credit for the review design — the 5 parallel specialized agents, confidence-based scoring, and false-positive filtering — belongs to the original. This fork changes only the Gitea contact points. + +## Why a fork + +Vigilar is hosted on a self-hosted Gitea instance (`git.adlee.work`), not GitHub. The upstream `code-review` plugin is hard-wired to `gh` (its `allowed-tools`, PR-fetching, and comment-posting all call `gh`), so it cannot run against this repo as-is. This fork substitutes the five `gh` contact points with `tea` equivalents and changes code-link URLs from GitHub's `blob/SHA/path#L` format to Gitea's `src/commit/SHA/path#L` format. + +## Usage + +On a branch with an open Gitea pull request against `main`: + + /code-review-tea:code-review + +Claude will: +- Verify the PR is reviewable (skip closed/draft/trivial/already-reviewed) +- Gather relevant CLAUDE.md files +- Summarize the change +- Launch 5 parallel review agents (CLAUDE.md compliance, bug scan, git-history context, prior-PR comments, in-code-comment compliance) +- Score each finding 0–100 for confidence +- Filter to findings ≥80 +- Post a single review comment back to the Gitea PR via `tea api` + +## Requirements + +- `tea` CLI (v0.14.1+) installed and logged in as `alee` against `https://git.adlee.work` +- The `alee` login need NOT be the default — the command passes `--remote origin` to resolve context +- An open Gitea pull request to review + +## Load (this plugin is NOT auto-discovered) + +A plugin placed in `/.claude/plugins//` is not auto-discovered by Claude Code. Load it explicitly: + + # per-session (recommended): + claude --plugin-dir .claude/plugins/code-review-tea + + # persistent, user-scope (across all your projects): + claude plugin init code-review-tea # installs to ~/.claude/skills/code-review-tea/ + +## Differences from upstream + +| Area | Upstream (GitHub) | This fork (Gitea) | +|---|---|---| +| CLI | `gh` | `tea` | +| PR metadata | `gh pr view` | `tea pulls --fields ... -o json` | +| Diff | `gh pr diff` | `git diff origin/...origin/` (local; `tea pulls --fields diff` returns empty in 0.14.1) | +| Comment post | `gh pr comment --body` | `tea api /repos/{owner}/{repo}/issues//comments -F body=@-` (`-F` typed field reads stdin; `/repos/` prefix required) | +| Code link | `github.com/o/r/blob/SHA/path#L` | `git.adlee.work/alee/vigilar/src/commit/SHA/path#L` (SHA must be remote-present) | +| Inline line comments | (upstream posts one summary comment) | NOT attempted — single summary comment only (Gitea inline-comment API needs `tea api` review endpoints; out of scope) | + +See `commands/RESOLVED_INVOCATION.md` for the verified `tea` calls. diff --git a/.claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md b/.claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md new file mode 100644 index 0000000..7ad5483 --- /dev/null +++ b/.claude/plugins/code-review-tea/commands/RESOLVED_INVOCATION.md @@ -0,0 +1,26 @@ +# Resolved tea post-back invocation (verified via Task 2 smoke run) + +Gitea comment posting that survives large multi-line Markdown bodies: + + tea api --remote origin "/repos/{owner}/{repo}/issues//comments" -F body=@- # body via stdin [VERIFIED] + # fallback: -F body=@/tmp/review-tea-body.md # body via file [VERIFIED] + +CRITICAL: use `-F` (typed field), NOT `-f`. `-f key=@file` posts the literal string `@file`; +only `-F key=@file` / `-F key=@-` reads the file/stdin. The endpoint MUST include the `/repos/` +prefix: `/repos/{owner}/{repo}/issues//comments` (without /repos/ it 404s). `tea api` already +prints JSON to stdout — do NOT pass `-o json` (that writes the body to a file named `json`). + +Code link format (verified to render / resolve to HTTP 200 when SHA is remote-present): + https://git.adlee.work/alee/vigilar/src/commit//#L-L # path segment src/commit [VERIFIED] + +Eligibility metadata fetch: + tea pulls --remote origin --fields index,state,draft,title,mergeable,base,head,body -o json + # NOTE: tea v0.14.1 returns empty `diff`/`patch` fields even when requested — do not rely on them. + +Diff source (preferred, local — the reliable source in this tea build): + git diff origin/...origin/ # base/head come from the PR JSON's base/head fields + +Already-reviewed check: + tea pulls review-comments --remote origin -o json # scan body for "### Code review" marker + +Login context: the `alee` tea login is NOT default (tea login list shows default=false). [VERIFIED: --remote origin resolves context; --login alee fallback not needed] diff --git a/CLAUDE.md b/CLAUDE.md index 9c87547..049668d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,3 +37,6 @@ DIY offline-first home security system. Python 3.11+, Flask + Bootstrap 5 dark t - `vigilar config validate` — check config - `pytest` — run tests - `ruff check vigilar/` — lint + +## Code Review +- `/code-review-tea:code-review` — review the current Gitea PR (project-local fork of Anthropic's code-review plugin, adapted from `gh` to `tea`; credit: Boris Cherny). Load via `claude --plugin-dir .claude/plugins/code-review-tea`. See `.claude/plugins/code-review-tea/README.md`. -- 2.49.1