portzilla 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +130 -284
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,368 +1,214 @@
1
- # portzilla
1
+ <p align="center">
2
+ <img src="logo.png" alt="Portzilla" width="360">
3
+ </p>
2
4
 
3
- [![CI](https://github.com/011010/portzilla/actions/workflows/ci.yml/badge.svg)](https://github.com/011010/portzilla/actions/workflows/ci.yml)
5
+ <h1 align="center">portzilla</h1>
4
6
 
5
- `portzilla` is a lease registry for localhost ports. It exists because AI coding agents (Claude Code, Cursor, and similar tools) increasingly run several parallel sessions on one machine — each in its own git worktree, each starting its own dev server — and today those sessions have no way to coordinate. An agent that finds port 3000 busy typically just kills whatever is on it, which can be a sibling session's dev server. `portzilla` gives processes a way to claim a port with an owner PID and a purpose tag, gives conflicting claims the next free port instead of stealing, lets anyone ask who owns a port before killing it, and prunes leases whose owning process has died. All output is available as JSON so agents can consume it directly, and the tool works the same way for a human typing commands in a terminal.
7
+ <p align="center">
8
+ <strong>Lease registry for localhost ports — stop killing your sibling's dev server.</strong>
9
+ </p>
6
10
 
7
- This is coordination, not diagnostics: existing tools like `witr`, `kill-port`, and ServerSlayer tell you what is on a port or kill it after the fact. `portzilla` is the layer that prevents the conflict in the first place.
11
+ <p align="center">
12
+ <a href="https://github.com/011010/portzilla/actions/workflows/ci.yml"><img src="https://github.com/011010/portzilla/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
13
+ <a href="https://crates.io/crates/portzilla"><img src="https://img.shields.io/crates/v/portzilla" alt="crates.io"></a>
14
+ <a href="https://www.npmjs.com/package/portzilla"><img src="https://img.shields.io/npm/v/portzilla" alt="npm"></a>
15
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT"></a>
16
+ </p>
8
17
 
9
- For maintainers, the complete release procedure is documented in [`docs/RELEASING.md`](docs/RELEASING.md).
18
+ > AI coding agents (Claude Code, Cursor, etc.) run parallel sessions in git worktrees — each starting its own dev server. Today they coordinate by killing whatever is on a port. `portzilla` is the layer that **prevents the conflict**.
10
19
 
11
- ## 30-second demo
20
+ - **Claim, don't kill** — `portzilla claim 3000 --tag next-dev` gives you a port with owner PID + purpose tag. Conflicts and already-bound ports get the next available port instead of stealing.
21
+ - **Ask before you kill** — `portzilla who 3000` tells you who owns a port. JSON everywhere so agents can consume it directly.
22
+ - **Guard by default** — intercepts `kill`, `lsof | xargs kill`, `fuser -k`, `kill-port` and blocks kills against another session's live lease.
23
+
24
+ Existing tools (`witr`, `kill-port`, ServerSlayer) tell you what's on a port *after* the fact. `portzilla` prevents the conflict in the first place.
25
+
26
+ ![Portzilla preventing a port conflict](docs/assets/portzilla-demo.gif)
27
+
28
+ ## Contents
29
+
30
+ - [Quick start](#quick-start)
31
+ - [Demo](#demo)
32
+ - [Install](#install)
33
+ - [Commands](#commands)
34
+ - [Watch mode](#watch-mode)
35
+ - [MCP server](#mcp-server)
36
+ - [Kill guard](#kill-guard)
37
+ - [Data file & config](#data-file--config)
38
+ - [Limitations](#limitations)
39
+
40
+ ## Quick start
12
41
 
13
42
  ```console
14
- $ portzilla claim 3000 --tag next-dev --pid 57107
43
+ $ portzilla claim 3000 --tag next-dev --session "$CLAUDE_CODE_SESSION_ID"
15
44
  claimed port 3000 for pid 57107 (tag: next-dev)
16
45
 
17
- $ portzilla claim 3000 --tag vite-dev --pid 57108
18
- port 3000 is busy; claimed port 3001 instead for pid 57108 (tag: vite-dev)
19
-
20
- $ portzilla who 3001
21
- port: 3001
22
- pid: 57108
23
- tag: vite-dev
24
- session: (none)
25
- age: 3s
46
+ $ portzilla who 3000
47
+ port: 3000
48
+ pid: 57107
49
+ tag: next-dev
26
50
  status: alive
27
51
 
28
- $ portzilla who 3001 --json
29
- {"port":3001,"pid":57108,"tag":"vite-dev","created_at":1785959877,"session":null,"age_secs":3,"alive":true}
30
-
31
52
  $ portzilla ls
32
53
  PORT PID STATUS AGE TAG
33
54
  3000 57107 alive 5s next-dev
34
- 3001 57108 alive 3s vite-dev
55
+ ```
56
+
57
+ Data-producing commands accept `--json` for agent consumption. See [CLI reference](docs/CLI.md).
58
+
59
+ ## Demo
60
+
61
+ ```console
62
+ $ portzilla claim 3000 --tag next-dev --pid 57107
63
+ claimed port 3000 for pid 57107 (tag: next-dev)
64
+
65
+ $ portzilla claim 3000 --tag vite-dev --pid 57108
66
+ port 3000 is busy (lease conflict); claimed port 3001 instead for pid 57108 (tag: vite-dev)
67
+
68
+ $ portzilla who 3001 --json
69
+ {"port":3001,"pid":57108,"tag":"vite-dev","created_at":1785959877,"session":null,"process_start_time":1785959876,"age_secs":3,"alive":true}
35
70
 
36
71
  $ portzilla release 3001
37
72
  warning: released port 3001 whose owning pid 57108 is still alive
38
73
  port: 3001
39
74
  pid: 57108
40
75
  tag: vite-dev
41
- session: (none)
42
- age: 3s
43
76
  status: alive
44
77
 
45
78
  $ portzilla prune
46
79
  no dead leases to prune
47
80
  ```
48
81
 
49
- The output above is real: it was captured by running the built binary with `PORTZILLA_DATA_DIR` pointed at a temporary directory holding two genuinely live processes.
82
+ > Output is real — captured with `PORTZILLA_DATA_DIR` pointed at a temp directory with two live processes.
50
83
 
51
84
  ## Install
52
85
 
53
- ### Cargo
54
-
86
+ **Cargo:**
55
87
  ```console
56
88
  $ cargo install portzilla
57
- ```
58
-
59
- To install from a local checkout:
60
-
61
- ```console
89
+ # from local checkout:
62
90
  $ cargo install --path .
63
91
  ```
64
92
 
65
- ### curl
66
-
67
- Downloads a prebuilt binary from GitHub Releases into `~/.local/bin`:
68
-
93
+ **curl** (prebuilt binary to `~/.local/bin`, falls back to cargo):
69
94
  ```console
70
95
  $ curl --proto '=https' --tlsv1.2 -LsSf https://raw.githubusercontent.com/011010/portzilla/main/scripts/install.sh | sh
96
+ # specific version / directory:
97
+ $ curl --proto '=https' --tlsv1.2 -LsSf https://raw.githubusercontent.com/011010/portzilla/main/scripts/install.sh | PORTZILLA_VERSION=0.2.0 PORTZILLA_INSTALL_DIR=/usr/local/bin sh
71
98
  ```
72
99
 
73
- To install a specific version or directory:
74
-
75
- ```console
76
- $ curl --proto '=https' --tlsv1.2 -LsSf https://raw.githubusercontent.com/011010/portzilla/main/scripts/install.sh | PORTZILLA_VERSION=0.1.0 PORTZILLA_INSTALL_DIR=/usr/local/bin sh
77
- ```
78
-
79
- If a release asset is unavailable, the installer falls back to `cargo install portzilla`.
80
-
81
- ### npm
82
-
100
+ **npm** (same native binary):
83
101
  ```console
84
102
  $ npm install -g portzilla
85
103
  ```
86
104
 
87
- The npm package installs the same native `portzilla` binary. It downloads a GitHub Release asset when available and falls back to Cargo when needed.
88
-
89
- Release binaries are currently available for Linux x86_64/ARM64, macOS Intel/Apple Silicon, and Windows x86_64/ARM64. Each release asset includes a `.sha256` checksum file.
90
-
91
- ## Command reference
92
-
93
- Every command accepts `--json` to print a single JSON value on stdout instead of human-readable text. Every command reads and writes the same file-locked JSON state file, so concurrent invocations from different processes are serialized safely.
94
-
95
- ### `portzilla claim <PORT> --tag <TAG> [--pid <PID>] [--session <SESSION>] [--json]`
96
-
97
- Claims `<PORT>` for the given (or default) PID and tag.
98
-
99
- - `--tag <TAG>` — required. Human-readable description of what the port is for.
100
- - `--pid <PID>` — optional. Defaults to the PID of the parent process (the shell or agent invoking `portzilla`); falls back to `portzilla`'s own PID if the parent cannot be determined.
101
- - `--session <SESSION>` — optional. Groups related leases under a session identifier.
102
- - `--json` — print the outcome as JSON instead of a one-line summary.
103
-
104
- Conflict resolution:
105
-
106
- - No lease on the requested port, or the existing lease's owning PID is dead: the port is claimed (or re-taken) directly. Not reassigned.
107
- - A live lease on the requested port already owned by the same PID: the lease is updated in place (idempotent re-claim — tag and session can change, the port does not). Not reassigned.
108
- - A live lease on the requested port owned by a different PID: `portzilla` finds the next free port at or after `requested_port + 1` (skipping ports with a live lease and ports the OS reports as bound) and claims that instead. Reassigned.
109
-
110
- ### `portzilla ls [--json]`
111
-
112
- Lists every recorded lease. Human output is a table (`PORT PID STATUS AGE TAG`); JSON output is an array of lease objects (see shape below).
113
-
114
- ### `portzilla who <PORT> [--json]`
115
-
116
- Shows the lease recorded on `<PORT>`. Exits with code `2` and prints nothing to stdout if no lease exists on that port.
105
+ Binaries for Linux x86_64/ARM64, macOS Intel/Apple Silicon, Windows x86_64/ARM64 — each with `.sha256` checksums.
117
106
 
118
- ### `portzilla release <PORT> [--json]`
107
+ ## Commands
119
108
 
120
- Removes the lease recorded on `<PORT>` and prints the removed lease. Exits with code `2` if no lease exists on that port. If the owning PID is still alive at the time of release, a warning is printed to stderr (`release` always wins — it does not check ownership or refuse to act).
109
+ | Command | What it does |
110
+ |---------|--------------|
111
+ | `portzilla claim <PORT> --tag <TAG> [--pid <PID>] [--session <S>]` | Claim a port; on conflict with a live lease from another PID, auto-claims next free port |
112
+ | `portzilla ls` | List all leases (`PORT PID STATUS AGE TAG`) |
113
+ | `portzilla who <PORT>` | Show lease on a port (exit `2` if none) |
114
+ | `portzilla release <PORT>` | Remove lease (always wins; warns if PID still alive) |
115
+ | `portzilla prune` | Remove all leases whose PID is dead |
116
+ | `portzilla watch [--interval <SECONDS>]` | Repeatedly prune leases whose recorded PID is dead |
121
117
 
122
- ### `portzilla prune [--json]`
118
+ Data-producing commands are file-locked and support `--json`. Full flags, conflict semantics, exit codes and JSON shapes → **[docs/CLI.md](docs/CLI.md)**.
123
119
 
124
- Removes every lease whose owning PID is no longer alive and prints each one that was removed. Human output prints `no dead leases to prune` if nothing was pruned; JSON output prints `[]`.
120
+ ## Watch mode
125
121
 
126
- ## Exit codes
122
+ `portzilla watch` is an optional foreground watcher. It is not a central IPC
123
+ daemon: it uses the same locked local state file as the other commands, does
124
+ not listen for clients, and agents continue to use the CLI or MCP server for
125
+ claims and queries.
127
126
 
128
- | Code | Meaning |
129
- |------|---------|
130
- | `0` | Success |
131
- | `1` | Unexpected error (I/O failure, corrupt state file, lock failure) |
132
- | `2` | Requested lease not found (`who` / `release` on a port with no lease) |
133
-
134
- ## JSON output shapes
135
-
136
- ### Lease object (`ls`, `who`, `release`, `prune`)
137
-
138
- Used as a single object by `who` and `release`, and as an array of these objects by `ls` and `prune`:
139
-
140
- ```json
141
- {
142
- "port": 3001,
143
- "pid": 57108,
144
- "tag": "vite-dev",
145
- "created_at": 1785959877,
146
- "session": null,
147
- "age_secs": 3,
148
- "alive": true
149
- }
127
+ ```console
128
+ $ portzilla watch --interval 30
129
+ no leases pruned
130
+ pruned port 3000 (pid 57107, tag: next-dev)
150
131
  ```
151
132
 
152
- `created_at` is a Unix timestamp in seconds. `session` is `null` unless `--session` was given at claim time. `alive` reflects a live PID-table check at the moment of the query, not a cached value.
133
+ The watcher validates that `--interval` is a positive number of seconds and
134
+ defaults to `60`. It runs one prune cycle immediately, waits for the interval,
135
+ then repeats until Ctrl-C. Each cycle checks recorded process liveness, not
136
+ lease age, and removes only leases whose recorded server process is no longer
137
+ alive. For a new lease, preservation requires a verified process identity: the
138
+ current process must match both the recorded PID and `process_start_time`. If
139
+ identity could not be resolved when the lease was created, it is intentionally
140
+ unverified/dead and may be pruned even when that numeric PID currently exists.
141
+ Legacy leases without identity metadata retain PID-only liveness behavior. If
142
+ an agent exits while a new lease's verified recorded server process remains
143
+ alive, that lease is preserved.
153
144
 
154
- ### Claim outcome (`claim --json`)
145
+ Ordinary store errors are printed to stderr and retried on the next cycle. A
146
+ startup error, such as an inability to open the data directory, is fatal and
147
+ exits the command instead of entering the retry loop. Ctrl-C shuts down the
148
+ watcher successfully.
149
+
150
+ With `--json`, stdout contains one event per completed cycle, including empty
151
+ cycles:
155
152
 
156
153
  ```json
157
- {
158
- "port": 3001,
159
- "pid": 57285,
160
- "tag": "vite-dev",
161
- "created_at": 1785959898,
162
- "session": null,
163
- "requested_port": 3000,
164
- "reassigned": true
165
- }
154
+ {"event":"watch_cycle","pruned":[]}
155
+ {"event":"watch_cycle","pruned":[{"port":3000,"pid":57107,"tag":"next-dev","created_at":1785959877,"session":null,"process_start_time":1785959876,"age_secs":3,"alive":false}]}
166
156
  ```
167
157
 
168
- `requested_port` is the port that was originally asked for; `port` is the port actually leased. `reassigned` is `true` only when `port != requested_port` because of a live conflicting claim.
158
+ Diagnostics, including retry and shutdown messages, go to stderr. See the
159
+ [CLI reference](docs/CLI.md) for the complete event shape.
169
160
 
170
161
  ## MCP server
171
162
 
172
- `portzilla serve --mcp` runs an [MCP](https://modelcontextprotocol.io) server over stdio, exposing `claim`, `who`, `ls`, `release`, and `prune` as MCP tools (those are the registered tool names — no `portzilla_` prefix). This is for AI coding agents with MCP tool access (Claude Code, and any other MCP client): they call `who` the same way they call any other structured tool — typed JSON in, typed JSON out — instead of shelling out to the CLI and parsing text.
173
-
174
- Register it with Claude Code:
163
+ For agents with MCP access (Claude Code, etc.) — typed JSON in/out instead of shelling out:
175
164
 
176
165
  ```console
177
166
  $ claude mcp add portzilla -- portzilla serve --mcp
178
167
  ```
179
168
 
180
- Every tool's description is written to make the intended behavior explicit to the calling agent — the `claim` tool description, for example, says outright to use it *instead of* killing whatever occupies a port. Tool results use the exact same flat JSON shapes documented above for `--json` output (see [JSON output shapes](#json-output-shapes)), so anything already written against the CLI's JSON recognizes MCP results too.
181
-
182
- - **`claim(port, tag, pid?, session?)`** — same semantics as `portzilla claim`. `pid` is optional here for a different reason than on the CLI: there is no meaningful "parent process" to default to (the MCP client, not a shell, owns the session), so an omitted `pid` falls back to the portzilla server process's own PID — almost never what you want — and the result carries an extra `note` field saying so. Always pass the PID of the process you started (or are about to start) on that port when you have it.
183
- - **`who(port)`** — same semantics as `portzilla who`.
184
- - **`ls()`** — same semantics as `portzilla ls`, no arguments.
185
- - **`release(port)`** — same semantics as `portzilla release`, including the still-alive warning (surfaced as a `was_alive` field on the result instead of a stderr line).
186
- - **`prune()`** — same semantics as `portzilla prune`, no arguments.
187
-
188
- **Errors**: a missing lease (`who`/`release` on a port with no lease) comes back as a *tool-level* error — the JSON-RPC call still succeeds, but the tool result is flagged `isError: true` with a structured `{"error": "not_found", "port": ..., "message": ...}` body. This mirrors the CLI's exit code `2`: it is an expected, well-formed outcome the calling agent should see and act on, not a protocol failure. Actual portzilla failures (I/O errors, corrupt state, lock failures — the CLI's exit code `1`) come back as real JSON-RPC protocol errors instead, since those mean the server itself couldn't do its job.
189
-
190
- The MCP server reads and writes the exact same locked `leases.json` the CLI does (respecting `PORTZILLA_DATA_DIR`) — it is a second front end onto the same on-disk state, not a separate store.
169
+ Exposes `claim`, `who`, `ls`, `release`, `prune` as MCP tools with the same JSON shapes as `--json`. See **[docs/CLI.md#mcp-server](docs/CLI.md#mcp-server)**.
191
170
 
192
171
  ## Kill guard
193
172
 
194
- MCP tool access (above) makes it *possible* for an agent to check ownership before acting. The kill guard is what makes checking the *default*: it intercepts kill-shaped commands before they run and blocks the ones that would kill another session's live, leased process — instead of relying on the agent to remember to run `who` first.
195
-
196
- The guard itself (`src/guard.rs`) is harness-agnostic: it takes a shell command string and the current lease list and returns a verdict, with no knowledge of Claude Code, Cursor, Gemini CLI, Codex CLI, Kimi CLI, OpenCode, Windsurf, or any other tool. Each harness gets a thin adapter over the same core (`src/claude_code.rs`, `src/cursor.rs`, `src/gemini.rs`, `src/codex.rs`, `src/kimi.rs`, `src/opencode.rs`, `src/windsurf.rs`) that only translates the harness's hook payload in and its response shape out — adding a new harness means writing another adapter like these, never touching the guard itself.
173
+ Makes *checking ownership the default* — blocks `kill` commands that would kill another session's live leased process.
197
174
 
198
- It recognizes:
175
+ Recognizes `kill <pid>`, `pkill`/`killall`, `lsof -ti:<port> | xargs kill`, `fuser -k <port>/tcp`, `kill-port <port>` (including `sudo`, `env` wrappers and `sh -c` payloads). Verdict: **Allow** / **Deny** (live foreign lease) / **Warn** (unresolvable).
199
176
 
200
- - `kill <pid>` / `kill -9 <pid>` — explicit PIDs, including `sudo kill ...`, `FOO=1 kill ...` (leading env-var assignments), and `/usr/bin/kill ...` (matched by basename)
201
- - `pkill <name>` / `killall <name>` — process names (can't be resolved to a specific lease, so this only ever warns, never denies)
202
- - `lsof -ti:<port> | xargs kill` (and the `lsof -ti :<port>` / `-9` variants) — only when actually piped together, not merely run one after another with `;`/`&&`
203
- - `fuser -k <port>/tcp` (and `/udp`) — a bare `fuser -k <port>` with no protocol suffix is not treated as a port kill, matching real `fuser`'s own argument parsing
204
- - `npx kill-port <port>` / `kill-port <port>` (including `npx -y kill-port ...` / `npx --yes kill-port ...`)
177
+ | Harness | Hook | Deny reaches model? | Own-lease? |
178
+ |---------|------|---------------------|------------|
179
+ | **Claude Code** | `PreToolUse` — `portzilla hook claude-code` | Yes (`permissionDecisionReason`) | **Yes** (`$CLAUDE_CODE_SESSION_ID`) |
180
+ | **Cursor** | `beforeShellExecution` — `portzilla hook cursor` | Likely (`agent_message`) | No |
181
+ | **Gemini CLI** | `BeforeTool` — `portzilla hook gemini` | Yes (Deny), no Warn channel | No |
182
+ | **Codex CLI** | `PreToolUse` — `portzilla hook codex` | Yes (Deny + Warn via `additionalContext`) | No |
183
+ | **Kimi CLI** | `PreToolUse` — `portzilla hook kimi` | Yes (stderr on exit 2) | No |
184
+ | **OpenCode** | Plugin shim — `portzilla init opencode` | Yes (Deny + Warn) | **Yes** (`$PORTZILLA_SESSION`) |
185
+ | **Windsurf** | `pre_run_command` — `portzilla hook windsurf` | Yes (stderr) | No |
186
+ | **Anything else** | `portzilla guard -- <cmd>` | N/A (exit 2) | **Yes** (`--session` / `$PORTZILLA_SESSION`) |
205
187
 
206
- Leading wrapper prefixes are stripped before the verb is read, so the kill intent is detected whether it appears directly or behind one of `env`, `command`, `exec`, `nohup`, `builtin`, or any combination with `sudo` — `sudo env FOO=1 command kill <pid>` resolves to `kill <pid>`. A leading `sh -c '<payload>'` invocation is also unwrapped (the same shape the universal `guard` wrapper handles for argv), so a kill hidden inside the payload is detected through the hook adapters too.
188
+ Setup: `portzilla init <harness>` prints the snippet to add — never writes files for you. Guard fails open by default; `PORTZILLA_FAIL_CLOSED=1` opts into fail-closed.
207
189
 
208
- For each, it resolves the target PID or port against the lease registry and decides:
190
+ Full harness setup, `sh -c` unwrapping rules, and fail-open/closed semantics → **[docs/GUARD.md](docs/GUARD.md)**.
209
191
 
210
- - **Allow** — no kill intent detected, the target has no live lease, the lease is dead, or the lease is yours (you're allowed to kill/restart your own claimed process — see "Session ownership" below).
211
- - **Deny** — the target has a live lease owned by someone else. The explanation names the port, PID, and tag, and says what to do instead: check `portzilla who <port>`, claim a different port, or ask before proceeding if the lease looks stale.
212
- - **Warn** — a kill intent was detected but can't be resolved to a specific port/PID (killing by process name). portzilla can't verify safety here, so it surfaces a warning instead of silently allowing or incorrectly denying.
192
+ ## Data file & config
213
193
 
214
- This is intentionally not a real shell parser — see the module doc comment in `src/guard.rs` for the exact approximation (split on `|`/`;`/`&&`/`||`, look at each segment's first word) and its tested boundaries, e.g. `killall-whatever` doesn't trigger `killall` detection, and `echo "kill 123"` doesn't trigger `kill` detection. False negatives are an accepted tradeoff; false positives are not.
194
+ Resolution order: `PORTZILLA_DATA_DIR` → `$XDG_DATA_HOME/portzilla` → `~/.local/share/portzilla`. State at `leases.json` (atomic write + `leases.json.lock`).
215
195
 
216
- ### Support matrix
196
+ `PORTZILLA_DATA_DIR` isolates tests/CI. `tag` max 1024 chars, `session` max 512, hook stdin capped at 1 MiB. New leases persist `process_start_time` when available; reassignment JSON includes `reassignment_reason` (`lease_conflict` or `os_occupied`). Claims for an explicit PID that does not exist yet are retained as unverified/dead records, not as ownership promises. The normal CLI default attributes a claim to its live parent process. See **[docs/CLI.md](docs/CLI.md)**.
217
197
 
218
- | Harness | Mechanism | Deny reason reaches the model? | Own-lease recognition? |
219
- |---|---|---|---|
220
- | **Claude Code** | `PreToolUse` hook, `portzilla hook claude-code` | Yes — `permissionDecisionReason` | **Yes** — `--session "$CLAUDE_CODE_SESSION_ID"` |
221
- | **Cursor** | `beforeShellExecution` hook, `portzilla hook cursor` | Likely — `agent_message` is documented for this event without a deny-only qualifier (unlike some other Cursor hook events' docs); delivery on `permission: "allow"` is not positively confirmed, only not ruled out — needs a live Cursor smoke test | No — `conversation_id` isn't exposed to the agent's shell commands |
222
- | **Gemini CLI** | `BeforeTool` hook on `run_shell_command`, `portzilla hook gemini` | Yes for Deny (`reason`); **no non-blocking channel for Warn** (human-only, `systemMessage`) | No — the shell tool only sets `GEMINI_CLI=1`, not a session id |
223
- | **Codex CLI** | `PreToolUse` hook, `portzilla hook codex` | Yes — `permissionDecisionReason` on deny; **yes for Warn** — `additionalContext` is added as extra developer context the model sees | No — `session_id` reaches the hook payload but not the agent's shell commands |
224
- | **Kimi CLI** | `PreToolUse` hook, `portzilla hook kimi` | Yes — stderr on exit 2 is fed back to the model; **yes for Warn** — exit-0 stdout is added to the model's context | No — `session_id` reaches the hook payload but not the agent's shell commands |
225
- | **OpenCode** | Plugin shim (`portzilla init opencode` prints `portzilla.js`) shelling out to `portzilla hook opencode` | Yes for Deny — throwing surfaces the reason as a tool error; **yes for Warn** — appended to the tool result via `tool.execute.after` | **Yes** — the shim injects `PORTZILLA_SESSION` into bash subprocess env via `shell.env`, and the guard gets the session id from `tool.execute.before` |
226
- | **Windsurf** | `pre_run_command` hook, `portzilla hook windsurf` | Yes for Deny — stderr on exit 2 is shown to the Cascade agent; **no non-blocking channel for Warn** (stderr on exit 0 is human-visible only; with `show_output: true`) | No — `trajectory_id` reaches the hook payload but not the agent's shell commands |
227
- | **Anything else** (Aider, scripts, a human) | `portzilla guard -- <command...>` | N/A — the command is simply not run (exit 2); there's no model in the loop to explain to | **Yes** — `--session <S>` or `PORTZILLA_SESSION` |
228
-
229
- "Own-lease recognition" means: a lease claimed with the right session identifier is recognized as *yours*, so the guard lets you kill/restart your own process. Without it, the guard still protects you from killing *other* sessions' processes — it just can't yet tell your own process apart from a stranger's, so it protects everyone equally, including you.
230
-
231
- ### Claude Code setup
232
-
233
- ```console
234
- $ portzilla init claude-code
235
- ```
236
-
237
- prints the exact `.claude/settings.json` snippet to add (project-level `.claude/settings.json` or user-level `~/.claude/settings.json`), registering `portzilla hook claude-code` as a `PreToolUse` hook on the `Bash` tool. This only prints instructions — it never writes to your settings file.
238
-
239
- For session ownership to resolve end to end, claim with the session id Claude Code exposes to Bash tool subprocesses (verified against the Claude Code environment variables reference — `CLAUDE_CODE_SESSION_ID` "matches the `session_id` field in the hook JSON input" for Bash, PowerShell, and hook subprocesses):
240
-
241
- ```console
242
- $ portzilla claim 3000 --tag "vite dev" --session "$CLAUDE_CODE_SESSION_ID"
243
- ```
244
-
245
- ### Cursor setup
246
-
247
- ```console
248
- $ portzilla init cursor
249
- ```
250
-
251
- prints the `.cursor/hooks.json` snippet (project `.cursor/hooks.json` or user `~/.cursor/hooks.json`), registering `portzilla hook cursor` as a `beforeShellExecution` hook. Cursor's own hook runner already fails open by default on a hook crash/timeout/invalid-JSON (unless `failClosed: true` is set, which this setup does not ask for).
252
-
253
- Cursor does not currently expose `conversation_id` to the shell commands it runs — only to the hook payload itself (verified: the hooks doc's own "Environment Variables" table lists `CURSOR_PROJECT_DIR`, `CURSOR_VERSION`, `CURSOR_USER_EMAIL`, `CURSOR_TRANSCRIPT_PATH`, `CURSOR_CODE_REMOTE`, and `CLAUDE_PROJECT_DIR` — none of them a session/conversation id, and that table is explicitly scoped to what the hook script receives, not the agent's own commands). So there is currently no `--session` value a Cursor-driven claim can use to be recognized as its own later. Foreign-lease protection still works fully; own-lease recognition doesn't yet, pending Cursor documenting such a variable.
254
-
255
- ### Gemini CLI setup
256
-
257
- ```console
258
- $ portzilla init gemini
259
- ```
260
-
261
- prints the `.gemini/settings.json` snippet (project `.gemini/settings.json`, user `~/.gemini/settings.json`, or system `/etc/gemini-cli/settings.json`), registering `portzilla hook gemini` as a `BeforeTool` hook matched on the `run_shell_command` tool.
262
-
263
- Two things are worth knowing here, both found during verification rather than assumed: first, hook registration lives in `settings.json`, not a standalone `hooks/hooks.json` file inside an extension directory — the current reference documents only the `settings.json`-based mechanism. Second, `run_shell_command`'s own subprocess (the agent's actual shell commands) is only ever given `GEMINI_CLI=1` — a bare presence flag, not a session id (`GEMINI_SESSION_ID` exists, but is documented as available to hook script subprocesses, not shell-tool subprocesses) — so, same as Cursor, own-lease recognition isn't available yet.
264
-
265
- ### Codex CLI setup
266
-
267
- ```console
268
- $ portzilla init codex
269
- ```
270
-
271
- prints the exact `.codex/hooks.json` snippet to add (project-level `.codex/hooks.json` or user-level `~/.codex/hooks.json`), registering `portzilla hook codex` as a `PreToolUse` hook matched on `Bash`. Codex's hooks are [generally available](https://developers.openai.com/codex/hooks); project-level hooks are only loaded once the project's `.codex/` layer is trusted (Codex asks you to review/trust new hooks — see its `/hooks` command).
272
-
273
- Codex's own env-vars reference does not expose the session id to the shell commands the agent runs — only to the hook payload itself — so, same as Cursor and Gemini CLI, own-lease recognition isn't available yet. Deny reasons do reach the model (`permissionDecisionReason`), and `Warn` verdicts ride the `additionalContext` field Codex adds to the model's context.
274
-
275
- ### Kimi CLI setup
276
-
277
- ```console
278
- $ portzilla init kimi
279
- ```
280
-
281
- prints the exact `~/.kimi/config.toml` snippet to add, registering `portzilla hook kimi` as a `[[hooks]]` entry on `PreToolUse` matched on `Shell`. Kimi's hooks are Beta (implementation details may change), and Kimi CLI is being [wound down in favor of Kimi Code CLI](https://github.com/MoonshotAI/kimi-cli) — re-verify this integration when adopting the successor.
282
-
283
- Kimi's `PreToolUse` contract is exit-code driven rather than JSON-response driven: `portzilla hook kimi` exits 2 (with the reason on stderr, which Kimi feeds back to the model) to deny, and prints `Warn` explanations as plain text on stdout, which Kimi adds to the model's context on allow. As with Cursor/Gemini/Codex, the session id reaches the hook payload but not the agent's own shell commands, so own-lease recognition isn't available yet.
284
-
285
- ### OpenCode setup
286
-
287
- ```console
288
- $ portzilla init opencode
289
- ```
290
-
291
- prints the full source of the `portzilla.js` plugin shim to save as `.opencode/plugin/portzilla.js` (project) or `~/.config/opencode/plugin/portzilla.js` (user), then restart OpenCode — plugins load once at startup, not hot-reloaded. Your editor needs `portzilla` on PATH. OpenCode hooks run in-process as JS/TS plugin modules, which is why this harness uses a shim instead of running `portzilla` as the hook directly.
292
-
293
- The shim hooks `tool.execute.before` for the `bash` tool, shells out to `portzilla hook opencode`, and throws with the deny reason (OpenCode surfaces it to the model as a tool error) or defers a warn to `tool.execute.after` so the model sees it on the tool result without blocking. Because the shim also adds a `shell.env` hook that injects `PORTZILLA_SESSION` into every bash subprocess, this is the only non-Claude harness where end-to-end own-lease recognition works:
294
-
295
- ```console
296
- $ portzilla claim 3000 --tag "vite dev" --session "$PORTZILLA_SESSION"
297
- ```
298
-
299
- ### Windsurf setup
300
-
301
- ```console
302
- $ portzilla init windsurf
303
- ```
304
-
305
- prints the exact `.windsurf/hooks.json` snippet to add, registering `portzilla hook windsurf` as a `pre_run_command` hook. Cascade Hooks' contract is exit-code driven: exit 2 blocks and the message on stderr reaches the agent, exit 0 allows, and Windsurf treats any other exit code as allow (fail-open). Windsurf has no non-blocking model-visible warn channel, so `Verdict::Warn` rides stderr on exit 0 — never blocks, and is visible to a human when `show_output: true` is set. `trajectory_id` reaches the hook payload but not the agent's own shell commands, so own-lease recognition isn't available yet. Note that Cascade hooks don't load at all while a workspace is open in Restricted Mode.
306
-
307
- ### Anything else: `portzilla guard`
308
-
309
- For harnesses with no hook mechanism (Aider), and for a human or a script that just wants the guard in front of a command:
310
-
311
- ```console
312
- $ portzilla guard -- kill 57107
313
- portzilla guard: blocked — Port 3000 is leased to pid 57107 (tag: "next-dev") — a live process owned by another session, not a stale one. ...
314
- $ echo $?
315
- 2
316
- ```
317
-
318
- - **Deny** — the command is not executed at all; the explanation goes to stderr and `portzilla guard` exits `2`.
319
- - **Warn** — a warning goes to stderr, then the command runs.
320
- - **Allow** — the command runs with no extra output.
321
- - `--session <S>`, or the `PORTZILLA_SESSION` environment variable if `--session` is omitted, enables own-lease recognition the same way `--session` does for `claim`.
322
- - The command after `--` is executed directly — no shell, so pipes and compounds are not interpreted by `portzilla guard` itself. On Unix this replaces the current process via `exec`, so exit codes pass straight through as if `portzilla guard` were never there (and if the command itself can't be started, `portzilla guard` exits with the same POSIX convention a shell would: `127` if it wasn't found, `126` for any other reason — not executable, permission denied, etc.). For a pipe or compound command, wrap it in `sh -c`:
323
-
324
- ```console
325
- $ portzilla guard -- sh -c 'lsof -ti:3000 | xargs kill'
326
- ```
327
-
328
- `portzilla guard` recognizes an `sh`/`bash`/`zsh`/`dash` invocation with a `-c`-family flag (combined, like `-lc`, or separate, like `-x -c` or `--norc -c`) ahead of the payload, and analyzes the raw payload directly instead of the literal `sh -c ...` text — including recursively through a nested `sh -c "sh -c '...'"`, up to 8 levels deep. This is a targeted unwrap for that specific shape, not a shell parser: it does not follow `$(...)` command substitution, variable expansion, or backslash escaping inside the payload, and only recognizes `sh`/`bash`/`zsh`/`dash` by name (not `ksh`, `fish`, `python3 -c`, PowerShell's `-Command`, etc.) — see `src/guard_cmd.rs`'s module doc comment for the complete, current list of what it does and doesn't catch.
329
-
330
- ### Fail-open, always
331
-
332
- A guard that can crash or hang and take the user's session down with it is worse than no guard. Every adapter (`hook claude-code`, `hook cursor`, `hook gemini`) and `guard` fails open at every step: unreadable stdin, malformed hook JSON, an unreadable lease store, even an internal panic — all of it is caught and turned into "allow, note it on stderr" rather than ever blocking or crashing. For the hook adapters this means the harness's own normal permission flow applies unmodified, exactly as if the hook weren't installed; a portzilla-side problem never denies a command, only the command itself looking unsafe does.
333
-
334
- ### Fail-closed mode (opt-in)
335
-
336
- Set `PORTZILLA_FAIL_CLOSED=1` to flip the tradeoff: when portzilla can't verify a command's safety (corrupt store, oversized payload, unparseable input, missing command, internal panic), the hook adapters emit their harness's deny shape with the reason going to the model, and `portzilla guard` exits 2 without running the command. Default is fail-open; this is for users who specifically prefer "block when unverified" over "let it through." The shape and channel of each deny match the harness's own conventions (Claude Code's `permissionDecisionReason`, Cursor's `agent_message`, Gemini's `reason`).
337
-
338
- ## Input validation
339
-
340
- - `claim` rejects port 0 (clap range 1..=65535); the same check exists in `Store::claim` so any other caller (MCP, direct library use) hits it too.
341
- - `tag` is capped at 1024 characters and `session` at 512; oversized values are rejected with a clear error before the store is touched.
342
- - Hook runners cap stdin at 1 MiB; over-cap inputs are treated like a malformed payload.
343
-
344
- ## Data file location
345
-
346
- `portzilla` resolves its data directory in this order:
347
-
348
- 1. `PORTZILLA_DATA_DIR` environment variable, used directly as the data directory.
349
- 2. `$XDG_DATA_HOME/portzilla`.
350
- 3. `$HOME/.local/share/portzilla`.
351
-
352
- The state lives at `<data_dir>/leases.json`, a pretty-printed JSON array of lease objects, written atomically (write to a temp file, then rename) and guarded by an exclusive file lock at `<data_dir>/leases.json.lock` for the duration of every read-modify-write operation.
198
+ ## Limitations
353
199
 
354
- Set `PORTZILLA_DATA_DIR` to isolate tests, CI runs, or throwaway experiments from your real lease store.
200
+ **PID reuse.** New leases record `process_start_time` when it can be resolved and require a verified match for both the PID and start time during liveness checks. New leases whose identity cannot be resolved are intentionally unverified/dead and can be pruned even if the numeric PID exists. Legacy leases without identity metadata retain PID-only checks. `sysinfo` reports start times at one-second resolution, so a PID recycled within the same second cannot be distinguished perfectly. Checks are point-in-time: `prune` sweeps on demand, and the optional foreground `watch` command repeats those sweeps. An active expiry daemon remains on the [roadmap](docs/ROADMAP.md). See [PRD non-goals](docs/PRD.md).
355
201
 
356
- ## Limitations
202
+ **OS occupancy.** `claim` also probes IPv4 wildcard/loopback and usable IPv6 wildcard/loopback addresses. A bound but unregistered port is skipped and reports `reassignment_reason: "os_occupied"`; socket state can change immediately after the probe, so claiming is coordination, not a reservation.
357
203
 
358
- **PID reuse.** Liveness is determined by asking the OS process table "does a process with this PID exist right now?" (via `sysinfo`). Operating systems recycle PIDs. If a leased process dies and, before that lease is pruned or released, a new unrelated process happens to be assigned the same PID, `portzilla` will report the old lease as `alive` — a false positive. This is a known tradeoff of not running a background daemon: there is no process to actively watch for exit events, only a point-in-time PID check on each query. `portzilla prune` mitigates this by letting you sweep dead leases on demand; an active daemon is on the [roadmap](docs/ROADMAP.md) to close this gap for good.
204
+ **State-file versions.** New writes use a versioned `leases.json` envelope (`format_version: 2`) so newer identity fields cannot be silently discarded. Legacy bare-array files are read and upgraded on the next write. Older binaries cannot safely read v2 files and must be upgraded before using the same data directory; unknown future versions are rejected without rewriting the file.
359
205
 
360
- `portzilla` does not manage processes (it will not start or stop a dev server for you), does not enforce a firewall or sandbox, and does not coordinate ports across machines — see [`docs/PRD.md`](docs/PRD.md) for the full list of non-goals.
206
+ `portzilla` does not start/stop servers, enforce firewall/sandbox, or coordinate across machines.
361
207
 
362
208
  ## Roadmap
363
209
 
364
- v0.1 covers `claim`, `ls`, `who`, `release`, `prune`, JSON output, and locked local state. v0.1.x adds the MCP server (`serve --mcp`, documented above) so agents can call `portzilla` natively instead of shelling out. v0.2 adds the kill guard: a harness-agnostic core plus adapters for Claude Code, Cursor, Gemini CLI, Codex CLI, Kimi CLI, OpenCode, and Windsurf, plus a universal `portzilla guard` wrapper for everything else (all documented above). See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the full versioned plan.
210
+ v0.1: `claim`/`ls`/`who`/`release`/`prune` + JSON + locked state. v0.1.x: MCP server. v0.2: kill guard + harness adapters + `portzilla guard`. The optional foreground `watch` command is implemented; an active daemon remains future work. Full plan → [`docs/ROADMAP.md`](docs/ROADMAP.md). Release procedure → [`docs/RELEASING.md`](docs/RELEASING.md).
365
211
 
366
212
  ## License
367
213
 
368
- MIT. See [`LICENSE`](LICENSE).
214
+ MIT — see [`LICENSE`](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "portzilla",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Port and process lease coordinator for parallel AI coding-agent sessions",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/011010/portzilla",