From 834e9bf680038e66301a92a9fe1060bfc08f151b Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:02:51 +0800 Subject: [PATCH 01/24] =?UTF-8?q?feat(crates/handwriting-core):=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E7=85=A7=E7=89=87=E5=9D=90=E6=A0=87=E5=8F=8D?= =?UTF-8?q?=E6=9F=A5=E4=B8=8E=E9=80=8F=E8=A7=86=E9=80=8F=E6=98=8E=E5=A2=A8?= =?UTF-8?q?=E8=BF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:代理需要把照片上的目标位置换算回排版坐标,原照片渲染始终合成底纸。 解决手段:公开照片反投影与经校验的空白纸生成入口,按 PNG/PDF 需求选择投影底层,并验证倾斜横线的坐标往返。 收益:投影稿可导出透明墨迹,PDF 继续使用底纸;同一原照上的位置可以直接校正。 --- crates/handwriting-core/src/photo.rs | 47 ++++++++++++++++++- crates/handwriting-core/src/render.rs | 12 +++++ .../tests/generation_pipeline.rs | 42 +++++++++++++++++ 3 files changed, 100 insertions(+), 1 deletion(-) diff --git a/crates/handwriting-core/src/photo.rs b/crates/handwriting-core/src/photo.rs index e21e1fa7..c46d795e 100644 --- a/crates/handwriting-core/src/photo.rs +++ b/crates/handwriting-core/src/photo.rs @@ -83,6 +83,39 @@ impl PaperProjection { } } + /// Convert a photo-space target to the layout coordinates used by glyph edits. + pub fn paper_point(&self, [x, y]: [f32; 2]) -> [f32; 2] { + match self { + Self::Rotated { + angle, + photo_center, + layout_center, + } => { + let (sin, cos) = (-angle).sin_cos(); + rotate([x, y], *photo_center, *layout_center, sin, cos) + } + Self::Rulings { + first, + step, + layout_edges: [l, r], + columns, + rows, + } => { + let i = rows + .partition_point(|row| height(row, columns, x) < y) + .saturating_sub(1) + .min(rows.len() - 2); + let ya = height(&rows[i], columns, x); + let t = (y - ya) / (height(&rows[i + 1], columns, x) - ya); + let [left, right] = edges(&rows[i], &rows[i + 1], t); + [ + lerp(*l, *r, (x - left) / (right - left)), + first + (i as f32 + t) * step, + ] + } + } + } + /// Inverse-sample just the transparent handwriting and illustration layer. pub fn composite( &self, @@ -90,7 +123,15 @@ impl PaperProjection { ink: &RgbaImage, cancel: &Cancellation, ) -> Result { - let mut out = photo.clone(); + self.composite_into(photo.clone(), ink, cancel) + } + + pub(crate) fn composite_into( + &self, + mut out: RgbaImage, + ink: &RgbaImage, + cancel: &Cancellation, + ) -> Result { match self { Self::Rotated { angle, @@ -220,6 +261,10 @@ mod tests { for (px, py) in [(24, 21), (40, 19), (8, 47), (56, 41)] { assert_eq!(result[(px, py)], Rgba([255, 0, 0, 255])); } + for [x, y] in [[16., 32.], [20., 20.], [43., 27.], [42., 12.]] { + let back = map.paper_point(map.photo_point(x, y)); + assert!((back[0] - x).abs() < 1e-4 && (back[1] - y).abs() < 1e-4); + } assert_eq!(map.photo_point(16., 32.), [8., 47.]); assert_eq!(map.photo_point(48., 32.), [56., 41.]); assert_eq!(result[(32, 32)], photo[(32, 32)]); diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index e63d442d..877554cb 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -346,6 +346,12 @@ pub fn render_until_page Result<()>>( emit, ) } +/// Unmarked preset stationery for comparison with a rendered page. +pub fn preset_paper(w: u32, h: u32, params: &Parameters, limits: &Limits) -> Result { + params.validate(w, h, limits)?; + Ok(blank_paper(w, h, params)) +} + pub fn render_on_photo Result<()>>( r: &RenderRequest, cancel: &Cancellation, @@ -395,6 +401,12 @@ pub(crate) fn render_output Result<()>>( None => paper, }; let output = match photo { + Some((projection, background)) + if r.params.transparent_background && !r.params.pdf_save => + { + let clear = RgbaImage::new(background.width(), background.height()); + projection.composite_into(clear, &image, cancel)? + } Some((projection, background)) => projection.composite(background, &image, cancel)?, None => image, }; diff --git a/crates/handwriting-core/tests/generation_pipeline.rs b/crates/handwriting-core/tests/generation_pipeline.rs index bfcc45c9..0521dd08 100644 --- a/crates/handwriting-core/tests/generation_pipeline.rs +++ b/crates/handwriting-core/tests/generation_pipeline.rs @@ -48,6 +48,48 @@ fn request(text: &str) -> RenderRequest { } } +#[test] +fn projected_ink_only_keeps_photo_coordinates_and_pdf_paper() { + use image::{Rgba, RgbaImage}; + let mut req = request("坐标"); + req.params.fine_edit = true; + req.params.transparent_background = true; + let paper = RgbaImage::from_pixel(300, 220, Rgba([170, 180, 190, 255])); + let map = photo::PaperProjection::Rotated { + angle: 0., + layout_center: [0., 0.], + photo_center: [40., 25.], + }; + let render = |req: &RenderRequest| { + let mut result = None; + handwriting_core::render::render_on_photo( + req, + &Cancellation::default(), + 1, + &map, + &paper, + |_, img| { + result = Some(img); + Ok(()) + }, + ) + .unwrap(); + result.unwrap() + }; + let ink = render(&req); + assert_eq!(ink.dimensions(), paper.dimensions()); + assert_eq!(ink[(0, 0)][3], 0); + let (x, y, _) = ink + .enumerate_pixels() + .find(|(_, _, p)| p[3] == 255) + .unwrap(); + assert!(x >= 40 && y >= 25); + req.params.pdf_save = true; + let on_paper = render(&req); + assert_eq!(on_paper[(0, 0)], paper[(0, 0)]); + assert_eq!(on_paper[(x, y)], ink[(x, y)]); +} + #[test] fn standard_wrap_keeps_words_and_closing_punctuation_with_their_neighbours() { fn lines(text: &str, width: u32) -> Vec { From 58e7028f07988422d569314ce28ce07217273ba0 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:02:52 +0800 Subject: [PATCH 02/24] =?UTF-8?q?feat(crates/panache-mcp):=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=8C=89=E7=85=A7=E7=89=87=E5=9C=88=E9=80=89=E6=A0=A1?= =?UTF-8?q?=E6=AD=A3=E4=B8=8E=E6=88=90=E5=93=81=E5=A4=8D=E7=9B=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:实际斜拍信纸中,识线成功的稿件即使全程看不见正文也能导出;旧接口还须重新建稿才能更改整页参考线。 解决手段:按版本保存校准、上传字体和调整,按照片多边形选字、将字块映射到四角;复盘返回原纸、成品、参考线和像素证据,历史支持回查每轮修改及观察。 收益:模型可根据实际响应和人的位置指示反复校正;导出给出复盘覆盖与可见性提示。独立 stdio 用例覆盖不可见正文、旧版恢复、透视圈选和预览导出一致性。 设计依据:Reflexion 使用外部任务反馈和情节记忆指导后续尝试(https://proceedings.neurips.cc/paper/2023/hash/1b44b878bb782e6954cd888628510e90-Abstract-Conference.html);SICA 对照历史版本和评估(https://github.com/MaximeRobeyns/self_improving_coding_agent)。这里留存按稿件可检验的动作和结果。 --- crates/panache-mcp/src/controls.json | 4 + crates/panache-mcp/src/controls.rs | 23 ++- crates/panache-mcp/src/drafts.rs | 128 ++++++++++++- crates/panache-mcp/src/engine.rs | 173 +++++++++++++++++- crates/panache-mcp/src/inputs.rs | 23 ++- crates/panache-mcp/src/main.rs | 87 +++++---- crates/panache-mcp/src/paper.rs | 2 +- crates/panache-mcp/src/placement.rs | 115 ++++++++++++ crates/panache-mcp/src/review.rs | 264 +++++++++++++++++++++++++++ crates/panache-mcp/src/tuning.rs | 113 ++++++++++++ crates/panache-mcp/tests/smoke.py | 64 +++++++ 11 files changed, 950 insertions(+), 46 deletions(-) create mode 100644 crates/panache-mcp/src/placement.rs create mode 100644 crates/panache-mcp/src/review.rs create mode 100644 crates/panache-mcp/src/tuning.rs diff --git a/crates/panache-mcp/src/controls.json b/crates/panache-mcp/src/controls.json index 87d0ea4c..da9bd23e 100644 --- a/crates/panache-mcp/src/controls.json +++ b/crates/panache-mcp/src/controls.json @@ -13,6 +13,8 @@ "right_margin": {"type":"number","min":0,"max":10000,"unit":"px"}, "top_margin": {"type":"number","min":0,"max":10000,"unit":"px"}, "bottom_margin": {"type":"number","min":0,"max":10000,"unit":"px"}, + "paper": {"type":"choice","values":["plain","ruled","grid","dots"]}, + "seed": {"type":"integer","min":0,"max":4294967295,"unit":"first section seed"}, "width": {"type":"integer","min":1,"max":16000,"unit":"px (preset paper)"}, "height": {"type":"integer","min":1,"max":16000,"unit":"px (preset paper)"}, "layout_style": {"type":"choice","values":["standard","homework"]}, @@ -27,7 +29,9 @@ "latin_digits": {"type":"boolean"} }, "ink": { + "transparent_background": {"type":"boolean","description":"Ink-only PNG preview and ZIP. PDF retains the paper."}, "ink": {"type":"color"}, + "ink_alpha": {"type":"integer","min":0,"max":255,"description":"Alpha channel of the selected RGBA pen color, before ink opacity."}, "ink_opacity": {"type":"integer","min":0,"max":100,"unit":"%"}, "ink_thickness": {"type":"number","min":-2,"max":2,"unit":"px","step":0.1}, "ink_softness": {"type":"number","min":0,"max":2,"unit":"px","step":0.1} diff --git a/crates/panache-mcp/src/controls.rs b/crates/panache-mcp/src/controls.rs index 2e4edf60..592250f8 100644 --- a/crates/panache-mcp/src/controls.rs +++ b/crates/panache-mcp/src/controls.rs @@ -91,13 +91,25 @@ pub fn parameters(draft: &Snapshot<'_>, section: u32, changes: &Changes) -> Resu layout.apply(&mut params); } - if changes.is_empty() { - return Ok(params); - } let mut fields = serde_json::to_value(¶ms)?; for (k, v) in changes { match k.as_str() { - "font" => continue, + "font" | "ink_alpha" => continue, + "seed" => { + fields["seed"] = json!(v.as_u64().context("Invalid seed")? + u64::from(section) - 1) + } + "paper" => { + ensure!( + draft.paper.is_none(), + "Preset paper requires a draft without imported stationery" + ); + fields["underlined"] = json!(v == "ruled"); + fields["paper_pattern"] = if v == "grid" || v == "dots" { + v.clone() + } else { + Value::Null + }; + } "ink" => { let mut tinted = style.clone(); tinted.ink = v.as_str().context("Invalid ink")?.to_owned(); @@ -109,6 +121,9 @@ pub fn parameters(draft: &Snapshot<'_>, section: u32, changes: &Changes) -> Resu _ => fields[k] = v.clone(), } } + if let Some(alpha) = changes.get("ink_alpha") { + fields["fill"][3] = alpha.clone(); + } params = serde_json::from_value(fields)?; params.ink_layers = params.ink_opacity != 100 || params.ink_thickness != 0. || params.ink_softness != 0.; diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index c044d855..a029c6f9 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -21,6 +21,30 @@ pub struct Snapshot<'a> { } impl Snapshot<'_> { + pub fn record_review(&self, section: u32, page: usize, evidence: &Value) -> Result<()> { + self.drafts + .record_review(self.id, self.revision, section, page, evidence) + } + + 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 page_reviews WHERE draft=? AND revision=?", + params![self.id,self.revision], |r|Ok((r.get(0)?,r.get(1)?)))?) + } + 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=?)", + params![self.id, handle], + |r| r.get(0), + )?) + } + pub fn font_bytes(&self, handle: &str) -> Result> { + Ok(self.drafts.connect()?.query_row( + "SELECT bytes FROM draft_fonts WHERE draft=? AND handle=?", + params![self.id, handle], + |r| r.get(0), + )?) + } pub fn camera(&self, paper: Option<&[u8]>) -> Result { let input = serde_json::from_value(Value::Object(self.controls.clone()))?; Ok(handwriting_core::export::CameraMetadata::from_paper( @@ -47,6 +71,7 @@ impl Snapshot<'_> { section: u32, version: u32, edits: &handwriting_core::fine_edit::Adjustments, + details: &Value, ) -> Result { let mut db = self.drafts.connect()?; let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; @@ -62,6 +87,10 @@ impl Snapshot<'_> { serde_json::to_string(edits)? ], )?; + tx.execute( + "INSERT INTO edit_notes VALUES(?,?,?)", + params![self.id, next, details.to_string()], + )?; tx.commit()?; Ok(next) } @@ -78,6 +107,7 @@ impl Snapshot<'_> { } } +#[derive(Clone)] pub struct Section { pub number: u32, pub version: u32, @@ -113,6 +143,22 @@ impl Drafts { revision INTEGER NOT NULL, source TEXT NOT NULL, prepared TEXT NOT NULL, PRIMARY KEY(draft,number,revision) ); + CREATE TABLE IF NOT EXISTS paper_layouts ( + draft TEXT NOT NULL, revision INTEGER NOT NULL, layout TEXT NOT NULL, + PRIMARY KEY(draft,revision) + ); + CREATE TABLE IF NOT EXISTS draft_fonts ( + draft TEXT NOT NULL, handle TEXT NOT NULL, bytes BLOB NOT NULL, + PRIMARY KEY(draft,handle) + ); + CREATE TABLE IF NOT EXISTS edit_notes ( + draft TEXT NOT NULL, revision INTEGER NOT NULL, details TEXT NOT NULL, + PRIMARY KEY(draft,revision) + ); + CREATE TABLE IF NOT EXISTS page_reviews ( + draft TEXT NOT NULL, revision INTEGER NOT NULL, section INTEGER NOT NULL, + page INTEGER NOT NULL, evidence TEXT NOT NULL, PRIMARY KEY(draft,revision,section,page) + ); CREATE TABLE IF NOT EXISTS papers ( draft TEXT PRIMARY KEY REFERENCES drafts(id), layout TEXT NOT NULL, image BLOB NOT NULL ); @@ -240,13 +286,20 @@ impl Drafts { Some((r, layout, s)) => (r, layout, serde_json::from_str(&s)?), None => (0, 0, crate::controls::Changes::new()), }; + let updated_layout: Option = self.connect()?.query_row( + "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 { controls, settings_revision, layout_revision, id, drafts: self, - paper: layout.as_deref().map(serde_json::from_str).transpose()?, + paper: updated_layout + .or(layout) + .as_deref() + .map(serde_json::from_str) + .transpose()?, revision, style: serde_json::from_str(&style)?, }) @@ -255,7 +308,10 @@ impl Drafts { &self, draft: &Snapshot<'_>, controls: &crate::controls::Changes, - camera_only: bool, + preserve_layout: bool, + paper: Option<&PaperLayout>, + font: Option<(&str, &[u8])>, + details: &Value, ) -> Result { let mut db = self.connect()?; let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; @@ -264,7 +320,23 @@ impl Drafts { "INSERT INTO settings VALUES (?1,?2,?3)", params![draft.id, next, serde_json::to_string(controls)?], )?; - if camera_only { + if let Some(paper) = paper { + tx.execute( + "INSERT INTO paper_layouts VALUES(?,?,?)", + params![draft.id, next, serde_json::to_string(paper)?], + )?; + } + if let Some((handle, bytes)) = font { + tx.execute( + "INSERT INTO draft_fonts VALUES(?,?,?)", + params![draft.id, handle, bytes], + )?; + } + tx.execute( + "INSERT INTO edit_notes VALUES(?,?,?)", + params![draft.id, next, details.to_string()], + )?; + if preserve_layout { tx.execute( "INSERT INTO camera_revisions VALUES (?1,?2,?3)", params![draft.id, next, draft.layout_revision], @@ -284,6 +356,56 @@ impl Drafts { ); Ok(next) } + pub fn record_review( + &self, + id: &str, + rev: u32, + section: u32, + page: usize, + evidence: &Value, + ) -> Result<()> { + self.connect()?.execute( + "INSERT OR REPLACE INTO page_reviews VALUES(?,?,?,?,?)", + params![id, rev, section, u32::try_from(page)?, evidence.to_string()], + )?; + Ok(()) + } + + pub fn trajectory(&self, id: &str, rev: u32, offset: u32, limit: u32) -> Result { + ensure!((1..=50).contains(&limit), "Trajectory limit must be 1..50"); + let db = self.connect()?; + let mut stmt=db.prepare( + "WITH events(revision,action,section,page,evidence) AS ( + SELECT revision,'save_section',number,NULL,NULL FROM sections WHERE draft=?1 + UNION ALL SELECT revision,'tune_handwriting',NULL,NULL,NULL FROM settings WHERE draft=?1 + UNION ALL SELECT revision,'adjust_glyphs',section,NULL,NULL FROM glyph_edits WHERE draft=?1 + UNION ALL SELECT revision,'page_review',section,page,evidence FROM page_reviews WHERE draft=?1 + ) + SELECT e.revision,e.action,e.section,COALESCE(e.page,json_extract(n.details,'$.page')), + COALESCE(e.evidence,n.details,'{}') + FROM events e LEFT JOIN edit_notes n ON n.draft=?1 AND n.revision=e.revision + WHERE e.revision<=?2 + ORDER BY e.revision DESC,(e.action='page_review') DESC,e.section,e.page + LIMIT ?3 OFFSET ?4")?; + let mut entries = Vec::new(); + let mut rows = stmt.query(params![id, rev, limit + 1, offset])?; + while let Some(row) = rows.next()? { + let details: String = row.get(4)?; + entries.push(json!({ + "revision":row.get::<_,u32>(0)?, + "action":row.get::<_,String>(1)?, + "section":row.get::<_,Option>(2)?, + "page":row.get::<_,Option>(3)?, + "details":serde_json::from_str::(&details)?, + })); + } + let more = entries.len() > limit as usize; + entries.truncate(limit as usize); + Ok( + json!({"draft_id":id,"revision":rev,"events":entries,"next_offset":if more {offset.checked_add(limit)} else {None}}), + ) + } + pub fn review( &self, id: &str, diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index b10d7eba..e5136a0f 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -19,6 +19,33 @@ use crate::{ use handwriting_core::fine_edit::{self, Adjustment, Adjustments}; use serde_json::{Value, json}; +// Coordinates relative to the original tile center, transformed in paint order. +fn glyph_point( + g: &fine_edit::GlyphBounds, + edit: Option<&Adjustment>, + mut offset: [f64; 2], +) -> [f32; 2] { + let [x, y, w, h] = g.bounds; + let mut center = [x as f64 + w as f64 / 2., y as f64 + h as f64 / 2.]; + if let Some(e) = edit { + center[0] += f64::from(e.dx); + center[1] += f64::from(e.dy); + let (sin, cos) = f64::from(e.angle).to_radians().sin_cos(); + let scale = f64::from(e.scale) / 100.; + let [u, v] = offset; + offset = [scale * (cos * u - sin * v), scale * (sin * u + cos * v)]; + if let Some([a, b, c, d, f, k, g, h]) = e.warp { + let [u, v] = offset; + let z = g * u + h * v + 1.; + offset = [(a * u + b * v + c) / z, (d * u + f * v + k) / z]; + } + } + [ + (center[0] + offset[0]) as f32, + (center[1] + offset[1]) as f32, + ] +} + struct CachedPage { draft: String, section: u32, @@ -94,11 +121,22 @@ impl Engine { .and_then(serde_json::Value::as_str) .unwrap_or(&draft.style.font); ensure!( - self.names.iter().any(|f| f == font_name), + font_name.starts_with("upload:") || self.names.iter().any(|f| f == font_name), "Font no longer available: {}", font_name ); - let primary = self.font(font_name)?; + let primary = if font_name.starts_with("upload:") { + let key = format!("{}:{}", draft.id, font_name); + if let Some(font) = self.fonts.get(&key) { + font.clone() + } else { + let font = FontBook::load(&draft.font_bytes(font_name)?)?; + self.fonts.insert(key, font.clone()); + font + } + } else { + self.font(font_name)? + }; let fonts = FontBook::with_text_fallbacks(primary, §ion.text, |name| { if self.names.iter().any(|n| n == name) { self.font(name).map(Some) @@ -211,6 +249,41 @@ impl Engine { req.params.fine_edit = true; Ok(req) } + pub fn review_baselines( + &mut self, + draft: &Snapshot<'_>, + section: Section, + page: usize, + cancel: &Cancellation, + ) -> Result> { + let req = self.fine_request(draft, section)?; + let (_, glyphs) = fine_edit::inspect_page(&req, page, cancel)?; + let edits = req + .params + .fine_edits + .as_ref() + .map(|v| { + v.glyphs + .iter() + .map(|e| (e.id, e)) + .collect::>() + }) + .unwrap_or_default(); + let stride = glyphs.len().div_ceil(384).max(1); + Ok(glyphs + .iter() + .filter(|g| g.illustration.is_none()) + .step_by(stride) + .map(|g| { + let dy = f64::from(g.baseline - g.bounds[1]) - f64::from(g.bounds[3]) / 2.; + crate::review::photo_point( + draft, + glyph_point(g, edits.get(&g.id).copied(), [0., dy]), + ) + }) + .collect()) + } + pub fn layout( &mut self, draft: &Snapshot<'_>, @@ -228,6 +301,27 @@ impl Engine { if input.illustrations_only == Some(true) { bounds.retain(|g| g.illustration.is_some()); } + let edits = req + .params + .fine_edits + .as_ref() + .map(|v| { + v.glyphs + .iter() + .map(|e| (e.id, e)) + .collect::>() + }) + .unwrap_or_default(); + let center = |g: &fine_edit::GlyphBounds| { + crate::review::photo_point(draft, glyph_point(g, edits.get(&g.id).copied(), [0., 0.])) + }; + if let Some(poly) = &input.region { + ensure!( + (3..=32).contains(&poly.len()), + "Use 3..32 vertices in image pixels" + ); + bounds.retain(|g| crate::review::contains(poly, center(g))); + } let utf16: Vec<_> = req.text.encode_utf16().collect(); let rows: Vec<_> = bounds .iter() @@ -235,6 +329,9 @@ impl Engine { .take(limit) .map(|g| { let mut row = json!({"id":g.id,"bounds":g.bounds}); + if input.region.is_some() { + row["selected_center"] = json!(center(g)); + } if let Some(parent) = g.illustration { row["kind"] = json!(if parent == g.id { "illustration" @@ -277,6 +374,12 @@ impl Engine { .and_then(|v| v.glyphs.iter().find(|e| e.id == g.id)) { row["adjustment"] = json!(edit); + let w = f64::from(g.bounds[2]) / 2.; + let h = f64::from(g.bounds[3]) / 2.; + row["current_photo_quad"] = + json!([[-w, -h], [w, -h], [w, h], [-w, h]].map(|uv| { + crate::review::photo_point(draft, glyph_point(g, Some(edit), uv)) + })); } row }) @@ -300,7 +403,9 @@ impl Engine { "Choose 1..32 distinct glyph IDs" ); ensure!( - input.dx.is_some() + input.target_quad.is_some() + || input.place_center.is_some() + || input.dx.is_some() || input.dy.is_some() || input.scale.is_some() || input.angle.is_some() @@ -363,6 +468,55 @@ impl Engine { .flat_map(|v| v.glyphs) .map(|e| (e.id, e)) .collect(); + let params = &req.params; + let [w, h] = draft + .paper + .as_ref() + .map(|p| p.photo_size.unwrap_or([p.width, p.height])) + .unwrap_or([params.width.unwrap_or(0), params.height.unwrap_or(0)]); + let placement = if let Some(quad) = input.target_quad { + ensure!( + input.place_center.is_none() + && input.dx.is_none() + && input.dy.is_none() + && input.angle.is_none() + && input.scale.is_none() + && input.shape.is_none(), + "Use target_quad separately from other geometry fields" + ); + Some(crate::placement::Placement::new( + draft, + [w, h], + &bounds, + &ids, + quad, + )?) + } else { + None + }; + let translation = if let Some(target) = input.place_center { + ensure!( + input.dx.is_none() && input.dy.is_none() && input.shape.is_none(), + "Use place_center separately from dx/dy/shape" + ); + ensure!(target[0] < w && target[1] < h, "Target outside the page"); + let projection = draft.paper.as_ref().and_then(|p| p.projection.as_ref()); + let dest = target.map(|v| v as f32); + let dest = projection.map_or(dest, |p| p.paper_point(dest)); + let mut mean = [0., 0.]; + for g in bounds.iter().filter(|g| ids.contains(&g.id)) { + let pos = glyph_point(g, edits.get(&g.id), [0., 0.]); + for axis in 0..2 { + mean[axis] += pos[axis] / ids.len() as f32; + } + } + Some([ + (dest[0] - mean[0]).round() as i32, + (dest[1] - mean[1]).round() as i32, + ]) + } else { + None + }; for id in ids { let e = edits.entry(id).or_insert(Adjustment { id, @@ -380,6 +534,9 @@ impl Engine { .iter() .find(|g| g.id == id) .context("Unknown glyph")?; + if let Some(map) = &placement { + map.apply(e, glyph.bounds)?; + } if let Some(shape) = &input.shape { let height = f64::from(glyph.bounds[3].max(1)); let ratio = f64::from(shape.top_width_percent) / 100.; @@ -401,6 +558,14 @@ impl Engine { ]) }; } + if let Some([dx, dy]) = translation { + e.dx = e.dx.checked_add(dx).context("Position overflow")?; + e.dy = e.dy.checked_add(dy).context("Position overflow")?; + ensure!( + (-65535..=65535).contains(&e.dx) && (-65535..=65535).contains(&e.dy), + "Move exceeds the supported layout range" + ); + } e.dx = input.dx.unwrap_or(e.dx); e.dy = input.dy.unwrap_or(e.dy); e.angle = input.angle.unwrap_or(e.angle); @@ -425,6 +590,7 @@ impl Engine { key, glyphs: edits.into_values().collect(), }, + &json!({"page":input.page,"ids":input.ids,"place_center":input.place_center,"target_quad":input.target_quad,"dx":input.dx,"dy":input.dy,"scale":input.scale,"angle":input.angle,"shape":input.shape,"opacity":input.opacity,"thickness":input.thickness,"softness":input.softness,"color":input.color,"note":input.note}), ) } pub fn export( @@ -446,6 +612,7 @@ impl Engine { cancel.check()?; let (_, edits) = draft.edits(§ion)?; 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)?; diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 2083279a..eccf5d65 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -66,7 +66,7 @@ pub enum PaperMode { Flatten, } -#[derive(Deserialize, JsonSchema)] +#[derive(serde::Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Guide { /// Zero-based writable ruling number, counted from the first supplied ruling. @@ -112,10 +112,17 @@ pub struct Describe { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Tune { + /// Replace the writing area on the saved paper, using 2..32 photo-space baselines. Pass [] to restore the original import calibration. Existing text is reflowed. Use the top and bottom writable lines even on unruled paper. + pub paper_guides: Option>, + /// Import an absolute local TTF/OTF file into this draft. Its bytes are retained across restarts. + pub font_path: Option, + /// Brief observable issue or user instruction that motivated this edit (max 320 characters). + pub note: Option, pub draft_id: String, pub expected_revision: u32, /// Sparse name/value patch from describe_controls. Null restores the original setting. - pub changes: std::collections::BTreeMap, + #[serde(default)] + pub changes: serde_json::Map, } #[derive(Deserialize, JsonSchema)] @@ -127,6 +134,7 @@ pub struct List { #[derive(Clone, Copy, Default, Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "snake_case")] pub enum ReadView { + Trajectory, #[default] Excerpt, Summary, @@ -151,12 +159,13 @@ pub struct Read { #[derive(Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PreviewView { + Review, Paper, Image, Layout, } -#[derive(Deserialize, JsonSchema)] +#[derive(serde::Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Shape { /// Horizontal shear in degrees, -20..20. Positive displaces the bottom to the right. @@ -168,12 +177,18 @@ pub struct Shape { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Nudge { + /// Optional short user feedback or observable reason to retain with this revision. + pub note: Option, pub draft_id: String, pub expected_revision: u32, pub section: u32, pub page: usize, /// Up to 32 glyph IDs from preview_handwriting(view="layout") on this page. pub ids: Vec, + /// Move this selection as a group so its mean glyph center lands at [x,y] on the preview. Use separately from dx, dy and shape. + pub place_center: Option<[u32; 2]>, + /// Absolute placement of the original selected block into four image pixels (TL,TR,BR,BL). Replaces prior geometric edits for these IDs. Exclusive with other geometry changes. + pub target_quad: Option<[[u32; 2]; 4]>, /// Absolute offsets in pixels from the original glyph position. Omitted fields retain their values. pub dx: Option, pub dy: Option, @@ -196,6 +211,8 @@ pub struct Nudge { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Preview { + /// Layout only. Select glyph centers in this polygon (3..32 original image pixel pairs). Returned IDs can be adjusted together. + pub region: Option>, /// In layout view, only return illustration outlines and isolated details. pub illustrations_only: Option, /// "image" (default), "paper" for the saved stationery alone, or "layout" for base glyph geometry. diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index e615b5e9..5274a78a 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -4,6 +4,9 @@ mod engine; mod inputs; mod markdown; mod paper; +mod placement; +mod review; +mod tuning; use anyhow::{Context, Result, ensure}; use drafts::Drafts; @@ -180,7 +183,7 @@ impl ServerHandler for Panache { use rmcp::model::{Implementation, ServerCapabilities, ServerConfig}; ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) .with_server_info(Implementation::new("panache-mcp", handwriting_core::app_version())) - .with_instructions("Drafts contain versioned Markdown sections. Images, the saved paper and per-glyph geometry are available on demand. Photo-space coordinates describe the preview; local adjustments use paper-space pixels.") + .with_instructions("Drafts contain versioned Markdown sections. Images, the saved paper and per-glyph geometry are available on demand. Photo-space coordinates describe the preview; local adjustments use paper-space pixels. For photo placement use preview_handwriting(view=review), compare the three labeled images, ask the user about ambiguous regions, and review the edited revision. Read view=trajectory to revisit actions and evidence.") } } @@ -221,6 +224,12 @@ impl Panache { .and_then(|v| v.as_str()) .unwrap_or(&draft.style.font) ), + "paper" => draft + .controls + .get(k) + .cloned() + .unwrap_or(json!(draft.style.paper)), + "ink_alpha" => json!(params.fill[3]), "ink" => json!( draft .controls @@ -246,31 +255,21 @@ impl Panache { } #[tool( - description = "Tune a saved draft with a sparse control patch; returns a new revision. Preview that revision before export." + description = "Revise a draft: change controls, import a local font_path, or replace paper_guides on its saved image. For a special writing area ask the user for first/last writable baselines. Review the new revision before export." )] - fn tune_handwriting(&self, Parameters(input): Parameters) -> CallToolResult { - tool_result((|| { - let draft = self - .0 - .drafts - .snapshot(&input.draft_id, Some(input.expected_revision))?; - let changes = controls::merge( - &draft.controls, - &input.changes.into_iter().collect(), - &self.0.fonts, - )?; - ensure!(changes != draft.controls, "No control values changed"); - controls::parameters(&draft, 1, &changes)?; - let camera_only = changes.keys().chain(draft.controls.keys()).all(|key| { - controls::catalog()["camera"].get(key).is_some() - || changes.get(key) == draft.controls.get(key) - }); - let next = self.0.drafts.tune(&draft, &changes, camera_only)?; - Ok(reply( - format!("Saved revision {next}."), - json!({"draft_id":draft.id,"revision":next,"controls":changes,"fine_layout":if camera_only { "preserved" } else { "inspect_again" }}), - )) - })()) + async fn tune_handwriting(&self, Parameters(input): Parameters) -> CallToolResult { + let state = self.0.clone(); + tool_result( + async { + let permit = state.prepare_slot.clone().acquire_owned().await?; + tokio::task::spawn_blocking(move || { + let _permit = permit; + tuning::apply(&state, input) + }) + .await? + } + .await, + ) } #[tool( @@ -316,11 +315,20 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "Read one section: summary, excerpt (default, image data omitted), or exact source. Offset counts Unicode characters in the selected view." + description = "Read view=trajectory for recent draft edits, user-provided edit notes and page review evidence (offset/limit count events). Other views read one section: summary, excerpt (default, image data omitted), or exact source. Offset counts Unicode characters in the selected view." )] fn read_section(&self, Parameters(input): Parameters) -> CallToolResult { tool_result((|| { let draft = self.0.drafts.snapshot(&input.draft_id, input.revision)?; + if input.view == Some(ReadView::Trajectory) { + let result = self.0.drafts.trajectory( + draft.id, + draft.revision, + input.offset.unwrap_or(0), + input.limit.unwrap_or(12), + )?; + return Ok(reply(result.to_string(), result)); + } let mut result = self.0.drafts.review( &input.draft_id, draft.revision, @@ -353,8 +361,8 @@ impl Panache { } #[tool( - annotations(read_only_hint = true, open_world_hint = false), - description = "Preview one page. Default image; view=layout returns base glyph boxes [x,y,width,height] in pixels, paginated with offset/limit, for adjust_glyphs. view=paper gives the saved background alone. Set illustrations_only=true in layout for editable diagram outlines and details. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline in image pixels." + annotations(open_world_hint = false), + description = "Preview one page. view=review returns paper, finished image, reference overlay and visible ink evidence. Compare top/middle/bottom alignment and ink appearance. Use layout with region (photo pixel polygon) to select glyph IDs; view=layout returns base glyph boxes [x,y,width,height] in pixels, paginated with offset/limit, for adjust_glyphs. view=paper gives the saved background alone. Set illustrations_only=true in layout for editable diagram outlines and details. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline in image pixels." )] async fn preview_handwriting( &self, @@ -365,6 +373,7 @@ impl Panache { .render(ctx, move |state, engine, cancel| { let draft = state.drafts.snapshot(&input.draft_id, input.revision)?; ensure!(input.illustrations_only.is_none() || input.view==Some(PreviewView::Layout),"illustrations_only requires view=layout"); + ensure!(input.region.is_none() || input.view==Some(PreviewView::Layout),"region requires layout view"); if input.view==Some(PreviewView::Paper){ ensure!(input.offset.is_none() && input.limit.is_none() && input.section.is_none() && input.page.is_none(),"view=paper takes only draft_id and revision"); let bytes=draft.background()?.context("No imported paper for this draft")?; @@ -380,6 +389,12 @@ impl Panache { .pop() .context("Empty draft")?; let page = input.page.unwrap_or(1); + if input.view == Some(PreviewView::Review) { + ensure!(input.limit.is_none() && input.offset.is_none(),"Review a single page without pagination"); + let baselines=engine.review_baselines(&draft,section.clone(),page,cancel)?; + let (png,_)=engine.preview(&draft,section,page,cancel)?; + return review::page(&draft,number,page,&png,&baselines,cancel); + } if input.view == Some(PreviewView::Layout) { let result = engine.layout(&draft, section, &input, cancel)?; return Ok(reply(result.to_string(), result)); @@ -404,7 +419,7 @@ impl Panache { } #[tool( - description = "Adjust selected glyphs in one section/page by IDs from its layout view. Use the same revision. Offsets and shape are in paper space before sheet projection. Shape applies additional local shear or taper." + description = "Adjust selected glyphs in one section/page by IDs from its layout view. Use the same revision. Offsets and shape are in paper space before sheet projection. Use place_center for a group move; target_quad maps the entire selected text block into four corners on the image. Shape adjusts each glyph individually." )] async fn adjust_glyphs( &self, @@ -421,6 +436,10 @@ impl Panache { .sections(draft.id, draft.revision, Some(input.section))? .pop() .context("Unknown section")?; + ensure!( + input.note.as_ref().is_none_or(|s| s.chars().count() <= 320), + "Note exceeds 320 characters" + ); let next = engine.adjust(&draft, section, &input, cancel)?; Ok(reply( format!("Saved revision {next}."), @@ -432,7 +451,7 @@ impl Panache { } #[tool( - description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns absolute path and actual page count." + description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns path and page count. For visual acceptance, inspect view=review on the intended revision first, especially after moving glyphs or changing ink." )] async fn export_handwriting( &self, @@ -444,6 +463,9 @@ 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 (path, pages) = engine.export( &state.output, &draft, sections, input.format.unwrap_or_default(), cancel, |pages| { @@ -454,9 +476,10 @@ impl Panache { } }, )?; - let message = format!("已导出 **{pages} 页**(版本 {})。\n\n`{}`", draft.revision, path.display()); + let warning=if zero_text_ink || visibility_flags>0 {"墨迹可见性需要复查。"}else{""}; + let message = format!("已导出 **{pages} 页**(版本 {})。该版已有 {reviewed}/{pages} 页复盘证据。{warning}可用 preview_handwriting(view=review) 核对成品。\n\n`{}`", draft.revision, path.display()); Ok(reply(message, json!({ - "draft_id": input.draft_id, "revision": draft.revision, "path": path, "pages": pages + "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} }))) }).await; tool_result(result) diff --git a/crates/panache-mcp/src/paper.rs b/crates/panache-mcp/src/paper.rs index 7c736ed3..ea1f87c9 100644 --- a/crates/panache-mcp/src/paper.rs +++ b/crates/panache-mcp/src/paper.rs @@ -41,7 +41,7 @@ impl PaperLayout { } data } - fn from_guides(width: u32, height: u32, guides: &[Guide]) -> Result { + pub fn from_guides(width: u32, height: u32, guides: &[Guide]) -> Result { ensure!( (2..=32).contains(&guides.len()) && guides[0].row == 0, "Supply 2..32 guides starting at row 0" diff --git a/crates/panache-mcp/src/placement.rs b/crates/panache-mcp/src/placement.rs new file mode 100644 index 00000000..5eedd378 --- /dev/null +++ b/crates/panache-mcp/src/placement.rs @@ -0,0 +1,115 @@ +//! Place a selection's original layout rectangle into four corners on the photograph. +use crate::drafts::Snapshot; +use anyhow::{Result, ensure}; +use handwriting_core::fine_edit::{Adjustment, GlyphBounds}; +use std::collections::BTreeSet; + +pub struct Placement { + // Paper-space homography normalized at the selection's top left. + matrix: [f64; 8], + origin: [f64; 2], +} +impl Placement { + pub fn new( + draft: &Snapshot<'_>, + size: [u32; 2], + glyphs: &[GlyphBounds], + ids: &BTreeSet, + quad: [[u32; 2]; 4], + ) -> Result { + let mut corners = [[0.; 2]; 4]; + let map = draft.paper.as_ref().and_then(|p| p.projection.as_ref()); + for (dst, src) in corners.iter_mut().zip(quad) { + ensure!( + src[0] < size[0] && src[1] < size[1], + "Target corner outside the image" + ); + let pt = src.map(|v| v as f32); + *dst = map.map_or(pt, |m| m.paper_point(pt)).map(f64::from); + } + for i in 0..4 { + let [a, b, c] = [corners[i], corners[(i + 1) % 4], corners[(i + 2) % 4]]; + ensure!( + (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) > 0.01, + "Supply a convex TL, TR, BR, BL quadrilateral" + ); + } + let mut left = f64::INFINITY; + let mut top = f64::INFINITY; + let mut right = f64::NEG_INFINITY; + let mut bottom = f64::NEG_INFINITY; + for g in glyphs.iter().filter(|g| ids.contains(&g.id)) { + let [x, y, w, h] = g.bounds.map(f64::from); + left = left.min(x); + top = top.min(y); + right = right.max(x + w); + bottom = bottom.max(y + h); + } + let (w, h) = (right - left, bottom - top); + ensure!(w > 0. && h > 0., "Empty selection"); + let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = corners; + let (ax, ay) = (x1 - x2, y1 - y2); + let (bx, by) = (x3 - x2, y3 - y2); + let (dx, dy) = (x0 - x1 + x2 - x3, y0 - y1 + y2 - y3); + // Solve the two perspective coefficients of the unit-square-to-quad map. + let det = ax * by - ay * bx; + let g = (dx * by - dy * bx) / det; + let k = (ax * dy - ay * dx) / det; + Ok(Self { + origin: [left, top], + matrix: [ + (x1 * (1. + g) - x0) / w, + (x3 * (1. + k) - x0) / h, + x0, + (y1 * (1. + g) - y0) / w, + (y3 * (1. + k) - y0) / h, + y0, + g / w, + k / h, + ], + }) + } + + pub fn apply(&self, edit: &mut Adjustment, bounds: [i32; 4]) -> Result<()> { + let [x, y, w, h] = bounds.map(f64::from); + let center = [x + w / 2., y + h / 2.]; + let (u, v) = (center[0] - self.origin[0], center[1] - self.origin[1]); + let [a, b, c, d, e, f, g, k] = self.matrix; + let z = 1. + g * u + k * v; + ensure!( + z.is_finite() && z > 1e-8, + "Selection crosses the perspective horizon" + ); + let nx = a * u + b * v + c; + let ny = d * u + e * v + f; + edit.dx = (nx / z - center[0]).round() as i32; + edit.dy = (ny / z - center[1]).round() as i32; + let (cx, cy) = ( + center[0] + f64::from(edit.dx), + center[1] + f64::from(edit.dy), + ); + // The renderer applies a tile-local transform around the translated center. + // Conjugate the shared block transform into that frame, retaining subpixel translation. + let warp = [ + a - cx * g, + b - cx * k, + nx - cx * z, + d - cy * g, + e - cy * k, + ny - cy * z, + g, + k, + ] + .map(|p| p / z); + ensure!( + warp.iter().all(|p| p.abs() <= 65535.) + && (-65535..=65535).contains(&edit.dx) + && (-65535..=65535).contains(&edit.dy), + "Perspective exceeds supported coordinates" + ); + edit.angle = 0; + edit.scale = 100; + edit.warp = Some(warp); + Ok(()) + } +} diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs new file mode 100644 index 00000000..793387cc --- /dev/null +++ b/crates/panache-mcp/src/review.rs @@ -0,0 +1,264 @@ +use crate::{controls, drafts::Snapshot, reply}; +use anyhow::{Result, ensure}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use handwriting_core::{Cancellation, Limits, export, imaging}; +use image::{Pixel, Rgba, RgbaImage, imageops}; +use rmcp::model::{CallToolResult, ContentBlock}; +use serde_json::json; + +pub fn photo_point(draft: &Snapshot<'_>, [x, y]: [f32; 2]) -> [f32; 2] { + draft + .paper + .as_ref() + .and_then(|p| p.projection.as_ref()) + .map_or([x, y], |m| m.photo_point(x, y)) +} + +// Even–odd crossings also handle concave freehand selections. +pub fn contains(poly: &[[i32; 2]], [x, y]: [f32; 2]) -> bool { + poly.iter() + .zip(poly.iter().cycle().skip(1)) + .filter(|(a, b)| { + let [ax, ay] = a.map(|v| v as f32); + let [bx, by] = b.map(|v| v as f32); + (ay > y) != (by > y) && x < (bx - ax) * (y - ay) / (by - ay) + ax + }) + .count() + % 2 + == 1 +} + +fn thumbnail(img: &RgbaImage) -> RgbaImage { + let scale = (900. / img.width().max(img.height()) as f32).min(1.); + imageops::thumbnail( + img, + (img.width() as f32 * scale).round().max(1.) as u32, + (img.height() as f32 * scale).round().max(1.) as u32, + ) +} +fn draw_path(img: &mut RgbaImage, points: &[[f32; 2]], sx: f32, sy: f32, color: Rgba) { + for pair in points.windows(2) { + let (x, y) = (pair[0][0] * sx, pair[0][1] * sy); + let (dx, dy) = (pair[1][0] * sx - x, pair[1][1] * sy - y); + let steps = dx.abs().max(dy.abs()).ceil().clamp(1., 2048.) as u32; + for i in 0..=steps { + let t = i as f32 / steps as f32; + let (px, py) = ((x + dx * t).round() as i32, (y + dy * t).round() as i32); + if px >= 0 && py >= 0 && px < img.width() as i32 && py < img.height() as i32 { + img.put_pixel(px as u32, py as u32, color); + } + } + } +} + +// Look for a continuous dark ridge in the untouched paper, on both sides of +// the glyph baseline. No contrast support means unknown, including blank paper. +fn ruling_offset(paper: &RgbaImage, point: [f32; 2], radius: i32) -> Option { + let [x, y] = point.map(|n| n.round() as i32); + if x < 3 + || x >= paper.width() as i32 - 3 + || y < radius + 3 + || y >= paper.height() as i32 - radius - 3 + { + return None; + } + let light = + |dx: i32, dy: i32| i32::from(paper[((x + dx) as u32, (y + dy) as u32)].to_luma()[0]); + let score = |dy: i32| { + (-3..=3) + .map(|dx| (light(dx, dy - 3).min(light(dx, dy + 3)) - light(dx, dy)).max(0)) + .sum::() + }; + let best = (-radius..=radius) + .map(|dy| (score(dy), -dy.abs(), dy)) + .max()?; + (best.0 >= 7 * 8).then_some(best.2) +} + +pub fn page( + draft: &Snapshot<'_>, + section: u32, + page: usize, + png: &str, + baselines: &[[f32; 2]], + cancel: &Cancellation, +) -> Result { + let params = controls::parameters(draft, section, &draft.controls)?; + let bytes = STANDARD.decode(png)?; + let limits = Limits { + max_file_bytes: bytes.len(), + ..Default::default() + }; + let mut finished = imaging::decode(&bytes, &limits)?.into_rgba8(); + drop(bytes); + let paper = match draft.background()? { + Some(b) => imaging::decode(&b, &Limits::default())?.into_rgba8(), + None => handwriting_core::render::preset_paper( + finished.width(), + finished.height(), + ¶ms, + &limits, + )?, + }; + ensure!( + paper.dimensions() == finished.dimensions(), + "Paper and output dimensions differ" + ); + let (w, h) = paper.dimensions(); + // The reference is anchored to the imported stationery, independent of later margin adjustments. + let (left, right, top, bottom, step) = draft.paper.as_ref().map_or( + ( + params.left_margin, + w as f32 - params.right_margin, + params.top_margin, + h as f32 - params.bottom_margin, + params.line_spacing, + ), + |p| { + ( + p.left as f32, + (p.width - p.right) as f32, + p.top as f32, + (p.height - p.bottom) as f32, + p.line_spacing, + ) + }, + ); + let path = |y: f32| { + (0..=16) + .map(|i| photo_point(draft, [left + (right - left) * i as f32 / 16., y])) + .collect::>() + }; + let mut perimeter = path(top); + let steps = ((bottom - top) / step).ceil().clamp(1., 512.) as u32; + for i in 1..=steps { + perimeter.push(photo_point( + draft, + [right, top + (bottom - top) * i as f32 / steps as f32], + )); + } + perimeter.extend(path(bottom).into_iter().rev()); + for i in (0..steps).rev() { + perimeter.push(photo_point( + draft, + [left, top + (bottom - top) * i as f32 / steps as f32], + )); + } + let mut changed = [0u64; 3]; + let mut outside = 0u64; + let mut peak = 0; + for y in 0..h { + cancel.check()?; + let mut cuts = Vec::new(); + let cy = y as f32 + 0.5; + for seg in perimeter.windows(2) { + let ([ax, ay], [bx, by]) = (seg[0], seg[1]); + if (ay > cy) != (by > cy) { + cuts.push(ax + (cy - ay) * (bx - ax) / (by - ay)); + } + } + cuts.sort_by(f32::total_cmp); + for x in 0..w { + let base = paper[(x, y)]; + let pixel = &mut finished[(x, y)]; + if params.transparent_background { + let mut composite = base; + composite.blend(pixel); + *pixel = composite; + } + let white = |p: Rgba, c: usize| { + 255 - ((255 - u16::from(p[c])) * u16::from(p[3])).div_ceil(255) + }; + let delta = (0..3) + .map(|c| white(*pixel, c).abs_diff(white(base, c))) + .max() + .unwrap(); + peak = peak.max(delta); + if delta >= 8 { + changed[(y as usize * 3 / h as usize).min(2)] += 1; + if cuts.partition_point(|v| *v <= x as f32 + 0.5) % 2 == 0 { + outside += 1; + } + } + } + } + let result = thumbnail(&finished); + let mut overlay = result.clone(); + let (sx, sy) = ( + overlay.width() as f32 / w as f32, + overlay.height() as f32 / h as f32, + ); + draw_path(&mut overlay, &perimeter, sx, sy, Rgba([228, 86, 35, 255])); + let rows = ((bottom - top) / step).floor() as usize; + for i in (1..=rows).step_by(rows.div_ceil(100).max(1)) { + draw_path( + &mut overlay, + &path(top + step * i as f32), + sx, + sy, + Rgba([0, 154, 171, 255]), + ); + } + let status = if peak == 0 { + "no_visible_change" + } else if changed.iter().sum::() == 0 { + "very_low_contrast" + } else { + "inspect_visually" + }; + let mut offsets: [Vec; 3] = Default::default(); + let mut sampled = [0u32; 3]; + for &point in baselines { + let band = (point[1].max(0.) as usize).min(h as usize - 1) * 3 / h as usize; + sampled[band] += 1; + if let Some(dy) = ruling_offset(&paper, point, (step / 3.).clamp(2., 18.) as i32) { + offsets[band].push(dy.abs()); + } + } + let band_alignment = offsets + .into_iter() + .zip(sampled) + .map(|(mut v, total)| { + v.sort_unstable(); + json!({"sampled":total,"supported_samples":v.len(),"median_abs_dy_px":v.get(v.len()/2)}) + }) + .collect::>(); + let evidence = json!({ + "visibility":status, + "alignment":draft.paper.as_ref().map(|p|p.summary()["alignment"].clone()), + "baseline_samples":baselines.len(), + "nearby_dark_ridge_by_image_third":band_alignment, + "max_rgb_delta":peak, + "changed_pixels_by_image_third":changed, + "channel_delta_threshold":8, + "changed_pixels_outside_reference":outside, + "transparent_png":params.transparent_background, + }); + draft.record_review(section, page, &evidence)?; + let next = if peak == 0 { + "If this page should contain text, check ink opacity/color, local edits and off-page placement. Review the new revision." + } else if outside > 0 || draft.paper.as_ref().is_some_and(|p| !p.ruled) { + "Confirm the intended writing area against the overlay. If ambiguous, show the user the image and ask which corners or first/last baselines to use." + } else { + "Compare the upper, middle and lower writing with the saved paper. Check header clearance, contrast, focus and letter size. Ask the user if the desired appearance is unclear." + }; + let metadata = json!({"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page,"photo_size":[w,h],"thumbnail_size":[result.width(),result.height()],"evidence":evidence,"next_step":next}); + let mut response = reply( + format!( + "{metadata}\nOrange = estimated writing area; cyan = projected layout guides. Baseline offsets sample nearby dark ridges on unmarked paper (null = no supported sample); a decoration can also form a ridge. Transparent PNG is shown on its paper for comparison." + ), + metadata, + ); + for (label, img) in [ + ("Saved paper", thumbnail(&paper)), + ("Finished appearance", result), + ("Reference overlay", overlay), + ] { + response.content.push(ContentBlock::text(label)); + response.content.push(ContentBlock::image( + STANDARD.encode(export::png(&img)?), + "image/png", + )); + } + Ok(response) +} diff --git a/crates/panache-mcp/src/tuning.rs b/crates/panache-mcp/src/tuning.rs new file mode 100644 index 00000000..ad63a7b0 --- /dev/null +++ b/crates/panache-mcp/src/tuning.rs @@ -0,0 +1,113 @@ +use crate::{Limits, State, Tune, controls, paper, reply}; +use anyhow::{Context, Result, ensure}; +use rmcp::model::CallToolResult; +use serde_json::json; +use std::fs; + +pub fn apply(state: &State, input: Tune) -> Result { + let mut draft = state + .drafts + .snapshot(&input.draft_id, Some(input.expected_revision))?; + let mut changes = if input.changes.is_empty() { + draft.controls.clone() + } else { + let mut fonts = state.fonts.clone(); + if let Some(handle) = input + .changes + .get("font") + .and_then(|v| v.as_str()) + .filter(|s| s.starts_with("upload:")) + { + ensure!(draft.has_font(handle)?, "Unknown font for this draft"); + fonts.push(handle.to_owned()); + } + controls::merge(&draft.controls, &input.changes, &fonts)? + }; + ensure!( + input.note.as_ref().is_none_or(|s| s.chars().count() <= 320), + "Note exceeds 320 characters" + ); + let font = if let Some(path) = &input.font_path { + use std::io::Read; + let extension = path + .extension() + .and_then(|ext| ext.to_str()) + .unwrap_or_default(); + ensure!( + path.is_absolute() + && (extension.eq_ignore_ascii_case("ttf") || extension.eq_ignore_ascii_case("otf")), + "Supply an absolute TTF or OTF path" + ); + ensure!( + !input.changes.contains_key("font"), + "Choose font_path or font" + ); + let file = fs::File::open(path)?; + let limit = Limits::default().max_file_bytes; + ensure!( + file.metadata()?.is_file() && file.metadata()?.len() <= limit as u64, + "Invalid font file or size" + ); + let mut bytes = Vec::new(); + file.take(limit as u64 + 1).read_to_end(&mut bytes)?; + ensure!(bytes.len() <= limit, "Font exceeds size limit"); + handwriting_core::FontBook::load(&bytes)?; + let handle = format!( + "upload:{}:{}", + draft.revision + 1, + path.file_name().unwrap_or_default().to_string_lossy() + ); + changes.insert("font".into(), json!(handle)); + Some((handle, bytes)) + } else { + None + }; + if let Some(guides) = &input.paper_guides { + let paper = draft + .paper + .as_ref() + .context("Import stationery before supplying guides")?; + let [w, h] = paper.photo_size.unwrap_or([paper.width, paper.height]); + draft.paper = if guides.is_empty() { + state.drafts.snapshot(draft.id, Some(1))?.paper + } else { + Some(paper::PaperLayout::from_guides(w, h, guides)?) + }; + for key in [ + "top_margin", + "bottom_margin", + "left_margin", + "right_margin", + "line_spacing", + ] { + if !input.changes.contains_key(key) { + changes.remove(key); + } + } + } + ensure!( + changes != draft.controls || input.paper_guides.is_some(), + "No control values changed" + ); + controls::parameters(&draft, 1, &changes)?; + let preserve_layout = changes.keys().chain(draft.controls.keys()).all(|key| { + key == "transparent_background" + || controls::catalog()["camera"].get(key).is_some() + || changes.get(key) == draft.controls.get(key) + }); + let paper = input.paper_guides.as_ref().and(draft.paper.as_ref()); + let details = json!({"changes":input.changes,"font":font.as_ref().map(|(name,_)|name),"paper_guides":input.paper_guides,"note":input.note}); + let preserve_layout = preserve_layout && paper.is_none(); + let next = state.drafts.tune( + &draft, + &changes, + preserve_layout, + paper, + font.as_ref().map(|(k, v)| (k.as_str(), v.as_slice())), + &details, + )?; + Ok(reply( + format!("Saved revision {next}."), + json!({"draft_id":draft.id,"revision":next,"paper":paper.map(|p|p.summary()),"controls":changes,"fine_layout":if preserve_layout { "preserved" } else { "inspect_again" }}), + )) +} diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index ab093d94..a66a5022 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -38,6 +38,66 @@ def png(result): ) +async def review_workflow(client, key, guides, font_path): + # Revise the same sheet after its source image has moved away. + guides = [{**g, "left": [g["left"][0]+12, g["left"][1]+9], + "right": [g["right"][0]+12, g["right"][1]+9]} for g in guides] + revised = (await call( + client, "tune_handwriting", **key, expected_revision=3, + paper_guides=guides, font_path=str(font_path), note="Write inside the indicated area.", + )).structuredContent + font_path.unlink() + assert revised["revision"] == 4 and revised["paper"]["alignment"] == "manual_guides" + assert (await client.call_tool("tune_handwriting", {**key, "expected_revision": 3, "paper_guides": guides})).isError + review = await call(client, "preview_handwriting", **key, view="review") + assert sum(c.type == "image" for c in review.content) == 3 + assert review.structuredContent["evidence"]["visibility"] == "inspect_visually" + glyph = (await call(client, "preview_handwriting", **key, view="layout", limit=1)).structuredContent["glyphs"][0] + selected = (await call(client, "preview_handwriting", **key, view="layout", region=glyph["photo_quad"])).structuredContent + assert glyph["id"] in [g["id"] for g in selected["glyphs"]] + await call(client, "adjust_glyphs", **key, expected_revision=4, section=1, page=1, + ids=[glyph["id"]], place_center=[170, 260], note="Move the chosen word.") + moved = (await call(client, "preview_handwriting", **key, view="layout", + region=[[166,256],[174,256],[174,264],[166,264]])).structuredContent + assert glyph["id"] in [g["id"] for g in moved["glyphs"]] + pdf = (await call(client, "export_handwriting", **key, format="pdf")).structuredContent + await call(client, "tune_handwriting", **key, expected_revision=5, changes={"transparent_background": True}) + transparent = png(await call(client, "preview_handwriting", **key)) + archive = (await call(client, "export_handwriting", **key, format="zip")).structuredContent + with ZipFile(archive["path"]) as z: + assert z.read("0.png") == transparent + same_pdf = (await call(client, "export_handwriting", **key, format="pdf")).structuredContent + 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["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["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" + previous = (await call(client, "read_section", **key, revision=5, view="trajectory")).structuredContent + assert previous["events"][0]["details"]["note"] == "Move the chosen word." + assert all(e["revision"] <= 5 for e in previous["events"]) + # Fit the full four-corner mask of a single glyph and check the reported final geometry. + ids = [glyph["id"]] + quad = [[130, 200], [166, 195], [171, 232], [126, 235]] + edit = dict(**key, expected_revision=7, section=1, page=1, ids=ids) + assert (await client.call_tool("adjust_glyphs", {**edit, "target_quad": [quad[i] for i in (0,2,1,3)]})).isError + await call(client, "adjust_glyphs", **edit, target_quad=quad) + geometry = (await call(client, "preview_handwriting", **key, view="layout", limit=1)).structuredContent + for actual, target in zip(geometry["glyphs"][0]["current_photo_quad"], quad, strict=True): + assert max(abs(a-b) for a,b in zip(actual,target,strict=True)) < 1.1 + await call(client, "tune_handwriting", **key, expected_revision=8, paper_guides=[]) + restored = (await call(client, "read_section", **key, view="summary")).structuredContent["paper"] + original = (await call(client, "read_section", **key, revision=1, view="summary")).structuredContent["paper"] + assert restored == original + assert (await call(client,"read_section",**key,revision=4,view="summary")).structuredContent["paper"] != original + return transparent + + async def smoke(command, arguments, out): with TemporaryDirectory() as temp: params = StdioServerParameters( @@ -137,6 +197,9 @@ async def smoke(command, arguments, out): ) assert invalid.isError paper_path.unlink() + font_path = Path(temp) / "imported.ttf" + shutil.copyfile(Path(__file__).resolve().parents[3] / "assets/font_assets/李国夫手写体.ttf", font_path) + imported_preview = await review_workflow(client, gkey, guides, font_path) paper_id = custom["draft_id"] paper_preview = png( await call(client, "preview_handwriting", draft_id=paper_id) @@ -234,6 +297,7 @@ async def progress(value, total, message=None): ) async with stdio_client(params) as streams, ClientSession(*streams) as client: await client.initialize() + assert png(await call(client, "preview_handwriting", **gkey, revision=6)) == imported_preview assert (await call(client, "list_drafts")).structuredContent["drafts"][0][ "draft_id" ] == doc From e040d459710babbf877e99451fa74f53d2eef0d5 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:02:53 +0800 Subject: [PATCH 03/24] =?UTF-8?q?docs(crates/panache-mcp):=20=E8=AF=B4?= =?UTF-8?q?=E6=98=8E=E7=85=A7=E7=89=87=E6=8E=92=E7=89=88=E4=B8=8E=E4=BA=BA?= =?UTF-8?q?=E5=B7=A5=E5=A4=8D=E6=A0=B8=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:第一次接入的模型和操作者需要知道哪些问题能测量、何时需要进一步确认。 解决手段:说明照片原始像素、圈选、透视、参考线回退、审稿信号和动作轨迹,并链接设计参考研究。 收益:仓库提供可执行的复盘入口和审美判断边界,便于人与模型协同修改。 --- crates/panache-mcp/README.md | 12 +++++++++++- crates/panache-mcp/tool-design.md | 16 +++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 04478ccb..eb8c1dec 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -53,7 +53,7 @@ cargo build --locked --release -p panache-mcp | `preview_handwriting` | 默认返回首页 PNG。用 `section`、`page` 查看指定节中的一页,两者从 1 开始。 | | `export_handwriting` | 按节顺序导出整份稿件,返回绝对路径、版本和实际页数。格式可选 `pdf` 或 `zip`,ZIP 从 `0.png` 开始编号。 | | `describe_controls` | 先列参数组,再按 `group` 查看单位、范围和枚举值。附上 `draft_id` 和 `revision` 可读取该版的实际值。 | -| `tune_handwriting` | 一次提交多项全稿参数,如 `{"ink_opacity":85,"word_spacing":2}`。`null` 恢复建稿时的设置。 | +| `tune_handwriting` | 可在原稿上更新参考线、导入本机字体,并一次提交多项全稿参数,如 `{"ink_opacity":85,"word_spacing":2}`。`null` 恢复建稿时的设置。 | | `adjust_glyphs` | 先用 `preview_handwriting(view="layout")` 取编号和坐标,再按同一节、页和版本调整选中字形。 | 面向 AI 客户端的调用示例、披露边界和测量口径见[工具设计](tool-design.md)。 @@ -64,6 +64,16 @@ cargo build --locked --release -p panache-mcp 整稿上限为整理后 10 万字、200 页。完整导出只在调用导出工具时执行;客户端可以取消,提供进度令牌时可看到已完成页数。ZIP 逐页写盘,PDF 在内存中组装压缩页面后写盘。结果成功后才移入 `exports/`。稿件及历史持续保存在 `PANACHE_MCP_HOME`;Windows 默认是 `%LOCALAPPDATA%/Panache/mcp`,其他系统默认是 `$XDG_DATA_HOME/Panache/mcp` 或 `~/.local/share/Panache/mcp`。 +## 照片排版与成品复盘 + +1. 用 `save_section` 导入照片并保留版本号。用 `preview_handwriting(view="review")` 取得同一页的底纸、成品和叠图。图片最多长边 900 像素,像素坐标以返回的 `photo_size` 为准。需要看笔画细节时取原尺寸 `view="image"`。 +2. 上、中、下分别看字是否顺着实际横线、有没有盖住页眉,以及墨色和笔画锐度是否适合底纸。复盘附带像素对比和附近暗线的偏差。无横线或用户只说“放这边”时,把底纸或叠图展示给人,确认目标区域、首末行或四个角,再做修改。 +3. 调用 `tune_handwriting(draft_id, expected_revision, paper_guides, note)` 在原照片上重排全文。至少给两条参考线,每条提供行号与左右端点。无横线纸也可以指定想写入的区域。传空数组恢复建稿时的校准。旧版本仍可回看;改写书写区域会重置冲突的边距覆盖,重新排版后需重新选字。 +4. 局部改动用 `preview_handwriting(view="layout", region=[[x,y],…])` 圈选字形中心,结果按页分批。把选中的 ID 和相同版本交给 `adjust_glyphs`。`place_center` 将一组字移到指定照片位置;`target_quad` 按左上、右上、右下、左下四角放置所选字块,替换该组已有几何调整。局部字形还可分别调倾斜、浓度和笔画。调整后复查新版本。 +5. 用 `read_section(view="trajectory")` 回看该稿的近期操作、简短调整理由和按页记录的复盘指标。可锁定版本,用 `offset/limit` 向前翻。把需要人判断的歧义带回当前会话;确定符合用途后导出同一版本。 + +`tune_handwriting(font_path=…)` 会把本机 TTF/OTF 随稿保存。可用返回的字体标识在同一稿内切回该字体。墨迹组的 `transparent_background` 控制原尺寸 PNG 预览和 ZIP,PDF 保留纸张。透明稿复盘会把墨迹放回底纸,方便判断实际可读性。 + ## 验证 构建后可用官方 Python MCP 客户端跑一次 stdio 端到端测试。`--out` 可选,用于保留诗稿的预览和 PDF。 diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index 538b559b..5ebf308e 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -2,7 +2,7 @@ ## 工具发现 -Panache 在 `tools/list` 中稳定公布九个任务入口。模型可以直接保存、预览、导出;只有需要调参时才调用 `describe_controls`。目录按排版、字体、墨迹、扰动和删除线五组组织,和服务端参数校验共用同一份定义。 +Panache 在 `tools/list` 中稳定公布九个任务入口。模型可以直接保存、预览、导出;只有需要调参时才调用 `describe_controls`。目录按排版、字体、墨迹、扰动、删除线和拍摄信息六组组织,和服务端参数校验共用同一份定义。 MCP 的工具列表支持分页。客户端可能取完所有页;分页能控制单次协议响应大小。Claude 的 Tool Search 支持宿主配置延迟加载,实际进入模型上下文的工具由宿主决定。Panache 的 stdio 客户端也可以完全不提供搜索,只用标准工具列表和调用接口。项目目前选择按需查询参数,避免为小型目录引入搜索索引和额外的调用步骤。设计依据见 [MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)、[MCP 路线图中的渐进发现](https://blog.modelcontextprotocol.io/posts/mcp-roadmap/) 和 [Claude Tool Search 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)。 @@ -21,7 +21,7 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 字号、行距和页边距以纸张原始像素为单位。照片底纸采用识别后的画布尺寸;边距和行距可手动微调。所有参数先合并再校验,因此可以在同一补丁里同时增加字号和行距。位移相对原始字框,`dx:4` 表示向右 4 px;后续只传 `dy` 会保留原有 `dx`。精修还支持缩放、旋转和浓度。字框为 `[x,y,width,height]`。遇到公式、插图或归一化导致源码无法准确对应时,模型可以结合可视预览和坐标定位。 -全文样式变更后要重新定位字形;改写一节会让该节的旧字形调整只在旧版本生效。在其他节追加文字可以继续复用原节的调整。并发写入出现版本冲突时,先读取最新摘要,再决定是否重做补丁。MCP 还可以用 `shape` 对选中字形做剪切或梯形变换。逐字着色仍由图形界面提供。 +全文样式变更后要重新定位字形;改写一节会让该节的旧字形调整只在旧版本生效。在其他节追加文字可以继续复用原节的调整。并发写入出现版本冲突时,先读取最新摘要,再决定是否重做补丁。MCP 还可以用 `shape` 对选中字形做剪切或梯形变换。也可对选中字形指定局部墨色。 ## 插图墨迹 @@ -31,7 +31,7 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 ## 照片和纸面坐标 -导入 `paper_path` 时,默认 `paper_mode="photo"` 在原照片上合成笔迹和插图。`flatten` 保存校平后的底纸。建稿结果只返回尺寸、边距、行距和识别方式。遇到置信度不足的照片会返回 `alignment="unverified"`。每个稿件使用建稿时的纸张快照,旧稿仍使用当时保存的底纸。 +导入 `paper_path` 时,默认 `paper_mode="photo"` 在原照片上合成笔迹和插图。`flatten` 保存校平后的底纸。建稿结果只返回尺寸、边距、行距和识别方式。遇到置信度不足的照片会返回 `alignment="unverified"`。稿件保留建稿时的纸张快照,后续版本可在同一底图上重新校准。 | 模型可以取得或指定的内容 | 对应接口 | | --- | --- | @@ -49,6 +49,16 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 - 几何视图每批默认 12 个字形,上限 32,不传 PNG 或字形蒙版图集。查看第 N 页仍需从该节开头排到第 N 页。真正需要目测字迹时,再显式取图片视图。 - 客户端应把稿件、标题及工具响应中的用户文字作为数据处理。宿主负责选择工具、执行权限和会话历史。减少默认输出能节约上下文;明确请求原文、图片或路径的客户端仍能取得相应数据。 +## 复盘证据与版本轨迹 + +`view="review"` 按需返回三张按相同比例缩放的图片。橙色边界和青色参考线来自书写区估计,叠图可与裸底纸对照。在原分辨率比较显示在纸上的墨迹和底纸,按图像上中下三等分统计 RGB 任一通道变化至少 8 级的像素及落在参考区外的数量。在抽样字形调整后的基线中点附近搜索底纸的局部暗线并报告垂直偏差中位数和支持样本数;校徽或背景纹理也可能给出暗线,无足够对比时返回空值。短文自然可能只覆盖上部。对有正文的页面,零像素变化是重新检查的明确信号。没有自动审美评分,验收时仍要查看原图,必要时请用户指出具体位置。 + +轨迹按稿件和版本保存在本机。修改操作与简短备注在同一事务提交,同一版本、节、页只保留一份复盘指标。查询不会返回原文、字体数据、图片字节或完整对话。这里的轨迹指已执行的动作和可复查的结果。模型可以对照前后版本调整下一步;没有修改模型权重或自动跨用户积累经验。 + +该设计借鉴了 Reflexion 将任务反馈留给下一次尝试的做法。关于模型仅靠自我判断纠错的研究使用的是推理任务,本项目将其作为设计动机。这里的效果由本项目的图像样本和回归用例单独验证。[Reflexion(NeurIPS 2023)](https://proceedings.neurips.cc/paper/2023/hash/1b44b878bb782e6954cd888628510e90-Abstract-Conference.html) · [外部反馈与自我纠错(ICLR 2024)](https://proceedings.iclr.cc/paper_files/paper/2024/hash/8b4add8b0aa8749d80a34ca5d941c355-Abstract-Conference.html) + +SICA 将历次尝试及其评估结果放入档案,供下一轮决策参考。本工具采用了可按版本取回结果的做法,作用域限于当前稿件,修改对象是稿件与排版参数。[SICA 作者实现](https://github.com/MaximeRobeyns/self_improving_coding_agent) + ## 如何复测 从仓库根目录运行下列命令。两个脚本都使用独立临时稿库。比较版本时,把相同的测量脚本指向两个构建,使用相同字体与测试图片。 From ddc48d79c3c458041d9271df92b528deead8b2e3 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:29:40 +0800 Subject: [PATCH 04/24] =?UTF-8?q?feat(crates/panache-mcp):=20=E4=BF=9D?= =?UTF-8?q?=E5=AD=98=E5=8F=AF=E5=BC=95=E7=94=A8=E7=9A=84=E9=80=90=E9=A1=B5?= =?UTF-8?q?=E5=A4=8D=E7=9B=98=E5=B9=B6=E6=AF=94=E8=BE=83=E4=B8=A4=E7=89=88?= =?UTF-8?q?=E8=AF=81=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:同版同页的新测量会覆盖旧结果,模型难以追溯偏差变化来自哪次测量,也难以找回用户对墨色或位置的原话。 解决手段:按页保存有稳定 ID、算法版本与成品像素摘要的观察,事务迁移旧数据;比较时列出编辑动作、理由、测量差值与支持样本。把用户原话和模型观察附在具体证据上,保持稿件版本。 收益:新接手的模型可区分基线改善、正文不可见和证据不足。旧库升级、重复十次复盘、斜纸校准、重分页和跨会话意见读取均有回归验证;比较无需重渲染或归档整页图片。 --- Cargo.lock | 1 + crates/panache-mcp/Cargo.toml | 1 + crates/panache-mcp/README.md | 15 + crates/panache-mcp/src/drafts.rs | 50 +-- crates/panache-mcp/src/drafts/observations.rs | 308 ++++++++++++++++++ crates/panache-mcp/src/engine.rs | 25 +- crates/panache-mcp/src/inputs.rs | 23 ++ crates/panache-mcp/src/main.rs | 45 ++- crates/panache-mcp/src/review.rs | 33 +- crates/panache-mcp/tests/review_comparison.py | 152 +++++++++ crates/panache-mcp/tests/smoke.py | 11 + crates/panache-mcp/tool-design.md | 8 +- 12 files changed, 626 insertions(+), 46 deletions(-) create mode 100644 crates/panache-mcp/src/drafts/observations.rs create mode 100644 crates/panache-mcp/tests/review_comparison.py diff --git a/Cargo.lock b/Cargo.lock index eec0ca0f..2393373a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1500,6 +1500,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "sha2 0.10.9", "tempfile", "tokio", "uuid", diff --git a/crates/panache-mcp/Cargo.toml b/crates/panache-mcp/Cargo.toml index 2453b878..9bc78bbe 100644 --- a/crates/panache-mcp/Cargo.toml +++ b/crates/panache-mcp/Cargo.toml @@ -9,6 +9,7 @@ publish.workspace = true handwriting-core.workspace = true tokio = { workspace = true, features = ["sync"] } rquickjs = "0.14" +sha2 = "0.10.9" serde.workspace = true serde_json = "1" rmcp = { version = "3.11", features = ["transport-io"] } diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index eb8c1dec..f770660b 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -54,6 +54,7 @@ cargo build --locked --release -p panache-mcp | `export_handwriting` | 按节顺序导出整份稿件,返回绝对路径、版本和实际页数。格式可选 `pdf` 或 `zip`,ZIP 从 `0.png` 开始编号。 | | `describe_controls` | 先列参数组,再按 `group` 查看单位、范围和枚举值。附上 `draft_id` 和 `revision` 可读取该版的实际值。 | | `tune_handwriting` | 可在原稿上更新参考线、导入本机字体,并一次提交多项全稿参数,如 `{"ink_opacity":85,"word_spacing":2}`。`null` 恢复建稿时的设置。 | +| `annotate_review` | 将用户原话或模型观察挂到指定复盘 ID,保持稿件版本号。 | | `adjust_glyphs` | 先用 `preview_handwriting(view="layout")` 取编号和坐标,再按同一节、页和版本调整选中字形。 | 面向 AI 客户端的调用示例、披露边界和测量口径见[工具设计](tool-design.md)。 @@ -74,6 +75,20 @@ cargo build --locked --release -p panache-mcp `tune_handwriting(font_path=…)` 会把本机 TTF/OTF 随稿保存。可用返回的字体标识在同一稿内切回该字体。墨迹组的 `transparent_background` 控制原尺寸 PNG 预览和 ZIP,PDF 保留纸张。透明稿复盘会把墨迹放回底纸,方便判断实际可读性。 +### 比较两版,找回当时的依据 + +先对要看的两个版本分别调用 `preview_handwriting(view="review", revision=…)`,记下返回的 `review_id`。用户明确表达偏好后,用 `annotate_review(draft_id, review_id, origin="user_quote", text=…)` 保存原话。模型自己的观察使用 `model_observation`。 + +例如,比较第 1 节第 1 页的 v3 与 v4: + +```json +{"draft_id":"…","view":"review","section":1,"page":1,"revision":4,"compare_revision":3} +``` + +该调用读取两版各自最近归档的该页复盘,返回测量、所引用的评语及其间全稿的编辑动作。差值为 v4 减 v3。先确认正文仍然可见,再结合每个区域的支持样本数解释偏差。全局墨色设置相同只说明参数一致,局部精修及肉眼观感还要另查。可用 `offset/limit` 翻阅编辑动作。某版缺复盘时,先查看所缺版本;算法不同、页面内容改变或尺寸不同时仅列两侧证据,保留比较限制。 + +精确复查用 `read_section(view="review",draft_id=…,review_id=…)`,跨会话可用。要看图时再按版本取 `view="image"`。像素摘要用于核对重渲染结果,系统不为每次复盘归档整页图片。 + ## 验证 构建后可用官方 Python MCP 客户端跑一次 stdio 端到端测试。`--out` 可选,用于保留诗稿的预览和 PDF。 diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index a029c6f9..151eb9b9 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -1,3 +1,4 @@ +mod observations; use anyhow::{Context, Result, ensure}; use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; use serde_json::{Value, json}; @@ -21,16 +22,6 @@ pub struct Snapshot<'a> { } impl Snapshot<'_> { - pub fn record_review(&self, section: u32, page: usize, evidence: &Value) -> Result<()> { - self.drafts - .record_review(self.id, self.revision, section, page, evidence) - } - - 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 page_reviews WHERE draft=? AND revision=?", - params![self.id,self.revision], |r|Ok((r.get(0)?,r.get(1)?)))?) - } 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=?)", @@ -155,15 +146,12 @@ impl Drafts { draft TEXT NOT NULL, revision INTEGER NOT NULL, details TEXT NOT NULL, PRIMARY KEY(draft,revision) ); - CREATE TABLE IF NOT EXISTS page_reviews ( - draft TEXT NOT NULL, revision INTEGER NOT NULL, section INTEGER NOT NULL, - page INTEGER NOT NULL, evidence TEXT NOT NULL, PRIMARY KEY(draft,revision,section,page) - ); CREATE TABLE IF NOT EXISTS papers ( draft TEXT PRIMARY KEY REFERENCES drafts(id), layout TEXT NOT NULL, image BLOB NOT NULL ); ", )?; + observations::initialize(&mut drafts.connect()?)?; Ok(drafts) } fn connect(&self) -> Result { @@ -356,36 +344,25 @@ impl Drafts { ); Ok(next) } - pub fn record_review( - &self, - id: &str, - rev: u32, - section: u32, - page: usize, - evidence: &Value, - ) -> Result<()> { - self.connect()?.execute( - "INSERT OR REPLACE INTO page_reviews VALUES(?,?,?,?,?)", - params![id, rev, section, u32::try_from(page)?, evidence.to_string()], - )?; - Ok(()) - } - pub fn trajectory(&self, id: &str, rev: u32, offset: u32, limit: u32) -> Result { ensure!((1..=50).contains(&limit), "Trajectory limit must be 1..50"); let db = self.connect()?; let mut stmt=db.prepare( - "WITH events(revision,action,section,page,evidence) AS ( - SELECT revision,'save_section',number,NULL,NULL FROM sections WHERE draft=?1 - UNION ALL SELECT revision,'tune_handwriting',NULL,NULL,NULL FROM settings WHERE draft=?1 - UNION ALL SELECT revision,'adjust_glyphs',section,NULL,NULL FROM glyph_edits WHERE draft=?1 - UNION ALL SELECT revision,'page_review',section,page,evidence FROM page_reviews WHERE draft=?1 + "WITH events(revision,action,section,page,evidence,review_id,origin,seq) AS ( + SELECT revision,'save_section',number,NULL,NULL,NULL,'draft_edit',0 FROM sections WHERE draft=?1 + UNION ALL SELECT revision,'tune_handwriting',NULL,NULL,NULL,NULL,'draft_edit',0 FROM settings WHERE draft=?1 + UNION ALL SELECT revision,'adjust_glyphs',section,NULL,NULL,NULL,'draft_edit',0 FROM glyph_edits WHERE draft=?1 + UNION ALL SELECT revision,'page_review',section,page,evidence,review_id,'measurement',seq + FROM review_observations WHERE draft=?1 + UNION ALL SELECT o.revision,'review_feedback',o.section,o.page,json_object('text',f.note), + o.review_id,f.origin,f.rowid FROM review_feedback f JOIN review_observations o USING(review_id) + WHERE o.draft=?1 ) SELECT e.revision,e.action,e.section,COALESCE(e.page,json_extract(n.details,'$.page')), - COALESCE(e.evidence,n.details,'{}') + COALESCE(e.evidence,n.details,'{}'),e.review_id,e.origin FROM events e LEFT JOIN edit_notes n ON n.draft=?1 AND n.revision=e.revision WHERE e.revision<=?2 - ORDER BY e.revision DESC,(e.action='page_review') DESC,e.section,e.page + ORDER BY e.revision DESC,(e.action='review_feedback') DESC,(e.action='page_review') DESC,e.seq DESC,e.section,e.page LIMIT ?3 OFFSET ?4")?; let mut entries = Vec::new(); let mut rows = stmt.query(params![id, rev, limit + 1, offset])?; @@ -394,6 +371,7 @@ impl Drafts { entries.push(json!({ "revision":row.get::<_,u32>(0)?, "action":row.get::<_,String>(1)?, + "review_id":row.get::<_,Option>(5)?,"origin":row.get::<_,String>(6)?, "section":row.get::<_,Option>(2)?, "page":row.get::<_,Option>(3)?, "details":serde_json::from_str::(&details)?, diff --git a/crates/panache-mcp/src/drafts/observations.rs b/crates/panache-mcp/src/drafts/observations.rs new file mode 100644 index 00000000..1c24f349 --- /dev/null +++ b/crates/panache-mcp/src/drafts/observations.rs @@ -0,0 +1,308 @@ +use super::{Drafts, Snapshot}; +use anyhow::{Context, Result, ensure}; +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; +use serde_json::{Value, json}; +use uuid::Uuid; + +pub(super) fn initialize(db: &mut Connection) -> Result<()> { + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + tx.execute_batch(" + CREATE TABLE IF NOT EXISTS review_observations( + 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, + UNIQUE(draft,revision,section,page,algorithm,pixel_sha256) + ); + CREATE INDEX IF NOT EXISTS reviews_by_page ON review_observations(draft,revision,section,page,seq); + CREATE TABLE IF NOT EXISTS review_feedback( + 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.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) + SELECT lower(hex(randomblob(16))),draft,revision,section,page,evidence FROM page_reviews; + DROP TABLE page_reviews;")?; + } + tx.commit()?; + Ok(()) +} + +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 + 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)?, + }))).optional()?.context("Unknown review in this draft and revision range")?; + record["evidence"] = serde_json::from_str( + record["evidence"] + .as_str() + .context("Invalid review evidence")?, + )?; + let mut stmt = db.prepare( + "SELECT origin,note FROM review_feedback WHERE review_id=? ORDER BY rowid DESC LIMIT 51", + )?; + let mut notes = stmt + .query_map([id], |r| { + Ok(json!({"origin":r.get::<_,String>(0)?,"text":r.get::<_,String>(1)?})) + })? + .collect::>>()?; + record["more_feedback"] = json!(notes.len() > 50); + notes.truncate(50); + record["feedback"] = json!(notes); + Ok(record) +} + +impl Snapshot<'_> { + pub fn record_review( + &self, + section: u32, + page: usize, + algorithm: &str, + pixel: &str, + content: &str, + evidence: &Value, + ) -> Result { + 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()])?; + 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))?; + let record = by_id(&tx, &id, self)?; + tx.commit()?; + Ok(record) + } + + pub fn observation(&self, id: &str) -> Result { + 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 compare_reviews( + &self, + before: u32, + section: u32, + page: usize, + offset: u32, + limit: u32, + ) -> Result { + ensure!( + before > 0 && before < self.revision, + "compare_revision must identify an earlier revision" + ); + ensure!( + section > 0 && page > 0 && (1..=50).contains(&limit), + "Use a one-based section/page and 1..50 edit actions" + ); + 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 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 + UNION ALL SELECT revision,'adjust_glyphs',section FROM glyph_edits WHERE draft=?1) + SELECT rev,action,section,details FROM actions LEFT JOIN edit_notes ON draft=?1 AND revision=rev + WHERE rev>?2 AND rev<=?3 ORDER BY rev LIMIT ?4 OFFSET ?5")?; + let mut rows = stmt.query(params![self.id, before, self.revision, limit + 1, offset])?; + let mut actions = Vec::new(); + while let Some(row) = rows.next()? { + let details: Option = row.get(3)?; + actions.push(json!({"revision":row.get::<_,u32>(0)?,"action":row.get::<_,String>(1)?, + "section":row.get::<_,Option>(2)?,"details":details.as_deref().map(serde_json::from_str::).transpose()?})); + } + let more = actions.len() > limit as usize; + actions.truncate(limit as usize); + Ok( + json!({"draft_id":self.id,"section":section,"page":page,"compare_revision":before,"revision":self.revision, + "comparison":compare(previous.as_ref(),current.as_ref()),"before":previous,"after":current, + "actions":actions,"next_offset":if more{offset.checked_add(limit)}else{None}, + "guidance":"Deltas are after minus before. Check support, visible ink and attributed feedback before judging placement or aesthetics. Actions show what changed; concurrent edits do not isolate a cause. Request view=image with a revision to see a fresh rendering."}), + ) + } +} + +impl Drafts { + pub fn annotate(&self, input: &crate::ReviewFeedback) -> Result { + let text = input.text.trim(); + ensure!( + !text.is_empty() && text.chars().count() <= 320, + "Feedback must contain 1..320 characters" + ); + let origin = serde_json::to_value(&input.origin)?; + let mut db = self.connect()?; + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let revision: u32 = tx + .query_row( + "SELECT revision FROM review_observations WHERE draft=? AND review_id=?", + params![input.draft_id, input.review_id], + |r| r.get(0), + ) + .optional()? + .context("Unknown review in this draft")?; + tx.execute( + "INSERT INTO review_feedback(review_id,origin,note) VALUES(?,?,?) + ON CONFLICT(review_id,origin,note) DO NOTHING", + params![input.review_id, origin.as_str(), text], + )?; + tx.commit()?; + Ok( + json!({"draft_id":input.draft_id,"review_id":input.review_id,"revision":revision,"origin":origin,"text":text}), + ) + } +} + +fn compare(before: Option<&Value>, after: Option<&Value>) -> Value { + let mut reasons = Vec::new(); + if before.is_none() { + reasons.push("missing_before_review"); + } + if after.is_none() { + reasons.push("missing_after_review"); + } + let (Some(a), Some(b)) = (before, after) else { + return json!({"limitations":reasons,"delta":null}); + }; + if a["algorithm"].is_null() || b["algorithm"].is_null() { + reasons.push("unknown_algorithm"); + } else if a["algorithm"] != b["algorithm"] { + reasons.push("different_algorithms"); + } + if a["page_content_sha256"].is_null() || b["page_content_sha256"].is_null() { + reasons.push("unknown_page_content"); + } else if a["page_content_sha256"] != b["page_content_sha256"] { + reasons.push("page_content_changed_or_repaginated"); + } + let (a, b) = (&a["evidence"], &b["evidence"]); + if a["photo_size"] != b["photo_size"] { + reasons.push("different_image_dimensions"); + } + if !reasons.is_empty() { + return json!({"limitations":reasons,"delta":null}); + } + let difference = |x: &Value, y: &Value| -> Option { Some(y.as_i64()? - x.as_i64()?) }; + let bands=(0..3).map(|i|{ + let x=&a["nearby_dark_ridge_by_image_third"][i]; + let y=&b["nearby_dark_ridge_by_image_third"][i]; + let support=[x["supported_samples"].as_u64().unwrap_or(0),y["supported_samples"].as_u64().unwrap_or(0)]; + let enough=support.iter().all(|n|*n>=3); + json!({"supported_before_after":support,"limitation":if enough {None}else{Some("insufficient_ridge_support")}, + "median_abs_dy_px":if enough{difference(&x["median_abs_dy_px"],&y["median_abs_dy_px"])}else{None}, + "changed_pixels":difference(&a["changed_pixels_by_image_third"][i],&b["changed_pixels_by_image_third"][i])}) + }).collect::>(); + json!({"limitations":reasons,"delta":{"visibility_before":a["visibility"],"visibility_after":b["visibility"], + "max_rgb_delta":difference(&a["max_rgb_delta"],&b["max_rgb_delta"]), + "changed_pixels_outside_each_reference":difference(&a["changed_pixels_outside_reference"],&b["changed_pixels_outside_reference"]), + "by_image_third":bands,"global_ink_settings_equal":a["global_ink"]==b["global_ink"]}}) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn upgrades_old_rows_without_inventing_provenance_and_deduplicates_new_observations() + -> Result<()> { + let home = tempfile::tempdir()?; + let db = Connection::open(home.path().join("drafts.sqlite3"))?; + db.execute_batch("CREATE TABLE page_reviews(draft TEXT NOT NULL,revision INTEGER NOT NULL, + section INTEGER NOT NULL,page INTEGER NOT NULL,evidence TEXT NOT NULL,PRIMARY KEY(draft,revision,section,page)); + INSERT INTO page_reviews VALUES('d',1,1,1,'{\"visibility\":\"no_visible_change\"}');")?; + drop(db); + let drafts = Drafts::open(home.path())?; + drafts.connect()?.execute( + "INSERT INTO drafts VALUES ('d','title',?,3,0,1)", + [serde_json::to_string(&crate::Style::default())?], + )?; + let old = drafts.snapshot("d", Some(1))?; + let legacy_id = drafts.trajectory("d", 1, 0, 5)?["events"][0]["review_id"] + .as_str() + .unwrap() + .to_owned(); + let legacy = old.observation(&legacy_id)?; + assert!( + legacy["algorithm"].is_null() + && legacy["pixel_sha256"].is_null() + && legacy["page_content_sha256"].is_null() + ); + assert_eq!(legacy["evidence"]["visibility"], "no_visible_change"); + 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)?; + for _ in 0..9 { + assert_eq!( + rev2.record_review(1, 1, "a", "pixels", "content", &observation)?, + first + ); + } + assert_eq!( + drafts.connect()?.query_row( + "SELECT count(*) FROM review_observations WHERE revision=2", + [], + |r| r.get::<_, u32>(0) + )?, + 1 + ); + let changed = rev2.record_review(1, 1, "a", "other-pixels", "content", &observation)?; + let upgraded = rev2.record_review( + 1, + 1, + "b", + "other-pixels", + "content", + &json!({"visibility":"very_low_contrast","photo_size":[400,500]}), + )?; + assert_ne!(first["review_id"], changed["review_id"]); + assert_ne!(changed["review_id"], upgraded["review_id"]); + assert_eq!(rev2.review_counts()?, (1, 1)); + 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)?; + assert_eq!( + comparison["comparison"]["limitations"], + json!(["different_algorithms"]) + ); + assert!(comparison["comparison"]["delta"].is_null()); + assert!( + rev3.compare_reviews(1, 1, 1, 0, 5)?["comparison"]["limitations"] + .as_array() + .unwrap() + .contains(&json!("unknown_algorithm")) + ); + for record in [first, changed, upgraded, legacy] { + let reopened = Drafts::open(home.path())?; + assert_eq!( + reopened + .snapshot("d", None)? + .observation(record["review_id"].as_str().unwrap())?, + record + ); + } + Ok(()) + } +} diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index e5136a0f..a231a6f2 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -255,7 +255,8 @@ impl Engine { section: Section, page: usize, cancel: &Cancellation, - ) -> Result> { + ) -> Result { + let source_revision = section.version; let req = self.fine_request(draft, section)?; let (_, glyphs) = fine_edit::inspect_page(&req, page, cancel)?; let edits = req @@ -270,7 +271,21 @@ impl Engine { }) .unwrap_or_default(); let stride = glyphs.len().div_ceil(384).max(1); - Ok(glyphs + // Bind page membership to the immutable section text and all layout units, not just the measurement sample. + use sha2::{Digest, Sha256}; + let mut membership = Sha256::new(); + membership.update(source_revision.to_le_bytes()); + for glyph in &glyphs { + membership.update(glyph.id.to_le_bytes()); + membership.update( + glyph + .source_utf16 + .unwrap_or([u32::MAX; 2]) + .map(u32::to_le_bytes) + .concat(), + ); + } + let baselines = glyphs .iter() .filter(|g| g.illustration.is_none()) .step_by(stride) @@ -281,7 +296,11 @@ impl Engine { glyph_point(g, edits.get(&g.id).copied(), [0., dy]), ) }) - .collect()) + .collect(); + Ok(crate::review::PageSample { + baselines, + content_sha256: format!("{:x}", membership.finalize()), + }) } pub fn layout( diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index eccf5d65..e203fbba 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -134,6 +134,7 @@ pub struct List { #[derive(Clone, Copy, Default, Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "snake_case")] pub enum ReadView { + Review, Trajectory, #[default] Excerpt, @@ -144,6 +145,8 @@ pub enum ReadView { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Read { + /// With view=review, retrieve one immutable measurement and its attributed feedback. + pub review_id: Option, /// Default excerpt omits inline image bytes; summary omits text; source reads exact Markdown. pub view: Option, pub draft_id: String, @@ -211,6 +214,8 @@ pub struct Nudge { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Preview { + /// With view=review, compare stored evidence on this section/page with an earlier draft revision. Returns data only. Offset/limit paginate intervening edit actions. + pub compare_revision: Option, /// Layout only. Select glyph centers in this polygon (3..32 original image pixel pairs). Returned IDs can be adjusted together. pub region: Option>, /// In layout view, only return illustration outlines and isolated details. @@ -234,3 +239,21 @@ pub struct Export { pub revision: Option, pub format: Option, } + +#[derive(Deserialize, JsonSchema, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum FeedbackOrigin { + UserQuote, + ModelObservation, +} + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReviewFeedback { + pub draft_id: String, + pub review_id: String, + /// user_quote is reserved for the user's actual words; use model_observation for your interpretation. + pub origin: FeedbackOrigin, + /// Short, page-specific feedback, up to 320 characters. + pub text: String, +} diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 5274a78a..7f392d56 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -315,11 +315,21 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "Read view=trajectory for recent draft edits, user-provided edit notes and page review evidence (offset/limit count events). Other views read one section: summary, excerpt (default, image data omitted), or exact source. Offset counts Unicode characters in the selected view." + description = "Read view=review with review_id for exact stored evidence and its user quotes or model observations. Read view=trajectory for recent draft edits, user-provided edit notes and page review evidence (offset/limit count events). Other views read one section: summary, excerpt (default, image data omitted), or exact source. Offset counts Unicode characters in the selected view." )] fn read_section(&self, Parameters(input): Parameters) -> CallToolResult { tool_result((|| { 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"); if input.view == Some(ReadView::Trajectory) { let result = self.0.drafts.trajectory( draft.id, @@ -362,13 +372,32 @@ impl Panache { #[tool( annotations(open_world_hint = false), - description = "Preview one page. view=review returns paper, finished image, reference overlay and visible ink evidence. Compare top/middle/bottom alignment and ink appearance. Use layout with region (photo pixel polygon) to select glyph IDs; view=layout returns base glyph boxes [x,y,width,height] in pixels, paginated with offset/limit, for adjust_glyphs. view=paper gives the saved background alone. Set illustrations_only=true in layout for editable diagram outlines and details. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline in image pixels." + description = "With view=review and compare_revision, read a data-only same-page comparison with exact review IDs, intervening edits, feedback and limitations. Omit compare_revision to measure one page. view=review returns paper, finished image, reference overlay and visible ink evidence. Compare top/middle/bottom alignment and ink appearance. Use layout with region (photo pixel polygon) to select glyph IDs; view=layout returns base glyph boxes [x,y,width,height] in pixels, paginated with offset/limit, for adjust_glyphs. view=paper gives the saved background alone. Set illustrations_only=true in layout for editable diagram outlines and details. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline in image pixels." )] async fn preview_handwriting( &self, Parameters(input): Parameters, ctx: RequestContext, ) -> CallToolResult { + if let Some(before) = input.compare_revision { + return tool_result((|| { + ensure!( + input.view == Some(PreviewView::Review) + && input.region.is_none() + && input.illustrations_only.is_none(), + "compare_revision requires an unfiltered review view" + ); + let draft = self.0.drafts.snapshot(&input.draft_id, input.revision)?; + let data = draft.compare_reviews( + before, + input.section.unwrap_or(1), + input.page.unwrap_or(1), + u32::try_from(input.offset.unwrap_or(0))?, + u32::try_from(input.limit.unwrap_or(20))?, + )?; + Ok(reply(data.to_string(), data)) + })()); + } let result = self .render(ctx, move |state, engine, cancel| { let draft = state.drafts.snapshot(&input.draft_id, input.revision)?; @@ -418,6 +447,18 @@ impl Panache { tool_result(result) } + #[tool( + 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 { + tool_result( + self.0 + .drafts + .annotate(&input) + .map(|data| reply(data.to_string(), data)), + ) + } + #[tool( description = "Adjust selected glyphs in one section/page by IDs from its layout view. Use the same revision. Offsets and shape are in paper space before sheet projection. Use place_center for a group move; target_quad maps the entire selected text block into four corners on the image. Shape adjusts each glyph individually." )] diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs index 793387cc..28a50043 100644 --- a/crates/panache-mcp/src/review.rs +++ b/crates/panache-mcp/src/review.rs @@ -75,12 +75,17 @@ fn ruling_offset(paper: &RgbaImage, point: [f32; 2], radius: i32) -> Option (best.0 >= 7 * 8).then_some(best.2) } +pub struct PageSample { + pub baselines: Vec<[f32; 2]>, + pub content_sha256: String, +} + pub fn page( draft: &Snapshot<'_>, section: u32, page: usize, png: &str, - baselines: &[[f32; 2]], + sample: &PageSample, cancel: &Cancellation, ) -> Result { let params = controls::parameters(draft, section, &draft.controls)?; @@ -91,6 +96,13 @@ pub fn page( }; let mut finished = imaging::decode(&bytes, &limits)?.into_rgba8(); drop(bytes); + use sha2::{Digest, Sha256}; + let mut hash = Sha256::new(); + hash.update(finished.width().to_le_bytes()); + hash.update(finished.height().to_le_bytes()); + hash.update(finished.as_raw()); + let pixel_digest = format!("{:x}", hash.finalize()); + let baselines = &sample.baselines; let paper = match draft.background()? { Some(b) => imaging::decode(&b, &Limits::default())?.into_rgba8(), None => handwriting_core::render::preset_paper( @@ -225,6 +237,8 @@ pub fn page( .collect::>(); let evidence = json!({ "visibility":status, + "photo_size":[w,h], + "global_ink":{"rgba":params.fill,"opacity":params.ink_opacity,"thickness":params.ink_thickness,"softness":params.ink_softness,"depth_sigma":params.ink_depth_sigma}, "alignment":draft.paper.as_ref().map(|p|p.summary()["alignment"].clone()), "baseline_samples":baselines.len(), "nearby_dark_ridge_by_image_third":band_alignment, @@ -234,7 +248,14 @@ pub fn page( "changed_pixels_outside_reference":outside, "transparent_png":params.transparent_background, }); - draft.record_review(section, page, &evidence)?; + let observation = draft.record_review( + section, + page, + "paper-review/1", + &pixel_digest, + &sample.content_sha256, + &evidence, + )?; let next = if peak == 0 { "If this page should contain text, check ink opacity/color, local edits and off-page placement. Review the new revision." } else if outside > 0 || draft.paper.as_ref().is_some_and(|p| !p.ruled) { @@ -242,7 +263,13 @@ pub fn page( } else { "Compare the upper, middle and lower writing with the saved paper. Check header clearance, contrast, focus and letter size. Ask the user if the desired appearance is unclear." }; - let metadata = json!({"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page,"photo_size":[w,h],"thumbnail_size":[result.width(),result.height()],"evidence":evidence,"next_step":next}); + let metadata = { + let mut metadata = observation; + metadata["photo_size"] = json!([w, h]); + metadata["thumbnail_size"] = json!([result.width(), result.height()]); + metadata["next_step"] = json!(next); + metadata + }; let mut response = reply( format!( "{metadata}\nOrange = estimated writing area; cyan = projected layout guides. Baseline offsets sample nearby dark ridges on unmarked paper (null = no supported sample); a decoration can also form a ridge. Transparent PNG is shown on its paper for comparison." diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py new file mode 100644 index 00000000..d03c3c8b --- /dev/null +++ b/crates/panache-mcp/tests/review_comparison.py @@ -0,0 +1,152 @@ +"""Page comparison through actual MCP calls, using a synthetic sloping ruled sheet.""" + +import sqlite3 +import struct +import zlib +from contextlib import closing + + +def slanted_sheet(path): + width, height = 400, 500 + left, right = 40, 360 + rows = [88 + 38 * i for i in range(9)] + pixels = bytearray() + for y in range(height): + pixels.append(0) + for x in range(width): + on_rule = left <= x <= right and y + (x - left) // 20 in rows + pixels.append(75 if on_rule else 235) + + def chunk(tag, data): + return ( + struct.pack(">I", len(data)) + + tag + + data + + struct.pack(">I", zlib.crc32(tag + data)) + ) + + path.write_bytes( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(pixels)) + + chunk(b"IEND", b"") + ) + return [ + {"row": i, "left": [left, rows[i]], "right": [right, rows[i] - 16]} + for i in (0, 8) + ] + + +async def exercise(client, directory, call): + path = directory / "slanted.png" + guides = slanted_sheet(path) + shifted = [ + { + **g, + "left": [g["left"][0], g["left"][1] + 7], + "right": [g["right"][0], g["right"][1] + 7], + } + for g in guides + ] + saved = await call( + client, + "save_section", + markdown="逐字检查书写的基线方向。\n\n观察第二行字的位置。\n\n保留用户喜欢的墨色。", + paper_path=str(path), + paper_guides=shifted, + style={"font_size": 22, "seed": 31}, + ) + key = {"draft_id": saved.structuredContent["draft_id"]} + + async def tune(rev, **args): + await call(client, "tune_handwriting", **key, expected_revision=rev, **args) + + async def review(rev): + return ( + await call( + client, "preview_handwriting", **key, revision=rev, view="review" + ) + ).structuredContent + + async def compare(before, after): + response = await call( + client, + "preview_handwriting", + **key, + revision=after, + view="review", + compare_revision=before, + ) + assert all(part.type != "image" for part in response.content) + return response.structuredContent + + def assets(): + with closing(sqlite3.connect(directory / "drafts.sqlite3")) as db: + counts = [ + db.execute( + f"SELECT count(*),coalesce(sum(length({col})),0) FROM {table}" + ).fetchone() + for table, col in (("papers", "image"), ("draft_fonts", "bytes")) + ] + return counts, sorted( + p.name + for p in directory.rglob("*") + if p.is_file() and not p.name.startswith("drafts.sqlite3") + ) + + await tune(1, changes={"ink": "#363840"}) + await tune(2, changes={"ink_opacity": 87}) + old = await review(3) + await tune(3, paper_guides=guides, note="Align to the printed lines.") + new = await review(4) + quote = "保留 v3 的墨色,采用 v4 的位置。" + await call( + client, + "annotate_review", + **key, + review_id=old["review_id"], + origin="user_quote", + text=quote, + ) + await call( + client, + "annotate_review", + **key, + review_id=new["review_id"], + origin="model_observation", + text="上部基线更贴近横线。", + ) + inventory = assets() + result = await compare(3, 4) + assert await compare(3, 4) == result + assert assets() == inventory + assert [a["revision"] for a in result["actions"]] == [4] + assert result["actions"][0]["details"]["paper_guides"] == guides + assert result["before"]["feedback"] == [{"origin": "user_quote", "text": quote}] + assert result["after"]["review_id"] == new["review_id"] + delta = result["comparison"]["delta"] + assert delta["global_ink_settings_equal"] + top, _, bottom = delta["by_image_third"] + assert min(top["supported_before_after"]) >= 3 and top["median_abs_dy_px"] < 0, ( + result + ) + assert ( + bottom["median_abs_dy_px"] is None + and bottom["limitation"] == "insufficient_ridge_support" + ) + await tune(4, changes={"ink_opacity": 0}) + assert "missing_after_review" in (await compare(4, 5))["comparison"]["limitations"] + await review(5) + invisible = (await compare(4, 5))["comparison"]["delta"] + assert ( + invisible["visibility_after"] == "no_visible_change" + and invisible["by_image_third"][0]["median_abs_dy_px"] == 0 + ) + await tune(5, changes={"right_margin": 318}) + await review(6) + reflow = (await compare(4, 6))["comparison"] + assert ( + reflow["delta"] is None + and "page_content_changed_or_repaginated" in reflow["limitations"] + ) + return key, old["review_id"], quote diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index a66a5022..ac92aa76 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -14,6 +14,8 @@ from tempfile import TemporaryDirectory from zipfile import ZipFile +import review_comparison + from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client @@ -111,6 +113,7 @@ async def smoke(command, arguments, out): assert info.serverInfo.name == "panache-mcp" tools = await client.list_tools() assert {t.name for t in tools.tools} == { + "annotate_review", "list_fonts", "describe_controls", "tune_handwriting", @@ -209,6 +212,7 @@ async def smoke(command, arguments, out): "save_section", {"markdown": "missing", "paper_path": str(paper_path)} ) assert failed.isError + comparison_key, reviewed_id, user_quote = await review_comparison.exercise(client, Path(temp), call) # Keep the traditional eight verse lines for a single folio. poem = POEM.replace(",", ",\n") saved = ( @@ -297,6 +301,13 @@ async def progress(value, total, message=None): ) async with stdio_client(params) as streams, ClientSession(*streams) as client: await client.initialize() + 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}] + 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"} + assert (await client.call_tool("read_section",{**gkey,"view":"review","review_id":reviewed_id})).isError assert png(await call(client, "preview_handwriting", **gkey, revision=6)) == imported_preview assert (await call(client, "list_drafts")).structuredContent["drafts"][0][ "draft_id" diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index 5ebf308e..67d59a5a 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -2,7 +2,7 @@ ## 工具发现 -Panache 在 `tools/list` 中稳定公布九个任务入口。模型可以直接保存、预览、导出;只有需要调参时才调用 `describe_controls`。目录按排版、字体、墨迹、扰动、删除线和拍摄信息六组组织,和服务端参数校验共用同一份定义。 +Panache 在 `tools/list` 中公布十个任务入口。模型可以直接保存、预览、导出;只有需要调参时才调用 `describe_controls`。目录按排版、字体、墨迹、扰动、删除线和拍摄信息六组组织,和服务端参数校验共用同一份定义。 MCP 的工具列表支持分页。客户端可能取完所有页;分页能控制单次协议响应大小。Claude 的 Tool Search 支持宿主配置延迟加载,实际进入模型上下文的工具由宿主决定。Panache 的 stdio 客户端也可以完全不提供搜索,只用标准工具列表和调用接口。项目目前选择按需查询参数,避免为小型目录引入搜索索引和额外的调用步骤。设计依据见 [MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)、[MCP 路线图中的渐进发现](https://blog.modelcontextprotocol.io/posts/mcp-roadmap/) 和 [Claude Tool Search 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)。 @@ -53,7 +53,11 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 `view="review"` 按需返回三张按相同比例缩放的图片。橙色边界和青色参考线来自书写区估计,叠图可与裸底纸对照。在原分辨率比较显示在纸上的墨迹和底纸,按图像上中下三等分统计 RGB 任一通道变化至少 8 级的像素及落在参考区外的数量。在抽样字形调整后的基线中点附近搜索底纸的局部暗线并报告垂直偏差中位数和支持样本数;校徽或背景纹理也可能给出暗线,无足够对比时返回空值。短文自然可能只覆盖上部。对有正文的页面,零像素变化是重新检查的明确信号。没有自动审美评分,验收时仍要查看原图,必要时请用户指出具体位置。 -轨迹按稿件和版本保存在本机。修改操作与简短备注在同一事务提交,同一版本、节、页只保留一份复盘指标。查询不会返回原文、字体数据、图片字节或完整对话。这里的轨迹指已执行的动作和可复查的结果。模型可以对照前后版本调整下一步;没有修改模型权重或自动跨用户积累经验。 +轨迹按稿件和版本保存在本机。修改操作与简短备注在同一事务提交,复盘按稿件版本、节页、测量算法版本及成品像素摘要去重。像素摘要为 SHA-256,输入依次是两个小端 u32 宽高和导出预览的原始 RGBA8 字节,在透明墨迹叠回纸张前计算。算法或成品变化产生新 ID,旧库迁移保留原证据并将未知来源字段置空。导出按不同节页计数,并取每页最近归档的测量。改变测量口径时应提升算法版本。查询不会返回原文、字体数据、图片字节或完整对话。这里的轨迹指已执行的动作和可复查的结果。模型可以对照前后版本调整下一步;没有修改模型权重或自动跨用户积累经验。 + +比较默认仅返回数据,取同一节页两版最近归档的复盘及各自最近 50 条署名反馈。精确 ID 可用来回查对比时所用的观察,更早的反馈也可在轨迹中分页查找。页面成员摘要绑定不可变节版本和该页所有字形的源位置;重新保存该节可能保守地中止定量比较。分区至少在两侧各有 3 个暗线支持样本才返回中位偏差的差值,这是最低报告门槛。它不能证明两组样本完全相同或有统计显著性。越界像素相对各版本自己的书写区计算。 + +反馈是调用方标注来源的本稿记录。`user_quote` 应逐字引用人的意见,`model_observation` 用于模型自己的观察。历史编辑备注的作者无法追溯时仍归为编辑上下文。若一轮同时改了墨迹与参考线,对比列出操作和观测结果,具体因果与偏好留给复核者判断。 该设计借鉴了 Reflexion 将任务反馈留给下一次尝试的做法。关于模型仅靠自我判断纠错的研究使用的是推理任务,本项目将其作为设计动机。这里的效果由本项目的图像样本和回归用例单独验证。[Reflexion(NeurIPS 2023)](https://proceedings.neurips.cc/paper/2023/hash/1b44b878bb782e6954cd888628510e90-Abstract-Conference.html) · [外部反馈与自我纠错(ICLR 2024)](https://proceedings.iclr.cc/paper_files/paper/2024/hash/8b4add8b0aa8749d80a34ca5d941c355-Abstract-Conference.html) From 8358969b2cb74ff585d217b7eb996a5a9ab6ab7b Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:39:59 +0800 Subject: [PATCH 05/24] =?UTF-8?q?docs(crates/panache-mcp):=20=E4=BF=9D?= =?UTF-8?q?=E7=95=99=E5=A4=8D=E7=9B=98=E8=AE=BE=E8=AE=A1=E4=BE=9D=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:工具文档混有一次性的验证结论。 解决手段:保留研究动机,将验证证据集中在测试与 PR。 收益:长期文档聚焦稳定的接口约定。 --- crates/panache-mcp/tool-design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index 67d59a5a..8511dac8 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -59,7 +59,7 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 反馈是调用方标注来源的本稿记录。`user_quote` 应逐字引用人的意见,`model_observation` 用于模型自己的观察。历史编辑备注的作者无法追溯时仍归为编辑上下文。若一轮同时改了墨迹与参考线,对比列出操作和观测结果,具体因果与偏好留给复核者判断。 -该设计借鉴了 Reflexion 将任务反馈留给下一次尝试的做法。关于模型仅靠自我判断纠错的研究使用的是推理任务,本项目将其作为设计动机。这里的效果由本项目的图像样本和回归用例单独验证。[Reflexion(NeurIPS 2023)](https://proceedings.neurips.cc/paper/2023/hash/1b44b878bb782e6954cd888628510e90-Abstract-Conference.html) · [外部反馈与自我纠错(ICLR 2024)](https://proceedings.iclr.cc/paper_files/paper/2024/hash/8b4add8b0aa8749d80a34ca5d941c355-Abstract-Conference.html) +该设计借鉴了 Reflexion 将任务反馈留给下一次尝试的做法。关于模型仅靠自我判断纠错的研究使用的是推理任务,本项目将其作为设计动机。[Reflexion(NeurIPS 2023)](https://proceedings.neurips.cc/paper/2023/hash/1b44b878bb782e6954cd888628510e90-Abstract-Conference.html) · [外部反馈与自我纠错(ICLR 2024)](https://proceedings.iclr.cc/paper_files/paper/2024/hash/8b4add8b0aa8749d80a34ca5d941c355-Abstract-Conference.html) SICA 将历次尝试及其评估结果放入档案,供下一轮决策参考。本工具采用了可按版本取回结果的做法,作用域限于当前稿件,修改对象是稿件与排版参数。[SICA 作者实现](https://github.com/MaximeRobeyns/self_improving_coding_agent) From 629e78d10818091532a5ec23c10c7ff28ce7e608 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:40:35 +0800 Subject: [PATCH 06/24] =?UTF-8?q?fix(crates/panache-mcp):=20=E6=8F=90?= =?UTF-8?q?=E7=A4=BA=E6=9C=AA=E5=A4=8D=E7=9B=98=E9=A1=B5=E7=9A=84=E5=B1=80?= =?UTF-8?q?=E9=83=A8=E5=A2=A8=E8=BF=B9=E9=A3=8E=E9=99=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:全局墨色正常时,局部字形仍能被调为完全透明。 解决手段:导出返回缺少可见性证据的页数,以单字透明图检验四角投影和零墨迹。 收益:覆盖从实际像素到导出提示的路径,并避免对正确的投影再求逆。 --- .github/workflows/flutter_desktop.yml | 2 +- crates/panache-mcp/src/main.rs | 4 ++-- crates/panache-mcp/tests/smoke.py | 28 ++++++++++++++++++++++++++- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/.github/workflows/flutter_desktop.yml b/.github/workflows/flutter_desktop.yml index 24e69120..18345c80 100644 --- a/.github/workflows/flutter_desktop.yml +++ b/.github/workflows/flutter_desktop.yml @@ -59,7 +59,7 @@ jobs: - name: 验证随包 MCP 的预览、导出和历史恢复 shell: bash run: | - python -m pip install "mcp>=1.12,<2" + python -m pip install "mcp>=1.12,<2" Pillow if [[ "$RUNNER_OS" == Windows ]]; then python crates/panache-mcp/tests/smoke.py target/desktop-package/windows/Panache/handwriting_app.exe --server-arg=--mcp python crates/panache-mcp/tests/context_metrics.py target/desktop-package/windows/Panache/handwriting_app.exe --mcp diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 7f392d56..f5fa5d80 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -517,10 +517,10 @@ impl Panache { } }, )?; - let warning=if zero_text_ink || visibility_flags>0 {"墨迹可见性需要复查。"}else{""}; + let warning=if zero_text_ink || visibility_flags>0 {"墨迹可见性需要复查。"}else if (reviewed as usize)=1.12,<2"] +# dependencies = ["mcp>=1.12,<2", "Pillow"] # /// """Exercise a real MCP client over stdio. Optionally keep the poem's PNG and PDF.""" import argparse import asyncio import base64 +import io import json import os import shutil @@ -14,6 +15,8 @@ from tempfile import TemporaryDirectory from zipfile import ZipFile +from PIL import Image + import review_comparison from mcp import ClientSession, StdioServerParameters @@ -100,6 +103,28 @@ async def review_workflow(client, key, guides, font_path): return transparent +async def placement_pixels(client): + saved = (await call(client, "save_section", markdown="字", style={"seed": 17})).structuredContent + key = {"draft_id": saved["draft_id"]} + await call(client, "tune_handwriting", **key, expected_revision=1, changes={"transparent_background": True}) + glyph = (await call(client, "preview_handwriting", **key, view="layout")).structuredContent["glyphs"][0] + async def ink_box(): + with Image.open(io.BytesIO(png(await call(client, "preview_handwriting", **key)))) as im: + return im.getchannel("A").getbbox() + original = await ink_box() + quad = [[140, 180], [255, 170], [250, 254], [145, 255]] + edit = dict(**key, section=1, page=1, ids=[glyph["id"]]) + await call(client, "adjust_glyphs", **edit, expected_revision=2, target_quad=quad) + left, top, right, bottom = await ink_box() + assert 139 <= left < right <= 256 and 169 <= top < bottom <= 256 + assert right - left > 2 * (original[2] - original[0]) + await call(client, "adjust_glyphs", **edit, expected_revision=3, opacity=0) + assert await ink_box() is None + exported = await call(client, "export_handwriting", **key) + assert exported.structuredContent["review"]["pages_without_visibility_evidence"] == 1 + assert "局部墨迹" in exported.content[0].text + + async def smoke(command, arguments, out): with TemporaryDirectory() as temp: params = StdioServerParameters( @@ -212,6 +237,7 @@ async def smoke(command, arguments, out): "save_section", {"markdown": "missing", "paper_path": str(paper_path)} ) assert failed.isError + await placement_pixels(client) comparison_key, reviewed_id, user_quote = await review_comparison.exercise(client, Path(temp), call) # Keep the traditional eight verse lines for a single folio. poem = POEM.replace(",", ",\n") From 0448319c3b8fc9560b60e1d4f4802f0ced5d9c12 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:40:37 +0800 Subject: [PATCH 07/24] =?UTF-8?q?test(crates/panache-mcp):=20=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E4=B8=8A=E4=BC=A0=E5=AD=97=E4=BD=93=E5=AE=9E=E9=99=85?= =?UTF-8?q?=E5=8F=82=E4=B8=8E=E6=B8=B2=E6=9F=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:重启前后结果一致仍可能一直使用默认字体。 解决手段:固定稿件、种子和版式,只切换默认与上传字体,重启后回查两份版本。 收益:可检出静默回退到默认字体的问题。 --- crates/panache-mcp/tests/smoke.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index e8ecbdec..72d8b1f3 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -51,6 +51,8 @@ async def review_workflow(client, key, guides, font_path): client, "tune_handwriting", **key, expected_revision=3, paper_guides=guides, font_path=str(font_path), note="Write inside the indicated area.", )).structuredContent + imported_font = revised["controls"]["font"] + assert imported_font.startswith("upload:") font_path.unlink() assert revised["revision"] == 4 and revised["paper"]["alignment"] == "manual_guides" assert (await client.call_tool("tune_handwriting", {**key, "expected_revision": 3, "paper_guides": guides})).isError @@ -100,7 +102,14 @@ async def review_workflow(client, key, guides, font_path): original = (await call(client, "read_section", **key, revision=1, view="summary")).structuredContent["paper"] assert restored == original assert (await call(client,"read_section",**key,revision=4,view="summary")).structuredContent["paper"] != original - return transparent + # Change only the font between two otherwise identical historical revisions. + await call(client, "tune_handwriting", **key, expected_revision=9, + changes={"ink_opacity": 100, "font": "霞鹜文楷.ttf"}) + default = png(await call(client, "preview_handwriting", **key, revision=10)) + await call(client, "tune_handwriting", **key, expected_revision=10, changes={"font": imported_font}) + uploaded = png(await call(client, "preview_handwriting", **key, revision=11)) + assert default != uploaded + return transparent, default, uploaded async def placement_pixels(client): @@ -227,7 +236,7 @@ async def smoke(command, arguments, out): paper_path.unlink() font_path = Path(temp) / "imported.ttf" shutil.copyfile(Path(__file__).resolve().parents[3] / "assets/font_assets/李国夫手写体.ttf", font_path) - imported_preview = await review_workflow(client, gkey, guides, font_path) + imported_preview, default_font_image, uploaded_font_image = await review_workflow(client, gkey, guides, font_path) paper_id = custom["draft_id"] paper_preview = png( await call(client, "preview_handwriting", draft_id=paper_id) @@ -335,6 +344,8 @@ async def progress(value, total, message=None): assert {e["origin"] for e in events} >= {"draft_edit","measurement","user_quote","model_observation"} assert (await client.call_tool("read_section",{**gkey,"view":"review","review_id":reviewed_id})).isError assert png(await call(client, "preview_handwriting", **gkey, revision=6)) == imported_preview + assert png(await call(client, "preview_handwriting", **gkey, revision=10)) == default_font_image + assert png(await call(client, "preview_handwriting", **gkey, revision=11)) == uploaded_font_image assert (await call(client, "list_drafts")).structuredContent["drafts"][0][ "draft_id" ] == doc From 538299a48bfefecd5698a7af5e2162e3b78cccdf Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:51:03 +0800 Subject: [PATCH 08/24] =?UTF-8?q?feat(crates/panache-mcp):=20=E7=99=BB?= =?UTF-8?q?=E8=AE=B0=E5=AF=BC=E5=87=BA=E5=BD=92=E5=B1=9E=E5=B9=B6=E9=99=90?= =?UTF-8?q?=E5=88=B6=E5=BA=9F=E5=BC=83=E6=96=87=E4=BB=B6=E6=B8=85=E7=90=86?= =?UTF-8?q?=E8=8C=83=E5=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:同一稿件会累积导出,旧文件名无法证明归属,直接清理可能使交付路径或复盘依据失效。 解决手段:提供用量、按稿预览和仅限中断导出临时文件的清理入口。对新大文件提供目录预算与卷空间预留,跨进程串行写入,并在执行前复核文件登记与身份。 收益:模型可报告可安全释放的字节数。子进程中断、文件替换、并发写入、重复执行和历史评语回查均有回归覆盖。 --- Cargo.lock | 131 +++++++- crates/panache-mcp/Cargo.toml | 2 + crates/panache-mcp/README.md | 21 ++ crates/panache-mcp/src/drafts.rs | 2 +- crates/panache-mcp/src/engine.rs | 28 +- crates/panache-mcp/src/inputs.rs | 2 +- crates/panache-mcp/src/main.rs | 64 +++- crates/panache-mcp/src/storage.rs | 353 ++++++++++++++++++++++ crates/panache-mcp/src/storage/cleanup.rs | 281 +++++++++++++++++ crates/panache-mcp/src/storage/tests.rs | 178 +++++++++++ crates/panache-mcp/src/tuning.rs | 4 + crates/panache-mcp/tests/smoke.py | 3 + crates/panache-mcp/tool-design.md | 2 +- 13 files changed, 1034 insertions(+), 37 deletions(-) create mode 100644 crates/panache-mcp/src/storage.rs create mode 100644 crates/panache-mcp/src/storage/cleanup.rs create mode 100644 crates/panache-mcp/src/storage/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 2393373a..30da34f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -470,7 +470,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -515,6 +515,15 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "file-id" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1fc6a637b6dc58414714eddd9170ff187ecb0933d4c7024d1abbd23a3cc26e9" +dependencies = [ + "windows-sys 0.60.2", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -563,6 +572,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "futures" version = "0.3.34" @@ -1316,7 +1335,7 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1404,7 +1423,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1491,7 +1510,9 @@ version = "0.1.0" dependencies = [ "anyhow", "base64 0.23.1", + "file-id", "fontdue", + "fs2", "handwriting-core", "image", "rmcp", @@ -1865,7 +1886,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2099,7 +2120,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2192,7 +2213,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2267,7 +2288,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2626,6 +2647,28 @@ dependencies = [ "safe_arch", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-core" version = "0.62.2" @@ -2685,6 +2728,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -2694,6 +2746,71 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/crates/panache-mcp/Cargo.toml b/crates/panache-mcp/Cargo.toml index 9bc78bbe..9df6ee2e 100644 --- a/crates/panache-mcp/Cargo.toml +++ b/crates/panache-mcp/Cargo.toml @@ -21,3 +21,5 @@ tempfile = "3" fontdue = "0.9.4" image = { version = "0.25", default-features = false } anyhow = "1" +fs2 = "0.4.3" +file-id = "0.2.3" diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index f770660b..3d354c25 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -54,6 +54,9 @@ cargo build --locked --release -p panache-mcp | `export_handwriting` | 按节顺序导出整份稿件,返回绝对路径、版本和实际页数。格式可选 `pdf` 或 `zip`,ZIP 从 `0.png` 开始编号。 | | `describe_controls` | 先列参数组,再按 `group` 查看单位、范围和枚举值。附上 `draft_id` 和 `revision` 可读取该版的实际值。 | | `tune_handwriting` | 可在原稿上更新参考线、导入本机字体,并一次提交多项全稿参数,如 `{"ink_opacity":85,"word_spacing":2}`。`null` 恢复建稿时的设置。 | +| `storage_usage` | 查询目录和逐稿用量,以及当前预算。 | +| `plan_cleanup` | 按稿列出废弃临时文件和受保护的已交付导出。 | +| `apply_cleanup` | 复核计划,仅清理选中的废弃临时文件。 | | `annotate_review` | 将用户原话或模型观察挂到指定复盘 ID,保持稿件版本号。 | | `adjust_glyphs` | 先用 `preview_handwriting(view="layout")` 取编号和坐标,再按同一节、页和版本调整选中字形。 | @@ -65,6 +68,24 @@ cargo build --locked --release -p panache-mcp 整稿上限为整理后 10 万字、200 页。完整导出只在调用导出工具时执行;客户端可以取消,提供进度令牌时可看到已完成页数。ZIP 逐页写盘,PDF 在内存中组装压缩页面后写盘。结果成功后才移入 `exports/`。稿件及历史持续保存在 `PANACHE_MCP_HOME`;Windows 默认是 `%LOCALAPPDATA%/Panache/mcp`,其他系统默认是 `$XDG_DATA_HOME/Panache/mcp` 或 `~/.local/share/Panache/mcp`。 +## 容量与清理 + +用 `storage_usage` 查询数据目录内常规文件的长度、数据库及其 WAL/SHM 大小、导出目录和所在卷剩余字节。可传 `draft_id` 查看一稿的正文历史、底纸、字体、逐页证据、评语等内容字节数。文件长度、SQLite 内容长度和磁盘分配量口径不同。跨稿复用同一字体的文件目前仍按稿保存。 + +管理员可在 MCP 启动环境设置以下无符号整数字节值,默认均未设置。多个 MCP 进程共用一个本地目录时应使用相同配置。 + +| 环境变量 | 触发行为 | +| --- | --- | +| `PANACHE_MCP_WARN_BYTES` | 目录文件总长度达到阈值时,用量查询返回 `warning=true`。 | +| `PANACHE_MCP_MAX_HOME_BYTES` | 用目录剩余预算控制新的字体、底纸和导出内容。正文、复盘与 SQLite 页、索引、日志仍可增长,这是大文件写入预算。 | +| `PANACHE_MCP_MIN_FREE_BYTES` | 为该磁盘卷保留空间。导入时检查内容长度;导出时按文件增长量检查,包括 ZIP 写入和结尾索引。 | + +容量不足时可继续读取稿件、比较历史和查询用量。查询不会改变稿件。导出、导入大文件和执行清理共用同一数据目录的跨进程锁;遇到 busy 可在当前操作结束后重试。 + +1. 用 `plan_cleanup(draft_id=…)` 只读预览。每页最多 50 条登记,可用 `next_after_id` 继续。成功交付的 PDF/ZIP 列出版本、文件名与字节数,交付路径可能仍有人引用。旧版未登记文件计入目录用量。 +2. 只有 `abandoned_temp` 可以交给 `apply_cleanup(plan_id=…, candidate_ids=[…])`。计划限当前服务进程,五分钟有效。工具在执行时复核登记、文件身份、修改时间、大小和任务锁,返回实际移除的文件长度及跳过原因。 +3. 若用户要求的释放量大于可安全清理的字节数,报告差额。成功交付的导出、来源不明的文件、正文、历史、纸张、字体和复盘评语均受保护。低磁盘空间不会触发自动淘汰。需要删除已交付成品时,由用户按报告中的具体文件自行处理。 + ## 照片排版与成品复盘 1. 用 `save_section` 导入照片并保留版本号。用 `preview_handwriting(view="review")` 取得同一页的底纸、成品和叠图。图片最多长边 900 像素,像素坐标以返回的 `photo_size` 为准。需要看笔画细节时取原尺寸 `view="image"`。 diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 151eb9b9..1ce64138 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -154,7 +154,7 @@ impl Drafts { observations::initialize(&mut drafts.connect()?)?; Ok(drafts) } - fn connect(&self) -> Result { + pub(crate) fn connect(&self) -> Result { let db = Connection::open(&self.0)?; db.busy_timeout(std::time::Duration::from_secs(5))?; Ok(db) diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index a231a6f2..9dedbbbf 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -1,15 +1,7 @@ use anyhow::{Context, Result, ensure}; use base64::{Engine as _, engine::general_purpose::STANDARD}; use handwriting_core::{Cancellation, FontBook, Limits, RenderRequest, export}; -use std::{ - collections::HashMap, - fs, - io::Write, - path::{Path, PathBuf}, - sync::Arc, -}; -use tempfile::NamedTempFile; -use uuid::Uuid; +use std::{collections::HashMap, fs, io::Write, path::PathBuf, sync::Arc}; use crate::{ Format, @@ -614,14 +606,13 @@ impl Engine { } pub fn export( &mut self, - dir: &Path, + writer: &mut crate::storage::BudgetWriter<'_>, draft: &Snapshot<'_>, sections: Vec
, format: Format, cancel: &Cancellation, mut progress: impl FnMut(usize), - ) -> Result<(PathBuf, usize)> { - let mut temp = NamedTempFile::new_in(dir)?; + ) -> Result { let mut count = 0; let mut background = draft.background()?; let camera = draft.camera(background.as_deref())?; @@ -644,24 +635,19 @@ impl Engine { cancel.check()?; Ok(()) }; - let extension = match format { + match format { Format::Pdf => { let mut pdf = export::PdfExport::lossless(); render_sections(&mut |_, page| pdf.add(page))?; - temp.write_all(&pdf.finish_with_camera(&camera))?; - "pdf" + writer.write_all(&pdf.finish_with_camera(&camera))?; } Format::Zip => { - let mut zip = export::ZipExport::new(temp.as_file_mut()); + let mut zip = export::ZipExport::new(writer); render_sections(&mut |i, page| zip.add_with_camera(i, page, &camera))?; zip.finish()?; - "zip" } }; - temp.as_file_mut().flush()?; cancel.check()?; - let path = dir.join(format!("panache-{}.{}", Uuid::new_v4(), extension)); - temp.persist_noclobber(&path)?; - Ok((path, count)) + Ok(count) } } diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index e203fbba..a1b6c1b9 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -13,7 +13,7 @@ pub enum Paper { Dots, } -#[derive(Deserialize, JsonSchema, Default)] +#[derive(Clone, Copy, Deserialize, JsonSchema, Default)] #[serde(rename_all = "snake_case")] pub enum Format { #[default] diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index f5fa5d80..95617307 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -6,6 +6,7 @@ mod markdown; mod paper; mod placement; mod review; +mod storage; mod tuning; use anyhow::{Context, Result, ensure}; @@ -32,7 +33,7 @@ struct State { drafts: Drafts, engine: Mutex, fonts: Vec, - output: PathBuf, + storage: storage::Storage, worker: Arc, render_slot: Arc, prepare_slot: Arc, @@ -60,6 +61,20 @@ impl Drop for CancelOnDrop { } impl Panache { + async fn storage_task( + &self, + run: impl FnOnce(&storage::Storage, &Drafts) -> Result + Send + 'static, + ) -> CallToolResult { + let state = self.0.clone(); + tool_result( + async { + let value = tokio::task::spawn_blocking(move || run(&state.storage, &state.drafts)) + .await??; + Ok(reply(value.to_string(), value)) + } + .await, + ) + } async fn render( &self, ctx: RequestContext, @@ -161,6 +176,10 @@ impl Panache { } _ => None, }; + let _budget = paper + .as_ref() + .map(|p| state.storage.import(p.bytes.len())) + .transpose()?; state .drafts .save(&input, &prepared, style.as_ref(), paper.as_ref()) @@ -491,6 +510,37 @@ impl Panache { ) } + #[tool( + annotations(read_only_hint = true, open_world_hint = false), + description = "Inspect MCP home file sizes, available volume space, limits and protected payload. Optionally scope logical counts and registered exports to one draft. Use before considering cleanup." + )] + async fn storage_usage(&self, Parameters(input): Parameters) -> CallToolResult { + self.storage_task(move |store, drafts| store.usage(drafts, input)) + .await + } + #[tool( + annotations(read_only_hint = true, open_world_hint = false), + description = "Preview one draft's registered exports, eligible abandoned temporary files and byte estimates. Delivered files are report-only. No disk changes. Pass next_after_id to see more." + )] + async fn plan_cleanup( + &self, + Parameters(input): Parameters, + ) -> CallToolResult { + self.storage_task(move |store, drafts| store.plan_cleanup(drafts, input)) + .await + } + #[tool( + annotations(destructive_hint = true, open_world_hint = false), + description = "Remove selected abandoned temporary files from a fresh plan in this session. Intended only for reclaiming failed exports. A plan is not permission to delete user deliverables. No paths, completed exports, manuscript history, fonts, papers or reviews can be selected." + )] + async fn apply_cleanup( + &self, + Parameters(input): Parameters, + ) -> CallToolResult { + self.storage_task(move |store, drafts| store.apply_cleanup(drafts, input)) + .await + } + #[tool( description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns path and page count. For visual acceptance, inspect view=review on the intended revision first, especially after moving glyphs or changing ink." )] @@ -507,8 +557,9 @@ impl Panache { 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 (path, pages) = engine.export( - &state.output, &draft, sections, input.format.unwrap_or_default(), cancel, + 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| { if let Some(token) = &progress_token { let update = rmcp::model::ProgressNotificationParam::new(token.clone(), pages as f64) @@ -516,7 +567,7 @@ impl Panache { let _ = tokio::runtime::Handle::current().block_on(peer.notify_progress(update)); } }, - )?; + ))?; let warning=if zero_text_ink || visibility_flags>0 {"墨迹可见性需要复查。"}else if (reviewed as usize) Result<()> { .context("Set PANACHE_MCP_HOME to a writable directory")?; let output = home.join("exports"); fs::create_dir_all(&output)?; + let drafts = Drafts::open(&home)?; let state = State { - drafts: Drafts::open(&home)?, + storage: storage::Storage::open(&home, &drafts)?, + drafts, fonts: engine.names.clone(), engine: Mutex::new(engine), - output: std::path::absolute(output)?, worker: fs::read_to_string(worker)?.into(), render_slot: Arc::new(Semaphore::new(1)), prepare_slot: Arc::new(Semaphore::new(1)), diff --git a/crates/panache-mcp/src/storage.rs b/crates/panache-mcp/src/storage.rs new file mode 100644 index 00000000..9cf077d6 --- /dev/null +++ b/crates/panache-mcp/src/storage.rs @@ -0,0 +1,353 @@ +//! Ownership and write budgets for the MCP data directory. +mod cleanup; +#[cfg(test)] +mod tests; +pub use cleanup::{ApplyCleanup, CleanupScope}; + +use crate::{Format, drafts::Drafts}; +use anyhow::{Context, Result, ensure}; +use rusqlite::{Connection, params}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::{ + env, + fs::{self, File, Metadata, OpenOptions}, + io::{self, Seek, SeekFrom, Write}, + path::{Path, PathBuf}, + sync::Mutex, +}; +use tempfile::Builder; +use uuid::Uuid; + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Usage { + /// Optional draft for logical payload counts. File and volume totals always cover this MCP home. + pub draft_id: Option, +} + +#[derive(Default, Serialize)] +struct Policy { + warn_bytes: Option, + max_home_bytes: Option, + min_free_bytes: Option, +} + +fn setting(key: &str) -> Result> { + env::var_os(key) + .map(|raw| { + raw.to_str() + .context("Invalid environment value")? + .parse() + .with_context(|| format!("{key} must be an unsigned byte count")) + }) + .transpose() +} + +pub struct Storage { + home: PathBuf, + exports: PathBuf, + policy: Policy, + plans: Mutex, +} + +// Windows junctions can have directory type even though they redirect traversal. +fn redirected(meta: &Metadata) -> bool { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + meta.file_attributes() & 0x400 != 0 + } + #[cfg(not(windows))] + { + meta.is_symlink() + } +} + +fn metadata(path: &Path) -> io::Result> { + match fs::symlink_metadata(path) { + Ok(m) => Ok(Some(m)), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +fn directory_bytes(root: &Path) -> Result { + let mut total = 0u64; + let mut dirs = vec![root.to_owned()]; + while let Some(dir) = dirs.pop() { + for entry in fs::read_dir(dir)? { + let path = entry?.path(); + let Some(m) = metadata(&path)? else { continue }; + if redirected(&m) { + continue; + } + if m.is_dir() { + dirs.push(path) + } else if m.is_file() { + total = total.saturating_add(m.len()) + } + } + } + Ok(total) +} + +fn identity(path: &Path) -> Result { + use file_id::FileId::*; + let id = match file_id::get_file_id(path)? { + Inode { + device_id, + inode_number, + } => format!("i:{device_id}:{inode_number}"), + LowRes { + volume_serial_number, + file_index, + } => format!("l:{volume_serial_number}:{file_index}"), + HighRes { + volume_serial_number, + file_id, + } => format!("h:{volume_serial_number}:{file_id}"), + }; + let created = fs::symlink_metadata(path)? + .created() + .ok() + .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_nanos()); + Ok(format!("{id}:{created:?}")) +} + +impl Storage { + pub fn open(home: &Path, db: &Drafts) -> Result { + let home = home.canonicalize()?; + let exports = home.join("exports"); + let store = Self { + home, + exports, + policy: Policy { + warn_bytes: setting("PANACHE_MCP_WARN_BYTES")?, + max_home_bytes: setting("PANACHE_MCP_MAX_HOME_BYTES")?, + min_free_bytes: setting("PANACHE_MCP_MIN_FREE_BYTES")?, + }, + plans: Mutex::default(), + }; + store.check_directory()?; + store.lock_file()?; + db.connect()?.execute_batch( + "CREATE TABLE IF NOT EXISTS export_files( + id TEXT PRIMARY KEY, draft TEXT NOT NULL, revision INTEGER NOT NULL, + format TEXT NOT NULL, temp_name TEXT NOT NULL, identity TEXT NOT NULL, + published INTEGER NOT NULL DEFAULT 0); + CREATE INDEX IF NOT EXISTS exports_by_draft ON export_files(draft,id);", + )?; + Ok(store) + } + + fn check_directory(&self) -> Result<()> { + let m = fs::symlink_metadata(&self.exports)?; + ensure!( + m.is_dir() && !redirected(&m), + "Expected a local exports directory" + ); + Ok(()) + } + + fn lock_file(&self) -> Result { + let path = self.home.join(".large-writes.lock"); + if let Some(m) = metadata(&path)? { + ensure!(m.is_file() && !redirected(&m), "Invalid storage lock"); + } + Ok(OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(path)?) + } + + pub fn write_lock(&self) -> Result { + self.check_directory()?; + let lock = self.lock_file()?; + lock.try_lock() + .context("Storage busy: retry when the current import, export or cleanup ends")?; + Ok(lock) + } + + fn allowance(&self) -> Result { + let mut remaining = u64::MAX; + if let Some(cap) = self.policy.max_home_bytes { + remaining = cap.saturating_sub(directory_bytes(&self.home)?); + } + if let Some(reserve) = self.policy.min_free_bytes { + remaining = remaining.min(fs2::available_space(&self.home)?.saturating_sub(reserve)); + } + Ok(remaining) + } + + pub fn import(&self, bytes: usize) -> Result { + let guard = self.write_lock()?; + let remaining = self.allowance()?; + ensure!( + bytes as u64 <= remaining, + "Storage limit: {bytes} requested, {remaining} available for imports; inspect storage_usage and plan_cleanup" + ); + Ok(guard) + } + + pub fn export( + &self, + drafts: &Drafts, + draft: &str, + revision: u32, + format: Format, + render: F, + ) -> Result<(PathBuf, usize)> + where + F: FnOnce(&mut BudgetWriter<'_>) -> Result, + { + let _guard = self.write_lock()?; + ensure!( + self.allowance()? > 0, + "Storage limit: no capacity for a new export; inspect storage_usage and plan_cleanup" + ); + let db = drafts.connect()?; + let id = Uuid::new_v4().to_string(); + let extension = match format { + Format::Pdf => "pdf", + Format::Zip => "zip", + }; + let mut temp = Builder::new() + .prefix(".panache-") + .suffix(".part") + .tempfile_in(&self.exports)?; + let name = temp + .path() + .file_name() + .and_then(|v| v.to_str()) + .context("Invalid staging name")?; + db.execute("INSERT INTO export_files(id,draft,revision,format,temp_name,identity) VALUES(?,?,?,?,?,?)", + params![id,draft,revision,extension,name,identity(temp.path())?])?; + let path = self.exports.join(format!("panache-{id}.{extension}")); + let publish = || -> Result<_> { + let mut output = BudgetWriter { + file: temp.as_file_mut(), + limit: self.allowance()?, + reserve: self.policy.min_free_bytes, + volume: &self.home, + }; + let pages = render(&mut output)?; + output.flush()?; + temp.persist_noclobber(&path)?; + db.execute("UPDATE export_files SET published=1 WHERE id=?", [&id])?; + Ok(pages) + }; + 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| (path, pages)) + } + + pub fn usage(&self, drafts: &Drafts, input: Usage) -> Result { + self.check_directory()?; + if let Some(id) = &input.draft_id { + drafts.snapshot(id, None)?; + } + let db = drafts.connect()?; + let total = directory_bytes(&self.home)?; + let export_bytes = directory_bytes(&self.exports)?; + let mut database = serde_json::Map::new(); + for name in ["drafts.sqlite3", "drafts.sqlite3-wal", "drafts.sqlite3-shm"] { + database.insert( + name.into(), + json!( + metadata(&self.home.join(name))? + .filter(|m| m.is_file() && !redirected(m)) + .map_or(0, |m| m.len()) + ), + ); + } + let mut logical = serde_json::Map::new(); + for (label, table, bytes) in [ + ("fonts", "draft_fonts", "length(bytes)"), + ("papers", "papers", "length(image)"), + ( + "section_versions", + "sections", + "octet_length(source)+octet_length(prepared)", + ), + ( + "observations", + "review_observations", + "octet_length(evidence)", + ), + ( + "feedback", + "review_feedback JOIN review_observations USING(review_id)", + "octet_length(note)", + ), + ("glyph_edits", "glyph_edits", "octet_length(edits)"), + ("edit_notes", "edit_notes", "octet_length(details)"), + ] { + let sql = format!( + "SELECT count(*),coalesce(sum({bytes}),0) FROM {table} WHERE ?1 IS NULL OR draft=?1" + ); + logical.insert( + label.into(), + db.query_row(&sql, [&input.draft_id], |r| { + Ok(json!({"count":r.get::<_,i64>(0)?,"payload_bytes":r.get::<_,i64>(1)?})) + })?, + ); + } + let totals = self.cleanup_totals(&db, input.draft_id.as_deref())?; + let free = fs2::available_space(&self.home)?; + Ok( + json!({"draft_id":input.draft_id,"home_file_bytes":total,"database_file_bytes":database,"export_directory_bytes":export_bytes, + "available_disk_bytes":free,"policy":self.policy,"warning":self.policy.warn_bytes.is_some_and(|n|total>=n) + || self.policy.max_home_bytes.is_some_and(|n|total>=n) || self.policy.min_free_bytes.is_some_and(|n|free<=n), + "logical_payload":logical,"eligible_temp_bytes":totals.scoped_temporary,"delivered_bytes":totals.scoped_delivered,"writer_busy":totals.busy, + "home_classes":{"abandoned_temp_bytes":totals.temporary,"delivered_report_only_bytes":totals.delivered,"protected_or_unclassified_bytes":total.saturating_sub(totals.temporary).saturating_sub(totals.delivered),"unclassified_export_bytes":export_bytes.saturating_sub(totals.temporary).saturating_sub(totals.delivered)}, + "scope":"Home totals count regular file lengths. Logical payload and registered file classes use the selected draft. Other files, database history and delivered outputs are protected from apply_cleanup."}), + ) + } +} + +pub struct BudgetWriter<'a> { + file: &'a mut File, + limit: u64, + reserve: Option, + volume: &'a Path, +} + +impl Write for BudgetWriter<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.limit != u64::MAX || self.reserve.is_some() { + let end = self + .file + .stream_position()? + .saturating_add(buf.len() as u64); + let growth = end.saturating_sub(self.file.metadata()?.len()); + if end > self.limit + || (self.reserve.is_some() + && growth + > fs2::available_space(self.volume)? + .saturating_sub(self.reserve.unwrap_or_default())) + { + return Err(io::Error::other(format!( + "Storage limit: export requests end offset {end}, budget {}; inspect storage_usage and plan_cleanup", + self.limit + ))); + } + } + self.file.write(buf) + } + fn flush(&mut self) -> io::Result<()> { + self.file.flush() + } +} + +impl Seek for BudgetWriter<'_> { + fn seek(&mut self, pos: SeekFrom) -> io::Result { + self.file.seek(pos) + } +} diff --git a/crates/panache-mcp/src/storage/cleanup.rs b/crates/panache-mcp/src/storage/cleanup.rs new file mode 100644 index 00000000..2a89e6b4 --- /dev/null +++ b/crates/panache-mcp/src/storage/cleanup.rs @@ -0,0 +1,281 @@ +use super::*; +use rusqlite::{OptionalExtension, Row}; +use std::{ + collections::{HashMap, HashSet}, + time::{Duration, Instant, SystemTime}, +}; + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CleanupScope { + /// Exact current draft. Other drafts are never included. + pub draft_id: String, + /// Continue the inventory after this returned ID. + pub after_id: Option, +} +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ApplyCleanup { + /// Short-lived plan from this MCP session. + pub plan_id: String, + /// Only abandoned_temp candidates in that plan may be selected. + pub candidate_ids: Vec, +} + +struct Entry { + id: String, + draft: String, + revision: u32, + format: String, + temp: String, + identity: String, + published: bool, +} + +impl Entry { + fn read(r: &Row<'_>) -> rusqlite::Result { + Ok(Self { + id: r.get(0)?, + draft: r.get(1)?, + revision: r.get(2)?, + format: r.get(3)?, + temp: r.get(4)?, + identity: r.get(5)?, + published: r.get(6)?, + }) + } + fn inspect(&mut self, store: &Storage) -> Result> { + ensure!( + Uuid::parse_str(&self.id).is_ok() && matches!(self.format.as_str(), "pdf" | "zip"), + "Invalid export registration" + ); + let final_name = format!("panache-{}.{}", self.id, self.format); + // Publication renames before SQLite is marked complete. After a crash the final + // file stays protected, including when somebody later replaces that path. + if !self.published && metadata(&store.exports.join(&final_name))?.is_some() { + self.published = true; + } + let filename = if self.published { + final_name + } else { + ensure!( + self.temp.starts_with(".panache-") + && self.temp.ends_with(".part") + && self + .temp + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')), + "Invalid staging registration" + ); + self.temp.clone() + }; + let path = store.exports.join(filename); + let Some(m) = metadata(&path)? else { + return Ok(None); + }; + if !m.is_file() || redirected(&m) || identity(&path)? != self.identity { + return Ok(None); + } + Ok(Some(( + path, + Stamp { + bytes: m.len(), + modified: m.modified()?, + identity: self.identity.clone(), + }, + ))) + } +} +const COLUMNS: &str = + "SELECT id,draft,revision,format,temp_name,identity,published FROM export_files"; +#[derive(Clone, PartialEq)] +struct Stamp { + bytes: u64, + modified: SystemTime, + identity: String, +} +struct Plan { + created: Instant, + draft: String, + items: HashMap, +} +#[derive(Default)] +pub(super) struct Plans { + entries: HashMap, +} + +#[derive(Default)] +pub(super) struct Totals { + pub temporary: u64, + pub delivered: u64, + pub scoped_temporary: u64, + pub scoped_delivered: u64, + pub busy: bool, +} +impl Storage { + pub(super) fn cleanup_totals(&self, db: &Connection, draft: Option<&str>) -> Result { + let guard = self.lock_file()?; + let busy = match guard.try_lock() { + Ok(()) => false, + Err(fs::TryLockError::WouldBlock) => true, + Err(e) => return Err(e.into()), + }; + let mut stmt = db.prepare(COLUMNS)?; + let mut totals = Totals { + busy, + ..Default::default() + }; + for row in stmt.query_map([], Entry::read)? { + let mut entry = row?; + if !entry.published && busy { + continue; + } + if let Some((_, stamp)) = entry.inspect(self)? { + let scoped = draft.is_none_or(|d| d == entry.draft); + if entry.published { + totals.delivered += stamp.bytes; + if scoped { + totals.scoped_delivered += stamp.bytes + } + } else { + totals.temporary += stamp.bytes; + if scoped { + totals.scoped_temporary += stamp.bytes + } + } + } + } + Ok(totals) + } + pub fn plan_cleanup(&self, drafts: &Drafts, input: CleanupScope) -> Result { + drafts.snapshot(&input.draft_id, None)?; + let _guard = self.write_lock()?; + let db = drafts.connect()?; + let mut stmt = db.prepare(&format!( + "{COLUMNS} WHERE draft=?1 AND id>?2 ORDER BY id LIMIT 51" + ))?; + let mut rows = stmt.query_map( + params![input.draft_id, input.after_id.unwrap_or_default()], + Entry::read, + )?; + let mut listed = Vec::new(); + let mut items = HashMap::new(); + let mut last_id = String::new(); + for row in rows.by_ref().take(50) { + let mut entry = row?; + last_id.clone_from(&entry.id); + let found = entry.inspect(self)?; + let bytes = found.as_ref().map(|(_, s)| s.bytes); + let name = found + .as_ref() + .and_then(|(p, _)| p.file_name()) + .and_then(|s| s.to_str()); + let class = match &found { + None => "missing_or_identity_changed", + Some(_) if entry.published => "delivered_report_only", + Some(_) => "abandoned_temp", + }; + listed.push(json!({"id":entry.id,"revision":entry.revision,"format":entry.format,"filename":name,"bytes":bytes,"class":class})); + if let Some((_, stamp)) = found + && !entry.published + { + items.insert(entry.id, stamp); + } + } + let next = rows.next().transpose()?.map(|_| last_id); + let eligible: u64 = items.values().map(|s| s.bytes).sum(); + let plan_id = if items.is_empty() { + None + } else { + let mut plans = self + .plans + .lock() + .map_err(|_| anyhow::anyhow!("Plans unavailable"))?; + plans + .entries + .retain(|_, p| p.created.elapsed() < Duration::from_secs(300)); + if plans.entries.len() >= 32 + && let Some(old) = plans + .entries + .iter() + .min_by_key(|(_, p)| p.created) + .map(|(k, _)| k.clone()) + { + plans.entries.remove(&old); + } + let id = Uuid::new_v4().to_string(); + plans.entries.insert( + id.clone(), + Plan { + draft: input.draft_id.clone(), + created: Instant::now(), + items, + }, + ); + Some(id) + }; + Ok( + json!({"draft_id":input.draft_id,"plan_id":plan_id,"entries":listed,"eligible_temp_bytes":eligible, + "next_after_id":next,"scope":"Only registered abandoned temporary files can be removed. Delivered files are report-only; unknown files are excluded. A plan expires after 300 seconds or server restart."}), + ) + } + + pub fn apply_cleanup(&self, drafts: &Drafts, input: ApplyCleanup) -> Result { + ensure!( + (1..=50).contains(&input.candidate_ids.len()), + "Choose 1..50 candidate IDs from one plan" + ); + let _guard = self.write_lock()?; + let plans = self + .plans + .lock() + .map_err(|_| anyhow::anyhow!("Plans unavailable"))?; + let plan = plans + .entries + .get(&input.plan_id) + .context("Unknown plan; preview again")?; + ensure!( + plan.created.elapsed() < Duration::from_secs(300), + "Plan expired; preview again" + ); + let ids = input.candidate_ids.iter().collect::>(); + ensure!( + ids.iter().all(|id| plan.items.contains_key(*id)), + "Selection contains an ineligible ID" + ); + let db = drafts.connect()?; + let mut removed = Vec::new(); + let mut skipped = Vec::new(); + let mut bytes = 0; + for id in ids { + let entry = db + .query_row( + &format!("{COLUMNS} WHERE id=? AND draft=? AND published=0"), + params![id, plan.draft], + Entry::read, + ) + .optional()?; + let candidate = if let Some(mut entry) = entry { + let found = entry.inspect(self)?; + if entry.published { None } else { found } + } else { + None + }; + if let Some((path, stamp)) = candidate + && plan.items[id] == stamp + { + match fs::remove_file(&path) { + Ok(()) => { + bytes += stamp.bytes; + removed.push(id); + db.execute("DELETE FROM export_files WHERE id=? AND published=0", [id])?; + } + Err(e) => skipped.push(json!({"id":id,"reason":e.kind().to_string()})), + } + } else { + skipped.push(json!({"id":id,"reason":"missing_or_changed"})); + } + } + Ok(json!({"removed_ids":removed,"removed_file_bytes":bytes,"skipped":skipped})) + } +} diff --git a/crates/panache-mcp/src/storage/tests.rs b/crates/panache-mcp/src/storage/tests.rs new file mode 100644 index 00000000..74b17c3d --- /dev/null +++ b/crates/panache-mcp/src/storage/tests.rs @@ -0,0 +1,178 @@ +use super::*; +use std::process::Command; + +// Exit inside the registered writer to exercise actual process death and kernel lock release. +#[test] +fn interrupted_writer() -> Result<()> { + let Some(home) = env::var_os("PANACHE_TEST_CRASH_HOME") else { + return Ok(()); + }; + let home = PathBuf::from(home); + let drafts = Drafts::open(&home)?; + let store = Storage::open(&home, &drafts)?; + store.export(&drafts, "draft", 1, Format::Zip, |writer| { + writer.write_all(b"unfinished")?; + writer.flush()?; + std::process::exit(23) + })?; + unreachable!() +} + +#[test] +fn plan_reclaims_only_selected_abandoned_writes() -> 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("INSERT INTO drafts VALUES('draft','test','{}',1,0,1)", [])?; + let historical = drafts.snapshot("draft", Some(1))?; + let record = historical.record_review( + 1, + 1, + "a", + "p", + "c", + &json!({"visibility":"inspect_visually"}), + )?; + let review_id = record["review_id"].as_str().unwrap(); + drafts.annotate(&crate::ReviewFeedback { + draft_id: "draft".into(), + review_id: review_id.into(), + origin: crate::FeedbackOrigin::UserQuote, + text: "保留这个墨色".into(), + })?; + 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| { + writer.write_all(b"delivered")?; + Ok(1) + })?; + // Simulate a crash after the final rename but before recording publication. + db.execute("UPDATE export_files SET published=0 WHERE published=1", [])?; + let crash = || -> Result<()> { + let status = Command::new(env::current_exe()?) + .args(["--exact", "storage::tests::interrupted_writer"]) + .env("PANACHE_TEST_CRASH_HOME", dir.path()) + .status()?; + ensure!(status.code() == Some(23), "Expected interrupted writer"); + Ok(()) + }; + crash()?; + let plan = || { + store.plan_cleanup( + &drafts, + CleanupScope { + draft_id: "draft".into(), + after_id: None, + }, + ) + }; + let first = plan()?; + let eligible = |plan: &Value| -> (String, String) { + let item = plan["entries"] + .as_array() + .unwrap() + .iter() + .find(|v| v["class"] == "abandoned_temp") + .unwrap(); + ( + item["id"].as_str().unwrap().to_string(), + item["filename"].as_str().unwrap().to_string(), + ) + }; + let (id, name) = eligible(&first); + let apply = |plan: &Value, id: &str| { + store.apply_cleanup( + &drafts, + ApplyCleanup { + plan_id: plan["plan_id"].as_str().unwrap().into(), + candidate_ids: vec![id.into()], + }, + ) + }; + let delivered_id = first["entries"] + .as_array() + .unwrap() + .iter() + .find(|v| v["class"] == "delivered_report_only") + .unwrap()["id"] + .as_str() + .unwrap(); + assert!(apply(&first, delivered_id).is_err()); + let original = store.exports.join(name); + fs::rename(&original, store.exports.join("moved-by-user"))?; + fs::write(&original, b"user-owned replacement")?; + assert_eq!(apply(&first, &id)?["removed_file_bytes"], 0); + assert_eq!(fs::read(&original)?, b"user-owned replacement"); + crash()?; + let next = plan()?; + let (id, _) = eligible(&next); + let reopened = Storage::open(dir.path(), &drafts)?; + assert!( + reopened + .apply_cleanup( + &drafts, + ApplyCleanup { + plan_id: next["plan_id"].as_str().unwrap().into(), + candidate_ids: vec![id.clone()] + } + ) + .is_err() + ); + let live = store.write_lock()?; + assert!(store.import(1).is_err()); + assert!(plan().is_err()); + assert!(apply(&next, &id).is_err()); + assert_eq!( + store.usage(&drafts, Usage { draft_id: None })?["eligible_temp_bytes"], + 0 + ); + drop(live); + assert_eq!(apply(&next, &id)?["removed_file_bytes"], 10); + assert_eq!(apply(&next, &id)?["removed_file_bytes"], 0); + assert_eq!( + Drafts::open(dir.path())? + .snapshot("draft", Some(1))? + .observation(review_id)?["feedback"][0]["text"], + "保留这个墨色" + ); + assert_eq!(fs::read(&old)?, b"legacy"); + assert_eq!(fs::read(delivered)?, b"delivered"); + assert_eq!( + store.usage(&drafts, Usage { draft_id: None })?["home_classes"]["unclassified_export_bytes"], + 38 + ); + Ok(()) +} + +#[test] +fn budgets_block_heavy_writes_without_publishing_partial_outputs() -> Result<()> { + let dir = tempfile::tempdir()?; + fs::create_dir(dir.path().join("exports"))?; + let drafts = Drafts::open(dir.path())?; + 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| { + w.write_all(&[0; 17])?; + Ok(1) + }); + assert!(result.is_err()); + assert_eq!(fs::read_dir(&store.exports)?.count(), 0); + 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| { + w.write_all(&[0; 200])?; + w.seek(SeekFrom::Start(100))?; + w.write_all(&[0; 100])?; + w.write_all(&vec![0; 300_000])?; + Ok(1) + }); + assert!(result.is_err()); + assert_eq!(fs::read_dir(&store.exports)?.count(), 0); + let usage = store.usage(&drafts, Usage { draft_id: None })?; + assert_eq!(usage["delivered_bytes"], 0); + Ok(()) +} diff --git a/crates/panache-mcp/src/tuning.rs b/crates/panache-mcp/src/tuning.rs index ad63a7b0..e08fa6fe 100644 --- a/crates/panache-mcp/src/tuning.rs +++ b/crates/panache-mcp/src/tuning.rs @@ -98,6 +98,10 @@ pub fn apply(state: &State, input: Tune) -> Result { let paper = input.paper_guides.as_ref().and(draft.paper.as_ref()); let details = json!({"changes":input.changes,"font":font.as_ref().map(|(name,_)|name),"paper_guides":input.paper_guides,"note":input.note}); let preserve_layout = preserve_layout && paper.is_none(); + let _budget = font + .as_ref() + .map(|(_, bytes)| state.storage.import(bytes.len())) + .transpose()?; let next = state.drafts.tune( &draft, &changes, diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 72d8b1f3..e7e16ef5 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -148,6 +148,9 @@ async def smoke(command, arguments, out): tools = await client.list_tools() assert {t.name for t in tools.tools} == { "annotate_review", + "storage_usage", + "plan_cleanup", + "apply_cleanup", "list_fonts", "describe_controls", "tune_handwriting", diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index 8511dac8..d5daa808 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -2,7 +2,7 @@ ## 工具发现 -Panache 在 `tools/list` 中公布十个任务入口。模型可以直接保存、预览、导出;只有需要调参时才调用 `describe_controls`。目录按排版、字体、墨迹、扰动、删除线和拍摄信息六组组织,和服务端参数校验共用同一份定义。 +Panache 在 `tools/list` 中公布十三个任务入口。模型可以直接保存、预览、导出;只有需要调参时才调用 `describe_controls`。目录按排版、字体、墨迹、扰动、删除线和拍摄信息六组组织,和服务端参数校验共用同一份定义。 MCP 的工具列表支持分页。客户端可能取完所有页;分页能控制单次协议响应大小。Claude 的 Tool Search 支持宿主配置延迟加载,实际进入模型上下文的工具由宿主决定。Panache 的 stdio 客户端也可以完全不提供搜索,只用标准工具列表和调用接口。项目目前选择按需查询参数,避免为小型目录引入搜索索引和额外的调用步骤。设计依据见 [MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)、[MCP 路线图中的渐进发现](https://blog.modelcontextprotocol.io/posts/mcp-roadmap/) 和 [Claude Tool Search 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)。 From 4f82f965e49625584d26d592871099e23537b8d1 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 17:51:24 +0800 Subject: [PATCH 09/24] =?UTF-8?q?test(crates/panache-mcp):=20=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E5=AE=B9=E9=87=8F=E4=B8=8D=E8=B6=B3=E6=97=B6=E7=9A=84?= =?UTF-8?q?=E8=B7=A8=E4=BC=9A=E8=AF=9D=E5=B7=A5=E4=BD=9C=E6=B5=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:逐表测试难以保证 MCP 客户端在容量不足时仍能读取旧稿与复盘。 解决手段:通过 stdio 连续比较十次并核对产物字节差额,再以受限预算重启,分别尝试导入字体、底纸和导出。 收益:验证失败操作不会增加稿件内容或导出文件,旧版仍能渲染且用户原话可按证据 ID 读取。 --- crates/panache-mcp/tests/review_comparison.py | 16 +++++++++++++++- crates/panache-mcp/tests/smoke.py | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index d03c3c8b..b7ac7765 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -4,6 +4,7 @@ import struct import zlib from contextlib import closing +from pathlib import Path def slanted_sheet(path): @@ -118,8 +119,21 @@ def assets(): ) inventory = assets() result = await compare(3, 4) - assert await compare(3, 4) == result + usage = (await call(client, "storage_usage", **key)).structuredContent + for _ in range(10): + assert await compare(3, 4) == result + repeated = (await call(client, "storage_usage", **key)).structuredContent + assert repeated["logical_payload"] == usage["logical_payload"] + assert repeated["export_directory_bytes"] == usage["export_directory_bytes"] assert assets() == inventory + exported = (await call(client, "export_handwriting", **key, format="zip")).structuredContent + size = Path(exported["path"]).stat().st_size + after = (await call(client, "storage_usage", **key)).structuredContent + assert after["export_directory_bytes"] == repeated["export_directory_bytes"] + size + assert after["delivered_bytes"] == size and after["eligible_temp_bytes"] == 0 + planned = (await call(client, "plan_cleanup", **key)).structuredContent + assert planned["plan_id"] is None + assert [entry["class"] for entry in planned["entries"]] == ["delivered_report_only"] assert [a["revision"] for a in result["actions"]] == [4] assert result["actions"][0]["details"]["paper_guides"] == guides assert result["before"]["feedback"] == [{"origin": "user_quote", "text": quote}] diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index e7e16ef5..87bdb0ec 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -557,6 +557,24 @@ async def progress(value, total, message=None): ) == adjusted ) + 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() + usage = (await call(client, "storage_usage", **comparison_key)).structuredContent + assert usage["warning"] and usage["policy"]["max_home_bytes"] == 1 + for name, args in [ + ("save_section", {"markdown": "不可导入", "paper_path": str(Path(__file__).parent.resolve() / "fixtures/ruled.png")}), + ("tune_handwriting", {**comparison_key, "expected_revision": 6, "font_path": str(Path(__file__).resolve().parents[3] / "assets/font_assets/李国夫手写体.ttf")}), + ("export_handwriting", {**comparison_key, "format": "zip"}), + ]: + failure = await client.call_tool(name, args) + assert failure.isError and "Storage limit" in failure.content[0].text + after = (await call(client, "storage_usage", **comparison_key)).structuredContent + assert after["logical_payload"] == usage["logical_payload"] + assert after["export_directory_bytes"] == usage["export_directory_bytes"] + stored = (await call(client, "read_section", **comparison_key, view="review", review_id=reviewed_id)).structuredContent + assert stored["feedback"][0]["text"] == user_quote + assert png(await call(client, "preview_handwriting", draft_id=paper_id, revision=3)) == adjusted print( f"Poem: 1 page. Extended draft: {archive['pages']} pages. Cache, selected page, old revision, restart and conflicts verified." ) From 916b038aef89e13d874bb7575117703de4ae333d Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 18:12:34 +0800 Subject: [PATCH 10/24] =?UTF-8?q?fix(crates/panache-mcp):=20=E6=81=A2?= =?UTF-8?q?=E5=A4=8D=E7=8B=AC=E7=AB=8B=E6=B5=8B=E9=87=8F=20MCP=20=E4=B8=8A?= =?UTF-8?q?=E4=B8=8B=E6=96=87=E7=9A=84=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:按文档运行 context_metrics.py 时,间接导入图像测试导致缺少未声明的 Pillow。 解决手段:将 stdio 调用断言移到只依赖 MCP 客户端的测试模块,保留图像依赖在对应测试。 收益:干净的 SDK 环境可以直接获取新客户端首轮工具与返回数据大小。 --- crates/panache-mcp/tests/context_metrics.py | 2 +- crates/panache-mcp/tests/mcp_client.py | 7 +++++++ crates/panache-mcp/tests/smoke.py | 7 +------ 3 files changed, 9 insertions(+), 7 deletions(-) create mode 100644 crates/panache-mcp/tests/mcp_client.py diff --git a/crates/panache-mcp/tests/context_metrics.py b/crates/panache-mcp/tests/context_metrics.py index 1fda670a..69dcf66a 100644 --- a/crates/panache-mcp/tests/context_metrics.py +++ b/crates/panache-mcp/tests/context_metrics.py @@ -14,7 +14,7 @@ from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client -from smoke import call +from mcp_client import call def size(result): diff --git a/crates/panache-mcp/tests/mcp_client.py b/crates/panache-mcp/tests/mcp_client.py new file mode 100644 index 00000000..806378a5 --- /dev/null +++ b/crates/panache-mcp/tests/mcp_client.py @@ -0,0 +1,7 @@ +"""Shared assertions for MCP stdio integration tests.""" + + +async def call(client, name, **args): + result = await client.call_tool(name, args) + assert not result.isError, (name, result.content[0]) + return result diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 87bdb0ec..04357497 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -18,6 +18,7 @@ from PIL import Image import review_comparison +from mcp_client import call from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client @@ -30,12 +31,6 @@ 最爱湖东行不足,绿杨阴里白沙堤。""" -async def call(client, name, **args): - result = await client.call_tool(name, args) - assert not result.isError, (name, result.content[0]) - return result - - def png(result): return base64.b64decode( next(item.data for item in result.content if item.type == "image"), From 237b09f5133d0ed73c7025222626796a03a37598 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 18:24:28 +0800 Subject: [PATCH 11/24] =?UTF-8?q?fix(crates/panache-mcp):=20=E5=B9=B6?= =?UTF-8?q?=E5=8F=91=E9=A6=96=E6=AC=A1=E6=89=93=E5=BC=80=E6=97=B6=E5=8F=AF?= =?UTF-8?q?=E9=9D=A0=E5=88=9D=E5=A7=8B=E5=8C=96=E7=A8=BF=E4=BB=B6=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:两个陌生客户端在同一新目录同时连接时,40 次真实初始化中有 9 次因 SQLite 锁冲突退出。 解决手段:在切换 WAL 时有限重试可恢复的锁错误,同一连接在短事务中建表,并加入八路并发打开回归。 收益:修复后双进程和八进程共 180 次真实握手通过,大文件写锁期间仍能初始化并列出稿件。 --- crates/panache-mcp/src/drafts.rs | 63 +++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 1ce64138..34a6ce8f 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -1,8 +1,9 @@ mod observations; use anyhow::{Context, Result, ensure}; -use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; +use rusqlite::{Connection, ErrorCode, OptionalExtension, TransactionBehavior, params}; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; use uuid::Uuid; use crate::Style; @@ -10,6 +11,37 @@ use crate::paper::{ImportedPaper, PaperLayout}; pub struct Drafts(PathBuf); +#[cfg(test)] +#[test] +fn concurrent_first_opens_share_a_complete_schema() -> Result<()> { + let home = tempfile::tempdir()?; + let ready = std::sync::Barrier::new(8); + std::thread::scope(|s| -> Result<()> { + let workers: Vec<_> = (0..8) + .map(|_| { + s.spawn(|| -> Result<()> { + ready.wait(); + let drafts = Drafts::open(home.path())?; + let db = drafts.connect()?; + assert!( + db.table_exists(None, "drafts")? + && db.table_exists(None, "review_observations")? + ); + assert_eq!( + db.pragma_query_value(None, "journal_mode", |r| r.get::<_, String>(0))?, + "wal" + ); + Ok(()) + }) + }) + .collect(); + for worker in workers { + worker.join().unwrap()?; + } + Ok(()) + }) +} + pub struct Snapshot<'a> { pub revision: u32, pub style: Style, @@ -108,9 +140,29 @@ pub struct Section { impl Drafts { pub fn open(dir: &Path) -> Result { let drafts = Self(dir.join("drafts.sqlite3")); - drafts.connect()?.execute_batch( + let mut db = drafts.connect()?; + // Concurrent first opens can both hold read locks when SQLite upgrades to WAL. + // SQLite may return BUSY immediately for this upgrade despite its busy timeout. + let deadline = Instant::now() + Duration::from_secs(5); + loop { + match db.pragma_update(None, "journal_mode", "WAL") { + Err(err) + if matches!( + err.sqlite_error_code(), + Some(ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked) + ) && Instant::now() < deadline => + { + std::thread::sleep(Duration::from_millis(20)) + } + result => { + result.context("Enable WAL for the draft database")?; + break; + } + } + } + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + tx.execute_batch( " - PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS drafts ( id TEXT PRIMARY KEY, title TEXT NOT NULL, style TEXT NOT NULL, revision INTEGER NOT NULL, chars INTEGER NOT NULL, sections INTEGER NOT NULL @@ -151,12 +203,13 @@ impl Drafts { ); ", )?; - observations::initialize(&mut drafts.connect()?)?; + tx.commit()?; + observations::initialize(&mut db)?; Ok(drafts) } pub(crate) fn connect(&self) -> Result { let db = Connection::open(&self.0)?; - db.busy_timeout(std::time::Duration::from_secs(5))?; + db.busy_timeout(Duration::from_secs(5))?; Ok(db) } pub fn save( From 1efa2cefadc0d79a94f9448449f4a591c9a2eb38 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 18:24:47 +0800 Subject: [PATCH 12/24] =?UTF-8?q?feat(crates/panache-mcp):=20=E6=8C=89?= =?UTF-8?q?=E5=8E=9F=E5=9B=BE=E5=A4=9A=E8=BE=B9=E5=BD=A2=E5=A4=8D=E6=9F=A5?= =?UTF-8?q?=E4=B8=A4=E7=89=88=E5=A2=A8=E8=BF=B9=E4=B8=8E=E4=BF=9D=E6=8A=A4?= =?UTF-8?q?=E5=8C=BA=E5=9F=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:整页观察难以辨认单字级别的缺失和误改。GEditBench v2 将编辑目标及保真分别评价(https://arxiv.org/abs/2603.28547)。 解决手段:在已有复盘入口增加同坐标裁剪、前后选区和区域内外变化计数,拒绝跨底纸或重分页比较。通过真实 stdio 覆盖局部不可见与整页验收的边界。 收益:可单独检查目标与保护区,重看原位、目标位及其周围,避免用邻字贡献的像素断言目标字依然可见。 --- crates/panache-mcp/src/inputs.rs | 8 +- crates/panache-mcp/src/main.rs | 25 +- crates/panache-mcp/src/review.rs | 73 ++-- crates/panache-mcp/src/review/local.rs | 349 ++++++++++++++++++ crates/panache-mcp/tests/review_comparison.py | 16 + crates/panache-mcp/tests/smoke.py | 8 + 6 files changed, 440 insertions(+), 39 deletions(-) create mode 100644 crates/panache-mcp/src/review/local.rs diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index a1b6c1b9..3c28b442 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -214,13 +214,15 @@ pub struct Nudge { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Preview { - /// With view=review, compare stored evidence on this section/page with an earlier draft revision. Returns data only. Offset/limit paginate intervening edit actions. + /// In review, compare with an earlier revision. Omit region for stored, data-only evidence (offset/limit paginate edits). With region, render paired crops. pub compare_revision: Option, - /// Layout only. Select glyph centers in this polygon (3..32 original image pixel pairs). Returned IDs can be adjusted together. + /// 3..32 vertices in native output image pixels, origin top left. Layout selects glyph centers. Review measures the polygon and shows its bounding crop. pub region: Option>, + /// With review, region and compare_revision, mark the original position of moved content. The crop covers both polygons; differences outside their union cover the rest of the page. + pub previous_region: Option>, /// In layout view, only return illustration outlines and isolated details. pub illustrations_only: Option, - /// "image" (default), "paper" for the saved stationery alone, or "layout" for base glyph geometry. + /// "image" (default), "paper" for saved stationery, "layout" for glyph geometry, or "review" for appearance evidence. pub view: Option, /// Layout mode: start index and number of glyphs (default 12, max 32). pub offset: Option, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 95617307..b0704ab6 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -391,19 +391,28 @@ impl Panache { #[tool( annotations(open_world_hint = false), - description = "With view=review and compare_revision, read a data-only same-page comparison with exact review IDs, intervening edits, feedback and limitations. Omit compare_revision to measure one page. view=review returns paper, finished image, reference overlay and visible ink evidence. Compare top/middle/bottom alignment and ink appearance. Use layout with region (photo pixel polygon) to select glyph IDs; view=layout returns base glyph boxes [x,y,width,height] in pixels, paginated with offset/limit, for adjust_glyphs. view=paper gives the saved background alone. Set illustrations_only=true in layout for editable diagram outlines and details. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline in image pixels." + 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." )] async fn preview_handwriting( &self, Parameters(input): Parameters, ctx: RequestContext, ) -> CallToolResult { - if let Some(before) = input.compare_revision { + if input.previous_region.is_some() + && !(input.view == Some(PreviewView::Review) + && input.region.is_some() + && input.compare_revision.is_some()) + { + return tool_result(Err(anyhow::anyhow!( + "previous_region requires view=review, region and compare_revision" + ))); + } + if let Some(before) = input.compare_revision + && input.region.is_none() + { return tool_result((|| { ensure!( - input.view == Some(PreviewView::Review) - && input.region.is_none() - && input.illustrations_only.is_none(), + input.view == Some(PreviewView::Review) && input.illustrations_only.is_none(), "compare_revision requires an unfiltered review view" ); let draft = self.0.drafts.snapshot(&input.draft_id, input.revision)?; @@ -421,7 +430,8 @@ impl Panache { .render(ctx, move |state, engine, cancel| { let draft = state.drafts.snapshot(&input.draft_id, input.revision)?; ensure!(input.illustrations_only.is_none() || input.view==Some(PreviewView::Layout),"illustrations_only requires view=layout"); - ensure!(input.region.is_none() || input.view==Some(PreviewView::Layout),"region requires layout view"); + ensure!(input.region.is_none() || matches!(input.view, Some(PreviewView::Layout | PreviewView::Review)),"region requires view=layout or review"); + ensure!(input.compare_revision.is_none() || input.view==Some(PreviewView::Review),"compare_revision requires view=review"); if input.view==Some(PreviewView::Paper){ ensure!(input.offset.is_none() && input.limit.is_none() && input.section.is_none() && input.page.is_none(),"view=paper takes only draft_id and revision"); let bytes=draft.background()?.context("No imported paper for this draft")?; @@ -439,6 +449,9 @@ impl Panache { let page = input.page.unwrap_or(1); if input.view == Some(PreviewView::Review) { ensure!(input.limit.is_none() && input.offset.is_none(),"Review a single page without pagination"); + if let Some(region) = &input.region { + return review::local::page(&state.drafts, engine, &draft, section, &input, region, cancel); + } let baselines=engine.review_baselines(&draft,section.clone(),page,cancel)?; let (png,_)=engine.preview(&draft,section,page,cancel)?; return review::page(&draft,number,page,&png,&baselines,cancel); diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs index 28a50043..01a1b9cd 100644 --- a/crates/panache-mcp/src/review.rs +++ b/crates/panache-mcp/src/review.rs @@ -1,8 +1,10 @@ +pub mod local; + use crate::{controls, drafts::Snapshot, reply}; use anyhow::{Result, ensure}; use base64::{Engine as _, engine::general_purpose::STANDARD}; -use handwriting_core::{Cancellation, Limits, export, imaging}; -use image::{Pixel, Rgba, RgbaImage, imageops}; +use handwriting_core::{Cancellation, Limits, Parameters, export, imaging}; +use image::{GenericImageView, Pixel, Rgba, RgbaImage, imageops}; use rmcp::model::{CallToolResult, ContentBlock}; use serde_json::json; @@ -28,7 +30,7 @@ pub fn contains(poly: &[[i32; 2]], [x, y]: [f32; 2]) -> bool { == 1 } -fn thumbnail(img: &RgbaImage) -> RgbaImage { +fn thumbnail(img: &impl GenericImageView>) -> RgbaImage { let scale = (900. / img.width().max(img.height()) as f32).min(1.); imageops::thumbnail( img, @@ -80,6 +82,41 @@ pub struct PageSample { pub content_sha256: String, } +fn decode_page(png: &str) -> Result { + let bytes = STANDARD.decode(png)?; + let limits = Limits { + max_file_bytes: bytes.len(), + ..Default::default() + }; + Ok(imaging::decode(&bytes, &limits)?.into_rgba8()) +} + +fn reference_paper( + draft: &Snapshot<'_>, + size: (u32, u32), + params: &Parameters, +) -> Result { + let limits = Limits::default(); + let paper = match draft.background()? { + Some(b) => imaging::decode(&b, &limits)?.into_rgba8(), + None => handwriting_core::render::preset_paper(size.0, size.1, params, &limits)?, + }; + ensure!( + paper.dimensions() == size, + "Paper and output dimensions differ" + ); + Ok(paper) +} + +fn rgb_delta(a: Rgba, b: Rgba) -> u16 { + let white = + |p: Rgba, c: usize| 255 - ((255 - u16::from(p[c])) * u16::from(p[3])).div_ceil(255); + (0..3) + .map(|c| white(a, c).abs_diff(white(b, c))) + .max() + .unwrap() +} + pub fn page( draft: &Snapshot<'_>, section: u32, @@ -89,13 +126,7 @@ pub fn page( cancel: &Cancellation, ) -> Result { let params = controls::parameters(draft, section, &draft.controls)?; - let bytes = STANDARD.decode(png)?; - let limits = Limits { - max_file_bytes: bytes.len(), - ..Default::default() - }; - let mut finished = imaging::decode(&bytes, &limits)?.into_rgba8(); - drop(bytes); + let mut finished = decode_page(png)?; use sha2::{Digest, Sha256}; let mut hash = Sha256::new(); hash.update(finished.width().to_le_bytes()); @@ -103,19 +134,7 @@ pub fn page( hash.update(finished.as_raw()); let pixel_digest = format!("{:x}", hash.finalize()); let baselines = &sample.baselines; - let paper = match draft.background()? { - Some(b) => imaging::decode(&b, &Limits::default())?.into_rgba8(), - None => handwriting_core::render::preset_paper( - finished.width(), - finished.height(), - ¶ms, - &limits, - )?, - }; - ensure!( - paper.dimensions() == finished.dimensions(), - "Paper and output dimensions differ" - ); + let paper = reference_paper(draft, finished.dimensions(), ¶ms)?; let (w, h) = paper.dimensions(); // The reference is anchored to the imported stationery, independent of later margin adjustments. let (left, right, top, bottom, step) = draft.paper.as_ref().map_or( @@ -178,13 +197,7 @@ pub fn page( composite.blend(pixel); *pixel = composite; } - let white = |p: Rgba, c: usize| { - 255 - ((255 - u16::from(p[c])) * u16::from(p[3])).div_ceil(255) - }; - let delta = (0..3) - .map(|c| white(*pixel, c).abs_diff(white(base, c))) - .max() - .unwrap(); + let delta = rgb_delta(*pixel, base); peak = peak.max(delta); if delta >= 8 { changed[(y as usize * 3 / h as usize).min(2)] += 1; diff --git a/crates/panache-mcp/src/review/local.rs b/crates/panache-mcp/src/review/local.rs new file mode 100644 index 00000000..9fae0a2f --- /dev/null +++ b/crates/panache-mcp/src/review/local.rs @@ -0,0 +1,349 @@ +use super::{decode_page, reference_paper, rgb_delta, thumbnail}; +use crate::{ + Preview, controls, + drafts::{Drafts, Section, Snapshot}, + engine::Engine, + reply, +}; +use anyhow::{Context, Result, ensure}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use handwriting_core::{Cancellation, Parameters, export}; +use image::{GenericImageView, Pixel, RgbaImage}; +use rmcp::model::{CallToolResult, ContentBlock}; +use serde::Serialize; +use serde_json::json; + +type Point = [i32; 2]; +const THRESHOLD: u16 = 8; + +fn edges(poly: &[Point]) -> impl Iterator + '_ { + poly.iter() + .copied() + .zip(poly.iter().copied().cycle().skip(1)) +} + +fn turn(a: Point, b: Point, p: Point) -> i64 { + i64::from(b[0] - a[0]) * i64::from(p[1] - a[1]) + - i64::from(b[1] - a[1]) * i64::from(p[0] - a[0]) +} + +fn between(a: Point, p: Point, b: Point) -> bool { + (0..2).all(|i| (a[i].min(b[i])..=a[i].max(b[i])).contains(&p[i])) +} + +fn intersects(a: Point, b: Point, c: Point, d: Point) -> bool { + let (ac, ad, ca, cb) = (turn(a, b, c), turn(a, b, d), turn(c, d, a), turn(c, d, b)); + (ac.signum() * ad.signum() < 0 && ca.signum() * cb.signum() < 0) + || (ac == 0 && between(a, c, b)) + || (ad == 0 && between(a, d, b)) + || (ca == 0 && between(c, a, d)) + || (cb == 0 && between(c, b, d)) +} + +fn validate_polygon(poly: &[Point], (w, h): (u32, u32)) -> Result<()> { + ensure!((3..=32).contains(&poly.len()), "Use 3..32 polygon vertices"); + ensure!( + poly.iter() + .all(|&[x, y]| (0..=w as i32).contains(&x) && (0..=h as i32).contains(&y)), + "Polygon vertices must be inside native output pixel edges [0,{w}] x [0,{h}]" + ); + for (i, (a, b)) in edges(poly).enumerate() { + let c = poly[(i + 2) % poly.len()]; + ensure!( + a != b && (turn(a, b, c) != 0 || between(a, b, c)), + "Polygon has a duplicate or reversing edge" + ); + for (j, (c, d)) in edges(poly).enumerate().skip(i + 2) { + if i != 0 || j + 1 != poly.len() { + ensure!( + !intersects(a, b, c, d), + "Polygon must be simple with no intersecting edges" + ); + } + } + } + Ok(()) +} + +// Fill horizontal spans at pixel centers. Concave polygons can produce several spans. +fn row_mask(poly: &[Point], y: u32, mask: &mut [bool]) { + mask.fill(false); + let cy = f64::from(y) + 0.5; + let mut cuts = [0usize; 32]; + let mut count = 0; + for ([ax, ay], [bx, by]) in edges(poly) { + if (f64::from(ay) > cy) != (f64::from(by) > cy) { + let x = f64::from(ax) + (cy - f64::from(ay)) * f64::from(bx - ax) / f64::from(by - ay); + cuts[count] = (x - 0.5).ceil() as usize; + count += 1; + } + } + cuts[..count].sort_unstable(); + for pair in cuts[..count].chunks_exact(2) { + mask[pair[0]..pair[1]].fill(true); + } +} + +#[derive(Default, Serialize)] +struct Ink { + sampled_pixels: u64, + ink_pixels: u64, + max_rgb_delta: u16, +} + +impl Ink { + fn sample(&mut self, delta: u16) { + self.sampled_pixels += 1; + self.ink_pixels += u64::from(delta >= THRESHOLD); + self.max_rgb_delta = self.max_rgb_delta.max(delta); + } +} + +#[derive(Default, Serialize)] +struct Measurements { + region: Ink, + previous_region: Option, +} + +impl Measurements { + fn sample(&mut self, region: bool, previous: bool, delta: u16) { + if region { + self.region.sample(delta); + } + if previous { + self.previous_region.get_or_insert_default().sample(delta); + } + } +} + +#[derive(Default, Serialize)] +struct Difference { + inside_union_changed_pixels: u64, + outside_union_changed_pixels: u64, + region_changed_pixels: u64, + previous_region_changed_pixels: Option, +} + +struct Appearance { + finished: RgbaImage, + params: Parameters, + content_sha256: String, +} + +impl Appearance { + fn render( + engine: &mut Engine, + draft: &Snapshot<'_>, + section: Section, + page: usize, + cancel: &Cancellation, + ) -> Result { + let params = controls::parameters(draft, section.number, &draft.controls)?; + let sample = engine.review_baselines(draft, section.clone(), page, cancel)?; + let (png, _) = engine.preview(draft, section, page, cancel)?; + Ok(Self { + finished: decode_page(&png)?, + params, + content_sha256: sample.content_sha256, + }) + } + + fn composite(&mut self, paper: &RgbaImage, cancel: &Cancellation) -> Result<()> { + if self.params.transparent_background { + for (pixels, bases) in self.finished.rows_mut().zip(paper.rows()) { + cancel.check()?; + for (pixel, &base) in pixels.zip(bases) { + let mut visible = base; + visible.blend(pixel); + *pixel = visible; + } + } + } + Ok(()) + } +} + +pub fn page( + drafts: &Drafts, + engine: &mut Engine, + draft: &Snapshot<'_>, + section: Section, + input: &Preview, + region: &[Point], + cancel: &Cancellation, +) -> Result { + let page = input.page.unwrap_or(1); + let number = section.number; + let previous = input.previous_region.as_deref().unwrap_or_default(); + ensure!( + input + .compare_revision + .is_none_or(|rev| rev > 0 && rev < draft.revision), + "compare_revision must identify an earlier revision" + ); + let mut after = Appearance::render(engine, draft, section, page, cancel)?; + let size = after.finished.dimensions(); + validate_polygon(region, size)?; + if let Some(old) = &input.previous_region { + validate_polygon(old, size)?; + } + let paper = reference_paper(draft, size, &after.params)?; + after.composite(&paper, cancel)?; + let before = if let Some(revision) = input.compare_revision { + let old = drafts.snapshot(draft.id, Some(revision))?; + let section = drafts + .sections(old.id, revision, Some(number))? + .pop() + .context("Section absent in compare_revision")?; + let mut before = Appearance::render(engine, &old, section, page, cancel)?; + ensure!( + before.finished.dimensions() == size, + "Cannot compare local pixels: different_image_dimensions" + ); + ensure!( + before.content_sha256 == after.content_sha256, + "Cannot compare local pixels: page_content_changed_or_repaginated" + ); + // Imported paper bytes are immutable per draft; generated stationery depends on controls. + if old.paper.is_none() { + ensure!( + reference_paper(&old, size, &before.params)? == paper, + "Cannot compare local pixels: different_reference_paper" + ); + } + before.composite(&paper, cancel)?; + Some(before) + } else { + None + }; + let [mut left, mut top] = region[0]; + let [mut right, mut bottom] = region[0]; + for &[x, y] in region.iter().chain(previous) { + left = left.min(x); + top = top.min(y); + right = right.max(x); + bottom = bottom.max(y); + } + let bounds = [ + left as u32, + top as u32, + (right - left) as u32, + (bottom - top) as u32, + ]; + let mut after_metrics = Measurements::default(); + let mut before_metrics = Measurements::default(); + let mut diff = Difference { + previous_region_changed_pixels: input.previous_region.as_ref().map(|_| 0), + ..Default::default() + }; + let mut mask = vec![false; size.0 as usize]; + let mut old_mask = mask.clone(); + let rows = if before.is_some() { + 0..size.1 + } else { + bounds[1]..bounds[1] + bounds[3] + }; + let cols = if before.is_some() { + 0..size.0 + } else { + bounds[0]..bounds[0] + bounds[2] + }; + for y in rows { + cancel.check()?; + row_mask(region, y, &mut mask); + row_mask(previous, y, &mut old_mask); + for x in cols.clone() { + let inside = mask[x as usize]; + let old = old_mask[x as usize]; + let pixel = after.finished[(x, y)]; + let base = paper[(x, y)]; + if inside || old { + after_metrics.sample(inside, old, rgb_delta(pixel, base)); + } + if let Some(before) = &before { + let prior = before.finished[(x, y)]; + if inside || old { + before_metrics.sample(inside, old, rgb_delta(prior, base)); + } + if rgb_delta(pixel, prior) >= THRESHOLD { + diff.region_changed_pixels += u64::from(inside); + if let Some(count) = &mut diff.previous_region_changed_pixels { + *count += u64::from(old); + } + if inside || old { + diff.inside_union_changed_pixels += 1; + } else { + diff.outside_union_changed_pixels += 1; + } + } + } + } + } + ensure!( + after_metrics.region.sampled_pixels > 0 + && (previous.is_empty() || after_metrics.previous_region.is_some()), + "Each polygon must enclose at least one pixel center" + ); + let crop = |img: &RgbaImage| { + let [x, y, w, h] = bounds; + thumbnail(&*img.view(x, y, w, h)) + }; + let paper_crop = crop(&paper); + let metadata = json!({ + "draft_id":draft.id,"section":number,"page":page,"revision":draft.revision,"compare_revision":input.compare_revision, + "photo_size":size,"region":region,"previous_region":input.previous_region,"crop_bounds":bounds, + "crop_image_size":paper_crop.dimensions(),"channel_delta_threshold":THRESHOLD, + "coordinate_space":"Native output pixel edges; origin top left, x right, y down. crop_bounds is [x,y,width,height]. Measurements use pixel centers inside each polygon.", + "after":after_metrics,"before":before.as_ref().map(|_|before_metrics),"difference":before.as_ref().map(|_|diff), + "guidance":"Ink counts pixels whose largest visible RGB channel difference from the paper is at least 8. Revision differences apply the same threshold to before and after appearances; outside_union_changed_pixels covers the entire page outside both polygons. This local inspection leaves full-page review status unchanged. Inspect the crops against the request, including whether disappearance was intended. Overlapping text and diagrams contribute to the same pixels. Check protected areas with another region. Stop once the target and protected areas meet the request; ask if intent or attribution is unclear." + }); + let mut response = reply(metadata.to_string(), metadata); + let mut append = |label: &str, img: RgbaImage| -> Result<()> { + response.content.push(ContentBlock::text(label)); + response.content.push(ContentBlock::image( + STANDARD.encode(export::png(&img)?), + "image/png", + )); + Ok(()) + }; + append("Saved paper crop", paper_crop)?; + if let Some(before) = before { + append("Before crop", crop(&before.finished))?; + } + append("After crop", crop(&after.finished))?; + Ok(response) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_invalid_photo_polygons() { + for poly in [ + vec![[1, 0], [2, 0], [3, 0]], + vec![[0, 0], [8, 8], [8, 0], [0, 8]], + vec![[0, 0], [9, 1], [1, 4]], + vec![[0, 0], [8, 0], [8, 8], [0, 0]], + vec![[0, 0], [8, 0], [7, 0], [0, 8]], + ] { + assert!(validate_polygon(&poly, (8, 8)).is_err(), "{poly:?}"); + } + } + + #[test] + fn mask_matches_even_odd_centers_for_concave_polygon_including_photo_edges() { + let poly = [[0, 0], [8, 0], [8, 6], [6, 4], [4, 1], [2, 4], [0, 6]]; + validate_polygon(&poly, (8, 6)).unwrap(); + let mut mask = [true; 8]; + for y in 0..6 { + row_mask(&poly, y, &mut mask); + for (x, &inside) in mask.iter().enumerate() { + assert_eq!( + inside, + super::super::contains(&poly, [x as f32 + 0.5, y as f32 + 0.5]) + ); + } + } + } +} diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index b7ac7765..3e2d1f7e 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -163,4 +163,20 @@ def assets(): reflow["delta"] is None and "page_content_changed_or_repaginated" in reflow["limitations"] ) + + async def incompatible(draft_id, before, after, reason): + result = await client.call_tool("preview_handwriting", { + "draft_id": draft_id, "view": "review", "revision": after, + "compare_revision": before, "region": [[0, 0], [30, 0], [30, 30]], + }) + assert result.isError and reason in result.content[0].text, result.content[0] + assert all(part.type != "image" for part in result.content) + + await incompatible(key["draft_id"], 4, 6, "page_content_changed_or_repaginated") + preset = (await call(client, "save_section", markdown="字", style={"seed": 13})).structuredContent + preset_id = preset["draft_id"] + await call(client, "tune_handwriting", draft_id=preset_id, expected_revision=1, changes={"paper": "grid"}) + await incompatible(preset_id, 1, 2, "different_reference_paper") + await call(client, "tune_handwriting", draft_id=preset_id, expected_revision=2, changes={"width": 800}) + await incompatible(preset_id, 2, 3, "different_image_dimensions") return key, old["review_id"], quote diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 04357497..514498a2 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -124,6 +124,14 @@ async def ink_box(): assert right - left > 2 * (original[2] - original[0]) await call(client, "adjust_glyphs", **edit, expected_revision=3, opacity=0) assert await ink_box() is None + local = await call(client, "preview_handwriting", **key, revision=4, view="review", + compare_revision=3, region=[[130,160],[265,160],[265,265],[130,265]]) + assert len([item for item in local.content if item.type == "image"]) == 3 + measured = local.structuredContent + assert measured["crop_bounds"] == [130, 160, 135, 105] + assert measured["before"]["region"]["ink_pixels"] > 0 + assert measured["after"]["region"]["ink_pixels"] == 0 + 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 "局部墨迹" in exported.content[0].text From 17d0b2924c85c2be0115f82047879eca91711fec Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 18:25:35 +0800 Subject: [PATCH 13/24] =?UTF-8?q?feat(app):=20=E5=BC=95=E5=AF=BC=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E9=AA=8C=E8=AF=81=20MCP=20=E8=BF=9E=E6=8E=A5=E5=B9=B6?= =?UTF-8?q?=E5=90=91=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=8A=AB=E9=9C=B2=E8=83=BD?= =?UTF-8?q?=E5=8A=9B=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:首次接入者需要找到注册入口并确认连接是否成功。纯文字客户端还要解释照片如何传入、如何验收和透明输出保存在哪里。 解决手段:在设置页的复制提示中给出下一步和列字体的验证方式,更新两种语言的接入示例。在握手、复盘和导出契约内披露本机路径、视觉能力和格式约束。 收益:实际桌面包在中文及空格路径、空 PATH 下列出了九款字体并导出 PDF。陌生客户端可以用默认纸先完成任务,随后请用户确认需要看图的判断。 --- README.md | 2 +- README.zh-CN.md | 2 +- app/lib/l10n/app_en.arb | 2 +- app/lib/l10n/app_zh.arb | 2 +- crates/panache-mcp/README.md | 14 ++++++++++++-- crates/panache-mcp/src/inputs.rs | 1 + crates/panache-mcp/src/main.rs | 11 +++++++++-- crates/panache-mcp/tool-design.md | 21 ++++++++++++++++++++- 8 files changed, 46 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 49d10d6b..edf1ab27 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ The Windows, macOS, and Linux desktop packages include a local MCP server. Open > Write my notes and the process diagram on this photo of my stationery. Show me the first page, then export the whole draft as a PDF. -The client can list fonts, save Markdown in sections, revisit earlier revisions, preview individual pages, and adjust a diagram or table against the paper’s rulings. [MCP tools and configuration](crates/panache-mcp/README.md) +For the photo, give the client a file path accessible on the computer running Panache. A client that passes images to its model can inspect the finished page and review a selected area. In a text-only client, ask for the measurements and open the exported PDF locally to judge the appearance. [MCP tools and configuration](crates/panache-mcp/README.md) | Process state diagram | Resource allocation table | | --- | --- | diff --git a/README.zh-CN.md b/README.zh-CN.md index 39f475dc..a8274710 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -28,7 +28,7 @@ Windows、macOS 和 Linux 桌面版随附本地 MCP 服务。在 **应用设置 > 用这张斜拍的信纸排我的笔记,画出进程状态转换图。先给我看第一页,确认后把整份导出成 PDF。 -可以让 AI 列出字体、按节保存 Markdown、回查旧稿,也可以只预览指定页,按纸上横线微调流程图和表格。[MCP 工具与配置说明](crates/panache-mcp/README.md) +请提供运行 Panache 的电脑能读取的照片路径。能向模型传递图片的客户端可以检查成品、放大复盘选区。在纯文字客户端中,可让 AI 说明测量结果,再打开导出的本地 PDF 看实际效果。[MCP 工具与配置说明](crates/panache-mcp/README.md) | 进程状态转换图 | 资源分配表 | | --- | --- | diff --git a/app/lib/l10n/app_en.arb b/app/lib/l10n/app_en.arb index b10ac0c4..9e9257eb 100644 --- a/app/lib/l10n/app_en.arb +++ b/app/lib/l10n/app_en.arb @@ -264,7 +264,7 @@ "motionSaveFailed": "Motion preference applied but could not be saved.", "connectAiClient": "Connect AI client", "copyMcpConfig": "Copy MCP configuration (JSON)", - "mcpConfigCopied": "MCP configuration copied", + "mcpConfigCopied": "Configuration copied. Add Panache in your AI client’s MCP settings, then ask it to list Panache’s fonts.", "mcpCopyFailed": "Could not copy the configuration. Please try again.", "copyImage": "Copy image", "imageCopied": "Image copied to clipboard", diff --git a/app/lib/l10n/app_zh.arb b/app/lib/l10n/app_zh.arb index 903b9e87..6e227a3c 100644 --- a/app/lib/l10n/app_zh.arb +++ b/app/lib/l10n/app_zh.arb @@ -264,7 +264,7 @@ "motionSaveFailed": "动效设置已应用,但未能保存。", "connectAiClient": "连接 AI 客户端", "copyMcpConfig": "复制 MCP 配置(JSON)", - "mcpConfigCopied": "MCP 配置已复制", + "mcpConfigCopied": "配置已复制。请在 AI 客户端的 MCP 设置里添加 Panache,然后问它「Panache 有哪些字体?」", "mcpCopyFailed": "配置复制失败,请重试。", "copyImage": "复制图片", "imageCopied": "图片已复制到剪贴板", diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 3d354c25..83d65cfb 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -4,7 +4,11 @@ ## 在桌面版连接 AI 客户端 -完整解压或安装桌面版,打开「应用设置 → 连接 AI 客户端」即可复制本机的 JSON 配置。把它加入客户端的 MCP 配置,已有其他服务时合并 `mcpServers.panache`。客户端通过标准输入输出启动 Panache,关闭工作台后也能使用。移动安装目录后可重新复制。 +1. 完整解压或安装桌面版,在「应用设置 → 连接 AI 客户端」复制本机配置。 +2. 在支持**本地 stdio 服务**的 AI 客户端中注册名为 `panache` 的服务。使用 `mcpServers` 格式的 JSON 配置可直接合并其中的 `panache` 条目,保留已有服务。若客户端使用表单、TOML 或其他格式,按其格式填入复制结果中的 `command` 和可选的 `args`。程序路径填作一项,每个参数各占一项。 +3. 在客户端重新加载 MCP 配置或重新连接,问它「请调用 Panache 列出可用字体」。收到本机的字体文件名就表示连接成功。若客户端只接受服务器网址,请选择能在本机启动 stdio 程序的客户端。 + +客户端通过标准输入输出启动 Panache,关闭工作台后也能使用。移动安装目录后可重新复制。 桌面包包含 MCP、字体和 Markdown 转换器,JavaScript 运行时已编入 MCP 程序。Windows 新安装使用根目录启动器,可自动跟随应用更新;从旧启动器升级的安装会使用当前版本的 MCP 路径,更新后请重新复制。 @@ -40,9 +44,11 @@ cargo build --locked --release -p panache-mcp ## 写稿、预览和复查 +第一次可以直接说:「把‘西湖春早,柳色正新。’排成一页手写稿,用默认纸张,先让我看一眼。」客户端会用 `save_section` 建稿,再把返回的 `draft_id` 和 `revision` 交给 `preview_handwriting`。满意后可以说「把刚才那一版导出成 PDF」。导出工具返回本机文件路径。 + 使用自己的纸张时,在第一次调用 `save_section` 时传入 `paper_path`,例如 `{"markdown":"第一题","paper_path":"C:/作业/南昌大学横线纸.jpg"}`。路径指向运行 MCP 的电脑上的图片。默认保留原照片,按识别到的横线投影字迹和插图。`paper` 返回排版尺寸、边距、行距、识线结果,投影时另有原照尺寸。可用 `preview_handwriting(view="paper")` 单独看底纸,或在导入时通过 `paper_guides` 指定参考线。需要校平底纸时传 `paper_mode="flatten"`。无可靠横线时保留底图,使用普通行距。纸张随稿件保存一次,后续追加、回查、预览和导出可在原图移动后继续使用。 -可以对 agent 说:「用志莽行书给《钱塘湖春行》排一页,先让我看预览。确认后用同一版导出 PDF。」 +如果照片是聊天附件,请先确认客户端能提供 MCP 进程可读的本机文件路径,必要时先把图片存到这台电脑。带视觉能力的模型可以查看客户端转交的预览图。客户端或模型只能处理文字时,可读取版面和像素测量,并请用户打开导出文件确认外观,再按反馈修改。 | 工具 | 用法 | | --- | --- | @@ -94,6 +100,8 @@ cargo build --locked --release -p panache-mcp 4. 局部改动用 `preview_handwriting(view="layout", region=[[x,y],…])` 圈选字形中心,结果按页分批。把选中的 ID 和相同版本交给 `adjust_glyphs`。`place_center` 将一组字移到指定照片位置;`target_quad` 按左上、右上、右下、左下四角放置所选字块,替换该组已有几何调整。局部字形还可分别调倾斜、浓度和笔画。调整后复查新版本。 5. 用 `read_section(view="trajectory")` 回看该稿的近期操作、简短调整理由和按页记录的复盘指标。可锁定版本,用 `offset/limit` 向前翻。把需要人判断的歧义带回当前会话;确定符合用途后导出同一版本。 +要核对局部改动,用 `preview_handwriting(view="review", region=…, revision=新版本, compare_revision=旧版本)` 查看同一区域的底纸、改前和改后图。移动字块时还可用 `previous_region` 圈出旧位置。需要保护的文字或页眉可单独圈选复查。区域使用原尺寸成品像素。[局部坐标与测量示例](tool-design.md#局部改动的复查) + `tune_handwriting(font_path=…)` 会把本机 TTF/OTF 随稿保存。可用返回的字体标识在同一稿内切回该字体。墨迹组的 `transparent_background` 控制原尺寸 PNG 预览和 ZIP,PDF 保留纸张。透明稿复盘会把墨迹放回底纸,方便判断实际可读性。 ### 比较两版,找回当时的依据 @@ -110,6 +118,8 @@ cargo build --locked --release -p panache-mcp 精确复查用 `read_section(view="review",draft_id=…,review_id=…)`,跨会话可用。要看图时再按版本取 `view="image"`。像素摘要用于核对重渲染结果,系统不为每次复盘归档整页图片。 +使用 Windows 上的 Python 客户端脚本时,若只有终端显示的中文乱码,可以将该客户端的标准输出和终端设为 UTF-8(例如向 Python 进程传入 `PYTHONIOENCODING=utf-8`)。 + ## 验证 构建后可用官方 Python MCP 客户端跑一次 stdio 端到端测试。`--out` 可选,用于保留诗稿的预览和 PDF。 diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 3c28b442..81fbc0c9 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -239,6 +239,7 @@ pub struct Preview { pub struct Export { pub draft_id: String, pub revision: Option, + /// PDF includes the paper. ZIP contains page PNGs and respects the transparent_background ink control. pub format: Option, } diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index b0704ab6..00ab026e 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -202,7 +202,14 @@ impl ServerHandler for Panache { use rmcp::model::{Implementation, ServerCapabilities, ServerConfig}; ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) .with_server_info(Implementation::new("panache-mcp", handwriting_core::app_version())) - .with_instructions("Drafts contain versioned Markdown sections. Images, the saved paper and per-glyph geometry are available on demand. Photo-space coordinates describe the preview; local adjustments use paper-space pixels. For photo placement use preview_handwriting(view=review), compare the three labeled images, ask the user about ambiguous regions, and review the edited revision. Read view=trajectory to revisit actions and evidence.") + .with_instructions(concat!( + "Start with save_section(markdown). Use its draft_id and revision for preview_handwriting or export_handwriting. ", + "Use list_fonts for names and list_drafts to resume. A paper_path must be readable on the server computer. ", + "For photo placement use preview_handwriting(view=review). Inspect the returned images when available. ", + "If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", + "Ask for clarification on ambiguous regions. 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." + )) } } @@ -555,7 +562,7 @@ impl Panache { } #[tool( - description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns path and page count. For visual acceptance, inspect view=review on the intended revision first, 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 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." )] async fn export_handwriting( &self, diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index d5daa808..834c1003 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -4,6 +4,8 @@ Panache 在 `tools/list` 中公布十三个任务入口。模型可以直接保存、预览、导出;只有需要调参时才调用 `describe_controls`。目录按排版、字体、墨迹、扰动、删除线和拍摄信息六组组织,和服务端参数校验共用同一份定义。 +客户端负责启动 stdio 程序、把工具提供给模型,并决定将返回的文本、结构化数据和图片交给谁。首次可调用 `list_fonts` 验证连接,再用 `save_section` 创建一节短文,按返回版本预览。请区分用户能在聊天里看到图片与模型能读取工具图片这两种能力。模型实际收到图片时可以描述字迹和位置;只收到文字时,可以报告测量值,并请用户在预览或导出文件中确认字形、可读性和布局偏好。 + MCP 的工具列表支持分页。客户端可能取完所有页;分页能控制单次协议响应大小。Claude 的 Tool Search 支持宿主配置延迟加载,实际进入模型上下文的工具由宿主决定。Panache 的 stdio 客户端也可以完全不提供搜索,只用标准工具列表和调用接口。项目目前选择按需查询参数,避免为小型目录引入搜索索引和额外的调用步骤。设计依据见 [MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)、[MCP 路线图中的渐进发现](https://blog.modelcontextprotocol.io/posts/mcp-roadmap/) 和 [Claude Tool Search 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)。 ## 一次调整 @@ -55,7 +57,7 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 轨迹按稿件和版本保存在本机。修改操作与简短备注在同一事务提交,复盘按稿件版本、节页、测量算法版本及成品像素摘要去重。像素摘要为 SHA-256,输入依次是两个小端 u32 宽高和导出预览的原始 RGBA8 字节,在透明墨迹叠回纸张前计算。算法或成品变化产生新 ID,旧库迁移保留原证据并将未知来源字段置空。导出按不同节页计数,并取每页最近归档的测量。改变测量口径时应提升算法版本。查询不会返回原文、字体数据、图片字节或完整对话。这里的轨迹指已执行的动作和可复查的结果。模型可以对照前后版本调整下一步;没有修改模型权重或自动跨用户积累经验。 -比较默认仅返回数据,取同一节页两版最近归档的复盘及各自最近 50 条署名反馈。精确 ID 可用来回查对比时所用的观察,更早的反馈也可在轨迹中分页查找。页面成员摘要绑定不可变节版本和该页所有字形的源位置;重新保存该节可能保守地中止定量比较。分区至少在两侧各有 3 个暗线支持样本才返回中位偏差的差值,这是最低报告门槛。它不能证明两组样本完全相同或有统计显著性。越界像素相对各版本自己的书写区计算。 +省略 `region` 的版本比较仅返回数据,取同一节页两版最近归档的复盘及各自最近 50 条署名反馈。精确 ID 可用来回查对比时所用的观察,更早的反馈也可在轨迹中分页查找。页面成员摘要绑定不可变节版本和该页所有字形的源位置;重新保存该节可能保守地中止定量比较。分区至少在两侧各有 3 个暗线支持样本才返回中位偏差的差值,这是最低报告门槛。它不能证明两组样本完全相同或有统计显著性。越界像素相对各版本自己的书写区计算。 反馈是调用方标注来源的本稿记录。`user_quote` 应逐字引用人的意见,`model_observation` 用于模型自己的观察。历史编辑备注的作者无法追溯时仍归为编辑上下文。若一轮同时改了墨迹与参考线,对比列出操作和观测结果,具体因果与偏好留给复核者判断。 @@ -63,6 +65,23 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 SICA 将历次尝试及其评估结果放入档案,供下一轮决策参考。本工具采用了可按版本取回结果的做法,作用域限于当前稿件,修改对象是稿件与排版参数。[SICA 作者实现](https://github.com/MaximeRobeyns/self_improving_coding_agent) +## 局部改动的复查 + +例如把一行字向右移后,可以在 `preview_handwriting` 中圈出新旧位置。以下坐标仅作示例,实际请从该页预览和 `view="layout"` 取得。 + +```json +{ + "draft_id": "…", "view": "review", "section": 1, "page": 1, + "revision": 4, "compare_revision": 3, + "region": [[160,210],[260,210],[260,250],[160,250]], + "previous_region": [[40,210],[140,210],[140,250],[40,250]] +} +``` + +坐标使用原尺寸成品的像素边界,左上为原点,向右、向下为正。用 3 至 32 个顶点围成无自交的多边形,无需重复首点。返回的 `crop_bounds=[x,y,width,height]` 覆盖所有指定区域,`crop_image_size` 给出实际返回的裁图尺寸,最长边为 900 像素。按相同范围依次查看底纸、改前和改后图;只检查当前版时省略 `compare_revision` 和 `previous_region`,返回底纸和当前成品两张图。 + +看 `before`、`after` 中各区域的 `ink_pixels`,可核对新位置是否出现墨迹、旧位置是否仍有笔画。底纸与成品任一可见 RGB 通道相差至少 8 级就计入墨迹。两版间也用这个阈值比较,`difference.outside_union_changed_pixels` 涵盖整页中两个区域并集之外的变动。重叠的图文都会计入,可把需要保护的标题或框线单独圈出再比较。若纸张像素、输出尺寸或页面内容已改变,分别检查各版本。局部复查即时渲染;要保存整页复盘或引用 `review_id` 时,另取一次不带区域的 `view="review"`。 + ## 如何复测 从仓库根目录运行下列命令。两个脚本都使用独立临时稿库。比较版本时,把相同的测量脚本指向两个构建,使用相同字体与测试图片。 From 1a8ce771d4b8e9a5ad73781facf9835fe4deb28e Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 18:25:51 +0800 Subject: [PATCH 14/24] =?UTF-8?q?test(crates/panache-mcp):=20=E6=8F=90?= =?UTF-8?q?=E4=BE=9B=E5=8F=AF=E5=A4=8D=E8=B7=91=E7=9A=84=E6=95=B4=E9=A1=B5?= =?UTF-8?q?=E5=92=8C=E5=B1=80=E9=83=A8=E5=A4=8D=E7=9B=98=E7=9B=B2=E8=AF=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:需要知道裁剪对漏字、误改和受保护内容的识别是否有帮助,还要控制比较顺序的影响。参考 EditJudgeBias(https://arxiv.org/abs/2610.01670)。 解决手段:用官方客户端生成八个有预设意图的案例和两组偏好题,交叉分派整页及局部图片、交换候选顺序,以原图像素另查严格保真并记录传输开销。 收益:可重建相同的盲评刺激、区分人工或模型判断与像素变化,并定位首次精修时观察到的保护区变化。 --- crates/panache-mcp/README.md | 6 + .../tests/local_review_experiment.py | 527 ++++++++++++++++++ 2 files changed, 533 insertions(+) create mode 100644 crates/panache-mcp/tests/local_review_experiment.py diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 83d65cfb..b1d62a6c 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -127,3 +127,9 @@ cargo build --locked --release -p panache-mcp ```sh uv run --script crates/panache-mcp/tests/smoke.py target/release/panache-mcp --out output/pdf ``` + +局部复查盲评使用合成页面。构建后运行以下命令,在新的输出目录中生成两组顺序配平的图片与任务,以及单独保存的答案和逐例统计。给评审者各发一组,待其回答后再打开 `private/key.json`。脚本另外核对源图像素。调用数和字节数只统计取复盘结果的开销,选区已提供。 + +```sh +uv run --script crates/panache-mcp/tests/local_review_experiment.py target/release/panache-mcp --out output/local-review-pilot +``` diff --git a/crates/panache-mcp/tests/local_review_experiment.py b/crates/panache-mcp/tests/local_review_experiment.py new file mode 100644 index 00000000..30ad448c --- /dev/null +++ b/crates/panache-mcp/tests/local_review_experiment.py @@ -0,0 +1,527 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = ["mcp>=1.12,<2", "Pillow"] +# /// +"""Generate counterbalanced visual review packets and verify their source pixels over stdio.""" + +import argparse +import asyncio +import base64 +import io +import json +import os +import random +from functools import partial +from pathlib import Path +from tempfile import TemporaryDirectory + +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client +from PIL import Image, ImageChops, ImageDraw + +from mcp_client import call as call_tool + +TEXT = """雨落山川春意深。 + +松间清泉入晚云。 + +白鹭低飞穿绿野。 + +几点疏星照远村。 + +轻舟已过柳荫岸。 + +昨日题诗寄故人。 + +青石桥边闻短笛。 + +小窗闲坐读新书。""" + +# Each task states the user's intent independently of the synthetic edit. +CASES = [ + ( + "keep", + "山", + "Keep 山 in the first line clearly legible and leave the nearby writing alone.", + "revise", + ), + ( + "remove", + "川", + "Remove 川 from the first line, leaving the other writing alone.", + "accept", + ), + ( + "move", + "春", + "Move 春 from the first line into the blank area directly below its original column.", + "accept", + ), + ( + "collateral", + "意", + "Move 意 from the first line into the blank area directly below its original column and preserve 松 on the second line.", + "revise", + ), + ( + "overlap", + "深", + "Two glyphs were deliberately stacked in the same box. Can the remaining ink prove that 深 is still independently visible?", + "uncertain", + ), + ( + "keep", + "泉", + "Make 泉 in the second line slightly lighter but keep it clearly legible.", + "accept", + ), + ( + "remove", + "间", + "Remove 间 from the second line, leaving the other writing alone.", + "revise", + ), + ( + "collateral", + "云", + "Lighten 云 in the second line, keeping it legible and preserving 山 in the first line.", + "accept", + ), +] + + +def pixels(response): + return [ + Image.open(io.BytesIO(base64.b64decode(item.data))).convert("RGB") + for item in response.content + if item.type == "image" + ] + + +def rectangle(glyph): + x, y, w, h = glyph["bounds"] + return (x, y, x + w, y + h) + + +def polygon(box): + left, top, right, bottom = box + return [[left, top], [right, top], [right, bottom], [left, bottom]] + + +def union(*boxes): + return ( + min(b[0] for b in boxes), + min(b[1] for b in boxes), + max(b[2] for b in boxes), + max(b[3] for b in boxes), + ) + + +def shifted(b, dy): + return (b[0], b[1] + dy, b[2], b[3] + dy) + + +def context_bounds(size, box): + left, top, right, bottom = box + return ( + max(0, left - 24), + max(0, top - 18), + min(size[0], right + 24), + min(size[1], bottom + 18), + ) + + +def crop_with_context(image, box): + return image.crop(context_bounds(image.size, box)) + + +def save_pair(path, left, right, names): + def scale(image): + ratio = min(480 / image.width, 660 / image.height, 3) + size = (round(image.width * ratio), round(image.height * ratio)) + return image.resize(size, Image.Resampling.LANCZOS) + + left, right = map(scale, (left, right)) + image = Image.new( + "RGB", + (left.width + right.width + 18, max(left.height, right.height) + 24), + "white", + ) + draw = ImageDraw.Draw(image) + for x, panel, label in [(0, left, names[0]), (left.width + 18, right, names[1])]: + draw.text((x + 2, 3), label, fill="black") + image.paste(panel, (x, 22)) + image.save(path) + + +async def fixture(call, case): + kind, char, _, _ = CASES[case] + saved = ( + await call( + "save_section", + markdown=TEXT, + style={ + "seed": 222 + case, + "font_size": 32, + "paper": "ruled", + }, + ) + ).structuredContent + key = {"draft_id": saved["draft_id"]} + rows = ( + await call("preview_handwriting", **key, view="layout", limit=32) + ).structuredContent["glyphs"] + glyphs = {g.get("text"): g for g in rows} + target = glyphs[char] + source = rectangle(target) + protected = glyphs["松" if case == 3 else "山"] + revision = 1 + + async def edit(glyph, **change): + nonlocal revision + revision = ( + await call( + "adjust_glyphs", + **key, + section=1, + page=1, + expected_revision=revision, + ids=[glyph["id"]], + **change, + ) + ).structuredContent["revision"] + + if kind == "overlap": + await edit(glyphs["春"], target_quad=polygon(source)) + before = revision + dest = source + if case in (0, 1, 4): + await edit(target, opacity=0) + elif case in (2, 3): + # A full line lands on written text. Use the blank rows below all eight lines. + dy = 535 + await edit(target, dy=dy) + dest = shifted(source, dy) + if case == 3: + await edit(protected, opacity=0) + elif case == 6: + await edit(glyphs["清"], opacity=0) + else: + await edit(target, opacity=72) + return key, before, revision, source, dest, rectangle(protected), target["id"] + + +def dump(path, value): + path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8") + + +def threshold_difference(first, second): + red, green, blue = ImageChops.difference(first, second).split() + peak = ImageChops.lighter(ImageChops.lighter(red, green), blue) + return peak.point(lambda p: 255 if p >= 8 else 0) + + +async def verify_region( + call, key, before, after, source, dest, protected, target_id, case, raw, full +): + async def compare(box, old=None): + extra = {"previous_region": polygon(old)} if old and old != box else {} + return await call( + "preview_handwriting", + **key, + view="review", + revision=after, + compare_revision=before, + region=polygon(box), + **extra, + ) + + def wire_bytes(result): + return len(result.model_dump_json(by_alias=True, exclude_none=True).encode()) + + def check_crops(response, bounds): + data = response.structuredContent + x, y, r, b = bounds + assert data["crop_bounds"] == [x, y, r - x, b - y] + paper, old, new = pixels(response) + for frame, image in zip([old, new], raw, strict=True): + assert ImageChops.difference(frame, image.crop(bounds)).getbbox() is None + return paper, old, new + + def changed(image): + return image.histogram()[255] + + expected = threshold_difference(*raw) + tight = await compare(dest, source) + bounds = union(source, dest) + paper, old, new = check_crops(tight, bounds) + measured = tight.structuredContent + for name, box in [("region", dest), ("previous_region", source)]: + if name == "previous_region" and source == dest: + continue + local_box = tuple(v - bounds[i % 2] for i, v in enumerate(box)) + for revision, img in [("before", old), ("after", new)]: + counts = measured[revision][name] + assert counts["sampled_pixels"] == (box[2] - box[0]) * (box[3] - box[1]) + assert counts["ink_pixels"] == changed( + threshold_difference(img, paper).crop(local_box) + ) + assert measured["difference"][name + "_changed_pixels"] == changed( + expected.crop(box) + ) + mask = Image.new("L", expected.size) + for box in [source, dest]: + mask.paste(255, box) + inside = changed(ImageChops.multiply(expected, mask)) + delta = measured["difference"] + assert delta["inside_union_changed_pixels"] == inside + assert delta["outside_union_changed_pixels"] == changed(expected) - inside + a, b = ( + measured["before"]["region"]["ink_pixels"], + measured["after"]["region"]["ink_pixels"], + ) + if case in (0, 1): + # A neighboring glyph can enter a selected rectangle after the target is hidden. + assert a > b + if case == 0: + assert b == 0 + assert full[1].structuredContent["evidence"]["visibility"] == "inspect_visually" + if case in (2, 3): + assert ( + b > a + and measured["before"]["previous_region"]["ink_pixels"] + > measured["after"]["previous_region"]["ink_pixels"] + ) + if case == 4: + assert ( + b > 0 + ) # The surviving, deliberately superimposed glyph still has strokes. + if case == 6: + assert b > 0 and delta["outside_union_changed_pixels"] > 0 + + # The packets show the exact native pixels returned by a request with neighboring context. + dst, src = [context_bounds(raw[0].size, box) for box in (dest, source)] + primary = await compare(dst, src) + check_crops(primary, union(src, dst)) + displayed = [primary] + protected_metrics = None + if case in (3, 7): + box = context_bounds(raw[0].size, protected) + companion = await compare(box) + check_crops(companion, box) + protected_tight = await compare(protected) + check_crops(protected_tight, protected) + tight_change = protected_tight.structuredContent["difference"][ + "region_changed_pixels" + ] + context_change = companion.structuredContent["difference"][ + "region_changed_pixels" + ] + assert tight_change == changed(expected.crop(protected)) + assert context_change == changed(expected.crop(box)) + protected_metrics = { + "tight_changed_pixels": tight_change, + "context_changed_pixels": context_change, + } + if case == 3: + assert tight_change > 0 + else: + # Isolate the opacity change after the first fine edit has activated glyph rendering. + # Both blind frames remain the original before/after images. + restored = await call( + "adjust_glyphs", + **key, + section=1, + page=1, + expected_revision=after, + ids=[target_id], + opacity=100, + ) + control = await call( + "preview_handwriting", + **key, + view="review", + revision=restored.structuredContent["revision"], + compare_revision=after, + region=polygon(dest), + ) + matched = control.structuredContent["difference"] + assert ( + matched["inside_union_changed_pixels"] > 0 + and matched["outside_union_changed_pixels"] == 0 + ) + assert not ( + dest[0] < protected[2] + and protected[0] < dest[2] + and dest[1] < protected[3] + and protected[1] < dest[3] + ) + protected_metrics["matched_restore_inside_target_changed_pixels"] = matched[ + "inside_union_changed_pixels" + ] + protected_metrics["matched_restore_outside_target_changed_pixels"] = ( + matched["outside_union_changed_pixels"] + ) + displayed.append(companion) + return { + "case": case + 1, + "page_calls": len(full), + "local_calls": len(displayed), + "page_bytes": sum(map(wire_bytes, full)), + "local_bytes": sum(map(wire_bytes, displayed)), + "tight_region_before_ink": a, + "tight_region_after_ink": b, + "difference": delta, + "protected": protected_metrics, + "page_visibility": full[1].structuredContent["evidence"]["visibility"], + } + + +async def generate(client, out, verify): + call = partial(call_tool, client) + + layouts = {} + rng = random.Random(1729) + local = list(range(8)) + rng.shuffle(local) + for group in "AB": + order = list(range(10)) + rng.shuffle(order) + folder = out / group + folder.mkdir(parents=True, exist_ok=True) + layouts[group] = (folder, order) + private = out / "private" + private.mkdir(exist_ok=True) + keys, results = {}, [] + prompts = {group: {} for group in layouts} + for case, (_, char, question, answer) in enumerate(CASES): + print(f"Rendering case {case + 1}/{len(CASES)}", flush=True) + key, before, after, source, dest, protected, target_id = await fixture( + call, case + ) + area = union(source, dest) + + async def preview(view, revision): + return await call( + "preview_handwriting", **key, revision=revision, view=view + ) + + whole, raw = [], [] + full_wire = [] + for revision in (before, after): + response = await preview("review", revision) + full_wire.append(response) + whole.append(pixels(response)[1]) + raw.append(pixels(await preview("image", revision))[0]) + if verify: + results.append( + await verify_region( + call, + key, + before, + after, + source, + dest, + protected, + target_id, + case, + raw, + full_wire, + ) + ) + dump(private / "metrics.json", results) + local_images = [crop_with_context(im, area) for im in raw] + # Give both readers the requested protected field. Its ROI costs another call. + for group, (folder, order) in layouts.items(): + task = f"T{order.index(case) + 1:02d}" + use_local = (case in local[:4]) == (group == "A") + panels = local_images if use_local else whole + save_pair(folder / f"{task}.png", *panels, ["Before", "After"]) + if use_local and case in (3, 7): + save_pair( + folder / f"{task}-protected.png", + *(crop_with_context(im, protected) for im in raw), + ["Protected before", "Protected after"], + ) + prompts[group][task] = question + keys[f"{group}/{task}"] = { + "case": case + 1, + "mode": "local" if use_local else "page", + "answer": answer, + } + if case in (2, 3): + # Restore the same row's text with a small local change in rhythm and tilt. + style_case = case + 6 + rows = (await preview("layout", before)).structuredContent["glyphs"] + glyph = next(g for g in rows if g.get("text") == char) + styled = await call( + "adjust_glyphs", + **key, + section=1, + page=1, + expected_revision=after, + ids=[glyph["id"]], + dx=5 if case == 2 else -4, + dy=-5 if case == 2 else 4, + angle=9 if case == 2 else -8, + ) + version = styled.structuredContent["revision"] + xs = (0, max(10, min(source[1], dest[1]) - 35), 450, source[3] + 25) + natural = [ + im.crop(xs) + for im in (raw[0], pixels(await preview("image", version))[0]) + ] + for group, (folder, order) in layouts.items(): + task = f"T{order.index(style_case) + 1:02d}" + swap = (group == "A") == (case == 3) + pair = natural[::-1] if swap else natural + save_pair(folder / f"{task}.png", *pair, ["A", "B"]) + prompts[group][task] = ( + "Appearance only. Which version of the handwriting has more natural spacing " + "and flow? Answer A, B, tie, or uncertain, with a visible reason." + ) + keys[f"{group}/{task}"] = { + "case": style_case + 1, + "candidate_before": "B" if swap else "A", + } + for group, (folder, _) in layouts.items(): + prompt = ( + "Read each image at its provided size. Each T-number is independent. " + "The panels show two rendered snapshots. Some views show the full page, " + "others show a local crop; a supplementary image shows a named protected field. " + "For an edit request, answer accept / revise / uncertain with one concrete visual " + "observation. Use uncertain if the requested conclusion cannot be justified from " + "the displayed pixels. For appearance questions use the specified A/B scale. " + "Return one line per T-number. Do not inspect source, neighboring folders, or image " + "metadata.\n\n" + ) + (folder / "TASKS.txt").write_text( + prompt + + "\n".join( + f"{task} {prompts[group][task]}" for task in sorted(prompts[group]) + ), + encoding="utf-8", + ) + dump(private / "key.json", keys) + + +async def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("binary", type=Path) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument( + "--packet-only", + action="store_true", + help="Generate visuals on a build without local review.", + ) + args = parser.parse_args() + with TemporaryDirectory() as directory: + env = {**os.environ, "PANACHE_MCP_HOME": directory} + params = StdioServerParameters(command=str(args.binary.resolve()), env=env) + async with stdio_client(params) as streams, ClientSession(*streams) as client: + await client.initialize() + await generate(client, args.out, not args.packet_only) + + +if __name__ == "__main__": + asyncio.run(main()) From b109b54adb636acafd176f61e17251b6a41537be Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 18:28:09 +0800 Subject: [PATCH 15/24] =?UTF-8?q?fix(crates/panache-mcp):=20=E8=B7=A8?= =?UTF-8?q?=E6=B8=B2=E6=9F=93=E6=A8=A1=E5=BC=8F=E5=A4=8D=E6=9F=A5=E6=97=B6?= =?UTF-8?q?=E6=8A=AB=E9=9C=B2=E4=BF=9D=E6=8A=A4=E5=8C=BA=E5=8F=98=E5=8C=96?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:盲评中两位模型均接受一项淡化操作,但首轮精修在受保护的另一字框中造成 183 个超过阈值的像素变化。 解决手段:将本次渲染实际使用的模式随预览缓存返回,跨模式局部比较时给出前后模式和保护区提示,保留真实像素差值。用正式客户端回归首次及后续精修。 收益:用户能区分视觉满意与严格保真。模型可解释首次逐字渲染带来的额外变化,再检查保护区,无需改变历史稿件的渲染。 --- crates/panache-mcp/src/engine.rs | 20 +++++++++++++++----- crates/panache-mcp/src/main.rs | 8 ++++---- crates/panache-mcp/src/review/local.rs | 17 ++++++++++++++--- crates/panache-mcp/tests/smoke.py | 8 +++++++- crates/panache-mcp/tool-design.md | 2 ++ 5 files changed, 42 insertions(+), 13 deletions(-) diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index 9dedbbbf..397bac3e 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -38,6 +38,12 @@ fn glyph_point( ] } +#[derive(Clone)] +pub struct RenderedPreview { + pub png: String, + pub fine_edit: bool, +} + struct CachedPage { draft: String, section: u32, @@ -45,7 +51,7 @@ struct CachedPage { settings: u32, edits: u32, page: usize, - png: String, + preview: RenderedPreview, } type PageSink<'a> = dyn FnMut(usize, &image::RgbaImage) -> handwriting_core::Result<()> + 'a; @@ -160,7 +166,7 @@ impl Engine { section: Section, page_number: usize, cancel: &Cancellation, - ) -> Result<(String, bool)> { + ) -> Result<(RenderedPreview, bool)> { let (n, v) = (section.number, section.version); ensure!( (1..=Limits::default().max_pages).contains(&page_number), @@ -173,7 +179,7 @@ impl Engine { && p.edits == edit_revision && (p.section, p.version, p.page) == (n, v, page_number) }) { - return Ok((hit.png.clone(), true)); + return Ok((hit.preview.clone(), true)); } let mut background = draft.background()?; let camera = draft.camera(background.as_deref())?; @@ -189,6 +195,10 @@ impl Engine { })?; let png = image.with_context(|| format!("Section has {pages} pages; requested {page_number}"))?; + let preview = RenderedPreview { + png, + fine_edit: request.params.fine_edit, + }; if self.cache.len() == 4 { self.cache.pop_front(); } @@ -199,9 +209,9 @@ impl Engine { settings: draft.settings_revision, edits: edit_revision, page: page_number, - png: png.clone(), + preview: preview.clone(), }); - Ok((png, false)) + Ok((preview, false)) } fn photo<'a>( draft: &'a Snapshot<'_>, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 00ab026e..4f5fbaf5 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -460,8 +460,8 @@ impl Panache { return review::local::page(&state.drafts, engine, &draft, section, &input, region, cancel); } let baselines=engine.review_baselines(&draft,section.clone(),page,cancel)?; - let (png,_)=engine.preview(&draft,section,page,cancel)?; - return review::page(&draft,number,page,&png,&baselines,cancel); + let (preview,_)=engine.preview(&draft,section,page,cancel)?; + return review::page(&draft,number,page,&preview.png,&baselines,cancel); } if input.view == Some(PreviewView::Layout) { let result = engine.layout(&draft, section, &input, cancel)?; @@ -471,7 +471,7 @@ impl Panache { input.offset.is_none() && input.limit.is_none(), "offset and limit require view=layout" ); - let (png, cached) = engine.preview(&draft, section, page, cancel)?; + let (preview, cached) = engine.preview(&draft, section, page, cancel)?; let mut result = reply( format!("第 {number} 节 · 第 {page} 页 · 版本 {}", draft.revision), json!({ @@ -479,7 +479,7 @@ impl Panache { "section": number, "page_in_section": page, "cached": cached }), ); - result.content.push(ContentBlock::image(png, "image/png")); + result.content.push(ContentBlock::image(preview.png, "image/png")); Ok(result) }) .await; diff --git a/crates/panache-mcp/src/review/local.rs b/crates/panache-mcp/src/review/local.rs index 9fae0a2f..e18cace4 100644 --- a/crates/panache-mcp/src/review/local.rs +++ b/crates/panache-mcp/src/review/local.rs @@ -128,6 +128,7 @@ struct Appearance { finished: RgbaImage, params: Parameters, content_sha256: String, + fine_edit: bool, } impl Appearance { @@ -140,11 +141,12 @@ impl Appearance { ) -> Result { let params = controls::parameters(draft, section.number, &draft.controls)?; let sample = engine.review_baselines(draft, section.clone(), page, cancel)?; - let (png, _) = engine.preview(draft, section, page, cancel)?; + let (preview, _) = engine.preview(draft, section, page, cancel)?; Ok(Self { - finished: decode_page(&png)?, + finished: decode_page(&preview.png)?, params, content_sha256: sample.content_sha256, + fine_edit: preview.fine_edit, }) } @@ -289,7 +291,7 @@ pub fn page( thumbnail(&*img.view(x, y, w, h)) }; let paper_crop = crop(&paper); - let metadata = json!({ + let mut metadata = json!({ "draft_id":draft.id,"section":number,"page":page,"revision":draft.revision,"compare_revision":input.compare_revision, "photo_size":size,"region":region,"previous_region":input.previous_region,"crop_bounds":bounds, "crop_image_size":paper_crop.dimensions(),"channel_delta_threshold":THRESHOLD, @@ -297,6 +299,15 @@ pub fn page( "after":after_metrics,"before":before.as_ref().map(|_|before_metrics),"difference":before.as_ref().map(|_|diff), "guidance":"Ink counts pixels whose largest visible RGB channel difference from the paper is at least 8. Revision differences apply the same threshold to before and after appearances; outside_union_changed_pixels covers the entire page outside both polygons. This local inspection leaves full-page review status unchanged. Inspect the crops against the request, including whether disappearance was intended. Overlapping text and diagrams contribute to the same pixels. Check protected areas with another region. Stop once the target and protected areas meet the request; ask if intent or attribution is unclear." }); + if let Some(prior) = &before + && prior.fine_edit != after.fine_edit + { + let mode = |fine| if fine { "fine_edit" } else { "standard" }; + metadata["render_mode_change"] = json!({ + "before": mode(prior.fine_edit), "after": mode(after.fine_edit), + "guidance": "Fine edit applies ink variation to individual glyphs. Switching rendering modes can change unedited writing. All measured differences remain visible changes; inspect protected areas before judging the edit." + }); + } let mut response = reply(metadata.to_string(), metadata); let mut append = |label: &str, img: RgbaImage| -> Result<()> { response.content.push(ContentBlock::text(label)); diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 514498a2..d9877995 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -122,12 +122,18 @@ async def ink_box(): left, top, right, bottom = await ink_box() assert 139 <= left < right <= 256 and 169 <= top < bottom <= 256 assert right - left > 2 * (original[2] - original[0]) + region = [[130,160],[265,160],[265,265],[130,265]] + changed = await call(client, "preview_handwriting", **key, revision=3, view="review", + compare_revision=2, region=region) + mode = changed.structuredContent["render_mode_change"] + assert (mode["before"], mode["after"]) == ("standard", "fine_edit") await call(client, "adjust_glyphs", **edit, expected_revision=3, opacity=0) assert await ink_box() is None local = await call(client, "preview_handwriting", **key, revision=4, view="review", - compare_revision=3, region=[[130,160],[265,160],[265,265],[130,265]]) + compare_revision=3, region=region) assert len([item for item in local.content if item.type == "image"]) == 3 measured = local.structuredContent + assert "render_mode_change" not in measured assert measured["crop_bounds"] == [130, 160, 135, 105] assert measured["before"]["region"]["ink_pixels"] > 0 assert measured["after"]["region"]["ink_pixels"] == 0 diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index 834c1003..32ef569f 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -82,6 +82,8 @@ SICA 将历次尝试及其评估结果放入档案,供下一轮决策参考。 看 `before`、`after` 中各区域的 `ink_pixels`,可核对新位置是否出现墨迹、旧位置是否仍有笔画。底纸与成品任一可见 RGB 通道相差至少 8 级就计入墨迹。两版间也用这个阈值比较,`difference.outside_union_changed_pixels` 涵盖整页中两个区域并集之外的变动。重叠的图文都会计入,可把需要保护的标题或框线单独圈出再比较。若纸张像素、输出尺寸或页面内容已改变,分别检查各版本。局部复查即时渲染;要保存整页复盘或引用 `review_id` 时,另取一次不带区域的 `view="review"`。 +局部比较若出现 `render_mode_change`,表示两次生成实际使用了不同的墨迹渲染方式。普通文本首次精修可能切换为逐字生成笔画扰动,使其他字也出现像素变化。投影照片从建稿时即使用逐字渲染。涉及保护区时按实际图像和用户要求核验;要求像素保持时应披露测到的变化。 + ## 如何复测 从仓库根目录运行下列命令。两个脚本都使用独立临时稿库。比较版本时,把相同的测量脚本指向两个构建,使用相同字体与测试图片。 From 354819193177f5562b272e0cfb697432ae9811cd Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 19:53:57 +0800 Subject: [PATCH 16/24] =?UTF-8?q?docs(crates/panache-mcp):=20=E8=AF=B4?= =?UTF-8?q?=E6=98=8E=E7=9B=B8=E6=9C=BA=E5=85=83=E6=95=B0=E6=8D=AE=E5=92=8C?= =?UTF-8?q?=E7=AC=94=E7=94=BB=E6=9F=94=E5=8C=96=E7=9A=84=E4=BD=9C=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:首次接入的模型看到镜头和 ISO 参数后,无法从参数说明判断它们是否能消除字迹的贴图感。 解决手段:在相机参数目录中明确导出元数据的用途,提供笔画柔化的参数入口。协议回归同时比较写入 EXIF 前后的解码像素。 收益:用户能找到实际影响字迹外观的选项,验收时也能区分文件字节变化与可见像素变化。 --- crates/panache-mcp/src/controls.json | 8 ++++---- crates/panache-mcp/tests/smoke.py | 3 +++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/panache-mcp/src/controls.json b/crates/panache-mcp/src/controls.json index da9bd23e..ecf658dc 100644 --- a/crates/panache-mcp/src/controls.json +++ b/crates/panache-mcp/src/controls.json @@ -1,9 +1,9 @@ { "camera": { - "camera_make": {"type":"string","maxLength":96,"description":"Optional paper camera maker in printable ASCII. Source EXIF takes precedence."}, - "camera_model": {"type":"string","maxLength":96,"description":"Optional paper camera model in printable ASCII."}, - "camera_lens": {"type":"string","maxLength":96,"description":"Optional lens model in printable ASCII."}, - "camera_iso": {"type":"integer","min":1,"max":65535,"unit":"ISO"} + "camera_make": {"type":"string","maxLength":96,"description":"Camera make for export metadata. Used when the paper has no valid EXIF make."}, + "camera_model": {"type":"string","maxLength":96,"description":"Camera model for export metadata when missing from the paper EXIF."}, + "camera_lens": {"type":"string","maxLength":96,"description":"Lens model for export metadata when missing from the paper EXIF. Use ink_softness in the ink group to soften strokes."}, + "camera_iso": {"type":"integer","min":1,"max":65535,"unit":"ISO","description":"ISO for export metadata when missing from the paper EXIF. Ink appearance is controlled by the ink group."} }, "layout": { "font_size": {"type":"number","min":1,"max":2048,"unit":"px"}, diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index d9877995..943fcf4a 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -491,6 +491,9 @@ async def progress(value, total, message=None): assert camera_change.structuredContent["fine_layout"] == "preserved" tagged = png(await call(client, "preview_handwriting", draft_id=paper_id)) assert b"eXIf" in tagged and b"Test Camera" in tagged and tagged != adjusted + with Image.open(io.BytesIO(adjusted)) as untagged, Image.open(io.BytesIO(tagged)) as with_exif: + assert untagged.size == with_exif.size + assert untagged.convert("RGBA").tobytes() == with_exif.convert("RGBA").tobytes() tagged_layout = (await call(client, "preview_handwriting", **probe)).structuredContent assert tagged_layout["glyphs"][0]["adjustment"] == again["adjustment"] cleared = await call(client, "tune_handwriting", draft_id=paper_id, From 0fd01b2d99a17224ca1d8391b2a092503ff80867 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 19:54:10 +0800 Subject: [PATCH 17/24] =?UTF-8?q?feat(crates/panache-mcp):=20=E5=BC=95?= =?UTF-8?q?=E5=AF=BC=E7=94=BB=E4=BD=9C=E9=80=89=E4=BD=8D=E5=B9=B6=E6=8C=89?= =?UTF-8?q?=E5=8E=9F=E5=83=8F=E7=B4=A0=E5=A4=8D=E6=9F=A5=E5=AD=97=E8=BF=B9?= =?UTF-8?q?=E8=A7=82=E6=84=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:横线偏差能说明位置,缩小的整页图难以判断笔画和照片焦点是否协调。用户也可能在没有横线的画作上题字,具体留白需向本人确认。 解决手段:在握手、导入和整页复查中披露可用范围,给出锚定当前版本的原像素裁图调用与调参入口;未定选位以自然语言请用户指出,支持在同稿继续。用协议测试实际墨色、柔度和透明度变化。 收益:模型能用照片附近的笔画、印字及横线进行视觉对照,区分位置证据与外观判断。参考 https://arxiv.org/abs/2411.15245 对字形和颜色独立控制的研究;本项目以自身成品像素验证。 --- crates/panache-mcp/README.md | 6 +- crates/panache-mcp/src/main.rs | 18 +++-- crates/panache-mcp/src/review.rs | 42 +++++++++++- crates/panache-mcp/tests/review_comparison.py | 68 ++++++++++++++++++- crates/panache-mcp/tool-design.md | 4 +- 5 files changed, 127 insertions(+), 11 deletions(-) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index b1d62a6c..888f5431 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -94,14 +94,16 @@ cargo build --locked --release -p panache-mcp ## 照片排版与成品复盘 -1. 用 `save_section` 导入照片并保留版本号。用 `preview_handwriting(view="review")` 取得同一页的底纸、成品和叠图。图片最多长边 900 像素,像素坐标以返回的 `photo_size` 为准。需要看笔画细节时取原尺寸 `view="image"`。 -2. 上、中、下分别看字是否顺着实际横线、有没有盖住页眉,以及墨色和笔画锐度是否适合底纸。复盘附带像素对比和附近暗线的偏差。无横线或用户只说“放这边”时,把底纸或叠图展示给人,确认目标区域、首末行或四个角,再做修改。 +1. 用 `save_section` 导入照片并保留版本号。用 `preview_handwriting(view="review")` 取得同一页的底纸、成品和叠图。整页复查图长边最多 900 像素,像素坐标以返回的 `photo_size` 为准。检查有字区域的横线、页眉、页边和需要保留的图案。 +2. 无横线纸和画作均可排字。若位置不明确,先问“你想把字写在哪一侧?也可以圈一块区域,或指出要留白的图案”。用户已指定位置或委托选位时,可以直接排版给出预览。拍摄清楚、页边可辨的照片方便定位;只有失焦、遮挡或斜拍确实妨碍了本次要求时,才指出具体看不清的部分,建议换一张平整清晰的照片。 3. 调用 `tune_handwriting(draft_id, expected_revision, paper_guides, note)` 在原照片上重排全文。至少给两条参考线,每条提供行号与左右端点。无横线纸也可以指定想写入的区域。传空数组恢复建稿时的校准。旧版本仍可回看;改写书写区域会重置冲突的边距覆盖,重新排版后需重新选字。 4. 局部改动用 `preview_handwriting(view="layout", region=[[x,y],…])` 圈选字形中心,结果按页分批。把选中的 ID 和相同版本交给 `adjust_glyphs`。`place_center` 将一组字移到指定照片位置;`target_quad` 按左上、右上、右下、左下四角放置所选字块,替换该组已有几何调整。局部字形还可分别调倾斜、浓度和笔画。调整后复查新版本。 5. 用 `read_section(view="trajectory")` 回看该稿的近期操作、简短调整理由和按页记录的复盘指标。可锁定版本,用 `offset/limit` 向前翻。把需要人判断的歧义带回当前会话;确定符合用途后导出同一版本。 要核对局部改动,用 `preview_handwriting(view="review", region=…, revision=新版本, compare_revision=旧版本)` 查看同一区域的底纸、改前和改后图。移动字块时还可用 `previous_region` 圈出旧位置。需要保护的文字或页眉可单独圈选复查。区域使用原尺寸成品像素。[局部坐标与测量示例](tool-design.md#局部改动的复查) +如果字像贴在照片上,在照片整页复查的 `photo_appearance` 中取 `preview_arguments` 再调用一次 `preview_handwriting`。有页内文字基线样本时,这组参数会给出该版本一处字迹附近的原像素底纸和成品裁图;也可以自己圈选。对照邻近印字或横线的边缘清晰度、墨色深浅,再看字号与可写空间是否相称。用 `describe_controls` 指定稿件、版本和 `ink`、`layout` 或 `typography` 参数组可查当前值。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比。改一版后,对同一选区加入 `compare_revision` 比较。只有文字结果的客户端可转述测量,请用户看图判断观感。 + `tune_handwriting(font_path=…)` 会把本机 TTF/OTF 随稿保存。可用返回的字体标识在同一稿内切回该字体。墨迹组的 `transparent_background` 控制原尺寸 PNG 预览和 ZIP,PDF 保留纸张。透明稿复盘会把墨迹放回底纸,方便判断实际可读性。 ### 比较两版,找回当时的依据 diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 4f5fbaf5..a209179c 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -151,7 +151,7 @@ impl Panache { }; let permit = self.0.prepare_slot.clone().acquire_owned().await?; let worker = self.0.worker.clone(); - let saved = tokio::task::spawn_blocking({ + let mut saved = tokio::task::spawn_blocking({ let state = self.0.clone(); move || -> Result { let _permit = permit; @@ -186,12 +186,18 @@ impl Panache { } }) .await??; - let message = format!( + let mut message = format!( "已保存稿件 `{}` 的第 {} 节,当前版本 **{}**。", saved["draft_id"].as_str().unwrap_or_default(), saved["section"], saved["revision"] ); + if saved["paper"]["alignment"] == "unverified" { + let hint = "未识别到可靠横线。无横线纸和画作均可继续使用。若落字位置不明确,先问用户想写在哪一侧、是否方便圈出区域,或哪些图案要留白。已有指定区域或用户已委托选位时,可直接按意图在本稿排版;用 tune_handwriting 的 paper_guides 定位,再用 preview_handwriting 的 review 视图复查。"; + saved["placement_guidance"] = json!(hint); + message.push('\n'); + message.push_str(hint); + } Ok(reply(message, saved)) } } @@ -205,9 +211,11 @@ impl ServerHandler for Panache { .with_instructions(concat!( "Start with save_section(markdown). Use its draft_id and revision for preview_handwriting or export_handwriting. ", "Use list_fonts for names and list_drafts to resume. A paper_path must be readable on the server computer. ", - "For photo placement use preview_handwriting(view=review). Inspect the returned images when available. ", + "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. ", - "Ask for clarification on ambiguous regions. Photo coordinates use native output pixels; local dx/dy use paper-space pixels. ", + "Unruled paper and artwork are supported. If placement is unclear ask where to write or what to keep clear; follow specified or delegated choices. ", + "Only suggest a clearer, flatter photo if visible blur, occlusion or perspective prevents the requested placement; identify the obstruction. ", + "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." )) } @@ -281,7 +289,7 @@ impl Panache { } #[tool( - description = "Revise a draft: change controls, import a local font_path, or replace paper_guides on its saved image. For a special writing area ask the user for first/last writable baselines. 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. Review the new revision before export." )] async fn tune_handwriting(&self, Parameters(input): Parameters) -> CallToolResult { let state = self.0.clone(); diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs index 01a1b9cd..b11f9675 100644 --- a/crates/panache-mcp/src/review.rs +++ b/crates/panache-mcp/src/review.rs @@ -82,6 +82,30 @@ pub struct PageSample { pub content_sha256: String, } +// Suggest a crop around a sampled text line at native resolution, including neighboring paper. +fn detail_region( + baselines: &[[f32; 2]], + (width, height): (u32, u32), + font_size: f32, +) -> Option<[[u32; 2]; 4]> { + let on_page = |&&[x, y]: &&[f32; 2]| { + (0. ..width as f32).contains(&x) && (0. ..height as f32).contains(&y) + }; + let mut points = baselines.iter().filter(on_page); + let middle = points.clone().count() / 2; + let &[x, y] = points.nth(middle)?; + let w = width.min((font_size * 10.).round().clamp(160., 800.) as u32); + let h = height.min((font_size * 4.).round().clamp(96., 480.) as u32); + let left = (x as u32).saturating_sub(w / 2).min(width - w); + let top = (y as u32).saturating_sub(h / 2).min(height - h); + Some([ + [left, top], + [left + w, top], + [left + w, top + h], + [left, top + h], + ]) +} + fn decode_page(png: &str) -> Result { let bytes = STANDARD.decode(png)?; let limits = Limits { @@ -272,15 +296,29 @@ pub fn page( let next = if peak == 0 { "If this page should contain text, check ink opacity/color, local edits and off-page placement. Review the new revision." } else if outside > 0 || draft.paper.as_ref().is_some_and(|p| !p.ruled) { - "Confirm the intended writing area against the overlay. If ambiguous, show the user the image and ask which corners or first/last baselines to use." + "Check the overlay against the intended area. If placement is unclear, ask where to write (which side, a marked area, or what to keep clear). If the user specified the area or delegated placement, use that direction and review the result." } else { - "Compare the upper, middle and lower writing with the saved paper. Check header clearance, contrast, focus and letter size. Ask the user if the desired appearance is unclear." + "Compare writing across the occupied parts of the page with the saved paper. Check the requested position, header clearance, contrast, focus and letter size." }; let metadata = { let mut metadata = observation; metadata["photo_size"] = json!([w, h]); metadata["thumbnail_size"] = json!([result.width(), result.height()]); metadata["next_step"] = json!(next); + if draft.paper.is_some() { + let mut appearance = json!({ + "inspect":"Compare the strokes with nearby photographed marks for edge softness, contrast and size, and with the available writing space for letter size. Baseline offsets only measure placement. If images are unavailable, ask the user to inspect the crop before judging appearance.", + "controls":"describe_controls with draft_id, revision and group: ink (ink #RRGGBB, ink_opacity %, ink_softness and ink_thickness in paper-space px); layout (font_size in paper-space px); typography (font).", + "after_edit":"Review the edited revision. Use the same region with compare_revision for paper/before/after crops. If text reflowed onto different pages, inspect each revision separately." + }); + if let Some(region) = detail_region(baselines, (w, h), params.font_size) { + appearance["preview_arguments"] = json!({ + "draft_id":draft.id,"revision":draft.revision,"section":section,"page":page, + "view":"review","region":region + }); + } + metadata["photo_appearance"] = appearance; + } metadata }; let mut response = reply( diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index 3e2d1f7e..51a16194 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -1,11 +1,15 @@ """Page comparison through actual MCP calls, using a synthetic sloping ruled sheet.""" +import base64 +import io import sqlite3 import struct import zlib from contextlib import closing from pathlib import Path +from PIL import Image, ImageChops, ImageDraw, ImageStat + def slanted_sheet(path): width, height = 400, 500 @@ -38,7 +42,67 @@ def chunk(tag, data): ] +async def unruled_artwork(client, directory, call): + path = directory / "unruled.png" + paper = Image.new("RGB", (1100, 640), "#eee5d8") + ImageDraw.Draw(paper).ellipse((830, 150, 1020, 480), fill="#ada7ba") + paper.save(path) + saved = await call(client, "save_section", markdown="春风又绿江南岸。", paper_path=str(path), + style={"font_size": 34, "seed": 27}) + key = {"draft_id": saved.structuredContent["draft_id"]} + assert saved.structuredContent["paper"]["alignment"] == "unverified" + assert "哪一侧" in saved.structuredContent["placement_guidance"] + assert "已委托选位" in saved.content[0].text + path.unlink() + # The user picks the left side, leaving the drawing on the right clear. + await call(client, "tune_handwriting", **key, expected_revision=1, paper_guides=[ + {"row": 0, "left": [100, 180], "right": [650, 170]}, + {"row": 5, "left": [70, 450], "right": [700, 440]}, + ]) + whole = (await call(client, "preview_handwriting", **key, view="review")).structuredContent + appearance = whole["photo_appearance"] + args = appearance["preview_arguments"] + assert args["revision"] == 2 and args["draft_id"] == key["draft_id"] + assert "ink_softness" in appearance["controls"] + archived = await call(client, "read_section", **key, view="review", review_id=whole["review_id"]) + assert "photo_appearance" not in archived.structuredContent["evidence"] + crop = await call(client, "preview_handwriting", **args) + x, y, w, h = crop.structuredContent["crop_bounds"] + assert crop.structuredContent["crop_image_size"] == [w, h] and max(w, h) <= 900 + assert crop.structuredContent["after"]["region"]["ink_pixels"] > 0 + + def images(result): + return [Image.open(io.BytesIO(base64.b64decode(item.data))).convert("RGB") + for item in result.content if item.type == "image"] + + base, finished = images(crop) + full = images(await call(client, "preview_handwriting", **key, revision=2))[0] + bounds = (x, y, x + w, y + h) + assert base.tobytes() == paper.crop(bounds).tobytes() + assert finished.tobytes() == full.crop(bounds).tobytes() + assert full.crop((800, 0, 1100, 640)).tobytes() == paper.crop((800, 0, 1100, 640)).tobytes() + for rev, change in [(2, {"ink_softness": 0.8}), (3, {"ink": "#843522"}), (4, {"ink_opacity": 70})]: + await call(client, "tune_handwriting", **key, expected_revision=rev, changes=change) + paired = await call(client, "preview_handwriting", **{**args, "revision": rev + 1}, + compare_revision=rev) + assert paired.structuredContent["difference"]["region_changed_pixels"] > 0, change + paper_crop, before, after = images(paired) + assert paper_crop.tobytes() == base.tobytes() and before.tobytes() == finished.tobytes() + old_delta = ImageChops.difference(base, before).convert("L") + new_delta = ImageChops.difference(base, after).convert("L") + if "ink_softness" in change: + # Feathered strokes reach more of the surrounding paper. + assert new_delta.histogram()[0] < old_delta.histogram()[0] + elif "ink" in change: + # Moving the pen toward brick red leaves more red in the finished crop. + assert ImageStat.Stat(after).sum[0] > ImageStat.Stat(before).sum[0] + else: + assert ImageStat.Stat(new_delta).sum[0] < ImageStat.Stat(old_delta).sum[0] + finished = after + + async def exercise(client, directory, call): + await unruled_artwork(client, directory, call) path = directory / "slanted.png" guides = slanted_sheet(path) shifted = [ @@ -150,7 +214,7 @@ def assets(): ) await tune(4, changes={"ink_opacity": 0}) assert "missing_after_review" in (await compare(4, 5))["comparison"]["limitations"] - await review(5) + assert "photo_appearance" in await review(5) invisible = (await compare(4, 5))["comparison"]["delta"] assert ( invisible["visibility_after"] == "no_visible_change" @@ -175,6 +239,8 @@ async def incompatible(draft_id, before, after, reason): await incompatible(key["draft_id"], 4, 6, "page_content_changed_or_repaginated") preset = (await call(client, "save_section", markdown="字", style={"seed": 13})).structuredContent preset_id = preset["draft_id"] + plain = await call(client, "preview_handwriting", draft_id=preset_id, view="review") + assert "photo_appearance" not in plain.structuredContent await call(client, "tune_handwriting", draft_id=preset_id, expected_revision=1, changes={"paper": "grid"}) await incompatible(preset_id, 1, 2, "different_reference_paper") await call(client, "tune_handwriting", draft_id=preset_id, expected_revision=2, changes={"width": 800}) diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index 32ef569f..04ae7737 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -33,7 +33,7 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 ## 照片和纸面坐标 -导入 `paper_path` 时,默认 `paper_mode="photo"` 在原照片上合成笔迹和插图。`flatten` 保存校平后的底纸。建稿结果只返回尺寸、边距、行距和识别方式。遇到置信度不足的照片会返回 `alignment="unverified"`。稿件保留建稿时的纸张快照,后续版本可在同一底图上重新校准。 +导入 `paper_path` 时,默认 `paper_mode="photo"` 在原照片上合成笔迹和插图。`flatten` 保存校平后的底纸。建稿结果返回尺寸、边距、行距和识别方式。没有识别到可靠横线时返回 `alignment="unverified"` 和 `placement_guidance`。如果无横线纸或画作上的落字位置不明确,直接问用户想写在哪里或哪些内容需要留白。把指定区域映射成 `paper_guides` 就能在同稿上继续;用户委托选位时可先给预览。 | 模型可以取得或指定的内容 | 对应接口 | | --- | --- | @@ -55,6 +55,8 @@ MCP 的工具列表支持分页。客户端可能取完所有页;分页能控 `view="review"` 按需返回三张按相同比例缩放的图片。橙色边界和青色参考线来自书写区估计,叠图可与裸底纸对照。在原分辨率比较显示在纸上的墨迹和底纸,按图像上中下三等分统计 RGB 任一通道变化至少 8 级的像素及落在参考区外的数量。在抽样字形调整后的基线中点附近搜索底纸的局部暗线并报告垂直偏差中位数和支持样本数;校徽或背景纹理也可能给出暗线,无足够对比时返回空值。短文自然可能只覆盖上部。对有正文的页面,零像素变化是重新检查的明确信号。没有自动审美评分,验收时仍要查看原图,必要时请用户指出具体位置。 +照片整页复查单独返回 `photo_appearance`。若页内有抽样文字基线,`preview_arguments` 可直接传给 `preview_handwriting`,取得当前节、页、版本的同位置原像素裁图。示例区域围绕一条抽样基线,用户关心其他区域时换用对应的 `region`。局部裁图让视觉客户端对照附近实际印字、横线或纸面,分别判断墨色、边缘和相对字号;没有参照物时可结合用户反馈。提示与示例区域只随本次复查返回,历史记录仍只保存原有测量。 + 轨迹按稿件和版本保存在本机。修改操作与简短备注在同一事务提交,复盘按稿件版本、节页、测量算法版本及成品像素摘要去重。像素摘要为 SHA-256,输入依次是两个小端 u32 宽高和导出预览的原始 RGBA8 字节,在透明墨迹叠回纸张前计算。算法或成品变化产生新 ID,旧库迁移保留原证据并将未知来源字段置空。导出按不同节页计数,并取每页最近归档的测量。改变测量口径时应提升算法版本。查询不会返回原文、字体数据、图片字节或完整对话。这里的轨迹指已执行的动作和可复查的结果。模型可以对照前后版本调整下一步;没有修改模型权重或自动跨用户积累经验。 省略 `region` 的版本比较仅返回数据,取同一节页两版最近归档的复盘及各自最近 50 条署名反馈。精确 ID 可用来回查对比时所用的观察,更早的反馈也可在轨迹中分页查找。页面成员摘要绑定不可变节版本和该页所有字形的源位置;重新保存该节可能保守地中止定量比较。分区至少在两侧各有 3 个暗线支持样本才返回中位偏差的差值,这是最低报告门槛。它不能证明两组样本完全相同或有统计显著性。越界像素相对各版本自己的书写区计算。 From c9063619bfb2ef4c9e78ca994699f28a10f9d645 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 19:54:24 +0800 Subject: [PATCH 18/24] =?UTF-8?q?fix(crates/panache-mcp):=20=E5=BE=AE?= =?UTF-8?q?=E8=B0=83=E5=A2=A8=E8=89=B2=E5=92=8C=E6=9F=94=E5=BA=A6=E6=97=B6?= =?UTF-8?q?=E4=BF=9D=E7=95=99=E5=B7=B2=E5=AE=9A=E4=BD=8D=E7=9A=84=E5=AD=97?= =?UTF-8?q?=E5=BD=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:实拍纸上已将末字移至右侧,再单独调整墨色、柔度和透明度时,旧版丢失 480 纸面像素的位移,目标位置的可见墨迹由 242 变为零。 解决手段:对仅影响笔画绘制的墨迹参数复用原排版版本,仍按新设置重新渲染。回归核对调整保留、原位置坐标及恢复颜色后输出一致,并披露字体或参考线变更的复核要求。 收益:用户能先确定题字位置,再逐版改善墨色与照片的协调程度;实拍复验中字框中心保持在 (926.9, 295.9)。 --- crates/panache-mcp/README.md | 2 +- crates/panache-mcp/src/main.rs | 2 +- crates/panache-mcp/src/tuning.rs | 2 +- crates/panache-mcp/tests/smoke.py | 17 ++++++++++++++++- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 888f5431..58aea301 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -102,7 +102,7 @@ cargo build --locked --release -p panache-mcp 要核对局部改动,用 `preview_handwriting(view="review", region=…, revision=新版本, compare_revision=旧版本)` 查看同一区域的底纸、改前和改后图。移动字块时还可用 `previous_region` 圈出旧位置。需要保护的文字或页眉可单独圈选复查。区域使用原尺寸成品像素。[局部坐标与测量示例](tool-design.md#局部改动的复查) -如果字像贴在照片上,在照片整页复查的 `photo_appearance` 中取 `preview_arguments` 再调用一次 `preview_handwriting`。有页内文字基线样本时,这组参数会给出该版本一处字迹附近的原像素底纸和成品裁图;也可以自己圈选。对照邻近印字或横线的边缘清晰度、墨色深浅,再看字号与可写空间是否相称。用 `describe_controls` 指定稿件、版本和 `ink`、`layout` 或 `typography` 参数组可查当前值。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比。改一版后,对同一选区加入 `compare_revision` 比较。只有文字结果的客户端可转述测量,请用户看图判断观感。 +如果字像贴在照片上,在照片整页复查的 `photo_appearance` 中取 `preview_arguments` 再调用一次 `preview_handwriting`。有页内文字基线样本时,这组参数会给出该版本一处字迹附近的原像素底纸和成品裁图;也可以自己圈选。对照邻近印字或横线的边缘清晰度、墨色深浅,再看字号与可写空间是否相称。用 `describe_controls` 指定稿件、版本和 `ink`、`layout` 或 `typography` 参数组可查当前值。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比。仅修改墨迹组参数时会保留已完成的单字移位和透视调整;更换字体、字号或参考线后应在新版本重新检查选区。改一版后,对同一选区加入 `compare_revision` 比较。只有文字结果的客户端可转述测量,请用户看图判断观感。 `tune_handwriting(font_path=…)` 会把本机 TTF/OTF 随稿保存。可用返回的字体标识在同一稿内切回该字体。墨迹组的 `transparent_background` 控制原尺寸 PNG 预览和 ZIP,PDF 保留纸张。透明稿复盘会把墨迹放回底纸,方便判断实际可读性。 diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index a209179c..40af0d76 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -289,7 +289,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. 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. Review the new revision before export." )] async fn tune_handwriting(&self, Parameters(input): Parameters) -> CallToolResult { let state = self.0.clone(); diff --git a/crates/panache-mcp/src/tuning.rs b/crates/panache-mcp/src/tuning.rs index e08fa6fe..e46ef08e 100644 --- a/crates/panache-mcp/src/tuning.rs +++ b/crates/panache-mcp/src/tuning.rs @@ -91,7 +91,7 @@ pub fn apply(state: &State, input: Tune) -> Result { ); controls::parameters(&draft, 1, &changes)?; let preserve_layout = changes.keys().chain(draft.controls.keys()).all(|key| { - key == "transparent_background" + controls::catalog()["ink"].get(key).is_some() || controls::catalog()["camera"].get(key).is_some() || changes.get(key) == draft.controls.get(key) }); diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 943fcf4a..9496b38a 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -500,6 +500,21 @@ async def progress(value, total, message=None): expected_revision=4, changes={"camera_model": None, "camera_iso": None}) assert cleared.structuredContent["revision"] == 5 assert png(await call(client, "preview_handwriting", draft_id=paper_id)) == adjusted + ink_settings = {"ink": "#36363b", "ink_alpha": 247, "ink_opacity": 88, + "ink_softness": 0.8, "ink_thickness": 0.2} + prior_ink = {key: tuned["controls"].get(key) for key in ink_settings} + for rev, patch in [(5, ink_settings), (6, prior_ink)]: + ink_change = await call(client, "tune_handwriting", draft_id=paper_id, + expected_revision=rev, changes=patch) + assert ink_change.structuredContent["fine_layout"] == "preserved" + glyph = (await call(client, "preview_handwriting", **probe)).structuredContent["glyphs"][0] + assert glyph["current_photo_quad"] == again["current_photo_quad"] + assert glyph["adjustment"] == again["adjustment"] + rendered = png(await call(client, "preview_handwriting", draft_id=paper_id)) + if rev == 5: + assert rendered != adjusted + else: + assert rendered == adjusted # Exercise a long draft without ever exporting or rendering its tail. repeated = "逐题列出已知条件,检查解题步骤。\n" * 600 large = ( @@ -553,7 +568,7 @@ async def progress(value, total, message=None): client, "save_section", draft_id=paper_id, - expected_revision=5, + expected_revision=7, section=1, markdown="重排后的版本", ) From 0270cee5f823d971328342e5e94ee26dec2d59a1 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 20:14:53 +0800 Subject: [PATCH 19/24] =?UTF-8?q?feat(crates/panache-mcp):=20=E5=8C=BA?= =?UTF-8?q?=E5=88=86=E7=BC=BA=E5=A4=B1=E6=A0=8F=E4=BD=8D=E5=92=8C=E5=8F=AF?= =?UTF-8?q?=E5=AE=9A=E4=BD=8D=E7=9A=84=E5=A4=8D=E6=9D=82=E8=A1=A8=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:要求制作完整表单时,只看到正文的首次接入者会先建局部草稿再追问;可辨的侧栏和评分区又容易被误判为溢出。 解决手段:在握手前段披露整页与部分填写的选择,解释转向栏位及正文区域外的有意落字。用自动生成的表格检验公开协议的实际填写、侧栏读向和指定区域外的像素。 收益:在同一裁片上,用新提示的独立会话询问补图前没有业务调用;用户明确只填正文后可继续。完整表实测可保留评分栏并交付。 --- crates/panache-mcp/README.md | 6 +- crates/panache-mcp/src/inputs.rs | 2 +- crates/panache-mcp/src/main.rs | 8 +- crates/panache-mcp/src/review.rs | 2 +- crates/panache-mcp/tests/coursework_form.py | 106 ++++++++++++++++++++ crates/panache-mcp/tests/smoke.py | 7 ++ 6 files changed, 124 insertions(+), 7 deletions(-) create mode 100644 crates/panache-mcp/tests/coursework_form.py diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 58aea301..ccd58ee2 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -94,14 +94,16 @@ cargo build --locked --release -p panache-mcp ## 照片排版与成品复盘 -1. 用 `save_section` 导入照片并保留版本号。用 `preview_handwriting(view="review")` 取得同一页的底纸、成品和叠图。整页复查图长边最多 900 像素,像素坐标以返回的 `photo_size` 为准。检查有字区域的横线、页眉、页边和需要保留的图案。 -2. 无横线纸和画作均可排字。若位置不明确,先问“你想把字写在哪一侧?也可以圈一块区域,或指出要留白的图案”。用户已指定位置或委托选位时,可以直接排版给出预览。拍摄清楚、页边可辨的照片方便定位;只有失焦、遮挡或斜拍确实妨碍了本次要求时,才指出具体看不清的部分,建议换一张平整清晰的照片。 +1. 表格、无横线纸和画作均可排字。用户已指定位置或委托选位时,直接按意图排版。落字区有歧义时,简短问“要写在哪个栏,哪些地方留白?”若必填区域在画外,或失焦、遮挡、透视已使它无法定位,建稿前指出具体缺哪一块,请用户补拍该区域或确认只填可见部分。已明确要求只写正文时,直接填写可定位的正文区。 +2. 用 `save_section` 导入照片并保留版本号。用 `preview_handwriting(view="review")` 取得同一页的底纸、成品和叠图。整页复查图长边最多 900 像素,像素坐标以返回的 `photo_size` 为准。检查有字区域的横线、页眉、页边和需要保留的图案。 3. 调用 `tune_handwriting(draft_id, expected_revision, paper_guides, note)` 在原照片上重排全文。至少给两条参考线,每条提供行号与左右端点。无横线纸也可以指定想写入的区域。传空数组恢复建稿时的校准。旧版本仍可回看;改写书写区域会重置冲突的边距覆盖,重新排版后需重新选字。 4. 局部改动用 `preview_handwriting(view="layout", region=[[x,y],…])` 圈选字形中心,结果按页分批。把选中的 ID 和相同版本交给 `adjust_glyphs`。`place_center` 将一组字移到指定照片位置;`target_quad` 按左上、右上、右下、左下四角放置所选字块,替换该组已有几何调整。局部字形还可分别调倾斜、浓度和笔画。调整后复查新版本。 5. 用 `read_section(view="trajectory")` 回看该稿的近期操作、简短调整理由和按页记录的复盘指标。可锁定版本,用 `offset/limit` 向前翻。把需要人判断的歧义带回当前会话;确定符合用途后导出同一版本。 要核对局部改动,用 `preview_handwriting(view="review", region=…, revision=新版本, compare_revision=旧版本)` 查看同一区域的底纸、改前和改后图。移动字块时还可用 `previous_region` 圈出旧位置。需要保护的文字或页眉可单独圈选复查。区域使用原尺寸成品像素。[局部坐标与测量示例](tool-design.md#局部改动的复查) +作业表可用正文横线设置参考线,将同一页的课程、姓名等字块分别定位。若侧栏印字自下往上读,将原字块的左上、右上、右下、左下四角依次投到侧栏的左下、左上、右上、右下。复查时按栏核对读向、印字和留给老师的评分区。`changed_pixels_outside_reference` 也会计入正文参考区外有意填写的表头和侧栏,应结合这些栏位解读。 + 如果字像贴在照片上,在照片整页复查的 `photo_appearance` 中取 `preview_arguments` 再调用一次 `preview_handwriting`。有页内文字基线样本时,这组参数会给出该版本一处字迹附近的原像素底纸和成品裁图;也可以自己圈选。对照邻近印字或横线的边缘清晰度、墨色深浅,再看字号与可写空间是否相称。用 `describe_controls` 指定稿件、版本和 `ink`、`layout` 或 `typography` 参数组可查当前值。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比。仅修改墨迹组参数时会保留已完成的单字移位和透视调整;更换字体、字号或参考线后应在新版本重新检查选区。改一版后,对同一选区加入 `compare_revision` 比较。只有文字结果的客户端可转述测量,请用户看图判断观感。 `tune_handwriting(font_path=…)` 会把本机 TTF/OTF 随稿保存。可用返回的字体标识在同一稿内切回该字体。墨迹组的 `transparent_background` 控制原尺寸 PNG 预览和 ZIP,PDF 保留纸张。透明稿复盘会把墨迹放回底纸,方便判断实际可读性。 diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 81fbc0c9..20ff8a2c 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -190,7 +190,7 @@ pub struct Nudge { pub ids: Vec, /// Move this selection as a group so its mean glyph center lands at [x,y] on the preview. Use separately from dx, dy and shape. pub place_center: Option<[u32; 2]>, - /// Absolute placement of the original selected block into four image pixels (TL,TR,BR,BL). Replaces prior geometric edits for these IDs. Exclusive with other geometry changes. + /// Image destinations of the original block's TL,TR,BR,BL corners, in that order (for a 90° counterclockwise sidebar: BL,TL,TR,BR of the field). Replaces prior geometry; use separately from other geometry changes. pub target_quad: Option<[[u32; 2]; 4]>, /// Absolute offsets in pixels from the original glyph position. Omitted fields retain their values. pub dx: Option, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 40af0d76..3f572aa7 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -209,12 +209,14 @@ impl ServerHandler for Panache { ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) .with_server_info(Implementation::new("panache-mcp", handwriting_core::app_version())) .with_instructions(concat!( - "Start with save_section(markdown). Use its draft_id and revision for preview_handwriting or export_handwriting. ", + "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. ", "Use list_fonts for names and 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. ", - "Unruled paper and artwork are supported. If placement is unclear ask where to write or what to keep clear; follow specified or delegated choices. ", - "Only suggest a clearer, flatter photo if visible blur, occlusion or perspective prevents the requested placement; identify the obstruction. ", + "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." )) diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs index b11f9675..50646d8a 100644 --- a/crates/panache-mcp/src/review.rs +++ b/crates/panache-mcp/src/review.rs @@ -296,7 +296,7 @@ pub fn page( let next = if peak == 0 { "If this page should contain text, check ink opacity/color, local edits and off-page placement. Review the new revision." } else if outside > 0 || draft.paper.as_ref().is_some_and(|p| !p.ruled) { - "Check the overlay against the intended area. If placement is unclear, ask where to write (which side, a marked area, or what to keep clear). If the user specified the area or delegated placement, use that direction and review the result." + "Check the overlay against the intended fields and protected print. Writing outside the reference can belong in a header or sidebar. If placement is unclear, ask where to write or what to keep clear; follow specified or delegated placement." } else { "Compare writing across the occupied parts of the page with the saved paper. Check the requested position, header clearance, contrast, focus and letter size." }; diff --git a/crates/panache-mcp/tests/coursework_form.py b/crates/panache-mcp/tests/coursework_form.py new file mode 100644 index 00000000..ed1f10db --- /dev/null +++ b/crates/panache-mcp/tests/coursework_form.py @@ -0,0 +1,106 @@ +"""Fill a synthetic coursework form through public MCP calls and check its pixels.""" + +import base64 +import io + +from PIL import Image, ImageChops, ImageDraw + +from mcp_client import call + + +def corners(box): + left, top, right, bottom = box + return [[left, top], [right, top], [right, bottom], [left, bottom]] + + +def finished_image(result): + block = next(b for b in result.content if b.type == "image") + return Image.open(io.BytesIO(base64.b64decode(block.data))).convert("RGB") + + +def ink_mask(paper, finished): + delta = ImageChops.difference(paper, finished).convert("L") + return delta.point(lambda value: 255 if value >= 8 else 0) + + +async def exercise(client, directory): + # Fixture annotations express the user's choices independently of detected lines. + paper = Image.new("RGB", (420, 460), "#f8f6ed") + draw = ImageDraw.Draw(paper) + draw.text((80, 12), "UNIVERSITY COURSEWORK", fill="black") + draw.rectangle((24, 48, 395, 88), outline="black") + draw.text((34, 61), "Course", fill="black") + draw.line((255, 48, 255, 88), fill="black") + draw.text((265, 61), "Score:", fill="black") + draw.rectangle((24, 104, 395, 428), outline="black") + draw.line((73, 104, 73, 428), fill="black") + label = Image.new("RGB", (42, 16), paper.getpixel((0, 0))) + ImageDraw.Draw(label).text((0, 0), "Name", fill="black") + paper.paste(label.transpose(Image.Transpose.ROTATE_90), (32, 365)) + for y in range(150, 421, 40): + draw.line((85, y, 383, y), fill="#909aa2") + path = directory / "coursework.png" + paper.save(path) + + body = ["观察云层", "记录风向"] + course, name = "电磁学", "林舟" + saved = (await call( + client, "save_section", markdown="\n\n".join([*body, course, name]), + paper_path=str(path), style={"font_size": 24, "seed": 29}, + paper_guides=[{"row": row, "left": [85, y], "right": [383, y]} + for row, y in [(0, 150), (6, 390)]], + )).structuredContent + key = {"draft_id": saved["draft_id"], "section": 1, "page": 1} + revision = saved["revision"] + + layout = (await call(client, "preview_handwriting", **key, revision=revision, + view="layout", limit=32)).structuredContent + assert layout["next_offset"] is None + glyphs = {g["text"]: g for g in layout["glyphs"]} + assert set(glyphs) == set("".join([*body, course, name])) + + async def place(text, quad): + nonlocal revision + revision = (await call( + client, "adjust_glyphs", **key, expected_revision=revision, + ids=[glyphs[c]["id"] for c in text], target_quad=quad, + )).structuredContent["revision"] + + # Leave the two body lines on their guides. Relocate only the field values. + header = (97, 54, 164, 80) + await place(course, corners(header)) + horizontal = finished_image(await call(client, "preview_handwriting", **key, revision=revision)) + pts = [p for c in name for p in glyphs[c]["photo_quad"]] + xs, ys = zip(*pts) + source = (min(xs), min(ys), max(xs), max(ys)) + reference = ink_mask(paper.crop(source), horizontal.crop(source)) + side = (33, 342 - reference.width, 33 + reference.height, 342) + tl, tr, br, bl = corners(side) + await place(name, [bl, tl, tr, br]) + + # Check the final raster independently of the geometry the server reports. + final = finished_image(await call(client, "preview_handwriting", **key, revision=revision)) + ink = ink_mask(paper, final) + observed = ink.crop(side).transpose(Image.Transpose.ROTATE_270) + overlap = ImageChops.darker(reference, observed).histogram()[255] + union = ImageChops.lighter(reference, observed).histogram()[255] + assert union > 0 and overlap / union > 0.80, (overlap, union) + + rows = [(84, 120, 205, 159), (84, 160, 205, 199)] + for field, text in [(header, course), *zip(rows, body, strict=True)]: + selected = (await call(client, "preview_handwriting", **key, revision=revision, + view="layout", region=corners(field))).structuredContent + by_x = sorted(selected["glyphs"], key=lambda g: g["selected_center"][0]) + assert "".join(g["text"] for g in by_x) == text + for glyph in by_x: + xs, ys = zip(*glyph.get("current_photo_quad", glyph["photo_quad"])) + assert ink.crop((min(xs), min(ys), max(xs), max(ys))).getbbox(), glyph["text"] + # Every pixel outside the designated fields, including the printed name, + # title, score box and all other rules, must survive untouched. + diff = ImageChops.difference(paper, final) + for box in [header, side, *rows]: + diff.paste((0, 0, 0), box) + assert diff.getbbox() is None, diff.getbbox() + review = (await call(client, "preview_handwriting", **key, revision=revision, + view="review")).structuredContent + assert review["evidence"]["changed_pixels_outside_reference"] > 0 diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 9496b38a..9e077fc9 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -17,6 +17,7 @@ from PIL import Image +import coursework_form import review_comparison from mcp_client import call @@ -154,6 +155,11 @@ async def smoke(command, arguments, out): async with stdio_client(params) as streams, ClientSession(*streams) as client: info = await client.initialize() assert info.serverInfo.name == "panache-mcp" + # These branches guide the client before a draft exists, including on ruled paper. + before_save, _, _ = info.instructions.partition("save_section(") + 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 tools = await client.list_tools() assert {t.name for t in tools.tools} == { "annotate_review", @@ -259,6 +265,7 @@ async def smoke(command, arguments, out): ) assert failed.isError 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) # Keep the traditional eight verse lines for a single folio. poem = POEM.replace(",", ",\n") From 8ae00c9ce58aa2aa3d7611387b56a471bec0c356 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 20:17:13 +0800 Subject: [PATCH 20/24] =?UTF-8?q?fix(crates/panache-mcp):=20=E6=8C=87?= =?UTF-8?q?=E6=98=8E=E8=A3=81=E7=89=87=E9=A6=96=E8=A1=8C=E5=9F=BA=E7=BA=BF?= =?UTF-8?q?=E9=9C=80=E8=A6=81=E7=9A=84=E7=95=99=E7=99=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:同一张正文裁片的两个独立会话均因第一条点线靠近图片上缘,首次提交的基线数组被拒。 解决手段:在参考线参数中公开首行约束,区分行距错误和上缘不足,并在上缘不足时带回实际间距和下一条可用横线的选择方法。用协议回归比较实际和所需像素。 收益:模型可以在建稿前选择合适的第一行,收到错误后也有准确的修正依据,减少盲目重试。 --- crates/panache-mcp/src/inputs.rs | 2 +- crates/panache-mcp/src/paper.rs | 8 ++++++-- crates/panache-mcp/tests/coursework_form.py | 8 ++++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 20ff8a2c..0cdf2bcc 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -69,7 +69,7 @@ pub enum PaperMode { #[derive(serde::Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Guide { - /// Zero-based writable ruling number, counted from the first supplied ruling. + /// Count writable baselines from row 0. At the image center, leave one full row interval above row 0; on a tight crop start at the next visible ruling. pub row: u16, /// Left and right endpoints [x,y] of this same baseline in original photo pixels. pub left: [u32; 2], diff --git a/crates/panache-mcp/src/paper.rs b/crates/panache-mcp/src/paper.rs index ea1f87c9..de8858b1 100644 --- a/crates/panache-mcp/src/paper.rs +++ b/crates/panache-mcp/src/paper.rs @@ -68,8 +68,12 @@ impl PaperLayout { let last_y = line(last, center); let step = (last_y - first_y) / f32::from(last.row); ensure!( - step >= 1. && first_y >= step && last_y < height as f32, - "Guides leave no room for the first or last line" + step.is_finite() && step >= 1. && last_y < height as f32, + "Supply ordered baseline rows at least one pixel apart, ending within the image" + ); + ensure!( + first_y >= step, + "Row 0 has {first_y:.1}px above it at image center; it needs one row interval ({step:.1}px). On a tight crop use the next visible ruling as row 0 and renumber the remaining guides." ); let left = guides[0].left[0]; let right = guides[0].right[0]; diff --git a/crates/panache-mcp/tests/coursework_form.py b/crates/panache-mcp/tests/coursework_form.py index ed1f10db..93393963 100644 --- a/crates/panache-mcp/tests/coursework_form.py +++ b/crates/panache-mcp/tests/coursework_form.py @@ -42,6 +42,14 @@ async def exercise(client, directory): path = directory / "coursework.png" paper.save(path) + cropped_guides = [{"row": row, "left": [85, y], "right": [383, y]} + for row, y in [(0, 12), (6, 252)]] + crowded = await client.call_tool("save_section", { + "markdown": "试填", "paper_path": str(path), "paper_guides": cropped_guides, + }) + assert crowded.isError and "12.0px" in crowded.content[0].text + assert "40.0px" in crowded.content[0].text and "next visible ruling" in crowded.content[0].text + body = ["观察云层", "记录风向"] course, name = "电磁学", "林舟" saved = (await call( From 3c6ac777d2f002d117ca46987b54fc11f453c310 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 20:52:09 +0800 Subject: [PATCH 21/24] =?UTF-8?q?feat(crates/panache-mcp):=20=E5=BC=95?= =?UTF-8?q?=E5=AF=BC=E4=BD=9C=E4=B8=9A=E5=92=8C=E5=AE=9E=E9=AA=8C=E6=8A=A5?= =?UTF-8?q?=E5=91=8A=E5=85=88=E6=A0=B8=E5=AF=B9=E6=B7=B7=E6=8E=92=E7=AC=94?= =?UTF-8?q?=E8=BF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:实拍作业样张中的中文、英文和数字均来自李国夫手写体。此前工具只列出字体名,模型容易另配西文字体,看不出用户想要的同一套快写笔迹。 解决手段:在 MCP 初始化与字体清单中披露混排审样流程,在 typography 目录说明西文字体、数字和比例的继承与复位。偏好未定时展示实际纸面上的短样并征求意见,已确认或委托选字时直接继续。用 stdio 测试在同一稿中切换西文覆盖再恢复主字体。 收益:陌生客户端能在整页排版前给出有依据的建议。回归验证恢复默认参数后,中英数试样与最初的主字体预览逐像素一致。 --- crates/panache-mcp/README.md | 2 +- crates/panache-mcp/src/controls.json | 6 +++--- crates/panache-mcp/src/main.rs | 16 +++++++++++++--- crates/panache-mcp/tests/smoke.py | 22 ++++++++++++++++++++-- crates/panache-mcp/tool-design.md | 2 ++ 5 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index ccd58ee2..0650a40f 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -52,7 +52,7 @@ cargo build --locked --release -p panache-mcp | 工具 | 用法 | | --- | --- | -| `list_fonts` | 列出本地可选的字体文件名。 | +| `list_fonts` | 列出本地字体。为作业、实验报告选笔迹时,指导模型展示中英数混排小样,按用户偏好定稿。 | | `save_section` | 用 `markdown` 新建稿件。首次可传标题、字体、字号、纸样、墨色、种子和作业排版模式。返回 `draft_id`、版本号和节号。 | | `list_drafts` | 找回本地稿件和最新版本。每批 20 条,可传 `offset`。 | | `read_section` | `summary` 取版本、长度和样式;默认 `excerpt` 隐去正文中已识别的内嵌图片数据;`source` 读取精确 Markdown。后两种视图按字符分页,默认 1000 字,单次最多 4000 字。 | diff --git a/crates/panache-mcp/src/controls.json b/crates/panache-mcp/src/controls.json index ecf658dc..4a3486f2 100644 --- a/crates/panache-mcp/src/controls.json +++ b/crates/panache-mcp/src/controls.json @@ -24,9 +24,9 @@ }, "typography": { "font": {"type":"font"}, - "latin_font": {"type":"choice","values":["handlee","patrick_hand","indie_flower","kalam","shadows_into_light"]}, - "latin_font_scale": {"type":"integer","min":50,"max":150,"unit":"%"}, - "latin_digits": {"type":"boolean"} + "latin_font": {"type":"choice","values":["handlee","patrick_hand","indie_flower","kalam","shadows_into_light"],"description":"Optional override for ASCII letters. Omit on a new draft or set to null in tune_handwriting to follow the main font, with fallback for missing glyphs."}, + "latin_font_scale": {"type":"integer","min":50,"max":150,"unit":"%","description":"Size of ASCII letters relative to the main font, also applies to digits when latin_digits is true. Reset to 100 for an unscaled sample."}, + "latin_digits": {"type":"boolean","description":"False keeps 0–9 at the main font and size. True applies the Latin size and any selected Latin font to digits."} }, "ink": { "transparent_background": {"type":"boolean","description":"Ink-only PNG preview and ZIP. PDF retains the paper."}, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 3f572aa7..be96e5c7 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -212,7 +212,7 @@ impl ServerHandler for Panache { "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. ", - "Use list_fonts for names and list_drafts to resume. A paper_path must be readable on the server computer. ", + "For mixed-script homework or lab reports, see list_fonts. Show a short mixed sample if the preferred hand is undecided. 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. ", @@ -310,7 +310,7 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "List local font filenames accepted by save_section." + description = "List local fonts accepted by save_section and how to preview a coherent Chinese, English and digit sample." )] fn list_fonts(&self) -> CallToolResult { let names = self @@ -319,7 +319,17 @@ impl Panache { .iter() .map(|name| format!("- {name}")) .collect::>(); - reply(names.join("\n"), json!({"fonts": self.0.fonts})) + let guidance = concat!( + "For homework and lab reports, start with the primary font’s own letters and digits. ", + "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 choice. For a mismatch, inspect describe_controls(group=typography) before trying a separate Latin font." + ); + reply( + format!("{}\n\n{guidance}", names.join("\n")), + json!({"fonts": self.0.fonts, "sample_guidance": guidance}), + ) } #[tool( diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 9e077fc9..51330dce 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -108,6 +108,21 @@ async def review_workflow(client, key, guides, font_path): return transparent, default, uploaded +async def mixed_script_sample(client): + saved = (await call(client, "save_section", markdown="样品 A 的质量为 12.5 g。", + style={"font": "李国夫手写体.ttf", "seed": 17})).structuredContent + key = {"draft_id": saved["draft_id"]} + primary = png(await call(client, "preview_handwriting", **key)) + override = {"latin_font": "kalam", "latin_digits": True, "latin_font_scale": 120} + await call(client, "tune_handwriting", **key, expected_revision=1, changes=override) + assert png(await call(client, "preview_handwriting", **key)) != primary + reset = {"latin_font": None, "latin_digits": False, "latin_font_scale": 100} + await call(client, "tune_handwriting", **key, expected_revision=2, changes=reset) + spec = (await call(client, "describe_controls", **key, group="typography")).structuredContent + assert {name: spec["values"][name] for name in reset} == reset + assert png(await call(client, "preview_handwriting", **key)) == primary + + async def placement_pixels(client): saved = (await call(client, "save_section", markdown="字", style={"seed": 17})).structuredContent key = {"draft_id": saved["draft_id"]} @@ -176,8 +191,10 @@ async def smoke(command, arguments, out): "preview_handwriting", "export_handwriting", } - fonts = (await call(client, "list_fonts")).structuredContent["fonts"] - assert "志莽行书.ttf" in fonts + listed = await call(client, "list_fonts") + guidance = listed.structuredContent["sample_guidance"] + assert guidance in listed.content[0].text + assert "志莽行书.ttf" in listed.structuredContent["fonts"] paper_path = Path(temp) / "我的 横线纸.png" shutil.copyfile( Path(__file__).parent / "fixtures" / "ruled.png", paper_path @@ -264,6 +281,7 @@ async def smoke(command, arguments, out): "save_section", {"markdown": "missing", "paper_path": str(paper_path)} ) assert failed.isError + await mixed_script_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) diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index 04ae7737..314c1464 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -6,6 +6,8 @@ Panache 在 `tools/list` 中公布十三个任务入口。模型可以直接保 客户端负责启动 stdio 程序、把工具提供给模型,并决定将返回的文本、结构化数据和图片交给谁。首次可调用 `list_fonts` 验证连接,再用 `save_section` 创建一节短文,按返回版本预览。请区分用户能在聊天里看到图片与模型能读取工具图片这两种能力。模型实际收到图片时可以描述字迹和位置;只收到文字时,可以报告测量值,并请用户在预览或导出文件中确认字形、可读性和布局偏好。 +作业或实验报告混排时,先用主字体排一句真实内容,例如“样品 A 的质量为 12.5 g”。在目标纸面和字号下看笔画粗细、倾斜、英文字高与数字辨识度。风格还没定时,把混排预览给用户,说明推荐理由,再问“这种笔迹可以用在整份报告里吗?”用户已选定字体或委托选字时直接依约排版。已有稿件可用 `describe_controls(group="typography")` 查看当前设置;要恢复主字体原本的英数比例,可用 `tune_handwriting` 传 `changes: {"latin_font": null, "latin_digits": false, "latin_font_scale": 100}`。缺字可能触发字体回退,仍以实际预览为准。 + MCP 的工具列表支持分页。客户端可能取完所有页;分页能控制单次协议响应大小。Claude 的 Tool Search 支持宿主配置延迟加载,实际进入模型上下文的工具由宿主决定。Panache 的 stdio 客户端也可以完全不提供搜索,只用标准工具列表和调用接口。项目目前选择按需查询参数,避免为小型目录引入搜索索引和额外的调用步骤。设计依据见 [MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)、[MCP 路线图中的渐进发现](https://blog.modelcontextprotocol.io/posts/mcp-roadmap/) 和 [Claude Tool Search 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)。 ## 一次调整 From 35092fa0918037f22f984b0726da6df95a8b90ea Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 21:00:07 +0800 Subject: [PATCH 22/24] =?UTF-8?q?fix(crates/panache-mcp):=20=E6=98=8E?= =?UTF-8?q?=E7=A4=BA=E8=8B=B1=E6=95=B0=E9=BB=98=E8=AE=A4=E8=B7=9F=E9=9A=8F?= =?UTF-8?q?=E4=B8=BB=E5=AD=97=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:字体目录此前只列出五种西文字体,模型可能误解为必选。用户希望作业的中英数笔迹自然一致,并保留在指定风格或表达不满时单独调整的能力。 解决手段:在初始化、主字体字段和选字入口说明省略西文设置的用法,在字体目录公开继承选项及引擎实际默认值。stdio 回归对照新稿默认值、无关调参后的既有覆盖及复原后的预览。 收益:模型可直接用主字体排英文和数字,减少无依据的调参,也能在继续编辑旧稿时保留用户选定的西文字体。 --- crates/panache-mcp/src/controls.json | 6 +++--- crates/panache-mcp/src/inputs.rs | 2 +- crates/panache-mcp/src/main.rs | 6 +++--- crates/panache-mcp/tests/smoke.py | 14 +++++++++++--- crates/panache-mcp/tool-design.md | 2 +- 5 files changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/panache-mcp/src/controls.json b/crates/panache-mcp/src/controls.json index 4a3486f2..5c3e7365 100644 --- a/crates/panache-mcp/src/controls.json +++ b/crates/panache-mcp/src/controls.json @@ -24,9 +24,9 @@ }, "typography": { "font": {"type":"font"}, - "latin_font": {"type":"choice","values":["handlee","patrick_hand","indie_flower","kalam","shadows_into_light"],"description":"Optional override for ASCII letters. Omit on a new draft or set to null in tune_handwriting to follow the main font, with fallback for missing glyphs."}, - "latin_font_scale": {"type":"integer","min":50,"max":150,"unit":"%","description":"Size of ASCII letters relative to the main font, also applies to digits when latin_digits is true. Reset to 100 for an unscaled sample."}, - "latin_digits": {"type":"boolean","description":"False keeps 0–9 at the main font and size. True applies the Latin size and any selected Latin font to digits."} + "latin_font": {"type":"choice","default":null,"values":[null,"handlee","patrick_hand","indie_flower","kalam","shadows_into_light"],"description":"Default: follow the main font for ASCII letters, with fallback for missing glyphs. Leave unset unless the user asks for a separate English hand or dislikes the lettering. In an existing draft, omitting this key keeps its current value; null clears the override."}, + "latin_font_scale": {"type":"integer","min":50,"max":150,"unit":"%","default":100,"description":"Size of ASCII letters relative to the main font, also applies to digits when latin_digits is true. Reset to 100 for an unscaled sample."}, + "latin_digits": {"type":"boolean","default":false,"description":"Leave unset on new drafts. False keeps 0–9 at the main font and size. True applies the Latin size and any selected Latin font to digits."} }, "ink": { "transparent_background": {"type":"boolean","description":"Ink-only PNG preview and ZIP. PDF retains the paper."}, diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 0cdf2bcc..d93cfbc6 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -24,7 +24,7 @@ pub enum Format { #[derive(Clone, Serialize, Deserialize, JsonSchema)] #[serde(default, deny_unknown_fields)] pub struct Style { - /// Exact filename from list_fonts. + /// Main font filename from list_fonts. English letters and digits follow it by default. pub font: String, pub paper: Paper, /// RGB hex color, e.g. #302c30. diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index be96e5c7..b199d0cb 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -212,7 +212,7 @@ impl ServerHandler for Panache { "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. ", - "For mixed-script homework or lab reports, see list_fonts. Show a short mixed sample if the preferred hand is undecided. Use list_drafts to resume. A paper_path must be readable on the server computer. ", + "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. ", @@ -320,11 +320,11 @@ impl Panache { .map(|name| format!("- {name}")) .collect::>(); let guidance = concat!( - "For homework and lab reports, start with the primary font’s own letters and digits. ", + "Select only the main font for a new draft. Its letters and digits are the default, including for homework and lab reports. ", "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 choice. For a mismatch, inspect describe_controls(group=typography) before trying a separate Latin font." + "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)." ); reply( format!("{}\n\n{guidance}", names.join("\n")), diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 51330dce..6baeeb9f 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -112,14 +112,22 @@ async def mixed_script_sample(client): saved = (await call(client, "save_section", markdown="样品 A 的质量为 12.5 g。", style={"font": "李国夫手写体.ttf", "seed": 17})).structuredContent key = {"draft_id": saved["draft_id"]} + inherited = {"latin_font": None, "latin_digits": False, "latin_font_scale": 100} + initial = (await call(client, "describe_controls", **key, group="typography")).structuredContent + assert {k: initial["controls"][k]["default"] for k in inherited} == inherited + assert {k: initial["values"][k] for k in inherited} == inherited + assert None in initial["controls"]["latin_font"]["values"] primary = png(await call(client, "preview_handwriting", **key)) override = {"latin_font": "kalam", "latin_digits": True, "latin_font_scale": 120} await call(client, "tune_handwriting", **key, expected_revision=1, changes=override) assert png(await call(client, "preview_handwriting", **key)) != primary - reset = {"latin_font": None, "latin_digits": False, "latin_font_scale": 100} - await call(client, "tune_handwriting", **key, expected_revision=2, changes=reset) + await call(client, "tune_handwriting", **key, expected_revision=2, changes={"ink_opacity": 90}) + current = (await call(client, "describe_controls", **key, group="typography")).structuredContent + assert {k: current["values"][k] for k in override} == override + await call(client, "tune_handwriting", **key, expected_revision=3, + changes={**inherited, "ink_opacity": None}) spec = (await call(client, "describe_controls", **key, group="typography")).structuredContent - assert {name: spec["values"][name] for name in reset} == reset + assert {name: spec["values"][name] for name in inherited} == inherited assert png(await call(client, "preview_handwriting", **key)) == primary diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index 314c1464..f6c9197d 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -6,7 +6,7 @@ Panache 在 `tools/list` 中公布十三个任务入口。模型可以直接保 客户端负责启动 stdio 程序、把工具提供给模型,并决定将返回的文本、结构化数据和图片交给谁。首次可调用 `list_fonts` 验证连接,再用 `save_section` 创建一节短文,按返回版本预览。请区分用户能在聊天里看到图片与模型能读取工具图片这两种能力。模型实际收到图片时可以描述字迹和位置;只收到文字时,可以报告测量值,并请用户在预览或导出文件中确认字形、可读性和布局偏好。 -作业或实验报告混排时,先用主字体排一句真实内容,例如“样品 A 的质量为 12.5 g”。在目标纸面和字号下看笔画粗细、倾斜、英文字高与数字辨识度。风格还没定时,把混排预览给用户,说明推荐理由,再问“这种笔迹可以用在整份报告里吗?”用户已选定字体或委托选字时直接依约排版。已有稿件可用 `describe_controls(group="typography")` 查看当前设置;要恢复主字体原本的英数比例,可用 `tune_handwriting` 传 `changes: {"latin_font": null, "latin_digits": false, "latin_font_scale": 100}`。缺字可能触发字体回退,仍以实际预览为准。 +新稿选定主字体后省略西文字体、数字字体和字号比例。用户希望整体更潦草时,优先换主字体,保持整套笔迹协调。只有用户单独指定英数风格,或表示对其中一类的效果不满意,才考虑调整对应项。已有稿件省略参数会保留现值。作业或实验报告混排时,先用主字体排一句真实内容,例如“样品 A 的质量为 12.5 g”。在目标纸面和字号下看笔画粗细、倾斜、英文字高与数字辨识度。风格还没定时,把混排预览给用户,说明推荐理由,再问“这种笔迹可以用在整份报告里吗?”用户已选定字体或委托选字时直接依约排版。已有稿件可用 `describe_controls(group="typography")` 查看当前设置;要恢复主字体原本的英数比例,可用 `tune_handwriting` 传 `changes: {"latin_font": null, "latin_digits": false, "latin_font_scale": 100}`。缺字可能触发字体回退,仍以实际预览为准。 MCP 的工具列表支持分页。客户端可能取完所有页;分页能控制单次协议响应大小。Claude 的 Tool Search 支持宿主配置延迟加载,实际进入模型上下文的工具由宿主决定。Panache 的 stdio 客户端也可以完全不提供搜索,只用标准工具列表和调用接口。项目目前选择按需查询参数,避免为小型目录引入搜索索引和额外的调用步骤。设计依据见 [MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)、[MCP 路线图中的渐进发现](https://blog.modelcontextprotocol.io/posts/mcp-roadmap/) 和 [Claude Tool Search 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)。 From 393a34dddcf0d101c852da845e452d392a5bf04b Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 21:34:03 +0800 Subject: [PATCH 23/24] =?UTF-8?q?docs(crates/panache-mcp):=20=E6=8C=89?= =?UTF-8?q?=E5=AE=9E=E9=99=85=E6=94=B9=E7=A8=BF=E6=AD=A5=E9=AA=A4=E9=87=8D?= =?UTF-8?q?=E5=86=99=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=8C=87=E5=8D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:原指南将工具参数、视觉判断和存储实现放在一起,读者容易混淆布局查询、整页复盘和版本对比,也容易把响应字节数误认为模型 token。 解决手段:用混排试字和沿线移动单字贯穿示例,按使用目的列出参数和返回结果,将测量与存储细节折叠。保留局部复查示例的既有链接入口。 收益:客户端开发者能按任务选择调用,区分可自动检查的像素变化与需要人看图判断的效果,并用同一口径核对上下文开销。 --- crates/panache-mcp/tool-design.md | 123 ++++++++++++++++-------------- 1 file changed, 67 insertions(+), 56 deletions(-) diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index f6c9197d..bb97c194 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -1,77 +1,67 @@ -# AI 客户端如何调整手稿 +# 用 Panache MCP 排版和检查手稿 -## 工具发现 +假设用户发来一张斜拍的实验报告纸,希望把记录写在横线上,英文和数字也像同一个人写的。第一次接入 Panache 的客户端需要完成三件事:找到能写的位置,选好笔迹,确认导出的那一版确实符合要求。这份指南按这个顺序介绍该用哪个工具、该看返回结果中的什么内容。 -Panache 在 `tools/list` 中公布十三个任务入口。模型可以直接保存、预览、导出;只有需要调参时才调用 `describe_controls`。目录按排版、字体、墨迹、扰动、删除线和拍摄信息六组组织,和服务端参数校验共用同一份定义。 +## 从一行字开始 -客户端负责启动 stdio 程序、把工具提供给模型,并决定将返回的文本、结构化数据和图片交给谁。首次可调用 `list_fonts` 验证连接,再用 `save_section` 创建一节短文,按返回版本预览。请区分用户能在聊天里看到图片与模型能读取工具图片这两种能力。模型实际收到图片时可以描述字迹和位置;只收到文字时,可以报告测量值,并请用户在预览或导出文件中确认字形、可读性和布局偏好。 +在 AI 客户端登记 Panache 的 stdio 配置后,调用 `list_fonts`。能列出本机字体,就可以试写第一行。用 `save_section` 传入 Markdown,记下返回的 `draft_id` 和 `revision`,再用这两个值调用 `preview_handwriting`。**省略预览的 `view` 时,返回这版手稿的单页 PNG。** 指定节和页时从 1 开始计数。 -新稿选定主字体后省略西文字体、数字字体和字号比例。用户希望整体更潦草时,优先换主字体,保持整套笔迹协调。只有用户单独指定英数风格,或表示对其中一类的效果不满意,才考虑调整对应项。已有稿件省略参数会保留现值。作业或实验报告混排时,先用主字体排一句真实内容,例如“样品 A 的质量为 12.5 g”。在目标纸面和字号下看笔画粗细、倾斜、英文字高与数字辨识度。风格还没定时,把混排预览给用户,说明推荐理由,再问“这种笔迹可以用在整份报告里吗?”用户已选定字体或委托选字时直接依约排版。已有稿件可用 `describe_controls(group="typography")` 查看当前设置;要恢复主字体原本的英数比例,可用 `tune_handwriting` 传 `changes: {"latin_font": null, "latin_digits": false, "latin_font_scale": 100}`。缺字可能触发字体回退,仍以实际预览为准。 +作业或实验报告适合直接拿一句正文试字,比如“样品 A 的质量为 12.5 g”。新稿只选主字体,英文和数字默认跟随它。如果用户想要整体再潦草一些,先换主字体。在目标纸张和字号下看看:中文和英文的笔画粗细是否协调?`12.5` 和单位能否一眼辨认?风格未定时,把小样给用户看,说清推荐理由,再问“这种笔迹可以用在整份报告里吗?”用户已经定好或委托选字时,就继续排版。 -MCP 的工具列表支持分页。客户端可能取完所有页;分页能控制单次协议响应大小。Claude 的 Tool Search 支持宿主配置延迟加载,实际进入模型上下文的工具由宿主决定。Panache 的 stdio 客户端也可以完全不提供搜索,只用标准工具列表和调用接口。项目目前选择按需查询参数,避免为小型目录引入搜索索引和额外的调用步骤。设计依据见 [MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)、[MCP 路线图中的渐进发现](https://blog.modelcontextprotocol.io/posts/mcp-roadmap/) 和 [Claude Tool Search 文档](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)。 +只有用户对英文或数字单独提出要求,才需要查 `describe_controls(group="typography", draft_id=…)`。编辑旧稿时,省略参数会保留原设置。要撤销以前的西文字体和缩放,可以给 `tune_handwriting` 传这组 `changes`: -## 一次调整 - -假设要把墨色调淡,再把第二页的一处字迹右移。如果有稿件 ID,只需要保存 ID、当前版本和相关节号;省略 ID 时可以用 `list_drafts` 找回稿件。以下调用中的版本号用于示例,实际应使用工具返回的版本。 - -| 调用 | 参数示例 | 模型拿到的结果 | -| --- | --- | --- | -| `describe_controls` | `{"group":"ink","draft_id":"…","revision":5}` | 墨迹控件的类型、范围、单位和该稿当前值 | -| `tune_handwriting` | `{"draft_id":"…","expected_revision":5,"changes":{"ink_opacity":85}}` | 新版本 6 | -| `preview_handwriting` | `{"draft_id":"…","revision":6,"section":1,"page":2,"view":"layout","limit":12}` | 原始字框、编号、已有调整和下一批偏移量 | -| `adjust_glyphs` | `{"draft_id":"…","expected_revision":6,"section":1,"page":2,"ids":[37],"dx":4}` | 新版本 7;示例编号 37 须替换为本页实际编号 | -| `preview_handwriting` | `{"draft_id":"…","revision":7,"section":1,"page":2}` | 单页 PNG | -| `export_handwriting` | `{"draft_id":"…","revision":7,"format":"pdf"}` | 整稿 PDF 的本机路径和页数 | - -字号、行距和页边距以纸张原始像素为单位。照片底纸采用识别后的画布尺寸;边距和行距可手动微调。所有参数先合并再校验,因此可以在同一补丁里同时增加字号和行距。位移相对原始字框,`dx:4` 表示向右 4 px;后续只传 `dy` 会保留原有 `dx`。精修还支持缩放、旋转和浓度。字框为 `[x,y,width,height]`。遇到公式、插图或归一化导致源码无法准确对应时,模型可以结合可视预览和坐标定位。 - -全文样式变更后要重新定位字形;改写一节会让该节的旧字形调整只在旧版本生效。在其他节追加文字可以继续复用原节的调整。并发写入出现版本冲突时,先读取最新摘要,再决定是否重做补丁。MCP 还可以用 `shape` 对选中字形做剪切或梯形变换。也可对选中字形指定局部墨色。 - -## 插图墨迹 +```json +{"latin_font": null, "latin_digits": false, "latin_font_scale": 100} +``` -在 `preview_handwriting(view="layout", illustrations_only=true)` 查询本页插图。结果中同一 `illustration_id` 下,`illustration` 表示框线、箭头等剩余笔迹,`illustration_detail` 表示可独立选择的连通笔迹区域。用坐标与单页图像对应标签。改变整个图的墨迹时,把同组编号放进同一次调用,每图最多 32 项。 +主字体缺字时,引擎可能使用备用字体,最后以实际成图为准。客户端决定是否将工具图片传给模型。如果用户能看图、模型只收到文字,模型可以报告坐标和测量结果,再请用户确认笔迹的观感。 -例如对一个标签调用 `adjust_glyphs`,传 `thickness: 0.5` 增加 0.5 px 笔画粗细,也可同时传 `softness: 0.2`、`opacity: 85` 或 `color: "#304458"`。粗细和柔化以 0.1 px 为单位;归零恢复原始插图笔迹,墨色用 `inherit` 恢复。图内文字来自导入的像素;标签与框线粘连、笔迹太密时,会保留为整体。 +## 一次改稿需要哪些调用? -## 照片和纸面坐标 +以“把整稿墨色调淡,再把第二页的‘还’沿横线往右挪一点”为例。下表假设当前稿件为 v5,目标在第 1 节第 2 页。实际调用应使用服务端返回的版本号和字形 ID。 -导入 `paper_path` 时,默认 `paper_mode="photo"` 在原照片上合成笔迹和插图。`flatten` 保存校平后的底纸。建稿结果返回尺寸、边距、行距和识别方式。没有识别到可靠横线时返回 `alignment="unverified"` 和 `placement_guidance`。如果无横线纸或画作上的落字位置不明确,直接问用户想写在哪里或哪些内容需要留白。把指定区域映射成 `paper_guides` 就能在同稿上继续;用户委托选位时可先给预览。 +| 目的 | 调用与关键参数 | 看什么 | +| --- | --- | --- | +| 查这份稿的墨色 | `describe_controls(group="ink", draft_id=…, revision=5)` | 找到 `ink_opacity` 的当前值和范围。 | +| 调淡整稿 | `tune_handwriting(draft_id=…, expected_revision=5, changes={"ink_opacity":85})` | 保存后得到 v6。单改墨迹会保留已有的局部摆放。 | +| 找到“还” | `preview_handwriting(draft_id=…, revision=6, section=1, page=2, view="layout")` | 用文字、坐标和编号定位。这里假设查到 ID 37。 | +| 移动这个字 | `adjust_glyphs(draft_id=…, expected_revision=6, section=1, page=2, ids=[37], dx=4)` | 得到 v7。位移相对原始字框;以后只改 `dy`,会保留这次的 `dx`。 | +| 核对并导出 | 先在 v7 预览这一页,再用 `export_handwriting(draft_id=…, revision=7, format="pdf")` 导出 | 预览和导出指向同一版本。用户特别要求其他字保持原样时,再做下文的局部比较。 | -| 模型可以取得或指定的内容 | 对应接口 | -| --- | --- | -| 单独查看稿件底纸、或查看任意一页的成品 | `preview_handwriting(view="paper")`、`view="image"`。两者按需返回图片 | -| 照片上的字形位置与横线方向 | `view="layout"`。投影稿的 `photo_quad` 为基础字框左上、右上、右下、左下四角,`photo_baseline` 为基线两端。单位是成品照片像素。已有的单字调整另列在 `adjustment` | -| 按自己观察到的横线定位版心 | 建稿时传 `paper_guides`。每项含 `row`、`left:[x,y]`、`right:[x,y]`,坐标取自原图。第 0 行和最后一条可写行决定范围,中间可再给参考行。两行间按宽度变化插值 | -| 改一组字的局部形状 | `adjust_glyphs` 的 `dx/dy` 使用投影前的纸面坐标。`shape:{"shear_degrees":4,"top_width_percent":94}` 让字底向右倾并略微收窄字顶。`{"shear_degrees":0,"top_width_percent":100}` 恢复默认形状 | +换字体、改字号或重设参考线,都可能让正文重新排版。这时应从新版重新找字。改写某一节后,该节原有的单字调整仍可在旧版本中查看;追加其他节时可以复用原节调整。如果需要更换本机字体,可用 `tune_handwriting(font_path=…)` 导入 TTF 或 OTF,字体会随稿保留。如果另一位客户端先保存了,先读最新摘要,确认目标仍在,再提交修改。局部图文较复杂时,可结合预览和字框定位公式、插图或经过排版转换的文字。 -整页投影已经包含纸面的斜度和远近变化。局部形变叠加在纸面投影之前。选择检查哪页、是否精修,由客户端根据图像决定。 +如果要交付只有笔迹的 PNG,可在墨迹组开启 `transparent_background`,再导出 ZIP;同稿导出 PDF 时会保留底纸。导出结果会说明当前版本哪些页已有整页复盘记录。 -## 控制进入模型的内容 +## 在照片上找到正确的位置 -- 续接工作时,先用 `read_section(view="summary")` 查版本和长度。默认摘录保留图片说明,用 `attachment` 代替识别到的内嵌图片 URI。摘录的分页偏移针对摘录视图;精确恢复和改写正文应分页取 `view="source"`。后者可能包含原始图片数据。摘录不能作为原文覆盖保存。 -- 参数目录按组返回。图片路径在建稿时由调用方提供;纸张快照和数据库保存在服务端。导出工具返回本机路径,客户端需要访问同一文件系统才能打开。 -- 几何视图每批默认 12 个字形,上限 32,不传 PNG 或字形蒙版图集。查看第 N 页仍需从该节开头排到第 N 页。真正需要目测字迹时,再显式取图片视图。 -- 客户端应把稿件、标题及工具响应中的用户文字作为数据处理。宿主负责选择工具、执行权限和会话历史。减少默认输出能节约上下文;明确请求原文、图片或路径的客户端仍能取得相应数据。 +建稿时传入服务端能读取的 `paper_path`。默认的 `paper_mode="photo"` 在原照片上写字,保留拍照时的透视;`flatten` 使用校平后的底纸。先看返回的画布尺寸、边距、行距和横线识别结果,再决定是否需要手动校准。 -## 复盘证据与版本轨迹 +- **有清楚的横线,但字没贴上去。** 在同一份稿上用 `tune_handwriting(paper_guides=…)` 指出第一条和最后一条可写基线,必要时补中间几行。每条包含行号 `row` 和原图上的两个端点 `left:[x,y]`、`right:[x,y]`,首行编号为 0。两个端点沿纸纹取,即使横线在照片里向上斜,也能给模型一个明确的书写方向。传空数组可恢复建稿时的校准。 +- **没有横线,或者纸上有画。** `alignment="unverified"` 表示没找到可靠横线。用户已指定右下角或委托选位时,可以在该区域试排。左右都有空白、位置会影响画面时,再问用户想写在哪、哪里要留白。若任务要求填写表头,但表头被裁掉或遮住了,先请用户补拍,或确认只写可见部分。 +- **只需调一块文字。** 在 `view="layout"` 中用原图像素圈选字形中心。投影稿的 `photo_quad` 给出原始字框的左上、右上、右下、左下四角,`photo_baseline` 给出原始基线两端,已有调整另列。要把一组字挪到图中的某点,用 `place_center`;要贴合斜栏或转向侧栏,用 `target_quad` 指定目标四角。只需相对移动时用 `dx/dy`,它们的单位是投影前的纸面像素。纸面上水平移动,在照片上可能同时改变 x 和 y。 -`view="review"` 按需返回三张按相同比例缩放的图片。橙色边界和青色参考线来自书写区估计,叠图可与裸底纸对照。在原分辨率比较显示在纸上的墨迹和底纸,按图像上中下三等分统计 RGB 任一通道变化至少 8 级的像素及落在参考区外的数量。在抽样字形调整后的基线中点附近搜索底纸的局部暗线并报告垂直偏差中位数和支持样本数;校徽或背景纹理也可能给出暗线,无足够对比时返回空值。短文自然可能只覆盖上部。对有正文的页面,零像素变化是重新检查的明确信号。没有自动审美评分,验收时仍要查看原图,必要时请用户指出具体位置。 +局部 `shape` 也在纸面投影之前生效。比如 `{"shear_degrees":4,"top_width_percent":94}` 会让字底向右倾,字顶略窄;设回 0 度和 100% 就还原。字号、行距和边距同样按纸面像素指定,可以在一次修改里一起调整。 -照片整页复查单独返回 `photo_appearance`。若页内有抽样文字基线,`preview_arguments` 可直接传给 `preview_handwriting`,取得当前节、页、版本的同位置原像素裁图。示例区域围绕一条抽样基线,用户关心其他区域时换用对应的 `region`。局部裁图让视觉客户端对照附近实际印字、横线或纸面,分别判断墨色、边缘和相对字号;没有参照物时可结合用户反馈。提示与示例区域只随本次复查返回,历史记录仍只保存原有测量。 +**如果要改的是插图**,给布局预览加上 `illustrations_only=true`。同一个 `illustration_id` 下,`illustration` 是框线、箭头等主体,`illustration_detail` 是能单独选中的笔迹。要把某个标签写粗一点,可对它的 ID 用 `adjust_glyphs(thickness=0.5)`;还可调 `softness`、`opacity` 或 `color`。粗细与柔化以 0.1 px 为步长,归零恢复原效果,颜色用 `inherit` 恢复。每次最多选 32 个 ID。标签若与框线连成一片,工具只能把这片笔迹作为整体处理。 -轨迹按稿件和版本保存在本机。修改操作与简短备注在同一事务提交,复盘按稿件版本、节页、测量算法版本及成品像素摘要去重。像素摘要为 SHA-256,输入依次是两个小端 u32 宽高和导出预览的原始 RGBA8 字节,在透明墨迹叠回纸张前计算。算法或成品变化产生新 ID,旧库迁移保留原证据并将未知来源字段置空。导出按不同节页计数,并取每页最近归档的测量。改变测量口径时应提升算法版本。查询不会返回原文、字体数据、图片字节或完整对话。这里的轨迹指已执行的动作和可复查的结果。模型可以对照前后版本调整下一步;没有修改模型权重或自动跨用户积累经验。 +## 排好了,怎样验收? -省略 `region` 的版本比较仅返回数据,取同一节页两版最近归档的复盘及各自最近 50 条署名反馈。精确 ID 可用来回查对比时所用的观察,更早的反馈也可在轨迹中分页查找。页面成员摘要绑定不可变节版本和该页所有字形的源位置;重新保存该节可能保守地中止定量比较。分区至少在两侧各有 3 个暗线支持样本才返回中位偏差的差值,这是最低报告门槛。它不能证明两组样本完全相同或有统计显著性。越界像素相对各版本自己的书写区计算。 +先想清楚用户要确认什么。整页有没有字,只动了一个字,下一轮要接着哪一版改,这三种问题需要的证据不同。 -反馈是调用方标注来源的本稿记录。`user_quote` 应逐字引用人的意见,`model_observation` 用于模型自己的观察。历史编辑备注的作者无法追溯时仍归为编辑上下文。若一轮同时改了墨迹与参考线,对比列出操作和观测结果,具体因果与偏好留给复核者判断。 +| 想确认的事 | `preview_handwriting` 的参数 | 返回内容 | +| --- | --- | --- | +| 这页写在哪、是否看得见 | `view="review"` | 当前版的底纸、成品和参考线叠图,以及整页测量和 `review_id`。 | +| 这个字的墨色是否和照片协调 | `view="review", region=…` | 同一位置的底纸和当前成品两张裁图。照片整页复盘若给出 `photo_appearance.preview_arguments`,可以直接用它取得建议的局部。 | +| 两版在这块地方有何区别 | `view="review", region=…, compare_revision=…` | 底纸、改前、改后三张裁图。移动了内容时,用 `previous_region` 补上旧位置。 | +| 已经看过两版,只想读记录 | `view="review", compare_revision=…`,省略区域 | 读取两版已保存的测量、评语和期间的修改,只返回数据。某版缺记录时,先对该版做一次整页复盘。 | -该设计借鉴了 Reflexion 将任务反馈留给下一次尝试的做法。关于模型仅靠自我判断纠错的研究使用的是推理任务,本项目将其作为设计动机。[Reflexion(NeurIPS 2023)](https://proceedings.neurips.cc/paper/2023/hash/1b44b878bb782e6954cd888628510e90-Abstract-Conference.html) · [外部反馈与自我纠错(ICLR 2024)](https://proceedings.iclr.cc/paper_files/paper/2024/hash/8b4add8b0aa8749d80a34ca5d941c355-Abstract-Conference.html) +整页叠图中的橙线标出估计书写区,青线标出参考线。服务端在原尺寸像素上比较成品与底纸:任一可见 RGB 通道相差至少 8 级,就计为可见变化。它按页面上、中、下三区报告数量,也统计参考区外的变化。有正文却整页零变化,应检查墨迹透明度和落字位置。表头或侧栏可能本来就要写,看到区外计数时要回看用户指定的栏位。 -SICA 将历次尝试及其评估结果放入档案,供下一轮决策参考。本工具采用了可按版本取回结果的做法,作用域限于当前稿件,修改对象是稿件与排版参数。[SICA 作者实现](https://github.com/MaximeRobeyns/self_improving_coding_agent) +要判断是否贴线,看有多少个字形基线采样点能在附近找到可信的底纸暗线,以及垂直偏差的中位数。没找到足够对比时会返回空值,纹理或校徽也可能被当作暗线。至于字迹像不像写在这张纸上,应放大笔画,对照旁边的印字、纸纹和焦点,再看粗细、边缘和字号。 -## 局部改动的复查 +### 局部改动的复查 -例如把一行字向右移后,可以在 `preview_handwriting` 中圈出新旧位置。以下坐标仅作示例,实际请从该页预览和 `view="layout"` 取得。 +例如要确认“还”移动后,旧处干净、新处有字、校名没动。下面比较第 1 节第 1 页的 v3 和 v4;两个区域应换成实际测得的坐标。 ```json { @@ -82,19 +72,40 @@ SICA 将历次尝试及其评估结果放入档案,供下一轮决策参考。 } ``` -坐标使用原尺寸成品的像素边界,左上为原点,向右、向下为正。用 3 至 32 个顶点围成无自交的多边形,无需重复首点。返回的 `crop_bounds=[x,y,width,height]` 覆盖所有指定区域,`crop_image_size` 给出实际返回的裁图尺寸,最长边为 900 像素。按相同范围依次查看底纸、改前和改后图;只检查当前版时省略 `compare_revision` 和 `previous_region`,返回底纸和当前成品两张图。 +1. **先看两个位置。** `region` 圈新位置,`previous_region` 圈旧位置。多边形用原尺寸成品像素,原点在左上,向右、向下为正。每区用 3 至 32 个顶点,不自交,不用重复首点。裁图的 `crop_bounds` 是原图上的 `[x,y,width,height]`,返回图的尺寸见 `crop_image_size`,最长边最多 900 px。 +2. **再查其他地方。** 对比两版的 `ink_pixels`,看旧区还剩多少墨迹、新区是否出现笔画。`difference.outside_union_changed_pixels` 统计整页中两区以外达到同一阈值的变化。图文重叠时会一起计数,可另圈校名单独查。阈值下计数为零仍允许细微色差;如果用户要求逐像素相同,应比较原尺寸导出图。 +3. **解释意外变化。** `render_mode_change` 表示两版用了不同的笔迹渲染方式。普通文本首次精修时可能切换到逐字生成,连未选中的字也略有变化。投影照片从建稿时就使用逐字渲染。若保护区确有变化,应说明位置和程度;底纸、尺寸或页面内容变了,则分开检查两版。 + +### 下一轮怎样接着改? + +`read_section(view="trajectory")` 按版本列出修改、简短理由和逐页复盘。比如用户说“留 v3 的墨色,用 v4 的位置”,可用 `annotate_review` 将原话挂到对应的 `review_id`,来源填 `user_quote`;模型自己看到“旧位置还有墨迹”,来源填 `model_observation`。下次可以按 ID 取回当时的记录,或按版本重新出图。局部复查即时渲染,要保存一条可引用的记录,需要做整页复盘。 + +
+实现客户端时,怎样解释两版测量的差值? + +本机 SQLite 按稿件版本、节页、算法版本和成品像素摘要复用相同的观察。摘要使用 SHA-256,依次输入小端 u32 宽、高及原始 RGBA8 像素;透明预览在叠回纸张前计算。算法或像素改变后会产生新的复盘 ID,迁移旧记录时会保留测量并留空未知字段。轨迹存的是本稿的动作和结果,无须保存整段对话或每轮整页图片。 -看 `before`、`after` 中各区域的 `ink_pixels`,可核对新位置是否出现墨迹、旧位置是否仍有笔画。底纸与成品任一可见 RGB 通道相差至少 8 级就计入墨迹。两版间也用这个阈值比较,`difference.outside_union_changed_pixels` 涵盖整页中两个区域并集之外的变动。重叠的图文都会计入,可把需要保护的标题或框线单独圈出再比较。若纸张像素、输出尺寸或页面内容已改变,分别检查各版本。局部复查即时渲染;要保存整页复盘或引用 `review_id` 时,另取一次不带区域的 `view="review"`。 +两版比较会取同一节页最近归档的观察,每版最多带回最近 50 条署名反馈,更早的可在轨迹中分页查找。页面成员摘要包含节版本和字形来源位置;重新保存正文后,即使页码相同,也可能无法量化比较。分区两侧各至少有 3 个暗线样本才报告偏差之差。参考区外的像素数以各版自己的书写区为准。如果同时改了字体、墨色和参考线,应结合成图判断原因,单项差值不足以解释观感变化。 -局部比较若出现 `render_mode_change`,表示两次生成实际使用了不同的墨迹渲染方式。普通文本首次精修可能切换为逐字生成笔画扰动,使其他字也出现像素变化。投影照片从建稿时即使用逐字渲染。涉及保护区时按实际图像和用户要求核验;要求像素保持时应披露测到的变化。 +保留每轮修改和外部反馈的做法参考了 [Reflexion](https://proceedings.neurips.cc/paper/2023/hash/1b44b878bb782e6954cd888628510e90-Abstract-Conference.html)、[SICA](https://github.com/MaximeRobeyns/self_improving_coding_agent) 和[外部反馈与自我纠错研究](https://proceedings.iclr.cc/paper_files/paper/2024/hash/8b4add8b0aa8749d80a34ca5d941c355-Abstract-Conference.html)。 -## 如何复测 +
-从仓库根目录运行下列命令。两个脚本都使用独立临时稿库。比较版本时,把相同的测量脚本指向两个构建,使用相同字体与测试图片。 +## 怎样控制上下文和测量开销? + +Panache 通过 `tools/list` 提供 13 个工具。模型可以直接建稿、预览、导出。需要调参时再用 `describe_controls` 查排版、字体、墨迹、扰动、删除线或拍摄信息中的一组。客户端决定把哪些工具说明、图片和历史消息交给模型;支持分页或延迟加载的客户端可以按需取用。[MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) · [工具发现的设计背景](https://blog.modelcontextprotocol.io/posts/mcp-roadmap/) · [Claude Tool Search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) + +- **找位置**用 `preview_handwriting(view="layout")`。默认一次取 12 个字形,最多 32 个,返回坐标和编号,不传图片。指定第 N 页时,引擎仍需从该节起点排到第 N 页。 +- **接着写**先用 `list_drafts` 找回稿件,再用 `read_section(view="summary")` 读版本和长度。普通 `read_section` 默认返回摘录,用 `attachment` 替换识别到的内嵌图片数据。要改原文,分页读 `view="source"`,以该视图的偏移量续读,避免把摘录里的占位符写回正文。 +- **交付文件**时,导出返回服务端的本地路径,客户端要能访问该文件。宿主负责执行权限和会话历史,应将稿件内容和工具结果中的用户文字作为数据处理。 + +从仓库根目录运行下面两条命令,均使用独立的临时稿库。比较两个构建时,应使用相同脚本、字体和测试图片。 ```sh uv run --script crates/panache-mcp/tests/context_metrics.py target/release/panache-mcp uv run --script crates/panache-mcp/tests/smoke.py target/release/panache-mcp ``` -`context_metrics.py` 计算官方 Python SDK 返回对象重新序列化后的紧凑 UTF-8 JSON 字节数,包含文本和结构化结果。它记录工具清单、默认复查、摘要、单页图片与字框响应的大小,仅输出计数。该指标不计 JSON-RPC 外壳、宿主系统提示、缓存或模型 tokenizer,不能直接换算成模型账单。端到端测试另验证版本冲突、缓存、改稿后的编号失效、重启恢复,以及导出图像与同版预览像素一致。 +`context_metrics.py` 将 Python SDK 返回的工具清单、文本、结构化结果和图片响应重新编码成紧凑 UTF-8 JSON,报告字节数。`smoke.py` 通过真实 stdio 客户端验证改稿、版本冲突、重启恢复和导出等行为。 + +要查一次任务实际花了多少 token,应读模型客户端的用量记录,分开看未缓存输入、缓存输入和输出。一次 MCP 响应有多少字节、一次模型请求读入多少上下文、整份作业累计花多少 token,是三个不同的问题。长任务中,同一段会话历史可能随多次模型请求重复计入。 From ee1b4be72d4db069f396b9435b351d58b65b4ca5 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 21:43:34 +0800 Subject: [PATCH 24/24] =?UTF-8?q?ci(.github/workflows):=20=E7=BA=AF=20Mark?= =?UTF-8?q?down=20=E6=9B=B4=E6=96=B0=E5=A4=8D=E7=94=A8=E5=B7=B2=E9=80=9A?= =?UTF-8?q?=E8=BF=87=E7=9A=84=20PR=20=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:pull_request 路径过滤按整个 PR 的差异判断。已含 Flutter/Rust 改动的 PR 再推说明文档时,仍会重新排队多平台构建。 解决手段:统一排除普通 Markdown,保留打包所需的字体、许可证和服务包说明。同步事件只在更新范围全是说明、同一 PR 和基础 SHA 的上一版工作流成功时跳过构建。历史运行名称保存当时的基础 SHA,避免将移动后的基础分支当作已验证。新增混合改动、重命名、比较上限与失败记录的回归检查。 收益:文档 PR 可直接略过应用 CI,混合 PR 追加文档时只需轻量检查,缺少可复用记录时仍执行原有验证,手动发布质量检查保持完整。 --- .github/scripts/markdown-update.cjs | 42 ++++++++++++++++++ .github/scripts/markdown-update.test.cjs | 55 ++++++++++++++++++++++++ .github/workflows/flutter.yml | 28 ++++++++---- .github/workflows/flutter_desktop.yml | 27 +++++++----- .github/workflows/flutter_mobile.yml | 30 ++++++++----- .github/workflows/markdown-update.yml | 34 +++++++++++++++ .github/workflows/rust.yml | 31 ++++++++----- 7 files changed, 207 insertions(+), 40 deletions(-) create mode 100644 .github/scripts/markdown-update.cjs create mode 100644 .github/scripts/markdown-update.test.cjs create mode 100644 .github/workflows/markdown-update.yml diff --git a/.github/scripts/markdown-update.cjs b/.github/scripts/markdown-update.cjs new file mode 100644 index 00000000..a1c388ba --- /dev/null +++ b/.github/scripts/markdown-update.cjs @@ -0,0 +1,42 @@ +// The PR path filters see the entire PR. Here we check just the update. +module.exports = async function skipMarkdownBuild({ github, context, core }, workflow) { + const { before, pull_request: pr } = context.payload; + const { owner, repo } = context.repo; + if (!before || !pr?.head.repo?.id || context.payload.action !== "synchronize") return false; + + try { + const { data: diff } = await github.rest.repos.compareCommitsWithBasehead({ + owner, repo, basehead: `${before}...${pr.head.sha}`, per_page: 1, + }); + // GitHub returns at most 300 changed files. An incomplete list cannot justify a skip. + if (diff.status !== "ahead" || !diff.files?.length || diff.files.length >= 300) return false; + + function isDocumentation(path) { + if (!path.endsWith(".md")) return false; + if (path.startsWith("assets/licenses/") || path.startsWith("assets/font_assets/")) return false; + if (path === "deploy/rust/README.md" && workflow === "rust.yml") return false; + if (workflow !== "flutter.yml" && /^crates\/[^/]+\/licenses\//.test(path)) return false; + return true; + } + + if (!diff.files.every(file => isDocumentation(file.filename) && + (file.status !== "renamed" || (file.previous_filename && isDocumentation(file.previous_filename))))) { + return false; + } + + // pull_requests[].base.sha in the runs API can reflect the current PR base. + // The workflow's run-name records the base actually used when that run started. + const { data } = await github.rest.actions.listWorkflowRuns({ + owner, repo, workflow_id: workflow, event: "pull_request", head_sha: before, per_page: 100, + }); + const previous = data.workflow_runs.find(run => + run.display_title === `PR #${pr.number} · base ${pr.base.sha}` && + run.head_repository?.id === pr.head.repo?.id && run.head_branch === pr.head.ref); + if (previous?.status !== "completed" || previous.conclusion !== "success") return false; + core.notice(`Only Markdown documentation changed. Reusing ${previous.html_url}`); + return true; + } catch (error) { + core.warning(`Could not verify this update; running the build: ${error.message}`); + return false; + } +}; diff --git a/.github/scripts/markdown-update.test.cjs b/.github/scripts/markdown-update.test.cjs new file mode 100644 index 00000000..860a342f --- /dev/null +++ b/.github/scripts/markdown-update.test.cjs @@ -0,0 +1,55 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const skipMarkdownBuild = require("./markdown-update.cjs"); + +const pull = { number: 14, head: { sha: "new", ref: "feature", repo: { id: 1 } }, base: { sha: "main" } }; +const green = { + display_title: "PR #14 · base main", status: "completed", conclusion: "success", + head_branch: "feature", head_repository: { id: 1 }, html_url: "previous-run", +}; + +async function check({ + files = [{ filename: "app/guide.md" }], status = "ahead", runs = [green], + action = "synchronize", workflow = "rust.yml", unavailable = false, +} = {}) { + const github = { rest: { + repos: { compareCommitsWithBasehead: async ({ basehead }) => { + assert.equal(basehead, "old...new"); + if (unavailable) throw new Error("compare unavailable"); + return { data: { files, status } }; + } }, + actions: { listWorkflowRuns: async ({ head_sha, workflow_id }) => { + assert.equal(head_sha, "old"); + assert.equal(workflow_id, workflow); + return { data: { workflow_runs: runs } }; + } }, + } }; + const context = { repo: { owner: "owner", repo: "repo" }, payload: { action, before: "old", pull_request: pull } }; + return skipMarkdownBuild({ github, context, core: { notice() {}, warning() {} } }, workflow); +} + +test("ordinary Markdown can reuse a successful check on the same PR and base", async () => { + assert.equal(await check({ files: [{ filename: "README.md" }, { filename: "crates/guide.md" }] }), true); + assert.equal(await check({ files: [{ status: "renamed", filename: "new.md", previous_filename: "old.md" }] }), true); +}); + +test("mixed updates, packaged files and renames from code need a build", async () => { + for (const name of ["app/lib/main.dart", "assets/licenses/FONT-LICENSES.md", "assets/font_assets/info.md", + "crates/handwriting-core/licenses/OFL.md", "deploy/rust/README.md"]) { + assert.equal(await check({ files: [{ filename: "guide.md" }, { filename: name }] }), false, name); + } + assert.equal(await check({ files: [{ status: "renamed", filename: "guide.md", previous_filename: "src/code.rs" }] }), false); + assert.equal(await check({ files: [{ status: "renamed", filename: "guide.md", previous_filename: "deploy/rust/README.md" }] }), false); + assert.equal(await check({ files: [{ filename: "deploy/rust/README.md" }], workflow: "flutter.yml" }), true); +}); + +test("only proven checks can be reused", async () => { + for (const options of [ + { action: "opened" }, { status: "diverged" }, { files: [] }, { unavailable: true }, + { files: Array(300).fill({ filename: "guide.md" }) }, { runs: [] }, + { runs: [{ ...green, display_title: "PR #14 · base another-base" }] }, + { runs: [{ ...green, conclusion: "cancelled" }, green] }, + { runs: [{ ...green, status: "in_progress", conclusion: null }] }, + { runs: [{ ...green, head_repository: { id: 2 } }] }, + ]) assert.equal(await check(options), false); +}); diff --git a/.github/workflows/flutter.yml b/.github/workflows/flutter.yml index d2b44c51..b5d3b515 100644 --- a/.github/workflows/flutter.yml +++ b/.github/workflows/flutter.yml @@ -1,4 +1,6 @@ name: Flutter UI +run-name: >- + ${{ github.event_name == 'pull_request' && format('PR #{0} · base {1}', github.event.pull_request.number, github.event.pull_request.base.sha) || github.workflow }} permissions: contents: read @@ -16,27 +18,33 @@ on: - "scripts/tests/test_desktop_release_version.py" - "scripts/tests/test_windows_launcher.py" - "app/**" - - "!app/README.md" - - "!app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md" - "scripts/*release*.*" - - "!scripts/*release*.md" - "scripts/tests/test-flutter-release.cjs" - ".github/workflows/publish_flutter.yml" - "vendor/**" - - "!vendor/**/README.md" - - "!vendor/**/CHANGELOG.md" - - "!vendor/**/docs/**/*.md" - "assets/pubspec.yaml" - - "assets/licenses/**" - "LICENSE" - - "assets/font_assets/**" - "scripts/test-flutter-web.py" - "scripts/tests/test_flutter_web_runner.py" + - ".github/scripts/markdown-update*.cjs" + - ".github/workflows/markdown-update.yml" - ".github/workflows/flutter.yml" + - "!**/*.md" + - "assets/licenses/**" + - "assets/font_assets/**" workflow_dispatch: jobs: + markdown-update: + permissions: + actions: read + contents: read + uses: ./.github/workflows/markdown-update.yml + with: + workflow: flutter.yml desktop-updater: + needs: markdown-update + if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} name: Desktop updater (${{ matrix.os }}) timeout-minutes: 20 strategy: @@ -89,6 +97,8 @@ jobs: run: python -m unittest discover -s scripts/tests -p test_windows_launcher.py verify: + needs: markdown-update + if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -115,6 +125,8 @@ jobs: - run: node --test scripts/tests/test-flutter-release.cjs browser-persistence: + needs: markdown-update + if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} timeout-minutes: 15 strategy: fail-fast: false diff --git a/.github/workflows/flutter_desktop.yml b/.github/workflows/flutter_desktop.yml index 18345c80..acbc331e 100644 --- a/.github/workflows/flutter_desktop.yml +++ b/.github/workflows/flutter_desktop.yml @@ -1,37 +1,44 @@ name: Flutter 独立桌面客户端 +run-name: >- + ${{ github.event_name == 'pull_request' && format('PR #{0} · base {1}', github.event.pull_request.number, github.event.pull_request.base.sha) || github.workflow }} on: workflow_dispatch: pull_request: paths: - "VERSION" - "app/**" - - "!app/README.md" - - "!app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md" - "vendor/**" - - "!vendor/**/README.md" - - "!vendor/**/CHANGELOG.md" - - "!vendor/**/docs/**/*.md" - "crates/**" - - "!crates/README.md" - - "!crates/*/README.md" - - "!crates/panache-mcp/tool-design.md" - "Cargo.toml" - "Cargo.lock" - - "assets/font_assets/**" - "assets/pubspec.yaml" - - "assets/licenses/**" - "LICENSE" - "scripts/build-flutter-desktop.py" - "scripts/windows_launcher.py" - "scripts/tests/test_desktop_release_version.py" - "scripts/tests/test_windows_launcher.py" - "scripts/embed-macos-backend.sh" + - ".github/scripts/markdown-update*.cjs" + - ".github/workflows/markdown-update.yml" - ".github/workflows/flutter_desktop.yml" + - "!**/*.md" + - "assets/licenses/**" + - "assets/font_assets/**" + - "crates/*/licenses/**" env: PYTHONUTF8: "1" PYTHONIOENCODING: "utf-8" jobs: + markdown-update: + permissions: + actions: read + contents: read + uses: ./.github/workflows/markdown-update.yml + with: + workflow: flutter_desktop.yml package: + needs: markdown-update + if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} strategy: fail-fast: false matrix: diff --git a/.github/workflows/flutter_mobile.yml b/.github/workflows/flutter_mobile.yml index 169380e8..f9aa0294 100644 --- a/.github/workflows/flutter_mobile.yml +++ b/.github/workflows/flutter_mobile.yml @@ -1,4 +1,6 @@ name: Flutter Mobile +run-name: >- + ${{ github.event_name == 'pull_request' && format('PR #{0} · base {1}', github.event.pull_request.number, github.event.pull_request.base.sha) || github.workflow }} permissions: contents: read on: @@ -6,30 +8,34 @@ on: paths: - "VERSION" - "app/**" - - "!app/README.md" - - "!app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md" - "scripts/*release*.*" - - "!scripts/*release*.md" - "scripts/tests/test-flutter-release.cjs" - ".github/workflows/publish_flutter.yml" - "vendor/**" - - "!vendor/**/README.md" - - "!vendor/**/CHANGELOG.md" - - "!vendor/**/docs/**/*.md" - "crates/**" - - "!crates/README.md" - - "!crates/*/README.md" - - "!crates/panache-mcp/tool-design.md" - "Cargo.*" - "assets/pubspec.yaml" - - "assets/licenses/**" - "LICENSE" - - "assets/font_assets/**" - "scripts/build-mobile-engine.py" + - ".github/scripts/markdown-update*.cjs" + - ".github/workflows/markdown-update.yml" - ".github/workflows/flutter_mobile.yml" + - "!**/*.md" + - "assets/licenses/**" + - "assets/font_assets/**" + - "crates/*/licenses/**" workflow_dispatch: jobs: + markdown-update: + permissions: + actions: read + contents: read + uses: ./.github/workflows/markdown-update.yml + with: + workflow: flutter_mobile.yml android: + needs: markdown-update + if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} runs-on: ubuntu-latest steps: - name: Free space for Android, Rust and emulator builds @@ -71,6 +77,8 @@ jobs: name: android-release path: app/build/app/outputs/flutter-apk/app-release.apk ios: + needs: markdown-update + if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} runs-on: macos-15 steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/markdown-update.yml b/.github/workflows/markdown-update.yml new file mode 100644 index 00000000..11691a7d --- /dev/null +++ b/.github/workflows/markdown-update.yml @@ -0,0 +1,34 @@ +name: Check Markdown-only PR update +on: + workflow_call: + inputs: + workflow: + required: true + type: string + outputs: + skip: + value: ${{ jobs.compare.outputs.skip }} +jobs: + compare: + if: github.event_name == 'pull_request' && github.event.action == 'synchronize' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + outputs: + skip: ${{ steps.check.outputs.result }} + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: .github/scripts + persist-credentials: false + - run: node --test .github/scripts/markdown-update.test.cjs + - name: Check the update against the previous verified revision + id: check + uses: actions/github-script@v7 + env: + CALLER_WORKFLOW: ${{ inputs.workflow }} + with: + script: | + const skip = require('./.github/scripts/markdown-update.cjs'); + return await skip({ github, context, core }, process.env.CALLER_WORKFLOW); diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index e82a9c62..ea2b7641 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -1,4 +1,6 @@ name: Rust 后端 +run-name: >- + ${{ github.event_name == 'pull_request' && format('PR #{0} · base {1}', github.event.pull_request.number, github.event.pull_request.base.sha) || github.workflow }} on: pull_request: paths: @@ -7,31 +9,36 @@ on: - "scripts/build-text-worker.py" - "scripts/tests/test_web_build_version.py" - "crates/**" - - "!crates/README.md" - - "!crates/*/README.md" - - "!crates/panache-mcp/tool-design.md" - "Cargo.toml" - "Cargo.lock" - "app/**" - - "!app/README.md" - - "!app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md" - "scripts/*release*.*" - - "!scripts/*release*.md" - "scripts/tests/test-flutter-release.cjs" - ".github/workflows/publish_flutter.yml" - "vendor/**" - - "!vendor/**/README.md" - - "!vendor/**/CHANGELOG.md" - - "!vendor/**/docs/**/*.md" - - "assets/font_assets/**" - - "assets/licenses/**" - "LICENSE" - "scripts/build-rust-service.sh" - "deploy/rust/**" + - ".github/scripts/markdown-update*.cjs" + - ".github/workflows/markdown-update.yml" - ".github/workflows/rust.yml" + - "!**/*.md" + - "assets/licenses/**" + - "assets/font_assets/**" + - "crates/*/licenses/**" + - "deploy/rust/README.md" workflow_dispatch: jobs: + markdown-update: + permissions: + actions: read + contents: read + uses: ./.github/workflows/markdown-update.yml + with: + workflow: rust.yml verify: + needs: markdown-update + if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} strategy: fail-fast: false matrix: @@ -49,6 +56,8 @@ jobs: - run: cargo test --locked --workspace - run: cargo build --locked --release -p handwriting-server flutter-integration: + needs: markdown-update + if: ${{ !cancelled() && needs.markdown-update.outputs.skip != 'true' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v4