Watch
0
0
Fork
You've already forked hyperhive
0

hive-bash-mcp: count bash commands over OTEL in the daemon, drop the sqlite hand-off

This commit is contained in:
damocles 2026-11-18 19:44:18 +01:00 • committed by mara
commit 076df804e4
4 changed files with 100 additions and 184 deletions

View file

@ -32,7 +32,6 @@ mod router_todos;
mod schedule_timer;
mod serve_common;
mod state_entry_watch;
mod stats;
mod subagent_role_watch;
mod swarm_agent_commands;
mod swarm_agent_state;
@ -1031,7 +1030,6 @@ async fn handle_turn<S: Surface>(
unread,
});
bus.set_state(TurnState::Thinking);
let started_at = chrono::Utc::now().timestamp();
let started_instant = std::time::Instant::now();
let model_at_start = bus.model();
// Read-and-clear: this wake prompt is the one turn that gets to carry
@ -1064,7 +1062,6 @@ async fn handle_turn<S: Surface>(
let (open_threads, open_reminders) = S::post_turn_counts(socket).await;
let context_window = bus.api_context_window();
let row = serve_common::build_row(serve_common::TurnRowArgs {
started_at,
duration_ms,
model: model_at_start,
wake_from: from.clone(),

View file

@ -6,7 +6,7 @@
//! only the harness-only concepts: wall-clock turn duration as *this harness*
//! measures it, what woke the turn, its outcome classification, the loose-ends
//! backlog, sessions and their first turn's cost, context-window fill, the
//! tools a turn called (claude exports no tool-call counter), bash commands,
//! tools a turn called (claude exports no tool-call counter),
//! reminders, and the cost an ACP agent reports — claude's runtime reports none.
//!
//! Synchronous instruments, not observable ones: unlike hive-c0re's
@ -31,7 +31,6 @@
use std::collections::HashMap;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::Duration;
use opentelemetry::KeyValue;
@ -96,9 +95,6 @@ struct Instruments {
reported_cost: Counter<f64>,
/// Tool calls made, keyed by `tool` (`Skill:<skill>` for a skill).
tool_calls: Counter<u64>,
/// Shell commands run by bash tasks, keyed by `command`: the normalised
/// head the bash daemon records, not the full command line.
bash_commands: Counter<u64>,
/// Reminders scheduled and delivered, keyed by `event`.
reminders: Counter<u64>,
/// Input tokens of the first turn of a fresh claude session: what the
@ -153,7 +149,6 @@ pub fn record(row: &TurnStatRow, fresh_session: bool) {
for (tool, calls) in tool_call_counts(row.tool_call_breakdown_json.as_deref()) {
inst.tool_calls.add(calls, &[KeyValue::new("tool", tool)]);
}
record_new_bash_commands(inst, row.started_at);
}
/// The per-tool call counts a turn stored in `tool_call_breakdown_json`; a
@ -164,25 +159,6 @@ fn tool_call_counts(json: Option<&str>) -> Vec<(String, u64)> {
.unwrap_or_default()
}
/// Unix seconds up to which bash commands are already counted; `0` before the
/// first turn of this run.
static BASH_COUNTED_UNTIL: AtomicI64 = AtomicI64::new(0);
/// Count the bash commands recorded since the last call. The first call after
/// the harness starts counts only commands newer than `turn_started_at`, so a
/// restart does not count the whole history again.
fn record_new_bash_commands(inst: &Instruments, turn_started_at: i64) {
let now = chrono::Utc::now().timestamp();
let mut since = BASH_COUNTED_UNTIL.swap(now, Ordering::Relaxed);
if since == 0 {
since = turn_started_at.saturating_sub(1);
}
for (command, n) in crate::stats::bash_heads_since(since) {
inst.bash_commands
.add(n, &[KeyValue::new("command", command)]);
}
}
/// Count one reminder event, `scheduled` or `delivered`. No-op when OTEL isn't
/// configured, same as [`record`].
pub fn record_reminder(event: &'static str) {
@ -348,7 +324,6 @@ fn build() -> Option<Instruments> {
.build(),
reported_cost: meter.f64_counter("hyperhive.agent.cost.usage").build(),
tool_calls: meter.u64_counter("hyperhive.agent.tool.calls").build(),
bash_commands: meter.u64_counter("hyperhive.agent.bash.commands").build(),
reminders: meter.u64_counter("hyperhive.agent.reminders").build(),
first_turn_context: meter
.u64_gauge("hyperhive.agent.first_turn.context")

View file

@ -29,7 +29,6 @@ pub fn format_wake_prompt(from: &str, body: &str, redelivered: bool, interrupted
/// (`otel_turn_metrics::record`).
#[derive(Debug, Clone)]
pub struct TurnStatRow {
pub started_at: i64,
pub duration_ms: i64,
pub model: String,
pub wake_from: String,
@ -51,7 +50,6 @@ pub struct TurnStatRow {
/// `get_loose_ends` call before it's consumed — `Bus::take_tool_calls` resets
/// the counter, so there's only one chance to read it per turn.
pub struct TurnRowArgs<'a> {
pub started_at: i64,
pub duration_ms: i64,
pub model: String,
pub wake_from: String,
@ -68,7 +66,6 @@ pub struct TurnRowArgs<'a> {
#[must_use]
pub fn build_row(args: TurnRowArgs<'_>) -> TurnStatRow {
let TurnRowArgs {
started_at,
duration_ms,
model,
wake_from,
@ -101,7 +98,6 @@ pub fn build_row(args: TurnRowArgs<'_>) -> TurnStatRow {
Err(TurnError::Failed(_)) => "failed",
};
TurnStatRow {
started_at,
duration_ms,
model,
wake_from,
@ -149,7 +145,6 @@ mod build_row_tests {
tool_calls: &[(&str, u64)],
) -> super::TurnStatRow {
build_row(TurnRowArgs {
started_at: 10,
duration_ms: 2_000,
model: "opus".to_owned(),
wake_from: "todo".to_owned(),
@ -187,7 +182,7 @@ mod build_row_tests {
let _dir = crate::paths::harness_dir_guard();
let row = row_for(&Ok(false), &[("Bash", 3)]);
assert_eq!((row.started_at, row.duration_ms), (10, 2_000));
assert_eq!(row.duration_ms, 2_000);
assert_eq!(
(row.model.as_str(), row.wake_from.as_str()),
("opus", "todo")
@ -210,7 +205,6 @@ mod build_row_tests {
let bus = Bus::new();
bus.set_resolved_model(Some("claude-opus-4-8".to_owned()));
let row = build_row(TurnRowArgs {
started_at: 0,
duration_ms: 0,
model: "opus".to_owned(),
wake_from: "todo".to_owned(),

View file

@ -1,63 +0,0 @@
//! The shell-command heads the bash daemon records in the harness's `hyperhive-turn-stats.sqlite`,
//! read for the OTEL bash-command counter.
use std::path::PathBuf;
use rusqlite::{Connection, OpenFlags};
fn default_path() -> PathBuf {
crate::paths::harness_dir().join("hyperhive-turn-stats.sqlite")
}
/// The shell-command heads recorded after `since` (unix seconds, exclusive),
/// with how often each ran, for the OTEL bash-command counter. Reads the live
/// database read-only; a missing database or `bash_commands` table (no bash
/// task has run yet) is an empty list, not an error.
#[must_use]
pub fn bash_heads_since(since: i64) -> Vec<(String, u64)> {
let Ok(conn) = Connection::open_with_flags(default_path(), OpenFlags::SQLITE_OPEN_READ_ONLY)
else {
return Vec::new();
};
let _ = conn.busy_timeout(std::time::Duration::from_millis(500));
read_bash_heads_since(&conn, since).unwrap_or_default()
}
fn read_bash_heads_since(conn: &Connection, since: i64) -> rusqlite::Result<Vec<(String, u64)>> {
let mut stmt =
conn.prepare("SELECT head, COUNT(*) FROM bash_commands WHERE ts > ?1 GROUP BY head")?;
let rows = stmt.query_map([since], |row| {
Ok((
row.get::<_, String>(0)?,
u64::try_from(row.get::<_, i64>(1)?).unwrap_or(0),
))
})?;
rows.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use rusqlite::params;
/// The OTEL bash-command counter reads only the heads recorded after its
/// watermark, and a database without the table yields nothing.
#[test]
fn bash_heads_since_counts_only_newer_rows() {
let conn = Connection::open_in_memory().unwrap();
assert!(read_bash_heads_since(&conn, 0).is_err(), "no table yet");
conn.execute_batch("CREATE TABLE bash_commands (ts INTEGER NOT NULL, head TEXT NOT NULL);")
.unwrap();
for (ts, head) in [(10, "cargo"), (20, "cargo"), (30, "git"), (30, "cargo")] {
conn.execute(
"INSERT INTO bash_commands (ts, head) VALUES (?1, ?2)",
params![ts, head],
)
.unwrap();
}
let mut got = read_bash_heads_since(&conn, 10).unwrap();
got.sort();
assert_eq!(got, vec![("cargo".to_owned(), 2), ("git".to_owned(), 1)]);
assert!(read_bash_heads_since(&conn, 30).unwrap().is_empty());
}
}