Metadata-Version: 2.4
Name: droidguard
Version: 2.0.1
Summary: Deterministic Android Verification & AI Agent Governance Engine
Author: DroidGuard Contributors
License: Apache-2.0
Project-URL: Homepage, https://github.com/rabee-elkholy/droidguard
Project-URL: Documentation, https://github.com/rabee-elkholy/droidguard#readme
Project-URL: Repository, https://github.com/rabee-elkholy/droidguard.git
Project-URL: Issues, https://github.com/rabee-elkholy/droidguard/issues
Project-URL: Changelog, https://github.com/rabee-elkholy/droidguard/blob/main/CHANGELOG.md
Keywords: android,ai-agents,agentic-coding,gradle,governance,roborazzi,konsist,compose,claude-code,cursor,codex
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Build Tools
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0; extra == "dev"
Requires-Dist: ruff>=0.5.0; extra == "dev"
Requires-Dist: mypy>=1.10.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Dynamic: license-file

# 🛡️ DroidGuard 2.0

<p align="center">
  <strong>Deterministic Android Verification & AI Agent Governance Engine</strong><br>
  <em>Protect your Android codebase from agent hallucinations, unauthorized Git mutations, ANRs, broken Room migrations, and untranslated strings.</em>
</p>

<p align="center">
  <a href="https://pypi.org/project/droidguard/"><img src="https://img.shields.io/pypi/v/droidguard?color=blue&style=flat-square" alt="PyPI Version"></a>
  <a href="https://pypi.org/project/droidguard/"><img src="https://img.shields.io/pypi/pyversions/droidguard?style=flat-square" alt="Python Versions"></a>
  <a href="https://github.com/rabee-elkholy/droidguard/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-green?style=flat-square" alt="License"></a>
  <a href="https://github.com/rabee-elkholy/droidguard/actions"><img src="https://img.shields.io/github/actions/workflow/status/rabee-elkholy/droidguard/ci.yml?branch=main&style=flat-square" alt="CI Build"></a>
  <a href="https://github.com/rabee-elkholy/droidguard/actions"><img src="https://img.shields.io/badge/coverage-80%25-brightgreen?style=flat-square" alt="Test Coverage"></a>
</p>

---

## ⚡ The Problem DroidGuard Solves

Autonomous AI coding agents (**Claude Code, Cursor, OpenAI Codex, Antigravity, Copilot, Windsurf**) are transforming software development. However, Android engineering has strict platform-specific constraints that general LLMs frequently violate:

- ❌ **Destructive Git Mutations**: AI agents committing directly to `main`, force-pushing, resetting HEAD, or modifying Git branches without human developer review.
- ❌ **Broken Room SQLite Migrations**: Modifying entity schemas without incrementing database version numbers or writing SQLite `Migration` classes, causing production crashes on user devices.
- ❌ **Missing Localization Strings**: Adding hardcoded strings or updating `values/strings.xml` while forgetting Arabic (`values-ar`), French (`values-fr`), or other locale parity, breaking multi-language users.
- ❌ **Compose Recomposition Freezes & ANRs**: Using unstable parameters (`List<T>`) causing UI jank, or wrapping background tasks in `runBlocking` / `Thread.sleep()` on the Android Main thread.
- ❌ **Orphaned Gradle Daemons**: Child compiler processes locking files on Windows and Unix systems during AI task interruption.

**DroidGuard 2.0** sits between your AI coding agents and your Android codebase as a **deterministic, fail-closed governance firewall and quality verification engine**.

---

## 🚀 Key Features

