graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: bound bash timeout and MCP reuse teardown (#850, #849)
Rach40caa53a6590
diff --git a/apps/native/package.json b/apps/native/package.jsonindex 60ac2dc6..72ddd245 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -10,7 +10,7 @@"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000","mock-serve": "node scripts/mock-serve.mjs","lint": "next lint",- "test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts components/site/harness-split.test.ts components/site/useDesktopShortcuts.test.ts",+ "test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts components/site/harness-split.test.ts","electron:build": "bash electron/build.sh","test:electron": "bun test electron/policy.test.cjs","test:desktop": "bun test lib ./electron/*.test.cjs",diff --git a/docs/adr/0026-foreground-bash-auto-backgrounds.md b/docs/adr/0026-foreground-bash-auto-backgrounds.mdindex b19fda6b..ef25517b 100644--- a/docs/adr/0026-foreground-bash-auto-backgrounds.md+++ b/docs/adr/0026-foreground-bash-auto-backgrounds.md@@ -20,7 +20,9 @@ partial output. A real compile keeps running. The model gets the turn back.## Decision-- Root foreground `bash` waits up to 120s (or `timeout` ms, capped at 10h).+- Root foreground `bash` waits up to 120s. An explicit `timeout` may shorten+ that wait; a larger value cannot extend it (#850). Process lifetime after+ promotion is the job registry, not the overloaded `timeout` field.- If the child is still running, it is moved onto the existing job registry.The model receives a job id. `bash_output` / `bash_kill` / `/jobs` work asthey do for `run_in_background: true`. The process is not killed.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 914467b3..6e15d012 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -36,7 +36,7 @@ record only when you need the evidence or the edge cases.| [0023](0023-codex-subagent-is-sidecar-not-v8.md) | Codex check: take sidecar-vs-critical-path spawn prompts; reject V8 Code Mode, extra spawn tools, and parent-history fork. || [0024](0024-three-harness-compare-prompt-subagent-rss.md) | Steal short child briefs + sidecar spawn; `print(read_file)` returns the file; `-p` skips the shared-tree checkpoint (evals are sibling sandboxes); reject rlm-only catalog, grok heap, Harbor. || [0025](0025-io-uring-is-not-the-process-io.md) | Process Io stays Zig `Threaded`. spec-ptc is already the default loop (ADR 0022). Do not take ublk or switch `main` to `std.Io.Uring`. |-| [0026](0026-foreground-bash-auto-backgrounds.md) | Root foreground `bash` auto-backgrounds after 120s (or `timeout` ms); it is not killed. Subagents still kill at 120s (#93). |+| [0026](0026-foreground-bash-auto-backgrounds.md) | Root foreground `bash` auto-backgrounds after 120s (a shorter `timeout` may promote earlier); it is not killed. Subagents still kill at 120s (#93). || [0027](0027-kimi-identity-is-graff.md) | Kimi Coding User-Agent is `graff/<version>`, not a spoofed `kimi-code-cli` token. X-Msh device fields follow kimi-code's shapes. || [0028](0028-codex-session-id-is-the-cache-key.md) | Codex HTTP/WS `session_id` is the `prompt_cache_key` (openai/codex ModelClient default), not a per-process random UUID. || [0029](0029-mcp-inside-rlm-and-return-shapes.md) | Loaded MCP tools are rlm host functions; persist return shapes on the load result, never the prefix; fat MCP results auto-slim; default `-p` connects `.mcp.json` (folded, not skipped). |diff --git a/src/exec_bash.zig b/src/exec_bash.zigindex 9619495a..c76e2797 100644--- a/src/exec_bash.zig+++ b/src/exec_bash.zig@@ -1,9 +1,10 @@//! Root and subagent `bash` dispatch. Split out of exec.zig so the grok-build//! auto-background path (#620) has room without growing exec.zig.//!-//! Root foreground: spawn a job, wait up to 120s (or `timeout` ms), then-//! promote rather than kill — the process keeps running and the model gets a-//! job id. Subagents stay on the #93 kill-at-120s path (no TTY, no /jobs UI).+//! Root foreground: spawn a job, wait up to 120s (a shorter `timeout` may+//! promote earlier; a larger one cannot extend the wait), then promote+//! rather than kill — the process keeps running and the model gets a job+//! id. Subagents stay on the #93 kill-at-120s path (no TTY, no /jobs UI).const std = @import("std");const Io = std.Io;@@ -93,12 +94,15 @@ fn defaultRootWaitMs() u64 {}fn rootWaitMs(input: Value) u64 {- const t = intField(input, "timeout") orelse return defaultRootWaitMs();- if (t <= 0) return defaultRootWaitMs();- return @min(@as(u64, @intCast(t)), job_wait.wait_cap_ms);+ const bound = defaultRootWaitMs();+ const t = intField(input, "timeout") orelse return bound;+ if (t <= 0) return bound;+ // #850: timeout may shorten the foreground wait; it must not recreate the+ // #620 hang by stretching it toward the 10h job-wait cap.+ return @min(@as(u64, @intCast(t)), bound);}-test "rootWaitMs: omitted/zero use 120s; positive values clamp to the 10h cap" {+test "rootWaitMs: omitted/zero use 120s; a shorter timeout may promote earlier" {const empty = try std.json.parseFromSlice(Value, std.testing.allocator, "{}", .{});defer empty.deinit();try std.testing.expectEqual(root_wait_ms, rootWaitMs(empty.value));@@ -108,12 +112,18 @@ test "rootWaitMs: omitted/zero use 120s; positive values clamp to the 10h cap" {const custom = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":5000}", .{});defer custom.deinit();try std.testing.expectEqual(@as(u64, 5_000), rootWaitMs(custom.value));+}++test "#850: a large explicit timeout cannot extend the foreground bound" {const huge = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":999999999}", .{});defer huge.deinit();- try std.testing.expectEqual(job_wait.wait_cap_ms, rootWaitMs(huge.value));+ try std.testing.expectEqual(root_wait_ms, rootWaitMs(huge.value));+ try std.testing.expect(rootWaitMs(huge.value) < job_wait.wait_cap_ms);+ const schema = @embedFile("schema.zig");+ try std.testing.expect(std.mem.indexOf(u8, schema, "max 36000000") == null);}-test "rootWaitMs: lean unattended oneshot defaults to 15s; timeout still wins" {+test "rootWaitMs: lean unattended oneshot defaults to 15s; shorter timeout still wins" {const main_mod = @import("main.zig");const nlt = @import("no_local_tools.zig");const saved_u = main_mod.unattended;@@ -130,6 +140,9 @@ test "rootWaitMs: lean unattended oneshot defaults to 15s; timeout still wins" {const custom = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":5000}", .{});defer custom.deinit();try std.testing.expectEqual(@as(u64, 5_000), rootWaitMs(custom.value));+ const huge = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":60000}", .{});+ defer huge.deinit();+ try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMs(huge.value));main_mod.unattended = false;try std.testing.expectEqual(root_wait_ms, rootWaitMs(empty.value));}diff --git a/src/jobs_tests.zig b/src/jobs_tests.zigindex d6bce488..4feeb357 100644--- a/src/jobs_tests.zig+++ b/src/jobs_tests.zig@@ -157,6 +157,32 @@ test "#620: a still-running foreground wait promotes instead of killing" {try std.testing.expect(std.mem.indexOf(u8, snap.text, "running") != null);}+test "#850: a bounded promote leaves the child on bash_output and bash_kill" {+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;+ jobs.g_jobs = .{};+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ const id = (try jobs.spawnJob(gpa, io, "sleep 8; printf never")).id;+ defer jobs.jobsReap(gpa, io);+ const waited = try jobs.waitForeground(gpa, io, id, 200);+ defer switch (waited) {+ .running => |r| gpa.free(r.output),+ .done => |d| gpa.free(d.output),+ .cancelled => |c| gpa.free(c.output),+ };+ try std.testing.expect(waited == .running);+ const snap = try jobs.jobOutput(gpa, io, id, 0);+ defer gpa.free(snap.text);+ try std.testing.expect(std.mem.indexOf(u8, snap.text, "running") != null);+ const killed = try jobs.jobKill(gpa, io, id);+ defer gpa.free(killed.text);+ try std.testing.expect(!killed.is_error);+ try std.testing.expect(std.mem.indexOf(u8, killed.text, "killed") != null);+ const after = try jobs.jobOutput(gpa, io, id, 2_000);+ defer gpa.free(after.text);+ try std.testing.expect(std.mem.indexOf(u8, after.text, "running") == null);+}+test "#620: a short foreground command finishes as done, not a job" {if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;jobs.g_jobs = .{};diff --git a/src/net_efficiency_test.zig b/src/net_efficiency_test.zigindex c7f401a9..556094a5 100644--- a/src/net_efficiency_test.zig+++ b/src/net_efficiency_test.zig@@ -105,9 +105,7 @@ test "MCP modern connect + next list reuse one TCP connection" {var done: std.atomic.Value(bool) = .init(false);var srv: ListSrv = .{ .accepts = &accepts, .posts = &posts, .done = &done };var fut = io.async(ListSrv.run, .{ &srv, io, &listener });- defer fut.await(io);- defer done.store(true, .release);- defer if (std.Io.net.IpAddress.connect(&listener.socket.address, io, .{ .mode = .stream })) |s| s.close(io) else |_| {};+ defer joinReuseServer(io, &listener, &done, &fut);var url_buf: [64]u8 = undefined;const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/mcp", .{listener.socket.address.getPort()});@@ -230,6 +228,61 @@ test "MCP HTTP no longer omits Accept-Encoding" {try std.testing.expect(std.mem.indexOf(u8, src, "readerDecompressing") != null);}+/// #849: Zig runs `defer` in reverse source order. Stop the accept loop+/// before the wake connect, then join. A wake-before-stop leaves the+/// server blocked on `accept` with no further connection. Extra wakes+/// after 2s keep a failed cleanup from stalling `zig build test`.+fn joinReuseServer(io: Io, listener: *std.Io.net.Server, done: *std.atomic.Value(bool), fut: anytype) void {+ done.store(true, .release);+ if (std.Io.net.IpAddress.connect(&listener.socket.address, io, .{ .mode = .stream })) |s| {+ s.close(io);+ } else |_| {}+ const watchdog = struct {+ fn run(io_: Io, finished: *std.atomic.Value(bool), listener_: *std.Io.net.Server) void {+ var i: u32 = 0;+ while (i < 40) : (i += 1) {+ if (finished.load(.acquire)) return;+ io_.sleep(.fromMilliseconds(50), .awake) catch return;+ }+ if (std.Io.net.IpAddress.connect(&listener_.socket.address, io_, .{ .mode = .stream })) |s| {+ s.close(io_);+ } else |_| {}+ }+ };+ var finished: std.atomic.Value(bool) = .init(false);+ var wd = io.async(watchdog.run, .{ io, &finished, listener });+ fut.await(io);+ finished.store(true, .release);+ wd.await(io);+}++test "MCP reuse teardown stops the listener before the wake accept" {+ const src = @embedFile("net_efficiency_test.zig");+ const helper = std.mem.indexOf(u8, src, "fn joinReuseServer(").?;+ const stop = std.mem.indexOfPos(u8, src, helper, "done.store(true, .release)").?;+ const wake = std.mem.indexOfPos(u8, src, stop, "IpAddress.connect(&listener.socket.address").?;+ const join = std.mem.indexOfPos(u8, src, wake, "fut.await(io)").?;+ try std.testing.expect(stop < wake);+ try std.testing.expect(wake < join);+}++test "#849: blocked accept loop joins within a bound after stop-then-wake" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const io = std.testing.io;+ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ var listener = try std.Io.net.IpAddress.listen(&addr, io, .{});+ defer listener.deinit(io);+ var accepts: std.atomic.Value(u8) = .init(0);+ var posts: std.atomic.Value(u8) = .init(2);+ var done: std.atomic.Value(bool) = .init(false);+ var srv: ListSrv = .{ .accepts = &accepts, .posts = &posts, .done = &done };+ var fut = io.async(ListSrv.run, .{ &srv, io, &listener });+ const t0 = std.Io.Timestamp.now(io, .awake).nanoseconds;+ joinReuseServer(io, &listener, &done, &fut);+ const ms = @divTrunc(std.Io.Timestamp.now(io, .awake).nanoseconds - t0, std.time.ns_per_ms);+ try std.testing.expect(ms < 2000);+}+fn gzipAlloc(gpa: std.mem.Allocator, plain: []const u8) ![]u8 {var out_buf: [4096]u8 = undefined;var out: Io.Writer = .fixed(&out_buf);diff --git a/src/no_local_tools.zig b/src/no_local_tools.zigindex e4d8f707..f3a93cdd 100644--- a/src/no_local_tools.zig+++ b/src/no_local_tools.zig@@ -125,7 +125,7 @@ pub const lean_subagent_desc = "Spawn a sidecar for a self-contained task. Child/// One-shot tool prose (ADR 0046). Same names and JSON schemas; shorter/// descriptions so flash models start and finish instead of rereading/// essays. Do not drop to four tools (ADR 0024).-pub const lean_bash_desc = "Run /bin/sh -c in cwd. Returns stdout, stderr, exit. Foreground still running after 15s (or timeout ms) backgrounds — bash_output(wait_ms>0) waits; do not poll.";+pub const lean_bash_desc = "Run /bin/sh -c in cwd. Returns stdout, stderr, exit. Foreground still running after 15s (or a shorter timeout) backgrounds — bash_output(wait_ms>0) waits; do not poll.";pub const lean_read_file_desc = "Read a UTF-8 file. Call before editing. contains=exact-key numbered lines; start_line/end_line for a window.";pub const lean_edit_file_desc = "Replace exact text. Prefer one batched edits[] over many calls. Prefer over write_file for an existing file.";pub const lean_codedb_desc = "Indexed nav: context <task> (local) · around <name> · callpath A B · list_dir <path> · status. Prefer over bash grep/find/ls.";diff --git a/src/schema.zig b/src/schema.zigindex 88694107..61e77589 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -53,9 +53,9 @@ const empty_schema =pub const base_specs = [_]ToolSpec{.{.name = "bash",- .desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). Foreground commands that are still running after 120s (or timeout ms) are moved to the background and return a job id — the process keeps running. For long-running commands set run_in_background true to skip the wait. You are notified on completion — do not poll. bash_output(wait_ms>0) blocks until exit (up to 10h); omit wait_ms for a snapshot. Stop it with bash_kill. A background job that writes nothing and is read by nobody for 2 hours is stopped for inactivity and you are told; rerun it only if it is still needed (the user pins a long-lived server with /jobs keep).",+ .desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). Foreground commands that are still running after 120s (or a shorter timeout ms) are moved to the background and return a job id — the process keeps running. For long-running commands set run_in_background true to skip the wait. You are notified on completion — do not poll. bash_output(wait_ms>0) blocks until exit (up to 10h); omit wait_ms for a snapshot. Stop it with bash_kill. A background job that writes nothing and is read by nobody for 2 hours is stopped for inactivity and you are told; rerun it only if it is still needed (the user pins a long-lived server with /jobs keep).",.schema =- \\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "timeout": {"type": "integer", "description": "Optional foreground wait in milliseconds before auto-background (default 120000, max 36000000). 0 uses the default. Ignored when run_in_background is true."}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]}+ \\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "timeout": {"type": "integer", "description": "Optional foreground wait in milliseconds before auto-background. A shorter value promotes earlier; a larger value cannot extend past the 120s (lean -p: 15s) bound. 0 uses the default. Ignored when run_in_background is true."}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]},},.{