Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- MCP 客户端指南增加只翻旧检查记录的工具选择和调用示例。
- MCP 查旧检查单时可按新增原文定位上一版,并按该版实际排版查询指定节的末页。
- MCP 在作业和实验报告的笔迹建议中区分松散笔迹与偶发涂改,指明对应调节项和预览方法。
- MCP 调参可传 `preserve_local_adjustments=true`,在全稿重排影响已有字形调整时保留当前版本。

## v1.21.0 (2026-11-24)

Expand Down
4 changes: 4 additions & 0 deletions crates/panache-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ cargo build --locked --release -p panache-mcp

如果字像贴在照片上,在照片整页复查的 `photo_appearance` 中取 `preview_arguments` 再调用一次 `preview_handwriting`。有页内文字基线样本时,这组参数会给出该版本一处字迹附近的原像素底纸和成品裁图;也可以自己圈选。对照邻近印字或横线的边缘清晰度、墨色深浅,再看字号与可写空间是否相称。用 `describe_controls` 指定稿件、版本和 `ink`、`layout` 或 `typography` 参数组可查当前值。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比。仅修改墨迹组参数时会保留已完成的单字移位和透视调整;更换字体、字号或参考线后应在新版本重新检查选区。改一版后,对同一选区加入 `compare_revision` 比较。只有文字结果的客户端可转述测量,请用户看图判断观感。

需要保留手动移字时,在 `tune_handwriting` 顶层传入 `preserve_local_adjustments=true`。例如,稿件中仍有字形调整时,更改 `variation.perturb_theta_sigma` 会返回一个受影响的节号,稿件停留在原版本。只更改墨迹或相机元数据仍可保存。被拒绝后应保持 `true`。只有用户明确同意新布局不再应用这些手动调整时,才可传 `false`;旧版仍可回看。

例如,先前已确认行距 56、左边距 67,后来要求恢复导入时的参考线并保留这两个数值。在同一次调用中传 `paper_guides=[]` 和 `changes={"line_spacing":56,"left_margin":67}`;想让文字重新跟随底纸时,省略相应数值。如果之前摆好的字也必须留在原位,再传 `preserve_local_adjustments=true`。补回行距和边距仍会触发重排;若保护生效,整次请求停在原版本。

`tune_handwriting(font_path=…)` 会把本机 TTF/OTF 随稿保存。可用返回的字体标识在同一稿内切回该字体。墨迹组的 `transparent_background` 控制原尺寸 PNG 预览和 ZIP,PDF 保留纸张。透明稿复盘会把墨迹放回底纸,方便判断实际可读性。

### 比较两版,找回当时的依据
Expand Down
53 changes: 52 additions & 1 deletion crates/panache-mcp/src/drafts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use uuid::Uuid;
use crate::Style;
use crate::paper::{ImportedPaper, PaperLayout};

const REVISION_CONFLICT: &str = "Revision conflict; read the latest revision before retrying";

pub struct Drafts(PathBuf);

#[cfg(test)]
Expand Down Expand Up @@ -43,6 +45,30 @@ fn concurrent_first_opens_share_a_complete_schema() -> Result<()> {
})
}

#[cfg(test)]
#[test]
fn glyph_edit_committed_after_preflight_wins_the_revision() -> Result<()> {
let home = tempfile::tempdir()?;
let drafts = Drafts::open(home.path())?;
let save = serde_json::from_value(json!({"markdown":"字"}))?;
let saved = drafts.save(&save, "字", Some(&Style::default()), None, None)?;
let draft = drafts.snapshot(saved["draft_id"].as_str().unwrap(), Some(1))?;
draft.require_unadjusted_layout()?;

// Commit another writer's glyph edit between the guard and the settings write.
let edits = serde_json::from_value(json!({"key":"test","glyphs":[
{"id":0,"dx":12,"dy":0,"scale":100,"angle":0,"opacity":100,"color":null}
]}))?;
assert_eq!(draft.store_edits(1, 1, &edits, &Value::Null)?, 2);
let result = drafts.tune(&draft, &draft.controls, false, None, None, &Value::Null);
assert_eq!(result.unwrap_err().to_string(), REVISION_CONFLICT);
let current = drafts.snapshot(draft.id, None)?;
assert_eq!(current.revision, 2);
assert_eq!(current.settings_revision, 0);
assert!(current.require_unadjusted_layout().is_err());
Ok(())
}

