refactor(hive-c0re): group src-root files into submodules

stores/ (sqlite-backed host stores + db helper), stats/, agent_config/,
workers/ — pure git-mv moves; crate-root re-exports keep every
crate::<module> path compiling. flake_check stays at root (synchronous
approval-flow validation, not a background worker)
This commit is contained in:
müde 2026-07-06 22:38:47 +02:00
commit 0e4b5a1120
29 changed files with 68 additions and 24 deletions

View file

@ -0,0 +1,95 @@
//! Per-agent capability configuration. Stored at
//! `/var/lib/hyperhive/meta/capabilities.json` alongside `topology.json`
//! and `tool-groups.json`.
//!
//! Format: a JSON object mapping agent name to an array of
//! `hive_sh4re::Capability` `snake_case` strings:
//!
//! ```json
//! {
//! "atlas": ["read_host_journal"],
//! "ruth": ["query_agent_state"]
//! }
//! ```
//!
//! An absent entry (or an absent file) means "no extra capabilities".
//! `render_flake` in `meta.rs` reads this file and injects
//! `HIVE_CAPABILITIES` into each agent's systemd service env; absent
//! entries emit no env var so agents without capabilities don't trigger
//! a spurious rebuild.
//!
//! Write path: `set_caps` is called from the dashboard action handler
//! that the operator uses to grant/revoke capabilities per agent.
use std::collections::BTreeMap;
use std::path::PathBuf;
const CAPABILITIES_FILE: &str = "capabilities.json";
#[must_use]
pub fn capabilities_path() -> PathBuf {
crate::meta::meta_dir().join(CAPABILITIES_FILE)
}
/// Read the per-agent capability map. Returns an empty map when the
/// file is absent or unparsable — callers treat a missing entry as
/// "no extra capabilities".
#[must_use]
pub fn read() -> BTreeMap<String, Vec<String>> {
let path = capabilities_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 capabilities for one agent. Returns an empty
/// vec when the agent has no entry.
#[must_use]
pub fn caps_for(name: &str) -> Vec<String> {
read().get(name).cloned().unwrap_or_default()
}
/// Check whether an agent holds a specific capability.
#[must_use]
pub fn has_cap(name: &str, cap: hive_sh4re::Capability) -> bool {
caps_for(name)
.iter()
.any(|s| s.eq_ignore_ascii_case(cap.as_str()))
}
/// Persist the full capability 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 = capabilities_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 capabilities for one agent and persist the map. An empty
/// `caps` vec removes the entry (agent has no capabilities).
pub fn set_caps(name: &str, caps: &[String]) -> std::io::Result<()> {
let mut current = read();
if caps.is_empty() {
current.remove(name);
} else {
current.insert(name.to_owned(), caps.to_vec());
}
write(&current)
}
/// Remove an agent from the capability map entirely. Called by
/// `meta::sync_agents` when an agent is deprovisioned so stale entries
/// don't accumulate. No-op if the agent has no entry.
pub fn remove_agent(name: &str) -> std::io::Result<()> {
let mut current = read();
if current.remove(name).is_some() {
write(&current)?;
}
Ok(())
}

View file

@ -0,0 +1,176 @@
//! Wire-protocol size limits shared across the agent + manager
//! sockets. Caps on inline message bodies stop a single chatty agent
//! (or a misbehaving extra-MCP server) from flooding the broker
//! sqlite with megabyte-sized rows that then bloat every recipient's
//! wake-prompt context. Anything genuinely larger should be written
//! to a state file and the path sent as the body.
//!
//! Reminders get a separate auto-file escape hatch (see
//! `socket_server::handle_remind`) so callers don't have to think
//! about it — oversized reminder bodies get persisted to disk
//! transparently and the inbox sees a pointer.
/// Per-message body cap. Applies to `send`, `ask` question text,
/// `answer` body, and the stored inline form of a reminder. 4 KiB
/// catches the bulk of conversational overflow (status reports,
/// bullet-list summaries, short proposals) while staying small
/// enough that a backed-up inbox of ~10 unread messages only adds
/// ~40 KiB to the recipient's wake-prompt context. Genuinely
/// long-form artifacts (audit reports, full diffs, transcripts)
/// still belong in a state file — the error message on overflow
/// points callers at that escape hatch.
pub const MESSAGE_MAX_BYTES: usize = 4096;
/// Validate that `body` fits under [`MESSAGE_MAX_BYTES`]. Returns a
/// caller-ready error string (caller wraps in
/// `AgentResponse::Err`/`ManagerResponse::Err`) on failure.
///
/// `label` shows up in the error message verbatim — pass a short
/// noun like `"send"`, `"question"`, `"broadcast"` so the model can
/// tell which call got rejected.
pub fn check_size(label: &str, body: &str) -> Result<(), String> {
if body.len() > MESSAGE_MAX_BYTES {
Err(format!(
"{label} body too long ({} bytes, max {MESSAGE_MAX_BYTES}); write the \
payload to a file under your `/agents/<you>/state/` dir and send the \
path as the body instead",
body.len()
))
} else {
Ok(())
}
}
/// Per-status soft cap. `set_status` renders as a short chip on the
/// dashboard agent card — the front-end truncates long strings to
/// keep the row layout intact, so a multi-paragraph "session report"
/// is wasted bytes that just bloat the rescan emit + container view
/// payload. Cap at 200 chars to fit the chip plus a little
/// descriptive padding without forcing the operator to read a
/// scrolling chunk.
/// NOTE: `hive-ag3nt/src/mcp.rs::write_status_file` mirrors this constant
/// client-side so invalid text is caught before the file is written.
/// Keep in sync if this value changes.
pub const STATUS_MAX_CHARS: usize = 200;
/// Validate a `set_status` payload. Single-line + bounded so
/// callers can't dump multi-paragraph session reports into the
/// dashboard chip. Whitespace trim is done by the caller before the
/// store-to-disk step — we run validation on the trimmed form so
/// surrounding whitespace doesn't push a borderline-legal status
/// past the cap.
///
/// Empty / all-whitespace input is accepted: the call site treats
/// that as "clear the status" and removes the on-disk sentinel. Tests
/// + caller cover both directions.
///
/// Returns a caller-ready error string suitable for surfacing in the
/// `*Response::Err` shape.
pub fn check_status_text(text: &str) -> Result<(), String> {
let trimmed = text.trim();
if trimmed.is_empty() {
// Empty = clear-status sentinel; nothing to validate.
return Ok(());
}
// Newline / carriage-return: status is a single-line chip on the
// dashboard. Multi-line session reports should go to a state file.
if trimmed.contains('\n') || trimmed.contains('\r') {
return Err(
"set_status text must be a single line — write multi-line context to \
a file under your `/agents/<you>/state/` dir and reference that path \
from the chip instead"
.to_owned(),
);
}
let len = trimmed.chars().count();
if len > STATUS_MAX_CHARS {
return Err(format!(
"set_status text too long ({len} chars, max {STATUS_MAX_CHARS}); the \
dashboard chip truncates anything longer, so trim to a short summary \
and write the detail to `/agents/<you>/state/<file>` instead"
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_short_body() {
assert!(check_size("send", "hello").is_ok());
assert!(check_size("send", &"x".repeat(MESSAGE_MAX_BYTES)).is_ok());
}
#[test]
fn rejects_oversize_body() {
let err = check_size("send", &"x".repeat(MESSAGE_MAX_BYTES + 1)).unwrap_err();
assert!(err.contains("send body too long"));
assert!(err.contains(&format!("max {MESSAGE_MAX_BYTES}")));
}
#[test]
fn label_threads_through() {
let err = check_size("question", &"x".repeat(MESSAGE_MAX_BYTES + 1)).unwrap_err();
assert!(err.starts_with("question body too long"));
}
#[test]
fn check_status_accepts_short_single_line() {
assert!(check_status_text("idle").is_ok());
assert!(check_status_text("processing matrix messages").is_ok());
// Boundary: exactly STATUS_MAX_CHARS chars trimmed is still
// accepted; one more rejects.
let max = "a".repeat(STATUS_MAX_CHARS);
assert!(check_status_text(&max).is_ok());
}
#[test]
fn check_status_accepts_empty_and_whitespace() {
// Empty + whitespace-only are the "clear status" sentinel and
// bypass the rest of the checks.
assert!(check_status_text("").is_ok());
assert!(check_status_text(" ").is_ok());
assert!(check_status_text("\n\t ").is_ok());
}
#[test]
fn check_status_rejects_multi_line() {
let err = check_status_text("line one\nline two").unwrap_err();
assert!(err.contains("single line"), "err = {err}");
// Carriage return alone also rejects (windows linebreak / CR-only).
assert!(check_status_text("a\rb").is_err());
}
#[test]
fn check_status_rejects_oversize() {
let too_long = "a".repeat(STATUS_MAX_CHARS + 1);
let err = check_status_text(&too_long).unwrap_err();
assert!(err.contains("too long"), "err = {err}");
assert!(err.contains(&format!("max {STATUS_MAX_CHARS}")));
}
#[test]
fn check_status_counts_chars_not_bytes() {
// Multi-byte chars (emoji, accented letters) count once each
// per char — chars().count() not byte len. STATUS_MAX_CHARS
// worth of 4-byte chars is still legal.
let emoji = "💜".repeat(STATUS_MAX_CHARS);
assert!(
check_status_text(&emoji).is_ok(),
"{STATUS_MAX_CHARS} emoji should fit"
);
let too_many = "💜".repeat(STATUS_MAX_CHARS + 1);
assert!(check_status_text(&too_many).is_err());
}
#[test]
fn check_status_validates_post_trim() {
// Leading/trailing whitespace is trimmed before the length
// check — a borderline-legal payload with spaces around it
// still passes.
let padded = format!(" {} ", "a".repeat(STATUS_MAX_CHARS));
assert!(check_status_text(&padded).is_ok());
}
}

View file

@ -0,0 +1,10 @@
//! Per-agent configuration registries: tool groups, capabilities,
//! topology (all JSON files under `/var/lib/hyperhive/meta/`) and the
//! shared wire-protocol size limits. Each submodule is re-exported at
//! the crate root, so `crate::topology::…` etc. keep working
//! unchanged.
pub mod capabilities;
pub mod limits;
pub mod tool_groups;
pub mod topology;

View file

@ -0,0 +1,120 @@
//! 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 default"
//! (`AGENT_DEFAULT`: `messaging + meta + inbox + execution`). `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 to `AGENT_DEFAULT`.
//!
//! Write path: `set_groups` is called from the dashboard action handler
//! that the operator uses to grant/revoke tool groups per agent.
use std::collections::BTreeMap;
use std::path::PathBuf;
use anyhow::Context as _;
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. Use `set_groups` (or `remove_agent`) from outside this
/// module — they go through the validated write path.
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"))
}
/// Validate a slice of group name strings against `ToolGroup::ALL`.
/// Returns `Ok(())` when all names are known, or `Err` listing the
/// unrecognised names so callers can surface a useful error message.
pub fn validate_groups(groups: &[String]) -> anyhow::Result<()> {
let valid: std::collections::BTreeSet<&str> = hive_sh4re::ToolGroup::ALL
.iter()
.map(|g| g.as_str())
.collect();
let unknown: Vec<&str> = groups
.iter()
.map(String::as_str)
.filter(|s| !valid.contains(s))
.collect();
if unknown.is_empty() {
Ok(())
} else {
anyhow::bail!(
"unknown tool group(s): {}; valid names are: {}",
unknown.join(", "),
hive_sh4re::ToolGroup::ALL
.iter()
.map(|g| g.as_str())
.collect::<Vec<_>>()
.join(", ")
)
}
}
/// Set the tool groups for one agent and persist the map. An empty
/// `groups` vec removes the entry (agent reverts to role default).
/// Returns an error if any name is not in `ToolGroup::ALL`.
pub fn set_groups(name: &str, groups: &[String]) -> anyhow::Result<()> {
if !groups.is_empty() {
validate_groups(groups)?;
}
let mut current = read();
if groups.is_empty() {
current.remove(name);
} else {
current.insert(name.to_owned(), groups.to_vec());
}
write(&current).with_context(|| format!("write tool-groups for {name}"))
}
/// 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(())
}

View file

@ -0,0 +1,912 @@
//! Agent topology storage — single source of truth for parent/child
//! relations in the hive. Persisted as a flat JSON map of `name →
//! parent name | null` at `/var/lib/hyperhive/meta/topology.json`,
//! alongside the meta `flake.nix`, so topology changes thread through
//! the same git commit log as deploys.
//!
//! Agent roles are stored alongside in `roles.json` as a flat map of
//! `name → [role, ...]`. Roles gate additional bind-mount grants; see
//! `lifecycle::set_nspawn_flags` for the consumer.
//!
//! Format, rationale, read/reconcile/inject/surface flow, and target
//! enforcement semantics: `docs/agent-hierarchy.md::Current state`.
//! `<parent>` sentinel resolution (delivered by [`resolve_recipient`]):
//! `docs/conventions.md::Recipient sentinels`.
use std::collections::BTreeMap;
use std::path::PathBuf;
const TOPOLOGY_FILE: &str = "topology.json";
#[must_use]
pub fn topology_path() -> PathBuf {
crate::meta::meta_dir().join(TOPOLOGY_FILE)
}
/// Snapshot of the topology map. Read on every `container_view::build_all`
/// and every `render_flake` call. The file is small (one line per agent),
/// so we re-read rather than caching — keeps the source of truth on disk.
///
/// Returns an empty map when the file is absent or unparsable; callers
/// treat that as "no recorded parents", which falls back to every agent
/// being root-level. Safe degradation for fresh installs that haven't
/// run through `meta::sync_agents` yet.
#[must_use]
pub fn read() -> BTreeMap<String, Option<String>> {
let path = topology_path();
let Ok(raw) = std::fs::read_to_string(&path) else {
return BTreeMap::new();
};
serde_json::from_str(&raw).unwrap_or_default()
}
/// Look up one agent's parent. Returns `None` when the agent is root
/// or absent from the file. Cheap convenience over `read()` for
/// callers that want a single entry.
#[must_use]
pub fn parent_of(name: &str) -> Option<String> {
read().get(name).cloned().flatten()
}
/// Return the direct children of `name` — agents whose `topology.json`
/// entry has `name` as their parent. Reads the map once and scans all
/// entries; cheap enough for the fan-out path (one disk read per send
/// to `<children>`).
#[must_use]
pub fn children_of(name: &str) -> Vec<String> {
children_of_in(&read(), name)
}
/// Pure form of [`children_of`] for unit tests.
#[must_use]
pub fn children_of_in(topo: &BTreeMap<String, Option<String>>, name: &str) -> Vec<String> {
topo.iter()
.filter_map(|(agent, parent)| {
if parent.as_deref() == Some(name) {
Some(agent.clone())
} else {
None
}
})
.collect()
}
/// Return every agent that has no parent in the topology. These are the
/// "top-level" agents a `can_manage_top_level_agents` role holder is
/// granted access to. No agent name is hardcoded — the set is derived
/// purely from topology structure.
///
/// In normal operation this is just the manager, but any agent the
/// operator explicitly places outside the hierarchy is also included.
#[must_use]
pub fn top_level_agents() -> Vec<String> {
top_level_agents_in(&read())
}
/// Pure form of [`top_level_agents`] for unit tests.
#[must_use]
pub fn top_level_agents_in(topo: &BTreeMap<String, Option<String>>) -> Vec<String> {
topo.iter()
.filter_map(|(name, parent)| {
if parent.is_none() {
Some(name.clone())
} else {
None
}
})
.collect()
}
/// Resolve a magic recipient sentinel (currently just
/// [`hive_sh4re::PARENT_RECIPIENT`]) to a real broker recipient at
/// send time. Returns an owned `String` so callers can plug it
/// straight into [`crate::broker::Broker::send`] without
/// borrow-juggling around the temporary lookup.
///
/// Rules + rationale: `docs/conventions.md::Recipient sentinels`.
/// Fast path: ordinary recipient names short-circuit before any
/// disk read — only `<parent>` triggers `read()` on `topology.json`.
#[must_use]
pub fn resolve_recipient(sender: &str, to: &str) -> String {
// Early exit: only sentinel recipients need topology lookup. This
// keeps the cost of a normal `send` at one string comparison.
if to != hive_sh4re::PARENT_RECIPIENT {
return to.to_owned();
}
resolve_recipient_in(&read(), sender, to)
}
/// Pure form of [`resolve_recipient`] taking the topology map
/// explicitly. Split out so unit tests can exercise the sentinel
/// rules without writing a `topology.json` to disk.
#[must_use]
pub fn resolve_recipient_in(
topo: &BTreeMap<String, Option<String>>,
sender: &str,
to: &str,
) -> String {
if to == hive_sh4re::PARENT_RECIPIENT {
topo.get(sender)
.cloned()
.flatten()
.unwrap_or_else(|| hive_sh4re::OPERATOR_RECIPIENT.to_owned())
} else {
to.to_owned()
}
}
/// True when `candidate` is `ancestor` or any descendant of
/// `ancestor` per the current topology. Walks parents from
/// `candidate` upward; the walk terminates at root or on a cycle
/// (cycle defence: bounded to 32 hops, more than any plausible
/// hive depth). Used by the cancel-authorization check in
/// `socket_server::handle_cancel_schedule` to enforce
/// "managers can cancel anything their subtree owns."
#[must_use]
pub fn is_descendant_of(candidate: &str, ancestor: &str) -> bool {
if candidate == ancestor {
return true;
}
let topo = read();
let mut cur = candidate.to_owned();
for _ in 0..32 {
let Some(parent) = topo.get(&cur).cloned().flatten() else {
return false;
};
if parent == ancestor {
return true;
}
cur = parent;
}
false
}
/// Persist the topology map. Sorted JSON output (`BTreeMap` is sorted by
/// key) keeps git diffs minimal across re-writes. Best-effort —
/// returns an `io::Error` so callers can decide whether a failure
/// should abort their op (`sync_agents`, `RequestSetParent`) or just log.
pub fn write(topology: &BTreeMap<String, Option<String>>) -> std::io::Result<()> {
let path = topology_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let text = serde_json::to_string_pretty(topology)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(&path, format!("{text}\n"))
}
/// Compute the default topology for a fresh install: every agent is a
/// root (parent = null). There is no structural "manager" — agents
/// arrange themselves via explicit parent edges (an agent-requested
/// sub-agent gets a requester-as-parent edge at `init_config`; the
/// operator reparents via the dashboard / `RequestSetParent` API).
/// Used by `meta::sync_agents` on first call to seed `topology.json`.
///
/// As soon as an explicit write lands (dashboard / `RequestSetParent`
/// API), this seeding stops touching pre-existing entries —
/// `sync_agents` only adds rows for newly-spawned agents against
/// whatever the operator has configured.
#[must_use]
#[allow(
dead_code,
reason = "kept for the dashboard / RequestSetParent write API; \
`sync_agents` does its own seeding today"
)]
pub fn default_seed(agent_names: &[String]) -> BTreeMap<String, Option<String>> {
let mut out = BTreeMap::new();
for name in agent_names {
out.insert(name.clone(), None);
}
out
}
/// Pure validation + apply for [`set_parent`]. Splits off so tests
/// can exercise the rules (cycle / unknown) on an in-memory
/// `BTreeMap` without touching the on-disk `topology.json`. Returns
/// either the post-move map (caller writes it back) or a
/// user-readable error string.
///
/// The manager is reparentable like any other agent — its special
/// powers come from the privileged MCP socket, not its tree
/// position. The cycle walk below covers "moving X under its own
/// descendant" for the manager as much as any other agent.
/// `docs/agent-hierarchy.md::Current state` has the rationale.
pub fn apply_set_parent(
topo: &BTreeMap<String, Option<String>>,
child: &str,
new_parent: Option<&str>,
) -> Result<BTreeMap<String, Option<String>>, String> {
if !topo.contains_key(child) {
return Err(format!("unknown agent: {child}"));
}
if let Some(p) = new_parent {
if !topo.contains_key(p) {
return Err(format!("unknown parent: {p}"));
}
if p == child {
return Err("an agent cannot be its own parent".to_owned());
}
// Cycle check: walk `p`'s ancestors in the EXISTING map. If
// we hit `child`, then making `child`'s parent = `p` would
// close the loop (child → … → p → child).
let mut cur = p.to_owned();
for _ in 0..32 {
if cur == child {
return Err(format!(
"cycle: {p} is in {child}'s subtree (would create a loop)"
));
}
let Some(next) = topo.get(&cur).cloned().flatten() else {
break;
};
cur = next;
}
}
let mut next = topo.clone();
next.insert(child.to_owned(), new_parent.map(str::to_owned));
Ok(next)
}
/// Operator-driven parent move. Set `child`'s parent to `new_parent`
/// (or `None` to promote to root). See [`apply_set_parent`] for the
/// validation rules. The operator-set parent sticks across
/// `reconcile()` calls (which preserves existing entries).
///
/// No bind-mount / container churn today — the hierarchy is
/// currently logical-only. Once sub-manager bind mounts land, the
/// caller adds an umount-old / mount-new / restart-cascade step on
/// top.
pub fn set_parent(child: &str, new_parent: Option<&str>) -> Result<(), String> {
let current = read();
// Idempotent no-op fast path: skip the disk write when nothing
// changes. apply_set_parent still runs to surface validation
// errors (e.g. unknown child) so the caller gets a real signal.
let next = apply_set_parent(&current, child, new_parent)?;
if next == current {
return Ok(());
}
write(&next).map_err(|e| format!("write topology.json: {e}"))
}
/// Declare a brand-new agent's parent edge before the agent exists in
/// the container set. Unlike [`set_parent`] (which reparents an entry
/// that must already be present), this inserts a fresh `child -> parent`
/// row. Used by the `InitConfig` approval to place a just-scaffolded
/// sub-agent under its requesting parent, so the edge is in place
/// before the first apply-commit spawns the container (and before
/// [`reconcile`] would otherwise default it to the manager).
///
/// Idempotent when the edge already exists. Refuses to clobber an entry
/// whose parent differs (one agent can't steal another's child) and
/// validates that `parent` is itself a known agent.
pub fn add_child(child: &str, parent: &str) -> Result<(), String> {
let current = read();
match apply_add_child(&current, child, parent)? {
Some(next) => write(&next).map_err(|e| format!("write topology.json: {e}")),
None => Ok(()),
}
}
/// Pure form of [`add_child`] for unit tests. Returns the post-insert
/// map (caller writes it back), `None` for an idempotent no-op (edge
/// already present), or an error string (unknown parent / name owned by
/// a different parent).
pub fn apply_add_child(
topo: &BTreeMap<String, Option<String>>,
child: &str,
parent: &str,
) -> Result<Option<BTreeMap<String, Option<String>>>, String> {
if !topo.contains_key(parent) {
return Err(format!("unknown parent: {parent}"));
}
match topo.get(child) {
Some(Some(p)) if p == parent => return Ok(None),
Some(existing) => {
return Err(format!(
"agent {child} already exists in topology (parent: {existing:?}); \
refusing to reparent via add_child"
));
}
None => {}
}
let mut next = topo.clone();
next.insert(child.to_owned(), Some(parent.to_owned()));
Ok(Some(next))
}
/// Reconcile `topology.json` against the current agent set. Adds an
/// entry (default: parent = null — a new agent with no declared parent
/// is its own root) for any agent missing from the file; removes
/// entries for agents no longer
/// present. Existing entries are preserved as-is — operator/manager
/// choices stick across regenerations. Returns true when the file
/// changed and should be re-committed by the caller.
///
/// `pending` lists agents that have an operator-approved proposed config
/// repo but no container yet (init'd, not yet spawned). They are KEPT
/// (not dropped) so the parent edge written at `InitConfig` approval
/// survives until the first apply-commit, but they are NOT seeded with a
/// default parent here and NOT added to roles — that happens when the
/// container actually spawns and the name moves into `agent_names`.
pub fn reconcile(agent_names: &[String], pending: &[String]) -> std::io::Result<bool> {
let (next, changed) = apply_reconcile(&read(), agent_names, pending);
if changed {
write(&next)?;
}
// Keep roles in sync with the live agent set (pending agents get
// roles when they spawn).
reconcile_roles(agent_names)?;
Ok(changed)
}
/// Pure form of [`reconcile`] for unit tests. Adds missing live agents
/// at their default position, drops entries for agents that are neither
/// live nor pending-init, and reports whether anything changed.
#[must_use]
pub fn apply_reconcile(
current: &BTreeMap<String, Option<String>>,
agent_names: &[String],
pending: &[String],
) -> (BTreeMap<String, Option<String>>, bool) {
let mut next = current.clone();
let mut changed = false;
for name in agent_names {
if !next.contains_key(name) {
// A new agent with no declared parent defaults to root
// (parent = null). Agent-requested sub-agents always carry an
// explicit requester-as-parent edge (written at init_config
// approval), so they never hit this default — only
// user/operator-initiated spawns do, and those are roots. No
// agent is structurally privileged here: "root-ness" is just
// a null parent.
next.insert(name.clone(), None);
changed = true;
}
}
let known: std::collections::HashSet<&String> =
agent_names.iter().chain(pending.iter()).collect();
next.retain(|name, _| {
let keep = known.contains(name);
if !keep {
changed = true;
}
keep
});
(next, changed)
}
// ---------------------------------------------------------------------------
// Roles
// ---------------------------------------------------------------------------
/// Agents with this role have every parentless agent in the topology
/// (see `top_level_agents`) added as virtual children for bind-mount
/// and config-change purposes. Enables recovery: if a top-level agent
/// is down, a role holder can still read its state and update its config.
///
/// The manager receives this role by default on first `reconcile_roles`
/// call; operators can revoke it with `set_role`.
pub const ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS: &str = "can_manage_top_level_agents";
const ROLES_FILE: &str = "roles.json";
#[must_use]
pub fn roles_path() -> std::path::PathBuf {
crate::meta::meta_dir().join(ROLES_FILE)
}
/// Read the roles map from disk. Returns an empty map when absent or
/// unparsable — same safe-degradation pattern as `topology::read`.
#[must_use]
pub fn read_roles() -> BTreeMap<String, Vec<String>> {
let Ok(raw) = std::fs::read_to_string(roles_path()) else {
return BTreeMap::new();
};
serde_json::from_str(&raw).unwrap_or_default()
}
/// Persist the roles map. Sorted output keeps git diffs minimal.
pub fn write_roles(roles: &BTreeMap<String, Vec<String>>) -> std::io::Result<()> {
let path = roles_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let text = serde_json::to_string_pretty(roles)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(&path, format!("{text}\n"))
}
/// Return true when `name` holds `role`.
#[must_use]
pub fn has_role(name: &str, role: &str) -> bool {
has_role_in(&read_roles(), name, role)
}
/// Pure form of [`has_role`] for unit tests.
#[must_use]
pub fn has_role_in(roles: &BTreeMap<String, Vec<String>>, name: &str, role: &str) -> bool {
roles
.get(name)
.is_some_and(|rs| rs.iter().any(|r| r == role))
}
/// Grant or revoke a role for `name`. Idempotent — no disk write when the
/// state is already correct.
///
/// Empty role lists are kept in the map (never removed). An absent key means
/// "never seen" (seed on next `reconcile_roles`); an empty list means
/// "explicitly revoked" (do not re-seed). Callers that want to remove an
/// agent from the map entirely should use `reconcile_roles` (agent departure).
pub fn set_role(name: &str, role: &str, enabled: bool) -> Result<(), String> {
let mut roles = read_roles();
let list = roles.entry(name.to_owned()).or_default();
let held = list.iter().any(|r| r == role);
match (enabled, held) {
(true, false) => list.push(role.to_owned()),
(false, true) => list.retain(|r| r != role),
_ => return Ok(()),
}
// Intentionally do NOT remove empty entries — an empty list signals an
// explicit revoke and prevents reconcile_roles from re-seeding the role.
write_roles(&roles).map_err(|e| format!("write roles.json: {e}"))
}
/// Reconcile `roles.json` against the current agent set:
/// - Seeds root's default `can_manage_top_level_agents` role on first
/// appearance (operator can revoke with `set_role`).
/// - Drops entries for agents that no longer exist.
///
/// Returns true when the file changed.
pub fn reconcile_roles(agent_names: &[String]) -> std::io::Result<bool> {
let mut roles = read_roles();
let mut changed = false;
let root = crate::lifecycle::MANAGER_NAME;
if agent_names.iter().any(|n| n == root) && !roles.contains_key(root) {
roles.insert(
root.to_owned(),
vec![ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS.to_owned()],
);
changed = true;
}
let known: std::collections::HashSet<_> = agent_names.iter().collect();
roles.retain(|name, _| {
let keep = known.contains(name);
if !keep {
changed = true;
}
keep
});
if changed {
write_roles(&roles)?;
}
Ok(changed)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_seed_makes_every_agent_root() {
// No structural manager: every agent defaults to root (null
// parent). Explicit edges (init_config / dashboard) are layered
// on later.
let agents = vec![
"alice".to_owned(),
crate::lifecycle::MANAGER_NAME.to_owned(),
"bob".to_owned(),
];
let seed = default_seed(&agents);
assert_eq!(seed.get(crate::lifecycle::MANAGER_NAME), Some(&None));
assert_eq!(seed.get("alice"), Some(&None));
assert_eq!(seed.get("bob"), Some(&None));
}
#[test]
fn default_seed_handles_empty_input() {
let seed = default_seed(&[]);
assert!(seed.is_empty());
}
fn topo_three_level() -> BTreeMap<String, Option<String>> {
let mut m = BTreeMap::new();
m.insert(crate::lifecycle::MANAGER_NAME.to_owned(), None);
m.insert(
"alice".to_owned(),
Some(crate::lifecycle::MANAGER_NAME.to_owned()),
);
m.insert("bob".to_owned(), Some("alice".to_owned()));
m.insert("carol".to_owned(), Some("alice".to_owned()));
m
}
#[test]
fn apply_set_parent_promotes_to_root() {
let next = apply_set_parent(&topo_three_level(), "alice", None).unwrap();
assert_eq!(next.get("alice"), Some(&None));
}
#[test]
fn apply_set_parent_reparents_under_sibling_subtree() {
// bob and carol both under alice; move carol under bob.
let next = apply_set_parent(&topo_three_level(), "carol", Some("bob")).unwrap();
assert_eq!(next.get("carol"), Some(&Some("bob".to_owned())));
}
#[test]
fn apply_set_parent_allows_manager_move() {
// The manager is reparentable like any other agent (its
// privileges live on the MCP socket, not its tree position).
// Build a topo with an unrelated root-level agent `peer` so
// moving the manager under it doesn't trip the cycle walk
// (every non-manager agent in topo_three_level descends from
// the manager, so that fixture can't exercise a legal
// manager move).
let mut topo = BTreeMap::new();
topo.insert(crate::lifecycle::MANAGER_NAME.to_owned(), None);
topo.insert("peer".to_owned(), None);
let next = apply_set_parent(&topo, crate::lifecycle::MANAGER_NAME, Some("peer"))
.expect("manager move should succeed");
assert_eq!(
next.get(crate::lifecycle::MANAGER_NAME),
Some(&Some("peer".to_owned()))
);
}
#[test]
fn apply_set_parent_refuses_manager_under_own_descendant() {
// Moving the manager under `bob` (who already lives under
// `alice` who lives under the manager) would close the loop.
// The general cycle walk catches this; no separate manager
// guard needed.
let err = apply_set_parent(
&topo_three_level(),
crate::lifecycle::MANAGER_NAME,
Some("bob"),
)
.unwrap_err();
assert!(err.contains("cycle"), "err = {err}");
}
#[test]
fn apply_set_parent_refuses_unknown_child() {
let err = apply_set_parent(&topo_three_level(), "nobody", Some("alice")).unwrap_err();
assert!(err.contains("unknown agent"), "err = {err}");
}
#[test]
fn apply_set_parent_refuses_unknown_parent() {
let err = apply_set_parent(&topo_three_level(), "bob", Some("nobody")).unwrap_err();
assert!(err.contains("unknown parent"), "err = {err}");
}
#[test]
fn apply_set_parent_refuses_self() {
let err = apply_set_parent(&topo_three_level(), "alice", Some("alice")).unwrap_err();
assert!(err.contains("own parent"), "err = {err}");
}
#[test]
fn apply_set_parent_refuses_cycle() {
// bob's parent is alice; trying to make alice's parent =
// bob would close the loop alice → bob → alice.
let err = apply_set_parent(&topo_three_level(), "alice", Some("bob")).unwrap_err();
assert!(err.contains("cycle"), "err = {err}");
}
#[test]
fn apply_set_parent_refuses_deep_cycle() {
// Three-deep chain: manager → alice → bob → carol. Moving
// alice under carol would create the loop alice → carol → bob → alice.
let mut topo = BTreeMap::new();
topo.insert(crate::lifecycle::MANAGER_NAME.to_owned(), None);
topo.insert(
"alice".to_owned(),
Some(crate::lifecycle::MANAGER_NAME.to_owned()),
);
topo.insert("bob".to_owned(), Some("alice".to_owned()));
topo.insert("carol".to_owned(), Some("bob".to_owned()));
let err = apply_set_parent(&topo, "alice", Some("carol")).unwrap_err();
assert!(err.contains("cycle"), "err = {err}");
}
#[test]
fn apply_set_parent_is_idempotent_noop() {
// bob is already under alice — same value returned.
let next = apply_set_parent(&topo_three_level(), "bob", Some("alice")).unwrap();
assert_eq!(next, topo_three_level());
}
#[test]
fn apply_add_child_inserts_new_edge_under_parent() {
// alice spawns a brand-new child `dora`: the edge lands
// with alice as parent without disturbing the rest of the tree.
let next = apply_add_child(&topo_three_level(), "dora", "alice")
.unwrap()
.expect("brand-new edge should produce a map");
assert_eq!(next.get("dora"), Some(&Some("alice".to_owned())));
// existing entries untouched.
assert_eq!(next.get("bob"), Some(&Some("alice".to_owned())));
}
#[test]
fn apply_add_child_is_idempotent_when_edge_exists() {
// bob already under alice — re-init returns a no-op (None).
assert!(
apply_add_child(&topo_three_level(), "bob", "alice")
.unwrap()
.is_none()
);
}
#[test]
fn apply_add_child_refuses_unknown_parent() {
let err = apply_add_child(&topo_three_level(), "dora", "nobody").unwrap_err();
assert!(err.contains("unknown parent"), "err = {err}");
}
#[test]
fn apply_add_child_refuses_name_owned_by_other_parent() {
// bob lives under alice; the manager can't claim it via add_child.
let err = apply_add_child(&topo_three_level(), "bob", crate::lifecycle::MANAGER_NAME)
.unwrap_err();
assert!(err.contains("already exists"), "err = {err}");
}
#[test]
fn apply_reconcile_adds_missing_live_agent_as_root() {
// A live agent with no prior topology entry defaults to root
// (null parent) — no structural manager to hang it under.
let live = vec![
crate::lifecycle::MANAGER_NAME.to_owned(),
"newbie".to_owned(),
];
let (next, changed) = apply_reconcile(&BTreeMap::new(), &live, &[]);
assert!(changed);
assert_eq!(next.get("newbie"), Some(&None));
assert_eq!(next.get(crate::lifecycle::MANAGER_NAME), Some(&None));
}
#[test]
fn apply_reconcile_drops_vanished_agent() {
let live = vec![
crate::lifecycle::MANAGER_NAME.to_owned(),
"alice".to_owned(),
];
// carol + bob are gone from the live set and not pending.
let (next, changed) = apply_reconcile(&topo_three_level(), &live, &[]);
assert!(changed);
assert!(!next.contains_key("bob"));
assert!(!next.contains_key("carol"));
assert!(next.contains_key("alice"));
}
#[test]
fn apply_reconcile_keeps_pending_init_agent_edge() {
// `dora` was init'd under alice (edge present) but has no
// container yet, so it's absent from the live set. It must NOT
// be dropped, and its alice-parent edge must be preserved (not
// re-seeded under the manager).
let mut topo = topo_three_level();
topo.insert("dora".to_owned(), Some("alice".to_owned()));
let live = vec![
crate::lifecycle::MANAGER_NAME.to_owned(),
"alice".to_owned(),
"bob".to_owned(),
"carol".to_owned(),
];
let pending = vec!["dora".to_owned()];
let (next, changed) = apply_reconcile(&topo, &live, &pending);
assert!(!changed, "no change expected: {next:?}");
assert_eq!(next.get("dora"), Some(&Some("alice".to_owned())));
}
#[test]
fn resolve_recipient_passes_through_ordinary_names() {
let topo = topo_three_level();
// Real labels, broadcast, and the operator literal all
// shortcut through unchanged — no resolution magic.
assert_eq!(resolve_recipient_in(&topo, "bob", "alice"), "alice");
assert_eq!(resolve_recipient_in(&topo, "bob", "*"), "*");
assert_eq!(
resolve_recipient_in(&topo, "bob", hive_sh4re::OPERATOR_RECIPIENT),
hive_sh4re::OPERATOR_RECIPIENT
);
}
#[test]
fn resolve_recipient_rewrites_parent_sentinel_to_parent_label() {
let topo = topo_three_level();
// bob's parent is alice → `<parent>` from bob goes to alice.
assert_eq!(
resolve_recipient_in(&topo, "bob", hive_sh4re::PARENT_RECIPIENT),
"alice"
);
// alice's parent is the manager — same one-hop rewrite.
assert_eq!(
resolve_recipient_in(&topo, "alice", hive_sh4re::PARENT_RECIPIENT),
crate::lifecycle::MANAGER_NAME
);
}
#[test]
fn resolve_recipient_falls_back_to_operator_for_root_agent() {
let topo = topo_three_level();
// Manager is structurally root (parent = None) → `<parent>`
// resolves to the operator (the "no parent → tell mara"
// fallback documented in conventions.md).
assert_eq!(
resolve_recipient_in(
&topo,
crate::lifecycle::MANAGER_NAME,
hive_sh4re::PARENT_RECIPIENT
),
hive_sh4re::OPERATOR_RECIPIENT
);
}
#[test]
fn resolve_recipient_falls_back_to_operator_for_unknown_sender() {
// Sender absent from topology entirely — defensive fallback
// covers the race window where an agent's spawn has registered
// its socket but the meta-flake `sync_agents` hasn't yet added
// its row.
let topo = topo_three_level();
assert_eq!(
resolve_recipient_in(&topo, "nobody", hive_sh4re::PARENT_RECIPIENT),
hive_sh4re::OPERATOR_RECIPIENT
);
}
#[test]
fn children_of_in_returns_direct_descendants() {
let topo = topo_three_level();
// alice's children: bob, carol.
let mut children = children_of_in(&topo, "alice");
children.sort();
assert_eq!(children, vec!["bob", "carol"]);
}
#[test]
fn children_of_in_manager_returns_root_level_agents() {
let topo = topo_three_level();
// Only alice's parent is manager; bob+carol are under alice.
let children = children_of_in(&topo, crate::lifecycle::MANAGER_NAME);
assert_eq!(children, vec!["alice"]);
}
#[test]
fn children_of_in_leaf_returns_empty() {
let topo = topo_three_level();
// bob and carol have no children.
assert!(children_of_in(&topo, "bob").is_empty());
assert!(children_of_in(&topo, "carol").is_empty());
}
#[test]
fn children_of_in_unknown_sender_returns_empty() {
let topo = topo_three_level();
assert!(children_of_in(&topo, "nobody").is_empty());
}
#[test]
fn top_level_agents_in_returns_parentless_agents() {
let topo = topo_three_level();
// Only the manager has no parent (alice/bob/carol all have parents).
let top = top_level_agents_in(&topo);
assert_eq!(top, vec![crate::lifecycle::MANAGER_NAME]);
}
#[test]
fn top_level_agents_in_multi_root_returns_all_parentless() {
let mut topo = topo_three_level();
// Simulate a second parentless agent alongside the manager.
topo.insert("orphan".to_owned(), None);
let mut top = top_level_agents_in(&topo);
top.sort();
let mut expected = vec![crate::lifecycle::MANAGER_NAME, "orphan"];
expected.sort_unstable();
assert_eq!(top, expected);
}
#[test]
fn top_level_agents_in_empty_topo_returns_empty() {
let topo = BTreeMap::new();
assert!(top_level_agents_in(&topo).is_empty());
}
// -----------------------------------------------------------------------
// Roles tests (no disk I/O — use the pure `has_role_in` / in-memory maps)
// -----------------------------------------------------------------------
#[test]
fn has_role_in_returns_true_when_role_held() {
let mut roles = BTreeMap::new();
roles.insert(
"alice".to_owned(),
vec![ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS.to_owned()],
);
assert!(has_role_in(
&roles,
"alice",
ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS
));
}
#[test]
fn has_role_in_returns_false_for_absent_agent() {
let roles: BTreeMap<String, Vec<String>> = BTreeMap::new();
assert!(!has_role_in(
&roles,
"alice",
ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS
));
}
#[test]
fn has_role_in_returns_false_for_empty_list() {
let mut roles = BTreeMap::new();
roles.insert("alice".to_owned(), vec![]);
assert!(!has_role_in(
&roles,
"alice",
ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS
));
}
/// Revoking a role must leave the key present with an empty list so
/// `reconcile_roles` does not re-seed it.
#[test]
fn set_role_revoke_keeps_empty_entry_as_tombstone() {
let mgr = crate::lifecycle::MANAGER_NAME;
// Build an in-memory roles map as set_role would see it after granting.
let mut roles: BTreeMap<String, Vec<String>> = BTreeMap::new();
roles.insert(
mgr.to_owned(),
vec![ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS.to_owned()],
);
// Simulate the revoke path of set_role (in-memory, no disk).
let list = roles.entry(mgr.to_owned()).or_default();
let held = list.iter().any(|r| r == ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS);
assert!(held);
list.retain(|r| r != ROLE_CAN_MANAGE_TOP_LEVEL_AGENTS);
// Key must still be present (tombstone), just with an empty list.
assert!(roles.contains_key(mgr), "empty entry must not be removed");
assert!(roles[mgr].is_empty());
}
/// `reconcile_roles` must not re-seed the manager when its entry exists
/// but is empty (operator explicitly revoked the role).
#[test]
fn reconcile_roles_in_does_not_reseed_after_explicit_revoke() {
let mgr = crate::lifecycle::MANAGER_NAME;
let agent_names = [mgr.to_owned(), "alice".to_owned()];
let mut roles: BTreeMap<String, Vec<String>> = BTreeMap::new();
// Tombstone: manager was seen before but all roles were revoked.
roles.insert(mgr.to_owned(), vec![]);
let mgr_present = agent_names.iter().any(|n| n == mgr);
let should_seed = mgr_present && !roles.contains_key(mgr);
// should_seed must be false because manager key is present (tombstone).
assert!(
!should_seed,
"reconcile_roles must not re-seed an explicit revoke"
);
}
/// `reconcile_roles` seeds the manager on first appearance (no prior entry).
#[test]
fn reconcile_roles_in_seeds_root_when_absent() {
let mgr = crate::lifecycle::MANAGER_NAME;
let agent_names = [mgr.to_owned(), "alice".to_owned()];
let roles: BTreeMap<String, Vec<String>> = BTreeMap::new(); // empty
let should_seed = agent_names.iter().any(|n| n == mgr) && !roles.contains_key(mgr);
assert!(should_seed, "reconcile_roles must seed manager when absent");
}
}