From 4be6d3e4d0b590918c77947cf6172b8186c4b155 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 17:33:43 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix:=20=E3=80=8C=E6=95=99=E6=88=91=E5=81=9A?= =?UTF-8?q?=E3=80=8D=E8=AE=80=2030=20=E5=A4=A9=E7=9A=84=E7=A8=BD=E6=A0=B8?= =?UTF-8?q?=E7=B4=80=E9=8C=84=EF=BC=8C=E5=81=9A=E5=AE=8C=E7=9A=84=E5=9B=9E?= =?UTF-8?q?=E5=90=88=E4=B9=9F=E5=AD=B8=E5=BE=97=E5=88=B0=EF=BC=9B=E6=95=B4?= =?UTF-8?q?=E7=90=86=E5=81=9A=E6=B3=95=E5=9B=9E=E5=A0=B1=E7=9A=84=E5=95=8F?= =?UTF-8?q?=E9=A1=8C=E9=80=B2=E5=BE=97=E4=BA=86=E5=BE=85=E6=94=B9=E9=80=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 教我做(skillify)只讀那個 Bot 的工作紀錄(oplog),但一回合結束時工作紀錄就縮到只剩還在等的訊息 (通常整份刪掉)——長按的是自己早就做完的那則訊息,所以每次都回「那一回合沒有可重播的步驟」。 工作紀錄是給當掉後收尾用的,本來就只留進行中的那一回合;每一步的參數和結果另外照抄進 30 天的 稽核紀錄(oplog/audit.db,手機的稽核時間軸已經改讀它)。教我做要的正是「過去某一回合的步驟」, 所以改讀稽核紀錄,不是把工作紀錄留著。 整理做法(learn)在回答送出、這一回合 Done 之後才在背景跑(不讓使用者等),它回報的 AnyBot 自己的 問題(StreamEvent::Issues)卻排在「舊回合的零星事件一律丟掉」的檢查後面——紀錄寫了「Bot 回報了 2 個 AnyBot 自己的問題」,待改進還是空的。改成跟 Learned 一樣在那個檢查前面處理(事件的順序本來 就是 Done 在前,不能為了它讓使用者等整理做法)。 - store:records(bot) 把稽核紀錄裡 30 天內的回合和步驟還原成工作紀錄的格式(回合開頭帶使用者的話、 每一步的參數和結果、回合結束排在步驟後面);KEEP_DAYS 公開給錯誤訊息用。 - appctl skillify:讀 store::records,稽核紀錄打不開才退回工作紀錄;把手機送的訊息時間 at 交下去。 - memory::skillify: - 學的是按的那則訊息開始的那一回合:同一句話可能做過好幾次(30 天內很常見),有 at 就取那個時間 之後第一個開始的回合,沒有 at(或時鐘對不上)才取最近的。 - 比對時兩邊都照手機 plain() 的規則整理(拿掉 * _ ` # >、連結只留字、換行併成空白)——手機送的是 plain(m.text),原本訊息裡有 >、_ 或換行就對不上。技能的名字、說明、做法改用那一回合原本的字 (併成一行),不用手機去過標記的字(teach_log.txt 不會變成 teachlog.txt)。 - 回傳 Result,分開「找不到以「…」開始的那一回合(只找得到 30 天內、由一則訊息開始的回合;做事中途 插的話不算)」和「沒有可重播的步驟」;「这件事」→「這件事」(整份 memory.rs 用 ICU Hans-Hant 掃過, 只有這一個簡體字)。 - app drain_events:Issues 跟 Learned 一樣在回合結束後也收;記在主 Bot 名下(支線的算主 Bot 的)。 - 手機:教我做帶上訊息的 at;成功後呼叫的 again() 在那裡不是函式(全域的 again 是 loadChat 的旗標), 按了會丟 TypeError,拿掉。 - verify-anybot:phone 多一個 long-press [--text](觸控按住 0.8 秒),走得到長按的選單; SKILL.md、ctl 的用法一起寫。 - 功能地圖:replay.md 的「教我做」改走真的選單(長按 › 教我做),拿掉「走不到」那一步;陷阱補上學的是 哪一回合、只找 30 天內、找不到時說什麼;garden.md、replay.md 的自動測試列上新測試。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在、ANYBOT_HF_BASE 連不到)全綠(672 過、46 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。新測試 appctl::a_turn_that_has_ended_can_still_be_taught、memory::the_phones_plain_words_find_the_turn、 memory::the_message_pressed_is_the_turn_learned、app::anybots_own_problems_found_after_the_turn_reach_the_list, store 的 the_trail_keeps_the_story… 加了 records、a_finished_turn_can_become_a_skill 加了「這件事」——把修正 拿掉再跑都失敗(找不到那一回合、待改進是空的、簡體字、學到後來那一回合、說明變成去過標記的字), 放回去都過。另外請一個乾淨脈絡的 Agent 照 replay.md、garden.md 審過 diff,它提的三點(同一句話學錯回合、 技能的字被手機去掉標記、插話也說「30 天內」)都改了。verify-anybot 冷開照地圖寫的跑:replay.md 三步 (做五步學會、重播填空格、教我做——長按 › 選單 › 「已存成技能」,那一回合已經做完、工作紀錄不在,技能 steps 1、參數和說明都照原樣 echo 教 >> teach.txt;長按插話跳「找不到以「…」開始的那一回合…」)都過,修改前 第三步是 HTTP 400;garden.md 沒事不報、/doctor 遮金鑰、待改進合併計次(browser_fill_contact 一條 count 2、 bots 驗證小幫手,重開後還在)、版本都過,修改前第三步待改進是空的。 未驗證: garden.md 的「電腦版 設定 › 更新」要開桌面視窗(desktop-shot),沒跑;「有事的報告、當掉」和 replay.md 的「網站地圖」照地圖寫的走不到(要明天 8:44、真的當掉、真的模型);garden.md 是在審查後那幾處 修改之前的建置上跑的(那幾處只動 skillify 和手機的教我做,沒動待改進);真的手機的長按沒有測(用無頭 Chrome 的觸控事件代替);超過 30 天的回合、別台裝置時鐘不準時的 at 只靠單元測試。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- .claude/skills/verify-anybot/SKILL.md | 1 + .claude/skills/verify-anybot/scripts/ctl | 4 +- .../skills/verify-anybot/scripts/phone.mjs | 10 ++ docs/feature-map/garden.md | 2 +- docs/feature-map/replay.md | 6 +- mobile/index.html | 2 +- src/app.rs | 39 ++++-- src/appctl.rs | 39 +++++- src/memory.rs | 116 ++++++++++++++---- src/store.rs | 67 +++++++++- 10 files changed, 238 insertions(+), 48 deletions(-) diff --git a/.claude/skills/verify-anybot/SKILL.md b/.claude/skills/verify-anybot/SKILL.md index 8766bef..f465212 100644 --- a/.claude/skills/verify-anybot/SKILL.md +++ b/.claude/skills/verify-anybot/SKILL.md @@ -74,6 +74,7 @@ $CTL phone login # 手機密碼從 scratch 的檔案打進去(不 | `wait [秒]`、`wait-gone [秒]` | 等元素出現(看得見)/消失 | | `wait-text <字> [--in ] [秒]` | 等畫面(或某一塊)出現這些字 | | `click [--text <字>]` | 在元素正中間按一下;`--text` 選含這些字的那一個 | +| `long-press [--text <字>]` | 在元素正中間用手指(觸控)按住 0.8 秒再放開:手機的長按,例如自己訊息的選單 `long-press '.m.user .bub' --text 某句話` | | `send <字>` | 在聊天的輸入框 `#input` 打字、按送出 `#b-send` | | `type <字>` | 點進輸入框、清空、像鍵盤一樣打字 | | `press Enter`(`Escape`、`Tab`、`Backspace`) | 按鍵 | diff --git a/.claude/skills/verify-anybot/scripts/ctl b/.claude/skills/verify-anybot/scripts/ctl index 1e01e5a..2f995bf 100755 --- a/.claude/skills/verify-anybot/scripts/ctl +++ b/.claude/skills/verify-anybot/scripts/ctl @@ -16,7 +16,7 @@ # ctl model-reply <比對的字> <回答> | --clear 之後 system 或最後一則使用者訊息含這段字的請求,假模型回這個答案 # ctl model [jq 篩選] 假模型收到的請求(model-requests.jsonl,一行一個) # ctl procs [--none] <字> 這次 scratch 開的程式(環境帶著 scratch 的 HOME)裡,指令列含這段字的;--none:要一個都沒有 -# ctl phone <動作> … 用無頭 Chrome 操作手機頁面(start、open [--listed]、login [--wrong]、send <字>、click、type、wait…、shot、stop) +# ctl phone <動作> … 用無頭 Chrome 操作手機頁面(start、open [--listed]、login [--wrong]、send <字>、click、long-press、type、wait…、shot、stop) # ctl fingerprint 比對連上時拿到的憑證和資料夾裡的 lan-cert.der # ctl desktop-shot <名稱> [ANYBOT_SHOT_*=值 …] 把桌面視窗畫成圖(會在螢幕上開一下視窗:要 ABV_ALLOW_WINDOW=1) # ctl down 關掉這次開的一切、把最後狀態抄進證據、刪 scratch;證據留著 @@ -419,7 +419,7 @@ cmd_phone() { node "$PHONE" --state "$st" type '#input' "$1" node "$PHONE" --state "$st" click '#b-send' ;; stop) node "$PHONE" --state "$st" stop; setv CHROME_PID "" ;; - "") die "ctl phone …" ;; + "") die "ctl phone …" ;; *) node "$PHONE" --state "$st" --out "$RUN/phone" "$sub" "$@" ;; esac } diff --git a/.claude/skills/verify-anybot/scripts/phone.mjs b/.claude/skills/verify-anybot/scripts/phone.mjs index 73357b0..f82c0da 100755 --- a/.claude/skills/verify-anybot/scripts/phone.mjs +++ b/.claude/skills/verify-anybot/scripts/phone.mjs @@ -9,6 +9,7 @@ // wait-gone [秒] 等元素消失或看不見 // wait-text <字> [--in ] [秒] 等畫面上出現這些字 // click [--text <字>] 在元素正中間按一下(有 --text:符合 css 而且含這些字的那一個) +// long-press [--text <字>] 在元素正中間用手指按住 0.8 秒再放開(手機的長按,例如訊息的選單) // type <字> | --file <檔> 點進輸入框、清空、像鍵盤一樣打進去(--file:字從檔案讀,密碼不進指令列) // press <鍵> Enter、Escape、Tab、Backspace // text [css] 印出看得到的字 @@ -234,6 +235,15 @@ async function main() { await mouseClick(c, x, y); break; } + case "long-press": { + // 手指按住(觸控,不是滑鼠):頁面看 touchstart 之後有沒有放開,按滿 0.8 秒才放。 + const { x, y } = await center(c, rest[0] || die("long-press 要 css"), TEXT); + await c.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 }); + await c.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] }); + await sleep(800); + await c.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + break; + } case "type": { const css = rest[0]; const text = FILE ? fs.readFileSync(FILE, "utf8").trim() : rest[1]; diff --git a/docs/feature-map/garden.md b/docs/feature-map/garden.md index 7fa6131..f4dba3f 100644 --- a/docs/feature-map/garden.md +++ b/docs/feature-map/garden.md @@ -34,7 +34,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「 - **版本**(covers `garden-update`):帳戶選單 › 設定 › 更新。指令:`$CTL phone open --listed && $CTL phone click '#b-me' && $CTL phone click '#sheet-in .opt' --text 設定 && $CTL phone click '[data-go="updates"]' && $CTL phone wait-text 已是最新版 --in '#list' && $CTL api GET /api/settings --jq '{version, newer}'`。看到:版本(這個 checkout 的 HEAD)和建置時間、「已是最新版」。 - **電腦版 設定 › 更新**(covers `garden-issues`、`garden-update`、`garden-daily`):指令:要開視窗——`$CTL stop && ABV_ALLOW_WINDOW=1 $CTL desktop-shot garden-updates ANYBOT_SHOT_TAB=updates`(示範資料:真資料的截圖打不開 更新;有新版:加 `ANYBOT_SHOT_NEWER=0`)。看到:「自動更新」「園丁報告」開關、「重新啟動」;示範資料沒有待改進,「待改進」那一條的 ×2 和「全部清除」靠上面那一步的 state 和 `cargo test garden::`。 - **有事的報告、當掉**(covers `garden-daily`、`garden-weekly`、`garden-crash`):指令:走不到——scratch 一開就把今天那份看過(沒事不報),下一份要明天平日 8:44、每週要週一;「園丁報告」開關只在電腦版;當掉要程式真的出錯。看到:最接近的真路是自動測試(有失敗才報、一天一次、每週只列花太多的、當掉報告只說一次又遮過);關掉「園丁報告」兩種都不出現要在電腦版看。 -- 自動測試:`cargo test garden::`、`cargo test memory::`(`anybots_own_problems_are_reported_apart_from_the_skill`)、`cargo test logfile::`、`cargo test doctor::`。 +- 自動測試:`cargo test garden::`、`cargo test anybots_own_problems`(整理做法時另外記;一輪做完之後才回報的也記進清單)、`cargo test logfile::`、`cargo test doctor::`。 ## 陷阱 diff --git a/docs/feature-map/replay.md b/docs/feature-map/replay.md index 0996c19..adfc52c 100644 --- a/docs/feature-map/replay.md +++ b/docs/feature-map/replay.md @@ -25,10 +25,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-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 api POST /api/act/app '{"name":"skillify","args":{"prompt":"寫教學 [[call shell {\"command\":\"echo 教 >> teach.txt\"}]]"}}'`。看到:「已把「…」那一回合存成技能「…」(1 步可重播),…」。 -- **教我做的選單**(covers `replay-teach`):指令:走不到——選單要長按自己的訊息,ctl phone 沒有長按或右鍵。看到:最接近的真路是上一步(同一個請求)。 +- **教我做**(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-map`):指令:走不到——地圖的內容是真的模型照回頭看的提示寫的(假模型照劇本回)。看到:最接近的真路是第一步:回頭看的請求帶著「已經有的技能」,同名就合併;寫法靠自動測試。 -- 自動測試:`cargo test memory::`(`a_long_enough_job_is_looked_back_on`、`what_differs_each_time_becomes_a_blank_filled_at_replay`)、`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 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::`。 ## 陷阱 @@ -36,5 +35,6 @@ - `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。 - 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。 - 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面的步驟和照編號點的步驟。 +- 「教我做」學的是那則訊息開始的那一回合(同一句話之後又做過也一樣),只找得到 30 天內的;更早的、或做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。 - `save_skill` 存同名的技能會把原本存的可重播步驟一起換掉([skills](skills.md))。 - (驗證)插話太慢,那一輪會先結束、五步被拆成兩輪就不會學:每一步送出後立刻等下一個步驟出現再送。 diff --git a/mobile/index.html b/mobile/index.html index 0409585..899215a 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -1555,7 +1555,7 @@ function msgMenu(i) { if (m.text) items.push({icon: "copy", label: "複製", on: () => copyText(m.text)}); if (m.text && m.role !== "user" && S.voice.speak) items.push({icon: "audio-lines", label: "唸出來", on: () => speakText(m.text)}); if (m.text && owner()) items.push({icon: "reply", label: "引用回覆", on: () => { S.quote = {text: plain(m.text).slice(0, 300), raw: m.text}; renderQuote(); $("input").focus(); }}); - if (m.text && owner() && m.role === "user") items.push({icon: "sparkles", label: "教我做(學這一回合)", on: async () => { if (await app("skillify", {prompt: plain(m.text).slice(0, 200)}, 0, "已存成技能,下次說名字就會照做")) again(); }}); + if (m.text && owner() && m.role === "user") items.push({icon: "sparkles", label: "教我做(學這一回合)", on: () => app("skillify", {prompt: plain(m.text).slice(0, 200), at: m.at}, 0, "已存成技能,下次說名字就會照做")}); const lastBot = [...S.msgs].reverse().find((x) => x.role !== "user" && x.text); if (m === lastBot && owner()) items.push({icon: "refresh", label: "重新產生這個回答", on: regen}); // 重新產生 kept what it replaced (on the brain): put it back. diff --git a/src/app.rs b/src/app.rs index 9cc99f9..dec7a37 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2957,6 +2957,17 @@ impl App { self.dirty = true; continue; } + // 待改進: AnyBot's own problems the same look back found, queued for whoever fixes + // AnyBot — after the turn too. (A branch's are its main bot's, as its skills are.) + if let StreamEvent::Issues(list) = ev { + let name = self.state.bot(self.state.home_of(id)).map(|b| b.name.clone()).unwrap_or_default(); + let now = crate::routines::now(); + for i in &list { + crate::garden::note_issue(&mut self.state.improvements, i, &name, now); + } + self.dirty = true; + continue; + } // 目標: the check after a turn has spoken. if let StreamEvent::Goal(since, judged) = ev { self.goal_verdict(ctx, id, since, judged); @@ -3128,14 +3139,6 @@ impl App { m.images.clear(); } } - // 待改進: AnyBot's own problems this bot ran into, queued for whoever fixes AnyBot. - StreamEvent::Issues(list) => { - let name = b.name.clone(); - let now = crate::routines::now(); - for i in &list { - crate::garden::note_issue(&mut self.state.improvements, i, &name, now); - } - } // The model said how much it reads: this bot summarizes in time from now on. StreamEvent::ContextLimit(n) => { b.context_tokens = n; @@ -8260,6 +8263,26 @@ mod tests { } } + /// 待改進: the look back that finds AnyBot's own problems runs after the turn has ended + /// (agent::learn, after Done) — what it reports is queued then, like the skill it learns, + /// not dropped with a finished turn's leftovers. + #[test] + fn anybots_own_problems_found_after_the_turn_reach_the_list() { + let ctx = egui::Context::default(); + let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-issues-after-turn.png"))); + let id = app.state.bots[0].id; + let name = app.state.bots[0].name.clone(); + app.state.improvements.clear(); + app.streams.insert(id, Live { cancel: Arc::new(AtomicBool::new(false)), started: Instant::now(), last: Instant::now(), produced: true, status: None, paused: false, paused_at: None, unattended: false, steer: Arc::new(Mutex::new(vec![])), direct: Arc::new(AtomicBool::new(false)), turn_id: "t".into(), turn: 1 }); + // As agent.rs sends them: the turn is done, then the look back reports. + app.tx.send((id, 1, StreamEvent::Done)).unwrap(); + app.tx.send((id, 1, StreamEvent::Issues(vec!["browser_fill_contact 填不進電話欄".into(), "browser_fill_contact 又填錯欄".into()]))).unwrap(); + app.drain_events(&ctx); + assert!(!app.streams.contains_key(&id), "the turn is over"); + let got: Vec<(String, u32, Vec)> = app.state.improvements.iter().map(|i| (i.text.clone(), i.count, i.bots.clone())).collect(); + assert_eq!(got, vec![("browser_fill_contact 填不進電話欄".to_string(), 2, vec![name])], "one item for the one tool, counted twice"); + } + /// A question that takes another's place with the same call id (call_0 every round) and as /// many questions — the last one answered on the phone, or while this chat wasn't open — /// starts fresh: it doesn't take the last one's step and picks, so 送出 can't send answers diff --git a/src/appctl.rs b/src/appctl.rs index 54cf65d..e2950c8 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -766,16 +766,22 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome if prompt.is_empty() { return err("要學的是哪件事?".into()); } - let recs = crate::oplog::OpLog::for_bot(bot_id).read(); - match crate::memory::skillify(&prompt, &recs) { - Some(sk) => { + // 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 + // trail that can't be opened leaves the log. + let mut recs = crate::store::records(bot_id); + if recs.is_empty() { + recs = crate::oplog::OpLog::for_bot(bot_id).read(); + } + match crate::memory::skillify(&prompt, v["at"].as_i64(), &recs) { + Ok(sk) => { let n = sk.steps.len(); let name = sk.name.clone(); crate::memory::upsert_skill(&mut state.skills, sk); let who = learned(state, bot_id, &name); ok(format!("已把「{prompt}」那一回合存成技能「{name}」({n} 步可重播),{who}")) } - None => err("那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)".into()), + Err(why) => err(why), } } "create_bot" => { @@ -1030,6 +1036,31 @@ mod tests { assert!(st.bot(other).unwrap().skills.is_none()); } + /// 教我做 is pressed under a message whose turn is over — and a turn's work log is gone the + /// moment it ends. The audit trail still has its steps. + #[test] + fn a_turn_that_has_ended_can_still_be_taught() { + use crate::oplog::{OpLog, Outcome, Prompt, Record, Replay}; + let mut st = State::samples(); + // (Its own id: this process's tests share one trail.) + let bot = 7341; + st.bots[0].id = bot; + let log = OpLog::for_bot(bot); + let now = crate::model::now_ms(); + let said = "寫教學 [[call shell {\"command\":\"echo 教 >> teach.txt\"}]]"; + log.append(&Record::OperationStarted { op: "teach-1".into(), at: now, source_leaf: 0, prompt: Some(Prompt { at: now, text: said.into() }) }); + log.append(&Record::ToolStarted { op: "teach-1".into(), call_id: "c1".into(), name: "shell".into(), args: "{\"command\":\"echo 教 >> teach.txt\"}".into(), replay: Replay::Never, at: now + 1 }); + log.append(&Record::ToolFinished { op: "teach-1".into(), call_id: "c1".into(), status: "done".into(), at: now + 2 }); + log.finish("teach-1", Outcome::Completed); + assert!(log.read().is_empty(), "the turn's work log is gone once it ends"); + let out = apply(&mut st, bot, "skillify", &json!({"prompt": said}).to_string()); + assert!(out.ok && out.text.contains("(1 步可重播)"), "{}", out.text); + let k = st.skills.iter().find(|k| k.description == format!("示範學會:{said}")).expect("saved"); + assert_eq!((k.steps.len(), k.steps[0].tool.as_str(), k.steps[0].args.as_str()), (1, "shell", "{\"command\":\"echo 教 >> teach.txt\"}")); + let none = apply(&mut st, bot, "skillify", r#"{"prompt":"沒做過的事"}"#); + assert!(!none.ok && none.text.contains("找不到以「沒做過的事」開始的那一回合"), "{}", none.text); + } + #[test] fn a_routine_can_say_how_many_it_is_to_send_and_the_run_is_told() { let mut st = State::samples(); diff --git a/src/memory.rs b/src/memory.rs index 783e9db..32d6f25 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -196,29 +196,40 @@ pub fn merge_skill_files(skills: &mut Vec) -> usize { n } -/// C8: 示範即教學 — turn the most recent finished turn that answered `prompt` into a skill, -/// keeping the steps that worked and threw nothing away. Looking steps (screenshots, reads) are -/// dropped: a replay looks for itself. Steps that point at a number on the screen (ref) are -/// dropped too — numbers only live as long as the look that made them. -pub fn skillify(prompt: &str, recs: &[crate::oplog::Record]) -> Option { - let key: String = prompt.chars().take(40).collect(); - let mut op = String::new(); - for r in recs.iter().rev() { - if let crate::oplog::Record::OperationStarted { op: o, prompt: Some(p), .. } = r { - if p.text.chars().take(40).collect::() == key { - op = o.clone(); - break; - } - } - } - if op.is_empty() { - return None; - } +/// A message's words as the phone's 教我做 sends them (its `plain()`): link targets, markdown +/// marks and line breaks gone. A turn is found by these, whichever way its words arrive. +fn plain_words(t: &str) -> String { + static LINK: std::sync::OnceLock = std::sync::OnceLock::new(); + let link = LINK.get_or_init(|| regex::Regex::new(r"\[([^\]]+)\]\([^)]+\)").expect("link pattern")); + let t: String = link.replace_all(t, "$1").chars().filter(|c| !"*_`#>".contains(*c)).collect(); + t.split_whitespace().collect::>().join(" ") +} + +/// C8: 示範即教學 — turn the turn that `prompt` started into a skill, keeping the steps that +/// worked and threw nothing away. `at`: when that message was sent — the same words may have +/// started other turns since (an earlier try, a later one that went wrong), so it is the first +/// turn starting from then; without it (or with a clock that disagrees), the latest. Looking +/// steps (screenshots, reads) are dropped: a replay looks for itself. Steps that point at a +/// number on the screen (ref) are dropped too — numbers only live as long as the look that made +/// them. Err: why nothing was saved. +pub fn skillify(prompt: &str, at: Option, recs: &[crate::oplog::Record]) -> Result { + let key: String = plain_words(prompt).chars().take(40).collect(); + // (op, when the turn started, the words that started it), oldest first. + let turns: Vec<(&str, i64, &str)> = recs + .iter() + .filter_map(|r| match r { + crate::oplog::Record::OperationStarted { op, at, prompt: Some(p), .. } if plain_words(&p.text).chars().take(40).collect::() == key => Some((op.as_str(), *at, p.text.as_str())), + _ => None, + }) + .collect(); + 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)); + }; let mut done: Vec<(String, bool)> = vec![]; // index-parallel with steps: (call_id, finished ok) let mut steps: Vec<(String, String)> = vec![]; for r in recs { match r { - crate::oplog::Record::ToolStarted { op: o, call_id, name, args, .. } if o == &op => { + crate::oplog::Record::ToolStarted { op: o, call_id, name, args, .. } if o == op => { let a: serde_json::Value = serde_json::from_str(args).unwrap_or_default(); let looks = matches!( name.as_str(), @@ -230,7 +241,7 @@ pub fn skillify(prompt: &str, recs: &[crate::oplog::Record]) -> Option { done.push((call_id.clone(), true)); } } - crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == &op && status != "done" => { + crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == op && status != "done" => { if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) { e.1 = false; } @@ -246,13 +257,16 @@ pub fn skillify(prompt: &str, recs: &[crate::oplog::Record]) -> Option { .take(24) .collect(); if kept.is_empty() { - return None; + return Err("那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)".into()); } - let name: String = prompt.chars().take(24).collect(); - Some(Skill { + // Named and described in that turn's own words (what the phone sends has lost its marks: + // teach_log.txt came as teachlog.txt), on one line. + let said = said.split_whitespace().collect::>().join(" "); + let name: String = said.chars().take(24).collect(); + Ok(Skill { name, - description: format!("示範學會:{prompt}"), - instructions: format!("照著做過一次的那條路做完这件事:{prompt}"), + description: format!("示範學會:{said}"), + instructions: format!("照著做過一次的那條路做完這件事:{said}"), steps: kept, source: "learned".into(), ..Default::default() @@ -1421,12 +1435,60 @@ mod tests { Record::ToolStarted { op: "o1".into(), call_id: "c4".into(), name: "computer".into(), args: "{\"action\":\"click\",\"ref\":3}".into(), replay: Replay::Safe, at: 8 }, Record::ToolFinished { op: "o1".into(), call_id: "c4".into(), status: "done".into(), at: 9 }, ]; - let sk = skillify("每天記一下日期", &recs).unwrap(); + let sk = skillify("每天記一下日期", None, &recs).unwrap(); // only the shell date step survives: looks and numbered clicks are dropped, failures too assert_eq!(sk.steps.len(), 1); assert_eq!(sk.steps[0].tool, "shell"); assert!(sk.steps[0].args.contains("date")); - assert!(skillify("沒這回合", &recs).is_none()); + assert!(skillify("沒這回合", None, &recs).unwrap_err().starts_with("找不到以「沒這回合」開始的那一回合")); + assert!(sk.instructions.starts_with("照著做過一次的那條路做完這件事"), "{}", sk.instructions); + } + + /// The phone's 教我做 sends the message as it shows it (plain(): no marks, no line breaks, + /// a link's words only): that still finds the turn the message started. + #[test] + fn the_phones_plain_words_find_the_turn() { + use crate::oplog::{Prompt, Record, Replay}; + let said = "寫教學\n**記一筆** 到 [紀錄](https://example.com) >> teach_log.txt"; + let recs = vec![ + Record::OperationStarted { op: "o1".into(), at: 1, source_leaf: 0, prompt: Some(Prompt { at: 1, text: said.into() }) }, + Record::ToolStarted { op: "o1".into(), call_id: "c1".into(), name: "shell".into(), args: "{\"command\":\"echo 教 >> teach_log.txt\"}".into(), replay: Replay::Never, at: 2 }, + Record::ToolFinished { op: "o1".into(), call_id: "c1".into(), status: "done".into(), at: 3 }, + ]; + // (mobile/index.html: plain(m.text).slice(0, 200)) + let phone = "寫教學 記一筆 到 紀錄 teachlog.txt"; + let k = skillify(phone, None, &recs).unwrap(); + assert_eq!(k.steps.len(), 1); + // Named and described in the turn's own words, on one line. + 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. + let looked = vec![ + 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 }, + ]; + assert_eq!(skillify("看一下", None, &looked).unwrap_err(), "那一回合沒有可重播的步驟(只有看畫面的動作,或都失敗了)"); + } + + /// The same words, said on two days: the message pressed is the turn learned — Monday's run + /// that worked, not Tuesday's that went wrong after it. + #[test] + fn the_message_pressed_is_the_turn_learned() { + use crate::oplog::{Prompt, Record, Replay}; + let turn = |op: &str, at: i64, cmd: &str, status: &str| { + vec![ + Record::OperationStarted { op: op.into(), at: at + 5, source_leaf: 0, prompt: Some(Prompt { at, text: "幫我簽到".into() }) }, + Record::ToolStarted { op: op.into(), call_id: "c1".into(), name: "shell".into(), args: format!("{{\"command\":\"{cmd}\"}}"), replay: Replay::Never, at: at + 6 }, + Record::ToolFinished { op: op.into(), call_id: "c1".into(), status: status.into(), at: at + 7 }, + ] + }; + let recs: Vec = [turn("mon", 1_000, "sign-in --ok", "done"), turn("tue", 2_000, "sign-in --other", "done")].concat(); + 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] fn remember_tells_the_same_thing_from_another_fact() { diff --git a/src/store.rs b/src/store.rs index b6393c7..2d5d648 100644 --- a/src/store.rs +++ b/src/store.rs @@ -21,8 +21,8 @@ use rusqlite::{params, Connection}; use std::path::PathBuf; use std::sync::{Mutex, OnceLock}; -/// How far back the timeline answers. Rows older than this are deleted on open. -const KEEP_DAYS: i64 = 30; +/// How far back the timeline (and 教我做) answers. Rows older than this are deleted on open. +pub const KEEP_DAYS: i64 = 30; pub struct Store { conn: Mutex, @@ -368,6 +368,60 @@ 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 +/// (with the person's words), its steps (the arguments they ran with, how each ended) and its +/// end. What 教我做 reads — 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 (read as Never). +pub fn records(bot: u64) -> Vec { + let bot = bot as i64; + let Some(s) = store() 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("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![]; + }; + let rows = st + .query_map(params![bot, cutoff], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, i64>(1)?, + r.get::<_, Option>(2)?, + r.get::<_, String>(3)?, + r.get::<_, Option>(4)?, + r.get::<_, Option>(5)?, + r.get::<_, Option>(6)?, + r.get::<_, Option>(7)?, + )) + }) + .map(|it| it.filter_map(Result::ok).collect::>()) + .unwrap_or_default(); + 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(); + for (op, at, end_at, kind, name, detail, status, call_id) in rows { + if kind == "turn" { + out.push(Record::OperationStarted { op: op.clone(), at, source_leaf: 0, prompt: detail.map(|text| crate::oplog::Prompt { at, text }) }); + let outcome = match status.as_deref() { + Some("completed") => Some(Outcome::Completed), + Some("aborted") => Some(Outcome::Aborted), + Some("failed") => Some(Outcome::Failed), + _ => None, + }; + if let Some(outcome) = outcome { + ends.push(Record::OperationFinished { op, outcome }); + } + continue; + } + let call_id = call_id.unwrap_or_default(); + out.push(Record::ToolStarted { op: op.clone(), call_id: call_id.clone(), name: name.unwrap_or_default(), args: detail.unwrap_or_default(), replay: crate::oplog::Replay::Never, at }); + if let Some(status) = status.filter(|s| s != "running") { + out.push(Record::ToolFinished { op, call_id, status, at: end_at.unwrap_or(at) }); + } + } + out.extend(ends); + out +} + /// The phone's 稽核時間軸: finished turns stay here, so the page answers for /// KEEP_DAYS, not just for the turn running now. Newest turn first; the last 20 turns. pub fn turns(bot: u64) -> serde_json::Value { @@ -770,6 +824,15 @@ mod tests { 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"][2]["state"], "consumed"); + // …and as work-log lines again (what 教我做 reads): turns and steps, each turn's end + // after its steps. + let recs = records(bot); + let kinds: Vec = 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!(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[2], Record::ToolFinished { status, at, .. } if status == "done" && *at == t0 + 20)); + assert!(matches!(&recs[5], Record::OperationFinished { op, outcome: Outcome::Completed } if op == "op1")); } #[test] From 26054455643dafc7f5a3a1559a5afa0c34711ae8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 17:54:21 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix:=20=E3=80=8C=E6=95=99=E6=88=91=E5=81=9A?= =?UTF-8?q?=E3=80=8D=E5=AD=B8=E7=9A=84=E6=98=AF=E8=81=8A=E5=A4=A9=E8=A3=A1?= =?UTF-8?q?=E7=95=99=E8=91=97=E7=9A=84=E9=82=A3=E4=B8=80=E6=AC=A1=E2=80=94?= =?UTF-8?q?=E2=80=94=E7=A8=BD=E6=A0=B8=E7=B4=80=E9=8C=84=E8=A8=98=E4=B8=8B?= =?UTF-8?q?=E8=A8=8A=E6=81=AF=E7=9A=84=E6=99=82=E9=96=93=EF=BC=8C=E9=87=8D?= =?UTF-8?q?=E6=96=B0=E7=94=A2=E7=94=9F=E5=BE=8C=E4=B8=8D=E5=86=8D=E5=AD=B8?= =?UTF-8?q?=E5=88=B0=E8=A2=AB=E6=8F=9B=E6=8E=89=E7=9A=84=E9=82=A3=E6=AC=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一版用「訊息時間之後第一個開始的回合」找那一回合,但稽核紀錄沒存訊息自己的時間(還原時拿回合 開始的時間代替),而重新產生、重新傳送、重試是同一則訊息(同一個 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 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- docs/feature-map/replay.md | 7 ++- src/appctl.rs | 55 ++++++++++++++++--- src/memory.rs | 109 +++++++++++++++++++----------------- src/store.rs | 110 +++++++++++++++++++++++++++---------- 4 files changed, 190 insertions(+), 91 deletions(-) diff --git a/docs/feature-map/replay.md b/docs/feature-map/replay.md index adfc52c..231177c 100644 --- a/docs/feature-map/replay.md +++ b/docs/feature-map/replay.md @@ -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-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 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`):指令:走不到——地圖的內容是真的模型照回頭看的提示寫的(假模型照劇本回)。看到:最接近的真路是第一步:回頭看的請求帶著「已經有的技能」,同名就合併;寫法靠自動測試。 -- 自動測試:`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 的)。 - `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。 - 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。 -- 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面的步驟和照編號點的步驟。 -- 「教我做」學的是那則訊息開始的那一回合(同一句話之後又做過也一樣),只找得到 30 天內的;更早的、或做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。 +- 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面、讀說明或技能、重播的步驟和照編號點的步驟。 +- 「教我做」學的是那則訊息開始的那一回合(同一句話別次做的不算);按過重新產生、重新傳送或重試,學的是聊天裡留著的最後那一次。只找得到 30 天內的;更早的、做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。舊版手機頁面不帶訊息的時間,就學最近一次以同樣的話開始的回合(插的話跟某一回合開頭一樣,會學到那一回合)。 - `save_skill` 存同名的技能會把原本存的可重播步驟一起換掉([skills](skills.md))。 - (驗證)插話太慢,那一輪會先結束、五步被拆成兩輪就不會學:每一步送出後立刻等下一個步驟出現再送。 diff --git a/src/appctl.rs b/src/appctl.rs index e2950c8..0b65fb7 100644 --- a/src/appctl.rs +++ b/src/appctl.rs @@ -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 /// it for them (Bot 設定 › 技能). Says who can use it now. 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); if state.bots.iter().any(|b| b.id != bot_id && b.skills.is_some()) { "你會用了;其他 Bot 要在 Bot 設定 › 技能勾選才會。".into() @@ -767,13 +769,11 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome return err("要學的是哪件事?".into()); } // 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 - // trail that can't be opened leaves the log. - let mut recs = crate::store::records(bot_id); - if recs.is_empty() { - recs = crate::oplog::OpLog::for_bot(bot_id).read(); - } - match crate::memory::skillify(&prompt, v["at"].as_i64(), &recs) { + // work log keeps only the open turn; the audit trail keeps each one KEEP_DAYS. Which + // turn from the turns' first lines (`at`: when the message was sent), then that one's steps. + let taught = crate::memory::taught_turn(&prompt, v["at"].as_i64(), &crate::store::turn_starts(bot_id)) + .and_then(|(op, said)| crate::memory::skillify(&said, &crate::store::turn_records(bot_id, &op))); + match taught { Ok(sk) => { let n = sk.steps.len(); let name = sk.name.clone(); @@ -1061,6 +1061,47 @@ mod tests { 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] fn a_routine_can_say_how_many_it_is_to_send_and_the_run_is_told() { let mut st = State::samples(); diff --git a/src/memory.rs b/src/memory.rs index 32d6f25..6a22199 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -205,43 +205,48 @@ fn plain_words(t: &str) -> String { t.split_whitespace().collect::>().join(" ") } -/// C8: 示範即教學 — turn the turn that `prompt` started into a skill, keeping the steps that -/// worked and threw nothing away. `at`: when that message was sent — the same words may have -/// started other turns since (an earlier try, a later one that went wrong), so it is the first -/// turn starting from then; without it (or with a clock that disagrees), the latest. Looking -/// steps (screenshots, reads) are dropped: a replay looks for itself. Steps that point at a -/// number on the screen (ref) are dropped too — numbers only live as long as the look that made -/// them. Err: why nothing was saved. -pub fn skillify(prompt: &str, at: Option, recs: &[crate::oplog::Record]) -> Result { +/// Which turn 教我做 means: the one the pressed message started. `at` is when that message was +/// sent; one message can start several turns (重新產生、重新傳送、重試 start it again) and the +/// chat shows the last, so it is the latest turn started by that very message — none (a 插話 +/// starts no turn of its own): not found. Without `at` (an older phone page) it is the latest +/// turn started by the same words. `starts`: the turns' first lines (store::turn_starts). +/// Ok: (that turn, the words that started it). +pub fn taught_turn(prompt: &str, at: Option, starts: &[crate::oplog::Record]) -> Result<(String, String), String> { let key: String = plain_words(prompt).chars().take(40).collect(); - // (op, when the turn started, the words that started it), oldest first. - let turns: Vec<(&str, i64, &str)> = recs + starts .iter() - .filter_map(|r| match r { - crate::oplog::Record::OperationStarted { op, at, prompt: Some(p), .. } if plain_words(&p.text).chars().take(40).collect::() == key => Some((op.as_str(), *at, p.text.as_str())), + .rev() + .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::() == key => Some((op.clone(), p.text.clone())), _ => None, }) - .collect(); - 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)); - }; + .ok_or_else(|| 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 { let mut done: Vec<(String, bool)> = vec![]; // index-parallel with steps: (call_id, finished ok) let mut steps: Vec<(String, String)> = vec![]; for r in recs { 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 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(); - if !looks && !numbered { + if !never_replayed(name) && !numbered { steps.push((name.clone(), args.clone())); 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) { e.1 = false; } @@ -551,7 +556,7 @@ pub fn replay_steps(turn: &[crate::model::Message], picks: &[usize], blanks: &[( let mut out = vec![]; for &k in picks { 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; } 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}; let recs = vec![ 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::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::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::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 }, + // 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(); - // only the shell date step survives: looks and numbered clicks are dropped, failures too - assert_eq!(sk.steps.len(), 1); - assert_eq!(sk.steps[0].tool, "shell"); + let (op, said) = taught_turn("每天記一下日期", None, &recs[..1]).unwrap(); + assert_eq!((op.as_str(), said.as_str()), ("o1", "每天記一下日期")); + let sk = skillify(&said, &recs).unwrap(); + // 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::>(), ["shell"]); 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); } @@ -1457,38 +1467,35 @@ mod tests { ]; // (mobile/index.html: plain(m.text).slice(0, 200)) 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); // Named and described in the turn's own words, on one line. 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. let looked = vec![ 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 }, ]; - 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 - /// that worked, not Tuesday's that went wrong after it. + /// The message pressed is the turn learned: Monday's 「幫我簽到」 is Monday's run, not + /// 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] fn the_message_pressed_is_the_turn_learned() { - use crate::oplog::{Prompt, Record, Replay}; - let turn = |op: &str, at: i64, cmd: &str, status: &str| { - vec![ - Record::OperationStarted { op: op.into(), at: at + 5, source_leaf: 0, prompt: Some(Prompt { at, text: "幫我簽到".into() }) }, - Record::ToolStarted { op: op.into(), call_id: "c1".into(), name: "shell".into(), args: format!("{{\"command\":\"{cmd}\"}}"), replay: Replay::Never, at: at + 6 }, - Record::ToolFinished { op: op.into(), call_id: "c1".into(), status: status.into(), at: at + 7 }, - ] - }; - let recs: Vec = [turn("mon", 1_000, "sign-in --ok", "done"), turn("tue", 2_000, "sign-in --other", "done")].concat(); - 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())); + use crate::oplog::{Prompt, Record}; + // (op, when the turn started, when its message was sent) + 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() }) }; + let starts = [start("mon", 1_005, 1_000), start("tue", 2_005, 2_000), start("tue-again", 2_500, 2_000)]; + let op = |at| taught_turn("幫我簽到", at, &starts).map(|t| t.0); + 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"); + assert_eq!(op(None), Ok("tue-again".into()), "no time (an older phone page): the latest by its words"); } #[test] fn remember_tells_the_same_thing_from_another_fact() { diff --git a/src/store.rs b/src/store.rs index 2d5d648..83299a8 100644 --- a/src/store.rs +++ b/src/store.rs @@ -82,12 +82,21 @@ fn audit_schema(c: &Connection) -> Option<()> { name TEXT, detail 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_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<()> { @@ -319,8 +328,8 @@ pub fn record(bot: u64, r: &Record) { match r { Record::OperationStarted { op, at, prompt, .. } => { let _ = c.execute( - "INSERT INTO audit(bot,op,at,kind,detail) VALUES(?1,?2,?3,'turn',?4)", - params![bot, op, at, prompt.as_ref().map(|p| p.text.clone())], + "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()), prompt.as_ref().map(|p| p.at)], ); } 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 -/// (with the person's words), its steps (the arguments they ran with, how each ended) and its -/// end. What 教我做 reads — 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 (read as Never). -pub fn records(bot: u64) -> Vec { - let bot = bot as i64; +/// The turns of the last KEEP_DAYS, oldest first, as each one's first work-log line: what the +/// person said and when that message was sent (0: a turn kept before the trail had it). What +/// 教我做 picks a turn from — then turn_records reads just that one. +pub fn turn_starts(bot: u64) -> Vec { + let cutoff = crate::model::now_ms() - KEEP_DAYS * 86_400_000; + 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 { + 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 { let Some(s) = store() 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("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 { + 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 { return vec![]; }; let rows = st - .query_map(params![bot, cutoff], |r| { + .query_map(args, |r| { Ok(( - r.get::<_, String>(0)?, - r.get::<_, i64>(1)?, - r.get::<_, Option>(2)?, - r.get::<_, String>(3)?, - r.get::<_, Option>(4)?, - r.get::<_, Option>(5)?, - r.get::<_, Option>(6)?, - r.get::<_, Option>(7)?, + (r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, Option>(2)?, r.get::<_, String>(3)?), + (r.get::<_, Option>(4)?, r.get::<_, Option>(5)?, r.get::<_, Option>(6)?, r.get::<_, Option>(7)?, r.get::<_, Option>(8)?), )) }) .map(|it| it.filter_map(Result::ok).collect::>()) .unwrap_or_default(); 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(); - 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" { - 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() { Some("completed") => Some(Outcome::Completed), 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]["status"], "done", "the finished tool answers with its end status"); assert_eq!(ts[1]["steps"][2]["state"], "consumed"); - // …and as work-log lines again (what 教我做 reads): turns and steps, each turn's end - // after its steps. - let recs = records(bot); + // …and as work-log lines again (what 教我做 reads): the turns' starts, with when the + // message was sent; then one turn's start, steps and end. + 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 = 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!(matches!(&recs[0], Record::OperationStarted { prompt: Some(p), .. } if p.text == "幫我叫車")); + assert_eq!(kinds, ["operation_started", "tool_started", "tool_finished", "operation_finished"]); 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[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) = 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 = 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] From e755e5878dfda1805b31aa1fec96ee96318adb1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 19:27:21 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix:=20=E3=80=8C=E6=95=99=E6=88=91=E5=81=9A?= =?UTF-8?q?=E3=80=8D=E5=B8=B6=E9=99=84=E4=BB=B6=E7=9A=84=E8=A8=8A=E6=81=AF?= =?UTF-8?q?=E3=80=81=E6=9B=B4=E6=96=B0=E5=89=8D=E7=9A=84=E5=9B=9E=E5=90=88?= =?UTF-8?q?=E4=B9=9F=E5=AD=B8=E5=BE=97=E5=88=B0=EF=BC=9B=E7=A8=BD=E6=A0=B8?= =?UTF-8?q?=E7=B4=80=E9=8C=84=E5=8A=A0=E4=B8=8D=E4=BA=86=E6=96=B0=E6=AC=84?= =?UTF-8?q?=E4=BD=8D=E6=99=82=E7=85=A7=E6=A8=A3=E5=AF=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 帶附件的訊息:送給模型的那一份會在使用者的字後面接上附件的說明(app.rs 組歷史時),工作紀錄記的 就是那一份,所以短訊息的前 40 字對不上,只會說「找不到(只找得到 30 天內…)」。現在帶了 at 就只認 時間(那則訊息本身),技能的名字和說明用 attach::typed_part 拿掉附件說明、只留使用者打的字; 照字找的路(沒帶 at 的舊手機頁面)也先拿掉附件說明再比。 - 更新前的回合:那時的稽核紀錄沒記訊息時間(讀成 0),帶了 at 一定對不上。對不上時改在「沒記時間」 的回合裡照字找最近一次——有記時間的回合不會被這樣找到,所以插話、重新產生的判斷不受影響;風險只有 更新前 30 天內、插話剛好跟某一回合開頭一樣,跟舊手機頁面同一種,陷阱照實寫。 - 稽核紀錄:ALTER TABLE 失敗(例如另一個 AnyBot 正拿著寫入鎖)時,回合那一列原本因為指名 prompt_at 而寫不進去,手機的稽核時間軸也跟著空掉。insert_turn 寫不進時改寫不帶 prompt_at 的版本;讀的時候沒有 那一欄就當時間不知道。 - verify-anybot:phone 多一個 upload <檔>(DOM.setFileInputFiles,代替系統的檔案選擇器), 用來驗證聊天的附件;SKILL.md、ctl 的用法一起寫。 - 功能地圖 replay.md:陷阱補上「這一版以前做的回合照字找」;自動測試列上新測試。 - 沒改:學習步驟裡的 computer_use_show、當掉後「繼續」把一件事拆成兩回合——都不會讓 Bot 或使用者 誤會到要寫進陷阱。 已驗證: 完整 cargo test(金鑰清空、DOCKER_HOST 指到不存在、ANYBOT_HF_BASE 連不到)全綠(678 過、46 ignored 沒跑);cargo clippy --bin anybot --all-targets -- -D warnings 沒有警告;sh deploy/ci/lint-sh.sh 過。新測試 memory::a_message_with_a_file_and_an_older_turn_can_be_taught、store::the_trail_keeps_writing_when_the_new_column_cannot_be_added (真的讓 ALTER 失敗:另一條連線 BEGIN IMMEDIATE 拿著寫入鎖)、attach::the_words_typed_come_back_from_the_models_copy。 證明會擋:taught_turn 換回上一個 commit(2605445)的版本,帶附件的訊息「找不到」;拿掉沒記時間的 照字找,更新前的回合「找不到」;拿掉不帶 prompt_at 的 insert 和讀法,回合一列都沒寫進去;放回去都過。 verify-anybot 冷開照地圖寫的跑 replay.md 四步都過;另外用新的 upload 在手機選一個檔案(清單.txt)送 「看這張」,假模型收到的是「看這張\n\n[附件「清單.txt」…]」,長按 › 教我做 存成技能「看這張」、說明 「示範學會:看這張」、一步 echo 看過 >> seen.txt。 未驗證: 真的手機選檔案(用 DOM.setFileInputFiles 代替系統的檔案選擇器)和長按(用無頭 Chrome 的觸控事件); 已經有舊 audit.db、而且裡面有更新前回合的真實資料夾——只用單元測試;ALTER 失敗的情況只在單元測試裡造出來; 「網站地圖」照地圖寫的走不到(要真的模型)。 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- .claude/skills/verify-anybot/SKILL.md | 1 + .claude/skills/verify-anybot/scripts/ctl | 4 +- .../skills/verify-anybot/scripts/phone.mjs | 11 ++++ docs/feature-map/replay.md | 4 +- src/attach.rs | 15 ++++++ src/memory.rs | 43 +++++++++++---- src/store.rs | 52 ++++++++++++++++--- 7 files changed, 109 insertions(+), 21 deletions(-) diff --git a/.claude/skills/verify-anybot/SKILL.md b/.claude/skills/verify-anybot/SKILL.md index f465212..59b6eec 100644 --- a/.claude/skills/verify-anybot/SKILL.md +++ b/.claude/skills/verify-anybot/SKILL.md @@ -76,6 +76,7 @@ $CTL phone login # 手機密碼從 scratch 的檔案打進去(不 | `click [--text <字>]` | 在元素正中間按一下;`--text` 選含這些字的那一個 | | `long-press [--text <字>]` | 在元素正中間用手指(觸控)按住 0.8 秒再放開:手機的長按,例如自己訊息的選單 `long-press '.m.user .bub' --text 某句話` | | `send <字>` | 在聊天的輸入框 `#input` 打字、按送出 `#b-send` | +| `upload <檔>` | 在檔案選擇欄(`input type=file`,隱藏的也可以)選這個檔案,代替系統的檔案選擇器;聊天的附件是 `upload '#file' <檔>`,送出前 `wait-text <檔名> --in '#chips'` | | `type <字>` | 點進輸入框、清空、像鍵盤一樣打字 | | `press Enter`(`Escape`、`Tab`、`Backspace`) | 按鍵 | | `text [css]` | 印出看得到的字 | diff --git a/.claude/skills/verify-anybot/scripts/ctl b/.claude/skills/verify-anybot/scripts/ctl index 2f995bf..90d704c 100755 --- a/.claude/skills/verify-anybot/scripts/ctl +++ b/.claude/skills/verify-anybot/scripts/ctl @@ -16,7 +16,7 @@ # ctl model-reply <比對的字> <回答> | --clear 之後 system 或最後一則使用者訊息含這段字的請求,假模型回這個答案 # ctl model [jq 篩選] 假模型收到的請求(model-requests.jsonl,一行一個) # ctl procs [--none] <字> 這次 scratch 開的程式(環境帶著 scratch 的 HOME)裡,指令列含這段字的;--none:要一個都沒有 -# ctl phone <動作> … 用無頭 Chrome 操作手機頁面(start、open [--listed]、login [--wrong]、send <字>、click、long-press、type、wait…、shot、stop) +# ctl phone <動作> … 用無頭 Chrome 操作手機頁面(start、open [--listed]、login [--wrong]、send <字>、click、long-press、upload、type、wait…、shot、stop) # ctl fingerprint 比對連上時拿到的憑證和資料夾裡的 lan-cert.der # ctl desktop-shot <名稱> [ANYBOT_SHOT_*=值 …] 把桌面視窗畫成圖(會在螢幕上開一下視窗:要 ABV_ALLOW_WINDOW=1) # ctl down 關掉這次開的一切、把最後狀態抄進證據、刪 scratch;證據留著 @@ -419,7 +419,7 @@ cmd_phone() { node "$PHONE" --state "$st" type '#input' "$1" node "$PHONE" --state "$st" click '#b-send' ;; stop) node "$PHONE" --state "$st" stop; setv CHROME_PID "" ;; - "") die "ctl phone …" ;; + "") die "ctl phone …" ;; *) node "$PHONE" --state "$st" --out "$RUN/phone" "$sub" "$@" ;; esac } diff --git a/.claude/skills/verify-anybot/scripts/phone.mjs b/.claude/skills/verify-anybot/scripts/phone.mjs index f82c0da..e2eb9fe 100755 --- a/.claude/skills/verify-anybot/scripts/phone.mjs +++ b/.claude/skills/verify-anybot/scripts/phone.mjs @@ -11,6 +11,7 @@ // click [--text <字>] 在元素正中間按一下(有 --text:符合 css 而且含這些字的那一個) // long-press [--text <字>] 在元素正中間用手指按住 0.8 秒再放開(手機的長按,例如訊息的選單) // type <字> | --file <檔> 點進輸入框、清空、像鍵盤一樣打進去(--file:字從檔案讀,密碼不進指令列) +// upload <檔> 在檔案選擇欄(input type=file,可以是隱藏的)選這個檔案,等於系統的檔案選擇器選好按「打開」 // press <鍵> Enter、Escape、Tab、Backspace // text [css] 印出看得到的字 // shot <名稱> 證據:/NN-名稱.png(截圖)、.ax.txt(無障礙樹)、.txt(看得到的字) @@ -244,6 +245,16 @@ async function main() { await c.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); break; } + case "upload": { + // 系統的檔案選擇器開不了(無頭):直接把檔案放進那個 input,頁面照樣收到 change。 + const file = rest[1] || die("upload 要 css 和檔案"); + if (!fs.existsSync(file)) die(`沒有這個檔案:${file}`); + const { root } = await c.send("DOM.getDocument", { depth: 0 }); + const { nodeId } = await c.send("DOM.querySelector", { nodeId: root.nodeId, selector: rest[0] }); + if (!nodeId) die(`找不到 ${rest[0]}`); + await c.send("DOM.setFileInputFiles", { nodeId, files: [path.resolve(file)] }); + break; + } case "type": { const css = rest[0]; const text = FILE ? fs.readFileSync(FILE, "utf8").trim() : rest[1]; diff --git a/docs/feature-map/replay.md b/docs/feature-map/replay.md index 231177c..92c8596 100644 --- a/docs/feature-map/replay.md +++ b/docs/feature-map/replay.md @@ -28,7 +28,7 @@ - **教我做**(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`):指令:走不到——地圖的內容是真的模型照回頭看的提示寫的(假模型照劇本回)。看到:最接近的真路是第一步:回頭看的請求帶著「已經有的技能」,同名就合併;寫法靠自動測試。 -- 自動測試:`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::`。 +- 自動測試:`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`、`a_message_with_a_file_and_an_older_turn_can_be_taught`)、`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::`。 ## 陷阱 @@ -36,6 +36,6 @@ - `replay_skill` 屬於「看螢幕與操作」能力:沒有這個能力的 Bot、別人(訊息管道、團隊成員)傳來的那一輪都沒有它。技能沒存步驟就只能讀了自己做。 - 重播會停下來:空格沒給齊(會說要填哪幾格);畫面上找不到同一種、同名的東西時先自動截一次圖再找,還是沒有就停在第幾步交還給 Bot;任何一步失敗、被拒或重複,後面都不做。有風險的步驟照樣問使用者。 - 某一步點的東西說不出名字(只有編號),整份就不存步驟;「教我做」也會丟掉只看畫面、讀說明或技能、重播的步驟和照編號點的步驟。 -- 「教我做」學的是那則訊息開始的那一回合(同一句話別次做的不算);按過重新產生、重新傳送或重試,學的是聊天裡留著的最後那一次。只找得到 30 天內的;更早的、做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。舊版手機頁面不帶訊息的時間,就學最近一次以同樣的話開始的回合(插的話跟某一回合開頭一樣,會學到那一回合)。 +- 「教我做」學的是那則訊息開始的那一回合(同一句話別次做的不算);按過重新產生、重新傳送或重試,學的是聊天裡留著的最後那一次。只找得到 30 天內的;更早的、做事中途插的話,會說「找不到以「…」開始的那一回合」;只有看畫面或都失敗的會說「那一回合沒有可重播的步驟」。舊版手機頁面不帶訊息的時間、或那一回合是這一版以前做的(沒記時間),就學最近一次以同樣的話開始的回合(插的話跟某一回合開頭一樣,會學到那一回合)。 - `save_skill` 存同名的技能會把原本存的可重播步驟一起換掉([skills](skills.md))。 - (驗證)插話太慢,那一輪會先結束、五步被拆成兩輪就不會學:每一步送出後立刻等下一個步驟出現再送。 diff --git a/src/attach.rs b/src/attach.rs index 3d4398e..865b2bc 100644 --- a/src/attach.rs +++ b/src/attach.rs @@ -256,10 +256,25 @@ pub fn for_model(atts: &[Attachment]) -> (String, Vec) { (text, images) } +/// The words a person wrote, without what for_model put after them (a turn's first line in the +/// work log is the model's copy of the message). +pub fn typed_part(text: &str) -> &str { + text.find("\n\n[附件").map_or(text, |i| &text[..i]) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn the_words_typed_come_back_from_the_models_copy() { + let a = |name: &str| Attachment { name: name.into(), path: format!("/nowhere/{name}"), image: name.ends_with(".png"), bytes: 3, on_box: String::new() }; + let (extra, _) = for_model(&[a("貓.png"), a("帳.bin")]); + assert!(extra.contains("[附件圖片「貓.png」") && extra.contains("[附件「帳.bin」"), "{extra}"); + assert_eq!(typed_part(&format!("看這張\n第二行{extra}")), "看這張\n第二行"); + assert_eq!(typed_part("沒有附件"), "沒有附件"); + } + #[test] fn text_and_images_reach_the_model() { let dir = std::env::temp_dir().join(format!("anybot-attach-test-{}", std::process::id())); diff --git a/src/memory.rs b/src/memory.rs index 6a22199..cd0056b 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -207,20 +207,25 @@ fn plain_words(t: &str) -> String { /// Which turn 教我做 means: the one the pressed message started. `at` is when that message was /// sent; one message can start several turns (重新產生、重新傳送、重試 start it again) and the -/// chat shows the last, so it is the latest turn started by that very message — none (a 插話 -/// starts no turn of its own): not found. Without `at` (an older phone page) it is the latest -/// turn started by the same words. `starts`: the turns' first lines (store::turn_starts). -/// Ok: (that turn, the words that started it). +/// chat shows the last, so it is the latest turn started by that very message (by its time +/// alone: the model's copy of the words carries its attachments' text too) — none (a 插話 starts +/// no turn of its own): not found. Without `at` (an older phone page), or for a turn kept before +/// the trail had the time (0), it is the latest turn started by the same words. `starts`: the +/// turns' first lines (store::turn_starts). Ok: (that turn, the words the person typed). pub fn taught_turn(prompt: &str, at: Option, starts: &[crate::oplog::Record]) -> Result<(String, String), String> { let key: String = plain_words(prompt).chars().take(40).collect(); - starts - .iter() - .rev() - .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::() == key => Some((op.clone(), p.text.clone())), + let same_words = |p: &crate::oplog::Prompt| plain_words(crate::attach::typed_part(&p.text)).chars().take(40).collect::() == key; + let latest = |ok: &dyn Fn(&crate::oplog::Prompt) -> bool| { + starts.iter().rev().find_map(|r| match r { + crate::oplog::Record::OperationStarted { op, prompt: Some(p), .. } if ok(p) => Some((op.clone(), crate::attach::typed_part(&p.text).to_string())), _ => None, }) - .ok_or_else(|| format!("找不到以「{prompt}」開始的那一回合(只找得到 {} 天內、由一則訊息開始的回合;做事中途插的話不算)", crate::store::KEEP_DAYS)) + }; + let found = match at { + Some(t) => latest(&|p| p.at == t).or_else(|| latest(&|p| p.at == 0 && same_words(p))), + None => latest(&same_words), + }; + found.ok_or_else(|| format!("找不到以「{prompt}」開始的那一回合(只找得到 {} 天內、由一則訊息開始的回合;做事中途插的話不算)", crate::store::KEEP_DAYS)) } /// Steps a replay never repeats: looking (a replay looks for itself), reading a guide or a skill, @@ -1497,6 +1502,24 @@ mod tests { assert!(op(Some(2_200)).unwrap_err().starts_with("找不到以「幫我簽到」開始的那一回合"), "a 插話 typed at 2_200 started no turn"); assert_eq!(op(None), Ok("tue-again".into()), "no time (an older phone page): the latest by its words"); } + + /// A message sent with a file: the turn's words carry the file's text after the person's + /// (the model's copy) — found by the message's time, named in the words typed. A turn kept + /// before the trail had the time (0) is found by its words. + #[test] + fn a_message_with_a_file_and_an_older_turn_can_be_taught() { + use crate::oplog::{Prompt, Record}; + let file = crate::attach::Attachment { name: "貓.png".into(), path: "/nowhere/貓.png".into(), image: true, bytes: 3, on_box: String::new() }; + let modelled = format!("看這張{}", crate::attach::for_model(&[file]).0); + let starts = [ + Record::OperationStarted { op: "old".into(), at: 500, source_leaf: 0, prompt: Some(Prompt { at: 0, text: "以前的簽到".into() }) }, + Record::OperationStarted { op: "with-file".into(), at: 3_005, source_leaf: 3_000, prompt: Some(Prompt { at: 3_000, text: modelled }) }, + ]; + assert_eq!(taught_turn("看這張", Some(3_000), &starts), Ok(("with-file".into(), "看這張".into()))); + assert_eq!(taught_turn("看這張", None, &starts).map(|t| t.0), Ok("with-file".into()), "by its words too"); + assert_eq!(taught_turn("以前的簽到", Some(400), &starts).map(|t| t.0), Ok("old".into()), "a turn from before the time was kept"); + assert!(taught_turn("以前的", Some(400), &starts).is_err(), "…by all its words, not a part"); + } #[test] fn remember_tells_the_same_thing_from_another_fact() { let bot = 4261; diff --git a/src/store.rs b/src/store.rs index 83299a8..32abf45 100644 --- a/src/store.rs +++ b/src/store.rs @@ -326,12 +326,7 @@ pub fn record(bot: u64, r: &Record) { let Ok(c) = s.conn.lock() else { return }; let now = crate::model::now_ms(); match r { - Record::OperationStarted { op, at, prompt, .. } => { - let _ = c.execute( - "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()), prompt.as_ref().map(|p| p.at)], - ); - } + Record::OperationStarted { op, at, prompt, .. } => insert_turn(&c, bot, op, *at, prompt.as_ref()), Record::StepAttempt { op, step, .. } => { let _ = c.execute("INSERT INTO audit(bot,op,at,kind,name) VALUES(?1,?2,?3,'model',?4)", params![bot, op, now, step]); } @@ -397,7 +392,13 @@ pub fn turn_records(bot: u64, op: &str) -> Vec { fn rebuilt(filter: &str, args: impl rusqlite::Params) -> Vec { let Some(s) = store() else { return vec![] }; let Ok(c) = s.conn.lock() else { return vec![] }; - 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 { + rebuilt_on(&c, filter, args) +} + +fn rebuilt_on(c: &Connection, filter: &str, args: impl rusqlite::Params) -> Vec { + // (A trail that never got prompt_at reads every message's time as unknown.) + let sql = |sent: &str| format!("SELECT op,at,end_at,kind,name,detail,status,call_id,{sent} FROM audit WHERE {filter} ORDER BY id ASC"); + let Ok(mut st) = c.prepare(&sql("prompt_at")).or_else(|_| c.prepare(&sql("NULL"))) else { return vec![]; }; let rows = st @@ -436,6 +437,15 @@ fn rebuilt(filter: &str, args: impl rusqlite::Params) -> Vec { out } +/// A turn's row, with when its message was sent — or without, on a trail that never got that +/// column (the ALTER failed): the timeline keeps going either way. +fn insert_turn(c: &Connection, bot: i64, op: &str, at: i64, prompt: Option<&crate::oplog::Prompt>) { + let text = prompt.map(|p| p.text.as_str()); + if c.execute("INSERT INTO audit(bot,op,at,kind,detail,prompt_at) VALUES(?1,?2,?3,'turn',?4,?5)", params![bot, op, at, text, prompt.map(|p| p.at)]).is_err() { + let _ = c.execute("INSERT INTO audit(bot,op,at,kind,detail) VALUES(?1,?2,?3,'turn',?4)", params![bot, op, at, text]); + } +} + /// The phone's 稽核時間軸: finished turns stay here, so the page answers for /// KEEP_DAYS, not just for the turn running now. Newest turn first; the last 20 turns. pub fn turns(bot: u64) -> serde_json::Value { @@ -851,6 +861,34 @@ mod tests { assert!(!turn_records(bot, "op2").iter().any(|r| matches!(r, Record::OperationFinished { .. })), "the open turn has no end"); } + /// Another AnyBot holds the trail's write lock when this one opens it: the new column can't + /// be added — the trail still opens, and turns are still written (their time unknown). + #[test] + fn the_trail_keeps_writing_when_the_new_column_cannot_be_added() { + let dir = std::env::temp_dir().join(format!("anybot-audit-noalter-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join("audit.db"); + let other = connect(&p).unwrap(); + other + .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); + CREATE INDEX audit_bot_at ON audit(bot, at DESC); CREATE INDEX audit_call ON audit(bot, op, call_id); + BEGIN IMMEDIATE;", + ) + .unwrap(); + let c = connect(&p).unwrap(); + c.busy_timeout(std::time::Duration::ZERO).unwrap(); + assert!(audit_schema(&c).is_some(), "the trail still opens"); + other.execute_batch("COMMIT;").unwrap(); + let has: i64 = c.query_row("SELECT COUNT(*) FROM pragma_table_info('audit') WHERE name='prompt_at'", [], |r| r.get(0)).unwrap(); + assert_eq!(has, 0, "the column couldn't be added"); + insert_turn(&c, 5, "op1", 100, Some(&Prompt { at: 90, text: "照樣記下".into() })); + let recs = rebuilt_on(&c, "bot=?1", params![5]); + assert!(matches!(recs.as_slice(), [Record::OperationStarted { op, prompt: Some(p), .. }] if op == "op1" && p.text == "照樣記下" && p.at == 0), "{recs:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// (op, (words, when sent)) of each turn turn_starts gives. fn turns_started(bot: u64) -> Vec<(String, Option<(String, i64)>)> { turn_starts(bot) From 7adcb172788cd9fb2f76192b4427244a1555aedb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Wed, 18 Nov 2026 19:43:41 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix:=20=E6=95=99=E6=88=91=E5=81=9A=E2=80=94?= =?UTF-8?q?=E2=80=94=E8=A8=8A=E6=81=AF=E6=99=82=E9=96=93=E6=98=AF=200?= =?UTF-8?q?=EF=BC=88=E8=A8=98=E4=B8=8B=E6=99=82=E9=96=93=E4=B9=8B=E5=89=8D?= =?UTF-8?q?=E7=9A=84=E8=A8=8A=E6=81=AF=EF=BC=89=E4=B8=8D=E7=AE=97=E6=8C=87?= =?UTF-8?q?=E5=90=8D=E5=93=AA=E4=B8=80=E5=9B=9E=E5=90=88=EF=BC=8C=E7=85=A7?= =?UTF-8?q?=E5=AD=97=E6=89=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 審查(e755e58)的 P2:手機對記下時間之前的訊息送 at: 0,taught_turn 拿 0 去比,任何沒記時間的回合 都對得上,按一則跟它無關的舊訊息也會學到最新那個沒記時間的回合。0 當成沒給時間,走照字的那條路。 已驗證: memory 測試補兩句(at 0+同樣的字找得到、at 0+不同的字找不到);拿掉修正時 a_message_with_a_file_and_an_older_turn_can_be_taught 失敗,放回後逐位元組相同; 全部 cargo test(不帶金鑰、DOCKER_HOST 指到不存在)通過;clippy -D warnings 乾淨 未驗證: 真的資料夾裡升級前的回合(只有單元測試) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Uirha5sXAsDLzxz6UZJgoC --- src/memory.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/memory.rs b/src/memory.rs index cd0056b..54cab7e 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -213,6 +213,8 @@ fn plain_words(t: &str) -> String { /// the trail had the time (0), it is the latest turn started by the same words. `starts`: the /// turns' first lines (store::turn_starts). Ok: (that turn, the words the person typed). pub fn taught_turn(prompt: &str, at: Option, starts: &[crate::oplog::Record]) -> Result<(String, String), String> { + // A message from before times were kept says `at: 0`: that names no turn — go by its words. + let at = at.filter(|t| *t > 0); let key: String = plain_words(prompt).chars().take(40).collect(); let same_words = |p: &crate::oplog::Prompt| plain_words(crate::attach::typed_part(&p.text)).chars().take(40).collect::() == key; let latest = |ok: &dyn Fn(&crate::oplog::Prompt) -> bool| { @@ -1519,6 +1521,10 @@ mod tests { assert_eq!(taught_turn("看這張", None, &starts).map(|t| t.0), Ok("with-file".into()), "by its words too"); assert_eq!(taught_turn("以前的簽到", Some(400), &starts).map(|t| t.0), Ok("old".into()), "a turn from before the time was kept"); assert!(taught_turn("以前的", Some(400), &starts).is_err(), "…by all its words, not a part"); + // A message from before times were kept comes with `at: 0`: found by its words, never as + // whichever untimed turn is newest. + assert_eq!(taught_turn("以前的簽到", Some(0), &starts).map(|t| t.0), Ok("old".into())); + assert!(taught_turn("完全不同的一句話", Some(0), &starts).is_err(), "at 0 names no turn"); } #[test] fn remember_tells_the_same_thing_from_another_fact() {