AnyBot/src/garden.rs

228 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 園丁: watching what goes wrong across every bot, so a mistake that keeps coming back is fixed
// once in AnyBot (or its settings) instead of being written into one more skill. Lauren Tan's
// gardener: watch → queue without fixing → group by cause → fix what repeats; one-offs need
// nothing. Two parts here: the queue of AnyBot's own problems the bots report (待改進), and the
// report a day and a week that reads the routines' runs and that queue.
use serde::{Deserialize, Serialize};
/// One of AnyBot's own problems a bot ran into (a tool that failed, a workaround it needed).
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct Improvement {
pub text: String,
/// Times it was reported (the same tool, or the same words).
pub count: u32,
/// Seconds since 1970, first and latest report.
pub first: i64,
pub last: i64,
/// Which bots reported it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub bots: Vec<String>,
}
/// Items kept in the queue (the oldest go first).
pub const MAX_IMPROVEMENTS: usize = 50;
/// Reports after which a problem counts as recurring (worth fixing, said in the report).
pub const RECURRING: u32 = 2;
/// The tool names a report mentions (words like browser_fill_contact): two reports about the
/// same tool are the same problem, however differently they were worded.
fn tools_named(text: &str) -> Vec<String> {
let mut v: Vec<String> = text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).filter(|w| w.contains('_') && w.len() > 3).map(|w| w.to_ascii_lowercase()).collect();
v.sort();
v.dedup();
v
}
fn plain(text: &str) -> String {
text.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_lowercase()
}
/// Queue a problem a bot reported: counted on an item about the same tool (or with the same
/// words), else added.
pub fn note_issue(list: &mut Vec<Improvement>, text: &str, bot: &str, now: i64) {
let text = text.trim();
if text.is_empty() {
return;
}
let tools = tools_named(text);
let same = |i: &Improvement| {
let theirs = tools_named(&i.text);
if !tools.is_empty() && !theirs.is_empty() {
tools.iter().any(|t| theirs.contains(t))
} else {
plain(&i.text) == plain(text)
}
};
match list.iter_mut().find(|i| same(i)) {
Some(i) => {
i.count += 1;
i.last = now;
if !bot.is_empty() && !i.bots.iter().any(|b| b == bot) {
i.bots.push(bot.to_string());
}
}
None => {
list.push(Improvement { text: text.to_string(), count: 1, first: now, last: now, bots: if bot.is_empty() { vec![] } else { vec![bot.to_string()] } });
let extra = list.len().saturating_sub(MAX_IMPROVEMENTS);
list.drain(..extra);
}
}
}
// ---------- the reports ----------
/// A run that took this many steps or more, with this share of them failing, went the long way.
const LONG_WAY_STEPS: u32 = 10;
const LONG_WAY_FAILED_PERCENT: u32 = 30;
/// Weekly: a routine worth a look — failing this share of its runs, or this heavy on average.
const WEEK_FAILED_PERCENT: u32 = 20;
const WEEK_AVG_STEPS: u32 = 60;
const WEEK_AVG_MINUTES: i64 = 30;
/// When the reports come (the person's time): the daily one on weekdays from 8:44, the weekly one
/// on Mondays from 8:49 — dr eggbot's transcript-healthcheck and routine-healthcheck.
pub const DAILY_AT: (u32, u32) = (8, 44);
pub const WEEKLY_AT: (u32, u32) = (8, 49);
/// One bot's routines, for the reports: (bot name, its routines).
pub type Fleet<'a> = Vec<(&'a str, &'a [crate::routines::Routine])>;
/// The day's look at what went wrong (since `since`): failed or cut-off runs, runs that went the
/// long way, routines AnyBot paused, problems that keep coming back. None when there is nothing
/// to say — a report with nothing in it trains people to skip it.
pub fn daily_report(fleet: &Fleet, issues: &[Improvement], since: i64) -> Option<String> {
use crate::routines::{describe_run, RunOutcome};
let mut lines = vec![];
for (bot, routines) in fleet {
for r in routines.iter() {
if r.paused && !r.paused_why.is_empty() {
lines.push(format!("· {bot}「{}」已暫停:{}", r.title, r.paused_why));
continue;
}
for run in r.runs.iter().filter(|x| x.started >= since) {
let bad = matches!(run.outcome, RunOutcome::Failed | RunOutcome::Interrupted);
let long_way = run.steps >= LONG_WAY_STEPS && run.failed_steps * 100 >= run.steps * LONG_WAY_FAILED_PERCENT;
if bad || long_way {
let why = if bad { "" } else { "(很多步沒成功)" };
lines.push(format!("· {bot}「{}」{}{why}", r.title, describe_run(run, &r.schedule.timezone)));
}
}
}
}
for i in issues.iter().filter(|i| i.count >= RECURRING && i.last >= since) {
lines.push(format!("· AnyBot 待改進(×{}):{}", i.count, i.text));
}
let recurring = issues.iter().any(|i| i.count >= RECURRING && i.last >= since);
let tip = if recurring { "\n(重複出現的待改進:修好那個工具,或把它的用法和陷阱補進 AnyBot 功能地圖。)" } else { "" };
(!lines.is_empty()).then(|| format!("園丁:過去一天有 {} 件事值得看一下。\n{}{tip}", lines.len(), lines.join("\n")))
}
/// The week's look at what the routines cost (since `since`): the ones failing often or heavy
/// on average, with their runs, steps and minutes. None when every routine is fine.
pub fn weekly_report(fleet: &Fleet, since: i64) -> Option<String> {
use crate::routines::RunOutcome;
let mut lines = vec![];
for (bot, routines) in fleet {
for r in routines.iter() {
let runs: Vec<_> = r.runs.iter().filter(|x| x.started >= since && x.outcome != RunOutcome::Running).collect();
if runs.is_empty() {
continue;
}
let n = runs.len() as u32;
let failed = runs.iter().filter(|x| matches!(x.outcome, RunOutcome::Failed | RunOutcome::Interrupted)).count() as u32;
let steps: u32 = runs.iter().map(|x| x.steps).sum();
let minutes: i64 = runs.iter().map(|x| ((x.ended - x.started).max(0) + 59) / 60).sum();
let heavy = steps / n >= WEEK_AVG_STEPS || minutes / n as i64 >= WEEK_AVG_MINUTES;
if failed * 100 >= n * WEEK_FAILED_PERCENT || heavy {
lines.push(format!("· {bot}「{}」跑了 {n} 次,{failed} 次沒成功;共 {steps} 步、{minutes} 分鐘(平均每次 {} 步、{} 分鐘)", r.title, steps / n, minutes / n as i64));
}
}
}
(!lines.is_empty()).then(|| format!("園丁:這週有 {} 條例行任務值得調整(失敗多或很耗時)。\n{}", lines.len(), lines.join("\n")))
}
/// Whether a report is due now: its time of day has come in the person's zone, on its day, and
/// it hasn't been made today (`last` = the day it was last made, as yyyymmdd).
pub fn due(now: i64, tz: chrono_tz::Tz, at: (u32, u32), mondays_only: bool, last: u32) -> Option<u32> {
use chrono::{Datelike, TimeZone, Timelike};
let t = chrono::Utc.timestamp_opt(now, 0).single()?.with_timezone(&tz);
let day = t.year() as u32 * 10_000 + t.month() * 100 + t.day();
let weekday_ok = if mondays_only { t.weekday() == chrono::Weekday::Mon } else { t.weekday().num_days_from_monday() < 5 };
(weekday_ok && (t.hour(), t.minute()) >= at && day != last).then_some(day)
}
#[cfg(test)]
mod tests {
use super::*;
fn routine(title: &str, runs: Vec<crate::routines::RoutineRun>) -> crate::routines::Routine {
let s = crate::routines::Schedule { frequency: crate::routines::Frequency::Daily, interval: 1, days_of_week: vec![], month_day: None, weekday_of_month: None, month: None, time: "17:00".into(), timezone: "Asia/Taipei".into(), once: false, flexible: false };
crate::routines::Routine { id: 1, title: title.into(), prompt: String::new(), schedule: s, paused: false, created_at: 0, last_run: None, next_run: None, computer: String::new(), trigger: None, runs, paused_why: String::new(), target_sends: 0 }
}
fn run(started: i64, outcome: crate::routines::RunOutcome, steps: u32, failed: u32) -> crate::routines::RoutineRun {
crate::routines::RoutineRun { started, ended: started + 600, outcome, note: "原因".into(), steps, failed_steps: failed, sent: 0, sends: vec![] }
}
#[test]
fn the_daily_report_says_only_what_went_wrong_and_nothing_on_a_good_day() {
use crate::routines::RunOutcome::*;
let fine = [routine("貓咪海巡", vec![run(1_000, Succeeded, 40, 1)])];
let fleet: Fleet = vec![("賴桑", &fine)];
assert_eq!(daily_report(&fleet, &[], 0), None, "nothing to say, nothing said");
let rough = [routine("主婦海巡", vec![run(500, Failed, 9, 9), run(1_000, Succeeded, 170, 160), run(2_000, Succeeded, 30, 2)])];
let fleet: Fleet = vec![("賴桑", &rough)];
let issues = vec![Improvement { text: "browser_fill_contact 被誤用".into(), count: 3, first: 0, last: 1_500, bots: vec![] }];
let r = daily_report(&fleet, &issues, 800).unwrap();
assert!(r.contains("2 件事"), "{r}");
assert!(r.contains("170 步,160 步沒成功") && r.contains("很多步沒成功"), "{r}");
assert!(!r.contains("9 步"), "before the window: {r}");
assert!(r.contains("待改進(×3)"));
}
#[test]
fn the_weekly_report_names_the_costly_routines_only() {
use crate::routines::RunOutcome::*;
let a = [routine("拾日海巡", vec![run(100, Succeeded, 120, 10), run(200, Succeeded, 100, 5)])];
let b = [routine("早報", vec![run(100, Succeeded, 8, 0)])];
let fleet: Fleet = vec![("賴桑", &a), ("小幫手", &b)];
let w = weekly_report(&fleet, 0).unwrap();
assert!(w.contains("拾日海巡") && w.contains("跑了 2 次") && w.contains("平均每次 110 步") && !w.contains("早報"), "{w}");
let quiet: Fleet = vec![("小幫手", &b)];
assert_eq!(weekly_report(&quiet, 0), None);
}
#[test]
fn reports_come_once_a_day_after_their_time() {
let tz = chrono_tz::Asia::Taipei;
let at = |d: u32, h: u32, m: u32| tz.with_ymd_and_hms(2026, 11, d, h, m, 0).unwrap().timestamp();
use chrono::TimeZone;
// Mon 2026-11-16 08:43: not yet; 08:44: due; made today: not again. Saturday: no.
assert_eq!(due(at(16, 8, 43), tz, DAILY_AT, false, 0), None);
assert_eq!(due(at(16, 8, 44), tz, DAILY_AT, false, 0), Some(20261116));
assert_eq!(due(at(16, 15, 0), tz, DAILY_AT, false, 20261116), None);
assert_eq!(due(at(14, 9, 0), tz, DAILY_AT, false, 0), None);
// The weekly one: Mondays only.
assert_eq!(due(at(16, 8, 50), tz, WEEKLY_AT, true, 0), Some(20261116));
assert_eq!(due(at(17, 8, 50), tz, WEEKLY_AT, true, 0), None);
}
#[test]
fn the_same_tool_problem_is_counted_not_repeated() {
let mut q = vec![];
note_issue(&mut q, "Bot 一直誤用 browser_fill_contact 來打字", "賴桑", 10);
note_issue(&mut q, "browser_fill_contact 回「沒有開著的分頁」,其實分頁開著", "拾日", 20);
note_issue(&mut q, "多行留言只能用剪貼簿貼上", "賴桑", 30);
note_issue(&mut q, "多行留言只能用剪貼簿貼上。", "賴桑", 40);
note_issue(&mut q, " ", "x", 50);
assert_eq!(q.len(), 2);
assert_eq!((q[0].count, q[0].first, q[0].last), (2, 10, 20));
assert_eq!(q[0].bots, vec!["賴桑", "拾日"]);
assert_eq!(q[1].count, 2, "the same words, punctuation aside");
for i in 0..60 {
note_issue(&mut q, &format!("問題 {i}"), "", 100 + i);
}
assert_eq!(q.len(), MAX_IMPROVEMENTS);
}
}