graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
jobs: a parked command's handle keeps an answer across continuation
justrach0ba057b9b6db
diff --git a/docs/adr/0264-a-parked-job-keeps-its-outcome.md b/docs/adr/0264-a-parked-job-keeps-its-outcome.mdnew file mode 100644index 00000000..c33e7c72--- /dev/null+++ b/docs/adr/0264-a-parked-job-keeps-its-outcome.md@@ -0,0 +1,32 @@+# 0264. A parked foreground job keeps an answer for its handle++Status: accepted 2026-10-07++## Context++ADR 0218 made background jobs durable but kept parked foreground commands on+pipes, because their `cmd &` idioms depend on pipe EOF. Their handles outlived+them: after a session continued in another graff process, `action=output` or+`action=kill` on the handle found no owner and could only say "interrupted or+unknown outcome", even when the command had finished (#1486).++## Decision++- When the foreground wait parks a command, graff writes+ `.graff/job-parked/<id>.json` with the command and the owning graff's+ identity.+- When the pool frees the job, the record is rewritten with its final state:+ the exit code and the unread output tail (16 KB), killed, stopped at session+ end, or left running at session end.+- A handle this process does not own is answered from that record. If the+ owner is still alive, the answer says the job belongs to that graff. If the+ owner died without a final state, the answer says so and does not claim the+ command finished.+- Records older than a week are swept when a new one is written.++## Consequences++A continuation gets an explicit result for every parked handle instead of+"unknown". The command itself still dies with its owner's pipes; making it+survive would need ADR 0218's file capture from the start, which would break+the pipe-EOF idioms. Revisit if parked commands need to survive a crash.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex fdfc85ee..9e495acb 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -288,6 +288,7 @@ record only when you need the evidence or the edge cases.| [0259](0259-openai-routes-compact-only-server-side.md) | First-party Responses routes (direct API, Codegraff GPT, ChatGPT plan) compact only server-side: no client-summary fallback while the server arm is on. A compaction item's `encrypted_content` is metered at 16 bytes/token, not as text, so a blob-anchored history does not re-compact every step. || [0260](0260-clef-compaction-replaces-client-summary.md) | `GRAFF_CLEF_COMPACT=1` routes client-summary compactions through the gateway's server-side `POST /v1/compact` (Clef decision-model pruning, text verbatim); OpenAI-family server paths are untouched and any failure falls back to the summary. || [0261](0261-client-summary-stays-the-compactor.md) | The client summary stays the compactor: `GRAFF_CLEF_COMPACT` defaults off (Clef rarely pruned and mostly fell back to the summary in measurement); first-party Responses routes use only the provider's own compaction. Supersedes 0260's default. |+| [0264](0264-a-parked-job-keeps-its-outcome.md) | A parked foreground job records its outcome in `.graff/job-parked/<id>.json` (exit code and unread tail, or how session end treated it), so a later process answers its handle instead of "unknown outcome". Completes ADR 0218's follow-up without moving parked jobs off pipes. || [0270](0270-a-closed-stdio-mcp-server-restarts-on-its-next-call.md) | A stdio MCP server whose connection closes goes back to dormant with its launch config and restarts on its next call; the failed call is never replayed, and after two restarts in a session its tools are withdrawn as before. || [0278](0278-t3-code-acp-profile.md) | An ACP client named `t3-code…` gets a profile: slash commands are the first prompt block, the client's `cwd` is never swapped for an auto-isolated tree, a `model` config option lists reachable models, and `/model` and `/yolo` are not advertised. || [0280](0280-mcp-servers-report-state-and-reconnect.md) | Every configured MCP server has one status row (`graff mcp status --json`, `/mcp`); `graff mcp reconnect` / `/mcp reconnect` run a real handshake and refresh its catalog; `graff mcp enable|disable` live in `~/.codegraff/mcp-state.json`; the catalog cache keys on cwd + env, and server `env` overlays graff's own. |diff --git a/src/exec_bash.zig b/src/exec_bash.zigindex 48e55ce6..03440162 100644--- a/src/exec_bash.zig+++ b/src/exec_bash.zig@@ -432,6 +432,7 @@ fn execUnchecked(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {// finite one keeps the wait-until-exit `action=output`.const server = server_like;if (server) jobs.markPersistent(io, r.id);+ jobs.markParked(io, r.id); // #1486@import("subagent_interactive.zig").request(ctx);break :blk .{ .text = try startedText(gpa, r.id, cmd, ssh, if (server) .server else .finite, wait_ms / 1000, r.output), .pending = true };},diff --git a/src/job_parked.zig b/src/job_parked.zignew file mode 100644index 00000000..fe49d5df--- /dev/null+++ b/src/job_parked.zig@@ -0,0 +1,184 @@+//! #1486: a foreground command parked in the background stays on pipes (ADR+//! 0218: its `cmd &` idioms depend on pipe EOF), so it cannot outlive the+//! graff that owns it. Its handle could: a resumed or restarted session that+//! asked for it found no owner and could only answer "unknown outcome".+//!+//! A parked job now leaves a small record, `.graff/job-parked/<id>.json`,+//! written when it parks and rewritten with its final state (exit code and the+//! unread output tail, or how session end treated it) when the pool frees it.+//! A later process answers that handle from the record instead of losing it.+//! A record whose owner is still alive is answered as owned elsewhere; one+//! whose owner died without a final state says exactly that.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const proc_identity = @import("proc_identity.zig");++pub const dir_rel = ".graff/job-parked";+const tail_cap = 16 * 1024;+const max_age_ns: i96 = 7 * std.time.ns_per_day;++pub const State = enum { running, exited, killed, stopped_at_exit, left_running };++pub const Record = struct {+ id: u64,+ cmd: []const u8,+ owner_pid: i32 = 0,+ owner_start: proc_identity.StartId = 0,+ state: State = .running,+ exit_code: ?u8 = null,+ output: []const u8 = "",+ reported: bool = false,+};++/// Tests point this at a tmp dir; production writes under the process cwd.+pub var base_override: ?Io.Dir = null;++fn base() Io.Dir {+ return base_override orelse Io.Dir.cwd();+}++fn path(buf: []u8, id: u64) []const u8 {+ return std.fmt.bufPrint(buf, "{s}/{d}.json", .{ dir_rel, id }) catch unreachable;+}++/// Write `rec`. Best effort: a failed write leaves the earlier record.+pub fn write(io: Io, rec: Record) void {+ var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const body = std.json.Stringify.valueAlloc(arena, rec, .{}) catch return;+ base().createDirPath(io, dir_rel) catch return;+ var buf: [96]u8 = undefined;+ const final = path(&buf, rec.id);+ const tmp = std.fmt.allocPrint(arena, "{s}.tmp", .{final}) catch return;+ base().writeFile(io, .{ .sub_path = tmp, .data = body }) catch return;+ base().rename(tmp, base(), final, io) catch base().deleteFile(io, tmp) catch {};+}++/// The job just parked: record it as running under this process.+pub fn begin(io: Io, id: u64, cmd: []const u8) void {+ sweep(io);+ write(io, .{ .id = id, .cmd = cmd, .owner_pid = proc_identity.selfPid(), .owner_start = proc_identity.selfStartId(io) });+}++/// What the pool knew about the job when it freed it.+pub const Final = struct {+ exit_code: ?u8,+ done: bool,+ killed: bool,+ session_end: bool,+ unread: []const u8,+};++pub fn finish(io: Io, id: u64, cmd: []const u8, f: Final) void {+ const state: State = if (!f.done)+ .left_running+ else if (f.killed and f.session_end)+ .stopped_at_exit+ else if (f.killed)+ .killed+ else+ .exited;+ const tail = f.unread[f.unread.len -| tail_cap..];+ write(io, .{+ .id = id,+ .cmd = cmd,+ .state = state,+ .exit_code = f.exit_code,+ .output = tail,+ .reported = f.done and f.unread.len == 0,+ });+}++/// The answer for a handle this process does not own, or null when no parked+/// job ever recorded it.+pub fn describe(gpa: Allocator, io: Io, id: u64) ?Answer {+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var buf: [96]u8 = undefined;+ const bytes = base().readFileAlloc(io, path(&buf, id), arena, .limited(tail_cap + 8 * 1024)) catch return null;+ const rec = std.json.parseFromSliceLeaky(Record, arena, bytes, .{ .ignore_unknown_fields = true }) catch return null;+ if (rec.id != id) return null;+ return render(gpa, io, rec) catch null;+}++pub const Answer = struct { text: []u8, is_error: bool };++fn render(gpa: Allocator, io: Io, rec: Record) !Answer {+ var aw: Io.Writer.Allocating = .init(gpa);+ errdefer aw.deinit();+ const w = &aw.writer;+ var is_error = true;+ switch (rec.state) {+ .running => {+ const owner = proc_identity.stateOf(io, .{ .pid = rec.owner_pid, .start_id = rec.owner_start });+ if (owner == .held and rec.owner_pid != proc_identity.selfPid()) {+ try w.print("job {d} ({s}) belongs to another running graff (pid {d}); read it from that session", .{ rec.id, rec.cmd, rec.owner_pid });+ } else {+ try w.print("job {d} ({s}) was a parked foreground command whose graff ended without recording an outcome; its output pipes closed with that graff, so the command most likely stopped then. Its output and exit status were not kept; do not assume it finished", .{ rec.id, rec.cmd });+ }+ },+ .exited => {+ is_error = (rec.exit_code orelse 1) != 0;+ if (rec.exit_code) |c|+ try w.print("job {d} ({s}) finished before this continuation: exited with code {d}", .{ rec.id, rec.cmd, c })+ else+ try w.print("job {d} ({s}) finished before this continuation: terminated abnormally", .{ rec.id, rec.cmd });+ },+ .killed => try w.print("job {d} ({s}) was killed before this continuation", .{ rec.id, rec.cmd }),+ .stopped_at_exit => try w.print("job {d} ({s}) was stopped when its graff session ended; it did not finish", .{ rec.id, rec.cmd }),+ .left_running => try w.print("job {d} ({s}) was left running when its graff session ended; its output is no longer captured — /jobs or `graff servers` show what still runs", .{ rec.id, rec.cmd }),+ }+ if (rec.output.len > 0) {+ try w.writeAll("\nunread output:\n");+ try w.writeAll(rec.output);+ } else if (rec.reported) {+ try w.writeAll("\n(its output was already read)");+ }+ return .{ .text = try aw.toOwnedSlice(), .is_error = is_error };+}++/// Drop records older than a week. Cheap: one directory pass per park.+fn sweep(io: Io) void {+ var dir = base().openDir(io, dir_rel, .{ .iterate = true }) catch return;+ defer dir.close(io);+ const now = Io.Clock.real.now(io).nanoseconds;+ var it = dir.iterate();+ while (it.next(io) catch return) |entry| {+ if (entry.kind != .file) continue;+ const st = dir.statFile(io, entry.name, .{}) catch continue;+ if (now - st.mtime.nanoseconds > max_age_ns) dir.deleteFile(io, entry.name) catch {};+ }+}++test "#1486 a parked job's record answers its handle after its graff is gone" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ base_override = tmp.dir;+ defer base_override = null;++ try std.testing.expect(describe(gpa, io, 7) == null);+ // Parked by a graff that died before the pool could record an outcome.+ write(io, .{ .id = 7, .cmd = "make test", .owner_pid = 0 });+ const lost = describe(gpa, io, 7).?;+ defer gpa.free(lost.text);+ try std.testing.expect(lost.is_error);+ try std.testing.expect(std.mem.indexOf(u8, lost.text, "without recording an outcome") != null);++ finish(io, 7, "make test", .{ .exit_code = 0, .done = true, .killed = false, .session_end = true, .unread = "all green\n" });+ const done = describe(gpa, io, 7).?;+ defer gpa.free(done.text);+ try std.testing.expect(!done.is_error);+ try std.testing.expect(std.mem.indexOf(u8, done.text, "exited with code 0") != null);+ try std.testing.expect(std.mem.indexOf(u8, done.text, "all green") != null);++ finish(io, 7, "make test", .{ .exit_code = null, .done = true, .killed = true, .session_end = true, .unread = "" });+ const stopped = describe(gpa, io, 7).?;+ defer gpa.free(stopped.text);+ try std.testing.expect(std.mem.indexOf(u8, stopped.text, "stopped when its graff session ended") != null);+}diff --git a/src/jobs.zig b/src/jobs.zigindex 0f27bd7d..62a50f90 100644--- a/src/jobs.zig+++ b/src/jobs.zig@@ -80,6 +80,7 @@ pub const Job = struct { // session-global; pump drains pipes or capture files;dropped: bool = false,quiet: bool = false, // skip job_notify until auto-bg (#620)persistent: bool = false, // started with run_in_background (#810)+ parked: bool = false, // #1486: a parked foreground command keeps a record of its outcomefuture: Io.Future(void) = undefined,stream: ?process_runner.StreamFn = null,stream_ctx: ?*anyopaque = null,@@ -93,6 +94,7 @@ const browser_guard = @import("job_browser_guard.zig");const job_idle = @import("job_idle.zig"); // #199const job_registry = @import("job_registry.zig"); // #199const job_capture = @import("job_capture.zig"); // ADR 0218+const job_parked = @import("job_parked.zig"); // #1486const proc_identity = @import("proc_identity.zig");const util = @import("util.zig");const tool_pulse = @import("tool_pulse.zig"); // silence heartbeat during waitForeground@@ -114,6 +116,16 @@ const Jobs = struct {pub var g_jobs: Jobs = .{};+/// #1486: the foreground wait parked this job; record it so its handle+/// keeps an answer after this graff is gone.+pub fn markParked(io: Io, id: u64) void {+ g_jobs.mutex.lockUncancelable(io);+ defer g_jobs.mutex.unlock(io);+ const job = g_jobs.find(id) orelse return;+ job.parked = true;+ job_parked.begin(io, job.id, job.cmd);+}+pub fn markPersistent(io: Io, id: u64) void {g_jobs.mutex.lockUncancelable(io);defer g_jobs.mutex.unlock(io);@@ -387,6 +399,7 @@ pub fn jobOutput(gpa: Allocator, io: Io, id: u64, wait_ms: u64) !ToolOutput {g_jobs.mutex.lockUncancelable(io);const job = g_jobs.find(id) orelse {g_jobs.mutex.unlock(io);+ if (job_parked.describe(gpa, io, id)) |known| return .{ .text = known.text, .is_error = known.is_error };return .{ .text = try std.fmt.allocPrint(gpa, "background job {d} has no live owner in this process — interrupted or unknown outcome; do not assume it never ran or rerun it automatically; /jobs lists current jobs", .{id}), .is_error = true };};browser_guard.touch(job, nowMs(io)); // a read or a blocking wait is activity (#199)@@ -449,7 +462,10 @@ pub fn jobKill(gpa: Allocator, io: Io, id: u64) !ToolOutput {{g_jobs.mutex.lockUncancelable(io);defer g_jobs.mutex.unlock(io);- const job = g_jobs.find(id) orelse return .{ .text = try std.fmt.allocPrint(gpa, "background job {d} has no live owner in this process — interrupted or unknown outcome; no process was stopped; /jobs lists current jobs", .{id}), .is_error = true };+ const job = g_jobs.find(id) orelse {+ if (job_parked.describe(gpa, io, id)) |known| return .{ .text = known.text, .is_error = known.is_error };+ return .{ .text = try std.fmt.allocPrint(gpa, "background job {d} has no live owner in this process — interrupted or unknown outcome; no process was stopped; /jobs lists current jobs", .{id}), .is_error = true };+ };if (job.done) {consumed(io, job); // already-finished also reports the exitconst unread = job.buf.items.len - job.cursor;@@ -485,6 +501,7 @@ pub const waitForeground = job_foreground.waitForeground;fn freeJob(gpa: Allocator, io: Io, job: *Job) void {job.future.await(io);+ if (job.parked) job_parked.finish(io, job.id, job.cmd, .{ .exit_code = job.exit_code, .done = job.done, .killed = job.killed, .session_end = job.exit_cleanup, .unread = job.buf.items[job.cursor..] });// A kept job still writes to its capture: a later resume re-attaches it.if (job.capture) |c| job_capture.release(gpa, io, c, !job.detach);job.buf.deinit(gpa);@@ -539,6 +556,7 @@ test { // split-out modules: unreferenced, their tests silently never run_ = @import("worktree_lease.zig");_ = .{ job_wait, job_notify, job_idle, job_registry, browser_guard, job_capture };_ = @import("job_durable.zig");+ _ = job_parked;_ = @import("job_recover.zig");_ = @import("jobs_tests.zig");}