diff --git a/CHANGELOG.md b/CHANGELOG.md index b84468a9..3713fc03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 未发布 +- MCP 可按稿件版本、节号和页码只读找回已存的整页复盘;缺少记录时明确返回空结果。 + ## v1.21.0 (2026-11-24) - 在「关于与反馈 → 支持作者」可查看随应用提供的微信赞赏码。官网首页也可直接扫码支持 Simon。 diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 35739a2b..d2c3d696 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -72,6 +72,8 @@ 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` 精确读取。 + 长作业可以按题组或章节分次传入,每节从新页开始。需要连续排版的段落放在同一节,公式、表格、代码块也应完整放在一节内。追加时带上 `draft_id` 和上次返回的 `expected_revision`;修改已有节时再给出 `section`。另一位客户端抢先保存后,用 `read_section` 复核最新内容再提交。 每次保存只转换这一节,Markdown 原文和整理结果存入本地 SQLite。预览某节第 N 页时,引擎从该节开头排到第 N 页,只编码选中的一页。进程内保留最近生成的四张预览,修改其他节仍可复用。预览和导出传相同的 `revision` 可锁定稿件。种子和样式随稿保存,复现时需使用相同字体和引擎。 diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 7d22c236..bb3e215e 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -44,6 +44,7 @@ fn concurrent_first_opens_share_a_complete_schema() -> Result<()> { } pub struct Snapshot<'a> { + pub latest_revision: u32, pub revision: u32, pub style: Style, pub controls: crate::controls::Changes, @@ -339,6 +340,7 @@ impl Drafts { "SELECT layout FROM paper_layouts WHERE draft=? AND revision<=? ORDER BY revision DESC LIMIT 1", params![id,revision], |r| r.get(0)).optional()?; Ok(Snapshot { + latest_revision: latest, controls, settings_revision, layout_revision, diff --git a/crates/panache-mcp/src/drafts/observations.rs b/crates/panache-mcp/src/drafts/observations.rs index 39c17476..4cafd92e 100644 --- a/crates/panache-mcp/src/drafts/observations.rs +++ b/crates/panache-mcp/src/drafts/observations.rs @@ -56,6 +56,24 @@ fn by_id(db: &Connection, id: &str, draft: &Snapshot<'_>) -> Result { Ok(record) } +fn page_record( + db: &Connection, + draft: &Snapshot<'_>, + revision: u32, + section: u32, + page: u32, +) -> Result> { + let id: Option = db + .query_row( + "SELECT review_id FROM review_observations + WHERE draft=? AND revision=? AND section=? AND page=? ORDER BY seq DESC LIMIT 1", + params![draft.id, revision, section, page], + |row| row.get(0), + ) + .optional()?; + id.map(|id| by_id(db, &id, draft)).transpose() +} + impl Snapshot<'_> { pub fn record_review( &self, @@ -84,6 +102,19 @@ impl Snapshot<'_> { by_id(&self.drafts.connect()?, id, self) } + pub fn page_observation(&self, section: u32, page: u32) -> Result { + ensure!(section > 0 && page > 0, "section and page start at 1"); + let mut db = self.drafts.connect()?; + let tx = db.transaction()?; + let record = page_record(&tx, self, self.revision, section, page)?; + Ok(record.unwrap_or_else(|| { + json!({ + "draft_id": self.id, "revision": self.revision, "section": section, "page": page, + "review_id": null, "status": "no_recorded_review", + }) + })) + } + 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) @@ -110,19 +141,9 @@ impl Snapshot<'_> { ); let mut db = self.drafts.connect()?; let tx = db.transaction()?; - let fetch = |rev: u32| -> Result> { - let id: Option = tx - .query_row( - "SELECT review_id FROM review_observations - WHERE draft=? AND revision=? AND section=? AND page=? ORDER BY seq DESC LIMIT 1", - params![self.id, rev, section, u32::try_from(page)?], - |r| r.get(0), - ) - .optional()?; - id.map(|v| by_id(&tx, &v, self)).transpose() - }; - let previous = fetch(before)?; - let current = fetch(self.revision)?; + let page = u32::try_from(page)?; + let previous = page_record(&tx, self, before, section, page)?; + let current = page_record(&tx, self, self.revision, section, page)?; let mut stmt=tx.prepare("WITH actions(rev,action,section) AS ( SELECT revision,'save_section',number FROM sections WHERE draft=?1 UNION ALL SELECT revision,'tune_handwriting',NULL FROM settings WHERE draft=?1 @@ -253,6 +274,7 @@ mod tests { && legacy["page_content_sha256"].is_null() ); assert_eq!(legacy["evidence"]["visibility"], "no_visible_change"); + assert_eq!(old.page_observation(1, 1)?, legacy); let observation = json!({"visibility":"inspect_visually","photo_size":[400,500]}); let rev2 = drafts.snapshot("d", Some(2))?; let first = rev2.record_review(1, 1, "a", "pixels", "content", &observation)?; @@ -281,6 +303,8 @@ mod tests { )?; assert_ne!(first["review_id"], changed["review_id"]); assert_ne!(changed["review_id"], upgraded["review_id"]); + assert_eq!(rev2.page_observation(1, 1)?, upgraded); + assert_eq!(old.page_observation(1, 1)?, legacy); assert_eq!(rev2.review_counts()?, (1, 1)); let rev3 = drafts.snapshot("d", Some(3))?; rev3.record_review(1, 1, "a", "pixels", "content", &observation)?; diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 5efd5ea2..5bbe90f4 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -145,7 +145,10 @@ pub enum ReadView { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Read { - /// With view=review, retrieve one immutable measurement and its attributed feedback. + /// With view=review, retrieve the most recently recorded full-page measurement at this one-based + /// page in the selected section (default 1) and exact revision (default latest). Omit review_id. + pub page: Option, + /// With view=review, retrieve one immutable measurement and its attributed feedback by ID instead of page. pub review_id: Option, /// With trajectory, pass next_cursor to continue the same snapshot, including its filters. Omit offset. pub cursor: Option, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 5d7fb9bb..e5d33cc6 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -66,6 +66,48 @@ 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)); + } + ensure!( + input.section.is_none(), + "Supply page with section, or review_id alone" + ); + 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) +} + fn tool_result(out: Result) -> CallToolResult { out.unwrap_or_else(|error| { CallToolResult::error(vec![ContentBlock::text(format!("{error:#}"))]) @@ -134,7 +176,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. ", - "For photos use preview_handwriting(view=review). Follow photo_appearance.preview_arguments for a native detail crop when available. ", + "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. ", "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. ", @@ -286,7 +328,7 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "Read view=trajectory for draft history, highest associated revision first. Filter by feedback_origin=user_quote and optionally section for verbatim quotes in events[].details.text with their revision and review_id. Use view=review with review_id for full measurements or other feedback on that review. Text views: summary, excerpt (default, image data omitted), or exact source." + description = "For a prior check of a particular sheet, 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)." )] fn read_section(&self, Parameters(input): Parameters) -> CallToolResult { tool_result((|| { @@ -294,6 +336,10 @@ impl Panache { 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" + ); if input.view == Some(ReadView::Trajectory) { ensure!(input.review_id.is_none(), "review_id requires view=review"); let result = self.0.drafts.trajectory(&input)?; @@ -302,13 +348,7 @@ impl Panache { ensure!(input.cursor.is_none(), "cursor requires view=trajectory"); let draft = self.0.drafts.snapshot(&input.draft_id, input.revision)?; if input.view == Some(ReadView::Review) { - ensure!( - input.section.is_none() && input.offset.is_none() && input.limit.is_none(), - "Exact review lookup uses draft_id and review_id" - ); - let data = - draft.observation(input.review_id.as_deref().context("Provide review_id")?)?; - return Ok(reply(data.to_string(), data)); + return read_review(&draft, &input); } ensure!(input.review_id.is_none(), "review_id requires view=review"); let mut result = self.0.drafts.review( @@ -344,7 +384,7 @@ impl Panache { #[tool( annotations(open_world_hint = false), - description = "view=review returns paper, finished appearance, overlay and full-page evidence. With compare_revision alone it reads stored data, review IDs, intervening edits and limitations. With region it renders labeled local crops in native image coordinates and measures visible changes; add compare_revision for paired before/after, and previous_region for the old location of moved content. Use a separate region to inspect protected content. view=layout returns glyph IDs and base boxes [x,y,width,height], paginated by offset/limit. Use region to select current glyph centers, illustrations_only for diagrams. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline. view=paper returns the saved background." + description = "A full-page view=review renders and records a check. To look up an existing check without rendering use read_section(view=review, section, page). view=review returns paper, finished appearance, overlay and full-page evidence. With compare_revision alone it reads stored data, review IDs, intervening edits and limitations. With region it renders labeled local crops in native image coordinates and measures visible changes; add compare_revision for paired before/after, and previous_region for the old location of moved content. Use a separate region to inspect protected content. view=layout returns glyph IDs and base boxes [x,y,width,height], paginated by offset/limit. Use region to select current glyph centers, illustrations_only for diagrams. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline. view=paper returns the saved background." )] async fn preview_handwriting( &self, diff --git a/crates/panache-mcp/tests/review_comparison.py b/crates/panache-mcp/tests/review_comparison.py index 5a6038c3..0edcc898 100644 --- a/crates/panache-mcp/tests/review_comparison.py +++ b/crates/panache-mcp/tests/review_comparison.py @@ -278,6 +278,14 @@ def assets(): and bottom["limitation"] == "insufficient_ridge_support" ) await tune(4, changes={"ink_opacity": 0}) + inventory = assets() + for _ in range(2): + empty = await call(client, "read_section", **key, view="review", section=1, page=1) + assert empty.structuredContent["status"] == "no_recorded_review" + assert empty.structuredContent["revision"] == empty.structuredContent["latest_draft_revision"] == 5 + assert empty.structuredContent["review_id"] is None + assert all(block.type == "text" for block in empty.content) + assert assets() == inventory assert "missing_after_review" in (await compare(4, 5))["comparison"]["limitations"] assert "photo_appearance" in await review(5) invisible = (await compare(4, 5))["comparison"]["delta"] diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 12564d81..1b471d3b 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -404,6 +404,20 @@ async def progress(value, total, message=None): retrieved = (await call(client, "read_section", **comparison_key, view="review", review_id=reviewed_id)).structuredContent assert retrieved["revision"] == 3 and retrieved["section"] == retrieved["page"] == 1 assert retrieved["feedback"] == [{"origin":"user_quote","text":user_quote}] + lookup = dict(**comparison_key, view="review", page=1) + receipt = await call(client, "read_section", **lookup, revision=3) + assert receipt.structuredContent == {**retrieved, "latest_draft_revision": 6} + older = await call(client, "read_section", **comparison_key, view="review", review_id=reviewed_id) + assert json.loads(older.content[0].text) == retrieved == older.structuredContent + assert "revision=6, section=1, page=1" in older.content[1].text + assert f"检查单号 {reviewed_id}" in receipt.content[0].text + for args in (dict(**lookup, revision=3, section=2), dict(**gkey, view="review", page=1, revision=1)): + missing = (await call(client, "read_section", **args)).structuredContent + assert missing["status"] == "no_recorded_review" and missing["review_id"] is None + assert missing["draft_id"] == args["draft_id"] and missing["revision"] == args["revision"] + for args in ({**lookup, "review_id": reviewed_id}, {**lookup, "view": "trajectory"}, + {**lookup, "page": 0}, {**lookup, "section": 0}, {**lookup, "limit": 1}): + assert (await client.call_tool("read_section", args)).isError assert (await call(client,"read_section",**comparison_key,view="summary")).structuredContent["revision"] == 6 events = (await call(client,"read_section",**comparison_key,view="trajectory",limit=50)).structuredContent["events"] assert {e["origin"] for e in events} >= {"draft_edit","measurement","user_quote","model_observation"}