fix(clippy): clear remaining -D warnings failures in rusty-claude-cli

`cargo clippy --workspace --all-targets -- -D warnings` is this repo's own
documented verification command, and it could not run to completion. Earlier
compile failures were masking a further 48 lints; with those cleared the
workspace now passes with zero findings.

Real fixes, not suppressions:
  - status_json_value took 8 positional parameters, four of them a tail of
    `Option<&_>` that most callers passed as None — trivially transposable.
    Grouped into `StatusJsonExtras` with a Default impl; all 7 call sites now
    name only the fields they actually set.
  - extract_help_metadata's 8-tuple return is now a documented `HelpMetadata`
    alias.
  - the auto-compact loop indexed preserve_schedule by its loop counter;
    it now iterates the array directly.
  - a sandbox status chain had two identical arms; merged the condition.
  - a filter_map whose every arm returned Some is now a map.
  - 33 unused stdout/stderr bindings in the output-format contract tests are
    prefixed with `_`, and 9 `map_or(false, ..)` are now `is_some_and(..)`.

NOTE: several `--bin claw` tests (parse_args defaults) read the *real*
`~/.claw/settings.json` rather than an isolated config home, so they fail on
any machine whose user config sets `permissions.defaultMode`. With that file
moved aside the binary's suite is 207/207. That isolation gap is pre-existing
and left for a separate change.

Verified: clippy workspace/all-targets/-D warnings reports 0; cargo test
--workspace passes with the user config neutralised; scripts/fmt.sh clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9McEEH32ZtyM62GSXVSyJ
(cherry picked from commit 03c8a8fd7ba6e405a8217d00d3766c1c6367e527)
This commit is contained in:
reacechalmers authored and clawdbot committed 2026-10-12 22:58:19 +00:00
1 parent cd01ffc5f3
commit 2944e02a09
3 files changed
+130 -137

No files matched your search

