feat(#513): inject HIVE_TOOL_GROUPS from meta tool-groups.json per agent

This commit is contained in:
damocles 2026-06-01 12:17:47 +02:00 committed by mara
commit 816523861c
4 changed files with 129 additions and 5 deletions

View file

@ -290,9 +290,23 @@ binary flavor.
| `scheduling` | `request_schedule_prompt`, `fire_schedule_now`, `cancel_schedule`, `edit_schedule`, `list_schedules` *(privileged)* |
| `diagnostics` | `get_logs` *(privileged)* |
**Config storage** — per-agent tool groups live in
`/var/lib/hyperhive/meta/tool-groups.json` (hive-c0re-owned, committed to the
meta repo alongside `topology.json`). Format: `{ "alice": ["messaging", "meta",
"inbox", "lifecycle"], "bob": ["messaging", "meta", "inbox"] }`. An absent entry
means "use role default". Tool permissions are intentionally NOT configurable
from `agent.nix` — that file goes through the manager's approval flow, so
letting it declare its own groups would let the manager grant itself any tool by
submitting a config commit, bypassing the operator gate.
**Setting groups** — the operator sets groups via the dashboard or
`hive-c0re::tool_groups::set_groups(name, groups)`. After a change
`meta::sync_agents` commits the updated file; the next agent rebuild picks up
the new `HIVE_TOOL_GROUPS` env var. Agents with no entry get no var.
**Runtime resolution** — at session start the harness reads `HIVE_TOOL_GROUPS`
(a comma-separated list of snake_case group names written by the meta renderer
from per-agent config). Unrecognised tokens are logged and skipped. Falls back
(a comma-separated list of snake_case group names injected by the meta renderer
from `tool-groups.json`). Unrecognised tokens are logged and skipped. Falls back
to `ToolGroup::AGENT_DEFAULT` (`messaging`, `meta`, `inbox`) or
`ToolGroup::MANAGER_DEFAULT` (all groups) when the var is absent or empty.

View file

@ -45,4 +45,5 @@ pub mod scheduled_prompts;
pub mod scheduled_prompts_worker;
pub mod server;
pub mod stats_vacuum;
pub mod tool_groups;
pub mod topology;

View file

@ -141,6 +141,13 @@ pub async fn sync_agents(
if crate::topology::topology_path().exists() {
git(&dir, &["add", "topology.json"]).await?;
}
// Stage tool-groups.json when it exists. Created on first
// `set_groups` call (operator-driven); absent = all agents on
// their role defaults, no file needed. git add is a no-op when
// the file is unchanged.
if crate::tool_groups::tool_groups_path().exists() {
git(&dir, &["add", "tool-groups.json"]).await?;
}
nix(&dir, &["flake", "lock"]).await?;
if std::path::Path::new(&dir).join("flake.lock").exists() {
git(&dir, &["add", "flake.lock"]).await?;
@ -436,7 +443,7 @@ where
let pronouns_escaped = operator_pronouns.replace('\\', "\\\\").replace('"', "\\\"");
let _ = writeln!(
out,
" dashboardPort = {dashboard_port};\n operatorPronouns = \"{pronouns_escaped}\";\n mkAgent = {{ name, isManager, port, parent ? null }}:"
" dashboardPort = {dashboard_port};\n operatorPronouns = \"{pronouns_escaped}\";\n mkAgent = {{ name, isManager, port, parent ? null, toolGroups ? null }}:"
);
out.push_str(
r#" let
@ -446,6 +453,7 @@ where
input = inputs."agent-${name}";
service = if isManager then "hive-m1nd" else "hive-ag3nt";
parentEnv = if parent == null then {} else { HIVE_PARENT = parent; };
toolGroupsEnv = if toolGroups == null then {} else { HIVE_TOOL_GROUPS = toolGroups; };
in
base.extendModules {
modules = [
@ -477,7 +485,7 @@ where
HIVE_LABEL = name;
HYPERHIVE_STATE_DIR = "/agents/${name}/state";
};
systemd.services.${service}.environment = parentEnv // {
systemd.services.${service}.environment = parentEnv // toolGroupsEnv // {
HIVE_PORT = toString port;
HIVE_LABEL = name;
HIVE_DASHBOARD_PORT = toString dashboardPort;
@ -527,19 +535,32 @@ where
// (every container at root). `meta::sync_agents` seeds the file
// on first run with manager as root + everyone else under manager.
let topology = crate::topology::read();
let tool_groups_map = crate::tool_groups::read();
for spec in agents {
let parent_attr = topology
.get(&spec.name)
.and_then(|p| p.as_ref())
.map_or_else(|| "null".to_owned(), |p| format!("\"{p}\""));
// Emit `toolGroups = "group1,group2"` when the operator has
// explicitly configured groups for this agent. Absent entry = null
// = harness falls back to its role default (no env var emitted,
// no rebuild cascade for agents whose groups haven't changed).
let groups = tool_groups_map.get(&spec.name).cloned().unwrap_or_default();
let tool_groups_attr = if groups.is_empty() {
"null".to_owned()
} else {
let joined = groups.join(",");
format!("\"{joined}\"")
};
let _ = writeln!(
out,
" {} = mkAgent {{ name = \"{}\"; isManager = {}; port = {}; parent = {}; }};",
" {} = mkAgent {{ name = \"{}\"; isManager = {}; port = {}; parent = {}; toolGroups = {}; }};",
spec.name,
spec.name,
if spec.is_manager { "true" } else { "false" },
spec.port,
parent_attr,
tool_groups_attr,
);
}
out.push_str(" };\n };\n}\n");

View file

@ -0,0 +1,88 @@
//! Per-agent tool-group configuration. Stored at
//! `/var/lib/hyperhive/meta/tool-groups.json` alongside `topology.json`
//! and the meta `flake.nix`.
//!
//! Format: a JSON object mapping agent name to an array of
//! `hive_sh4re::ToolGroup` snake_case strings:
//!
//! ```json
//! {
//! "alice": ["messaging", "meta", "inbox", "lifecycle"],
//! "bob": ["messaging", "meta", "inbox"]
//! }
//! ```
//!
//! An absent entry (or an absent file) means "use the harness role
//! default" — agents get `messaging + meta + inbox`, the manager gets
//! all groups. `render_flake` in `meta.rs` reads this file and
//! injects `HIVE_TOOL_GROUPS` into each agent's systemd service env;
//! agents with no entry get no env var and the harness falls back.
//!
//! Write path: `set_groups` is called from the dashboard action handler
//! that the operator uses to grant/revoke tool groups per agent.
//! The manager may also request group changes via an approval; hive-c0re
//! applies the change on approval, commits the file, and cascades a rebuild.
use std::collections::BTreeMap;
use std::path::PathBuf;
const TOOL_GROUPS_FILE: &str = "tool-groups.json";
#[must_use]
pub fn tool_groups_path() -> PathBuf {
crate::meta::meta_dir().join(TOOL_GROUPS_FILE)
}
/// Read the per-agent tool-group map. Returns an empty map when the
/// file is absent or unparsable — callers treat a missing entry as
/// "use role default".
#[must_use]
pub fn read() -> BTreeMap<String, Vec<String>> {
let path = tool_groups_path();
let Ok(raw) = std::fs::read_to_string(&path) else {
return BTreeMap::new();
};
serde_json::from_str(&raw).unwrap_or_default()
}
/// Look up the configured tool groups for one agent. Returns an empty
/// vec when the agent has no entry — callers should treat this as
/// "use the harness role default."
#[must_use]
pub fn groups_for(name: &str) -> Vec<String> {
read().get(name).cloned().unwrap_or_default()
}
/// Persist the full tool-groups map. Sorted JSON output keeps diffs
/// minimal. Best-effort — returns `io::Error` so callers decide
/// whether to abort or log.
pub fn write(map: &BTreeMap<String, Vec<String>>) -> std::io::Result<()> {
let path = tool_groups_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let text = serde_json::to_string_pretty(map)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(&path, format!("{text}\n"))
}
/// Set the tool groups for one agent and persist the map. An empty
/// `groups` vec removes the entry (agent reverts to role default).
pub fn set_groups(name: &str, groups: &[String]) -> std::io::Result<()> {
let mut current = read();
if groups.is_empty() {
current.remove(name);
} else {
current.insert(name.to_owned(), groups.to_vec());
}
write(&current)
}
/// Drop the entry for an agent that is being destroyed. Idempotent.
pub fn remove_agent(name: &str) -> std::io::Result<()> {
let mut current = read();
if current.remove(name).is_some() {
write(&current)?;
}
Ok(())
}