graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Auto-isolation: take a startup claim before deciding (#1200)
justracha203b3fd5961
diff --git a/src/main.zig b/src/main.zigindex 81734e23..a85485f8 100644--- a/src/main.zig+++ b/src/main.zig@@ -579,7 +579,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig") }; // h2 stream path, and graff's request/response contract over the pinned http-zig_ = @import("tui_acp_updates.zig");_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root- _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_elicit.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig") };+ _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_elicit.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("startup_claim.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig") };_ = @import("task_outcome.zig"); // goal-outcome telemetry events_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here_ = .{ @import("additional_tests.zig"), @import("req_stats.zig"), @import("exact_reply.zig"), @import("rlm_order_tests.zig"), @import("async_tool_policy.zig"), @import("agent_async_tools.zig"), @import("request_usage_attempts.zig"), @import("learn_formal.zig") };diff --git a/src/startup_claim.zig b/src/startup_claim.zignew file mode 100644index 00000000..d60c0523--- /dev/null+++ b/src/startup_claim.zig@@ -0,0 +1,84 @@+//! A per-checkout startup claim for auto-isolation (#1200).+//!+//! A session writes its presence record only after boot, so two sessions+//! started together both read the checkout as unclaimed and both stay on the+//! primary working tree. Before deciding, an eligible session takes this claim+//! with an exclusive create, which is atomic across processes. A fresh claim+//! held by another live process means the checkout is contended and this+//! session isolates. After `window_ms` the presence registry is authoritative+//! again, so a session that later moved off the checkout does not keep forcing+//! isolation, and nothing needs to release the claim.+//!+//! Residual race: two sessions reclaiming the same stale claim in the same+//! instant can both win. That needs a dead owner and a simultaneous start.++const std = @import("std");+const Io = std.Io;+const proc_identity = @import("proc_identity.zig");++pub const window_ms: i64 = 60_000;++const Claim = struct { owner: proc_identity.Record, ms: i64 };++fn parse(text: []const u8) ?Claim {+ const owner = proc_identity.parseRecord(text) orelse return null;+ const at = std.mem.indexOf(u8, text, " ms=") orelse return null;+ const rest = text[at + 4 ..];+ const end = std.mem.indexOfAny(u8, rest, " \n") orelse rest.len;+ return .{ .owner = owner, .ms = std.fmt.parseInt(i64, rest[0..end], 10) catch return null };+}++fn take(io: Io, dir: Io.Dir, name: []const u8, now_ms: i64) bool {+ const me = proc_identity.selfRecord(io);+ var buf: [128]u8 = undefined;+ const line = std.fmt.bufPrint(&buf, "graff-owner 1 pid={d} start={d} ms={d}\n", .{ me.pid, me.start_id, now_ms }) catch return false;+ dir.writeFile(io, .{ .sub_path = name, .data = line, .flags = .{ .exclusive = true } }) catch return false;+ return true;+}++fn liveOther(io: Io, dir: Io.Dir, name: []const u8, now_ms: i64) ?bool {+ var buf: [128]u8 = undefined;+ const text = dir.readFile(io, name, &buf) catch return null;+ const c = parse(text) orelse return false; // unparsable: not an owner+ if (c.owner.pid == proc_identity.selfPid()) return false;+ return now_ms - c.ms < window_ms and proc_identity.stateOf(io, c.owner) == .held;+}++/// True when another live session took this checkout's startup claim within+/// the window. Otherwise the claim is now ours and this returns false.+pub fn heldByOther(io: Io, dir: Io.Dir, name: []const u8, now_ms: i64) bool {+ for (0..2) |_| {+ if (take(io, dir, name, now_ms)) return false;+ const other = liveOther(io, dir, name, now_ms) orelse continue; // vanished: retry+ if (other) return true;+ dir.deleteFile(io, name) catch {}; // stale or our own leftover: retake+ }+ return liveOther(io, dir, name, now_ms) orelse false;+}++/// The claim's file name for one checkout identity.+pub fn fileName(buf: *[48]u8, identity: []const u8) []const u8 {+ return std.fmt.bufPrint(buf, "startup-{x:0>16}.claim", .{std.hash.Wyhash.hash(0x1200, identity)}) catch unreachable;+}++test "the first session takes the claim; a fresh live claim is contended; a stale one is retaken" {+ if (@import("builtin").os.tag == .windows) return;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var nbuf: [48]u8 = undefined;+ const name = fileName(&nbuf, "/repo/.git");+ const now: i64 = 1_000_000;+ try std.testing.expect(!heldByOther(io, tmp.dir, name, now));+ // Our own claim never contends with us.+ try std.testing.expect(!heldByOther(io, tmp.dir, name, now + 10));++ // pid 1 is always alive: a fresh claim it holds is contention.+ try tmp.dir.writeFile(io, .{ .sub_path = name, .data = "graff-owner 1 pid=1 start=0 ms=1000000\n" });+ try std.testing.expect(heldByOther(io, tmp.dir, name, now + 5_000));+ // Past the window the registry is authoritative again; the claim is retaken.+ try std.testing.expect(!heldByOther(io, tmp.dir, name, now + window_ms + 1));+ var buf: [128]u8 = undefined;+ const mine = parse(try tmp.dir.readFile(io, name, &buf)).?;+ try std.testing.expectEqual(proc_identity.selfPid(), mine.owner.pid);+}diff --git a/src/task_workspace.zig b/src/task_workspace.zigindex 3c43673b..bbcc061a 100644--- a/src/task_workspace.zig+++ b/src/task_workspace.zig@@ -379,6 +379,20 @@ pub fn checkoutClaimed(gpa: Allocator, io: Io, arena: Allocator, home: []const ureturn lease.duplicateOwner(peers.records, peers.probes, identity.id, self) != null;}+/// Take this checkout's startup claim, or report that a peer holds it (#1200).+fn startupContended(gpa: Allocator, io: Io, arena: Allocator, home: []const u8) bool {+ if (home.len == 0) return false;+ const identity = lease.currentIdentity(gpa, io, arena);+ if (identity.id.len == 0 or identity.kind == .not_git) return false;+ const dir_path = std.fmt.allocPrint(arena, "{s}/{s}", .{ home, presence.registry_subdir }) catch return false;+ Io.Dir.cwd().createDirPath(io, dir_path) catch return false;+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return false;+ defer dir.close(io);+ var buf: [48]u8 = undefined;+ const claim = @import("startup_claim.zig");+ return claim.heldByOther(io, dir, claim.fileName(&buf, identity.id), @import("util.zig").unixMs(io));+}+pub fn enter(io: Io, arena: Allocator, wt: Workspace) !void {if (builtin.os.tag == .windows) return error.Unsupported;const z = try arena.dupeSentinel(u8, wt.path, 0);@@ -394,14 +408,9 @@ pub fn enter(io: Io, arena: Allocator, wt: Workspace) !void {pub fn maybeAutoIsolate(gpa: Allocator, io: Io, arena: Allocator, home: []const u8, already_isolated: bool, lean: bool) AutoIsolate {if (builtin.os.tag == .windows) return .skip;const is_git = isGitAt(gpa, io, ".");- const claimed = checkoutClaimed(gpa, io, arena, home);- if (!shouldAutoIsolate(.{- .already_isolated = already_isolated,- .lean = lean,- .is_git = is_git,- .claimed = claimed,- .windows = false,- })) return .skip;+ const eligible = shouldAutoIsolate(.{ .already_isolated = already_isolated, .lean = lean, .is_git = is_git, .claimed = true, .windows = false });+ // #1200: a live peer, or one that started with us and has not announced yet.+ if (!eligible or !(checkoutClaimed(gpa, io, arena, home) or startupContended(gpa, io, arena, home))) return .skip;var raw: [4]u8 = undefined;io.random(&raw);const nonce = std.fmt.bytesToHex(raw, .lower);