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 @@ -2,6 +2,7 @@

## 未发布

- MCP 导出时可选记录宿主实际采用的作业经验 ID,便于按交付文件区分「查到」和「声明用过」。按经验 ID 可查宿主自报的采用次数和最近的交付版本,不代表经验有效。
- 照片稿整页复查在有可比纸面线索时提示查找适用的新增墨迹控制,缺少纸面投影时明确说明原因。
- 已建立纸面投影的照片稿可在 MCP 中选择让新增笔迹随局部纸色调整,或按原照上的两个点渐变柔化。两项默认关闭,不改动底纸,适用于预览及 PDF 和 PNG 导出。
- 修复已有精细编辑的稿件在表格避让更新后静默移位或换页;旧稿继续使用原布局,新稿仍按表格避让排版。
Expand Down
25 changes: 13 additions & 12 deletions app/test/workspace_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ class MemoryStorage implements WorkspaceStorage {
}

class ControlledApi extends HandwritingApi {
ControlledApi() : super('http://example.invalid');
ControlledApi({this.fineEdit = false}) : super('http://example.invalid');
final bool fineEdit;
final submission = Completer<String>();
Map<String, String>? submittedFields;
final rendered = Completer<List<Uint8List>>();
Expand All @@ -36,8 +37,12 @@ class ControlledApi extends HandwritingApi {
@override
bool get supportsCancel => true;
@override
Future<dynamic> getJson(String path) async =>
path == '/api/fonts_info' ? ['test.ttf'] : {'version': 'test'};
Future<dynamic> getJson(String path) async => path == '/api/fonts_info'
? ['test.ttf']
: {
'version': 'test',
'capabilities': {'fine_edit': fineEdit},
};
@override
Future<String> submit(
Map<String, String> fields,
Expand Down Expand Up @@ -243,28 +248,24 @@ void main() {
'fineEdits': {
'key': key,
'glyphs': [
{
'id': 1,
'dx': 4,
'dy': 0,
'scale': 100,
'angle': 0,
'opacity': 100,
},
{'id': 1, 'dx': 4, 'dy': 0, 'scale': 100, 'angle': 0, 'opacity': 100},
],
},
});
final api = ControlledApi()..supportsFineEdit = true;
final api = ControlledApi(fineEdit: true);
final w = Workspace(api: api, storage: storage);
addTearDown(w.dispose);
await w.initialize();

final preview = w.generate();
expect(api.submittedFields?['fine_edit'], 'true');
expect(jsonDecode(api.submittedFields!['fine_edits']!), {
'key': key,
'glyphs': [],
});
api.submission.complete('preview-task');
await api.previewRequested.future;
api.rendered.complete([]);
expect(await preview, isTrue);
});

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 @@ -246,6 +246,10 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/

普通作业导出后,`experience_reflection` 附上 `export_id` 和最多八个已检查页面的引用。如果同一页在之前的版本也有原生检查单,`earlier_reference` 会指向最近的已检查旧版。更多页面可通过 `read_section(view="review")` 查回。

需要记录经验是否真的用在交付版时,可以在 `export_handwriting` 传可选的 `applied_experience_ids`(最多 16 个)。只填宿主已经按适用条件采用的经验,搜到但没用过的不填,也不必为这个字段额外检索。省略表示「未报告」;传 `[]` 表示「明确没用」。发布成功后,`experience_application` 回执说明实际保存的 ID(`basis="host_report"`)和忽略的项数。重复、未生效、已撤回或未知的 ID 不保存;全部无效或超出上限时不写采用记录,仍正常导出。记录按 `export_id` 关联到确切稿件和版本;它不改成稿、经验状态或检索排序,也不能证明经验带来了收益。

已知经验 ID 时,`read_homework_experience` 的 `applications` 返回 `basis="host_report"`、声明采用这条经验的已发布导出数 `reported_exports`,以及最近最多 20 次的 `items`(`export_id`、`draft_id`、`revision` 和分页用的 `seq`)。同一导出重复填同一 ID 只计一次;同一版本的两次导出分别计数。把这一页的 `applications.next_after` 传给 `applications_after` 可看更早的交付,原有 `after` 仍只翻验证记录 `cases`。退役不会擦掉历史声明;零条声明不等于从来没用。只有按 ID 审计时能看到这项统计,不进入检索结果或排序。

