Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c238ffe1ff | ||
|
|
cc67a05974 | ||
|
|
cce35c20e6 |
17 changed files with 437 additions and 182 deletions
20
CLAUDE.md
20
CLAUDE.md
|
|
@ -25,13 +25,19 @@ hand-maintained per-file tree drifts out of sync with the code.
|
|||
### Rust workspace (`Cargo.toml` members)
|
||||
|
||||
- **`hive-c0re/`** — host daemon (runs as the unprivileged `hive-core`
|
||||
user) plus two operator CLIs. `src/main.rs` is the `hive-c0re` binary
|
||||
(serve / spawn / kill / rebuild / approve / destroy / periodic vacuum
|
||||
loops); `src/bin/hivectl.rs` is the ad-hoc operator admin CLI. Owns
|
||||
the sqlite broker, approval + question + reminder + schedule queues,
|
||||
the meta flake, lifecycle (`nixos-container` shellouts), gateway /
|
||||
forge / matrix provisioning, per-container stats, and the axum
|
||||
operator dashboard (`dashboard.rs`). Largest crate.
|
||||
user). `src/main.rs` is the `hive-c0re` binary — **daemon-only**
|
||||
(`serve` + the periodic vacuum/sweep loops); the operator CLI lives in
|
||||
the separate `hivectl` crate, which talks to the daemon over the host
|
||||
admin socket. Owns the sqlite broker, approval + question + reminder +
|
||||
schedule queues, the meta flake, lifecycle (`nixos-container`
|
||||
shellouts), gateway / forge / matrix provisioning, per-container stats,
|
||||
and the axum operator dashboard (`dashboard.rs`). Largest crate.
|
||||
- **`hivectl/`** — standalone operator CLI (`hivectl` binary). Talks to
|
||||
the `hive-c0re` daemon over the host admin socket (`hive-host-sock`
|
||||
wire types) — does NOT link `hive-c0re`. Verbs: `agents <spawn|kill|
|
||||
destroy|rebuild|restart|list|set-parent|…>`, `approvals <pending|
|
||||
approve|deny>`, `forge`/`matrix`/`github`/`gateway` provisioning,
|
||||
`choom`, `stop`/`start`, `wg`/`peer-config`.
|
||||
- **`hive-ag3nt/`** — in-container harness; three sibling binaries for
|
||||
every agent (`hive-agent` serve loop, `hive-agent-mcp`,
|
||||
`hive-agent-wake`). Turn-loop *policy* layer (`turn.rs`) over the `hive-claude`
|
||||
|
|
|
|||
17
Cargo.lock
generated
17
Cargo.lock
generated
|
|
@ -1665,6 +1665,23 @@ dependencies = [
|
|||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hivectl"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bcrypt",
|
||||
"clap",
|
||||
"clap-markdown",
|
||||
"clap_complete",
|
||||
"hive-host-sock",
|
||||
"hive-sh4re",
|
||||
"indicatif",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.12.4"
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ members = [
|
|||
"hive-priv",
|
||||
"hive-priv-sock",
|
||||
"hive-sh4re",
|
||||
"hivectl",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ above was spawned by `alice`), and the operator can reparent any agent. The
|
|||
bootstrap container (`ruth`) is just another root. Re-parenting is
|
||||
operator-driven:
|
||||
|
||||
- CLI: `hive-c0re set-parent <child> --parent <new>` (or `--root` to
|
||||
- CLI: `hivectl agents set-parent <child> --parent <new>` (or `--root` to
|
||||
promote). Exactly one of `--parent` / `--root` is required.
|
||||
- Dashboard: `POST /api/topology/set-parent` (form fields `child`,
|
||||
optional `new_parent` — absent / empty ⇒ promote to root).
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ request.
|
|||
3. The operator reviews the PR **on the forge** (native diff, threaded
|
||||
comments, CI status) and sees a matching card on the dashboard with a
|
||||
"review PR on forge" deep link. They click ◆ APPR0VE (or
|
||||
`hive-c0re approve <id>` on the CLI) once satisfied.
|
||||
`hivectl approvals approve <id>` on the CLI) once satisfied.
|
||||
4. On approve, `run_merge_config_pr`:
|
||||
- re-reads the live PR head and **aborts if it drifted** from the
|
||||
reviewed `fetched_sha` (the submitter must push again, which queues
|
||||
|
|
@ -110,7 +110,7 @@ kind-specific payload carrier.
|
|||
- `Spawn` — direct container creation from the agent's config repo.
|
||||
`commit_ref` is empty. Submitted via `HostRequest::RequestSpawn`
|
||||
(operator-gated, the `◆ R3QU3ST SP4WN` dashboard button +
|
||||
`hive-c0re request-spawn` CLI). The host-level `HostRequest::Spawn`
|
||||
`hivectl agents request-spawn` CLI). The host-level `HostRequest::Spawn`
|
||||
variant bypasses the approval queue entirely — privileged-context use
|
||||
only (operator on the host shell, test scripts, one-off recoveries).
|
||||
This is the **canonical first-spawn**: a new agent's `InitConfig`
|
||||
|
|
|
|||
|
|
@ -304,7 +304,7 @@ step would re-fire).
|
|||
`R3V1V3` queues a Spawn approval that reuses the kept state on
|
||||
approve (no re-login).
|
||||
- `PURG3` (opt-in via the dashboard button or
|
||||
`hive-c0re destroy --purge <name>`) — DESTR0Y plus wipes
|
||||
`hivectl agents destroy --purge <name>`) — DESTR0Y plus wipes
|
||||
`/var/lib/hyperhive/{agents,applied}/<name>/`. Config history,
|
||||
claude creds, /state/ notes, and the harness dir are all gone.
|
||||
No undo.
|
||||
|
|
|
|||
|
|
@ -23,6 +23,16 @@ This document contains the help content for the `hivectl` command-line program.
|
|||
* [`hivectl agents list`↴](#hivectl-agents-list)
|
||||
* [`hivectl agents restart`↴](#hivectl-agents-restart)
|
||||
* [`hivectl agents restart-all`↴](#hivectl-agents-restart-all)
|
||||
* [`hivectl agents spawn`↴](#hivectl-agents-spawn)
|
||||
* [`hivectl agents request-spawn`↴](#hivectl-agents-request-spawn)
|
||||
* [`hivectl agents kill`↴](#hivectl-agents-kill)
|
||||
* [`hivectl agents destroy`↴](#hivectl-agents-destroy)
|
||||
* [`hivectl agents rebuild`↴](#hivectl-agents-rebuild)
|
||||
* [`hivectl agents set-parent`↴](#hivectl-agents-set-parent)
|
||||
* [`hivectl approvals`↴](#hivectl-approvals)
|
||||
* [`hivectl approvals pending`↴](#hivectl-approvals-pending)
|
||||
* [`hivectl approvals approve`↴](#hivectl-approvals-approve)
|
||||
* [`hivectl approvals deny`↴](#hivectl-approvals-deny)
|
||||
* [`hivectl wg`↴](#hivectl-wg)
|
||||
* [`hivectl wg init`↴](#hivectl-wg-init)
|
||||
* [`hivectl wg peer`↴](#hivectl-wg-peer)
|
||||
|
|
@ -58,6 +68,7 @@ Sibling to the `hive-c0re` daemon binary. Covers host-side admin operations that
|
|||
* `github` — GitHub account provisioning: write an operator-supplied personal access token (PAT) into an agent's `github-token` state file so its `gh` wrapper + git credential helper can authenticate. Unlike forge/matrix there is no account creation — the operator supplies a PAT for an existing GitHub account. A CLI alternative to the dashboard credentials tab; the integration is on by default (`hyperhive.github.enable`), so no per-agent config is needed
|
||||
* `gateway` — 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
|
||||
* `agents` — Agent container management. Requires the hive-c0re daemon to be running (connects to the host admin socket)
|
||||
* `approvals` — Operator approval queue: list pending requests, approve / deny them. Requires the hive-c0re daemon to be running (connects to the host admin socket)
|
||||
* `wg` — WireGuard inter-hive mesh setup helpers (`services.hyperhive.swarm`)
|
||||
* `peer-config` — Generate the federation peer-config block for THIS hive — the nix a peer operator pastes into their `services.hyperhive.swarm.peers` to trust + reach this hive. Emits `caCert` (+ a `cp` line for the cert) when this hive serves a self-signed CA, the WireGuard public key when the mesh key exists, and the `wireguard{Address,Endpoint}` you pass. The hive's own domain is filled in automatically from the running daemon (`services.hyperhive.domain`). Reads local state (the TLS CA cert, the wg key); never mutates. `wg init` calls this at the end, so a fresh mesh setup prints the hand-over block too
|
||||
* `choom` — Open an interactive Claude session inside an agent container
|
||||
|
|
@ -309,6 +320,12 @@ Agent container management. Requires the hive-c0re daemon to be running (connect
|
|||
* `list` — Show all managed agents with their status (running / needs-login / needs-update) and technical state (deployed sha, parent, pending reminders). The host roster overview; reuses the dashboard's per-agent aggregation. Requires the daemon running
|
||||
* `restart` — Stop and start a single agent container without rebuilding config. Useful for "kick the container" when the process is stuck or the container needs a clean restart without changing the NixOS config. Rides the job queue (serialized against in-flight rebuilds for the same agent); waits with live progress unless `--no-wait`
|
||||
* `restart-all` — Restart ALL managed agent containers via one restart DAG each — unrelated agents overlap, each serializes on its own lease. Waits for the whole set with live progress unless `--no-wait`
|
||||
* `spawn` — Spawn a new agent container directly (`h-<name>`). Bypasses the approval queue — operator-on-the-host only. For approval-gated spawns, use `request-spawn`
|
||||
* `request-spawn` — Queue a spawn request as an approval. The container is created on `hivectl approvals approve <id>` (or the dashboard APPR0VE button)
|
||||
* `kill` — Stop a managed container (graceful)
|
||||
* `destroy` — Tear down a sub-agent container. The container is removed; persistent state (config repos + Claude credentials) is kept by default. Pass `--purge` to also wipe the agent's state dirs (config + creds + notes). No undo
|
||||
* `rebuild` — Apply pending config to a managed container
|
||||
* `set-parent` — Move an agent in the topology tree. Set `--parent` to a new parent agent name, or pass `--root` to promote the agent to root (no parent). Exactly one is required. Refuses cycles and unknown agents
|
||||
|
||||
|
||||
|
||||
|
|
@ -352,6 +369,133 @@ Restart ALL managed agent containers via one restart DAG each — unrelated agen
|
|||
|
||||
|
||||
|
||||
## `hivectl agents spawn`
|
||||
|
||||
Spawn a new agent container directly (`h-<name>`). Bypasses the approval queue — operator-on-the-host only. For approval-gated spawns, use `request-spawn`
|
||||
|
||||
**Usage:** `hivectl agents spawn <NAME>`
|
||||
|
||||
###### **Arguments:**
|
||||
|
||||
* `<NAME>` — Agent name (e.g. `iris`)
|
||||
|
||||
|
||||
|
||||
## `hivectl agents request-spawn`
|
||||
|
||||
Queue a spawn request as an approval. The container is created on `hivectl approvals approve <id>` (or the dashboard APPR0VE button)
|
||||
|
||||
**Usage:** `hivectl agents request-spawn <NAME>`
|
||||
|
||||
###### **Arguments:**
|
||||
|
||||
* `<NAME>` — Agent name
|
||||
|
||||
|
||||
|
||||
## `hivectl agents kill`
|
||||
|
||||
Stop a managed container (graceful)
|
||||
|
||||
**Usage:** `hivectl agents kill <NAME>`
|
||||
|
||||
###### **Arguments:**
|
||||
|
||||
* `<NAME>` — Agent name
|
||||
|
||||
|
||||
|
||||
## `hivectl agents destroy`
|
||||
|
||||
Tear down a sub-agent container. The container is removed; persistent state (config repos + Claude credentials) is kept by default. Pass `--purge` to also wipe the agent's state dirs (config + creds + notes). No undo
|
||||
|
||||
**Usage:** `hivectl agents destroy [OPTIONS] <NAME>`
|
||||
|
||||
###### **Arguments:**
|
||||
|
||||
* `<NAME>` — Agent name
|
||||
|
||||
###### **Options:**
|
||||
|
||||
* `--purge`
|
||||
|
||||
|
||||
|
||||
## `hivectl agents rebuild`
|
||||
|
||||
Apply pending config to a managed container
|
||||
|
||||
**Usage:** `hivectl agents rebuild <NAME>`
|
||||
|
||||
###### **Arguments:**
|
||||
|
||||
* `<NAME>` — Agent name
|
||||
|
||||
|
||||
|
||||
## `hivectl agents set-parent`
|
||||
|
||||
Move an agent in the topology tree. Set `--parent` to a new parent agent name, or pass `--root` to promote the agent to root (no parent). Exactly one is required. Refuses cycles and unknown agents
|
||||
|
||||
**Usage:** `hivectl agents set-parent [OPTIONS] <CHILD>`
|
||||
|
||||
###### **Arguments:**
|
||||
|
||||
* `<CHILD>` — Agent to move
|
||||
|
||||
###### **Options:**
|
||||
|
||||
* `--parent <PARENT>` — New parent agent name. Mutually exclusive with `--root`
|
||||
* `--root` — Promote `child` to root (no parent)
|
||||
|
||||
|
||||
|
||||
## `hivectl approvals`
|
||||
|
||||
Operator approval queue: list pending requests, approve / deny them. Requires the hive-c0re daemon to be running (connects to the host admin socket)
|
||||
|
||||
**Usage:** `hivectl approvals <COMMAND>`
|
||||
|
||||
###### **Subcommands:**
|
||||
|
||||
* `pending` — List pending approval requests submitted by agents
|
||||
* `approve` — Approve a pending request by id; the action runs immediately
|
||||
* `deny` — Deny a pending request by id
|
||||
|
||||
|
||||
|
||||
## `hivectl approvals pending`
|
||||
|
||||
List pending approval requests submitted by agents
|
||||
|
||||
**Usage:** `hivectl approvals pending`
|
||||
|
||||
|
||||
|
||||
## `hivectl approvals approve`
|
||||
|
||||
Approve a pending request by id; the action runs immediately
|
||||
|
||||
**Usage:** `hivectl approvals approve <ID>`
|
||||
|
||||
###### **Arguments:**
|
||||
|
||||
* `<ID>` — Approval id (from `hivectl approvals pending`)
|
||||
|
||||
|
||||
|
||||
## `hivectl approvals deny`
|
||||
|
||||
Deny a pending request by id
|
||||
|
||||
**Usage:** `hivectl approvals deny <ID>`
|
||||
|
||||
###### **Arguments:**
|
||||
|
||||
* `<ID>` — Approval id
|
||||
|
||||
|
||||
|
||||
## `hivectl wg`
|
||||
|
||||
WireGuard inter-hive mesh setup helpers (`services.hyperhive.swarm`).
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
//! `hive-c0re` library — module surface shared by the `hive-c0re`
|
||||
//! daemon binary and the `hivectl` operator CLI.
|
||||
//! `hive-c0re` library — the coordinator daemon's module surface
|
||||
//! (coordinator, broker, axum dashboard, admin/manager/agent unix
|
||||
//! sockets, background sweepers). Consumed by the `hive-c0re` daemon
|
||||
//! binary (`src/main.rs`).
|
||||
//!
|
||||
//! `hive-c0re` (daemon) keeps the systemd service shape it always had:
|
||||
//! coordinator, broker, axum dashboard, admin/manager/agent unix
|
||||
//! sockets, background sweepers. `hivectl` (sibling bin under
|
||||
//! `src/bin/hivectl.rs`) reuses a thin subset (`forge`, `matrix`,
|
||||
//! `lifecycle`) to expose host-side administration verbs — manually
|
||||
//! provisioning forge / matrix users for an agent, etc.
|
||||
//! The operator CLI lives in the **standalone `hivectl` crate**, which
|
||||
//! talks to the daemon over the host admin socket (`hive-host-sock` wire
|
||||
//! types) rather than linking this crate — so `hive-c0re` is daemon-only,
|
||||
//! not a library shared with a CLI.
|
||||
//!
|
||||
//! Every module is re-exported `pub` so anything in the crate is
|
||||
//! addressable from either binary; the lib doesn't have a curated
|
||||
//! addressable from the daemon binary; the lib doesn't have a curated
|
||||
//! surface beyond "this is where the modules live".
|
||||
//!
|
||||
//! Cohesive clusters live in directory submodules (`stores`, `stats`,
|
||||
|
|
@ -19,7 +19,6 @@
|
|||
|
||||
pub mod actions;
|
||||
pub mod agent_config;
|
||||
pub mod client;
|
||||
pub mod container_view;
|
||||
pub mod coordinator;
|
||||
pub mod dashboard;
|
||||
|
|
|
|||
|
|
@ -25,10 +25,14 @@ use tokio::process::Command;
|
|||
|
||||
use crate::coordinator::{AgentPaths, HiveEnv};
|
||||
|
||||
/// Sub-agent container prefix. `nixos-container` caps the total container name
|
||||
/// at 11 chars (it gets encoded into network interface names), so the agent
|
||||
/// name itself can be at most `MAX_AGENT_NAME` chars.
|
||||
pub const AGENT_PREFIX: &str = "h-";
|
||||
// `AGENT_PREFIX` (`h-`) + `container_name` are shared with the host-side
|
||||
// `hivectl` CLI, so they live in `hive-host-sock`; re-exported here so this
|
||||
// module stays the daemon's facade for its own callsites.
|
||||
pub use hive_host_sock::{AGENT_PREFIX, container_name};
|
||||
|
||||
/// Max agent-name length. `nixos-container` caps the total container name at
|
||||
/// 11 chars (it gets encoded into network interface names) and `AGENT_PREFIX`
|
||||
/// (`h-`) takes 2, so the agent name itself is at most `MAX_AGENT_NAME` chars.
|
||||
pub const MAX_AGENT_NAME: usize = 9;
|
||||
/// Logical name of the manager agent (broker recipient, state-dir key,
|
||||
/// meta flake attribute). All persistent state lives under `ruth/`.
|
||||
|
|
@ -124,11 +128,6 @@ pub fn bridge_gateway_ip(subnet_cidr: &str) -> Option<String> {
|
|||
Some(ip_str.to_owned())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn container_name(name: &str) -> String {
|
||||
format!("{AGENT_PREFIX}{name}")
|
||||
}
|
||||
|
||||
/// Read the agent user's `(uid, gid)` from the container's nixos-managed
|
||||
/// `/etc/passwd`. Returns `None` when the container hasn't been built
|
||||
/// yet, the passwd file is unparseable, or the agent user is missing
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use anyhow::{Context as _, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
use hive_host_sock::{HostRequest, HostResponse};
|
||||
|
||||
// Every module hangs off the `hive_c0re` library (see `src/lib.rs`).
|
||||
// The daemon and the `hivectl` sibling binary share the same module
|
||||
|
|
@ -12,7 +11,7 @@ use hive_host_sock::{HostRequest, HostResponse};
|
|||
// explicit (any new daemon entry point reads off the next add).
|
||||
use hive_c0re::coordinator::{Coordinator, HiveEnv, ServeConfig};
|
||||
use hive_c0re::{
|
||||
agent_sockets, auto_update, broker, client, crash_watch, dashboard, dashboard_events, forge,
|
||||
agent_sockets, auto_update, broker, crash_watch, dashboard, dashboard_events, forge,
|
||||
host_stats, job_queue, knowledge, matrix, mcp_sockets, migrate, reminder_scheduler,
|
||||
scheduled_prompts_worker, server, socket_server, sweep_health, warnings,
|
||||
};
|
||||
|
|
@ -91,52 +90,6 @@ enum Cmd {
|
|||
#[arg(long)]
|
||||
build_slots: Option<usize>,
|
||||
},
|
||||
/// Spawn a new agent container directly (`hive-agent-<name>`). Bypasses
|
||||
/// the approval queue — use only as an operator on the host. For
|
||||
/// approval-gated spawns, use `request-spawn` instead.
|
||||
Spawn { name: String },
|
||||
/// Queue a spawn request as an approval. The container is created on
|
||||
/// `approve <id>` (CLI) or the dashboard's APPR0VE button.
|
||||
RequestSpawn { name: String },
|
||||
/// Stop a managed container (graceful).
|
||||
Kill { name: String },
|
||||
/// Tear down a sub-agent container. Container is removed; persistent
|
||||
/// state (config repos + Claude credentials) is kept by default. Pass
|
||||
/// `--purge` to also wipe the agent's state dirs (config + creds +
|
||||
/// notes). No undo.
|
||||
Destroy {
|
||||
name: String,
|
||||
#[arg(long)]
|
||||
purge: bool,
|
||||
},
|
||||
/// Apply pending config to a managed container.
|
||||
Rebuild { name: String },
|
||||
/// List managed containers.
|
||||
List,
|
||||
/// List pending approval requests submitted by the manager.
|
||||
Pending,
|
||||
/// Approve a pending request by id; the action runs immediately.
|
||||
Approve { id: i64 },
|
||||
/// Deny a pending request by id.
|
||||
Deny { id: i64 },
|
||||
/// Move an agent in the topology tree. Set `--parent` to a new
|
||||
/// parent agent name; pass `--root` to promote the agent to root
|
||||
/// (no parent). Refuses cycles and unknown agents. The manager
|
||||
/// is reparentable like any other agent — its privileges come
|
||||
/// from the privileged MCP socket, not its tree position.
|
||||
SetParent {
|
||||
child: String,
|
||||
/// New parent agent name. Mutually exclusive with `--root`.
|
||||
/// Exactly one of `--parent` / `--root` is required — clap
|
||||
/// rejects both-absent calls so a fat-fingered
|
||||
/// `hive-c0re set-parent alice` doesn't silently promote
|
||||
/// alice to root.
|
||||
#[arg(long, conflicts_with = "root", required_unless_present = "root")]
|
||||
parent: Option<String>,
|
||||
/// Promote `child` to root (no parent).
|
||||
#[arg(long)]
|
||||
root: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
|
|
@ -206,37 +159,6 @@ async fn main() -> Result<()> {
|
|||
}
|
||||
cmd_serve(sc.env, sc.model_prices, sc.build_slots, db, &cli.socket).await
|
||||
}
|
||||
Cmd::Spawn { name } => {
|
||||
render(client::request(&cli.socket, HostRequest::Spawn { name }).await?)
|
||||
}
|
||||
Cmd::RequestSpawn { name } => {
|
||||
render(client::request(&cli.socket, HostRequest::RequestSpawn { name }).await?)
|
||||
}
|
||||
Cmd::Kill { name } => {
|
||||
render(client::request(&cli.socket, HostRequest::Kill { name }).await?)
|
||||
}
|
||||
Cmd::Destroy { name, purge } => {
|
||||
render(client::request(&cli.socket, HostRequest::Destroy { name, purge }).await?)
|
||||
}
|
||||
Cmd::Rebuild { name } => {
|
||||
render(client::request(&cli.socket, HostRequest::Rebuild { name }).await?)
|
||||
}
|
||||
Cmd::List => render(client::request(&cli.socket, HostRequest::List).await?),
|
||||
Cmd::Pending => render(client::request(&cli.socket, HostRequest::Pending).await?),
|
||||
Cmd::Approve { id } => {
|
||||
render(client::request(&cli.socket, HostRequest::Approve { id }).await?)
|
||||
}
|
||||
Cmd::Deny { id } => render(client::request(&cli.socket, HostRequest::Deny { id }).await?),
|
||||
Cmd::SetParent {
|
||||
child,
|
||||
parent,
|
||||
root,
|
||||
} => {
|
||||
let new_parent = if root { None } else { parent };
|
||||
render(
|
||||
client::request(&cli.socket, HostRequest::SetParent { child, new_parent }).await?,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -648,11 +570,3 @@ fn spawn_broker_to_dashboard_forwarder(coord: Arc<Coordinator>) {
|
|||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn render(resp: HostResponse) -> Result<()> {
|
||||
println!("{}", serde_json::to_string_pretty(&resp)?);
|
||||
if !resp.ok {
|
||||
bail!(resp.error.unwrap_or_else(|| "request failed".to_owned()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,6 +24,12 @@
|
|||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// Layout facts shared with the host-side `hivectl` CLI live in
|
||||
// `hive-host-sock` (the crate hivectl links instead of the whole daemon);
|
||||
// re-exported here so this module stays the daemon's single-source facade for
|
||||
// its own callsites.
|
||||
pub use hive_host_sock::{AGENTS_ROOT, GATEWAY_HTPASSWD, HOST_SOCKET, agent_state_dir};
|
||||
|
||||
/// Root of all hive-c0re persistent state.
|
||||
// nix: bind-mount source `services.hyperhive.c0re.statePath` (hive-c0re.nix) — must match.
|
||||
pub const STATE_ROOT: &str = "/var/lib/hyperhive";
|
||||
|
|
@ -35,11 +41,6 @@ pub const STATE_ROOT: &str = "/var/lib/hyperhive";
|
|||
// stay in sync; the privsep boundary prevents importing across the crate.
|
||||
pub const RUNTIME_ROOT: &str = "/run/hyperhive";
|
||||
|
||||
/// Default host admin socket (`/run/hyperhive/host.sock`). Exposed as a
|
||||
/// `&str` for the `--socket` / `--host-socket` clap `default_value` in
|
||||
/// `main.rs` (hive-c0re) and `bin/hivectl.rs`.
|
||||
pub const HOST_SOCKET: &str = "/run/hyperhive/host.sock";
|
||||
|
||||
/// `/run/hive-agent` — per-agent runtime socket dir root (web + bound
|
||||
/// markers), one subdir per agent.
|
||||
// nix: agent container bind-mount / `RuntimeDirectory` (the harness nix modules) — must match.
|
||||
|
|
@ -158,26 +159,12 @@ pub fn agent_sockets_file() -> PathBuf {
|
|||
// single Rust-side source.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `agents/` — per-agent persistent state root (one subdir per agent,
|
||||
/// bind-mounted into each container as `/agents/<name>`). A `&str` (the
|
||||
/// dashboard state-file allow-list uses it for `strip_prefix` /
|
||||
/// `starts_with` checks), so it stays a const; [`agents_root`] wraps it.
|
||||
// nix: agent container bind-mount source (harness modules / agent.nix template) — must match.
|
||||
// priv-sock: `hive_priv_sock::AGENT_STATE_ROOT` is the same value and must stay in sync;
|
||||
// the privsep boundary prevents importing across the crate.
|
||||
pub const AGENTS_ROOT: &str = "/var/lib/hyperhive/agents";
|
||||
|
||||
/// `agents/` root (`AGENTS_ROOT`) as an owned `PathBuf`.
|
||||
#[must_use]
|
||||
pub fn agents_root() -> PathBuf {
|
||||
PathBuf::from(AGENTS_ROOT)
|
||||
}
|
||||
|
||||
/// `agents/<name>` — one agent's persistent state root.
|
||||
#[must_use]
|
||||
pub fn agent_state_dir(name: &str) -> PathBuf {
|
||||
agents_root().join(name)
|
||||
}
|
||||
|
||||
/// `applied/` — per-agent *applied* (deployed) config repos + rev markers,
|
||||
/// distinct from the proposed configs under `agents/<name>/config`.
|
||||
// nix: read by hive-c0re only, but paired with `agents/` in the deploy flow.
|
||||
|
|
@ -253,12 +240,6 @@ pub fn gateway_agents_conf() -> PathBuf {
|
|||
gateway_dir().join("agents.conf")
|
||||
}
|
||||
|
||||
/// `gateway/gateway.htpasswd` — nginx basic-auth credential store for the
|
||||
/// operator dashboard vhost. A `&str` (used as a `hivectl` clap
|
||||
/// `default_value`), so it stays a const rather than a `PathBuf` fn.
|
||||
// nix: read by the gateway container's nginx (hive-gateway.nix) — must match.
|
||||
pub const GATEWAY_HTPASSWD: &str = "/var/lib/hyperhive/gateway/gateway.htpasswd";
|
||||
|
||||
/// `forge-core-token` — the hive-c0re forge account API token. A `&str`
|
||||
/// (used in `Path::new` + user-facing `format!` messages), so it stays a
|
||||
/// const rather than a `PathBuf` fn.
|
||||
|
|
|
|||
|
|
@ -6,9 +6,51 @@
|
|||
//! payload types it references (`Approval`, `AgentStatusRow`, `jobs::DagView`)
|
||||
//! stay in `hive-sh4re`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use hive_sh4re::{AgentStatusRow, Approval, jobs};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// ── Shared hive layout facts ──────────────────────────────────────────────
|
||||
// Paths + names both the `hive-c0re` daemon and the host-side `hivectl` CLI
|
||||
// must agree on. Homed here (the protocol crate both sides already depend on)
|
||||
// so a standalone `hivectl` can reach them without linking the whole daemon
|
||||
// crate. `hive-c0re`'s `paths` / `lifecycle` modules re-export these, staying
|
||||
// the daemon's single-source facade for its own callsites.
|
||||
|
||||
/// Default host admin socket (`/run/hyperhive/host.sock`). Used as the
|
||||
/// `--socket` / `--host-socket` clap `default_value` in the daemon and
|
||||
/// `hivectl`.
|
||||
pub const HOST_SOCKET: &str = "/run/hyperhive/host.sock";
|
||||
|
||||
/// `agents/` — per-agent persistent state root (one subdir per agent,
|
||||
/// bind-mounted into each container as `/agents/<name>`).
|
||||
// nix: agent container bind-mount source (harness modules / agent.nix template) — must match.
|
||||
// priv-sock: `hive_priv_sock::AGENT_STATE_ROOT` is the same value and must stay in sync;
|
||||
// the privsep boundary prevents importing across the crate.
|
||||
pub const AGENTS_ROOT: &str = "/var/lib/hyperhive/agents";
|
||||
|
||||
/// `agents/<name>` — one agent's persistent state root.
|
||||
#[must_use]
|
||||
pub fn agent_state_dir(name: &str) -> PathBuf {
|
||||
PathBuf::from(AGENTS_ROOT).join(name)
|
||||
}
|
||||
|
||||
/// `gateway/gateway.htpasswd` — nginx basic-auth credential store for the
|
||||
/// operator dashboard vhost. `hivectl`'s `--htpasswd-file` clap default.
|
||||
// nix: read by the gateway container's nginx (hive-gateway.nix) — must match.
|
||||
pub const GATEWAY_HTPASSWD: &str = "/var/lib/hyperhive/gateway/gateway.htpasswd";
|
||||
|
||||
/// nspawn machine-name prefix for agent containers (`h-<name>`). A single
|
||||
/// `starts_with(AGENT_PREFIX)` filter enumerates managed containers.
|
||||
pub const AGENT_PREFIX: &str = "h-";
|
||||
|
||||
/// Map an agent's logical name to its nspawn machine name (`h-<name>`).
|
||||
#[must_use]
|
||||
pub fn container_name(name: &str) -> String {
|
||||
format!("{AGENT_PREFIX}{name}")
|
||||
}
|
||||
|
||||
/// Requests on the host admin socket.
|
||||
///
|
||||
/// Wire format: one JSON object per line.
|
||||
|
|
|
|||
24
hivectl/Cargo.toml
Normal file
24
hivectl/Cargo.toml
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
[package]
|
||||
name = "hivectl"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "hivectl"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
bcrypt.workspace = true
|
||||
clap.workspace = true
|
||||
clap_complete.workspace = true
|
||||
clap-markdown = "0.1"
|
||||
hive-host-sock.workspace = true
|
||||
hive-sh4re.workspace = true
|
||||
indicatif.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
27
hivectl/src/client.rs
Normal file
27
hivectl/src/client.rs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use hive_host_sock::{HostRequest, HostResponse};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
pub async fn request(socket: &Path, req: HostRequest) -> Result<HostResponse> {
|
||||
let stream = UnixStream::connect(socket)
|
||||
.await
|
||||
.with_context(|| format!("connect to {}", socket.display()))?;
|
||||
let (read, mut write) = stream.into_split();
|
||||
|
||||
let mut payload = serde_json::to_string(&req)?;
|
||||
payload.push('\n');
|
||||
write.write_all(payload.as_bytes()).await?;
|
||||
write.flush().await?;
|
||||
|
||||
let mut reader = BufReader::new(read);
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).await?;
|
||||
if line.is_empty() {
|
||||
bail!("server closed connection without responding");
|
||||
}
|
||||
let resp: HostResponse = serde_json::from_str(line.trim())?;
|
||||
Ok(resp)
|
||||
}
|
||||
402
hivectl/src/dag_progress.rs
Normal file
402
hivectl/src/dag_progress.rs
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
//! `hivectl` rebuild-queue progress rendering.
|
||||
//!
|
||||
//! Split out of `hivectl.rs` (which is already large): everything that
|
||||
//! polls the daemon's DAG queue (`HostRequest::QueueDag`) and renders the
|
||||
//! per-DAG / per-node progress lives here. [`wait_for_dags`] is the entry
|
||||
//! point the command handlers call; it dispatches to a live `indicatif`
|
||||
//! animation on a TTY and a plain line-on-change stream otherwise.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
|
||||
/// Poll the submitted DAG ids (`HostRequest::QueueDag`, ~1s interval) and
|
||||
/// render progress until they all reach a terminal state. Exits non-zero
|
||||
/// (via the returned `Err`) when any DAG (or fan-out child) ends `failed`;
|
||||
/// a `cancelled` DAG terminates the wait but is an operator action, not an
|
||||
/// error.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the daemon socket can't be reached, or if any polled
|
||||
/// DAG finished in the `failed` state.
|
||||
pub(crate) async fn wait_for_dags(socket: &Path, ids: Vec<u64>, no_wait: bool) -> Result<()> {
|
||||
use std::io::IsTerminal as _;
|
||||
if no_wait || ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// Animate only on a real terminal. Piped / CI output falls back to the
|
||||
// plain line-on-change stream so logs stay free of spinner redraw noise.
|
||||
if std::io::stderr().is_terminal() {
|
||||
wait_for_dags_animated(socket, ids).await
|
||||
} else {
|
||||
wait_for_dags_plain(socket, ids).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-TTY progress: print a fresh line whenever a DAG's rendered state
|
||||
/// changes. No cursor tricks, so it's clean in pipes and CI logs.
|
||||
async fn wait_for_dags_plain(socket: &Path, ids: Vec<u64>) -> Result<()> {
|
||||
let mut pending: std::collections::BTreeSet<u64> = ids.into_iter().collect();
|
||||
let mut last: std::collections::HashMap<u64, String> = std::collections::HashMap::new();
|
||||
let mut failed: Vec<String> = Vec::new();
|
||||
while !pending.is_empty() {
|
||||
for id in pending.clone() {
|
||||
let resp = crate::client::request(socket, hive_host_sock::HostRequest::QueueDag { id })
|
||||
.await
|
||||
.with_context(|| format!("connect to daemon socket {}", socket.display()))?;
|
||||
let dags = resp.dags.unwrap_or_default();
|
||||
if dags.is_empty() {
|
||||
// Evicted from the queue's history tail — it finished a
|
||||
// while ago; nothing left to report on.
|
||||
println!("job #{id}: gone from queue history");
|
||||
pending.remove(&id);
|
||||
continue;
|
||||
}
|
||||
let mut all_terminal = true;
|
||||
for d in &dags {
|
||||
let line = render_dag_line(d);
|
||||
if last.get(&d.id) != Some(&line) {
|
||||
println!("{line}");
|
||||
last.insert(d.id, line);
|
||||
}
|
||||
// Node-level terminality, not the roll-up: a DAG rolls
|
||||
// up `failed` the moment one node fails while its
|
||||
// after-any recovery node (rebuild's tail Reconcile)
|
||||
// may still be running — keep watching so the operator
|
||||
// sees whether the agent came back.
|
||||
if d.nodes.iter().all(|n| n.state.is_terminal()) {
|
||||
if d.state == hive_sh4re::jobs::State::Failed {
|
||||
failed.push(format!("{} {}", d.kind.as_str(), dag_agents(d)));
|
||||
}
|
||||
} else {
|
||||
all_terminal = false;
|
||||
}
|
||||
}
|
||||
if all_terminal {
|
||||
pending.remove(&id);
|
||||
}
|
||||
}
|
||||
if !pending.is_empty() {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
finish_wait(failed)
|
||||
}
|
||||
|
||||
/// TTY progress: a live `indicatif` render — one braille-spinner line per
|
||||
/// DAG node (grouped under a per-DAG header), each with its own elapsed
|
||||
/// timer, plus an overall-elapsed footer. A node with more than one
|
||||
/// dependency (fan-in) gets its own row with an `(after …)` marker rather
|
||||
/// than being crammed onto a chain line.
|
||||
async fn wait_for_dags_animated(socket: &Path, ids: Vec<u64>) -> Result<()> {
|
||||
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
|
||||
|
||||
let spinner = ProgressStyle::with_template(" {spinner} {msg}")
|
||||
.unwrap_or_else(|_| ProgressStyle::default_spinner())
|
||||
.tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏", "·"]);
|
||||
let plain =
|
||||
ProgressStyle::with_template("{msg}").unwrap_or_else(|_| ProgressStyle::default_bar());
|
||||
|
||||
let mp = MultiProgress::new();
|
||||
let started = std::time::Instant::now();
|
||||
// Per-DAG header bars + per-node bars, keyed so we update in place. The
|
||||
// insertion order groups a DAG's nodes right under its header.
|
||||
let mut dag_bars: std::collections::HashMap<u64, ProgressBar> =
|
||||
std::collections::HashMap::new();
|
||||
let mut node_bars: std::collections::HashMap<(u64, hive_sh4re::jobs::NodeId), ProgressBar> =
|
||||
std::collections::HashMap::new();
|
||||
let mut node_done: std::collections::HashSet<(u64, hive_sh4re::jobs::NodeId)> =
|
||||
std::collections::HashSet::new();
|
||||
|
||||
let mut pending: std::collections::BTreeSet<u64> = ids.into_iter().collect();
|
||||
let mut failed: Vec<String> = Vec::new();
|
||||
|
||||
while !pending.is_empty() {
|
||||
let now = now_unix();
|
||||
for id in pending.clone() {
|
||||
let resp = crate::client::request(socket, hive_host_sock::HostRequest::QueueDag { id })
|
||||
.await
|
||||
.with_context(|| format!("connect to daemon socket {}", socket.display()))?;
|
||||
let dags = resp.dags.unwrap_or_default();
|
||||
if dags.is_empty() {
|
||||
mp.println(format!("job #{id}: gone from queue history"))
|
||||
.ok();
|
||||
pending.remove(&id);
|
||||
continue;
|
||||
}
|
||||
let mut all_terminal = true;
|
||||
for d in &dags {
|
||||
let hdr = dag_bars.entry(d.id).or_insert_with(|| {
|
||||
let b = mp.add(ProgressBar::new_spinner());
|
||||
b.set_style(plain.clone());
|
||||
b
|
||||
});
|
||||
hdr.set_message(format!(
|
||||
"{} {} {} · {}",
|
||||
state_glyph(d.state),
|
||||
d.kind.as_str(),
|
||||
dag_agents(d),
|
||||
fmt_dur(dag_elapsed(d, now)),
|
||||
));
|
||||
for n in &d.nodes {
|
||||
let key = (d.id, n.id);
|
||||
if node_done.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
let bar = node_bars.entry(key).or_insert_with(|| {
|
||||
let b = mp.add(ProgressBar::new_spinner());
|
||||
b.set_style(spinner.clone());
|
||||
b.enable_steady_tick(std::time::Duration::from_millis(120));
|
||||
b
|
||||
});
|
||||
if n.state.is_terminal() {
|
||||
bar.set_style(plain.clone());
|
||||
bar.finish_with_message(format!(
|
||||
" {} {}",
|
||||
state_glyph(n.state),
|
||||
node_line(d, n, now)
|
||||
));
|
||||
node_done.insert(key);
|
||||
} else {
|
||||
bar.set_message(node_line(d, n, now));
|
||||
}
|
||||
}
|
||||
if d.nodes.iter().all(|n| n.state.is_terminal()) {
|
||||
if d.state == hive_sh4re::jobs::State::Failed {
|
||||
failed.push(format!("{} {}", d.kind.as_str(), dag_agents(d)));
|
||||
}
|
||||
} else {
|
||||
all_terminal = false;
|
||||
}
|
||||
}
|
||||
if all_terminal {
|
||||
pending.remove(&id);
|
||||
}
|
||||
}
|
||||
if !pending.is_empty() {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
// Leave the final node lines on screen; drop the still-spinning headers
|
||||
// into their terminal state and print an overall-elapsed footer.
|
||||
for hdr in dag_bars.values() {
|
||||
hdr.finish();
|
||||
}
|
||||
mp.println(format!(
|
||||
"done · {} elapsed",
|
||||
fmt_dur(started.elapsed().as_secs().try_into().unwrap_or(0))
|
||||
))
|
||||
.ok();
|
||||
finish_wait(failed)
|
||||
}
|
||||
|
||||
/// Shared tail: succeed when nothing failed, else bail listing the failures.
|
||||
fn finish_wait(mut failed: Vec<String>) -> Result<()> {
|
||||
if failed.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
failed.sort();
|
||||
failed.dedup();
|
||||
bail!("queued job(s) failed: {}", failed.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
/// Distinct agents across a DAG's nodes, comma-joined for display — the
|
||||
/// per-node replacement for the old DAG-level `agent` field. Single-agent
|
||||
/// DAGs render one name; a hive-wide DAG lists each.
|
||||
fn dag_agents(d: &hive_sh4re::jobs::DagView) -> String {
|
||||
let mut seen: Vec<&str> = Vec::new();
|
||||
for n in &d.nodes {
|
||||
if !seen.contains(&n.agent.as_str()) {
|
||||
seen.push(&n.agent);
|
||||
}
|
||||
}
|
||||
seen.join(",")
|
||||
}
|
||||
|
||||
/// Current unix time in seconds (0 on the impossible pre-epoch error).
|
||||
fn now_unix() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.ok()
|
||||
.and_then(|d| i64::try_from(d.as_secs()).ok())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Elapsed seconds for a DAG: `started_at` (falling back to `enqueued_at`)
|
||||
/// through `finished_at` or `now`.
|
||||
fn dag_elapsed(d: &hive_sh4re::jobs::DagView, now: i64) -> i64 {
|
||||
let start = d.started_at.unwrap_or(d.enqueued_at);
|
||||
(d.finished_at.unwrap_or(now) - start).max(0)
|
||||
}
|
||||
|
||||
/// Elapsed seconds for a node: `started_at` → `finished_at`/`now`, or 0
|
||||
/// when it hasn't started.
|
||||
fn node_elapsed(n: &hive_sh4re::jobs::NodeView, now: i64) -> i64 {
|
||||
match n.started_at {
|
||||
Some(start) => (n.finished_at.unwrap_or(now) - start).max(0),
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Compact duration: `45s` under a minute, else `1m03s`.
|
||||
fn fmt_dur(secs: i64) -> String {
|
||||
let s = secs.max(0);
|
||||
if s < 60 {
|
||||
format!("{s}s")
|
||||
} else {
|
||||
format!("{}m{:02}s", s / 60, s % 60)
|
||||
}
|
||||
}
|
||||
|
||||
/// One animated node line: kind, live step, an `(after …)` marker for a
|
||||
/// fan-in node (>1 dep), its elapsed timer, and a truncated error tail.
|
||||
fn node_line(d: &hive_sh4re::jobs::DagView, n: &hive_sh4re::jobs::NodeView, now: i64) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let mut s = n.kind.clone();
|
||||
if n.state == hive_sh4re::jobs::State::Running
|
||||
&& let Some(step) = &n.step
|
||||
{
|
||||
let _ = write!(s, " ({step})");
|
||||
}
|
||||
if n.deps.len() > 1 {
|
||||
let after: Vec<&str> = n
|
||||
.deps
|
||||
.iter()
|
||||
.filter_map(|dep| d.nodes.iter().find(|m| m.id == *dep))
|
||||
.map(|m| m.kind.as_str())
|
||||
.collect();
|
||||
if !after.is_empty() {
|
||||
let _ = write!(s, " (after {})", after.join(", "));
|
||||
}
|
||||
}
|
||||
let el = node_elapsed(n, now);
|
||||
if el > 0 {
|
||||
let _ = write!(s, " · {}", fmt_dur(el));
|
||||
}
|
||||
if let Some(err) = &n.error {
|
||||
let short: String = err.chars().take(100).collect();
|
||||
let _ = write!(s, " — {short}");
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn state_glyph(state: hive_sh4re::jobs::State) -> &'static str {
|
||||
match state {
|
||||
hive_sh4re::jobs::State::Queued => "⏸",
|
||||
hive_sh4re::jobs::State::Running => "▶",
|
||||
hive_sh4re::jobs::State::Done => "✔",
|
||||
hive_sh4re::jobs::State::Failed => "✖",
|
||||
hive_sh4re::jobs::State::Cancelled => "⊘",
|
||||
}
|
||||
}
|
||||
|
||||
/// One progress line for a DAG: roll-up glyph, template, agent, then
|
||||
/// the node chain with the running node's live step label — the CLI
|
||||
/// twin of the dashboard's queue card. Used by the plain (non-TTY) path.
|
||||
fn render_dag_line(d: &hive_sh4re::jobs::DagView) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let mut out = format!(
|
||||
"{} {} {:<12}",
|
||||
state_glyph(d.state),
|
||||
d.kind.as_str(),
|
||||
dag_agents(d)
|
||||
);
|
||||
for (i, n) in d.nodes.iter().enumerate() {
|
||||
let sep = if i == 0 { " " } else { " → " };
|
||||
let _ = write!(out, "{sep}{} {}", state_glyph(n.state), n.kind);
|
||||
if n.state == hive_sh4re::jobs::State::Running
|
||||
&& let Some(step) = &n.step
|
||||
{
|
||||
let _ = write!(out, " ({step})");
|
||||
}
|
||||
}
|
||||
if let Some(err) = d.nodes.iter().find_map(|n| n.error.as_deref()) {
|
||||
let short: String = err.chars().take(120).collect();
|
||||
let _ = write!(out, " — {short}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use hive_sh4re::jobs::{DagView, NodeView, Source, State, Template};
|
||||
|
||||
use super::render_dag_line;
|
||||
|
||||
fn node(id: u32, agent: &str, kind: &str, state: State, step: Option<&str>) -> NodeView {
|
||||
NodeView {
|
||||
id,
|
||||
agent: agent.to_owned(),
|
||||
kind: kind.to_owned(),
|
||||
deps: if id == 0 { vec![] } else { vec![id - 1] },
|
||||
state,
|
||||
step: step.map(str::to_owned),
|
||||
build_log_id: None,
|
||||
started_at: None,
|
||||
finished_at: None,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_dag_line_shows_chain_and_running_step() {
|
||||
let dag = DagView {
|
||||
id: 7,
|
||||
kind: Template::Rebuild,
|
||||
state: State::Running,
|
||||
source: Source::Manual,
|
||||
reason: "manual".to_owned(),
|
||||
enqueued_at: 0,
|
||||
started_at: Some(1),
|
||||
finished_at: None,
|
||||
inputs: vec![],
|
||||
approval_id: None,
|
||||
perm_payload: None,
|
||||
nodes: vec![
|
||||
node(0, "alice", "prebuild", State::Done, None),
|
||||
node(1, "alice", "stop_for_update", State::Done, None),
|
||||
node(
|
||||
2,
|
||||
"alice",
|
||||
"swap",
|
||||
State::Running,
|
||||
Some("nixos-container update"),
|
||||
),
|
||||
node(3, "alice", "reconcile", State::Queued, None),
|
||||
],
|
||||
};
|
||||
let line = render_dag_line(&dag);
|
||||
assert!(line.starts_with("▶ rebuild alice"), "{line}");
|
||||
assert!(
|
||||
line.contains(
|
||||
"✔ prebuild → ✔ stop_for_update → ▶ swap (nixos-container update) → ⏸ reconcile"
|
||||
),
|
||||
"{line}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_dag_line_surfaces_first_node_error() {
|
||||
let mut failed = node(0, "bob", "prebuild", State::Failed, None);
|
||||
failed.error = Some("nix build exploded".to_owned());
|
||||
let dag = DagView {
|
||||
id: 8,
|
||||
kind: Template::Rebuild,
|
||||
state: State::Failed,
|
||||
source: Source::Manual,
|
||||
reason: "manual".to_owned(),
|
||||
enqueued_at: 0,
|
||||
started_at: Some(1),
|
||||
finished_at: Some(2),
|
||||
inputs: vec![],
|
||||
approval_id: None,
|
||||
perm_payload: None,
|
||||
nodes: vec![failed],
|
||||
};
|
||||
let line = render_dag_line(&dag);
|
||||
assert!(line.contains("✖ rebuild"), "{line}");
|
||||
assert!(line.contains("— nix build exploded"), "{line}");
|
||||
}
|
||||
}
|
||||
2063
hivectl/src/main.rs
Normal file
2063
hivectl/src/main.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -23,8 +23,8 @@
|
|||
defaultText = lib.literalExpression "hyperhive.packages.\${system}.default";
|
||||
description = ''
|
||||
hyperhive workspace package. Provides `/bin/hive-c0re`
|
||||
(coordinator daemon + admin-socket CLI) and `/bin/hivectl`
|
||||
(operator-facing host CLI for ad-hoc administration). Wired to
|
||||
(coordinator daemon) and `/bin/hivectl` (operator-facing host
|
||||
CLI for ad-hoc administration + the host admin socket). Wired to
|
||||
this flake's `packages.<system>.default` by
|
||||
`nixosModules.default` (via `lib.mkDefault`, so setting it here
|
||||
wins).
|
||||
|
|
|
|||
Loading…
Reference in a new issue