# tunectl — AI Agent Instructions

**tunectl** is a battle-tested VPS performance tuning toolkit for Ubuntu 24.04 LTS servers with 1–8 GB RAM.

This file is self-contained. An AI agent reading only this file can execute the full tunectl workflow without referencing any other documentation.

---

## Target Platform

- **OS:** Ubuntu 24.04 LTS
- **RAM:** 1–8 GB (parameters auto-scale based on detected RAM)
- **Python:** Python 3.x required (Ubuntu 24.04 ships Python 3.12)
- **Shell:** bash
- **Optional:** Node.js 18+ / npm for `npx tunectl` invocation

---

## Installation

```bash
# Clone the repository
git clone https://github.com/symulacr/tunectl.git
cd tunectl

# Option A: Run directly via Python
python3 -m tunectl --help

# Option B: Install with pip
pip install .
tunectl --help

# Option C: Run via npx (requires Node.js + npm)
npx tunectl --help
```

---

## Risk Tiers

tunectl organizes 86 tuning parameters into three risk tiers. Each higher tier includes all parameters from the tiers below it.

### Conservative (51 parameters)

Includes only **risk=none** parameters. Zero breakage risk. No reboot required.

Covers: sysctl memory/dirty tuning, inotify limits, I/O scheduler set to `none`, readahead optimization, `noatime` mount option. These are universally safe changes that improve performance on any Ubuntu 24.04 VPS.

### Balanced (80 parameters)

Includes **risk=none** and **risk=low** parameters (51 + 29 = 80 total). Very low risk, well-tested. Some items may need a reboot to take effect.

Adds on top of conservative: zram swap, BBR network congestion control, socket buffer tuning, THP (Transparent Huge Pages) set to `always`, KSM (Kernel Same-page Merging), jemalloc preload, service optimization suggestions, tmpfs `/tmp`.

### Aggressive (86 parameters)

Includes **all** risk levels: **risk=none**, **risk=low**, and **risk=med** (51 + 29 + 6 = 86 total). Low-to-medium risk — may affect specific workloads. Reboot required for full effect.

Adds on top of balanced: `preempt=none` kernel scheduling, cgroup isolation, memory overcommit set to `1`, balanced CPU mitigations. Recommended only after testing with your specific workload.

---

## Commands

tunectl provides 6 commands. Each is described below with its invocation syntax, options, and examples.

### 1. `tunectl discover`

**Purpose:** Detect the system environment and output a JSON profile. Strictly read-only — no system modifications.

**Requires root:** No

```bash
# Run discovery and view the system profile
tunectl discover

# Example output (JSON to stdout):
# {
#   "os_version": "Ubuntu 24.04 LTS",
#   "kernel_version": "6.8.0-101-generic",
#   "ram_mb": 8192,
#   "cpu_count": 4,
#   "disk_type": "virtio",
#   "swap_configured": true,
#   "swap_type": "zram",
#   "swap_total_mb": 4096
# }
```

### 2. `tunectl plan --tier <tier>`

**Purpose:** Show a dry-run tuning plan for the selected tier. Displays all parameters that would be changed, their current values, and target values. No system files are modified.

**Requires root:** No

**Options:**
- `--tier TIER` — Required. One of: `conservative`, `balanced`, `aggressive`.

```bash
# Preview conservative tier changes
tunectl plan --tier conservative

# Preview balanced tier changes
tunectl plan --tier balanced

# Preview aggressive tier changes (all 86 parameters)
tunectl plan --tier aggressive
```

### 3. `tunectl apply --tier <tier>`

**Purpose:** Apply tuning changes for the selected tier. Automatically creates a timestamped backup before making any modifications. Writes sysctl values, config files, and manages services as specified in the manifest.

**Requires root:** Yes — run with `sudo`

**Options:**
- `--tier TIER` — Required. One of: `conservative`, `balanced`, `aggressive`.

```bash
# Apply conservative tier (safest)
sudo tunectl apply --tier conservative

# Apply balanced tier (recommended for most servers)
sudo tunectl apply --tier balanced

# Apply aggressive tier (maximum performance)
sudo tunectl apply --tier aggressive
```

### 4. `tunectl rollback [--list] [--backup TIMESTAMP]`

**Purpose:** Restore system configuration from a backup created by `tunectl apply`. By default, restores from the most recent backup.

**Requires root:** Yes for restore operations — run with `sudo`. Listing backups does not require root.

**Options:**
- `--list` — List available backups sorted newest-first. Does not require root.
- `--backup TIMESTAMP` — Restore from a specific backup by its timestamp identifier.
- (no options) — Restore from the most recent backup.

```bash
# List available backups (no root needed)
tunectl rollback --list

# Rollback to the most recent backup
sudo tunectl rollback

# Rollback to a specific backup
sudo tunectl rollback --backup 2025-01-15T14-30-00
```

