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

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

Expand Down
2 changes: 2 additions & 0 deletions crates/panache-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ 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`;旧版仍可回看。

`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
3 changes: 3 additions & 0 deletions crates/panache-mcp/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ pub struct Describe {
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Tune {
/// 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, 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<Vec<Guide>>,
/// Import an absolute local TTF/OTF file into this draft. Its bytes are retained across restarts.
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
21 changes: 18 additions & 3 deletions crates/panache-mcp/tests/smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,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 +638,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 +669,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 +741,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