- **一条经验写一个可单独验证的动作。** 宿主填写适用标签 `tags`、具体条件 `scope`、动作 `action`、结合页面观察写出的理由 `reason`、该条自己的检查单 `reviews`。同一道题若有两个独立问题,可拆成两条,分别验证、检索和退役。拆分粒度由宿主判断。每次调用可传 0–16 条。同标签、条件和动作的重复提案复用原 ID。
- **有修前、修后检查单时,在最终答复前提交复盘决定。** 调用 `record_homework_experience`,逐条引用本次导出和交付版检查单,可附同稿旧版。只有本题的数值或笔误可传 `rules=[]`。干净完成的作业也可以直接交付。工具返回每条的 ID 和状态;宿主可以向用户简述刚记录的做法及其待验证状态。
- **下次用新作业的原话或主题直接搜条目。** 持有 ID 时可用 `read_homework_experience` 审计来源及逐次验证。不同会话共享同一个 Panache 数据目录时可见同一经验库。
Expand Down
12 changes: 11 additions & 1 deletion crates/panache-mcp/src/experience.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Evidence-backed, individually retrievable guidance from ordinary homework deliveries.
pub(crate) mod application;
mod fulltext;
mod opportunity;
#[cfg(test)]
Expand All @@ -13,7 +14,7 @@ use serde_json::{Value, json};
use std::collections::BTreeSet;
use uuid::Uuid;

