Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## 未发布

- MCP 查旧检查单时可按新增原文定位上一版,并按该版实际排版查询指定节的末页。

- MCP 可按稿件版本、节号和页码只读找回已存的整页复盘;缺少记录时明确返回空结果。

## v1.21.0 (2026-11-24)
Expand Down
5 changes: 5 additions & 0 deletions crates/handwriting-core/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,11 @@ pub(crate) fn render_output<F: FnMut(usize, RgbaImage) -> Result<()>>(
})
}

/// Run the normal pagination pass, discarding each page before compositing or encoding.
pub fn count_pages(request: &RenderRequest, cancel: &Cancellation) -> Result<usize> {
render_pages(request, cancel, usize::MAX, |_, _, _| Ok(()))
}

pub(crate) fn render_pages(
r: &RenderRequest,
cancel: &Cancellation,
Expand Down
4 changes: 3 additions & 1 deletion crates/panache-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 复核最新内容再提交。

Expand Down
113 changes: 113 additions & 0 deletions crates/panache-mcp/src/drafts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,21 @@ pub struct Snapshot<'a> {
}

impl Snapshot<'_> {
pub fn review_section(&self, requested: Option<u32>) -> Result<u32> {
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<bool> {
Ok(self.drafts.connect()?.query_row(
"SELECT EXISTS(SELECT 1 FROM draft_fonts WHERE draft=? AND handle=?)",
Expand Down Expand Up @@ -309,6 +324,104 @@ impl Drafts {
.collect::<rusqlite::Result<Vec<_>>>()?;
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<Vec<String>> {
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::<Vec<_>>()
.join(" ");
choices.push(format!("section={number} {}", json!(text)));
}
Ok(choices)
}

/// Find a single transition from absent to present across all versions of all sections.
pub fn text_introduction(&self, id: &str, text: &str) -> Result<(u32, u32)> {
ensure!(
!text.trim().is_empty() && text.chars().count() <= 160,
"before_text needs 1..160 characters from the saved Markdown"
);
let db = self.connect()?;
let mut statement = db.prepare(
"WITH versions AS (
SELECT number,revision,instr(source,?2)>0 AS present
FROM sections WHERE draft=?1
), changes AS (
SELECT number,revision,present,
lag(present,1,0) OVER (PARTITION BY number ORDER BY revision) AS previously_present
FROM versions
)
SELECT number,revision FROM changes WHERE present AND NOT previously_present
ORDER BY revision,number LIMIT 3",
)?;
let matches = statement
.query_map(params![id, text], |row| {
Ok((row.get::<_, u32>(0)?, row.get::<_, u32>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
let &(section, revision) = matches.first().context(
"No section contains before_text. Read the source for a literal fragment or specify a revision."
)?;
if matches.len() > 1 {
let mut message = String::from(
"这段原文有多个加入时点。请让用户确认是首次加入之前,还是后来再次加入之前;也可分别核对并逐版列出,未确认时不要代选。",
);
let same_section = matches[0].0 == matches[1].0;
for (number, added) in matches.iter().take(2) {
if same_section {
message.push_str(&format!("\n第 {added} 版加入了这段原文。"));
} else {
message.push_str(&format!("\n第 {added} 版在第 {number} 节加入了这段原文。"));
}
if *added == 1 {
message.push_str("这是初稿,之前没有稿件。");
} else {
let before = added - 1;
let choices = self.review_section_choices(id, before)?;
message.push_str(&format!(
"加入前查 revision={before};该版可查的正文:{}",
choices.join(" · ")
));
}
}
if matches.len() > 2 {
message.push_str(
"\n这里只列最早两次,另有加入时点。可通过 trajectory 和 source 核对。",
);
}
anyhow::bail!(
"{message}\n所补文字只用来认版本。请按用户要查的正文选择 section,保留 page,移除 before_text 后按明确版本查单。"
);
}
ensure!(
revision > 1,
"before_text already occurs in the first revision; no earlier draft exists."
);
Ok((section, revision))
}

pub fn snapshot<'a>(&'a self, id: &'a str, requested: Option<u32>) -> Result<Snapshot<'a>> {
let (latest, style, layout): (u32, String, Option<String>) = self
.connect()?
Expand Down
19 changes: 19 additions & 0 deletions crates/panache-mcp/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32> {
let (_, edits) = draft.edits(&section)?;
// 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<RenderRequest> {
let (_, edits) = draft.edits(&section)?;
let projected = draft.paper.as_ref().is_some_and(|p| p.projection.is_some());
Expand Down
21 changes: 19 additions & 2 deletions crates/panache-mcp/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,29 @@ 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<u32>,
/// 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<ReviewPage>,
/// For a page review just before an addition: an exact, distinctive fragment of the added Markdown.
/// Uses the revision immediately before its unique introduction; repeated introductions are ambiguous. Omit revision.
pub before_text: Option<String>,
/// With view=review, retrieve one immutable measurement and its attributed feedback by ID instead of page.
pub review_id: Option<String>,
/// With trajectory, pass next_cursor to continue the same snapshot, including its filters. Omit offset.
Expand Down
Loading
Loading