Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Goals: fix the 0.6.5 QA minors (api-M2..M7, remediation-1) (#250)

Oleksandr Ivanchenko69082d91f3ea
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb13fcb4..96d110c8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
+### Fixed
+- **Goals: clearer checks and fewer false alarms.** A page over 5 MB is "can't check", not "not met". A redirect is
+ still not followed, and the reason names where it points. A changed file shows both the expected and the actual
+ hash. One dropped connection no longer flips a met goal that passed last time; two in a row do, and an error right after a failure shows "can't check" at once. A notice you turned off isn't counted
+ against the daily cap. Deleting a goal closes its open "Restore" mission and cancels its tasks, keeping the history.
+ The goal tool's schema now matches what it accepts (`json_value` needs a `pointer`; `contains` is listed).
+
## [Mac 0.6.6] - 2026-11-03
### Changed
diff --git a/src/server/goals/mod.rs b/src/server/goals/mod.rs
index af2b2fc5..de170ac4 100644
--- a/src/server/goals/mod.rs
+++ b/src/server/goals/mod.rs
@@ -12,7 +12,7 @@ use crate::db::goals::{Goal, GoalCheck, GoalEvent, NewGoal, NewGoalCheck, Observ
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::continuity::{notify, notify_on, Notification};
use crate::server::AppState;
use predicate::Predicate;
use serde::Deserialize;
@@ -37,6 +37,8 @@ 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;
+/// Runs in a row where every check errored before a met goal is called unknown: one blip is not news.
+pub const ERRORS_TO_UNKNOWN: i64 = 2;
/// 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.
@@ -254,6 +256,9 @@ pub struct Judged {
/// 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.
+/// - A met goal whose checks all errored once (a dropped connection, a timeout) stays met if the run
+/// before passed; only [`ERRORS_TO_UNKNOWN`] such runs in a row make it unknown. An error right
+/// after a failure shows unknown at once.
/// - 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();
@@ -274,12 +279,20 @@ pub fn decide(prior: &str, fail_streak: i64, error_runs: i64, confirm: i64, resu
}
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)
+ let errors = if all_errored { error_runs + 1 } else { 0 };
+ let status = if open || holds_blip(prior, fail_streak, all_errored, errors) { prior } else { "unknown" };
+ (status.into(), 0, errors, says)
}
}
}
+/// Whether a run where every check errored leaves a met goal met: only when the run before passed
+/// (no failure streak) and it is not yet [`ERRORS_TO_UNKNOWN`] errors in a row. After a failure an
+/// error shows unknown, so fail, error, fail, error... can't keep a goal met for ever.
+pub fn holds_blip(prior: &str, fail_streak: i64, all_errored: bool, errors: i64) -> bool {
+ prior == "met" && fail_streak == 0 && all_errored && errors < ERRORS_TO_UNKNOWN
+}
+
/// 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 {
@@ -411,8 +424,13 @@ pub fn emit_goal(state: &AppState, g: &Goal) {
/// 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.
+/// cap hides pings, not state. Returns whether it went out; a notice the person turned off in
+/// Settings is neither sent nor recorded, so it never counts toward the cap.
pub async fn notice(state: &AppState, g: &Goal, kind: &str, title: String, body: String) -> bool {
+ // With goal alerts off in Settings nothing is sent, so nothing is recorded or counted
+ if !notify_on(state).await.iter().any(|k| k == "goal_alert") {
+ return false;
+ }
let now = now_ms();
let sent = state.db.goal_notices_since(&g.id, now - DAY_MS).await.unwrap_or(0);
if sent >= NOTICE_CAP {
@@ -498,15 +516,42 @@ mod tests {
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
+ // G-T-05, G-V-05, G-Q-02: fail, error, fail doesn't confirm (the error after a failure shows unknown)
assert_eq!(walk(2, &[ok, bad, err, bad]), ["met", "met", "unknown", "unknown"]);
- assert_eq!(walk(2, &[ok, err, err]), ["met", "unknown", "unknown"]);
+ assert_eq!(walk(2, &[ok, bad, err, err, bad]), ["met", "met", "unknown", "unknown", "unknown"]);
+ // api-M7: one error on a met goal changes nothing; two in a row are unknown; a pass between resets
+ assert_eq!(walk(2, &[ok, err]), ["met", "met"]);
+ assert_eq!(walk(2, &[ok, err, err]), ["met", "met", "unknown"]);
+ assert_eq!(walk(2, &[ok, err, ok, err]), ["met", "met", "met", "met"]);
+ // A goal that never met has nothing to keep
+ assert_eq!(walk(2, &[err]), ["unknown"]);
+ // Output the predicate couldn't read isn't a dropped connection: unknown at once
+ let unreadable = [Judged { required: true, verdict: UNK, errored: false }];
+ assert_eq!(decide("met", 0, 0, 2, &unreadable).0, "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 alternating_fail_and_error_never_leaves_a_goal_met() {
+ let ok: &[Judged] = &[j(true, MET)];
+ let bad: &[Judged] = &[j(true, NOT)];
+ let err: &[Judged] = &[j(true, UNK)];
+ // A blip is held only when the run before passed. After a failure the error shows unknown,
+ // and the fail/error pattern can't keep the goal met for ever.
+ for confirm in [2, 3] {
+ let seq: Vec<&[Judged]> = std::iter::once(ok).chain((0..4).flat_map(|_| [bad, err])).collect();
+ let seen = walk(confirm, &seq);
+ assert_eq!(seen[0], "met");
+ assert_eq!(seen[1], "met", "one failure is not news");
+ assert!(seen[2..].iter().all(|s| s == "unknown"), "confirm {confirm}: fail, error, fail, error... gave {seen:?}");
+ }
+ // A pass between the failures does hold a blip: fail, pass, error, fail is still met
+ assert_eq!(walk(2, &[ok, bad, ok, err, bad]), ["met", "met", "met", "met", "met"]);
+ }
+
#[test]
fn advisory_checks_never_decide() {
// G-T-07, G-V-07, G-V-08
diff --git a/src/server/goals/predicate.rs b/src/server/goals/predicate.rs
index 871fad4e..1eee146f 100644
--- a/src/server/goals/predicate.rs
+++ b/src/server/goals/predicate.rs
@@ -29,6 +29,10 @@ pub fn metrics(kind: &str) -> &'static [&'static str] {
}
}
+/// Every operator some metric takes, for the `goal_propose` schema. `contains` is a json_value
+/// operator; the contains metrics (body_contains, stdout_contains) accept it too and ignore it.
+pub const ALL_OPERATORS: [&str; 7] = ["eq", "ne", "lt", "lte", "gt", "gte", "contains"];
+
/// 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] {
@@ -302,9 +306,42 @@ fn json_value(body: Option<&str>, pointer: &str, op: &str, target: &str) -> (&'s
(verdict(holds), Some(render(v)))
}
+/// Why a body check on a page past the read cap says nothing: the needle may be in the part that
+/// wasn't read.
+pub const TOO_BIG: &str = "The page is larger than 5 MB, so I can't check it";
+
+/// The plain reason a 3xx answer is not met: kwant doesn't follow redirects (a redirect could lead
+/// to an address the check wasn't approved for), so the person points the check at the final one.
+fn redirect_reason(host: Option<&str>) -> String {
+ match host {
+ Some(h) => format!("it redirects to {h}, and kwant doesn't follow redirects: use the final address"),
+ None => "it redirects to another address on the same site, and kwant doesn't follow redirects: use the final address".into(),
+ }
+}
+
/// 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>) {
+ let (verdict, observed) = judge_value(pred, spec, status, seen, latency_ms);
+ let metric = pred.map(|p| p.metric.as_str());
+ // A body past the read cap: a needle that wasn't found may be in the part that wasn't read
+ if seen.body_truncated && verdict != MET && matches!(metric, Some("body_contains" | "json_value")) {
+ return (UNKNOWN, Some(TOO_BIG.into()));
+ }
+ // A 3xx answer that wasn't met: say where it points
+ if verdict == NOT_MET {
+ if let Some(to) = &seen.redirect {
+ let why = redirect_reason(to.as_deref());
+ return (verdict, Some(match observed {
+ Some(o) => format!("{o}: {why}"),
+ None => why,
+ }));
+ }
+ }
+ (verdict, observed)
+}
+
+fn judge_value(pred: Option<&Predicate>, spec: &Value, status: &str, seen: &Seen, latency_ms: i64) -> (&'static str, Option<String>) {
if status == "error" {
return (UNKNOWN, None);
}
@@ -369,7 +406,21 @@ pub async fn run(kind: &str, spec: &Value, pred: Option<&Predicate>, folder: Opt
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) }
+ let excerpt = sha256_excerpt(spec, &seen).unwrap_or_else(|| redact(&output));
+ Outcome { status, verdict, observed: observed.map(|o| cap(&redact(&o), MAX_OBSERVED_CHARS)), excerpt }
+}
+
+/// What a `file_sha256` check shows: both hashes, which `redact` would hide as random-looking
+/// words. They are hashes, not file contents, so the person can compare them. None unless both
+/// read as hex.
+fn sha256_excerpt(spec: &Value, seen: &Seen) -> Option<String> {
+ let (got, want) = seen.sha256.as_ref()?;
+ let hex = |h: &str| !h.is_empty() && h.len() <= 64 && h.chars().all(|c| c.is_ascii_hexdigit());
+ if !hex(got) || !hex(want) {
+ return None;
+ }
+ let head = redact(&format!("sha256 of {}", spec["path"].as_str().unwrap_or("the file").trim()));
+ Some(if got == want { format!("{head} is {got}, as expected") } else { format!("{head} changed\nexpected {want}\nactual {got}") })
}
/// Plain words for a predicate, as the person reads it before approving ("responds in under
@@ -611,4 +662,68 @@ mod tests {
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");
}
+
+ // Post-0.6.5 api-M3: a page past the read cap can't say a needle is missing
+ #[test]
+ fn a_body_past_the_read_cap_is_cant_check_not_not_met() {
+ let cut = Seen { body_truncated: true, ..http(200, "start of a very long page") };
+ let has = p("body_contains", None, "needle");
+ assert_eq!(j(&has, json!({}), &cut), (UNKNOWN, Some(TOO_BIG.into())));
+ assert_eq!(TOO_BIG, "The page is larger than 5 MB, so I can't check it");
+ // Found in the part that was read: that is still true
+ assert_eq!(j(&p("body_contains", None, "start"), json!({}), &cut).0, MET);
+ // A partial document isn't JSON; the reason is the size, not "not JSON"
+ let at = json!({ "pointer": "/ok" });
+ assert_eq!(j(&p("json_value", Some("eq"), "true"), at, &cut), (UNKNOWN, Some(TOO_BIG.into())));
+ // Status and latency don't read the body
+ assert_eq!(j(&p("status", Some("eq"), "200"), json!({}), &cut).0, MET);
+ // Not past the cap: a missing needle is not met, as before
+ assert_eq!(j(&has, json!({}), &http(200, "short")).0, NOT_MET);
+ }
+
+ // api-M4: a redirect is not followed; the reason names where it points
+ #[test]
+ fn a_redirect_says_where_it_points() {
+ let moved = Seen { redirect: Some(Some("www.example.com".into())), ..http(301, "") };
+ let (v, seen) = j(&p("status", Some("eq"), "200"), json!({}), &moved);
+ assert_eq!(v, NOT_MET);
+ let seen = seen.unwrap();
+ assert!(seen.starts_with("301: it redirects to www.example.com"), "{seen}");
+ assert!(seen.contains("use the final address"), "{seen}");
+ let same = Seen { redirect: Some(None), ..http(302, "") };
+ let seen = j(&p("status", Some("eq"), "200"), json!({}), &same).1.unwrap();
+ assert!(seen.contains("another address on the same site"), "{seen}");
+ // A body check on the redirect page is not met with the same reason
+ assert!(j(&p("body_contains", None, "ok"), json!({}), &moved).1.unwrap().contains("www.example.com"));
+ // Met stays plain, and no redirect leaves the value alone
+ assert_eq!(j(&p("status", Some("ne"), "200"), json!({}), &moved), (MET, Some("301".into())));
+ assert_eq!(j(&p("status", Some("eq"), "200"), json!({}), &http(500, "")), (NOT_MET, Some("500".into())));
+ }
+
+ // api-M5: both hashes show, though the excerpt is redacted
+ #[tokio::test]
+ async fn a_sha256_mismatch_shows_both_hashes() {
+ let dir = std::env::temp_dir().join(format!("kwnt-sha-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("release.bin"), "hello").unwrap();
+ let actual = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
+ let expected = "a".repeat(64);
+ let spec = json!({ "path": "release.bin", "sha256": expected });
+ let out = run("file_sha256", &spec, None, Some(dir.as_path()), true).await;
+ assert_eq!(out.verdict, NOT_MET);
+ assert!(out.excerpt.contains(&format!("expected {expected}")), "{}", out.excerpt);
+ assert!(out.excerpt.contains(&format!("actual {actual}")), "{}", out.excerpt);
+ assert!(!out.excerpt.contains("••"), "{}", out.excerpt);
+ // A match says so
+ let ok = run("file_sha256", &json!({ "path": "release.bin", "sha256": actual.to_uppercase() }), None, Some(dir.as_path()), true).await;
+ assert_eq!(ok.verdict, MET);
+ assert!(ok.excerpt.contains(actual), "{}", ok.excerpt);
+ // Not a hash: nothing is shown unredacted
+ let odd = run("file_sha256", &json!({ "path": "release.bin", "sha256": "sk-live-not-a-hash-but-a-secret" }), None, Some(dir.as_path()), true).await;
+ assert!(!odd.excerpt.contains("sk-live-not-a-hash-but-a-secret"));
+ // A missing file has no hash to show
+ let gone = run("file_sha256", &json!({ "path": "gone.bin", "sha256": expected }), None, Some(dir.as_path()), true).await;
+ assert!(gone.excerpt.contains("doesn't exist"), "{}", gone.excerpt);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/src/server/goals/routes.rs b/src/server/goals/routes.rs
index 7aa603f0..6a75a35d 100644
--- a/src/server/goals/routes.rs
+++ b/src/server/goals/routes.rs
@@ -264,6 +264,8 @@ pub async fn delete_goal(State(state): State<AppState>, RawQuery(q): RawQuery, P
Ok(g) => g,
Err(r) => return r,
};
+ // Its restore mission is closed first: its link rows go with the goal
+ crate::server::goals_remediation::withdraw_for_delete(&state, &g.id).await;
match state.db.delete_goal(&g.id, &g.space_id).await {
Ok(true) => {
emit(&state, &g.id, "deleted", &g.space_id);
diff --git a/src/server/goals/runner.rs b/src/server/goals/runner.rs
index c0df014d..b48e2893 100644
--- a/src/server/goals/runner.rs
+++ b/src/server/goals/runner.rs
@@ -122,7 +122,9 @@ pub async fn run_goal(state: &AppState, g: Goal) -> Option<Goal> {
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" {
+ // A met goal that had one blip stays as it was: nothing about it changed
+ let held_blip = status == "met" && g.status == "met" && says == RunSays::Unknown && g.fail_streak == 0;
+ let status_reason = if held_blip || (status == g.status && status != "met") {
g.status_reason.clone()
} else {
match says {
diff --git a/src/server/goals/tool.rs b/src/server/goals/tool.rs
index 7b1ba12c..9707c7f4 100644
--- a/src/server/goals/tool.rs
+++ b/src/server/goals/tool.rs
@@ -3,7 +3,7 @@
//! 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 super::{build_goal, emit_goal, predicate, CheckInput, GoalInput};
use crate::db::goals::{Created, MAX_DRAFTS};
use crate::db::missions::now_ms;
use crate::server::continuity::SelfScope;
@@ -12,7 +12,21 @@ use serde_json::{json, Value};
pub const TOOL: &str = "goal_propose";
+/// The `metric` and `operator` of the schema, from what predicate validation accepts, so the two
+/// can't drift apart.
+fn metric_help() -> String {
+ format!(
+ "http: {}; command: {}. Leave out for the usual (http status 200, command exit code 0). Say what the target is compared with in `target`.",
+ predicate::metrics("http").join(", "),
+ predicate::metrics("command").join(", ")
+ )
+}
+
pub fn tool() -> Value {
+ let metrics: Vec<&str> = ["http", "command"]
+ .iter()
+ .flat_map(|k| predicate::metrics(k).iter().copied())
+ .collect();
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.",
@@ -32,9 +46,9 @@ pub fn tool() -> Value {
"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"]},
+ "spec": {"type": "object", "description": "command: {command, timeout_secs?}; http: {url}, and for the json_value metric also {pointer}, a JSON pointer such as /status or /items/0/name (empty for the whole document); file_exists: {path}; file_contains: {path, text}; file_sha256: {path, sha256}. Paths are relative to your folder."},
+ "metric": {"type": "string", "enum": metrics, "description": metric_help()},
+ "operator": {"type": "string", "enum": predicate::ALL_OPERATORS, "description": "How the metric is compared with the target. status and exit_code take eq, ne; latency_ms lt, lte; stdout_number and json_value eq, ne, lt, lte, gt, gte; json_value also contains (text in a string, or an item of an array). body_contains and stdout_contains take no operator."},
"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."},
},
@@ -100,3 +114,177 @@ pub async fn call(state: &AppState, scope: &SelfScope, args: &Value) -> (String,
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use predicate::normalize;
+
+ fn schema_list(path: &[&str]) -> Vec<String> {
+ let mut v = tool();
+ for k in ["inputSchema", "properties", "checks", "items", "properties"]
+ .iter()
+ .chain(path)
+ {
+ v = v[*k].clone();
+ }
+ v["enum"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|x| x.as_str().unwrap().to_string())
+ .collect()
+ }
+
+ /// A target every metric takes, whatever its type.
+ fn target(metric: &str, op: Option<&str>) -> &'static str {
+ match (metric, op) {
+ ("status", _) => "200",
+ ("exit_code", _) => "0",
+ ("latency_ms", _) => "500",
+ ("stdout_number", _) => "5",
+ ("json_value", Some("lt" | "lte" | "gt" | "gte")) => "5",
+ _ => "ok",
+ }
+ }
+
+ fn accepts(kind: &str, metric: &str, op: Option<&str>) -> bool {
+ normalize(
+ kind,
+ &json!({"url": "https://example.com/health", "pointer": "/status"}),
+ Some(metric),
+ op,
+ Some(target(metric, op)),
+ )
+ .is_ok()
+ }
+
+ const KINDS: [&str; 2] = ["http", "command"];
+ /// Names a bot might try, valid or not (`json_path` is the one the schema once advertised).
+ const TRIED_METRICS: [&str; 10] = [
+ "status",
+ "latency_ms",
+ "body_contains",
+ "json_value",
+ "json_path",
+ "exit_code",
+ "stdout_contains",
+ "stdout_number",
+ "body_matches",
+ "stdout",
+ ];
+ const TRIED_OPERATORS: [&str; 11] = [
+ "eq", "ne", "lt", "lte", "gt", "gte", "contains", "like", "matches", "in", "between",
+ ];
+
+ #[test]
+ fn every_metric_the_schema_lists_is_accepted() {
+ let listed = schema_list(&["metric"]);
+ assert!(!listed.is_empty());
+ for m in &listed {
+ assert!(
+ KINDS.iter().any(|k| accepts(k, m, None)),
+ "the schema lists metric {m}, which validation refuses"
+ );
+ }
+ }
+
+ #[test]
+ fn every_metric_validation_accepts_is_listed() {
+ let listed = schema_list(&["metric"]);
+ for kind in KINDS {
+ for m in TRIED_METRICS {
+ if accepts(kind, m, None) {
+ assert!(
+ listed.iter().any(|l| l == m),
+ "{kind} accepts metric {m}, which the schema doesn't list"
+ );
+ }
+ }
+ // And what the kind says it offers
+ for m in predicate::metrics(kind) {
+ assert!(
+ listed.iter().any(|l| l == m),
+ "{kind} offers {m}, which the schema doesn't list"
+ );
+ }
+ }
+ assert!(
+ !listed.iter().any(|l| l == "json_path"),
+ "json_path isn't a metric"
+ );
+ }
+
+ #[test]
+ fn every_operator_the_schema_lists_is_accepted() {
+ let listed = schema_list(&["operator"]);
+ for op in &listed {
+ let some_metric_takes_it = KINDS.iter().any(|k| {
+ predicate::metrics(k)
+ .iter()
+ .any(|m| accepts(k, m, Some(op)))
+ });
+ assert!(
+ some_metric_takes_it,
+ "the schema lists operator {op}, which no metric accepts"
+ );
+ }
+ }
+
+ #[test]
+ fn every_operator_validation_accepts_is_listed() {
+ let listed = schema_list(&["operator"]);
+ for kind in KINDS {
+ for m in predicate::metrics(kind) {
+ for op in TRIED_OPERATORS {
+ if accepts(kind, m, Some(op)) {
+ assert!(
+ listed.iter().any(|l| l == op),
+ "{m} accepts operator {op}, which the schema doesn't list"
+ );
+ }
+ }
+ }
+ }
+ // contains is the one the schema lacked
+ assert!(listed.iter().any(|l| l == "contains"));
+ }
+
+ #[test]
+ fn a_json_check_written_from_the_schema_is_accepted() {
+ // The spec description says json_value needs a pointer
+ let v = tool();
+ let spec = v["inputSchema"]["properties"]["checks"]["items"]["properties"]["spec"]
+ ["description"]
+ .as_str()
+ .unwrap();
+ assert!(
+ spec.contains("json_value") && spec.contains("pointer"),
+ "{spec}"
+ );
+ let spec = json!({"url": "https://example.com/health", "pointer": "/status"});
+ for (op, t) in [
+ ("eq", "ok"),
+ ("ne", "down"),
+ ("contains", "ok"),
+ ("gte", "3"),
+ ] {
+ let p = normalize("http", &spec, Some("json_value"), Some(op), Some(t))
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ (p.metric.as_str(), p.operator.as_deref()),
+ ("json_value", Some(op))
+ );
+ }
+ // A bad pointer is refused in words
+ assert!(normalize(
+ "http",
+ &json!({"url": "https://x.test", "pointer": "status"}),
+ Some("json_value"),
+ Some("eq"),
+ Some("ok")
+ )
+ .is_err());
+ }
+}
diff --git a/src/server/goals_remediation.rs b/src/server/goals_remediation.rs
index b34f906c..bbaa073b 100644
--- a/src/server/goals_remediation.rs
+++ b/src/server/goals_remediation.rs
@@ -266,6 +266,19 @@ async fn cancel_mission(state: &AppState, link: &GoalLink) {
missions::emit_mission(state, &link.mission_id).await;
}
+/// The goal is being deleted: its open restore mission and that mission's unfinished tasks are
+/// cancelled, so deleting a goal to stop the noise leaves nothing running or waiting. Nothing is
+/// removed: the mission, its tasks and their history stay on the board, as cancelled. A mission
+/// another open goal still shares is left for that goal. Call before the goal's rows go.
+pub async fn withdraw_for_delete(state: &AppState, goal_id: &str) {
+ for link in state.db.goal_links(goal_id, 50).await.unwrap_or_default().into_iter().filter(|l| l.closed_at.is_none()) {
+ let shared = state.db.links_of_mission(&link.mission_id).await.unwrap_or_default().into_iter().any(|l| l.goal_id != goal_id && l.closed_at.is_none());
+ if !shared {
+ cancel_mission(state, &link).await;
+ }
+ }
+}
+
/// Reads the Investigate report, if the bot wrote one inside the goal's folder.
async fn read_report(folder: &str, rel: &str) -> Option<String> {
let base = std::fs::canonicalize(folder).ok()?;
diff --git a/src/server/missions/checks.rs b/src/server/missions/checks.rs
index 6303638b..fa8f147e 100644
--- a/src/server/missions/checks.rs
+++ b/src/server/missions/checks.rs
@@ -77,6 +77,13 @@ pub struct Seen {
pub stdout: Option<String>,
pub http_status: Option<u16>,
pub body: Option<String>,
+ /// The body was longer than the read cap, so `body` is only its start.
+ pub body_truncated: bool,
+ /// Where a 3xx answer points: the host only (never the path or query, which may hold a token),
+ /// or `None` inside it when the address stays on the checked host. Not followed.
+ pub redirect: Option<Option<String>>,
+ /// A `file_sha256` check's `(actual, expected)` hashes, both lowercase hex.
+ pub sha256: Option<(String, String)>,
}
/// Runs one check; returns `(status, output)` with status "passed", "failed" or "error".
@@ -115,7 +122,7 @@ pub async fn run_spec_seen(kind: &str, spec: &Value, folder: Option<&Path>, pers
None => Err("spec.url is missing".into()),
},
"file_exists" | "file_contains" | "file_sha256" => match (s("path"), need_folder()) {
- (Some(rel), Ok(dir)) => file(kind, rel, spec, dir).await,
+ (Some(rel), Ok(dir)) => file(kind, rel, spec, dir, &mut seen).await,
(None, _) => Err("spec.path is missing".into()),
(_, Err(e)) => Err(e),
},
@@ -147,11 +154,19 @@ async fn http(url: &str, spec: &Value, person_ok: bool, seen: &mut Seen) -> Resu
Some(want) => u64::from(status) == want,
None => (200..300).contains(&status),
};
+ if (300..400).contains(&status) {
+ let from = resp.url().clone();
+ let to = resp.headers().get(reqwest::header::LOCATION).and_then(|l| l.to_str().ok()).and_then(|l| from.join(l).ok());
+ seen.redirect = to.map(|u| u.host_str().filter(|h| Some(*h) != from.host_str()).map(str::to_string));
+ }
let mut body = Vec::new();
let mut stream = resp;
while let Ok(Some(chunk)) = stream.chunk().await {
body.extend_from_slice(&chunk);
if body.len() >= MAX_READ_BYTES {
+ // Cut at the cap exactly (a chunk may run past it); it only counts as cut if more follows
+ seen.body_truncated = body.len() > MAX_READ_BYTES || matches!(stream.chunk().await, Ok(Some(c)) if !c.is_empty());
+ body.truncate(MAX_READ_BYTES);
break;
}
}
@@ -162,6 +177,15 @@ async fn http(url: &str, spec: &Value, person_ok: bool, seen: &mut Seen) -> Resu
if let Some(t) = contains {
out.push_str(&format!("; {} \"{t}\"", if has { "contains" } else { "does not contain" }));
}
+ if let Some(to) = &seen.redirect {
+ out.push_str(&format!(
+ "; redirects to {}, which kwant doesn't follow",
+ to.as_deref().unwrap_or("another address on the same site")
+ ));
+ }
+ if seen.body_truncated {
+ out.push_str("; the page is larger than 5 MB, so only its start was read");
+ }
seen.http_status = Some(status);
seen.body = Some(text.into_owned());
Ok((ok_status && has, out))
@@ -180,7 +204,7 @@ fn send_error(url: &str, e: &reqwest::Error) -> String {
format!("GET {url} failed: network error, {why} ({e})")
}
-async fn file(kind: &str, rel: &str, spec: &Value, dir: &Path) -> Result<(bool, String), String> {
+async fn file(kind: &str, rel: &str, spec: &Value, dir: &Path, seen: &mut Seen) -> Result<(bool, String), String> {
let path = inside(dir, rel)?;
let meta = tokio::fs::metadata(&path).await;
match kind {
@@ -197,6 +221,7 @@ async fn file(kind: &str, rel: &str, spec: &Value, dir: &Path) -> Result<(bool,
if kind == "file_sha256" {
let got = hex(&Sha256::digest(&bytes));
let want = spec["sha256"].as_str().unwrap_or("").trim().to_ascii_lowercase();
+ seen.sha256 = Some((got.clone(), want.clone()));
Ok((got == want, format!("sha256 of {rel} is {got}")))
} else {
let want = spec["text"].as_str().unwrap_or("");
diff --git a/tests/goals_remediation_test.rs b/tests/goals_remediation_test.rs
index 7a21e252..b1b50813 100644
--- a/tests/goals_remediation_test.rs
+++ b/tests/goals_remediation_test.rs
@@ -891,3 +891,45 @@ async fn g_d_03_no_draft_turn_when_three_drafts_already_wait() {
let (s, _) = send(&e, "POST", "/api/goals/draft", None, Some(json!({"space_id": space, "kwant_id": e.bot, "text": "the site answers"})), None).await;
assert_eq!(s, StatusCode::CONFLICT);
}
+
+// Post-0.6.5 (Rigel's remediation Minor 1): deleting a goal closes its open Restore mission
+
+#[tokio::test]
+async fn g_r_25_deleting_a_goal_cancels_its_open_restore_mission_and_keeps_the_history() {
+ let e = setup().await;
+ let g = goal(&e, "Site is up", "suggest").await;
+ break_goal(&e, &g.id).await;
+ tick_at(&e.state, now()).await;
+ let l = open_link(&e, &g.id).await;
+ assert_eq!(task(&e, &l.fix_task_id).await.state, "backlog", "the held Fix");
+ assert_ne!(task(&e, &l.investigate_task_id).await.state, "cancelled");
+ let (s, _) = send(&e, "DELETE", &format!("/api/goals/{}", g.id), None, None, None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert!(e.state.db.get_goal(&g.id).await.unwrap().is_none());
+ // The mission and its tasks are still there, cancelled
+ let m = e.state.db.get_mission(&l.mission_id).await.unwrap().expect("the mission stays on the board");
+ assert_eq!(m.status, "cancelled");
+ assert!(m.finished_at.is_some());
+ assert_eq!(task(&e, &l.investigate_task_id).await.state, "cancelled");
+ assert_eq!(task(&e, &l.fix_task_id).await.state, "cancelled");
+ assert!(!e.state.db.task_events(&l.fix_task_id, 50).await.unwrap().is_empty(), "the task keeps its history");
+ // Nothing reopens it
+ tick_at(&e.state, now() + 30 * MIN).await;
+ assert_eq!(e.state.db.get_mission(&l.mission_id).await.unwrap().unwrap().status, "cancelled");
+}
+
+#[tokio::test]
+async fn g_r_26_deleting_a_goal_with_no_remediation_changes_no_mission() {
+ let e = setup().await;
+ let a = goal(&e, "Site is up", "suggest").await;
+ let folder2 = e.folder.parent().unwrap().join("other");
+ std::fs::create_dir_all(&folder2).unwrap();
+ let b = goal_in(&e, "Other site is up", &folder2, "suggest", 2).await;
+ break_goal(&e, &b.id).await;
+ tick_at(&e.state, now()).await;
+ let lb = open_link(&e, &b.id).await;
+ let (s, _) = send(&e, "DELETE", &format!("/api/goals/{}", a.id), None, None, None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(e.state.db.get_mission(&lb.mission_id).await.unwrap().unwrap().status, "active", "another goal's mission is untouched");
+ assert_ne!(task(&e, &lb.investigate_task_id).await.state, "cancelled");
+}
diff --git a/tests/goals_test.rs b/tests/goals_test.rs
index a0d80bf8..e4916b35 100644
--- a/tests/goals_test.rs
+++ b/tests/goals_test.rs
@@ -207,6 +207,7 @@ async fn an_error_between_failures_is_unknown_and_never_confirms() {
// The edit doesn't touch the streak: only runs do
assert_eq!(edited.fail_streak, 1);
let after = run_now(&e, &g.id).await;
+ // An error right after a failure shows unknown (a blip is held only after a pass) and breaks the run of failures
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();
@@ -433,3 +434,201 @@ async fn a_fresh_install_runs_nothing() {
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)));
}
+
+// Post-0.6.5 api-M7: one transport blip doesn't turn a met goal into "can't check"
+#[tokio::test]
+async fn one_dropped_connection_keeps_a_met_goal_met_and_two_in_a_row_do_not() {
+ let e = setup().await;
+ let up = server(vec![200]).await;
+ let g = create(&e, &new_goal(&e, &up, 2)).await;
+ assert_eq!(run_now(&e, &g.id).await.status, "met");
+ point(&e, &g.id, &closed_port()).await;
+ let blip = run_now(&e, &g.id).await;
+ assert_eq!((blip.status.as_str(), blip.status_reason.as_str(), blip.error_runs), ("met", "", 1));
+ assert!(!kinds(&e, &g.id).await.contains(&"unknown".to_string()), "no timeline entry for a blip");
+ // The run's own record still says it couldn't check
+ assert_eq!(e.state.db.recent_observations(&g.id, 1).await.unwrap()[0].verdict, "unknown");
+ // A good run in between starts the count again
+ point(&e, &g.id, &up).await;
+ let back = run_now(&e, &g.id).await;
+ assert_eq!((back.status.as_str(), back.error_runs), ("met", 0));
+ point(&e, &g.id, &closed_port()).await;
+ assert_eq!(run_now(&e, &g.id).await.status, "met", "a second blip, but not in a row");
+ // Two in a row: now it can't say
+ let two = run_now(&e, &g.id).await;
+ assert_eq!((two.status.as_str(), two.status_reason.as_str(), two.error_runs), ("unknown", "cant_check", 2));
+ assert!(two.unknown_since.is_some());
+ assert_eq!(kinds(&e, &g.id).await.iter().filter(|k| *k == "unknown").count(), 1);
+ assert!(notices(&e, &g.id).await.is_empty(), "never news before a day");
+}
+
+/// Points the goal's one check at `url`, leaving everything else as it is.
+async fn point(e: &Env, id: &str, url: &str) {
+ let url = url.to_string();
+ e.state
+ .db
+ .edit_goal(id, &e.space, "person", now_ms(), move |_g: &mut Goal| {
+ 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![],
+ })
+ })
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+}
+
+// Post-0.6.5 api-M6: a notice that wasn't sent is neither recorded nor counted
+#[tokio::test]
+async fn a_notice_the_person_turned_off_is_not_recorded_or_counted() {
+ let e = setup().await;
+ let g = create(&e, &new_goal(&e, "https://example.com/", 1)).await;
+ // goal_alert off in Settings (known, so not read as a new kind)
+ e.state.db.set_setting("notify_on", r#"["turn_finished"]"#).await.unwrap();
+ e.state.db.set_setting("notify_known", r#"["turn_finished","goal_alert"]"#).await.unwrap();
+ for _ in 0..5 {
+ assert!(!goals::notice(&e.state, &g, "broken", "t".into(), "b".into()).await);
+ }
+ assert!(notices(&e, &g.id).await.is_empty(), "nothing recorded as sent");
+ assert!(!kinds(&e, &g.id).await.contains(&"notice_capped".to_string()), "and not as capped either");
+ assert_eq!(e.state.db.goal_notices_since(&g.id, 0).await.unwrap(), 0);
+ // Turned back on, all three still go out
+ e.state.db.set_setting("notify_on", r#"["turn_finished","goal_alert"]"#).await.unwrap();
+ 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_eq!(notices(&e, &g.id).await, ["broken", "broken", "broken"]);
+}
+
+// A "can't check" notice with goal_alert off sends nothing and records nothing, and runs still update the status
+#[tokio::test]
+async fn cant_check_with_alerts_off_sends_nothing_and_the_status_still_moves() {
+ let e = setup().await;
+ let up = server(vec![200]).await;
+ let g = create(&e, &new_goal(&e, &closed_port(), 2)).await;
+ assert_eq!(run_now(&e, &g.id).await.status, "unknown");
+ e.state.db.set_setting("notify_on", r#"["turn_finished"]"#).await.unwrap();
+ e.state.db.set_setting("notify_known", r#"["turn_finished","goal_alert"]"#).await.unwrap();
+ let stuck = e.state.db.goals_unknown_since(now_ms() + goals::UNKNOWN_NOTICE_MS).await.unwrap().into_iter().find(|x| x.id == g.id).unwrap();
+ for _ in 0..3 {
+ assert!(!goals::notice(&e.state, &stuck, "cant_check", "t".into(), "b".into()).await);
+ runner::tick(&e.state).await;
+ }
+ assert!(notices(&e, &g.id).await.is_empty());
+ assert!(!kinds(&e, &g.id).await.contains(&"notice_capped".to_string()));
+ // Still unknown, and the next good run moves it to met all the same
+ assert_eq!(e.state.db.get_goal(&g.id).await.unwrap().unwrap().status, "unknown");
+ point(&e, &g.id, &up).await;
+ assert_eq!(run_now(&e, &g.id).await.status, "met");
+ assert!(notices(&e, &g.id).await.is_empty());
+}
+
+/// A server for one path answering with `status`, `headers` and `body`.
+async fn page(status: u16, headers: Vec<(&'static str, String)>, body: Vec<u8>) -> String {
+ use axum::routing::get;
+ let app = Router::new().route(
+ "/",
+ get(move || {
+ let (headers, body) = (headers.clone(), body.clone());
+ async move {
+ let mut r = axum::response::Response::new(Body::from(body));
+ *r.status_mut() = StatusCode::from_u16(status).unwrap();
+ for (k, v) in headers {
+ r.headers_mut().insert(k, v.parse().unwrap());
+ }
+ r
+ }
+ }),
+ );
+ 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 body_goal(e: &Env, url: &str, metric: &str, target: &str) -> NewGoal {
+ let mut g = new_goal(e, url, 1);
+ g.checks[0].metric = Some(metric.into());
+ g.checks[0].operator = None;
+ g.checks[0].target = Some(target.into());
+ g
+}
+
+// Post-0.6.5 api-M3: a page past 5 MB is "can't check", never a false not_met
+#[tokio::test]
+async fn a_page_over_5_mb_is_cant_check_not_broken() {
+ let e = setup().await;
+ let mut body = vec![b'x'; 5 * 1024 * 1024 + 4096];
+ body.extend_from_slice(b"needle");
+ body[..5].copy_from_slice(b"early");
+ let url = page(200, vec![], body).await;
+ // The needle is past the cap
+ let g = create(&e, &body_goal(&e, &url, "body_contains", "needle")).await;
+ let after = run_now(&e, &g.id).await;
+ assert_eq!(after.status, "unknown", "not broken");
+ assert!(!kinds(&e, &g.id).await.contains(&"not_met".to_string()));
+ let obs = e.state.db.recent_observations(&g.id, 1).await.unwrap().remove(0);
+ assert_eq!(obs.verdict, "unknown");
+ assert_eq!(obs.observed_value.as_deref(), Some("The page is larger than 5 MB, so I can't check it"));
+ assert!(obs.excerpt.contains("larger than 5 MB"), "{}", obs.excerpt);
+ // One in the part that was read is still found
+ let g2 = create(&e, &body_goal(&e, &url, "body_contains", "early")).await;
+ assert_eq!(run_now(&e, &g2.id).await.status, "met");
+ // A short page without the needle is still not met
+ let short = page(200, vec![], b"hello".to_vec()).await;
+ let g3 = create(&e, &body_goal(&e, &short, "body_contains", "needle")).await;
+ assert_eq!(run_now(&e, &g3.id).await.status, "not_met");
+}
+
+// Post-0.6.5 api-M4: a redirect is not followed; the reason names where it goes
+#[tokio::test]
+async fn a_redirect_is_not_followed_and_says_where_it_goes() {
+ let e = setup().await;
+ let url = page(301, vec![("location", "https://www.example.org/start?token=abc123".into())], vec![]).await;
+ let g = create(&e, &new_goal(&e, &url, 1)).await;
+ assert_eq!(run_now(&e, &g.id).await.status, "not_met");
+ let obs = e.state.db.recent_observations(&g.id, 1).await.unwrap().remove(0);
+ let seen = obs.observed_value.unwrap();
+ assert!(seen.starts_with("301: it redirects to www.example.org"), "{seen}");
+ assert!(seen.contains("use the final address"), "{seen}");
+ assert!(!seen.contains("token") && !obs.excerpt.contains("token"), "only the host is shown, never the path or query");
+ assert!(obs.excerpt.contains("redirects to www.example.org"), "{}", obs.excerpt);
+ // A relative Location stays on the same site
+ let rel = page(302, vec![("location", "/login".into())], vec![]).await;
+ let g2 = create(&e, &new_goal(&e, &rel, 1)).await;
+ run_now(&e, &g2.id).await;
+ let seen = e.state.db.recent_observations(&g2.id, 1).await.unwrap().remove(0).observed_value.unwrap();
+ assert!(seen.contains("another address on the same site"), "{seen}");
+ // The redirect target was never fetched: a plain 200 has no such note
+ let ok = page(200, vec![], vec![]).await;
+ let g3 = create(&e, &new_goal(&e, &ok, 1)).await;
+ assert_eq!(run_now(&e, &g3.id).await.status, "met");
+}
+
+// Post-0.6.5 api-M5: the goal's own record shows both hashes
+#[tokio::test]
+async fn a_changed_file_shows_its_expected_and_actual_hash() {
+ let e = setup().await;
+ let dir = tempdir().unwrap();
+ std::fs::write(dir.path().join("release.bin"), "hello").unwrap();
+ let mut ng = new_goal(&e, "https://example.com/", 1);
+ ng.folder = dir.path().to_string_lossy().into_owned();
+ let expected = "b".repeat(64);
+ ng.checks = vec![NewGoalCheck { label: "unchanged".into(), kind: "file_sha256".into(), spec: json!({"path": "release.bin", "sha256": expected}), metric: None, operator: None, target: None, severity: "required".into(), freshness_minutes: 120 }];
+ let g = create(&e, &ng).await;
+ assert_eq!(run_now(&e, &g.id).await.status, "not_met");
+ let obs = e.state.db.recent_observations(&g.id, 1).await.unwrap().remove(0);
+ assert!(obs.excerpt.contains(&format!("expected {expected}")), "{}", obs.excerpt);
+ assert!(obs.excerpt.contains("actual 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"), "{}", obs.excerpt);
+}