graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
perf: accelerate startup and trace recipe outcomes
Rach Pradhan7e08374c4bb9
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex bcf94323..bd1b29e4 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -29,7 +29,7 @@ jobs:# (anonymous, opt out with --no-telemetry / GRAFF_NO_TELEMETRY).TELEMETRY_ENDPOINT="https://harness-telemetry.rachpradhan.workers.dev"for target in aarch64-macos x86_64-macos x86_64-linux aarch64-linux x86_64-windows aarch64-windows; do- zig build -Doptimize=ReleaseFast -Dtarget="$target" -Dversion="$VERSION" -Dtelemetry-endpoint="$TELEMETRY_ENDPOINT"+ zig build graff -Doptimize=ReleaseFast -Dtarget="$target" -Dversion="$VERSION" -Dtelemetry-endpoint="$TELEMETRY_ENDPOINT"name="graff-$target"mkdir "$name"# Windows targets emit graff.exe; every other target emits graff.@@ -48,5 +48,10 @@ jobs:env:GH_TOKEN: ${{ github.token }}run: |+ notes=(--generate-notes)+ notes_file="docs/releases/${GITHUB_REF_NAME}.md"+ if [ -f "$notes_file" ]; then+ notes=(--notes-file "$notes_file")+ figh release create "$GITHUB_REF_NAME" graff-*.tar.gz SHA256SUMS install.sh \- --title "$GITHUB_REF_NAME" --generate-notes+ --title "$GITHUB_REF_NAME" --draft "${notes[@]}"diff --git a/README.md b/README.mdindex 2de97d47..403f30ee 100644--- a/README.md+++ b/README.md@@ -770,6 +770,14 @@ inspectable. The system prompt tells the agent how to locate the file, so"profile yourself" or "why was that slow?" makes it answer from data. `/trace`toggles tracing and prints the exact path.+Startup also emits structured `startup_phase` receipts with cumulative and+per-phase milliseconds. Each turn emits a `recipe_outcome` keyed by an exact+recipe fingerprint: provider, model, effort, prompt, toolset, harness version,+and an observational task class, alongside success, latency, model/tool calls,+tool errors, uncached/cache-read tokens, and estimated cost. These records are+the data plane for task-aware recipe comparison; they do not silently switch+models or effort levels.+Long tool results are stored exactly under `.graff/tool-results/`; model historyreceives a short preview and an inspectable file pointer instead. Responsesrequests are explicitly capped at 16k output tokens (4k for compaction and 64diff --git a/build.zig b/build.zigindex 183c8c81..c0eeb66a 100644--- a/build.zig+++ b/build.zig@@ -54,10 +54,13 @@ pub fn build(b: *std.Build) void {// standalone graff-repl exe below). The repo's first dependency.const zigzag = b.dependency("zigzag", .{ .target = target, .optimize = optimize });exe.root_module.addImport("zigzag", zigzag.module("zigzag"));- b.installArtifact(exe);+ const install_graff = b.addInstallArtifact(exe, .{});+ b.getInstallStep().dependOn(&install_graff.step);+ const graff_step = b.step("graff", "Build and install only the release CLI");+ graff_step.dependOn(&install_graff.step);const run_cmd = b.addRunArtifact(exe);- run_cmd.step.dependOn(b.getInstallStep());+ run_cmd.step.dependOn(&install_graff.step);const run_step = b.step("run", "Run the harness");run_step.dependOn(&run_cmd.step);diff --git a/docs/hyperagents.md b/docs/hyperagents.mdindex dfeab5cb..156285fd 100644--- a/docs/hyperagents.md+++ b/docs/hyperagents.md@@ -95,6 +95,13 @@ code (Python/TS), not in the harness:and children counts — everything DGM-H's parent selection needs:`sᵢ = σ(λ(αᵢ − α_mid))`, `hᵢ = 1/(1+nᵢ)`, sample ∝ sᵢ·hᵢ (λ=10, α_mid =mean of top-3, per the paper).+- **Recipe outcome** = every root turn also binds the prompt genome to its+ exact provider/model, reasoning effort, toolset hash, harness version, and+ coarse task class. Success, latency, model/tool calls, tool errors,+ cache/uncached tokens, and estimated cost remain separate objectives so a+ later selector can maintain a Pareto frontier instead of promoting a cheap+ failure through one gameable scalar. This is observational today; automatic+ model/effort promotion requires signed recipe provenance and canary rollback.- **Recitation / memory** (the capability DGM-H invents for itself —performance trackers, IMPROVEMENTS.md): the harness already encouragesfilesystem-as-context (Manus lessons); the driver should keep itsdiff --git a/docs/releases/v0.0.211.md b/docs/releases/v0.0.211.mdnew file mode 100644index 00000000..0acc7381--- /dev/null+++ b/docs/releases/v0.0.211.md@@ -0,0 +1,62 @@+# 11.4x faster one-shot runs, bounded MCP shutdown, and recipe outcomes++v0.0.211 removes the largest fixed costs from short CLI, SDK, and automation+runs. It also adds the observational data needed to compare complete agent+recipes without silently changing anyone's model, effort, or tools.++## Startup and shutdown performance++- A measured one-shot startup and exit path fell from `1.409 s +/- 0.048 s` on+ v0.0.210 to `123.4 ms +/- 3.9 ms`, an 11.42x improvement on the same machine.+- The patched core starts and exits in about 4.3 ms when the optional companion+ is absent. Remaining time in the full measurement belongs to companion+ discovery and teardown.+- Kimi's live account catalog is now lazy. Unrelated providers do not pay for a+ Kimi network request at startup, while Kimi selection, `/model`, and `/models`+ still load the current account catalog on demand.+- MCP stdio servers receive a clean EOF shutdown, followed by a bounded 100 ms+ grace period. A server that refuses to exit is force-terminated and reaped,+ preventing slow exits and orphaned processes.+- Release jobs now build the `graff` CLI directly instead of also compiling the+ standalone development REPL for every target.++## Inspectable performance receipts++- Startup traces now include structured `startup_phase` records with phase and+ cumulative milliseconds.+- Every root turn emits a `recipe_outcome` for the exact provider, model,+ reasoning effort, prompt, toolset, harness version, and coarse task class.+- Outcomes keep success, latency, model calls, tool calls, tool errors,+ uncached tokens, cache-read tokens, and estimated cost as separate objectives.+ The included Pareto comparison foundation cannot reward a cheap failure by+ collapsing everything into one score.+- Signed scores link back to local recipe metadata for later analysis.+- Recipe tracking is observational in this release. Automatic model or effort+ routing remains disabled until signed provenance, canaries, and rollback are+ in place.++## Reliability and compatibility++- Dynamic Kimi catalogs continue to expose account-enabled models such as K3,+ their live context windows, and supported thinking controls.+- Kimi credential entry refreshes the live catalog immediately.+- Existing command, model preference, SDK, transport, trace, and signed-score+ behavior remains compatible.++## Validation and distribution++- The full Zig test suite, formatting checks, build, and diff checks pass on+ Zig `0.17.0-dev.813+2153f8143`.+- Deterministic JSON controls pass all 19 cases, and saved model preference tests+ pass.+- ReleaseFast cross-builds pass for Apple silicon macOS, Intel macOS, x86_64+ Linux, arm64 Linux, x86_64 Windows, and arm64 Windows.+- Both macOS binaries are Developer ID signed and submitted to Apple's+ notarization service before this draft is published.+- Every published archive is covered by `SHA256SUMS`.++```sh+curl -fsSL https://raw.githubusercontent.com/justrach/codegraff/main/install.sh | sh+```++**Full changelog:** https://github.com/justrach/codegraff/compare/v0.0.210...v0.0.211diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 9c32417c..8b6029ee 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -34,6 +34,8 @@ const pricing = @import("pricing.zig");const default_context = pricing.default_context;const g_cost = &pricing.g_cost;const models_cache = @import("models_cache.zig");+const kimi_catalog = @import("kimi_catalog.zig");+const providers = @import("providers.zig");const command_catalog = @import("command_catalog.zig");const serde = @import("serde.zig");@@ -261,7 +263,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,}if (std.mem.eql(u8, line, "/models")) {root.ensureStoredKeys(keys);- root.ensureModelCatalog(keys.*);+ providers.ensureModelQueryCatalogs(root, keys.*, "");try out.writeAll("model ctx compact@ provider key vision\n");for (pricing.models()) |m| {const has_key = keys.get(m.provider) != null;@@ -278,6 +280,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,});}try out.print("(codex catalog: {s})\n", .{models_cache.codex_catalog_source});+ try out.print("(kimi catalog: {s})\n", .{kimi_catalog.catalog_source});try out.print("(unknown models: {d}k ctx; claude* → anthropic, else → codegraff)\n", .{default_context / 1000});// Live LM Studio models: query the local server so loaded models show up// in /models without hand-typing their ids. Best-effort and silent if thediff --git a/src/commands_model.zig b/src/commands_model.zigindex 78889b7e..1c42ac62 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -27,6 +27,7 @@ const fetchOpenAIModels = keys_cli.fetchOpenAIModels;const harness_version = main_mod.harness_version;const pricing = @import("pricing.zig");+const kimi_catalog = @import("kimi_catalog.zig");const resolveModelName = pricing.resolveModelName;const pickers = @import("pickers.zig");@@ -126,7 +127,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (std.mem.startsWith(u8, line, "/model") and !std.mem.startsWith(u8, line, "/models")) {root.ensureStoredKeys(keys);const arg = std.mem.trim(u8, line["/model".len..], " \t");- if (providers.modelQueryMayUseCodex(arg)) root.ensureModelCatalog(keys.*);+ providers.ensureModelQueryCatalogs(root, keys.*, arg);if (arg.len == 0) {if (main_mod.use_color) { // interactive TTY → fuzzy pickerif (modelPicker(root, keys, arena, out)) |idx| {@@ -437,6 +438,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,const home = root.home;const saved = storeKey(root.io, root.gpa, arena, home, pid, key); // persistkeys.sources[idx.?] = if (saved) .stored else .session;+ if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, home, keys.values[idx.?].?);try out.print("✓ {s} key set (live{s}) — now: /model {s}\n", .{ pid, if (saved) " + Keychain" else "", pid });try out.flush();return true;diff --git a/src/kimi_catalog.zig b/src/kimi_catalog.zigindex 8e5b2c04..c62f61b8 100644--- a/src/kimi_catalog.zig+++ b/src/kimi_catalog.zig@@ -19,6 +19,7 @@ pub const device_model = @tagName(builtin.os.tag) ++ " " ++ @tagName(builtin.cpupub const os_version = @tagName(builtin.os.tag);pub var device_id: []const u8 = "unknown";pub var catalog_source: []const u8 = "baked offline fallback";+var catalog_attempted = false;const private_file_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o600) else .default_file;const private_dir_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o700) else .default_dir;@@ -188,6 +189,7 @@ pub fn load(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, access:catalog_source = "baked fallback — no Kimi login";return false;}+ catalog_attempted = true;var client: std.http.Client = .{ .allocator = gpa, .io = io };defer client.deinit();var aw: Io.Writer.Allocating = .init(arena);@@ -219,6 +221,14 @@ pub fn load(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, access:return true;}+/// Demand-load the account catalog at most once per process. Startup calls+/// this only when Kimi can actually win model selection; `/model` and+/// `/models` call it when their catalog surfaces become visible.+pub fn ensure(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, access: []const u8) void {+ if (catalog_attempted) return;+ _ = load(io, gpa, arena, home, access);+}+test "parseModels accepts Kimi aliases and K3 context windows" {var state = std.heap.ArenaAllocator.init(std.testing.allocator);defer state.deinit();diff --git a/src/main.zig b/src/main.zigindex 244589e8..b3bf8bd9 100644--- a/src/main.zig+++ b/src/main.zig@@ -5,12 +5,6 @@const std = @import("std");const Io = std.Io;-fn bootMark(io: Io, started: Io.Timestamp, enabled: bool, label: []const u8) void {- if (!enabled) return;- const ms = @max(0, started.untilNow(io, .awake).toMilliseconds());- std.debug.print("[boot +{d}ms] {s}\n", .{ ms, label });-}-/// #131: pre-load the shared HTTP client's CA bundle single-threaded, so the/// parallel subagents that share this client (on pool threads) never race the/// lazy CA-bundle rescan on their first concurrent HTTPS connect. Zig std flags@@ -131,6 +125,7 @@ test {_ = mainloop;_ = args;_ = startup;+ _ = startup_timing;_ = session_start;_ = session_run;_ = provider_mod;@@ -248,11 +243,11 @@ const cli = @import("cli.zig");const args = @import("args.zig");// Post-arg-parse setup (resolveKeys, buildSystemPrompt, early subcommand dispatch) lives in startup.zig; everything after credentials/http.Client exist lives in sibling session_start.zig.const startup = @import("startup.zig");+const startup_timing = @import("startup_timing.zig");const session_start = @import("session_start.zig");const session_run = @import("session_run.zig");pub fn main(init: std.process.Init) !void {- const boot_started = Io.Timestamp.now(init.io, .awake);- const boot_debug = init.environ_map.get("GRAFF_BOOT_DEBUG") != null;+ var boot = startup_timing.Tracker.init(init.io, init.environ_map.get("GRAFF_BOOT_DEBUG") != null);const gpa = init.gpa;const io = init.io;const arena = init.arena.allocator();@@ -278,7 +273,7 @@ pub fn main(init: std.process.Init) !void {// CLI flags: the Flags struct + parsing loop live in args.zig; downstream code reads flags.<name> in place of ~27 locals this block used to declare.const flags = try args.parse(init);var invocation_budget: run_budget_mod.RunBudget = .{ .max_model_calls = max_model_calls };- bootMark(init.io, boot_started, boot_debug, "args");+ boot.mark(init.io, "args");// GRAFF_CODEX_URL: override the codex responses endpoint (localhost mocks / integration tests). Parsed BEFORE subcommand dispatch and// resolveKeys — `graff models [refresh]` fetches the catalog inside runSubcommand and the initial Keys.build runs inside resolveKeys.// environ_map slices are process-lifetime (resolveKeys stores them into Keys the same way), so the value is kept as-is without duping.@@ -290,7 +285,7 @@ pub fn main(init: std.process.Init) !void {// Credential/model resolution (env vars → on-disk logins → `harness key set` store, env always wins; then --model or the last-saved model) lives// in startup.zig as resolveKeys() — pure over env/disk/arena, safe to call outside main()'s own stack frame.const resolved_keys = try startup.resolveKeys(io, gpa, arena, init.environ_map, flags.model_flag);- bootMark(io, boot_started, boot_debug, "credentials/model");+ boot.mark(io, "credentials/model");var keys = resolved_keys.keys;const default_provider = resolved_keys.default_provider;const stale_saved_model = resolved_keys.stale_saved_model;@@ -301,7 +296,7 @@ pub fn main(init: std.process.Init) !void {var client_ready: Io.Event = .unset;http.g_client_ready = &client_ready;var client_warm_fut = io.async(prewarmCaBundleTask, .{ &client, gpa, io, &client_ready });- bootMark(io, boot_started, boot_debug, "CA warm scheduled");+ boot.mark(io, "CA warm scheduled");defer {_ = client_warm_fut.await(io);http.g_client_ready = null;@@ -329,7 +324,7 @@ pub fn main(init: std.process.Init) !void {const run_trajectory_path = try trace.trajectoryPath(arena, identity.run_id);try session_start.setupWorktreeAndBanner(io, gpa, arena, init.environ_map, flags, out, run_trace_path, codex_account, stale_saved_model, preferred_provider, default_provider);session_start.loadScoreSigningKey(io, arena, init.environ_map);- bootMark(io, boot_started, boot_debug, "banner");+ boot.mark(io, "banner");// Session trace (best-effort: a failed open just disables tracing).var trace_buf: [8 * 1024]u8 = undefined;@@ -343,6 +338,7 @@ pub fn main(init: std.process.Init) !void {.identity = identity,.path = run_trace_path,};+ boot.attach(&tracer);// One trajectory file per run; the archive reader scans the directory.// Node ids restart per run and cross-run lineage threads through prompt_sha.@@ -380,7 +376,7 @@ pub fn main(init: std.process.Init) !void {// auto-connect only with --yolo (trusted) or explicit per-session consent; otherwise start with an empty (but live) registry so `/mcp add`// still works.var registry_storage = try session_start.initRegistryConsent(io, gpa, arena, out, in, flags, mcp_config_path, use_color, json_mode);- bootMark(io, boot_started, boot_debug, "MCP registry");+ boot.mark(io, "MCP registry");defer registry_storage.deinit();const registry: ?*mcp.Registry = ®istry_storage;// Per-skill/companion opt-outs, animation/theme settings, and the --selftest-spinner headless render live in session_start.zig. The theme/@@ -395,16 +391,16 @@ pub fn main(init: std.process.Init) !void {out.flush() catch {};};if (theme_setup.should_exit) return;- bootMark(io, boot_started, boot_debug, "settings/theme");+ boot.mark(io, "settings/theme");try session_start.connectCompanion(io, ®istry_storage, flags, out, json_mode);const mcp_tools: []const mcp.Tool = registry_storage.tools;// If the metered companion connected, probe its license once so the note below can lean into paid tools (vs the conservative free-codedb note).if (mcpServerConnected(mcp_tools, "codedbpro")) g_codedbpro_licensed = probeCodedbproLicensed(gpa, io);- bootMark(io, boot_started, boot_debug, "companion");+ boot.mark(io, "companion");var approvals: Approvals = undefined;try session_run.initApprovalsHooksFleet(io, gpa, arena, init.environ_map, &approvals, flags, out, json_mode);- bootMark(io, boot_started, boot_debug, "approvals/hooks/fleet");+ boot.mark(io, "approvals/hooks/fleet");defer {for (approvals.prefixes.items) |p| gpa.free(p);approvals.prefixes.deinit(gpa);@@ -426,7 +422,7 @@ pub fn main(init: std.process.Init) !void {);const sys_normal = sys_prompt.sys_normal;const sys_strict = sys_prompt.sys_strict;- bootMark(io, boot_started, boot_debug, "system prompt");+ boot.mark(io, "system prompt");var snaps: Snapshots = .{ .gpa = gpa, .io = io };defer snaps.deinit();@@ -442,7 +438,7 @@ pub fn main(init: std.process.Init) !void {root.scratch_arena = &scratch_state; // #124: route the root's transient parse garbage here; reset per request()root.fallback_active = stale_saved_model != null;root.fallback_blocked = root.fallback_active and preferred_provider != null and !std.mem.eql(u8, preferred_provider.?, root.provider.id) and !fallback_config.contains(root.fallback_allow, root.provider.id);- bootMark(io, boot_started, boot_debug, "root agent");+ boot.mark(io, "root agent");defer joinElites(io); // reap if the session quits before any turn joins itsession_run.saveOrResumeSession(&root, &keys, arena, flags);diff --git a/src/mainloop.zig b/src/mainloop.zigindex ab848a38..75c2b6a5 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -24,6 +24,7 @@ const jobs = @import("jobs.zig");const session = @import("session.zig");const repl_glue = @import("repl_glue.zig");const mainloop_score = @import("mainloop_score.zig");+const mainloop_trace = @import("mainloop_trace.zig");const scoring = @import("scoring.zig");const trace = @import("trace.zig");const telemetry = @import("telemetry.zig");@@ -240,7 +241,7 @@ pub fn run(ctx: *Ctx) !void {const provider_field = if (parsed.object.get("provider")) |v| (if (v == .string) v.string else "") else "";const model_field = if (parsed.object.get("model")) |v| (if (v == .string) v.string else "") else "";const legacy_name = if (parsed.object.get("name")) |v| (if (v == .string) v.string else "") else "";- if (providers.controlRequestMayUseCodex(provider_field, model_field, legacy_name)) ctx.root.ensureModelCatalog(ctx.keys.*);+ providers.ensureControlRequestCatalogs(ctx.root, ctx.keys.*, provider_field, model_field, legacy_name);const provider = providers.resolveProviderControlRequest(ctx.keys, ctx.arena, provider_field, model_field, legacy_name) catch |err| {const label = providers.setModelRequestLabel(ctx.arena, provider_field, model_field, legacy_name) catch "<requested model>";const message = switch (err) {@@ -466,6 +467,7 @@ pub fn run(ctx: *Ctx) !void {try ctx.out.writeAll("\n");try ctx.out.flush();}+ const turn_before = mainloop_trace.begin(ctx.root, ctx.io);const turn_started = Io.Timestamp.now(ctx.io, .awake);// A failed turn must never kill the session: ApiError is already// reported inside request(); anything else is surfaced here. Either@@ -475,42 +477,7 @@ pub fn run(ctx: *Ctx) !void {// terminal event, and compaction gate. Reuse one full-history scan for// all three instead of serializing an increasingly large history 3x.const post_turn_context_tokens = ctx.root.effectiveContextTokens();- if (trace.g_traj) |tj| {- const fp = scoring.promptFingerprint(ctx.root.systemPrompt());- const turn_ms: i64 = @intCast(@max(0, turn_started.untilNow(ctx.io, .awake).toMilliseconds()));- const turn_ok = if (turn_result) |_| true else |_| false;- const turn_tools = ctx.root.tools_used.render(ctx.arena);- tj.capturePrompt(fp, ctx.root.systemPrompt());- tj.node(.{- .id = turn_id,- .parent = prev_turn_id,- .kind = "turn",- .label = ctx.root.provider.model,- .t = tj.elapsedMs(),- .ms = turn_ms,- .prompt_sha = &fp,- .prompt_mutated = !std.mem.eql(u8, &fp, &prev_prompt_fp),- .task = util.utf8Prefix(base_msg, 160),- .tools = turn_tools,- .ok = turn_ok,- .context_tokens = post_turn_context_tokens,- });- // Preserve the failure reason in the archive: the turn node only- // records ok:false, so an adjacent error record keeps the- // user-visible detail (network give-up, api error) joinable to it (#86).- if (!turn_ok) {- const fail_detail: []const u8 = if (turn_result) |_| "" else |e| switch (e) {- error.ApiError => ctx.root.last_api_error orelse "api error",- error.StreamStalled => ctx.root.last_api_error orelse "stream stalled — ended turn",- error.StreamDropped => ctx.root.last_api_error orelse "stream dropped — ended turn",- else => @errorName(e),- };- tj.node(.{ .kind = "turn_error", .parent = turn_id, .t = tj.elapsedMs(), .detail = fail_detail });- }- if (telemetry.g_telem) |t| t.runEvent(&fp, !std.mem.eql(u8, &fp, &prev_prompt_fp), turn_ok, turn_ms, turn_tools);- prev_turn_id = turn_id;- prev_prompt_fp = fp;- }+ mainloop_trace.record(ctx.root, ctx.io, ctx.arena, base_msg, turn_id, turn_started, turn_result, post_turn_context_tokens, turn_before, &prev_turn_id, &prev_prompt_fp);const final_text = turn_result catch |err| switch (err) {error.Interrupted => {// Esc: keep what streamed so far in history (as an assistantdiff --git a/src/mainloop_score.zig b/src/mainloop_score.zigindex 8ba4f3ed..506be261 100644--- a/src/mainloop_score.zig+++ b/src/mainloop_score.zig@@ -6,6 +6,7 @@ const std = @import("std");const agent_mod = @import("agent.zig");const scoring = @import("scoring.zig");+const recipe = @import("recipe.zig");const telemetry = @import("telemetry.zig");const trace = @import("trace.zig");const util = @import("util.zig");@@ -85,6 +86,7 @@ pub fn handle(root: *agent_mod.Agent, obj: std.json.ObjectMap) void {var niche_buf: [64]u8 = undefined;const niche = scoring.sanitizeMetaField(&niche_buf, util.utf8Prefix(stringField(obj, "niche"), 64));const provider_class = scoring.providerClass(root.provider.model);+ const recipe_snapshot = recipe.snapshotForPromptHash(root.provider.id, root.provider.model, @tagName(root.reasoning), sha, recipe.toolsetFingerprint(root.toolsJson()), if (niche.len > 0) niche else "interactive");const signature = scoring.signScore(sha, parent, score, run_id, judge_id, artifact_sha, eval_set_hash, niche, provider_class);const signed = scoring.g_score_key != null;@@ -102,6 +104,12 @@ pub fn handle(root: *agent_mod.Agent, obj: std.json.ObjectMap) void {.eval_set_hash = eval_set_hash,.niche = niche,.provider_class = provider_class,+ // Recipe metadata is local observability for now. It intentionally is+ // not sent to fleet selection until a future signed envelope version.+ .recipe_sha = &recipe_snapshot.recipe_sha,+ .recipe_model = root.provider.model,+ .recipe_effort = @tagName(root.reasoning),+ .recipe_toolset_sha = &recipe_snapshot.toolset_sha,.sig = if (signed) @as([]const u8, &signature) else "",.t = trajectory.elapsedMs(),});diff --git a/src/mainloop_trace.zig b/src/mainloop_trace.zignew file mode 100644index 00000000..79ef0c79--- /dev/null+++ b/src/mainloop_trace.zig@@ -0,0 +1,119 @@+//! Per-turn trajectory + recipe outcome recording, extracted from mainloop so+//! the oversized event loop keeps moving toward the repository's 600-LOC cap.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const pricing = @import("pricing.zig");+const recipe = @import("recipe.zig");+const scoring = @import("scoring.zig");+const telemetry = @import("telemetry.zig");+const trace = @import("trace.zig");+const util = @import("util.zig");++pub const Before = struct {+ model_calls: u64,+ cost: pricing.CostTally,+};++pub fn begin(root: *agent_mod.Agent, io: Io) Before {+ return .{+ .model_calls = if (root.run_budget) |budget| budget.used() else 0,+ .cost = pricing.g_cost.snap(io),+ };+}++pub fn record(+ root: *agent_mod.Agent,+ io: Io,+ arena: Allocator,+ task: []const u8,+ turn_id: u64,+ turn_started: Io.Timestamp,+ result: anyerror![]const u8,+ context_tokens: u64,+ before: Before,+ prev_turn_id: *u64,+ prev_prompt_fp: *[16]u8,+) void {+ const prompt = root.systemPrompt();+ const prompt_fp = scoring.promptFingerprint(prompt);+ const task_class = recipe.classifyTask(task);+ const current_recipe = recipe.snapshot(root.provider.id, root.provider.model, @tagName(root.reasoning), prompt, root.toolsJson(), task_class);+ const turn_ms: i64 = @intCast(@max(0, turn_started.untilNow(io, .awake).toMilliseconds()));+ const turn_ok = if (result) |_| true else |_| false;+ const turn_tools = root.tools_used.render(arena);+ const after = pricing.g_cost.snap(io);+ const outcome: recipe.Outcome = .{+ .success = turn_ok,+ .latency_ms = @intCast(@max(0, turn_ms)),+ .model_calls = (if (root.run_budget) |budget| budget.used() else before.model_calls) -| before.model_calls,+ .tool_errors = root.tools_used.errorCount(),+ .uncached_tokens = after.in_tokens -| before.cost.in_tokens,+ .cache_read_tokens = after.cache_tokens -| before.cost.cache_tokens,+ .cost_microusd = @intFromFloat(@max(0.0, after.usd - before.cost.usd) * 1_000_000.0),+ };+ const mutated = !std.mem.eql(u8, &prompt_fp, prev_prompt_fp);++ if (root.tracer) |tracer| tracer.write(.{+ .t = tracer.elapsedMs(),+ .ev = "recipe_outcome",+ .recipe_sha = ¤t_recipe.recipe_sha,+ .task_class = task_class,+ .provider = root.provider.id,+ .model = root.provider.model,+ .effort = @tagName(root.reasoning),+ .success = outcome.success,+ .latency_ms = outcome.latency_ms,+ .model_calls = outcome.model_calls,+ .tool_calls = root.tool_calls_this_turn,+ .tool_errors = outcome.tool_errors,+ .uncached_tokens = outcome.uncached_tokens,+ .cache_read_tokens = outcome.cache_read_tokens,+ .cache_permille = outcome.cachePermille(),+ .cost_microusd = outcome.cost_microusd,+ });++ if (trace.g_traj) |trajectory| {+ trajectory.capturePrompt(prompt_fp, prompt);+ trajectory.node(.{+ .id = turn_id,+ .parent = prev_turn_id.*,+ .kind = "turn",+ .label = root.provider.model,+ .t = trajectory.elapsedMs(),+ .ms = turn_ms,+ .prompt_sha = &prompt_fp,+ .prompt_mutated = mutated,+ .recipe_sha = ¤t_recipe.recipe_sha,+ .recipe_provider = root.provider.id,+ .recipe_model = root.provider.model,+ .recipe_effort = @tagName(root.reasoning),+ .recipe_toolset_sha = ¤t_recipe.toolset_sha,+ .task_class = task_class,+ .task = util.utf8Prefix(task, 160),+ .tools = turn_tools,+ .ok = turn_ok,+ .context_tokens = context_tokens,+ .model_calls = outcome.model_calls,+ .tool_errors = outcome.tool_errors,+ .uncached_tokens = outcome.uncached_tokens,+ .cache_read_tokens = outcome.cache_read_tokens,+ .cost_microusd = outcome.cost_microusd,+ });+ if (!turn_ok) {+ const detail: []const u8 = if (result) |_| "" else |err| switch (err) {+ error.ApiError => root.last_api_error orelse "api error",+ error.StreamStalled => root.last_api_error orelse "stream stalled — ended turn",+ error.StreamDropped => root.last_api_error orelse "stream dropped — ended turn",+ else => @errorName(err),+ };+ trajectory.node(.{ .kind = "turn_error", .parent = turn_id, .t = trajectory.elapsedMs(), .detail = detail });+ }+ if (telemetry.g_telem) |item| item.runEvent(&prompt_fp, mutated, turn_ok, turn_ms, turn_tools);+ prev_turn_id.* = turn_id;+ prev_prompt_fp.* = prompt_fp;+ }+}diff --git a/src/mcp.zig b/src/mcp.zigindex 997accc0..cc357666 100644--- a/src/mcp.zig+++ b/src/mcp.zig@@ -11,6 +11,7 @@//! fast relative to LLM calls, so global serialization is fine.const std = @import("std");+const builtin = @import("builtin");const Io = std.Io;const Value = std.json.Value;const Allocator = std.mem.Allocator;@@ -58,6 +59,57 @@ fn rewriteOneOf(a: Allocator, v: *Value) Allocator.Error!void {/// HTTP+SSE removal) don't apply to this stdio-only client.const latest_protocol = "2025-11-25";+const shutdown_grace = std.Io.Duration.fromMilliseconds(100);++fn waitChild(child: *std.process.Child, io: Io) std.process.Child.WaitError!std.process.Child.Term {+ return child.wait(io);+}++fn shutdownDeadline(io: Io) void {+ io.sleep(shutdown_grace, .awake) catch {};+}++/// Signal a normal stdio-server shutdown with EOF, but never let a server's+/// SIGTERM handler stall the CLI. A child that does not exit within the grace+/// window is force-killed and reaped so one-shot/SDK callers do not inherit+/// teardown latency or zombies.+fn stopChild(io: Io, child: *std.process.Child) void {+ if (child.id == null) return;+ if (child.stdin) |stdin| {+ stdin.close(io);+ child.stdin = null;+ }++ const Done = union(enum) { exited: std.process.Child.WaitError!std.process.Child.Term, deadline: void };+ var done_buf: [2]Done = undefined;+ var sel: Io.Select(Done) = .init(io, &done_buf);+ sel.concurrent(.exited, waitChild, .{ child, io }) catch {+ child.kill(io);+ return;+ };+ sel.concurrent(.deadline, shutdownDeadline, .{io}) catch {+ _ = sel.await() catch {};+ sel.cancelDiscard();+ return;+ };+ const first = sel.await() catch {+ sel.cancelDiscard();+ child.kill(io);+ return;+ };+ sel.cancelDiscard();+ if (first == .exited or child.id == null) return;++ switch (builtin.os.tag) {+ .windows => child.kill(io),+ .wasi => unreachable,+ else => {+ std.posix.kill(child.id.?, .KILL) catch {};+ _ = child.wait(io) catch child.kill(io);+ },+ }+}+const Server = struct {name: []const u8,child: std.process.Child,@@ -265,7 +317,7 @@ pub const Registry = struct {// handshake fails — McpClosed — has an already-dead child).var registry_owns_child = false;errdefer if (!registry_owns_child) {- _ = child.kill(reg.io);+ stopChild(reg.io, &child);};const server = try a.create(Server);@@ -323,7 +375,7 @@ pub const Registry = struct {}pub fn deinit(reg: *Registry) void {- for (reg.servers) |server| _ = server.child.kill(reg.io);+ for (reg.servers) |server| stopChild(reg.io, &server.child);reg.arena_state.deinit();}diff --git a/src/picker_auth.zig b/src/picker_auth.zigindex 006fd174..b184bd99 100644--- a/src/picker_auth.zig+++ b/src/picker_auth.zig@@ -18,6 +18,7 @@ const provider_mod = @import("provider.zig");const keys_cli = @import("keys_cli.zig");const command_catalog = @import("command_catalog.zig");const pricing = @import("pricing.zig");+const kimi_catalog = @import("kimi_catalog.zig");const Agent = agent_mod.Agent;const Keys = provider_mod.Keys;@@ -205,6 +206,7 @@ pub fn offerProviderAuth(keys.values[si] = dup;const saved = storeKey(root.io, root.gpa, arena, root.home, pid, dup);keys.sources[si] = if (saved) .stored else .session;+ if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, root.home, dup);try out.print("\xe2\x9c\x93 {s} key set (live{s})\n", .{ pid, if (saved) " + Keychain" else "" });}diff --git a/src/providers.zig b/src/providers.zigindex a45c2fc7..7fcd79ac 100644--- a/src/providers.zig+++ b/src/providers.zig@@ -14,6 +14,7 @@ const Value = std.json.Value;const pricing = @import("pricing.zig");const resolveModelName = pricing.resolveModelName;+const kimi_catalog = @import("kimi_catalog.zig");const serde = @import("serde.zig");const saveModel = serde.saveModel;@@ -213,11 +214,10 @@ pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*Iconst failed_id = root.provider.id;const failed_model = root.provider.model;root.ensureStoredKeys(keys);- var fallback = nextFallbackProvider(keys.*, failed_id, attempted[0..attempted_len], root.fallback_allow) orelse return err;- if (std.mem.eql(u8, fallback.id, "codex")) {- root.ensureModelCatalog(keys.*);- fallback = nextFallbackProvider(keys.*, failed_id, attempted[0..attempted_len], root.fallback_allow) orelse return err;- }+ // The failure path is already paying for exhaustive credentials;+ // hydrate deferred account catalogs before choosing a fallback.+ ensureModelQueryCatalogs(root, keys.*, "");+ const fallback = nextFallbackProvider(keys.*, failed_id, attempted[0..attempted_len], root.fallback_allow) orelse return err;attempted[attempted_len] = fallback.id;attempted_len += 1;const note = try applyFallbackProvider(root, arena, fallback);@@ -289,6 +289,25 @@ pub fn modelQueryMayUseCodex(query: []const u8) bool {return true;}+fn modelQueryMayUseKimi(query: []const u8) bool {+ const arg = std.mem.trim(u8, query, " \t");+ if (arg.len == 0) return true;+ const provider_end = std.mem.indexOfAny(u8, arg, " /\t") orelse arg.len;+ const provider_id = arg[0..provider_end];+ for (provider_specs) |spec| {+ if (!std.mem.eql(u8, spec.id, provider_id)) continue;+ return std.mem.eql(u8, spec.id, "kimi");+ }+ if (pricing.modelInTable(arg)) return pricing.providerModelInTable("kimi", arg);+ return true;+}++pub fn ensureModelQueryCatalogs(root: *Agent, keys: Keys, query: []const u8) void {+ if (modelQueryMayUseCodex(query)) root.ensureModelCatalog(keys);+ if (modelQueryMayUseKimi(query))+ kimi_catalog.ensure(root.io, root.gpa, root.arena, root.home, keys.get("kimi") orelse "");+}+/// Structured set_model has separate provider/model fields. An explicit/// provider fully determines routing; a model-only request remains fuzzy.pub fn controlRequestMayUseCodex(provider_query: []const u8, model_query: []const u8, legacy_name: []const u8) bool {@@ -298,6 +317,18 @@ pub fn controlRequestMayUseCodex(provider_query: []const u8, model_query: []consreturn modelQueryMayUseCodex(legacy_name);}+pub fn ensureControlRequestCatalogs(root: *Agent, keys: Keys, provider_query: []const u8, model_query: []const u8, legacy_name: []const u8) void {+ if (controlRequestMayUseCodex(provider_query, model_query, legacy_name)) root.ensureModelCatalog(keys);+ const query = if (std.mem.trim(u8, provider_query, " \t").len != 0)+ provider_query+ else if (std.mem.trim(u8, model_query, " \t").len != 0)+ model_query+ else+ legacy_name;+ if (modelQueryMayUseKimi(query))+ kimi_catalog.ensure(root.io, root.gpa, root.arena, root.home, keys.get("kimi") orelse "");+}+fn resolveProviderRequest(keys: *Keys, arena: Allocator, query: []const u8) !Provider {const arg = std.mem.trim(u8, query, " \t");if (arg.len == 0) return error.InvalidModelRequest;@@ -490,6 +521,10 @@ test "Codex catalog demand follows model request routing" {try std.testing.expect(modelQueryMayUseCodex("codex"));try std.testing.expect(modelQueryMayUseCodex("codex future-sol"));try std.testing.expect(modelQueryMayUseCodex("future-account-rollout"));+ try std.testing.expect(modelQueryMayUseKimi(""));+ try std.testing.expect(!modelQueryMayUseKimi("codegraff"));+ try std.testing.expect(modelQueryMayUseKimi("kimi"));+ try std.testing.expect(modelQueryMayUseKimi("k3"));try std.testing.expect(!controlRequestMayUseCodex("codegraff", "deepseek-v4-pro", ""));try std.testing.expect(controlRequestMayUseCodex("codex", "", ""));try std.testing.expect(controlRequestMayUseCodex("", "future-account-rollout", ""));diff --git a/src/recipe.zig b/src/recipe.zignew file mode 100644index 00000000..f152be30--- /dev/null+++ b/src/recipe.zig@@ -0,0 +1,188 @@+//! Versioned run-recipe identity and Pareto comparison primitives. This is the+//! local data-plane foundation for later task-aware model/effort selection;+//! it records observations without changing routing behavior.++const std = @import("std");+const trace = @import("trace.zig");+const util = @import("util.zig");++pub const Snapshot = struct {+ recipe_sha: [16]u8,+ prompt_sha: [16]u8,+ toolset_sha: [16]u8,+};++fn shortHash(text: []const u8) [16]u8 {+ var digest: [32]u8 = undefined;+ std.crypto.hash.sha2.Sha256.hash(text, &digest, .{});+ return std.fmt.bytesToHex(digest[0..8].*, .lower);+}++pub fn toolsetFingerprint(tools: []const u8) [16]u8 {+ return shortHash(tools);+}++/// Coarse, observational task class for per-class recipe comparison. It never+/// changes routing by itself; misclassification can only affect analytics.+pub fn classifyTask(text: []const u8) []const u8 {+ const groups = [_]struct { label: []const u8, needles: []const []const u8 }{+ .{ .label = "debug", .needles = &.{ " debug", "bug", " failing", " failure", "crash", " error" } },+ .{ .label = "review", .needles = &.{ "review", "audit", "security", "defect" } },+ .{ .label = "research", .needles = &.{ "research", "investigate", "compare", "explain", "look up" } },+ .{ .label = "implement", .needles = &.{ "implement", " build", " create", " add", " edit", "refactor", "fix" } },+ };+ for (groups) |group| for (group.needles) |needle|+ if (util.indexOfIgnoreCase(text, needle) != null) return group.label;+ return "general";+}++fn hashField(hasher: *std.crypto.hash.sha2.Sha256, field: []const u8) void {+ var len: [8]u8 = undefined;+ std.mem.writeInt(u64, &len, field.len, .little);+ hasher.update(&len);+ hasher.update(field);+}++pub fn snapshot(+ provider: []const u8,+ model: []const u8,+ effort: []const u8,+ prompt: []const u8,+ tools: []const u8,+ task_class: []const u8,+) Snapshot {+ const prompt_sha = shortHash(prompt);+ return snapshotForPromptHash(provider, model, effort, &prompt_sha, shortHash(tools), task_class);+}++pub fn snapshotForPromptHash(+ provider: []const u8,+ model: []const u8,+ effort: []const u8,+ prompt_sha: []const u8,+ toolset_sha: [16]u8,+ task_class: []const u8,+) Snapshot {+ var hasher = std.crypto.hash.sha2.Sha256.init(.{});+ hashField(&hasher, "recipe-v1");+ hashField(&hasher, @import("build_options").version);+ hashField(&hasher, provider);+ hashField(&hasher, model);+ hashField(&hasher, effort);+ hashField(&hasher, prompt_sha);+ hashField(&hasher, &toolset_sha);+ hashField(&hasher, task_class);+ var digest: [32]u8 = undefined;+ hasher.final(&digest);+ return .{+ .recipe_sha = std.fmt.bytesToHex(digest[0..8].*, .lower),+ .prompt_sha = if (prompt_sha.len == 16) prompt_sha[0..16].* else shortHash(prompt_sha),+ .toolset_sha = toolset_sha,+ };+}++pub fn record(+ tracer: *trace.Tracer,+ trajectory: ?*trace.Trajectory,+ provider: []const u8,+ model: []const u8,+ effort: []const u8,+ prompt: []const u8,+ tools: []const u8,+ task_class: []const u8,+) Snapshot {+ const value = snapshot(provider, model, effort, prompt, tools, task_class);+ tracer.write(.{+ .t = tracer.elapsedMs(),+ .ev = "recipe",+ .recipe_sha = &value.recipe_sha,+ .provider = provider,+ .model = model,+ .effort = effort,+ .prompt_sha = &value.prompt_sha,+ .toolset_sha = &value.toolset_sha,+ .task_class = task_class,+ .harness_version = @import("build_options").version,+ });+ if (trajectory) |traj| traj.node(.{+ .kind = "recipe",+ .recipe_sha = &value.recipe_sha,+ .provider = provider,+ .model = model,+ .effort = effort,+ .prompt_sha = &value.prompt_sha,+ .toolset_sha = &value.toolset_sha,+ .task_class = task_class,+ .harness_version = @import("build_options").version,+ .t = traj.elapsedMs(),+ });+ return value;+}++/// Metrics stay objective and separately inspectable. Selection can keep a+/// Pareto frontier instead of hiding quality/latency/cost tradeoffs inside one+/// scalar that a recipe might game.+pub const Outcome = struct {+ success: bool,+ latency_ms: u64,+ model_calls: u64,+ tool_errors: u64,+ uncached_tokens: u64,+ cache_read_tokens: u64,+ cost_microusd: u64,++ pub fn cachePermille(self: Outcome) u16 {+ const total = self.uncached_tokens +| self.cache_read_tokens;+ if (total == 0) return 0;+ return @intCast(@min(@as(u64, 1000), self.cache_read_tokens *| 1000 / total));+ }+};++/// True only when `candidate` is no worse on every objective and strictly+/// better on at least one. Success is mandatory against a successful baseline.+pub fn dominates(candidate: Outcome, baseline: Outcome) bool {+ if (!candidate.success and baseline.success) return false;+ const no_worse = @intFromBool(candidate.success) >= @intFromBool(baseline.success) and+ candidate.latency_ms <= baseline.latency_ms and+ candidate.model_calls <= baseline.model_calls and+ candidate.tool_errors <= baseline.tool_errors and+ candidate.uncached_tokens <= baseline.uncached_tokens and+ candidate.cost_microusd <= baseline.cost_microusd and+ candidate.cachePermille() >= baseline.cachePermille();+ if (!no_worse) return false;+ return candidate.success != baseline.success or+ candidate.latency_ms < baseline.latency_ms or+ candidate.model_calls < baseline.model_calls or+ candidate.tool_errors < baseline.tool_errors or+ candidate.uncached_tokens < baseline.uncached_tokens or+ candidate.cost_microusd < baseline.cost_microusd or+ candidate.cachePermille() > baseline.cachePermille();+}++test "recipe identity changes with model effort tools and task class" {+ const base = snapshot("codegraff", "deepseek-v4-pro", "medium", "prompt", "tools-a", "implementer");+ try std.testing.expectEqual(base.recipe_sha, snapshot("codegraff", "deepseek-v4-pro", "medium", "prompt", "tools-a", "implementer").recipe_sha);+ try std.testing.expect(!std.mem.eql(u8, &base.recipe_sha, &snapshot("codegraff", "deepseek-v4-pro", "high", "prompt", "tools-a", "implementer").recipe_sha));+ try std.testing.expect(!std.mem.eql(u8, &base.recipe_sha, &snapshot("codegraff", "deepseek-v4-pro", "medium", "prompt", "tools-b", "implementer").recipe_sha));+ try std.testing.expect(!std.mem.eql(u8, &base.recipe_sha, &snapshot("codegraff", "deepseek-v4-pro", "medium", "prompt", "tools-a", "reviewer").recipe_sha));+}++test "Pareto dominance never trades success for speed" {+ const base: Outcome = .{ .success = true, .latency_ms = 1000, .model_calls = 2, .tool_errors = 0, .uncached_tokens = 1000, .cache_read_tokens = 500, .cost_microusd = 2000 };+ var faster = base;+ faster.latency_ms = 800;+ try std.testing.expect(dominates(faster, base));+ var failed = faster;+ failed.success = false;+ try std.testing.expect(!dominates(failed, base));+ var tradeoff = faster;+ tradeoff.cost_microusd = 3000;+ try std.testing.expect(!dominates(tradeoff, base));+}++test "task classification is observational and coarse" {+ try std.testing.expectEqualStrings("debug", classifyTask("please debug the failing request"));+ try std.testing.expectEqualStrings("review", classifyTask("security review this diff"));+ try std.testing.expectEqualStrings("implement", classifyTask("can we implement the patch"));+ try std.testing.expectEqualStrings("general", classifyTask("hello there"));+}diff --git a/src/session_run.zig b/src/session_run.zigindex f2dfb581..20e6a770 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -40,6 +40,7 @@ const mcp = @import("mcp.zig");const jobs = @import("jobs.zig");const trace = @import("trace.zig");const scoring = @import("scoring.zig");+const recipe = @import("recipe.zig");const telemetry = @import("telemetry.zig");const util = @import("util.zig");const ansi = @import("ansi.zig");@@ -63,7 +64,7 @@ const hooks = @import("hooks.zig");pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: *provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "repl"))) return false;root.ensureStoredKeys(keys);- root.ensureModelCatalog(keys.*);+ providers.ensureModelQueryCatalogs(root, keys.*, "");// The standalone chat REPL can switch wire formats inside its own model// picker, so materialize every catalog only when this surface is entered.try root.ensureRootTools(.anthropic);@@ -239,6 +240,7 @@ pub fn buildRootAgent(if (flags.eval_cmd_flag) |c| root.eval_cmd = try arena.dupe(u8, c);if (flags.eval_target_flag) |t| root.eval_target = t;if (flags.eval_niche_flag) |n| root.eval_niche = try arena.dupe(u8, n);+ _ = recipe.record(tracer, trace.g_traj, root.provider.id, root.provider.model, @tagName(root.reasoning), root.systemPrompt(), root.toolsJson(), if (root.eval_niche.len > 0) root.eval_niche else "interactive");tracer.note("session", root.provider.model);// Distribute (docs §9.E): pull this tier's live fleet champions and prefer// them over the baked builtins. Best-effort + bounded; emits fleet:elite_pull.diff --git a/src/startup.zig b/src/startup.zigindex 63eafc01..21518721 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -97,6 +97,24 @@ fn startupNeedsCodexCatalog(keys: provider_mod.Keys, model_flag: ?[]const u8, sareturn std.mem.eql(u8, fallback.id, "codex");}+fn startupNeedsKimiCatalog(keys: provider_mod.Keys, model_flag: ?[]const u8, saved: ?serde.SavedModel) bool {+ if (keys.get("kimi") == null) return false;+ if (model_flag) |query| {+ if (explicitProvider(query)) |id| return std.mem.eql(u8, id, "kimi");+ if (pricing.modelInTable(query)) return pricing.providerModelInTable("kimi", query);+ // A free-form query may name an account-only rollout.+ return true;+ }+ if (saved) |selection| {+ if (std.mem.eql(u8, selection.pid, "kimi")) return true;+ if (pricing.providerModelInTable(selection.pid, selection.model) and keys.get(selection.pid) != null) return false;+ // A stale/keyless preference may fall through to Kimi.+ return true;+ }+ const fallback = keys.defaultProvider() catch return false;+ return std.mem.eql(u8, fallback.id, "kimi");+}+test "Codex catalog loads at startup only when selection can observe it" {try std.testing.expectEqualStrings("deepseek", explicitProvider("deepseek").?);try std.testing.expect(explicitProvider("deepseek-v4-pro") == null);@@ -136,6 +154,19 @@ test "Codex catalog loads at startup only when selection can observe it" {try std.testing.expect(!startupNeedsCodexCatalog(keys, "codex", null));}+test "Kimi catalog loads at startup only when selection can observe it" {+ var keys: provider_mod.Keys = .{ .values = @splat(null) };+ for (provider_mod.provider_specs, &keys.values) |spec, *value| {+ if (std.mem.eql(u8, spec.id, "kimi") or std.mem.eql(u8, spec.id, "codegraff")) value.* = "token";+ }+ try std.testing.expect(!startupNeedsKimiCatalog(keys, "codegraff", null));+ try std.testing.expect(startupNeedsKimiCatalog(keys, "kimi", null));+ try std.testing.expect(startupNeedsKimiCatalog(keys, "k3", null));+ try std.testing.expect(startupNeedsKimiCatalog(keys, "future-kimi-rollout", null));+ try std.testing.expect(!startupNeedsKimiCatalog(keys, null, .{ .pid = "codegraff", .model = "deepseek-v4-pro" }));+ try std.testing.expect(startupNeedsKimiCatalog(keys, null, .{ .pid = "kimi", .model = "k3" }));+}+/// Resolves API keys/credentials (env vars → codegraff/codex/kimi on-disk/// logins → the `harness key set` store, env always wins — same precedence/// as before) and picks the startup model (--model flag, else the@@ -227,7 +258,8 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp// native-cache parse, and possible refresh until a model surface needs it.if (startupNeedsCodexCatalog(keys, model_flag, saved_model))model_catalog.ensure(io, gpa, arena, home, keys.get("codex") orelse "", keys.codex_account);- if (keys.get("kimi")) |token| _ = kimi_catalog.load(io, gpa, arena, home, token);+ if (startupNeedsKimiCatalog(keys, model_flag, saved_model))+ kimi_catalog.ensure(io, gpa, arena, home, keys.get("kimi") orelse "");if (home.len != 0) {// Apply the independent models.dev price/context overlay after routing// discovery. Provider-specific Codex windows remain authoritative.diff --git a/src/startup_timing.zig b/src/startup_timing.zignew file mode 100644index 00000000..217d4792--- /dev/null+++ b/src/startup_timing.zig@@ -0,0 +1,68 @@+//! Structured startup phase receipts. Milestones recorded before the trace+//! file exists are buffered in a fixed array, then flushed when main attaches+//! the session tracer. Later milestones stream directly to that same trace.++const std = @import("std");+const Io = std.Io;+const trace = @import("trace.zig");++pub const Tracker = struct {+ const max_phases = 16;+ const Phase = struct { label: []const u8, cumulative_ms: i64, phase_ms: i64 };++ started: Io.Timestamp,+ debug: bool,+ phases: [max_phases]Phase = undefined,+ phases_len: usize = 0,+ last_ms: i64 = 0,+ tracer: ?*trace.Tracer = null,++ pub fn init(io: Io, debug: bool) Tracker {+ return .{ .started = Io.Timestamp.now(io, .awake), .debug = debug };+ }++ pub fn mark(self: *Tracker, io: Io, label: []const u8) void {+ const cumulative_ms: i64 = @intCast(@max(0, self.started.untilNow(io, .awake).toMilliseconds()));+ const phase: Phase = .{+ .label = label,+ .cumulative_ms = cumulative_ms,+ .phase_ms = @max(0, cumulative_ms - self.last_ms),+ };+ self.last_ms = cumulative_ms;+ if (self.debug) std.debug.print("[boot +{d}ms, phase {d}ms] {s}\n", .{ phase.cumulative_ms, phase.phase_ms, label });+ if (self.tracer) |tracer| {+ emit(tracer, phase);+ } else if (self.phases_len < self.phases.len) {+ self.phases[self.phases_len] = phase;+ self.phases_len += 1;+ }+ }++ pub fn attach(self: *Tracker, tracer: *trace.Tracer) void {+ if (self.tracer != null) return;+ self.tracer = tracer;+ for (self.phases[0..self.phases_len]) |phase| emit(tracer, phase);+ self.phases_len = 0;+ }++ fn emit(tracer: *trace.Tracer, phase: Phase) void {+ tracer.write(.{+ .t = tracer.elapsedMs(),+ .ev = "startup_phase",+ .phase = phase.label,+ .phase_ms = phase.phase_ms,+ .startup_ms = phase.cumulative_ms,+ });+ }+};++test "startup phases retain order and non-negative deltas before attach" {+ var tracker = Tracker.init(std.testing.io, false);+ tracker.mark(std.testing.io, "args");+ tracker.mark(std.testing.io, "credentials");+ try std.testing.expectEqual(@as(usize, 2), tracker.phases_len);+ try std.testing.expectEqualStrings("args", tracker.phases[0].label);+ try std.testing.expectEqualStrings("credentials", tracker.phases[1].label);+ try std.testing.expect(tracker.phases[0].phase_ms >= 0);+ try std.testing.expect(tracker.phases[1].cumulative_ms >= tracker.phases[0].cumulative_ms);+}diff --git a/src/trace.zig b/src/trace.zigindex 32bfced8..3ce35be5 100644--- a/src/trace.zig+++ b/src/trace.zig@@ -328,6 +328,12 @@ pub const ToolSink = struct {return alloc.dupe(u8, aw.writer.buffered()) catch "";}+ pub fn errorCount(self: *const ToolSink) u64 {+ var total: u64 = 0;+ for (self.entries.items) |entry| total += @intFromBool(entry.err);+ return total;+ }+pub fn clear(self: *ToolSink, io: Io) void {self.mutex.lockUncancelable(io);defer self.mutex.unlock(io);