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 step 3: offers, Accept, Dismiss, hourly scan
Lin (kwant bot)a7b91b31d0c1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5b089c1d..0d30abb2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).mostly verified, mostly done by one bot and not already covered by a routine, on or off, qualify.Tasks made by bots, routines, hand-offs or chats never count. The scan is a preview: it creates nooffer and no routine yet. This is step 2 of Automation Discovery.+- **Automation Discovery suggests routines you can accept or dismiss.** With it on, each space is+ scanned once an hour (or when you ask) and new suggestions are kept, at most 2 a day (you can change+ that) and 5 waiting per space, each with one notification. A suggestion shows its schedule, first+ 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 being+ suggested 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+ suggested 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 come+ next.### Changed- **kwant.si footer says "Made in Germany with ❤️".** The line sits under the trademark note on everydiff --git a/docs/mission-control.md b/docs/mission-control.mdindex c4688291..12e0ef24 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -870,8 +870,9 @@ tool.## 20. Automation Discovery (Phase D4)Design note: `phase-d/automation-discovery.md`. v1 learns only from board tasks the person created.-**Build step 1 (shipped): what a routine's runs are held to. Step 2: the miner and a read-only scan.**-Offers, Accept and Dismiss come in step 3.+**Build step 1 (shipped): what a routine's runs are held to. Step 2 (shipped): the miner and a+read-only scan. Step 3: offers that are kept, Accept, Dismiss, the hourly scan.** The screens come in+step 4.**Routine outcomes.** Every routine can carry, besides its instructions:- `task_class`: the Flight School class of each run's task (§14). `null`, `""` or `general` clear it.@@ -922,12 +923,78 @@ now and at least half a period after the last ask. Checks that passed with the sasks are kept (≤ 10); `person`/`peer_review` checks, ones whose spec changes every time and ones thatpassed once are listed as left out.-**Scan** (`POST /api/automation-discovery/scan?space=`, person only): `{blocked_by, preview: true,-timezone, offered, skipped: [{cluster_key, title, asks, reason}]}`. `blocked_by` is `off`, `board_off` or-`no_timezone` (none set, or one this machine can't read), with empty lists; with the setting off nothing-is read. It writes nothing: no offer, no event, no routine. A thread or channel that no longer fits-falls back to the bot's direct chat, and check specs are shown with secrets masked. Settings:-`automation_discovery` `off` (default) or `on`, `automation_discovery_daily_cap` 0–10 (default 2).+**Settings:** `automation_discovery` `off` (default) or `on`, `automation_discovery_daily_cap` 0–10+(default 2; anything else, a non-number too, is refused). Every `/api/automation-discovery` route is the+person's only: a bot's token gets 403. Nothing is created without Accept.++**Scan** (`POST /api/automation-discovery/scan?space=`): scans now (ignoring the hourly wait, not the+cap) and keeps what it finds. `{blocked_by: null, preview: false, timezone, offered: [suggestion],+skipped: [{cluster_key, title, asks, reason}], expired: [id], superseded: [id]}`. `blocked_by` is `off`,+`board_off` or `no_timezone` (none set, or one this machine can't read), with empty lists; with the+setting off nothing is read or written. `?preview=1` is step 2's preview: `{blocked_by, preview: true,+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 habit+still 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+notification. 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+a channel of another space, falls back to the bot's direct chat. Checks a routine may not carry are+moved to the left-out list.++**The hourly scan.** While the setting is on, the board is on and a time zone is set, every non-archived+space is scanned once an hour (the loop wakes every 10 minutes and reads+`automation_discovery_last_scan`). It writes nothing otherwise. Each new offer sends one notification,+kind `automation_suggested` ("Suggested routine: <name>", "<bot> could do this on a schedule. Accept or+dismiss it in Routines."), with no chat text; it can be turned off like any kind and is not a Needs-you+item. Lists saved before the kind existed count it as on.++**List** (`GET /api/automation-discovery?space=&status=`): `{setting: "on"|"off", daily_cap, blocked_by:+[every reason, empty when scans run], last_scan_at, suggestions: [suggestion], stats: {offered_30d,+accepted_30d, dismissed_30d, retained, dropped}}`. `status` is `offered` (default), `accepted`,+`dismissed`, `expired`, `superseded` or `all`, newest first; anything else is 400. While scans can't run,+live offers are hidden.++A **suggestion**: `{id, space_id, cluster_key, kwant_id, name, instructions, schedule, schedule_text,+first_run_at, first_run_text, delivery: {channel_id?|thread_id?|direct_kwant_id?}, task_class,+acceptance, checks: [{kind, spec, required}], left_out_checks: [{kind, spec, reason}], chain,+source_task_ids, sources: [{id, title, created_at, state}], time_spread, evidence, permissions, status,+routine_id, cooldown_until, routine_deleted_at, retention, retention_at, offered_at, decided_at}`. Check+specs are shown with secrets masked. A live offer's first run is recomputed whenever it is shown: the+next slot after now and at least half a period after the last ask. Once accepted, it is the routine's+first run.++`permissions` previews what the bot may do when the routine runs; Accept grants nothing: `{flight_school,+tier: observe|sandbox|act, tier_from: class|any_class|default|off, tier_label, approval_mode:+ask|smart|off, payments_ask: true, past: {external, workspace, needed_ok}}`. `past` counts the tool calls+of the source tasks' turns that changed something outside or in the workspace, and those the person+approved.++**Accept** (`POST /api/automation-discovery/:id/accept`, `Idempotency-Key` required, else 400). Body,+all optional: `{name, instructions, schedule, kwant_id, channel_id, thread_id, acceptance,+keep_checks: [index]}`; unknown fields are 400. Checks can be dropped (`keep_checks`, out of range: 422),+not added. Another bot must be in the suggestion's space; a thread or direct chat belongs to the+suggested bot, so another bot delivers to its own direct chat unless told otherwise. The routine is+built and checked like `POST /api/routines`, then gets `origin: "discovery"`, the `suggestion_id` and+the first run recomputed for now. The status change, the routine and the `accepted` event are one+transaction. 201 `{suggestion, routine, first_run_text}`; the same key replays it+(`idempotent-replayed: true`). Once the offer isn't live: 409 `{error, status, routine_id}`. A `?space=`+naming another space: 404.++**Dismiss** (`POST /api/automation-discovery/:id/dismiss`): 200 `{suggestion}`, with `cooldown_until`+30 days on; the habit is `cooling_off` until then. 409 as for Accept.++**After Accept.** Turning the routine off or on appends `disabled`/`enabled` (actor `person` or+`kwant`); deleting it sets `routine_deleted_at`, appends `deleted` and cools the habit off for 30 days.+An undone delete makes the new routine the suggestion's again (`origin`, `suggestion_id`, and the+suggestion's `routine_id`), so the habit is covered again. 14 days after Accept, each scan's retention+pass marks the suggestion `retained` (its routine exists and is on) or `dropped`, once, with an event;+it runs every 10 minutes whatever the setting says now.++**Export.** A bundle's routines carry `task_class` and `acceptance`, and `checks` only when no spec+holds anything that looks like a secret. An import brings the class and the acceptance; checks are+never applied (the person approves checks), and the preview says so.**Storage** (add-only, idempotent): `routines` gains nullable `origin` (`discovery` for an acceptedoffer), `suggestion_id`, `task_class`, `acceptance` and `checks` (JSON). `routine_suggestions` holdsdiff --git a/src/automation_discovery.rs b/src/automation_discovery.rsindex 2876ee83..c7b6a21e 100644--- a/src/automation_discovery.rs+++ b/src/automation_discovery.rs@@ -5,7 +5,7 @@//! mission-control/phase-d/automation-discovery.md §4–§5; contract: docs/mission-control.md §20.use crate::routines::{now_in, run_time_text, MonthDay, Schedule};-use chrono::{DateTime, Datelike, Duration, NaiveDate, Timelike, Utc, Weekday};+use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveTime, Timelike, Utc, Weekday};use serde::Serialize;use serde_json::Value;use sha2::{Digest, Sha256};@@ -41,6 +41,8 @@ pub const CHAIN_MAX_SOURCES: usize = 20;pub const CHAIN_HOURS: i64 = 24;/// What a routine may carry (as `POST /api/routines` allows).pub const MAX_CHECKS: usize = 10;+/// How far a habit's usual time must move before its live offer is replaced.+pub const SUPERSEDE_MINUTES: i64 = 30;const NAME_CHARS: usize = 80;const SOURCES_IN_INSTRUCTIONS: usize = 5;@@ -229,7 +231,7 @@ pub struct Skip {}/// Where the routine would post.-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, serde::Deserialize)]pub struct Delivery {#[serde(skip_serializing_if = "Option::is_none")]pub channel_id: Option<String>,@@ -287,6 +289,8 @@ pub struct Evidence {pub total: usize,pub time_spread: String,pub time_varies: bool,+ /// The newest matched ask: Accept recomputes the first run from it (design §5).+ pub last_ask_at: DateTime<Utc>,}/// A routine the miner would suggest. Nothing here is stored or created by the miner.@@ -314,6 +318,11 @@ pub struct Offer {pub struct Scan {pub offered: Vec<Offer>,pub skipped: Vec<Skip>,+ /// Habits that already have a live offer and still pass, as they would be offered now: the+ /// caller keeps, or replaces, the live offer with these and expires the rest (design §6).+ /// Each is also in `skipped` as `already_offered`.+ #[serde(skip)]+ pub live: Vec<Offer>,}// Cadence@@ -794,6 +803,7 @@ pub fn mine(input: &Input) -> Scan {}let mut passing: Vec<Offer> = Vec::new();let mut skipped: Vec<Skip> = Vec::new();+ let mut live: Vec<Offer> = Vec::new();for c in &mut clusters {c.tasks.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));let days = days_of(c, input.tz);@@ -835,9 +845,9 @@ pub fn mine(input: &Input) -> Scan {skipped.push(skip(Reason::CoolingOff));continue;}- if input.past.live.contains(&c.key) {+ let is_live = input.past.live.contains(&c.key);+ if is_live {skipped.push(skip(Reason::AlreadyOffered));- continue;}let minutes: Vec<u32> = cadence.matched.iter().map(|&i| days[i].minutes).collect();@@ -867,7 +877,7 @@ pub fn mine(input: &Input) -> Scan {(None, Some(channel)) => Delivery { channel_id: Some(channel), ..Default::default() },(None, None) => Delivery { direct_kwant_id: Some(bot.clone()), ..Default::default() },};- passing.push(Offer {+ let offer = Offer {cluster_key: c.key.clone(),instructions: instructions(&name, &acceptance, &chain, &sources),first_run_text: run_time_text(first_run_at, schedule.tz()),@@ -893,9 +903,15 @@ pub fn mine(input: &Input) -> Scan {total: days.len(),time_spread: if lo == hi { hhmm(lo) } else { format!("{}–{}", hhmm(lo), hhmm(hi)) },time_varies: hi - lo > TIME_VARIES_MINUTES,+ last_ask_at: last_ask,},sources,- });+ };+ if is_live {+ live.push(offer);+ } else {+ passing.push(offer);+ }}// A follow-up written into another offer's steps isn't offered on its own@@ -915,14 +931,33 @@ pub fn mine(input: &Input) -> Scan {let capped = passing.split_off(room.min(passing.len()));skipped.extend(capped.into_iter().map(|o| Skip { title: o.name.clone(), asks: o.evidence.total, cluster_key: o.cluster_key, reason: Reason::Capped }));skipped.sort_by(|a, b| a.cluster_key.cmp(&b.cluster_key));- Scan { offered: passing, skipped }+ Scan { offered: passing, skipped, live }+}++/// Whether a live offer (`schedule`, `kwant_id`) no longer says what the habit is now, so a scan+/// replaces it: another rhythm, days, zone or bot, or a usual time moved by at least+/// [`SUPERSEDE_MINUTES`]. Smaller drifts of the median keep the offer, so it doesn't churn.+pub fn materially_changed(schedule: &Schedule, kwant_id: &str, now: &Offer) -> bool {+ if kwant_id != now.kwant_id {+ return true;+ }+ let minutes = |t: &str| NaiveTime::parse_from_str(t, "%H:%M").ok().map(|t| i64::from(t.hour() * 60 + t.minute()));+ let moved = |a: &str, b: &str| match (minutes(a), minutes(b)) {+ (Some(a), Some(b)) => (a - b).abs() >= SUPERSEDE_MINUTES,+ _ => a != b,+ };+ match (schedule, &now.schedule) {+ (Schedule::Daily { time: a, tz: x }, Schedule::Daily { time: b, tz: y }) => x != y || moved(a, b),+ (Schedule::Weekly { time: a, weekdays: d, tz: x }, Schedule::Weekly { time: b, weekdays: e, tz: y }) => d != e || x != y || moved(a, b),+ (Schedule::Monthly { time: a, days: d, tz: x }, Schedule::Monthly { time: b, days: e, tz: y }) => d != e || x != y || moved(a, b),+ _ => true,+ }}#[cfg(test)]mod tests {use super::*;use crate::routines::local_instant;- use chrono::NaiveTime;const BERLIN: &str = "Europe/Berlin";@@ -1168,6 +1203,38 @@ mod tests {assert_eq!((d.pattern, d.month_day, d.matched.clone()), (Pattern::Monthly, Some(MonthDay::Day(3)), vec![1, 2, 3, 4]));}+ #[test]+ fn a_habit_on_the_31st_takes_a_30_day_months_last_day() {+ // September has no 31st: asking on the 30th is the same habit, so it runs on the last day+ let dates = ["2026-07-31", "2026-08-31", "2026-09-30"].map(date);+ let tasks = asks(BERLIN, "m", "Pay rent", &dates, "09:00");+ let o = Fx::new(BERLIN, at(BERLIN, date("2026-10-05"), "10:00"), tasks).only_offer();+ assert_eq!(o.schedule, Schedule::Monthly { time: "09:00".into(), days: vec![MonthDay::Last], tz: BERLIN.into() });+ assert_eq!(o.first_run_at, at(BERLIN, date("2026-10-31"), "09:00"));+ // A habit on the 30th is not one on the last day+ let dates = ["2026-07-30", "2026-08-30", "2026-09-30"].map(date);+ let tasks = asks(BERLIN, "m", "Pay rent", &dates, "09:00");+ let o = Fx::new(BERLIN, at(BERLIN, date("2026-10-05"), "10:00"), tasks).only_offer();+ assert_eq!(o.schedule, Schedule::Monthly { time: "09:00".into(), days: vec![MonthDay::Day(30)], tz: BERLIN.into() });+ assert_eq!(o.first_run_at, at(BERLIN, date("2026-10-30"), "09:00"));+ }++ #[test]+ fn the_60_and_120_day_windows_end_where_they_say() {+ // Weekly: an ask 59 days back counts, one 60 days back doesn't+ let mondays = every("2026-08-24", 7, 9);+ let d = detect(&days(&mondays), date("2026-10-22")).unwrap();+ assert_eq!((d.pattern, d.matched.first()), (Pattern::Weekly, Some(&0)));+ let d = detect(&days(&mondays), date("2026-10-23")).unwrap();+ assert_eq!((d.pattern, d.matched.first(), d.matched.len()), (Pattern::Weekly, Some(&1), 8));+ // Monthly: 119 days back counts, 120 doesn't+ let thirds = ["2026-06-03", "2026-07-03", "2026-08-03", "2026-09-03"].map(date);+ let d = detect(&days(&thirds), date("2026-09-30")).unwrap();+ assert_eq!((d.pattern, d.matched.clone()), (Pattern::Monthly, vec![0, 1, 2, 3]));+ let d = detect(&days(&thirds), date("2026-10-01")).unwrap();+ assert_eq!((d.pattern, d.matched.clone()), (Pattern::Monthly, vec![1, 2, 3]));+ }+// Near-misses at each tolerance edge#[test]@@ -1398,8 +1465,32 @@ mod tests {let mut fx = Fx::new(BERLIN, after_weekly(), weekly("d", "Weekly report"));fx.past.cooling.insert(key.clone());assert_eq!(fx.only_skip(), Reason::CoolingOff);- fx.past = Past { live: HashSet::from([key]), live_count: 1, ..Past::default() };+ fx.past = Past { live: HashSet::from([key.clone()]), live_count: 1, ..Past::default() };assert_eq!(fx.only_skip(), Reason::AlreadyOffered);+ // Still passing, so the caller keeps the live offer; it is not offered again+ let scan = fx.scan();+ assert_eq!(scan.live.len(), 1);+ assert_eq!(scan.live[0].cluster_key, key);+ assert_eq!(scan.live[0].evidence.last_ask_at, at(BERLIN, date("2026-10-12"), "09:00"));+ // Cooling wins over live, so a live offer of a cooled habit isn't in `live` (it expires)+ fx.past.cooling.insert(key);+ assert!(fx.scan().live.is_empty());+ }++ #[test]+ fn a_live_offer_is_replaced_only_for_a_real_change() {+ let fx = Fx::new(BERLIN, after_weekly(), weekly("m", "Weekly report"));+ let now = fx.only_offer();+ let weekly_at = |time: &str, days: &[&str], tz: &str| Schedule::Weekly { time: time.into(), weekdays: days.iter().map(|d| d.to_string()).collect(), tz: tz.into() };+ assert!(!materially_changed(&now.schedule, "bot-a", &now));+ // The median drifting under half an hour keeps the offer+ assert!(!materially_changed(&weekly_at("09:15", &["mon"], BERLIN), "bot-a", &now));+ assert!(!materially_changed(&weekly_at("08:31", &["mon"], BERLIN), "bot-a", &now));+ assert!(materially_changed(&weekly_at("09:30", &["mon"], BERLIN), "bot-a", &now));+ assert!(materially_changed(&weekly_at("09:00", &["mon", "thu"], BERLIN), "bot-a", &now));+ assert!(materially_changed(&weekly_at("09:00", &["mon"], "America/New_York"), "bot-a", &now));+ assert!(materially_changed(&Schedule::Daily { time: "09:00".into(), tz: BERLIN.into() }, "bot-a", &now));+ assert!(materially_changed(&now.schedule, "bot-b", &now));}#[test]@@ -1560,6 +1651,23 @@ mod tests {assert_eq!(first_run_at(&w, monday, monday + Duration::hours(1)), Some(at(BERLIN, date("2026-10-12"), "09:00")));}+ #[test]+ fn first_run_is_recomputed_when_accepted_days_later() {+ // Offered on Monday 10:00 after that Monday's 09:00 ask: the stored first run is next Monday+ let w = Schedule::Weekly { time: "09:00".into(), weekdays: vec!["mon".into()], tz: BERLIN.into() };+ let asked = at(BERLIN, date("2026-10-12"), "09:00");+ let stored = first_run_at(&w, asked, at(BERLIN, date("2026-10-12"), "10:00")).unwrap();+ assert_eq!(stored, at(BERLIN, date("2026-10-19"), "09:00"));+ // Accepted the Wednesday after that Monday: the following Monday, not the stale one+ let wednesday = at(BERLIN, date("2026-10-21"), "11:00");+ assert_eq!(first_run_at(&w, asked, wednesday), Some(at(BERLIN, date("2026-10-26"), "09:00")));+ // Edited to Thursdays: the next Thursday+ let thu = Schedule::Weekly { time: "09:00".into(), weekdays: vec!["thu".into()], tz: BERLIN.into() };+ assert_eq!(first_run_at(&thu, asked, wednesday), Some(at(BERLIN, date("2026-10-22"), "09:00")));+ // Across the 25 October DST change it stays 09:00 local+ assert_eq!(first_run_at(&w, asked, at(BERLIN, date("2026-10-20"), "08:00")), Some(at(BERLIN, date("2026-10-26"), "09:00")));+ }+#[test]fn an_unreadable_time_zone_finds_nothing() {let fx = Fx { tz: "Mars/Olympus", ..Fx::new(BERLIN, after_weekly(), weekly("z", "Weekly report")) };diff --git a/src/db/automation.rs b/src/db/automation.rsindex 946ea60f..cee639e2 100644--- a/src/db/automation.rs+++ b/src/db/automation.rs@@ -3,11 +3,112 @@//! each run's task. Add-only: older binaries ignore all of it, and running it twice changes//! nothing. See docs/mission-control.md §20.+use super::continuity::{insert_routine, NewRoutine, RoutineRow};use super::{Database, DbError};-use crate::automation_discovery::{self as miner, PassedCheck, Past, RoutineRef, TaskRow};+use crate::automation_discovery::{self as miner, Offer, PassedCheck, Past, RoutineRef, TaskRow};use chrono::{DateTime, Duration, Utc};-use serde_json::Value;+use serde_json::{json, Value};+use sqlx::{FromRow, SqliteConnection};use std::collections::HashSet;+use uuid::Uuid;++/// An accepted suggestion's routine counts as kept (`retained`) or not (`dropped`) this long after+/// Accept (design §10).+pub const RETENTION_DAYS: i64 = 14;++/// One stored offer, as `routine_suggestions` holds it (JSON columns as text).+#[derive(Debug, Clone, FromRow)]+pub struct SuggestionRow {+ pub id: String,+ pub space_id: String,+ pub cluster_key: String,+ pub kwant_id: String,+ pub name: String,+ pub instructions: String,+ pub schedule: String,+ pub first_run_at: DateTime<Utc>,+ pub delivery: String,+ pub task_class: String,+ pub acceptance: String,+ pub checks: String,+ pub left_out_checks: String,+ pub chain: String,+ pub source_task_ids: String,+ pub evidence: String,+ pub status: String,+ pub routine_id: Option<String>,+ pub cooldown_until: Option<DateTime<Utc>>,+ pub routine_deleted_at: Option<DateTime<Utc>>,+ pub retention: Option<String>,+ pub retention_at: Option<DateTime<Utc>>,+ pub offered_at: DateTime<Utc>,+ pub decided_at: Option<DateTime<Utc>>,+}++/// What Accept or Dismiss did.+#[derive(Debug)]+pub enum Decided {+ /// Done: the suggestion now, and for Accept the routine it made.+ Done(Box<SuggestionRow>, Option<Box<RoutineRow>>),+ /// It wasn't a live offer any more: as it is now.+ NotOffered(Box<SuggestionRow>),+ /// No such suggestion in the space.+ Missing,+}++/// Counts for Insights (design §10).+#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]+pub struct SuggestionStats {+ pub offered_30d: i64,+ pub accepted_30d: i64,+ pub dismissed_30d: i64,+ pub retained: i64,+ pub dropped: i64,+}++/// What the source tasks' turns did (design §5): tool calls with an outside effect, with a+/// workspace effect, and how many of them the person had to approve.+#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]+pub struct PastTools {+ pub external: i64,+ pub workspace: i64,+ pub needed_ok: i64,+}++const SUGGESTION_SELECT: &str = "SELECT 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, routine_id, cooldown_until,+ routine_deleted_at, retention, retention_at, offered_at, decided_at FROM routine_suggestions";++fn text<T: serde::Serialize + ?Sized>(v: &T) -> String {+ serde_json::to_string(v).unwrap_or_default()+}++/// Appends to a suggestion's history.+async fn event(conn: &mut SqliteConnection, suggestion: &str, kind: &str, actor: &str, detail: Value, now: DateTime<Utc>) -> Result<(), DbError> {+ sqlx::query("INSERT INTO routine_suggestion_events (suggestion_id, kind, actor, detail, created_at) VALUES (?, ?, ?, ?, ?)")+ .bind(suggestion)+ .bind(kind)+ .bind(actor)+ .bind(detail.to_string())+ .bind(now)+ .execute(conn)+ .await?;+ Ok(())+}++/// In the transaction that deletes routine `routine`: when it was discovered, its suggestion+/// notes the delete (so its habit cools off for 30 days) and the history gets `deleted`.+pub(super) async fn routine_deleted(conn: &mut SqliteConnection, routine: &str, now: DateTime<Utc>) -> Result<(), DbError> {+ let ids: Vec<(String,)> = sqlx::query_as("UPDATE routine_suggestions SET routine_deleted_at = ? WHERE routine_id = ? AND routine_deleted_at IS NULL RETURNING id")+ .bind(now)+ .bind(routine)+ .fetch_all(&mut *conn)+ .await?;+ for (id,) in ids {+ event(conn, &id, "deleted", "kwant", json!({ "routine_id": routine }), now).await?;+ }+ Ok(())+}/// Routine columns this migration adds, all nullable: a routine without them runs as before./// `origin` is `NULL` (made by hand or by a bot) or `discovery`; `checks` is JSON@@ -180,4 +281,244 @@ impl Database {offered_24h: usize::try_from(offered_24h).unwrap_or(0),})}++ /// Stores `offer` (its delivery and checks as they should be kept, specs unmasked) as a live+ /// offer of `space`, unless the habit already has one or the space is at its limits: fewer+ /// than `max_live` live offers and fewer than `daily_cap` offered in the last 24 hours. One+ /// statement checks and inserts, so racing scans can't pass a limit or make two. The id, when+ /// stored.+ pub async fn store_offer(&self, space: &str, offer: &Offer, now: DateTime<Utc>, daily_cap: i64, max_live: usize) -> 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?;+ let res = 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)+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, 'offered', ?17+ WHERE (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",+ )+ .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(now)+ .bind(i64::try_from(max_live).unwrap_or(i64::MAX))+ .bind(now - Duration::hours(24))+ .bind(daily_cap)+ .execute(&mut *tx)+ .await?;+ if res.rows_affected() == 0 {+ tx.rollback().await?;+ return Ok(None);+ }+ event(&mut tx, &id, "offered", "kwant", json!({ "cluster_key": offer.cluster_key }), 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?)+ }++ /// The space's suggestions, newest first; `status` filters (`None`: all).+ pub async fn list_suggestions(&self, space: &str, status: Option<&str>) -> Result<Vec<SuggestionRow>, DbError> {+ Ok(sqlx::query_as::<_, SuggestionRow>(&format!(+ "{SUGGESTION_SELECT} WHERE space_id = ?1 AND (?2 IS NULL OR status = ?2) ORDER BY offered_at DESC, id"+ ))+ .bind(space)+ .bind(status)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Ends live offer `id` as `expired` or `superseded` (a scan found its habit gone or+ /// changed). False when it wasn't live.+ pub async fn end_offer(&self, id: &str, kind: &str, now: DateTime<Utc>) -> Result<bool, DbError> {+ let mut tx = self.pool.begin().await?;+ let res = sqlx::query("UPDATE routine_suggestions SET status = ?, decided_at = ? WHERE id = ? AND status = 'offered'")+ .bind(kind)+ .bind(now)+ .bind(id)+ .execute(&mut *tx)+ .await?;+ if res.rows_affected() == 0 {+ tx.rollback().await?;+ return Ok(false);+ }+ event(&mut tx, id, kind, "kwant", json!({}), now).await?;+ tx.commit().await?;+ Ok(true)+ }++ /// The decision made on a suggestion that is no longer live, or that isn't in `space`.+ async fn not_offered(&self, id: &str, space: &str) -> Result<Decided, DbError> {+ Ok(match self.get_suggestion(id).await? {+ Some(s) if s.space_id == space => Decided::NotOffered(Box::new(s)),+ _ => Decided::Missing,+ })+ }++ /// Accept (design §6): in one transaction the live offer becomes `accepted`, `routine` (built+ /// and validated by the caller, `origin` and `suggestion_id` set) is created and linked, and+ /// the history gets `accepted`. Either all of it happens or none.+ pub async fn accept_suggestion(&self, id: &str, space: &str, routine: &NewRoutine, now: DateTime<Utc>) -> Result<Decided, DbError> {+ let routine_space = self.routine_space(routine).await?;+ if routine_space.as_str() != space {+ return Err(DbError::OtherSpace("the bot is in another space".into()));+ }+ let routine_id = Uuid::new_v4().to_string();+ let mut tx = self.pool.begin().await?;+ // A write first, so the transaction holds the lock from its first statement. From here on+ // the suggestion's first run is the routine's+ let res = sqlx::query(+ "UPDATE routine_suggestions SET status = 'accepted', decided_at = ?, routine_id = ?, first_run_at = COALESCE(?, first_run_at)+ WHERE id = ? AND space_id = ? AND status = 'offered'",+ )+ .bind(now)+ .bind(&routine_id)+ .bind(routine.next_run_at)+ .bind(id)+ .bind(space)+ .execute(&mut *tx)+ .await?;+ if res.rows_affected() == 0 {+ tx.rollback().await?;+ return self.not_offered(id, space).await;+ }+ insert_routine(&mut tx, &routine_id, &routine_space, routine).await?;+ event(&mut tx, id, "accepted", "person", json!({ "routine_id": routine_id }), now).await?;+ tx.commit().await?;+ let s = self.get_suggestion(id).await?.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))?;+ let r = self.get_routine(&routine_id).await?.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))?;+ Ok(Decided::Done(Box::new(s), Some(Box::new(r))))+ }++ /// Dismiss (design §6): the habit isn't offered again for [`miner::DISMISS_COOL_OFF_DAYS`].+ pub async fn dismiss_suggestion(&self, id: &str, space: &str, now: DateTime<Utc>) -> Result<Decided, DbError> {+ let until = now + Duration::days(miner::DISMISS_COOL_OFF_DAYS);+ let mut tx = self.pool.begin().await?;+ let res = sqlx::query(+ "UPDATE routine_suggestions SET status = 'dismissed', decided_at = ?, cooldown_until = ? WHERE id = ? AND space_id = ? AND status = 'offered'",+ )+ .bind(now)+ .bind(until)+ .bind(id)+ .bind(space)+ .execute(&mut *tx)+ .await?;+ if res.rows_affected() == 0 {+ tx.rollback().await?;+ return self.not_offered(id, space).await;+ }+ event(&mut tx, id, "dismissed", "person", json!({ "cooldown_until": until }), now).await?;+ tx.commit().await?;+ let s = self.get_suggestion(id).await?.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))?;+ Ok(Decided::Done(Box::new(s), None))+ }++ /// A discovered routine switched on or off (design §8): `enabled` or `disabled` in its+ /// suggestion's history.+ pub async fn suggestion_switched(&self, suggestion: &str, enabled: bool, actor: &str) -> Result<(), DbError> {+ let mut conn = self.pool.acquire().await?;+ event(&mut conn, suggestion, if enabled { "enabled" } else { "disabled" }, actor, json!({}), Utc::now()).await+ }++ /// An undone delete of a discovered routine: the new routine `routine` is again the one+ /// accepted from `suggestion`, so it keeps "Suggested by kwant" and its habit stops cooling+ /// off. Only for that suggestion's accepted, space-matching link, and only while no other+ /// routine holds it. False when nothing was linked.+ pub async fn relink_discovered(&self, routine: &str, suggestion: &str) -> Result<bool, DbError> {+ let mut tx = self.pool.begin().await?;+ let res = sqlx::query(+ "UPDATE routines SET origin = 'discovery', suggestion_id = ?1 WHERE id = ?2+ AND EXISTS (SELECT 1 FROM routine_suggestions s WHERE s.id = ?1 AND s.status = 'accepted' AND s.space_id = routines.space_id)+ AND NOT EXISTS (SELECT 1 FROM routines o WHERE o.suggestion_id = ?1 AND o.id <> ?2)",+ )+ .bind(suggestion)+ .bind(routine)+ .execute(&mut *tx)+ .await?;+ if res.rows_affected() == 0 {+ tx.rollback().await?;+ return Ok(false);+ }+ sqlx::query("UPDATE routine_suggestions SET routine_id = ?, routine_deleted_at = NULL WHERE id = ?")+ .bind(routine)+ .bind(suggestion)+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ Ok(true)+ }++ /// The daily retention pass (design §10), for every space: accepted suggestions decided at+ /// least [`RETENTION_DAYS`] ago get `retained` if their routine exists and is on now, else+ /// `dropped`. Written once, never recomputed. How many it marked.+ pub async fn mark_retention(&self, now: DateTime<Utc>) -> Result<usize, DbError> {+ let mut tx = self.pool.begin().await?;+ let marked: Vec<(String, String)> = sqlx::query_as(+ "UPDATE routine_suggestions SET retention = CASE WHEN EXISTS+ (SELECT 1 FROM routines r WHERE r.id = routine_suggestions.routine_id AND r.enabled) THEN 'retained' ELSE 'dropped' END,+ retention_at = ?1+ WHERE status = 'accepted' AND retention IS NULL AND decided_at <= ?2+ RETURNING id, retention",+ )+ .bind(now)+ .bind(now - Duration::days(RETENTION_DAYS))+ .fetch_all(&mut *tx)+ .await?;+ for (id, retention) in &marked {+ event(&mut tx, id, retention, "kwant", json!({}), now).await?;+ }+ tx.commit().await?;+ Ok(marked.len())+ }++ 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),+ 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",+ )+ .bind(space)+ .bind(since)+ .fetch_one(&self.pool)+ .await?;+ Ok(SuggestionStats { offered_30d, accepted_30d, dismissed_30d, retained, dropped })+ }++ /// What the turns of `tasks` did (design §5), from `turn_tool_calls`.+ pub async fn past_tools(&self, tasks: &[String]) -> Result<PastTools, DbError> {+ if tasks.is_empty() {+ return Ok(PastTools::default());+ }+ let list = serde_json::to_string(tasks).unwrap_or_default();+ let (external, workspace, needed_ok): (i64, i64, i64) = sqlx::query_as(+ "SELECT COALESCE(SUM(effect = 'external'), 0), COALESCE(SUM(effect = 'workspace'), 0), COALESCE(SUM(decision = 'approved'), 0)+ FROM turn_tool_calls WHERE task_id IN (SELECT value FROM json_each(?))",+ )+ .bind(list)+ .fetch_one(&self.pool)+ .await?;+ Ok(PastTools { external, workspace, needed_ok })+ }}diff --git a/src/db/continuity.rs b/src/db/continuity.rsindex 37dc8a1f..143822ec 100644--- a/src/db/continuity.rs+++ b/src/db/continuity.rs@@ -713,37 +713,16 @@ impl Database {pub async fn create_routine(&self, input: &NewRoutine) -> Result<RoutineRow, DbError> {let space = self.routine_space(input).await?;let id = Uuid::new_v4().to_string();- sqlx::query(- "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at, space_id, \- thread_id, context_message_id, origin, suggestion_id, task_class, acceptance, checks) \- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",- )- .bind(&id)- .bind(&input.kwant_id)- .bind(&input.channel_id)- .bind(&input.name)- .bind(&input.instructions)- .bind(&input.schedule)- .bind(input.enabled)- .bind(input.next_run_at)- .bind(Utc::now())- .bind(space.as_str())- .bind(&input.thread_id)- .bind(&input.context_message_id)- .bind(&input.origin)- .bind(&input.suggestion_id)- .bind(&input.task_class)- .bind(&input.acceptance)- .bind(&input.checks)- .execute(&self.pool)- .await?;+ let mut conn = self.pool.acquire().await?;+ insert_routine(&mut conn, &id, &space, input).await?;+ drop(conn);self.get_routine(&id).await?.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))}/// The kwant (and channel, when set) a routine runs as must share a space.- async fn routine_space(&self, input: &NewRoutine) -> Result<SpaceId, DbError> {+ pub(super) async fn routine_space(&self, input: &NewRoutine) -> Result<SpaceId, DbError> {let other = || DbError::OtherSpace("the bot and channel must be in the same space".into());let space = self.space_of_kwant(&input.kwant_id).await?.ok_or_else(other)?;if let Some(channel) = &input.channel_id {@@ -798,6 +777,10 @@ impl Database {.bind(id).execute(&mut *tx).await?;+ if res.rows_affected() > 0 {+ // A discovered routine's habit isn't offered again for 30 days+ super::automation::routine_deleted(&mut tx, id, Utc::now()).await?;+ }tx.commit().await?;Ok(res.rows_affected() > 0)}@@ -990,6 +973,35 @@ async fn pinned_count(tx: &mut sqlx::Transaction<'_, Sqlite>, kwant_id: &str) ->Ok(n)}+/// Inserts a routine as `id` in `space`, which [`Database::routine_space`] checked.+pub(super) async fn insert_routine(conn: &mut sqlx::SqliteConnection, id: &str, space: &SpaceId, input: &NewRoutine) -> Result<(), DbError> {+ sqlx::query(+ "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at, space_id, \+ thread_id, context_message_id, origin, suggestion_id, task_class, acceptance, checks) \+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(id)+ .bind(&input.kwant_id)+ .bind(&input.channel_id)+ .bind(&input.name)+ .bind(&input.instructions)+ .bind(&input.schedule)+ .bind(input.enabled)+ .bind(input.next_run_at)+ .bind(Utc::now())+ .bind(space.as_str())+ .bind(&input.thread_id)+ .bind(&input.context_message_id)+ .bind(&input.origin)+ .bind(&input.suggestion_id)+ .bind(&input.task_class)+ .bind(&input.acceptance)+ .bind(&input.checks)+ .execute(conn)+ .await?;+ Ok(())+}+#[cfg(test)]mod tests {use super::*;@@ -1028,3 +1040,4 @@ mod tests {);}}+diff --git a/src/db/imports.rs b/src/db/imports.rsindex 8bf44e8e..fec33fed 100644--- a/src/db/imports.rs+++ b/src/db/imports.rs@@ -424,14 +424,23 @@ impl Database {.into_iter().map(|(name, description, body)| SkillSpec { name, description, body }).collect();- let routines = sqlx::query_as::<_, (String, String, String)>(- "SELECT name, instructions, schedule FROM routines WHERE kwant_id = ? ORDER BY created_at, rowid",+ type Row = (String, String, String, Option<String>, Option<String>, Option<String>);+ let routines = sqlx::query_as::<_, Row>(+ "SELECT name, instructions, schedule, task_class, acceptance, checks FROM routines WHERE kwant_id = ? ORDER BY created_at, rowid",).bind(&k.id).fetch_all(&self.pool).await?.into_iter()- .map(|(name, instructions, schedule)| RoutineSpec { name, instructions, schedule: serde_json::from_str(&schedule).ok(), schedule_text: None })+ .map(|(name, instructions, schedule, task_class, acceptance, checks)| RoutineSpec {+ name,+ instructions,+ schedule: serde_json::from_str(&schedule).ok(),+ schedule_text: None,+ task_class,+ acceptance,+ checks: shareable_checks(checks.as_deref()),+ }).collect();let tool_hints = self.list_active_mcp_servers_for_kwant(&k.id).await?.into_iter().map(|s| s.name).collect();Ok(BotSpec {@@ -529,6 +538,14 @@ async fn insert_pending_skill(Ok(id)}+/// A routine's checks for a bundle, only when no spec holds anything that looks like a secret:+/// a bundle is shared, and a masked check would be useless.+fn shareable_checks(checks: Option<&str>) -> Option<Vec<serde_json::Value>> {+ let list: Vec<serde_json::Value> = serde_json::from_str(checks?).ok()?;+ let clean = list.iter().all(|c| crate::server::missions::autofix::redact_value(&c["spec"]) == c["spec"]);+ (clean && !list.is_empty()).then_some(list)+}+async fn insert_paused_routine(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,space: &SpaceId,@@ -544,8 +561,8 @@ async fn insert_paused_routine(.unwrap_or_else(crate::import::placeholder_schedule);let id = Uuid::new_v4().to_string();sqlx::query(- "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at, space_id)- VALUES (?, ?, NULL, ?, ?, ?, 0, NULL, ?, ?)",+ "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at, space_id, task_class, acceptance)+ VALUES (?, ?, NULL, ?, ?, ?, 0, NULL, ?, ?, ?, ?)",).bind(&id).bind(kwant_id)@@ -554,6 +571,8 @@ async fn insert_paused_routine(.bind(serde_json::to_string(&schedule)?).bind(now).bind(space.as_str())+ .bind(&r.task_class)+ .bind(&r.acceptance).execute(&mut **tx).await?;Ok(id)diff --git a/src/import/mod.rs b/src/import/mod.rsindex 03554122..f93ffd91 100644--- a/src/import/mod.rs+++ b/src/import/mod.rs@@ -147,6 +147,16 @@ pub struct RoutineSpec {/// The schedule as the source wrote it: a cron line, `09:00`, `daily 09:00`, ….#[serde(default)]pub schedule_text: Option<String>,+ /// Each run's Flight School class (kwant bundles only; absent: `general`).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub task_class: Option<String>,+ /// What "done" means for each run (kwant bundles only).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub acceptance: Option<String>,+ /// Each run's checks `[{kind, spec, required}]`. Exported only when no spec holds a secret;+ /// never applied on import, since a check runs commands the person must approve.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub checks: Option<Vec<serde_json::Value>>,}#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]@@ -714,11 +724,22 @@ fn tidy_routines(placeholder_schedule()}};+ if r.checks.as_ref().is_some_and(|c| !c.is_empty()) {+ warnings.push(Notice::new(who, format!("Routine {label}: its checks weren't brought over. Add them in Routines if you want them.")));+ }+ let task_class = r+ .task_class+ .map(|c| c.trim().to_string())+ .filter(|c| crate::db::flight_school::valid_class(c) && c != crate::db::flight_school::DEFAULT_CLASS);+ let acceptance = r.acceptance.map(|a| cut(a.trim(), crate::server::scheduler::MAX_ACCEPTANCE_CHARS)).filter(|a| !a.is_empty());out.push(RoutineSpec {name,instructions,schedule: serde_json::to_value(&schedule).ok(),schedule_text: r.schedule_text.map(|t| cut(t.trim(), 200)),+ task_class,+ acceptance,+ checks: None,});}out@@ -782,7 +803,7 @@ mod tests {}fn routine(schedule: Option<serde_json::Value>, text: Option<&str>) -> RoutineSpec {- RoutineSpec { name: "r".into(), instructions: "i".into(), schedule, schedule_text: text.map(Into::into) }+ RoutineSpec { name: "r".into(), instructions: "i".into(), schedule, schedule_text: text.map(Into::into), ..Default::default() }}#[test]diff --git a/src/import/parsers.rs b/src/import/parsers.rsindex 097350ca..8e08783d 100644--- a/src/import/parsers.rs+++ b/src/import/parsers.rs@@ -412,6 +412,7 @@ fn from_grokbot(v: &Value) -> Bundle {// An object like {"type": "cron", "expression": …, "timeZone": …} is read as is.schedule: r.get("schedule").filter(|v| v.is_object()).cloned(),schedule_text: Some(any_s(r, &["schedule", "cron", "time"])).filter(|t| !t.is_empty()),+ ..Default::default()}).collect();let tool_hints = arr(v, "plugins")@@ -530,7 +531,7 @@ fn from_openmaus_package(v: &Value) -> Result<Bundle, ImportError> {b.skills = skills_by_name.into_iter().filter(|sk| !used.contains(&sk.name)).collect();for r in arr(pkg, "routines") {let (schedule, schedule_text) = openmaus_schedule(r.get("schedule").unwrap_or(&Value::Null));- let spec = RoutineSpec { name: s(r, "name"), instructions: any_s(r, &["prompt", "instructions"]), schedule, schedule_text };+ let spec = RoutineSpec { name: s(r, "name"), instructions: any_s(r, &["prompt", "instructions"]), schedule, schedule_text, ..Default::default() };let agent = s(r, "agent");match b.bots.iter_mut().find(|bot| bot.ref_ == agent) {Some(bot) => bot.routines.push(spec),@@ -575,6 +576,7 @@ fn from_openmaus_grok(v: &Value) -> Bundle {// An object like {"type": "cron", "expression": …, "timeZone": …} is read as is.schedule: r.get("schedule").filter(|v| v.is_object()).cloned(),schedule_text: Some(any_s(r, &["schedule", "cron", "time", "when"])).filter(|t| !t.is_empty()),+ ..Default::default()}).collect();let mut tool_hints = texts(arr(bot, "connectedApps"));diff --git a/src/server/auth.rs b/src/server/auth.rsindex f564b578..aaff020c 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -870,6 +870,9 @@ mod tests {assert!(person_only(&post, "/api/skills/s1/replay"));assert!(person_only(&post, "/api/automation-discovery/scan"));assert!(person_only(&get, "/api/automation-discovery/scan?space=s1"));+ assert!(person_only(&get, "/api/automation-discovery"));+ assert!(person_only(&post, "/api/automation-discovery/sug_1/accept"));+ assert!(person_only(&post, "/api/automation-discovery/sug_1/dismiss"));assert!(!person_only(&get, "/api/skills/s1"));assert!(person_only(&post, "/api/missions"));assert!(person_only(&post, "/api/missions/m1/approve"));diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rsindex 120e9ef2..6666c33a 100644--- a/src/server/bot_actions.rs+++ b/src/server/bot_actions.rs@@ -1826,7 +1826,14 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,let p = deleted_routine_payload(&before)?;let resp = super::scheduler::create_by(state, space.clone(), space_uri("/api/routines", &space), p, By::Person).await;let created = ok_or_conflict(resp, "the routine can't be recreated").await?;- return Ok(created["id"].as_str().map(str::to_string));+ let id = created["id"].as_str().map(str::to_string);+ // A discovered routine stays "Suggested by kwant" (design §8)+ if let (Some(id), Some("discovery"), Some(suggestion)) = (&id, before["origin"].as_str(), before["suggestion_id"].as_str()) {+ if let Err(e) = state.db.relink_discovered(id, suggestion).await {+ tracing::warn!(error = %e, routine = %id, "relinking an undone discovered routine");+ }+ }+ return Ok(id);}"bot_create" => delete_unused_bot(state, &target).await?,"bot_hire" => {diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex a9bd7b25..9b9915d6 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; 11] = [+pub const NOTIFY_KINDS: [&str; 12] = ["turn_finished","approval_needed","routine_failed",@@ -46,6 +46,7 @@ pub const NOTIFY_KINDS: [&str; 11] = ["human_step","app_update","work_ahead",+ "automation_suggested",];const MASK: &str = "••••••••";@@ -1327,7 +1328,7 @@ 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; 2] = ["app_update", "work_ahead"];+const KINDS_SINCE_FIRST_LIST: [&str; 3] = ["app_update", "work_ahead", "automation_suggested"];/// 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/missions/discovery.rs b/src/server/missions/discovery.rsindex 34e2dd13..85e6d9b2 100644--- a/src/server/missions/discovery.rs+++ b/src/server/missions/discovery.rs@@ -1,28 +1,46 @@-//! Mission Control Phase D4: Automation Discovery's scan. Reads the person's board tasks of one-//! space, runs the miner (`crate::automation_discovery`) and says which routines it would suggest-//! and why every other habit gets none. Step 2 is a preview: it stores nothing, neither an offer-//! nor a routine, and offering, Accept and Dismiss come in step 3. Off by default. See-//! docs/mission-control.md §20 and mission-control/phase-d/automation-discovery.md.--use super::routes::internal;-use crate::automation_discovery::{self as miner, Delivery, Input, Offer, Scan};+//! Mission Control Phase D4: Automation Discovery. Reads the person's board tasks of a space, runs+//! the miner (`crate::automation_discovery`) and keeps what it finds as offers the person accepts+//! (a routine is made) or dismisses (not offered again for 30 days). Nothing is created without+//! Accept. Scans run hourly while the setting is on, or when the person asks; every route is the+//! person's only. Off by default. See docs/mission-control.md §20 and+//! mission-control/phase-d/automation-discovery.md.++// Handler helpers return the ready-made error `Response`+#![allow(clippy::result_large_err)]++use super::routes::{bad, err, internal, not_found};+use crate::automation_discovery::{self as miner, CheckSpec, Delivery, Input, LeftOut, Offer, Scan};+use crate::db::automation::{Decided, SuggestionRow};use crate::db::spaces::SpaceId;use crate::db::DbError;-use crate::routines::now_in;-use crate::server::spaces::Scope;+use crate::routines::{now_in, run_time_text, Schedule};+use crate::server::continuity::{notify, Notification};+use crate::server::scheduler::{self, RoutineCheck, RoutinePayload, RoutineView};+use crate::server::spaces::{space_param, Scope};use crate::server::AppState;use axum::{- extract::State,+ body::Bytes,+ extract::{Path, Query, RawQuery, State},+ http::{HeaderMap, StatusCode},response::{IntoResponse, Response},Json,};-use chrono::{DateTime, Utc};+use chrono::{DateTime, Duration, Utc};+use serde::Deserialize;use serde_json::{json, Value};use std::collections::HashSet;+use tokio_util::sync::CancellationToken;pub const SETTING: &str = "automation_discovery";pub const MODES: [&str; 2] = ["off", "on"];pub const CAP_SETTING: &str = "automation_discovery_daily_cap";+/// When the last scan of every space ran (RFC 3339): the hourly scan waits an hour from it.+pub const LAST_SCAN_SETTING: &str = "automation_discovery_last_scan";+/// How often the background loop wakes; it scans when the last scan is [`SCAN_EVERY`] old.+const TICK: std::time::Duration = std::time::Duration::from_secs(10 * 60);+const SCAN_EVERY: Duration = Duration::hours(1);+/// Statuses `GET ?status=` takes; `all` lists every one.+const STATUSES: [&str; 6] = ["offered", "accepted", "dismissed", "expired", "superseded", "all"];pub async fn enabled(state: &AppState) -> bool {matches!(state.db.get_setting(SETTING).await.ok().flatten().as_deref().map(str::trim), Some("on"))@@ -61,6 +79,22 @@ async fn blocked_by(state: &AppState, now: DateTime<Utc>) -> Result<String, &'stOk(tz)}+/// Every reason no scan runs, for `GET` (empty: scans run).+async fn blockers(state: &AppState, now: DateTime<Utc>) -> Vec<&'static str> {+ let mut why = Vec::new();+ if !enabled(state).await {+ why.push("off");+ }+ if !super::enabled(state).await {+ why.push("board_off");+ }+ let tz = state.db.get_setting(crate::server::bot_actions::TIMEZONE_SETTING).await.ok().flatten().unwrap_or_default();+ if tz.trim().is_empty() || now_in(tz.trim(), now).is_err() {+ why.push("no_timezone");+ }+ why+}+/// Where an offer would deliver, if that place is still there: its bot's own unarchived thread,/// or a channel of the space; else the bot's direct chat.async fn deliverable(state: &AppState, space: &str, offer: &Offer) -> Delivery {@@ -80,20 +114,26 @@ async fn deliverable(state: &AppState, space: &str, offer: &Offer) -> Delivery {direct}-/// One scan of `space` at `now`, read-only: what would be offered and what was skipped.-pub async fn preview(state: &AppState, space_id: &SpaceId, now: DateTime<Utc>) -> Result<Value, DbError> {+/// Masks secrets in the check specs of an offer that is shown.+fn redact(checks: &mut [CheckSpec], left_out: &mut [LeftOut]) {+ for c in checks {+ c.spec = super::autofix::redact_value(&c.spec);+ }+ for c in left_out {+ c.spec = super::autofix::redact_value(&c.spec);+ }+}++/// Runs the miner over `space` at `now` in `tz`.+async fn mine(state: &AppState, space_id: &SpaceId, tz: &str, now: DateTime<Utc>) -> Result<Scan, DbError> {let space = space_id.as_str();- let tz = match blocked_by(state, now).await {- Ok(tz) => tz,- Err(why) => return Ok(json!({ "blocked_by": why, "preview": true, "offered": [], "skipped": [] })),- };let tasks = state.db.discovery_tasks(space, now).await?;let checks = state.db.discovery_checks(space, now).await?;let routines = state.db.discovery_routines(space).await?;let past = state.db.discovery_past(space, now).await?;let bots: HashSet<String> = state.db.list_kwants(space_id).await?.into_iter().map(|k| k.id).collect();- let Scan { mut offered, skipped } = miner::mine(&Input {- tz: &tz,+ Ok(miner::mine(&Input {+ tz,now,tasks: &tasks,checks: &checks,@@ -102,16 +142,19 @@ pub async fn preview(state: &AppState, space_id: &SpaceId, now: DateTime<Utc>) -past: &past,daily_cap: usize::try_from(daily_cap(state).await).unwrap_or(0),max_live: miner::MAX_LIVE_PER_SPACE,- });+ }))+}++/// One scan of `space` at `now`, read-only: what would be offered and what was skipped.+pub async fn preview(state: &AppState, space_id: &SpaceId, now: DateTime<Utc>) -> Result<Value, DbError> {+ let tz = match blocked_by(state, now).await {+ Ok(tz) => tz,+ Err(why) => return Ok(json!({ "blocked_by": why, "preview": true, "offered": [], "skipped": [] })),+ };+ let Scan { mut offered, skipped, .. } = mine(state, space_id, &tz, now).await?;for o in &mut offered {- o.delivery = deliverable(state, space, o).await;- // Shown on a card: secrets in a check's spec never are- for c in &mut o.checks {- c.spec = super::autofix::redact_value(&c.spec);- }- for c in &mut o.left_out_checks {- c.spec = super::autofix::redact_value(&c.spec);- }+ o.delivery = deliverable(state, space_id.as_str(), o).await;+ redact(&mut o.checks, &mut o.left_out_checks);}Ok(json!({"blocked_by": null,@@ -122,11 +165,490 @@ pub async fn preview(state: &AppState, space_id: &SpaceId, now: DateTime<Utc>) -}))}-/// `POST /api/automation-discovery/scan?space=` (person only): what a scan would offer now, and-/// why every other habit gets none. Writes nothing; with the setting off it reads nothing either.-pub async fn scan(State(state): State<AppState>, Scope(space): Scope) -> Response {- match preview(&state, &space, Utc::now()).await {- Ok(v) => Json(v).into_response(),+/// An offer as it is stored: where it delivers now, and only checks a routine may carry (the+/// rest are listed as left out). Specs stay unmasked; they are masked whenever shown.+async fn storable(state: &AppState, space: &str, mut o: Offer) -> Offer {+ o.delivery = deliverable(state, space, &o).await;+ let (keep, refused): (Vec<CheckSpec>, Vec<CheckSpec>) = o.checks.into_iter().partition(|c| super::validate_check(&c.kind, &c.spec, true).is_ok());+ o.checks = keep;+ o.left_out_checks.extend(refused.into_iter().map(|c| LeftOut { kind: c.kind, spec: c.spec, reason: "not allowed on a routine" }));+ o+}++/// What a scan of one space did.+#[derive(Debug, Default)]+pub struct Stored {+ /// Suggestion ids stored as new offers.+ pub offered: Vec<String>,+ /// Live offers ended because their habit no longer passes, or changed.+ pub expired: Vec<String>,+ pub superseded: Vec<String>,+ pub skipped: Vec<miner::Skip>,+}++/// 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.+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();+ let live = state.db.list_suggestions(space, Some("offered")).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());+ }+ }+ }+ // Ended offers free their habits and their room: mine again with that+ if !out.expired.is_empty() || !out.superseded.is_empty() {+ scan = mine(state, space_id, tz, now).await?;+ }+ let cap = daily_cap(state).await;+ for o in scan.offered {+ let key = o.cluster_key.clone();+ let 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;+ }+ out.offered.push(id);+ }+ // Another scan got there first, or the space filled up meanwhile+ None => out.skipped.push(miner::Skip { cluster_key: key, title: o.name.clone(), asks: o.evidence.total, reason: miner::Reason::Capped }),+ }+ }+ out.skipped.extend(scan.skipped);+ out.skipped.sort_by(|a, b| a.cluster_key.cmp(&b.cluster_key));+ Ok(out)+}++/// The one notification a new offer gets (design §10): its name and bot, nothing from a chat.+async fn announce(state: &AppState, o: &Offer) {+ let kwant_name = match state.db.get_kwant(&o.kwant_id).await {+ Ok(Some(k)) => k.name,+ _ => return,+ };+ notify(+ state,+ Notification {+ kind: "automation_suggested",+ kwant_id: o.kwant_id.clone(),+ body: format!("{kwant_name} could do this on a schedule. Accept or dismiss it in Routines."),+ title: format!("Suggested routine: {}", o.name),+ kwant_name,+ channel_id: None,+ },+ )+ .await;+}++/// The hourly scan of every space (when the setting is on), and the retention pass.+pub async fn tick(state: &AppState, now: DateTime<Utc>) -> usize {+ // Retention marks routines already accepted, so it runs whatever the setting says now+ if let Err(e) = state.db.mark_retention(now).await {+ tracing::warn!(error = %e, "automation discovery retention");+ }+ let Ok(tz) = blocked_by(state, now).await else { return 0 };+ if last_scan(state).await.is_some_and(|at| now - at < SCAN_EVERY && at <= now) {+ return 0;+ }+ let mut offered = 0;+ for space in state.db.list_spaces().await.unwrap_or_default().into_iter().filter(|s| s.archived_at.is_none()) {+ match scan_space(state, &SpaceId::new(&space.id), &tz, now).await {+ Ok(s) => offered += s.offered.len(),+ Err(e) => tracing::warn!(error = %e, space = %space.id, "automation discovery scan"),+ }+ }+ let _ = state.db.set_setting(LAST_SCAN_SETTING, &now.to_rfc3339()).await;+ offered+}++async fn last_scan(state: &AppState) -> Option<DateTime<Utc>> {+ let v = state.db.get_setting(LAST_SCAN_SETTING).await.ok().flatten()?;+ DateTime::parse_from_rfc3339(v.trim()).ok().map(|t| t.with_timezone(&Utc))+}++pub fn spawn(state: AppState, shutdown: CancellationToken) {+ tokio::spawn(async move {+ loop {+ tokio::select! {+ _ = shutdown.cancelled() => return,+ _ = tokio::time::sleep(TICK) => {}+ }+ tick(&state, Utc::now()).await;+ }+ });+}++// What the person sees++fn tier_label(tier: &str) -> &'static str {+ match tier {+ "observe" => "Observe: every change asks you first",+ "sandbox" => "Sandbox: commands that can change things ask you first",+ _ => "Act: works on its own, within its approvals",+ }+}++/// What the bot may do when the routine runs (design §5): a preview of what it already has, never+/// a grant.+async fn permissions(state: &AppState, row: &SuggestionRow, sources: &[String]) -> Value {+ let flight_school = super::flight_school::enabled(&state.db).await;+ // Off, Flight School holds nothing back: the bot acts as it does today+ let (tier, tier_from) = if flight_school { super::flight_school::tier_of(&state.db, &row.kwant_id, &row.task_class).await } else { ("act", "off") };+ let approval_mode = state.db.kwant_approvals(&row.kwant_id).await.map(|m| m.effective).unwrap_or_else(|_| "ask".into());+ let past = state.db.past_tools(sources).await.unwrap_or_default();+ json!({+ "flight_school": flight_school,+ "tier": tier,+ "tier_from": tier_from,+ "tier_label": tier_label(tier),+ "approval_mode": approval_mode,+ "payments_ask": true,+ "past": past,+ })+}++/// A stored suggestion as the API returns it (design §11): its JSON columns parsed, check specs+/// masked, and for a live offer the first run recomputed for `now` from its schedule (§5).+async fn suggestion_json(state: &AppState, row: &SuggestionRow, now: DateTime<Utc>) -> Value {+ let parse = |s: &str| serde_json::from_str::<Value>(s).unwrap_or(Value::Null);+ let mut evidence = parse(&row.evidence);+ let sources = evidence.get_mut("sources").map(Value::take).unwrap_or_else(|| json!([]));+ if let Some(e) = evidence.as_object_mut() {+ e.remove("sources");+ }+ let schedule = serde_json::from_str::<Schedule>(&row.schedule).ok();+ let mut first_run_at = row.first_run_at;+ if row.status == "offered" {+ let last_ask = evidence["last_ask_at"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok()).map_or(row.offered_at, |t| t.with_timezone(&Utc));+ if let Some(at) = schedule.as_ref().and_then(|s| miner::first_run_at(s, last_ask, now)) {+ first_run_at = at;+ }+ }+ let tz = schedule.as_ref().and_then(Schedule::tz);+ let masked = |s: &str| -> Value {+ let mut list: Vec<Value> = serde_json::from_str(s).unwrap_or_default();+ for c in &mut list {+ c["spec"] = super::autofix::redact_value(&c["spec"]);+ }+ Value::Array(list)+ };+ let source_ids: Vec<String> = serde_json::from_str(&row.source_task_ids).unwrap_or_default();+ let schedule_value = parse(&row.schedule);+ json!({+ "id": row.id,+ "space_id": row.space_id,+ "cluster_key": row.cluster_key,+ "kwant_id": row.kwant_id,+ "name": row.name,+ "instructions": row.instructions,+ "schedule_text": crate::server::bot_actions::schedule_text(&schedule_value),+ "schedule": schedule_value,+ "first_run_at": first_run_at,+ "first_run_text": run_time_text(first_run_at, tz),+ "delivery": parse(&row.delivery),+ "task_class": row.task_class,+ "acceptance": row.acceptance,+ "checks": masked(&row.checks),+ "left_out_checks": masked(&row.left_out_checks),+ "chain": parse(&row.chain),+ "source_task_ids": source_ids,+ "sources": sources,+ "time_spread": evidence["time_spread"].clone(),+ "evidence": evidence,+ "permissions": permissions(state, row, &source_ids).await,+ "status": row.status,+ "routine_id": row.routine_id,+ "cooldown_until": row.cooldown_until,+ "routine_deleted_at": row.routine_deleted_at,+ "retention": row.retention,+ "retention_at": row.retention_at,+ "offered_at": row.offered_at,+ "decided_at": row.decided_at,+ })+}++async fn suggestions_json(state: &AppState, ids: &[String], now: DateTime<Utc>) -> Vec<Value> {+ let mut out = Vec::new();+ for id in ids {+ if let Ok(Some(row)) = state.db.get_suggestion(id).await {+ out.push(suggestion_json(state, &row, now).await);+ }+ }+ out+}++// Routes++#[derive(Deserialize, Default)]+pub struct ListQuery {+ status: Option<String>,+}++/// `GET /api/automation-discovery?space=&status=` (person only): the setting, what keeps scans+/// from running, the last scan, the suggestions (`status`, default `offered`; `all`) and stats.+/// While a scan can't run, live offers are hidden.+pub async fn list(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<ListQuery>) -> Response {+ let now = Utc::now();+ let status = q.status.as_deref().map(str::trim).filter(|s| !s.is_empty()).unwrap_or("offered");+ if !STATUSES.contains(&status) {+ return bad("status must be offered, accepted, dismissed, expired, superseded or all");+ }+ let blocked_by = blockers(&state, now).await;+ let rows = match state.db.list_suggestions(space.as_str(), (status != "all").then_some(status)).await {+ Ok(r) => r,+ Err(e) => return internal(e),+ };+ let mut suggestions = Vec::new();+ for row in rows.iter().filter(|r| blocked_by.is_empty() || r.status != "offered") {+ suggestions.push(suggestion_json(&state, row, now).await);+ }+ let stats = match state.db.suggestion_stats(space.as_str(), now).await {+ Ok(s) => s,+ Err(e) => return internal(e),+ };+ Json(json!({+ "setting": if enabled(&state).await { "on" } else { "off" },+ "daily_cap": daily_cap(&state).await,+ "blocked_by": blocked_by,+ "last_scan_at": last_scan(&state).await,+ "suggestions": suggestions,+ "stats": stats,+ }))+ .into_response()+}++#[derive(Deserialize, Default)]+pub struct ScanQuery {+ #[serde(default)]+ preview: Option<String>,+}++/// `POST /api/automation-discovery/scan?space=` (person only): scans now, ignoring the hourly+/// wait but not the cap, and keeps the offers. `?preview=1` only says what it would offer and+/// writes nothing. With the setting off nothing is read.+pub async fn scan(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<ScanQuery>) -> Response {+ let now = Utc::now();+ if q.preview.as_deref().is_some_and(|p| matches!(p.trim(), "1" | "true" | "yes")) {+ return match preview(&state, &space, now).await {+ Ok(v) => Json(v).into_response(),+ Err(e) => internal(e),+ };+ }+ let tz = match blocked_by(&state, now).await {+ Ok(tz) => tz,+ Err(why) => return Json(json!({ "blocked_by": why, "preview": false, "offered": [], "skipped": [], "expired": [], "superseded": [] })).into_response(),+ };+ let stored = match scan_space(&state, &space, &tz, now).await {+ Ok(s) => s,+ Err(e) => return internal(e),+ };+ let _ = state.db.set_setting(LAST_SCAN_SETTING, &now.to_rfc3339()).await;+ Json(json!({+ "blocked_by": null,+ "preview": false,+ "timezone": tz,+ "offered": suggestions_json(&state, &stored.offered, now).await,+ "skipped": stored.skipped,+ "expired": stored.expired,+ "superseded": stored.superseded,+ }))+ .into_response()+}++/// `POST …/:id/accept` body: overrides of the suggestion, all optional (design §6).+#[derive(Debug, Deserialize, Default)]+#[serde(deny_unknown_fields)]+pub struct AcceptBody {+ pub name: Option<String>,+ pub instructions: Option<String>,+ pub schedule: Option<Value>,+ pub kwant_id: Option<String>,+ /// A channel of the space; `null` or `""`: the bot's direct chat.+ #[serde(default, deserialize_with = "scheduler::double_option")]+ pub channel_id: Option<Option<String>>,+ /// One of the bot's own threads.+ #[serde(default, deserialize_with = "scheduler::double_option")]+ pub thread_id: Option<Option<String>>,+ #[serde(default, deserialize_with = "scheduler::double_option")]+ pub acceptance: Option<Option<String>>,+ /// Indexes into the suggestion's checks to keep (default: all). Checks can be dropped here,+ /// not added.+ pub keep_checks: Option<Vec<usize>>,+}++/// The suggestion `id`, refused (404) when an explicit `?space=` names another space.+async fn load(state: &AppState, query: Option<&str>, id: &str) -> Result<SuggestionRow, Response> {+ match state.db.get_suggestion(id).await {+ Ok(Some(s)) if space_param(query).is_none_or(|q| q.trim() == s.space_id) => Ok(s),+ Ok(_) => Err(not_found("suggestion")),+ Err(e) => Err(internal(e)),+ }+}++fn not_offered(s: &SuggestionRow) -> Response {+ (StatusCode::CONFLICT, Json(json!({ "error": format!("this suggestion was already {}", s.status), "status": s.status, "routine_id": s.routine_id }))).into_response()+}++/// The routine Accept makes from `s` with the person's overrides `b`, built and checked like any+/// routine, then given the first run recomputed for `now` (design §5) and the discovery origin.+async fn routine_from(state: &AppState, s: &SuggestionRow, b: AcceptBody, now: DateTime<Utc>) -> Result<crate::db::continuity::NewRoutine, Response> {+ let stored_checks: Vec<RoutineCheck> = serde_json::from_str(&s.checks).unwrap_or_default();+ let checks = match &b.keep_checks {+ None => stored_checks,+ Some(keep) => {+ if let Some(i) = keep.iter().find(|i| **i >= stored_checks.len()) {+ return Err(err(StatusCode::UNPROCESSABLE_ENTITY, format!("keep_checks: no check {i} (the suggestion has {})", stored_checks.len())));+ }+ stored_checks.into_iter().enumerate().filter(|(i, _)| keep.contains(i)).map(|(_, c)| c).collect()+ }+ };+ let schedule = match b.schedule {+ Some(v) => Some(serde_json::from_value::<Schedule>(v).map_err(|e| bad(format!("invalid schedule: {e}")))?),+ None => serde_json::from_str::<Schedule>(&s.schedule).ok(),+ };+ let kwant_id = b.kwant_id.map(|k| k.trim().to_string()).unwrap_or_else(|| s.kwant_id.clone());+ match state.db.space_of_kwant(&kwant_id).await {+ Ok(Some(space)) if space.as_str() == s.space_id => {}+ Ok(Some(_)) => return Err(bad("the bot is in another space")),+ Ok(None) => return Err(bad("unknown kwant_id")),+ Err(e) => return Err(internal(e)),+ }+ // Where it delivers: the person's choice, else the suggestion's (if still there). A thread or+ // direct chat belongs to the suggested bot, so another bot gets its own direct chat.+ let (mut channel_id, mut thread_id) = (b.channel_id, b.thread_id);+ if channel_id.is_none() && thread_id.is_none() {+ let offer_place: Delivery = serde_json::from_str(&s.delivery).unwrap_or_default();+ let here = deliverable_row(state, s, offer_place).await;+ match (here.channel_id, here.thread_id) {+ (Some(c), _) => channel_id = Some(Some(c)),+ (None, Some(t)) if kwant_id == s.kwant_id => thread_id = Some(Some(t)),+ _ => channel_id = Some(None),+ }+ }+ let class = (s.task_class != crate::db::flight_school::DEFAULT_CLASS).then(|| s.task_class.clone());+ let acceptance = b.acceptance.unwrap_or_else(|| Some(s.acceptance.clone()));+ let p = RoutinePayload {+ kwant_id: Some(kwant_id),+ channel_id,+ name: Some(b.name.unwrap_or_else(|| s.name.clone())),+ instructions: Some(b.instructions.unwrap_or_else(|| s.instructions.clone())),+ schedule,+ enabled: Some(true),+ thread_id,+ context_message_id: None,+ task_class: Some(class),+ acceptance: Some(acceptance),+ checks: Some(Some(checks)),+ };+ let mut r = scheduler::build(state, p, None).await?;+ let evidence: Value = serde_json::from_str(&s.evidence).unwrap_or_default();+ let last_ask = evidence["last_ask_at"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok()).map_or(s.offered_at, |t| t.with_timezone(&Utc));+ let fin: Schedule = serde_json::from_str(&r.schedule).map_err(internal)?;+ if let Some(at) = miner::first_run_at(&fin, last_ask, now) {+ r.next_run_at = Some(at);+ }+ r.origin = Some("discovery".into());+ r.suggestion_id = Some(s.id.clone());+ Ok(r)+}++/// [`deliverable`] for a stored suggestion.+async fn deliverable_row(state: &AppState, s: &SuggestionRow, place: Delivery) -> Delivery {+ let direct = Delivery { direct_kwant_id: Some(s.kwant_id.clone()), ..Default::default() };+ if let Some(t) = &place.thread_id {+ return match state.db.get_thread(t).await {+ Ok(Some(t)) if t.kwant_id == s.kwant_id && !t.archived => place,+ _ => direct,+ };+ }+ if let Some(c) = &place.channel_id {+ return match state.db.get_channel(c).await {+ Ok(Some(c)) if c.space_id == s.space_id => place,+ _ => direct,+ };+ }+ direct+}++/// Accept at `now`: 201-shaped `{suggestion, routine, first_run_text}` or the error response.+pub async fn accept_at(state: &AppState, query: Option<&str>, id: &str, body: AcceptBody, now: DateTime<Utc>) -> Result<Value, Response> {+ let s = load(state, query, id).await?;+ if s.status != "offered" {+ return Err(not_offered(&s));+ }+ let routine = routine_from(state, &s, body, now).await?;+ match state.db.accept_suggestion(&s.id, &s.space_id, &routine, now).await {+ Ok(Decided::Done(s, Some(r))) => {+ state.scheduler_wake.notify_one();+ let routine = RoutineView::from(*r);+ let tz = serde_json::from_value::<Schedule>(routine.schedule.clone()).ok();+ let first_run_text = routine.next_run_at.map(|at| run_time_text(at, tz.as_ref().and_then(Schedule::tz)));+ Ok(json!({+ "suggestion": suggestion_json(state, &s, now).await,+ "routine": routine,+ "first_run_text": first_run_text,+ }))+ }+ Ok(Decided::NotOffered(s)) => Err(not_offered(&s)),+ Ok(Decided::Done(..) | Decided::Missing) => Err(not_found("suggestion")),+ Err(DbError::OtherSpace(m)) => Err(bad(m)),+ Err(e) => Err(internal(e)),+ }+}++/// `POST /api/automation-discovery/:id/accept` (person only; `Idempotency-Key` required): makes+/// the routine (design §6). 201 `{suggestion, routine, first_run_text}`; the same key again+/// replays it; 409 `{routine_id}` once it isn't a live offer; 400 for an invalid override; 422+/// for `keep_checks` out of range.+pub async fn accept(State(state): State<AppState>, RawQuery(q): RawQuery, headers: HeaderMap, Path(id): Path<String>, body: Bytes) -> Response {+ if headers.get("idempotency-key").is_none() {+ return bad("Idempotency-Key is required");+ }+ // No body: the suggestion as it is. A body that isn't one (an unknown field too) is refused+ let body: AcceptBody = if body.iter().all(u8::is_ascii_whitespace) {+ AcceptBody::default()+ } else {+ match serde_json::from_slice(&body) {+ Ok(b) => b,+ Err(e) => return bad(format!("invalid body: {e}")),+ }+ };+ let route = format!("POST /api/automation-discovery/{id}/accept");+ let mut resp = super::graph::idempotent(&state, &headers, route, || accept_at(&state, q.as_deref(), &id, body, Utc::now())).await;+ if resp.status() == StatusCode::OK {+ *resp.status_mut() = StatusCode::CREATED;+ }+ resp+}++/// `POST /api/automation-discovery/:id/dismiss` (person only): not offered again for 30 days.+/// 200 `{suggestion}`; 409 once it isn't a live offer.+pub async fn dismiss(State(state): State<AppState>, RawQuery(q): RawQuery, Path(id): Path<String>) -> Response {+ let now = Utc::now();+ let s = match load(&state, q.as_deref(), &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ match state.db.dismiss_suggestion(&s.id, &s.space_id, now).await {+ Ok(Decided::Done(s, _)) => Json(json!({ "suggestion": suggestion_json(&state, &s, now).await })).into_response(),+ Ok(Decided::NotOffered(s)) => not_offered(&s),+ Ok(Decided::Missing) => not_found("suggestion"),Err(e) => internal(e),}}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 3fa402b9..1f98743b 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -404,7 +404,10 @@ pub fn create_router(state: AppState) -> Router {.route("/api/human-steps/:id", get(human_steps::get)).route("/api/human-steps/:id/done", post(human_steps::done)).route("/api/human-steps/:id/decline", post(human_steps::decline))+ .route("/api/automation-discovery", get(missions::discovery::list)).route("/api/automation-discovery/scan", post(missions::discovery::scan))+ .route("/api/automation-discovery/:id/accept", post(missions::discovery::accept))+ .route("/api/automation-discovery/:id/dismiss", post(missions::discovery::dismiss)).route("/api/skills/foundry", get(missions::foundry::overview)).route("/api/skills/foundry/:cluster/draft", post(missions::foundry::draft_now)).route("/api/skills/:id/foundry", get(missions::foundry::detail))diff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex d55bdcdb..6b1f3779 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -27,7 +27,7 @@ use tokio_util::sync::CancellationToken;pub const MAX_SLEEP: Duration = Duration::from_secs(30);const MAX_NAME_CHARS: usize = 100;const MAX_ROUTINE_INSTRUCTIONS_CHARS: usize = 4000;-const MAX_ACCEPTANCE_CHARS: usize = 4000;+pub(crate) const MAX_ACCEPTANCE_CHARS: usize = 4000;/// Checks one routine copies onto each run's task.const MAX_ROUTINE_CHECKS: usize = 10;@@ -165,7 +165,7 @@ pub struct RoutinePayload {}/// Tells a missing field (`None`) from an explicit `null` (`Some(None)`).-fn double_option<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<Option<T>>, D::Error> {+pub(crate) fn double_option<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<Option<T>>, D::Error> {Ok(Some(Option::<T>::deserialize(d)?))}@@ -225,7 +225,7 @@ fn build_outcome(}/// Merges `p` over `existing` and checks the result.-async fn build(+pub(crate) async fn build(state: &AppState,p: RoutinePayload,existing: Option<&RoutineRow>,@@ -429,6 +429,13 @@ pub async fn update_by(state: &AppState, id: String, p: RoutinePayload, by: By)match state.db.update_routine(&id, &input).await {Ok(Some(r)) => {state.scheduler_wake.notify_one();+ // A discovered routine's switches feed its suggestion's history (design §10)+ if let (Some(sug), true) = (existing.suggestion_id.as_deref(), existing.enabled != r.enabled) {+ let actor = if by == By::Bot { "kwant" } else { "person" };+ if let Err(e) = state.db.suggestion_switched(sug, r.enabled, actor).await {+ tracing::warn!(error = %e, routine = %id, "recording a discovered routine's switch");+ }+ }Json(RoutineView::from(r)).into_response()}Ok(None) => StatusCode::NOT_FOUND.into_response(),@@ -833,5 +840,6 @@ 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::missions::discovery::spawn(state.clone(), shutdown.clone());spawn(state, shutdown);}diff --git a/tests/app_update_test.rs b/tests/app_update_test.rsindex a379c143..01215c3e 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"]));+ assert_eq!(on, kinds(&["turn_finished", "approval_needed", "app_update", "work_ahead", "automation_suggested"]));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/automation_discovery_test.rs b/tests/automation_discovery_test.rsindex ca6723f3..54f9c99f 100644--- a/tests/automation_discovery_test.rs+++ b/tests/automation_discovery_test.rs@@ -1,14 +1,16 @@-//! Automation Discovery step 2 (Phase D4): the read-only scan route. It is off by default and-//! then reads nothing; on, it previews offers from the person's board tasks and never writes an-//! offer or a routine; bots can't call it; it only learns from tasks the person made. The miner's-//! own cases are unit tests in `src/automation_discovery.rs`. Contract: docs/mission-control.md §20.+//! Automation Discovery (Phase D4). Off by default and then reads and writes nothing; on, scans+//! (hourly, or when the person asks) keep offers from the person's board tasks, within the daily+//! cap and 5 live per space, one notification each; Accept makes the routine once, Dismiss cools+//! the habit off; a preview writes nothing; bots get 403 everywhere; it only learns from tasks+//! the person made. The miner's own cases are unit tests in `src/automation_discovery.rs`.+//! Contract: docs/mission-control.md §20.use axum::{body::{to_bytes, Body},- http::{Request, StatusCode},+ http::{HeaderMap, Request, StatusCode},Router,};-use chrono::{DateTime, Datelike, Duration, NaiveTime, Utc};+use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveTime, Utc};use kwnt::{automation_discovery::cluster_key,broker::PermissionBroker,@@ -24,9 +26,12 @@ use kwnt::{routines::{local_date, local_instant},server::{continuity::{SelfScope, TurnOrigin},- create_router, mcp_runtime, AppState,+ create_router, mcp_runtime,+ missions::discovery::{self, AcceptBody},+ AppState,},tools::ToolRunner,+ RuntimeEvent,};use serde_json::{json, Value};use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};@@ -35,6 +40,8 @@ use tower::ServiceExt;const TZ: &str = "Europe/Berlin";const SCAN: &str = "/api/automation-discovery/scan";+const PREVIEW: &str = "/api/automation-discovery/scan?preview=1";+const LIST: &str = "/api/automation-discovery";struct Env {app: Router,@@ -58,15 +65,29 @@ async fn setup() -> Env {}async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {+ let (status, _, v) = call_with(app, method, uri, auth, None, body).await;+ (status, v)+}++async fn call_with(app: &Router, method: &str, uri: &str, auth: Option<&str>, key: Option<&str>, body: Option<Value>) -> (StatusCode, HeaderMap, 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}"));}+ if let Some(key) = key {+ req = req.header("idempotency-key", key);+ }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 headers = resp.headers().clone();let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();- (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+ (status, headers, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++/// Accept as the person with Idempotency-Key `key`.+async fn accept(e: &Env, id: &str, key: &str, body: Value) -> (StatusCode, HeaderMap, Value) {+ call_with(&e.app, "POST", &format!("{LIST}/{id}/accept"), None, Some(key), Some(body)).await}async fn person(e: &Env, method: &str, uri: &str, body: Option<Value>) -> Value {@@ -100,6 +121,12 @@ fn weeks_ago(weeks: i64) -> DateTime<Utc> {/// A task `owner` verified, made `created_by` from `source_kind` at `at`.async fn done_task(e: &Env, owner: &Kwant, title: &str, at: DateTime<Utc>, source_kind: &str, created_by: &str) -> String {+ ended_task(e, owner, title, at, source_kind, created_by, "verified", None).await+}++/// [`done_task`] ending in `state`, forked from `fork_of` if given.+#[allow(clippy::too_many_arguments)]+async fn ended_task(e: &Env, owner: &Kwant, title: &str, at: DateTime<Utc>, source_kind: &str, created_by: &str, state: &str, fork_of: Option<&str>) -> String {let t = NewTask {title: title.into(),acceptance: "The report is in the shared folder".into(),@@ -123,7 +150,9 @@ async fn done_task(e: &Env, owner: &Kwant, title: &str, at: DateTime<Utc>, sourc};let c = e.state.db.add_check(&check).await.unwrap();e.state.db.finish_check(&c.id, "passed", None, "person", None).await.unwrap();- sqlx::query("UPDATE tasks SET state = 'verified', created_at = ?, finished_at = ? WHERE id = ?")+ sqlx::query("UPDATE tasks SET state = ?, forked_from = ?, created_at = ?, finished_at = ? WHERE id = ?")+ .bind(state)+ .bind(fork_of).bind(at).bind(at + Duration::minutes(30)).bind(&t.id)@@ -162,8 +191,17 @@ async fn the_scan_is_off_by_default_and_then_finds_nothing() {habit(&e, &a, "Weekly report").await;let s = person(&e, "GET", "/api/settings", None).await;assert_eq!((s["automation_discovery"].as_str(), s["automation_discovery_daily_cap"].as_i64()), (Some("off"), Some(2)));+ let before = written_rows(&e).await;let v = person(&e, "POST", SCAN, None).await;+ assert_eq!(v, json!({"blocked_by": "off", "preview": false, "offered": [], "skipped": [], "expired": [], "superseded": []}));+ let v = person(&e, "POST", PREVIEW, None).await;assert_eq!(v, json!({"blocked_by": "off", "preview": true, "offered": [], "skipped": []}));+ // Nor does the hourly scan, ever+ assert_eq!(discovery::tick(&e.state, Utc::now()).await, 0);+ assert_eq!(discovery::tick(&e.state, Utc::now() + Duration::hours(3)).await, 0);+ assert_eq!(written_rows(&e).await, before);+ let l = person(&e, "GET", LIST, None).await;+ assert_eq!((l["setting"].clone(), l["blocked_by"].clone(), l["suggestions"].clone()), (json!("off"), json!(["off"]), json!([])));}#[tokio::test]@@ -172,8 +210,10 @@ async fn the_scan_needs_the_board_and_a_time_zone() {discovery_on(&e).await;person(&e, "POST", "/api/settings", Some(json!({"timezone": ""}))).await;assert_eq!(person(&e, "POST", SCAN, None).await["blocked_by"], "no_timezone");+ assert_eq!(person(&e, "GET", LIST, None).await["blocked_by"], json!(["no_timezone"]));person(&e, "POST", "/api/settings", Some(json!({"mission_board": false, "timezone": TZ}))).await;assert_eq!(person(&e, "POST", SCAN, None).await["blocked_by"], "board_off");+ assert_eq!(person(&e, "POST", PREVIEW, None).await["blocked_by"], "board_off");}#[tokio::test]@@ -189,10 +229,13 @@ async fn a_scan_previews_a_habit_and_writes_nothing() {done_task(&e, &a, "Weekly digest", weeks_ago(w), "delegation", &a.id).await;done_task(&e, &a, "Weekly digest", weeks_ago(w), "mission", &a.id).await;done_task(&e, &a, "Weekly digest", weeks_ago(w), "chat", "person").await;+ // The person's own, but cancelled, or a fork of another task+ let cancelled = ended_task(&e, &a, "Weekly backup", weeks_ago(w), "person", "person", "cancelled", None).await;+ ended_task(&e, &a, "Weekly cleanup", weeks_ago(w), "person", "person", "verified", Some(&cancelled)).await;}let before: Vec<i64> = written_rows(&e).await;- let v = person(&e, "POST", SCAN, None).await;+ let v = person(&e, "POST", PREVIEW, None).await;assert_eq!((v["blocked_by"].clone(), v["preview"].clone(), v["timezone"].clone()), (Value::Null, json!(true), json!(TZ)), "{v}");assert_eq!(titles(&v, "offered"), ["Weekly report"], "{v}");let o = &v["offered"][0];@@ -213,7 +256,7 @@ async fn a_scan_previews_a_habit_and_writes_nothing() {assert_eq!(written_rows(&e).await, before);assert_eq!(before[..3], [0, 0, 0]);// And the same again- assert_eq!(person(&e, "POST", SCAN, None).await, v);+ assert_eq!(person(&e, "POST", PREVIEW, None).await, v);}/// Rows in routine_suggestions, routine_suggestion_events, routines and settings.@@ -268,6 +311,10 @@ async fn settings_are_checked() {let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(bad.clone())).await;assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}: {v}");}+ // Not a number at all: refused before anything is saved+ let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(json!({"automation_discovery_daily_cap": "abc"}))).await;+ assert!(status.is_client_error(), "{status} {v}");+ assert_eq!(person(&e, "GET", "/api/settings", None).await["automation_discovery_daily_cap"], 2);person(&e, "POST", "/api/settings", Some(json!({"automation_discovery": "on", "automation_discovery_daily_cap": 0}))).await;let s = person(&e, "GET", "/api/settings", None).await;assert_eq!((s["automation_discovery"].as_str(), s["automation_discovery_daily_cap"].as_i64()), (Some("on"), Some(0)));@@ -283,3 +330,313 @@ async fn a_daily_cap_of_zero_offers_nothing() {assert!(v["offered"].as_array().unwrap().is_empty());assert_eq!(v["skipped"][0]["reason"], "capped");}++// Step 3: offers that are kept, Accept, Dismiss, the hourly scan++/// Six weekly asks of `title` by `owner`, at 09:00 Berlin, the last on `last`.+async fn mondays(e: &Env, owner: &Kwant, title: &str, last: NaiveDate) {+ for w in 0..6 {+ let at = berlin(last - Duration::weeks(w), 9, 0);+ done_task(e, owner, &format!("{title} {}", at.date_naive()), at, "person", "person").await;+ }+}++fn berlin(d: NaiveDate, h: u32, m: u32) -> DateTime<Utc> {+ local_instant(TZ, d, NaiveTime::from_hms_opt(h, m, 0).unwrap()).unwrap().unwrap()+}++fn day(s: &str) -> NaiveDate {+ NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()+}++/// A habit on a weekday of its own (`k` days before today's), for its own bot.+async fn habit_on(e: &Env, k: i64, name: &str) -> Kwant {+ let b = bot(e, name).await;+ for w in 1..=6 {+ let at = weeks_ago(w) - Duration::days(k);+ done_task(e, &b, &format!("{name} status digest {}", at.date_naive()), at, "person", "person").await;+ }+ b+}++async fn live(e: &Env) -> i64 {+ sqlx::query_as::<_, (i64,)>("SELECT COUNT(*) FROM routine_suggestions WHERE status = 'offered'").fetch_one(&e.pool).await.unwrap().0+}++async fn events(e: &Env, suggestion: &str) -> Vec<(String, String)> {+ sqlx::query_as("SELECT kind, actor FROM routine_suggestion_events WHERE suggestion_id = ? ORDER BY id").bind(suggestion).fetch_all(&e.pool).await.unwrap()+}++fn suggested(rx: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> Vec<(String, String)> {+ let mut out = Vec::new();+ while let Ok(ev) = rx.try_recv() {+ if let RuntimeEvent::Notify { kind, title, body, .. } = ev {+ if kind == "automation_suggested" {+ out.push((title, body));+ }+ }+ }+ out+}++#[tokio::test]+async fn a_scan_keeps_one_offer_per_habit_and_notifies_once() {+ 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 v = person(&e, "POST", SCAN, None).await;+ assert_eq!((v["preview"].clone(), titles(&v, "offered")), (json!(false), vec!["Weekly report".to_string()]), "{v}");+ let o = &v["offered"][0];+ let id = o["id"].as_str().unwrap().to_string();+ assert!(id.starts_with("sug_"), "{o}");+ assert_eq!(o["status"], "offered");+ assert_eq!(o["sources"].as_array().unwrap().len(), 6, "{o}");+ assert_eq!(o["permissions"]["payments_ask"], true);+ assert!(o["permissions"]["tier_label"].as_str().is_some(), "{o}");+ assert!(o["first_run_text"].as_str().unwrap().ends_with(TZ));+ assert_eq!(events(&e, &id).await, [("offered".to_string(), "kwant".to_string())]);+ let n = suggested(&mut rx);+ assert_eq!(n.len(), 1, "{n:?}");+ assert_eq!(n[0].0, "Suggested routine: Weekly report");+ assert!(n[0].1.starts_with("Ana could do this"), "{n:?}");++ // Again: the live offer stays the one, no second notification+ let v = person(&e, "POST", SCAN, None).await;+ assert!(v["offered"].as_array().unwrap().is_empty(), "{v}");+ assert_eq!(v["skipped"][0]["reason"], "already_offered");+ assert_eq!(live(&e).await, 1);+ assert!(suggested(&mut rx).is_empty());++ let l = person(&e, "GET", LIST, None).await;+ assert_eq!((l["setting"].clone(), l["blocked_by"].clone()), (json!("on"), json!([])));+ assert_eq!(l["suggestions"].as_array().unwrap().iter().map(|s| s["id"].clone()).collect::<Vec<_>>(), [json!(id)]);+ assert!(l["last_scan_at"].is_string(), "{l}");+ assert_eq!(l["stats"]["offered_30d"], 1, "{l}");+ // While scans can't run, live offers are hidden+ person(&e, "POST", "/api/settings", Some(json!({"automation_discovery": "off"}))).await;+ assert_eq!(person(&e, "GET", LIST, None).await["suggestions"], json!([]));+ let (status, _) = call(&e.app, "GET", &format!("{LIST}?status=maybe"), None, None).await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+}++#[tokio::test]+async fn accept_makes_the_routine_once() {+ 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();++ // Without a key nothing happens+ let (status, _, v) = call_with(&e.app, "POST", &format!("{LIST}/{id}/accept"), None, None, Some(json!({}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");+ // Out-of-range check, unknown field, another space: refused, nothing made+ assert_eq!(accept(&e, &id, "k0", json!({"keep_checks": [3]})).await.0, StatusCode::UNPROCESSABLE_ENTITY);+ assert!(accept(&e, &id, "k0b", json!({"surprise": 1})).await.0.is_client_error());+ let (status, _, _) = call_with(&e.app, "POST", &format!("{LIST}/{id}/accept?space=spc_other"), None, Some("k0c"), Some(json!({}))).await;+ assert!(status.is_client_error(), "{status}");+ assert_eq!(count(&e, "routines").await, 0);++ let (status, _, v) = accept(&e, &id, "k1", json!({})).await;+ assert_eq!(status, StatusCode::CREATED, "{v}");+ let r = &v["routine"];+ assert_eq!((r["origin"].clone(), r["suggestion_id"].clone(), r["enabled"].clone()), (json!("discovery"), json!(id), json!(true)), "{r}");+ assert_eq!(r["kwant_id"], a.id);+ assert_eq!(r["checks"], json!([{"kind": "file_exists", "spec": {"path": "reports/weekly.md"}, "required": true}]));+ assert_eq!(r["acceptance"], "The report is in the shared folder");+ assert!(v["first_run_text"].as_str().unwrap().ends_with(TZ), "{v}");+ assert_eq!((v["suggestion"]["status"].clone(), v["suggestion"]["routine_id"].clone()), (json!("accepted"), r["id"].clone()));++ // The same key replays it; another key, or Dismiss, finds it already accepted+ let (status, headers, again) = accept(&e, &id, "k1", json!({})).await;+ assert_eq!((status, again["routine"]["id"].clone()), (StatusCode::CREATED, r["id"].clone()));+ assert_eq!(headers.get("idempotent-replayed").and_then(|h| h.to_str().ok()), Some("true"));+ let (status, _, v) = accept(&e, &id, "k2", json!({})).await;+ assert_eq!((status, v["status"].clone(), v["routine_id"].clone()), (StatusCode::CONFLICT, json!("accepted"), r["id"].clone()), "{v}");+ let (status, v) = call(&e.app, "POST", &format!("{LIST}/{id}/dismiss"), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT, "{v}");+ assert_eq!(count(&e, "routines").await, 1);+ assert_eq!(events(&e, &id).await.iter().map(|e| e.0.as_str()).collect::<Vec<_>>(), ["offered", "accepted"]);++ // The routine now covers the habit+ let v = person(&e, "POST", SCAN, None).await;+ assert_eq!(v["skipped"][0]["reason"], "covered", "{v}");+ // Switching it off and on is in the suggestion's history+ let rid = r["id"].as_str().unwrap();+ person(&e, "PATCH", &format!("/api/routines/{rid}"), Some(json!({"enabled": false}))).await;+ person(&e, "PATCH", &format!("/api/routines/{rid}"), Some(json!({"enabled": true}))).await;+ assert_eq!(events(&e, &id).await.iter().map(|e| e.0.as_str()).collect::<Vec<_>>(), ["offered", "accepted", "disabled", "enabled"]);+ let (status, v) = call(&e.app, "GET", &format!("{LIST}?status=accepted"), None, None).await;+ assert_eq!((status, v["suggestions"].as_array().unwrap().len()), (StatusCode::OK, 1));+}++#[tokio::test]+async fn dismiss_cools_the_habit_off_and_accept_is_refused() {+ 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 (status, v) = call(&e.app, "POST", &format!("{LIST}/{id}/dismiss?space=spc_other"), None, None).await;+ assert!(status.is_client_error(), "{v}");+ let v = person(&e, "POST", &format!("{LIST}/{id}/dismiss"), None).await;+ assert_eq!(v["suggestion"]["status"], "dismissed");+ let until = DateTime::parse_from_rfc3339(v["suggestion"]["cooldown_until"].as_str().unwrap()).unwrap();+ assert!((until.with_timezone(&Utc) - Utc::now() - Duration::days(30)).num_minutes().abs() < 5, "{v}");++ let (status, _, v) = accept(&e, &id, "k1", json!({})).await;+ assert_eq!((status, v["status"].clone()), (StatusCode::CONFLICT, json!("dismissed")), "{v}");+ assert_eq!(count(&e, "routines").await, 0);+ let v = person(&e, "POST", SCAN, None).await;+ assert_eq!((v["offered"].clone(), v["skipped"][0]["reason"].clone()), (json!([]), json!("cooling_off")), "{v}");+ let (status, _) = call(&e.app, "POST", &format!("{LIST}/sug_nope/dismiss"), None, None).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn accepted_days_later_the_first_run_is_the_next_slot() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ let space = SpaceId::default_space();+ mondays(&e, &a, "Weekly report", day("2026-10-12")).await;+ mondays(&e, &a, "Send invoices", day("2026-10-12")).await;+ // Offered on Monday 12 Oct, after that day's asks: first run the Monday after+ let monday = berlin(day("2026-10-12"), 10, 0);+ let stored = discovery::scan_space(&e.state, &space, TZ, monday).await.unwrap();+ assert_eq!(stored.offered.len(), 2, "{stored:?}");+ let rows = e.state.db.list_suggestions(space.as_str(), Some("offered")).await.unwrap();+ assert!(rows.iter().all(|r| r.first_run_at == berlin(day("2026-10-19"), 9, 0)));+ let id = |name: &str| rows.iter().find(|r| r.name == name).unwrap().id.clone();++ // Accepted on Wednesday 21 Oct, after the 19th passed: Monday 26 Oct (winter time by then)+ let wed = berlin(day("2026-10-21"), 15, 0);+ let v = discovery::accept_at(&e.state, None, &id("Weekly report"), AcceptBody::default(), wed).await.unwrap();+ assert_eq!(v["routine"]["next_run_at"], json!(berlin(day("2026-10-26"), 9, 0)), "{v}");+ assert_eq!(v["first_run_text"], v["suggestion"]["first_run_text"]);+ // Moved to Thursdays: the next Thursday+ let body = AcceptBody { schedule: Some(json!({"type": "weekly", "time": "09:00", "weekdays": ["thu"], "tz": TZ})), ..Default::default() };+ let v = discovery::accept_at(&e.state, None, &id("Send invoices"), body, wed).await.unwrap();+ assert_eq!(v["routine"]["next_run_at"], json!(berlin(day("2026-10-22"), 9, 0)), "{v}");+ assert_eq!(v["routine"]["schedule"]["weekdays"], json!(["thu"]));+}++#[tokio::test]+async fn accept_takes_the_persons_edits() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ let b = bot(&e, "Ben").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 body = json!({"name": "Friday report", "instructions": "Write it", "kwant_id": b.id, "keep_checks": [], "acceptance": null});+ let (status, _, v) = accept(&e, &id, "k1", body).await;+ assert_eq!(status, StatusCode::CREATED, "{v}");+ let r = &v["routine"];+ assert_eq!((r["name"].clone(), r["instructions"].clone(), r["kwant_id"].clone()), (json!("Friday report"), json!("Write it"), json!(b.id)));+ assert_eq!((r["checks"].clone(), r["acceptance"].clone(), r["channel_id"].clone(), r["thread_id"].clone()), (json!([]), Value::Null, Value::Null, Value::Null));+}++#[tokio::test]+async fn the_hourly_scan_keeps_the_cap_and_five_live() {+ let e = setup().await;+ person(&e, "POST", "/api/settings", Some(json!({"automation_discovery": "on", "automation_discovery_daily_cap": 10}))).await;+ for (k, name) in ["Ana", "Ben", "Cleo", "Dan", "Eve", "Fay", "Gus"].iter().enumerate() {+ habit_on(&e, k as i64, name).await;+ }+ let now = Utc::now();+ assert_eq!(discovery::tick(&e.state, now).await, 5);+ assert_eq!(live(&e).await, 5);+ // Within the hour nothing runs; after it, the space is full+ assert_eq!(discovery::tick(&e.state, now + Duration::minutes(30)).await, 0);+ assert_eq!(discovery::tick(&e.state, now + Duration::minutes(61)).await, 0);+ assert_eq!(live(&e).await, 5);+}++#[tokio::test]+async fn the_daily_cap_holds_across_scans() {+ 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 now = Utc::now();+ assert_eq!(discovery::tick(&e.state, now).await, 2);+ assert_eq!(discovery::tick(&e.state, now + Duration::minutes(61)).await, 0);+ let v = person(&e, "POST", SCAN, None).await;+ assert!(v["offered"].as_array().unwrap().is_empty() && v["skipped"].as_array().unwrap().iter().any(|s| s["reason"] == "capped"), "{v}");+ assert_eq!(live(&e).await, 2);+ assert_eq!(discovery::tick(&e.state, now + Duration::hours(25)).await, 2);+ assert_eq!(live(&e).await, 4);+ assert_eq!(suggested(&mut rx).len(), 4);+}++#[tokio::test]+async fn a_live_offer_ends_when_its_habit_does() {+ let e = setup().await;+ let a = bot(&e, "Ana").await;+ let space = SpaceId::default_space();+ mondays(&e, &a, "Weekly report", day("2026-10-12")).await;+ let monday = berlin(day("2026-10-12"), 10, 0);+ let id = discovery::scan_space(&e.state, &space, TZ, monday).await.unwrap().offered[0].clone();+ // Three Mondays later without an ask, it has stopped+ let later = berlin(day("2026-11-03"), 10, 0);+ let s = discovery::scan_space(&e.state, &space, TZ, later).await.unwrap();+ assert_eq!((s.expired.clone(), s.offered.len()), (vec![id.clone()], 0), "{s:?}");+ assert_eq!(e.state.db.get_suggestion(&id).await.unwrap().unwrap().status, "expired");+ assert_eq!(events(&e, &id).await.iter().map(|e| e.0.as_str()).collect::<Vec<_>>(), ["offered", "expired"]);+}++#[tokio::test]+async fn bots_get_403_on_every_route() {+ 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 t = token(&e, &a).await;+ for (method, uri) in [("GET", LIST.to_string()), ("POST", SCAN.to_string()), ("POST", PREVIEW.to_string()), ("POST", format!("{LIST}/{id}/accept")), ("POST", format!("{LIST}/{id}/dismiss"))] {+ let (status, _, v) = call_with(&e.app, method, &uri, Some(&t), Some("k"), Some(json!({}))).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "{method} {uri}: {v}");+ }+ assert_eq!((count(&e, "routines").await, live(&e).await), (0, 1));+}++async fn tool(e: &Env, token: &str, name: &str, args: Value) -> (String, bool) {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "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"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"].as_bool().unwrap_or(false))+}++#[tokio::test]+async fn undoing_a_bots_delete_keeps_the_routine_discovered() {+ 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 r = accept(&e, &id, "k1", json!({})).await.2["routine"].clone();++ let t = token(&e, &a).await;+ let (text, failed) = tool(&e, &t, "routine_delete", json!({"routine": r["id"]})).await;+ assert!(!failed, "{text}");+ let s = e.state.db.get_suggestion(&id).await.unwrap().unwrap();+ assert!(s.routine_deleted_at.is_some());+ assert_eq!(events(&e, &id).await.last().unwrap().0, "deleted");+ // Deleted, the habit cools off rather than being offered again+ assert_eq!(person(&e, "POST", SCAN, None).await["skipped"][0]["reason"], "cooling_off");++ let actions = person(&e, "GET", "/api/bot-actions", None).await;+ let del = actions.as_array().unwrap().iter().find(|x| x["action"] == "routine_delete").unwrap().clone();+ let v = person(&e, "POST", &format!("/api/bot-actions/{}/undo", del["id"].as_str().unwrap()), None).await;+ assert_eq!(v["status"], "undone", "{v}");+ let back = person(&e, "GET", "/api/routines", None).await[0].clone();+ assert_eq!((back["origin"].clone(), back["suggestion_id"].clone()), (json!("discovery"), json!(id)), "{back}");+ let s = e.state.db.get_suggestion(&id).await.unwrap().unwrap();+ 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");+}diff --git a/tests/continuity_test.rs b/tests/continuity_test.rsindex 0b5fc7fd..c78ba8fd 100644--- a/tests/continuity_test.rs+++ b/tests/continuity_test.rs@@ -1569,7 +1569,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"])+ 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"]));let (status, _) = req(diff --git a/tests/import_test.rs b/tests/import_test.rsindex fd1fc4ef..86f6e55c 100644--- a/tests/import_test.rs+++ b/tests/import_test.rs@@ -12,7 +12,7 @@ use kwnt::{broker::PermissionBroker,config::Config,db::{- models::{McpServer, NewMessage},+ models::{McpServer, NewKwant, NewMessage},spaces::{NewSpace, SpaceId},Database,},@@ -705,3 +705,48 @@ async fn pasted_schedule_with_a_time_zone_keeps_it_and_stays_paused() {assert_eq!(stored, json!({ "type": "cron", "expression": "0 7 * * *", "tz": "Europe/Berlin" }));assert!(rows.iter().all(|r| !r.enabled && r.next_run_at.is_none()), "routines still arrive paused");}++/// A routine's class and acceptance travel in a bundle; its checks only when no spec holds a+/// secret, and an import never applies them (the person approves checks).+#[tokio::test]+async fn routine_outcomes_are_exported_and_checks_only_when_secret_free() {+ let e = setup().await;+ let a = new_space(&e, "Source").await;+ let b = new_space(&e, "Copy").await;+ let bot = NewKwant { name: "Ana".into(), title: "Reporter".into(), persona_prompt: String::new(), soul: String::new(), avatar_sprite: "s".into(), driver_type: "cli".into(), preferred_model: "codex".into() };+ let k = e.state.db.create_kwant(&SpaceId::new(a.clone()), &bot).await.unwrap();+ let routine = |name: &str, check: Value| {+ json!({+ "kwant_id": k.id, "name": name, "instructions": "Write the weekly report",+ "schedule": {"type": "weekly", "time": "09:00", "weekdays": ["mon"], "tz": "UTC"}, "enabled": false,+ "task_class": "reporting", "acceptance": "report.md exists", "checks": [check],+ })+ };+ let clean = json!({"kind": "file_exists", "spec": {"path": "report.md"}});+ let secret = json!({"kind": "command", "spec": {"command": "curl -H 'Authorization: Bearer sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789' https://example.com"}});+ for (name, check) in [("Clean", clean.clone()), ("Secret", secret)] {+ let (status, v) = json_call(&e.app, "POST", &format!("/api/routines?space={a}"), routine(name, check)).await;+ assert_eq!(status, StatusCode::CREATED, "{v}");+ }+ let (status, bundle) = get(&e.app, &format!("/api/export?space={a}")).await;+ assert_eq!(status, StatusCode::OK, "{bundle}");+ let routines = bundle["bots"][0]["routines"].as_array().unwrap().clone();+ assert!(!bundle.to_string().contains("sk-ant-api03"), "{bundle}");+ let by = |n: &str| routines.iter().find(|r| r["name"] == n).unwrap().clone();+ assert_eq!((by("Clean")["task_class"].clone(), by("Clean")["acceptance"].clone()), (json!("reporting"), json!("report.md exists")));+ assert_eq!(by("Clean")["checks"], json!([{"kind": "file_exists", "spec": {"path": "report.md"}, "required": true}]));+ assert!(by("Secret").get("checks").is_none(), "{}", by("Secret"));+ assert_eq!(by("Secret")["task_class"], "reporting");++ let (status, p) = send(&e.app, "POST", &format!("/api/import/preview?space={b}&filename=space.kwant.json"), "application/octet-stream", bundle.to_string().into_bytes()).await;+ assert_eq!(status, StatusCode::OK, "{p}");+ assert!(p["warnings"].to_string().contains("checks weren't brought over"), "{}", p["warnings"]);+ let (status, v) = apply(&e.app, &b, &p["bundle"], &[]).await;+ assert_eq!(status, StatusCode::CREATED, "{v}");+ let (_, list) = get(&e.app, &format!("/api/routines?space={b}")).await;+ let list = list.as_array().unwrap();+ assert_eq!(list.len(), 2, "{list:?}");+ for r in list {+ assert_eq!((r["task_class"].clone(), r["acceptance"].clone(), r["checks"].clone()), (json!("reporting"), json!("report.md exists"), json!([])), "{r}");+ }+}