PR State Bug Hunter is a state-of-the-art, AI-powered hybrid static and semantic analysis engine designed to intercept complex asynchronous race conditions, memory leaks, lifecycle mismatches, and network framing anomalies in Pull Requests before they compromise production stability.
By orchestrating a sophisticated dual-tier validation pipeline, the tool merges the deterministic velocity of Babel Abstract Syntax Tree (AST) parsing with the nuanced logical cognition of Google Gemini and OpenAI models. This integration yields high-fidelity, actionable remediation recommendations with a near-zero false-positive rate.
The engine operates on a robust two-layer pipeline, optimizing both computational overhead and semantic precision:
graph TD
A[PR Synchronization Triggered] --> B[Diff Parser: Compute Line Mutation Ranges]
B --> C[AST Static Sweep: Identify Structural Code Anomalies]
C -->|No Structural Violations| D[AI Agent: General Diff Semantic Audit]
C -->|Structural Violations Mapped| E[Surgical Context Extractor]
D --> F[Semantic AI Auditor: Gemini / OpenAI]
E --> F
F -->|Semantic Decision & Actionable Remediation| G[Incremental Cache Manager]
G --> H[GitHub PR Inline Commentary & Executive Dashboard]
G -->|Optional| I[Slash-Command /fix Automated Remediation]
[!NOTE]
The Rationale Behind Hybrid Analysis
Direct LLM processing of entire codebases introduces prohibitive token latency and financial overhead. Our pipeline bypasses this by leveraging Babel AST walkers to filter out structurally sound code within milliseconds. The AI engine is selectively invoked only for mutated blocks flagged with architectural weaknesses (e.g., unshielded async operations, incomplete resource tear-downs). This methodology minimizes API dependency and mitigates network latency.
To preserve swift developer feedback cycles and prevent redundant LLM invocations, the system employs a cryptographically signed SHA-256 caching mechanism.
filePath + line + ruleId + codeSnippetContext. This signature is cached locally in .bug-hunter-cache.json.Standard static analysis tools frequently generate false positives due to rigid pattern matching. PR State Bug Hunter solves this through a robust scope-aware variable tracker.
useEffect or Vue onMounted hooks, if an event listener's cleanup function is assigned to a variable or intermediate handler (const cleanup = () => ...) and subsequently returned transitively, the AST parser backtracks through the scope tree to verify the integrity of the release mechanism, successfully neutralizing false positives.Rather than relying on basic regex string matching, the parser performs native AST transformations across multiple component paradigms:
useEffect async anti-patterns, missing teardowns, unshielded race conditions on unmounted targets, and stale state closures..svelte file templates to isolate <script> blocks, detecting manual store .subscribe leaks neglected in onDestroy.<script setup>) to verify event listeners and intervals registered inside onMounted are systematically purged in onUnmounted or onBeforeUnmount./fix)Enables direct, closed-loop code refactoring directly from the GitHub code review interface.
/fix (or /fix <line>) on a PR triggers the action to check out the target branch, apply the AI-proposed refactoring patch, and commit the secure code changes directly back to the repository branch.node test-local.js --fix <line> in their terminal.All diagnostic runs and validation metadata are recorded locally in .bug-hunter-telemetry.json. In GitHub environments, the action monitors developer sentiment (e.g., negative reactions like ๐) to automatically flag potential false positives, enabling data-driven refinement of the underlying semantic rules.
The AST parser identifies structural anomalies mapped to specific concurrency rules, which are subsequently audited semantically by the AI engine:
| Rule Identifier | Target Framework | Vulnerability Signature & Concurrency Risk |
|---|---|---|
EFFECT_DIRECT_ASYNC |
React | useEffect(async () => ...) implementation. Prevents synchronous cleanup execution, exposing the component to memory leaks during rapid unmounts. |
EFFECT_UNCLEANED_SUBSCRIPTION |
React | Subscriptions, event listeners, or timers created inside useEffect lacking an explicit cleanup callback return. |
EFFECT_UNGUARDED_ASYNC |
React / Vue | Asynchronous operations (fetch/axios) executed without mount guards (AbortController or active flags), risking stale state mutation on unmounted DOM nodes. |
STALE_ASYNC_STATE_UPDATE |
React | Stale closure hazard where async resolutions write state using variables directly rather than utilizing functional state updates (setState(prev => ...)). |
SVELTE_UNCLEANED_SUBSCRIBE |
Svelte | Manual store subscriptions (store.subscribe) executed without storing the unsubscribe handler or omitting its invocation in onDestroy. |
VUE_UNCLEANED_ONMOUNTED |
Vue | Event listeners or intervals established in onMounted Composition hooks that are not systematically cleared inside onUnmounted. |
UNFRAMED_STREAM_DATA |
Node.js / Agnostic | Stream data event handlers (socket.on('data')) executing direct JSON.parse operations without handling message framing boundaries, causing crashes on split packets. |
action.yml)Integrate PR State Bug Hunter into your repository CI/CD workflow by creating a .github/workflows/bug-hunter.yml configuration:
name: PR State Bug Hunter
on:
pull_request:
types: [opened, synchronize, reopened]
pull_request_review_comment:
types: [created]
issue_comment:
types: [created]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Run Sentinel Analysis
uses: ./ # Path to local Action or repository reference
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
gemini-api-key: ${{ secrets.GEMINI_API_KEY }} # Natively supports OPENAI_API_KEY
severity-threshold: 'LOW'
auto-comment: 'true'
gemini-model: 'gemini-1.5-flash' # Supports gpt-4o-mini interchangeably
[!TIP]
If no AI API Key is provided, the action executes a graceful fallback mode, skipping the semantic AI validation phase and posting raw AST warning outputs directly to the PR to maintain continuous analysis availability.
github-token (Required): The repository access token (${{ secrets.GITHUB_TOKEN }}) utilized to post PR suggestions and commit automated code fixes.gemini-api-key (Optional): The credentials used for semantic validation. Accepts either Google Gemini keys or OpenAI keys (prefixed with sk-).severity-threshold (Default: LOW): The filtering threshold for reporting vulnerabilities (LOW, MEDIUM, HIGH).auto-comment (Default: true): Dictates whether the engine automatically submits inline review comments and summary panels.gemini-model (Default: gemini-1.5-flash): The target model name used for semantic evaluation.Developers can evaluate, verify, and run the entire concurrency analysis pipeline on their local environments without pushing commits to remote branches:
Initialize package dependencies locally:
npm install
Create a .env file at the root of the workspace directory and specify your API credentials:
GEMINI_API_KEY=sk-proj-YOUR_API_KEY_HERE
[!NOTE]
The internal multi-provider client automatically detects the'sk-'prefix, seamlessly routing requests to OpenAI's REST endpoints instead of Google Gemini.
Execute the local test runner to run React, Svelte, Vue AST scans, taint tracking checks, and AI semantic cache hits:
node test-local.js
To test the automated patching mechanism on a specific mutated line in your mock files:
node test-local.js --fix 24
This command parses the component, audits the event listener leak, contacts the semantic engine for a drop-in patch, and safely merges the cleanup code back into the file.
pr-state-bug-hunter/
โโโ src/
โ โโโ agents/
โ โ โโโ bugHunterAgent.js # Multi-provider (Gemini/OpenAI) semantic coordinator
โ โโโ analyzer/
โ โ โโโ astParser.js # Babel AST walkers and transitive taint tracker
โ โ โโโ cacheManager.js # SHA-256 cryptographic caching engine
โ โ โโโ diffParser.js # Unified diff parser & changed line mapper
โ โโโ github/
โ โ โโโ octokitClient.js # Octokit integration for PR reviews & auto-fixes
โ โโโ index.js # Entry point for the GitHub Action (isMain guarded)
โโโ src/test-cases/
โ โโโ buggyComponent.jsx # React concurrency vulnerabilities & clean samples
โ โโโ buggySvelte.svelte # Svelte manual subscription leak test case
โ โโโ buggyVue.vue # Vue Composition listener & interval leak test case
โโโ action.yml # GitHub Action interface declaration
โโโ test-local.js # Local test runner & CLI auto-fix simulator
โโโ package.json
โโโ README.md
This project is licensed under the terms of the MIT License. See the LICENSE file for details.