From d23ca7628d023c3bc57d8e65410be1b83f5d86e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Tue, 17 Nov 2026 11:18:12 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20clippy=20=E5=85=A8=E9=83=A8=E6=B8=85?= =?UTF-8?q?=E4=B9=BE=E6=B7=A8=EF=BC=8CCI=20=E6=9C=89=E6=96=B0=E8=AD=A6?= =?UTF-8?q?=E5=91=8A=E5=B0=B1=E5=A4=B1=E6=95=97=EF=BC=9Bmake=20lint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 工程基礎計畫 E6。33 個警告改掉,行為不變(測試全過): - 順序一樣、寫法更直接:sort_by(b.cmp(a)) → sort_by_key(Reverse)(三處,都是穩定排序);chunks_exact(4) → as_chunks::<4>()(拿掉一個 unwrap);用 checked_div 取代先判斷 total > 0;兩個一樣的分支合成一個條件;計數迴圈用 enumerate;單一運算式的立即呼叫閉包改成區塊;回傳 () 的函式不再包在 Ok() 裡。 - 型別取名:VoicesAnswer、Vocab、Group。system_prompt 的 11 個參數留著(每個是指示的不同部分),標 allow 並寫理由。 - 小的:多餘的 clone、format!、vec!、into、借用;3_600_000 的分組;文件註解的縮排和空行;新檔案明說不截斷。 - .gitea/workflows/ci.yml:clippy 改成 `--all-targets -- -D warnings`(原本只報告)。make lint 跑一樣的檢查。 - 不加 rust-toolchain.toml:AnyBot 是使用者自己建的,釘版本會逼每個人和 make update-server 多下載一套 Rust;CI 映像本來就釘 1.98.1。 已驗證:cargo test 560 全過;cargo clippy --bin anybot --all-targets -- -D warnings 在這台 Mac 過。 未驗證:只在 Linux 編譯的程式(x11.rs、wl.rs、portal.rs…)的 clippy:這台 Mac 看不到,第一次 CI 跑會檢查,若有警告會擋下來。 Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 10 ++++++---- Makefile | 5 +++++ docs/plan-2026-11-engineering.md | 5 +++-- src/agent.rs | 4 ++-- src/app.rs | 16 ++++++++-------- src/app/drops_ui.rs | 4 ++-- src/app/layout_audit.rs | 2 +- src/app/voice_ui.rs | 5 ++++- src/browser.rs | 8 ++++---- src/drops.rs | 5 ++++- src/embed.rs | 8 ++++---- src/find.rs | 2 +- src/m2v.rs | 7 +++++-- src/mcp.rs | 9 ++++----- src/memory.rs | 16 +++++++--------- src/memstore.rs | 11 ++++++----- src/store.rs | 4 ++-- 17 files changed, 68 insertions(+), 53 deletions(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 871a2d7..fa8307a 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -1,5 +1,5 @@ -# Every push and pull request: build, test, clippy (report only — the tree is not rustfmt' -# clean, so `cargo fmt --check` would need its own one-time reformatting change first). Release builds are release.yml's job. +# Every push and pull request: build, test, clippy with no warnings allowed (the tree is not +# rustfmt-clean, so `cargo fmt --check` would need its own one-time reformatting change first). Release builds are release.yml's job. # # Runners (see deploy/ci/README.md): # anybot-linux a Linux computer with Docker; jobs run in anybot-builder:22.04 @@ -31,8 +31,10 @@ jobs: run: | cargo test --bin anybot -- --skip live > "${RUNNER_TEMP:-/tmp}/test.log" 2>&1 || { tail -n 80 "${RUNNER_TEMP:-/tmp}/test.log"; exit 1; } tail -n 5 "${RUNNER_TEMP:-/tmp}/test.log" - - name: Clippy (report only) - run: cargo clippy --bin anybot 2>&1 | tail -30 + - name: Clippy (no warnings) + # The tree is clippy-clean (engineering plan E6): a new warning fails the build. Linux-only + # code (x11.rs, wl.rs, portal.rs…) is checked here first — it can't be on a Mac. + run: cargo clippy --bin anybot --all-targets -- -D warnings - name: Relay build and test run: cd relay && cargo test diff --git a/Makefile b/Makefile index 6dea974..f71e307 100644 --- a/Makefile +++ b/Makefile @@ -51,6 +51,7 @@ help: @echo " make doctor 檢查這台缺什麼" @echo " make test 跑測試" @echo " make lint-sh 檢查 shell 腳本(語法、中文標點黏變數)" + @echo " make lint 跟 CI 一樣的 clippy 檢查(有警告就失敗)" @echo "" @echo " make serve 不開視窗執行(伺服器、一直開著的電腦)" @echo " make setup 把這台接到你的 AnyBot(終端機裡的引導畫面)" @@ -94,6 +95,10 @@ test: check-rust lint-sh: @sh deploy/ci/lint-sh.sh +# The same clippy check CI runs: no warnings allowed (clippy.toml has AnyBot's own rules). +lint: check-rust + $(CARGO) clippy --bin anybot --all-targets -- -D warnings + deps: sh ./install.sh deps diff --git a/docs/plan-2026-11-engineering.md b/docs/plan-2026-11-engineering.md index a4e645e..cf47d0f 100644 --- a/docs/plan-2026-11-engineering.md +++ b/docs/plan-2026-11-engineering.md @@ -33,8 +33,9 @@ - 做法:`net::agent(timeout)` 統一建 `ureq` 用戶端(信任的憑證、逾時、User-Agent);`clippy.toml` 用 `disallowed-methods` 擋其他地方自己建。連接器的伺服器和 shell 指令開在自己的 process group,停掉時整群一起停(npx/uvx 帶起來的子行程不再留著)。`mcp::call` 收停止訊號(按停止不用等 120 秒)。 - 做完:`cargo clippy` 對新的違規報錯;停掉連接器後 `pgrep` 找不到它的子行程;按停止一秒內連接器呼叫就結束。 -### E6. clippy 全清、CI 擋新的警告、釘住工具鏈 ⬜ -- 做法:清掉現有 clippy 警告;`.gitea/workflows/ci.yml` 的 clippy 改成 `-D warnings`;加 `rust-toolchain.toml`。 +### E6. clippy 全清、CI 擋新的警告 ✅ +- 做法:清掉現有 clippy 警告;`.gitea/workflows/ci.yml` 的 clippy 改成 `-D warnings`;`make lint` 跑同一個檢查。 +- 不加 `rust-toolchain.toml`:AnyBot 是使用者自己從原始碼建的,釘住版本會逼每個人(和 `make update-server`)多下載一套 Rust;CI 的映像已經釘 1.98.1,Cargo.toml 的 rust-version 管最低版本。 - 做完:`cargo clippy --all-targets -- -D warnings` 過。 ### E7. 共用的假模型測試工具 ⬜ diff --git a/src/agent.rs b/src/agent.rs index dbf572c..4c82a62 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -4304,9 +4304,9 @@ mod tests { let model = std::env::var("ANYBOT_LIVE_MODEL").unwrap_or_else(|_| "husky".into()); let own = crate::model::BOT_COMPUTER_NAME.to_string(); let _ = std::fs::remove_dir_all("/tmp/anybot-live"); - let mut specs = tools::specs_for(&[own.clone()], &own); + let mut specs = tools::specs_for(std::slice::from_ref(&own), &own); if crate::botbrowser::available() { - specs.extend(crate::web::specs_for(&[own.clone()], &own)); + specs.extend(crate::web::specs_for(std::slice::from_ref(&own), &own)); } let job = Job { req: ChatRequest { diff --git a/src/app.rs b/src/app.rs index 3896ab7..98f237f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -382,10 +382,8 @@ impl App { // ANYBOT_SHOT_PINS=n: the grid at the top shows n bots (the main one and n-1 pinned). if let Some(n) = std::env::var("ANYBOT_SHOT_PINS").ok().and_then(|v| v.parse::().ok()) { let primary = state.primary_bot; - let mut kept = 1; - for b in state.bots.iter_mut().filter(|b| b.pinned && b.id != primary) { - b.pinned = kept < n; - kept += 1; + for (i, b) in state.bots.iter_mut().filter(|b| b.pinned && b.id != primary).enumerate() { + b.pinned = i + 1 < n; } } state.skills = crate::skills::BUILTIN_SKILLS @@ -891,8 +889,8 @@ impl App { j(serde_json::json!({"id": "1", "name": "第三季報表.xlsx", "bytes": 48_211_000, "from": "MacBook Pro", "to": "m", "to_name": "Mac mini", "state": "sending", "sent": 30_100_000, "at": now})), j(serde_json::json!({"id": "2", "name": "IMG_2041.heic", "bytes": 3_420_000, "from": "手機", "to": "x", "to_name": "MacBook Pro", "state": "done", "at": now - 9 * 60_000})), j(serde_json::json!({"id": "3", "name": "https://thsrc.com.tw/booking/…", "bytes": 60, "text": "https://thsrc.com.tw/booking/abc", "from": "MacBook Pro", "to": "phone", "to_name": "手機", "state": "ready", "at": now - 40 * 60_000})), - j(serde_json::json!({"id": "4", "name": "備份-2026-11.zip", "bytes": 812_000_000, "from": "MacBook Pro", "to": "l", "to_name": "客廳 Linux", "state": "waiting", "note": "目前離線", "at": now - 3 * 3600_000})), - j(serde_json::json!({"id": "5", "name": "合約草稿.pdf", "bytes": 1_250_000, "from": "研究助理", "to": "m", "to_name": "Mac mini", "state": "failed", "note": "那台電腦的磁碟滿了", "at": now - 26 * 3600_000})), + j(serde_json::json!({"id": "4", "name": "備份-2026-11.zip", "bytes": 812_000_000, "from": "MacBook Pro", "to": "l", "to_name": "客廳 Linux", "state": "waiting", "note": "目前離線", "at": now - 3 * 3_600_000})), + j(serde_json::json!({"id": "5", "name": "合約草稿.pdf", "bytes": 1_250_000, "from": "研究助理", "to": "m", "to_name": "Mac mini", "state": "failed", "note": "那台電腦的磁碟滿了", "at": now - 26 * 3_600_000})), ], "x", "m", @@ -3109,7 +3107,7 @@ impl App { self.settle(id, TurnOutcome::Error); if let Some(m) = self.state.bot_mut(id).and_then(|b| b.messages.last_mut()).filter(|m| m.role == Role::Assistant) { if m.text.is_empty() { - m.text = msg.into(); + m.text = msg; } else { m.text.push_str(&format!("\n\n{msg}")); } @@ -6824,6 +6822,8 @@ fn unattended_what(msgs: &[Message]) -> &'static str { } } +// (Eleven inputs, each a different part of the instructions; a struct of them would only rename them.) +#[allow(clippy::too_many_arguments)] fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_computer: &str, roles: &tools::Roles, missing: Option<&str>, lines: &[String], mac_apps: bool, mcp: bool, pinned: &[String], about_you: &[String]) -> String { use crate::profile::has; // 能力: the rules for what this bot can do only (profile.rs); the rest isn't its business. @@ -7508,7 +7508,7 @@ mod tests { let h2 = group_history(&msgs, None, 0, &st); assert_eq!(sys1, sys2, "the instructions are the same from turn to turn"); assert!(!sys1.contains("現在是") && sys1.contains("- 咖啡不加糖") && sys1.contains("search_memory")); - let view = |h: &[Message]| h.iter().map(|m| (m.role.clone(), m.text.clone(), m.context.clone())).collect::>(); + let view = |h: &[Message]| h.iter().map(|m| (m.role, m.text.clone(), m.context.clone())).collect::>(); assert_eq!(view(&h2[..h1.len()]), view(&h1), "the first turn is the beginning of the second, word for word"); assert_eq!(h1[0].context, "〔送出時間:2025-11-11(週二)10:00〕\n〔相關記憶(AnyBot 依這則訊息找出來的,不一定都用得上):\n- 我喜歡靠窗的座位〕\n〔用繁體中文和台灣用語回答,不要用簡體字〕"); assert_eq!(h2[2].context, "〔送出時間:2025-11-11(週二)11:00〕\n〔用繁體中文和台灣用語回答,不要用簡體字〕"); diff --git a/src/app/drops_ui.rs b/src/app/drops_ui.rs index 76aa08b..b62d79a 100644 --- a/src/app/drops_ui.rs +++ b/src/app/drops_ui.rs @@ -113,7 +113,7 @@ impl App { } // Words the person sent here are for pasting: the newest goes on the clipboard. if let Some(r) = fresh.iter().rev().find(|r| !r.text.is_empty()) { - crate::platform::copy_text(&ctx, &r.text); + crate::platform::copy_text(ctx, &r.text); } if !self.headless && self.state.alert_sound { crate::voice::chime(); @@ -207,7 +207,7 @@ impl App { for (what, id) in acts { match what { "reveal" => crate::preview::reveal(std::path::Path::new(&id)), - "copy" => crate::platform::copy_text(&ctx, &id), + "copy" => crate::platform::copy_text(ctx, &id), "pick" => { let (tx, rx) = channel(); pg.picked = Some(rx); diff --git a/src/app/layout_audit.rs b/src/app/layout_audit.rs index ddb355a..4cebc7d 100644 --- a/src/app/layout_audit.rs +++ b/src/app/layout_audit.rs @@ -197,7 +197,7 @@ fn scenes() -> Vec<(&'static str, Open)> { b.messages.push(Message::tool_result("audit-p1", crate::plan::SUBMIT_TOOL, &crate::plan::approved_result(&[]))); b.messages.push(Message { tool_calls: vec![call("audit-p2", "新版:")], ..Message::assistant("", "模型") }); b.plan = Some(crate::plan::Plan { task: long.into(), since: 0, stage: crate::plan::Stage::Doing, revisions: 0, steps: vec![ - crate::plan::Step { title: format!("備份舊資料夾到 /Volumes/Backup/very/deep/path/that/keeps/going/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND"), status: crate::plan::Status::Done }, + crate::plan::Step { title: "備份舊資料夾到 /Volumes/Backup/very/deep/path/that/keeps/going/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND".into(), status: crate::plan::Status::Done }, crate::plan::Step { title: long.into(), status: crate::plan::Status::InProgress }, crate::plan::Step { title: "檢查兩邊的檔案數量".into(), status: crate::plan::Status::Pending }] }); } diff --git a/src/app/voice_ui.rs b/src/app/voice_ui.rs index 776c6bd..18787a7 100644 --- a/src/app/voice_ui.rs +++ b/src/app/voice_ui.rs @@ -72,7 +72,7 @@ pub struct VoiceUi { test_note: Arc>>, test_note_at: String, /// The voices 說 offers: fetched the first time a 聲音 menu opens, kept until 說 changes. - voices_rx: Option, String>>>, + voices_rx: Option>, voice_list: Vec<(String, String)>, voices_err: String, /// Which 說 (service, address, key) the list is for. @@ -84,6 +84,9 @@ pub struct VoiceUi { } /// What a 聲音 row shows and offers. +/// The voices a 說 service offers (id, name), or why not. +type VoicesAnswer = Result, String>; + pub(super) struct VoiceRow { /// The chosen voice by name, or what an empty choice means. pub(super) shown: String, diff --git a/src/browser.rs b/src/browser.rs index a4cef93..363ba36 100644 --- a/src/browser.rs +++ b/src/browser.rs @@ -1488,7 +1488,7 @@ mod tests { } }); let url = format!("http://127.0.0.1:{port}/"); - let r = (|| -> Result<(), String> { + let r = { botbrowser::as_job("lines", || -> Result<(), String> { botbrowser::open(&url, None)?; let refs = || -> Result { run("browser_elements", &json!({})).map(|r| r.0) }; @@ -1509,7 +1509,7 @@ mod tests { assert!(typed.contains("甲 ⏎ 乙"), "{typed}"); Ok(()) }) - })(); + }; let _ = botbrowser::quit(None); r.unwrap(); } @@ -1552,7 +1552,7 @@ document.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey } }); let url = format!("http://127.0.0.1:{port}/"); - let r = (|| -> Result<(), String> { + let r = { botbrowser::as_job("send", || -> Result<(), String> { botbrowser::open(&url, None)?; let info = |mode: &str, rf: &str, value: &str| -> Result { run(SEND_INFO, &json!({"mode": mode, "ref": rf, "value": value})).map(|r| serde_json::from_str(&r.0).unwrap()) }; @@ -1589,7 +1589,7 @@ document.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey assert_eq!((s["kind"].clone(), s["text"].clone()), (json!("search"), json!("貓抓板")), "{s}"); Ok(()) }) - })(); + }; let _ = botbrowser::quit(None); r.unwrap(); } diff --git a/src/drops.rs b/src/drops.rs index ce1d3c8..90c293c 100644 --- a/src/drops.rs +++ b/src/drops.rs @@ -387,7 +387,10 @@ impl Office { } self.set(&p.id, |p| p.state = "sending".into()); let outcome = if p.to == me { - let r = if p.text.is_empty() { self.land_file(&self.bin(&p.id), &p.name, &p.id, &p.from, p.bytes).map(|_| ()) } else { Ok(self.land_text(&p.text, &p.id, &p.from)) }; + let r = if p.text.is_empty() { self.land_file(&self.bin(&p.id), &p.name, &p.id, &p.from, p.bytes).map(|_| ()) } else { + self.land_text(&p.text, &p.id, &p.from); + Ok(()) + }; match r { Ok(()) => Outcome::Done, Err(e) => Outcome::Failed(e), diff --git a/src/embed.rs b/src/embed.rs index bf8f789..b6503a4 100644 --- a/src/embed.rs +++ b/src/embed.rs @@ -142,8 +142,8 @@ pub fn status() -> String { }, Engine::Local if FETCHING.load(Ordering::Relaxed) => { let (got, total) = (GOT.load(Ordering::Relaxed), TOTAL.load(Ordering::Relaxed)); - if total > 0 { - format!("正在下載本機模型:{}%({} / {} MB),好了會自己開始", got * 100 / total, got >> 20, total >> 20) + if let Some(pct) = (got * 100).checked_div(total) { + format!("正在下載本機模型:{pct}%({} / {} MB),好了會自己開始", got >> 20, total >> 20) } else { "正在下載本機模型…".into() } @@ -355,7 +355,7 @@ pub fn f32s_to_blob(v: &[f32]) -> Vec { } pub fn blob_to_f32s(b: &[u8]) -> Vec { - b.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect() + b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect() } /// Cosine, with the guards a shelf of half-filled vectors deserves. @@ -383,7 +383,7 @@ mod tests { // with words. configure("http://127.0.0.1:1/v1", "ollama"); assert!(!enabled(), "a port with nothing behind it means no semantic search"); - assert!(embed(&vec!["test".to_string()]).is_none()); + assert!(embed(&["test".to_string()]).is_none()); configure("http://127.0.0.1:11434", "off"); assert!(!enabled()); configure("http://127.0.0.1:11434", ""); diff --git a/src/find.rs b/src/find.rs index df3ab87..b40905e 100644 --- a/src/find.rs +++ b/src/find.rs @@ -74,7 +74,7 @@ pub fn search(bots: &[Bot], query: &str) -> (Vec, bool) { } } // Newest first; messages without a time keep their order, after the dated ones. - out.sort_by(|a, b| b.at.cmp(&a.at)); + out.sort_by_key(|a| std::cmp::Reverse(a.at)); let more = out.len() > LIMIT; out.truncate(LIMIT); (out, more) diff --git a/src/m2v.rs b/src/m2v.rs index ef43c8e..f416dc1 100644 --- a/src/m2v.rs +++ b/src/m2v.rs @@ -53,7 +53,7 @@ impl Model { if table.len() != rows * dim + rows * 4 { return Err("模型檔大小不對(下載沒有完成?)".into()); } - let scales: Vec = table[rows * dim..].chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + let scales: Vec = table[rows * dim..].as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); table.truncate(rows * dim); table.shrink_to_fit(); let raw = std::fs::read(dir.join("vocab.bin")).map_err(|e| e.to_string())?; @@ -179,7 +179,10 @@ pub fn normalize(text: &str) -> String { out } -fn read_vocab(raw: &[u8]) -> Result<(HashMap, u32>, Vec, usize), String> { +/// The words and their rows, the per-row scales, and the vector size. +type Vocab = (HashMap, u32>, Vec, usize); + +fn read_vocab(raw: &[u8]) -> Result { if raw.len() < 8 || &raw[..4] != b"AVB1" { return Err("字表檔格式不對".into()); } diff --git a/src/mcp.rs b/src/mcp.rs index 554be82..6f3986d 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -1542,11 +1542,10 @@ for line in sys.stdin: } /// Live integration with the openapi-mcp (Go) server, which hot-reloads its swagger and - /// shouts list_changed over the SSE stream. Setup: - /// 1. /tmp/openapimcp-live.yaml exists (port 3901, Spec.File /tmp/openapimcp-live.json, - /// ReloadSeconds 60 so only the management endpoint reloads — the openapimcp repo ships one), - /// 2. from the openapimcp repo: ./bin/srv -f /tmp/openapimcp-live.yaml - /// Then: cargo test openapimcp_live -- --ignored --nocapture + /// shouts list_changed over the SSE stream. Setup: /tmp/openapimcp-live.yaml exists (port 3901, + /// Spec.File /tmp/openapimcp-live.json, ReloadSeconds 60 so only the management endpoint + /// reloads — the openapimcp repo ships one); from the openapimcp repo run + /// `./bin/srv -f /tmp/openapimcp-live.yaml`; then `cargo test openapimcp_live -- --ignored --nocapture`. /// Adding a path to the spec file and POSTing /api/reload must reach us over the open SSE /// stream and refresh the tools without a reconnect. #[test] diff --git a/src/memory.rs b/src/memory.rs index 2e8cb95..deed947 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -83,10 +83,10 @@ pub const TEMPLATES: [Template; 5] = [ Template { name: "開發助手", description: "看程式、跑測試、追 GitHub 上的事", instructions: "改程式前先讀相關檔案和測試。每次修改後跑測試,回報結果。PR 或 CI 的事件來時,先看紀錄再下結論。", shape: "hex", color: "black" }, ]; -/// ---- Skill files (P7): a skill you can keep in a file, share, and install ---- -/// -/// A `.md` file in `/skills/`: front matter (`name:`, `description:`), the instructions -/// as the body, and an optional ```steps fence (the ReplayStep list a replay follows). +// ---- Skill files (P7): a skill you can keep in a file, share, and install ---- +// +// A `.md` file in `/skills/`: front matter (`name:`, `description:`), the instructions +// as the body, and an optional ```steps fence (the ReplayStep list a replay follows). pub fn skill_dir() -> std::path::PathBuf { // Tests never touch the person's data folder. @@ -214,11 +214,9 @@ 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 => { - if status != "done" { - if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) { - e.1 = false; - } + 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; } } _ => {} diff --git a/src/memstore.rs b/src/memstore.rs index e72f5e2..6f31708 100644 --- a/src/memstore.rs +++ b/src/memstore.rs @@ -323,9 +323,8 @@ pub fn search_as(bot: u64, query: &str, kinds: &[&str], limit: usize, literal: b if !have.contains(t.as_str()) { continue; } - if *f >= 1.0 { - got += w; - } else if !terms.iter().any(|(big, bf)| *bf >= 1.0 && big.contains(t.as_str()) && have.contains(big.as_str())) { + // (A whole term, or a piece no matched whole term already counts.) + if *f >= 1.0 || !terms.iter().any(|(big, bf)| *bf >= 1.0 && big.contains(t.as_str()) && have.contains(big.as_str())) { got += w; } } @@ -675,7 +674,9 @@ const FOLD_CHARS: usize = 400; fn fold_line(label: &str, items: &[(String, u32)], total: u32) -> String { let asks: Vec = items.iter().map(|(a, _)| a.replace('、', ",")).collect(); let vecs: Option>> = if crate::embed::enabled() { crate::embed::embed(&asks) } else { None }; - let mut groups: Vec<(String, HashSet, Option>, u32)> = vec![]; + // (the ask, its words, its vector, how many asked it) + type Group = (String, HashSet, Option>, u32); + let mut groups: Vec = vec![]; for (i, ask) in asks.iter().enumerate() { if ask.is_empty() { continue; @@ -691,7 +692,7 @@ fn fold_line(label: &str, items: &[(String, u32)], total: u32) -> String { None => groups.push((ask.clone(), ws, v, n)), } } - groups.sort_by(|a, b| b.3.cmp(&a.3)); + groups.sort_by_key(|a| std::cmp::Reverse(a.3)); let mut s = format!("{label}({total} 件):"); let mut shown = 0u32; for (i, (ask, _, _, n)) in groups.iter().enumerate() { diff --git a/src/store.rs b/src/store.rs index 8964045..b6393c7 100644 --- a/src/store.rs +++ b/src/store.rs @@ -60,7 +60,7 @@ fn connect(p: &std::path::Path) -> Option { #[cfg(unix)] if !p.exists() { use std::os::unix::fs::OpenOptionsExt; - let _ = std::fs::OpenOptions::new().write(true).create(true).mode(0o600).open(p); + let _ = std::fs::OpenOptions::new().write(true).create(true).truncate(false).mode(0o600).open(p); } let c = Connection::open(p).ok()?; crate::httpd::tighten_permissions(p); @@ -679,7 +679,7 @@ pub fn docs_search(query: &str, limit: usize) -> Vec<(String, String)> { Ok(()) }); } - scored.sort_by(|a, b| b.0.cmp(&a.0)); + scored.sort_by_key(|a| std::cmp::Reverse(a.0)); for (_, path, text) in scored { if !words.iter().any(|(p, t)| p == &path && t == &text) { words.push((path, text));