# Optix — Developer Guide

> **Single source of truth for developers, contributors, and maintainers.**
> For a user/stakeholder-facing overview, see **Summary.md**.

**Project:** OptixV4 Android pentesting platform · **Brand:** ori.on
**Current build version:** `1.0.0` (`versionCode 1`, `versionName "1.0.0"`)
**Last doc update:** 2026-07-17

> ⚠️ **Documentation accuracy note:** Several older `.md` files (README, APP-OVERVIEW, DEVELOPER-GUIDE, CONTRIBUTING, CHANGELOG-2026-07-09) described version `3.4.9`, "68+ tools", a separate `IntentParser.kt` / `ToolDispatcher.kt` / `ResponseTemplates.kt` AI layer, and Termux-only execution. **None of those match the current codebase.** This guide reflects the actual source as of 2026-07-17. Where the old docs disagreed with the code, the code wins.

---

## Table of Contents
1. [Project Overview](#1-project-overview)
2. [Technology Stack](#2-technology-stack)
3. [Architecture](#3-architecture)
4. [UI / Navigation](#4-ui--navigation)
5. [Development Environment](#5-development-environment)
6. [Project Structure](#6-project-structure)
7. [Core Systems](#7-core-systems)
8. [Implementation Status](#8-implementation-status)
9. [AI Integration](#9-ai-integration)
10. [Build & Deployment](#10-build--deployment)
11. [Testing](#11-testing)
12. [Technical Debt & Known Bugs](#12-technical-debt--known-bugs)
13. [Contributing](#13-contributing)
14. [Security Considerations](#14-security-considerations)
15. [Troubleshooting](#15-troubleshooting)

---

## 1. Project Overview

### Mission
A free, open-source Android network pentesting and vulnerability-assessment platform for both professional red teamers and security beginners — comprehensive tooling, AI-assisted guidance, and visual network intelligence, all mobile-first.

### Current status (2026-07-17)
- **Stage:** Active development, pre-1.0 feature-complete-ish build (`1.0.0`).
- **Tool count:** ~40 active tool classes across 11 categories (see Summary.md).
- **AI:** Conversational assistant (MockBrain offline + 6 cloud providers) wired into tool execution.
- **Test coverage:** Near 0% — no CI test suite yet (see Technical Debt).
- **Build:** Gradle 8.7, Kotlin 2.0.21, Compose; compiles against `compileSdk 35`. **`assembleDebug` builds clean** as of 2026-07-17 (see §12 for the build-error fixes applied).

### Alignment with mission
✅ Mobile-first pentesting · ✅ Educational + professional audiences · ✅ AI-assisted · ✅ Free/open-source · ⚠️ Comprehensive coverage (network/web/OSINT/cloud done; containers/AI-red-team pending).

---

## 2. Technology Stack

| Component | Technology | Notes |
|-----------|-----------|-------|
| Language | Kotlin | JVM target 17 |
| UI | Jetpack Compose (BOM) + Material3 | Declarative UI |
| Build | Gradle 8.7 (version catalog `libs.*`) | `gradlew` wrapper |
| Min / Target SDK | API 26 / 35 | Android 8.0+ |
| DI | Hilt (ksp) | Standard Android DI |
| Persistence | Room (ksp), DataStore (preferences) | Nodes, sessions, settings |
| Async | Kotlin Coroutines + Flows | IO dispatcher for tools |
| Networking | OkHttp (+ SSE, logging), Gson, kotlinx-serialization-json | REST + streaming |
| Protocol libs | dnsjava, jcifs-ng (SMB), snmp4j, jsch (SSH) | **Native** (no Termux needed) |
| Permissions | Accompanist permissions | Runtime prompts |
| Logging | Timber | |
| Native tools | Termux + ShellExecutor | nmap, masscan, hydra, etc. |

**AI provider deps:** No dedicated SDKs — OpenAI/Anthropic/Gemini are called via OkHttp (OpenAI-compatible chat completions). Groq, Mistral, and OpenRouter reuse the OpenAI provider with a different base URL (see `AiProviderFactory`).

---

## 3. Architecture

### Layers
```
UI (Compose screens)
  └─ ViewModel (state + intent)
       └─ Use Cases (domain)  ← AiBridgeUseCase, RunToolUseCase, SessionUseCase
            └─ Repositories (Settings / Node / Session / Tool)
                 └─ Data (Room, DataStore, OkHttp)
AI layer (MockBrain + providers)
  └─ LlmProvider interface → OfflineProvider / OpenAi(-compatible) / Anthropic / Gemini
Tool system
  └─ ToolRegistry → ToolExecutionEngine → BaseTool.execute → ShellExecutor / native libs
```

### Design patterns
- **MVVM** — ViewModels own UI state via `StateFlow`.
- **Repository** — abstracts data sources.
- **Hilt DI** — `@Inject` constructor injection throughout.
- **Factory** — `ToolRegistry` holds tools; `AiProviderFactory` builds providers.
- **Strategy** — `LlmProvider` implemented per backend.
- **Observer** — `Flow`/`StateFlow` for reactive updates.

### Module / package layout (`app/src/main/kotlin/com/optix/android/`)
```
ai/                       # MockBrain, IntentParser/ResponseTemplates NOT present
  MockBrain.kt            # Offline regex-based intent → tool dispatch
  AiBridge.kt             # (legacy/compat) high-level AI orchestration
  IntentParser.kt         # small NLP helpers (not the old monolith)
  ToolDispatcher.kt       # routing helpers
  ResponseTemplates.kt    # message templates
  providers/              # LlmProvider, OfflineProvider, OpenAiProvider,
                          #   AnthropicProvider, GeminiProvider, AiProviderFactory
domain/
  model/                  # Tool, ToolCategory, ToolMetadata, ToolEvent, AiProvider*, Session
  repository/             # repository interfaces
  usecase/                # AiBridgeUseCase, RunToolUseCase, SessionUseCase
di/                       # Hilt modules (App, Database, Tool, Network)
tools/
  registry/               # BaseTool, ToolRegistry
  engine/                 # ToolExecutionEngine, ShellExecutor, EnvironmentManager
  network/ web/ exploit/ osint/ cloud/ utility/ ai/   # tool implementations
  archive/                # legacy stubs (WpScan, WhatWeb, SnmpWalk, Smb, ... .txt)
ui/
  MainActivity.kt, navigation/AppNavigation.kt
  screens/ ai/ lanmap/ settings/ disclaimer/
  components/             # ToolPicker, ToolConfigForm, SessionSheet, ResultCard, etc.
  theme/                  # AppTheme, Color, Type, Theme (custom T. global alias)
util/                     # NetworkUtils, Extensions, HardwareMonitor
OptixApplication.kt
```

---

## 4. UI / Navigation

Two-tab single-activity design (`MainActivity` + `AppNavigation`):

| Tab | Route | Function |
|-----|-------|----------|
| **BRAIN** | AI chat | Conversational tool execution via MockBrain / cloud LLM |
| **NETWORK** | Globe + tool workspace | 3D globe, node detail, console, tool panel |

- **DisclaimerScreen** — shown once on first launch (DataStore flag).
- **Settings** — provider selection, API keys, proxy/Tor, theme picker, tool timeout.

### Globe visualization
- Node colors: gateway (amber), active target (accent), open ports, Wi-Fi (read-only), stale (faded).
- Interactions: tap node → detail panel; zoom buttons; drag to pan; subnet orbital rings.
- `LanMapScreen.kt` is a **large monolith** (~1000+ LOC) — decomposition is on the debt list.

### Theme system
8 themes via `AppTheme` + `LocalAppTheme` composition local; persisted in DataStore. Uses a non-standard `T.` global alias rather than `MaterialTheme` tokens (see debt).

---

## 5. Development Environment

### Prerequisites
- **Windows 10/11** (current dev machine), **Android Studio** (latest stable).
- **JDK 17** (e.g. Eclipse Adoptium).
- **Android SDK** 26–35.
- Git.

### Workspace layout
```
OPTIX/
├── Summary.md            # ← user/stakeholder overview (this repo)
├── Developer.md          # ← this file
├── docs/
│   ├── tools/            # tool manuals (e.g. AWS-INSPECTOR-MANUAL.md)
│   └── .archive/         # legacy consolidated docs (historical only)
└── newest-errors-iplist-targetselect-workspace-master/
    └── OptixV4/          # ← Android app root (gradle project)
        ├── app/
        │   ├── build.gradle.kts
        │   └── src/main/kotlin/com/optix/android/...
        ├── gradle.properties
        ├── local.properties   # sdk.dir (configure locally)
        └── settings.gradle.kts
```

### Build commands
```bash
cd newest-errors-iplist-targetselect-workspace-master/OptixV4
.\gradlew.bat clean assembleDebug
.\gradlew.bat installDebug
.\gradlew.bat test                 # (currently minimal)
```

### Known build issues
- **Corrupted KSP / Kotlin cache after a crashed daemon** — previously surfaced as
  `java.nio.file.FileAlreadyExistsException` (Hilt/KSP generated files) and
  `Could not connect to Kotlin compile daemon` / `Failed connecting to the daemon in 4 retries`.
  These were **not** source errors — they were caused by an interrupted/crashed build leaving a
  stale `build/generated/ksp` + `.kotlin` cache. **Fix:** clean the cache and rebuild:
  ```bash
  .\gradlew.bat clean
  Remove-Item -Recurse -Force app\build\generated\ksp
  .\gradlew.bat assembleDebug
  ```
  `gradle.properties` already sets `ksp.incremental=false` and a generous JVM heap
  (`-Xmx4096m`, `kotlin.daemon.jvmargs=-Xmx4g`), which suppresses the KSP collision class of bug.
- **Hilt dependency cycle** — `MockBrain → AiProviderFactory → ToolRegistry → MockBrain` was a
  construction-time cycle that failed `hiltJavaCompileDebug` with `[Dagger/DependencyCycle]`.
  **Fix (2026-07-17):** `MockBrain`'s `ToolRegistry` dependency is now injected as
  `Lazy<ToolRegistry>` (used only lazily at runtime in `validateToolNames()` / the `status`
  command), which breaks the cycle without changing behavior. See §12.

---

## 6. Project Structure — Key Files

| File | Purpose |
|------|---------|
| `ai/MockBrain.kt` | Offline intent parsing → tool dispatch + educational replies |
| `ai/providers/AiProviderFactory.kt` | Builds `LlmProvider` per selected backend |
| `domain/model/Tool.kt` | `ToolMetadata`, `ToolParam`, `ToolCategory`, `ParamType` |
| `tools/registry/BaseTool.kt` | Abstract tool base; `execute(params, emit)`, `validate()` |
| `tools/engine/ToolExecutionEngine.kt` | Timeout, validation, cancellation wrapper (Flow) |
| `tools/engine/ShellExecutor.kt` | Termux/native shell execution (streamed) |
| `ui/screens/lanmap/LanMapScreen.kt` | Network workspace UI (large) |
| `ui/screens/lanmap/LanMapViewModel.kt` | Network state + persistence |
| `ui/screens/ai/AiViewModel.kt` | Chat state management |
| `domain/usecase/*` | `AiBridgeUseCase`, `RunToolUseCase`, `SessionUseCase` |

---

## 7. Core Systems

### 7.1 Tool system
Every tool extends `BaseTool` and implements:
```kotlin
abstract class BaseTool {
    abstract val metadata: ToolMetadata
    abstract suspend fun execute(
        params: Map<String, Any>,
        emit: suspend (ToolEvent) -> Unit,
    )
    open fun validate(params: Map<String, Any>): List<String>  // required-field checks
}
```
- **Registration:** tools are registered in `di/ToolModule.kt` into `ToolRegistry`.
- **Execution:** `ToolExecutionEngine.run(tool, params)` returns a `Flow<ToolEvent>` with per-tool timeouts (see `TOOL_TIMEOUTS`) and cooperative cancellation. The engine emits `ToolEvent.Done` on completion/timeout/error — tools should also emit `Done` as their final event.
- **Execution backends:** native Kotlin/Java libraries (dnsjava, jcifs-ng, snmp4j, jsch) for many scanners; Termux/CLI via `ShellExecutor` for nmap, masscan, hydra, nikto, sqlmap, etc.

### 7.2 Tool metadata
```kotlin
data class ToolMetadata(
    val name: String,
    val displayName: String,
    val description: String,
    val category: ToolCategory,
    val parameters: List<ToolParam>,
    val requiresRoot: Boolean = false,
    val requiresNetwork: Boolean = true,
    val requiresTermux: Boolean = false,
    val supportedPlatforms: List<String> = emptyList(),
    val apiKeyRef: String? = null,
    val chainSuggestions: List<String> = emptyList(),
)

enum class ToolCategory {
    NETWORK_SCANNING, DNS_WEB, EXPLOITATION, PAYLOADS_UTILITIES,
    LPE, LATERAL_MOVEMENT, OSINT, AI_REDTEAM,
    CLOUD_SEC, CONTAINER_SEC, THREAT_INTEL
}
```

### 7.3 Network / node persistence
- Nodes persisted in Room (`NodeEntity` keyed by IP). LAN scans **merge** with existing nodes; missing nodes marked `STALE`.
- MAC addresses resolved from `/proc/net/arp`; device-type heuristics from MAC/hostname.
- `LanMapViewModel` builds a network context summary injected into AI prompts.

### 7.4 Sessions & console
- Every tool run creates a `SessionEntity` (tool, params JSON, result, duration, success).
- Global console `Flow` capped at 500 entries; scan-history bottom sheet re-displays past runs.

### 7.5 Tool events
```kotlin
sealed class ToolEvent {
    data class Started(val toolName: String) : ToolEvent()
    data class Log(val message: String, val level: LogLevel) : ToolEvent()
    data class Output(val line: String) : ToolEvent()
    data class Result(val result: ToolResult) : ToolEvent()
    data class Error(val message: String, val exception: Throwable? = null) : ToolEvent()
    data class Done(val toolName: String) : ToolEvent()
}
```

---

## 8. Implementation Status

### Categories
| Category | Status |
|----------|--------|
| Network & Scanning | ✅ Implemented |
| DNS & Web | ✅ Implemented |
| Exploitation | ✅ Implemented |
| Privilege Escalation | ✅ Implemented (LinPEAS, WinPEAS) |
| Lateral Movement | ✅ Implemented (BloodHound, CME) |
| OSINT | ✅ Implemented (7 tools; some need API keys) |
| Cloud Security | ✅ Implemented (AWS, GCP, Azure) |
| Payloads & Utilities | ✅ Implemented |
| Threat Intelligence | ⚠️ Partial (OpenCTI wrapper, not fully wired) |
| AI Red-Team | ✅ Implemented (LLM prompt-injection probe; more tools planned) |
| Container & Kubernetes | 📋 Planned (0 tools) |

### Recent completed work (history)
- Cloud security trio (AWS Inspector, GCP Asset Scanner, Azure AD Tool) added; AI dispatch patterns extended.
- MockBrain offline assistant with regex intent dispatch + contextual follow-up suggestions.
- 6 LLM provider integrations via `AiProviderFactory`.
- Globe UI improvements (zoom controls, tap handling, subnet grouping, port badges).
- **2026-07-17:** fixed a build-breaking cascade (KSP cache corruption, suspend-context, recursion,
  regex escapes, missing Hilt bindings, and a `MockBrain`/`ToolRegistry` dependency cycle); the
  `LlmPromptInjectionTool` AI-red-team tool is now registered and DI-resolvable (see §12).

---

## 9. AI Integration

### Offline assistant — MockBrain
`ai/MockBrain.kt` is the default (no-key) assistant:
1. **Exact commands** — `help`, `tools`, `status`, `clear`, greetings.
2. **Tool dispatch** — regex patterns (e.g. `^lan ?scan`, `^port ?scan`, `^nmap`, `^dns`, `^shodan`) → returns a `MockBrainResponse(text, toolCall)`.
3. **Natural-language inference** — fuzzy patterns map phrases to tools.
4. **Contextual follow-ups** — affirmative replies after a scan suggest the next tool based on open ports / OS.
5. **Chat patterns** — ~60+ educational/explainer patterns.

`OfflineProvider` converts a `MockBrainResponse` with a `toolCall` into a `ProviderEvent.ToolCall` so `AiBridge` actually executes the tool; the `text` becomes the preamble. `MockBrain.validateToolNames()` warns at startup if a dispatched tool name isn't in the registry.

### Cloud providers
`AiProviderFactory` maps `AiProviderType` → `LlmProvider`:
- `OFFLINE` → `OfflineProvider(MockBrain)`
- `GEMINI` → `GeminiProvider`
- `OPENAI` → `OpenAiProvider`
- `GROQ` / `MISTRAL` / `OPENROUTER` → `OpenAiProvider` with a different base URL
- `ANTHROPIC` → `AnthropicProvider`

All implement `LlmProvider.streamChat(...)`.

### Open gaps (from planning)
- No function-calling / tool-use API on cloud providers.
- No input sanitization, output filtering, prompt-injection defense, or rate limiting on the AI layer (security gap).
- No session continuity across app restarts; no structured CVE/MITRE knowledge base.
- AI red-teaming module not started.

---

## 10. Build & Deployment

```bash
.\gradlew.bat clean assembleDebug      # debug APK
.\gradlew.bat assembleRelease          # release (minify enabled)
.\gradlew.bat installDebug
```

### Release checklist
- [ ] Bump `versionName`/`versionCode` in `app/build.gradle.kts`.
- [ ] Update documentation (Summary.md / Developer.md).
- [ ] Run `./gradlew test` (once tests exist).
- [ ] Test on multiple Android versions (8–15), with/without root, with/without Termux.
- [ ] Sign release APK; publish to GitHub Releases (not Play Store).

Versioning follows SemVer (`MAJOR.MINOR.PATCH`).

---

## 11. Testing

**Current state:** ⚠️ No meaningful automated test suite. Coverage ≈ 0%.

### Strategy (target)
- **Unit:** `MockBrain` dispatch, `ToolDispatcher`/`IntentParser` mapping, `ToolExecutionEngine` timeout/validation, parser utils. Target 75%+ overall.
- **Integration:** tool execution via `ToolRegistry` + `ToolExecutionEngine`; Room repositories.
- **UI:** Compose tests for BRAIN/NETWORK tabs, globe rendering, node detail.
- **Security:** shell-injection sanitization, required confirmation for destructive tools.

Use `kotlinx-coroutines-test` and `HiltAndroidTest`. Add tests when touching `MockBrain`, the engine, or tool I/O.

---

## 12. Technical Debt & Known Bugs

### Critical debt 🔴
1. **No automated tests** — regression risk; refactor unsafe.
2. **No audit logging / pre-execution ethical confirmation** — legal/accountability gap.
3. **LanMapScreen monolith** (~1000+ LOC) — extract `GlobeCanvas`, `NodeDetailPanel`, `ToolPanel`, `ConsolePanel`, `TargetPanel`.

### Medium debt 🟡
4. **IP-as-primary-key** node entities — DHCP changes orphan data; prefer stable `nodeId` (MAC/UUID).
5. **No export/reporting** — can't produce professional reports.
6. **Custom `T.` theme alias** — breaks Compose previews; migrate to `MaterialTheme`.
7. **AI safety layer missing** — no sanitization / abuse detection / rate limiting.

### Low debt 🟢
8. Default app icon still placeholder.
9. Port scan 1–9999 unoptimized (no tiered top-1000-first).

### Known bugs (from BUG_CHECK_REPORT.md — status as of 2026-07-16)
**Resolved in this pass:**
- ✅ **HunterIoTool.kt** — `email!!` null-crash fixed (safe `?: "unknown"`).
- ✅ **HydraTool.kt** — `requiresRoot` set to false (Hydra does not need root; was blocking non-root use); `Done` semantics already correct.
- ✅ **BloodhoundTool.kt** — query mode now emits `Done` on every path and uses a correct single-arg `su -c` python invocation.
- ✅ **MetasploitTool.kt** — RC file now written via Kotlin `File.writeText` (no fragile `echo '…'`), removing shell-quoting hazards.
- ✅ **MockBrain.kt** — fixed offline AI tool-name mismatches: `linpeas`/`winpeas`/`cme`/`bloodhound` now map to the real `*_termux` registry names; added `nuclei` → `nuclei_termux` dispatch. (These mismatches silently failed AI-driven tool calls.)

**Resolved in this pass (2026-07-17 — build + AI-red-team wiring):**
- ✅ **Build now compiles cleanly** — `assembleDebug` succeeds (was failing on a cascade of
  compile + Hilt errors). Root cause was a crashed Kotlin daemon + corrupted KSP cache, on top of
  several genuine source errors that had crept in. Fixes applied:
  - **KSP/Hilt cache corruption** — the `FileAlreadyExistsException` / "could not connect to daemon"
    failures were stale-cache artifacts, not code bugs; cleared `build/generated/ksp` + `.kotlin`
    caches. (`gradle.properties` already disables KSP incremental mode + raises the JVM heap.)
  - **`LlmPromptInjectionTool.kt`** — `Classifier.classify` called the `suspend fun generate(...)`
    from a non-suspending context; made `classify` a `suspend fun` and switched the `forEach` to a
    `for` loop. Also fixed a latent type bug: `canaries.filter { }` returns a `Map`, not a `List`,
    which broke iteration — normalized both branches to `List<Map.Entry>`.
  - **`LanMapViewModel.kt`** — `fun bootstrapCapabilities()` was recursing into itself instead of
    calling the injected `BootstrapCapabilities` use case; injected `bootstrapUseCase` and called it.
  - **`ChainParser.kt`** — invalid regex escape sequences (`\{`, `\"`) fixed by switching to raw
    strings; `(?s)` inline flag replaces the unresolved `RegexOption.DOTALL`; array branch now wraps
    parsed steps in a `ToolChain` (was returning `List<ToolChainStep>?` from a `ToolChain?` function).
  - **`ChainRepository.kt`** — added the missing `asStateFlow()` import.
  - **`ToolModule.kt`** — `LlmPromptInjectionTool` / `AiModelEnumTool` need `AiProviderFactory`;
    `KubeReconTool` / `DockerInspectTool` need `ShellExecutor`. Injected both and passed them in.
  - **Hilt bindings** — `SessionExporter` was missing `@Inject` on its constructor; `AuditLogRepository`
    interface was not bound (added `@Binds` in `RepositoryModule`).
  - **Hilt dependency cycle** — `MockBrain → AiProviderFactory → ToolRegistry → MockBrain` broken by
    making `MockBrain`'s `ToolRegistry` a `Lazy<ToolRegistry>`.
- ✅ **AI red-team tool wired** — `LlmPromptInjectionTool` (prompt-injection resilience probe) is now
  registered in `ToolModule` and DI-resolvable via `AiProviderFactory`. The "AI Security & Red Team"
  category is no longer just planned (see §8).

**Still open:**
- 🟡 **EnvironmentManager.kt / NetworkUtils.kt** — silent exception swallowing; add logging.
- 🟡 **ShellExecutor.kt** — broad `catch (Exception)`; prefer specific exceptions.
- 🟡 **ToolExecutionEngine.kt** — `timeoutFor()` duplicates `resolveTimeoutSeconds()` logic; consolidate.

### Follow-up chaining (new)
Discovery tools now emit `ToolEvent.ChainSuggestion` (port_scanner, ssh_audit, http_inspector), which
`LanMapViewModel` surfaces as a clickable **NEXT** chip in `BottomControlPanel` (`runSuggestedChain`).
This closes the "can't act on discovery results" gap without leaving the NETWORK tab.

---

## 13. Contributing

### Workflow
1. Fork → branch (`feature/...`, `bugfix/...`, `docs/...`).
2. Make changes; follow Kotlin + Compose conventions.
3. Commit via **Conventional Commits** (`feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`).
4. Add/update tests for non-trivial logic.
5. Update **Summary.md** / **Developer.md** when behavior or architecture changes.
6. Open a PR; describe testing performed.

### Adding a new tool
1. Create `tools/<category>/YourTool.kt` extending `BaseTool`, declaring `ToolMetadata` with `parameters`.
2. Register it in `di/ToolModule.kt` and add to `ToolRegistry`.
3. If it should be AI-runnable offline, add a regex + handler in `MockBrain.toolDispatch` (or `nlToolPatterns`) and a `toolCall` name matching the registry name.
4. For cloud-CLI tools, route through `ShellExecutor` (Termux). For pure-Kotlin scanners, use the native libs (dnsjava, jcifs-ng, snmp4j, jsch).
5. Write a user manual under `docs/tools/` (model it on `AWS-INSPECTOR-MANUAL.md`).
6. Update tool counts/categories in Summary.md.

### Coding standards
- Kotlin official conventions; Compose best practices (state hoisting, `@Preview`, `modifier` last param).
- Public APIs get KDoc.
- Never hardcode API keys; use encrypted DataStore.
- Emit `ToolEvent.Done` exactly once at the end of `execute`.

---

## 14. Security Considerations

- **Shell injection:** `ShellExecutor` should sanitize inputs; avoid string-concatenated commands. Validate user-supplied targets/IPs/domains.
- **Permissions:** declare & request `INTERNET`, `ACCESS_NETWORK_STATE`, `ACCESS_WIFI_STATE`, `ACCESS_FINE_LOCATION`, storage (runtime).
- **Sensitive data:** API keys in encrypted DataStore; redact secrets from logs.
- **HTTPS only** for provider calls; consider certificate pinning for production.
- **Ethical guardrails:** destructive/exploit tools should require explicit confirmation; an audit trail is planned but not yet implemented.

---

## 15. Troubleshooting

- **Kotlin daemon failed / `FileAlreadyExistsException` in `build/generated/ksp`** — usually a
  stale cache from an interrupted build, not a code error. Run `.\gradlew.bat clean`, delete
  `app\build\generated\ksp` and `.kotlin` caches, then rebuild.
- **Hilt `[Dagger/DependencyCycle]`** — a construction-time cycle in the singleton graph. Inject the
  offending dependency as `Lazy<T>` (as done for `MockBrain`'s `ToolRegistry`) to break it.
- **SDK not found** — set `sdk.dir` in `local.properties`.
- **App crashes on launch** — check Hilt graph, Room migrations, permissions; `adb logcat | findstr optix`.
- **Termux tool not found** — install via Termux (`pkg install nmap ...`); Optix prompts to install missing tools.
- **Globe blank** — run a LAN scan first; verify canvas size & theme colors.
- **AI not responding** — check provider selection + API key; Offline (MockBrain) needs no key.

---

## Glossary
| Term | Meaning |
|------|---------|
| BaseTool | Abstract superclass for all tools |
| MockBrain | Offline regex-based AI assistant |
| ToolEvent | Sealed event stream from tool execution |
| LlmProvider | Interface for cloud/offline AI backends |
| ShellExecutor | Termux/native shell runner |
| LanMapScreen | NETWORK tab UI (globe + tools) |

---

© 2026 ori.on · Open source. **Unauthorized use is illegal and unethical.**