### 5. `tunectl audit`

**Purpose:** Verify all 86 manifest tuning entries against the live system state. Reports PASS, FAIL, or SKIP for each entry. Strictly read-only — no system modifications.

**Requires root:** No

```bash
# Run the audit
tunectl audit

# Example output:
# [SWAP-001] PASS  vm.swappiness  expected=180  actual=180
# [MEM-001]  FAIL  vm.dirty_ratio  expected=40  actual=20
# ...
# 51/86 checks passed
```

### 6. `tunectl benchmark [--baseline] [--compare]`

**Purpose:** Run CPU, memory, and disk I/O performance benchmarks using sysbench and fio. Supports capturing a baseline and comparing before/after results.

**Requires root:** No

**Options:**
- (no options) — Run all benchmarks and display current results.
- `--baseline` — Run benchmarks and save results as a baseline for later comparison.
- `--compare` — Run benchmarks and display a comparison table against the saved baseline, showing absolute and percentage changes.

```bash
# Run benchmarks and display results
tunectl benchmark

# Capture a baseline before tuning
tunectl benchmark --baseline

# After tuning, compare against the baseline
tunectl benchmark --compare

# Example comparison output:
# Metric                  Baseline    Current     Change     %Change
# cpu_single_thread       1234 eps    1356 eps    +122       +9.9%
# memory_write            5678 MiB/s  6012 MiB/s  +334       +5.9%
# disk_randread_iops      12000       14500       +2500      +20.8%
```

---

## Root Privileges Summary

| Command       | Requires Root | Notes                                      |
|---------------|---------------|--------------------------------------------|
| `discover`    | No            | Read-only system detection                 |
| `plan`        | No            | Dry-run preview, no changes made           |
| `apply`       | **Yes**       | Modifies system config files and sysctl    |
| `rollback`    | **Yes**       | Restores config files (--list works without root) |
| `audit`       | No            | Read-only verification of live system      |
| `benchmark`   | No            | Runs sysbench and fio performance tests    |

---

## Recommended Workflow

Follow this 5-step sequence to tune a server safely:

1. **Discover** — Detect the current system environment and review the profile.
   ```bash
   tunectl discover
   ```

2. **Plan** — Preview the tuning changes for your chosen tier. Always review the plan before applying.
   ```bash
   tunectl plan --tier balanced
   ```

3. **Apply** — Apply the tuning changes. A backup is automatically created before any modifications.
   ```bash
   sudo tunectl apply --tier balanced
   ```

4. **Audit** — Verify that all tuning parameters were applied correctly.
   ```bash
   tunectl audit
   ```

5. **Benchmark** — Measure performance after tuning. Optionally compare against a pre-tuning baseline.
   ```bash
   tunectl benchmark
   ```

For before/after comparison, capture a baseline before step 3:
```bash
tunectl benchmark --baseline       # Before apply
sudo tunectl apply --tier balanced # Apply tuning
tunectl benchmark --compare        # Compare results
```

---

## Safety Guidance

- **Always preview with `plan` before `apply`.** The `plan` command shows exactly what will change without modifying any files. Review the output before proceeding.
- **Dry-run is the default.** The underlying tuning engine defaults to dry-run mode. No system modifications occur unless you explicitly use `apply`.
- **Automatic backups.** Every `apply` creates a timestamped backup at `/var/lib/tunectl/backups/` before writing any changes. You can always roll back.
- **Start with conservative tier.** If unsure, begin with `--tier conservative` (zero breakage risk), verify with `audit`, then consider upgrading to `balanced`.
- **Rollback is always available.** If anything goes wrong after applying, run `sudo tunectl rollback` to instantly restore the previous state.
- **Parameters auto-scale.** RAM-dependent parameters are automatically scaled based on detected system memory (reference values are for 8 GB). No manual adjustment needed for servers with different RAM sizes.
- **Idempotent operations.** Running `apply` multiple times with the same tier produces the same result. It is safe to re-apply.

---

## Backup Location

All backups are stored at:
```
/var/lib/tunectl/backups/YYYY-MM-DDTHH-MM-SS/
```

Each backup directory contains copies of every config file modified during that apply operation.

---

## Exit Codes

All commands use consistent exit codes:

| Code | Meaning            |
|------|--------------------|
| 0    | Success            |
| 1    | Operational failure |
| 2    | Usage error        |

For `audit`: exit code 0 means all checks passed; exit code 1 means one or more checks failed (expected on untuned systems).

---

## Quick Reference

```bash
# Full workflow (balanced tier)
tunectl discover
tunectl plan --tier balanced
sudo tunectl apply --tier balanced
tunectl audit
tunectl benchmark

# Rollback if needed
sudo tunectl rollback

# View available backups
tunectl rollback --list

# Capture baseline and compare
tunectl benchmark --baseline
sudo tunectl apply --tier balanced
tunectl benchmark --compare
```
