graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(routing): bill and route by the SEAT, not the model name (#471)
Rach Pradhan235bf34ca8d1
diff --git a/gui/src/services/desktop/clientQaMock.ts b/gui/src/services/desktop/clientQaMock.tsindex f80458cb..d2cbe009 100644--- a/gui/src/services/desktop/clientQaMock.ts+++ b/gui/src/services/desktop/clientQaMock.ts@@ -13,7 +13,7 @@ import type {UpdatePromptSettingsInput,} from "./types/contracts";-const QA_WORKSPACE_PATH = "/Users/pranavp/projects/harness/codegraff/gui";+const QA_WORKSPACE_PATH = "/Users/example/projects/codegraff/gui";const QA_CONVERSATION_ID = "qa-existing-chat";export const isQaMockMode =@@ -311,6 +311,11 @@ export function mockInvokeCommand<T>({ id: `${conversationId}-assistant`, kind: "assistant", requestId: `${conversationId}-request`, text: "QA mock response with a bullet list:\n\n- Markdown bullets align correctly.\n- `inline code` stays readable.\n\n```ts\nconst theme = 'clean-modern';\n```\n\n[Codegraff](https://github.com/justrach/codegraff)" },]) as T);}+ case "respond_followup": {+ // The mock never leaves a followup pending: answering just returns the+ // current snapshot with no followup, which clears the needs-input state.+ return Promise.resolve(createQaSnapshot(QA_CONVERSATION_ID, createQaSnapshot().conversationViews[0]?.messages ?? []) as T);+ }case "list_providers":return Promise.resolve(qaProviders.map((p) => ({ ...p })) as T);case "start_provider_auth": {diff --git a/plans/2026-06-15-gui-port-review-handoff.md b/plans/2026-06-15-gui-port-review-handoff.mdindex de6abfc2..f19ac70a 100644--- a/plans/2026-06-15-gui-port-review-handoff.md+++ b/plans/2026-06-15-gui-port-review-handoff.md@@ -2,7 +2,7 @@## Context-This repository is the Zig-native Codegraff target at `/Users/pranavp/projects/harness/codegraff-zig`. The GUI was copied from the Rust/Tauri/React Codegraff2 source repository and adapted in place so it can be tested locally against the Zig-native `graff` binary.+This repository is the Zig-native Codegraff target at `<workspace>/codegraff-zig`. The GUI was copied from the Rust/Tauri/React Codegraff2 source repository and adapted in place so it can be tested locally against the Zig-native `graff` binary.The chosen migration strategy is copy-first: preserve the existing GUI shell and progressively replace source-specific runtime coupling.@@ -14,7 +14,7 @@ Expected target-repo changes for this port:- `src/main.zig` has formatter-only whitespace changes required by the repo's Zig 0.16 formatter.- `gui/` is newly copied and adapted.-The original source repo at `/Users/pranavp/projects/harness/codegraff` has a pre-existing `codedb.snapshot` modification that is not part of this port. Do not include it in the target port commit.+The original source repo at `<workspace>/codegraff` has a pre-existing `codedb.snapshot` modification that is not part of this port. Do not include it in the target port commit.## Major Decisions@@ -85,11 +85,11 @@ A later cleanup pass can remove, gate, or re-enable these pieces as feature pari## Verification Completed-From `/Users/pranavp/projects/harness/codegraff-zig`:+From `<workspace>/codegraff-zig`:```bash-/Users/pranavp/.local/zig/0.16.0/zig build-/Users/pranavp/.local/zig/0.16.0/zig build test --summary all+zig build+zig build test --summary allcargo check --manifest-path gui/src-tauri/Cargo.tomlcd gui && npm run build```@@ -97,8 +97,8 @@ cd gui && npm run buildThe GUI was also launched locally with:```bash-cd /Users/pranavp/projects/harness/codegraff-zig-/Users/pranavp/.local/zig/0.16.0/zig build+cd <workspace>/codegraff-zig+zig buildcd guiCODEGRAFF_GUI_BINARY=../zig-out/bin/graff npm run tauri dev```diff --git a/scripts/eval/longhorizon/run_longhorizon.py b/scripts/eval/longhorizon/run_longhorizon.pyindex b8e2afc0..9f501e92 100644--- a/scripts/eval/longhorizon/run_longhorizon.py+++ b/scripts/eval/longhorizon/run_longhorizon.py@@ -17,7 +17,7 @@ FIX = ROOT / "fixture"RUNS = ROOT / "runs"MEMO = pathlib.Path(os.environ.get("LH_MEMO_BIN", "")) # optional comparison arm; not vendored-GRAFF = os.environ.get("GRAFF_BIN", "/Users/blackfloofie/codegraff/zig-out/bin/graff")+GRAFF = os.environ.get("GRAFF_BIN", str(ROOT.parents[2] / "zig-out" / "bin" / "graff"))MODEL = os.environ.get("GRAFF_EVAL_MODEL", "gpt-5.6-sol")STEPS = int(os.environ.get("LH_STEPS", "12"))FILLER = int(os.environ.get("LH_FILLER", "26")) # lines/step, under the 4096B handle thresholddiff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex f4c1e8ea..63b6992f 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -14,7 +14,7 @@"src/main.zig","src/repl.zig"],- "test_count_baseline": 1125,+ "test_count_baseline": 1151,"test_count_slack": 25,"required_invariants": [{diff --git a/src/agent_context.zig b/src/agent_context.zigindex bac47879..7d232c84 100644--- a/src/agent_context.zig+++ b/src/agent_context.zig@@ -8,6 +8,7 @@ const Agent = @import("agent.zig").Agent;const context_tokens = @import("context_tokens.zig");const messages_mod = @import("messages.zig");const pricing = @import("pricing.zig");+const billing = @import("billing.zig");const g_cost = &pricing.g_cost;test "recordUsage (#202): floors the meter from the local estimate when usage is absent" {@@ -183,11 +184,12 @@ pub fn usageInt(obj: std.json.ObjectMap, name: []const u8) i64 {}/// Record one request's usage into the session-wide tally (g_cost):-/// token counts always; USD only for API-key providers with a-/// price_table row. Subscription providers (codex, claude) bill flat-/// and tally as sub_calls; unpriced models as unpriced_calls.+/// token counts always; USD only for metered seats with a price_table row.+/// #471: the seat is classified from the provider AND how its credential was+/// obtained — a flat-rate login (codex/kimi/xai) tallies as sub_calls and adds+/// $0, while an env key on that same provider is metered like any other.pub fn recordCost(self: *Agent, uncached_in: i64, cache_in: i64, out: i64) void {- g_cost.add(self.io, self.provider.id, self.provider.model, uncached_in, cache_in, out);+ g_cost.add(self.io, billing.forProvider(self.provider), self.provider.model, uncached_in, cache_in, out);}/// #174: ~4-bytes/token estimate of the FULL history serialized as Responsesdiff --git a/src/agent_request.zig b/src/agent_request.zigindex 5f1e7a31..dcf2a877 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -287,6 +287,12 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {if (err == error.RateLimited and main_mod.g_5xx_body_len > 0 andisQuotaExceeded(main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len])){+ // #471: a flat-rate plan that has run out is exactly+ // when the metered key it outranked earns its keep.+ // Hand over and retry rather than failing a session+ // with a working credential sitting unused. One-way+ // and announced — see credential_failover.+ if (policy.handOffExhaustedPlan(self)) continue;self.last_api_error = std.fmt.allocPrint(self.arena, "rate limited (429): {s} — {s}", .{ policy.quota_cap_marker, main_mod.g_5xx_body_buf[0..main_mod.g_5xx_body_len] }) catch "rate limited (429): quota exceeded";if (telemetry.g_telem) |t| t.errorEvent("quota", self.last_api_error orelse "quota exceeded");if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, 0, body.len, 0, 0, 0, true);diff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex 341006cb..aebe3330 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -6,6 +6,8 @@ const Agent = @import("agent.zig").Agent;const http = @import("http.zig");const RetryPlan = http.RetryPlan;const oauth = @import("oauth.zig");+const billing = @import("billing.zig"); // #471 seat billing class+const credential_failover = @import("credential_failover.zig"); // #471 parked metered keyconst oauth_helpers = @import("oauth_helpers.zig"); // tests pin g_codex_home, the resolver startup setsconst telemetry = @import("telemetry.zig");const util = @import("util.zig");@@ -541,3 +543,28 @@ test "recoverContextOverflow (#193): overflow trims + retries once; guard and notry std.testing.expect(!recoverContextOverflow(&agent, "invalid api key", null, &retried2));try std.testing.expect(!retried2);}++/// #471: this seat is a flat-rate plan that has just reported a quota cap, and+/// a metered credential was parked behind it at startup. Hand over to that key+/// for the rest of the session and say so, returning true so the caller retries+/// the SAME request on the new credential instead of failing the turn.+///+/// Gated on the seat being `.sub`: a metered seat hitting a billing cap has+/// nothing better to switch to, and promoting there would burn the reserve on+/// a wall it cannot get past. One-way by construction — credential_failover+/// promotes once per provider, so a second cap falls through to the normal+/// error path rather than looping on a credential that is also exhausted.+pub fn handOffExhaustedPlan(self: *Agent) bool {+ if (billing.forProvider(self.provider) != .sub) return false;+ const promotion = credential_failover.promote(self.provider.id) orelse return false;+ self.provider.api_key = self.arena.dupe(u8, promotion.key) catch promotion.key;+ self.provider.source = promotion.source;+ self.ws_off = false;+ self.ws_transport_failures = 0;+ if (self.tracer) |tr| tr.note("credential_failover", "plan exhausted — switched to the parked metered key");+ self.say(+ "[⚠ your {s} plan is out of quota — switching to the {s} API key for the rest of this session. Calls now bill PER TOKEN.]\n",+ .{ self.provider.id, promotion.source.label() },+ ) catch {};+ return true;+}diff --git a/src/bench_priors.zig b/src/bench_priors.zigindex 4d5c171e..4fd68321 100644--- a/src/bench_priors.zig+++ b/src/bench_priors.zig@@ -332,6 +332,15 @@ pub fn effCost(m: Best) f64 {/// #373: does `a` beat `b` outright — at least `b`'s score for strictly less/// money? Then `b` is not a rung, it is a mistake: every task `b` could run,/// `a` runs at least as well for less.+///+/// Deliberately ONE cost axis. A second arm on list price was tried for #471+/// and reverted: `dominates` feeds a Pareto front, mixing two incomparable+/// cost axes makes it non-transitive, and a dominated model then evicts a+/// survivor the winner does not itself dominate (`gpt-5.4` knocked out+/// `gpt-5.6-terra` on list price while being pruned on $/task by `sol`,+/// which is unpriced and so could not evict terra itself). The list-price+/// rule #471 needs is a post-condition on the finished ladder instead —+/// tier_ladder.cheaperSeat.pub fn dominates(a: Best, b: Best) bool {return a.score >= b.score and effCost(a) < effCost(b);}diff --git a/src/billing.zig b/src/billing.zignew file mode 100644index 00000000..c4ba8ab6--- /dev/null+++ b/src/billing.zig@@ -0,0 +1,120 @@+//! Which billing class one provider SEAT falls into (#471).+//!+//! Split out of pricing.zig because the answer is not a property of a price+//! sheet. `pricing.priceFor` is keyed by model NAME alone — `price_overlay` is+//! rebuilt from the models.dev sheet in ~/.codegraff/models.json, which has no+//! provider column — so `gpt-5.6-luna` carries the same list price whether it+//! is reached through a metered OpenAI key or a flat-rate Codex login. Two+//! facts the sheet cannot see decide the class:+//!+//! 1. the PROVIDER's declared plan (`ProviderSpec.sub_login`), and+//! 2. HOW this session's credential was obtained+//! (`Keys.CredentialSource` — `.login` vs `.environment`/`.stored`).+//!+//! It is the login that is flat-rate, not the vendor. `graff login xai` buys a+//! SuperGrok plan; `XAI_API_KEY` is metered api.x.ai access. Same provider,+//! same model, different bill — so classification takes the source, and a+//! caller that only knows the provider id gets the metered answer.+//!+//! WHY THIS EXISTS AT ALL. Before #471 the classifier was a hardcoded id list+//! (`provider_id == "codex" or "kimi"`) living in pricing.zig, and it was the+//! THIRD such list to disagree with the other two: `ProviderSpec.LoginKind`+//! knew about codegraff/codex/kimi but not xai, `oauth.refreshOAuthKey` knew+//! about kimi/xai/codex but not codegraff, and the billing list knew about+//! codex/kimi only. The result was that xAI OAuth sessions — a real+//! device-code flow since oauth.zig's xaiLogin — were billed to /cost at grok+//! list price against a subscription the user had already paid for. Declaring+//! it on the spec makes a new subscription provider one field instead of an id+//! remembered in N files.++const std = @import("std");+const pricing = @import("pricing.zig");+const provider_mod = @import("provider.zig");++pub const Billing = pricing.Billing;+pub const CredentialSource = provider_mod.Keys.CredentialSource;++/// True when a `/login` on this provider buys a flat-rate plan. Reads the+/// declaration on the provider spec; an unknown id (a workspace router) is+/// metered, which is the safe direction — it over-reports cost rather than+/// hiding spend.+pub fn subscriptionLogin(provider_id: []const u8) bool {+ for (provider_mod.provider_specs) |spec|+ if (std.mem.eql(u8, spec.id, provider_id)) return spec.sub_login;+ if (provider_mod.additional_router) |spec|+ if (std.mem.eql(u8, spec.id, provider_id)) return spec.sub_login;+ return false;+}++/// The billing class of one API call on this seat.+pub fn forSeat(provider_id: []const u8, model: []const u8, source: CredentialSource) Billing {+ if (source == .login and subscriptionLogin(provider_id)) return .sub;+ return if (pricing.priceFor(model) != null) .priced else .unpriced;+}++/// The class of a resolved `Provider`, which already carries both inputs.+pub fn forProvider(p: provider_mod.Provider) Billing {+ return forSeat(p.id, p.model, p.source);+}++/// A seat that costs nothing per token, so no cost ceiling applies to it: the+/// #292 rung check exists to stop an AUTOMATIC ladder rung from spending more+/// than the model the user chose, and on a flat-rate plan every rung spends+/// the same nothing. Ranking such a seat by score-per-dollar is meaningless+/// (and divides by zero); callers should rank by capability alone.+pub fn freeAtTheMargin(p: provider_mod.Provider) bool {+ return forProvider(p) == .sub;+}++test "a flat-rate login and a metered key on the same seat bill differently (#471)" {+ // The regression: xAI OAuth was billed at grok list price because the+ // classifier keyed on provider id alone and xai wasn't on its list.+ try std.testing.expectEqual(Billing.sub, forSeat("xai", "grok-4.3", .login));+ try std.testing.expectEqual(Billing.priced, forSeat("xai", "grok-4.3", .environment));++ // Same discipline for the two providers that were already classified: the+ // subscription is the login, so KIMI_API_KEY is metered per token.+ try std.testing.expectEqual(Billing.sub, forSeat("kimi", "kimi-k2.7", .login));+ try std.testing.expectEqual(Billing.priced, forSeat("kimi", "kimi-k2.7", .environment));++ // codex has no usable env key (env_key is the CODEX_DISABLED sentinel), so+ // it is only ever reached by login — but the source still gates it.+ try std.testing.expectEqual(Billing.sub, forSeat("codex", "gpt-5.5", .login));++ // A metered vendor's login (none exists today) would still be priced, and+ // the codegraff gateway's device login draws on credits, not a plan.+ try std.testing.expectEqual(Billing.priced, forSeat("anthropic", "claude-sonnet-4-6", .login));+ try std.testing.expectEqual(Billing.priced, forSeat("codegraff", "claude-sonnet-4-6", .login));++ // Unpriced stays unpriced: no plan, no price row.+ try std.testing.expectEqual(Billing.unpriced, forSeat("openai", "mystery-model", .environment));+}++test "subscriptionLogin is declared on the spec, not a hardcoded id list" {+ // Every provider whose spec says sub_login must also HAVE a login flow;+ // a plan you cannot sign into would silently zero out real spend.+ for (provider_mod.provider_specs) |spec| {+ if (!spec.sub_login) continue;+ try std.testing.expect(spec.login != .api_key);+ try std.testing.expect(subscriptionLogin(spec.id));+ }+ // And the inverse guard that caught this bug: every device login is+ // classified one way or the other on purpose, never by omission.+ for (provider_mod.provider_specs) |spec| {+ if (spec.login == .api_key) continue;+ const declared = spec.sub_login or std.mem.eql(u8, spec.id, "codegraff");+ try std.testing.expect(declared);+ }+ try std.testing.expect(!subscriptionLogin("no-such-provider"));+}++test "freeAtTheMargin follows the credential, not the vendor" {+ const seat = struct {+ fn p(id: []const u8, model: []const u8, source: CredentialSource) provider_mod.Provider {+ return .{ .id = id, .kind = .openai, .auth = .bearer, .url = "", .api_key = "", .model = model, .context = 0, .source = source };+ }+ }.p;+ try std.testing.expect(freeAtTheMargin(seat("xai", "grok-4.3", .login)));+ try std.testing.expect(!freeAtTheMargin(seat("xai", "grok-4.3", .environment)));+ try std.testing.expect(!freeAtTheMargin(seat("anthropic", "claude-opus-4-8", .environment)));+}diff --git a/src/credential_failover.zig b/src/credential_failover.zignew file mode 100644index 00000000..25d4a078--- /dev/null+++ b/src/credential_failover.zig@@ -0,0 +1,139 @@+//! A flat-rate plan outranks a metered key on the same provider — until the+//! plan runs out (#471).+//!+//! kimi and xai (and codex, via ChatGPT) can hold BOTH credentials at once: an+//! API key you are billed for per token, and a subscription you have already+//! paid for. Before this, startup.resolveKeys filled the single `Keys` slot+//! from the environment first and only reached for a login `if (value ==+//! null)`, so the metered key won silently and every call was billed twice+//! over — once to the plan's monthly fee, once to the token meter.+//!+//! The plan wins now. The metered credential is not discarded, though: it is+//! parked here, because "the plan is better" stops being true the moment the+//! plan is exhausted, and a session that dies on a quota wall when a working+//! key is sitting right there would be a worse bug than the one being fixed.+//!+//! HANDOFF IS ONE-WAY AND ANNOUNCED. A quota cap (agent_request's+//! isQuotaExceeded path, not a transient 429) promotes the parked key for the+//! rest of the session and says so. It never silently drifts back: re-testing+//! an exhausted plan mid-run would spend real money discovering that it is+//! still exhausted, and the user needs to know their billing changed anyway.++const std = @import("std");++const provider_mod = @import("provider.zig");+const Keys = provider_mod.Keys;+const n_providers = provider_mod.provider_specs.len;++fn indexOf(provider_id: []const u8) ?usize {+ for (provider_mod.provider_specs, 0..) |spec, i|+ if (std.mem.eql(u8, spec.id, provider_id)) return i;+ return null;+}++var g_value: [n_providers]?[]const u8 = @splat(null);+var g_source: [n_providers]Keys.CredentialSource = @splat(.none);+var g_promoted: [n_providers]bool = @splat(false);++/// Park the metered credential a plan is being preferred over.+pub fn park(provider_id: []const u8, value: []const u8, source: Keys.CredentialSource) void {+ const i = indexOf(provider_id) orelse return;+ g_value[i] = value;+ g_source[i] = source;+ g_promoted[i] = false;+}++/// Is a metered credential standing by for this provider, unused so far?+pub fn standingBy(provider_id: []const u8) bool {+ const i = indexOf(provider_id) orelse return false;+ return g_value[i] != null and !g_promoted[i];+}++pub fn promoted(provider_id: []const u8) bool {+ const i = indexOf(provider_id) orelse return false;+ return g_promoted[i];+}++pub fn parkedSource(provider_id: []const u8) Keys.CredentialSource {+ const i = indexOf(provider_id) orelse return .none;+ return g_source[i];+}++pub const Promotion = struct { key: []const u8, source: Keys.CredentialSource };++/// Hand this provider over to its parked metered credential, once. Returns+/// null when there is nothing parked or the handoff already happened, so the+/// caller falls through to its normal error path rather than looping.+pub fn promote(provider_id: []const u8) ?Promotion {+ const i = indexOf(provider_id) orelse return null;+ if (g_promoted[i]) return null;+ const key = g_value[i] orelse return null;+ g_promoted[i] = true;+ return .{ .key = key, .source = g_source[i] };+}++/// Seat `spec` on its PLAN when one exists, parking whatever metered+/// credential already held the slot. Called per provider from+/// startup.resolveKeys, which owns the "is this provider even in play"+/// gate (#274 — a login refresh is a synchronous network call).+///+/// Only kimi and xai reach the load here: codegraff's device login is not a+/// flat-rate plan (`sub_login = false`), and codex is resolved earlier because+/// its `env_key` is the CODEX_DISABLED sentinel, so it has no metered key to+/// outrank in the first place.+pub fn preferPlan(+ io: std.Io,+ gpa: std.mem.Allocator,+ arena: std.mem.Allocator,+ home: []const u8,+ spec: provider_mod.ProviderSpec,+ value: *?[]const u8,+ source: *Keys.CredentialSource,+) void {+ if (!spec.sub_login) return;+ const oauth = @import("oauth.zig");+ const token = switch (spec.login) {+ .kimi_device => oauth.loadKimiOAuth(io, gpa, arena, home, false, null),+ .xai_device => oauth.loadXaiOAuth(io, gpa, arena, home, false, null),+ else => null,+ } orelse return;+ if (value.*) |metered| park(spec.id, metered, source.*);+ value.* = token;+ source.* = .login;+}++/// Test-only: the table is process-global, like the key store it mirrors.+pub fn resetForTest() void {+ g_value = @splat(null);+ g_source = @splat(.none);+ g_promoted = @splat(false);+}++test "#471 a parked metered key is handed over once, and only once" {+ resetForTest();+ defer resetForTest();++ try std.testing.expect(!standingBy("kimi"));+ try std.testing.expect(promote("kimi") == null); // nothing parked: no handoff++ park("kimi", "sk-metered", .environment);+ try std.testing.expect(standingBy("kimi"));+ try std.testing.expect(!promoted("kimi"));+ try std.testing.expectEqual(Keys.CredentialSource.environment, parkedSource("kimi"));++ const first = promote("kimi").?;+ try std.testing.expectEqualStrings("sk-metered", first.key);+ try std.testing.expectEqual(Keys.CredentialSource.environment, first.source);+ try std.testing.expect(promoted("kimi"));+ // Standing by is now false: it is in use, not in reserve.+ try std.testing.expect(!standingBy("kimi"));++ // One-way: a second quota wall on the SAME provider must not re-promote+ // and re-announce, it must fall through to the normal error path.+ try std.testing.expect(promote("kimi") == null);++ // Providers are independent, and an unknown id is inert rather than fatal.+ try std.testing.expect(promote("xai") == null);+ try std.testing.expect(promote("no-such-provider") == null);+ try std.testing.expect(!standingBy("no-such-provider"));+}diff --git a/src/goal_persist_tests.zig b/src/goal_persist_tests.zigindex a1644b82..21b08d00 100644--- a/src/goal_persist_tests.zig+++ b/src/goal_persist_tests.zig@@ -529,5 +529,5 @@ test "absolute path prompts are not mistaken for slash commands" {try std.testing.expect(repl_glue.isSlashCommandLine("/not-a-command"));try std.testing.expect(!repl_glue.isSlashCommandLine("/System/Library/PrivateFrameworks/StorageManagement.framework/PlugIns/StorageManagementService what causes this to start"));- try std.testing.expect(!repl_glue.isSlashCommandLine("/Users/blackfloofie/codedb/src/main.zig explain this"));+ try std.testing.expect(!repl_glue.isSlashCommandLine("/Users/example/codedb/src/main.zig explain this"));}diff --git a/src/pricing.zig b/src/pricing.zigindex da52c212..1dc6d9d5 100644--- a/src/pricing.zig+++ b/src/pricing.zig@@ -27,8 +27,11 @@ pub const price_table = [_]ModelPrice{.{ .name = "gpt-5.3-codex", .in = 1.75, .out = 14, .cache = 0.175 },.{ .name = "gpt-5.2", .in = 1.75, .out = 14, .cache = 0.175 },.{ .name = "gpt-5-codex", .in = 1.25, .out = 10, .cache = 0.125 },- .{ .name = "claude-opus-4-8", .in = 15, .out = 75, .cache = 1.5 },- .{ .name = "claude-opus-4.8", .in = 15, .out = 75, .cache = 1.5 },+ .{ .name = "claude-fable-5", .in = 10, .out = 50, .cache = 1 }, // pricier than opus-5; unpriced it read as a cheap rung+ .{ .name = "claude-opus-5", .in = 5, .out = 25, .cache = 0.5 },+ .{ .name = "claude-sonnet-5", .in = 2, .out = 10, .cache = 0.2 }, // introductory, $3/$15 from 2026-09-01+ .{ .name = "claude-opus-4-8", .in = 5, .out = 25, .cache = 0.5 },+ .{ .name = "claude-opus-4.8", .in = 5, .out = 25, .cache = 0.5 },.{ .name = "claude-sonnet-4-6", .in = 3, .out = 15, .cache = 0.3 },.{ .name = "claude-sonnet-4.6", .in = 3, .out = 15, .cache = 0.3 },.{ .name = "claude-haiku-4-5", .in = 1, .out = 5, .cache = 0.1 },@@ -60,15 +63,12 @@ pub fn priceFor(model: []const u8) ?ModelPrice {return null;}-/// Billing class of one API call: the codex subscription login bills-/// flat-rate, price_table rows bill per token, anything else is unpriced.+/// Billing class of one API call: a flat-rate subscription login bills nothing+/// per token, price_table rows bill per token, anything else is unpriced.+/// Classifying a SEAT is billing.zig's job — it needs the provider spec and the+/// credential source, neither of which belongs in a price sheet.pub const Billing = enum { sub, priced, unpriced };-pub fn billingFor(provider_id: []const u8, model: []const u8) Billing {- if (std.mem.eql(u8, provider_id, "codex") or std.mem.eql(u8, provider_id, "kimi")) return .sub;- return if (priceFor(model) != null) .priced else .unpriced;-}-/// USD for one request at price `p` (negative token counts clamp to 0).pub fn usdFor(p: ModelPrice, uncached_in: i64, cache_in: i64, out: i64) f64 {const fi: f64 = @floatFromInt(@max(uncached_in, 0));@@ -93,17 +93,23 @@ pub const CostTally = struct {sub_calls: u64 = 0, // subscription-billed (flat-rate; contribute $0)unpriced_calls: u64 = 0, // no price_table row- pub fn add(self: *CostTally, io: Io, provider_id: []const u8, model: []const u8, uncached_in: i64, cache_in: i64, out: i64) void {+ /// `billing` is the caller's already-classified seat (billing.forSeat): a+ /// flat-rate login and a metered env key on the SAME provider+model are+ /// different classes, so the tally cannot derive it itself (#471).+ pub fn add(self: *CostTally, io: Io, billing: Billing, model: []const u8, uncached_in: i64, cache_in: i64, out: i64) void {self.mutex.lockUncancelable(io);defer self.mutex.unlock(io);self.api_calls +|= 1;self.in_tokens +|= @intCast(@max(uncached_in, 0));self.cache_tokens +|= @intCast(@max(cache_in, 0));self.out_tokens +|= @intCast(@max(out, 0));- switch (billingFor(provider_id, model)) {+ switch (billing) {.sub => self.sub_calls +|= 1,.unpriced => self.unpriced_calls +|= 1,- .priced => self.usd += usdFor(priceFor(model).?, uncached_in, cache_in, out),+ // No `.?`: the class comes from the caller; a dropped row falls back.+ .priced => {+ if (priceFor(model)) |p| self.usd += usdFor(p, uncached_in, cache_in, out) else self.unpriced_calls +|= 1;+ },}}@@ -181,6 +187,8 @@ pub const model_table = [_]ModelInfo{// (windows from max_input_tokens) — do not grow or "fix" these rows to// track releases; they exist so boot, --schema, and routing work before// the first authenticated fetch.+ .{ .provider = "anthropic", .name = "claude-opus-5", .context = 1_000_000 },+ .{ .provider = "anthropic", .name = "claude-sonnet-5", .context = 1_000_000 },.{ .provider = "anthropic", .name = "claude-fable-5", .context = 1_000_000 },.{ .provider = "anthropic", .name = "claude-opus-4-8", .context = 1_000_000 },.{ .provider = "anthropic", .name = "claude-opus-4-7", .context = 1_000_000 },@@ -577,13 +585,8 @@ test "refresh overlay augments price/context lookups (codex cap still applies)"try std.testing.expectEqual(codex_context_window, contextFor("codex", "future-model-x"));}-test "billingFor: subscription, priced, unpriced classification" {- try std.testing.expectEqual(Billing.sub, billingFor("codex", "gpt-5.5")); // priced model, but flat-rate login- try std.testing.expectEqual(Billing.sub, billingFor("kimi", "k3"));- try std.testing.expectEqual(Billing.priced, billingFor("openai", "gpt-5.5"));- try std.testing.expectEqual(Billing.priced, billingFor("anthropic", "claude-sonnet-4-6"));- try std.testing.expectEqual(Billing.unpriced, billingFor("openai", "mystery-model"));-}+// Seat classification moved to billing.zig with #471 — it needs the provider+// spec and the credential source, not the price sheet. Its tests live there.test "usdFor: per-million math and negative clamping" {const p = priceFor("gpt-5.5").?; // $5 in / $30 out / $0.5 cache per 1Mdiff --git a/src/pricing_tests.zig b/src/pricing_tests.zigindex fb1bdc41..b05ab1da 100644--- a/src/pricing_tests.zig+++ b/src/pricing_tests.zig@@ -12,7 +12,7 @@ test "CostTally token and call counters saturate" {.api_calls = std.math.maxInt(u64),.sub_calls = std.math.maxInt(u64),};- tally.add(std.testing.io, "codex", "gpt-5.5", 10, 10, 10);+ tally.add(std.testing.io, .sub, "gpt-5.5", 10, 10, 10);try std.testing.expectEqual(std.math.maxInt(u64), tally.in_tokens);try std.testing.expectEqual(std.math.maxInt(u64), tally.cache_tokens);try std.testing.expectEqual(std.math.maxInt(u64), tally.out_tokens);diff --git a/src/provider.zig b/src/provider.zigindex 98dc196f..027b7dcf 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -38,7 +38,7 @@ fn contextWindowFor(provider_id: []const u8, model: []const u8) u64 {/// provider_specs; one additional OpenAI-compatible router may be loaded from/// `.graff/.config.router` at startup.pub const ProviderSpec = struct {- pub const LoginKind = enum { api_key, codegraff_device, codex_device, kimi_device };+ pub const LoginKind = enum { api_key, codegraff_device, codex_device, kimi_device, xai_device };pub const CatalogKind = enum { baked, codex, kimi, openai, anthropic };id: []const u8,@@ -49,6 +49,17 @@ pub const ProviderSpec = struct {env_key: []const u8,default_model: []const u8,login: LoginKind = .api_key,+ /// #471: a login on this provider buys a FLAT-RATE plan (ChatGPT/Codex,+ /// Kimi Code, SuperGrok), so its calls cost nothing per token and must not+ /// be priced off the models.dev sheet. Declared here so a new subscription+ /// provider is one field rather than a hardcoded id list in a second file.+ ///+ /// It is the login that is flat-rate, not the vendor: an env key or `/key`+ /// on the SAME provider still bills per token, so billing.zig reads this+ /// only when the credential's `Keys.CredentialSource` is `.login`. The+ /// codegraff gateway is deliberately false — its device login draws on+ /// metered credits, not a plan.+ sub_login: bool = false,catalog: CatalogKind = .baked,models_url: []const u8 = "",takes_effort: bool = false,@@ -67,12 +78,14 @@ pub const provider_specs = [_]ProviderSpec{// Kimi Code publishes the protocol per model. Missing/`kimi` is the native// chat-completions wire; a live `protocol: anthropic` row is switched in// Keys.build to the beta Messages endpoint + x-api-key, matching kimi-code.- .{ .id = "kimi", .display_name = "Kimi", .kind = .openai, .auth = .bearer, .url = kimi_native_url, .env_key = "KIMI_API_KEY", .default_model = "k3", .login = .kimi_device, .catalog = .kimi },+ .{ .id = "kimi", .display_name = "Kimi", .kind = .openai, .auth = .bearer, .url = kimi_native_url, .env_key = "KIMI_API_KEY", .default_model = "k3", .login = .kimi_device, .sub_login = true, .catalog = .kimi },// moonshot: the regular Kimi Open Platform (pay-as-you-go API key, not the// Coding plan). OpenAI-compatible; .cn host for China. kimi-latest tracks// the newest Kimi. Same /v1/models discovery applies if wired later..{ .id = "moonshot", .display_name = "Moonshot", .kind = .openai, .auth = .bearer, .url = "https://api.moonshot.ai/v1/chat/completions", .env_key = "MOONSHOT_API_KEY", .default_model = "kimi-latest" },- .{ .id = "xai", .display_name = "xAI", .kind = .openai, .auth = .bearer, .url = "https://api.x.ai/v1/chat/completions", .env_key = "XAI_API_KEY", .default_model = "grok-4.3" },+ // `graff login xai` is a real device-code OAuth flow (oauth.zig), so xAI's+ // login is a SuperGrok plan while XAI_API_KEY is metered api.x.ai access.+ .{ .id = "xai", .display_name = "xAI", .kind = .openai, .auth = .bearer, .url = "https://api.x.ai/v1/chat/completions", .env_key = "XAI_API_KEY", .default_model = "grok-4.3", .login = .xai_device, .sub_login = true },.{ .id = "zai", .display_name = "Z.AI", .kind = .openai, .auth = .bearer, .url = "https://api.z.ai/api/paas/v4/chat/completions", .env_key = "ZAI_API_KEY", .default_model = "glm-5.2" },.{ .id = "fugu", .display_name = "fugu", .kind = .openai, .auth = .bearer, .url = "https://api.sakana.ai/v1/chat/completions", .env_key = "FUGU_API_KEY", .default_model = "fugu-ultra" },.{ .id = "fireworks", .display_name = "fireworks", .kind = .openai, .auth = .bearer, .url = "https://api.fireworks.ai/inference/v1/chat/completions", .env_key = "FIREWORKS_API_KEY", .default_model = "accounts/fireworks/models/deepseek-v4-pro" },@@ -86,7 +99,7 @@ pub const provider_specs = [_]ProviderSpec{// — it's the OAuth access token read from CODEX_HOME/auth.json at startup// (see loadCodexAuth), the same on-disk-credential trick used for the// codegraff gateway key in ~/forge/.credentials.json.- .{ .id = "codex", .display_name = "Codex (ChatGPT)", .kind = .responses, .auth = .bearer, .url = "https://chatgpt.com/backend-api/codex/responses", .env_key = "CODEX_DISABLED", .default_model = "gpt-5.6-sol", .login = .codex_device, .catalog = .codex },+ .{ .id = "codex", .display_name = "Codex (ChatGPT)", .kind = .responses, .auth = .bearer, .url = "https://chatgpt.com/backend-api/codex/responses", .env_key = "CODEX_DISABLED", .default_model = "gpt-5.6-sol", .login = .codex_device, .sub_login = true, .catalog = .codex },};/// Optional workspace-local router loaded from `.graff/.config.router`.diff --git a/src/route_check.zig b/src/route_check.zigindex fa701481..ac17fb14 100644--- a/src/route_check.zig+++ b/src/route_check.zig@@ -14,6 +14,8 @@ const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const pricing = @import("pricing.zig");+const billing = @import("billing.zig");+const report = @import("route_report.zig");const provider_mod = @import("provider.zig");pub const Seat = struct {@@ -37,7 +39,7 @@ pub fn seatFor(keys: provider_mod.Keys, query: []const u8) Answer {return .{ .seat = .{.pid = p.id,.model = p.model,- .billing = pricing.billingFor(p.id, p.model),+ .billing = billing.forProvider(p),.source = p.source,} };}@@ -57,8 +59,12 @@ pub fn command(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, sconst rk = try @import("startup.zig").resolveKeys(io, gpa, arena, environ_map, null, null);if (sub_args.len == 0) {const d = rk.default_provider;- try out.print("session default: {s}/{s} · auth: {s} · billing: {s}\n", .{ d.id, d.model, d.source.label(), billingLabel(pricing.billingFor(d.id, d.model)) });- try out.writeAll("\nusage: graff route <model> [<model>…] — dry-run which provider a model would land on (no API call)\n");+ try out.print("session default: {s}/{s} · auth: {s} · billing: {s}\n\n", .{ d.id, d.model, d.source.label(), billingLabel(billing.forProvider(d)) });+ // #471: which providers are actually reachable, what each bills, and+ // the worker tiers it offers — the question that decides where every+ // unpinned subagent lands.+ const home = @import("keys_cli.zig").homeEnv(environ_map) orelse "";+ try report.write(out, report.rows(io, arena, rk.keys, home));try out.flush();return;}@@ -79,7 +85,9 @@ pub fn command(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, s}test "seatFor: family-alias spelling seats the sub, exact names hold, unknown misses" {- const all = provider_mod.Keys{ .values = @splat("k") };+ // Sources matter since #471: the flat-rate plan is the LOGIN, so a seat+ // only bills as .sub when its credential came from one.+ const all = provider_mod.Keys{ .values = @splat("k"), .sources = @splat(.login) };const kk = seatFor(all, "kimi-k3");try std.testing.expectEqualStrings("kimi", kk.seat.pid);try std.testing.expectEqualStrings("k3", kk.seat.model);@@ -88,6 +96,12 @@ test "seatFor: family-alias spelling seats the sub, exact names hold, unknown mitry std.testing.expectEqualStrings("codex", sol.seat.pid);try std.testing.expectEqual(pricing.Billing.sub, sol.seat.billing);try std.testing.expect(seatFor(all, "totally-unknown-zzz") == .unknown);++ // The same seat reached with KIMI_API_KEY is billed, not free. (Whether it+ // lands on .priced or .unpriced is the price sheet's business; what must+ // never happen is a metered key being written off as a subscription.)+ const keyed = provider_mod.Keys{ .values = @splat("k"), .sources = @splat(.environment) };+ try std.testing.expect(seatFor(keyed, "kimi-k3").seat.billing != .sub);}test "seatFor: catalogued model with no serving credential reports no_credential, not a gateway seat" {diff --git a/src/route_phase.zig b/src/route_phase.zigindex 0f51c487..e389336a 100644--- a/src/route_phase.zig+++ b/src/route_phase.zig@@ -165,7 +165,7 @@ pub fn forPhase(// Re-clear the cost ceiling for the swapped model: learning may descend// price, never escalate it, and a swap that somehow fails the ceiling is// dropped rather than failing the phase.- if (!pin_mod.rungAffordable(base.model, learned)) return seat;+ if (!pin_mod.rungAffordableOn(base, learned)) return seat;seat.pin = base.withModel(learned);seat.provider = seat.pin.?;return seat;diff --git a/src/route_report.zig b/src/route_report.zignew file mode 100644index 00000000..af551e80--- /dev/null+++ b/src/route_report.zig@@ -0,0 +1,186 @@+//! `graff route` with no model: which providers you can actually reach right+//! now, what each one bills, and the worker tiers it offers (#471).+//!+//! The gap this fills: `graff models` lists the catalog and `graff route+//! <model>` resolves ONE seat, so nothing answered "what am I logged into,+//! and which of those cost me money?". That question decides where every+//! unpinned subagent lands, and it was only answerable by reading traces.+//!+//! THE COLLISION IT EXISTS TO SURFACE. A provider can hold two credentials at+//! once — `KIMI_API_KEY` *and* a `graff login kimi` plan, `XAI_API_KEY` *and*+//! SuperGrok. `Keys` has one slot per provider and startup.resolveKeys fills+//! it from the environment FIRST, loading a login only `if (value == null)`.+//! So the metered key silently wins and every call bills per token against a+//! subscription already paid for — the expensive branch, chosen invisibly.+//! Detecting it needs a credential probe that does NOT consume the login, so+//! `loginOnDisk` only stats the file: no refresh, no network, no spend.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const provider_mod = @import("provider.zig");+const billing_mod = @import("billing.zig");+const tier_ladder = @import("subagent_tier_ladder.zig");+const credential_store = @import("credential_store.zig");+const credential_failover = @import("credential_failover.zig");+const oauth_helpers = @import("oauth_helpers.zig");+const pricing = @import("pricing.zig");++pub const Row = struct {+ id: []const u8,+ source: provider_mod.Keys.CredentialSource,+ billing: pricing.Billing,+ frontier: []const u8 = "",+ mid: []const u8 = "",+ small: []const u8 = "",+ /// A saved login exists on disk for this provider, whatever won the slot.+ login_available: bool = false,+ /// A metered credential is parked behind the plan, unused (#471).+ key_standing_by: bool = false,+ /// The plan ran out mid-session and the parked key took over.+ failed_over: bool = false,+};++/// Does a saved device-login credential exist for `spec`? File presence only —+/// never a refresh, so listing providers cannot cost a network round trip or+/// rotate a token out from under a running session.+pub fn loginOnDisk(io: Io, arena: Allocator, home: []const u8, spec: provider_mod.ProviderSpec) bool {+ if (home.len == 0) return false;+ const path = switch (spec.login) {+ .api_key => return false,+ .kimi_device => credential_store.oauthPath(arena, home, ".kimi"),+ .xai_device => credential_store.oauthPath(arena, home, ".xai"),+ .codex_device => blk: {+ const dir = oauth_helpers.codexHomeDir(arena, home) orelse return false;+ break :blk std.fmt.allocPrint(arena, "{s}/auth.json", .{dir}) catch return false;+ },+ .codegraff_device => std.fmt.allocPrint(arena, "{s}/.simple-harness-codegraff.json", .{home}) catch return false,+ };+ if (path.len == 0) return false;+ _ = Io.Dir.cwd().statFile(io, path, .{}) catch return false;+ return true;+}++fn rungOr(name: ?[]const u8) []const u8 {+ return name orelse "";+}++/// One row per provider that has ANY credential. A provider you cannot reach+/// is left out: the question is what is available, not what exists.+pub fn rows(io: Io, arena: Allocator, keys: provider_mod.Keys, home: []const u8) []const Row {+ var out: std.ArrayList(Row) = .empty;+ for (provider_mod.provider_specs) |spec| {+ const source = keys.source(spec.id);+ const on_disk = loginOnDisk(io, arena, home, spec);+ if (source == .none and !on_disk) continue;+ const model = pricing.providerDefaultModel(spec.id, spec.default_model);+ var row: Row = .{+ .id = spec.id,+ .source = source,+ .billing = billing_mod.forSeat(spec.id, model, source),+ .login_available = on_disk,+ .key_standing_by = credential_failover.standingBy(spec.id),+ .failed_over = credential_failover.promoted(spec.id),+ };+ if (tier_ladder.forProvider(spec.id)) |l| {+ row.frontier = l.frontier;+ row.mid = rungOr(l.mid);+ row.small = rungOr(l.small);+ }+ out.append(arena, row) catch break;+ }+ return out.items;+}++pub fn write(out: *Io.Writer, list: []const Row) !void {+ if (list.len == 0) {+ try out.writeAll("no provider credentials found — `graff login <provider>` or `graff key set`\n");+ return;+ }+ try out.writeAll("provider auth billing frontier / mid / small\n");+ for (list) |r| {+ try out.print("{s: <12} {s: <14} {s: <14} ", .{ r.id, r.source.label(), billingWord(r.billing) });+ if (r.frontier.len == 0) {+ try out.writeAll("(no tier ladder — workers inherit the root model)\n");+ } else {+ try out.print("{s} / {s} / {s}\n", .{ r.frontier, dash(r.mid), dash(r.small) });+ }+ }+ var noted = false;+ for (list) |r| {+ if (r.failed_over) {+ noted = true;+ try out.print("\n! {s}: the plan ran out of quota this session, so its API key took over — billing PER TOKEN now.\n", .{r.id});+ } else if (r.key_standing_by) {+ noted = true;+ try out.print("\n· {s}: plan in use; its API key is parked and takes over only if the plan runs out.\n", .{r.id});+ }+ }+ if (!noted) try out.writeAll("\nusage: graff route <model> [<model>…] — dry-run one model's seat (no API call)\n");+}++fn dash(s: []const u8) []const u8 {+ return if (s.len == 0) "-" else s;+}++fn billingWord(b: pricing.Billing) []const u8 {+ return switch (b) {+ .sub => "subscription",+ .priced => "metered",+ .unpriced => "unpriced",+ };+}++test "#471 the plan is in use and the metered key is reported as reserve" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ // Both credentials exist. The plan won the slot; the key is parked. What+ // the user must be able to see is that the reserve exists and is NOT+ // costing them anything yet.+ const reserved: Row = .{ .id = "kimi", .source = .login, .billing = .sub, .frontier = "k3", .mid = "k3", .login_available = true, .key_standing_by = true };+ var buf: std.ArrayList(u8) = .empty;+ var w = std.Io.Writer.Allocating.fromArrayList(a, &buf);+ try write(&w.writer, &.{reserved});+ try std.testing.expect(std.mem.indexOf(u8, w.written(), "parked") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.written(), "subscription") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.written(), "k3 / k3 / -") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.written(), "PER TOKEN") == null); // not billing yet++ // After the plan runs dry the same provider must say so loudly: billing+ // silently changed, which is the one thing the user cannot infer.+ const spent: Row = .{ .id = "kimi", .source = .environment, .billing = .priced, .frontier = "k3", .mid = "k3", .login_available = true, .failed_over = true };+ var buf2: std.ArrayList(u8) = .empty;+ var w2 = std.Io.Writer.Allocating.fromArrayList(a, &buf2);+ try write(&w2.writer, &.{spent});+ try std.testing.expect(std.mem.indexOf(u8, w2.written(), "PER TOKEN") != null);+ try std.testing.expect(std.mem.indexOf(u8, w2.written(), "ran out of quota") != null);++ // A plain provider with no reserve gets no note at all, and one with no+ // ladder says so rather than printing empty columns.+ const bare: Row = .{ .id = "xai", .source = .login, .billing = .sub, .login_available = true };+ var buf3: std.ArrayList(u8) = .empty;+ var w3 = std.Io.Writer.Allocating.fromArrayList(a, &buf3);+ try write(&w3.writer, &.{bare});+ try std.testing.expect(std.mem.indexOf(u8, w3.written(), "no tier ladder") != null);+ try std.testing.expect(std.mem.indexOf(u8, w3.written(), "parked") == null);+}++test "#471 loginOnDisk never reports a login for an api_key-only provider" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ for (provider_mod.provider_specs) |spec| {+ if (spec.login != .api_key) continue;+ try std.testing.expect(!loginOnDisk(std.testing.io, a, "/nonexistent-home", spec));+ }+ // …and a device-login provider with no credential file is simply absent,+ // not an error: `graff route` must work before you have logged into+ // anything at all.+ for (provider_mod.provider_specs) |spec| {+ if (spec.login == .api_key) continue;+ try std.testing.expect(!loginOnDisk(std.testing.io, a, "/nonexistent-home", spec));+ }+}diff --git a/src/startup.zig b/src/startup.zigindex 0390742d..b93a1867 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -31,6 +31,7 @@ const mcp = @import("mcp.zig");const provider_mod = @import("provider.zig");const keys_cli = @import("keys_cli.zig");const oauth = @import("oauth.zig");+const credential_failover = @import("credential_failover.zig"); // #471: plan beats key, key stands byconst pricing = @import("pricing.zig");const models_cache = @import("models_cache.zig");const kimi_catalog = @import("kimi_catalog.zig");@@ -187,27 +188,15 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytypcodex_account = auth.account;}}- // Kimi "login": OAuth device-flow token from `graff login kimi`- // (~/.kimi/credentials/graff-oauth.json), refreshed in place when near- // expiry. Same on-disk-credential pattern as codex/codegraff; env wins.- // #274: refreshing is a synchronous network round-trip, so an explicit- // provider/exact-model selection that cannot route to kimi/xai must skip- // it entirely rather than pay for it on every startup — same selective-- // scope discipline as the stored-key load a few lines below.+ // #471: the kimi/xAI device logins outrank their env keys, and the metered+ // key is parked rather than dropped — credential_failover.preferPlan owns+ // that policy. #274: the gate stays here because only startup knows what+ // this invocation selected; a login refresh is a synchronous network call+ // no provider outside the selection should pay for.if (keys_cli.homeEnv(environ_map)) |home| {for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {- if (std.mem.eql(u8, spec.id, "kimi") and value.* == null and storedKeyMayAffectSelection(spec.id, model_flag, worker_provider_hint)) {- if (oauth.loadKimiOAuth(io, gpa, arena, home, false, null)) |key| {- value.* = key;- source.* = .login;- }- }- if (std.mem.eql(u8, spec.id, "xai") and value.* == null and storedKeyMayAffectSelection(spec.id, model_flag, worker_provider_hint)) {- if (oauth.loadXaiOAuth(io, gpa, arena, home, false, null)) |key| {- value.* = key;- source.* = .login;- }- }+ if (!storedKeyMayAffectSelection(spec.id, model_flag, worker_provider_hint)) continue;+ credential_failover.preferPlan(io, gpa, arena, home, spec, value, source);}}// An explicit provider or exact catalog model can observe only itsdiff --git a/src/subagent_pin.zig b/src/subagent_pin.zigindex 04110e9f..b24ba5df 100644--- a/src/subagent_pin.zig+++ b/src/subagent_pin.zig@@ -60,6 +60,7 @@ const std = @import("std");const provider_mod = @import("provider.zig");const Provider = provider_mod.Provider;const pricing = @import("pricing.zig");+const billing = @import("billing.zig"); // #471: seat billing class (flat-rate login vs metered key)const bench_priors = @import("bench_priors.zig");const fleet = @import("fleet.zig");const selection = @import("subagent_selection.zig");@@ -243,14 +244,14 @@ pub fn resolveIn(base: Provider, pin: Pin, cell: Cell) Resolved {// opus-class) an automatic rung must not spend more than the model// the user chose. Escalation stays possible, but only by naming the// model in the call — visible, never implicit.- if (!rungAffordable(base.model, resolved)) return .{ .outcome = .rung_pricier };+ if (!rungAffordableOn(base, resolved)) return .{ .outcome = .rung_pricier };// #372: the learned layer sits HERE, below every explicit pin. It is// handed the CATALOG-resolved ladder answer and may return a measured// improvement on it; a swap that somehow fails the same cost ceiling// is dropped rather than failing the spawn, so the worst case is// today's ladder answer.if (route_policy.learnedRung(base.id, cell, resolved)) |learned| {- if (rungAffordable(base.model, learned)) return finish(base, learned, .learned_policy);+ if (rungAffordableOn(base, learned)) return finish(base, learned, .learned_policy);}return finish(base, resolved, .ladder);}@@ -258,12 +259,28 @@ pub fn resolveIn(base: Provider, pin: Pin, cell: Cell) Resolved {return .{};}-/// Flat-rate, device-login subscription providers, in fallback preference-/// order (bench scores rank them when several are logged in). codegraff's-/// license is deliberately absent: it fronts the metered multi-vendor-/// gateway this policy protects the user's wallet FROM. `pub` since #380:+/// Flat-rate, device-login subscription providers. Derived from the specs'+/// `sub_login` declaration rather than listed here, because #471 found this+/// was the FOURTH hardcoded "which providers are subscriptions" list in the+/// tree and they disagreed: xAI has had a real device-code login since+/// oauth.zig's xaiLogin, and its absence from this array is what kept a paid+/// SuperGrok seat out of sub-first routing entirely. codegraff's license+/// stays out for the same reason as before — `sub_login = false`, because it+/// fronts the metered multi-vendor gateway this policy protects the wallet+/// FROM. Order follows provider_specs; bench scores rank the candidates that+/// are actually logged in, so it only breaks exact ties. `pub` since #380:/// vision_ask.visionSeat searches the same candidates under the same rule.-pub const subscription_providers = [_][]const u8{ "codex", "kimi" };+pub const subscription_providers = blk: {+ var ids: [provider_mod.provider_specs.len][]const u8 = undefined;+ var n: usize = 0;+ for (provider_mod.provider_specs) |spec| {+ if (!spec.sub_login) continue;+ ids[n] = spec.id;+ n += 1;+ }+ const frozen = ids[0..n].*;+ break :blk frozen;+};/// SUB-FIRST TIER ROUTING (explicit `tier` asks only — the silent no-tier/// default still inherits the user's chosen family): a logged-in flat-rate@@ -297,6 +314,20 @@ fn subscriptionRung(tier: Tier, base: Provider) ?Resolved {/// subscription families like codex carry no per-token price — blocking/// there would kill every intra-family rung); a priced base with an unpriced/// rung cannot prove the rung is not an escalation, so it blocks.+///+/// #471: a flat-rate BASE seat has no ceiling either, and unlike the unpriced+/// case that is not an accident of the sheet. The ceiling exists to stop an+/// automatic rung from spending more than the model the user chose; on a+/// subscription every rung spends the same nothing, so enforcing models.dev+/// list prices there would gate a seat by money nobody is paying. Note the+/// base's own price row can appear at any time — `price_overlay` is rebuilt+/// from a remote sheet on every `graff models refresh` and matches on bare+/// model name — so this cannot rely on `priceFor` returning null.+pub fn rungAffordableOn(base: Provider, rung_model: []const u8) bool {+ if (billing.freeAtTheMargin(base)) return true;+ return rungAffordable(base.model, rung_model);+}+pub fn rungAffordable(base_model: []const u8, rung_model: []const u8) bool {const bp = pricing.priceFor(base_model) orelse return true;const rp = pricing.priceFor(rung_model) orelse return false;diff --git a/src/subagent_pin_tests.zig b/src/subagent_pin_tests.zigindex 539c63d6..0346dcb9 100644--- a/src/subagent_pin_tests.zig+++ b/src/subagent_pin_tests.zig@@ -171,30 +171,32 @@ test "graceful fallback: every unhonorable pin keeps the session default, never// A provider with no ladder at all: a tier pin is a no-op, not a crash.const xai: Provider = .{ .id = "xai", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "grok-4.3", .context = 256_000 };try std.testing.expectEqual(pin_mod.Outcome.no_ladder, pin_mod.forSpawn(xai, obj(a, "{\"tier\":\"small\"}"), true).outcome);- // A ladder without that rung (deepseek has no `small`) — never rounds to- // the nearest rung.- const deepseek: Provider = .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-pro", .context = 128_000 };+ // A ladder without that rung (deepseek is frontier-only, anthropic has no+ // `mid`) — never rounds to the nearest rung.+ const deepseek: Provider = .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-flash", .context = 128_000 };try std.testing.expectEqual(pin_mod.Outcome.no_rung, pin_mod.forSpawn(deepseek, obj(a, "{\"tier\":\"small\"}"), true).outcome);- try std.testing.expectEqualStrings("deepseek-v4-flash", pin_mod.forSpawn(deepseek, obj(a, "{\"tier\":\"mid\"}"), true).provider.?.model);+ const opus: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-opus-5", .context = 1_000_000 };+ try std.testing.expectEqual(pin_mod.Outcome.no_rung, pin_mod.forSpawn(opus, obj(a, "{\"tier\":\"mid\"}"), true).outcome);+ try std.testing.expectEqualStrings("claude-sonnet-5", pin_mod.forSpawn(opus, obj(a, "{\"tier\":\"small\"}"), true).provider.?.model);}test "cost ceiling: a tier rung may descend price but never raise it" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();const a = arena_state.allocator();- // deepseek's compiled ladder: frontier deepseek-v4-pro ($0.435/0.87),- // mid deepseek-v4-flash ($0.14/0.28). Descending is fine…- const pro: Provider = .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-pro", .context = 128_000 };- try std.testing.expectEqualStrings("deepseek-v4-flash", pin_mod.forSpawn(pro, obj(a, "{\"tier\":\"mid\"}"), true).provider.?.model);- // …but a flash root asking for the frontier rung would RAISE cost —+ // anthropic's compiled ladder: frontier claude-opus-5 ($5/25), small+ // claude-sonnet-5 ($2/10). Descending is fine…+ const opus: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-opus-5", .context = 1_000_000 };+ try std.testing.expectEqualStrings("claude-sonnet-5", pin_mod.forSpawn(opus, obj(a, "{\"tier\":\"small\"}"), true).provider.?.model);+ // …but a sonnet-5 root asking for the frontier rung would RAISE cost —// blocked with a reason, spawn keeps the session default. Naming the// model explicitly still escalates: that is the visible, consented path.- const flash: Provider = .{ .id = "deepseek", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "deepseek-v4-flash", .context = 128_000 };- const blocked = pin_mod.forSpawn(flash, obj(a, "{\"tier\":\"frontier\"}"), true);+ const sonnet: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-sonnet-5", .context = 1_000_000 };+ const blocked = pin_mod.forSpawn(sonnet, obj(a, "{\"tier\":\"frontier\"}"), true);try std.testing.expectEqual(pin_mod.Outcome.rung_pricier, blocked.outcome);try std.testing.expect(blocked.provider == null);try std.testing.expect(blocked.outcome.describe().len > 0);- try std.testing.expectEqualStrings("deepseek-v4-pro", pin_mod.forSpawn(flash, obj(a, "{\"model\":\"deepseek-v4-pro\"}"), true).provider.?.model);+ try std.testing.expectEqualStrings("claude-opus-5", pin_mod.forSpawn(sonnet, obj(a, "{\"model\":\"claude-opus-5\"}"), true).provider.?.model);// The affordability rule itself: unpriced base has no ceiling; a priced// base blocks an unpriced rung (it cannot prove it is not an escalation).try std.testing.expect(pin_mod.rungAffordable("model-with-no-price-anywhere", "deepseek-v4-pro"));@@ -233,6 +235,105 @@ test "sub-first routing: a logged-in flat-rate sub outranks metered for explicittry std.testing.expectEqual(pin_mod.Outcome.no_rung, pin_mod.forSpawn(dsv, obj(a, "{\"tier\":\"small\"}"), true).outcome);}+test "two logins split the tiers: k3 is mid, luna is the mechanical rung (#471)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const bench = @import("bench_priors.zig");+ const saved = bench.g_keys;+ defer bench.g_keys = saved;+ var keys: provider_mod.Keys = .{ .values = @splat(null) };+ for (provider_mod.provider_specs, 0..) |spec, i| {+ if (std.mem.eql(u8, spec.id, "kimi") or std.mem.eql(u8, spec.id, "codex")) keys.values[i] = "tok";+ }+ bench.g_keys = &keys;++ // Both plans logged in, metered anthropic root. The three tiers land on+ // three different paid-for seats, and none of them costs a cent extra:+ // frontier -> codex sol (73 beats k3's 68 on the bench sheet)+ // mid -> kimi k3 (codex has no mid rung; terra is dominated)+ // small -> codex luna (kimi declares no small rung, so k3's higher+ // score cannot swallow the mechanical tier —+ // code search and greps stay on the cheap seat)+ const claude: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-opus-5", .context = 1_000_000 };+ const want = [_]struct { tier: []const u8, pid: []const u8, model: []const u8 }{+ .{ .tier = "frontier", .pid = "codex", .model = "gpt-5.6-sol" },+ .{ .tier = "mid", .pid = "kimi", .model = "k3" },+ .{ .tier = "small", .pid = "codex", .model = "gpt-5.6-luna" },+ };+ for (want) |w| {+ const body = std.fmt.allocPrint(a, "{{\"tier\":\"{s}\"}}", .{w.tier}) catch unreachable;+ const routed = pin_mod.forSpawn(claude, obj(a, body), true);+ try std.testing.expectEqual(pin_mod.Outcome.sub_routed, routed.outcome);+ try std.testing.expectEqualStrings(w.pid, routed.provider.?.id);+ try std.testing.expectEqualStrings(w.model, routed.provider.?.model);+ }++ // The regression this guards: kimi used to have no ladder row at all, so+ // sub-first routing skipped it and tier:"mid" fell through to a METERED+ // anthropic rung — paying for work a logged-in plan already covers.+ // The candidate list is derived from the specs' sub_login declaration.+ var saw_kimi = false;+ for (pin_mod.subscription_providers) |sid| {+ try std.testing.expect(!std.mem.eql(u8, sid, "zai"));+ try std.testing.expect(!std.mem.eql(u8, sid, "codegraff"));+ if (std.mem.eql(u8, sid, "kimi")) saw_kimi = true;+ }+ try std.testing.expect(saw_kimi);+}++test "a kimi root borrows codex's cheap rung: small -> luna when it is logged in (#471)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const bench = @import("bench_priors.zig");+ const sl = bench.g_ladders;+ const sk = bench.g_keys;+ defer {+ bench.g_ladders = sl;+ bench.g_keys = sk;+ }+ // A REAL session's ladders, not the compiled fallbacks: the shipped bench+ // sheet dominates codex's terra out of existence, so codex has no mid rung+ // and kimi's k3 is the only mid seat either plan offers.+ bench.g_ladders = bench.derive(a, &bench.builtin_entries);++ const kimi_root: Provider = .{ .id = "kimi", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "k3", .context = 1_048_576 };+ var both: provider_mod.Keys = .{ .values = @splat(null) };+ for (provider_mod.provider_specs, 0..) |spec, i| {+ if (std.mem.eql(u8, spec.id, "kimi") or std.mem.eql(u8, spec.id, "codex")) both.values[i] = "tok";+ }+ bench.g_keys = &both;++ // The point of sub-first routing seen from the other side: sitting ON the+ // kimi plan, mechanical work still goes to codex's luna, because kimi's+ // plan has no cheap rung and the codex login is already paid for. Neither+ // hop costs a cent, so crossing is free — and the login IS the consent.+ const small = pin_mod.forSpawn(kimi_root, obj(a, "{\"tier\":\"small\"}"), true);+ try std.testing.expectEqual(pin_mod.Outcome.sub_routed, small.outcome);+ try std.testing.expectEqualStrings("codex", small.provider.?.id);+ try std.testing.expectEqualStrings("gpt-5.6-luna", small.provider.?.model);++ // Escalating works the same way: sol outscores k3 on the bench sheet.+ const top = pin_mod.forSpawn(kimi_root, obj(a, "{\"tier\":\"frontier\"}"), true);+ try std.testing.expectEqual(pin_mod.Outcome.sub_routed, top.outcome);+ try std.testing.expectEqualStrings("gpt-5.6-sol", top.provider.?.model);++ // …and asking for mid while already seated on the mid model is a no-op,+ // not a pointless re-seat: k3 IS kimi's mid rung.+ try std.testing.expectEqual(pin_mod.Outcome.same, pin_mod.forSpawn(kimi_root, obj(a, "{\"tier\":\"mid\"}"), true).outcome);++ // Kimi alone: nothing to borrow, so the cheap tier has no rung and the+ // spawn keeps the session default rather than silently escalating to k3.+ var solo: provider_mod.Keys = .{ .values = @splat(null) };+ for (provider_mod.provider_specs, 0..) |spec, i| {+ if (std.mem.eql(u8, spec.id, "kimi")) solo.values[i] = "tok";+ }+ bench.g_keys = &solo;+ try std.testing.expectEqual(pin_mod.Outcome.no_rung, pin_mod.forSpawn(kimi_root, obj(a, "{\"tier\":\"small\"}"), true).outcome);+ try std.testing.expectEqual(pin_mod.Outcome.same, pin_mod.forSpawn(kimi_root, obj(a, "{\"tier\":\"frontier\"}"), true).outcome);+}+test "a pin never crosses a provider boundary" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/subagent_selection.zig b/src/subagent_selection.zigindex 9e28c734..266be944 100644--- a/src/subagent_selection.zig+++ b/src/subagent_selection.zig@@ -187,13 +187,16 @@ test "defaultLadderModel: descends one rung per provider, bottom rung inherits"try std.testing.expect(defaultLadderModel(mk("codex", "gpt-5.6-luna")) == null);// openai: same shape, sibling namestry std.testing.expectEqualStrings("gpt-5.6-terra", defaultLadderModel(mk("openai", "gpt-5.6")).?);- // anthropic: opus -> sonnet -> haiku -> (bottom)- try std.testing.expectEqualStrings("claude-sonnet-4-6", defaultLadderModel(mk("anthropic", "claude-opus-4-8")).?);- try std.testing.expectEqualStrings("claude-haiku-4-5", defaultLadderModel(mk("anthropic", "claude-sonnet-4-6")).?);- try std.testing.expect(defaultLadderModel(mk("anthropic", "claude-haiku-4-5")) == null);- // deepseek: pro steps to its only cheaper rung (flash); flash has nowhere lower- try std.testing.expectEqualStrings("deepseek-v4-flash", defaultLadderModel(mk("deepseek", "deepseek-v4-pro")).?);+ // anthropic: opus-5 -> sonnet-5 -> (bottom). #471 dropped the opus-4-8 and+ // sonnet-4-6 rungs: every opus generation bills the same $5/$25 per MTok,+ // so descending within the family is not a cheaper seat at all.+ try std.testing.expectEqualStrings("claude-sonnet-5", defaultLadderModel(mk("anthropic", "claude-opus-5")).?);+ try std.testing.expect(defaultLadderModel(mk("anthropic", "claude-sonnet-5")) == null);+ try std.testing.expect(defaultLadderModel(mk("anthropic", "claude-opus-4-8")) == null);+ // deepseek: flash overtook pro and is 3x cheaper too, so it is the whole+ // ladder — one seat, nothing to descend to, and pro is not a rung at all.try std.testing.expect(defaultLadderModel(mk("deepseek", "deepseek-v4-flash")) == null);+ try std.testing.expect(defaultLadderModel(mk("deepseek", "deepseek-v4-pro")) == null);// unlisted provider -> no ladder at alltry std.testing.expect(defaultLadderModel(mk("xai", "grok-4.3")) == null);// a real, catalogued model that just isn't a rung on its own provider's@@ -212,10 +215,10 @@ test "default ladder: resolves the mid sibling when no flags are given" {try std.testing.expectEqualStrings("codex", worker.id); // provider-local, unpinnedtry std.testing.expectEqualStrings("gpt-5.6-terra", worker.model);- const anthropic_root = try keys.providerById("anthropic", "claude-opus-4-8");+ const anthropic_root = try keys.providerById("anthropic", "claude-opus-5");const anthropic_worker = resolveSubagentProvider(keys, anthropic_root, null, null, false, false).?;try std.testing.expectEqualStrings("anthropic", anthropic_worker.id);- try std.testing.expectEqualStrings("claude-sonnet-4-6", anthropic_worker.model);+ try std.testing.expectEqualStrings("claude-sonnet-5", anthropic_worker.model);}test "default ladder: bottom-rung and off-ladder roots inherit (resolve to null)" {diff --git a/src/subagent_tier_ladder.zig b/src/subagent_tier_ladder.zigindex 921b1dea..29ee77d6 100644--- a/src/subagent_tier_ladder.zig+++ b/src/subagent_tier_ladder.zig@@ -65,17 +65,74 @@ pub const TierLadder = struct {pub const ladders = [_]TierLadder{.{ .provider = "codex", .frontier = "gpt-5.6-sol", .mid = "gpt-5.6-terra", .small = "gpt-5.6-luna" },.{ .provider = "openai", .frontier = "gpt-5.6", .mid = "gpt-5.6-terra", .small = "gpt-5.6-luna" },- .{ .provider = "anthropic", .frontier = "claude-opus-4-8", .mid = "claude-sonnet-4-6", .small = "claude-haiku-4-5" },- .{ .provider = "deepseek", .frontier = "deepseek-v4-pro", .mid = "deepseek-v4-flash" },+ // #471: opus-5 and sonnet-5 are the current lineup, and the rungs below+ // frontier must be cheaper SEATS. Every opus generation bills the same+ // $5/$25 per MTok, so "descend from opus-5 to opus-4-8" saves nothing —+ // it is the same seat, one generation older. sonnet-5 at $2/$10 is the+ // real cheap rung, 2.5x under opus on both halves of the bill.+ .{ .provider = "anthropic", .frontier = "claude-opus-5", .small = "claude-sonnet-5" },+ // deepseek-v4-flash overtook pro: better AND $0.14/$0.28 against pro's+ // $0.435/$0.87. Pro is dominated on both axes, so it is not a rung under+ // flash — it is just worse. One seat, no descent.+ .{ .provider = "deepseek", .frontier = "deepseek-v4-flash" },+ // Kimi's plan is one flagship. k3 is the MID-tier subscription seat —+ // sub-first routing sends `tier:"mid"` here (codex has no mid rung) while+ // `tier:"small"` still lands on codex's luna, which is what the cheap+ // mechanical work (code search, greps, extraction) actually wants. Giving+ // k3 a `small` rung too would let it outscore luna and swallow that tier.+ .{ .provider = "kimi", .frontier = "k3", .mid = "k3" },};+/// Is `rung` a genuinely cheaper SEAT than `frontier` — strictly less $/MTok+/// on the real price sheet? Unknown on either side answers true: an unpriced+/// model cannot be disproved (codex's `gpt-5.6-sol` has no row at all), and+/// #291's descent must keep working there.+///+/// #471: the bench sheet ranks by $/TASK, which folds the seat's rate together+/// with how many tokens a model burns, so a terser model of the same price+/// reads as "cheaper". That is how `claude-opus-4-8` came to sit under+/// `claude-opus-5` as anthropic's cheap rung while billing the identical+/// $5/$25 per MTok — a descent that saves literally nothing.+pub fn cheaperSeat(frontier: []const u8, rung: []const u8) bool {+ // The SAME model at a lower rung is a one-seat plan describing itself, not+ // a fake descent: Kimi's subscription serves only k3, so k3 is both its+ // frontier and its mid. What the check forbids is a DIFFERENT model that+ // costs the same or more — opus-4-8 under opus-5 — because that trades+ // capability away for nothing.+ if (std.mem.eql(u8, frontier, rung)) return true;+ const fp = pricing.priceFor(frontier) orelse return true;+ const rp = pricing.priceFor(rung) orelse return true;+ return rp.in + rp.out < fp.in + fp.out;+}++/// Drop any rung that is not a cheaper seat than the ladder's own frontier.+fn seatChecked(l: TierLadder) TierLadder {+ var out = l;+ if (out.mid) |m| if (!cheaperSeat(out.frontier, m)) {+ out.mid = null;+ };+ if (out.small) |s| if (!cheaperSeat(out.frontier, s)) {+ out.small = null;+ };+ return out;+}+/// The ladder row for a provider, if any. A bench-derived ladder (a/// .harness/bench.json score/cost sheet — see bench_priors.zig) outranks the/// compiled table: measured capability+cost beats a hand-picked default. A/// provider absent from both has no default tiering — roots on it inherit.+///+/// #471: a derived ladder is seat-checked first, and one left with NO cheaper+/// rung at all is not a ladder — it offers no descent — so the compiled row+/// takes over rather than the provider losing its tiering entirely. Measured+/// data still outranks the default whenever it names a real cheaper seat.pub fn forProvider(provider_id: []const u8) ?TierLadder {- for (@import("bench_priors.zig").g_ladders) |l| if (std.mem.eql(u8, l.provider, provider_id)) return l;- for (ladders) |l| if (std.mem.eql(u8, l.provider, provider_id)) return l;+ for (@import("bench_priors.zig").g_ladders) |l| if (std.mem.eql(u8, l.provider, provider_id)) {+ const checked = seatChecked(l);+ if (checked.mid != null or checked.small != null) return checked;+ break;+ };+ for (ladders) |l| if (std.mem.eql(u8, l.provider, provider_id)) return seatChecked(l);return null;}@@ -124,3 +181,47 @@ test "Tier.parse/modelFor: the rung vocabulary #292 pins against (#291 names)" {// A family with no such rung answers null rather than the nearest rung.try std.testing.expect(forProvider("deepseek").?.modelFor(.small) == null);}++test "#471 a rung must be a cheaper SEAT, not merely a terser one" {+ // The bug: `claude-opus-4-8` sat under `claude-opus-5` as anthropic's+ // cheap rung because the bench sheet rates it $2.9/task against opus-5's+ // $12.0 — but both bill the identical $5/$25 per MTok, so descending to it+ // saves nothing whatsoever. It is the same seat, one generation older.+ try std.testing.expect(!cheaperSeat("claude-opus-5", "claude-opus-4-8"));+ // Nor may a "rung" cost MORE than the frontier it hangs under.+ try std.testing.expect(!cheaperSeat("claude-opus-5", "claude-fable-5"));+ // sonnet-5 is the real thing: $2/$10 against $5/$25, cheaper on both halves.+ try std.testing.expect(cheaperSeat("claude-opus-5", "claude-sonnet-5"));+ // Unknown on either side cannot be disproved, and #291's descent has to+ // keep working on providers whose models carry no price row at all+ // (codex's gpt-5.6-sol is the live example).+ try std.testing.expect(cheaperSeat("gpt-5.6-sol", "gpt-5.6-luna"));+ try std.testing.expect(cheaperSeat("claude-opus-5", "no-such-model"));+}++test "#471 a derived ladder offering no real descent yields to the compiled row" {+ const bench = @import("bench_priors.zig");+ const saved = bench.g_ladders;+ defer bench.g_ladders = saved;++ // What the builtin sheet actually derives for anthropic today. Both rungs+ // fail the seat check — fable-5 is pricier than the frontier, opus-4-8 is+ // the same price — so this is not a ladder: it offers no descent at all.+ const derived = [_]TierLadder{+ .{ .provider = "anthropic", .frontier = "claude-opus-5", .mid = "claude-fable-5", .small = "claude-opus-4-8" },+ };+ bench.g_ladders = &derived;+ const l = forProvider("anthropic").?;+ try std.testing.expectEqualStrings("claude-opus-5", l.frontier);+ try std.testing.expect(l.mid == null);+ try std.testing.expectEqualStrings("claude-sonnet-5", l.small.?); // from the compiled row++ // A derived ladder that DOES name a genuinely cheaper seat still wins:+ // measured data outranks the hand-picked default, which is the whole+ // point of #373. Only the empty-after-checking case yields.+ const real = [_]TierLadder{+ .{ .provider = "anthropic", .frontier = "claude-opus-5", .small = "claude-haiku-4-5" },+ };+ bench.g_ladders = ℜ+ try std.testing.expectEqualStrings("claude-haiku-4-5", forProvider("anthropic").?.small.?);+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 788c97af..af1ff289 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -53,6 +53,7 @@ const route_trace = @import("route_trace.zig");// #376 phase-uniform learned routing + the rung-stratified fitness fold.const route_phase = @import("route_phase.zig");const route_check = @import("route_check.zig");+const route_report = @import("route_report.zig"); // #471 credential/tier listing// #380 vision-aware spawn routing + the report-time capability-honesty flag.const vision_ask = @import("vision_ask.zig");const vision_ask_tests = @import("vision_ask_tests.zig");@@ -208,6 +209,7 @@ test {_ = route_trace;_ = route_phase;_ = route_check;+ _ = route_report;_ = vision_ask;_ = vision_ask_tests;_ = pricing_tests;diff --git a/src/title.zig b/src/title.zigindex f2d6d640..6d374012 100644--- a/src/title.zig+++ b/src/title.zig@@ -207,8 +207,8 @@ pub fn cleanTitle(raw: []const u8) ?[]const u8 {test "titleFromPrompt and folderBasename format TUI headers" {try std.testing.expectEqualStrings("Chat", titleFromPrompt(" \n\t "));try std.testing.expectEqualStrings("Refactor the auth middleware", titleFromPrompt(" Refactor the auth middleware\nwith tests"));- try std.testing.expectEqualStrings("codegraff", folderBasename("/Users/rach/src/codegraff"));- try std.testing.expectEqualStrings("codegraff", folderBasename("/Users/rach/src/codegraff/"));+ try std.testing.expectEqualStrings("codegraff", folderBasename("/Users/example/src/codegraff"));+ try std.testing.expectEqualStrings("codegraff", folderBasename("/Users/example/src/codegraff/"));}test "reasoningDelta extracts thinking/reasoning per provider wire format (#75)" {diff --git a/src/vision_ask.zig b/src/vision_ask.zigindex 2a16ca39..81c849aa 100644--- a/src/vision_ask.zig+++ b/src/vision_ask.zig@@ -254,7 +254,7 @@ pub fn visionSeat(base: Provider) ?Provider {if (best) |b| return b;}const local = visionModelFor(base.id) orelse return null;- if (!subagent_pin.rungAffordable(base.model, local)) return null;+ if (!subagent_pin.rungAffordableOn(base, local)) return null;return base.withModel(local);}@@ -264,7 +264,7 @@ pub fn visionSeat(base: Provider) ?Provider {/// can authorize it by name — so the refusal has to say which model that is.pub fn blockedByCost(base: Provider) []const u8 {const name = visionModelFor(base.id) orelse return "";- return if (subagent_pin.rungAffordable(base.model, name)) "" else name;+ return if (subagent_pin.rungAffordableOn(base, name)) "" else name;}/// The whole spawn-time decision: run the #292/#372 chain unchanged, then askdiff --git a/src/vision_ask_tests.zig b/src/vision_ask_tests.zigindex 6f919d85..e01c646d 100644--- a/src/vision_ask_tests.zig+++ b/src/vision_ask_tests.zig@@ -185,13 +185,17 @@ test "#380 fast fail: no vision-capable model anywhere refuses the spawn, action// Saying "none is reachable" there would be a lie, so it is a distinct// message that names the model and how to authorize it.withKeys(&keys, &.{"anthropic"});- const cheap: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-haiku-4-5", .context = 200_000 };- try std.testing.expectEqualStrings("", va.blockedByCost(cheap)); // haiku IS the cheap vision rung — affordable, so not this case+ // #471 moved anthropic's cheap rung from haiku-4-5 to sonnet-5, so the+ // vision seat is sonnet-5 ($2/$10) rather than haiku ($1/$5): still 2.5x+ // under opus, and now a genuinely cheaper SEAT than the frontier instead+ // of an equally-priced older opus.+ const cheap: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-sonnet-5", .context = 200_000 };+ try std.testing.expectEqualStrings("", va.blockedByCost(cheap)); // sonnet-5 IS the cheap vision rung — affordable, so not this caseconst priced_out: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "deepseek-v4-flash", .context = 200_000 };- try std.testing.expectEqualStrings("claude-haiku-4-5", va.blockedByCost(priced_out));- const cost_msg = try va.blockMessage(std.testing.allocator, .{ .path = "a.png", .blocked = true, .pricier = "claude-haiku-4-5" });+ try std.testing.expectEqualStrings("claude-sonnet-5", va.blockedByCost(priced_out));+ const cost_msg = try va.blockMessage(std.testing.allocator, .{ .path = "a.png", .blocked = true, .pricier = "claude-sonnet-5" });defer std.testing.allocator.free(cost_msg);- try std.testing.expect(std.mem.indexOf(u8, cost_msg, "model:\"claude-haiku-4-5\"") != null); // how to authorize it+ try std.testing.expect(std.mem.indexOf(u8, cost_msg, "model:\"claude-sonnet-5\"") != null); // how to authorize ittry std.testing.expect(std.mem.indexOf(u8, cost_msg, "escalate") != null); // and why it was not takentry std.testing.expect(!std.mem.eql(u8, cost_msg, msg));}@@ -200,7 +204,7 @@ test "#380 candidate search: sub-first, then provider-local under the cost ceili// Ladder rungs bottom-up, so a re-route descends price rather than seizing// the frontier model.try std.testing.expectEqualStrings("gpt-5.6-luna", va.visionModelFor("codex").?);- try std.testing.expectEqualStrings("claude-haiku-4-5", va.visionModelFor("anthropic").?);+ try std.testing.expectEqualStrings("claude-sonnet-5", va.visionModelFor("anthropic").?);try std.testing.expect(va.visionModelFor("deepseek") == null); // no vision model at any rungconst saved = bench.g_keys;@@ -219,12 +223,12 @@ test "#380 candidate search: sub-first, then provider-local under the cost ceilitry std.testing.expectEqualStrings("gpt-5.6-luna", seat.model);// An anthropic base with no sub logged in resolves provider-locally, and- // only because haiku is CHEAPER than the opus it replaces.+ // only because sonnet-5 is CHEAPER than the opus it replaces.withKeys(&keys, &.{"anthropic"});- const opus_root: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-opus-4-8", .context = 200_000 };+ const opus_root: Provider = .{ .id = "anthropic", .kind = .anthropic, .auth = .x_api_key, .url = "", .api_key = "k", .model = "claude-opus-5", .context = 1_000_000 };const local = va.visionSeat(opus_root).?;try std.testing.expectEqualStrings("anthropic", local.id);- try std.testing.expectEqualStrings("claude-haiku-4-5", local.model);+ try std.testing.expectEqualStrings("claude-sonnet-5", local.model);}test "#380 honesty flag: each disclaimer spelling is caught, ordinary reports are not" {