graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Preserve worker resume settings and active checkout retention
Rach Pradhan38cc24dd8639
diff --git a/docs/adr/0164-task-workspace-archive-needs-current-evidence.md b/docs/adr/0164-task-workspace-archive-needs-current-evidence.mdindex 3fd8a5ed..4750776e 100644--- a/docs/adr/0164-task-workspace-archive-needs-current-evidence.md+++ b/docs/adr/0164-task-workspace-archive-needs-current-evidence.md@@ -21,6 +21,13 @@ is exactly the checkout's current commit. Missing or stale evidence keeps thecheckout. Teardown runs only after the keep checks, and failure keeps thecheckout. Kept work is returned with its reason.+Age-based pruning is also distinct from an explicit discard. It retains the+current checkout, release/hotfix branches, experiment pools (ADR 0037), locked+trees, live or unverifiable+auto-session processes, and registered live owners. A legacy owner record with+no process start identity cannot prove the tree unused. Unreadable ownership+evidence retains the tree; age never overrides the dirty/unique-commit checks.+## ConsequencesOld workspaces without recorded base metadata retain their existing explicitdiff --git a/docs/adr/0170-workers-retain-owned-conversations.md b/docs/adr/0170-workers-retain-owned-conversations.mdindex 10506767..c85445fc 100644--- a/docs/adr/0170-workers-retain-owned-conversations.md+++ b/docs/adr/0170-workers-retain-owned-conversations.md@@ -23,7 +23,9 @@ Resume shares the live parent's aggregate budget. A finite budget cannot safelybe reconstructed after process restart because the parent may have spent moresince the checkpoint, so such resumes fail closed. Unlimited histories may berestored by the same persisted parent session. Provider availability and retained-workspace are checked again. A changed protocol is refused rather than reinterpreting+workspace are checked again. Rebuild the saved model’s wire settings on the available+original provider before checking its protocol; the parent may now use a different+model. A changed protocol for the saved model is refused rather than reinterpretingsaved messages. A restored text-only child retains that restriction, and an earlierloop deadline cannot be renewed by clearing the parent deadline. Completed jobsrelease the conversation arena immediately; only their compact reports stay live.diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 244bdca7..b9e37f45 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -15,7 +15,7 @@"src/repl.zig","TUI/root.zig"],- "test_count_baseline": 2690,+ "test_count_baseline": 2696,"test_count_slack": 25,"required_invariants": [{diff --git a/scripts/test-workspace-lifecycle.py b/scripts/test-workspace-lifecycle.pyindex 3e80873a..8486dc34 100644--- a/scripts/test-workspace-lifecycle.py+++ b/scripts/test-workspace-lifecycle.py@@ -65,3 +65,54 @@ with tempfile.TemporaryDirectory(prefix="graff-workspace-lifecycle-") as temporaassert not git("branch", "--list", "worktree-task")assert (root / ".graff/archive-log").read_text() == "archive"print("Workspace lifecycle: setup/run cwd, base tracking, exact merged-head proof, dirty retention, explicit discard, teardown and branch cleanup passed")++ # Retention must not treat a clean, live checkout as an unused directory.+ # Isolate the owner registry as well as Git; never inspect real live sessions.+ home = Path(temporary) / "home"+ registry = home / ".graff/live"+ registry.mkdir(parents=True)+ env.update(HOME=str(home), USERPROFILE=str(home))++ def checkout(name, branch):+ path = Path(temporary) / name+ git("worktree", "add", "-b", branch, str(path), "main")+ return path++ release = checkout("release", "release/fixture")+ hotfix = checkout("hotfix", "hotfix/fixture")+ live = checkout("live", f"worktree-session-{os.getpid()}-fixture")+ owned = checkout("owned", "worktree-owned")+ pool = checkout("pool", "graff/exp/fixture/1")+ malformed = checkout("malformed", "worktree-session-invalid-fixture")+ dirty = checkout("dirty", "worktree-dirty")+ unique = checkout("unique", "worktree-unique")+ scratch = checkout("scratch", "worktree-unused")+ current = checkout("current", "worktree-current")+ (dirty / "untracked").write_text("preserve me")+ (unique / "file").write_text("unique commit\n")+ git("add", "file", cwd=unique)+ git("commit", "-qm", "unique", cwd=unique)+ identity = git("rev-parse", "--path-format=absolute", "--git-dir", cwd=owned)+ record = registry / "fixture.json"+ record.write_text(json.dumps({"pid": os.getpid(), "start_id": 0, "identity": identity}))+ result = subprocess.run([binary, "worktree", "prune", "older-than", "0"],+ cwd=current, env=env, text=True, capture_output=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert not scratch.exists(), result.stdout+ for protected in (release, hotfix, live, owned, pool, malformed, dirty, unique, current):+ assert protected.is_dir(), f"removed protected {protected.name}: {result.stdout}"+ assert (dirty / "untracked").read_text() == "preserve me"+ assert git("log", "-1", "--format=%s", cwd=unique) == "unique"+ # Removing the fixture's legacy owner proves it alone prevented removal.+ record.unlink()+ assert "removed" in graff("prune", "older-than", "0")+ assert not owned.exists()+ unverified = checkout("unverified", "worktree-unverified")+ for malformed_record in ({"pid": os.getpid()}, {"pid": -1, "identity": identity}):+ record.write_text(json.dumps(malformed_record))+ graff("prune", "older-than", "0")+ assert unverified.exists(), "unverifiable owner record permitted removal"+ record.unlink()+ graff("prune", "older-than", "0")+ assert not unverified.exists()+ print("Worktree retention: release/hotfix, live PID, legacy owner, current cwd, dirty and unique work kept; unused tree removed")diff --git a/src/subagent_resume.zig b/src/subagent_resume.zigindex b711a3ff..a68caf92 100644--- a/src/subagent_resume.zig+++ b/src/subagent_resume.zig@@ -54,14 +54,10 @@ pub fn exec(ctx: tools.ToolCtx, input: std.json.Value) !tools.ToolOutput {const message = tools.strField(input, "message") orelse return tools.missingArg(ctx.gpa, "message");if (std.mem.trim(u8, message, " \t\r\n").len == 0 or message.len > @import("subagent_feedback.zig").max_message_bytes or !std.unicode.utf8ValidateSlice(message)) return refuse(ctx, "message must be valid UTF-8, nonempty and at most 16 KiB");if (!retained.budgetAllowed(state.record, ctx)) return refuse(ctx, "retained deadline or finite run budget is unavailable; exhausted limits cannot be renewed");- var provider = ctx.provider;- if (!std.mem.eql(u8, provider.id, state.record.provider)) {- provider = ctx.subagent_provider orelse return refuse(ctx, "original provider is unavailable; no provider switch was authorized");- if (!std.mem.eql(u8, provider.id, state.record.provider)) return refuse(ctx, "original provider is unavailable");- }- if (state.record.protocol) |kind| if (kind != provider.kind) return refuse(ctx, "original provider protocol is unavailable; cannot reinterpret saved history");- provider.model = state.record.model;- provider.context = state.record.context;+ const provider = providerFor(state.record, ctx) catch |err| return refuse(ctx, switch (err) {+ error.RetainedWorkerProviderUnavailable => "original provider is unavailable; no provider switch was authorized",+ error.RetainedWorkerProtocolChanged => "original provider protocol is unavailable; cannot reinterpret saved history",+ });var child = ctx;child.retained_worker = state;child.agent_cwd = state.record.cwd;@@ -71,3 +67,18 @@ pub fn exec(ctx: tools.ToolCtx, input: std.json.Value) !tools.ToolOutput {transferred = true;return out;}++/// Restore the retained model on an authorized existing provider credential.+pub fn providerFor(record: retained.Record, ctx: tools.ToolCtx) error{ RetainedWorkerProviderUnavailable, RetainedWorkerProtocolChanged }!Provider {+ var provider = ctx.provider;+ if (!std.mem.eql(u8, provider.id, record.provider)) {+ provider = ctx.subagent_provider orelse return error.RetainedWorkerProviderUnavailable;+ if (!std.mem.eql(u8, provider.id, record.provider)) return error.RetainedWorkerProviderUnavailable;+ }+ // The parent may now use another model with a different wire format.+ // Validate the saved protocol against the saved model, not the parent.+ provider = provider.withModel(record.model);+ if (record.protocol) |kind| if (kind != provider.kind) return error.RetainedWorkerProtocolChanged;+ provider.context = record.context;+ return provider;+}diff --git a/src/subagent_retained.zig b/src/subagent_retained.zigindex 956a6956..229bc2d5 100644--- a/src/subagent_retained.zig+++ b/src/subagent_retained.zig@@ -312,3 +312,76 @@ test "retained worker cannot resume an expired deadline after parent clears it"const record: Record = .{ .id = test_id, .family = "parent-family", .label = "worker", .provider = "fixture", .model = "fixture", .deadline_ms = 1 };try std.testing.expect(!budgetAllowed(record, ctx));}++test "retained provider restores saved model wire after parent model changes" {+ const select = @import("subagent_resume.zig").providerFor;+ const keys: @import("provider.zig").Keys = .{ .values = @splat(null) };+ const spec = @import("provider.zig").specFor("codegraff").?;+ const chat = keys.build(spec, "test-key", "mimo-v2.5-pro");+ const responses = chat.withModel("gpt-6-sol");+ for ([_]@import("provider.zig").Provider{ chat, responses }, [_]@import("provider.zig").Provider{ responses, chat }) |current, original| {+ var ctx = testContext();+ ctx.provider = current;+ ctx.provider.account = "parent-account";+ ctx.provider.source = .environment;+ const record: Record = .{ .id = test_id, .family = "parent-family", .label = "worker", .provider = original.id, .model = original.model, .protocol = original.kind, .context = 123456 };+ const restored = try select(record, ctx);+ try std.testing.expectEqual(original.kind, restored.kind);+ try std.testing.expectEqualStrings(original.url, restored.url);+ try std.testing.expectEqualStrings(original.model, restored.model);+ try std.testing.expectEqualStrings(current.api_key, restored.api_key);+ try std.testing.expectEqualStrings(ctx.provider.account, restored.account);+ try std.testing.expectEqual(ctx.provider.source, restored.source);+ try std.testing.expectEqual(original.auth, restored.auth);+ try std.testing.expectEqual(@as(u64, 123456), restored.context);+ }+}++test "retained provider still rejects actual saved protocol drift" {+ const keys: @import("provider.zig").Keys = .{ .values = @splat(null) };+ var ctx = testContext();+ ctx.provider = keys.build(@import("provider.zig").specFor("codegraff").?, "key", "gpt-6-sol");+ const record: Record = .{ .id = test_id, .family = "parent-family", .label = "worker", .provider = "codegraff", .model = "gpt-6-sol", .protocol = .openai };+ try std.testing.expectError(error.RetainedWorkerProtocolChanged, @import("subagent_resume.zig").providerFor(record, ctx));+}++test "retained provider uses only available original credential" {+ const keys: @import("provider.zig").Keys = .{ .values = @splat(null) };+ var ctx = testContext();+ const record: Record = .{ .id = test_id, .family = "parent-family", .label = "worker", .provider = "codegraff", .model = "gpt-6-sol", .protocol = .responses };+ try std.testing.expectError(error.RetainedWorkerProviderUnavailable, @import("subagent_resume.zig").providerFor(record, ctx));+ ctx.subagent_provider = keys.build(@import("provider.zig").specFor("codegraff").?, "worker-credential", "mimo-v2.5-pro");+ ctx.subagent_provider.?.account = "worker-account";+ ctx.subagent_provider.?.source = .environment;+ const restored = try @import("subagent_resume.zig").providerFor(record, ctx);+ try std.testing.expectEqualStrings("worker-account", restored.account);+ try std.testing.expectEqual(ctx.subagent_provider.?.source, restored.source);+ try std.testing.expectEqualStrings("worker-credential", restored.api_key);+ try std.testing.expectEqual(@import("provider.zig").Provider.Kind.responses, restored.kind);+ try std.testing.expectEqualStrings("https://gateway.codegraff.com/v1/responses", restored.url);+}++test "retained provider rebuilds auth and rejects changed live protocol for the saved model" {+ const pricing = @import("pricing.zig");+ const providers = @import("provider.zig");+ const saved = pricing.active_model_table;+ defer pricing.active_model_table = saved;+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var rows = [_]pricing.ModelInfo{+ .{ .provider = "kimi", .name = "native", .context = 1000, .protocol = .kimi },+ .{ .provider = "kimi", .name = "messages", .context = 1000, .protocol = .anthropic },+ };+ try std.testing.expect(pricing.activateKimiModels(arena.allocator(), &rows));+ const keys: providers.Keys = .{ .values = @splat(null) };+ var ctx = testContext();+ ctx.provider = keys.build(providers.specFor("kimi").?, "same-credential", "native");+ const record: Record = .{ .id = test_id, .family = "parent-family", .label = "worker", .provider = "kimi", .model = "messages", .protocol = .anthropic };+ const resumed = try @import("subagent_resume.zig").providerFor(record, ctx);+ try std.testing.expectEqual(providers.Provider.Auth.x_api_key, resumed.auth);+ try std.testing.expectEqualStrings(providers.kimi_anthropic_url, resumed.url);+ try std.testing.expectEqualStrings(ctx.provider.api_key, resumed.api_key);+ rows[1].protocol = .kimi;+ try std.testing.expect(pricing.activateKimiModels(arena.allocator(), &rows));+ try std.testing.expectError(error.RetainedWorkerProtocolChanged, @import("subagent_resume.zig").providerFor(record, ctx));+}diff --git a/src/worktree_prune.zig b/src/worktree_prune.zigindex 247f357e..b8babcec 100644--- a/src/worktree_prune.zig+++ b/src/worktree_prune.zig@@ -317,6 +317,56 @@ pub fn parseOlderThanArg(args: []const []const u8) ??i64 {return null;}+/// Retention is not an explicit request to discard a release or an active tree.+fn protectedBranch(refname: []const u8) bool {+ const branch = shortBranch(refname);+ return std.mem.eql(u8, branch, "release") or std.mem.eql(u8, branch, "hotfix") or+ std.mem.startsWith(u8, branch, "release/") or std.mem.startsWith(u8, branch, "hotfix/");+}++fn ownerActive(owner: worktree_lease.Owner, identity: []const u8, probe: @import("proc_identity.zig").Probe) bool {+ if (!std.mem.eql(u8, owner.identity, identity)) return false;+ return switch (probe) {+ .gone => false,+ .unknown => true,+ .id => |id| owner.start_id == 0 or id == owner.start_id,+ };+}++/// Unlike the startup warning, deletion treats a legacy live PID as occupied.+/// Read without pruning the registry; an unreadable registry cannot prove safety.+fn registeredOwner(io: Io, arena: Allocator, identity: []const u8) bool {+ const home = @import("job_registry.zig").home;+ if (home.len == 0) return true;+ const registry = std.fs.path.join(arena, &.{ home, @import("presence.zig").registry_subdir }) catch return true;+ var dir = Io.Dir.cwd().openDir(io, registry, .{ .iterate = true }) catch |err| return err != error.FileNotFound;+ defer dir.close(io);+ var it = dir.iterate();+ while (it.next(io) catch return true) |entry| {+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".json")) continue;+ const text = dir.readFileAlloc(io, entry.name, arena, .limited(64 * 1024)) catch return true;+ const owner = @import("presence_record.zig").parseRecord(arena, text) orelse return true;+ if (owner.pid <= 0 or owner.identity.len == 0) return true;+ if (ownerActive(owner, identity, @import("proc_identity.zig").probe(io, owner.pid))) return true;+ }+ return false;+}++fn retentionKeep(gpa: Allocator, io: Io, arena: Allocator, e: Entry, current: worktree_lease.Identity) ?[]const u8 {+ if (current.kind == .not_git or current.id.len == 0) return "unverifiable current checkout";+ if (e.locked) return "locked worktree";+ if (@import("experiment_pool.zig").isExperimentTree(e.path, e.branch)) return "retained experiment pool";+ if (protectedBranch(e.branch)) return "protected release/hotfix branch";+ if (@import("worktree_reap.zig").sessionPid(e.branch)) |pid| {+ if (@import("proc_identity.zig").probe(io, pid) != .gone) return "live or unverified session process";+ } else if (std.mem.startsWith(u8, shortBranch(e.branch), "worktree-session-")) return "unverifiable session process";+ const candidate = worktree_lease.identityAt(gpa, io, arena, e.path);+ if (candidate.kind == .not_git or candidate.id.len == 0) return "unverifiable checkout identity";+ if (std.mem.eql(u8, candidate.id, current.id)) return "current checkout";+ if (registeredOwner(io, arena, candidate.id)) return "live owner or unverifiable registry";+ return null;+}+fn removeStale(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, older_than_ms: i64) !void {const r = listPorcelain(gpa, io) orelse return;defer {@@ -326,9 +376,14 @@ fn removeStale(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, older_const entries = try parseEntries(arena, r.stdout);const main_path = mainWorktreePath(worktree_lease.gitCommonDir(gpa, io, arena));const now_ms = unixMs(io);+ const current = worktree_lease.currentIdentity(gpa, io, arena);var removed: usize = 0;for (entries, 0..) |e, i| {const is_main = i == 0 or (main_path.len > 0 and std.mem.eql(u8, e.path, main_path));+ if (!is_main) if (retentionKeep(gpa, io, arena, e, current)) |reason| {+ try out.print(" kept {s} — {s}\n", .{ e.path, reason });+ continue;+ };const verdict = pruneVerdict(is_main, keepReasonFor(gpa, io, e), worktreeAgeMs(io, now_ms, e.path), older_than_ms);switch (verdict) {.keep_main => continue,@@ -459,3 +514,29 @@ test "verdictText: every kept reason explains itself, reusing the #276 wording"try std.testing.expect(std.mem.indexOf(u8, verdictText(.keep_too_new), "retention") != null);try std.testing.expectEqualStrings("", verdictText(.remove));}++test "retention protects release and hotfix branches without overmatching scratch names" {+ try std.testing.expectEqualStrings("unverifiable current checkout", retentionKeep(+ std.testing.allocator,+ std.testing.io,+ std.testing.allocator,+ .{},+ .{},+ ).?);+ for ([_][]const u8{ "release", "hotfix", "refs/heads/release/next", "refs/heads/hotfix/fix" }) |name|+ try std.testing.expect(protectedBranch(name));+ for ([_][]const u8{ "worktree-release-notes", "release-notes", "feature/hotfix" }) |name|+ try std.testing.expect(!protectedBranch(name));+}++test "retention keeps live legacy and unknown owners but permits dead or reused PIDs" {+ const owner: worktree_lease.Owner = .{ .pid = 123, .identity = "fixture", .start_id = 456 };+ try std.testing.expect(ownerActive(owner, "fixture", .{ .id = 456 }));+ try std.testing.expect(ownerActive(owner, "fixture", .unknown));+ try std.testing.expect(!ownerActive(owner, "fixture", .gone));+ try std.testing.expect(!ownerActive(owner, "fixture", .{ .id = 789 }));+ try std.testing.expect(!ownerActive(owner, "different", .{ .id = 456 }));+ var legacy = owner;+ legacy.start_id = 0;+ try std.testing.expect(ownerActive(legacy, "fixture", .{ .id = 789 }));+}