From 0d2a6870758f8dc2be5ba6f07b630e8bed8e7740 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Tue, 24 Nov 2026 18:56:51 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat(crates/panache-mcp):=20=E5=B0=86?= =?UTF-8?q?=E6=97=A7=E7=A8=BF=E6=9C=AB=E9=A1=B5=E6=A3=80=E6=9F=A5=E5=8D=95?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E5=88=B0=E5=8E=9F=E6=96=87=E5=8A=A0=E5=85=A5?= =?UTF-8?q?=E5=89=8D=E7=9A=84=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:跨版本查验时,修改前的稿件与后来版本可以在相同的页码留下不同单据,也可能只有前几页做过检查。 解决手段:在按页查单时支持用独有原文字串解析其首次加入前一版,并按该版稿件的实际分页定位目标节末页,返回匹配的修订和原单据。歧义和无前版情况显式报错。 收益:客户端可在同一次只读调用核对版本、页码和反馈来源,缺单位置无需新建记录,现有按编号和数字页查询保留原路径。 --- CHANGELOG.md | 2 + crates/handwriting-core/src/render.rs | 5 + crates/panache-mcp/README.md | 4 +- crates/panache-mcp/src/drafts.rs | 28 ++++ crates/panache-mcp/src/engine.rs | 19 +++ crates/panache-mcp/src/inputs.rs | 20 ++- crates/panache-mcp/src/main.rs | 150 ++++++++++++------ crates/panache-mcp/tests/review_comparison.py | 37 +++++ 8 files changed, 217 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3713fc03..14cfcc31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 未发布 +- MCP 查旧检查单时可按新增原文定位上一版,并按该版实际排版查询指定节的末页。 + - MCP 可按稿件版本、节号和页码只读找回已存的整页复盘;缺少记录时明确返回空结果。 ## v1.21.0 (2026-11-24) diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index 74c60587..4acf4d45 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -292,6 +292,11 @@ pub(crate) fn render_output Result<()>>( }) } +/// Run the normal pagination pass, discarding each page before compositing or encoding. +pub fn count_pages(request: &RenderRequest, cancel: &Cancellation) -> Result { + render_pages(request, cancel, usize::MAX, |_, _, _| Ok(())) +} + pub(crate) fn render_pages( r: &RenderRequest, cancel: &Cancellation, diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index d2c3d696..9ebfe7c1 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -72,7 +72,9 @@ cargo build --locked --release -p panache-mcp 面向 AI 客户端的调用示例、披露边界和测量口径见[工具设计](tool-design.md)。 -查某版、某节、某一页当时留下的整页复盘,可用 `read_section(view="review", revision=3, section=2, page=1, draft_id=…)`。返回最近记录在这个位置的测量值、原检查单编号及注明来源的评语。该位置没有记录时返回 `status="no_recorded_review"`;这项查询不会生成页面,也不判断该页是否实际存在。已知检查单编号时仍可按 `review_id` 精确读取。 +查某版、某节、某一页当时留下的整页复盘,可用 `read_section(view="review", revision=3, section=2, page=1, draft_id=…)`。返回最近记录在这个位置的测量值、原检查单编号及注明来源的评语。该位置没有记录时返回 `status="no_recorded_review"`;直接按数字页码查单不会排版,也不判断该页是否实际存在。已知检查单编号时仍可按 `review_id` 精确读取。 + +如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复、无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。旧版可在事后补验,单据的版本号只表示受检稿件版本。 长作业可以按题组或章节分次传入,每节从新页开始。需要连续排版的段落放在同一节,公式、表格、代码块也应完整放在一节内。追加时带上 `draft_id` 和上次返回的 `expected_revision`;修改已有节时再给出 `section`。另一位客户端抢先保存后,用 `read_section` 复核最新内容再提交。 diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index bb3e215e..11c0f79d 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -309,6 +309,34 @@ impl Drafts { .collect::>>()?; Ok(json!({"drafts":entries,"offset":offset})) } + /// The first saved source containing a literal, provided it identifies a single section. + pub fn text_introduction(&self, id: &str, text: &str) -> Result<(u32, u32)> { + ensure!( + !text.trim().is_empty() && text.chars().count() <= 160, + "before_text needs 1..160 characters from the saved Markdown" + ); + let db = self.connect()?; + let mut statement = db.prepare( + "SELECT number, min(revision) FROM sections + WHERE draft=? AND instr(source,?)>0 GROUP BY number LIMIT 2", + )?; + let mut rows = statement.query(params![id, text])?; + let first = rows.next()?.context( + "No section contains before_text. Read the source for a literal fragment or specify a revision." + )?; + let section = first.get(0)?; + let revision = first.get(1)?; + ensure!( + rows.next()?.is_none(), + "before_text matches several sections. Use a more specific fragment or specify a revision." + ); + ensure!( + revision > 1, + "before_text already occurs in the first revision; no earlier draft exists." + ); + Ok((section, revision)) + } + pub fn snapshot<'a>(&'a self, id: &'a str, requested: Option) -> Result> { let (latest, style, layout): (u32, String, Option) = self .connect()? diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index d92bb5aa..6577435a 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -244,6 +244,25 @@ impl Engine { None => handwriting_core::render::render_until_page(request, cancel, stop, emit), } } + pub fn page_count( + &mut self, + draft: &Snapshot<'_>, + section: Section, + cancel: &Cancellation, + ) -> Result { + let (_, edits) = draft.edits(§ion)?; + // Projected photos are laid out in rectified paper space. Their final photo composite does not paginate. + let background = if draft.paper.as_ref().is_some_and(|p| p.projection.is_some()) { + None + } else { + draft.background()? + }; + let req = self.request(draft, section, background, edits)?; + Ok(u32::try_from(handwriting_core::render::count_pages( + &req, cancel, + )?)?) + } + fn fine_request(&mut self, draft: &Snapshot<'_>, section: Section) -> Result { let (_, edits) = draft.edits(§ion)?; let projected = draft.paper.as_ref().is_some_and(|p| p.projection.is_some()); diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 5bbe90f4..b1217609 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -142,12 +142,28 @@ pub enum ReadView { Source, } +#[derive(Clone, Copy, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum ReviewPage { + Number(u32), + Last(LastPage), +} + +#[derive(Clone, Copy, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum LastPage { + Last, +} + #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Read { /// With view=review, retrieve the most recently recorded full-page measurement at this one-based - /// page in the selected section (default 1) and exact revision (default latest). Omit review_id. - pub page: Option, + /// page, or "last" to paginate the selected section at the same revision. Omit review_id. + pub page: Option, + /// For a page review just before an addition: an exact, distinctive fragment of the added Markdown. + /// Uses the revision before its first occurrence; must match only one section. Omit revision. + pub before_text: Option, /// With view=review, retrieve one immutable measurement and its attributed feedback by ID instead of page. pub review_id: Option, /// With trajectory, pass next_cursor to continue the same snapshot, including its filters. Omit offset. diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index e5d33cc6..2ac47eec 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -66,46 +66,102 @@ fn reply(message: String, metadata: serde_json::Value) -> CallToolResult { result } -fn read_review(draft: &drafts::Snapshot<'_>, input: &Read) -> Result { - ensure!( - input.offset.is_none() && input.limit.is_none(), - "view=review does not use offset or limit" - ); - if let Some(page) = input.page { - ensure!(input.review_id.is_none(), "Use page or review_id, not both"); - let section = input.section.unwrap_or(1); - let mut record = draft.page_observation(section, page)?; - record["latest_draft_revision"] = json!(draft.latest_revision); - let receipt = match record["review_id"].as_str() { - Some(id) => format!("已存整页检查单 · 检查单号 {id}"), - None => "此版此页没有已存的整页检查单。其他版本的单据只证明当时的版本。".to_owned(), - }; - let text = format!( - "第 {} 版 · 第 {section} 节第 {page} 页(当前稿件第 {} 版)\n{receipt}\n{}", - draft.revision, draft.latest_revision, record - ); - return Ok(reply(text, record)); +fn page_receipt( + draft: &drafts::Snapshot<'_>, + section: u32, + page: u32, + anchor: Option<(u32, u32)>, +) -> Result { + let mut record = draft.page_observation(section, page)?; + record["latest_draft_revision"] = json!(draft.latest_revision); + if let Some((anchor_section, added_revision)) = anchor { + record["before_text_match"] = + json!({"section": anchor_section, "introduced_revision": added_revision}); } - ensure!( - input.section.is_none(), - "Supply page with section, or review_id alone" + let receipt = match record["review_id"].as_str() { + Some(id) if anchor.is_some() => format!( + "已存整页检查单 · 检查单号 {id}。此单属于所查版本;旧版可事后补验,开单与后续编辑的先后无法确定。" + ), + Some(id) => format!("已存整页检查单 · 检查单号 {id}"), + None => "此版此页没有已存的整页检查单。其他版本的单据只证明当时的版本。".to_owned(), + }; + let text = format!( + "第 {} 版 · 第 {section} 节第 {page} 页(当前稿件第 {} 版)\n{receipt}\n{}", + draft.revision, draft.latest_revision, record ); - let data = draft.observation( - input - .review_id - .as_deref() - .context("Supply review_id or page")?, - )?; - let mut content_note = None; - if data["revision"].as_u64() != Some(u64::from(draft.revision)) { - content_note = Some(ContentBlock::text(format!( - "此单属于第 {} 版。若要确认所查第 {} 版是否留有整页检查单,请用 read_section(view=review, revision={}, section={}, page={}) 查该版。", - data["revision"], draft.revision, draft.revision, data["section"], data["page"] - ))); + Ok(reply(text, record)) +} + +impl Panache { + async fn read_review( + &self, + input: Read, + ctx: RequestContext, + ) -> Result { + ensure!( + input.cursor.is_none() && input.feedback_origin.is_none(), + "cursor and feedback_origin require view=trajectory" + ); + ensure!( + input.offset.is_none() && input.limit.is_none(), + "view=review does not use offset or limit" + ); + if let Some(page) = input.page { + ensure!(input.review_id.is_none(), "Use page or review_id, not both"); + ensure!( + input.before_text.is_none() || input.revision.is_none(), + "Use before_text or revision, not both" + ); + let anchor = input + .before_text + .as_deref() + .map(|t| self.0.drafts.text_introduction(&input.draft_id, t)) + .transpose()?; + let revision = anchor.map(|(_, added)| added - 1).or(input.revision); + let section = input.section.unwrap_or(1); + ensure!(section > 0, "section starts at 1"); + return match page { + ReviewPage::Number(n) => { + let draft = self.0.drafts.snapshot(&input.draft_id, revision)?; + page_receipt(&draft, section, n, anchor) + } + ReviewPage::Last(_) => { + self.render(ctx, move |state, engine, cancel| { + let draft = state.drafts.snapshot(&input.draft_id, revision)?; + let source = state + .drafts + .sections(draft.id, draft.revision, Some(section))? + .pop() + .context("Empty section")?; + let last = engine.page_count(&draft, source, cancel)?; + page_receipt(&draft, section, last, anchor) + }) + .await + } + }; + } + ensure!( + input.section.is_none() && input.before_text.is_none(), + "Supply page with section or before_text, or review_id alone" + ); + let draft = self.0.drafts.snapshot(&input.draft_id, input.revision)?; + let data = draft.observation( + input + .review_id + .as_deref() + .context("Supply review_id or page")?, + )?; + let mut content_note = None; + if data["revision"].as_u64() != Some(u64::from(draft.revision)) { + content_note = Some(ContentBlock::text(format!( + "此单属于第 {} 版。若要确认所查第 {} 版是否留有整页检查单,请用 read_section(view=review, revision={}, section={}, page={}) 查该版。", + data["revision"], draft.revision, draft.revision, data["section"], data["page"] + ))); + } + let mut result = reply(data.to_string(), data); + result.content.extend(content_note); + Ok(result) } - let mut result = reply(data.to_string(), data); - result.content.extend(content_note); - Ok(result) } fn tool_result(out: Result) -> CallToolResult { @@ -176,7 +232,7 @@ impl ServerHandler for Panache { "Ask for a photo clearly showing it or permission to fill only visible areas; wait before saving or trial placement. If partial work was requested, proceed there. ", "Use save_section(markdown), then its draft_id and revision for preview_handwriting or export_handwriting. ", "English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. For an undecided homework or lab-report style, see list_fonts for sample guidance. Use list_drafts to resume. A paper_path must be readable on the server computer. ", - "To check what was already recorded, use read_section(view=review, section, page) at the requested revision (omit revision for current). Use preview_handwriting(view=review) for a new photo inspection; it records a check. Follow photo_appearance.preview_arguments for a native detail crop when available. ", + "For old checks before a passage was added, use read_section(view=review, before_text=literal from that addition, section, page); page can be \"last\". For current checks omit revision. Use preview_handwriting(view=review) for a new photo inspection; it records a check. Follow photo_appearance.preview_arguments for a native detail crop when available. ", "If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", "Forms, unruled paper and artwork are supported. Follow specified or delegated placement, matching field orientation and preserving printed labels. ", "If the intended writing area is ambiguous, ask which field to fill or leave clear. ", @@ -328,17 +384,24 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "For a prior check of a particular sheet, start with view=review, section and page. Omit revision for the current draft, or specify the exact historical revision. The check receipt number (检查单号) is review_id. Read its saved measurements and attributed feedback, or no_recorded_review, without rendering. A known review_id retrieves that record. Use view=trajectory to identify revisions from edits or search across versions: older events remain in the results. Filter by section and feedback_origin=user_quote for verbatim events[].details.text. Text views: summary, excerpt (default, image data omitted), source (exact Markdown)." + description = "For a prior check of a particular sheet, use view=review, section and page. For “before adding [words]” pass before_text with a literal fragment of the addition; for the final sheet of that section pass page=\"last\". These select and paginate the same historical version in one lookup. Otherwise omit revision for current or set a revision. The check receipt number (检查单号) is review_id. Read its saved measurements and attributed feedback, or no_recorded_review, without creating a check. A known review_id retrieves that record. Use view=trajectory to identify revisions from edits or search across versions: older events remain in the results. Filter by section and feedback_origin=user_quote for verbatim events[].details.text. Text views: summary, excerpt (default, image data omitted), source (exact Markdown)." )] - fn read_section(&self, Parameters(input): Parameters) -> CallToolResult { + async fn read_section( + &self, + Parameters(input): Parameters, + ctx: RequestContext, + ) -> CallToolResult { + if input.view == Some(ReadView::Review) { + return tool_result(self.read_review(input, ctx).await); + } tool_result((|| { ensure!( input.feedback_origin.is_none() || input.view == Some(ReadView::Trajectory), "feedback_origin requires view=trajectory" ); ensure!( - input.page.is_none() || input.view == Some(ReadView::Review), - "page requires view=review" + input.page.is_none() && input.before_text.is_none(), + "page and before_text require view=review" ); if input.view == Some(ReadView::Trajectory) { ensure!(input.review_id.is_none(), "review_id requires view=review"); @@ -347,9 +410,6 @@ impl Panache { } ensure!(input.cursor.is_none(), "cursor requires view=trajectory"); let draft = self.0.drafts.snapshot(&input.draft_id, input.revision)?; - if input.view == Some(ReadView::Review) { - return read_review(&draft, &input); - } ensure!(input.review_id.is_none(), "review_id requires view=review"); let mut result = self.0.drafts.review( &input.draft_id, diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index 0edcc898..9398e823 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -166,10 +166,47 @@ async def history(**args): assert (await client.call_tool("read_section", {**key, **invalid})).isError +async def historical_last_page(client, directory, call, path, guides): + saved = await call(client, "save_section", paper_path=str(path), paper_guides=guides, + markdown="\n\n".join(f"初次测量第{i}行。" for i in range(20))) + key = {"draft_id": saved.structuredContent["draft_id"]} + exported = await call(client, "export_handwriting", **key, revision=1, format="zip") + last = exported.structuredContent["pages"] + assert last > 1 + await call(client, "preview_handwriting", **key, revision=1, view="review", page=1) + await call(client, "save_section", **key, expected_revision=1, section=1, + markdown="复测补录:一行。") + current = (await call(client, "preview_handwriting", **key, view="review")).structuredContent + select = {**key, "view": "review", "section": 1, "page": "last"} + assert (await call(client, "read_section", **select)).structuredContent["review_id"] == current["review_id"] + anchored = {**select, "before_text": "复测补录"} + with closing(sqlite3.connect(directory / "drafts.sqlite3")) as db: + sql = "SELECT seq,review_id FROM review_observations WHERE draft=? ORDER BY seq" + records = db.execute(sql, (key["draft_id"],)).fetchall() + for _ in range(2): + receipt = await call(client, "read_section", **anchored) + data = receipt.structuredContent + assert (data["revision"], data["section"], data["page"]) == (1, 1, last) + assert data["before_text_match"] == {"introduced_revision": 2, "section": 1} + assert data["review_id"] is None and data["status"] == "no_recorded_review" + assert all(part.type == "text" for part in receipt.content) + assert db.execute(sql, (key["draft_id"],)).fetchall() == records + old = (await call(client, "preview_handwriting", **key, revision=1, view="review", page=last)).structuredContent + receipt = await call(client, "read_section", **anchored) + assert receipt.structuredContent["review_id"] == old["review_id"] + assert "事后补验" in receipt.content[0].text + for override in ({"before_text": "初次测量"}, {"before_text": "缺少的段落"}, + {"before_text": ""}, {"revision": 1}, {"section": 2}, {"page": "latest"}): + assert (await client.call_tool("read_section", {**anchored, **override})).isError + await call(client, "save_section", **key, expected_revision=2, markdown="复测补录也写在此节。") + assert (await client.call_tool("read_section", anchored)).isError + + async def exercise(client, directory, call): await unruled_artwork(client, directory, call) path = directory / "slanted.png" guides = slanted_sheet(path) + await historical_last_page(client, directory, call, path, guides) shifted = [ { **g, From 32f0929140977a65ad2319323b9f27a018901aaf Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Tue, 24 Nov 2026 18:58:59 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix(crates/panache-mcp):=20=E6=8B=92?= =?UTF-8?q?=E7=BB=9D=E5=B0=86=E9=87=8D=E5=A4=8D=E5=BC=95=E5=85=A5=E7=9A=84?= =?UTF-8?q?=E6=96=87=E5=AD=97=E7=BB=91=E5=AE=9A=E5=88=B0=E5=8D=95=E4=B8=80?= =?UTF-8?q?=E6=97=A7=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:同一节中的补记可能被删除并重新加入,按最初含该字串的版本定位会掩盖两个可能的编辑边界。 解决手段:按每一节的修订顺序查找从缺少到包含原文的转换,只有唯一的引入事件可以绑定前一版。增加连续保留、删后重加、跨节重复和明确版本回退的回归覆盖。 收益:用户描述存在多个可行解释时,助手可以请求明确所指编辑,避免将真实检查单套到另一版。 --- crates/panache-mcp/README.md | 2 +- crates/panache-mcp/src/drafts.rs | 15 +++++++++++---- crates/panache-mcp/src/inputs.rs | 2 +- crates/panache-mcp/tests/review_comparison.py | 13 +++++++++++-- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 9ebfe7c1..f07d45a2 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -74,7 +74,7 @@ cargo build --locked --release -p panache-mcp 查某版、某节、某一页当时留下的整页复盘,可用 `read_section(view="review", revision=3, section=2, page=1, draft_id=…)`。返回最近记录在这个位置的测量值、原检查单编号及注明来源的评语。该位置没有记录时返回 `status="no_recorded_review"`;直接按数字页码查单不会排版,也不判断该页是否实际存在。已知检查单编号时仍可按 `review_id` 精确读取。 -如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复、无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。旧版可在事后补验,单据的版本号只表示受检稿件版本。 +如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复、同节删后重加、无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。旧版可在事后补验,单据的版本号只表示受检稿件版本。 长作业可以按题组或章节分次传入,每节从新页开始。需要连续排版的段落放在同一节,公式、表格、代码块也应完整放在一节内。追加时带上 `draft_id` 和上次返回的 `expected_revision`;修改已有节时再给出 `section`。另一位客户端抢先保存后,用 `read_section` 复核最新内容再提交。 diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 11c0f79d..40fcbdef 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -309,7 +309,7 @@ impl Drafts { .collect::>>()?; Ok(json!({"drafts":entries,"offset":offset})) } - /// The first saved source containing a literal, provided it identifies a single section. + /// Find a single transition from absent to present across all versions of all sections. pub fn text_introduction(&self, id: &str, text: &str) -> Result<(u32, u32)> { ensure!( !text.trim().is_empty() && text.chars().count() <= 160, @@ -317,8 +317,15 @@ impl Drafts { ); let db = self.connect()?; let mut statement = db.prepare( - "SELECT number, min(revision) FROM sections - WHERE draft=? AND instr(source,?)>0 GROUP BY number LIMIT 2", + "WITH versions AS ( + SELECT number,revision,instr(source,?2)>0 AS present + FROM sections WHERE draft=?1 + ), changes AS ( + SELECT number,revision,present, + lag(present,1,0) OVER (PARTITION BY number ORDER BY revision) AS previously_present + FROM versions + ) + SELECT number,revision FROM changes WHERE present AND NOT previously_present LIMIT 2", )?; let mut rows = statement.query(params![id, text])?; let first = rows.next()?.context( @@ -328,7 +335,7 @@ impl Drafts { let revision = first.get(1)?; ensure!( rows.next()?.is_none(), - "before_text matches several sections. Use a more specific fragment or specify a revision." + "before_text was introduced more than once (possibly in different sections). Use a more specific fragment or specify a revision." ); ensure!( revision > 1, diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index b1217609..2b86fa7e 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -162,7 +162,7 @@ pub struct Read { /// page, or "last" to paginate the selected section at the same revision. Omit review_id. pub page: Option, /// For a page review just before an addition: an exact, distinctive fragment of the added Markdown. - /// Uses the revision before its first occurrence; must match only one section. Omit revision. + /// Uses the revision immediately before its unique introduction; repeated introductions are ambiguous. Omit revision. pub before_text: Option, /// With view=review, retrieve one immutable measurement and its attributed feedback by ID instead of page. pub review_id: Option, diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index 9398e823..5dc9977e 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -198,8 +198,17 @@ async def historical_last_page(client, directory, call, path, guides): for override in ({"before_text": "初次测量"}, {"before_text": "缺少的段落"}, {"before_text": ""}, {"revision": 1}, {"section": 2}, {"page": "latest"}): assert (await client.call_tool("read_section", {**anchored, **override})).isError - await call(client, "save_section", **key, expected_revision=2, markdown="复测补录也写在此节。") - assert (await client.call_tool("read_section", anchored)).isError + # Retaining the fragment across edits is still the same introduction. + await call(client, "save_section", **key, expected_revision=2, section=1, markdown="复测补录:两行。") + numeric = {**anchored, "page": last} + assert (await call(client, "read_section", **numeric)).structuredContent["review_id"] == old["review_id"] + await call(client, "save_section", **key, expected_revision=3, section=1, markdown="新题目。") + await call(client, "save_section", **key, expected_revision=4, section=1, markdown="复测补录:新题目。") + assert (await client.call_tool("read_section", numeric)).isError + await call(client, "save_section", **key, expected_revision=5, markdown="另一节也写了新题目。") + assert (await client.call_tool("read_section", {**numeric, "before_text": "新题目"})).isError + explicit = {**select, "revision": 1, "page": last} + assert (await call(client, "read_section", **explicit)).structuredContent["review_id"] == old["review_id"] async def exercise(client, directory, call): From adb9666964d5ad7c12ad645849f2849b18578cd2 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Tue, 24 Nov 2026 19:03:43 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix(crates/panache-mcp):=20=E7=BB=99?= =?UTF-8?q?=E5=87=BA=E9=87=8D=E5=A4=8D=E8=A1=A5=E8=AE=B0=E7=9A=84=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E7=89=88=E6=9C=AC=E9=80=89=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:用户尚未说明哪一次补入原文时,笼统的歧义报错仍会让客户端自行代选一个历史版本。 解决手段:按时间列出最早两次引入的节和版本,给出可直接读取的前一版。标明首次建稿没有前版、候选过多时仅列示例,并提示询问用户或分别核对。 收益:客户端可以使用用户熟悉的先后关系确认要查的稿件,歧义回执不混入任何候选检查单。 --- crates/panache-mcp/README.md | 2 +- crates/panache-mcp/src/drafts.rs | 40 ++++++++++++++----- crates/panache-mcp/tests/review_comparison.py | 14 ++++++- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index f07d45a2..04ce5854 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -74,7 +74,7 @@ cargo build --locked --release -p panache-mcp 查某版、某节、某一页当时留下的整页复盘,可用 `read_section(view="review", revision=3, section=2, page=1, draft_id=…)`。返回最近记录在这个位置的测量值、原检查单编号及注明来源的评语。该位置没有记录时返回 `status="no_recorded_review"`;直接按数字页码查单不会排版,也不判断该页是否实际存在。已知检查单编号时仍可按 `review_id` 精确读取。 -如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复、同节删后重加、无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。旧版可在事后补验,单据的版本号只表示受检稿件版本。 +如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复或同节删后重加时,结果列出最早两个加入时点及对应的前一版。请用户选择,也可分版回答。无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。旧版可在事后补验,单据的版本号只表示受检稿件版本。 长作业可以按题组或章节分次传入,每节从新页开始。需要连续排版的段落放在同一节,公式、表格、代码块也应完整放在一节内。追加时带上 `draft_id` 和上次返回的 `expected_revision`;修改已有节时再给出 `section`。另一位客户端抢先保存后,用 `read_section` 复核最新内容再提交。 diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 40fcbdef..16c89892 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -325,18 +325,40 @@ impl Drafts { lag(present,1,0) OVER (PARTITION BY number ORDER BY revision) AS previously_present FROM versions ) - SELECT number,revision FROM changes WHERE present AND NOT previously_present LIMIT 2", + SELECT number,revision FROM changes WHERE present AND NOT previously_present + ORDER BY revision,number LIMIT 3", )?; - let mut rows = statement.query(params![id, text])?; - let first = rows.next()?.context( + let matches = statement + .query_map(params![id, text], |row| { + Ok((row.get::<_, u32>(0)?, row.get::<_, u32>(1)?)) + })? + .collect::>>()?; + let &(section, revision) = matches.first().context( "No section contains before_text. Read the source for a literal fragment or specify a revision." )?; - let section = first.get(0)?; - let revision = first.get(1)?; - ensure!( - rows.next()?.is_none(), - "before_text was introduced more than once (possibly in different sections). Use a more specific fragment or specify a revision." - ); + if matches.len() > 1 { + let mut message = String::from( + "这段原文有多个加入时点。请让用户确认是首次加入之前,还是后来再次加入之前;也可分别核对并逐版列出,未确认时不要代选。", + ); + for (number, added) in matches.iter().take(2) { + let choice = if *added == 1 { + "这是初稿,之前没有稿件。".to_owned() + } else { + format!("要查加入前的稿件,传 revision={}。", added - 1) + }; + message.push_str(&format!( + "\n第 {added} 版第 {number} 节加入了这段原文。{choice}" + )); + } + if matches.len() > 2 { + message.push_str( + "\n这里只列最早两次,另有加入时点。可通过 trajectory 和 source 核对。", + ); + } + anyhow::bail!( + "{message}\n按明确版本查单时移除 before_text,保留原来待查的 section 和 page。" + ); + } ensure!( revision > 1, "before_text already occurs in the first revision; no earlier draft exists." diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index 5dc9977e..26d9282c 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -204,9 +204,19 @@ async def historical_last_page(client, directory, call, path, guides): assert (await call(client, "read_section", **numeric)).structuredContent["review_id"] == old["review_id"] await call(client, "save_section", **key, expected_revision=3, section=1, markdown="新题目。") await call(client, "save_section", **key, expected_revision=4, section=1, markdown="复测补录:新题目。") - assert (await client.call_tool("read_section", numeric)).isError - await call(client, "save_section", **key, expected_revision=5, markdown="另一节也写了新题目。") + ambiguous = await client.call_tool("read_section", numeric) + assert ambiguous.isError + options = ambiguous.content[0].text + assert options.index("revision=1") < options.index("revision=4") + assert "未确认时不要代选" in options and old["review_id"] not in options + await call(client, "save_section", **key, expected_revision=5, markdown="另一节也写了新题目和初次测量。") assert (await client.call_tool("read_section", {**numeric, "before_text": "新题目"})).isError + await call(client, "save_section", **key, expected_revision=6, markdown="第三节:初次测量。") + several = await client.call_tool("read_section", {**numeric, "before_text": "初次测量"}) + assert several.isError + options = several.content[0].text + assert "之前没有稿件" in options and "revision=5" in options + assert "只列最早两次" in options and "revision=6" not in options explicit = {**select, "revision": 1, "page": last} assert (await call(client, "read_section", **explicit)).structuredContent["review_id"] == old["review_id"] From 08089ac7f08b5787d3b02d801944f5c5d70f513a Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Tue, 24 Nov 2026 19:08:54 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(crates/panache-mcp):=20=E5=9C=A8?= =?UTF-8?q?=E9=80=89=E5=AE=9A=E6=97=A7=E7=89=88=E6=97=B6=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E5=BE=85=E6=9F=A5=E6=AD=A3=E6=96=87=E6=89=80=E5=9C=A8=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:重复引入时给出的编辑节号容易被误用为查单的目标节,多节旧稿省略节号还可能意外选中第一节。 解决手段:在各版本选项中列出有界的节号与正文开头,同节反复补入仅显示时间。相对定位或查末页时,多节稿需指定目标节;传统数字页查询沿用原有默认。 收益:可按用户要查的正文选择版本和页,节提示不会展开内嵌图片,也不会生成检查单。 --- crates/panache-mcp/README.md | 2 +- crates/panache-mcp/src/drafts.rs | 72 ++++++++++++++++--- crates/panache-mcp/src/inputs.rs | 3 +- crates/panache-mcp/src/main.rs | 8 ++- crates/panache-mcp/tests/review_comparison.py | 17 +++++ 5 files changed, 90 insertions(+), 12 deletions(-) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 04ce5854..9ebfb93e 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -74,7 +74,7 @@ cargo build --locked --release -p panache-mcp 查某版、某节、某一页当时留下的整页复盘,可用 `read_section(view="review", revision=3, section=2, page=1, draft_id=…)`。返回最近记录在这个位置的测量值、原检查单编号及注明来源的评语。该位置没有记录时返回 `status="no_recorded_review"`;直接按数字页码查单不会排版,也不判断该页是否实际存在。已知检查单编号时仍可按 `review_id` 精确读取。 -如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复或同节删后重加时,结果列出最早两个加入时点及对应的前一版。请用户选择,也可分版回答。无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。旧版可在事后补验,单据的版本号只表示受检稿件版本。 +如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复或同节删后重加时,结果列出最早两个加入时点及对应的前一版。可查的正文节附有简短开头,便于区分补记所在节和实际要查的节。请用户选择,也可分版回答。按补记或末页查多节稿时需明确待查节号。无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。旧版可在事后补验,单据的版本号只表示受检稿件版本。 长作业可以按题组或章节分次传入,每节从新页开始。需要连续排版的段落放在同一节,公式、表格、代码块也应完整放在一节内。追加时带上 `draft_id` 和上次返回的 `expected_revision`;修改已有节时再给出 `section`。另一位客户端抢先保存后,用 `read_section` 复核最新内容再提交。 diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 16c89892..c1832f53 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -56,6 +56,21 @@ pub struct Snapshot<'a> { } impl Snapshot<'_> { + pub fn review_section(&self, requested: Option) -> Result { + if let Some(section) = requested { + ensure!(section > 0, "section starts at 1"); + return Ok(section); + } + let choices = self.drafts.review_section_choices(self.id, self.revision)?; + ensure!( + choices.len() == 1, + "请按待查的正文选择 section。第 {} 版可查的节:{}", + self.revision, + choices.join(" · ") + ); + Ok(1) + } + pub fn has_font(&self, handle: &str) -> Result { Ok(self.drafts.connect()?.query_row( "SELECT EXISTS(SELECT 1 FROM draft_fonts WHERE draft=? AND handle=?)", @@ -309,6 +324,39 @@ impl Drafts { .collect::>>()?; Ok(json!({"drafts":entries,"offset":offset})) } + // Bound the source prefix in SQLite, including when a section starts with an inline photo. + fn review_section_choices(&self, id: &str, revision: u32) -> Result> { + let db = self.connect()?; + let mut stmt = db.prepare( + "SELECT number, substr(source,1,48) FROM sections JOIN ( + SELECT number, max(revision) AS revision FROM sections + WHERE draft=?1 AND revision<=?2 GROUP BY number ORDER BY number LIMIT 5 + ) USING(number,revision) WHERE draft=?1 ORDER BY number", + )?; + let mut choices = Vec::new(); + let mut rows = stmt.query(params![id, revision])?; + while let Some(row) = rows.next()? { + if choices.len() == 4 { + choices.push("其余节可用 view=excerpt 查阅".to_owned()); + break; + } + let number: u32 = row.get(0)?; + let prefix: String = row.get(1)?; + let before_image = prefix + .find("![") + .into_iter() + .chain(prefix.find("data:")) + .min() + .unwrap_or(prefix.len()); + let text = prefix[..before_image] + .split_whitespace() + .collect::>() + .join(" "); + choices.push(format!("section={number} {}", json!(text))); + } + Ok(choices) + } + /// Find a single transition from absent to present across all versions of all sections. pub fn text_introduction(&self, id: &str, text: &str) -> Result<(u32, u32)> { ensure!( @@ -340,15 +388,23 @@ impl Drafts { let mut message = String::from( "这段原文有多个加入时点。请让用户确认是首次加入之前,还是后来再次加入之前;也可分别核对并逐版列出,未确认时不要代选。", ); + let same_section = matches[0].0 == matches[1].0; for (number, added) in matches.iter().take(2) { - let choice = if *added == 1 { - "这是初稿,之前没有稿件。".to_owned() + if same_section { + message.push_str(&format!("\n第 {added} 版加入了这段原文。")); } else { - format!("要查加入前的稿件,传 revision={}。", added - 1) - }; - message.push_str(&format!( - "\n第 {added} 版第 {number} 节加入了这段原文。{choice}" - )); + message.push_str(&format!("\n第 {added} 版在第 {number} 节加入了这段原文。")); + } + if *added == 1 { + message.push_str("这是初稿,之前没有稿件。"); + } else { + let before = added - 1; + let choices = self.review_section_choices(id, before)?; + message.push_str(&format!( + "加入前查 revision={before};该版可查的正文:{}", + choices.join(" · ") + )); + } } if matches.len() > 2 { message.push_str( @@ -356,7 +412,7 @@ impl Drafts { ); } anyhow::bail!( - "{message}\n按明确版本查单时移除 before_text,保留原来待查的 section 和 page。" + "{message}\n所补文字只用来认版本。请按用户要查的正文选择 section,保留 page,移除 before_text 后按明确版本查单。" ); } ensure!( diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 2b86fa7e..b3dad018 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -159,7 +159,8 @@ pub enum LastPage { #[serde(deny_unknown_fields)] pub struct Read { /// With view=review, retrieve the most recently recorded full-page measurement at this one-based - /// page, or "last" to paginate the selected section at the same revision. Omit review_id. + /// page, or "last" to paginate the selected section at the same revision. With "last" or before_text, + /// specify the section containing the requested body in a multi-section draft. Omit review_id. pub page: Option, /// For a page review just before an addition: an exact, distinctive fragment of the added Markdown. /// Uses the revision immediately before its unique introduction; repeated introductions are ambiguous. Omit revision. diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 2ac47eec..c3958a0f 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -118,16 +118,20 @@ impl Panache { .map(|t| self.0.drafts.text_introduction(&input.draft_id, t)) .transpose()?; let revision = anchor.map(|(_, added)| added - 1).or(input.revision); - let section = input.section.unwrap_or(1); - ensure!(section > 0, "section starts at 1"); return match page { ReviewPage::Number(n) => { let draft = self.0.drafts.snapshot(&input.draft_id, revision)?; + let section = if anchor.is_some() { + draft.review_section(input.section)? + } else { + input.section.unwrap_or(1) + }; page_receipt(&draft, section, n, anchor) } ReviewPage::Last(_) => { self.render(ctx, move |state, engine, cancel| { let draft = state.drafts.snapshot(&input.draft_id, revision)?; + let section = draft.review_section(input.section)?; let source = state .drafts .sections(draft.id, draft.revision, Some(section))? diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index 26d9282c..e4b5eadb 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -209,6 +209,7 @@ async def historical_last_page(client, directory, call, path, guides): options = ambiguous.content[0].text assert options.index("revision=1") < options.index("revision=4") assert "未确认时不要代选" in options and old["review_id"] not in options + assert "section=1" in options and "第 1 节加入" not in options await call(client, "save_section", **key, expected_revision=5, markdown="另一节也写了新题目和初次测量。") assert (await client.call_tool("read_section", {**numeric, "before_text": "新题目"})).isError await call(client, "save_section", **key, expected_revision=6, markdown="第三节:初次测量。") @@ -217,6 +218,22 @@ async def historical_last_page(client, directory, call, path, guides): options = several.content[0].text assert "之前没有稿件" in options and "revision=5" in options assert "只列最早两次" in options and "revision=6" not in options + # A last-page or relative lookup must not silently use section one in a multi-section draft. + for args in ({**key, "view": "review", "page": "last", "revision": 6}, + {**key, "view": "review", "page": 1, "before_text": "第三节:"}): + missing_section = await client.call_tool("read_section", args) + assert missing_section.isError and "section=2" in missing_section.content[0].text + image = base64.b64encode(path.read_bytes()).decode("ascii") + await call(client, "save_section", **key, expected_revision=7, markdown=f"![图](data:image/png;base64,{image})") + await call(client, "save_section", **key, expected_revision=8, markdown="第 5 节正文") + listing = await client.call_tool("read_section", {**key, "view": "review", "page": "last"}) + assert listing.isError + text = listing.content[0].text + assert "section=4" in text and "其余节" in text and "section=5" not in text + assert "base64" not in text and image[:16] not in text + # An ordinary numbered page keeps the established first-section default. + direct = await call(client, "read_section", **key, view="review", revision=6, page=1) + assert direct.structuredContent["section"] == 1 explicit = {**select, "revision": 1, "page": last} assert (await call(client, "read_section", **explicit)).structuredContent["review_id"] == old["review_id"]