<p align="center">
  <img src="logo.svg" alt="AI Agent - Infrastructure & Security Engineer" width="96" height="96">
</p>

<h1 align="center">AI Agent — Infrastructure & Security Engineer</h1>

<p align="center">
  <strong>Oracle Cloud Infrastructure — CIS Foundations Benchmark 3.0 — AI-Powered Compliance Platform</strong>
</p>

<p align="center">
  <img src="https://img.shields.io/badge/version-2.7-C74634?style=flat-square" alt="Version">
  <img src="https://img.shields.io/badge/python-3.12-3776AB?style=flat-square" alt="Python">
  <img src="https://img.shields.io/badge/FastAPI-0.115-009688?style=flat-square" alt="FastAPI">
  <img src="https://img.shields.io/badge/OCI-GenAI-C74634?style=flat-square" alt="OCI">
  <img src="https://img.shields.io/badge/docker-compose-2496ED?style=flat-square" alt="Docker">
  <img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="License">
</p>

---

## Overview

AI Agent — Infrastructure & Security Engineer is a self-hosted web application that automates **CIS Oracle Cloud Infrastructure Foundations Benchmark 3.0** compliance checks, powered by **OCI Generative AI** for intelligent analysis and an **MCP (Model Context Protocol)** server architecture for extensible task execution.

The platform combines security compliance scanning, AI-powered chat with **RAG (Retrieval-Augmented Generation)**, infrastructure exploration, and vector-based knowledge storage into a single, containerized solution with a **dual frontend** (legacy SPA + React SPA at `/app/`), **Oracle Dark Premium** theme (light/dark modes), **KPI dashboard** with compliance gauge, **i18n** (pt/en), and **Chart.js** visualizations.

---

## Features

### 🤖 AI Chat Agent with RAG + MCP Tool Use
- **OCI Generative AI** integration via official SDK (`oci.generative_ai_inference`)
- **RAG (Retrieval-Augmented Generation)**: automatically queries ADB vector store for relevant context before generating responses
- **MCP Tool Use (Function Calling)**: GenAI models can call tools from registered MCP servers during chat — supports both Cohere and Generic (OpenAI-style) function calling formats with automatic tool execution loop (max 5 iterations)
- **Chat Memory Compaction**: automatic summarization of older messages when conversation exceeds ~6000 tokens — keeps 20 recent messages (10 interactions) intact and generates an LLM-based summary of older context
- **Chat Sidebar**: collapsible right-side panel with model parameters (temperature, max_tokens, top_p, top_k, penalties) for quick adjustment during conversation
- **Multimodal Chat**: upload images (PNG/JPG/GIF/WebP), PDFs, and text files directly in the chat for AI analysis — supports up to 5 files per message via OCI GenAI `ImageContent` and `DocumentContent`
- **Async Background Processing**: chat requests return immediately, GenAI + MCP tools process in background via dedicated thread pool (16 threads), frontend polls for results — eliminates 504 timeouts on long-running scans
- **Thinking Indicator**: button disables and shows spinner + "Pensando..." while waiting for GenAI response, with message timestamps
- 15 chat models + 3 embedding models across 5 providers: **Meta** (Llama 4), **Google** (Gemini 2.5), **OpenAI** (GPT-5.2/5.1/5 Mini/4.1/4o, o3/o4-mini), **xAI** (Grok 4/3)
- OCID-based model resolution: catalog maps model IDs to OCI resource IDs per region for reliable API calls
- 16 OCI regions supported with auto-generated endpoints
- **Provider parameter matrix**: automatic parameter segmentation per model — reasoning models (o3/o4-mini) only get `max_completion_tokens` + `reasoning_effort`, OpenAI GPT-4.x gets freq/pres penalties, Google/Meta get `top_k`, xAI gets basic params. Unsupported parameters are explicitly nulled to prevent SDK serialization errors
- Full parameter control: temperature, max_tokens, top_p, top_k, frequency/presence penalty (when supported by model)
- Toggle MCP tools on/off per chat session
- Conversation history with session management
- On-Demand and Dedicated serving modes

### 🏗️ Terraform Agent (IaC)
- **AI-powered Terraform code generation** for OCI infrastructure provisioning
- Dedicated chat interface with OCI Terraform provider context
- **Workspace management**: create, plan, apply, destroy Terraform workspaces
- **Compartment-aware**: browse and select target compartment for provisioning, with existing OCI resources injected as context
- **Plan/Apply/Destroy lifecycle**: full Terraform workflow with real-time output tracking
- **File management**: view generated `.tf` files, copy, download individually or as bundle
- **Confirmation modal**: type "DESTROY" to confirm resource destruction
- **Inline file editor**: click any generated `.tf` file to edit in-place with monospace editor, Tab support, and save — auto-syncs with workspace code
- **Split-panel terminal**: real-time Plan/Apply/Destroy output in a dark terminal panel alongside files/plan/resources (always visible)
- **Multi-file generation**: AI generates separate `.tf` files via `// filename:` markers (main.tf, variables.tf, outputs.tf, etc.)
- **Smart file correction**: when fixing errors, model generates only changed files — frontend merges with existing workspace, preserving untouched files. Existing files, plan output, and apply errors are injected as context automatically
- **14-point validation checklist**: system prompt enforces cross-references, CIDRs, security lists, route tables, DRG attachments, RPC peering, HCL block syntax, resource type validation, and variable declarations
- **Auto-split pipeline (3 layers)**: frontend + backend auto-split of monolithic HCL files into categorized files (networking.tf, compute.tf, etc.) + backend deduplication to prevent duplicate resource errors
- **HCL syntax fix**: automatic expansion of single-line blocks with multiple arguments into valid multi-line HCL format
- **Resource type validation**: SQLite-based validation of ~937 OCI resource types with `difflib.get_close_matches` suggestions for invalid types — warnings appended automatically to model responses
- **Chat history**: ChatGPT-style session history with rename/delete, shared between Chat Agent and Terraform Agent
- **Resizable split view**: chat on top (50%), files/plan/resources + terminal on bottom (50%) with drag-to-resize
- Terraform CLI installed in container (v1.7.5)
- **Terraform Resource Reference**: auto-generated OCI provider resource catalog (~937 resources) injected into system prompt — built from `terraform providers schema -json` at container startup, stored in SQLite, refreshable via menu button
- **Official Resource Docs Injection**: on-demand fetch of Example Usage + Argument Reference from the official OCI Terraform provider docs (registry.terraform.io) — cached in SQLite, injected into model context based on detected resource types
- **Smart variable resolution**: auto-generates `terraform.tfvars` by scanning declared variables and mapping them to OCI config values (`tenancy_ocid`, `user_ocid`, `fingerprint`, `compartment_id`, `ssh_public_key`) — region is never forced, respecting variable defaults
- **Multi-region provider management**: auto-detects provider aliases and region variables in generated code, generates `provider.tf` with credentials and correct region references (`var.region` instead of hardcoded values)
- **Region safety guard**: plan is blocked if the model does not declare `variable "region"` — prevents accidental provisioning in the wrong region by never falling back to hardcoded defaults
- **Rollback button**: when `terraform apply` fails, a Rollback button appears allowing manual `terraform destroy` to clean up partially created resources (requires typing "ROLLBACK" to confirm)
- **System prompt sync**: Terraform system prompt in code is automatically synced to DB on every restart — single source of truth
- Compact system prompt optimized for OCI Terraform provider best practices (100K max_tokens)
- **Flat workspace enforcement**: system prompt prohibits `module` blocks (workspace has no subdirectories) and enforces single-file variable declarations (`variables.tf` only)