pub struct Snapshot<'a> {
pub latest_revision: u32,
pub revision: u32,
Expand Down Expand Up @@ -144,6 +170,31 @@ impl Snapshot<'_> {
}
}

pub fn require_unadjusted_layout(&self) -> Result<()> {
ensure!(self.revision == self.latest_revision, "{REVISION_CONFLICT}");
// This query reads immutable history. Drafts::advance rejects a write racing the preflight.
let section: Option<u32> = self
.drafts
.connect()?
.query_row(
"SELECT e.section FROM glyph_edits e
WHERE e.draft=?1 AND e.settings_revision=?2 AND e.revision<=?3
AND e.source_revision=(SELECT MAX(s.revision) FROM sections s
WHERE s.draft=e.draft AND s.number=e.section AND s.revision<=?3)
LIMIT 1",
params![self.id, self.layout_revision, self.revision],
|row| row.get(0),
)
.optional()?;
if let Some(section) = section {
anyhow::bail!(
"Reflow would stop applying local glyph adjustments in section {section} of revision {}. This request saved no new revision. Keep preserve_local_adjustments=true. Only if the user explicitly agrees to lose those adjustments in the new layout may you use preserve_local_adjustments=false.",
self.revision
);
}
Ok(())
}

pub fn store_edits(
&self,
section: u32,
Expand Down Expand Up @@ -554,7 +605,7 @@ impl Drafts {
"UPDATE drafts SET revision=?1 WHERE id=?2 AND revision=?3",
params![next, id, expected]
)? == 1,
"Revision conflict; read the latest revision before retrying"
"{REVISION_CONFLICT}"
);
Ok(next)
}
Expand Down
7 changes: 6 additions & 1 deletion crates/panache-mcp/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,12 @@ 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.
/// Set to true only when the user wants to preserve manual glyph adjustments. Reject reflow that would stop applying them. Ink and camera changes can still be saved.
#[serde(default)]
pub preserve_local_adjustments: bool,
/// Replace the writing area on the saved paper with 2..32 photo-space baselines. Use the top and bottom writable lines even on unruled paper. Pass [] to restore the original import calibration. Existing text is reflowed.
/// Setting guides (including []) clears saved top_margin, bottom_margin, left_margin, right_margin, and text line_spacing unless those keys are included in changes in the same call.
/// To keep specific overrides, resend only their approved saved values in changes; omit them to inherit from the paper. Restoring those numbers still reflows hand-placed text. If its placement must stay, also set preserve_local_adjustments=true. If refused, leave the draft as it is.
pub paper_guides: Option<Vec<Guide>>,
/// Import an absolute local TTF/OTF file into this draft. Its bytes are retained across restarts.
pub font_path: Option<std::path::PathBuf>,
Expand Down
2 changes: 1 addition & 1 deletion crates/panache-mcp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ impl Panache {
}