pub(crate) fn initialize(db: &Connection) -> Result<()> {
pub(crate) fn initialize(db: &rusqlite::Transaction<'_>) -> Result<()> {
db.execute_batch("
CREATE TABLE IF NOT EXISTS experience_rules (
id TEXT PRIMARY KEY, signature TEXT NOT NULL UNIQUE, scope TEXT NOT NULL,
Expand All @@ -33,6 +34,7 @@ pub(crate) fn initialize(db: &Connection) -> Result<()> {
ON experience_cases(rule_id,draft,revision,reviews) WHERE role='source';
CREATE INDEX IF NOT EXISTS experience_cases_by_rule ON experience_cases(rule_id,seq);
")?;
application::initialize(db)?;
fulltext::initialize(db)
}

Expand Down Expand Up @@ -90,6 +92,9 @@ pub struct Read {
/// Exclusive evidence sequence cursor from a previous read.
#[serde(default)]
after: u64,
/// Exclusive host-reported application cursor from applications.next_after. Pages only
/// applications, newest first; counts are declarations, not evidence or search ranking.
applications_after: Option<u64>,
}

#[derive(Copy, Clone, Deserialize, JsonSchema)]
Expand Down Expand Up @@ -474,6 +479,11 @@ impl Drafts {
Value::Null
};
rule["cases"] = json!(cases);
rule["applications"] = serde_json::to_value(application::read(
&tx,
&input.rule_id,
input.applications_after,
)?)?;
Ok(rule)
}
}
136 changes: 136 additions & 0 deletions crates/panache-mcp/src/experience/application.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//! Optional host declarations, separate from rule evidence and ranking.
use anyhow::Result;
use rusqlite::{Transaction, params};
use serde::Serialize;
use std::collections::BTreeSet;

const MAX_IDS: usize = 16;

#[derive(Serialize)]
pub(crate) struct Report {
basis: &'static str,
recorded: bool,
applied_experience_ids: Vec<String>,
ignored_count: usize,
}

pub(super) fn initialize(db: &Transaction<'_>) -> Result<()> {
db.execute_batch(
"CREATE TABLE IF NOT EXISTS experience_application_reports(
export_id TEXT PRIMARY KEY,
ignored_count INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS experience_applications(
seq INTEGER PRIMARY KEY,
export_id TEXT NOT NULL REFERENCES experience_application_reports(export_id),
rule_id TEXT NOT NULL REFERENCES experience_rules(id),
UNIQUE(export_id,rule_id)
);
CREATE INDEX IF NOT EXISTS experience_applications_by_rule
ON experience_applications(rule_id,seq,export_id);",
)?;
Ok(())
}

#[derive(Serialize)]
pub(super) struct Applications {
basis: &'static str,
reported_exports: i64,
items: Vec<Application>,
next_after: Option<i64>,
}

#[derive(Serialize)]
struct Application {
seq: i64,
export_id: String,
draft_id: String,
revision: u32,
}

pub(super) fn read(
db: &Transaction<'_>,
rule_id: &str,
after: Option<u64>,
) -> Result<Applications> {
// Count and page on the same SQLite snapshot as the rule and its evidence.
let reported_exports = db.query_row(
"SELECT count(*) FROM experience_applications a
CROSS JOIN export_files e ON e.id=a.export_id
WHERE a.rule_id=? AND e.published=1",
[rule_id],
|row| row.get(0),
)?;
let mut stmt = db.prepare(
"SELECT a.seq,a.export_id,e.draft,e.revision FROM experience_applications a
CROSS JOIN export_files e ON e.id=a.export_id
WHERE a.rule_id=? AND a.seq<? AND e.published=1 ORDER BY a.seq DESC LIMIT 21",
)?;
let mut items = stmt
.query_map(
params![
rule_id,
after.map(i64::try_from).transpose()?.unwrap_or(i64::MAX)
],
|row| {
Ok(Application {
seq: row.get(0)?,
export_id: row.get(1)?,
draft_id: row.get(2)?,
revision: row.get(3)?,
})
},
)?
.collect::<rusqlite::Result<Vec<_>>>()?;
let more = items.len() > 20;
items.truncate(20);
Ok(Applications {
basis: "host_report",
reported_exports,
next_after: if more {
items.last().map(|item| item.seq)
} else {
None
},
items,
})
}

/// Call during publication. A malformed or stale declaration cannot prevent the file delivery.
pub(crate) fn record(db: &Transaction<'_>, export_id: &str, ids: &[String]) -> Result<Report> {
let mut report = Report {
basis: "host_report",
recorded: false,
applied_experience_ids: Vec::new(),
ignored_count: ids.len(),
};
if ids.len() <= MAX_IDS {
let mut seen = BTreeSet::new();
let mut exists = db.prepare(
"SELECT EXISTS(SELECT 1 FROM experience_rules WHERE id=? AND status='active')",
)?;
for id in ids {
if uuid::Uuid::parse_str(id).is_ok()
&& seen.insert(id)
&& exists.query_row([id], |row| row.get::<_, bool>(0))?
{
report.applied_experience_ids.push(id.clone());
}
}
report.ignored_count -= report.applied_experience_ids.len();
if ids.is_empty() || !report.applied_experience_ids.is_empty() {
db.execute(
"INSERT INTO experience_application_reports(export_id,ignored_count)
VALUES(?,?)",
params![export_id, u32::try_from(report.ignored_count)?],
)?;
let mut insert =
db.prepare("INSERT INTO experience_applications(export_id,rule_id) VALUES(?,?)")?;
for id in &report.applied_experience_ids {
insert.execute(params![export_id, id])?;
}
report.recorded = true;
}
}
Ok(report)
}
4 changes: 4 additions & 0 deletions crates/panache-mcp/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,10 @@ pub struct Export {
/// Up to 512 KiB before base64 encoding. Larger files stay available at the returned server path.
#[serde(default)]
pub include_file: bool,
/// Optional host report: list only active homework experience IDs whose advice you actually used
/// in this delivered revision (at most 16). Search results alone do not count.
/// Omit if not reporting, or pass [] to report that none were used. Do not search just to fill this field.
pub applied_experience_ids: Option<Vec<String>>,
}

#[derive(Clone, Copy, Deserialize, JsonSchema, PartialEq, serde::Serialize)]
Expand Down
8 changes: 6 additions & 2 deletions crates/panache-mcp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ impl Panache {

#[tool(
annotations(read_only_hint = true, open_world_hint = false),
description = "Audit one known rule by ID, including pending, rejected or retired status, original evidence and independent validations. Use search_homework_experience for current task instructions."
description = "Audit one known rule by ID, including pending, rejected or retired status, original evidence and independent validations. Applications are host reports of published exports, not evidence of effectiveness. Use search_homework_experience for current task instructions."
)]
async fn read_homework_experience(
&self,
Expand Down Expand Up @@ -879,7 +879,8 @@ impl Panache {
let mut different = Vec::new();
let params = controls::parameters(&draft, 1, &draft.controls)?;
let zero_text_ink = params.ink_opacity == 0 || params.fill[3] == 0;
let storage::PublishedExport {id: export_id, path, pages, file} = state.storage.export(&state.drafts,draft.id,draft.revision,format, |writer| engine.export(
let storage::PublishedExport {id: export_id, path, pages, file, application} = state.storage.export(
&state.drafts, draft.id, draft.revision, format, input.applied_experience_ids.as_deref(), |writer| engine.export(
writer, &draft, sections, (format, active_finish), cancel,
|pages, section, page, image| {
match reviewed_pages.get(&(section, page)) {
Expand Down Expand Up @@ -967,6 +968,9 @@ impl Panache {
if matches!(format, Format::Zip) && let Some(finish @ engine::export_blur::Finish::Gradient(_)) = finish {
finish.write_metadata(&mut metadata);
}
if let Some(application) = application {
metadata["experience_application"] = serde_json::to_value(application)?;
}
let mut result = reply(message, metadata);
if input.include_file {
delivery::include_file(&mut result, file, &path, format);
Expand Down
25 changes: 19 additions & 6 deletions crates/panache-mcp/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ mod cleanup;
mod tests;
pub use cleanup::{ApplyCleanup, CleanupScope};

use crate::{Format, drafts::Drafts};
use crate::{Format, drafts::Drafts, experience::application};
use anyhow::{Context, Result, ensure};
use rusqlite::{Connection, params};
use schemars::JsonSchema;
Expand All @@ -25,6 +25,7 @@ pub(crate) struct PublishedExport {
pub path: PathBuf,
pub pages: usize,
pub file: File,
pub application: Option<application::Report>,
}

#[derive(Deserialize, JsonSchema)]
Expand Down Expand Up @@ -207,6 +208,7 @@ impl Storage {
draft: &str,
revision: u32,
format: Format,
applied_experience_ids: Option<&[String]>,
render: F,
) -> Result<PublishedExport>
where
Expand All @@ -217,7 +219,7 @@ impl Storage {
self.allowance()? > 0,
"Storage limit: no capacity for a new export; inspect storage_usage and plan_cleanup"
);
let db = drafts.connect()?;
let mut db = drafts.connect()?;
let id = Uuid::new_v4().to_string();
let extension = match format {
Format::Pdf => "pdf",
Expand All @@ -244,19 +246,30 @@ impl Storage {
};
let pages = render(&mut output)?;
output.flush()?;
let file = temp.persist_noclobber(&path)?;
db.execute("UPDATE export_files SET published=1 WHERE id=?", [&id])?;
Ok((pages, file))
let (file, application) = if let Some(ids) = applied_experience_ids {
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let report = application::record(&tx, &id, ids)?;
let file = temp.persist_noclobber(&path)?;
tx.execute("UPDATE export_files SET published=1 WHERE id=?", [&id])?;
tx.commit()?;
(file, Some(report))
} else {
let file = temp.persist_noclobber(&path)?;
db.execute("UPDATE export_files SET published=1 WHERE id=?", [&id])?;
(file, None)
};
Ok((pages, file, application))
};
let result = publish();
if result.is_err() && metadata(&path)?.is_none() {
db.execute("DELETE FROM export_files WHERE id=? AND published=0", [&id])?;
}
result.map(|(pages, file)| PublishedExport {
result.map(|(pages, file, application)| PublishedExport {
id,
path,
pages,
file,
application,
})
}

Expand Down
Loading
Loading