Skip to content

World's first open-source enterprise world model.

The ontology agent remembers what it has seen, and already-in-the-ontology becomes a proposal: 0061 cut 1.1 (#950)

WaylandYang4f9458c9bfe0
diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs
index 940e2ec8..bc58d3be 100644
--- a/crates/utopia-cli/src/main.rs
+++ b/crates/utopia-cli/src/main.rs
@@ -82,7 +82,7 @@ struct ManifestDataDir {
/// not a side effect of a code change.
// 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current`
// 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71
-const CURRENT_SCHEMA_VERSION: u32 = 82;
+const CURRENT_SCHEMA_VERSION: u32 = 83;
fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
diff --git a/crates/utopia-extract/src/ontology_agent.rs b/crates/utopia-extract/src/ontology_agent.rs
index 36e4c59d..32888169 100644
--- a/crates/utopia-extract/src/ontology_agent.rs
+++ b/crates/utopia-extract/src/ontology_agent.rs
@@ -90,6 +90,8 @@ pub struct Proposal {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Existing {
pub key: String,
+ /// forward | reverse:形状的主语是不是属性的主语。类别词对类的没有方向
+ pub direction: Option<String>,
pub signatures: Vec<i64>,
pub kind_words: Vec<i64>,
}
@@ -121,12 +123,15 @@ datatype (number | date | text | bool) and no ranges. Otherwise value=false with
as class keys, existing or proposed in this same answer.\n\
- Keys are snake_case ASCII. Reuse an existing key only under existing, never as a proposal.\n\
- If an existing property or class already holds a shape, list it under existing with the shape ids \
-instead of proposing.\n\
+instead of proposing, with dir: forward when the shape's subject is the property's subject, reverse \
+when the shape reads the property backwards (\"X wrote Y\" is author read in reverse).\n\
+- Do not propose the inverse of an existing property: list the shape under that property with dir \
+reverse.\n\
Answer with one JSON object and nothing else:\n\
{\"p\":[{\"kind\":\"property\",\"key\":\"...\",\"label\":\"...\",\"definition\":\"...\",\"value\":false,\
\"datatype\":null,\"domains\":[\"class_key\"],\"ranges\":[\"class_key\"],\"s\":[ids],\"k\":[ids],\"q\":[ids]},\
{\"kind\":\"class\",\"key\":\"...\",\"label\":\"...\",\"definition\":\"...\",\"parents\":[\"class_key\"],\
-\"s\":[],\"k\":[ids],\"q\":[ids]}],\"existing\":[{\"key\":\"existing_key\",\"s\":[ids],\"k\":[ids]}]}";
+\"s\":[],\"k\":[ids],\"q\":[ids]}],\"existing\":[{\"key\":\"existing_key\",\"dir\":\"forward\",\"s\":[ids],\"k\":[ids]}]}";
pub fn build_proposal_messages(
signatures: &[OpenSignature<'_>],
@@ -385,8 +390,17 @@ pub fn parse_proposal_response(
reply.malformed += 1;
continue;
}
+ let direction = match obj.get("dir").and_then(Value::as_str).map(str::trim) {
+ Some("reverse") => Some("reverse".to_string()),
+ Some("forward") | None | Some("") => Some("forward".to_string()),
+ Some(_) => {
+ reply.malformed += 1;
+ continue;
+ }
+ };
reply.existing.push(Existing {
key,
+ direction,
signatures,
kind_words,
});
@@ -405,7 +419,7 @@ mod tests {
#[test]
fn a_well_formed_reply_yields_proposals_and_existing() {
- let raw = r#"{"p":[{"kind":"property","key":"supplies","label":"supplies","definition":"The subject organisation delivers goods to the object organisation. Not for one-off sales.","value":false,"datatype":null,"domains":["organization"],"ranges":["organization"],"s":[0,2],"k":[],"q":[1]},{"kind":"class","key":"supplier","label":"Supplier","definition":"An organisation that supplies others.","parents":["organization"],"s":[],"k":[0],"q":[]}],"existing":[{"key":"located_in","s":[1],"k":[]}]}"#;
+ let raw = r#"{"p":[{"kind":"property","key":"supplies","label":"supplies","definition":"The subject organisation delivers goods to the object organisation. Not for one-off sales.","value":false,"datatype":null,"domains":["organization"],"ranges":["organization"],"s":[0,2],"k":[],"q":[1]},{"kind":"class","key":"supplier","label":"Supplier","definition":"An organisation that supplies others.","parents":["organization"],"s":[],"k":[0],"q":[]}],"existing":[{"key":"located_in","dir":"reverse","s":[1],"k":[]}]}"#;
let r = parse_proposal_response(raw, &ids_of(&[0, 1, 2]), &ids_of(&[0]), &ids_of(&[1]))
.unwrap();
assert_eq!(r.malformed, 0);
@@ -420,6 +434,7 @@ mod tests {
r.existing,
vec![Existing {
key: "located_in".into(),
+ direction: Some("reverse".into()),
signatures: vec![1],
kind_words: vec![]
}]
diff --git a/crates/utopia-server/src/ontology_agent.rs b/crates/utopia-server/src/ontology_agent.rs
index fff7f59c..b7ac1dbc 100644
--- a/crates/utopia-server/src/ontology_agent.rs
+++ b/crates/utopia-server/src/ontology_agent.rs
@@ -9,9 +9,11 @@ use std::collections::{HashMap, HashSet};
use serde::Deserialize;
use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
use utopia_core::models::RelationAxioms;
use utopia_core::AppError;
use utopia_extract::ontology_agent as agent;
+use utopia_store::agent_reviews::{self, Review};
use utopia_store::phrase_bindings::PhraseSignature;
use utopia_store::type_bindings::KindWordSignature;
use utopia_store::{competency_questions, phrase_bindings, type_bindings};
@@ -72,6 +74,9 @@ pub async fn propose(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
/// 一条合并后的提案:同一个键在几批里都被提了,形状、类别词、问题并起来,定义取第一次的
struct Merged {
proposal: agent::Proposal,
+ /// Some = 这是「本体里已经有」:relation | attribute | class,进 map_to。
+ /// 方向记在每条形状上(同一个属性,"X wrote Y" 反着读、"Y's author X" 正着读)
+ map_kind: Option<String>,
shapes: Vec<Value>,
phrases: Vec<String>,
words: Vec<String>,
@@ -91,11 +96,65 @@ async fn propose_locked(
let class_key: HashMap<Uuid, &str> = classes.iter().map(|c| (c.id, c.key.as_str())).collect();
let class_keys: HashSet<&str> = classes.iter().map(|c| c.key.as_str()).collect();
let prop_keys: HashSet<&str> = props.iter().map(|p| p.key.as_str()).collect();
+ let prop_kind: HashMap<&str, &str> = props
+ .iter()
+ .map(|p| (p.key.as_str(), p.kind.as_str()))
+ .collect();
+ // 词表的指纹:类键 + 属性键。代理看过没提、或答「已有」的形状,词表不变就不再送
+ let basis = {
+ let mut keys: Vec<&str> = class_keys.iter().copied().collect();
+ keys.sort_unstable();
+ let mut pkeys: Vec<&str> = prop_keys.iter().copied().collect();
+ pkeys.sort_unstable();
+ let digest = Sha256::digest(format!("{}##{}", keys.join(" "), pkeys.join(" ")).as_bytes());
+ digest
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect::<String>()
+ };
// 已经提过的(不论表态与否)不再提:采纳的等对齐重判;拒绝的人已经说过不要;
- // 还开着的人还没看
+ // 还开着的人还没看。看过没提的和答「已有」的,词表变了才再送(cut 1.1:第一次真跑
+ // 120 条里 85 条没进提案,下一轮又排在最前)
+ // 看过没提的形状记的是当时的陈述数(basis = "count:n"):陈述数翻倍了才再送——多了一个
+ // 属性不必再问代理,对齐自己会拿新属性去重判(0053 指纹),问代理只会每次采纳后把全部
+ // 没提的形状再烧一遍。答「已有」的记的是词表指纹:词表变了再送
let mut proposed_shapes: HashSet<String> = HashSet::new();
let mut proposed_words: HashSet<String> = HashSet::new();
+ let mut declined_shapes: HashMap<String, i64> = HashMap::new();
+ let mut declined_words: HashMap<String, i64> = HashMap::new();
+ for r in agent_reviews::list(pool, kb_id).await? {
+ let word = r.shape.get("kind_word").and_then(Value::as_str);
+ if r.outcome == "declined" {
+ let seen_count = r
+ .basis
+ .strip_prefix("count:")
+ .and_then(|n| n.parse::<i64>().ok())
+ .unwrap_or(1);
+ match (r.kind.as_str(), word) {
+ ("phrase", _) => {
+ declined_shapes.insert(shape_key(&r.shape), seen_count);
+ }
+ (_, Some(w)) => {
+ declined_words.insert(w.to_string(), seen_count);
+ }
+ _ => {}
+ }
+ continue;
+ }
+ if r.outcome != "proposed" && r.basis != basis {
+ continue;
+ }
+ match (r.kind.as_str(), word) {
+ ("phrase", _) => {
+ proposed_shapes.insert(shape_key(&r.shape));
+ }
+ (_, Some(w)) => {
+ proposed_words.insert(w.to_string());
+ }
+ _ => {}
+ }
+ }
for s in utopia_store::ontology::signatures_already_proposed(pool, kb_id).await? {
for p in s
.get("phrases")
@@ -103,7 +162,7 @@ async fn propose_locked(
.into_iter()
.flatten()
{
- proposed_shapes.insert(p.to_string());
+ proposed_shapes.insert(shape_key(p));
}
for w in s
.get("kind_words")
@@ -132,7 +191,13 @@ async fn propose_locked(
Some("none" | "undecided")
)
})
- .filter(|s| !proposed_shapes.contains(&shape_of(s).to_string()))
+ .filter(|s| {
+ let key = shape_key(&shape_of(s));
+ !proposed_shapes.contains(&key)
+ && declined_shapes
+ .get(&key)
+ .is_none_or(|seen| s.count >= seen * 2)
+ })
.collect();
open.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.phrase.cmp(&b.phrase)));
open.truncate(SIGNATURES_PER_ROUND);
@@ -152,7 +217,12 @@ async fn propose_locked(
Some("none" | "undecided")
)
})
- .filter(|w| !proposed_words.contains(&w.kind_word))
+ .filter(|w| {
+ !proposed_words.contains(&w.kind_word)
+ && declined_words
+ .get(&w.kind_word)
+ .is_none_or(|seen| w.count >= seen * 2)
+ })
.collect();
open_words.sort_by(|a, b| {
b.count
@@ -232,6 +302,8 @@ async fn propose_locked(
let mut merged: HashMap<String, Merged> = HashMap::new();
let mut order: Vec<String> = Vec::new();
+ // 这一轮看过的每条形状的去向(调用失败的批次不记,下一轮再送)
+ let mut reviews: Vec<Review> = Vec::new();
let (mut failed, mut malformed, mut skipped_existing) = (0usize, 0usize, 0usize);
for b in 0..calls {
let sig_batch = sig_items
@@ -268,6 +340,61 @@ async fn propose_locked(
}
};
malformed += parsed.malformed;
+ let mut sig_outcome: HashMap<i64, (&str, String)> = HashMap::new();
+ let mut word_outcome: HashMap<i64, (&str, String)> = HashMap::new();
+ // 「本体里已经有」:存成 map_to 提案,人点「用已有的」就是一次人的绑定判定
+ for e in &parsed.existing {
+ let map_kind = if let Some(k) = prop_kind.get(e.key.as_str()) {
+ (*k).to_string()
+ } else if class_keys.contains(e.key.as_str()) {
+ "class".to_string()
+ } else {
+ malformed += 1;
+ continue;
+ };
+ let slot = format!("map_to:{}", e.key);
+ let entry = merged.entry(slot.clone()).or_insert_with(|| {
+ order.push(slot);
+ Merged {
+ proposal: agent::Proposal {
+ kind: "existing".into(),
+ key: e.key.clone(),
+ label: e.key.clone(),
+ definition: String::new(),
+ value: false,
+ datatype: None,
+ domains: Vec::new(),
+ ranges: Vec::new(),
+ parents: Vec::new(),
+ signatures: Vec::new(),
+ kind_words: Vec::new(),
+ questions: Vec::new(),
+ },
+ map_kind: Some(map_kind),
+ shapes: Vec::new(),
+ phrases: Vec::new(),
+ words: Vec::new(),
+ quotes: Vec::new(),
+ serves: Vec::new(),
+ }
+ });
+ if map_kind_is_class(entry) {
+ // 类接的是类别词;形状指给类是答错了格,不记
+ for id in &e.kind_words {
+ if let Some(w) = open_words.get(*id as usize) {
+ push_word(entry, w);
+ word_outcome.insert(*id, ("existing", e.key.clone()));
+ }
+ }
+ } else {
+ for id in &e.signatures {
+ if let Some(sig) = open.get(*id as usize) {
+ push_shape(entry, sig, e.direction.as_deref());
+ sig_outcome.insert(*id, ("existing", e.key.clone()));
+ }
+ }
+ }
+ }
for p in parsed.proposals {
// 模型被告知已有的不要提;还是提了就当它没说(对齐那边会把形状挂上去)
let taken = match p.kind.as_str() {
@@ -288,6 +415,7 @@ async fn propose_locked(
questions: Vec::new(),
..p.clone()
},
+ map_kind: None,
shapes: Vec::new(),
phrases: Vec::new(),
words: Vec::new(),
@@ -295,36 +423,20 @@ async fn propose_locked(
serves: Vec::new(),
}
});
+ let target = format!("{}:{}", section_of(&p), p.key);
for id in p.signatures {
let Some(s) = open.get(id as usize) else {
continue;
};
- let shape = shape_of(s);
- if entry.shapes.contains(&shape) {
- continue;
- }
- entry.shapes.push(shape);
- if !entry.phrases.contains(&s.phrase) {
- entry.phrases.push(s.phrase.clone());
- }
- for q in s.quotes.iter().take(1) {
- if entry.quotes.len() < 3 && !entry.quotes.contains(q) {
- entry.quotes.push(q.clone());
- }
- }
+ push_shape(entry, s, None);
+ sig_outcome.insert(id, ("proposed", target.clone()));
}
for id in p.kind_words {
let Some(w) = open_words.get(id as usize) else {
continue;
};
- if !entry.words.contains(&w.kind_word) {
- entry.words.push(w.kind_word.clone());
- for e in w.examples.iter().take(1) {
- if entry.quotes.len() < 3 && !entry.quotes.contains(e) {
- entry.quotes.push(e.clone());
- }
- }
- }
+ push_word(entry, w);
+ word_outcome.insert(id, ("proposed", target.clone()));
}
for id in p.questions {
let Some(q) = questions.get(id as usize) else {
@@ -335,6 +447,40 @@ async fn propose_locked(
}
}
}
+ for si in sig_batch {
+ let (outcome, target) = sig_outcome
+ .get(&si.id)
+ .map(|(o, t)| (*o, Some(t.clone())))
+ .unwrap_or(("declined", None));
+ reviews.push(Review {
+ kind: "phrase".into(),
+ shape: shape_of(open[si.id as usize]),
+ outcome: outcome.into(),
+ target,
+ basis: if outcome == "declined" {
+ format!("count:{}", open[si.id as usize].count)
+ } else {
+ basis.clone()
+ },
+ });
+ }
+ for wi in word_batch {
+ let (outcome, target) = word_outcome
+ .get(&wi.id)
+ .map(|(o, t)| (*o, Some(t.clone())))
+ .unwrap_or(("declined", None));
+ reviews.push(Review {
+ kind: "kind_word".into(),
+ shape: json!({ "kind_word": wi.kind_word }),
+ outcome: outcome.into(),
+ target,
+ basis: if outcome == "declined" {
+ format!("count:{}", wi.count)
+ } else {
+ basis.clone()
+ },
+ });
+ }
}
let items: Vec<utopia_store::ontology::AgentProposal> = order
@@ -343,11 +489,35 @@ async fn propose_locked(
.filter(|m| !m.shapes.is_empty() || !m.words.is_empty())
.map(|m| {
let p = &m.proposal;
- let section = match (p.kind.as_str(), p.value) {
- ("class", _) => "entity_types",
- (_, true) => "attribute_types",
- _ => "relation_types",
- };
+ if let Some(map_kind) = &m.map_kind {
+ let label = if map_kind == "class" {
+ classes
+ .iter()
+ .find(|c| c.key == p.key)
+ .map(|c| c.label.as_str())
+ } else {
+ props
+ .iter()
+ .find(|r| r.key == p.key)
+ .map(|r| r.label.as_str())
+ };
+ return utopia_store::ontology::AgentProposal {
+ section: "map_to".into(),
+ key: p.key.clone(),
+ payload: json!({
+ "key": p.key,
+ "label": label.unwrap_or(p.key.as_str()),
+ "kind": map_kind,
+ "forms": m.phrases,
+ "kind_words": m.words,
+ "examples": m.quotes,
+ "proposed_by": "agent",
+ }),
+ serves: Vec::new(),
+ signatures: json!({ "phrases": m.shapes, "kind_words": m.words }),
+ };
+ }
+ let section = section_of(p);
let mut payload = json!({
"key": p.key,
"label": p.label,
@@ -380,7 +550,17 @@ async fn propose_locked(
}
})
.collect();
+ // 同一个目标上一轮已经答过一批形状:并起来,不是盖掉(第一次真跑第三轮盖掉了第二轮的)
+ let mut items = items;
+ for it in items.iter_mut().filter(|it| it.section == "map_to") {
+ if let Some(prev) =
+ utopia_store::ontology::open_proposal(pool, kb_id, "map_to", &it.key).await?
+ {
+ merge_map_to(it, &prev);
+ }
+ }
utopia_store::ontology::save_agent_proposals(pool, kb_id, &items).await?;
+ agent_reviews::record(pool, kb_id, &reviews).await?;
tracing::info!(%kb_id, proposals = items.len(), failed, malformed, skipped_existing, "本体代理结束");
if !items.is_empty() {
state.emit_pending(kb_id);
@@ -388,6 +568,113 @@ async fn propose_locked(
Ok(())
}
+fn section_of(p: &agent::Proposal) -> &'static str {
+ match (p.kind.as_str(), p.value) {
+ ("class", _) => "entity_types",
+ (_, true) => "attribute_types",
+ _ => "relation_types",
+ }
+}
+
+fn map_kind_is_class(m: &Merged) -> bool {
+ m.map_kind.as_deref() == Some("class")
+}
+
+/// 形状的身份写成一个键:短语 + 两端的类键 + 宾语是不是字面值(方向不算——
+/// map_to 里的形状带方向,比身份时得去掉)
+fn shape_key(v: &Value) -> String {
+ json!({
+ "phrase": v.get("phrase"),
+ "subject": v.get("subject"),
+ "object": v.get("object"),
+ "value": v.get("value"),
+ })
+ .to_string()
+}
+
+/// 形状的身份:短语 + 两端的类键 + 宾语是不是字面值(方向不算)
+fn same_shape(a: &Value, b: &Value) -> bool {
+ ["phrase", "subject", "object", "value"]
+ .iter()
+ .all(|k| a.get(k) == b.get(k))
+}
+
+fn push_shape(entry: &mut Merged, s: &PhraseSignature, direction: Option<&str>) {
+ let mut shape = shape_of(s);
+ if let Some(d) = direction {
+ shape["direction"] = json!(d);
+ }
+ if entry.shapes.iter().any(|x| same_shape(x, &shape)) {
+ return;
+ }
+ entry.shapes.push(shape);
+ if !entry.phrases.contains(&s.phrase) {
+ entry.phrases.push(s.phrase.clone());
+ }
+ for q in s.quotes.iter().take(1) {
+ if entry.quotes.len() < 3 && !entry.quotes.contains(q) {
+ entry.quotes.push(q.clone());
+ }
+ }
+}
+
+fn push_word(entry: &mut Merged, w: &KindWordSignature) {
+ if entry.words.contains(&w.kind_word) {
+ return;
+ }
+ entry.words.push(w.kind_word.clone());
+ for e in w.examples.iter().take(1) {
+ if entry.quotes.len() < 3 && !entry.quotes.contains(e) {
+ entry.quotes.push(e.clone());
+ }
+ }
+}
+
+/// 把上一轮开着的 map_to 行并进这一轮的:形状、说法、类别词、例句取并集,先前的在前
+fn merge_map_to(
+ it: &mut utopia_store::ontology::AgentProposal,
+ prev: &utopia_store::ontology::StoredProposal,
+) {
+ let mut shapes: Vec<Value> = prev
+ .signatures
+ .get("phrases")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ for s in it
+ .signatures
+ .get("phrases")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ {
+ if !shapes.iter().any(|x| same_shape(x, s)) {
+ shapes.push(s.clone());
+ }
+ }
+ let union = |field: &str, from_payload: bool| -> Vec<String> {
+ let (a, b) = if from_payload {
+ (prev.payload.get(field), it.payload.get(field))
+ } else {
+ (prev.signatures.get(field), it.signatures.get(field))
+ };
+ let mut out = strings(a);
+ for x in strings(b) {
+ if !out.contains(&x) {
+ out.push(x);
+ }
+ }
+ out
+ };
+ let words = union("kind_words", false);
+ let forms = union("forms", true);
+ let examples: Vec<String> = union("examples", true).into_iter().take(3).collect();
+ it.payload["forms"] = json!(forms);
+ it.payload["kind_words"] = json!(words);
+ it.payload["examples"] = json!(examples);
+ it.signatures = json!({ "phrases": shapes, "kind_words": words });
+}
+
fn datatype_or_text(d: Option<&str>) -> &str {
match d {
Some(d @ ("text" | "number" | "date" | "bool")) => d,
@@ -455,6 +742,8 @@ pub async fn adopt(
.trim()
.to_string();
let id = match section {
+ // 「用已有的」:形状各写一条人的绑定判定(同审核页),类别词各归到那个类
+ "map_to" => adopt_map_to(state, kb_id, &p, &classes).await?,
"entity_types" => {
let parents = resolve(
edits
@@ -543,10 +832,18 @@ pub async fn adopt(
_ => {
return Err(AppError::invalid(
"bad_section",
- "section 只能是 entity_types、relation_types 或 attribute_types",
+ "section 只能是 map_to、entity_types、relation_types 或 attribute_types",
))
}
};
+ // 新元素要有向量,对齐的短名单才看得见它(候选多于短名单长度时按向量挑;没向量的
+ // 属性永远进不了名单,形状的指纹就不变,采纳了也不重判——第一次真跑 bordered_by 就
+ // 是这样)。补的只是缺的那几条,通常一次 embed 调用
+ if section != "map_to" {
+ if let Err(e) = crate::ontology_index::refresh(state, kb_id).await {
+ tracing::warn!(%kb_id, error = %e, "采纳后本体向量没补上,对齐的短名单看不见新元素");
+ }
+ }
utopia_store::ontology::decide_proposal(pool, kb_id, section, key, "adopted", actor).await?;
let _ = utopia_store::audit::record(
pool,
@@ -562,6 +859,80 @@ pub async fn adopt(
Ok(id)
}
+/// map_to 的采纳:目标是属性,提案里的每条形状写成人的绑定(属性 + 方向),投影跟着
+/// 排(同审核页的 `decide_alignment_phrase`);目标是类,每个类别词归到它。返回目标的 id
+async fn adopt_map_to(
+ state: &AppState,
+ kb_id: Uuid,
+ p: &utopia_store::ontology::StoredProposal,
+ classes: &[utopia_core::models::EntityType],
+) -> Result<Uuid, AppError> {
+ let pool = &state.pool;
+ let kind = p
+ .payload
+ .get("kind")
+ .and_then(Value::as_str)
+ .unwrap_or("relation");
+ if kind == "class" {
+ let class = classes
+ .iter()
+ .find(|c| c.key == p.key)
+ .map(|c| c.id)
+ .ok_or_else(|| AppError::invalid("unknown_class", "no class with that key"))?;
+ for w in strings(p.signatures.get("kind_words")) {
+ type_bindings::decide_and_apply_human(
+ pool,
+ kb_id,
+ &w,
+ Some(class),
+ &json!({ "person": p.key, "via": "ontology_agent" }),
+ )
+ .await?;
+ }
+ return Ok(class);
+ }
+ let property = utopia_store::ontology::relation_type_views(pool, kb_id)
+ .await?
+ .into_iter()
+ .find(|r| r.key == p.key)
+ .map(|r| r.id)
+ .ok_or_else(|| AppError::invalid("unknown_property", "no property with that key"))?;
+ let sigs = phrase_bindings::signatures(pool, kb_id).await?;
+ for shape in p
+ .signatures
+ .get("phrases")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ {
+ // 此刻已经没有陈述的形状跳过。方向是这条形状自己的
+ let Some(sig) = sigs.iter().find(|s| same_shape(&shape_of(s), shape)) else {
+ continue;
+ };
+ let direction = match shape.get("direction").and_then(Value::as_str) {
+ Some("reverse") => "reverse",
+ _ => "forward",
+ };
+ let votes = json!({ "person": { "property": p.key, "direction": direction, "via": "ontology_agent" } });
+ phrase_bindings::decide_with_delivery(
+ pool,
+ kb_id,
+ sig,
+ phrase_bindings::Decision {
+ relation_type_id: Some(property),
+ direction: Some(direction),
+ status: "bound",
+ votes: &votes,
+ decided_by: "person",
+ basis: None,
+ },
+ )
+ .await?;
+ }
+ state.emit_review(kb_id);
+ Ok(property)
+}
+
#[cfg(test)]
#[path = "ontology_agent_tests.rs"]
mod tests;
diff --git a/crates/utopia-server/src/ontology_agent_tests.rs b/crates/utopia-server/src/ontology_agent_tests.rs
index 20a75e7b..9be6d562 100644
--- a/crates/utopia-server/src/ontology_agent_tests.rs
+++ b/crates/utopia-server/src/ontology_agent_tests.rs
@@ -35,6 +35,7 @@ struct Fx {
kb: Uuid,
organization: Uuid,
place: Uuid,
+ located_in: Uuid,
/// 采纳的人(decided_by 是外键)
user: Uuid,
model: Model,
@@ -43,14 +44,18 @@ struct Fx {
}
impl Fx {
- /// 一个库:organization、place 两个类,没有属性;Acme —founded in→ London 一条开放陈述
+ /// 一个库:organization、place 两个类,一条属性 located_in(organization → place);
+ /// Acme —founded in→ London、Acme —located in→ London 两条开放陈述(形状按短语排:
+ /// s0 = founded in,s1 = located in)
async fn new(replies: Vec<Value>) -> anyhow::Result<Option<Self>> {
let Some(url) = utopia_store::test_db::url() else {
return Ok(None);
};
let pool = sqlx::PgPool::connect(&url).await?;
utopia_store::db::migrate(&pool).await?;
- let (org, ws, kb, organization, place, acme, london, statement, user) = (
+ let (org, ws, kb, organization, place, acme, london, statement, user, located_in, st2) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
Uuid::now_v7(),
Uuid::now_v7(),
Uuid::now_v7(),
@@ -71,8 +76,13 @@ impl Fx {
('{place}','{kb}','place','Place','#000','circle','a geographic location');
INSERT INTO entities(id,kb_id,canonical_name,type_id) VALUES
('{acme}','{kb}','Acme','{organization}'), ('{london}','{kb}','London','{place}');
+ INSERT INTO relation_types(id,kb_id,key,label,kind,temporal,description) VALUES
+ ('{located_in}','{kb}','located_in','located in','relation','state','where an organization sits');
+ INSERT INTO relation_type_domains(relation_type_id,entity_type_id) VALUES ('{located_in}','{organization}');
+ INSERT INTO relation_type_ranges(relation_type_id,entity_type_id) VALUES ('{located_in}','{place}');
INSERT INTO facts(id,kb_id,subject_id,object_id,layer,phrase) VALUES
- ('{statement}','{kb}','{acme}','{london}','open','founded in');"
+ ('{statement}','{kb}','{acme}','{london}','open','founded in'),
+ ('{st2}','{kb}','{acme}','{london}','open','located in');"
))
.execute(&pool)
.await?;
@@ -114,6 +124,7 @@ impl Fx {
kb,
organization,
place,
+ located_in,
user,
model,
server,
@@ -121,27 +132,33 @@ impl Fx {
}))
}
- /// 对齐判过这条形状:没有属性可绑
+ /// 对齐判过这两条形状:没有属性可绑
async fn decide_none(&self) -> anyhow::Result<()> {
let sigs = phrase_bindings::signatures(&self.pool, self.kb).await?;
- assert_eq!(sigs.len(), 1, "one open statement, one signature");
- phrase_bindings::decide(
- &self.pool,
- self.kb,
- &sigs[0],
- Decision {
- relation_type_id: None,
- direction: None,
- status: "none",
- votes: &json!({ "reason": "no_properties" }),
- decided_by: "agent",
- basis: Some("test"),
- },
- )
- .await?;
+ assert_eq!(sigs.len(), 2, "two open statements, two signatures");
+ for sig in &sigs {
+ phrase_bindings::decide(
+ &self.pool,
+ self.kb,
+ sig,
+ Decision {
+ relation_type_id: None,
+ direction: None,
+ status: "none",
+ votes: &json!({ "reason": "no_candidates" }),
+ decided_by: "agent",
+ basis: Some("test"),
+ },
+ )
+ .await?;
+ }
Ok(())
}
+ async fn requests(&self) -> usize {
+ self.model.requests.lock().unwrap().len()
+ }
+
async fn cleanup(self) -> anyhow::Result<()> {
self.server.abort();
sqlx::query("DELETE FROM jobs WHERE payload->>'kb_id'=$1")
@@ -149,6 +166,10 @@ impl Fx {
.execute(&self.pool)
.await?;
// decided_by 指向 users,不级联:先清提案再删组织
+ sqlx::query("DELETE FROM ontology_agent_reviews WHERE kb_id=$1")
+ .bind(self.kb)
+ .execute(&self.pool)
+ .await?;
sqlx::query("DELETE FROM ontology_proposals WHERE kb_id=$1")
.bind(self.kb)
.execute(&self.pool)
@@ -218,6 +239,10 @@ async fn an_unbound_shape_becomes_a_proposal_that_serves_a_question_and_adoption
text.contains("organization"),
"the glossary is offered: {text}"
);
+ assert!(
+ text.contains("located_in"),
+ "existing properties are in the glossary: {text}"
+ );
assert!(
text.contains("Where was each organization founded?"),
"the accepted question is offered: {text}"
@@ -245,12 +270,26 @@ async fn an_unbound_shape_becomes_a_proposal_that_serves_a_question_and_adoption
"the place where an organization was founded"
);
- // 提过的形状下一轮不再送:没有模型调用
+ // 提过的形状、看过没提的形状(located in)下一轮都不再送:没有模型调用
+ let outcomes: Vec<(String, String)> = sqlx::query_as(
+ "SELECT shape->>'phrase', outcome FROM ontology_agent_reviews WHERE kb_id=$1 ORDER BY 1",
+ )
+ .bind(f.kb)
+ .fetch_all(&f.pool)
+ .await?;
+ assert_eq!(
+ outcomes,
+ vec![
+ ("founded in".to_string(), "proposed".to_string()),
+ ("located in".to_string(), "declined".to_string())
+ ],
+ "every offered shape is recorded with its outcome"
+ );
propose(&f.state, f.kb).await?;
assert_eq!(
- f.model.requests.lock().unwrap().len(),
+ f.requests().await,
1,
- "an already-proposed shape is not offered again"
+ "already-proposed and declined shapes are not offered again"
);
// 采纳:属性建出来,签名域值域照提案,提案标记 adopted,短语对齐排上
@@ -345,3 +384,140 @@ async fn a_proposal_for_an_existing_key_or_binding_nothing_is_dropped() -> anyho
assert!(open[0].serves.is_empty());
f.cleanup().await
}
+
+#[tokio::test]
+async fn a_declined_shape_returns_when_its_statements_double_and_an_existing_answer_becomes_a_binding(
+) -> anyhow::Result<()> {
+ let Some(f) = Fx::new(vec![
+ // 第一轮:founded in 没提;located in 本体里已经有(located_in,正向)
+ json!({ "p": [], "existing": [{ "key": "located_in", "dir": "forward", "s": [1], "k": [] }] }),
+ // 陈述翻倍之后的那轮:只有 founded in 送来(这一批里它是 s0),答成 located_in 反着读
+ json!({ "p": [], "existing": [{ "key": "located_in", "dir": "reverse", "s": [0], "k": [] }] }),
+ ])
+ .await?
+ else {
+ return Ok(());
+ };
+ f.decide_none().await?;
+
+ propose(&f.state, f.kb).await?;
+ assert_eq!(f.requests().await, 1);
+ let open = utopia_store::ontology::open_proposals(&f.pool, f.kb).await?;
+ assert_eq!(
+ open.len(),
+ 1,
+ "the existing answer is a map_to proposal: {open:?}"
+ );
+ let m = &open[0];
+ assert_eq!(m.section, "map_to");
+ assert_eq!(m.key, "located_in");
+ assert_eq!(m.proposed_by, "agent");
+ assert_eq!(m.payload["kind"], "relation");
+ assert_eq!(
+ m.payload["label"], "located in",
+ "the target's label travels with it"
+ );
+ assert_eq!(m.payload["forms"][0], "located in");
+ assert_eq!(m.signatures["phrases"][0]["phrase"], "located in");
+ assert_eq!(m.signatures["phrases"][0]["direction"], "forward");
+
+ // 第二轮:一条提过(map_to)、一条看过没提,词表没变——不问
+ propose(&f.state, f.kb).await?;
+ assert_eq!(f.requests().await, 1, "nothing new to look at");
+
+ // 词表变了(多了一个类):看过没提的不再问——对齐自己会拿新元素去重判,问代理只是烧 token
+ utopia_store::ontology::create_entity_type(
+ &f.pool,
+ f.kb,
+ "city",
+ "City",
+ "#000",
+ "circle",
+ &[f.place],
+ "a city",
+ )
+ .await?;
+ propose(&f.state, f.kb).await?;
+ assert_eq!(
+ f.requests().await,
+ 1,
+ "a changed glossary alone does not re-offer declined shapes"
+ );
+
+ // founded in 的陈述翻倍了(1 → 2):再送一次;map_to 已经提过的 located in 不送
+ sqlx::query(
+ "INSERT INTO facts(id,kb_id,subject_id,object_id,layer,phrase)
+ SELECT $1, kb_id, subject_id, object_id, 'open', 'founded in' FROM facts
+ WHERE kb_id=$2 AND phrase='founded in' LIMIT 1",
+ )
+ .bind(Uuid::now_v7())
+ .bind(f.kb)
+ .execute(&f.pool)
+ .await?;
+ propose(&f.state, f.kb).await?;
+ assert_eq!(
+ f.requests().await,
+ 2,
+ "a declined shape with twice the statements is offered again"
+ );
+ let text = user_text(&f.model.requests.lock().unwrap()[1]);
+ assert!(
+ text.contains("founded in"),
+ "the declined shape is offered again: {text}"
+ );
+ assert!(
+ !text.contains("s1"),
+ "the shape already proposed as map_to is not offered: {text}"
+ );
+
+ // 这一轮的答案并进同一条 map_to:两条形状,各自的方向
+ let open = utopia_store::ontology::open_proposals(&f.pool, f.kb).await?;
+ assert_eq!(open.len(), 1, "still one map_to row: {open:?}");
+ let shapes = open[0].signatures["phrases"].as_array().unwrap().clone();
+ assert_eq!(
+ shapes.len(),
+ 2,
+ "shapes from both rounds are kept: {shapes:?}"
+ );
+ assert_eq!(shapes[0]["phrase"], "located in");
+ assert_eq!(shapes[0]["direction"], "forward");
+ assert_eq!(shapes[1]["phrase"], "founded in");
+ assert_eq!(shapes[1]["direction"], "reverse");
+ assert_eq!(
+ open[0].payload["forms"],
+ json!(["located in", "founded in"])
+ );
+
+ // 采纳 map_to:两条形状都成了人的绑定,绑到 located_in,各按自己的方向
+ let id = adopt(
+ &f.state,
+ f.kb,
+ "map_to",
+ "located_in",
+ AdoptEdits::default(),
+ f.user,
+ )
+ .await?;
+ assert_eq!(id, f.located_in);
+ let bindings = phrase_bindings::bindings(&f.pool, f.kb).await?;
+ for (phrase, dir) in [("located in", "forward"), ("founded in", "reverse")] {
+ let b = bindings
+ .iter()
+ .find(|b| b.phrase == phrase)
+ .expect("the binding exists");
+ assert_eq!(b.status, "bound", "{phrase}");
+ assert_eq!(b.decided_by, "person", "{phrase}");
+ assert_eq!(b.relation_type_id, Some(f.located_in), "{phrase}");
+ assert_eq!(b.direction.as_deref(), Some(dir), "{phrase}");
+ }
+ assert!(
+ utopia_store::ontology::open_proposals(&f.pool, f.kb)
+ .await?
+ .is_empty(),
+ "the map_to proposal is adopted"
+ );
+ // 再来一轮:两条都绑上了——不问
+ propose(&f.state, f.kb).await?;
+ assert_eq!(f.requests().await, 2);
+ f.cleanup().await
+}
diff --git a/crates/utopia-store/src/agent_reviews.rs b/crates/utopia-store/src/agent_reviews.rs
new file mode 100644
index 00000000..5306ff40
--- /dev/null
+++ b/crates/utopia-store/src/agent_reviews.rs
@@ -0,0 +1,49 @@
+//! 本体代理看过的形状(0061 cut 1.1):提了、已有、没提各记一行,下一轮据此不再送。
+
+use serde_json::Value;
+use sqlx::PgPool;
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+#[derive(Debug, Clone, sqlx::FromRow)]
+pub struct Review {
+ /// phrase | kind_word
+ pub kind: String,
+ pub shape: Value,
+ /// proposed | existing | declined
+ pub outcome: String,
+ pub target: Option<String>,
+ /// 看它时词表的指纹;变了,已有与没提的形状再送一次
+ pub basis: String,
+}
+
+pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Review>> {
+ Ok(sqlx::query_as(
+ "SELECT kind, shape, outcome, target, basis FROM ontology_agent_reviews WHERE kb_id = $1",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 记一轮看过的。同一形状再看是刷新
+pub async fn record(pool: &PgPool, kb_id: Uuid, items: &[Review]) -> AppResult<()> {
+ for it in items {
+ sqlx::query(
+ "INSERT INTO ontology_agent_reviews (kb_id, kind, shape, outcome, target, basis)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (kb_id, kind, shape) DO UPDATE
+ SET outcome = EXCLUDED.outcome, target = EXCLUDED.target,
+ basis = EXCLUDED.basis, reviewed_at = now()",
+ )
+ .bind(kb_id)
+ .bind(&it.kind)
+ .bind(&it.shape)
+ .bind(&it.outcome)
+ .bind(&it.target)
+ .bind(&it.basis)
+ .execute(pool)
+ .await?;
+ }
+ Ok(())
+}
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index 98059872..5c869395 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -3,6 +3,7 @@
pub mod access;
pub mod accounts;
+pub mod agent_reviews;
pub mod alerts;
pub mod alignment_queue;
pub mod audit;
diff --git a/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md b/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md
index 9987d2af..9773c297 100644
--- a/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md
+++ b/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md
@@ -1,6 +1,6 @@
# 0061 · The ontology is proposed from the open graph and judged by its questions
-- **Status**: Accepted 2026-09-26 · 0044 cut 5 · cut 1 built (#947, migration 0077): competency questions are rows, the agent proposes from unbound signatures and kind words into `ontology_proposals`, adoption writes the element and re-decides its shapes through alignment · cuts 2–4 open · the ontology agent reads the open graph's unbound signatures and kind words against the base's competency questions and proposes types, properties and rules with definitions, examples and the signatures they would bind; approval writes the ontology and re-decides those signatures; every approved element carries regression cases; the ontology is measured by the questions it answers
+- **Status**: Accepted 2026-09-26 · 0044 cut 5 · cut 1 built (#947, migration 0077): competency questions are rows, the agent proposes from unbound signatures and kind words into `ontology_proposals`, adoption writes the element and re-decides its shapes through alignment · cut 1.1 (#950, migration 0078): the agent records every shape it saw, "already in the ontology" becomes a map_to proposal adopted as a person's binding per shape, adoption embeds the element before alignment · measured on a 100-document base: ~9k tokens a call, 12 calls a round, about half of a round's proposals adoptable as-is · cuts 2–4 open · the ontology agent reads the open graph's unbound signatures and kind words against the base's competency questions and proposes types, properties and rules with definitions, examples and the signatures they would bind; approval writes the ontology and re-decides those signatures; every approved element carries regression cases; the ontology is measured by the questions it answers
- **Written**: 2026-09-26 (conventions in the [README](README.md))
- **Related**: [0044](0044-the-ontology-is-a-view-over-what-documents-say.md) §4 decided the workbench and named this cut; [0003](0003-ontology-growth-loop.md) grew the ontology from `ontology_misses` and surface predicates, which [0044](0044-the-ontology-is-a-view-over-what-documents-say.md) cut 1 left idle and #725 retires; [0012](0012-the-ontology-is-a-contract-not-a-suggestion.md) makes every element a contract a person signed, which this record keeps; [0053](0053-a-phrase-decision-records-the-inputs-it-considered.md) is what makes approval re-decide signatures without a new mechanism; [0008](0008-ontology-packs-as-cold-start.md) is the second of the three sources; [0043](0043-every-review-queue-is-governed.md) and #725 give the queue its shape. From #725's "Ontology proposals" row and 0044's open question about a base with no questions.
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index ccad7e06..6eff5539 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -81,7 +81,7 @@ The test for writing one: if someone (including us) looks at a piece of code in
| 0053 | [A phrase decision records the inputs it considered](0053-a-phrase-decision-records-the-inputs-it-considered.md) | Implemented 2026-09-23 · a decision stores a fingerprint of the ancestor closures and admitted candidates it saw; stale means the fingerprint of the current inputs differs, which is what timestamps could not see (#807, #795): inheritance, parent edges, edits during the request; no-candidate and overflow become recorded outcomes; requeue reads live signatures only, so orphaned rows stop looping · revised 2026-09-26: kind words fingerprinted too, read from one snapshot and compared again when a reply is accepted
| 0054 | [A source may push statements in the open contract](0054-a-source-may-push-statements-in-the-open-contract.md) | Proposed 2026-09-23 · cut 1 in its PR · a `statements` source accepts the open extraction contract (`e`/`s`/`n`) verbatim on `POST /sources/{id}/statements` with the `api` push's identity, versions and tombstones; the payload is stored as one chunk and extraction parses it instead of prompting a model, then runs the unchanged path, so a pushed statement is an open statement and reaches the typed graph only through alignment; there is no slot for a property or class; an update marks earlier statements stale, it does not close them; tables stay on the mount (0036)
| 0060 | [A rule's definition has a history](0060-a-rule-definition-has-a-history.md) | Implemented 2026-09-25 (#912, migration 0076) · A business rule was edited in place and a derivation pointed at the row, so an invalidated conclusion pointed at a rule that now said something else. Every edit that changes what a rule says opens a **version**, a full snapshot with a record time; a derivation names the version it was drawn under, a kept conclusion moves to the new one, and the proof, the rules panel and a versions endpoint read the history. Name, description and the switch open nothing. Exporting rule bodies per version is now honest and stays #902's second cut |
-| 0061 | [The ontology is proposed from the open graph and judged by its questions](0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md) | Accepted · cut 1 built (#947): questions, agent proposals, adoption · cuts 2–4 open · A base's unbound signatures and classless kind words are what its documents say and its ontology cannot hold, and nothing says what the ontology is *for*. **Competency questions** become rows of the base and the standard an element is judged by; an **ontology agent** reads the unbound signatures and kind words against them and proposes types, properties and rules with a definition, the statements they would bind and the questions they serve; **approval** writes the element with its structure and re-decides those signatures through 0053's basis, and every approved element carries **regression cases** rerun when its definition changes. Measured by questions answered correctly and by the share of proposals people change. No automatic adoption; the 0003 `Suggest` retires once this replaces it |
+| 0061 | [The ontology is proposed from the open graph and judged by its questions](0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md) | Accepted · cut 1 built (#947): questions, agent proposals, adoption · cut 1.1 (#950): the agent remembers what it saw, existing answers become map_to · cuts 2–4 open · A base's unbound signatures and classless kind words are what its documents say and its ontology cannot hold, and nothing says what the ontology is *for*. **Competency questions** become rows of the base and the standard an element is judged by; an **ontology agent** reads the unbound signatures and kind words against them and proposes types, properties and rules with a definition, the statements they would bind and the questions they serve; **approval** writes the element with its structure and re-decides those signatures through 0053's basis, and every approved element carries **regression cases** rerun when its definition changes. Measured by questions answered correctly and by the share of proposals people change. No automatic adoption; the 0003 `Suggest` retires once this replaces it |
| 0062 | [The export says what is contested](0062-the-export-says-what-is-contested.md) | Proposed 2026-09-25 · #564: the RDF export carries `fact_conflicts` and `axiom_violations` as two distinct resource classes — conflicts point at the prior and incoming statements, violations at the statements they are about and (open rows only) the governing criterion and its relation; an ordered `rdf:List` keeps cycle paths; precondition is the current-ontology invariant: `status = 'open'` means reconciled against the current ontology, so criterion-changing ontology edits settle superseded open rows with `criterion_changed` and re-detect in the same transaction
| | Record | Domain | Status |
diff --git a/migrations/0078_the_agent_remembers_what_it_has_seen.sql b/migrations/0078_the_agent_remembers_what_it_has_seen.sql
new file mode 100644
index 00000000..72b4b680
--- /dev/null
+++ b/migrations/0078_the_agent_remembers_what_it_has_seen.sql
@@ -0,0 +1,24 @@
+-- 0061 · cut 1.1:代理记得自己看过什么。
+--
+-- 第一次真跑(bench4,100 篇):送去 120 条形状,35 条进了提案,其余 85 条没有任何记录,
+-- 下一轮按陈述数排序又是它们排在最前——每轮七成 token 花在模型已经看过、已经决定不提的
+-- 形状上。同一轮里模型答"本体里已经有"的(陈述最多的那些:died in → placeOfDeath、
+-- wrote → author)也被丢掉了,而那正是审核队列要的判断。
+--
+-- 每条送去的形状记一行:提了、已有、没提。提了的不再送(采纳后由对齐重判,拒绝了人已说过);
+-- 已有与没提的,等词表变了再送——basis 是看它时词表(类键 + 属性键)的指纹。
+CREATE TABLE ontology_agent_reviews (
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ -- phrase | kind_word
+ kind TEXT NOT NULL CHECK (kind IN ('phrase', 'kind_word')),
+ -- phrase: {"phrase","subject","object","value"};kind_word: {"kind_word"}
+ shape JSONB NOT NULL,
+ -- proposed | existing | declined
+ outcome TEXT NOT NULL CHECK (outcome IN ('proposed', 'existing', 'declined')),
+ -- proposed: 提案的 section:key;existing: 已有元素的键
+ target TEXT,
+ -- 看它时词表的指纹
+ basis TEXT NOT NULL,
+ reviewed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kb_id, kind, shape)
+);
diff --git a/web/src/api.ts b/web/src/api.ts
index 681d7e91..ecfd69e0 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1298,6 +1298,8 @@ export interface AgentProposalFields {
subject: string | null;
object: string | null;
value: boolean;
+ /** map_to 的形状:读属性的方向 forward | reverse */
+ direction?: string;
}[];
kind_words?: string[];
};
@@ -1342,14 +1344,16 @@ export interface OntologyProposals {
* 跟 relation_types 的区别是不建东西:同一个意思长出第二个 key,
* 这批事实就永久分在两处,谁也认不出它们本是一回事。
*/
- map_to?: {
+ map_to?: (AgentProposalFields & {
key: string;
/** 服务端标的:目标落在关系还是属性上。两条改写路径不一样,
- 而模型只答得出一个 key,看不出它在哪一档 */
+ 而模型只答得出一个 key,看不出它在哪一档。代理提的还有 class */
kind?: string;
+ /** 代理提的:目标的标签,人看键看不懂 */
+ label?: string;
forms?: string[];
reason?: string;
- }[];
+ })[];
}
/** 原文说过、本体里没有、因而事实没有谓词的说法。 */
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index 91965fc6..9afa5673 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -1809,10 +1809,32 @@ function UniquenessPanel({
);
}
+/** Suggest 提的那部分:批量加入只吃它们。代理提的每条都是人签的契约(0012),不进「全部加入」 */
+function manualOnly(d: OntologyProposals): OntologyProposals {
+ const own = <T extends { proposed_by?: string }>(xs: T[] | undefined) =>
+ (xs ?? []).filter((x) => x.proposed_by !== "agent");
+ return {
+ entity_types: own(d.entity_types),
+ relation_types: own(d.relation_types),
+ attribute_types: own(d.attribute_types),
+ map_to: own(d.map_to),
+ };
+}
+function manualCount(d: OntologyProposals): number {
+ const m = manualOnly(d);
+ return (
+ m.entity_types.length +
+ m.relation_types.length +
+ (m.attribute_types?.length ?? 0) +
+ (m.map_to?.length ?? 0)
+ );
+}
+
/** 库里现在有几条代理提的提案:等代理答完的判据 */
function agentCount(d: OntologyProposals | null | undefined): number {
if (!d) return 0;
return [
+ ...(d.map_to ?? []),
...d.entity_types,
...d.relation_types,
...(d.attribute_types ?? []),
@@ -1831,7 +1853,8 @@ function AgentMeta({
const shapeText = shapes
.map(
(sh) =>
- `${sh.subject ?? "?"} — ${sh.phrase} → ${sh.value ? "value" : (sh.object ?? "?")}`,
+ `${sh.subject ?? "?"} — ${sh.phrase} → ${sh.value ? "value" : (sh.object ?? "?")}` +
+ (sh.direction === "reverse" ? " (reverse)" : ""),
)
.join("\n");
const examples = (p.examples ?? []).join("\n");
@@ -2027,7 +2050,8 @@ function MissesPanel({
const empty =
!d.entity_types?.length &&
!d.relation_types?.length &&
- !d.attribute_types?.length;
+ !d.attribute_types?.length &&
+ !d.map_to?.length;
if (!empty) setProposals(d);
}
}, [storedProposals.data, proposals]);
@@ -2078,7 +2102,7 @@ function MissesPanel({
key,
reason,
}: {
- section: "entity_types" | "relation_types" | "attribute_types";
+ section: "map_to" | "entity_types" | "relation_types" | "attribute_types";
key: string;
reason?: string;
}) => api.decideProposal(kbId, section, key, "rejected", reason),
@@ -2095,7 +2119,7 @@ function MissesPanel({
onError,
});
const reject = (
- section: "entity_types" | "relation_types" | "attribute_types",
+ section: "map_to" | "entity_types" | "relation_types" | "attribute_types",
key: string,
) => {
const reason = window.prompt(S.ontology.rejectReasonPrompt) ?? "";
@@ -2259,14 +2283,24 @@ function MissesPanel({
// 映射到已有类型:不建东西,只把这些说法的事实挂过去。
// 跟新建走同一个采纳入口,因为它对图做的事一模一样——也因此同样可撤销
const approveMapping = useMutation({
- mutationFn: (p: { key: string; kind?: string; forms?: string[] }) =>
- api.adoptPredicate(kbId, {
- key: p.key,
- existing: true,
- // 目标是属性时值要按它的 datatype 换算,服务端据此分道
- kind: p.kind === "attribute" ? "attribute" : "relation",
- forms: p.forms ?? [],
- }),
+ // 代理提的「已有」:形状各写一条人的绑定判定(0061 cut 1.1),走采纳端点
+ mutationFn: (p: {
+ key: string;
+ kind?: string;
+ forms?: string[];
+ proposed_by?: string;
+ }) =>
+ p.proposed_by === "agent"
+ ? api
+ .adoptProposal(kbId, "map_to", p.key)
+ .then(() => ({}) as Awaited<ReturnType<typeof api.adoptPredicate>>)
+ : api.adoptPredicate(kbId, {
+ key: p.key,
+ existing: true,
+ // 目标是属性时值要按它的 datatype 换算,服务端据此分道
+ kind: p.kind === "attribute" ? "attribute" : "relation",
+ forms: p.forms ?? [],
+ }),
onSuccess: (data, p) => {
const moved = data.remapped ?? 0;
const left = data.unconvertible ?? 0;
@@ -2580,26 +2614,17 @@ function MissesPanel({
{S.ontology.proposals}
</h4>
{/* 常见情形是"这些都对"——一条条点是把一个决定拆成八个 */}
- {proposals.relation_types.length +
- proposals.entity_types.length +
- (proposals.attribute_types?.length ?? 0) +
- (proposals.map_to?.length ?? 0) >
- 1 && (
+ {manualCount(proposals) > 1 && (
<Button
size="sm"
variant="secondary"
className="ml-auto"
disabled={addAll.isPending}
- onClick={() => addAll.mutate(proposals)}
+ onClick={() => addAll.mutate(manualOnly(proposals))}
>
{addAll.isPending
? S.ontology.addingAll
- : S.ontology.addAll(
- proposals.relation_types.length +
- proposals.entity_types.length +
- (proposals.attribute_types?.length ?? 0) +
- (proposals.map_to?.length ?? 0),
- )}
+ : S.ontology.addAll(manualCount(proposals))}
</Button>
)}
</div>
@@ -2610,6 +2635,7 @@ function MissesPanel({
<div key={`map-${p.key}`} className="flex items-center gap-2 text-body">
<Chip tone="success">=</Chip>
<span className="font-mono text-ink-2">{p.key}</span>
+ {p.label && <span className="text-ink">{p.label}</span>}
{!!p.forms?.length && (
<span
className="text-small text-ink-2 truncate"
@@ -2618,7 +2644,8 @@ function MissesPanel({
{p.forms.join(" · ")}
</span>
)}
- {!!p.forms?.length && (
+ {/* 改写多少条是 0003 那条路的账;代理提的走绑定,形状数在 AgentMeta 里 */}
+ {!!p.forms?.length && p.proposed_by !== "agent" && (
<span className="text-small text-accent">
{S.ontology.willRemap(factsWaiting(p.forms))}
</span>
@@ -2628,6 +2655,7 @@ function MissesPanel({
{p.reason}
</span>
)}
+ <AgentMeta p={p} />
<Button variant="primary"
size="sm"
className="ml-auto"
@@ -2636,6 +2664,16 @@ function MissesPanel({
>
{S.ontology.mapOver}
</Button>
+ {p.proposed_by === "agent" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => reject("map_to", p.key)}
+ disabled={rejectProposal.isPending}
+ >
+ {S.ontology.rejectProposal}
+ </Button>
+ )}
</div>
))}
{proposals.entity_types.map((p) => (
@@ -2677,7 +2715,7 @@ function MissesPanel({
{p.temporal && <Chip tone="neutral">{p.temporal}</Chip>}
{/* 影响面:采纳后会改写多少条、归并了哪些写法。没有这个,
"approve" 就只是凭空多一个空关系 */}
- {!!p.forms?.length && (
+ {!!p.forms?.length && p.proposed_by !== "agent" && (
<span
className="text-small text-accent"
title={p.forms.join(" · ")}
@@ -2719,7 +2757,7 @@ function MissesPanel({
<span className="text-ink">{p.label}</span>
<Chip tone="neutral">{p.datatype ?? "text"}</Chip>
{p.unit && <Chip tone="neutral">{p.unit}</Chip>}
- {!!p.forms?.length && (
+ {!!p.forms?.length && p.proposed_by !== "agent" && (
<span
className="text-small text-accent"
title={p.forms.join(" · ")}