Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Preserve server retention intent across owner exits

justrach499191f2a5d1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 29f2374b..cb660866 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -79,6 +79,7 @@ jobs:
python3 scripts/eval/test_process_guard.py
python3 scripts/test-acp-failure.py
python3 scripts/regression-release-297.py
+ python3 scripts/test-server-retention.py --evidence "$RUNNER_TEMP/server-retention"
python3 scripts/test-pr-completion-acp.py
python3 scripts/test-claim-repository.py
python3 scripts/test-claim-lifecycle.py
diff --git a/docs/adr/0098-orphan-listeners-are-not-stop-authority.md b/docs/adr/0098-orphan-listeners-are-not-stop-authority.md
index 9d26a1b2..1b43185d 100644
--- a/docs/adr/0098-orphan-listeners-are-not-stop-authority.md
+++ b/docs/adr/0098-orphan-listeners-are-not-stop-authority.md
@@ -42,3 +42,14 @@ 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.
+
+## Retention intent
+
+Retention does not imply a user pin. Ownership records preserve the original
+pin flag and record whether retention followed a user pin or unverified
+consumer visibility. A later `servers list` shows that reason. Legacy records
+without a reason remain unknown: older versions set the pin flag during both
+paths, so the flag cannot establish historical user intent. This changes
+observability, not the conservative cleanup rule above. The production
+retention regression verifies a surviving listener after owner exit, its
+record and CLI explanation, and an explicit verified stop.
diff --git a/scripts/test-server-retention.py b/scripts/test-server-retention.py
new file mode 100644
index 00000000..50271523
--- /dev/null
+++ b/scripts/test-server-retention.py
@@ -0,0 +1,101 @@
+"""Verify post-exit server retention through actual agent dispatch and sockets."""
+import argparse, importlib.util, json, os, socket, sys, tempfile, signal, time, shlex, shutil, subprocess
+from pathlib import Path
+root = Path(__file__).resolve().parents[1]
+parser = argparse.ArgumentParser(description=__doc__)
+parser.add_argument('--graff', type=Path, default=root / 'zig-out/bin/graff')
+parser.add_argument('--evidence', type=Path, required=True)
+args = parser.parse_args()
+out = args.evidence.resolve()
+out.mkdir(parents=True, exist_ok=True)
+graff = args.graff.resolve()
+spec = importlib.util.spec_from_file_location('regression', root / 'scripts/regression-release-297.py')
+reg = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(reg)
+def run_case(mode):
+ global out
+ out = args.evidence.resolve() / mode
+ out.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix='graff-listener-retain-') as temp:
+ work = Path(temp)
+ (work / 'mcp.json').write_text('{"mcpServers":{}}')
+ (work / 'listener.py').write_text("import json,os,socket,time\nfrom pathlib import Path\ns=socket.socket();s.bind(('127.0.0.1',0));s.listen(16)\nPath('listener.json').write_text(json.dumps({'pid':os.getpid(),'port':s.getsockname()[1]}))\nwhile True: time.sleep(1)\n")
+ (work / 'ready.py').write_text("import time,json,socket\nfrom pathlib import Path\nfor _ in range(100):\n if Path('listener.json').exists():break\n time.sleep(.05)\ns=json.loads(Path('listener.json').read_text());socket.create_connection(('127.0.0.1',s['port']),timeout=2).close();print('listener ready')\n")
+ env = {k: v for (k, v) in os.environ.items() if not k.endswith('_API_KEY')}
+ env.update(HOME=temp, LMSTUDIO_API_KEY='local', GRAFF_NO_TELEMETRY='1', GRAFF_FLEET='off', GRAFF_NO_SMOLIFY='1', GRAFF_NO_CODEDB_GUARD='1', NO_COLOR='1', GRAFF_JOB_IDLE_WARN_MINS='0', GRAFF_JOB_IDLE_STOP_MINS='1', GRAFF_MCP_CONFIG=str(work / 'mcp.json'))
+ model = reg.ScriptedModel([{'tool': 'bash', 'arguments': {'command': shlex.quote(sys.executable) + ' listener.py', 'run_in_background': True}}, reg.tool(shlex.quote(sys.executable) + ' ready.py'), {'text': 'The isolated listener is ready.'}])
+ model.start(1234)
+ pid = None
+ try:
+ command = [str(graff), '--json', '--yolo', '--old', '--model', 'lmstudio']
+ prompt = json.dumps({'type': 'user', 'text': 'Start the isolated listener and verify readiness.'}) + '\n'
+ if mode == 'normal':
+ done = reg.bounded_run(command, cwd=work, env=env, text=True, capture_output=True, timeout=110, input=prompt)
+ else:
+ with (out / 'owner-stdout.log').open('w+') as stdout, (out / 'owner-stderr.log').open('w+') as stderr:
+ process = subprocess.Popen(command, cwd=work, env=env, text=True, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr)
+ try:
+ process.stdin.write(prompt)
+ process.stdin.flush()
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ if len(model.requests) >= 3 and (work / 'listener.json').exists():
+ break
+ assert process.poll() is None, 'owner exited before crash fixture'
+ time.sleep(.05)
+ else:
+ raise AssertionError('listener was not ready before crash')
+ process.kill()
+ process.wait(timeout=10)
+ stdout.seek(0); stderr.seek(0)
+ done = subprocess.CompletedProcess(command, 0, stdout.read(), stderr.read())
+ finally:
+ if process.poll() is None:
+ process.kill(); process.wait(timeout=10)
+ process.stdin.close()
+
+ (out / 'retained-events.jsonl').write_text(done.stdout)
+ (out / 'retained-stderr.log').write_text(done.stderr)
+ (out / 'retained-requests.json').write_text(json.dumps(model.requests, indent=2))
+ for folder in ('sessions', 'traces', 'trajectories'):
+ if (work / '.graff' / folder).exists():
+ shutil.copytree(work / '.graff' / folder, out / folder, dirs_exist_ok=True)
+ state = json.loads((work / 'listener.json').read_text())
+ pid = state['pid']
+ assert done.returncode == 0, done.stderr
+ with socket.create_connection(('127.0.0.1', state['port']), timeout=2):
+ pass
+ recs = list((work / '.codegraff/jobs').glob('*.json'))
+ assert len(recs) == 1, recs
+ record = json.loads(recs[0].read_text())
+ assert not record['pinned'], record
+ assert record['retained'] == (mode == 'normal'), record
+ assert record.get('retention_reason') == ('unverified_consumers' if mode == 'normal' else None), record
+ (out / 'retained-record.json').write_text(json.dumps(record, indent=2))
+ listing = reg.bounded_run([str(graff), 'servers', 'list'], cwd=work, env=env, text=True, capture_output=True, timeout=30)
+ (out / 'retained-list.log').write_text(listing.stdout)
+ assert str(record['pid']) in listing.stdout, listing.stdout
+ if mode == 'normal':
+ assert 'consumer visibility unknown' in listing.stdout, listing.stdout
+ else:
+ row = next(line for line in listing.stdout.splitlines() if line.split() and line.split()[0].lstrip('+') == str(record['pid']))
+ assert 'gone' in row, row
+ stopped = reg.bounded_run([str(graff), 'servers', 'stop', str(record['pid'])], cwd=work, env=env, text=True, capture_output=True, timeout=30)
+ (out / 'retained-stop.log').write_text(stopped.stdout)
+ try:
+ socket.create_connection(('127.0.0.1', state['port']), timeout=0.5).close()
+ raise AssertionError('owned listener survived explicit stop')
+ except OSError:
+ pass
+ (out / 'retained-results.json').write_text(json.dumps({'status': 'passed', 'checks': ['survivor is not falsely marked as a user pin', 'real background listener survives owner session exit when browser visibility unknown', 'ownership record stays discoverable after owner exit', 'explicit verified stop closes listener']}, indent=2))
+ print(f'PASS {mode}: owner exit preserves accurate intent; fresh verified stop closes socket')
+ finally:
+ model.stop()
+ if pid:
+ try:
+ os.kill(pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+
+for mode in ('normal', 'crash'):
+ run_case(mode)
diff --git a/src/job_registry.zig b/src/job_registry.zig
index 8294b28d..4fcd36ca 100644
--- a/src/job_registry.zig
+++ b/src/job_registry.zig
@@ -33,6 +33,7 @@ pub const Record = struct {
started_ms: i64 = 0,
pinned: bool = false,
retained: bool = false,
+ retention_reason: ?enum { user_pin, unverified_consumers } = null,
};
pub fn dirPath(buf: []u8, base: []const u8) ?[]const u8 {
@@ -177,8 +178,8 @@ pub fn retain(io: Io, base: []const u8, rec: Record, stdout: ?Io.File, stderr: ?
}) catch return false;
}
var kept = rec;
- kept.pinned = true;
kept.retained = true;
+ kept.retention_reason = if (rec.pinned) .user_pin else .unverified_consumers;
write(io, base, kept);
return true;
}
@@ -240,3 +241,25 @@ test "stopTree never signals a pid whose start identity is not ours" {
const real: Record = .{ .pid = me.pid, .start_id = me.start_id, .cmd = "us" };
try std.testing.expectEqual(State.running, state(io, real));
}
+
+test "retention preserves user pin intent and records why cleanup deferred" {
+ if (!posix) return error.SkipZigTest;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var path: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &path);
+ for ([_]bool{ false, true }) |pinned| {
+ try std.testing.expect(retain(io, path[0..n], .{ .pid = 321, .cmd = "fixture", .pinned = pinned }, null, null));
+ const records = list(io, arena, path[0..n]);
+ try std.testing.expectEqual(@as(usize, 1), records.len);
+ try std.testing.expect(records[0].retained);
+ try std.testing.expectEqual(pinned, records[0].pinned);
+ try std.testing.expectEqualStrings(if (pinned) "user_pin" else "unverified_consumers", @tagName(records[0].retention_reason.?));
+ }
+ const legacy = try std.json.parseFromSliceLeaky(Record, arena, "{\"pid\":321,\"cmd\":\"legacy\",\"pinned\":true,\"retained\":true}", .{});
+ try std.testing.expect(legacy.retention_reason == null);
+}
diff --git a/src/jobs_tests.zig b/src/jobs_tests.zig
index 4feeb357..6c0ad37c 100644
--- a/src/jobs_tests.zig
+++ b/src/jobs_tests.zig
@@ -300,6 +300,8 @@ test "#199: a pinned job is retained at session end — record kept, tree alive,
const recs = job_registry.list(io, arena, job_registry.home);
try std.testing.expectEqual(@as(usize, 1), recs.len);
try std.testing.expect(recs[0].retained);
+ try std.testing.expect(recs[0].pinned);
+ try std.testing.expectEqualStrings("user_pin", @tagName(recs[0].retention_reason.?));
try std.testing.expectEqual(pid, recs[0].pid);
try std.testing.expectEqual(job_registry.State.running, job_registry.state(io, recs[0]));
// A later `graff servers stop <pid>`: verified, then the whole group goes.
diff --git a/src/servers_cmd.zig b/src/servers_cmd.zig
index bf07432e..2be9d604 100644
--- a/src/servers_cmd.zig
+++ b/src/servers_cmd.zig
@@ -38,6 +38,13 @@ pub fn command(gpa: Allocator, io: Io, arena: Allocator, args: []const []const u
.unverifiable => "unknown",
};
try out.print("{d:<8} {s:<9} {s:<8} {s:<6} {s:<21} {s}", .{ rec.pid, state_s, age, owner, ports, util.utf8Prefix(rec.cmd, 60) });
+ if (rec.retained) {
+ const why: []const u8 = if (rec.retention_reason) |reason| switch (reason) {
+ .user_pin => "user pin",
+ .unverified_consumers => "consumer visibility unknown",
+ } else "reason unknown (legacy record)";
+ try out.print(" [kept: {s}]", .{why});
+ }
if (rec.cwd.len > 0) try out.print(" ({s})", .{rec.cwd});
try out.writeAll("\n");
}