AnyBot/src/garden.rs

226 lines
12 KiB
Rust
Raw Normal View History

feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
// 園丁: 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));
}
(!lines.is_empty()).then(|| format!("園丁:過去一天有 {} 件事值得看一下。\n{}", 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 };
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
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 }
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
}
fn run(started: i64, outcome: crate::routines::RunOutcome, steps: u32, failed: u32) -> crate::routines::RoutineRun {
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
crate::routines::RoutineRun { started, ended: started + 600, outcome, note: "原因".into(), steps, failed_steps: failed, sent: 0, sends: vec![] }
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
}
#[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);
}
}