### 📝 Terraform Prompt Generator
- **AI-powered prompt generation** for OCI infrastructure — generates structured, optimized prompts to feed into the Terraform Agent
- Dedicated chat interface (sub-menu under Terraform) matching Terraform Agent layout
- **Curated model selection**: only 7 recommended models (GPT-4.1, o3, o4-mini, GPT-5.1, GPT-5.2, Gemini 2.5 Pro, Gemini 2.5 Flash), grouped by provider
- **Same knowledge pipeline as Terraform Agent**: compact resource reference + auto-detected resource types + official docs from GitHub (cached in SQLite)
- **Official Terraform docs injection**: detects resource types from user message (keywords + explicit `oci_*` mentions), fetches Example Usage + Argument Reference from GitHub, cached in `tf_resource_docs` table
- **Conversation history**: persistent sessions (agent_type `tf-prompt`) with sidebar history panel, rename/delete, session restore
- **Contextual follow-up**: conversation history sent to GenAI for iterative prompt refinement
- **Copy & Send**: action buttons on assistant messages to copy the prompt or send directly to the Terraform Agent input
- Robust system prompt with OCI Provider constraints, inference rules, architecture templates, and workspace restrictions
- Example prompts as clickable buttons for quick start

### ⚡ OCI Resource Actions
- **Start/Stop Compute Instances** directly from OCI Account Explorer with one click
- **Start/Stop Autonomous Databases** from Explorer with confirmation prompt
- **Start/Stop DB Systems, MySQL, Container Instances** — 5 resource types with operational control
- **Update Network Access**: add your IP to ADB ACL (whitelisted_ips) directly from Explorer
- **ACL display**: view current whitelisted IPs for Autonomous Databases in Explorer cards
- **Auto-refresh**: resource state updates automatically after Start/Stop actions (polling)
- Lifecycle state badges (RUNNING/STOPPED/AVAILABLE) with color indicators
- Actions audited in the audit log

### 🔍 OCI Account Explorer
- **KPI stats bar**: real-time resource counts per category with tooltip breakdown, cached in SQLite for instant loading
- **Tree-view navigation** with resizable side panel (280px default) and drag handle
- **36 resource types** across 9 categories:
  - **Compute**: Instances, Boot Volumes, Instance Pools
  - **Networking**: VCNs, Subnets, Security Lists, NSGs, Route Tables, NAT/Internet/Service Gateways, Public IPs, Load Balancers
  - **Storage**: Buckets, Block Volumes, File Systems, Mount Targets
  - **Database**: Autonomous Databases, DB Systems, MySQL DB Systems
  - **Containers**: Container Instances, OKE Clusters
  - **Serverless**: Functions, API Gateways
  - **Observability**: Alarms, Log Groups, Notification Topics, Events Rules
  - **Security**: Vaults, DNS Zones, Network Firewalls, Firewall Policies
  - **IAM**: Users, Groups, Policies, Dynamic Groups
- **Enhanced views**: expandable cards for VCNs (CIDRs, DNS), Subnets (AD, route table), Load Balancers (listeners, backends), Buckets (size, object count, visibility)
- **Multi-region support**: select and filter by multiple OCI regions with checkbox selection
- **Compartment tree**: hierarchical compartment browser with full OCID visibility
- **Dead state filtering**: automatically hides TERMINATED/DELETED/DELETING resources
- **Background count refresh**: counts cached in SQLite, refreshed on compartment access without blocking UI
- **Security list detail**: view ingress/egress rules directly in the explorer
- Select which OCI connection to explore
- Real-time API calls via OCI Python SDK

### 📊 CIS Compliance Reports (Oracle Official Engine)
- Powered by Oracle's official `cis_reports.py` (6660 lines, 48 CIS + 11 OBP checks)
- **Granular execution parameters**: CIS Level (1/2), OCI Best Practices, Raw Data, OCID Redaction
  - **Level 1**: Essential security controls that can be implemented with minimal impact on operations. Recommended as baseline for all organizations.
  - **Level 2**: Advanced security controls that may restrict functionality or require more effort to implement. Recommended for high-security environments.
- **Multiple output formats**: HTML summary, CSV per section/finding, JSON summary, optional XLSX
- **Report history**: full execution history with status, tenancy filter, and download actions (HTML/JSON) in the Reports tab
- **Delete reports**: remove completed reports and their associated files from the system
- **File browser**: dedicated Downloads tab with expandable cards per completed report, files grouped by category (Summary, CIS Findings, OBP, Raw Data, etc.)
- **Embed individual files**: embed any report file (CSV, TXT, JSON, PDF) directly into the ADB vector store for RAG enrichment
- Region filtering with multi-select
- Real-time progress tracking with phase-based progress bar
- **CIS Engine auto-update**: check for new versions of `cis_reports.py` from Oracle's GitHub repository and update with one click (admin only). Custom patches are automatically reapplied after update

### 📋 LAD A-Team CIS Compliance Report
- **Professional compliance report** following Oracle Cloud Security Assessment format (cover page, purpose statement, disclaimer, copyright)
- **Table of Contents** with links to each section and recommendation
- **Security Overview**: 7 Oracle security pillars (Customer Isolation, Data Encryption, Data Management, etc.)
- **CIS Assessment Summary**: table with Domains / Total Controls / Failed / Passed per section
- **CIS Benchmark Recommendation Summary**: full table with Item / Description / Status (OK/FAILED)
- **Detailed findings**: per-recommendation cards with compliance percentage bar, result description, and remediation steps
- **RAG-powered remediation**: enriched remediation steps fetched from ADB vector store (`CISRECOM` table) using cosine similarity search — filters by exact recommendation number, extracts only remediation section from matched chunks
- **Affected resources CSV links**: non-compliant findings show a clickable link to download the CSV with affected resource details (authenticated via JWT token)
- **Download PDF**: `window.print()` with CSS `@page A4` formatting for professional PDF output
- **Caching**: generated HTML cached to disk, subsequent views are instant; "Regenerar" button clears cache and re-generates
- **Collapsible sections**: HTML report and compliance report start minimized, expandable on demand

