From 06dbdbf79553a21342a09d2ef984a73046aea591 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Sun, 29 Nov 2026 15:02:43 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat(crates/panache-mcp):=20=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E5=AF=BC=E5=87=BA=E6=97=B6=E5=A3=B0=E6=98=8E=E9=87=87?= =?UTF-8?q?=E7=94=A8=E7=9A=84=E4=BD=9C=E4=B8=9A=E7=BB=8F=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:检索结果只能说明模型搜到了什么,无法区分是否实际采用。 解决手段:导出接受可选经验 ID,在文件发布时核对有效状态并保存宿主声明。 收益:能按稿件、版本和交付回执审计采用情况,不改变成品或把声明误当成效果。 --- CHANGELOG.md | 2 + crates/panache-mcp/README.md | 2 + crates/panache-mcp/src/experience.rs | 2 + .../panache-mcp/src/experience/application.rs | 64 +++++++++ crates/panache-mcp/src/inputs.rs | 4 + crates/panache-mcp/src/main.rs | 6 +- crates/panache-mcp/src/storage.rs | 25 +++- crates/panache-mcp/src/storage/tests.rs | 50 ++++++- .../tests/experience_application.py | 136 ++++++++++++++++++ 9 files changed, 280 insertions(+), 11 deletions(-) create mode 100644 crates/panache-mcp/src/experience/application.rs create mode 100644 crates/panache-mcp/tests/experience_application.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 867d2287..6c1ac404 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 未发布 +- MCP 导出时可选记录宿主实际采用的作业经验 ID,便于按交付文件区分「查到」和「声明用过」。这项记录不评价经验效果。 + - 照片稿整页复查在有可比纸面线索时提示查找适用的新增墨迹控制,缺少纸面投影时明确说明原因。 - 已建立纸面投影的照片稿可在 MCP 中选择让新增笔迹随局部纸色调整,或按原照上的两个点渐变柔化。两项默认关闭,不改动底纸,适用于预览及 PDF 和 PNG 导出。 - 修复已有精细编辑的稿件在表格避让更新后静默移位或换页;旧稿继续使用原布局,新稿仍按表格避让排版。 diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index f90f46bf..03665ab5 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -246,6 +246,8 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/ 普通作业导出后,`experience_reflection` 附上 `export_id` 和最多八个已检查页面的引用。如果同一页在之前的版本也有原生检查单,`earlier_reference` 会指向最近的已检查旧版。更多页面可通过 `read_section(view="review")` 查回。 +需要记录经验是否真的用在交付版时,可以在 `export_handwriting` 传可选的 `applied_experience_ids`(最多 16 个)。只填宿主已经按适用条件采用的经验,搜到但没用过的不填,也不必为这个字段额外检索。省略表示「未报告」;传 `[]` 表示「明确没用」。发布成功后,`experience_application` 回执说明实际保存的 ID(`basis="host_report"`)和忽略的项数。重复、未生效、已撤回或未知的 ID 不保存;全部无效或超出上限时不写采用记录,仍正常导出。记录按 `export_id` 关联到确切稿件和版本;它不改成稿、经验状态或检索排序,也不能证明经验带来了收益。 + - **一条经验写一个可单独验证的动作。** 宿主填写适用标签 `tags`、具体条件 `scope`、动作 `action`、结合页面观察写出的理由 `reason`、该条自己的检查单 `reviews`。同一道题若有两个独立问题,可拆成两条,分别验证、检索和退役。拆分粒度由宿主判断。每次调用可传 0–16 条。同标签、条件和动作的重复提案复用原 ID。 - **有修前、修后检查单时,在最终答复前提交复盘决定。** 调用 `record_homework_experience`,逐条引用本次导出和交付版检查单,可附同稿旧版。只有本题的数值或笔误可传 `rules=[]`。干净完成的作业也可以直接交付。工具返回每条的 ID 和状态;宿主可以向用户简述刚记录的做法及其待验证状态。 - **下次用新作业的原话或主题直接搜条目。** 持有 ID 时可用 `read_homework_experience` 审计来源及逐次验证。不同会话共享同一个 Panache 数据目录时可见同一经验库。 diff --git a/crates/panache-mcp/src/experience.rs b/crates/panache-mcp/src/experience.rs index 936d30c0..bd64b34f 100644 --- a/crates/panache-mcp/src/experience.rs +++ b/crates/panache-mcp/src/experience.rs @@ -1,4 +1,5 @@ //! Evidence-backed, individually retrievable guidance from ordinary homework deliveries. +pub(crate) mod application; mod fulltext; mod opportunity; #[cfg(test)] @@ -33,6 +34,7 @@ pub(crate) fn initialize(db: &Connection) -> Result<()> { ON experience_cases(rule_id,draft,revision,reviews) WHERE role='source'; CREATE INDEX IF NOT EXISTS experience_cases_by_rule ON experience_cases(rule_id,seq); ")?; + application::initialize(db)?; fulltext::initialize(db) } diff --git a/crates/panache-mcp/src/experience/application.rs b/crates/panache-mcp/src/experience/application.rs new file mode 100644 index 00000000..da019fc8 --- /dev/null +++ b/crates/panache-mcp/src/experience/application.rs @@ -0,0 +1,64 @@ +//! Optional host declarations, separate from rule evidence and ranking. +use anyhow::Result; +use rusqlite::{Connection, params}; +use serde::Serialize; +use std::collections::BTreeSet; + +const MAX_IDS: usize = 16; + +#[derive(Serialize)] +pub(crate) struct Report { + basis: &'static str, + recorded: bool, + applied_experience_ids: Vec, + ignored_count: usize, +} + +pub(super) fn initialize(db: &Connection) -> Result<()> { + db.execute_batch( + "CREATE TABLE IF NOT EXISTS experience_application_reports( + export_id TEXT PRIMARY KEY, + rule_ids TEXT NOT NULL, + ignored_count INTEGER NOT NULL + );", + )?; + Ok(()) +} + +/// Call during publication. A malformed or stale declaration cannot prevent the file delivery. +pub(crate) fn record(db: &Connection, export_id: &str, ids: &[String]) -> Result { + let mut report = Report { + basis: "host_report", + recorded: false, + applied_experience_ids: Vec::new(), + ignored_count: ids.len(), + }; + if ids.len() <= MAX_IDS { + let mut seen = BTreeSet::new(); + let mut exists = db.prepare( + "SELECT EXISTS(SELECT 1 FROM experience_rules WHERE id=? AND status='active')", + )?; + for id in ids { + if uuid::Uuid::parse_str(id).is_ok() + && seen.insert(id) + && exists.query_row([id], |row| row.get::<_, bool>(0))? + { + report.applied_experience_ids.push(id.clone()); + } + } + report.ignored_count -= report.applied_experience_ids.len(); + if ids.is_empty() || !report.applied_experience_ids.is_empty() { + db.execute( + "INSERT INTO experience_application_reports(export_id,rule_ids,ignored_count) + VALUES(?,?,?)", + params![ + export_id, + serde_json::to_string(&report.applied_experience_ids)?, + u32::try_from(report.ignored_count)? + ], + )?; + report.recorded = true; + } + } + Ok(report) +} diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 3d35e525..6ea2ff78 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -450,6 +450,10 @@ pub struct Export { /// Up to 512 KiB before base64 encoding. Larger files stay available at the returned server path. #[serde(default)] pub include_file: bool, + /// Optional host report: list only active homework experience IDs whose advice you actually used + /// in this delivered revision (at most 16). Search results alone do not count. + /// Omit if not reporting, or pass [] to report that none were used. Do not search just to fill this field. + pub applied_experience_ids: Option>, } #[derive(Clone, Copy, Deserialize, JsonSchema, PartialEq, serde::Serialize)] diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index c21e17fc..d0f3ad74 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -879,7 +879,8 @@ impl Panache { let mut different = Vec::new(); let params = controls::parameters(&draft, 1, &draft.controls)?; let zero_text_ink = params.ink_opacity == 0 || params.fill[3] == 0; - let storage::PublishedExport {id: export_id, path, pages, file} = state.storage.export(&state.drafts,draft.id,draft.revision,format, |writer| engine.export( + let storage::PublishedExport {id: export_id, path, pages, file, application} = state.storage.export( + &state.drafts, draft.id, draft.revision, format, input.applied_experience_ids.as_deref(), |writer| engine.export( writer, &draft, sections, (format, active_finish), cancel, |pages, section, page, image| { match reviewed_pages.get(&(section, page)) { @@ -967,6 +968,9 @@ impl Panache { if matches!(format, Format::Zip) && let Some(finish @ engine::export_blur::Finish::Gradient(_)) = finish { finish.write_metadata(&mut metadata); } + if let Some(application) = application { + metadata["experience_application"] = serde_json::to_value(application)?; + } let mut result = reply(message, metadata); if input.include_file { delivery::include_file(&mut result, file, &path, format); diff --git a/crates/panache-mcp/src/storage.rs b/crates/panache-mcp/src/storage.rs index a5b7c2dc..98342147 100644 --- a/crates/panache-mcp/src/storage.rs +++ b/crates/panache-mcp/src/storage.rs @@ -4,7 +4,7 @@ mod cleanup; mod tests; pub use cleanup::{ApplyCleanup, CleanupScope}; -use crate::{Format, drafts::Drafts}; +use crate::{Format, drafts::Drafts, experience::application}; use anyhow::{Context, Result, ensure}; use rusqlite::{Connection, params}; use schemars::JsonSchema; @@ -25,6 +25,7 @@ pub(crate) struct PublishedExport { pub path: PathBuf, pub pages: usize, pub file: File, + pub application: Option, } #[derive(Deserialize, JsonSchema)] @@ -207,6 +208,7 @@ impl Storage { draft: &str, revision: u32, format: Format, + applied_experience_ids: Option<&[String]>, render: F, ) -> Result where @@ -217,7 +219,7 @@ impl Storage { self.allowance()? > 0, "Storage limit: no capacity for a new export; inspect storage_usage and plan_cleanup" ); - let db = drafts.connect()?; + let mut db = drafts.connect()?; let id = Uuid::new_v4().to_string(); let extension = match format { Format::Pdf => "pdf", @@ -244,19 +246,30 @@ impl Storage { }; let pages = render(&mut output)?; output.flush()?; - let file = temp.persist_noclobber(&path)?; - db.execute("UPDATE export_files SET published=1 WHERE id=?", [&id])?; - Ok((pages, file)) + let (file, application) = if let Some(ids) = applied_experience_ids { + let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; + let report = application::record(&tx, &id, ids)?; + let file = temp.persist_noclobber(&path)?; + tx.execute("UPDATE export_files SET published=1 WHERE id=?", [&id])?; + tx.commit()?; + (file, Some(report)) + } else { + let file = temp.persist_noclobber(&path)?; + db.execute("UPDATE export_files SET published=1 WHERE id=?", [&id])?; + (file, None) + }; + Ok((pages, file, application)) }; let result = publish(); if result.is_err() && metadata(&path)?.is_none() { db.execute("DELETE FROM export_files WHERE id=? AND published=0", [&id])?; } - result.map(|(pages, file)| PublishedExport { + result.map(|(pages, file, application)| PublishedExport { id, path, pages, file, + application, }) } diff --git a/crates/panache-mcp/src/storage/tests.rs b/crates/panache-mcp/src/storage/tests.rs index 504d54e6..eec8c46b 100644 --- a/crates/panache-mcp/src/storage/tests.rs +++ b/crates/panache-mcp/src/storage/tests.rs @@ -10,7 +10,7 @@ fn interrupted_writer() -> Result<()> { let home = PathBuf::from(home); let drafts = Drafts::open(&home)?; let store = Storage::open(&home, &drafts)?; - store.export(&drafts, "draft", 1, Format::Zip, |writer| { + store.export(&drafts, "draft", 1, Format::Zip, None, |writer| { writer.write_all(b"unfinished")?; writer.flush()?; std::process::exit(23) @@ -44,7 +44,7 @@ fn plan_reclaims_only_selected_abandoned_writes() -> Result<()> { })?; let old = dir.path().join("exports").join("panache-old.pdf"); fs::write(&old, b"legacy")?; - let delivered = store.export(&drafts, "draft", 1, Format::Pdf, |writer| { + let delivered = store.export(&drafts, "draft", 1, Format::Pdf, None, |writer| { writer.write_all(b"delivered")?; Ok(1) })?; @@ -161,7 +161,7 @@ fn budgets_block_heavy_writes_without_publishing_partial_outputs() -> Result<()> let mut store = Storage::open(dir.path(), &drafts)?; store.policy.min_free_bytes = Some(u64::MAX); assert!(store.import(1).is_err()); - let result = store.export(&drafts, "draft", 1, Format::Zip, |w| { + let result = store.export(&drafts, "draft", 1, Format::Zip, Some(&[]), |w| { w.write_all(&[0; 17])?; Ok(1) }); @@ -170,7 +170,7 @@ fn budgets_block_heavy_writes_without_publishing_partial_outputs() -> Result<()> store.policy.min_free_bytes = None; store.policy.max_home_bytes = Some(directory_bytes(&store.home)? + 200_000); assert!(store.import(300_000).is_err()); - let result = store.export(&drafts, "draft", 1, Format::Zip, |w| { + let result = store.export(&drafts, "draft", 1, Format::Zip, Some(&[]), |w| { w.write_all(&[0; 200])?; w.seek(SeekFrom::Start(100))?; w.write_all(&[0; 100])?; @@ -181,5 +181,47 @@ fn budgets_block_heavy_writes_without_publishing_partial_outputs() -> Result<()> assert_eq!(fs::read_dir(&store.exports)?.count(), 0); let usage = store.usage(&drafts, Usage { draft_id: None })?; assert_eq!(usage["delivered_bytes"], 0); + let reports: u32 = drafts.connect()?.query_row( + "SELECT count(*) FROM experience_application_reports", + [], + |row| row.get(0), + )?; + assert_eq!(reports, 0); + Ok(()) +} + +#[test] +fn failed_application_write_leaves_no_deliverable_or_report() -> Result<()> { + let dir = tempfile::tempdir()?; + fs::create_dir(dir.path().join("exports"))?; + let drafts = Drafts::open(dir.path())?; + let store = Storage::open(dir.path(), &drafts)?; + let db = drafts.connect()?; + db.execute_batch( + "CREATE TRIGGER deny_application BEFORE INSERT ON experience_application_reports + BEGIN SELECT RAISE(ABORT, 'test declaration write failure'); END;", + )?; + let denied = store.export(&drafts, "draft", 1, Format::Pdf, Some(&[]), |w| { + w.write_all(b"rendered")?; + Ok(1) + }); + assert!(denied.is_err()); + assert_eq!(fs::read_dir(&store.exports)?.count(), 0); + let counts = |db: &rusqlite::Connection| -> Result<(u32, u32)> { + Ok(db.query_row( + "SELECT (SELECT count(*) FROM export_files), + (SELECT count(*) FROM experience_application_reports)", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + )?) + }; + assert_eq!(counts(&db)?, (0, 0)); + db.execute_batch("DROP TRIGGER deny_application;")?; + let published = store.export(&drafts, "draft", 1, Format::Pdf, Some(&[]), |w| { + w.write_all(b"rendered")?; + Ok(1) + })?; + assert_eq!(fs::read(published.path)?, b"rendered"); + assert_eq!(counts(&db)?, (1, 1)); Ok(()) } diff --git a/crates/panache-mcp/tests/experience_application.py b/crates/panache-mcp/tests/experience_application.py new file mode 100644 index 00000000..aca9ef66 --- /dev/null +++ b/crates/panache-mcp/tests/experience_application.py @@ -0,0 +1,136 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = ["mcp>=1.12,<2"] +# /// +"""Exercise optional experience declarations through actual MCP file delivery.""" + +import argparse +import asyncio +import hashlib +import json +from pathlib import Path +from tempfile import TemporaryDirectory + +from experience_visibility import delivered, result +from mcp_client import clone_home, isolated_session, open_db + +UNKNOWN = "00000000-0000-4000-8000-000000000000" + + +async def seed(client): + source, _, _ = await delivered(client, "来源", "三组共 12 颗种子,每组 12 / 3 = 4。") + common = { + "tags": ["homework"], + "scope": "求每组平均数,核对除数和单位。", + "reason": "只看答案不能知道用了哪个除数。", + "reviews": source["reviews"], + } + ids = (await result( + client, "record_homework_experience", **{k: v for k, v in source.items() if k != "reviews"}, + rules=[{**common, "action": action} for action in ( + "读回分式里的除数。", "读回分式里的单位。", "检查表格题的单位。", "检查流程图节点。", + )], + ))["rules"] + active, withdrawn, pending, rejected = (r["rule_id"] for r in ids) + positive, _, earlier = await delivered( + client, "正例", "八颗种子分两组,8 / 2 = 4。", before="八颗种子分两组,8 / 4 = 2。", + ) + boundary, _, _ = await delivered(client, "边界例", "三组共有九颗种子,9 / 3 = 3。") + for rule in (active, withdrawn): + await result(client, "validate_homework_experience", rule_id=rule, kind="positive", + passed=True, reason="按原题核对修订后的算式。", **{ + **positive, "reviews": positive["reviews"] + [earlier], + }) + await result(client, "validate_homework_experience", rule_id=rule, kind="boundary", + passed=True, reason="原来正确的等式不变。", **boundary) + await result(client, "retire_homework_experience", rule_id=withdrawn, reason="测试退役。") + await result(client, "validate_homework_experience", rule_id=rejected, kind="boundary", + passed=False, reason="仅用于控制组。", **boundary) + return active, withdrawn, pending, rejected + + +def report_rows(home): + with open_db(home) as db: + return dict((id, (draft, revision, published, json.loads(ids), ignored)) + for id, draft, revision, published, ids, ignored in db.execute( + "SELECT export_id,draft,revision,published,rule_ids,ignored_count " + "FROM experience_application_reports JOIN export_files ON export_id=id")) + + +async def run(binary, root, baseline=None): + home = root / "main" + home.mkdir() + async with isolated_session(binary, home) as (client, _): + active, retired, pending, rejected = await seed(client) + draft = await result(client, "save_section", markdown="十二颗种子平均分四组。12 / 4 = 3。", + style={"homework": True, "seed": 141}) + key = {"draft_id": draft["draft_id"], "revision": draft["revision"]} + old = await result(client, "export_handwriting", **key) + assert "experience_application" not in old and not report_rows(home) + empty = await result(client, "export_handwriting", **key, applied_experience_ids=[]) + filtered = await result(client, "export_handwriting", **key, + applied_experience_ids=[active, active, retired, pending, rejected, UNKNOWN]) + assert empty["experience_application"] == { + "basis": "host_report", "recorded": True, "applied_experience_ids": [], "ignored_count": 0, + } + assert filtered["experience_application"] == { + "basis": "host_report", "recorded": True, "applied_experience_ids": [active], "ignored_count": 5, + } + for args in ([retired, pending, rejected, UNKNOWN], [active] * 17): + bad = await result(client, "export_handwriting", **key, applied_experience_ids=args) + assert not bad["experience_application"]["recorded"] + assert bad["experience_application"]["ignored_count"] == len(args) + pdf = Path(old["path"]).read_bytes() + assert all(Path(r["path"]).read_bytes() == pdf for r in (empty, filtered, bad)) + wrong = await client.call_tool("export_handwriting", {**key, "revision": 999, + "applied_experience_ids": [active]}) + assert wrong.isError + changed = await result(client, "save_section", draft_id=key["draft_id"], section=1, + expected_revision=key["revision"], markdown="十三颗种子。") + assert changed["revision"] == 2 + old_revision = await result(client, "export_handwriting", **key, applied_experience_ids=[active]) + assert Path(old_revision["path"]).read_bytes() == pdf + no_report = await result(client, "export_handwriting", draft_id=key["draft_id"], revision=2) + assert Path(no_report["path"]).read_bytes() != pdf + zipped = await result(client, "export_handwriting", **key, format="zip") + zipped_report = await result(client, "export_handwriting", **key, format="zip", + applied_experience_ids=[active]) + from zipfile import ZipFile + def pages(path): + with ZipFile(path) as z: + return [z.read(n) for n in z.namelist() if n.endswith(".png")] + assert pages(zipped["path"]) == pages(zipped_report["path"]) + assert len(pages(zipped["path"])) == 1 + async with isolated_session(binary, home) as (client, _): + listings = (await client.list_tools()).tools + assert {x.name for x in listings} >= {"search_homework_experience", "export_handwriting"} + assert len(listings) == 19 + new_schema = next(x.inputSchema for x in listings if x.name == "export_handwriting") + assert "applied_experience_ids" in new_schema["properties"] + assert "applied_experience_ids" not in new_schema.get("required", []) + rows = report_rows(home) + pairs = [(empty, [], 0), (filtered, [active], 5), (old_revision, [active], 0), + (zipped_report, [active], 0)] + assert rows == {receipt["export_id"]: (key["draft_id"], key["revision"], 1, ids, ignored) + for receipt, ids, ignored in pairs} + lookup = await result(client, "search_homework_experience", tags=["homework"]) + assert [r["rule_id"] for r in lookup["rules"]] == [active] + if baseline is not None: + legacy = clone_home(home, "baseline") + async with isolated_session(baseline, legacy) as (client, _): + old = await result(client, "export_handwriting", **key) + assert Path(old["path"]).read_bytes() == pdf and "experience_application" not in old + response = await client.call_tool("export_handwriting", {**key, "applied_experience_ids": [active]}) + assert response.isError + print(json.dumps({"confirmed_reports": len(rows), "pdf_sha256": hashlib.sha256(pdf).hexdigest(), + "png_sha256": hashlib.sha256(pages(zipped["path"])[0]).hexdigest(), + "legacy_comparison": baseline is not None})) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("binary", type=Path) + parser.add_argument("--baseline", type=Path) + args = parser.parse_args() + with TemporaryDirectory() as tmp: + asyncio.run(run(args.binary.resolve(), Path(tmp), args.baseline and args.baseline.resolve())) From af39f99046cfb5dc4e5e24a9c4bf5f987e5129ed Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Sun, 29 Nov 2026 16:57:52 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat(crates/panache-mcp):=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=8C=89=E7=BB=8F=E9=AA=8C=E6=9F=A5=E4=BA=A4=E4=BB=98?= =?UTF-8?q?=E9=87=87=E7=94=A8=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:导出可以声明采用了哪些经验,但 MCP 不能查回这些记录;按经验查旧的 JSON 列也需要逐行展开。 解决手段:在原有经验读取工具中加入宿主声明的次数、交付版本和独立分页。把声明拆成报告和逐条索引,原子迁移旧记录,补齐翻页、重启和写入中途失败的验证。 收益:无需打开数据库即可查到哪次交付声明用了这条经验,不改变原有检索排序、规则状态或成品。 --- CHANGELOG.md | 3 +- crates/panache-mcp/README.md | 2 + crates/panache-mcp/src/experience.rs | 10 +- .../panache-mcp/src/experience/application.rs | 110 +++++++++++++++--- crates/panache-mcp/src/main.rs | 2 +- crates/panache-mcp/src/storage/tests.rs | 58 +++++++++ .../tests/experience_application.py | 95 +++++++++++++-- 7 files changed, 252 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c1ac404..7073b267 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,7 @@ ## 未发布 -- MCP 导出时可选记录宿主实际采用的作业经验 ID,便于按交付文件区分「查到」和「声明用过」。这项记录不评价经验效果。 - +- MCP 导出时可选记录宿主实际采用的作业经验 ID,便于按交付文件区分「查到」和「声明用过」。按经验 ID 可查宿主自报的采用次数和最近的交付版本,不代表经验有效。 - 照片稿整页复查在有可比纸面线索时提示查找适用的新增墨迹控制,缺少纸面投影时明确说明原因。 - 已建立纸面投影的照片稿可在 MCP 中选择让新增笔迹随局部纸色调整,或按原照上的两个点渐变柔化。两项默认关闭,不改动底纸,适用于预览及 PDF 和 PNG 导出。 - 修复已有精细编辑的稿件在表格避让更新后静默移位或换页;旧稿继续使用原布局,新稿仍按表格避让排版。 diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 03665ab5..5a7847d7 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -248,6 +248,8 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/ 需要记录经验是否真的用在交付版时,可以在 `export_handwriting` 传可选的 `applied_experience_ids`(最多 16 个)。只填宿主已经按适用条件采用的经验,搜到但没用过的不填,也不必为这个字段额外检索。省略表示「未报告」;传 `[]` 表示「明确没用」。发布成功后,`experience_application` 回执说明实际保存的 ID(`basis="host_report"`)和忽略的项数。重复、未生效、已撤回或未知的 ID 不保存;全部无效或超出上限时不写采用记录,仍正常导出。记录按 `export_id` 关联到确切稿件和版本;它不改成稿、经验状态或检索排序,也不能证明经验带来了收益。 +已知经验 ID 时,`read_homework_experience` 的 `applications` 返回 `basis="host_report"`、声明采用这条经验的已发布导出数 `reported_exports`,以及最近最多 20 次的 `items`(`export_id`、`draft_id`、`revision` 和分页用的 `seq`)。同一导出重复填同一 ID 只计一次;同一版本的两次导出分别计数。把这一页的 `applications.next_after` 传给 `applications_after` 可看更早的交付,原有 `after` 仍只翻验证记录 `cases`。退役不会擦掉历史声明;零条声明不等于从来没用。只有按 ID 审计时能看到这项统计,不进入检索结果或排序。 + - **一条经验写一个可单独验证的动作。** 宿主填写适用标签 `tags`、具体条件 `scope`、动作 `action`、结合页面观察写出的理由 `reason`、该条自己的检查单 `reviews`。同一道题若有两个独立问题,可拆成两条,分别验证、检索和退役。拆分粒度由宿主判断。每次调用可传 0–16 条。同标签、条件和动作的重复提案复用原 ID。 - **有修前、修后检查单时,在最终答复前提交复盘决定。** 调用 `record_homework_experience`,逐条引用本次导出和交付版检查单,可附同稿旧版。只有本题的数值或笔误可传 `rules=[]`。干净完成的作业也可以直接交付。工具返回每条的 ID 和状态;宿主可以向用户简述刚记录的做法及其待验证状态。 - **下次用新作业的原话或主题直接搜条目。** 持有 ID 时可用 `read_homework_experience` 审计来源及逐次验证。不同会话共享同一个 Panache 数据目录时可见同一经验库。 diff --git a/crates/panache-mcp/src/experience.rs b/crates/panache-mcp/src/experience.rs index bd64b34f..57cb82a2 100644 --- a/crates/panache-mcp/src/experience.rs +++ b/crates/panache-mcp/src/experience.rs @@ -14,7 +14,7 @@ use serde_json::{Value, json}; use std::collections::BTreeSet; use uuid::Uuid; -pub(crate) fn initialize(db: &Connection) -> Result<()> { +pub(crate) fn initialize(db: &rusqlite::Transaction<'_>) -> Result<()> { db.execute_batch(" CREATE TABLE IF NOT EXISTS experience_rules ( id TEXT PRIMARY KEY, signature TEXT NOT NULL UNIQUE, scope TEXT NOT NULL, @@ -92,6 +92,9 @@ pub struct Read { /// Exclusive evidence sequence cursor from a previous read. #[serde(default)] after: u64, + /// Exclusive host-reported application cursor from applications.next_after. Pages only + /// applications, newest first; counts are declarations, not evidence or search ranking. + applications_after: Option, } #[derive(Copy, Clone, Deserialize, JsonSchema)] @@ -476,6 +479,11 @@ impl Drafts { Value::Null }; rule["cases"] = json!(cases); + rule["applications"] = serde_json::to_value(application::read( + &tx, + &input.rule_id, + input.applications_after, + )?)?; Ok(rule) } } diff --git a/crates/panache-mcp/src/experience/application.rs b/crates/panache-mcp/src/experience/application.rs index da019fc8..27636fa9 100644 --- a/crates/panache-mcp/src/experience/application.rs +++ b/crates/panache-mcp/src/experience/application.rs @@ -1,6 +1,6 @@ //! Optional host declarations, separate from rule evidence and ranking. use anyhow::Result; -use rusqlite::{Connection, params}; +use rusqlite::{Transaction, params}; use serde::Serialize; use std::collections::BTreeSet; @@ -14,19 +14,100 @@ pub(crate) struct Report { ignored_count: usize, } -pub(super) fn initialize(db: &Connection) -> Result<()> { +pub(super) fn initialize(db: &Transaction<'_>) -> Result<()> { db.execute_batch( "CREATE TABLE IF NOT EXISTS experience_application_reports( - export_id TEXT PRIMARY KEY, - rule_ids TEXT NOT NULL, - ignored_count INTEGER NOT NULL - );", + export_id TEXT PRIMARY KEY, + ignored_count INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS experience_applications( + seq INTEGER PRIMARY KEY, + export_id TEXT NOT NULL REFERENCES experience_application_reports(export_id), + rule_id TEXT NOT NULL REFERENCES experience_rules(id), + UNIQUE(export_id,rule_id) + ); + CREATE INDEX IF NOT EXISTS experience_applications_by_rule + ON experience_applications(rule_id,seq,export_id);", )?; + // Preserve reports made by earlier builds of this draft, including explicit empty reports. + if db.column_exists(None, c"experience_application_reports", c"rule_ids")? { + db.execute_batch( + "INSERT INTO experience_applications(export_id,rule_id) + SELECT DISTINCT r.export_id, j.value + FROM experience_application_reports r, json_each(r.rule_ids) j + ORDER BY r.rowid, j.key; + ALTER TABLE experience_application_reports DROP COLUMN rule_ids;", + )?; + } Ok(()) } +#[derive(Serialize)] +pub(super) struct Applications { + basis: &'static str, + reported_exports: i64, + items: Vec, + next_after: Option, +} + +#[derive(Serialize)] +struct Application { + seq: i64, + export_id: String, + draft_id: String, + revision: u32, +} + +pub(super) fn read( + db: &Transaction<'_>, + rule_id: &str, + after: Option, +) -> Result { + // Count and page on the same SQLite snapshot as the rule and its evidence. + let reported_exports = db.query_row( + "SELECT count(*) FROM experience_applications a + CROSS JOIN export_files e ON e.id=a.export_id + WHERE a.rule_id=? AND e.published=1", + [rule_id], + |row| row.get(0), + )?; + let mut stmt = db.prepare( + "SELECT a.seq,a.export_id,e.draft,e.revision FROM experience_applications a + CROSS JOIN export_files e ON e.id=a.export_id + WHERE a.rule_id=? AND a.seq>>()?; + let more = items.len() > 20; + items.truncate(20); + Ok(Applications { + basis: "host_report", + reported_exports, + next_after: if more { + items.last().map(|item| item.seq) + } else { + None + }, + items, + }) +} + /// Call during publication. A malformed or stale declaration cannot prevent the file delivery. -pub(crate) fn record(db: &Connection, export_id: &str, ids: &[String]) -> Result { +pub(crate) fn record(db: &Transaction<'_>, export_id: &str, ids: &[String]) -> Result { let mut report = Report { basis: "host_report", recorded: false, @@ -49,14 +130,15 @@ pub(crate) fn record(db: &Connection, export_id: &str, ids: &[String]) -> Result report.ignored_count -= report.applied_experience_ids.len(); if ids.is_empty() || !report.applied_experience_ids.is_empty() { db.execute( - "INSERT INTO experience_application_reports(export_id,rule_ids,ignored_count) - VALUES(?,?,?)", - params![ - export_id, - serde_json::to_string(&report.applied_experience_ids)?, - u32::try_from(report.ignored_count)? - ], + "INSERT INTO experience_application_reports(export_id,ignored_count) + VALUES(?,?)", + params![export_id, u32::try_from(report.ignored_count)?], )?; + let mut insert = + db.prepare("INSERT INTO experience_applications(export_id,rule_id) VALUES(?,?)")?; + for id in &report.applied_experience_ids { + insert.execute(params![export_id, id])?; + } report.recorded = true; } } diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index d0f3ad74..d1a49ef9 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -473,7 +473,7 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "Audit one known rule by ID, including pending, rejected or retired status, original evidence and independent validations. Use search_homework_experience for current task instructions." + description = "Audit one known rule by ID, including pending, rejected or retired status, original evidence and independent validations. Applications are host reports of published exports, not evidence of effectiveness. Use search_homework_experience for current task instructions." )] async fn read_homework_experience( &self, diff --git a/crates/panache-mcp/src/storage/tests.rs b/crates/panache-mcp/src/storage/tests.rs index eec8c46b..d11858eb 100644 --- a/crates/panache-mcp/src/storage/tests.rs +++ b/crates/panache-mcp/src/storage/tests.rs @@ -225,3 +225,61 @@ fn failed_application_write_leaves_no_deliverable_or_report() -> Result<()> { assert_eq!(counts(&db)?, (1, 1)); Ok(()) } + +#[test] +fn failed_second_application_rolls_back_first_and_report() -> Result<()> { + let dir = tempfile::tempdir()?; + fs::create_dir(dir.path().join("exports"))?; + let drafts = Drafts::open(dir.path())?; + let store = Storage::open(dir.path(), &drafts)?; + let db = drafts.connect()?; + let first = uuid::Uuid::new_v4().to_string(); + let second = uuid::Uuid::new_v4().to_string(); + for id in [&first, &second] { + db.execute( + "INSERT INTO experience_rules(id,signature,scope,action,reason,status) + VALUES(?1,?1,'scope','action','reason','active')", + [id], + )?; + } + db.execute_batch( + "CREATE TRIGGER deny_second_application BEFORE INSERT ON experience_applications + WHEN EXISTS(SELECT 1 FROM experience_applications) + BEGIN SELECT RAISE(ABORT, 'test second application write failure'); END;", + )?; + let publish = || { + store.export( + &drafts, + "draft", + 1, + Format::Pdf, + Some(&[first.clone(), second.clone()]), + |w| { + w.write_all(b"rendered")?; + Ok(1) + }, + ) + }; + assert!(publish().err().unwrap().to_string().contains("test second")); + assert_eq!(fs::read_dir(&store.exports)?.count(), 0); + let counts = || { + db.query_row( + "SELECT (SELECT count(*) FROM export_files), + (SELECT count(*) FROM experience_application_reports), + (SELECT count(*) FROM experience_applications)", + [], + |row| { + Ok(( + row.get::<_, u32>(0)?, + row.get::<_, u32>(1)?, + row.get::<_, u32>(2)?, + )) + }, + ) + }; + assert_eq!(counts()?, (0, 0, 0)); + db.execute_batch("DROP TRIGGER deny_second_application;")?; + assert_eq!(fs::read(publish()?.path)?, b"rendered"); + assert_eq!(counts()?, (1, 1, 2)); + Ok(()) +} diff --git a/crates/panache-mcp/tests/experience_application.py b/crates/panache-mcp/tests/experience_application.py index aca9ef66..7df6a30c 100644 --- a/crates/panache-mcp/tests/experience_application.py +++ b/crates/panache-mcp/tests/experience_application.py @@ -12,6 +12,7 @@ from tempfile import TemporaryDirectory from experience_visibility import delivered, result +from zipfile import ZipFile from mcp_client import clone_home, isolated_session, open_db UNKNOWN = "00000000-0000-4000-8000-000000000000" @@ -51,13 +52,46 @@ async def seed(client): def report_rows(home): with open_db(home) as db: - return dict((id, (draft, revision, published, json.loads(ids), ignored)) - for id, draft, revision, published, ids, ignored in db.execute( - "SELECT export_id,draft,revision,published,rule_ids,ignored_count " - "FROM experience_application_reports JOIN export_files ON export_id=id")) + reports = {export: (draft, revision, published, [], ignored) + for export, draft, revision, published, ignored in db.execute( + "SELECT export_id,draft,revision,published,ignored_count " + "FROM experience_application_reports JOIN export_files ON export_id=id")} + for export, rule in db.execute( + "SELECT export_id,rule_id FROM experience_applications ORDER BY seq" + ): + reports[export][3].append(rule) + return reports -async def run(binary, root, baseline=None): +async def audit(client, rule_id, **cursor): + return await result(client, "read_homework_experience", rule_id=rule_id, **cursor) + + +async def verify_legacy_migration(binary, previous, home): + home.mkdir() + async with isolated_session(previous, home) as (client, _): + active, _, _, _ = await seed(client) + draft = await result(client, "save_section", markdown="迁移前创建的稿件。") + key = {"draft_id": draft["draft_id"], "revision": draft["revision"]} + empty = await result(client, "export_handwriting", **key, applied_experience_ids=[]) + first = await result(client, "export_handwriting", **key, + applied_experience_ids=[active, active, UNKNOWN]) + latest = await result(client, "export_handwriting", **key, applied_experience_ids=[active]) + assert "applications" not in await audit(client, active) + for _ in range(2): + async with isolated_session(binary, home) as (client, _): + apps = (await audit(client, active))["applications"] + assert apps["reported_exports"] == 2 + assert [r["export_id"] for r in apps["items"]] == [latest["export_id"], first["export_id"]] + assert report_rows(home) == { + empty["export_id"]: (*key.values(), 1, [], 0), + first["export_id"]: (*key.values(), 1, [active], 2), + latest["export_id"]: (*key.values(), 1, [active], 0), + } + return len(report_rows(home)) + + +async def run(binary, root, baseline=None, previous=None): home = root / "main" home.mkdir() async with isolated_session(binary, home) as (client, _): @@ -95,7 +129,6 @@ async def run(binary, root, baseline=None): zipped = await result(client, "export_handwriting", **key, format="zip") zipped_report = await result(client, "export_handwriting", **key, format="zip", applied_experience_ids=[active]) - from zipfile import ZipFile def pages(path): with ZipFile(path) as z: return [z.read(n) for n in z.namelist() if n.endswith(".png")] @@ -103,8 +136,9 @@ def pages(path): assert len(pages(zipped["path"])) == 1 async with isolated_session(binary, home) as (client, _): listings = (await client.list_tools()).tools - assert {x.name for x in listings} >= {"search_homework_experience", "export_handwriting"} - assert len(listings) == 19 + assert {x.name for x in listings} >= { + "read_homework_experience", "search_homework_experience", "export_handwriting", + } new_schema = next(x.inputSchema for x in listings if x.name == "export_handwriting") assert "applied_experience_ids" in new_schema["properties"] assert "applied_experience_ids" not in new_schema.get("required", []) @@ -115,6 +149,43 @@ def pages(path): for receipt, ids, ignored in pairs} lookup = await result(client, "search_homework_experience", tags=["homework"]) assert [r["rule_id"] for r in lookup["rules"]] == [active] + assert "applications" not in lookup["rules"][0] + first_read = await audit(client, active) + apps = first_read["applications"] + assert apps["basis"] == "host_report" and apps["reported_exports"] == 3 + assert apps["next_after"] is None + press_order = [filtered, old_revision, zipped_report] + assert [item["export_id"] for item in apps["items"]] == [ + receipt["export_id"] for receipt in reversed(press_order) + ] + assert all((r["draft_id"], r["revision"]) == tuple(key.values()) for r in apps["items"]) + for rule_id in (retired, pending, rejected): + assert (await audit(client, rule_id))["applications"] == { + "basis": "host_report", "reported_exports": 0, "items": [], "next_after": None, + } + + for _ in range(20): + press_order.append(await result(client, "export_handwriting", **key, + applied_experience_ids=[active, active])) + first_page = (await audit(client, active))["applications"] + assert first_page["reported_exports"] == 23 and len(first_page["items"]) == 20 + assert first_page["next_after"] == first_page["items"][-1]["seq"] + + # A new export before requesting page 2 must not shift the older page. + new = await result(client, "export_handwriting", **key, applied_experience_ids=[active]) + second = await audit(client, active, applications_after=first_page["next_after"]) + second_page = second["applications"] + assert second["cases"] == first_read["cases"] + assert second_page["reported_exports"] == 24 and second_page["next_after"] is None + assert [item["export_id"] for page in (first_page, second_page) for item in page["items"]] == [ + receipt["export_id"] for receipt in reversed(press_order) + ] + assert (await audit(client, active))["applications"]["items"][0]["export_id"] == new["export_id"] + cases_only = await audit(client, active, after=first_read["cases"][-1]["seq"]) + assert cases_only["cases"] == [] and cases_only["applications"]["reported_exports"] == 24 + await result(client, "retire_homework_experience", rule_id=active, reason="历史声明仍可查。") + assert (await audit(client, active))["applications"]["reported_exports"] == 24 + assert (await result(client, "search_homework_experience", tags=["homework"]))["rules"] == [] if baseline is not None: legacy = clone_home(home, "baseline") async with isolated_session(baseline, legacy) as (client, _): @@ -122,7 +193,9 @@ def pages(path): assert Path(old["path"]).read_bytes() == pdf and "experience_application" not in old response = await client.call_tool("export_handwriting", {**key, "applied_experience_ids": [active]}) assert response.isError - print(json.dumps({"confirmed_reports": len(rows), "pdf_sha256": hashlib.sha256(pdf).hexdigest(), + migrated = 0 if previous is None else await verify_legacy_migration(binary, previous, root / "previous") + print(json.dumps({"confirmed_reports": len(rows), "paged_adoptions": 23, "after_new_export": 24, + "migrated_reports": migrated, "pdf_sha256": hashlib.sha256(pdf).hexdigest(), "png_sha256": hashlib.sha256(pages(zipped["path"])[0]).hexdigest(), "legacy_comparison": baseline is not None})) @@ -131,6 +204,8 @@ def pages(path): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("binary", type=Path) parser.add_argument("--baseline", type=Path) + parser.add_argument("--previous", type=Path, help="Previous draft build with JSON report storage") args = parser.parse_args() with TemporaryDirectory() as tmp: - asyncio.run(run(args.binary.resolve(), Path(tmp), args.baseline and args.baseline.resolve())) + asyncio.run(run(args.binary.resolve(), Path(tmp), args.baseline and args.baseline.resolve(), + args.previous and args.previous.resolve())) From 0059f304b6eadd3fc3a1a923db6fd725ab101103 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Sun, 29 Nov 2026 17:04:53 +0800 Subject: [PATCH 3/4] =?UTF-8?q?refactor(crates/panache-mcp):=20=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E6=9C=AA=E5=8F=91=E5=B8=83=E7=9A=84=E9=87=87=E7=94=A8?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E8=BF=81=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:旧 JSON 列只存在于 #75 的早期草稿,main 尚未引入采用记录表。 解决手段:直接创建最终表和索引,把专项验证改为从已有稿件、交付和经验的 main 数据目录升级。 收益:减少正式版本不需要的数据库改表逻辑,并直接验证现有用户升级路径。 --- .../panache-mcp/src/experience/application.rs | 10 -- .../tests/experience_application.py | 91 ++++++++++--------- 2 files changed, 47 insertions(+), 54 deletions(-) diff --git a/crates/panache-mcp/src/experience/application.rs b/crates/panache-mcp/src/experience/application.rs index 27636fa9..b375b91c 100644 --- a/crates/panache-mcp/src/experience/application.rs +++ b/crates/panache-mcp/src/experience/application.rs @@ -29,16 +29,6 @@ pub(super) fn initialize(db: &Transaction<'_>) -> Result<()> { CREATE INDEX IF NOT EXISTS experience_applications_by_rule ON experience_applications(rule_id,seq,export_id);", )?; - // Preserve reports made by earlier builds of this draft, including explicit empty reports. - if db.column_exists(None, c"experience_application_reports", c"rule_ids")? { - db.execute_batch( - "INSERT INTO experience_applications(export_id,rule_id) - SELECT DISTINCT r.export_id, j.value - FROM experience_application_reports r, json_each(r.rule_ids) j - ORDER BY r.rowid, j.key; - ALTER TABLE experience_application_reports DROP COLUMN rule_ids;", - )?; - } Ok(()) } diff --git a/crates/panache-mcp/tests/experience_application.py b/crates/panache-mcp/tests/experience_application.py index 7df6a30c..0560c004 100644 --- a/crates/panache-mcp/tests/experience_application.py +++ b/crates/panache-mcp/tests/experience_application.py @@ -10,10 +10,10 @@ import json from pathlib import Path from tempfile import TemporaryDirectory +from zipfile import ZipFile from experience_visibility import delivered, result -from zipfile import ZipFile -from mcp_client import clone_home, isolated_session, open_db +from mcp_client import isolated_session, open_db UNKNOWN = "00000000-0000-4000-8000-000000000000" @@ -67,37 +67,48 @@ async def audit(client, rule_id, **cursor): return await result(client, "read_homework_experience", rule_id=rule_id, **cursor) -async def verify_legacy_migration(binary, previous, home): - home.mkdir() - async with isolated_session(previous, home) as (client, _): - active, _, _, _ = await seed(client) - draft = await result(client, "save_section", markdown="迁移前创建的稿件。") - key = {"draft_id": draft["draft_id"], "revision": draft["revision"]} - empty = await result(client, "export_handwriting", **key, applied_experience_ids=[]) - first = await result(client, "export_handwriting", **key, - applied_experience_ids=[active, active, UNKNOWN]) - latest = await result(client, "export_handwriting", **key, applied_experience_ids=[active]) - assert "applications" not in await audit(client, active) - for _ in range(2): - async with isolated_session(binary, home) as (client, _): - apps = (await audit(client, active))["applications"] - assert apps["reported_exports"] == 2 - assert [r["export_id"] for r in apps["items"]] == [latest["export_id"], first["export_id"]] - assert report_rows(home) == { - empty["export_id"]: (*key.values(), 1, [], 0), - first["export_id"]: (*key.values(), 1, [active], 2), - latest["export_id"]: (*key.values(), 1, [active], 0), - } - return len(report_rows(home)) - - -async def run(binary, root, baseline=None, previous=None): +async def run(binary, root, baseline=None): home = root / "main" home.mkdir() + if baseline is not None: + # Open the same populated directory first with main, then with the candidate. + async with isolated_session(baseline, home) as (client, _): + ids = await seed(client) + baseline_rule = await audit(client, ids[0]) + baseline_draft = await result( + client, "save_section", markdown="十二颗种子平均分四组。12 / 4 = 3。", + style={"homework": True, "seed": 141}, + ) + key = {"draft_id": baseline_draft["draft_id"], "revision": baseline_draft["revision"]} + receipt = await result(client, "export_handwriting", **key) + baseline_pdf = Path(receipt["path"]).read_bytes() + assert "experience_application" not in receipt and "applications" not in baseline_rule + response = await client.call_tool( + "export_handwriting", {**key, "applied_experience_ids": [ids[0]]}, + ) + assert response.isError + with open_db(home) as db: + assert not db.execute( + "SELECT name FROM sqlite_master WHERE name IN " + "('experience_application_reports', 'experience_applications')" + ).fetchall() + async with isolated_session(binary, home) as (client, _): - active, retired, pending, rejected = await seed(client) - draft = await result(client, "save_section", markdown="十二颗种子平均分四组。12 / 4 = 3。", - style={"homework": True, "seed": 141}) + active, retired, pending, rejected = ids if baseline is not None else await seed(client) + if baseline is not None: + upgraded_rule = await audit(client, active) + assert upgraded_rule.pop("applications") == { + "basis": "host_report", "reported_exports": 0, "items": [], "next_after": None, + } + assert upgraded_rule == baseline_rule and not report_rows(home) + with open_db(home) as db: + assert db.execute( + "SELECT draft,revision,published FROM export_files WHERE id=?", (receipt["export_id"],) + ).fetchone() == (key["draft_id"], key["revision"], 1) + draft = baseline_draft + else: + draft = await result(client, "save_section", markdown="十二颗种子平均分四组。12 / 4 = 3。", + style={"homework": True, "seed": 141}) key = {"draft_id": draft["draft_id"], "revision": draft["revision"]} old = await result(client, "export_handwriting", **key) assert "experience_application" not in old and not report_rows(home) @@ -115,6 +126,8 @@ async def run(binary, root, baseline=None, previous=None): assert not bad["experience_application"]["recorded"] assert bad["experience_application"]["ignored_count"] == len(args) pdf = Path(old["path"]).read_bytes() + if baseline is not None: + assert pdf == baseline_pdf assert all(Path(r["path"]).read_bytes() == pdf for r in (empty, filtered, bad)) wrong = await client.call_tool("export_handwriting", {**key, "revision": 999, "applied_experience_ids": [active]}) @@ -186,26 +199,16 @@ def pages(path): await result(client, "retire_homework_experience", rule_id=active, reason="历史声明仍可查。") assert (await audit(client, active))["applications"]["reported_exports"] == 24 assert (await result(client, "search_homework_experience", tags=["homework"]))["rules"] == [] - if baseline is not None: - legacy = clone_home(home, "baseline") - async with isolated_session(baseline, legacy) as (client, _): - old = await result(client, "export_handwriting", **key) - assert Path(old["path"]).read_bytes() == pdf and "experience_application" not in old - response = await client.call_tool("export_handwriting", {**key, "applied_experience_ids": [active]}) - assert response.isError - migrated = 0 if previous is None else await verify_legacy_migration(binary, previous, root / "previous") print(json.dumps({"confirmed_reports": len(rows), "paged_adoptions": 23, "after_new_export": 24, - "migrated_reports": migrated, "pdf_sha256": hashlib.sha256(pdf).hexdigest(), + "pdf_sha256": hashlib.sha256(pdf).hexdigest(), "png_sha256": hashlib.sha256(pages(zipped["path"])[0]).hexdigest(), - "legacy_comparison": baseline is not None})) + "upgraded_from_main": baseline is not None})) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("binary", type=Path) - parser.add_argument("--baseline", type=Path) - parser.add_argument("--previous", type=Path, help="Previous draft build with JSON report storage") + parser.add_argument("--baseline", type=Path, help="Main build used to create a populated pre-feature database") args = parser.parse_args() with TemporaryDirectory() as tmp: - asyncio.run(run(args.binary.resolve(), Path(tmp), args.baseline and args.baseline.resolve(), - args.previous and args.previous.resolve())) + asyncio.run(run(args.binary.resolve(), Path(tmp), args.baseline and args.baseline.resolve())) From 48ff287e0d9fc001d6c29c1c17e0f276b3100d9f Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Sun, 29 Nov 2026 17:33:47 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(app/test):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E7=B2=BE=E7=BB=86=E7=BC=96=E8=BE=91=E9=A2=84=E8=A7=88=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=E7=9A=84=E5=BC=95=E6=93=8E=E6=A8=A1=E6=8B=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:测试初始化时读取引擎能力,模拟版本回执遗漏精细编辑支持,预览请求因而缺少排版键。 解决手段:由模拟引擎声明精细编辑能力,继续断言请求只带旧稿排版键,并完成模拟预览响应。 收益:回归测试走完正常预览流程,同一个模拟问题不再阻断三平台的相关 CI。 --- app/test/workspace_test.dart | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/app/test/workspace_test.dart b/app/test/workspace_test.dart index 247e7a9b..ef95a2de 100644 --- a/app/test/workspace_test.dart +++ b/app/test/workspace_test.dart @@ -27,7 +27,8 @@ class MemoryStorage implements WorkspaceStorage { } class ControlledApi extends HandwritingApi { - ControlledApi() : super('http://example.invalid'); + ControlledApi({this.fineEdit = false}) : super('http://example.invalid'); + final bool fineEdit; final submission = Completer(); Map? submittedFields; final rendered = Completer>(); @@ -36,8 +37,12 @@ class ControlledApi extends HandwritingApi { @override bool get supportsCancel => true; @override - Future getJson(String path) async => - path == '/api/fonts_info' ? ['test.ttf'] : {'version': 'test'}; + Future getJson(String path) async => path == '/api/fonts_info' + ? ['test.ttf'] + : { + 'version': 'test', + 'capabilities': {'fine_edit': fineEdit}, + }; @override Future submit( Map fields, @@ -243,28 +248,24 @@ void main() { 'fineEdits': { 'key': key, 'glyphs': [ - { - 'id': 1, - 'dx': 4, - 'dy': 0, - 'scale': 100, - 'angle': 0, - 'opacity': 100, - }, + {'id': 1, 'dx': 4, 'dy': 0, 'scale': 100, 'angle': 0, 'opacity': 100}, ], }, }); - final api = ControlledApi()..supportsFineEdit = true; + final api = ControlledApi(fineEdit: true); final w = Workspace(api: api, storage: storage); addTearDown(w.dispose); await w.initialize(); final preview = w.generate(); + expect(api.submittedFields?['fine_edit'], 'true'); expect(jsonDecode(api.submittedFields!['fine_edits']!), { 'key': key, 'glyphs': [], }); api.submission.complete('preview-task'); + await api.previewRequested.future; + api.rendered.complete([]); expect(await preview, isTrue); });