fix(ci): satisfy Rust 1.88 clippy gate

This commit is contained in:
Hunter Bown
2026-05-24 01:20:19 -05:00
parent 93c525a200
commit 2947eff9d1
47 changed files with 101 additions and 159 deletions
+1 -2
View File
@@ -1284,8 +1284,7 @@ fn load_mcp_server_definitions(store: &ConfigStore) -> Vec<McpServerDefinition>
Ok(definitions) => definitions,
Err(err) => {
eprintln!(
"warning: failed to parse persisted MCP server definitions ({}): {}",
MCP_SERVER_DEFINITIONS_KEY, err
"warning: failed to parse persisted MCP server definitions ({MCP_SERVER_DEFINITIONS_KEY}): {err}"
);
Vec::new()
}
+4 -4
View File
@@ -77,7 +77,7 @@ fn parse_duration_secs(s: &str) -> Result<i64> {
'd' | 'h' | 'm' | 's' => {
let n: i64 = num_buf
.parse()
.map_err(|_| anyhow::anyhow!("invalid duration component: {:?}", num_buf))?;
.map_err(|_| anyhow::anyhow!("invalid duration component: {num_buf:?}"))?;
num_buf.clear();
let factor = match ch {
'd' => 86_400,
@@ -88,7 +88,7 @@ fn parse_duration_secs(s: &str) -> Result<i64> {
};
total += n * factor;
}
_ => anyhow::bail!("unrecognised character {:?} in duration {:?}", ch, s),
_ => anyhow::bail!("unrecognised character {ch:?} in duration {s:?}"),
}
}
@@ -99,7 +99,7 @@ fn parse_duration_secs(s: &str) -> Result<i64> {
}
if total == 0 {
anyhow::bail!("duration {:?} resolved to zero seconds", s);
anyhow::bail!("duration {s:?} resolved to zero seconds");
}
Ok(total)
@@ -796,7 +796,7 @@ fn print_human(rollup: &Rollup) {
let mut cats: Vec<(&String, &u64)> = rollup.capacity.by_category.iter().collect();
cats.sort_by(|a, b| b.1.cmp(a.1));
cats.iter()
.map(|(k, v)| format!("{} {}", v, k))
.map(|(k, v)| format!("{v} {k}"))
.collect::<Vec<_>>()
.join(", ")
};
+4 -8
View File
@@ -337,8 +337,7 @@ fn validate_base_url_security(base_url: &str) -> Result<()> {
.is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
{
logging::warn(format!(
"Using insecure HTTP base URL because {} is set",
ALLOW_INSECURE_HTTP_ENV
"Using insecure HTTP base URL because {ALLOW_INSECURE_HTTP_ENV} is set"
));
return Ok(());
}
@@ -349,17 +348,14 @@ fn validate_base_url_security(base_url: &str) -> Result<()> {
\n\
Loopback hosts (localhost, 127.0.0.1, [::1]) are auto-allowed.\n\
For other trusted local hosts (LAN, llama.cpp on a private IP, etc.)\n\
set the env var `{env}=1` in the shell that runs deepseek and re-run.\n\
set the env var `{ALLOW_INSECURE_HTTP_ENV}=1` in the shell that runs deepseek and re-run.\n\
\n\
Example: `{env}=1 deepseek` (note the underscores).",
base_url = base_url,
env = ALLOW_INSECURE_HTTP_ENV,
Example: `{ALLOW_INSECURE_HTTP_ENV}=1 deepseek` (note the underscores).",
);
}
anyhow::bail!(
"Refusing base URL '{}': only HTTPS (or explicitly allowed HTTP) URLs are supported.",
base_url,
"Refusing base URL '{base_url}': only HTTPS (or explicitly allowed HTTP) URLs are supported.",
)
}
+1 -2
View File
@@ -1604,8 +1604,7 @@ fn log_thinking_mode_violations(body: &Value) {
let has_tc = msg.get("tool_calls").is_some();
if reasoning.trim().is_empty() {
violations.push(format!(
"assistant[{idx}] (reasoning_content missing, tool_calls={})",
has_tc
"assistant[{idx}] (reasoning_content missing, tool_calls={has_tc})"
));
}
}
+1 -1
View File
@@ -97,7 +97,7 @@ fn add_anchor(app: &mut App, text: &str) -> CommandResult {
};
// Write separator and anchor content.
if let Err(e) = writeln!(file, "\n---\n{}", text) {
if let Err(e) = writeln!(file, "\n---\n{text}") {
return CommandResult::error(format!("Failed to write anchor: {e}"));
}
+1 -2
View File
@@ -23,8 +23,7 @@ pub fn goal(app: &mut App, arg: Option<&str>) -> CommandResult {
.map(|b| format!(" (budget: {b} tokens)"))
.unwrap_or_default();
CommandResult::message(format!(
"Goal set: \"{}\"{} — tracking progress.",
objective, budget_str
"Goal set: \"{objective}\"{budget_str} — tracking progress."
))
}
_ => {
+3 -5
View File
@@ -736,7 +736,7 @@ pub fn rlm(app: &mut App, arg: Option<&str>) -> CommandResult {
let source_arg = if resolves_to_existing_file(app, &target) {
format!(r#"file_path: "{target}""#)
} else {
format!("content: {:?}", target)
format!("content: {target:?}")
};
let message = format!(
"Open and use a persistent RLM session for this request. Call `rlm_open` with name `slash_rlm` and {source_arg}. Then call `rlm_configure` with `sub_rlm_max_depth: {max_depth}`. Use `rlm_eval` to inspect the context through `peek`, `search`, and `chunk`, and call `finalize(...)` from the REPL when ready. If a `var_handle` is returned, use `handle_read` for bounded slices or projections before answering."
@@ -764,8 +764,7 @@ pub fn agent(_app: &mut App, arg: Option<&str>) -> CommandResult {
}
};
let message = format!(
"Open a persistent sub-agent session for this task. Call `agent_open` with name `slash_agent`, `prompt: {:?}`, and `max_depth: {max_depth}`. Use `agent_eval` to wait for the next terminal/current projection and `handle_read` on the returned transcript_handle if you need more detail. Verify any claimed side effects before reporting success.",
task
"Open a persistent sub-agent session for this task. Call `agent_open` with name `slash_agent`, `prompt: {task:?}`, and `max_depth: {max_depth}`. Use `agent_eval` to wait for the next terminal/current projection and `handle_read` on the returned transcript_handle if you need more detail. Verify any claimed side effects before reporting success."
);
CommandResult::with_message_and_action(
format!("Opening persistent sub-agent at depth {max_depth}..."),
@@ -1227,8 +1226,7 @@ mod tests {
for alias in command.aliases {
assert!(
!names.contains(alias),
"alias /{} collides with a command name",
alias
"alias /{alias} collides with a command name"
);
assert!(aliases.insert(*alias), "duplicate command alias /{alias}");
}
+1 -1
View File
@@ -164,7 +164,7 @@ fn append_note(notes_path: &Path, note_content: &str) -> Result<(), String> {
};
// Write separator and note content
if let Err(e) = writeln!(file, "\n---\n{}", note_content) {
if let Err(e) = writeln!(file, "\n---\n{note_content}") {
return Err(format!("Failed to write note: {e}"));
}
+1 -1
View File
@@ -141,7 +141,7 @@ pub fn user_commands_matching(prefix: &str, workspace: Option<&Path>) -> Vec<Str
load_user_commands(workspace)
.into_iter()
.filter(|(name, _)| name.starts_with(&prefix))
.map(|(name, _)| format!("/{}", name))
.map(|(name, _)| format!("/{name}"))
.collect()
}
+4 -4
View File
@@ -1373,7 +1373,7 @@ fn build_formatted_summary_request(
}
ContentBlock::ToolResult { content, .. } => {
let snippet = truncate_chars(content, limits.tool_result_snippet_chars);
let _ = write!(conversation_text, "Tool result: {}\n\n", snippet);
let _ = write!(conversation_text, "Tool result: {snippet}\n\n");
}
ContentBlock::Thinking { .. } => {
// Skip thinking blocks in summary
@@ -1465,9 +1465,9 @@ fn extract_workflow_context(messages: &[Message], workspace: Option<&Path>) -> S
.strip_prefix(ws)
.unwrap_or(Path::new(file))
.display();
context.push_str(&format!("- `{}`\n", relative));
context.push_str(&format!("- `{relative}`\n"));
} else {
context.push_str(&format!("- `{}`\n", file));
context.push_str(&format!("- `{file}`\n"));
}
}
context.push('\n');
@@ -1482,7 +1482,7 @@ fn extract_workflow_context(messages: &[Message], workspace: Option<&Path>) -> S
if !tasks_identified.is_empty() {
context.push_str("**Tasks/TODOs Identified:**\n");
for task in &tasks_identified {
context.push_str(&format!("- {}\n", task));
context.push_str(&format!("- {task}\n"));
}
context.push('\n');
}
+5 -11
View File
@@ -2142,14 +2142,13 @@ pub fn ensure_config_file_exists(path: Option<PathBuf>) -> Result<Option<PathBuf
# base_url = "https://api.deepseek.com/beta"
# Default model
default_text_model = "{default_model}"
default_text_model = "{DEFAULT_TEXT_MODEL}"
# Thinking mode (DeepSeek V4 reasoning effort):
# "auto" | "off" | "low" | "medium" | "high" | "max"
# Shift+Tab in the TUI cycles between off / high / max.
reasoning_effort = "auto"
"#,
default_model = DEFAULT_TEXT_MODEL
"#
);
write_config_file_secure(&config_path, &content)
.with_context(|| format!("Failed to write config to {}", config_path.display()))?;
@@ -2888,11 +2887,7 @@ fn apply_profile(config: ConfigFile, profile: Option<&str>) -> Result<Config> {
}
})
.unwrap_or_else(|| "none".to_string());
anyhow::bail!(
"Profile '{}' not found. Available profiles: {}",
profile_name,
available
)
anyhow::bail!("Profile '{profile_name}' not found. Available profiles: {available}")
}
}
} else {
@@ -3335,14 +3330,13 @@ api_key = "{key_to_write}"
# base_url = "https://api.deepseek.com/beta"
# Default model
default_text_model = "{default_model}"
default_text_model = "{DEFAULT_TEXT_MODEL}"
# Thinking mode (DeepSeek V4 reasoning effort):
# "off" | "low" | "medium" | "high" | "max"
# Shift+Tab in the TUI cycles between off / high / max.
reasoning_effort = "max"
"#,
default_model = DEFAULT_TEXT_MODEL
"#
)
};
+1 -2
View File
@@ -796,8 +796,7 @@ mod tests {
let elapsed = start.elapsed();
let per_call_ns = elapsed.as_nanos() as f64 / iters as f64;
println!(
"compute_profile window={window_len:>4} total={:?} per-call={per_call_ns:>8.0}ns",
elapsed
"compute_profile window={window_len:>4} total={elapsed:?} per-call={per_call_ns:>8.0}ns"
);
}
}
+2 -3
View File
@@ -1363,7 +1363,7 @@ impl Engine {
"Emergency compaction complete: {before_count} → {after_count} messages ({removed} removed), ~{before_tokens} → ~{after_tokens} tokens"
);
if retries_used > 0 {
details.push_str(&format!(" ({} retries)", retries_used));
details.push_str(&format!(" ({retries_used} retries)"));
}
if trimmed > 0 {
details.push_str(&format!(", trimmed {trimmed} oldest"));
@@ -1382,8 +1382,7 @@ impl Engine {
let message = format!(
"Emergency context compaction failed to reduce request below model limit \
(estimate ~{} tokens, budget ~{}).",
after_tokens, target_budget
(estimate ~{after_tokens} tokens, budget ~{target_budget})."
);
self.emit_compaction_failed(id, true, message.clone()).await;
let _ = self.tx_event.send(Event::status(message)).await;
+11 -21
View File
@@ -180,9 +180,8 @@ impl Engine {
if estimated_input > input_budget {
if context_recovery_attempts >= MAX_CONTEXT_RECOVERY_ATTEMPTS {
let message = format!(
"Context remains above model limit after {} recovery attempts \
(~{} token estimate, ~{} budget). Please run /compact or /clear.",
MAX_CONTEXT_RECOVERY_ATTEMPTS, estimated_input, input_budget
"Context remains above model limit after {MAX_CONTEXT_RECOVERY_ATTEMPTS} recovery attempts \
(~{estimated_input} token estimate, ~{input_budget} budget). Please run /compact or /clear."
);
turn_error = Some(message.clone());
let _ = self
@@ -489,8 +488,7 @@ impl Engine {
transparent_stream_retries =
transparent_stream_retries.saturating_add(1);
crate::logging::info(format!(
"Transparent stream retry {}/{} (no content received yet): {}",
transparent_stream_retries, MAX_TRANSPARENT_STREAM_RETRIES, message,
"Transparent stream retry {transparent_stream_retries}/{MAX_TRANSPARENT_STREAM_RETRIES} (no content received yet): {message}",
));
// Drop the failed stream before issuing the new
// request to release the underlying connection.
@@ -585,8 +583,7 @@ impl Engine {
caller,
} => {
crate::logging::info(format!(
"Tool '{}' block start. Initial input: {:?}",
name, input
"Tool '{name}' block start. Initial input: {input:?}"
));
current_block_kind = Some(ContentBlockKind::ToolUse);
current_tool_indices.insert(index, tool_uses.len());
@@ -604,8 +601,7 @@ impl Engine {
}
ContentBlockStart::ServerToolUse { id, name, input } => {
crate::logging::info(format!(
"Server tool '{}' block start. Initial input: {:?}",
name, input
"Server tool '{name}' block start. Initial input: {input:?}"
));
current_block_kind = Some(ContentBlockKind::ToolUse);
current_tool_indices.insert(index, tool_uses.len());
@@ -781,14 +777,12 @@ impl Engine {
if stream_retry_attempts < MAX_STREAM_RETRIES {
stream_retry_attempts = stream_retry_attempts.saturating_add(1);
crate::logging::warn(format!(
"Stream died with no content (attempt {}/{}); retrying request",
stream_retry_attempts, MAX_STREAM_RETRIES
"Stream died with no content (attempt {stream_retry_attempts}/{MAX_STREAM_RETRIES}); retrying request"
));
let _ = self
.tx_event
.send(Event::status(format!(
"Connection interrupted; retrying ({}/{})",
stream_retry_attempts, MAX_STREAM_RETRIES
"Connection interrupted; retrying ({stream_retry_attempts}/{MAX_STREAM_RETRIES})"
)))
.await;
// Don't preserve the per-stream `turn_error` — we're
@@ -798,8 +792,7 @@ impl Engine {
continue;
}
crate::logging::warn(format!(
"Stream retry budget exhausted ({} attempts); failing turn",
stream_retry_attempts
"Stream retry budget exhausted ({stream_retry_attempts} attempts); failing turn"
));
} else if stream_errors == 0 {
// Healthy round → reset retry budget so we don't carry over
@@ -1156,8 +1149,7 @@ impl Engine {
let tool_input = tool.input.clone();
let tool_caller = tool.caller.clone();
crate::logging::info(format!(
"Planning tool '{}' with input: {:?}",
tool_name, tool_input
"Planning tool '{tool_name}' with input: {tool_input:?}"
));
let interactive = (tool_name == "exec_shell"
@@ -1201,8 +1193,7 @@ impl Engine {
&& let Some(canonical) = registry.resolve(&tool_name)
{
crate::logging::info(format!(
"Resolved hallucinated tool name '{}' -> '{}'",
tool_name, canonical
"Resolved hallucinated tool name '{tool_name}' -> '{canonical}'"
));
tool_def = tool_catalog.iter().find(|d| d.name == canonical);
if tool_def.is_some() {
@@ -1281,8 +1272,7 @@ impl Engine {
format!("Auto-loaded deferred tool '{tool_name}' after model request.")
} else {
format!(
"Auto-loaded deferred tool '{}' after resolving '{}'.",
tool_name, requested_tool_name
"Auto-loaded deferred tool '{tool_name}' after resolving '{requested_tool_name}'."
)
};
let _ = self.tx_event.send(Event::status(status)).await;
+1 -1
View File
@@ -794,7 +794,7 @@ fn truncate_output(value: &str, max_chars: usize) -> String {
}
let truncated: String = value.chars().take(max_chars).collect();
format!("{}...", truncated)
format!("{truncated}...")
}
#[cfg(test)]
+1 -1
View File
@@ -719,7 +719,7 @@ impl HookExecutor {
stdout: String::new(),
stderr: String::new(),
duration: started.elapsed(),
error: Some(format!("Hook timed out after {}s", timeout_secs)),
error: Some(format!("Hook timed out after {timeout_secs}s")),
}
}
Err(e) => HookResult {
+4 -4
View File
@@ -1918,7 +1918,7 @@ async fn run_doctor(config: &Config, workspace: &Path, config_path_override: Opt
} else if error_msg.contains("connect") {
println!(" Connection failed. Check firewall settings or try again");
} else {
println!(" Error: {}", error_msg);
println!(" Error: {error_msg}");
}
}
}
@@ -3512,7 +3512,7 @@ fn collect_diff(args: &ReviewArgs) -> Result<String> {
let output = cmd
.output()
.map_err(|e| anyhow::anyhow!("Failed to run git diff. Is git installed? ({})", e))?;
.map_err(|e| anyhow::anyhow!("Failed to run git diff. Is git installed? ({e})"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("git diff failed: {}", stderr.trim());
@@ -3544,7 +3544,7 @@ fn run_apply(args: ApplyArgs) -> Result<()> {
.arg("--whitespace=nowarn")
.arg(&tmp_path)
.output()
.map_err(|e| anyhow::anyhow!("Failed to run git apply: {}", e))?;
.map_err(|e| anyhow::anyhow!("Failed to run git apply: {e}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -3966,7 +3966,7 @@ fn run_sandbox_command(args: SandboxArgs) -> Result<()> {
print!("{}", String::from_utf8_lossy(&stdout));
}
if !stderr.is_empty() {
eprint!("{}", stderr_str);
eprint!("{stderr_str}");
}
if sandbox_denied {
eprintln!(
+5 -8
View File
@@ -1282,10 +1282,7 @@ impl McpConnection {
stderr_tail,
})
} else {
anyhow::bail!(
"MCP server '{}' config must have either 'command' or 'url'",
name
);
anyhow::bail!("MCP server '{name}' config must have either 'command' or 'url'");
};
let mut conn = Self {
@@ -1950,7 +1947,7 @@ impl McpPool {
// Format: mcp_{server}_{resource_name}
// Note: resource names might contain spaces, we should probably slugify them
let safe_name = resource.name.replace(' ', "_").to_lowercase();
resources.push((format!("mcp_{}_{}", server, safe_name), resource));
resources.push((format!("mcp_{server}_{safe_name}"), resource));
}
}
resources
@@ -1963,7 +1960,7 @@ impl McpPool {
for (server, conn) in &self.connections {
for template in conn.resource_templates() {
let safe_name = template.name.replace(' ', "_").to_lowercase();
templates.push((format!("mcp_{}_{}", server, safe_name), template));
templates.push((format!("mcp_{server}_{safe_name}"), template));
}
}
templates
@@ -2082,11 +2079,11 @@ impl McpPool {
/// Parse a prefixed name into (server_name, tool_name)
fn parse_prefixed_name<'a>(&self, prefixed_name: &'a str) -> Result<(&'a str, &'a str)> {
if !prefixed_name.starts_with("mcp_") {
anyhow::bail!("Invalid MCP tool name: {}", prefixed_name);
anyhow::bail!("Invalid MCP tool name: {prefixed_name}");
}
let rest = &prefixed_name[4..];
let Some((server, tool)) = rest.split_once('_') else {
anyhow::bail!("Invalid MCP tool name format: {}", prefixed_name);
anyhow::bail!("Invalid MCP tool name format: {prefixed_name}");
};
Ok((server, tool))
}
+1 -1
View File
@@ -65,7 +65,7 @@ impl PrefixFingerprint {
_ => sha256_hex(b""),
};
let combined = format!("{}:{}", system_sha256, tools_sha256);
let combined = format!("{system_sha256}:{tools_sha256}");
let combined_sha256 = sha256_hex(combined.as_bytes());
Self {
+3 -4
View File
@@ -168,8 +168,7 @@ fn load_handoff_block(workspace: &Path) -> Option<String> {
return None;
}
Some(format!(
"## Previous Session Relay\n\nThe previous session in this workspace left a relay artifact at `{}`. Consider it the first artifact to read on this turn — open blockers, in-flight changes, and recent decisions live there. Update or rewrite it before exiting if state changes materially.\n\n{}",
HANDOFF_RELATIVE_PATH, trimmed
"## Previous Session Relay\n\nThe previous session in this workspace left a relay artifact at `{HANDOFF_RELATIVE_PATH}`. Consider it the first artifact to read on this turn — open blockers, in-flight changes, and recent decisions live there. Update or rewrite it before exiting if state changes materially.\n\n{trimmed}"
))
}
@@ -600,7 +599,7 @@ pub fn system_prompt_for_mode_with_context_skills_session_and_approval(
// `load_project_context_with_parents` auto-generates .deepseek/instructions.md
// when no context file exists, so the fallback should always be available.
let mut full_prompt = if let Some(project_block) = project_context.as_system_block() {
format!("{}\n\n{}", mode_prompt, project_block)
format!("{mode_prompt}\n\n{project_block}")
} else {
// Extremely unlikely: context generation failed (e.g. filesystem error).
// Use mode prompt alone rather than panic.
@@ -1664,7 +1663,7 @@ mod tests {
#[test]
fn legacy_constants_still_available() {
// Verify the legacy .txt constant still compiles and contains expected content
assert!(!AGENT_PROMPT.is_empty());
assert!(AGENT_PROMPT.lines().next().is_some());
}
// ── Cache-prefix stability harness (#263 step 2) ───────────────────────
+1 -2
View File
@@ -205,9 +205,8 @@ impl PythonRuntime {
let interpreter = resolve_python_interpreter().ok_or_else(|| {
format!(
"no Python interpreter found on PATH (tried {:?}). \
"no Python interpreter found on PATH (tried {PYTHON_CANDIDATES:?}). \
Install Python 3 and ensure one of these commands works, then restart codewhale.",
PYTHON_CANDIDATES,
)
})?;
let (program, interpreter_args) = split_interpreter_spec(&interpreter);
+1 -2
View File
@@ -2459,8 +2459,7 @@ impl RuntimeThreadManager {
..
} => {
let message = format!(
"Capacity intervention: {action} (~{before_prompt_tokens} -> ~{after_prompt_tokens}) replay={:?} replan={replan_performed}",
replay_outcome
"Capacity intervention: {action} (~{before_prompt_tokens} -> ~{after_prompt_tokens}) replay={replay_outcome:?} replan={replan_performed}"
);
let item = TurnItemRecord {
schema_version: CURRENT_RUNTIME_SCHEMA_VERSION,
+2 -3
View File
@@ -1656,10 +1656,9 @@ mod tests {
"workspace": "/tmp"
}},
"messages": [
{{ "role": "user", "content": [ {{ "Text": {{ "text": {body:?} }} }} ] }}
{{ "role": "user", "content": [ {{ "Text": {{ "text": {big_text:?} }} }} ] }}
]
}}"#,
body = big_text
}}"#
);
let extracted =
+2 -3
View File
@@ -399,7 +399,7 @@ pub async fn update_with_registry(
let marker_body = fs::read_to_string(&marker_path)
.with_context(|| format!("failed to read {}", marker_path.display()))?;
let marker: InstalledFromMarker = serde_json::from_str(&marker_body)
.with_context(|| format!("malformed {} for {name}", INSTALLED_FROM_MARKER))?;
.with_context(|| format!("malformed {INSTALLED_FROM_MARKER} for {name}"))?;
// Re-resolve the URL, taking the existing checksum as a short-circuit hint:
// we still hit the network so the user gets a useful "no upstream change"
@@ -719,8 +719,7 @@ async fn sync_one_skill(
return SkillSyncOutcome::Failed {
name: name.to_string(),
reason: format!(
"download from {url} exceeds compressed size cap ({} bytes)",
compressed_cap
"download from {url} exceeds compressed size cap ({compressed_cap} bytes)"
),
};
}
+1 -1
View File
@@ -1318,7 +1318,7 @@ impl TaskManager {
),
TaskStatus::Canceled => "Task canceled".to_string(),
TaskStatus::Queued | TaskStatus::Running => {
format!("Task ended in unexpected state: {}", mode_label)
format!("Task ended in unexpected state: {mode_label}")
}
},
detail_path: None,
+1 -1
View File
@@ -208,7 +208,7 @@ mod tests {
.current_dir(root)
.status()
.expect("git should spawn");
assert!(status.success(), "git {:?} failed", args);
assert!(status.success(), "git {args:?} failed");
};
run(&["init", "-q"]);
run(&["config", "user.email", "test@example.com"]);
+2 -3
View File
@@ -161,7 +161,7 @@ impl ToolSpec for FimEditTool {
// 7. Build the new content and write it back
let generated_len = generated_text.len();
let new_content = format!("{}{}{}", fim_prompt, generated_text, fim_suffix);
let new_content = format!("{fim_prompt}{generated_text}{fim_suffix}");
fs::write(&resolved, &new_content).map_err(|e| {
ToolError::execution_failed(format!("Failed to write {}: {}", resolved.display(), e))
})?;
@@ -173,8 +173,7 @@ impl ToolSpec for FimEditTool {
prefix_end,
suffix_start,
message: format!(
"FIM edit applied to `{}`. Generated {} chars between prefix_anchor end (byte {}) and suffix_anchor start (byte {}).",
path, generated_len, prefix_end, suffix_start,
"FIM edit applied to `{path}`. Generated {generated_len} chars between prefix_anchor end (byte {prefix_end}) and suffix_anchor start (byte {suffix_start}).",
),
};
+3 -3
View File
@@ -332,7 +332,7 @@ mod tests {
.current_dir(root)
.status()
.expect("git should spawn");
assert!(status.success(), "git {:?} failed", args);
assert!(status.success(), "git {args:?} failed");
};
run(&["init", "-q"]);
@@ -347,7 +347,7 @@ mod tests {
.current_dir(root)
.status()
.expect("git should spawn");
assert!(status.success(), "git {:?} failed", args);
assert!(status.success(), "git {args:?} failed");
};
run(&["add", "."]);
run(&["commit", "-q", "-m", message]);
@@ -438,7 +438,7 @@ mod tests {
.current_dir(tmp.path())
.status()
.expect("git should spawn");
assert!(status.success(), "git {:?} failed", args);
assert!(status.success(), "git {args:?} failed");
};
run_git(&["config", "core.quotepath", "true"]);
+1 -1
View File
@@ -517,7 +517,7 @@ mod tests {
.current_dir(root)
.status()
.expect("git should spawn");
assert!(status.success(), "git {:?} failed", args);
assert!(status.success(), "git {args:?} failed");
}
fn init_git_repo(root: &Path) {
@@ -897,8 +897,7 @@ mod tests {
payload
.to_string()
.contains("canonical session artifact body"),
"summary should pull from session artifact, got: {}",
payload
"summary should pull from session artifact, got: {payload}"
);
}
+2 -2
View File
@@ -1213,7 +1213,7 @@ fn render_lines(lines: &[String], start: usize, end: usize) -> String {
if line_no < start || line_no > end {
return None;
}
Some(format!("{:>4} {}", line_no, line))
Some(format!("{line_no:>4} {line}"))
})
.collect::<Vec<_>>()
.join("\n")
@@ -1414,7 +1414,7 @@ fn replace_links(html: &str, base_url: &str) -> (String, Vec<WebLink>) {
url: resolved.clone(),
text: text.clone(),
});
output.push_str(&format!("[{}] {}", id, text));
output.push_str(&format!("[{id}] {text}"));
} else {
output.push_str(&resolved);
}
+1 -1
View File
@@ -256,7 +256,7 @@ fn build_mcp_entries(
tool.model_name,
tool.description
.as_ref()
.map_or(String::new(), |desc| format!(" ({})", desc))
.map_or(String::new(), |desc| format!(" ({desc})"))
),
command: tool.model_name.clone(),
action: CommandPaletteAction::InsertText {
+1 -1
View File
@@ -101,7 +101,7 @@ pub fn build_context_inspector_text(app: &App) -> String {
crate::utils::display_path(&app.workspace)
);
if let Some(session_id) = app.current_session_id.as_deref() {
let _ = writeln!(out, "Session: {}", session_id);
let _ = writeln!(out, "Session: {session_id}");
}
let (used, max, percent) = usage;
let _ = writeln!(
+2 -12
View File
@@ -318,20 +318,10 @@ fn render_diff_line(
fn format_line_numbers(old_line: Option<usize>, new_line: Option<usize>, marker: char) -> String {
let old = old_line
.map(|value| {
format!(
"{value:>LINE_NUMBER_WIDTH$}",
LINE_NUMBER_WIDTH = LINE_NUMBER_WIDTH
)
})
.map(|value| format!("{value:>LINE_NUMBER_WIDTH$}"))
.unwrap_or_else(|| " ".repeat(LINE_NUMBER_WIDTH));
let new = new_line
.map(|value| {
format!(
"{value:>LINE_NUMBER_WIDTH$}",
LINE_NUMBER_WIDTH = LINE_NUMBER_WIDTH
)
})
.map(|value| format!("{value:>LINE_NUMBER_WIDTH$}"))
.unwrap_or_else(|| " ".repeat(LINE_NUMBER_WIDTH));
format!("{old} {new} {marker} ")
}
+2 -4
View File
@@ -568,7 +568,7 @@ mod tests {
// Identical query matches start with high bonus.
let a = score("main", "main.rs").unwrap();
let b = score("main", "src/very/deep/main.rs").unwrap();
assert!(a > b, "a={} b={}", a, b);
assert!(a > b, "a={a} b={b}");
}
#[test]
@@ -591,9 +591,7 @@ mod tests {
if let Some(inline_score) = inline {
assert!(
boundary > inline_score,
"boundary={} inline={}",
boundary,
inline_score
"boundary={boundary} inline={inline_score}"
);
}
}
+1 -4
View File
@@ -623,10 +623,7 @@ pub(crate) fn footer_cache_spans(app: &App) -> Vec<Span<'static>> {
palette::STATUS_ERROR
};
vec![Span::styled(
format!(
"Cache: {:.1}% hit | hit {hit_tokens} | miss {miss_tokens}",
percent
),
format!("Cache: {percent:.1}% hit | hit {hit_tokens} | miss {miss_tokens}"),
Style::default().fg(color),
)]
}
+1 -1
View File
@@ -3413,7 +3413,7 @@ mod tests {
};
let lines = cell.lines_with_mode(80, true, super::RenderMode::Live);
// One header line, no details/args/output expansion.
assert_eq!(lines.len(), 1, "expected exactly 1 line, got {:?}", lines);
assert_eq!(lines.len(), 1, "expected exactly 1 line, got {lines:?}");
let rendered: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
// Header carries the agent id and the running status.
assert!(
+2 -3
View File
@@ -307,7 +307,7 @@ mod tests {
#[test]
fn catalog_is_non_empty_and_sections_have_entries() {
assert!(!KEYBINDINGS.is_empty());
assert!(KEYBINDINGS.iter().any(|entry| !entry.chord.is_empty()));
// Every declared section should appear in the catalog at least once,
// otherwise the help overlay would render an empty heading.
let sections = [
@@ -322,8 +322,7 @@ mod tests {
for section in sections {
assert!(
KEYBINDINGS.iter().any(|entry| entry.section == section),
"no entries for section {:?}",
section
"no entries for section {section:?}"
);
}
}
+3 -5
View File
@@ -543,7 +543,7 @@ fn build_list_lines(
) -> Vec<Line<'static>> {
let mut lines = Vec::new();
let header = if search_mode {
format!("/{}", search_input)
format!("/{search_input}")
} else {
format!(
"1-9 history | PgUp/PgDn scroll | Enter resume | / search | s sort | a all | d delete | Sort: {sort_label}"
@@ -656,7 +656,7 @@ fn build_preview_lines(session: &SavedSession) -> Vec<String> {
session.metadata.message_count, session.metadata.model
));
if let Some(mode) = session.metadata.mode.as_deref() {
out.push(format!("Mode: {}", mode));
out.push(format!("Mode: {mode}"));
}
out.push("".to_string());
@@ -993,9 +993,7 @@ mod tests {
let rendered_width: usize = line.spans.iter().map(|span| span.content.width()).sum();
assert!(
rendered_width <= width as usize,
"line width {} exceeded pane width {}",
rendered_width,
width
"line width {rendered_width} exceeded pane width {width}"
);
}
}
+3 -3
View File
@@ -1712,7 +1712,7 @@ fn render_context_panel(f: &mut Frame, area: Rect, app: &App) {
// ── LSP ──────────────────────────────────────────────────────
let lsp_label = if app.lsp_enabled { "on" } else { "off" };
lines.push(Line::from(Span::styled(
format!("lsp: {}", lsp_label),
format!("lsp: {lsp_label}"),
Style::default().fg(palette::TEXT_MUTED),
)));
@@ -1738,7 +1738,7 @@ fn render_context_panel(f: &mut Frame, area: Rect, app: &App) {
} else if bytes >= 1024 {
format!("{:.1} KB", bytes as f64 / 1024.0)
} else {
format!("{} B", bytes)
format!("{bytes} B")
}
})
.unwrap_or_else(|_| "".to_string());
@@ -2617,7 +2617,7 @@ mod tests {
};
let text = lines_to_text(&subagent_panel_lines(&summary, &[], 64, 8));
assert!(!text[0].contains("No agents"), "header: {:?}", text);
assert!(!text[0].contains("No agents"), "header: {text:?}");
assert!(
text.iter()
.any(|line| line.contains("RLM foreground work active")),
+2 -2
View File
@@ -259,10 +259,10 @@ fn format_task_detail(task: &TaskRecord) -> String {
}
lines.push(format!("Created: {}", task.created_at));
if let Some(started_at) = task.started_at {
lines.push(format!("Started: {}", started_at));
lines.push(format!("Started: {started_at}"));
}
if let Some(ended_at) = task.ended_at {
lines.push(format!("Ended: {}", ended_at));
lines.push(format!("Ended: {ended_at}"));
}
if let Some(duration) = task.duration_ms {
lines.push(format!("Duration: {:.2}s", duration as f64 / 1000.0));
+5 -7
View File
@@ -253,7 +253,7 @@ pub async fn run_tui(config: &Config, options: TuiOptions) -> Result<()> {
// Terminal probe with timeout to prevent hanging on unresponsive terminals
let probe_timeout = terminal_probe_timeout(config);
let enable_raw = tokio::task::spawn_blocking(move || {
enable_raw_mode().map_err(|e| anyhow::anyhow!("Failed to enable raw mode: {}", e))
enable_raw_mode().map_err(|e| anyhow::anyhow!("Failed to enable raw mode: {e}"))
});
match tokio::time::timeout(probe_timeout, enable_raw).await {
@@ -2599,7 +2599,7 @@ async fn run_event_loop(
// Insert @path into the composer.
let path_str = rel_path.to_string_lossy().to_string();
app.status_message = Some(format!("Attached @{path_str}"));
app.insert_str(&format!("@{} ", path_str));
app.insert_str(&format!("@{path_str} "));
} else {
// Directory was expanded/collapsed; rebuild.
app.needs_redraw = true;
@@ -6898,16 +6898,14 @@ fn maybe_warn_context_pressure(app: &mut App) {
if percent >= CONTEXT_CRITICAL_THRESHOLD_PERCENT {
app.status_message = Some(format!(
"Context critical: {:.0}% ({used}/{max} tokens). {recommendation}",
percent
"Context critical: {percent:.0}% ({used}/{max} tokens). {recommendation}"
));
return;
}
if app.status_message.is_none() {
app.status_message = Some(format!(
"Context high: {:.0}% ({used}/{max} tokens). {recommendation}",
percent
"Context high: {percent:.0}% ({used}/{max} tokens). {recommendation}"
));
}
}
@@ -7278,7 +7276,7 @@ fn activity_status_line(cell: &HistoryCell) -> Option<String> {
}
Some(line)
}
HistoryCell::Error { severity, .. } => Some(format!("Status: {:?}", severity)),
HistoryCell::Error { severity, .. } => Some(format!("Status: {severity:?}")),
HistoryCell::SubAgent(_) => None,
_ => None,
}
+1 -2
View File
@@ -459,8 +459,7 @@ impl ModalView for HelpView {
let cursor = if is_selected { "" } else { " " };
let label = truncate_to_width(&entry.label, label_width);
let desc = truncate_to_width(&entry.description, desc_capacity);
let line_text =
format!("{cursor}{label:<label_width$} {desc}", label = label,);
let line_text = format!("{cursor}{label:<label_width$} {desc}",);
lines.push(Line::from(Span::styled(line_text, style)));
}
}
+1 -1
View File
@@ -1717,7 +1717,7 @@ impl ModalView for SubAgentsView {
let mut summary_parts = Vec::new();
for (label, count, color) in status_summary {
summary_parts.push(Line::from(Span::styled(
format!("{}: {}", label, count),
format!("{label}: {count}"),
Style::default().fg(color),
)));
}
+1 -1
View File
@@ -583,7 +583,7 @@ impl Renderable for ComposerWidget<'_> {
SubmitDisposition::Immediate => {
if queue_count > 0 {
(
Some(format!("↵ send ({} queued)", queue_count)),
Some(format!("↵ send ({queue_count} queued)")),
palette::DEEPSEEK_SKY,
)
} else {
+1 -1
View File
@@ -164,7 +164,7 @@ impl ToolSpec for ImageAnalyzeTool {
let response = client
.post(&url)
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", api_key))
.header("Authorization", format!("Bearer {api_key}"))
.json(&payload)
.send()
.await
+2 -2
View File
@@ -35,7 +35,7 @@ fn color_to_rgb(color: Color) -> (u8, u8, u8) {
Color::LightMagenta => (255, 153, 255),
Color::Cyan => (0, 255, 255),
Color::LightCyan => (153, 255, 255),
_ => panic!("unsupported color variant for contrast test: {:?}", color),
_ => panic!("unsupported color variant for contrast test: {color:?}"),
}
}
@@ -79,7 +79,7 @@ fn audit_file(path: &Path, violations: &mut Vec<String>) {
for (line_num, line) in content.lines().enumerate() {
for deprecated in DEPRECATED_DIRECT_COLORS {
let pattern = format!("palette::{}", deprecated);
let pattern = format!("palette::{deprecated}");
if line.contains(&pattern) {
let is_allowed = ALLOWED_PATTERNS.iter().any(|p| line.contains(p));
if !is_allowed {