graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: reconcile orphan listener hints without expanding stop authority
yxlyx056d1e467de1
diff --git a/docs/adr/0098-orphan-listeners-are-not-stop-authority.md b/docs/adr/0098-orphan-listeners-are-not-stop-authority.mdnew file mode 100644index 00000000..9d26a1b2--- /dev/null+++ b/docs/adr/0098-orphan-listeners-are-not-stop-authority.md@@ -0,0 +1,44 @@+# 0098. Orphan listener evidence is not stop authority++Status: accepted 2026-09-10++## Context++Ownership records introduced by ADR 0062 cannot describe servers that were+started before the registry existed or whose record write failed. Inherited+environment variables and an orphaned process group can help discover those+listeners, but cannot prove that Graff may safely terminate them. Separate+IPv4 and IPv6 listeners can also use the same numeric port.++## Decision++Discover probable legacy listeners as read-only candidates. Never adopt them+into the ownership registry or signal them based on an environment marker.+Permission failures and incomplete probes remain explicit uncertainty.++For recorded jobs, stopping requires a nonzero matching process start identity+and a verified dedicated process group. Revalidate before escalation; failed+signals are not successful cleanup. PID-only compatibility for display does+not grant stop authority.++Recognizable server launches receive a bounded cross-address-family TCP port+preflight. It must never stop the incumbent. Shell syntax that cannot be+classified safely remains outside the preflight guarantee; a check is not a+socket reservation and cannot eliminate a subsequent bind race.++Silence is not proof that a browser tab is closed. Automatic idle and session+cleanup must preserve a listening job, or one whose listener state cannot be+verified, when browser visibility is unknown. Explicit user stop remains+available. This conservative rule supersedes ADR 0062's assumption that a+silent server can always be stopped. It intentionally retains some unused+servers rather than terminate one still in use; full external-browser tab+inventory is not claimed.++## Consequences++Discovery improves visibility without expanding kill authority. Unknown+browser state sacrifices automatic cleanup for safety. A future complete tab+observer can make a server eligible after its last tab closes, but an empty or+failed partial inventory must never stand in for that evidence.++Related: #817.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex f412a3c8..a624dcd3 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -107,6 +107,8 @@ record only when you need the evidence or the edge cases.| [0094](0094-subagent-interrupt-is-a-cancel-file.md) | GUI Stop writes `{id}.cancel` in the activity dir; the child finishes failed even if the model returns. Not `session/cancel`. || [0096](0096-desktop-link-destination.md) | Persist the desktop link destination outside origin-scoped storage; validate once and reveal the focused chat's Browser without navigating the app. || [0097](0097-isolate-probe-clipboards.md) | Offline PTY probes get private clipboard commands per process; direct probe runs retain OS clipboard integration. |+| [0098](0098-orphan-listeners-are-not-stop-authority.md) | Legacy listener discovery is read-only; stop authority requires verified ownership, port preflight checks both families, and unknown browser visibility protects listening jobs. |+## When to write onediff --git a/src/doctor.zig b/src/doctor.zigindex f563b122..5f30260e 100644--- a/src/doctor.zig+++ b/src/doctor.zig@@ -70,6 +70,7 @@ pub const State = struct {jobs: []const live.JobView = &.{},budget_max: u64 = 0,budget_used: u64 = 0,+ listener_findings: []const Check = &.{},};/// A goal that replaced live work legitimately starts with no checklist of its@@ -90,11 +91,11 @@ pub fn snapshot(root: *const Agent, now_ms: i64) State {};}-/// Goal/todo plus the in-process job table and RunBudget. Still no lease or-/// listener registry — those files do not exist, so they stay unreported.+/// Goal/todo, live jobs, budget, and read-only legacy listener discovery.pub fn snapshotWithLive(arena: Allocator, root: *const Agent, now_ms: i64) Allocator.Error!State {var st = snapshot(root, now_ms);st.jobs = try live.captureJobs(arena, root.io);+ st.listener_findings = try @import("server_diagnostics.zig").capture(arena, root.io);if (root.run_budget) |b| {st.budget_max = b.max_model_calls;st.budget_used = b.used();@@ -111,6 +112,7 @@ pub fn run(arena: Allocator, st: State) Allocator.Error![]const Check {if (try staleGoal(arena, st)) |c| try out.append(arena, c);if (try todoEpochAboveGoal(arena, st)) |c| try out.append(arena, c);if (try armedCompletionGate(arena, st)) |c| try out.append(arena, c);+ try out.appendSlice(arena, st.listener_findings);try live.append(arena, &out, .{.jobs = st.jobs,.budget_max = st.budget_max,diff --git a/src/exec_bash.zig b/src/exec_bash.zigindex 08e382f5..9619495a 100644--- a/src/exec_bash.zig+++ b/src/exec_bash.zig@@ -202,7 +202,37 @@ fn formatCapped(gpa: Allocator, cmd: []const u8, run: jobs.CappedRun) !ToolOutpureturn .{ .text = try aw.toOwnedSlice(), .is_error = exit_code == null or exit_code.? != 0, .cancelled = run.cancelled };}+const server_port = @import("server_port.zig");++test {+ _ = server_port;+}+pub fn exec(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {+ const cmd = strField(call.input, "command") orelse return missingArg(ctx.gpa, "command");+ // Respect the subagent gate before running even a read-only probe.+ const approved = if (ctx.from_sub) (if (ctx.approvals) |ap| ap.allowed(ctx.io, cmd) else true) else true;+ var warning = false;+ if (approved) if (server_port.requested(cmd)) |port| {+ switch (server_port.probe(ctx.gpa, ctx.io, port)) {+ .conflict => return .{+ .text = try std.fmt.allocPrint(ctx.gpa, "server launch refused: TCP port {d} already has a listener (IPv4 or IPv6). No process was stopped. Reuse the intended server or choose another port after checking ownership.", .{port}),+ .is_error = true,+ },+ .unknown => warning = true,+ .clear => {},+ }+ };+ var result = try execUnchecked(ctx, call);+ if (warning) {+ const text = try std.mem.concat(ctx.gpa, u8, &.{ server_port.unknown_warning, result.text });+ ctx.gpa.free(result.text);+ result.text = text;+ }+ return result;+}++fn execUnchecked(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {const gpa = ctx.gpa;const io = ctx.io;const input = call.input;diff --git a/src/job_browser_guard.zig b/src/job_browser_guard.zignew file mode 100644index 00000000..31930740--- /dev/null+++ b/src/job_browser_guard.zig@@ -0,0 +1,135 @@+//! Conservative automatic cleanup guard. Socket inventory is NOT browser-tab+//! inventory: even a silent listener may serve an open external browser tab.+const std = @import("std");+const builtin = @import("builtin");+const runner = @import("process_runner.zig");+const idle = @import("job_idle.zig");+pub const Probe = enum { closed, listening, unknown };+pub const retry_ms = 60 * std.time.ms_per_s;++/// Inventory the entire owned process group, not merely the shell leader.+/// Any internet socket protects the job (including UDP and connected sockets).+/// Empty/error/partial inventories are never evidence of absence.+pub fn classify(exit_ok: bool, incomplete: bool, output: []const u8, diagnostics: []const u8) Probe {+ if (!exit_ok or incomplete or diagnostics.len != 0) return .unknown;+ var process = false;+ var file = false;+ var lines = std.mem.splitScalar(u8, output, '\n');+ while (lines.next()) |line| {+ if (line.len == 0) continue;+ switch (line[0]) {+ 'p' => {+ if (process and !file) return .unknown;+ const pid = std.fmt.parseInt(u32, line[1..], 10) catch return .unknown;+ if (pid == 0) return .unknown;+ process = true;+ file = false;+ },+ 't' => {+ if (!process) return .unknown;+ if (std.mem.eql(u8, line[1..], "IPv4") or std.mem.eql(u8, line[1..], "IPv6")) return .listening;+ // Unknown file types may be sockets on an unsupported platform.+ if (!std.mem.eql(u8, line[1..], "REG") and !std.mem.eql(u8, line[1..], "DIR") and+ !std.mem.eql(u8, line[1..], "CHR") and !std.mem.eql(u8, line[1..], "FIFO") and+ !std.mem.eql(u8, line[1..], "PIPE") and !std.mem.eql(u8, line[1..], "unix") and+ !std.mem.eql(u8, line[1..], "systm")) return .unknown;+ file = true;+ },+ 'f' => {}, // lsof always includes file descriptors with field output+ else => return .unknown,+ }+ }+ return if (process and file) .closed else .unknown;+}++pub fn probe(gpa: std.mem.Allocator, io: std.Io, pid: i32) Probe {+ if (builtin.os.tag != .macos and builtin.os.tag != .linux) return .unknown;+ if (pid <= 0) return .unknown;+ var buf: [24]u8 = undefined;+ const group = std.fmt.bufPrint(&buf, "{d}", .{pid}) catch return .unknown;+ const result = runner.runCapped(gpa, io, &.{ "lsof", "-nP", "-a", "-g", group, "-Fpt" }, 256 * 1024, 4096, 1500) catch return .unknown;+ defer gpa.free(result.stdout);+ defer gpa.free(result.stderr);+ const ok = switch (result.term) {+ .exited => |code| code == 0,+ else => false,+ };+ return classify(ok, result.timed_out or result.cancelled or result.stdout_truncated or result.stderr_truncated, result.stdout, result.stderr);+}++/// Failed pipe handoff must keep the existing pump draining, not kill or+/// close the pipes. This can hold session shutdown until the job exits.+pub const ExitAction = enum { stop, detach, drain };+pub fn exitAction(result: Probe, pinned: bool, handoff_ok: bool) ExitAction {+ if (!pinned and result == .closed) return .stop;+ return if (handoff_ok) .detach else .drain;+}++pub fn touch(job: anytype, now: i64) void {+ job.last_active_ms = now;+ job.activity_revision +%= 1;+}++pub fn mayStop(result: Probe, pinned: bool, before: i64, after: i64, still_idle: bool) bool {+ return result == .closed and !pinned and before == after and still_idle;+}++/// Called with the pool locked; returns locked. The bounded subprocess runs+/// outside the mutex, then activity, pinning and shutdown are checked again.+pub fn checkIdle(pool: anytype, job: anytype, gpa: std.mem.Allocator, io: std.Io, pid: i32, now: i64) void {+ if (now < job.browser_probe_after_ms) return;+ job.browser_probe_after_ms = now + retry_ms;+ const activity = job.activity_revision;+ pool.mutex.unlock(io);+ const result = probe(gpa, io, pid);+ pool.mutex.lockUncancelable(io);+ const still_idle = idle.verdict(@intCast(@max(now - job.last_active_ms, 0)), job.idle_warned, job.pinned) == .stop;+ if (!job.kill_requested and !job.detach and !job.exit_cleanup and mayStop(result, job.pinned, activity, job.activity_revision, still_idle)) {+ job.kill_requested = true;+ job.stopped_idle = true;+ }+}++test "browser guard closed inventory allows ordinary idle jobs only" {+ try std.testing.expectEqual(Probe.closed, classify(true, false, "p12\nf1\ntREG\nf2\ntFIFO\n", ""));+ try std.testing.expect(mayStop(.closed, false, 1, 1, true));+ try std.testing.expect(!mayStop(.closed, true, 1, 1, true));+ try std.testing.expect(!mayStop(.closed, false, 1, 2, true));+ try std.testing.expect(!mayStop(.closed, false, 1, 1, false));+}++test "browser guard listeners and unknown never imply closed tabs" {+ try std.testing.expectEqual(Probe.listening, classify(true, false, "p12\nf4\ntIPv6\n", ""));+ try std.testing.expect(!mayStop(.listening, false, 1, 1, true));+ try std.testing.expect(!mayStop(.unknown, false, 1, 1, true));+}++test "browser guard failures and incomplete inventory fail closed" {+ for ([_]Probe{+ classify(false, false, "p12\ntREG\n", ""),+ classify(true, true, "p12\ntREG\n", ""),+ classify(true, false, "p12\ntREG\n", "permission denied"),+ classify(true, false, "", ""),+ classify(true, false, "p12\n", ""),+ classify(true, false, "p12\ntREG\np13\n", ""),+ classify(true, false, "p12\np13\ntREG\n", ""),+ classify(true, false, "p12\ntUNKNOWN\n", ""),+ }) |result| try std.testing.expectEqual(Probe.unknown, result);+}++test "browser guard exit handoff failure preserves draining without kill" {+ for ([_]Probe{ .listening, .unknown }) |result| {+ try std.testing.expectEqual(ExitAction.drain, exitAction(result, false, false));+ try std.testing.expectEqual(ExitAction.detach, exitAction(result, false, true));+ }+ try std.testing.expectEqual(ExitAction.drain, exitAction(.closed, true, false));+ try std.testing.expectEqual(ExitAction.detach, exitAction(.closed, true, true));+ try std.testing.expectEqual(ExitAction.stop, exitAction(.closed, false, false));+}++test "browser guard tracks same millisecond reads and pin changes" {+ var job = struct { last_active_ms: i64 = 42, activity_revision: i64 = 0 }{};+ const before = job.activity_revision;+ touch(&job, 42);+ try std.testing.expect(!mayStop(.closed, false, before, job.activity_revision, true));+}diff --git a/src/job_registry.zig b/src/job_registry.zigindex 873e5391..8294b28d 100644--- a/src/job_registry.zig+++ b/src/job_registry.zig@@ -93,6 +93,7 @@ pub const State = enum { running, gone, unverifiable };/// Is the recorded leader still the process we started? A live pid with a/// different start identity is a recycled pid: gone, and never signalled.pub fn state(io: Io, rec: Record) State {+ if (rec.pid <= 1) return .unverifiable;return stateOf(rec.start_id, proc_identity.probe(io, rec.pid));}@@ -100,7 +101,7 @@ pub fn stateOf(start_id: u64, live: proc_identity.Probe) State {return switch (live) {.gone => .gone,.unknown => .unverifiable,- .id => |v| if (start_id == 0 or v == start_id) .running else .gone,+ .id => |v| if (start_id == 0 or v == 0) .unverifiable else if (v == start_id) .running else .gone,};}@@ -147,25 +148,14 @@ pub fn parseLsofPorts(arena: Allocator, text: []const u8) []const u8 {return out.items;}-pub const StopResult = enum { stopped, gone, unverifiable, unsupported };+pub const StopResult = @import("job_registry_stop.zig").Result;/// TERM the whole group, give it 2s, then KILL — only when the leader still/// carries the recorded start identity.pub fn stopTree(io: Io, rec: Record) StopResult {if (!posix) return .unsupported;- switch (state(io, rec)) {- .gone => return .gone,- .unverifiable => return .unverifiable,- .running => {},- }- std.posix.kill(-rec.pid, .TERM) catch return .gone;- var waited: u64 = 0;- while (waited < 2000) : (waited += 100) {- io.sleep(.fromMilliseconds(100), .awake) catch break;- if (proc_identity.probe(io, rec.pid) == .gone) return .stopped;- }- std.posix.kill(-rec.pid, .KILL) catch {};- return .stopped;+ const stop = @import("job_registry_stop.zig");+ return stop.stop(rec.pid, rec.start_id, stop.Native{ .io = io });}/// Session end for a pinned job: hand each of its pipes to a detached@@ -203,10 +193,10 @@ test "parseLsofPorts: n lines only, deduped, joined" {try std.testing.expectEqualStrings("", parseLsofPorts(arena, "p1\nf2\n"));}-test "stateOf: a recycled pid is gone, an opaque one is unverifiable, legacy 0 trusts the pid" {+test "stateOf: recycled pid is gone, opaque and legacy identities are unverifiable" {try std.testing.expectEqual(State.running, stateOf(77, .{ .id = 77 }));try std.testing.expectEqual(State.gone, stateOf(77, .{ .id = 78 }));- try std.testing.expectEqual(State.running, stateOf(0, .{ .id = 78 }));+ try std.testing.expectEqual(State.unverifiable, stateOf(0, .{ .id = 78 }));try std.testing.expectEqual(State.gone, stateOf(77, .gone));try std.testing.expectEqual(State.unverifiable, stateOf(77, .unknown));}diff --git a/src/job_registry_stop.zig b/src/job_registry_stop.zignew file mode 100644index 00000000..20bd2e6b--- /dev/null+++ b/src/job_registry_stop.zig@@ -0,0 +1,120 @@+//! Fail-closed group stopping. All effects are injected for deterministic tests.+const std = @import("std");+const builtin = @import("builtin");+const identity = @import("proc_identity.zig");+pub const Result = enum { stopped, gone, unverifiable, unsupported };+pub const Signal = enum { term, kill };++/// A command string is not an executable identity (shells may exec arbitrary+/// commands). Records do not store an executable fingerprint, so start identity+/// and verified group leadership are the available ownership evidence.+pub fn stop(pid: i32, start_id: u64, ops: anytype) Result {+ if (pid <= 1 or start_id == 0) return .unverifiable;+ switch (ops.probe(pid)) {+ .gone => return .gone,+ .unknown => return .unverifiable,+ .id => |id| {+ if (id == 0) return .unverifiable;+ if (id != start_id) return .gone;+ },+ }+ if (!eligible(pid, start_id, ops)) return .unverifiable;+ ops.signal(pid, .term) catch return .unverifiable;+ for (0..20) |_| {+ ops.sleep() catch return .unverifiable;+ if (ops.groupGone(pid)) |gone| {+ if (gone) return .stopped;+ } else return .unverifiable;+ // A terminated leader can disappear before its children finish exiting.+ // Keep observing the group, but never grant another signal on that fact.+ switch (ops.probe(pid)) {+ .gone => continue,+ .unknown => return .unverifiable,+ .id => |id| if (id != start_id) return .unverifiable,+ }+ if (!eligible(pid, start_id, ops)) return .unverifiable;+ }+ // Never escalate on a stale pre-TERM identity or process group.+ if (!eligible(pid, start_id, ops)) return .unverifiable;+ ops.signal(pid, .kill) catch return .unverifiable;+ for (0..20) |_| {+ ops.sleep() catch return .unverifiable;+ if (ops.groupGone(pid)) |gone| {+ if (gone) return .stopped;+ } else return .unverifiable;+ if (!eligible(pid, start_id, ops)) return .unverifiable;+ }+ return .unverifiable;+}++fn eligible(pid: i32, start_id: u64, ops: anytype) bool {+ const own = ops.ownGroup() orelse return false;+ if (own <= 0 or own == pid) return false;+ const group = ops.group(pid) orelse return false;+ if (group != pid) return false;+ // Read identity last, immediately before allowing a signal.+ return switch (ops.probe(pid)) {+ .id => |id| id != 0 and id == start_id,+ else => false,+ };+}++pub fn noLiveMembers(text: []const u8, pid: i32) ?bool {+ var lines = std.mem.tokenizeAny(u8, text, "\r\n");+ var rows: usize = 0;+ while (lines.next()) |line| {+ var fields = std.mem.tokenizeAny(u8, line, " \t");+ const group = std.fmt.parseInt(i32, fields.next() orelse return null, 10) catch return null;+ const state = fields.next() orelse return null;+ if (fields.next() != null or state.len == 0) return null;+ rows += 1;+ if (group == pid and state[0] != 'Z') return false;+ }+ return if (rows == 0) null else true;+}++extern "c" fn getpgid(pid: c_int) c_int;++pub const Native = struct {+ io: std.Io,+ pub fn probe(self: Native, pid: i32) identity.Probe {+ return identity.probe(self.io, pid);+ }+ pub fn ownGroup(self: Native) ?i32 {+ return self.group(0);+ }+ pub fn group(_: Native, pid: i32) ?i32 {+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return null;+ const pgid = getpgid(pid);+ return if (pgid > 0) pgid else null;+ }+ pub fn signal(_: Native, pid: i32, sig: Signal) !void {+ try std.posix.kill(-pid, if (sig == .term) .TERM else .KILL);+ }+ pub fn groupGone(self: Native, pid: i32) ?bool {+ std.posix.kill(-pid, @enumFromInt(0)) catch |err| switch (err) {+ error.ProcessNotFound => return true,+ // Darwin can report EPERM for a zombie-only group. This is not+ // absence evidence: require the independent process inventory.+ error.PermissionDenied => {},+ else => return null,+ };+ // Detached children can remain zombies until the parent exits. They+ // cannot serve sockets and SIGKILL cannot remove them; don't mistake+ // an unreaped process for a live tree. Inspect without reaping a child+ // that another waiter may own.+ const gpa = std.heap.page_allocator;+ const r = @import("process_runner.zig").runCapped(gpa, self.io, &.{ "ps", "-axo", "pgid=,stat=" }, 1024 * 1024, 4096, 500) catch return null;+ defer gpa.free(r.stdout);+ defer gpa.free(r.stderr);+ if (r.timed_out or r.cancelled or r.stdout_truncated or r.stderr_truncated or r.stderr.len != 0) return null;+ switch (r.term) {+ .exited => |code| if (code != 0) return null,+ else => return null,+ }+ return noLiveMembers(r.stdout, pid);+ }+ pub fn sleep(self: Native) !void {+ try self.io.sleep(.fromMilliseconds(100), .awake);+ }+};diff --git a/src/job_registry_stop_tests.zig b/src/job_registry_stop_tests.zignew file mode 100644index 00000000..d64930c0--- /dev/null+++ b/src/job_registry_stop_tests.zig@@ -0,0 +1,100 @@+const std = @import("std");+const stop = @import("job_registry_stop.zig");+const Probe = @import("proc_identity.zig").Probe;+const Fake = struct {+ live: Probe = .{ .id = 77 },+ pgid: ?i32 = 42,+ own: ?i32 = 99,+ signals: usize = 0,+ sleeps: usize = 0,+ fail_signal: ?stop.Signal = null,+ fail_sleep: bool = false,+ gone: ?bool = false,+ group_gone_at: usize = 999,+ change_at: usize = 999,+ changed: Probe = .{ .id = 78 },+ pub fn probe(self: *Fake, _: i32) Probe {+ return if (self.sleeps >= self.change_at) self.changed else self.live;+ }+ pub fn group(self: *Fake, _: i32) ?i32 {+ return self.pgid;+ }+ pub fn ownGroup(self: *Fake) ?i32 {+ return self.own;+ }+ pub fn signal(self: *Fake, _: i32, sig: stop.Signal) !void {+ self.signals += 1;+ if (self.fail_signal == sig) return error.PermissionDenied;+ }+ pub fn groupGone(self: *Fake, _: i32) ?bool {+ return if (self.sleeps >= self.group_gone_at) true else self.gone;+ }+ pub fn sleep(self: *Fake) !void {+ if (self.fail_sleep) return error.Canceled;+ self.sleeps += 1;+ }+};++test "stopped group may contain only zombies but never live or unknown members" {+ try std.testing.expectEqual(@as(?bool, true), stop.noLiveMembers("42 Z\n43 S\n", 42));+ try std.testing.expectEqual(@as(?bool, false), stop.noLiveMembers("42 Z\n42 S+\n", 42));+ try std.testing.expectEqual(@as(?bool, null), stop.noLiveMembers(" \n", 42));+ try std.testing.expectEqual(@as(?bool, null), stop.noLiveMembers("42\n", 42));+}++test "stop rejects zero identity and unsafe pids without signals" {+ var f: Fake = .{};+ for ([_]i32{ -42, 0, 1 }) |pid| try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(pid, 77, &f));+ try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(42, 0, &f));+ try std.testing.expectEqual(@as(usize, 0), f.signals);+}+test "stop rejects mismatched unknown and zero live identities" {+ for ([_]Probe{ .{ .id = 78 }, .unknown, .{ .id = 0 } }, 0..) |live, i| {+ var f: Fake = .{ .live = live };+ try std.testing.expectEqual(if (i == 0) stop.Result.gone else stop.Result.unverifiable, stop.stop(42, 77, &f));+ try std.testing.expectEqual(@as(usize, 0), f.signals);+ }+}+test "stop rejects own group nonleader and unavailable group" {+ for ([_]?i32{ 99, null, 41 }) |group| {+ var f: Fake = .{ .pgid = group };+ try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(42, 77, &f));+ try std.testing.expectEqual(@as(usize, 0), f.signals);+ }+ var f: Fake = .{ .own = 42 };+ try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(42, 77, &f));+ try std.testing.expectEqual(@as(usize, 0), f.signals);+}+test "stop does not escalate after reuse unknown or leader exit" {+ for ([_]Probe{ .{ .id = 78 }, .unknown, .gone }) |changed| {+ var f: Fake = .{ .change_at = 20, .changed = changed };+ try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(42, 77, &f));+ try std.testing.expectEqual(@as(usize, 1), f.signals);+ }+}+test "stop waits for descendants after leader exit without another signal" {+ var f: Fake = .{ .change_at = 1, .changed = .gone, .group_gone_at = 3 };+ try std.testing.expectEqual(stop.Result.stopped, stop.stop(42, 77, &f));+ try std.testing.expectEqual(@as(usize, 1), f.signals);+ try std.testing.expectEqual(@as(usize, 3), f.sleeps);+}++test "stop reports TERM and KILL failures without success" {+ for ([_]stop.Signal{ .term, .kill }, 1..) |sig, count| {+ var f: Fake = .{ .fail_signal = sig };+ try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(42, 77, &f));+ try std.testing.expectEqual(count, f.signals);+ }+}+test "stop requires confirmed group exit and honors probe and sleep errors" {+ var success: Fake = .{ .gone = true };+ try std.testing.expectEqual(stop.Result.stopped, stop.stop(42, 77, &success));+ var unknown_group: Fake = .{ .gone = null };+ try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(42, 77, &unknown_group));+ var canceled: Fake = .{ .fail_sleep = true };+ try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(42, 77, &canceled));+ try std.testing.expectEqual(@as(usize, 1), canceled.signals);+ var survives: Fake = .{};+ try std.testing.expectEqual(stop.Result.unverifiable, stop.stop(42, 77, &survives));+ try std.testing.expectEqual(@as(usize, 2), survives.signals);+}diff --git a/src/jobs.zig b/src/jobs.zigindex 2355917c..1068174d 100644--- a/src/jobs.zig+++ b/src/jobs.zig@@ -42,9 +42,6 @@ pub fn toolRunOptions(cwd: ?[]const u8) CappedRunOptions {};}-// `graff worktree …` + the per-turn checkpoint commit live in worktree_cmd.zig-// (moved out when the pool grew its idle lifecycle, #199); callers still reach-// them through jobs.const worktree_cmd = @import("worktree_cmd.zig");pub const worktreeAutoCommit = worktree_cmd.worktreeAutoCommit;pub const worktreeCommand = worktree_cmd.worktreeCommand;@@ -69,6 +66,10 @@ const Job = struct { // session-global; pump drains pipes; survives Esccwd: ?[]u8 = null, // owned copy: /jobs restart reruns in the same placestarted_ms: i64 = 0, // unix ms, for age columns and the recordlast_active_ms: i64 = 0, // awake ms: last output byte, read, wait tick, or pin+ browser_probe_after_ms: i64 = 0,+ activity_revision: i64 = 0,+ group_pid: i32 = 0,+ exit_cleanup: bool = false,pinned: bool = false, // /jobs keep: no idle stop, retained at session endidle_warned: bool = false,stopped_idle: bool = false, // the idle policy killed it, not bash_kill@@ -90,6 +91,7 @@ const Job = struct { // session-global; pump drains pipes; survives Escpub const job_unread_cap = 256 * 1024;const job_wait = @import("job_wait.zig");const job_notify = @import("job_notify.zig");+const browser_guard = @import("job_browser_guard.zig");const job_idle = @import("job_idle.zig"); // #199const job_registry = @import("job_registry.zig"); // #199const proc_identity = @import("proc_identity.zig");@@ -124,7 +126,7 @@ fn jobDrain(job: *Job, gpa: Allocator, readers: []const *Io.Reader, now_ms: i64)for (readers, 0..) |r, i| {const b = r.buffered();if (b.len == 0) continue;- job.last_active_ms = now_ms; // output is activity (#199)+ browser_guard.touch(job, now_ms); // output is activity (#199)if (job.stream) |emit| emit(job.stream_ctx, @intCast(i), b);job.buf.appendSlice(gpa, b) catch {};r.toss(b.len);@@ -161,17 +163,14 @@ fn jobPump(job: *Job, gpa: Allocator, io: Io) void {// #199: silence is the idle clock — no bytes, no read, no pin.const idle_ms: u64 = @intCast(@max(now - job.last_active_ms, 0));var warn = false;- if (!job.kill_requested and !job.detach) {+ if (!job.kill_requested and !job.detach and !job.exit_cleanup) {switch (job_idle.verdict(idle_ms, job.idle_warned, job.pinned)) {.none => {},.warn => {job.idle_warned = true;warn = true;},- .stop => {- job.kill_requested = true;- job.stopped_idle = true;- },+ .stop => browser_guard.checkIdle(&g_jobs, job, gpa, io, pid, now),}}killed = job.kill_requested;@@ -254,7 +253,7 @@ pub fn setPinned(io: Io, id: u32, pinned: bool) ?bool {const job = g_jobs.find(id) orelse return null;if (job.done) return false;job.pinned = pinned;- job.last_active_ms = nowMs(io);+ browser_guard.touch(job, nowMs(io));if (comptime posix_groups) job_registry.write(io, job_registry.home, recordOf(io, job));return true;}@@ -275,8 +274,7 @@ pub fn restartJob(gpa: Allocator, io: Io, id: u32) !*Job {return spawnJobOpts(gpa, io, cmd, .{ .cwd = cwd });}-/// Session end for a pinned job (#199): hand its pipes to a detached drainer-/// and keep its record, instead of killing it. False = kill it after all.+/// Hand retained pipes to a detached drainer; failure never authorizes a kill.fn retainAtExit(io: Io, job: *Job) bool {if (comptime !posix_groups) return false;const rec = recordOf(io, job);@@ -328,6 +326,7 @@ pub fn spawnJobOpts(gpa: Allocator, io: Io, cmd: []const u8, opts: SpawnOpts) !*.id = 0,.cmd = cmd_copy,.child = child,+ .group_pid = if (comptime posix_groups) (child.id orelse 0) else 0,.stream = opts.stream,.stream_ctx = opts.stream_ctx,.quiet = opts.quiet,@@ -385,7 +384,7 @@ pub fn jobOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {g_jobs.mutex.unlock(io);return .{ .text = try std.fmt.allocPrint(gpa, "no background job {d} — it may never have started; /jobs lists them", .{id}), .is_error = true };};- job.last_active_ms = nowMs(io); // a read or a blocking wait is activity (#199)+ browser_guard.touch(job, nowMs(io)); // a read or a blocking wait is activity (#199)const deadline = job_wait.resolveDeadlineFor(wait_ms, job.persistent);unread = job.buf.items.len - job.cursor;const fresh = job.buf.items[job.cursor..];@@ -519,7 +518,7 @@ pub fn waitForeground(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !FgWait {g_jobs.mutex.unlock(io);return error.NoSuchJob;};- job.last_active_ms = nowMs(io); // the foreground wait is activity (#199)+ browser_guard.touch(job, nowMs(io)); // the foreground wait is activity (#199)if (job.done) {const pair = takeUnread(gpa, job) catch {g_jobs.mutex.unlock(io);@@ -573,12 +572,19 @@ pub fn jobsReap(gpa: Allocator, io: Io) void {g_jobs.mutex.unlock(io);return;};+ for (jobs) |job| job.exit_cleanup = true;+ g_jobs.mutex.unlock(io);for (jobs) |job| {- // #199: a pinned, still-running job is kept, not killed — its pipes- // go to a detached drainer, its record stays for `graff servers`.- if (job.pinned and !job.done and retainAtExit(io, job)) job.detach = true else job.kill_requested = true;+ const result = browser_guard.probe(gpa, io, job.group_pid);+ g_jobs.mutex.lockUncancelable(io);+ if (!job.done and !job.kill_requested) {+ if (browser_guard.exitAction(result, job.pinned, false) != .stop) {+ job.detach = browser_guard.exitAction(result, job.pinned, retainAtExit(io, job)) == .detach;+ if (!job.detach) std.debug.print("retained job pipe handoff failed; cleanup waits while the pump keeps draining (no kill)\n", .{});+ } else job.kill_requested = true;+ }+ g_jobs.mutex.unlock(io);}- g_jobs.mutex.unlock(io);for (jobs) |job| freeJob(gpa, io, job);gpa.free(jobs);// toOwnedSlice already emptied the pool; deinit would poison reuse.@@ -587,6 +593,6 @@ pub fn jobsReap(gpa: Allocator, io: Io) void {test { // split-out modules: unreferenced, their tests silently never run_ = worktree_cmd;_ = @import("worktree_lease.zig");- _ = .{ job_wait, job_notify, job_idle, job_registry };+ _ = .{ job_wait, job_notify, job_idle, job_registry, browser_guard };_ = @import("jobs_tests.zig");}diff --git a/src/main.zig b/src/main.zigindex a7922d51..f9cb6146 100644--- a/src/main.zig+++ b/src/main.zig@@ -54,7 +54,7 @@ test { // unit_tests' root is main.zig only, so reference every split-out module_ = models_cache;_ = ansi;_ = serve;- _ = .{ @import("json_inbox.zig"), @import("acp_inbox.zig"), @import("cite_markup.zig") };+ _ = .{ @import("json_inbox.zig"), @import("acp_inbox.zig"), @import("cite_markup.zig"), @import("server_diagnostics.zig"), @import("server_discovery.zig"), @import("job_browser_guard.zig"), @import("server_port.zig"), @import("job_registry_stop_tests.zig") };_ = util;_ = learn_store;_ = learn_eval;diff --git a/src/server_diagnostics.zig b/src/server_diagnostics.zignew file mode 100644index 00000000..fa7805fc--- /dev/null+++ b/src/server_diagnostics.zig@@ -0,0 +1,62 @@+//! Read-only adapters for legacy listener discovery; never grants stop authority.+const std = @import("std");+const discovery = @import("server_discovery.zig");+const doctor = @import("doctor.zig");+const A = std.mem.Allocator;++pub fn findings(arena: A, result: discovery.Result) A.Error![]const doctor.Check {+ var out: std.ArrayList(doctor.Check) = .empty;+ if (result.incomplete) try out.append(arena, .{+ .id = "LISTENER_PROBE_UNAVAILABLE",+ .severity = .warn,+ .title = "listener discovery incomplete",+ .detail = "A bounded process or socket probe could not complete. Missing evidence does not mean no orphan listeners exist; no processes were stopped.",+ });+ for (result.candidates) |candidate| try out.append(arena, .{+ .id = "ORPHANED_LISTENER_CANDIDATE",+ .severity = .warn,+ .title = "possible pre-registry listener",+ .detail = try std.fmt.allocPrint(arena, "Orphan group {d}, listener {d}: inherited Graff marker is only a hint, not ownership or stop authority. Inspect with graff servers; no process was adopted or stopped.", .{ candidate.pid, candidate.listener }),+ });+ return out.toOwnedSlice(arena);+}++pub fn capture(arena: A, io: std.Io) A.Error![]const doctor.Check {+ var result = discovery.scan(arena, io, arena) catch discovery.Result{ .incomplete = true };+ const registry = @import("job_registry.zig");+ const records = registry.list(io, arena, registry.home);+ var suspects: std.ArrayList(discovery.Candidate) = .empty;+ for (result.candidates) |candidate| {+ var recorded = false;+ for (records) |record| {+ if (record.pid == candidate.pid and registry.state(io, record) == .running) recorded = true;+ }+ if (!recorded) try suspects.append(arena, candidate);+ }+ result.candidates = suspects.items;+ return findings(arena, result);+}++pub fn warnStartup(arena: A, io: std.Io) void {+ const checks = capture(arena, io) catch return;+ var buf: [4096]u8 = undefined;+ var writer = std.Io.File.stderr().writer(io, &buf);+ for (checks) |check| writer.interface.print("warning: {s}: {s}\n", .{ check.title, check.detail }) catch return;+ writer.interface.flush() catch {};+}++test "orphan diagnostics preserve uncertainty without stop authority" {+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);+ defer arena.deinit();+ const checks = try findings(arena.allocator(), .{ .incomplete = true, .candidates = &.{.{ .pid = 42, .listener = 43 }} });+ try std.testing.expectEqual(@as(usize, 2), checks.len);+ try std.testing.expectEqualStrings("LISTENER_PROBE_UNAVAILABLE", checks[0].id);+ try std.testing.expectEqualStrings("ORPHANED_LISTENER_CANDIDATE", checks[1].id);+ try std.testing.expect(std.mem.indexOf(u8, checks[1].detail, "not ownership or stop authority") != null);+}++test "empty complete orphan scan makes no finding" {+ const checks = try findings(std.testing.allocator, .{});+ defer std.testing.allocator.free(checks);+ try std.testing.expectEqual(@as(usize, 0), checks.len);+}diff --git a/src/server_discovery.zig b/src/server_discovery.zignew file mode 100644index 00000000..a0611cd0--- /dev/null+++ b/src/server_discovery.zig@@ -0,0 +1,144 @@+//! Untrusted orphan hints, never ownership. No adoption or signalling API.+const std = @import("std");+const builtin = @import("builtin");+const runner = @import("process_runner.zig");+const A = std.mem.Allocator;+pub const Candidate = struct { pid: i32, listener: i32 };+pub const Result = struct { candidates: []const Candidate = &.{}, incomplete: bool = false };+pub const Process = struct { pid: i32, ppid: i32, pgid: i32, uid: u32 };++pub fn parseProcess(line: []const u8) ?Process {+ var it = std.mem.tokenizeAny(u8, line, " \t\r");+ const pid = std.fmt.parseInt(i32, it.next() orelse return null, 10) catch return null;+ const ppid = std.fmt.parseInt(i32, it.next() orelse return null, 10) catch return null;+ const pgid = std.fmt.parseInt(i32, it.next() orelse return null, 10) catch return null;+ const uid = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null;+ if (it.next() != null or pid <= 1 or ppid < 0 or pgid <= 1) return null;+ return .{ .pid = pid, .ppid = ppid, .pgid = pgid, .uid = uid };+}++pub fn marker(text: []const u8) bool {+ var it = std.mem.tokenizeAny(u8, text, " \t\r\n\x00");+ while (it.next()) |word| {+ // Environment is spoofable (and ps may include argv). This is a hint ONLY.+ if (!std.mem.startsWith(u8, word, "GRAFF_")) continue;+ const eq = std.mem.indexOfScalar(u8, word, '=') orelse continue;+ if (eq > 6 and eq + 1 < word.len) return true;+ }+ return false;+}++fn lookup(procs: []const Process, pid: i32) ?Process {+ for (procs) |p| if (p.pid == pid) return p;+ return null;+}++pub fn orphanLeader(procs: []const Process, listener: i32, uid: u32) ?Process {+ const p = lookup(procs, listener) orelse return null;+ const leader = lookup(procs, p.pgid) orelse return null;+ if (p.uid != uid or leader.uid != uid or leader.pid != leader.pgid or leader.ppid != 1) return null;+ return leader;+}++pub fn descendant(procs: []const Process, child: Process, leader: Process) bool {+ var p = child;+ for (0..procs.len) |_| {+ if (p.uid != leader.uid or p.pgid != leader.pid) return false;+ if (p.pid == leader.pid) return true;+ p = lookup(procs, p.ppid) orelse return false;+ }+ return false;+}++fn capture(gpa: A, io: std.Io, arena: A, argv: []const []const u8, empty_ok: bool) ![]const u8 {+ const r = try runner.runCapped(gpa, io, argv, 1024 * 1024, 4096, 500);+ defer gpa.free(r.stdout);+ defer gpa.free(r.stderr);+ if (r.timed_out or r.stdout_truncated or r.stderr_truncated or r.cancelled) return error.DiscoveryIncomplete;+ switch (r.term) {+ .exited => |code| if (code != 0 and !(empty_ok and code == 1 and r.stdout.len == 0 and r.stderr.len == 0)) return error.DiscoveryCommandFailed,+ else => return error.DiscoveryCommandFailed,+ }+ if (r.stderr.len != 0) return error.DiscoveryCommandFailed;+ return try arena.dupe(u8, r.stdout);+}++/// At most 35 short subprocesses, capped output, at most 4096 processes and+/// 32 environment inspections. Failures/limits remain visible, not healthy.+pub fn scan(gpa: A, io: std.Io, arena: A) !Result {+ if (builtin.os.tag != .linux and builtin.os.tag != .macos) return error.DiscoveryUnsupported;+ const uid_text = try capture(gpa, io, arena, &.{ "id", "-u" }, false);+ const uid = std.fmt.parseInt(u32, std.mem.trim(u8, uid_text, " \r\n"), 10) catch return error.DiscoveryMalformed;+ const table = try capture(gpa, io, arena, &.{ "ps", "-axo", "pid=,ppid=,pgid=,uid=" }, false);+ var procs: std.array_list.Managed(Process) = .init(arena);+ var lines = std.mem.splitScalar(u8, table, '\n');+ while (lines.next()) |line| {+ if (procs.items.len >= 4096) return error.DiscoveryLimit;+ if (parseProcess(line)) |p| try procs.append(p);+ }+ if (procs.items.len == 0) return error.DiscoveryMalformed;+ var ubuf: [16]u8 = undefined;+ const uid_s = try std.fmt.bufPrint(&ubuf, "{d}", .{uid});+ const sockets = try capture(gpa, io, arena, &.{ "lsof", "-a", "-nP", "-u", uid_s, "-iTCP", "-sTCP:LISTEN", "-Fp" }, true);+ var result: Result = .{};+ var candidates: std.array_list.Managed(Candidate) = .init(arena);+ var checked: std.array_list.Managed(i32) = .init(arena);+ var inspections: usize = 0;+ lines = std.mem.splitScalar(u8, sockets, '\n');+ while (lines.next()) |line| {+ if (line.len == 0 or line[0] != 'p') continue;+ const listener = std.fmt.parseInt(i32, line[1..], 10) catch return error.DiscoveryMalformed;+ const leader = orphanLeader(procs.items, listener, uid) orelse continue;+ if (std.mem.indexOfScalar(i32, checked.items, leader.pid) != null) continue;+ try checked.append(leader.pid);+ for (procs.items) |p| {+ if (!descendant(procs.items, p, leader)) continue;+ if (inspections >= 32) {+ result.incomplete = true;+ break;+ }+ inspections += 1;+ var pbuf: [16]u8 = undefined;+ const pid_s = try std.fmt.bufPrint(&pbuf, "{d}", .{p.pid});+ const env = capture(gpa, io, arena, &.{ "ps", "eww", "-p", pid_s, "-o", "command=" }, false) catch {+ result.incomplete = true;+ continue;+ };+ if (marker(env)) {+ try candidates.append(.{ .pid = leader.pid, .listener = listener });+ break;+ }+ }+ }+ result.candidates = candidates.items;+ return result;+}++test "discovery process parser rejects malformed and unsafe IDs" {+ try std.testing.expectEqual(@as(i32, 20), parseProcess("20 1 20 501").?.pid);+ try std.testing.expect(parseProcess("20 1 20 nope") == null);+ try std.testing.expect(parseProcess("1 0 1 501") == null);+ try std.testing.expect(parseProcess("20 1 20 501 extra") == null);+}++test "discovery markers are token bounded and nonempty hints" {+ try std.testing.expect(marker("node GRAFF_SESSION=x"));+ try std.testing.expect(marker("X=a\x00GRAFF_JOB_ID=2\x00"));+ try std.testing.expect(!marker("NOT_GRAFF_SESSION=x GRAFF_SESSION="));+}++test "discovery requires same-user orphan group leader and descendant chain" {+ const procs = [_]Process{+ .{ .pid = 20, .ppid = 1, .pgid = 20, .uid = 501 },+ .{ .pid = 21, .ppid = 20, .pgid = 20, .uid = 501 },+ .{ .pid = 22, .ppid = 21, .pgid = 20, .uid = 501 },+ .{ .pid = 23, .ppid = 1, .pgid = 20, .uid = 502 },+ .{ .pid = 24, .ppid = 24, .pgid = 20, .uid = 501 },+ };+ try std.testing.expect(orphanLeader(&procs, 22, 501) != null);+ try std.testing.expect(orphanLeader(&procs, 23, 501) == null);+ try std.testing.expect(orphanLeader(&procs, 22, 502) == null);+ try std.testing.expect(descendant(&procs, procs[2], procs[0]));+ try std.testing.expect(!descendant(&procs, procs[3], procs[0]));+ try std.testing.expect(!descendant(&procs, procs[4], procs[0]));+}diff --git a/src/server_port.zig b/src/server_port.zignew file mode 100644index 00000000..8da07e42--- /dev/null+++ b/src/server_port.zig@@ -0,0 +1,189 @@+//! Conservative, best-effort preflight. This is not a bind reservation.+const std = @import("std");+const jobs = @import("jobs.zig");++fn eq(a: []const u8, b: []const u8) bool {+ return std.mem.eql(u8, a, b);+}++fn numeric(s: []const u8) ?u16 {+ if (s.len == 0) return null;+ for (s) |c| if (c < '0' or c > '9') return null;+ const p = std.fmt.parseInt(u16, s, 10) catch return null;+ return if (p == 0) null else p;+}++// Quotes remain opaque: text containing flags is never interpreted as flags.+// Complex shell syntax is deliberately unsupported rather than guessed.+fn tokens(cmd: []const u8, out: *[128][]const u8) ?usize {+ var i: usize = 0;+ var n: usize = 0;+ while (i < cmd.len) {+ while (i < cmd.len and std.ascii.isWhitespace(cmd[i])) : (i += 1) {+ if (cmd[i] == '\n' or cmd[i] == '\r') return null;+ }+ if (i == cmd.len) break;+ if (n == out.len) return null;+ const start = i;+ var quote: u8 = 0;+ while (i < cmd.len) : (i += 1) {+ const c = cmd[i];+ if (quote != 0) {+ if (c == quote) quote = 0;+ continue;+ }+ if (c == '\'' or c == '"') {+ quote = c;+ } else if (std.ascii.isWhitespace(c)) break else if (std.mem.indexOfScalar(u8, "\\$`;|<>()#", c) != null) return null;+ }+ if (quote != 0) return null;+ out[n] = cmd[start..i];+ n += 1;+ }+ return n;+}++fn known(t: []const []const u8) ?usize {+ if (t.len == 0) return null;+ const base = std.fs.path.basename(t[0]);+ if (eq(base, "next")) {+ if (t.len > 1 and (eq(t[1], "dev") or eq(t[1], "start"))) return 2;+ return null;+ }+ if (eq(base, "vite") or eq(base, "uvicorn") or eq(base, "http-server")) return 1;+ if (eq(base, "npm") or eq(base, "pnpm") or eq(base, "yarn") or eq(base, "bun")) {+ var i: usize = 1;+ if (i < t.len and eq(t[i], "run")) i += 1;+ if (i < t.len and (eq(t[i], "dev") or eq(t[i], "start") or eq(t[i], "serve"))) return i + 1;+ }+ if (eq(base, "npx") and t.len > 1) {+ // Do not recursively accept arbitrary package-manager invocations.+ if (eq(t[1], "next") or eq(t[1], "vite") or eq(t[1], "http-server")) {+ if (known(t[1..])) |n| return n + 1;+ }+ }+ return null;+}++/// Returns only an explicit numeric request in a recognized server launch.+/// cd DIR && launch is supported; pipelines, substitutions and scripts are not.+pub fn requested(cmd: []const u8) ?u16 {+ var buf: [128][]const u8 = undefined;+ const count = tokens(cmd, &buf) orelse return null;+ var t = buf[0..count];+ if (t.len >= 3 and eq(t[0], "cd") and eq(t[2], "&&")) t = t[3..];+ for (t) |word| if (std.mem.indexOfScalar(u8, word, '&') != null) return null;+ var port: ?u16 = null;+ while (t.len > 0 and std.mem.indexOfScalar(u8, t[0], '=') != null) {+ const split = std.mem.indexOfScalar(u8, t[0], '=').?;+ if (split == 0) return null;+ for (t[0][0..split], 0..) |c, i| {+ if (!(std.ascii.isAlphabetic(c) or c == '_' or (i > 0 and std.ascii.isDigit(c)))) return null;+ }+ if (eq(t[0][0..split], "PORT")) port = numeric(t[0][split + 1 ..]) orelse return null;+ t = t[1..];+ }+ var i = known(t) orelse return null;+ while (i < t.len) : (i += 1) {+ const word = t[i];+ if (eq(word, "--port") or eq(word, "-p")) {+ i += 1;+ if (i == t.len) return null;+ port = numeric(t[i]) orelse return null;+ } else if (std.mem.startsWith(u8, word, "--port=")) {+ port = numeric(word[7..]) orelse return null;+ }+ }+ return port;+}++pub const Status = enum { clear, conflict, unknown };++/// lsof -Fn yields nADDRESS:PORT for both IPv4 and IPv6. Match numeric+/// ports, never address families, substrings, process names or PID ownership.+pub fn listenerStatus(output: []const u8, port: u16) Status {+ var lines = std.mem.tokenizeAny(u8, output, "\r\n");+ var malformed = false;+ while (lines.next()) |line| {+ if (line[0] != 'n') continue;+ const colon = std.mem.lastIndexOfScalar(u8, line, ':') orelse {+ malformed = true;+ continue;+ };+ const p = numeric(line[colon + 1 ..]) orelse {+ malformed = true;+ continue;+ };+ if (p == port) return .conflict;+ }+ return if (malformed) .unknown else .clear;+}++pub fn probe(gpa: std.mem.Allocator, io: std.Io, port: u16) Status {+ // No -i4/-i6: inspect ALL TCP listeners. Bound both runtime and output.+ const run = jobs.runCappedWithOptions(gpa, io, &.{ "lsof", "-nP", "-iTCP", "-sTCP:LISTEN", "-Fn" }, 256 * 1024, 4096, 2000, .{}) catch return .unknown;+ defer gpa.free(run.stdout);+ defer gpa.free(run.stderr);+ const parsed = listenerStatus(run.stdout, port);+ if (parsed == .conflict) return .conflict;+ if (run.timed_out or run.cancelled or run.stdout_truncated or run.stderr_truncated or run.stderr.len != 0) return .unknown;+ switch (run.term) {+ .exited => |code| {+ if (code != 0 and !(code == 1 and run.stdout.len == 0)) return .unknown;+ },+ else => return .unknown,+ }+ return parsed;+}++pub const unknown_warning = "[warning: server port preflight unavailable or incomplete; port availability is unknown. Launching without verified collision protection; no existing listener was stopped.]\n";++test "server port: conservative command table" {+ const Case = struct { cmd: []const u8, port: ?u16 };+ for ([_]Case{+ .{ .cmd = "next dev --port 3000", .port = 3000 },+ .{ .cmd = "npx next start --port=3001", .port = 3001 },+ .{ .cmd = "npm run dev -- -p 3002", .port = 3002 },+ .{ .cmd = "PORT=3003 pnpm dev", .port = 3003 },+ .{ .cmd = "cd 'my project' && PORT=3004 yarn start", .port = 3004 },+ .{ .cmd = "vite --host ::1 --port=3000", .port = 3000 },+ .{ .cmd = "uvicorn app:app --port 8000", .port = 8000 },+ .{ .cmd = "git -p log", .port = null },+ .{ .cmd = "curl -p 3000 localhost", .port = null },+ .{ .cmd = "arbitrary --port 3000", .port = null },+ .{ .cmd = "PORT=3000 echo hello", .port = null },+ .{ .cmd = "echo 'next dev --port 3000'", .port = null },+ .{ .cmd = "next dev '--port 3000'", .port = null },+ .{ .cmd = "next dev --port $PORT", .port = null },+ .{ .cmd = "next dev --port 65536", .port = null },+ .{ .cmd = "next dev --port 0", .port = null },+ .{ .cmd = "next dev --port 3000 | cat", .port = null },+ .{ .cmd = "next dev --port 3000; echo done", .port = null },+ .{ .cmd = "next dev --port 3000\necho done", .port = null },+ .{ .cmd = "next dev --port '3000'", .port = null },+ .{ .cmd = "npm install --port 3000", .port = null },+ .{ .cmd = "next dev # --port 3000", .port = null },+ }) |c| try std.testing.expectEqual(c.port, requested(c.cmd));+}++test "server port: all listener families and exact numeric ports" {+ try std.testing.expectEqual(Status.conflict, listenerStatus("p123\nf5\nn127.0.0.1:3000\n", 3000));+ try std.testing.expectEqual(Status.conflict, listenerStatus("p456\nf6\nn[::1]:3000\n", 3000));+ try std.testing.expectEqual(Status.conflict, listenerStatus("n*:3000\n", 3000));+ try std.testing.expectEqual(Status.clear, listenerStatus("n[::1]:13000\nn127.0.0.1:3001\n", 3000));+ try std.testing.expectEqual(Status.clear, listenerStatus("", 3000));+ try std.testing.expectEqual(Status.unknown, listenerStatus("nlocalhost:http\n", 3000));+}++test "server port: loopback listener preflight does not stop listener" {+ const io = std.testing.io;+ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ var server = try std.Io.net.IpAddress.listen(&addr, io, .{});+ defer server.deinit(io);+ const status = probe(std.testing.allocator, io, server.socket.address.getPort());+ if (status == .unknown) return error.SkipZigTest; // lsof is optional+ try std.testing.expectEqual(Status.conflict, status);+ var target = server.socket.address;+ const stream = try std.Io.net.IpAddress.connect(&target, io, .{ .mode = .stream });+ defer stream.close(io);+}diff --git a/src/servers_cmd.zig b/src/servers_cmd.zigindex 4670f1ff..ef78f797 100644--- a/src/servers_cmd.zig+++ b/src/servers_cmd.zig@@ -10,6 +10,7 @@ const Allocator = std.mem.Allocator;const job_registry = @import("job_registry.zig");const tool_pulse = @import("tool_pulse.zig");const util = @import("util.zig");+const discovery = @import("server_discovery.zig");pub fn command(gpa: Allocator, io: Io, arena: Allocator, args: []const []const u8) !void {var buf: [4096]u8 = undefined;@@ -17,12 +18,12 @@ pub fn command(gpa: Allocator, io: Io, arena: Allocator, args: []const []const uconst out = &w.interface;defer out.flush() catch {};const home = job_registry.home;- if (home.len == 0) return out.writeAll("graff servers: no HOME, so no job records\n");+ if (home.len == 0) try out.writeAll("graff servers: no HOME, so no job records (discovery still available)\n");const action = if (args.len > 0) args[0] else "list";- const recs = job_registry.list(io, arena, home);+ const recs = if (home.len == 0) &.{} else job_registry.list(io, arena, home);if (std.mem.eql(u8, action, "list") or std.mem.eql(u8, action, "ls")) {- if (recs.len == 0) return out.writeAll("no background servers on record — graff writes one per background job it starts (~/.codegraff/jobs)\n");+ if (recs.len == 0) try out.writeAll("no background servers on record — checking suspected orphan listeners\n");const now = util.unixMs(io);try out.writeAll("pid state age owner port(s) command\n");for (recs) |rec| {@@ -40,7 +41,20 @@ pub fn command(gpa: Allocator, io: Io, arena: Allocator, args: []const []const uif (rec.cwd.len > 0) try out.print(" ({s})", .{rec.cwd});try out.writeAll("\n");}- return out.writeAll("graff servers stop <pid> ends one (its whole process group); graff servers prune drops records of dead ones\n");+ const found = discovery.scan(gpa, io, arena) catch |err| {+ try out.print("orphan discovery unavailable/incomplete: {s}; listener status is unknown\n", .{@errorName(err)});+ return;+ };+ for (found.candidates) |candidate| {+ var recorded = false;+ for (recs) |rec| {+ if (rec.pid == candidate.pid and job_registry.state(io, rec) == .running) recorded = true;+ }+ if (!recorded) try out.print("{d:<8} suspected orphan listener (listener pid {d}); report-only, ownership unverified\n", .{ candidate.pid, candidate.listener });+ }+ if (found.incomplete) try out.writeAll("orphan discovery incomplete: inspection limit or process query failed; listener status is unknown\n");+ try out.writeAll("Suspects are never adopted or stopped: environment hints cannot prove ownership or revalidate start/executable/group identity.\n");+ return out.writeAll("graff servers stop <pid> ends a verified recorded job only; graff servers prune drops dead records\n");}if (std.mem.eql(u8, action, "stop")) {@@ -62,7 +76,7 @@ pub fn command(gpa: Allocator, io: Io, arena: Allocator, args: []const []const u}return;}- return out.print("no record of pid {d} — only jobs graff started can be stopped here; graff servers lists them\n", .{pid});+ return out.print("no record of pid {d} — suspected listeners are report-only and cannot be stopped here; exact start/executable/group identity is not available\n", .{pid});}if (std.mem.eql(u8, action, "prune")) {diff --git a/src/startup.zig b/src/startup.zigindex 5a5630aa..79ef2311 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -439,6 +439,9 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.processreturn true;}+ if (!main_mod.json_mode and flags.oneshot_prompt == null)+ @import("server_diagnostics.zig").warnStartup(arena, io);+// ADR 0042: claim the pager before keys / MCP / prompt so `graff tui`// (and TTY `graff repl`) do not sit on a blank shell. No-op off a TTY.if (!main_mod.json_mode and flags.oneshot_prompt == null and flags.isPager()) {