diff --git a/CHANGELOG.md b/CHANGELOG.md index 867d2287..7073b267 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## 未发布 +- MCP 导出时可选记录宿主实际采用的作业经验 ID,便于按交付文件区分「查到」和「声明用过」。按经验 ID 可查宿主自报的采用次数和最近的交付版本,不代表经验有效。 - 照片稿整页复查在有可比纸面线索时提示查找适用的新增墨迹控制,缺少纸面投影时明确说明原因。 - 已建立纸面投影的照片稿可在 MCP 中选择让新增笔迹随局部纸色调整,或按原照上的两个点渐变柔化。两项默认关闭,不改动底纸,适用于预览及 PDF 和 PNG 导出。 - 修复已有精细编辑的稿件在表格避让更新后静默移位或换页;旧稿继续使用原布局,新稿仍按表格避让排版。 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); }); diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index f90f46bf..5a7847d7 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -246,6 +246,10 @@ 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` 关联到确切稿件和版本;它不改成稿、经验状态或检索排序,也不能证明经验带来了收益。 + +已知经验 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 936d30c0..57cb82a2 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)] @@ -13,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, @@ -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) } @@ -90,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)] @@ -474,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 new file mode 100644 index 00000000..b375b91c --- /dev/null +++ b/crates/panache-mcp/src/experience/application.rs @@ -0,0 +1,136 @@ +//! Optional host declarations, separate from rule evidence and ranking. +use anyhow::Result; +use rusqlite::{Transaction, 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: &Transaction<'_>) -> Result<()> { + db.execute_batch( + "CREATE TABLE IF NOT EXISTS experience_application_reports( + 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);", + )?; + 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: &Transaction<'_>, 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,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; + } + } + 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..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, @@ -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..d11858eb 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,105 @@ 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(()) +} + +#[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 new file mode 100644 index 00000000..0560c004 --- /dev/null +++ b/crates/panache-mcp/tests/experience_application.py @@ -0,0 +1,214 @@ +# /// 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 zipfile import ZipFile + +from experience_visibility import delivered, result +from mcp_client import 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: + 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 audit(client, rule_id, **cursor): + return await result(client, "read_homework_experience", rule_id=rule_id, **cursor) + + +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 = 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) + 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() + 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]}) + 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]) + 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} >= { + "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", []) + 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] + 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"] == [] + print(json.dumps({"confirmed_reports": len(rows), "paged_adoptions": 23, "after_new_export": 24, + "pdf_sha256": hashlib.sha256(pdf).hexdigest(), + "png_sha256": hashlib.sha256(pages(zipped["path"])[0]).hexdigest(), + "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, 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()))