[PATCH 2/2] tuna: Add AGENTS.md guide for AI coding assistants

John Kacur <[email protected]> Tue, 16 Jun 2026 14:23:32 -0400
Newsgroups org.kernel.vger.linux-rt-users
Message-ID <[email protected]>
Add comprehensive documentation for AI coding assistants working with
the tuna codebase. This guide covers project architecture, development
guidelines, build system, testing, and key components including the CLI,
GUI, scheduler management, and CPU power management.

The document is useful for both AI assistants and human developers as
a comprehensive reference to the project structure and conventions.

Assisted-by: Claude Sonnet 4.5 <[email protected]>
Signed-off-by: John Kacur <[email protected]>
---
 AGENTS.md | 415 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 415 insertions(+)
 create mode 100644 AGENTS.md

diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 000000000000..2ae59d8825d2
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,415 @@
+SPDX-License-Identifier: GPL-2.0-only
+
+Copyright 2026 John Kacur <[email protected]>
+
+# AGENTS.md - AI Coding Assistant Guide for tuna
+
+This document provides guidance for AI coding assistants working with the tuna codebase.
+
+## Project Overview
+
+**tuna** is a program for tuning running processes, threads, and interrupt handlers (IRQs) on Linux systems. It provides both a graphical interface and command-line tools for adjusting scheduler policies, priorities, and CPU affinity to optimize real-time performance.
+
+- **License**: GPL-2.0-only
+- **Language**: Python 3.10+
+- **Primary Maintainer**: John Kacur <[email protected]>
+- **Original Author**: Arnaldo Carvalho de Melo <[email protected]>
+- **Repository**: https://git.kernel.org/pub/scm/utils/tuna/tuna.git/
+
+## Architecture
+
+### Directory Structure
+
+```
+tuna/
+├── tuna-cmd.py                   # Main CLI entry point
+├── oscilloscope-cmd.py           # Latency visualization tool
+├── tuna/                         # Core Python package
+│   ├── __init__.py              # Package initialization
+│   ├── tuna.py                  # Core logic and thread/IRQ manipulation
+│   ├── tuna_gui.py              # GTK GUI main window
+│   ├── tuna_sched.py            # Scheduler policy/priority handling
+│   ├── cpupower.py              # CPU power state management
+│   ├── sysfs.py                 # Sysfs interface utilities
+│   ├── new_eth.py               # Network interface utilities
+│   ├── oscilloscope.py          # Oscilloscope visualization
+│   ├── config.py                # Configuration file handling
+│   ├── help.py                  # Help text and documentation
+│   ├── utils.py                 # Utility functions
+│   ├── tuna_gui.glade           # GTK GUI layout definition
+│   └── gui/                     # GUI components
+│       ├── __init__.py          # GUI package initialization
+│       ├── commonview.py        # Shared GUI view components
+│       ├── cpuview.py           # CPU view widget
+│       ├── irqview.py           # IRQ view widget
+│       ├── procview.py          # Process/thread view widget
+│       ├── profileview.py       # Profile management view
+│       └── util.py              # GUI utility functions
+├── docs/                        # Documentation
+│   ├── tuna.8                   # Man page
+│   ├── oscilloscope+tuna.html   # HTML documentation
+│   └── oscilloscope+tuna.pdf    # PDF documentation
+├── tests/                       # Test suite
+│   ├── run_tests.sh             # Test runner script
+│   ├── test_converters.py       # Unit tests for converter functions
+│   ├── test_eperm_handling.py   # Tests for EPERM error handling
+│   └── README.md                # Testing documentation
+├── etc/                         # Configuration files
+│   └── tuna/                    # Example tuna profiles
+├── help/                        # Help files
+│   └── kthreads/                # Kernel thread documentation
+├── po/                          # Translations (gettext)
+├── patches/                     # Patch queue (if any)
+├── local/                       # Local development notes
+├── setup.py                     # Legacy setuptools configuration
+├── pyproject.toml               # Modern Python project metadata
+├── Makefile                     # Build and test targets
+├── tuna.desktop                 # Desktop application launcher
+├── org.tuna.policy              # PolicyKit policy file
+└── ChangeLog                    # Change history
+```
+
+### Core Components
+
+1. **Main CLI** (`tuna-cmd.py`)
+   - Command-line argument parsing using argparse
+   - Subcommand architecture (isolate, move, run, etc.)
+   - Thread and IRQ manipulation
+   - Profile save/load functionality
+
+2. **Core Library** (`tuna/tuna.py`)
+   - Process and thread enumeration
+   - IRQ handling and manipulation
+   - CPU affinity management
+   - Scheduler policy and priority setting
+   - Integration with python-linux-procfs
+
+3. **GUI** (`tuna/tuna_gui.py`, `tuna/gui/`)
+   - GTK-based graphical interface
+   - Interactive views for CPUs, processes, threads, and IRQs
+   - Drag-and-drop CPU affinity assignment
+   - Real-time updates of system state
+   - Profile management
+
+4. **Scheduler Management** (`tuna/tuna_sched.py`)
+   - Parsing and setting scheduler policies (SCHED_FIFO, SCHED_RR, SCHED_OTHER, etc.)
+   - RT priority range validation
+   - Policy name to constant conversion
+
+5. **Oscilloscope** (`tuna/oscilloscope.py`, `oscilloscope-cmd.py`)
+   - Real-time latency visualization
+   - Multi-threaded latency monitoring
+   - Graphical display of scheduling behavior
+
+6. **CPU Power Management** (`tuna/cpupower.py`)
+   - CPU idle state (C-state) management
+   - Enable/disable idle states per CPU
+   - Query idle state information
+
+7. **Utilities**
+   - `tuna/sysfs.py` - Sysfs interface helpers
+   - `tuna/new_eth.py` - Network interface utilities
+   - `tuna/utils.py` - General utility functions
+   - `tuna/config.py` - Configuration file parsing
+
+## Development Guidelines
+
+### Code Style
+
+- Follow PEP 8 Python style guidelines
+- Use 4-space indentation (no tabs)
+- SPDX license identifier at top of each file: `# SPDX-License-Identifier: GPL-2.0-only`
+- Use descriptive variable names
+- Add docstrings for modules and functions
+
+### Python Version
+
+- Target Python 3.10+ for compatibility with RHEL 9+
+- Use modern Python features (type hints encouraged)
+- Avoid deprecated Python 2 constructs
+
+### Dependencies
+
+**Required**:
+- Python >= 3.10
+- python-linux-procfs - Process information library
+
+**Optional** (for GUI):
+- PyGObject (python3-gobject)
+- GTK 3
+- python3-inet_diag (for network socket information)
+
+**System utilities**:
+- PolicyKit (for privilege escalation)
+
+## Build and Installation
+
+### Build Commands
+
+```bash
+# Run unit tests
+make tests
+# or
+make unit-tests
+
+# Run EPERM handling tests
+make test-eperm
+
+# Clean Python cache files
+make pyclean
+
+# Generate ctags
+make tags
+
+# Clean generated logs
+make cleanlogs
+
+# Full clean
+make clean
+```
+
+### Installation
+
+```bash
+# Install with setup.py
+python3 setup.py install
+
+# Install with pip (development mode)
+pip install -e .
+
+# Install via system package manager (Fedora/RHEL)
+dnf install tuna
+```
+
+## Testing
+
+### Test Structure
+
+1. **Unit Tests** (`tests/test_converters.py`)
+   - Tests for CPU list parsing
+   - Tests for thread list parsing
+   - Tests for scheduler policy/priority parsing
+   - Run with: `./tests/run_tests.sh` or `make tests`
+
+2. **EPERM Tests** (`tests/test_eperm_handling.py`)
+   - Tests for handling permission errors gracefully
+   - Validates that tuna continues when operations fail with EPERM
+   - Run with: `make test-eperm`
+
+### Important Testing Notes
+
+- Most tuna operations require root privileges
+- Tests should handle permission errors gracefully
+- GUI tests are not automated (require manual testing)
+
+## Common Tasks
+
+### Adding a New Subcommand
+
+1. Edit `tuna-cmd.py`
+2. Add new parser in `gen_parser()` function
+3. Add command handler function
+4. Update man page (`docs/tuna.8`)
+5. Add tests if applicable
+
+### Modifying Thread/IRQ Manipulation
+
+- Core logic is in `tuna/tuna.py`
+- Uses procfs library for process information
+- IRQ affinity via `/proc/irq/*/smp_affinity` or `/proc/irq/*/smp_affinity_list`
+- Thread affinity via `sched_setaffinity()`
+
+### Modifying GUI
+
+- Main window: `tuna/tuna_gui.py`
+- GUI layout: `tuna/tuna_gui.glade` (edit with Glade)
+- View components: `tuna/gui/` directory
+- Use GTK 3 APIs (PyGObject)
+
+### Working with Scheduler Policies
+
+Tuna supports all Linux scheduler policies:
+
+**Supported Scheduler Policies:**
+- `SCHED_OTHER` (or `OTHER`) - Default time-sharing scheduler for normal tasks
+- `SCHED_FIFO` (or `FIFO`) - Realtime FIFO scheduler (priority 1-99)
+- `SCHED_RR` (or `RR`) - Realtime round-robin scheduler (priority 1-99)
+- `SCHED_BATCH` (or `BATCH`) - Batch processing, lower priority than SCHED_OTHER (priority 0)
+- `SCHED_IDLE` (or `IDLE`) - Very low priority, runs only when no other tasks are runnable (priority 0)
+- `SCHED_DEADLINE` (or `DEADLINE`) - Deadline scheduling for guaranteed bandwidth
+
+**Realtime Policies:** Only SCHED_FIFO and SCHED_RR are considered realtime policies.
+
+```python
+from tuna import tuna_sched
+
+# Parse policy:priority string (FIFO realtime with priority 50)
+policy, priority = tuna_sched.get_policy_and_rtprio("FIFO:50")
+
+# Batch policy (priority must be 0)
+policy, priority = tuna_sched.get_policy_and_rtprio("BATCH:0")
+
+# Idle policy (priority must be 0)
+policy, priority = tuna_sched.get_policy_and_rtprio("IDLE:0")
+
+# Set thread scheduler
+tuna_sched.set_thread_sched(pid, tid, policy, priority)
+```
+
+## Configuration
+
+### Profile Files
+
+Tuna supports profile files that describe system tuning configurations:
+
+```
+# Example profile format
+# Isolate CPUs 2-3
+isolate_cpus: 2-3
+
+# Move IRQ 16 to CPU 0
+irq_16_affinity: 0
+
+# Set thread priority
+thread_1234_policy: FIFO:80
+```
+
+Profiles can be saved with `tuna save` and applied with `tuna profilename`.
+
+## CLI Usage Examples
+
+```bash
+# Show current state
+tuna
+
+# Isolate CPUs 2-3 (move all threads/IRQs away)
+tuna isolate -c 2-3
+
+# Move thread 1234 to CPU 4
+tuna move -t 1234 -c 4
+
+# Set thread scheduler policy
+tuna threads -t 1234 -p FIFO:80
+
+# Move IRQ 16 to CPU 0
+tuna move -q 16 -c 0
+
+# Disable C-states on CPU 2
+tuna cpu_power -c 2 --disable 2
+
+# Run command on isolated CPUs
+tuna run -c 2-3 -- ./my-rt-app
+```
+
+## GUI Usage
+
+Launch tuna without arguments to start the GUI:
+
+```bash
+tuna
+```
+
+The GUI provides:
+- Interactive CPU, thread, and IRQ views
+- Drag-and-drop affinity assignment
+- Real-time system state updates
+- Profile save/load
+- Visual indication of isolated CPUs
+
+## Key Files
+
+- `tuna-cmd.py` - CLI entry point
+- `tuna/tuna.py` - Core thread/IRQ manipulation
+- `tuna/tuna_gui.py` - GUI main window
+- `tuna/tuna_sched.py` - Scheduler policy handling
+- `docs/tuna.8` - Man page
+- `tests/run_tests.sh` - Test runner
+
+## Debugging
+
+Enable debug output:
+
+```bash
+# CLI debug logging to file
+tuna -L DEBUG <command>
+
+# CLI debug logging to console
+tuna -D <command>
+```
+
+Debug logs include detailed information about:
+- Argument parsing
+- Thread and IRQ operations
+- Permission errors
+- System state changes
+
+## Common Gotchas
+
+1. **Root Required**: Most tuna operations require root/sudo privileges
+2. **PolicyKit**: GUI uses PolicyKit for privilege escalation
+3. **EPERM Handling**: Some operations may fail with EPERM (e.g., PID 1, containerized processes)
+   - Tuna should warn and continue, not crash
+4. **Kernel Threads**: Not all kernel threads can be moved to different CPUs
+5. **IRQ Affinity**: Some IRQs may not support affinity changes
+6. **CPU Hotplug**: Tuna assumes static CPU configuration during runtime
+7. **GUI Dependencies**: GUI requires PyGObject and GTK 3
+8. **Converter Functions**: Argument type converters should not have side effects (recent fix)
+
+## Recent Changes
+
+Check `git log` for recent commits. Notable recent development:
+
+**Code Quality Improvements:**
+- Eliminated global variables (`ps`, `irqs`) for better modularity
+- Removed side effects from argparse type converters
+- Deferred type conversions for cleaner argument parsing
+
+**Testing:**
+- Added unit tests for converter functions
+- Improved test documentation
+- Added `.local/` to gitignore for development notes
+
+**Copyright:**
+- Updated copyright notices to reflect current maintainership
+
+## Support and Contact
+
+- Maintainer: John Kacur <[email protected]>
+- Mailing list: [email protected]
+- Bug reports: Send to maintainer with mailing list CC'd
+
+## Git Workflow
+
+- **Main branch**: `main`
+- **Repository**: https://git.kernel.org/pub/scm/utils/tuna/tuna.git/
+- **Patch submission**: Use standard git format-patch/send-email, send to maintainer with mailing list CC'd
+- **Mailing list**: [email protected]
+
+### Development Workflow
+
+1. Make changes to code
+2. Run unit tests: `make tests`
+3. Test manually with root privileges: `sudo tuna <command>`
+4. Update documentation if needed
+5. Submit patches to mailing list or create pull request
+
+## Additional Notes for AI Assistants
+
+1. **Python Version**: Target Python 3.10+ for RHEL 9+ compatibility
+2. **Privilege Handling**: Always check for root privileges and fail gracefully
+3. **Error Recovery**: Permission errors (EPERM) should warn, not crash
+4. **GUI vs CLI**: Changes to core logic affect both interfaces
+5. **procfs Dependency**: Uses python-linux-procfs for process information
+6. **Thread Safety**: GUI runs in GTK main loop, use appropriate threading
+7. **Translations**: Use gettext for user-facing strings
+8. **Policy Files**: Profile format is custom, not standardized
+
+## Related Projects
+
+- **rteval**: Real-time evaluation tool - https://git.kernel.org/pub/scm/utils/rteval/rteval.git
+- **rt-tests**: Real-time test suite - https://git.kernel.org/pub/scm/utils/rt-tests/rt-tests.git
+
+---
+
+**Last Updated**: 2026-06-16
+**Document Version**: 1.0
-- 
2.54.0