diff --git a/CHANGELOG.md b/CHANGELOG.md index b84468a9..2ea1959c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## 未发布 +- MCP 新检查单记录首次入档时的稿件版本,历史查单会说明单据能证明的先后关系。 +- MCP 调参兼容直接指定控件或按控件组提交。 +- 可用 `PANACHE_MCP_PRESERVE_REVIEWS=1` 在改稿和打印期间保留原有检查记录。 +- MCP 在多节稿件的逐页复盘中提示节号和节内页码,方便从中断处继续核对。 +- MCP 可按稿件版本、节号和页码只读找回已存的整页复盘;缺少记录时明确返回空结果。 +- MCP 客户端指南增加只翻旧检查记录的工具选择和调用示例。 +- MCP 查旧检查单时可按新增原文定位上一版,并按该版实际排版查询指定节的末页。 +- MCP 在作业和实验报告的笔迹建议中区分松散笔迹与偶发涂改,指明对应调节项和预览方法。 + ## v1.21.0 (2026-11-24) - 在「关于与反馈 → 支持作者」可查看随应用提供的微信赞赏码。官网首页也可直接扫码支持 Simon。 diff --git a/crates/handwriting-core/src/fine_edit.rs b/crates/handwriting-core/src/fine_edit.rs index b2ef0b75..41c0ade5 100644 --- a/crates/handwriting-core/src/fine_edit.rs +++ b/crates/handwriting-core/src/fine_edit.rs @@ -52,7 +52,7 @@ pub fn inspect_page( return Err(Error::new("invalid_parameter", "Invalid fine edit page")); } let mut geometry = None; - crate::render::render_pages(request, cancel, page, |i, _, ink| { + let pages = crate::render::render_pages(request, cancel, page, |i, _, ink| { if i + 1 == page && let Some(crate::render::PageInk::Fine(tiles)) = ink { @@ -73,7 +73,12 @@ pub fn inspect_page( })?; Ok(( document_key(&request.text, &request.params), - geometry.ok_or_else(|| Error::new("invalid_page", "Page not found"))?, + geometry.ok_or_else(|| { + Error::new( + "invalid_page", + format!("Page {page} not found; available page count: {pages}"), + ) + })?, )) } diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index 74c60587..4acf4d45 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -292,6 +292,11 @@ pub(crate) fn render_output Result<()>>( }) } +/// Run the normal pagination pass, discarding each page before compositing or encoding. +pub fn count_pages(request: &RenderRequest, cancel: &Cancellation) -> Result { + render_pages(request, cancel, usize::MAX, |_, _, _| Ok(())) +} + pub(crate) fn render_pages( r: &RenderRequest, cancel: &Cancellation, diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 35739a2b..78535f34 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -57,8 +57,8 @@ cargo build --locked --release -p panache-mcp | `list_drafts` | 找回本地稿件和最新版本。每批 20 条,可传 `offset`。 | | `read_section` | `summary` 取版本、长度和样式;默认 `excerpt` 隐去正文中已识别的内嵌图片数据;`source` 读取精确 Markdown。后两种视图按字符分页,默认 1000 字,单次最多 4000 字。 | | `preview_handwriting` | 默认返回首页 PNG。用 `section`、`page` 查看指定节中的一页,两者从 1 开始。 | -| `export_handwriting` | 按节顺序导出整份稿件,返回绝对路径、版本和实际页数。格式可选 `pdf` 或 `zip`,ZIP 从 `0.png` 开始编号。 | -| `describe_controls` | 先列参数组,再按 `group` 查看单位、范围和枚举值。附上 `draft_id` 和 `revision` 可读取该版的实际值。 | +| `export_handwriting` | 按节顺序导出整份稿件,返回绝对路径、版本和实际页数。格式可选 `pdf` 或 `zip`,ZIP 从 `0.png` 开始编号。导出结果的 `review.unreviewed_pages` 按打印顺序列出缺少整页复盘的 `section`、`page`。将这些坐标与导出的版本号传给 `preview_handwriting(view="review")` 可逐张补看。 | +| `describe_controls` | 调参时可将参数直接放在 `changes` 内,也可写成 `{"changes":{"variation":{"perturb_theta_sigma":0.07}}}`。先列参数组,再按 `group` 查看单位、范围和枚举值。附上 `draft_id` 和 `revision` 可读取该版的实际值。 | | `tune_handwriting` | 可在原稿上更新参考线、导入本机字体,并一次提交多项全稿参数,如 `{"ink_opacity":85,"word_spacing":2}`。`null` 恢复建稿时的设置。 | | `storage_usage` | 查询目录和逐稿用量,以及当前预算。 | | `plan_cleanup` | 按稿列出废弃临时文件和受保护的已交付导出。 | @@ -66,12 +66,20 @@ cargo build --locked --release -p panache-mcp | `annotate_review` | 将用户原话或模型观察挂到指定复盘 ID,保持稿件版本号。 | | `adjust_glyphs` | 先用 `preview_handwriting(view="layout")` 取编号和坐标,再按同一节、页和版本调整选中字形。 | +若本次只改稿、打印和统计缺单页,可在客户端的 MCP 服务配置中设置 `PANACHE_MCP_PRESERVE_REVIEWS=1`。该连接仍可正常调参、看图和导出,完整检查单与评语会保留原样。 + 例如用 `list_fonts(query="楷", source="system", limit=8)` 检索系统字体。把 `entries[].id` 用于建稿的 `style.font` 或调稿的 `changes.font`。随包字体继续接受原文件名。个人和系统字体会随稿保存,删除源文件后仍可预览历史版本。TTF、OTF 和 TTC/OTC 中带轮廓、单个字面大小不超过 32 MiB 的字体可供选择。 桌面与 MCP 共享“我的字体”目录,`list_fonts` 的 `user_dir` 给出绝对路径。Windows 使用 `%LOCALAPPDATA%/Panache/fonts`,macOS 使用 `~/Library/Application Support/Panache/fonts`,Linux 使用 `$XDG_DATA_HOME/Panache/fonts`(默认 `~/.local/share/Panache/fonts`)。可通过 `PANACHE_USER_FONT_DIR` 指定绝对路径。把字体放入后调用 `list_fonts(source="user", refresh=true)`。 面向 AI 客户端的调用示例、披露边界和测量口径见[工具设计](tool-design.md)。 +查归属某版、某节、某一页的整页复盘,可用 `read_section(view="review", revision=3, section=2, page=1, draft_id=…)`。返回最近记录在这个位置的测量值、原检查单编号及注明来源的评语。该位置没有记录时返回 `status="no_recorded_review"`;直接按数字页码查单不会排版,也不判断该页是否实际存在。已知检查单编号时仍可按 `review_id` 精确读取。 + +如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复或同节删后重加时,结果列出最早两个加入时点及对应的前一版。可查的正文节附有简短开头,便于区分补记所在节和实际要查的节。请用户选择,也可分版回答。按补记或末页查多节稿时需明确待查节号。无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。单据的 `revision` 表示受检版本,`filed_at_revision` 表示首次入档时稿件的最新版本。旧库没有保存这一信息的单据返回 `null`。回答“补记前验过吗”时请同时转述 `receipt_summary` 中的时间结论。 + +预览的页码在每一节内从 1 开始。翻过一节末页时,错误信息给出这节的实际页数,以及所查版本中下一节的起始页;历史版本已到末节时会提示到此为止。 + 长作业可以按题组或章节分次传入,每节从新页开始。需要连续排版的段落放在同一节,公式、表格、代码块也应完整放在一节内。追加时带上 `draft_id` 和上次返回的 `expected_revision`;修改已有节时再给出 `section`。另一位客户端抢先保存后,用 `read_section` 复核最新内容再提交。 每次保存只转换这一节,Markdown 原文和整理结果存入本地 SQLite。预览某节第 N 页时,引擎从该节开头排到第 N 页,只编码选中的一页。进程内保留最近生成的四张预览,修改其他节仍可复用。预览和导出传相同的 `revision` 可锁定稿件。种子和样式随稿保存,复现时需使用相同字体和引擎。 diff --git a/crates/panache-mcp/src/controls.json b/crates/panache-mcp/src/controls.json index 5c3e7365..7ff757f5 100644 --- a/crates/panache-mcp/src/controls.json +++ b/crates/panache-mcp/src/controls.json @@ -42,14 +42,14 @@ "word_spacing_sigma": {"type":"number","min":0,"max":100,"unit":"px"}, "perturb_x_sigma": {"type":"number","min":0,"max":100,"unit":"px"}, "perturb_y_sigma": {"type":"number","min":0,"max":100,"unit":"px"}, - "perturb_theta_sigma": {"type":"number","min":0,"max":3.14,"unit":"rad"}, + "perturb_theta_sigma": {"type":"number","min":0,"max":3.14,"unit":"rad","description":"Variation in glyph tilt. For a slightly hurried hand keep the font and seed; try increasing the current value by 0.02 rad, then preview the same line and check digits, units and alignment. perturb_x_sigma and perturb_y_sigma vary position in paper-space pixels."}, "ink_depth_sigma": {"type":"number","min":0,"max":255,"unit":"intensity"} }, "strike": { - "strikethrough_probability": {"type":"number","min":0,"max":1,"unit":"probability"}, + "strikethrough_probability": {"type":"number","min":0,"max":1,"unit":"probability","description":"For requested occasional corrections: randomly insert a crossed-out extra character before the intended text when monospaced=false. Try 0.005 for a sparse sample; a short page may have none. Compare the same line with only probability changed; confirm a visible crossed-out character before reporting one. Check reflow and numbers. For a looser hand alone, leave this unchanged. Exact placement on a chosen word is unsupported; Markdown ~~text~~ is stripped to text."}, "strikethrough_width": {"type":"number","min":0,"max":100,"unit":"px"}, "strikethrough_length_sigma": {"type":"number","min":0,"max":100,"unit":"px"}, "strikethrough_width_sigma": {"type":"number","min":0,"max":100,"unit":"px"}, - "strikethrough_angle_sigma": {"type":"number","min":0,"max":3.14,"unit":"rad"} + "strikethrough_angle_sigma": {"type":"number","min":0,"max":3.14,"unit":"deg"} } } diff --git a/crates/panache-mcp/src/controls.rs b/crates/panache-mcp/src/controls.rs index 592250f8..724e5b8e 100644 --- a/crates/panache-mcp/src/controls.rs +++ b/crates/panache-mcp/src/controls.rs @@ -13,6 +13,33 @@ pub fn catalog() -> &'static Changes { }) } +/// Normalize catalog groups at the input boundary. A scalar control (e.g. ink) +/// can share its name with a group; only an object selects the grouped syntax. +pub fn flatten_patch(changes: Changes) -> Result { + let mut patch = Changes::new(); + for (key, value) in changes { + if let (Some(group), Value::Object(fields)) = (catalog().get(&key), &value) { + ensure!(!fields.is_empty(), "Empty control group {key}"); + for (field, setting) in fields { + ensure!( + group.get(field).is_some(), + "Unknown control {field} in group {key}" + ); + ensure!( + patch.insert(field.clone(), setting.clone()).is_none(), + "Duplicate control {field}" + ); + } + } else { + ensure!( + patch.insert(key.clone(), value).is_none(), + "Duplicate control {key}" + ); + } + } + Ok(patch) +} + pub fn merge(current: &Changes, patch: &Changes, fonts: &[String]) -> Result { ensure!(!patch.is_empty(), "Supply at least one control"); let mut next = current.clone(); diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 7d22c236..35b69d8c 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -44,6 +44,7 @@ fn concurrent_first_opens_share_a_complete_schema() -> Result<()> { } pub struct Snapshot<'a> { + pub latest_revision: u32, pub revision: u32, pub style: Style, pub controls: crate::controls::Changes, @@ -55,6 +56,59 @@ pub struct Snapshot<'a> { } impl Snapshot<'_> { + pub fn review_section(&self, requested: Option) -> Result { + if let Some(section) = requested { + ensure!(section > 0, "section starts at 1"); + let exists: bool = self.drafts.connect()?.query_row( + "SELECT EXISTS(SELECT 1 FROM sections WHERE draft=? AND number=? AND revision<=?)", + params![self.id, section, self.revision], + |row| row.get(0), + )?; + ensure!( + exists, + "第 {} 版还没有第 {section} 节。请保留所查版本和页码,按待查正文选择已有的节:{}", + self.revision, + self.drafts + .review_section_choices(self.id, self.revision)? + .join(" · ") + ); + return Ok(section); + } + let choices = self.drafts.review_section_choices(self.id, self.revision)?; + ensure!( + choices.len() == 1, + "请按待查的正文选择 section。第 {} 版可查的节:{}", + self.revision, + choices.join(" · ") + ); + Ok(1) + } + + pub fn page_error(&self, section: u32, mut error: handwriting_core::Error) -> anyhow::Error { + if error.code != "invalid_page" { + return error.into(); + } + let next = self.drafts.connect().and_then(|db| { + Ok(db.query_row( + "SELECT MIN(number) FROM sections WHERE draft=? AND number>? AND revision<=?", + params![self.id, section, self.revision], + |row| row.get::<_, Option>(0), + )?) + }); + let hint = match next { + Ok(Some(next)) => { + format!("To continue after this section, use section={next}, page=1.") + } + Ok(None) => "This is the last section at this revision.".to_owned(), + Err(_) => "Check the available sections before continuing.".to_owned(), + }; + error.message = format!( + "{} (revision {}, section {section}). Pages start at 1 within each section. {hint}", + error.message, self.revision + ); + error.into() + } + pub fn has_font(&self, handle: &str) -> Result { Ok(self.drafts.connect()?.query_row( "SELECT EXISTS(SELECT 1 FROM draft_fonts WHERE draft=? AND handle=?)", @@ -308,6 +362,104 @@ impl Drafts { .collect::>>()?; Ok(json!({"drafts":entries,"offset":offset})) } + // Bound the source prefix in SQLite, including when a section starts with an inline photo. + fn review_section_choices(&self, id: &str, revision: u32) -> Result> { + let db = self.connect()?; + let mut stmt = db.prepare( + "SELECT number, substr(source,1,48) FROM sections JOIN ( + SELECT number, max(revision) AS revision FROM sections + WHERE draft=?1 AND revision<=?2 GROUP BY number ORDER BY number LIMIT 5 + ) USING(number,revision) WHERE draft=?1 ORDER BY number", + )?; + let mut choices = Vec::new(); + let mut rows = stmt.query(params![id, revision])?; + while let Some(row) = rows.next()? { + if choices.len() == 4 { + choices.push("其余节可用 view=excerpt 查阅".to_owned()); + break; + } + let number: u32 = row.get(0)?; + let prefix: String = row.get(1)?; + let before_image = prefix + .find("![") + .into_iter() + .chain(prefix.find("data:")) + .min() + .unwrap_or(prefix.len()); + let text = prefix[..before_image] + .split_whitespace() + .collect::>() + .join(" "); + choices.push(format!("section={number} {}", json!(text))); + } + Ok(choices) + } + + /// Find a single transition from absent to present across all versions of all sections. + pub fn text_introduction(&self, id: &str, text: &str) -> Result<(u32, u32)> { + ensure!( + !text.trim().is_empty() && text.chars().count() <= 160, + "before_text needs 1..160 characters from the saved Markdown" + ); + let db = self.connect()?; + let mut statement = db.prepare( + "WITH versions AS ( + SELECT number,revision,instr(source,?2)>0 AS present + FROM sections WHERE draft=?1 + ), changes AS ( + SELECT number,revision,present, + lag(present,1,0) OVER (PARTITION BY number ORDER BY revision) AS previously_present + FROM versions + ) + SELECT number,revision FROM changes WHERE present AND NOT previously_present + ORDER BY revision,number LIMIT 3", + )?; + let matches = statement + .query_map(params![id, text], |row| { + Ok((row.get::<_, u32>(0)?, row.get::<_, u32>(1)?)) + })? + .collect::>>()?; + let &(section, revision) = matches.first().context( + "No section contains before_text. Read the source for a literal fragment or specify a revision." + )?; + if matches.len() > 1 { + let mut message = String::from( + "这段原文有多个加入时点。请让用户确认是首次加入之前,还是后来再次加入之前;也可分别核对并逐版列出,未确认时不要代选。", + ); + let same_section = matches[0].0 == matches[1].0; + for (number, added) in matches.iter().take(2) { + if same_section { + message.push_str(&format!("\n第 {added} 版加入了这段原文。")); + } else { + message.push_str(&format!("\n第 {added} 版在第 {number} 节加入了这段原文。")); + } + if *added == 1 { + message.push_str("这是初稿,之前没有稿件。"); + } else { + let before = added - 1; + let choices = self.review_section_choices(id, before)?; + message.push_str(&format!( + "加入前查 revision={before};该版可查的正文:{}", + choices.join(" · ") + )); + } + } + if matches.len() > 2 { + message.push_str( + "\n这里只列最早两次,另有加入时点。可通过 trajectory 和 source 核对。", + ); + } + anyhow::bail!( + "{message}\n所补文字只用来认版本。请按用户要查的正文选择 section,保留 page,移除 before_text 后按明确版本查单。" + ); + } + ensure!( + revision > 1, + "before_text already occurs in the first revision; no earlier draft exists." + ); + Ok((section, revision)) + } + pub fn snapshot<'a>(&'a self, id: &'a str, requested: Option) -> Result> { let (latest, style, layout): (u32, String, Option) = self .connect()? @@ -339,6 +491,7 @@ impl Drafts { "SELECT layout FROM paper_layouts WHERE draft=? AND revision<=? ORDER BY revision DESC LIMIT 1", params![id,revision], |r| r.get(0)).optional()?; Ok(Snapshot { + latest_revision: latest, controls, settings_revision, layout_revision, diff --git a/crates/panache-mcp/src/drafts/observations.rs b/crates/panache-mcp/src/drafts/observations.rs index 39c17476..1fb32447 100644 --- a/crates/panache-mcp/src/drafts/observations.rs +++ b/crates/panache-mcp/src/drafts/observations.rs @@ -11,6 +11,7 @@ pub(super) fn initialize(db: &mut Connection) -> Result<()> { seq INTEGER PRIMARY KEY, review_id TEXT NOT NULL UNIQUE, draft TEXT NOT NULL, revision INTEGER NOT NULL, section INTEGER NOT NULL, page INTEGER NOT NULL, algorithm TEXT, pixel_sha256 TEXT, content_sha256 TEXT, evidence TEXT NOT NULL, + filed_at_revision INTEGER, UNIQUE(draft,revision,section,page,algorithm,pixel_sha256) ); CREATE INDEX IF NOT EXISTS reviews_by_page ON review_observations(draft,revision,section,page,seq); @@ -18,6 +19,9 @@ pub(super) fn initialize(db: &mut Connection) -> Result<()> { review_id TEXT NOT NULL REFERENCES review_observations(review_id), origin TEXT NOT NULL, note TEXT NOT NULL, UNIQUE(review_id,origin,note) );")?; + if !tx.column_exists(None, "review_observations", "filed_at_revision")? { + tx.execute_batch("ALTER TABLE review_observations ADD COLUMN filed_at_revision INTEGER")?; + } if tx.table_exists(None, "page_reviews")? { // Older observations did not retain a pixel digest or measurement version. tx.execute_batch("INSERT INTO review_observations(review_id,draft,revision,section,page,evidence) @@ -29,13 +33,13 @@ pub(super) fn initialize(db: &mut Connection) -> Result<()> { } fn by_id(db: &Connection, id: &str, draft: &Snapshot<'_>) -> Result { - let mut record=db.query_row("SELECT revision,section,page,algorithm,pixel_sha256,content_sha256,evidence + let mut record=db.query_row("SELECT revision,section,page,algorithm,pixel_sha256,content_sha256,evidence,filed_at_revision FROM review_observations WHERE draft=? AND review_id=? AND revision<=?", params![draft.id,id,draft.revision],|r|Ok(json!({ "draft_id":draft.id,"review_id":id,"origin":"measurement","revision":r.get::<_,u32>(0)?, "section":r.get::<_,u32>(1)?,"page":r.get::<_,u32>(2)?,"algorithm":r.get::<_,Option>(3)?, "pixel_sha256":r.get::<_,Option>(4)?,"page_content_sha256":r.get::<_,Option>(5)?, - "evidence":r.get::<_,String>(6)?, + "evidence":r.get::<_,String>(6)?, "filed_at_revision":r.get::<_,Option>(7)?, }))).optional()?.context("Unknown review in this draft and revision range")?; record["evidence"] = serde_json::from_str( record["evidence"] @@ -56,6 +60,24 @@ fn by_id(db: &Connection, id: &str, draft: &Snapshot<'_>) -> Result { Ok(record) } +fn page_record( + db: &Connection, + draft: &Snapshot<'_>, + revision: u32, + section: u32, + page: u32, +) -> Result> { + let id: Option = db + .query_row( + "SELECT review_id FROM review_observations + WHERE draft=? AND revision=? AND section=? AND page=? ORDER BY seq DESC LIMIT 1", + params![draft.id, revision, section, page], + |row| row.get(0), + ) + .optional()?; + id.map(|id| by_id(db, &id, draft)).transpose() +} + impl Snapshot<'_> { pub fn record_review( &self, @@ -69,9 +91,9 @@ impl Snapshot<'_> { let page = u32::try_from(page)?; let mut db = self.drafts.connect()?; let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; - tx.execute("INSERT INTO review_observations(review_id,draft,revision,section,page,algorithm,pixel_sha256,content_sha256,evidence) - VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT(draft,revision,section,page,algorithm,pixel_sha256) DO NOTHING", - params![Uuid::new_v4().to_string(),self.id,self.revision,section,page,algorithm,pixel,content,evidence.to_string()])?; + tx.execute("INSERT INTO review_observations(review_id,draft,revision,section,page,algorithm,pixel_sha256,content_sha256,evidence,filed_at_revision) + VALUES(?,?,?,?,?,?,?,?,?,(SELECT revision FROM drafts WHERE id=?)) ON CONFLICT(draft,revision,section,page,algorithm,pixel_sha256) DO NOTHING", + params![Uuid::new_v4().to_string(),self.id,self.revision,section,page,algorithm,pixel,content,evidence.to_string(),self.id])?; let id:String=tx.query_row("SELECT review_id FROM review_observations WHERE draft=? AND revision=? AND section=? AND page=? AND algorithm=? AND pixel_sha256=?", params![self.id,self.revision,section,page,algorithm,pixel],|r|r.get(0))?; @@ -84,12 +106,33 @@ impl Snapshot<'_> { by_id(&self.drafts.connect()?, id, self) } - pub fn review_counts(&self) -> Result<(u32, u32)> { - Ok(self.drafts.connect()?.query_row("SELECT count(*), - count(CASE WHEN json_extract(evidence,'$.visibility') IN ('no_visible_change','very_low_contrast') THEN 1 END) - FROM review_observations WHERE seq IN (SELECT max(seq) FROM review_observations - WHERE draft=? AND revision=? GROUP BY section,page)",params![self.id,self.revision], - |r|Ok((r.get(0)?,r.get(1)?)))?) + pub fn page_observation(&self, section: u32, page: u32) -> Result { + ensure!(section > 0 && page > 0, "section and page start at 1"); + let mut db = self.drafts.connect()?; + let tx = db.transaction()?; + let record = page_record(&tx, self, self.revision, section, page)?; + Ok(record.unwrap_or_else(|| { + json!({ + "draft_id": self.id, "revision": self.revision, "section": section, "page": page, + "review_id": null, "status": "no_recorded_review", + }) + })) + } + + /// Latest full-page visibility flag for each measured page in this revision. + pub fn reviewed_pages(&self) -> Result> { + let db = self.drafts.connect()?; + let mut statement = db.prepare( + "SELECT section, page, COALESCE(json_extract(evidence,'$.visibility') + IN ('no_visible_change','very_low_contrast'), 0) + FROM review_observations WHERE seq IN (SELECT max(seq) FROM review_observations + WHERE draft=? AND revision=? GROUP BY section,page)", + )?; + Ok(statement + .query_map(params![self.id, self.revision], |row| { + Ok(((row.get(0)?, row.get::<_, u32>(1)? as usize), row.get(2)?)) + })? + .collect::>()?) } pub fn compare_reviews( @@ -110,19 +153,9 @@ impl Snapshot<'_> { ); let mut db = self.drafts.connect()?; let tx = db.transaction()?; - let fetch = |rev: u32| -> Result> { - let id: Option = tx - .query_row( - "SELECT review_id FROM review_observations - WHERE draft=? AND revision=? AND section=? AND page=? ORDER BY seq DESC LIMIT 1", - params![self.id, rev, section, u32::try_from(page)?], - |r| r.get(0), - ) - .optional()?; - id.map(|v| by_id(&tx, &v, self)).transpose() - }; - let previous = fetch(before)?; - let current = fetch(self.revision)?; + let page = u32::try_from(page)?; + let previous = page_record(&tx, self, before, section, page)?; + let current = page_record(&tx, self, self.revision, section, page)?; let mut stmt=tx.prepare("WITH actions(rev,action,section) AS ( SELECT revision,'save_section',number FROM sections WHERE draft=?1 UNION ALL SELECT revision,'tune_handwriting',NULL FROM settings WHERE draft=?1 @@ -252,10 +285,13 @@ mod tests { && legacy["pixel_sha256"].is_null() && legacy["page_content_sha256"].is_null() ); + assert!(legacy["filed_at_revision"].is_null()); assert_eq!(legacy["evidence"]["visibility"], "no_visible_change"); + assert_eq!(old.page_observation(1, 1)?, legacy); let observation = json!({"visibility":"inspect_visually","photo_size":[400,500]}); let rev2 = drafts.snapshot("d", Some(2))?; let first = rev2.record_review(1, 1, "a", "pixels", "content", &observation)?; + assert_eq!(first["filed_at_revision"], 3); for _ in 0..9 { assert_eq!( rev2.record_review(1, 1, "a", "pixels", "content", &observation)?, @@ -281,7 +317,9 @@ mod tests { )?; assert_ne!(first["review_id"], changed["review_id"]); assert_ne!(changed["review_id"], upgraded["review_id"]); - assert_eq!(rev2.review_counts()?, (1, 1)); + assert_eq!(rev2.page_observation(1, 1)?, upgraded); + assert_eq!(old.page_observation(1, 1)?, legacy); + assert_eq!(rev2.reviewed_pages()?, [((1, 1), true)].into()); let rev3 = drafts.snapshot("d", Some(3))?; rev3.record_review(1, 1, "a", "pixels", "content", &observation)?; let comparison = rev3.compare_reviews(2, 1, 1, 0, 5)?; @@ -296,6 +334,20 @@ mod tests { .unwrap() .contains(&json!("unknown_algorithm")) ); + drafts + .connect()? + .execute("UPDATE drafts SET revision=4 WHERE id='d'", [])?; + assert_eq!( + rev2.record_review(1, 1, "a", "pixels", "content", &observation)?, + first + ); + // Reopening an existing digest from an older database must not date it retroactively. + drafts.connect()?.execute( + "UPDATE review_observations SET filed_at_revision=NULL WHERE review_id=?", + [changed["review_id"].as_str().unwrap()], + )?; + let changed = rev2.record_review(1, 1, "a", "other-pixels", "content", &observation)?; + assert!(changed["filed_at_revision"].is_null()); for record in [first, changed, upgraded, legacy] { let reopened = Drafts::open(home.path())?; assert_eq!( diff --git a/crates/panache-mcp/src/drafts/trajectory.rs b/crates/panache-mcp/src/drafts/trajectory.rs index 17e3d7ce..e89aea67 100644 --- a/crates/panache-mcp/src/drafts/trajectory.rs +++ b/crates/panache-mcp/src/drafts/trajectory.rs @@ -116,7 +116,9 @@ impl Drafts { let more = entries.len() > limit as usize; entries.truncate(limit as usize); let next_offset = page.offset.checked_add(limit).filter(|_| more); - let mut result = json!({"draft_id":page.draft_id,"revision":page.revision,"events":entries,"next_offset":next_offset}); + let mut result = json!({"draft_id":page.draft_id,"revision":page.revision,"events":entries,"next_offset":next_offset, + "event_order":"reviewed_or_edited_revision_desc", + "order_note":"检查单和评语按受检稿件版本排列。要判断何时开单,请按 review_id 查原单的 filed_at_revision;旧单可能缺少这项记录。"}); if let Some(offset) = next_offset { page.offset = offset; result["next_cursor"] = json!(URL_SAFE_NO_PAD.encode(serde_json::to_vec(&page)?)); diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index d92bb5aa..7ad34d4f 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -194,8 +194,15 @@ impl Engine { } Ok(()) })?; - let png = - image.with_context(|| format!("Section has {pages} pages; requested {page_number}"))?; + let png = image.ok_or_else(|| { + draft.page_error( + n, + handwriting_core::Error::new( + "invalid_page", + format!("Section has {pages} pages; requested {page_number}"), + ), + ) + })?; let preview = RenderedPreview { png, fine_edit: request.params.fine_edit, @@ -244,6 +251,25 @@ impl Engine { None => handwriting_core::render::render_until_page(request, cancel, stop, emit), } } + pub fn page_count( + &mut self, + draft: &Snapshot<'_>, + section: Section, + cancel: &Cancellation, + ) -> Result { + let (_, edits) = draft.edits(§ion)?; + // Projected photos are laid out in rectified paper space. Their final photo composite does not paginate. + let background = if draft.paper.as_ref().is_some_and(|p| p.projection.is_some()) { + None + } else { + draft.background()? + }; + let req = self.request(draft, section, background, edits)?; + Ok(u32::try_from(handwriting_core::render::count_pages( + &req, cancel, + )?)?) + } + fn fine_request(&mut self, draft: &Snapshot<'_>, section: Section) -> Result { let (_, edits) = draft.edits(§ion)?; let projected = draft.paper.as_ref().is_some_and(|p| p.projection.is_some()); @@ -259,9 +285,11 @@ impl Engine { page: usize, cancel: &Cancellation, ) -> Result { + let number = section.number; let source_revision = section.version; let req = self.fine_request(draft, section)?; - let (_, glyphs) = fine_edit::inspect_page(&req, page, cancel)?; + let (_, glyphs) = fine_edit::inspect_page(&req, page, cancel) + .map_err(|error| draft.page_error(number, error))?; let edits = req .params .fine_edits @@ -319,7 +347,8 @@ impl Engine { let page = input.page.unwrap_or(1); let number = section.number; let req = self.fine_request(draft, section)?; - let (_, mut bounds) = fine_edit::inspect_page(&req, page, cancel)?; + let (_, mut bounds) = fine_edit::inspect_page(&req, page, cancel) + .map_err(|error| draft.page_error(number, error))?; if input.illustrations_only == Some(true) { bounds.retain(|g| g.illustration.is_some()); } @@ -418,7 +447,7 @@ impl Engine { sections: Vec
, format: Format, cancel: &Cancellation, - mut progress: impl FnMut(usize), + mut on_page: impl FnMut(usize, u32, usize), ) -> Result { let mut count = 0; let mut background = draft.background()?; @@ -428,15 +457,22 @@ impl Engine { for section in sections { cancel.check()?; let (_, edits) = draft.edits(§ion)?; + let number = section.number; let mut request = self.request(draft, section, background.take(), edits)?; request.params.pdf_save = matches!(format, Format::Pdf); request.limits.max_pages -= count; - Self::render_pages(&request, photo.as_ref(), cancel, usize::MAX, |_, page| { - emit(count, &page)?; - count += 1; - progress(count); - Ok(()) - })?; + Self::render_pages( + &request, + photo.as_ref(), + cancel, + usize::MAX, + |index, page| { + emit(count, &page)?; + count += 1; + on_page(count, number, index + 1); + Ok(()) + }, + )?; background = request.background.take(); } cancel.check()?; diff --git a/crates/panache-mcp/src/engine/adjustments.rs b/crates/panache-mcp/src/engine/adjustments.rs index cc26c594..7ad2eaf5 100644 --- a/crates/panache-mcp/src/engine/adjustments.rs +++ b/crates/panache-mcp/src/engine/adjustments.rs @@ -23,7 +23,8 @@ impl Engine { let changes = GlyphChanges::parse(input, &draft.style)?; let version = section.version; let mut req = self.fine_request(draft, section)?; - let (key, mut bounds) = fine_edit::inspect_page(&req, input.page, cancel)?; + let (key, mut bounds) = fine_edit::inspect_page(&req, input.page, cancel) + .map_err(|error| draft.page_error(input.section, error))?; bounds.retain(|g| changes.ids.contains(&g.id)); let mut selected = BTreeMap::new(); for glyph in &bounds { diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 5efd5ea2..d1c9a1f4 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -119,8 +119,9 @@ pub struct Tune { /// Brief observable issue or user instruction that motivated this edit (max 320 characters). pub note: Option, pub draft_id: String, + /// Current revision returned by list_drafts or the last edit. pub expected_revision: u32, - /// Sparse name/value patch from describe_controls. Null restores the original setting. + /// Pass controls under changes, e.g. {"perturb_theta_sigma":0.07}. Group objects from describe_controls also work inside changes. Null restores a control. #[serde(default)] pub changes: serde_json::Map, } @@ -142,10 +143,30 @@ pub enum ReadView { Source, } +#[derive(Clone, Copy, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum ReviewPage { + Number(u32), + Last(LastPage), +} + +#[derive(Clone, Copy, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum LastPage { + Last, +} + #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Read { - /// With view=review, retrieve one immutable measurement and its attributed feedback. + /// With view=review, retrieve the most recently recorded full-page measurement at this one-based + /// page, or "last" to paginate the selected section at the same revision. With "last" or before_text, + /// specify the section containing the requested body in a multi-section draft. Omit review_id. + pub page: Option, + /// For a page review just before an addition: an exact, distinctive fragment of the added Markdown. + /// Uses the revision immediately before its unique introduction; repeated introductions are ambiguous. Omit revision. + pub before_text: Option, + /// With view=review, retrieve one immutable measurement and its attributed feedback by ID instead of page. pub review_id: Option, /// With trajectory, pass next_cursor to continue the same snapshot, including its filters. Omit offset. pub cursor: Option, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 5d7fb9bb..fe797d7b 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -36,6 +36,7 @@ use tokio::sync::Semaphore; struct State { drafts: Drafts, + preserve_reviews: bool, engine: Mutex, fonts: Vec, local_fonts: LocalFonts, @@ -66,6 +67,130 @@ fn reply(message: String, metadata: serde_json::Value) -> CallToolResult { result } +fn add_receipt_summary(record: &mut serde_json::Value) -> String { + let position = format!( + "第 {} 版 · 第 {} 节第 {} 页", + record["revision"], record["section"], record["page"] + ); + let conclusion = match record["review_id"].as_str() { + None => format!("{position}没有已存的整页检查单。是否曾在纸上看过,档案无法判断。"), + Some(id) => match record["filed_at_revision"].as_u64() { + Some(filed) if Some(filed) == record["revision"].as_u64() => { + format!( + "{position}已存整页检查单,检查单号 {id}。首次入档时稿件仍为第 {filed} 版。" + ) + } + Some(filed) => format!( + "{position}有一张事后补验的检查单,检查单号 {id}。首次入档时稿件已到第 {filed} 版,这张单无法证明改稿前已经验过。" + ), + None => format!( + "能否确认改稿前已验过?无法确认。{position}有旧单,检查单号 {id}。旧单未记录首次入档时的稿件版本,可能是事后补验。" + ), + }, + }; + record["receipt_summary"] = json!(conclusion); + conclusion +} + +fn page_receipt( + draft: &drafts::Snapshot<'_>, + section: u32, + page: u32, + anchor: Option<(u32, u32)>, +) -> Result { + let mut record = draft.page_observation(section, page)?; + record["latest_draft_revision"] = json!(draft.latest_revision); + if let Some((anchor_section, added_revision)) = anchor { + record["before_text_match"] = + json!({"section": anchor_section, "introduced_revision": added_revision}); + } + let conclusion = add_receipt_summary(&mut record); + let text = format!( + "{conclusion}\n当前稿件第 {} 版。\n{record}", + draft.latest_revision + ); + Ok(reply(text, record)) +} + +impl Panache { + async fn read_review( + &self, + input: Read, + ctx: RequestContext, + ) -> Result { + ensure!( + input.cursor.is_none() && input.feedback_origin.is_none(), + "cursor and feedback_origin require view=trajectory" + ); + ensure!( + input.offset.is_none() && input.limit.is_none(), + "view=review does not use offset or limit" + ); + if let Some(page) = input.page { + ensure!(input.review_id.is_none(), "Use page or review_id, not both"); + ensure!( + input.before_text.is_none() || input.revision.is_none(), + "Use before_text or revision, not both" + ); + let anchor = input + .before_text + .as_deref() + .map(|t| self.0.drafts.text_introduction(&input.draft_id, t)) + .transpose()?; + let revision = anchor.map(|(_, added)| added - 1).or(input.revision); + return match page { + ReviewPage::Number(n) => { + let draft = self.0.drafts.snapshot(&input.draft_id, revision)?; + let section = if anchor.is_some() { + draft.review_section(input.section)? + } else { + input.section.unwrap_or(1) + }; + page_receipt(&draft, section, n, anchor) + } + ReviewPage::Last(_) => { + self.render(ctx, move |state, engine, cancel| { + let draft = state.drafts.snapshot(&input.draft_id, revision)?; + let section = draft.review_section(input.section)?; + let source = state + .drafts + .sections(draft.id, draft.revision, Some(section))? + .pop() + .context("Empty section")?; + let last = engine.page_count(&draft, source, cancel)?; + page_receipt(&draft, section, last, anchor) + }) + .await + } + }; + } + ensure!( + input.section.is_none() && input.before_text.is_none(), + "Supply page with section or before_text, or review_id alone" + ); + let draft = self.0.drafts.snapshot(&input.draft_id, input.revision)?; + let mut data = draft.observation( + input + .review_id + .as_deref() + .context("Supply review_id or page")?, + )?; + let summary = add_receipt_summary(&mut data); + let mut content_note = None; + if input.revision.is_some() && data["revision"].as_u64() != Some(u64::from(draft.revision)) + { + content_note = Some(ContentBlock::text(format!( + "此单属于第 {} 版。若要确认所查第 {} 版是否留有整页检查单,请用 read_section(view=review, revision={}, section={}, page={}) 查该版。", + data["revision"], draft.revision, draft.revision, data["section"], data["page"] + ))); + } + let mut result = reply(data.to_string(), data); + result.content.push(ContentBlock::text(summary)); + result.content.extend(content_note); + Ok(result) + } +} + fn tool_result(out: Result) -> CallToolResult { out.unwrap_or_else(|error| { CallToolResult::error(vec![ContentBlock::text(format!("{error:#}"))]) @@ -127,20 +252,30 @@ impl Panache { impl ServerHandler for Panache { fn get_info(&self) -> rmcp::model::ServerConfig { use rmcp::model::{Implementation, ServerCapabilities, ServerConfig}; + let instructions = concat!( + "If a required area of a photo is outside the frame, or blur, occlusion or perspective prevents locating it, identify that area before drafting. ", + "Ask for a photo clearly showing it or permission to fill only visible areas; wait before saving or trial placement. If partial work was requested, proceed there. ", + "For looser, less uniform homework or lab handwriting (字稍微草一点), inspect describe_controls(group=variation). For requested crossed-out mistakes (涂改痕迹), inspect group=strike. ", + "Use save_section(markdown), then its draft_id and revision for preview_handwriting or export_handwriting. ", + "English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. For an undecided homework or lab-report style, see list_fonts for sample guidance. Use list_drafts to resume. A paper_path must be readable on the server computer. ", + "For old checks before a passage was added, use read_section(view=review, before_text=literal from that addition, section, page); page can be \"last\". For current checks omit revision. If the user asks to see or print without a new check, use view=image for the appearance and export_handwriting for the file and missing pages. A full-page preview_handwriting(view=review) records a check. Follow photo_appearance.preview_arguments for a native detail crop when available. ", + "If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", + "Forms, unruled paper and artwork are supported. Follow specified or delegated placement, matching field orientation and preserving printed labels. ", + "If the intended writing area is ambiguous, ask which field to fill or leave clear. ", + "Photo coordinates use native output pixels; local dx/dy use paper-space pixels. ", + "Inspect the edited appearance with view=image when no new check is requested. Use read_section(view=trajectory) to revisit actions and evidence." + ); + let mode = if self.0.preserve_reviews { + "This connection preserves stored reviews. Use view=image to inspect and export_handwriting to print. " + } else { + "" + }; ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) - .with_server_info(Implementation::new("panache-mcp", handwriting_core::app_version())) - .with_instructions(concat!( - "If a required area of a photo is outside the frame, or blur, occlusion or perspective prevents locating it, identify that area before drafting. ", - "Ask for a photo clearly showing it or permission to fill only visible areas; wait before saving or trial placement. If partial work was requested, proceed there. ", - "Use save_section(markdown), then its draft_id and revision for preview_handwriting or export_handwriting. ", - "English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. For an undecided homework or lab-report style, see list_fonts for sample guidance. Use list_drafts to resume. A paper_path must be readable on the server computer. ", - "For photos use preview_handwriting(view=review). Follow photo_appearance.preview_arguments for a native detail crop when available. ", - "If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", - "Forms, unruled paper and artwork are supported. Follow specified or delegated placement, matching field orientation and preserving printed labels. ", - "If the intended writing area is ambiguous, ask which field to fill or leave clear. ", - "Photo coordinates use native output pixels; local dx/dy use paper-space pixels. ", - "Review the edited revision. Use read_section(view=trajectory) to revisit actions and evidence." + .with_server_info(Implementation::new( + "panache-mcp", + handwriting_core::app_version(), )) + .with_instructions(format!("{mode}{instructions}")) } } @@ -148,7 +283,7 @@ impl ServerHandler for Panache { impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "Discover handwriting settings by group. Omit group for an index; request one group before tuning." + description = "For less even handwriting, inspect group=variation; for requested occasional crossed-out mistakes, group=strike. Pass draft_id to read current values before tune_handwriting. Omit group for the index." )] fn describe_controls(&self, Parameters(input): Parameters) -> CallToolResult { tool_result((|| { @@ -212,7 +347,7 @@ impl Panache { } #[tool( - description = "Revise a draft: change controls, import a local font_path, or replace paper_guides on its saved image. Map the intended area onto first/last writable baselines even on artwork or unruled paper. Ink-group changes preserve local glyph placement; after changing font, size or guides, inspect the new layout. Review the new revision before export." + description = "Revise a draft: change controls, import a local font_path, or replace paper_guides on its saved image. Map the intended area onto first/last writable baselines even on artwork or unruled paper. Ink-group changes preserve local glyph placement; after changing font, size or guides, inspect the new layout. Use view=image to inspect the result when the user wants to preserve checks." )] async fn tune_handwriting(&self, Parameters(input): Parameters) -> CallToolResult { let state = self.0.clone(); @@ -243,7 +378,7 @@ impl Panache { "For a hurried pen style, try 李国夫手写体.ttf if listed. Use a short line from the task with Chinese, an English term and a number or unit. ", "Preview it at the intended size on the intended paper. Compare stroke weight, slant, relative size and digit legibility. ", "If the style is undecided, show the sample, recommend a font based on what is visible, and ask if it fits before laying out the full page. ", - "Honor an approved or delegated main font. A request for generally messier handwriting applies to the main font. Only consider separate settings for letters or digits when the user specifically requests them or expresses dissatisfaction with their appearance; then inspect describe_controls(group=typography)." + "Keep an approved font. For a less regular hand inspect describe_controls(group=variation) and preview a small change. If the user wants occasional corrections, inspect group=strike. Only consider separate settings for letters or digits when the user specifically requests them or expresses dissatisfaction with their appearance; then inspect describe_controls(group=typography)." ); let mut data = json!({ "entries": page.fonts, "total": page.total, @@ -286,14 +421,25 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "Read view=trajectory for draft history, highest associated revision first. Filter by feedback_origin=user_quote and optionally section for verbatim quotes in events[].details.text with their revision and review_id. Use view=review with review_id for full measurements or other feedback on that review. Text views: summary, excerpt (default, image data omitted), or exact source." + description = "For a prior check of a particular sheet, use view=review, section and page. For “before adding [words]” pass before_text with a literal fragment of the addition; for the final sheet of that section pass page=\"last\". These select and paginate the same historical version in one lookup. For a single requested sheet cite its returned review_id and receipt_summary. Other revisions can have separate receipts for the same page. Otherwise omit revision for current or set a revision. The check receipt number (检查单号) is review_id. Read its saved measurements and attributed feedback, or no_recorded_review, without creating a check. A known review_id retrieves that record. Use view=trajectory to identify revisions from edits or search across versions: older events remain in the results. Filter by section and feedback_origin=user_quote for verbatim events[].details.text. Text views: summary, excerpt (default, image data omitted), source (exact Markdown)." )] - fn read_section(&self, Parameters(input): Parameters) -> CallToolResult { + async fn read_section( + &self, + Parameters(input): Parameters, + ctx: RequestContext, + ) -> CallToolResult { + if input.view == Some(ReadView::Review) { + return tool_result(self.read_review(input, ctx).await); + } tool_result((|| { ensure!( input.feedback_origin.is_none() || input.view == Some(ReadView::Trajectory), "feedback_origin requires view=trajectory" ); + ensure!( + input.page.is_none() && input.before_text.is_none(), + "page and before_text require view=review" + ); if input.view == Some(ReadView::Trajectory) { ensure!(input.review_id.is_none(), "review_id requires view=review"); let result = self.0.drafts.trajectory(&input)?; @@ -301,15 +447,6 @@ impl Panache { } ensure!(input.cursor.is_none(), "cursor requires view=trajectory"); let draft = self.0.drafts.snapshot(&input.draft_id, input.revision)?; - if input.view == Some(ReadView::Review) { - ensure!( - input.section.is_none() && input.offset.is_none() && input.limit.is_none(), - "Exact review lookup uses draft_id and review_id" - ); - let data = - draft.observation(input.review_id.as_deref().context("Provide review_id")?)?; - return Ok(reply(data.to_string(), data)); - } ensure!(input.review_id.is_none(), "review_id requires view=review"); let mut result = self.0.drafts.review( &input.draft_id, @@ -344,7 +481,7 @@ impl Panache { #[tool( annotations(open_world_hint = false), - description = "view=review returns paper, finished appearance, overlay and full-page evidence. With compare_revision alone it reads stored data, review IDs, intervening edits and limitations. With region it renders labeled local crops in native image coordinates and measures visible changes; add compare_revision for paired before/after, and previous_region for the old location of moved content. Use a separate region to inspect protected content. view=layout returns glyph IDs and base boxes [x,y,width,height], paginated by offset/limit. Use region to select current glyph centers, illustrations_only for diagrams. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline. view=paper returns the saved background." + description = "Use view=image to see the page without filing a check. A full-page view=review renders and records a check. To look up an existing check without rendering use read_section(view=review, section, page). view=review returns paper, finished appearance, overlay and full-page evidence. With compare_revision alone it reads stored data, review IDs, intervening edits and limitations. With region it renders labeled local crops in native image coordinates and measures visible changes; add compare_revision for paired before/after, and previous_region for the old location of moved content. Use a separate region to inspect protected content. view=layout returns glyph IDs and base boxes [x,y,width,height], paginated by offset/limit. Use region to select current glyph centers, illustrations_only for diagrams. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline. view=paper returns the saved background." )] async fn preview_handwriting( &self, @@ -358,6 +495,11 @@ impl Panache { description = "Attach a user's exact quote or your own model observation to a review_id. Does not advance the draft revision. Use read_section(view=review,review_id=...) to retrieve it." )] fn annotate_review(&self, Parameters(input): Parameters) -> CallToolResult { + if self.0.preserve_reviews { + return tool_result(Err(anyhow::anyhow!( + "此连接保留原有检查记录,无法添加评语。可用 read_section(view=review) 查阅原单。" + ))); + } tool_result( self.0 .drafts @@ -430,7 +572,7 @@ impl Panache { } #[tool( - description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns a local file path and page count. For ink-only PNG pages, set transparent_background=true with tune_handwriting (ink group) and export ZIP. PDF always includes paper. Text-only clients can give the user the PDF path for visual inspection. Review the intended revision, especially after moving glyphs or changing ink." + description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns the path, page count and review.unreviewed_pages in print order. For a print-and-report request return the file and missing pages. Only if a new check is requested, use preview_handwriting(view=review) at the exported revision. For ink-only PNG pages, set transparent_background=true with tune_handwriting (ink group) and export ZIP. PDF always includes paper. Text-only clients can give the user the PDF path for visual inspection. Use view=image to inspect the intended appearance without filing a check." )] async fn export_handwriting( &self, @@ -442,13 +584,19 @@ impl Panache { let result = self.render(ctx, move |state, engine, cancel| { let draft = state.drafts.snapshot(&input.draft_id, input.revision)?; let sections = state.drafts.sections(&input.draft_id, draft.revision, None)?; - let (reviewed,visibility_flags)=draft.review_counts()?; - let params=controls::parameters(&draft,1,&draft.controls)?; - let zero_text_ink=params.ink_opacity==0 || params.fill[3]==0; + let reviewed_pages = draft.reviewed_pages()?; + let mut unreviewed = Vec::new(); + let mut visibility_flags = 0; + let params = controls::parameters(&draft, 1, &draft.controls)?; + let zero_text_ink = params.ink_opacity == 0 || params.fill[3] == 0; let format = input.format.unwrap_or_default(); let (path, pages) = state.storage.export(&state.drafts,draft.id,draft.revision,format, |writer| engine.export( writer, &draft, sections, format, cancel, - |pages| { + |pages, section, page| { + match reviewed_pages.get(&(section, page)) { + Some(flagged) => visibility_flags += usize::from(*flagged), + None => unreviewed.push(json!({"section":section,"page":page})), + } if let Some(token) = &progress_token { let update = rmcp::model::ProgressNotificationParam::new(token.clone(), pages as f64) .with_message(format!("{pages} pages rendered")); @@ -456,10 +604,29 @@ impl Panache { } }, ))?; - let warning=if zero_text_ink || visibility_flags>0 {"墨迹可见性需要复查。"}else if (reviewed as usize) 0 { + "墨迹可见性需要复查。" + } else if reviewed < pages { + "未复盘页的局部墨迹可见性尚未核验。" + } else { + "" + }; + let remaining = if unreviewed.is_empty() { + String::new() + } else { + format!(" 缺少整页检查单的节内页码:{}。", serde_json::to_string(&unreviewed)?) + }; + let message = format!("已导出 **{pages} 页**(版本 {})。该版已有 {reviewed}/{pages} 页复盘证据。{warning}{remaining}\n\n`{}`", draft.revision, path.display()); Ok(reply(message, json!({ - "draft_id": input.draft_id, "revision": draft.revision, "path": path, "pages": pages, "review":{"pages_with_evidence":reviewed,"pages_with_visibility_flags":visibility_flags,"global_text_ink_zero":zero_text_ink,"pages_without_visibility_evidence":pages.saturating_sub(reviewed as usize)} + "draft_id": input.draft_id, "revision": draft.revision, "path": path, "pages": pages, + "review": { + "pages_with_evidence": reviewed, + "pages_with_visibility_flags": visibility_flags, + "global_text_ink_zero": zero_text_ink, + "pages_without_visibility_evidence": unreviewed.len(), + "unreviewed_pages": unreviewed, + } }))) }).await; tool_result(result) @@ -504,7 +671,14 @@ async fn main() -> Result<()> { let output = home.join("exports"); fs::create_dir_all(&output)?; let drafts = Drafts::open(&home)?; + let preserve_reviews = match env::var_os("PANACHE_MCP_PRESERVE_REVIEWS").as_deref() { + None => false, + Some(value) if value == "0" => false, + Some(value) if value == "1" => true, + _ => anyhow::bail!("PANACHE_MCP_PRESERVE_REVIEWS must be 0 or 1"), + }; let state = State { + preserve_reviews, storage: storage::Storage::open(&home, &drafts)?, drafts, local_fonts: LocalFonts::new(engine.names.clone(), Limits::default().max_file_bytes), diff --git a/crates/panache-mcp/src/preview.rs b/crates/panache-mcp/src/preview.rs index 29deb6af..282e6da7 100644 --- a/crates/panache-mcp/src/preview.rs +++ b/crates/panache-mcp/src/preview.rs @@ -87,6 +87,11 @@ fn render( .pop() .context("Empty draft")?; let page = input.page.unwrap_or(1); + let max = Limits::default().max_pages; + ensure!( + (1..=max).contains(&page), + "Requested page {page} in section {number}. Page numbers start at 1 within each section (maximum {max})." + ); if input.view == Some(PreviewView::Review) { ensure!( input.limit.is_none() && input.offset.is_none(), @@ -103,6 +108,10 @@ fn render( cancel, ); } + ensure!( + !state.preserve_reviews, + "此连接保留原有检查记录。看成图请用 view=image,查原单请用 read_section(view=review),打印请用 export_handwriting。" + ); let baselines = engine.review_baselines(&draft, section.clone(), page, cancel)?; let (preview, _) = engine.preview(&draft, section, page, cancel)?; return review::page(&draft, number, page, &preview.png, &baselines, cancel); diff --git a/crates/panache-mcp/src/tuning.rs b/crates/panache-mcp/src/tuning.rs index aa3a4ad2..7fdc81aa 100644 --- a/crates/panache-mcp/src/tuning.rs +++ b/crates/panache-mcp/src/tuning.rs @@ -4,7 +4,8 @@ use rmcp::model::CallToolResult; use serde_json::json; use std::fs; -pub fn apply(state: &State, input: Tune) -> Result { +pub fn apply(state: &State, mut input: Tune) -> Result { + input.changes = controls::flatten_patch(input.changes)?; let mut draft = state .drafts .snapshot(&input.draft_id, Some(input.expected_revision))?; diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index 5a6038c3..4e67e5c1 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -166,10 +166,85 @@ async def history(**args): assert (await client.call_tool("read_section", {**key, **invalid})).isError +async def historical_last_page(client, directory, call, path, guides): + saved = await call(client, "save_section", paper_path=str(path), paper_guides=guides, + markdown="\n\n".join(f"初次测量第{i}行。" for i in range(20))) + key = {"draft_id": saved.structuredContent["draft_id"]} + exported = await call(client, "export_handwriting", **key, revision=1, format="zip") + last = exported.structuredContent["pages"] + assert last > 1 + await call(client, "preview_handwriting", **key, revision=1, view="review", page=1) + await call(client, "save_section", **key, expected_revision=1, section=1, + markdown="复测补录:一行。") + current = (await call(client, "preview_handwriting", **key, view="review")).structuredContent + select = {**key, "view": "review", "section": 1, "page": "last"} + assert (await call(client, "read_section", **select)).structuredContent["review_id"] == current["review_id"] + anchored = {**select, "before_text": "复测补录"} + with closing(sqlite3.connect(directory / "drafts.sqlite3")) as db: + sql = "SELECT seq,review_id FROM review_observations WHERE draft=? ORDER BY seq" + records = db.execute(sql, (key["draft_id"],)).fetchall() + for _ in range(2): + receipt = await call(client, "read_section", **anchored) + data = receipt.structuredContent + assert (data["revision"], data["section"], data["page"]) == (1, 1, last) + assert data["before_text_match"] == {"introduced_revision": 2, "section": 1} + assert data["review_id"] is None and data["status"] == "no_recorded_review" + assert all(part.type == "text" for part in receipt.content) + assert db.execute(sql, (key["draft_id"],)).fetchall() == records + old = (await call(client, "preview_handwriting", **key, revision=1, view="review", page=last)).structuredContent + receipt = await call(client, "read_section", **anchored) + assert receipt.structuredContent["review_id"] == old["review_id"] + assert receipt.structuredContent["filed_at_revision"] == 2 + assert "事后补验" in receipt.structuredContent["receipt_summary"] + assert receipt.content[0].text.startswith(receipt.structuredContent["receipt_summary"]) + for override in ({"before_text": "初次测量"}, {"before_text": "缺少的段落"}, + {"before_text": ""}, {"revision": 1}, {"section": 2}, {"page": "latest"}): + assert (await client.call_tool("read_section", {**anchored, **override})).isError + # Retaining the fragment across edits is still the same introduction. + await call(client, "save_section", **key, expected_revision=2, section=1, markdown="复测补录:两行。") + numeric = {**anchored, "page": last} + assert (await call(client, "read_section", **numeric)).structuredContent["review_id"] == old["review_id"] + await call(client, "save_section", **key, expected_revision=3, section=1, markdown="新题目。") + await call(client, "save_section", **key, expected_revision=4, section=1, markdown="复测补录:新题目。") + ambiguous = await client.call_tool("read_section", numeric) + assert ambiguous.isError + options = ambiguous.content[0].text + assert options.index("revision=1") < options.index("revision=4") + assert "未确认时不要代选" in options and old["review_id"] not in options + assert "section=1" in options and "第 1 节加入" not in options + await call(client, "save_section", **key, expected_revision=5, markdown="另一节也写了新题目和初次测量。") + assert (await client.call_tool("read_section", {**numeric, "before_text": "新题目"})).isError + await call(client, "save_section", **key, expected_revision=6, markdown="第三节:初次测量。") + several = await client.call_tool("read_section", {**numeric, "before_text": "初次测量"}) + assert several.isError + options = several.content[0].text + assert "之前没有稿件" in options and "revision=5" in options + assert "只列最早两次" in options and "revision=6" not in options + # A last-page or relative lookup must not silently use section one in a multi-section draft. + for args in ({**key, "view": "review", "page": "last", "revision": 6}, + {**key, "view": "review", "page": 1, "before_text": "第三节:"}): + missing_section = await client.call_tool("read_section", args) + assert missing_section.isError and "section=2" in missing_section.content[0].text + image = base64.b64encode(path.read_bytes()).decode("ascii") + await call(client, "save_section", **key, expected_revision=7, markdown=f"![图](data:image/png;base64,{image})") + await call(client, "save_section", **key, expected_revision=8, markdown="第 5 节正文") + listing = await client.call_tool("read_section", {**key, "view": "review", "page": "last"}) + assert listing.isError + text = listing.content[0].text + assert "section=4" in text and "其余节" in text and "section=5" not in text + assert "base64" not in text and image[:16] not in text + # An ordinary numbered page keeps the established first-section default. + direct = await call(client, "read_section", **key, view="review", revision=6, page=1) + assert direct.structuredContent["section"] == 1 + explicit = {**select, "revision": 1, "page": last} + assert (await call(client, "read_section", **explicit)).structuredContent["review_id"] == old["review_id"] + + async def exercise(client, directory, call): await unruled_artwork(client, directory, call) path = directory / "slanted.png" guides = slanted_sheet(path) + await historical_last_page(client, directory, call, path, guides) shifted = [ { **g, @@ -278,6 +353,14 @@ def assets(): and bottom["limitation"] == "insufficient_ridge_support" ) await tune(4, changes={"ink_opacity": 0}) + inventory = assets() + for _ in range(2): + empty = await call(client, "read_section", **key, view="review", section=1, page=1) + assert empty.structuredContent["status"] == "no_recorded_review" + assert empty.structuredContent["revision"] == empty.structuredContent["latest_draft_revision"] == 5 + assert empty.structuredContent["review_id"] is None + assert all(block.type == "text" for block in empty.content) + assert assets() == inventory assert "missing_after_review" in (await compare(4, 5))["comparison"]["limitations"] assert "photo_appearance" in await review(5) invisible = (await compare(4, 5))["comparison"]["delta"] diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 12564d81..c15fed92 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -73,11 +73,13 @@ async def review_workflow(client, key, guides, font_path): assert Path(same_pdf["path"]).read_bytes() == Path(pdf["path"]).read_bytes() await call(client, "tune_handwriting", **key, expected_revision=6, changes={"ink_opacity": 0}) unreviewed = (await call(client, "export_handwriting", **key, format="zip")).structuredContent["review"] + assert unreviewed["unreviewed_pages"] == [{"section": 1, "page": 1}] assert unreviewed["pages_with_evidence"] == 0 and unreviewed["global_text_ink_zero"] invisible = (await call(client, "preview_handwriting", **key, view="review")).structuredContent assert invisible["evidence"]["visibility"] == "no_visible_change" assert invisible["evidence"]["max_rgb_delta"] == 0 flagged = (await call(client, "export_handwriting", **key, format="zip")).structuredContent["review"] + assert flagged["unreviewed_pages"] == [] assert flagged["pages_with_evidence"] == 1 and flagged["pages_with_visibility_flags"] == 1 recent = (await call(client, "read_section", **key, view="trajectory", limit=1)).structuredContent assert recent["next_offset"] == 1 and recent["events"][0]["details"]["visibility"] == "no_visible_change" @@ -131,6 +133,31 @@ async def mixed_script_sample(client): assert png(await call(client, "preview_handwriting", **key)) == primary +async def handwriting_variation_sample(client): + markdown = "样品 A 的质量为 12.5 g。" + saved = (await call(client, "save_section", markdown=markdown, style={"seed": 17})).structuredContent + key = {"draft_id": saved["draft_id"]} + base = png(await call(client, "preview_handwriting", **key)) + for invalid in ({"variation": {"perturb_theta_sigma": 0.07}, "perturb_theta_sigma": 0.08}, + {"variation": {"strikethrough_probability": 0.1}}, {"variation": {}}): + rejected = await client.call_tool("tune_handwriting", {**key, "expected_revision": 1, "changes": invalid}) + assert rejected.isError + tuned = await call(client, "tune_handwriting", **key, expected_revision=1, + changes={"variation": {"perturb_theta_sigma": 0.07}}) + assert tuned.structuredContent["controls"]["perturb_theta_sigma"] == 0.07 + loose = png(await call(client, "preview_handwriting", **key)) + assert loose != base + strike = (await call(client, "describe_controls", **key, group="strike")).structuredContent + assert strike["values"]["strikethrough_probability"] == 0 + assert strike["controls"]["strikethrough_angle_sigma"]["unit"] == "deg" + # Force the optional effect for a deterministic positive control on a short line. + await call(client, "tune_handwriting", **key, expected_revision=2, changes={"strikethrough_probability": 1}) + assert png(await call(client, "preview_handwriting", **key)) != loose + assert png(await call(client, "preview_handwriting", **key, revision=2)) == loose + source = (await call(client, "read_section", **key, view="source")).structuredContent + assert source["markdown"] == markdown + + async def placement_pixels(client): saved = (await call(client, "save_section", markdown="字", style={"seed": 17})).structuredContent key = {"draft_id": saved["draft_id"]} @@ -164,6 +191,7 @@ async def ink_box(): assert measured["difference"]["outside_union_changed_pixels"] == 0 exported = await call(client, "export_handwriting", **key) assert exported.structuredContent["review"]["pages_without_visibility_evidence"] == 1 + assert exported.structuredContent["review"]["unreviewed_pages"] == [{"section": 1, "page": 1}] assert "局部墨迹" in exported.content[0].text @@ -190,6 +218,7 @@ async def smoke(command, arguments, out): assert "outside the frame" in before_save and "wait before saving" in before_save assert "partial work was requested" in before_save assert "ask which field" in info.instructions + assert "group=variation" in info.instructions and "group=strike" in info.instructions tools = await client.list_tools() assert {t.name for t in tools.tools} == { "annotate_review", @@ -209,6 +238,10 @@ async def smoke(command, arguments, out): listed = await call(client, "list_fonts") guidance = listed.structuredContent["sample_guidance"] assert guidance in listed.content[0].text + for group, name in [("variation", "perturb_theta_sigma"), ("strike", "strikethrough_probability")]: + assert f"group={group}" in guidance + spec = (await call(client, "describe_controls", group=group)).structuredContent + assert spec["controls"][name]["description"] assert "志莽行书.ttf" in listed.structuredContent["fonts"] results = (await call(client, "list_fonts", source="user", query="localsample", limit=1)).structuredContent assert results["total"] == 1 and results["next_offset"] is None @@ -310,6 +343,7 @@ async def smoke(command, arguments, out): ) assert failed.isError await mixed_script_sample(client) + await handwriting_variation_sample(client) await placement_pixels(client) await coursework_form.exercise(client, Path(temp)) comparison_key, reviewed_id, user_quote = await review_comparison.exercise(client, Path(temp), call) @@ -362,6 +396,9 @@ async def smoke(command, arguments, out): client, "preview_handwriting", draft_id=doc, section=2, page=2 ) middle = png(later) + # Review a later sheet first. Earlier-revision and local evidence cannot fill gaps. + await call(client, "preview_handwriting", draft_id=doc, revision=1, view="review") + await call(client, "preview_handwriting", draft_id=doc, section=2, page=2, view="review") notifications = [] async def progress(value, total, message=None): @@ -377,7 +414,35 @@ async def progress(value, total, message=None): assert notifications == list(range(1, archive["pages"] + 1)) with ZipFile(archive["path"]) as z: assert archive["pages"] == len(z.namelist()) >= 3 + remaining = [{"section": 1, "page": 1}] + [ + {"section": 2, "page": page} for page in range(1, len(z.namelist())) if page != 2 + ] + assert archive["review"]["unreviewed_pages"] == remaining + assert archive["review"]["pages_without_visibility_evidence"] == len(remaining) + assert archive["review"]["pages_with_evidence"] == 1 assert z.read("0.png") == original and z.read("2.png") == middle + # An export gap is a coordinate at the exported revision, even when the + # same section and page have a stored receipt on an earlier revision. + receipt_args = {"draft_id": doc, "view": "review", **remaining[0]} + gap = await call(client, "read_section", **receipt_args, revision=archive["revision"]) + assert gap.structuredContent["status"] == "no_recorded_review" + assert "档案无法判断" in gap.content[0].text + prior = await call(client, "read_section", draft_id=doc, view="review", + section=1, page="last", before_text="数学作业") + assert prior.structuredContent["revision"] == 1 and prior.structuredContent["review_id"] + wrong_section = await client.call_tool("read_section", { + "draft_id": doc, "view": "review", "section": 2, "page": "last", "before_text": "数学作业", + }) + assert wrong_section.isError and "section=1" in wrong_section.content[0].text + by_page = await call(client, "read_section", **receipt_args, revision=1) + assert by_page.structuredContent["review_id"] == prior.structuredContent["review_id"] + assert "事后补验" in by_page.content[0].text + appearance = await call(client, "preview_handwriting", draft_id=doc, + revision=archive["revision"], view="image", **remaining[0]) + assert png(appearance) == original + repeated = await call(client, "export_handwriting", draft_id=doc, + revision=archive["revision"], format="zip") + assert repeated.structuredContent["review"] == archive["review"] conflict = await client.call_tool( "save_section", {"draft_id": doc, "expected_revision": 1, "markdown": "迟到的编辑"}, @@ -386,7 +451,23 @@ async def progress(value, total, message=None): missing = await client.call_tool( "preview_handwriting", {"draft_id": doc, "section": 1, "page": 2} ) - assert missing.isError + assert missing.isError and "section=2, page=1" in missing.content[0].text + for view in ("layout", "review"): + missing = await client.call_tool("preview_handwriting", { + "draft_id": doc, "section": 1, "page": 2, "view": view, + }) + assert missing.isError + assert "available page count: 1" in missing.content[0].text + assert "section=2, page=1" in missing.content[0].text + historical = await client.call_tool("preview_handwriting", { + "draft_id": doc, "revision": 1, "page": 2, "view": "review", + }) + assert historical.isError and "last section" in historical.content[0].text + assert "section=2" not in historical.content[0].text + zero = await client.call_tool("preview_handwriting", { + "draft_id": doc, "section": 2, "page": 0, "view": "layout", + }) + assert zero.isError and "start at 1" in zero.content[0].text edited = await call( client, "save_section", @@ -404,6 +485,24 @@ async def progress(value, total, message=None): retrieved = (await call(client, "read_section", **comparison_key, view="review", review_id=reviewed_id)).structuredContent assert retrieved["revision"] == 3 and retrieved["section"] == retrieved["page"] == 1 assert retrieved["feedback"] == [{"origin":"user_quote","text":user_quote}] + lookup = dict(**comparison_key, view="review", page=1) + receipt = await call(client, "read_section", **lookup, revision=3) + summary = receipt.structuredContent["receipt_summary"] + assert receipt.structuredContent == {**retrieved, "latest_draft_revision": 6, "receipt_summary": summary} + assert retrieved["filed_at_revision"] == 3 and "仍为第 3 版" in summary + older = await call(client, "read_section", **comparison_key, view="review", review_id=reviewed_id) + assert json.loads(older.content[0].text) == retrieved == older.structuredContent + assert older.content[1].text == summary and len(older.content) == 2 + explicit = await call(client, "read_section", **comparison_key, view="review", review_id=reviewed_id, revision=6) + assert "revision=6, section=1, page=1" in explicit.content[2].text + assert f"检查单号 {reviewed_id}" in receipt.content[0].text + for args in (dict(**lookup, revision=3, section=2), dict(**gkey, view="review", page=1, revision=1)): + missing = (await call(client, "read_section", **args)).structuredContent + assert missing["status"] == "no_recorded_review" and missing["review_id"] is None + assert missing["draft_id"] == args["draft_id"] and missing["revision"] == args["revision"] + for args in ({**lookup, "review_id": reviewed_id}, {**lookup, "view": "trajectory"}, + {**lookup, "page": 0}, {**lookup, "section": 0}, {**lookup, "limit": 1}): + assert (await client.call_tool("read_section", args)).isError assert (await call(client,"read_section",**comparison_key,view="summary")).structuredContent["revision"] == 6 events = (await call(client,"read_section",**comparison_key,view="trajectory",limit=50)).structuredContent["events"] assert {e["origin"] for e in events} >= {"draft_edit","measurement","user_quote","model_observation"} @@ -638,6 +737,20 @@ async def progress(value, total, message=None): ) == adjusted ) + protected = params.model_copy(update={"env": {**params.env, "PANACHE_MCP_PRESERVE_REVIEWS": "1"}}) + async with stdio_client(protected) as streams, ClientSession(*streams) as client: + assert "preserves stored reviews" in (await client.initialize()).instructions + key = {"draft_id": doc, "revision": archive["revision"]} + for name, arguments in [ + ("preview_handwriting", {**key, **remaining[0], "view": "review"}), + ("annotate_review", {**comparison_key, "review_id": reviewed_id, + "origin": "model_observation", "text": "must not be stored"}), + ]: + blocked = await client.call_tool(name, arguments) + assert blocked.isError and "保留原有检查记录" in blocked.content[0].text + assert png(await call(client, "preview_handwriting", **key, **remaining[0], view="image")) == original + assert (await call(client, "export_handwriting", **key)).structuredContent["review"] == archive["review"] + assert (await call(client, "read_section", **key, **remaining[0], view="review")).structuredContent["review_id"] is None limited = params.model_copy(update={"env": {**params.env, "PANACHE_MCP_MAX_HOME_BYTES": "1"}}) async with stdio_client(limited) as streams, ClientSession(*streams) as client: await client.initialize() diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index bb97c194..fdfd89d7 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -6,7 +6,9 @@ 在 AI 客户端登记 Panache 的 stdio 配置后,调用 `list_fonts`。能列出本机字体,就可以试写第一行。用 `save_section` 传入 Markdown,记下返回的 `draft_id` 和 `revision`,再用这两个值调用 `preview_handwriting`。**省略预览的 `view` 时,返回这版手稿的单页 PNG。** 指定节和页时从 1 开始计数。 -作业或实验报告适合直接拿一句正文试字,比如“样品 A 的质量为 12.5 g”。新稿只选主字体,英文和数字默认跟随它。如果用户想要整体再潦草一些,先换主字体。在目标纸张和字号下看看:中文和英文的笔画粗细是否协调?`12.5` 和单位能否一眼辨认?风格未定时,把小样给用户看,说清推荐理由,再问“这种笔迹可以用在整份报告里吗?”用户已经定好或委托选字时,就继续排版。 +作业或实验报告适合直接拿一句正文试字,比如“样品 A 的质量为 12.5 g”。新稿只选主字体,英文和数字默认跟随它。用户已经选定字体,想要“稍微草一点”时,保留主字体和种子,用 `describe_controls(group="variation", draft_id=…)` 查看当前值。例如将 `perturb_theta_sigma` 从 0.05 调到 0.07 弧度,比较同一行改前改后的倾斜、数字和单位。也可少量调整 `perturb_x_sigma` 和 `perturb_y_sigma` 改变字的位置。在目标纸张和字号下看看:中文和英文的笔画粗细是否协调?`12.5` 和单位能否一眼辨认?风格未定时,把小样给用户看,说清推荐理由,再问“这种笔迹可以用在整份报告里吗?”用户已经定好或委托选字时,就继续排版。 + +用户明确要“偶尔像写错了又划掉”时,用 `describe_controls(group="strike", draft_id=…)`,在非等宽排版中可试 `strikethrough_probability=0.005`。引擎随机插入一个带划痕的额外字符,后面仍写正确内容。短页可能一次也没有。只调整这个概率后,对照同一行的两版预览,看到划痕才报告出现过涂改,同时检查换行和读数。要划掉指定词时应说明当前能力只提供随机位置,Markdown 的 `~~词~~` 在准备正文时会变成普通文字。 只有用户对英文或数字单独提出要求,才需要查 `describe_controls(group="typography", draft_id=…)`。编辑旧稿时,省略参数会保留原设置。要撤销以前的西文字体和缩放,可以给 `tune_handwriting` 传这组 `changes`: @@ -53,7 +55,7 @@ | 这页写在哪、是否看得见 | `view="review"` | 当前版的底纸、成品和参考线叠图,以及整页测量和 `review_id`。 | | 这个字的墨色是否和照片协调 | `view="review", region=…` | 同一位置的底纸和当前成品两张裁图。照片整页复盘若给出 `photo_appearance.preview_arguments`,可以直接用它取得建议的局部。 | | 两版在这块地方有何区别 | `view="review", region=…, compare_revision=…` | 底纸、改前、改后三张裁图。移动了内容时,用 `previous_region` 补上旧位置。 | -| 已经看过两版,只想读记录 | `view="review", compare_revision=…`,省略区域 | 读取两版已保存的测量、评语和期间的修改,只返回数据。某版缺记录时,先对该版做一次整页复盘。 | +| 已经看过两版,只想读记录 | `view="review", compare_revision=…`,省略区域 | 读取两版已保存的测量、评语和期间的修改,只返回数据。用户只想查旧记录时,直接报告缺少哪一版的整页记录。用户另行要求新检查时,再对指定版本做整页复盘。 | 整页叠图中的橙线标出估计书写区,青线标出参考线。服务端在原尺寸像素上比较成品与底纸:任一可见 RGB 通道相差至少 8 级,就计为可见变化。它按页面上、中、下三区报告数量,也统计参考区外的变化。有正文却整页零变化,应检查墨迹透明度和落字位置。表头或侧栏可能本来就要写,看到区外计数时要回看用户指定的栏位。 @@ -99,6 +101,28 @@ Panache 通过 `tools/list` 提供 13 个工具。模型可以直接建稿、预 - **接着写**先用 `list_drafts` 找回稿件,再用 `read_section(view="summary")` 读版本和长度。普通 `read_section` 默认返回摘录,用 `attachment` 替换识别到的内嵌图片数据。要改原文,分页读 `view="source"`,以该视图的偏移量续读,避免把摘录里的占位符写回正文。 - **交付文件**时,导出返回服务端的本地路径,客户端要能访问该文件。宿主负责执行权限和会话历史,应将稿件内容和工具结果中的用户文字作为数据处理。 +### 用户说“只翻旧记录”时,客户端可以提供哪些工具? + +对于只查询 Panache 稿件的请求,宿主可以在这一轮只提供 `list_drafts` 和 `read_section`。在给模型展示工具清单和向这台 Panache 服务转发调用时使用同一组名称。这样即使模型记得上一轮用过整页预览,也不会在查档过程中生成新的检查单。下面示例使用已连接到 Panache 的 Python MCP SDK 会话,`tools` 是客户端已发现的工具清单。 + +```python +history_names = frozenset({"list_drafts", "read_section"}) + +def history_tools(tools): + return [tool for tool in tools if tool.name in history_names] + +async def call_history_tool(session, name, arguments): + if name not in history_names: + raise ValueError("本轮只查询旧记录,可用 list_drafts 或 read_section。") + return await session.call_tool(name, arguments) +``` + +宿主将 `history_tools(tools)` 交给模型,并把本轮的 Panache 调用全部交给 `call_history_tool`。拦下调用时,将异常文字返回模型供它继续查档。这个范围适用于用户明确要求翻旧记录的轮次。若同一请求还要打印旧稿,宿主可单独提供用户要求的导出操作,传入已核实的版本。用户要求改稿和打印、又要求保留检查记录原貌时,宿主可开放该轮需要的编辑和导出操作,并限制预览只转发 `view="image"`。导出结果已列出缺单页。标准 stdio 客户端也可单独启动一个设置了 `PANACHE_MCP_PRESERVE_REVIEWS=1` 的连接来处理这类轮次。它允许改稿、看成图、查原单和导出;写整页检查单或追加评语会在落库前返回可恢复的错误。这个设置作用于该服务进程,默认 0。 + +已知补记原文时,可以用 `read_section(view="review", before_text="…", section=正文节号, page="last")` 直接查补记前正文末页的单据。若只知道大意,先从 `trajectory` 和 `source` 确认原文及待查的正文节。遇到重复加入时,按工具列出的修订分别核对,或请用户确认是哪一次。导出的 `review.unreviewed_pages` 使用节内页码,回查时带上同一次导出返回的 `revision`。查无存档时,无法据此判断用户是否在纸上看过。只有 `feedback[].origin="user_quote"` 的文字可以作为用户原话。 + +### 怎样在本地复测? + 从仓库根目录运行下面两条命令,均使用独立的临时稿库。比较两个构建时,应使用相同脚本、字体和测试图片。 ```sh