fix(#1375): clean up pedantic warnings and re-enable -D warnings without pedantic bypass

This commit is contained in:
damocles 2026-06-05 15:59:45 +02:00 committed by mara
commit fb726197ea
28 changed files with 109 additions and 90 deletions

View file

@ -301,6 +301,7 @@ pub(crate) async fn dispatch_shared(
})
}
#[allow(clippy::too_many_lines)]
async fn dispatch(req: &AgentRequest, agent: &str, coord: &Arc<Coordinator>) -> AgentResponse {
if let Some(resp) = dispatch_shared(req, agent, coord).await {
return resp;
@ -497,8 +498,7 @@ async fn dispatch(req: &AgentRequest, agent: &str, coord: &Arc<Coordinator>) ->
};
}
tracing::info!(%agent, %name, "agent: request_init_config for child");
match crate::manager_server::submit_init_config(coord, name, description.clone()).await
{
match crate::manager_server::submit_init_config(coord, name, description.clone()) {
Ok(_id) => AgentResponse::Ok,
Err(e) => AgentResponse::Err {
message: format!("{e:#}"),
@ -591,7 +591,7 @@ pub async fn dispatch_host_journal(
.await
{
Ok((stdout, stderr)) => {
let content = if !stdout.is_empty() { stdout } else { stderr };
let content = if stdout.is_empty() { stderr } else { stdout };
AgentResponse::HostJournal { content }
}
Err(e) => AgentResponse::Err {

View file

@ -210,7 +210,7 @@ pub fn topology_sort(
let mut queue: VecDeque<String> = VecDeque::new();
// Seed roots: entries with no parent, or names not present in topo at all.
for name in &name_set {
if topo.get(name).is_none_or(|p| p.is_none()) {
if topo.get(name).is_none_or(Option::is_none) {
depth.insert(name.clone(), 0);
queue.push_back(name.clone());
}

View file

@ -23,7 +23,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::coordinator::Coordinator;
const VACUUM_INTERVAL: Duration = Duration::from_secs(3600);
const VACUUM_INTERVAL: Duration = Duration::from_hours(1);
/// Keep completed task files for 48 hours before sweeping them.
const KEEP_SECS: i64 = 48 * 3600;
@ -101,7 +101,7 @@ fn should_delete(json_path: &Path, cutoff: i64) -> bool {
}
let completed_at = v
.get("completed_at")
.and_then(|t| t.as_i64())
.and_then(serde_json::Value::as_i64)
.unwrap_or(i64::MAX);
completed_at < cutoff
}

View file

@ -60,7 +60,7 @@ enum Cmd {
/// Gateway htpasswd user management. Add, remove, or list users in
/// an htpasswd file used by the gateway's HTTP Basic auth
/// (`services.hyperhive.gateway.auth`). Credentials are stored as
/// BCrypt hashes — no extra service or PAM required.
/// `BCrypt` hashes — no extra service or PAM required.
Gateway {
#[command(subcommand)]
cmd: GatewayCmd,
@ -179,7 +179,7 @@ enum MatrixCmd {
SyncAdmin,
/// Promote a matrix user to homeserver admin via the admin API.
/// Uses the hive system admin token at
/// `/var/lib/hyperhive/matrix-admin-token`. The server_name is
/// `/var/lib/hyperhive/matrix-admin-token`. The `server_name` is
/// discovered automatically from the running homeserver.
PromoteUser {
/// Matrix localpart of the user to promote (e.g. `argus`).
@ -205,7 +205,7 @@ const DEFAULT_HTPASSWD_FILE: &str = "/var/lib/hyperhive/gateway/gateway.htpasswd
#[derive(Subcommand)]
enum GatewayCmd {
/// Add a new user or update the password of an existing user in the
/// gateway htpasswd file. The password is hashed with BCrypt (cost 12).
/// gateway htpasswd file. The password is hashed with `BCrypt` (cost 12).
///
/// Pass `--password-stdin` when scripting or when you don't want the
/// password visible in shell history. The file is created if it does
@ -581,7 +581,7 @@ fn htpasswd_write(path: &Path, lines: &[String]) -> Result<()> {
}
/// Add or update `username` in the htpasswd file at `file`, hashing
/// `password` with BCrypt (cost 12). Creates the file when absent.
/// `password` with `BCrypt` (cost 12). Creates the file when absent.
fn gateway_create_user(
file: &Path,
username: &str,
@ -698,7 +698,7 @@ fn validate_htpasswd_username(username: &str) -> Result<()> {
if username.contains(':') {
bail!("username must not contain ':' (htpasswd field separator)");
}
if username.chars().any(|c| c.is_control()) {
if username.chars().any(char::is_control) {
bail!("username must not contain control characters");
}
Ok(())

View file

@ -118,11 +118,11 @@ fn read_harness_flags(name: &str) -> (bool, bool) {
{
let rl = v
.get("rate_limited")
.and_then(|x| x.as_bool())
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
let nl = v
.get("needs_login")
.and_then(|x| x.as_bool())
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
return (rl, nl);
}

View file

@ -433,7 +433,7 @@ impl Coordinator {
}
/// Emit a `ToolGroupsChanged` snapshot event. Called from the
/// rebuild-queue worker after a `PermChange` / ToolGroups entry
/// rebuild-queue worker after a `PermChange` / `ToolGroups` entry
/// commits the JSON file, so the P3RM1SS10NS tab updates live.
pub fn emit_tool_groups_snapshot(self: &Arc<Self>) {
use hive_sh4re::ToolGroup;

View file

@ -1432,8 +1432,7 @@ mod tests {
fn tmproot(tag: &str) -> std::path::PathBuf {
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
.map_or(0, |d| d.as_nanos());
let p = std::env::temp_dir().join(format!("hyperhive-test-{tag}-{ts}"));
std::fs::create_dir_all(&p).unwrap();
p

View file

@ -415,7 +415,7 @@ mod tests {
.get("kind")
.and_then(|k| k.as_str())
.expect("kind field present");
assert_eq!(ev.kind_tag(), serde_kind, "kind_tag() drift on {ev:?}",);
assert_eq!(ev.kind_tag(), serde_kind, "kind_tag() drift on {ev:?}");
}
}
}

View file

@ -228,9 +228,9 @@ pub async fn write(names: &[String]) -> Result<()> {
/// (gateway container temporarily down, systemd-run error) is
/// recovered automatically without requiring a new file write.
///
/// Backs off to one retry per [`RELOAD_RETRY_SECS`] after a failure so a
/// Backs off to one retry per `RELOAD_RETRY_SECS` after a failure so a
/// permanently broken gateway doesn't hammer `systemctl` on every tick.
/// A fresh `write()` call always resets the backoff (new RELOAD_PENDING
/// A fresh `write()` call always resets the backoff (new `RELOAD_PENDING`
/// set to `true` + immediate attempt) so topology changes are still
/// applied promptly.
pub async fn reload_if_pending() {

View file

@ -25,7 +25,7 @@ pub const LOCAL_DIR: &str = "/var/lib/hyperhive/knowledge";
pub const CONTAINER_MOUNT: &str = "/knowledge";
/// Default README pushed to a freshly created `internal/knowledge` repo.
/// Short explanation + empty ToC with an HTML comment instructing contributors
/// Short explanation + empty table-of-contents with an HTML comment instructing contributors
/// to add entries when they create new files.
const README_CONTENT: &str = "\
# knowledge
@ -114,10 +114,10 @@ async fn seed_readme(core_token: &str) -> Result<()> {
.args(["-C", LOCAL_DIR].iter().chain(args.iter()))
.output()
.await
.with_context(|| format!("git {:?}", args))?;
.with_context(|| format!("git {args:?}"))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_owned();
anyhow::bail!("git {:?} failed: {stderr}", args);
anyhow::bail!("git {args:?} failed: {stderr}");
}
}
let url = format!("http://core:{core_token}@localhost:3000/{ORG}/{REPO}.git");

View file

@ -1127,6 +1127,7 @@ fn bind_child_agent_dirs(child: &str, binds: &mut Vec<BindMount>) {
});
}
#[allow(clippy::too_many_lines)]
async fn set_nspawn_flags(
container: &str,
runtime_dir: &Path,
@ -1299,7 +1300,7 @@ async fn set_nspawn_flags(
/// Build the per-line callback for `create_container_streaming` /
/// `update_container_streaming`. Both ops share identical dispatch logic
/// (stdout → info + append_stdout, stderr → warn + append_stderr); this
/// (stdout → info + `append_stdout`, stderr → warn + `append_stderr`); this
/// helper avoids duplicating that match body across the two call sites.
fn make_log_callback(
logs: Option<std::sync::Arc<crate::build_logs::BuildLogs>>,
@ -1324,7 +1325,7 @@ fn make_log_callback(
}
/// Execute a container operation via hive-priv and integrate with
/// build_logs.sqlite. hive-priv runs as root and forwards output lines
/// `build_logs.sqlite`. hive-priv runs as root and forwards output lines
/// to hive-c0re in real time via the streaming priv protocol. Each line
/// is appended to the build-log row as it arrives, so the dashboard
/// shows live progress during long `nixos-container create` / `update` runs.

View file

@ -206,6 +206,7 @@ async fn main() -> Result<()> {
/// dashboard), then serve the admin socket until a signal arrives.
#[allow(
clippy::too_many_arguments,
clippy::too_many_lines,
reason = "the `serve` subcommand's args are the host-level config the daemon \
boots from (flakes, ports, pronouns, context-window + resource \
limits); they flow straight through to Coordinator::open"

View file

@ -83,7 +83,7 @@ async fn dispatch(req: &ManagerRequest, coord: &Arc<Coordinator>) -> ManagerResp
match req {
ManagerRequest::RequestInitConfig { name, description } => {
tracing::info!(%name, "manager: request_init_config");
match submit_init_config(coord, name, description.clone()).await {
match submit_init_config(coord, name, description.clone()) {
Ok(_id) => ManagerResponse::Ok,
Err(e) => ManagerResponse::Err {
message: format!("{e:#}"),
@ -245,7 +245,7 @@ async fn dispatch(req: &ManagerRequest, coord: &Arc<Coordinator>) -> ManagerResp
.await
{
Ok((stdout, stderr)) => {
let content = if !stdout.is_empty() { stdout } else { stderr };
let content = if stdout.is_empty() { stderr } else { stdout };
ManagerResponse::Logs { content }
}
Err(e) => ManagerResponse::Err {
@ -340,7 +340,7 @@ pub(crate) fn validate_commit_ref(commit_ref: &str) -> Result<()> {
/// Queue an `InitConfig` approval for a brand-new agent whose config repo
/// does not yet exist. Shared between the manager and agent sockets.
pub(crate) async fn submit_init_config(
pub(crate) fn submit_init_config(
coord: &Arc<Coordinator>,
name: &str,
description: Option<String>,

View file

@ -347,7 +347,7 @@ async fn discover_admin_room_id(
}
json["room_id"]
.as_str()
.map(|s| s.to_owned())
.map(ToString::to_string)
.ok_or_else(|| anyhow::anyhow!("matrix: admin room alias response missing room_id: {json}"))
}
@ -449,7 +449,7 @@ mod extract_new_password_tests {
///
/// Strategy: send the command, capture its `event_id`, then poll backwards
/// (`dir=b&limit=20`) on each tick. Events in a backward response are
/// newest-first; we walk the list until we find our own command event_id,
/// newest-first; we walk the list until we find our own command `event_id`,
/// then stop — everything before that marker in the list is a response that
/// arrived *after* our command. We check `body` and `formatted_body` of
/// every non-self message in that window.
@ -651,31 +651,30 @@ pub async fn ensure_user_for(
// Account already exists — try to re-login with the stored password.
tracing::info!(%name, "matrix: user already exists, attempting login with stored password");
let pw_path = password_path(name);
let stored = match std::fs::read_to_string(&pw_path)
let stored = if let Some(pw) = std::fs::read_to_string(&pw_path)
.ok()
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
{
Some(pw) => pw,
None => {
// Password file missing — attempt auto-recovery via admin API.
// This covers the case where agent state dirs were wiped but the
// homeserver still has the accounts. Requires the hive admin
// token at /var/lib/hyperhive/matrix-admin-token.
tracing::info!(
%name,
"matrix: stored password missing, attempting admin-API auto-recovery"
);
match auto_reset_password(client, name).await {
Ok(new_pw) => new_pw,
Err(e) => {
anyhow::bail!(
"matrix: user {name} already exists but password is missing \
pw
} else {
// Password file missing — attempt auto-recovery via admin API.
// This covers the case where agent state dirs were wiped but the
// homeserver still has the accounts. Requires the hive admin
// token at /var/lib/hyperhive/matrix-admin-token.
tracing::info!(
%name,
"matrix: stored password missing, attempting admin-API auto-recovery"
);
match auto_reset_password(client, name).await {
Ok(new_pw) => new_pw,
Err(e) => {
anyhow::bail!(
"matrix: user {name} already exists but password is missing \
and admin auto-recovery failed ({e:#}) run:\n\
hivectl matrix reset-password {name}\n\
hivectl matrix create-user {name}"
)
}
)
}
}
};
@ -783,7 +782,7 @@ pub async fn sync_agent_standalone(name: &str) {
/// non-empty. Does NOT promote the account via API (that requires
/// admin rights which this fn bootstraps); on a fresh homeserver the
/// first-registered rule fires automatically; on an existing homeserver
/// the operator must promote the account once via `hivectl matrix
/// the operator must promote the account once via
/// `hivectl matrix promote-user hive` or the conduit admin room.
pub async fn ensure_admin_user(client: &reqwest::Client, register_token: &str) -> Result<()> {
use std::os::unix::fs::PermissionsExt;

View file

@ -334,7 +334,7 @@ pub async fn lock_update_hyperhive() -> Result<()> {
/// Write the tool-groups file for `agent` and commit it atomically
/// under `META_LOCK`. Ensures the JSON change is staged + committed
/// before the next `prepare_deploy` or `sync_agents` runs, so the
/// working tree is never left dirty by an untimely PermChange write.
/// working tree is never left dirty by an untimely `PermChange` write.
pub async fn commit_tool_groups(agent: &str, groups: &[String]) -> Result<()> {
let _guard = META_LOCK.lock().await;
crate::tool_groups::set_groups(agent, groups)?;
@ -467,11 +467,7 @@ pub async fn bulk_commit_topology(
.iter()
.filter_map(|(child, new_parent)| {
let old = topo_before.get(*child).cloned().flatten();
if old.as_deref() != *new_parent {
Some((child.to_string(), old))
} else {
None
}
(old.as_deref() != *new_parent).then_some((child.to_string(), old))
})
.collect();
Ok(changed)

View file

@ -147,7 +147,7 @@ fn migrate_harness_files(name: &str) {
match std::fs::rename(&src, &dst) {
Ok(()) => tracing::info!(%name, %file, "migration: moved to harness dir"),
Err(e) => {
tracing::warn!(%name, %file, error = ?e, "migration: move to harness dir failed")
tracing::warn!(%name, %file, error = ?e, "migration: move to harness dir failed");
}
}
}

View file

@ -106,7 +106,7 @@ pub async fn update_container(name: &str) -> Result<(String, String)> {
/// Streaming variant: forward stdout/stderr lines to `on_line` as they
/// arrive. Returns `Ok(())` on success; the callback is responsible for
/// appending lines to build_logs or otherwise capturing the output.
/// appending lines to `build_logs` or otherwise capturing the output.
pub async fn update_container_streaming(
name: &str,
on_line: impl FnMut(PrivStream, &str),

View file

@ -1364,9 +1364,9 @@ mod tests {
assert!(!q.set_step(999, "anything"));
}
/// A MetaUpdate cascade Rebuild (with parent_id = Some(meta_id)) must
/// NOT dedup into a pre-existing Queued Rebuild with a different parent_id
/// (e.g. from a startup sweep). Without the parent_id dedup guard the
/// A `MetaUpdate` cascade `Rebuild` (with `parent_id` = `Some(meta_id)`) must
/// NOT dedup into a pre-existing `Queued` `Rebuild` with a different `parent_id`
/// (e.g. from a startup sweep). Without the `parent_id` dedup guard the
/// cascade rebuild would be swallowed and the agent would never rebuild
/// against the post-lock-bump meta.
#[test]

View file

@ -63,7 +63,7 @@ fn tick(coord: &Arc<Coordinator>) {
// Single-transaction batch: one DB lock acquisition for N reminders
// instead of N sequential lock/unlock cycles.
let results = coord.broker.deliver_reminders_batch(&items);
let any_delivered = results.iter().any(|r| r.is_ok());
let any_delivered = results.iter().any(Result::is_ok);
for ((id, agent, _body), result) in items.iter().zip(results.iter()) {
if let Err(e) = result {
let reason = format!("{e:#}");

View file

@ -666,7 +666,7 @@ mod tests {
let mut top = top_level_agents_in(&topo);
top.sort();
let mut expected = vec![crate::lifecycle::MANAGER_NAME, "orphan"];
expected.sort();
expected.sort_unstable();
assert_eq!(top, expected);
}