Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Goals API: typed predicates, verdicts, loop with lease, routes, goal_propose (0.6.5 B.1) (#231)
Oleksandr Ivanchenkoa2462c5699db
diff --git a/src/db/goals.rs b/src/db/goals.rsnew file mode 100644index 00000000..b667f19e--- /dev/null+++ b/src/db/goals.rs@@ -0,0 +1,1106 @@+//! Goals (docs/mission-control.md §22): what the person wants to stay true, the checks kwant+//! re-runs on a schedule, what they observed, a timeline, and the fix tasks a confirmed failure+//! opened. Add-only: new tables, no change to an existing one (fix tasks are linked through+//! `goal_fix_tasks`, so `tasks` keeps its `source_kind` CHECK and isn't rebuilt). Older binaries+//! ignore all of it, and running the migration twice changes nothing. Times are milliseconds.+//! No foreign keys: `foreign_keys` is on for one pooled connection only, so deleting a goal+//! removes its rows itself, in one transaction.++use super::{Database, DbError};+use serde_json::{json, Value};+use sqlx::{FromRow, SqliteConnection};+use uuid::Uuid;++/// Open drafts (bot proposals waiting for the person) one space can hold.+pub const MAX_DRAFTS: i64 = 3;+/// Observations kept per goal, newest first.+pub const KEEP_OBSERVATIONS: i64 = 200;+/// Timeline events kept per goal, newest first.+pub const KEEP_EVENTS: i64 = 500;+/// A run's lease (`checking_since`) older than this is taken over: that run died with the server.+pub const LEASE_STALE_MS: i64 = 15 * 60 * 1000;+/// A fix task in one of these states is done with; any other is the goal's open fix.+pub const CLOSED_TASK_STATES: [&str; 3] = ["verified", "cancelled", "failed"];++const TABLES: &[&str] = &[+ "CREATE TABLE IF NOT EXISTS goals (+ id TEXT PRIMARY KEY,+ space_id TEXT NOT NULL,+ title TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ kwant_id TEXT NOT NULL,+ folder TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL,+ status_reason TEXT NOT NULL DEFAULT '',+ mode TEXT NOT NULL DEFAULT 'suggest',+ interval_minutes INTEGER NOT NULL DEFAULT 60,+ confirm_failures INTEGER NOT NULL DEFAULT 2,+ budget_tokens INTEGER NOT NULL DEFAULT 0,+ max_fixes_per_day INTEGER NOT NULL DEFAULT 3,+ priority INTEGER NOT NULL DEFAULT 2,+ created_by TEXT NOT NULL,+ approved_by TEXT,+ approved_at INTEGER,+ paused_at INTEGER,+ next_check_at INTEGER,+ last_checked_at INTEGER,+ checking_since INTEGER,+ fail_streak INTEGER NOT NULL DEFAULT 0,+ error_runs INTEGER NOT NULL DEFAULT 0,+ unknown_since INTEGER,+ version INTEGER NOT NULL DEFAULT 1,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS idx_goals_space ON goals(space_id, created_at)",+ "CREATE INDEX IF NOT EXISTS idx_goals_due ON goals(next_check_at)",+ "CREATE TABLE IF NOT EXISTS goal_checks (+ id TEXT PRIMARY KEY,+ goal_id TEXT NOT NULL,+ position INTEGER NOT NULL,+ label TEXT NOT NULL,+ kind TEXT NOT NULL,+ spec TEXT NOT NULL,+ metric TEXT,+ operator TEXT,+ target TEXT,+ severity TEXT NOT NULL DEFAULT 'required',+ freshness_minutes INTEGER NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS idx_goal_checks_goal ON goal_checks(goal_id, position)",+ "CREATE TABLE IF NOT EXISTS goal_observations (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ goal_id TEXT NOT NULL,+ check_id TEXT NOT NULL,+ status TEXT NOT NULL,+ verdict TEXT NOT NULL,+ observed_value TEXT,+ excerpt TEXT NOT NULL DEFAULT '',+ observed_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS idx_goal_observations_check ON goal_observations(goal_id, check_id, id)",+ "CREATE TABLE IF NOT EXISTS goal_events (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ goal_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ actor TEXT NOT NULL,+ detail TEXT NOT NULL DEFAULT '{}',+ created_at INTEGER NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS idx_goal_events_goal ON goal_events(goal_id, id)",+ "CREATE TABLE IF NOT EXISTS goal_fix_tasks (+ goal_id TEXT NOT NULL,+ task_id TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ PRIMARY KEY (goal_id, task_id)+ )",+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_goal_fix_tasks_task ON goal_fix_tasks(task_id)",+];++const GOAL_SELECT: &str = "SELECT id, space_id, title, description, kwant_id, folder, status, status_reason, mode,+ interval_minutes, confirm_failures, budget_tokens, max_fixes_per_day, priority, created_by, approved_by, approved_at,+ paused_at, next_check_at, last_checked_at, checking_since, fail_streak, error_runs, unknown_since, version,+ created_at, updated_at FROM goals";++#[derive(Debug, Clone, PartialEq, Eq, FromRow)]+pub struct Goal {+ pub id: String,+ pub space_id: String,+ pub title: String,+ pub description: String,+ /// The bot that fixes it (and, for a proposal, the one that proposed it).+ pub kwant_id: String,+ /// Where its `command` and `file_*` checks run: the bot's own folder in the space.+ pub folder: String,+ pub status: String,+ /// Why the goal is `needs_you` or `unknown`, in plain words; empty otherwise.+ pub status_reason: String,+ pub mode: String,+ pub interval_minutes: i64,+ pub confirm_failures: i64,+ pub budget_tokens: i64,+ pub max_fixes_per_day: i64,+ /// 1 (high), 2 (default) or 3.+ pub priority: i64,+ /// "person", or the id of the bot that proposed it.+ pub created_by: String,+ pub approved_by: Option<String>,+ pub approved_at: Option<i64>,+ pub paused_at: Option<i64>,+ pub next_check_at: Option<i64>,+ pub last_checked_at: Option<i64>,+ /// The lease of the run going on, if any.+ pub checking_since: Option<i64>,+ pub fail_streak: i64,+ /// Runs in a row where every check errored (the backoff).+ pub error_runs: i64,+ /// When the goal last became `unknown` (None while it isn't): the 24-hour "can't check" notice.+ pub unknown_since: Option<i64>,+ pub version: i64,+ pub created_at: i64,+ pub updated_at: i64,+}++/// One check of a goal: what kwant runs (`kind`, `spec`, through the mission checks' runner) and+/// the typed predicate its result must meet (`metric`, `operator`, `target`; none for the file+/// kinds, whose result is the predicate).+#[derive(Debug, Clone, PartialEq, Eq, FromRow)]+pub struct GoalCheck {+ pub id: String,+ pub goal_id: String,+ pub position: i64,+ pub label: String,+ pub kind: String,+ pub spec: String,+ pub metric: Option<String>,+ pub operator: Option<String>,+ pub target: Option<String>,+ /// `required` checks decide the goal; `advisory` ones show but never do.+ pub severity: String,+ pub freshness_minutes: i64,+}++impl GoalCheck {+ pub fn spec_value(&self) -> Value {+ serde_json::from_str(&self.spec).unwrap_or(Value::Null)+ }++ pub fn required(&self) -> bool {+ self.severity != "advisory"+ }+}++#[derive(Debug, Clone, PartialEq, Eq, FromRow)]+pub struct Observation {+ pub id: i64,+ pub goal_id: String,+ pub check_id: String,+ /// What the check did: `passed`, `failed` or `error`.+ pub status: String,+ /// What that says about the check, judged by its predicate: `passed`, `failed` or `unknown`+ /// (an error, or output the predicate can't read).+ pub verdict: String,+ /// The metric's value as seen (`503`, `412`, `found`), redacted; None for the file kinds or+ /// when the check couldn't run.+ pub observed_value: Option<String>,+ /// Redacted output, at most 2 000 characters. Observed text, never instructions.+ pub excerpt: String,+ pub observed_at: i64,+ /// `observed_at` + the check's freshness: after this it says nothing (unknown).+ pub expires_at: i64,+}++/// One check's result, as a run stores it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NewObservation {+ pub check_id: String,+ pub status: String,+ pub verdict: String,+ pub observed_value: Option<String>,+ pub excerpt: String,+ pub expires_at: i64,+}++#[derive(Debug, Clone, PartialEq, Eq, FromRow)]+pub struct GoalEvent {+ pub id: i64,+ pub goal_id: String,+ pub kind: String,+ pub actor: String,+ pub detail: String,+ pub created_at: i64,+}++impl GoalEvent {+ pub fn detail_value(&self) -> Value {+ serde_json::from_str(&self.detail).unwrap_or_else(|_| json!({}))+ }+}++/// A fix task as the goal sees it: the link and the task's state now (None: the task is gone).+#[derive(Debug, Clone, PartialEq, Eq, FromRow)]+pub struct FixLink {+ pub task_id: String,+ pub created_at: i64,+ pub state: Option<String>,+ pub spent_tokens: Option<i64>,+}++#[derive(Debug, Clone, PartialEq)]+pub struct NewGoalCheck {+ pub label: String,+ pub kind: String,+ pub spec: Value,+ pub metric: Option<String>,+ pub operator: Option<String>,+ pub target: Option<String>,+ pub severity: String,+ pub freshness_minutes: i64,+}++#[derive(Debug, Clone)]+pub struct NewGoal {+ pub space_id: String,+ pub title: String,+ pub description: String,+ pub kwant_id: String,+ pub folder: String,+ pub mode: String,+ pub interval_minutes: i64,+ pub confirm_failures: i64,+ pub budget_tokens: i64,+ pub max_fixes_per_day: i64,+ pub priority: i64,+ /// "person", or the proposing bot's id.+ pub created_by: String,+ /// A bot's proposal, waiting for the person; otherwise created approved by `created_by`.+ pub draft: bool,+ pub checks: Vec<NewGoalCheck>,+}++#[derive(Debug)]+pub enum Created {+ Goal(Box<Goal>),+ /// The space already has [`MAX_DRAFTS`] drafts.+ TooManyDrafts,+}++/// What a person's edit changes, decided by the caller with the goal as it is inside the write+/// lock (see [`Database::edit_goal`]).+#[derive(Debug, Default)]+pub struct Edit {+ /// Replaces the checks; a check with the same kind and spec as one before keeps its id, so+ /// its observations and streak stay.+ pub checks: Option<Vec<NewGoalCheck>>,+ /// Timeline events to add: `(kind, detail)`.+ pub events: Vec<(&'static str, Value)>,+}++/// What a finished run writes (see [`Database::finish_goal_run`]).+#[derive(Debug, Clone, Default)]+pub struct RunUpdate {+ pub status: String,+ pub status_reason: String,+ pub fail_streak: i64,+ pub error_runs: i64,+ pub next_check_at: i64,+ pub events: Vec<(&'static str, Value)>,+}++async fn goal_in(conn: &mut SqliteConnection, id: &str) -> Result<Option<Goal>, sqlx::Error> {+ sqlx::query_as::<_, Goal>(&format!("{GOAL_SELECT} WHERE id = ?")).bind(id).fetch_optional(conn).await+}++async fn event_in(conn: &mut SqliteConnection, goal_id: &str, kind: &str, actor: &str, detail: &Value, now: i64) -> Result<(), sqlx::Error> {+ sqlx::query("INSERT INTO goal_events (goal_id, kind, actor, detail, created_at) VALUES (?, ?, ?, ?, ?)")+ .bind(goal_id)+ .bind(kind)+ .bind(actor)+ .bind(detail.to_string())+ .bind(now)+ .execute(conn)+ .await?;+ Ok(())+}++/// Writes `checks` as the goal's checks. One with the same kind, spec and predicate as an old+/// check keeps that check's id (so its observations still count; a new label, severity or+/// freshness doesn't change what they say); the old ones not kept go with their observations.+async fn put_checks(conn: &mut SqliteConnection, goal_id: &str, checks: &[NewGoalCheck]) -> Result<(), sqlx::Error> {+ let old: Vec<GoalCheck> = sqlx::query_as("SELECT id, goal_id, position, label, kind, spec, metric, operator, target, severity, freshness_minutes FROM goal_checks WHERE goal_id = ?")+ .bind(goal_id)+ .fetch_all(&mut *conn)+ .await?;+ let mut kept: Vec<String> = Vec::new();+ let mut rows = Vec::new();+ for (i, c) in checks.iter().enumerate() {+ let spec = c.spec.to_string();+ let reuse = old.iter().find(|o| {+ o.kind == c.kind && o.spec_value() == c.spec && o.metric == c.metric && o.operator == c.operator && o.target == c.target && !kept.contains(&o.id)+ });+ let id = match reuse {+ Some(o) => o.id.clone(),+ None => Uuid::new_v4().to_string(),+ };+ kept.push(id.clone());+ rows.push((id, i as i64, c, spec));+ }+ for o in old.iter().filter(|o| !kept.contains(&o.id)) {+ sqlx::query("DELETE FROM goal_observations WHERE goal_id = ? AND check_id = ?").bind(goal_id).bind(&o.id).execute(&mut *conn).await?;+ }+ sqlx::query("DELETE FROM goal_checks WHERE goal_id = ?").bind(goal_id).execute(&mut *conn).await?;+ for (id, position, c, spec) in rows {+ sqlx::query(+ "INSERT INTO goal_checks (id, goal_id, position, label, kind, spec, metric, operator, target, severity, freshness_minutes)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(id)+ .bind(goal_id)+ .bind(position)+ .bind(&c.label)+ .bind(&c.kind)+ .bind(spec)+ .bind(&c.metric)+ .bind(&c.operator)+ .bind(&c.target)+ .bind(&c.severity)+ .bind(c.freshness_minutes)+ .execute(&mut *conn)+ .await?;+ }+ Ok(())+}++impl Database {+ pub(super) async fn migrate_goals(&self) -> Result<(), DbError> {+ for stmt in TABLES {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ // A database made by the first goals build (never released) lacks this column+ let _ = sqlx::query("ALTER TABLE goals ADD COLUMN unknown_since INTEGER").execute(&self.pool).await;+ Ok(())+ }++ /// Creates a goal with its checks and a `created` event. A draft is refused when the space+ /// already holds [`MAX_DRAFTS`]: counted and inserted under one write lock, so two bots+ /// proposing at once can't pass the cap.+ pub async fn create_goal(&self, g: &NewGoal, now: i64) -> Result<Created, DbError> {+ let mut tx = self.begin_write().await?;+ if g.draft {+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM goals WHERE space_id = ? AND status = 'draft'")+ .bind(&g.space_id)+ .fetch_one(&mut *tx)+ .await?;+ if n >= MAX_DRAFTS {+ tx.rollback().await?;+ return Ok(Created::TooManyDrafts);+ }+ }+ let id = Uuid::new_v4().to_string();+ let (status, approved_by, approved_at, next) = if g.draft {+ ("draft", None, None, None)+ } else {+ ("checking", Some(g.created_by.as_str()), Some(now), Some(now))+ };+ sqlx::query(+ "INSERT INTO goals (id, space_id, title, description, kwant_id, folder, status, mode, interval_minutes,+ confirm_failures, budget_tokens, max_fixes_per_day, priority, created_by, approved_by, approved_at,+ next_check_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&id)+ .bind(&g.space_id)+ .bind(&g.title)+ .bind(&g.description)+ .bind(&g.kwant_id)+ .bind(&g.folder)+ .bind(status)+ .bind(&g.mode)+ .bind(g.interval_minutes)+ .bind(g.confirm_failures)+ .bind(g.budget_tokens)+ .bind(g.max_fixes_per_day)+ .bind(g.priority)+ .bind(&g.created_by)+ .bind(approved_by)+ .bind(approved_at)+ .bind(next)+ .bind(now)+ .bind(now)+ .execute(&mut *tx)+ .await?;+ put_checks(&mut tx, &id, &g.checks).await?;+ event_in(&mut tx, &id, "created", &g.created_by, &json!({ "draft": g.draft }), now).await?;+ let goal = goal_in(&mut tx, &id).await?;+ tx.commit().await?;+ goal.map(|g| Created::Goal(Box::new(g))).ok_or_else(|| DbError::Migration("the new goal wasn't stored".into()))+ }++ pub async fn get_goal(&self, id: &str) -> Result<Option<Goal>, DbError> {+ let mut conn = self.pool.acquire().await?;+ Ok(goal_in(&mut conn, id).await?)+ }++ /// The space's goals, drafts first, then oldest first.+ pub async fn list_goals(&self, space_id: &str) -> Result<Vec<Goal>, DbError> {+ Ok(sqlx::query_as::<_, Goal>(&format!("{GOAL_SELECT} WHERE space_id = ? ORDER BY status = 'draft' DESC, created_at, id"))+ .bind(space_id)+ .fetch_all(&self.pool)+ .await?)+ }++ pub async fn count_draft_goals(&self, space_id: &str) -> Result<i64, DbError> {+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM goals WHERE space_id = ? AND status = 'draft'").bind(space_id).fetch_one(&self.pool).await?;+ Ok(n)+ }++ pub async fn goal_checks(&self, goal_id: &str) -> Result<Vec<GoalCheck>, DbError> {+ Ok(sqlx::query_as("SELECT id, goal_id, position, label, kind, spec, metric, operator, target, severity, freshness_minutes FROM goal_checks WHERE goal_id = ? ORDER BY position")+ .bind(goal_id)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Up to `per_check` newest observations of each of the goal's checks, newest first.+ pub async fn recent_observations(&self, goal_id: &str, per_check: i64) -> Result<Vec<Observation>, DbError> {+ Ok(sqlx::query_as(+ "SELECT id, goal_id, check_id, status, verdict, observed_value, excerpt, observed_at, expires_at FROM (+ SELECT o.*, ROW_NUMBER() OVER (PARTITION BY o.check_id ORDER BY o.id DESC) AS n+ FROM goal_observations o WHERE o.goal_id = ?+ ) WHERE n <= ? ORDER BY id DESC",+ )+ .bind(goal_id)+ .bind(per_check)+ .fetch_all(&self.pool)+ .await?)+ }++ /// The goal's newest events, newest first.+ pub async fn goal_events(&self, goal_id: &str, limit: i64) -> Result<Vec<GoalEvent>, DbError> {+ Ok(sqlx::query_as("SELECT id, goal_id, kind, actor, detail, created_at FROM goal_events WHERE goal_id = ? ORDER BY id DESC LIMIT ?")+ .bind(goal_id)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }++ /// The newest of the goal's `met` / `not_met` events: which side of an outage it is on.+ pub async fn last_goal_mark(&self, goal_id: &str) -> Result<Option<String>, DbError> {+ let row: Option<(String,)> = sqlx::query_as("SELECT kind FROM goal_events WHERE goal_id = ? AND kind IN ('met', 'not_met') ORDER BY id DESC LIMIT 1")+ .bind(goal_id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|r| r.0))+ }++ pub async fn add_goal_event(&self, goal_id: &str, kind: &str, actor: &str, detail: &Value) -> Result<(), DbError> {+ let mut conn = self.pool.acquire().await?;+ event_in(&mut conn, goal_id, kind, actor, detail, super::missions::now_ms()).await?;+ Ok(())+ }++ /// Approves a draft of the space: it is checked from now on. None if it isn't a draft there.+ pub async fn approve_goal(&self, id: &str, space_id: &str, by: &str, now: i64) -> Result<Option<Goal>, DbError> {+ let mut tx = self.begin_write().await?;+ let r = sqlx::query(+ "UPDATE goals SET status = 'checking', status_reason = '', approved_by = ?, approved_at = ?, next_check_at = ?,+ version = version + 1, updated_at = ? WHERE id = ? AND space_id = ? AND status = 'draft'",+ )+ .bind(by)+ .bind(now)+ .bind(now)+ .bind(now)+ .bind(id)+ .bind(space_id)+ .execute(&mut *tx)+ .await?;+ if r.rows_affected() != 1 {+ tx.rollback().await?;+ return Ok(None);+ }+ event_in(&mut tx, id, "approved", by, &json!({}), now).await?;+ let goal = goal_in(&mut tx, id).await?;+ tx.commit().await?;+ Ok(goal)+ }++ /// A person's edit: `decide` sees the goal of the space as it is under the write lock, changes+ /// it in place (or refuses with a message) and says what else to write. The version goes up,+ /// so a run that started before the edit doesn't overwrite it. `Ok(None)`: no such goal.+ pub async fn edit_goal<F>(&self, id: &str, space_id: &str, actor: &str, now: i64, decide: F) -> Result<Option<Result<Goal, String>>, DbError>+ where+ F: FnOnce(&mut Goal) -> Result<Edit, String>,+ {+ let mut tx = self.begin_write().await?;+ let Some(mut g) = goal_in(&mut tx, id).await?.filter(|g| g.space_id == space_id) else {+ tx.rollback().await?;+ return Ok(None);+ };+ let edit = match decide(&mut g) {+ Ok(e) => e,+ Err(why) => {+ tx.rollback().await?;+ return Ok(Some(Err(why)));+ }+ };+ sqlx::query(+ "UPDATE goals SET title = ?, description = ?, kwant_id = ?, folder = ?, status = ?, status_reason = ?, mode = ?,+ interval_minutes = ?, confirm_failures = ?, budget_tokens = ?, max_fixes_per_day = ?, priority = ?,+ paused_at = ?, next_check_at = ?, fail_streak = ?, error_runs = ?,+ unknown_since = CASE WHEN ? = 'unknown' THEN COALESCE(unknown_since, ?) ELSE NULL END,+ version = version + 1, updated_at = ? WHERE id = ?",+ )+ .bind(&g.title)+ .bind(&g.description)+ .bind(&g.kwant_id)+ .bind(&g.folder)+ .bind(&g.status)+ .bind(&g.status_reason)+ .bind(&g.mode)+ .bind(g.interval_minutes)+ .bind(g.confirm_failures)+ .bind(g.budget_tokens)+ .bind(g.max_fixes_per_day)+ .bind(g.priority)+ .bind(g.paused_at)+ .bind(g.next_check_at)+ .bind(g.fail_streak)+ .bind(g.error_runs)+ .bind(&g.status)+ .bind(now)+ .bind(now)+ .bind(id)+ .execute(&mut *tx)+ .await?;+ if let Some(checks) = &edit.checks {+ put_checks(&mut tx, id, checks).await?;+ }+ for (kind, detail) in &edit.events {+ event_in(&mut tx, id, kind, actor, detail, now).await?;+ }+ let goal = goal_in(&mut tx, id).await?;+ tx.commit().await?;+ Ok(goal.map(Ok))+ }++ /// Deletes a goal of the space with its checks, observations, events and fix-task links (the+ /// tasks stay on the board). False if there was none.+ pub async fn delete_goal(&self, id: &str, space_id: &str) -> Result<bool, DbError> {+ let mut tx = self.begin_write().await?;+ let r = sqlx::query("DELETE FROM goals WHERE id = ? AND space_id = ?").bind(id).bind(space_id).execute(&mut *tx).await?;+ if r.rows_affected() != 1 {+ tx.rollback().await?;+ return Ok(false);+ }+ for table in ["goal_checks", "goal_observations", "goal_events", "goal_fix_tasks"] {+ sqlx::query(&format!("DELETE FROM {table} WHERE goal_id = ?")).bind(id).execute(&mut *tx).await?;+ }+ tx.commit().await?;+ Ok(true)+ }++ /// Goals whose check is due at `now` and not running: approved, not paused, no live lease.+ pub async fn due_goal_ids(&self, now: i64, limit: i64) -> Result<Vec<String>, DbError> {+ let rows: Vec<(String,)> = sqlx::query_as(+ "SELECT id FROM goals WHERE next_check_at IS NOT NULL AND next_check_at <= ? AND status NOT IN ('draft', 'paused')+ AND (checking_since IS NULL OR checking_since < ?) ORDER BY next_check_at LIMIT ?",+ )+ .bind(now)+ .bind(now - LEASE_STALE_MS)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|r| r.0).collect())+ }++ /// Takes the goal's run lease (`checking_since = now`) if no live run holds it. `due_only`+ /// (the loop) also needs it approved, not paused and due; otherwise (Check now) any goal but a+ /// draft. The lease is the token the run renews and finishes with.+ pub async fn lease_goal(&self, id: &str, now: i64, due_only: bool) -> Result<Option<Goal>, DbError> {+ let due = if due_only { " AND status != 'paused' AND next_check_at IS NOT NULL AND next_check_at <= ?" } else { "" };+ let sql = format!(+ "UPDATE goals SET checking_since = ? WHERE id = ? AND status != 'draft' AND (checking_since IS NULL OR checking_since < ?){due}"+ );+ let mut q = sqlx::query(&sql).bind(now).bind(id).bind(now - LEASE_STALE_MS);+ if due_only {+ q = q.bind(now);+ }+ let mut tx = self.begin_write().await?;+ if q.execute(&mut *tx).await?.rows_affected() != 1 {+ tx.rollback().await?;+ return Ok(None);+ }+ let goal = goal_in(&mut tx, id).await?;+ tx.commit().await?;+ Ok(goal)+ }++ /// Moves the lease from `old` to `new` (a run still going); false if the run lost it (the goal+ /// was deleted, or the lease went stale and another run took it).+ pub async fn renew_goal_lease(&self, id: &str, old: i64, new: i64) -> Result<bool, DbError> {+ let r = sqlx::query("UPDATE goals SET checking_since = ? WHERE id = ? AND checking_since = ?").bind(new).bind(id).bind(old).execute(&self.pool).await?;+ Ok(r.rows_affected() == 1)+ }++ /// Whether the run holding `lease` still holds it.+ pub async fn holds_goal_lease(&self, id: &str, lease: i64) -> Result<bool, DbError> {+ let row: Option<(i64,)> = sqlx::query_as("SELECT 1 FROM goals WHERE id = ? AND checking_since = ?").bind(id).bind(lease).fetch_optional(&self.pool).await?;+ Ok(row.is_some())+ }++ /// Stores a run's observations while the run holds `lease`, then keeps the newest+ /// [`KEEP_OBSERVATIONS`]. False (nothing stored) if the run lost its lease.+ pub async fn record_observations(&self, goal_id: &str, lease: i64, obs: &[NewObservation], now: i64) -> Result<bool, DbError> {+ let mut tx = self.begin_write().await?;+ let held: Option<(i64,)> = sqlx::query_as("SELECT 1 FROM goals WHERE id = ? AND checking_since = ?").bind(goal_id).bind(lease).fetch_optional(&mut *tx).await?;+ if held.is_none() {+ tx.rollback().await?;+ return Ok(false);+ }+ for o in obs {+ sqlx::query(+ "INSERT INTO goal_observations (goal_id, check_id, status, verdict, observed_value, excerpt, observed_at, expires_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(goal_id)+ .bind(&o.check_id)+ .bind(&o.status)+ .bind(&o.verdict)+ .bind(&o.observed_value)+ .bind(&o.excerpt)+ .bind(now)+ .bind(o.expires_at)+ .execute(&mut *tx)+ .await?;+ }+ sqlx::query(+ "DELETE FROM goal_observations WHERE goal_id = ? AND id NOT IN+ (SELECT id FROM goal_observations WHERE goal_id = ? ORDER BY id DESC LIMIT ?)",+ )+ .bind(goal_id)+ .bind(goal_id)+ .bind(KEEP_OBSERVATIONS)+ .execute(&mut *tx)+ .await?;+ sqlx::query("UPDATE goals SET last_checked_at = ? WHERE id = ?").bind(now).bind(goal_id).execute(&mut *tx).await?;+ tx.commit().await?;+ Ok(true)+ }++ /// Ends a run: writes its outcome and frees the lease. If the person edited, paused or resumed+ /// the goal since the run started (`version` moved on), only the lease is freed, so their+ /// change stands (an edit already asked for a check now). Returns the goal as it is now; None+ /// if the run lost its lease.+ pub async fn finish_goal_run(&self, id: &str, lease: i64, version: i64, u: &RunUpdate, now: i64) -> Result<Option<Goal>, DbError> {+ let mut tx = self.begin_write().await?;+ let r = sqlx::query(+ "UPDATE goals SET status = ?, status_reason = ?, fail_streak = ?, error_runs = ?, next_check_at = ?,+ unknown_since = CASE WHEN ? = 'unknown' THEN COALESCE(unknown_since, ?) ELSE NULL END,+ checking_since = NULL, updated_at = ? WHERE id = ? AND checking_since = ? AND version = ?",+ )+ .bind(&u.status)+ .bind(&u.status_reason)+ .bind(u.fail_streak)+ .bind(u.error_runs)+ .bind(u.next_check_at)+ .bind(&u.status)+ .bind(now)+ .bind(now)+ .bind(id)+ .bind(lease)+ .bind(version)+ .execute(&mut *tx)+ .await?;+ if r.rows_affected() == 1 {+ for (kind, detail) in &u.events {+ event_in(&mut tx, id, kind, "kwant", detail, now).await?;+ }+ sqlx::query(+ "DELETE FROM goal_events WHERE goal_id = ? AND id NOT IN+ (SELECT id FROM goal_events WHERE goal_id = ? ORDER BY id DESC LIMIT ?)",+ )+ .bind(id)+ .bind(id)+ .bind(KEEP_EVENTS)+ .execute(&mut *tx)+ .await?;+ } else {+ let r = sqlx::query("UPDATE goals SET checking_since = NULL WHERE id = ? AND checking_since = ?").bind(id).bind(lease).execute(&mut *tx).await?;+ if r.rows_affected() != 1 {+ tx.rollback().await?;+ return Ok(None);+ }+ }+ let goal = goal_in(&mut tx, id).await?;+ tx.commit().await?;+ Ok(goal)+ }++ /// Frees a run's lease without an outcome (the run found nothing to do).+ pub async fn release_goal_lease(&self, id: &str, lease: i64, next_check_at: Option<i64>) -> Result<(), DbError> {+ sqlx::query("UPDATE goals SET checking_since = NULL, next_check_at = COALESCE(?, next_check_at) WHERE id = ? AND checking_since = ?")+ .bind(next_check_at)+ .bind(id)+ .bind(lease)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Sets the goal's status from outside a run (a fix task moved), unless it is a draft or+ /// paused. `only_from`: change it only from one of these. Returns the goal if it changed.+ pub async fn set_goal_status(&self, id: &str, status: &str, reason: &str, only_from: &[&str], event: Option<(&str, Value)>) -> Result<Option<Goal>, DbError> {+ let now = super::missions::now_ms();+ let mut tx = self.begin_write().await?;+ let Some(g) = goal_in(&mut tx, id).await? else {+ tx.rollback().await?;+ return Ok(None);+ };+ if matches!(g.status.as_str(), "draft" | "paused") || (!only_from.is_empty() && !only_from.contains(&g.status.as_str())) {+ tx.rollback().await?;+ return Ok(None);+ }+ sqlx::query(+ "UPDATE goals SET status = ?, status_reason = ?,+ unknown_since = CASE WHEN ? = 'unknown' THEN COALESCE(unknown_since, ?) ELSE NULL END, updated_at = ? WHERE id = ?",+ )+ .bind(status)+ .bind(reason)+ .bind(status)+ .bind(now)+ .bind(now)+ .bind(id)+ .execute(&mut *tx)+ .await?;+ if let Some((kind, detail)) = event {+ event_in(&mut tx, id, kind, "kwant", &detail, now).await?;+ }+ let goal = goal_in(&mut tx, id).await?;+ tx.commit().await?;+ Ok(goal)+ }++ /// Asks for a check soon: `next_check_at = at` unless one is already due earlier.+ pub async fn check_goal_soon(&self, id: &str, at: i64) -> Result<(), DbError> {+ sqlx::query("UPDATE goals SET next_check_at = MIN(COALESCE(next_check_at, ?), ?) WHERE id = ? AND status NOT IN ('draft', 'paused')")+ .bind(at)+ .bind(at)+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Links a new fix task to the goal and logs `fix_opened`, while the run that opened it still+ /// holds `lease`. False (nothing linked) if it doesn't: the caller cancels the task.+ pub async fn link_fix_task(&self, goal_id: &str, lease: i64, task_id: &str, detail: &Value, now: i64) -> Result<bool, DbError> {+ let mut tx = self.begin_write().await?;+ let held: Option<(i64,)> = sqlx::query_as("SELECT 1 FROM goals WHERE id = ? AND checking_since = ?").bind(goal_id).bind(lease).fetch_optional(&mut *tx).await?;+ if held.is_none() {+ tx.rollback().await?;+ return Ok(false);+ }+ sqlx::query("INSERT INTO goal_fix_tasks (goal_id, task_id, created_at) VALUES (?, ?, ?)").bind(goal_id).bind(task_id).bind(now).execute(&mut *tx).await?;+ event_in(&mut tx, goal_id, "fix_opened", "kwant", detail, now).await?;+ tx.commit().await?;+ Ok(true)+ }++ /// The goal's fix tasks, newest first, with each task's state and spend now.+ pub async fn goal_fix_links(&self, goal_id: &str) -> Result<Vec<FixLink>, DbError> {+ Ok(sqlx::query_as(+ "SELECT f.task_id, f.created_at, t.state, t.spent_tokens FROM goal_fix_tasks f LEFT JOIN tasks t ON t.id = f.task_id+ WHERE f.goal_id = ? ORDER BY f.created_at DESC, f.rowid DESC",+ )+ .bind(goal_id)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Fix tasks the goal opened since `since` (the daily cap counts a rolling 24 hours).+ pub async fn fixes_since(&self, goal_id: &str, since: i64) -> Result<i64, DbError> {+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM goal_fix_tasks WHERE goal_id = ? AND created_at >= ?").bind(goal_id).bind(since).fetch_one(&self.pool).await?;+ Ok(n)+ }++ /// The goal a task was opened to fix, if any.+ pub async fn goal_of_task(&self, task_id: &str) -> Result<Option<String>, DbError> {+ let row: Option<(String,)> = sqlx::query_as("SELECT goal_id FROM goal_fix_tasks WHERE task_id = ?").bind(task_id).fetch_optional(&self.pool).await?;+ Ok(row.map(|r| r.0))+ }++ /// Goals with a fix task that is ready, not held and not running: the fix runner's work.+ pub async fn goals_with_ready_fix(&self) -> Result<Vec<(String, String)>, DbError> {+ Ok(sqlx::query_as(+ "SELECT f.goal_id, f.task_id FROM goal_fix_tasks f JOIN tasks t ON t.id = f.task_id JOIN goals g ON g.id = f.goal_id+ WHERE t.state = 'ready' AND t.held_at IS NULL AND g.status != 'paused' ORDER BY f.created_at",+ )+ .fetch_all(&self.pool)+ .await?)+ }++ /// Deletes drafts created before `before` (nobody approved them: they expire silently after+ /// 7 days, plan B.0 rule 4), with their rows. Returns `(id, space_id)` of each.+ pub async fn expire_drafts(&self, before: i64) -> Result<Vec<(String, String)>, DbError> {+ let mut tx = self.begin_write().await?;+ let gone: Vec<(String, String)> = sqlx::query_as("SELECT id, space_id FROM goals WHERE status = 'draft' AND created_at < ?").bind(before).fetch_all(&mut *tx).await?;+ for (id, _) in &gone {+ sqlx::query("DELETE FROM goals WHERE id = ? AND status = 'draft'").bind(id).execute(&mut *tx).await?;+ for table in ["goal_checks", "goal_observations", "goal_events", "goal_fix_tasks"] {+ sqlx::query(&format!("DELETE FROM {table} WHERE goal_id = ?")).bind(id).execute(&mut *tx).await?;+ }+ }+ tx.commit().await?;+ Ok(gone)+ }++ /// Goals `unknown` since `before` or longer that haven't had the "can't check" notice (sent, or+ /// held back by the cap) for this stretch of unknown.+ pub async fn goals_unknown_since(&self, before: i64) -> Result<Vec<Goal>, DbError> {+ Ok(sqlx::query_as::<_, Goal>(&format!(+ "{GOAL_SELECT} WHERE status = 'unknown' AND unknown_since IS NOT NULL AND unknown_since <= ? AND NOT EXISTS (+ SELECT 1 FROM goal_events e WHERE e.goal_id = goals.id AND e.kind IN ('notified', 'notice_capped')+ AND e.created_at >= goals.unknown_since AND json_extract(e.detail, '$.kind') = 'cant_check')"+ ))+ .bind(before)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Notices sent about the goal since `since` (the cap counts a rolling 24 hours).+ pub async fn goal_notices_since(&self, goal_id: &str, since: i64) -> Result<i64, DbError> {+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM goal_events WHERE goal_id = ? AND kind = 'notified' AND created_at >= ?")+ .bind(goal_id)+ .bind(since)+ .fetch_one(&self.pool)+ .await?;+ Ok(n)+ }++ /// Whether the person was told the goal broke, or that kwant can't check it, since it was last+ /// met (so a recovery is worth a notice).+ pub async fn told_broken(&self, goal_id: &str) -> Result<bool, DbError> {+ let row: Option<(i64,)> = sqlx::query_as(+ "SELECT 1 FROM goal_events WHERE goal_id = ? AND kind = 'notified' AND json_extract(detail, '$.kind') IN ('broken', 'cant_check')+ AND id > COALESCE((SELECT MAX(id) FROM goal_events WHERE goal_id = ? AND kind = 'met'), 0) LIMIT 1",+ )+ .bind(goal_id)+ .bind(goal_id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.is_some())+ }++ /// Met goals, not running, with a required check whose newest observation has expired (at or+ /// before `now`) or that has none: they can't be called met any more.+ pub async fn stale_met_goals(&self, now: i64) -> Result<Vec<String>, DbError> {+ let rows: Vec<(String,)> = sqlx::query_as(+ "SELECT g.id FROM goals g WHERE g.status = 'met' AND g.checking_since IS NULL AND EXISTS (+ SELECT 1 FROM goal_checks c WHERE c.goal_id = g.id AND c.severity != 'advisory' AND COALESCE((+ SELECT o.expires_at FROM goal_observations o WHERE o.goal_id = g.id AND o.check_id = c.id ORDER BY o.id DESC LIMIT 1+ ), 0) <= ?)",+ )+ .bind(now)+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|r| r.0).collect())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ async fn db() -> (Database, tempfile::TempDir) {+ let tmp = tempfile::tempdir().unwrap();+ (Database::init(tmp.path()).await.unwrap(), tmp)+ }++ fn new_goal(space: &str, draft: bool) -> NewGoal {+ NewGoal {+ space_id: space.into(),+ title: "Site stays up".into(),+ description: "The home page answers 200".into(),+ kwant_id: "bot-1".into(),+ folder: "/tmp/x".into(),+ mode: "suggest".into(),+ interval_minutes: 60,+ confirm_failures: 2,+ budget_tokens: 0,+ max_fixes_per_day: 3,+ priority: 2,+ created_by: if draft { "bot-1".into() } else { "person".into() },+ draft,+ checks: vec![check("home", "http", json!({"url": "http://127.0.0.1:9/"}))],+ }+ }++ fn check(label: &str, kind: &str, spec: Value) -> NewGoalCheck {+ let (metric, operator, target) = if kind == "http" { (Some("status".into()), Some("eq".into()), Some("200".into())) } else { (None, None, None) };+ NewGoalCheck { label: label.into(), kind: kind.into(), spec, metric, operator, target, severity: "required".into(), freshness_minutes: 120 }+ }++ fn obs(check_id: &str, status: &str, verdict: &str, excerpt: &str) -> NewObservation {+ NewObservation {+ check_id: check_id.into(),+ status: status.into(),+ verdict: verdict.into(),+ observed_value: None,+ excerpt: excerpt.into(),+ expires_at: i64::MAX,+ }+ }++ fn created(c: Created) -> Goal {+ match c {+ Created::Goal(g) => *g,+ Created::TooManyDrafts => panic!("refused"),+ }+ }++ #[tokio::test]+ async fn drafts_are_capped_per_space_and_a_dismissed_one_frees_its_slot() {+ let (db, _dir) = db().await;+ let mut ids = Vec::new();+ for _ in 0..MAX_DRAFTS {+ ids.push(created(db.create_goal(&new_goal("s1", true), 1).await.unwrap()).id);+ }+ assert!(matches!(db.create_goal(&new_goal("s1", true), 2).await.unwrap(), Created::TooManyDrafts));+ // Another space has its own three; an approved goal doesn't count+ assert!(matches!(db.create_goal(&new_goal("s2", true), 2).await.unwrap(), Created::Goal(_)));+ assert!(matches!(db.create_goal(&new_goal("s1", false), 2).await.unwrap(), Created::Goal(_)));+ assert!(db.approve_goal(&ids[0], "s1", "person", 3).await.unwrap().is_some());+ assert!(matches!(db.create_goal(&new_goal("s1", true), 4).await.unwrap(), Created::Goal(_)));+ assert!(db.delete_goal(&ids[1], "s1").await.unwrap());+ assert!(matches!(db.create_goal(&new_goal("s1", true), 5).await.unwrap(), Created::Goal(_)));+ assert_eq!(db.count_draft_goals("s1").await.unwrap(), MAX_DRAFTS);+ }++ #[tokio::test]+ async fn concurrent_proposals_never_pass_the_cap() {+ let (db, _dir) = db().await;+ let mut handles = Vec::new();+ for _ in 0..8 {+ let db = db.clone();+ handles.push(tokio::spawn(async move { db.create_goal(&new_goal("s1", true), 1).await.unwrap() }));+ }+ let mut made = 0;+ for h in handles {+ if matches!(h.await.unwrap(), Created::Goal(_)) {+ made += 1;+ }+ }+ assert_eq!(made, MAX_DRAFTS);+ assert_eq!(db.count_draft_goals("s1").await.unwrap(), MAX_DRAFTS);+ }++ #[tokio::test]+ async fn a_draft_is_never_due_or_leased_and_approval_is_once() {+ let (db, _dir) = db().await;+ let g = created(db.create_goal(&new_goal("s1", true), 1).await.unwrap());+ assert_eq!(g.status, "draft");+ assert!(db.due_goal_ids(i64::MAX / 2, 10).await.unwrap().is_empty());+ assert!(db.lease_goal(&g.id, 10, false).await.unwrap().is_none());+ assert!(db.approve_goal(&g.id, "other-space", "person", 5).await.unwrap().is_none());+ let a = db.approve_goal(&g.id, "s1", "person", 5).await.unwrap().unwrap();+ assert_eq!((a.status.as_str(), a.approved_by.as_deref(), a.next_check_at), ("checking", Some("person"), Some(5)));+ assert!(db.approve_goal(&g.id, "s1", "person", 6).await.unwrap().is_none());+ assert_eq!(db.due_goal_ids(5, 10).await.unwrap(), vec![g.id.clone()]);+ let kinds: Vec<String> = db.goal_events(&g.id, 50).await.unwrap().into_iter().map(|e| e.kind).collect();+ assert_eq!(kinds, ["approved", "created"]);+ }++ #[tokio::test]+ async fn one_lease_at_a_time_until_it_goes_stale() {+ let (db, _dir) = db().await;+ let g = created(db.create_goal(&new_goal("s1", false), 1).await.unwrap());+ let t0 = 1_000;+ assert!(db.lease_goal(&g.id, t0, true).await.unwrap().is_some());+ assert!(db.lease_goal(&g.id, t0 + 1, false).await.unwrap().is_none());+ assert!(db.lease_goal(&g.id, t0 + LEASE_STALE_MS - 1, true).await.unwrap().is_none());+ assert!(db.due_goal_ids(t0 + 5, 10).await.unwrap().is_empty());+ // Renewed, it stays live; the old token is dead+ assert!(db.renew_goal_lease(&g.id, t0, t0 + 10).await.unwrap());+ assert!(!db.renew_goal_lease(&g.id, t0, t0 + 20).await.unwrap());+ // Stale after 15 minutes: another run takes over, and the first can't store anything+ let t1 = t0 + 10 + LEASE_STALE_MS + 1;+ assert!(db.lease_goal(&g.id, t1, true).await.unwrap().is_some());+ let o = vec![obs("c", "passed", "met", "")];+ assert!(!db.record_observations(&g.id, t0 + 10, &o, t1).await.unwrap());+ assert!(db.record_observations(&g.id, t1, &o, t1).await.unwrap());+ }++ #[tokio::test]+ async fn observations_keep_the_newest_200_per_goal() {+ let (db, _dir) = db().await;+ let g = created(db.create_goal(&new_goal("s1", false), 1).await.unwrap());+ let check = db.goal_checks(&g.id).await.unwrap()[0].id.clone();+ assert!(db.lease_goal(&g.id, 10, false).await.unwrap().is_some());+ for i in 0..210 {+ let o = vec![obs(&check, "passed", "met", &format!("run {i}"))];+ assert!(db.record_observations(&g.id, 10, &o, 100 + i).await.unwrap());+ }+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM goal_observations WHERE goal_id = ?").bind(&g.id).fetch_one(&db.pool).await.unwrap();+ assert_eq!(n, KEEP_OBSERVATIONS);+ let newest = db.recent_observations(&g.id, 3).await.unwrap();+ assert_eq!(newest.iter().map(|o| o.excerpt.as_str()).collect::<Vec<_>>(), ["run 209", "run 208", "run 207"]);+ }++ #[tokio::test]+ async fn a_run_that_overlaps_an_edit_frees_the_lease_but_keeps_the_edit() {+ let (db, _dir) = db().await;+ let g = created(db.create_goal(&new_goal("s1", false), 1).await.unwrap());+ let leased = db.lease_goal(&g.id, 10, false).await.unwrap().unwrap();+ let paused = db+ .edit_goal(&g.id, "s1", "person", 11, |g| {+ g.status = "paused".into();+ g.paused_at = Some(11);+ Ok(Edit { events: vec![("paused", json!({}))], ..Default::default() })+ })+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ assert_eq!(paused.version, leased.version + 1);+ let u = RunUpdate { status: "met".into(), next_check_at: 999, events: vec![("met", json!({}))], ..Default::default() };+ let after = db.finish_goal_run(&g.id, 10, leased.version, &u, 12).await.unwrap().unwrap();+ assert_eq!((after.status.as_str(), after.checking_since), ("paused", None));+ assert_eq!(db.last_goal_mark(&g.id).await.unwrap(), None);+ }++ #[tokio::test]+ async fn an_edit_keeps_unchanged_checks_and_their_observations() {+ let (db, _dir) = db().await;+ let g = created(db.create_goal(&new_goal("s1", false), 1).await.unwrap());+ let old = db.goal_checks(&g.id).await.unwrap();+ assert!(db.lease_goal(&g.id, 10, false).await.unwrap().is_some());+ let o = vec![obs(&old[0].id, "failed", "not_met", "")];+ assert!(db.record_observations(&g.id, 10, &o, 10).await.unwrap());+ let mut checks = new_goal("s1", false).checks;+ checks[0].label = "renamed".into();+ checks[0].severity = "advisory".into();+ checks.push(check("file", "file_exists", json!({"path": "ok"})));+ db.edit_goal(&g.id, "s1", "person", 11, |_| Ok(Edit { checks: Some(checks), ..Default::default() })).await.unwrap().unwrap().unwrap();+ let now = db.goal_checks(&g.id).await.unwrap();+ assert_eq!(now.len(), 2);+ assert_eq!((now[0].id.as_str(), now[0].label.as_str(), now[0].required()), (old[0].id.as_str(), "renamed", false));+ assert_eq!(db.recent_observations(&g.id, 5).await.unwrap().len(), 1);+ // A changed target is a new check: what it observed answered another question+ let mut changed = new_goal("s1", false).checks;+ changed[0].target = Some("204".into());+ db.edit_goal(&g.id, "s1", "person", 12, |_| Ok(Edit { checks: Some(changed), ..Default::default() })).await.unwrap().unwrap().unwrap();+ assert_ne!(db.goal_checks(&g.id).await.unwrap()[0].id, old[0].id);+ assert!(db.recent_observations(&g.id, 5).await.unwrap().is_empty());+ }++ #[tokio::test]+ async fn deleting_a_goal_removes_its_rows_and_a_late_run_writes_nothing() {+ let (db, _dir) = db().await;+ let g = created(db.create_goal(&new_goal("s1", false), 1).await.unwrap());+ let check = db.goal_checks(&g.id).await.unwrap()[0].id.clone();+ assert!(db.lease_goal(&g.id, 10, false).await.unwrap().is_some());+ let o = vec![obs(&check, "failed", "not_met", "")];+ assert!(db.record_observations(&g.id, 10, &o, 10).await.unwrap());+ assert!(db.link_fix_task(&g.id, 10, "task-1", &json!({}), 10).await.unwrap());+ assert!(!db.delete_goal(&g.id, "other-space").await.unwrap());+ assert!(db.delete_goal(&g.id, "s1").await.unwrap());+ for table in ["goals", "goal_checks", "goal_observations", "goal_events", "goal_fix_tasks"] {+ let col = if table == "goals" { "id" } else { "goal_id" };+ let (n,): (i64,) = sqlx::query_as(&format!("SELECT COUNT(*) FROM {table} WHERE {col} = ?")).bind(&g.id).fetch_one(&db.pool).await.unwrap();+ assert_eq!(n, 0, "{table}");+ }+ assert!(!db.record_observations(&g.id, 10, &[], 11).await.unwrap());+ assert!(!db.link_fix_task(&g.id, 10, "task-2", &json!({}), 11).await.unwrap());+ let u = RunUpdate { status: "met".into(), ..Default::default() };+ assert!(db.finish_goal_run(&g.id, 10, g.version, &u, 12).await.unwrap().is_none());+ assert!(db.get_goal(&g.id).await.unwrap().is_none());+ assert_eq!(db.goal_of_task("task-1").await.unwrap(), None);+ }++ #[tokio::test]+ async fn the_migration_runs_twice() {+ let (db, _dir) = db().await;+ db.migrate_goals().await.unwrap();+ db.migrate_goals().await.unwrap();+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex 2a6cf8e2..1fb06354 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -35,6 +35,7 @@ pub mod auditor;pub mod foundry;pub mod automation;pub mod truth_ledger;+pub mod goals;pub mod routing;pub mod smart_results;@@ -204,6 +205,8 @@ impl Database {db.migrate_foundry().await?;// Phase D4: routines carry class, acceptance and checks; suggestion storage (add-only)db.migrate_automation_discovery().await?;+ // 0.6.5: Goals, their checks, observations, timeline and fix-task links (add-only)+ db.migrate_goals().await?;// Phase C1: the Truth Ledger mirrors memory (add-only). Last, so no later step rebuilds// a table its triggers or lookups depend ondb.migrate_truth_ledger().await?;diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex 84a9a197..e8ef06db 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -271,6 +271,9 @@ pub enum RuntimeEvent {/// A mission changed (status, budget, counts). `mission` carries `space_id`.#[serde(rename = "mission_updated", alias = "MissionUpdated")]MissionUpdated { mission: Value },+ /// A goal changed (status, checks, schedule, its fix task); `GET /api/goals/:id` has the rest.+ #[serde(rename = "goal_updated", alias = "GoalUpdated")]+ GoalUpdated { id: String, status: String, space_id: String },/// Something the user asked to be told about. `kind` is one of `continuity::NOTIFY_KINDS`/// ("turn_finished", "approval_needed", "human_step", …). `body` never holds chat text, tool arguments or secrets.#[serde(rename = "notify", alias = "Notify")]diff --git a/src/server/auth.rs b/src/server/auth.rsindex f0f176a2..401c5c17 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -340,6 +340,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {// Mission Control: approving plans, verifying, rejecting, retrying and approving checks are// the person's calls; bots act on tasks only through their task tools["", "api", "missions" | "tasks" | "checks", ..] => *method != Method::GET && *method != Method::HEAD,+ // Goals: creating, approving, editing, pausing, deleting and Check now are the person's;+ // bots only propose drafts (the `goal_propose` tool)+ ["", "api", "goals", ..] => *method != Method::GET && *method != Method::HEAD,// AutoFix's proposed changes to routines, checks and tasks: only the person reads, approves// or rejects them; bots only propose (the `workflow_propose` tool)["", "api", "workflow-changes", ..] => true,@@ -907,6 +910,13 @@ mod tests {assert!(!person_only(&get, "/api/tasks/t1/flags"));assert!(!person_only(&get, "/api/tasks"));assert!(!person_only(&get, "/api/missions/insights"));+ assert!(person_only(&post, "/api/goals"));+ assert!(person_only(&post, "/api/goals/g1/approve"));+ assert!(person_only(&post, "/api/goals/g1/check"));+ assert!(person_only(&Method::PATCH, "/api/goals/g1"));+ assert!(person_only(&del, "/api/goals/g1"));+ assert!(!person_only(&get, "/api/goals"));+ assert!(!person_only(&get, "/api/goals/g1"));assert!(person_only(&get, "/api/performance"));assert!(person_only(&post, "/api/passwords/bitwarden/unlock"));assert!(person_only(&del, "/api/passwords/bitwarden"));diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex b2d50403..a5ddb9bc 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -34,7 +34,7 @@ const AGENT_SEARCH_LIMIT: i64 = 20;/// Longest notification body.pub const NOTIFY_BODY_CHARS: usize = 200;const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(5);-pub const NOTIFY_KINDS: [&str; 14] = [+pub const NOTIFY_KINDS: [&str; 15] = ["turn_finished","approval_needed","routine_failed",@@ -49,6 +49,7 @@ pub const NOTIFY_KINDS: [&str; 14] = ["automation_suggested","tier_proposed","fact_disputed",+ "goal_alert",];const MASK: &str = "••••••••";@@ -515,6 +516,7 @@ fn tool_list(scope: &SelfScope, board: bool) -> Value {list.extend(super::missions::tools::tools());list.push(super::missions::flight_school::tool());list.push(super::missions::flight_school::propose_tool());+ list.push(super::goals::tool::tool());}list.extend(super::skills::tools());list.extend(super::mcp_suggest::tools());@@ -1125,6 +1127,7 @@ async fn call_tool(n if super::bot_actions::handles(n) => super::bot_actions::call(state, scope, n, args).await,n if super::hires::handles(n) => super::hires::call(state, scope, n, args).await,n if super::missions::tools::handles(n) => super::missions::tools::call(state, scope, n, args).await,+ super::goals::tool::TOOL => super::goals::tool::call(state, scope, args).await,"tier_status" => super::missions::flight_school::call_tool(state, &scope.kwant_id, args).await,"tier_propose" => super::missions::flight_school::call_propose(state, scope, args).await,"list_attachments" if scope.origin.is_some() => super::attachments::tool_list(state, scope).await,@@ -1467,8 +1470,8 @@ pub async fn notify_settings_view(state: &AppState) -> (String, Vec<String>) {pub const NOTIFY_KNOWN_SETTING: &str = "notify_known";/// Kinds added after `notify_on` lists were first saved but before `notify_known` existed: a list/// saved without `notify_known` was chosen from every kind but these.-const KINDS_SINCE_FIRST_LIST: [&str; 5] =- ["app_update", "work_ahead", "automation_suggested", "tier_proposed", "fact_disputed"];+const KINDS_SINCE_FIRST_LIST: [&str; 6] =+ ["app_update", "work_ahead", "automation_suggested", "tier_proposed", "fact_disputed", "goal_alert"];/// Kinds the user wants to hear about; all of them unless set. A kind added after the list was/// saved is on, so a new event isn't silently off for everyone who ever saved the settings.diff --git a/src/server/goals/mod.rs b/src/server/goals/mod.rsnew file mode 100644index 00000000..c977499a--- /dev/null+++ b/src/server/goals/mod.rs@@ -0,0 +1,597 @@+//! Goals (docs/mission-control.md §22): what should stay true, checked on a schedule. There is no+//! setting: goals show with the Mission board, and nothing runs until the person creates or+//! approves one, so an upgrade starts no background work. Quiet by default (plan B.0): a goal+//! tells the person only when its state changes, at most [`NOTICE_CAP`] times in 24 hours.++pub mod predicate;+pub mod routes;+pub mod runner;+pub mod tool;++use crate::db::goals::{Goal, GoalCheck, GoalEvent, NewGoal, NewGoalCheck, Observation};+use crate::db::missions::now_ms;+use crate::db::spaces::SpaceId;+use crate::drivers::events::RuntimeEvent;+use crate::server::continuity::{notify, Notification};+use crate::server::AppState;+use predicate::Predicate;+use serde::Deserialize;+use serde_json::{json, Value};++pub const MODES: [&str; 3] = ["watch", "suggest", "fix"];+pub const INTERVAL_RANGE: (i64, i64) = (15, 1440);+pub const DEFAULT_INTERVAL: i64 = 60;+pub const CONFIRM_RANGE: (i64, i64) = (1, 3);+/// Consecutive failing runs before a goal is called broken (plan B.0: a single failure is never news).+pub const DEFAULT_CONFIRM: i64 = 2;+pub const FIXES_RANGE: (i64, i64) = (1, 10);+pub const DEFAULT_MAX_FIXES: i64 = 3;+pub const PRIORITY_RANGE: (i64, i64) = (1, 3);+pub const DEFAULT_PRIORITY: i64 = 2;+pub const MAX_CHECKS: usize = 10;+pub const MAX_BUDGET: i64 = 10_000_000;+/// Freshness, in minutes: at most a week.+pub const FRESHNESS_RANGE: (i64, i64) = (1, 10_080);+/// Notices per goal in any rolling 24 hours (plan B.0 rule 1).+pub const NOTICE_CAP: i64 = 3;+pub const DAY_MS: i64 = 24 * 60 * 60 * 1000;+/// Unapproved drafts are deleted silently after this (plan B.0 rule 4).+pub const DRAFT_TTL_MS: i64 = 7 * DAY_MS;+/// A goal unknown this long gets its one "can't check" notice.+pub const UNKNOWN_NOTICE_MS: i64 = DAY_MS;+/// Statuses that mean an incident is open: further failures, or a run that can't check, change nothing.+pub const INCIDENT: [&str; 4] = ["not_met", "fixing", "needs_you", "waiting"];++/// A check as the person (or `goal_propose`) writes it.+#[derive(Debug, Clone, Deserialize)]+pub struct CheckInput {+ #[serde(default)]+ pub label: String,+ pub kind: String,+ #[serde(default)]+ pub spec: Value,+ pub metric: Option<String>,+ pub operator: Option<String>,+ /// Text or a number.+ #[serde(default)]+ pub target: Value,+ /// `required` (default) or `advisory`.+ pub severity: Option<String>,+ /// The v1 spelling of severity.+ pub required: Option<bool>,+ pub freshness_minutes: Option<i64>,+}++fn in_range(v: i64, (lo, hi): (i64, i64)) -> bool {+ (lo..=hi).contains(&v)+}++/// `v` if given and in range, the default if not given.+pub fn ranged(v: Option<i64>, range: (i64, i64), default: i64, what: &str) -> Result<i64, String> {+ match v {+ None => Ok(default),+ Some(n) if in_range(n, range) => Ok(n),+ Some(_) => Err(format!("{what} must be {}–{}", range.0, range.1)),+ }+}++/// Checks a goal's checks and fills in their defaults: a predicate for each typed kind, severity,+/// and freshness (twice the interval). At least one must be required, since only required checks+/// decide the goal. `has_folder`: command and file checks run in the bot's folder, so they need one.+pub fn validate_checks(input: &[CheckInput], interval: i64, has_folder: bool) -> Result<Vec<NewGoalCheck>, String> {+ if input.is_empty() {+ return Err("a goal needs at least one check".into());+ }+ if input.len() > MAX_CHECKS {+ return Err(format!("a goal has at most {MAX_CHECKS} checks"));+ }+ let mut out = Vec::new();+ for (i, c) in input.iter().enumerate() {+ let n = i + 1;+ let kind = c.kind.trim();+ if !predicate::metrics(kind).is_empty() || matches!(kind, "file_exists" | "file_contains" | "file_sha256") {+ } else {+ return Err(format!("check {n}: kind is one of command, http, file_exists, file_contains, file_sha256"));+ }+ if !c.spec.is_object() {+ return Err(format!("check {n}: spec must be an object"));+ }+ if kind != "http" && !has_folder {+ return Err(format!("check {n}: {kind} checks run in a bot's folder, so the goal needs a bot"));+ }+ // The person approves the goal, so an http check may reach this computer (plan B.4)+ crate::server::missions::validate_check(kind, &c.spec, true).map_err(|e| format!("check {n}: {e}"))?;+ let target = match &c.target {+ Value::Null => None,+ Value::String(s) => Some(s.clone()),+ Value::Number(x) => Some(x.to_string()),+ Value::Bool(b) => Some(b.to_string()),+ _ => return Err(format!("check {n}: target is text or a number")),+ };+ let pred = predicate::normalize(kind, &c.spec, c.metric.as_deref(), c.operator.as_deref(), target.as_deref()).map_err(|e| format!("check {n}: {e}"))?;+ let severity = match (c.severity.as_deref().map(str::trim), c.required) {+ (Some("required"), _) | (None, Some(true) | None) => "required",+ (Some("advisory"), _) | (None, Some(false)) => "advisory",+ (Some(other), _) => return Err(format!("check {n}: severity is required or advisory, not {other}")),+ };+ let freshness = ranged(c.freshness_minutes, FRESHNESS_RANGE, (interval * 2).min(FRESHNESS_RANGE.1), "freshness_minutes")+ .map_err(|e| format!("check {n}: {e}"))?;+ let label = match c.label.trim() {+ "" => predicate::says(kind, &c.spec, pred.as_ref()),+ l => l.to_string(),+ };+ out.push(NewGoalCheck {+ label: label.chars().take(200).collect(),+ kind: kind.to_string(),+ spec: c.spec.clone(),+ metric: pred.as_ref().map(|p| p.metric.clone()),+ operator: pred.as_ref().and_then(|p| p.operator.clone()),+ target: pred.as_ref().map(|p| p.target.clone()),+ severity: severity.into(),+ freshness_minutes: freshness,+ });+ }+ if !out.iter().any(|c| c.severity == "required") {+ return Err("at least one check must be required: advisory checks never decide a goal".into());+ }+ Ok(out)+}++/// A goal as the person (or `goal_propose`) writes it.+#[derive(Debug, Clone, Deserialize)]+pub struct GoalInput {+ #[serde(default)]+ pub title: String,+ #[serde(default)]+ pub description: String,+ /// Its bot (id or name); the space's first bot if left out.+ pub kwant_id: Option<String>,+ pub mode: Option<String>,+ pub interval_minutes: Option<i64>,+ pub confirm_failures: Option<i64>,+ pub budget_tokens: Option<i64>,+ pub max_fixes_per_day: Option<i64>,+ pub priority: Option<i64>,+ #[serde(default)]+ pub checks: Vec<CheckInput>,+ /// "Make this a goal" from a task: Juno's route (B.2), refused here until it lands.+ pub from_task: Option<String>,+}++pub fn valid_title(t: &str) -> Result<String, String> {+ let t = t.trim();+ if t.is_empty() || t.chars().count() > 200 {+ return Err("title must be 1–200 characters".into());+ }+ Ok(t.to_string())+}++pub fn valid_mode(m: Option<&str>, default: &str) -> Result<String, String> {+ match m.map(str::trim) {+ None => Ok(default.into()),+ Some(m) if MODES.contains(&m) => Ok(m.into()),+ Some(_) => Err("mode is watch, suggest or fix".into()),+ }+}++pub fn valid_budget(b: Option<i64>) -> Result<i64, String> {+ match b {+ None => Ok(0),+ Some(n) if (0..=MAX_BUDGET).contains(&n) => Ok(n),+ Some(_) => Err(format!("budget_tokens must be 0–{MAX_BUDGET}")),+ }+}++/// Checks a goal and fills in its defaults. `created_by`: "person" or the proposing bot's id;+/// `draft`: a bot's proposal, waiting for the person.+pub async fn build_goal(state: &AppState, space: &SpaceId, p: &GoalInput, created_by: &str, draft: bool) -> Result<NewGoal, String> {+ let title = valid_title(&p.title)?;+ if p.description.chars().count() > 2000 {+ return Err("description is at most 2000 characters".into());+ }+ let mode = valid_mode(p.mode.as_deref(), "suggest")?;+ let interval = ranged(p.interval_minutes, INTERVAL_RANGE, DEFAULT_INTERVAL, "interval_minutes")?;+ let confirm = ranged(p.confirm_failures, CONFIRM_RANGE, DEFAULT_CONFIRM, "confirm_failures")?;+ let fixes = ranged(p.max_fixes_per_day, FIXES_RANGE, DEFAULT_MAX_FIXES, "max_fixes_per_day")?;+ let priority = ranged(p.priority, PRIORITY_RANGE, DEFAULT_PRIORITY, "priority")?;+ let budget = valid_budget(p.budget_tokens)?;+ let bot = match p.kwant_id.as_deref().map(str::trim).filter(|s| !s.is_empty()) {+ Some(who) => Some(crate::server::missions::bot_in_space(state, space, who).await.ok_or("kwant_id isn't a bot in this space")?),+ None => state.db.list_kwants(space).await.ok().and_then(|b| b.into_iter().next()),+ };+ let checks = validate_checks(&p.checks, interval, bot.is_some())?;+ let kwant_id = bot.map(|b| b.id).unwrap_or_default();+ Ok(NewGoal {+ space_id: space.as_str().to_string(),+ title,+ description: p.description.trim().to_string(),+ kwant_id,+ // Empty: its bot's folder, found when it runs+ folder: String::new(),+ mode,+ interval_minutes: interval,+ confirm_failures: confirm,+ budget_tokens: budget,+ max_fixes_per_day: fixes,+ priority,+ created_by: created_by.into(),+ draft,+ checks,+ })+}++/// The stored predicate of a check; None for the file kinds.+pub fn predicate_of(c: &GoalCheck) -> Option<Predicate> {+ Predicate::from_json(&json!({ "metric": c.metric, "operator": c.operator, "target": c.target }))+}++/// What one run of a goal said, from its checks' verdicts.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RunSays {+ /// Every required check is met.+ Met,+ /// A required check is not met.+ Failed,+ /// No required check failed, but one couldn't say (an error or unreadable output).+ Unknown,+}++/// One check's verdict in a run.+#[derive(Debug, Clone, Copy)]+pub struct Judged {+ pub required: bool,+ pub verdict: &'static str,+ /// The check didn't run or got no answer.+ pub errored: bool,+}++/// The goal after a run: `(status, fail_streak, error_runs, says)`.+///+/// - Met resets both counters and the goal is met.+/// - Failed adds one to the streak. Only at `confirm` failures in a row does the goal become+/// not_met; before that it keeps its status (a met goal stays met: one failure is never news).+/// - Unknown is not a failure and breaks a run of failures: an error between two failures doesn't+/// confirm one (G-Q-02; the safer reading of Q14). The goal shows unknown.+/// - While an incident is open (not_met, fixing, needs_you, waiting), failures and unknown runs+/// keep its status, so a goal is never "broken" twice for one incident.+/// - Advisory checks never decide.+pub fn decide(prior: &str, fail_streak: i64, error_runs: i64, confirm: i64, results: &[Judged]) -> (String, i64, i64, RunSays) {+ let required: Vec<&Judged> = results.iter().filter(|j| j.required).collect();+ let says = if required.iter().any(|j| j.verdict == predicate::NOT_MET) {+ RunSays::Failed+ } else if !required.is_empty() && required.iter().all(|j| j.verdict == predicate::MET) {+ RunSays::Met+ } else {+ RunSays::Unknown+ };+ let open = INCIDENT.contains(&prior);+ match says {+ RunSays::Met => ("met".into(), 0, 0, says),+ RunSays::Failed => {+ let streak = fail_streak + 1;+ let status = if streak >= confirm && !open { "not_met" } else { prior };+ (status.into(), streak, 0, says)+ }+ RunSays::Unknown => {+ let all_errored = !results.is_empty() && results.iter().all(|j| j.errored);+ let status = if open { prior } else { "unknown" };+ (status.into(), 0, if all_errored { error_runs + 1 } else { 0 }, says)+ }+ }+}++/// Minutes to the next check: the interval, doubled for each run past the third where every check+/// errored, up to a day.+pub fn next_interval_minutes(interval: i64, error_runs: i64) -> i64 {+ if error_runs < 3 {+ return interval;+ }+ let doublings = (error_runs - 2).min(10) as u32;+ interval.saturating_mul(1 << doublings).min(1440)+}++/// Up to 10% of `minutes`, in ms, drawn fresh each time so goals made together spread out.+pub fn jitter_ms(minutes: i64) -> i64 {+ let span = minutes * 60_000 / 10;+ if span <= 0 {+ return 0;+ }+ (uuid::Uuid::new_v4().as_u128() % span as u128) as i64+}++fn parse(text: &str) -> Value {+ serde_json::from_str(text).unwrap_or(Value::Null)+}++/// A check with its newest observation. An observation at or past `expires_at` is out of date: its+/// verdict reads unknown, whatever it was.+pub fn check_json(c: &GoalCheck, latest: Option<&Observation>, now: i64, excerpt_chars: usize) -> Value {+ let spec = c.spec_value();+ let pred = predicate_of(c);+ let latest = latest.map(|o| {+ let expired = o.expires_at <= now;+ json!({+ "status": o.status,+ "verdict": if expired { predicate::UNKNOWN } else { o.verdict.as_str() },+ "expired": expired,+ "observed_value": o.observed_value,+ "excerpt": o.excerpt.chars().take(excerpt_chars).collect::<String>(),+ "observed_at": o.observed_at,+ "expires_at": o.expires_at,+ })+ });+ json!({+ "id": c.id,+ "label": c.label,+ "kind": c.kind,+ "spec": spec,+ "metric": c.metric,+ "operator": c.operator,+ "target": c.target,+ "severity": c.severity,+ "required": c.required(),+ "freshness_minutes": c.freshness_minutes,+ "says": predicate::says(&c.kind, &spec, pred.as_ref()),+ "latest": latest,+ })+}++/// The status to show: a met goal whose required check is out of date (or never ran) is unknown,+/// never met.+pub fn shown_status(g: &Goal, checks: &[GoalCheck], latest: &[Observation], now: i64) -> (String, String) {+ if g.status == "met" {+ let stale = checks.iter().filter(|c| c.required()).any(|c| latest.iter().find(|o| o.check_id == c.id).is_none_or(|o| o.expires_at <= now));+ if stale {+ return ("unknown".into(), "out_of_date".into());+ }+ }+ (g.status.clone(), g.status_reason.clone())+}++pub fn goal_fields(g: &Goal, status: &str, reason: &str) -> Value {+ json!({+ "id": g.id,+ "space_id": g.space_id,+ "title": g.title,+ "description": g.description,+ "kwant_id": g.kwant_id,+ "folder": g.folder,+ "status": status,+ "status_reason": reason,+ "mode": g.mode,+ "priority": g.priority,+ "interval_minutes": g.interval_minutes,+ "confirm_failures": g.confirm_failures,+ "budget_tokens": g.budget_tokens,+ "max_fixes_per_day": g.max_fixes_per_day,+ "created_by": g.created_by,+ "approved_by": g.approved_by,+ "approved_at": g.approved_at,+ "paused_at": g.paused_at,+ "next_check_at": g.next_check_at,+ "last_checked_at": g.last_checked_at,+ "checking_since": g.checking_since,+ "fail_streak": g.fail_streak,+ "unknown_since": g.unknown_since,+ "version": g.version,+ "created_at": g.created_at,+ "updated_at": g.updated_at,+ })+}++/// A goal with its checks and their newest observations. `excerpt_chars` keeps list rows small.+pub async fn goal_json(state: &AppState, g: &Goal, excerpt_chars: usize) -> Value {+ let now = now_ms();+ let checks = state.db.goal_checks(&g.id).await.unwrap_or_default();+ let latest = state.db.recent_observations(&g.id, 1).await.unwrap_or_default();+ let (status, reason) = shown_status(g, &checks, &latest, now);+ let mut v = goal_fields(g, &status, &reason);+ v["checks"] = checks.iter().map(|c| check_json(c, latest.iter().find(|o| o.check_id == c.id), now, excerpt_chars)).collect();+ v+}++pub fn event_json(e: &GoalEvent) -> Value {+ json!({ "id": e.id, "kind": e.kind, "actor": e.actor, "detail": parse(&e.detail), "created_at": e.created_at })+}++/// Tells open boards the goal changed (`status` "deleted" when it is gone).+pub fn emit(state: &AppState, id: &str, status: &str, space_id: &str) {+ let _ = state.event_sender.send(RuntimeEvent::GoalUpdated { id: id.into(), status: status.into(), space_id: space_id.into() });+}++pub fn emit_goal(state: &AppState, g: &Goal) {+ emit(state, &g.id, &g.status, &g.space_id);+}++/// Sends one goal notice (`kind`: broken, recovered, cant_check, needs_you) unless the goal+/// already had [`NOTICE_CAP`] in the last 24 hours. A capped notice is logged, never sent: the+/// cap hides pings, not state. Returns whether it went out.+pub async fn notice(state: &AppState, g: &Goal, kind: &str, title: String, body: String) -> bool {+ let now = now_ms();+ let sent = state.db.goal_notices_since(&g.id, now - DAY_MS).await.unwrap_or(0);+ if sent >= NOTICE_CAP {+ let _ = state.db.add_goal_event(&g.id, "notice_capped", "kwant", &json!({ "kind": kind })).await;+ return false;+ }+ let bot = match state.db.get_kwant(&g.kwant_id).await.ok().flatten() {+ Some(k) => Some(k),+ None => state.db.list_kwants(&SpaceId::new(&g.space_id)).await.ok().and_then(|ks| ks.into_iter().next()),+ };+ let Some(bot) = bot else {+ return false;+ };+ let _ = state.db.add_goal_event(&g.id, "notified", "kwant", &json!({ "kind": kind })).await;+ notify(state, Notification { kind: "goal_alert", kwant_id: bot.id, kwant_name: bot.name, channel_id: None, title, body }).await;+ true+}++fn clock(ms: i64) -> String {+ chrono::DateTime::from_timestamp_millis(ms).map(|t| t.format("%H:%M UTC").to_string()).unwrap_or_default()+}++/// The notices a run's change of state earns (plan B.0 rule 1): broken when an incident opens,+/// recovered when a goal the person was told about is met again. `owed_recovery` is read before+/// the run wrote its `met` event. Remediation (B.2) may send broken later, with the diagnosis.+pub async fn on_change(state: &AppState, before: &str, after: &Goal, failing: &[String], owed_recovery: bool) {+ if after.status == "not_met" && !INCIDENT.contains(&before) {+ let what = failing.first().cloned().unwrap_or_else(|| "a check".into());+ let body = format!("Since {}, this isn't true: {what}. kwant checked {} times in a row. Open the Mission board to see what it saw.", clock(now_ms()), after.confirm_failures.max(1));+ notice(state, after, "broken", format!("{} is failing", after.title), body).await;+ } else if after.status == "met" && before != "met" && owed_recovery {+ notice(state, after, "recovered", format!("{} is OK again", after.title), "Its checks pass again. Nothing else to do.".into()).await;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn j(required: bool, verdict: &'static str) -> Judged {+ Judged { required, verdict, errored: verdict == predicate::UNKNOWN }+ }++ const MET: &str = predicate::MET;+ const NOT: &str = predicate::NOT_MET;+ const UNK: &str = predicate::UNKNOWN;++ /// Runs `seq` from a fresh goal; returns the statuses after each run.+ fn walk(confirm: i64, seq: &[&[Judged]]) -> Vec<String> {+ let (mut status, mut streak, mut errs) = ("checking".to_string(), 0, 0);+ let mut out = Vec::new();+ for r in seq {+ let (s, st, e, _) = decide(&status, streak, errs, confirm, r);+ (status, streak, errs) = (s, st, e);+ out.push(status.clone());+ }+ out+ }++ #[test]+ fn one_failure_is_never_news_and_two_confirm() {+ let ok: &[Judged] = &[j(true, MET)];+ let bad: &[Judged] = &[j(true, NOT)];+ // G-V-02, G-V-03+ assert_eq!(walk(2, &[ok, bad]), ["met", "met"]);+ assert_eq!(walk(2, &[ok, bad, bad]), ["met", "met", "not_met"]);+ // G-V-04: a pass resets the streak+ assert_eq!(walk(2, &[ok, bad, ok, bad]), ["met", "met", "met", "met"]);+ // G-V-09: confirm 1 and 3+ assert_eq!(walk(1, &[ok, bad]), ["met", "not_met"]);+ assert_eq!(walk(3, &[ok, bad, bad, bad]), ["met", "met", "met", "not_met"]);+ // A new goal is never met before a pass (G-V-01)+ assert_eq!(walk(2, &[bad]), ["checking"]);+ }++ #[test]+ fn an_error_is_unknown_and_never_confirms_a_failure() {+ let ok: &[Judged] = &[j(true, MET)];+ let bad: &[Judged] = &[j(true, NOT)];+ let err: &[Judged] = &[j(true, UNK)];+ // G-T-05, G-V-05, G-Q-02: fail, error, fail doesn't confirm+ assert_eq!(walk(2, &[ok, bad, err, bad]), ["met", "met", "unknown", "unknown"]);+ assert_eq!(walk(2, &[ok, err, err]), ["met", "unknown", "unknown"]);+ // Once confirmed, an error during the incident keeps it open: no second "broken"+ assert_eq!(walk(2, &[ok, bad, bad, err, bad]), ["met", "met", "not_met", "not_met", "not_met"]);+ // Recovery closes it+ assert_eq!(walk(2, &[bad, bad, ok]), ["checking", "not_met", "met"]);+ }++ #[test]+ fn advisory_checks_never_decide() {+ // G-T-07, G-V-07, G-V-08+ let adv_fails: &[Judged] = &[j(true, MET), j(false, NOT)];+ let adv_unknown: &[Judged] = &[j(true, MET), j(false, UNK)];+ let one_unknown: &[Judged] = &[j(true, MET), j(true, UNK)];+ assert_eq!(decide("met", 0, 0, 1, adv_fails).3, RunSays::Met);+ assert_eq!(decide("met", 0, 0, 1, adv_unknown).3, RunSays::Met);+ assert_eq!(decide("met", 0, 0, 1, one_unknown).0, "unknown");+ assert_eq!(decide("met", 0, 0, 1, &[j(false, MET)]).0, "unknown");+ }++ #[test]+ fn the_backoff_counts_only_runs_where_everything_errored() {+ let all_err: &[Judged] = &[j(true, UNK), j(false, UNK)];+ let partly = [Judged { required: true, verdict: UNK, errored: false }, j(false, MET)];+ assert_eq!(decide("unknown", 0, 2, 2, all_err).2, 3);+ assert_eq!(decide("unknown", 0, 2, 2, &partly).2, 0);+ assert_eq!(decide("unknown", 0, 5, 2, &[j(true, MET)]).2, 0);+ // G-V-10+ assert_eq!(next_interval_minutes(60, 2), 60);+ assert_eq!(next_interval_minutes(60, 3), 120);+ assert_eq!(next_interval_minutes(60, 4), 240);+ assert_eq!(next_interval_minutes(60, 40), 1440);+ for _ in 0..50 {+ assert!((0..360_000).contains(&jitter_ms(60)));+ }+ }++ fn input(v: Value) -> Vec<CheckInput> {+ serde_json::from_value(v).unwrap()+ }++ #[test]+ fn checks_are_validated_with_their_defaults() {+ let c = validate_checks(&input(json!([{"kind": "http", "spec": {"url": "https://example.com"}}])), 60, false).unwrap();+ assert_eq!((c[0].metric.as_deref(), c[0].operator.as_deref(), c[0].target.as_deref()), (Some("status"), Some("eq"), Some("200")));+ assert_eq!((c[0].severity.as_str(), c[0].freshness_minutes), ("required", 120));+ assert_eq!(c[0].label, "https://example.com answers with status 200");+ let c = validate_checks(&input(json!([{"kind": "http", "spec": {"url": "https://e.x"}, "metric": "latency_ms", "operator": "lt", "target": 500}])), 15, false).unwrap();+ assert_eq!(c[0].target.as_deref(), Some("500"));+ // G-T-07: only advisory is refused; G-T-08+ for (bad, why) in [+ (json!([{"kind": "http", "spec": {"url": "https://e.x"}, "severity": "advisory"}]), "at least one check must be required"),+ (json!([{"kind": "http", "spec": {"url": "https://e.x"}, "metric": "latency_ms", "operator": "eq", "target": 5}]), "latency_ms takes"),+ (json!([{"kind": "http", "spec": {"url": "https://e.x"}, "metric": "stdout_number", "target": 5}]), "metric is one of"),+ (json!([{"kind": "http", "spec": {"url": "https://e.x"}, "metric": "latency_ms"}]), "needs a target"),+ (json!([{"kind": "command", "spec": {"command": "true"}}]), "needs a bot"),+ (json!([{"kind": "ftp", "spec": {}}]), "kind is one of"),+ (json!([{"kind": "http", "spec": {"url": "https://e.x"}, "severity": "maybe"}]), "severity is required or advisory"),+ (json!([{"kind": "http", "spec": {"url": "https://e.x"}, "freshness_minutes": 0}]), "freshness_minutes"),+ (json!([]), "at least one check"),+ ] {+ let e = validate_checks(&input(bad.clone()), 60, false).unwrap_err();+ assert!(e.contains(why), "{bad}: {e}");+ }+ assert!(validate_checks(&input(json!([{"kind": "command", "spec": {"command": "true"}}])), 60, true).is_ok());+ }++ fn obs(check: &str, expires_at: i64) -> Observation {+ Observation {+ id: 1,+ goal_id: "g".into(),+ check_id: check.into(),+ status: "passed".into(),+ verdict: "met".into(),+ observed_value: Some("200".into()),+ excerpt: "x".repeat(50),+ observed_at: 0,+ expires_at,+ }+ }++ fn check(id: &str, severity: &str) -> GoalCheck {+ GoalCheck {+ id: id.into(),+ goal_id: "g".into(),+ position: 0,+ label: "l".into(),+ kind: "http".into(),+ spec: r#"{"url":"https://e.x"}"#.into(),+ metric: Some("status".into()),+ operator: Some("eq".into()),+ target: Some("200".into()),+ severity: severity.into(),+ freshness_minutes: 120,+ }+ }++ #[test]+ fn an_out_of_date_observation_is_unknown_never_met() {+ // G-T-06: expired at the boundary too+ let v = check_json(&check("c", "required"), Some(&obs("c", 1000)), 1000, 10);+ assert_eq!((v["latest"]["verdict"].as_str(), v["latest"]["expired"].as_bool()), (Some("unknown"), Some(true)));+ assert_eq!(v["latest"]["excerpt"].as_str().map(str::len), Some(10));+ let v = check_json(&check("c", "required"), Some(&obs("c", 1001)), 1000, 10);+ assert_eq!(v["latest"]["verdict"], "met");+ }+}diff --git a/src/server/goals/predicate.rs b/src/server/goals/predicate.rsnew file mode 100644index 00000000..28543d44--- /dev/null+++ b/src/server/goals/predicate.rs@@ -0,0 +1,605 @@+//! A goal check's typed predicate (docs/mission-control.md §22): which value of a run it reads+//! (the metric), how it compares (the operator) and with what (the target). The file kinds keep+//! their v1 meaning and take none. Matching is literal: no regex, no shell, nothing in a target is+//! evaluated. An error, or output the predicate can't read, is `unknown`, never `not_met`.++use crate::server::missions::autofix::redact;+use crate::server::missions::checks::{run_spec_seen, Seen};+use serde_json::{json, Value};+use std::path::Path;+use std::time::Instant;++pub const MET: &str = "met";+pub const NOT_MET: &str = "not_met";+pub const UNKNOWN: &str = "unknown";++/// Largest number a numeric target may hold.+pub const MAX_NUMBER: f64 = 1e15;+pub const MAX_TARGET_CHARS: usize = 1000;+pub const MAX_LATENCY_MS: f64 = 600_000.0;+/// Longest stored observed value.+const MAX_OBSERVED_CHARS: usize = 500;++/// The metrics `kind` offers; none for the file kinds.+pub fn metrics(kind: &str) -> &'static [&'static str] {+ match kind {+ "http" => &["status", "latency_ms", "body_contains", "json_value"],+ "command" => &["exit_code", "stdout_contains", "stdout_number"],+ _ => &[],+ }+}++/// The operators `metric` takes, its default first. Empty: a contains metric, which matches its+/// target as written and takes no operator.+pub fn operators(metric: &str) -> &'static [&'static str] {+ match metric {+ "status" | "exit_code" => &["eq", "ne"],+ "latency_ms" => &["lt", "lte"],+ "json_value" => &["eq", "ne", "lt", "lte", "gt", "gte", "contains"],+ "stdout_number" => &["eq", "ne", "lt", "lte", "gt", "gte"],+ _ => &[],+ }+}++#[derive(Debug, Clone, PartialEq)]+pub struct Predicate {+ pub metric: String,+ /// None for a contains metric.+ pub operator: Option<String>,+ pub target: String,+}++impl Predicate {+ fn new(metric: &str, operator: Option<&str>, target: &str) -> Self {+ Predicate { metric: metric.into(), operator: operator.map(Into::into), target: target.into() }+ }++ pub fn to_json(&self) -> Value {+ json!({ "metric": self.metric, "operator": self.operator, "target": self.target })+ }++ /// A predicate a fix task's check carries in `spec.predicate`.+ pub fn from_json(v: &Value) -> Option<Self> {+ let metric = v["metric"].as_str()?;+ let target = v["target"].as_str()?;+ Some(Predicate::new(metric, v["operator"].as_str(), target))+ }+}++/// What a check of `kind` means when the person gave no metric: status 200 for http, exit code 0+/// for a command; None for the file kinds.+pub fn default_predicate(kind: &str) -> Option<Predicate> {+ match kind {+ "http" => Some(Predicate::new("status", Some("eq"), "200")),+ "command" => Some(Predicate::new("exit_code", Some("eq"), "0")),+ _ => None,+ }+}++/// A finite number within [`MAX_NUMBER`], as a target or a JSON string holds it.+pub fn number(s: &str) -> Option<f64> {+ s.trim().parse::<f64>().ok().filter(|n| n.is_finite() && n.abs() <= MAX_NUMBER)+}++fn whole(s: &str, lo: i64, hi: i64) -> Option<i64> {+ s.trim().parse::<i64>().ok().filter(|n| (lo..=hi).contains(n))+}++/// A JSON pointer: empty (the whole document) or `/`-separated, with `~0` / `~1` escapes only.+fn valid_pointer(p: &str) -> bool {+ if p.is_empty() {+ return true;+ }+ if !p.starts_with('/') || p.len() > 500 {+ return false;+ }+ let mut chars = p.chars().peekable();+ while let Some(c) = chars.next() {+ if c == '~' && !matches!(chars.next(), Some('0' | '1')) {+ return false;+ }+ }+ true+}++/// Checks and completes a check's predicate. With no metric, operator or target a kind gets its+/// default ([`default_predicate`]); a metric without an operator gets the metric's first; every+/// metric needs a target. Returns None for the file kinds.+pub fn normalize(kind: &str, spec: &Value, metric: Option<&str>, operator: Option<&str>, target: Option<&str>) -> Result<Option<Predicate>, String> {+ let metric = metric.map(str::trim).filter(|m| !m.is_empty());+ let operator = operator.map(str::trim).filter(|o| !o.is_empty());+ let offered = metrics(kind);+ if offered.is_empty() {+ if metric.is_some() || operator.is_some() || target.is_some() {+ return Err(format!("{kind} checks take no metric, operator or target"));+ }+ return Ok(None);+ }+ let Some(metric) = metric else {+ if operator.is_some() || target.is_some() {+ return Err(format!("say which value the target is for: metric is one of {}", offered.join(", ")));+ }+ return Ok(default_predicate(kind));+ };+ if !offered.contains(&metric) {+ return Err(format!("a {kind} check's metric is one of {}, not {metric}", offered.join(", ")));+ }+ let ops = operators(metric);+ let operator = match operator {+ None if ops.is_empty() => None,+ Some("contains") if ops.is_empty() => None,+ Some(o) if ops.is_empty() => return Err(format!("{metric} matches its target as written and takes no operator, not {o}")),+ None => Some(ops[0]),+ Some(o) if ops.contains(&o) => Some(o),+ Some(o) => return Err(format!("{metric} takes {}, not {o}", ops.join(", "))),+ };+ let target = target.ok_or_else(|| format!("{metric} needs a target"))?;+ if target.chars().count() > MAX_TARGET_CHARS {+ return Err(format!("the target is too long ({MAX_TARGET_CHARS} characters at most)"));+ }+ let target = match metric {+ "status" => whole(target, 100, 599).ok_or("an http status target is a whole number from 100 to 599")?.to_string(),+ "exit_code" => whole(target, 0, 255).ok_or("an exit code target is a whole number from 0 to 255")?.to_string(),+ "latency_ms" => {+ let n = number(target).filter(|n| (0.0..=MAX_LATENCY_MS).contains(n)).ok_or("a latency target is a number of milliseconds from 0 to 600000")?;+ plain(n)+ }+ "stdout_number" => plain(number(target).ok_or("stdout_number needs a number target, at most 1e15 either way")?),+ "json_value" => {+ if !spec["pointer"].is_null() && !spec["pointer"].as_str().is_some_and(valid_pointer) {+ return Err("spec.pointer is a JSON pointer: empty for the whole document, or like /status or /items/0/name".into());+ }+ match operator {+ Some("lt" | "lte" | "gt" | "gte") => plain(number(target).ok_or("a json_value compared with lt, lte, gt or gte needs a number target, at most 1e15 either way")?),+ Some("contains") if target.is_empty() => return Err("json_value contains needs a target".into()),+ _ => target.to_string(),+ }+ }+ _ if target.is_empty() => return Err(format!("{metric} needs the text to look for")),+ _ => target.to_string(),+ };+ Ok(Some(Predicate::new(metric, operator, &target)))+}++/// A number as a target stores it: whole numbers without a decimal point.+fn plain(n: f64) -> String {+ if n.fract() == 0.0 && n.abs() < 1e15 {+ format!("{}", n as i64)+ } else {+ n.to_string()+ }+}++/// The first number in `text`: an optional `-`, digits with optional `,ddd` thousands groups, an+/// optional decimal part and an optional exponent (`Total: 1,234.5` is 1234.5, `1e3` is 1000,+/// `42abc` is 42). None if there is none.+pub fn first_number(text: &str) -> Option<f64> {+ let b = text.as_bytes();+ let digit = |k: usize| b.get(k).is_some_and(u8::is_ascii_digit);+ let mut i = 0;+ while i < b.len() {+ let neg = b[i] == b'-';+ let mut k = i + usize::from(neg);+ if !(digit(k) || (b.get(k) == Some(&b'.') && digit(k + 1))) {+ i += 1;+ continue;+ }+ let mut s = String::from(if neg { "-" } else { "" });+ while digit(k) {+ s.push(b[k] as char);+ k += 1;+ }+ while b.get(k) == Some(&b',') && digit(k + 1) && digit(k + 2) && digit(k + 3) && !digit(k + 4) {+ s.push_str(&text[k + 1..k + 4]);+ k += 4;+ }+ if b.get(k) == Some(&b'.') && digit(k + 1) {+ s.push('.');+ k += 1;+ while digit(k) {+ s.push(b[k] as char);+ k += 1;+ }+ }+ if matches!(b.get(k), Some(b'e' | b'E')) {+ let sign = matches!(b.get(k + 1), Some(b'+' | b'-'));+ let mut e = k + 1 + usize::from(sign);+ if digit(e) {+ s.push('e');+ if sign {+ s.push(b[k + 1] as char);+ }+ while digit(e) {+ s.push(b[e] as char);+ e += 1;+ }+ }+ }+ return s.parse::<f64>().ok().filter(|n| n.is_finite());+ }+ None+}++fn compare(value: f64, op: &str, target: f64) -> Option<bool> {+ Some(match op {+ "eq" => value == target,+ "ne" => value != target,+ "lt" => value < target,+ "lte" => value <= target,+ "gt" => value > target,+ "gte" => value >= target,+ _ => return None,+ })+}++fn verdict(holds: Option<bool>) -> &'static str {+ match holds {+ Some(true) => MET,+ Some(false) => NOT_MET,+ None => UNKNOWN,+ }+}++fn shown(n: f64) -> String {+ plain(n)+}++/// A JSON value as text: a string as written, anything else as JSON.+fn render(v: &Value) -> String {+ match v {+ Value::String(s) => s.clone(),+ other => other.to_string(),+ }+}++/// A JSON number, or a string that reads as one (eq and ne compare leniently: 200 equals "200").+fn as_number(v: &Value) -> Option<f64> {+ match v {+ Value::Number(n) => n.as_f64(),+ Value::String(s) => number(s),+ _ => None,+ }+}++fn text_contains(haystack: Option<&str>, needle: &str) -> (&'static str, Option<String>) {+ match haystack {+ None => (UNKNOWN, None),+ Some(h) if h.contains(needle) => (MET, Some("found".into())),+ Some(_) => (NOT_MET, Some("not found".into())),+ }+}++fn json_value(body: Option<&str>, pointer: &str, op: &str, target: &str) -> (&'static str, Option<String>) {+ let Some(body) = body else { return (UNKNOWN, None) };+ let Ok(doc) = serde_json::from_str::<Value>(body) else { return (UNKNOWN, Some("not JSON".into())) };+ // A JSON answer without the value is an answer: not met+ let Some(v) = doc.pointer(pointer) else { return (NOT_MET, Some("missing".into())) };+ let holds = match op {+ "eq" | "ne" => {+ let same = match (as_number(v), number(target)) {+ (Some(a), Some(b)) => a == b,+ _ => render(v) == target,+ };+ Some(same == (op == "eq"))+ }+ "contains" => match v {+ Value::String(s) => Some(s.contains(target)),+ Value::Array(items) => Some(items.iter().any(|i| match (as_number(i), number(target)) {+ (Some(a), Some(b)) => a == b,+ _ => render(i) == target,+ })),+ _ => None,+ },+ o => match (as_number(v), number(target)) {+ (Some(a), Some(b)) => compare(a, o, b),+ _ => None,+ },+ };+ (verdict(holds), Some(render(v)))+}++/// One check's verdict on what its run saw, with the value it read. `status` is the run's own+/// result: `error` (it didn't run, or got no answer) is always unknown.+pub fn judge(pred: Option<&Predicate>, spec: &Value, status: &str, seen: &Seen, latency_ms: i64) -> (&'static str, Option<String>) {+ if status == "error" {+ return (UNKNOWN, None);+ }+ let Some(p) = pred else {+ // The file kinds: v1's meaning+ return (if status == "passed" { MET } else { NOT_MET }, None);+ };+ let op = p.operator.as_deref().unwrap_or("");+ let target = number(&p.target);+ match p.metric.as_str() {+ "status" => match (seen.http_status, target) {+ (Some(code), Some(t)) => (verdict(compare(f64::from(code), op, t)), Some(code.to_string())),+ (code, _) => (UNKNOWN, code.map(|c| c.to_string())),+ },+ "latency_ms" => match target {+ Some(t) => (verdict(compare(latency_ms as f64, op, t)), Some(latency_ms.to_string())),+ None => (UNKNOWN, Some(latency_ms.to_string())),+ },+ "body_contains" => text_contains(seen.body.as_deref(), &p.target),+ "json_value" => json_value(seen.body.as_deref(), spec["pointer"].as_str().unwrap_or(""), op, &p.target),+ "exit_code" => match (seen.exit_code, target) {+ // Killed, not executable or not found: the command didn't say anything about the goal+ (Some(code), _) if code < 0 || code == 126 || code == 127 => (UNKNOWN, Some(code.to_string())),+ (Some(code), Some(t)) => (verdict(compare(code as f64, op, t)), Some(code.to_string())),+ (code, _) => (UNKNOWN, code.map(|c| c.to_string())),+ },+ "stdout_contains" => text_contains(seen.stdout.as_deref(), &p.target),+ "stdout_number" => match (seen.stdout.as_deref().map(first_number), target) {+ (Some(Some(n)), Some(t)) => (verdict(compare(n, op, t)), Some(shown(n))),+ (Some(None), _) => (UNKNOWN, Some("no number".into())),+ _ => (UNKNOWN, None),+ },+ _ => (UNKNOWN, None),+ }+}++/// A check's run, judged.+#[derive(Debug, Clone)]+pub struct Outcome {+ /// What the check did: `passed`, `failed` or `error` (v1's meaning).+ pub status: String,+ pub verdict: &'static str,+ /// Redacted, at most 500 characters.+ pub observed: Option<String>,+ /// Redacted output, at most 2 000 characters.+ pub excerpt: String,+}++fn cap(s: &str, n: usize) -> String {+ if s.chars().count() <= n {+ return s.to_string();+ }+ let mut out: String = s.chars().take(n - 1).collect();+ out.push('…');+ out+}++/// Runs one check and judges it. The latency is the whole GET, body included (up to 5 MB).+/// Nothing but the redacted excerpt and observed value leaves here: never the body.+pub async fn run(kind: &str, spec: &Value, pred: Option<&Predicate>, folder: Option<&Path>, person_ok: bool) -> Outcome {+ let started = Instant::now();+ let (status, output, seen) = run_spec_seen(kind, spec, folder, person_ok).await;+ let latency = i64::try_from(started.elapsed().as_millis()).unwrap_or(i64::MAX);+ let (verdict, observed) = judge(pred, spec, &status, &seen, latency);+ Outcome { status, verdict, observed: observed.map(|o| cap(&redact(&o), MAX_OBSERVED_CHARS)), excerpt: redact(&output) }+}++/// Plain words for a predicate, as the person reads it before approving ("responds in under+/// 500 ms"). They say what the stored metric, operator and target mean.+pub fn says(kind: &str, spec: &Value, pred: Option<&Predicate>) -> String {+ let s = |k: &str| spec[k].as_str().unwrap_or("").trim().to_string();+ let rel = |op: &str| match op {+ "eq" => "equal to",+ "ne" => "not equal to",+ "lt" => "below",+ "lte" => "at most",+ "gt" => "above",+ "gte" => "at least",+ _ => "containing",+ };+ let Some(p) = pred else {+ return match kind {+ "file_exists" => format!("{} exists", s("path")),+ "file_contains" => format!("{} contains \"{}\"", s("path"), spec["text"].as_str().unwrap_or("")),+ "file_sha256" => format!("{} is unchanged (sha256 {})", s("path"), s("sha256").chars().take(12).collect::<String>()),+ other => format!("a {other} check"),+ };+ };+ let op = p.operator.as_deref().unwrap_or("");+ let t = &p.target;+ match p.metric.as_str() {+ "status" if op == "ne" => format!("{} doesn't answer with status {t}", s("url")),+ "status" => format!("{} answers with status {t}", s("url")),+ "latency_ms" if op == "lte" => format!("{} responds in {t} ms or less", s("url")),+ "latency_ms" => format!("{} responds in under {t} ms", s("url")),+ "body_contains" => format!("the page at {} contains \"{t}\"", s("url")),+ "json_value" => {+ let at = match s("pointer") {+ p if p.is_empty() => "the JSON".to_string(),+ p => p,+ };+ format!("{at} at {} is {} {t}", s("url"), rel(op))+ }+ "exit_code" if op == "ne" => format!("`{}` doesn't exit with code {t}", s("command")),+ "exit_code" if t == "0" => format!("`{}` succeeds (exit code 0)", s("command")),+ "exit_code" => format!("`{}` exits with code {t}", s("command")),+ "stdout_contains" => format!("`{}` prints \"{t}\"", s("command")),+ "stdout_number" => format!("the first number `{}` prints is {} {t}", s("command"), rel(op)),+ other => format!("{other} {op} {t}"),+ }+}++/// A fix task's check that carries its goal's predicate (`spec.predicate`) is judged by it, so the+/// fix is verified by what the goal means. Returns `(status, output)` as [`run_spec`] does, the+/// predicate's unknown being an error; None without a predicate.+///+/// [`run_spec`]: crate::server::missions::checks::run_spec+pub async fn run_for_check(kind: &str, spec: &Value, folder: Option<&Path>, person_ok: bool) -> Option<(String, String)> {+ let pred = Predicate::from_json(&spec["predicate"])?;+ let out = run(kind, spec, Some(&pred), folder, person_ok).await;+ let status = match out.verdict {+ MET => "passed",+ NOT_MET => "failed",+ _ => "error",+ };+ let wanted = says(kind, spec, Some(&pred));+ let seen = out.observed.as_deref().map(|o| format!(" (observed: {o})")).unwrap_or_default();+ Some((status.into(), format!("{} {wanted}{seen}\n{}", if status == "passed" { "met:" } else { "not met:" }, out.excerpt)))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn p(metric: &str, op: Option<&str>, target: &str) -> Predicate {+ Predicate::new(metric, op, target)+ }++ fn http(code: u16, body: &str) -> Seen {+ Seen { http_status: Some(code), body: Some(body.into()), ..Default::default() }+ }++ fn cmd(code: i64, out: &str) -> Seen {+ Seen { exit_code: Some(code), stdout: Some(out.into()), ..Default::default() }+ }++ fn j(pred: &Predicate, spec: Value, seen: &Seen) -> (&'static str, Option<String>) {+ judge(Some(pred), &spec, "failed", seen, 0)+ }++ #[test]+ fn the_first_number_is_read() {+ assert_eq!(first_number("Total: 42"), Some(42.0));+ assert_eq!(first_number("1,234"), Some(1234.0));+ assert_eq!(first_number("1,234,567 rows"), Some(1_234_567.0));+ assert_eq!(first_number("12,34"), Some(12.0));+ assert_eq!(first_number("3.5"), Some(3.5));+ assert_eq!(first_number("-2"), Some(-2.0));+ assert_eq!(first_number("1e3"), Some(1000.0));+ assert_eq!(first_number("2.5E-1"), Some(0.25));+ assert_eq!(first_number("7 then 9"), Some(7.0));+ assert_eq!(first_number("42abc"), Some(42.0));+ assert_eq!(first_number(".5"), Some(0.5));+ assert_eq!(first_number("a - 2"), Some(2.0));+ assert_eq!(first_number("none here"), None);+ assert_eq!(first_number(""), None);+ }++ #[test]+ fn http_status_and_latency() {+ let ok = p("status", Some("eq"), "200");+ assert_eq!(j(&ok, json!({}), &http(200, "")), (MET, Some("200".into())));+ assert_eq!(j(&ok, json!({}), &http(204, "")).0, NOT_MET);+ assert_eq!(j(&ok, json!({}), &http(500, "")).0, NOT_MET);+ // Redirects aren't followed: a 301 is what was seen+ assert_eq!(j(&ok, json!({}), &http(301, "")), (NOT_MET, Some("301".into())));+ assert_eq!(j(&p("status", Some("ne"), "500"), json!({}), &http(503, "")).0, MET);+ // lt fails at the limit, lte passes+ let lt = p("latency_ms", Some("lt"), "500");+ let lte = p("latency_ms", Some("lte"), "500");+ let at = |pred: &Predicate, ms| judge(Some(pred), &json!({}), "passed", &http(200, ""), ms).0;+ assert_eq!((at(<, 499), at(<, 500), at(<, 501)), (MET, NOT_MET, NOT_MET));+ assert_eq!((at(<e, 499), at(<e, 500), at(<e, 501)), (MET, MET, NOT_MET));+ }++ #[test]+ fn contains_is_literal_and_case_sensitive() {+ let has = p("body_contains", None, "ok");+ assert_eq!(j(&has, json!({}), &http(200, "all ok")), (MET, Some("found".into())));+ assert_eq!(j(&has, json!({}), &http(200, "fine")), (NOT_MET, Some("not found".into())));+ assert_eq!(j(&has, json!({}), &http(200, "OK")).0, NOT_MET);+ let big = format!("{}ok", "x".repeat(5 * 1024 * 1024 - 2));+ assert_eq!(j(&has, json!({}), &http(200, &big)).0, MET);+ let re = p("body_contains", None, "a.*b");+ assert_eq!(j(&re, json!({}), &http(200, "axxb")).0, NOT_MET);+ assert_eq!(j(&re, json!({}), &http(200, "a.*b")).0, MET);+ let sh = p("stdout_contains", None, "$(whoami)");+ assert_eq!(j(&sh, json!({}), &cmd(0, "me")).0, NOT_MET);+ assert_eq!(j(&sh, json!({}), &cmd(0, "literal $(whoami)")).0, MET);+ }++ #[test]+ fn json_values_by_pointer() {+ let body = r#"{"status":"ok","code":200,"text":"200","a":[{"b":3}],"a/b":true,"n":null,"tags":["x","y",5]}"#;+ let at = |ptr: &str, op: &str, t: &str| j(&p("json_value", Some(op), t), json!({ "pointer": ptr }), &http(200, body));+ assert_eq!(at("/status", "eq", "ok"), (MET, Some("ok".into())));+ assert_eq!(at("/a/0/b", "gte", "3"), (MET, Some("3".into())));+ assert_eq!(at("/a~1b", "eq", "true").0, MET);+ assert_eq!(at("/missing", "eq", "x"), (NOT_MET, Some("missing".into())));+ // Lenient: 200 equals "200" either way round+ assert_eq!(at("/code", "eq", "200").0, MET);+ assert_eq!(at("/text", "eq", "200").0, MET);+ assert_eq!(at("/text", "lt", "300").0, MET);+ assert_eq!(at("/n", "eq", "null"), (MET, Some("null".into())));+ assert_eq!(at("/tags", "contains", "y").0, MET);+ assert_eq!(at("/tags", "contains", "5").0, MET);+ assert_eq!(at("/tags", "contains", "z").0, NOT_MET);+ assert_eq!(at("/status", "contains", "o").0, MET);+ // A number can't be ordered against text, nor searched+ assert_eq!(at("/status", "gt", "1").0, UNKNOWN);+ assert_eq!(at("/code", "contains", "2").0, UNKNOWN);+ assert_eq!(at("", "contains", "x").0, UNKNOWN);+ let not_json = j(&p("json_value", Some("eq"), "1"), json!({ "pointer": "/a" }), &http(200, "<html>"));+ assert_eq!(not_json, (UNKNOWN, Some("not JSON".into())));+ }++ #[test]+ fn commands_by_exit_code_and_output() {+ let zero = p("exit_code", Some("eq"), "0");+ assert_eq!(j(&zero, json!({}), &cmd(0, "")), (MET, Some("0".into())));+ assert_eq!(j(&zero, json!({}), &cmd(1, "")).0, NOT_MET);+ assert_eq!(j(&p("exit_code", Some("ne"), "0"), json!({}), &cmd(1, "")).0, MET);+ assert_eq!(j(&p("exit_code", Some("eq"), "1"), json!({}), &cmd(1, "")).0, MET);+ // Not found, not executable, killed: unknown whatever the operator says+ assert_eq!(j(&zero, json!({}), &cmd(127, "")).0, UNKNOWN);+ assert_eq!(j(&p("exit_code", Some("ne"), "0"), json!({}), &cmd(126, "")).0, UNKNOWN);+ assert_eq!(j(&zero, json!({}), &cmd(-1, "")).0, UNKNOWN);+ let n = |op: &str, t: &str, out: &str| j(&p("stdout_number", Some(op), t), json!({}), &cmd(0, out));+ assert_eq!(n("eq", "42", "Total: 42"), (MET, Some("42".into())));+ assert_eq!(n("gt", "1000", "1,234").0, MET);+ assert_eq!(n("lt", "4", "3.5").0, MET);+ assert_eq!(n("lte", "-2", "-2").0, MET);+ assert_eq!(n("gte", "1000", "1e3").0, MET);+ assert_eq!(n("ne", "7", "7 and 9").0, NOT_MET);+ assert_eq!(n("eq", "42", "42abc").0, MET);+ assert_eq!(n("eq", "1", "nothing"), (UNKNOWN, Some("no number".into())));+ assert_eq!(n("eq", "1", "").0, UNKNOWN);+ // The exit code doesn't matter to an output metric+ assert_eq!(j(&p("stdout_contains", None, "ready"), json!({}), &cmd(3, "ready")).0, MET);+ }++ #[test]+ fn errors_are_unknown_and_files_keep_their_meaning() {+ let ok = p("status", Some("eq"), "200");+ assert_eq!(judge(Some(&ok), &json!({}), "error", &Seen::default(), 0), (UNKNOWN, None));+ assert_eq!(judge(None, &json!({}), "passed", &Seen::default(), 0), (MET, None));+ assert_eq!(judge(None, &json!({}), "failed", &Seen::default(), 0), (NOT_MET, None));+ assert_eq!(judge(None, &json!({}), "error", &Seen::default(), 0), (UNKNOWN, None));+ }++ #[test]+ fn predicates_are_checked() {+ let n = |kind: &str, spec: Value, m: Option<&str>, o: Option<&str>, t: Option<&str>| normalize(kind, &spec, m, o, t);+ assert_eq!(n("http", json!({}), None, None, None), Ok(Some(p("status", Some("eq"), "200"))));+ assert_eq!(n("command", json!({}), None, None, None), Ok(Some(p("exit_code", Some("eq"), "0"))));+ assert_eq!(n("file_exists", json!({}), None, None, None), Ok(None));+ assert_eq!(n("http", json!({}), Some("latency_ms"), None, Some("500")), Ok(Some(p("latency_ms", Some("lt"), "500"))));+ assert_eq!(n("http", json!({}), Some("body_contains"), Some("contains"), Some("ok")), Ok(Some(p("body_contains", None, "ok"))));+ assert_eq!(n("command", json!({}), Some("stdout_number"), Some("gte"), Some("1e3")), Ok(Some(p("stdout_number", Some("gte"), "1000"))));+ assert_eq!(n("command", json!({}), Some("stdout_number"), Some("lt"), Some("2.5")), Ok(Some(p("stdout_number", Some("lt"), "2.5"))));+ assert!(n("http", json!({}), Some("latency_ms"), Some("eq"), Some("500")).is_err());+ assert!(n("http", json!({}), Some("latency_ms"), Some("lt"), Some("fast")).is_err());+ assert!(n("http", json!({}), Some("latency_ms"), Some("lt"), Some("-1")).is_err());+ assert!(n("command", json!({}), Some("stdout_number"), Some("lt"), Some("NaN")).is_err());+ assert!(n("command", json!({}), Some("stdout_number"), Some("lt"), Some("Infinity")).is_err());+ assert!(n("command", json!({}), Some("stdout_number"), Some("lt"), Some("1e308")).is_err());+ assert!(n("http", json!({}), Some("body_contains"), None, Some(&"x".repeat(10_000))).is_err());+ assert!(n("http", json!({ "pointer": "a/b" }), Some("json_value"), Some("eq"), Some("1")).is_err());+ assert!(n("http", json!({ "pointer": "/a~2" }), Some("json_value"), Some("eq"), Some("1")).is_err());+ assert!(n("http", json!({ "pointer": "/a~1b" }), Some("json_value"), Some("eq"), Some("1")).is_ok());+ assert!(n("http", json!({}), Some("json_value"), Some("gt"), Some("big")).is_err());+ assert!(n("http", json!({}), Some("speed"), None, Some("1")).is_err());+ assert!(n("http", json!({}), Some("stdout_number"), Some("lt"), Some("1")).is_err());+ assert!(n("http", json!({}), Some("status"), Some("eq"), None).is_err());+ assert!(n("http", json!({}), Some("status"), Some("eq"), Some("700")).is_err());+ assert!(n("command", json!({}), Some("exit_code"), Some("eq"), Some("256")).is_err());+ assert!(n("http", json!({}), None, Some("eq"), Some("200")).is_err());+ assert!(n("file_exists", json!({}), Some("exit_code"), None, None).is_err());+ assert!(n("command", json!({}), Some("stdout_contains"), None, Some("")).is_err());+ }++ #[test]+ fn plain_words_match_the_predicate() {+ let url = json!({ "url": "https://x.test/health" });+ assert_eq!(says("http", &url, Some(&p("latency_ms", Some("lt"), "500"))), "https://x.test/health responds in under 500 ms");+ assert_eq!(says("http", &url, Some(&p("latency_ms", Some("lte"), "500"))), "https://x.test/health responds in 500 ms or less");+ assert_eq!(says("http", &url, Some(&p("status", Some("eq"), "200"))), "https://x.test/health answers with status 200");+ assert_eq!(says("command", &json!({ "command": "make test" }), Some(&p("exit_code", Some("eq"), "0"))), "`make test` succeeds (exit code 0)");+ assert_eq!(says("command", &json!({ "command": "wc -l" }), Some(&p("stdout_number", Some("lte"), "10"))), "the first number `wc -l` prints is at most 10");+ assert_eq!(says("file_exists", &json!({ "path": "out.txt" }), None), "out.txt exists");+ }+}diff --git a/src/server/goals/routes.rs b/src/server/goals/routes.rsnew file mode 100644index 00000000..fdb1ce6b--- /dev/null+++ b/src/server/goals/routes.rs@@ -0,0 +1,271 @@+//! `/api/goals`. Reads are open like the rest of the app API; every change is person-only+//! (`auth.rs`), so a bot can propose a goal (`goal_propose`) but never approve, edit or run one.++use super::{build_goal, emit, emit_goal, event_json, goal_json, valid_budget, valid_mode, valid_title, validate_checks, CheckInput, GoalInput};+use super::{ranged, CONFIRM_RANGE, FIXES_RANGE, INTERVAL_RANGE, PRIORITY_RANGE};+use crate::db::goals::{Created, Edit, Goal};+use crate::db::missions::now_ms;+use crate::server::spaces::{space_param, Scope};+use crate::server::AppState;+use axum::{+ extract::{Path, RawQuery, State},+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use serde::Deserialize;+use serde_json::{json, Value};++/// Excerpt characters per check on list rows; a goal's own page shows the stored excerpt.+const LIST_EXCERPT: usize = 200;+const PAGE_EXCERPT: usize = 2000;+const PAGE_EVENTS: i64 = 50;++fn err(status: StatusCode, msg: impl Into<String>) -> Response {+ (status, Json(json!({ "error": msg.into() }))).into_response()+}++fn bad(msg: impl Into<String>) -> Response {+ err(StatusCode::BAD_REQUEST, msg)+}++fn conflict(msg: impl Into<String>) -> Response {+ err(StatusCode::CONFLICT, msg)+}++fn not_found() -> Response {+ err(StatusCode::NOT_FOUND, "no such goal")+}++fn internal(e: impl std::fmt::Display) -> Response {+ tracing::warn!(error = %e, "goals");+ err(StatusCode::INTERNAL_SERVER_ERROR, "something went wrong")+}++#[allow(clippy::result_large_err)]+async fn load(state: &AppState, query: Option<&str>, id: &str) -> Result<Goal, Response> {+ match state.db.get_goal(id).await {+ Ok(Some(g)) if space_param(query).is_none_or(|s| s.trim() == g.space_id) => Ok(g),+ Ok(_) => Err(not_found()),+ Err(e) => Err(internal(e)),+ }+}++pub async fn list_goals(State(state): State<AppState>, Scope(space): Scope) -> Response {+ let goals = match state.db.list_goals(space.as_str()).await {+ Ok(g) => g,+ Err(e) => return internal(e),+ };+ let mut out = Vec::new();+ for g in &goals {+ out.push(goal_json(&state, g, LIST_EXCERPT).await);+ }+ Json(json!({ "goals": out })).into_response()+}++async fn page(state: &AppState, g: &Goal) -> Value {+ let events = state.db.goal_events(&g.id, PAGE_EVENTS).await.unwrap_or_default();+ let fixes = state.db.goal_fix_links(&g.id).await.unwrap_or_default();+ let spent: i64 = fixes.iter().filter_map(|f| f.spent_tokens).sum();+ json!({+ "goal": goal_json(state, g, PAGE_EXCERPT).await,+ "events": events.iter().map(event_json).collect::<Vec<_>>(),+ "fix_tasks": fixes.iter().map(|f| json!({ "task_id": f.task_id, "state": f.state, "spent_tokens": f.spent_tokens, "created_at": f.created_at })).collect::<Vec<_>>(),+ "spent_tokens": spent,+ })+}++pub async fn get_goal(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {+ match load(&state, q.as_deref(), &id).await {+ Ok(g) => Json(page(&state, &g).await).into_response(),+ Err(r) => r,+ }+}++/// The person's goal: active at once, its first check due now.+pub async fn create_goal(State(state): State<AppState>, Scope(space): Scope, headers: HeaderMap, Json(p): Json<GoalInput>) -> Response {+ if p.from_task.is_some() {+ return err(StatusCode::UNPROCESSABLE_ENTITY, "making a goal from a task isn't available yet");+ }+ let route = format!("POST /api/goals?space={}", space.as_str());+ crate::server::missions::graph::idempotent(&state, &headers, route, || async {+ let new = build_goal(&state, &space, &p, "person", false).await.map_err(bad)?;+ match state.db.create_goal(&new, now_ms()).await {+ Ok(Created::Goal(g)) => {+ emit_goal(&state, &g);+ Ok(page(&state, &g).await)+ }+ Ok(Created::TooManyDrafts) => Err(internal("a person's goal counted as a draft")),+ Err(e) => Err(internal(e)),+ }+ })+ .await+}++#[derive(Debug, Deserialize)]+pub struct PatchGoal {+ pub title: Option<String>,+ pub description: Option<String>,+ pub mode: Option<String>,+ pub interval_minutes: Option<i64>,+ pub confirm_failures: Option<i64>,+ pub budget_tokens: Option<i64>,+ pub max_fixes_per_day: Option<i64>,+ pub priority: Option<i64>,+ pub checks: Option<Vec<CheckInput>>,+ /// Pause (true) or resume (false). Resuming checks at once.+ pub paused: Option<bool>,+}++pub async fn patch_goal(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>, Json(p): Json<PatchGoal>) -> Response {+ let g = match load(&state, q.as_deref(), &id).await {+ Ok(g) => g,+ Err(r) => return r,+ };+ let checked = (|| -> Result<_, String> {+ let title = p.title.as_deref().map(valid_title).transpose()?;+ if p.description.as_ref().is_some_and(|d| d.chars().count() > 2000) {+ return Err("description is at most 2000 characters".into());+ }+ let mode = p.mode.as_deref().map(|m| valid_mode(Some(m), "suggest")).transpose()?;+ let interval = p.interval_minutes.map(|n| ranged(Some(n), INTERVAL_RANGE, 0, "interval_minutes")).transpose()?;+ let confirm = p.confirm_failures.map(|n| ranged(Some(n), CONFIRM_RANGE, 0, "confirm_failures")).transpose()?;+ let fixes = p.max_fixes_per_day.map(|n| ranged(Some(n), FIXES_RANGE, 0, "max_fixes_per_day")).transpose()?;+ let priority = p.priority.map(|n| ranged(Some(n), PRIORITY_RANGE, 0, "priority")).transpose()?;+ let budget = p.budget_tokens.map(|b| valid_budget(Some(b))).transpose()?;+ let checks = match &p.checks {+ Some(c) => Some(validate_checks(c, interval.unwrap_or(g.interval_minutes), !g.kwant_id.is_empty() || !g.folder.is_empty())?),+ None => None,+ };+ Ok((title, mode, interval, confirm, fixes, priority, budget, checks))+ })();+ let (title, mode, interval, confirm, fixes, priority, budget, checks) = match checked {+ Ok(v) => v,+ Err(e) => return bad(e),+ };+ let now = now_ms();+ let description = p.description.clone();+ let paused = p.paused;+ let result = state+ .db+ .edit_goal(&g.id, &g.space_id, "person", now, move |g| {+ let mut events = Vec::new();+ let mut changed = Vec::new();+ let schedule_moved = interval.is_some_and(|i| i != g.interval_minutes) || checks.is_some();+ macro_rules! set {+ ($field:ident, $v:expr) => {+ if let Some(v) = $v {+ if g.$field != v {+ changed.push(stringify!($field));+ g.$field = v;+ }+ }+ };+ }+ set!(title, title);+ set!(description, description.map(|d| d.trim().to_string()));+ set!(mode, mode);+ set!(interval_minutes, interval);+ set!(confirm_failures, confirm);+ set!(max_fixes_per_day, fixes);+ set!(priority, priority);+ set!(budget_tokens, budget);+ if checks.is_some() {+ changed.push("checks");+ }+ match paused {+ Some(true) if g.status == "draft" => return Err("approve the draft before pausing it".into()),+ Some(false) if g.status == "draft" => return Err("approve the draft to start checking it".into()),+ Some(true) if g.status != "paused" => {+ g.status = "paused".into();+ g.status_reason = String::new();+ g.paused_at = Some(now);+ g.next_check_at = None;+ events.push(("paused", json!({})));+ }+ Some(false) if g.status == "paused" => {+ // Back to a fresh start: no streak from before the pause carries over+ g.status = "checking".into();+ g.status_reason = String::new();+ g.paused_at = None;+ g.next_check_at = Some(now);+ g.fail_streak = 0;+ g.error_runs = 0;+ events.push(("resumed", json!({})));+ }+ _ => {}+ }+ if schedule_moved && !matches!(g.status.as_str(), "draft" | "paused") {+ // New checks or a new interval: check now rather than on the old schedule+ g.next_check_at = Some(now);+ }+ if !changed.is_empty() {+ events.push(("edited", json!({ "fields": changed })));+ }+ Ok(Edit { checks, events })+ })+ .await;+ match result {+ Ok(Some(Ok(g))) => {+ emit_goal(&state, &g);+ Json(page(&state, &g).await).into_response()+ }+ Ok(Some(Err(why))) => conflict(why),+ Ok(None) => not_found(),+ Err(e) => internal(e),+ }+}++pub async fn approve_goal(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {+ let g = match load(&state, q.as_deref(), &id).await {+ Ok(g) => g,+ Err(r) => return r,+ };+ match state.db.approve_goal(&g.id, &g.space_id, "person", now_ms()).await {+ Ok(Some(g)) => {+ emit_goal(&state, &g);+ Json(page(&state, &g).await).into_response()+ }+ Ok(None) => conflict(format!("the goal is {}, not a draft", g.status)),+ Err(e) => internal(e),+ }+}++/// Check now: runs the goal's checks at once, in the background, unless it is a draft, paused or+/// already being checked. 202 with the goal; its result comes over SSE.+pub async fn check_goal(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {+ let g = match load(&state, q.as_deref(), &id).await {+ Ok(g) => g,+ Err(r) => return r,+ };+ if matches!(g.status.as_str(), "draft" | "paused") {+ return conflict(format!("the goal is {}", g.status));+ }+ match state.db.lease_goal(&g.id, now_ms(), false).await {+ Ok(Some(leased)) => {+ let body = page(&state, &leased).await;+ let st = state.clone();+ tokio::spawn(async move {+ super::runner::run_goal(&st, leased).await;+ });+ (StatusCode::ACCEPTED, Json(body)).into_response()+ }+ Ok(None) => conflict("the goal is being checked right now"),+ Err(e) => internal(e),+ }+}++pub async fn delete_goal(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {+ let g = match load(&state, q.as_deref(), &id).await {+ Ok(g) => g,+ Err(r) => return r,+ };+ match state.db.delete_goal(&g.id, &g.space_id).await {+ Ok(true) => {+ emit(&state, &g.id, "deleted", &g.space_id);+ Json(json!({ "deleted": g.id })).into_response()+ }+ Ok(false) => not_found(),+ Err(e) => internal(e),+ }+}diff --git a/src/server/goals/runner.rs b/src/server/goals/runner.rsnew file mode 100644index 00000000..c0df014d--- /dev/null+++ b/src/server/goals/runner.rs@@ -0,0 +1,154 @@+//! The goal loop. Every [`TICK`] it deletes week-old drafts, calls met goals whose evidence is out+//! of date unknown, sends the one "can't check" notice after a day of unknown, and runs the goals+//! that are due, each under its lease (`checking_since`) so two runs never overlap. With no+//! approved goals it does nothing but those queries: an upgrade starts no background work.++use super::{decide, emit, emit_goal, jitter_ms, next_interval_minutes, notice, on_change, predicate, predicate_of, Judged, RunSays};+use super::{DRAFT_TTL_MS, UNKNOWN_NOTICE_MS};+use crate::db::goals::{Goal, NewObservation, RunUpdate};+use crate::db::missions::now_ms;+use crate::server::AppState;+use serde_json::json;+use std::path::PathBuf;+use std::sync::{Arc, LazyLock};+use tokio::sync::Semaphore;+use tokio_util::sync::CancellationToken;++const TICK: std::time::Duration = std::time::Duration::from_secs(30);+/// Goals checked at once by the loop, server-wide.+const PARALLEL: usize = 4;++static RUNS: LazyLock<Arc<Semaphore>> = LazyLock::new(|| Arc::new(Semaphore::new(PARALLEL)));++pub fn spawn(state: AppState, shutdown: CancellationToken) {+ tokio::spawn(async move {+ loop {+ tokio::select! {+ _ = shutdown.cancelled() => return,+ _ = tokio::time::sleep(TICK) => {}+ }+ tick(&state).await;+ }+ });+}++/// One pass of the loop; the ids of the goals it started checking.+pub async fn tick(state: &AppState) -> Vec<String> {+ let now = now_ms();+ for (id, space) in state.db.expire_drafts(now - DRAFT_TTL_MS).await.unwrap_or_default() {+ emit(state, &id, "deleted", &space);+ }+ for id in state.db.stale_met_goals(now).await.unwrap_or_default() {+ if let Ok(Some(g)) = state.db.set_goal_status(&id, "unknown", "out_of_date", &["met"], Some(("unknown", json!({ "reason": "out_of_date" })))).await {+ emit_goal(state, &g);+ }+ }+ for g in state.db.goals_unknown_since(now - UNKNOWN_NOTICE_MS).await.unwrap_or_default() {+ let body = "kwant hasn't been able to check this for a day, so it can't say whether it's true. Open the Mission board to see what went wrong.".to_string();+ notice(state, &g, "cant_check", format!("Can't check {}", g.title), body).await;+ }+ let mut started = Vec::new();+ let free = RUNS.available_permits();+ if free == 0 {+ return started;+ }+ for id in state.db.due_goal_ids(now, free as i64).await.unwrap_or_default() {+ let Ok(permit) = RUNS.clone().try_acquire_owned() else { break };+ let Ok(Some(g)) = state.db.lease_goal(&id, now_ms(), true).await else { continue };+ started.push(g.id.clone());+ let state = state.clone();+ tokio::spawn(async move {+ run_goal(&state, g).await;+ drop(permit);+ });+ }+ started+}++/// Where a goal's command and file checks run: its folder, else its bot's.+pub fn goal_folder(state: &AppState, g: &Goal) -> Option<PathBuf> {+ if !g.folder.trim().is_empty() {+ return Some(PathBuf::from(g.folder.trim()));+ }+ if g.kwant_id.is_empty() {+ return None;+ }+ let space = crate::db::spaces::SpaceId::new(&g.space_id);+ Some(crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(&state.config.data_dir, &space), &g.kwant_id))+}++/// Runs every check of a goal it holds the lease for (`g` as [`lease_goal`] returned it) and+/// writes the outcome. Gives up quietly if it loses the lease (the goal was deleted, or the run+/// took so long another run took over); if the person edited the goal meanwhile, only the lease is+/// freed and their edit stands.+///+/// [`lease_goal`]: crate::db::Database::lease_goal+pub async fn run_goal(state: &AppState, g: Goal) -> Option<Goal> {+ let mut lease = g.checking_since?;+ emit_goal(state, &g);+ let checks = state.db.goal_checks(&g.id).await.unwrap_or_default();+ let folder = goal_folder(state, &g);+ let mut obs = Vec::new();+ let mut judged = Vec::new();+ let mut failing = Vec::new();+ for c in &checks {+ let spec = c.spec_value();+ let pred = predicate_of(c);+ let out = predicate::run(&c.kind, &spec, pred.as_ref(), folder.as_deref(), true).await;+ let now = now_ms();+ if !state.db.renew_goal_lease(&g.id, lease, now).await.unwrap_or(false) {+ return None;+ }+ lease = now;+ if out.verdict == predicate::NOT_MET && c.required() {+ let says = predicate::says(&c.kind, &spec, pred.as_ref());+ failing.push(match &out.observed {+ Some(o) => format!("{says} (it saw {o})"),+ None => says,+ });+ }+ judged.push(Judged { required: c.required(), verdict: out.verdict, errored: out.status == "error" });+ obs.push(NewObservation {+ check_id: c.id.clone(),+ status: out.status,+ verdict: out.verdict.to_string(),+ observed_value: out.observed,+ excerpt: out.excerpt,+ expires_at: now + c.freshness_minutes.max(1) * 60_000,+ });+ }+ let now = now_ms();+ if !state.db.record_observations(&g.id, lease, &obs, now).await.unwrap_or(false) {+ return None;+ }+ let (status, fail_streak, error_runs, says) = decide(&g.status, g.fail_streak, g.error_runs, g.confirm_failures, &judged);+ let status_reason = if status == g.status && status != "met" {+ g.status_reason.clone()+ } else {+ match says {+ RunSays::Met => String::new(),+ RunSays::Failed => "failing".into(),+ RunSays::Unknown => "cant_check".into(),+ }+ };+ let mut events = Vec::new();+ if status != g.status {+ match status.as_str() {+ "not_met" => events.push(("not_met", json!({ "failing": failing, "confirmed_after": fail_streak }))),+ "met" => events.push(("met", json!({}))),+ "unknown" => events.push(("unknown", json!({ "reason": status_reason }))),+ _ => {}+ }+ }+ // Read before this run logs `met`, which closes the stretch the person was told about+ let owed_recovery = status == "met" && g.status != "met" && state.db.told_broken(&g.id).await.unwrap_or(false);+ let next = now + next_interval_minutes(g.interval_minutes, error_runs) * 60_000 + jitter_ms(g.interval_minutes);+ let u = RunUpdate { status, status_reason, fail_streak, error_runs, next_check_at: next, events };+ let after = state.db.finish_goal_run(&g.id, lease, g.version, &u, now).await.ok().flatten()?;+ emit_goal(state, &after);+ if after.version == g.version {+ on_change(state, &g.status, &after, &failing, owed_recovery).await;+ }+ Some(after)+}+diff --git a/src/server/goals/tool.rs b/src/server/goals/tool.rsnew file mode 100644index 00000000..7b1ba12c--- /dev/null+++ b/src/server/goals/tool.rs@@ -0,0 +1,102 @@+//! `goal_propose`: a bot drafts a goal when the person asks for one. The draft does nothing until+//! the person approves it on the board; at most [`MAX_DRAFTS`] wait per space, and one nobody+//! approves is deleted silently after a week. A bot can't make a goal fix things on its own: a+//! proposed `fix` becomes `suggest`, and the person raises it.++use super::{build_goal, emit_goal, CheckInput, GoalInput};+use crate::db::goals::{Created, MAX_DRAFTS};+use crate::db::missions::now_ms;+use crate::server::continuity::SelfScope;+use crate::server::AppState;+use serde_json::{json, Value};++pub const TOOL: &str = "goal_propose";++pub fn tool() -> Value {+ json!({+ "name": TOOL,+ "description": "Propose a goal: something that should stay true (a site answers, a file exists, a number stays under a limit), checked on a schedule. It is a draft until the person approves it on the board; nothing is checked before that. Use it only when the person asks you to watch, keep an eye on or make sure of something, never on your own.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "title": {"type": "string", "description": "What should stay true, in the person's words."},+ "description": {"type": "string"},+ "interval_minutes": {"type": "integer", "minimum": super::INTERVAL_RANGE.0, "maximum": super::INTERVAL_RANGE.1},+ "mode": {"type": "string", "enum": ["watch", "suggest"], "description": "watch: only tell the person; suggest (default): also offer a fix for them to start."},+ "checks": {+ "type": "array",+ "minItems": 1,+ "maxItems": super::MAX_CHECKS,+ "items": {+ "type": "object",+ "properties": {+ "label": {"type": "string"},+ "kind": {"type": "string", "enum": ["command", "http", "file_exists", "file_contains", "file_sha256"]},+ "spec": {"type": "object", "description": "command: {command, timeout_secs?}; http: {url}; file_exists: {path}; file_contains: {path, text}; file_sha256: {path, sha256}. Paths are relative to your folder."},+ "metric": {"type": "string", "description": "http: status, latency_ms, body_contains, json_path; command: exit_code, stdout_contains, stdout_number. Leave out for the usual (status 200, exit code 0)."},+ "operator": {"type": "string", "enum": ["eq", "ne", "lt", "lte", "gt", "gte"]},+ "target": {"description": "What the metric is compared with: a number or text."},+ "severity": {"type": "string", "enum": ["required", "advisory"], "description": "Only required checks decide the goal."},+ },+ "required": ["kind", "spec"],+ },+ },+ },+ "required": ["title", "checks"],+ },+ })+}++pub async fn call(state: &AppState, scope: &SelfScope, args: &Value) -> (String, bool) {+ if !crate::server::missions::enabled(state).await {+ return ("The task board is off in Settings.".into(), true);+ }+ let space = match state.db.space_of_kwant(&scope.kwant_id).await {+ Ok(Some(s)) => s,+ _ => return ("Could not find your space.".into(), true),+ };+ let checks: Vec<CheckInput> = match serde_json::from_value(args["checks"].clone()) {+ Ok(c) => c,+ Err(e) => return (format!("checks: {e}"), true),+ };+ let mode = match args["mode"].as_str().map(str::trim) {+ Some("fix") | None => "suggest",+ Some(m) => m,+ };+ let input = GoalInput {+ title: args["title"].as_str().unwrap_or("").into(),+ description: args["description"].as_str().unwrap_or("").into(),+ kwant_id: Some(scope.kwant_id.clone()),+ mode: Some(mode.into()),+ interval_minutes: args["interval_minutes"].as_i64(),+ confirm_failures: None,+ budget_tokens: None,+ max_fixes_per_day: None,+ priority: None,+ checks,+ from_task: None,+ };+ let new = match build_goal(state, &space, &input, &scope.kwant_id, true).await {+ Ok(n) => n,+ Err(e) => return (e, true),+ };+ match state.db.create_goal(&new, now_ms()).await {+ Ok(Created::Goal(g)) => {+ emit_goal(state, &g);+ let out = json!({+ "goal_id": g.id,+ "status": "draft",+ "note": "Proposed. The person approves it on the Mission board; nothing is checked before that.",+ });+ (serde_json::to_string_pretty(&out).unwrap_or_default(), false)+ }+ Ok(Created::TooManyDrafts) => (+ format!("There are already {MAX_DRAFTS} goals waiting for the person's approval in this space. Ask them to approve or delete one first."),+ true,+ ),+ Err(e) => {+ tracing::warn!(error = %e, "goal_propose");+ ("Could not save the goal.".into(), true)+ }+ }+}diff --git a/src/server/missions/checks.rs b/src/server/missions/checks.rsindex be9d573e..6303638b 100644--- a/src/server/missions/checks.rs+++ b/src/server/missions/checks.rs@@ -69,10 +69,27 @@ fn excerpt(s: &str) -> String {format!("…\n{tail}")}+/// What a check run saw beyond passed or failed, for a goal's typed predicate (§22): a command's+/// exit code and stdout, an http GET's status and body text (up to 5 MB).+#[derive(Debug, Default, Clone)]+pub struct Seen {+ pub exit_code: Option<i64>,+ pub stdout: Option<String>,+ pub http_status: Option<u16>,+ pub body: Option<String>,+}+/// Runs one check; returns `(status, output)` with status "passed", "failed" or "error"./// `person_ok`: the person added or approved it, so an `http` check may reach this computer or a/// private network; otherwise the URL must resolve to public addresses only, and is fetched from them.pub async fn run_spec(kind: &str, spec: &Value, folder: Option<&Path>, person_ok: bool) -> (String, String) {+ let (status, output, _) = run_spec_seen(kind, spec, folder, person_ok).await;+ (status, output)+}++/// [`run_spec`], also returning what the run saw.+pub async fn run_spec_seen(kind: &str, spec: &Value, folder: Option<&Path>, person_ok: bool) -> (String, String, Seen) {+ let mut seen = Seen::default();let s = |k: &str| spec[k].as_str().map(str::trim).filter(|v| !v.is_empty());let need_folder = || folder.ok_or_else(|| "this task has no folder to check in".to_string());let r: Result<(bool, String), String> = match kind {@@ -83,6 +100,8 @@ pub async fn run_spec(kind: &str, spec: &Value, folder: Option<&Path>, person_okOk(v) => {let code = v["exit_code"].as_i64().unwrap_or(-1);let out = format!("exit code {code}\n{}{}", v["stdout"].as_str().unwrap_or(""), v["stderr"].as_str().unwrap_or(""));+ seen.exit_code = Some(code);+ seen.stdout = Some(v["stdout"].as_str().unwrap_or("").to_string());Ok((code == 0, out))}Err(e) => Err(e.to_string()),@@ -92,7 +111,7 @@ pub async fn run_spec(kind: &str, spec: &Value, folder: Option<&Path>, person_ok(_, Err(e)) => Err(e),},"http" => match s("url") {- Some(url) => http(url, spec, person_ok).await,+ Some(url) => http(url, spec, person_ok, &mut seen).await,None => Err("spec.url is missing".into()),},"file_exists" | "file_contains" | "file_sha256" => match (s("path"), need_folder()) {@@ -103,13 +122,13 @@ pub async fn run_spec(kind: &str, spec: &Value, folder: Option<&Path>, person_okother => Err(format!("kwant doesn't run {other} checks")),};match r {- Ok((true, out)) => ("passed".into(), excerpt(&out)),- Ok((false, out)) => ("failed".into(), excerpt(&out)),- Err(e) => ("error".into(), excerpt(&e)),+ Ok((true, out)) => ("passed".into(), excerpt(&out), seen),+ Ok((false, out)) => ("failed".into(), excerpt(&out), seen),+ Err(e) => ("error".into(), excerpt(&e), seen),}}-async fn http(url: &str, spec: &Value, person_ok: bool) -> Result<(bool, String), String> {+async fn http(url: &str, spec: &Value, person_ok: bool, seen: &mut Seen) -> Result<(bool, String), String> {let mut builder = reqwest::Client::builder();if !person_ok {let (host, addrs) = crate::mcp::fetch_risk::public_only(url).map_err(|why| format!("not fetched: {why}; the person can approve it"))?;@@ -143,6 +162,8 @@ async fn http(url: &str, spec: &Value, person_ok: bool) -> Result<(bool, String)if let Some(t) = contains {out.push_str(&format!("; {} \"{t}\"", if has { "contains" } else { "does not contain" }));}+ seen.http_status = Some(status);+ seen.body = Some(text.into_owned());Ok((ok_status && has, out))}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 4794bed5..d5ad9f45 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -48,6 +48,7 @@ pub mod waiting;pub mod decide;pub mod work_ahead;pub mod missions;+pub mod goals;pub mod app_update_routes;pub mod smart_results;@@ -368,6 +369,10 @@ pub fn create_router(state: AppState) -> Router {.route("/api/questions/:id/answer", post(questions::answer)).route("/api/messages/:message_id/decisions/:index/change", post(decide::change)).route("/api/work-ahead/run", post(work_ahead::run_now))+ .route("/api/goals", get(goals::routes::list_goals).post(goals::routes::create_goal))+ .route("/api/goals/:id", get(goals::routes::get_goal).patch(goals::routes::patch_goal).delete(goals::routes::delete_goal))+ .route("/api/goals/:id/approve", post(goals::routes::approve_goal))+ .route("/api/goals/:id/check", post(goals::routes::check_goal)).route("/api/missions", get(missions::routes::list_missions).post(missions::routes::create_mission)).route("/api/missions/insights", get(missions::routes::insights)).route("/api/performance", get(missions::performance::report))diff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex 6b1f3779..02c92cf8 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -840,6 +840,7 @@ pub fn spawn_background(state: AppState, shutdown: CancellationToken) {crate::documents::reminders::spawn(state.clone(), shutdown.clone());super::missions::listener::spawn(state.clone(), shutdown.clone());super::missions::foundry::spawn(state.clone(), shutdown.clone());+ super::goals::runner::spawn(state.clone(), shutdown.clone());super::missions::discovery::spawn(state.clone(), shutdown.clone());spawn(state, shutdown);}diff --git a/src/server/sse.rs b/src/server/sse.rsindex c0744036..97590314 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -113,6 +113,7 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {E::Error { kwant_id, .. } => contexts([kwant_id]),E::RoutineRun { routine_id, .. } => vec![Owner::Routine(routine_id.clone())],E::TaskUpdated { task: v } | E::MissionUpdated { mission: v } => fields(v, &["space_id"], Owner::Space),+ E::GoalUpdated { space_id, .. } => vec![Owner::Space(space_id.clone())],E::Notify { space_id, kwant_id, channel_id, .. } => {let mut out: Vec<Owner> = space_id.iter().cloned().map(Owner::Space).collect();out.extend(contexts([channel_id, &Some(kwant_id.clone())]));@@ -292,6 +293,7 @@ mod tests {E::RoutineRun { routine_id: s("r"), run_id: s("x"), status: s("ok") },E::TaskUpdated { task: json!({"id": "t", "space_id": "spc_x"}) },E::MissionUpdated { mission: json!({"id": "m", "space_id": "spc_x"}) },+ E::GoalUpdated { id: s("g"), status: s("met"), space_id: s("spc_x") },E::Notify {kind: s("x"),kwant_id: s("k"),@@ -347,6 +349,7 @@ mod tests {| E::RoutineRun { .. }| E::TaskUpdated { .. }| E::MissionUpdated { .. }+ | E::GoalUpdated { .. }| E::Notify { .. } => {}}}diff --git a/tests/app_update_test.rs b/tests/app_update_test.rsindex e2ec9295..131d6a39 100644--- a/tests/app_update_test.rs+++ b/tests/app_update_test.rs@@ -263,7 +263,7 @@ async fn app_update_and_work_ahead_are_on_for_lists_saved_before_they_existed()// What a person who saved their notification settings before #78 has storede.state.db.set_setting("notify_on", r#"["turn_finished","approval_needed"]"#).await.unwrap();let on = continuity::notify_on(&e.state).await;- assert_eq!(on, kinds(&["turn_finished", "approval_needed", "app_update", "work_ahead", "automation_suggested", "tier_proposed", "fact_disputed"]));+ assert_eq!(on, kinds(&["turn_finished", "approval_needed", "app_update", "work_ahead", "automation_suggested", "tier_proposed", "fact_disputed", "goal_alert"]));assert!(update_notification_delivered(&e, "0.1.2").await);let (_, s) = call(&e.app, "GET", "/api/settings", None).await;assert!(s["notify_on"].as_array().unwrap().contains(&json!("app_update")), "the switch shows on: {s}");diff --git a/tests/continuity_test.rs b/tests/continuity_test.rsindex da8c7095..957c6aed 100644--- a/tests/continuity_test.rs+++ b/tests/continuity_test.rs@@ -1599,7 +1599,7 @@ async fn webhook_setting_is_https_only_and_masked() {assert_eq!(s["notify_webhook_url"], "");assert_eq!(s["notify_on"],- json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update", "work_ahead", "automation_suggested", "tier_proposed", "fact_disputed"])+ json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update", "work_ahead", "automation_suggested", "tier_proposed", "fact_disputed", "goal_alert"]));let (status, _) = req(diff --git a/tests/goals_test.rs b/tests/goals_test.rsnew file mode 100644index 00000000..eeb93309--- /dev/null+++ b/tests/goals_test.rs@@ -0,0 +1,419 @@+//! Goals (plan §B.1, B.0): the loop with its lease, `/api/goals`, and `goal_propose`.+//! qa/test-plan.md 5.17 (G-T) and the loop's B.0 rules in 5.20 (G-Q).++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{+ goals::{Created, Edit, Goal, NewGoal, NewGoalCheck},+ missions::now_ms,+ models::Kwant,+ spaces::SpaceId,+ Database,+ },+ router::LayaRouter,+ server::{+ continuity::{SelfScope, TurnOrigin},+ create_router,+ goals::{self, runner},+ mcp_runtime, AppState,+ },+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};+use tempfile::{tempdir, TempDir};+use tower::ServiceExt;++struct Env {+ app: Router,+ state: AppState,+ bot: Kwant,+ general: String,+ space: String,+ _tmp: TempDir,+}++async fn setup() -> Env {+ let tmp = tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let space = SpaceId::default_space();+ let bot = state.db.list_kwants(&space).await.unwrap()[0].clone();+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap().id;+ Env { app: create_router(state.clone()), state, bot, general, space: space.as_str().to_string(), _tmp: tmp }+}++async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ if let Some(token) = auth {+ req = req.header("authorization", format!("Bearer {token}"));+ }+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let status = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++/// A one-route server answering with the statuses in `codes`, in turn (the last repeats).+async fn server(codes: Vec<u16>) -> String {+ use axum::routing::get;+ let n = Arc::new(AtomicUsize::new(0));+ let app = Router::new().route(+ "/",+ get(move || {+ let n = n.clone();+ let codes = codes.clone();+ async move { StatusCode::from_u16(codes[n.fetch_add(1, Ordering::SeqCst).min(codes.len() - 1)]).unwrap() }+ }),+ );+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = l.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(l, app).await.unwrap() });+ format!("http://{addr}/")+}++fn closed_port() -> String {+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ format!("http://127.0.0.1:{}/", l.local_addr().unwrap().port())+}++fn new_goal(e: &Env, url: &str, confirm: i64) -> NewGoal {+ NewGoal {+ space_id: e.space.clone(),+ title: "Site is up".into(),+ description: String::new(),+ kwant_id: e.bot.id.clone(),+ folder: String::new(),+ mode: "suggest".into(),+ interval_minutes: 60,+ confirm_failures: confirm,+ budget_tokens: 0,+ max_fixes_per_day: 3,+ priority: 2,+ created_by: "person".into(),+ draft: false,+ checks: vec![NewGoalCheck {+ label: "up".into(),+ kind: "http".into(),+ spec: json!({ "url": url }),+ metric: Some("status".into()),+ operator: Some("eq".into()),+ target: Some("200".into()),+ severity: "required".into(),+ freshness_minutes: 120,+ }],+ }+}++async fn create(e: &Env, g: &NewGoal) -> Goal {+ match e.state.db.create_goal(g, now_ms()).await.unwrap() {+ Created::Goal(g) => *g,+ Created::TooManyDrafts => panic!("too many drafts"),+ }+}++async fn run_now(e: &Env, id: &str) -> Goal {+ let g = e.state.db.lease_goal(id, now_ms(), false).await.unwrap().expect("leased");+ runner::run_goal(&e.state, g).await.expect("ran")+}++async fn kinds(e: &Env, id: &str) -> Vec<String> {+ e.state.db.goal_events(id, 100).await.unwrap().into_iter().map(|e| e.kind).collect()+}++async fn notices(e: &Env, id: &str) -> Vec<String> {+ let mut out: Vec<String> = e+ .state+ .db+ .goal_events(id, 100)+ .await+ .unwrap()+ .into_iter()+ .filter(|ev| ev.kind == "notified")+ .map(|ev| ev.detail_value()["kind"].as_str().unwrap_or("").to_string())+ .collect();+ out.reverse();+ out+}++// G-T-04, G-Q-01: one failure is never news; the confirm count is; one notice per incident+#[tokio::test]+async fn a_goal_breaks_only_after_its_confirm_count_and_tells_once() {+ let e = setup().await;+ let url = server(vec![200, 500, 500, 500, 200]).await;+ let g = create(&e, &new_goal(&e, &url, 2)).await;+ let mut seq = Vec::new();+ for _ in 0..5 {+ seq.push(run_now(&e, &g.id).await.status);+ }+ assert_eq!(seq, ["met", "met", "not_met", "not_met", "met"]);+ assert_eq!(kinds(&e, &g.id).await.iter().filter(|k| *k == "not_met").count(), 1);+ assert_eq!(notices(&e, &g.id).await, ["broken", "recovered"]);+ let after = e.state.db.get_goal(&g.id).await.unwrap().unwrap();+ assert!(after.checking_since.is_none());+ assert!(after.next_check_at.unwrap() >= now_ms() + 59 * 60_000);+ // The observation keeps what was seen and when it goes out of date+ let obs = e.state.db.recent_observations(&g.id, 1).await.unwrap();+ assert_eq!((obs[0].verdict.as_str(), obs[0].observed_value.as_deref()), ("met", Some("200")));+ assert!(obs[0].expires_at > now_ms() + 119 * 60_000);+}++// G-T-05, G-Q-02: an error is unknown, breaks a run of failures, and never notifies+#[tokio::test]+async fn an_error_between_failures_is_unknown_and_never_confirms() {+ let e = setup().await;+ let flaky = server(vec![200, 500]).await;+ let g = create(&e, &new_goal(&e, &flaky, 2)).await;+ assert_eq!(run_now(&e, &g.id).await.status, "met");+ assert_eq!(run_now(&e, &g.id).await.fail_streak, 1);+ // The same goal now points at a closed port for one run+ let down = closed_port();+ let swap = |url: String| {+ move |g: &mut Goal| {+ let _ = g;+ Ok(Edit {+ checks: Some(vec![NewGoalCheck {+ label: "up".into(),+ kind: "http".into(),+ spec: json!({ "url": url }),+ metric: Some("status".into()),+ operator: Some("eq".into()),+ target: Some("200".into()),+ severity: "required".into(),+ freshness_minutes: 120,+ }]),+ events: vec![],+ })+ }+ };+ let edited = e.state.db.edit_goal(&g.id, &e.space, "person", now_ms(), swap(down)).await.unwrap().unwrap().unwrap();+ // The edit doesn't touch the streak: only runs do+ assert_eq!(edited.fail_streak, 1);+ let after = run_now(&e, &g.id).await;+ assert_eq!((after.status.as_str(), after.fail_streak, after.error_runs), ("unknown", 0, 1));+ assert!(after.unknown_since.is_some());+ e.state.db.edit_goal(&g.id, &e.space, "person", now_ms(), swap(flaky)).await.unwrap().unwrap().unwrap();+ let after = run_now(&e, &g.id).await;+ assert_eq!((after.status.as_str(), after.fail_streak), ("unknown", 1), "fail, error, fail is not two failures in a row");+ assert!(notices(&e, &g.id).await.is_empty());+}++// G-T-09: one run at a time; an edit during a run wins; a deleted goal's run writes nothing+#[tokio::test]+async fn the_lease_keeps_runs_apart_and_edits_win() {+ let e = setup().await;+ let url = server(vec![200]).await;+ let g = create(&e, &new_goal(&e, &url, 2)).await;+ let leased = e.state.db.lease_goal(&g.id, now_ms(), false).await.unwrap().unwrap();+ assert!(e.state.db.lease_goal(&g.id, now_ms(), false).await.unwrap().is_none());+ let (status, _) = call(&e.app, "POST", &format!("/api/goals/{}/check", g.id), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT);+ e.state+ .db+ .edit_goal(&g.id, &e.space, "person", now_ms(), |g| {+ g.title = "Renamed".into();+ Ok(Edit { checks: None, events: vec![] })+ })+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ let after = runner::run_goal(&e.state, leased).await.unwrap();+ assert_eq!((after.title.as_str(), after.status.as_str()), ("Renamed", "checking"));+ assert!(after.checking_since.is_none());+ let leased = e.state.db.lease_goal(&g.id, now_ms(), false).await.unwrap().unwrap();+ e.state.db.delete_goal(&g.id, &e.space).await.unwrap();+ assert!(runner::run_goal(&e.state, leased).await.is_none());+}++// G-T-06, G-Q-13: out of date is unknown, never met; drafts expire silently after a week+#[tokio::test]+async fn the_tick_expires_drafts_and_out_of_date_evidence_quietly() {+ let e = setup().await;+ let mut d = new_goal(&e, "https://example.com/", 2);+ d.draft = true;+ let draft = match e.state.db.create_goal(&d, now_ms() - goals::DRAFT_TTL_MS - 1000).await.unwrap() {+ Created::Goal(g) => *g,+ _ => panic!(),+ };+ let url = server(vec![200]).await;+ let mut quick = new_goal(&e, &url, 2);+ quick.checks[0].freshness_minutes = 1;+ let g = create(&e, &quick).await;+ assert_eq!(run_now(&e, &g.id).await.status, "met");+ // Not due, so nothing runs; the draft goes+ assert!(runner::tick(&e.state).await.is_empty());+ assert!(e.state.db.get_goal(&draft.id).await.unwrap().is_none());+ assert_eq!(e.state.db.get_goal(&g.id).await.unwrap().unwrap().status, "met");+ // A minute on, its evidence is out of date+ assert!(e.state.db.stale_met_goals(now_ms() + 61_000).await.unwrap().contains(&g.id));+ let (_, page) = call(&e.app, "GET", &format!("/api/goals/{}", g.id), None, None).await;+ assert_eq!(page["goal"]["status"], "met");+ e.state.db.set_goal_status(&g.id, "unknown", "out_of_date", &["met"], None).await.unwrap().unwrap();+ assert!(notices(&e, &g.id).await.is_empty());+}++// G-Q-06: unknown never notifies before a day, then exactly once+#[tokio::test]+async fn unknown_tells_once_after_a_day() {+ let e = setup().await;+ let g = create(&e, &new_goal(&e, &closed_port(), 2)).await;+ assert_eq!(run_now(&e, &g.id).await.status, "unknown");+ runner::tick(&e.state).await;+ assert!(notices(&e, &g.id).await.is_empty());+ // A day later (moved back by hand)+ let day_ago = now_ms() - goals::UNKNOWN_NOTICE_MS - 1000;+ assert!(!e.state.db.goals_unknown_since(day_ago).await.unwrap().iter().any(|x| x.id == g.id));+ let later = e.state.db.goals_unknown_since(now_ms() + goals::UNKNOWN_NOTICE_MS).await.unwrap();+ let stuck = later.into_iter().find(|x| x.id == g.id).unwrap();+ assert!(goals::notice(&e.state, &stuck, "cant_check", "t".into(), "b".into()).await);+ assert!(e.state.db.goals_unknown_since(now_ms() + goals::UNKNOWN_NOTICE_MS).await.unwrap().is_empty());+ assert_eq!(notices(&e, &g.id).await, ["cant_check"]);+}++// G-Q-24: no more than three notices per goal per day; held back ones are logged+#[tokio::test]+async fn notices_are_capped_at_three_a_day() {+ let e = setup().await;+ let g = create(&e, &new_goal(&e, "https://example.com/", 1)).await;+ for _ in 0..3 {+ assert!(goals::notice(&e.state, &g, "broken", "t".into(), "b".into()).await);+ }+ assert!(!goals::notice(&e.state, &g, "recovered", "t".into(), "b".into()).await);+ assert!(kinds(&e, &g.id).await.contains(&"notice_capped".to_string()));+}++// G-T-01..03, G-T-07, G-T-08, G-T-10: the API+#[tokio::test]+async fn the_api_creates_edits_pauses_and_deletes_goals() {+ let e = setup().await;+ let url = server(vec![200]).await;+ let body = json!({+ "title": "Site is up",+ "checks": [+ {"kind": "http", "spec": {"url": url}},+ {"kind": "http", "spec": {"url": url}, "metric": "latency_ms", "operator": "lt", "target": 5000, "severity": "advisory"},+ ],+ });+ let (status, v) = call(&e.app, "POST", "/api/goals", None, Some(body)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ let id = v["goal"]["id"].as_str().unwrap().to_string();+ assert_eq!((v["goal"]["status"].as_str(), v["goal"]["mode"].as_str(), v["goal"]["confirm_failures"].as_i64()), (Some("checking"), Some("suggest"), Some(2)));+ assert_eq!(v["goal"]["checks"][0]["says"], format!("{url} answers with status 200"));+ assert_eq!(v["goal"]["checks"][1]["required"], false);+ // Refusals+ for (bad, code) in [+ (json!({"title": "", "checks": [{"kind": "http", "spec": {"url": url}}]}), StatusCode::BAD_REQUEST),+ (json!({"title": "x", "checks": [{"kind": "http", "spec": {"url": url}, "severity": "advisory"}]}), StatusCode::BAD_REQUEST),+ (json!({"title": "x", "interval_minutes": 5, "checks": [{"kind": "http", "spec": {"url": url}}]}), StatusCode::BAD_REQUEST),+ (json!({"from_task": "t1"}), StatusCode::UNPROCESSABLE_ENTITY),+ ] {+ let (status, v) = call(&e.app, "POST", "/api/goals", None, Some(bad.clone())).await;+ assert_eq!(status, code, "{bad}: {v}");+ }+ // Check now runs in the background and comes back met+ let (status, _) = call(&e.app, "POST", &format!("/api/goals/{id}/check"), None, None).await;+ assert_eq!(status, StatusCode::ACCEPTED);+ let mut met = false;+ for _ in 0..50 {+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ if e.state.db.get_goal(&id).await.unwrap().unwrap().status == "met" {+ met = true;+ break;+ }+ }+ assert!(met);+ let (_, list) = call(&e.app, "GET", "/api/goals", None, None).await;+ assert_eq!(list["goals"][0]["checks"][0]["latest"]["verdict"], "met");+ // Pause, then Check now is refused; resume starts fresh+ let (status, v) = call(&e.app, "PATCH", &format!("/api/goals/{id}"), None, Some(json!({"paused": true, "title": "Site answers"}))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ assert_eq!((v["goal"]["status"].as_str(), v["goal"]["title"].as_str()), (Some("paused"), Some("Site answers")));+ assert!(v["goal"]["next_check_at"].is_null());+ let (status, _) = call(&e.app, "POST", &format!("/api/goals/{id}/check"), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT);+ let (_, v) = call(&e.app, "PATCH", &format!("/api/goals/{id}"), None, Some(json!({"paused": false}))).await;+ assert_eq!(v["goal"]["status"], "checking");+ let ev: Vec<&str> = v["events"].as_array().unwrap().iter().filter_map(|x| x["kind"].as_str()).collect();+ for k in ["resumed", "paused", "edited"] {+ assert!(ev.contains(&k), "{ev:?}");+ }+ // Approve is only for drafts; another space can't see it+ let (status, _) = call(&e.app, "POST", &format!("/api/goals/{id}/approve"), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT);+ let (status, _) = call(&e.app, "GET", &format!("/api/goals/{id}?space=elsewhere"), None, None).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+ let (status, _) = call(&e.app, "DELETE", &format!("/api/goals/{id}"), None, None).await;+ assert_eq!(status, StatusCode::OK);+ let (status, _) = call(&e.app, "GET", &format!("/api/goals/{id}"), None, None).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++async fn turn(e: &Env, turn_id: &str) -> String {+ let origin = TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() };+ let scope = SelfScope { kwant_id: e.bot.id.clone(), kwant_name: e.bot.name.clone(), origin: Some(origin), turn_id: Some(turn_id.into()), ..Default::default() };+ mcp_runtime::prepare_turn_with_self(&e.state, &e.bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1+}++async fn propose(e: &Env, token: &str, args: Value) -> (bool, String) {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "goal_propose", "arguments": args}});+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ (v["result"]["isError"].as_bool().unwrap_or(false), v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string())+}++// G-T-11, G-T-12, G-Q-11, G-Q-14: a bot proposes, the person approves; three drafts at most+#[tokio::test]+async fn a_bot_proposes_drafts_and_only_the_person_approves() {+ let e = setup().await;+ let token = turn(&e, "t-goal").await;+ let args = json!({"title": "Report exists", "mode": "fix", "checks": [{"kind": "file_exists", "spec": {"path": "report.md"}}]});+ let (err, text) = propose(&e, &token, args.clone()).await;+ assert!(!err, "{text}");+ let id = serde_json::from_str::<Value>(&text).unwrap()["goal_id"].as_str().unwrap().to_string();+ let g = e.state.db.get_goal(&id).await.unwrap().unwrap();+ assert_eq!((g.status.as_str(), g.mode.as_str(), g.created_by.as_str()), ("draft", "suggest", e.bot.id.as_str()));+ // A draft runs nothing, even at the tick+ assert!(g.next_check_at.is_none());+ assert!(runner::tick(&e.state).await.is_empty());+ for _ in 0..2 {+ assert!(!propose(&e, &token, args.clone()).await.0);+ }+ let (err, text) = propose(&e, &token, args.clone()).await;+ assert!(err && text.contains("already 3 goals"), "{text}");+ // A bot can't approve, edit or run it+ for (method, uri) in [("POST", format!("/api/goals/{id}/approve")), ("PATCH", format!("/api/goals/{id}")), ("POST", format!("/api/goals/{id}/check"))] {+ let (status, _) = call(&e.app, method, &uri, Some(&token), Some(json!({"title": "x"}))).await;+ assert!(status == StatusCode::FORBIDDEN || status == StatusCode::UNAUTHORIZED, "{method} {uri}: {status}");+ }+ let (status, v) = call(&e.app, "POST", &format!("/api/goals/{id}/approve"), None, None).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ assert_eq!(v["goal"]["status"], "checking");+ assert!(v["goal"]["next_check_at"].as_i64().is_some());+}++// G-Q-14: an upgrade (a fresh install) has no goals and starts nothing+#[tokio::test]+async fn a_fresh_install_runs_nothing() {+ let e = setup().await;+ assert!(runner::tick(&e.state).await.is_empty());+ let (status, v) = call(&e.app, "GET", "/api/goals", None, None).await;+ assert_eq!((status, v["goals"].as_array().map(Vec::len)), (StatusCode::OK, Some(0)));+}