### 🛡️ Built-in CIS MCP Server (Granular Per-Section)
- **Auto-registered** CIS Compliance Scanner MCP server — available out of the box
- **12 granular tools** instead of monolithic full-tenancy scan:
  - `cis_scan_iam` — IAM checks (CIS 1.1–1.17): users, policies, groups, MFA, API keys
  - `cis_scan_networking` — Network checks (CIS 2.1–2.8): security lists, NSGs, VCNs
  - `cis_scan_compute` — Compute checks (CIS 3.1–3.3): instance metadata, monitoring
  - `cis_scan_logging_monitoring` — Logging/Monitoring checks (CIS 4.1–4.17): audit, alarms, events
  - `cis_scan_storage` — Storage checks (CIS 5.1–5.3): buckets, block volumes, file systems
  - `cis_scan_asset_management` — Asset checks (CIS 6.1–6.2): compartments, tagging
  - `cis_list_configs` / `cis_list_checks` — list available OCI configs and CIS checks
  - `cis_get_check` / `cis_get_remediation` — detailed findings and remediation guidance
  - `cis_get_scan_status` / `cis_invalidate_cache` — session status and cache management
- **Per-section data collection**: each scan tool collects only the OCI data needed for that section, avoiding unnecessary API calls
- **Region-specific scanning**: all scan tools accept optional `regions` parameter to target specific OCI regions (e.g., `["us-ashburn-1"]`) instead of scanning the entire tenancy
- **Session caching**: collected data is cached per config+regions scope (2-hour TTL), so subsequent scans on different sections reuse shared prerequisites (compartments, identity domains)
- **Compartment filtering**: scan results can be filtered by specific compartment, showing only relevant findings
- **Collection error tracking**: errors during data collection are captured per section and reported to the caller
- **Parallelized data collection**: base collectors and regional collectors run in parallel thread pools (up to 8 workers), with 30-minute timeout per tool call and 1 automatic retry on failure
- Based on Oracle's official `cis_reports.py` (6660 lines, 48 CIS + 11 OBP checks)

### 🔌 MCP Server Registry + Tool Discovery
- Register multiple MCP servers (stdio, SSE, Python module)
- **Automatic tool discovery**: connect to MCP servers and discover available tools with names, descriptions, and input schemas
- **Manual tool definition**: add/edit tools with JSON Schema parameter definitions
- **Chat Agent integration**: discovered tools are automatically available as GenAI function calls during chat
- Upload `.py` scripts directly to servers
- **Link MCP servers to ADB Vector** databases as tools
- Activate/deactivate servers
- Select which MCP server to use per report execution

### 🗄️ Autonomous Database Vector Storage
- Oracle Autonomous Database connection with **mTLS Wallet** authentication
- `python-oracledb` Thin mode (no Oracle Client needed)
- Wallet ZIP upload and automatic extraction
- Connection testing with **case-insensitive table validation** against ADB `user_tables`
- **Multiple vector tables per ADB**: register, edit, toggle active/inactive — tables managed inside the edit connection card
- **Multi-table RAG search**: queries all active tables across all ADB configs, merges results by cosine distance
- **Auto-resolve embedding config**: automatically uses existing OCI credentials for GenAI embeddings — no separate GenAI config required
- **Case-insensitive table matching**: supports both uppercase and lowercase table names in Oracle ADB with quoted identifiers

### 🧬 Embeddings & Knowledge Base
- Dedicated tab for managing vector embeddings and knowledge base
- **CIS Recommendations**: upload CIS PDF to populate the `cisrecom` vector table with Oracle Cloud security recommendations
- **Knowledge Base (Base de Conhecimento)**: upload documents (`.txt`, `.pdf`, `.csv`, `.json`, `.md`) or **import URLs** (web pages, PDF links) to populate the `engineerknowledgebase` vector table — content is automatically extracted, chunked, and vectorized
- **URL import**: fetches web pages, strips HTML tags/scripts, extracts readable text, and generates embeddings — supports HTML pages and remote PDFs
- **Embed CIS Reports**: automatically chunk reports by section with tenancy name, regions, and compartments enrichment, with `report_date` metadata for tracking data freshness
- **Purge & re-embed**: option to purge old embeddings by tenancy before re-embedding updated reports
- **Preview chunks before embedding**: review generated sections before creating embeddings
- **OCI GenAI Embeddings**: uses Cohere Embed models (v4.0, multilingual) via OCI GenAI `embed_text` API
- **Consult Embeddings**: dedicated sub-menu under Embeddings with chat-like interface — query the vector store in natural language, AI searches all active tables via cosine similarity and returns contextual answers with source citations
- Browse and inspect embeddings from the ADB vector store
- 3 embedding models supported: Cohere Embed v4.0, OpenAI Text Embedding 3 Large/Small

### 📜 Configuration & Chat Logs
- **Persistent activity log** per configuration tab (OCI, GenAI, ADB, MCP)
- **Chat audit logs**: all chat interactions (user messages, AI responses, tool calls, errors) logged with session/message ID, severity, and source
- Logs all test, save, upload, report, and ingest operations with severity (success/error/info)
- **Inline log panel** at the bottom of each config tab with severity filter
- Auto-cleanup of logs older than 30 days
- Admin can view all logs; users see only their own
- API endpoints for listing and clearing logs

### 🔄 Export / Import Configuration
- **Full config export** as JSON: OCI credentials (with private keys), GenAI configs, MCP servers, system prompts, app settings, ADB vector configs
- **Import** from exported JSON with merge-by-ID (skips existing, prevents duplicates)
- Private keys exported as base64 and restored to disk on import
- Enables full environment migration between machines (Mac ↔ Windows ↔ Linux)