```
                                 ┌──────────────────────────────────────────────┐
                                 │              AI Coding Agents                │
                                 │ (Claude Code, Cursor, Codex, Copilot, etc.)  │
                                 └──────────────────────┬───────────────────────┘
                                                        │
                                         [ Universal PreToolUse Hook ]
                                                        ▼
┌───────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                       🛡️ DROIDGUARD 2.0                                               │
├──────────────────────────────┬───────────────────────────────┬────────────────────────────────────────┤
│     1. Safety & Policy       │     2. Android Intelligence   │      3. Governance & Delivery          │
├──────────────────────────────┼───────────────────────────────┼────────────────────────────────────────┤
│ • Git Mutation Blocker       │ • Multi-Locale String Parity  │ • N-Leaf Subagent Review Consensus     │
│ • Shell / Base64 Unwrapping  │ • Room Schema JSON Validator  │ • SQLite Relational State Engine       │
│ • ADB Hardware Protection    │ • Compose Stability Metrics   │ • Win32 Job Object Process Supervisor  │
│ • Trojan Source Bidi Defense │ • Konsist Architecture Rules  │ • Unified PM Gateway (Zoho, Jira, etc.)│
│ • Path Traversal Shield      │ • StrictMode / ANR Sentinel   │ • AgentLens / SWE-bench Tracing        │
└──────────────────────────────┴───────────────────────────────┴────────────────────────────────────────┘
                                                        │
                                                        ▼
                                 ┌──────────────────────────────────────────────┐
                                 │              Android Project                 │
                                 │ (Gradle, Kotlin DSL, AGP 8+, Compose, Room) │
                                 └──────────────────────────────────────────────┘
```

### 1. Fail-Closed Safety Engine
- **Absolute Git Authority**: Blocks all forms of `git commit`, `git push`, `git reset`, `git checkout -b`, and disguised flags (`-C`, `--git-dir`). Only the human developer holds commit authority.
- **Shell Indirection & Obfuscation Guard**: Unwraps PowerShell base64 (`-EncodedCommand`), backtick escaping (``g`i`t``), nested execution (`bash -c`, `cmd /c`, `python -c`), and blocks dynamic `iex` execution.
- **ADB Hardware Guard**: Blocks destructive device commands (`adb monkey`, `pm clear`, `uninstall`, `reboot recovery`), while permitting safe telemetry (`logcat`, `install -r`, `screencap`).
- **Trojan Source Defense**: Detects and blocks bidirectional Unicode override characters (RLO, LRO, PDF).

### 2. Android 7-Layer Verification Engine (`dg preflight`)
1. **Multi-Locale String Parity**: Validates key parity across all `values-*/strings.xml`, `<plurals>`, `<string-array>`, and positional format specifiers (`%1$s`, `%2$d`).
2. **Room Database Schema JSON Diff**: Inspects `schemas/<DbClass>/<version>.json`, detects added/removed/renamed tables and columns, and enforces matching `Migration(N, N+1)` code in Kotlin/Java.
3. **Jetpack Compose Compiler Metrics**: Parses `*-composables.txt` and `*-classes.txt`, detecting unstable parameters and non-skippable composable functions.
4. **Konsist Architecture Rules**: Enforces Clean Architecture domain layer isolation, `@Immutable` on MVI state models, and forbids inline FQCNs.
5. **Performance & ANR Sentinel**: Scans for `runBlocking`, blocking `Thread.sleep()`, and ViewModel Context memory leaks.
6. **Roborazzi Headless JVM Visual Tests**: Validates Compose screenshot reports for visual regressions across RTL Arabic and Dark Mode.
7. **Android Lint CLI Incremental Runner**: Enforces baseline compliance and zero fatal errors.

### 3. Multi-Agent Review Consensus (`dg verify`)
- Calculates a 12-character SHA-256 extended code fingerprint covering Kotlin, Java, XML, Gradle Kotlin DSL, `proguard-rules.pro`, Room schema JSONs, and `CMakeLists.txt`.
- Gated build authorization requiring configurable quorum (3, 5, 7 subagent approvals recorded in SQLite `ReviewLedger` across 5 specialized personas: `security`, `convention`, `perf-anr`, `regression-impact`, `qa-diagnostics`).

### 4. Supervised Gradle Runner
- Uses **Win32 Job Objects** on Windows and **process groups** on Linux/macOS to terminate child compiler and daemon processes with zero orphan leaks.
- Structured compiler error extraction for Kotlin (`file:line:col`), Java, Manifest merger conflicts, and Room schemas.

### 5. Unified Project Management Gateway
- Single vendor-agnostic adapter interface supporting **Zoho Sprints (multi-region .com, .eu, .in, .sa, .au), Jira Cloud v3, Linear GraphQL, and GitHub Projects**.
- Enforces security policy forbidding AI agents from marking tasks as `Done` or `Solved` (restricting transitions to `In Review` or `Ready for QA`).
- Theme-resilient HTML formatting preserving Kotlin Generics (`List<UserProfile>`) with automatic Arabic RTL direction.

