Skip to content

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

Python

refactor(engine): the lifecycle cluster emits events, not prints (#429)

Rach Pradhan054fd5f1875c
diff --git a/src/agent.zig b/src/agent.zig
index 36516e80..b9d4f3c7 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -14,6 +14,10 @@ const ReasoningEffort = main_mod.ReasoningEffort;
const ws = @import("ws.zig"); // codex Responses WS transport (delta continuation held across a turn)
const mcp = @import("mcp.zig");
const approvals_mod = @import("approvals.zig");
+/// The shared approval state, re-exported: a module that only passes one
+/// through (session_run's startup helpers) can name the type off the Agent
+/// that owns it instead of importing approvals.zig itself (#429).
+pub const Approvals = approvals_mod.Approvals;
const trace = @import("trace.zig");
const tools_mod = @import("tools.zig");
const vision = @import("vision.zig");
diff --git a/src/approvals.zig b/src/approvals.zig
index d009028d..4c661c77 100644
--- a/src/approvals.zig
+++ b/src/approvals.zig
@@ -72,7 +72,10 @@ pub const Approvals = struct {
}
pub const settings_dir = ".harness";
- pub const settings_path = ".harness/settings.json";
+ /// 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;
/// "Always allow" appends the key and persists the allow-list to the
/// project's .harness/settings.json, so approvals survive restarts.
diff --git a/src/engine_events.zig b/src/engine_events.zig
index 0b94edbe..f47a4977 100644
--- a/src/engine_events.zig
+++ b/src/engine_events.zig
@@ -103,6 +103,60 @@ pub const BatchOutcome = struct { done: usize, failed: usize, cancelled: usize }
/// 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 };
+
/// 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) {
@@ -186,6 +240,43 @@ pub const EngineEvent = union(enum) {
completion_text: ToolText,
/// 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,
};
/// Durable events are the protocol stream: what the --json wire emits today
@@ -207,6 +298,9 @@ pub fn durable(ev: EngineEvent) bool {
// except ask_user, whose typed reply IS the result.
.tool_result, .tool_call_finished => |r| !r.meta or r.ask_user,
.tool_rejected => true,
+ // The lifecycle cluster is presentation-only except the failover,
+ // which has always been the wire's `model` event.
+ .provider_fallback => true,
else => false,
};
}
@@ -322,6 +416,31 @@ test "slice 1c: the tool-cluster notices are presentation pulses" {
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 "generation only moves forward, one restart at a time" {
const before = generation();
try std.testing.expect(before >= 1);
diff --git a/src/engine_sink.zig b/src/engine_sink.zig
index da07f6ef..6904376a 100644
--- a/src/engine_sink.zig
+++ b/src/engine_sink.zig
@@ -42,6 +42,7 @@ const EngineEvent = engine_events.EngineEvent;
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 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.
@@ -107,10 +108,54 @@ pub fn jsonSink(a: *Agent) EngineSink {
return .{ .ctx = a, .vt = if (a.out == null) &json_dropped_vtable else &json_vtable };
}
+/// The session lifecycle's terminal sink (slice 2). Its ctx is the WRITER, not
+/// an Agent: startup's banner and config reports happen before an Agent exists
+/// and shutdown's after it stops mattering, so `forAgent` has nothing to hand
+/// them. Nothing this cluster draws needs render state, which is why a plain
+/// writer suffices here and does not for the stream.
+///
+/// A null writer is a run with no frontend (a one-shot, whose stdout carries
+/// only the answer; `graff acp`, whose stdout is someone else's protocol) —
+/// legitimate, not an error: session_render stays silent for it, except the
+/// failover notice, which falls back to stderr as it always did. The sentinel
+/// exists only because `ctx` cannot be null.
+pub fn writerSink(w: ?*Io.Writer) EngineSink {
+ return .{ .ctx = if (w) |x| @ptrCast(x) else @ptrCast(&no_frontend), .vt = &lifecycle_vtable };
+}
+
+/// The lifecycle's sink for a moment an Agent DOES own — the mid-turn provider
+/// failover, whose --json half is the wire's `model` event but whose terminal
+/// half belongs to the caller's writer (mainloop's stdout, the REPL's own
+/// sink), not to `a.out`. Same choice as forAgent, different terminal target.
+pub fn forSession(a: *Agent, w: ?*Io.Writer) EngineSink {
+ if (a.sink) |s| return s;
+ return if (main_mod.json_mode) jsonSink(a) else writerSink(w);
+}
+
+var no_frontend: u8 align(@alignOf(Io.Writer)) = 0;
+
+/// Startup probed stdout and found a color-capable terminal. A capability, not
+/// an event: it settles what the terminal half's palette IS before anything is
+/// drawn, so it crosses the boundary as a call rather than an emission.
+pub fn enableColor() void {
+ session_render.enableColor();
+}
+
const tui_vtable: VTable = .{ .emit = tuiEmit, .durable = false };
const json_vtable: VTable = .{ .emit = jsonEmit, .durable = true };
/// Same writer, nothing to write to: see jsonSink.
const json_dropped_vtable: VTable = .{ .emit = jsonEmit, .durable = false };
+/// Presentation-only, like the TUI's: the wire lines this cluster owns go out
+/// through jsonSink instead, so this one must never reserve a sequence id.
+const lifecycle_vtable: VTable = .{ .emit = lifecycleEmit, .durable = false };
+
+fn lifecycleEmit(ctx: *anyopaque, ev: Stamped) void {
+ const w: ?*Io.Writer = if (ctx == @as(*anyopaque, @ptrCast(&no_frontend)))
+ null
+ else
+ @ptrCast(@alignCast(ctx));
+ session_render.emit(w, ev.event);
+}
/// Today's interactive rendering, relocated behind the event contract. Every
/// branch is the old inline agent_stream.zig code path, gate for gate.
@@ -198,6 +243,19 @@ fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {
.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),
}
}
@@ -238,6 +296,19 @@ fn jsonEmit(ctx: *anyopaque, ev: Stamped) void {
.tool_result => |r| jsonLine(w, ev.cursor, .{ .type = "tool_result", .name = r.name, .is_error = r.is_error, .text = r.text }),
.tool_call_finished => |r| jsonLine(w, ev.cursor, .{ .type = "tool_call_finished", .name = r.name, .is_error = r.is_error, .ms = r.ms }),
.tool_rejected => |r| jsonLine(w, ev.cursor, .{ .type = "tool_rejected", .name = r.name, .reason = r.reason, .input = r.input, .message = r.message }),
+ // The failover's wire half (slice 2). Its `note` is a FIXED wire
+ // string, not the payload's context_note: a --json client is being
+ // told the saved preference survived, while the terminal is told what
+ // happened to the conversation. Two audiences, one event, and the
+ // difference lives here because this is the one translation point.
+ .provider_fallback => |f| jsonLine(w, ev.cursor, .{
+ .type = "model",
+ .ok = true,
+ .provider = f.to_provider,
+ .model = f.to_model,
+ .context = f.to_context,
+ .note = "automatic session fallback; saved model preference kept",
+ }),
// Unreachable: durable() gated every other tag out above. Kept as a
// hard stop so a NEW durable variant cannot silently reach the wire
// without a shape — that would burn its id on nothing (#330).
@@ -251,278 +322,6 @@ fn jsonLine(w: *Io.Writer, cursor: engine_events.Cursor, payload: anytype) void
w.flush() catch return;
}
-test "dispatch preserves emission order and stamps at the boundary" {
- // emit(undefined, ...) is sound only while json_mode is false (no lock
- // taken): pin it so a leaky earlier test can never turn this into UB.
- const saved_json = main_mod.json_mode;
- main_mod.json_mode = false;
- defer main_mod.json_mode = saved_json;
- protocol_seq.resetForTest();
- defer protocol_seq.resetForTest();
- var rec: std.ArrayList(Stamped) = .empty;
- defer rec.deinit(std.testing.allocator);
- const vt: VTable = .{ .emit = recordEmit, .durable = true };
- const s: EngineSink = .{ .ctx = &rec, .vt = &vt };
- s.emit(undefined, .stream_begin);
- s.emit(undefined, .{ .reasoning_delta = .{ .text = "think" } });
- s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });
- s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });
- s.emit(undefined, .stream_finished);
- try std.testing.expectEqual(@as(usize, 5), rec.items.len);
- const want_tags: [5]std.meta.Tag(EngineEvent) = .{
- .stream_begin, .reasoning_delta, .text_delta, .stream_complete, .stream_finished,
- };
- for (want_tags, rec.items) |tag, got| try std.testing.expectEqual(tag, std.meta.activeTag(got.event));
- // Durable deltas reserved fresh ids; pulses ride at the last reserved
- // position — the wire's numbering shows no gap for them.
- const want_seq: [5]u64 = .{ 0, 1, 2, 2, 2 };
- for (want_seq, rec.items) |seq, got| try std.testing.expectEqual(seq, got.cursor.sequence);
- for (rec.items) |got| try std.testing.expectEqual(engine_events.generation(), got.cursor.generation);
-}
-
-test "a presentation sink never reserves sequence ids" {
- const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
- main_mod.json_mode = false;
- defer main_mod.json_mode = saved_json;
- protocol_seq.resetForTest();
- defer protocol_seq.resetForTest();
- var rec: std.ArrayList(Stamped) = .empty;
- defer rec.deinit(std.testing.allocator);
- const vt: VTable = .{ .emit = recordEmit, .durable = false };
- const s: EngineSink = .{ .ctx = &rec, .vt = &vt };
- s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });
- try std.testing.expectEqual(@as(u64, 0), rec.items[0].cursor.sequence);
- try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
-}
-
-/// The Agent shape every sink test renders through: allocator-backed, rooted
-/// (not a subagent), writing into the caller's buffer. `io` stays undefined —
-/// dispatch only touches it under the --json lock, which these tests pin off.
-fn testAgent(w: *Io.Writer) Agent {
- return .{
- .gpa = std.testing.allocator,
- .arena = std.testing.allocator,
- .io = undefined,
- .client = undefined,
- .provider = undefined,
- .messages = undefined,
- .sub = false,
- .label = "test",
- .out = w,
- };
-}
-
-fn recordEmit(ctx: *anyopaque, ev: Stamped) void {
- const rec: *std.ArrayList(Stamped) = @ptrCast(@alignCast(ctx));
- rec.append(std.testing.allocator, ev) catch @panic("OOM");
-}
-
-test "JsonSink writes today's wire lines byte-for-byte" {
- const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
- main_mod.json_mode = false;
- defer main_mod.json_mode = saved_json;
- protocol_seq.resetForTest();
- defer protocol_seq.resetForTest();
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- const s = jsonSink(&a);
- s.emit(undefined, .{ .reasoning_delta = .{ .text = "why" } });
- s.emit(undefined, .{ .text_delta = .{ .text = "hi\n" } });
- s.emit(undefined, .stream_begin); // pulses have no wire shape
- // End-of-stream flushes the held render tail (old-path parity); with
- // clean md state that adds no bytes and emits no wire line.
- s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });
- try std.testing.expectEqualStrings(
- "{\"seq\":1,\"type\":\"reasoning\",\"text\":\"why\"}\n{\"seq\":2,\"type\":\"text\",\"text\":\"hi\\n\"}\n",
- aw.writer.buffered(),
- );
-}
-
-test "TuiSink streams tool-arg prose raw and never ends the answer line (slice 1b)" {
- const saved_color = main_mod.use_color; // pin the no-color branch
- main_mod.use_color = false;
- defer main_mod.use_color = saved_color;
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- const s = tuiSink(&a);
- s.emit(undefined, .{ .tool_arg_delta = .{ .text = "answer " } });
- s.emit(undefined, .{ .tool_arg_delta = .{ .text = "prose" } });
- // Exactly the bytes, flushed per delta, no separators added — the old
- // inline emitArgText no-color branch.
- try std.testing.expectEqualStrings("answer prose", aw.writer.buffered());
-}
-
-test "TuiSink transport-abort notices reproduce the old inline lines (slice 1b)" {
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- const s = tuiSink(&a);
- const cases = [_]struct { ev: engine_events.TransportAbort, want: []const u8 }{
- .{ .ev = .{ .reason = .stalled, .turn_ending = false }, .want = "\n⚠ stream stalled\n" },
- .{ .ev = .{ .reason = .stalled, .turn_ending = true }, .want = "\n⚠ stream stalled — ending turn\n" },
- .{ .ev = .{ .reason = .dropped, .turn_ending = false }, .want = "\n⚠ connection dropped\n" },
- .{ .ev = .{ .reason = .dropped, .turn_ending = true }, .want = "\n⚠ connection dropped — response ended early\n" },
- // A deliberate interrupt was never announced at the transport layer.
- .{ .ev = .{ .reason = .interrupted, .turn_ending = true }, .want = "" },
- };
- for (cases) |c| {
- aw.clearRetainingCapacity();
- s.emit(undefined, .{ .transport_aborted = c.ev });
- try std.testing.expectEqualStrings(c.want, aw.writer.buffered());
- }
-}
-
-test "JsonSink stays silent for moments the wire never carried (slice 1b)" {
- const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
- main_mod.json_mode = false;
- defer main_mod.json_mode = saved_json;
- protocol_seq.resetForTest();
- defer protocol_seq.resetForTest();
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- const s = jsonSink(&a);
- s.emit(undefined, .{ .tool_arg_delta = .{ .text = "prose" } });
- s.emit(undefined, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = true } });
- s.emit(undefined, .{ .transport_aborted = .{ .reason = .dropped, .turn_ending = false } });
- // No wire line AND no sequence id burned: both stay pulses, so the
- // wire's gap-free numbering is untouched by them (#330).
- try std.testing.expectEqualStrings("", aw.writer.buffered());
- try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
-}
-
-test "JsonSink writes the tool bracket byte-for-byte, in wire order (slice 1c)" {
- const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
- main_mod.json_mode = false;
- defer main_mod.json_mode = saved_json;
- protocol_seq.resetForTest();
- defer protocol_seq.resetForTest();
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- const s = jsonSink(&a);
-
- const input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"fixture.txt\"}", .{});
- const call: engine_events.ToolInvocation = .{ .name = "read_file", .input = input };
- const done: engine_events.ToolOutcome = .{ .name = "read_file", .text = "hi", .is_error = false, .ms = 7 };
- s.emit(undefined, .{ .tool_call_announced = call });
- s.emit(undefined, .{ .tool_call_started = call });
- s.emit(undefined, .{ .tool_result = done });
- s.emit(undefined, .{ .tool_call_finished = done });
- s.emit(undefined, .{ .tool_rejected = .{ .name = "bash", .input = input, .reason = "budget", .message = "no" } });
- try std.testing.expectEqualStrings(
- "{\"seq\":1,\"type\":\"tool_call\",\"name\":\"read_file\",\"input\":{\"path\":\"fixture.txt\"}}\n" ++
- "{\"seq\":2,\"type\":\"tool_call_started\",\"name\":\"read_file\",\"input\":{\"path\":\"fixture.txt\"}}\n" ++
- "{\"seq\":3,\"type\":\"tool_result\",\"name\":\"read_file\",\"is_error\":false,\"text\":\"hi\"}\n" ++
- "{\"seq\":4,\"type\":\"tool_call_finished\",\"name\":\"read_file\",\"is_error\":false,\"ms\":7}\n" ++
- "{\"seq\":5,\"type\":\"tool_rejected\",\"name\":\"bash\",\"reason\":\"budget\",\"input\":{\"path\":\"fixture.txt\"},\"message\":\"no\"}\n",
- aw.writer.buffered(),
- );
-}
-
-test "JsonSink drops ask_user's bracket and a meta result without burning ids (slice 1c)" {
- const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
- main_mod.json_mode = false;
- defer main_mod.json_mode = saved_json;
- protocol_seq.resetForTest();
- defer protocol_seq.resetForTest();
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- const s = jsonSink(&a);
-
- const ask: engine_events.ToolInvocation = .{ .name = "ask_user", .input = .null, .ask_user = true };
- s.emit(undefined, .{ .tool_call_announced = ask }); // the wire's `ask_user` event carries this moment
- s.emit(undefined, .{ .tool_call_started = ask });
- s.emit(undefined, .{ .tool_result = .{ .name = "todo_write", .text = "todos", .is_error = false, .meta = true } });
- s.emit(undefined, .{ .parallel_batch_started = .{ .count = 2 } }); // TUI-only notices
- s.emit(undefined, .completion_deferred);
- s.emit(undefined, .{ .completion_text = .{ .text = "done" } });
- // No line AND no id spent: the wire's numbering stays gap-free (#330).
- try std.testing.expectEqualStrings("", aw.writer.buffered());
- try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
-
- // ask_user's own RESULT is on the wire, though — the typed reply is it.
- s.emit(undefined, .{ .tool_result = .{ .name = "ask_user", .text = "yes", .is_error = false, .meta = true, .ask_user = true } });
- try std.testing.expectEqualStrings(
- "{\"seq\":1,\"type\":\"tool_result\",\"name\":\"ask_user\",\"is_error\":false,\"text\":\"yes\"}\n",
- aw.writer.buffered(),
- );
-}
-
-test "a frontendless agent's wire sink burns no ids for the lines it cannot write (#330)" {
- const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
- main_mod.json_mode = false;
- defer main_mod.json_mode = saved_json;
- protocol_seq.resetForTest();
- defer protocol_seq.resetForTest();
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- a.out = null; // a pool-thread subagent, or the ACP root: nowhere to write
- const s = jsonSink(&a);
- try std.testing.expect(!s.vt.durable); // the guarantee is structural, not per-call-site
-
- const input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"f\"}", .{});
- const call: engine_events.ToolInvocation = .{ .name = "read_file", .input = input };
- const done: engine_events.ToolOutcome = .{ .name = "read_file", .text = "hi", .is_error = false };
- s.emit(undefined, .{ .tool_call_announced = call });
- s.emit(undefined, .{ .tool_call_started = call });
- s.emit(undefined, .{ .tool_result = done });
- s.emit(undefined, .{ .tool_call_finished = done });
- s.emit(undefined, .{ .tool_rejected = .{ .name = "bash", .input = input, .reason = "budget", .message = "no" } });
- s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });
- // Every one of those would have been a wire line for a rooted agent. With
- // no writer there is no line, so there must be no id either: a supervisor
- // reads a gap as lost data.
- try std.testing.expectEqualStrings("", aw.writer.buffered());
- try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
-}
-
-test "TuiSink draws the ⚙ and ✓ lines and nothing for the brackets (slice 1c)" {
- const saved_color = main_mod.use_color;
- main_mod.use_color = false;
- defer main_mod.use_color = saved_color;
- const saved_json = main_mod.json_mode; // sayText's root gate reads it
- main_mod.json_mode = false;
- defer main_mod.json_mode = saved_json;
- const ansi = @import("ansi.zig");
- const saved_style = ansi.style;
- ansi.style = .{}; // assert the text, not the palette
- defer ansi.style = saved_style;
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- const s = tuiSink(&a);
-
- const input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"fixture.txt\"}", .{});
- const call: engine_events.ToolInvocation = .{ .name = "read_file", .input = input };
- const done: engine_events.ToolOutcome = .{ .name = "read_file", .text = "line one\nline two\n", .is_error = false };
- s.emit(undefined, .{ .tool_call_announced = call });
- s.emit(undefined, .{ .tool_call_started = call }); // silent: the ⚙ line already said it
- s.emit(undefined, .{ .tool_result = done });
- s.emit(undefined, .{ .tool_call_finished = done }); // silent
- s.emit(undefined, .{ .tool_rejected = .{ .name = "bash", .input = input, .reason = "budget", .message = "no" } }); // silent
- // Exactly the two lines the eval golden's tool turn shows.
- try std.testing.expectEqualStrings("⚙ read_file {\"path\":\"fixture.txt\"}\n ✓ line one…\n", aw.writer.buffered());
-}
-
-test "TuiSink renders a plain text delta exactly as the no-color TTY did" {
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a = testAgent(&aw.writer);
- const s = tuiSink(&a);
- s.emit(undefined, .{ .text_delta = .{ .text = "plain\n" } });
- try std.testing.expectEqualStrings("plain\n", aw.writer.buffered());
- // Normal end after streamed text: the separating newline, as before.
- s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });
- try std.testing.expectEqualStrings("plain\n\n", aw.writer.buffered());
+test {
+ _ = @import("engine_sink_tests.zig");
}
diff --git a/src/engine_sink_tests.zig b/src/engine_sink_tests.zig
new file mode 100644
index 00000000..f46304ba
--- /dev/null
+++ b/src/engine_sink_tests.zig
@@ -0,0 +1,379 @@
+//! The tests for engine_sink.zig, split into a sibling so the boundary itself
+//! keeps room to grow (#429; the same `*_tests.zig` shape providers.zig and
+//! imagegen.zig already use). They drive the real sinks through the real
+//! dispatch, so nothing here is a mock of the thing under test.
+
+const std = @import("std");
+const Io = std.Io;
+
+const main_mod = @import("main.zig");
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+
+const engine_events = @import("engine_events.zig");
+const EngineEvent = engine_events.EngineEvent;
+const protocol_seq = @import("protocol_seq.zig");
+const engine_sink = @import("engine_sink.zig");
+const EngineSink = engine_sink.EngineSink;
+const VTable = engine_sink.VTable;
+const Stamped = engine_sink.Stamped;
+const jsonSink = engine_sink.jsonSink;
+const tuiSink = engine_sink.tuiSink;
+const writerSink = engine_sink.writerSink;
+
+test "dispatch preserves emission order and stamps at the boundary" {
+ // emit(undefined, ...) is sound only while json_mode is false (no lock
+ // taken): pin it so a leaky earlier test can never turn this into UB.
+ const saved_json = main_mod.json_mode;
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var rec: std.ArrayList(Stamped) = .empty;
+ defer rec.deinit(std.testing.allocator);
+ const vt: VTable = .{ .emit = recordEmit, .durable = true };
+ const s: EngineSink = .{ .ctx = &rec, .vt = &vt };
+ s.emit(undefined, .stream_begin);
+ s.emit(undefined, .{ .reasoning_delta = .{ .text = "think" } });
+ s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });
+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });
+ s.emit(undefined, .stream_finished);
+ try std.testing.expectEqual(@as(usize, 5), rec.items.len);
+ const want_tags: [5]std.meta.Tag(EngineEvent) = .{
+ .stream_begin, .reasoning_delta, .text_delta, .stream_complete, .stream_finished,
+ };
+ for (want_tags, rec.items) |tag, got| try std.testing.expectEqual(tag, std.meta.activeTag(got.event));
+ // Durable deltas reserved fresh ids; pulses ride at the last reserved
+ // position — the wire's numbering shows no gap for them.
+ const want_seq: [5]u64 = .{ 0, 1, 2, 2, 2 };
+ for (want_seq, rec.items) |seq, got| try std.testing.expectEqual(seq, got.cursor.sequence);
+ for (rec.items) |got| try std.testing.expectEqual(engine_events.generation(), got.cursor.generation);
+}
+
+test "a presentation sink never reserves sequence ids" {
+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var rec: std.ArrayList(Stamped) = .empty;
+ defer rec.deinit(std.testing.allocator);
+ const vt: VTable = .{ .emit = recordEmit, .durable = false };
+ const s: EngineSink = .{ .ctx = &rec, .vt = &vt };
+ s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });
+ try std.testing.expectEqual(@as(u64, 0), rec.items[0].cursor.sequence);
+ try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
+}
+
+/// The Agent shape every sink test renders through: allocator-backed, rooted
+/// (not a subagent), writing into the caller's buffer. `io` stays undefined —
+/// dispatch only touches it under the --json lock, which these tests pin off.
+fn testAgent(w: *Io.Writer) Agent {
+ return .{
+ .gpa = std.testing.allocator,
+ .arena = std.testing.allocator,
+ .io = undefined,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = w,
+ };
+}
+
+fn recordEmit(ctx: *anyopaque, ev: Stamped) void {
+ const rec: *std.ArrayList(Stamped) = @ptrCast(@alignCast(ctx));
+ rec.append(std.testing.allocator, ev) catch @panic("OOM");
+}
+
+test "JsonSink writes today's wire lines byte-for-byte" {
+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ const s = jsonSink(&a);
+ s.emit(undefined, .{ .reasoning_delta = .{ .text = "why" } });
+ s.emit(undefined, .{ .text_delta = .{ .text = "hi\n" } });
+ s.emit(undefined, .stream_begin); // pulses have no wire shape
+ // End-of-stream flushes the held render tail (old-path parity); with
+ // clean md state that adds no bytes and emits no wire line.
+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });
+ try std.testing.expectEqualStrings(
+ "{\"seq\":1,\"type\":\"reasoning\",\"text\":\"why\"}\n{\"seq\":2,\"type\":\"text\",\"text\":\"hi\\n\"}\n",
+ aw.writer.buffered(),
+ );
+}
+
+test "TuiSink streams tool-arg prose raw and never ends the answer line (slice 1b)" {
+ const saved_color = main_mod.use_color; // pin the no-color branch
+ main_mod.use_color = false;
+ defer main_mod.use_color = saved_color;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ const s = tuiSink(&a);
+ s.emit(undefined, .{ .tool_arg_delta = .{ .text = "answer " } });
+ s.emit(undefined, .{ .tool_arg_delta = .{ .text = "prose" } });
+ // Exactly the bytes, flushed per delta, no separators added — the old
+ // inline emitArgText no-color branch.
+ try std.testing.expectEqualStrings("answer prose", aw.writer.buffered());
+}
+
+test "TuiSink transport-abort notices reproduce the old inline lines (slice 1b)" {
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ const s = tuiSink(&a);
+ const cases = [_]struct { ev: engine_events.TransportAbort, want: []const u8 }{
+ .{ .ev = .{ .reason = .stalled, .turn_ending = false }, .want = "\n⚠ stream stalled\n" },
+ .{ .ev = .{ .reason = .stalled, .turn_ending = true }, .want = "\n⚠ stream stalled — ending turn\n" },
+ .{ .ev = .{ .reason = .dropped, .turn_ending = false }, .want = "\n⚠ connection dropped\n" },
+ .{ .ev = .{ .reason = .dropped, .turn_ending = true }, .want = "\n⚠ connection dropped — response ended early\n" },
+ // A deliberate interrupt was never announced at the transport layer.
+ .{ .ev = .{ .reason = .interrupted, .turn_ending = true }, .want = "" },
+ };
+ for (cases) |c| {
+ aw.clearRetainingCapacity();
+ s.emit(undefined, .{ .transport_aborted = c.ev });
+ try std.testing.expectEqualStrings(c.want, aw.writer.buffered());
+ }
+}
+
+test "JsonSink stays silent for moments the wire never carried (slice 1b)" {
+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ const s = jsonSink(&a);
+ s.emit(undefined, .{ .tool_arg_delta = .{ .text = "prose" } });
+ s.emit(undefined, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = true } });
+ s.emit(undefined, .{ .transport_aborted = .{ .reason = .dropped, .turn_ending = false } });
+ // No wire line AND no sequence id burned: both stay pulses, so the
+ // wire's gap-free numbering is untouched by them (#330).
+ try std.testing.expectEqualStrings("", aw.writer.buffered());
+ try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
+}
+
+test "JsonSink writes the tool bracket byte-for-byte, in wire order (slice 1c)" {
+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ const s = jsonSink(&a);
+
+ const input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"fixture.txt\"}", .{});
+ const call: engine_events.ToolInvocation = .{ .name = "read_file", .input = input };
+ const done: engine_events.ToolOutcome = .{ .name = "read_file", .text = "hi", .is_error = false, .ms = 7 };
+ s.emit(undefined, .{ .tool_call_announced = call });
+ s.emit(undefined, .{ .tool_call_started = call });
+ s.emit(undefined, .{ .tool_result = done });
+ s.emit(undefined, .{ .tool_call_finished = done });
+ s.emit(undefined, .{ .tool_rejected = .{ .name = "bash", .input = input, .reason = "budget", .message = "no" } });
+ try std.testing.expectEqualStrings(
+ "{\"seq\":1,\"type\":\"tool_call\",\"name\":\"read_file\",\"input\":{\"path\":\"fixture.txt\"}}\n" ++
+ "{\"seq\":2,\"type\":\"tool_call_started\",\"name\":\"read_file\",\"input\":{\"path\":\"fixture.txt\"}}\n" ++
+ "{\"seq\":3,\"type\":\"tool_result\",\"name\":\"read_file\",\"is_error\":false,\"text\":\"hi\"}\n" ++
+ "{\"seq\":4,\"type\":\"tool_call_finished\",\"name\":\"read_file\",\"is_error\":false,\"ms\":7}\n" ++
+ "{\"seq\":5,\"type\":\"tool_rejected\",\"name\":\"bash\",\"reason\":\"budget\",\"input\":{\"path\":\"fixture.txt\"},\"message\":\"no\"}\n",
+ aw.writer.buffered(),
+ );
+}
+
+test "JsonSink drops ask_user's bracket and a meta result without burning ids (slice 1c)" {
+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ const s = jsonSink(&a);
+
+ const ask: engine_events.ToolInvocation = .{ .name = "ask_user", .input = .null, .ask_user = true };
+ s.emit(undefined, .{ .tool_call_announced = ask }); // the wire's `ask_user` event carries this moment
+ s.emit(undefined, .{ .tool_call_started = ask });
+ s.emit(undefined, .{ .tool_result = .{ .name = "todo_write", .text = "todos", .is_error = false, .meta = true } });
+ s.emit(undefined, .{ .parallel_batch_started = .{ .count = 2 } }); // TUI-only notices
+ s.emit(undefined, .completion_deferred);
+ s.emit(undefined, .{ .completion_text = .{ .text = "done" } });
+ // No line AND no id spent: the wire's numbering stays gap-free (#330).
+ try std.testing.expectEqualStrings("", aw.writer.buffered());
+ try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
+
+ // ask_user's own RESULT is on the wire, though — the typed reply is it.
+ s.emit(undefined, .{ .tool_result = .{ .name = "ask_user", .text = "yes", .is_error = false, .meta = true, .ask_user = true } });
+ try std.testing.expectEqualStrings(
+ "{\"seq\":1,\"type\":\"tool_result\",\"name\":\"ask_user\",\"is_error\":false,\"text\":\"yes\"}\n",
+ aw.writer.buffered(),
+ );
+}
+
+test "a frontendless agent's wire sink burns no ids for the lines it cannot write (#330)" {
+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ a.out = null; // a pool-thread subagent, or the ACP root: nowhere to write
+ const s = jsonSink(&a);
+ try std.testing.expect(!s.vt.durable); // the guarantee is structural, not per-call-site
+
+ const input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"f\"}", .{});
+ const call: engine_events.ToolInvocation = .{ .name = "read_file", .input = input };
+ const done: engine_events.ToolOutcome = .{ .name = "read_file", .text = "hi", .is_error = false };
+ s.emit(undefined, .{ .tool_call_announced = call });
+ s.emit(undefined, .{ .tool_call_started = call });
+ s.emit(undefined, .{ .tool_result = done });
+ s.emit(undefined, .{ .tool_call_finished = done });
+ s.emit(undefined, .{ .tool_rejected = .{ .name = "bash", .input = input, .reason = "budget", .message = "no" } });
+ s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });
+ // Every one of those would have been a wire line for a rooted agent. With
+ // no writer there is no line, so there must be no id either: a supervisor
+ // reads a gap as lost data.
+ try std.testing.expectEqualStrings("", aw.writer.buffered());
+ try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
+}
+
+test "TuiSink draws the ⚙ and ✓ lines and nothing for the brackets (slice 1c)" {
+ const saved_color = main_mod.use_color;
+ main_mod.use_color = false;
+ defer main_mod.use_color = saved_color;
+ const saved_json = main_mod.json_mode; // sayText's root gate reads it
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ const ansi = @import("ansi.zig");
+ const saved_style = ansi.style;
+ ansi.style = .{}; // assert the text, not the palette
+ defer ansi.style = saved_style;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ const s = tuiSink(&a);
+
+ const input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"fixture.txt\"}", .{});
+ const call: engine_events.ToolInvocation = .{ .name = "read_file", .input = input };
+ const done: engine_events.ToolOutcome = .{ .name = "read_file", .text = "line one\nline two\n", .is_error = false };
+ s.emit(undefined, .{ .tool_call_announced = call });
+ s.emit(undefined, .{ .tool_call_started = call }); // silent: the ⚙ line already said it
+ s.emit(undefined, .{ .tool_result = done });
+ s.emit(undefined, .{ .tool_call_finished = done }); // silent
+ s.emit(undefined, .{ .tool_rejected = .{ .name = "bash", .input = input, .reason = "budget", .message = "no" } }); // silent
+ // Exactly the two lines the eval golden's tool turn shows.
+ try std.testing.expectEqualStrings("⚙ read_file {\"path\":\"fixture.txt\"}\n ✓ line one…\n", aw.writer.buffered());
+}
+
+test "TuiSink renders a plain text delta exactly as the no-color TTY did" {
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ const s = tuiSink(&a);
+ s.emit(undefined, .{ .text_delta = .{ .text = "plain\n" } });
+ try std.testing.expectEqualStrings("plain\n", aw.writer.buffered());
+ // Normal end after streamed text: the separating newline, as before.
+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });
+ try std.testing.expectEqualStrings("plain\n\n", aw.writer.buffered());
+}
+
+const swap: engine_events.ProviderFallback = .{
+ .from_provider = "codex",
+ .from_model = "gpt-5.5",
+ .to_provider = "anthropic",
+ .to_model = "claude-sonnet-5",
+ .to_context = 200_000,
+ .context_note = "context kept",
+};
+
+test "slice 2: the lifecycle sink draws through a plain writer and reserves nothing" {
+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ const ansi = @import("ansi.zig");
+ const saved_style = ansi.style;
+ ansi.style = .{}; // assert the text, not the palette
+ defer ansi.style = saved_style;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+
+ const s = writerSink(&aw.writer);
+ s.emit(undefined, .{ .session_notice = .{ .text = "loaded 3 saved approval(s)", .tone = .dim } });
+ s.emit(undefined, .{ .session_saved = .{ .name = "session-9", .ext = ".session.json" } });
+ s.emit(undefined, .{ .provider_fallback = swap });
+ try std.testing.expectEqualStrings(
+ "loaded 3 saved approval(s)\n" ++
+ "↩ session saved → session-9.session.json\n" ++
+ "⚠ gpt-5.5 via codex is unavailable; trying claude-sonnet-5 via anthropic for this session (context kept) — saved default kept\n",
+ aw.writer.buffered(),
+ );
+ // Presentation, all of it: the wire's numbering is untouched even though
+ // the failover IS a durable event on the sink that owns the wire (#330).
+ try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());
+}
+
+test "slice 2: JsonSink writes the failover as today's `model` line, not the terminal's" {
+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+
+ jsonSink(&a).emit(undefined, .{ .provider_fallback = swap });
+ // The literal a --json client has always received, `note` and all — the
+ // wire's note, not the payload's context_note.
+ try std.testing.expectEqualStrings(
+ "{\"seq\":1,\"type\":\"model\",\"ok\":true,\"provider\":\"anthropic\",\"model\":\"claude-sonnet-5\"," ++
+ "\"context\":200000,\"note\":\"automatic session fallback; saved model preference kept\"}\n",
+ aw.writer.buffered(),
+ );
+ // A lifecycle pulse still has no wire shape and still burns no id.
+ aw.clearRetainingCapacity();
+ jsonSink(&a).emit(undefined, .{ .session_banner = .{ .cwd = "/repo", .trace_path = "t" } });
+ try std.testing.expectEqualStrings("", aw.writer.buffered());
+ try std.testing.expectEqual(@as(u64, 1), protocol_seq.current());
+}
+
+test "slice 2: forSession picks the wire in --json and the caller's writer otherwise" {
+ const saved_json = main_mod.json_mode;
+ defer main_mod.json_mode = saved_json;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+
+ main_mod.json_mode = true;
+ try std.testing.expect(engine_sink.forSession(&a, null).vt.durable); // the wire, which reserves ids
+ main_mod.json_mode = false;
+ try std.testing.expect(!engine_sink.forSession(&a, &aw.writer).vt.durable); // the terminal, which does not
+ // An injected sink still wins, as it does for forAgent.
+ const vt: VTable = .{ .emit = recordEmit, .durable = true };
+ var rec: std.ArrayList(Stamped) = .empty;
+ defer rec.deinit(std.testing.allocator);
+ a.sink = .{ .ctx = &rec, .vt = &vt };
+ try std.testing.expectEqual(@as(*const VTable, &vt), engine_sink.forSession(&a, null).vt);
+}
diff --git a/src/harness_settings.zig b/src/harness_settings.zig
new file mode 100644
index 00000000..f5f9e662
--- /dev/null
+++ b/src/harness_settings.zig
@@ -0,0 +1,11 @@
+//! Where the harness's own policy lives: approvals, lifecycle hooks, per-skill
+//! opt-outs, the animation/theme preference, the fallback allow-list. One
+//! workspace file, read and rewritten by half a dozen modules.
+//!
+//! A leaf with no imports, because the PATH is not a policy concern (#429):
+//! before this, `Approvals.settings_path` was the only name for it, so a module
+//! that merely wanted to read the file — hooks.zig, which parses the "hooks"
+//! object out of it — had to import approvals.zig, a terminal-cluster module
+//! that prompts the user. approvals.zig re-exports this as
+//! `Approvals.settings_path`, so every existing call site is unchanged.
+pub const path = ".harness/settings.json";
diff --git a/src/hooks.zig b/src/hooks.zig
index 22ef9b9d..259a280a 100644
--- a/src/hooks.zig
+++ b/src/hooks.zig
@@ -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). 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_settings.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)
@@ -15,10 +16,8 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const root = @import("main.zig");
-const approvals_mod = @import("approvals.zig");
-const terminal = @import("term.zig");
-const Approvals = approvals_mod.Approvals;
-const win = terminal.win;
+const harness_settings = @import("harness_settings.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:
@@ -91,7 +90,7 @@ fn parseHookList(arena: Allocator, v: ?Value) []const Hook {
/// 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, Approvals.settings_path, arena, .limited(1 << 20)) catch return .{};
+ const data = Io.Dir.cwd().readFileAlloc(io, harness_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 --git a/src/main.zig b/src/main.zig
index 2f72e481..35d7f2ff 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -389,7 +389,7 @@ pub fn main(init: std.process.Init) !void {
};
if (theme_setup.should_exit) return;
boot.mark(io, "settings/theme");
- try session_start.connectCompanion(io, &registry_storage, flags, out, json_mode, init.environ_map);
+ try session_start.connectCompanion(io, arena, &registry_storage, flags, out, json_mode, init.environ_map);
const mcp_tools: []const mcp.Tool = registry_storage.tools;
// If the metered companion connected, probe its license once so the note below can lean into paid tools (vs the conservative free-codedb note).
if (mcpServerConnected(mcp_tools, "codedbpro")) g_codedbpro_licensed = probeCodedbproLicensed(gpa, io);
diff --git a/src/mcp_config.zig b/src/mcp_config.zig
index 6c44d37d..56708ff3 100644
--- a/src/mcp_config.zig
+++ b/src/mcp_config.zig
@@ -126,11 +126,14 @@ pub fn load(io: Io, arena: Allocator, dir: Io.Dir, project_path: []const u8, glo
/// global-only listing behind. `prefix`/`suffix` carry the caller's styling
/// (dim/reset at startup, empty for the plain CLI).
pub fn reportInvalid(merged: Merged, w: *Io.Writer, project_path: []const u8, global_path: ?[]const u8, prefix: []const u8, suffix: []const u8) !void {
- const complaint = " is not valid MCP config (expected a JSON object with \"mcpServers\"); ignoring it.";
- if (merged.invalid_project) try w.print("{s}{s}" ++ complaint ++ "{s}\n", .{ prefix, project_path, suffix });
- if (merged.invalid_global) try w.print("{s}{s}" ++ complaint ++ "{s}\n", .{ prefix, global_path orelse "", suffix });
+ if (merged.invalid_project) try w.print("{s}{s}" ++ invalid_complaint ++ "{s}\n", .{ prefix, project_path, suffix });
+ if (merged.invalid_global) try w.print("{s}{s}" ++ invalid_complaint ++ "{s}\n", .{ prefix, global_path orelse "", suffix });
}
+/// What follows the path in that report. Public because startup says the same
+/// thing as a typed notice now (#429) rather than printing it here.
+pub const invalid_complaint = " is not valid MCP config (expected a JSON object with \"mcpServers\"); ignoring it.";
+
/// Whether `{home}/.mcpconfig.json` exists. That path belongs to other MCP
/// clients and graff never reads it, so startup says so once instead of leaving
/// the user to wonder why their servers never appeared.
diff --git a/src/providers.zig b/src/providers.zig
index b2588f49..ac478102 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -1,6 +1,6 @@
//! Provider-switch core: resolve a /model or set_model request to a
//! Provider, apply it to the running Agent (translating or clearing history
-//! across a wire-format change), and print the switch confirmation. Split
+//! across a wire-format change), and announce the switch. Split
//! out of main.zig (600-line goal). The interactive pickers + ultracode
//! steering + login-auth flow that build on top of this live in
//! pickers.zig, which back-imports switchProvider from here. Back-imports
@@ -23,7 +23,7 @@ const saveModel = serde.saveModel;
const messages_mod = @import("messages.zig");
const textMessage = messages_mod.textMessage;
-const ansi = @import("ansi.zig");
+const engine_sink = @import("engine_sink.zig"); // #429: the failover notice is a typed event, not a print
const fallback_config = @import("fallback_config.zig");
const util = @import("util.zig");
const trace = @import("trace.zig");
@@ -259,22 +259,19 @@ pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*I
attempted[attempted_len] = fallback.id;
attempted_len += 1;
const note = try applyFallbackProvider(root, arena, fallback);
- if (main_mod.json_mode) {
- root.emit(.{ .type = "model", .ok = true, .provider = fallback.id, .model = fallback.model, .context = fallback.context, .note = "automatic session fallback; saved model preference kept" });
- } else if (out) |w| {
- try w.print("{s}⚠ {s} via {s} is unavailable; trying {s} via {s} for this session ({s}) — saved default kept{s}\n", .{
- ansi.style.yellow,
- failed_model,
- failed_id,
- fallback.model,
- fallback.id,
- note,
- ansi.style.reset,
- });
- try w.flush();
- } else {
- std.debug.print("⚠ {s} via {s} is unavailable; trying {s} via {s} for this session ({s}) — saved default kept\n", .{ failed_model, failed_id, fallback.model, fallback.id, note });
- }
+ // One moment, three audiences (#422): the --json wire's `model`
+ // event, the terminal's warning, and — for a run whose stdout is
+ // reserved (`-p`, `acp`) — stderr, because a silent model swap is
+ // a cost and consent surprise. The sink picks; `out` is the
+ // caller's frontend, which is not always `root.out`.
+ engine_sink.forSession(root, out).emit(root.io, .{ .provider_fallback = .{
+ .from_provider = failed_id,
+ .from_model = failed_model,
+ .to_provider = fallback.id,
+ .to_model = fallback.model,
+ .to_context = fallback.context,
+ .context_note = note,
+ } });
if (root.tracer) |tr| {
const trace_note = std.fmt.allocPrint(arena, "{s}/{s} -> {s}/{s}", .{ failed_id, failed_model, fallback.id, fallback.model }) catch "automatic provider fallback";
tr.note("model_fallback", trace_note);
diff --git a/src/session_render.zig b/src/session_render.zig
new file mode 100644
index 00000000..fbb8d3db
--- /dev/null
+++ b/src/session_render.zig
@@ -0,0 +1,251 @@
+//! The session-lifecycle cluster's terminal half (#422 slice 2), the sibling
+//! of agent_stream_render.zig (the stream) and agent_tool_render.zig (tools):
+//! the one file down here that reaches the palette, so the lifecycle engine
+//! files (session_start, session_run, providers, hooks) reach none of it.
+//!
+//! Every function is the old inline code path byte for byte — the format
+//! strings, the argument order, and the two places where a reset deliberately
+//! lands somewhere other than just before the newline are reproduced exactly,
+//! because a rendered line changing shape is a UX change and this is a
+//! refactor. Two intentional differences from the inline originals, both
+//! shared with slice 1: write errors are swallowed rather than propagated (a
+//! sink cannot fail its emitter), and every line flushes.
+//!
+//! `emit` takes an OPTIONAL writer: this cluster runs where a frontend may not
+//! exist at all (a one-shot with stdout reserved for the answer, `graff acp`).
+//! Null means "no frontend": almost everything is then silent, exactly as
+//! before, and the failover notice falls back to stderr the way its old
+//! `std.debug.print` branch did.
+
+const std = @import("std");
+const Io = std.Io;
+
+const ansi = @import("ansi.zig");
+const style = &ansi.style;
+const terminal = @import("term.zig");
+const mcp_config = @import("mcp_config.zig"); // the global config path the consent prompt names
+const engine_events = @import("engine_events.zig");
+const EngineEvent = engine_events.EngineEvent;
+
+/// The `-w` line's suffix when the session will checkpoint each turn.
+const autocommit_suffix = " · auto-committing each turn (`graff worktree merge` to land it)";
+/// What the startup banner says a session can do. Frontend knowledge: these
+/// are this TUI's keys, and a different client's would differ.
+const banner_hints = " · / for commands · @ picks a file · esc interrupts · ↑/↓ history · tab completes · ctrl-d quits · trace → ";
+
+/// Startup found a color-capable terminal. A capability handshake rather than
+/// an event — nothing has been drawn yet — but the palette is this half's own
+/// state, so the engine says only that color exists and this decides what it
+/// looks like. Reached through engine_sink.enableColor.
+pub fn enableColor() void {
+ ansi.style = ansi.Style.ansi;
+}
+
+/// Draw one lifecycle event, or nothing when the moment belongs to another
+/// cluster. The caller has already applied the engine's own gates (json_mode,
+/// one-shot) — see the vocabulary's note on why those stayed at the emit site.
+pub fn emit(w: ?*Io.Writer, ev: EngineEvent) void {
+ switch (ev) {
+ .session_notice => |n| notice(w, n),
+ .session_banner => |b| line(w, "{s}codegraff{s} · folder: {s}{s}{s}" ++ banner_hints ++ "{s}\n", .{
+ style.bold, style.reset, style.accent, b.cwd, style.reset, b.trace_path,
+ }),
+ .worktree_entered => |t| line(w, "{s}worktree:{s} {s}{s}{s} (branch {s}) — edits isolated from the main checkout{s}\n", .{
+ style.dim, style.reset, style.accent, t.path, style.reset, t.branch,
+ if (t.autocommit) autocommit_suffix else "",
+ }),
+ .saved_model_unavailable => |m| savedModelUnavailable(w, m),
+ .mcp_consent_prompt => |p| line(
+ w,
+ "{s}⚠ {d} untrusted MCP server(s) are configured for this session (.mcp.json and/or ~/" ++
+ mcp_config.global_rel_path ++
+ "). They may run local commands or receive data over the network. Connect them this session? [y/N] {s}",
+ .{ style.bold, p.count, style.reset },
+ ),
+ .provider_fallback => |f| providerFallback(w, f),
+ .session_saved => |s| line(w, "{s}↩ session saved → {s}{s}{s}\n", .{ style.dim, s.name, style.reset, s.ext }),
+ // #396: the run is over, so the terminal goes back to the shell before
+ // teardown. Unconditional, as the old inline call was — a --json
+ // one-shot still ran on somebody's tty.
+ .run_finished => terminal.tty.releaseTerminal(),
+ else => {},
+ }
+}
+
+/// An ordinary notice: the tone colors the whole line, or just the badge when
+/// the notice carries one. A plain notice emits no escape bytes at all, which
+/// is what keeps the un-styled lines (the Codex login line, the MCP init
+/// failure) byte-identical to their old un-styled prints.
+fn notice(w: ?*Io.Writer, n: engine_events.Notice) void {
+ const color = toneColor(n.tone);
+ if (n.lead.len > 0) return line(w, "{s}{s}{s}{s}\n", .{ color, n.lead, style.reset, n.text });
+ if (n.tone == .plain) return line(w, "{s}\n", .{n.text});
+ line(w, "{s}{s}{s}\n", .{ color, n.text, style.reset });
+}
+
+fn toneColor(tone: engine_events.Notice.Tone) []const u8 {
+ return switch (tone) {
+ .plain => "",
+ .dim => style.dim,
+ .warn => style.yellow,
+ .alert => style.red,
+ };
+}
+
+/// The startup twin of providerFallback. The reset lands AFTER the newline
+/// here because the inline original wrote it with a separate `writeAll`, and
+/// this is a refactor: the bytes are the contract.
+fn savedModelUnavailable(w: ?*Io.Writer, m: engine_events.SavedModelNotice) void {
+ const out = w orelse return;
+ out.print("{s}note: saved model '{s}' is unavailable — selected {s} via {s} for this session; saved preference kept{s}{s}\n", .{
+ style.dim,
+ m.saved,
+ m.model,
+ m.provider,
+ if (m.blocked) ". Cross-provider use is blocked until /fallback allow " else "",
+ if (m.blocked) m.provider else "",
+ }) catch return;
+ out.writeAll(style.reset) catch return;
+ out.flush() catch {};
+}
+
+/// A run with no frontend still owes the user this one: a silent model swap is
+/// a cost and consent surprise, so it goes to stderr when stdout is reserved
+/// for the answer (`-p`) or is a protocol stream someone else owns (`acp`).
+fn providerFallback(w: ?*Io.Writer, f: engine_events.ProviderFallback) void {
+ const out = w orelse {
+ std.debug.print("⚠ {s} via {s} is unavailable; trying {s} via {s} for this session ({s}) — saved default kept\n", .{
+ f.from_model, f.from_provider, f.to_model, f.to_provider, f.context_note,
+ });
+ return;
+ };
+ line(out, "{s}⚠ {s} via {s} is unavailable; trying {s} via {s} for this session ({s}) — saved default kept{s}\n", .{
+ style.yellow, f.from_model, f.from_provider, f.to_model, f.to_provider, f.context_note, style.reset,
+ });
+}
+
+fn line(w: ?*Io.Writer, comptime fmt: []const u8, args: anytype) void {
+ const out = w orelse return;
+ out.print(fmt, args) catch return;
+ out.flush() catch {};
+}
+
+// ── Byte-identity tests ──────────────────────────────────────────────────
+// Each case is the literal the pre-#429 inline call site produced, spelled out
+// rather than rebuilt from the same constants: a test that compares the code
+// to itself cannot guard a conversion.
+
+/// Render one event into a fresh buffer with the palette pinned so the
+/// assertions are about text, not about which escape codes are in fashion.
+fn renderTest(aw: *Io.Writer.Allocating, ev: EngineEvent) []const u8 {
+ aw.clearRetainingCapacity();
+ emit(&aw.writer, ev);
+ return aw.writer.buffered();
+}
+
+test "slice 2: the startup lines render exactly as the inline prints did" {
+ const saved = ansi.style;
+ ansi.style = .{}; // color off: the un-styled shape the no-TTY startup writes
+ defer ansi.style = saved;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+
+ try std.testing.expectEqualStrings(
+ "codegraff · folder: /repo · / for commands · @ picks a file · esc interrupts · ↑/↓ history · tab completes · ctrl-d quits · trace → .graff/traces/ab.jsonl\n",
+ renderTest(&aw, .{ .session_banner = .{ .cwd = "/repo", .trace_path = ".graff/traces/ab.jsonl" } }),
+ );
+ try std.testing.expectEqualStrings(
+ "worktree: .graff/worktrees/w (branch worktree-w) — edits isolated from the main checkout · auto-committing each turn (`graff worktree merge` to land it)\n",
+ renderTest(&aw, .{ .worktree_entered = .{ .path = ".graff/worktrees/w", .branch = "worktree-w", .autocommit = true } }),
+ );
+ try std.testing.expectEqualStrings(
+ "worktree: .graff/worktrees/w (branch worktree-w) — edits isolated from the main checkout\n",
+ renderTest(&aw, .{ .worktree_entered = .{ .path = ".graff/worktrees/w", .branch = "worktree-w", .autocommit = false } }),
+ );
+ try std.testing.expectEqualStrings(
+ "note: saved model 'k2' is unavailable — selected sonnet via anthropic for this session; saved preference kept\n",
+ renderTest(&aw, .{ .saved_model_unavailable = .{ .saved = "k2", .model = "sonnet", .provider = "anthropic", .blocked = false } }),
+ );
+ try std.testing.expectEqualStrings(
+ "note: saved model 'k2' is unavailable — selected sonnet via anthropic for this session; saved preference kept. Cross-provider use is blocked until /fallback allow anthropic\n",
+ renderTest(&aw, .{ .saved_model_unavailable = .{ .saved = "k2", .model = "sonnet", .provider = "anthropic", .blocked = true } }),
+ );
+ // No trailing newline: the answer is typed on this line (still #430's).
+ try std.testing.expectEqualStrings(
+ "⚠ 2 untrusted MCP server(s) are configured for this session (.mcp.json and/or ~/.codegraff/mcp.json). They may run local commands or receive data over the network. Connect them this session? [y/N] ",
+ renderTest(&aw, .{ .mcp_consent_prompt = .{ .count = 2 } }),
+ );
+ try std.testing.expectEqualStrings(
+ "↩ session saved → session-17.session.json\n",
+ renderTest(&aw, .{ .session_saved = .{ .name = "session-17", .ext = ".session.json" } }),
+ );
+}
+
+test "slice 2: a notice's tone colors the line, a badge colors only itself" {
+ const saved = ansi.style;
+ ansi.style = ansi.Style.ansi; // the interactive palette: where the escapes matter
+ defer ansi.style = saved;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+
+ // Whole-line dim, reset before the newline — the shape every startup
+ // "loaded N …" / "[mcp:…] …" line had inline.
+ try std.testing.expectEqualStrings(
+ "\x1b[2mloaded 2 saved approval(s) from .harness/settings.json\x1b[0m\n",
+ renderTest(&aw, .{ .session_notice = .{ .text = "loaded 2 saved approval(s) from .harness/settings.json", .tone = .dim } }),
+ );
+ try std.testing.expectEqualStrings(
+ "\x1b[33m⚠ session save failed: AccessDenied\x1b[0m\n",
+ renderTest(&aw, .{ .session_notice = .{ .text = "⚠ session save failed: AccessDenied", .tone = .warn } }),
+ );
+ // A badge is colored and closed, then the rest of the line rides plain.
+ try std.testing.expectEqualStrings(
+ "\x1b[31m⚠ YOLO\x1b[0m mode (--yolo): all bash/tool/MCP permission prompts are skipped\n",
+ renderTest(&aw, .{ .session_notice = .{
+ .lead = "⚠ YOLO",
+ .text = " mode (--yolo): all bash/tool/MCP permission prompts are skipped",
+ .tone = .alert,
+ } }),
+ );
+ // A plain notice emits no escape bytes even with the palette live.
+ try std.testing.expectEqualStrings(
+ "[mcp] init failed: ConnectionRefused — continuing without MCP\n",
+ renderTest(&aw, .{ .session_notice = .{ .text = "[mcp] init failed: ConnectionRefused — continuing without MCP" } }),
+ );
+}
+
+test "slice 2: the failover notice, with a frontend and without one" {
+ const saved = ansi.style;
+ ansi.style = .{};
+ defer ansi.style = saved;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ const swap: engine_events.ProviderFallback = .{
+ .from_provider = "codex",
+ .from_model = "gpt-5.5",
+ .to_provider = "anthropic",
+ .to_model = "sonnet",
+ .to_context = 200_000,
+ .context_note = "context kept",
+ };
+ try std.testing.expectEqualStrings(
+ "⚠ gpt-5.5 via codex is unavailable; trying sonnet via anthropic for this session (context kept) — saved default kept\n",
+ renderTest(&aw, .{ .provider_fallback = swap }),
+ );
+ // With no writer the notice goes to stderr instead of vanishing; nothing
+ // reaches the (absent) frontend, which is what this can assert.
+ emit(null, .{ .provider_fallback = swap });
+}
+
+test "slice 2: a frontendless lifecycle draws nothing" {
+ // Everything except the failover is silent with no writer — and none of it
+ // may fault on the null.
+ emit(null, .{ .session_banner = .{ .cwd = "/repo", .trace_path = "t" } });
+ emit(null, .{ .session_notice = .{ .text = "x", .tone = .dim } });
+ emit(null, .{ .worktree_entered = .{ .path = "p", .branch = "b", .autocommit = true } });
+ emit(null, .{ .saved_model_unavailable = .{ .saved = "a", .model = "b", .provider = "c", .blocked = true } });
+ emit(null, .{ .mcp_consent_prompt = .{ .count = 1 } });
+ emit(null, .{ .session_saved = .{ .name = "s", .ext = ".session.json" } });
+ // A moment from another cluster is not this renderer's business.
+ emit(null, .{ .text_delta = .{ .text = "hi" } });
+}
diff --git a/src/session_run.zig b/src/session_run.zig
index 032f5371..430ec875 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -1,7 +1,13 @@
//! Agent-boot + run-loop entry helpers, split out of session_start.zig (600-line
//! goal). Covers approvals/hooks/fleet-type loading through Agent construction,
-//! the `graff repl`/one-shot early-exit paths, session resume/finalize, and the
-//! skills/theme/PTY self-tests setup.
+//! the `graff repl`/one-shot early-exit paths, and session resume/finalize. The
+//! skills/theme/PTY-self-test phase moved on to session_settings.zig (#429) and
+//! is re-exported from here.
+//!
+//! Engine side of the #422 boundary: every line this file used to print — the
+//! startup "loaded N …" notices, the session-saved line, the one-shot's
+//! terminal handoff — is a typed event now (engine_events.zig), rendered by
+//! whichever sink the run has. Nothing here reaches the terminal cluster.
//!
//! Same dangling-pointer discipline as session_start.zig: `buildRootAgent`
//! returns `agent_mod.Agent` by value — safe because its pointer fields
@@ -22,17 +28,11 @@ const Allocator = std.mem.Allocator;
const args = @import("args.zig");
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
-const approvals_mod = @import("approvals.zig");
+const Approvals = agent_mod.Approvals; // via the Agent that owns it, not approvals.zig (#429)
const tools_mod = @import("tools.zig");
-const http = @import("http.zig");
-const ws = @import("ws.zig");
-const agent_ws = @import("agent_ws.zig"); // codex_ws_idle_ms override (#codex-ws)
-const no_local_tools = @import("no_local_tools.zig"); // #330: GRAFF_NO_LOCAL_TOOLS
const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const pricing = @import("pricing.zig");
-const skills = @import("skills.zig");
-const anim = @import("anim.zig");
const mcp = @import("mcp.zig");
const jobs = @import("jobs.zig");
const trace = @import("trace.zig");
@@ -40,15 +40,18 @@ 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 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");
const messages_mod = @import("messages.zig");
const session = @import("session.zig");
+const session_settings = @import("session_settings.zig");
const goal_flow = @import("goal_flow.zig");
const fleet = @import("fleet.zig");
const hooks = @import("hooks.zig");
@@ -58,7 +61,6 @@ const run_budget_mod = @import("run_budget.zig");
const learning_privacy = @import("learning_privacy.zig");
const commands_privacy = @import("commands_privacy.zig");
const prompts = @import("prompts.zig");
-const terminal = @import("term.zig"); // #396: releaseTerminal at one-shot completion
/// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL
/// agent loop — each prompt runs a full root turn (tools + MCP) via
@@ -118,7 +120,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
root.in = null; // gate: deny instead of prompt; ask_user: self-decide
root.out = null; // tool progress → stderr; stdout carries only the answer
root.stream_quiet = true;
- const ultracode_msg = try pickers.applyUltracodeSteering(arena, prompt_text, prompt_text, prompts.ultracodeActive(root));
+ const ultracode_msg = try shapes.applyUltracodeSteering(arena, prompt_text, prompt_text, prompts.ultracodeActive(root));
if (ultracode_msg.explicit) {
tracer.note("ultracode", prompt_text[0..@min(prompt_text.len, 120)]);
if (telemetry.g_telem) |t| t.ultracode();
@@ -174,7 +176,10 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
for (root.md_table.items) |r| gpa.free(r);
root.md_table.deinit(gpa);
root.tools_used.deinit(gpa);
- terminal.tty.releaseTerminal(); // #396: the run is over — hand the tty back and latch the reader shut before main()'s teardown
+ // #396: the run is over. The frontend hands the terminal back and latches
+ // its reader shut before main()'s teardown — a terminal-ownership move the
+ // sink owns now, in EVERY mode, exactly as the old unconditional call did.
+ engine_sink.writerSink(out).emit(io, .run_finished);
}
/// Loads persisted command/tool approvals + lifecycle hooks + the MAP-Elites
@@ -184,24 +189,28 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_m
/// = undefined;`) and this fills it in place, so main() can still register
/// its own `defer` for `approvals.prefixes` right after the call (a `defer`
/// registered here would fire when THIS returns, not when main() does).
-pub fn initApprovalsHooksFleet(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, approvals: *approvals_mod.Approvals, flags: args.Flags, out: *Io.Writer, json_mode: bool) !void {
+pub fn initApprovalsHooksFleet(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, approvals: *Approvals, flags: args.Flags, out: *Io.Writer, json_mode: bool) !void {
approvals.* = .{ .yolo = flags.yolo_flag };
const persisted_approvals = approvals.loadPersisted(io, gpa, arena);
// 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 })));
// 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 })));
+}
+
+/// 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
@@ -226,7 +235,7 @@ pub fn buildRootAgent(
out: *Io.Writer,
in: *Io.Reader,
registry: ?*mcp.Registry,
- approvals: *approvals_mod.Approvals,
+ approvals: *Approvals,
tracer: *trace.Tracer,
sys_normal: []const u8,
snaps: *tools_mod.Snapshots,
@@ -348,12 +357,13 @@ pub fn compactResumedSession(root: *agent_mod.Agent) void {
/// goal); `root` is already stable main()-owned storage.
pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, json_mode: bool) !void {
if (!json_mode and root.messages.items.len > 0) {
+ const sink = engine_sink.writerSink(out);
if (session.saveSession(root, arena, root.session_name)) |_| {
- out.print("{s}↩ session saved → {s}{s}{s}\n", .{ ansi.style.dim, root.session_name, ansi.style.reset, session.session_ext }) catch {};
+ sink.emit(io, .{ .session_saved = .{ .name = root.session_name, .ext = session.session_ext } });
} else |err| { // one line, and true: never contradict a failure with "saved" (#273)
- out.print("{s}⚠ session save failed: {t}{s}\n", .{ ansi.style.yellow, err, ansi.style.reset }) catch {};
+ const text = std.fmt.allocPrint(arena, "⚠ session save failed: {t}", .{err}) catch "⚠ session save failed";
+ sink.emit(io, .{ .session_notice = .{ .text = text, .tone = .warn } });
}
- out.flush() catch {};
} else {
session.saveSession(root, arena, root.session_name) catch {};
}
@@ -366,168 +376,11 @@ pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer
try out.flush();
}
-pub const ThemeSetup = struct {
- theme_on: bool,
- limyuxi_glam: bool,
- /// True when a PTY self-test already ran + printed its render — main()
- /// should return immediately (but AFTER registering the theme/limyuxi
- /// reset defers below, exactly like the original inline code did).
- should_exit: bool,
-};
-
-/// Per-skill/companion opt-outs, animation + terminal-theme settings, the
-/// headless PTY render self-tests, and the
-/// yxlyx-birthday cosmetic theme. Moved out of main() verbatim (600-line
-/// goal). Returns which reset defers main() needs to register — the
-/// escape-code RESETS must fire when main() itself returns (not when this
-/// helper returns), so the `defer`s stay in main(), gated on the booleans
-/// this returns; main() registers them in the same order as the original
-/// inline code so LIFO defer-firing order is unchanged.
-pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out: *Io.Writer, flags: args.Flags, use_color: bool, json_mode: bool, cwd_display: []const u8) !ThemeSetup {
- // Companion auto-activation: if the metered code-intelligence companion
- // (codedb-pro, formerly muonry) is installed but nothing connected it (no
- // workspace .mcp.json entry, or consent declined), spawn it directly — a
- // user-installed companion at the same trust level as the skills
- // auto-detection above it, NOT arbitrary workspace config.
- main_mod.g_path_env = try arena.dupe(u8, environ_map.get("PATH") orelse "");
- main_mod.g_codedb_guard = environ_map.get("GRAFF_NO_CODEDB_GUARD") == null; // issue #626 guard, opt-out via env
- main_mod.g_force_stall_once = environ_map.get("GRAFF_FORCE_STALL_ONCE") != null; // #134 test seam
- main_mod.g_force_drop_once = environ_map.get("GRAFF_FORCE_DROP_ONCE") != null; // #132/#133 test seam
- main_mod.g_force_stall_always = environ_map.get("GRAFF_FORCE_STALL_ALWAYS") != null; // #56 test seam (exhaust the reconnect budget)
- main_mod.g_force_drop_always = environ_map.get("GRAFF_FORCE_DROP_ALWAYS") != null; // #56 test seam
- // #134: let a provider that buffers a long reasoning phase in total silence
- // raise the mid-stream idle-stall cutoff (default 120s). Seconds; ignored if
- // unparseable or 0. A stall is never a user interrupt regardless of the value.
- if (environ_map.get("GRAFF_STREAM_STALL_SECS")) |v| {
- if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
- if (secs > 0) http.stream_stall_ms = @min(secs, 86_400) * 1000; // clamp: <=1 day, no u64 overflow
- } else |_| {}
- }
- // #codex-ws: GRAFF_CODEX_WS=off|0|false|no (case-insensitive, the
- // GRAFF_FLEET predicate) forces the SSE transport for codex;
- // GRAFF_WS_DEBUG=1 dumps the ws handshake + frames to stderr. This is the
- // SOLE parse site for the codex transport knobs — a copy in main() would
- // be silently overwritten here, since setupSkillsAndTheme runs later.
- if (environ_map.get("GRAFF_CODEX_WS")) |v| {
- main_mod.g_codex_ws = !(std.ascii.eqlIgnoreCase(v, "off") or std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "no"));
- }
- // #225 GRAFF_CLOCK_SLEEP (root-only clock_sleep meta tool) and #330
- // GRAFF_NO_LOCAL_TOOLS (the hard local-execution gate): both are
- // affirmative-only (1|true|on|yes), like GRAFF_WS_FORCE_FAIL_ONCE below,
- // and both are OR'd onto their CLI flag so a conflicting or absent env
- // value can never silently turn --clock-sleep / --no-local-tools back off.
- if (environ_map.get("GRAFF_CLOCK_SLEEP")) |v| {
- main_mod.g_clock_sleep = main_mod.g_clock_sleep or std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "yes");
- }
- if (environ_map.get("GRAFF_NO_LOCAL_TOOLS")) |v| no_local_tools.enabled = no_local_tools.enabled or no_local_tools.envEnables(v);
- // (#codex-ws) GRAFF_CODEX_WS_IDLE_SECS raises/lowers the held-WS idle limit
- // (default 4 min — the backend killed ours within 8.5 min idle; opencode
- // pools at 5). Mirrors GRAFF_STREAM_STALL_SECS above: seconds, ignored if
- // unparseable or 0, clamped to <=1 day.
- if (environ_map.get("GRAFF_CODEX_WS_IDLE_SECS")) |v| {
- if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
- if (secs > 0) agent_ws.codex_ws_idle_ms = @intCast(@min(secs, 86_400) * 1000);
- } else |_| {}
- }
- // #203: GRAFF_CONTEXT / GRAFF_CONTEXT_WINDOW declares the context window (in
- // tokens) for an unknown/local model whose real window graff can't look up,
- // replacing the conservative 200k fallback so the compaction gate + per-output
- // cap are sized correctly. Only affects models that fall back to the default
- // (see provider.contextWindowFor). Ignored if unparseable or 0.
- if (environ_map.get("GRAFF_CONTEXT") orelse environ_map.get("GRAFF_CONTEXT_WINDOW")) |v| {
- if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |n| {
- if (n > 0) provider_mod.g_context_override = n;
- } else |_| {}
- }
- // #204: GRAFF_COMPACT_PCT overrides the auto-compaction threshold as a percent
- // of the window (default 80). Clamped to 1..100; ignored if unparseable or 0.
- if (environ_map.get("GRAFF_COMPACT_PCT")) |v| {
- if (std.fmt.parseInt(u8, std.mem.trim(u8, v, " \t"), 10)) |pct| {
- if (pct > 0) provider_mod.g_compact_pct_override = @min(pct, 100);
- } else |_| {}
- }
- ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;
- // GRAFF_WS_FORCE_FAIL_ONCE proves a clean retry; the counted sibling proves
- // that two consecutive failures latch the SSE fallback. Test seams only.
- if (environ_map.get("GRAFF_WS_FORCE_FAIL_ONCE")) |v| {
- ws.g_force_connect_failure_once = std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "yes");
- }
- if (environ_map.get("GRAFF_WS_FORCE_FAIL_COUNT")) |v| {
- ws.g_force_connect_failure_count = std.fmt.parseInt(u8, std.mem.trim(u8, v, " \t"), 10) catch 0;
- }
- skills.loadSkillSettings(io, arena); // per-skill opt-outs, also gates the auto-connect
- anim.loadAnimationSetting(io, arena); // {"animation": "..."} → thinking spinner choice
- anim.loadThemeSetting(io, arena); // {"theme": "<name>"} → opt-in terminal color theme
- const theme_on = anim.g_theme != null and use_color and !json_mode;
- if (theme_on) {
- out.writeAll(anim.themes[anim.g_theme.?].seq) catch {};
- out.flush() catch {};
- }
- // 🎂 yxlyx's birthday glam — when graff runs from her home dir, dress her
- // Ghostty in the pastel-pink theme (limyuxi_theme: light pink bg, dark plum
- // text, pink-leaning palette) and switch the spinner to glittery sparkles.
- // Cosmetic, flagged, gated to her cwd; resets everything on exit.
- const limyuxi_glam = anim.limyuxi_birthday_white and use_color and !json_mode and
- (std.mem.eql(u8, cwd_display, "/Users/limyuxi") or std.mem.startsWith(u8, cwd_display, "/Users/limyuxi/"));
- if (limyuxi_glam) {
- out.writeAll(anim.limyuxi_theme) catch {};
- out.flush() catch {};
- if (anim.animIndex("dragon")) |gi| {
- anim.g_anim_index = gi;
- anim.g_anim_off = false;
- anim.g_anim_random = false;
- }
- }
- if (flags.selftest_spinner_flag) {
- // Headless render of the real thinking-spinner pool for the PTY anti-stealth
- // test (scripts/test-pty-spinner.py): runs the real selection (so a cwd-gated
- // pick surfaces) and prints every frame fn's output to stdout, where the test
- // scans for the U+1F4A9 / supplementary-plane glyph class the poop hid in.
- anim.selectSpinner(io);
- out.print("selected: {s}\n", .{anim.anims[anim.g_anim_current].name}) catch {};
- for (anim.anims) |a| {
- var i: usize = 0;
- while (i < 48) : (i += 1) {
- a.frame(out, i) catch {};
- out.writeByte('\n') catch {};
- }
- }
- out.flush() catch {};
- return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = true };
- }
- if (flags.selftest_markdown_flag) {
- var probe: agent_mod.Agent = .{
- .gpa = arena,
- .arena = arena,
- .io = io,
- .client = undefined,
- .provider = undefined,
- .messages = undefined,
- .sub = false,
- .label = "markdown-selftest",
- .out = out,
- };
- probe.streamMarkdown(
- \\## Gaps
- \\- No bot-specific route tests exist.
- \\- Pin `install.sh` and verify its checksum.
- \\
- \\## Recommended implementation order
- \\1. **Immediately:** require collaborator permission.
- \\2) **Next:** deduplicate `X-GitHub-Delivery`.
- \\- [ ] Add a Daytona credential preflight.
- \\- [x] Sanitize public errors.
- \\ - Preserve private incident detail.
- \\> Public errors must never expose secrets.
- );
- probe.flushStreamTail();
- out.writeByte('\n') catch {};
- out.flush() catch {};
- return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = true };
- }
- anim.loadDevSpinnerOptOut(io, arena, environ_map);
- return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = false };
-}
+// The settings/theme phase moved to session_settings.zig (#429): it is the one
+// part of this file that legitimately draws, so it sits on the terminal side of
+// the #422 boundary. Re-exported so main() still calls it through session_run.
+pub const ThemeSetup = session_settings.ThemeSetup;
+pub const setupSkillsAndTheme = session_settings.setupSkillsAndTheme;
/// Contribution is on by default, so say it once per machine before anything
/// can be sent. Quiet in --json/-p, where stdout is protocol output.
diff --git a/src/session_settings.zig b/src/session_settings.zig
new file mode 100644
index 00000000..00389c4a
--- /dev/null
+++ b/src/session_settings.zig
@@ -0,0 +1,188 @@
+//! The settings phase of startup, split out of session_run.zig (600-line goal,
+//! #429): per-skill/companion opt-outs, the env knobs that tune transports and
+//! budgets, the animation + terminal-theme preferences, the headless PTY render
+//! self-tests, and the yxlyx-birthday cosmetic theme.
+//!
+//! It lives here rather than in session_run because it is the one part of that
+//! file that legitimately DRAWS — theme escape sequences, spinner frames, a
+//! markdown probe — so it belongs on the terminal side of the #422 boundary
+//! with agent_stream_render.zig and session_render.zig, not on the engine side.
+//! session_run re-exports both names, so main() is unchanged.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const args = @import("args.zig");
+const main_mod = @import("main.zig");
+const agent_mod = @import("agent.zig");
+const http = @import("http.zig");
+const ws = @import("ws.zig");
+const agent_ws = @import("agent_ws.zig"); // codex_ws_idle_ms override (#codex-ws)
+const no_local_tools = @import("no_local_tools.zig"); // #330: GRAFF_NO_LOCAL_TOOLS
+const provider_mod = @import("provider.zig");
+const skills = @import("skills.zig");
+const anim = @import("anim.zig");
+
+pub const ThemeSetup = struct {
+ theme_on: bool,
+ limyuxi_glam: bool,
+ /// True when a PTY self-test already ran + printed its render — main()
+ /// should return immediately (but AFTER registering the theme/limyuxi
+ /// reset defers below, exactly like the original inline code did).
+ should_exit: bool,
+};
+
+/// Per-skill/companion opt-outs, animation + terminal-theme settings, the
+/// headless PTY render self-tests, and the
+/// yxlyx-birthday cosmetic theme. Moved out of main() verbatim (600-line
+/// goal). Returns which reset defers main() needs to register — the
+/// escape-code RESETS must fire when main() itself returns (not when this
+/// helper returns), so the `defer`s stay in main(), gated on the booleans
+/// this returns; main() registers them in the same order as the original
+/// inline code so LIFO defer-firing order is unchanged.
+pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out: *Io.Writer, flags: args.Flags, use_color: bool, json_mode: bool, cwd_display: []const u8) !ThemeSetup {
+ // Companion auto-activation: if the metered code-intelligence companion
+ // (codedb-pro, formerly muonry) is installed but nothing connected it (no
+ // workspace .mcp.json entry, or consent declined), spawn it directly — a
+ // user-installed companion at the same trust level as the skills
+ // auto-detection above it, NOT arbitrary workspace config.
+ main_mod.g_path_env = try arena.dupe(u8, environ_map.get("PATH") orelse "");
+ main_mod.g_codedb_guard = environ_map.get("GRAFF_NO_CODEDB_GUARD") == null; // issue #626 guard, opt-out via env
+ main_mod.g_force_stall_once = environ_map.get("GRAFF_FORCE_STALL_ONCE") != null; // #134 test seam
+ main_mod.g_force_drop_once = environ_map.get("GRAFF_FORCE_DROP_ONCE") != null; // #132/#133 test seam
+ main_mod.g_force_stall_always = environ_map.get("GRAFF_FORCE_STALL_ALWAYS") != null; // #56 test seam (exhaust the reconnect budget)
+ main_mod.g_force_drop_always = environ_map.get("GRAFF_FORCE_DROP_ALWAYS") != null; // #56 test seam
+ // #134: let a provider that buffers a long reasoning phase in total silence
+ // raise the mid-stream idle-stall cutoff (default 120s). Seconds; ignored if
+ // unparseable or 0. A stall is never a user interrupt regardless of the value.
+ if (environ_map.get("GRAFF_STREAM_STALL_SECS")) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
+ if (secs > 0) http.stream_stall_ms = @min(secs, 86_400) * 1000; // clamp: <=1 day, no u64 overflow
+ } else |_| {}
+ }
+ // #codex-ws: GRAFF_CODEX_WS=off|0|false|no (case-insensitive, the
+ // GRAFF_FLEET predicate) forces the SSE transport for codex;
+ // GRAFF_WS_DEBUG=1 dumps the ws handshake + frames to stderr. This is the
+ // SOLE parse site for the codex transport knobs — a copy in main() would
+ // be silently overwritten here, since setupSkillsAndTheme runs later.
+ if (environ_map.get("GRAFF_CODEX_WS")) |v| {
+ main_mod.g_codex_ws = !(std.ascii.eqlIgnoreCase(v, "off") or std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "no"));
+ }
+ // #225 GRAFF_CLOCK_SLEEP (root-only clock_sleep meta tool) and #330
+ // GRAFF_NO_LOCAL_TOOLS (the hard local-execution gate): both are
+ // affirmative-only (1|true|on|yes), like GRAFF_WS_FORCE_FAIL_ONCE below,
+ // and both are OR'd onto their CLI flag so a conflicting or absent env
+ // value can never silently turn --clock-sleep / --no-local-tools back off.
+ if (environ_map.get("GRAFF_CLOCK_SLEEP")) |v| {
+ main_mod.g_clock_sleep = main_mod.g_clock_sleep or std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "yes");
+ }
+ if (environ_map.get("GRAFF_NO_LOCAL_TOOLS")) |v| no_local_tools.enabled = no_local_tools.enabled or no_local_tools.envEnables(v);
+ // (#codex-ws) GRAFF_CODEX_WS_IDLE_SECS raises/lowers the held-WS idle limit
+ // (default 4 min — the backend killed ours within 8.5 min idle; opencode
+ // pools at 5). Mirrors GRAFF_STREAM_STALL_SECS above: seconds, ignored if
+ // unparseable or 0, clamped to <=1 day.
+ if (environ_map.get("GRAFF_CODEX_WS_IDLE_SECS")) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
+ if (secs > 0) agent_ws.codex_ws_idle_ms = @intCast(@min(secs, 86_400) * 1000);
+ } else |_| {}
+ }
+ // #203: GRAFF_CONTEXT / GRAFF_CONTEXT_WINDOW declares the context window (in
+ // tokens) for an unknown/local model whose real window graff can't look up,
+ // replacing the conservative 200k fallback so the compaction gate + per-output
+ // cap are sized correctly. Only affects models that fall back to the default
+ // (see provider.contextWindowFor). Ignored if unparseable or 0.
+ if (environ_map.get("GRAFF_CONTEXT") orelse environ_map.get("GRAFF_CONTEXT_WINDOW")) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |n| {
+ if (n > 0) provider_mod.g_context_override = n;
+ } else |_| {}
+ }
+ // #204: GRAFF_COMPACT_PCT overrides the auto-compaction threshold as a percent
+ // of the window (default 80). Clamped to 1..100; ignored if unparseable or 0.
+ if (environ_map.get("GRAFF_COMPACT_PCT")) |v| {
+ if (std.fmt.parseInt(u8, std.mem.trim(u8, v, " \t"), 10)) |pct| {
+ if (pct > 0) provider_mod.g_compact_pct_override = @min(pct, 100);
+ } else |_| {}
+ }
+ ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;
+ // GRAFF_WS_FORCE_FAIL_ONCE proves a clean retry; the counted sibling proves
+ // that two consecutive failures latch the SSE fallback. Test seams only.
+ if (environ_map.get("GRAFF_WS_FORCE_FAIL_ONCE")) |v| {
+ ws.g_force_connect_failure_once = std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "yes");
+ }
+ if (environ_map.get("GRAFF_WS_FORCE_FAIL_COUNT")) |v| {
+ ws.g_force_connect_failure_count = std.fmt.parseInt(u8, std.mem.trim(u8, v, " \t"), 10) catch 0;
+ }
+ skills.loadSkillSettings(io, arena); // per-skill opt-outs, also gates the auto-connect
+ anim.loadAnimationSetting(io, arena); // {"animation": "..."} → thinking spinner choice
+ anim.loadThemeSetting(io, arena); // {"theme": "<name>"} → opt-in terminal color theme
+ const theme_on = anim.g_theme != null and use_color and !json_mode;
+ if (theme_on) {
+ out.writeAll(anim.themes[anim.g_theme.?].seq) catch {};
+ out.flush() catch {};
+ }
+ // 🎂 yxlyx's birthday glam — when graff runs from her home dir, dress her
+ // Ghostty in the pastel-pink theme (limyuxi_theme: light pink bg, dark plum
+ // text, pink-leaning palette) and switch the spinner to glittery sparkles.
+ // Cosmetic, flagged, gated to her cwd; resets everything on exit.
+ const limyuxi_glam = anim.limyuxi_birthday_white and use_color and !json_mode and
+ (std.mem.eql(u8, cwd_display, "/Users/limyuxi") or std.mem.startsWith(u8, cwd_display, "/Users/limyuxi/"));
+ if (limyuxi_glam) {
+ out.writeAll(anim.limyuxi_theme) catch {};
+ out.flush() catch {};
+ if (anim.animIndex("dragon")) |gi| {
+ anim.g_anim_index = gi;
+ anim.g_anim_off = false;
+ anim.g_anim_random = false;
+ }
+ }
+ if (flags.selftest_spinner_flag) {
+ // Headless render of the real thinking-spinner pool for the PTY anti-stealth
+ // test (scripts/test-pty-spinner.py): runs the real selection (so a cwd-gated
+ // pick surfaces) and prints every frame fn's output to stdout, where the test
+ // scans for the U+1F4A9 / supplementary-plane glyph class the poop hid in.
+ anim.selectSpinner(io);
+ out.print("selected: {s}\n", .{anim.anims[anim.g_anim_current].name}) catch {};
+ for (anim.anims) |a| {
+ var i: usize = 0;
+ while (i < 48) : (i += 1) {
+ a.frame(out, i) catch {};
+ out.writeByte('\n') catch {};
+ }
+ }
+ out.flush() catch {};
+ return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = true };
+ }
+ if (flags.selftest_markdown_flag) {
+ var probe: agent_mod.Agent = .{
+ .gpa = arena,
+ .arena = arena,
+ .io = io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "markdown-selftest",
+ .out = out,
+ };
+ probe.streamMarkdown(
+ \\## Gaps
+ \\- No bot-specific route tests exist.
+ \\- Pin `install.sh` and verify its checksum.
+ \\
+ \\## Recommended implementation order
+ \\1. **Immediately:** require collaborator permission.
+ \\2) **Next:** deduplicate `X-GitHub-Delivery`.
+ \\- [ ] Add a Daytona credential preflight.
+ \\- [x] Sanitize public errors.
+ \\ - Preserve private incident detail.
+ \\> Public errors must never expose secrets.
+ );
+ probe.flushStreamTail();
+ out.writeByte('\n') catch {};
+ out.flush() catch {};
+ return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = true };
+ }
+ anim.loadDevSpinnerOptOut(io, arena, environ_map);
+ return .{ .theme_on = theme_on, .limyuxi_glam = limyuxi_glam, .should_exit = false };
+}
diff --git a/src/session_start.zig b/src/session_start.zig
index 4e207b4c..8d5ec81c 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -7,6 +7,11 @@
//! registry connect (consent prompt + companion auto-activation), and the
//! `graff repl`/one-shot-prompt early-exit paths.
//!
+//! Engine side of the #422 boundary: the banner, the worktree line, the config
+//! reports and the consent question are typed events (engine_events.zig) that a
+//! sink renders — this file names no colors and holds no key hints. The consent
+//! ANSWER is still read inline; that half belongs to input inversion (#430).
+//!
//! Same dangling-pointer discipline as startup.zig: `openTraceFile`,
//! `openBehaviorFile`, and `openTrajFile` return a plain
//! (non-self-referential) File.Writer by value — main() assigns it to its OWN
@@ -33,7 +38,6 @@ const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const pricing = @import("pricing.zig");
const skills = @import("skills.zig");
-const anim = @import("anim.zig");
const mcp = @import("mcp.zig");
const mcp_cli = @import("mcp_cli.zig");
const mcp_config = @import("mcp_config.zig");
@@ -43,11 +47,11 @@ const trace = @import("trace.zig");
const scoring = @import("scoring.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's lines are typed events, not prints
+const engine_events = @import("engine_events.zig");
const title_mod = @import("title.zig");
const fallback_config = @import("fallback_config.zig");
const repl = @import("repl.zig");
-const pickers = @import("pickers.zig");
const repl_glue = @import("repl_glue.zig");
const messages_mod = @import("messages.zig");
const session = @import("session.zig");
@@ -87,12 +91,13 @@ pub fn setupWorktreeAndBanner(
preferred_provider: ?[]const u8,
default_provider: provider_mod.Provider,
) !void {
- // Color only on an interactive terminal, and honor NO_COLOR.
+ // Color only on an interactive terminal, and honor NO_COLOR. The palette
+ // itself is a sink concern (#429); this only decides whether there is one.
if (environ_map.get("NO_COLOR") == null and (Io.File.stdout().isTty(io) catch false)) {
- ansi.style = ansi.Style.ansi;
main_mod.use_color = true;
+ engine_sink.enableColor();
}
- const style = &ansi.style;
+ const sink = engine_sink.writerSink(out);
// --worktree/-w: run this session in an isolated git worktree so parallel
// agents don't collide on files. Creates .graff/worktrees/<name> on branch
// worktree-<name> (from HEAD) and enters it; reuses it if it already exists.
@@ -114,11 +119,11 @@ pub fn setupWorktreeAndBanner(
if (std.posix.system.chdir(wt_z.ptr) != 0)
std.process.fatal("--worktree '{s}': could not enter {s} (is this a git repository?)", .{ wt, wt_path });
main_mod.g_worktree_branch = wt_branch; // non-null = auto-commit each turn to this scratch branch
- if (!main_mod.json_mode) {
- const ac: []const u8 = if (main_mod.g_worktree_autocommit) " · auto-committing each turn (`graff worktree merge` to land it)" else "";
- out.print("{s}worktree:{s} {s}{s}{s} (branch {s}) — edits isolated from the main checkout{s}\n", .{ style.dim, style.reset, style.accent, wt_path, style.reset, wt_branch, ac }) catch {};
- out.flush() catch {};
- }
+ if (!main_mod.json_mode) sink.emit(io, .{ .worktree_entered = .{
+ .path = wt_path,
+ .branch = wt_branch,
+ .autocommit = main_mod.g_worktree_autocommit,
+ } });
}
}
var cwd_buf: [4096]u8 = undefined;
@@ -137,40 +142,32 @@ pub fn setupWorktreeAndBanner(
tool_spill.enable(.{ .io = io, .dir = .cwd(), .base_abs = main_mod.g_cwd_display });
if (!main_mod.json_mode and flags.oneshot_prompt == null) {
- try out.print("{s}codegraff{s} · folder: {s}{s}{s} · / for commands · @ picks a file · esc interrupts · ↑/↓ history · tab completes · ctrl-d quits · trace → {s}\n", .{ style.bold, style.reset, style.accent, main_mod.g_cwd_display, style.reset, trace_path });
- try out.flush();
- if (codex_account) |acct| {
- try out.print("logged into Codex (ChatGPT account {s}…) — /model codex\n", .{acct[0..@min(acct.len, 8)]});
- try out.flush();
- }
- if (flags.yolo_flag) {
- try out.print("{s}⚠ YOLO{s} mode (--yolo): all bash/tool/MCP permission prompts are skipped\n", .{ style.red, style.reset });
- try out.flush();
- }
+ sink.emit(io, .{ .session_banner = .{ .cwd = main_mod.g_cwd_display, .trace_path = trace_path } });
+ if (codex_account) |acct| sink.emit(io, .{ .session_notice = .{
+ .text = try std.fmt.allocPrint(arena, "logged into Codex (ChatGPT account {s}…) — /model codex", .{acct[0..@min(acct.len, 8)]}),
+ } });
+ if (flags.yolo_flag) sink.emit(io, .{ .session_notice = .{
+ .lead = "⚠ YOLO",
+ .text = " mode (--yolo): all bash/tool/MCP permission prompts are skipped",
+ .tone = .alert,
+ } });
if (stale_saved_model) |nm| {
const allowed = fallback_config.load(io, arena);
const cross_provider = preferred_provider != null and !std.mem.eql(u8, preferred_provider.?, default_provider.id);
- const blocked = cross_provider and !fallback_config.contains(allowed, default_provider.id);
- try out.print("{s}note: saved model '{s}' is unavailable — selected {s} via {s} for this session; saved preference kept{s}{s}\n", .{
- style.dim,
- nm,
- default_provider.model,
- default_provider.id,
- if (blocked) ". Cross-provider use is blocked until /fallback allow " else "",
- if (blocked) default_provider.id else "",
- });
- try out.writeAll(style.reset);
- try out.flush();
+ sink.emit(io, .{ .saved_model_unavailable = .{
+ .saved = nm,
+ .model = default_provider.model,
+ .provider = default_provider.id,
+ .blocked = cross_provider and !fallback_config.contains(allowed, default_provider.id),
+ } });
}
- if (main_mod.show_timing or main_mod.show_cost) {
- try out.print("{s}displays on:{s}{s}{s}\n", .{
- style.dim,
+ if (main_mod.show_timing or main_mod.show_cost) sink.emit(io, .{ .session_notice = .{
+ .text = try std.fmt.allocPrint(arena, "displays on:{s}{s}", .{
if (main_mod.show_timing) " per-tool timing" else "",
if (main_mod.show_cost) " session cost" else "",
- style.reset,
- });
- try out.flush();
- }
+ }),
+ .tone = .dim,
+ } });
}
}
@@ -366,6 +363,7 @@ pub fn initTelemetry(io: Io, gpa: Allocator, client: *std.http.Client, environ_m
/// returning it is safe.
pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Writer, in: *Io.Reader, flags: args.Flags, mcp_config_path: []const u8, home: []const u8, use_color: bool, json_mode: bool, environ_map: anytype) !mcp.Registry {
const global_path = mcp_config.globalPath(arena, home, environ_map);
+ const sink = engine_sink.writerSink(out);
// --json's stdout is a JSONL stream and a one-shot's is the answer; neither
// can carry chatter. With a global config `mcp_count > 0` in every project,
// so an unguarded line here would corrupt the head of every --json run.
@@ -375,25 +373,28 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr
// Reported here rather than in `Registry.init`, which never runs when
// consent is declined — a config that does not parse must be named
// either way.
- try mcp_config.reportInvalid(merged, out, mcp_config_path, global_path, ansi.style.dim, ansi.style.reset);
+ if (merged.invalid_project) sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "{s}" ++ mcp_config.invalid_complaint, .{mcp_config_path})));
+ if (merged.invalid_global) sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "{s}" ++ mcp_config.invalid_complaint, .{global_path orelse ""})));
// A config graff does not read is worse than no config: say so once.
if (mcp_config.unsupportedConfigPresent(io, arena, home))
- try out.print("{s}ignoring ~/" ++ mcp_config.unsupported_rel_path ++ ": unsupported path — use ~/" ++ mcp_config.global_rel_path ++ " (global) or {s} (project){s}\n", .{ ansi.style.dim, mcp_config_path, ansi.style.reset });
+ sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "ignoring ~/" ++ mcp_config.unsupported_rel_path ++ ": unsupported path — use ~/" ++ mcp_config.global_rel_path ++ " (global) or {s} (project)", .{mcp_config_path})));
}
const mcp_count = mcp_cli.countMcpServers(merged);
var connect_mcp = flags.yolo_flag or mcp_count == 0;
if (mcp_count > 0 and !flags.yolo_flag and !json_mode and use_color) {
- try out.print("{s}⚠ {d} untrusted MCP server(s) are configured for this session (.mcp.json and/or ~/" ++ mcp_config.global_rel_path ++ "). They may run local commands or receive data over the network. Connect them this session? [y/N] {s}", .{ ansi.style.bold, mcp_count, ansi.style.reset });
- try out.flush();
+ sink.emit(io, .{ .mcp_consent_prompt = .{ .count = mcp_count } });
+ // Still an inline read: only the QUESTION is inverted here, and the
+ // answer becomes a typed command in #430 (input inversion).
const ans = in.takeDelimiter('\n') catch null;
connect_mcp = ans != null and ans.?.len > 0 and (ans.?[0] == 'y' or ans.?[0] == 'Y');
}
var registry: mcp.Registry = if (connect_mcp) ((mcp.Registry.init(gpa, io, mcp_config_path, global_path, home, environ_map) catch |err| inner: {
- try out.print("[mcp] init failed: {t} — continuing without MCP\n", .{err});
+ sink.emit(io, .{ .session_notice = .{ .text = try std.fmt.allocPrint(arena, "[mcp] init failed: {t} — continuing without MCP", .{err}) } });
if (telemetry.g_telem) |t| t.errorEvent("mcp", @errorName(err));
break :inner null;
}) orelse mcp.Registry.emptyWithOAuthHome(gpa, io, home)) else outer: {
- if (mcp_count > 0 and !quiet) try out.print("{s}skipped {d} MCP server(s) — /mcp trust to connect them now (or re-run with --yolo){s}\n", .{ ansi.style.dim, mcp_count, ansi.style.reset });
+ if (mcp_count > 0 and !quiet)
+ sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "skipped {d} MCP server(s) — /mcp trust to connect them now (or re-run with --yolo)", .{mcp_count})));
break :outer mcp.Registry.emptyWithOAuthHome(gpa, io, home);
};
// Set on every path, not just `init`'s: `/mcp trust` has to find the global
@@ -412,7 +413,9 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr
/// Moved out of main() (600-line goal); mutates `registry` in place (it's
/// already main()-owned and stable by the time this is called, so a pointer
/// is all that's needed — no return-by-value trickery here).
-pub fn connectCompanion(io: Io, registry: *mcp.Registry, flags: args.Flags, out: *Io.Writer, json_mode: bool, environ_map: anytype) !void {
+pub fn connectCompanion(io: Io, arena: Allocator, registry: *mcp.Registry, flags: args.Flags, out: *Io.Writer, json_mode: bool, environ_map: anytype) !void {
+ const sink = engine_sink.writerSink(out);
+ const speak = !json_mode and flags.oneshot_prompt == null;
connect: {
for (skills.companion_servers) |c| if (skills.mcpServerConnected(registry.tools, c.server)) break :connect;
for (skills.companion_servers) |c| {
@@ -420,10 +423,7 @@ pub fn connectCompanion(io: Io, registry: *mcp.Registry, flags: args.Flags, out:
if (registry.addServer(c.server, c.bin, &.{"--mcp"})) |_| {
break;
} else |err| {
- if (!json_mode and flags.oneshot_prompt == null) {
- try out.print("{s}[mcp:{s}] auto-connect failed ({t}) — native tools only{s}\n", .{ ansi.style.dim, c.server, err, ansi.style.reset });
- try out.flush();
- }
+ if (speak) sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "[mcp:{s}] auto-connect failed ({t}) — native tools only", .{ c.server, err })));
}
}
}
@@ -434,14 +434,18 @@ pub fn connectCompanion(io: Io, registry: *mcp.Registry, flags: args.Flags, out:
const access = environ_map.get("GRAFF_SMOLIFY_ACCESS") orelse "public";
const full_access = std.ascii.eqlIgnoreCase(access, "full") or std.ascii.eqlIgnoreCase(access, "authenticated");
const added = registry.connectSmolify(full_access) catch |err| {
- if (!json_mode and flags.oneshot_prompt == null) {
- try out.print("{s}[mcp:smolify] auto-connect failed ({t}) — continuing offline{s}\n", .{ ansi.style.dim, err, ansi.style.reset });
- try out.flush();
- }
+ if (speak) sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "[mcp:smolify] auto-connect failed ({t}) — continuing offline", .{err})));
return;
};
- if (added > 0 and !json_mode and flags.oneshot_prompt == null)
- try out.print("{s}[mcp:smolify] available on demand — {d} {s} tool(s){s}\n", .{ ansi.style.dim, added, if (full_access) "full-access" else "anonymous public-read", ansi.style.reset });
+ if (added > 0 and speak)
+ sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "[mcp:smolify] available on demand — {d} {s} tool(s)", .{ added, if (full_access) "full-access" else "anonymous public-read" })));
+}
+
+/// The startup cluster's most common line: dim, no badge. A helper rather than
+/// a variant — the tone is the only thing these share and the only thing a
+/// sink needs from them.
+fn dimNotice(text: []const u8) engine_events.EngineEvent {
+ return .{ .session_notice = .{ .text = text, .tone = .dim } };
}
test "core Smolify registration is offline and lazy" {
diff --git a/src/term.zig b/src/term.zig
index 7abf3e5f..fdc7049e 100644
--- a/src/term.zig
+++ b/src/term.zig
@@ -1,68 +1,17 @@
-//! Terminal primitives (std/builtin leaf, no main import): the Windows console
-//! API shim, the cross-platform raw-mode / stdin-poll `tty` layer, terminal
-//! size (termCols/termRows), the streamed-reasoning row counter, and the
-//! stdin-ready polls. Split out of main.zig (600-line goal). main re-exports
-//! win (hooks.zig back-imports it) and aliases the rest back so call sites stay
+//! Terminal primitives (std/builtin leaf, no main import): the cross-platform
+//! raw-mode / stdin-poll `tty` layer, terminal size (termCols/termRows), the
+//! streamed-reasoning row counter, and the stdin-ready polls. Split out of
+//! main.zig (600-line goal). main aliases the rest back so call sites stay
//! unqualified.
+//!
+//! The Windows console/pipe shim moved to win_api.zig (#429) and is re-exported
+//! below: hooks.zig wants one call out of it (PeekNamedPipe) and must not have
+//! to import the terminal cluster to get it.
const std = @import("std");
const builtin = @import("builtin");
-pub const win = struct {
- const HANDLE = *anyopaque;
- const BOOL = i32;
- const DWORD = u32;
- const WORD = u16;
- const WCHAR = u16;
- const SHORT = i16;
-
- const STD_INPUT_HANDLE: DWORD = 0xFFFFFFF6; // (DWORD)-10
- const STD_OUTPUT_HANDLE: DWORD = 0xFFFFFFF5; // (DWORD)-11
-
- const ENABLE_PROCESSED_INPUT: DWORD = 0x0001;
- const ENABLE_LINE_INPUT: DWORD = 0x0002;
- const ENABLE_ECHO_INPUT: DWORD = 0x0004;
- const ENABLE_VIRTUAL_TERMINAL_INPUT: DWORD = 0x0200;
- const ENABLE_PROCESSED_OUTPUT: DWORD = 0x0001;
- const ENABLE_VIRTUAL_TERMINAL_PROCESSING: DWORD = 0x0004;
-
- const WAIT_OBJECT_0: DWORD = 0x0;
- const INFINITE: DWORD = 0xFFFFFFFF;
- const KEY_EVENT: WORD = 0x0001;
-
- const COORD = extern struct { X: SHORT, Y: SHORT };
- const SMALL_RECT = extern struct { Left: SHORT, Top: SHORT, Right: SHORT, Bottom: SHORT };
- const CONSOLE_SCREEN_BUFFER_INFO = extern struct {
- dwSize: COORD,
- dwCursorPosition: COORD,
- wAttributes: WORD,
- srWindow: SMALL_RECT,
- dwMaximumWindowSize: COORD,
- };
- const KEY_EVENT_RECORD = extern struct {
- bKeyDown: BOOL,
- wRepeatCount: WORD,
- wVirtualKeyCode: WORD,
- wVirtualScanCode: WORD,
- UnicodeChar: WCHAR,
- dwControlKeyState: DWORD,
- };
- // EventType (WORD) + ABI padding + the 16-byte event union, modeled as its
- // largest relevant member (KEY_EVENT_RECORD), totals 20 bytes — the C size.
- const INPUT_RECORD = extern struct {
- EventType: WORD,
- KeyEvent: KEY_EVENT_RECORD,
- };
-
- extern "kernel32" fn GetStdHandle(nStdHandle: DWORD) callconv(.winapi) HANDLE;
- extern "kernel32" fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *DWORD) callconv(.winapi) BOOL;
- extern "kernel32" fn SetConsoleMode(hConsoleHandle: HANDLE, dwMode: DWORD) callconv(.winapi) BOOL;
- extern "kernel32" fn GetConsoleScreenBufferInfo(hConsoleOutput: HANDLE, lpInfo: *CONSOLE_SCREEN_BUFFER_INFO) callconv(.winapi) BOOL;
- extern "kernel32" fn GetNumberOfConsoleInputEvents(hConsoleInput: HANDLE, lpNumberOfEvents: *DWORD) callconv(.winapi) BOOL;
- extern "kernel32" fn ReadConsoleInputW(hConsoleInput: HANDLE, lpBuffer: [*]INPUT_RECORD, nLength: DWORD, lpRead: *DWORD) callconv(.winapi) BOOL;
- extern "kernel32" fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) callconv(.winapi) DWORD;
- pub extern "kernel32" fn PeekNamedPipe(hNamedPipe: HANDLE, lpBuffer: ?*anyopaque, nBufferSize: DWORD, lpBytesRead: ?*DWORD, lpTotalBytesAvail: ?*DWORD, lpBytesLeftThisMessage: ?*DWORD) callconv(.winapi) BOOL;
-};
+pub const win = @import("win_api.zig");
/// Cross-platform terminal control. POSIX uses termios + ioctl(TIOCGWINSZ) +
/// poll; Windows uses the console API (Get/SetConsoleMode, screen-buffer info,
@@ -549,11 +498,17 @@ test "#396 firewall: the idle prompt read is job-control aware and gives the tty
test "#396 firewall: both completion paths release the terminal" {
// One-shot (`-p`, the headless --yolo path) releases at the end of the run,
- // after the answer is printed and the session saved.
+ // after the answer is printed and the session saved. Since #429 it says so
+ // as a typed event — the engine no longer touches the tty itself — so the
+ // pin follows the emission, and a second pin holds the sink arm that turns
+ // it back into a release. Both halves have to exist or the run never gives
+ // the terminal back.
const oneshot = @embedFile("session_run.zig");
const answer_at = std.mem.indexOf(u8, oneshot, "session.saveSession(root, arena, root.session_name)").?;
- const release_at = std.mem.indexOf(u8, oneshot, "terminal.tty.releaseTerminal();").?;
+ const release_at = std.mem.indexOf(u8, oneshot, ".emit(io, .run_finished);").?;
try std.testing.expect(answer_at < release_at);
+ const sink = @embedFile("session_render.zig");
+ try std.testing.expect(std.mem.indexOf(u8, sink, ".run_finished => terminal.tty.releaseTerminal(),") != null);
// The interactive loop releases on ANY exit, and its defer is registered
// last so LIFO teardown runs it first — before flushSavesAtExit and the
// slower telemetry/learning phases main() owns.
diff --git a/src/win_api.zig b/src/win_api.zig
new file mode 100644
index 00000000..98e88fd2
--- /dev/null
+++ b/src/win_api.zig
@@ -0,0 +1,65 @@
+//! The Windows console/pipe API shim: the kernel32 externs and the ABI structs
+//! the harness needs, and nothing else. A std/builtin leaf with no imports at
+//! all, so a caller may reach for one syscall without taking a dependency it
+//! does not want.
+//!
+//! Split out of term.zig (#422/#429): the shim lived inside the terminal
+//! module, so hooks.zig — which wants exactly ONE call, PeekNamedPipe, to poll
+//! a child's stderr pipe — had to import the terminal cluster to get it.
+//! term.zig keeps `pub const win = @import("win_api.zig")`, so its own call
+//! sites are unchanged; the declarations are `pub` because they now cross a
+//! file boundary, not because anything else should reach for them.
+
+pub const HANDLE = *anyopaque;
+pub const BOOL = i32;
+pub const DWORD = u32;
+pub const WORD = u16;
+pub const WCHAR = u16;
+pub const SHORT = i16;
+
+pub const STD_INPUT_HANDLE: DWORD = 0xFFFFFFF6; // (DWORD)-10
+pub const STD_OUTPUT_HANDLE: DWORD = 0xFFFFFFF5; // (DWORD)-11
+
+pub const ENABLE_PROCESSED_INPUT: DWORD = 0x0001;
+pub const ENABLE_LINE_INPUT: DWORD = 0x0002;
+pub const ENABLE_ECHO_INPUT: DWORD = 0x0004;
+pub const ENABLE_VIRTUAL_TERMINAL_INPUT: DWORD = 0x0200;
+pub const ENABLE_PROCESSED_OUTPUT: DWORD = 0x0001;
+pub const ENABLE_VIRTUAL_TERMINAL_PROCESSING: DWORD = 0x0004;
+
+pub const WAIT_OBJECT_0: DWORD = 0x0;
+pub const INFINITE: DWORD = 0xFFFFFFFF;
+pub const KEY_EVENT: WORD = 0x0001;
+
+pub const COORD = extern struct { X: SHORT, Y: SHORT };
+pub const SMALL_RECT = extern struct { Left: SHORT, Top: SHORT, Right: SHORT, Bottom: SHORT };
+pub const CONSOLE_SCREEN_BUFFER_INFO = extern struct {
+ dwSize: COORD,
+ dwCursorPosition: COORD,
+ wAttributes: WORD,
+ srWindow: SMALL_RECT,
+ dwMaximumWindowSize: COORD,
+};
+pub const KEY_EVENT_RECORD = extern struct {
+ bKeyDown: BOOL,
+ wRepeatCount: WORD,
+ wVirtualKeyCode: WORD,
+ wVirtualScanCode: WORD,
+ UnicodeChar: WCHAR,
+ dwControlKeyState: DWORD,
+};
+// EventType (WORD) + ABI padding + the 16-byte event union, modeled as its
+// largest relevant member (KEY_EVENT_RECORD), totals 20 bytes — the C size.
+pub const INPUT_RECORD = extern struct {
+ EventType: WORD,
+ KeyEvent: KEY_EVENT_RECORD,
+};
+
+pub extern "kernel32" fn GetStdHandle(nStdHandle: DWORD) callconv(.winapi) HANDLE;
+pub extern "kernel32" fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *DWORD) callconv(.winapi) BOOL;
+pub extern "kernel32" fn SetConsoleMode(hConsoleHandle: HANDLE, dwMode: DWORD) callconv(.winapi) BOOL;
+pub extern "kernel32" fn GetConsoleScreenBufferInfo(hConsoleOutput: HANDLE, lpInfo: *CONSOLE_SCREEN_BUFFER_INFO) callconv(.winapi) BOOL;
+pub extern "kernel32" fn GetNumberOfConsoleInputEvents(hConsoleInput: HANDLE, lpNumberOfEvents: *DWORD) callconv(.winapi) BOOL;
+pub extern "kernel32" fn ReadConsoleInputW(hConsoleInput: HANDLE, lpBuffer: [*]INPUT_RECORD, nLength: DWORD, lpRead: *DWORD) callconv(.winapi) BOOL;
+pub extern "kernel32" fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) callconv(.winapi) DWORD;
+pub extern "kernel32" fn PeekNamedPipe(hNamedPipe: HANDLE, lpBuffer: ?*anyopaque, nBufferSize: DWORD, lpBytesRead: ?*DWORD, lpTotalBytesAvail: ?*DWORD, lpBytesLeftThisMessage: ?*DWORD) callconv(.winapi) BOOL;