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
Automation Discovery: replace a changed offer in one step, outside the cap
Lin (kwant bot)c185fc9fa818
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0d30abb2..5cab9c83 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,7 +28,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).run, checks, the tasks it came from and what the bot may do when it runs. Accept makes the routine,with your changes to the name, schedule, bot, delivery, acceptance or checks; Dismiss stops it beingsuggested for 30 days. Nothing is made without Accept, and only you can see, accept or dismiss- suggestions. Suggestions whose habit stopped or changed are withdrawn. Undoing the delete of a+ suggestions. Suggestions whose habit stopped are withdrawn; one whose habit changed (another bot,+ days or time) is updated in place, without a second notification and without using up the day's+ suggestions. Undoing the delete of asuggested routine keeps it marked as suggested. Exports now carry a routine's class and acceptance,and its checks when they hold no secrets. This is step 3 of Automation Discovery; the screens comenext.diff --git a/docs/mission-control.md b/docs/mission-control.mdindex 12e0ef24..dc4536b1 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -936,10 +936,14 @@ timezone, offered: [offer], skipped}`, writing nothing at all.A scan, per space: a live offer whose habit no longer passes the miner is `expired`; one whose habitstill passes but changed (another bot, another rhythm, days or time zone, or the time moved ≥ 30-minutes) is `superseded` and offered again as it is now, within the cap and without a second+minutes) is replaced in one transaction: the old row becomes `superseded` (event `superseded`,+`{replaced_by}`) and the habit as it is now is stored live (event `offered`, `{cluster_key, replaces}`),+keeping the old `offered_at`, or neither happens. A replacement adds no live offer and is no new offer,+so the daily cap and the live limit don't apply to it, nothing counts it toward them, and it sends nonotification. Then each new offer is stored (`sug_…`) with one `offered` event, within the daily cap-(offers in the last 24 hours) and 5 live per space, checked in the same statement as the insert, so two-racing scans store one offer per habit. Delivery is re-checked: a thread that is gone or archived, or+(new offers in the last 24 hours, rolling, not local midnight; replacements don't count) and 5 live per+space, checked in the same statement as the insert, so two racing scans store one offer per habit.+`stats.offered_30d` counts new offers the same way. Delivery is re-checked: a thread that is gone or archived, ora channel of another space, falls back to the bot's direct chat. Checks a routine may not carry aremoved to the left-out list.diff --git a/src/db/automation.rs b/src/db/automation.rsindex cee639e2..ef6b90bf 100644--- a/src/db/automation.rs+++ b/src/db/automation.rs@@ -79,6 +79,12 @@ const SUGGESTION_SELECT: &str = "SELECT id, space_id, cluster_key, kwant_id, namtask_class, acceptance, checks, left_out_checks, chain, source_task_ids, evidence, status, routine_id, cooldown_until,routine_deleted_at, retention, retention_at, offered_at, decided_at FROM routine_suggestions";+/// SQL: suggestion `c` was a new offer, not a replacement of a live one whose habit changed+/// (its `offered` event names the offer it `replaces`). Only new offers count toward the daily+/// cap and the stats, so a habit that changes is counted once however often it is replaced.+const NEW_OFFER: &str = "NOT EXISTS (SELECT 1 FROM routine_suggestion_events e+ WHERE e.suggestion_id = c.id AND e.kind = 'offered' AND json_extract(e.detail, '$.replaces') IS NOT NULL)";+fn text<T: serde::Serialize + ?Sized>(v: &T) -> String {serde_json::to_string(v).unwrap_or_default()}@@ -261,7 +267,7 @@ impl Database {.bind(space).fetch_all(&self.pool).await?;- let (offered_24h,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM routine_suggestions WHERE space_id = ? AND offered_at > ?")+ let (offered_24h,): (i64,) = sqlx::query_as(&format!("SELECT COUNT(*) FROM routine_suggestions c WHERE space_id = ? AND offered_at > ? AND {NEW_OFFER}")).bind(space).bind(now - Duration::hours(24)).fetch_one(&self.pool)@@ -292,14 +298,14 @@ impl Database {let mut evidence = serde_json::to_value(&offer.evidence).unwrap_or_default();evidence["sources"] = serde_json::to_value(&offer.sources).unwrap_or_default();let mut tx = self.pool.begin().await?;- let res = sqlx::query(+ let res = sqlx::query(&format!("INSERT INTO routine_suggestions (id, space_id, cluster_key, kwant_id, name, instructions, schedule, first_run_at, delivery,task_class, acceptance, checks, left_out_checks, chain, source_task_ids, evidence, status, offered_at)SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, 'offered', ?17WHERE (SELECT COUNT(*) FROM routine_suggestions WHERE space_id = ?2 AND status = 'offered') < ?18- AND (SELECT COUNT(*) FROM routine_suggestions WHERE space_id = ?2 AND offered_at > ?19) < ?20- ON CONFLICT DO NOTHING",- )+ AND (SELECT COUNT(*) FROM routine_suggestions c WHERE space_id = ?2 AND offered_at > ?19 AND {NEW_OFFER}) < ?20+ ON CONFLICT DO NOTHING"+ )).bind(&id).bind(space).bind(&offer.cluster_key)@@ -331,6 +337,62 @@ impl Database {Ok(Some(id))}+ /// Replaces live offer `old` of `space`, whose habit changed (design §6), with `offer` as the+ /// habit is now, in one transaction: `old` becomes `superseded` and the replacement is stored+ /// live, or neither happens. The replacement adds no live offer and is no new offer, so the+ /// daily cap and the live limit don't apply to it and it isn't counted toward them (its+ /// `offered` event names the offer it `replaces`); it keeps `old`'s `offered_at`. `None` when+ /// `old` is no longer live (another scan, or the person, decided it first).+ pub async fn replace_offer(&self, old: &str, space: &str, offer: &Offer, now: DateTime<Utc>) -> Result<Option<String>, DbError> {+ let id = format!("sug_{}", Uuid::new_v4().simple());+ let mut evidence = serde_json::to_value(&offer.evidence).unwrap_or_default();+ evidence["sources"] = serde_json::to_value(&offer.sources).unwrap_or_default();+ let mut tx = self.pool.begin().await?;+ // A write first, so the transaction holds the lock from its first statement+ let offered_at: Option<(DateTime<Utc>,)> = sqlx::query_as(+ "UPDATE routine_suggestions SET status = 'superseded', decided_at = ?1+ WHERE id = ?2 AND space_id = ?3 AND cluster_key = ?4 AND status = 'offered' RETURNING offered_at",+ )+ .bind(now)+ .bind(old)+ .bind(space)+ .bind(&offer.cluster_key)+ .fetch_optional(&mut *tx)+ .await?;+ let Some((offered_at,)) = offered_at else {+ tx.rollback().await?;+ return Ok(None);+ };+ sqlx::query(+ "INSERT INTO routine_suggestions (id, space_id, cluster_key, kwant_id, name, instructions, schedule, first_run_at, delivery,+ task_class, acceptance, checks, left_out_checks, chain, source_task_ids, evidence, status, offered_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, 'offered', ?17)",+ )+ .bind(&id)+ .bind(space)+ .bind(&offer.cluster_key)+ .bind(&offer.kwant_id)+ .bind(&offer.name)+ .bind(&offer.instructions)+ .bind(text(&offer.schedule))+ .bind(offer.first_run_at)+ .bind(text(&offer.delivery))+ .bind(&offer.task_class)+ .bind(&offer.acceptance)+ .bind(text(&offer.checks))+ .bind(text(&offer.left_out_checks))+ .bind(text(&offer.chain))+ .bind(text(&offer.source_task_ids))+ .bind(evidence.to_string())+ .bind(offered_at)+ .execute(&mut *tx)+ .await?;+ event(&mut tx, old, "superseded", "kwant", json!({ "replaced_by": id }), now).await?;+ event(&mut tx, &id, "offered", "kwant", json!({ "cluster_key": offer.cluster_key, "replaces": old }), now).await?;+ tx.commit().await?;+ Ok(Some(id))+ }+pub async fn get_suggestion(&self, id: &str) -> Result<Option<SuggestionRow>, DbError> {Ok(sqlx::query_as::<_, SuggestionRow>(&format!("{SUGGESTION_SELECT} WHERE id = ?")).bind(id).fetch_optional(&self.pool).await?)}@@ -491,14 +553,14 @@ impl Database {pub async fn suggestion_stats(&self, space: &str, now: DateTime<Utc>) -> Result<SuggestionStats, DbError> {let since = now - Duration::days(30);- let (offered_30d, accepted_30d, dismissed_30d, retained, dropped): (i64, i64, i64, i64, i64) = sqlx::query_as(- "SELECT COALESCE(SUM(offered_at > ?2), 0),+ let (offered_30d, accepted_30d, dismissed_30d, retained, dropped): (i64, i64, i64, i64, i64) = sqlx::query_as(&format!(+ "SELECT COALESCE(SUM(offered_at > ?2 AND {NEW_OFFER}), 0),COALESCE(SUM(status = 'accepted' AND decided_at > ?2), 0),COALESCE(SUM(status = 'dismissed' AND decided_at > ?2), 0),COALESCE(SUM(retention = 'retained'), 0),COALESCE(SUM(retention = 'dropped'), 0)- FROM routine_suggestions WHERE space_id = ?1",- )+ FROM routine_suggestions c WHERE space_id = ?1"+ )).bind(space).bind(since).fetch_one(&self.pool)diff --git a/src/server/missions/discovery.rs b/src/server/missions/discovery.rsindex 85e6d9b2..54fdbd42 100644--- a/src/server/missions/discovery.rs+++ b/src/server/missions/discovery.rs@@ -187,33 +187,37 @@ pub struct Stored {}/// One scan of `space` at `now` that keeps what it finds (design §6): a live offer whose habit no-/// longer passes is `expired`, one whose rhythm, time or bot changed is `superseded` and offered-/// again as it is now (within the cap, without a second notification); new habits are stored as-/// offers, one notification each. Two scans racing store one offer per habit.+/// longer passes is `expired`; one whose rhythm, time or bot changed is replaced, in one step, by+/// the habit as it is now (outside the daily cap and the live limit, since it adds no offer, and+/// without a second notification). New habits are stored as offers, one notification each. Two+/// scans racing store one offer per habit.pub async fn scan_space(state: &AppState, space_id: &SpaceId, tz: &str, now: DateTime<Utc>) -> Result<Stored, DbError> {let space = space_id.as_str();let mut out = Stored::default();- let mut scan = mine(state, space_id, tz, now).await?;- let mut replaced: HashSet<String> = HashSet::new();+ // Live offers first, then the miner: an offer another scan stores in between isn't in `live`,+ // so it can't be mistaken for one whose habit is gone (and expired, and offered twice)let live = state.db.list_suggestions(space, Some("offered")).await?;+ let mut scan = mine(state, space_id, tz, now).await?;for row in &live {let now_offer = scan.live.iter().find(|o| o.cluster_key == row.cluster_key);- let kind = match (now_offer, serde_json::from_str::<Schedule>(&row.schedule)) {- (None, _) => "expired",- (Some(o), Ok(s)) if !miner::materially_changed(&s, &row.kwant_id, o) => continue,- (Some(_), _) => "superseded",- };- if state.db.end_offer(&row.id, kind, now).await? {- if kind == "expired" {- out.expired.push(row.id.clone());- } else {- replaced.insert(row.cluster_key.clone());- out.superseded.push(row.id.clone());+ match (now_offer, serde_json::from_str::<Schedule>(&row.schedule)) {+ (None, _) => {+ if state.db.end_offer(&row.id, "expired", now).await? {+ out.expired.push(row.id.clone());+ }+ }+ (Some(o), Ok(s)) if !miner::materially_changed(&s, &row.kwant_id, o) => {}+ (Some(o), _) => {+ let o = storable(state, space, o.clone()).await;+ // `None`: another scan or the person decided it first; that decision stands+ if state.db.replace_offer(&row.id, space, &o, now).await?.is_some() {+ out.superseded.push(row.id.clone());+ }}}}- // Ended offers free their habits and their room: mine again with that- if !out.expired.is_empty() || !out.superseded.is_empty() {+ // Expired offers free their habits and their room: mine again with that+ if !out.expired.is_empty() {scan = mine(state, space_id, tz, now).await?;}let cap = daily_cap(state).await;@@ -222,9 +226,7 @@ pub async fn scan_space(state: &AppState, space_id: &SpaceId, tz: &str, now: Datlet o = storable(state, space, o).await;match state.db.store_offer(space, &o, now, cap, miner::MAX_LIVE_PER_SPACE).await? {Some(id) => {- if !replaced.contains(&key) {- announce(state, &o).await;- }+ announce(state, &o).await;out.offered.push(id);}// Another scan got there first, or the space filled up meanwhilediff --git a/tests/automation_discovery_test.rs b/tests/automation_discovery_test.rsindex 54f9c99f..1e9be892 100644--- a/tests/automation_discovery_test.rs+++ b/tests/automation_discovery_test.rs@@ -640,3 +640,157 @@ async fn undoing_a_bots_delete_keeps_the_routine_discovered() {assert_eq!((s.routine_id.as_deref(), s.routine_deleted_at), (back["id"].as_str(), None));assert_eq!(person(&e, "POST", SCAN, None).await["skipped"][0]["reason"], "covered");}++// Rigel's review of #165: a changed habit under a used-up cap, races, midnight, bots, toggles++#[tokio::test]+async fn a_changed_habit_is_replaced_even_when_the_cap_is_used_up() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ let b = bot(&e, "Ben").await;+ let c = bot(&e, "Cleo").await;+ let space = SpaceId::default_space();+ person(&e, "POST", "/api/settings", Some(json!({"automation_discovery": "on", "automation_discovery_daily_cap": 1}))).await;+ mondays(&e, &a, "Weekly report", day("2026-10-12")).await;+ let mut rx = e.state.event_sender.subscribe();+ let monday = berlin(day("2026-10-12"), 10, 0);+ let old = discovery::scan_space(&e.state, &space, TZ, monday).await.unwrap().offered[0].clone();++ // The habit moves to Ben while the day's one offer is used up: the offer is replaced, not lost+ sqlx::query("UPDATE tasks SET owner_kwant_id = ? WHERE owner_kwant_id = ?").bind(&b.id).bind(&a.id).execute(&e.pool).await.unwrap();+ let s = discovery::scan_space(&e.state, &space, TZ, monday + Duration::hours(2)).await.unwrap();+ assert_eq!((s.superseded.clone(), s.offered.len()), (vec![old.clone()], 0), "{s:?}");+ let rows = e.state.db.list_suggestions(space.as_str(), Some("offered")).await.unwrap();+ assert_eq!(rows.len(), 1);+ let new = &rows[0];+ assert_eq!((new.kwant_id.as_str(), new.cluster_key.as_str()), (b.id.as_str(), e.state.db.get_suggestion(&old).await.unwrap().unwrap().cluster_key.as_str()));+ assert_eq!(e.state.db.get_suggestion(&old).await.unwrap().unwrap().status, "superseded");+ assert_eq!(events(&e, &old).await.iter().map(|e| e.0.as_str()).collect::<Vec<_>>(), ["offered", "superseded"]);+ assert_eq!(events(&e, &new.id).await.iter().map(|e| e.0.as_str()).collect::<Vec<_>>(), ["offered"]);+ assert_eq!(suggested(&mut rx).len(), 1, "one notification, for the first offer only");++ // The replacement used no room: a new habit is still capped that day, and offered the next+ mondays(&e, &c, "Send invoices", day("2026-10-12")).await;+ let s = discovery::scan_space(&e.state, &space, TZ, monday + Duration::hours(3)).await.unwrap();+ assert!(s.offered.is_empty() && s.skipped.iter().any(|k| k.title == "Send invoices" && matches!(k.reason, kwnt::automation_discovery::Reason::Capped)), "{s:?}");+ // Changed again: replaced again, still one live and no notification+ sqlx::query("UPDATE tasks SET owner_kwant_id = ? WHERE owner_kwant_id = ? AND title LIKE 'Weekly report%'").bind(&a.id).bind(&b.id).execute(&e.pool).await.unwrap();+ let s = discovery::scan_space(&e.state, &space, TZ, monday + Duration::hours(4)).await.unwrap();+ assert_eq!((s.superseded.len(), s.offered.len(), live(&e).await), (1, 0, 1), "{s:?}");+ assert!(suggested(&mut rx).is_empty());+ let s = discovery::scan_space(&e.state, &space, TZ, monday + Duration::hours(25)).await.unwrap();+ assert_eq!((s.offered.len(), live(&e).await), (1, 2), "{s:?}");+ assert_eq!(suggested(&mut rx).len(), 1);+ // Stats count each habit's offer once, however often it was replaced+ assert_eq!(e.state.db.suggestion_stats(space.as_str(), monday + Duration::hours(25)).await.unwrap().offered_30d, 2);+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn six_accepts_at_once_make_one_routine() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ discovery_on(&e).await;+ habit(&e, &a, "Weekly report").await;+ let id = person(&e, "POST", SCAN, None).await["offered"][0]["id"].as_str().unwrap().to_string();+ let racers = (0..6).map(|i| {+ let (app, uri) = (e.app.clone(), format!("{LIST}/{id}/accept"));+ tokio::spawn(async move { call_with(&app, "POST", &uri, None, Some(&format!("race-{i}")), Some(json!({}))).await.0 })+ });+ let mut statuses: Vec<StatusCode> = futures::future::join_all(racers).await.into_iter().map(Result::unwrap).collect();+ statuses.sort();+ assert_eq!(statuses, [StatusCode::CREATED, StatusCode::CONFLICT, StatusCode::CONFLICT, StatusCode::CONFLICT, StatusCode::CONFLICT, StatusCode::CONFLICT]);+ assert_eq!(count(&e, "routines").await, 1);+ assert_eq!(events(&e, &id).await.iter().filter(|e| e.0 == "accepted").count(), 1);+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn six_scans_at_once_make_one_offer_and_one_notification() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ discovery_on(&e).await;+ habit(&e, &a, "Weekly report").await;+ let mut rx = e.state.event_sender.subscribe();+ let racers = (0..6).map(|_| {+ let app = e.app.clone();+ tokio::spawn(async move { call(&app, "POST", SCAN, None, None).await.0 })+ });+ for status in futures::future::join_all(racers).await {+ assert_eq!(status.unwrap(), StatusCode::OK);+ }+ assert_eq!((live(&e).await, count(&e, "routine_suggestions").await), (1, 1));+ assert_eq!(suggested(&mut rx).len(), 1);+}++#[tokio::test]+async fn the_cap_is_a_rolling_day_not_local_midnight() {+ let e = setup().await;+ discovery_on(&e).await;+ for (k, name) in ["Ana", "Ben", "Cleo", "Dan"].iter().enumerate() {+ habit_on(&e, k as i64, name).await;+ }+ let mut rx = e.state.event_sender.subscribe();+ let today = local_date(TZ, Utc::now()).unwrap().unwrap();+ let late = berlin(today, 23, 30);+ assert_eq!(discovery::tick(&e.state, late).await, 2);+ // 00:31, a new local day, and six hours on: still within 24 hours of those two+ let after_midnight = late + Duration::minutes(61);+ assert_eq!(local_date(TZ, after_midnight).unwrap().unwrap(), today.succ_opt().unwrap());+ assert_eq!(discovery::tick(&e.state, after_midnight).await, 0);+ assert_eq!(discovery::tick(&e.state, late + Duration::hours(6)).await, 0);+ assert_eq!((live(&e).await, suggested(&mut rx).len()), (2, 2));+ assert_eq!(discovery::tick(&e.state, late + Duration::hours(24) + Duration::minutes(1)).await, 2);+ assert_eq!(live(&e).await, 4);+}++#[tokio::test]+async fn a_bot_cannot_mark_a_routine_discovered() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ discovery_on(&e).await;+ habit(&e, &a, "Weekly report").await;+ let sid = person(&e, "POST", SCAN, None).await["offered"][0]["id"].as_str().unwrap().to_string();+ let t = token(&e, &a).await;+ let schedule = json!({"type": "weekly", "time": "09:00", "weekdays": ["mon"], "tz": TZ});+ let args = json!({"name": "Mine", "instructions": "Do it", "schedule": schedule, "origin": "discovery", "suggestion_id": sid});+ let _ = tool(&e, &t, "routine_create", args).await;+ let routines = person(&e, "GET", "/api/routines", None).await;+ for r in routines.as_array().unwrap() {+ let _ = tool(&e, &t, "routine_update", json!({"routine": r["id"], "origin": "discovery", "suggestion_id": sid})).await;+ }+ let linked: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM routines WHERE origin IS NOT NULL OR suggestion_id IS NOT NULL").fetch_one(&e.pool).await.unwrap();+ assert_eq!(linked.0, 0);+ assert_eq!(e.state.db.get_suggestion(&sid).await.unwrap().unwrap().status, "offered");+}++#[tokio::test]+async fn with_the_notification_off_the_offer_is_kept_quietly() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ discovery_on(&e).await;+ person(&e, "POST", "/api/settings", Some(json!({"notify_on": ["turn_finished"]}))).await;+ habit(&e, &a, "Weekly report").await;+ let mut rx = e.state.event_sender.subscribe();+ let v = person(&e, "POST", SCAN, None).await;+ assert_eq!(titles(&v, "offered"), ["Weekly report"]);+ assert_eq!(live(&e).await, 1);+ assert!(suggested(&mut rx).is_empty());+}++#[tokio::test]+async fn keep_checks_saves_the_real_spec_not_the_mask() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ discovery_on(&e).await;+ habit(&e, &a, "Weekly report").await;+ let secret = "sk-live0123456789abcdef/weekly.md";+ sqlx::query("UPDATE outcome_checks SET spec = ?").bind(json!({"path": secret}).to_string()).execute(&e.pool).await.unwrap();+ let v = person(&e, "POST", SCAN, None).await;+ let o = &v["offered"][0];+ assert_eq!(o["checks"][0]["spec"]["path"], "[redacted]", "shown masked: {o}");+ let id = o["id"].as_str().unwrap();+ let (status, _, v) = accept(&e, id, "k1", json!({"keep_checks": [0]})).await;+ assert_eq!(status, StatusCode::CREATED, "{v}");+ let rid = v["routine"]["id"].as_str().unwrap();+ let (checks,): (String,) = sqlx::query_as("SELECT checks FROM routines WHERE id = ?").bind(rid).fetch_one(&e.pool).await.unwrap();+ assert!(checks.contains(secret) && !checks.contains("[redacted]"), "{checks}");+}