drop the sqlite event log nothing reads, and the comments naming routes that are gone
This commit is contained in:
parent
6289b8d64b
commit
cbda9c162f
11 changed files with 71 additions and 305 deletions
|
|
@ -8,13 +8,11 @@
|
|||
//! future events; the dashboard JS deals with the cold-start case by
|
||||
//! showing "connecting…" until the first event arrives.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use chrono::Utc;
|
||||
use hive_claude::TokenUsage;
|
||||
use rusqlite::{Connection, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_wire::agent_inference::Source;
|
||||
use tokio::sync::broadcast;
|
||||
|
|
@ -25,38 +23,15 @@ use crate::harness_state::{
|
|||
};
|
||||
|
||||
const CHANNEL_CAPACITY: usize = 256;
|
||||
/// Path to the persisted event db. Overridable via `HYPERHIVE_EVENTS_DB`
|
||||
/// for dev / tests; otherwise derived from the agent's harness dir.
|
||||
fn events_db_path() -> PathBuf {
|
||||
std::env::var_os("HYPERHIVE_EVENTS_DB").map_or_else(
|
||||
|| crate::paths::harness_dir().join("hyperhive-events.sqlite"),
|
||||
PathBuf::from,
|
||||
)
|
||||
}
|
||||
|
||||
const SCHEMA: &str = "
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ts INTEGER NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_ts ON events (ts);
|
||||
";
|
||||
|
||||
/// Envelope carried over the broadcast channel: the `LiveEvent` itself
|
||||
/// plus a monotonic per-process seq stamped by `Bus::emit`. SSE consumers
|
||||
/// serialize this directly (seq becomes a sibling of the `kind` tag);
|
||||
/// clients use seq to dedupe their buffered live traffic against the
|
||||
/// snapshot/history responses (drop anything with `seq <= snapshot.seq`).
|
||||
/// serialize this directly (seq becomes a sibling of the `kind` tag).
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct BusEvent {
|
||||
pub seq: u64,
|
||||
/// Unix seconds at emit time. Serialized as a sibling of the `kind`
|
||||
/// tag so the agent terminal can render turn start/end times (and
|
||||
/// turn duration) on the live stream; history rows carry the same
|
||||
/// `ts` field sourced from the persisted `events.ts` column, so the
|
||||
/// renderer reads `ts` identically for live + scrollback.
|
||||
/// turn duration) on the live stream.
|
||||
pub ts: i64,
|
||||
#[serde(flatten)]
|
||||
pub event: LiveEvent,
|
||||
|
|
@ -86,9 +61,9 @@ pub enum LiveEvent {
|
|||
/// enums can't flatten a tag onto a primitive newtype, and serde
|
||||
/// fails serialization at runtime — silently, because the SSE
|
||||
/// handler's `filter_map(... .ok()? ...)` swallows the error, so a
|
||||
/// regression here goes unnoticed until the sqlite history shows
|
||||
/// `"null"` rows. The web UI's `note` renderer already reads
|
||||
/// `ev.text`, so the wire shape matches without a JS change.
|
||||
/// regression here goes unnoticed until a reader sees
|
||||
/// `"null"` rows. The `note` renderer reads `ev.text`, so the wire shape
|
||||
/// matches without a JS change.
|
||||
Note { text: String },
|
||||
/// Turn finished. `ok=false` means claude exited non-zero or the
|
||||
/// harness hit a transport error.
|
||||
|
|
@ -121,54 +96,8 @@ pub enum LiveEvent {
|
|||
TurnStateChanged { state: TurnState, since_unix: i64 },
|
||||
}
|
||||
|
||||
/// sqlite-backed event log. Wraps a `Connection` behind a `Mutex` so the
|
||||
/// `Bus` (which clones cheaply) shares one writer.
|
||||
struct EventStore {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
impl EventStore {
|
||||
fn open(path: &Path) -> rusqlite::Result<Self> {
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
let conn = Connection::open(path)?;
|
||||
crate::sqlite_writer::configure_wal(&conn)?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
Ok(Self {
|
||||
conn: Mutex::new(conn),
|
||||
})
|
||||
}
|
||||
|
||||
fn append(&self, event: &LiveEvent) -> rusqlite::Result<()> {
|
||||
let ts = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.ok()
|
||||
.and_then(|d| i64::try_from(d.as_secs()).ok())
|
||||
.unwrap_or(0);
|
||||
let kind = match event {
|
||||
LiveEvent::TurnStart { .. } => "turn_start",
|
||||
LiveEvent::Stream(_) => "stream",
|
||||
LiveEvent::Note { .. } => "note",
|
||||
LiveEvent::TurnEnd { .. } => "turn_end",
|
||||
LiveEvent::StatusChanged { .. } => "status_changed",
|
||||
LiveEvent::ModelChanged { .. } => "model_changed",
|
||||
LiveEvent::EffortChanged { .. } => "effort_changed",
|
||||
LiveEvent::TokenUsageChanged { .. } => "token_usage_changed",
|
||||
LiveEvent::TurnStateChanged { .. } => "turn_state_changed",
|
||||
};
|
||||
let payload = serde_json::to_string(event).unwrap_or_else(|_| "null".into());
|
||||
let conn = self.conn.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO events (ts, kind, payload_json) VALUES (?1, ?2, ?3)",
|
||||
params![ts, kind, payload],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Authoritative turn-loop state. The harness owns it; the web UI
|
||||
/// reads via `/api/state` and renders. Lives alongside the bus
|
||||
/// is published to the swarm queue for the swarm UI. Lives alongside the bus
|
||||
/// because everyone who has a `Bus` already has the right handle to
|
||||
/// poke the state on transitions.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
|
|
@ -196,13 +125,7 @@ pub struct Bus {
|
|||
/// Monotonic per-process counter stamped onto every `BusEvent`.
|
||||
/// Persisted nowhere — a harness restart resets seq to 0; clients
|
||||
/// always treat reconnect as "fresh state, fresh stream of seqs."
|
||||
/// Historical events served from sqlite carry no seq (they predate
|
||||
/// the live channel the seq is meant to dedupe against).
|
||||
event_seq: Arc<AtomicU64>,
|
||||
/// Persistent event log. `None` only if opening the sqlite db failed
|
||||
/// at construction — we keep going so the harness doesn't die on a
|
||||
/// missing state dir mount in dev / test scenarios.
|
||||
store: Option<Arc<EventStore>>,
|
||||
/// Current turn-loop state + since-when (unix seconds).
|
||||
state: Arc<Mutex<(TurnState, i64)>>,
|
||||
/// Model name passed to `claude --model`. Default `haiku`; a value the
|
||||
|
|
@ -229,8 +152,8 @@ pub struct Bus {
|
|||
/// `hyperhive-harness.json` (see `harness_state`), so the host can
|
||||
/// surface the status on the dashboard without a live socket call.
|
||||
rate_limited: Arc<AtomicBool>,
|
||||
/// One-shot: operator asked to reset the claude session (`POST
|
||||
/// /api/new-session`). Consumed at the *next* turn boundary by
|
||||
/// One-shot: operator asked to reset the claude session (the swarm
|
||||
/// UI's `/clear`). Consumed at the *next* turn boundary by
|
||||
/// `turn::drive_turn`, which archives the current session so the turn
|
||||
/// starts fresh. Deferred (not applied in the handler) so the archive
|
||||
/// never races a claude process mid-write — one claude per container,
|
||||
|
|
@ -258,7 +181,7 @@ pub struct Bus {
|
|||
post_compact_wake: Arc<Mutex<Option<String>>>,
|
||||
/// Stops the turn in flight, for a runtime that offers it (ACP). Set once
|
||||
/// by the serve loop when it builds the session; unset on claude, whose
|
||||
/// turn `/api/cancel` stops by signalling the `claude` process.
|
||||
/// turn the swarm UI's cancel stops by signalling the `claude` process.
|
||||
turn_canceller: Arc<OnceLock<hive_runtime::Canceller>>,
|
||||
/// Current fresh-claude-session id (FK to `sessions.id`). Set by the
|
||||
/// bin loop after minting a session row on a fresh start; stamped onto
|
||||
|
|
@ -306,18 +229,10 @@ pub struct Bus {
|
|||
}
|
||||
|
||||
impl Bus {
|
||||
/// Open the events db (path from `events_db_path()`). On failure, fall back
|
||||
/// to a no-store bus — the harness still works, just without persistent history.
|
||||
/// A bus with no subscribers and the model, effort and rate-limit state the harness
|
||||
/// last recorded.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
let path = events_db_path();
|
||||
let store = match EventStore::open(&path) {
|
||||
Ok(s) => Some(Arc::new(s)),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = ?e, path = %path.display(), "events db open failed; running without history");
|
||||
None
|
||||
}
|
||||
};
|
||||
let (tx, _) = broadcast::channel(CHANNEL_CAPACITY);
|
||||
let (initial_model, model_source) = local_model(configured_model());
|
||||
let (initial_effort, effort_source) = local_effort(configured_effort());
|
||||
|
|
@ -328,7 +243,6 @@ impl Bus {
|
|||
Self {
|
||||
tx: Arc::new(tx),
|
||||
event_seq: Arc::new(AtomicU64::new(0)),
|
||||
store,
|
||||
state: Arc::new(Mutex::new((TurnState::Idle, Utc::now().timestamp()))),
|
||||
model: Arc::new(Mutex::new(initial_model)),
|
||||
effort: Arc::new(Mutex::new(initial_effort)),
|
||||
|
|
@ -368,7 +282,7 @@ impl Bus {
|
|||
self.turn_canceller.get()
|
||||
}
|
||||
|
||||
/// Request a session reset (operator `POST /api/new-session`). Deferred:
|
||||
/// Request a session reset (the swarm UI's `/clear`). Deferred:
|
||||
/// the flag is consumed at the next turn boundary by `drive_turn`, which
|
||||
/// archives the current session so no claude process is mid-write when the
|
||||
/// file is renamed. Idempotent — two clicks before the next turn still
|
||||
|
|
@ -766,10 +680,9 @@ impl Bus {
|
|||
}
|
||||
|
||||
/// Broadcast a status flip (online / `needs_login_idle` / `rate_limited`).
|
||||
/// Called by the bin entry points + `turn::wait_for_login` + the
|
||||
/// `/api/logout` handler — every site that mutates the
|
||||
/// `Arc<Mutex<LoginState>>` should also call this so the web UI
|
||||
/// drops its periodic /api/state poll while a turn loop is running.
|
||||
/// Called by the bin entry points + `turn::wait_for_login` + the login
|
||||
/// watch — every site that mutates the `Arc<Mutex<LoginState>>` should
|
||||
/// also call this so the status the swarm reads follows it.
|
||||
///
|
||||
/// `hyperhive-harness.json` persists across harness restarts so the
|
||||
/// host-side dashboard can render the status without a live socket call:
|
||||
|
|
@ -830,11 +743,6 @@ impl Bus {
|
|||
}
|
||||
|
||||
pub fn emit(&self, event: LiveEvent) {
|
||||
if let Some(store) = &self.store
|
||||
&& let Err(e) = store.append(&event)
|
||||
{
|
||||
tracing::warn!(error = ?e, "events: append failed");
|
||||
}
|
||||
let envelope = BusEvent {
|
||||
seq: self.next_seq(),
|
||||
ts: Utc::now().timestamp(),
|
||||
|
|
@ -902,8 +810,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn bus_event_serializes_ts_and_seq_beside_kind() {
|
||||
// Live SSE frame: same `ts` sibling as history (plus `seq`), so the
|
||||
// renderer is path-agnostic between live + scrollback.
|
||||
// Live SSE frame: `ts` and `seq` are siblings of `kind`.
|
||||
let v = serde_json::to_value(BusEvent {
|
||||
seq: 7,
|
||||
ts: 1_700_000_000,
|
||||
|
|
|
|||
|
|
@ -33,8 +33,7 @@ pub fn default_dir() -> PathBuf {
|
|||
/// exactly these to force re-login while preserving session-history files —
|
||||
/// so boot detection ([`has_session`]) and logout agree by construction.
|
||||
/// Rationale + the previous wholesale-wipe shape we replaced live in
|
||||
/// `docs/4-implementation/web-ui/agent-page.md::Per-agent endpoints`
|
||||
/// (the `/api/logout` bullet).
|
||||
/// the login watch (`login_watch.rs`).
|
||||
///
|
||||
/// `.credentials.json` is the actual OAuth session; `mcp-needs-auth-cache.json`
|
||||
/// is claude-code's MCP-auth cache and a weaker signal. Both are kept in the
|
||||
|
|
@ -168,7 +167,7 @@ pub async fn wait_for_login(
|
|||
);
|
||||
// Announce `needs_login_idle` to the bus so
|
||||
// `hyperhive-harness.json` records it on every entry path —
|
||||
// cold-boot, 401-mid-turn, and `/api/logout`. The host reads that
|
||||
// cold-boot, 401-mid-turn, and the login watch's logout. The host reads that
|
||||
// file to surface `needs_login` on the dashboard. Idempotent —
|
||||
// re-entering this function after a transient operator action
|
||||
// rewrites the same on-disk state.
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
//! while waiting ([`crate::claude_credentials`]).
|
||||
//! - A store that answers "nothing stored" after a version was installed here
|
||||
//! means the operator deleted the stored login: the agent is logged out as
|
||||
//! `/api/logout` does it, and the recorded version is forgotten so the next
|
||||
//! the harness does it, and the recorded version is forgotten so the next
|
||||
//! login installs.
|
||||
//! - A read that fails does nothing. A store that cannot be reached says
|
||||
//! nothing about the login, and logging out on it would turn a store restart
|
||||
|
|
|
|||
|
|
@ -524,7 +524,7 @@ async fn serve_main<S: Surface>(socket: &Path, poll_ms: u64) -> Result<()> {
|
|||
tokio::spawn(swarm_inference::run(bus.clone()));
|
||||
// The permissions the swarm grants this agent, read before each turn.
|
||||
tokio::spawn(swarm_permissions::run());
|
||||
// Set by the web UI's `/api/cancel` on a successful SIGINT, read-and-
|
||||
// Set by a cancel (the swarm UI's cancel command) on a successful SIGINT, read-and-
|
||||
// cleared by `handle_turn` before building the next wake prompt — see
|
||||
// `hive_sh4re::inbox::INTERRUPTED_HINT`. Shared between the web server task and
|
||||
// the serve loop the same way `bus`/`todo_wake` are.
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
//!
|
||||
//! All agents (including the manager `root`) use `/agents/{label}/state`
|
||||
//! for agent-owned durable notes, and `/agents/{label}/harness` for
|
||||
//! harness-internal files (`hyperhive-events.sqlite`, `hyperhive-model`, etc.)
|
||||
//! harness-internal files (`hyperhive-turn-stats.sqlite`, `hyperhive-model`, etc.)
|
||||
//! that should not clutter what claude sees as "my notes dir".
|
||||
//! Claude credentials live at `$HOME/.claude` (resolves to
|
||||
//! `/home/<agent-name>/.claude` because the harness service runs as a
|
||||
|
|
@ -28,7 +28,7 @@ pub fn state_dir() -> PathBuf {
|
|||
}
|
||||
|
||||
/// Harness-internal state directory. Holds files the harness owns
|
||||
/// (`hyperhive-events.sqlite`, `hyperhive-turn-stats.sqlite`,
|
||||
/// (`hyperhive-turn-stats.sqlite`,
|
||||
/// `hyperhive-model`) so they do not appear inside the agent-visible
|
||||
/// `/agents/{label}/state` tree. Delegates to the shared canonical
|
||||
/// resolver in `hive_agent_sock::paths` so the harness + every
|
||||
|
|
@ -41,8 +41,8 @@ pub fn harness_dir() -> PathBuf {
|
|||
}
|
||||
|
||||
/// Consolidated harness-local state db — todos + reminders, one table
|
||||
/// each — mutable per-agent state the harness owns, kept out of the
|
||||
/// append-only `hyperhive-events.sqlite` sink. Each store's `open()` only
|
||||
/// each — mutable per-agent state the harness owns, kept apart
|
||||
/// from the append-only turn-stats db. Each store's `open()` only
|
||||
/// applies its own `CREATE TABLE IF NOT EXISTS` against this same path
|
||||
/// (see their call sites), so distinct table names keep them from
|
||||
/// colliding without needing a per-store path wrapper here.
|
||||
|
|
|
|||
|
|
@ -1,99 +1,10 @@
|
|||
//! Shared connection setup for the harness's own sqlite writers.
|
||||
//!
|
||||
//! The default rollback journal costs an fsync per commit and takes an
|
||||
//! exclusive lock, so a write that overlaps a read on another connection (the
|
||||
//! stats page, the hourly vacuum) fails at once with `SQLITE_BUSY`. WAL with
|
||||
//! `synchronous=NORMAL` removes the per-row fsync and lets readers and the
|
||||
//! writer overlap, and the busy timeout makes the remaining writer-vs-writer
|
||||
//! overlap wait instead of dropping the row.
|
||||
//!
|
||||
//! WAL is only for databases that nothing outside the agent reads: a
|
||||
//! read-only connection to a WAL database needs the `-wal` and `-shm`
|
||||
//! sidecars to exist or be creatable, and hive-c0re reads as another uid
|
||||
//! across the agent-owned harness dir. Such a database takes just
|
||||
//! [`BUSY_TIMEOUT`].
|
||||
//! A write that overlaps another connection's lock (the stats page, the hourly
|
||||
//! vacuum) fails at once with `SQLITE_BUSY` unless the connection has a busy
|
||||
//! timeout, so writers set [`BUSY_TIMEOUT`] to wait instead of dropping the row.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rusqlite::Connection;
|
||||
|
||||
/// How long a writer waits on a locked database before giving up.
|
||||
pub const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Put `conn` into WAL mode with `synchronous=NORMAL` and a busy timeout.
|
||||
///
|
||||
/// The timeout is set first so the journal-mode switch, which needs a lock,
|
||||
/// waits too. `journal_mode` persists in the database file; the other two are
|
||||
/// per connection, so every writer connection calls this.
|
||||
///
|
||||
/// When sqlite answers the switch with the old mode (it does that, not an
|
||||
/// error, on a filesystem that cannot do WAL), this logs a warning and leaves
|
||||
/// the database in that mode: a working rollback-journal database beats no
|
||||
/// database.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Propagates sqlite pragma failures.
|
||||
pub fn configure_wal(conn: &Connection) -> rusqlite::Result<()> {
|
||||
conn.busy_timeout(BUSY_TIMEOUT)?;
|
||||
let mode =
|
||||
conn.pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get::<_, String>(0))?;
|
||||
if !mode.eq_ignore_ascii_case("wal") {
|
||||
tracing::warn!(%mode, "sqlite journal_mode stayed put instead of switching to wal");
|
||||
}
|
||||
conn.pragma_update(None, "synchronous", "NORMAL")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn configure_wal_sets_wal_normal_sync_and_busy_timeout() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let conn = Connection::open(dir.path().join("w.sqlite")).unwrap();
|
||||
configure_wal(&conn).unwrap();
|
||||
|
||||
let mode: String = conn
|
||||
.query_row("PRAGMA journal_mode", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
let sync: i64 = conn
|
||||
.query_row("PRAGMA synchronous", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
let busy: i64 = conn
|
||||
.query_row("PRAGMA busy_timeout", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(mode, "wal");
|
||||
assert_eq!(sync, 1, "NORMAL");
|
||||
assert_eq!(busy, 5000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configure_wal_keeps_a_database_that_cannot_switch_usable() {
|
||||
// An in-memory database cannot switch to WAL; sqlite answers "memory".
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
configure_wal(&conn).unwrap();
|
||||
let mode: String = conn
|
||||
.query_row("PRAGMA journal_mode", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(mode, "memory");
|
||||
conn.execute_batch("CREATE TABLE t(x); INSERT INTO t VALUES (1)")
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_connection_still_sees_committed_rows() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("w.sqlite");
|
||||
let writer = Connection::open(&path).unwrap();
|
||||
configure_wal(&writer).unwrap();
|
||||
writer.execute_batch("CREATE TABLE t(x)").unwrap();
|
||||
let reader = Connection::open(&path).unwrap();
|
||||
configure_wal(&reader).unwrap();
|
||||
writer.execute("INSERT INTO t VALUES (1)", []).unwrap();
|
||||
let n: i64 = reader
|
||||
.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(n, 1);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -427,7 +427,7 @@ fn acp_permits(ask: &PermissionAsk<'_>, web: bool) -> bool {
|
|||
/// the percent policy — including the pre-compaction checkpoint turn). This
|
||||
/// layer wraps it with the two hyperhive-specific concerns:
|
||||
///
|
||||
/// - **Session reset (pre-turn)** — an operator reset (`/api/new-session`) or
|
||||
/// - **Session reset (pre-turn)** — an operator reset (the swarm UI's `/clear`) or
|
||||
/// the auto-reset heuristic (context large AND prompt cache gone cold)
|
||||
/// archives the current session at this turn boundary so the run starts
|
||||
/// fresh. The two are mutually exclusive. This is deliberately *not* part of
|
||||
|
|
@ -445,7 +445,7 @@ pub async fn drive_turn(
|
|||
session: &AgentSession,
|
||||
) -> TurnOutcome {
|
||||
if bus.take_session_reset() {
|
||||
// Operator-requested (deferred from `POST /api/new-session`).
|
||||
// Operator-requested (deferred from the swarm UI's `/clear`).
|
||||
bus.emit(LiveEvent::Note {
|
||||
text: "operator: resetting session — archiving before this turn".into(),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
//! Agent-side cleanup of this agent's own harness artifacts: completed
|
||||
//! bash-task files and verbose `stream` event rows.
|
||||
//! bash-task files, delivered reminders and acked todos, and the event log an
|
||||
//! earlier harness wrote.
|
||||
//!
|
||||
//! Runs IN the harness (not host-side in hive-c0re) because the files are
|
||||
//! owned by the agent user. Under privsep hive-c0re runs as the unprivileged
|
||||
//! `hive-core` user and cannot delete agent-owned files — the old host-side
|
||||
//! sweeps hit `PermissionDenied` on the bash-task trio and an
|
||||
//! attempt-to-write-a-readonly-database error on `events.sqlite`. The harness
|
||||
//! attempt-to-write-a-readonly-database error on a harness database. The harness
|
||||
//! owns these paths, so the deletes succeed here.
|
||||
//!
|
||||
//! Trade-off (accepted — issue tracker "perms borked"): a misbehaving harness
|
||||
|
|
@ -17,16 +18,10 @@
|
|||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use rusqlite::{Connection, Result, params};
|
||||
|
||||
/// How often the sweep runs.
|
||||
const VACUUM_INTERVAL: Duration = Duration::from_hours(1);
|
||||
/// Keep completed bash-task files this long before deleting their trio.
|
||||
const BASH_KEEP_SECS: i64 = 48 * 3600;
|
||||
/// Keep verbose `stream` event rows this long before pruning. Other event
|
||||
/// kinds are never deleted by this sweep — they carry the semantic per-turn
|
||||
/// history the operator scrolls back through.
|
||||
const STREAM_KEEP_SECS: i64 = 14 * 24 * 3600;
|
||||
/// Keep delivered (soft-deleted, `sent_at` set) reminder rows this long
|
||||
/// before reaping them — same window as `STREAM_KEEP_SECS`, kept around
|
||||
/// only to serve the trailing-window `ReminderRollup` stats.
|
||||
|
|
@ -41,7 +36,7 @@ const TODO_ACKED_KEEP_SECS: i64 = 30 * 24 * 3600;
|
|||
const TERMINAL_STATUSES: &[&str] = &["done", "timed_out", "interrupted"];
|
||||
|
||||
/// Background loop: hourly, prune this agent's stale bash-task files and
|
||||
/// verbose event rows. Detached task — runs for the harness's lifetime;
|
||||
/// the event log an earlier harness left behind. Detached task — runs for the harness's lifetime;
|
||||
/// errors are logged, never fatal.
|
||||
pub async fn run() {
|
||||
loop {
|
||||
|
|
@ -62,14 +57,7 @@ fn sweep_once() {
|
|||
}
|
||||
}
|
||||
|
||||
let events_db = harness.join("hyperhive-events.sqlite");
|
||||
if events_db.exists() {
|
||||
match vacuum_events(&events_db) {
|
||||
Ok(0) => {}
|
||||
Ok(n) => tracing::info!(removed = n, "events vacuum"),
|
||||
Err(e) => tracing::warn!(error = ?e, "events vacuum failed"),
|
||||
}
|
||||
}
|
||||
remove_old_event_log(&harness);
|
||||
|
||||
let state_db = crate::paths::state_db();
|
||||
if state_db.exists() {
|
||||
|
|
@ -87,8 +75,7 @@ fn sweep_once() {
|
|||
}
|
||||
|
||||
/// Reap delivered reminder rows older than [`REMINDER_KEEP_SECS`] via the
|
||||
/// typed store API (own short-lived connection — mirrors `vacuum_events`'s
|
||||
/// own connection to `events.sqlite` rather than sharing the harness's live
|
||||
/// typed store API (own short-lived connection rather than the harness's live
|
||||
/// `Reminders` handle).
|
||||
fn vacuum_reminders(path: &Path) -> anyhow::Result<usize> {
|
||||
let store = crate::reminders::Reminders::open(path)?;
|
||||
|
|
@ -165,15 +152,21 @@ fn delete_trio(dir: &Path, stem: &str) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Prune verbose `stream` event rows older than [`STREAM_KEEP_SECS`] from the
|
||||
/// agent's `events.sqlite`. Returns the number of rows deleted.
|
||||
fn vacuum_events(path: &Path) -> Result<u64> {
|
||||
let conn = Connection::open(path)?;
|
||||
crate::sqlite_writer::configure_wal(&conn)?;
|
||||
let cutoff = chrono::Utc::now().timestamp() - STREAM_KEEP_SECS;
|
||||
let removed = conn.execute(
|
||||
"DELETE FROM events WHERE kind = 'stream' AND ts < ?1",
|
||||
params![cutoff],
|
||||
)?;
|
||||
Ok(u64::try_from(removed).unwrap_or(0))
|
||||
/// Delete the sqlite event log (and its WAL files) that harnesses used to
|
||||
/// write for the per-agent page's history. Nothing reads or writes it now.
|
||||
fn remove_old_event_log(harness: &Path) {
|
||||
for name in [
|
||||
"hyperhive-events.sqlite",
|
||||
"hyperhive-events.sqlite-wal",
|
||||
"hyperhive-events.sqlite-shm",
|
||||
] {
|
||||
let path = harness.join(name);
|
||||
match std::fs::remove_file(&path) {
|
||||
Ok(()) => tracing::info!(path = %path.display(), "removed the old event log"),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => {
|
||||
tracing::warn!(path = %path.display(), error = %e, "removing the old event log failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use super::LoginStateCell;
|
|||
/// the credential files (via [`crate::login::clear_session`]) and flip
|
||||
/// `LoginState::NeedsLogin`; `by` heads the Note. Returns what was wiped, for the response.
|
||||
pub(crate) async fn force_logout(login: &LoginStateCell, bus: &Bus, by: &str) -> String {
|
||||
// Step 1: SIGINT claude (best-effort, matches `post_cancel_turn`).
|
||||
// Step 1: SIGINT claude (best-effort, as a cancel does).
|
||||
let _ = super::sigint_claude();
|
||||
// Step 2: delete OAuth credential files only — login::clear_session owns
|
||||
// the file set and preserves session-history files alongside them.
|
||||
|
|
@ -35,7 +35,7 @@ pub(crate) async fn force_logout(login: &LoginStateCell, bus: &Bus, by: &str) ->
|
|||
}
|
||||
|
||||
/// Human-readable summary of a [`crate::login::ClearedSession`] outcome for
|
||||
/// the `/api/logout` response + note. Deliberately distinguishes "nothing to
|
||||
/// the login watch's note. Deliberately distinguishes "nothing to
|
||||
/// delete" from "something's there but we couldn't delete it" — both leave
|
||||
/// `wiped` empty, but only the former is actually "already logged out";
|
||||
/// conflating them would report a stuck undeletable `.credentials.json` as
|
||||
|
|
|
|||
|
|
@ -1,13 +1,12 @@
|
|||
//! Per-container HTTP UI. SPA shape: `GET /` returns a static shell;
|
||||
//! `GET /static/*` serves CSS + JS; `GET /api/state` returns the page
|
||||
//! state as JSON; the JS app renders. Live events stream on
|
||||
//! `/events/stream`. Action POSTs return either a
|
||||
//! 303 Redirect (for browsers that submit the form normally) or just
|
||||
//! 200 OK — the JS app re-fetches `/api/state` afterwards.
|
||||
//! Per-container HTTP server: the stats and screen pages (`GET /stats`,
|
||||
//! `GET /screen`, `GET /static/*`), `GET /` redirecting to `/stats`, the small
|
||||
//! JSON the dashboard card and those pages read (`/api/state`,
|
||||
//! `/api/dashboard-state`, `/api/stats`) and the live event stream
|
||||
//! `/events/stream`.
|
||||
//!
|
||||
//! Handlers are split by concern into the submodules below; this file owns the
|
||||
//! shared [`AppState`], the listener + router wiring in [`serve`], and a couple
|
||||
//! of small shared helpers ([`error_response`], [`SOCKET_FETCH_TIMEOUT`]).
|
||||
//! shared [`AppState`], the listener + router wiring in [`serve`], and the
|
||||
//! claude-signalling helpers the cancel command and the login watch share.
|
||||
|
||||
mod auth;
|
||||
pub(crate) use auth::force_logout;
|
||||
|
|
@ -230,8 +229,8 @@ fn read_gui_vnc_port() -> Option<u16> {
|
|||
std::env::var("HIVE_GUI_VNC_PORT").ok()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Outcome of [`sigint_claude`] — shared by `/api/cancel` and `/api/logout`
|
||||
/// so both can render the same three cases.
|
||||
/// Outcome of [`sigint_claude`] — shared by the cancel command and the login watch's
|
||||
/// logout so both can render the same three cases.
|
||||
enum SigintOutcome {
|
||||
/// The tracked pid was signalled.
|
||||
Signalled,
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ fn read_own_status() -> (Option<String>, Option<i64>) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Build the navigation link list for the agent page header. URLs
|
||||
/// Build the navigation link list for the dashboard card's icon strip. URLs
|
||||
/// are paths (relative) for `Container` targets and absolute
|
||||
/// for `External`; the frontend resolves each against its `kind`
|
||||
/// against the right base so the backend never has to guess the
|
||||
|
|
|
|||
Loading…
Reference in a new issue