graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(tools): silence heartbeat so a long tool call never reads as a hang
Rach Pradhan62b66eea1ee2
diff --git a/src/exec_bash_stream.zig b/src/exec_bash_stream.zigindex b4f25dfa..139dafac 100644--- a/src/exec_bash_stream.zig+++ b/src/exec_bash_stream.zig@@ -11,6 +11,7 @@ const Io = std.Io;const engine_sink = @import("engine_sink.zig");const jobs = @import("jobs.zig");const main_mod = @import("main.zig");+const tool_pulse = @import("tool_pulse.zig");/// grok-build `StreamingSpec.max_delta_bytes` for `bash_output_chunk`.pub const max_delta_bytes: usize = 16 * 1024;@@ -23,6 +24,16 @@ pub fn attach(opts: *jobs.CappedRunOptions, live: bool, stream: *Ctx) void {if (!live) return;opts.stream = &emit;opts.stream_ctx = stream;+ opts.pulse = &pulse;+}++/// The silence half (#607): one dim chrome line per tool_pulse threshold so a+/// quiet build never reads as a hang. Not gated on /debug — it is an elapsed+/// notice (ADR 0020 keeps RAW bytes behind /debug), and --json drops it.+fn pulse(ctx: ?*anyopaque, elapsed_ms: u64) void {+ const c: *const Ctx = @ptrCast(@alignCast(ctx orelse return));+ var ebuf: [16]u8 = undefined;+ tool_pulse.emitNotice(c.io, "· bash still running · {s}", .{tool_pulse.formatElapsed(&ebuf, elapsed_ms)});}pub fn emit(ctx: ?*anyopaque, which: u8, chunk: []const u8) void {diff --git a/src/job_notify.zig b/src/job_notify.zigindex 4d8c8eb2..6cf4b988 100644--- a/src/job_notify.zig+++ b/src/job_notify.zig@@ -7,6 +7,7 @@ const Io = std.Io;const agent_mod = @import("agent.zig");const engine_sink = @import("engine_sink.zig");+const tool_pulse = @import("tool_pulse.zig");const Agent = agent_mod.Agent;pub const Notice = struct {@@ -66,6 +67,15 @@ pub fn record(io: Io, id: u32, exit_code: ?u8, killed: bool, cmd: []const u8) vo}}+/// One dim chrome line per tool_pulse threshold while a blocking bash_output+/// wait runs long (#607). ADR 0010 keeps the wait single-hop; this only tells+/// the human it is alive. Presentation pulse: --json drops it, and a session+/// with no bound sink (subagents) stays quiet.+pub fn stillRunning(io: Io, id: u32, waited_ms: u64) void {+ var ebuf: [16]u8 = undefined;+ tool_pulse.emitNotice(io, "· bash_output · job {d} still running · {s}", .{ id, tool_pulse.formatElapsed(&ebuf, waited_ms) });+}+/// Drain queued notices into `buf`. Null when nothing finished.pub fn takeWake(io: Io, buf: []u8) ?[]const u8 {mu.lockUncancelable(io);diff --git a/src/jobs.zig b/src/jobs.zigindex 586d241b..b1973ff8 100644--- a/src/jobs.zig+++ b/src/jobs.zig@@ -67,23 +67,6 @@ pub const keepReasonText = agent_worktree.keepReasonText;// identity) live in their own modules: jobs.zig is at the 600-line cap.const worktree_prune = @import("worktree_prune.zig");-/// True if the current git working tree has uncommitted *tracked* changes-/// (staged or unstaged). Untracked files (`?? …`) don't count — `git reset-/// --hard` leaves them alone, so they're safe around a worktree land.-fn gitTreeDirty(gpa: Allocator, io: Io) bool {- const r = runCapped(gpa, io, &.{ "git", "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return false;- defer {- gpa.free(r.stdout);- gpa.free(r.stderr);- }- if (!ranOk(r)) return false;- var it = std.mem.tokenizeScalar(u8, r.stdout, '\n');- while (it.next()) |line| {- if (line.len >= 2 and !std.mem.startsWith(u8, line, "??")) return true;- }- return false;-}-/// Per-turn checkpoint commit for `-w` sessions. The worktree branch is a/// throwaway scratch branch, so committing every turn is free and gives durable/// rewind points across restarts; `graff worktree merge` later --squashes the@@ -142,7 +125,7 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [// Refuse to land into a dirty tree: the conflict-recovery below resets// tracked files, which would eat uncommitted work. Untracked files (the// worktrees, traces) are fine — reset --hard leaves them be.- if (gitTreeDirty(gpa, io)) {+ if (worktree_prune.treeDirty(gpa, io)) {try out.print("✗ your working tree has uncommitted changes — commit or stash them first, then `graff worktree merge {s}`\n", .{name});return;}@@ -254,6 +237,7 @@ const Job = struct {const job_unread_cap = 256 * 1024;const job_wait = @import("job_wait.zig");const job_notify = @import("job_notify.zig");+const tool_pulse = @import("tool_pulse.zig");/// POSIX process groups; windows/wasi have none, so the group kills below and/// the job's own pgid are compiled out there (#198).@@ -409,6 +393,9 @@ pub fn spawnJob(gpa: Allocator, io: Io, cmd: []const u8) !*Job {pub fn jobOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {const deadline = job_wait.resolveDeadline(wait_ms);var waited: u64 = 0;+ // #607: one dim chrome line per silence threshold so a long blocking wait+ // never reads as a hang. ADR 0010 keeps the wait itself single-hop.+ var still = tool_pulse.Pulse{};while (true) {g_jobs.mutex.lockUncancelable(io);const job = g_jobs.find(id) orelse {@@ -453,6 +440,7 @@ pub fn jobOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {continue;};waited += 100;+ if (still.due(waited)) job_notify.stillRunning(io, id, waited);}}diff --git a/src/process_runner.zig b/src/process_runner.zigindex 4aa3aef4..dc9b121a 100644--- a/src/process_runner.zig+++ b/src/process_runner.zig@@ -10,6 +10,7 @@ const posix_process_groups = switch (builtin.os.tag) {.windows, .wasi => false,else => true,};+const tool_pulse = @import("tool_pulse.zig");const GroupId = if (posix_process_groups) std.posix.pid_t else void;const WindowsJobHandle = if (builtin.os.tag == .windows) ?std.os.windows.HANDLE else void;@@ -100,6 +101,13 @@ pub const CappedRunOptions = struct {kill_process_tree: bool = false,stream: ?StreamFn = null,stream_ctx: ?*anyopaque = null,+ /// Silence heartbeat (#607): called with ms since spawn once a run has+ /// been quiet past tool_pulse's schedule, so a long build never reads as+ /// a hang. Raw chunks still go through `stream`; this is chrome only.+ pulse: ?*const fn (ctx: ?*anyopaque, elapsed_ms: u64) void = null,+ /// Schedule overrides (tests run the real thresholds in milliseconds).+ pulse_first_ms: u64 = tool_pulse.first_silence_ms,+ pulse_interval_ms: u64 = tool_pulse.silence_interval_ms,};/// #253: RLIMIT_NOFILE as this process actually observes it. main() calls@@ -221,6 +229,10 @@ pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, stvar esc_killed = false;var timed_out = false;const started: Io.Timestamp = .now(io, .awake);+ // Silence-heartbeat clock (#607): reset whenever either pipe produces a+ // fresh byte, read by tool_pulse's schedule at each 200ms poll tick.+ var quiet_since: Io.Timestamp = started;+ var pulse: tool_pulse.Pulse = .{ .next_at_ms = options.pulse_first_ms, .interval_ms = options.pulse_interval_ms };loop: while (true) {var eof = false;multi_reader.fill(64, .{ .duration = .{ .raw = .fromMilliseconds(200), .clock = .awake } }) catch |err| switch (err) {@@ -230,6 +242,9 @@ pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, st};for (readers, caps, &saved, &streamed, [_]u8{ 0, 1 }) |reader, cap, *item, *seen, which| {const buffered = reader.buffered();+ // Fresh bytes this tick: anything past the streamed mark, or any+ // residue at all once capping started tossing what it saved.+ if ((item.* != null and buffered.len > 0) or buffered.len > seen.*) quiet_since = .now(io, .awake);if (options.stream) |fn_emit| {if (buffered.len > seen.*) {const end = if (item.* != null) @min(buffered.len, cap) else buffered.len;@@ -240,6 +255,11 @@ pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, stif (item.* == null and buffered.len > cap) item.* = try gpa.dupe(u8, buffered[0..cap]);if (item.* != null) reader.toss(buffered.len);}+ if (!eof) {+ const silence: u64 = @intCast(@max(0, quiet_since.untilNow(io, .awake).toMilliseconds()));+ if (pulse.due(silence))+ if (options.pulse) |pulse_fn| pulse_fn(options.stream_ctx, @intCast(@max(0, started.untilNow(io, .awake).toMilliseconds())));+ }if (eof) break :loop;if (Agent.esc_cancel.load(.acquire)) {esc_killed = true;@@ -275,6 +295,48 @@ pub fn ranOk(run: CappedRun) bool {return run.term == .exited and run.term.exited == 0;}+const PulseCapture = struct {+ var fired: usize = 0;+ var last_ms: u64 = 0;+ fn fire(ctx: ?*anyopaque, elapsed_ms: u64) void {+ _ = ctx;+ fired += 1;+ last_ms = elapsed_ms;+ }+};++test "#607: a quiet run fires the silence heartbeat; output resets it" {+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ PulseCapture.fired = 0;+ const quiet = try runCappedWithOptions(gpa, io, &.{ "/bin/sh", "-c", "sleep 0.45" }, 1024, 1024, 0, .{+ .pulse = PulseCapture.fire,+ .pulse_first_ms = 50,+ .pulse_interval_ms = 120,+ });+ defer {+ gpa.free(quiet.stdout);+ gpa.free(quiet.stderr);+ }+ // ~450ms of silence past a 50ms first beat at 120ms spacing: several beats.+ try std.testing.expect(PulseCapture.fired >= 2);+ try std.testing.expect(PulseCapture.last_ms >= 50);++ // A run that keeps producing never crosses the silence schedule.+ PulseCapture.fired = 0;+ const chatty = try runCappedWithOptions(gpa, io, &.{ "/bin/sh", "-c", "i=0; while [ $i -lt 12 ]; do echo tick; i=$((i+1)); sleep 0.05; done" }, 4096, 1024, 0, .{+ .pulse = PulseCapture.fire,+ .pulse_first_ms = 50,+ .pulse_interval_ms = 120,+ });+ defer {+ gpa.free(chatty.stdout);+ gpa.free(chatty.stderr);+ }+ try std.testing.expectEqual(@as(usize, 0), PulseCapture.fired);+}+/// #253: descriptor high-water probe. `dup` always hands back the LOWEST free/// slot, so claiming a fixed burst and taking the highest number returned/// counts everything the process is holding below that ceiling — unlike adiff --git a/src/tool_pulse.zig b/src/tool_pulse.zignew file mode 100644index 00000000..9a4e274f--- /dev/null+++ b/src/tool_pulse.zig@@ -0,0 +1,101 @@+//! Silence heartbeat for long-running tools — the "is it stuck?" line.+//!+//! A blocking tool call (a foreground `bash` build, a `bash_output wait_ms>0`+//! wait per ADR 0010) can hold the turn for many minutes with zero visible+//! output; #607's pre-push hook sat silent for 13 of them and the session read+//! as hung. The fix is presentation-only: after enough SILENCE, emit one dim+//! `session_notice` pulse saying how long the call has run. ADR 0020 keeps raw+//! bytes behind /debug; an elapsed line is chrome, not output. The event is a+//! pulse, so --json drops it and no wire shape changes.++const std = @import("std");+const Io = std.Io;++const engine_sink = @import("engine_sink.zig");+const main_mod = @import("main.zig");+const style = &@import("ansi.zig").style;++/// First "still running" line after this much silence…+pub const first_silence_ms: u64 = 15_000;+/// …then every interval of continued silence (reset by any new output).+pub const silence_interval_ms: u64 = 60_000;++/// Per-call schedule state. Pure: callers own the clock.+pub const Pulse = struct {+ /// Silence total that triggers the next line.+ next_at_ms: u64 = first_silence_ms,+ /// Continued-silence spacing between beats. Injectable so tests can run+ /// the real schedule without waiting out the production intervals.+ interval_ms: u64 = silence_interval_ms,++ pub fn reset(self: *Pulse) void {+ self.next_at_ms = first_silence_ms;+ }++ /// True exactly once each time accumulated silence crosses the schedule.+ pub fn due(self: *Pulse, silence_ms: u64) bool {+ if (silence_ms < self.next_at_ms) return false;+ // Align the next beat relative to the crossing so a coarse poll+ // (~200ms ticks, 100ms job waits) cannot drift into double fires.+ const over = silence_ms - self.next_at_ms;+ self.next_at_ms = silence_ms + self.interval_ms - (over % self.interval_ms);+ return true;+ }+};++/// `2m10s`-style elapsed for humans.+pub fn formatElapsed(buf: []u8, ms: u64) []const u8 {+ const s = ms / 1000;+ if (s < 60) return std.fmt.bufPrint(buf, "{d}s", .{s}) catch buf[0..0];+ const m = s / 60;+ if (m < 60) return std.fmt.bufPrint(buf, "{d}m{d:0>2}s", .{ m, s % 60 }) catch buf[0..0];+ return std.fmt.bufPrint(buf, "{d}h{d:0>2}m", .{ m / 60, m % 60 }) catch buf[0..0];+}++/// One dim chrome line per threshold. Frontend sink first (fullscreen TUI);+/// the line REPL/headless keep the process-default sink on the turn thread,+/// which a pool-thread tool cannot reach — so chrome lands straight on stdout,+/// the same privilege exec_bash_stream's live chunks (and tick_gate's cards)+/// already hold. Presentation pulse: --json drops it.+pub fn emitNotice(io: Io, comptime fmt: []const u8, args: anytype) void {+ var buf: [160]u8 = undefined;+ const text = std.fmt.bufPrint(&buf, fmt, args) catch return;+ if (engine_sink.hostedSink()) |sink| {+ sink.emit(io, .{ .session_notice = .{ .text = text, .tone = .dim } });+ return;+ }+ if (main_mod.json_mode) return;+ const w = main_mod.g_out orelse return;+ w.print("{s}{s}{s}\n", .{ style.dim, text, style.reset }) catch return;+ w.flush() catch {};+}++test "Pulse fires once per silence threshold, then on the interval" {+ var p: Pulse = .{};+ try std.testing.expect(!p.due(0));+ try std.testing.expect(!p.due(first_silence_ms - 1));+ try std.testing.expect(p.due(first_silence_ms));+ // The next beat is a full interval past the crossing, not past zero.+ try std.testing.expect(!p.due(first_silence_ms + silence_interval_ms - 1));+ try std.testing.expect(p.due(first_silence_ms + silence_interval_ms));+ // New output resets the whole schedule.+ p.reset();+ try std.testing.expect(!p.due(first_silence_ms - 1));+ try std.testing.expect(p.due(first_silence_ms));+}++test "Pulse tolerates a coarse poll skipping a beat" {+ var p: Pulse = .{};+ // A 5x-interval jump (a stalled clock) fires once, not five times.+ try std.testing.expect(p.due(5 * first_silence_ms));+ try std.testing.expect(p.due(first_silence_ms + 4 * silence_interval_ms + 1));+}++test "formatElapsed renders seconds, minutes, and hours" {+ var buf: [16]u8 = undefined;+ try std.testing.expectEqualStrings("0s", formatElapsed(&buf, 0));+ try std.testing.expectEqualStrings("59s", formatElapsed(&buf, 59_000));+ try std.testing.expectEqualStrings("1m00s", formatElapsed(&buf, 60_000));+ try std.testing.expectEqualStrings("2m10s", formatElapsed(&buf, 130_000));+ try std.testing.expectEqualStrings("1h00m", formatElapsed(&buf, 3_600_000));+}diff --git a/src/worktree_prune.zig b/src/worktree_prune.zigindex 97e92104..9757c5df 100644--- a/src/worktree_prune.zig+++ b/src/worktree_prune.zig@@ -22,6 +22,24 @@ const keepReasonText = agent_worktree.keepReasonText;const worktree_lease = @import("worktree_lease.zig");const unixMs = @import("util.zig").unixMs;+/// True if the current git working tree has uncommitted *tracked* changes+/// (staged or unstaged). Untracked files (`?? …`) don't count —+/// `git reset --hard` leaves them alone, so they are safe around a land.+/// Moved from jobs.zig, which sits against the 600-line cap.+pub fn treeDirty(gpa: Allocator, io: Io) bool {+ const r = runCapped(gpa, io, &.{ "git", "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return false;+ defer {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ }+ if (!ranOk(r)) return false;+ var it = std.mem.tokenizeScalar(u8, r.stdout, '\n');+ while (it.next()) |line| {+ if (line.len >= 2 and !std.mem.startsWith(u8, line, "??")) return true;+ }+ return false;+}+/// Age we could not establish. Never "0" — an unreadable mtime must keep the/// worktree, not make it look brand new (or, worse, infinitely old).pub const unknown_age_ms: i64 = -1;