Skip to content

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

Python

feat(doctor): live jobs and budget; TUI /doctor is the real report

Cursor Agent4e6d0b1f8bc5
diff --git a/TUI/catalog.zig b/TUI/catalog.zig
index da899449..0e47f134 100644
--- a/TUI/catalog.zig
+++ b/TUI/catalog.zig
@@ -48,7 +48,7 @@ pub const items = [_]Item{
.{ .name = "/peek", .desc = "See what a live session is doing" },
.{ .name = "/vim-mode", .desc = "Vim keys in the scrollback", .aliases = &.{"/vim"} },
.{ .name = "/help", .desc = "List commands" },
- .{ .name = "/doctor", .desc = "Health check" },
+ .{ .name = "/doctor", .desc = "Health check: goal, jobs, budget" },
.{ .name = "/shortcuts", .desc = "Keyboard shortcuts", .aliases = &.{"/keys"} },
};
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index 935cba68..fadba2fc 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -196,7 +196,13 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {
} else if (std.mem.eql(u8, canon, "/paste")) {
pasteClipboard(self);
} else if (std.mem.eql(u8, canon, "/doctor")) {
- self.pushFmt(.system, "ok · model={s} via {s} · cwd={s} · theme={s} · vim={s}", .{ engine.g_model_name, engine.g_model_provider, engine.g_cwd, @tagName(self.theme_id), onOff(self.vim_mode) }) catch {};
+ var buf: [4096]u8 = undefined;
+ if (engine.g_hud_fn) |f| {
+ const n = f(.doctor, &buf);
+ if (n > 0) self.push(.system, buf[0..n]) catch {};
+ } else {
+ self.push(.system, "doctor unavailable (no session sink)") catch {};
+ }
} else if (std.mem.eql(u8, canon, "/import-claude")) {
self.push(.system, "adopting Claude/Cursor MCP writes ~/.codegraff — run `graff mcp import` from this repo") catch {};
} else if (std.mem.eql(u8, canon, "/jump")) {
diff --git a/TUI/dispatch_command_tests.zig b/TUI/dispatch_command_tests.zig
index ec9ea260..fd361753 100644
--- a/TUI/dispatch_command_tests.zig
+++ b/TUI/dispatch_command_tests.zig
@@ -122,6 +122,48 @@ test "/usage with a session HUD is the cost line, not chars" {
try std.testing.expect(std.mem.indexOf(u8, text, "offline") == null);
}
+test "/doctor uses the session HUD, not a chrome-only status line (#321)" {
+ engine.g_hud_fn = struct {
+ fn f(kind: engine.HudKind, buf: []u8) usize {
+ if (kind != .doctor) return 0;
+ const s = "info GOAL_STATE no standing goal\n no goal is set.\ninfo JOB_STATE no background jobs\n";
+ const n = @min(s.len, buf.len);
+ @memcpy(buf[0..n], s[0..n]);
+ return n;
+ }
+ }.f;
+ defer engine.g_hud_fn = null;
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ _ = applyLine(&m, "/doctor");
+ const text = m.history.items[m.history.items.len - 1].text;
+ try std.testing.expect(std.mem.indexOf(u8, text, "GOAL_STATE") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "ok · model=") == null);
+}
+
+test "/doctor via Term paints GOAL_STATE, not a chrome ok line (#321)" {
+ engine.g_hud_fn = struct {
+ fn f(kind: engine.HudKind, buf: []u8) usize {
+ if (kind != .doctor) return 0;
+ const s = "info GOAL_STATE no standing goal\n no goal is set.\n";
+ const n = @min(s.len, buf.len);
+ @memcpy(buf[0..n], s[0..n]);
+ return n;
+ }
+ }.f;
+ defer engine.g_hud_fn = null;
+ var term: @import("sim.zig").Term = undefined;
+ term.init(std.testing.allocator, 80, 24);
+ defer term.deinit();
+ _ = term.typeText("/doctor");
+ _ = term.enter();
+ const vis = try term.screen();
+ defer std.testing.allocator.free(vis);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "GOAL_STATE") != null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "ok · model=") == null);
+}
+
test "every slash name printed in /help dispatches" {
var m: Model = undefined;
m.setup(std.testing.allocator);
diff --git a/TUI/engine.zig b/TUI/engine.zig
index 6ed896d8..312871d4 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -248,7 +248,7 @@ pub fn bgRun(op: *BgOp) void {
op.done.store(true, .release);
}
-pub const HudKind = enum { debug, usage };
+pub const HudKind = enum { debug, usage, doctor };
pub const HudFn = *const fn (kind: HudKind, buf: []u8) usize;
/// Everything the host frontend hands the loop at startup: the callbacks that
diff --git a/docs/yxlyx-leftovers.md b/docs/yxlyx-leftovers.md
index 76c4b3db..ddc9b6d2 100644
--- a/docs/yxlyx-leftovers.md
+++ b/docs/yxlyx-leftovers.md
@@ -12,7 +12,7 @@ of the same head and is closed as duplicate), `#679` MCP TLS reuse
| Issue | In this repo today | This cut |
| --- | --- | --- |
-| [#321](https://github.com/justrach/codegraff/issues/321) `/doctor` | Goal/todo slice shipped: `/doctor` in `src/doctor.zig` + `commands_misc` dispatch. Checks: `GOAL_STATE`, `GOAL_TODO_EPOCH_MISMATCH`, `STALE_GOAL`, `TODO_EPOCH_ABOVE_GOAL`, `COMPLETION_GATE_ARMED`. Read-only; JSON via `toJson`. | Landed earlier. **Parked:** session-lease, owned-job, listener, and aggregate-budget findings (`DUPLICATE_WORKTREE_OWNER`, `STALE_SESSION_LEASE`, `ORPHANED_OWNED_JOB`, …). Those need a durable job/session registry `doctor.zig` refuses to fake. |
+| [#321](https://github.com/justrach/codegraff/issues/321) `/doctor` | Goal/todo slice plus the live job table and `RunBudget`: `JOB_STATE`, `JOB_SHARES_ROOT_PGID`, `BUDGET_STATE`, `BUDGET_NEAR_LIMIT`, `BUDGET_EXCEEDED`. TUI `/doctor` uses the same report (no chrome-only "ok" line). | Partial. **Parked:** durable session-lease, listener, and orphan-descendant findings (`DUPLICATE_WORKTREE_OWNER`, `STALE_SESSION_LEASE`, `ORPHANED_OWNED_JOB`, `LISTENER_AFTER_CLEANUP`). Those need a registry that does not exist; doctor still refuses to fake them. |
| [#217](https://github.com/justrach/codegraff/issues/217) governed run budget | `src/run_budget.zig`: invocation-wide `--max-model-calls` (default unlimited), concurrency 8, depth 1. Charged across root / children / title / judges / compaction. Exhaustion is a structured stop, not a model plea. `--max-tool-calls` is still root-only. | Partial. **Parked:** finite defaults for `/goal`/`/loop`, wall-time, token, and USD ceilings, descendant tool accounting, slash widening-with-approval. |
| [#220](https://github.com/justrach/codegraff/issues/220) protected verifiers | `--eval` / `--until` scores a command the agent can invoke. ADR [0008](adr/0008-synthetic-evals-use-external-verifiers.md) is the eval-suite rule, not a `/goal` acceptance contract. | **Parked.** Independent verifier stages and hidden tests are a new controller, not a docs tweak. |
| [#306](https://github.com/justrach/codegraff/issues/306) review runaway | Same budget knobs as #217. `/review` is one isolated pass (catalog). No review-specific cycle cap or "confirm before implementing" gate. | **Parked** on the #217 remainder. |
@@ -24,7 +24,9 @@ of the same head and is closed as duplicate), `#679` MCP TLS reuse
## Cheap truth
-The only leftover that already lives as product in this repo is `/doctor`'s
-goal/todo report and the optional `--max-model-calls` envelope. Everything
-else is either another surface (Daytona, iOS, registry) or a new mode
-(idle-server supervisor, protected verifier, review cycle cap).
+The leftover that already lives as product is `/doctor`: goal/todo plus the
+live in-process job table and `RunBudget` (`JOB_STATE`, `JOB_SHARES_ROOT_PGID`,
+`BUDGET_STATE`, `BUDGET_NEAR_LIMIT`, `BUDGET_EXCEEDED`). Line REPL and TUI
+share that report. Everything else is another surface (Daytona, iOS, a
+durable lease/listener/orphan registry) or a new mode (idle-server
+supervisor, protected verifier, review cycle cap).
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 41fb9236..79c476de 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -55,7 +55,7 @@ pub const commands = [_]Item{
.{ .name = "/skills", .usage = "/skills [add|remove <name>]", .desc = "list SKILL.md playbooks + companion tools; add/remove enables or disables one" },
.{ .name = "/plugins", .usage = "/plugins [list|load <name>]", .desc = "list Claude/Cursor/Grok/Codex plugin trees graff is reading in place; load names one" },
.{ .name = "/hooks", .desc = "list lifecycle hooks and the built-in codedb guard" },
- .{ .name = "/doctor", .desc = "read-only health check: goal/todo invariants, and why steering will or will not be appended" },
+ .{ .name = "/doctor", .desc = "read-only health check: goal/todo, live jobs, model-call budget" },
.{ .name = "/btw", .usage = "/btw <question>", .desc = "ask one side question about this conversation — billed, never added, rides the parent cache prefix" },
.{ .name = "/compact", .desc = "compact history into a fresh context (OpenAI server-side when available)" },
.{ .name = "/rewind", .usage = "/rewind [n|<snapshot>]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits; /rewind <snapshot id> restores a sandbox filesystem instead, never the conversation" },
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 5082b8db..f94df501 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -169,7 +169,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
// #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")) {
- const checks = try doctor.run(arena, doctor.snapshot(root, util.unixMs(root.io)));
+ const checks = try doctor.run(arena, try doctor.snapshotWithLive(arena, root, util.unixMs(root.io)));
try out.writeAll(try doctor.render(arena, checks));
try out.flush();
return true;
diff --git a/src/doctor.zig b/src/doctor.zig
index ac17c8f6..f563b122 100644
--- a/src/doctor.zig
+++ b/src/doctor.zig
@@ -12,12 +12,11 @@
//! tested against a literal `State` with an injected clock. `snapshot` is the
//! only place an Agent is touched, and it is a field copy.
//!
-//! This is the goal/todo SLICE of #321. Its session-lease, owned-job, listener
-//! and aggregate-budget checks (DUPLICATE_WORKTREE_OWNER, STALE_SESSION_LEASE,
-//! ORPHANED_OWNED_JOB, JOB_SHARES_ROOT_PGID, LISTENER_AFTER_CLEANUP,
-//! BUDGET_EXCEEDED, ...) need a durable job/session registry that does not
-//! exist yet; they are deliberately absent rather than faked, because a doctor
-//! that reports "healthy" from state it cannot see is worse than no doctor.
+//! Goal/todo plus the live job table and RunBudget (#321). Session-lease,
+//! listener, and orphan-descendant checks (DUPLICATE_WORKTREE_OWNER,
+//! STALE_SESSION_LEASE, ORPHANED_OWNED_JOB, LISTENER_AFTER_CLEANUP) still
+//! need a durable registry that does not exist; they stay absent rather than
+//! reporting "healthy" from state the doctor cannot see.
const std = @import("std");
const Allocator = std.mem.Allocator;
@@ -27,6 +26,7 @@ const Agent = agent_mod.Agent;
const Goal = agent_mod.Goal;
const TodoItem = agent_mod.TodoItem;
const goal_state = @import("goal_state.zig");
+const live = @import("doctor_live.zig");
/// Ordered least-to-most severe: `worst` compares them by tag value, so the
/// declaration order IS the ladder. `error` is spelled as a quoted identifier
@@ -66,6 +66,10 @@ pub const State = struct {
/// age-dependent rules then report rather than suppress, since an unknown
/// age is not evidence of freshness.
now_ms: i64 = 0,
+ /// Live job/budget snapshot (#321). Empty/unlimited is a valid reading.
+ jobs: []const live.JobView = &.{},
+ budget_max: u64 = 0,
+ budget_used: u64 = 0,
};
/// A goal that replaced live work legitimately starts with no checklist of its
@@ -86,6 +90,18 @@ pub fn snapshot(root: *const Agent, now_ms: i64) State {
};
}
+/// Goal/todo plus the in-process job table and RunBudget. Still no lease or
+/// listener registry — those files do not exist, so they stay unreported.
+pub fn snapshotWithLive(arena: Allocator, root: *const Agent, now_ms: i64) Allocator.Error!State {
+ var st = snapshot(root, now_ms);
+ st.jobs = try live.captureJobs(arena, root.io);
+ if (root.run_budget) |b| {
+ st.budget_max = b.max_model_calls;
+ st.budget_used = b.used();
+ }
+ return st;
+}
+
/// Every check, in report order: the always-present evidence line first, then
/// findings. Read-only by construction - it returns text and mutates nothing.
pub fn run(arena: Allocator, st: State) Allocator.Error![]const Check {
@@ -95,6 +111,11 @@ pub fn run(arena: Allocator, st: State) Allocator.Error![]const Check {
if (try staleGoal(arena, st)) |c| try out.append(arena, c);
if (try todoEpochAboveGoal(arena, st)) |c| try out.append(arena, c);
if (try armedCompletionGate(arena, st)) |c| try out.append(arena, c);
+ try live.append(arena, &out, .{
+ .jobs = st.jobs,
+ .budget_max = st.budget_max,
+ .budget_used = st.budget_used,
+ });
return out.toOwnedSlice(arena);
}
@@ -312,10 +333,12 @@ test "doctor: a healthy session reports the evidence line and nothing else (#321
defer arena_state.deinit();
const ar = arena_state.allocator();
- // No goal at all.
+ // No goal at all. Live job/budget evidence is always present and info.
const none = try run(ar, .{});
- try std.testing.expectEqual(@as(usize, 1), none.len);
+ try std.testing.expectEqual(@as(usize, 3), none.len);
try std.testing.expectEqualStrings("GOAL_STATE", none[0].id);
+ try std.testing.expectEqualStrings("JOB_STATE", none[1].id);
+ try std.testing.expectEqualStrings("BUDGET_STATE", none[2].id);
try std.testing.expectEqual(Severity.info, worst(none));
// An active goal working its own checklist: still no warnings (#321
@@ -329,7 +352,7 @@ test "doctor: a healthy session reports the evidence line and nothing else (#321
.todos = &todos,
.now_ms = 5_000_000,
});
- try std.testing.expectEqual(@as(usize, 1), healthy.len);
+ try std.testing.expectEqual(@as(usize, 3), healthy.len);
try std.testing.expectEqual(Severity.info, worst(healthy));
try std.testing.expect(std.mem.indexOf(u8, healthy[0].detail, "1 open of 2 item(s)") != null);
try std.testing.expect(std.mem.indexOf(u8, healthy[0].detail, "steering IS appended") != null);
@@ -466,7 +489,7 @@ test "doctor: render and toJson carry the stable id and severity (#321)" {
// if it is escaped: parse it back rather than trusting the substring above.
const parsed = try std.json.parseFromSlice(std.json.Value, ar, json, .{});
defer parsed.deinit();
- try std.testing.expectEqual(@as(usize, 2), parsed.value.array.items.len);
+ try std.testing.expectEqual(@as(usize, 4), parsed.value.array.items.len);
try std.testing.expectEqualStrings("STALE_GOAL", parsed.value.array.items[1].object.get("id").?.string);
try std.testing.expectEqual(Severity.warn, worst(checks));
}
diff --git a/src/doctor_live.zig b/src/doctor_live.zig
new file mode 100644
index 00000000..39fe15d5
--- /dev/null
+++ b/src/doctor_live.zig
@@ -0,0 +1,202 @@
+//! Live process-table half of /doctor (#321).
+//!
+//! Goal/todo checks stay in doctor.zig. These read the in-memory job pool and
+//! RunBudget — harness-owned state that already exists. They do NOT invent a
+//! durable session-lease or listener registry; those still have nothing to
+//! read, so they stay absent rather than reporting "healthy" from thin air.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+
+const doctor = @import("doctor.zig");
+const Check = doctor.Check;
+const Severity = doctor.Severity;
+const jobs_mod = @import("jobs.zig");
+
+pub const JobView = struct {
+ id: u32 = 0,
+ done: bool = false,
+ shares_root_pgid: bool = false,
+};
+
+pub const Live = struct {
+ jobs: []const JobView = &.{},
+ budget_max: u64 = 0,
+ budget_used: u64 = 0,
+};
+
+/// Copy the live job table. `shares_root_pgid` is measured here (getpgid)
+/// so `append` stays a pure function of the snapshot.
+pub fn captureJobs(arena: Allocator, io: Io) Allocator.Error![]const JobView {
+ jobs_mod.g_jobs.mutex.lockUncancelable(io);
+ defer jobs_mod.g_jobs.mutex.unlock(io);
+ const self_pid = thisPid();
+ var out: std.ArrayList(JobView) = .empty;
+ for (jobs_mod.g_jobs.list.items) |job| {
+ const pid = job.child.id orelse 0;
+ try out.append(arena, .{
+ .id = job.id,
+ .done = job.done,
+ .shares_root_pgid = !job.done and pid != 0 and sharesRootPgid(pid, self_pid),
+ });
+ }
+ return out.toOwnedSlice(arena);
+}
+
+fn thisPid() i32 {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return 0;
+ return @intCast(std.posix.system.getpid());
+}
+
+fn sharesRootPgid(pid: std.posix.pid_t, self_pid: i32) bool {
+ if (builtin.os.tag != .linux) return false;
+ if (self_pid <= 0) return false;
+ const rc = std.os.linux.getpgid(pid);
+ if (@as(isize, @bitCast(rc)) < 0) return false;
+ const pg: i32 = @intCast(@as(u32, @truncate(rc)));
+ return pg == self_pid;
+}
+
+pub fn append(arena: Allocator, out: *std.ArrayList(Check), live: Live) Allocator.Error!void {
+ try out.append(arena, try jobStateLine(arena, live.jobs));
+ if (try jobSharesRoot(arena, live.jobs)) |c| try out.append(arena, c);
+ try out.append(arena, try budgetStateLine(arena, live.budget_max, live.budget_used));
+ if (try budgetFinding(arena, live.budget_max, live.budget_used)) |c| try out.append(arena, c);
+}
+
+fn jobStateLine(arena: Allocator, jobs: []const JobView) Allocator.Error!Check {
+ if (jobs.len == 0) return .{
+ .id = "JOB_STATE",
+ .severity = .info,
+ .title = "no background jobs",
+ .detail = "the in-process job table is empty. Forgotten localhost trees started outside bash are not visible here.",
+ };
+ var running: usize = 0;
+ var done: usize = 0;
+ for (jobs) |j| {
+ if (j.done) done += 1 else running += 1;
+ }
+ return .{
+ .id = "JOB_STATE",
+ .severity = .info,
+ .title = "background jobs in this process",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "{d} job(s) in the table ({d} running, {d} done). This is the live pool, not a durable registry across restarts.",
+ .{ jobs.len, running, done },
+ ),
+ };
+}
+
+fn jobSharesRoot(arena: Allocator, jobs: []const JobView) Allocator.Error!?Check {
+ var n: usize = 0;
+ var first: u32 = 0;
+ for (jobs) |j| {
+ if (!j.shares_root_pgid) continue;
+ if (n == 0) first = j.id;
+ n += 1;
+ }
+ if (n == 0) return null;
+ return .{
+ .id = "JOB_SHARES_ROOT_PGID",
+ .severity = .warn,
+ .title = "a background job shares graff's process group",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "{d} live job(s) share the root PGID (first id {d}). A group kill would take graff down with them.",
+ .{ n, first },
+ ),
+ };
+}
+
+fn budgetStateLine(arena: Allocator, max: u64, used: u64) Allocator.Error!Check {
+ if (max == 0) return .{
+ .id = "BUDGET_STATE",
+ .severity = .info,
+ .title = "model-call budget is unlimited",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "{d} model call(s) this invocation; --max-model-calls is unset so the doctor will not warn on spend.",
+ .{used},
+ ),
+ };
+ return .{
+ .id = "BUDGET_STATE",
+ .severity = .info,
+ .title = "model-call budget",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "{d} of {d} model call(s) used ({d} remaining).",
+ .{ used, max, max -| used },
+ ),
+ };
+}
+
+fn budgetFinding(arena: Allocator, max: u64, used: u64) Allocator.Error!?Check {
+ if (max == 0) return null;
+ if (used >= max) return .{
+ .id = "BUDGET_EXCEEDED",
+ .severity = .@"error",
+ .title = "model-call budget is exhausted",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "{d} of {d} calls used. Further model work is refused until the process exits.",
+ .{ used, max },
+ ),
+ };
+ if (used * 5 >= max * 4) return .{
+ .id = "BUDGET_NEAR_LIMIT",
+ .severity = .warn,
+ .title = "model-call budget is nearly spent",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "{d} of {d} calls used ({d} remaining).",
+ .{ used, max, max - used },
+ ),
+ };
+ return null;
+}
+
+fn find(checks: []const Check, id: []const u8) ?Check {
+ for (checks) |c| {
+ if (std.mem.eql(u8, c.id, id)) return c;
+ }
+ return null;
+}
+
+test "doctor live: empty jobs and unlimited budget are info only" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var out: std.ArrayList(Check) = .empty;
+ try append(ar, &out, .{});
+ try std.testing.expect(find(out.items, "JOB_STATE") != null);
+ try std.testing.expectEqual(Severity.info, find(out.items, "JOB_STATE").?.severity);
+ try std.testing.expect(find(out.items, "JOB_SHARES_ROOT_PGID") == null);
+ try std.testing.expect(find(out.items, "BUDGET_STATE") != null);
+ try std.testing.expect(find(out.items, "BUDGET_NEAR_LIMIT") == null);
+ try std.testing.expect(find(out.items, "BUDGET_EXCEEDED") == null);
+}
+
+test "doctor live: JOB_SHARES_ROOT_PGID and budget ladder (#321)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ const jobs = [_]JobView{
+ .{ .id = 3, .done = false, .shares_root_pgid = true },
+ .{ .id = 4, .done = true, .shares_root_pgid = false },
+ };
+ var out: std.ArrayList(Check) = .empty;
+ try append(ar, &out, .{ .jobs = &jobs, .budget_max = 10, .budget_used = 8 });
+ const share = find(out.items, "JOB_SHARES_ROOT_PGID") orelse return error.TestExpectedShare;
+ try std.testing.expectEqual(Severity.warn, share.severity);
+ try std.testing.expect(std.mem.indexOf(u8, share.detail, "id 3") != null);
+ try std.testing.expectEqual(Severity.warn, find(out.items, "BUDGET_NEAR_LIMIT").?.severity);
+
+ out.clearRetainingCapacity();
+ try append(ar, &out, .{ .budget_max = 4, .budget_used = 4 });
+ try std.testing.expectEqual(Severity.@"error", find(out.items, "BUDGET_EXCEEDED").?.severity);
+ try std.testing.expect(find(out.items, "BUDGET_NEAR_LIMIT") == null);
+}
diff --git a/src/main.zig b/src/main.zig
index 6baf87eb..a37727d5 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -99,6 +99,8 @@ test { // unit_tests' root is main.zig only, so reference every split-out module
_ = commands_session;
_ = commands_model;
_ = commands_misc;
+ _ = @import("doctor.zig");
+ _ = @import("doctor_live.zig");
_ = agent_table;
_ = agent_argstream;
_ = agent_render;
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index cbbaa79e..1d8f88ef 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -28,8 +28,12 @@ const channel_worker = @import("channel_worker.zig");
const util = @import("util.zig");
const obs = @import("obs.zig");
const vision = @import("vision.zig");
+const doctor = @import("doctor.zig");
const builtin = @import("builtin");
+/// Live root for `/doctor`. The HUD callback has no ctx argument.
+var g_doctor_root: ?*agent_mod.Agent = null;
+
/// `graff tui` (and TTY `graff repl`). Bare `graff` stays the default session.
pub fn wantsTui(flags: args.Flags, json_mode: bool) bool {
if (json_mode or flags.oneshot_prompt != null) return false;
@@ -109,6 +113,8 @@ pub fn run(
engine_sink.hosted_frontend = true;
defer engine_sink.hosted_frontend = false;
obs.ensureSession();
+ g_doctor_root = root;
+ defer g_doctor_root = null;
var acp_session: tui_acp.Session = undefined;
acp_session.init(gpa, @as(u64, @bitCast(util.unixMs(io))));
tui_acp.attach(&acp_session);
@@ -373,11 +379,35 @@ fn copyCb(ctx: ?*anyopaque, text: []const u8) bool {
return term == .exited and term.exited == 0;
}
+fn writeDoctor(w: *Io.Writer) void {
+ const root = g_doctor_root orelse {
+ w.writeAll("doctor unavailable (no live session)\n") catch {};
+ return;
+ };
+ var scratch: [8192]u8 = undefined;
+ var fba = std.heap.FixedBufferAllocator.init(&scratch);
+ const arena = fba.allocator();
+ const st = doctor.snapshotWithLive(arena, root, util.unixMs(root.io)) catch {
+ w.writeAll("doctor snapshot failed\n") catch {};
+ return;
+ };
+ const checks = doctor.run(arena, st) catch {
+ w.writeAll("doctor run failed\n") catch {};
+ return;
+ };
+ const text = doctor.render(arena, checks) catch {
+ w.writeAll("doctor render failed\n") catch {};
+ return;
+ };
+ w.writeAll(text) catch {};
+}
+
fn hudCb(kind: tui.HudKind, buf: []u8) usize {
var w: Io.Writer = .fixed(buf);
switch (kind) {
.debug => obs.renderHud(&w) catch {},
.usage => obs.renderUsage(&w) catch {},
+ .doctor => writeDoctor(&w),
}
if (kind == .debug) {
if (tui_acp.sessionId()) |sid| w.print(" acp {s}\n", .{sid}) catch {};
@@ -404,6 +434,13 @@ test "debug HUD names the in-process ACP session" {
try std.testing.expect(std.mem.indexOf(u8, buf[0..n], s.session_id) != null);
}
+test "hudCb doctor without a live root says so" {
+ g_doctor_root = null;
+ var buf: [256]u8 = undefined;
+ const n = hudCb(.doctor, &buf);
+ try std.testing.expect(std.mem.indexOf(u8, buf[0..n], "no live session") != null);
+}
+
test "hudCb usage/debug use the cost-tally renderer, not chars" {
const io = std.testing.io;
const c = &pricing.g_cost;