# Bug Hunter

> Adversarial bug hunting with a sequential-first pipeline (Recon, Hunter, Skeptic, Referee) that can optionally use safe read-only parallel triage. Finds, verifies, and auto-fixes real bugs by default (with --scan-only opt-out) using checkpointed verification and resume state for large codebases. Use this skill whenever the user wants bug finding, security audits, regression checks, or code review…

- **Type:** Skill
- **Install:** `agentstack add skill-codexstar69-bug-hunter-bug-hunter`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [codexstar69](https://agentstack.voostack.com/s/codexstar69)
- **Installs:** 0
- **Category:** [Developer Tools](https://agentstack.voostack.com/c/developer-tools)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [codexstar69](https://github.com/codexstar69)
- **Source:** https://github.com/codexstar69/bug-hunter

## Install

```sh
agentstack add skill-codexstar69-bug-hunter-bug-hunter
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Bug Hunt - Adversarial Bug Finding

Run a sequential-first adversarial bug hunt on your codebase. Use parallelism only for read-only triage and independent verification tasks.

## Table of Contents
- [Usage](#usage)
- [Target](#target)
- [Context Budget](#context-budget)
- [Execution Steps](#execution-steps)
- [Step 7: Present the Final Report](#step-7-present-the-final-report)
- [Self-Test Mode](#self-test-mode)
- [Error handling](#error-handling)

**Phase 1 — Find & Verify:**
```
Recon (map) --> Hunter (deep scan) --> Skeptic (challenge) --> Referee (final verdict)
                    ^                 (optional read-only dual-lens triage can run here)
                    |
             state + chunk checkpoints
```

**Phase 2 — Fix & Verify (default when bugs are confirmed):**
```
Baseline --> Git branch --> sequential Fixer (single writer) --> targeted verify --> full verify --> report
                    ^                                                              |
                    +------------------------ checkpoint commits + auto-revert -----+
```

For small scans (1-10 source files): runs single Hunter + single Skeptic (no parallelism overhead).
For large scans: process chunks sequentially with persistent state to avoid compaction drift.

## Usage

```
/bug-hunter                              # Scan entire project
/bug-hunter src/                         # Scan specific directory
/bug-hunter lib/auth.ts                  # Scan specific file
/bug-hunter -b feature-xyz              # Scan files changed in feature-xyz vs main
/bug-hunter -b feature-xyz --base dev   # Scan files changed in feature-xyz vs dev
/bug-hunter --pr                        # Easy alias for --pr current
/bug-hunter --pr current                # Review the current PR end to end
/bug-hunter --pr recent --scan-only     # Review the most recent PR without editing code
/bug-hunter --pr 123                    # Review a specific PR number
/bug-hunter --pr-security               # PR security review: PR scope + threat model + dependency scan
/bug-hunter --last-pr --review          # Easy mnemonic for “review the last PR”
/bug-hunter --review-pr                 # Alias for --pr current
/bug-hunter --staged                    # Scan staged files (pre-commit check)
/bug-hunter --scan-only src/            # Scan only, no code changes
/bug-hunter --review src/               # Easy alias for --scan-only
/bug-hunter --fix src/                   # Find bugs AND auto-fix them
/bug-hunter --plan-only src/             # Build fix strategy + plan, but do not edit files
/bug-hunter --plan src/                  # Easy alias for --plan-only
/bug-hunter --safe src/                  # Easy alias for --fix --approve
/bug-hunter --preview src/               # Easy alias for --fix --dry-run
/bug-hunter --autonomous src/            # Alias for no-intervention auto-fix run
/bug-hunter --fix -b feature-xyz        # Find + fix on branch diff
/bug-hunter --fix --approve src/        # Find + fix, but ask before each fix
/bug-hunter src/                         # Loops by default: audit + fix until all queued source files are covered
/bug-hunter --no-loop src/               # Single-pass only, no iterating
/bug-hunter --no-loop --scan-only src/   # Single-pass scan, no fixes, no loop
/bug-hunter --deps src/                 # Include dependency CVE scan
/bug-hunter --threat-model src/         # Generate/use STRIDE threat model
/bug-hunter --security-review src/      # Enterprise security workflow: threat model + CVEs + validation
/bug-hunter --validate-security src/    # Force vulnerability-validation for security findings
/bug-hunter --deps --threat-model src/  # Full security audit
/bug-hunter --fix --dry-run src/        # Preview fixes without editing files
```

## Target

The raw arguments are: $ARGUMENTS

**Parse the arguments as follows:**

0. Default `LOOP_MODE=true`. If arguments contain `--no-loop`: strip it from the arguments and set `LOOP_MODE=false`. The `--loop` flag is accepted for backwards compatibility but is a no-op (loop is already the default).

0b. Default `FIX_MODE=true`.
0c. If arguments contain `--scan-only`: strip it from the arguments and set `FIX_MODE=false`.
0d. If arguments contain `--fix`: strip it from the arguments and set `FIX_MODE=true`. The remaining arguments are parsed normally below.
0e. If arguments contain `--autonomous`: strip it from the arguments, set `AUTONOMOUS_MODE=true`, and force `FIX_MODE=true` (canary-first + confidence-gated).
0f. If arguments contain `--approve`: strip it from the arguments and set `APPROVE_MODE=true`. When this flag is set, Fixer agents run in `mode: "default"` (user reviews and approves each edit). When not set, `APPROVE_MODE=false` and Fixers run autonomously.
0g. If arguments contain `--deps`: strip it and set `DEP_SCAN=true`. Dependency scanning runs package manager audit tools and checks if vulnerable APIs are actually called in the codebase.
0h. If arguments contain `--threat-model`: strip it and set `THREAT_MODEL_MODE=true`. Generates a STRIDE threat model at `.bug-hunter/threat-model.md` if one doesn't exist, then feeds it to Recon + Hunter for targeted security analysis.
0i. If arguments contain `--dry-run`: strip it and set `DRY_RUN_MODE=true`. Forces `FIX_MODE=true`. In dry-run mode, Phase 2 builds the fix plan and the Fixer reads code and outputs planned changes as unified diff previews, but no file edits, git commits, or lock acquisition occur. Produces `fix-report.json` with `"dry_run": true`.
0j. If arguments contain `--preview`: strip it, set `DRY_RUN_MODE=true`, and force `FIX_MODE=true`. Treat it as a memorable alias for `--fix --dry-run`.
0k. If arguments contain `--plan-only`: strip it and set `PLAN_ONLY_MODE=true`. The pipeline still scans, verifies, and builds `fix-strategy.json` + `fix-plan.json`, but it stops before the Fixer edits code.
0l. If arguments contain `--plan`: strip it and set `PLAN_ONLY_MODE=true`. Treat it as a memorable alias for `--plan-only`.
0m. If arguments contain `--review-pr`: strip it and treat it as `--pr current`.
0n. If arguments contain `--pr` with no selector after it, treat it as `--pr current`.
0o. If arguments contain `--last-pr`: strip it and treat it as `--pr recent`.
0p. If arguments contain `--review`: strip it and set `FIX_MODE=false`. Treat it as a memorable alias for `--scan-only`.
0q. If arguments contain `--safe`: strip it, set `FIX_MODE=true`, and set `APPROVE_MODE=true`. Treat it as a memorable alias for `--fix --approve`.
0r. If arguments contain `--pr-security`: strip it, set `PR_SECURITY_MODE=true`, force `DEP_SCAN=true`, force `THREAT_MODEL_MODE=true`, force `FIX_MODE=false`, and if no explicit `--pr` selector was provided treat it as `--pr current`.
0s. If arguments contain `--security-review`: strip it, set `SECURITY_REVIEW_MODE=true`, force `DEP_SCAN=true`, force `THREAT_MODEL_MODE=true`, and force `FIX_MODE=false`.
0t. If arguments contain `--validate-security`: strip it and set `VALIDATE_SECURITY_MODE=true`.

1. If arguments contain `--pr `: this is **PR review mode**.
   - Valid selectors: `current`, `recent`, or a PR number like `123`.
   - If `--base ` is present, pass it through for current-branch git fallback.
   - Run:
     ```bash
     node "$SKILL_DIR/scripts/pr-scope.cjs" resolve "" --repo-root "$PWD" [--base ]
     ```
   - If it fails, report the error to the user and stop.
   - Save the JSON result to `.bug-hunter/pr-scope.json` for later reporting.
   - Use `changedFiles` from the JSON output as the scan target (scan full file contents, not just the diff).

2. If arguments contain `--staged`: this is **staged file mode**.
   - Run `git diff --cached --name-only` via a shell command to get the list of staged files.
   - If the command fails, report the error to the user and stop.
   - If no files are staged, tell the user there are no staged changes to scan and stop.
   - The scan target is the list of staged files (scan their full contents, not just the diff).

3. If arguments contain `-b `: this is **branch diff mode**.
   - Extract the branch name after `-b`.
   - If `--base ` is also present, use that as the base branch. Otherwise default to `main`.
   - Run `git diff --name-only ...` via a shell command to get the list of changed files.
   - If the command fails (e.g. branch not found), report the error to the user and stop.
   - If no files changed, tell the user there are no changes to scan and stop.
   - The scan target is the list of changed files (scan their full contents, not just the diff).

4. If arguments do NOT contain `--pr`, `-b`, or `--staged`: treat the entire argument string as a **path target** (file or directory). If empty, scan the current working directory.

**After resolving the file list (for modes 1, 2, and 3), filter out non-source files:**

Remove any files matching these patterns — they are not scannable source code:
- Docs/text: `*.md`, `*.txt`, `*.rst`, `*.adoc`
- Config: `*.json`, `*.yaml`, `*.yml`, `*.toml`, `*.ini`, `*.cfg`, `.env*`, `.gitignore`, `.editorconfig`, `.prettierrc*`, `.eslintrc*`, `tsconfig.json`, `jest.config.*`, `vitest.config.*`, `webpack.config.*`, `vite.config.*`, `next.config.*`, `tailwind.config.*`
- Lockfiles: `*.lock`, `*.sum`
- Minified/maps: `*.min.js`, `*.min.css`, `*.map`
- Assets: `*.svg`, `*.png`, `*.jpg`, `*.gif`, `*.ico`, `*.woff*`, `*.ttf`, `*.eot`
- Project meta: `LICENSE`, `CHANGELOG*`, `CONTRIBUTING*`, `CODE_OF_CONDUCT*`, `Makefile`, `Dockerfile`, `docker-compose*`, `Procfile`
- Vendor dirs: `node_modules/`, `vendor/`, `dist/`, `build/`, `.next/`, `__pycache__/`, `.venv/`

If after filtering there are zero source files left, tell the user: "No scannable source files found — only config/docs/assets were changed." and stop.

## Context Budget

**FILE_BUDGET is computed by the triage script (Step 1), not by Recon.** The triage script samples 30 files from the codebase, computes average line count, and derives:
```
avg_tokens_per_file = average_lines_per_file * 4
FILE_BUDGET = floor(150000 / avg_tokens_per_file)   # capped at 60, floored at 10
```

Triage also determines the strategy directly, so Step 3 just reads the triage output — no circular dependency.

Then determine partitioning:

| Total source files | Strategy | Hunters | Skeptics |
|--------------------|----------|---------|----------|
| 1 | Single-file mode | 1 general | 1 |
| 2-10 | Small mode | 1 general | 1 |
| 11 to FILE_BUDGET | Parallel mode (hybrid) | 1 deep Hunter (+ optional 2 read-only triage Hunters) | 1-2 by directory |
| FILE_BUDGET+1 to FILE_BUDGET*2 | Extended mode | Sequential chunked Hunters | 1-2 by directory |
| FILE_BUDGET*2+1 to FILE_BUDGET*3 | Scaled mode | Sequential chunked Hunters with resume state | 1-2 by directory |
| > FILE_BUDGET*3 | Large-codebase mode + Loop | Domain-scoped pipelines + boundary audits | Per-domain 1-2 |

If triage was not run (e.g., Recon was called directly without the orchestrator), use the default FILE_BUDGET of 40.

**File partitioning rules (Extended/Scaled modes):**
- **Service-aware partitioning (preferred)**: If Recon detected multiple service boundaries (monorepo), partition by service.
- **Risk-tier partitioning (fallback)**: process CRITICAL then HIGH then MEDIUM then LOW.
- Keep chunk size small (recommended 20-40 files) to avoid context compaction issues.
- Persist chunk progress in `.bug-hunter/state.json` so restarts do not re-scan done chunks.
- Test files (CONTEXT-ONLY) are included only when needed for intent.

If the triage output shows `needsLoop: true` and `LOOP_MODE=false` (user passed `--no-loop`), warn the user: "This codebase has [N] source files (FILE_BUDGET: [B]). Single-pass mode will only cover a subset. Loop mode is recommended for thorough coverage (remove `--no-loop` to enable). Large codebases use domain-scoped auditing — see `modes/large-codebase.md`."

## Execution Steps

### Step 0: Preflight checks

Before doing anything else, verify the environment:

1. **Resolve skill directory**: Determine `SKILL_DIR` dynamically.
   - Preferred: derive it from the absolute path of the current `SKILL.md` (`dirname` of this file).
   - Fallback probe order: `$HOME/.agents/skills/bug-hunter`, `$HOME/.claude/skills/bug-hunter`, `$HOME/.codex/skills/bug-hunter`, `$HOME/.cursor/skills/bug-hunter`, `$HOME/.kiro/skills/bug-hunter`, `$HOME/.copilot/skills/bug-hunter`, `$HOME/.windsurf/skills/bug-hunter`, `$HOME/.opencode/skills/bug-hunter`.
   - Use this path for ALL file reads and shell commands.

2. **Verify skill files exist**: Run `ls "$SKILL_DIR/skills/hunter/SKILL.md"` via Bash. If this fails, stop and tell the user: "Bug Hunter skill files not found. Reinstall the skill and retry."

3. **Node.js availability**: Run `node --version` via a shell command.
   - If available: set `NODEJS_AVAILABLE=true`. Full pipeline features enabled.
   - If NOT available: set `NODEJS_AVAILABLE=false`. Warn the user:
     "Node.js is not available. Schema validation, triage, doc-lookup, and experiment tracking will be skipped. The core pipeline (Recon -> Hunter -> Skeptic -> Referee) still works."
   - Continue the pipeline — the core analysis is LLM-driven and does not require Node.js.

3b. **Create output directory**:
    ```bash
    mkdir -p .bug-hunter/payloads .bug-hunter/domains
    ```
    This directory stores all pipeline artifacts. Add `.bug-hunter/` to your project's `.gitignore`.

4. **Doc lookup availability (optional, non-blocking)**: Run a quick smoke test:
   ```
   node "$SKILL_DIR/scripts/doc-lookup.cjs" search "express" "middleware"
   ```
   - If it returns results, set `DOC_LOOKUP_AVAILABLE=true`.
   - If it fails, try the fallback: `node "$SKILL_DIR/scripts/context7-api.cjs" search "express" "middleware"`
   - If both fail, warn the user and set `DOC_LOOKUP_AVAILABLE=false`.
   - Missing `CONTEXT7_API_KEY` must NOT block execution; anonymous lookups may still work.

5. **Verify helper scripts exist**:
   ```
   ls "$SKILL_DIR/scripts/run-bug-hunter.cjs" "$SKILL_DIR/scripts/bug-hunter-state.cjs" "$SKILL_DIR/scripts/delta-mode.cjs" "$SKILL_DIR/scripts/payload-guard.cjs" "$SKILL_DIR/scripts/fix-lock.cjs" "$SKILL_DIR/scripts/triage.cjs" "$SKILL_DIR/scripts/doc-lookup.cjs" "$SKILL_DIR/scripts/pr-scope.cjs"
   ```
   If any are missing, stop and tell the user to update/reinstall the skill.
   Note: `code-index.cjs` is optional — enables cross-domain dependency analysis for boundary audits in large-codebase mode, but the pipeline works fully without it.
   Note: `context7-api.cjs` is kept as a fallback — `doc-lookup.cjs` is the primary doc verification script.
   Note: `worktree-harvest.cjs` is optional — enables worktree-isolated Fixer dispatch for `subagent`/`teams` backends. Without it, Fixers edit directly on the fix branch (still safe via single-writer lock + auto-revert).

5b. **Check Context Hub CLI (recommended, non-blocking)**:
   ```bash
   chub --help 2>/dev/null && chub update 2>/dev/null
   ```
   - If `chub` is available, set `CHUB_AVAILABLE=true`. Report: `✓ Context Hub available — using curated docs for verification.`
   - If `chub` is NOT installed, set `CHUB_AVAILABLE=false`. **Warn the user visibly:**
     ```
     ⚠️ Context Hub (chub) is not installed. Doc verification will fall back to Context7 API,
        which has broader coverage but less curated results.

        For better doc verification accuracy, install Context Hub:
          npm install -g @aisuite/chub

        More info: https://github.com/andrewyng/context-hub
     ```
   - Do NOT block the pipeline — Context7 fallback works, just with less curated results.

6. **Select orchestration backend (cross-CLI portability)**:

   Detect which dispatch tools are available in your runtime. Use the FIRST that works:

   **Option A — `subagent` tool (Pi agent, preferred for parallel):**
   - Test: call `subagent({ action: "list" })`. If it returns without error, this backend works.
   - Set `AGENT_BACKEND = "subagent"`

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [codexstar69](https://github.com/codexstar69)
- **Source:** [codexstar69/bug-hunter](https://github.com/codexstar69/bug-hunter)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-codexstar69-bug-hunter-bug-hunter
- Seller: https://agentstack.voostack.com/s/codexstar69
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
