Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 122 additions & 0 deletions docs/antigravity-rotator/ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# 🏗️ Antigravity Rotator 1.0.0 Architecture

This document describes the high-level architecture and the "No-Wall" hacker methods used to make this rotator the most robust version ever built.

## 1. Zero-Trust Chrome Session (Profile Wipe)
Most automation fails because of cookie residue or "Choose an account" prompts from previous sessions.
- **The Problem**: Persistent browser profiles accumulate state that leads to non-deterministic UI flows.
- **The Method**: Before every rotation, the `chrome_profile` directory is completely deleted (`shutil.rmtree`).
- **The Result**: Chrome starts 100% fresh. Google is forced to present the initial login screen, eliminating any "Account Chooser" or "Verify it's you" confusion based on previous sessions.

## 2. Human-Emulation (Enter Key Bypass)
React-based applications like Google Login often block simulated button clicks (DOM `.click()`) or have invisible overlays that trap the mouse.
- **The Problem**: Selectors like `#identifierNext` are often "visible" but not "interactable" in the React lifecycle, causing automation to hang.
- **The Method**: Instead of clicking the button, the bot types the email/password and then sends a native **Keyboard Enter** event.
- **The Result**: Form submission is triggered at the OS level, which React cannot block without breaking accessibility for real users. This bypasses 99% of UI-based bot detection.

## 3. The Trash-Recycling Cycle (Undelete API)
Google Workspace has aggressive abuse protection (Error 412) when creating many accounts in a short time.
- **The Problem**: Creating and deleting 50 accounts a day triggers abuse flags.
- **The Method**: Instead of `Create -> Use -> Delete`, we use a recycling loop. Accounts are moved to the Trash (Deleted status). The rotator searches for deleted accounts and uses the `service.users().undelete()` API.
- **The Result**: We recycle a small pool of `rotator-*` accounts indefinitely. To Google, this looks like normal administrative user management, bypassing account creation limits.

## 4. Ultra-Wide Virtual Terminal (PTY Scaling)
Opencode's TUI (`clack`) is extremely sensitive to line breaks. A 1000-character Google OAuth URL will wrap and break on a standard 80-character terminal.
- **The Problem**: Wrapped URLs contain hidden newline characters (`\n`), which corrupt the OAuth token when pasted into the Opencode TUI.
- **The Method**: The virtual terminal (`pexpect.spawn`) is initialized with `dimensions=(200, 4000)`.
- **The Result**: The entire URL/Code fits on a single horizontal line, ensuring bit-perfect input for the Opencode CLI.

## 5. Auto-Purge Self-Healing
To prevent the "Zombie Account" issue where old accounts still appear in the Opencode CLI or Google Workspace:
- **The Method**: Every successful rotation ends with a `cleanup_all_except(new_email)` call.
- **The Action**:
1. **Local**: Scans `antigravity-accounts.json` and deletes every entry starting with `rotator-` except the new one.
2. **Cloud**: Scans Google Workspace and deletes (moves to Trash) all other active `rotator-*` accounts.
- **The Result**: The system state is reset to "Single Active Rotator" after every run, preventing configuration drift.

## 6. Phase 1: Intelligence & Quality Modules
In Phase 1, the architecture is extended with specialized agents for diagnostics and quality assurance.

### 6.1 Enhanced Debugging System (`src/debugger.py`)
- **Purpose**: Provides a "Flight Recorder" for errors.
- **Mechanism**: Intercepts exceptions and matches them against a regex-based pattern registry. It maintains a persistent JSON database of errors to identify recurring issues and suggest proven solutions.

### 6.2 Code Review Bot (`src/code_review.py`)
- **Purpose**: Automated quality gate.
- **Mechanism**: Performs static analysis using AST (Abstract Syntax Tree) and regex scanning. It scores code based on security, complexity, and maintainability, ensuring that new features don't introduce technical debt or vulnerabilities.

## 7. Phase 2: Collaboration & Delivery Modules
Phase 2 adds workflow tools that make it easier to collaborate, generate tests, and inspect changes.

### 7.1 Live Collaboration (`src/live_collaboration.py`)
- **Purpose**: Shared edit sessions with revision tracking.
- **Mechanism**: Tracks participants, applies line-based edits, detects stale revisions, and persists sessions as JSON.

