refactor(hive-agent): split the forge notification poller into its own crate
The poller was a `tokio::spawn` inside the `hive-agent` serve loop. It never needed anything from that loop except a socket path, so being in-process bought nothing and cost two things: a harness restart took forge notifications down with it, and the whole forge/HTTP dependency tree was linked into the serve-loop binary. It is now `hive-forge-notify`, a per-agent daemon with its own systemd unit, a sibling of `hive-bash-daemon` and `hive-matrix-daemon`. Same contract as those two: it reaches the harness only by upserting todos on the in-agent socket, and nowhere else. The module moves verbatim (`notify.rs`) — the formatters, the activation gates, the dedupe map and all 33 tests are unchanged. Only the socket call sites are rewritten, onto a small local `todo_client` rather than the harness's. That mirrors what both sibling daemons already do, and the etiquette differs on purpose: the harness's client carries a 60s backoff schedule sized to ride out a hive-c0re restart, which its callers need because they have no retry of their own. This poller's two call sites both sit inside the 30s poll loop and both treat a failure as "leave the thread unread, try next tick", so the poll interval already is the retry; a second backoff would only stack sleeps and delay the rest of the batch. The unit is `Restart=on-failure`, not `always`. An agent with no forge account is a supported configuration and the poller reports it by logging why and exiting 0 — under `always` that clean exit would be a restart loop on every forge-less agent. `forgejo-api`, `url` and `time` drop out of `hive-agent`'s dependencies with the module. Also corrects docs that outlived the code they described: the persisted `forge_cursor` field is long gone (forge's own read-state is the durable record of what has been delivered), but `docs/persistence.md` and the `harness_state` module docs still documented it as live.
This commit is contained in:
parent
d153d1d35f
commit
246c9471b1
18 changed files with 301 additions and 48 deletions
31
hive-forge-notify/Cargo.toml
Normal file
31
hive-forge-notify/Cargo.toml
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
[package]
|
||||
name = "hive-forge-notify"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
readme = "README.md"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
forgejo-api.workspace = true
|
||||
hive-agent-sock.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
time.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
url.workspace = true
|
||||
|
||||
# `hive-forge-notify` — long-running per-agent Forgejo notification
|
||||
# poller. Was a `tokio::spawn` inside the `hive-agent` serve loop; it is
|
||||
# its own process now so a harness restart (or a claude-side stall) does
|
||||
# not take forge notifications down with it, and so its dependency tree
|
||||
# (forgejo-api, reqwest, time, url) is not linked into the serve-loop
|
||||
# binary. Talks to the harness only over the in-agent todo socket.
|
||||
[[bin]]
|
||||
name = "hive-forge-notify"
|
||||
path = "src/main.rs"
|
||||
44
hive-forge-notify/README.md
Normal file
44
hive-forge-notify/README.md
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
# hive-forge-notify
|
||||
|
||||
Per-agent Forgejo notification poller: a long-running daemon
|
||||
(`hive-forge-notify`) that watches the agent's unread notification list
|
||||
and turns each thread into a todo the harness surfaces in
|
||||
`get_loose_ends`. This is why an agent wakes up when someone comments
|
||||
on its issue or requests its review.
|
||||
|
||||
## When to use it
|
||||
|
||||
Look here when changing what a forge notification *says* when it
|
||||
reaches an agent, or when it reaches one at all: the poll cadence, the
|
||||
self-echo filter, the comment / review / new-item / state-change
|
||||
wrapper formats, body-excerpt truncation, and the assigned-issue
|
||||
rollup all live in `notify.rs`. The behaviour contract — activation
|
||||
gates, filtering rules, the review-request override — is documented in
|
||||
[`docs/forge.md`](../docs/forge.md), "Notification poller".
|
||||
|
||||
## Shape
|
||||
|
||||
One bin, three modules:
|
||||
|
||||
- **`main.rs`** — argument-free entry point. Reads `HIVE_AGENT_SOCKET`,
|
||||
initialises tracing, hands off to `notify::run`.
|
||||
- **`notify.rs`** — the poller: forge client setup, the 30s loop, the
|
||||
formatters, mark-read, and the in-process delivery-dedupe map.
|
||||
- **`todo_client.rs`** — one-shot JSON-line client for the harness's
|
||||
in-agent socket. No retry schedule of its own; see the module doc.
|
||||
|
||||
## Why it is a separate process
|
||||
|
||||
It used to be a `tokio::spawn` inside the `hive-agent` serve loop. It
|
||||
never needed anything from the serve loop except a socket path, and
|
||||
running it in-process meant a harness restart also took forge
|
||||
notifications down, and linked the whole forge/HTTP dependency tree
|
||||
(`forgejo-api`, `reqwest`, `time`, `url`) into the serve-loop binary.
|
||||
It is now a sibling daemon alongside `hive-bash-daemon` and
|
||||
`hive-matrix-daemon`, with the same contract: it talks to the harness
|
||||
over the in-agent todo socket and nowhere else.
|
||||
|
||||
Forge's own read-state is the durable, cross-rebuild record of what has
|
||||
been delivered — there is no persisted cursor to migrate or corrupt. A
|
||||
restarted poller re-scans only the genuinely-still-unread set, which is
|
||||
tiny by construction because delivery marks the thread read.
|
||||
38
hive-forge-notify/src/main.rs
Normal file
38
hive-forge-notify/src/main.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
//! `hive-forge-notify` binary — long-running per-agent Forgejo
|
||||
//! notification poller. Polls the agent's unread notification list,
|
||||
//! formats each thread into a short summary, and pushes it as a todo
|
||||
//! (loose-ends v2) on the harness's in-agent socket so claude drives a
|
||||
//! turn to handle it.
|
||||
//!
|
||||
//! Takes no arguments: everything comes from the environment the
|
||||
//! per-agent systemd unit provides — `HIVE_FORGE_URL` (forwarded into
|
||||
//! every container by the meta flake), `HYPERHIVE_STATE_DIR` (where the
|
||||
//! agent's `forge-token` lives) and `HIVE_AGENT_SOCKET` (the harness's
|
||||
//! todo socket). When the forge is not configured for this agent the
|
||||
//! poller logs why and exits 0 — the unit is `Restart=on-failure`, so a
|
||||
//! forge-less agent settles instead of restart-looping.
|
||||
|
||||
mod notify;
|
||||
mod todo_client;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_env("RUST_LOG")
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
|
||||
)
|
||||
.init();
|
||||
|
||||
let socket = std::env::var_os("HIVE_AGENT_SOCKET").map_or_else(
|
||||
|| std::path::PathBuf::from(hive_agent_sock::DEFAULT_AGENT_SOCKET),
|
||||
std::path::PathBuf::from,
|
||||
);
|
||||
|
||||
tracing::info!(socket = %socket.display(), "hive-forge-notify starting");
|
||||
|
||||
// Returns only when the forge is not configured (or the token never
|
||||
// arrives); otherwise loops forever. Either way there is nothing left
|
||||
// for this process to do, so fall off the end and exit 0.
|
||||
notify::run(socket).await;
|
||||
}
|
||||
1722
hive-forge-notify/src/notify.rs
Normal file
1722
hive-forge-notify/src/notify.rs
Normal file
File diff suppressed because it is too large
Load diff
86
hive-forge-notify/src/todo_client.rs
Normal file
86
hive-forge-notify/src/todo_client.rs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
//! One-shot JSON-line client for the harness's in-agent socket
|
||||
//! (`HIVE_AGENT_SOCKET`) — the only channel this daemon has back into the
|
||||
//! harness.
|
||||
//!
|
||||
//! Deliberately has no retry/backoff schedule. The two callers are both
|
||||
//! inside the 30s poll loop and both treat a failed request as "leave the
|
||||
//! thread unread and try again next tick", so the poll interval *is* the
|
||||
//! retry — a second, in-request backoff would only stack sleeps on top of
|
||||
//! it and delay the rest of the batch. That is the opposite trade-off from
|
||||
//! the serve loop's client, which rides out a hive-c0re restart because
|
||||
//! its callers have no natural retry of their own.
|
||||
//!
|
||||
//! Each sibling per-agent daemon carries its own small helper like this
|
||||
//! one rather than sharing the harness's, so a daemon's socket etiquette
|
||||
//! stays visible in the crate that depends on it.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
/// Write one JSON request line to `socket` and read the single JSON
|
||||
/// response line back.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the socket cannot be connected, if the request
|
||||
/// cannot be serialised, if the write or read fails, if the server closes
|
||||
/// without responding, or if the response does not deserialise into
|
||||
/// `Resp`.
|
||||
pub async fn request<Req, Resp>(socket: &Path, req: &Req) -> Result<Resp>
|
||||
where
|
||||
Req: Serialize + ?Sized,
|
||||
Resp: DeserializeOwned,
|
||||
{
|
||||
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
|
||||
.with_context(|| format!("write to {}", socket.display()))?;
|
||||
write
|
||||
.flush()
|
||||
.await
|
||||
.with_context(|| format!("flush {}", socket.display()))?;
|
||||
|
||||
let mut reader = BufReader::new(read);
|
||||
let mut line = String::new();
|
||||
let read_bytes = reader
|
||||
.read_line(&mut line)
|
||||
.await
|
||||
.with_context(|| format!("read from {}", socket.display()))?;
|
||||
if read_bytes == 0 || line.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"{} closed the connection without responding",
|
||||
socket.display()
|
||||
));
|
||||
}
|
||||
Ok(serde_json::from_str(line.trim())?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::request;
|
||||
|
||||
/// Connecting to a path that does not exist is an error, not a hang —
|
||||
/// the caller (a poll tick) needs it to come back promptly so the rest
|
||||
/// of the batch still runs.
|
||||
#[tokio::test]
|
||||
async fn missing_socket_is_an_error() {
|
||||
let bogus = std::path::Path::new("/nonexistent/hive/agent.sock");
|
||||
let err = request::<(), serde_json::Value>(bogus, &())
|
||||
.await
|
||||
.expect_err("connect to a non-existent socket must fail");
|
||||
let msg = format!("{err:#}");
|
||||
assert!(msg.contains("connect to"), "missing connect context: {msg}");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue