<p align="center"><img src="docs/assets/readme/hero.webp" alt="A chibi troll at a PORTS toll booth asks for tickets as travellers queue with port-number flags" width="760"></p>
# troll
The port manager that guards the bridge: nothing crosses without paying the toll.
> **Status** — Cross-platform Rust binary supporting **Linux, macOS, and Windows**: manages claims, leases, named `[pools]`, apps, red zones,
> and 30-day removal `history` (with atomic restore), inspects drift and diagnoses ports (`explain`),
> and provides `doctor`, `serve`, `mcp` and `--llm-guide`.
> `troll serve` serves the local HTTP API and three-screen browser console (Console, Apps, History).
> `troll mcp` serves the Model Context Protocol over standard input and output.
> `troll init` configures the registry and `troll setup service` writes a user service definition
> (systemd user unit on Linux, `launchd` LaunchAgent on macOS, Task Scheduler XML on Windows).
> `troll import-legacy <dir>` previews legacy claims and `--apply` imports the permanent candidates in one update.
> What comes next is in the [plan](docs/plans/2026-11-29-troll-plan.md) and [cross-platform plan](docs/plans/2026-12-06-cross-platform-plan.md).
>
> Prefer pictures? Take the [illustrated tour](https://claude.ai/artifact/Y1Q8J5EuoXw7HBa9dDd79y) of the troll's bridge.
## Chapter 1 · The messy ledger
*In which the bridge gets rather crowded.*
On a machine full of development servers and coding agents, handwritten port claims can outlive the work that needed them. Troll peers at an illustrative ledger, eyes sparkling with concern:
| Claim files | Ports claimed | Claimed ports listening | Listening without a claim |
| ---: | ---: | ---: | ---: |
| ~1,000 | ~2,000 | a couple of dozen | a few dozen |
Those proportions are the point, and they are what prompted this program: claims
outnumbering listeners by two orders of magnitude, and listeners nobody claimed
at all.
`troll` is one Rust binary for managing ports on one machine. Claim long-lived ports, lease expiring ones, and see what's listening and who owns it.
## Chapter 2 · Three kinds of travellers
*In which every cart gets the right ticket.*
<table>
<tr>
<td align="center"><img src="docs/assets/readme/permanent.webp" alt="Troll plants a port 8123 flag on a castle tower beneath a permanent banner" width="220"></td>
<td align="center"><img src="docs/assets/readme/lease.webp" alt="Troll hands a fox a golden ticket for a 24-hour lease on port 20017" width="220"></td>
<td align="center"><img src="docs/assets/readme/ephemeral.webp" alt="Troll waves a robot cart with a port zero flag through the gate" width="220"></td>
</tr>
<tr>
<td><strong>Permanent</strong><br>For a long-lived app or shared service; stays until released.</td>
<td><strong>Leased</strong><br>For a port needed before startup. The default duration is 24 hours, the default maximum is 7 days, and the default range is 20000–24999.</td>
<td><strong>Ephemeral</strong><br>Bind port 0; the operating system picks an available port. Nothing is registered.</td>
</tr>
</table>
```mermaid
flowchart TD
Start["Need a port"] --> Long{"Long-lived app or shared service?"}
Long -- "Yes" --> Permanent["Permanent claim"]
Long -- "No" --> Known{"Must know the port before startup?"}
Known -- "Yes" --> Lease["Lease"]
Known -- "No" --> Ephemeral["Bind port 0"]
```
> A shared service, such as a database or cache, is claimed once with the projects that use it. Any local user of the account can release the claim. To release a service you manage, confirm its claim and dependents with `troll check PORT --json`, then pass its tag with `--if-tag`. A service listing dependents also requires `--force-shared`. Processes on the port keep running.
## Chapter 3 · The troll's spellbook
*In which a ticket earns a most satisfying stamp.*
Install and configure troll with the [quick start](#quick-start) first.
Check the example port and the zone list. Use a port with no claim, lease or
live listener, outside every enabled zone, the configured lease range and the
operating system's ephemeral range. See the [fixed-port check](RUNBOOK.md#check-a-fixed-port).
If any check rules out 8123, choose another port, repeat the checks and set
`CLAIM_PORT` to that number.
```sh
CLAIM_PORT=8123
troll check "$CLAIM_PORT"
troll zone list
```
Continue once the permanent claim succeeds. Set `LEASE_PORT` and `LEASED_AT`
to the `port` and `leased_at` values from your own lease reply.
```sh
troll claim "$CLAIM_PORT" --project demo --service web
troll lease --project demo --purpose preview --json
```
Releasing that lease leaves any process on its port running. The sweep
example previews which leases are reclaimable and leaves them registered.
The `with` example attempts to release only the lease it acquires when its
child exits.
```sh
troll with --project demo -- sh -c 'printf "Leased port %s\n" "$PORT"'
troll check "$LEASE_PORT"
troll explain "$CLAIM_PORT"
troll list
troll renew "$LEASE_PORT" --leased-at "$LEASED_AT"
troll release "$LEASE_PORT" --leased-at "$LEASED_AT"
troll history list
troll sweep --dry-run
troll doctor
troll --llm-guide
```
To release the permanent claim from this example, run `troll check "$CLAIM_PORT"`.
Confirm that it is the permanent `demo` claim for `web` that you created and
set `TAG` to its current tag. Run `troll release "$CLAIM_PORT" --if-tag "$TAG"`.
The guard checks that the saved contents still match their tag. An identical
recreation can have the same tag. Any process on the port keeps running.
Subcommands accept `--json` for scripts and agents. Add `--full` to
`troll --llm-guide` to print the complete manual.
Run `troll init` to configure a lease range and claim the dashboard's service
port. On a fresh registry the search starts at 7201. Init checks allocations
and live listeners, and excludes enabled red zones, the configured lease
range and the operating system's known ephemeral range for both suggested and
manually entered service ports.
On an installation that is already configured, interactive init can replace
`config.toml` and can write or upgrade the systemd user unit, so establish
both targets first. The [runbook's init notes](RUNBOOK.md#start-and-stop) say
how a replacement is published and why a running service keeps the settings it
started with. The
[startup preflight](RUNBOOK.md#startup-preflight) resolves which
`config.toml` init will read and write, and the
[unit file review](docs/guides/json-output.md#setup-service) resolves the unit
entry, including symlinked parents.
**Interactive init decides nothing until the end.** It asks a series of
questions — the registry home, the lease range, the service port, and
conditionally an app range, a well-known-ports zone, whether to write a
systemd user unit, whether to enable it, and whether to replace an existing
`config.toml` — and every answer is only a plan until the final
**Summary — apply these settings?** confirmation. Declining the summary
abandons all of it: no configuration is written, no claim is made and no unit
is installed. The one thing an earlier step can leave behind is
`registry.lock`, which reading an existing registry creates.
Three of those questions decide what happens to your files, and they are worth
separating:
- **Background service — write a systemd user unit for troll serve?** This is
the question that governs the unit. No here means no unit is written or
upgraded.
- **Enable the service now**, asked only after a yes to the unit. It governs
enablement and startup, not the file, so **answering no here does not spare
the unit file.**
- **Replace existing `config.toml`**, shown with a line-by-line preview and
asked only when the lease range, the service port or an explicit app range
changes. No here abandons the run.
So a yes to the unit, a no to activation and a yes to the summary leaves the
unit **written, upgraded, or kept unchanged** — unchanged when the installed
unit already matches what troll generates now — and init reports which.
Use `troll init --yes` to initialise a fresh installation with defaults. If a
configuration file already exists, `--yes` keeps it byte for byte and makes no
service-port claim. If that file lacks `service_port`, see the
[runbook remedies](RUNBOOK.md#failure-modes).
Decline activation in the wizard and follow the [startup preflight](RUNBOOK.md#startup-preflight)
before starting the console. The automatic sweep evaluates the whole registry
the process actually opens, removing reclaimable leases and keeping permanent
claims and leases that are active, overdue or of unknown state.
Register `troll mcp` as a standard-input/output server in your agent's Model
Context Protocol client. The [agent guide](docs/llm-guide-full.md#mcp) has a
configuration example.
## Chapter 4 · A lease's little life
*In which an expired ticket does not mean an empty cart.*
```mermaid
stateDiagram-v2
active --> overdue: Expired and still listening
active --> reclaimable: Expired and silent
active --> reclaimable: Holder process dead and port silent
overdue --> reclaimable: Port goes silent
reclaimable --> swept: Sweep
```
`troll` never stops or kills a process to reclaim a port. With ordinary terminal input the `troll with` child receives Ctrl-C once, from the terminal or from troll, whose one strict exception lets it pass received stop signals unchanged to its own child without escalating.
## Chapter 5 · Four doors, one troll
*In which all roads lead to the same ledger.*
Model Context Protocol (MCP) is how coding agents such as Claude Code and Codex call tools.
```mermaid
flowchart LR
CLI["Command line"] --> Core["troll-core"]
MCP["MCP server"] --> Core
API["HTTP API"] --> Core
Web["Web page"] --> API
Core --> Registry["registry.toml under a lock"]
Core --> Probe["troll-probe"]
Probe --> Sockets["Operating system listening sockets"]
```
| Door | Who uses it | What it does |
| --- | --- | --- |
| Command line | People and scripts | Claim, lease, check and release ports. |
| MCP server | Coding agents | Call port-management tools. |
| HTTP API | Local programs | Read the registry and make the same changes as the console. |
| Web page | People in a browser | Claim, edit and release permanent ports and apps, manage leases and stacks, set red zones and run a sweep. |
The file under a lock is the source of truth. The command line and MCP server work independently of the HTTP service.
### The web console
The console has three screens. **Console** lists **Claims** (**Apps**, and **Services and single claims**), **Leases**, **Listening with no claim**, **Red zones** and **Sweep**. **Apps and local ports** shows one section per project with its claims and leases, plus **Copy .env** and **Open web UIs** group actions. **History (30d)** lists apps, claims, components, leases and stacks removed within the last 30 days with one-click atomic **Restore**. Cards and list rows are color-accented by live state, display passively detected service badges and safe new-tab **Open** links for web interfaces, and open an **Info** modal showing process paths, service units, directory manifest/config files, and one-click copy buttons. The masthead displays the running `troll` version badge alongside the theme picker (six colour palettes) and Cards/List layout switch. The [console guide](docs/guides/console.md) walks through a private registry in the browser and gives terminal commands for the same workflows.

## Chapter 6 · The troll's oath
*In which the club is strictly decorative.*
<p align="center"><img src="docs/assets/readme/oath.webp" alt="Troll hugs a locked registry book while his club rests beside it with a flower" width="260"></p>
These are troll's promises:
- **Never swing the club.** Troll never kills, stops or signals arbitrary processes. A sweep removes only a reclaimable lease from the registry; it never signals the listener. The documented exception is `troll with`, which forwards a stop signal it received unchanged to its own child, without escalation.
- **Never lose the ledger.** Registry changes use a lock and a synced temporary file. Troll publishes the first registry by hard link without creating a backup; for later changes, it writes the previous registry to the backup and renames the new registry into place. See `link(2)` and `rename(2)`.
Troll is tested at 1,000 registry entries with a timed load and a timed locked update that adds a lease ([scale.rs](crates/troll-core/tests/scale.rs)).
- **Open the door only at home.** The service binds to `127.0.0.1`, checks every request's `Host` against an allowlist to guard against DNS rebinding, and requires a token for every change.
- **Keep secrets.** Process arguments are never shown.
## Chapter 7 · The road ahead
*In which our little guardian packs for three journeys.*
| Version | Destination |
| --- | --- |
| 0.0.x | Early development. |
| 0.1.0 | Initial Linux release (`v0.1.0`). |
| 0.2.x | Console redesign, styled human/plain CLI, 30-day history & restore, passive service/file inspection, named pools, `troll explain`, `/api/v1/snapshot`, console version badge, case-preserving red zone labels, and cross-platform refactor & QA. |
| 0.3.0 | Cross-platform release supporting Linux, macOS (arm64 + x86_64), and Windows (x86_64) with zero-`unsafe` OS probes, `launchd` and Task Scheduler service installers, Windows `netsh` excluded port range enforcement, live 3-OS CI QA, and 4-target prebuilt GitHub Release binaries (current). |
## Quick start
Linux, macOS, and Windows are supported.
### Prebuilt binaries
Download the archive for your platform from [GitHub Releases](https://github.com/michelabboud/troll/releases/latest)
(`x86_64-linux`, `aarch64-macos`, `x86_64-macos`, or `x86_64-windows` + `SHA256SUMS.txt`),
verify its checksum, extract `troll` (`troll.exe` on Windows), and place it on
your `PATH`.
> **macOS note:** If you downloaded the archive with a browser, macOS sets a
> quarantine attribute on unsigned binaries. Clear it before running:
> `xattr -d com.apple.quarantine ./troll` (or build from source with Cargo).
### Install from crates.io
```sh
cargo install troll --locked
```
### Build from checkout with Cargo
Install your platform's C build tools
(on Linux: `cc`/linker/libc dev files; on macOS: Xcode Command Line Tools; on
Windows: Visual Studio C++ Build Tools or MinGW). Install [rustup](https://rustup.rs/)
and put Cargo's bin directory (`~/.cargo/bin` or `%USERPROFILE%\.cargo\bin`) on
your `PATH`. From the root of a fresh checkout, rustup selects the pinned
Rust 1.98.1 toolchain.
`--locked` uses the versions in `Cargo.lock`. Cargo needs network access to
fetch the registry index and crates unless its cache already contains the
required index entries and locked crates.
Install the binary. If Cargo's install destination already contains `troll`,
verify that it is the binary you intend to update and preserve the old file if
you need it. This command installs the executable.
```sh
cargo install --path crates/troll --locked
```
On a fresh installation, run `troll init`. If you already configured troll,
use that configuration for the lease example below.
Confirm that the wizard shows the configuration, registry and state paths you
intend to use. Review the proposed ranges, service port and well-known ports
zone before applying the summary. Decline the optional systemd unit in this
walkthrough. On a fresh installation, init looks for an unclaimed, silent
service port starting at 7201. Its suggestions and manual choices exclude
enabled zones, the configured lease range and the operating system's known
ephemeral range.
Now take a lease.
```sh
troll lease --project myapp --purpose preview --json
```
The reply contains the assigned `port` and `leased_at` at the top level.
Use that port in your application. Record both values from your own reply;
when finished, substitute them in the command below:
```sh
troll release <port> --leased-at <leased_at>
```
Replace the angle-bracketed placeholders with the actual values, without the
brackets. Releasing the lease removes its registry entry; the process using
the port keeps running. See the [command-line guide](docs/guides/command-line.md)
for claims, renewals and more. Listener probing and `troll setup service` are
supported on Linux (`/proc` + systemd), macOS (`lsof`/`sysctl`/`ps` + `launchd`),
and Windows (`netstat`/`netsh`/PowerShell CIM + Task Scheduler).
## Build from source
Rust 1.98.1 is pinned in `rust-toolchain.toml`; you also need `just`.
```sh
just ci
```
## Documents
- [Illustrated tour](https://claude.ai/artifact/Y1Q8J5EuoXw7HBa9dDd79y): an interactive explainer of claims, leases and the bridge.
- [Plan](docs/plans/2026-11-29-troll-plan.md): the design and task list.
- [Feature ideas](docs/ideas/port-management-improvements.md): exploratory follow-up ideas for diagnosis, leases and local history.
- [Architecture](ARCHITECTURE.md): the shape of the code.
- [Runbook](RUNBOOK.md): service operation, recovery and teardown.
- [Command-line guide](docs/guides/command-line.md): everyday port management.
- [JSON and API reference](docs/guides/json-output.md): machine output, HTTP and MCP.
- [Console guide](docs/guides/console.md) for managing the registry from your browser.
- [Decision records](docs/adr/): decisions and alternatives considered.
- [Security](SECURITY.md): how to report a vulnerability.
- [Contributing](CONTRIBUTING.md): development and contribution guidance.
## Licence
MIT. Copyright (c) 2026 Michel Abboud. See [LICENSE](LICENSE).
## Agents
Run `troll setup claude` or `troll setup codex` to prepare the corresponding
plugin marketplace. Verify the host, account and staged `troll-local`
marketplace and `troll@troll-local` plugin before using the printed host
commands. For an existing marketplace or plugin, follow the
[setup review steps](docs/guides/json-output.md#setup-claude-and-setup-codex)
before changing it. Troll's CLI setup leaves its registry and running service
in place. The bundled skill teaches agents when to use claims, leases and port 0.