Local-first, cross-platform port discovery and service registry
pip install portregistry Copy PIP instructions
PortRegistry is a local-first, cross-platform port discovery and service registry. It:
It runs entirely on your machine: there is no cloud account, external database or telemetry.
It has three interfaces, all backed by one local daemon:
Status: v0.2.0 (usability release on top of the first implementation pass). See Known limitations for what has and has not been verified.
Architectural rule: one daemon process owns discovery, scheduling, application logic, event processing and every SQLite write. The GUI, TUI and CLI are clients: none of them scans the system or opens the database.
GUI: dashboard, ports explorer, endpoint and process detail, services, reservations (with a live availability check), conflicts, history, containers, machine and daemon status. Pages update live over SSE.
TUI: dashboard, ports (with search), services, reservations, conflicts, machines, history and settings, plus details and forms.
Browser (GUI) ──┐ session + CSRF Textual TUI ───┼── HTTP/JSON + SSE ──► PortRegistry daemon (one process, one uvicorn worker) Typer CLI ───┘ bearer token │ ├─ Django ASGI: /api/v1/* (DRF) + GUI pages + SSE stream ├─ Scheduler thread (native scan 10s, Docker 30s, retention hourly) ├─ Discovery: psutil provider · Docker SDK provider + event listener ├─ Services layer: reconciliation, registry, reservations, conflicts, history └─ Django ORM → SQLite (WAL, foreign keys, busy timeout) Package Responsibility portregistry.core Pure types, address/overlap semantics, identity, event bus, application container (no Django). portregistry.discovery psutil and Docker providers plus normalizers. They collect data only and never touch the database. portregistry.services The only code that writes to the database: reconciliation, registry, reservations, the conflict engine (pure) and its persistence, history, queries. portregistry.daemon Single-instance lock, scheduler, uvicorn server, lifecycle, client-side start/stop control. portregistry.django_app Settings, models, migrations, API (DRF), SSE. portregistry.gui Templates, HTMX partials, login, static assets (htmx vendored for offline use). portregistry.tui Textual app that talks to the API. portregistry.cli Typer commands that talk to the API. portregistry.client Shared sync and async HTTP clients. Key implementation decisions The GUI is served by the daemon. The browser is the client, and GUI views call the same services layer as the API. No second process touches SQLite. One writer at a time, short transactions. All writes go through services.db.write_transaction(), which combines a process-wide lock with a short atomic() block. Discovery data is collected before any transaction opens. Polling is the source of truth. psutil has no portable socket open/close events, so a periodic full scan is the correctness mechanism. Docker events only trigger a (debounced) inventory reconciliation; the periodic Docker inventory is the recovery path. Process identity is machine UUID + PID + creation time. If the creation time is unreadable, the identity is marked incomplete and is never merged with a later process that reuses the PID. Partial or failed scans never imply that something disappeared. An endpoint is marked gone only when a scan was authoritative for its protocol and port. For per-process fallback scans, it must also have been authoritative for its PID. Unchanged polls only update last_seen, so they create no new rows and no history entries. Observed state is kept apart from user intent. Observed state lives in ProcessInstance, Socket, DiscoveryScan and the Docker models. User intent lives in Service and PortReservation. History Event rows reference entities by id plus a snapshot, so deleting a service or reservation never deletes history. The scheduler starts only inside the daemon lifecycle. It is never started at import time or from Django AppConfig.ready(). SSE events are published only after the transaction commits, and clients treat them as hints. On (re)connect, clients refetch authoritative state. What works Discovery. Native discovery uses psutil:
Reconciliation and history. Results are deduplicated. History records only meaningful changes:
It also includes an event listener that reconnects with backoff. When Docker is unavailable, the rest of PortRegistry carries on normally.
Conflict engine. It reports occupied reservations, overlapping or duplicate reservations, unregistered listeners, service mismatches, missing expected services and incomplete discovery. Each finding is marked definite or potential and comes with an explanation and evidence.
You need Python 3.12 or newer. From the repository root:
py -3.12 -m venv .venv .\.venv\Scripts\Activate.ps1 python -m pip install --upgrade pip pip install -e ".[docker]" # or: pip install -e . (without Docker support) Linux / macOS:
python3.12 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip pip install -e ".[docker]" # or: pip install -e . With pipx (isolated, puts portregistry on your PATH):
pipx install ".[docker]" # from the repository root pipx run --spec . portregistry version Standalone bundles: CI builds one-folder PyInstaller bundles for Windows, Linux and macOS (portregistry- artifacts of the binaries job). Unzip and run portregistry (or portregistry.exe); no Python install is needed. To build one locally:
pip install -e ".[docker,binary]" # add ,tray on Windows/macOS for the tray icon pyinstaller --noconfirm --clean packaging/pyinstaller/portregistry.spec dist/portregistry/portregistry version Optional extras: docker (Docker discovery), tray (system tray icon: pystray + Pillow), binary (PyInstaller).
For development, which adds pytest, pytest-django, ruff, mypy and build:
pip install -e ".[docker,dev]" Check the installation:
portregistry version portregistry --help Optional Docker dependency Docker support is the docker extra (pip install "portregistry[docker]"). Without it, PortRegistry runs normally and reports Docker as unavailable ("Docker SDK for Python is not installed"). You can also turn Docker discovery off entirely with docker_enabled = false in the config file.
portregistry daemon start # detached; waits until it is healthy (initial scan runs first) portregistry daemon status # running? healthy? pid, URL portregistry daemon logs -n 100 # recent log lines (add -f to follow) portregistry daemon restart portregistry daemon stop # graceful: finishes the current scan, flushes writes, releases the lock Foreground (development): run portregistry daemon run and stop it with Ctrl+C. Different port: use portregistry daemon start --port 9876, or set PORTREGISTRY_PORT. Second daemon: starting a second daemon is refused. A crashed daemon never leaves a stale lock, because the OS releases it. Forced stop: daemon stop --force terminates the recorded process only after verifying its PID and creation time. Use it only if a graceful stop hangs. By default the daemon listens on 127.0.0.1:8765 with the API under /api/v1/. Binding to a non-loopback address needs both host and allow_remote = true in the config, and logs a security warning.
portregistry gui # starts the daemon if needed, opens a single-use login link portregistry gui --no-browser # just print the link (e.g. to open it elsewhere) The link is valid for 60 seconds and can be used once. It creates a browser session that lasts 7 days, after which you can browse to http://127.0.0.1:8765/ directly. Alternatively, open http://127.0.0.1:8765/login/ and paste the API token from the token file (see portregistry paths).
Browser changes use Django sessions with CSRF protection. Pages update live over Server-Sent Events. The top bar shows:
All assets are served locally, so the GUI works offline.
portregistry tui Key Action 1–8 / Tab Switch tab or move focus / Search ports r Refresh Enter Show details for the selected row Esc Back / close a Add a service n New reservation (pre-filled from the selected port) x Release the selected reservation i Show or hide info-level conflicts ? Help q Quit The TUI uses only the daemon API and is designed for SSH sessions. If the live connection drops, it keeps showing the last data with a warning and reconnects on its own.
portregistry status # daemon, freshness, providers, counts portregistry scan # scan now and wait (requests are coalesced) portregistry scan --protocol tcp --port 8080 # targeted reconciliation portregistry ports --port 8080 # who owns port 8080? portregistry ports --search node --protocol tcp portregistry ports -o json # JSON; -o csv for CSV portregistry ports show 42 # one endpoint with process/reservation/conflict context portregistry processes --search python portregistry containers portregistry service add webapp --exe node --cwd /srv/webapp --category web -d "Frontend" portregistry service list portregistry service show webapp portregistry service edit webapp --exe /usr/bin/node portregistry service delete webapp --yes # reservations are kept (unlinked) portregistry reserve 3000 --service webapp -d "dev server" portregistry reserve 5353 --protocol udp --address 0.0.0.0 portregistry reserve 8080 --dry-run # check only: occupancy + overlaps portregistry reservations # --status released|all portregistry reservations show 1 portregistry reservations edit 1 --address 127.0.0.1 portregistry release 1 portregistry conflicts # warnings and errors, with explanations portregistry conflicts --all # include info (e.g. unregistered listeners) portregistry history -n 50 --type endpoint portregistry machines portregistry report # markdown summary (or -o json) portregistry paths # where config/data/logs live Exit codes:
portregistry who 8080 # owner, project, label, Docker mapping, reservations, conflicts portregistry free # 5 free TCP ports in 3000-9999 (not observed, not reserved, not Docker-published) portregistry free --range 5000-5999 --protocol udp --count 3 portregistry free --reserve --service webapp # find and reserve in one step portregistry adopt 3000 # register the process on port 3000 as a service (pre-filled, asks to confirm) portregistry adopt 3000 --name shop --yes portregistry timeline 8080 --days 7 # who held port 8080 over the last week (text bars) portregistry ports --watch # live table: new endpoints green, closed ones red portregistry ports --group project # or --group process Labels: about 150 well-known and common development ports get a label (5432 PostgreSQL, 5173 Vite, 9229 Node inspector...). Labels are hints; they never decide ownership. Projects: a process's working directory is walked up (stat only, at most 12 levels) to find a project root (.git, pyproject.toml, package.json, compose.yaml...). Docker containers use their Compose project label. Adopt pre-fills name (project, Compose service or process), expected executable, working directory and category, and reserves the process's endpoints. In the GUI: Register as service on any port or process page. In the TUI: s on the Ports tab. Free-port checks also do a quick test bind on this machine by default, which catches sockets discovery could not see. Results are advisory; reserve a port to record intent. The OS ephemeral range and ports below 1024 are skipped unless you include them. GUI: "Suggest free port" in the reservation form, a Timeline page, ports grouping, and saved filters on Ports and History. TUI: a free-port button in the reservation form. Reducing noise The Conflicts page and History used to fill up with short-lived client sockets. v0.2 separates real changes from churn:
Commit a portregistry.toml to a repository so a team agrees on ports:
version = 1 [[service]] name = "web" expected_executable = "node" expected_working_directory = "." # relative to this file [[service.port]] port = 3000 # protocol defaults to tcp, address to * [[reservation]] # reservations without a service port = 5432 description = "Shared Postgres" portregistry init # scaffold from this directory's project (registered services + running processes) portregistry apply --dry-run # show creates/updates/unchanged portregistry apply # apply (one transaction; validated first) portregistry apply --prune # also release/delete items this manifest created earlier but no longer lists portregistry export -f backup.toml # full registry backup; restore with `portregistry apply backup.toml` portregistry export --format json --service web Services match by name and reservations by (service, protocol, port, address). Keys omitted from the manifest are left unchanged. --prune only touches items that were created or claimed by the same manifest file; nothing else is ever pruned.
Webhooks (opt-in; nothing is sent unless configured). Add to config.toml, then restart the daemon:
[[alerts.webhook]] url = "http://127.0.0.1:9000/portregistry" min_severity = "warning" # info | warning | error events = ["conflict.detected", "conflict.resolved", "docker.unavailable", "scan.failed"] secret = "shared-secret" # optional: X-PortRegistry-Signature: sha256= Delivery runs on a background thread with 3 retries and never blocks discovery. Test with portregistry alerts test; see counters with portregistry alerts status. Payload: {"source", "version", "event", "severity", "timestamp", "machine": {"hostname", "uuid"}, "data": {...}}.
Browser notifications: click Desktop alerts in the GUI sidebar (per-browser opt-in, uses the Notification API on live SSE events).
Scripts and CI: portregistry conflicts --fail-on warning exits with code 5 if any warning or error exists.
portregistry daemon install --dry-run # show exactly what would be written portregistry daemon install # start the daemon at login (add --tray for the tray icon) portregistry daemon autostart # status portregistry daemon uninstall OS Mechanism (per user, no admin rights) Windows HKCU\Software\Microsoft\Windows\CurrentVersion\Run value running pythonw -m portregistry daemon run --quiet (no console window) Linux systemd user unit ~/.config/systemd/user/portregistry.service (systemctl --user enable --now); XDG autostart .desktop file if systemd is unavailable macOS LaunchAgent ~/Library/LaunchAgents/io.portregistry.daemon.plist (launchctl bootstrap gui/ ) A PORTREGISTRY_HOME set when you run install is carried into the autostart entry.
Tray icon (pip install "portregistry[tray]", then portregistry tray): a coloured dot (green ok, yellow warnings or stale data, red errors, grey daemon down) with a menu to open the GUI, see conflicts, scan now, start/stop the daemon, and toggle notifications for new conflicts.
Doctor: portregistry doctor checks Python, config, data-dir permissions, token-file permissions, daemon reachability (or whether its port is taken), database integrity and WAL mode, disk space, scan health and freshness, visibility/elevation, Docker, scheduler, webhooks, autostart and the tray extra. Each check prints an exact fix. It exits 1 if anything fails (-o json for scripts).
Token rotation: portregistry token rotate replaces the local API token (the old one stops working immediately) and logs out browser sessions unless --keep-sessions. The new token is written to the token file and never printed.
Visibility hints: the GUI machine page, the "Limited visibility" badge and doctor explain how to get fuller visibility on your OS (for example, start the daemon from an Administrator terminal on Windows). PortRegistry still never elevates itself.
Run portregistry paths to see the exact paths. The defaults come from platformdirs:
Set PORTREGISTRY_HOME=/some/dir to keep everything under one directory, for isolated demos or several instances.
retention_days applies to events and to inactive observed sockets, processes, containers and scans. Services and reservations are never deleted by retention.
PortRegistry can stop the process that owns a port. This is off by default and changes the original PRD, which listed killing processes as a non-goal: it is now an opt-in feature with the constraints below. A stop cannot be undone.
Turn it on in config.toml and restart the daemon:
[control] enabled = true # off by default allow_other_users = false # only takes effect when the daemon runs elevated grace_seconds = 10 # how long a graceful stop waits (2-60) Own processes only. Never stopped: PortRegistry itself and its parents, the program making the request and its parents, PIDs 0/1/4, kernel threads, Windows services, critical system programs, and root/SYSTEM-owned processes. Other users' processes need allow_other_users = true and an elevated daemon. Two steps everywhere. Review shows the command line, folder, parent chain, stop method, ports and registered services affected. Continuing issues a single-use code, valid for 30 seconds and bound to that exact process (PID + creation time). You confirm by typing the PID. There is no --yes, and the CLI refuses to stop anything without an interactive terminal. Graceful first, labelled honestly. POSIX: SIGTERM. Windows: WM_CLOSE for programs with a window; console programs can only be ended at once and are labelled "immediate stop". A process that ignores a graceful stop is never force-stopped automatically; choose the forced stop explicitly. Tree mode (--tree, "Whole tree") lists every child first and refuses if any member is protected. Children are stopped before the parent. Docker and services are not stopped. For a container, the exact docker stop command is shown instead. Do it yourself instead. Every Stop page and portregistry stop --show-command prints the kill/taskkill commands; this works even while control is off. Audited. Every attempt, allowed or refused, is recorded in history (portregistry history --type process.stop), with who asked (GUI/CLI/TUI/API), the process identity, the method and the result. Webhooks can receive process.stopped, process.stop_refused, process.stop_failed and process.stop_timeout (without command lines). Control is forced off whenever the daemon listens on a non-loopback address. portregistry stop 3000 # review, then type the PID portregistry stop --pid 4242 --tree # the process and all of its children portregistry stop 3000 --show-command # print the commands only In the GUI use "Stop…" on a port or process page; in the TUI press X on the Ports tab.
PortRegistry never elevates privileges (no sudo, no UAC). It never reads process environment variables and never executes discovered command lines.
How much it can see depends on the OS and your privileges, and it reports this as limited visibility:
Command lines can contain secrets passed as arguments. They are stored only in the local database, are shown escaped, and can be turned off with collect_cmdline = false.
Overlap rules for the same protocol and port:
pip install -e ".[docker,dev]" portregistry daemon start portregistry status In another terminal, open a test TCP listener and a UDP socket:
python -c "import socket,time; t=socket.socket(); t.bind(('127.0.0.1',18080)); t.listen(); u=socket.socket(type=socket.SOCK_DGRAM); u.bind(('0.0.0.0',18081)); time.sleep(600)" Discover them:
portregistry scan portregistry ports --search 1808 # both appear with the owning python process + PID Register a service and reserve the occupied port:
portregistry service add demo --exe nginx portregistry reserve 18080 --service demo # -> error (definite) service_mismatch: expected 'nginx', observed python portregistry reserve 18080 --address 127.0.0.1 # -> overlapping_reservation with #1 portregistry reserve 18080 --protocol udp # -> no conflict: TCP and UDP are independent portregistry conflicts Open the GUI and the TUI. Both show the same machine, endpoints, reservations and conflicts:
portregistry gui portregistry tui Stop the test process (Ctrl+C), wait about 10 seconds or run portregistry scan, then check the history:
portregistry history -n 10 # endpoint.disappeared / process.disappeared, conflict changes Restart and confirm that the data survives:
portregistry daemon restart portregistry service list portregistry reservations --status all portregistry machines # same machine UUID Run the tests:
docker run -d --name demo-web -p 18090:80 nginx:alpine portregistry containers portregistry ports --port 18090 # host socket + Docker correlation docker rm -f demo-web # within seconds: container.disappeared in history Known limitations Platform coverage: Developed and verified on Windows 11 only: unit, integration, API, GUI, TUI and CLI tests, plus live daemon runs. Linux and macOS behaviour follows the documented psutil semantics and runs in CI, but has not been run interactively. Full platform parity is not claimed. Live Docker discovery was not verified on the development machine, which has no Docker or WSL. What was covered: fake-client unit tests and the "Docker unavailable" path.
A docker_live test suite (tests/docker/test_docker_live.py) runs in CI on Ubuntu and is intended for manual cross-checking on a Docker host:
PORTREGISTRY_REQUIRE_DOCKER=1 pytest -m docker_live GitHub's Windows and macOS runners cannot run Linux containers, so live Docker coverage there relies on that manual check.
pip install -e ".[docker,dev]" pytest # full suite (includes a real daemon-lifecycle test) pytest -m "not slow" # skip daemon subprocess tests pytest -m docker_live # live Docker tests (skipped if Docker is unreachable) ruff check src tests ruff format --check src tests mypy # core, discovery, config, paths, client, conflict engine, daemon parts, tray python -m build # sdist + wheel pyinstaller --noconfirm --clean packaging/pyinstaller/portregistry.spec # needs the [binary] extra Django management commands, for example after changing models:
python -m django makemigrations portregistry --settings=portregistry.django_app.settings CI is defined in .github/workflows/ci.yml. It runs lint and type checks, tests on Ubuntu, Windows and macOS with Python 3.12 and 3.13, a Docker-required live job on Ubuntu, a package build with wheel and pipx smoke tests, and PyInstaller bundles for all three OSes (each smoke-tested by starting and stopping the daemon).
devtools homelab ports psutil service-registry sockets
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




