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:
cflmy committed 2026-10-22 15:19:17 +08:00
1 parent 1c90312c02
commit 6bba0be6d2
5 files changed
+350 -1

No files matched your search

+108
View File
@@ -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
View File
@@ -59,6 +59,8 @@ fn dispatch(req: &Value) -> Result<Value, Value> {
Some("schema") => schema(&params),
// `<TAB>` M9: occlusion label search (two-tier vocabulary).
Some("labels.search") => labels_search(&params),
// `<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,
+3
View File
@@ -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;