fix: 「教我做」學的是聊天裡留著的那一次——稽核紀錄記下訊息的時間,重新產生後不再學到被換掉的那次
上一版用「訊息時間之後第一個開始的回合」找那一回合,但稽核紀錄沒存訊息自己的時間(還原時拿回合 開始的時間代替),而重新產生、重新傳送、重試是同一則訊息(同一個 at)再開一回合:最早的那次贏, 長按之後學到的是被換掉的第一次(審查者冷開重現:第一次 echo wrong、重新產生 echo right,教我做存了 echo wrong)。 - store:稽核紀錄的回合列多一欄 prompt_at(使用者那則訊息送出的時間);舊的 audit.db 開啟時 ALTER TABLE 加上,舊列留 NULL(讀成 0,不會被當成任何一則訊息)。records() 拆成 turn_starts(只讀回合 的第一行:說了什麼、什麼時候送的)和 turn_records(只讀選中的那一回合):原本是在畫面那條執行緒上、 拿著稽核紀錄的鎖,把 30 天內每一步的參數都讀出來。 - memory:taught_turn 先選回合——有 at 就只認 prompt.at 剛好等於它的回合、取最後一個(聊天顯示的那一次), 沒有就「找不到」,不再退回別的回合(插話的時間不會對上任何回合);沒帶 at 的舊手機頁面才取同樣的話 開始的最近一回合。skillify 只把那一回合的步驟做成技能。 - 跟自動學(replay_steps)共用同一份「重播不做的步驟」(never_replayed):教我做原本會留下 use_skill、 replay_skill、anybot_guide;computer_use_look、computer+action 是不存在的名字(工作紀錄記的是展開後的 computer_use_*),換成真的 computer_use_show。 - appctl:learned() 自己換成主 Bot(home_of)。從 apply() 進來本來就已經換過,這是讓它不靠呼叫的人。 - 功能地圖 replay.md:多一步「重新產生之後教我做」(長按 › 教我做,存的是 echo right);Bot 讀得到的 陷阱改寫:學的是那則訊息開始的、聊天裡留著的那一次,插話和 30 天以前的說找不到,舊手機頁面沒帶時間時 學什麼;丟掉的步驟加上讀說明或技能、重播。自動測試列上新測試。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在、ANYBOT_HF_BASE 連不到)全綠(675 過、46 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。新測試 appctl::after_regenerating_the_attempt_shown_is_learned、appctl::a_skill_learned_in_a_branch_is_the_main_bots、 store::an_older_trail_learns_when_messages_were_sent;memory 的 the_message_pressed_is_the_turn_learned 改成 重新產生和插話的情況、a_finished_turn_can_become_a_skill 加了 anybot_guide/use_skill/replay_skill、 store 的 the_trail_keeps_the_story… 改讀 turn_starts/turn_records。證明會擋:兩個 appctl 測試放進上一個 commit(4be6d3e)的程式碼跑都失敗(存了 echo wrong、主 Bot 沒拿到技能);把選回合改回「之後第一個、 沒有就最近的」、把三個名字拿出共用清單,memory 兩個測試都失敗;拿掉 ALTER,遷移測試失敗(no such column: prompt_at);放回去都過。verify-anybot 冷開照地圖寫的跑 replay.md 四步:做五步學會、重播填空格、 教我做(長按 › 選單)、重新產生之後教我做(手機按回答下面的「重新產生」,聊天只剩 echo right,存的 技能 steps 是 echo right >> sign.txt;sign.txt 裡兩次都有,因為兩次都真的跑了)都過。 未驗證: 已經有舊 audit.db 的真實資料夾升級——只用單元測試建一份沒有 prompt_at 欄的表驗證;舊版手機頁面 (不帶 at)只靠單元測試;「網站地圖」照地圖寫的走不到(要真的模型);真的手機的長按沒有測(用無頭 Chrome 的觸控事件代替);garden.md 這輪沒有重跑(這輪沒動待改進)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC
This commit is contained in:
parent
4be6d3e4d0
commit
2605445564
|
|
@ -26,15 +26,16 @@
|
||||||
- **做五步、學會**(covers `replay-learn`、`replay-steps`):指令:`$CTL model-reply 整理經驗 '{"save":true,"name":"記一筆","description":"在 log.txt 記一筆","instructions":"用 shell 在 log.txt 加一行。注意:一次一行。","replay":[9],"blanks":{"第五筆":"內容"},"tool_issues":[]}' && $CTL phone send '記五筆 [[call shell {"command":"sleep 4; echo 1"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 1' && $CTL phone send '[[call shell {"command":"sleep 4; echo 2"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 2' && $CTL phone send '[[call shell {"command":"sleep 4; echo 3"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 3' && $CTL phone send '[[call shell {"command":"sleep 4; echo 4"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 4' && $CTL phone send '[[call shell {"command":"echo 第五筆 >> log.txt"}]]' && $CTL phone wait-text '學會了新做法「記一筆」' --in '#msgs' 60 && $CTL phone shot replay-learned && $CTL model 'select(.rule) | .user_full | split(":\n- ")[0]' && $CTL state '.skills[] | select(.name == "記一筆") | .steps'`。看到:一輪五個「執行指令」,回覆下面「(學會了新做法「記一筆」,下次做這件事會照著做。)」;回頭看的請求列了每一步(插話也各佔一號,第五步是 9)和「已經有的技能」;技能只留那一步,「第五筆」變成 `{{內容}}`。
|
- **做五步、學會**(covers `replay-learn`、`replay-steps`):指令:`$CTL model-reply 整理經驗 '{"save":true,"name":"記一筆","description":"在 log.txt 記一筆","instructions":"用 shell 在 log.txt 加一行。注意:一次一行。","replay":[9],"blanks":{"第五筆":"內容"},"tool_issues":[]}' && $CTL phone send '記五筆 [[call shell {"command":"sleep 4; echo 1"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 1' && $CTL phone send '[[call shell {"command":"sleep 4; echo 2"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 2' && $CTL phone send '[[call shell {"command":"sleep 4; echo 3"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 3' && $CTL phone send '[[call shell {"command":"sleep 4; echo 4"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]?] | length == 4' && $CTL phone send '[[call shell {"command":"echo 第五筆 >> log.txt"}]]' && $CTL phone wait-text '學會了新做法「記一筆」' --in '#msgs' 60 && $CTL phone shot replay-learned && $CTL model 'select(.rule) | .user_full | split(":\n- ")[0]' && $CTL state '.skills[] | select(.name == "記一筆") | .steps'`。看到:一輪五個「執行指令」,回覆下面「(學會了新做法「記一筆」,下次做這件事會照著做。)」;回頭看的請求列了每一步(插話也各佔一號,第五步是 9)和「已經有的技能」;技能只留那一步,「第五筆」變成 `{{內容}}`。
|
||||||
- **重播、填空格**(covers `replay-steps`):先不給空格,再給;再看設定 › 整合 的清單。指令:`$CTL phone send '[[call replay_skill {"name":"記一筆"}]]' && $CTL phone wait-text '「記一筆」每次要填:內容' --in '#msgs' && $CTL phone send '[[call replay_skill {"name":"記一筆","values":{"內容":"重播的一筆"}}]]' && $CTL phone wait-text '重播「記一筆」做完了' --in '#msgs' && $CTL phone shot replay-run && $CTL botfile log.txt && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.via | test("重播")) | .tools[].detail]' && $CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="integrations"]' && $CTL phone wait-text '可重播 1 步' --in '#list'`。看到:第一次「「記一筆」每次要填:內容。用 values…」;第二次(電腦版「正在照技能重做:記一筆」)「執行指令 echo 重播的一筆 >> log.txt」沒經過模型(那一則標「fake-model(重播)」),回覆帶「(重播「記一筆」做完了,共 1 步。…)」;log.txt 多一行「重播的一筆」;清單裡記一筆標「可重播 1 步」。
|
- **重播、填空格**(covers `replay-steps`):先不給空格,再給;再看設定 › 整合 的清單。指令:`$CTL phone send '[[call replay_skill {"name":"記一筆"}]]' && $CTL phone wait-text '「記一筆」每次要填:內容' --in '#msgs' && $CTL phone send '[[call replay_skill {"name":"記一筆","values":{"內容":"重播的一筆"}}]]' && $CTL phone wait-text '重播「記一筆」做完了' --in '#msgs' && $CTL phone shot replay-run && $CTL botfile log.txt && $CTL api GET /api/bots/1 --jq '[.messages[] | select(.via | test("重播")) | .tools[].detail]' && $CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="integrations"]' && $CTL phone wait-text '可重播 1 步' --in '#list'`。看到:第一次「「記一筆」每次要填:內容。用 values…」;第二次(電腦版「正在照技能重做:記一筆」)「執行指令 echo 重播的一筆 >> log.txt」沒經過模型(那一則標「fake-model(重播)」),回覆帶「(重播「記一筆」做完了,共 1 步。…)」;log.txt 多一行「重播的一筆」;清單裡記一筆標「可重播 1 步」。
|
||||||
- **教我做**(covers `replay-teach`):做一回合、等它做完,長按自己那則訊息 ›「教我做(學這一回合)」。指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '寫教學 [[call shell {"command":"echo 教 >> teach.txt"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("teach"))] | length == 1' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone long-press '.m.user .bub' --text 寫教學 && $CTL phone wait-text 教我做 --in '#sheet-in' && $CTL phone shot replay-teach-menu && $CTL phone click '#sheet-in .opt' --text 教我做 && $CTL phone wait-text 已存成技能 --in '#toast' && $CTL phone shot replay-teach-saved && $CTL api GET /api/settings --jq '[.skills[] | select(.description | startswith("示範學會:寫教學")) | {name, description, steps}]'`。看到:選單有表情、「複製」「引用回覆」「教我做(學這一回合)」;按了跳「已存成技能,下次說名字就會照做」;多一個技能「寫教學 [[call shell {"comma」,steps 1,說明照那一回合原本的字「示範學會:寫教學 …echo 教 >> teach.txt…」——那一回合已經做完,照樣找得到。
|
- **教我做**(covers `replay-teach`):做一回合、等它做完,長按自己那則訊息 ›「教我做(學這一回合)」。指令:`$CTL phone open --listed && $CTL phone click '.row[data-bot="1"]' && $CTL phone send '寫教學 [[call shell {"command":"echo 教 >> teach.txt"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("teach"))] | length == 1' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone long-press '.m.user .bub' --text 寫教學 && $CTL phone wait-text 教我做 --in '#sheet-in' && $CTL phone shot replay-teach-menu && $CTL phone click '#sheet-in .opt' --text 教我做 && $CTL phone wait-text 已存成技能 --in '#toast' && $CTL phone shot replay-teach-saved && $CTL api GET /api/settings --jq '[.skills[] | select(.description | startswith("示範學會:寫教學")) | {name, description, steps}]'`。看到:選單有表情、「複製」「引用回覆」「教我做(學這一回合)」;按了跳「已存成技能,下次說名字就會照做」;多一個技能「寫教學 [[call shell {"comma」,steps 1,說明照那一回合原本的字「示範學會:寫教學 …echo 教 >> teach.txt…」——那一回合已經做完,照樣找得到。
|
||||||
|
- **重新產生之後教我做**(covers `replay-teach`):送一句、做完,指定重做時換一個指令,按回答下面的「重新產生」,再長按那則訊息 ›「教我做」。指令:`$CTL phone send '簽到 [[call shell {"command":"echo wrong >> sign.txt"}]]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("wrong"))] | length == 1' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL model-reply '簽到 [[call' '[[call shell {"command":"echo right >> sign.txt"}]]' && $CTL phone click '[data-regen]' && $CTL wait-api /api/bots/1 '[.messages[].tools[]? | select(.detail | test("right"))] | length == 1' && $CTL wait-api '/api/state?since=0' '.bots[0].busy == false' && $CTL phone long-press '.m.user .bub' --text 簽到 && $CTL phone click '#sheet-in .opt' --text 教我做 && $CTL phone wait-text 已存成技能 --in '#toast' && $CTL phone shot replay-teach-regenerated && $CTL state '[.skills[] | select(.description | startswith("示範學會:簽到")) | .steps[].args]'`。看到:聊天裡留下的是重做的那次(「執行指令 echo right >> sign.txt」);存的技能只有一步,是 `echo right >> sign.txt`——學的是聊天裡留著的那一次,不是被換掉的第一次(說明照那則訊息的字,所以還寫著 wrong)。
|
||||||
- **網站地圖**(covers `replay-map`):指令:走不到——地圖的內容是真的模型照回頭看的提示寫的(假模型照劇本回)。看到:最接近的真路是第一步:回頭看的請求帶著「已經有的技能」,同名就合併;寫法靠自動測試。
|
- **網站地圖**(covers `replay-map`):指令:走不到——地圖的內容是真的模型照回頭看的提示寫的(假模型照劇本回)。看到:最接近的真路是第一步:回頭看的請求帶著「已經有的技能」,同名就合併;寫法靠自動測試。
|
||||||
- 自動測試:`cargo test memory::`(`a_long_enough_job_is_looked_back_on`、`what_differs_each_time_becomes_a_blank_filled_at_replay`、`the_phones_plain_words_find_the_turn`、`the_message_pressed_is_the_turn_learned`)、`cargo test a_turn_that_has_ended_can_still_be_taught`、`cargo test a_skill_is_replayed_without_the_model_in_between`、`cargo test skills::`、`cargo test agent::`。
|
- 自動測試:`cargo test memory::`(`a_long_enough_job_is_looked_back_on`、`what_differs_each_time_becomes_a_blank_filled_at_replay`、`the_phones_plain_words_find_the_turn`、`the_message_pressed_is_the_turn_learned`)、`cargo test appctl::`(`a_turn_that_has_ended_can_still_be_taught`、`after_regenerating_the_attempt_shown_is_learned`、`a_skill_learned_in_a_branch_is_the_main_bots`)、`cargo test store::`、`cargo test a_skill_is_replayed_without_the_model_in_between`、`cargo test skills::`、`cargo test agent::`。
|
||||||
|
|
||||||
## 陷阱
|
## 陷阱
|
||||||
|
|
||||||
- 自動學到的、「教我做」存的技能,都自動算進那個 Bot 自己的技能清單(支線學的算主 Bot 的)。
|
- 自動學到的、「教我做」存的技能,都自動算進那個 Bot 自己的技能清單(支線學的算主 Bot 的)。
|
||||||
- `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。
|
- `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。
|
||||||
- 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。
|
- 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。
|
||||||
- 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面的步驟和照編號點的步驟。
|
- 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面、讀說明或技能、重播的步驟和照編號點的步驟。
|
||||||
- 「教我做」學的是那則訊息開始的那一回合(同一句話之後又做過也一樣),只找得到 30 天內的;更早的、或做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。
|
- 「教我做」學的是那則訊息開始的那一回合(同一句話別次做的不算);按過重新產生、重新傳送或重試,學的是聊天裡留著的最後那一次。只找得到 30 天內的;更早的、做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。舊版手機頁面不帶訊息的時間,就學最近一次以同樣的話開始的回合(插的話跟某一回合開頭一樣,會學到那一回合)。
|
||||||
- `save_skill` 存同名的技能會把原本存的可重播步驟一起換掉([skills](skills.md))。
|
- `save_skill` 存同名的技能會把原本存的可重播步驟一起換掉([skills](skills.md))。
|
||||||
- (驗證)插話太慢,那一輪會先結束、五步被拆成兩輪就不會學:每一步送出後立刻等下一個步驟出現再送。
|
- (驗證)插話太慢,那一輪會先結束、五步被拆成兩輪就不會學:每一步送出後立刻等下一個步驟出現再送。
|
||||||
|
|
|
||||||
|
|
@ -378,6 +378,8 @@ pub fn routine_report(r: &Routine) -> String {
|
||||||
/// A skill this bot just learned is one of its own; the others learn it when the person ticks
|
/// A skill this bot just learned is one of its own; the others learn it when the person ticks
|
||||||
/// it for them (Bot 設定 › 技能). Says who can use it now.
|
/// it for them (Bot 設定 › 技能). Says who can use it now.
|
||||||
fn learned(state: &mut State, bot_id: u64, name: &str) -> String {
|
fn learned(state: &mut State, bot_id: u64, name: &str) -> String {
|
||||||
|
// (A branch's is its main bot's.)
|
||||||
|
let bot_id = state.home_of(bot_id);
|
||||||
give_skill(state, bot_id, name);
|
give_skill(state, bot_id, name);
|
||||||
if state.bots.iter().any(|b| b.id != bot_id && b.skills.is_some()) {
|
if state.bots.iter().any(|b| b.id != bot_id && b.skills.is_some()) {
|
||||||
"你會用了;其他 Bot 要在 Bot 設定 › 技能勾選才會。".into()
|
"你會用了;其他 Bot 要在 Bot 設定 › 技能勾選才會。".into()
|
||||||
|
|
@ -767,13 +769,11 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
|
||||||
return err("要學的是哪件事?".into());
|
return err("要學的是哪件事?".into());
|
||||||
}
|
}
|
||||||
// That turn has usually ended (the person presses it under their own message): the
|
// That turn has usually ended (the person presses it under their own message): the
|
||||||
// work log keeps only the open turn; the audit trail keeps each one KEEP_DAYS. A
|
// work log keeps only the open turn; the audit trail keeps each one KEEP_DAYS. Which
|
||||||
// trail that can't be opened leaves the log.
|
// turn from the turns' first lines (`at`: when the message was sent), then that one's steps.
|
||||||
let mut recs = crate::store::records(bot_id);
|
let taught = crate::memory::taught_turn(&prompt, v["at"].as_i64(), &crate::store::turn_starts(bot_id))
|
||||||
if recs.is_empty() {
|
.and_then(|(op, said)| crate::memory::skillify(&said, &crate::store::turn_records(bot_id, &op)));
|
||||||
recs = crate::oplog::OpLog::for_bot(bot_id).read();
|
match taught {
|
||||||
}
|
|
||||||
match crate::memory::skillify(&prompt, v["at"].as_i64(), &recs) {
|
|
||||||
Ok(sk) => {
|
Ok(sk) => {
|
||||||
let n = sk.steps.len();
|
let n = sk.steps.len();
|
||||||
let name = sk.name.clone();
|
let name = sk.name.clone();
|
||||||
|
|
@ -1061,6 +1061,47 @@ mod tests {
|
||||||
assert!(!none.ok && none.text.contains("找不到以「沒做過的事」開始的那一回合"), "{}", none.text);
|
assert!(!none.ok && none.text.contains("找不到以「沒做過的事」開始的那一回合"), "{}", none.text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 重新產生 starts the same message again: 教我做 under it learns the attempt the chat shows
|
||||||
|
/// (the last), not the one it replaced — the trail keeps when each turn's message was sent.
|
||||||
|
#[test]
|
||||||
|
fn after_regenerating_the_attempt_shown_is_learned() {
|
||||||
|
use crate::oplog::{OpLog, Outcome, Prompt, Record, Replay};
|
||||||
|
let mut st = State::samples();
|
||||||
|
let bot = 7342;
|
||||||
|
st.bots[0].id = bot;
|
||||||
|
let log = OpLog::for_bot(bot);
|
||||||
|
let sent = crate::model::now_ms() - 10_000;
|
||||||
|
let said = "簽到 [[call shell {\"command\":\"echo wrong >> sign.txt\"}]]";
|
||||||
|
for (op, started, cmd) in [("try-1", sent + 5, "echo wrong >> sign.txt"), ("try-2", sent + 5_000, "echo right >> sign.txt")] {
|
||||||
|
log.append(&Record::OperationStarted { op: op.into(), at: started, source_leaf: sent, prompt: Some(Prompt { at: sent, text: said.into() }) });
|
||||||
|
log.append(&Record::ToolStarted { op: op.into(), call_id: "c1".into(), name: "shell".into(), args: json!({"command": cmd}).to_string(), replay: Replay::Never, at: started + 1 });
|
||||||
|
log.append(&Record::ToolFinished { op: op.into(), call_id: "c1".into(), status: "done".into(), at: started + 2 });
|
||||||
|
log.finish(op, Outcome::Completed);
|
||||||
|
}
|
||||||
|
let out = apply(&mut st, bot, "skillify", &json!({"prompt": said, "at": sent}).to_string());
|
||||||
|
assert!(out.ok, "{}", out.text);
|
||||||
|
let k = st.skills.iter().find(|k| k.description == format!("示範學會:{said}")).expect("saved");
|
||||||
|
assert_eq!(k.steps[0].args, json!({"command": "echo right >> sign.txt"}).to_string());
|
||||||
|
// A message sent at another time (a 插話 with the same words) started neither.
|
||||||
|
let other = apply(&mut st, bot, "skillify", &json!({"prompt": said, "at": sent + 1_000}).to_string());
|
||||||
|
assert!(!other.ok && other.text.contains("找不到"), "{}", other.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A branch's skill is its main bot's (as everything it keeps).
|
||||||
|
#[test]
|
||||||
|
fn a_skill_learned_in_a_branch_is_the_main_bots() {
|
||||||
|
let mut st = State::samples();
|
||||||
|
let main = st.bots[0].id;
|
||||||
|
st.bot_mut(main).unwrap().skills = Some(vec![]);
|
||||||
|
let mut b = st.bots[0].clone();
|
||||||
|
b.id = 778;
|
||||||
|
b.branch_of = main;
|
||||||
|
st.branch_bots.push(b);
|
||||||
|
learned(&mut st, 778, "支線學的");
|
||||||
|
assert_eq!(st.bot(main).unwrap().skills.clone().unwrap(), vec!["支線學的".to_string()]);
|
||||||
|
assert!(!st.bot(778).unwrap().skills.clone().unwrap_or_default().contains(&"支線學的".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_routine_can_say_how_many_it_is_to_send_and_the_run_is_told() {
|
fn a_routine_can_say_how_many_it_is_to_send_and_the_run_is_told() {
|
||||||
let mut st = State::samples();
|
let mut st = State::samples();
|
||||||
|
|
|
||||||
109
src/memory.rs
109
src/memory.rs
|
|
@ -205,43 +205,48 @@ fn plain_words(t: &str) -> String {
|
||||||
t.split_whitespace().collect::<Vec<_>>().join(" ")
|
t.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// C8: 示範即教學 — turn the turn that `prompt` started into a skill, keeping the steps that
|
/// Which turn 教我做 means: the one the pressed message started. `at` is when that message was
|
||||||
/// worked and threw nothing away. `at`: when that message was sent — the same words may have
|
/// sent; one message can start several turns (重新產生、重新傳送、重試 start it again) and the
|
||||||
/// started other turns since (an earlier try, a later one that went wrong), so it is the first
|
/// chat shows the last, so it is the latest turn started by that very message — none (a 插話
|
||||||
/// turn starting from then; without it (or with a clock that disagrees), the latest. Looking
|
/// starts no turn of its own): not found. Without `at` (an older phone page) it is the latest
|
||||||
/// steps (screenshots, reads) are dropped: a replay looks for itself. Steps that point at a
|
/// turn started by the same words. `starts`: the turns' first lines (store::turn_starts).
|
||||||
/// number on the screen (ref) are dropped too — numbers only live as long as the look that made
|
/// Ok: (that turn, the words that started it).
|
||||||
/// them. Err: why nothing was saved.
|
pub fn taught_turn(prompt: &str, at: Option<i64>, starts: &[crate::oplog::Record]) -> Result<(String, String), String> {
|
||||||
pub fn skillify(prompt: &str, at: Option<i64>, recs: &[crate::oplog::Record]) -> Result<Skill, String> {
|
|
||||||
let key: String = plain_words(prompt).chars().take(40).collect();
|
let key: String = plain_words(prompt).chars().take(40).collect();
|
||||||
// (op, when the turn started, the words that started it), oldest first.
|
starts
|
||||||
let turns: Vec<(&str, i64, &str)> = recs
|
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|r| match r {
|
.rev()
|
||||||
crate::oplog::Record::OperationStarted { op, at, prompt: Some(p), .. } if plain_words(&p.text).chars().take(40).collect::<String>() == key => Some((op.as_str(), *at, p.text.as_str())),
|
.find_map(|r| match r {
|
||||||
|
crate::oplog::Record::OperationStarted { op, prompt: Some(p), .. } if at.is_none_or(|t| p.at == t) && plain_words(&p.text).chars().take(40).collect::<String>() == key => Some((op.clone(), p.text.clone())),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
.collect();
|
.ok_or_else(|| format!("找不到以「{prompt}」開始的那一回合(只找得到 {} 天內、由一則訊息開始的回合;做事中途插的話不算)", crate::store::KEEP_DAYS))
|
||||||
let Some(&(op, _, said)) = at.and_then(|t| turns.iter().find(|(_, started, _)| *started >= t)).or(turns.last()) else {
|
}
|
||||||
return Err(format!("找不到以「{prompt}」開始的那一回合(只找得到 {} 天內、由一則訊息開始的回合;做事中途插的話不算)", crate::store::KEEP_DAYS));
|
|
||||||
};
|
/// Steps a replay never repeats: looking (a replay looks for itself), reading a guide or a skill,
|
||||||
|
/// replaying one. The learner (replay_steps) and 教我做 (skillify) drop the same ones.
|
||||||
|
fn never_replayed(name: &str) -> bool {
|
||||||
|
matches!(name, "computer_use_screenshot" | "computer_use_zoom" | "computer_use_show" | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_sent_log" | "anybot_guide" | "use_skill" | "replay_skill")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// C8: 示範即教學 — a turn's steps that worked and threw nothing away, as a skill named in the
|
||||||
|
/// words that started it (`said`; `recs`: that turn's lines, store::turn_records). Steps a replay
|
||||||
|
/// never repeats are dropped, and so are steps that point at a number on the screen (ref) —
|
||||||
|
/// numbers only live as long as the look that made them. Err: why nothing was saved.
|
||||||
|
pub fn skillify(said: &str, recs: &[crate::oplog::Record]) -> Result<Skill, String> {
|
||||||
let mut done: Vec<(String, bool)> = vec![]; // index-parallel with steps: (call_id, finished ok)
|
let mut done: Vec<(String, bool)> = vec![]; // index-parallel with steps: (call_id, finished ok)
|
||||||
let mut steps: Vec<(String, String)> = vec![];
|
let mut steps: Vec<(String, String)> = vec![];
|
||||||
for r in recs {
|
for r in recs {
|
||||||
match r {
|
match r {
|
||||||
crate::oplog::Record::ToolStarted { op: o, call_id, name, args, .. } if o == op => {
|
crate::oplog::Record::ToolStarted { call_id, name, args, .. } => {
|
||||||
let a: serde_json::Value = serde_json::from_str(args).unwrap_or_default();
|
let a: serde_json::Value = serde_json::from_str(args).unwrap_or_default();
|
||||||
let looks = matches!(
|
|
||||||
name.as_str(),
|
|
||||||
"computer_use_screenshot" | "computer_use_zoom" | "computer_use_look" | "browser_screenshot" | "browser_read" | "browser_elements"
|
|
||||||
) || (name == "computer" && matches!(a["action"].as_str().unwrap_or(""), "screenshot" | "zoom" | "look" | "scroll" | "move"));
|
|
||||||
let numbered = a["ref"].is_number() || !a["actions"].is_null();
|
let numbered = a["ref"].is_number() || !a["actions"].is_null();
|
||||||
if !looks && !numbered {
|
if !never_replayed(name) && !numbered {
|
||||||
steps.push((name.clone(), args.clone()));
|
steps.push((name.clone(), args.clone()));
|
||||||
done.push((call_id.clone(), true));
|
done.push((call_id.clone(), true));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == op && status != "done" => {
|
crate::oplog::Record::ToolFinished { call_id, status, .. } if status != "done" => {
|
||||||
if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) {
|
if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) {
|
||||||
e.1 = false;
|
e.1 = false;
|
||||||
}
|
}
|
||||||
|
|
@ -551,7 +556,7 @@ pub fn replay_steps(turn: &[crate::model::Message], picks: &[usize], blanks: &[(
|
||||||
let mut out = vec![];
|
let mut out = vec![];
|
||||||
for &k in picks {
|
for &k in picks {
|
||||||
let Some((_, Some(c))) = k.checked_sub(1).and_then(|i| steps.get(i)) else { continue };
|
let Some((_, Some(c))) = k.checked_sub(1).and_then(|i| steps.get(i)) else { continue };
|
||||||
if c.status == crate::model::ToolStatus::Failed || matches!(c.name.as_str(), "computer_use_screenshot" | "computer_use_zoom" | "browser_read" | "browser_screenshot" | "browser_elements" | "browser_sent_log" | "anybot_guide" | "use_skill" | "replay_skill") {
|
if c.status == crate::model::ToolStatus::Failed || never_replayed(&c.name) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let v: serde_json::Value = serde_json::from_str(&c.args).unwrap_or_default();
|
let v: serde_json::Value = serde_json::from_str(&c.args).unwrap_or_default();
|
||||||
|
|
@ -1426,21 +1431,26 @@ mod tests {
|
||||||
use crate::oplog::{Prompt, Record, Replay};
|
use crate::oplog::{Prompt, Record, Replay};
|
||||||
let recs = vec![
|
let recs = vec![
|
||||||
Record::OperationStarted { op: "o1".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: "每天記一下日期".into() }) },
|
Record::OperationStarted { op: "o1".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: "每天記一下日期".into() }) },
|
||||||
Record::ToolStarted { op: "o1".into(), call_id: "c1".into(), name: "computer".into(), args: "{\"action\":\"screenshot\"}".into(), replay: Replay::Safe, at: 2 },
|
Record::ToolStarted { op: "o1".into(), call_id: "c1".into(), name: "computer_use_screenshot".into(), args: "{}".into(), replay: Replay::Safe, at: 2 },
|
||||||
Record::ToolFinished { op: "o1".into(), call_id: "c1".into(), status: "done".into(), at: 3 },
|
Record::ToolFinished { op: "o1".into(), call_id: "c1".into(), status: "done".into(), at: 3 },
|
||||||
Record::ToolStarted { op: "o1".into(), call_id: "c2".into(), name: "shell".into(), args: "{\"cmd\":\"date\"}".into(), replay: Replay::Safe, at: 4 },
|
Record::ToolStarted { op: "o1".into(), call_id: "c2".into(), name: "shell".into(), args: "{\"cmd\":\"date\"}".into(), replay: Replay::Safe, at: 4 },
|
||||||
Record::ToolFinished { op: "o1".into(), call_id: "c2".into(), status: "done".into(), at: 5 },
|
Record::ToolFinished { op: "o1".into(), call_id: "c2".into(), status: "done".into(), at: 5 },
|
||||||
Record::ToolStarted { op: "o1".into(), call_id: "c3".into(), name: "shell".into(), args: "{\"cmd\":\"rm\"}".into(), replay: Replay::Safe, at: 6 },
|
Record::ToolStarted { op: "o1".into(), call_id: "c3".into(), name: "shell".into(), args: "{\"cmd\":\"rm\"}".into(), replay: Replay::Safe, at: 6 },
|
||||||
Record::ToolFinished { op: "o1".into(), call_id: "c3".into(), status: "failed".into(), at: 7 },
|
Record::ToolFinished { op: "o1".into(), call_id: "c3".into(), status: "failed".into(), at: 7 },
|
||||||
Record::ToolStarted { op: "o1".into(), call_id: "c4".into(), name: "computer".into(), args: "{\"action\":\"click\",\"ref\":3}".into(), replay: Replay::Safe, at: 8 },
|
Record::ToolStarted { op: "o1".into(), call_id: "c4".into(), name: "computer_use_click".into(), args: "{\"ref\":3}".into(), replay: Replay::Safe, at: 8 },
|
||||||
Record::ToolFinished { op: "o1".into(), call_id: "c4".into(), status: "done".into(), at: 9 },
|
Record::ToolFinished { op: "o1".into(), call_id: "c4".into(), status: "done".into(), at: 9 },
|
||||||
|
// Reading the guide or a skill, replaying one: never a step of its own (as the learner).
|
||||||
|
Record::ToolStarted { op: "o1".into(), call_id: "c5".into(), name: "anybot_guide".into(), args: "{\"topic\":\"replay\"}".into(), replay: Replay::Safe, at: 10 },
|
||||||
|
Record::ToolStarted { op: "o1".into(), call_id: "c6".into(), name: "use_skill".into(), args: "{\"name\":\"記日期\"}".into(), replay: Replay::Safe, at: 11 },
|
||||||
|
Record::ToolStarted { op: "o1".into(), call_id: "c7".into(), name: "replay_skill".into(), args: "{\"name\":\"記日期\"}".into(), replay: Replay::Never, at: 12 },
|
||||||
];
|
];
|
||||||
let sk = skillify("每天記一下日期", None, &recs).unwrap();
|
let (op, said) = taught_turn("每天記一下日期", None, &recs[..1]).unwrap();
|
||||||
// only the shell date step survives: looks and numbered clicks are dropped, failures too
|
assert_eq!((op.as_str(), said.as_str()), ("o1", "每天記一下日期"));
|
||||||
assert_eq!(sk.steps.len(), 1);
|
let sk = skillify(&said, &recs).unwrap();
|
||||||
assert_eq!(sk.steps[0].tool, "shell");
|
// only the shell date step survives: looks, guides, skills and numbered clicks are dropped, failures too
|
||||||
|
assert_eq!(sk.steps.iter().map(|s| s.tool.as_str()).collect::<Vec<_>>(), ["shell"]);
|
||||||
assert!(sk.steps[0].args.contains("date"));
|
assert!(sk.steps[0].args.contains("date"));
|
||||||
assert!(skillify("沒這回合", None, &recs).unwrap_err().starts_with("找不到以「沒這回合」開始的那一回合"));
|
assert!(taught_turn("沒這回合", None, &recs[..1]).unwrap_err().starts_with("找不到以「沒這回合」開始的那一回合"));
|
||||||
assert!(sk.instructions.starts_with("照著做過一次的那條路做完這件事"), "{}", sk.instructions);
|
assert!(sk.instructions.starts_with("照著做過一次的那條路做完這件事"), "{}", sk.instructions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1457,38 +1467,35 @@ mod tests {
|
||||||
];
|
];
|
||||||
// (mobile/index.html: plain(m.text).slice(0, 200))
|
// (mobile/index.html: plain(m.text).slice(0, 200))
|
||||||
let phone = "寫教學 記一筆 到 紀錄 teachlog.txt";
|
let phone = "寫教學 記一筆 到 紀錄 teachlog.txt";
|
||||||
let k = skillify(phone, None, &recs).unwrap();
|
let (op, words) = taught_turn(phone, Some(1), &recs[..1]).unwrap();
|
||||||
|
assert_eq!((op.as_str(), words.as_str()), ("o1", said));
|
||||||
|
assert_eq!(taught_turn(said, None, &recs[..1]).map(|t| t.0), Ok("o1".into()), "the words as typed find it too");
|
||||||
|
let k = skillify(&words, &recs).unwrap();
|
||||||
assert_eq!(k.steps.len(), 1);
|
assert_eq!(k.steps.len(), 1);
|
||||||
// Named and described in the turn's own words, on one line.
|
// Named and described in the turn's own words, on one line.
|
||||||
assert_eq!(k.description, "示範學會:寫教學 **記一筆** 到 [紀錄](https://example.com) >> teach_log.txt");
|
assert_eq!(k.description, "示範學會:寫教學 **記一筆** 到 [紀錄](https://example.com) >> teach_log.txt");
|
||||||
assert_eq!(skillify(said, None, &recs).map(|k| k.steps.len()), Ok(1), "the words as typed find it too");
|
|
||||||
// Only looking: the turn is there, nothing to replay.
|
// Only looking: the turn is there, nothing to replay.
|
||||||
let looked = vec![
|
let looked = vec![
|
||||||
Record::OperationStarted { op: "o2".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: "看一下".into() }) },
|
Record::OperationStarted { op: "o2".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: "看一下".into() }) },
|
||||||
Record::ToolStarted { op: "o2".into(), call_id: "c1".into(), name: "browser_screenshot".into(), args: "{}".into(), replay: Replay::Safe, at: 2 },
|
Record::ToolStarted { op: "o2".into(), call_id: "c1".into(), name: "browser_screenshot".into(), args: "{}".into(), replay: Replay::Safe, at: 2 },
|
||||||
];
|
];
|
||||||
assert_eq!(skillify("看一下", None, &looked).unwrap_err(), "那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)");
|
assert_eq!(skillify("看一下", &looked).unwrap_err(), "那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The same words, said on two days: the message pressed is the turn learned — Monday's run
|
/// The message pressed is the turn learned: Monday's 「幫我簽到」 is Monday's run, not
|
||||||
/// that worked, not Tuesday's that went wrong after it.
|
/// Tuesday's; Tuesday's, started again with 重新產生, is the attempt the chat shows (the last),
|
||||||
|
/// not the one thrown away; a 插話 with the same words started no turn: not found.
|
||||||
#[test]
|
#[test]
|
||||||
fn the_message_pressed_is_the_turn_learned() {
|
fn the_message_pressed_is_the_turn_learned() {
|
||||||
use crate::oplog::{Prompt, Record, Replay};
|
use crate::oplog::{Prompt, Record};
|
||||||
let turn = |op: &str, at: i64, cmd: &str, status: &str| {
|
// (op, when the turn started, when its message was sent)
|
||||||
vec![
|
let start = |op: &str, started: i64, sent: i64| Record::OperationStarted { op: op.into(), at: started, source_leaf: sent, prompt: Some(Prompt { at: sent, text: "幫我簽到".into() }) };
|
||||||
Record::OperationStarted { op: op.into(), at: at + 5, source_leaf: 0, prompt: Some(Prompt { at, text: "幫我簽到".into() }) },
|
let starts = [start("mon", 1_005, 1_000), start("tue", 2_005, 2_000), start("tue-again", 2_500, 2_000)];
|
||||||
Record::ToolStarted { op: op.into(), call_id: "c1".into(), name: "shell".into(), args: format!("{{\"command\":\"{cmd}\"}}"), replay: Replay::Never, at: at + 6 },
|
let op = |at| taught_turn("幫我簽到", at, &starts).map(|t| t.0);
|
||||||
Record::ToolFinished { op: op.into(), call_id: "c1".into(), status: status.into(), at: at + 7 },
|
assert_eq!(op(Some(1_000)), Ok("mon".into()), "Monday's message: Monday's turn");
|
||||||
]
|
assert_eq!(op(Some(2_000)), Ok("tue-again".into()), "regenerated: the attempt shown, not the one replaced");
|
||||||
};
|
assert!(op(Some(2_200)).unwrap_err().starts_with("找不到以「幫我簽到」開始的那一回合"), "a 插話 typed at 2_200 started no turn");
|
||||||
let recs: Vec<Record> = [turn("mon", 1_000, "sign-in --ok", "done"), turn("tue", 2_000, "sign-in --other", "done")].concat();
|
assert_eq!(op(None), Ok("tue-again".into()), "no time (an older phone page): the latest by its words");
|
||||||
let steps = |at| skillify("幫我簽到", at, &recs).map(|k| k.steps[0].args.clone());
|
|
||||||
assert_eq!(steps(Some(1_000)), Ok("{\"command\":\"sign-in --ok\"}".into()), "Monday's message: Monday's turn");
|
|
||||||
assert_eq!(steps(Some(2_000)), Ok("{\"command\":\"sign-in --other\"}".into()));
|
|
||||||
assert_eq!(steps(None), Ok("{\"command\":\"sign-in --other\"}".into()), "no time: the latest");
|
|
||||||
// A message the clock puts after every turn (another device's clock): still the latest.
|
|
||||||
assert_eq!(steps(Some(9_000)), Ok("{\"command\":\"sign-in --other\"}".into()));
|
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn remember_tells_the_same_thing_from_another_fact() {
|
fn remember_tells_the_same_thing_from_another_fact() {
|
||||||
|
|
|
||||||
110
src/store.rs
110
src/store.rs
|
|
@ -82,12 +82,21 @@ fn audit_schema(c: &Connection) -> Option<()> {
|
||||||
name TEXT,
|
name TEXT,
|
||||||
detail TEXT,
|
detail TEXT,
|
||||||
status TEXT,
|
status TEXT,
|
||||||
call_id TEXT
|
call_id TEXT,
|
||||||
|
prompt_at INTEGER
|
||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS audit_bot_at ON audit(bot, at DESC);
|
CREATE INDEX IF NOT EXISTS audit_bot_at ON audit(bot, at DESC);
|
||||||
CREATE INDEX IF NOT EXISTS audit_call ON audit(bot, op, call_id);",
|
CREATE INDEX IF NOT EXISTS audit_call ON audit(bot, op, call_id);",
|
||||||
)
|
)
|
||||||
.ok()
|
.ok()?;
|
||||||
|
// A turn's row keeps when the person's message was sent (教我做 finds the turns a message
|
||||||
|
// started by it). A trail from before has no such column: add it (its old rows stay NULL).
|
||||||
|
let has = c.query_row("SELECT COUNT(*) FROM pragma_table_info('audit') WHERE name='prompt_at'", [], |r| r.get::<_, i64>(0)).ok()? > 0;
|
||||||
|
if !has {
|
||||||
|
// (Another AnyBot on the same folder may have just added it: then this one fails, harmlessly.)
|
||||||
|
let _ = c.execute_batch("ALTER TABLE audit ADD COLUMN prompt_at INTEGER;");
|
||||||
|
}
|
||||||
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn memory_schema(c: &Connection) -> Option<()> {
|
fn memory_schema(c: &Connection) -> Option<()> {
|
||||||
|
|
@ -319,8 +328,8 @@ pub fn record(bot: u64, r: &Record) {
|
||||||
match r {
|
match r {
|
||||||
Record::OperationStarted { op, at, prompt, .. } => {
|
Record::OperationStarted { op, at, prompt, .. } => {
|
||||||
let _ = c.execute(
|
let _ = c.execute(
|
||||||
"INSERT INTO audit(bot,op,at,kind,detail) VALUES(?1,?2,?3,'turn',?4)",
|
"INSERT INTO audit(bot,op,at,kind,detail,prompt_at) VALUES(?1,?2,?3,'turn',?4,?5)",
|
||||||
params![bot, op, at, prompt.as_ref().map(|p| p.text.clone())],
|
params![bot, op, at, prompt.as_ref().map(|p| p.text.clone()), prompt.as_ref().map(|p| p.at)],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Record::StepAttempt { op, step, .. } => {
|
Record::StepAttempt { op, step, .. } => {
|
||||||
|
|
@ -368,39 +377,44 @@ pub fn record(bot: u64, r: &Record) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The trail's turns as work-log lines again, oldest first, KEEP_DAYS back: each turn's start
|
/// The turns of the last KEEP_DAYS, oldest first, as each one's first work-log line: what the
|
||||||
/// (with the person's words), its steps (the arguments they ran with, how each ended) and its
|
/// person said and when that message was sent (0: a turn kept before the trail had it). What
|
||||||
/// end. What 教我做 reads — the JSONL log drops a turn the moment it ends. Model attempts, typed
|
/// 教我做 picks a turn from — then turn_records reads just that one.
|
||||||
/// messages and stops aren't rebuilt; a step's replay class isn't kept (read as Never).
|
pub fn turn_starts(bot: u64) -> Vec<Record> {
|
||||||
pub fn records(bot: u64) -> Vec<Record> {
|
let cutoff = crate::model::now_ms() - KEEP_DAYS * 86_400_000;
|
||||||
let bot = bot as i64;
|
rebuilt("bot=?1 AND at>?2 AND kind='turn'", params![bot as i64, cutoff]).into_iter().filter(|r| matches!(r, Record::OperationStarted { .. })).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One turn of the trail as work-log lines again: its start, its steps (the arguments they ran
|
||||||
|
/// with, how each ended) and its end — the JSONL log drops a turn the moment it ends. Model
|
||||||
|
/// attempts, typed messages and stops aren't rebuilt; a step's replay class isn't kept (Never).
|
||||||
|
pub fn turn_records(bot: u64, op: &str) -> Vec<Record> {
|
||||||
|
rebuilt("bot=?1 AND op=?2 AND kind IN ('turn','tool')", params![bot as i64, op])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The trail's turn and step rows that `filter` picks, in order, as work-log lines (each turn's
|
||||||
|
/// end after its steps).
|
||||||
|
fn rebuilt(filter: &str, args: impl rusqlite::Params) -> Vec<Record> {
|
||||||
let Some(s) = store() else { return vec![] };
|
let Some(s) = store() else { return vec![] };
|
||||||
let Ok(c) = s.conn.lock() else { return vec![] };
|
let Ok(c) = s.conn.lock() else { return vec![] };
|
||||||
let cutoff = crate::model::now_ms() - KEEP_DAYS * 86_400_000;
|
let Ok(mut st) = c.prepare(&format!("SELECT op,at,end_at,kind,name,detail,status,call_id,prompt_at FROM audit WHERE {filter} ORDER BY id ASC")) else {
|
||||||
let Ok(mut st) = c.prepare("SELECT op,at,end_at,kind,name,detail,status,call_id FROM audit WHERE bot=?1 AND at>?2 AND kind IN ('turn','tool') ORDER BY id ASC") else {
|
|
||||||
return vec![];
|
return vec![];
|
||||||
};
|
};
|
||||||
let rows = st
|
let rows = st
|
||||||
.query_map(params![bot, cutoff], |r| {
|
.query_map(args, |r| {
|
||||||
Ok((
|
Ok((
|
||||||
r.get::<_, String>(0)?,
|
(r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, Option<i64>>(2)?, r.get::<_, String>(3)?),
|
||||||
r.get::<_, i64>(1)?,
|
(r.get::<_, Option<String>>(4)?, r.get::<_, Option<String>>(5)?, r.get::<_, Option<String>>(6)?, r.get::<_, Option<String>>(7)?, r.get::<_, Option<i64>>(8)?),
|
||||||
r.get::<_, Option<i64>>(2)?,
|
|
||||||
r.get::<_, String>(3)?,
|
|
||||||
r.get::<_, Option<String>>(4)?,
|
|
||||||
r.get::<_, Option<String>>(5)?,
|
|
||||||
r.get::<_, Option<String>>(6)?,
|
|
||||||
r.get::<_, Option<String>>(7)?,
|
|
||||||
))
|
))
|
||||||
})
|
})
|
||||||
.map(|it| it.filter_map(Result::ok).collect::<Vec<_>>())
|
.map(|it| it.filter_map(Result::ok).collect::<Vec<_>>())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
// A turn's end goes after all of its steps (its row is the turn's first).
|
|
||||||
let mut ends = Vec::new();
|
let mut ends = Vec::new();
|
||||||
for (op, at, end_at, kind, name, detail, status, call_id) in rows {
|
for ((op, at, end_at, kind), (name, detail, status, call_id, prompt_at)) in rows {
|
||||||
if kind == "turn" {
|
if kind == "turn" {
|
||||||
out.push(Record::OperationStarted { op: op.clone(), at, source_leaf: 0, prompt: detail.map(|text| crate::oplog::Prompt { at, text }) });
|
let sent = prompt_at.unwrap_or(0);
|
||||||
|
out.push(Record::OperationStarted { op: op.clone(), at, source_leaf: sent, prompt: detail.map(|text| crate::oplog::Prompt { at: sent, text }) });
|
||||||
let outcome = match status.as_deref() {
|
let outcome = match status.as_deref() {
|
||||||
Some("completed") => Some(Outcome::Completed),
|
Some("completed") => Some(Outcome::Completed),
|
||||||
Some("aborted") => Some(Outcome::Aborted),
|
Some("aborted") => Some(Outcome::Aborted),
|
||||||
|
|
@ -824,15 +838,51 @@ mod tests {
|
||||||
assert_eq!(ts[1]["steps"][1]["name"], "computer");
|
assert_eq!(ts[1]["steps"][1]["name"], "computer");
|
||||||
assert_eq!(ts[1]["steps"][1]["status"], "done", "the finished tool answers with its end status");
|
assert_eq!(ts[1]["steps"][1]["status"], "done", "the finished tool answers with its end status");
|
||||||
assert_eq!(ts[1]["steps"][2]["state"], "consumed");
|
assert_eq!(ts[1]["steps"][2]["state"], "consumed");
|
||||||
// …and as work-log lines again (what 教我做 reads): turns and steps, each turn's end
|
// …and as work-log lines again (what 教我做 reads): the turns' starts, with when the
|
||||||
// after its steps.
|
// message was sent; then one turn's start, steps and end.
|
||||||
let recs = records(bot);
|
let starts = turns_started(bot);
|
||||||
|
assert_eq!(starts, [("op1".to_string(), Some(("幫我叫車".to_string(), at(0)))), ("op2".to_string(), None)]);
|
||||||
|
let recs = turn_records(bot, "op1");
|
||||||
let kinds: Vec<String> = recs.iter().map(|r| serde_json::to_value(r).unwrap()["type"].as_str().unwrap().to_string()).collect();
|
let kinds: Vec<String> = recs.iter().map(|r| serde_json::to_value(r).unwrap()["type"].as_str().unwrap().to_string()).collect();
|
||||||
assert_eq!(kinds, ["operation_started", "tool_started", "tool_finished", "operation_started", "tool_started", "operation_finished"]);
|
assert_eq!(kinds, ["operation_started", "tool_started", "tool_finished", "operation_finished"]);
|
||||||
assert!(matches!(&recs[0], Record::OperationStarted { prompt: Some(p), .. } if p.text == "幫我叫車"));
|
|
||||||
assert!(matches!(&recs[1], Record::ToolStarted { call_id, args, .. } if call_id == "c1" && args == "{\"action\":\"click\"}"));
|
assert!(matches!(&recs[1], Record::ToolStarted { call_id, args, .. } if call_id == "c1" && args == "{\"action\":\"click\"}"));
|
||||||
assert!(matches!(&recs[2], Record::ToolFinished { status, at, .. } if status == "done" && *at == t0 + 20));
|
assert!(matches!(&recs[2], Record::ToolFinished { status, at, .. } if status == "done" && *at == t0 + 20));
|
||||||
assert!(matches!(&recs[5], Record::OperationFinished { op, outcome: Outcome::Completed } if op == "op1"));
|
assert!(matches!(&recs[3], Record::OperationFinished { op, outcome: Outcome::Completed } if op == "op1"));
|
||||||
|
assert!(!turn_records(bot, "op2").iter().any(|r| matches!(r, Record::OperationFinished { .. })), "the open turn has no end");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (op, (words, when sent)) of each turn turn_starts gives.
|
||||||
|
fn turns_started(bot: u64) -> Vec<(String, Option<(String, i64)>)> {
|
||||||
|
turn_starts(bot)
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|r| match r {
|
||||||
|
Record::OperationStarted { op, prompt, .. } => Some((op, prompt.map(|p| (p.text, p.at)))),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A trail from before turns kept when their message was sent: it gains the column, keeps
|
||||||
|
/// its rows (read as sent at 0), and new turns keep the time.
|
||||||
|
#[test]
|
||||||
|
fn an_older_trail_learns_when_messages_were_sent() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("anybot-audit-migrate-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let c = connect(&dir.join("audit.db")).unwrap();
|
||||||
|
c.execute_batch(
|
||||||
|
"CREATE TABLE audit(id INTEGER PRIMARY KEY, bot INTEGER NOT NULL, op TEXT NOT NULL, at INTEGER NOT NULL, end_at INTEGER, kind TEXT NOT NULL, name TEXT, detail TEXT, status TEXT, call_id TEXT);
|
||||||
|
INSERT INTO audit(bot,op,at,kind,detail,status) VALUES (5,'old',100,'turn','以前的事','completed');",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
audit_schema(&c).unwrap();
|
||||||
|
audit_schema(&c).unwrap();
|
||||||
|
let old: (String, Option<i64>) = c.query_row("SELECT detail, prompt_at FROM audit WHERE op='old'", [], |r| Ok((r.get(0)?, r.get(1)?))).unwrap();
|
||||||
|
assert_eq!(old, ("以前的事".to_string(), None));
|
||||||
|
c.execute("INSERT INTO audit(bot,op,at,kind,detail,prompt_at) VALUES (5,'new',200,'turn','新的事',190)", []).unwrap();
|
||||||
|
let new: Option<i64> = c.query_row("SELECT prompt_at FROM audit WHERE op='new'", [], |r| r.get(0)).unwrap();
|
||||||
|
assert_eq!(new, Some(190));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue