port-reclaim 0.5.0 → 0.6.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,225 @@
1
+ # Changelog
2
+
3
+ All notable changes to `port-reclaim` are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html) while treating `0.x` minor
6
+ bumps as potentially breaking for the programmatic API.
7
+
8
+ ## [0.6.0] - 2026-11-28
9
+
10
+ ### Added
11
+
12
+ - Read-only `doctor` diagnostics with socket addresses, protocol, project, uptime,
13
+ parent process, protection, and suggested next steps.
14
+ - `--check` for script preflight, including JSON output and nonzero status for
15
+ occupied, protected, unverifiable, and WSL host-side conflicts.
16
+ - `--protocol tcp|udp` and `--host IP` selection with individual socket metadata.
17
+ - Configurable `--timeout` (default 2000 ms for each shutdown/verification phase)
18
+ and Unix `--graceful-only` shutdown. Windows graceful-only explicitly refuses.
19
+ - Replacement-listener detection after termination, including parent metadata
20
+ when available; replacement processes are never automatically terminated.
21
+ - Standalone `port-reclaim.config.json`, named services, explicit `--workspace`
22
+ inheritance, an editor JSON schema, and cross-language integration recipes.
23
+ - `--confirm` to require approval even for same-directory processes.
24
+ - Policy-aware `inspectPorts()` and `reclaimPorts()` APIs with typed outcomes,
25
+ automatic config protection, optional confirmation callbacks, and injectable runners.
26
+ - Optional `doctor --docker` inspection of local container host-port mappings and
27
+ Compose labels. Docker commands are read-only; unavailable daemons produce warnings.
28
+ - Tag releases now require the full OS/Node test matrix and a matching package
29
+ version. Packed artifacts exclude compiled tests and include recipes and schema.
30
+
31
+ ### Fixed
32
+
33
+ - Explicit port reclamation now protects a PID that also owns an ignored port,
34
+ including sockets outside the selected protocol or address.
35
+ - Reclaim verifies release instead of claiming success immediately after signalling.
36
+ Unknown bind results fail safely. Windows probes include explicit loopback binds. Default
37
+ discovery treats an unsupported IPv6 family as not applicable; an explicitly selected IPv6
38
+ endpoint remains unverifiable rather than silently free.
39
+ - Process identity and protections are refreshed after confirmation across **every** requested
40
+ port, including ports that were initially free; multiple requested ports held by one PID cause
41
+ only one termination. A stable process-start identity is required and revalidated immediately
42
+ before signalling. Linux and Windows use high-resolution start identities; macOS exposes only
43
+ one-second resolution, so processes younger than two seconds are refused rather than risking a
44
+ same-second PID replacement. Low-level macOS termination requires both `expectedIdentity` and
45
+ `expectedAgeMs` from discovery.
46
+ - Configuration parsing reports malformed JSON, invalid settings, misspelled keys,
47
+ and read failures instead of silently discarding protections.
48
+ - Every non-protected requested port is re-inspected after candidate processing, including
49
+ initially free ports and declined/refused reports, so an unrelated process or Windows host
50
+ listener cannot leave a stale `free` report. Existing refusal diagnostics are preserved.
51
+ - TCP probes destroy accepted connections and have a bounded lifetime, preventing a client from
52
+ keeping `--check`, doctor, or reclaim pending indefinitely.
53
+ - Windows termination validates and kills through one retained PowerShell process handle, closing
54
+ the PID-reuse gap between identity inspection and a separate `taskkill` launch.
55
+ - Exported `parsePipeTable` and `parsePsTable` accept their legacy layouts; protocol tokens are
56
+ never interpreted as process identities.
57
+ - JSON mode emits a structured error document on operational discovery failures.
58
+ - Docker diagnostics honor `DOCKER_HOST` precedence over `DOCKER_CONTEXT`.
59
+ - OS commands have bounded execution and surface failures. Connected UDP parsing
60
+ uses the local endpoint rather than accidentally selecting the remote port.
61
+
62
+ ### Changed
63
+
64
+ - **Behavior change:** protected targets now exit 1 in reclaim mode; read-only
65
+ reports retain exit 0 unless `--check` is requested.
66
+ - **Behavior change:** malformed config and ignore entries now exit 2. Correct
67
+ previously ignored invalid entries before upgrading.
68
+ - Unix grace time is configurable instead of a fixed 250 ms. Windows terminates
69
+ only the selected PID, no longer its potentially unrelated descendants.
70
+ - Socket parser results retain separate addresses. Runner selection and shutdown
71
+ arguments are optional additions; high-level APIs enforce the shared policy.
72
+ - Same-directory matching remains a convenience, not a claim of staleness.
73
+
74
+ ## [0.5.0] - 2026-10-27
75
+
76
+ ### Added
77
+
78
+ - **WSL2 awareness.** Under WSL2's default NAT networking, a port held by a Windows process is
79
+ invisible to `lsof`/`ss` and binds cleanly inside Linux, so the port read as free while
80
+ Windows still answered `localhost`. The tool now names the Windows process instead, verified
81
+ against a real WSL2 instance. It reports only: Windows PIDs live in another namespace, so
82
+ signalling one could hit an unrelated local process. WSL's own `wslrelay` forwarder is
83
+ ignored deliberately, because it mirrors ports your WSL processes already serve.
84
+ - `--json` / `-j`: one machine-readable document per run, with a `state` per port (`free`,
85
+ `occupied`, `invisible`, `host-occupied`, `unverifiable`, `protected`) and the full process
86
+ record. Report-only, and it refuses to combine with `--yes`.
87
+ - Dependabot for npm and GitHub Actions, reviewed monthly.
88
+ - README badges for version, downloads, CI status and license.
89
+
90
+ ### Fixed
91
+
92
+ - **Process names were wrong on macOS, and on any Node 24 host running Linux.** Discovery read
93
+ the name from `ps -o comm=`, which on macOS returns the executable path truncated to 16
94
+ characters — a prompt read `'/Users/runner/ho'` where it should say `node` — and on Linux
95
+ reports the kernel *thread* name, which Node 24 renames, so every process appeared as
96
+ `MainThread`. This was not cosmetic: the Docker refusal and the always-prompt data-service list
97
+ both match on that value, so on those platforms the protections silently did nothing. Names now
98
+ come from `argv[0]` via `ps -o args=`, which reports the same thing everywhere. Wrong on macOS
99
+ since 0.1.0, and on Node 24 Linux since 0.2.0.
100
+
101
+ ### Testing
102
+
103
+ - New integration tests spawn real TCP and UDP listeners in their own process and make the
104
+ actual runner discover, terminate and re-probe them. Unit tests with a fake runner cannot
105
+ catch a wrong cmdlet name or a missing `taskkill` flag, both of which shipped previously; the
106
+ UDP case is the regression test for `Get-NetUDPConnection`.
107
+
108
+ ## [0.4.1] - 2026-10-02
109
+
110
+ ### Added
111
+
112
+ - `FORCE_COLOR=1` forces coloured output when stdout is not a terminal, for CI logs and
113
+ recorded demos. `NO_COLOR` still takes precedence.
114
+
115
+ ### Documentation
116
+
117
+ - A recorded demo GIF at the top of the README. Every frame is real tool output captured
118
+ from the CLI, not a mock-up.
119
+ - This changelog, and the contributing rules that keep the test suite and the latency budget
120
+ from silently regressing.
121
+
122
+ ## [0.4.0] - 2026-10-02
123
+
124
+ ### Added
125
+
126
+ - `--match REGEX` (`-m`) reclaims every port held by a process whose command name matches,
127
+ without naming ports. A process listening on several ports is terminated once and
128
+ reported as `Released ports 3000, 5173 from …`. The safety model is unchanged: refusals
129
+ still block, data services still prompt, a process holding any protected port is skipped,
130
+ an invalid expression exits `2`, and `--match` cannot be combined with port arguments.
131
+ - Coloured output: green for releases, red for refusals and errors, yellow for prompts,
132
+ dim for process details. Colour is disabled automatically when output is redirected, and
133
+ can be turned off with `--no-color` or the `NO_COLOR` environment variable. Styling is
134
+ ~30 lines of raw ANSI, so the package keeps a single runtime dependency.
135
+ - `ProcessRunner.discoverListening(regex)` for name-based selection, and a `ports` array on
136
+ discovered processes.
137
+ - Data services (`postgres`, `postmaster`, `mysqld`, `mariadbd`, `mongod`, `redis-server`,
138
+ `memcached`, `etcd`) are never auto-killed. Previously the working-directory check ran
139
+ before any name check, so a database started from inside the project looked exactly like a
140
+ stale dev server and was killed silently. They now always confirm; `--yes` still overrides.
141
+
142
+ ### Changed
143
+
144
+ - `--yes` is documented as never overriding a refusal, so the protection tiers are explicit.
145
+
146
+ ## [0.3.0] - 2026-10-02
147
+
148
+ ### Performance
149
+
150
+ - Discovery no longer starts one `powershell.exe` per query. On Windows a free port cost
151
+ ~1.0s and a busy port ~1.3s, because `netstat`-equivalent lookups ran three times; `netstat`
152
+ now decides whether anything is on the port and PowerShell is started at most once, for the
153
+ names of the processes actually found. On Unix, per-PID `ps` calls were batched into one.
154
+ - Measured on Windows 11: free port ~0.10s (was ~1.0s), identifying a busy port ~0.41s
155
+ (was ~1.26s), a full single-process reclaim ~0.59s. This is the first release with the
156
+ PRD's `< 2 second` goal actually verified.
157
+
158
+ ### Fixed
159
+
160
+ - **Windows UDP discovery never worked.** It called `Get-NetUDPConnection`, which is not a
161
+ cmdlet (`Get-NetUDPEndpoint` is), and `SilentlyContinue` swallowed the failure — so UDP
162
+ listeners were silently invisible on Windows.
163
+ - **Windows never showed a process uptime.** Age was computed as `UtcNow - StartTime`, but
164
+ `Get-Process StartTime` is local time, so the value was negative and got discarded.
165
+ - A port held by a process the current user cannot see — another user's or an elevated
166
+ process — was reported as free and exited `0`, so a chained `port-reclaim 3000 && next dev`
167
+ still failed. The port is now verified by briefly binding it, and an unclaimable port is
168
+ reported as such with guidance.
169
+ - Operating-system PIDs 0–4 (`System`/HTTP.sys, `systemd`) are refused rather than killed,
170
+ generalising the previous Docker-only refusal into a `refusal` reason on any discovered
171
+ process.
172
+
173
+ ### Removed
174
+
175
+ - `ProcessRunner` gained a required `probe()` method, and `PortProcess.docker` became the
176
+ more general `refusal` — both breaking for programmatic consumers. The unused
177
+ `parseWindowsPids` export was removed.
178
+
179
+ ## [0.2.1] - 2026-09-22
180
+
181
+ ### Documentation
182
+
183
+ - README gained an options table, a configuration section, a programmatic-usage section, and
184
+ a "why port-reclaim" comparison.
185
+ - Package metadata retargeted at the queries developers actually type: `kill-port`,
186
+ `port-killer`, `eaddrinuse`, `port-already-in-use`, `dev-server`.
187
+
188
+ ## [0.2.0] - 2026-09-22
189
+
190
+ ### Added
191
+
192
+ - Multiple ports in one invocation: `port-reclaim 3000 5173 8080`.
193
+ - `--list` / `-l` reports what holds a port — name, PID, working directory, uptime, protocol —
194
+ without terminating anything.
195
+ - `--yes` / `-y` (and `--force`) to terminate processes from other directories without prompting.
196
+ - Configuration so a bare `port-reclaim` works: a `port-reclaim` key in `package.json`
197
+ (`ports`, `ignore`) and a `.reclaimignore` file protecting listed ports.
198
+ - UDP listener discovery, process uptime, and Docker detection.
199
+ - A programmatic API (`port-reclaim` as a library) and generated TypeScript declarations.
200
+ - Exit codes: `0` free or released, `1` still in use or declined, `2` invalid input.
201
+
202
+ ### Fixed
203
+
204
+ - **`port-reclaim` reported success without freeing the port on Windows.** `taskkill` was
205
+ called without `/F`, which cannot end console processes such as Node dev servers, and the
206
+ command's failure was being swallowed.
207
+ - The `netstat` fallback matched ports by suffix, so querying port 3000 matched a listener on
208
+ 13000.
209
+
210
+ ## [0.1.0] - 2026-09-20
211
+
212
+ ### Added
213
+
214
+ - Initial release: identify the process holding a port and reclaim it, automatically when it
215
+ belongs to the current project and after confirmation otherwise. Cross-platform for macOS,
216
+ Linux, and Windows.
217
+
218
+ [0.6.0]: https://github.com/princegoel0/port-reclaim/compare/v0.5.0...v0.6.0
219
+ [0.5.0]: https://github.com/princegoel0/port-reclaim/compare/v0.4.1...v0.5.0
220
+ [0.4.1]: https://github.com/princegoel0/port-reclaim/compare/v0.4.0...v0.4.1
221
+ [0.4.0]: https://github.com/princegoel0/port-reclaim/compare/v0.3.0...v0.4.0
222
+ [0.3.0]: https://github.com/princegoel0/port-reclaim/compare/v0.2.1...v0.3.0
223
+ [0.2.1]: https://github.com/princegoel0/port-reclaim/compare/v0.2.0...v0.2.1
224
+ [0.2.0]: https://github.com/princegoel0/port-reclaim/compare/ba220dc...v0.2.0
225
+ [0.1.0]: https://github.com/princegoel0/port-reclaim/commit/ba220dc
package/README.md CHANGED
@@ -11,190 +11,301 @@ A zero-configuration, cross-platform CLI for safely reclaiming ports held by sta
11
11
 