### 7.2 Automated Test Generation (`src/testgen.py`)
- **Purpose**: Produce runnable pytest smoke tests from source code.
- **Mechanism**: Parses AST signatures, infers safe sample inputs, and emits a test module for public functions and classes.

### 7.3 Visual Diff Viewer (`src/visual_diff.py`)
- **Purpose**: Review code changes quickly.
- **Mechanism**: Uses SequenceMatcher to build side-by-side and unified diff views with change-impact metrics.

## 8. Phase 3: Performance, Security, and Workspaces
Phase 3 adds operational tooling for profiling, security review, and multi-repo orchestration.

### 8.1 Performance Profiler (`src/profiler.py`)
- **Purpose**: Measure hot paths and script runtime.
- **Mechanism**: Wraps `cProfile`/`pstats` in callable and script helpers plus a scoped context manager.

### 8.2 Security Scanner (`src/security_scan.py`)
- **Purpose**: Detect risky Python code with AST-first analysis.
- **Mechanism**: Visits the syntax tree for dangerous calls, shell execution, and obvious secret assignment patterns.

### 8.3 Workspace Manager (`src/workspace_manager.py`)
- **Purpose**: Track multiple git repositories and worktrees.
- **Mechanism**: Uses git subprocess calls with an explicit cwd and stores registry data as JSON.

## 9. Phase 4: Policy, Memory, Evaluation, and Aliases
Phase 4 adds cross-cutting safety and coordination tools inspired by the latest OpenClaw features.

### 9.1 Security Policy Guard (`src/policy_guard.py`)
- **Purpose**: Catch SSRF and config injection issues before they execute.
- **Mechanism**: Resolves URLs to IPs, checks for restricted address ranges, scans env mappings for interpolation tokens, and inspects registry documents for alias collisions.

### 9.2 Memory Wiki (`src/memory_wiki.py`)
- **Purpose**: Turn logs into durable, searchable memory.
- **Mechanism**: Stores hot JSONL events, synthesizes warm markdown digests, and archives cold entries for later recall.

### 9.3 QA Lab (`src/qa_lab.py`)
- **Purpose**: Compare candidate outputs before promoting them.
- **Mechanism**: Runs deterministic text scoring in parallel and ranks candidates with a structured report.

### 9.4 Provider Alias Registry (`src/provider_alias_registry.py`)
- **Purpose**: Keep provider variants reproducible and collision-free.
- **Mechanism**: Stores alias bindings in a lockfile and rejects duplicate alias claims.

---

## 10. Phase 5: Routing, Search, and Workboards

### 10.1 Taskboard (`src/taskboard.py`)
- **Purpose**: Persist lightweight operational work items.
- **Mechanism**: Stores task records in SQLite with status transitions, reconciliation, and snapshot reporting.

### 10.2 SearXNG Client (`src/search_client.py`)
- **Purpose**: Query a trusted SearXNG endpoint for private search workflows.
- **Mechanism**: Normalizes trusted base URLs, fetches JSON search results, and renders human-readable or JSON reports.

### 10.3 Guardrails (`src/guardrails.py`)
- **Purpose**: Intercept unsafe prompts and outputs before they spread.
- **Mechanism**: Evaluates regex-backed input/output rules and supports blocking or redaction decisions.

### 10.4 Cron Allow-List (`src/cron_allowlist.py`)
- **Purpose**: Restrict scheduled commands to approved argv prefixes.
- **Mechanism**: Splits commands with shell-aware parsing, checks for metacharacters, and persists rule sets to JSON.

### 10.5 Failover Router (`src/failover_router.py`)
- **Purpose**: Route work to healthy providers with cooldown-aware fallback.
- **Mechanism**: Maintains route candidates, records success/failure outcomes, and skips candidates under cooldown.

---
**Branding**: OpenSIN / sincode
94 changes: 94 additions & 0 deletions docs/antigravity-rotator/PHASE10_FEATURES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# 🚀 Phase 10 Features: Multi-Cloud Orchestration

