Metadata-Version: 2.4
Name: termstats
Version: 0.12.0
Summary: Beautiful terminal server dashboard with real-time charts
Author-email: Martin Pfeffer <support@celox.io>
License-Expression: MIT
Project-URL: Homepage, https://termstats.celox.io
Project-URL: Repository, https://github.com/pepperonas/termstats
Project-URL: Issues, https://github.com/pepperonas/termstats/issues
Keywords: terminal,dashboard,monitoring,system,cpu,memory,server,devops,sysadmin,tui,charts,cli,audio,spectrum,equalizer,bpm,decibel
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: Utilities
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: psutil>=5.9
Requires-Dist: rich>=13.0
Provides-Extra: audio
Requires-Dist: numpy>=1.24; extra == "audio"
Requires-Dist: sounddevice>=0.4.6; extra == "audio"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: numpy>=1.24; extra == "dev"
Requires-Dist: sounddevice>=0.4.6; extra == "dev"
Dynamic: license-file

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/banner.png" alt="termstats banner: your terminal, real insights" width="100%"/>
</div>

# termstats

<div align="center">

**Beautiful terminal server dashboard with real-time charts.**

<!-- headline - generated by tools/badges.py, refreshed by CI on every push to main -->
[![Version](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pepperonas/termstats/main/.github/badges/version.json&style=for-the-badge)](CHANGELOG.md)
[![Lines of code](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pepperonas/termstats/main/.github/badges/loc.json&style=for-the-badge)](termstats/cli.py)
[![Unit tests](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pepperonas/termstats/main/.github/badges/tests.json&style=for-the-badge&logo=pytest&logoColor=white)](tests/)

