World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A reuse keeps what a person decided after the agent read it (#1288)
Maya Kid86bd5da5f9cd
diff --git a/crates/utopia-server/src/api/question_routes.rs b/crates/utopia-server/src/api/question_routes.rsindex 2502e724..ecf967a2 100644--- a/crates/utopia-server/src/api/question_routes.rs+++ b/crates/utopia-server/src/api/question_routes.rs@@ -249,7 +249,8 @@ pub struct AdoptReq {pub edits: ontology_agent::AdoptEdits,}-/// 采纳一条提案(人改过的几格随请求来):建元素、标记、排对齐+/// 采纳一条提案(人改过的几格随请求来):元素、回归用例、采纳的状态和后续任务一次提交。+/// 复用时,代理读过之后人另定了、和提案不一样的形状或类别词留着没写,列在 `skipped` 里pub async fn adopt(State(state): State<AppState>,AuthUser(user): AuthUser,@@ -257,7 +258,9 @@ pub async fn adopt(Json(req): Json<AdoptReq>,) -> ApiResult<Json<serde_json::Value>> {utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?;- let id =+ let adopted =ontology_agent::adopt(&state, kb_id, &req.section, &req.key, req.edits, user.id).await?;- Ok(Json(json!({ "id": id })))+ Ok(Json(+ json!({ "id": adopted.id, "skipped": adopted.skipped }),+ ))}diff --git a/crates/utopia-server/src/ontology_agent.rs b/crates/utopia-server/src/ontology_agent.rsindex 449e8391..6b61a96b 100644--- a/crates/utopia-server/src/ontology_agent.rs+++ b/crates/utopia-server/src/ontology_agent.rs@@ -7,6 +7,7 @@use std::collections::{HashMap, HashSet};+use chrono::{DateTime, Utc};use serde::Deserialize;use serde_json::{json, Value};use sha2::{Digest, Sha256};@@ -107,6 +108,8 @@ struct Merged {shapes: Vec<Value>,phrases: Vec<String>,words: Vec<String>,+ /// 复用时代理读到每个类别词的判定是哪一刻定的,同形状上的 `seen_decided_at`+ words_seen: serde_json::Map<String, Value>,quotes: Vec<String>,serves: Vec<Uuid>,}@@ -405,6 +408,10 @@ async fn propose_locked(}).collect();tracing::info!(%kb_id, shapes = open.len(), kind_words = open_words.len(), questions = questions.len(), calls, "本体代理开始");+ // 复用提案记下代理读到的判定是哪一刻定的:采纳时人的判定不是那一刻的,就是代理读过之后定的,+ // 复用不替人改。不拿提案行存入的时刻比:那在全部模型调用之后,下一轮并进同一行时还会再挪+ let seen_shape = |s: &PhraseSignature| bindings.get(&s.key()).map(|b| b.decided_at);+ let seen_word = |w: &KindWordSignature| word_bindings.get(&w.kind_word).map(|b| b.decided_at);let mut merged: HashMap<String, Merged> = HashMap::new();let mut order: Vec<String> = Vec::new();@@ -485,6 +492,7 @@ async fn propose_locked(shapes: Vec::new(),phrases: Vec::new(),words: Vec::new(),+ words_seen: serde_json::Map::new(),quotes: Vec::new(),serves: Vec::new(),}@@ -493,14 +501,14 @@ async fn propose_locked(// 类接的是类别词;形状指给类是答错了格,不记for id in &e.kind_words {if let Some(w) = open_words.get(*id as usize) {- push_word(entry, w);+ push_word(entry, w, seen_word(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());+ push_shape(entry, sig, e.direction.as_deref(), seen_shape(sig));sig_outcome.insert(*id, ("existing", e.key.clone()));}}@@ -530,23 +538,25 @@ async fn propose_locked(shapes: Vec::new(),phrases: Vec::new(),words: Vec::new(),+ words_seen: serde_json::Map::new(),quotes: Vec::new(),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;};- push_shape(entry, s, None);+ push_shape(entry, s, None, 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;};- push_word(entry, w);+ push_word(entry, w, None);word_outcome.insert(id, ("proposed", target.clone()));}for id in p.questions {@@ -625,7 +635,8 @@ async fn propose_locked("proposed_by": "agent",}),serves: Vec::new(),- signatures: json!({ "phrases": m.shapes, "kind_words": m.words }),+ signatures: json!({ "phrases": m.shapes, "kind_words": m.words,+ "kind_words_seen_decided_at": m.words_seen }),};}let section = section_of(p);@@ -752,11 +763,19 @@ fn same_shape(a: &Value, b: &Value) -> bool {.all(|k| a.get(k) == b.get(k))}-fn push_shape(entry: &mut Merged, s: &PhraseSignature, direction: Option<&str>) {+fn push_shape(+ entry: &mut Merged,+ s: &PhraseSignature,+ direction: Option<&str>,+ seen: Option<DateTime<Utc>>,+) {let mut shape = shape_of(s);if let Some(d) = direction {shape["direction"] = json!(d);}+ if let Some(at) = seen {+ shape["seen_decided_at"] = json!(at);+ }if entry.shapes.iter().any(|x| same_shape(x, &shape)) {return;}@@ -771,11 +790,14 @@ fn push_shape(entry: &mut Merged, s: &PhraseSignature, direction: Option<&str>)}}-fn push_word(entry: &mut Merged, w: &KindWordSignature) {+fn push_word(entry: &mut Merged, w: &KindWordSignature, seen: Option<DateTime<Utc>>) {if entry.words.contains(&w.kind_word) {return;}entry.words.push(w.kind_word.clone());+ if let Some(at) = seen {+ entry.words_seen.insert(w.kind_word.clone(), json!(at));+ }for e in w.examples.iter().take(1) {if entry.quotes.len() < 3 && !entry.quotes.contains(e) {entry.quotes.push(e.clone());@@ -822,10 +844,24 @@ fn merge_map_to(let words = union("kind_words", false);let forms = union("forms", true);let examples: Vec<String> = union("examples", true).into_iter().take(3).collect();+ // 形状带着各自读到的时刻并过来了;类别词的另存一格,也要并。只留这一轮的,上一轮的词就+ // 没了读到的时刻,采纳时连代理读过的那个人的判定也不替换了+ let seen_of = |signatures: &Value| {+ signatures+ .get("kind_words_seen_decided_at")+ .and_then(Value::as_object)+ .cloned()+ .unwrap_or_default()+ };+ let mut words_seen = seen_of(&prev.signatures);+ for (w, at) in seen_of(&it.signatures) {+ words_seen.entry(w).or_insert(at);+ }it.payload["forms"] = json!(forms);it.payload["kind_words"] = json!(words);it.payload["examples"] = json!(examples);- it.signatures = json!({ "phrases": shapes, "kind_words": words });+ it.signatures = json!({ "phrases": shapes, "kind_words": words,+ "kind_words_seen_decided_at": words_seen });}fn datatype_or_text(d: Option<&str>) -> &str {@@ -854,9 +890,52 @@ fn strings(v: Option<&Value>) -> Vec<String> {.collect()}+/// 采纳的回执+#[derive(Debug)]+pub struct Adopted {+ /// 新元素的 id;复用时是目标的 id+ pub id: Uuid,+ /// 复用时留着没写的形状或类别词,各带人定成了什么:代理读过之后人另定了、和提案不一样的。+ /// 两个人的判断不一样,采纳的人得看见,所以列出来而不是悄悄跳过+ pub skipped: Vec<Value>,+}++/// 一条绑定此刻的判定:谁、什么时候定的、定成了什么(比的时候用 id,回执里写键)+#[derive(sqlx::FromRow)]+struct Decided {+ decided_by: String,+ decided_at: DateTime<Utc>,+ status: String,+ target_id: Option<Uuid>,+ target: Option<String>,+ #[sqlx(default)]+ direction: Option<String>,+}++impl Decided {+ /// 人在代理读过它之后定的。提案答的是代理读到的那个判定,那个照样替掉;之后人定的,提案和+ /// 采纳的人看的卡片都没见过,不替人改。只看是不是代理读到的那一刻,不比先后:`decided_at`+ /// 是定它的事务开始的时刻,先开始、后提交的人的判定,时刻会早于代理读到的那个。没记下读到+ /// 哪一刻的(这一格之前存的提案),人的判定一概不改+ fn by_person_after_read(&self, read: Option<DateTime<Utc>>) -> bool {+ self.decided_by == "person" && read.is_none_or(|at| at != self.decided_at)+ }++ /// 和提案定得一样:绑到同一个属性、同一个方向,或同一个类(类别词没有方向)+ fn agrees(&self, target: Uuid, direction: Option<&str>) -> bool {+ self.status == "bound"+ && self.target_id == Some(target)+ && self.direction.as_deref() == direction+ }+}++/// 代理读到这条判定时它的 `decided_at`(`push_shape`、`push_word` 记下的)+fn read_at(seen: Option<&Value>) -> Option<DateTime<Utc>> {+ seen.and_then(|v| serde_json::from_value(v.clone()).ok())+}+/// 采纳一条代理提案(0061 决定 3):锁住提案,在一个事务里重读并锁住它要的类或复用的目标,-/// 写元素(复用时写人的判定)、回归用例、采纳的状态和后续任务,一次提交。返回新元素的 id,-/// 复用时是目标的 id。+/// 写元素(复用时写人的判定)、回归用例、采纳的状态和后续任务,一次提交。////// 从前这几步各自提交:属性先落库,例句写回归用例时才发现宾语是实体(`bad_property_shape`),/// 留下一个没有提案采纳过的属性、一份排着的对齐,和一条键已被占、再也采纳不了的提案@@ -867,10 +946,10 @@ pub async fn adopt(key: &str,edits: AdoptEdits,actor: Uuid,-) -> Result<Uuid, AppError> {+) -> Result<Adopted, AppError> {let pool = &state.pool;let mut tx = pool.begin().await?;- let (id, detail) = match adopt_on(&mut tx, kb_id, section, key, edits, actor).await {+ let (adopted, detail) = match adopt_on(&mut tx, kb_id, section, key, edits, actor).await {Ok(done) => done,Err(error) => {// 回滚完再答:马上重试的请求不会撞上这次还没放掉的锁@@ -890,7 +969,7 @@ pub async fn adopt(actor,"ontology_proposal.adopted",section.trim_end_matches('s'),- Some(id),+ Some(adopted.id),detail,).await;@@ -898,7 +977,7 @@ pub async fn adopt(if section == "map_to" {state.emit_review(kb_id);}- Ok(id)+ Ok(adopted)}/// 采纳和别的写撞上、整个事务回滚了,什么都没留下,重试是安全的:答审核页认得、可以重试的@@ -957,7 +1036,7 @@ struct Locked {proposal: StoredProposal,}-/// 采纳在事务里的全部;返回元素的 id 和审计要记的几格+/// 采纳在事务里的全部;返回回执和审计要记的几格async fn adopt_on(tx: &mut Transaction<'_, Postgres>,kb_id: Uuid,@@ -965,7 +1044,7 @@ async fn adopt_on(key: &str,edits: AdoptEdits,actor: Uuid,-) -> Result<(Uuid, Value), AppError> {+) -> Result<(Adopted, Value), AppError> {// 先锁提案:同一条的另一次采纳、拒绝和代理的刷新都等这次提交,提交后它已不再开着。// 只认代理提的:旧 Suggest 留下的提案没有采纳的入口let locked: Option<Locked> = sqlx::query_as(@@ -1005,9 +1084,10 @@ async fn adopt_on(.unwrap_or("").trim().to_string();+ let mut skipped = Vec::new();let id = match section {// 「用已有的」:形状各写一条人的绑定判定(同审核页),类别词各归到那个类- "map_to" => adopt_map_to(tx, kb_id, p).await?,+ "map_to" => adopt_map_to(tx, kb_id, p, &mut skipped).await?,"entity_types" => {let parents = lock_classes(tx,@@ -1090,10 +1170,10 @@ async fn adopt_on())}};- finish_adoption(tx, kb_id, &locked, id, actor, edited).await?;+ finish_adoption(tx, kb_id, &locked, id, actor, edited, &skipped).await?;let detail =json!({ "key": key, "label": label, "proposed_by": p.proposed_by, "serves": p.serves });- Ok((id, detail))+ Ok((Adopted { id, skipped }, detail))}/// 新元素的后续任务,和元素一起提交:先补向量、再对齐,同编辑器的次序。新元素要有向量,对齐@@ -1124,7 +1204,8 @@ async fn embed_then_align(}/// 回归用例和采纳的状态(决定 4),在采纳的事务里。人改过没有(决定 5 的第二个数)和状态同一条-/// UPDATE 写下:从前是采纳提交之后的另一条语句+/// UPDATE 写下:从前是采纳提交之后的另一条语句。复用留着没写的形状(`skipped`)不写用例:人定得+/// 和提案不一样;人后来定得一样的照写async fn finish_adoption(tx: &mut Transaction<'_, Postgres>,kb_id: Uuid,@@ -1132,6 +1213,7 @@ async fn finish_adoption(property_id: Uuid,actor: Uuid,edited: bool,+ skipped: &[Value],) -> Result<(), AppError> {let proposal = &locked.proposal;let mut examples = Vec::new();@@ -1147,6 +1229,7 @@ async fn finish_adoption(.and_then(Value::as_array).into_iter().flatten()+ .filter(|shape| !skipped.iter().any(|s| same_shape(s, shape))){let ids = match shape.get("example_statement_ids") {Some(ids) => serde_json::from_value::<Vec<Uuid>>(ids.clone()).map_err(|_| {@@ -1194,17 +1277,23 @@ async fn finish_adoption(/// map_to 的采纳,在采纳的事务里:目标是属性,提案里的每条形状写成人的绑定(属性 + 方向),/// 投影跟着排(同审核页的 `decide_alignment_phrase`);目标是类,每个类别词归到它,短语对齐-/// 跟着排。返回目标的 id+/// 跟着排。返回目标的 id。+///+/// 代理读过之后人另定了的形状或类别词不写:和提案一样的算已写(形状照样有回归用例),不一样的+/// 原样留着、记进 `skipped`。一条也写不了的不算采纳async fn adopt_map_to(tx: &mut Transaction<'_, Postgres>,kb_id: Uuid,p: &StoredProposal,+ skipped: &mut Vec<Value>,) -> Result<Uuid, AppError> {let kind = p.payload.get("kind").and_then(Value::as_str).unwrap_or("relation");+ // 这次写下的;人在代理读过之后定得和提案一样、算作已写的+ let (mut written, mut agreed) = (0usize, 0usize);if kind == "class" {let class = lock_classes(tx, kb_id, std::slice::from_ref(&p.key)).await?[0];// 实体正被抽取或对齐改着时只等 2 秒,同审核页的类别词判定@@ -1212,18 +1301,52 @@ async fn adopt_map_to(.execute(&mut **tx).await?;let votes = json!({ "person": p.key, "via": "ontology_agent" });+ let seen = p.signatures.get("kind_words_seen_decided_at");for w in strings(p.signatures.get("kind_words")) {- type_bindings::decide_and_apply_human_tx(tx, kb_id, &w, Some(class), &votes).await?;+ // 已有的绑定行先锁住再看:看过之后、写下之前,人改不了它。还没有这一行时锁不住,+ // 人第一次定它可能被这次写盖掉。类的键用子查询读,不连表:等到别人提交了这一行,+ // Postgres 拿新版本重算这条查询,连表连上的却还是等之前那一行(EvalPlanQual),+ // 回执里人刚定的类就成了空+ let now: Option<Decided> = sqlx::query_as(+ "SELECT b.decided_by, b.decided_at, b.status, b.type_id AS target_id,+ (SELECT t.key FROM entity_types t WHERE t.id = b.type_id) AS target+ FROM type_bindings b+ WHERE b.kb_id = $1 AND b.kind_word = $2 FOR UPDATE OF b",+ )+ .bind(kb_id)+ .bind(type_bindings::normalize(&w))+ .fetch_optional(&mut **tx)+ .await?;+ let read = read_at(seen.and_then(|s| s.get(w.as_str())));+ if let Some(d) = now.filter(|d| d.by_person_after_read(read)) {+ if d.agrees(class, None) {+ // 不重写:判定还是那个人的+ agreed += 1;+ } else {+ skipped.push(json!({ "kind_word": w,+ "person": { "status": d.status, "class": d.target } }));+ }+ continue;+ }+ if type_bindings::decide_and_apply_human_tx(tx, kb_id, &w, Some(class), &votes).await? {+ written += 1;+ }+ }+ if written + agreed == 0 {+ return Err(nothing_left());+ }+ // 换了类,这些实体的短语签名跟着变:短语对齐和判定一起提交,整次采纳排一份;一个词都没写+ // 就不排,人定的那次已经排过。照排,不看有没有同样的排着,理由同 `embed_then_align`:+ // 排着的那份可能在这次提交之前就被领走+ if written > 0 {+ utopia_store::jobs::enqueue_with_max_attempts_tx(+ tx,+ "align_phrases",+ json!({ "kb_id": kb_id }),+ 3,+ )+ .await?;}- // 换了类,这些实体的短语签名跟着变:短语对齐和判定一起提交,整次采纳排一份。照排,不看- // 有没有同样的排着,理由同 `embed_then_align`:排着的那份可能在这次提交之前就被领走- utopia_store::jobs::enqueue_with_max_attempts_tx(- tx,- "align_phrases",- json!({ "kb_id": kb_id }),- 3,- )- .await?;return Ok(class);}// 目标在事务里重读并锁住防删(FOR KEY SHARE,理由同 `lock_classes`):采纳提交之前它删不掉@@ -1237,7 +1360,6 @@ async fn adopt_map_to(let property = property.ok_or_else(|| AppError::invalid("unknown_property", "no property with that key"))?;let sigs = phrase_bindings::signatures(&mut **tx, kb_id).await?;- let mut written = false;for shape in p.signatures.get("phrases")@@ -1253,8 +1375,40 @@ async fn adopt_map_to(Some("reverse") => "reverse",_ => "forward",};+ // 已有的绑定行先锁住再看,属性的键用子查询读,同类别词+ let now: Option<Decided> = sqlx::query_as(+ "SELECT b.decided_by, b.decided_at, b.status, b.relation_type_id AS target_id,+ (SELECT r.key FROM relation_types r WHERE r.id = b.relation_type_id) AS target,+ b.direction+ FROM phrase_bindings b+ WHERE b.kb_id = $1 AND b.phrase = $2 AND b.subject_type_id IS NOT DISTINCT FROM $3+ AND b.object_type_id IS NOT DISTINCT FROM $4 AND b.object_is_value = $5+ FOR UPDATE OF b",+ )+ .bind(kb_id)+ .bind(phrase_bindings::normalize(&sig.phrase))+ .bind(sig.subject_type_id)+ .bind(sig.object_type_id.filter(|_| !sig.object_is_value))+ .bind(sig.object_is_value)+ .fetch_optional(&mut **tx)+ .await?;+ if let Some(d) =+ now.filter(|d| d.by_person_after_read(read_at(shape.get("seen_decided_at"))))+ {+ if d.agrees(property, Some(direction)) {+ // 不重写:判定还是那个人的,回归用例照写+ agreed += 1;+ } else {+ // 形状的四格同提案里那条:`finish_adoption` 凭它认出这条,不写回归用例+ skipped.push(json!({+ "phrase": sig.phrase, "subject": sig.subject_type_key,+ "object": sig.object_type_key, "value": sig.object_is_value,+ "person": { "status": d.status, "property": d.target, "direction": d.direction } }));+ }+ continue;+ }let votes = json!({ "person": { "property": p.key, "direction": direction, "via": "ontology_agent" } });- written |= phrase_bindings::decide_on(+ if phrase_bindings::decide_on(tx,kb_id,sig,@@ -1269,9 +1423,15 @@ async fn adopt_map_to(marks_asked: false,},)- .await?;+ .await?+ {+ written += 1;+ }+ }+ if written + agreed == 0 {+ return Err(nothing_left());}- if written {+ if written > 0 {// 判定和它的投影一起提交(0051)。整次提交排一份,不是一条形状一份:这些判定都和这一份// 同一次提交,它跑时读当下的绑定,0051 要的「每条判定都有和它一起提交的任务」照样成立utopia_store::jobs::enqueue_with_max_attempts_tx(@@ -1285,6 +1445,16 @@ async fn adopt_map_to(Ok(property)}+/// 复用的形状或类别词一条也写不了:都是人定得和提案不一样、照人留着的,或都没有陈述了。话里+/// 不说人是代理读过之后定的:没记下读到哪一刻的旧提案,人在提案之前定的也照留+fn nothing_left() -> AppError {+ AppError::CodedConflict {+ code: "proposal_stale",+ message: "Nothing in this proposal is left to write: each of its shapes or kind words is decided differently by a person or has no statements any more."+ .into(),+ }+}+/// 任务入口:给库提问题(决定 1 的"没有问题的库不被卡住")。界面上点、或本体代理发现库里/// 一条问题都没有时走这里pub async fn propose_questions(state: &AppState, kb_id: Uuid) -> anyhow::Result<usize> {diff --git a/crates/utopia-server/src/ontology_agent_tests.rs b/crates/utopia-server/src/ontology_agent_tests.rsindex 410f4f6d..e6073af9 100644--- a/crates/utopia-server/src/ontology_agent_tests.rs+++ b/crates/utopia-server/src/ontology_agent_tests.rs@@ -428,7 +428,8 @@ async fn an_unbound_shape_becomes_a_proposal_that_serves_a_question_and_adoption},f.user,)- .await?;+ .await?+ .id;let props = utopia_store::ontology::relation_type_views(&f.pool, f.kb).await?;let built = props.iter()@@ -670,7 +671,8 @@ async fn a_declined_shape_returns_when_its_statements_double_and_an_existing_ansAdoptEdits::default(),f.user,)- .await?;+ .await?+ .id;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")] {@@ -949,6 +951,217 @@ async fn a_class_reuse_queues_its_own_phrase_alignment() -> anyhow::Result<()> {f.cleanup().await}+/// 复用替掉的是代理读到的那个判定,读过之后人定的照人留着。founded in、firm 是人在代理读之前+/// 说的「没有」,照样替掉(firm 是第一轮读的,company 下一轮并进同一行,并的时候不丢它读到的时刻);+/// located in、company 是读过之后人绑到别处的,留着、列在回执里,located in 还是同事在采纳等着那一行+/// 时才提交的;headquartered in、wharf 是读过之后人绑得和提案一样的,算已写:不重写、不列,形状照样+/// 有回归用例;只有 wharf 的那条复用什么都没写,不另排短语对齐。venue 那条一个也写不了,整条不算+/// 采纳;没记下读到哪一刻的旧提案,人的判定一概不改+#[tokio::test]+async fn a_reuse_keeps_what_a_person_decided_after_the_agent_read_it() -> anyhow::Result<()> {+ let Some(f) = Fx::new(vec![+ // 形状按短语排:s0 founded in、s1 headquartered in、s2 located in;+ // 类别词 k0 firm、k1 venue、k2 wharf+ json!({ "p": [], "existing": [{ "key": "located_in", "s": [0, 1, 2] },+ { "key": "organization", "k": [0] }, { "key": "place", "k": [1] },+ { "key": "site", "k": [2] }] }),+ json!({ "p": [], "existing": [{ "key": "organization", "k": [0] }] }),+ ])+ .await?+ else {+ return Ok(());+ };+ f.decide_none().await?;+ f.seed_question().await?;+ let based_in = Uuid::now_v7();+ let site = Uuid::now_v7();+ // 类别词放在不出现在陈述里的实体上:归了类,形状的两端也不跟着变+ sqlx::raw_sql(&format!(+ "INSERT INTO relation_types(id,kb_id,key,label,kind,temporal,description)+ VALUES ('{based_in}','{kb}','based_in','based in','relation','state','x');+ INSERT INTO entity_types(id,kb_id,key,label,color,shape,description)+ VALUES ('{site}','{kb}','site','Site','#000','circle','x');+ INSERT INTO facts(id,kb_id,subject_id,object_id,layer,phrase)+ SELECT '{fact}', kb_id, subject_id, object_id, 'open', 'headquartered in'+ FROM facts WHERE kb_id='{kb}' AND phrase='located in';+ INSERT INTO entities(id,kb_id,canonical_name,specific_type) VALUES+ ('{}','{kb}','Initech','firm'), ('{}','{kb}','Hall','venue'),+ ('{}','{kb}','Globex','company'), ('{}','{kb}','Pier','wharf');",+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ Uuid::now_v7(),+ kb = f.kb,+ fact = Uuid::now_v7(),+ ))+ .execute(&f.pool)+ .await?;+ let votes = json!({ "person": "test" });+ let word = |w: &'static str, class: Option<Uuid>, by: &'static str| {+ let status = if class.is_some() { "bound" } else { "none" };+ type_bindings::decide(&f.pool, f.kb, w, &[], class, status, &votes, by)+ };+ let sigs = phrase_bindings::signatures(&f.pool, f.kb).await?;+ let sig = |phrase: &str| sigs.iter().find(|s| s.phrase == phrase).unwrap();+ let person = |property: Option<Uuid>| Decision {+ relation_type_id: property,+ direction: property.map(|_| "forward"),+ status: if property.is_some() { "bound" } else { "none" },+ votes: &votes,+ decided_by: "person",+ basis: None,+ marks: None,+ marks_asked: false,+ };+ let shape = |phrase: &str, property: Option<Uuid>| {+ phrase_bindings::decide(&f.pool, f.kb, sig(phrase), person(property))+ };+ shape("founded in", None).await?;+ shape("headquartered in", None).await?;+ word("firm", None, "person").await?;+ word("venue", None, "agent").await?;+ word("wharf", None, "agent").await?;+ // company 还没判过,这一轮不送;判成「没有」后下一轮才送+ propose(&f.state, f.kb).await?;+ word("company", None, "agent").await?;+ propose(&f.state, f.kb).await?;+ assert_eq!(f.requests().await, 2);++ // 代理读过之后人定的+ shape("headquartered in", Some(f.located_in)).await?;+ word("company", Some(f.place), "person").await?;+ word("venue", Some(f.organization), "person").await?;+ word("wharf", Some(site), "person").await?;+ // located in 是同事定的,等 located_in 的采纳排到那一行后面才提交。那次的事务在代理读到的判定+ // 之前就开始了:decided_at 是事务开始的时刻,比读到的还早,照样是读过之后定的+ let mut deciding = f.pool.begin().await?;+ let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")+ .fetch_one(&mut *deciding)+ .await?;+ let colleague = person(Some(based_in));+ phrase_bindings::decide_on(&mut deciding, f.kb, sig("located in"), colleague).await?;+ sqlx::query(+ "UPDATE phrase_bindings SET decided_at = decided_at - interval '1 day'+ WHERE kb_id = $1 AND phrase = 'located in'",+ )+ .bind(f.kb)+ .execute(&mut *deciding)+ .await?;+ let pool = f.pool.clone();+ let commit = async move {+ for _ in 0..500 {+ let waiting: bool = sqlx::query_scalar(+ "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))",+ )+ .bind(pid)+ .fetch_one(&pool)+ .await?;+ if waiting {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ deciding.commit().await?;+ anyhow::Ok(())+ };++ let adopt = |key: &str| json!({ "section": "map_to", "key": key });+ let ((status, body), ()) = tokio::try_join!(+ f.post("/ontology/proposals/adopt", adopt("located_in")),+ commit+ )?;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ body["skipped"],+ json!([{ "phrase": "located in", "subject": "organization", "object": "place", "value": false,+ "person": { "status": "bound", "property": "based_in", "direction": "forward" } }])+ );+ let (status, body) = f+ .post("/ontology/proposals/adopt", adopt("organization"))+ .await?;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ body["skipped"],+ json!([{ "kind_word": "company", "person": { "status": "bound", "class": "place" } }])+ );+ let (status, body) = f.post("/ontology/proposals/adopt", adopt("site")).await?;+ assert_eq!(+ (status, &body["skipped"]),+ (StatusCode::OK, &json!([])),+ "{body}"+ );+ let (status, body) = f.post("/ontology/proposals/adopt", adopt("place")).await?;+ assert_eq!(+ (status, &body["code"]),+ (StatusCode::CONFLICT, &json!("proposal_stale")),+ "{body}"+ );+ // 这一格之前存的复用没记读到的时刻:founded in 此刻是人的判定,不改,整条不算采纳+ let reuse = json!({ "key": "based_in", "kind": "relation", "proposed_by": "agent" });+ let shapes = json!({ "phrases": [f.shape("founded in").await?] });+ f.seed("map_to", "based_in", reuse, shapes).await?;+ let (status, body) = f+ .post("/ontology/proposals/adopt", adopt("based_in"))+ .await?;+ assert_eq!(+ (status, &body["code"]),+ (StatusCode::CONFLICT, &json!("proposal_stale")),+ "{body}"+ );++ type Row = (String, Option<String>, Option<String>);+ let row = |s: &str, key: &str, via: Option<&str>| -> Row {+ (s.into(), Some(key.into()), via.map(Into::into))+ };+ let shapes: Vec<Row> = sqlx::query_as(+ "SELECT b.phrase, r.key, b.votes #>> '{person,via}' FROM phrase_bindings b+ LEFT JOIN relation_types r ON r.id = b.relation_type_id WHERE b.kb_id = $1 ORDER BY 1",+ )+ .bind(f.kb)+ .fetch_all(&f.pool)+ .await?;+ let words: Vec<Row> = sqlx::query_as(+ "SELECT b.kind_word, t.key, b.votes->>'via' FROM type_bindings b+ LEFT JOIN entity_types t ON t.id = b.type_id WHERE b.kb_id = $1 ORDER BY 1",+ )+ .bind(f.kb)+ .fetch_all(&f.pool)+ .await?;+ let via = Some("ontology_agent");+ assert_eq!(+ (shapes, words),+ (+ vec![+ row("founded in", "located_in", via),+ row("headquartered in", "located_in", None),+ row("located in", "based_in", None),+ ],+ vec![+ row("company", "place", None),+ row("firm", "organization", via),+ row("venue", "organization", None),+ row("wharf", "site", None),+ ]+ ),+ "what the agent read is replaced; what a person decided after it stays theirs"+ );+ let cases: Vec<String> = sqlx::query_scalar(+ "SELECT f.phrase FROM ontology_regression_cases c JOIN facts f ON f.id = c.statement_id+ WHERE c.kb_id = $1 ORDER BY 1",+ )+ .bind(f.kb)+ .fetch_all(&f.pool)+ .await?;+ assert_eq!(+ cases,+ ["founded in", "headquartered in"],+ "none for the kept shape"+ );+ // venue 那条还开着。后三次都没多排任务、没多写用例:两份任务、两条用例都是前两次采纳的+ assert_eq!(f.left_by("place").await?, (true, "open".to_string(), 2, 2));+ f.cleanup().await+}+/// 采纳途中,提案要的类被删了:等删完答 unknown_class,什么都不写,不是写父类时才撞上外键#[tokio::test]async fn a_class_deleted_during_adoption_answers_unknown_class() -> anyhow::Result<()> {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.mdindex 219055dd..589b510e 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**: In progress · accepted 2026-09-26 · cuts 1 and 1.1 built (#947, #950), cut 3 slices 1–2 (#955, #962) · revised 2026-10-16 (#1257) · open: cut 2, the rest of cut 3, cut 4+- **Status**: In progress · accepted 2026-09-26 · cuts 1 and 1.1 built (#947, #950), cut 3 slices 1–2 (#955, #962) · revised 2026-10-16 (#1257) · revised 2026-10-17 (#1288) · open: cut 2, the rest of cut 3, cut 4- **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.@@ -20,6 +20,8 @@ The open graph holds statements with their phrases, quotes, kind words and names**Revision 2026-10-16 (adoption is one commit, #1257):** decision 3 did not say that adopting is one operation, and adoption committed the element, its alignment job and the adopted status separately, embedding the element inside the request; an attribute whose example statement has an entity object was committed before its regression case was refused, leaving an element no proposal adopted. Adopting now commits the element (for a reuse, the person's bindings), its regression cases, the adopted status and its follow-up jobs together or not at all, and makes no model call: like the editor, it queues `embed_ontology` ahead of alignment. Only adoption adopts; the status-only endpoint rejects.+**Revision 2026-10-17 (a reuse keeps what a person decided after the agent read it, #1288):** decision 3's "A signature a person decided stays as the person left it" did not say against what. A reuse wrote every shape and kind word it named as the adopter's binding, overwriting a binding a colleague decided after the agent read it, which neither the proposal nor the adopter had seen. For a reuse, the decision the agent read is what the proposal answers and is replaced; a person's decision made after that read stays. The proposal records when each decision it read was made. A person's later decision that binds the way the proposal does counts as written, and a shape keeps its regression case; one that differs is left as it is, gets no case and is listed in the answer. A reuse with nothing left to write is refused. A reuse saved before this revision recorded no reads, so adopting it keeps every person's decision.+**4. Every approved element carries regression cases.** The example statements that motivated a proposal become `ontology_regression_cases` on adoption: a statement and the property or class it is expected to bind to. A later edit to the element's definition, domains or ranges reruns alignment on exactly those signatures and records which cases still bind. A failing case is shown on the workbench beside the edit; it is not reverted for the person, because a definition may be tightened on purpose. A person can add a case from any statement ("this should bind here"), which is the "make a rule" action #725 names.**5. Two numbers measure the ontology.** Questions answered correctly: each accepted question is asked over the typed graph the way a person would ask it in chat, and the answer is judged against the expected answer where one is written, or against whether the shape it needs exists and holds facts. Proposals people change: the share of the agent's proposals rejected or edited before adoption. Both are reported per base and by the bench 0044's table names, FDA and statistics corpora with written questions.diff --git a/web/src/api.ts b/web/src/api.tsindex 798b1baf..c5e260b5 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -2330,12 +2330,13 @@ export const api = {/** 上次算出来、还没人表态的提案(0049)。刷新页面靠它,不必重跑模型 */storedProposals: (kbId: string) =>request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/proposals`),- /** 一条提案有人表态了。改状态不删行——拒绝留痕,下一轮 Suggest 不再刷回待看 */+ /** 一条提案有人拒绝了。改状态不删行——拒绝留痕,下一轮 Suggest 不再刷回待看。+ * 只收拒绝:采纳走 adoptProposal,元素和采纳的状态一起提交(0061 决定 3) */decideProposal: (kbId: string,section: string,key: string,- status: "adopted" | "rejected",+ status: "rejected",/** 拒绝的理由(0061):下一轮代理读得到 */reason?: string,) =>@@ -2349,7 +2350,7 @@ export const api = {method: "POST",body: "{}",}),- /** 采纳代理的一条提案(0061 决定 3):服务端建元素、标记、排对齐 */+ /** 采纳代理的一条提案(0061 决定 3):元素、回归用例、采纳的状态和后续任务一次提交 */adoptProposal: (kbId: string,section: string,@@ -2363,7 +2364,11 @@ export const api = {parents?: string[];},) =>- request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/proposals/adopt`, {+ request<{+ id: string;+ /** 复用时留着没写的形状或类别词,各带人定成了什么:代理读过之后人另定了、和提案不一样的 */+ skipped: ({ phrase: string } | { kind_word: string })[];+ }>(`/api/v1/kbs/${kbId}/ontology/proposals/adopt`, {method: "POST",body: JSON.stringify({ section, key, ...(edits ?? {}) }),}),diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex efb8a52a..2eb3e0d8 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -145,6 +145,10 @@ export const en = {unknown_marks: "A single date marks the start, the end, or neither.",marks_needs_state:"Only a state property says what a single date marks. Events and timeless properties don't.",+ // 采纳提案(0061 决定 3):撞上别的写、整次回滚了;复用要写的都已由人另定+ alignment_busy: "Something else is updating the same items. Nothing was saved; try again shortly.",+ proposal_stale:+ "Nothing in this proposal is left to adopt: each of its phrases or kind words is decided differently by a person or no longer appears in any statement. Reject it to clear it.",},/** 机器给的补充(cron 解析器的原话之类)缀在措辞后面 */errDetail: (msg: string, detail: string) => `${msg} (${detail})`,@@ -1801,6 +1805,12 @@ export const en = {rejectReasonPrompt:"Why not? (optional — the agent reads it before proposing again)",rejectedProposal: "Rejected",+ /* 复用时人另定了的,照人的留着没写(0061 决定 3):只说留了几条。不说是代理读过之后定的:+ 没记下读到哪一刻的旧提案,人在提案之前定的也照留 */+ adoptKept: (n: number) =>+ n === 1+ ? "Saved. One of these was decided differently by a person and stays as they decided."+ : `Saved. ${n} of these were decided differently by a person and stay as they decided.`,questions: "Competency questions",questionsHint:"What this knowledge base should be able to answer. The agent proposes classes and properties that serve these; they are the ontology's acceptance test.",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex 17c16c7d..ddda99a1 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -130,6 +130,10 @@ export const zh: Strings = {empty_state_span: "起止相同的状态任何时刻都不成立。给一个晚于起点的终点,或者让它开着。",unknown_marks: "单个日期标的是开始、结束,或者都不是。",marks_needs_state: "只有状态属性才说单个日期标的是什么,事件与恒常属性不说。",+ // 采纳提案(0061 决定 3):撞上别的写、整次回滚了;复用要写的都已由人另定+ alignment_busy: "另一项操作正在改同样的内容,这次什么都没保存,请稍后再试。",+ proposal_stale:+ "这条提案已经没有可采纳的了:它的每个短语或类别词要么已由人另行判定,要么已不在任何陈述里。拒绝它就能清掉。",},errDetail: (msg: string, detail: string) => `${msg}(${detail})`,toast: {@@ -1574,6 +1578,7 @@ export const zh: Strings = {rejectProposal: "拒绝",rejectReasonPrompt: "为什么不要?(可不填——代理下次提案前会读)",rejectedProposal: "已拒绝",+ adoptKept: (n: number) => `已保存。其中 ${n} 条已由人另行判定,按人的判定保留。`,questions: "能力问题",questionsHint:"这个知识库应该答得上来的问题。代理提的类与属性要服务它们;它们就是本体的验收标准。",diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsxindex a7dd4784..96e9ec0a 100644--- a/web/src/pages/Ontology.tsx+++ b/web/src/pages/Ontology.tsx@@ -2197,8 +2197,10 @@ function MissesPanel({const adopt = useMutation({mutationFn: ({ section, key }: { section: Section; key: string }) =>api.adoptProposal(kbId, section, key),- onSuccess: (_d, v) => {- toast.success(v.section === "map_to" ? S.toast.saved : S.toast.added);+ onSuccess: (d, v) => {+ // 复用时有人在代理读过之后另定了的,照人的留着没写:说一声,不然卡片一走像是全写了+ if (d.skipped.length > 0) toast.info(S.ontology.adoptKept(d.skipped.length));+ else toast.success(v.section === "map_to" ? S.toast.saved : S.toast.added);drop(v.section, v.key);onChanged();},