> **Status:** Implemented (Issue #48) — OpenSIN AI now orchestrates across OCI, HF Spaces, and Cloudflare.

Phase 10 gives every OpenSIN AI agent the ability to be scheduled optimally across a heterogeneous multi-cloud topology, tracking node costs and providing zero-downtime geographic failover.

---

## Why This Makes OpenSIN Better Than Claude Code

Claude Code has no multi-cloud orchestration or failover logic. OpenSIN AI can dynamically shift workloads between free OCI instances, cheap HF Spaces, and fast Cloudflare workers, minimizing costs while maximizing uptime via haversine-based geographic failover.

---

## 1. CloudRegistry (`src/multi_cloud.py`)

Central SQLite-backed catalogue of all multi-cloud nodes.

### Key Capabilities

- **Upsert Registration**: Register nodes with latitude and longitude.
- **Status Tracking**: active, offline, maintenance.
- **Provider Tags**: oci, hf, cloudflare, aws, gcp.

### Usage

```python
from src.multi_cloud import CloudRegistry

registry = CloudRegistry()
registry.register_node("oci-fra-1", "OCI Frankfurt", "oci", "eu-frankfurt", 0.0001, lat=50.1109, lon=8.6821)
```

---

## 2. CostScheduler (`src/multi_cloud.py`)

Calculates the cheapest path to deploy an agent.

### Key Capabilities

- **Cheapest-First Routing**: Orders available nodes by `cost_per_ms`.
- **Provider Pinning**: Optional `preferred_providers` filter.

### Usage

```python
from src.multi_cloud import CostScheduler

scheduler = CostScheduler()
deploy = scheduler.schedule_workload("agent-security")
print(deploy["node_id"]) # → e.g. "oci-fra-1"
```

---

## 3. FailoverRouter (`src/multi_cloud.py`)

Geographic failover utilizing the Haversine formula to find the nearest active node.

### Key Capabilities

- **Nearest Neighbor Fallback**: Calculates great-circle distance between the crashed node and all active nodes to minimize latency.
- **Automatic Fencing**: Marks the failed node as `offline`.

### Usage

```python
from src.multi_cloud import FailoverRouter

router = FailoverRouter()
failover = router.trigger_failover("oci-fra-1")
print(f"Failed over to {failover['failover_node']} ({failover['distance_km']}km away)")
```

---

## 4. CLI Subcommands

All multi-cloud operations are available via `python3 -m main multi-cloud <subcommand>`.

```bash
# List active cloud nodes
python3 -m main multi-cloud list-nodes

# Register a new cloud node
python3 -m main multi-cloud register-node oci-fra-1 "OCI Frankfurt" oci eu-frankfurt 0.0001 --lat 50.1109 --lon 8.6821

# Schedule a workload
python3 -m main multi-cloud schedule my-agent-task

# Trigger failover
python3 -m main multi-cloud failover oci-fra-1
```
43 changes: 43 additions & 0 deletions docs/antigravity-rotator/PHASE11-12_FEATURES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# 🚀 Phases 11 & 12 Features: God-Level Intelligence

> **Status:** Implemented — OpenSIN AI has surpassed traditional coding assistants by reaching the ultimate "Agentix" God-Level state.

Phases 11 & 12 add Global Fleet Self-Healing and Autonomous Idle Monetization to ensure the fleet is never idle, never broken for long, and always generating value.

---

## 1. Telegram Brain & Global Fleet Self-Healing (Phase 11)

Claude Code breaks and stops when it hits a wall. OpenSIN AI doesn't.

### Key Capabilities

- **Telegram Alerting:** Real-time push notifications sent directly to the `A2A-SIN-TelegramBot`.
- **Closed-Loop Auto-Repair:** When a subagent crashes, the system autonomously intercepts the error log, opens a structured GitHub Issue, and spawns a repair subagent (`check-plan-done`) to fix the underlying codebase.

### Usage
```bash
# Manually trigger an alert
python3 -m main telegram-brain alert "Fleet status is operational."

# Manually trigger the auto-repair loop on a failed task
python3 -m main telegram-brain self-heal "task_fail_1" "ModuleNotFoundError: No module named 'x'"
```

---

## 2. Idle Workforce Monetization Engine (Phase 12)

"A2A Agenten sitzen NIEMALS einfach dumm rum." (AGENTS.md Priority 0001).

### Key Capabilities

- **Idle Detection:** Scans the Taskboard. If no user-defined pending tasks exist, the fleet activates the Monetization Engine.
- **Task Injection:** Automatically creates highly-profitable synthetic tasks (HackerOne Bug Bounties, Upwork Gigs, Prolific Surveys).
- **Cost-Optimized Routing:** The injected tasks are instantly routed to the cheapest available cloud node via Phase 10's `CostScheduler`.

### Usage
```bash
# Check idle status and inject a monetization task if the fleet is doing nothing
python3 -m main idle-monetize check
```
97 changes: 97 additions & 0 deletions docs/antigravity-rotator/PHASE1_FEATURES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# 🚀 Phase 1 Features: Enhanced Intelligence & Quality

Phase 1 introduces advanced diagnostic and quality assurance tools to the Antigravity Rotator ecosystem, ensuring higher reliability and code standards.

## 1. Enhanced Debugging System (`src/debugger.py`)

The Enhanced Debugging System provides intelligent error analysis, pattern matching, and a persistent error registry to accelerate troubleshooting.

### Key Capabilities
- **Intelligent Pattern Matching**: Automatically identifies common failure modes (Rate Limits, Auth Failures, Chrome Crashes, Network Issues, File Permissions).
- **Persistent Error Registry**: Tracks errors across sessions in `~/.config/opensin/error-registry.json`.
- **Automated Suggestions**: Provides actionable steps for each matched error pattern.
- **Debugging Dashboard**: Real-time statistics on error frequency, severity, and resolution rates.
- **15+ Known Errors**: Pre-configured patterns for the most common Antigravity/Opencode issues.

### Usage Examples

```python
from src.debugger import debug_error, debug_exception, debugger

# 1. Debug a specific error message
analysis = debug_error("Rate limit exceeded: 429 Too Many Requests", verbose=True)

# 2. Debug a caught exception
try:
# some code that fails
pass
except Exception as e:
debug_exception(e, verbose=True)

# 3. View the Debugging Dashboard
print(debugger.get_dashboard())
```

---

## 2. Code Review Bot (`src/code_review.py`)

An automated quality gate that scans the codebase for security vulnerabilities, code smells, and architectural complexity.

### Key Capabilities
- **Security Scanner**: Detects hardcoded secrets, SQL injection patterns, path traversal risks, and dangerous `eval/exec` usage.
- **Code Smell Detection**: Identifies long functions (>50 lines), excessive parameters (>5), deep nesting (>4 levels), bare except clauses, and print-based debugging.
- **AST-Complexity Analysis**: Uses Python's Abstract Syntax Tree to measure function length and nesting depth accurately.
- **Quality Scoring**: Generates a weighted score (0-100) based on:
- **Security (35%)**
- **Complexity (25%)**
- **Style (20%)**
- **Maintainability (20%)**
- **Formatted Reports**: Generates clean, actionable reports for single files or entire directories.

### Usage Examples

```python
from src.code_review import CodeReviewBot, format_review_report

bot = CodeReviewBot()

# 1. Review a single file
result = bot.review_file("src/rotator.py")
print(format_review_report(result))

# 2. Review the entire src directory
results = bot.review_directory("src/")
print(format_review_report(results))
```

---

## 🏗️ Phase 1 Architecture

```text
[ User / CLI ]
|
v
[ Antigravity Rotator ] <---- [ Code Review Bot ] (Pre-deployment Check)
| ^
| | (Scans)
v |
[ Opencode CLI ] <----------- [ Source Code ]
| ^
| (Errors) | (Analysis)
v |
[ Enhanced Debugger ] --------------+
|
+---> [ Error Registry (JSON) ]
+---> [ Debug Dashboard ]
```

## 🔧 Integration Guide

1. **Pre-Commit Hook**: Integrate `CodeReviewBot` into your CI/CD or pre-commit hooks to block low-quality code.
2. **Global Exception Handler**: Wrap the main rotator loop with `debug_exception` to capture and analyze runtime failures automatically.
3. **Health Monitoring**: Use `debugger.get_dashboard()` to monitor the long-term stability of the rotation fleet.

---
**Branding**: OpenSIN / sincode
Loading
Loading