[![Donate with PayPal](https://img.shields.io/badge/PayPal-support%20this%20project-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.com/donate/?business=martin.pfeffer%40celox.io&item_name=termstats&currency_code=EUR)

<!-- status -->
[![Tests](https://github.com/pepperonas/termstats/actions/workflows/tests.yml/badge.svg)](https://github.com/pepperonas/termstats/actions/workflows/tests.yml)
[![CI matrix](https://img.shields.io/badge/CI-Linux%20%7C%20macOS%20%7C%20Windows-2088FF?logo=githubactions&logoColor=white)](https://github.com/pepperonas/termstats/actions/workflows/tests.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![SemVer](https://img.shields.io/badge/SemVer-2.0.0-blue)](https://semver.org/spec/v2.0.0.html)
[![Changelog](https://img.shields.io/badge/changelog-keep%20a%20changelog-E05735?logo=keepachangelog&logoColor=white)](CHANGELOG.md)
[![Latest tag](https://img.shields.io/github/v/tag/pepperonas/termstats?label=tag&sort=semver)](https://github.com/pepperonas/termstats/tags)
[![Maintained](https://img.shields.io/badge/maintained-yes-brightgreen)](https://github.com/pepperonas/termstats/commits/main)

<!-- runtime -->
[![Python](https://img.shields.io/badge/Python-3.9%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![Python versions](https://img.shields.io/badge/tested%20on-3.9%20%7C%203.13-3776AB?logo=python&logoColor=white)](https://github.com/pepperonas/termstats/actions/workflows/tests.yml)
[![Live by default](https://img.shields.io/badge/mode-live%20by%20default-brightgreen)](#usage)
[![Refresh](https://img.shields.io/badge/refresh-0.5s-informational)](#usage)
[![Terminal](https://img.shields.io/badge/interface-terminal-black?logo=gnubash&logoColor=white)](#usage)
[![No config](https://img.shields.io/badge/config-none-informational)](#usage)
[![No telemetry](https://img.shields.io/badge/telemetry-none-success?logo=ghostery&logoColor=white)](#how-it-works)
[![Offline](https://img.shields.io/badge/network%20calls-zero-success)](#how-it-works)
[![No root](https://img.shields.io/badge/privileges-none%20required-success)](#platform-support)

<!-- platforms -->
[![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-lightgrey)](https://github.com/pepperonas/termstats)
[![Linux](https://img.shields.io/badge/Linux-supported-success?logo=linux&logoColor=white)](https://github.com/pepperonas/termstats)
[![macOS](https://img.shields.io/badge/macOS-supported-success?logo=apple&logoColor=white)](https://github.com/pepperonas/termstats)
[![Windows](https://img.shields.io/badge/Windows-supported-success?logo=windows&logoColor=white)](https://github.com/pepperonas/termstats)
[![Raspberry Pi](https://img.shields.io/badge/Raspberry%20Pi-works-C51A4A?logo=raspberrypi&logoColor=white)](#platform-support)
[![SSH friendly](https://img.shields.io/badge/over%20SSH-yes-success?logo=openssh&logoColor=white)](#usage)
[![Docker friendly](https://img.shields.io/badge/inside%20containers-yes-success?logo=docker&logoColor=white)](#platform-support)

<!-- dependencies -->
[![psutil](https://img.shields.io/badge/psutil-%E2%89%A55.9-orange?logo=python&logoColor=white)](https://github.com/giampaolo/psutil)
[![rich](https://img.shields.io/badge/rich-%E2%89%A513.0-purple?logo=python&logoColor=white)](https://github.com/Textualize/rich)
[![Dependencies](https://img.shields.io/badge/runtime%20deps-2-informational)](#requirements)
[![Install](https://img.shields.io/badge/install-pipx%20%2B%20git-2088FF?logo=git&logoColor=white)](#installation)

<!-- repository -->
[![Top language](https://img.shields.io/github/languages/top/pepperonas/termstats?logo=python&logoColor=white)](https://github.com/pepperonas/termstats)
[![Language count](https://img.shields.io/github/languages/count/pepperonas/termstats)](https://github.com/pepperonas/termstats)
[![Code size](https://img.shields.io/github/languages/code-size/pepperonas/termstats)](https://github.com/pepperonas/termstats)
[![Repo size](https://img.shields.io/github/repo-size/pepperonas/termstats)](https://github.com/pepperonas/termstats)
[![Commit activity](https://img.shields.io/github/commit-activity/m/pepperonas/termstats)](https://github.com/pepperonas/termstats/commits/main)
[![Last commit](https://img.shields.io/github/last-commit/pepperonas/termstats)](https://github.com/pepperonas/termstats/commits/main)
[![Created](https://img.shields.io/github/created-at/pepperonas/termstats)](https://github.com/pepperonas/termstats/commits/main)
[![Contributors](https://img.shields.io/github/contributors/pepperonas/termstats)](https://github.com/pepperonas/termstats/graphs/contributors)
[![Open issues](https://img.shields.io/github/issues/pepperonas/termstats)](https://github.com/pepperonas/termstats/issues)
[![Closed issues](https://img.shields.io/github/issues-closed/pepperonas/termstats)](https://github.com/pepperonas/termstats/issues?q=is%3Aissue+is%3Aclosed)
[![Open PRs](https://img.shields.io/github/issues-pr/pepperonas/termstats)](https://github.com/pepperonas/termstats/pulls)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/pepperonas/termstats/pulls)

<!-- social -->
[![Stars](https://img.shields.io/github/stars/pepperonas/termstats?style=social)](https://github.com/pepperonas/termstats/stargazers)
[![Forks](https://img.shields.io/github/forks/pepperonas/termstats?style=social)](https://github.com/pepperonas/termstats/network/members)
[![Watchers](https://img.shields.io/github/watchers/pepperonas/termstats?style=social)](https://github.com/pepperonas/termstats/watchers)

[![Made by celox.io](https://img.shields.io/badge/bottled%20%F0%9F%8D%BB%20by-Martin%20Pfeffer%20%C2%B7%20celox.io-informational)](https://celox.io)

</div>

---

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/termstats.png" alt="termstats dashboard screenshot" width="800"/>
<br/>
<sub>Rendered with <code>termstats --demo</code> — a scripted machine, so the picture is reproducible.</sub>
<br/><br/>
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/termstats-themes.png" alt="the six termstats themes" width="800"/>
<br/>
<sub>The six themes: default · mono · nord · gruvbox · catppuccin-mocha · viridis</sub>
<br/><br/>
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/compact.png" alt="termstats in an 80 by 24 terminal" width="560"/>
<br/>
<sub>The same dashboard in an 80×24 terminal: panels are dropped whole, nothing is squeezed.</sub>
<br/><br/>
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/eq.png" alt="termstats -eq: a 28-band spectrum analyser" width="800"/>
<br/>
<sub><code>termstats -eq</code>, a live frame — 28 bands from 40 Hz to 16 kHz, peak-hold markers above the bars, and the dim afterglow a falling bar leaves behind</sub>
<br/><br/>
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/db.png" alt="termstats -db: the level meter" width="390"/>
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/bpm.png" alt="termstats -bpm: the tempo detector" width="390"/>
<br/>
<sub><code>termstats -db</code> and <code>termstats -bpm</code> — the level and the tempo, drawn five rows tall, eased between samples, flaring on the beat; under the tempo the metronome head (<code>◆</code>) sweeps from beat to beat</sub>
<br/><br/>
<sub>Every terminal picture comes from <code>tools/screenshots.py</code>, which renders them from <code>--demo</code>; only the banner at the top is artwork.</sub>
</div>

---

A single-command system dashboard that renders CPU, memory, disk, network, top processes, and
live history charts directly in your terminal. No browser, no GUI, no config needed.

```bash
termstats               # live dashboard, refreshing twice a second
termstats --once        # a single snapshot, then exit
termstats --theme nord  # one of six themes; TERMSTATS_THEME=nord does the same
termstats --demo        # a scripted, repeatable machine - for screenshots and trying themes
termstats -eq           # spectrum analyser from the microphone (ts -eq with the alias); -bpm, -db
```

Running it with no arguments gives you the live view. Redirect or pipe it and you get one
snapshot instead, so `termstats > report.txt` still terminates.

## Contents

- [Features](#features)
- [Installation](#installation) — release downloads, the install script, pipx, pip, from source, Windows, the `ts` alias
- [Usage](#usage) — options, themes, environment, choosing the mode, fallbacks, exit
- [What the dashboard shows](#what-the-dashboard-shows) — the panels, disk on macOS, fitting the terminal
- [Microphone modes](#microphone-modes) — `-eq` spectrum analyser, `-bpm` tempo, `-db` level, `-x` both at once; the audio extra
- [Resource use](#resource-use) — what a frame costs, measured, and the levers that are yours
- [The native core](#the-native-core) — the same dashboard in Rust: 0.3 % of a core, 7 MB
- [Using the core as a library](#using-the-core-as-a-library) — the dashboard and the microphone screens as a cell grid, through a C interface
- [History and recommendation](#history-and-recommendation) — record what the machine does, get a computer recommended after 14 days
- [Platform Support](#platform-support)
- [Requirements](#requirements)
- [Health Report (optional)](#health-report-optional)
- [How It Works](#how-it-works) — collectors, cadence, the theme file, project layout
- [Compared with other dashboards](#compared-with-other-dashboards)
- [Development](#development) — tests, mutation testing, screenshots, releasing, badges
- [Naming & history](#naming--history)
- [Troubleshooting](#troubleshooting)
- [Support this project](#support-this-project)
- [Changelog](#changelog) · [License](#license) · [Author](#author)

## Features

- **CPU** — per-core gradient meters + total + steal time (Linux); many-core machines get a heat strip
- **Memory** — RAM & swap, with the kernel's cache as its own segment on the bar
- **Disk** — usage per *real* mountpoint + read/write throughput
- **Network** — TX/RX throughput + total transferred + connections
- **Top Processes** — sorted by CPU, with an inline load bar per process
- **Braille Area Charts** — CPU & network history at 2×4 dots per cell, filled with a vertical gradient, frameless, on a time-labelled axis, with live values in the title
- **Header Sparkline** — the last 30 s of CPU in sixteen cells, centred between identity and clock
- **Peak Markers** — every meter carries a hairline at its 30-sample high-water mark that decays with the data
- **Calm Under Load** — fixed-width numbers, eased fills, stable sort: no element changes width or place when a value moves
- **Six Themes** — `default`, `mono`, `nord`, `gruvbox`, `catppuccin-mocha`, `viridis`; each an OKLab ramp that is monotone in lightness and checked on truecolor, 256 and 16 colours
- **Fits Your Terminal** — the layout is height-aware, relayouts on resize, and nothing is drawn off-screen; `--compact` and `--no-border` when space is tight
- **One Colour Ramp** — cool → warm → hot, shared by every meter, value and chart
- **Cross-Platform** — Linux, macOS, Windows; braille → block → ASCII and truecolor → 256 → 16 → mono fallbacks, `NO_COLOR` honoured
- **Live by Default** — no flag needed; snapshot mode kicks in automatically when output is piped
- **Leaves Cleanly** — `Esc`, `q` or `Ctrl+C`; alternate screen, cursor and input mode all restored
- **`--demo`** — a scripted machine (network burst, CPU spike, filling disk) that plays the same way every time
- **Microphone modes** — `-eq` a 28-band spectrum analyser with peak hold, `-bpm` a tempo detector, `-db` a level meter, `-x` level and tempo side by side; the headline number is drawn five rows tall, eased between samples and flaring on the beat; optional `termstats[audio]` extra, `--demo` plays scripted music
- **They Move** — 30 frames a second; bars ease in seconds not frames, leave an afterglow that falls under gravity, peak markers hold then drop, every beat is an envelope that nudges the bars, lights the dot and flares the tempo, and a metronome sweeps between beats
- **Light on the Machine** — with the optional [native core](#the-native-core) the live dashboard takes about 0.3 % of one CPU core and 7 MB; without it, about 5 % ([Resource use](#resource-use))
- **Zero Config** — flags and environment variables only; no config file, no state on disk

## Installation

termstats is two programs that work together. Install either, or both:

| | What it is | Platforms | Needs |
|---|---|---|---|
| **`termstats-native`** | the system dashboard as one native binary — about 0.3 % of a CPU core | macOS, Linux | nothing |
| **`termstats`** | the Python program: the same dashboard plus the microphone modes, `--demo`, snapshots and every fallback | macOS, Linux, Windows | Python 3.9+ |

With both installed, `termstats` hands the live dashboard to the native binary by itself
(see [The native core](#the-native-core)). Every release carries both as downloads, plus
a `termstats.exe` for Windows that needs no Python: pick your platform on
**[termstats.celox.io](https://termstats.celox.io)**
([termstats.celox.io/download](https://termstats.celox.io/download) sends the file for the
machine you are on), or take the files from
[github.com/pepperonas/termstats/releases/latest](https://github.com/pepperonas/termstats/releases/latest).

> **Note:** termstats is not on PyPI — install it from the releases or from this repository.

### The native dashboard (macOS, Linux)

```bash
curl -fsSL https://github.com/pepperonas/termstats/releases/latest/download/install.sh | sh
termstats-native
```

The script downloads the binary for your machine from the latest release, checks it against
the release's `SHA256SUMS` and puts it into `~/.local/bin` — no toolchain, no root.
`TERMSTATS_BIN_DIR=/usr/local/bin` installs elsewhere, `TERMSTATS_VERSION=v0.12.0` a
particular release.

Or by hand — pick your machine:

| Machine | Download |
|---|---|
| macOS, Apple silicon | [`termstats-native-aarch64-apple-darwin.tar.gz`](https://github.com/pepperonas/termstats/releases/latest/download/termstats-native-aarch64-apple-darwin.tar.gz) |
| macOS, Intel | [`termstats-native-x86_64-apple-darwin.tar.gz`](https://github.com/pepperonas/termstats/releases/latest/download/termstats-native-x86_64-apple-darwin.tar.gz) |
| Linux, x86_64 | [`termstats-native-x86_64-unknown-linux-musl.tar.gz`](https://github.com/pepperonas/termstats/releases/latest/download/termstats-native-x86_64-unknown-linux-musl.tar.gz) |
| Linux, ARM64 (Raspberry Pi 4/5, ARM servers) | [`termstats-native-aarch64-unknown-linux-musl.tar.gz`](https://github.com/pepperonas/termstats/releases/latest/download/termstats-native-aarch64-unknown-linux-musl.tar.gz) |

```bash
curl -fsSLO https://github.com/pepperonas/termstats/releases/latest/download/termstats-native-aarch64-apple-darwin.tar.gz
tar -xzf termstats-native-aarch64-apple-darwin.tar.gz
mv termstats-native ~/.local/bin/        # any directory on your PATH
```

The Linux binaries are static and run on any distribution. A file downloaded with a
**browser** on macOS is quarantined and the binary is not notarised — remove the mark once
with `xattr -d com.apple.quarantine termstats-native` (a `curl` download carries none).

### The Python program — pipx (recommended)

```bash
pipx install https://github.com/pepperonas/termstats/releases/download/v0.12.0/termstats-0.12.0-py3-none-any.whl
```

That is the released version. The current state of the repository instead:

```bash
pipx install git+https://github.com/pepperonas/termstats.git
```

### pip (user install)

```bash
pip install --user https://github.com/pepperonas/termstats/releases/download/v0.12.0/termstats-0.12.0-py3-none-any.whl
```

### From source

```bash
git clone https://github.com/pepperonas/termstats.git
cd termstats
pipx install --editable .    # or: pip install -e .
(cd native && cargo install --path .)   # the native dashboard, needs a Rust toolchain
```

An editable install points at the checkout, so `git pull` (or your own edits)
take effect immediately — no reinstall needed.

### Windows

Without Python: download
[`termstats-windows-x86_64.zip`](https://github.com/pepperonas/termstats/releases/latest/download/termstats-windows-x86_64.zip),
unpack it and run `termstats.exe` — it is the Python program frozen together with its
interpreter and the microphone modes (64-bit Windows 10/11). It is not code-signed, so
SmartScreen may ask once (*More info → Run anyway*); check the file against the release's
`SHA256SUMS` first. The native core, `record` and `recommend` do not run on Windows.

With Python, the pipx and pip commands above work in PowerShell; pipx puts `termstats.exe` into
`%USERPROFILE%\.local\bin` (run `pipx ensurepath` once). Use **Windows Terminal**: it draws
the braille charts and 24-bit colour, and termstats recognises it through `WT_SESSION`. The
classic console window works too, but its fonts have no braille — start it with
`$env:TERMSTATS_GLYPHS = 'block'`. Resizing takes effect with the next refresh there
(Windows has no `SIGWINCH`), and see [Troubleshooting](#troubleshooting) before redirecting
output in Windows PowerShell 5.1.

### A shorter name

Two letters are enough at the prompt. It is a shell alias, not a second command — there is
deliberately no `stats` executable:

```bash
alias ts=termstats          # bash / zsh: put it in ~/.zshrc or ~/.bashrc
```

```powershell
Set-Alias ts termstats      # PowerShell: put it in $PROFILE
```

### Verify

```bash
termstats --version          # -> termstats 0.12.0
termstats-native --version   # -> termstats-native 0.12.0
```

If your shell says `command not found`, see [Troubleshooting](#troubleshooting).

## Usage

```bash
# Live dashboard (full-screen, refreshes every 0.5s, Ctrl+C to exit)
termstats

# Live with a custom refresh interval
termstats --interval 3
termstats -i 2

# One snapshot, then exit — even in a terminal
termstats --once
termstats -1

# Piped or redirected: snapshot mode is chosen automatically
termstats > report.txt
termstats | grep Load

# Force live even when piped
termstats --live | tee session.log

# Themes
termstats --theme gruvbox
termstats --list-themes           # every theme with its ramp
TERMSTATS_THEME=nord termstats    # the same, from the environment

# Frames: less padding, or title rules instead of boxes
termstats --compact
termstats --no-border --once > report.txt

# A scripted machine - screenshots, trying themes, showing it off
termstats --demo

# Module form (equivalent, requires the package + deps importable)
python -m termstats
```

### Options

| Flag | Description |
|------|-------------|
| *(none)* | Live dashboard in a terminal; a single snapshot when stdout is not a terminal |
| `-i N`, `--interval N`, `-interval N` | Live refresh interval in seconds (default: 0.5) |
| `-1`, `--once`, `-once` | Force a single snapshot and exit |
| `-l`, `--live`, `-live` | Force the live dashboard, even when piped |
| `-t NAME`, `--theme NAME`, `-theme NAME` | Colour theme (see [Themes](#themes)); overrides `TERMSTATS_THEME` |
| `--list-themes`, `-list-themes` | Print every theme with its ramp and exit |
| `--compact`, `-compact` | No padding inside the panels — two more bar cells per row |
| `--no-border`, `-no-border` | Title rules instead of frames; the body gets the full width |
| `--demo`, `-demo` | Scripted, repeatable metrics instead of this machine's (says **DEMO** in the header); with an audio mode, scripted music instead of the microphone |
| `-eq`, `--equalizer` | Live microphone spectrum analyser: 28 bands, peak hold, BPM and dBFS in the HUD ([audio extra](#microphone-modes)) |
| `-bpm`, `--bpm` | Tempo detector: BPM, confidence, beat indicator, kick-band meter, tempo history |
| `-db`, `--db` | Level meter: dBFS with a peak hairline, session min/max, level history |
| `-x`, `--x`, `--mix` | Level and tempo together: both headline numbers, meters and histories side by side; stacked on a narrow terminal |
| `-d`, `--device NAME` | Microphone to use, by any part of its name; default is the system input |
| `--list-devices` | List the input devices and exit |
| `-V`, `--version`, `-version` | Show version |
| `-h`, `--help`, `-help` | Show help |

Flags may be combined in any order, and every long option is also accepted with a single dash
(`-live`, `-once`, `-interval`, …). An unknown option, a bad interval, or `--live` together
with `--once` is an **error** — message on stderr, exit code 2 — never a silent fallback.

`--interval` is the *live refresh rate*. A snapshot always samples for one second, because
throughput figures need a measurable gap between two reads; passing an interval alongside
`--once` is accepted and ignored.

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/help.png" alt="the output of termstats --help" width="640"/>
<br/>
<sub><code>termstats --help</code> — every option, the single-dash spellings and the environment variables on one screen.</sub>
</div>

### Themes

```bash
termstats --list-themes
```

| Theme | Character |
|-------|-----------|
| `default` | Teal → amber → coral on a blue-black ground; the one in the screenshots |
| `mono` | Greys only — for terminals, and people, that do not want colour to carry meaning |
| `nord` | The Nord palette: frost blues, a yellow warning, an aurora red |
| `gruvbox` | Gruvbox dark: aqua, yellow, orange, red on warm grey |
| `catppuccin-mocha` | Catppuccin Mocha: teal, yellow, peach, red on mocha |
| `viridis` | The scientific colour map: purple → teal → green → yellow, perceptually uniform |

Every theme is a **ramp of four stops in OKLab**, interpolated in that space and mapped back
into the sRGB gamut by reducing chroma, never by clipping. Each ramp is **monotone in
lightness** — a higher load is always a brighter cell, so the meters still read as a scale
on a screen with poor colour — and each is checked to survive **quantisation to 256 and 16
colours** without folding two loads into one colour band. On a 16-colour terminal the ramp
is drawn from four named colours the theme chooses itself.

`--theme` wins over `TERMSTATS_THEME`; an unknown name is an error that lists the valid ones.

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/list-themes.png" alt="termstats --list-themes: every theme with its ramp and band counts" width="560"/>
<br/>
<sub><code>termstats --list-themes</code>: each ramp as a swatch, and how many distinct bands survive on 256 and 16 colours.</sub>
</div>

### Environment

| Variable | Effect |
|----------|--------|
| `TERMSTATS_THEME=name` | Default theme (the `--theme` flag overrides it) |
| `TERMSTATS_GLYPHS=braille\|block\|ascii` | Force a glyph level — `block` for fonts without braille, `ascii` for the plainest terminal |
| `TERMSTATS_NERD_FONT=1` | Prefix panel titles with Nerd Font icons |
| `TERMSTATS_NATIVE=0` | Never hand the live dashboard to `termstats-native` (see [The native core](#the-native-core)); a path instead of `0` names the binary to use |
| `NO_COLOR` | Any value: no colour and no bold/dim at all ([no-color.org](https://no-color.org)) |
| `COLORTERM=truecolor` / `24bit` | Enables 24-bit colour where `TERM` alone would suggest 256 |
| `WT_SESSION` | Set by Windows Terminal, which exports neither `TERM` nor `COLORTERM`; read as 24-bit colour |
| `TERM=dumb` | ASCII glyphs and no colour |

Detection order for colour is `NO_COLOR` → `TERM=dumb` → `COLORTERM` → `WT_SESSION` →
`TERM`, and for glyphs `TERMSTATS_GLYPHS` → `TERM=dumb` → whether stdout can encode the
drawing characters. When nothing at all is set on Windows — a bare console window — the
Windows build decides: 24-bit colour from Windows 10 1703 on, 16 colours before. Nothing is
read from a config file; there is none.

### Fallbacks

Both axes degrade **whole**: a glyph level is a complete vocabulary and a colour level a
complete palette, so the renderer never mixes two. Force any of them to see what a plainer
terminal gets, or to work around a font:

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/glyphs.png" alt="the same dashboard at the braille, block and ascii glyph levels" width="800"/>
<br/>
<sub>Glyph levels, left to right: <code>braille</code> (2×4 dots per chart cell), <code>block</code> (eighth-cell blocks — for fonts without braille), <code>ascii</code> (nothing outside 7-bit; the chart is hand-drawn). <code>TERMSTATS_GLYPHS=…</code> picks one.</sub>
</div>

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/colours.png" alt="the same dashboard on truecolor, 256, 16 colours and without colour" width="800"/>
<br/>
<sub>Colour levels: <code>truecolor</code>, <code>256</code>, <code>16</code> (named colours the theme chooses itself), <code>mono</code> (what <code>NO_COLOR=1</code> prints — the lightness scale alone still reads as a scale). <code>COLORTERM</code>, <code>WT_SESSION</code> and <code>TERM</code> decide; <code>--theme mono</code> keeps greys with colour escapes, <code>NO_COLOR</code> removes every escape.</sub>
</div>

The microphone screens degrade with everything else — bars, peak markers, the big digits and
the frequency axis all survive a terminal that can only draw 7-bit characters:

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/eq-ascii.png" alt="the equalizer drawn in ASCII only" width="620"/>
<br/>
<sub><code>TERMSTATS_GLYPHS=ascii termstats -eq</code>: the bars become <code>#</code>, the peak markers <code>-</code>, and nothing outside 7-bit is drawn.</sub>
</div>

### Choosing the mode

| Invocation | What happens | Why |
|------------|--------------|-----|
| `termstats` in a terminal | Live dashboard | A human is watching — keep it updating |
| `termstats > file`, `termstats \| less`, cron | One snapshot, exit 0 | A live loop would never terminate |
| `termstats --once` | One snapshot | Explicit beats inference |
| `termstats --live \| tee log` | Live dashboard | Explicit beats inference |

The terminal check is `sys.stdout.isatty()` — the same rule `ls` uses to decide whether to
print columns.

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/snapshot.png" alt="the first frame of termstats --once: charts still collecting" width="760"/>
<br/>
<sub>What a redirected run prints: the first frame. Rates already have their second sample (the one-second priming pause), the charts show their <code>collecting</code> skeleton — a chart needs history, a snapshot has none.</sub>
</div>

### Exit

In a live session, press **`s`** for the statistics dashboard, **`b`** for the BPM display,
**`d`** for the dB display, or **`x`** for both together. Press **`Esc`** or `Ctrl+C` to exit 0 without a traceback; the
alternate screen buffer, the cursor and the terminal's input mode are restored, so your
scrollback stays intact. `q` works too. The key is read within a tenth of a second, the same
slice a resize is noticed in.

For a single keypress to arrive at all, the terminal spends the session in cbreak mode. When
stdout is a terminal but stdin is not (`termstats --live < /dev/null`), or input is redirected,
nothing is read and `Ctrl+C` remains the way out. Resizing relayouts the dashboard at once
rather than at the next tick. An interrupted snapshot exits 130, quietly.

## What the dashboard shows

| Panel | Content |
|-------|---------|
| **Header** | Identity on the left — hostname, OS, load average (1/5/15 min), CPU count, uptime, process count — the wall clock, refresh interval and version on the right, and a **sixteen-cell CPU sparkline** centred between them (each cell the *peak* of its slice, tinted by the ramp). Every field has a fixed width, so nothing to its right moves when a number grows. The 1-minute load is coloured by the ramp against `2× CPUs`. In `--demo` a **DEMO** badge follows the wordmark. |
| **CPU** | One meter per logical core, plus a total. Every meter carries a **peak hairline** (`╵`) at the highest value of the last 30 samples, which moves down as the spike leaves the window; in live mode the fill eases towards its target while the number and the hairline stay raw. They sit in one tall column while they fit, split into up to four when they do not, and collapse to a single-line heat strip on machines with more cores than the panel can list. On Linux an additional **steal** meter shows hypervisor-stolen time, computed as a delta from `/proc/stat` between refreshes — the single most useful metric on an oversold VPS. |
| **Memory** | RAM and swap, with used/total beside the bar. The RAM bar has **two segments**: what processes hold (ramp colours) and what the kernel keeps as cache (`▒`, the same hue dimmed). psutil's `percent` counts cache as used, so the number is the sum of both — that is the "how full" everyone means — and the bar shows how it splits; `+5.7G cache` is spelled out in the note when the panel is wide enough. Swap is only shown when the machine actually has swap configured. |
| **Disk** | One meter per *real* mountpoint, plus system-wide read/write throughput. Pseudo filesystems (`tmpfs`, `devtmpfs`, `squashfs`, `overlay`, `devfs`, `autofs`) and volumes the OS marks `nobrowse`/`dontbrowse` are skipped, duplicate mountpoints collapsed. On macOS `/` reports the Data volume of its APFS group — see [Disk on macOS](#disk-on-macos). |
| **Network** | TX/RX throughput measured between refreshes, lifetime totals, and the open connection count. |
| **CPU History** | Braille **area** chart of total CPU over the last 60 samples, on an axis labelled in seconds-ago. The fill is tinted by the ramp at the *mean* load of the window, so a chart that has gone amber says the same thing an amber meter does. The steal series is drawn as a line over it whenever it is non-zero. The title states the newest value: `cpu · last 30s · 42%`. |
| **Network History** | rx as a filled area, tx as a line over it — two overlapping fills turn to mud where they cross. The axis is rounded (`0 / 300 / 600`, never `466.6`) and switches from KB/s to MB/s when the window's peak passes 2 MB/s. The title is a legend that doubles as a readout: `▇ rx 3.1MB/s  ━ tx 1.2MB/s · MB/s` — the filled glyph for the area, the bar for the line. |
| **Top Processes** | The hungriest processes by CPU — as many as the remaining height allows — each with an inline load bar and RSS. Ties are broken by PID, so rows do not swap places between frames. |
| **Footer** | `Ctrl+C to exit` in live mode, and `© <year> Martin Pfeffer \| celox.io` — the year from the clock. |

Everything colour-coded shares **one ramp**: cool at idle, warm under load, hot when
saturated. Each cell of a bar is tinted by its own position on that ramp, so a long bar
reads as a scale rather than a block, and the same ramp colours the load average, the chart
fills and the CPU/memory columns of the process table. The ramp is the theme's — see
[Themes](#themes) — built in OKLab and quantised down automatically on 256- and 16-colour
terminals. Values are bright and bold in the ramp tone, their units dim; panel titles are
the theme's accent, every frame the same quiet border.

### Disk on macOS

A stock Mac reports **nine** partitions for one physical disk — `/`, `/System/Volumes/VM`,
`Preboot`, `Update`, `xarts`, `iSCPreboot`, `Hardware`, `Data` and any mounted volume — four
of which claim the same total, because APFS shares free space across a container.

termstats hides everything Apple itself marks `nobrowse`/`dontbrowse` (the same flag that
keeps them out of Finder), and reports `/` using the **Data** volume of its APFS group.
Without that substitution the sealed, read-only system snapshot would show ~11G used on a
disk that is 98% full.

Throughput and steal are *rates*, so they need two samples. A snapshot primes the counters,
waits one second, and then prints — which is why `termstats --once` takes about a second. The
two history charts show a dotted baseline and `collecting · 2 samples needed` until the
second sample arrives, so they stay empty in snapshot mode by design; the live view fills
them in, and `--demo` opens with sixty samples already drawn.

The history buffer holds **60 samples**, not 60 seconds. At the 0.5 s default that is a
30-second window, and the panel titles say so — `last 30s`, or `last 3m` at `-i 3`. They are
computed from the interval rather than hard-coded, because "last 60s" was only ever true for
one particular interval.

### Fitting the terminal

The layout is height-aware. It measures what each panel needs, then spends the remaining
lines from the top: the CPU row and the memory/network/disk stack first, then the charts,
then as many processes as are left over. A panel that cannot be drawn with at least two rows
of content is **dropped whole** rather than reduced to an empty frame, and whichever panel
ends up last takes the leftover lines so nothing is left blank.

The dashboard therefore looks different on a 24-line terminal than on a 60-line one, by
design. Widen or lengthen the window and more of it appears — a resize is picked up at once
(`SIGWINCH`), not at the next refresh. Windows has no `SIGWINCH`; there the new size lands
with the next refresh, half a second later at most.

When columns are what you are short of, `--compact` drops the padding inside every panel
(two more bar cells per row) and `--no-border` replaces the frames with a title rule above
each body, which then runs the full width with a one-column gutter between the two columns.
Both are additive and both keep every layout invariant: nothing wider than the terminal, no
blank line inside the picture, every section whole or absent.

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/no-border.png" alt="termstats --no-border in a 120 by 36 terminal" width="760"/>
<br/>
<sub><code>--no-border</code> at 120×36: a title rule above each body instead of a frame, one gutter column between the two columns.</sub>
</div>

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/narrow.png" alt="termstats in a 100 by 26 terminal: one section dropped whole" width="640"/>
<br/>
<sub>100×26: not enough lines for everything, so the layout drops a whole section from the bottom instead of squeezing every panel. Nothing is drawn off-screen.</sub>
</div>

## Microphone modes

`termstats -eq`, `-bpm` and `-db` turn the same shell — header, theme, footer, fallbacks,
`Ctrl+C` — into a spectrum analyser, a tempo detector and a level meter fed by the
microphone; `-x` shows the level and the tempo on one screen. Nothing is recorded or
stored: blocks of 1024 samples are analysed and dropped. With the `ts` alias they are
`ts -eq`, `ts -bpm`, `ts -db`, `ts -x`, and in a live session the keys `b`, `d` and `x` move
between them.

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/eq.png" alt="termstats -eq: a 28-band spectrum analyser with peak-hold markers" width="760"/>
<br/>
<sub><code>termstats -eq</code>: 28 log-spaced bands from 40 Hz to 16 kHz, two cells per bar, coloured by height on the theme ramp, a peak-hold marker above each bar, a frequency axis — and the HUD every mode shares: beat dot, BPM, dBFS, confidence.</sub>
</div>

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/bpm.png" alt="termstats -bpm: the tempo detector" width="760"/>
<br/>
<sub><code>termstats -bpm</code>: the tempo, a beat dot that lights on every detected onset, confidence (how regular the beats are), a kick-band meter with its peak, and the tempo over time.</sub>
</div>

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/db.png" alt="termstats -db: the level meter" width="760"/>
<br/>
<sub><code>termstats -db</code>: the level of every block in dBFS, a meter with the recent peak as a hairline, the smoothed value, session minimum and maximum, and a level history. All three pictures come from <code>--demo</code>, which plays scripted music instead of opening a microphone.</sub>
</div>

### Level and tempo together

`termstats -x` (or `x` in a live session) is for the moment you want both numbers at
once — how loud, how fast — without looking at two windows or reading a HUD line:

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/mix.png" alt="termstats -x: level and tempo side by side" width="760"/>
<br/>
<sub><code>termstats -x</code>: the level on the left, the tempo on the right, under their own headings. Both headline numbers sit on the same rows, the level meter beside the confidence meter, the extremes beside the kick band, and the two histories start on the same row — everything to compare is on one horizontal line.</sub>
</div>

The screen is laid out for comparison rather than for a list. On a terminal wide enough
for two columns of forty cells (about 90 columns) the level takes the left column and the
tempo the right, and every element has its counterpart on the same row: heading, five
rows of digits, the line under them, the meters (level | confidence, extremes | kick
band), and the charts. The HUD line the single screens share is not drawn — everything
it carried is on screen at full size, and the beat dot moves into the tempo heading. The
same eased digits, metronome, afterglow and beat flare as on the single screens apply,
and the charts are still built off the render path.

Narrower than that, the two blocks stack under the shared HUD: level first, then tempo,
both numbers big when the terminal has about 23 rows for them and both on one line
otherwise — never one big and one small, which would read as if one mattered more. The
level history gets the remaining rows, and the tempo history joins it when there is
room for two charts. On the tightest terminals the breathing lines go before the
kick-band meter does, so an 80×11 window still shows every number.

### Installing the audio extra

The FFT needs numpy and the microphone needs PortAudio (via `sounddevice`); the system
dashboard needs neither, so they are an **optional extra** and a bare `termstats -eq` without
them says so and exits 2:

```bash
pipx install 'termstats[audio] @ git+https://github.com/pepperonas/termstats.git'   # fresh install
pipx inject termstats numpy sounddevice                                            # already installed
```

macOS and Windows wheels bundle PortAudio. Debian/Ubuntu need the library itself:
`sudo apt install libportaudio2`. The first run on macOS asks for microphone access for your
terminal application; deny it and the modes show silence, not an error.

### What is measured

| | |
|---|---|
| **Level** | RMS of each 1024-sample block, shown on the **positive scale a phone's sound-level app uses**: a quiet room reads about 40, conversation about 60, loud music about 80. Internally it is dBFS — decibels relative to the input's full scale, negative by definition and floored at −80 — and the display adds a fixed offset of 100. That offset is an **estimate, not a calibration**: without a reference microphone there is no true sound-pressure value, so the number is comparable between runs on the same device, not between devices, and it is not a measurement you can put in a noise complaint. Nothing but the display is shifted — the analysis, the history and the tempo gate all stay in dBFS, because a shifted value would no longer be dBFS at all. |
| **Spectrum** | Magnitude of a 4096-sample rolling FFT (Hann window, hopped by one block) folded into 28 log-spaced bands. Each band is the peak bin in dB; the bars span a 60 dB window under a slow global ceiling, so a whisper and a club both fill the panel while the bands keep their proportions. Bars rise fast and fall slowly; the peak marker holds ~140 ms, then falls in about two seconds. |
| **Tempo** | Energy in the 30–110 Hz kick band; an onset is a block that beats the 3 s moving average by 1.4× **and** rises above the peak of a lagged window (the SuperFlux rule, so a sustained bass note is one onset, not twenty). The median inter-onset interval is folded into 60–200 BPM and shown as a 4 s rolling mean; confidence is 1 − σ/median of the intervals. Onsets are gated on −45 dBFS (`quiet` in the HUD) so room noise never produces a tempo. The same estimator runs in inspector-rust and disco-controller. |

A tempo needs about five seconds of music. Halving and doubling are a genuine ambiguity
(a 60 BPM ballad and a 120 BPM track with a kick on every beat produce the same intervals);
the fold prefers the 60–200 range and snaps to the tempo already shown.

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/bpm-quiet.png" alt="the tempo screen in a silent room" width="700"/>
<br/>
<sub>Before any music plays: dashes instead of a number, <code>quiet</code> in the HUD and <code>waiting for music</code> under it. Onsets are gated on the level, so a silent room never invents a tempo.</sub>
</div>

### The headline number

`-db` and `-bpm` put their one important number in the middle of the screen, five rows tall,
drawn in the same bar glyph as every meter (so it degrades to `#` on an ASCII terminal like
everything else). Three things happen to it while a session runs:

- **It eases.** A level that jumps 40 → 78 → 44 between frames is noise the eye has to
  track; the shown value moves towards the measurement instead of snapping to it.
- **It has its own clock.** Twenty frames a second is right for a bar and far too fast for a
  digit — the last decimal would be a blur — so the number refreshes about five times a
  second while the bars, the beat dot and the flash keep every frame.
- **The tempo flares on the beat.** Every detected onset lights the digits for a tenth of a
  second, so the number itself carries the pulse.

The HUD line above keeps the raw sample, so the exact measurement is always on screen next
to the eased one. In a snapshot (`--once`, or a pipe) nothing is eased and nothing is held:
one frame, one number, the one that was measured. Below about ten rows there is no room for
five rows of digits and the screen falls back to a single line:

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/db-small.png" alt="the level meter on a short terminal" width="620"/>
<br/>
<sub>The same screen at 80×12. The value, the meter and the extremes stay; the big digits and the history are what give way.</sub>
</div>

### What moves, and how

The analyser produces numbers about 43 times a second, the screen draws 30 times a second,
and reading the newest numbers on every frame gives a picture that *steps*: a bar that jumps
to its new height, a peak marker that slides down a ruler, a beat that is a dot switching on
and off. A small motion layer (`termstats/motion.py`) sits between the two and makes every
quantity a function of **elapsed time**, so the look is the same at 20 and 30 frames a second
and a suspended laptop does not produce a jump on wake:

| | |
|---|---|
| **Bars** | ease towards their target — a 20 ms attack, a 120 ms release — so a rise is nearly instant and a fall is what the eye follows |
| **Afterglow** | where a bar was, a dim trail (`▒`) remains and falls under gravity, accelerating; it never sits below the bar |
| **Peak markers** | ride up with the bar, hold for 400 ms, then fall under gravity rather than at a constant rate |
| **The beat** | an impulse that decays to 1/e in 250 ms; everything that reacts to a beat reads this envelope — the dot lights hot and cools through two tones before it rests, the tempo digits flare and fade, and every bar is nudged up by up to 12 % |
| **Metronome** | on the tempo screen a head (`◆`) sweeps from left to right between two beats, at the tempo the detector found — the beat grid made visible |
| **Level meter** | VU-like ballistics: 30 ms up, 350 ms down |

The history charts change twice a second, not thirty times, so live they are rebuilt on a
worker thread twice a second and each frame draws the last finished one; the render thread
never waits. In a snapshot none of
this runs — the analyzer's numbers are drawn as they are, the chart is built once, and two
renders of the same state are identical.

### Devices, snapshots, refresh

`--list-devices` prints every input with its channel count and sample rate, and marks the one
that would be used without `--device`:

<div align="center">
<img src="https://raw.githubusercontent.com/pepperonas/termstats/main/docs/screenshots/devices.png" alt="the output of termstats --list-devices" width="560"/>
<br/>
<sub><code>termstats --list-devices</code> — an invented sound card, so the picture is the same on every machine.</sub>
</div>

`--device NAME` picks one by any part of its name (`-d usb`), the default is the system input. The analyser
runs at the device's own sample rate. The screens refresh 30 times a second (`-i` changes
that); `--once`, or a pipe, listens for 1.5 s and prints one frame — enough for a level, not
for a tempo, which the HUD shows as `---`. `--demo -eq` plays eight seconds of scripted
music before the first frame, so a tempo is already on screen.

## Resource use

A dashboard that is left running all day should not show up in its own process list. Measured
on an Apple-silicon MacBook with ~700 processes, the default 0.5 s interval, in a real
pseudo-terminal, start-up included (20 s runs for the Python columns, 30 s for the native one):

| | 0.7.0 | 0.8.0 (Python) | 0.9.0 ([native core](#the-native-core)) |
|---|---|---|---|
| CPU at 140×42 | 14.7 % of one core | 5.4 % | **0.35 %** |
| CPU at 200×60 | 19.3 % | 7.3 % | **0.3 %** |
| CPU at `-i 1`, 140×42 | — | 3.6 % | **0.2 %** |
| CPU per frame | ~73 ms | ~21 ms | **~0.7 ms** |
| Bytes written to the terminal | 145 KB/s | 74 KB/s | **~9 KB/s** |
| What is repainted | the whole screen, 3.9× a second | the whole screen, 2× a second | **only the cells that changed** |
| Resident memory | 45 MB | 36 MB | **7 MB** |

Two rounds of work are behind those columns.

**0.8.0 made the Python program a third of its cost**, in the order the profile gave:

- **The two history charts cost 20–50 ms each** — more than everything else in the frame
  together. They were drawn by a general plotting library that interpolates every line into
  thousands of points and fills the area dot by dot. termstats now rasterises its own charts
  (one pass over the dot columns, about **1 ms** each) and the dependency is gone, which also
  removes its import from every start.
- **The process table asked every process for everything.** Name, memory share and RSS were
  read for all ~700 processes to draw eight rows — and on macOS a name longer than fifteen
  characters costs a second system call for the command line. The scan now reads the CPU
  share only and fetches the rest for the rows that are drawn (35 ms → 9 ms), and a live
  session re-reads the table at most once a second.
- **Every frame was painted twice.** rich's own refresh thread re-rendered and re-sent the
  unchanged picture between two frames. The loop paints each frame itself; the thread is off.
- **Slow facts were read at frame rate.** Partition usage is re-read every 5 s and the
  connection count every 2 s in a live session, instead of twice per frame.

None of this applies to a snapshot or to `--demo`: `--once` measures everything for the one
frame it prints, and the demo advances by frames, not by the wall clock.

**0.9.0 asked what was left — and the answer was Python itself.** Of the 21 ms a frame
still cost, 11 ms were rich laying out and styling the screen, 9 ms were psutil walking the
process table (one system call per process — and about twelve microseconds of interpreter
around each), and the rest were small. None of that is a mistake to fix; it is what the
language costs. The same work in a compiled program:

| One frame at 140×42 | Python 0.8.0 | native |
|---|---|---|
| Process table, ~700 processes | 8.9 ms | 0.65 ms |
| CPU, memory, network, disks | ~4 ms | 0.15 ms |
| Layout and drawing | ~11 ms | 0.03 ms |
| Encoding for the terminal | (in the above) | 0.1 ms |

That is the [native core](#the-native-core): what remains in it is almost entirely the
kernel's own work.

The remaining levers are yours either way: **the cost is per frame**, so `-i 1` halves it and
`-i 2` halves it again.

## The native core

`native/` holds the system dashboard a second time, as a Rust program: **`termstats-native`**.
Same panels, same layout budget, same number formats, same six themes — the colour tables are
generated from `theme.py`, and a test compares the layout constants of the two programs — at
about a fifteenth of the CPU and a fifth of the memory of the Python program.

```bash
curl -fsSL https://github.com/pepperonas/termstats/releases/latest/download/install.sh | sh
termstats                # hands the live dashboard to the native core from now on
termstats-native         # or run it directly
```

The script and the four downloads are described under [Installation](#installation). With a
Rust toolchain it also builds from source:
`cargo install --git https://github.com/pepperonas/termstats termstats-native`.

**You do not have to change what you type.** When `termstats-native` is on the `PATH`,
`termstats` starts it for the live dashboard and steps aside (`exec`, no second process).
The keys `b`, `d` and `x` lead back to the microphone screens — the native core starts the
Python program again for them — and `s` there returns to the native dashboard. Everything
else is still drawn by Python: snapshots (`--once`, pipes), `--demo`, the microphone modes,
the `block` and `ascii` glyph levels, 16-colour terminals, Nerd Font titles, and Windows.
`TERMSTATS_NATIVE=0` keeps the dashboard in Python; `TERMSTATS_NATIVE=/path/to/binary` names
a binary that is not on the `PATH`.

Three things make the difference, in this order:

- **The machine is read with direct system calls.** mach, sysctl and libproc on macOS, `/proc`
  on Linux — one dependency (`libc`), nothing between the program and the kernel. The whole
  process table costs about 0.65 ms; the name of a process is asked for only for the rows
  that are drawn.
- **Only what changed reaches the terminal.** A frame is drawn into a grid of cells and
  compared with what the terminal already shows; the difference goes out in one write,
  bracketed by synchronized-output marks (a terminal that does not know them ignores them).
  A dashboard at rest changes a few dozen cells a frame — about a tenth of the bytes, and
  your terminal emulator's own work shrinks with them. That part never shows in termstats'
  numbers, and on a busy screen it is the larger one.
- **Between two frames the process sleeps in one `poll()`.** A key or a resize wakes it,
  nothing else does: no timer slices, no refresh thread.

Its own options — the same spellings as `termstats` where they exist:

```
termstats-native [-i SEC] [--theme NAME] [--compact] [--no-border]
                 [--once] [--size COLSxROWS] [--samples N] [--list-themes] [--version]
```

`--size 140x42` gives a snapshot its size when there is no terminal to ask (a service, a
web view); `--samples 30 -i 1` takes thirty samples before it prints, so the charts are
filled. `termstats-native --bench` prints what each part of a frame costs on the machine it
runs on.

**Linux** is served by the same source (`/proc`, `statvfs`). The releases carry static
binaries for x86_64 and ARM64; to build one yourself, without a cross compiler:

```bash
rustup target add aarch64-unknown-linux-musl          # or x86_64-unknown-linux-musl
cd native && RUSTFLAGS="-C linker=rust-lld -C link-self-contained=yes" \
    cargo build --release --target aarch64-unknown-linux-musl
```

What the native core does not do, on purpose: it has no connection count (root-only on
macOS, and a walk over every socket elsewhere), and on a terminal too small for the plan it
packs the cores tighter instead of cropping the panel — the one place its picture is better
than the one it copies.

## Using the core as a library

The native core is also a Rust library (`termstats_native`) with a C interface, for programs
that are not a terminal: it samples the machine and draws the dashboard into a grid of cells
(character, foreground, background, bold) that the caller paints however it likes. A macOS
desktop-background app is built on exactly this. The contract is one hand-written header,
[`native/include/termstats_core.h`](native/include/termstats_core.h) (`TS_ABI 2`):

- `ts_create` / `ts_free` / `ts_set_options` — a core with a theme, a sample interval and
  switches for which **views** are drawn (cpu, memory, network, disk, charts, processes,
  and the microphone screens: equalizer, level, tempo) and which **chrome** (header, clock,
  version, footer, hints, brand line).
- `ts_sample(core, mono)` reads the machine; `ts_draw(core, w, h, mono, regions, out)`
  returns the cells plus the rows that changed since the last frame. With dashboard and
  audio views both on, the audio panels are a column on the right from 190 columns and rows
  at the bottom below that; `regions` lets the caller redraw only the dashboard or only the
  audio.
- `ts_feed_audio(core, samples, n, rate)` hands over microphone samples (mono, any block
  size, any rate from 4 to 768 kHz); `ts_audio_state` says when there is no permission or no
  device, and the audio panels show it. The analysis — FFT, 28 bands, tempo, level — is the
  Python program's, ported; the core captures nothing itself.

**Threading:** a core is used from one thread, with one exception — `ts_feed_audio` may be
called from the audio thread while another thread draws (it only copies the samples into a
guarded two-second ring). Stop and join that feed **before** `ts_free`.

To link it, depend on the crate by git revision and re-export the interface from a crate of
type `staticlib` (`pub use termstats_native::ffi::*;`); copy the header verbatim. The
terminal program does not use any of this and behaves exactly as before.

## History and recommendation

termstats can keep a history of what the machine does and, after two weeks, say which
computer fits that use: the cheapest current Mac that meets it at three levels of headroom,
plus the best machine that runs Linux. Both commands are done by
[the native core](#the-native-core) (macOS and Linux; not Windows).

```bash
termstats record install     # record from every login on, in the background
termstats record status      # is it running, which day of the 14 it is, how big the log is
termstats recommend          # the recommendation, once 14 days are on file
termstats recommend --now    # a first impression from what is there, marked provisional
termstats recommend --json   # the same for another program
termstats record uninstall   # stop and remove the service; the history stays
termstats record purge       # delete the history
```

`termstats-native record ...` is the same thing without the Python program.

### What is recorded

A background service (a launchd agent on macOS, a systemd user unit on Linux) takes a light
reading every 5 seconds and looks at the process table every 30. It keeps **one line a
minute**, written five minutes at a time:

| | per minute |
|---|---|
| Processor | average, 95th percentile and maximum load; how many cores were busy at once; how often one core was pinned while the rest idled |
| Memory | used (average, maximum), what the machine *wanted* (used plus what it had to compress or swap out), swap, memory pressure |
| Graphics | utilisation, average and maximum |
| Storage, network | space in use, bytes read and written, bytes received and sent |
| Circumstances | mains or battery, charge, thermal throttling, number of external displays |
| Who | the names of the three programs that used the most CPU time and the most memory |

A value the system does not offer stays an empty field, it is never written as zero. Time
the machine slept is marked as a gap and not counted as idle.

The log is plain text, tab-separated, one file a day:
`~/.local/state/termstats/history/YYYY-MM-DD.tsv` (`TERMSTATS_STATE_DIR` or `XDG_STATE_HOME`
move it). The files are readable only by you (`0600`), hold program **names** and nothing
else about what you do - no arguments, no paths, no window titles - and are never sent
anywhere: termstats does not talk to the network. About 300 KB a day, 4 MB a fortnight; files older than 90
days are deleted (`record --keep-days N`).

Measured on a MacBook Pro (M1 Pro, ~700 processes) over ten minutes: **0.024 % of a core (0.14 s of CPU time) and 6.2 MB of memory - 5.5 MB of that is what the program occupies before it has done anything**.

### How the recommendation is made

`termstats recommend` reads the last four weeks at most and reduces them to a need:

- **Memory**: the 99th percentile of what the machine wanted, plus headroom, rounded up to a
  size that is sold.
- **Processor**: the load at the 95th percentile and how long it stayed near the limit,
  converted through the benchmark score of the chip it was measured on. A history from an
  M1 Pro and one from an M4 ask for different things at the same percentage.
- **Graphics**: the 95th percentile and the share of time above 80 %.
- **Storage**: what is in use, its growth over the period, plus reserve.
- **Form**: never decided for you. Every level is answered twice - a laptop to carry and a
  machine for the desk - because where the next job is done is not in the history: a
  fortnight at the socket does not mean the machine never has to travel. Time on battery
  and with an external display is reported next to the picks, and changes none of them.
  Sustained load or thermal throttling rules out fanless machines in both.

Three levels are named - *just enough*, *fits*, *with reserve* (10 %, 30 % and 80 % of
memory headroom, with matching targets for the other parts) - each with model, chip, memory,
storage and the list price in euro, once as a laptop and once as a desktop, followed by the
figures from your own history that led to it, the price gap between the two set-ups, and a
reminder that a desktop's price is the computer alone (display, keyboard and pointing device
come on top). The Linux alternative to the fitting level is named both ways as well. If the
current machine is enough, the report says so.

`--json` carries the same: each entry of `tiers` has `need`, `laptop` and `desktop`, and
`linux` has `laptop` and `desktop` (a pick is `null` when nothing in the catalogue meets it).

The machines come from `catalog/hardware.json`: every Mac Apple currently sells, with each
memory and storage step at its price in the German Apple store, and a selection of machines
that run Linux (Framework, TUXEDO, ThinkPad, mini PCs). Each entry carries its source and
the catalogue its date; a catalogue older than 120 days says so in the report. It ships
with the release and is never fetched.

### A daily mail

[`examples/daily-report.example.py`](examples/daily-report.example.py) (standard library
only, not part of the package) sums up yesterday from the history, adds the current
`recommend --now` report and mails both through `msmtp` on a host reached over ssh. Attached is a PDF of the day in charts (processor, memory, graphics, disk and network over the day, the largest consumers, the days so far, the recommendation as a table): the report is built as HTML with inline SVG and printed by a headless Chrome, Chromium, Edge or Brave; without one the mail goes out without it. Its
docstring lists the environment variables; run it once a day from cron, a launchd agent or
a systemd timer. It sends each day once and nothing for a day without history. Mind what
it sends: the names of your busiest programs leave the machine with that mail.

### What it cannot know

- Benchmark scores compare classes of chips, not percent. Graphics scores for Macs (Metal)
  and for the other machines (OpenCL) are only roughly comparable.
- Prices are list prices on the catalogue's date; some Linux entries are temporary shop
  prices, and a chip too new to have published scores is left out rather than guessed.
- Software that needs one particular system, ports, screen size, weight: yours to weigh.
- Two weeks describe those two weeks. A fortnight without the heavy project recommends a
  smaller machine than you need.

## Platform Support

| Feature | Linux | macOS | Windows |
|---------|:-----:|:-----:|:-------:|
| CPU per-core | Yes | Yes | Yes |
| CPU steal time | Yes | — | — |
| Memory & swap | Yes | Yes | Yes |
| Disk usage | Yes | Yes | Yes |
| Disk I/O speed | Yes | Yes | Yes |
| Network throughput | Yes | Yes | Yes |
| Connection count | Yes | Root only | Yes |
| Top processes | Yes | Yes | Yes |
| Live charts | Yes | Yes | Yes |
| Load average | Yes | Yes | Yes* |
| Resize | Immediate | Immediate | Next refresh |
| Microphone modes | Yes, needs `libportaudio2` | Yes | Yes |

\* Windows has no load average; psutil emulates one from a sampler thread that reads
`0.00` for its first five seconds after start.

Panels that cannot be filled degrade quietly rather than failing: an unreadable partition is
skipped, and a denied connection count is omitted instead of shown as zero.

## Requirements

- Python 3.9+
- [psutil](https://github.com/giampaolo/psutil) — cross-platform system metrics
- [rich](https://github.com/Textualize/rich) — terminal formatting
- optional, for the microphone modes only: [numpy](https://numpy.org) and
  [sounddevice](https://python-sounddevice.readthedocs.io) — the `termstats[audio]` extra
- [the native core](#the-native-core) needs nothing at all: the release binaries are
  self-contained (a Rust toolchain only to build it yourself)

The charts are drawn in **Unicode braille** (U+2800–U+28FF), which packs 2×4 dots into one
character cell. Font coverage for that block is near-universal; if yours lacks it the charts
show replacement boxes while everything else stays readable.

The charts are rasterised by termstats itself. Until 0.7 they were drawn by
[plotext](https://github.com/piccolomo/plotext); 0.8.0 dropped the dependency — see
[Resource use](#resource-use) for why.

A terminal of roughly 120×40 or larger gives the intended two-column layout; the panels
reflow on narrower terminals, and the charts scale with the window.

## Health Report (optional)

termstats includes a companion script for automated server health monitoring. When deployed on
a server, it can generate a PDF health report and send it via email on a schedule.

**What the health report covers:**

- Overall status with traffic-light ratings (OK / WARNING / CRITICAL)
- CPU, steal time, load, RAM, swap, disk — each evaluated against configurable thresholds
- SAR trend data (CPU & steal over time)
- Per-core CPU breakdown
- Network totals and connection count
- Top processes by CPU usage
- Docker container resource usage

**Default thresholds:**

| Metric | Warning | Critical |
|--------|---------|----------|
| CPU | 80% | 95% |
| Steal | 5% | 20% |
| RAM | 85% | 95% |
| Swap | 50% | 80% |
| Disk | 80% | 90% |
| Load | 2x CPUs | 4x CPUs |

When a threshold is breached, the email subject is prefixed with `[WARNING]` or `[CRITICAL]`
for easy filtering.

**Setup:** The health report script requires SMTP credentials and is not part of the installed
package. See [examples/celox-health-report.example.py](examples/celox-health-report.example.py)
for a template. Pair it with a systemd timer or cron job for automated scheduling.

## How It Works

termstats uses [psutil](https://github.com/giampaolo/psutil) to collect system metrics,
[rich](https://github.com/Textualize/rich) for terminal rendering with colored panels and
tables, and its own rasteriser for the history charts (2×4 braille dots or 2×2 quadrants per
cell). On Linux, CPU steal time is read directly from `/proc/stat`.

Rates (CPU, disk I/O, network) are deltas between consecutive samples, kept in module-level
`deque`s capped at 60 entries. That cap is a *sample* count; multiply it by the refresh
interval to get the window the charts cover.

Live mode renders into rich's alternate-screen `Live` view, and frames are scheduled on a
fixed grid: the loop sleeps `interval − render time` rather than a flat `interval`, so the
real cadence does not drift by the cost of drawing a frame, and it resynchronises instead of
firing a burst of catch-up frames when one render overruns. The wait runs in 0.1 s slices
and a `SIGWINCH` handler cuts it short, so a resize is redrawn within a tenth of a second and
the cadence restarts from that frame.

Colour lives in one place, `termstats/theme.py`: the glyph sets, the spacing and format
tokens, the OKLab conversions and the six themes. `cli.py` names tokens and never a colour
or a drawing character — a test reads its source and refuses any hex value or glyph literal.
Ramp lookups are cached; the whole dashboard renders and prints in about 20 ms at 140×42.

### Project layout

```
termstats/
├── termstats/
│   ├── __init__.py      # version - the single source --version and the header read
│   ├── __main__.py      # python -m termstats
│   ├── cli.py           # collectors, renderers, layout, arg handling, entry point main()
│   ├── theme.py         # glyph sets, spacing/format tokens, OKLab ramps, the six themes
│   ├── demo.py          # the scripted machine behind --demo
│   ├── audio.py         # -eq/-bpm/-db: dBFS, log bands, peak hold, tempo estimator, demo synth (numpy)
│   └── capture.py       # the microphone (sounddevice), imported lazily, every failure a sentence
├── native/              # the same dashboard in Rust: termstats-native (cargo; one dependency, libc)
│   └── src/             # main.rs loop+tty · sys/ macOS+Linux collectors · screen.rs cells+diff · ui.rs layout
├── tests/               # pytest suite (pure unit tests, psutil stubbed)
├── tools/badges.py      # generates .github/badges/*.json for the headline badges
├── tools/gen_native_themes.py  # writes native/src/themes.rs from theme.py (a test checks it is current)
├── tools/release_notes.py  # the CHANGELOG section of a version: the text of its GitHub release
├── install.sh           # installs termstats-native from the latest release (checksum-verified)
├── tools/demo.tape      # VHS recording script for the --demo GIF
├── tools/screenshots.py # renders every README picture from --demo (SVG + index.html for the browser)
├── docs/screenshots/    # the rendered PNGs the README embeds
├── .github/
│   ├── badges/          # shields.io endpoint JSON, refreshed by CI
│   └── workflows/       # test matrix + badge refresh
├── examples/            # optional server health-report template (not packaged)
├── CHANGELOG.md         # Keep a Changelog, SemVer
├── pyproject.toml       # metadata + the `termstats` console script
└── README.md
```

## Development

```bash
git clone https://github.com/pepperonas/termstats.git
cd termstats
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"   # runtime deps + pytest

termstats                # run it
python -m termstats      # same thing without the console script
```

### Tests

```bash
pytest                   # the whole suite, about three seconds
pytest -q tests/test_args.py
env -u COLORTERM TERM=dumb pytest      # must be green too: the suite pins its own capabilities
(cd native && cargo test --release)    # the native core's own suite, 43 tests
```

The exact count is on the badge at the top of this file — it is generated, not typed.

The suite is unit tests — no sleeping, no live terminal, no network — plus three real
`termstats --demo --once` processes that check the escape codes a 16-, 256- and truecolor
terminal actually receive (skipped on Windows, where rich renders a pipe through the win32
API and there is no ANSI to inspect). psutil is stubbed with fakes so the collectors can be
driven through their failure paths (an unreadable mountpoint, `AccessDenied` on connection
counts, a process that vanishes mid-iteration), and the chart rasteriser is pinned on the
picture it draws: the area, the line over it, the fixed axis, the exact size.

The suite **pins its own terminal capabilities** (truecolor, braille) instead of detecting
them, so it means the same thing on every machine: green under `TERM=dumb`, `NO_COLOR=1`,
a shell without `COLORTERM`, and on the CI runners. The first 0.4.0 run was red in all four
CI cells because the fixture took the colour level it found in the runner's environment —
a test that depends on the environment is not a test of the code.

What it covers:

| Area | Examples |
|------|----------|
| Argument parsing | every flag spelling, unknown options exit 2, `-i` value consumption, `nan`/`inf`/`0`/negative intervals |
| Mode selection | live in a terminal, snapshot when piped, `--once`/`--live` overrides, the two together rejected |
| Timing | the computed history window, drift-compensated frame scheduling, the refresh rate tracking the interval |
| Layout | fits *and* fills the height at thirteen terminal geometries, no line wider than the terminal, no blank lines, no stump panels |
| Meters | ramp continuity and clamping, exact bar width, eighth-cell fill, the dimmed cache segment, the annotation dropped rather than sliced |
| Charts | braille markers, area fills (and that only one network series is filled), ramp-derived colours, the rounded and unit-scaled axis, the time axis, live-value subtitles, and the hand-drawn ASCII chart |
| Header | the sparkline shows peaks not means, appears only with history, never in ASCII mode; the line never collides with itself at any width |
| Disk | `nobrowse` filtering, the macOS Data substitution and its counter-checks, mountpoint shortening |
| Badge tooling | the LOC counting rules, the three `pytest --collect-only` output shapes, and the refusal to publish a zero |
| Charts | no plotting library, a failing rasteriser costs a chart and not the dashboard, byte→KB conversion, the 0–100 CPU axis, Linux-only steal series |
| Formatting | bar fill and colour thresholds, rate scaling across the B/KB/MB boundaries |
| Collectors | pseudo-filesystem filtering, mountpoint truncation, rate baselines, process sorting and limits, `/proc/stat` steal parsing |
| Packaging | the two version strings agree, plotext stays out of the dependencies, no `stats` alias, no PyPI claim, README badges match the package |
| Dashboard | one full render against the real machine, one history sample per render, brand line intact |
| Output encoding | a cp1252 stdout is widened to UTF-8; unreconfigurable streams degrade quietly |
| Themes | OKLab round-trips, gamut mapping, monotone lightness of every theme, 256/16-colour band checks, `--theme`/`TERMSTATS_THEME`/`--list-themes`, capability detection |
| Stability | fixed-width formats, the header's fixed fields and width-only tail tiers, a 20-frame stormy geometry sweep in which no element may change width or place |
| Peaks | the 30-sample high-water mark, its hairline placement and colour, raw peak over eased fill |
| Frame | one border tone on every panel, bold-accent titles, dim units, `--compact`/`--no-border` layout invariants, process rows ordered = rows shown |
| Footer & header | dynamic year, hint only in live mode, ASCII `(c)`, the sparkline centred by width alone |
| Lifecycle | SIGWINCH guard and restore, sliced waits, immediate relayout with cadence resync, cursor always restored, Ctrl+C quiet |
| Windows | `WT_SESSION` and the conhost build in the colour chain, load-average priming, the docs and CI keep the PowerShell path honest |
| Docs sync | every parser flag has a README row and a `--help` line, every `TERMSTATS_*` variable and theme is documented, every README image exists and every screenshot is shown, the table of contents matches the headings, the changelog is dated and descending |
| Screenshot tool | importable, one SVG per view, no window chrome, byte-identical on repeat, the ASCII tile is 7-bit, the mono tile has no colour, the snapshot shows the skeleton, the audio views carry a tempo, the device listing invents its devices |
| Keys | which bytes mean quit and which only start an arrow key, the watcher's states and its restore, both loops leaving, the footer and `--help` naming `Esc` |
| Device listing | index, name, channels and rate in the output, the default marked once, the empty case, and `--list-devices` going through that one renderer |
| Audio DSP | dBFS of silence/full scale/quiet tones, log-spaced edges, a pure tone lights its own band and no distant one, unit interval, silence settles, attack faster than release, peaks hold then fall and never sit below the level, the tempo estimator locks onto a metronome, folds octaves, ignores steady noise and the quiet room, forgets after silence, the demo synth is deterministic, within full scale, loud enough, and has the tempo it claims |
| Audio screens | every mode fits every size, badge and HUD in every mode, bars follow the levels, columns adapt to the width, peak markers only above the bar, ASCII stays 7-bit, the level screen shows value/min/max/meter and drops the chart before the meter, the tempo screen shows the number or `---` and a beat dot that lights and rests |
| Motion | the beat envelope fires to one and decays with time not frames, bars rise fast and fall slowly at 15 and 30 fps alike, trails snap up and fall with gravity and never sink below the bar, peaks hold then fall, the meter has VU ballistics, the phase sweeps and wraps, a minute-long pause is one short step |
| Live vs snapshot | live bars ease towards a jump, a falling bar leaves a trail, a beat nudges every bar, the dot and the tempo digits fade instead of switching, the metronome moves right and exists only live with a tempo, the meter falls like a needle, the chart is built on a worker off the render path and a failed rebuild keeps the old chart; a snapshot stands perfectly still and builds its chart every time |
| Audio arguments & capture | every flag spelling, one mode at a time, faster default refresh, `-i` still wins, `--device` needs a value and an audio mode, `--demo` needs no microphone, `--once` and a pipe measure briefly, `--list-devices`, the missing-extra message names the install; the microphone opens mono float32 at the device's own rate, resolves by substring or default, explains a missing library, PortAudio or device, and never lets a consumer error reach the audio thread |
| Demo | the psutil surface contract against the source, byte-identical stories per seed, the story's shape, reproducible snapshots |
| Definition of Done | no hard-coded colours or glyphs in `cli.py`, WCAG contrast of every theme against its background, no escapes under `NO_COLOR` or in a pipe, every fallback level renders and speaks only its own escapes — in-process and, on Linux/macOS, in a fresh process per colour level |

Every assertion that guards a past bug was verified by re-introducing the bug and watching
the test go red. Do the same for new ones — a test you have not seen fail is not a guarantee.

CI runs the suite on Linux, macOS and Windows (and on Python 3.9, the claimed floor) via
`.github/workflows/tests.yml`.

Build distributables:

```bash
pip install build
python -m build          # -> dist/termstats-<version>-py3-none-any.whl + .tar.gz
```

### Mutation testing

Every new pin is mutated once before it counts: the guarded line is broken on purpose, the
test must go red, then the line is restored (the file is copied first and its checksum
compared after). A test that has not been seen failing proves nothing — several pins in this
repository were rewritten because they stayed green on the first try, and a mutation that
does not compile is not a mutation at all (pytest exits 4, not 1, when `conftest.py` cannot
import the module).

### Screenshots

Every picture in this README is rendered, not captured:

```bash
python tools/screenshots.py OUT_DIR                 # every view: SVG per view + index.html
python tools/screenshots.py OUT_DIR --only hero,help
```

The tool drives `--demo` (default seed, its own clock pinned to one instant), renders each
view with a private copy of the CLI module so histories and peak markers start empty, and
exports rich's SVG without the window chrome. `index.html` lays the SVGs out with one section
per figure — `#hero`, `#grid`, `#compact`, `#no-border`, `#narrow`, `#snapshot`,
`#list-themes`, `#glyphs`, `#colours`, `#help` — which a real browser then rasterises to the
PNGs (`python3 -m http.server` in `OUT_DIR`, Playwright element screenshots). Run it **after**
a version bump: the header carries the version.

### Releasing

termstats follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Below 1.0.0 a
**minor** bump may break the command line and a **patch** bump may not; 1.0.0 will be the
first release that promises a stable interface.

1. Bump the version in **three** places: `pyproject.toml` (packaging reads it),
   `termstats/__init__.py` (the header and `--version`) and `native/Cargo.toml` (the native
   core) — then `cargo build` in `native/` so `Cargo.lock` follows.
2. Add the entry to [CHANGELOG.md](CHANGELOG.md) — it becomes the text of the release.
3. Update the two versioned wheel URLs under [Installation](#installation).
4. Run `python tools/badges.py` to refresh `.github/badges/*.json`.
5. `pytest` and `cargo test --release`, commit, then tag `vX.Y.Z` and push the tag.

The pushed tag does the rest: `.github/workflows/release.yml` builds the native binary for
four targets (macOS Apple silicon and Intel, Linux x86_64 and ARM64 as static musl
binaries), the wheel and the sdist, starts what it can start on the runner, and publishes
them as a GitHub release with `install.sh` and `SHA256SUMS`. A release that already exists
is updated in place (`workflow_dispatch` with the tag re-runs it).

The suite checks steps 1–4 for you: the three version strings must agree, the changelog's
top entry must name the current version, the wheel URLs in this file must carry it, the
committed version badge must match the package, and the asset names in the workflow, in
`install.sh` and in this file must be the same four. A forgotten bump shows up as a red
test rather than as a dead download link.

### Badges

The version, lines-of-code and unit-test badges are **generated**, never typed:

```bash
python tools/badges.py            # rewrite .github/badges/*.json
python tools/badges.py --check    # exit 1 if they are out of date
```

`.github/workflows/badges.yml` runs the script on every push to `main` and commits the result
when a number moved, so the three headline badges track the repository on their own. The
script refuses to emit a zero test count — a badge announcing "0 unit tests" because pytest
was missing from the interpreter is exactly the confident wrong number it exists to prevent.

Uninstall:

```bash
pipx uninstall termstats     # or: pip uninstall termstats
```

## Compared with other dashboards

termstats is a **dashboard**, not a process manager: you look at it, you do not act in it.
That choice is what the rest follows from.

| | termstats | htop | btop | glances |
|---|---|---|---|---|
| Kind | dashboard | process manager | dashboard + process manager | dashboard, also web/server |
| Language | Python, with an optional native core in Rust | C | C++ | Python |
| Configuration | none — flags and environment only | `htoprc` | `btop.conf` | `glances.conf` |
| One-shot output for cron / files | yes, automatic when piped | no | no | yes (`--stdout`, `--export`) |
| History charts | braille area charts, CPU + network | meters only | braille graphs, several | sparklines + history mode |
| Themes | 6, OKLab ramps checked on 256/16 | colour schemes | many | few |
| Acting on processes (kill, renice, tree) | no | yes | yes | limited |
| Install | release binary (one `curl`), or `pipx install` | distro package | distro package / binary | `pip install glances` |

If you want to kill a process from the screen you are looking at, use htop or btop. If you
want the state of a machine in one glance, in a file, or on a terminal that only speaks
16 colours and ASCII, termstats is built for exactly that.

## Naming & history

This project was called **`stats`** until August 2026 and had to give up that name: a
different, unrelated project (a self-hosted VPS security monitor) took over the `stats`
repository slot. Everything user-facing was renamed in one pass:

| | before | now |
|---|---|---|
| Repository | `pepperonas/stats` | `pepperonas/termstats` |
| Command | `stats` | `termstats` |
| Python package | `stats` | `termstats` |
| Distribution name | `stats-dashboard` | `termstats` |
| Module form | `python -m stats` | `python -m termstats` |

**Migrating from an old checkout:** remove the old install first, then install fresh —
the old and new packages are unrelated as far as pip is concerned and would otherwise
coexist.

```bash
pipx uninstall stats-dashboard 2>/dev/null || pip uninstall -y stats-dashboard
pipx install git+https://github.com/pepperonas/termstats.git
```

There is deliberately **no `stats` alias command**: reintroducing that name would bring back
exactly the ambiguity the rename resolved.

**The version number was also reset**, from `1.1.4` to `0.1.0`, when live mode became the
default. termstats has never been on a package index, so nothing downstream could break — and
a 1.x number claimed a stability guarantee the command line had not earned. 0.x is where a
tool that still changes its own defaults belongs. The pre-reset releases are listed at the
bottom of [CHANGELOG.md](CHANGELOG.md) and remain in the git log.

## Troubleshooting

**`termstats: command not found` after installing** — the install directory is not on your
`PATH`. pipx puts binaries in `~/.local/bin`; run `pipx ensurepath` (then open a new shell),
or add it yourself:

```bash
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && exec zsh
```

**`ModuleNotFoundError: No module named 'psutil'` with `python -m termstats`** — you are
running a Python that does not have the dependencies. Use the console script, or activate the
environment termstats was installed into.

**Charts stay on `collecting · 2 samples needed`** — expected in snapshot mode; they need
two samples. Run it in a terminal without `--once`, or use `--demo` for a full picture.

**`termstats` printed one screen and exited instead of updating** — stdout was not a
terminal, so snapshot mode was chosen automatically. That happens when you pipe (`| less`,
`| grep`), redirect (`> file`), or run it from cron or a CI step. Pass `--live` to override.

**`termstats` in a script never returns** — you forced `--live` somewhere output is not
consumed. Drop the flag and let the terminal check decide, or pass `--once`.

**A screen recording or `script(1)` session shows the live view where you wanted a snapshot**
— those allocate a pty, so the terminal check correctly says "a human is watching". Use
`--once`.

**`termstats -live` printed a snapshot instead of the live dashboard** — before 1.1.2 the
parser matched only `-l`/`--live` and silently ignored everything else, so `-live` fell
through to snapshot mode, where both history panels read `Collecting data...`. Fixed in
1.1.2: `-live` works, and unknown options now exit 2 with a message.

**`AttributeError: module 'plotext' has no attribute 'clear_figure'`**, or charts that read
**`Charts need plotext 5.x`** — an installation older than 0.8.0 with plotext 6.x in its
environment. termstats 0.8.0 no longer uses plotext at all; upgrade, and the library can be
removed (`pipx runpip termstats uninstall plotext`).

**termstats uses more CPU than expected** — see [Resource use](#resource-use): the cost is
per frame, so `-i 1` halves it and `-i 2` halves it again, and a smaller window costs less
than a large one.

**Connection count missing** — `psutil.net_connections()` needs root on macOS, and any
platform may answer `AccessDenied` under a restricted account. The row is omitted rather
than shown as zero.

**Panels are missing** — the layout drops what does not fit rather than drawing it
off-screen. Make the window taller: the charts need about 13 spare lines, the process list
about 5.

**The charts show boxes instead of a line** — your font has no Unicode braille block
(U+2800–U+28FF). Almost all modern monospace fonts do; switch font, or redirect the output
(`termstats --once > out.txt`), which is unaffected.

**Colours look flat or wrong** — the ramp is emitted as truecolor and quantised for 256- and
16-colour terminals. Inside `tmux`, set `default-terminal "tmux-256color"` and start it with
`tmux -2`, or export `COLORTERM=truecolor`. If colour is not wanted at all, `--theme mono`
keeps the lightness scale, and `NO_COLOR=1` removes every escape code.

**The charts show boxes, but my font does have braille** — some fonts have the block but
draw it badly. `TERMSTATS_GLYPHS=block` uses eighth-cell blocks for the charts instead.

**Layout looks cramped or wrapped** — widen the terminal; the two-column arrangement assumes
roughly 92 columns and the charts look best from about 110. `--compact` buys two bar cells
per row, `--no-border` a few more and a cleaner look in screenshots.

**The chart says `last 30s` but I expected 60** — the buffer holds 60 *samples*, and the
default interval is 0.5 s. Run `-i 1` for a 60-second window; the title always states the
real one.

**Refreshing twice a second is too busy** — `termstats -i 2`. Each frame walks the process
table, so a longer interval is also the cheaper one on a small machine.

**`UnicodeEncodeError: 'charmap' codec ...` on Windows** — you are redirecting output
(`termstats > out.txt`) and Windows defaults that stream to cp1252, which cannot encode the
block characters the bars are drawn with. Fixed in 1.1.4; on older versions set
`PYTHONIOENCODING=utf-8`.

**`the microphone modes need the audio extra`** — `-eq`, `-bpm` and `-db` import numpy and
sounddevice, which the system dashboard does not ship. `pipx inject termstats numpy sounddevice`,
or install with the extra (see [Microphone modes](#microphone-modes)).

**`PortAudio is not available`** — the Linux `sounddevice` wheel does not bundle the library:
`sudo apt install libportaudio2` (Fedora: `portaudio`). macOS and Windows wheels carry it.

**`no input device matches 'x'`** — the message lists the inputs it can see; `--list-devices`
shows them with index, channels and sample rate. Pick with any part of the name: `-d usb`.

**The level sits at −60.0 and nothing moves** — the terminal application has no microphone
permission (macOS: System Settings → Privacy & Security → Microphone), or the default input is
a virtual device (loopback drivers, conferencing tools). `--list-devices`, then `--device`.

**Colours look flat in Windows Terminal** — fixed in 0.4.1. Windows Terminal announces
itself only through `WT_SESSION`, and earlier versions read the missing `TERM` as a
16-colour terminal. On 0.4.0 and older, `$env:COLORTERM = 'truecolor'` restores the ramps.

**A redirected file is full of `Γûê` and `Γá┤` in PowerShell** — that is PowerShell,
not termstats. Windows PowerShell 5.1 and PowerShell 7.0–7.3 decode a native command's
output through `[Console]::OutputEncoding` (the OEM code page) before writing the file, so
the UTF-8 that termstats emits is re-read as cp850 or cp437. PowerShell 7.4 and later pass
the bytes through unchanged and the file is correct. On the older shells, either switch the
console to UTF-8 first — `[Console]::OutputEncoding = [Text.Encoding]::UTF8` — or ask for
plain characters with `$env:TERMSTATS_GLYPHS = 'ascii'`.

**Boxes instead of charts in the classic Windows console** — the old `conhost` window with
Consolas has no braille glyphs. Windows Terminal draws them itself; in the classic window,
`$env:TERMSTATS_GLYPHS = 'block'` uses eighth-cell blocks instead.

## Support this project

termstats is free, MIT-licensed, ad-free and telemetry-free, and it will stay that way. If
it saves you a few `htop`-and-`iftop`-in-two-panes sessions, a coffee is always welcome:

<div align="center">

[![Donate with PayPal](https://img.shields.io/badge/PayPal-support%20this%20project-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.com/donate/?business=martin.pfeffer%40celox.io&item_name=termstats&currency_code=EUR)

</div>

Not in a position to donate? A star, a bug report, or a note about how it behaves on hardware
I do not own is worth just as much.

## Changelog

See [CHANGELOG.md](CHANGELOG.md). The project follows
[Semantic Versioning](https://semver.org/spec/v2.0.0.html); while it is below 1.0.0 a minor
bump may change the command line and a patch bump may not.

## License

[MIT](LICENSE) — Martin Pfeffer

## Author

**Martin Pfeffer**

- Website: [celox.io](https://celox.io)
- GitHub: [@pepperonas](https://github.com/pepperonas)
