Skip to content

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

Python

Fold issue-fix PRs 774, 775, 778-783 into release/v0.0.292

Rached453ccc95ad
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e5927470..fff42f20 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,41 @@ current is part of cutting a release.
## Unreleased
+- `#768`: the Computer Use `node_repl` bridge no longer dies on
+ `createElicitation is unavailable` during a read-only
+ `sky.get_app_state({ disableDiff: true })`. Graff advertises MCP form
+ elicitation, accepts that inspect mid-call, and otherwise returns an
+ actionable fallback that names the desktop `computer` tool. ADR 0036,
+ ADR 0071.
+- `#773`: `/update` checks a GitHub release and, after an explicit human
+ confirm, installs it for the next launch. The live process, conversation,
+ and permissions stay on the original version; `/new` and `/resume` do not
+ activate it. The in-session service pins the tag, verifies SHA256SUMS, and
+ writes atomically — it does not run `install.sh` or restart. `graff update
+ --check` shares the same running/latest comparison. ADR 0085.
+- `#765`: native `codedb context` honors local-only repository policy.
+ Project instructions and `.graff` policy files that forbid transmitting
+ working data, or a per-call `local_only` argument, dispatch
+ `codedb context --local` (on-device BM25/symbol/graph) and never invoke
+ remote advisory rerank. If local-only cannot be guaranteed — including
+ an explicit `--hybrid`/`--semantic` under that policy — the call is
+ refused before spawn. Ordinary reads stay native codedb (ADR 0040).
+ ADR 0084.
+- `#751`: Meta / Muse Spark requests send `tool_choice: auto` only, and
+ fold `reasoning_effort: max` to `xhigh`. The gateway rewrite stays a
+ safety net. ADR 0083.
+- `#750`: the resize-anchor PTY probe waits for a stable frame after a
+ width change instead of asserting on the first (possibly stale) repaint.
+- `#748`: an error-only SSE event is reported as that error, not retried
+ as a truncated gateway body.
+- `#761`: `read_file` optional fields stay out of `required[]` (path only).
+ Null or empty `contains` / null bounds / null `compact` are a whole-file
+ read, so strict tool calling can omit unused mutually exclusive fields.
+ Nonempty `contains` still cannot combine with bounds or `compact`.
+- `#776`: the native Open a folder picker keeps listing candidates while you
+ type, ranks them like `/model` (closest name first), and shows a resolved
+ directory with a trailing `/` (never `//`). Exact-path Go / Open folder
+ and row selection are unchanged.
- Prompt-cache affinity is the git root, or one scratch seed when there is
no `.git`. Eval sandboxes and worktrees can reuse a warm system+tools
prefix instead of paying it on every leaf cwd. An offline test fails if
diff --git a/TUI/bgop.zig b/TUI/bgop.zig
index 21530f87..adc06f0e 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`, `/update`, `!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,15 @@ 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",
+ .update => "update failed to start",
}) catch {};
} else switch (op.kind) {
.compact => applyCompact(self, op),
.bash => applyBash(self, op),
.files => applyFiles(self, op),
+ .version => applyVersion(self, op),
+ .update => applyUpdate(self, op),
}
release(self, op);
self.scroll = 0;
@@ -161,6 +165,26 @@ 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 {};
+ }
+}
+
+fn applyUpdate(self: *Model, op: *Op) void {
+ if (op.text) |text| {
+ self.push(.system, text) catch {};
+ } else if (op.cancelled) {
+ self.push(.system, "update cancelled — the existing install is unchanged") catch {};
+ } else {
+ self.push(.err, "update check unavailable") catch {};
+ }
+}
+
const testing = std.testing;
fn drain(m: *Model) !void {
@@ -284,20 +308,34 @@ 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;
+ }
+ fn update(_: ?*anyopaque, _: std.mem.Allocator, _: []const u8) ?[]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;
+ engine.g_update_fn = Fake.update;
defer {
engine.g_compact_fn = null;
engine.g_bash_fn = null;
engine.g_files_fn = null;
+ engine.g_version_fn = null;
+ engine.g_update_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" },
+ .{ .kind = .update, .message = "update failed to start" },
};
for (cases) |case| {
var m: Model = undefined;
diff --git a/TUI/catalog.zig b/TUI/catalog.zig
index a8dc3d5b..4eab8638 100644
--- a/TUI/catalog.zig
+++ b/TUI/catalog.zig
@@ -16,7 +16,9 @@ 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 = "/update", .desc = "Install a release for the next launch (this session keeps running)" },
.{ .name = "/debug", .desc = "Live observability HUD" },
.{ .name = "/cache", .desc = "Prompt-cache posture and remaining max levers" },
.{ .name = "/rewind", .desc = "Undo the last turn", .aliases = &.{"/undo"} },
@@ -104,6 +106,8 @@ test "filter: slash prefix and alias" {
try std.testing.expect(lookup("/debug") != null);
try std.testing.expect(lookup("/cache") != null);
try std.testing.expect(lookup("/cost") != null);
+ try std.testing.expect(lookup("/version") != null);
+ try std.testing.expect(lookup("/update") != null);
try std.testing.expect(lookup("/tell") != null);
try std.testing.expect(lookup("/peek") != null);
try std.testing.expect(lookup("/not-a-cmd") == null);
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index b9c55b63..1bcee197 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -203,8 +203,12 @@ 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, "/update")) {
+ startUpdate(self, arg);
} else if (std.mem.eql(u8, canon, "/usage")) {
var buf: [512]u8 = undefined;
if (engine.g_hud_fn) |f| {
@@ -449,6 +453,22 @@ pub fn looksLikeImagePath(s: []const u8) bool {
return true;
}
+fn startUpdate(self: *Model, arg: []const u8) void {
+ const action = if (std.mem.eql(u8, arg, "install")) "install" else "check";
+ if (engine.g_update_fn == null) {
+ self.push(.system, "check for a release with /update; install it for the next launch only after you confirm. This session keeps running.") catch {};
+ return;
+ }
+ const cmd = self.alloc.dupe(u8, action) catch {
+ self.push(.err, "update check unavailable") catch {};
+ return;
+ };
+ if (!bgop.start(self, .update, &.{}, cmd, if (std.mem.eql(u8, action, "install")) "installing update" else "checking for update")) {
+ self.alloc.free(cmd);
+ self.push(.system, busy_note) catch {};
+ }
+}
+
fn onOff(v: bool) []const u8 {
return if (v) "on" else "off";
}
diff --git a/TUI/dispatch_command_tests.zig b/TUI/dispatch_command_tests.zig
index 3e3bbb4c..f2b32693 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;
@@ -33,6 +34,37 @@ test "/debug opens the observability overlay" {
try std.testing.expectEqual(app.Overlay.debug, m.overlay);
}
+test "/update checks in the background and does not activate via /new" {
+ engine.g_update_fn = struct {
+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, action: []const u8) ?[]const u8 {
+ return std.fmt.allocPrint(gpa, "running: v0.0.289 (this process)\ninstalled: v0.0.292\nlatest: v0.0.292\n{s}\n/new and /resume keep this process and do not activate the update.\n", .{action}) catch null;
+ }
+ }.f;
+ defer engine.g_update_fn = null;
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "keep talking");
+ _ = applyLine(&m, "/update");
+ try std.testing.expect(m.bg != null);
+ try std.testing.expectEqual(engine.BgOp.Kind.update, m.bg.?.kind);
+ var spins: usize = 0;
+ while (!m.bg.?.done.load(.acquire)) : (spins += 1) {
+ if (spins > 1_000_000) return error.UpdateCheckNeverFinished;
+ 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:") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "do not activate") != null);
+ const before = m.history.items.len;
+ _ = applyLine(&m, "/new");
+ const new_text = m.history.items[m.history.items.len - 1].text;
+ try std.testing.expect(std.mem.indexOf(u8, new_text, "update") == null);
+ try std.testing.expect(std.mem.indexOf(u8, new_text, "activate") == null);
+ try std.testing.expect(m.history.items.len < before + 3);
+}
+
test "/cache opens the same observability overlay" {
var m: Model = undefined;
m.setup(std.testing.allocator);
@@ -41,6 +73,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.zig
index 42fd4ab5..e37b2375 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -71,13 +71,17 @@ 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;
+pub const UpdateFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, action: []const u8) ?[]const u8;
+pub var g_update_fn: ?UpdateFn = null;
-/// A background engine op: `/compact`, `!cmd`, or the @-file list. Same
+/// A background engine op: `/compact`, `/version`, `/update`, `!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, update };
kind: Kind,
gpa: std.mem.Allocator,
@@ -98,7 +102,7 @@ pub const BgOp = struct {
/// compact output — gpa-owned.
compact: CompactOut = .{},
ok: bool = false,
- /// bash / files output — gpa-owned.
+ /// bash / files / version / update output — gpa-owned.
text: ?[]const u8 = null,
};
@@ -113,6 +117,12 @@ 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);
+ },
+ .update => if (g_update_fn) |f| {
+ op.text = f(g_turn_ctx, op.gpa, op.cmd);
+ },
}
op.done.store(true, .release);
}
@@ -152,6 +162,8 @@ 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,
+ update_fn: ?UpdateFn = null,
};
pub var g_turn_fn: ?TurnFn = null;
diff --git a/TUI/overlaypane.zig b/TUI/overlaypane.zig
index 08ab854b..2145ec9b 100644
--- a/TUI/overlaypane.zig
+++ b/TUI/overlaypane.zig
@@ -253,6 +253,8 @@ const help_body =
\\ /effort reasoning depth (type to filter)
\\ /settings model · effort · mode · theme
\\ /usage /cost live token/cost line
+ \\ /version running binary and latest release status
+ \\ /update install a release for the next launch
\\ /debug observability HUD
\\ /cache prompt-cache posture
\\ /plan toggle plan mode
diff --git a/TUI/root.zig b/TUI/root.zig
index 84fa3cfb..3d5981bb 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -41,6 +41,8 @@ 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 UpdateFn = engine.UpdateFn;
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.zig
index d260a119..92d07da3 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -61,6 +61,8 @@ 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_update_fn = opts.update_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/apps/native/README.md b/apps/native/README.md
index 6657dfaa..fb525597 100644
--- a/apps/native/README.md
+++ b/apps/native/README.md
@@ -92,8 +92,9 @@ server only validates a root it is handed) with the active one checked:
- **Open a folder…** (also the caret beside the tab bar's folder chip)
opens a folder picker (`/api/workspaces` walks one level at a time,
- marks git roots, takes a typed or pasted path) and switches to the
- folder you pick.
+ marks git roots, takes a typed or pasted path, ranks fuzzy name matches
+ like `/model`) and switches to the folder you pick. Resolved directories
+ show a trailing `/`.
- **Workspace settings…** edits the active workspace: display name, the
model new tabs spawn with, whether tools are auto-approved
(`graff acp --yolo`), and whether each tab's agent starts the MCP
diff --git a/apps/native/app/api/workspaces/route.ts b/apps/native/app/api/workspaces/route.ts
index fd453cc1..438b9840 100644
--- a/apps/native/app/api/workspaces/route.ts
+++ b/apps/native/app/api/workspaces/route.ts
@@ -2,6 +2,7 @@ import { existsSync, readdirSync, statSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { NextRequest } from "next/server";
+import { displayDirPath, joinDir } from "@/lib/folder-picker";
import { defaultRoot, expandHome } from "@/lib/server-root";
export const runtime = "nodejs";
@@ -35,13 +36,13 @@ export async function GET(req: NextRequest) {
if (entry.name.startsWith(".") || HIDDEN.has(entry.name)) continue;
const full = path.join(target, entry.name);
if (!(entry.isDirectory() || (entry.isSymbolicLink() && isDir(full)))) continue;
- entries.push({ name: entry.name, path: full, git: existsSync(path.join(full, ".git")) });
+ entries.push({ name: entry.name, path: joinDir(target, entry.name), git: existsSync(path.join(full, ".git")) });
}
entries.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
const parent = path.dirname(target);
return Response.json({
ok: true,
- path: target,
+ path: displayDirPath(target),
parent: parent === target ? null : parent,
git: existsSync(path.join(target, ".git")),
home,
diff --git a/apps/native/components/atoms/Switch.tsx b/apps/native/components/atoms/Switch.tsx
index 3c297df1..c847e3c1 100644
--- a/apps/native/components/atoms/Switch.tsx
+++ b/apps/native/components/atoms/Switch.tsx
@@ -11,6 +11,7 @@ export function Switch({
}) {
return (
<button
+ type="button"
role="switch"
aria-checked={checked}
aria-label={label}
diff --git a/apps/native/components/site/WorkspaceDialog.tsx b/apps/native/components/site/WorkspaceDialog.tsx
index 7e5a2f72..e80dbba1 100644
--- a/apps/native/components/site/WorkspaceDialog.tsx
+++ b/apps/native/components/site/WorkspaceDialog.tsx
@@ -1,9 +1,10 @@
"use client";
-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { Switch } from "@/components/atoms/Switch";
import type { PromptModel } from "@/components/primitives/PromptBar";
+import { displayDirPath, rankFolderEntries, sameDir, splitFolderQuery } from "@/lib/folder-picker";
import { browseFolders, fsReveal, type FolderListing } from "@/lib/fs-client";
import { IconCrossSmall, IconFolder } from "@/lib/icons";
import { basename, type Workspace } from "@/lib/workspaces";
@@ -11,8 +12,9 @@ import { basename, type Workspace } from "@/lib/workspaces";
/* ─────────────────────────────────────────────────────────
* WORKSPACE DIALOG
* The two faces of the sidebar's workspace menu. "New workspace" walks
- * the machine's folders one level at a time (or takes a typed path) and
- * hands back the folder graff should run in. "Workspace settings" edits
+ * the machine's folders one level at a time (typed paths stay listed and
+ * fuzzy-ranked like /model) and hands back the folder graff should run in.
+ * "Workspace settings" edits
* how new tabs in a workspace spawn: its name, default model and whether
* tools are auto-approved.
* ───────────────────────────────────────────────────────── */
@@ -94,7 +96,7 @@ function GitBadge() {
function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPick: (path: string) => void; onClose: () => void }) {
const [listing, setListing] = useState<FolderListing | null>(null);
- const [typed, setTyped] = useState(startPath ?? "~");
+ const [typed, setTyped] = useState(displayDirPath(startPath ?? "~"));
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
// Only the newest navigation may land: a slow listing of a big folder
@@ -102,21 +104,24 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi
const seq = useRef(0);
const pickRef = useRef(onPick);
pickRef.current = onPick;
- const go = useCallback(async (target: string, pick = false) => {
+ const go = useCallback(async (target: string, opts: { pick?: boolean; refresh?: boolean } = {}) => {
const n = (seq.current += 1);
- setBusy(true);
- setListing(null);
+ const refresh = opts.refresh === true;
+ if (!refresh) {
+ setBusy(true);
+ setListing(null);
+ }
setError(null);
try {
const next = await browseFolders(target);
if (n !== seq.current) return;
setListing(next);
- setTyped(next.path);
+ if (!refresh) setTyped(displayDirPath(next.path));
setError(null);
- if (pick) pickRef.current(next.path);
+ if (opts.pick) pickRef.current(next.path);
} catch (err) {
if (n !== seq.current) return;
- setError(err instanceof Error ? err.message : String(err));
+ if (!refresh) setError(err instanceof Error ? err.message : String(err));
} finally {
if (n === seq.current) setBusy(false);
}
@@ -126,6 +131,18 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi
return () => { seq.current++; };
}, [go, startPath]);
+ const parsed = splitFolderQuery(typed, listing?.path);
+ const listingPath = listing?.path ?? null;
+ useEffect(() => {
+ if (!listingPath || !parsed.browse) return;
+ if (sameDir(parsed.browse, listingPath)) return;
+ void go(parsed.browse, { refresh: true });
+ }, [go, listingPath, parsed.browse]);
+ const shown = useMemo(
+ () => (listing ? rankFolderEntries(listing.entries, parsed.needle) : []),
+ [listing, parsed.needle],
+ );
+
const crumbs = listing ? listing.path.split("/").filter(Boolean) : [];
const crumbPath = (i: number) => `/${crumbs.slice(0, i + 1).join("/")}`;
const home = listing?.home;
@@ -146,7 +163,7 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi
</span>
<input
value={typed}
- onChange={(event) => { seq.current++; setTyped(event.target.value); setBusy(false); setError(null); setListing(null); }}
+ onChange={(event) => { setTyped(event.target.value); setError(null); }}
spellCheck={false}
autoFocus
aria-label="Folder path"
@@ -161,11 +178,11 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi
</button>
</form>
<div className="flex items-center gap-1.5 text-[11.5px] text-ink-3">
- <Chip onClick={() => void go("~")} active={listing?.path === home}>
+ <Chip onClick={() => void go("~")} active={sameDir(listing?.path, home)}>
Home
</Chip>
{repo && (
- <Chip onClick={() => void go(repo)} active={listing?.path === repo}>
+ <Chip onClick={() => void go(repo)} active={sameDir(listing?.path, repo)}>
{basename(repo)}
</Chip>
)}
@@ -212,7 +229,7 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi
<span>Up one level</span>
</button>
)}
- {listing.entries.map((entry) => (
+ {shown.map((entry) => (
<div
key={entry.path}
className="group flex h-8 items-center gap-2 rounded-[7px] px-2 transition-colors duration-100 hover:bg-hover"
@@ -238,14 +255,16 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi
</button>
</div>
))}
- {listing.entries.length === 0 && <p className="px-2 py-2 text-[12.5px] text-ink-3">No folders here</p>}
+ {shown.length === 0 && (
+ <p className="px-2 py-2 text-[12.5px] text-ink-3">{parsed.needle ? "No folders match this name." : "No folders here"}</p>
+ )}
</div>
)}
</div>
<div className="flex shrink-0 items-center gap-2 border-t border-line px-4 py-3">
- <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-ink-3" title={listing?.path}>
- {listing?.path ?? ""}
+ <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-ink-3" title={listing ? displayDirPath(listing.path) : ""}>
+ {listing ? displayDirPath(listing.path) : ""}
</span>
<button
type="button"
@@ -257,7 +276,7 @@ function FolderPicker({ startPath, onPick, onClose }: { startPath?: string; onPi
<button
type="button"
disabled={!typed.trim() || busy}
- onClick={() => void go(typed, true)}
+ onClick={() => void go(typed, { pick: true })}
className="h-8 rounded-full bg-ink px-3.5 text-[12.5px] font-medium text-canvas transition-opacity hover:opacity-90 disabled:opacity-50"
>
Open folder
diff --git a/apps/native/electron/project-recovery-visual.cjs b/apps/native/electron/project-recovery-visual.cjs
index 8225f0a4..4b8d6f94 100644
--- a/apps/native/electron/project-recovery-visual.cjs
+++ b/apps/native/electron/project-recovery-visual.cjs
@@ -20,9 +20,11 @@ async function runProjectRecovery({ win, origin, output }) {
r.requests.push({url:String(input),body:options?.body});
if(url.pathname==='/api/workspaces') {
const folder=url.searchParams.get('path');
- const listing={path:folder,parent:'/demo',home:'/demo',default:'/demo/field-notes',git:false,entries:[{name:'child',path:folder+'/child',git:false}]};
- if(folder==='/demo/missing') return json({error:'Folder does not exist'},404);
- if(folder==='/demo/slow') await new Promise(resolve=>r.holds.folder=resolve);
+ const root=String(folder||'').replace(/\/+$/,'')||'/';
+ const join=(name)=>root==='/'?'/'+name:root+'/'+name;
+ const listing={path:root==='/'?'/':root+'/',parent:'/demo',home:'/demo',default:'/demo/field-notes',git:false,entries:[{name:'alpha',path:join('alpha'),git:false},{name:'codegraff',path:join('codegraff'),git:false},{name:'child',path:join('child'),git:false}]};
+ if(root==='/demo/missing') return json({error:'Folder does not exist'},404);
+ if(root==='/demo/slow') await new Promise(resolve=>r.holds.folder=resolve);
return json(listing);
}
if(url.pathname==='/api/sessions'&&url.searchParams.has('name')) {
@@ -100,6 +102,10 @@ async function runProjectRecovery({ win, origin, output }) {
await js(`document.querySelector('button[aria-label="Open folder…"]').click()`);
await wait(`!!document.querySelector('[role="dialog"] button[title$="/child"]')`);
+ assert.ok(await js(`document.querySelector('[aria-label="Folder path"]').value.endsWith('/')`),'Resolved folder paths show a trailing slash');
+ await input('Folder path','codeg');
+ await wait(`!!document.querySelector('[role="dialog"] button[title$="/codegraff"]')`);
+ assert.equal(await js(`document.querySelector('[role="dialog"] .group button[title]')?.title?.endsWith('/codegraff')`),true,'Closest fuzzy match is listed first');
await input('Folder path','/demo/missing');
await click('[role="dialog"] button','Open folder');
await wait(`!!document.querySelector('[role="dialog"] [role="alert"]')`);
diff --git a/apps/native/electron/projects-visual.cjs b/apps/native/electron/projects-visual.cjs
index 653d8130..37cb8bae 100644
--- a/apps/native/electron/projects-visual.cjs
+++ b/apps/native/electron/projects-visual.cjs
@@ -4,7 +4,34 @@ const path = require('node:path');
async function runProjectVisuals({ win, origin, output }) {
const wc = win.webContents, js = code => wc.executeJavaScript(code);
const wait = async code => { for (let i = 0; i < 100; i++) { if (await js(code)) return; await new Promise(r => setTimeout(r, 50)); } throw Error(`Project check timed out: ${code}`); };
+ const openSettings = async () => {
+ await js(`document.querySelector('[data-workspace-trigger]').click()`);
+ await wait(`!!document.querySelector('[data-workspace-menu]')`);
+ await js(`Array.from(document.querySelectorAll('[data-workspace-menu] button')).find(b=>b.textContent.includes('Project settings')).click()`);
+ await wait(`!!document.querySelector('[role="dialog"]')`);
+ };
await js(`window.projectRequests=[];const projectFetch=window.fetch;window.fetch=(input,options)=>{window.projectRequests.push(String(input));return projectFetch(input,options);};true`);
+ await openSettings();
+ const originalSettings = await js(`(()=>{const d=document.querySelector('[role="dialog"]');return {name:d.querySelector('input').value,yolo:d.querySelector('[aria-label="Auto-approve tools"]').getAttribute('aria-checked'),mcp:d.querySelector('[aria-label="Start MCP servers"]').getAttribute('aria-checked')}})()`);
+ await js(`(()=>{const d=document.querySelector('[role="dialog"]'),e=d.querySelector('input');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,'cancel-probe');e.dispatchEvent(new Event('input',{bubbles:true}));d.querySelector('[aria-label="Auto-approve tools"]').click()})()`);
+ assert.ok(await js(`!!document.querySelector('[role="dialog"]')`), 'Auto-approve switch keeps Project Settings open');
+ assert.notEqual(await js(`document.querySelector('[aria-label="Auto-approve tools"]').getAttribute('aria-checked')`), originalSettings.yolo);
+ await js(`Array.from(document.querySelectorAll('[role="dialog"] button')).find(b=>b.textContent==='Cancel').click()`);
+ await wait(`!document.querySelector('[role="dialog"]')`);
+ await openSettings();
+ assert.deepEqual(await js(`(()=>{const d=document.querySelector('[role="dialog"]');return {name:d.querySelector('input').value,yolo:d.querySelector('[aria-label="Auto-approve tools"]').getAttribute('aria-checked')}})()`), { name: originalSettings.name, yolo: originalSettings.yolo }, 'Cancel discards the settings draft');
+ await js(`(()=>{const d=document.querySelector('[role="dialog"]'),e=d.querySelector('input');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,'settings-save-probe');e.dispatchEvent(new Event('input',{bubbles:true}));d.querySelector('[aria-label="Auto-approve tools"]').click()})()`);
+ assert.ok(await js(`!!document.querySelector('[role="dialog"]')`), 'Auto-approve switch still keeps the dialog open before Save');
+ await js(`document.querySelector('[aria-label="Start MCP servers"]').click()`);
+ assert.ok(await js(`!!document.querySelector('[role="dialog"]')`), 'MCP switch keeps Project Settings open');
+ await js(`Array.from(document.querySelectorAll('[role="dialog"] button')).find(b=>b.textContent==='Save').click()`);
+ await wait(`!document.querySelector('[role="dialog"]')`);
+ await openSettings();
+ assert.deepEqual(await js(`(()=>{const d=document.querySelector('[role="dialog"]');return {name:d.querySelector('input').value,yolo:d.querySelector('[aria-label="Auto-approve tools"]').getAttribute('aria-checked'),mcp:d.querySelector('[aria-label="Start MCP servers"]').getAttribute('aria-checked')}})()`), { name: 'settings-save-probe', yolo: originalSettings.yolo === 'true' ? 'false' : 'true', mcp: originalSettings.mcp === 'true' ? 'false' : 'true' }, 'Save persists the complete settings draft');
+ await js(`(()=>{const d=document.querySelector('[role="dialog"]'),e=d.querySelector('input');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,${JSON.stringify(originalSettings.name)});e.dispatchEvent(new Event('input',{bubbles:true}));d.querySelector('[aria-label="Auto-approve tools"]').click()})()`);
+ await js(`document.querySelector('[aria-label="Start MCP servers"]').click()`);
+ await js(`Array.from(document.querySelectorAll('[role="dialog"] button')).find(b=>b.textContent==='Save').click()`);
+ await wait(`!document.querySelector('[role="dialog"]')`);
await js(`document.querySelector('button[aria-label="Projects"]').click()`);
await wait(`!!document.querySelector('[aria-label="Search projects"]')`);
await js(`(()=>{const e=document.querySelector('[aria-label="Search projects"]');Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,'folder-42');e.dispatchEvent(new Event('input',{bubbles:true}));})()`);
diff --git a/apps/native/lib/folder-picker.test.ts b/apps/native/lib/folder-picker.test.ts
new file mode 100644
index 00000000..a35b39bb
--- /dev/null
+++ b/apps/native/lib/folder-picker.test.ts
@@ -0,0 +1,76 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { displayDirPath, joinDir, rankFolderEntries, sameDir, splitFolderQuery } from "./folder-picker.ts";
+
+describe("displayDirPath", () => {
+ it("adds a single trailing separator and leaves root alone", () => {
+ assert.equal(displayDirPath("/Users/example"), "/Users/example/");
+ assert.equal(displayDirPath("/Users/example/"), "/Users/example/");
+ assert.equal(displayDirPath("/"), "/");
+ assert.equal(displayDirPath("~"), "~/");
+ });
+});
+
+describe("joinDir / sameDir", () => {
+ it("never emits a double slash", () => {
+ assert.equal(joinDir("/Users/example", "src"), "/Users/example/src");
+ assert.equal(joinDir("/Users/example/", "src"), "/Users/example/src");
+ assert.equal(joinDir("/", "Users"), "/Users");
+ assert.equal(joinDir("/", "/Users"), "/Users");
+ });
+ it("treats a trailing slash as the same directory", () => {
+ assert.equal(sameDir("/Users/example", "/Users/example/"), true);
+ assert.equal(sameDir("/", "/"), true);
+ assert.equal(sameDir("/a", "/b"), false);
+ assert.equal(sameDir("/a", null), false);
+ });
+});
+
+describe("splitFolderQuery", () => {
+ it("keeps a resolved current path as browse, not parent + name", () => {
+ assert.deepEqual(splitFolderQuery("/Users/example", "/Users/example"), {
+ browse: "/Users/example",
+ needle: "",
+ });
+ assert.deepEqual(splitFolderQuery("/Users/example/", "/Users/example"), {
+ browse: "/Users/example",
+ needle: "",
+ });
+ });
+ it("splits a partial child off the parent directory", () => {
+ assert.deepEqual(splitFolderQuery("/Users/example/cod", "/Users/example"), {
+ browse: "/Users/example/",
+ needle: "cod",
+ });
+ assert.deepEqual(splitFolderQuery("codegra", "/Users/example"), {
+ browse: null,
+ needle: "codegra",
+ });
+ assert.deepEqual(splitFolderQuery("~/proj"), { browse: "~/", needle: "proj" });
+ });
+});
+
+describe("rankFolderEntries", () => {
+ const entries = [
+ { name: "README-notes", path: "/demo/README-notes" },
+ { name: "codegraff", path: "/demo/codegraff" },
+ { name: "codex-scratch", path: "/demo/codex-scratch" },
+ { name: "lib", path: "/demo/lib" },
+ ];
+ it("keeps directory order when the needle is empty", () => {
+ assert.deepEqual(rankFolderEntries(entries, "").map((e) => e.name), [
+ "README-notes",
+ "codegraff",
+ "codex-scratch",
+ "lib",
+ ]);
+ });
+ it("ranks the closest folder name first, like /model", () => {
+ assert.deepEqual(rankFolderEntries(entries, "code").map((e) => e.name), [
+ "codegraff",
+ "codex-scratch",
+ ]);
+ assert.deepEqual(rankFolderEntries(entries, "lib").map((e) => e.name), ["lib"]);
+ assert.deepEqual(rankFolderEntries(entries, "zzz"), []);
+ });
+});
diff --git a/apps/native/lib/folder-picker.ts b/apps/native/lib/folder-picker.ts
new file mode 100644
index 00000000..2e93f1a5
--- /dev/null
+++ b/apps/native/lib/folder-picker.ts
@@ -0,0 +1,73 @@
+/** Path display and query-aware ranking for the Open a folder picker.
+ * Identity paths stay slash-stripped (`workspaces.normalizePath`); the field
+ * and footer show a directory with a trailing `/` so the next segment is
+ * obvious. Ranking is the `/model` fuzzy score. */
+
+import { fuzzyScore } from "./fuzzy.ts";
+
+/** POSIX directory form for display: `/Users/me` → `/Users/me/`; `/` stays `/`. */
+export function displayDirPath(p: string): string {
+ const n = p.replace(/\\/g, "/");
+ if (!n) return n;
+ if (n === "/") return "/";
+ return n.endsWith("/") ? n : `${n}/`;
+}
+
+/** Compare two directory strings, ignoring a trailing separator. */
+export function sameDir(a: string | null | undefined, b: string | null | undefined): boolean {
+ if (a == null || b == null) return false;
+ return normalizeDir(a) === normalizeDir(b);
+}
+
+export function normalizeDir(p: string): string {
+ const n = p.replace(/\\/g, "/").replace(/\/+$/, "");
+ return n.length > 0 ? n : "/";
+}
+
+/** Join a parent directory and a child name without emitting `//`. */
+export function joinDir(parent: string, name: string): string {
+ const base = parent.replace(/\\/g, "/").replace(/\/+$/, "");
+ const child = name.replace(/^\/+/, "");
+ if (!base || base === "/") return `/${child}`;
+ return `${base}/${child}`;
+}
+
+export type FolderQuery = {
+ /** Directory to list, or `null` when the field is a bare name. */
+ browse: string | null;
+ /** Last path segment — the fuzzy needle. */
+ needle: string;
+};
+
+/** Split a typed path into the directory to list and the name to rank.
+ * `current` is the listing already on screen: typing that path without a
+ * trailing slash is still "this folder", not parent + last segment. */
+export function splitFolderQuery(typed: string, current?: string | null): FolderQuery {
+ const t = typed.trim();
+ if (!t) return { browse: null, needle: "" };
+ if (current && sameDir(t, current)) return { browse: current, needle: "" };
+ if (t === "~") return { browse: "~", needle: "" };
+ if (t.endsWith("/") || t.endsWith("\\")) return { browse: t, needle: "" };
+ const slash = Math.max(t.lastIndexOf("/"), t.lastIndexOf("\\"));
+ if (slash < 0) return { browse: null, needle: t };
+ const browse = t.slice(0, slash + 1);
+ return { browse: browse || "/", needle: t.slice(slash + 1) };
+}
+
+export type RankableFolder = { name: string; path: string };
+
+/** Keep alpha order when the needle is empty; otherwise closest `/model`
+ * match first. Non-matches drop out. */
+export function rankFolderEntries<T extends RankableFolder>(entries: readonly T[], needle: string): T[] {
+ const q = needle.trim();
+ if (!q) return [...entries];
+ const scored: { item: T; score: number; idx: number }[] = [];
+ for (let i = 0; i < entries.length; i += 1) {
+ const item = entries[i];
+ const score = fuzzyScore(item.name, q) ?? fuzzyScore(item.path, q);
+ if (score == null) continue;
+ scored.push({ item, score, idx: i });
+ }
+ scored.sort((a, b) => b.score - a.score || a.idx - b.idx);
+ return scored.map((row) => row.item);
+}
diff --git a/apps/native/lib/fuzzy.test.ts b/apps/native/lib/fuzzy.test.ts
new file mode 100644
index 00000000..37736bc7
--- /dev/null
+++ b/apps/native/lib/fuzzy.test.ts
@@ -0,0 +1,31 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { fuzzyScore, fuzzySubseq } from "./fuzzy.ts";
+
+describe("fuzzySubseq", () => {
+ it("matches across punctuation gaps", () => {
+ assert.equal(fuzzySubseq("gpt-5.5", "gpt5.5"), true);
+ assert.equal(fuzzySubseq("claude-opus-4-8", "opus"), true);
+ assert.equal(fuzzySubseq("anything", ""), true);
+ assert.equal(fuzzySubseq("gpt-5.5", "xyz"), false);
+ assert.equal(fuzzySubseq("abc", "abcd"), false);
+ });
+});
+
+describe("fuzzyScore", () => {
+ it("ranks basename prefix above substring above subsequence", () => {
+ const demo = fuzzyScore("sdk/py/demo.py", "dem");
+ const readme = fuzzyScore("README.md", "dem");
+ assert.ok(demo != null && readme != null && demo > readme);
+ const sub = fuzzyScore(".graff/traces/run.jsonl", "trace");
+ const seq = fuzzyScore("t-r-a-c-e.txt", "trace");
+ assert.ok(sub != null && seq != null && sub > seq);
+ const basePre = fuzzyScore("src/main.zig", "main");
+ const mid = fuzzyScore("domain.zig", "main");
+ assert.ok(basePre != null && mid != null && basePre > mid);
+ assert.ok((fuzzyScore("sdk/ts/harness.ts", "sdk") ?? 0) >= 300_000 - 200);
+ assert.ok((fuzzyScore("gpt-5.6-sol", "5.6 sol") ?? 0) > (fuzzyScore("gpt-5.6", "5.6") ?? 0));
+ assert.equal(fuzzyScore("abc", "xyz"), null);
+ assert.equal(fuzzyScore("abc", ""), 0);
+ });
+});
diff --git a/apps/native/lib/fuzzy.ts b/apps/native/lib/fuzzy.ts
new file mode 100644
index 00000000..7dcd42c4
--- /dev/null
+++ b/apps/native/lib/fuzzy.ts
@@ -0,0 +1,64 @@
+/** Same ranking the line-REPL `/model` picker uses (`src/pickers.zig`):
+ * prefix beats substring beats subsequence; separators fold so "5.6 sol"
+ * hits `gpt-5.6-sol`. Higher is better; `null` is no match. */
+
+const SEPS = new Set(["-", "_", " ", ".", "/"]);
+
+function foldSeps(s: string): string {
+ let out = "";
+ for (const ch of s) {
+ if (SEPS.has(ch)) continue;
+ out += ch.toLowerCase();
+ }
+ return out;
+}
+
+function indexOfIgnoreCase(hay: string, needle: string): number {
+ if (needle.length === 0) return 0;
+ if (needle.length > hay.length) return -1;
+ const h = hay.toLowerCase();
+ const n = needle.toLowerCase();
+ return h.indexOf(n);
+}
+
+function startsWithIgnoreCase(hay: string, needle: string): boolean {
+ return hay.length >= needle.length && hay.slice(0, needle.length).toLowerCase() === needle.toLowerCase();
+}
+
+/** fzf-style: every char of `needle` appears in `hay` in order, gaps allowed. */
+export function fuzzySubseq(hay: string, needle: string): boolean {
+ if (needle.length === 0) return true;
+ const h = hay.toLowerCase();
+ const n = needle.toLowerCase();
+ let ni = 0;
+ for (let i = 0; i < h.length; i += 1) {
+ if (h[i] === n[ni]) {
+ ni += 1;
+ if (ni === n.length) return true;
+ }
+ }
+ return false;
+}
+
+function scoreFolded(hay: string, needle: string): number | null {
+ if (needle.length === 0) return 0;
+ if (needle.length > hay.length) return null;
+ const lenPen = Math.min(hay.length, 200);
+ const slash = hay.lastIndexOf("/");
+ const base = slash >= 0 ? slash + 1 : 0;
+ if (startsWithIgnoreCase(hay.slice(base), needle) || startsWithIgnoreCase(hay, needle)) {
+ return 300_000 - lenPen;
+ }
+ const pos = indexOfIgnoreCase(hay, needle);
+ if (pos >= 0) return 200_000 - Math.min(pos, 1000) * 10 - lenPen;
+ if (fuzzySubseq(hay, needle)) return 100_000 - lenPen;
+ return null;
+}
+
+/** Rank a fuzzy match. Prefix > substring > subsequence. Empty needle is 0. */
+export function fuzzyScore(hay: string, needle: string): number | null {
+ if (needle.length === 0) return 0;
+ const direct = scoreFolded(hay, needle);
+ if (direct != null) return direct;
+ return scoreFolded(foldSeps(hay), foldSeps(needle));
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index 46312451..7fcfc66f 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -10,7 +10,7 @@
"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000",
"mock-serve": "node scripts/mock-serve.mjs",
"lint": "next lint",
- "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts",
+ "test": "node --experimental-strip-types --test lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts",
"electron:build": "bash electron/build.sh",
"test:electron": "bun test electron/policy.test.cjs",
"test:desktop": "bun test lib ./electron/*.test.cjs",
diff --git a/build.zig b/build.zig
index 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/docs/adr/0083-meta-tool-choice-is-auto-only.md b/docs/adr/0083-meta-tool-choice-is-auto-only.md
new file mode 100644
index 00000000..da74f31e
--- /dev/null
+++ b/docs/adr/0083-meta-tool-choice-is-auto-only.md
@@ -0,0 +1,24 @@
+# 0083. Meta tool_choice is auto-only at the source
+
+Status: accepted 2026-09-07
+
+## Context
+
+`muse-spark-1.3` 400'd on any non-`auto` `tool_choice`. Meta's error: only
+`"auto"` is supported; `"none"`, `"required"`, and named choices are not.
+The gateway already translates those: `none` drops tools+choice,
+`required`/named become `auto`. A silent rewrite means the harness asked
+for a forced call and got a maybe. `reasoning_effort: max` has the same
+shape (1.3 non-contributor; gateway folds to `xhigh`).
+
+## Decision
+
+Normalise at the source for Meta and any `muse-spark*` model, including
+when the seat is the Codegraff gateway. `tool_choice` is always `auto`.
+`max`/`ultra` effort becomes `xhigh`. The gateway stays a safety net for
+unknown seats. Do not send `required` and hope the gateway rewrites it.
+
+## Consequences
+
+A forced-tool turn on Muse Spark is a request, not a guarantee — the
+model may answer in prose. Revisit if Meta adds `required`. #751.
diff --git a/docs/adr/0084-codedb-context-honors-local-only.md b/docs/adr/0084-codedb-context-honors-local-only.md
new file mode 100644
index 00000000..88e902a2
--- /dev/null
+++ b/docs/adr/0084-codedb-context-honors-local-only.md
@@ -0,0 +1,31 @@
+# 0084. Native codedb context honors local-only retrieval
+
+Status: accepted 2026-09-07
+
+## Context
+
+codedb's default `context` composer may send relative paths and bounded
+snippets to a hosted embeddings lane for advisory rerank. The tool result
+then reports retrieval-privacy metadata and a remote-retention policy
+(`none_by_codedb_policy`). #765: that is not equivalent to no network
+egress. Project instructions that prohibit transmitting working data had
+no effect, and the native schema had no per-call local-only control.
+
+## Decision
+
+When repository policy (AGENTS.md / HARNESS.md / CLAUDE.md phrases, or
+`.graff/policy.json` / `.graff/retrieval-policy`) or `local_only=true`
+requires on-device retrieval, native `codedb context` dispatches
+`codedb context --local` and never hybrid/semantic rerank. If that
+boundary cannot be guaranteed (caller asked for `--hybrid`/`--semantic`
+under the policy), refuse before spawn and explain. Do not redirect
+ordinary reads to codedb-pro (ADR 0040).
+
+## Consequences
+
+- Repos that forbid transmitting working data stay on local BM25/symbol/graph.
+- Callers can enforce the boundary with `local_only` even when policy files
+ are silent.
+- Hybrid remains the default where policy does not require local-only.
+- Revisit only if codedb grows a stronger in-process local composer that
+ graff should prefer over `--local`.
diff --git a/docs/adr/0085-in-session-update-is-next-launch.md b/docs/adr/0085-in-session-update-is-next-launch.md
new file mode 100644
index 00000000..7c1eb450
--- /dev/null
+++ b/docs/adr/0085-in-session-update-is-next-launch.md
@@ -0,0 +1,33 @@
+# 0085. In-session `/update` installs for the next launch
+
+Status: accepted 2026-09-07
+
+## Context
+
+Updating from a live terminal session must not require a second terminal, and
+must not interrupt the conversation. Automatic restart and launch-flag replay
+(#770) would activate new code in a way that looks like `/new` or `/resume`
+had switched binaries. The existing `graff update` CLI is process-fatal and
+delegates to `curl | install.sh`, which inherits a TTY and is not safe to
+call from the pager.
+
+## Decision
+
+`/update` (line REPL and TUI) uses a nonfatal in-process service: pin a
+GitHub release tag, download that tag's tarball and `SHA256SUMS`, verify,
+and atomically replace the resolved user install. Installation requires an
+explicit human confirm in this process (TTY picker or `/update install`
+after a human `/update` check). Model output, tool calls, saved
+conversations, and yolo/always-approve are not authorization.
+
+The live process, conversation, and permissions stay on the original binary.
+`/new` and `/resume` only change conversation state. A later normal launch
+uses the installed executable. Package-managed and zig-out paths are
+explained, not overwritten. Fail closed if verification is missing.
+
+## Consequences
+
+Activating new code without a restart stays out of scope (same boundary as
+ADR 0079). `graff update --check` shares the running/latest comparison in
+`version_status.zig`. Isolated fixtures cover install, already-installed,
+offline/malformed, verify, permission, cancel, and concurrent requests.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 11404220..dc6631f9 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -92,6 +92,9 @@ record only when you need the evidence or the edge cases.
| [0079](0079-desktop-updates-are-signed-and-user-restarted.md) | Signed desktop updates download in the background and install only on explicit restart; one process owns each profile. |
| [0080](0080-desktop-projects-are-folders.md) | Desktop projects are folders; preferences survive local UI origin changes, and new chats inherit the focused project's folder. |
| [0081](0081-desktop-split-focus-and-layout.md) | Split positions remain stable as focus changes; shared controls and draggable separators keep navigation usable. |
+| [0083](0083-meta-tool-choice-is-auto-only.md) | Meta / Muse Spark `tool_choice` is `auto` at the source; `max` effort folds to `xhigh` (#751). |
+| [0084](0084-codedb-context-honors-local-only.md) | Native `codedb context` is `--local` (or refused before spawn) when repository policy or `local_only` forbids transmitting working data; no-retention hybrid is not no egress. |
+| [0085](0085-in-session-update-is-next-launch.md) | `/update` installs a verified release for the next launch; this session keeps its original binary. |
## When to write one
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 20222900..ac1c6302 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 2009,
+ "test_count_baseline": 2063,
"test_count_slack": 25,
"required_invariants": [
{
@@ -67,6 +67,11 @@
"id": "cache-affinity-scratch",
"test": "affinity: two scratch sandboxes share one project cache id",
"why": "289 remasure: hashing the leaf cwd minted a unique xAI partition per eval sandbox and paid the system+tools prefix at $2/M."
+ },
+ {
+ "id": "sse-error-not-truncated",
+ "test": "#748: error-only OpenAI SSE is an error envelope, not a missing stream",
+ "why": "#748: an explicit streamed error was retried as a truncated gateway body."
}
],
"docs_only_paths": [
diff --git a/scripts/test-tui-resize-anchor.py b/scripts/test-tui-resize-anchor.py
index a73e834f..c3e95db8 100644
--- a/scripts/test-tui-resize-anchor.py
+++ b/scripts/test-tui-resize-anchor.py
@@ -139,6 +139,24 @@ def frame_at(fd, rows, cols, settle=1.2):
return parse(drain(fd, settle))
+def stable_frame(fd, rows, cols, budget=1.5):
+ # #750: a width change can emit two full frames (old wrap, then anchored).
+ # The first parse is a real frame — it just is not the settled one — so
+ # the parallel suite saw a marker jump. Wait for two identical parses
+ # inside the original settle budget. Do not relax DRIFT.
+ resize(fd, rows, cols)
+ last = None
+ deadline = time.time() + budget
+ while time.time() < deadline:
+ now = parse(drain(fd, 0.12))
+ if now is None:
+ continue
+ if last is not None and now == last:
+ return now
+ last = now
+ return last
+
+
def reread(fd):
"""A full frame at the current width, via a HEIGHT-only jiggle.
@@ -190,7 +208,7 @@ def run():
# Every step must CHANGE the height: an identical winsize is not a
# resize, so no full repaint follows it and there is nothing to read.
for h in (18, 34, 22, ROWS):
- rows = frame_at(fd, h, COLS)
+ rows = stable_frame(fd, h, COLS)
if rows is None:
return f"no full repaint at height {h}"
if find(rows, TAIL) is None:
@@ -216,14 +234,18 @@ def run():
# --- the width sweep --------------------------------------------------
seen = [(COLS, top)]
for w in (76, 58, 44, 92, COLS):
- rows = frame_at(fd, ROWS, w)
+ rows = stable_frame(fd, ROWS, w)
if rows is None:
return f"no full repaint at width {w}"
at = find(rows, MARK)
if at is None:
return f"width {w} scrolled {MARK} off screen (anchor lost); seen={seen}"
if abs(at - top) > DRIFT:
- return f"width {w} moved {MARK} from row {top} to {at}; seen={seen}"
+ again = stable_frame(fd, ROWS, w, budget=1.8)
+ at2 = find(again, MARK) if again else None
+ if at2 is None or abs(at2 - top) > DRIFT:
+ return f"width {w} moved {MARK} from row {top} to {at2 if at2 is not None else at}; seen={seen}"
+ at = at2
seen.append((w, at))
print(f" widths/rows: {seen}")
return None
diff --git a/src/agent_gateway_retry.zig b/src/agent_gateway_retry.zig
index 71eb32ae..f6892952 100644
--- a/src/agent_gateway_retry.zig
+++ b/src/agent_gateway_retry.zig
@@ -113,10 +113,22 @@ pub fn isShortGatewayFlake(etype: []const u8, code: ?[]const u8, msg: []const u8
return generic and std.mem.trim(u8, msg, " \t\r\n").len == 0;
}
+/// An explicit streamed error (not a truncated JSON body). Must not be
+/// classified as a gateway flake — invalid_request is deterministic (#748).
+pub fn sseLooksLikeError(body: []const u8) bool {
+ if (std.mem.indexOf(u8, body, "event: error") != null) return true;
+ if (std.mem.indexOf(u8, body, "event:error") != null) return true;
+ if (std.mem.indexOf(u8, body, "\"error\"") != null and
+ std.mem.indexOf(u8, body, "\"choices\"") == null)
+ return true;
+ return false;
+}
+
/// Unparseable body that is keep-alive comments or a tiny truncated
/// payload (the 110-byte follow-up). Bounded. Real JSON error envelopes
/// do not reach this — they go through `afterServerErrorOrParseReject`.
pub fn retryDegenerateBody(self: *Agent, body: []const u8, retries: *usize) !bool {
+ if (sseLooksLikeError(body)) return false;
const tiny = body.len > 0 and body.len <= 256;
if (!policy.sseKeepAliveOnly(body) and !tiny) return false;
if (retries.* >= max_short_flake_retries) return false;
@@ -195,3 +207,11 @@ test "isShortGatewayFlake: internal/empty api_error retry; invalid/auth/quota do
try std.testing.expect(isShortGatewayFlake("api_error", null, "Malformed JSON in request body"));
try std.testing.expect(!isShortGatewayFlake("invalid_request_error", null, "invalid prompt"));
}
+
+test "#748: error-only SSE is not a truncated gateway body" {
+ const err_sse = "event: error\ndata: {\"error\":{\"type\":\"invalid_request_error\",\"message\":\"bad\"}}\n";
+ try std.testing.expect(sseLooksLikeError(err_sse));
+ try std.testing.expect(sseLooksLikeError("data: {\"error\":{\"message\":\"only auto\"}}\n"));
+ try std.testing.expect(!sseLooksLikeError(": OPENROUTER PROCESSING\n"));
+ try std.testing.expect(!sseLooksLikeError("data: {\"choices\":[{\"delta\":{}}]}\n"));
+}
diff --git a/src/agent_request_body.zig b/src/agent_request_body.zig
index 697df30e..70e69f81 100644
--- a/src/agent_request_body.zig
+++ b/src/agent_request_body.zig
@@ -137,9 +137,9 @@ pub fn buildBody(self: *Agent, tools_in: ?[]const u8, force_tool: bool, stream:
try writeKimiTools(&s, self.scratchAlloc(), t)
else
try serde.writeOpenAITools(&s, self.scratchAlloc(), t);
- if (force_tool) {
- try s.objectField("tool_choice");
- try s.write("required");
+ if (force_tool or @import("meta_wire.zig").restricted(self.provider.id, self.provider.model)) {
+ try s.objectField("tool_choice"); // #751: Meta is auto-only
+ try s.write(@import("meta_wire.zig").toolChoice(force_tool, self.provider.id, self.provider.model));
}
}
try s.objectField("messages");
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 2c127a95..b9533c06 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -465,6 +465,18 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
const payload = ssePayload(raw_line) orelse continue;
const v = std.json.parseFromSliceLeaky(Value, self.scratchAlloc(), payload, .{ .allocate = .alloc_always }) catch continue; // #124: per-event parse tree is transient (deltas are appendSlice'd into session accumulators)
if (v != .object) continue;
+ // Error-only SSE (`event: error` / `data: {"error":…}`) has no
+ // choices chunk. Hand the envelope back so request() reports it
+ // instead of falling through to the truncated-body retry (#748).
+ if (v.object.get("error")) |err| if (err != .null) {
+ var env: std.json.ObjectMap = .empty;
+ try env.put(result_arena, "type", .{ .string = "error" });
+ try env.put(result_arena, "error", try util.dupeJsonValue(result_arena, err));
+ return env;
+ };
+ if (v.object.get("type")) |t| if (t == .string and std.mem.eql(u8, t.string, "error")) {
+ return (try util.dupeJsonValue(result_arena, v)).object;
+ };
// The final usage chunk (stream_options.include_usage) may have
// an empty choices array.
if (v.object.get("usage")) |u| if (u == .object) {
diff --git a/src/agent_steps_tests.zig b/src/agent_steps_tests.zig
index 731c1c38..a6a4bb6f 100644
--- a/src/agent_steps_tests.zig
+++ b/src/agent_steps_tests.zig
@@ -53,3 +53,27 @@ test "assembleOpenAI preserves streamed reasoning and Gemini echo fields" {
try std.testing.expectEqualStrings("stop", gchoice.get("finish_reason").?.string);
try std.testing.expectEqualStrings("GSIG", gcall.get("extra_content").?.object.get("google").?.object.get("thought_signature").?.string);
}
+
+test "#748: error-only OpenAI SSE is an error envelope, not a missing stream" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = undefined,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = null,
+ };
+ const root = (try agent.assembleOpenAI(
+ "event: error\n" ++
+ "data: {\"error\":{\"type\":\"invalid_request_error\",\"message\":\"only auto is supported\"}}\n\n",
+ )).?;
+ try std.testing.expectEqualStrings("error", root.get("type").?.string);
+ try std.testing.expectEqualStrings("invalid_request_error", root.get("error").?.object.get("type").?.string);
+ try std.testing.expectEqualStrings("only auto is supported", root.get("error").?.object.get("message").?.string);
+}
diff --git a/src/cli.zig b/src/cli.zig
index db116778..7497a4f0 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.
@@ -24,6 +24,7 @@ pub const changelog_text =
\\0.0.289
\\ • background-agent handles survive an interrupted API turn (#753)
\\ • prompt-cache affinity is the git root, not the leaf cwd
+ \\ • Meta tool_choice is auto-only; error-only SSE is not a truncate-retry (#751 #748)
\\
\\0.0.288
\\ • GPT-6 Astra is the default Codex model: mid-turn steer, vision, hosted search, OpenAI compact
@@ -384,89 +385,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 +409,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 +416,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/codedb_exec.zig b/src/codedb_exec.zig
index 03b69582..6c241abd 100644
--- a/src/codedb_exec.zig
+++ b/src/codedb_exec.zig
@@ -16,6 +16,7 @@ const harness_policy = @import("harness_policy.zig");
const list_dir = @import("list_dir.zig");
const codedb_health = @import("codedb_health.zig");
const codedb_around = @import("codedb_around.zig");
+const codedb_local = @import("codedb_local.zig");
const jobs = @import("jobs.zig");
const main_mod = @import("main.zig");
const hooks = @import("hooks.zig");
@@ -90,6 +91,8 @@ pub fn exec(ctx: ToolCtx, input: std.json.Value) !ToolOutput {
.is_error = true,
};
+ if (std.mem.eql(u8, sub, "context")) return execContext(ctx, it.rest(), input);
+
if (isPathSub(sub)) {
if (firstPathArg(it.rest())) |path| {
if (!harness_policy.confinedPath(path) or !harness_policy.noSymlinkEscape(io, path, ctx.agent_cwd))
@@ -132,6 +135,53 @@ pub fn exec(ctx: ToolCtx, input: std.json.Value) !ToolOutput {
return .{ .text = text };
}
+fn requiredLocal(ctx: ToolCtx, input: std.json.Value) bool {
+ if (codedb_local.inputRequiresLocal(input)) return true;
+ if (ctx.agent_cwd) |root| {
+ var dir = Io.Dir.cwd().openDir(ctx.io, root, .{}) catch
+ return codedb_local.dirRequiresLocal(ctx.io, ctx.gpa, Io.Dir.cwd());
+ defer dir.close(ctx.io);
+ return codedb_local.dirRequiresLocal(ctx.io, ctx.gpa, dir);
+ }
+ return codedb_local.dirRequiresLocal(ctx.io, ctx.gpa, Io.Dir.cwd());
+}
+
+fn execContext(ctx: ToolCtx, rest: []const u8, input: std.json.Value) !ToolOutput {
+ const gpa = ctx.gpa;
+ const plan = codedb_local.planContext(requiredLocal(ctx, input), rest);
+ if (plan.kind == .refuse) {
+ return .{ .text = try gpa.dupe(u8, plan.refuse_reason), .is_error = true };
+ }
+
+ var argv: std.ArrayList([]const u8) = .empty;
+ defer argv.deinit(gpa);
+ try argv.append(gpa, "codedb");
+ try argv.append(gpa, "context");
+ try codedb_local.appendContextArgs(gpa, &argv, plan, rest);
+
+ const run = jobs.runCappedWithOptions(gpa, ctx.io, argv.items, 512 * 1024, 4096, deadline_ms, jobs.toolRunOptions(ctx.agent_cwd)) catch |e| switch (e) {
+ error.FileNotFound => return .{
+ .text = try gpa.dupe(u8, "codedb isn't installed — it's open source at github.com/justrach/codedb; install it, then run `codedb` once in the repo to index it. Folder listing still works: codedb list_dir ."),
+ .is_error = true,
+ },
+ else => return tools.failure(gpa, e),
+ };
+ gpa.free(run.stderr);
+ const text = run.stdout;
+ if (run.timed_out) {
+ defer gpa.free(text);
+ return .{
+ .text = try std.fmt.allocPrint(gpa, "codedb context timed out after {d}s and was killed — narrow the query, or run it through bash if it really needs that long", .{deadline_ms / 1000}),
+ .is_error = true,
+ };
+ }
+ if (text.len == 0) {
+ defer gpa.free(text);
+ return .{ .text = try gpa.dupe(u8, "(codedb returned nothing — try `codedb status` or `codedb tree` to confirm the repo is indexed, or refine the query)") };
+ }
+ return .{ .text = text };
+}
+
/// Opt-in exploratory read via `codedb read <path> [-L a-b] --compact`. Lossy
/// view for reasoning only; returns null on any codedb failure so the caller
/// falls back to the native byte-exact read (#66).
@@ -204,3 +254,25 @@ test "advertised surface is the one-shots, hop verbs stay callable" {
try std.testing.expect(!std.mem.eql(u8, s, "read"));
}
}
+
+test "execContext refuses remote rerank under local_only before spawn" {
+ const gpa = std.testing.allocator;
+ const parsed = try std.json.parseFromSlice(std.json.Value, gpa, "{\"command\":\"context --hybrid auth\",\"local_only\":true}", .{});
+ defer parsed.deinit();
+ var client: std.http.Client = undefined;
+ const ctx = ToolCtx{
+ .gpa = gpa,
+ .io = std.testing.io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ };
+ const out = try execContext(ctx, "--hybrid auth", parsed.value);
+ defer gpa.free(out.text);
+ try std.testing.expect(out.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, out.text, "not dispatched") != null);
+ try std.testing.expect(!codedb_local.wouldInvokeRemoteRerank(codedb_local.planContext(true, "--hybrid auth")));
+}
diff --git a/src/codedb_local.zig b/src/codedb_local.zig
new file mode 100644
index 00000000..9ed9e12b
--- /dev/null
+++ b/src/codedb_local.zig
@@ -0,0 +1,283 @@
+//! Local-only retrieval policy for native `codedb context` (#765).
+//!
+//! codedb's default composer may send relative paths and bounded snippets to a
+//! hosted embeddings lane for advisory rerank. "No remote retention" is not no
+//! egress. When repository policy or the per-call `local_only` argument
+//! requires on-device retrieval, graff injects `context --local` before spawn
+//! and never dispatches hybrid/semantic rerank. If that boundary cannot be
+//! guaranteed, dispatch is refused. Ordinary reads stay native codedb
+//! (ADR 0040) — this is not a codedb-pro redirect.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const json_args = @import("json_args.zig");
+const util = @import("util.zig");
+
+pub const instruction_names = [_][]const u8{ "AGENTS.md", "HARNESS.md", "CLAUDE.md" };
+pub const policy_json_path = ".graff/policy.json";
+pub const retrieval_policy_path = ".graff/retrieval-policy";
+
+const phrases = [_][]const u8{
+ "local-only retrieval",
+ "local only retrieval",
+ "local-only search",
+ "local only search",
+ "no transmission of working data",
+ "do not transmit working data",
+ "don't transmit working data",
+ "never transmit working data",
+ "prohibit transmission of working",
+ "prohibiting transmission of working",
+ "working data must not leave",
+ "no remote rerank",
+ "no remote ranking",
+ "do not send working data",
+ "never send working data",
+ "do not transmit repository",
+};
+
+pub const Kind = enum { local, remote, refuse };
+
+pub const Plan = struct {
+ kind: Kind,
+ inject_local: bool,
+ refuse_reason: []const u8 = "",
+};
+
+pub const refuse_remote =
+ "codedb context: repository policy requires local-only retrieval. Remote reranking sends relative paths and snippets over the network even when the provider claims no remote retention, so the call was not dispatched. Omit --hybrid/--semantic (graff will run `codedb context --local`) or pass local_only=true.";
+
+const remote_flags = [_][]const u8{ "--hybrid", "--semantic" };
+const local_flags = [_][]const u8{ "--local", "--no-semantic" };
+
+pub fn textRequiresLocal(text: []const u8) bool {
+ for (phrases) |p| {
+ if (util.indexOfIgnoreCase(text, p) != null) return true;
+ }
+ return false;
+}
+
+pub fn policyJsonRequiresLocal(body: []const u8) bool {
+ var parsed = std.json.parseFromSlice(std.json.Value, std.heap.page_allocator, std.mem.trim(u8, body, " \t\r\n"), .{}) catch return false;
+ defer parsed.deinit();
+ if (parsed.value != .object) return false;
+ if (stringIsLocal(parsed.value.object.get("retrieval"))) return true;
+ if (boolIsTrue(parsed.value.object.get("local_only"))) return true;
+ const codedb = parsed.value.object.get("codedb") orelse return false;
+ if (codedb != .object) return false;
+ return stringIsLocal(codedb.object.get("retrieval")) or boolIsTrue(codedb.object.get("local_only"));
+}
+
+fn stringIsLocal(v: ?std.json.Value) bool {
+ const val = v orelse return false;
+ if (val != .string) return false;
+ return std.ascii.eqlIgnoreCase(val.string, "local-only") or
+ std.ascii.eqlIgnoreCase(val.string, "local_only") or
+ std.ascii.eqlIgnoreCase(val.string, "local");
+}
+
+fn boolIsTrue(v: ?std.json.Value) bool {
+ const val = v orelse return false;
+ return val == .bool and val.bool;
+}
+
+pub fn retrievalPolicyRequiresLocal(body: []const u8) bool {
+ const trimmed = std.mem.trim(u8, body, " \t\r\n");
+ if (trimmed.len == 0) return false;
+ if (std.ascii.eqlIgnoreCase(trimmed, "local")) return true;
+ return util.indexOfIgnoreCase(trimmed, "local-only") != null or
+ util.indexOfIgnoreCase(trimmed, "local_only") != null;
+}
+
+pub fn dirRequiresLocal(io: Io, gpa: Allocator, dir: Io.Dir) bool {
+ for (instruction_names) |name| {
+ const body = dir.readFileAlloc(io, name, gpa, .limited(64 * 1024)) catch continue;
+ defer gpa.free(body);
+ if (textRequiresLocal(body)) return true;
+ }
+ if (dir.readFileAlloc(io, policy_json_path, gpa, .limited(16 * 1024))) |body| {
+ defer gpa.free(body);
+ if (policyJsonRequiresLocal(body)) return true;
+ } else |_| {}
+ if (dir.readFileAlloc(io, retrieval_policy_path, gpa, .limited(4 * 1024))) |body| {
+ defer gpa.free(body);
+ if (retrievalPolicyRequiresLocal(body)) return true;
+ } else |_| {}
+ return false;
+}
+
+pub fn inputRequiresLocal(input: std.json.Value) bool {
+ return json_args.flag(input, "local_only");
+}
+
+pub fn tokenIsRemoteFlag(tok: []const u8) bool {
+ for (remote_flags) |f| if (std.mem.eql(u8, tok, f)) return true;
+ return false;
+}
+
+pub fn tokenIsLocalFlag(tok: []const u8) bool {
+ for (local_flags) |f| if (std.mem.eql(u8, tok, f)) return true;
+ return false;
+}
+
+pub fn restHasFlag(rest: []const u8, check: *const fn ([]const u8) bool) bool {
+ var it = std.mem.tokenizeAny(u8, rest, " \t");
+ while (it.next()) |tok| {
+ if (check(tok)) return true;
+ }
+ return false;
+}
+
+/// Default `context` is hybrid (remote advisory rerank) unless `--local`.
+pub fn defaultWouldRemoteRerank(rest: []const u8) bool {
+ return !restHasFlag(rest, tokenIsLocalFlag);
+}
+
+pub fn planContext(required_local: bool, rest: []const u8) Plan {
+ if (!required_local) {
+ if (restHasFlag(rest, tokenIsLocalFlag)) return .{ .kind = .local, .inject_local = false };
+ return .{ .kind = .remote, .inject_local = false };
+ }
+ if (restHasFlag(rest, tokenIsRemoteFlag)) {
+ return .{ .kind = .refuse, .inject_local = false, .refuse_reason = refuse_remote };
+ }
+ return .{ .kind = .local, .inject_local = !restHasFlag(rest, tokenIsLocalFlag) };
+}
+
+pub fn wouldInvokeRemoteRerank(plan: Plan) bool {
+ return plan.kind == .remote;
+}
+
+/// Caller has already pushed `codedb` and `context`.
+pub fn appendContextArgs(gpa: Allocator, argv: *std.ArrayList([]const u8), plan: Plan, rest: []const u8) !void {
+ if (plan.inject_local) try argv.append(gpa, "--local");
+ var it = std.mem.tokenizeAny(u8, rest, " \t");
+ while (it.next()) |tok| {
+ if (tokenIsRemoteFlag(tok)) continue;
+ try argv.append(gpa, tok);
+ }
+}
+
+pub fn contextArgv(gpa: Allocator, plan: Plan, rest: []const u8) ![]const []const u8 {
+ var argv: std.ArrayList([]const u8) = .empty;
+ errdefer argv.deinit(gpa);
+ try argv.append(gpa, "codedb");
+ try argv.append(gpa, "context");
+ try appendContextArgs(gpa, &argv, plan, rest);
+ return argv.toOwnedSlice(gpa);
+}
+
+test "project-instruction phrases require local-only; generic offline notes do not" {
+ try std.testing.expect(textRequiresLocal("Do not transmit working data to any network service."));
+ try std.testing.expect(textRequiresLocal("Repository policy: local-only retrieval for codedb."));
+ try std.testing.expect(textRequiresLocal("explicit project instructions prohibiting transmission of working data"));
+ try std.testing.expect(textRequiresLocal("Use no remote rerank on context queries."));
+ try std.testing.expect(!textRequiresLocal("tier 1 is deterministic and offline (no provider calls, no network, no spend)"));
+ try std.testing.expect(!textRequiresLocal("Invalid remote compaction falls back locally"));
+}
+
+test "policy files honor local-only retrieval" {
+ try std.testing.expect(policyJsonRequiresLocal("{\"retrieval\":\"local-only\"}"));
+ try std.testing.expect(policyJsonRequiresLocal("{\"local_only\":true}"));
+ try std.testing.expect(policyJsonRequiresLocal("{\"codedb\":{\"retrieval\":\"local\"}}"));
+ try std.testing.expect(!policyJsonRequiresLocal("{\"retrieval\":\"hybrid\"}"));
+ try std.testing.expect(!policyJsonRequiresLocal("{\"local_only\":false}"));
+ try std.testing.expect(!policyJsonRequiresLocal("not json"));
+ try std.testing.expect(retrievalPolicyRequiresLocal("local-only\n"));
+ try std.testing.expect(retrievalPolicyRequiresLocal("local"));
+ try std.testing.expect(!retrievalPolicyRequiresLocal("hybrid"));
+}
+
+test "dirRequiresLocal reads instructions and .graff policy files" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+
+ try std.testing.expect(!dirRequiresLocal(io, gpa, tmp.dir));
+
+ try tmp.dir.writeFile(io, .{ .sub_path = "README.md", .data = "no remote rerank\n" });
+ try std.testing.expect(!dirRequiresLocal(io, gpa, tmp.dir));
+
+ try tmp.dir.writeFile(io, .{ .sub_path = "AGENTS.md", .data = "Do not transmit working data.\n" });
+ try std.testing.expect(dirRequiresLocal(io, gpa, tmp.dir));
+ try tmp.dir.writeFile(io, .{ .sub_path = "AGENTS.md", .data = "be helpful\n" });
+ try std.testing.expect(!dirRequiresLocal(io, gpa, tmp.dir));
+
+ try tmp.dir.createDirPath(io, ".graff");
+ try tmp.dir.writeFile(io, .{ .sub_path = policy_json_path, .data = "{\"retrieval\":\"local-only\"}\n" });
+ try std.testing.expect(dirRequiresLocal(io, gpa, tmp.dir));
+}
+
+test "local-only context never selects remote rerank" {
+ const gpa = std.testing.allocator;
+ const task = "find the request authentication path";
+ const plan = planContext(true, task);
+ try std.testing.expectEqual(Kind.local, plan.kind);
+ try std.testing.expect(plan.inject_local);
+ try std.testing.expect(!wouldInvokeRemoteRerank(plan));
+ try std.testing.expect(defaultWouldRemoteRerank(task));
+
+ const argv = try contextArgv(gpa, plan, task);
+ defer gpa.free(argv);
+ try std.testing.expectEqualStrings("codedb", argv[0]);
+ try std.testing.expectEqualStrings("context", argv[1]);
+ try std.testing.expectEqualStrings("--local", argv[2]);
+ try std.testing.expectEqualStrings(task[0..4], argv[3][0..4]);
+ for (argv) |tok| {
+ try std.testing.expect(!tokenIsRemoteFlag(tok));
+ try std.testing.expect(!std.mem.eql(u8, tok, "--hybrid"));
+ try std.testing.expect(!std.mem.eql(u8, tok, "--semantic"));
+ }
+}
+
+test "local-only refuses hybrid flags before dispatch" {
+ const plan = planContext(true, "--hybrid find auth");
+ try std.testing.expectEqual(Kind.refuse, plan.kind);
+ try std.testing.expect(!wouldInvokeRemoteRerank(plan));
+ try std.testing.expect(std.mem.indexOf(u8, plan.refuse_reason, "not dispatched") != null);
+ try std.testing.expect(std.mem.indexOf(u8, plan.refuse_reason, "local-only") != null);
+
+ const semantic = planContext(true, "--semantic how does auth work");
+ try std.testing.expectEqual(Kind.refuse, semantic.kind);
+ try std.testing.expect(!wouldInvokeRemoteRerank(semantic));
+}
+
+test "per-call local_only and existing --local stay on-device" {
+ const gpa = std.testing.allocator;
+ {
+ const parsed = try std.json.parseFromSlice(std.json.Value, gpa, "{\"command\":\"context auth\",\"local_only\":true}", .{});
+ defer parsed.deinit();
+ try std.testing.expect(inputRequiresLocal(parsed.value));
+ const plan = planContext(inputRequiresLocal(parsed.value), "auth");
+ try std.testing.expect(!wouldInvokeRemoteRerank(plan));
+ }
+ {
+ const parsed = try std.json.parseFromSlice(std.json.Value, gpa, "{\"command\":\"context auth\"}", .{});
+ defer parsed.deinit();
+ try std.testing.expect(!inputRequiresLocal(parsed.value));
+ }
+ const already = planContext(true, "--local auth");
+ try std.testing.expectEqual(Kind.local, already.kind);
+ try std.testing.expect(!already.inject_local);
+ try std.testing.expect(!wouldInvokeRemoteRerank(already));
+ const argv = try contextArgv(gpa, already, "--local auth");
+ defer gpa.free(argv);
+ var locals: usize = 0;
+ for (argv) |tok| {
+ if (std.mem.eql(u8, tok, "--local")) locals += 1;
+ try std.testing.expect(!tokenIsRemoteFlag(tok));
+ }
+ try std.testing.expectEqual(@as(usize, 1), locals);
+}
+
+test "without local-only policy default context still allows remote rerank" {
+ const plan = planContext(false, "find auth");
+ try std.testing.expectEqual(Kind.remote, plan.kind);
+ try std.testing.expect(wouldInvokeRemoteRerank(plan));
+ try std.testing.expect(defaultWouldRemoteRerank("find auth"));
+ try std.testing.expect(!defaultWouldRemoteRerank("--local find auth"));
+ try std.testing.expect(!defaultWouldRemoteRerank("--no-semantic find auth"));
+}
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 13a2d4cb..b38ce23a 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -84,6 +84,8 @@ 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 = "/update", .usage = "/update [install]", .desc = "check for a release and install it for the next launch (this session keeps running)" },
.{ .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.zig
index a3aae89e..4ddf182e 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,14 @@ 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;
+ }
+ if (try @import("update_cmd.zig").tryHandle(root, arena, line, out)) return true; // #773 /update
// #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/exec.zig b/src/exec.zig
index d93e1bda..478187a2 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -274,12 +274,13 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);
const start_line = intField(input, "start_line");
const end_line = intField(input, "end_line");
- const contains = strField(input, "contains");
+ // Strict tool calling often sends null/"" for unused optionals (#761).
+ // Empty contains is omitted so a whole-file or window read stays legal.
+ const contains_raw = strField(input, "contains");
+ const contains: ?[]const u8 = if (contains_raw) |n| (if (n.len == 0) null else n) else null;
const want_compact = tools.json_args.flag(input, "compact");
- if (contains) |needle| {
- if (needle.len == 0) return .{ .text = try gpa.dupe(u8, "read_file: contains must not be empty"), .is_error = true };
- if (start_line != null or end_line != null or want_compact) return .{ .text = try gpa.dupe(u8, "read_file: contains cannot be combined with start_line, end_line, or compact"), .is_error = true };
- }
+ if (contains != null and (start_line != null or end_line != null or want_compact))
+ return .{ .text = try gpa.dupe(u8, "read_file: contains cannot be combined with start_line, end_line, or compact"), .is_error = true };
// #66: opt-in compact view routes to `codedb read <path> [-L a-b] --compact`
// when codedb is present and this file is indexed. Lossy (strips comments/
// blanks, shows line numbers) so it is NEVER the default and is labeled
@@ -435,4 +436,5 @@ test { // main.zig is at the 600-line cap; exec.zig is these modules' importer,
_ = @import("mcp_shapes.zig");
_ = @import("spec_ptc.zig");
_ = @import("xai_hosted.zig");
+ _ = @import("read_file_schema_tests.zig"); // #761: optional read_file fields
}
diff --git a/src/help.zig b/src/help.zig
index 037430ab..2c947e8e 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", "/update", "/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.zig
index 2214a49c..0f4e60ea 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/mcp.zig b/src/mcp.zig
index 949487ac..ee6e8093 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -24,6 +24,7 @@ const mcp_stdio = @import("mcp_stdio.zig");
const mcp_teardown = @import("mcp_teardown.zig");
const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stamps
const mcp_rpc = @import("mcp_rpc.zig");
+const mcp_elicitation = @import("mcp_elicitation.zig");
const mcp_cache = @import("mcp_cache.zig");
const util = @import("util.zig");
const vision = @import("vision.zig"); // #249: MCP image results become staged vision blocks
@@ -489,6 +490,8 @@ pub const Registry = struct {
defer response_arena_state.deinit();
const response_alloc = response_arena_state.allocator();
if (!server.initialized) try initializeServer(server, response_alloc, reg.arena(), null);
+ server.elicit_source = pw.writer.buffered();
+ defer server.elicit_source = "";
const resp = request(server, response_alloc, pw.writer.buffered(), "tools/call", tool.original_name) catch |err| switch (err) {
// Streamable HTTP servers use 404 to expire a session. Re-run the
// MCP handshake once, then retry the call without the stale ID.
@@ -518,6 +521,8 @@ pub const Registry = struct {
const c = e.object.get("code") orelse break :blk 0;
break :blk if (c == .integer) c.integer else 0;
} else 0;
+ if (mcp_elicitation.looksUnavailable(msg))
+ return .{ .text = try out_alloc.dupe(u8, mcp_elicitation.fallback), .is_error = true };
const text = if (code != 0)
try std.fmt.allocPrint(out_alloc, "MCP error {d}: {s}", .{ code, msg })
else
@@ -556,11 +561,17 @@ pub const Registry = struct {
try sw.write(sc);
}
}
- return .{ .text = try ow.toOwnedSlice(), .is_error = is_error };
+ const text = try ow.toOwnedSlice();
+ if (mcp_elicitation.looksUnavailable(text)) {
+ out_alloc.free(text);
+ return .{ .text = try out_alloc.dupe(u8, mcp_elicitation.fallback), .is_error = true };
+ }
+ return .{ .text = text, .is_error = is_error };
}
};
test {
_ = @import("mcp_cache.zig");
_ = @import("mcp_boot.zig");
+ _ = @import("mcp_elicitation.zig");
}
diff --git a/src/mcp_elicitation.zig b/src/mcp_elicitation.zig
new file mode 100644
index 00000000..7db12577
--- /dev/null
+++ b/src/mcp_elicitation.zig
@@ -0,0 +1,383 @@
+//! MCP form elicitation for the signed Codex Computer Use bridge (#768).
+//!
+//! `node_repl` / `@oai/sky` call `nodeRepl.createElicitation` before desktop
+//! work. Clients that advertise no form capability fail the JS call before any
+//! accessibility state returns. Graff advertises form mode and answers
+//! `elicitation/create` on the stdio request-scoped channel:
+//!
+//! - read-only `get_app_state` (especially `disableDiff: true`) is accepted
+//! with schema defaults — inspect is not a confirmation prompt;
+//! - URL mode and mutating sky input are declined with an actionable fallback
+//! (desktop `computer` tool, reconnect MCP). Do not embed V8 or spoof Codex.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+
+const mcp_protocol = @import("mcp_protocol.zig");
+const mcp_stdio = @import("mcp_stdio.zig");
+const util = @import("util.zig");
+
+/// Legacy `initialize` `capabilities` object. `{form:{}}` is the 2025-11-25
+/// form-only shape; an empty `elicitation` object is also form-only, but
+/// node_repl checks the named form key before calling createElicitation.
+pub const client_capabilities = "{\"elicitation\":{\"form\":{}}}";
+
+pub const initialize_params =
+ "{\"protocolVersion\":\"" ++ mcp_protocol.legacy_protocol ++
+ "\",\"capabilities\":" ++ client_capabilities ++
+ ",\"clientInfo\":{\"name\":\"simple-harness\",\"version\":\"0.1\"}}";
+
+/// Shown when form elicitation is required and we cannot accept the request.
+pub const fallback =
+ \\Computer Use form elicitation is unavailable or was declined.
+ \\
+ \\For a read-only accessibility inspect, call sky.get_app_state({ app: "<name>", disableDiff: true }). Graff advertises MCP form elicitation and accepts that inspect without a form prompt. Reconnect MCP (`/mcp trust`) if this session started before that capability existed.
+ \\
+ \\If you need a snapshot without the Codex node_repl bridge, use the desktop `computer` tool (action: snapshot or apps) after Computer use is enabled in the Codegraff app menu. Do not use the plugin's raw Computer Use MCP client or synthesize OS events.
+;
+
+const mutating = [_][]const u8{
+ "sky.click",
+ "sky.type",
+ "sky.press",
+ "sky.scroll",
+ "sky.hotkey",
+ "sky.drag",
+ "sky.setValue",
+ "sky.set_value",
+ "sky.keyPress",
+ "sky.key_press",
+ ".click(",
+ ".typeText(",
+ ".pressKey(",
+ ".setValue(",
+};
+
+fn contains(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+fn mutatingSky(source: []const u8) bool {
+ for (mutating) |token| if (contains(source, token)) return true;
+ return false;
+}
+
+/// True when the in-flight `tools/call` is a read-only Computer Use inspect.
+pub fn readonlyAppState(source: []const u8) bool {
+ if (!contains(source, "get_app_state")) return false;
+ return !mutatingSky(source);
+}
+
+fn readonlyMessage(params: Value) bool {
+ if (params != .object) return false;
+ const message = params.object.get("message") orelse return false;
+ if (message != .string) return false;
+ const m = message.string;
+ const hints = [_][]const u8{
+ "get_app_state",
+ "app state",
+ "app-state",
+ "accessibility",
+ "disableDiff",
+ "read-only",
+ "read only",
+ "readonly",
+ };
+ for (hints) |h| if (contains(m, h)) return true;
+ return false;
+}
+
+fn urlMode(params: Value) bool {
+ if (params != .object) return false;
+ const mode = params.object.get("mode") orelse return false;
+ return mode == .string and std.mem.eql(u8, mode.string, "url");
+}
+
+pub const Action = enum { accept, decline };
+
+pub fn decide(source: []const u8, params: Value) Action {
+ if (urlMode(params)) return .decline;
+ if (readonlyAppState(source) or readonlyMessage(params)) return .accept;
+ return .decline;
+}
+
+fn sensitiveName(name: []const u8) bool {
+ const keys = [_][]const u8{ "password", "secret", "token", "credential", "api_key", "apikey" };
+ for (keys) |k| {
+ if (util.indexOfIgnoreCase(name, k) != null) return true;
+ }
+ return false;
+}
+
+fn writeDefault(w: *Io.Writer, schema: Value) bool {
+ if (schema != .object) return false;
+ if (schema.object.get("default")) |d| {
+ var s: std.json.Stringify = .{ .writer = w };
+ s.write(d) catch return false;
+ return true;
+ }
+ const typ = if (schema.object.get("type")) |t| (if (t == .string) t.string else "") else "";
+ if (std.mem.eql(u8, typ, "boolean")) {
+ w.writeAll("true") catch return false;
+ return true;
+ }
+ if (std.mem.eql(u8, typ, "number") or std.mem.eql(u8, typ, "integer")) {
+ w.writeAll("0") catch return false;
+ return true;
+ }
+ if (std.mem.eql(u8, typ, "array")) {
+ w.writeAll("[]") catch return false;
+ return true;
+ }
+ if (schema.object.get("enum")) |en| {
+ if (en == .array and en.array.items.len > 0) {
+ var s: std.json.Stringify = .{ .writer = w };
+ s.write(en.array.items[0]) catch return false;
+ return true;
+ }
+ }
+ if (std.mem.eql(u8, typ, "string") or typ.len == 0) {
+ w.writeAll("\"\"") catch return false;
+ return true;
+ }
+ return false;
+}
+
+fn requiredHas(schema: Value, name: []const u8) bool {
+ if (schema != .object) return false;
+ const req = schema.object.get("required") orelse return false;
+ if (req != .array) return false;
+ for (req.array.items) |item| {
+ if (item == .string and std.mem.eql(u8, item.string, name)) return true;
+ }
+ return false;
+}
+
+/// Schema defaults (or safe primitives) for an accept. Null if a required
+/// secret field cannot be filled.
+pub fn acceptContent(arena: Allocator, schema: ?Value) ?[]const u8 {
+ const root = schema orelse return "{}";
+ if (root != .object) return "{}";
+ const props = root.object.get("properties") orelse return "{}";
+ if (props != .object) return "{}";
+
+ var aw: Io.Writer.Allocating = .init(arena);
+ aw.writer.writeByte('{') catch return null;
+ var first = true;
+ var it = props.object.iterator();
+ while (it.next()) |entry| {
+ if (sensitiveName(entry.key_ptr.*) and requiredHas(root, entry.key_ptr.*)) return null;
+ if (!first) aw.writer.writeByte(',') catch return null;
+ first = false;
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.write(entry.key_ptr.*) catch return null;
+ aw.writer.writeByte(':') catch return null;
+ if (!writeDefault(&aw.writer, entry.value_ptr.*)) return null;
+ }
+ aw.writer.writeByte('}') catch return null;
+ return aw.toOwnedSlice() catch null;
+}
+
+pub fn looksUnavailable(text: []const u8) bool {
+ return contains(text, "createElicitation is unavailable") or
+ contains(text, "does not support form elicitation") or
+ contains(text, "Client does not support elicitation");
+}
+
+pub fn surface(alloc: Allocator, text: []const u8) ![]u8 {
+ if (looksUnavailable(text)) return alloc.dupe(u8, fallback);
+ return alloc.dupe(u8, text);
+}
+
+fn incomingMethod(msg: Value) ?[]const u8 {
+ if (msg != .object) return null;
+ if (msg.object.get("result") != null or msg.object.get("error") != null) return null;
+ const method = msg.object.get("method") orelse return null;
+ return if (method == .string) method.string else null;
+}
+
+fn incomingId(msg: Value) ?i64 {
+ if (msg != .object) return null;
+ const id = msg.object.get("id") orelse return null;
+ return if (id == .integer) id.integer else null;
+}
+
+fn incomingParams(msg: Value) Value {
+ if (msg != .object) return .null;
+ return msg.object.get("params") orelse .null;
+}
+
+pub fn replyBody(arena: Allocator, id: i64, action: Action, content: []const u8) ![]u8 {
+ return switch (action) {
+ .accept => std.fmt.allocPrint(arena,
+ \\{{"jsonrpc":"2.0","id":{d},"result":{{"action":"accept","content":{s}}}}}
+ , .{ id, content }),
+ .decline => std.fmt.allocPrint(arena,
+ \\{{"jsonrpc":"2.0","id":{d},"result":{{"action":"decline"}}}}
+ , .{id}),
+ };
+}
+
+/// If `line` is `elicitation/create`, write a JSON-RPC result and return true.
+pub fn replyStdio(w: *Io.Writer, arena: Allocator, line: []const u8, source: []const u8) !bool {
+ const trimmed = std.mem.trim(u8, line, " \t\r\n");
+ if (trimmed.len == 0) return false;
+ const msg = std.json.parseFromSliceLeaky(Value, arena, trimmed, .{ .allocate = .alloc_always }) catch return false;
+ const method = incomingMethod(msg) orelse return false;
+ const id = incomingId(msg) orelse return false;
+ if (!std.mem.eql(u8, method, "elicitation/create")) return false;
+
+ const params = incomingParams(msg);
+ var action = decide(source, params);
+ var content: []const u8 = "{}";
+ if (action == .accept) {
+ const schema = if (params == .object) params.object.get("requestedSchema") else null;
+ if (acceptContent(arena, schema)) |filled| {
+ content = filled;
+ } else {
+ action = .decline;
+ }
+ }
+ try mcp_stdio.writeRequest(w, try replyBody(arena, id, action, content));
+ return true;
+}
+
+const testing = std.testing;
+
+test "client capabilities advertise form elicitation (#768)" {
+ try testing.expect(contains(client_capabilities, "\"elicitation\""));
+ try testing.expect(contains(client_capabilities, "\"form\""));
+ try testing.expect(contains(initialize_params, client_capabilities));
+ try testing.expect(contains(initialize_params, mcp_protocol.legacy_protocol));
+}
+
+test "readonlyAppState: get_app_state + disableDiff is inspect-only (#768)" {
+ const src =
+ \\sky.get_app_state({ app: "Codegraff", disableDiff: true })
+ ;
+ try testing.expect(readonlyAppState(src));
+ try testing.expect(readonlyAppState("{\"code\":\"await sky.get_app_state({app:\\\"X\\\",disableDiff:true})\"}"));
+ try testing.expect(readonlyAppState("get_app_state({ app: \"Finder\" })"));
+ try testing.expect(!readonlyAppState(""));
+ try testing.expect(!readonlyAppState("console.log('hi')"));
+}
+
+test "readonlyAppState: mutating sky calls are not inspect-only (#768)" {
+ try testing.expect(!readonlyAppState("sky.get_app_state({app:'X'}); sky.click({x:1})"));
+ try testing.expect(!readonlyAppState("sky.click({ x: 10, y: 10 })"));
+ try testing.expect(!readonlyAppState("sky.get_app_state({ disableDiff: false }); sky.setValue({id:1})"));
+}
+
+test "decide accepts read-only inspect and declines URL / input (#768)" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const inspect = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"message":"Inspect Codegraff app state","requestedSchema":{"type":"object","properties":{}}}
+ , .{});
+ try testing.expectEqual(Action.accept, decide("sky.get_app_state({disableDiff:true})", inspect));
+ try testing.expectEqual(Action.accept, decide("", inspect));
+
+ const url = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"mode":"url","message":"Sign in","url":"https://example.invalid"}
+ , .{});
+ try testing.expectEqual(Action.decline, decide("sky.get_app_state({disableDiff:true})", url));
+
+ const click = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"message":"Allow click"}
+ , .{});
+ try testing.expectEqual(Action.decline, decide("sky.click({x:1,y:2})", click));
+}
+
+test "acceptContent fills defaults and refuses required secrets (#768)" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ try testing.expectEqualStrings("{}", acceptContent(a, null).?);
+
+ const empty = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"type":"object","properties":{}}
+ , .{});
+ try testing.expectEqualStrings("{}", acceptContent(a, empty).?);
+
+ const flagged = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"type":"object","properties":{"approved":{"type":"boolean","default":true}}}
+ , .{});
+ try testing.expectEqualStrings("{\"approved\":true}", acceptContent(a, flagged).?);
+
+ const secret = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"type":"object","properties":{"password":{"type":"string"}},"required":["password"]}
+ , .{});
+ try testing.expect(acceptContent(a, secret) == null);
+}
+
+test "replyBody: accept carries content, decline names no form fields (#768)" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const ok = try replyBody(a, 99, .accept, "{}");
+ try testing.expect(contains(ok, "\"action\":\"accept\""));
+ try testing.expect(contains(ok, "\"content\":{}"));
+ const no = try replyBody(a, 7, .decline, "{}");
+ try testing.expect(contains(no, "\"action\":\"decline\""));
+ try testing.expect(!contains(no, "\"content\""));
+}
+
+test "looksUnavailable / surface rewrite the node_repl form-elicitation crash (#768)" {
+ const raw = "nodeRepl.createElicitation is unavailable because the MCP client does not support form elicitation";
+ try testing.expect(looksUnavailable(raw));
+ try testing.expect(!looksUnavailable("app state ok"));
+
+ const rewritten = try surface(testing.allocator, raw);
+ defer testing.allocator.free(rewritten);
+ try testing.expect(contains(rewritten, "disableDiff: true"));
+ try testing.expect(contains(rewritten, "computer"));
+ try testing.expect(contains(rewritten, "snapshot"));
+ try testing.expect(!contains(rewritten, "createElicitation is unavailable"));
+
+ const passthrough = try surface(testing.allocator, "other MCP error");
+ defer testing.allocator.free(passthrough);
+ try testing.expectEqualStrings("other MCP error", passthrough);
+}
+
+test "replyStdio accepts get_app_state elicitation and writes a JSON-RPC result (#768)" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var buf: [1024]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ const line =
+ \\{"jsonrpc":"2.0","id":42,"method":"elicitation/create","params":{"message":"Inspect","requestedSchema":{"type":"object","properties":{}}}}
+ ;
+ try testing.expect(try replyStdio(&w, a, line, "sky.get_app_state({ app: \"Codegraff\", disableDiff: true })"));
+ const out = w.buffered();
+ try testing.expect(contains(out, "\"action\":\"accept\""));
+ try testing.expect(std.mem.endsWith(u8, out, "\n"));
+}
+
+test "replyStdio declines mutating sky input (#768)" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var buf: [1024]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ const line =
+ \\{"jsonrpc":"2.0","id":3,"method":"elicitation/create","params":{"message":"Click"}}
+ ;
+ try testing.expect(try replyStdio(&w, a, line, "sky.click({x:1,y:2})"));
+ try testing.expect(contains(w.buffered(), "\"action\":\"decline\""));
+}
+
+test "replyStdio ignores notifications and ordinary results (#768)" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var buf: [64]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ try testing.expect(!try replyStdio(&w, a, "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}", ""));
+ try testing.expect(!try replyStdio(&w, a, "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}", ""));
+ try testing.expectEqual(@as(usize, 0), w.buffered().len);
+}
diff --git a/src/mcp_protocol.zig b/src/mcp_protocol.zig
index 152ad88a..9e82788f 100644
--- a/src/mcp_protocol.zig
+++ b/src/mcp_protocol.zig
@@ -67,10 +67,10 @@ pub fn negotiatedProtocol(response: Value, transport: Transport) ![]const u8 {
/// The three reserved `_meta` keys (basic/index § `_meta`), pre-rendered as a
/// single JSON object member. graff supports exactly one modern version and
-/// declares no client capabilities, so this is a comptime constant rather
-/// than something built per request.
+/// advertises form elicitation so Computer Use `node_repl` can confirm
+/// (`elicitation/create`) instead of crashing (#768).
pub const modern_meta =
- \\"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"codegraff","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}
+ \\"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"codegraff","version":"1"},"io.modelcontextprotocol/clientCapabilities":{"elicitation":{"form":{}}}}
;
/// Build a JSON-RPC request line. Modern era splices the `_meta` envelope
@@ -265,6 +265,8 @@ test "buildRequest: modern with empty params splices the full _meta envelope" {
try std.testing.expect(meta.object.get("io.modelcontextprotocol/protocolVersion") != null);
try std.testing.expect(meta.object.get("io.modelcontextprotocol/clientCapabilities") != null);
try std.testing.expect(meta.object.get("io.modelcontextprotocol/clientInfo") != null);
+ const caps = meta.object.get("io.modelcontextprotocol/clientCapabilities").?.object;
+ try std.testing.expect(caps.get("elicitation").?.object.get("form") != null);
}
test "buildRequest: modern with non-empty params preserves them and adds no stray comma" {
diff --git a/src/mcp_rpc.zig b/src/mcp_rpc.zig
index 15a7d033..56473276 100644
--- a/src/mcp_rpc.zig
+++ b/src/mcp_rpc.zig
@@ -9,6 +9,7 @@ const std = @import("std");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
+const mcp_elicitation = @import("mcp_elicitation.zig");
const mcp_http = @import("mcp_http.zig");
const mcp_protocol = @import("mcp_protocol.zig");
const mcp_stdio = @import("mcp_stdio.zig");
@@ -49,6 +50,9 @@ pub const Server = struct {
probe_fallback: ?LegacyReason = null,
/// In-flight HTTP `notifications/initialized` (not awaited before tools/list).
pending_initialized: ?Io.Future(void) = null,
+ /// Borrowed `tools/call` JSON while `request` is in flight; used to accept
+ /// read-only Computer Use `get_app_state` elicitation (#768).
+ elicit_source: []const u8 = "",
};
pub fn deinitServer(server: *Server, io: Io, budget: mcp_teardown.Budget) void {
@@ -141,11 +145,7 @@ fn handshakeRequest(server: *Server, a: Allocator, bound_io: ?Io, params: []cons
}
pub fn initializeServer(server: *Server, response_alloc: Allocator, session_alloc: Allocator, bound_io: ?Io) !void {
- const init_resp = try handshakeRequest(server, response_alloc, bound_io,
- \\{"protocolVersion":"
- ++ legacy_protocol ++
- \\","capabilities":{},"clientInfo":{"name":"simple-harness","version":"0.1"}}
- , "initialize");
+ const init_resp = try handshakeRequest(server, response_alloc, bound_io, mcp_elicitation.initialize_params, "initialize");
const protocol_transport: mcp_protocol.Transport = switch (server.transport) {
.stdio => .stdio,
.http => .streamable_http,
@@ -185,6 +185,7 @@ pub fn request(server: *Server, response_alloc: Allocator, params: []const u8, m
const r = &stdio.stdout_reader.interface;
while (true) {
const line = try mcp_stdio.takeLine(r);
+ if (try mcp_elicitation.replyStdio(&stdio.stdin_writer.interface, response_alloc, line, server.elicit_source)) continue;
if (mcp_http.matchingResponse(response_alloc, line, id)) |parsed| return parsed;
}
},
diff --git a/src/mcp_rpc_tests.zig b/src/mcp_rpc_tests.zig
index 8b5f933b..9c12bbb1 100644
--- a/src/mcp_rpc_tests.zig
+++ b/src/mcp_rpc_tests.zig
@@ -233,3 +233,27 @@ test "probeStdio (#327): the DEFAULT deadline covers a cold-starting server" {
try std.testing.expectEqual(mcp_rpc.StdioProbeOutcome.modern, try mcp_rpc.probeStdio(spawned.server, a, io));
try std.testing.expect(spawned.server.probe_fallback == null);
}
+
+test "request (#768): mid-call form elicitation for get_app_state is accepted" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ // First JSON-RPC id is 1 (`Server.next_id`). The fixture emits a form
+ // elicitation, then the tools/call result only after it reads the accept.
+ var spawned = try spawnReplying(a, io,
+ \\read line
+ \\printf '%s\n' '{"jsonrpc":"2.0","id":99,"method":"elicitation/create","params":{"message":"Inspect app state","requestedSchema":{"type":"object","properties":{}}}}'
+ \\read reply
+ \\printf '%s\n' '{"jsonrpc":"2.0","id":1,"result":{"ok":true}}'
+ \\cat >/dev/null
+ );
+ defer mcp_stdio.stopChild(io, &spawned.child);
+ spawned.server.elicit_source = "sky.get_app_state({ app: \"Codegraff\", disableDiff: true })";
+ spawned.server.era = .legacy;
+ spawned.server.initialized = true;
+ const resp = try mcp_rpc.request(spawned.server, a, "{\"name\":\"js\",\"arguments\":{}}", "tools/call", "js");
+ try std.testing.expect(resp.object.get("result").?.object.get("ok").?.bool);
+}
diff --git a/src/meta_wire.zig b/src/meta_wire.zig
new file mode 100644
index 00000000..8d7756fd
--- /dev/null
+++ b/src/meta_wire.zig
@@ -0,0 +1,105 @@
+//! Meta / Muse Spark request-body policy (#751).
+//!
+//! Meta's chat API only accepts `tool_choice: "auto"`. `none`, `required`,
+//! and named function choices 400 as `request_rejected`. The gateway already
+//! translates those; the harness still must not emit them for a known-
+//! restricted model — a silent `required`→`auto` rewrite at the gateway is
+//! a semantic gap. ADR 0083.
+
+const std = @import("std");
+
+/// Native Meta seat, or a Muse Spark id on any provider (Codegraff gateway).
+pub fn restricted(provider_id: []const u8, model: []const u8) bool {
+ if (std.mem.eql(u8, provider_id, "meta")) return true;
+ return std.mem.startsWith(u8, model, "muse-spark");
+}
+
+/// Value written as OpenAI-chat `tool_choice`. Restricted models always
+/// get `auto`, even when the harness wanted a forced call.
+pub fn toolChoice(force_tool: bool, provider_id: []const u8, model: []const u8) []const u8 {
+ if (restricted(provider_id, model)) return "auto";
+ return if (force_tool) "required" else "auto";
+}
+
+/// Chat `reasoning_effort` after Z.AI's own map. Meta 1.3 rejects `max`
+/// for non-contributor seats; fold `max`/`ultra` to `xhigh`. Everyone
+/// else: `ultra` → `max`, otherwise the tag as-is.
+pub fn chatEffort(requested: []const u8, provider_id: []const u8, model: []const u8) []const u8 {
+ if (restricted(provider_id, model)) {
+ if (std.mem.eql(u8, requested, "max") or std.mem.eql(u8, requested, "ultra"))
+ return "xhigh";
+ return requested;
+ }
+ if (std.mem.eql(u8, requested, "ultra")) return "max";
+ return requested;
+}
+
+test "meta: restricted is the meta seat or any muse-spark id" {
+ try std.testing.expect(restricted("meta", "muse-spark-1.3"));
+ try std.testing.expect(restricted("codegraff", "muse-spark-1.3"));
+ try std.testing.expect(restricted("meta", "something-else"));
+ try std.testing.expect(!restricted("openai", "gpt-5.6"));
+ try std.testing.expect(!restricted("codegraff", "grok-4.6"));
+}
+
+test "meta: tool_choice is auto even when the harness forces a call" {
+ try std.testing.expectEqualStrings("auto", toolChoice(true, "meta", "muse-spark-1.3"));
+ try std.testing.expectEqualStrings("auto", toolChoice(false, "meta", "muse-spark-1.3"));
+ try std.testing.expectEqualStrings("auto", toolChoice(true, "codegraff", "muse-spark-1.2"));
+ try std.testing.expectEqualStrings("required", toolChoice(true, "openai", "gpt-5.6"));
+ try std.testing.expectEqualStrings("auto", toolChoice(false, "openai", "gpt-5.6"));
+}
+
+test "meta: max/ultra effort folds to xhigh; other providers keep ultra→max" {
+ try std.testing.expectEqualStrings("xhigh", chatEffort("max", "meta", "muse-spark-1.3"));
+ try std.testing.expectEqualStrings("xhigh", chatEffort("ultra", "codegraff", "muse-spark-1.3"));
+ try std.testing.expectEqualStrings("high", chatEffort("high", "meta", "muse-spark-1.3"));
+ try std.testing.expectEqualStrings("max", chatEffort("ultra", "openai", "gpt-5.6"));
+ try std.testing.expectEqualStrings("high", chatEffort("high", "openai", "gpt-5.6"));
+}
+
+test "meta: forced chat body sends auto, never required; max effort is xhigh" {
+ const Agent = @import("agent.zig").Agent;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var messages = std.json.Array.init(arena);
+ var user: std.json.ObjectMap = .empty;
+ try user.put(arena, "role", .{ .string = "user" });
+ try user.put(arena, "content", .{ .string = "hello" });
+ try messages.append(.{ .object = user });
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = .{
+ .id = "meta",
+ .kind = .openai,
+ .auth = .bearer,
+ .url = "https://api.meta.ai/v1/chat/completions",
+ .api_key = "k",
+ .model = "muse-spark-1.3",
+ .context = 1_048_576,
+ },
+ .messages = messages,
+ .sub = false,
+ .label = "",
+ .out = null,
+ .sys_normal = "system",
+ .reasoning = .max,
+ };
+ const tools = "[{\"type\":\"function\",\"function\":{\"name\":\"ping\",\"description\":\"\",\"parameters\":{\"type\":\"object\"}}}]";
+ const forced = try agent.buildBody(tools, true, true, true);
+ defer std.testing.allocator.free(forced);
+ try std.testing.expect(std.mem.indexOf(u8, forced, "\"tool_choice\":\"required\"") == null);
+ try std.testing.expect(std.mem.indexOf(u8, forced, "\"tool_choice\":\"auto\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, forced, "\"reasoning_effort\":\"xhigh\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, forced, "\"reasoning_effort\":\"max\"") == null);
+
+ agent.provider.id = "codegraff";
+ const gw = try agent.buildBody(tools, true, true, true);
+ defer std.testing.allocator.free(gw);
+ try std.testing.expect(std.mem.indexOf(u8, gw, "\"tool_choice\":\"required\"") == null);
+ try std.testing.expect(std.mem.indexOf(u8, gw, "\"tool_choice\":\"auto\"") != null);
+}
diff --git a/src/read_file_schema_tests.zig b/src/read_file_schema_tests.zig
new file mode 100644
index 00000000..2a4f6864
--- /dev/null
+++ b/src/read_file_schema_tests.zig
@@ -0,0 +1,69 @@
+//! #761: optional `read_file` fields must stay optional, and a path-only
+//! (or null/empty optional) call is a whole-file read. Reached from
+//! exec.zig's test block.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Value = std.json.Value;
+
+const exec = @import("exec.zig");
+const tools = @import("tools.zig");
+
+fn testCtx(client: *std.http.Client, cwd: []const u8) tools.ToolCtx {
+ return .{
+ .gpa = std.testing.allocator,
+ .io = std.testing.io,
+ .client = client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ .agent_cwd = cwd,
+ };
+}
+
+fn readFile(cwd: []const u8, input_json: []const u8) !tools.ToolOutput {
+ var parsed = try std.json.parseFromSlice(Value, std.testing.allocator, input_json, .{});
+ defer parsed.deinit();
+ var client: std.http.Client = undefined;
+ return exec.execTool(testCtx(&client, cwd), .{
+ .id = "call_1",
+ .name = "read_file",
+ .input = parsed.value,
+ });
+}
+
+test "read_file (#761): a call with only path is a whole-file read" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "note.txt", .data = "hello whole file\n" });
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &real_buf);
+ const cwd = real_buf[0..n];
+
+ const only_path = try readFile(cwd, "{\"path\":\"note.txt\"}");
+ defer gpa.free(only_path.text);
+ try std.testing.expect(!only_path.is_error);
+ try std.testing.expectEqualStrings("hello whole file\n", only_path.text);
+
+ const nulls = try readFile(cwd,
+ \\{"path":"note.txt","start_line":null,"end_line":null,"contains":null,"compact":null}
+ );
+ defer gpa.free(nulls.text);
+ try std.testing.expect(!nulls.is_error);
+ try std.testing.expectEqualStrings("hello whole file\n", nulls.text);
+
+ const empty_contains = try readFile(cwd, "{\"path\":\"note.txt\",\"contains\":\"\"}");
+ defer gpa.free(empty_contains.text);
+ try std.testing.expect(!empty_contains.is_error);
+ try std.testing.expectEqualStrings("hello whole file\n", empty_contains.text);
+
+ const combined = try readFile(cwd, "{\"path\":\"note.txt\",\"contains\":\"hello\",\"start_line\":1}");
+ defer gpa.free(combined.text);
+ try std.testing.expect(combined.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, combined.text, "cannot be combined") != null);
+}
diff --git a/src/repl.zig b/src/repl.zig
index dd50bd1d..96b5d5f9 100644
--- a/src/repl.zig
+++ b/src/repl.zig
@@ -73,6 +73,10 @@ pub var g_models: []const u8 = ""; // comma-joined model names (for /models)
pub var g_model_fn: ?ModelFn = null; // switch the active model by name
pub 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 const UpdateFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, action: []const u8) ?[]const u8;
+pub var g_update_fn: ?UpdateFn = null;
pub var g_debug: bool = false; // GRAFF_REPL_DEBUG / `/debug` → dump raw stream + frames to stderr
// ---------------------------------------------------------------------------
@@ -356,6 +360,8 @@ pub const HELP_CALC =
\\Commands:
\\ /help this help
\\ /clear clear the conversation
+ \\ /version running binary and latest release status
+ \\ /update install a release for the next launch (this session keeps running)
\\ /animation enso|braille|dragon spinner style
\\ /quit exit (also /q, ctrl-c)
\\
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index fd22b9e8..23bacb3c 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -26,6 +26,8 @@ const ReasoningEffort = main_mod.ReasoningEffort;
const mcp = @import("mcp.zig");
const repl = @import("repl.zig");
+const version_status = @import("version_status.zig");
+const update_cmd = @import("update_cmd.zig");
const approvals_mod = @import("approvals.zig");
const Approvals = approvals_mod.Approvals;
const pricing = @import("pricing.zig");
@@ -540,3 +542,25 @@ pub fn goalPromptFromLine(line: []const u8) ?[]const u8 {
if (std.ascii.eqlIgnoreCase(g, sub)) return null;
return g;
}
+
+/// Scripted `graff repl` host commands. The TUI path wires the same actions
+/// through tui_launch; this bind is the zigzag / headless equivalent.
+pub fn bindHostCommands() void {
+ repl.g_version_fn = versionCb;
+ repl.g_update_fn = updateCb;
+}
+
+pub fn unbindHostCommands() void {
+ repl.g_version_fn = null;
+ repl.g_update_fn = null;
+}
+
+pub fn versionCb(ctx: ?*anyopaque, gpa: Allocator) ?[]const u8 {
+ const c: *ReplCtx = @ptrCast(@alignCast(ctx orelse return null));
+ return version_status.commandText(c.io, gpa, main_mod.harness_version) catch null;
+}
+
+pub fn updateCb(ctx: ?*anyopaque, gpa: Allocator, action: []const u8) ?[]const u8 {
+ const c: *ReplCtx = @ptrCast(@alignCast(ctx orelse return null));
+ return update_cmd.hostAction(c.io, gpa, c.home, action);
+}
diff --git a/src/repl_model_commands.zig b/src/repl_model_commands.zig
index 3de44a36..6326cf57 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,10 @@ 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, "/update")) {
+ showUpdate(self, arg);
} 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 +134,59 @@ 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);
+}
+
+fn showUpdate(self: *Model, action: []const u8) void {
+ if (repl.g_update_fn) |f| if (f(repl.g_turn_ctx, self.alloc, if (action.len == 0) "check" else action)) |text| {
+ self.pushOwned(.info, text) catch self.alloc.free(text);
+ return;
+ };
+ self.push(.info, "check for a release with /update; install it for the next launch only after you confirm. This session keeps running.") catch {};
+}
+
+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);
+}
+
+test "/update does not claim /new activates a binary" {
+ repl.g_update_fn = null;
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ runCommand(&m, "/update");
+ const text = m.history.items[m.history.items.len - 1].text;
+ try std.testing.expect(std.mem.indexOf(u8, text, "next launch") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "keeps running") != null);
+ runCommand(&m, "/new");
+ const new_text = m.history.items[m.history.items.len - 1].text;
+ try std.testing.expect(std.mem.indexOf(u8, new_text, "update") == null);
+ try std.testing.expect(std.mem.indexOf(u8, new_text, "activate") == 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.zig
index 653c9245..deaa3fdf 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 emerald
pub const HELP_CHAT =
\\Commands (mirrors the graff session):
\\ /help /clear /new /quit conversation
- \\ /rewind /compact /cost history
+ \\ /rewind /compact /cost /version /update history, running binary, next-launch install
\\ /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/schema.zig b/src/schema.zig
index 15b253d9..a997f574 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -76,7 +76,7 @@ pub const base_specs = [_]ToolSpec{
.name = "read_file",
.desc = "Read a UTF-8 text file or view a PNG/JPEG/GIF/WebP image up to 5 MiB. Read images one at a time; pixels reach the next model request when vision is supported. Call this before editing any text file. For a read-only exact-key lookup, pass contains to return only matching numbered lines instead of the whole file. Whole-file reads over 256 KiB return a short preview; pass start_line/end_line (1-based, inclusive) for a byte-exact window from any size file.",
.schema =
- \\{"type": "object", "properties": {"path": {"type": "string", "description": "File path, relative to the working directory"}, "start_line": {"type": "integer", "description": "Optional 1-based first line to return (byte-exact slice; omit for whole file)"}, "end_line": {"type": "integer", "description": "Optional 1-based last line to return, inclusive"}, "contains": {"type": "string", "description": "Optional exact literal; return only matching lines with line numbers instead of the whole file. Prefer this for exact-key read-only lookups. Cannot combine with start_line, end_line, or compact."}, "compact": {"type": "boolean", "description": "Exploratory only: return a comment/blank-stripped view via codedb (line numbers shown). NEVER use before an edit — re-read without compact to copy exact text."}}, "required": ["path"]}
+ \\{"type": "object", "properties": {"path": {"type": "string", "description": "File path, relative to the working directory"}, "start_line": {"type": ["integer", "null"], "description": "Optional 1-based first line to return (byte-exact slice; omit or null for whole file)"}, "end_line": {"type": ["integer", "null"], "description": "Optional 1-based last line to return, inclusive; omit or null for whole file"}, "contains": {"type": ["string", "null"], "description": "Optional exact literal; return only matching lines with line numbers instead of the whole file. Prefer this for exact-key read-only lookups. Omit, null, or empty for a whole-file or window read. Cannot combine a nonempty value with start_line, end_line, or compact."}, "compact": {"type": ["boolean", "null"], "description": "Exploratory only: return a comment/blank-stripped view via codedb (line numbers shown). Omit, null, or false for a byte-exact read. NEVER use before an edit — re-read without compact to copy exact text."}}, "required": ["path"]}
,
},
.{
@@ -105,9 +105,9 @@ pub const base_specs = [_]ToolSpec{
.{ .name = skill_docs.tool_name, .desc = skill_docs.tool_desc, .schema = skill_docs.tool_schema },
.{
.name = "codedb",
- .desc = "Indexed code nav (github.com/justrach/codedb). ONE command — not a hop chain: context <task> · around <name> · callpath A B · list_dir <path> · status. Prefer over bash grep/find/ls. list_dir is in-process (gitignore, PathConfine; no binary). status reports codedb.snapshot. Paths stay in the cwd.",
+ .desc = "Indexed code nav (github.com/justrach/codedb). ONE command — not a hop chain: context <task> · around <name> · callpath A B · list_dir <path> · status. Prefer over bash grep/find/ls. list_dir is in-process (gitignore, PathConfine; no binary). status reports codedb.snapshot. Paths stay in the cwd. context is local-only when local_only is set or repository policy forbids transmitting working data (no remote rerank).",
.schema =
- \\{"type": "object", "properties": {"command": {"type": "string", "description": "One of: \"context how does auth work\", \"around codedbGuard\", \"callpath exec codedbGuard\", \"list_dir src\", \"status\"."}}, "required": ["command"]}
+ \\{"type": "object", "properties": {"command": {"type": "string", "description": "One of: \"context how does auth work\", \"around codedbGuard\", \"callpath exec codedbGuard\", \"list_dir src\", \"status\"."}, "local_only": {"type": "boolean", "description": "Force on-device retrieval: dispatch `codedb context --local` with no remote rerank. Also applied automatically when repository policy requires local-only retrieval. If local-only cannot be guaranteed, the call is refused before spawn."}}, "required": ["command"]}
,
},
.{ .name = result_read.tool_name, .desc = result_read.tool_desc, .schema = result_read.tool_schema },
diff --git a/src/session_run.zig b/src/session_run.zig
index effafb8e..9024c3b6 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -114,6 +114,8 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent
if (models_buf.items.len != 0) models_buf.appendSlice(", ") catch {};
models_buf.appendSlice(mi.name) catch {};
}
+ repl_glue.bindHostCommands();
+ defer repl_glue.unbindHostCommands();
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.
diff --git a/src/skill_runtime_adapter.zig b/src/skill_runtime_adapter.zig
index c672ba90..1e918625 100644
--- a/src/skill_runtime_adapter.zig
+++ b/src/skill_runtime_adapter.zig
@@ -10,7 +10,8 @@ pub const computer_use =
\\Graff exposes this plugin's authenticated, signed Codex `node_repl` bridge through MCP-qualified tool names. Keep the bootstrap, confirmation policy, fresh-state workflow, and `nodeRepl.emitImage(...)` instructions below unchanged.
\\
\\- Where the skill says to use `node_repl`, call `mcp__node_repl__js`; use `mcp__node_repl__js_reset` and `mcp__node_repl__js_add_node_module_dir` for the two companion operations.
- \\- If those tools are absent, ask the user to run `/mcp trust` or restart with `--yolo`. Do not use the plugin's raw Computer Use MCP client or substitute OS event synthesis: the macOS service authenticates the signed Codex process chain.
+ \\- Read-only inspect uses `sky.get_app_state({ app, disableDiff: true })`. Graff advertises MCP form elicitation and accepts that inspect so `nodeRepl.createElicitation` does not fail. Mutating sky input still follows the skill's confirmation policy.
+ \\- If form elicitation is still unavailable, do not retry the same call. Use the desktop `computer` tool (`snapshot` / `apps`) after Computer use is enabled in the Codegraff app menu, or ask the user to reconnect MCP (`/mcp trust`). Do not use the plugin's raw Computer Use MCP client or substitute OS event synthesis: the macOS service authenticates the signed Codex process chain.
;
pub fn prefix(name: []const u8, from_plugin: bool) []const u8 {
@@ -23,3 +24,10 @@ test "only the plugin Computer Use skill receives the signed node_repl adapter"
try std.testing.expectEqualStrings("", prefix("computer-use", false));
try std.testing.expectEqualStrings("", prefix("other", true));
}
+
+test "Computer Use adapter names the read-only inspect and desktop fallback (#768)" {
+ const text = prefix("computer-use", true);
+ try std.testing.expect(std.mem.indexOf(u8, text, "disableDiff: true") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "createElicitation") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "computer") != null);
+}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 9c5c771e..26c162f5 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -358,4 +358,14 @@ test {
_ = @import("codex_tool_search.zig"); // hosted tool_search on gpt-5.4+ Codex
_ = @import("tool_call_args.zig"); // #752: truncated tool-call arguments must not poison history
_ = @import("cache_affinity.zig"); // ADR 0069: git-root / scratch cache seed
+ _ = @import("meta_wire.zig"); // #751 / ADR 0083: Meta tool_choice is auto-only
+ _ = @import("codedb_local.zig"); // #765: local-only codedb context (no remote rerank)
+ _ = @import("version_status.zig");
+ _ = @import("update_target.zig");
+ _ = @import("update_archive.zig");
+ _ = @import("update_service.zig");
+ _ = @import("update_cmd.zig");
+ _ = @import("update_tests.zig");
+ _ = @import("mcp_elicitation.zig"); // #768: Computer Use form elicitation
+ _ = @import("skill_runtime_adapter.zig"); // #768: read-only get_app_state adapter
}
diff --git a/src/tool_schema_tests.zig b/src/tool_schema_tests.zig
index 49846dd1..e141f8df 100644
--- a/src/tool_schema_tests.zig
+++ b/src/tool_schema_tests.zig
@@ -384,6 +384,57 @@ test "note_constraint (#381): root-only, append-only, and a valid one-property s
try std.testing.expect(std.mem.indexOf(u8, schema.tools_anthropic_sub, "note_constraint") == null);
}
+fn requiredNames(sch: Value) []const Value {
+ if (sch.object.get("required")) |req| if (req == .array) return req.array.items;
+ return &.{};
+}
+
+fn assertReadFileOptionals(name: []const u8, sch: Value) anyerror!void {
+ if (!std.mem.eql(u8, name, "read_file")) return;
+ try testing.expect(sch.object.get("properties").?.object.get("path") != null);
+ for ([_][]const u8{ "start_line", "end_line", "contains", "compact" }) |field| {
+ try testing.expect(sch.object.get("properties").?.object.get(field) != null);
+ for (requiredNames(sch)) |r| {
+ if (r == .string) try testing.expect(!std.mem.eql(u8, r.string, field));
+ }
+ }
+ var saw_path = false;
+ for (requiredNames(sch)) |r| {
+ if (r == .string and std.mem.eql(u8, r.string, "path")) saw_path = true;
+ }
+ try testing.expect(saw_path);
+}
+
+test "read_file (#761): optional fields stay out of required[] in every emitted catalog" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var found_spec = false;
+ for (schema.root_specs ++ schema.optional_specs) |t| {
+ if (!std.mem.eql(u8, t.name, "read_file")) continue;
+ found_spec = true;
+ const parsed = try std.json.parseFromSliceLeaky(Value, arena, t.schema, .{});
+ try assertReadFileOptionals(t.name, parsed);
+ }
+ try testing.expect(found_spec);
+
+ const saved_gate = no_local_tools.enabled;
+ const saved_imagegen = imagegen.available;
+ defer {
+ no_local_tools.enabled = saved_gate;
+ imagegen.available = saved_imagegen;
+ }
+ no_local_tools.enabled = false;
+ imagegen.available = false;
+ const specs = try schema.effectiveRootSpecs(arena);
+ for ([_]Provider.Kind{ .anthropic, .openai, .responses }) |kind| {
+ const catalog = try schema.renderRootTools(arena, kind, specs, &.{});
+ try forEachServedSchema(arena, catalog, assertReadFileOptionals);
+ try forEachServedSchema(arena, schema.subToolsJson(kind, false), assertReadFileOptionals);
+ }
+}
+
test "subagent desc: Codex sidecar rules, no routing essay on the catalog prefix" {
var found = false;
for (schema.root_specs) |t| if (std.mem.eql(u8, t.name, "subagent")) {
@@ -398,3 +449,14 @@ test "subagent desc: Codex sidecar rules, no routing essay on the catalog prefix
};
try std.testing.expect(found);
}
+
+test "codedb schema exposes per-call local_only (#765)" {
+ var found = false;
+ for (schema.root_specs) |t| if (std.mem.eql(u8, t.name, "codedb")) {
+ found = true;
+ try std.testing.expect(std.mem.indexOf(u8, t.schema, "\"local_only\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, t.schema, "no remote rerank") != null);
+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "local_only") != null);
+ };
+ try std.testing.expect(found);
+}
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index 369661a9..83c13a67 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -13,6 +13,8 @@ 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 update_cmd = @import("update_cmd.zig");
const repl_bash = @import("repl_bash.zig");
const repl_glue = @import("repl_glue.zig");
const session = @import("session.zig");
@@ -149,6 +151,8 @@ pub fn run(
.emergency_fn = emergencyCb,
.idle_wake_fn = idleWakeCb,
.peer_fn = tui_peer.peerCb,
+ .version_fn = versionCb,
+ .update_fn = updateCb,
});
try tui_session.syncRoot(&convo, root);
}
@@ -194,6 +198,11 @@ fn historyCb(ctx: ?*anyopaque, op: tui.HistoryOp) void {
}
}
+fn updateCb(ctx: ?*anyopaque, gpa: Allocator, action: []const u8) ?[]const u8 {
+ const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));
+ return update_cmd.hostAction(c.io, gpa, c.home, action);
+}
+
fn idleWakeCb(ctx: ?*anyopaque, buf: []u8) ?[]const u8 {
const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));
if (job_notify.takeIdleWake(c.io, buf)) |t| return t; // an idle stop waits for a real step boundary (#199)
@@ -201,6 +210,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/update_archive.zig b/src/update_archive.zig
new file mode 100644
index 00000000..35cca139
--- /dev/null
+++ b/src/update_archive.zig
@@ -0,0 +1,200 @@
+//! Pin a release artifact, verify it against that release's SHA256SUMS, and
+//! extract the `graff` binary. Fail closed if the sums file is missing,
+//! malformed, or does not match. No remote scripts.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+pub const Error = error{ VerifyFailed, Malformed, OutOfMemory };
+
+pub fn sha256Hex(bytes: []const u8, out: *[64]u8) []const u8 {
+ var digest: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{});
+ const digits = "0123456789abcdef";
+ for (digest, 0..) |b, i| {
+ out[i * 2] = digits[b >> 4];
+ out[i * 2 + 1] = digits[b & 0x0f];
+ }
+ return out;
+}
+
+/// Find the lowercase hex digest for `asset` in GNU `sha256sum` text.
+/// Fail closed on a missing or malformed line.
+pub fn digestFor(sums: []const u8, asset: []const u8) ?[]const u8 {
+ var lines = std.mem.splitScalar(u8, sums, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0 or line[0] == '#') continue;
+ if (line.len < 66) return null;
+ const hex = line[0..64];
+ for (hex) |c| {
+ const ok = (c >= '0' and c <= '9') or (c >= 'a' and c <= 'f') or (c >= 'A' and c <= 'F');
+ if (!ok) return null;
+ }
+ var rest = std.mem.trim(u8, line[64..], " \t");
+ if (rest.len > 0 and (rest[0] == '*' or rest[0] == ' ')) rest = std.mem.trim(u8, rest, " *");
+ if (std.mem.eql(u8, rest, asset) or std.mem.endsWith(u8, rest, asset)) return hex;
+ }
+ return null;
+}
+
+pub fn verifyAsset(sums: []const u8, asset: []const u8, bytes: []const u8) Error!void {
+ const want = digestFor(sums, asset) orelse return error.VerifyFailed;
+ var hex: [64]u8 = undefined;
+ const got = sha256Hex(bytes, &hex);
+ if (!eqlHex(want, got)) return error.VerifyFailed;
+}
+
+fn eqlHex(a: []const u8, b: []const u8) bool {
+ if (a.len != b.len) return false;
+ var same: u8 = 0;
+ for (a, b) |x, y| same |= std.ascii.toLower(x) ^ std.ascii.toLower(y);
+ return same == 0;
+}
+
+fn isZeroBlock(hdr: []const u8) bool {
+ for (hdr) |b| if (b != 0) return false;
+ return true;
+}
+
+fn tarName(hdr: []const u8) []const u8 {
+ const prefix = memCstr(hdr[345..500]);
+ const name = memCstr(hdr[0..100]);
+ if (prefix.len == 0) return name;
+ return name; // we only match a basename of graff
+}
+
+fn memCstr(s: []const u8) []const u8 {
+ return s[0 .. std.mem.indexOfScalar(u8, s, 0) orelse s.len];
+}
+
+fn tarSize(hdr: []const u8) ?u64 {
+ const field = memCstr(hdr[124..136]);
+ const trimmed = std.mem.trim(u8, field, " \t");
+ if (trimmed.len == 0) return 0;
+ return std.fmt.parseInt(u64, trimmed, 8) catch null;
+}
+
+fn isGraffMember(name: []const u8) bool {
+ const base = std.fs.path.basename(name);
+ return std.mem.eql(u8, base, "graff") or std.mem.eql(u8, base, "graff.exe");
+}
+
+pub fn extractGraff(gpa: Allocator, tar_bytes: []const u8) Error![]u8 {
+ if (tar_bytes.len < 512) return error.Malformed;
+ var off: usize = 0;
+ while (off + 512 <= tar_bytes.len) {
+ const hdr = tar_bytes[off .. off + 512];
+ if (isZeroBlock(hdr)) break;
+ const size = tarSize(hdr) orelse return error.Malformed;
+ const typeflag = hdr[156];
+ off += 512;
+ if (off + size > tar_bytes.len) return error.Malformed;
+ const payload = tar_bytes[off .. off + @as(usize, @intCast(size))];
+ off += std.mem.alignForward(usize, @as(usize, @intCast(size)), 512);
+ if ((typeflag == 0 or typeflag == '0') and isGraffMember(tarName(hdr)))
+ return gpa.dupe(u8, payload);
+ }
+ return error.Malformed;
+}
+
+pub fn gunzip(gpa: Allocator, gz: []const u8) Error![]u8 {
+ var in_reader: std.Io.Reader = .fixed(gz);
+ const window = gpa.alloc(u8, std.compress.flate.max_window_len) catch return error.OutOfMemory;
+ defer gpa.free(window);
+ var dec = std.compress.flate.Decompress.init(&in_reader, .gzip, window);
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ errdefer out.deinit();
+ _ = dec.reader.streamRemaining(&out.writer) catch return error.Malformed;
+ return out.toOwnedSlice() catch return error.OutOfMemory;
+}
+
+pub fn extractVerified(gpa: Allocator, sums: []const u8, asset: []const u8, archive: []const u8) Error![]u8 {
+ try verifyAsset(sums, asset, archive);
+ const tar = gunzip(gpa, archive) catch |err| switch (err) {
+ error.Malformed, error.OutOfMemory => return err,
+ else => return error.Malformed,
+ };
+ defer gpa.free(tar);
+ return extractGraff(gpa, tar);
+}
+
+fn checksumField(hdr: []u8) void {
+ @memset(hdr[148..156], ' ');
+ var sum: u32 = 0;
+ for (hdr[0..512]) |b| sum += b;
+ _ = std.fmt.bufPrint(hdr[148..155], "{o:0>6}", .{sum}) catch {};
+ hdr[155] = 0;
+}
+
+/// Build a one-file ustar + gzip for isolated fixtures. Never used as a
+/// production download path.
+pub fn fixtureArchive(gpa: Allocator, member_name: []const u8, payload: []const u8) ![]u8 {
+ const data_pad = std.mem.alignForward(usize, payload.len, 512);
+ const tar = try gpa.alloc(u8, 512 + data_pad + 1024);
+ errdefer gpa.free(tar);
+ @memset(tar, 0);
+ const hdr = tar[0..512];
+ const name_len = @min(member_name.len, 99);
+ @memcpy(hdr[0..name_len], member_name[0..name_len]);
+ _ = try std.fmt.bufPrint(hdr[100..107], "{o:0>7}", .{@as(u32, 0o0755)});
+ _ = try std.fmt.bufPrint(hdr[124..135], "{o:0>11}", .{payload.len});
+ hdr[156] = '0';
+ @memcpy(hdr[257..262], "ustar");
+ hdr[263] = '0';
+ checksumField(hdr);
+ @memcpy(tar[512 .. 512 + payload.len], payload);
+ const gz = try gzipAlloc(gpa, tar);
+ gpa.free(tar);
+ return gz;
+}
+
+pub fn gzipAlloc(gpa: Allocator, plain: []const u8) ![]u8 {
+ var out_buf: [1 << 16]u8 = undefined;
+ var out: std.Io.Writer = .fixed(&out_buf);
+ const window = try gpa.alloc(u8, std.compress.flate.max_window_len);
+ defer gpa.free(window);
+ const c = try gpa.create(std.compress.flate.Compress);
+ defer gpa.destroy(c);
+ c.* = try std.compress.flate.Compress.init(&out, window, .gzip, .default);
+ try c.writer.writeAll(plain);
+ try c.finish();
+ return gpa.dupe(u8, out.buffered());
+}
+
+pub fn sumsLine(gpa: Allocator, asset: []const u8, bytes: []const u8) ![]u8 {
+ var hex: [64]u8 = undefined;
+ _ = sha256Hex(bytes, &hex);
+ return std.fmt.allocPrint(gpa, "{s} {s}\n", .{ hex, asset });
+}
+
+test "digestFor reads GNU sha256sum lines and rejects junk" {
+ const body = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa graff-x86_64-linux.tar.gz\n";
+ try std.testing.expectEqualStrings(
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ digestFor(body, "graff-x86_64-linux.tar.gz").?,
+ );
+ try std.testing.expect(digestFor("not-a-sum\n", "graff-x86_64-linux.tar.gz") == null);
+ try std.testing.expect(digestFor(body, "graff-aarch64-macos.tar.gz") == null);
+}
+
+test "verify + extract a fixture archive" {
+ const gpa = std.testing.allocator;
+ const archive = try fixtureArchive(gpa, "graff-x86_64-linux/graff", "NEWBIN");
+ defer gpa.free(archive);
+ const sums = try sumsLine(gpa, "graff-x86_64-linux.tar.gz", archive);
+ defer gpa.free(sums);
+ const bin = try extractVerified(gpa, sums, "graff-x86_64-linux.tar.gz", archive);
+ defer gpa.free(bin);
+ try std.testing.expectEqualStrings("NEWBIN", bin);
+}
+
+test "verification fails closed on a wrong digest" {
+ const gpa = std.testing.allocator;
+ const archive = try fixtureArchive(gpa, "graff", "NEWBIN");
+ defer gpa.free(archive);
+ try std.testing.expectError(
+ error.VerifyFailed,
+ extractVerified(gpa, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb graff-x86_64-linux.tar.gz\n", "graff-x86_64-linux.tar.gz", archive),
+ );
+}
diff --git a/src/update_cmd.zig b/src/update_cmd.zig
new file mode 100644
index 00000000..62d69103
--- /dev/null
+++ b/src/update_cmd.zig
@@ -0,0 +1,288 @@
+//! `/update` for the line REPL: check a release, ask a human, install for
+//! the next launch. Yolo, tools, model text, and saved conversations never
+//! authorize an install. ACP / pipes have no TTY picker, so they only check.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const Agent = @import("agent.zig").Agent;
+const pickers = @import("pickers.zig");
+const version_status = @import("version_status.zig");
+const update_target = @import("update_target.zig");
+const update_service = @import("update_service.zig");
+
+pub const installed_for_next_launch = update_target.install_note;
+pub const no_activate_note = update_target.no_activate_note;
+
+var pending_tag: [64]u8 = undefined;
+var pending_tag_len: usize = 0;
+var pending_target: [std.fs.max_path_bytes]u8 = undefined;
+var pending_target_len: usize = 0;
+var test_running: ?[]const u8 = null;
+var test_target: ?[]const u8 = null;
+var test_fetch: ?update_service.Fetch = null;
+var test_asset: ?[]const u8 = null;
+var test_cancel: ?*const std.atomic.Value(bool) = null;
+var test_auto_consent: bool = false;
+var suppress_picker: bool = false;
+
+pub fn resetPending() void {
+ pending_tag_len = 0;
+ pending_target_len = 0;
+}
+
+pub fn setTestHooks(
+ running: ?[]const u8,
+ target: ?[]const u8,
+ fetch: ?update_service.Fetch,
+ asset: ?[]const u8,
+ cancel: ?*const std.atomic.Value(bool),
+ auto_consent: bool,
+) void {
+ test_running = running;
+ test_target = target;
+ test_fetch = fetch;
+ test_asset = asset;
+ test_cancel = cancel;
+ test_auto_consent = auto_consent;
+ if (target == null) resetPending();
+}
+
+fn rememberOffer(tag: []const u8, target: []const u8) void {
+ pending_tag_len = @min(tag.len, pending_tag.len);
+ @memcpy(pending_tag[0..pending_tag_len], tag[0..pending_tag_len]);
+ pending_target_len = @min(target.len, pending_target.len);
+ @memcpy(pending_target[0..pending_target_len], target[0..pending_target_len]);
+}
+
+/// Human `/update install` after a prior `/update` check in this process.
+pub fn consumePending() ?update_service.Consent {
+ if (pending_tag_len == 0) return null;
+ pending_tag_len = 0;
+ pending_target_len = 0;
+ return .human;
+}
+
+pub fn hasPending() bool {
+ return pending_tag_len != 0;
+}
+
+pub fn renderReport(out: *Io.Writer, report: update_service.Report) !void {
+ try out.print("running: v{s} (this process)\n", .{report.running()});
+ if (report.installed()) |inst|
+ try out.print("installed: v{s} ({s})\n", .{ inst, report.target })
+ else if (report.target.len > 0)
+ try out.print("installed: unknown ({s})\n", .{report.target});
+ if (report.latest()) |latest|
+ try out.print("latest: v{s}\n", .{latest})
+ else
+ try out.writeAll("latest: unable to check\n");
+ switch (report.kind) {
+ .available => {
+ try out.print("An update is available. Install v{s} for the next launch? This session stays on v{s}.\n", .{
+ report.latest() orelse "?",
+ report.running(),
+ });
+ try out.writeAll("Type /update install after reviewing, or confirm the picker. ");
+ try out.writeAll(no_activate_note);
+ try out.writeByte('\n');
+ },
+ .already_installed => {
+ try out.writeAll("That release is already installed for the next launch. This session is still running its original version.\n");
+ try out.writeAll(no_activate_note);
+ try out.writeByte('\n');
+ },
+ .current => try out.print("graff is up to date (v{s})\n", .{report.running()}),
+ .newer => try out.print("running v{s} is newer than latest v{s} — not downgrading\n", .{
+ report.running(),
+ report.latest() orelse "?",
+ }),
+ .installed => {
+ try out.writeAll(installed_for_next_launch);
+ try out.writeByte('\n');
+ try out.writeAll(no_activate_note);
+ try out.writeByte('\n');
+ },
+ .offline => try out.writeAll("update check failed — offline or the release feed did not respond\n"),
+ .malformed => try out.writeAll("update check failed — malformed release response (not guessing)\n"),
+ .verify_failed => try out.writeAll("update refused — the artifact did not match the release SHA256SUMS\n"),
+ .permission => try out.writeAll("update refused — the install target is not writable (not escalating privileges)\n"),
+ .cancelled => try out.writeAll("update cancelled — the existing install is unchanged\n"),
+ .busy => try out.writeAll("an update is already installing — this session is unchanged\n"),
+ .unsupported, .package_managed, .development => {
+ try out.writeAll(report.detail);
+ try out.writeByte('\n');
+ },
+ .no_consent => try out.writeAll("update not installed — a human has to confirm in this terminal\n"),
+ }
+}
+
+pub fn renderText(gpa: Allocator, report: update_service.Report) Allocator.Error![]u8 {
+ var aw: Io.Writer.Allocating = .init(gpa);
+ errdefer aw.deinit();
+ renderReport(&aw.writer, report) catch return error.OutOfMemory;
+ return aw.toOwnedSlice();
+}
+
+fn makeOpts(root: *Agent, target: []const u8, fetch: update_service.Fetch, asset: []const u8) update_service.Opts {
+ return .{
+ .io = root.io,
+ .gpa = root.gpa,
+ .running_version = test_running orelse @import("main.zig").harness_version,
+ .target_path = target,
+ .asset_name = asset,
+ .fetch = fetch,
+ .cancel = test_cancel,
+ };
+}
+
+fn productionFetch(root: *Agent, store: *update_service.HttpFetch) update_service.Fetch {
+ store.* = .{
+ .io = root.io,
+ .gpa = root.gpa,
+ .user_agent = "simple-harness/" ++ @import("main.zig").harness_version,
+ };
+ return store.fetch();
+}
+
+fn resolveTarget(root: *Agent, buf: []u8) update_target.Target {
+ if (test_target) |t| return .{ .kind = .supported, .path = t, .detail = "test fixture" };
+ const exe = std.process.executablePathAlloc(root.io, root.gpa) catch
+ return .{ .kind = .unsupported, .path = "", .detail = update_target.explain(.unsupported) };
+ defer root.gpa.free(exe);
+ const resolved = update_target.resolve(exe, root.home, buf);
+ if (resolved.path.ptr == buf.ptr) return resolved;
+ const n = @min(resolved.path.len, buf.len);
+ @memcpy(buf[0..n], resolved.path[0..n]);
+ return .{ .kind = resolved.kind, .path = buf[0..n], .detail = resolved.detail };
+}
+
+fn offerChoices() []const pickers.PickItem {
+ return &.{
+ .{ .name = "Install for the next launch", .desc = "keep this session on the original version" },
+ .{ .name = "Not now", .desc = "leave the install unchanged" },
+ };
+}
+
+fn confirmInstall(root: *Agent, out: *Io.Writer) bool {
+ if (suppress_picker) return false;
+ if (test_auto_consent) return true;
+ const yolo = if (root.approvals) |a| a.yolo else false;
+ _ = yolo; // yolo is not authorization
+ const idx = pickers.listPicker(root, root.arena, out, "Update ›", offerChoices()) orelse return false;
+ return idx == 0;
+}
+
+pub fn tryHandle(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
+ _ = arena;
+ const t = std.mem.trim(u8, line, " \t\r\n");
+ if (!std.mem.eql(u8, t, "/update") and !std.mem.startsWith(u8, t, "/update ")) return false;
+ const arg = std.mem.trim(u8, t["/update".len..], " \t");
+
+ var target_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const target = resolveTarget(root, &target_buf);
+ if (target.kind != .supported) {
+ var r: update_service.Report = .{
+ .kind = switch (target.kind) {
+ .package_managed => .package_managed,
+ .development => .development,
+ else => .unsupported,
+ },
+ .target = target.path,
+ .detail = target.detail,
+ };
+ const run = version_status.stripV(test_running orelse @import("main.zig").harness_version);
+ const n = @min(run.len, r.running_buf.len);
+ @memcpy(r.running_buf[0..n], run[0..n]);
+ r.running_len = n;
+ try renderReport(out, r);
+ try out.flush();
+ return true;
+ }
+ if (update_target.assetName() == null and test_asset == null) {
+ try out.writeAll(update_target.explain(.unsupported));
+ try out.writeByte('\n');
+ try out.flush();
+ return true;
+ }
+
+ var http_store: update_service.HttpFetch = undefined;
+ const fetch = test_fetch orelse productionFetch(root, &http_store);
+ const asset = test_asset orelse update_target.assetName().?;
+ const opts = makeOpts(root, target.path, fetch, asset);
+
+ if (std.mem.eql(u8, arg, "install")) {
+ const consent = consumePending() orelse {
+ try out.writeAll("Run /update first and confirm the release. Model output, tools, and yolo do not authorize an install.\n");
+ try out.flush();
+ return true;
+ };
+ const report = update_service.install(opts, consent);
+ try renderReport(out, report);
+ try out.flush();
+ return true;
+ }
+
+ const report = update_service.inspect(opts);
+ if (report.kind == .available) {
+ if (report.latest_tag()) |tag| rememberOffer(tag, target.path);
+ if (confirmInstall(root, out)) {
+ _ = consumePending();
+ const installed = update_service.install(opts, .human);
+ try renderReport(out, installed);
+ try out.flush();
+ return true;
+ }
+ }
+ try renderReport(out, report);
+ try out.flush();
+ return true;
+}
+
+/// Host callback for the TUI / zigzag repl: `check` or `install`.
+pub fn hostAction(io: Io, gpa: Allocator, home: []const u8, action: []const u8) ?[]const u8 {
+ suppress_picker = true;
+ defer suppress_picker = false;
+ var dummy: Agent = .{
+ .gpa = gpa,
+ .arena = gpa,
+ .io = io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "update",
+ .out = null,
+ .home = home,
+ };
+ var aw: Io.Writer.Allocating = .init(gpa);
+ const line: []const u8 = if (std.mem.eql(u8, action, "install")) "/update install" else "/update";
+ _ = tryHandle(&dummy, gpa, line, &aw.writer) catch {
+ aw.deinit();
+ return null;
+ };
+ return aw.toOwnedSlice() catch {
+ aw.deinit();
+ return null;
+ };
+}
+
+test "yolo and a missing pending offer are not authorization" {
+ resetPending();
+ try std.testing.expect(consumePending() == null);
+ rememberOffer("v0.0.292", "/tmp/fixture/graff");
+ try std.testing.expect(hasPending());
+ try std.testing.expect(consumePending() == .human);
+ try std.testing.expect(!hasPending());
+}
+
+test "success copy names the next launch and refuses /new activation" {
+ try std.testing.expectEqualStrings(
+ "Update installed for the next launch. This session is still running its original version; you can keep working.",
+ installed_for_next_launch,
+ );
+ try std.testing.expect(std.mem.indexOf(u8, no_activate_note, "/new") != null);
+ try std.testing.expect(std.mem.indexOf(u8, no_activate_note, "/resume") != null);
+ try std.testing.expect(std.mem.indexOf(u8, no_activate_note, "do not activate") != null);
+}
diff --git a/src/update_service.zig b/src/update_service.zig
new file mode 100644
index 00000000..1d584bfe
--- /dev/null
+++ b/src/update_service.zig
@@ -0,0 +1,295 @@
+//! Nonfatal, noninteractive in-session update service.
+//!
+//! Pins a GitHub release tag, downloads that tag's tarball + SHA256SUMS,
+//! verifies, and atomically replaces a caller-supplied install path. Never
+//! calls `graff update`, never runs install.sh, never inherits a TTY, never
+//! execs or relaunches this process. Concurrent installs serialize; a
+//! failure or cancel before commit leaves the existing file in place.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const version_status = @import("version_status.zig");
+const update_target = @import("update_target.zig");
+const archive = @import("update_archive.zig");
+const credential_store = @import("credential_store.zig");
+
+pub const FetchError = error{ Offline, Malformed, Permission, OutOfMemory };
+
+pub const Fetch = struct {
+ ctx: ?*anyopaque = null,
+ get: *const fn (ctx: ?*anyopaque, gpa: Allocator, url: []const u8) FetchError![]u8,
+};
+
+pub const Consent = enum { human };
+
+pub const Kind = enum {
+ available,
+ already_installed,
+ current,
+ newer,
+ unsupported,
+ package_managed,
+ development,
+ offline,
+ malformed,
+ verify_failed,
+ permission,
+ cancelled,
+ busy,
+ installed,
+ no_consent,
+};
+
+pub const Report = struct {
+ kind: Kind,
+ target: []const u8 = "",
+ detail: []const u8 = "",
+ running_buf: [64]u8 = undefined,
+ running_len: usize = 0,
+ installed_buf: [64]u8 = undefined,
+ installed_len: usize = 0,
+ latest_buf: [64]u8 = undefined,
+ latest_len: usize = 0,
+ tag_buf: [64]u8 = undefined,
+ tag_len: usize = 0,
+
+ pub fn running(self: *const Report) []const u8 {
+ return self.running_buf[0..self.running_len];
+ }
+ pub fn installed(self: *const Report) ?[]const u8 {
+ return if (self.installed_len == 0) null else self.installed_buf[0..self.installed_len];
+ }
+ pub fn latest(self: *const Report) ?[]const u8 {
+ return if (self.latest_len == 0) null else self.latest_buf[0..self.latest_len];
+ }
+ pub fn latest_tag(self: *const Report) ?[]const u8 {
+ return if (self.tag_len == 0) null else self.tag_buf[0..self.tag_len];
+ }
+};
+
+fn hold(buf: *[64]u8, src: []const u8) usize {
+ const n = @min(src.len, buf.len);
+ @memcpy(buf[0..n], src[0..n]);
+ return n;
+}
+
+pub const Opts = struct {
+ io: Io,
+ gpa: Allocator,
+ running_version: []const u8,
+ target_path: []const u8,
+ asset_name: []const u8,
+ fetch: Fetch,
+ cancel: ?*const std.atomic.Value(bool) = null,
+};
+
+var install_busy = std.atomic.Value(bool).init(false);
+
+pub fn resetBusyForTest() void {
+ install_busy.store(false, .release);
+}
+
+fn cancelled(opts: Opts) bool {
+ const flag = opts.cancel orelse return false;
+ return flag.load(.acquire);
+}
+
+fn tryLock() bool {
+ return install_busy.cmpxchgStrong(false, true, .acq_rel, .acquire) == null;
+}
+
+fn unlock() void {
+ install_busy.store(false, .release);
+}
+
+pub fn readInstalledVersion(io: Io, gpa: Allocator, target_path: []const u8) ?[]u8 {
+ var side_buf: [std.fs.max_path_bytes + 8]u8 = undefined;
+ const side = update_target.versionSidecar(target_path, &side_buf) orelse return null;
+ return Io.Dir.cwd().readFileAlloc(io, side, gpa, .limited(128)) catch return null;
+}
+
+pub fn writeInstalledVersion(io: Io, target_path: []const u8, version: []const u8) void {
+ var side_buf: [std.fs.max_path_bytes + 8]u8 = undefined;
+ const side = update_target.versionSidecar(target_path, &side_buf) orelse return;
+ const parent = std.fs.path.dirname(side) orelse return;
+ var dir = Io.Dir.cwd().openDir(io, parent, .{}) catch return;
+ defer dir.close(io);
+ credential_store.replaceFile(io, dir, std.fs.path.basename(side), version, .default_file) catch {};
+}
+
+fn fetchOwned(opts: Opts, url: []const u8) FetchError![]u8 {
+ return opts.fetch.get(opts.fetch.ctx, opts.gpa, url);
+}
+
+fn latestFromFetch(opts: Opts) FetchError![]u8 {
+ const body = fetchOwned(opts, version_status.repo_api) catch |err| return err;
+ defer opts.gpa.free(body);
+ var tag_buf: [64]u8 = undefined;
+ const tag = version_status.copyTagName(body, &tag_buf) orelse return error.Malformed;
+ return opts.gpa.dupe(u8, tag);
+}
+
+fn snapshot(opts: Opts, kind: Kind, latest_tag: ?[]const u8, installed: ?[]const u8, detail: []const u8) Report {
+ var r: Report = .{ .kind = kind, .target = opts.target_path, .detail = detail };
+ r.running_len = hold(&r.running_buf, version_status.stripV(opts.running_version));
+ if (installed) |v| r.installed_len = hold(&r.installed_buf, version_status.stripV(v));
+ if (latest_tag) |t| {
+ r.tag_len = hold(&r.tag_buf, t);
+ r.latest_len = hold(&r.latest_buf, version_status.stripV(t));
+ }
+ return r;
+}
+
+pub fn inspect(opts: Opts) Report {
+ const installed = readInstalledVersion(opts.io, opts.gpa, opts.target_path);
+ defer if (installed) |v| opts.gpa.free(v);
+ const tag = latestFromFetch(opts) catch |err| return snapshot(opts, switch (err) {
+ error.Offline => .offline,
+ error.Malformed => .malformed,
+ error.Permission => .permission,
+ error.OutOfMemory => .offline,
+ }, null, installed, "could not reach the release feed");
+ defer opts.gpa.free(tag);
+
+ const run = version_status.compare(opts.running_version, tag);
+ if (run.failure == .latest_tag) return snapshot(opts, .malformed, tag, installed, "unparseable release tag");
+
+ if (installed) |inst| {
+ if (version_status.alreadyHasRelease(inst, tag))
+ return snapshot(opts, .already_installed, tag, inst, "the install target is already at this release");
+ }
+
+ return snapshot(opts, switch (run.state) {
+ .current => .current,
+ .older, .dev => if (run.order == .gt) .newer else .available,
+ .newer => .newer,
+ .unable => .malformed,
+ }, tag, installed, "");
+}
+
+fn pinnedUrls(opts: Opts, tag: []const u8, asset_buf: *[512]u8, sums_buf: *[512]u8) error{Malformed}!struct { asset: []const u8, sums: []const u8 } {
+ const asset = std.fmt.bufPrint(asset_buf, "{s}/{s}/{s}", .{
+ version_status.repo_download_base, tag, opts.asset_name,
+ }) catch return error.Malformed;
+ const sums = std.fmt.bufPrint(sums_buf, "{s}/{s}/SHA256SUMS", .{
+ version_status.repo_download_base, tag,
+ }) catch return error.Malformed;
+ return .{ .asset = asset, .sums = sums };
+}
+
+const exe_mode: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit)
+ Io.File.Permissions.fromMode(0o755)
+else
+ .default_file;
+
+fn atomicPlace(io: Io, target_path: []const u8, bytes: []const u8) error{Permission}!void {
+ const parent = std.fs.path.dirname(target_path) orelse return error.Permission;
+ var dir = Io.Dir.cwd().openDir(io, parent, .{}) catch return error.Permission;
+ defer dir.close(io);
+ credential_store.replaceFile(io, dir, std.fs.path.basename(target_path), bytes, exe_mode) catch return error.Permission;
+}
+
+fn existingMatches(io: Io, gpa: Allocator, path: []const u8, bytes: []const u8) bool {
+ const cur = Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(80 * 1024 * 1024)) catch return false;
+ defer gpa.free(cur);
+ return std.mem.eql(u8, cur, bytes);
+}
+
+/// Install the pinned latest release into `opts.target_path`. Requires an
+/// explicit `Consent.human` minted by the TTY picker or `/update install`
+/// after a human `/update` check — yolo, tools, and saved transcripts never
+/// call this.
+pub fn install(opts: Opts, consent: Consent) Report {
+ _ = consent;
+ if (!tryLock()) return snapshot(opts, .busy, null, null, "an update is already installing");
+ defer unlock();
+ if (cancelled(opts)) return snapshot(opts, .cancelled, null, null, "update cancelled");
+
+ const viewed = inspect(opts);
+ switch (viewed.kind) {
+ .available => {},
+ .already_installed, .current, .newer, .offline, .malformed, .permission => return viewed,
+ else => return viewed,
+ }
+ const tag = viewed.latest_tag() orelse return snapshot(opts, .malformed, null, viewed.installed(), "release tag missing");
+ var tag_owned: [64]u8 = undefined;
+ if (tag.len > tag_owned.len) return snapshot(opts, .malformed, null, viewed.installed(), "release tag missing");
+ @memcpy(tag_owned[0..tag.len], tag);
+ const tag_copy = tag_owned[0..tag.len];
+
+ if (cancelled(opts)) return snapshot(opts, .cancelled, tag_copy, viewed.installed(), "update cancelled");
+
+ var asset_url_buf: [512]u8 = undefined;
+ var sums_url_buf: [512]u8 = undefined;
+ const urls = pinnedUrls(opts, tag_copy, &asset_url_buf, &sums_url_buf) catch
+ return snapshot(opts, .malformed, tag_copy, viewed.installed(), "could not pin release URLs");
+
+ const sums = fetchOwned(opts, urls.sums) catch |err| return snapshot(opts, switch (err) {
+ error.Offline => .offline,
+ error.Malformed => .malformed,
+ error.Permission => .permission,
+ error.OutOfMemory => .offline,
+ }, tag_copy, viewed.installed(), "SHA256SUMS unavailable — refusing to install");
+ defer opts.gpa.free(sums);
+ if (cancelled(opts)) return snapshot(opts, .cancelled, tag_copy, viewed.installed(), "update cancelled");
+
+ const tarball = fetchOwned(opts, urls.asset) catch |err| return snapshot(opts, switch (err) {
+ error.Offline => .offline,
+ error.Malformed => .malformed,
+ error.Permission => .permission,
+ error.OutOfMemory => .offline,
+ }, tag_copy, viewed.installed(), "release artifact unavailable");
+ defer opts.gpa.free(tarball);
+ if (cancelled(opts)) return snapshot(opts, .cancelled, tag_copy, viewed.installed(), "update cancelled");
+
+ const bin = archive.extractVerified(opts.gpa, sums, opts.asset_name, tarball) catch |err| return snapshot(opts, switch (err) {
+ error.VerifyFailed => .verify_failed,
+ error.Malformed => .malformed,
+ error.OutOfMemory => .offline,
+ }, tag_copy, viewed.installed(), "artifact verification failed");
+ defer opts.gpa.free(bin);
+ if (cancelled(opts)) return snapshot(opts, .cancelled, tag_copy, viewed.installed(), "update cancelled");
+
+ if (existingMatches(opts.io, opts.gpa, opts.target_path, bin)) {
+ writeInstalledVersion(opts.io, opts.target_path, version_status.stripV(tag_copy));
+ return snapshot(opts, .already_installed, tag_copy, version_status.stripV(tag_copy), "the install target already has these bytes");
+ }
+
+ atomicPlace(opts.io, opts.target_path, bin) catch
+ return snapshot(opts, .permission, tag_copy, viewed.installed(), "install target is not writable — not escalating privileges");
+ writeInstalledVersion(opts.io, opts.target_path, version_status.stripV(tag_copy));
+ return snapshot(opts, .installed, tag_copy, version_status.stripV(tag_copy), update_target.install_note);
+}
+
+pub const HttpFetch = struct {
+ io: Io,
+ gpa: Allocator,
+ user_agent: []const u8,
+ max_bytes: usize = 80 * 1024 * 1024,
+
+ pub fn get(ctx: ?*anyopaque, gpa: Allocator, url: []const u8) FetchError![]u8 {
+ const self: *HttpFetch = @ptrCast(@alignCast(ctx orelse return error.Offline));
+ var client: std.http.Client = .{ .allocator = self.gpa, .io = self.io };
+ defer client.deinit();
+ var aw: Io.Writer.Allocating = .init(gpa);
+ errdefer aw.deinit();
+ const extra = [_]std.http.Header{.{ .name = "Accept", .value = "application/octet-stream" }};
+ const res = client.fetch(.{
+ .location = .{ .url = url },
+ .method = .GET,
+ .response_writer = &aw.writer,
+ .headers = .{ .user_agent = .{ .override = self.user_agent } },
+ .extra_headers = &extra,
+ }) catch return error.Offline;
+ if (@intFromEnum(res.status) != 200) return error.Offline;
+ if (aw.writer.buffered().len > self.max_bytes) return error.Malformed;
+ return aw.toOwnedSlice() catch return error.OutOfMemory;
+ }
+
+ pub fn fetch(self: *HttpFetch) Fetch {
+ return .{ .ctx = self, .get = get };
+ }
+};
diff --git a/src/update_target.zig b/src/update_target.zig
new file mode 100644
index 00000000..be27a254
--- /dev/null
+++ b/src/update_target.zig
@@ -0,0 +1,169 @@
+//! Resolve the on-disk graff the in-session updater may replace.
+//!
+//! Never PATH-lookup `graff` or `install.sh`. A project-local zig-out binary,
+//! a Homebrew/Nix/apt prefix, or an unwritable system path is explained
+//! rather than guessed or escalated.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Allocator = std.mem.Allocator;
+
+pub const Kind = enum { supported, package_managed, development, unsupported };
+
+pub const Target = struct {
+ kind: Kind,
+ path: []const u8,
+ detail: []const u8,
+};
+
+pub const install_note =
+ \\Update installed for the next launch. This session is still running its original version; you can keep working.
+;
+
+pub const no_activate_note =
+ \\/new and /resume keep this process and do not activate the update.
+;
+
+pub fn assetTriple() ?[]const u8 {
+ const os = builtin.os.tag;
+ const arch = builtin.cpu.arch;
+ return switch (os) {
+ .macos => switch (arch) {
+ .aarch64 => "aarch64-macos",
+ .x86_64 => "x86_64-macos",
+ else => null,
+ },
+ .linux => switch (arch) {
+ .aarch64 => "aarch64-linux",
+ .x86_64 => "x86_64-linux",
+ else => null,
+ },
+ else => null,
+ };
+}
+
+pub fn assetName() ?[]const u8 {
+ const triple = assetTriple() orelse return null;
+ return switch (builtin.os.tag) {
+ .macos => if (std.mem.eql(u8, triple, "aarch64-macos"))
+ "graff-aarch64-macos.tar.gz"
+ else
+ "graff-x86_64-macos.tar.gz",
+ .linux => if (std.mem.eql(u8, triple, "aarch64-linux"))
+ "graff-aarch64-linux.tar.gz"
+ else
+ "graff-x86_64-linux.tar.gz",
+ else => null,
+ };
+}
+
+pub fn versionSidecar(path: []const u8, buf: []u8) ?[]const u8 {
+ const n = std.fmt.bufPrint(buf, "{s}.version", .{path}) catch return null;
+ return n;
+}
+
+fn contains(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+fn basenameIs(path: []const u8, name: []const u8) bool {
+ return std.mem.eql(u8, std.fs.path.basename(path), name);
+}
+
+/// Classify an absolute (or user-supplied) executable path. `home` may be
+/// empty; then `$HOME/bin` is not treated as the install.sh target.
+pub fn classify(path: []const u8, home: []const u8) Kind {
+ if (path.len == 0) return .unsupported;
+ if (contains(path, "/Cellar/") or contains(path, "/linuxbrew/") or
+ contains(path, "/Homebrew/") or contains(path, "/homebrew/"))
+ return .package_managed;
+ if (contains(path, "/nix/store/") or contains(path, "/.nix-profile/") or
+ contains(path, "/nix-profile/"))
+ return .package_managed;
+ if (contains(path, "/snap/") or contains(path, "/flatpak/") or
+ contains(path, "/var/lib/flatpak/"))
+ return .package_managed;
+ if (contains(path, "/opt/local/")) return .package_managed;
+ if (std.mem.startsWith(u8, path, "/usr/bin/") or
+ std.mem.startsWith(u8, path, "/bin/") or
+ std.mem.startsWith(u8, path, "/usr/sbin/"))
+ return .package_managed;
+ if (contains(path, "/zig-out/bin/") or contains(path, "/.zig-cache/") or
+ contains(path, "/zig-cache/"))
+ return .development;
+ if (home.len > 0) {
+ if (underHomeBin(path, home, "bin") or underHomeBin(path, home, ".local/bin"))
+ return .supported;
+ }
+ // A writable user prefix that is not a package tree. `/usr/local/bin`
+ // is often Homebrew on Intel Macs — treat it as package-managed when
+ // the basename is graff and it is not under $HOME.
+ if (std.mem.startsWith(u8, path, "/usr/local/") or std.mem.startsWith(u8, path, "/opt/homebrew/"))
+ return .package_managed;
+ if (basenameIs(path, "graff") or basenameIs(path, "graff.exe")) return .supported;
+ return .unsupported;
+}
+
+fn underHomeBin(path: []const u8, home: []const u8, rel: []const u8) bool {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const prefix = std.fmt.bufPrint(&buf, "{s}/{s}/", .{ home, rel }) catch return false;
+ return std.mem.startsWith(u8, path, prefix);
+}
+
+pub fn explain(kind: Kind) []const u8 {
+ return switch (kind) {
+ .supported => "writable user install (install.sh location)",
+ .package_managed => "this install is package-managed — update it with the package manager, not /update",
+ .development => "this process is a development build (zig-out); /update will not overwrite the checkout",
+ .unsupported => "this platform or install location is not supported for in-session updates",
+ };
+}
+
+/// Prefer the running executable when it is a supported user install.
+/// A development process may still name `$HOME/bin/graff` as the future-launch
+/// target when that path is classified supported — never zig-out, never PATH.
+pub fn resolve(running_exe: []const u8, home: []const u8, buf: []u8) Target {
+ const running_kind = classify(running_exe, home);
+ if (running_kind == .supported) {
+ return .{ .kind = .supported, .path = running_exe, .detail = explain(.supported) };
+ }
+ if (running_kind == .package_managed) {
+ return .{ .kind = .package_managed, .path = running_exe, .detail = explain(.package_managed) };
+ }
+ if (home.len > 0) {
+ const home_bin = std.fmt.bufPrint(buf, "{s}/bin/graff", .{home}) catch
+ return .{ .kind = running_kind, .path = running_exe, .detail = explain(running_kind) };
+ if (classify(home_bin, home) == .supported) {
+ return .{
+ .kind = .supported,
+ .path = home_bin,
+ .detail = "install.sh default ($HOME/bin/graff) — this process stays on its original binary",
+ };
+ }
+ }
+ return .{ .kind = running_kind, .path = running_exe, .detail = explain(running_kind) };
+}
+
+test "classify: package trees and zig-out never look supported" {
+ try std.testing.expectEqual(Kind.package_managed, classify("/opt/homebrew/bin/graff", "/Users/me"));
+ try std.testing.expectEqual(Kind.package_managed, classify("/usr/local/Cellar/graff/0.1/bin/graff", "/Users/me"));
+ try std.testing.expectEqual(Kind.package_managed, classify("/nix/store/aaa/bin/graff", "/home/me"));
+ try std.testing.expectEqual(Kind.package_managed, classify("/usr/bin/graff", "/home/me"));
+ try std.testing.expectEqual(Kind.development, classify("/work/codegraff/zig-out/bin/graff", "/home/me"));
+ try std.testing.expectEqual(Kind.supported, classify("/home/me/bin/graff", "/home/me"));
+ try std.testing.expectEqual(Kind.supported, classify("/home/me/.local/bin/graff", "/home/me"));
+}
+
+test "resolve: a zig-out process names $HOME/bin, never the checkout" {
+ var buf: [256]u8 = undefined;
+ const t = resolve("/repo/zig-out/bin/graff", "/home/me", &buf);
+ try std.testing.expectEqual(Kind.supported, t.kind);
+ try std.testing.expectEqualStrings("/home/me/bin/graff", t.path);
+}
+
+test "resolve: Homebrew stays package-managed" {
+ var buf: [256]u8 = undefined;
+ const t = resolve("/opt/homebrew/bin/graff", "/Users/me", &buf);
+ try std.testing.expectEqual(Kind.package_managed, t.kind);
+ try std.testing.expect(std.mem.indexOf(u8, t.detail, "package-managed") != null);
+}
diff --git a/src/update_tests.zig b/src/update_tests.zig
new file mode 100644
index 00000000..f0287ffc
--- /dev/null
+++ b/src/update_tests.zig
@@ -0,0 +1,360 @@
+//! Isolated-fixture acceptance for the in-session updater. Never touches the
+//! developer's live graff executable.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const Agent = @import("agent.zig").Agent;
+const Approvals = @import("approvals.zig").Approvals;
+const archive = @import("update_archive.zig");
+const update_cmd = @import("update_cmd.zig");
+const update_service = @import("update_service.zig");
+const update_target = @import("update_target.zig");
+
+const asset = "graff-x86_64-linux.tar.gz";
+const latest_json = "{\"tag_name\":\"v0.0.292\"}";
+
+const Fixture = struct {
+ archive: []const u8,
+ sums: []const u8,
+ fail: enum { none, offline, malformed, no_sums, bad_sums } = .none,
+ seen_latest_download: std.atomic.Value(bool) = .init(false),
+ fetches: std.atomic.Value(usize) = .init(0),
+ cancel_on_tarball: ?*std.atomic.Value(bool) = null,
+ hold: ?*std.atomic.Value(bool) = null,
+
+ fn get(ctx: ?*anyopaque, gpa: Allocator, url: []const u8) update_service.FetchError![]u8 {
+ const self: *Fixture = @ptrCast(@alignCast(ctx orelse return error.Offline));
+ _ = self.fetches.fetchAdd(1, .monotonic);
+ if (self.hold) |h| {
+ while (h.load(.acquire)) std.Thread.yield() catch {};
+ }
+ if (self.fail == .offline) return error.Offline;
+ if (std.mem.indexOf(u8, url, "/releases/latest") != null) {
+ if (self.fail == .malformed) return gpa.dupe(u8, "{nope") catch return error.OutOfMemory;
+ return gpa.dupe(u8, latest_json) catch return error.OutOfMemory;
+ }
+ if (std.mem.indexOf(u8, url, "/latest/download/") != null) {
+ self.seen_latest_download.store(true, .release);
+ return error.Malformed;
+ }
+ if (std.mem.endsWith(u8, url, "SHA256SUMS")) {
+ if (self.fail == .no_sums) return error.Offline;
+ if (self.fail == .bad_sums)
+ return gpa.dupe(u8, "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc graff-x86_64-linux.tar.gz\n") catch return error.OutOfMemory;
+ return gpa.dupe(u8, self.sums) catch return error.OutOfMemory;
+ }
+ if (self.cancel_on_tarball) |c| c.store(true, .release);
+ return gpa.dupe(u8, self.archive) catch return error.OutOfMemory;
+ }
+
+ fn fetch(self: *Fixture) update_service.Fetch {
+ return .{ .ctx = self, .get = get };
+ }
+};
+
+fn setupArchive(gpa: Allocator) !struct { bytes: []u8, sums: []u8 } {
+ const bytes = try archive.fixtureArchive(gpa, "graff-x86_64-linux/graff", "NEW-GRAFF");
+ errdefer gpa.free(bytes);
+ return .{ .bytes = bytes, .sums = try archive.sumsLine(gpa, asset, bytes) };
+}
+
+fn fixturePath(tmp: *std.testing.TmpDir, io: Io, gpa: Allocator, name: []const u8) ![]u8 {
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &buf);
+ return std.fmt.allocPrint(gpa, "{s}/{s}", .{ buf[0..n], name });
+}
+
+fn opts(io: Io, gpa: Allocator, target: []const u8, fetch: update_service.Fetch, cancel: ?*const std.atomic.Value(bool)) update_service.Opts {
+ return .{
+ .io = io,
+ .gpa = gpa,
+ .running_version = "0.0.289",
+ .target_path = target,
+ .asset_name = asset,
+ .fetch = fetch,
+ .cancel = cancel,
+ };
+}
+
+fn stub(out: *Io.Writer, yolo: bool, approvals: *Approvals) Agent {
+ approvals.* = .{ .yolo = yolo };
+ return .{
+ .gpa = std.testing.allocator,
+ .arena = std.testing.allocator,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = out,
+ .approvals = approvals,
+ .session_name = "live",
+ .home = "/tmp/issue-773-home-must-not-be-used",
+ };
+}
+
+test "successful install replaces only the fixture and keeps the session" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ update_cmd.resetPending();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "graff", .data = "OLD-GRAFF" });
+ const target = try fixturePath(&tmp, io, gpa, "graff");
+ defer gpa.free(target);
+ update_service.writeInstalledVersion(io, target, "0.0.289");
+
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+ var fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums };
+ const before = try Io.Dir.cwd().readFileAlloc(io, target, gpa, .limited(64));
+ defer gpa.free(before);
+ try std.testing.expectEqualStrings("OLD-GRAFF", before);
+
+ var approvals: Approvals = .{ .yolo = true };
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var root = stub(&aw.writer, true, &approvals);
+ const yolo_before = root.approvals.?.yolo;
+ const session_before = root.session_name;
+ const messages_before = root.session_name;
+
+ const report = update_service.install(opts(io, gpa, target, fx.fetch(), null), .human);
+ try std.testing.expectEqual(update_service.Kind.installed, report.kind);
+ try std.testing.expectEqualStrings(update_target.install_note, report.detail);
+ try std.testing.expect(!fx.seen_latest_download.load(.acquire));
+
+ const after = try Io.Dir.cwd().readFileAlloc(io, target, gpa, .limited(64));
+ defer gpa.free(after);
+ try std.testing.expectEqualStrings("NEW-GRAFF", after);
+ try std.testing.expect(root.approvals.?.yolo == yolo_before);
+ try std.testing.expectEqualStrings(session_before, root.session_name);
+ try std.testing.expectEqualStrings(messages_before, root.session_name);
+
+ try std.testing.expect(try update_cmd.tryHandle(&root, gpa, "/new", &aw.writer) == false);
+}
+
+test "already-installed and current versions do not reinstall" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "graff", .data = "OLD-GRAFF" });
+ const target = try fixturePath(&tmp, io, gpa, "graff");
+ defer gpa.free(target);
+ update_service.writeInstalledVersion(io, target, "0.0.292");
+
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+ var fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums };
+ const report = update_service.install(opts(io, gpa, target, fx.fetch(), null), .human);
+ try std.testing.expectEqual(update_service.Kind.already_installed, report.kind);
+ const stayed = try Io.Dir.cwd().readFileAlloc(io, target, gpa, .limited(64));
+ defer gpa.free(stayed);
+ try std.testing.expectEqualStrings("OLD-GRAFF", stayed);
+
+ var current_fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums };
+ var current_opts = opts(io, gpa, target, current_fx.fetch(), null);
+ current_opts.running_version = "0.0.292";
+ update_service.writeInstalledVersion(io, target, "0.0.292");
+ const current = update_service.inspect(current_opts);
+ try std.testing.expectEqual(update_service.Kind.already_installed, current.kind);
+}
+
+test "offline and malformed release responses fail closed" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "graff", .data = "OLD" });
+ const target = try fixturePath(&tmp, io, gpa, "graff");
+ defer gpa.free(target);
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+
+ var offline_fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums, .fail = .offline };
+ try std.testing.expectEqual(update_service.Kind.offline, update_service.inspect(opts(io, gpa, target, offline_fx.fetch(), null)).kind);
+
+ var bad_fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums, .fail = .malformed };
+ try std.testing.expectEqual(update_service.Kind.malformed, update_service.inspect(opts(io, gpa, target, bad_fx.fetch(), null)).kind);
+
+ const stayed = try Io.Dir.cwd().readFileAlloc(io, target, gpa, .limited(64));
+ defer gpa.free(stayed);
+ try std.testing.expectEqualStrings("OLD", stayed);
+}
+
+test "failed verification and missing sums leave the fixture untouched" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "graff", .data = "OLD" });
+ const target = try fixturePath(&tmp, io, gpa, "graff");
+ defer gpa.free(target);
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+
+ var bad: Fixture = .{ .archive = pack.bytes, .sums = pack.sums, .fail = .bad_sums };
+ try std.testing.expectEqual(update_service.Kind.verify_failed, update_service.install(opts(io, gpa, target, bad.fetch(), null), .human).kind);
+
+ var missing: Fixture = .{ .archive = pack.bytes, .sums = pack.sums, .fail = .no_sums };
+ try std.testing.expectEqual(update_service.Kind.offline, update_service.install(opts(io, gpa, target, missing.fetch(), null), .human).kind);
+
+ const stayed = try Io.Dir.cwd().readFileAlloc(io, target, gpa, .limited(64));
+ defer gpa.free(stayed);
+ try std.testing.expectEqualStrings("OLD", stayed);
+}
+
+test "permission errors do not escalate or replace" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+ var fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums };
+ const report = update_service.install(opts(io, gpa, "/proc/graff-must-not-exist/graff", fx.fetch(), null), .human);
+ try std.testing.expectEqual(update_service.Kind.permission, report.kind);
+}
+
+test "cancellation before commit keeps the existing install" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "graff", .data = "OLD" });
+ const target = try fixturePath(&tmp, io, gpa, "graff");
+ defer gpa.free(target);
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+ var cancel = std.atomic.Value(bool).init(false);
+ var fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums, .cancel_on_tarball = &cancel };
+ const report = update_service.install(opts(io, gpa, target, fx.fetch(), &cancel), .human);
+ try std.testing.expectEqual(update_service.Kind.cancelled, report.kind);
+ const stayed = try Io.Dir.cwd().readFileAlloc(io, target, gpa, .limited(64));
+ defer gpa.free(stayed);
+ try std.testing.expectEqualStrings("OLD", stayed);
+}
+
+const Race = struct {
+ o: update_service.Opts,
+ kind: update_service.Kind = .busy,
+ fn run(self: *Race) void {
+ self.kind = update_service.install(self.o, .human).kind;
+ }
+};
+
+test "simultaneous installs serialize; the loser stays busy" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "graff", .data = "OLD" });
+ const target = try fixturePath(&tmp, io, gpa, "graff");
+ defer gpa.free(target);
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+ var hold = std.atomic.Value(bool).init(true);
+ var fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums, .hold = &hold };
+ var first: Race = .{ .o = opts(io, gpa, target, fx.fetch(), null) };
+ var thr = try std.Thread.spawn(.{}, Race.run, .{&first});
+ var spins: usize = 0;
+ while (fx.fetches.load(.monotonic) == 0) : (spins += 1) {
+ if (spins > 1_000_000) return error.InstallNeverStarted;
+ std.Thread.yield() catch {};
+ }
+ var fx2: Fixture = .{ .archive = pack.bytes, .sums = pack.sums };
+ const second = update_service.install(opts(io, gpa, target, fx2.fetch(), null), .human);
+ try std.testing.expectEqual(update_service.Kind.busy, second.kind);
+ hold.store(false, .release);
+ thr.join();
+ try std.testing.expect(first.kind == .installed or first.kind == .already_installed);
+ update_service.resetBusyForTest();
+}
+
+test "/update install without a human pending offer is refused even in yolo" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ update_cmd.resetPending();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "graff", .data = "OLD" });
+ const target = try fixturePath(&tmp, io, gpa, "graff");
+ defer gpa.free(target);
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+ var fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums };
+ update_cmd.setTestHooks("0.0.289", target, fx.fetch(), asset, null, false);
+ defer update_cmd.setTestHooks(null, null, null, null, null, false);
+
+ var approvals: Approvals = .{ .yolo = true };
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var root = stub(&aw.writer, true, &approvals);
+ try std.testing.expect(try update_cmd.tryHandle(&root, gpa, "/update install", &aw.writer));
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "do not authorize") != null);
+ const stayed = try Io.Dir.cwd().readFileAlloc(io, target, gpa, .limited(64));
+ defer gpa.free(stayed);
+ try std.testing.expectEqualStrings("OLD", stayed);
+}
+
+test "/update check then human install reports the next-launch sentence" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ update_service.resetBusyForTest();
+ update_cmd.resetPending();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "graff", .data = "OLD" });
+ const target = try fixturePath(&tmp, io, gpa, "graff");
+ defer gpa.free(target);
+ const pack = try setupArchive(gpa);
+ defer gpa.free(pack.bytes);
+ defer gpa.free(pack.sums);
+ var fx: Fixture = .{ .archive = pack.bytes, .sums = pack.sums };
+ update_cmd.setTestHooks("0.0.289", target, fx.fetch(), asset, null, false);
+ defer update_cmd.setTestHooks(null, null, null, null, null, false);
+
+ var approvals: Approvals = .{};
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var root = stub(&aw.writer, false, &approvals);
+ try std.testing.expect(try update_cmd.tryHandle(&root, gpa, "/update", &aw.writer));
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "running:") != null);
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "v0.0.289") != null);
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "v0.0.292") != null);
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "/new") != null);
+ try std.testing.expect(update_cmd.hasPending());
+
+ aw.clearRetainingCapacity();
+ try std.testing.expect(try update_cmd.tryHandle(&root, gpa, "/update install", &aw.writer));
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), update_target.install_note) != null);
+ const after = try Io.Dir.cwd().readFileAlloc(io, target, gpa, .limited(64));
+ defer gpa.free(after);
+ try std.testing.expectEqualStrings("NEW-GRAFF", after);
+}
+
+test "/new and /resume copy never claims to activate an update" {
+ const new_msg = "new session →";
+ const resume_msg = "resumed";
+ try std.testing.expect(std.mem.indexOf(u8, new_msg, "update") == null);
+ try std.testing.expect(std.mem.indexOf(u8, resume_msg, "activate") == null);
+ try std.testing.expect(std.mem.indexOf(u8, update_target.no_activate_note, "do not activate") != null);
+}
diff --git a/src/version_status.zig b/src/version_status.zig
new file mode 100644
index 00000000..860f2001
--- /dev/null
+++ b/src/version_status.zig
@@ -0,0 +1,211 @@
+//! Running / installed / latest comparison shared by `graff update --check`,
+//! the startup update notice, and the terminal `/update` (and `/version`)
+//! surfaces. One policy so the CLI and the in-session command cannot drift.
+
+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 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);
+ }
+};
+
+pub const repo_api = "https://api.github.com/repos/justrach/codegraff/releases/latest";
+pub const repo_download_base = "https://github.com/justrach/codegraff/releases/download";
+
+pub 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. `latest_tag` is the GitHub tag (with or without `v`);
+/// `running_version` is the build option baked into this process.
+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,
+ };
+}
+
+/// True when `candidate` is a clean release at or newer than `latest_tag`.
+/// Used to refuse a reinstall or implicit downgrade of an already-installed
+/// binary that is current even when this process is older.
+pub fn alreadyHasRelease(installed_version: []const u8, latest_tag: []const u8) bool {
+ const check = compare(installed_version, latest_tag);
+ return switch (check.state) {
+ .current, .newer => true,
+ .dev => check.order == .gt or check.order == .eq,
+ .older, .unable => false,
+ };
+}
+
+pub 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));
+}
+
+/// Leak-free tag extract for tests and the update service: copies into `buf`.
+pub fn copyTagName(body: []const u8, buf: []u8) ?[]const u8 {
+ var parsed = std.json.parseFromSlice(Value, std.heap.page_allocator, body, .{}) catch return null;
+ defer parsed.deinit();
+ if (parsed.value != .object) return null;
+ const tag = parsed.value.object.get("tag_name") orelse return null;
+ if (tag != .string or tag.string.len == 0 or tag.string.len > buf.len) return null;
+ @memcpy(buf[0..tag.string.len], tag.string);
+ return buf[0..tag.string.len];
+}
+
+/// 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 "alreadyHasRelease refuses a reinstall when disk is current or newer" {
+ try std.testing.expect(alreadyHasRelease("0.0.292", "v0.0.292"));
+ try std.testing.expect(alreadyHasRelease("0.0.293", "v0.0.292"));
+ try std.testing.expect(!alreadyHasRelease("0.0.291", "v0.0.292"));
+ try std.testing.expect(!alreadyHasRelease("0.0.291-3-gabc", "v0.0.292"));
+}
+
+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);
+}
diff --git a/src/zai_wire.zig b/src/zai_wire.zig
index 7731747b..e686e7d1 100644
--- a/src/zai_wire.zig
+++ b/src/zai_wire.zig
@@ -67,7 +67,7 @@ pub fn writeChatExtras(s: *std.json.Stringify, provider_id: []const u8, model: [
}
if (!std.mem.eql(u8, provider_id, "kimi") and send_effort) {
try s.objectField("reasoning_effort");
- try s.write(if (is_zai) reasoningEffort(requested) else if (std.mem.eql(u8, requested, "ultra")) "max" else requested);
+ try s.write(if (is_zai) reasoningEffort(requested) else @import("meta_wire.zig").chatEffort(requested, provider_id, model));
}
}