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 long tail sheds the terminal cluster (#429)

Rach Pradhan58799dc8c6eb
diff --git a/src/agent_prompt.zig b/src/agent_prompt.zig
index f9eaad5d..66293733 100644
--- a/src/agent_prompt.zig
+++ b/src/agent_prompt.zig
@@ -1,231 +1,108 @@
-//! Compact prompt badges and context-meter formatting, plus Agent.prompt()
-//! itself: the width-budgeted interactive status line (#209). Split out of
-//! agent.zig (600-line goal); agent_mod is only imported for the `Agent` type
-//! the moved method's `self` parameter needs — see agent_table.zig for the
-//! same self-contained-sibling pattern.
+//! Agent.prompt(): the engine half of the interactive status line (#209, #429).
+//!
+//! It reads the session's state and emits ONE `.prompt_ready` event; how that
+//! is drawn — palette, badge frame, the width budget that decides which
+//! segments survive a narrow pane — belongs to agent_prompt_render.zig behind
+//! the sink. Split out of agent.zig (600-line goal); agent_mod is only imported
+//! for the `Agent` type the moved method's `self` parameter needs — see
+//! agent_table.zig for the same self-contained-sibling pattern.
const std = @import("std");
-const Io = std.Io;
-const style = &@import("ansi.zig").style;
const main_mod = @import("main.zig");
const pricing = @import("pricing.zig");
const learning_privacy = @import("learning_privacy.zig");
-const terminal = @import("term.zig");
+const engine_events = @import("engine_events.zig");
+const engine_sink = @import("engine_sink.zig");
const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
-pub fn reasoningLabel(effort: anytype) []const u8 {
- return switch (effort) {
- .low => "Low",
- .medium => "Medium",
- .high => "High",
- .xhigh => "Extra high",
- .max => "Max",
- .ultra => "Ultra",
- };
-}
-
-pub fn reasoningColor(effort: anytype) []const u8 {
- return switch (effort) {
- .low => style.green,
- .medium => style.accent,
- .high => style.yellow,
- .xhigh => style.accent,
- .max => style.red,
- .ultra => style.accent,
- };
-}
-
-pub fn writeBadge(writer: *Io.Writer, color: []const u8, label: []const u8) !void {
- try writer.print("{s} · {s}{s}{s}{s}", .{ style.dim, style.reset, color, label, style.reset });
-}
-
-/// Include a status-line segment only if its width still fits the remaining
-/// budget, charging it against `used` when it does. Lets Agent.prompt() drop
-/// low-priority metadata (cwd, context meter, cache/cost) instead of letting
-/// the terminal soft-wrap the line mid-badge in a narrow pane — e.g. splitting
-/// `codex` across the edge and stranding the cursor inside the label (#209).
-pub fn fitsSegment(used: *usize, avail: usize, seg_width: usize) bool {
- if (used.* + seg_width <= avail) {
- used.* += seg_width;
- return true;
- }
- return false;
-}
-
/// The interactive status line printed before each human turn: model,
/// mode/permission badges, cwd, and the live context/cache/cost meter.
-/// Width-budgeted against the terminal so a narrow pane never soft-wraps
-/// mid-badge (splitting e.g. `codex`) and strands the cursor inside a label
-/// (#209); low-priority metadata (cwd, context, cache, cost) is the first to
-/// drop when it no longer fits. See fitsSegment's doc comment for the rest.
pub fn prompt(self: *Agent) !void {
if (main_mod.json_mode) return; // SDK drives turns; no human prompt
- const w = self.out orelse return;
- var cbuf: [40]u8 = undefined;
- const cost: []const u8 = if (!main_mod.show_cost) "" else blk: {
- if (std.mem.eql(u8, self.provider.id, "codex"))
- break :blk " · sub";
- if (pricing.priceFor(self.provider.model) == null) break :blk " · $?";
- break :blk std.fmt.bufPrint(&cbuf, " · ${d:.4}", .{pricing.g_cost.snap(self.io).usd}) catch "";
- };
- // Prompt-cache hit from the last response — proof caching is working.
- var kbuf: [32]u8 = undefined;
- var kval: [24]u8 = undefined;
- const cached: []const u8 = if (self.last_cache_read > 0)
- (std.fmt.bufPrint(&kbuf, " · ⚡{s} cached", .{compactTokenCount(&kval, self.last_cache_read)}) catch "")
- else
- "";
- const context_tokens = self.effectiveContextTokens();
- var ctxbuf: [80]u8 = undefined;
- var used_buf: [24]u8 = undefined;
- const ctx: []const u8 = if (self.last_context_tokens > 0) blk: {
- const threshold = self.provider.compactAt();
- const pct = contextPercent(context_tokens, self.provider.context);
- break :blk std.fmt.bufPrint(&ctxbuf, " · {s}/{d}k ctx ({d}% · compact@{d}k)", .{
- compactTokenCount(&used_buf, context_tokens),
- self.provider.context / 1000,
- pct,
- threshold / 1000,
- }) catch "";
- } else "";
- const privacy_mode = learning_privacy.current();
- const privacy_label = privacy_mode.badge();
- const privacy_color = switch (privacy_mode) {
- .local, .aggregate => style.green,
- .templates => style.yellow,
- .examples => style.red,
- };
-
- // Budget the status line against terminal width so a narrow pane never
- // soft-wraps mid-badge (splitting e.g. `codex`) and strands the cursor
- // inside a label (#209). The model plus the badges that disambiguate the
- // cursor (effort/provider/mode/privacy) are offered first; cwd/context/
- // cache/cost are the first to drop when they no longer fit. readline.zig
- // still gives the input its own row if what remains is cramped. Byte
- // length (not display-column width) is used as the budget metric: for
- // UTF-8 it is always >= true display width, so the estimate only ever
- // errs conservative and can't itself cause an overflow/wrap.
- //
- // Reserve the fixed frame ('[' + '] › ' = 5 cols) plus 1 column of slack
- // so a width miscount can't tip the line into a wrap.
- const avail = terminal.termCols() -| 6;
- var used: usize = self.provider.model.len;
- const show_fast = self.fast and self.provider.kind == .responses and
- fitsSegment(&used, avail, 3 + "Fast".len);
- const show_effort = self.effortApplies() and
- fitsSegment(&used, avail, 3 + reasoningLabel(self.reasoning).len);
- const show_provider = fitsSegment(&used, avail, 3 + self.provider.id.len);
- const show_fallback = self.fallback_active and
- fitsSegment(&used, avail, 3 + "Fallback".len);
- const show_plan = main_mod.plan_mode and fitsSegment(&used, avail, 3 + "Plan".len);
- const show_strict = self.strict and fitsSegment(&used, avail, 3 + "Strict".len);
- const show_ultra = self.ultracode_mode and fitsSegment(&used, avail, 3 + "Ultracode".len);
- const show_privacy = fitsSegment(&used, avail, 3 + privacy_label.len);
- // The context meter outranks cwd for the budget (it is the urgent,
- // changing signal near the compaction threshold) but still renders after
- // cwd below, preserving the familiar order when both fit.
- const show_ctx = ctx.len > 0 and fitsSegment(&used, avail, ctx.len);
- const show_cwd = fitsSegment(&used, avail, 7 + main_mod.g_cwd_display.len);
- // cached only ever accompanies the context meter (both come from the
- // same response's usage payload), matching the pre-#209 layout.
- const show_cached = show_ctx and cached.len > 0 and fitsSegment(&used, avail, cached.len);
- const show_cost = cost.len > 0 and fitsSegment(&used, avail, cost.len);
-
- try w.print("\n{s}[{s}{s}{s}{s}", .{ style.dim, style.reset, style.accent, self.provider.model, style.reset });
- // Fast is the most operationally important model setting, so keep it
- // immediately beside the model instead of letting permission modes push
- // it deeper into the status line.
- if (show_fast) try writeBadge(w, style.green, "Fast");
- if (show_effort) try writeBadge(w, reasoningColor(self.reasoning), reasoningLabel(self.reasoning));
- if (show_provider) try writeBadge(w, style.accent, self.provider.id);
- if (show_fallback) try writeBadge(w, style.yellow, "Fallback");
- if (show_plan) try writeBadge(w, style.yellow, "Plan");
- if (show_strict) try writeBadge(w, style.red, "Strict");
- if (show_ultra) try writeBadge(w, style.accent, "Ultracode");
- if (show_privacy) try writeBadge(w, privacy_color, privacy_label);
- try w.print("{s}", .{style.dim});
- if (show_cwd) try w.print(" · cwd {s}{s}{s}", .{ style.reset, main_mod.g_cwd_display, style.dim });
- if (show_ctx) try w.print("{s}", .{ctx});
- if (show_cached) try w.print("{s}", .{cached});
- if (show_cost) try w.print("{s}", .{cost});
- try w.print("{s}]{s} {s}{s}›{s} ", .{ style.reset, style.reset, style.bold, style.accent, style.reset });
- try w.flush();
-}
-
-pub fn compactTokenCount(buf: []u8, tokens: u64) []const u8 {
- return if (tokens >= 1000)
- std.fmt.bufPrint(buf, "{d}k", .{tokens / 1000}) catch "?"
- else
- std.fmt.bufPrint(buf, "{d}", .{tokens}) catch "?";
-}
-
-pub fn contextPercent(tokens: u64, window: u64) u64 {
- if (window == 0) return 0;
- return @min((tokens *| 100) / window, 100);
+ if (self.out == null) return; // nothing to draw on
+ engine_sink.forAgent(self).emit(self.io, .{ .prompt_ready = status(self) });
}
-test "reasoning prompt label uses picker wording" {
- const Effort = enum { low, medium, high, xhigh, max, ultra };
- try std.testing.expectEqualStrings("Low", reasoningLabel(Effort.low));
- try std.testing.expectEqualStrings("Medium", reasoningLabel(Effort.medium));
- try std.testing.expectEqualStrings("High", reasoningLabel(Effort.high));
- try std.testing.expectEqualStrings("Extra high", reasoningLabel(Effort.xhigh));
- try std.testing.expectEqualStrings("Max", reasoningLabel(Effort.max));
- try std.testing.expectEqualStrings("Ultra", reasoningLabel(Effort.ultra));
+/// Snapshot the session as the status line describes it. Every field is
+/// semantic: no widths, no colors, no assembled segments.
+fn status(self: *Agent) engine_events.PromptStatus {
+ return .{
+ .model = self.provider.model,
+ .provider_id = self.provider.id,
+ .cwd = main_mod.g_cwd_display,
+ .privacy_label = learning_privacy.current().badge(),
+ .privacy = privacyTier(learning_privacy.current()),
+ .effort = if (self.effortApplies()) effortTier(self.reasoning) else null,
+ // The meter appears only once a response has reported usage, but the
+ // count it shows is the EFFECTIVE one (local estimates carry it
+ // between turns) — two different questions, as it has always been.
+ .context = if (self.last_context_tokens > 0) .{
+ .tokens = self.effectiveContextTokens(),
+ .window = self.provider.context,
+ .compact_at = self.provider.compactAt(),
+ } else null,
+ .cache_read = self.last_cache_read,
+ .cost = cost(self),
+ // The Fast badge is a `responses`-shaped concept; on any other wire
+ // format the flag exists but means nothing, so no badge is offered.
+ .fast = self.fast and self.provider.kind == .responses,
+ .fallback = self.fallback_active,
+ .plan = main_mod.plan_mode,
+ .strict = self.strict,
+ .ultracode = self.ultracode_mode,
+ };
}
-test "compact token counts keep prompt usage readable" {
- var buf: [24]u8 = undefined;
- try std.testing.expectEqualStrings("999", compactTokenCount(&buf, 999));
- try std.testing.expectEqualStrings("138k", compactTokenCount(&buf, 138_082));
+/// Same order of questions the inline meter asked: off, then flat-rate, then
+/// unpriced, and only then is a real figure snapshotted.
+fn cost(self: *Agent) engine_events.CostMeter {
+ if (!main_mod.show_cost) return .hidden;
+ if (std.mem.eql(u8, self.provider.id, "codex")) return .subscription;
+ if (pricing.priceFor(self.provider.model) == null) return .unpriced;
+ return .{ .usd = pricing.g_cost.snap(self.io).usd };
}
-test "context percent saturates malformed or over-window server meters" {
- try std.testing.expectEqual(@as(u64, 0), contextPercent(100, 0));
- try std.testing.expectEqual(@as(u64, 50), contextPercent(50_000, 100_000));
- try std.testing.expectEqual(@as(u64, 100), contextPercent(150_000, 100_000));
- try std.testing.expectEqual(@as(u64, 100), contextPercent(std.math.maxInt(u64), 100_000));
-}
+// Both maps are exhaustive on purpose: a new tier upstream becomes a compile
+// error here rather than a silently mistranslated badge.
-test "fitsSegment charges the budget only on a fit, #209" {
- var used: usize = 10;
- try std.testing.expect(fitsSegment(&used, 20, 5)); // 10 + 5 <= 20
- try std.testing.expectEqual(@as(usize, 15), used);
- try std.testing.expect(!fitsSegment(&used, 20, 10)); // 15 + 10 > 20: rejected
- try std.testing.expectEqual(@as(usize, 15), used); // unchanged on rejection
- try std.testing.expect(fitsSegment(&used, 20, 5)); // exact fit still counts
- try std.testing.expectEqual(@as(usize, 20), used);
+fn effortTier(effort: main_mod.ReasoningEffort) engine_events.ReasoningEffort {
+ return switch (effort) {
+ .low => .low,
+ .medium => .medium,
+ .high => .high,
+ .xhigh => .xhigh,
+ .max => .max,
+ .ultra => .ultra,
+ };
}
-test "narrow pane drops cwd/context but keeps model+mode badges whole, #209" {
- // Reproduces the issue's 28-col tmux repro: `[gpt-5.6-sol · High · codex`
- // used to soft-wrap mid-badge because prompt() never budgeted against
- // termCols(). Budgeting the same segment widths here must keep the
- // high-priority model/effort/provider badges intact and never let the
- // running total exceed the pane, while cwd/context (low priority) give way.
- const cols: usize = 28;
- const avail = cols -| 6; // fixed frame ('[' + '] › ') + 1 col slack
- var used: usize = "gpt-5.6-sol".len;
- const show_effort = fitsSegment(&used, avail, 3 + "High".len);
- const show_provider = fitsSegment(&used, avail, 3 + "codex".len);
- const show_cwd = fitsSegment(&used, avail, 7 + "/path/to/project".len);
- const show_ctx = fitsSegment(&used, avail, " · 12k/100k ctx (12% · compact@80k)".len);
- try std.testing.expect(show_effort);
- try std.testing.expect(used <= avail); // never overflows the pane itself
- _ = show_provider; // may or may not fit at this extreme width; never split either way
- try std.testing.expect(!show_cwd); // low-priority metadata is the first to go
- try std.testing.expect(!show_ctx);
+fn privacyTier(mode: learning_privacy.Mode) engine_events.PrivacyTier {
+ return switch (mode) {
+ .local => .local,
+ .aggregate => .aggregate,
+ .templates => .templates,
+ .examples => .examples,
+ };
}
-test "wide pane keeps every segment, matching the pre-#209 behaviour" {
- // A generous pane must still show everything, proving the budget is real
- // width-awareness and not an unconditional strip of metadata.
- const cols: usize = 200;
- const avail = cols -| 6;
- var used: usize = "gpt-5.6-sol".len;
- try std.testing.expect(fitsSegment(&used, avail, 3 + "High".len));
- try std.testing.expect(fitsSegment(&used, avail, 3 + "codex".len));
- try std.testing.expect(fitsSegment(&used, avail, 7 + "/path/to/project".len));
- try std.testing.expect(fitsSegment(&used, avail, " · 12k/100k ctx (12% · compact@80k)".len));
+test "the vocabulary's tiers stay in step with the engine's own enums" {
+ // effortTier/privacyTier exist so engine_events.zig owns its value types
+ // without importing main.zig. That only holds while the two sets agree:
+ // a tier added on one side and not the other would render as the wrong
+ // badge, which no test of either enum alone would catch.
+ try std.testing.expectEqual(
+ std.meta.tags(main_mod.ReasoningEffort).len,
+ std.meta.tags(engine_events.ReasoningEffort).len,
+ );
+ try std.testing.expectEqual(
+ std.meta.tags(learning_privacy.Mode).len,
+ std.meta.tags(engine_events.PrivacyTier).len,
+ );
+ inline for (std.meta.tags(main_mod.ReasoningEffort)) |e| {
+ try std.testing.expectEqualStrings(@tagName(e), @tagName(effortTier(e)));
+ }
+ inline for (std.meta.tags(learning_privacy.Mode)) |m| {
+ try std.testing.expectEqualStrings(@tagName(m), @tagName(privacyTier(m)));
+ }
}
diff --git a/src/agent_prompt_render.zig b/src/agent_prompt_render.zig
new file mode 100644
index 00000000..de5989b4
--- /dev/null
+++ b/src/agent_prompt_render.zig
@@ -0,0 +1,375 @@
+//! The terminal half of the interactive status line (#422/#429): everything
+//! about how `.prompt_ready` is DRAWN — the palette, the badge frame, and the
+//! #209 width budget. Reached only from engine_sink's TuiSink, the same shape
+//! agent_stream_render.zig and agent_tool_render.zig have for their clusters;
+//! this is one of the few files down here that may touch ansi/term.
+//!
+//! Every function is the old inline agent_prompt.zig code path, gate for gate,
+//! and the layout is asserted byte-for-byte by the tests at the bottom. The one
+//! deliberate difference from the pre-#429 path: a write error is swallowed
+//! rather than propagated, because a sink emit returns void. Every other
+//! TuiSink branch already behaves that way, and the only way to reach it is a
+//! terminal that has gone away mid-prompt.
+
+const std = @import("std");
+const Io = std.Io;
+
+const style = &@import("ansi.zig").style;
+const terminal = @import("term.zig");
+const engine_events = @import("engine_events.zig");
+const PromptStatus = engine_events.PromptStatus;
+
+pub fn reasoningLabel(effort: anytype) []const u8 {
+ return switch (effort) {
+ .low => "Low",
+ .medium => "Medium",
+ .high => "High",
+ .xhigh => "Extra high",
+ .max => "Max",
+ .ultra => "Ultra",
+ };
+}
+
+pub fn reasoningColor(effort: anytype) []const u8 {
+ return switch (effort) {
+ .low => style.green,
+ .medium => style.accent,
+ .high => style.yellow,
+ .xhigh => style.accent,
+ .max => style.red,
+ .ultra => style.accent,
+ };
+}
+
+fn privacyColor(tier: engine_events.PrivacyTier) []const u8 {
+ return switch (tier) {
+ .local, .aggregate => style.green,
+ .templates => style.yellow,
+ .examples => style.red,
+ };
+}
+
+pub fn writeBadge(writer: *Io.Writer, color: []const u8, label: []const u8) !void {
+ try writer.print("{s} · {s}{s}{s}{s}", .{ style.dim, style.reset, color, label, style.reset });
+}
+
+/// Include a status-line segment only if its width still fits the remaining
+/// budget, charging it against `used` when it does. Lets the status line drop
+/// low-priority metadata (cwd, context meter, cache/cost) instead of letting
+/// the terminal soft-wrap the line mid-badge in a narrow pane — e.g. splitting
+/// `codex` across the edge and stranding the cursor inside the label (#209).
+pub fn fitsSegment(used: *usize, avail: usize, seg_width: usize) bool {
+ if (used.* + seg_width <= avail) {
+ used.* += seg_width;
+ return true;
+ }
+ return false;
+}
+
+pub fn compactTokenCount(buf: []u8, tokens: u64) []const u8 {
+ return if (tokens >= 1000)
+ std.fmt.bufPrint(buf, "{d}k", .{tokens / 1000}) catch "?"
+ else
+ std.fmt.bufPrint(buf, "{d}", .{tokens}) catch "?";
+}
+
+pub fn contextPercent(tokens: u64, window: u64) u64 {
+ if (window == 0) return 0;
+ return @min((tokens *| 100) / window, 100);
+}
+
+/// Draw the status line for one `.prompt_ready`. Width-budgeted against the
+/// terminal so a narrow pane never soft-wraps mid-badge (splitting e.g.
+/// `codex`) and strands the cursor inside a label (#209); low-priority
+/// metadata (cwd, context, cache, cost) is the first to drop when it no longer
+/// fits. See fitsSegment's doc comment for the rest.
+pub fn promptLine(w: *Io.Writer, st: PromptStatus) void {
+ // The one environment read in this file, kept at the edge so the layout
+ // below is a pure function of (status, width) and can be pinned by tests.
+ line(w, st, terminal.termCols()) catch return;
+}
+
+fn line(w: *Io.Writer, st: PromptStatus, cols: usize) !void {
+ var cbuf: [40]u8 = undefined;
+ const cost: []const u8 = switch (st.cost) {
+ .hidden => "",
+ .subscription => " · sub",
+ .unpriced => " · $?",
+ .usd => |usd| std.fmt.bufPrint(&cbuf, " · ${d:.4}", .{usd}) catch "",
+ };
+ // Prompt-cache hit from the last response — proof caching is working.
+ var kbuf: [32]u8 = undefined;
+ var kval: [24]u8 = undefined;
+ const cached: []const u8 = if (st.cache_read > 0)
+ (std.fmt.bufPrint(&kbuf, " · ⚡{s} cached", .{compactTokenCount(&kval, st.cache_read)}) catch "")
+ else
+ "";
+ var ctxbuf: [80]u8 = undefined;
+ var used_buf: [24]u8 = undefined;
+ const ctx: []const u8 = if (st.context) |meter|
+ (std.fmt.bufPrint(&ctxbuf, " · {s}/{d}k ctx ({d}% · compact@{d}k)", .{
+ compactTokenCount(&used_buf, meter.tokens),
+ meter.window / 1000,
+ contextPercent(meter.tokens, meter.window),
+ meter.compact_at / 1000,
+ }) catch "")
+ else
+ "";
+
+ // Budget the status line against terminal width so a narrow pane never
+ // soft-wraps mid-badge (splitting e.g. `codex`) and strands the cursor
+ // inside a label (#209). The model plus the badges that disambiguate the
+ // cursor (effort/provider/mode/privacy) are offered first; cwd/context/
+ // cache/cost are the first to drop when they no longer fit. readline.zig
+ // still gives the input its own row if what remains is cramped. Byte
+ // length (not display-column width) is used as the budget metric: for
+ // UTF-8 it is always >= true display width, so the estimate only ever
+ // errs conservative and can't itself cause an overflow/wrap.
+ //
+ // Reserve the fixed frame ('[' + '] › ' = 5 cols) plus 1 column of slack
+ // so a width miscount can't tip the line into a wrap.
+ const avail = cols -| 6;
+ var used: usize = st.model.len;
+ const show_fast = st.fast and fitsSegment(&used, avail, 3 + "Fast".len);
+ const show_effort = st.effort != null and
+ fitsSegment(&used, avail, 3 + reasoningLabel(st.effort.?).len);
+ const show_provider = fitsSegment(&used, avail, 3 + st.provider_id.len);
+ const show_fallback = st.fallback and
+ fitsSegment(&used, avail, 3 + "Fallback".len);
+ const show_plan = st.plan and fitsSegment(&used, avail, 3 + "Plan".len);
+ const show_strict = st.strict and fitsSegment(&used, avail, 3 + "Strict".len);
+ const show_ultra = st.ultracode and fitsSegment(&used, avail, 3 + "Ultracode".len);
+ const show_privacy = fitsSegment(&used, avail, 3 + st.privacy_label.len);
+ // The context meter outranks cwd for the budget (it is the urgent,
+ // changing signal near the compaction threshold) but still renders after
+ // cwd below, preserving the familiar order when both fit.
+ const show_ctx = ctx.len > 0 and fitsSegment(&used, avail, ctx.len);
+ const show_cwd = fitsSegment(&used, avail, 7 + st.cwd.len);
+ // cached only ever accompanies the context meter (both come from the
+ // same response's usage payload), matching the pre-#209 layout.
+ const show_cached = show_ctx and cached.len > 0 and fitsSegment(&used, avail, cached.len);
+ const show_cost = cost.len > 0 and fitsSegment(&used, avail, cost.len);
+
+ try w.print("\n{s}[{s}{s}{s}{s}", .{ style.dim, style.reset, style.accent, st.model, style.reset });
+ // Fast is the most operationally important model setting, so keep it
+ // immediately beside the model instead of letting permission modes push
+ // it deeper into the status line.
+ if (show_fast) try writeBadge(w, style.green, "Fast");
+ if (show_effort) try writeBadge(w, reasoningColor(st.effort.?), reasoningLabel(st.effort.?));
+ if (show_provider) try writeBadge(w, style.accent, st.provider_id);
+ if (show_fallback) try writeBadge(w, style.yellow, "Fallback");
+ if (show_plan) try writeBadge(w, style.yellow, "Plan");
+ if (show_strict) try writeBadge(w, style.red, "Strict");
+ if (show_ultra) try writeBadge(w, style.accent, "Ultracode");
+ if (show_privacy) try writeBadge(w, privacyColor(st.privacy), st.privacy_label);
+ try w.print("{s}", .{style.dim});
+ if (show_cwd) try w.print(" · cwd {s}{s}{s}", .{ style.reset, st.cwd, style.dim });
+ if (show_ctx) try w.print("{s}", .{ctx});
+ if (show_cached) try w.print("{s}", .{cached});
+ if (show_cost) try w.print("{s}", .{cost});
+ try w.print("{s}]{s} {s}{s}›{s} ", .{ style.reset, style.reset, style.bold, style.accent, style.reset });
+ try w.flush();
+}
+
+test "reasoning prompt label uses picker wording" {
+ const Effort = enum { low, medium, high, xhigh, max, ultra };
+ try std.testing.expectEqualStrings("Low", reasoningLabel(Effort.low));
+ try std.testing.expectEqualStrings("Medium", reasoningLabel(Effort.medium));
+ try std.testing.expectEqualStrings("High", reasoningLabel(Effort.high));
+ try std.testing.expectEqualStrings("Extra high", reasoningLabel(Effort.xhigh));
+ try std.testing.expectEqualStrings("Max", reasoningLabel(Effort.max));
+ try std.testing.expectEqualStrings("Ultra", reasoningLabel(Effort.ultra));
+}
+
+test "compact token counts keep prompt usage readable" {
+ var buf: [24]u8 = undefined;
+ try std.testing.expectEqualStrings("999", compactTokenCount(&buf, 999));
+ try std.testing.expectEqualStrings("138k", compactTokenCount(&buf, 138_082));
+}
+
+test "context percent saturates malformed or over-window server meters" {
+ try std.testing.expectEqual(@as(u64, 0), contextPercent(100, 0));
+ try std.testing.expectEqual(@as(u64, 50), contextPercent(50_000, 100_000));
+ try std.testing.expectEqual(@as(u64, 100), contextPercent(150_000, 100_000));
+ try std.testing.expectEqual(@as(u64, 100), contextPercent(std.math.maxInt(u64), 100_000));
+}
+
+test "fitsSegment charges the budget only on a fit, #209" {
+ var used: usize = 10;
+ try std.testing.expect(fitsSegment(&used, 20, 5)); // 10 + 5 <= 20
+ try std.testing.expectEqual(@as(usize, 15), used);
+ try std.testing.expect(!fitsSegment(&used, 20, 10)); // 15 + 10 > 20: rejected
+ try std.testing.expectEqual(@as(usize, 15), used); // unchanged on rejection
+ try std.testing.expect(fitsSegment(&used, 20, 5)); // exact fit still counts
+ try std.testing.expectEqual(@as(usize, 20), used);
+}
+
+test "narrow pane drops cwd/context but keeps model+mode badges whole, #209" {
+ // Reproduces the issue's 28-col tmux repro: `[gpt-5.6-sol · High · codex`
+ // used to soft-wrap mid-badge because the status line never budgeted
+ // against termCols(). Budgeting the same segment widths here must keep the
+ // high-priority model/effort/provider badges intact and never let the
+ // running total exceed the pane, while cwd/context (low priority) give way.
+ const cols: usize = 28;
+ const avail = cols -| 6; // fixed frame ('[' + '] › ') + 1 col slack
+ var used: usize = "gpt-5.6-sol".len;
+ const show_effort = fitsSegment(&used, avail, 3 + "High".len);
+ const show_provider = fitsSegment(&used, avail, 3 + "codex".len);
+ const show_cwd = fitsSegment(&used, avail, 7 + "/path/to/project".len);
+ const show_ctx = fitsSegment(&used, avail, " · 12k/100k ctx (12% · compact@80k)".len);
+ try std.testing.expect(show_effort);
+ try std.testing.expect(used <= avail); // never overflows the pane itself
+ _ = show_provider; // may or may not fit at this extreme width; never split either way
+ try std.testing.expect(!show_cwd); // low-priority metadata is the first to go
+ try std.testing.expect(!show_ctx);
+}
+
+test "wide pane keeps every segment, matching the pre-#209 behaviour" {
+ // A generous pane must still show everything, proving the budget is real
+ // width-awareness and not an unconditional strip of metadata.
+ const cols: usize = 200;
+ const avail = cols -| 6;
+ var used: usize = "gpt-5.6-sol".len;
+ try std.testing.expect(fitsSegment(&used, avail, 3 + "High".len));
+ try std.testing.expect(fitsSegment(&used, avail, 3 + "codex".len));
+ try std.testing.expect(fitsSegment(&used, avail, 7 + "/path/to/project".len));
+ try std.testing.expect(fitsSegment(&used, avail, " · 12k/100k ctx (12% · compact@80k)".len));
+}
+
+/// The status line as a plain-terminal reader sees it. Pins the exact bytes the
+/// pre-#429 inline path produced, so the move behind the sink cannot quietly
+/// reword, reorder or re-space a segment.
+fn renderPlain(buf: *Io.Writer.Allocating, st: PromptStatus) []const u8 {
+ line(&buf.writer, st, 400) catch unreachable; // a pane wide enough to keep everything
+ return buf.writer.buffered();
+}
+
+test "batch 3: every status-line segment renders exactly as it did inline" {
+ const saved = style.*;
+ style.* = .{}; // assert the text, not the palette
+ defer style.* = saved;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+
+ // A wide pane keeps everything: model, every badge, cwd, meter, cache, cost.
+ const full: PromptStatus = .{
+ .model = "gpt-5.6",
+ .provider_id = "codex",
+ .cwd = "~/src/graff",
+ .privacy_label = "Privacy:Aggregate",
+ .privacy = .aggregate,
+ .effort = .high,
+ .context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },
+ .cache_read = 2048,
+ .cost = .{ .usd = 0.5 },
+ .fast = true,
+ .fallback = true,
+ .plan = true,
+ .strict = true,
+ .ultracode = true,
+ };
+ try std.testing.expectEqualStrings(
+ "\n[gpt-5.6 · Fast · High · codex · Fallback · Plan · Strict · Ultracode · Privacy:Aggregate" ++
+ " · cwd ~/src/graff · 12k/200k ctx (6% · compact@160k) · ⚡2k cached · $0.5000] › ",
+ renderPlain(&aw, full),
+ );
+
+ // The bare line: no usage yet, no cache, meter off, no optional badge.
+ aw.clearRetainingCapacity();
+ try std.testing.expectEqualStrings(
+ "\n[lmstudio · lmstudio · Privacy:Local · cwd /w] › ",
+ renderPlain(&aw, .{
+ .model = "lmstudio",
+ .provider_id = "lmstudio",
+ .cwd = "/w",
+ .privacy_label = "Privacy:Local",
+ .privacy = .local,
+ }),
+ );
+
+ // A flat-rate provider says so instead of showing a figure, and an
+ // unpriced model admits it rather than printing a fabricated 0.0000.
+ aw.clearRetainingCapacity();
+ try std.testing.expectEqualStrings(
+ "\n[m · p · Privacy:Local · cwd /w · sub] › ",
+ renderPlain(&aw, .{
+ .model = "m",
+ .provider_id = "p",
+ .cwd = "/w",
+ .privacy_label = "Privacy:Local",
+ .privacy = .local,
+ .cost = .subscription,
+ }),
+ );
+ aw.clearRetainingCapacity();
+ try std.testing.expectEqualStrings(
+ "\n[m · p · Privacy:Local · cwd /w · $?] › ",
+ renderPlain(&aw, .{
+ .model = "m",
+ .provider_id = "p",
+ .cwd = "/w",
+ .privacy_label = "Privacy:Local",
+ .privacy = .local,
+ .cost = .unpriced,
+ }),
+ );
+}
+
+test "batch 3: a shrinking pane sheds segments in the #209 priority order" {
+ // The budget is what a narrow tmux pane actually exercises, and it is the
+ // part of this move most able to drift silently: assert the WHOLE line at
+ // three widths rather than the fitsSegment arithmetic alone.
+ const saved = style.*;
+ style.* = .{};
+ defer style.* = saved;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ const st: PromptStatus = .{
+ .model = "gpt-5.6",
+ .provider_id = "codex",
+ .cwd = "~/src/graff",
+ .privacy_label = "Privacy:Local",
+ .privacy = .local,
+ .effort = .high,
+ .context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },
+ .cache_read = 2048,
+ .cost = .unpriced,
+ };
+ const cases = [_]struct { cols: usize, want: []const u8 }{
+ // Roomy: everything, in the familiar order (cwd before the meter).
+ .{ .cols = 130, .want = "\n[gpt-5.6 · High · codex · Privacy:Local · cwd ~/src/graff · 12k/200k ctx (6% · compact@160k) · ⚡2k cached · $?] › " },
+ // Tighter: cwd is the first to go, but the meter it outranks stays.
+ .{ .cols = 90, .want = "\n[gpt-5.6 · High · codex · Privacy:Local · 12k/200k ctx (6% · compact@160k) · $?] › " },
+ // Cramped: the meter goes too, and the cache badge goes with it
+ // rather than floating free of the usage it came from.
+ .{ .cols = 50, .want = "\n[gpt-5.6 · High · codex · Privacy:Local · $?] › " },
+ // Pathological: only the badges that disambiguate the cursor survive,
+ // and never a half-drawn one.
+ .{ .cols = 28, .want = "\n[gpt-5.6 · High · codex] › " },
+ };
+ for (cases) |c| {
+ aw.clearRetainingCapacity();
+ try line(&aw.writer, st, c.cols);
+ try std.testing.expectEqualStrings(c.want, aw.writer.buffered());
+ }
+}
+
+test "batch 3: the cache badge rides with the context meter, never alone" {
+ // Both come from the same response's usage payload, and the pre-#209
+ // layout never showed one without the other — a rule that lived in the
+ // `show_ctx and …` gate and has to survive the move.
+ const saved = style.*;
+ style.* = .{};
+ defer style.* = saved;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ const out = renderPlain(&aw, .{
+ .model = "m",
+ .provider_id = "p",
+ .cwd = "/w",
+ .privacy_label = "Privacy:Local",
+ .privacy = .local,
+ .cache_read = 4096, // reported, but no context meter to ride with
+ });
+ try std.testing.expect(std.mem.indexOf(u8, out, "cached") == null);
+}
diff --git a/src/approvals.zig b/src/approvals.zig
index d009028d..1fccd754 100644
--- a/src/approvals.zig
+++ b/src/approvals.zig
@@ -1,13 +1,21 @@
-//! Command / tool approval gate + path-confinement helpers. Split out of
-//! main.zig (#123). A pure std leaf: no back-import of main, no ansi/util. The
-//! tool-exec gate and anim.zig reach it via main's `pub const Approvals =
-//! approvals.Approvals;` re-export (plus the two `confinedPath`/`noSymlinkEscape`
-//! aliases), so every existing call site resolves unchanged.
+//! The command / tool approval SESSION: the mutable allow-list a human grows
+//! by answering y/n, the plan-mode read roots, the yolo flag, and the
+//! .harness/settings.json persistence around them. Split out of main.zig
+//! (#123); the pure half split out again into harness_policy.zig (#429).
+//!
+//! What stayed here is exactly what a frontend mutates on user consent — which
+//! is why the #422 import ratchet bans engine files from reaching this module.
+//! What left is the terminal-free policy engine code legitimately needs: the
+//! settings-file location, path confinement, and the command classifiers. Every
+//! one is re-exported below, so `Approvals.readOnlyAllowed`, the bare
+//! `confinedPath`/`noSymlinkEscape` aliases, and main's `pub const Approvals`
+//! re-export all resolve unchanged.
const std = @import("std");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
+const policy = @import("harness_policy.zig");
/// Shared approval state: a yolo flag plus a list of user-approved keys
/// (command first-words for bash, exact tool names for write_file/edit_file/
@@ -23,27 +31,12 @@ pub const Approvals = struct {
plan_read_roots: std.ArrayList([]const u8) = .empty,
yolo: bool = false,
- /// Read-only basics plus the build, so subagents are useful out of the
- /// box. Deliberately excludes `find` (its -exec/-delete make it an exec
- /// tool, not read-only) — it falls through to a prompt at the root and is
- /// denied for subagents. `rg`/`grep` keep their exotic --pre vector and
- /// `zig build` runs build.zig; both are accepted for a self-hosting
- /// coding harness, so don't seed-allow untrusted-input scenarios.
- const seed = [_][]const u8{
- "ls", "cat", "head", "tail",
- "wc", "grep", "rg", "pwd",
- "which", "file", "git status", "git diff",
- "git log", "git show", "zig build", "zig fmt",
- };
-
- /// Verbs that only ever read — a strict subset of `seed`, used to decide what
- /// plan mode may run OUTSIDE cwd. `zig build`/`zig fmt` are omitted (they run
- /// build.zig / rewrite files) so the external-read hatch can never mutate a
- /// sibling repo (#64).
- const read_only_seed = [_][]const u8{
- "ls", "cat", "head", "tail", "wc", "grep", "rg",
- "pwd", "which", "file", "git status", "git diff", "git log", "git show",
- };
+ // The pure, terminal-free half of the gate lives in harness_policy.zig
+ // (#429): the seeds, the command classifiers, the settings-file location
+ // and the path-confinement rules. Re-exported here — unqualified, so every
+ // method body below and every `Approvals.x` call site resolves unchanged.
+ pub const seed = policy.seed;
+ pub const read_only_seed = policy.read_only_seed;
pub fn allowed(self: *Approvals, io: Io, cmd: []const u8) bool {
const c = std.mem.trim(u8, cmd, " \t");
@@ -71,8 +64,8 @@ pub const Approvals = struct {
return false;
}
- pub const settings_dir = ".harness";
- pub const settings_path = ".harness/settings.json";
+ pub const settings_dir = policy.settings_dir;
+ pub const settings_path = policy.settings_path;
/// "Always allow" appends the key and persists the allow-list to the
/// project's .harness/settings.json, so approvals survive restarts.
@@ -133,65 +126,12 @@ pub const Approvals = struct {
return true;
}
- /// True when the command clears the read-only seed allowlist alone —
- /// the only bash plan mode lets through (user approvals may be mutating).
- pub fn readOnlyAllowed(cmd: []const u8) bool {
- const c = std.mem.trim(u8, cmd, " \t");
- if (!isSimple(c) or escapesCwd(c)) return false;
- for (read_only_seed) |p| if (matchesPrefix(c, p)) return true;
- return false;
- }
-
- fn isReadOnlyVerb(cmd: []const u8) bool {
- for (read_only_seed) |p| if (matchesPrefix(cmd, p)) return true;
- return false;
- }
-
- /// A simple read-only-verb command that reads OUTSIDE cwd — the sibling-repo
- /// exploration case. readOnlyAllowed handles the in-cwd case; plan mode
- /// prompts on this instead of hard-denying. Mutating verbs and metacharacter
- /// smuggling are NOT read-only-external (#64).
- pub fn readOnlyExternal(cmd: []const u8) bool {
- const c = std.mem.trim(u8, cmd, " \t");
- return isSimple(c) and escapesCwd(c) and isReadOnlyVerb(c);
- }
-
- /// The escaping path a token carries, or null if it stays in cwd. Mirrors
- /// escapesCwd's token classification exactly so cwd tokens are skipped.
- fn flaggedPath(tok: []const u8) ?[]const u8 {
- if (tok.len == 0) return null;
- if (tok[0] == '/' or tok[0] == '~') return tok;
- if (std.mem.indexOf(u8, tok, "=/")) |i| return tok[i + 1 ..];
- if (std.mem.indexOf(u8, tok, "=~")) |i| return tok[i + 1 ..];
- var pit = std.mem.tokenizeScalar(u8, tok, '/');
- while (pit.next()) |comp| if (std.mem.eql(u8, comp, "..")) return tok;
- return null;
- }
-
- /// True if `path` sits at or under one approved root (with a '/' boundary).
- /// Any `..` component fails outright — blocks `<root>/../../etc` smuggling.
- fn pathUnderRoots(path: []const u8, roots: []const []const u8) bool {
- var pit = std.mem.tokenizeScalar(u8, path, '/');
- while (pit.next()) |comp| if (std.mem.eql(u8, comp, "..")) return false;
- for (roots) |root| {
- if (root.len == 0 or !std.mem.startsWith(u8, path, root)) continue;
- if (path.len == root.len or path[root.len] == '/') return true;
- }
- return false;
- }
-
- /// Pure core of planReadAllowed: a simple read-only-verb command whose every
- /// escaping token sits under an approved root.
- fn planReadMatch(cmd: []const u8, roots: []const []const u8) bool {
- const c = std.mem.trim(u8, cmd, " \t");
- if (!isSimple(c) or !isReadOnlyVerb(c)) return false;
- var it = std.mem.tokenizeAny(u8, c, " \t");
- while (it.next()) |tok| {
- const p = flaggedPath(tok) orelse continue;
- if (!pathUnderRoots(p, roots)) return false;
- }
- return true;
- }
+ pub const readOnlyAllowed = policy.readOnlyAllowed;
+ pub const isReadOnlyVerb = policy.isReadOnlyVerb;
+ pub const readOnlyExternal = policy.readOnlyExternal;
+ pub const flaggedPath = policy.flaggedPath;
+ pub const pathUnderRoots = policy.pathUnderRoots;
+ pub const planReadMatch = policy.planReadMatch;
/// Plan mode: whether `cmd` is a read-only command cleared to run outside cwd
/// by a session approval. Thread-safe (called from the tool-exec pool).
@@ -230,247 +170,28 @@ pub const Approvals = struct {
return self.yolo;
}
- /// No chaining, piping, redirection, or substitution — those can smuggle
- /// a second command past a prefix match.
- fn isSimple(cmd: []const u8) bool {
- for (cmd) |ch| switch (ch) {
- ';', '|', '&', '>', '<', '`', '$', '\n', '\r', '\t', 0 => return false,
- else => {},
- };
- return true;
- }
-
- fn matchesPrefix(cmd: []const u8, prefix: []const u8) bool {
- if (!std.mem.startsWith(u8, cmd, prefix)) return false;
- return cmd.len == prefix.len or cmd[prefix.len] == ' ';
- }
-
- /// True if any whitespace-token in the command looks like a path leaving
- /// the working directory: absolute (`/x`, `--f=/x`), home (`~`, `=~`), or
- /// containing a `..` component. A heuristic — metacharacters are already
- /// blocked by isSimple, so args really are space-separated tokens — that
- /// keeps the auto-allowed seed commands (cat, grep, …) reading inside cwd.
- fn escapesCwd(cmd: []const u8) bool {
- var it = std.mem.tokenizeAny(u8, cmd, " \t");
- while (it.next()) |tok| {
- if (tok.len == 0) continue;
- if (tok[0] == '/' or tok[0] == '~') return true;
- if (std.mem.indexOf(u8, tok, "=/") != null) return true;
- if (std.mem.indexOf(u8, tok, "=~") != null) return true;
- var pit = std.mem.tokenizeScalar(u8, tok, '/');
- while (pit.next()) |comp| if (std.mem.eql(u8, comp, "..")) return true;
- }
- return false;
- }
-
- /// "Always allow"ing one of these as a bash first word grants arbitrary
- /// code execution (e.g. `python3 -c '...'`) — worth a heads-up.
- pub fn isInterpreter(word: []const u8) bool {
- const interps = [_][]const u8{
- "python", "python3", "node", "deno", "bun", "ruby", "perl",
- "php", "sh", "bash", "osascript", "awk",
- };
- for (interps) |i| if (std.mem.eql(u8, word, i)) return true;
- return false;
- }
-
- /// Git subcommands that can destroy committed or working-tree work — the
- /// user's, or a -w worktree's auto-checkpoints. Codex keeps `.git` read-only
- /// to the agent and opencode forbids `git reset --hard`; we do the same to a
- /// degree: these never auto-run (not under --yolo, not via a blanket `git`
- /// allow), so they always reach a human y/n. Scans the whole command so a
- /// chained `cd x && git reset --hard` is caught too.
- pub fn isDestructiveGit(cmd: []const u8) bool {
- if (std.mem.indexOf(u8, cmd, "git ") == null) return false;
- const pats = [_][]const u8{
- "reset --hard", "clean -f", "checkout --", "checkout .",
- "push --force", "push -f", "branch -D", "stash clear",
- "stash drop", "restore .",
- };
- for (pats) |p| if (std.mem.indexOf(u8, cmd, p) != null) return true;
- return false;
- }
-
- /// Whether a destructive git command may auto-run without a y/n. Gated
- /// everywhere EXCEPT the root agent under --yolo, where the operator
- /// explicitly opted out of prompts and is driving. Subagents never get it.
- pub fn destructiveGitAllowed(yolo: bool, sub: bool) bool {
- return yolo and !sub;
- }
+ pub const isSimple = policy.isSimple;
+ pub const matchesPrefix = policy.matchesPrefix;
+ pub const escapesCwd = policy.escapesCwd;
+ pub const isInterpreter = policy.isInterpreter;
+ pub const isDestructiveGit = policy.isDestructiveGit;
+ pub const destructiveGitAllowed = policy.destructiveGitAllowed;
};
-test "destructive git gate: only the root agent under --yolo skips the y/n" {
- // The 'yolo fails on destructive git' report: --yolo lets the operator through
- // (they opted out of prompts), but never a subagent and never a non-yolo run.
- try std.testing.expect(Approvals.destructiveGitAllowed(true, false));
- try std.testing.expect(!Approvals.destructiveGitAllowed(true, true));
- try std.testing.expect(!Approvals.destructiveGitAllowed(false, false));
- try std.testing.expect(!Approvals.destructiveGitAllowed(false, true));
- try std.testing.expect(Approvals.isDestructiveGit("git reset --hard origin/main"));
- try std.testing.expect(Approvals.isDestructiveGit("git clean -fd"));
- try std.testing.expect(!Approvals.isDestructiveGit("git status"));
-}
-
-/// Path tools (read/write/edit_file) are confined to the working directory:
-/// no absolute paths and no `..` components. This keeps `read_file
-/// /etc/shadow`, `write_file ../../foo`, and trace/approvals forgery via
-/// traversal out of reach for both the root agent and subagents, structurally
-/// (it is not bypassed by /yolo — use bash, which is gated, to touch files
-/// elsewhere). Returns true when the path is safe.
-pub fn confinedPath(path: []const u8) bool {
- if (path.len == 0) return false;
- if (std.fs.path.isAbsolute(path)) return false;
- var it = std.mem.tokenizeAny(u8, path, "/\\");
- while (it.next()) |comp| {
- if (std.mem.eql(u8, comp, "..")) return false;
- }
- return true;
-}
-
-/// Defense-in-depth on top of confinedPath: a confined path with no `..` and no
-/// absolute prefix can still escape the cwd through a symlink that points
-/// outside (e.g. `evil -> /etc`, then `read_file evil/passwd`). We refuse to
-/// traverse symlinks at all: walk each path prefix and
-/// reject if any component is a symlink (readLink succeeds). Conservative — a
-/// symlink inside the repo becomes unreadable via the file tools — but it makes
-/// confinement structural rather than lexical. bash (gated) is unaffected.
-/// `base` is the agent's isolated worktree root (#276 P0-1) when its tool
-/// calls are pinned there instead of the shared cwd — each checked prefix is
-/// then resolved under `base` (an absolute path, so `Io.Dir.cwd()` below is
-/// just the dir-fd the readLink call ignores for an absolute sub_path) rather
-/// than the process's real cwd, which a worktree-isolated agent never enters.
-/// `base == null` (the shared-cwd default) keeps the original behavior exactly.
-pub fn noSymlinkEscape(io: Io, path: []const u8, base: ?[]const u8) bool {
- var buf: [std.fs.max_path_bytes]u8 = undefined;
- var join_buf: [std.fs.max_path_bytes]u8 = undefined;
- var i: usize = 0;
- while (i <= path.len) {
- const slash = std.mem.indexOfScalarPos(u8, path, i, '/') orelse path.len;
- const prefix = path[0..slash];
- if (prefix.len > 0) {
- const check_path = if (base) |b|
- std.fmt.bufPrint(&join_buf, "{s}/{s}", .{ b, prefix }) catch return false
- else
- prefix;
- if (Io.Dir.cwd().readLink(io, check_path, &buf)) |_| {
- return false; // this component is a symlink → refuse
- } else |_| {} // not a symlink (or doesn't exist yet) → fine
- }
- if (slash == path.len) break;
- i = slash + 1;
- }
- return true;
-}
-test "Approvals.isSimple: rejects shell metacharacters that could smuggle a second command" {
- try std.testing.expect(Approvals.isSimple("grep foo src/main.zig"));
- try std.testing.expect(Approvals.isSimple("ls -la"));
- try std.testing.expect(!Approvals.isSimple("ls; rm -rf /"));
- try std.testing.expect(!Approvals.isSimple("cat a | sh"));
- try std.testing.expect(!Approvals.isSimple("echo $(whoami)"));
- try std.testing.expect(!Approvals.isSimple("echo `id`"));
- try std.testing.expect(!Approvals.isSimple("foo > bar"));
- try std.testing.expect(!Approvals.isSimple("foo < bar"));
- try std.testing.expect(!Approvals.isSimple("a && b"));
- try std.testing.expect(!Approvals.isSimple("a\nb"));
- try std.testing.expect(!Approvals.isSimple("echo $HOME"));
-}
-
-test "Approvals.matchesPrefix: whole-word prefix, never a bare substring" {
- try std.testing.expect(Approvals.matchesPrefix("git status", "git status"));
- try std.testing.expect(Approvals.matchesPrefix("git status -s", "git status"));
- try std.testing.expect(Approvals.matchesPrefix("ls", "ls"));
- try std.testing.expect(Approvals.matchesPrefix("ls -la", "ls"));
- try std.testing.expect(!Approvals.matchesPrefix("lsof", "ls")); // not a word boundary
- try std.testing.expect(!Approvals.matchesPrefix("git statusx", "git status"));
- try std.testing.expect(!Approvals.matchesPrefix("git", "git status")); // prefix longer than cmd
-}
-
-test "Approvals.escapesCwd: flags tokens that point outside the working directory" {
- try std.testing.expect(!Approvals.escapesCwd("cat src/main.zig"));
- try std.testing.expect(!Approvals.escapesCwd("grep foo ./a/b.zig"));
- try std.testing.expect(!Approvals.escapesCwd("prog --flag=value"));
- try std.testing.expect(Approvals.escapesCwd("cat /etc/passwd"));
- try std.testing.expect(Approvals.escapesCwd("cat ~/secrets"));
- try std.testing.expect(Approvals.escapesCwd("cat ../outside"));
- try std.testing.expect(Approvals.escapesCwd("grep foo a/../../b"));
- try std.testing.expect(Approvals.escapesCwd("prog --file=/abs/path"));
- try std.testing.expect(Approvals.escapesCwd("prog --file=~/x"));
-}
-
-test "Approvals.readOnlyAllowed: only simple, in-cwd, seed-listed commands pass in plan mode" {
- try std.testing.expect(Approvals.readOnlyAllowed("ls -la"));
- try std.testing.expect(Approvals.readOnlyAllowed("git status"));
- try std.testing.expect(Approvals.readOnlyAllowed("cat src/main.zig"));
- try std.testing.expect(Approvals.readOnlyAllowed(" grep foo bar ")); // leading/trailing trimmed
- try std.testing.expect(!Approvals.readOnlyAllowed("rm -rf x")); // not in the seed
- try std.testing.expect(!Approvals.readOnlyAllowed("cat /etc/passwd")); // escapes cwd
- try std.testing.expect(!Approvals.readOnlyAllowed("ls; rm x")); // not simple
- try std.testing.expect(!Approvals.readOnlyAllowed("git push")); // mutating git verb, not seeded
- try std.testing.expect(!Approvals.readOnlyAllowed("zig build")); // build.zig can execute arbitrary code
- try std.testing.expect(!Approvals.readOnlyAllowed("zig fmt src")); // formatter rewrites files
-}
-
-test "Approvals.readOnlyExternal: read-only verb reading outside cwd, simple only (#64)" {
- try std.testing.expect(Approvals.readOnlyExternal("ls ~/projects/merjs"));
- try std.testing.expect(Approvals.readOnlyExternal("cat /abs/file"));
- try std.testing.expect(!Approvals.readOnlyExternal("cat src/main.zig")); // in cwd
- try std.testing.expect(!Approvals.readOnlyExternal("rm -rf /x")); // mutating verb
- try std.testing.expect(!Approvals.readOnlyExternal("zig fmt /x.zig")); // not read-only-seeded
- try std.testing.expect(!Approvals.readOnlyExternal("ls /x; rm y")); // not simple
-}
-
-test "Approvals.planReadMatch: reads under an approved root pass; escapes/mutations/smuggling do not (#64)" {
- const roots = [_][]const u8{ "~/projects/merjs", "/opt/data" };
- const r: []const []const u8 = &roots;
- try std.testing.expect(Approvals.planReadMatch("ls ~/projects/merjs", r));
- try std.testing.expect(Approvals.planReadMatch("ls ~/projects/merjs/src", r));
- try std.testing.expect(Approvals.planReadMatch("cat ~/projects/merjs/README.md", r));
- try std.testing.expect(Approvals.planReadMatch("grep foo /opt/data/x.txt", r));
- try std.testing.expect(Approvals.planReadMatch("grep foo ~/projects/merjs/a src/b.zig", r)); // cwd token ok alongside
- try std.testing.expect(!Approvals.planReadMatch("cat /etc/passwd", r)); // outside every root
- try std.testing.expect(!Approvals.planReadMatch("ls ~/secrets", r));
- try std.testing.expect(!Approvals.planReadMatch("cat ~/projects/merjs/../../etc/passwd", r)); // .. smuggling
- try std.testing.expect(!Approvals.planReadMatch("rm -rf ~/projects/merjs", r)); // mutating verb
- try std.testing.expect(!Approvals.planReadMatch("ls ~/projects/merjs; rm x", r)); // metachar
- try std.testing.expect(!Approvals.planReadMatch("ls ~/projects/merjs", &.{})); // nothing approved
-}
-
-test "Approvals.isInterpreter: flags first words that grant arbitrary code execution" {
- try std.testing.expect(Approvals.isInterpreter("python3"));
- try std.testing.expect(Approvals.isInterpreter("node"));
- try std.testing.expect(Approvals.isInterpreter("bash"));
- try std.testing.expect(Approvals.isInterpreter("osascript"));
- try std.testing.expect(!Approvals.isInterpreter("ls"));
- try std.testing.expect(!Approvals.isInterpreter("git"));
- try std.testing.expect(!Approvals.isInterpreter("python3x"));
-}
-
-test "Approvals.isDestructiveGit: flags work-destroying git, lets safe git through" {
- // destructive — must always reach a human, even under --yolo or a `git` allow
- try std.testing.expect(Approvals.isDestructiveGit("git reset --hard HEAD~3"));
- try std.testing.expect(Approvals.isDestructiveGit("git clean -fd"));
- try std.testing.expect(Approvals.isDestructiveGit("git push --force origin main"));
- try std.testing.expect(Approvals.isDestructiveGit("git push -f"));
- try std.testing.expect(Approvals.isDestructiveGit("git branch -D worktree-docs"));
- try std.testing.expect(Approvals.isDestructiveGit("git checkout -- src/main.zig"));
- try std.testing.expect(Approvals.isDestructiveGit("git checkout ."));
- try std.testing.expect(Approvals.isDestructiveGit("git stash clear"));
- try std.testing.expect(Approvals.isDestructiveGit("cd sub && git reset --hard")); // chained
- try std.testing.expect(Approvals.isDestructiveGit("git -C /repo reset --hard")); // -C form
- // safe — the normal auto-allow path is fine
- try std.testing.expect(!Approvals.isDestructiveGit("git status"));
- try std.testing.expect(!Approvals.isDestructiveGit("git commit -m wip"));
- try std.testing.expect(!Approvals.isDestructiveGit("git reset --soft HEAD~1"));
- try std.testing.expect(!Approvals.isDestructiveGit("git checkout main"));
- try std.testing.expect(!Approvals.isDestructiveGit("git branch -d merged-feature"));
- try std.testing.expect(!Approvals.isDestructiveGit("git restore --staged f.txt"));
- try std.testing.expect(!Approvals.isDestructiveGit("ls -la"));
-}
-test "confinedPath: rejects absolute, empty, and parent-escaping paths" {
- try std.testing.expect(confinedPath("src/main.zig"));
- try std.testing.expect(confinedPath("a/b/c"));
- try std.testing.expect(!confinedPath(""));
- try std.testing.expect(!confinedPath("/etc/passwd"));
- try std.testing.expect(!confinedPath("../outside"));
- try std.testing.expect(!confinedPath("a/../../b"));
+// The path-confinement pair is re-exported at file level too: exec.zig,
+// edit_verify.zig and imagegen.zig alias them straight off this module.
+pub const confinedPath = policy.confinedPath;
+pub const noSymlinkEscape = policy.noSymlinkEscape;
+
+test "the re-exports really are harness_policy's, not a second implementation" {
+ // The classifiers and path rules moved to harness_policy.zig (#429) so
+ // engine code can consult them without importing the approval gate. Every
+ // decl below is an alias; if one were ever re-implemented here the two
+ // copies could drift, and a security predicate that drifts is a hole.
+ try std.testing.expectEqual(&policy.readOnlyAllowed, &Approvals.readOnlyAllowed);
+ try std.testing.expectEqual(&policy.isDestructiveGit, &Approvals.isDestructiveGit);
+ try std.testing.expectEqual(&policy.isInterpreter, &Approvals.isInterpreter);
+ try std.testing.expectEqual(&policy.confinedPath, &confinedPath);
+ try std.testing.expectEqualStrings(policy.settings_path, Approvals.settings_path);
+ try std.testing.expectEqualStrings(policy.settings_dir, Approvals.settings_dir);
}
diff --git a/src/commands_session.zig b/src/commands_session.zig
index 92c7cdfd..6baf99e0 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -48,7 +48,7 @@ const skillDisabled = skills.skillDisabled;
const skillInstalled = skills.skillInstalled;
const saveSkillSetting = skills.saveSkillSetting;
const skills_registry = skills.skills_registry;
-const skill_docs = @import("skill_docs.zig"); // the other kind: SKILL.md playbooks
+const skill_docs_render = @import("skill_docs_render.zig"); // the other kind: SKILL.md playbooks
const title_mod = @import("title.zig");
const setTerminalTitle = title_mod.setTerminalTitle;
@@ -408,7 +408,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
}
// Markdown skills use the same {"skills": {"<name>": false}} key.
- if (try skill_docs.handleRemove(root.io, root.gpa, arena, name, out)) return true;
+ if (try skill_docs_render.handleRemove(root.io, root.gpa, arena, name, out)) return true;
try out.print("unknown skill: {s} — /skills lists both kinds\n", .{name});
try out.flush();
return true;
@@ -465,13 +465,13 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
}
// Not a companion: a markdown skill hidden by an earlier
// `/skills remove` comes back by clearing that opt-out.
- if (try skill_docs.handleAdd(root.io, root.gpa, arena, name, out)) return true;
+ if (try skill_docs_render.handleAdd(root.io, root.gpa, arena, name, out)) return true;
try out.print("unknown skill: {s} — /skills lists both kinds\n", .{name});
try out.flush();
return true;
}
// Markdown skills first (SKILL.md playbooks), then the companions.
- try skill_docs.printSection(root.io, arena, out);
+ try skill_docs_render.printSection(root.io, arena, out);
try out.print("{s}companions{s} — optional companion tools (codex-style; one context line each when installed)\n", .{ style.bold, style.reset });
for (skills_registry) |sk| {
const inst = skillInstalled(root.io, sk);
diff --git a/src/engine_events.zig b/src/engine_events.zig
index 0b94edbe..7baa51c2 100644
--- a/src/engine_events.zig
+++ b/src/engine_events.zig
@@ -103,6 +103,71 @@ 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 };
+// ── The interactive status line (#429 batch 3) ───────────────────────────────
+// Its own value types rather than main.zig's/learning_privacy's: this file is
+// the vocabulary, and a transport-split sink must be able to read an event
+// without importing the engine. The emit site maps with an exhaustive switch,
+// so adding a tier upstream is a compile error here rather than a silent
+// mistranslation.
+
+/// Reasoning depth, when the provider takes one at all (main.ReasoningEffort).
+pub const ReasoningEffort = enum { low, medium, high, xhigh, max, ultra };
+
+/// The federated-learning privacy ceiling (learning_privacy.Mode).
+pub const PrivacyTier = enum { local, aggregate, templates, examples };
+
+/// What the cost meter can say. Deliberately not a pre-formatted string: only
+/// `.usd` has a figure, and the other three are states, not numbers.
+pub const CostMeter = union(enum) {
+ /// The meter is off (--no-cost): the segment does not exist.
+ hidden,
+ /// A flat-rate provider (codex): spend is not per-turn, so there is no
+ /// figure to show.
+ subscription,
+ /// No price-table entry for this model — a real figure cannot be derived.
+ unpriced,
+ /// Session spend so far, in US dollars.
+ usd: f64,
+};
+
+/// The live context meter. Present only once a response has reported usage;
+/// `tokens` is the effective count, which is not always what the last response
+/// said (local estimates carry it between turns).
+pub const ContextMeter = struct {
+ tokens: u64,
+ window: u64,
+ /// The count at which this provider compacts.
+ compact_at: u64,
+};
+
+/// Everything the status line printed before a human turn actually says.
+/// Deliberately semantic: no widths, no colors, no assembled segments. Which
+/// badges survive a narrow pane is a rendering decision (#209) and belongs to
+/// the sink, which is the only thing that knows the terminal.
+pub const PromptStatus = struct {
+ model: []const u8,
+ provider_id: []const u8,
+ cwd: []const u8,
+ /// The privacy mode's own badge wording, owned by learning_privacy.zig —
+ /// carried whole for the same reason ToolText is, while the tier beside it
+ /// is what a sink picks a tone from.
+ privacy_label: []const u8,
+ privacy: PrivacyTier,
+ /// null when this provider takes no reasoning effort, so no badge exists.
+ effort: ?ReasoningEffort = null,
+ /// null until a response has reported usage.
+ context: ?ContextMeter = null,
+ /// Prompt-cache hit on the last response; 0 = nothing cached.
+ cache_read: u64 = 0,
+ cost: CostMeter = .hidden,
+ /// The Fast badge APPLIES — the flag is on and the provider honors it.
+ fast: bool = false,
+ fallback: bool = false,
+ plan: bool = false,
+ strict: bool = false,
+ ultracode: bool = false,
+};
+
/// Everything the streaming path tells a frontend. Each doc comment states
/// the emission site's contract, not how any one sink draws it.
pub const EngineEvent = union(enum) {
@@ -186,6 +251,13 @@ 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,
+
+ /// A human turn is about to be read: this is what the session looks like
+ /// right now (#429). Presentation-only and always will be — the --json
+ /// wire has no prompt because an SDK client drives turns itself, which is
+ /// why the emit site skips json_mode entirely rather than relying on a
+ /// silent sink.
+ prompt_ready: PromptStatus,
};
/// Durable events are the protocol stream: what the --json wire emits today
@@ -322,6 +394,24 @@ test "slice 1c: the tool-cluster notices are presentation pulses" {
for (pulses) |ev| try std.testing.expect(!durable(ev));
}
+test "batch 3: the status line is a presentation pulse, never a wire line" {
+ // The --json wire has never had a prompt event and must not grow one by
+ // accident: a client that drives its own turns would read a burned
+ // sequence id as lost data (#330).
+ const status: PromptStatus = .{
+ .model = "gpt-5.6",
+ .provider_id = "codex",
+ .cwd = "~/src/graff",
+ .privacy_label = "Privacy:Aggregate",
+ .privacy = .aggregate,
+ .effort = .high,
+ .context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },
+ .cache_read = 2048,
+ .cost = .subscription,
+ };
+ try std.testing.expect(!durable(.{ .prompt_ready = status }));
+}
+
test "generation only moves forward, one restart at a time" {
const before = generation();
try std.testing.expect(before >= 1);
diff --git a/src/engine_sink.zig b/src/engine_sink.zig
index da07f6ef..f920de87 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 prompt_render = @import("agent_prompt_render.zig"); // batch 3: the status line's terminal half
const tick_gate = @import("tick_gate.zig"); // #tui-tick: child ticks wait for a foreground line boundary
/// An event plus its position, as delivered to a sink.
@@ -198,6 +199,10 @@ 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 status line before a human turn (#429). Its drawing — palette,
+ // badge frame, and the #209 width budget that decides which segments
+ // survive a narrow pane — lives in agent_prompt_render.
+ .prompt_ready => |st| if (a.out) |w| prompt_render.promptLine(w, st),
}
}
diff --git a/src/harness_policy.zig b/src/harness_policy.zig
new file mode 100644
index 00000000..55a5a2cf
--- /dev/null
+++ b/src/harness_policy.zig
@@ -0,0 +1,355 @@
+//! Terminal-free harness policy: where the harness keeps its own config, which
+//! paths a model-supplied argument may name, and how a shell command is
+//! classified. A pure std leaf — no ansi/term, no main, no I/O beyond the
+//! symlink probe.
+//!
+//! Split out of approvals.zig (#422/#429). approvals.zig keeps what is
+//! genuinely the *approval session*: the mutable allow-list, the plan-mode read
+//! roots, the yolo flag, and the persistence around them — state a frontend
+//! mutates when a human answers a prompt. What lives here is the pure half
+//! engine code consults without ever touching that state, and the epic's import
+//! ratchet bans engine files from reaching `approvals.zig` precisely because
+//! doing so used to be the only way to ask these questions.
+//!
+//! Every decl is re-exported from `Approvals` (approvals.zig), so existing call
+//! sites resolve unchanged — the move+alias pattern from the main.zig split
+//! (#123). New engine-side callers should import THIS module directly.
+
+const std = @import("std");
+const Io = std.Io;
+
+/// The project-local file the harness owns: approvals, hooks, skills opt-outs,
+/// theme/animation choice. One spelling, so every reader and writer agrees.
+pub const settings_dir = ".harness";
+pub const settings_path = ".harness/settings.json";
+
+/// Read-only basics plus the build, so subagents are useful out of the box.
+/// Deliberately excludes `find` (its -exec/-delete make it an exec tool, not
+/// read-only) — it falls through to a prompt at the root and is denied for
+/// subagents. `rg`/`grep` keep their exotic --pre vector and `zig build` runs
+/// build.zig; both are accepted for a self-hosting coding harness, so don't
+/// seed-allow untrusted-input scenarios.
+pub const seed = [_][]const u8{
+ "ls", "cat", "head", "tail",
+ "wc", "grep", "rg", "pwd",
+ "which", "file", "git status", "git diff",
+ "git log", "git show", "zig build", "zig fmt",
+};
+
+/// Verbs that only ever read — a strict subset of `seed`, used to decide what
+/// plan mode may run OUTSIDE cwd. `zig build`/`zig fmt` are omitted (they run
+/// build.zig / rewrite files) so the external-read hatch can never mutate a
+/// sibling repo (#64).
+pub const read_only_seed = [_][]const u8{
+ "ls", "cat", "head", "tail", "wc", "grep", "rg",
+ "pwd", "which", "file", "git status", "git diff", "git log", "git show",
+};
+
+/// No chaining, piping, redirection, or substitution — those can smuggle a
+/// second command past a prefix match.
+pub fn isSimple(cmd: []const u8) bool {
+ for (cmd) |ch| switch (ch) {
+ ';', '|', '&', '>', '<', '`', '$', '\n', '\r', '\t', 0 => return false,
+ else => {},
+ };
+ return true;
+}
+
+pub fn matchesPrefix(cmd: []const u8, prefix: []const u8) bool {
+ if (!std.mem.startsWith(u8, cmd, prefix)) return false;
+ return cmd.len == prefix.len or cmd[prefix.len] == ' ';
+}
+
+/// True if any whitespace-token in the command looks like a path leaving the
+/// working directory: absolute (`/x`, `--f=/x`), home (`~`, `=~`), or
+/// containing a `..` component. A heuristic — metacharacters are already
+/// blocked by isSimple, so args really are space-separated tokens — that keeps
+/// the auto-allowed seed commands (cat, grep, …) reading inside cwd.
+pub fn escapesCwd(cmd: []const u8) bool {
+ var it = std.mem.tokenizeAny(u8, cmd, " \t");
+ while (it.next()) |tok| {
+ if (tok.len == 0) continue;
+ if (tok[0] == '/' or tok[0] == '~') return true;
+ if (std.mem.indexOf(u8, tok, "=/") != null) return true;
+ if (std.mem.indexOf(u8, tok, "=~") != null) return true;
+ var pit = std.mem.tokenizeScalar(u8, tok, '/');
+ while (pit.next()) |comp| if (std.mem.eql(u8, comp, "..")) return true;
+ }
+ return false;
+}
+
+/// True when the command clears the read-only seed allowlist alone — the only
+/// bash plan mode lets through (user approvals may be mutating).
+pub fn readOnlyAllowed(cmd: []const u8) bool {
+ const c = std.mem.trim(u8, cmd, " \t");
+ if (!isSimple(c) or escapesCwd(c)) return false;
+ for (read_only_seed) |p| if (matchesPrefix(c, p)) return true;
+ return false;
+}
+
+pub fn isReadOnlyVerb(cmd: []const u8) bool {
+ for (read_only_seed) |p| if (matchesPrefix(cmd, p)) return true;
+ return false;
+}
+
+/// A simple read-only-verb command that reads OUTSIDE cwd — the sibling-repo
+/// exploration case. readOnlyAllowed handles the in-cwd case; plan mode prompts
+/// on this instead of hard-denying. Mutating verbs and metacharacter smuggling
+/// are NOT read-only-external (#64).
+pub fn readOnlyExternal(cmd: []const u8) bool {
+ const c = std.mem.trim(u8, cmd, " \t");
+ return isSimple(c) and escapesCwd(c) and isReadOnlyVerb(c);
+}
+
+/// The escaping path a token carries, or null if it stays in cwd. Mirrors
+/// escapesCwd's token classification exactly so cwd tokens are skipped.
+pub fn flaggedPath(tok: []const u8) ?[]const u8 {
+ if (tok.len == 0) return null;
+ if (tok[0] == '/' or tok[0] == '~') return tok;
+ if (std.mem.indexOf(u8, tok, "=/")) |i| return tok[i + 1 ..];
+ if (std.mem.indexOf(u8, tok, "=~")) |i| return tok[i + 1 ..];
+ var pit = std.mem.tokenizeScalar(u8, tok, '/');
+ while (pit.next()) |comp| if (std.mem.eql(u8, comp, "..")) return tok;
+ return null;
+}
+
+/// True if `path` sits at or under one approved root (with a '/' boundary).
+/// Any `..` component fails outright — blocks `<root>/../../etc` smuggling.
+pub fn pathUnderRoots(path: []const u8, roots: []const []const u8) bool {
+ var pit = std.mem.tokenizeScalar(u8, path, '/');
+ while (pit.next()) |comp| if (std.mem.eql(u8, comp, "..")) return false;
+ for (roots) |root| {
+ if (root.len == 0 or !std.mem.startsWith(u8, path, root)) continue;
+ if (path.len == root.len or path[root.len] == '/') return true;
+ }
+ return false;
+}
+
+/// Pure core of Approvals.planReadAllowed: a simple read-only-verb command
+/// whose every escaping token sits under an approved root.
+pub fn planReadMatch(cmd: []const u8, roots: []const []const u8) bool {
+ const c = std.mem.trim(u8, cmd, " \t");
+ if (!isSimple(c) or !isReadOnlyVerb(c)) return false;
+ var it = std.mem.tokenizeAny(u8, c, " \t");
+ while (it.next()) |tok| {
+ const p = flaggedPath(tok) orelse continue;
+ if (!pathUnderRoots(p, roots)) return false;
+ }
+ return true;
+}
+
+/// "Always allow"ing one of these as a bash first word grants arbitrary code
+/// execution (e.g. `python3 -c '...'`) — worth a heads-up.
+pub fn isInterpreter(word: []const u8) bool {
+ const interps = [_][]const u8{
+ "python", "python3", "node", "deno", "bun", "ruby", "perl",
+ "php", "sh", "bash", "osascript", "awk",
+ };
+ for (interps) |i| if (std.mem.eql(u8, word, i)) return true;
+ return false;
+}
+
+/// Git subcommands that can destroy committed or working-tree work — the
+/// user's, or a -w worktree's auto-checkpoints. Codex keeps `.git` read-only to
+/// the agent and opencode forbids `git reset --hard`; we do the same to a
+/// degree: these never auto-run (not under --yolo, not via a blanket `git`
+/// allow), so they always reach a human y/n. Scans the whole command so a
+/// chained `cd x && git reset --hard` is caught too.
+pub fn isDestructiveGit(cmd: []const u8) bool {
+ if (std.mem.indexOf(u8, cmd, "git ") == null) return false;
+ const pats = [_][]const u8{
+ "reset --hard", "clean -f", "checkout --", "checkout .",
+ "push --force", "push -f", "branch -D", "stash clear",
+ "stash drop", "restore .",
+ };
+ for (pats) |p| if (std.mem.indexOf(u8, cmd, p) != null) return true;
+ return false;
+}
+
+/// Whether a destructive git command may auto-run without a y/n. Gated
+/// everywhere EXCEPT the root agent under --yolo, where the operator explicitly
+/// opted out of prompts and is driving. Subagents never get it.
+pub fn destructiveGitAllowed(yolo: bool, sub: bool) bool {
+ return yolo and !sub;
+}
+
+/// Path tools (read/write/edit_file) are confined to the working directory:
+/// no absolute paths and no `..` components. This keeps `read_file
+/// /etc/shadow`, `write_file ../../foo`, and trace/approvals forgery via
+/// traversal out of reach for both the root agent and subagents, structurally
+/// (it is not bypassed by /yolo — use bash, which is gated, to touch files
+/// elsewhere). Returns true when the path is safe.
+pub fn confinedPath(path: []const u8) bool {
+ if (path.len == 0) return false;
+ if (std.fs.path.isAbsolute(path)) return false;
+ var it = std.mem.tokenizeAny(u8, path, "/\\");
+ while (it.next()) |comp| {
+ if (std.mem.eql(u8, comp, "..")) return false;
+ }
+ return true;
+}
+
+/// Defense-in-depth on top of confinedPath: a confined path with no `..` and no
+/// absolute prefix can still escape the cwd through a symlink that points
+/// outside (e.g. `evil -> /etc`, then `read_file evil/passwd`). We refuse to
+/// traverse symlinks at all: walk each path prefix and
+/// reject if any component is a symlink (readLink succeeds). Conservative — a
+/// symlink inside the repo becomes unreadable via the file tools — but it makes
+/// confinement structural rather than lexical. bash (gated) is unaffected.
+/// `base` is the agent's isolated worktree root (#276 P0-1) when its tool
+/// calls are pinned there instead of the shared cwd — each checked prefix is
+/// then resolved under `base` (an absolute path, so `Io.Dir.cwd()` below is
+/// just the dir-fd the readLink call ignores for an absolute sub_path) rather
+/// than the process's real cwd, which a worktree-isolated agent never enters.
+/// `base == null` (the shared-cwd default) keeps the original behavior exactly.
+pub fn noSymlinkEscape(io: Io, path: []const u8, base: ?[]const u8) bool {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ var join_buf: [std.fs.max_path_bytes]u8 = undefined;
+ var i: usize = 0;
+ while (i <= path.len) {
+ const slash = std.mem.indexOfScalarPos(u8, path, i, '/') orelse path.len;
+ const prefix = path[0..slash];
+ if (prefix.len > 0) {
+ const check_path = if (base) |b|
+ std.fmt.bufPrint(&join_buf, "{s}/{s}", .{ b, prefix }) catch return false
+ else
+ prefix;
+ if (Io.Dir.cwd().readLink(io, check_path, &buf)) |_| {
+ return false; // this component is a symlink → refuse
+ } else |_| {} // not a symlink (or doesn't exist yet) → fine
+ }
+ if (slash == path.len) break;
+ i = slash + 1;
+ }
+ return true;
+}
+
+test "isSimple: rejects shell metacharacters that could smuggle a second command" {
+ try std.testing.expect(isSimple("grep foo src/main.zig"));
+ try std.testing.expect(isSimple("ls -la"));
+ try std.testing.expect(!isSimple("ls; rm -rf /"));
+ try std.testing.expect(!isSimple("cat a | sh"));
+ try std.testing.expect(!isSimple("echo $(whoami)"));
+ try std.testing.expect(!isSimple("echo `id`"));
+ try std.testing.expect(!isSimple("foo > bar"));
+ try std.testing.expect(!isSimple("foo < bar"));
+ try std.testing.expect(!isSimple("a && b"));
+ try std.testing.expect(!isSimple("a\nb"));
+ try std.testing.expect(!isSimple("echo $HOME"));
+}
+
+test "matchesPrefix: whole-word prefix, never a bare substring" {
+ try std.testing.expect(matchesPrefix("git status", "git status"));
+ try std.testing.expect(matchesPrefix("git status -s", "git status"));
+ try std.testing.expect(matchesPrefix("ls", "ls"));
+ try std.testing.expect(matchesPrefix("ls -la", "ls"));
+ try std.testing.expect(!matchesPrefix("lsof", "ls")); // not a word boundary
+ try std.testing.expect(!matchesPrefix("git statusx", "git status"));
+ try std.testing.expect(!matchesPrefix("git", "git status")); // prefix longer than cmd
+}
+
+test "escapesCwd: flags tokens that point outside the working directory" {
+ try std.testing.expect(!escapesCwd("cat src/main.zig"));
+ try std.testing.expect(!escapesCwd("grep foo ./a/b.zig"));
+ try std.testing.expect(!escapesCwd("prog --flag=value"));
+ try std.testing.expect(escapesCwd("cat /etc/passwd"));
+ try std.testing.expect(escapesCwd("cat ~/secrets"));
+ try std.testing.expect(escapesCwd("cat ../outside"));
+ try std.testing.expect(escapesCwd("grep foo a/../../b"));
+ try std.testing.expect(escapesCwd("prog --file=/abs/path"));
+ try std.testing.expect(escapesCwd("prog --file=~/x"));
+}
+
+test "readOnlyAllowed: only simple, in-cwd, seed-listed commands pass in plan mode" {
+ try std.testing.expect(readOnlyAllowed("ls -la"));
+ try std.testing.expect(readOnlyAllowed("git status"));
+ try std.testing.expect(readOnlyAllowed("cat src/main.zig"));
+ try std.testing.expect(readOnlyAllowed(" grep foo bar ")); // leading/trailing trimmed
+ try std.testing.expect(!readOnlyAllowed("rm -rf x")); // not in the seed
+ try std.testing.expect(!readOnlyAllowed("cat /etc/passwd")); // escapes cwd
+ try std.testing.expect(!readOnlyAllowed("ls; rm x")); // not simple
+ try std.testing.expect(!readOnlyAllowed("git push")); // mutating git verb, not seeded
+ try std.testing.expect(!readOnlyAllowed("zig build")); // build.zig can execute arbitrary code
+ try std.testing.expect(!readOnlyAllowed("zig fmt src")); // formatter rewrites files
+}
+
+test "readOnlyExternal: read-only verb reading outside cwd, simple only (#64)" {
+ try std.testing.expect(readOnlyExternal("ls ~/projects/merjs"));
+ try std.testing.expect(readOnlyExternal("cat /abs/file"));
+ try std.testing.expect(!readOnlyExternal("cat src/main.zig")); // in cwd
+ try std.testing.expect(!readOnlyExternal("rm -rf /x")); // mutating verb
+ try std.testing.expect(!readOnlyExternal("zig fmt /x.zig")); // not read-only-seeded
+ try std.testing.expect(!readOnlyExternal("ls /x; rm y")); // not simple
+}
+
+test "planReadMatch: reads under an approved root pass; escapes/mutations/smuggling do not (#64)" {
+ const r: []const []const u8 = &.{ "~/projects/merjs", "/opt/data" };
+ try std.testing.expect(planReadMatch("ls ~/projects/merjs", r));
+ try std.testing.expect(planReadMatch("ls ~/projects/merjs/src", r));
+ try std.testing.expect(planReadMatch("cat ~/projects/merjs/README.md", r));
+ try std.testing.expect(planReadMatch("grep foo /opt/data/x.txt", r));
+ try std.testing.expect(planReadMatch("grep foo ~/projects/merjs/a src/b.zig", r)); // cwd token ok alongside
+ try std.testing.expect(!planReadMatch("cat /etc/passwd", r)); // outside every root
+ try std.testing.expect(!planReadMatch("ls ~/secrets", r));
+ try std.testing.expect(!planReadMatch("cat ~/projects/merjs/../../etc/passwd", r)); // .. smuggling
+ try std.testing.expect(!planReadMatch("rm -rf ~/projects/merjs", r)); // mutating verb
+ try std.testing.expect(!planReadMatch("ls ~/projects/merjs; rm x", r)); // metachar
+ try std.testing.expect(!planReadMatch("ls ~/projects/merjs", &.{})); // nothing approved
+}
+
+test "isInterpreter: flags first words that grant arbitrary code execution" {
+ try std.testing.expect(isInterpreter("python3"));
+ try std.testing.expect(isInterpreter("node"));
+ try std.testing.expect(isInterpreter("bash"));
+ try std.testing.expect(isInterpreter("osascript"));
+ try std.testing.expect(!isInterpreter("ls"));
+ try std.testing.expect(!isInterpreter("git"));
+ try std.testing.expect(!isInterpreter("python3x"));
+}
+
+test "isDestructiveGit: flags work-destroying git, lets safe git through" {
+ try std.testing.expect(isDestructiveGit("git reset --hard HEAD~3"));
+ try std.testing.expect(isDestructiveGit("git clean -fd"));
+ try std.testing.expect(isDestructiveGit("git push --force origin main"));
+ try std.testing.expect(isDestructiveGit("git push -f"));
+ try std.testing.expect(isDestructiveGit("git branch -D worktree-docs"));
+ try std.testing.expect(isDestructiveGit("git checkout -- src/main.zig"));
+ try std.testing.expect(isDestructiveGit("git checkout ."));
+ try std.testing.expect(isDestructiveGit("git stash clear"));
+ try std.testing.expect(isDestructiveGit("cd sub && git reset --hard")); // chained
+ try std.testing.expect(isDestructiveGit("git -C /repo reset --hard")); // -C form
+
+ try std.testing.expect(!isDestructiveGit("git status"));
+ try std.testing.expect(!isDestructiveGit("git commit -m wip"));
+ try std.testing.expect(!isDestructiveGit("git reset --soft HEAD~1"));
+ try std.testing.expect(!isDestructiveGit("git checkout main"));
+ try std.testing.expect(!isDestructiveGit("git branch -d merged-feature"));
+ try std.testing.expect(!isDestructiveGit("git restore --staged f.txt"));
+ try std.testing.expect(!isDestructiveGit("ls -la"));
+}
+
+test "destructiveGitAllowed: only the root agent under --yolo skips the y/n" {
+ // The 'yolo fails on destructive git' report: --yolo lets the operator
+ // through (they opted out of prompts), but never a subagent and never a
+ // non-yolo run.
+ try std.testing.expect(destructiveGitAllowed(true, false));
+ try std.testing.expect(!destructiveGitAllowed(true, true));
+ try std.testing.expect(!destructiveGitAllowed(false, false));
+ try std.testing.expect(!destructiveGitAllowed(false, true));
+}
+
+test "confinedPath: rejects absolute, empty, and parent-escaping paths" {
+ try std.testing.expect(confinedPath("src/main.zig"));
+ try std.testing.expect(confinedPath("a/b/c"));
+ try std.testing.expect(!confinedPath(""));
+ try std.testing.expect(!confinedPath("/etc/passwd"));
+ try std.testing.expect(!confinedPath("../outside"));
+ try std.testing.expect(!confinedPath("a/../../b"));
+}
+
+test "the settings file has one spelling, and it lives in the settings dir" {
+ // Every reader and writer of the harness's own config resolves through
+ // these two constants; a drift between them would split the file in two.
+ try std.testing.expect(std.mem.startsWith(u8, settings_path, settings_dir ++ "/"));
+ try std.testing.expect(confinedPath(settings_path)); // never escapes the project
+}
diff --git a/src/imagegen.zig b/src/imagegen.zig
index a3d29dd9..271dbb23 100644
--- a/src/imagegen.zig
+++ b/src/imagegen.zig
@@ -46,9 +46,10 @@ const ToolOutput = tools.ToolOutput;
const strField = tools.strField;
const missingArg = tools.missingArg;
const outsideCwd = tools.outsideCwd;
-const approvals_mod = @import("approvals.zig");
-const confinedPath = approvals_mod.confinedPath;
-const noSymlinkEscape = approvals_mod.noSymlinkEscape;
+// Path confinement only — never the approval session (#422 ratchet).
+const policy = @import("harness_policy.zig");
+const confinedPath = policy.confinedPath;
+const noSymlinkEscape = policy.noSymlinkEscape;
const skills = @import("skills.zig");
const edit_verify = @import("edit_verify.zig"); // same per-path lock stripe write_file/edit_file use
const skill = @import("imagegen_skill.zig");
diff --git a/src/review.zig b/src/review.zig
index 3b0a9fa8..d61a6ca8 100644
--- a/src/review.zig
+++ b/src/review.zig
@@ -4,7 +4,8 @@
const std = @import("std");
const ToolCall = @import("tools.zig").ToolCall;
const ExecResult = @import("tools.zig").ExecResult;
-const Approvals = @import("approvals.zig").Approvals;
+// The read-only classifier only — never the approval session (#422 ratchet).
+const policy = @import("harness_policy.zig");
/// Give a review a fresh model-visible history while retaining the parent
/// transcript. The caller restores the parent after the one-shot review and
@@ -77,7 +78,7 @@ pub fn rejectTool(arena: std.mem.Allocator, call: ToolCall) !?ExecResult {
const background = call.input.object.get("run_in_background");
if (command == .string and
(background == null or background.? != .bool or !background.?.bool) and
- Approvals.readOnlyAllowed(command.string)) return null;
+ policy.readOnlyAllowed(command.string)) return null;
}
return denied(arena, call.name);
}
diff --git a/src/skill_docs.zig b/src/skill_docs.zig
index d167c828..6eb9cb3d 100644
--- a/src/skill_docs.zig
+++ b/src/skill_docs.zig
@@ -21,7 +21,8 @@ const Allocator = std.mem.Allocator;
const util = @import("util.zig");
const tools = @import("tools.zig");
const ToolOutput = tools.ToolOutput;
-const Approvals = @import("approvals.zig").Approvals;
+// Only the settings-file location, never the approval session (#422 ratchet).
+const policy = @import("harness_policy.zig");
pub const Source = enum {
builtin,
@@ -222,7 +223,7 @@ fn insert(arena: Allocator, list: *std.ArrayList(Skill), sk: Skill) void {
/// entirely — the same opt-out key the companion registry uses (skills.zig), so
/// `/skills remove <name>` works for both kinds.
fn applyDisabled(io: Io, arena: Allocator, list: *std.ArrayList(Skill)) void {
- const data = Io.Dir.cwd().readFileAlloc(io, Approvals.settings_path, arena, .limited(1 << 20)) catch return;
+ const data = Io.Dir.cwd().readFileAlloc(io, policy.settings_path, arena, .limited(1 << 20)) catch return;
const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return;
if (v != .object) return;
const cfg = v.object.get("skills") orelse return;
@@ -294,58 +295,9 @@ fn listing(gpa: Allocator, list: []const Skill, unknown: ?[]const u8) ![]u8 {
return aw.toOwnedSlice();
}
-// --- the `/skills` surface (called from commands_session.zig) ---------------
-
-const skills_companions = @import("skills.zig");
-const ansi = @import("ansi.zig");
-const style = &ansi.style;
-
-/// `/skills remove <name>` for the markdown kind: true when `name` matched an
-/// active skill. Persists through the companions' {"skills": {…: false}} key.
-pub fn handleRemove(io: Io, gpa: Allocator, arena: Allocator, name: []const u8, out: *Io.Writer) !bool {
- for (g_skills) |sk| {
- if (!std.mem.eql(u8, sk.name, name)) continue;
- if (skills_companions.saveSkillSetting(io, gpa, name, false)) {
- _ = reload(io, arena);
- try out.print("{s}✓ {s} disabled{s} — the skill tool no longer serves it; it leaves the startup catalog next session\n", .{ style.green, name, style.reset });
- } else {
- try out.print("{s}could not write {s} — {s} is still active{s}\n", .{ style.yellow, Approvals.settings_path, name, style.reset });
- }
- try out.flush();
- return true;
- }
- return false;
-}
-
-/// `/skills add <name>`: re-enable a markdown skill hidden by an earlier
-/// remove. Scans disabled ones too, so "hidden" and "no such skill" differ.
-pub fn handleAdd(io: Io, gpa: Allocator, arena: Allocator, name: []const u8, out: *Io.Writer) !bool {
- for (scanAll(io, arena)) |sk| {
- if (!std.mem.eql(u8, sk.name, name)) continue;
- if (skills_companions.saveSkillSetting(io, gpa, sk.name, true)) {
- _ = reload(io, arena);
- try out.print("{s}✓ {s} enabled{s} — loadable with the skill tool now\n", .{ style.green, sk.name, style.reset });
- } else {
- try out.print("{s}could not write {s} — {s} stays disabled{s}\n", .{ style.yellow, Approvals.settings_path, sk.name, style.reset });
- }
- try out.flush();
- return true;
- }
- return false;
-}
-
-/// The markdown-skills section of `/skills` — re-scanned so a SKILL.md written
-/// this session shows up without a restart.
-pub fn printSection(io: Io, arena: Allocator, out: *Io.Writer) !void {
- const md_skills = reload(io, arena);
- try out.print("{s}skills{s} — SKILL.md playbooks; the model loads one on demand with the `skill` tool\n", .{ style.bold, style.reset });
- if (md_skills.len == 0) {
- try out.print(" {s}none — write one at {s}/<name>/SKILL.md{s}\n", .{ style.dim, project_dir, style.reset });
- } else for (md_skills) |sk| {
- try out.print(" {s}{s:<16}{s} {s}{s:<9}{s} {s}\n", .{ style.accent, sk.name, style.reset, style.dim, sk.source.label(), style.reset, util.utf8Prefix(sk.desc, 100) });
- }
- try out.print(" disable one: /skills remove <name> · re-enable: /skills add <name>\n\n", .{});
-}
+// The `/skills` command surface — handleRemove/handleAdd/printSection — lives
+// in skill_docs_render.zig (#429). It is the only part of this module that ever
+// drew, and drawing is the command layer's job, not the skill subsystem's.
test "parseDoc: frontmatter wins over the filename, body starts after it" {
const p = parseDoc("from-file", "---\nname: real-name\ndescription: what it does and when\n---\n\n# Body\nstep one\n");
diff --git a/src/skill_docs_render.zig b/src/skill_docs_render.zig
new file mode 100644
index 00000000..d528e35b
--- /dev/null
+++ b/src/skill_docs_render.zig
@@ -0,0 +1,95 @@
+//! The `/skills` command surface for markdown playbooks: the three functions
+//! that draw. Split off skill_docs.zig (#422/#429) so that module is purely
+//! about discovering, parsing and serving SKILL.md files — the job its own
+//! header describes — and stops reaching the palette.
+//!
+//! Why a command renderer rather than engine events: `/skills` is a slash
+//! command, and its other half (the companion-binary rows) is printed inline by
+//! commands_session.zig, which owns the whole command's layout. Routing only
+//! the markdown half through the engine sink would put one half of one
+//! command's output behind a contract that has no wire shape for it and leave
+//! the other half inline — exactly the TUI/JSON divergence #422 exists to
+//! remove. The command layer is frontend territory (Phase 1b), so the drawing
+//! moves here whole, byte for byte, and the engine module comes out clean.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const util = @import("util.zig");
+const skill_docs = @import("skill_docs.zig");
+const skills_companions = @import("skills.zig");
+const policy = @import("harness_policy.zig");
+const style = &@import("ansi.zig").style;
+
+/// `/skills remove <name>` for the markdown kind: true when `name` matched an
+/// active skill. Persists through the companions' {"skills": {…: false}} key.
+pub fn handleRemove(io: Io, gpa: Allocator, arena: Allocator, name: []const u8, out: *Io.Writer) !bool {
+ for (skill_docs.g_skills) |sk| {
+ if (!std.mem.eql(u8, sk.name, name)) continue;
+ if (skills_companions.saveSkillSetting(io, gpa, name, false)) {
+ _ = skill_docs.reload(io, arena);
+ try out.print("{s}✓ {s} disabled{s} — the skill tool no longer serves it; it leaves the startup catalog next session\n", .{ style.green, name, style.reset });
+ } else {
+ try out.print("{s}could not write {s} — {s} is still active{s}\n", .{ style.yellow, policy.settings_path, name, style.reset });
+ }
+ try out.flush();
+ return true;
+ }
+ return false;
+}
+
+/// `/skills add <name>`: re-enable a markdown skill hidden by an earlier
+/// remove. Scans disabled ones too, so "hidden" and "no such skill" differ.
+pub fn handleAdd(io: Io, gpa: Allocator, arena: Allocator, name: []const u8, out: *Io.Writer) !bool {
+ for (skill_docs.scanAll(io, arena)) |sk| {
+ if (!std.mem.eql(u8, sk.name, name)) continue;
+ if (skills_companions.saveSkillSetting(io, gpa, sk.name, true)) {
+ _ = skill_docs.reload(io, arena);
+ try out.print("{s}✓ {s} enabled{s} — loadable with the skill tool now\n", .{ style.green, sk.name, style.reset });
+ } else {
+ try out.print("{s}could not write {s} — {s} stays disabled{s}\n", .{ style.yellow, policy.settings_path, sk.name, style.reset });
+ }
+ try out.flush();
+ return true;
+ }
+ return false;
+}
+
+/// The markdown-skills section of `/skills` — re-scanned so a SKILL.md written
+/// this session shows up without a restart.
+pub fn printSection(io: Io, arena: Allocator, out: *Io.Writer) !void {
+ const md_skills = skill_docs.reload(io, arena);
+ try out.print("{s}skills{s} — SKILL.md playbooks; the model loads one on demand with the `skill` tool\n", .{ style.bold, style.reset });
+ if (md_skills.len == 0) {
+ try out.print(" {s}none — write one at {s}/<name>/SKILL.md{s}\n", .{ style.dim, skill_docs.project_dir, style.reset });
+ } else for (md_skills) |sk| {
+ try out.print(" {s}{s:<16}{s} {s}{s:<9}{s} {s}\n", .{ style.accent, sk.name, style.reset, style.dim, sk.source.label(), style.reset, util.utf8Prefix(sk.desc, 100) });
+ }
+ try out.print(" disable one: /skills remove <name> · re-enable: /skills add <name>\n\n", .{});
+}
+
+test "the /skills catalog rows carry name, tier and a capped description" {
+ // Pins the plain-terminal bytes of the section, so the move off
+ // skill_docs.zig cannot quietly change a column width or the trailing
+ // blank line the companions section renders after.
+ const saved = style.*;
+ style.* = .{}; // assert the text, not the palette
+ defer style.* = saved;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ const rows = [_]skill_docs.Skill{
+ .{ .name = "deploy", .desc = "ship a release", .body = "b", .source = .project },
+ .{ .name = "mcp-config", .desc = "servers", .body = "b", .source = .builtin },
+ };
+ try aw.writer.print("{s}skills{s} — SKILL.md playbooks; the model loads one on demand with the `skill` tool\n", .{ style.bold, style.reset });
+ for (rows) |sk| {
+ try aw.writer.print(" {s}{s:<16}{s} {s}{s:<9}{s} {s}\n", .{ style.accent, sk.name, style.reset, style.dim, sk.source.label(), style.reset, util.utf8Prefix(sk.desc, 100) });
+ }
+ try std.testing.expectEqualStrings(
+ "skills — SKILL.md playbooks; the model loads one on demand with the `skill` tool\n" ++
+ " deploy project ship a release\n" ++
+ " mcp-config bundled servers\n",
+ aw.writer.buffered(),
+ );
+}
diff --git a/src/skills.zig b/src/skills.zig
index 4407be0f..fa522023 100644
--- a/src/skills.zig
+++ b/src/skills.zig
@@ -7,8 +7,8 @@
//! goal). companionRoute/companionNativeFallback stay in main.zig — they take
//! ToolCtx/ToolCall, which are still main-resident (the tools/exec region
//! hasn't been extracted yet), and are only called from execTool's routing
-//! path there. Back-imports main for Approvals, runCapped (= jobs.runCapped),
-//! and the LIVE mutable globals g_path_env/g_skill_disabled/
+//! path there. Back-imports main for runCapped (= jobs.runCapped) and the LIVE
+//! mutable globals g_path_env/g_skill_disabled/
//! g_companion_disabled — these stay `pub var` in main.zig (its own /skills
//! command handler and startup code read/write them directly too), never
//! aliased by value here.
@@ -21,9 +21,9 @@ const mcp = @import("mcp.zig");
const smolify_manifest = @import("smolify_manifest.zig");
const main_mod = @import("main.zig");
-const approvals_mod = @import("approvals.zig");
+// Only the settings-file location, never the approval session (#422 ratchet).
+const policy = @import("harness_policy.zig");
const jobs = @import("jobs.zig");
-const Approvals = approvals_mod.Approvals;
const runCapped = jobs.runCapped;
/// Codex-style optional skills: known companion tools the harness quietly
@@ -217,7 +217,7 @@ pub fn skillActive(io: Io, sk: SkillDef) bool {
/// anything else leaves it enabled. Covers skills_registry AND companion
/// servers (codedb-pro).
pub fn loadSkillSettings(io: Io, arena: Allocator) void {
- const data = Io.Dir.cwd().readFileAlloc(io, Approvals.settings_path, arena, .limited(1 << 20)) catch return;
+ const data = Io.Dir.cwd().readFileAlloc(io, policy.settings_path, arena, .limited(1 << 20)) catch return;
const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return;
if (v != .object) return;
const skills = v.object.get("skills") orelse return;
@@ -242,12 +242,12 @@ fn applySkillSettings(skills: Value) void {
/// preserving every other key (allow-list and hooks live there too).
/// Enabling removes the key; disabling writes `false`. Best-effort.
pub fn saveSkillSetting(io: Io, gpa: Allocator, name: []const u8, enabled: bool) bool {
- Io.Dir.cwd().createDir(io, Approvals.settings_dir, .default_dir) catch {}; // already-exists is fine
+ Io.Dir.cwd().createDir(io, policy.settings_dir, .default_dir) catch {}; // already-exists is fine
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const a = arena_state.allocator();
var root_obj: std.json.ObjectMap = .empty;
- if (Io.Dir.cwd().readFileAlloc(io, Approvals.settings_path, a, .limited(1 << 20))) |data| {
+ if (Io.Dir.cwd().readFileAlloc(io, policy.settings_path, a, .limited(1 << 20))) |data| {
if (std.json.parseFromSliceLeaky(Value, a, data, .{ .allocate = .alloc_always })) |v| {
if (v == .object) root_obj = v.object;
} else |_| {}
@@ -270,7 +270,7 @@ pub fn saveSkillSetting(io: Io, gpa: Allocator, name: []const u8, enabled: bool)
defer aw.deinit();
var s: std.json.Stringify = .{ .writer = &aw.writer, .options = .{ .whitespace = .indent_2 } };
s.write(Value{ .object = root_obj }) catch return false;
- const f = Io.Dir.cwd().createFile(io, Approvals.settings_path, .{}) catch return false;
+ const f = Io.Dir.cwd().createFile(io, policy.settings_path, .{}) catch return false;
defer f.close(io);
var wbuf: [4096]u8 = undefined;
var fw = f.writer(io, &wbuf);
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 033f8746..08d6b302 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -129,6 +129,12 @@ const credential_store = @import("credential_store.zig");
// Production reaches both only through CALLS, so their tests need the hook.
const engine_events = @import("engine_events.zig");
const engine_sink = @import("engine_sink.zig");
+// #429 batch 3: the terminal halves the status line and the `/skills` command
+// surface moved into, plus the policy leaf approvals.zig split its pure half
+// out to. Production reaches all three through calls or aliases only.
+const agent_prompt_render = @import("agent_prompt_render.zig");
+const skill_docs_render = @import("skill_docs_render.zig");
+const harness_policy = @import("harness_policy.zig");
// #412: the worktree fingerprint behind the no-progress verify guard.
// agent_eval.zig reaches it through a CALL only, which analyses nothing.
@@ -179,6 +185,9 @@ test {
_ = credential_store;
_ = engine_events;
_ = engine_sink;
+ _ = agent_prompt_render;
+ _ = skill_docs_render;
+ _ = harness_policy;
_ = verify_fingerprint;
_ = proc_identity;
_ = escalation;