+85 -91
View File
@@ -1941,9 +1941,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
// Only reject for known top-level subcommands that don't use compact.
let first = rest[0].as_str();
if is_known_top_level_subcommand(first) && first != "prompt" {
return Err(format!(
"invalid_flag_value: --compact is only supported with prompt mode.\nUsage: claw --compact \"<prompt>\" or echo \"<prompt>\" | claw --compact"
));
return Err("invalid_flag_value: --compact is only supported with prompt mode.\nUsage: claw --compact \"<prompt>\" or echo \"<prompt>\" | claw --compact".to_string());
}
}
@@ -3147,10 +3145,11 @@ fn print_model_validation_warning_status(
usage,
permission_mode,
context,
None,
None,
allowed_tools,
Some(&format_selection),
&StatusJsonExtras {
allowed_tools,
format_selection: Some(&format_selection),
..StatusJsonExtras::default()
},
);
let object = value
.as_object_mut()
@@ -3226,9 +3225,7 @@ fn parse_system_prompt_args(
})?;
// #99: validate --date is a plausible date string (no newlines, reasonable length)
if value.contains('\n') || value.contains('\r') {
return Err(format!(
"invalid_flag_value: --date value contains invalid characters.\nUsage: --date <YYYY-MM-DD>"
));
return Err("invalid_flag_value: --date value contains invalid characters.\nUsage: --date <YYYY-MM-DD>".to_string());
}
if value.len() > 20 {
return Err(format!(
@@ -3465,11 +3462,7 @@ impl DiagnosticCheck {
fn json_value(&self) -> Value {
// Derive a stable snake_case id from the check name for machine-readable keying (#704).
let id = self
.name
.to_ascii_lowercase()
.replace(' ', "_")
.replace('-', "_");
let id = self.name.to_ascii_lowercase().replace([' ', '-'], "_");
let mut value = Map::from_iter([
("id".to_string(), Value::String(id.clone())),
(
@@ -6650,10 +6643,8 @@ fn run_resume_command(
},
default_permission_mode().as_str(),
&context,
None, // #148: resumed sessions don't have flag provenance
None,
None,
None,
// #148: resumed sessions don't have flag provenance
&StatusJsonExtras::default(),
)),
})
}
@@ -6791,16 +6782,15 @@ fn run_resume_command(
}
SlashCommand::Plugins { action, target } => {
// Only list is supported in resume mode (no runtime to reload)
match action.as_deref() {
Some(action @ ("install" | "uninstall" | "enable" | "disable" | "update")) => {
// #777: use interactive_only: prefix + \n hint so #776's classify/split
// emits error_kind:interactive_only + non-null hint instead of unknown+null.
// Orchestrators can now detect this and switch to a live REPL instead of retrying.
return Err(format!(
"interactive_only: /plugins {action} requires a live session to reload the plugin runtime.\nStart `claw` and run `/plugins {action}` inside the REPL, or use `claw plugins {action}` as a direct CLI command."
).into());
}
_ => {}
if let Some(action @ ("install" | "uninstall" | "enable" | "disable" | "update")) =
action.as_deref()
{
// #777: use interactive_only: prefix + \n hint so #776's classify/split
// emits error_kind:interactive_only + non-null hint instead of unknown+null.
// Orchestrators can now detect this and switch to a live REPL instead of retrying.
return Err(format!(
"interactive_only: /plugins {action} requires a live session to reload the plugin runtime.\nStart `claw` and run `/plugins {action}` inside the REPL, or use `claw plugins {action}` as a direct CLI command."
).into());
}
let cwd = env::current_dir()?;
let payload = plugins_command_payload_for(
@@ -7940,8 +7930,7 @@ impl LiveCli {
let max_compact_rounds = 4;
let preserve_schedule = [4, 2, 1, 0];
for round in 0..max_compact_rounds {
let preserve = preserve_schedule[round];
for (round, &preserve) in preserve_schedule.iter().enumerate() {
println!(
" Auto-compacting session (round {}/{}, preserving {} recent messages)...",
round + 1,
@@ -8709,8 +8698,8 @@ impl LiveCli {
let cwd = env::current_dir()?;
// #803: reject flag-shaped tokens in list filter for BOTH text and JSON modes.
// Previously the guard was JSON-only (#793); text mode silently returned empty success.
if action.as_deref() == Some("list") {
if let Some(filter) = target.as_deref() {
if action == Some("list") {
if let Some(filter) = target {
if filter.starts_with('-') {
if matches!(output_format, CliOutputFormat::Json) {
// ROADMAP #817: this is a handled local inventory parse error.
@@ -9670,31 +9659,49 @@ fn print_status_snapshot(
usage,
permission_mode.mode.as_str(),
&context,
Some(&provenance),
Some(&permission_mode),
allowed_tools,
Some(&format_selection),
&StatusJsonExtras {
provenance: Some(&provenance),
permission_provenance: Some(&permission_mode),
allowed_tools,
format_selection: Some(&format_selection),
},
))?
),
}
Ok(())
}
/// Optional provenance and selection inputs for [`status_json_value`].
///
/// Grouped into a struct rather than trailing positional parameters: they are all
/// `Option<&_>` and most callers pass `None` for most of them, which makes a
/// positional tail easy to transpose silently.
///
/// `provenance` (#148) drives the `model_source` field ("flag" | "env" | "config" |
/// "default") and `model_raw` (user input before alias resolution, or null when the
/// source is "default"). Callers without provenance (legacy resume paths) leave it
/// `None`, in which case both fields are omitted.
#[derive(Default)]
struct StatusJsonExtras<'a> {
provenance: Option<&'a ModelProvenance>,
permission_provenance: Option<&'a PermissionModeProvenance>,
allowed_tools: Option<&'a AllowedToolSet>,
format_selection: Option<&'a OutputFormatSelection>,
}
fn status_json_value(
model: Option<&str>,
usage: StatusUsage,
permission_mode: &str,
context: &StatusContext,
// #148: optional provenance for `model` field. Surfaces `model_source`
// ("flag" | "env" | "config" | "default") and `model_raw` (user input
// before alias resolution, or null when source is "default"). Callers
// that don't have provenance (legacy resume paths) pass None, in which
// case both new fields are omitted.
provenance: Option<&ModelProvenance>,
permission_provenance: Option<&PermissionModeProvenance>,
allowed_tools: Option<&AllowedToolSet>,
format_selection: Option<&OutputFormatSelection>,
extras: &StatusJsonExtras<'_>,
) -> serde_json::Value {
let StatusJsonExtras {
provenance,
permission_provenance,
allowed_tools,
format_selection,
} = *extras;
// #143: top-level `status` marker so claws can distinguish
// a clean run from a degraded run (config parse failed but other fields
// are still populated). `config_load_error` carries the parse-error string
@@ -10176,9 +10183,7 @@ fn sandbox_json_value(status: &runtime::SandboxStatus) -> serde_json::Value {
// (#731: "not supported on macOS" is a degraded state, not a hard error;
// filesystem_active:true means partial containment is working)
// error = enabled but unsupported AND no filesystem sandbox either (nothing active)
let top_status = if !status.enabled {
"ok"
} else if status.active {
let top_status = if !status.enabled || status.active {
"ok"
} else if status.supported {
"warn"
@@ -10553,18 +10558,20 @@ fn render_doctor_help_json() -> serde_json::Value {
}
/// #683-#692: extract structured metadata from help prose
fn extract_help_metadata(
topic: LocalHelpTopic,
) -> (
Option<String>, // usage
Option<String>, // purpose
Option<String>, // output description
Option<Vec<String>>, // formats
Option<Vec<String>>, // related
Option<Vec<String>>, // aliases
bool, // local_only
bool, // requires_credentials
) {
/// Parsed fields of a help topic: usage, purpose, output description, formats,
/// related topics, aliases, local-only, requires-credentials.
type HelpMetadata = (
Option<String>,
Option<String>,
Option<String>,
Option<Vec<String>>,
Option<Vec<String>>,
Option<Vec<String>>,
bool,
bool,
);
fn extract_help_metadata(topic: LocalHelpTopic) -> HelpMetadata {
let text = render_help_topic(topic);
let mut usage = None;
let mut purpose = None;
@@ -13253,9 +13260,7 @@ fn format_context_window_blocked_error(session_id: &str, error: &api::ApiError)
}
api::ApiError::RetriesExhausted { last_error, .. } => {
let detail = match last_error.as_ref() {
api::ApiError::Api(details) => {
details.message.as_deref().unwrap_or(&details.body)
}
api::ApiError::Api(details) => details.message.as_deref().unwrap_or(&details.body),
other => return format_context_window_blocked_error(session_id, other),
}
.trim();
@@ -14273,39 +14278,37 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
let content = message
.blocks
.iter()
.filter_map(|block| match block {
ContentBlock::Text { text } => {
Some(InputContentBlock::Text { text: text.clone() })
}
.map(|block| match block {
ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
ContentBlock::Thinking {
thinking,
signature,
} => {
// 保留 Thinking 块:OpenAI 兼容协议会把它转成 reasoning_content 字段
// 回传给 DeepSeek V4(避免 400 "reasoning_content must be passed back" 错误)
Some(InputContentBlock::Thinking {
InputContentBlock::Thinking {
thinking: thinking.clone(),
signature: signature.clone(),
})
}
}
ContentBlock::ToolUse { id, name, input } => Some(InputContentBlock::ToolUse {
ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
id: id.clone(),
name: name.clone(),
input: serde_json::from_str(input)
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
}),
},
ContentBlock::ToolResult {
tool_use_id,
output,
is_error,
..
} => Some(InputContentBlock::ToolResult {
} => InputContentBlock::ToolResult {
tool_use_id: tool_use_id.clone(),
content: vec![ToolResultContentBlock::Text {
text: output.clone(),
}],
is_error: *is_error,
}),
},
})
.collect::<Vec<_>>();
(!content.is_empty()).then(|| InputMessage {
@@ -16178,10 +16181,7 @@ mod tests {
usage,
"workspace-write",
&context,
None,
None,
None,
None,
&super::StatusJsonExtras::default(),
);
assert_eq!(
json.get("status").and_then(|v| v.as_str()),
@@ -16253,10 +16253,10 @@ mod tests {
usage,
"workspace-write",
&context,
None,
None,
Some(&allowed),
None,
&super::StatusJsonExtras {
allowed_tools: Some(&allowed),
..super::StatusJsonExtras::default()
},
);
assert_eq!(
restricted_json
@@ -16286,10 +16286,7 @@ mod tests {
usage,
"workspace-write",
&clean_context,
None,
None,
None,
None,
&super::StatusJsonExtras::default(),
);
assert_eq!(
clean_json.get("status").and_then(|v| v.as_str()),
@@ -17237,7 +17234,7 @@ mod tests {
for action in ["remove", "uninstall", "delete"] {
assert_eq!(
parse_args(&["skills".to_string(), action.to_string()])
.expect(&format!("skills {action} should parse")),
.unwrap_or_else(|_| panic!("skills {action} should parse")),
CliAction::Skills {
args: Some(action.to_string()),
output_format: CliOutputFormat::Text,
@@ -18191,10 +18188,7 @@ mod tests {
},
"workspace-write",
&context,
None,
None,
None,
None,
&super::StatusJsonExtras::default(),
);
assert_eq!(
@@ -2,7 +2,6 @@ use std::io::{self, IsTerminal, Write};
use runtime::{save_user_provider_settings, ConfigLoader, RuntimeProviderConfig};
const PROVIDERS: &[(&str, &str, &str)] = &[
("1", "Anthropic", "anthropic"),
("2", "xAI / Grok", "xai"),