Skip to content

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

Python

agent: add /goal and /loop commands, codedb-pro licensed note, refresh model catalog

Rach Pradhanece13ca86e9c
diff --git a/gui/src-tauri/src/runtime/simple.rs b/gui/src-tauri/src/runtime/simple.rs
index 3ab58c6e..fd09b6ae 100644
--- a/gui/src-tauri/src/runtime/simple.rs
+++ b/gui/src-tauri/src/runtime/simple.rs
@@ -27,6 +27,7 @@ struct ConversationState {
active_request_ids: Vec<String>,
active_agent_id: Option<String>,
plan_mode: bool,
+ goal: Option<String>,
updated_at: i64,
}
@@ -45,7 +46,9 @@ struct RuntimeState {
/// forwarded live to running sessions. None effort = the binary default.
selected_effort: Option<String>,
fast_enabled: bool,
- /// Cached `graff --schema` model list (populated lazily).
+ /// Last successful `graff --schema` model list. Refreshed when the prompt
+ /// settings endpoint is read so the GUI picks up newly shipped models
+ /// without an app restart.
model_catalog: Option<Vec<ModelOption>>,
/// Live `ask_user` prompts awaiting a GUI answer, keyed by conversation.
/// Surfaced as the conversation's `followup` so the FollowupComposer renders.
@@ -56,8 +59,10 @@ struct RuntimeState {
#[derive(Clone)]
struct ModelOption {
provider: String,
+ provider_name: Option<String>,
name: String,
context: Option<u64>,
+ is_default: bool,
}
/// A persistent `graff --json` child bound to one conversation. Keeping the
@@ -143,7 +148,7 @@ impl RuntimeManager {
/// Returns the model picker, populated from `graff --schema`.
pub async fn get_prompt_settings(&self, _: Option<String>) -> Result<PromptSettingsDto> {
- let catalog = self.ensure_model_catalog().await;
+ let catalog = self.refresh_model_catalog().await;
let configured_provider_ids = configured_provider_ids().await;
let (selected_provider, selected_model, selected_effort, fast_enabled) = {
let state = self.state.lock().await;
@@ -245,7 +250,7 @@ impl RuntimeManager {
&self,
input: UpdatePromptSettingsInput,
) -> Result<PromptSettingsDto> {
- let catalog = self.ensure_model_catalog().await;
+ let catalog = self.refresh_model_catalog().await;
let configured_provider_ids = configured_provider_ids().await;
let available_catalog = filtered_catalog_models(&catalog, &configured_provider_ids);
let selected_model = available_catalog
@@ -298,8 +303,18 @@ impl RuntimeManager {
return catalog.clone();
}
}
+ self.refresh_model_catalog().await
+ }
+
+ /// Re-reads `graff --schema` so prompt-settings reflects the current binary's
+ /// provider/model list. If the schema read fails after a successful earlier
+ /// read, keep showing the last known catalog rather than blanking the picker.
+ async fn refresh_model_catalog(&self) -> Vec<ModelOption> {
let catalog = codegraff_schema_models().await;
let mut state = self.state.lock().await;
+ if catalog.is_empty() {
+ return state.model_catalog.clone().unwrap_or_default();
+ }
state.model_catalog = Some(catalog.clone());
catalog
}
@@ -403,6 +418,8 @@ impl RuntimeManager {
Ok(vec![
command("help", "Show available commands.", false),
command("agent", "Show active agent.", false),
+ command("goal", "Set/show the current objective.", true),
+ command("loop", "Run an autonomous plan→act→verify pass.", true),
command("compact", "Compact current conversation.", true),
command("workspace-status", "Show git status.", true),
])
@@ -418,8 +435,10 @@ impl RuntimeManager {
.unwrap_or_else(|| format!("chat-{}", Uuid::new_v4().simple()));
let request_id = format!("request-{}", Uuid::new_v4().simple());
let plan_mode = input.agent_id.as_deref() == Some("muse");
+ let loop_mode = input.agent_id.as_deref() == Some("loop");
let title_model_arg = self.selected_model_name().await;
let is_first_turn;
+ let engine_prompt;
{
let mut state = self.state.lock().await;
set_active_workspace(&mut state, &input.workspace_path);
@@ -439,10 +458,23 @@ impl RuntimeManager {
active_request_ids: vec![],
active_agent_id,
plan_mode,
+ goal: None,
updated_at: now_millis(),
});
conversation.plan_mode = plan_mode;
conversation.updated_at = now_millis();
+ let goal_prompt = conversation
+ .goal
+ .as_ref()
+ .map(|goal| format!("{}\n\n[harness goal: {}]", input.prompt, goal))
+ .unwrap_or_else(|| input.prompt.clone());
+ engine_prompt = if loop_mode {
+ format!(
+ "{goal_prompt}\n\n[harness note: /loop was used. Work autonomously until the prompt is satisfied: make a brief plan, execute it with tools, verify the result, and only stop when you can report completion or you need a required human decision. Keep iterations tight and avoid asking for confirmation between routine steps.]"
+ )
+ } else {
+ goal_prompt
+ };
is_first_turn = conversation.messages.is_empty();
if is_first_turn && is_placeholder_title(&conversation.title) {
conversation.title = title_from_prompt(&input.prompt);
@@ -501,7 +533,7 @@ impl RuntimeManager {
&conversation_id,
&request_id,
&input.workspace_path,
- &input.prompt,
+ &engine_prompt,
)
.await
{
@@ -909,6 +941,7 @@ impl RuntimeManager {
messages: conversation.messages.clone(),
active_agent_id: conversation.active_agent_id.clone(),
plan_mode: conversation.plan_mode,
+ goal: conversation.goal.clone(),
updated_at: conversation.updated_at,
})
.collect()
@@ -1053,6 +1086,83 @@ impl RuntimeManager {
result_kind: CommandResultKindDto::Agents,
payload: Some(CommandPayloadDto::Agents(self.agents_payload().await)),
}),
+ "goal" => {
+ let _workspace = workspace_path.context("Missing workspace")?;
+ let conversation_id = conversation_id.context("Missing conversation")?;
+ let text = args.join(" ").trim().to_string();
+ let body = if text.is_empty() {
+ let current = {
+ let state = self.state.lock().await;
+ state
+ .conversations
+ .get(&conversation_id)
+ .and_then(|conversation| conversation.goal.clone())
+ };
+ current
+ .map(|goal| format!("Current goal: {goal}\n\nClear it with /goal clear."))
+ .unwrap_or_else(|| "No active goal. Set one with /goal <objective>.".into())
+ } else if text.eq_ignore_ascii_case("clear") || text.eq_ignore_ascii_case("off") {
+ self.mutate_conversation(&conversation_id, |conversation| {
+ conversation.goal = None;
+ })
+ .await;
+ self.persist_conversations().await;
+ "Goal cleared. Future turns will not get goal steering.".into()
+ } else {
+ let goal = text.clone();
+ self.mutate_conversation(&conversation_id, move |conversation| {
+ conversation.goal = Some(goal);
+ })
+ .await;
+ self.persist_conversations().await;
+ format!(
+ "Goal set: {text}\n\nFuture turns in this chat will include this objective as steering."
+ )
+ };
+ let snapshot = self.snapshot().await?;
+ let _ = self.emitter.emit_session_updated(snapshot.clone());
+ Ok(CommandRunResultDto {
+ title: "/goal".into(),
+ body: Some(body),
+ snapshot: Some(snapshot),
+ saved_path: None,
+ result_kind: CommandResultKindDto::Text,
+ payload: None,
+ })
+ }
+ "loop" => {
+ let prompt = args.join(" ").trim().to_string();
+ if prompt.is_empty() {
+ return Ok(CommandRunResultDto {
+ title: "/loop".into(),
+ body: Some(
+ "Usage: /loop <prompt> — run an autonomous plan→act→verify pass."
+ .into(),
+ ),
+ snapshot: None,
+ saved_path: None,
+ result_kind: CommandResultKindDto::Text,
+ payload: None,
+ });
+ }
+ let workspace = workspace_path.context("Missing workspace")?;
+ let snapshot = self
+ .send_prompt(SendPromptInput {
+ workspace_path: workspace,
+ conversation_id,
+ prompt,
+ agent_id: Some("loop".into()),
+ })
+ .await?;
+ Ok(CommandRunResultDto {
+ title: "/loop".into(),
+ body: None,
+ snapshot: Some(snapshot),
+ saved_path: None,
+ result_kind: CommandResultKindDto::Snapshot,
+ payload: None,
+ })
+ }
"compact" => Ok(CommandRunResultDto {
title: "/compact".into(),
body: None,
@@ -1086,7 +1196,7 @@ impl RuntimeManager {
_ => Ok(CommandRunResultDto {
title: format!("/{name}"),
body: Some(format!(
- "Available MVP commands: /help, /agent, /compact, /workspace-status. Args: {}",
+ "Available MVP commands: /help, /agent, /goal, /loop, /compact, /workspace-status. Args: {}",
args.join(" ")
)),
snapshot: None,
@@ -1425,6 +1535,7 @@ impl RuntimeManager {
active_request_ids: vec![],
active_agent_id: None,
plan_mode: false,
+ goal: None,
updated_at: now_millis(),
},
);
@@ -1970,6 +2081,8 @@ struct PersistedConversation {
#[serde(default)]
plan_mode: bool,
#[serde(default)]
+ goal: Option<String>,
+ #[serde(default)]
updated_at: i64,
}
@@ -2053,6 +2166,7 @@ fn load_persisted_conversations() -> HashMap<String, ConversationState> {
active_request_ids: vec![],
active_agent_id: conversation.active_agent_id,
plan_mode: conversation.plan_mode,
+ goal: conversation.goal,
updated_at: conversation.updated_at,
},
)
@@ -2166,7 +2280,7 @@ fn command(name: &str, usage: &str, requires_workspace: bool) -> CommandDescript
is_agent_switch: false,
execution_kind: CommandExecutionKindDto::Runnable,
requires_workspace,
- requires_conversation: name == "compact",
+ requires_conversation: matches!(name, "compact" | "goal" | "loop"),
argument_hint: None,
result_kind: CommandResultKindDto::Text,
}
@@ -2221,6 +2335,41 @@ async fn codegraff_schema_models() -> Vec<ModelOption> {
Ok(schema) => schema,
Err(_) => return vec![],
};
+ let provider_names: HashMap<String, String> = schema
+ .get("providers")
+ .and_then(serde_json::Value::as_array)
+ .map(|providers| {
+ providers
+ .iter()
+ .filter_map(|provider| {
+ Some((
+ provider.get("id")?.as_str()?.to_string(),
+ provider
+ .get("name")
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or(provider.get("id")?.as_str()?)
+ .to_string(),
+ ))
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ let provider_defaults: HashMap<String, String> = schema
+ .get("providers")
+ .and_then(serde_json::Value::as_array)
+ .map(|providers| {
+ providers
+ .iter()
+ .filter_map(|provider| {
+ Some((
+ provider.get("id")?.as_str()?.to_string(),
+ provider.get("default_model")?.as_str()?.to_string(),
+ ))
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
schema
.get("models")
.and_then(serde_json::Value::as_array)
@@ -2228,9 +2377,15 @@ async fn codegraff_schema_models() -> Vec<ModelOption> {
models
.iter()
.filter_map(|model| {
+ let provider = model.get("provider")?.as_str()?.to_string();
+ let name = model.get("name")?.as_str()?.to_string();
Some(ModelOption {
- provider: model.get("provider")?.as_str()?.to_string(),
- name: model.get("name")?.as_str()?.to_string(),
+ provider_name: provider_names.get(&provider).cloned(),
+ is_default: provider_defaults
+ .get(&provider)
+ .is_some_and(|default_model| default_model == &name),
+ provider,
+ name,
context: model.get("context").and_then(serde_json::Value::as_u64),
})
})
@@ -2348,7 +2503,10 @@ fn prompt_model_option(model: &ModelOption) -> PromptModelOptionDto {
PromptModelOptionDto {
provider_id: model.provider.clone(),
- provider_name: provider_display_name(&model.provider),
+ provider_name: model
+ .provider_name
+ .clone()
+ .unwrap_or_else(|| provider_display_name(&model.provider)),
model_id: model.name.clone(),
model_name: Some(model.name.clone()),
context_length: model.context,
@@ -2367,8 +2525,14 @@ fn selected_prompt_model_pair(
let default_model = available_catalog
.iter()
- .find(|model| model.name == "deepseek-v4-pro")
+ .find(|model| model.provider == "codegraff" && model.is_default)
.copied()
+ .or_else(|| {
+ available_catalog
+ .iter()
+ .find(|model| model.is_default)
+ .copied()
+ })
.or_else(|| available_catalog.first().copied());
selected_provider
@@ -2674,7 +2838,11 @@ fn codegraff_binary() -> String {
}
}
}
- for abs in ["/opt/homebrew/bin/graff", "/usr/local/bin/graff", "/usr/bin/graff"] {
+ for abs in [
+ "/opt/homebrew/bin/graff",
+ "/usr/local/bin/graff",
+ "/usr/bin/graff",
+ ] {
if Path::new(abs).is_file() {
return abs.to_string();
}
@@ -3370,6 +3538,7 @@ mod tests {
active_request_ids: vec![],
active_agent_id: None,
plan_mode: false,
+ goal: None,
updated_at: 10,
},
);
@@ -3498,8 +3667,10 @@ mod tests {
fn model(provider: &str, name: &str) -> ModelOption {
ModelOption {
provider: provider.into(),
+ provider_name: None,
name: name.into(),
context: None,
+ is_default: provider == "codegraff" && name == "deepseek-v4-pro",
}
}
@@ -3625,6 +3796,7 @@ mod tests {
active_request_ids: vec![],
active_agent_id: None,
plan_mode: false,
+ goal: None,
updated_at: 10,
},
);
@@ -3638,6 +3810,7 @@ mod tests {
active_request_ids: vec![],
active_agent_id: None,
plan_mode: false,
+ goal: None,
updated_at: 20,
},
);
diff --git a/gui/src/hooks/useCommandRouter.ts b/gui/src/hooks/useCommandRouter.ts
index 5334b598..002d8178 100644
--- a/gui/src/hooks/useCommandRouter.ts
+++ b/gui/src/hooks/useCommandRouter.ts
@@ -18,6 +18,8 @@ const ARG_COMMANDS = new Set([
"workspace-query",
"workspace-search",
"workflow",
+ "goal",
+ "loop",
"reasoning-effort",
]);
diff --git a/gui/src/services/desktop/client.ts b/gui/src/services/desktop/client.ts
index d2850dc7..938c96da 100644
--- a/gui/src/services/desktop/client.ts
+++ b/gui/src/services/desktop/client.ts
@@ -72,6 +72,8 @@ const qaCommandRows: Array<[
["agent", "Show active agent and available agents.", null, "agents"],
["sage", "Switch to Sage.", null, "agents"],
["reasoning-effort", "Update reasoning effort.", "<low|medium|high>", "text"],
+ ["goal", "Set/show the current objective.", "<objective|clear>", "text"],
+ ["loop", "Run an autonomous plan→act→verify pass.", "<prompt>", "snapshot"],
["workspace-info", "Show indexed workspace metadata.", null, "workspaceInfo"],
["workspace-status", "Show workspace file status.", null, "workspaceStatus"],
["workspace-query", "Search the workspace semantically.", "<query>", "workspaceSearch"],
@@ -236,6 +238,10 @@ function qaCommandResult(input: {
case "reasoning-effort":
qaReasoningEffort = input.args[0] ?? qaReasoningEffort;
return { body: `Reasoning effort is now **${qaReasoningEffort ?? "default"}**.`, payload: null, resultKind: "text", savedPath: null, snapshot: null, title };
+ case "goal":
+ return { body: input.args.length > 0 ? `Goal set: **${input.args.join(" ")}**.` : "No active goal. Set one with `/goal <objective>`.", payload: null, resultKind: "text", savedPath: null, snapshot: null, title };
+ case "loop":
+ return { body: "Started an autonomous plan→act→verify pass.", payload: null, resultKind: "snapshot", savedPath: null, snapshot: createQaSnapshot(input.conversationId ?? QA_CONVERSATION_ID, [{ id: "qa-loop-user", kind: "user", requestId: "qa-loop-request", text: `/loop ${input.args.join(" ")}` }, { id: "qa-loop-assistant", kind: "assistant", requestId: "qa-loop-request", text: "Loop pass complete: planned, acted, and verified the requested change." }]), title };
case "workspace-info":
return { body: "| Field | Value |\n|---|---|\n| Workspace | Codegraff GUI |\n| Branch | qa/mock-browser |\n| Indexed nodes | 1,284 |", payload: { createdAt: "2026-06-03T00:00:00Z", kind: "workspaceInfo", lastUpdated: "2026-06-03T12:00:00Z", nodeCount: 1284n, relationCount: 642n, workingDir: QA_WORKSPACE_PATH, workspaceId: "qa-codegraff-gui", workspacePath: QA_WORKSPACE_PATH }, resultKind: "workspaceInfo", savedPath: null, snapshot: null, title };
case "workspace-status":
diff --git a/src/main.zig b/src/main.zig
index 73578f9f..4f42f67b 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -2190,6 +2190,13 @@ const skills_registry = [_]SkillDef{
/// model knows when to reach for its tools. The native tools stay registered
/// regardless — they are the fallback whenever an MCP call fails, is denied,
/// or the server is disconnected/skipped.
+/// Licensed-aware variant of the codedbpro note. When `codedb-pro probe`
+/// succeeds (paid + usable) we inject THIS instead of the conservative
+/// "prefer free codedb" note below — leaning into the tools the user pays for.
+/// Edits still stay native: edit_file/write_file are /rewind-snapshotted and
+/// already splice via zigpatch, whereas codedb-pro edit/patch/replace bypass /rewind.
+const codedbpro_note_licensed = "The codedb-pro MCP server is connected and LICENSED (mcp__codedbpro__* tools) — prefer it, you are paying for it. Use mcp__codedbpro__read (mode=outline first, then symbol/lines) instead of read_file for navigating code, mcp__codedbpro__faster_search / meta_search for content and fuzzy search (the native codedb tool stays a fine fast path for indexed symbol/outline/callers/find lookups), and mcp__codedbpro__batch to run several independent reads/searches in one round-trip. KEEP EDITS on the native edit_file/write_file tools — they are snapshot-tracked for /rewind and already splice via zigpatch; codedb-pro edit/patch/replace bypass /rewind, so do not route edits through it. Whenever an mcp__codedbpro__ call fails, fall back to read_file/codedb/bash.";
+
const McpNote = struct { server: []const u8, note: []const u8 };
const mcp_notes = [_]McpNote{
.{
@@ -2293,6 +2300,12 @@ fn skillInstalled(io: Io, sk: SkillDef) bool {
/// webfetch never shells out to it — even when its binaries are on PATH.
var g_skill_disabled = [_]bool{false} ** skills_registry.len;
+/// Same opt-out, for the metered companion MCP servers (codedb-pro). They live
+/// in companion_servers, NOT skills_registry, so they need their own flags —
+/// this is the bug fix: {"skills": {"codedbpro": false}} now actually disables
+/// the auto-connect (skillDisabled() never matched a companion server name).
+var g_companion_disabled = [_]bool{false} ** companion_servers.len;
+
fn skillIndex(name: []const u8) ?usize {
for (skills_registry, 0..) |sk, i| if (std.mem.eql(u8, sk.name, name)) return i;
return null;
@@ -2303,24 +2316,68 @@ fn skillDisabled(name: []const u8) bool {
return g_skill_disabled[i];
}
+/// Companion-server opt-out (e.g. codedb-pro): {"skills": {"codedbpro": false}}.
+/// Server names aren't in skills_registry, so skillDisabled() can't see them —
+/// the companion auto-connect gate uses this instead.
+fn companionDisabled(server: []const u8) bool {
+ for (companion_servers, 0..) |c, i| if (std.mem.eql(u8, c.server, server)) return g_companion_disabled[i];
+ return false;
+}
+
+/// True when `codedb-pro probe` exits 0 (paid + usable). Set once at startup
+/// after the companion connects; selects the licensed vs conservative note.
+var g_codedbpro_licensed: bool = false;
+
+/// Run the companion's `probe` — its own harness-gating capability check, the
+/// same gate the codedb-pro CLI hooks use. Exit 0 == licensed and usable.
+fn probeCodedbproLicensed(gpa: Allocator, io: Io) bool {
+ const run = runCapped(gpa, io, &.{ "codedb-pro", "probe" }, 256, 256) catch return false;
+ defer {
+ gpa.free(run.stdout);
+ gpa.free(run.stderr);
+ }
+ return switch (run.term) {
+ .exited => |code| code == 0,
+ else => false,
+ };
+}
+
+/// Pick the codedbpro system-prompt note: the lean-in note when licensed, else
+/// the conservative free-codedb fallback (`conservative`, from mcp_notes).
+fn codedbproNote(server: []const u8, licensed: bool, conservative: []const u8) []const u8 {
+ if (licensed and std.mem.eql(u8, server, "codedbpro")) return codedbpro_note_licensed;
+ return conservative;
+}
+
/// Installed AND not user-disabled — the only check callers should use.
fn skillActive(io: Io, sk: SkillDef) bool {
return !skillDisabled(sk.name) and skillInstalled(io, sk);
}
-/// Parse the "skills" section of .harness/settings.json into
-/// g_skill_disabled (call once at startup): {"skills": {"<name>": false}}
-/// disables; anything else leaves the skill enabled.
+/// Parse the "skills" section of .harness/settings.json into the disabled
+/// flags (call once at startup): {"skills": {"<name>": false}} disables;
+/// anything else leaves it enabled. Covers skills_registry AND companion
+/// servers (codedb-pro).
fn loadSkillSettings(io: Io, arena: Allocator) void {
const data = Io.Dir.cwd().readFileAlloc(io, Approvals.settings_path, arena, .limited(1 << 20)) catch return;
const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return;
if (v != .object) return;
const skills = v.object.get("skills") orelse return;
+ applySkillSettings(skills);
+}
+
+/// Pure half of loadSkillSettings (no disk I/O), so the opt-out wiring is
+/// unit-testable: maps {"skills": {"<name>": false}} onto the disabled flags.
+fn applySkillSettings(skills: Value) void {
if (skills != .object) return;
for (skills_registry, 0..) |sk, i| {
const entry = skills.object.get(sk.name) orelse continue;
if (entry == .bool and !entry.bool) g_skill_disabled[i] = true;
}
+ for (companion_servers, 0..) |c, i| {
+ const entry = skills.object.get(c.server) orelse continue;
+ if (entry == .bool and !entry.bool) g_companion_disabled[i] = true;
+ }
}
// ── thinking animations ──────────────────────────────────────────────────
@@ -4127,7 +4184,7 @@ pub fn main(init: std.process.Init) !void {
connect: {
for (companion_servers) |c| if (mcpServerConnected(registry_storage.tools, c.server)) break :connect;
for (companion_servers) |c| {
- if (skillDisabled(c.server) or !binOnPath(io, c.bin)) continue;
+ if (companionDisabled(c.server) or !binOnPath(io, c.bin)) continue;
if (registry_storage.addServer(c.server, c.bin, &.{"--mcp"})) |_| {
break;
} else |err| {
@@ -4139,6 +4196,9 @@ pub fn main(init: std.process.Init) !void {
}
}
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 the paid tools (vs the conservative free-codedb note).
+ if (mcpServerConnected(mcp_tools, "codedbpro")) g_codedbpro_licensed = probeCodedbproLicensed(gpa, io);
var approvals: Approvals = .{ .yolo = yolo_flag };
defer {
@@ -4193,7 +4253,8 @@ pub fn main(init: std.process.Init) !void {
// succeeded). Native tools remain the fallback either way.
for (mcp_notes) |mn| {
if (!mcpServerConnected(mcp_tools, mn.server)) continue;
- sys_normal = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ sys_normal, mn.note });
+ const note = codedbproNote(mn.server, g_codedbpro_licensed, mn.note);
+ sys_normal = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ sys_normal, note });
}
const sys_strict: []const u8 = try std.fmt.allocPrint(arena, "{s}{s}", .{ sys_normal, strict_note });
@@ -12032,6 +12093,39 @@ test "skillDisabled: registry lookup and toggle" {
try std.testing.expect(!skillDisabled("not-a-skill"));
}
+test "companion opt-out: {\"skills\":{\"codedbpro\":false}} disables auto-connect" {
+ // applySkillSettings is the pure half of loadSkillSettings; prove the
+ // settings key flips companionDisabled(), the flag the auto-connect reads.
+ const saved_companion = g_companion_disabled;
+ const ki = skillIndex("kuri").?;
+ const saved_kuri = g_skill_disabled[ki];
+ defer {
+ g_companion_disabled = saved_companion;
+ g_skill_disabled[ki] = saved_kuri;
+ }
+ g_companion_disabled = [_]bool{false} ** companion_servers.len;
+ g_skill_disabled[ki] = false;
+
+ var arena_inst = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_inst.deinit();
+ const json = "{\"skills\":{\"codedbpro\":false,\"kuri\":false}}";
+ const v = try std.json.parseFromSliceLeaky(Value, arena_inst.allocator(), json, .{ .allocate = .alloc_always });
+ applySkillSettings(v.object.get("skills").?);
+
+ try std.testing.expect(companionDisabled("codedbpro")); // the fix: was always false before
+ try std.testing.expect(skillDisabled("kuri")); // existing registry path still works
+ try std.testing.expect(!companionDisabled("not-a-server"));
+}
+
+test "codedbproNote: licensed flips codedbpro to the lean-in note" {
+ const cons = "CONSERVATIVE-NOTE";
+ try std.testing.expectEqualStrings(cons, codedbproNote("codedbpro", false, cons)); // unlicensed -> conservative
+ try std.testing.expectEqualStrings(cons, codedbproNote("muonry", true, cons)); // other servers untouched
+ try std.testing.expectEqualStrings(codedbpro_note_licensed, codedbproNote("codedbpro", true, cons)); // licensed -> lean-in
+ try std.testing.expect(std.mem.indexOf(u8, codedbpro_note_licensed, "mcp__codedbpro__read") != null);
+ try std.testing.expect(std.mem.indexOf(u8, codedbpro_note_licensed, "/rewind") != null);
+}
+
test "parseAnswerRequest: preserves multiline text and optional call id" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();