#[tool(
description = "Revise a draft: change controls, import a local font_path, or replace paper_guides on its saved image. Map the intended area onto first/last writable baselines even on artwork or unruled paper. Ink-group changes preserve local glyph placement; after changing font, size or guides, inspect the new layout. Use view=image to inspect the result when the user wants to preserve checks."
description = "Revise a draft's controls, font_path or paper_guides. If the user wants earlier hand-placed text kept in place, pass preserve_local_adjustments=true on this call. Ink-only changes keep placement. Map the writing area onto the first/last writable baselines even on artwork or unruled paper. After a font, size or guide change, inspect the new layout. Use view=image to inspect without filing a check."
)]
async fn tune_handwriting(&self, Parameters(input): Parameters<Tune>) -> CallToolResult {
let state = self.0.clone();
Expand Down
3 changes: 3 additions & 0 deletions crates/panache-mcp/src/tuning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ pub fn apply(state: &State, mut input: Tune) -> Result<CallToolResult> {
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();
if input.preserve_local_adjustments && !preserve_layout {
draft.require_unadjusted_layout()?;
}
let _budget = font
.as_ref()
.map(|(_, bytes)| state.storage.import(bytes.len()))
Expand Down
33 changes: 29 additions & 4 deletions crates/panache-mcp/tests/smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,17 @@ async def review_workflow(client, key, guides, font_path):
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=[])
# Keeping the numeric layout cannot carry hand-placed glyphs across a guide reset.
controls = (await call(client, "describe_controls", **key, group="layout")).structuredContent["values"]
reset = dict(**key, expected_revision=8, paper_guides=[])
protected = await client.call_tool("tune_handwriting", {
**reset, "preserve_local_adjustments": True,
"changes": {name: controls[name] for name in ("line_spacing", "left_margin")},
})
assert protected.isError and "section 1 of revision 8" in protected.content[0].text
current = (await call(client, "preview_handwriting", **key, view="layout", limit=1)).structuredContent
assert current["glyphs"][0]["current_photo_quad"] == geometry["glyphs"][0]["current_photo_quad"]
await call(client, "tune_handwriting", **reset)
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
Expand Down Expand Up @@ -143,7 +153,7 @@ async def handwriting_variation_sample(client):
rejected = await client.call_tool("tune_handwriting", {**key, "expected_revision": 1, "changes": invalid})
assert rejected.isError
tuned = await call(client, "tune_handwriting", **key, expected_revision=1,
changes={"variation": {"perturb_theta_sigma": 0.07}})
preserve_local_adjustments=True, changes={"variation": {"perturb_theta_sigma": 0.07}})
assert tuned.structuredContent["controls"]["perturb_theta_sigma"] == 0.07
loose = png(await call(client, "preview_handwriting", **key))
assert loose != base
Expand Down Expand Up @@ -638,8 +648,20 @@ async def progress(value, total, message=None):
).structuredContent
with ZipFile(exported_fine["path"]) as pages:
assert pages.read("0.png") == adjusted
blocked = await client.call_tool("tune_handwriting", {
"draft_id": paper_id, "expected_revision": 3, "preserve_local_adjustments": True,
"changes": {"variation": {"perturb_theta_sigma": 0.07}},
})
assert blocked.isError
assert blocked.content[0].text == (
"Reflow would stop applying local glyph adjustments in section 1 of revision 3. "
"This request saved no new revision. Keep preserve_local_adjustments=true. "
"Only if the user explicitly agrees to lose those adjustments in the new layout "
"may you use preserve_local_adjustments=false."
)
camera_change = await call(client, "tune_handwriting", draft_id=paper_id,
expected_revision=3, changes={"camera_model": "Test Camera", "camera_iso": 200})
expected_revision=3, preserve_local_adjustments=True,
changes={"camera_model": "Test Camera", "camera_iso": 200})
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
Expand All @@ -657,7 +679,7 @@ async def progress(value, total, message=None):
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)
expected_revision=rev, changes=patch, preserve_local_adjustments=True)
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"]
Expand Down Expand Up @@ -729,6 +751,9 @@ async def progress(value, total, message=None):
await call(client, "preview_handwriting", **probe)
).structuredContent
assert all("adjustment" not in g for g in refreshed["glyphs"])
reflow = await call(client, "tune_handwriting", draft_id=paper_id, expected_revision=8,
changes={"perturb_theta_sigma": 0.07}, preserve_local_adjustments=True)
assert reflow.structuredContent["revision"] == 9
assert (
png(
await call(
Expand Down