### 🎨 Theme System & UI
- **Light/Dark mode toggle** in the sidebar footer
- **Oracle Dark Premium** design: deep dark backgrounds (#0D0F12), dark cards (#1A1D24), Oracle Red accent (#C74634)
- **Oracle-branded light mode**: warm light backgrounds (original theme)
- Theme preference persisted in localStorage across sessions
- All CSS driven by CSS custom properties — zero hardcoded colors
- **SVG icon system**: 45+ Lucide-based inline SVG icons replace all emojis for cross-platform consistency (Windows/Mac/Linux)
- **KPI Dashboard**: compliance score gauge (SVG semicircular arc with gradient), pass/fail/total KPI cards, donut chart (severity distribution), horizontal bar chart (findings by section) — powered by Chart.js 4.4.7
- **Animated UI**: staggered fade-in for cards/KPIs/tables, smooth theme transitions, hover effects with transforms, shimmer loading states, pulse alerts

### ✏️ Terraform Prompt Editor
- **Inline prompt editor** accessible from the Terraform menu (3-dot menu → Editar Prompt)
- Edit the active Terraform system prompt name and content
- **Auto-save with debounce** (800ms): changes saved to database automatically as you type
- Visual "Salvando..." → "Salvo ✓" indicator

### 🔐 Security
- **JWT authentication** with configurable expiry
- **TOTP MFA** (Google Authenticator / Authy compatible)
- **RBAC** with 3 roles: Admin, User, Viewer
- Audit logging for all operations
- Encrypted credential storage

---

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    Docker Compose                            │
│                                                              │
│  ┌──────────────┐       ┌──────────────────────────────┐    │
│  │  Nginx        │       │  FastAPI Backend              │    │
│  │  (Frontend)   │──────▶│  (Python 3.12)               │    │
│  │  :8080        │       │  :8000                        │    │
│  └──────────────┘       │                                │    │
│                          │  ┌─────────────┐              │    │
│                          │  │ OCI SDK      │──▶ OCI APIs │    │
│                          │  ├─────────────┤              │    │
│                          │  │ GenAI Client │──▶ LLM      │    │
│                          │  ├─────────────┤   (tools)   │    │
│                          │  │ MCP Client   │──▶ MCP Svrs │    │
│                          │  ├─────────────┤   (discover │    │
│                          │  │              │   +execute) │    │
│                          │  ├─────────────┤              │    │
│                          │  │ Terraform    │──▶ Plan /   │    │
│                          │  │              │   Apply    │    │
│                          │  ├─────────────┤              │    │
│                          │  │ oracledb     │──▶ ADB      │    │
│                          │  ├─────────────┤              │    │
│                          │  │ RAG Pipeline │──▶ Embed +  │    │
│                          │  │              │   Search    │    │
│                          │  └─────────────┘              │    │
│                          │                                │    │
│                          │  SQLite (agent.db)             │    │
│                          └──────────────────────────────┘    │
│                                     │                        │
│                              agent-data volume               │
└─────────────────────────────────────────────────────────────┘
```

---

## Quick Start

### Prerequisites

- Docker and Docker Compose
- OCI API Key pair (private `.pem` key + fingerprint)
- OCI Tenancy OCID, User OCID, Compartment OCID

### 1. Clone & Configure

```bash
git clone https://github.com/nogueiragustavo/oci-cis-agent.git
cd oci-cis-agent
cp .env.example .env
```

Edit `.env`:
```env
APP_SECRET=your-very-long-random-secret-string-here-at-least-64-chars
JWT_EXPIRY_HOURS=12
PORT=8080
```

### 2. Build & Run

```bash
docker compose up -d --build
```

### 3. Access

Open `http://localhost:8080`

Default credentials:
- **Username:** `admin`
- **Password:** `admin123`

> ⚠️ Change the default password immediately after first login.

---

## Configuration Guide

### Step 1 — OCI Credentials

Navigate to **OCI Credentials** tab and add:

| Field | Description |
|-------|-------------|
| Tenancy Name | Friendly name (e.g., `my-company`) |
| OCID Tenancy | `ocid1.tenancy.oc1..xxxxx` |
| OCID User | `ocid1.user.oc1..xxxxx` |
| Fingerprint | `aa:bb:cc:dd:ee:ff:...` |
| Region | `sa-saopaulo-1`, `us-ashburn-1`, etc. |
| Compartment OCID | `ocid1.compartment.oc1..xxxxx` |
| Private Key | `.pem` file |
| Key Passphrase | *(optional)* Only required if the private key is encrypted |

Click **Testar** to validate the connection.

### Step 2 — GenAI Model

Navigate to **GenAI Config** tab:

1. Select the **OCI Credential** created in Step 1 — **Region** and **Compartment OCID** are auto-filled from the selected credential
2. Choose a **model** from the catalog
3. Adjust the **GenAI region** if needed (auto-populated, must have Generative AI service available)
4. Adjust parameters (temperature, max_tokens, etc.)
5. The **endpoint** is auto-generated: `https://inference.generativeai.{region}.oci.oraclecloud.com`

For **dedicated endpoints**, switch Serving Type to `DEDICATED` and provide the endpoint ID.

The GenAI connection follows Oracle's official SDK pattern:

```python
# Auth via stored OCI config
config = oci.config.from_file(config_path, "DEFAULT")

# Client with endpoint, retry, and timeout
client = oci.generative_ai_inference.GenerativeAiInferenceClient(
    config=config,
    service_endpoint=endpoint,
    retry_strategy=oci.retry.NoneRetryStrategy(),
    timeout=(10, 240)
)

# Chat with TextContent + Message objects
chat_detail = oci.generative_ai_inference.models.ChatDetails()
chat_detail.serving_mode = OnDemandServingMode(model_id="...")
chat_detail.chat_request = GenericChatRequest(messages=[...])
chat_detail.compartment_id = compartment_id
```

### Step 3 — MCP Servers (Optional)

Register MCP servers for extended task execution and **Chat Agent tool use**:

| Type | Use Case |
|------|----------|
| `stdio` | Local Python scripts (e.g., CIS check runner) |
| `SSE` | Remote HTTP servers |
| `module` | Upload `.py` files directly |

MCP servers can be **linked to ADB Vector** databases, enabling them to use the vector store as a tool during report execution.

**Tool Discovery**: After registering a server, click **"Descobrir Tools"** to automatically discover available tools via MCP protocol. You can also add tools manually with name, description, and JSON Schema parameters. Discovered tools are automatically available as **function calls** in the Chat Agent.

### Step 4 — ADB Vector + RAG (Optional)

For persistent vector storage and RAG-powered chat:

1. Add DSN (TNS name from tnsnames.ora, e.g., `myatp_high`)
2. Set credentials (username/password)
3. Select an **Embedding Model** (Cohere Embed v4.0 recommended)
4. Upload Wallet ZIP (for mTLS)
5. Test the connection
6. **Register vector tables**: add the names of existing tables in your ADB (e.g., `cisrecom`, `engineerknowledgebase`). Table names are case-insensitive and validated against ADB. Toggle tables active/inactive to control which are queried during RAG.

> GenAI Config is optional — the app auto-resolves embedding credentials from your existing OCI config.

### Step 5 — Embeddings (Optional)

Navigate to the **Embeddings** tab to populate the vector store:

1. **CIS Recommendations**: Upload the CIS PDF to populate the `cisrecom` table with Oracle Cloud security recommendations
2. **Knowledge Base**: Upload documents (`.txt`, `.pdf`, `.csv`, `.json`, `.md`) or paste a URL to import web pages — all content goes to the `engineerknowledgebase` table
3. **From CIS Reports** (Downloads tab): Embed completed reports with option to purge old data first
4. Browse and inspect embeddings per table

Once embeddings exist, the **chat automatically uses RAG** — it queries all active vector tables across all ADB configs for relevant context before generating responses with the selected GenAI model.

---

## OCI IAM Policies

The following policies are required in your tenancy:

```
Allow group <group-name> to use generative-ai-family in compartment <compartment-name>
Allow group <group-name> to read all-resources in tenancy
Allow group <group-name> to inspect compartments in tenancy
Allow group <group-name> to inspect autonomous-databases in compartment <compartment-name>
Allow group <group-name> to read virtual-network-family in compartment <compartment-name>
Allow group <group-name> to read instance-family in compartment <compartment-name>
Allow group <group-name> to read objectstorage-namespaces in tenancy
Allow group <group-name> to read buckets in compartment <compartment-name>
```

---

## Project Structure

```
oci-cis-agent/
├── backend/
│   ├── app.py              # FastAPI application (~6700 lines)
│   ├── cis_reports.py       # Oracle CIS Benchmark checker (6660 lines, report engine)
│   ├── mcp_cis_server.py    # MCP server with 12 granular CIS tools (~700 lines)
│   ├── gen_tf_reference.py  # OCI Terraform provider resource catalog generator
│   ├── Dockerfile           # Python 3.12 + OCI CLI + Terraform CLI
│   └── requirements.txt     # Dependencies
├── frontend/
│   └── index.html           # Legacy SPA with Oracle Dark Premium theme (~2800 lines)
├── frontend-react/
│   ├── src/                 # React 19 SPA (TypeScript, 42 source files, ~12500 lines)
│   │   ├── pages/           # 8 page components (Dashboard, Explorer, Reports, Chat, Terraform, etc.)
│   │   ├── api/             # API client + endpoint modules
│   │   ├── stores/          # Zustand auth store
│   │   ├── hooks/           # Custom hooks (theme, i18n)
│   │   └── i18n/            # Internationalization (pt/en, 625 keys)
│   └── dist/                # Built SPA served at /app/
├── scripts/
│   ├── reportgenerator.js   # n8n reference script (report layout)
│   └── *.pdf                # Oracle CIS report PDF template
├── nginx/
│   └── default.conf         # Reverse proxy (legacy / + React /app/ + API /api/)
├── docker-compose.yml       # Orchestration
├── logo.svg                 # Project logo (Oracle AI Robot)
├── .env.example             # Environment template
├── .gitignore
└── README.md
```

---

## API Reference

### Authentication

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/auth/login` | Login (username + password + optional TOTP) |
| POST | `/api/auth/logout` | Logout and invalidate session |
| POST | `/api/auth/register` | Create user (admin only) |
| POST | `/api/auth/change-password` | Change password |

### OCI Management

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/oci/config` | Save OCI credentials (multipart) |
| GET | `/api/oci/configs` | List OCI credentials |
| PUT | `/api/oci/configs/{id}` | Update OCI credential (multipart) |
| POST | `/api/oci/test/{id}` | Test OCI connection |
| DELETE | `/api/oci/configs/{id}` | Delete OCI credential |

### OCI Account Explorer

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/oci/explore/{id}/compartments` | List compartments |
| GET | `/api/oci/explore/{id}/compartment-tree` | Hierarchical compartment tree |
| GET | `/api/oci/explore/{id}/regions` | List subscribed regions |
| GET | `/api/oci/explore/{id}/vcns` | List VCNs |
| GET | `/api/oci/explore/{id}/subnets` | List Subnets |
| GET | `/api/oci/explore/{id}/security_lists` | List Security Lists (with rules) |
| GET | `/api/oci/explore/{id}/nsgs` | List Network Security Groups |
| GET | `/api/oci/explore/{id}/route_tables` | List Route Tables (with rules) |
| GET | `/api/oci/explore/{id}/nat_gateways` | List NAT Gateways |
| GET | `/api/oci/explore/{id}/internet_gateways` | List Internet Gateways |
| GET | `/api/oci/explore/{id}/service_gateways` | List Service Gateways |
| GET | `/api/oci/explore/{id}/network_firewalls` | List Network Firewalls |
| GET | `/api/oci/explore/{id}/network_firewall_policies` | List Firewall Policies |
| GET | `/api/oci/explore/{id}/public_ips` | List Public IPs |
| GET | `/api/oci/explore/{id}/instances` | List Compute Instances |
| GET | `/api/oci/explore/{id}/instance_pools` | List Instance Pools |
| GET | `/api/oci/explore/{id}/container_instances` | List Container Instances |
| GET | `/api/oci/explore/{id}/databases` | List Autonomous Databases |
| GET | `/api/oci/explore/{id}/db_systems` | List DB Systems |
| GET | `/api/oci/explore/{id}/mysql_db_systems` | List MySQL DB Systems |
| GET | `/api/oci/explore/{id}/buckets` | List Object Storage Buckets |
| GET | `/api/oci/explore/{id}/block_volumes` | List Block Volumes |
| GET | `/api/oci/explore/{id}/boot_volumes` | List Boot Volumes |
| GET | `/api/oci/explore/{id}/file_systems` | List File Systems |
| GET | `/api/oci/explore/{id}/mount_targets` | List Mount Targets |
| GET | `/api/oci/explore/{id}/oke_clusters` | List OKE Clusters |
| GET | `/api/oci/explore/{id}/load_balancers` | List Load Balancers |
| GET | `/api/oci/explore/{id}/functions` | List Functions |
| GET | `/api/oci/explore/{id}/iam_users` | List IAM Users |
| GET | `/api/oci/explore/{id}/iam_groups` | List IAM Groups |
| GET | `/api/oci/explore/{id}/iam_policies` | List IAM Policies |
| GET | `/api/oci/explore/{id}/iam_dynamic_groups` | List Dynamic Groups |
| GET | `/api/oci/explore/{id}/vaults` | List Vaults |
| GET | `/api/oci/explore/{id}/dns_zones` | List DNS Zones |
| GET | `/api/oci/explore/{id}/api_gateways` | List API Gateways |
| GET | `/api/oci/explore/{id}/alarms` | List Alarms |
| GET | `/api/oci/explore/{id}/log_groups` | List Log Groups |
| GET | `/api/oci/explore/{id}/notification_topics` | List Notification Topics |
| GET | `/api/oci/explore/{id}/events_rules` | List Events Rules |
| GET | `/api/oci/explore/{id}/counts` | Get cached resource counts (instant from SQLite) |
| POST | `/api/oci/explore/{id}/counts/refresh` | Refresh all resource counts in background |

### OCI Resource Actions

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/oci/instances/{id}/action` | Start/Stop compute instance |
| POST | `/api/oci/autonomous-databases/{id}/action` | Start/Stop Autonomous Database |
| POST | `/api/oci/db-systems/{id}/action` | Start/Stop DB System |
| POST | `/api/oci/mysql-db-systems/{id}/action` | Start/Stop MySQL DB System |
| POST | `/api/oci/container-instances/{id}/action` | Start/Stop Container Instance |

### Generative AI

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/genai/models` | List available models and regions |
| POST | `/api/genai/config` | Save GenAI configuration |
| GET | `/api/genai/configs` | List GenAI configurations |
| PUT | `/api/genai/configs/{id}` | Update GenAI configuration |
| POST | `/api/genai/test/{id}` | Test GenAI connection |
| DELETE | `/api/genai/configs/{id}` | Delete GenAI config |

### MCP Servers

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/mcp/servers` | Register MCP server |
| GET | `/api/mcp/servers` | List MCP servers |
| PUT | `/api/mcp/servers/{id}` | Update MCP server |
| PUT | `/api/mcp/servers/{id}/toggle` | Activate/deactivate |
| POST | `/api/mcp/servers/{id}/upload` | Upload script file |
| PUT | `/api/mcp/servers/{id}/link-adb` | Link to ADB Vector |
| POST | `/api/mcp/servers/{id}/discover-tools` | Auto-discover tools from MCP server |
| PUT | `/api/mcp/servers/{id}/tools` | Manually update tool definitions |
| DELETE | `/api/mcp/servers/{id}` | Delete MCP server |

### ADB Vector

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/adb/config` | Save ADB connection (with GenAI config + embedding model) |
| GET | `/api/adb/configs` | List ADB connections (includes vector tables) |
| PUT | `/api/adb/configs/{id}` | Update ADB connection (multipart) |
| POST | `/api/adb/parse-wallet` | Parse wallet ZIP and extract DSN names |
| POST | `/api/adb/{id}/upload-wallet` | Upload wallet ZIP |
| POST | `/api/adb/test/{id}` | Test ADB connection |
| GET | `/api/adb/{id}/tables` | List vector tables for ADB config |
| POST | `/api/adb/{id}/tables` | Add vector table |
| PUT | `/api/adb/{id}/tables/{tid}` | Update vector table (name, description, active) |
| POST | `/api/adb/{id}/tables/check` | Validate registered tables against ADB (case-insensitive) |
| DELETE | `/api/adb/{id}/tables/{tid}` | Remove vector table |
| DELETE | `/api/adb/configs/{id}` | Delete ADB config |

### Embeddings

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/embeddings/preview/{rid}` | Preview report chunks before embedding (with tenancy/regions/compartments) |
| POST | `/api/embeddings/report/{rid}` | Generate embeddings from CIS report (chunked by section, accepts `table_name`, `report_date`) |
| POST | `/api/embeddings/report/{rid}/file/{fid}` | Embed individual report file (CSV/TXT/JSON/PDF) into vector store |
| POST | `/api/embeddings/upload` | Upload file (.txt/.pdf/.csv/.json/.md) and generate embeddings |
| POST | `/api/embeddings/upload-url` | Import URL (web page or PDF), extract text, and generate embeddings |
| POST | `/api/embeddings/consult` | Query embeddings via vector search + GenAI (natural language Q&A) |
| POST | `/api/embeddings/{vid}/purge` | Purge old embeddings by table + tenancy before re-embedding |
| GET | `/api/embeddings/{vid}/list` | List embeddings in ADB (paginated, accepts `table_name` query param) |
| DELETE | `/api/embeddings/{vid}/{doc_id}` | Delete individual embedding (accepts `table_name` query param) |

### Terraform Agent

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/terraform/chat` | Send message to Terraform Agent |
| GET | `/api/terraform/resources` | List OCI resources in compartment (for context) |
| POST | `/api/terraform/workspaces` | Create Terraform workspace |
| GET | `/api/terraform/workspaces` | List user's workspaces |
| GET | `/api/terraform/workspaces/{wid}` | Get workspace details |
| PUT | `/api/terraform/workspaces/{wid}/code` | Update workspace Terraform code |
| POST | `/api/terraform/workspaces/{wid}/plan` | Run `terraform plan` |
| POST | `/api/terraform/workspaces/{wid}/apply` | Run `terraform apply` |
| POST | `/api/terraform/workspaces/{wid}/destroy` | Run `terraform destroy` |
| GET | `/api/terraform/workspaces/{wid}/status` | Poll workspace execution status |
| GET | `/api/terraform/workspaces/{wid}/download` | Download workspace `.tf` files |
| POST | `/api/terraform/workspaces/{wid}/cancel` | Cancel running Terraform operation |
| DELETE | `/api/terraform/workspaces/{wid}` | Delete workspace |
| POST | `/api/terraform/refresh-reference` | Regenerate OCI Terraform resource reference (UI button) |
| POST | `/api/terraform/generate-prompt` | Generate structured Terraform prompt via AI (Prompt Generator) |

### Chat & Reports

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/chat` | Send message (with RAG + MCP tool use, accepts `use_tools` flag) |
| POST | `/api/chat/upload` | Send message with file attachments (multipart, images/PDFs/text) |
| GET | `/api/chat/sessions` | List chat sessions (history) with agent type filter |
| GET | `/api/chat/sessions/{sid}/messages` | Get messages for a session |
| PUT | `/api/chat/sessions/{sid}/title` | Rename a chat session |
| DELETE | `/api/chat/{sid}` | Delete chat session and messages |
| POST | `/api/reports/run` | Execute CIS report |
| GET | `/api/reports` | List reports |
| DELETE | `/api/reports/{rid}` | Delete report and associated files |
| GET | `/api/reports/{id}/html` | View HTML report |
| GET | `/api/reports/{id}/download` | Download report |
| GET | `/api/reports/{rid}/summary` | Report KPI summary (score, pass/fail, sections) |
| GET | `/api/reports/{rid}/files` | List report files by category |
| GET | `/api/reports/{rid}/files/{fid}/download` | Download individual report file |
| GET | `/api/reports/{rid}/compliance-report` | Serve cached LAD A-Team compliance report HTML |
| POST | `/api/reports/{rid}/compliance-report/generate` | Generate compliance report (background, with RAG) |
| GET | `/api/reports/{rid}/compliance-report/status` | Check if compliance report is ready |

### CIS Engine

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/cis-engine/version` | Current CIS engine version |
| GET | `/api/cis-engine/check-update` | Check GitHub for newer version (admin) |
| POST | `/api/cis-engine/update` | Download + apply update with patches (admin) |

### Config Logs

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/config-logs` | List config logs (filterable by `config_type`, `severity`, `config_id`) |
| DELETE | `/api/config-logs` | Clear config logs (admin, filterable by `config_type`, `config_id`) |

### Admin

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/users` | List users (admin) |
| PUT | `/api/users/{id}` | Update user role/status |
| POST | `/api/mfa/setup` | Generate MFA secret |
| POST | `/api/mfa/verify` | Activate MFA |
| GET | `/api/audit-log` | View audit log (admin) |
| GET | `/api/health` | Health check |

---

## Supported GenAI Models (15 Chat + 3 Embedding)

All models include OCID mapping for `us-ashburn-1`. For other regions, use the "Personalizado (usar OCID)" option.

### Chat Models

| Provider | Model | Model ID | API Format |
|----------|-------|----------|------------|
| Meta | Llama 4 Maverick | `meta.llama-4-maverick-17b-128e-instruct-fp8` | GENERIC |
| Meta | Llama 4 Scout | `meta.llama-4-scout-17b-16e-instruct` | GENERIC |
| Google | Gemini 2.5 Pro | `google.gemini-2.5-pro` | GENERIC |
| Google | Gemini 2.5 Flash | `google.gemini-2.5-flash` | GENERIC |
| OpenAI | GPT-5.2 | `openai.gpt-5.2` | GENERIC |
| OpenAI | GPT-5.1 | `openai.gpt-5.1` | GENERIC |
| OpenAI | GPT-5 Mini | `openai.gpt-5-mini` | GENERIC |
| OpenAI | **GPT-4.1 (Default)** | `openai.gpt-4.1` | GENERIC |
| OpenAI | GPT-4.1 Mini | `openai.gpt-4.1-mini` | GENERIC |
| OpenAI | GPT-4o | `openai.gpt-4o` | GENERIC |
| OpenAI | o4-mini | `openai.o4-mini` | GENERIC |
| OpenAI | o3 | `openai.o3` | GENERIC |
| xAI | Grok 4 | `xai.grok-4` | GENERIC |
| xAI | Grok 3 | `xai.grok-3` | GENERIC |
| xAI | Grok 3 Mini Fast | `xai.grok-3-mini-fast` | GENERIC |

> **Custom OCID**: You can also use any model available in your region by selecting "Personalizado (usar OCID)" and providing the full model OCID.

### Embedding Models

| Provider | Model | Model ID | Dimensions |
|----------|-------|----------|------------|
| Cohere | Embed v4.0 (Multimodal) | `cohere.embed-v4.0` | 1536 |
| OpenAI | Text Embedding 3 Large | `openai.text-embedding-3-large` | 3072 |
| OpenAI | Text Embedding 3 Small | `openai.text-embedding-3-small` | 1536 |

### GenAI Regions

`us-chicago-1` · `us-ashburn-1` · `us-phoenix-1` · `uk-london-1` · `eu-frankfurt-1` · `ap-tokyo-1` · `ap-osaka-1` · `sa-saopaulo-1` · `ca-toronto-1` · `ap-melbourne-1` · `ap-mumbai-1` · `eu-amsterdam-1` · `me-jeddah-1` · `ap-singapore-1` · `ap-seoul-1` · `sa-vinhedo-1`

---

## Tech Stack

| Component | Technology |
|-----------|-----------|
| Backend | Python 3.12, FastAPI 0.115, Uvicorn |
| Frontend | React 19 SPA (Vite + TypeScript) at `/app/` + legacy Vanilla JS SPA, Oracle Dark Premium theme, Chart.js, i18n (pt/en) |
| Auth | JWT + TOTP MFA + RBAC |
| Database | SQLite (WAL mode) |
| OCI SDK | `oci` 2.133.0, `oci-cli` |
| ADB | `python-oracledb` 2.4.1 (Thin mode) |
| GenAI | `oci.generative_ai_inference` |
| Container | Docker Compose, Nginx reverse proxy |
| MCP | Model Context Protocol SDK (stdio/SSE) with tool discovery + execution |
| Terraform | Terraform CLI 1.7.5, OCI Provider |
| CIS Scanner | Oracle CIS Foundations Benchmark 3.0 checker (`cis_reports.py`) |

---

## Versioning

| Version | Date | Changes |
|---------|------|---------|
| **v2.7** | 2026-03 | **LAD A-Team CIS Compliance Report**: professional Oracle-format compliance report with cover page, TOC, Security Overview (7 pillars), CIS Assessment Summary, detailed findings with compliance % bars, RAG-powered remediation from ADB vector store (`CISRECOM` table with strict recommendation number filtering), affected resources CSV download links per non-compliant finding (JWT auth via query param). **React SPA**: 16-page React 19 frontend at `/app/` (TypeScript, Vite, Zustand, 42 source files), dual-served alongside legacy SPA via nginx. **i18n**: full internationalization with 625 keys (pt/en), language switcher persisted in localStorage. **Report management**: delete reports endpoint, embed individual report files (CSV/TXT/JSON/PDF) into vector store. **Terraform ZIP download**: replaced individual file downloads with client-side ZIP generation (pure JS, no external lib). **Explorer UX**: silent polling during start/stop actions eliminates flickering (resources update in-place without clearing the list). **Report sections collapsed by default**: HTML report and compliance report iframes start minimized. |
| **v2.6** | 2026-03 | **Rename**: app renamed to "AI Agent — Infrastructure & Security Engineer". **Session Token Auth**: OCI session token authentication support (type selector API Key/Session Token, conditional form fields, collapsible credential form, type tags in credentials table, `SecurityTokenSigner` backend). **Terraform Workspaces submenu**: sidebar sub-tab listing all workspaces grouped by date with accordion UI, filtered by existing chat sessions (INNER JOIN), actions (plan/apply/destroy/delete/open). **Retry on failure**: "Reenviar" button on failed messages across Chat Agent, Terraform Agent, and Prompt Generator. **Terraform fixes**: `f2` undefined variable in dedup logic, `oci_core_services` false positive validation (data sources excluded), `S.tfCode` reconstruction from `S.tfFiles` for Re-plan, auto-fix button visible without pre-selected model, DRG attachment rules in system prompt. **Resilience**: stuck workspace recovery on container restart (planning/applying/destroying → reset + lock file cleanup). |
| **v2.5** | 2026-03 | **Explorer Expansion**: KPI stats bar with per-category resource counts (cached in SQLite `explorer_counts_cache`, background refresh on compartment access), enhanced views for VCNs/Subnets/Load Balancers/Buckets with expandable cards, start/stop for DB Systems + MySQL + Container Instances (5 resource types total), dead state filtering (`TERMINATED`/`DELETED`/`DELETING` hidden across all 36 endpoints), wider compartment tree (280px), IAM excluded from compartment totals. **Prompt Generator Intelligence**: same knowledge pipeline as Terraform Agent — auto-detects resource types from user message, fetches official docs (Example Usage + Arguments) from GitHub cached in SQLite, uses compact categorized resource reference. **Network Firewall fix**: `NetworkFirewallPolicySummaryCollection` not iterable — added `.items` accessor for collection objects. |
| **v2.4** | 2026-03 | **Terraform Safety & UX**: region safety guard (plan blocked if model omits `variable "region"` — prevents wrong-region provisioning), rollback button on apply failure (manual `terraform destroy` with "ROLLBACK" confirmation), SSH public key field in OCI configs (auto-injected into `terraform.tfvars` for compute instances), reasoning_effort uppercase fix for OCI SDK, split-panel layout (terminal right 40%, files/plan/resources below chat 60%), plan button persists after destroy. **Terraform tfvars**: expanded `oci_var_map` with `ssh_public_key`/`ssh_authorized_keys` auto-mapping from OCI config |
| **v2.3** | 2026-03 | **Consult Embeddings**: dedicated sub-menu with chat-like interface for natural language Q&A against vector store — queries all active tables via cosine similarity, returns contextual answers with source citations (works with or without GenAI config). **Knowledge Base & RAG Enhancements**: Knowledge Base (Base de Conhecimento) with file upload + URL import to `engineerknowledgebase` vector table, CIS Recommendations upload to `cisrecom` table, URL content extraction (HTML tag/script stripping, remote PDF parsing), auto-resolve embedding config from OCI credentials (no separate GenAI config required), `report_date` metadata tracking for embedding freshness, purge & re-embed flow for updated reports. **ADB Vector Improvements**: case-insensitive table matching with quoted identifiers for Oracle ADB, table validation endpoint against `user_tables`, tables section moved inside edit connection card, case-preserving table registration (removed forced uppercase). **Vector search fix**: FLOAT32 compatibility for VECTOR_DISTANCE queries, base64-decoded compartment_id for auto-resolved OCI configs. **Embeddings tab cleanup**: removed delete buttons, simplified to read-only view, updated descriptions. **Dependencies**: added PyPDF2 for PDF text extraction |
| **v2.2** | 2026-03 | **UI Modernization (Phases 1B-5)**: Oracle Dark Premium theme, 45+ Lucide SVG icons replacing all emojis, KPI dashboard with compliance gauge + Chart.js donut/bar charts, report summary API endpoint, Phase 5 animations (staggered fade-in, smooth theme transitions, hover effects) — animations scoped to tab switch only (no flickering on re-render). **Terraform Intelligence**: official resource docs injection from registry.terraform.io (Example Usage + Argument Reference, on-demand fetch + SQLite cache), smart tfvars auto-generation from declared variables, multi-region provider management with `var.region` support, RPC anti-cycle rule, system prompt auto-sync to DB, 60-min polling timeout for long-running applies. **ADB fix**: wallet_password always passed for thin mode mTLS (fixes DPY-6005). CIS_EMBEDDINGS default removed from ADB config |
| **v2.1** | 2026-03 | Terraform Agent (AI-powered IaC generation with plan/apply/destroy lifecycle, workspace management, Terraform CLI in container, inline file editor, split-panel terminal, multi-file generation via `// filename:` markers, **smart file correction** with merge-based updates, **14-point validation checklist**, 100K max_tokens), **3-layer auto-split pipeline** (frontend + backend monolithic HCL splitting into categorized files + backend deduplication), **HCL syntax auto-fix** (single-line blocks expanded to multi-line), **SQLite-based resource type validation** (~937 types with `difflib` suggestions for invalid types), **Terraform Resource Reference** (auto-generated OCI provider catalog from `terraform providers schema -json`, generated at startup to survive volume mounts, stored in SQLite, refreshable via menu button), compact system prompt for Terraform agent, ChatGPT-style chat history for both Chat Agent and Terraform Agent (rename/delete sessions), OCI Resource Actions (start/stop instances and Autonomous DBs from **OCI Account Explorer**), OCI Explorer expanded to 40+ resource types across 8 categories with tree-view navigation and resizable panels, compartment filtering for MCP CIS scans, chat sidebar with model parameters, chat audit logs, collection error tracking in MCP server, tool timeout increased to 30min with auto-retry, memory compaction tuned (6K threshold, 20 recent messages), model catalog trimmed from 69 to 15 curated models, improved GenAI response extraction with fallback for empty responses, fixed layout overflow (no page scroll), provider alias detection with brace-matching parser, multi-region Terraform support |
| **v2.0** | 2026-03 | Async background chat processing (no more 504 timeouts), frontend polling with timestamps, 8 uvicorn workers + 16-thread chat executor for ~12 simultaneous chats, parallelized MCP data collection (5-thread base + 8-thread regional), 2-hour MCP session cache, 5-min tool timeout, full dead code cleanup across backend/frontend/MCP |
| **v1.9** | 2026-03 | Multimodal chat (image/PDF/text file upload with OCI GenAI ImageContent/DocumentContent), region-specific MCP scanning (`regions` param on all scan tools), orphaned report auto-detection on progress poll, nginx timeout increased to 15min, improved API error handling for non-JSON responses |
| **v1.8** | 2026-03 | CIS Engine auto-update from Oracle GitHub with automatic patch reapplication, version check UI card (admin), new `/api/cis-engine/*` endpoints, report file listing and individual download endpoints, reorganized Reports tab (execution history + status) and Downloads tab (file browser only with expandable cards per report), CIS Level description tooltip, persistent log expand during report generation |
| **v1.7** | 2026-03 | Oracle official CIS report engine (replaces lightweight checker), granular report parameters (Level, OBP, Raw Data, Redact), per-report file storage with category browser, tenancy filter in Downloads, individual file download |
| **v1.6** | 2026-03 | Granular CIS MCP server (12 per-section scan tools: IAM, Networking, Compute, Logging/Monitoring, Storage, Asset Management), chat memory compaction with LLM-based summarization, GenAI tool use loop fix (accumulated conversation), chat thinking indicator, auto-registered CIS MCP server |
| **v1.5** | 2026-03 | MCP Tool Use in Chat (GenAI function calling with auto tool discovery + execution via MCP SDK), multi-table ADB vector search, preview chunks before embedding, enriched embeddings with tenancy/regions/compartments, searchable dropdowns, editable vector tables, orphaned report cleanup on restart |
| **v1.4** | 2026-03 | In-place config editing, 69 chat + 11 embedding models with OCID resolution (OpenAI GPT-5.3/5.2/5.1/5/4.1/4o/Codex/Image/Audio, xAI, Google, Meta, ProtectAI), OpenAI Text Embedding 3, custom OCID support, wallet auto-parse with DSN extraction |
| **v1.3** | 2026-03 | Persistent config logs per tab, GenAI auto-fill from OCI credentials, inline UX feedback with loading spinners, MCP type-switch fix, encrypted key passphrase support, Docker stdin hang fix |
| **v1.2** | 2026-03 | RAG pipeline (OCI GenAI embeddings + ADB vector search), dedicated Embeddings tab, CIS report chunking, file upload embedding |
| **v1.1** | 2025-02 | OCI SDK GenAI (exact pattern), OCI Account Explorer, MCP↔ADB linking, full chat parameters |
| **v1.0** | 2025-02 | Initial release: OCI theme, GenAI integration, MCP servers, ADB vector, JWT+MFA+RBAC |

---

## Development

### Run Backend Locally

```bash
cd backend
pip install -r requirements.txt
DATA_DIR=./data uvicorn app:app --reload --port 8000
```

### Run with Docker

```bash
docker compose up -d --build
docker compose logs -f backend
```

### Rebuild After Changes

```bash
docker compose down
docker compose up -d --build
```

---

## Troubleshooting

**OCI CLI test fails with timeout:**
Check that your API key is correctly configured and the tenancy OCID is valid. Ensure outbound HTTPS (443) is allowed.

**GenAI returns 401/403:**
Verify the IAM policy `Allow group ... to use generative-ai-family in compartment ...` exists. Check that the compartment OCID in the GenAI config matches the policy.

**OCI CLI test hangs with passphrase prompt (Docker):**
If your private key is encrypted (`ENCRYPTED` in the PEM header), provide the passphrase in the **Key Passphrase** field when saving the credential. Unencrypted keys work without a passphrase. The app automatically detects encrypted keys and blocks upload if no passphrase is provided.

**ADB connection fails (`DPY-6005: cannot connect`):**
Ensure the wallet ZIP contains `tnsnames.ora` and `ewallet.pem`. The DSN must match a service name in `tnsnames.ora` (e.g., `myatp_high`). If using an auto-login wallet without a custom password, leave the wallet password field empty — the app automatically passes an empty string for `wallet_password` which is required by `python-oracledb` thin mode even for auto-login wallets.

**Container won't start:**
```bash
docker compose logs backend
```

---

## License

MIT

---

<p align="center">
  <sub>Built with ❤️ for Oracle Cloud Infrastructure security compliance</sub>
</p>