diff --git a/AGENTS.md b/AGENTS.md index 984c64d..1900f8a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,89 +9,391 @@ Use third party libraries whenever there's a well-maintained, active, and widely Build extensible pieces of logic that can easily be integrated with other pieces. DRY principles should be loosely held. Architecture MUST be clear and well thought-out. Ask the user for clarification whenever ambiguity is discovered around architecture, or you think a better approach than planned exists. -Isolate development CLAUDE files/skills/agents/etc from the tools and prompts that will be used by the app. There should be no pollution of external Claude config with what the Ghost AI Assistant sees and uses. -## Beads Rust Workflow Integration +--- -This project uses [beads_viewer](https://github.com/Dicklesworthstone/beads_viewer) for issue tracking. Issues are stored in `.beads/` and tracked in git. +## Issue Tracking with br (beads_rust) -### Essential Commands +All issue tracking goes through **br** (beads_rust). No other TODO systems. + +Key invariants: + +- `.beads/` is authoritative state and **must always be committed** with code changes. +- Do not edit `.beads/*.jsonl` directly; only via `br`. +- **br is non-invasive**: it NEVER executes git commands. You must manually commit `.beads/` changes. + +### Basics + +Check ready work: ```bash -# View issues (launches TUI - NOT FOR AGENT USE, human only) -bv - -# CLI commands for agents (use --json for machine-readable output) -br ready --json # Show issues ready to work (no blockers) -br list --status=open --json # All open issues -br show --json # Full issue details with dependencies -br create --title="..." --type=task --priority=2 -br update --status=in_progress -br close --reason="Completed" -br close # Close multiple issues at once -br sync # Commit and push changes +br ready --json ``` -### Robot Mode (Agent-Optimized bv Commands) - -Use `bv --robot-*` flags for structured JSON output optimized for AI agents: +Create issues: ```bash -# Essential robot commands -bv --robot-triage # THE MEGA-COMMAND: unified analysis, recommendations, health -bv --robot-next # Single top recommendation (minimal output) -bv --robot-plan # Dependency-respecting execution plan -bv --robot-priority # Priority recommendations with reasoning -bv --robot-insights # Deep graph analysis (PageRank, bottlenecks, etc.) - -# File impact analysis (check before editing) -bv --robot-impact # Risk assessment for modifying files -bv --robot-file-beads # What beads have touched this file? -bv --robot-file-hotspots # High-churn files (conflict zones) -bv --robot-related # Find related beads - -# Filtering options (work with most robot commands) -bv --robot-triage --robot-by-label=backend -bv --robot-priority --robot-min-confidence=0.7 -bv --robot-insights --label=api # Scope to label subgraph +br create "Issue title" -t bug|feature|task -p 0-4 --json +br create "Issue title" -p 1 --deps discovered-from:bv-123 --json ``` -Run `bv -robot-help` for complete robot mode documentation. - -### Workflow Pattern - -1. **Start**: Run `br ready` to find actionable work -2. **Claim**: Use `br update --status=in_progress` -3. **Work**: Implement the task -4. **Complete**: Use `br close ` -5. **Sync**: Always run `br sync` at session end - -### Key Concepts - -- **Dependencies**: Issues can block other issues. `br ready` shows only unblocked work. -- **Priority**: P0=critical, P1=high, P2=medium, P3=low, P4=backlog (use numbers, not words) -- **Types**: task, bug, feature, epic, question, docs -- **Blocking**: `br dep add ` to add dependencies - -### Session Protocol - -**Before ending any session, run this checklist:** +Update: ```bash -git status # Check what changed -git add # Stage code changes -br sync # Commit beads changes -git commit -m "..." # Commit code -br sync # Commit any new beads changes -git push # Push to remote +br update bv-42 --status in_progress --json +br update bv-42 --priority 1 --json ``` -### Best Practices +Complete: -- Check `br ready` at session start to find available work -- Update status as you work (in_progress → closed) -- Create new issues with `br create` when you discover tasks -- Use descriptive titles and set appropriate priority/type -- Always `br sync` before ending session +```bash +br close bv-42 --reason "Completed" --json +``` + +Types: + +- `bug`, `feature`, `task`, `epic`, `chore` + +Priorities: + +- `0` critical (security, data loss, broken builds) +- `1` high +- `2` medium (default) +- `3` low +- `4` backlog + +Agent workflow: + +1. `br ready` to find unblocked work. +2. Claim: `br update --status in_progress`. +3. Implement + test. +4. If you discover new work, create a new bead with `discovered-from:`. +5. Close when done. +6. Sync and commit: + ```bash + br sync --flush-only # Export to JSONL (no git ops) + git add .beads/ # Stage beads changes + git commit -m "..." # Commit with code changes + ``` + +Never: + +- Use markdown TODO lists. +- Use other trackers. +- Duplicate tracking. + +--- + +## Using bv as an AI Sidecar + +bv is a graph-aware triage engine for Beads projects (.beads/beads.jsonl). Instead of parsing JSONL or hallucinating graph traversal, use robot flags for deterministic, dependency-aware outputs with precomputed metrics (PageRank, betweenness, critical path, cycles, HITS, eigenvector, k-core). + +**Scope boundary:** bv handles *what to work on* (triage, priority, planning). For multi-agent coordination (messaging, work claiming, file reservations), see the optional MCP Agent Mail section above. + +**⚠️ CRITICAL: Use ONLY `--robot-*` flags. Bare `bv` launches an interactive TUI that blocks your session.** + +### The Workflow: Start With Triage + +**`bv --robot-triage` is your single entry point.** It returns everything you need in one call: +- `quick_ref`: at-a-glance counts + top 3 picks +- `recommendations`: ranked actionable items with scores, reasons, unblock info +- `quick_wins`: low-effort high-impact items +- `blockers_to_clear`: items that unblock the most downstream work +- `project_health`: status/type/priority distributions, graph metrics +- `commands`: copy-paste shell commands for next steps + +```bash +bv --robot-triage # THE MEGA-COMMAND: start here +bv --robot-next # Minimal: just the single top pick + claim command +``` + +### Other Commands + +**Planning:** +| Command | Returns | +|---------|---------| +| `--robot-plan` | Parallel execution tracks with `unblocks` lists | +| `--robot-priority` | Priority misalignment detection with confidence | + +**Graph Analysis:** +| Command | Returns | +|---------|---------| +| `--robot-insights` | Full metrics: PageRank, betweenness, HITS, eigenvector, critical path, cycles, k-core, articulation points, slack | +| `--robot-label-health` | Per-label health: `health_level` (healthy\|warning\|critical), `velocity_score`, `staleness`, `blocked_count` | +| `--robot-label-flow` | Cross-label dependency: `flow_matrix`, `dependencies`, `bottleneck_labels` | +| `--robot-label-attention [--attention-limit=N]` | Attention-ranked labels by: (pagerank × staleness × block_impact) / velocity | + +**History & Change Tracking:** +| Command | Returns | +|---------|---------| +| `--robot-history` | Bead-to-commit correlations: `stats`, `histories` (per-bead events/commits/milestones), `commit_index` | +| `--robot-diff --diff-since ` | Changes since ref: new/closed/modified issues, cycles introduced/resolved | + +**Other Commands:** +| Command | Returns | +|---------|---------| +| `--robot-burndown ` | Sprint burndown, scope changes, at-risk items | +| `--robot-forecast ` | ETA predictions with dependency-aware scheduling | +| `--robot-alerts` | Stale issues, blocking cascades, priority mismatches | +| `--robot-suggest` | Hygiene: duplicates, missing deps, label suggestions, cycle breaks | +| `--robot-graph [--graph-format=json\|dot\|mermaid]` | Dependency graph export | +| `--export-graph ` | Self-contained interactive HTML visualization | + +### Scoping & Filtering + +```bash +bv --robot-plan --label backend # Scope to label's subgraph +bv --robot-insights --as-of HEAD~30 # Historical point-in-time +bv --recipe actionable --robot-plan # Pre-filter: ready to work (no blockers) +bv --recipe high-impact --robot-triage # Pre-filter: top PageRank scores +bv --robot-triage --robot-triage-by-track # Group by parallel work streams +bv --robot-triage --robot-triage-by-label # Group by domain +``` + +### Understanding Robot Output + +**All robot JSON includes:** +- `data_hash` — Fingerprint of source beads.jsonl (verify consistency across calls) +- `status` — Per-metric state: `computed|approx|timeout|skipped` + elapsed ms +- `as_of` / `as_of_commit` — Present when using `--as-of`; contains ref and resolved SHA + +**Two-phase analysis:** +- **Phase 1 (instant):** degree, topo sort, density — always available immediately +- **Phase 2 (async, 500ms timeout):** PageRank, betweenness, HITS, eigenvector, cycles — check `status` flags + +**For large graphs (>500 nodes):** Some metrics may be approximated or skipped. Always check `status`. + +### jq Quick Reference + +```bash +bv --robot-triage | jq '.quick_ref' # At-a-glance summary +bv --robot-triage | jq '.recommendations[0]' # Top recommendation +bv --robot-plan | jq '.plan.summary.highest_impact' # Best unblock target +bv --robot-insights | jq '.status' # Check metric readiness +bv --robot-insights | jq '.Cycles' # Circular deps (must fix!) +bv --robot-label-health | jq '.results.labels[] | select(.health_level == "critical")' +``` + +**Performance:** Phase 1 instant, Phase 2 async (500ms timeout). Prefer `--robot-plan` over `--robot-insights` when speed matters. Results cached by data hash. Use `bv --profile-startup` for diagnostics. + +Use bv instead of parsing beads.jsonl—it computes PageRank, critical paths, cycles, and parallel tracks deterministically. + +--- + +### Hybrid Semantic Search (CLI) + +`bv --search` supports hybrid ranking (text + graph metrics). + +```bash +# Default (text-only) +bv --search "login oauth" + +# Hybrid mode with preset +bv --search "login oauth" --search-mode hybrid --search-preset impact-first + +# Hybrid with custom weights +bv --search "login oauth" --search-mode hybrid \ + --search-weights '{"text":0.4,"pagerank":0.2,"status":0.15,"impact":0.1,"priority":0.1,"recency":0.05}' + +# Robot JSON output (adds mode/preset/weights + component_scores for hybrid) +bv --search "login oauth" --search-mode hybrid --robot-search +``` + +Env defaults: +- `BV_SEARCH_MODE` (text|hybrid) +- `BV_SEARCH_PRESET` (default|bug-hunting|sprint-planning|impact-first|text-only) +- `BV_SEARCH_WEIGHTS` (JSON string, overrides preset) + +--- + +### Static Site Export for Stakeholder Reporting + +Generate a static dashboard for non-technical stakeholders: + +```bash +# Interactive wizard (recommended) +bv --pages + +# Or export locally +bv --export-pages ./dashboard --pages-title "Sprint 42 Status" +``` + +The output is a self-contained HTML/JS bundle that: +- Shows triage recommendations (from --robot-triage) +- Visualizes dependencies +- Supports full-text search (FTS5) +- Works offline after initial load +- Requires no installation to view + +**Deployment options:** +- `bv --pages` → Interactive wizard for GitHub Pages deployment +- `bv --export-pages ./dir` → Local export for custom hosting +- `bv --preview-pages ./dir` → Preview bundle locally + +**For CI/CD integration:** +```bash +bv --export-pages ./bv-pages --pages-title "Nightly Build" +# Then deploy ./bv-pages to your hosting of choice +``` + +--- + +## ast-grep vs ripgrep + +**Use `ast-grep` when structure matters.** It parses code and matches AST nodes, so results ignore comments/strings, understand syntax, and can safely rewrite code. + +- Refactors/codemods: rename APIs, change patterns +- Policy checks: enforce patterns across a repo + +**Use `ripgrep` when text is enough.** Fastest way to grep literals/regex. + +- Recon: find strings, TODOs, config values +- Pre-filter: narrow candidates before precise pass + +**Go-specific examples:** + +```bash +# Find all error returns without wrapping +ast-grep run -l Go -p 'return err' + +# Find all fmt.Println (should use structured logging) +ast-grep run -l Go -p 'fmt.Println($$$)' + +# Quick grep for a function name +rg -n 'func.*LoadConfig' -t go + +# Combine: find files then match precisely +rg -l -t go 'sync.Mutex' | xargs ast-grep run -l Go -p 'mu.Lock()' +``` + +--- + +## Morph Warp Grep — AI-Powered Code Search + +**Use `mcp__morph-mcp__warp_grep` for exploratory "how does X work?" questions.** An AI search agent automatically expands your query into multiple search patterns, greps the codebase, reads relevant files, and returns precise line ranges. + +**Use `ripgrep` for targeted searches.** When you know exactly what you're looking for. + +| Scenario | Tool | +|----------|------| +| "How is graph analysis implemented?" | `warp_grep` | +| "Where is PageRank computed?" | `warp_grep` | +| "Find all uses of `NewAnalyzer`" | `ripgrep` | +| "Rename function across codebase" | `ast-grep` | + +**warp_grep usage:** +``` +mcp__morph-mcp__warp_grep( + repoPath: "/path/to/beads_viewer", + query: "How does the correlation package detect orphan commits?" +) +``` + +**Anti-patterns:** +- ❌ Using `warp_grep` to find a known function name → use `ripgrep` +- ❌ Using `ripgrep` to understand architecture → use `warp_grep` + +--- + +## UBS Quick Reference + +UBS = "Ultimate Bug Scanner" — static analysis for catching bugs early. + +**Golden Rule:** `ubs ` before every commit. Exit 0 = safe. Exit >0 = fix & re-run. + +```bash +ubs file.go file2.go # Specific files (< 1s) +ubs $(git diff --name-only --cached) # Staged files +ubs --only=go pkg/ # Go files only +ubs . # Whole project +``` + +**Output Format:** +``` +⚠️ Category (N errors) + file.go:42:5 – Issue description + 💡 Suggested fix +Exit code: 1 +``` + +**Fix Workflow:** +1. Read finding → understand the issue +2. Navigate `file:line:col` → view context +3. Verify real issue (not false positive) +4. Fix root cause +5. Re-run `ubs ` → exit 0 +6. Commit + +**Bug Severity (Go-specific):** +- **Critical**: nil dereference, division by zero, race conditions, resource leaks +- **Important**: error handling, type assertions without check +- **Contextual**: TODO/FIXME, unused variables + +--- + +## cass — Cross-Agent Session Search + +`cass` indexes prior agent conversations (Claude Code, Codex, Cursor, Gemini, ChatGPT, Aider, etc.) into a unified, searchable index so you can reuse solved problems. + +**NEVER run bare `cass`** — it launches an interactive TUI. Always use `--robot` or `--json`. + +### Quick Start + +```bash +# Check if index is healthy (exit 0=ok, 1=run index first) +cass health + +# Search across all agent histories +cass search "authentication error" --robot --limit 5 + +# View a specific result (from search output) +cass view /path/to/session.jsonl -n 42 --json + +# Expand context around a line +cass expand /path/to/session.jsonl -n 42 -C 3 --json + +# Learn the full API +cass capabilities --json # Feature discovery +cass robot-docs guide # LLM-optimized docs +``` + +### Key Flags + +| Flag | Purpose | +|------|---------| +| `--robot` / `--json` | Machine-readable JSON output (required!) | +| `--fields minimal` | Reduce payload: `source_path`, `line_number`, `agent` only | +| `--limit N` | Cap result count | +| `--agent NAME` | Filter to specific agent (claude, codex, cursor, etc.) | +| `--days N` | Limit to recent N days | + +**stdout = data only, stderr = diagnostics. Exit 0 = success.** + +### Robot Mode Etiquette + +- Prefer `cass --robot-help` and `cass robot-docs ` for machine-first docs +- The CLI is forgiving: globals placed before/after subcommand are auto-normalized +- If parsing fails, follow the actionable errors with examples +- Use `--color=never` in non-TTY automation for ANSI-free output + +### Pre-Flight Health Check + +```bash +cass health --json +``` + +Returns in <50ms: +- **Exit 0:** Healthy—proceed with queries +- **Exit 1:** Unhealthy—run `cass index --full` first + +### Exit Codes + +| Code | Meaning | Retryable | +|------|---------|-----------| +| 0 | Success | N/A | +| 1 | Health check failed | Yes—run `cass index --full` | +| 2 | Usage/parsing error | No—fix syntax | +| 3 | Index/DB missing | Yes—run `cass index --full` | + +Treat cass as a way to avoid re-solving problems other agents already handled. -