π¬ Ultimate Bug Scanner v5.0
The AI Coding Agentβs Secret Weapon: Flagging Likely Bugs for Fixing Early On
# One command to catch 1000+ bug patterns (always master, cache-busted)
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh?$(date +%s)" \
| bash -s --
Just want it to do everything without confirmations? Live life on the edge with easy-mode to auto-install every dependency, accept all prompts, detect local coding agents, and wire their quality guardrails with zero extra questions:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh?$(date +%s)" \
| bash -s -- --easy-mode
Note: Windows users must run the installer one-liner from within Git Bash, β¦
π¬ Ultimate Bug Scanner v5.0
The AI Coding Agentβs Secret Weapon: Flagging Likely Bugs for Fixing Early On
# One command to catch 1000+ bug patterns (always master, cache-busted)
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh?$(date +%s)" \
| bash -s --
Just want it to do everything without confirmations? Live life on the edge with easy-mode to auto-install every dependency, accept all prompts, detect local coding agents, and wire their quality guardrails with zero extra questions:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh?$(date +%s)" \
| bash -s -- --easy-mode
Note: Windows users must run the installer one-liner from within Git Bash, or use WSL for Windows.
π₯ The Problem: AI Moves Fast, Bugs Move Faster
Youβre coding faster than ever with Claude Code, Codex, Cursor, and other AI coding agents. Youβre shipping features in minutes that used to take days. But hereβs the painful truth:
Even the best AI makes these mistakes:
JavaScript/TypeScript example (similar patterns exist in Python, Go, Rust, Java, C++, Ruby):
// β CRITICAL BUG #1: Null pointer crash waiting to happen
const submitButton = document.getElementById('submit');
submitButton.addEventListener('click', handleSubmit); // π₯ Crashes if element doesn't exist
// β CRITICAL BUG #2: XSS vulnerability
function displayUserComment(comment) {
document.getElementById('comments').innerHTML = comment; // π¨ Security hole
}
// β CRITICAL BUG #3: Silent failure (missing await)
async function saveUser(data) {
const result = validateUser(data); // π₯ Should be 'await validateUser(data)'
await saveToDatabase(result); // Saves undefined!
}
// β CRITICAL BUG #4: Always false comparison
if (calculatedValue === NaN) { // π₯ This NEVER works (always false)
console.log("Invalid calculation");
}
// β CRITICAL BUG #5: parseInt footgun
const zipCode = parseInt(userInput); // π₯ "08" becomes 0 in old browsers (octal!)
Each of these bugs could cost 3-6 hours to debug in production. Similar issues plague every language: unguarded null access, missing await, security holes from eval(), buffer overflows from strcpy(), .unwrap() panics, goroutine leaks... Youβve probably hit all of them.
π― The Solution: Your 24/7 Bug Hunting Partner
π§ Language-Aware Meta-Runner
ubsauto-detects JavaScript/TypeScript, Python, C/C++, Rust, Go, Java, and Ruby in the same repo and fans out to per-language scanners.- Each scanner lives under
modules/ubs-<lang>.sh, ships independently, and supports--format text|json|jsonl|sariffor consistent downstream tooling. - Modules download lazily (PATH β repo
modules/β cached under${XDG_DATA_HOME:-$HOME/.local/share}/ubs/modules) and are validated before execution. - Results from every language merge into one text/JSON/SARIF report via
jq, so CI systems and AI agents only have to parse a single artifact.
π Supply-Chain Safeguards
- Every lazily-downloaded module ships with a pinned SHA-256 checksum baked into the meta-runner. Files fetched from GitHub are verified before they can execute, preventing tampering between releases.
- The cache lives under
${XDG_DATA_HOME:-$HOME/.local/share}/ubs/modulesby default; use--module-dirto relocate it (e.g., inside a CI workspace) while retaining the same verification guarantees. - Run
ubs doctorat any time to audit your environment. It checks for curl/wget availability, writable cache directories, and per-language module integrity. Add--fixto redownload missing or corrupted modules proactively. - Scanner runs still respect
--update-modules, but an invalid checksum now causes an immediate failure with remediation guidance rather than executing unverified code.
π Category Packs & Shareable Reports
--category=resource-lifecyclefocuses the scanners on Python/Go/Java resource hygiene (context managers, defer symmetry, try-with-resources). UBS automatically narrows the language set to those with lifecycle packs enabled and suppresses unrelated categories.--comparison=<baseline.json>diff the latest combined summary against a stored run. Deltas feed into console output, JSON, HTML, and SARIF automation metadata so CI can detect regressions.--report-json=<file>writes an enriched summary (project, totals, git metadata, optional comparison block) that you can archive or share with teammates/CI.--html-report=<file>emits a standalone HTML preview showing totals, trends vs. baseline, and per-language breakdownsβideal for attaching to PRs or chat updates.- All shareable outputs inject GitHub permalinks when UBS is run inside a git repo with a GitHub remote. Text output automatically annotates
path:linereferences, JSON gainsgit.*metadata, and merged SARIF runs now includeversionControlProvenanceplusautomationDetailskeyed by the comparison id.
Resource lifecycle heuristics in each language
- Python β Category 16 now correlates every
open()call against matchingwith open(...)usage and explicitencoding=parameters, while Category 19 uses the new AST helper atmodules/helpers/resource_lifecycle_py.pyto walk every file, socket, subprocess, asyncio task, and context cancellation path. The helper resolves alias imports, context managers, and awaited tasks so the diff counts (acquire=X, release=Y, context-managed=Z) show the exact imbalance per file. - Go β Category 5/17 now run a Go AST walker (
modules/helpers/resource_lifecycle_go.go) that detectscontext.With*calls missing cancel,time.NewTicker/NewTimerwithoutStop,os.Open/sql.OpenwithoutClose, and mutexLock/Unlocksymmetry. Findings come straight from the AST positions, so βticker missing Stop()β lines map to the exactfile:lineinstead of coarse regex summaries. - Java β Category 5 surfaces
FileInputStream, readers/writers, JDBC handles, etc. that were created outside try-with-resources, while Category 19 keeps tracking executor services and file streams that never close. The new summary text matches the manifest fixtures, so CI will fail if regression swallows these warnings.
Shareable output quickstart
# 1) Capture a baseline JSON (checked into CI artifacts or local history)
ubs --ci --only=python --category=resource-lifecycle \
--report-json .ubs/baseline.json test-suite/python/buggy
# 2) Re-run with comparison + HTML preview for PRs or chat threads
ubs --ci --only=python --category=resource-lifecycle \
--comparison .ubs/baseline.json \
--report-json .ubs/latest.json \
--html-report .ubs/latest.html \
test-suite/python/buggy
latest.json now contains the git metadata (repo URL, commit, blob_base) plus a comparison.delta block, and latest.html renders a lightweight dashboard summarising the deltas. SARIF uploads also pick up the comparison id so repeating runs in CI stay grouped by automation id.
π‘ Basic Usage
# Scan current directory
ubs .
# Scan specific directory
ubs /path/to/your/project
# Verbose mode (show more code examples)
ubs -v .
# Save report to file
ubs . bug-report.txt
# CI mode (exit code 1 on warnings)
ubs . --fail-on-warning
# Quiet mode (summary only)
ubs -q .
# Skip specific categories (e.g., skip TODO markers)
ubs . --skip=11,14
# Custom file extensions
ubs . --include-ext=js,ts,vue,svelte
Handy switches
# Git-aware quick scans (changed files only)
ubs --staged # Scan files staged for commit
ubs --diff # Scan working tree changes vs HEAD
# Strictness profiles
ubs --profile=strict # Fail on warnings, enforce high standards
ubs --profile=loose # Skip TODO/debug/code-quality nits when prototyping
# Machine-readable output
ubs . --format=json # Pure JSON on stdout; logs go to stderr
ubs . --format=jsonl # Line-delimited summary per scanner + totals
ubs . --format=jsonl --beads-jsonl out/findings.jsonl # Save JSONL for Beads/"strung"
Keeping noise low
- UBS auto-ignores common junk (
node_modules, virtualenvs, dist/build/target/vendor, editor caches, etc.). - Inline suppression is available when a finding is intentional:
eval("print('safe')") # ubs:ignore
π Quick Install (30 Seconds)
Option 1: Automated Install (Recommended)
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh?$(date +%s)" | bash
Option 2: Integrity-first install (signed checksums)
export UBS_MINISIGN_PUBKEY="RWQg+jMrKiloMT5L3URISMoRzCMc/pVcVRCTfuY+WIzttzIr4CUJYRUk"
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/scripts/verify.sh | bash
The verifier downloads SHA256SUMS + SHA256SUMS.minisig from the matching release, validates them with minisign, checks install.sh, and only then executes it. Use --insecure to bypass verification (not recommended).
Option 3: Nix
Run directly (no install):
nix run github:Dicklesworthstone/ultimate_bug_scanner
Dev shell for contributors:
nix develop
Option 4: Docker / OCI
Pull & inspect:
docker run --rm ghcr.io/dicklesworthstone/ubs-tools ubs --help
Scan host code (risk-aware: grants container access to host FS):
docker run --rm -v /:/host ghcr.io/dicklesworthstone/ubs-tools bash -c "cd /host/path && ubs ."
β οΈ Use the host-mount pattern only when you understand the write-access implications.
Deployment & Security
- Release playbook (how we cut signed releases): docs/release.md
- Supply chain & verification model: docs/security.md
The installer will:
- β
Install the
ubscommand globally - β
Optionally install
ast-grep(for advanced AST analysis) - β
Optionally install
ripgrep(for 10x faster scanning) - β
Optionally install
jq(needed for JSON/SARIF merging across all language scanners) - β
Optionally install
typos(smart spellchecker for docs and identifiers) - β
Optionally install
Node.js + typescript(enables deep TypeScript type narrowing analysis) - β
Auto-run
ubs doctorpost-install and append a session summary to~/.config/ubs/session.md - β
Capture readiness facts (ripgrep/jq/typos/type narrowing) and store them for
ubs sessions --entries 1 - β Set up git hooks (block commits with critical bugs)
- β Set up Claude Code hooks (scan on file save)
- β Add documentation to your AGENTS.md
Need to revisit what the installer discovered later? Run ubs sessions --entries 1 to view the most recent session log (or point teammates at the same summary).
Need the βjust make it workβ button? Run the installer with --easy-mode to auto-install every dependency, accept all prompts, detect local coding agents, and wire their quality guardrails with zero extra questions:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh?$(date +%s)" \
| bash -s -- --easy-mode
Total time: 30 seconds to 2 minutes (depending on dependencies)
Need to keep your shell RC files untouched? Combine --no-path-modify (and optionally --skip-hooks) with the command aboveβthe installer will still drop ubs into your chosen --install-dir, but it will skip both PATH edits and the alias helper entirely.
Option 2: Manual Install
# Download and install the unified runner
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/ubs \
-o /usr/local/bin/ubs && chmod +x /usr/local/bin/ubs
# Verify it works
ubs --help
# Optional but recommended: Install dependencies
npm install -g @ast-grep/cli # AST-based analysis
brew install ripgrep # 10x faster searching (or: apt/dnf/cargo install)
brew install typos-cli # Spellchecker tuned for code (or: cargo install typos-cli)
npm install -g typescript # Enables full tsserver-based type narrowing checks
Option 3: Use Without Installing
# Download once
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/ubs \
-o ubs && chmod +x ubs
# Run it
./ubs .
Installer Safety Nets
Uninstall from any shell
Run the installer in --uninstall mode via curl if you want to remove UBS and all of its integrations:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh?$(date +%s)" | bash -s -- --uninstall --non-interactive
This command deletes the UBS binary, shell RC snippets/aliases, config under ~/.config/ubs, and the optional Claude/Git hooks that the installer set up. Because it passes --non-interactive, it auto-confirms all prompts and runs unattended.
| Flag | What it does | Why it matters |
|---|---|---|
--dry-run | Prints every install action (downloads, PATH edits, hook writes, cleanup) without touching disk. Dry runs still resolve config, detect agents, and show you exactly what would change. | Audit the installer, demo it to teammates, or validate CI steps without modifying a workstation. |
--self-test | Immediately runs test-suite/install/run_tests.sh after installation and exits non-zero if the smoke suite fails. | CI/CD jobs and verified setups can prove the installer still works end-to-end before trusting a release. |
--skip-type-narrowing | Skip the Node.js + TypeScript readiness probe and the cross-language guard analyzers (JS/Rust/Kotlin/Swift). | Useful for air-gapped hosts or environments that want to stay in heuristic-only mode. |
--skip-typos | Skip the Typos spellchecker installation + diagnostics. | Handy when corp images already provide Typos or when you deliberately disable spellcheck automation. |
--skip-doctor | Skip the automatic ubs doctor run + session summary after install. | Use when CI already runs doctor separately or when youβre iterating locally and want a faster finish. |
Warning
--self-test requires running install.sh from a working tree that contains test-suite/install/run_tests.sh (i.e., the repo root). Curl-piping the installer from GitHub canβt self-test because the harness isnβt present, so the flag will error out early instead of giving a false sense of safety.
Note
After every install the script now double-checks command -v ubs. If another copy shadows the freshly written binary, youβll get an explicit warning with both paths so you can fix PATH order before running scans.
Tip
Type narrowing relies on Node.js plus the typescript npm package and the Python helpers that power the Rust/Kotlin/Swift checks. The installer now checks Node/TypeScript readiness, can optionally run npm install -g typescript, and surfaces the status inside install.sh --diagnose. Use --skip-type-narrowing if youβre on an air-gapped host or plan to keep the heuristic-only mode.
Tip
To avoid global npm permission issues, the installer now detects/installs bun just like other dependencies and uses bun install --global typescript by default, falling back to npm only if bun isnβt available.
The diagnostics also call out Swift guard readiness: if python3 is available we count .swift files under your repo and record whether the guard helper will actually run. That fact shows up in install.sh --diagnose output and the auto-generated session log so iOS/macOS teams can tell at a glance whether the ObjC-bridging heuristics are active.
Common combos
# Preview everything without touching dotfiles or hooks
bash install.sh --dry-run --no-path-modify --skip-hooks --non-interactive
# CI-friendly install that self-tests the smoke harness
bash install.sh --easy-mode --self-test --skip-hooks
π Auto-Update
The ubs meta-runner automatically checks for updates once every 24 hours. If a new version is available, it self-updates securely before running your scan.
To disable this behavior (e.g., in strict environments):
export UBS_NO_AUTO_UPDATE=1
# or
ubs --no-auto-update .
Ultimate Bug Scanner is like having a senior developer review every line of code in under 5 seconds; itβs the perfect automated companion to your favorite coding agent:
$ ubs .
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π¬ ULTIMATE BUG SCANNER v4.4 - Scanning your project... β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Project: /Users/you/awesome-app
Files: 247 JS/TS + 58 Python + 24 Go + 16 Java + 11 Ruby + 12 C++/Rust files
Finished: 3.2 seconds
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Summary Statistics:
Files scanned: 247
π₯ Critical: 0 β Would have crashed in production!
β οΈ Warnings: 8 β Should fix before shipping
βΉοΈ Info: 23 β Code quality improvements
β¨ EXCELLENT! No critical issues found β¨
β‘ Why Developers + AI Agents Will Love This Tool
π 1. Catches What Humans & AI Miss
18 specialized detection categories covering the bugs that actually matter:
Category What It Prevents Time Saved Per Bug Null Safety βCannot read property of undefinedβ crashes 2-4 hours Security Holes XSS, code injection, prototype pollution 8-20 hours + reputation damage Async/Await Bugs Race conditions, unhandled rejections 4-8 hours Memory Leaks Event listeners, timers, detached DOM 6-12 hours Type Coercion JavaScriptβs === vs == madness 1-3 hours + 13 more categories 100+ hours/month saved
π¨ 2. Blazing Fast (Because Your Time Matters)
Small project (5K lines): 0.8 seconds β‘
Medium project (50K lines): 3.2 seconds π
Large project (200K lines): 12 seconds π¨
Huge project (1M lines): 58 seconds π
Thatβs 10,000+ lines analyzed per second. Faster than you can say βbut it worked on my machine.β
π€ 3. Built FOR AI Agents, BY Developers Who Use AI
Unlike traditional linters that fight AI-generated code, this scanner embraces it:
β
Designed for Claude Code, Cursor, Windsurf, Aider, Continue, Copilot
β
Zero configuration - works with ANY JS/TS, Python, C/C++, Rust, Go, Java, or Ruby project
β
Integrates with git hooks, CI/CD, file watchers
β
Actionable output (tells you WHAT's wrong and HOW to fix it)
β
Fails fast in CI (catch bugs before they merge)
β
React Hooks dependency analysis that spots missing deps, unstable objects, and stale closures
β
Lightweight taint analysis that traces req.body/window.location/localStorage β innerHTML/res.send/eval/exec/db.query and flags flows without DOMPurify/escapeHtml/parameterized SQL
π 4. Real-World Impact
| Scenario | Without Scanner | With Scanner |
|---|---|---|
| AI implements user auth | β’ 3 null pointer crashes (9h debugging) β’ 1 XSS vulnerability (8h + incident) β’ 2 race conditions (4h debugging) Total: ~21 hours + security incident | β’ All issues caught in 4 seconds β’ Fixed before commit (15 min) Total: 15 minutes Savings: 84x faster β‘ |
| Refactor payment flow | β’ Division by zero in edge case (3h) β’ Unhandled promise rejection (2h) β’ Missing error logging (1h) Total: 6 hours debugging | β’ Caught instantly (3 sec) β’ Fixed before merge (10 min) Total: 10 minutes Savings: 36x faster π |
π€ AI Agent Integration (The Real Magic)
On-Device Agent Guardrails
install.sh now inspects your workstation for the most common coding agents (the same set listed below) and, when asked, drops guardrails that remind those agents to run ubs --fail-on-warning . before claiming a task is done. In --easy-mode this happens automatically; otherwise you can approve each integration individually.
| Agent / IDE | What we wire up | Why it helps |
|---|---|---|
Claude Code Desktop (.claude/hooks/on-file-write.sh) | File-save hook that shells out to ubs --ci whenever Claude saves JS/TS files. | Keeps Claude from accepting βApply Patchβ without a fresh scan. |
Cursor (.cursor/rules) | Shared rule block that tells Cursor plans/tasks to run ubs --fail-on-warning . and summarize outstanding issues. | Cursorβs autonomous jobs inherit the same QA checklist as humans. |
Codex CLI (.codex/rules) | Adds the identical rule block for Anthropicβs Codex terminal workflow. | Ensures Codex sessions never skip the scanner during long refactors. |
Gemini Code Assist (.gemini/rules) | Guidance instructing Gemini agents to run ubs before closing a ticket. | Keeps Geminiβs asynchronous fixes aligned with UBS exit criteria. |
Windsurf (.windsurf/rules) | Guardrail text + sample command palette snippet referencing ubs. | Windsurfβs multi-step plans stay grounded in the same quality gate. |
Cline (.cline/rules) | Markdown instructions that Clineβs VS Code extension ingests. | Forces every βtool callβ from Cline to mention scanner findings. |
OpenCode MCP (.opencode/rules) | Local MCP instructions so HTTP tooling always calls ubs before replying. | Makes OpenCodeβs multi-agent swarms share the same notion of βdoneβ. |
Why This Matters for AI Workflows
When youβre coding with AI, youβre moving 10-100x faster than traditional development. But bugs accumulate just as quickly. Traditional tools slow you down. This scanner keeps pace:
Traditional workflow: AI-powered workflow with scanner:
ββββββββββββββββββββ ββββββββββββββββββββ
β AI writes code β β AI writes code β
ββββββββββ¬ββββββββββ ββββββββββ¬ββββββββββ
β β
β β
ββββββββββββββββββββ ββββββββββββββββββββ
β You review β β Scanner runs β
β (15 min) β β (3 seconds) β
ββββββββββ¬ββββββββββ ββββββββββ¬ββββββββββ
β β
β β
ββββββββββββββββββββ ββββββββββββββββββββ
β Tests pass? β β Critical bugs? β
ββββββββββ¬ββββββββββ ββββββββββ¬ββββββββββ
β NO! β YES!
β β
ββββββββββββββββββββ ββββββββββββββββββββ
β Debug in prod β β AI fixes them β
β (6 hours) β β (5 minutes) β
ββββββββββββββββββββ ββββββββββ¬ββββββββββ
β
ββββββββββββββββββββ
β Ship with β
β confidence β
ββββββββββββββββββββ
Total: 6.25 hours Total: 8 minutes
Pattern 1: Claude Code Integration (Real-Time Scanning)
Drop this into .claude/hooks/on-file-write.sh:
#!/bin/bash
# Auto-scan UBS-supported languages (JS/TS, Python, C/C++, Rust, Go, Java, Ruby) on save
if [[ "$FILE_PATH" =~ \.(js|jsx|ts|tsx|mjs|cjs|py|pyw|pyi|c|cc|cpp|cxx|h|hh|hpp|hxx|rs|go|java|rb)$ ]]; then
echo "π¬ Quality check running..."
if ubs "${PROJECT_DIR}" --ci 2>&1 | head -30; then
echo "β
No critical issues"
else
echo "β οΈ Issues detected - review above"
fi
fi
Result: Every time Claude writes code, the scanner catches bugs instantly.
Pattern 2: Git Pre-Commit Hook (Quality Gate)
The installer can set this up automatically, or add to .git/hooks/pre-commit:
#!/bin/bash
# Block commits with critical bugs
echo "π¬ Running bug scanner..."
if ! ubs . --fail-on-warning 2>&1 | tee /tmp/scan.txt | tail -30; then
echo ""
echo "β Critical issues found. Fix them or use: git commit --no-verify"
echo ""
echo "Top issues:"
grep -A 3 "π₯ CRITICAL" /tmp/scan.txt | head -20
exit 1
fi
echo "β
Quality check passed - committing..."
Result: Bugs cannot be committed. Period.
Pattern 3: Cursor/Windsurf/Continue Integration
Add to your .cursorrules or similar:
## Code Quality Standards
Before marking any task as complete:
1. Run the bug scanner: `ubs .`
2. Fix ALL critical issues (π₯)
3. Review warnings (β οΈ) and fix if trivial
4. Only then mark task complete
If the scanner finds critical issues, your task is NOT done.
Result: AI agents have built-in quality standards.
Pattern 4: CI/CD Pipeline (GitHub Actions Example)
name: Code Quality Gate
on: [push, pull_request]
jobs:
bug-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Bug Scanner
run: |
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh?$(date +%s)" | bash -s -- --non-interactive
- name: Scan for Bugs
run: |
ubs . --fail-on-warning --ci
Result: Pull requests with critical bugs cannot merge.
Pattern 5: The Fix-Verify Loop (For AI Agents)
This is the golden pattern for AI coding workflows:
#!/bin/bash
# Have your AI agent run this after implementing features
echo "π¬ Post-implementation quality check..."
# Run scanner
if ubs . --fail-on-warning > /tmp/scan-result.txt 2>&1; then
echo "β
All quality checks passed!"
echo "π Ready to commit"
exit 0
else
echo "β Issues found:"
echo ""
# Show critical issues
grep -A 5 "π₯ CRITICAL" /tmp/scan-result.txt | head -30
echo ""
echo "π€ AI: Please fix these issues and re-run this check"
exit 1
fi
Usage pattern:
User: "Add user registration with email validation"
AI Agent:
1. Implements the feature
2. Runs quality check (scanner finds 3 critical bugs)
3. Fixes the bugs
4. Re-runs quality check (passes)
5. Commits the code
Total time: 12 minutes (vs. 6 hours debugging in production)
Pattern 6: The βAI Agent Decision Treeβ
Train your AI agent to use this decision tree:
Did I modify code in any supported language?
(JS/TS, Python, Go, Rust, Java, C++, Ruby)
β
β YES
Changed more than 50 lines?
β
β YES
Run scanner ββββββββββββ
β β
β β
Critical issues found? βββββ€ YES
β NO β
β β
Warnings? β
β β
β YES β
Show to user β
Ask if should fix ββββββββ€
β NO β
β β
Commit code Fix issues
Important
Copy the blurb below to your projectβs AGENTS.md, .claude/claude_docs/, or .cursorrules file for comprehensive UBS integration guidance.
## UBS Quick Reference for AI Agents
UBS stands for "Ultimate Bug Scanner": **The AI Coding Agent's Secret Weapon: Flagging Likely Bugs for Fixing Early On**
**Install:** `curl -sSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/main/install.sh | bash`
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
**Commands:**
```bash
ubs file.ts file2.py # Specific files (< 1s) β USE THIS
ubs $(git diff --name-only --cached) # Staged files β before commit
ubs --only=js,python src/ # Language filter (3-5x faster)
ubs --ci --fail-on-warning . # CI mode β before PR
ubs --help # Full command reference
ubs sessions --entries 1 # Tail the latest install session log
ubs . # Whole project (ignores things like .venv and node_modules automatically)
Output Format:
β οΈ Category (N errors)
file.ts:42:5 β Issue description
π‘ Suggested fix
Exit code: 1
Parse: file:line:col β location | π‘ β how to fix | Exit 0/1 β pass/fail
Fix Workflow:
- Read finding β category + fix suggestion
- Navigate
file:line:colβ view context - Verify real issue (not false positive)
- Fix root cause (not symptom)
- Re-run
ubs <file>β exit 0 - Commit
Speed Critical: Scope to changed files. ubs src/file.ts (< 1s) vs ubs . (30s). Never full scan for small edits.
Bug Severity:
- Critical (always fix): Null safety, XSS/injection, async/await, memory leaks
- Important (production): Type narrowing, division-by-zero, resource leaks
- Contextual (judgment): TODO/FIXME, console logs
Anti-Patterns:
- β Ignore findings β β Investigate each
- β Full scan per edit β β Scope to file
- β Fix symptom (
if (x) { x.y }) β β Root cause (x?.y)
---
## π¬ **See It In Action**
*Examples show JavaScript output; each language has equivalent detections \(Python: None checks, Go: nil guards, Rust: Option handling, etc\.\)*
### **Example 1: Catching a Null Pointer Bug**
$ ubs src/
βββ NULL SAFETY & DEFENSIVE PROGRAMMING Detects: Null pointer dereferences, missing guards, unsafe property access
π₯ CRITICAL (5 found) Unguarded property access after getElementById Consider: const el = document.getElementById(βxβ); if (!el) return;
src/components/form.js:42 const submitBtn = document.getElementById(βsubmit-buttonβ); submitBtn.classList.add(βactiveβ); // β Crashes if element missing
src/utils/dom.js:87 const modal = document.querySelector(β.modalβ); modal.style.display = βblockβ; // β Runtime crash guaranteed
π‘ Fix: Always check for null before accessing properties
**Before:** 3 production crashes this week **After:** 0 crashes, caught in 2 seconds
### **Example 2: Security Vulnerability Detection**
βββ ASYNC/AWAIT & PROMISE PITFALLS Detects: Missing await, unhandled rejections, race conditions
π₯ CRITICAL (8 found) await used in non-async function SyntaxError in JavaScript
src/api/users.js:67 function saveUser(data) { await database.insert(data); // β SyntaxError! }
β οΈ WARNING (12 found) Promises without .catch() or try/catch Unhandled rejections crash Node.js
src/services/email.js:45 sendEmail(user.email).then(result => β¦) // β No error handling!
**Before:** Silent failures, mysterious bugs in production **After:** All async bugs caught and fixed before deploy
---
## π **What It Detects \(The Complete Arsenal\)**
*Each language module has specialized detections\. Examples below are representative \(JavaScript shown; Python has `eval()`, Go has goroutine leaks, Rust has `.unwrap()` panics, C\+\+ has buffer overflows, etc\.\)*
### π΄ **Critical Issues \(Production Blockers\)**
These **WILL** cause crashes, security breaches, or data corruption:
| Pattern | Example | Why It's Dangerous |
| ------- | ------- | ------------------ |
| `eval()` usage | `eval(userInput)` | Allows arbitrary code execution - **RCE vulnerability** |
| Direct NaN comparison | `if (x === NaN)` | Always returns false - **logic bug** |
| Missing await | `asyncFunc()` in async context | Silent failures, race conditions - **data corruption** |
| Prototype pollution | `obj.__proto__ = {}` | Security vulnerability - **privilege escalation** |
| Unguarded null access | `el.style.color` without null check | **Runtime crash** guaranteed |
| `parseInt` without radix | `parseInt("08")` | Returns 0 in some browsers - **calculation bug** |
| Empty catch blocks | `catch(e) {}` | Swallows errors - **debugging nightmare** |
| `innerHTML` with user data | `el.innerHTML = userInput` | **XSS vulnerability** |
| Missing async keyword | `await` without `async function` | **SyntaxError** |
| Hardcoded secrets | `const key = "sk_live..."` | **Security breach** |
### π‘ **Warnings \(Should Fix Before Shipping\)**
These cause bugs, performance issues, or maintenance headaches:
| Pattern | Example | Impact |
| ------- | ------- | ------ |
| Promises without `.catch()` | `promise.then(...)` | Unhandled rejections crash Node\.js |
| Division without zero check | `total / count` | Returns `Infinity` or `NaN` |
| Event listeners without cleanup | `addEventListener` in React | **Memory leak** \(app gets slower over time\) |
| `setInterval` without clear | `setInterval(fn, 1000)` | **Timer leak** \(infinite timers\) |
| `await` inside loops | `for(...) { await api.call() }` | **Slow** \(sequential, not parallel\) |
| Array mutation during iteration | `arr.forEach(() => arr.push(...))` | **Skipped/duplicate** elements |
| Missing switch default | `switch(x) { case 1: ... }` | Unhandled values cause silent failures |
| `isNaN()` instead of `Number.isNaN()` | `isNaN("foo")` | Type coercion bugs |
### π΅ **Info \(Code Quality & Best Practices\)**
Improvements that make code cleaner and more maintainable:
- Optional chaining opportunities \(`obj?.prop?.value`\)
- Nullish coalescing opportunities \(`value ?? default`\)
- TypeScript `any` usage \(reduces type safety\)
- `console.log` statements \(remove before production\)
- Technical debt markers \(TODO, FIXME, HACK\)
- Performance optimizations \(DOM queries in loops\)
- `var` usage \(use `let`/`const` instead\)
- Deep property access without guards
- Large inline arrays \(move to separate files\)
- Complex nested ternaries \(readability\)
---
## βοΈ **Advanced Configuration**
### **Command-Line Options \(Full Reference\)**
ubs [OPTIONS] [PROJECT_DIR] [OUTPUT_FILE]
Core Options: -v, βverbose Show 10 code samples per finding (default: 3) -q, βquiet Minimal output (summary only) βci CI mode (stable output, no colors by default) βfail-on-warning Exit with code 1 on warnings (strict mode) βversion Print UBS meta-runner version and exit βprofile=MODE strict|loose (sets defaults for strictness) βbaseline=FILE Compare findings against a baseline JSON (alias for βcomparison) -h, βhelp Show help and exit
Git Integration: βstaged Scan only files staged for commit βdiff, βgit-diff Scan only modified files (working tree vs HEAD)
Output Control: βformat=FMT Output format: text|json|jsonl|sarif (default: text) βbeads-jsonl=FILE Write JSONL summary alongside normal output for Beads/βstrungβ βno-color Force disable ANSI colors OUTPUT_FILE Save report to file (auto-tees to stdout)
File Selection: βinclude-ext=CSV File extensions (default: auto-detect by language) JS: js,jsx,ts,tsx,mjs,cjs | Python: py,pyi,pyx Go: go | Rust: rs | Java: java | C++: cpp,cc,cxx,c,h Ruby: rb,rake,ru | Custom: βinclude-ext=js,ts,vue βexclude=GLOB[,β¦] Additional paths to exclude (comma-separated) Example: βexclude=legacy (deps ignored by default)
Performance: βjobs=N Parallel jobs for ripgrep (default: auto-detect cores) Set to 1 for deterministic output
Rule Control: βskip=CSV Skip categories by number (see output for numbers) Example: βskip=11,14 # Skip debug code + TODOs βskip-type-narrowing Disable tsserver-based guard analysis (falls back to text heuristics) βrules=DIR Additional ast-grep rules directory Rules are merged with built-in rules βno-auto-update Disable automatic self-update βsuggest-ignore Print large-directory candidates to add to .ubsignore (no changes applied)
Environment Variables: JOBS Same as βjobs=N NO_COLOR Disable colors (respects standard) CI Enable CI mode automatically
Arguments: PROJECT_DIR Directory to scan (default: current directory) OUTPUT_FILE Save full report to file
Exit Codes: 0 No critical issues (or no issues at all) 1 Critical issues found 1 Warnings found (only with βfail-on-warning) 2 Invalid arguments or configuration
### **Examples**
Basic scan
ubs .
Verbose scan with full details
ubs -v /path/to/project
Strict mode for CI (fail on any warning)
ubs βfail-on-warning βci
Save report without cluttering terminal
ubs . report.txt
Scan Vue.js project
ubs . βinclude-ext=js,ts,vue
Skip categories you donβt care about
ubs . βskip=14 # Skip TODO/FIXME markers
Maximum performance (use all cores)
ubs βjobs=0 . # Auto-detect ubs βjobs=16 . # Explicit core count
Exclude vendor code
ubs . βexclude=node_modules,vendor,dist,build
Custom rules directory
ubs . βrules=~/.config/ubs/custom-rules
Combine multiple options
ubs -v βfail-on-warning βexclude=legacy βinclude-ext=js,ts,tsx . report.txt
### JSONL schema
`--format=jsonl` \(and `--beads-jsonl=FILE`\) emit newline-delimited objects for easy piping into tools like Beads or `jq`:
{βtypeβ:βscannerβ,βprojectβ:β/path/to/projectβ,βlanguageβ:βpythonβ,βfilesβ:42,βcriticalβ:1,βwarningβ:3,βinfoβ:12,βtimestampβ:β2025-11-22T09:04:20Zβ} {βtypeβ:βtotalsβ,βprojectβ:β/path/to/projectβ,βfilesβ:99,βcriticalβ:1,βwarningβ:3,βinfoβ:27,βtimestampβ:β2025-11-22T09:04:22Zβ}
### **Custom AST-Grep Rules**
You can add your own bug detection patterns:
Create custom rules directory
mkdir -p ~/.config/ubs/rules
Add a custom rule (YAML format)
cat > ~/.config/ubs/rules/no-console-in-prod.yml <<βEOFβ id: custom.no-console-in-prod language: javascript rule: any:
- pattern: console.log($$$)
- pattern: console.debug($$$)
- pattern: console.info($$$) severity: warning message: βconsole statements should be removed before productionβ note: βUse a proper logging library or remove debug statementsβ EOF
Run with custom rules
ubs . βrules=~/.config/ubs/rules
**Common custom rules:**
Enforce specific naming conventions
id: custom.component-naming language: typescript rule: pattern: export function $NAME() { $$$ } not: pattern: export function $UPPER() { $$$ } severity: info message: βReact components should start with uppercase letterβ
Catch specific anti-patterns in your codebase
id: custom.no-direct-state-mutation language: typescript rule: pattern: this.state.$FIELD = $VALUE severity: critical message: βNever mutate state directly - use setState()β
### **Excluding False Positives**
If the scanner reports false positives for your specific use case:
Skip entire categories
ubs . βskip=11,14 # Skip debug code detection and TODO markers
Exclude specific files/directories
ubs . βexclude=legacy,third-party,generated
For persistent config, create a wrapper script
cat > /bin/ubs-custom <<βEOFβ
#!/bin/bash
ubs β$@β
βexclude=legacy,generated
βskip=14
βrules=/.config/ubs/rules
EOF
chmod +x ~/bin/ubs-custom
---
## π **How It Works \(Under the Hood\)**
### **Multi-Layer Analysis Engine**
The scanner uses a sophisticated 4-layer approach:
Layer 1: PATTERN MATCHING (Fast) βββ ββ Regex-based detection β ββ Optimized with ripgrep β ββ Finds 70% of bugs in <1 second β ββββΊ Combined Results Layer 2: AST ANALYSIS (Deep) βββββββ€ ββ Semantic code understanding β ββ Powered by ast-grep β ββ Catches complex patterns β β Layer 3: CONTEXT AWARENESS (Smart) β€ ββ Understands surrounding code β ββ Reduces false positives β ββ Knows when rules donβt apply β β Layer 4: STATISTICAL (Insightful) β ββ Code smell detection β ββ Anomaly identification β ββ Architectural suggestions β β Final Report (3-5 sec)
### **Technology Stack**
| Component | Technology | Purpose | Why This Choice |
| --------- | ---------- | ------- | --------------- |
| **Core Engine** | Bash 4\.0\+ | Orchestration | Universal compatibility, zero dependencies |
| **Pattern Matching** | Ripgrep | Text search | 10-100x faster than grep, parallelized |
| **AST Parser** | ast-grep | Semantic analysis | Understands code structure, not just text |
| **Fallback** | GNU grep | Text search | Works on any Unix-like system |
| **Rule Engine** | YAML | Pattern definitions | Human-readable, easy to extend |
### **Performance Optimizations**
Automatic parallelization (uses all CPU cores)
- Auto-detects: 16-core = 16 parallel jobs
- Manually set: βjobs=N
Smart file filtering (only scans relevant files)
- JS/TS: .js, .jsx, .ts, .tsx, .mjs, .cjs (auto-skip node_modules/dist/build)
- Python: .py + pyproject/requirements (skip venv/pycache)
- C/C++: .c/.cc/.cpp/.cxx + headers + CMake files (skip build/out)
- Rust: .rs + Cargo manifests (skip target/.cargo)
- Go: .go + go.mod/go.sum/go.work (skip vendor/bin)
- Java: .java + pom.xml + Gradle scripts (skip target/build/out)
- Ruby: .rb + Gemfile/Gemspec/Rakefile (skip vendor/bundle,tmp)
- Custom: βinclude-ext=js,ts,vue
Efficient streaming (low memory usage)
- No temp files created
- Results streamed as found
- Memory usage: <100MB for most projects
Incremental scanning (future feature)
- Only scan changed files (git diff)
- Cache previous results
- 10x faster on large projects
---
## π **Comparison with Other Tools**
| Feature | Ultimate Bug Scanner | ESLint | TypeScript | SonarQube | DeepCode |
| ------- | -------------------- | ------ | ---------- | --------- | -------- |
| **Setup Time** | 30 seconds | 30 minutes | 1-2 hours | 2-4 hours | Account required |
| **Speed \(50K lines\)** | 3 seconds | 15 seconds | 8 seconds | 2 minutes | Cloud upload |
| **Zero Config** | β
Yes | β No | β No | β No | β No |
| **Works Without Types** | β
Yes | β
Yes | β No | β
Yes | β
Yes |
| **Null Safety** | β
Yes | β οΈ Limited | β
Yes | β οΈ Limited | β οΈ Limited |
| **Security Scanning** | β
Yes | β οΈ Plugin | β No | β
Yes | β
Yes |
| **Memory Leaks** | β
Yes | β No | β No | β οΈ Limited | β No |
| **Async/Await** | β
Deep | β οΈ Basic | β
Good | β οΈ Basic | β οΈ Basic |
| **CI/CD Ready** | β
Yes | β
Yes | β
Yes | β
Yes | β οΈ Cloud |
| **Offline** | β
Yes | β
Yes | β
Yes | β οΈ Limited | β No |
| **AI Agent Friendly** | β
Built for it | β οΈ Config heavy | β οΈ Config heavy | β Complex | β οΈ Cloud |
| **Cost** | Free | Free | Free | $$$$ | $$$ |
**When to use what:**
- **Ultimate Bug Scanner**: Quick scans, AI workflows, no config needed
- **ESLint**: Style enforcement, custom rules, team standards
- **TypeScript**: Type safety \(use WITH this scanner\)
- **SonarQube**: Enterprise compliance, detailed metrics
- **DeepCode**: ML-powered analysis \(if you trust cloud\)
**Best combo:** TypeScript \+ ESLint \+ Ultimate Bug Scanner = Maximum safety
---
## π§ **Project Justification and Rationale**
### **Why This Exists \(And Why It's Not "Just Another Linter"\)**
You might be thinking: *"We already have ESLint, Pylint, Clippy, RuboCop\.\.\. why build another tool?"*
**Fair question\. And honestly, your first reaction is probably right to be skeptical\.**
### **The Initial Skepticism is Valid \(But Misses the Point\)**
When you first look at UBS, it's natural to think:
> *"This is just worse ESLint\. It has fewer rules, uses regex \(false positives\!\), and doesn't auto-fix anything\. Why would I use this instead of mature, comprehensive linters?"*
**That's analyzing through the wrong lens\.**
You're comparing it to tools designed for a **fundamentally different workflow** \(human developers writing code manually\) when it's solving a **fundamentally different problem** \(LLM agents generating code at 100x speed\)\.
It's like comparing a smoke detector to a building inspector:
- **Building inspector \(ESLint\):** Thorough, comprehensive, finds every issue, takes hours
- **Smoke detector \(UBS\):** Fast, catches critical dangers, instant alert, always running
**You need both\.** But when your house might be on fire \(AI just generated 500 lines in 30 seconds\), you want the smoke detector first\.
### **The Paradigm Shift: AI-Native Development**
Software development is undergoing a **fundamental transformation**:
**2020 \(Pre-LLM Era\):**
- Developer writes 50-200 lines/day manually
- Deep thought before each line
- Single language per project \(mostly\)
- Time to review: abundant
- Quality gate: comprehensive linting \+ code review \(hours\)
**2025 \(LLM Era\):**
- AI generates 500-5000 lines/day across projects
- Code appears in seconds
- Polyglot projects standard \(microservices in Go, UI in TypeScript, ML in Python, workers in Rust\)
- Time to review: scarce
- Quality gate needed: instant feedback \(\<5s\) or the loop breaks
**Traditional tools weren't designed for this\.** They were built when "code generation" meant 200 lines/day, not 2000\.
### **Here's the Fundamental Difference:**
### **1\. This Tool is Built FOR AI Agents, Not Just Humans**
Traditional linters were designed for **human developers** in **single-language codebases**\. UBS is designed for **LLM coding agents** working across **polyglot projects**\.
**The paradigm shift:**
| Traditional Linting \(Human-First\) | UBS Approach \(LLM-First\) |
| ----------------------------------- | -------------------------- |
| **Goal:** Comprehensive coverage \+ auto-fix <br>**Speed:** 15-60 seconds acceptable <br>**Setup:** 30 min config per language <br>**Languages:** One tool per language <br>**False positives:** Must be \<1% \(frustrates humans\) <br>**Output:** Human-readable prose | **Goal:** Critical bug detection \+ fast feedback <br>**Speed:** \<5 seconds required <br>**Setup:** Zero config \(instant start\) <br>**Languages:** One scan for all 7 languages <br>**False positives:** 10-20% OK \(LLMs filter instantly\) <br>**Output:** Structured file:line for LLM parsing |
### **2\. LLMs Don't Need Auto-FixβThey ARE the Auto-Fix Engine**
**Why traditional linters have auto-fix:**
// ESLint flags: βUse === instead of ==β if (value == null) // β
// ESLint auto-fix (rigid, no context): if (value === null) // β Technically correct, butβ¦
**Why UBS doesn't \(and shouldn't\):**
// UBS flags: βType coercion bug: == should be ===β if (value == null) // β
// Claude reads the error and understands context: if (value !== null && value !== undefined) // β Better - handles both // OR if (value != null) // β Or keeps == for null/undefined (intentional)
**The hard part is DETECTION, not fixing\.** Once flagged, LLMs can:
- Understand semantic context
- Consider surrounding code
- Apply the right fix \(not just the mechanical one\)
- Refactor holistically
Auto-fix would be **worse** because it's context-free\. LLMs need to know **WHAT'S wrong** and **WHERE**, then they fix it properly\.
### **3\. The Multi-Language Zero-Config Design is the Moat**
**Imagine asking Claude to set up quality gates for a polyglot project:**
**Traditional approach \(15-30 min per project\):**
JavaScript/TypeScript
npm install βsave-dev eslint @eslint/js @typescript-eslint/parser
Create .eslintrc.js (200 lines of config)
Python
pip install pylint black mypy
Create .pylintrc, pyproject.toml sections
Rust
Add to Cargo.toml: [lints]
Configure clippy rules
Go
Install golangci-lint, create .golangci.yml
Java
Setup Checkstyle + PMD + SpotBugs + config XMLs
C++
Setup clang-tidy, create .clang-tidy config
Ruby
Create .rubocop.yml with 150+ lines
Now run 7 different commands and parse 7 different output formatsβ¦
**UBS approach \(30 seconds\):**
curl -fsSL https://raw.githubusercontent.com/β¦/install.sh | bash ubs .
Done. All 7 languages scanned, unified report.
**This matters because:**
- LLMs generate code across languages in one session \(Python API β Go service β TypeScript UI β Rust worker\)
- Configuring 7 tools is error-prone for LLMs
- Humans don't want to maintain 7 different config files
- CI/CD pipelines want one command, one exit code
### **Type Narrowing Coverage Across Languages**
- **TypeScript** β UBS shells out to `tsserver` \(via the bundled helper\) whenever Node\.js \+ the `typescript` package are available\. The installer surfaces a "Type narrowing readiness" diagnostic so you immedi