Skip to content

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

Python

Merge branch 'feat/429-batch3-output-inversion' into integration/2026-08-06-batch

Rach Pradhan3eaa466b7332
diff --cc src/approvals.zig
index 4c661c77,1fccd754..81e14cf1
--- a/src/approvals.zig
+++ b/src/approvals.zig
@@@ -71,11 -64,8 +64,12 @@@ pub const Approvals = struct
return false;
}
- pub const settings_dir = ".harness";
- /// Re-exported so the dozens of `Approvals.settings_path` call sites keep
- /// working; harness_settings.zig owns it now, so a module that only reads
- /// the file no longer has to import this one (#429).
- pub const settings_path = @import("harness_settings.zig").path;
++ /// Re-exported so the dozens of `Approvals.settings_dir`/`settings_path`
++ /// call sites keep working; harness_policy.zig owns them now, so a module
++ /// that only reads the file no longer has to import this one, which
++ /// prompts the user (#429).
+ pub const settings_dir = policy.settings_dir;
+ pub const settings_path = policy.settings_path;
/// "Always allow" appends the key and persists the allow-list to the
/// project's .harness/settings.json, so approvals survive restarts.
diff --cc src/engine_events.zig
index f47a4977,7baa51c2..83a1c876
--- a/src/engine_events.zig
+++ b/src/engine_events.zig
@@@ -103,60 -103,71 +103,125 @@@ pub const BatchOutcome = struct { done
/// in that tool's own module, not in this vocabulary.
pub const ToolText = struct { text: []const u8 };
+/// One operational line about the session itself (slice 2): a config file that
+/// did not parse, an MCP server that would not connect, what startup loaded.
+/// The engine owns the wording — the shared shape is what keeps the lifecycle
+/// cluster from needing a variant per call site — and a sink owns how loud it
+/// looks. Anything with real structure a frontend would want to read gets its
+/// own variant instead (see session_banner and its neighbours below).
+pub const Notice = struct {
+ /// An emphasized opening fragment (a badge like "⚠ YOLO") a sink may draw
+ /// apart from the rest of the line; empty for an ordinary notice.
+ lead: []const u8 = "",
+ text: []const u8,
+ tone: Tone = .plain,
+
+ /// How much attention the line is asking for — the only rendering decision
+ /// the engine delegates, since it is about meaning, not palette.
+ pub const Tone = enum { plain, dim, warn, alert };
+};
+
+/// The interactive startup line. Only the two facts vary per run; what else
+/// goes on it (the key hints) is frontend knowledge and lives in the sink.
+pub const SessionBanner = struct { cwd: []const u8, trace_path: []const u8 };
+
+/// `-w/--worktree` entered its scratch checkout. `autocommit` says the run
+/// will checkpoint each turn onto that branch (main.g_worktree_autocommit).
+pub const WorktreeEntry = struct { path: []const u8, branch: []const u8, autocommit: bool };
+
+/// Startup could not honor the saved model preference and picked another.
+/// `blocked` means the substitute is cross-provider and not on the fallback
+/// allow-list, so it stays a one-session choice until the user widens it.
+pub const SavedModelNotice = struct {
+ saved: []const u8,
+ model: []const u8,
+ provider: []const u8,
+ blocked: bool,
+};
+
+/// A mid-turn provider failover (providers.runTurnWithFallback). Wire: the
+/// existing `model` event, which carries the SUBSTITUTE only — `context_note`
+/// (what happened to the conversation across the switch) is the terminal's
+/// half, and the wire's own fixed note lives in the sink that writes it.
+pub const ProviderFallback = struct {
+ from_provider: []const u8,
+ from_model: []const u8,
+ to_provider: []const u8,
+ to_model: []const u8,
+ to_context: u64,
+ context_note: []const u8,
+};
+
+/// The durable session file was written. `ext` is session.session_ext, kept in
+/// the payload rather than the sink because the extension belongs to the
+/// session format, not to any frontend.
+pub const SessionSaved = struct { name: []const u8, ext: []const u8 };
+
+ // ── The interactive status line (#429 batch 3) ───────────────────────────────
+ // Its own value types rather than main.zig's/learning_privacy's: this file is
+ // the vocabulary, and a transport-split sink must be able to read an event
+ // without importing the engine. The emit site maps with an exhaustive switch,
+ // so adding a tier upstream is a compile error here rather than a silent
+ // mistranslation.
+
+ /// Reasoning depth, when the provider takes one at all (main.ReasoningEffort).
+ pub const ReasoningEffort = enum { low, medium, high, xhigh, max, ultra };
+
+ /// The federated-learning privacy ceiling (learning_privacy.Mode).
+ pub const PrivacyTier = enum { local, aggregate, templates, examples };
+
+ /// What the cost meter can say. Deliberately not a pre-formatted string: only
+ /// `.usd` has a figure, and the other three are states, not numbers.
+ pub const CostMeter = union(enum) {
+ /// The meter is off (--no-cost): the segment does not exist.
+ hidden,
+ /// A flat-rate provider (codex): spend is not per-turn, so there is no
+ /// figure to show.
+ subscription,
+ /// No price-table entry for this model — a real figure cannot be derived.
+ unpriced,
+ /// Session spend so far, in US dollars.
+ usd: f64,
+ };
+
+ /// The live context meter. Present only once a response has reported usage;
+ /// `tokens` is the effective count, which is not always what the last response
+ /// said (local estimates carry it between turns).
+ pub const ContextMeter = struct {
+ tokens: u64,
+ window: u64,
+ /// The count at which this provider compacts.
+ compact_at: u64,
+ };
+
+ /// Everything the status line printed before a human turn actually says.
+ /// Deliberately semantic: no widths, no colors, no assembled segments. Which
+ /// badges survive a narrow pane is a rendering decision (#209) and belongs to
+ /// the sink, which is the only thing that knows the terminal.
+ pub const PromptStatus = struct {
+ model: []const u8,
+ provider_id: []const u8,
+ cwd: []const u8,
+ /// The privacy mode's own badge wording, owned by learning_privacy.zig —
+ /// carried whole for the same reason ToolText is, while the tier beside it
+ /// is what a sink picks a tone from.
+ privacy_label: []const u8,
+ privacy: PrivacyTier,
+ /// null when this provider takes no reasoning effort, so no badge exists.
+ effort: ?ReasoningEffort = null,
+ /// null until a response has reported usage.
+ context: ?ContextMeter = null,
+ /// Prompt-cache hit on the last response; 0 = nothing cached.
+ cache_read: u64 = 0,
+ cost: CostMeter = .hidden,
+ /// The Fast badge APPLIES — the flag is on and the provider honors it.
+ fast: bool = false,
+ fallback: bool = false,
+ plan: bool = false,
+ strict: bool = false,
+ ultracode: bool = false,
+ };
+
/// Everything the streaming path tells a frontend. Each doc comment states
/// the emission site's contract, not how any one sink draws it.
pub const EngineEvent = union(enum) {
@@@ -241,42 -252,12 +306,49 @@@
/// todo_write applied; the payload is the list as goal_todo rendered it.
todo_list_updated: ToolText,
+ // ── The session-lifecycle cluster (slice 2) ──────────────────────────
+ // These fire around the turn loop rather than inside it: startup, config
+ // loading, provider failover, shutdown. Most of them happen before an
+ // Agent exists or after it stops mattering, which is why they reach a
+ // sink through engine_sink.writerSink rather than forAgent.
+ //
+ // The `!json_mode` / `oneshot_prompt == null` gates stay at the EMIT
+ // sites, as slice 1c's review put the `!sub` gates back: who may write to
+ // the terminal at all is engine policy about who owns it, not a drawing
+ // decision, and a sink has no way to know a run is a one-shot.
+ /// An operational line about the session. Presentation-only: none of these
+ /// ever appeared on the --json wire.
+ session_notice: Notice,
+ /// The interactive startup banner.
+ session_banner: SessionBanner,
+ /// `-w/--worktree` entered its scratch checkout.
+ worktree_entered: WorktreeEntry,
+ /// The saved model preference could not be honored this session. The
+ /// startup twin of provider_fallback, and deliberately not a Notice: a
+ /// frontend that wants to offer "use it anyway" needs the fields.
+ saved_model_unavailable: SavedModelNotice,
+ /// Untrusted MCP servers are configured and the session wants a decision
+ /// before connecting them. TRANSITIONAL (Phase 1b): only the QUESTION is
+ /// inverted here — the stdin read still happens at the emit site. When
+ /// input inversion lands (#430) this becomes a request answered by a
+ /// `respond` command, so plan for replacement, not extension.
+ mcp_consent_prompt: struct { count: usize },
+ /// The active provider failed over mid-turn. Wire: the existing `model`
+ /// event; the terminal draws a notice instead.
+ provider_fallback: ProviderFallback,
+ /// The durable session file was written.
+ session_saved: SessionSaved,
+ /// The run is over and the engine is done with the frontend: a terminal
+ /// frontend hands raw mode back here (#396). Emitted on the one-shot's
+ /// completion path in EVERY mode, so a sink must not gate it on json_mode.
+ run_finished,
++
+ /// A human turn is about to be read: this is what the session looks like
+ /// right now (#429). Presentation-only and always will be — the --json
+ /// wire has no prompt because an SDK client drives turns itself, which is
+ /// why the emit site skips json_mode entirely rather than relying on a
+ /// silent sink.
+ prompt_ready: PromptStatus,
};
/// Durable events are the protocol stream: what the --json wire emits today
@@@ -416,31 -394,24 +488,49 @@@ test "slice 1c: the tool-cluster notice
for (pulses) |ev| try std.testing.expect(!durable(ev));
}
+test "slice 2: the lifecycle cluster is pulses, except the failover the wire carries" {
+ const pulses: [8]EngineEvent = .{
+ .{ .session_notice = .{ .text = "loaded 2 saved approval(s)", .tone = .dim } },
+ .{ .session_banner = .{ .cwd = "/repo", .trace_path = ".graff/traces/a.jsonl" } },
+ .{ .worktree_entered = .{ .path = ".graff/worktrees/w", .branch = "worktree-w", .autocommit = true } },
+ .{ .saved_model_unavailable = .{ .saved = "old", .model = "new", .provider = "codex", .blocked = false } },
+ .{ .mcp_consent_prompt = .{ .count = 3 } },
+ .{ .session_saved = .{ .name = "session-1", .ext = ".session.json" } },
+ .run_finished,
+ // A notice with a badge is still a notice, not a second variant.
+ .{ .session_notice = .{ .lead = "⚠ YOLO", .text = " mode", .tone = .alert } },
+ };
+ for (pulses) |ev| try std.testing.expect(!durable(ev));
+ // The failover has always reached a --json client as the `model` event, so
+ // it reserves an id like any other wire line.
+ try std.testing.expect(durable(.{ .provider_fallback = .{
+ .from_provider = "codex",
+ .from_model = "gpt-5.5",
+ .to_provider = "anthropic",
+ .to_model = "sonnet",
+ .to_context = 200_000,
+ .context_note = "context kept",
+ } }));
+}
+
+ test "batch 3: the status line is a presentation pulse, never a wire line" {
+ // The --json wire has never had a prompt event and must not grow one by
+ // accident: a client that drives its own turns would read a burned
+ // sequence id as lost data (#330).
+ const status: PromptStatus = .{
+ .model = "gpt-5.6",
+ .provider_id = "codex",
+ .cwd = "~/src/graff",
+ .privacy_label = "Privacy:Aggregate",
+ .privacy = .aggregate,
+ .effort = .high,
+ .context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },
+ .cache_read = 2048,
+ .cost = .subscription,
+ };
+ try std.testing.expect(!durable(.{ .prompt_ready = status }));
+ }
+
test "generation only moves forward, one restart at a time" {
const before = generation();
try std.testing.expect(before >= 1);
diff --cc src/engine_sink.zig
index 6904376a,f920de87..47118718
--- a/src/engine_sink.zig
+++ b/src/engine_sink.zig
@@@ -42,7 -42,7 +42,8 @@@ const EngineEvent = engine_events.Engin
const protocol_seq = @import("protocol_seq.zig");
const render = @import("agent_stream_render.zig");
const tool_render = @import("agent_tool_render.zig"); // slice 1c: the tool cluster's terminal half
+const session_render = @import("session_render.zig"); // slice 2: the lifecycle cluster's terminal half
+ const prompt_render = @import("agent_prompt_render.zig"); // batch 3: the status line's terminal half
const tick_gate = @import("tick_gate.zig"); // #tui-tick: child ticks wait for a foreground line boundary
/// An event plus its position, as delivered to a sink.
@@@ -243,19 -199,10 +244,23 @@@ fn tuiEmit(ctx: *anyopaque, ev: Stamped
.completion_deferred => tool_render.completionDeferred(a),
.goal_completed => tool_render.goalCompleted(a),
.completion_text, .todo_list_updated => |t| tool_render.toolTextLine(a, t.text),
+ // The lifecycle cluster (slice 2). An Agent-backed TUI sink reaches
+ // these only when one is injected (tests, a future frontend): the
+ // engine's own lifecycle emitters use writerSink, whose terminal
+ // target is the caller's writer rather than a.out.
+ .session_notice,
+ .session_banner,
+ .worktree_entered,
+ .saved_model_unavailable,
+ .mcp_consent_prompt,
+ .provider_fallback,
+ .session_saved,
+ .run_finished,
+ => session_render.emit(a.out, ev.event),
+ // The status line before a human turn (#429). Its drawing — palette,
+ // badge frame, and the #209 width budget that decides which segments
+ // survive a narrow pane — lives in agent_prompt_render.
+ .prompt_ready => |st| if (a.out) |w| prompt_render.promptLine(w, st),
}
}
diff --cc src/hooks.zig
index 259a280a,22ef9b9d..71d769c8
--- a/src/hooks.zig
+++ b/src/hooks.zig
@@@ -1,8 -1,7 +1,8 @@@
//! Lifecycle hooks (codex/Claude-style): the Hook/Hooks config types, the
//! settings.json "hooks" loader, and the per-hook subprocess runner. Split out
- //! of main.zig (#123). Takes the settings-file path from harness_settings.zig
-//! of main.zig (#123). Back-imports main only for Approvals (the settings-file
-//! path) and the win shim (Windows stderr-pipe peek). The pre/post/turn-end
++//! of main.zig (#123). Takes the settings-file path from harness_policy.zig
+//! and the Windows stderr-pipe peek from win_api.zig — both leaves, so this
+//! file imports nothing that draws to a terminal (#429). The pre/post/turn-end
//! dispatch stays in main. The codedb-guard (issue #626) per-file index cache
//! (CodedbFileCheck/codedbFileIndexed) also lives here (600-line goal); the
//! guard's on/off + PATH-presence globals (g_codedb_guard/g_codedb_present)
@@@ -16,8 -15,10 +16,8 @@@ const Value = std.json.Value
const Allocator = std.mem.Allocator;
const root = @import("main.zig");
- const harness_settings = @import("harness_settings.zig");
-const approvals_mod = @import("approvals.zig");
-const terminal = @import("term.zig");
-const Approvals = approvals_mod.Approvals;
-const win = terminal.win;
++const harness_policy = @import("harness_policy.zig");
+const win = @import("win_api.zig");
/// Lifecycle hooks (codex/Claude-style), loaded once at startup from
/// .harness/settings.json's "hooks" object. Three events:
@@@ -90,7 -91,7 +90,7 @@@ fn parseHookList(arena: Allocator, v: ?
/// Parse the "hooks" section of .harness/settings.json (arena-owned slices;
/// call once at startup with the session arena).
pub fn loadHooks(io: Io, arena: Allocator) Hooks {
- const data = Io.Dir.cwd().readFileAlloc(io, harness_settings.path, arena, .limited(1 << 20)) catch return .{};
- const data = Io.Dir.cwd().readFileAlloc(io, Approvals.settings_path, arena, .limited(1 << 20)) catch return .{};
++ const data = Io.Dir.cwd().readFileAlloc(io, harness_policy.settings_path, arena, .limited(1 << 20)) catch return .{};
const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return .{};
if (v != .object) return .{};
const hooks = v.object.get("hooks") orelse return .{};
diff --cc src/session_run.zig
index 430ec875,032f5371..b1b11e37
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@@ -40,12 -40,10 +40,12 @@@ const scoring = @import("scoring.zig")
const recipe = @import("recipe.zig");
const telemetry = @import("telemetry.zig");
const util = @import("util.zig");
-const ansi = @import("ansi.zig");
+const engine_sink = @import("engine_sink.zig"); // #429: startup/teardown lines are typed events
+const engine_events = @import("engine_events.zig");
- const harness_settings = @import("harness_settings.zig");
++const harness_policy = @import("harness_policy.zig");
const title_mod = @import("title.zig");
const repl = @import("repl.zig");
-const pickers = @import("pickers.zig");
+const shapes = @import("shapes.zig"); // applyUltracodeSteering lives here (#326)
const repl_glue = @import("repl_glue.zig");
const eval_memory = @import("eval_memory.zig");
const providers = @import("providers.zig");
@@@ -196,21 -191,17 +196,21 @@@ pub fn initApprovalsHooksFleet(io: Io,
// Agent types: builtins + .harness/agents/*.md (the MAP-Elites niches).
fleet.g_home = keys_cli.homeEnv(environ_map); // for /agents promote's personal tier
fleet.g_agent_types = fleet.loadAgentTypes(io, arena, fleet.g_home); // builtin < ~/.harness/agents (personal) < ./.harness/agents (private)
- if (persisted_approvals > 0 and !json_mode and flags.oneshot_prompt == null) {
- try out.print("{s}loaded {d} saved approval(s) from {s}{s}\n", .{ ansi.style.dim, persisted_approvals, approvals_mod.Approvals.settings_path, ansi.style.reset });
- try out.flush();
- }
+ const sink = engine_sink.writerSink(out);
+ const speak = !json_mode and flags.oneshot_prompt == null;
+ if (persisted_approvals > 0 and speak)
- sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "loaded {d} saved approval(s) from {s}", .{ persisted_approvals, harness_settings.path })));
++ sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "loaded {d} saved approval(s) from {s}", .{ persisted_approvals, harness_policy.settings_path })));
// Lifecycle hooks (pre_tool/post_tool/turn_end) from the same file.
// (Per-skill opt-outs were loaded earlier, before the muonry auto-connect.)
main_mod.g_hooks = hooks.loadHooks(io, arena);
- if (main_mod.g_hooks.total() > 0 and !json_mode and flags.oneshot_prompt == null) {
- try out.print("{s}loaded {d} lifecycle hook(s) from {s} — /hooks lists them{s}\n", .{ ansi.style.dim, main_mod.g_hooks.total(), approvals_mod.Approvals.settings_path, ansi.style.reset });
- try out.flush();
- }
+ if (main_mod.g_hooks.total() > 0 and speak)
- sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "loaded {d} lifecycle hook(s) from {s} — /hooks lists them", .{ main_mod.g_hooks.total(), harness_settings.path })));
++ sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "loaded {d} lifecycle hook(s) from {s} — /hooks lists them", .{ main_mod.g_hooks.total(), harness_policy.settings_path })));
+}
+
+/// The lifecycle's most common line: dim, no badge. A helper rather than a
+/// variant — see session_start.dimNotice.
+fn dimNotice(text: []const u8) engine_events.EngineEvent {
+ return .{ .session_notice = .{ .text = text, .tone = .dim } };
}
/// Constructs the root Agent: snapshots/client/tracer/approvals/registry are