Skip to content

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

Python

perf(plugins): time the scan and reuse the first walk

Cursor Agenta978b3a0c37a
diff --git a/docs/adr/0007-plugins-are-read-in-place.md b/docs/adr/0007-plugins-are-read-in-place.md
index 89b2acc9..155c3e75 100644
--- a/docs/adr/0007-plugins-are-read-in-place.md
+++ b/docs/adr/0007-plugins-are-read-in-place.md
@@ -50,5 +50,7 @@ config.
- Discover classifies with one readdir per visited directory (not a stat per
marker) and stores skill/agent dirs on the plugin so later merges do not
inspect again. A named `skill` load hits the session catalog; a miss or a
- list still rescans.
+ list still rescans. Production caches the first walk (MCP + fleet + skills
+ share it); tests do not. `/plugins` and the interactive boot line print
+ wall time so a slow home directory is visible.
- Revisit if a user needs to disable one plugin without `GRAFF_NO_PLUGINS`.
diff --git a/src/plugin_scan.zig b/src/plugin_scan.zig
new file mode 100644
index 00000000..5d7dea56
--- /dev/null
+++ b/src/plugin_scan.zig
@@ -0,0 +1,212 @@
+//! Timed, once-per-process plugin discover (ADR 0007).
+//!
+//! Startup used to walk Cursor/Claude/Grok trees three times (MCP merge, fleet
+//! agents, skill catalog). Production keeps the first walk and copies it;
+//! tests stay live so parallel cases cannot share a slot. `/plugins` and the
+//! interactive boot line print the wall time so a slow home directory is
+//! visible instead of a silent minute.
+
+const builtin = @import("builtin");
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const plugins = @import("plugins.zig");
+const layout = @import("plugin_layout.zig");
+
+pub const Stats = struct {
+ ms: i64 = 0,
+ first_ms: i64 = 0,
+ n: usize = 0,
+ visits: usize = 0,
+ cached: bool = false,
+};
+
+pub var last: Stats = .{};
+
+var lock: std.atomic.Value(bool) = .init(false);
+var ready = false;
+var inited = false;
+var store: std.heap.ArenaAllocator = undefined;
+var cached: []const plugins.Plugin = &.{};
+var home_buf: [std.fs.max_path_bytes]u8 = undefined;
+var home_len: usize = 0;
+var proj_buf: [std.fs.max_path_bytes]u8 = undefined;
+var proj_len: usize = 0;
+var first_ms: i64 = 0;
+var first_visits: usize = 0;
+
+fn acquire() void {
+ while (lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
+}
+
+fn release() void {
+ lock.store(false, .release);
+}
+
+pub fn invalidate() void {
+ if (builtin.is_test) return;
+ acquire();
+ defer release();
+ ready = false;
+}
+
+fn elapsedMs(start: Io.Timestamp, io: Io) i64 {
+ return @intCast(@max(0, start.untilNow(io, .awake).toMilliseconds()));
+}
+
+fn dup(arena: Allocator, s: []const u8) []const u8 {
+ if (s.len == 0) return "";
+ return arena.dupe(u8, s) catch "";
+}
+
+fn dupDirs(arena: Allocator, src: []const []const u8) []const []const u8 {
+ if (src.len == 0) return &.{};
+ const out = arena.alloc([]const u8, src.len) catch return &.{};
+ for (src, 0..) |d, i| out[i] = dup(arena, d);
+ return out;
+}
+
+fn copyPlugin(arena: Allocator, p: plugins.Plugin) plugins.Plugin {
+ var root: ?layout.RootSkill = null;
+ if (p.root_skill) |rs| {
+ root = .{ .path = dup(arena, rs.path), .name = dup(arena, rs.name), .dir = dup(arena, rs.dir) };
+ }
+ return .{
+ .name = dup(arena, p.name),
+ .path = dup(arena, p.path),
+ .origin = dup(arena, p.origin),
+ .personal = p.personal,
+ .skills = p.skills,
+ .agents = p.agents,
+ .mcp = p.mcp,
+ .commands = p.commands,
+ .skill_dirs = dupDirs(arena, p.skill_dirs),
+ .agent_dirs = dupDirs(arena, p.agent_dirs),
+ .root_skill = root,
+ };
+}
+
+fn copyList(arena: Allocator, src: []const plugins.Plugin) []const plugins.Plugin {
+ var out: std.ArrayList(plugins.Plugin) = .empty;
+ for (src) |p| out.append(arena, copyPlugin(arena, p)) catch {};
+ return out.items;
+}
+
+fn setKey(home: []const u8, proj: []const u8) void {
+ const h = home[0..@min(home.len, home_buf.len)];
+ const p = proj[0..@min(proj.len, proj_buf.len)];
+ @memcpy(home_buf[0..h.len], h);
+ home_len = h.len;
+ @memcpy(proj_buf[0..p.len], p);
+ proj_len = p.len;
+}
+
+fn keyMatch(home: []const u8, proj: []const u8) bool {
+ return std.mem.eql(u8, home_buf[0..home_len], home) and std.mem.eql(u8, proj_buf[0..proj_len], proj);
+}
+
+/// One-line receipt for `/plugins` and the interactive boot notice.
+pub fn formatStats(arena: Allocator, s: Stats) []const u8 {
+ if (s.cached)
+ return std.fmt.allocPrint(arena, "{d} plugin(s) in {d}ms (cached, first scan {d}ms, {d} dirs)", .{
+ s.n, s.ms, s.first_ms, s.visits,
+ }) catch "";
+ return std.fmt.allocPrint(arena, "{d} plugin(s) in {d}ms ({d} dirs)", .{ s.n, s.ms, s.visits }) catch "";
+}
+
+pub fn format(arena: Allocator) []const u8 {
+ return formatStats(arena, last);
+}
+
+pub fn discover(io: Io, arena: Allocator, home: ?[]const u8, project: Io.Dir) []const plugins.Plugin {
+ const start = Io.Timestamp.now(io, .awake);
+ const home_s = home orelse "";
+ var pbuf: [std.fs.max_path_bytes]u8 = undefined;
+ const pn = project.realPath(io, &pbuf) catch 0;
+ const proj_s = pbuf[0..pn];
+
+ if (!builtin.is_test) {
+ acquire();
+ if (ready and keyMatch(home_s, proj_s)) {
+ const list = copyList(arena, cached);
+ release();
+ last = .{
+ .ms = elapsedMs(start, io),
+ .first_ms = first_ms,
+ .n = list.len,
+ .visits = first_visits,
+ .cached = true,
+ };
+ return list;
+ }
+ release();
+ }
+
+ const list = plugins.discoverFresh(io, arena, home, project);
+ const took = elapsedMs(start, io);
+ last = .{
+ .ms = took,
+ .first_ms = took,
+ .n = list.len,
+ .visits = plugins.last_visits,
+ .cached = false,
+ };
+
+ if (!builtin.is_test) {
+ acquire();
+ defer release();
+ if (!inited) {
+ store = std.heap.ArenaAllocator.init(std.heap.page_allocator);
+ inited = true;
+ } else {
+ _ = store.reset(.retain_capacity);
+ }
+ cached = copyList(store.allocator(), list);
+ setKey(home_s, proj_s);
+ first_ms = took;
+ first_visits = plugins.last_visits;
+ ready = true;
+ }
+ return list;
+}
+
+const testing = std.testing;
+
+test "format: uncached vs cached wording names the milliseconds" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ try testing.expectEqualStrings("3 plugin(s) in 12ms (40 dirs)", formatStats(arena, .{
+ .ms = 12,
+ .first_ms = 12,
+ .n = 3,
+ .visits = 40,
+ .cached = false,
+ }));
+ try testing.expectEqualStrings("3 plugin(s) in 1ms (cached, first scan 840ms, 40 dirs)", formatStats(arena, .{
+ .ms = 1,
+ .first_ms = 840,
+ .n = 3,
+ .visits = 40,
+ .cached = true,
+ }));
+}
+
+test "discover: empty tmp home is zero plugins and the listing names milliseconds" {
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const io = testing.io;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &buf);
+ const home = std.fmt.allocPrint(arena, "{s}/home", .{buf[0..n]}) catch return error.OutOfMemory;
+ const list = plugins.discover(io, arena, home, tmp.dir);
+ try testing.expectEqual(@as(usize, 0), list.len);
+
+ var aw: std.Io.Writer.Allocating = .init(testing.allocator);
+ defer aw.deinit();
+ try testing.expect(try plugins.slashCommand(io, arena, home, "/plugins", &aw.writer));
+ try testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "ms") != null);
+}
diff --git a/src/plugins.zig b/src/plugins.zig
index b00cdb16..5d80cea9 100644
--- a/src/plugins.zig
+++ b/src/plugins.zig
@@ -46,6 +46,7 @@ pub var disabled: bool = false;
pub fn applyEnv(environ_map: anytype) void {
disabled = environ_map.get("GRAFF_NO_PLUGINS") != null;
+ @import("plugin_scan.zig").invalidate();
}
fn join(arena: Allocator, a: []const u8, b: []const u8) []const u8 {
@@ -133,9 +134,21 @@ const project_roots = [_]Spec{
.{ .rel = ".harness/plugins", .origin = "harness" },
};
+/// Dirs walked on the last `discoverFresh` (not a cache hit). `plugin_scan`
+/// copies this into the timed receipt.
+pub var last_visits: usize = 0;
+
+const scan = @import("plugin_scan.zig");
+
/// Every plugin tree under the usual Cursor/Claude/Grok/Codex/graff folders.
/// `project` is the workspace root (cwd in production, a tmp dir in tests).
+/// Production reuses the first walk; tests always scan live.
pub fn discover(io: Io, arena: Allocator, home: ?[]const u8, project: Io.Dir) []const Plugin {
+ return scan.discover(io, arena, home, project);
+}
+
+pub fn discoverFresh(io: Io, arena: Allocator, home: ?[]const u8, project: Io.Dir) []const Plugin {
+ last_visits = 0;
if (off()) return &.{};
var list: std.ArrayList(Plugin) = .empty;
var visits: usize = 0;
@@ -154,6 +167,7 @@ pub fn discover(io: Io, arena: Allocator, home: ?[]const u8, project: Io.Dir) []
}
}
}
+ last_visits = visits;
return list.items;
}
@@ -272,7 +286,7 @@ pub fn slashCommand(io: Io, arena: Allocator, home: []const u8, line: []const u8
if (p.skills) try out.writeAll(" skills: on-demand via the skill tool / /skills\n");
if (p.agents) try out.writeAll(" agents: in the fleet\n");
if (p.mcp) try out.writeAll(" mcp: in the merge (needs /mcp trust or --yolo)\n");
- try out.writeAll("hooks are not run.\n");
+ try out.print("hooks are not run. {s}\n", .{scan.format(arena)});
try out.flush();
return true;
}
@@ -281,11 +295,11 @@ pub fn slashCommand(io: Io, arena: Allocator, home: []const u8, line: []const u8
return true;
}
if (list.len == 0) {
- try out.writeAll("no plugins discovered. graff reads Claude/Cursor/Grok/Codex trees in place (skills/, commands/, agents/, mcp.json, root SKILL.md). nothing to copy; GRAFF_NO_PLUGINS=1 disables.\n");
+ try out.print("no plugins discovered ({d}ms, {d} dirs). graff reads Claude/Cursor/Grok/Codex trees in place (skills/, commands/, agents/, mcp.json, root SKILL.md). nothing to copy; GRAFF_NO_PLUGINS=1 disables.\n", .{ scan.last.ms, scan.last.visits });
try out.flush();
return true;
}
- try out.print("{d} plugin(s) (in-place, Claude layout, not copied):\n", .{list.len});
+ try out.print("{s} (in-place, Claude layout, not copied):\n", .{scan.format(arena)});
for (list) |p| {
try out.print(" {s} [{s}/{s}]", .{ p.name, p.origin, if (p.personal) "user" else "project" });
if (p.skills) try out.writeAll(" skills");
@@ -457,6 +471,7 @@ test "slashCommand: /plugins lists origin and refuses unrelated lines" {
try testing.expect(!(try slashCommand(testing.io, arena_state.allocator(), "", "/skills", &aw.writer)));
try testing.expect(try slashCommand(testing.io, arena_state.allocator(), "", "/plugins", &aw.writer));
try testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "plugin") != null);
+ try testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "ms") != null);
}
test "applyEnv: GRAFF_NO_PLUGINS disables discover and /plugins" {
diff --git a/src/session_start.zig b/src/session_start.zig
index be02598f..7e3ee858 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -41,6 +41,7 @@ const skills = @import("skills.zig");
const mcp = @import("mcp.zig");
const mcp_cli = @import("mcp_cli.zig");
const mcp_config = @import("mcp_config.zig");
+const plugin_scan = @import("plugin_scan.zig");
const adopt = @import("adopt.zig");
const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: the eager-vs-deferred policy for MCP tool schemas
const jobs = @import("jobs.zig");
@@ -402,6 +403,13 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr
// so an unguarded line here would corrupt the head of every --json run.
const quiet = json_mode or flags.oneshot_prompt != null or environ_map.get("GRAFF_REPL_DEBUG") == null;
const merged = mcp_config.load(io, arena, Io.Dir.cwd(), mcp_config_path, global_path, home);
+ // Interactive only: json/one-shot stdout cannot carry chatter. A slow
+ // Cursor/Claude tree used to look like a hung boot; this line is the clock.
+ if (!json_mode and flags.oneshot_prompt == null) {
+ const st = plugin_scan.last;
+ if (st.n > 0 or st.ms > 20)
+ sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "plugins: {s}", .{plugin_scan.format(arena)})));
+ }
// #416: resolve eager-vs-deferred BEFORE anything connects, so the first
// catalog render already knows which servers pay their schemas up front.
mcp_schema_gate.configure(arena, merged, environ_map);
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 802e247e..f61bf607 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -129,6 +129,7 @@ const peer_target = @import("peer_target.zig"); // exact DM / goal targeting
const workspace_switch = @import("workspace_switch.zig"); // ADR 0006 mid-session worktree switch
const plugins = @import("plugins.zig"); // ADR 0007 in-place plugin / foreign MCP discovery
const plugin_layout = @import("plugin_layout.zig"); // Claude commands/ + inline MCP + ${CLAUDE_PLUGIN_ROOT}
+const plugin_scan = @import("plugin_scan.zig"); // timed discover + production cache
// #345: the global-vs-project MCP config merge. mcp.zig does reference its
// decls, but the hook makes the coverage explicit rather than contingent on
@@ -263,6 +264,7 @@ test {
_ = workspace_switch;
_ = plugins;
_ = plugin_layout;
+ _ = plugin_scan;
_ = shutdown_trace;
_ = credential_store;
_ = engine_events;