graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: add runtime version status command
yxlyx9206e7f6da32
diff --git a/TUI/bgop.zig b/TUI/bgop.zigindex 21530f87..e9bb0d82 100644--- a/TUI/bgop.zig+++ b/TUI/bgop.zig@@ -1,4 +1,4 @@-//! Background engine ops. `/compact`, `!cmd` and the @-file list used to call+//! Background engine ops. `/compact`, `/version`, `!cmd` and the @-file list used to call//! straight into the engine from keys.handle, i.e. from inside run.zig's byte//! parse loop: no render, no poll, no key handling, no cancel for the whole//! round trip — a 5-60 s freeze indistinguishable from a hang (#533).@@ -72,11 +72,13 @@ pub fn finish(self: *Model) void {.compact => "compaction failed to start",.bash => "command failed to start",.files => "file list failed to start",+ .version => "version check failed to start",}) catch {};} else switch (op.kind) {.compact => applyCompact(self, op),.bash => applyBash(self, op),.files => applyFiles(self, op),+ .version => applyVersion(self, op),}release(self, op);self.scroll = 0;@@ -161,6 +163,16 @@ fn applyFiles(self: *Model, op: *Op) void {self.files_cache = self.alloc.dupe(u8, t) catch null;}+fn applyVersion(self: *Model, op: *Op) void {+ if (op.text) |text| {+ self.push(.system, text) catch {};+ } else if (op.cancelled) {+ self.push(.system, "version check cancelled") catch {};+ } else {+ self.push(.err, "version check unavailable") catch {};+ }+}+const testing = std.testing;fn drain(m: *Model) !void {@@ -284,20 +296,27 @@ test "thread spawn failure completes through finish without inline engine work (calls += 1;return null;}+ fn version(_: ?*anyopaque, _: std.mem.Allocator) ?[]const u8 {+ calls += 1;+ return null;+ }};Fake.calls = 0;engine.g_compact_fn = Fake.compact;engine.g_bash_fn = Fake.bash;engine.g_files_fn = Fake.files;+ engine.g_version_fn = Fake.version;defer {engine.g_compact_fn = null;engine.g_bash_fn = null;engine.g_files_fn = null;+ engine.g_version_fn = null;}const cases = [_]struct { kind: Op.Kind, message: []const u8 }{.{ .kind = .compact, .message = "compaction failed to start" },.{ .kind = .bash, .message = "command failed to start" },.{ .kind = .files, .message = "file list failed to start" },+ .{ .kind = .version, .message = "version check failed to start" },};for (cases) |case| {var m: Model = undefined;diff --git a/TUI/catalog.zig b/TUI/catalog.zigindex a8dc3d5b..7f0af231 100644--- a/TUI/catalog.zig+++ b/TUI/catalog.zig@@ -16,6 +16,7 @@ pub const items = [_]Item{.{ .name = "/compact", .desc = "Engine-compact model-visible history" },.{ .name = "/context", .desc = "Show context-window use" },.{ .name = "/session-info", .desc = "Session details", .aliases = &.{ "/status", "/info" } },+ .{ .name = "/version", .desc = "Running binary and latest release status" },.{ .name = "/usage", .desc = "Token usage and cost", .aliases = &.{"/cost"} },.{ .name = "/debug", .desc = "Live observability HUD" },.{ .name = "/cache", .desc = "Prompt-cache posture and remaining max levers" },diff --git a/TUI/dispatch.zig b/TUI/dispatch.zigindex b9c55b63..7095ac2e 100644--- a/TUI/dispatch.zig+++ b/TUI/dispatch.zig@@ -203,6 +203,8 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {self.pushFmt(.system, "session: {s}", .{self.session_name orelse "untitled"}) catch {};} else if (std.mem.eql(u8, canon, "/session-info")) {meters.sessionInfo(self);+ } else if (std.mem.eql(u8, canon, "/version")) {+ if (!bgop.start(self, .version, &.{}, "", "checking version")) self.push(.system, busy_note) catch {};} else if (std.mem.eql(u8, canon, "/debug") or std.mem.eql(u8, canon, "/cache")) {self.openOverlay(.debug);} else if (std.mem.eql(u8, canon, "/usage")) {diff --git a/TUI/dispatch_command_tests.zig b/TUI/dispatch_command_tests.zigindex 3e3bbb4c..e3431103 100644--- a/TUI/dispatch_command_tests.zig+++ b/TUI/dispatch_command_tests.zig@@ -4,6 +4,7 @@ const std = @import("std");const app = @import("app.zig");const dispatch = @import("dispatch.zig");+const bgop = @import("bgop.zig");const engine = @import("engine.zig");const turn = @import("turn.zig");const Effect = app.Effect;@@ -41,6 +42,31 @@ test "/cache opens the same observability overlay" {try std.testing.expectEqual(app.Overlay.debug, m.overlay);}+test "/version checks in the background and reports the running executable boundary" {+ engine.g_version_fn = struct {+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8 {+ return gpa.dupe(u8, "graff v0.0.291 (running process)\nlatest release: v0.0.292 — update available\n/new and /resume do not reload the executable.\n") catch null;+ }+ }.f;+ defer engine.g_version_fn = null;+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ _ = applyLine(&m, "/version");+ try std.testing.expect(m.bg != null);+ try std.testing.expectEqual(engine.BgOp.Kind.version, m.bg.?.kind);+ try std.testing.expectEqual(app.EntryKind.pending, m.history.items[0].kind);+ var spins: usize = 0;+ while (!m.bg.?.done.load(.acquire)) : (spins += 1) {+ if (spins > 1_000_000) return error.VersionCheckNeverFinished;+ std.Thread.yield() catch {};+ }+ bgop.finish(&m);+ const text = m.history.items[m.history.items.len - 1].text;+ try std.testing.expect(std.mem.indexOf(u8, text, "running process") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "/new and /resume") != null);+}+test "/usage is not a char-count view" {var m: Model = undefined;m.setup(std.testing.allocator);diff --git a/TUI/engine.zig b/TUI/engine.zigindex 42fd4ab5..8bddc9ed 100644--- a/TUI/engine.zig+++ b/TUI/engine.zig@@ -71,13 +71,15 @@ pub var g_idle_wake_fn: ?IdleWakeFn = null;/// mailbox (`tellCommand` / `peekCommand`). Caller frees the returned text.pub const PeerFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, line: []const u8) ?[]const u8;pub var g_peer_fn: ?PeerFn = null;+pub const VersionFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;+pub var g_version_fn: ?VersionFn = null;-/// A background engine op: `/compact`, `!cmd`, or the @-file list. Same+/// A background engine op: `/compact`, `/version`, `!cmd`, or the @-file list. Same/// thread + done-flag contract as Job, so the render+input loop keeps painting/// and Esc keeps reaching keys.handle while the engine works (#533). Every/// field the worker writes is read only after `done`.pub const BgOp = struct {- pub const Kind = enum { compact, bash, files };+ pub const Kind = enum { compact, bash, files, version };kind: Kind,gpa: std.mem.Allocator,@@ -98,7 +100,7 @@ pub const BgOp = struct {/// compact output — gpa-owned.compact: CompactOut = .{},ok: bool = false,- /// bash / files output — gpa-owned.+ /// bash / files / version output — gpa-owned.text: ?[]const u8 = null,};@@ -113,6 +115,9 @@ pub fn bgRun(op: *BgOp) void {.files => if (g_files_fn) |f| {op.text = f(g_turn_ctx, op.gpa);},+ .version => if (g_version_fn) |f| {+ op.text = f(g_turn_ctx, op.gpa);+ },}op.done.store(true, .release);}@@ -152,6 +157,7 @@ pub const RunOpts = struct {emergency_fn: ?*const fn (turn_ctx: ?*anyopaque) void = null,idle_wake_fn: ?IdleWakeFn = null,peer_fn: ?PeerFn = null,+ version_fn: ?VersionFn = null,};pub var g_turn_fn: ?TurnFn = null;diff --git a/TUI/root.zig b/TUI/root.zigindex 84fa3cfb..5df42612 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -41,6 +41,7 @@ pub const SessionState = engine.SessionState;pub const GoalOp = engine.GoalOp;pub const StateFn = engine.StateFn;pub const PeerFn = engine.PeerFn;+pub const VersionFn = engine.VersionFn;pub const RunOpts = run_mod.RunOpts;pub const run = run_mod.run;pub fn setCurrentModel(name: []const u8, provider: []const u8) void {diff --git a/TUI/run.zig b/TUI/run.zigindex d260a119..e4553d01 100644--- a/TUI/run.zig+++ b/TUI/run.zig@@ -61,6 +61,7 @@ pub fn run(engine.g_state_fn = opts.state_fn;engine.g_idle_wake_fn = opts.idle_wake_fn;engine.g_peer_fn = opts.peer_fn;+ engine.g_version_fn = opts.version_fn;engine.g_model_name = opts.model_name;engine.g_model_provider = opts.model_provider;engine.g_model_entries = opts.model_entries;diff --git a/build.zig b/build.zigindex 773c7e2d..7ecfc028 100644--- a/build.zig+++ b/build.zig@@ -169,6 +169,7 @@ pub fn build(b: *std.Build) void {.strip = lean_release,}),});+ repl_exe.root_module.addOptions("build_options", opts);repl_exe.root_module.addImport("zigzag", zigzag.module("zigzag"));b.installArtifact(repl_exe);diff --git a/src/cli.zig b/src/cli.zigindex db116778..faad485a 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -10,11 +10,11 @@const std = @import("std");const Io = std.Io;-const Value = std.json.Value;const Allocator = std.mem.Allocator;const root = @import("main.zig");const harness_version = root.harness_version;+const version_status = @import("version_status.zig");/// Shown under `graff --version` — a terse "what's new" for recent releases./// Keep it short and current; bump alongside the version each release.@@ -384,89 +384,13 @@ pub const usage_text =\\;-const Version = struct {- major: u32,- minor: u32,- patch: u32,-- fn eql(self: Version, other: Version) bool {- return self.major == other.major and self.minor == other.minor and self.patch == other.patch;- }-- fn order(self: Version, other: Version) std.math.Order {- if (self.major != other.major) return std.math.order(self.major, other.major);- if (self.minor != other.minor) return std.math.order(self.minor, other.minor);- return std.math.order(self.patch, other.patch);- }-};--/// Parse a leading `MAJOR.MINOR.PATCH` from `s` (after any leading 'v' is-/// stripped by the caller). Returns null if the numeric triple isn't present.-fn parseVersion(s: []const u8) ?Version {- var it = std.mem.splitScalar(u8, s, '.');- const major_s = it.next() orelse return null;- const minor_s = it.next() orelse return null;- const patch_s = it.next() orelse return null;- // Each component must be all digits up to the next '.' (or end). `patch`- // may trail a pre-release suffix ("-3-gabc", "-dev"); take only the leading- // digits so "0.0.14-3-gabc" parses as 0.0.14.- const major = std.fmt.parseInt(u32, major_s, 10) catch return null;- const minor = std.fmt.parseInt(u32, minor_s, 10) catch return null;- const patch_digits = std.mem.indexOfAny(u8, patch_s, "-+") orelse patch_s.len;- const patch = std.fmt.parseInt(u32, patch_s[0..patch_digits], 10) catch return null;- return .{ .major = major, .minor = minor, .patch = patch };-}--/// True when `s` is a bare release version with no `git describe` suffix — i.e.-/// exactly `MAJOR.MINOR.PATCH` (optionally 'v'-prefixed), no "-N-gHASH",-/// "-dirty", "-dev", or "+build". A dev/dirty/commit-ahead build is not a clean-/// release and shouldn't be silently "updated" (downgraded) to an older tag.-fn isCleanReleaseVersion(s: []const u8) bool {- if (s.len == 0) return false;- var dots: u8 = 0;- for (s) |c| {- switch (c) {- '0'...'9' => {},- '.' => dots += 1,- else => return false, // any '-','+','g',... means it's not a bare tag- }- }- return dots == 2;-}--fn fetchLatestReleaseTag(io: Io, gpa: Allocator, arena: Allocator, repo_api: []const u8) ?[]const u8 {- var client: std.http.Client = .{ .allocator = gpa, .io = io };- defer client.deinit();- var aw: Io.Writer.Allocating = .init(arena);- defer aw.deinit();- const extra = [_]std.http.Header{.{ .name = "Accept", .value = "application/vnd.github+json" }};- const res = client.fetch(.{- .location = .{ .url = repo_api },- .method = .GET,- .response_writer = &aw.writer,- .headers = .{ .user_agent = .{ .override = "simple-harness/" ++ harness_version } },- .extra_headers = &extra,- }) catch return null;- if (@intFromEnum(res.status) != 200) return null;- if (aw.writer.buffered().len > 64 * 1024) return null;- const v = std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always }) catch return null;- if (v != .object) return null;- const t = v.object.get("tag_name") orelse return null;- return if (t == .string) t.string else null;-}-/// Dim REPL/TUI line when GitHub has a newer release. Null if current, newer,/// offline, or GRAFF_NO_UPDATE_CHECK is set.pub fn updateAvailableLine(io: Io, gpa: Allocator, arena: Allocator, skip: bool) ?[]const u8 {if (skip) return null;- const repo_api = "https://api.github.com/repos/justrach/codegraff/releases/latest";- const latest_tag = fetchLatestReleaseTag(io, gpa, arena, repo_api) orelse return null;- const cur_raw = if (std.mem.startsWith(u8, harness_version, "v")) harness_version[1..] else harness_version;- const latest_raw = if (std.mem.startsWith(u8, latest_tag, "v")) latest_tag[1..] else latest_tag;- const cur = parseVersion(cur_raw) orelse return null;- const latest = parseVersion(latest_raw) orelse return null;- if (cur.order(latest) != .lt) return null;- return std.fmt.allocPrint(arena, "graff v{s} is available (you have {s}) — graff update", .{ latest_raw, cur_raw }) catch null;+ const check = version_status.checkLatest(io, gpa, arena, harness_version);+ if (check.order != .lt) return null;+ return std.fmt.allocPrint(arena, "graff v{s} is available (you have {s}) — graff update", .{ check.latest.?, check.running }) catch null;}/// `graff update [--force|--check]` — bring the installed binary up to the@@ -484,7 +408,6 @@ pub fn updateCommand(force: bool,check_only: bool,) !void {- const repo_api = "https://api.github.com/repos/justrach/codegraff/releases/latest";const install_url = environ.get("GRAFF_INSTALL_URL") orelse environ.get("HARNESS_INSTALL_URL") orelse"https://github.com/justrach/codegraff/releases/latest/download/install.sh";@@ -492,34 +415,20 @@ pub fn updateCommand(var ow = Io.File.stdout().writer(io, &obuf);const out = &ow.interface;- // current version, leading 'v' stripped so the comparison ignores tag style.- const cur_raw = if (std.mem.startsWith(u8, harness_version, "v")) harness_version[1..] else harness_version;-- // A release tag is a bare "MAJOR.MINOR.PATCH". A dev/dirty/commit-ahead- // build (from `git describe --tags --always --dirty`) carries a suffix- // ("-3-gabc", "-dirty", "-dev+hash", "0.1.0-dev") and is NOT a clean- // release version. Comparing such a string against a release tag with exact- // equality always mismatched, so `graff update` would "update" (downgrade)- // a newer dev build to an older release, and `--check` always reported an- // update available. Parse the leading numeric triple instead, and refuse to- // act on a non-release local build rather than silently downgrading it.- const cur = parseVersion(cur_raw);- const cur_is_release = cur != null and isCleanReleaseVersion(cur_raw);-- const latest_tag = fetchLatestReleaseTag(io, gpa, arena, repo_api);-- // `latest` is a release tag from GitHub, so it parses to a clean triple.- const latest_raw = if (latest_tag) |tag| (if (std.mem.startsWith(u8, tag, "v")) tag[1..] else tag) else null;- const latest = if (latest_raw) |r| parseVersion(r) else null;+ const check = version_status.checkLatest(io, gpa, arena, harness_version);+ const cur_raw = check.running;+ const latest_tag = check.latest_tag;+ const latest_raw = check.latest;- if (latest_tag != null and latest == null) {+ if (check.failure == .latest_tag) {// The release endpoint returned a tag we couldn't parse — treat like a// failed check rather than guessing.if (check_only) std.process.fatal("update check failed — unparseable release tag '{s}'", .{latest_tag.?});try out.print("could not parse latest release tag '{s}'; running installer anyway…\n", .{latest_tag.?});- } else if (latest != null) {- const up_to_date = cur != null and cur.?.eql(latest.?);- const cur_newer = cur != null and cur.?.order(latest.?) == .gt;+ } else if (latest_raw != null) {+ const up_to_date = check.order == .eq;+ const cur_newer = check.order == .gt;+ const cur_is_release = check.clean_release;if (check_only) {if (cur_is_release and up_to_date) {diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 13a2d4cb..60df023d 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -84,6 +84,7 @@ pub const commands = [_]Item{.{ .name = "/jobs", .usage = "/jobs [keep|unkeep|stop|restart <id>]", .desc = "list background jobs (age, port, idle stop); keep pins a server, restart reruns one" },.{ .name = "/cost", .desc = "session token usage and cost" },.{ .name = "/usage", .desc = "alias for /cost" },+ .{ .name = "/version", .desc = "show the version in this process and compare it with the latest release" },.{ .name = "/debug", .desc = "live content-free observability HUD (turns, tokens, tools, last events)" },.{ .name = "/cache", .desc = "prompt-cache posture: prefix hash, hit rate, last bust, remaining max levers" },.{ .name = "/tools", .desc = "session tool balance: codedb-pro vs zigrep vs native usage, gate refusals, skew" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex a3aae89e..98ba8862 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -16,6 +16,7 @@ const Agent = agent_mod.Agent;const Keys = provider_mod.Keys;const utf8Prefix = util.utf8Prefix;const harness_version = main_mod.harness_version;+const version_status = @import("version_status.zig");const mcp_config_path = main_mod.mcp_config_path;const session_ext = session.session_ext;const saveSession = session.saveSession;@@ -165,6 +166,13 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (std.mem.startsWith(u8, line, "/schedule") and (line.len == 9 or line[9] == ' ' or line[9] == '\t')) return @import("schedule.zig").slashCommand(root, arena, line, out);if (std.mem.startsWith(u8, line, "/adapter") and (line.len == 8 or line[8] == ' ' or line[8] == '\t')) return @import("channel_worker.zig").slashCommand(root, arena, line, out);if (try side_question.command(root, arena, line, out)) return true; // #415 /btw+ if (std.mem.eql(u8, line, "/version")) {+ const text = try version_status.commandText(root.io, root.gpa, harness_version);+ defer root.gpa.free(text);+ try out.writeAll(text);+ try out.flush();+ return true;+ }// #321: doctor.zig shipped with a catalog entry but no dispatch, so /doctor// was advertised in /help and the `/` menu while answering "unknown command".if (std.mem.eql(u8, line, "/doctor")) {diff --git a/src/help.zig b/src/help.zigindex 037430ab..e54d064d 100644--- a/src/help.zig+++ b/src/help.zig@@ -32,7 +32,7 @@ pub const sections = [_]Section{.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },.{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/schedule", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek", "/adapter" }, .blurb = peers_blurb },- .{ .title = "your setup", .names = &.{ "/login", "/key", "/cost", "/usage", "/privacy", "/mcp", "/import-claude", "/skills", "/plugins", "/agents", "/hooks", "/tools", "/fleet" } },+ .{ .title = "your setup", .names = &.{ "/login", "/key", "/cost", "/usage", "/version", "/privacy", "/mcp", "/import-claude", "/skills", "/plugins", "/agents", "/hooks", "/tools", "/fleet" } },.{ .title = "context & history", .names = &.{ "/compact", "/btw", "/doctor", "/debug", "/cache", "/trace", "/trajectory" } },.{ .title = "shell & images", .names = &.{ "/bash", "/image", "/images", "/paste" } },.{ .title = "look & feel", .names = &.{ "/theme", "/animation", "/title" } },diff --git a/src/main.zig b/src/main.zigindex 8c385d7b..9a7830b1 100644--- a/src/main.zig+++ b/src/main.zig@@ -78,6 +78,7 @@ test { // unit_tests' root is main.zig only, so reference every split-out module_ = mcp_cli;_ = @import("adopt.zig");_ = cli;+ _ = @import("version_status.zig");_ = prompts;_ = session;_ = keys_cli;diff --git a/src/repl.zig b/src/repl.zigindex dd50bd1d..eb0e4e48 100644--- a/src/repl.zig+++ b/src/repl.zig@@ -73,6 +73,8 @@ pub var g_models: []const u8 = ""; // comma-joined model names (for /models)pub var g_model_fn: ?ModelFn = null; // switch the active model by namepub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;pub var g_cancel_fn: ?CancelFn = null; // force-interrupt the running turn (steer drain)+pub const VersionFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;+pub var g_version_fn: ?VersionFn = null;pub var g_debug: bool = false; // GRAFF_REPL_DEBUG / `/debug` → dump raw stream + frames to stderr// ---------------------------------------------------------------------------@@ -356,6 +358,7 @@ pub const HELP_CALC =\\Commands:\\ /help this help\\ /clear clear the conversation+ \\ /version running binary and latest release status\\ /animation enso|braille|dragon spinner style\\ /quit exit (also /q, ctrl-c)\\diff --git a/src/repl_model_commands.zig b/src/repl_model_commands.zigindex 3de44a36..ba946b9b 100644--- a/src/repl_model_commands.zig+++ b/src/repl_model_commands.zig@@ -8,6 +8,8 @@ const std = @import("std");const repl = @import("repl.zig");const Model = repl.Model;+const version_status = @import("version_status.zig");+const build_options = @import("build_options");const util = @import("repl_util.zig");const eqlAny = util.eqlAny;@@ -41,6 +43,8 @@ pub fn runCommand(self: *Model, line: []const u8) void {self.compact();} else if (std.mem.eql(u8, cmd, "/help")) {self.push(.info, if (self.chat) HELP_CHAT else repl.HELP_CALC) catch {};+ } else if (std.mem.eql(u8, cmd, "/version")) {+ showVersion(self);} else if (std.mem.eql(u8, cmd, "/model")) {if (arg.len == 0) {if (repl.g_model_name.len > 0) self.pushFmt(.info, "model: {s}", .{repl.g_model_name}) catch {} else self.push(.info, "no model configured") catch {};@@ -128,6 +132,36 @@ pub fn runCommand(self: *Model, line: []const u8) void {}}+fn showVersion(self: *Model) void {+ if (repl.g_version_fn) |f| if (f(repl.g_turn_ctx, self.alloc)) |text| {+ self.pushOwned(.info, text) catch self.alloc.free(text);+ return;+ };+ var aw: std.Io.Writer.Allocating = .init(self.alloc);+ version_status.renderVersion(&aw.writer, version_status.compare(build_options.version, null)) catch {+ aw.deinit();+ self.push(.err, "version check unavailable") catch {};+ return;+ };+ const text = aw.toOwnedSlice() catch {+ aw.deinit();+ self.push(.err, "version check unavailable") catch {};+ return;+ };+ self.pushOwned(.info, text) catch self.alloc.free(text);+}++test "/version identifies the running process even without a release callback" {+ repl.g_version_fn = null;+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ runCommand(&m, "/version");+ const text = m.history.items[m.history.items.len - 1].text;+ try std.testing.expect(std.mem.indexOf(u8, text, "running process") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "/new and /resume") != null);+}+/// Remove the last user turn and everything after it (its reply).pub fn rewind(self: *Model) void {var i = self.history.items.len;diff --git a/src/repl_util.zig b/src/repl_util.zigindex 653c9245..e57f5ad9 100644--- a/src/repl_util.zig+++ b/src/repl_util.zig@@ -11,7 +11,7 @@ pub const accent = zz.Color.fromRgb(0x05, 0x96, 0x69); // codegraff.com emeraldpub const HELP_CHAT =\\Commands (mirrors the graff session):\\ /help /clear /new /quit conversation- \\ /rewind /compact /cost history+ \\ /rewind /compact /cost /version history and running binary\\ /model [name] /models model (switch / list)\\ /effort low|med|high|xhigh|max|ultra reasoning depth\\ /fast /thinking /ultracode thinking controls (toggles)diff --git a/src/session_run.zig b/src/session_run.zigindex effafb8e..cfb2bbe8 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -45,6 +45,7 @@ const engine_events = @import("engine_events.zig");const harness_policy = @import("harness_policy.zig");const title_mod = @import("title.zig");const repl = @import("repl.zig");+const version_status = @import("version_status.zig");const tui_launch = @import("tui_launch.zig");const shapes = @import("shapes.zig"); // applyUltracodeSteering lives here (#326)const repl_glue = @import("repl_glue.zig");@@ -114,6 +115,8 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agentif (models_buf.items.len != 0) models_buf.appendSlice(", ") catch {};models_buf.appendSlice(mi.name) catch {};}+ repl.g_version_fn = replVersionCb;+ defer repl.g_version_fn = null;try repl.runScripted(gpa, io, environ_map, in, out, &repl_ctx, repl_glue.replTurnCb, repl_glue.replModelCb, repl_glue.replCancelCb, root.provider.model, models_buf.items);// Same stderr footer as `-p`, so evals can score the scripted REPL the// same way. TTY `graff repl` is the TUI and keeps the restore tail clean.@@ -122,6 +125,11 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agentreturn true;}+fn replVersionCb(ctx: ?*anyopaque, gpa: Allocator) ?[]const u8 {+ const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));+ return version_status.commandText(c.io, gpa, main_mod.harness_version) catch null;+}+pub fn runFrontendCommands(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: *provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags, json_mode: bool, cwd: []const u8, final_io: Io) !bool {if (try runReplCommand(gpa, io, environ_map, root, keys, client, in, out, arena, flags)) {try finalizeSession(gpa, final_io, arena, out, root, json_mode);diff --git a/src/tui_launch.zig b/src/tui_launch.zigindex 369661a9..1bdebe1e 100644--- a/src/tui_launch.zig+++ b/src/tui_launch.zig@@ -13,6 +13,7 @@ const pricing = @import("pricing.zig");const providers = @import("providers.zig");const process_runner = @import("process_runner.zig");const repl = @import("repl.zig");+const version_status = @import("version_status.zig");const repl_bash = @import("repl_bash.zig");const repl_glue = @import("repl_glue.zig");const session = @import("session.zig");@@ -149,6 +150,7 @@ pub fn run(.emergency_fn = emergencyCb,.idle_wake_fn = idleWakeCb,.peer_fn = tui_peer.peerCb,+ .version_fn = versionCb,});try tui_session.syncRoot(&convo, root);}@@ -201,6 +203,11 @@ fn idleWakeCb(ctx: ?*anyopaque, buf: []u8) ?[]const u8 {return channel_worker.takeWake(c.io, buf);}+fn versionCb(ctx: ?*anyopaque, gpa: Allocator) ?[]const u8 {+ const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));+ return version_status.commandText(c.io, gpa, @import("build_options").version) catch null;+}+/// Overlay the TUI preview buffer as a repl.StreamBuf so replTurnCb's/// appendBytes publish `stream.len` as bytes arrive. Layout is identical/// (buf + atomic len); a copy would hide the live tail until the turn ends.diff --git a/src/version_status.zig b/src/version_status.zignew file mode 100644index 00000000..5fc07b0c--- /dev/null+++ b/src/version_status.zig@@ -0,0 +1,176 @@+//! Running-binary versus latest-release status shared by `graff update --check`,+//! the startup update notice, and the terminal `/version` commands.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++pub const State = enum { current, older, newer, dev, unable };+pub const Failure = enum { none, fetch, latest_tag };++pub const Check = struct {+ running: []const u8,+ latest: ?[]const u8 = null,+ latest_tag: ?[]const u8 = null,+ state: State,+ failure: Failure = .none,+ order: ?std.math.Order = null,+ clean_release: bool = false,+};++const Version = struct {+ major: u32,+ minor: u32,+ patch: u32,++ fn order(self: Version, other: Version) std.math.Order {+ if (self.major != other.major) return std.math.order(self.major, other.major);+ if (self.minor != other.minor) return std.math.order(self.minor, other.minor);+ return std.math.order(self.patch, other.patch);+ }+};++pub const repo_api = "https://api.github.com/repos/justrach/codegraff/releases/latest";++fn stripV(s: []const u8) []const u8 {+ return if (std.mem.startsWith(u8, s, "v")) s[1..] else s;+}++fn parseVersion(s: []const u8) ?Version {+ var it = std.mem.splitScalar(u8, s, '.');+ const major_s = it.next() orelse return null;+ const minor_s = it.next() orelse return null;+ const patch_s = it.next() orelse return null;+ const major = std.fmt.parseInt(u32, major_s, 10) catch return null;+ const minor = std.fmt.parseInt(u32, minor_s, 10) catch return null;+ const patch_digits = std.mem.indexOfAny(u8, patch_s, "-+") orelse patch_s.len;+ const patch = std.fmt.parseInt(u32, patch_s[0..patch_digits], 10) catch return null;+ return .{ .major = major, .minor = minor, .patch = patch };+}++fn isCleanReleaseVersion(s: []const u8) bool {+ if (s.len == 0) return false;+ var dots: u8 = 0;+ for (s) |c| switch (c) {+ '0'...'9' => {},+ '.' => dots += 1,+ else => return false,+ };+ return dots == 2;+}++/// Pure comparison policy. `latest_tag` is the GitHub release tag, with or+/// without a leading `v`; `running_version` is the build option baked into the+/// process and may carry a git-describe/dev suffix.+pub fn compare(running_version: []const u8, latest_tag: ?[]const u8) Check {+ const running = stripV(running_version);+ const tag = latest_tag orelse return .{ .running = running, .state = .unable, .failure = .fetch };+ const latest = stripV(tag);+ const release = parseVersion(latest) orelse return .{+ .running = running,+ .latest_tag = tag,+ .state = .unable,+ .failure = .latest_tag,+ };+ const current = parseVersion(running);+ const clean = current != null and isCleanReleaseVersion(running);+ const order = if (current) |v| v.order(release) else null;+ if (!clean) return .{+ .running = running,+ .latest = latest,+ .latest_tag = tag,+ .state = .dev,+ .order = order,+ };+ return .{+ .running = running,+ .latest = latest,+ .latest_tag = tag,+ .state = switch (order.?) {+ .lt => .older,+ .eq => .current,+ .gt => .newer,+ },+ .order = order,+ .clean_release = true,+ };+}++fn fetchLatestReleaseTag(io: Io, gpa: Allocator, arena: Allocator, running_version: []const u8) ?[]const u8 {+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ var aw: Io.Writer.Allocating = .init(arena);+ defer aw.deinit();+ const extra = [_]std.http.Header{.{ .name = "Accept", .value = "application/vnd.github+json" }};+ const user_agent = std.fmt.allocPrint(arena, "simple-harness/{s}", .{running_version}) catch return null;+ const res = client.fetch(.{+ .location = .{ .url = repo_api },+ .method = .GET,+ .response_writer = &aw.writer,+ .headers = .{ .user_agent = .{ .override = user_agent } },+ .extra_headers = &extra,+ }) catch return null;+ if (@intFromEnum(res.status) != 200 or aw.writer.buffered().len > 64 * 1024) return null;+ const parsed = std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always }) catch return null;+ if (parsed != .object) return null;+ const tag = parsed.object.get("tag_name") orelse return null;+ return if (tag == .string) tag.string else null;+}++pub fn checkLatest(io: Io, gpa: Allocator, arena: Allocator, running_version: []const u8) Check {+ return compare(running_version, fetchLatestReleaseTag(io, gpa, arena, running_version));+}++/// Human-facing `/version` response. The final note is deliberately present+/// for every state: a process cannot know whether its on-disk executable was+/// replaced after launch, and `/new`/`/resume` only mutate conversation state.+pub fn renderVersion(out: *Io.Writer, check: Check) !void {+ try out.print("graff v{s} (running process)\n", .{check.running});+ switch (check.state) {+ .current => try out.print("latest release: v{s} — current\n", .{check.latest.?}),+ .older => try out.print("latest release: v{s} — update available; run `graff update`\n", .{check.latest.?}),+ .newer => try out.print("latest release: v{s} — running version is newer; not downgrading\n", .{check.latest.?}),+ .dev => if (check.order == .gt)+ try out.print("latest release: v{s} — newer/dev build; no release update needed\n", .{check.latest.?})+ else+ try out.print("latest release: v{s} — dev build; run `graff update` to install the release\n", .{check.latest.?}),+ .unable => try out.writeAll("latest release: unable to check\n"),+ }+ try out.writeAll("If `graff update` installed a new binary, quit and start `graff` again. /new and /resume keep this process and do not reload the executable.\n");+}++pub fn commandText(io: Io, gpa: Allocator, running_version: []const u8) Allocator.Error![]u8 {+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const check = checkLatest(io, gpa, arena_state.allocator(), running_version);+ var aw: Io.Writer.Allocating = .init(gpa);+ errdefer aw.deinit();+ renderVersion(&aw.writer, check) catch return error.OutOfMemory;+ return aw.toOwnedSlice();+}++test "comparison classifies release and dev builds with one policy" {+ try std.testing.expectEqual(State.current, compare("0.0.292", "v0.0.292").state);+ try std.testing.expectEqual(State.older, compare("0.0.291", "v0.0.292").state);+ try std.testing.expectEqual(State.newer, compare("0.0.293", "v0.0.292").state);+ const dev = compare("0.0.293-2-gabc", "v0.0.292");+ try std.testing.expectEqual(State.dev, dev.state);+ try std.testing.expectEqual(std.math.Order.gt, dev.order.?);+}++test "unavailable and unparseable latest checks do not guess" {+ try std.testing.expectEqual(Failure.fetch, compare("0.0.292", null).failure);+ try std.testing.expectEqual(Failure.latest_tag, compare("0.0.292", "latest").failure);+}++test "version response names the running process and reload boundary" {+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ try renderVersion(&aw.writer, compare("0.0.291", "v0.0.292"));+ const text = aw.writer.buffered();+ try std.testing.expect(std.mem.indexOf(u8, text, "v0.0.291 (running process)") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "update available") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "/new and /resume") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "do not reload the executable") != null);+}