Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

bash: an explicit `timeout` can shorten the foreground wait, never extend it

justrach059fef60f24d
diff --git a/docs/adr/0097-explicit-bash-timeout-cannot-extend-the-foreground-wait.md b/docs/adr/0097-explicit-bash-timeout-cannot-extend-the-foreground-wait.md
new file mode 100644
index 00000000..9b21a270
--- /dev/null
+++ b/docs/adr/0097-explicit-bash-timeout-cannot-extend-the-foreground-wait.md
@@ -0,0 +1,46 @@
+# 0097. An explicit `timeout` shortens root bash's foreground wait, never extends it
+
+Status: accepted 2026-09-11
+
+## Context
+
+ADR 0026 promotes a still-running root foreground `bash` onto the job registry
+after 120s (grok-build's number). `timeout` ms was documented as replacing that
+wait — "waits up to 120s (or `timeout` ms, capped at 10h)".
+
+[#850](https://github.com/justrach/codegraff/issues/850) is that clause used the
+other way round. `rootWaitMs` returned `min(timeout, wait_cap_ms)`, so a model
+that read `timeout` as a *command deadline* — the natural reading, since every
+other `timeout` in the catalog kills — asked for an hour of foreground blocking
+and got it. `waitForeground` cannot return `.running` before its deadline, so
+the turn sat in the `· bash still running ·` pulse for the whole hour: exactly
+the failure mode [#620](https://github.com/justrach/codegraff/issues/620) closed
+(the model blocked 83 minutes, todos stuck at `0/5`), reachable again through a
+parameter instead of through a missing deadline.
+
+The schema invited it: "Optional foreground wait in milliseconds before
+auto-background (default 120000, max 36000000)", alongside a tool line reading
+"after 120s (or timeout ms)".
+
+## Decision
+
+- An explicit `timeout` may only make the foreground wait **shorter**. A larger
+ value is clamped to the effective default: 120s interactive, 15s on lean `-p`
+ (ADR 0055).
+- The default still promotes at 120s / 15s and never kills (ADR 0026).
+- `timeout` is therefore not a command lifetime. A command that genuinely has
+ to be waited on either runs with `run_in_background: true` or is waited for
+ with `bash_output(id, wait_ms>0)`, which blocks until exit (10h cap, ADR 0010).
+- The tool descriptions state the clamp and that alternative, which means the
+ generated SDKs change with them.
+
+## Consequences
+
+No `timeout` value can park a root turn in the pulse. The cost is one extra hop
+for a command the model expected to watch for minutes: at the bound it gets a
+job id plus partial output instead of the finished output, then either the exit
+notification or one `bash_output(wait_ms>0)`.
+
+Regression coverage in `src/exec_bash.zig`: a huge explicit timeout clamps to
+the bound (and to 15s on lean), and the promotion path leaves the child alive
+and reachable through `bash_output` / `bash_kill`.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8fcd3840..725315f5 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 (or a shorter `timeout` ms — ADR 0097); 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). |
@@ -106,6 +106,7 @@ record only when you need the evidence or the edge cases.
| [0093](0093-project-layout-breadth-and-directory-hints.md) | Project layout favors breadth under its caps; missing directories offer bounded sibling hints without changing confinement or ADR 0090 constraint policy. |
| [0094](0094-subagent-interrupt-is-a-cancel-file.md) | GUI Stop writes `{id}.cancel` in the activity dir; the child finishes failed even if the model returns. Not `session/cancel`. |
| [0095](0095-mcp-apps-are-isolated-result-views.md) | MCP Apps are private saved result views in isolated GUI/browser sandboxes; app tool calls require a future approval path. |
+| [0097](0097-explicit-bash-timeout-cannot-extend-the-foreground-wait.md) | An explicit `timeout` may only shorten root foreground bash's wait, never extend it past the auto-background bound (#850). |
## When to write one
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
index 08e382f5..30fe29b7 100644
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@ -6,6 +6,7 @@
//! job id. Subagents stay on the #93 kill-at-120s path (no TTY, no /jobs UI).
const std = @import("std");
+const builtin = @import("builtin");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const Value = std.json.Value;
@@ -20,7 +21,6 @@ const bash_stdout_cap = tools.bash_stdout_cap;
const bash_stderr_cap = tools.bash_stderr_cap;
const jobs = @import("jobs.zig");
-const job_wait = @import("job_wait.zig");
const exec_bash_stream = @import("exec_bash_stream.zig");
/// grok-build's default foreground wait. After this, root bash is moved to
@@ -92,13 +92,21 @@ fn defaultRootWaitMs() u64 {
return root_wait_ms;
}
+/// #850: an explicit `timeout` may promote EARLIER, never later. Letting a
+/// large value extend the wait re-opens #620 through the other door — a model
+/// that reads `timeout` as a command deadline parks the turn in the
+/// `· bash still running ·` pulse for however long it asked. The ceiling is
+/// the effective default (120s interactive, 15s on lean `-p`); the process
+/// keeps running either way, and `bash_output(id, wait_ms>0)` blocks until
+/// exit (10h cap) for a command that genuinely has to be waited on.
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 def = defaultRootWaitMs();
+ const t = intField(input, "timeout") orelse return def;
+ if (t <= 0) return def;
+ return @min(@as(u64, @intCast(t)), def);
}
-test "rootWaitMs: omitted/zero use 120s; positive values clamp to the 10h cap" {
+test "rootWaitMs: omitted/zero use 120s; a shorter timeout promotes 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,9 +116,28 @@ 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));
- 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));
+}
+
+// #850: `timeout` used to replace the promotion delay wholesale (capped only by
+// the 10h `wait_cap_ms`), so `{"timeout": 3600000}` parked the turn for an hour
+// — #620's failure mode, reachable through the parameter instead of a missing
+// deadline. It is a ceiling now, and the ceiling is the effective default.
+test "#850: a large explicit timeout cannot extend the foreground wait" {
+ const main_mod = @import("main.zig");
+ const nlt = @import("no_local_tools.zig");
+ const saved_u = main_mod.unattended;
+ const saved_l = nlt.lean;
+ defer {
+ main_mod.unattended = saved_u;
+ nlt.lean = saved_l;
+ }
+ main_mod.unattended = false;
+ const hour = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":3600000}", .{});
+ defer hour.deinit();
+ try std.testing.expectEqual(root_wait_ms, rootWaitMs(hour.value));
+ const absurd = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":999999999}", .{});
+ defer absurd.deinit();
+ try std.testing.expectEqual(root_wait_ms, rootWaitMs(absurd.value));
}
test "rootWaitMs: lean unattended oneshot defaults to 15s; timeout still wins" {
@@ -130,10 +157,42 @@ 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));
+ // #850: 15s is the ceiling on lean too — a longer ask still promotes at 15s.
+ const long = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":60000}", .{});
+ defer long.deinit();
+ try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMs(long.value));
main_mod.unattended = false;
try std.testing.expectEqual(root_wait_ms, rootWaitMs(empty.value));
}
+// The behavior half of #850: a wait bounded at the default promotes rather than
+// parking the turn, the child is NOT killed, and it stays reachable through the
+// same bash_output/bash_kill the auto-background result points the model at.
+// The 120s bound itself is the constant asserted above; 200ms stands in for the
+// expiry so the test does not sleep for the real one.
+test "#850: promotion at the bound leaves the child alive and reachable" {
+ 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 5; 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);
+ try std.testing.expectEqual(id, waited.running.id);
+ 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(std.mem.indexOf(u8, killed.text, "killed") != null);
+}
+
fn formatJobDone(gpa: Allocator, cmd: []const u8, wait: jobs.FgDone) !ToolOutput {
defer gpa.free(wait.output);
var aw: Io.Writer.Allocating = .init(gpa);
diff --git a/src/no_local_tools.zig b/src/no_local_tools.zig
index e4d8f707..df6f8227 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 ms) 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.zig
index 88694107..85a87a79 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; it may only SHORTEN the 120000 ms default — a larger value is clamped to it, never allowed to extend the wait. To wait for a genuinely long command, set run_in_background true and use bash_output(wait_ms>0), which blocks until exit (10h cap). 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"]}
,
},
.{