12
12
  ## Why `port-reclaim`?
13
13
 
14
- Tools like [`kill-port`](https://www.npmjs.com/package/kill-port) free a port by killing whatever holds it. `port-reclaim` is built for everyday development, where the process holding port 3000 is usually *yours*:
14
+ Freeing a port is the easy half. Knowing whether you *should* is the half that bites you. `port-reclaim` is built for everyday development, where the process holding port 3000 is usually *yours*:
15
15
 
16
16
  - **Knows your project** — a process started from your current directory is reclaimed automatically; anything else asks first. No more killing the wrong `node`.
17
- - **Shows what it found** — process name, PID, working directory, and uptime. `--list` looks without touching.
17
+ - **Explains conflicts** — `doctor` shows bindings, project, parent process, and next steps without terminating anything.
18
18
  - **Never kills Docker** — ports held by `docker-proxy` or Docker Desktop are reported with a hint to stop the container instead.
19
19
  - **Multiple ports, one command** — `port-reclaim 3000 5173 8080`.
20
- - **TCP and UDP** — catches UDP listeners as well as TCP.
21
- - **Configurable** — declare ports in `package.json` or `.reclaimignore`, then plain `port-reclaim` in your `dev` script is enough.
20
+ - **TCP and UDP** — select a protocol and IP address, with IPv4 and IPv6 diagnostics.
21
+ - **Configurable** — named services, standalone JSON configuration, shared workspace protections, and `.reclaimignore`.
22
+ - **Verifies the result** — waits for release and reports replacement listeners without repeatedly killing a respawning process.
22
23
 
23
24
  ## Install
24
25
 
25
- Run it once without installing:
26
-
27
26
  ```sh
28
27
  npx port-reclaim 3000
28
+ # Or install once:
29
+ npm install --global port-reclaim
29
30
  ```
30
31
 
31
- Or install it globally:
32
+ Requires Node.js 18 or newer. Supports macOS, Linux, Windows, and WSL. Unix
33
+ systems require `lsof` and `ps`; Windows uses `netstat` and PowerShell.
34
+ Missing system commands produce an error instead of an empty discovery result.
35
+
36
+ ## Everyday use
32
37
 
33
38
  ```sh
34
- npm install --global port-reclaim
35
- port-reclaim 3000
39
+ port-reclaim 3000 5173 # reclaim selected ports
40
+ port-reclaim doctor 3000 # diagnose without terminating anything
41
+ port-reclaim 3000 --confirm # ask even for a same-directory server
42
+ port-reclaim 3000 --protocol tcp # leave an unrelated UDP owner alone
43
+ port-reclaim 3000 --host 127.0.0.1 # select a specific binding address
44
+ port-reclaim 3000 --check --json # read-only preflight for scripts
45
+ port-reclaim web api # use configured service names
36
46
  ```
37
47
 
38
- Requires Node.js 18 or newer. Supports macOS, Linux, Windows, WSL, PowerShell, and CMD.
48
+ Matching the current directory identifies a project's process; it does **not**
49
+ prove that process is stale. Use `--confirm` when an active server might be useful.
39
50
 
40
- ## How It Works
51
+ ## Safety and shutdown
41
52
 
42
- ```sh
43
- port-reclaim <PORT> [PORT ...]
44
- port-reclaim --match <REGEX>
45
- ```
53
+ A process from the current directory is reclaimed automatically. Foreign or
54
+ unreadable directories and recognized data services require confirmation.
55
+ `--confirm` also requires confirmation for your current directory. Noninteractive
56
+ commands decline when confirmation is needed; `--yes` explicitly skips prompts.
46
57
 
47
- If the port is free, the command verifies it by briefly binding the port, then exits successfully. If the port is in use but no owning process is visible to the current user, the command reports that instead of claiming success. If the process working directory matches the current project, the process is terminated automatically — except for known data services (`postgres`, `postmaster`, `mysqld`, `mariadbd`, `mongod`, `redis-server`, `memcached`, `etcd`), which always ask first even when they share your directory. Processes from another directory, system services, and processes whose working directory cannot be read require explicit confirmation. Confirmation prompts show the process name, working directory, and uptime.
58
+ Docker processes, operating-system PIDs 0–4, and the reclaimer's own PID are
59
+ refused. Ports in `ignore` or `.reclaimignore` are protected. **If a process owns
60
+ any protected port, its other ports cannot be reclaimed either**, regardless of
61
+ protocol/address selection or `--yes`. Processes are re-inspected after a prompt,
62
+ including every requested port, even one that was initially free. A stable process-start
63
+ identity is required and checked immediately before signalling, so a recycled PID is rejected
64
+ when its start identity changes. macOS exposes only one-second start resolution, so
65
+ processes younger than two seconds are refused there rather than risking a same-second
66
+ replacement. Terminating a process closes all its sockets, including ports you did not select;
67
+ confirmation shows the known affected ports.
48
68
 
49
- The command uses a graceful termination signal first on Unix-like systems and falls back to a forceful signal if the process remains alive. Windows uses `taskkill /F`.
69
+ Known data services (`postgres`, `postmaster`, `mysqld`, `mariadbd`, `mongod`,
70
+ `redis-server`, `memcached`, `etcd`) always require confirmation, unless `--yes`
71
+ is supplied. Use ignored ports for protection that `--yes` cannot override.
50
72
 
51
- If confirmation is required in a non-interactive environment, the command declines safely and exits with status `1` (rerun with `--yes` to override). `--yes` skips prompts, including the protected-service prompt, but it cannot override a refusal — list a service's port in `.reclaimignore` to make it un-killable by accident.
73
+ On Unix, shutdown sends SIGTERM and waits up to 2 seconds before using SIGKILL.
74
+ Configure that budget with `--timeout 5000`. `--graceful-only` reports failure
75
+ instead of force-killing a process that does not exit in time.
52
76
 
53
- Ports held by Docker processes (for example `docker-proxy` or Docker Desktop) are never killed. The tool explains that the port looks like Docker and suggests stopping the container instead. The same refusal applies to operating-system PIDs (0–4, such as `System`/HTTP.sys on Windows or `systemd` on Linux), which are never signalled.
77
+ Windows console processes are terminated through a retained PowerShell process handle. The
78
+ handle's start identity is revalidated before it is killed, and descendants are not targeted.
79
+ `--graceful-only` refuses on Windows; stop the server in its original terminal for graceful shutdown.
54
80
 
55
- Both TCP and UDP listeners are discovered. Discovery costs one `netstat`/`lsof` call per port, with process names and uptimes fetched in a single batched query. Measured on Windows 11: ~0.1s for a free port, ~0.4s to identify a busy one, ~0.6s for a full reclaim.
81
+ After termination, each requested port must stay bindable for a short observation
82
+ window (150 ms, capped by `--timeout`). Verification has its own timeout budget.
83
+ A newly observed PID is reported as a possible restart, with parent metadata when
84
+ available; the replacement is never automatically killed. A delayed restart can
85
+ occur after observation, and another process can claim a port after any check.
86
+ The tool does not reserve ports for the application started next.
56
87
 
57
- ### Options
88
+ ## Options
58
89
 
59
90
  | Flag | Meaning |
60
91
  | --- | --- |
61
- | `-l`, `--list` | Report what is using each port without killing anything. |
62
- | `-y`, `--yes` | Terminate processes from other directories without prompting. |
63
- | `-m`, `--match REGEX` | Reclaim every port held by a process whose name matches REGEX, instead of naming ports. |
64
- | `-j`, `--json` | Print a machine-readable report. Never terminates anything. |
65
- | `--no-color` | Disable coloured output. |
66
- | `-h`, `--help` | Show the help message. |
67
- | `-v`, `--version` | Show the installed version. |
68
-
69
- ### Reclaiming by process name
70
-
71
- When you do not know which ports are involved, select by command name instead. `--match` scans every listening socket, keeps the processes whose name matches the regular expression (case-insensitive), and reclaims every port each one holds:
92
+ | `-l`, `--list` | Read-only listener report. |
93
+ | `-j`, `--json` | Machine-readable inspection; never terminates anything. |
94
+ | `--check` | Read-only; exit 1 unless every selected port is verified free. Combines with `--json`. |
95
+ | `-y`, `--yes` | Skip prompts, but never override refusals or ignored ports. |
96
+ | `--confirm` | Ask even for same-directory processes; incompatible with `--yes`. |
97
+ | `-m`, `--match REGEX` | Select listening processes by case-insensitive command-name regex. |
98
+ | `--protocol tcp\|udp` | Select one protocol; default is both. |
99
+ | `--host IP` | Select an IPv4 or IPv6 address; default is all. Hostnames are not accepted. |
100
+ | `--timeout MS` | Shutdown and verification budgets, each 1–60000 ms; default 2000. |
101
+ | `--graceful-only` | No forceful fallback; unsupported for Windows console processes. |
102
+ | `--workspace DIR` | Explicit workspace root for shared config and protections. |
103
+ | `--docker` | With `doctor`, identify containers through an optional local Docker CLI. |
104
+ | `--no-color` | Disable ANSI colours. Also honors `NO_COLOR` and `FORCE_COLOR`. |
105
+ | `-h`, `--help` | Show usage. |
106
+ | `-v`, `--version` | Show version. |
107
+
108
+ `doctor`, `--json`, and `--check` reject `--yes`. `--list` remains read-only even
109
+ if `--yes` is supplied. Selection chooses a **process** through its sockets; it
110
+ cannot close only one socket within a process.
111
+
112
+ IPv6 socket tables do not reliably expose whether a wildcard socket also accepts
113
+ IPv4. With an explicit IPv4 `--host`, the tool avoids guessing that an IPv6-only
114
+ listener should be killed. An unresolved dual-stack conflict is reported by the
115
+ bind probe; inspect without `--host` to see all owners. An unavailable address
116
+ family or insufficient permissions may produce `unverifiable`, not `free`.
117
+ Default discovery skips IPv6 endpoints when the OS reports that IPv6 is unsupported;
118
+ an explicit IPv6 `--host` still has to be verifiable.
119
+
120
+ ## Diagnose a conflict
72
121
 
73
122
  ```sh
74
- port-reclaim --match 'next-server|vite' --list
75
- port-reclaim --match '^node$' --yes
76
- ```
77
-
78
- The same safety rules apply: refusals still block Docker and operating-system PIDs, data services still prompt, and a process holding any protected port is skipped entirely. `--match` cannot be combined with port arguments, and an invalid expression exits with status `2`.
79
-
80
- ### WSL2
81
-
82
- Under WSL2's default **NAT** networking, Linux and Windows keep separate port spaces: a port held by a Windows process is invisible to `lsof` and `ss`, and binding it inside WSL succeeds. The tool detects that case through WSL's Windows interop and names the process instead of staying silent:
83
-
84
- ```
85
- Port 4951 is free inside WSL, but a Windows tcp listener 'node.exe' (PID 19220) already holds it.
123
+ port-reclaim doctor 3000
124
+ port-reclaim doctor 3000 --docker
125
+ port-reclaim doctor 3000 --json
86
126
  ```
87
127
 
88
- It still exits `0`, because the port genuinely is free in your WSL namespace and your server will start — only `localhost` from Windows keeps reaching the other process. Reclaim it from Windows, or set `networkingMode=mirrored` in `.wslconfig` to share one space. WSL's own forwarding helper (`wslrelay`) is ignored deliberately: it mirrors ports your WSL processes already serve, so reporting it would be a false alarm. Windows processes are never killed from WSL.
128
+ Doctor reports process name, PID, uptime, working directory, known bindings,
129
+ parent PID/name, protection, and a suggested next action. Parent information can
130
+ be unavailable because of permissions or a process that has exited. A parent is
131
+ a clue, not proof that it is a supervisor. Doctor never kills a process.
89
132
 
90
- ### Machine-readable output
133
+ Docker inspection is optional and read-only. It reports the container name, ID,
134
+ Compose service/project labels when present, and an explicit `docker stop <id>`
135
+ suggestion. It checks actual **host port mappings**, including remapped ports.
136
+ It only inspects local Unix-socket or named-pipe endpoints; remote contexts are
137
+ rejected. Docker being absent or unavailable produces a diagnostic warning, not
138
+ an automatic installation or daemon startup. No container is stopped by this tool.
91
139
 
92
- `--json` reports and never terminates, which makes it safe to drop into CI:
140
+ ## Reclaim by name
93
141
 
94
142
  ```sh
95
- port-reclaim 3000 5173 --json
96
- ```
97
-
98
- ```json
99
- {"ports":[{"port":3000,"state":"occupied","processes":[{"pid":28468,"name":"node","protocol":"tcp","ageMs":4341.3,"ports":[3000],"cwd":"C:\\repo","alwaysConfirm":false}],"host":null},
100
- {"port":5173,"state":"free","processes":[],"host":null}]}
143
+ port-reclaim --match 'next-server|vite' --list
144
+ port-reclaim --match '^node$' --confirm
101
145
  ```
102
146
 
103
- Each port carries a `state`: `free`, `occupied`, `invisible` (something holds it but the owner is not visible to this user), `host-occupied` (a Windows process holds it while you are in WSL2 NAT), `unverifiable`, or `protected`. `--match` works too and echoes the pattern. `--json` cannot be combined with `--yes`, since that would ask for a report and an action at the same time.
104
-
105
- ### Colour
106
-
107
- Successes are green, refusals and errors red, prompts yellow, and process details dim. Colour switches itself off when output is redirected, can be forced off with `--no-color` or the `NO_COLOR` environment variable, and forced on with `FORCE_COLOR=1` for CI logs and recorded demos.
147
+ `--match` cannot be combined with port numbers or named services. Protection
148
+ applies to all ports owned by the process, and a process is terminated at most
149
+ once. Other processes sharing a selected port are not terminated by a name match.
150
+ Reports may include these other owners so an unresolved conflict stays visible.
108
151
 
109
152
  ## Configuration
110
153
 
111
- Ports can be declared once so scripts can run plain `port-reclaim` with no arguments. Add a `port-reclaim` key to `package.json`:
154
+ For any language, create `port-reclaim.config.json` in the current directory:
112
155
 
113
156
  ```json
114
157
  {
115
- "port-reclaim": {
116
- "ports": [3000, 5173],
117
- "ignore": [5432]
158
+ "ports": [3000, 8000],
159
+ "ignore": [5432, 6379],
160
+ "services": {
161
+ "web": [3000],
162
+ "api": [8000],
163
+ "fullstack": [3000, 8000]
118
164
  }
119
165
  }
120
166
  ```
121
167
 
122
- Ports in `ignore` are skipped with a notice. A `.reclaimignore` file in the project root protects ports the same way — one port per line, `#` starts a comment:
168
+ The same object can live under `"port-reclaim"` in `package.json`. The standalone
169
+ file is applied after the package key. A nonempty `ports` list overrides earlier
170
+ defaults; service names override earlier definitions; ignored ports accumulate.
171
+ Explicit CLI ports/services replace configured default ports. Service names must
172
+ start with a letter, contain only letters, numbers, underscores or hyphens, and
173
+ cannot be `doctor`.
174
+
175
+ `.reclaimignore` adds protected ports, one per line, with optional comments:
123
176
 
124
177
  ```text
125
- # databases
126
- 5432
127
- 6379
178
+ 5432 # shared database
179
+ 6379 # redis
128
180
  ```
129
181
 
130
- ## Script Integration
182
+ Missing files are fine. Unreadable files, malformed JSON, invalid ports, unknown
183
+ keys, and malformed service definitions stop the command with exit 2. Protection
184
+ settings are never silently discarded. An optional `$schema` string is accepted;
185
+ [port-reclaim.schema.json](port-reclaim.schema.json) is included for editor support.
131
186
 
132
- Use it in a package script:
187
+ By default only the current directory is read. From `repo/apps/web`, use:
133
188
 
134
- ```json
135
- {
136
- "scripts": {
137
- "dev": "port-reclaim 3000 && next dev"
138
- }
139
- }
189
+ ```sh
190
+ port-reclaim web --workspace ../..
140
191
  ```
141
192
 
142
- Or rely on configured ports:
193
+ This merges configuration from the explicit root through every directory down to
194
+ the current directory. Child configs cannot remove inherited ignored ports. The
195
+ current directory must be inside the root. Workspace configuration does not
196
+ expand automatic termination to other packages: the exact working-directory
197
+ check still applies.
143
198
 
144
- ```json
145
- {
146
- "scripts": {
147
- "dev": "port-reclaim && next dev"
148
- },
149
- "port-reclaim": { "ports": [3000] }
150
- }
151
- ```
199
+ ## WSL
200
+
201
+ WSL NAT has separate Linux and Windows port spaces. When Linux can bind the port
202
+ but a Windows listener holds the corresponding host port, the tool reports that
203
+ owner and never signals its PID from Linux. Normal reclaim preserves exit 0 for
204
+ this case because the Linux server can start. `--check` exits 1, helping scripts
205
+ catch the fact that Windows localhost may reach the wrong server. Host discovery
206
+ is best-effort when Windows interop is unavailable; WSL forwarding helpers are
207
+ ignored.
208
+
209
+ ## JSON and exit codes
152
210
 
153
- The same command can be used from Python, Ruby, Go, Make, or shell scripts.
211
+ ```sh
212
+ port-reclaim 3000 5173 --json
213
+ ```
154
214
 
155
- ## Exit Codes
215
+ The report contains a `ports` array. Each entry has `port`, `state`, `processes`,
216
+ and `host`. Inspection states are `free`, `occupied`, `invisible` (owner not
217
+ visible), `unverifiable`, `protected`, and `host-occupied`. Diagnostic reports may
218
+ also include `parent` on processes, plus `containers` and `warnings` on ports.
219
+ Process `sockets` retain individual addresses and protocols; `protocol` is a
220
+ legacy summary, and `ports` includes all observed ports owned by the PID.
156
221
 
157
222
  | Code | Meaning |
158
223
  | --- | --- |
159
- | `0` | The port was free (verified by binding), listed with `--list`, or successfully released. |
160
- | `1` | The port is still in use: the user declined, the owner is not visible to the current user, a protected process refused the kill, or an operation failed. |
161
- | `2` | Invalid command-line input. |
224
+ | `0` | Reclaim succeeded, or a read-only inspection completed. `--check` requires every selected state to be `free`. No name matches also succeeds. |
225
+ | `1` | Reclaim declined, refused, protected, failed, or could not verify release; a check found a conflict; or an operational command failed. |
226
+ | `2` | Invalid CLI arguments or configuration. |
162
227
 
163
- ## Programmatic Use
228
+ Plain `--json`, `--list`, and `doctor` succeed when inspection succeeds even if
229
+ ports are occupied. Use `--check` when exit status should reflect availability.
164
230
 
165
- The process runner is exported for use in other tools:
231
+ ## Script integration
166
232
 
167
- ```js
168
- import { createProcessRunner } from "port-reclaim";
169
-
170
- const runner = createProcessRunner();
171
- const found = await runner.discover(3000);
172
- for (const process of found) {
173
- console.log(process.name, process.cwd, process.ageMs, process.refusal);
174
- }
175
- if (found.length > 0 && !found[0].refusal) {
176
- await runner.terminate(found[0].pid);
177
- }
178
- if (found.length === 0 && (await runner.probe(3000)) === "occupied") {
179
- console.log("in use by a process this user cannot see");
233
+ ```json
234
+ {
235
+ "scripts": {
236
+ "dev": "port-reclaim 3000 --protocol tcp && next dev"
237
+ }
180
238
  }
181
239
  ```
182
240
 
183
- `discover()` reports what is on a port, `terminate()` ends one PID, `probe()` answers whether the port is bindable at all — `"free"`, `"occupied"`, or `"unknown"` when the OS refuses to say — and `discoverListening(regex)` works the other way, returning every listening process whose name matches along with all the ports it holds. A `refusal` reason on a discovered process means `port-reclaim` will not kill it, whatever the caller asks; `terminate()` is still available if you decide otherwise. `alwaysConfirm` marks a process the CLI will not auto-kill just because it shares your directory.
241
+ See [integration recipes](docs/recipes.md) for Python/FastAPI/Django, Go, Java,
242
+ Make, PowerShell, npm/pnpm/Yarn, monorepos, and CI.
243
+
244
+ ## Programmatic use
184
245
 
185
- ## Security Notes
246
+ ```js
247
+ import { inspectPorts, reclaimPorts } from "port-reclaim";
248
+
249
+ const reports = await inspectPorts([3000], { protocol: "tcp", doctor: true });
250
+ console.log(reports);
251
+
252
+ const result = await reclaimPorts([3000], {
253
+ protocol: "tcp",
254
+ timeoutMs: 5000,
255
+ alwaysConfirm: true,
256
+ confirm: async (owner, affectedPorts) => {
257
+ // Delegate approval to your UI; false safely declines.
258
+ console.log(owner.name, owner.cwd, affectedPorts);
259
+ return false;
260
+ }
261
+ });
262
+ if (!result.ok) console.error(result.ports);
263
+ ```
186
264
 
187
- `port-reclaim` only acts on processes listening on the port you provide. It does not scan remote hosts, and it refuses to kill Docker processes and operating-system PIDs (0–4) — stop those containers and services yourself. Known data services are never auto-killed even when their working directory matches yours, but `--yes` does override that prompt, so protect the ports that matter with `.reclaimignore`. Ports protected by `.reclaimignore` or the `ignore` config are always skipped. Review the process name and working directory before confirming a process from another project. UDP matches are heuristic: a UDP socket on a port can belong to a client as well as a server. To confirm a port is free, the tool binds it momentarily and releases it, so a connection arriving in that instant can be reported as in use.
265
+ Both functions load current-directory protection settings automatically. Options
266
+ include `cwd`, `workspace`, `ignore`, `host`, and `protocol`. Reclaim also supports
267
+ `yes`, `alwaysConfirm`, `confirm`, `timeoutMs`, `gracefulOnly`, and a `match` regex.
268
+ Additional `ignore` ports combine with file-based protections. Without a callback,
269
+ processes requiring confirmation are declined. `yes` and `alwaysConfirm` conflict.
270
+ The library never creates terminal prompts or writes logs.
271
+
272
+ Reclaim results include `ok` and per-port states, adding `released`, `declined`,
273
+ `refused`, `restarted`, and `failed` to inspection states. Invalid arguments,
274
+ configuration, and discovery errors reject the promise; termination failures are
275
+ reported per port. Parent information is best-effort; optional Docker errors are
276
+ warnings. Pass a custom `ProcessRunner` as the third argument for integration tests.
277
+
278
+ `createProcessRunner()` remains available as a **low-level** API. Its
279
+ `terminate(pid, options)` does not load config or enforce project/Docker/data-service
280
+ policies. Pass `expectedIdentity` from discovery when calling it directly; the runner
281
+ revalidates that identity before signalling and before any Unix forceful fallback. macOS requires
282
+ both `expectedIdentity` and `expectedAgeMs`; targets younger than two seconds are refused because the
283
+ available start identity has only one-second resolution. Prefer `reclaimPorts` for those guarantees. Runner discovery and probes
284
+ accept an optional `{ protocol, host }`; `parent(pid)` and `containers(port)` are
285
+ optional diagnostic methods. Types are exported with the package.
286
+
287
+ ## Upgrading from 0.5
288
+
289
+ - Invalid config and ignore entries now fail instead of being silently ignored.
290
+ - Protected targets and unverifiable binds now fail a reclaim command rather than
291
+ allowing a chained server startup to proceed.
292
+ - Successful termination is followed by release verification; shutdown on Unix
293
+ gets a configurable grace period instead of a fixed 250 ms delay.
294
+ - Windows no longer kills a target's descendants automatically.
295
+ - Socket parser results retain separate addresses. Custom runners should honor
296
+ selection arguments and provide complete `ports`/`sockets` and a stable `identity`
297
+ for each discovered process; high-level reclaim refuses targets without one.
188
298
 
189
299
  ## Development
190
300
 
191
301
  ```sh
192
- npm install
302
+ npm ci
193
303
  npm test
194
- npm run build
304
+ npm pack --dry-run
195
305
  ```
196
306
 
197
- Pull requests are tested on Ubuntu, macOS, and Windows with Node.js 18, 20, 22, and 24.
307
+ CI covers Ubuntu, macOS, and Windows on Node.js 18, 20, 22, and 24. Tag publishing
308
+ is gated by that same matrix. See [CONTRIBUTING.md](https://github.com/princegoel0/port-reclaim/blob/main/CONTRIBUTING.md) for releases.
198
309
 
199
310
  ## License
200
311