feat(mlsp): M6 T1 会话内陈旧检测 — repair_apply 前后对照 + session.summary
机制:repair_apply 内同一作用域已同时持有 source(改前) 与 new_source(改后),
所以「描述是否还成立」可纯内存判定,无需 git/台账/exec:
stale ⟺ 标签文本未变 ∧ payload 指纹变了
按 (标签文本, 出现序号) 配对 → 移动代码不误报。
协议:
请求加可选 check_labels(默认 false,零开销零噪音)
响应加 labels.stale[{label,line,code_past,code_now}] + newly_seen
新增 session.summary → {labels_stale_seen, labels_fixed, labels_outstanding, items},
返回后清零(客户端收尾调用一次即闭合,不主动打屏)
取舍:
- 标签变了 → 不报(作者改描述即"已复核"信号)
- 新标签 → 不报(无历史可比)
- 指纹用 Debug:只需进程内一致;跨版本稳定指纹留给 T2/T3
- code_past/code_now 用 view::expr_display 渲染成人可读的表面语法
实测:
改 payload 0.1→0.2、标签不变 → stale 且带 code_past="100 * 0.1" / code_now="100 * 0.2"
同时改标签 → stale: []
session.summary → stale_seen=1, outstanding=1, items=["按税率算总价"]
测试:3 个集成(含反向验证"改描述即复核不误报");
全量 cargo test --release:590 passed / 0 failed(M10 后 587 + 3)
文档:doc/design/change-m6-t1-session.md
This commit is contained in:
1 parent
1c90312c02
commit
6bba0be6d2
5 files changed
+350
-1
No files matched your search
@@ -0,0 +1,109 @@
|
||||
# 变更记录:M6 T1 会话内陈旧检测 + 会话末汇总
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Implemented** |
|
||||
| 日期 | 2026-10-22 |
|
||||
| 里程碑 | M6([t1-session-staleness.md](t1-session-staleness.md) · [staleness-providers.md](staleness-providers.md) T1) |
|
||||
| 改动文件 | `src/label.rs` · `src/mlsp.rs` · `src/view/mod.rs` · `tests/occlusion.rs` |
|
||||
| 影响面 | MLSP `repair_apply` 新增可选字段;新增 `session.summary` 方法 |
|
||||
|
||||
---
|
||||
|
||||
## 1. 机制
|
||||
|
||||
`repair_apply` 内部同一作用域里同时有 `source`(改前)与 `new_source`(改后),
|
||||
所以「描述是否还成立」可以**纯内存**判定:
|
||||
|
||||
```
|
||||
stale ⟺ 标签文本未变 ∧ payload 指纹变了
|
||||
```
|
||||
|
||||
配对按 `(标签文本, 出现序号)`,因此**移动代码不会误报**。
|
||||
|
||||
请求:
|
||||
|
||||
```json
|
||||
{"method":"repair_apply","params":{
|
||||
"source":"…","ranges":[[3,3]],
|
||||
"edits":[{"op":"replace","line":3,"text":"**a = [按税率算总价](100 * 0.2)**"}],
|
||||
"check_labels":true}}
|
||||
```
|
||||
|
||||
响应:
|
||||
|
||||
```json
|
||||
{"id":1,"ok":true,"result":{
|
||||
"source":"…","edits_applied":1,
|
||||
"labels":{"newly_seen":1,"stale":[
|
||||
{"label":"按税率算总价","line":3,
|
||||
"code_past":"100 * 0.1","code_now":"100 * 0.2"}]}}}
|
||||
```
|
||||
|
||||
**同一份 `source` / `new_source` 就是"前一状态"**——不需要 git、不需要台账、
|
||||
不需要沙箱里的 exec 权限。这是"agent 回路不需要 VCS"的落地。
|
||||
|
||||
---
|
||||
|
||||
## 2. 会话末汇总(你要求做)
|
||||
|
||||
`session.summary` 返回并**重置**计数:
|
||||
|
||||
```json
|
||||
{"ok":true,"labels_stale_seen":1,"labels_fixed":0,
|
||||
"labels_outstanding":1,"items":["按税率算总价"]}
|
||||
```
|
||||
|
||||
| 字段 | 含义 |
|
||||
|------|------|
|
||||
| `labels_stale_seen` | 本次会话累计发现过多少条(去重按标签) |
|
||||
| `labels_fixed` | 曾经 outstanding、现在不再 stale 的条数 |
|
||||
| `labels_outstanding` | 仍未处理 |
|
||||
| `items` | 未处理的标签文本(只给文本,不重复诊断细节) |
|
||||
|
||||
设计:客户端在收尾时调用一次即可闭合;**不主动打屏**,不污染协议。
|
||||
|
||||
---
|
||||
|
||||
## 3. 关键取舍
|
||||
|
||||
| 取舍 | 理由 |
|
||||
|------|------|
|
||||
| `check_labels` 默认 **false** | 零开销、零噪音;agent 框架在修复回路里显式打开 |
|
||||
| 标签变了 → **不报** | 作者改描述本身就是"已复核"的信号 |
|
||||
| 新标签 → 不报 | 无历史可比 |
|
||||
| 指纹用 `Debug` | **只需进程内一致**;跨版本稳定指纹是 T2/T3 的事 |
|
||||
| payload 渲染用 `view::expr_display` | 让 `code_past/code_now` 是人能读的表面语法,而非 AST 调试串 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 测试
|
||||
|
||||
| 层 | 内容 | 结果 |
|
||||
|----|------|------|
|
||||
| 集成(3) | 只改 payload → `stale` 含 `code_past`/`code_now`;同时改标签 → `stale: []`;`session.summary` 计数正确 | ✅ |
|
||||
| 全量 | `cargo test --release` | **590 passed / 0 failed**(M10 后 587 + 3) |
|
||||
|
||||
**反向验证**:`t1_silent_when_label_also_changes` 证明"改描述即复核"不会误报。
|
||||
|
||||
---
|
||||
|
||||
## 5. 边界
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 只看本次编辑 | 跨会话漂移是 T2/T3 的职责(可选 provider) |
|
||||
| 解析失败则跳过 | 修复后的源码可能语法错误,此时不评测标签,交给 `validate` |
|
||||
| 会话状态是进程级 | 一条 MLSP 连接(一个进程)即一个会话;`session.summary` 后清零 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 变更清单
|
||||
|
||||
| 文件 | 变更 |
|
||||
|------|------|
|
||||
| `src/label.rs` | `StaleItem` · `payload_fingerprint` · `compare` · `SessionSummary`(含 `record`)· `OcclusionSite.payload_fp/payload_src` |
|
||||
| `src/mlsp.rs` | `repair_apply` 的 `check_labels`;`session.summary`;进程级 `SESSION` |
|
||||
| `src/view/mod.rs` | `pub use render::expr_display`(供诊断渲染 payload) |
|
||||
| `tests/occlusion.rs` | 3 个 T1 集成测试 |
|
||||
| `doc/design/change-m6-t1-session.md` | 本文件 |
|
||||
+108
@@ -22,6 +22,10 @@ pub struct OcclusionSite {
|
||||
pub unit: String,
|
||||
/// Identifiers the payload actually mentions (for L1 ref checks).
|
||||
pub payload_idents: std::collections::HashSet<String>,
|
||||
/// In-process fingerprint of the payload (T1 staleness comparison).
|
||||
pub payload_fp: String,
|
||||
/// Surface rendering of the payload (diagnostics: `code_past` / `code_now`).
|
||||
pub payload_src: String,
|
||||
}
|
||||
|
||||
/// Collect every occlusion in `module` (declaration order).
|
||||
@@ -99,6 +103,8 @@ fn walk_expr(expr: &Expr, line: u32, unit: &str, out: &mut Vec<OcclusionSite>) {
|
||||
line,
|
||||
unit: unit.to_string(),
|
||||
payload_idents: idents,
|
||||
payload_fp: payload_fingerprint(payload),
|
||||
payload_src: render_payload(payload),
|
||||
});
|
||||
if let Some(inner) = payload {
|
||||
walk_expr(inner, line, unit, out);
|
||||
@@ -437,3 +443,105 @@ pub fn search(module: &Module, words: &[String]) -> Vec<Hit> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M6 (T1): session-scoped staleness — compare before/after edits in memory.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// One occlusion whose payload changed while its label stayed the same.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StaleItem {
|
||||
pub label: String,
|
||||
/// 1-based line in the **new** source.
|
||||
pub line: u32,
|
||||
/// Rendered payload before the edit.
|
||||
pub code_past: String,
|
||||
/// Rendered payload after the edit.
|
||||
pub code_now: String,
|
||||
}
|
||||
|
||||
/// In-process fingerprint of a payload. Only used to compare two versions parsed
|
||||
/// by the *same* process, so a stable cross-version format is unnecessary.
|
||||
fn payload_fingerprint(payload: &Option<Box<Expr>>) -> String {
|
||||
match payload {
|
||||
Some(e) => format!("{e:?}"),
|
||||
None => "<empty>".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_payload(payload: &Option<Box<Expr>>) -> String {
|
||||
match payload {
|
||||
Some(e) => crate::view::expr_display(e),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Compare two versions of a document and return occlusions whose **payload**
|
||||
/// changed but whose **label** did not. Matching is by `(label, occurrence)`, so
|
||||
/// moving code around does not produce false positives.
|
||||
pub fn compare(before: &Module, after: &Module) -> Vec<StaleItem> {
|
||||
use std::collections::HashMap;
|
||||
|
||||
let before_sites = collect(before);
|
||||
let after_sites = collect(after);
|
||||
|
||||
// Group by label → ordered occurrences.
|
||||
let mut past: HashMap<&str, Vec<&OcclusionSite>> = HashMap::new();
|
||||
for s in &before_sites {
|
||||
past.entry(s.label.as_str()).or_default().push(s);
|
||||
}
|
||||
|
||||
let mut seen: HashMap<&str, usize> = HashMap::new();
|
||||
let mut out = Vec::new();
|
||||
for site in &after_sites {
|
||||
let idx = seen.entry(site.label.as_str()).or_insert(0);
|
||||
let occurrence = *idx;
|
||||
*idx += 1;
|
||||
let Some(old) = past.get(site.label.as_str()).and_then(|v| v.get(occurrence)) else {
|
||||
continue; // brand-new label: no history, nothing to compare
|
||||
};
|
||||
if old.payload_fp == site.payload_fp {
|
||||
continue;
|
||||
}
|
||||
out.push(StaleItem {
|
||||
label: site.label.clone(),
|
||||
line: site.line,
|
||||
code_past: old.payload_src.clone(),
|
||||
code_now: site.payload_src.clone(),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Session accumulator for `session.summary` (`<TAB>` M6).
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct SessionSummary {
|
||||
pub stale_seen: usize,
|
||||
pub fixed: usize,
|
||||
pub items: Vec<String>,
|
||||
}
|
||||
|
||||
impl SessionSummary {
|
||||
/// Record one round's comparison; returns the number of *newly* seen labels.
|
||||
pub fn record(&mut self, stale: &[StaleItem]) -> usize {
|
||||
let now: Vec<String> = stale.iter().map(|s| s.label.clone()).collect();
|
||||
let mut newly = 0;
|
||||
for label in &now {
|
||||
if !self.items.contains(label) {
|
||||
self.items.push(label.clone());
|
||||
self.stale_seen += 1;
|
||||
newly += 1;
|
||||
}
|
||||
}
|
||||
// Labels that were outstanding and are no longer stale are considered fixed.
|
||||
let still: Vec<String> = self
|
||||
.items
|
||||
.iter()
|
||||
.filter(|l| now.contains(l))
|
||||
.cloned()
|
||||
.collect();
|
||||
self.fixed += self.items.len() - still.len();
|
||||
self.items = still;
|
||||
newly
|
||||
}
|
||||
}
|
||||
+64
-1
@@ -59,6 +59,8 @@ fn dispatch(req: &Value) -> Result<Value, Value> {
|
||||
Some("schema") => schema(¶ms),
|
||||
// `<TAB>` M9: occlusion label search (two-tier vocabulary).
|
||||
Some("labels.search") => labels_search(¶ms),
|
||||
// `<TAB>` M6: one-shot session summary (T1 staleness seen/fixed).
|
||||
Some("session.summary") => session_summary(),
|
||||
other => Err(err(
|
||||
"mlsp.unknown_method",
|
||||
format!("未知方法 {other:?};可用:locate / syntax / validate / repair_targets / repair_apply / schema"),
|
||||
@@ -270,6 +272,12 @@ fn repair_apply(params: &Value) -> Result<Value, Value> {
|
||||
});
|
||||
}
|
||||
|
||||
let check_labels = match params.get("check_labels") {
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::String(s)) => s != "off" && s != "false",
|
||||
_ => false,
|
||||
};
|
||||
|
||||
match crate::repair::apply_edits(&source, &ranges, &edits) {
|
||||
Ok(new_source) => {
|
||||
if params.get("write").and_then(|w| w.as_bool()).unwrap_or(false) {
|
||||
@@ -280,7 +288,36 @@ fn repair_apply(params: &Value) -> Result<Value, Value> {
|
||||
std::fs::write(path, &new_source)
|
||||
.map_err(|e| err("mlsp.io_error", format!("写回 {path} 失败: {e}")))?;
|
||||
}
|
||||
Ok(json!({"source": new_source, "edits_applied": edits.len()}))
|
||||
// `<TAB>` M6 (T1): the edit is the perfect moment to ask "did the
|
||||
// description survive?" — before/after are both in hand, no VCS,
|
||||
// no ledger, and the answer is scoped to this very edit.
|
||||
let mut labels = Value::Null;
|
||||
if check_labels {
|
||||
if let (Ok(before), Ok(after)) = (
|
||||
crate::load::load_module_from_source(&source),
|
||||
crate::load::load_module_from_source(&new_source),
|
||||
) {
|
||||
let stale = crate::label::compare(&before, &after);
|
||||
let newly = with_session(|s| s.record(&stale));
|
||||
labels = json!({
|
||||
"stale": stale
|
||||
.iter()
|
||||
.map(|s| json!({
|
||||
"label": s.label,
|
||||
"line": s.line,
|
||||
"code_past": s.code_past,
|
||||
"code_now": s.code_now,
|
||||
}))
|
||||
.collect::<Vec<_>>(),
|
||||
"newly_seen": newly,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(json!({
|
||||
"source": new_source,
|
||||
"edits_applied": edits.len(),
|
||||
"labels": labels,
|
||||
}))
|
||||
}
|
||||
Err(oos) => Err(json!({
|
||||
"code": "mlsp.repair_out_of_scope",
|
||||
@@ -333,6 +370,32 @@ fn schema(params: &Value) -> Result<Value, Value> {
|
||||
|
||||
// ---------- 公共小工具 ----------
|
||||
|
||||
/// Per-process T1 session state (`repair_apply` rounds accumulate here).
|
||||
static SESSION: std::sync::Mutex<Option<crate::label::SessionSummary>> =
|
||||
std::sync::Mutex::new(None);
|
||||
|
||||
fn with_session<T>(f: impl FnOnce(&mut crate::label::SessionSummary) -> T) -> T {
|
||||
let mut guard = SESSION.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let s = guard.get_or_insert_with(Default::default);
|
||||
f(s)
|
||||
}
|
||||
|
||||
/// `session.summary` — report (and reset) the T1 counters. `<TAB>` M6
|
||||
fn session_summary() -> Result<Value, Value> {
|
||||
let s = with_session(|s| {
|
||||
let snap = s.clone();
|
||||
*s = Default::default();
|
||||
snap
|
||||
});
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"labels_stale_seen": s.stale_seen,
|
||||
"labels_fixed": s.fixed,
|
||||
"labels_outstanding": s.items.len(),
|
||||
"items": s.items,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `labels.search` — occlusion label query. `<TAB>` M9
|
||||
///
|
||||
/// params: `{ source | path, grep?: [..] | "a,b", also_builtin?: bool,
|
||||
|
||||
@@ -10,6 +10,9 @@ mod notebook_api;
|
||||
mod output;
|
||||
mod render;
|
||||
|
||||
/// Surface rendering of an expression (labels/diagnostics reuse). `<TAB>` M6
|
||||
pub use render::expr_display;
|
||||
|
||||
pub use output::{write_capture, write_static, CaptureOptions, OutputOptions};
|
||||
|
||||
use std::fs;
|
||||
|
||||
@@ -168,3 +168,69 @@ fn mlsp_labels_search_returns_hits() {
|
||||
assert!(text.contains("\"count\":2"), "text={text}");
|
||||
assert!(text.contains("客户留存率"), "text={text}");
|
||||
}
|
||||
|
||||
// ---- M6 (T1): session-scoped staleness via `repair_apply` ----
|
||||
|
||||
fn mlsp_session(reqs: &[&str]) -> Vec<String> {
|
||||
use std::io::Write;
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.arg("mlsp")
|
||||
.env("MARQDO_MARKUP", "occlusion")
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn mlsp");
|
||||
let payload: String = reqs.iter().map(|r| format!("{r}\n")).collect();
|
||||
child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.write_all(payload.as_bytes())
|
||||
.unwrap();
|
||||
let out = child.wait_with_output().unwrap();
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.lines()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn repair_req(src: &str, new_line: &str) -> String {
|
||||
let src_json = serde_json::to_string(src).unwrap();
|
||||
let line_json = serde_json::to_string(new_line).unwrap();
|
||||
format!(
|
||||
r#"{{"id":1,"method":"repair_apply","params":{{"source":{src_json},"ranges":[[3,3]],"edits":[{{"op":"replace","line":3,"text":{line_json}}}],"check_labels":true}}}}"#
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t1_flags_payload_change_only() {
|
||||
let src = "# main\n\n**a = [按税率算总价](100 * 0.1)**\n> print text=`a`\n";
|
||||
let out = mlsp_session(&[&repair_req(src, "**a = [按税率算总价](100 * 0.2)**")]);
|
||||
let line = out.join("\n");
|
||||
assert!(line.contains("\"stale\""), "{line}");
|
||||
assert!(line.contains("100 * 0.1"), "must show code_past: {line}");
|
||||
assert!(line.contains("100 * 0.2"), "must show code_now: {line}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t1_silent_when_label_also_changes() {
|
||||
let src = "# main\n\n**a = [按税率算总价](100 * 0.1)**\n> print text=`a`\n";
|
||||
let out = mlsp_session(&[&repair_req(
|
||||
src,
|
||||
"**a = [改成按两倍税率算](100 * 0.2)**",
|
||||
)]);
|
||||
let line = out.join("\n");
|
||||
assert!(line.contains("\"stale\":[]"), "label edit = author reviewed: {line}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t1_session_summary_reports_counters() {
|
||||
let src = "# main\n\n**a = [按税率算总价](100 * 0.1)**\n> print text=`a`\n";
|
||||
let out = mlsp_session(&[
|
||||
&repair_req(src, "**a = [按税率算总价](100 * 0.2)**"),
|
||||
r#"{"id":2,"method":"session.summary","params":{}}"#,
|
||||
]);
|
||||
let summary = out.last().expect("summary line");
|
||||
assert!(summary.contains("\"labels_stale_seen\":1"), "{summary}");
|
||||
assert!(summary.contains("\"labels_outstanding\":1"), "{summary}");
|
||||
}
|
||||
Reference in new issue
Block a user