### 6. Universal AI IDE & Assistant Adapters (`dg sync`)
- Seamlessly synchronizes project rules and configuration across **8 AI environments**:
  * **OpenAI Codex CLI & `AGENTS.md`** (`CODEX.md`, `AGENTS.md`, `.codex/prompts/*`)
  * **Google Antigravity** (`.agents/rules/droidguard-rules.md`)
  * **Anthropic Claude Code** (`CLAUDE.md`)
  * **Cursor IDE** (`.cursor/rules/droidguard.mdc`)
  * **GitHub Copilot** (`.github/copilot-instructions.md`)
  * **Windsurf IDE** (`.windsurfrules`)
  * **Cline & Roo Code** (`.clinerules`)
  * **Qwen Code** (`QWEN.md`)

---

## 📦 Installation

Install DroidGuard via pip (requires Python 3.11+):

```bash
pip install droidguard
```

Or install with development dependencies:

```bash
pip install "droidguard[dev]"
```

Verify installation:

```bash
dg --version
```

---

## 🛠️ CLI Quickstart

### 1. Initialize an Android Project
Run inside your Android project root:

```bash
dg init
```
*Auto-detects your Android project configuration (Compose/XML, Hilt/Koin, SDK levels, locales), generates `droidguard.toml`, creates `.agents/state/droidguard.db`, and configures `.githooks/pre-commit`.*

### 2. Run Environment Diagnostics
```bash
dg doctor
```
*Validates JDK 17+, Android SDK, Gradle Wrapper, ADB, Git hooks, and static analysis tools.*

### 3. Run Preflight Verification Checks
```bash
dg preflight
```
*Executes Strings, Room, Compose, Konsist, Lint, and Performance sentinels with graceful degradation in milliseconds.*

### 4. Verify Review Consensus & Code Fingerprint
```bash
dg verify
```
*Inspects SHA-256 package hash and verifies if required subagent review consensus has unlocked the build gate.*

### 5. Execute Multi-Stage QA Delivery Pipeline
```bash
dg deliver --task ZOHO-101
```
*Coordinates: preflight checks ➔ consensus validation ➔ supervised Gradle build ➔ PM status & QA handoff report update.*

### 6. Synchronize Rules Across All AI IDEs
```bash
dg sync
```
*Generates and updates `CLAUDE.md`, `CODEX.md`, `AGENTS.md`, `.cursor/rules/`, `.agents/`, and Copilot instructions.*

### 7. Rollback Session State
```bash
dg rollback --clean-temp
```

---

## ⚙️ Configuration (`droidguard.toml`)

DroidGuard is configured via a single documented `droidguard.toml` at the project root:

```toml
version = "2.0.0"

[project]
name = "MyAndroidApp"
di_framework = "hilt"       # auto | hilt | koin | dagger | anvil | manual
ui_toolkit = "compose"      # auto | compose | xml | hybrid | kmp
default_build_type = "debug"

[review]
enabled = true
leaf_count = 5              # 3, 5, 7 consensus reviewers
require_unanimous = false

[checks.strings]
enabled = true
base_locale = "values"
enforce_all_locales = true

[checks.room]
enabled = true
schema_dir = "schemas"
verify_migrations = true

[checks.compose]
enabled = true
enforce_immutable_state = true
fail_on_unstable_params = false

[checks.konsist]
enabled = true
enforce_clean_architecture = true
forbid_inline_fqcn = true

[checks.perf]
enabled = true
forbid_main_thread_queries = true
forbid_sleep = true
check_viewmodel_leaks = true

[pm]
provider = "zoho"           # zoho | jira | linear | github | none
domain = "sa"               # com | eu | in | sa | au
enforce_qa_handoff = true
forbid_done_status = true
```

---

## 🧪 Testing & Verification

DroidGuard includes an exhaustive test suite with over 85 unit, integration, and penetration test cases:

```bash
# Run pytest test suite
pytest tests/ -v

# Run type checker
mypy src/

# Run linter & formatter
ruff check src/ tests/
ruff format src/ tests/
```

---

## 📄 License

DroidGuard is licensed under the [Apache-2.0 License](LICENSE).
