`);
}
+// 完成宣稱關卡: under a reply that didn't match what its turn did; tapping it says why.
+function unvMark(m, i) {
+ return (m.check || []).length ? `` : "";
+}
+function unvSheet(i) {
+ const m = S.msgs[i];
+ if (!m || !(m.check || []).length) return;
+ sheet("未驗證", [], `
AnyBot 核對這一輪實際做了什麼,跟這則回覆對不上
${m.check.map((c) => `
${esc(c.why)}
`).join("")}
`);
+}
+// A link to a place on the bot's computer (sandbox:, file://, a path): the chat's file of that
+// name opens; otherwise it is said plainly that it can't open here.
+function openDeadLink(name) {
+ let n = name || "";
+ try { n = decodeURIComponent(n); } catch (_) {}
+ const a = [...S.msgs].reverse().flatMap((m) => m.attachments || []).find((x) => x.path && n && x.name.toLowerCase() === n.toLowerCase());
+ if (a) openFile(a.path, a.name, a.id || "");
+ else toast("這個連結指到 Bot 電腦上的位置,手機打不開;聊天裡也沒有這個檔案");
+}
// The device this page names for itself in 交付確認.
function deviceLabel() {
const ua = navigator.userAgent || "";
@@ -2014,7 +2034,8 @@ function renderMsgs() {
const bub = m.text ? `
`;
});
// Still working: what it is doing now; a message nobody answered yet can be sent again.
if (busy) h += (lastMsg && lastMsg.role !== "user" && !lastMsg.text && !(lastMsg.tools || []).length) || lastMsg?.role === "user" ? `
` : "";
@@ -2049,6 +2070,8 @@ $("msgs").addEventListener("click", async (e) => {
// The end of a drag that selected words is not a tap: nothing folds, opens or goes.
if (!e.target.closest("button,a") && selIn(e.target)) return;
const dv = e.target.closest("[data-dlv]"); if (dv) { dlvSheet(dv.dataset.dlv); return; }
+ const uv = e.target.closest("[data-unv]"); if (uv) { unvSheet(+uv.dataset.unv); return; }
+ const fl = e.target.closest("a.flink"); if (fl) { e.preventDefault(); openDeadLink(fl.dataset.fname); return; }
const st = e.target.closest(".step .h");
if (st) { const k = st.parentElement.dataset.step; S.openSteps[k] = !S.openSteps[k]; st.parentElement.classList.toggle("open"); return; }
const f = e.target.closest(".fold"); if (f) { S.unfold[f.dataset.turn] = true; renderMsgs(); return; }
@@ -2303,7 +2326,7 @@ const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達
/** What woke the bot, from the tag its message starts with (app::chat_ui::wake_tag on the
* desktop): [tag, icon, label], and the words after it. 監看's tag carries the command's number, so
* its words stay whole. (Every wake used to say 例行任務 — a 監看's lines, a colleague's message.) */
-const WAKE_TAGS = [["[目標]", "target", "目標"], ["[例行任務]", "alarm-clock", "例行任務"], ["[觸發]", "zap", "觸發"], ["[訊息管道]", "message", "訊息管道"], ["[來自 Bot]", "bot", "來自其他 Bot"], ["[交付]", "circle-alert", "交付沒顯示"], ["⏰ ", "alarm-clock", "例行任務"], ["⚡ ", "zap", "觸發"], ["💬 ", "message", "訊息管道"], ["📨 ", "bot", "來自其他 Bot"]];
+const WAKE_TAGS = [["[目標]", "target", "目標"], ["[例行任務]", "alarm-clock", "例行任務"], ["[觸發]", "zap", "觸發"], ["[訊息管道]", "message", "訊息管道"], ["[來自 Bot]", "bot", "來自其他 Bot"], ["[交付]", "circle-alert", "交付沒顯示"], ["[核對]", "circle-alert", "回覆沒對上"], ["⏰ ", "alarm-clock", "例行任務"], ["⚡ ", "zap", "觸發"], ["💬 ", "message", "訊息管道"], ["📨 ", "bot", "來自其他 Bot"]];
function wakeTag(text) {
const t = String(text || "");
for (const [tag, icon, label] of WAKE_TAGS) if (t.startsWith(tag)) return {icon, label, body: t.slice(tag.length)};
@@ -3634,6 +3657,8 @@ function inl(s) {
.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, "$1$2")
.replace(/~~([^~]+)~~/g, "$1")
.replace(/\[([^\]]+)\]\(page:(\d+)\)/g, (_, t, id) => `${t}`)
+ // A place on the bot's computer (sandbox:, file://, a path): opens the chat's file of that name.
+ .replace(/\[([^\]]+)\]\(((?:sandbox:|file:)[^)\s]*|(?:\/(?!\/)|~\/|\.\.?\/)[^)\s]*|[A-Za-z]:[\\/][^)\s]*)\)/g, (_, t, u) => `${t}`)
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '$1')
.replace(/(^|[\s((::,、「])(https?:\/\/[^\s<))」,。]+)/g, '$1$2');
}
diff --git a/src/app.rs b/src/app.rs
index 8a44827..d7fd41e 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -57,6 +57,7 @@ static STOPPING: AtomicBool = AtomicBool::new(false);
mod branch;
mod followup_ui;
mod deliver_ui;
+mod claims_ui;
mod talk_ui;
mod group;
#[cfg(test)]
@@ -2294,6 +2295,10 @@ impl App {
if !leftover.is_empty() {
self.pending_turns.push((bot_id, leftover));
}
+ // 完成宣稱關卡: what the reply says, against what the turn did (claims_ui.rs).
+ if outcome == TurnOutcome::Success && !is_branch {
+ self.check_claims(bot_id);
+ }
}
self.approvals.remove(&bot_id);
self.app_pending.remove(&bot_id);
@@ -7382,6 +7387,10 @@ fn group_history(messages: &[Message], speaker: Option, conv: u64, st: &Sta
if m.role == Role::Assistant && !m.reactions.is_empty() {
m.text = format!("{}\n(使用者對這則回應:{})", m.text, m.reactions.join(" "));
}
+ // 完成宣稱關卡: what AnyBot found when it checked this reply against its turn.
+ if m.role == Role::Assistant && !m.check.is_empty() {
+ m.text = format!("{}\n{}", m.text, crate::claims::history_line(&m.check));
+ }
// In a bot's own chat, a colleague's report (message_bot's answer back) is its words,
// labelled — not this bot's own.
if speaker.is_none() && m.role == Role::Assistant && m.author != 0 && m.author != conv && !m.summary {
diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs
index 7fda1e7..b32c604 100644
--- a/src/app/chat_ui.rs
+++ b/src/app/chat_ui.rs
@@ -836,6 +836,10 @@ impl App {
self.delivery_mark(ui, bot.id, &a, &card);
}
}
+ // 完成宣稱關卡: 「未驗證」 when the reply didn't match what its turn did.
+ if !m.check.is_empty() && !streaming {
+ self.claims_mark(ui, &m.check);
+ }
if !m.reactions.is_empty() {
ui.add_space(4.0);
ui.horizontal(|ui| {
@@ -1196,9 +1200,9 @@ pub fn slash_commands(draft: &str) -> Vec<(&'static str, &'static str)> {
/// The tags a woken message starts with: (tag, icon, label). The emoji forms are what older chats
/// were saved with. (The phone has the same table: mobile/index.html WAKE_TAGS.)
-const WAKE_TAGS: [(&str, crate::icons::Icon, &str); 10] = {
+const WAKE_TAGS: [(&str, crate::icons::Icon, &str); 11] = {
use crate::icons::Icon;
- [("[目標]", Icon::Target, "目標"), ("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("[交付]", Icon::Alert, "交付沒顯示"), ("⏰ ", Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")]
+ [("[目標]", Icon::Target, "目標"), ("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("[交付]", Icon::Alert, "交付沒顯示"), (crate::claims::WAKE_TAG, Icon::Alert, "回覆沒對上"), ("⏰ ",Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")]
};
/// "[例行任務]…" → (icon, label) and the words after the tag.
diff --git a/src/app/claims_ui.rs b/src/app/claims_ui.rs
new file mode 100644
index 0000000..3b43713
--- /dev/null
+++ b/src/app/claims_ui.rs
@@ -0,0 +1,184 @@
+// 完成宣稱關卡 in the window: when a turn ends well, its reply is held up against what the turn
+// really did (claims.rs) and what is found is kept on the reply. A hard one — said done or sent
+// and it wasn't, a link only the bot's computer opens — wakes the bot once to put it right, when
+// the turn was the owner's. Under the reply: a quiet 「未驗證」, why on hover. (The phone draws the
+// same from message_json's `check`; a screen computer from the brain's message.) A link to a
+// place on the bot's computer whose file is in the chat opens that file (markdown_ui).
+
+use super::*;
+use crate::claims::{self, Flag, Kind};
+
+/// Wakes for replies that didn't match since the person last wrote: no more than this.
+const WAKES_PER_EXCHANGE: usize = 1;
+
+/// How many times the bot was woken for a reply that didn't match since the owner last wrote.
+fn wakes_since_person(msgs: &[Message]) -> usize {
+ // (The owner's own word: a teammate's, another bot's or a 支線's report doesn't count again.)
+ let from = msgs.iter().rposition(|m| m.role == Role::User && !m.wake && !m.untrusted_sender && m.from_bot == 0 && m.branch == 0).map_or(0, |i| i + 1);
+ msgs[from..].iter().filter(|m| m.wake && m.text.starts_with(claims::WAKE_TAG)).count()
+}
+
+impl App {
+ /// After a turn that ended well (settle): its reply against its steps. Kept on the reply; a
+ /// hard one wakes the bot once — only when the owner started the turn (not a messaging
+ /// channel, a teammate or another bot: their request must not come back as a turn with the
+ /// owner's trust), not in a group chat (every member would take a turn), not while a goal
+ /// goes on (its judge reads the steps and carries on) or the person's next words wait.
+ pub(super) fn check_claims(&mut self, bot_id: u64) {
+ if self.demo {
+ return;
+ }
+ let goal_on = self.state.bot(bot_id).and_then(|b| b.goal.as_ref()).is_some_and(|g| g.active());
+ let person_next = self.pending_turns.iter().any(|(b, _)| *b == bot_id);
+ let waiting = self.waiting_wakes.iter().filter(|(b, m)| *b == bot_id && m.text.starts_with(claims::WAKE_TAG)).count();
+ let Some(b) = self.state.bot_mut(bot_id) else { return };
+ // The turn: from the message that started it (words sent while it worked are part of it).
+ let Some(start) = b.messages.iter().rposition(|m| m.role == Role::User && !m.steer) else { return };
+ let Some((at, flags)) = claims::check(&b.messages, start, !b.members.is_empty()) else { return };
+ if flags.is_empty() || b.messages[at].check == flags {
+ return;
+ }
+ log::info!("AnyBot:完成宣稱關卡 Bot {bot_id}:{}", flags.iter().map(|f| format!("{:?}", f.kind)).collect::>().join("、"));
+ b.messages[at].check = flags.clone();
+ let starter = &b.messages[start];
+ let owners = !starter.untrusted_sender && starter.from_bot == 0;
+ let quiet = !b.members.is_empty() || !owners || goal_on || person_next;
+ let hard: Vec = flags.iter().map(|f| f.kind).filter(|k| k.hard()).collect();
+ let since = wakes_since_person(&b.messages) + waiting;
+ self.mark();
+ self.save_now = true;
+ if hard.is_empty() || quiet || since >= WAKES_PER_EXCHANGE {
+ return;
+ }
+ // (The bot is free now: the wake starts its own turn on the next tick.)
+ self.waiting_wakes.push((bot_id, Message { wake: true, ..Message::user(&claims::wake_text(&hard)) }));
+ }
+
+ /// Under a reply AnyBot couldn't verify: 「未驗證」, and why on hover.
+ pub(super) fn claims_mark(&self, ui: &mut egui::Ui, flags: &[Flag]) {
+ let shown: Vec<&Flag> = flags.iter().filter(|f| f.kind.shown()).collect();
+ if shown.is_empty() {
+ return;
+ }
+ let p = self.pal;
+ ui.add_space(2.0);
+ let row = ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ let (rect, _) = ui.allocate_exact_size(vec2(12.0, 12.0), egui::Sense::hover());
+ crate::icons::paint(ui.painter(), rect, crate::icons::Icon::Alert, p.text3);
+ ui.label(RichText::new(t("未驗證")).size(FONT_XS).color(p.text3));
+ });
+ row.response.interact(egui::Sense::hover()).on_hover_ui(|ui| {
+ ui.set_max_width(340.0);
+ ui.label(RichText::new(t("AnyBot 核對這一輪實際做了什麼,跟這則回覆對不上")).size(FONT_SM).color(p.text));
+ for f in shown {
+ ui.label(RichText::new(format!("• {}", f.why)).size(FONT_XS).color(p.text2));
+ }
+ });
+ }
+
+ /// A link to a place on the bot's computer (claims::dead_link): a file of that name in the
+ /// open chat opens; a path that is on this computer opens as before; otherwise it is said
+ /// plainly that it can't open here.
+ pub(super) fn open_dead_link(&mut self, url: &str, name: &str) {
+ let local = url.strip_prefix("file://").unwrap_or(url);
+ let local = local.strip_prefix("~/").map(|r| dirs::home_dir().unwrap_or_default().join(r)).unwrap_or_else(|| std::path::PathBuf::from(local));
+ let found = self.state.bot(self.state.selected).and_then(|b| b.messages.iter().rev().flat_map(|m| m.attachments.iter()).find(|a| !name.is_empty() && a.name.eq_ignore_ascii_case(name)).map(|a| (a.name.clone(), a.path.clone())));
+ if let Some((n, path)) = found {
+ self.open_file(&n, &path);
+ } else if !url.to_lowercase().starts_with("sandbox:") && local.is_absolute() && local.exists() {
+ let _ = crate::computer::spawn_reaped(&mut crate::preview::system_open(&local.display().to_string()));
+ } else {
+ self.notice = Some(t("這個連結指到 Bot 電腦上的位置,這裡打不開;聊天裡也沒有這個檔案。請 Bot 用 send_file 傳過來。"));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::ToolCall;
+
+ fn test_app(ctx: &egui::Context) -> App {
+ let mut app = App::new(ctx, Some(std::env::temp_dir().join("anybot-claims.png")));
+ // (A made-up screenshot chat checks nothing: this one is real.)
+ app.demo = false;
+ app
+ }
+
+ /// A turn the owner started: the bot's failed send_file, and a reply that says 「已傳」 with a
+ /// sandbox link.
+ fn bad_turn(app: &mut App, bot: u64, first: Message) {
+ let b = app.state.bot_mut(bot).unwrap();
+ b.messages.push(first);
+ b.messages.push(Message { tool_calls: vec![ToolCall { id: "c1".into(), name: "send_file".into(), args: r#"{"path":"x.md"}"#.into(), status: ToolStatus::Failed }], ..Message::assistant("", "") });
+ b.messages.push(Message::tool_result("c1", "send_file", "找不到 x.md"));
+ b.messages.push(Message::assistant("已傳好了 [下載](sandbox:/home/bot/x.md)", ""));
+ }
+
+ /// Kept on the reply, and the owner's turn wakes the bot once — with fixed words only.
+ #[test]
+ fn a_reply_that_doesnt_match_is_marked_and_wakes_once() {
+ let ctx = egui::Context::default();
+ let mut app = test_app(&ctx);
+ let bot = app.state.bots[0].id;
+ bad_turn(&mut app, bot, Message::user("把 x.md 傳給我"));
+ app.check_claims(bot);
+ let reply = app.state.bot(bot).unwrap().messages.last().unwrap().clone();
+ let kinds: Vec = reply.check.iter().map(|f| f.kind).collect();
+ assert!(kinds.contains(&Kind::Undone) && kinds.contains(&Kind::DeadLink), "{kinds:?}");
+ let woke: Vec = app.waiting_wakes.iter().filter(|(b, _)| *b == bot).map(|(_, m)| m.text.clone()).collect();
+ assert_eq!(woke.len(), 1);
+ assert!(woke[0].starts_with(claims::WAKE_TAG) && !woke[0].contains("x.md") && !woke[0].contains("/home/bot"), "{}", woke[0]);
+ // Again (the same reply, or the woken turn's reply as bad): no second wake.
+ app.check_claims(bot);
+ let woken = app.waiting_wakes.remove(0).1;
+ bad_turn(&mut app, bot, woken);
+ app.check_claims(bot);
+ assert!(app.waiting_wakes.is_empty(), "once since the owner last wrote");
+ assert!(!app.state.bot(bot).unwrap().messages.last().unwrap().check.is_empty(), "still marked");
+ // The owner writes again: one more is allowed.
+ bad_turn(&mut app, bot, Message::user("再傳一次"));
+ app.check_claims(bot);
+ assert_eq!(app.waiting_wakes.len(), 1);
+ }
+
+ /// Someone else's turn (a messaging channel, a teammate, another bot), a group chat, a count
+ /// only: marked, never woken.
+ #[test]
+ fn others_turns_and_soft_ones_are_only_marked() {
+ let ctx = egui::Context::default();
+ let mut app = test_app(&ctx);
+ let bot = app.state.bots[0].id;
+ for first in [Message { wake: true, untrusted_sender: true, ..Message::user("[訊息管道]【路人】傳給我") }, Message { untrusted_sender: true, ..Message::user("【小明】傳給我") }, Message { from_bot: 99, ..Message::user("傳給我") }] {
+ bad_turn(&mut app, bot, first);
+ app.check_claims(bot);
+ assert!(!app.state.bot(bot).unwrap().messages.last().unwrap().check.is_empty());
+ assert!(app.waiting_wakes.is_empty());
+ }
+ let other = app.state.bots[1].id;
+ app.state.bot_mut(bot).unwrap().members = vec![other];
+ bad_turn(&mut app, bot, Message::user("誰傳一下"));
+ app.check_claims(bot);
+ assert!(app.waiting_wakes.is_empty(), "a group chat");
+ app.state.bot_mut(bot).unwrap().members.clear();
+ let b = app.state.bot_mut(bot).unwrap();
+ b.messages.push(Message::user("發文"));
+ b.messages.push(Message { tool_calls: vec![ToolCall { id: "p1".into(), name: "post_to_x".into(), args: r#"{"text":"早安"}"#.into(), status: ToolStatus::Done }], ..Message::assistant("", "") });
+ b.messages.push(Message::tool_result("p1", "post_to_x", "已發文"));
+ b.messages.push(Message::assistant("共送出 3 則。", ""));
+ app.check_claims(bot);
+ assert_eq!(app.state.bot(bot).unwrap().messages.last().unwrap().check[0].kind, Kind::Count);
+ assert!(app.waiting_wakes.is_empty(), "a count is only marked");
+ }
+
+ /// The bot reads, after its own reply, what was found (and that it isn't its own words).
+ #[test]
+ fn the_bot_reads_what_was_found_under_its_reply() {
+ let st = State::demo();
+ let flags = vec![Flag { kind: Kind::FileLink, why: "連結「下載」指到 Bot 電腦上的位置".into() }];
+ let msgs = vec", "") }];
+ let h = super::super::group_history(&msgs, None, 0, &st);
+ assert!(h[1].text.contains("〔AnyBot 核對這則回覆時發現") && h[1].text.contains("不是你寫的") && h[1].text.contains("連結「下載」"), "{}", h[1].text);
+ }
+}
diff --git a/src/app/markdown_ui.rs b/src/app/markdown_ui.rs
index f6f2635..e46ea1a 100644
--- a/src/app/markdown_ui.rs
+++ b/src/app/markdown_ui.rs
@@ -755,6 +755,12 @@ impl App {
if resp.clicked() {
self.page_view = Some((pid, None));
}
+ } else if let Some(name) = crate::claims::dead_link(&url) {
+ // 完成宣稱關卡: a place on the bot's computer — the chat's file of that name.
+ let resp = resp.on_hover_text(&url);
+ if resp.clicked() {
+ self.open_dead_link(&url, &name);
+ }
} else {
let resp = resp.on_hover_text(&url);
if resp.clicked() {
diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs
index d0ba749..bfb60d3 100644
--- a/src/app/mirror_ui.rs
+++ b/src/app/mirror_ui.rs
@@ -194,6 +194,8 @@ fn msg_sig(m: &Message) -> u64 {
for a in &m.attachments {
a.seen.len().hash(&mut h);
}
+ // 完成宣稱關卡: so does the 「未驗證」 under a reply.
+ m.check.len().hash(&mut h);
h.finish()
}
@@ -2684,6 +2686,18 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ /// 完成宣稱關卡: a reply marked on the brain changes its fingerprint, so the screens hear of it
+ /// (and get the mark with the message).
+ #[test]
+ fn a_replys_check_reaches_the_screens() {
+ let m = Message::assistant("已傳好了", "");
+ let before = msg_sig(&m);
+ let marked = Message { check: vec![crate::claims::Flag { kind: crate::claims::Kind::NoFile, why: "沒有檔案".into() }], ..m };
+ assert_ne!(msg_sig(&marked), before);
+ let back: Message = serde_json::from_value(serde_json::to_value(&marked).unwrap()).unwrap();
+ assert_eq!(back.check, marked.check);
+ }
+
/// 交付確認 on a screen computer: the brain's file is shown from a local copy, but keeps its
/// id; what the screen saw goes to the brain by that id (named there, by who asked); a
/// device's word on a file changes the message's fingerprint, so the screens hear of it.
diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs
index fc5b62c..7e28e39 100644
--- a/src/app/remote_ui.rs
+++ b/src/app/remote_ui.rs
@@ -306,6 +306,8 @@ impl App {
for a in &m.attachments {
a.seen.len().hash(&mut h);
}
+ // 完成宣稱關卡: the reply's 「未驗證」.
+ m.check.len().hash(&mut h);
}
if let Some(l) = self.streams.get(&b.id) {
(1u8, &l.status, l.paused, l.steer.lock().unwrap().len()).hash(&mut h);
diff --git a/src/appctl.rs b/src/appctl.rs
index 3e9b15c..12cc0c0 100644
--- a/src/appctl.rs
+++ b/src/appctl.rs
@@ -315,7 +315,8 @@ pub struct Outcome {
pub page: Option,
}
-/// Pages sent back once by the 寫法檢查 (bot, title): the next write of the same page is saved.
+/// Pages sent back once by the 寫法檢查 (bot, pages::write_key): the next write of the same page
+/// is saved.
static SENT_BACK: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeSet::new());
fn ok(text: String) -> Outcome {
@@ -506,14 +507,18 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
return err(format!("這是「{who}」的頁面,你只能讀不能改。要改請它改(ask_bot 或 message_bot 交代要改什麼),或不帶 id 做一頁你自己的。"));
}
// 寫法檢查: a page that reads badly is sent back once with what to fix; the next try
- // is saved whatever it still has (no loop when something can't be helped).
- let key = (bot_id, v["title"].as_str().unwrap_or("").trim().to_string());
- let fixes = crate::pages::review(v["content"].as_str().unwrap_or(""));
- {
+ // is saved whatever it still has (no loop when something can't be helped). The same
+ // page by id or by title; only a try with content counts — a bot that sends the
+ // content, then the kind and summary on their own, was sent back again and again
+ // (the second call, with no content, used to clear the first).
+ let content = v["content"].as_str().unwrap_or("");
+ if !content.trim().is_empty() {
+ let key = (bot_id, crate::pages::write_key(&state.pages, bot_id, &v));
+ let fixes = crate::pages::review(content);
let mut sent_back = SENT_BACK.lock().unwrap_or_else(|e| e.into_inner());
if !fixes.is_empty() && sent_back.insert(key.clone()) {
return err(format!(
- "頁面還沒存:照這幾點改寫後再呼叫一次 write_page(同樣的標題)——\n• {}\n改不掉的地方第二次會照樣存。",
+ "頁面還沒存:照這幾點改寫後再呼叫一次 write_page(同樣的 id 或標題,帶整頁 content)——\n• {}\n改不掉的地方第二次會照樣存。只改 kind、summary、verdict 這些的話,不用帶 content。",
fixes.join("\n• ")
));
}
@@ -1294,6 +1299,43 @@ mod tests {
assert!(apply(&mut st, b, "write_page", &clean).ok);
}
+ /// The real case: a bot updating its page sent the content (sent back), then the kind, note,
+ /// summary and verdict on their own with only the id (「頁面內容是空的」, and that cleared the
+ /// sent-back mark) — eight rounds, and the page stayed old. Now the fields change, and the
+ /// next try with content is the second try of the same page: saved.
+ #[test]
+ fn a_page_sent_back_is_saved_on_its_next_content_whatever_comes_between() {
+ let mut st = State::samples();
+ let b = st.bots[0].id;
+ assert!(apply(&mut st, b, "write_page", &json!({"title": "助理規格", "content": "## 現況\n舊版。"}).to_string()).ok);
+ let pid = st.pages.iter().find(|p| p.bot == b && p.title == "助理規格").unwrap().id;
+ let messy = json!({"id": pid, "content": "## 一、目的\n新版。\n\n---"}).to_string();
+ let first = apply(&mut st, b, "write_page", &messy);
+ assert!(!first.ok && first.text.contains("頁面還沒存") && first.text.contains("不用帶 content"), "{}", first.text);
+ let meta = apply(&mut st, b, "write_page", &json!({"id": pid, "kind": "decision", "note": "改寫", "summary": "定稿", "verdict": "先做可信任"}).to_string());
+ assert!(meta.ok && meta.page == Some(pid) && meta.text.contains("種類") && meta.text.contains("內容沒動"), "{}", meta.text);
+ let p = st.pages.iter().find(|p| p.id == pid).unwrap();
+ assert_eq!((p.kind.as_str(), p.summary.as_str(), p.verdict.as_str(), p.body.as_str(), p.revision), ("decision", "定稿", "先做可信任", "## 現況\n舊版。", 1));
+ // The same page by its title this time: still its second try.
+ let second = apply(&mut st, b, "write_page", &json!({"title": "助理規格", "content": "## 一、目的\n新版。\n\n---"}).to_string());
+ assert!(second.ok, "{}", second.text);
+ let p = st.pages.iter().find(|p| p.id == pid).unwrap();
+ assert!(p.body.contains("新版") && p.revision == 2 && p.title == "助理規格" && p.kind == "decision", "{p:?}");
+ // A new page: sent back by its title, a fields-only try in between (no page yet), saved next.
+ let new = json!({"title": "新的一頁", "content": "## 一、開頭\n內容"}).to_string();
+ assert!(!apply(&mut st, b, "write_page", &new).ok);
+ let between = apply(&mut st, b, "write_page", &json!({"title": "新的一頁", "kind": "notes"}).to_string());
+ assert!(!between.ok && between.text.contains("內容是空的"), "{}", between.text);
+ assert!(apply(&mut st, b, "write_page", &new).ok);
+ // Nothing to change at all: said so.
+ let nothing = apply(&mut st, b, "write_page", &json!({"id": pid}).to_string());
+ assert!(!nothing.ok && nothing.text.contains("沒有要改的欄位"), "{}", nothing.text);
+ // New content by id alone keeps the title.
+ assert!(apply(&mut st, b, "write_page", &json!({"id": pid, "content": "## 現況\n第三版。"}).to_string()).ok);
+ let p = st.pages.iter().find(|p| p.id == pid).unwrap();
+ assert_eq!((p.title.as_str(), p.revision), ("助理規格", 3));
+ }
+
/// 共用資源: a colleague's page is read, never overwritten; a skill is taught (the person is
/// asked first); what's about the person is kept once for every bot; a request can't go
/// round the bots for ever.
diff --git a/src/claims.rs b/src/claims.rs
new file mode 100644
index 0000000..d59acf7
--- /dev/null
+++ b/src/claims.rs
@@ -0,0 +1,615 @@
+// 完成宣稱關卡: what a bot's reply says it did, checked by the program against what its turn
+// really did — at the end of every turn, never by asking the bot. Real cases: a bot sent a file
+// into the chat and ended with 「[下載:….md](sandbox:/home/bot/bot-12/….md)」, a link that opens
+// nothing on the person's phone; another said 「已完成」 after the step that would have done it
+// failed; another 「送出 2 則」 when one went (evidence.rs).
+//
+// Few and sure — a wrong mark costs more than a missed one: a claim counts only where the words
+// plainly say it is done (not 「還沒」, 「如果…」, 「…之後」, a question, a hedge, a reply that
+// owns up to a failure), and a link only where it can't open anywhere but the bot's computer.
+// What is found is kept on the reply (Message::check): a quiet 「未驗證」 under it, the bot reads
+// it with its reply next turn (app::group_history), and a hard one wakes the bot once (app.rs).
+
+use crate::model::{Message, Role, ToolCall, ToolStatus};
+use serde::{Deserialize, Serialize};
+
+/// The tag a woken message starts with when a reply didn't match its turn (chat_ui WAKE_TAGS,
+/// mobile/index.html WAKE_TAGS).
+pub const WAKE_TAG: &str = "[核對]";
+
+/// What kind of mismatch.
+#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum Kind {
+ /// Said done or sent, and the turn's last step that would have done it failed or was refused.
+ Undone,
+ /// Said it put a file in the chat, and the turn put none there.
+ NoFile,
+ /// A link to a place on the bot's computer (sandbox:, file://, a path) — opens on no device
+ /// of the person's — and no file of that name in the chat.
+ DeadLink,
+ /// A link like that to a file that is in the chat: the screens open that file instead.
+ FileLink,
+ /// A number (or 「全部」) the steps don't bear out.
+ Count,
+}
+
+impl Kind {
+ /// The person can't get what the reply says they have: the bot is woken once to put it right.
+ pub fn hard(self) -> bool {
+ matches!(self, Kind::Undone | Kind::NoFile | Kind::DeadLink)
+ }
+ /// Shown under the reply. (A link to a file in the chat opens that file: nothing to show —
+ /// the bot is still told.)
+ pub fn shown(self) -> bool {
+ self != Kind::FileLink
+ }
+}
+
+/// One thing found, with why in plain words (shown behind the mark and read by the bot).
+#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
+pub struct Flag {
+ pub kind: Kind,
+ pub why: String,
+}
+
+/// Words that say it is done.
+const DONE: [&str; 15] = ["已完成", "已經完成", "完成了", "做好了", "弄好了", "處理好了", "辦好了", "搞定", "都好了", "寫好了", "改好了", "修好了", "設好了", "建好了", "整理好了"];
+/// Words that say something went to the person or out.
+const SENT: [&str; 29] = [
+ "已傳", "已經傳", "傳好了", "傳給你了", "傳過去了", "已送出", "已經送出", "送出了", "已寄出", "已經寄出", "寄出了", "寄好了", "已交付", "已上傳", "已經上傳", "上傳好了", "上傳了", "已發佈", "已發布", "已經發佈", "已經發布", "發佈了", "發布了", "已發送", "已附上", "附上了", "已放進聊天", "放進聊天了", "已經附上",
+];
+/// …of those, the ones that say a file came with the reply (in the chat).
+const FILE_SENT: [&str; 12] = ["已傳", "已經傳", "傳好了", "傳給你了", "已附上", "附上了", "已經附上", "已放進聊天", "放進聊天了", "已上傳", "已經上傳", "已交付"];
+/// What a file is called.
+const FILE_WORDS: [&str; 12] = ["檔案", "文件", "附件", "圖片", "圖檔", "照片", "截圖", "報告", "規格", "簡報", "試算表", "PDF"];
+/// Where a file goes that isn't the chat (send_to_device, mail, a drive, a site…).
+const ELSEWHERE: [&str; 17] = ["手機", "裝置", "信箱", "郵件", "email", "Email", "雲端", "Drive", "Slack", "Telegram", "Discord", "LINE", "網站", "網址", "資料夾", "桌面", "伺服器"];
+/// The same in English (lower case).
+const EN_CLAIMS: [&str; 16] = ["i've sent", "i have sent", "has been sent", "have been sent", "i've uploaded", "has been uploaded", "i've attached", "is attached", "i've delivered", "has been delivered", "i've published", "has been published", "i've completed", "has been completed", "all done", "it's done"];
+const EN_NOT: [&str; 12] = ["not ", "n't", "never", "if ", "once ", "when ", "after ", "will ", "going to", "unable", "failed", "couldn"];
+/// Anywhere in the sentence: it isn't (all) done, or it owns up to a problem.
+const NOT_DONE: [&str; 23] = ["還沒", "尚未", "沒有", "沒能", "沒辦法", "無法", "未能", "失敗", "不能", "不了", "未完成", "沒完成", "沒傳", "沒送", "沒成功", "不成功", "出錯", "卡住", "但", "不過", "只是", "除了", "部分"];
+/// Said kindly, not a "not" (removed before NOT_DONE is looked for).
+const BENIGN: [&str; 6] = ["沒有問題", "沒問題", "沒有錯誤", "沒有任何錯誤", "沒錯", "不客氣"];
+/// Before the claim: a condition, a plan, a hedge.
+const IF_LATER: [&str; 24] = ["如果", "若", "假如", "要是", "萬一", "一旦", "等你", "等我", "等它", "等到", "等一下", "之後", "以後", "稍後", "待會", "我會", "會再", "將會", "準備", "打算", "應該", "可能", "希望", "是否"];
+/// Right after the claim: what it modifies or waits for (「已完成的部分」「傳好了之後」「做好了再…」).
+const AFTER: [&str; 9] = ["的", "之後", "以後", "後", "再", "嗎", "沒", "與否", "了沒"];
+/// Words in the reply that own up to a step that didn't go (then a 「已完成」 elsewhere in it
+/// isn't taken against the failed step).
+const OWNS_UP: [&str; 12] = ["失敗", "沒成功", "不成功", "出錯", "被擋", "擋下", "拒絕", "無法", "沒辦法", "卡住", "還沒", "尚未"];
+/// The reply refers to something sent before this turn.
+const BEFORE: [&str; 10] = ["之前", "剛才", "剛剛", "上次", "先前", "稍早", "上一則", "前面", "上面", "昨天"];
+
+/// The words of a reply that make claims: without code (```…``` and `…`) and quoted lines.
+fn prose(text: &str) -> String {
+ let mut out = String::new();
+ let mut fenced = false;
+ for line in text.lines() {
+ let t = line.trim_start();
+ if t.starts_with("```") || t.starts_with("~~~") {
+ fenced = !fenced;
+ } else if !fenced && !t.starts_with('>') {
+ let mut code = false;
+ for ch in line.chars() {
+ if ch == '`' {
+ code = !code;
+ } else if !code {
+ out.push(ch);
+ }
+ }
+ }
+ out.push('\n');
+ }
+ out
+}
+
+/// Its sentences, each with whether it asks.
+fn sentences(text: &str) -> Vec<(String, bool)> {
+ let mut out = vec![];
+ let mut cur = String::new();
+ let chars: Vec = text.chars().collect();
+ for (i, &ch) in chars.iter().enumerate() {
+ let end = match ch {
+ '。' | '!' | '!' | '\n' | ';' | ';' => Some(false),
+ '?' | '?' => Some(true),
+ // (A full stop, not the dot of a file name.)
+ '.' if chars.get(i + 1).is_none_or(|c| c.is_whitespace()) => Some(false),
+ _ => None,
+ };
+ match end {
+ Some(asks) => {
+ if !cur.trim().is_empty() {
+ out.push((std::mem::take(&mut cur), asks));
+ }
+ cur.clear();
+ }
+ None => cur.push(ch),
+ }
+ }
+ if !cur.trim().is_empty() {
+ out.push((cur, false));
+ }
+ out
+}
+
+/// The sentence when nothing in it says 「not (all) done」 (said kindly — 「沒問題」 — isn't a 「沒」).
+fn unhedged(sentence: &str) -> Option {
+ let mut s = sentence.to_string();
+ for b in BENIGN {
+ s = s.replace(b, "");
+ }
+ (!s.contains('嗎') && !NOT_DONE.iter().any(|n| s.contains(n))).then_some(s)
+}
+
+fn add(flags: &mut Vec, f: Flag) {
+ if !flags.iter().any(|g| g.kind == f.kind) {
+ flags.push(f);
+ }
+}
+
+/// A claim in a sentence: (the claim word, whether it is about sending).
+fn claim_in(sentence: &str, asks: bool) -> Option<(&'static str, bool)> {
+ if asks || sentence.contains('嗎') {
+ return None;
+ }
+ let low = sentence.to_lowercase();
+ if let Some(w) = EN_CLAIMS.iter().copied().find(|w| low.contains(w)) {
+ if EN_NOT.iter().any(|n| low.contains(n)) {
+ return None;
+ }
+ let sent = !w.contains("done") && !w.contains("completed");
+ return Some((w, sent));
+ }
+ let s = unhedged(sentence)?;
+ let words = SENT.iter().map(|w| (*w, true)).chain(DONE.iter().map(|w| (*w, false)));
+ for (w, sent) in words {
+ let Some(at) = s.find(w) else { continue };
+ let before = &s[..at];
+ let after = &s[at + w.len()..];
+ // Inside 「…」: quoted, not said.
+ if before.matches('「').count() > before.matches('」').count() {
+ continue;
+ }
+ // Someone else did it (「你已上傳」), not 「幫你…」.
+ let last2: String = before.trim_end().chars().rev().take(2).collect::>().into_iter().rev().collect();
+ if (last2.ends_with('你') || last2.ends_with('您') || last2.ends_with('他') || last2.ends_with('她')) && !["幫你", "替你", "給你", "為你", "幫您", "替您", "給您", "為您"].contains(&last2.as_str()) {
+ continue;
+ }
+ if IF_LATER.iter().any(|m| before.contains(m)) || AFTER.iter().any(|m| after.trim_start().starts_with(m)) {
+ continue;
+ }
+ return Some((w, sent));
+ }
+ None
+}
+
+/// Steps that only look (reading, searching, a card): never what a 「已完成」 rests on.
+fn only_looks(name: &str) -> bool {
+ const PREFIX: [&str; 12] = ["read_", "list_", "search_", "get_", "find", "view_", "query", "web_search", "web_fetch", "fetch", "recall", "look"];
+ const NAMES: [&str; 10] = ["anybot_guide", "react", "show_card", "wait_answer", "browser_snapshot", "browser_screenshot", "computer_use_screenshot", "use_skill", "update_plan", "think"];
+ PREFIX.iter().any(|p| name.starts_with(p)) || NAMES.contains(&name)
+}
+
+/// Steps that hand something over or send it out.
+fn delivers(call: &ToolCall) -> bool {
+ const NAMES: [&str; 6] = ["send_file", "send_to_device", "publish_site", "message_bot", "post_to_x", "send_sms"];
+ let low = call.name.to_lowercase();
+ NAMES.contains(&call.name.as_str()) || crate::evidence::sends(call) || ["send", "upload", "publish", "post", "mail", "reply"].iter().any(|w| low.contains(w))
+}
+
+/// Whether a step that ended failed really didn't go: a command that only answered 「no」
+/// (grep found nothing, a test was false: exit code 1 and nothing printed) isn't a failure.
+fn really_failed(call: &ToolCall, result: Option<&Message>) -> bool {
+ match call.status {
+ ToolStatus::Denied => true,
+ ToolStatus::Failed => !(call.name == "shell" && result.is_some_and(|r| r.text.strip_prefix("結束代碼 1").is_some_and(|rest| rest.trim().is_empty()))),
+ _ => false,
+ }
+}
+
+/// A link target that opens only on the bot's computer: sandbox:…, file://…, an absolute path
+/// (/home/…, ~/…, C:\…) or one relative to a folder (./…, ../…). Its file name when it is one.
+pub fn dead_link(target: &str) -> Option {
+ let t = target.trim().trim_start_matches('<').trim_end_matches('>');
+ let low = t.to_lowercase();
+ let b = t.as_bytes();
+ let path = if low.starts_with("sandbox:") || low.starts_with("file:") {
+ t.split_once(':').map(|(_, p)| p).unwrap_or("")
+ } else if (t.starts_with('/') && !t.starts_with("//")) || t.starts_with("~/") || t.starts_with("./") || t.starts_with("../") || (b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/')) {
+ t
+ } else {
+ return None;
+ };
+ let path = path.split(['?', '#']).next().unwrap_or("");
+ let name = path.rsplit(['/', '\\']).next().unwrap_or("");
+ Some(percent_decode(name))
+}
+
+fn percent_decode(s: &str) -> String {
+ let b = s.as_bytes();
+ let mut out = Vec::with_capacity(b.len());
+ let mut i = 0;
+ while i < b.len() {
+ if b[i] == b'%' && i + 2 < b.len() {
+ if let Some(v) = std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) {
+ out.push(v);
+ i += 3;
+ continue;
+ }
+ }
+ out.push(b[i]);
+ i += 1;
+ }
+ String::from_utf8(out).unwrap_or_else(|_| s.to_string())
+}
+
+/// The links in a reply: (their words, where they point). Markdown [words](target) and .
+fn links(text: &str) -> Vec<(String, String)> {
+ let mut out = vec![];
+ let mut rest = text;
+ while let Some(i) = rest.find("](") {
+ let words = rest[..i].rsplit_once('[').map(|(_, w)| w).unwrap_or("");
+ let tail = &rest[i + 2..];
+ let end = tail.find(')').unwrap_or(tail.len());
+ let target = tail[..end].trim();
+ // (A title after the target: [a](/x.md "title").)
+ let target = target.split_once(" \"").map(|(t, _)| t).unwrap_or(target);
+ out.push((words.to_string(), target.to_string()));
+ rest = &tail[end.min(tail.len())..];
+ }
+ let mut rest = text;
+ while let Some(i) = rest.find('<') {
+ let tail = &rest[i + 1..];
+ let Some(end) = tail.find('>') else { break };
+ let t = &tail[..end];
+ let low = t.to_lowercase();
+ if (low.starts_with("sandbox:") || low.starts_with("file:")) && !t.contains(char::is_whitespace) {
+ out.push((String::new(), t.to_string()));
+ }
+ rest = &tail[end..];
+ }
+ out
+}
+
+/// 一、二、兩…九十九, or digits.
+fn number(s: &str) -> Option {
+ if let Ok(n) = s.parse() {
+ return Some(n);
+ }
+ let digit = |c: char| "零一二三四五六七八九".chars().position(|d| d == c).map(|p| p as u32).or((c == '兩').then_some(2));
+ let cs: Vec = s.chars().collect();
+ match cs.as_slice() {
+ [a] if *a == '十' => Some(10),
+ [a] => digit(*a),
+ ['十', b] => Some(10 + digit(*b)?),
+ [a, '十'] => Some(digit(*a)? * 10),
+ [a, '十', b] => Some(digit(*a)? * 10 + digit(*b)?),
+ _ => None,
+ }
+}
+
+/// 「送出 2 則」「已傳 3 張圖」: (how many, whether it is files rather than messages).
+fn counts(sentence: &str) -> Vec<(u32, bool)> {
+ use std::sync::OnceLock;
+ static MSGS: OnceLock = OnceLock::new();
+ static FILES: OnceLock = OnceLock::new();
+ let msgs = MSGS.get_or_init(|| regex::Regex::new(r"(?:傳送|發送|送出|發出|發了|發佈|發布|回覆|回了|貼出|貼了|留言|私訊|傳)了?\s*(\d+|[一二兩三四五六七八九十]+)\s*(?:則|篇|條)").unwrap());
+ let files = FILES.get_or_init(|| regex::Regex::new(r"(?:傳|附上|放進聊天|送出)了?\s*(\d+|[一二兩三四五六七八九十]+)\s*(?:個檔案|份檔案|個附件|份|張圖片|張圖|張照片|張)").unwrap());
+ let mut out = vec![];
+ for (re, file) in [(msgs, false), (files, true)] {
+ for c in re.captures_iter(sentence) {
+ if let Some(n) = c.get(1).and_then(|m| number(m.as_str())) {
+ out.push((n, file));
+ }
+ }
+ }
+ out
+}
+
+/// Short, for a reason shown in one line.
+fn short(s: &str, n: usize) -> String {
+ let t: String = s.chars().take(n).collect();
+ if s.chars().count() > n { format!("{t}…") } else { t }
+}
+
+/// What a turn's reply claims that its steps don't bear out. `chat`: the whole chat; `start`:
+/// the message that began the turn; `group`: a group chat. The reply is the turn's last message
+/// of the bot's own with words — not a 支線's report or a colleague's (put in the chat as the
+/// bot's, with `branch` or another `author`); in a group chat, the member who answered, and only
+/// its steps count. Its index and what was found (maybe nothing).
+pub fn check(chat: &[Message], start: usize, group: bool) -> Option<(usize, Vec)> {
+ let own = |m: &Message| m.role == Role::Assistant && m.branch == 0 && (group || m.author == 0);
+ let reply_at = (start..chat.len()).rev().find(|&i| {
+ let m = &chat[i];
+ own(m) && !m.text.trim().is_empty() && !m.note && !m.error && !m.summary && !m.interrupted
+ })?;
+ let reply = &chat[reply_at];
+ let turn: Vec<&Message> = chat[start..].iter().filter(|m| m.role != Role::Assistant || (own(m) && m.author == reply.author)).collect();
+ let results: std::collections::HashMap<&str, &Message> = turn.iter().filter(|m| m.role == Role::Tool).map(|m| (m.tool_call_id.as_str(), *m)).collect();
+ let steps: Vec<(&ToolCall, Option<&Message>)> = turn.iter().filter(|m| m.role == Role::Assistant).flat_map(|m| m.tool_calls.iter()).map(|c| (c, results.get(c.id.as_str()).copied())).collect();
+ // Files this turn put in the chat (send_file's land on its message; a picture shown too).
+ let attached: usize = turn.iter().filter(|m| m.role == Role::Assistant).map(|m| m.attachments.len()).sum();
+ let files_here = attached.max(steps.iter().filter(|(c, _)| c.name == "send_file" && c.status == ToolStatus::Done).count());
+ let words = prose(&reply.text);
+ let owns_up = OWNS_UP.iter().any(|w| words.contains(w));
+ let mut flags: Vec = vec![];
+
+ // (b) Links that open only on the bot's computer.
+ let chat_files: Vec<&crate::attach::Attachment> = chat[..=reply_at].iter().flat_map(|m| m.attachments.iter()).collect();
+ for (label, target) in links(&words) {
+ let Some(name) = dead_link(&target) else { continue };
+ let shown = if label.trim().is_empty() { short(&target, 40) } else { short(label.trim(), 30) };
+ let place = short(&target, 48);
+ match chat_files.iter().rev().find(|a| !name.is_empty() && a.name.eq_ignore_ascii_case(&name)) {
+ Some(a) => add(&mut flags, Flag { kind: Kind::FileLink, why: format!("連結「{shown}」指到 Bot 電腦上的位置({place}),手機和其他電腦打不開;畫面改成打開聊天裡的附件「{}」", short(&a.name, 40)) }),
+ None => add(&mut flags, Flag { kind: Kind::DeadLink, why: format!("連結「{shown}」指到 Bot 電腦上的位置({place}),手機和其他電腦打不開;聊天裡也沒有這個檔案") }),
+ }
+ }
+
+ // (a) Said done or sent, and the step that would have done it didn't go; said a file came, and none did.
+ for (s, asks) in sentences(&words) {
+ let Some((word, about_sending)) = claim_in(&s, asks) else { continue };
+ let related = |c: &ToolCall| if about_sending { delivers(c) } else { !only_looks(&c.name) };
+ if let Some((c, r)) = steps.iter().rev().find(|(c, _)| related(c)) {
+ if really_failed(c, *r) && !owns_up {
+ let how = if c.status == ToolStatus::Denied { "被擋下了" } else { "失敗了" };
+ add(&mut flags, Flag { kind: Kind::Undone, why: format!("說「{word}」,但這一輪最後一個相關的步驟「{}」{how}", crate::remote::tool_label(&c.name)) });
+ continue;
+ }
+ }
+ let file_claim = FILE_SENT.contains(&word) && (FILE_WORDS.iter().any(|w| s.contains(w)) || has_file_name(&s));
+ let went_elsewhere = ELSEWHERE.iter().any(|w| s.contains(w)) || steps.iter().any(|(c, _)| c.status == ToolStatus::Done && c.name != "send_file" && delivers(c));
+ let named_before = file_names(&s).iter().any(|n| chat[..start].iter().flat_map(|m| m.attachments.iter()).any(|a| a.name.eq_ignore_ascii_case(n)));
+ if file_claim && files_here == 0 && !went_elsewhere && !owns_up && !named_before && !BEFORE.iter().any(|w| s.contains(w)) {
+ add(&mut flags, Flag { kind: Kind::NoFile, why: format!("說「{word}」檔案,但這一輪沒有任何檔案放進聊天") });
+ }
+ }
+
+ // (c) Numbers the steps don't bear out.
+ let tally = crate::evidence::tally(&turn.iter().map(|m| (*m).clone()).collect::>());
+ let tried_sends = steps.iter().any(|(c, r)| crate::evidence::sends(c) || crate::evidence::went_out(c, *r));
+ let uncounted = steps.iter().any(|(c, _)| crate::mcp::is_mcp_tool(&c.name));
+ if !flags.iter().any(|f| f.kind == Kind::Undone) {
+ for (s, asks) in sentences(&words) {
+ if asks || unhedged(&s).is_none() || IF_LATER.iter().any(|m| s.contains(m)) {
+ continue;
+ }
+ for (n, file) in counts(&s) {
+ if file && files_here >= 1 && n as usize > files_here {
+ add(&mut flags, Flag { kind: Kind::Count, why: format!("說傳了 {n} 個檔案,這一輪只有 {files_here} 個放進聊天") });
+ } else if !file && tried_sends && !uncounted && n > tally.sent {
+ add(&mut flags, Flag { kind: Kind::Count, why: format!("說送出 {n} 則,系統只數到 {} 則真的送出去", tally.sent) });
+ }
+ }
+ }
+ }
+ Some((reply_at, flags))
+}
+
+/// File names (x.md, 規格-給CodeAgent.md) in a sentence.
+fn file_names(s: &str) -> Vec {
+ use std::sync::OnceLock;
+ static RE: OnceLock = OnceLock::new();
+ let re = RE.get_or_init(|| regex::Regex::new(r"[^\s「」『』()()\[\]<>、,,::]+\.(?:md|txt|pdf|png|jpe?g|gif|webp|svg|docx?|xlsx?|csv|pptx?|zip|html?|json|mp3|mp4|mov|wav)\b").unwrap());
+ re.find_iter(s).map(|m| m.as_str().to_string()).collect()
+}
+
+fn has_file_name(s: &str) -> bool {
+ !file_names(s).is_empty()
+}
+
+/// What the bot reads after its own reply next turn (app::group_history).
+pub fn history_line(flags: &[Flag]) -> String {
+ format!("〔AnyBot 核對這則回覆時發現(這行是系統加的,不是你寫的):{}〕", flags.iter().map(|f| f.why.as_str()).collect::>().join(";"))
+}
+
+/// The message that wakes the bot once to put a hard one right. Only fixed words: what it said
+/// and linked is its own, but the message starts a turn with the owner's trust, so nothing from
+/// the reply (or from a page or a file name it may have copied) rides along — the bot reads its
+/// reply and the line under it.
+pub fn wake_text(kinds: &[Kind]) -> String {
+ let mut why: Vec<&str> = vec![];
+ for k in kinds {
+ let w = match k {
+ Kind::Undone => "回覆說做好了或傳好了,但這一輪最後一個相關的步驟失敗或被擋下了",
+ Kind::NoFile => "回覆說傳了檔案,但這一輪沒有任何檔案放進聊天",
+ Kind::DeadLink => "回覆裡的連結指到你電腦上的位置(sandbox:、file:// 或路徑),使用者的手機和電腦打不開,聊天裡也沒有同名的附件",
+ _ => continue,
+ };
+ if !why.contains(&w) {
+ why.push(w);
+ }
+ }
+ format!("{WAKE_TAG}你上一則回覆跟這一輪實際做到的對不上:{}。使用者在他的裝置上還拿不到結果。先查清楚,再做其中一件:真的做完(檔案用 send_file 傳進聊天),或照實告訴使用者還沒好、卡在哪裡、下一步是什麼。不要寫 sandbox:、file:// 或電腦上的路徑當連結。(這是系統的通知,不是使用者說的話。)", why.join(";"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::attach::Attachment;
+
+ fn step(id: &str, name: &str, args: &str, status: ToolStatus) -> ToolCall {
+ ToolCall { id: id.into(), name: name.into(), args: args.into(), status }
+ }
+
+ /// A turn: the person's words, the bot's steps (each with its result), then its reply (with
+ /// files, if any).
+ fn turn(steps: Vec<(ToolCall, &str)>, reply: &str, files: Vec<&str>) -> Vec {
+ let mut msgs = vec![Message::user("幫我做")];
+ for (c, result) in steps {
+ let id = c.id.clone();
+ let name = c.name.clone();
+ msgs.push(Message { tool_calls: vec![c], ..Message::assistant("", "") });
+ msgs.push(Message::tool_result(&id, &name, result));
+ }
+ let atts = files.into_iter().map(|n| Attachment { name: n.into(), path: format!("/brain/{n}"), id: "a1b2c3".into(), ..Default::default() }).collect();
+ msgs.push(Message { attachments: atts, ..Message::assistant(reply, "") });
+ msgs
+ }
+
+ fn kinds(msgs: &[Message]) -> Vec {
+ check(msgs, 0, false).map(|(_, f)| f.into_iter().map(|f| f.kind).collect()).unwrap_or_default()
+ }
+
+ /// The real case: the file went into the chat, and the reply links it at sandbox:/… — the
+ /// link opens the attachment instead (nothing to show); with no such file it is marked.
+ #[test]
+ fn a_sandbox_link_to_a_file_in_the_chat_opens_it_one_to_nowhere_is_marked() {
+ let name = "人類助理工程規格-給CodeAgent.md";
+ let sent = step("c1", "send_file", &format!(r#"{{"path":"{name}"}}"#), ToolStatus::Done);
+ let reply = format!("規格寫好了。\n\n[下載:{name}](sandbox:/home/bot/bot-12/{name})");
+ let msgs = turn(vec![(sent.clone(), "已把檔案放進聊天(附件 a1b2c3)")], &reply, vec![name]);
+ let (at, flags) = check(&msgs, 0, false).unwrap();
+ assert_eq!(at, msgs.len() - 1);
+ assert_eq!(flags.iter().map(|f| f.kind).collect::>(), vec![Kind::FileLink]);
+ assert!(flags[0].why.contains("sandbox:/home/bot") && flags[0].why.contains(name), "{}", flags[0].why);
+ assert!(!flags[0].kind.shown() && !flags[0].kind.hard());
+ // No file of that name: marked, and a hard one.
+ let msgs = turn(vec![], "已傳好了 [下載](sandbox:/home/bot/x.md)", vec![]);
+ assert!(kinds(&msgs).contains(&Kind::DeadLink));
+ for target in ["file:///Users/me/x.pdf", "/home/bot/out/x.png", "~/報告.docx", "./out/a.csv", "C:\\Users\\me\\a.xlsx", "/mnt/data/%E5%A0%B1%E5%91%8A.md"] {
+ let msgs = turn(vec![], &format!("在這裡:[檔案]({target})"), vec![]);
+ assert_eq!(kinds(&msgs), vec![Kind::DeadLink], "{target}");
+ }
+ assert_eq!(dead_link("/mnt/data/%E5%A0%B1%E5%91%8A.md").as_deref(), Some("報告.md"));
+ assert_eq!(dead_link("").as_deref(), Some("a b.md"));
+ // Links that open: the web, a page, a mail; a link inside code isn't a link.
+ for ok in ["[來源](https://example.com/a.md)", "[頁面](page:3)", "[信](mailto:a@b.c)", "[網站](//cdn.example.com/x)", "`[x](/home/bot/x.md)`", "```\n[x](sandbox:/x.md)\n```"] {
+ assert!(kinds(&turn(vec![], ok, vec![])).is_empty(), "{ok}");
+ }
+ }
+
+ /// (a): 「已完成」「已傳」 after the step that would have done it failed or was refused.
+ #[test]
+ fn done_after_the_step_failed_is_marked() {
+ let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed);
+ let msgs = turn(vec![(failed.clone(), "找不到 a.md")], "已傳給你了。", vec![]);
+ let f = check(&msgs, 0, false).unwrap().1;
+ assert_eq!(f[0].kind, Kind::Undone);
+ assert!(f[0].why.contains("已傳") && f[0].why.contains("失敗了"), "{}", f[0].why);
+ let denied = step("c1", "publish_site", r#"{"path":"a.html"}"#, ToolStatus::Denied);
+ assert_eq!(kinds(&turn(vec![(denied, "使用者拒絕了這個操作")], "網站已發佈。", vec![])), vec![Kind::Undone]);
+ let edit = step("c1", "edit_file", r#"{"path":"a.md"}"#, ToolStatus::Failed);
+ assert_eq!(kinds(&turn(vec![(edit, "找不到要換掉的字")], "搞定!", vec![])), vec![Kind::Undone]);
+ // Tried again and it went: fine.
+ let again = step("c2", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Done);
+ assert!(kinds(&turn(vec![(failed.clone(), "找不到"), (again, "已放進聊天(附件 a1b2c3)")], "已傳給你了。", vec!["a.md"])).is_empty());
+ // A look at something after the work (a read that failed) isn't what 「完成」 rests on.
+ let wrote = step("c1", "edit_file", r#"{"path":"a.md"}"#, ToolStatus::Done);
+ let read = step("c2", "read_file", r#"{"path":"log.txt"}"#, ToolStatus::Failed);
+ assert!(kinds(&turn(vec![(wrote, "已修改"), (read, "找不到")], "已完成。", vec![])).is_empty());
+ // grep that found nothing (exit 1, nothing printed) didn't fail.
+ let grep = step("c1", "shell", r#"{"command":"grep -c ERROR log"}"#, ToolStatus::Failed);
+ assert!(kinds(&turn(vec![(grep, "結束代碼 1\n")], "檢查完成了,處理好了。", vec![])).is_empty());
+ let build = step("c1", "shell", r#"{"command":"cargo build"}"#, ToolStatus::Failed);
+ assert_eq!(kinds(&turn(vec![(build, "結束代碼 101\nerror[E0425]")], "做好了。", vec![])), vec![Kind::Undone]);
+ }
+
+ /// Not claims: not yet, a plan, a condition, a question, part of it, owning up — and the
+ /// person's own doing.
+ #[test]
+ fn words_that_arent_a_claim_are_left_alone() {
+ let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed);
+ for reply in [
+ "我還沒完成。",
+ "完成後我會通知你。",
+ "如果傳了,你會在上面看到。",
+ "已完成的部分是第一章,但第二章還沒。",
+ "傳好了之後跟你說。",
+ "要我現在傳給你嗎?",
+ "檔案傳好了嗎",
+ "做好了再給你看。",
+ "已完成大部分,不過最後一步失敗了。",
+ "傳檔失敗了,我換個方式。報告已完成。",
+ "你已上傳的檔案我看過了。",
+ "等你確認我就送出了",
+ "應該已經完成了,我再確認一次。",
+ "我把「已完成」的項目標成綠色。",
+ "I have not sent it yet.",
+ "Once it is done I will send it.",
+ ] {
+ assert!(kinds(&turn(vec![(failed.clone(), "找不到")], reply, vec![])).is_empty(), "{reply}");
+ }
+ // Nothing failed, nothing claimed about a file: nothing to say.
+ assert!(kinds(&turn(vec![], "好的,了解。", vec![])).is_empty());
+ // Said kindly is still a claim (「沒問題」 isn't a 「沒」).
+ assert_eq!(kinds(&turn(vec![(failed, "找不到")], "沒問題,已傳給你了。", vec![])), vec![Kind::Undone]);
+ // English claims are read too.
+ let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed);
+ assert_eq!(kinds(&turn(vec![(failed, "找不到")], "I've sent the report.", vec![])), vec![Kind::Undone]);
+ }
+
+ /// Said a file came with the reply, and the turn put none in the chat.
+ #[test]
+ fn a_file_said_sent_with_none_in_the_chat_is_marked() {
+ assert_eq!(kinds(&turn(vec![], "報告已傳給你,請查收。", vec![])), vec![Kind::NoFile]);
+ assert_eq!(kinds(&turn(vec![], "已附上 summary.pdf。", vec![])), vec![Kind::NoFile]);
+ // There is one: fine.
+ assert!(kinds(&turn(vec![], "報告已傳給你,請查收。", vec!["報告.md"])).is_empty());
+ // Sent somewhere else (a phone, mail), said so, or sent before this turn: not about this turn's chat.
+ let to_phone = step("c1", "send_to_device", r#"{"path":"a.pdf"}"#, ToolStatus::Done);
+ assert!(kinds(&turn(vec![(to_phone, "已傳到 iPhone")], "檔案已傳給你。", vec![])).is_empty());
+ assert!(kinds(&turn(vec![], "檔案已上傳到 Google Drive。", vec![])).is_empty());
+ assert!(kinds(&turn(vec![], "檔案剛剛已傳給你了。", vec![])).is_empty());
+ let mut earlier = vec![Message::user("傳報告"), Message { attachments: vec![Attachment { name: "a.pdf".into(), ..Default::default() }], ..Message::assistant("好了", "") }];
+ let start = earlier.len();
+ earlier.extend(turn(vec![], "a.pdf 已傳給你了。", vec![]));
+ assert!(check(&earlier, start, false).unwrap().1.is_empty());
+ // Not about a file: 「已完成」 alone needs a failed step, not a file.
+ assert!(kinds(&turn(vec![], "已完成,網站更新了。", vec![])).is_empty());
+ }
+
+ /// (c): a number the counts don't bear out — marked, never woken.
+ #[test]
+ fn a_count_the_steps_dont_bear_out_is_marked() {
+ let posted = step("c1", "post_to_x", r#"{"text":"早安"}"#, ToolStatus::Done);
+ let f = check(&turn(vec![(posted.clone(), "已發文")], "已發佈,共送出 2 則。", vec![]), 0, false).unwrap().1;
+ assert_eq!(f.iter().map(|f| f.kind).collect::>(), vec![Kind::Count]);
+ assert!(f[0].why.contains("2 則") && f[0].why.contains("1 則"), "{}", f[0].why);
+ assert!(!Kind::Count.hard() && Kind::Count.shown());
+ let again = step("c2", "post_to_x", r#"{"text":"午安"}"#, ToolStatus::Done);
+ assert!(kinds(&turn(vec![(posted.clone(), "已發文"), (again, "已發文")], "送出兩則了。", vec![])).is_empty());
+ // Nothing the counts can see (a connector's mail): no number is held against it.
+ assert!(kinds(&turn(vec![], "已寄出 3 則通知。", vec![])).is_empty());
+ // Files: said three, one came.
+ assert_eq!(kinds(&turn(vec![], "已傳 3 張圖給你。", vec!["a.png"])), vec![Kind::Count]);
+ assert!(kinds(&turn(vec![], "已傳 2 張圖給你。", vec!["a.png", "b.png"])).is_empty());
+ }
+
+ /// A group chat: only the member who answered — another's failed step isn't its.
+ #[test]
+ fn in_a_group_only_the_answering_members_steps_count() {
+ let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed);
+ let mut msgs = vec![Message::user("你們誰傳一下"), Message { author: 7, tool_calls: vec![failed], ..Message::assistant("", "") }, Message::tool_result("c1", "send_file", "找不到"), Message { author: 7, ..Message::assistant("我傳不了。", "") }];
+ let sent = step("c2", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Done);
+ msgs.push(Message { author: 8, tool_calls: vec![sent], ..Message::assistant("", "") });
+ msgs.push(Message::tool_result("c2", "send_file", "已放進聊天(附件 a1b2c3)"));
+ msgs.push(Message { author: 8, attachments: vec![Attachment { name: "a.md".into(), ..Default::default() }], ..Message::assistant("已傳給你了。", "") });
+ let (at, flags) = check(&msgs, 0, true).unwrap();
+ assert!(at == msgs.len() - 1 && flags.is_empty(), "{flags:?}");
+ }
+
+ /// A 支線's report or a colleague's (put in the chat as the bot's after its reply) isn't the
+ /// reply: the bot's own last words are.
+ #[test]
+ fn a_report_put_in_after_the_reply_isnt_the_reply() {
+ let failed = step("c1", "send_file", r#"{"path":"a.md"}"#, ToolStatus::Failed);
+ let mut msgs = turn(vec![(failed, "找不到")], "傳不了,找不到 a.md。", vec![]);
+ msgs.push(Message { branch: 3, ..Message::assistant("支線做完了,已傳給你了 [結果](sandbox:/home/bot/r.md)", "") });
+ msgs.push(Message { author: 9, ..Message::assistant("【同事】已完成。", "") });
+ let (at, flags) = check(&msgs, 0, false).unwrap();
+ assert_eq!(at, msgs.len() - 3);
+ assert!(flags.is_empty(), "{flags:?}");
+ }
+
+ #[test]
+ fn the_wake_says_only_fixed_words() {
+ let w = wake_text(&[Kind::DeadLink, Kind::Undone, Kind::DeadLink]);
+ assert!(w.starts_with(WAKE_TAG) && w.contains("sandbox:") && w.contains("失敗或被擋下") && w.contains("不是使用者說的話"), "{w}");
+ assert_eq!(w.matches("同名的附件").count(), 1);
+ let line = history_line(&[Flag { kind: Kind::FileLink, why: "連結「x」…".into() }]);
+ assert!(line.contains("不是你寫的") && line.contains("連結「x」"), "{line}");
+ }
+}
diff --git a/src/featuremap.rs b/src/featuremap.rs
index a5b62ab..0df2f9f 100644
--- a/src/featuremap.rs
+++ b/src/featuremap.rs
@@ -53,6 +53,7 @@ pub const AREAS: &[Area] = &[
area!("box", "Bot 的電腦"),
area!("files", "檔案與指令"),
area!("deliver", "交出結果:傳檔、打開、發佈網站"),
+ area!("claims", "完成宣稱檢查"),
area!("browser", "瀏覽器"),
area!("screen", "螢幕操作"),
area!("vault", "保險庫"),
diff --git a/src/i18n_table.rs b/src/i18n_table.rs
index 84cae88..10b639b 100644
--- a/src/i18n_table.rs
+++ b/src/i18n_table.rs
@@ -770,4 +770,8 @@ pub const ROWS: &[(&str, &str, &str)] = &[
("名稱不能空白,沒有改。", "A name can't be empty; it wasn't changed.", "名前は空にできません。変更していません。"),
("已經有叫「{n}」的連接器,名稱沒有改。", "There is already a connector called “{n}”; the name wasn't changed.", "「{n}」というコネクタがすでにあります。名前は変更していません。"),
("常用的連接器,按「加入」就能用。需要金鑰的會打開「新增連接器」並填好,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。下面的「公用市集」搜尋官方 MCP Registry 裡用網址連的連接器。", "Common connectors, ready with Add. One that needs a key opens Add connector filled in: add the key and press Add. Local ones need Node.js (npx) or uv (uvx). The public market below searches the official MCP Registry for connectors reached by address.", "よく使うコネクタは「追加」ですぐ使えます。キーが必要なものは「コネクタを追加」を入力済みで開きます。キーを入れて「追加」を押してください。ローカルのものは Node.js(npx)か uv(uvx)が必要です。下の「公開マーケット」は公式 MCP Registry からアドレスで接続するコネクタを検索します。"),
+ ("未驗證", "Unverified", "未検証"),
+ ("AnyBot 核對這一輪實際做了什麼,跟這則回覆對不上", "AnyBot checked what this turn really did, and it doesn't match this reply", "AnyBot がこのターンで実際に行われたことを確認したところ、この返信と一致しません"),
+ ("回覆沒對上", "Reply didn't match", "返信が一致しません"),
+ ("這個連結指到 Bot 電腦上的位置,這裡打不開;聊天裡也沒有這個檔案。請 Bot 用 send_file 傳過來。", "This link points to a place on the bot's computer and can't open here; the chat has no such file either. Ask the bot to send it with send_file.", "このリンクは Bot のコンピュータ上の場所を指しているため、ここでは開けません。チャットにもこのファイルはありません。Bot に send_file で送ってもらってください。"),
];
diff --git a/src/main.rs b/src/main.rs
index c8f40c1..8fa498b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -73,6 +73,7 @@ mod tools;
mod triggers;
mod embed;
mod evidence;
+mod claims;
mod tasks;
mod featuremap;
mod garden;
diff --git a/src/model.rs b/src/model.rs
index d83bc06..0c3371c 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -137,6 +137,11 @@ pub struct Message {
/// what it found (its report, which the main line reads too).
#[serde(default, skip_serializing_if = "is_zero")]
pub branch: u64,
+ /// 完成宣稱關卡 (claims.rs): what AnyBot found when it held this reply up against what its turn
+ /// really did — a claim the steps don't bear out, a link only the bot's computer can open.
+ /// Set by AnyBot at the turn's end, never by the model; shown as 「未驗證」 under the reply.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub check: Vec,
/// What the model reads after the person's words (送出時間, the memories): made by
/// app::group_history from the fields above, never saved.
#[serde(skip)]
@@ -229,10 +234,11 @@ fn chat_mark(b: &Bot) -> u64 {
for r in &m.reactions {
r.hash(&mut h);
}
- // (交付確認: a device's word on a file is kept too.)
+ // (交付確認: a device's word on a file is kept too; and 完成宣稱關卡's on a reply.)
for a in &m.attachments {
a.seen.len().hash(&mut h);
}
+ m.check.len().hash(&mut h);
};
b.messages.iter().for_each(&mut shape);
for (title, msgs) in &b.threads {
diff --git a/src/pages.rs b/src/pages.rs
index 73e2d2b..278927d 100644
--- a/src/pages.rs
+++ b/src/pages.rs
@@ -77,17 +77,17 @@ fn one() -> u32 {
pub fn specs() -> Vec {
vec. With an id (or the same title) it replaces that page's content and keeps the old version. Write Markdown: headings, short paragraphs, lists, tables, links to sources, Mermaid charts (```mermaid: pie, xychart-beta bar/line, timeline, gantt, flowchart), and these page blocks:\n```stats\n狀態 | 審查中 | 第 1 步\n預計開放 | 2027 Q2 | 媒體推估\n```\n```steps\n[x] 道路測試計畫審查 | 7/9 月開過兩次會\n[>] 道路測試 | 等交通部核定\n[ ] 正式開放\n```\n```chart\nbar 標題(bar | line | pie 換圖型)\n1月 | 120\n2月 | 320\n```\n```details 指令與原始數據\n(預設收起的 Markdown:證據、長清單、指令)\n```\n多系列:首行 `| 1月 | 2月`(第一格留空),每列 `名稱 | 120 | 320`。圖表用原生繪製(可縮放、hover 看數值,下方自動附數據表),優於 ```mermaid 的圖片。排版由渲染器接手:長條圖自動由大到小排序(月份/年份等自有順序的標籤不排);單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名——你只要把圖標題寫成結論。\n> [!NOTE] / [!TIP] / [!WARNING] / [!IMPORTANT] call-outs.\n\n寫法(Anthropic 的報告寫法:讀者先掃一眼,需要才往下讀):\n• 選 kind(data 數據分析 / compare 比較評測 / decision 決策備忘 / howto 教學步驟 / timeline 時間線 / prose 純敘述 / notes 筆記),第一屏跟著它:data → 一句結論+kpis 三個真數字+主圖表;compare → 一句取捨+verdict+對比表;decision → verdict 先講+三個理由+風險;howto → 適合誰+steps;timeline → mermaid timeline;prose/notes → 直接內文,不硬湊 KPI 卡。kpis 只放算得出的真數字(附 delta 如 +12%),verdict 只在有明確結論時寫。\n• 每一節的標題就是結論(「240 環境是測試場」,不是「240 環境的現實」),下面第一句補一個理由,再最多三點清單。\n• 數字放 ```stats 或表格,不塞在句子和括號裡;有趨勢或比較就出 ```chart,圖標題寫結論並帶數字,軸標籤帶單位。\n• 粗體一節最多一處(或不用);不用「→」帶結論、不用分隔線(---)、標題不編號(一、二、1.)——標題本身就是分段。\n• 待辦寫成 ```steps 勾選清單;指令放程式碼區塊,不放進表格。\n• 證據、長清單、指令、原始數據放進 ```details 標題(預設收起);第一屏只留結論、數字和下一步。\n• 句子短、主動語氣、用讀者的話(說「通知」不說「webhook 設定」);不寫「值得注意的是」這類套話。\n• 來源放最後,帶連結與日期。更新時把整頁維持成現況(不是日誌),並在 `note` 寫出改了什麼。\n• 存檔時會自動檢查寫法:被退回就照列出的地方改,用同樣的標題再送一次。",
+ json!({"name": "write_page", "description": "Make or update a page: a lasting, nicely laid-out document the person can open from the chat and that you keep up to date — a tracker (e.g. 「台灣 Tesla FSD 追蹤」), a report, a comparison, a plan, research notes. Use it whenever the person asks you to track, follow, summarise or compare something they will come back to; then link it in your reply as [標題](page:ID). With an id (or the same title) it replaces that page's content and keeps the old version; with an id and no content, only the other fields you send (title, summary, note, kind, kpis, verdict) change. Write Markdown: headings, short paragraphs, lists, tables, links to sources, Mermaid charts (```mermaid: pie, xychart-beta bar/line, timeline, gantt, flowchart), and these page blocks:\n```stats\n狀態 | 審查中 | 第 1 步\n預計開放 | 2027 Q2 | 媒體推估\n```\n```steps\n[x] 道路測試計畫審查 | 7/9 月開過兩次會\n[>] 道路測試 | 等交通部核定\n[ ] 正式開放\n```\n```chart\nbar 標題(bar | line | pie 換圖型)\n1月 | 120\n2月 | 320\n```\n```details 指令與原始數據\n(預設收起的 Markdown:證據、長清單、指令)\n```\n多系列:首行 `| 1月 | 2月`(第一格留空),每列 `名稱 | 120 | 320`。圖表用原生繪製(可縮放、hover 看數值,下方自動附數據表),優於 ```mermaid 的圖片。排版由渲染器接手:長條圖自動由大到小排序(月份/年份等自有順序的標籤不排);單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名——你只要把圖標題寫成結論。\n> [!NOTE] / [!TIP] / [!WARNING] / [!IMPORTANT] call-outs.\n\n寫法(Anthropic 的報告寫法:讀者先掃一眼,需要才往下讀):\n• 選 kind(data 數據分析 / compare 比較評測 / decision 決策備忘 / howto 教學步驟 / timeline 時間線 / prose 純敘述 / notes 筆記),第一屏跟著它:data → 一句結論+kpis 三個真數字+主圖表;compare → 一句取捨+verdict+對比表;decision → verdict 先講+三個理由+風險;howto → 適合誰+steps;timeline → mermaid timeline;prose/notes → 直接內文,不硬湊 KPI 卡。kpis 只放算得出的真數字(附 delta 如 +12%),verdict 只在有明確結論時寫。\n• 每一節的標題就是結論(「240 環境是測試場」,不是「240 環境的現實」),下面第一句補一個理由,再最多三點清單。\n• 數字放 ```stats 或表格,不塞在句子和括號裡;有趨勢或比較就出 ```chart,圖標題寫結論並帶數字,軸標籤帶單位。\n• 粗體一節最多一處(或不用);不用「→」帶結論、不用分隔線(---)、標題不編號(一、二、1.)——標題本身就是分段。\n• 待辦寫成 ```steps 勾選清單;指令放程式碼區塊,不放進表格。\n• 證據、長清單、指令、原始數據放進 ```details 標題(預設收起);第一屏只留結論、數字和下一步。\n• 句子短、主動語氣、用讀者的話(說「通知」不說「webhook 設定」);不寫「值得注意的是」這類套話。\n• 來源放最後,帶連結與日期。更新時把整頁維持成現況(不是日誌),並在 `note` 寫出改了什麼。\n• 存檔時會自動檢查寫法:被退回就照列出的地方改,用同樣的 id 或標題、帶整頁 content 再送一次(第二次一定存)。",
"parameters": {"type": "object", "properties": {
"title": {"type": "string", "description": "Short title, e.g. 台灣 Tesla FSD 追蹤"},
- "content": {"type": "string", "description": "The whole page in Markdown (without the title)"},
+ "content": {"type": "string", "description": "The whole page in Markdown (without the title). Leave it out only to change the other fields of an existing page (with its id)."},
"summary": {"type": "string", "description": "One line for the card: the current state in a few words"},
"note": {"type": "string", "description": "When updating: what changed, in one short sentence"},
"kind": {"type": "string", "enum": ["data", "compare", "decision", "howto", "timeline", "prose", "notes"], "description": "What kind of document this is; it decides the first screen. Omit for a plain page."},
"kpis": {"type": "array", "description": "Only for data pages: the 2-4 real numbers a reader must see first (never invented, never placeholders).", "items": {"type": "object", "properties": {"label": {"type": "string"}, "value": {"type": "string"}, "delta": {"type": "string", "description": "Change, e.g. +12% / -3 天 (empty when none)"}}, "required": ["label", "value"]}},
"verdict": {"type": "string", "description": "One-line conclusion, for decision/compare pages (rendered as a card before the text)"},
"id": {"type": "integer", "description": "The page to update (from list_pages or an earlier write_page)"}},
- "required": ["title", "content"]}}),
+ "required": ["title"]}}),
json!({"name": "read_page", "description": "Read a page (its Markdown): one of yours before updating it, or another bot's to use what it already found (theirs you can read, not change).", "parameters": {"type": "object", "properties": {"id": {"type": "integer"}, "title": {"type": "string"}}}}),
json!({"name": "list_pages", "description": "List the pages you made, then the other bots' pages you can read (id, title, whose, last update). Look here before researching something a colleague may already track.", "parameters": {"type": "object", "properties": {}}}),
]
@@ -144,28 +144,37 @@ pub struct Written {
pub text: String,
}
-/// write_page: make a page, or replace one (by id, or the same title from this bot).
+/// Which page a write_page call is about, for the 寫法檢查's 「the second try is saved」: its id
+/// (given, or this bot's page of that title), else its title (a page not made yet). A try that
+/// names the page by id and one by its title are the same page.
+pub fn write_key(pages: &[Page], bot: u64, args: &Value) -> String {
+ let title = args["title"].as_str().unwrap_or("");
+ match find(pages, bot, args["id"].as_u64(), title) {
+ Some(p) => format!("#{}", p.id),
+ None => format!("「{}」", title.chars().filter(|c| !c.is_whitespace()).collect::().to_lowercase()),
+ }
+}
+
+/// write_page: make a page, or replace one (by id, or the same title from this bot). With no
+/// content, a page of this bot's (by id or title) has only the other fields sent changed — a bot
+/// sends the content, then the kind, summary, verdict on their own, and that used to come back
+/// 「頁面內容是空的」.
pub fn write(pages: &mut Vec, next_id: &mut u64, bot: u64, args: &Value, now: i64) -> Result {
let title: String = args["title"].as_str().unwrap_or("").trim().chars().take(MAX_TITLE).collect();
let body = args["content"].as_str().unwrap_or("").trim().to_string();
let summary: String = args["summary"].as_str().unwrap_or("").trim().chars().take(200).collect();
let note: String = args["note"].as_str().unwrap_or("").trim().chars().take(300).collect();
- if title.is_empty() {
- return Err("頁面要有標題".into());
- }
if body.is_empty() {
- return Err("頁面內容是空的".into());
+ return update_fields(pages, bot, args, now);
+ }
+ if title.is_empty() && args["id"].as_u64().is_none() {
+ return Err("頁面要有標題".into());
}
if body.len() > MAX_BODY {
return Err(format!("頁面太長了(最多 {} 字)。請精簡,或拆成幾頁。", MAX_BODY));
}
let id = args["id"].as_u64();
- // 結構由內容決定:kind 決定第一屏怎麼排,kpis/verdict 有真資料才填、有才渲染。
- const KINDS: [&str; 7] = ["data", "compare", "decision", "howto", "timeline", "prose", "notes"];
- let kind: String = args["kind"].as_str().unwrap_or("").trim().to_lowercase().chars().take(12).collect();
- let kind = if KINDS.contains(&kind.as_str()) { kind } else { String::new() };
- let kpis: Vec = args["kpis"].as_array().map(|a| a.iter().filter_map(|k| Some(Kpi { label: k["label"].as_str()?.trim().chars().take(40).collect(), value: k["value"].as_str()?.trim().chars().take(40).collect(), delta: k["delta"].as_str().unwrap_or("").trim().chars().take(20).collect() })).take(4).collect()).unwrap_or_default();
- let verdict: String = args["verdict"].as_str().unwrap_or("").trim().chars().take(300).collect();
+ let (kind, kpis, verdict) = shape_of(args);
let existing = find(pages, bot, id, &title).map(|p| p.id);
if id.is_some() && existing.is_none() {
return Err(format!("找不到頁面 #{}。用 list_pages 看有哪些頁面,或不帶 id 建立新的。", id.unwrap_or(0)));
@@ -176,6 +185,8 @@ pub fn write(pages: &mut Vec, next_id: &mut u64, bot: u64, args: &Value, n
if p.bot != bot {
return Err("這是別的 Bot 的頁面,不能改".into());
}
+ // (Updated by id with no title: it keeps its title.)
+ let title = if title.is_empty() { p.title.clone() } else { title };
if p.body == body && p.title == title && (summary.is_empty() || p.summary == summary) && (kind.is_empty() || p.kind == kind) && (kpis.is_empty() || p.kpis == kpis) && (verdict.is_empty() || p.verdict == verdict) {
return Ok(Written { id: pid, text: format!("頁面「{}」內容沒有變化,沒有更新。連結:[{}](page:{})", p.title, p.title, pid) });
}
@@ -213,6 +224,69 @@ pub fn write(pages: &mut Vec, next_id: &mut u64, bot: u64, args: &Value, n
}
}
+/// The page's shape as sent: its kind, KPI numbers and verdict (empty: not sent).
+fn shape_of(args: &Value) -> (String, Vec, String) {
+ // 結構由內容決定:kind 決定第一屏怎麼排,kpis/verdict 有真資料才填、有才渲染。
+ const KINDS: [&str; 7] = ["data", "compare", "decision", "howto", "timeline", "prose", "notes"];
+ let kind: String = args["kind"].as_str().unwrap_or("").trim().to_lowercase().chars().take(12).collect();
+ let kind = if KINDS.contains(&kind.as_str()) { kind } else { String::new() };
+ let kpis: Vec = args["kpis"].as_array().map(|a| a.iter().filter_map(|k| Some(Kpi { label: k["label"].as_str()?.trim().chars().take(40).collect(), value: k["value"].as_str()?.trim().chars().take(40).collect(), delta: k["delta"].as_str().unwrap_or("").trim().chars().take(20).collect() })).take(4).collect()).unwrap_or_default();
+ let verdict: String = args["verdict"].as_str().unwrap_or("").trim().chars().take(300).collect();
+ (kind, kpis, verdict)
+}
+
+/// write_page with no content: the fields sent (title, summary, note, kind, kpis, verdict) of a
+/// page of this bot's change; its content and versions stay as they are.
+fn update_fields(pages: &mut [Page], bot: u64, args: &Value, now: i64) -> Result {
+ let title: String = args["title"].as_str().unwrap_or("").trim().chars().take(MAX_TITLE).collect();
+ let summary: String = args["summary"].as_str().unwrap_or("").trim().chars().take(200).collect();
+ let note: String = args["note"].as_str().unwrap_or("").trim().chars().take(300).collect();
+ let (kind, kpis, verdict) = shape_of(args);
+ let id = args["id"].as_u64();
+ let Some(pid) = find(pages, bot, id, &title).map(|p| p.id) else {
+ return Err(match id {
+ Some(i) => format!("找不到頁面 #{i}。用 list_pages 看有哪些頁面,或不帶 id 建立新的。"),
+ None if title.is_empty() => "頁面要有標題和內容".into(),
+ None => "頁面內容是空的".into(),
+ });
+ };
+ let p = pages.iter_mut().find(|p| p.id == pid).unwrap();
+ let mut changed: Vec<&str> = vec![];
+ if !title.is_empty() && title != p.title {
+ p.title = title;
+ changed.push("標題");
+ }
+ if !summary.is_empty() && summary != p.summary {
+ p.summary = summary;
+ changed.push("摘要");
+ }
+ if !note.is_empty() && note != p.note {
+ p.note = note;
+ changed.push("更新說明");
+ }
+ if !kind.is_empty() && kind != p.kind {
+ p.kind = kind;
+ changed.push("種類");
+ }
+ if !kpis.is_empty() && kpis != p.kpis {
+ p.kpis = kpis;
+ changed.push("數字卡");
+ }
+ if !verdict.is_empty() && verdict != p.verdict {
+ p.verdict = verdict;
+ changed.push("結論");
+ }
+ if changed.is_empty() {
+ // (Nothing at all sent to change: said as the mistake it is.)
+ if !["summary", "note", "kind", "kpis", "verdict"].iter().any(|k| !args[*k].is_null()) && args["title"].as_str().is_none_or(|t| t.trim().is_empty()) {
+ return Err(format!("頁面內容是空的,也沒有要改的欄位:要換內容就帶 content(整頁),只改其他的就帶 title、summary、note、kind、kpis 或 verdict。頁面「{}」沒有動。", p.title));
+ }
+ return Ok(Written { id: pid, text: format!("頁面「{}」沒有變化,沒有更新。連結:[{}](page:{pid})", p.title, p.title) });
+ }
+ p.updated = now;
+ Ok(Written { id: pid, text: format!("已更新頁面「{}」的{}(內容沒動,還是第 {} 版)。在回答裡用 [{}](page:{pid}) 連到它。", p.title, changed.join("、"), p.revision, p.title) })
+}
+
/// read_page: its own first; then another bot's (同事的頁面, to read — what a colleague already
/// tracks needn't be looked up again). `name` gives a bot's name.
pub fn read(pages: &[Page], bot: u64, args: &Value, name: impl Fn(u64) -> String) -> Result {
diff --git a/src/remote.rs b/src/remote.rs
index 74d7c18..57e69eb 100644
--- a/src/remote.rs
+++ b/src/remote.rs
@@ -458,7 +458,7 @@ pub fn message_json(m: &crate::model::Message, names: &HashMap, pag
}
})
.collect();
- Some(json!({
+ let mut v = json!({
"role": match m.role { Role::User => "user", _ => "assistant" },
"text": m.text,
"via": m.via,
@@ -473,7 +473,13 @@ pub fn message_json(m: &crate::model::Message, names: &HashMap, pag
"at": m.at,
"tools": calls,
"memories": m.memories,
- }))
+ });
+ // 完成宣稱關卡: what makes the reply 「未驗證」 (only on a reply that has one).
+ let check: Vec = m.check.iter().filter(|f| f.kind.shown()).map(|f| json!({"kind": f.kind, "why": f.why})).collect();
+ if !check.is_empty() {
+ v["check"] = json!(check);
+ }
+ Some(v)
}
/// A file in a message, for the phone. One the bot handed over (`by_bot`) also carries its id
@@ -3807,6 +3813,21 @@ mod tests {
assert!(!LOOSEN_REFUSED.contains("加密") && LOOSEN_REFUSED.contains("只能收緊、不能放寬"));
}
+ /// 完成宣稱關卡 on the phone: a reply's 「未驗證」 and why; a link to a file in the chat (opened
+ /// there instead) isn't shown; a reply with nothing found has no `check` at all.
+ #[test]
+ fn the_phone_gets_what_made_a_reply_unverified() {
+ use crate::claims::{Flag, Kind};
+ let names = HashMap::new();
+ let plain = crate::model::Message::assistant("好了", "");
+ assert!(message_json(&plain, &names, &[], &[]).unwrap().get("check").is_none());
+ let m = crate::model::Message { check: vec![Flag { kind: Kind::DeadLink, why: "連結「下載」打不開".into() }, Flag { kind: Kind::FileLink, why: "改開附件".into() }], ..plain.clone() };
+ let v = message_json(&m, &names, &[], &[]).unwrap();
+ assert_eq!(v["check"], json!([{"kind": "dead_link", "why": "連結「下載」打不開"}]));
+ let only_file = crate::model::Message { check: vec![Flag { kind: Kind::FileLink, why: "改開附件".into() }], ..plain };
+ assert!(message_json(&only_file, &names, &[], &[]).unwrap().get("check").is_none());
+ }
+
/// 交付確認 from a phone: a teammate may tell it too; the page's words never reach the bot as
/// they are (the device from a short list, the reason a code); the bot's file carries its id
/// and how it stands, the person's own file nothing new.