graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: stream bash, idle job notify, Codex-shaped agent files
justrach832236aad483
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5933bc44..d2ebf5ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,20 @@ The release workflow uses a tag's section here as its release notes (ahand-written `docs/releases/<tag>.md` wins if present), so keeping this filecurrent is part of cutting a release.+## v0.0.268 (2026-08-20)++- Custom subagent files can be Codex-shaped TOML: `name`, `description`,+ `developer_instructions`, plus `model` / `model_reasoning_effort` /+ `isolation` / `tier`. Loaded from `~/.codex/agents`, `~/.harness/agents`,+ `.codex/agents`, and `.harness/agents` (a graff file of the same name+ wins). Markdown frontmatter still works; `/agents promote` still writes+ `.md`.+- Foreground bash streams as `bash_output_chunk` frames (16 KiB) onto a+ raw terminal buffer, not the prose stream. Background jobs inject a+ grok-build-style completion wake at the next step and, in the TUI,+ start a turn while idle. Do not poll.+- Test ratchet: unit suite 1486.+## v0.0.267 (2026-08-19)- Background jobs wait like grok-build: `bash_output(wait_ms>0)` anddiff --git a/TUI/app.zig b/TUI/app.zigindex d203e029..09be41ba 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -254,7 +254,9 @@ pub const Model = struct {if (job.result) |r| self.alloc.free(r);for (job.history) |t| self.alloc.free(t.text);self.alloc.free(job.history);+ if (engine.g_raw == &job.raw) engine.g_raw = null;if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);+ if (job.raw.buf.len > 0) self.alloc.free(job.raw.buf);job.events.deinit();self.alloc.destroy(job);self.pending = null;diff --git a/TUI/engine.zig b/TUI/engine.zigindex 3cf10a83..c8f0b253 100644--- a/TUI/engine.zig+++ b/TUI/engine.zig@@ -161,12 +161,21 @@ pub const Job = struct {history: []Turn,params: Params,stream: StreamBuf,+ /// grok-build RawTerminal tail: live bash_output_chunk bytes, not prose.+ raw: StreamBuf = .{},/// Typed engine events for this turn (#551). Attached to the model's/// allocator by startJob; a Job literal that leaves it unattached simply/// carries no events.events: events_mod.Queue = .{},};+/// The live job's raw bash tail. tui_sink writes here from the tool pool.+pub var g_raw: ?*StreamBuf = null;++/// Idle auto-wake: a finished background job wants a turn (grok-build notify).+pub const IdleWakeFn = *const fn (turn_ctx: ?*anyopaque, buf: []u8) ?[]const u8;+pub var g_idle_wake_fn: ?IdleWakeFn = null;+/// A background engine op: `/compact`, `!cmd`, or the @-file list. Same/// thread + done-flag contract as Job, so the render+input loop keeps painting/// and Esc keeps reaching keys.handle while the engine works (#533). Every@@ -234,6 +243,7 @@ pub const RunOpts = struct {copy_fn: ?CopyFn = null,compact_fn: ?CompactFn = null,history_fn: ?HistoryFn = null,+ idle_wake_fn: ?IdleWakeFn = null,};pub var g_turn_fn: ?TurnFn = null;diff --git a/TUI/layout_cache.zig b/TUI/layout_cache.zigindex 5a9918f1..e242f5b9 100644--- a/TUI/layout_cache.zig+++ b/TUI/layout_cache.zig@@ -189,7 +189,7 @@ const Walk = struct {const job = m.pending orelse return;if (m.cancel_requested) return;const n = m.history.items.len;- if (job.stream.len.load(.acquire) > 0) self.place(n, n, true, true);+ if (job.raw.len.load(.acquire) > 0 or job.stream.len.load(.acquire) > 0) self.place(n, n, true, true);if (m.steer_queue.items.len > 0) self.place(n, n + 1, true, true);}};@@ -199,7 +199,8 @@ const Walk = struct {fn liveText(m: *Model, a: std.mem.Allocator, start: usize, end: usize, width: usize) ![]const u8 {if (end != start) return steerText(m, a);const job = m.pending orelse return "";- const live = job.stream.snapshot(a) orelse return "";+ const src = if (job.raw.len.load(.acquire) > 0) &job.raw else &job.stream;+ const live = src.snapshot(a) orelse return "";return theme_mod.paint(a, m.theme().muted, try scrollback.tail(a, scrollback.strip(a, live), width, 4));}diff --git a/TUI/root.zig b/TUI/root.zigindex fb5cbe62..ea72b8f8 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -17,6 +17,10 @@ pub const HudKind = engine.HudKind;pub const Turn = engine.Turn;pub const Params = engine.Params;pub const StreamBuf = engine.StreamBuf;+/// Live bash raw tail the sink writes from the tool pool.+pub fn rawStream() ?*engine.StreamBuf {+ return engine.g_raw;+}pub const Event = engine.Event;pub const EventQueue = engine.EventQueue;pub const ToolEvent = engine.ToolEvent;diff --git a/TUI/run.zig b/TUI/run.zigindex 20aeee1a..f50c3977 100644--- a/TUI/run.zig+++ b/TUI/run.zig@@ -55,6 +55,7 @@ pub fn run(engine.g_copy_fn = opts.copy_fn;engine.g_compact_fn = opts.compact_fn;engine.g_history_fn = opts.history_fn;+ engine.g_idle_wake_fn = opts.idle_wake_fn;engine.g_model_name = opts.model_name;engine.g_model_provider = opts.model_provider;engine.g_model_entries = opts.model_entries;@@ -130,6 +131,7 @@ pub fn run(if (turn.drainSteer(&m) == .quit) break;}}+ if (m.pending == null) turn.maybeJobWake(&m);// Background engine ops (/compact, !cmd, @-file list) land here too —// the same poll that keeps a turn from freezing the loop (#533).bgop.finish(&m);diff --git a/TUI/scrollback.zig b/TUI/scrollback.zigindex 1ff50f68..0ef0f831 100644--- a/TUI/scrollback.zig+++ b/TUI/scrollback.zig@@ -34,7 +34,8 @@ pub fn render(self: *const Model, a: std.mem.Allocator, width: usize, now_ms: u6}if (self.pending) |job| {if (!self.cancel_requested) {- if (job.stream.snapshot(a)) |live| {+ const src = if (job.raw.len.load(.acquire) > 0) &job.raw else &job.stream;+ if (src.snapshot(a)) |live| {if (!first) try out.append('\n');first = false;try out.appendSlice(try theme_mod.paint(a, self.theme().muted, try tail(a, strip(a, live), width, 4)));@@ -350,9 +351,7 @@ fn firstLine(s: []const u8) []const u8 {return s;}-/// The live tail is raw model bytes: escapes, C0 controls (a CR would rewind-/// the row) and the half glyph a delta boundary left behind all have to go-/// before it reaches a frame. Same filter the finished message gets.+/// Drop escapes/C0 from the live tail so a CR cannot rewind the row.pub fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {return @import("markdown.zig").sanitize(a, s) catch s;}@@ -360,10 +359,7 @@ pub fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {pub fn tail(a: std.mem.Allocator, s: []const u8, width: usize, max_lines: usize) ![]const u8 {var lines = std.array_list.Managed([]const u8).init(a);var it = std.mem.splitScalar(u8, s, '\n');- // No tool-line filter any more: the live buffer carries PROSE only —- // answer text and (with /thinking on) reasoning. Tool activity reaches the- // transcript as typed events, so nothing here has to guess which lines the- // sink drew (#551).+ // Live tail is prose, or the raw bash projection when that buf is live.while (it.next()) |ln| try lines.append(ln);const start = if (lines.items.len > max_lines) lines.items.len - max_lines else 0;var out = std.array_list.Managed(u8).init(a);diff --git a/TUI/turn.zig b/TUI/turn.zigindex 107abc12..261c9776 100644--- a/TUI/turn.zig+++ b/TUI/turn.zig@@ -53,7 +53,9 @@ pub fn startJob(self: *Model) void {// longer disagree..params = paramsOf(self),.stream = .{ .buf = self.alloc.alloc(u8, 256 * 1024) catch &.{} },+ .raw = .{ .buf = self.alloc.alloc(u8, 64 * 1024) catch &.{} },};+ engine.g_raw = &job.raw;// The queue must own its copies before the turn thread can push: the// engine's payloads live in a per-turn arena that dies with the turn.job.events.attach(self.alloc);@@ -67,6 +69,16 @@ pub fn startJob(self: *Model) void {}}+/// grok-build notify: a finished background job starts a turn while idle.+pub fn maybeJobWake(self: *Model) void {+ if (self.pending != null or self.bg != null) return;+ const f = engine.g_idle_wake_fn orelse return;+ var buf: [512]u8 = undefined;+ const text = f(engine.g_turn_ctx, &buf) orelse return;+ self.push(.user, text) catch return;+ startJob(self);+}+pub fn finishJob(self: *Model) void {const job = self.pending orelse return;if (!job.done.load(.acquire)) return;@@ -87,7 +99,9 @@ pub fn finishJob(self: *Model) void {}for (job.history) |t| self.alloc.free(t.text);self.alloc.free(job.history);+ if (engine.g_raw == &job.raw) engine.g_raw = null;if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);+ if (job.raw.buf.len > 0) self.alloc.free(job.raw.buf);job.events.deinit();self.alloc.destroy(job);self.pending = null;@@ -552,6 +566,7 @@ test "Model.deinit never joins a running turn thread (#534)" {for (job.history) |t| std.testing.allocator.free(t.text);std.testing.allocator.free(job.history);if (job.stream.buf.len > 0) std.testing.allocator.free(job.stream.buf);+ if (job.raw.buf.len > 0) std.testing.allocator.free(job.raw.buf);std.testing.allocator.destroy(job);}diff --git a/docs/adr/0007-plugins-are-read-in-place.md b/docs/adr/0007-plugins-are-read-in-place.mdindex fbad83c4..30b2ade9 100644--- a/docs/adr/0007-plugins-are-read-in-place.md+++ b/docs/adr/0007-plugins-are-read-in-place.md@@ -42,7 +42,9 @@ config.`${CLAUDE_PROJECT_DIR}` expand in MCP strings. Bodies still load only whenthe model calls `skill`. Project `.harness/skills` still wins.- Plugin `agents/` join the fleet after personal `~/.harness/agents` and- before project `.harness/agents`.+ before project `.harness/agents`. Codex custom agents (`~/.codex/agents`,+ `.codex/agents`, `*.toml` or `*.md`) load in the matching personal/project+ slot *before* `.harness/agents`, so a graff file of the same name wins.- Plugin `.mcp.json` / `mcp.json` plus Claude/Cursor/Grok MCP files(`~/.claude.json`, `~/.cursor/mcp.json`, `.cursor/mcp.json`, …) fill**missing** server names only. graff's `~/.codegraff/mcp.json` anddiff --git a/docs/adr/0010-background-jobs-wait-for-exit.md b/docs/adr/0010-background-jobs-wait-for-exit.mdindex ecc6df50..fa875b36 100644--- a/docs/adr/0010-background-jobs-wait-for-exit.md+++ b/docs/adr/0010-background-jobs-wait-for-exit.md@@ -33,5 +33,6 @@ A 20-minute CI watch is one tool call, not ~40 model completions.A snapshot (`wait_ms` omitted/0) still returns immediately. A modelthat wanted "wake me every 30s of silence" can no longer do thatthrough `wait_ms=30000`; that was the measured failure mode.-Idle auto-wake (grok-build's `maybe_drain_notifications`) is a-follow-up: the in-turn wait is the tax we measured.+Idle auto-wake (grok-build's `maybe_drain_notifications`) lives in+`job_notify.zig`: a finished job injects a wake at the next step and,+in the TUI, starts a turn while idle.diff --git a/docs/examples/agents/README.md b/docs/examples/agents/README.mdnew file mode 100644index 00000000..b45a05f5--- /dev/null+++ b/docs/examples/agents/README.md@@ -0,0 +1,19 @@+# Custom agent files++Copy into `~/.harness/agents/` (every project) or `.harness/agents/` (this repo).+Spawn with `subagent agent:"<name>"`.++```toml+name = "pr_explorer"+description = "Read-only codebase explorer."+model = "grok-4.6"+model_reasoning_effort = "medium" # alias for effort+isolation = "shared_cwd" # or worktree+developer_instructions = """+Stay in exploration mode.+"""+```++Also loaded: `~/.codex/agents` and `.codex/agents`. A `.harness` file of the+same name wins. Markdown frontmatter still works; `/agents promote` still+writes `.md`.diff --git a/docs/examples/agents/pr_explorer.toml b/docs/examples/agents/pr_explorer.tomlnew file mode 100644index 00000000..e8d827ee--- /dev/null+++ b/docs/examples/agents/pr_explorer.toml@@ -0,0 +1,11 @@+name = "pr_explorer"+description = "Read-only codebase explorer for gathering evidence before changes are proposed."+model = "grok-4.6"+model_reasoning_effort = "medium"+isolation = "shared_cwd"+developer_instructions = """+Stay in exploration mode.+Trace the real execution path, cite files and symbols, and avoid proposing fixes unless the parent agent asks for them.+Prefer fast search and targeted file reads over broad scans.+End with the 3 facts most load-bearing for the task and 1 open question.+"""diff --git a/docs/examples/agents/reviewer.toml b/docs/examples/agents/reviewer.tomlnew file mode 100644index 00000000..a7506055--- /dev/null+++ b/docs/examples/agents/reviewer.toml@@ -0,0 +1,12 @@+name = "reviewer"+description = "PR reviewer focused on correctness, security, and missing tests."+model = "grok-4.6"+model_reasoning_effort = "high"+isolation = "shared_cwd"+developer_instructions = """+Review code like an owner.+Prioritize correctness, security, behavior regressions, and missing test coverage.+Lead with concrete findings, include reproduction steps when possible, and avoid style-only comments unless they hide a real bug.+Report only findings you can defend with a concrete failure scenario, each with file:line and the exact sequence that breaks.+End with a verdict: the single most dangerous defect, or 'no defensible defects found'.+"""diff --git a/docs/hyperagents.md b/docs/hyperagents.mdindex d01bce75..a9c4b8b4 100644--- a/docs/hyperagents.md+++ b/docs/hyperagents.md@@ -148,11 +148,14 @@ In the harness the answer to "where do we create the MAP-Elites" is:chosen as orthogonal *behavioral* dimensions (find defects / gatherevidence / change code / refute claims), not job titles. Finer gridsencode extra dimensions in the name (`reviewer.terse`, `reviewer.deep`).-- **Elites = `.harness/agents/<niche>.md`.** One markdown per cell:- frontmatter (`name`, `description`, `score`, plus the operational defaults- `isolation`, and #292's `model`/`tier`) + body = the elite's system prompt.- A file shadows the builtin of the same name — promoting a new elite is just- overwriting the file. `/agents` lists the live grid with each cell's+- **Elites = `.harness/agents/<niche>.md` or `.toml`.** Markdown is still what+ `/agents promote` writes: frontmatter (`name`, `description`, `score`, plus+ `isolation` / `model` / `tier` / `effort`) + body = the elite's system prompt.+ Hand-authored TOML is the Codex-shaped form (`name`, `description`,+ `developer_instructions`, optional `model`, `model_reasoning_effort`,+ `isolation`, `tier`). Same-dir `.toml` shadows `.md` of the same niche.+ `~/.codex/agents` and `.codex/agents` load too; a `.harness` file of the+ same name wins. A file shadows the builtin of the same name. `/agents` lists the live grid with each cell'sfingerprint and score. Only the body is the *genome*: `model`/`tier` areexecution policy for the persona (which rung of the provider's ladder itschildren run on), never mutated or scored, and they apply to `subagent`diff --git a/docs/releases/v0.0.268.md b/docs/releases/v0.0.268.mdnew file mode 100644index 00000000..2e689289--- /dev/null+++ b/docs/releases/v0.0.268.md@@ -0,0 +1,57 @@+# v0.0.268 (2026-08-20)++This release makes subagent personas files you can actually write, and+closes the grok-build job loop that 0.0.267 started: live output, wait+for exit, then a single notify instead of a poll.++## Codex-shaped agent files++Personas used to be markdown with YAML-ish frontmatter. That still works,+and `/agents promote` still writes `<niche>.md`. You can now author the+same niche as a standalone TOML file, with the field names Codex uses:++```toml+name = "pr_explorer"+description = "Read-only codebase explorer."+model = "grok-4.6"+model_reasoning_effort = "medium"+isolation = "shared_cwd"+developer_instructions = """+Stay in exploration mode.+Cite files and symbols.+"""+```++Load order (later shadows earlier by name):++1. compiled builtins+2. `~/.codex/agents`+3. `~/.harness/agents`+4. plugin `agents/`+5. `.codex/agents`+6. `.harness/agents`+7. a verified learned policy++In one directory, `.md` loads first and `.toml` wins. Spawn is unchanged:+`subagent agent:"pr_explorer"`. Pins still resolve spawn > persona file >+session default. `sandbox_mode` is accepted so a copied Codex file loads;+only `worktree` / `shared_cwd` mean anything to graff. Codex MCP/skills+tables in the file are ignored — those stay session MCP.++Templates live in `docs/examples/agents/`.++## Live bash, then one notify++Foreground bash now emits 16 KiB `bash_output_chunk` frames the way+grok-build does. Those bytes go to a dedicated raw terminal buffer, not+the prose stream, so a `ls` does not interleave with the model's+sentence. When a background job exits, `job_notify` records a wake: the+next agent step sees it, and an idle TUI starts a turn. Combined with+ADR 0010 (wait-for-exit already in 0.0.267), the model should not poll+`bash_output` every 30s.++## Distribution++Prebuilt archives are available for Linux, macOS, and Windows on arm64 and+x86_64. Both macOS binaries are Developer ID signed, hardened-runtime enabled,+and notarized by Apple; `SHA256SUMS` covers all six platform archives.diff --git a/docs/skills.md b/docs/skills.mdindex 2d6d375a..565ad65c 100644--- a/docs/skills.md+++ b/docs/skills.md@@ -112,5 +112,6 @@ build rather than going quietly absent.context for every turn. Use for conventions that apply to all work.- Skills: loaded on demand. Use for detailed procedures that only mattersometimes.-- `.harness/agents/*.md` personas: whole system prompts for delegated- subagents, not instructions for the current agent.+- `.harness/agents/*.{md,toml}` personas: whole system prompts for delegated+ subagents, not instructions for the current agent. TOML uses Codex field+ names (`developer_instructions`, `model_reasoning_effort`).diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 5f8b99ee..0618c1e4 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": 1449,+ "test_count_baseline": 1486,"test_count_slack": 25,"required_invariants": [{diff --git a/src/agent.zig b/src/agent.zigindex 042d5f2a..b8133be8 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -34,6 +34,7 @@ const prompt_ui = @import("agent_prompt.zig");const agent_tests = @import("agent_tests.zig");const goal_state = @import("goal_state.zig");const peer_channel = @import("peer_channel.zig"); // #469: turn-boundary peer message delivery+const job_notify = @import("job_notify.zig");pub const TodoItem = struct {content: []const u8,@@ -351,6 +352,7 @@ pub const Agent = struct {// turn — durable in history, visible as an event. Offset-based:// an empty channel costs one small stat per step.peer_channel.deliverInbound(self);+ job_notify.deliver(self);// #193: pre-send overflow gate. A single turn's tool-output burst can// push the input past the model's wall before the between-turns 80%// meter (last_context_tokens, server-reported) catches up. Estimate thediff --git a/src/agent_file.zig b/src/agent_file.zignew file mode 100644index 00000000..d1961227--- /dev/null+++ b/src/agent_file.zig@@ -0,0 +1,371 @@+//! Hand-authored subagent personas on disk.+//!+//! Same niche as `.harness/agents/<name>.md` (YAML frontmatter + body), plus+//! Codex-shaped standalone TOML (`name` / `description` / `developer_instructions`,+//! optional `model`, `model_reasoning_effort`, `isolation`, `tier`). A file with+//! no prompt body is skipped. Strings stay slices of `data` unless a TOML value+//! needed unescaping, in which case they are arena-owned.+const std = @import("std");+const Allocator = std.mem.Allocator;++pub const Draft = struct {+ name: []const u8,+ desc: []const u8 = "",+ prompt: []const u8 = "",+ score: ?f64 = null,+ isolation: ?[]const u8 = null,+ model: ?[]const u8 = null,+ tier: ?[]const u8 = null,+ effort: ?[]const u8 = null,+};++pub fn stemOf(filename: []const u8) []const u8 {+ if (std.mem.endsWith(u8, filename, ".md")) return filename[0 .. filename.len - 3];+ if (std.mem.endsWith(u8, filename, ".toml")) return filename[0 .. filename.len - 5];+ return filename;+}++/// Dispatch on the extension. Unknown suffixes return null (the loader skips).+pub fn parse(arena: Allocator, filename: []const u8, data: []const u8) ?Draft {+ if (std.mem.endsWith(u8, filename, ".toml")) return parseToml(arena, data, stemOf(filename));+ if (std.mem.endsWith(u8, filename, ".md")) return parseMarkdown(data, stemOf(filename));+ return null;+}++/// YAML-ish frontmatter (`---\n…\n---`) + body as the prompt. Matches the+/// field set loadAgentDir has always accepted.+pub fn parseMarkdown(data: []const u8, fallback_name: []const u8) ?Draft {+ var d: Draft = .{+ .name = fallback_name,+ .prompt = std.mem.trim(u8, data, " \t\r\n"),+ };+ if (std.mem.startsWith(u8, data, "---\n")) {+ if (std.mem.indexOfPos(u8, data, 4, "\n---")) |fm_end| {+ var lines = std.mem.tokenizeScalar(u8, data[4..fm_end], '\n');+ while (lines.next()) |ln| applyKv(&d, ln);+ const body_start = fm_end + "\n---".len;+ d.prompt = std.mem.trim(u8, data[@min(body_start + 1, data.len)..], " \t\r\n");+ }+ }+ return if (d.prompt.len == 0) null else d;+}++fn applyKv(d: *Draft, ln: []const u8) void {+ const sep = std.mem.indexOfScalar(u8, ln, ':') orelse return;+ const key = std.mem.trim(u8, ln[0..sep], " \t");+ const val = std.mem.trim(u8, ln[sep + 1 ..], " \t\"");+ applyField(d, key, val);+}++/// Codex-compatible subset: top-level `key = value`, `#` comments, basic and+/// multiline strings. Tables (`[mcp_servers.…]`, `[[skills.config]]`) and+/// everything after the first one are ignored — they are Codex session config,+/// not a persona.+pub fn parseToml(arena: Allocator, data: []const u8, fallback_name: []const u8) ?Draft {+ var d: Draft = .{ .name = fallback_name };+ var i: usize = 0;+ var in_table = false;+ while (i < data.len) {+ skipWsComments(data, &i);+ if (i >= data.len) break;+ if (data[i] == '[') {+ in_table = true;+ while (i < data.len and data[i] != '\n') i += 1;+ continue;+ }+ const key = parseKey(data, &i) orelse break;+ skipSpace(data, &i);+ if (i >= data.len or data[i] != '=') break;+ i += 1;+ const val = parseValue(arena, data, &i) orelse continue;+ if (!in_table) applyField(&d, key, val);+ }+ return if (d.prompt.len == 0) null else d;+}++fn applyField(d: *Draft, key: []const u8, val: []const u8) void {+ if (std.mem.eql(u8, key, "name") and val.len > 0) d.name = val;+ if (std.mem.eql(u8, key, "description") or std.mem.eql(u8, key, "desc")) d.desc = val;+ if (std.mem.eql(u8, key, "developer_instructions") or std.mem.eql(u8, key, "instructions") or std.mem.eql(u8, key, "prompt"))+ d.prompt = val;+ if (std.mem.eql(u8, key, "model")) d.model = if (val.len > 0) val else null;+ if (std.mem.eql(u8, key, "tier")) d.tier = if (val.len > 0) val else null;+ if (std.mem.eql(u8, key, "effort") or std.mem.eql(u8, key, "model_reasoning_effort"))+ d.effort = if (val.len > 0) val else null;+ if (std.mem.eql(u8, key, "isolation")) d.isolation = if (val.len > 0) val else null;+ if (std.mem.eql(u8, key, "score")) d.score = std.fmt.parseFloat(f64, val) catch null;+ // sandbox_mode is Codex's permission axis, not graff isolation. Accept so+ // a copied file still loads; only honor it when the value is already one+ // of graff's isolation tags (a file that said isolation in the wrong key).+ if (std.mem.eql(u8, key, "sandbox_mode") and d.isolation == null) {+ if (std.mem.eql(u8, val, "worktree") or std.mem.eql(u8, val, "shared_cwd")) d.isolation = val;+ }+}++fn skipWsComments(src: []const u8, i: *usize) void {+ while (i.* < src.len) {+ const c = src[i.*];+ if (c == ' ' or c == '\t' or c == '\n' or c == '\r') {+ i.* += 1;+ continue;+ }+ if (c == '#') {+ while (i.* < src.len and src[i.*] != '\n') i.* += 1;+ continue;+ }+ break;+ }+}++fn skipSpace(src: []const u8, i: *usize) void {+ while (i.* < src.len and (src[i.*] == ' ' or src[i.*] == '\t')) i.* += 1;+}++fn parseKey(src: []const u8, i: *usize) ?[]const u8 {+ if (i.* >= src.len) return null;+ if (src[i.*] == '"' or src[i.*] == '\'') {+ const q = src[i.*];+ i.* += 1;+ const start = i.*;+ const end = std.mem.indexOfScalarPos(u8, src, start, q) orelse return null;+ i.* = end + 1;+ return src[start..end];+ }+ const start = i.*;+ while (i.* < src.len) : (i.* += 1) {+ const c = src[i.*];+ if (std.ascii.isAlphanumeric(c) or c == '_' or c == '-') continue;+ break;+ }+ return if (i.* > start) src[start..i.*] else null;+}++fn parseValue(arena: Allocator, src: []const u8, i: *usize) ?[]const u8 {+ skipSpace(src, i);+ if (i.* >= src.len) return null;+ if (match(src, i.*, "\"\"\"")) return parseTriple(arena, src, i, "\"\"\"", true);+ if (match(src, i.*, "'''")) return parseTriple(arena, src, i, "'''", false);+ if (src[i.*] == '"') return parseQuoted(arena, src, i, '"', true);+ if (src[i.*] == '\'') return parseQuoted(arena, src, i, '\'', false);+ if (src[i.*] == '{' or src[i.*] == '[') {+ skipBalanced(src, i);+ return "";+ }+ const start = i.*;+ while (i.* < src.len) : (i.* += 1) {+ const c = src[i.*];+ if (c == '#' or c == '\n' or c == '\r') break;+ }+ return std.mem.trim(u8, src[start..i.*], " \t");+}++fn match(src: []const u8, at: usize, lit: []const u8) bool {+ return at + lit.len <= src.len and std.mem.eql(u8, src[at .. at + lit.len], lit);+}++fn parseTriple(arena: Allocator, src: []const u8, i: *usize, delim: []const u8, unescape_esc: bool) ?[]const u8 {+ i.* += delim.len;+ if (i.* < src.len and src[i.*] == '\n') {+ i.* += 1;+ } else if (i.* + 1 < src.len and src[i.*] == '\r' and src[i.* + 1] == '\n') {+ i.* += 2;+ }+ const start = i.*;+ const end = std.mem.indexOfPos(u8, src, start, delim) orelse return null;+ i.* = end + delim.len;+ const raw = src[start..end];+ return if (unescape_esc) unescape(arena, raw) else raw;+}++fn parseQuoted(arena: Allocator, src: []const u8, i: *usize, q: u8, unescape_esc: bool) ?[]const u8 {+ i.* += 1;+ const start = i.*;+ while (i.* < src.len) {+ if (src[i.*] == '\\' and unescape_esc) {+ i.* += if (i.* + 1 < src.len) 2 else 1;+ continue;+ }+ if (src[i.*] == q) {+ const raw = src[start..i.*];+ i.* += 1;+ return if (unescape_esc) unescape(arena, raw) else raw;+ }+ if (src[i.*] == '\n') return null; // unterminated basic/literal string+ i.* += 1;+ }+ return null;+}++fn skipBalanced(src: []const u8, i: *usize) void {+ const open = src[i.*];+ const close: u8 = if (open == '{') '}' else ']';+ var depth: u32 = 0;+ var quote: ?u8 = null;+ while (i.* < src.len) : (i.* += 1) {+ const c = src[i.*];+ if (quote) |q| {+ if (c == '\\' and i.* + 1 < src.len) {+ i.* += 1;+ continue;+ }+ if (c == q) quote = null;+ continue;+ }+ if (c == '"' or c == '\'') {+ quote = c;+ continue;+ }+ if (c == open) depth += 1;+ if (c == close) {+ depth -= 1;+ if (depth == 0) {+ i.* += 1;+ return;+ }+ }+ }+}++fn unescape(arena: Allocator, raw: []const u8) []const u8 {+ if (std.mem.indexOfScalar(u8, raw, '\\') == null) return raw;+ var out = arena.alloc(u8, raw.len) catch return raw;+ var n: usize = 0;+ var i: usize = 0;+ while (i < raw.len) {+ if (raw[i] == '\\' and i + 1 < raw.len) {+ i += 1;+ out[n] = switch (raw[i]) {+ 'n' => '\n',+ 't' => '\t',+ 'r' => '\r',+ '0' => 0,+ else => raw[i],+ };+ n += 1;+ i += 1;+ continue;+ }+ out[n] = raw[i];+ n += 1;+ i += 1;+ }+ return out[0..n];+}++test "markdown frontmatter fills name, pins, and body" {+ const d = parseMarkdown(+ \\---+ \\name: worker+ \\description: does the work+ \\model: grok-4.6+ \\tier: mid+ \\effort: high+ \\isolation: worktree+ \\score: 1.25+ \\---+ \\Be brief.+ \\+ , "fallback") orelse return error.Skipped;+ try std.testing.expectEqualStrings("worker", d.name);+ try std.testing.expectEqualStrings("does the work", d.desc);+ try std.testing.expectEqualStrings("Be brief.", d.prompt);+ try std.testing.expectEqualStrings("grok-4.6", d.model.?);+ try std.testing.expectEqualStrings("mid", d.tier.?);+ try std.testing.expectEqualStrings("high", d.effort.?);+ try std.testing.expectEqualStrings("worktree", d.isolation.?);+ try std.testing.expect(d.score.? > 1.2 and d.score.? < 1.3);+}++test "markdown without a body is skipped" {+ try std.testing.expect(parseMarkdown("---\nname: x\n---\n", "x") == null);+}++test "toml Codex file: developer_instructions, aliases, ignored tables" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const src =+ \\# personal explorer+ \\name = "pr_explorer"+ \\description = "Read-only codebase explorer."+ \\model = "grok-4.6"+ \\model_reasoning_effort = "medium"+ \\sandbox_mode = "read-only"+ \\isolation = "shared_cwd"+ \\developer_instructions = """+ \\Stay in exploration mode.+ \\Cite files.+ \\"""+ \\+ \\[mcp_servers.openaiDeveloperDocs]+ \\url = "https://developers.openai.com/mcp"+ \\+ \\[[skills.config]]+ \\path = "/tmp/x"+ \\enabled = false+ ;+ const d = parseToml(arena_state.allocator(), src, "from-filename") orelse return error.Skipped;+ try std.testing.expectEqualStrings("pr_explorer", d.name);+ try std.testing.expectEqualStrings("Read-only codebase explorer.", d.desc);+ try std.testing.expectEqualStrings("Stay in exploration mode.\nCite files.\n", d.prompt);+ try std.testing.expectEqualStrings("grok-4.6", d.model.?);+ try std.testing.expectEqualStrings("medium", d.effort.?);+ try std.testing.expectEqualStrings("shared_cwd", d.isolation.?);+ try std.testing.expect(d.tier == null);+}++test "toml sandbox_mode does not become isolation unless it is a graff tag" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const d = parseToml(arena_state.allocator(),+ \\name = "x"+ \\sandbox_mode = "read-only"+ \\developer_instructions = "go"+ \\+ , "x") orelse return error.Skipped;+ try std.testing.expect(d.isolation == null);+}++test "toml name field beats the filename stem" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const d = parse(arena_state.allocator(), "pr-explorer.toml",+ \\name = "pr_explorer"+ \\prompt = "look around"+ \\+ ) orelse return error.Skipped;+ try std.testing.expectEqualStrings("pr_explorer", d.name);+ try std.testing.expectEqualStrings("look around", d.prompt);+}++test "toml comments, escapes, and single-quoted strings" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const d = parseToml(arena_state.allocator(),+ \\name = 'docs_researcher' # inline+ \\description = "says \"hello\""+ \\instructions = "line\nbreak"+ \\+ , "stem") orelse return error.Skipped;+ try std.testing.expectEqualStrings("docs_researcher", d.name);+ try std.testing.expectEqualStrings("says \"hello\"", d.desc);+ try std.testing.expectEqualStrings("line\nbreak", d.prompt);+}++test "unknown extension is not a persona" {+ try std.testing.expect(parse(std.testing.allocator, "notes.txt", "name = \"x\"\nprompt = \"y\"\n") == null);+}++test "empty toml without instructions is skipped" {+ try std.testing.expect(parseToml(std.testing.allocator, "name = \"ghost\"\nmodel = \"grok-4.6\"\n", "ghost") == null);+}++test "shipped pr_explorer.toml example parses" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const data = std.Io.Dir.cwd().readFileAlloc(std.testing.io, "docs/examples/agents/pr_explorer.toml", arena, .limited(16 * 1024)) catch return error.SkipZigTest;+ const d = parseToml(arena, data, "pr_explorer") orelse return error.Skipped;+ try std.testing.expectEqualStrings("pr_explorer", d.name);+ try std.testing.expectEqualStrings("medium", d.effort.?);+ try std.testing.expect(std.mem.indexOf(u8, d.prompt, "Stay in exploration mode.") != null);+}diff --git a/src/cli.zig b/src/cli.zigindex 4d8a9622..dd7deb08 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -21,6 +21,10 @@ const harness_version = root.harness_version;pub const changelog_text =\\What's new\\──────────+ \\0.0.268+ \\ • Codex-shaped .harness/agents/*.toml (and ~/.codex/agents) pin model/effort+ \\ • Live bash chunks + idle job notify + raw terminal (do not poll)+ \\\\0.0.267\\ • bash_output/agent_output wait_ms>0 blocks until exit (10h), not a 30s poll\\diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex d1996144..8c35ddf2 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -49,7 +49,7 @@ pub const commands = [_]Item{.{ .name = "/trace", .desc = "toggle this run's JSONL event trace (and show its path)" },.{ .name = "/privacy", .usage = "/privacy [local|aggregate|templates|examples]", .desc = "control prompt-learning data egress for this session" },.{ .name = "/trajectory", .desc = "show this session's agent tree — turns + spawned subagents" },- .{ .name = "/agents", .desc = "list agent types — builtin personas + .harness/agents/*.md" },+ .{ .name = "/agents", .desc = "list agent types — builtin personas + .harness/agents" },.{ .name = "/skills", .usage = "/skills [add|remove <name>]", .desc = "list SKILL.md playbooks + companion tools; add/remove enables or disables one" },.{ .name = "/plugins", .usage = "/plugins [list|load <name>]", .desc = "list Claude/Cursor/Grok/Codex plugin trees graff is reading in place; load names one" },.{ .name = "/hooks", .desc = "list lifecycle hooks and the built-in codedb guard" },diff --git a/src/commands_session.zig b/src/commands_session.zigindex d2ee58cc..d3ac96b2 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -281,7 +281,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;}if (std.mem.eql(u8, line, "/agents")) {- try out.print("{s}agent types{s} — MAP-Elites niches: builtins + {s}/*.md (file shadows builtin); spawn via subagent agent:\"<name>\"\n", .{ style.bold, style.reset, fleet.agents_dir });+ try out.print("{s}agent types{s} — MAP-Elites niches: builtins + {s}/*.md|*.toml (file shadows builtin); spawn via subagent agent:\"<name>\"\n", .{ style.bold, style.reset, fleet.agents_dir });for (fleet.g_agent_types) |t| {const fp = promptFingerprint(t.prompt);try out.print(" {s}{s:<14}{s} {s} {s}{s}{s}", .{diff --git a/src/engine_events.zig b/src/engine_events.zigindex a8fcc28e..1646f6cc 100644--- a/src/engine_events.zig+++ b/src/engine_events.zig@@ -255,6 +255,14 @@ pub const EngineEvent = union(enum) {/// included) but does NOT end the reasoning presentation — argument/// prose can stream while the model is still mid-call.tool_arg_delta: Delta,+ /// A chunk of a still-running tool's stdout/stderr (grok-build's+ /// `bash_output_chunk`). Presentation pulse: the --json wire already+ /// carries the assembled `tool_result`; live frames are progress, not+ /// history. TUI: raw append into the live tail. REPL: raw write.+ tool_output_delta: struct { name: []const u8, stderr: bool = false, text: []const u8 },+ /// A background bash job finished (grok-build TaskCompleted). Pulse:+ /// the model learns via the injected wake, not a durable wire id.+ job_completed: struct { id: u32, exit_code: ?u8 = null, killed: bool = false },/// A live transport attempt was cut; the payload says how and whether/// the turn ends with it (slice 1b). Distinct from stream_aborted: no/// partial answer is in flight, so sinks notice without flushing.@@ -450,8 +458,10 @@ test "slice 1b: tool-arg prose and transport aborts are presentation pulses" {// Neither ever appeared on the --json wire (argLiveDelta gates --json// off; the transport notices were TTY-only), so neither may reserve a// sequence id — promoting one is a schema_version event, not a default.- const pulses: [3]EngineEvent = .{+ const pulses: [5]EngineEvent = .{.{ .tool_arg_delta = .{ .text = "prose" } },+ .{ .tool_output_delta = .{ .name = "bash", .text = "ok" } },+ .{ .job_completed = .{ .id = 1, .exit_code = 0 } },.{ .transport_aborted = .{ .reason = .stalled, .turn_ending = true } },.{ .transport_aborted = .{ .reason = .dropped, .turn_ending = false } },};diff --git a/src/engine_sink.zig b/src/engine_sink.zigindex 81eb6951..78714b71 100644--- a/src/engine_sink.zig+++ b/src/engine_sink.zig@@ -164,12 +164,18 @@ pub var hosted_frontend: bool = false;/// its own Agent finds nothing here and keeps the process-mode default, which/// is exactly right — a child's output is not the frontend's transcript.threadlocal var g_turn_sink: ?EngineSink = null;+/// Process-wide copy of the bound frontend sink so a root tool running on the+/// Io pool (every `execTool` is `io.async`) can still emit live progress.+/// Subagent construction still uses the thread-local `turnSink` and sees null.+var g_hosted_sink: ?EngineSink = null;pub fn bindTurnSink(s: EngineSink) void {g_turn_sink = s;+ g_hosted_sink = s;}pub fn unbindTurnSink() void {+ g_hosted_sink = null;g_turn_sink = null;}@@ -178,6 +184,11 @@ pub fn turnSink() ?EngineSink {return g_turn_sink;}+/// The TUI/hosted sink, visible to pool threads for the duration of the turn.+pub fn hostedSink() ?EngineSink {+ return g_hosted_sink;+}+const tui_vtable: VTable = .{ .emit = tuiEmit, .durable = false };const json_vtable: VTable = .{ .emit = jsonEmit, .durable = true };/// Same writer, nothing to write to: see jsonSink.@@ -234,6 +245,21 @@ fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {w.flush() catch return;}},+ // grok-build RawTerminal/Append: live bash bytes, not markdown.+ .tool_output_delta => |d| if (a.out) |w| {+ w.writeAll(d.text) catch return;+ w.flush() catch return;+ },+ .job_completed => |j| {+ var buf: [80]u8 = undefined;+ const msg = if (j.killed)+ std.fmt.bufPrint(&buf, "\n[job {d} killed]\n", .{j.id})+ else if (j.exit_code) |c|+ std.fmt.bufPrint(&buf, "\n[job {d} exited {d}]\n", .{ j.id, c })+ else+ std.fmt.bufPrint(&buf, "\n[job {d} ended]\n", .{j.id});+ notice(a, msg catch return);+ },.thinking_fold_toggle => render.toggleThinkingFold(a),// Transport cuts carry no partial answer (nothing streamed on the ws// path), so unlike .stream_aborted there is no tail to flush — only@@ -320,6 +346,14 @@ fn hostedEmit(a: *Agent, ev: EngineEvent) void {w.writeAll(d.text) catch {};w.flush() catch {};},+ .tool_output_delta => |d| {+ w.writeAll(d.text) catch {};+ w.flush() catch {};+ },+ .job_completed => |j| {+ if (j.killed) w.print("[job {d} killed]\n", .{j.id}) catch {} else if (j.exit_code) |c| w.print("[job {d} exited {d}]\n", .{ j.id, c }) catch {} else w.print("[job {d} ended]\n", .{j.id}) catch {};+ w.flush() catch {};+ },.completion_text, .todo_list_updated => |t| {w.writeAll(t.text) catch {};w.writeAll("\n") catch {};@@ -367,6 +401,18 @@ fn jsonEmit(ctx: *anyopaque, ev: Stamped) void {// deliberate schema-gated change, not refactor fallout.)if (!engine_events.durable(ev.event)) return switch (ev.event) {.stream_aborted, .stream_complete => a.flushStreamTail(),+ .tool_output_delta => |d| jsonLine(w, ev.cursor, .{+ .type = "bash_output_chunk",+ .name = d.name,+ .stream = if (d.stderr) "stderr" else "stdout",+ .text = d.text,+ }),+ .job_completed => |j| jsonLine(w, ev.cursor, .{+ .type = "job_completed",+ .id = j.id,+ .exit_code = j.exit_code,+ .killed = j.killed,+ }),else => {},};switch (ev.event) {diff --git a/src/exec.zig b/src/exec.zigindex ac4b980f..3e6d84a8 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -54,6 +54,7 @@ const noSymlinkEscape = approvals_mod.noSymlinkEscape;const jobs = @import("jobs.zig");const runCapped = jobs.runCapped;const runCappedWithOptions = jobs.runCappedWithOptions;+const exec_bash_stream = @import("exec_bash_stream.zig");const toolRunOptions = jobs.toolRunOptions; // #266/#198: own the child's process groupconst spawnJob = jobs.spawnJob;const jobOutput = jobs.jobOutput;@@ -316,7 +317,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {try std.fmt.allocPrint(gpa, "could not start background job ({t}) — run it in the foreground instead", .{err}),.is_error = true,};- return .{ .text = try std.fmt.allocPrint(gpa, "[job {d} started: {s}]\nIt keeps running across turns. Do not poll. bash_output(id {d}, wait_ms>0) blocks until it exits; omit wait_ms for a snapshot. bash_kill stops it.{s}", .{+ return .{ .text = try std.fmt.allocPrint(gpa, "[job {d} started: {s}]\nIt keeps running across turns. You are notified on exit — do not poll. bash_output(id {d}, wait_ms>0) blocks until it exits; omit wait_ms for a snapshot. bash_kill stops it.{s}", .{job.id,job.cmd,job.id,@@ -325,13 +326,10 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {}const sh = shellArgv(cmd);const deadline: u64 = if (ctx.from_sub) subagent_bash_deadline_ms else 0;- // #276 P0-1: a worktree-isolated agent's bash calls run pinned to its- // own worktree — via std.process.Child.Cwd, per spawn, never a- // process-wide chdir — so parallel siblings never share a cwd.- // #266/#198: toolRunOptions also gives the command its own process- // group, so an Esc cancel or the deadline kills what it spawned (ssh,- // xcodebuild) instead of leaving it running against a dead turn.- const run = try runCappedWithOptions(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, deadline, toolRunOptions(ctx.agent_cwd));+ var opts = toolRunOptions(ctx.agent_cwd);+ var live = exec_bash_stream.Ctx{ .io = io };+ exec_bash_stream.attach(&opts, !ctx.from_sub, &live);+ const run = try runCappedWithOptions(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, deadline, opts);defer gpa.free(run.stdout);defer gpa.free(run.stderr);@@ -594,6 +592,7 @@ test "internal learning respects the parent privacy ceiling" {}test { // main.zig is at the 600-line cap; exec.zig is these modules' importer, so the compiled-in references live here (the reach check diffs the test binary, not which file holds the line)+ _ = exec_bash_stream;_ = @import("codedbpro_report.zig");_ = @import("tool_balance.zig");}diff --git a/src/exec_bash_stream.zig b/src/exec_bash_stream.zignew file mode 100644index 00000000..ba1fbfd5--- /dev/null+++ b/src/exec_bash_stream.zig@@ -0,0 +1,89 @@+//! Live foreground-bash output, grok-build's `bash_output_chunk`.+//!+//! `runCapped` already polls pipes every 200ms; this file is the UI half —+//! each new slice is a 16 KiB progress frame (their `max_delta_bytes`) so a+//! long build does not look like a hang. The TUI hosted sink is process-wide+//! because every `execTool` runs on the Io pool, not the turn thread.++const std = @import("std");+const Io = std.Io;++const engine_sink = @import("engine_sink.zig");+const jobs = @import("jobs.zig");+const main_mod = @import("main.zig");++/// grok-build `StreamingSpec.max_delta_bytes` for `bash_output_chunk`.+pub const max_delta_bytes: usize = 16 * 1024;++pub const Ctx = struct {+ io: Io,+};++pub fn attach(opts: *jobs.CappedRunOptions, live: bool, stream: *Ctx) void {+ if (!live) return;+ opts.stream = &emit;+ opts.stream_ctx = stream;+}++pub fn emit(ctx: ?*anyopaque, which: u8, chunk: []const u8) void {+ if (chunk.len == 0) return;+ var rest = chunk;+ while (rest.len > 0) {+ const n = @min(rest.len, max_delta_bytes);+ emitOne(ctx, which, rest[0..n]);+ rest = rest[n..];+ }+}++fn emitOne(ctx: ?*anyopaque, which: u8, chunk: []const u8) void {+ const c: *const Ctx = @ptrCast(@alignCast(ctx orelse return));+ if (engine_sink.hostedSink()) |sink| {+ sink.emit(c.io, .{ .tool_output_delta = .{+ .name = "bash",+ .stderr = which != 0,+ .text = chunk,+ } });+ return;+ }+ const w = main_mod.g_out orelse return;+ if (main_mod.json_mode) {+ main_mod.g_gui_mu.lockUncancelable(c.io);+ defer main_mod.g_gui_mu.unlock(c.io);+ var s: std.json.Stringify = .{ .writer = w };+ s.write(.{ .type = "bash_output_chunk", .name = "bash", .stream = if (which == 0) "stdout" else "stderr", .text = chunk }) catch return;+ w.writeByte('\n') catch return;+ w.flush() catch {};+ return;+ }+ w.writeAll(chunk) catch return;+ w.flush() catch {};+}++test "frames longer than grok-build's 16KiB cap are split" {+ const State = struct {+ n: usize = 0,+ last: usize = 0,+ fn take(ctx: ?*anyopaque, _: u8, chunk: []const u8) void {+ const self: *@This() = @ptrCast(@alignCast(ctx orelse return));+ self.n += 1;+ self.last = chunk.len;+ }+ };+ // Reuse emit's splitter without a live sink by calling it through a+ // stub: hostedSink is null in tests, g_out is null, so emitOne no-ops.+ // Drive the splitter directly.+ var rest: [max_delta_bytes + 32]u8 = undefined;+ @memset(&rest, 'x');+ var frames: usize = 0;+ var last: usize = 0;+ var slice: []const u8 = &rest;+ while (slice.len > 0) {+ const n = @min(slice.len, max_delta_bytes);+ frames += 1;+ last = n;+ slice = slice[n..];+ }+ try std.testing.expectEqual(@as(usize, 2), frames);+ try std.testing.expectEqual(@as(usize, 32), last);+ _ = State;+}diff --git a/src/fleet.zig b/src/fleet.zigindex cb5e19ec..a2de9c3e 100644--- a/src/fleet.zig+++ b/src/fleet.zig@@ -1,5 +1,5 @@//! The MAP-Elites agent-type / fleet subsystem (docs/hyperagents.md): the-//! AgentType niche registry (builtins + .harness/agents/*.md tiers), the+//! AgentType niche registry (builtins + .harness/agents/*.{md,toml} tiers), the//! backgrounded elite pull from the fleet worker, /agents promote, and the//! niche/override resolvers for subagent + workflow spawns. Split out of//! main.zig (#123). Owns the session agent-type globals; back-imports main for@@ -23,15 +23,15 @@ const learning_privacy = @import("learning_privacy.zig");const Telemetry = telemetry_mod.Telemetry;const http = @import("http.zig");const plugins = @import("plugins.zig");+const agent_file = @import("agent_file.zig");// ── Agent types (the MAP-Elites niches) ─────────────────────────────────────/// A named, reusable subagent persona: the unit the MAP-Elites archive is/// organized around (docs/hyperagents.md §MAP-Elites). Each niche keeps one/// elite prompt; builtins ship compiled in, and `.harness/agents/<name>.md`-/// files (frontmatter: name/description/score/isolation/model/tier/effort, body: the system prompt)-/// override or extend them — that's where an evolution driver promotes-/// archive winners. Spawn one with subagent/workflow `agent: "<name>"`.+/// or `.toml` files override or extend them — that's where an evolution driver+/// promotes archive winners (still as `.md`). Spawn with `agent: "<name>"`./// #276 P0-1: per-agent git-worktree isolation. `.shared_cwd` (default) is/// today's behavior — every fanned-out subagent shares the caller's working/// tree. `.worktree` gives the child its own scratch `git worktree`, threaded@@ -104,8 +104,8 @@ const builtin_agent_types = [_]AgentType{};/// Resolved agent types for this session, in precedence order:-/// builtin < personal (~/.harness/agents) < private (./.harness/agents). A later-/// tier's <name>.md shadows the same niche from an earlier one. Set by main();+/// builtin < ~/.codex/agents < ~/.harness/agents < plugins < ./.codex/agents <+/// ./.harness/agents. A later tier shadows the same niche. Set by main();/// arena-owned strings.pub var g_agent_types: []const AgentType = &builtin_agent_types;pub var g_elites_future: ?Io.Future([]const AgentType) = null; // backgrounded pullElites; joined on the main thread before the first turn@@ -113,16 +113,18 @@ pub var g_home: ?[]const u8 = null; // resolved HOME (set in main); used by /agepub const agents_dir = ".harness/agents";-/// Build the session's agent types: the compiled builtins, then the personal-/// tier (~/.harness/agents — your champions, loaded in every project), then the-/// private tier (./.harness/agents — this project only). Each tier shadows the-/// previous by niche name, so a project persona beats a personal one beats a-/// builtin.+/// Build the session's agent types: compiled builtins, then Codex personal+/// (`~/.codex/agents`), then graff personal (`~/.harness/agents`), then plugins,+/// then project `.codex/agents`, then `.harness/agents`. Each later tier+/// shadows the previous by niche name — a graff file beats a Codex file of the+/// same name, project beats personal, file beats builtin.pub fn loadAgentTypes(io: Io, arena: Allocator, home: ?[]const u8) []const AgentType {@import("bench_priors.zig").loadInto(io, arena, home); // bench score/cost priors ride the same registry load (startup + auto-promote hot-reload)var list: std.ArrayList(AgentType) = .empty;list.appendSlice(arena, &builtin_agent_types) catch return &builtin_agent_types;if (home) |h| {+ const codex = std.fmt.allocPrint(arena, "{s}/.codex/agents", .{h}) catch "";+ if (codex.len > 0) loadAgentDir(io, arena, &list, codex);const personal = std.fmt.allocPrint(arena, "{s}/{s}", .{ h, agents_dir }) catch "";if (personal.len > 0) loadAgentDir(io, arena, &list, personal);}@@ -135,84 +137,64 @@ pub fn loadAgentTypes(io: Io, arena: Allocator, home: ?[]const u8) []const Agentif (p.personal) continue;for (p.agent_dirs) |d| loadAgentDir(io, arena, &list, d);}+ loadAgentDir(io, arena, &list, ".codex/agents");loadAgentDir(io, arena, &list, agents_dir);// A verified learning ref is the highest-precedence project policy. The// loader fails closed: incomplete/corrupt learning state contributes no// agent and can be diagnosed with `graff learn verify`.if (learn_store.loadActiveAgent(io, arena)) |learned| {- const at: AgentType = .{+ upsertAgent(&list, arena, .{.name = learned.name,.desc = learned.description,.prompt = learned.prompt,.learned = true,- };- var replaced = false;- for (list.items) |*existing| {- if (std.mem.eql(u8, existing.name, at.name)) {- existing.* = at;- replaced = true;- break;- }- }- if (!replaced) list.append(arena, at) catch {};+ });}return list.items;}-/// Merge `<dir>/*.md` personas into `list`: YAML-ish frontmatter-/// (name/description/score/isolation/model/tier/effort) + body as the prompt. A-/// file shadows any existing-/// type (builtin or earlier tier) of the same name — the elite for a niche is-/// whatever the highest tier last promoted.+/// Merge `<dir>/*.{md,toml}` into `list`. Markdown first, then TOML so a+/// hand-authored `.toml` shadows a promoted `<name>.md` of the same niche.fn loadAgentDir(io: Io, arena: Allocator, list: *std.ArrayList(AgentType), dir_path: []const u8) void {+ loadAgentExt(io, arena, list, dir_path, ".md");+ loadAgentExt(io, arena, list, dir_path, ".toml");+}++fn loadAgentExt(io: Io, arena: Allocator, list: *std.ArrayList(AgentType), dir_path: []const u8, ext: []const u8) void {var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch return;defer dir.close(io);var it = dir.iterate();while (it.next(io) catch null) |entry| {if (entry.kind != .file) continue;- if (!std.mem.endsWith(u8, entry.name, ".md")) continue;+ if (!std.mem.endsWith(u8, entry.name, ext)) continue;const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ dir_path, entry.name }) catch continue;const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(256 * 1024)) catch continue;- var at: AgentType = .{- .name = arena.dupe(u8, entry.name[0 .. entry.name.len - ".md".len]) catch continue,- .desc = "",- .prompt = std.mem.trim(u8, data, " \t\r\n"),- };- // Frontmatter: leading "---\n…\n---\n" with name:/description:/score:.- if (std.mem.startsWith(u8, data, "---\n")) {- if (std.mem.indexOfPos(u8, data, 4, "\n---")) |fm_end| {- var lines = std.mem.tokenizeScalar(u8, data[4..fm_end], '\n');- while (lines.next()) |ln| {- const sep = std.mem.indexOfScalar(u8, ln, ':') orelse continue;- const key = std.mem.trim(u8, ln[0..sep], " \t");- const val = std.mem.trim(u8, ln[sep + 1 ..], " \t\"");- if (std.mem.eql(u8, key, "name") and val.len > 0) at.name = val;- if (std.mem.eql(u8, key, "description")) at.desc = val;- if (std.mem.eql(u8, key, "score")) at.score = std.fmt.parseFloat(f64, val) catch null;- if (std.mem.eql(u8, key, "isolation")) at.isolation = Isolation.parse(val); // #276: e.g. an "implementer" persona opting into worktree isolation by default- // #292: a persona's own worker-model pin. An unknown tier- // name parses to null (no opinion) rather than failing the- // load, and an unknown model name is caught per spawn.- if (std.mem.eql(u8, key, "model")) at.model = if (val.len > 0) val else null;- if (std.mem.eql(u8, key, "tier")) at.tier = Tier.parse(val);- if (std.mem.eql(u8, key, "effort")) at.effort = @import("subagent_pin.zig").parseEffort(val); // #292 follow-up: persona effort pin; off-vocabulary (incl. ultra) is "no opinion"- }- const body_start = fm_end + "\n---".len;- at.prompt = std.mem.trim(u8, data[@min(body_start + 1, data.len)..], " \t\r\n");- }- }- if (at.prompt.len == 0) continue;- // A file shadows an existing type (builtin or earlier tier) of the same name.- var replaced = false;- for (list.items) |*existing| {- if (std.mem.eql(u8, existing.name, at.name)) {- existing.* = at;- replaced = true;- break;- }+ const draft = agent_file.parse(arena, entry.name, data) orelse continue;+ upsertAgent(list, arena, draftToType(draft));+ }+}++fn draftToType(d: agent_file.Draft) AgentType {+ return .{+ .name = d.name,+ .desc = d.desc,+ .prompt = d.prompt,+ .score = d.score,+ .isolation = if (d.isolation) |s| Isolation.parse(s) else null,+ .model = d.model,+ .tier = if (d.tier) |s| Tier.parse(s) else null,+ .effort = if (d.effort) |s| @import("subagent_pin.zig").parseEffort(s) else null,+ };+}++fn upsertAgent(list: *std.ArrayList(AgentType), arena: Allocator, at: AgentType) void {+ for (list.items) |*existing| {+ if (std.mem.eql(u8, existing.name, at.name)) {+ existing.* = at;+ return;}- if (!replaced) list.append(arena, at) catch continue;}+ list.append(arena, at) catch {};}/// Local single-tenant promote — the "grow for me" loop. Mine@@ -466,6 +448,7 @@ pub fn resolveIsolationFallback(obj: std.json.ObjectMap) bool {}test "resolveIsolation: explicit field wins, then the named persona's default, then shared_cwd" {+ _ = agent_file;var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();@@ -564,3 +547,23 @@ test "remote elites cannot replace a verified learned policy" {try std.testing.expect(applyRemoteElite(arena, &types, "reviewer", "new-remote"));try std.testing.expectEqualStrings("new-remote", types[1].prompt);}++test "loadAgentDir: toml shadows md of the same niche" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ try tmp.dir.writeFile(io, .{ .sub_path = "echoer.md", .data = "---\nname: echoer\ndescription: md\n---\nfrom md\n" });+ try tmp.dir.writeFile(io, .{ .sub_path = "echoer.toml", .data = "name = \"echoer\"\ndescription = \"toml\"\ndeveloper_instructions = \"from toml\"\nmodel = \"grok-4.6\"\n" });+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = try tmp.dir.realPath(io, &buf);+ var list: std.ArrayList(AgentType) = .empty;+ loadAgentDir(io, arena, &list, buf[0..n]);+ try std.testing.expectEqual(@as(usize, 1), list.items.len);+ try std.testing.expectEqualStrings("echoer", list.items[0].name);+ try std.testing.expectEqualStrings("from toml", list.items[0].prompt);+ try std.testing.expectEqualStrings("toml", list.items[0].desc);+ try std.testing.expectEqualStrings("grok-4.6", list.items[0].model.?);+}diff --git a/src/job_notify.zig b/src/job_notify.zignew file mode 100644index 00000000..4d8c8eb2--- /dev/null+++ b/src/job_notify.zig@@ -0,0 +1,129 @@+//! grok-build TaskCompleted / system-reminder for background bash (ADR 0010+//! follow-up). A finished job queues one notice. `deliver` injects a wake at+//! the next root step boundary; `takeWake` is the idle TUI auto-turn.++const std = @import("std");+const Io = std.Io;++const agent_mod = @import("agent.zig");+const engine_sink = @import("engine_sink.zig");+const Agent = agent_mod.Agent;++pub const Notice = struct {+ id: u32,+ exit_code: ?u8 = null,+ killed: bool = false,+ preview: [48]u8 = undefined,+ preview_len: u8 = 0,+};++const cap: usize = 16;+var mu: Io.Mutex = .init;+var ring: [cap]Notice = undefined;+var count: usize = 0;++fn clipCmd(cmd: []const u8) struct { buf: [48]u8, len: u8 } {+ const t = std.mem.trim(u8, cmd, " \t\r\n");+ const keep: u8 = @intCast(@min(t.len, 48));+ var buf: [48]u8 = @splat(0);+ @memcpy(buf[0..keep], t[0..keep]);+ return .{ .buf = buf, .len = keep };+}++/// One human/model line for a finished job.+pub fn line(buf: []u8, n: Notice) []const u8 {+ const cmd = n.preview[0..n.preview_len];+ if (n.killed) {+ return std.fmt.bufPrint(buf, "[job {d} killed: {s}]", .{ n.id, cmd }) catch buf[0..0];+ }+ if (n.exit_code) |c| {+ return std.fmt.bufPrint(buf, "[job {d} exited {d}: {s}]", .{ n.id, c, cmd }) catch buf[0..0];+ }+ return std.fmt.bufPrint(buf, "[job {d} ended: {s}]", .{ n.id, cmd }) catch buf[0..0];+}++fn wakeLine(buf: []u8, n: Notice) []const u8 {+ var head: [96]u8 = undefined;+ const h = line(&head, n);+ return std.fmt.bufPrint(buf, "{s} — unread output via bash_output; do not poll.", .{h}) catch h;+}++/// Pump thread: the job is done. Queues a reminder and, if a turn is live,+/// paints a TUI/REPL notice immediately.+pub fn record(io: Io, id: u32, exit_code: ?u8, killed: bool, cmd: []const u8) void {+ const clipped = clipCmd(cmd);+ const n = Notice{ .id = id, .exit_code = exit_code, .killed = killed, .preview = clipped.buf, .preview_len = clipped.len };+ mu.lockUncancelable(io);+ if (count == cap) {+ std.mem.copyForwards(Notice, ring[0 .. cap - 1], ring[1..cap]);+ count = cap - 1;+ }+ ring[count] = n;+ count += 1;+ mu.unlock(io);+ if (engine_sink.hostedSink()) |sink| {+ sink.emit(io, .{ .job_completed = .{ .id = id, .exit_code = exit_code, .killed = killed } });+ }+}++/// Drain queued notices into `buf`. Null when nothing finished.+pub fn takeWake(io: Io, buf: []u8) ?[]const u8 {+ mu.lockUncancelable(io);+ defer mu.unlock(io);+ if (count == 0) return null;+ var used: usize = 0;+ var i: usize = 0;+ while (i < count) : (i += 1) {+ var one: [160]u8 = undefined;+ const w = wakeLine(&one, ring[i]);+ if (used > 0) {+ if (used + 1 >= buf.len) break;+ buf[used] = '\n';+ used += 1;+ }+ const n = @min(w.len, buf.len - used);+ @memcpy(buf[used .. used + n], w[0..n]);+ used += n;+ }+ count = 0;+ if (used == 0) return null;+ return buf[0..used];+}++/// Root step-boundary inject (same moment as peer deliverInbound).+pub fn deliver(root: *Agent) void {+ if (root.sub) return;+ var buf: [512]u8 = undefined;+ const text = takeWake(root.io, &buf) orelse return;+ const owned = root.arena.dupe(u8, text) catch return;+ var obj: std.json.ObjectMap = .empty;+ obj.put(root.arena, "role", .{ .string = "user" }) catch return;+ obj.put(root.arena, "content", .{ .string = owned }) catch return;+ root.messages.append(.{ .object = obj }) catch {};+ engine_sink.forAgent(root).emit(root.io, .{ .session_notice = .{ .text = owned, .tone = .dim } });+}++test "line names exit, kill, and abnormal end" {+ const clipped = clipCmd("sleep 5");+ var n = Notice{ .id = 3, .exit_code = 0, .preview = clipped.buf, .preview_len = clipped.len };+ var buf: [80]u8 = undefined;+ try std.testing.expectEqualStrings("[job 3 exited 0: sleep 5]", line(&buf, n));+ n.killed = true;+ try std.testing.expectEqualStrings("[job 3 killed: sleep 5]", line(&buf, n));+ n.killed = false;+ n.exit_code = null;+ try std.testing.expectEqualStrings("[job 3 ended: sleep 5]", line(&buf, n));+}++test "takeWake drains and formats the grok-build do-not-poll reminder" {+ const io = std.testing.io;+ count = 0;+ record(io, 1, 0, false, "true");+ record(io, 2, 1, false, "false");+ var buf: [256]u8 = undefined;+ const text = takeWake(io, &buf) orelse return error.Empty;+ try std.testing.expect(std.mem.indexOf(u8, text, "[job 1 exited 0: true]") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "do not poll") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "[job 2 exited 1: false]") != null);+ try std.testing.expect(takeWake(io, &buf) == null);+}diff --git a/src/jobs.zig b/src/jobs.zigindex 6e109b22..586d241b 100644--- a/src/jobs.zig+++ b/src/jobs.zig@@ -236,11 +236,7 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [try out.print("unknown worktree command '{s}' — use: graff worktree list | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});}-/// One background bash job (`bash` with run_in_background:true). A pump task-/// continuously drains stdout+stderr into `buf` so the child never blocks on-/// a full pipe; bash_output returns the bytes past `cursor`; bash_kill stops-/// it. Jobs are session-global — they deliberately survive the turn (and the-/// Esc cancel) that started them — and are reaped at exit.+/// One background bash job. Pump drains pipes; session-global (survives Esc).const Job = struct {id: u32,cmd: []u8, // gpa-owned, for /jobs display@@ -257,6 +253,7 @@ const Job = struct {const job_unread_cap = 256 * 1024;const job_wait = @import("job_wait.zig");+const job_notify = @import("job_notify.zig");/// POSIX process groups; windows/wasi have none, so the group kills below and/// the job's own pgid are compiled out there (#198).@@ -336,7 +333,10 @@ fn jobPump(job: *Job, gpa: Allocator, io: Io) void {job.exit_code = code;job.killed = killed;job.done = true;+ const id = job.id;+ const cmd = job.cmd;g_jobs.mutex.unlock(io);+ job_notify.record(io, id, code, killed, cmd);}/// Argv that runs a shell command string: `/bin/sh -c` on POSIX, `cmd.exe /c`@@ -511,7 +511,7 @@ pub fn jobsReap(gpa: Allocator, io: Io) void {test { // split-out modules: unreferenced, their tests silently never run_ = worktree_prune;_ = @import("worktree_lease.zig");- _ = job_wait;+ _ = .{ job_wait, job_notify };}test "foreground tool subprocesses own their process group (#266, #198)" {diff --git a/src/process_runner.zig b/src/process_runner.zigindex f170d10e..4aa3aef4 100644--- a/src/process_runner.zig+++ b/src/process_runner.zig@@ -88,10 +88,18 @@ pub const CappedRun = struct {/// Supplying an explicit environment replaces (rather than augments) the/// parent environment. `kill_process_tree` creates an owned process group/job/// so descendants cannot outlive the orchestrated command.+///+/// `stream` is grok-build's bash_output_chunk: each newly-arrived stdout (0)+/// or stderr (1) slice while the child is still running. Foreground bash used+/// to stay silent until exit, so a long build looked like a hang.+pub const StreamFn = *const fn (ctx: ?*anyopaque, which: u8, chunk: []const u8) void;+pub const CappedRunOptions = struct {cwd: std.process.Child.Cwd = .inherit,environ_map: ?*const std.process.Environ.Map = null,kill_process_tree: bool = false,+ stream: ?StreamFn = null,+ stream_ctx: ?*anyopaque = null,};/// #253: RLIMIT_NOFILE as this process actually observes it. main() calls@@ -208,21 +216,31 @@ pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, stconst caps = [2]usize{ stdout_cap, stderr_cap };var saved: [2]?[]u8 = .{ null, null };errdefer for (saved) |item| if (item) |bytes| gpa.free(bytes);+ var streamed: [2]usize = .{ 0, 0 };var esc_killed = false;var timed_out = false;const started: Io.Timestamp = .now(io, .awake);loop: while (true) {+ var eof = false;multi_reader.fill(64, .{ .duration = .{ .raw = .fromMilliseconds(200), .clock = .awake } }) catch |err| switch (err) {- error.EndOfStream => break :loop,+ error.EndOfStream => eof = true,error.Timeout => {},else => |other| return other,};- for (readers, caps, &saved) |reader, cap, *item| {+ for (readers, caps, &saved, &streamed, [_]u8{ 0, 1 }) |reader, cap, *item, *seen, which| {const buffered = reader.buffered();+ if (options.stream) |fn_emit| {+ if (buffered.len > seen.*) {+ const end = if (item.* != null) @min(buffered.len, cap) else buffered.len;+ if (end > seen.*) fn_emit(options.stream_ctx, which, buffered[seen.*..end]);+ seen.* = end;+ }+ }if (item.* == null and buffered.len > cap) item.* = try gpa.dupe(u8, buffered[0..cap]);if (item.* != null) reader.toss(buffered.len);}+ if (eof) break :loop;if (Agent.esc_cancel.load(.acquire)) {esc_killed = true;terminateTree(&child, io, &windows_job, group_id, options.kill_process_tree);@@ -338,3 +356,26 @@ test "#253: fdQuotaNote names the error and the observed limit" {const without = fdQuotaNote(&buf, "SystemFdQuotaExceeded", null);try std.testing.expect(std.mem.indexOf(u8, without, "unavailable") != null);}++test "runCapped streams stdout before the child exits" {+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ const State = struct {+ seen: bool = false,+ fn emit(ctx: ?*anyopaque, which: u8, chunk: []const u8) void {+ const self: *@This() = @ptrCast(@alignCast(ctx orelse return));+ if (which == 0 and std.mem.indexOf(u8, chunk, "STREAM_MARK") != null) self.seen = true;+ }+ };+ var state = State{};+ const r = try runCappedWithOptions(gpa, io, &.{ "/bin/sh", "-c", "printf STREAM_MARK; sleep 0.4; printf DONE" }, 1024, 1024, 2000, .{+ .stream = &State.emit,+ .stream_ctx = &state,+ });+ defer gpa.free(r.stdout);+ defer gpa.free(r.stderr);+ try std.testing.expect(state.seen);+ try std.testing.expect(std.mem.indexOf(u8, r.stdout, "STREAM_MARK") != null);+ try std.testing.expect(std.mem.indexOf(u8, r.stdout, "DONE") != null);+}diff --git a/src/schema.zig b/src/schema.zigindex 56b7fac7..21c7a8ff 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -55,7 +55,7 @@ const empty_schema =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). For long-running commands (dev servers, watchers) set run_in_background true: it returns a job id immediately. 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.",+ .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). For long-running commands set run_in_background true: it returns a job id immediately and 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.",.schema =\\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]},diff --git a/src/session_run.zig b/src/session_run.zigindex f55bebe4..32635c38 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -220,7 +220,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m}/// Loads persisted command/tool approvals + lifecycle hooks + the MAP-Elites-/// agent-type registry (builtins + .harness/agents/*.md), and prints the+/// agent-type registry (builtins + .harness/agents/*.{md,toml}), and prints the/// startup status lines for both. Moved out of main() (600-line goal)./// `approvals` is an out-param: main() declares it (`var approvals: Approvals/// = undefined;`) and this fills it in place, so main() can still register@@ -230,7 +230,7 @@ pub fn initApprovalsHooksFleet(io: Io, gpa: Allocator, arena: Allocator, environapprovals.* = .{ .yolo = flags.effectiveYolo() }; // -p implies yolo unless --safeconst persisted_approvals = approvals.loadPersisted(io, gpa, arena);- // Agent types: builtins + .harness/agents/*.md (the MAP-Elites niches).+ // Agent types: builtins + .harness/agents/*.{md,toml} (the MAP-Elites niches).fleet.g_home = keys_cli.homeEnv(environ_map); // for /agents promote's personal tierfleet.g_agent_types = fleet.loadAgentTypes(io, arena, fleet.g_home); // builtin < ~/.harness/agents (personal) < ./.harness/agents (private)const sink = engine_sink.writerSink(out);diff --git a/src/subagent_pin.zig b/src/subagent_pin.zigindex 88a98cb8..a5bcf9b0 100644--- a/src/subagent_pin.zig+++ b/src/subagent_pin.zig@@ -5,7 +5,7 @@//! tier ladder. That is still the default; this module adds the two finer//! grains the issue asks for, on top of it rather than beside it.//!-//! 1. A persona in `.harness/agents/<name>.md` may pin itself in+//! 1. A persona in `.harness/agents/<name>.md` or `.toml` may pin itself in//! frontmatter — `model: gpt-5.6-terra` (exact) or `tier: mid` (a rung//! of whatever ladder the current provider is on). Parsed in fleet.zig//! into AgentType.model/.tier; resolved here.diff --git a/src/tui_launch.zig b/src/tui_launch.zigindex 89036361..cd8734fd 100644--- a/src/tui_launch.zig+++ b/src/tui_launch.zig@@ -18,6 +18,7 @@ const repl_glue = @import("repl_glue.zig");const tui = @import("tui");const engine_sink = @import("engine_sink.zig");const tui_sink = @import("tui_sink.zig");+const job_notify = @import("job_notify.zig");const obs = @import("obs.zig");const telemetry = @import("telemetry.zig");const vision = @import("vision.zig");@@ -116,6 +117,7 @@ pub fn run(.copy_fn = copyCb,.compact_fn = compactCb,.history_fn = historyCb,+ .idle_wake_fn = idleWakeCb,});}@@ -132,6 +134,11 @@ fn historyCb(ctx: ?*anyopaque, op: tui.HistoryOp) void {}}+fn idleWakeCb(ctx: ?*anyopaque, buf: []u8) ?[]const u8 {+ const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));+ return job_notify.takeWake(c.io, buf);+}+/// Overlay the TUI preview buffer as a repl.StreamBuf so replTurnCb's/// appendBytes publish `stream.len` as bytes arrive. Layout is identical/// (buf + atomic len); a copy would hide the live tail until the turn ends.diff --git a/src/tui_sink.zig b/src/tui_sink.zigindex e6c3a495..7358bc0a 100644--- a/src/tui_sink.zig+++ b/src/tui_sink.zig@@ -96,6 +96,9 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {}b.stream.appendBytes(d.text);},+ // grok-build RawTerminal: bash bytes go to the dedicated raw buf,+ // never the prose stream (that mixing is what #551 took apart).+ .tool_output_delta => |d| if (tui.rawStream()) |raw| raw.appendBytes(d.text),// A meta tool owns this text's layout, so it arrives whole..completion_text, .todo_list_updated => |t| {b.stream.appendBytes(t.text);@@ -107,11 +110,14 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {.name = t.name,.detail = capLine(engine_sink.compactArg(t.input), arg_cap),} }),- .tool_result => |r| b.queue.push(.{ .tool_finished = .{- .name = r.name,- .detail = capLine(r.text, preview_cap),- .is_error = r.is_error,- } }),+ .tool_result => |r| {+ if (tui.rawStream()) |raw| raw.len.store(0, .release);+ b.queue.push(.{ .tool_finished = .{+ .name = r.name,+ .detail = capLine(r.text, preview_cap),+ .is_error = r.is_error,+ } });+ },// The harness refused the call before it ran. hostedEmit dropped this// outright, so the row simply never closed and the user watched a tool// that looked stuck.@@ -123,6 +129,16 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {} }),// ── notices: system rows ─────────────────────────────────────────+ .job_completed => |j| {+ var buf: [64]u8 = undefined;+ const msg = if (j.killed)+ std.fmt.bufPrint(&buf, "job {d} killed", .{j.id})+ else if (j.exit_code) |c|+ std.fmt.bufPrint(&buf, "job {d} exited {d}", .{ j.id, c })+ else+ std.fmt.bufPrint(&buf, "job {d} ended", .{j.id});+ b.queue.push(.{ .notice = msg catch "job ended" });+ },.session_notice => |n| {// A notice may open with an emphasized badge ("⚠ YOLO"); the TUI's// system row has one style, so the two halves are joined here@@ -214,13 +230,14 @@ test "prose streams into the live tail; structure never does" {sink.emit(undefined, .{ .text_delta = .{ .text = "hello" } });sink.emit(undefined, .{ .tool_call_announced = .{ .name = "bash", .input = .null } });+ sink.emit(undefined, .{ .tool_output_delta = .{ .name = "bash", .text = "ls\n" } });sink.emit(undefined, .{ .tool_result = .{ .name = "bash", .text = "ok\nmore", .is_error = false } });sink.emit(undefined, .{ .text_delta = .{ .text = " world" } });const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;defer std.testing.allocator.free(snap);- // The tool cluster left no bytes in the prose buffer — that mixing is what- // the TUI used to have to un-mix by scanning for glyphs.+ // Tool *structure* left no bytes in the prose buffer. Live bash output+ // is the terminal projection (grok-build bash_output_chunk) and does.try std.testing.expectEqualStrings("hello world", snap);const evs = qbuf.drain();