Skip to content

World's first open-source enterprise world model.

The ontology is proposed from the open graph and judged by its questions: cut 1 (#947)

WaylandYangb07af8f8ad9b
diff --git a/crates/utopia-cli/src/main.rs b/crates/utopia-cli/src/main.rs
index 75ac55b4..940e2ec8 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 = 81;
+const CURRENT_SCHEMA_VERSION: u32 = 82;
fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs
index 8af91dff..93c95c25 100644
--- a/crates/utopia-extract/src/lib.rs
+++ b/crates/utopia-extract/src/lib.rs
@@ -13,6 +13,7 @@ pub mod align;
pub mod errata;
pub mod governor;
pub mod implication;
+pub mod ontology_agent;
pub mod open;
pub mod phrase_align;
pub mod time;
diff --git a/crates/utopia-extract/src/ontology_agent.rs b/crates/utopia-extract/src/ontology_agent.rs
new file mode 100644
index 00000000..36e4c59d
--- /dev/null
+++ b/crates/utopia-extract/src/ontology_agent.rs
@@ -0,0 +1,497 @@
+//! 本体代理的一次提案调用(0061 决定 2)。
+//!
+//! 输入是开放图谱里本体接不住的形状——对齐判成「无」或「判不定」的签名(短语 × 两端的类,
+//! 带例句与引文)和绑不到类的类别词(带例名)——外加现在的本体(类与属性的定义、定义域、值域)
+//! 和库的能力问题。问的是:**加上哪几个类、哪几条属性,这些形状就接得住、这些问题就答得了**。
+//! 每条提案带一份写给对齐器看的定义、它会绑上的形状、它服务的问题;本体里已经有的属性接得住
+//! 的形状写在 `existing` 里,不另提。代理只提,不写本体(0012:本体是人签的契约)。
+//!
+//! 回复是紧凑 JSON,解析同 phrase_align:坏的一条计数、不毁掉整批;键不合法、形状 id 不在批里
+//! 都算坏。
+
+use crate::align::parse_value;
+use serde_json::Value;
+use std::collections::HashSet;
+use utopia_llm::ChatMessage;
+
+/// 一条对齐接不住的签名
+#[derive(Debug, Clone)]
+pub struct OpenSignature<'a> {
+ pub id: i64,
+ pub phrase: &'a str,
+ pub subject_class: Option<&'a str>,
+ pub object_class: Option<&'a str>,
+ pub object_is_value: bool,
+ pub statement_count: i64,
+ pub examples: &'a [String],
+ pub quotes: &'a [String],
+}
+
+/// 一个绑不到类的类别词
+#[derive(Debug, Clone)]
+pub struct OpenKindWord<'a> {
+ pub id: i64,
+ pub kind_word: &'a str,
+ pub count: i64,
+ pub examples: &'a [String],
+ pub phrases: &'a [String],
+}
+
+/// 本体现状:类与属性,照库里的语言给
+#[derive(Debug, Clone, Default)]
+pub struct Glossary<'a> {
+ /// (key, label, description)
+ pub classes: Vec<(&'a str, &'a str, &'a str)>,
+ /// (key, label, kind, domains, ranges, description)
+ pub properties: Vec<GlossaryProperty<'a>>,
+}
+
+/// 词表里的一条属性:(key, label, kind, domains, ranges, description)
+pub type GlossaryProperty<'a> = (
+ &'a str,
+ &'a str,
+ &'a str,
+ Vec<&'a str>,
+ Vec<&'a str>,
+ &'a str,
+);
+
+/// 一条能力问题
+#[derive(Debug, Clone)]
+pub struct QuestionItem<'a> {
+ pub id: i64,
+ pub text: &'a str,
+}
+
+/// 代理提的一条元素
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Proposal {
+ /// class | property
+ pub kind: String,
+ pub key: String,
+ pub label: String,
+ pub definition: String,
+ /// 属性:宾语是值(attribute)还是实体(relation)
+ pub value: bool,
+ /// 值属性的数据类型:number | date | text | bool
+ pub datatype: Option<String>,
+ /// 属性的定义域 / 值域,或类的父类:类键,可以是本体里的,也可以是这一批里刚提的
+ pub domains: Vec<String>,
+ pub ranges: Vec<String>,
+ pub parents: Vec<String>,
+ /// 它会绑上的签名 id 与类别词 id(本批内的)
+ pub signatures: Vec<i64>,
+ pub kind_words: Vec<i64>,
+ /// 它服务的问题 id
+ pub questions: Vec<i64>,
+}
+
+/// 「本体里已经有」:现有属性或类的键,与它接得住的形状
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Existing {
+ pub key: String,
+ pub signatures: Vec<i64>,
+ pub kind_words: Vec<i64>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ProposalReply {
+ pub proposals: Vec<Proposal>,
+ pub existing: Vec<Existing>,
+ /// 读不出的项数
+ pub malformed: usize,
+}
+
+const SYSTEM: &str = "\
+You are the ontology agent of a knowledge base. The base extracts statements from documents as \
+they are worded; an aligner then binds each statement shape (a relation phrase between a subject \
+class and an object class, or a kind word the documents use for a thing) to a property or class of \
+the ontology. The shapes below are the ones the ontology cannot hold: no property or class fits \
+them. The competency questions are what the base exists to answer.\n\
+Propose the smallest set of new classes and properties that would let the base hold these shapes \
+AND serve the questions. Rules:\n\
+- A proposal binds shapes: list the shape ids it would bind (s for signatures, k for kind words). \
+Do not propose an element that binds nothing.\n\
+- Prefer serving a question. An element that serves no question must bind at least two statements' \
+worth of shapes, or be a class that several kind words name.\n\
+- Write the definition for the aligner, in the language of the ontology: one or two sentences saying \
+what the property asserts, what its subject and object are, and what it does NOT cover.\n\
+- A property whose object is a value (a number, a date, text) is an attribute: value=true with a \
+datatype (number | date | text | bool) and no ranges. Otherwise value=false with domains and ranges \
+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\
+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]}]}";
+
+pub fn build_proposal_messages(
+ signatures: &[OpenSignature<'_>],
+ kind_words: &[OpenKindWord<'_>],
+ glossary: &Glossary<'_>,
+ questions: &[QuestionItem<'_>],
+) -> Vec<ChatMessage> {
+ let mut user = String::new();
+ user.push_str("Ontology classes:\n");
+ if glossary.classes.is_empty() {
+ user.push_str(" (none)\n");
+ }
+ for (key, label, description) in &glossary.classes {
+ user.push_str(&format!("- {key} · {label}"));
+ if !description.trim().is_empty() {
+ user.push_str(&format!(" · {}", description.trim()));
+ }
+ user.push('\n');
+ }
+ user.push_str("\nOntology properties:\n");
+ if glossary.properties.is_empty() {
+ user.push_str(" (none)\n");
+ }
+ for (key, label, kind, domains, ranges, description) in &glossary.properties {
+ user.push_str(&format!("- {key} · {label} · {kind}"));
+ if !domains.is_empty() {
+ user.push_str(&format!(" · domain: {}", domains.join(", ")));
+ }
+ if !ranges.is_empty() {
+ user.push_str(&format!(" · range: {}", ranges.join(", ")));
+ }
+ if !description.trim().is_empty() {
+ user.push_str(&format!(" · {}", description.trim()));
+ }
+ user.push('\n');
+ }
+ user.push_str("\nCompetency questions:\n");
+ if questions.is_empty() {
+ user.push_str(
+ " (none written yet: propose for the shapes that bind the most statements)\n",
+ );
+ }
+ for q in questions {
+ user.push_str(&format!("q{}: {}\n", q.id, q.text.trim()));
+ }
+ user.push_str("\nShapes the ontology cannot hold:\n");
+ for s in signatures {
+ let subject = s.subject_class.unwrap_or("(untyped)");
+ let object = if s.object_is_value {
+ "(a value)".to_string()
+ } else {
+ s.object_class.unwrap_or("(untyped)").to_string()
+ };
+ user.push_str(&format!(
+ "s{}: phrase \"{}\" · subject class: {} · object: {} · {} statements\n",
+ s.id, s.phrase, subject, object, s.statement_count
+ ));
+ for (i, ex) in s.examples.iter().enumerate() {
+ let quote = s.quotes.get(i).map(String::as_str).unwrap_or("").trim();
+ if quote.is_empty() {
+ user.push_str(&format!(" · {ex}\n"));
+ } else {
+ user.push_str(&format!(" · {ex}\n \"{quote}\"\n"));
+ }
+ }
+ }
+ for k in kind_words {
+ user.push_str(&format!(
+ "k{}: kind word \"{}\" · {} things",
+ k.id, k.kind_word, k.count
+ ));
+ if !k.examples.is_empty() {
+ user.push_str(&format!(" · e.g. {}", k.examples.join(", ")));
+ }
+ if !k.phrases.is_empty() {
+ user.push_str(&format!(
+ " · they are subjects of: {}",
+ k.phrases.join(", ")
+ ));
+ }
+ user.push('\n');
+ }
+ vec![
+ ChatMessage {
+ role: "system".into(),
+ content: SYSTEM.into(),
+ },
+ ChatMessage {
+ role: "user".into(),
+ content: user,
+ },
+ ]
+}
+
+fn ids(v: Option<&Value>, prefix: char, known: &HashSet<i64>) -> Result<Vec<i64>, ()> {
+ let Some(v) = v else { return Ok(Vec::new()) };
+ let Some(arr) = v.as_array() else {
+ return Err(());
+ };
+ let mut out = Vec::new();
+ for x in arr {
+ let id = match x {
+ Value::Number(n) => n.as_i64(),
+ Value::String(s) => s.trim().trim_start_matches(prefix).parse::<i64>().ok(),
+ _ => None,
+ };
+ match id {
+ Some(id) if known.contains(&id) => out.push(id),
+ _ => return Err(()),
+ }
+ }
+ Ok(out)
+}
+
+fn strings(v: Option<&Value>) -> Result<Vec<String>, ()> {
+ let Some(v) = v else { return Ok(Vec::new()) };
+ match v {
+ Value::Null => Ok(Vec::new()),
+ Value::String(s) => Ok(vec![s.trim().to_string()]),
+ Value::Array(a) => a
+ .iter()
+ .map(|x| x.as_str().map(|s| s.trim().to_string()).ok_or(()))
+ .collect(),
+ _ => Err(()),
+ }
+}
+
+fn valid_key(k: &str) -> bool {
+ !k.is_empty()
+ && k.len() <= 64
+ && k.chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
+ && k.chars().next().is_some_and(|c| c.is_ascii_lowercase())
+}
+
+/// 读回复。`signature_ids` / `kind_word_ids` / `question_ids` 是这一批里合法的 id:答案里指向别处的算坏项
+pub fn parse_proposal_response(
+ raw: &str,
+ signature_ids: &HashSet<i64>,
+ kind_word_ids: &HashSet<i64>,
+ question_ids: &HashSet<i64>,
+) -> anyhow::Result<ProposalReply> {
+ let v = parse_value(raw)?;
+ let mut reply = ProposalReply::default();
+ let items: Vec<&Value> = match v.get("p") {
+ Some(Value::Array(a)) => a.iter().collect(),
+ Some(Value::Object(m)) => m.values().collect(),
+ Some(Value::Null) | None => Vec::new(),
+ Some(_) => {
+ reply.malformed += 1;
+ Vec::new()
+ }
+ };
+ let mut seen: HashSet<String> = HashSet::new();
+ for it in items {
+ let Some(obj) = it.as_object() else {
+ reply.malformed += 1;
+ continue;
+ };
+ let kind = obj
+ .get("kind")
+ .and_then(Value::as_str)
+ .unwrap_or("property")
+ .trim()
+ .to_lowercase();
+ let key = obj
+ .get("key")
+ .and_then(Value::as_str)
+ .map(|k| k.trim().to_lowercase())
+ .unwrap_or_default();
+ if !matches!(kind.as_str(), "class" | "property")
+ || !valid_key(&key)
+ || !seen.insert(key.clone())
+ {
+ reply.malformed += 1;
+ continue;
+ }
+ let label = obj
+ .get("label")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .unwrap_or(&key)
+ .to_string();
+ let definition = obj
+ .get("definition")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .unwrap_or("")
+ .to_string();
+ let value = obj.get("value").and_then(Value::as_bool).unwrap_or(false);
+ let datatype = obj
+ .get("datatype")
+ .and_then(Value::as_str)
+ .map(|d| d.trim().to_lowercase())
+ .filter(|d| matches!(d.as_str(), "number" | "date" | "text" | "bool"));
+ let (Ok(domains), Ok(ranges), Ok(parents)) = (
+ strings(obj.get("domains")),
+ strings(obj.get("ranges")),
+ strings(obj.get("parents")),
+ ) else {
+ reply.malformed += 1;
+ continue;
+ };
+ let (Ok(signatures), Ok(kind_words), Ok(questions)) = (
+ ids(obj.get("s"), 's', signature_ids),
+ ids(obj.get("k"), 'k', kind_word_ids),
+ ids(obj.get("q"), 'q', question_ids),
+ ) else {
+ reply.malformed += 1;
+ continue;
+ };
+ // 什么形状都不绑的提案不是从图谱里长出来的:不收
+ if signatures.is_empty() && kind_words.is_empty() {
+ reply.malformed += 1;
+ continue;
+ }
+ reply.proposals.push(Proposal {
+ kind,
+ key,
+ label,
+ definition,
+ value,
+ datatype: if value { datatype } else { None },
+ domains: domains.into_iter().filter(|d| !d.is_empty()).collect(),
+ ranges: if value {
+ Vec::new()
+ } else {
+ ranges.into_iter().filter(|r| !r.is_empty()).collect()
+ },
+ parents: parents.into_iter().filter(|p| !p.is_empty()).collect(),
+ signatures,
+ kind_words,
+ questions,
+ });
+ }
+ if let Some(Value::Array(ex)) = v.get("existing") {
+ for it in ex {
+ let Some(obj) = it.as_object() else {
+ reply.malformed += 1;
+ continue;
+ };
+ let key = obj
+ .get("key")
+ .and_then(Value::as_str)
+ .map(|k| k.trim().to_string())
+ .unwrap_or_default();
+ let (Ok(signatures), Ok(kind_words)) = (
+ ids(obj.get("s"), 's', signature_ids),
+ ids(obj.get("k"), 'k', kind_word_ids),
+ ) else {
+ reply.malformed += 1;
+ continue;
+ };
+ if key.is_empty() || (signatures.is_empty() && kind_words.is_empty()) {
+ reply.malformed += 1;
+ continue;
+ }
+ reply.existing.push(Existing {
+ key,
+ signatures,
+ kind_words,
+ });
+ }
+ }
+ Ok(reply)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ids_of(xs: &[i64]) -> HashSet<i64> {
+ xs.iter().copied().collect()
+ }
+
+ #[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 r = parse_proposal_response(raw, &ids_of(&[0, 1, 2]), &ids_of(&[0]), &ids_of(&[1]))
+ .unwrap();
+ assert_eq!(r.malformed, 0);
+ assert_eq!(r.proposals.len(), 2);
+ assert_eq!(r.proposals[0].key, "supplies");
+ assert_eq!(r.proposals[0].signatures, vec![0, 2]);
+ assert_eq!(r.proposals[0].questions, vec![1]);
+ assert_eq!(r.proposals[0].domains, vec!["organization"]);
+ assert_eq!(r.proposals[1].kind, "class");
+ assert_eq!(r.proposals[1].parents, vec!["organization"]);
+ assert_eq!(
+ r.existing,
+ vec![Existing {
+ key: "located_in".into(),
+ signatures: vec![1],
+ kind_words: vec![]
+ }]
+ );
+ }
+
+ #[test]
+ fn a_proposal_that_binds_nothing_or_points_outside_the_batch_is_malformed() {
+ let raw = r#"{"p":[{"kind":"property","key":"orphan","label":"o","definition":"","s":[],"k":[],"q":[]},{"kind":"property","key":"far","label":"f","definition":"","s":[9],"k":[],"q":[]},{"kind":"property","key":"Bad Key","label":"b","definition":"","s":[0],"k":[],"q":[]},{"kind":"property","key":"ok","label":"ok","definition":"d","value":true,"datatype":"number","s":["s0"],"k":[],"q":["q1"]}]}"#;
+ let r = parse_proposal_response(raw, &ids_of(&[0]), &ids_of(&[]), &ids_of(&[1])).unwrap();
+ assert_eq!(r.malformed, 3);
+ assert_eq!(r.proposals.len(), 1);
+ assert_eq!(r.proposals[0].key, "ok");
+ assert!(r.proposals[0].value);
+ assert_eq!(r.proposals[0].datatype.as_deref(), Some("number"));
+ assert_eq!(
+ r.proposals[0].signatures,
+ vec![0],
+ "an id written as s0 still counts"
+ );
+ assert_eq!(r.proposals[0].questions, vec![1]);
+ }
+
+ #[test]
+ fn the_prompt_names_every_input_once() {
+ let examples = vec!["W-1 —supplies→ F-2".to_string()];
+ let quotes = vec!["W-1 supplies F-2 with parts.".to_string()];
+ let sigs = vec![OpenSignature {
+ id: 0,
+ phrase: "supplies",
+ subject_class: Some("organization"),
+ object_class: Some("organization"),
+ object_is_value: false,
+ statement_count: 7,
+ examples: &examples,
+ quotes: &quotes,
+ }];
+ let names = vec!["Acme Supply".to_string()];
+ let phrases = vec!["supplies".to_string()];
+ let kws = vec![OpenKindWord {
+ id: 0,
+ kind_word: "supplier",
+ count: 3,
+ examples: &names,
+ phrases: &phrases,
+ }];
+ let glossary = Glossary {
+ classes: vec![("organization", "Organization", "a company or institution")],
+ properties: vec![(
+ "located_in",
+ "located in",
+ "relation",
+ vec!["organization"],
+ vec!["location"],
+ "where a thing is",
+ )],
+ };
+ let qs = vec![QuestionItem {
+ id: 1,
+ text: "Who supplies whom?",
+ }];
+ let m = build_proposal_messages(&sigs, &kws, &glossary, &qs);
+ assert_eq!(m.len(), 2);
+ let user = &m[1].content;
+ for needle in [
+ "s0: phrase \"supplies\"",
+ "k0: kind word \"supplier\"",
+ "q1: Who supplies whom?",
+ "- located_in · located in · relation · domain: organization · range: location",
+ "\"W-1 supplies F-2 with parts.\"",
+ ] {
+ assert!(user.contains(needle), "missing {needle:?} in\n{user}");
+ }
+ }
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 6bf0c146..0143ec46 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -15,6 +15,7 @@ mod mcp;
mod members_routes;
mod oidc_routes;
pub(crate) mod ontology_routes;
+mod question_routes;
mod review_routes;
mod rig_model;
pub(crate) mod rule_routes;
@@ -360,6 +361,20 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
"/kbs/{id}/ontology/proposals",
get(ontology_routes::stored_proposals).post(ontology_routes::decide_proposal),
)
+ // 0061:能力问题是本体的验收标准;代理从开放图提本体,人采纳
+ .route(
+ "/kbs/{id}/questions",
+ get(question_routes::list).post(question_routes::create),
+ )
+ .route(
+ "/kbs/{id}/questions/{qid}",
+ patch(question_routes::update).delete(question_routes::delete),
+ )
+ .route("/kbs/{id}/ontology/propose", post(question_routes::propose))
+ .route(
+ "/kbs/{id}/ontology/proposals/adopt",
+ post(question_routes::adopt),
+ )
// OWL 导入:预览与落库分开两个端点,绝不让上传即改本体。
// 两者跑同一个 plan——分开的代码路径会分叉,而分叉意味着确认之后
// 发生的事与刚看过的不一样
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index 976a0882..610069d9 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -599,7 +599,17 @@ pub async fn stored_proposals(
});
for p in stored {
if let Some(arr) = out.get_mut(&p.section).and_then(|v| v.as_array_mut()) {
- arr.push(p.payload);
+ let mut item = p.payload;
+ // 代理提的多带三格:谁提的、服务哪些问题、会绑上哪些形状(0061)。Suggest 的
+ // 一份没有,前端照旧
+ if p.proposed_by == "agent" {
+ if let Some(o) = item.as_object_mut() {
+ o.insert("proposed_by".into(), json!("agent"));
+ o.insert("serves".into(), json!(p.serves));
+ o.insert("signatures".into(), p.signatures);
+ }
+ }
+ arr.push(item);
}
}
Ok(Json(out))
@@ -611,6 +621,9 @@ pub struct DecideProposalReq {
pub key: String,
/// adopted | rejected
pub status: String,
+ /// 拒绝的理由(0061:下一轮代理读得到)。采纳时忽略
+ #[serde(default)]
+ pub reason: Option<String>,
}
/// 一条提案有人表态了。**改状态不删行**:采纳发生过、拒绝也发生过,
@@ -625,15 +638,32 @@ pub async fn decide_proposal(
if !matches!(req.status.as_str(), "adopted" | "rejected") {
return Err(AppError::invalid("bad_status", "status 只能是 adopted 或 rejected").into());
}
- utopia_store::ontology::decide_proposal(
- &state.pool,
- kb_id,
- &req.section,
- &req.key,
- &req.status,
- user.id,
- )
- .await?;
+ let reason = req
+ .reason
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+ if req.status == "rejected" && reason.is_some() {
+ utopia_store::ontology::reject_proposal(
+ &state.pool,
+ kb_id,
+ &req.section,
+ &req.key,
+ reason,
+ user.id,
+ )
+ .await?;
+ } else {
+ utopia_store::ontology::decide_proposal(
+ &state.pool,
+ kb_id,
+ &req.section,
+ &req.key,
+ &req.status,
+ user.id,
+ )
+ .await?;
+ }
Ok(Json(json!({ "ok": true })))
}
diff --git a/crates/utopia-server/src/api/question_routes.rs b/crates/utopia-server/src/api/question_routes.rs
new file mode 100644
index 00000000..e9fb4f32
--- /dev/null
+++ b/crates/utopia-server/src/api/question_routes.rs
@@ -0,0 +1,166 @@
+//! 能力问题(0061 决定 1)与本体代理(决定 2、3)的接口。
+//! 看 = viewer;改 = editor:问题是本体的验收标准,提案采纳直接改本体。
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::Role;
+use utopia_core::AppError;
+use utopia_store::competency_questions as questions;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::ontology_agent;
+use crate::state::AppState;
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<Vec<questions::Question>>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ Ok(Json(questions::list(&state.pool, kb_id).await?))
+}
+
+#[derive(Deserialize)]
+pub struct CreateQuestionReq {
+ pub question: String,
+ #[serde(default)]
+ pub expected_answer: Option<String>,
+ #[serde(default)]
+ pub needs: Option<serde_json::Value>,
+}
+
+/// 人提的问题一落地就是 accepted:它就是人对这个库的要求
+pub async fn create(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<CreateQuestionReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?;
+ let text = req.question.trim();
+ if text.is_empty() {
+ return Err(AppError::invalid("question_required", "question is required").into());
+ }
+ let id = questions::create(
+ &state.pool,
+ kb_id,
+ questions::NewQuestion {
+ question: text,
+ expected_answer: req
+ .expected_answer
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty()),
+ needs: req.needs.as_ref(),
+ origin: "person",
+ status: "accepted",
+ created_by: Some(user.id),
+ },
+ )
+ .await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "competency_question.created",
+ "competency_question",
+ Some(id),
+ json!({ "question": text }),
+ )
+ .await;
+ Ok(Json(json!({ "id": id })))
+}
+
+#[derive(Deserialize)]
+pub struct UpdateQuestionReq {
+ #[serde(default)]
+ pub question: Option<String>,
+ /// 空串 = 清掉
+ #[serde(default)]
+ pub expected_answer: Option<String>,
+ #[serde(default)]
+ pub needs: Option<serde_json::Value>,
+ /// accepted | rejected | retired
+ #[serde(default)]
+ pub status: Option<String>,
+}
+
+pub async fn update(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, qid)): Path<(Uuid, Uuid)>,
+ Json(req): Json<UpdateQuestionReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?;
+ if let Some(q) = req.question.as_deref() {
+ if q.trim().is_empty() {
+ return Err(AppError::invalid("question_required", "question is required").into());
+ }
+ }
+ if req.question.is_some() || req.expected_answer.is_some() || req.needs.is_some() {
+ questions::update(
+ &state.pool,
+ kb_id,
+ qid,
+ req.question.as_deref().map(str::trim),
+ req.expected_answer.as_deref().map(str::trim),
+ req.needs.as_ref(),
+ )
+ .await?;
+ }
+ if let Some(status) = req.status.as_deref() {
+ questions::set_status(&state.pool, kb_id, qid, status).await?;
+ }
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn delete(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, qid)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?;
+ questions::delete(&state.pool, kb_id, qid).await?;
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 叫代理来看一眼:排一份任务,马上回。结果落在 `ontology_proposals`,界面从那里读
+pub async fn propose(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?;
+ let queued = utopia_store::jobs::enqueue_unless_queued(
+ &state.pool,
+ "propose_ontology",
+ json!({ "kb_id": kb_id }),
+ )
+ .await?;
+ Ok(Json(json!({ "queued": queued.is_some() })))
+}
+
+#[derive(Deserialize)]
+pub struct AdoptReq {
+ pub section: String,
+ pub key: String,
+ #[serde(default, flatten)]
+ pub edits: ontology_agent::AdoptEdits,
+}
+
+/// 采纳一条提案(人改过的几格随请求来):建元素、标记、排对齐
+pub async fn adopt(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<AdoptReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?;
+ let id =
+ ontology_agent::adopt(&state, kb_id, &req.section, &req.key, req.edits, user.id).await?;
+ Ok(Json(json!({ "id": id })))
+}
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
index bdaad212..65e8e7e8 100644
--- a/crates/utopia-server/src/main.rs
+++ b/crates/utopia-server/src/main.rs
@@ -22,6 +22,7 @@ mod mapping_index;
mod mappings;
mod notion;
mod object_storage;
+mod ontology_agent;
mod ontology_index;
mod ontology_packs;
mod owl_import;
@@ -636,6 +637,15 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow
.ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
governance::govern(st, kb_id).await
}
+ "propose_ontology" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ ontology_agent::propose(st, kb_id).await
+ }
"sync_source" => {
let source_id: Uuid = job
.payload
diff --git a/crates/utopia-server/src/ontology_agent.rs b/crates/utopia-server/src/ontology_agent.rs
new file mode 100644
index 00000000..fff7f59c
--- /dev/null
+++ b/crates/utopia-server/src/ontology_agent.rs
@@ -0,0 +1,567 @@
+//! 本体代理(0061 决定 2、3):对齐判成「没有」「没定」的短语形状与类别词,对着现有本体和
+//! 能力问题交给模型,让它提该建的类与属性。提案进 `ontology_proposals`,**人采纳才成为本体**
+//! (0012);采纳建出元素后排一次对齐,那些形状按 0053 的指纹自己重判。
+//!
+//! 形状的身份是短语加两端的类键加宾语是不是字面值——同 `phrase_bindings` 的键,只是用键
+//! 而不是 id 存进提案,好让人读得懂
+
+use std::collections::{HashMap, HashSet};
+
+use serde::Deserialize;
+use serde_json::{json, Value};
+use utopia_core::models::RelationAxioms;
+use utopia_core::AppError;
+use utopia_extract::ontology_agent as agent;
+use utopia_store::phrase_bindings::PhraseSignature;
+use utopia_store::type_bindings::KindWordSignature;
+use utopia_store::{competency_questions, phrase_bindings, type_bindings};
+use uuid::Uuid;
+
+use crate::extraction::chat_retrying_rate_limits_at;
+use crate::llm_util;
+use crate::state::AppState;
+
+/// 一次调用交给模型的形状数(0044 决定 3 的成本教训:词表每批只带一次)
+pub(crate) const SIGNATURES_PER_CALL: usize = 12;
+/// 每批跟着的类别词至多这么多
+pub(crate) const KIND_WORDS_PER_CALL: usize = 6;
+/// 一轮至多问这么多形状,按陈述数从多到少;其余等下一轮。界面上点一次也只花这么多
+pub(crate) const SIGNATURES_PER_ROUND: usize = 120;
+/// 对齐收尾时没绑上的形状够这么多,才叫代理来看(少于这个数人自己在审核页就处理了)
+pub(crate) const TRIGGER_UNBOUND: usize = 20;
+
+/// 形状写进提案里的样子
+fn shape_of(sig: &PhraseSignature) -> Value {
+ json!({
+ "phrase": sig.phrase,
+ "subject": sig.subject_type_key,
+ "object": sig.object_type_key,
+ "value": sig.object_is_value,
+ })
+}
+
+/// 任务入口:一个库同时只跑一份(同两种对齐,并行会把端点打出 502)
+pub async fn propose(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
+ let pool = &state.pool;
+ let kb = utopia_store::kbs::get(pool, kb_id).await?;
+ let settings = utopia_store::settings::get(pool, kb.workspace_id)
+ .await?
+ .ok_or_else(|| anyhow::anyhow!("Chat model not configured; cannot propose ontology"))?;
+ // 提本体是判断题:按端点默认的强度想
+ let client = llm_util::chat_client_thinking(&settings)
+ .ok_or_else(|| anyhow::anyhow!("Chat model not configured; cannot propose ontology"))?;
+ let mut guard = pool.acquire().await?;
+ let locked: bool = sqlx::query_scalar(
+ "SELECT pg_try_advisory_lock(hashtext('propose_ontology'), hashtext($1))",
+ )
+ .bind(kb_id.to_string())
+ .fetch_one(&mut *guard)
+ .await?;
+ if !locked {
+ tracing::info!(%kb_id, "本体代理已有一份在跑,这次跳过");
+ return Ok(());
+ }
+ let result = propose_locked(state, kb_id, &settings, &client).await;
+ let _ = sqlx::query("SELECT pg_advisory_unlock(hashtext('propose_ontology'), hashtext($1))")
+ .bind(kb_id.to_string())
+ .execute(&mut *guard)
+ .await;
+ result
+}
+
+/// 一条合并后的提案:同一个键在几批里都被提了,形状、类别词、问题并起来,定义取第一次的
+struct Merged {
+ proposal: agent::Proposal,
+ shapes: Vec<Value>,
+ phrases: Vec<String>,
+ words: Vec<String>,
+ quotes: Vec<String>,
+ serves: Vec<Uuid>,
+}
+
+async fn propose_locked(
+ state: &AppState,
+ kb_id: Uuid,
+ settings: &utopia_core::models::LlmSettings,
+ client: &utopia_llm::LlmClient,
+) -> anyhow::Result<()> {
+ let pool = &state.pool;
+ let classes = utopia_store::graph::entity_types(pool, kb_id).await?;
+ let props = utopia_store::ontology::relation_type_views(pool, kb_id).await?;
+ 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 mut proposed_shapes: HashSet<String> = HashSet::new();
+ let mut proposed_words: HashSet<String> = HashSet::new();
+ for s in utopia_store::ontology::signatures_already_proposed(pool, kb_id).await? {
+ for p in s
+ .get("phrases")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ {
+ proposed_shapes.insert(p.to_string());
+ }
+ for w in s
+ .get("kind_words")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ {
+ if let Some(w) = w.as_str() {
+ proposed_words.insert(w.to_string());
+ }
+ }
+ }
+
+ // 没绑上的形状:对齐判成「没有」或「没定」的。还没判的等对齐,不在这里猜
+ let sigs = phrase_bindings::signatures(pool, kb_id).await?;
+ let bindings: HashMap<_, _> = phrase_bindings::bindings(pool, kb_id)
+ .await?
+ .into_iter()
+ .map(|b| (b.key(), b))
+ .collect();
+ let mut open: Vec<&PhraseSignature> = sigs
+ .iter()
+ .filter(|s| {
+ matches!(
+ bindings.get(&s.key()).map(|b| b.status.as_str()),
+ Some("none" | "undecided")
+ )
+ })
+ .filter(|s| !proposed_shapes.contains(&shape_of(s).to_string()))
+ .collect();
+ open.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.phrase.cmp(&b.phrase)));
+ open.truncate(SIGNATURES_PER_ROUND);
+
+ // 没归类的类别词同理
+ let words = type_bindings::signatures(pool, kb_id).await?;
+ let word_bindings: HashMap<String, _> = type_bindings::bindings(pool, kb_id)
+ .await?
+ .into_iter()
+ .map(|b| (b.kind_word.clone(), b))
+ .collect();
+ let mut open_words: Vec<&KindWordSignature> = words
+ .iter()
+ .filter(|w| {
+ matches!(
+ word_bindings.get(&w.kind_word).map(|b| b.status.as_str()),
+ Some("none" | "undecided")
+ )
+ })
+ .filter(|w| !proposed_words.contains(&w.kind_word))
+ .collect();
+ open_words.sort_by(|a, b| {
+ b.count
+ .cmp(&a.count)
+ .then_with(|| a.kind_word.cmp(&b.kind_word))
+ });
+ let calls = open
+ .len()
+ .div_ceil(SIGNATURES_PER_CALL)
+ .max(open_words.len().div_ceil(KIND_WORDS_PER_CALL));
+ if calls == 0 {
+ tracing::info!(%kb_id, "本体代理:没有新的形状要看");
+ return Ok(());
+ }
+ open_words.truncate(calls * KIND_WORDS_PER_CALL);
+
+ let questions = competency_questions::accepted(pool, kb_id).await?;
+ let q_items: Vec<agent::QuestionItem<'_>> = questions
+ .iter()
+ .enumerate()
+ .map(|(i, q)| agent::QuestionItem {
+ id: i as i64,
+ text: &q.question,
+ })
+ .collect();
+ let q_ids: HashSet<i64> = (0..questions.len() as i64).collect();
+ let keys_of = |ids: &[Uuid]| -> Vec<&str> {
+ ids.iter()
+ .filter_map(|id| class_key.get(id).copied())
+ .collect()
+ };
+ let glossary = agent::Glossary {
+ classes: classes
+ .iter()
+ .map(|c| (c.key.as_str(), c.label.as_str(), c.description.as_str()))
+ .collect(),
+ properties: props
+ .iter()
+ .map(|p| {
+ (
+ p.key.as_str(),
+ p.label.as_str(),
+ p.kind.as_str(),
+ keys_of(&p.domains),
+ keys_of(&p.ranges),
+ p.description.as_str(),
+ )
+ })
+ .collect(),
+ };
+ let sig_items: Vec<agent::OpenSignature<'_>> = open
+ .iter()
+ .enumerate()
+ .map(|(i, s)| agent::OpenSignature {
+ id: i as i64,
+ phrase: &s.phrase,
+ subject_class: s.subject_type_key.as_deref(),
+ object_class: s.object_type_key.as_deref(),
+ object_is_value: s.object_is_value,
+ statement_count: s.count,
+ examples: &s.examples,
+ quotes: &s.quotes,
+ })
+ .collect();
+ let word_items: Vec<agent::OpenKindWord<'_>> = open_words
+ .iter()
+ .enumerate()
+ .map(|(i, w)| agent::OpenKindWord {
+ id: i as i64,
+ kind_word: &w.kind_word,
+ count: w.count,
+ examples: &w.examples,
+ phrases: &w.phrases,
+ })
+ .collect();
+ tracing::info!(%kb_id, shapes = open.len(), kind_words = open_words.len(), questions = questions.len(), calls, "本体代理开始");
+
+ let mut merged: HashMap<String, Merged> = HashMap::new();
+ let mut order: Vec<String> = Vec::new();
+ let (mut failed, mut malformed, mut skipped_existing) = (0usize, 0usize, 0usize);
+ for b in 0..calls {
+ let sig_batch = sig_items
+ .get(b * SIGNATURES_PER_CALL..)
+ .map(|rest| &rest[..rest.len().min(SIGNATURES_PER_CALL)])
+ .unwrap_or(&[]);
+ let word_batch = word_items
+ .get(b * KIND_WORDS_PER_CALL..)
+ .map(|rest| &rest[..rest.len().min(KIND_WORDS_PER_CALL)])
+ .unwrap_or(&[]);
+ let sig_ids: HashSet<i64> = sig_batch.iter().map(|s| s.id).collect();
+ let word_ids: HashSet<i64> = word_batch.iter().map(|w| w.id).collect();
+ let messages = agent::build_proposal_messages(sig_batch, word_batch, &glossary, &q_items);
+ let reply =
+ match chat_retrying_rate_limits_at(state, settings, client, &messages, Some(0.0)).await
+ {
+ Ok(r) => r,
+ Err(e) => {
+ if utopia_core::error::is_terminal(&e) {
+ return Err(e);
+ }
+ failed += 1;
+ tracing::warn!(%kb_id, batch = b, error = %e, "本体代理:这一批调用失败");
+ continue;
+ }
+ };
+ let parsed = match agent::parse_proposal_response(&reply.text, &sig_ids, &word_ids, &q_ids)
+ {
+ Ok(p) => p,
+ Err(e) => {
+ failed += 1;
+ tracing::warn!(%kb_id, batch = b, error = %e, "本体代理:回复读不出");
+ continue;
+ }
+ };
+ malformed += parsed.malformed;
+ for p in parsed.proposals {
+ // 模型被告知已有的不要提;还是提了就当它没说(对齐那边会把形状挂上去)
+ let taken = match p.kind.as_str() {
+ "class" => class_keys.contains(p.key.as_str()),
+ _ => prop_keys.contains(p.key.as_str()),
+ };
+ if taken {
+ skipped_existing += 1;
+ continue;
+ }
+ let slot = format!("{}:{}", p.kind, p.key);
+ let entry = merged.entry(slot.clone()).or_insert_with(|| {
+ order.push(slot);
+ Merged {
+ proposal: agent::Proposal {
+ signatures: Vec::new(),
+ kind_words: Vec::new(),
+ questions: Vec::new(),
+ ..p.clone()
+ },
+ shapes: Vec::new(),
+ phrases: Vec::new(),
+ words: Vec::new(),
+ quotes: Vec::new(),
+ serves: Vec::new(),
+ }
+ });
+ 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());
+ }
+ }
+ }
+ 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());
+ }
+ }
+ }
+ }
+ for id in p.questions {
+ let Some(q) = questions.get(id as usize) else {
+ continue;
+ };
+ if !entry.serves.contains(&q.id) {
+ entry.serves.push(q.id);
+ }
+ }
+ }
+ }
+
+ let items: Vec<utopia_store::ontology::AgentProposal> = order
+ .iter()
+ .filter_map(|slot| merged.get(slot))
+ .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",
+ };
+ let mut payload = json!({
+ "key": p.key,
+ "label": p.label,
+ "description": p.definition,
+ "forms": m.phrases,
+ "kind_words": m.words,
+ "examples": m.quotes,
+ "proposed_by": "agent",
+ });
+ match section {
+ "entity_types" => {
+ payload["parents"] = json!(p.parents);
+ }
+ "attribute_types" => {
+ payload["datatype"] = json!(datatype_or_text(p.datatype.as_deref()));
+ payload["domains"] = json!(p.domains);
+ }
+ _ => {
+ payload["temporal"] = json!("state");
+ payload["domains"] = json!(p.domains);
+ payload["ranges"] = json!(p.ranges);
+ }
+ }
+ utopia_store::ontology::AgentProposal {
+ section: section.to_string(),
+ key: p.key.clone(),
+ payload,
+ serves: m.serves.clone(),
+ signatures: json!({ "phrases": m.shapes, "kind_words": m.words }),
+ }
+ })
+ .collect();
+ utopia_store::ontology::save_agent_proposals(pool, kb_id, &items).await?;
+ tracing::info!(%kb_id, proposals = items.len(), failed, malformed, skipped_existing, "本体代理结束");
+ if !items.is_empty() {
+ state.emit_pending(kb_id);
+ }
+ Ok(())
+}
+
+fn datatype_or_text(d: Option<&str>) -> &str {
+ match d {
+ Some(d @ ("text" | "number" | "date" | "bool")) => d,
+ _ => "text",
+ }
+}
+
+/// 采纳时人改过的几格。None = 照提案
+#[derive(Debug, Default, Deserialize)]
+pub struct AdoptEdits {
+ pub label: Option<String>,
+ pub description: Option<String>,
+ pub datatype: Option<String>,
+ pub domains: Option<Vec<String>>,
+ pub ranges: Option<Vec<String>>,
+ pub parents: Option<Vec<String>>,
+}
+
+fn strings(v: Option<&Value>) -> Vec<String> {
+ v.and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(|x| x.as_str().map(str::to_string))
+ .collect()
+}
+
+/// 采纳一条代理提案(0061 决定 3):建出元素,标记提案,排对齐让形状重判。
+/// 返回新元素的 id
+pub async fn adopt(
+ state: &AppState,
+ kb_id: Uuid,
+ section: &str,
+ key: &str,
+ edits: AdoptEdits,
+ actor: Uuid,
+) -> Result<Uuid, AppError> {
+ let pool = &state.pool;
+ let Some(p) = utopia_store::ontology::open_proposal(pool, kb_id, section, key).await? else {
+ return Err(AppError::NotFound);
+ };
+ let classes = utopia_store::graph::entity_types(pool, kb_id).await?;
+ let by_key: HashMap<&str, Uuid> = classes.iter().map(|c| (c.key.as_str(), c.id)).collect();
+ let resolve = |keys: Vec<String>| -> Result<Vec<Uuid>, AppError> {
+ keys.iter()
+ .map(|k| {
+ by_key.get(k.as_str()).copied().ok_or_else(|| {
+ AppError::invalid("unknown_class", format!("class `{k}` does not exist"))
+ })
+ })
+ .collect()
+ };
+ let label = edits
+ .label
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .or_else(|| p.payload.get("label").and_then(Value::as_str))
+ .unwrap_or(key)
+ .to_string();
+ let description = edits
+ .description
+ .as_deref()
+ .or_else(|| p.payload.get("description").and_then(Value::as_str))
+ .unwrap_or("")
+ .trim()
+ .to_string();
+ let id = match section {
+ "entity_types" => {
+ let parents = resolve(
+ edits
+ .parents
+ .unwrap_or_else(|| strings(p.payload.get("parents"))),
+ )?;
+ let id = utopia_store::ontology::create_entity_type(
+ pool,
+ kb_id,
+ key,
+ &label,
+ utopia_store::palette::color_for_key(key),
+ "circle",
+ &parents,
+ &description,
+ )
+ .await?;
+ // 多了一个类:类别词里「没有」「没定」的要重判,短语对齐跟在它后面
+ let _ = utopia_store::jobs::enqueue_unless_pending(
+ pool,
+ "align_types",
+ json!({ "kb_id": kb_id }),
+ std::time::Duration::from_secs(5),
+ )
+ .await;
+ id
+ }
+ "relation_types" | "attribute_types" => {
+ let kind = if section == "attribute_types" {
+ "attribute"
+ } else {
+ "relation"
+ };
+ let domains = resolve(
+ edits
+ .domains
+ .unwrap_or_else(|| strings(p.payload.get("domains"))),
+ )?;
+ let ranges = if kind == "relation" {
+ resolve(
+ edits
+ .ranges
+ .unwrap_or_else(|| strings(p.payload.get("ranges"))),
+ )?
+ } else {
+ Vec::new()
+ };
+ let datatype = if kind == "attribute" {
+ Some(
+ datatype_or_text(
+ edits
+ .datatype
+ .as_deref()
+ .or_else(|| p.payload.get("datatype").and_then(Value::as_str)),
+ )
+ .to_string(),
+ )
+ } else {
+ None
+ };
+ let id = utopia_store::ontology::create_relation_type(
+ pool,
+ kb_id,
+ key,
+ &label,
+ "state",
+ RelationAxioms::default(),
+ &description,
+ kind,
+ &domains,
+ &ranges,
+ datatype.as_deref(),
+ None,
+ )
+ .await?;
+ // 多了一个属性:判成 none / undecided 的形状也许对得上了(0053 的指纹变了)
+ let _ = utopia_store::jobs::enqueue_unless_pending(
+ pool,
+ "align_phrases",
+ json!({ "kb_id": kb_id }),
+ std::time::Duration::from_secs(5),
+ )
+ .await;
+ id
+ }
+ _ => {
+ return Err(AppError::invalid(
+ "bad_section",
+ "section 只能是 entity_types、relation_types 或 attribute_types",
+ ))
+ }
+ };
+ utopia_store::ontology::decide_proposal(pool, kb_id, section, key, "adopted", actor).await?;
+ let _ = utopia_store::audit::record(
+ pool,
+ Some(kb_id),
+ actor,
+ "ontology_proposal.adopted",
+ section.trim_end_matches('s'),
+ Some(id),
+ json!({ "key": key, "label": label, "proposed_by": p.proposed_by, "serves": p.serves }),
+ )
+ .await;
+ state.emit_graph(kb_id);
+ Ok(id)
+}
+
+#[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
new file mode 100644
index 00000000..20a75e7b
--- /dev/null
+++ b/crates/utopia-server/src/ontology_agent_tests.rs
@@ -0,0 +1,347 @@
+//! 本体代理的一轮(0061):没绑上的形状和接受了的问题交给脚本化的模型,提案落进
+//! `ontology_proposals` 并记下服务的问题与形状;采纳建出属性并排对齐;提过的形状下一轮
+//! 不再送。没有 `UTOPIA_DATABASE_URL` 时跳过。
+use super::*;
+use axum::{extract::State, response::IntoResponse, routing::post, Json, Router};
+use serde_json::{json, Value};
+use std::sync::{Arc, Mutex};
+use utopia_store::phrase_bindings::Decision;
+
+#[derive(Clone)]
+struct Model {
+ replies: Arc<Mutex<Vec<Value>>>,
+ requests: Arc<Mutex<Vec<Value>>>,
+}
+async fn reply(State(m): State<Model>, Json(body): Json<Value>) -> impl IntoResponse {
+ m.requests.lock().unwrap().push(body);
+ let text = {
+ let mut replies = m.replies.lock().unwrap();
+ if replies.is_empty() {
+ panic!("unexpected model request");
+ }
+ replies.remove(0).to_string()
+ };
+ let frame = json!({"choices":[{"delta":{"content":text}}]});
+ (
+ [("content-type", "text/event-stream")],
+ format!("data: {frame}\n\ndata: [DONE]\n\n"),
+ )
+}
+
+struct Fx {
+ pool: sqlx::PgPool,
+ state: AppState,
+ org: Uuid,
+ kb: Uuid,
+ organization: Uuid,
+ place: Uuid,
+ /// 采纳的人(decided_by 是外键)
+ user: Uuid,
+ model: Model,
+ server: tokio::task::JoinHandle<()>,
+ _dir: tempfile::TempDir,
+}
+
+impl Fx {
+ /// 一个库:organization、place 两个类,没有属性;Acme —founded in→ London 一条开放陈述
+ 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) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ sqlx::raw_sql(&format!(
+ "INSERT INTO organizations(id,name) VALUES ('{org}','ontology-agent');
+ INSERT INTO workspaces(id,org_id,name) VALUES ('{ws}','{org}','ontology-agent');
+ INSERT INTO knowledge_bases(id,workspace_id,name) VALUES ('{kb}','{ws}','ontology-agent');
+ INSERT INTO users(id,org_id,email,password_hash,display_name) VALUES ('{user}','{org}','{user}@agent.test','unused','Adopter');
+ INSERT INTO entity_types(id,kb_id,key,label,color,shape,description) VALUES
+ ('{organization}','{kb}','organization','Organization','#000','circle','a company or institution'),
+ ('{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 facts(id,kb_id,subject_id,object_id,layer,phrase) VALUES
+ ('{statement}','{kb}','{acme}','{london}','open','founded in');"
+ ))
+ .execute(&pool)
+ .await?;
+ let model = Model {
+ replies: Arc::new(Mutex::new(replies)),
+ requests: Arc::new(Mutex::new(Vec::new())),
+ };
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
+ let endpoint = format!("http://{}", listener.local_addr()?);
+ let router = Router::new()
+ .route("/chat/completions", post(reply))
+ .with_state(model.clone());
+ let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
+ utopia_store::settings::upsert(
+ &pool,
+ ws,
+ Some(&endpoint),
+ None,
+ Some("scripted"),
+ None,
+ None,
+ None,
+ None,
+ )
+ .await?;
+ let dir = tempfile::tempdir()?;
+ let cfg = utopia_core::config::AppConfig {
+ data_dir: dir.path().to_string_lossy().into_owned(),
+ ..Default::default()
+ };
+ let search = Arc::new(utopia_search::SearchIndex::open(
+ &dir.path().join("search"),
+ )?);
+ let state = AppState::new(pool.clone(), &cfg, search, "test-only".into());
+ Ok(Some(Self {
+ pool,
+ state,
+ org,
+ kb,
+ organization,
+ place,
+ user,
+ model,
+ server,
+ _dir: dir,
+ }))
+ }
+
+ /// 对齐判过这条形状:没有属性可绑
+ 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?;
+ Ok(())
+ }
+
+ async fn cleanup(self) -> anyhow::Result<()> {
+ self.server.abort();
+ sqlx::query("DELETE FROM jobs WHERE payload->>'kb_id'=$1")
+ .bind(self.kb.to_string())
+ .execute(&self.pool)
+ .await?;
+ // decided_by 指向 users,不级联:先清提案再删组织
+ sqlx::query("DELETE FROM ontology_proposals WHERE kb_id=$1")
+ .bind(self.kb)
+ .execute(&self.pool)
+ .await?;
+ sqlx::query("DELETE FROM organizations WHERE id=$1")
+ .bind(self.org)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+}
+
+fn user_text(request: &Value) -> String {
+ request["messages"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|m| m["role"] == "user")
+ .filter_map(|m| m["content"].as_str())
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+#[tokio::test]
+async fn an_unbound_shape_becomes_a_proposal_that_serves_a_question_and_adoption_builds_the_property(
+) -> anyhow::Result<()> {
+ let Some(f) = Fx::new(vec![json!({
+ "p": [{
+ "kind": "property", "key": "founded_in", "label": "founded in",
+ "definition": "the place where an organization was founded",
+ "value": false, "datatype": null,
+ "domains": ["organization"], "ranges": ["place"],
+ "s": [0], "k": [], "q": [0]
+ }],
+ "existing": []
+ })])
+ .await?
+ else {
+ return Ok(());
+ };
+ f.decide_none().await?;
+ let qid = competency_questions::create(
+ &f.pool,
+ f.kb,
+ competency_questions::NewQuestion {
+ question: "Where was each organization founded?",
+ expected_answer: None,
+ needs: None,
+ origin: "person",
+ status: "accepted",
+ created_by: None,
+ },
+ )
+ .await?;
+
+ propose(&f.state, f.kb).await?;
+
+ // 模型看到了形状、词表和问题
+ let requests = f.model.requests.lock().unwrap().clone();
+ assert_eq!(requests.len(), 1, "one batch, one call");
+ let text = user_text(&requests[0]);
+ assert!(
+ text.contains("founded in"),
+ "the open shape is offered: {text}"
+ );
+ assert!(
+ text.contains("organization"),
+ "the glossary is offered: {text}"
+ );
+ assert!(
+ text.contains("Where was each organization founded?"),
+ "the accepted question is offered: {text}"
+ );
+
+ // 提案落库,带着谁提的、服务的问题、会绑的形状
+ let open = utopia_store::ontology::open_proposals(&f.pool, f.kb).await?;
+ assert_eq!(open.len(), 1, "one proposal: {open:?}");
+ let p = &open[0];
+ assert_eq!(p.section, "relation_types");
+ assert_eq!(p.key, "founded_in");
+ assert_eq!(p.proposed_by, "agent");
+ assert_eq!(p.serves, vec![qid]);
+ assert_eq!(
+ p.signatures["phrases"][0]["phrase"], "founded in",
+ "the shape it binds is recorded: {}",
+ p.signatures
+ );
+ assert_eq!(p.signatures["phrases"][0]["subject"], "organization");
+ assert_eq!(p.payload["forms"][0], "founded in");
+ assert_eq!(p.payload["domains"][0], "organization");
+ assert_eq!(p.payload["ranges"][0], "place");
+ assert_eq!(
+ p.payload["description"],
+ "the place where an organization was founded"
+ );
+
+ // 提过的形状下一轮不再送:没有模型调用
+ propose(&f.state, f.kb).await?;
+ assert_eq!(
+ f.model.requests.lock().unwrap().len(),
+ 1,
+ "an already-proposed shape is not offered again"
+ );
+
+ // 采纳:属性建出来,签名域值域照提案,提案标记 adopted,短语对齐排上
+ let id = adopt(
+ &f.state,
+ f.kb,
+ "relation_types",
+ "founded_in",
+ AdoptEdits {
+ label: Some("Founded in".into()),
+ ..Default::default()
+ },
+ f.user,
+ )
+ .await?;
+ let props = utopia_store::ontology::relation_type_views(&f.pool, f.kb).await?;
+ let built = props
+ .iter()
+ .find(|p| p.id == id)
+ .expect("the property exists");
+ assert_eq!(built.key, "founded_in");
+ // 属性标签照库里的规矩写成小驼峰:人的改动进去了,只是换了写法
+ assert_eq!(built.label, "foundedIn", "the person's edit wins");
+ assert_eq!(built.kind, "relation");
+ assert_eq!(built.domains, vec![f.organization]);
+ assert_eq!(built.ranges, vec![f.place]);
+ assert_eq!(
+ built.description,
+ "the place where an organization was founded"
+ );
+ assert!(
+ utopia_store::ontology::open_proposals(&f.pool, f.kb)
+ .await?
+ .is_empty(),
+ "the proposal is no longer open"
+ );
+ let status: String = sqlx::query_scalar(
+ "SELECT status FROM ontology_proposals WHERE kb_id=$1 AND section='relation_types' AND key='founded_in'",
+ )
+ .bind(f.kb)
+ .fetch_one(&f.pool)
+ .await?;
+ assert_eq!(status, "adopted");
+ assert!(
+ utopia_store::jobs::pending_for_kb(&f.pool, "align_phrases", f.kb).await?,
+ "adoption re-decides the shapes through alignment"
+ );
+
+ // 采纳过的不能再采纳
+ let again = adopt(
+ &f.state,
+ f.kb,
+ "relation_types",
+ "founded_in",
+ AdoptEdits::default(),
+ f.user,
+ )
+ .await;
+ assert!(
+ matches!(again, Err(AppError::NotFound)),
+ "a decided proposal is not open: {again:?}"
+ );
+ f.cleanup().await
+}
+
+#[tokio::test]
+async fn a_proposal_for_an_existing_key_or_binding_nothing_is_dropped() -> anyhow::Result<()> {
+ let Some(f) = Fx::new(vec![json!({
+ "p": [
+ // 已有的类:不提
+ {"kind": "class", "key": "place", "label": "Place", "definition": "x", "parents": [], "s": [], "k": [], "q": []},
+ // 什么都不绑:坏项
+ {"kind": "property", "key": "orphan", "label": "orphan", "definition": "x", "value": false,
+ "domains": [], "ranges": [], "s": [], "k": [], "q": []},
+ // 字面值属性:进 attribute_types,datatype 缺省 text
+ {"kind": "property", "key": "founding_note", "label": "founding note", "definition": "x", "value": true,
+ "datatype": "weird", "domains": ["organization"], "ranges": [], "s": [0], "k": [], "q": []}
+ ],
+ "existing": []
+ })])
+ .await?
+ else {
+ return Ok(());
+ };
+ f.decide_none().await?;
+ propose(&f.state, f.kb).await?;
+ let open = utopia_store::ontology::open_proposals(&f.pool, f.kb).await?;
+ assert_eq!(open.len(), 1, "only the attribute survives: {open:?}");
+ assert_eq!(open[0].section, "attribute_types");
+ assert_eq!(open[0].key, "founding_note");
+ assert_eq!(open[0].payload["datatype"], "text");
+ assert!(open[0].serves.is_empty());
+ f.cleanup().await
+}
diff --git a/crates/utopia-server/src/phrase_alignment.rs b/crates/utopia-server/src/phrase_alignment.rs
index 2a81b7e2..e9b4b968 100644
--- a/crates/utopia-server/src/phrase_alignment.rs
+++ b/crates/utopia-server/src/phrase_alignment.rs
@@ -892,6 +892,24 @@ async fn align_phrases_locked(
// 漏答的签名就只能等下一篇文档来排——最后一篇之后没有下一篇,它们就永远没有结论;
// 而漏答不写任何行,审核队列也看不见(同类别词对齐)
let unfinished = failed > 0 || unanswered > 0;
+ // 对齐收尾:没绑上的形状够多,叫本体代理来看(0061 决定 2)。代理自己跳过提过的,
+ // 所以这里只数不筛;一分钟的去抖让连着几篇文档只叫一次
+ if !changed && !unfinished {
+ let unbound = phrase_bindings::bindings(pool, kb_id)
+ .await?
+ .iter()
+ .filter(|b| matches!(b.status.as_str(), "none" | "undecided"))
+ .count();
+ if unbound >= crate::ontology_agent::TRIGGER_UNBOUND {
+ utopia_store::jobs::enqueue_unless_pending(
+ pool,
+ "propose_ontology",
+ serde_json::json!({ "kb_id": kb_id }),
+ std::time::Duration::from_secs(60),
+ )
+ .await?;
+ }
+ }
if changed {
utopia_store::jobs::enqueue_unless_queued(
pool,
diff --git a/crates/utopia-store/src/competency_questions.rs b/crates/utopia-store/src/competency_questions.rs
new file mode 100644
index 00000000..65b5d2b5
--- /dev/null
+++ b/crates/utopia-store/src/competency_questions.rs
@@ -0,0 +1,172 @@
+//! 能力问题(0061 决定 1):一个库该回答什么,写成行。本体的元素凭它们判:一条属性
+//! 值不值得批,看它服务哪个问题。人写的直接 accepted;代理从开放图谱里提的先 proposed。
+
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::PgPool;
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct Question {
+ pub id: Uuid,
+ pub kb_id: Uuid,
+ pub question: String,
+ pub expected_answer: Option<String>,
+ pub needs: Option<serde_json::Value>,
+ /// person | agent
+ pub origin: String,
+ /// accepted | proposed | rejected | retired
+ pub status: String,
+ pub created_by: Option<Uuid>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ pub last_checked_at: Option<DateTime<Utc>>,
+ pub last_result: Option<serde_json::Value>,
+}
+
+const COLS: &str = "id, kb_id, question, expected_answer, needs, origin, status, created_by,
+ created_at, updated_at, last_checked_at, last_result";
+
+fn validate(question: &str) -> AppResult<&str> {
+ let q = question.trim();
+ if q.is_empty() {
+ return Err(AppError::invalid(
+ "empty_question",
+ "A question needs words.",
+ ));
+ }
+ if q.chars().count() > 2000 {
+ return Err(AppError::invalid(
+ "long_question",
+ "A question is at most 2000 characters.",
+ ));
+ }
+ Ok(q)
+}
+
+/// 库里全部问题,新的在前
+pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Question>> {
+ Ok(sqlx::query_as(&format!(
+ "SELECT {COLS} FROM competency_questions WHERE kb_id = $1 ORDER BY created_at DESC, id"
+ ))
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 认下的问题:代理提案对着的是这些
+pub async fn accepted(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Question>> {
+ Ok(sqlx::query_as(&format!(
+ "SELECT {COLS} FROM competency_questions WHERE kb_id = $1 AND status = 'accepted'
+ ORDER BY created_at, id"
+ ))
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+pub struct NewQuestion<'a> {
+ pub question: &'a str,
+ pub expected_answer: Option<&'a str>,
+ pub needs: Option<&'a serde_json::Value>,
+ /// person | agent
+ pub origin: &'a str,
+ /// accepted | proposed
+ pub status: &'a str,
+ pub created_by: Option<Uuid>,
+}
+
+pub async fn create(pool: &PgPool, kb_id: Uuid, q: NewQuestion<'_>) -> AppResult<Uuid> {
+ let question = validate(q.question)?;
+ if !matches!(q.origin, "person" | "agent") || !matches!(q.status, "accepted" | "proposed") {
+ return Err(AppError::invalid(
+ "bad_question",
+ "origin is person or agent; status is accepted or proposed",
+ ));
+ }
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO competency_questions
+ (id, kb_id, question, expected_answer, needs, origin, status, created_by)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(question)
+ .bind(q.expected_answer.map(str::trim))
+ .bind(q.needs)
+ .bind(q.origin)
+ .bind(q.status)
+ .bind(q.created_by)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 改问题的文字、期望答案或形状。没给的不动;期望答案给空串是清掉
+pub async fn update(
+ pool: &PgPool,
+ kb_id: Uuid,
+ id: Uuid,
+ question: Option<&str>,
+ expected_answer: Option<&str>,
+ needs: Option<&serde_json::Value>,
+) -> AppResult<()> {
+ let question = question.map(validate).transpose()?;
+ let res = sqlx::query(
+ "UPDATE competency_questions
+ SET question = COALESCE($3, question),
+ expected_answer = CASE WHEN $4 IS NULL THEN expected_answer
+ WHEN btrim($4) = '' THEN NULL ELSE btrim($4) END,
+ needs = COALESCE($5, needs),
+ updated_at = now()
+ WHERE id = $2 AND kb_id = $1",
+ )
+ .bind(kb_id)
+ .bind(id)
+ .bind(question)
+ .bind(expected_answer)
+ .bind(needs)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 人对一条问题表态:认(accepted)、拒(rejected)、退役(retired)
+pub async fn set_status(pool: &PgPool, kb_id: Uuid, id: Uuid, status: &str) -> AppResult<()> {
+ if !matches!(status, "accepted" | "rejected" | "retired") {
+ return Err(AppError::invalid(
+ "bad_status",
+ "status is accepted, rejected or retired",
+ ));
+ }
+ let res = sqlx::query(
+ "UPDATE competency_questions SET status = $3, updated_at = now()
+ WHERE id = $2 AND kb_id = $1",
+ )
+ .bind(kb_id)
+ .bind(id)
+ .bind(status)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+pub async fn delete(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
+ let res = sqlx::query("DELETE FROM competency_questions WHERE id = $2 AND kb_id = $1")
+ .bind(kb_id)
+ .bind(id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
index 947de5e4..98059872 100644
--- a/crates/utopia-store/src/lib.rs
+++ b/crates/utopia-store/src/lib.rs
@@ -7,6 +7,7 @@ pub mod alerts;
pub mod alignment_queue;
pub mod audit;
pub mod business_rules;
+pub mod competency_questions;
pub mod conversations;
pub mod datasources;
pub mod db;
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index 978c1223..7e6d63d5 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -2037,12 +2037,112 @@ pub async fn set_disjoint_for(
// 本体提案(见 `ontology_proposals`)
// ---------------------------------------------------------------------------
-/// 一条落库的提案。`payload` 是接口原样返回的那一条。
+/// 一条落库的提案。`payload` 是接口原样返回的那一条。代理提的(0061)多带三样:
+/// 它服务的问题、它会绑上的形状,和谁提的
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct StoredProposal {
pub section: String,
pub key: String,
pub payload: serde_json::Value,
+ /// suggest | agent
+ pub proposed_by: String,
+ pub serves: Vec<Uuid>,
+ pub signatures: serde_json::Value,
+}
+
+/// 代理的一条提案(0061 决定 2):形状同 `save_proposals` 的一项,外加它服务的问题与会绑的形状
+pub struct AgentProposal {
+ pub section: String,
+ pub key: String,
+ pub payload: serde_json::Value,
+ pub serves: Vec<Uuid>,
+ pub signatures: serde_json::Value,
+}
+
+/// 把代理的一轮提案写下来。已经有人表过态的不动(同 `save_proposals`);同一个键再提是刷新,
+/// 服务的问题与形状一起刷
+pub async fn save_agent_proposals(
+ pool: &PgPool,
+ kb_id: Uuid,
+ items: &[AgentProposal],
+) -> AppResult<()> {
+ for it in items {
+ sqlx::query(
+ "INSERT INTO ontology_proposals
+ (id, kb_id, section, key, payload, proposed_by, serves, signatures)
+ VALUES ($1, $2, $3, $4, $5, 'agent', $6, $7)
+ ON CONFLICT (kb_id, section, key) DO UPDATE
+ SET payload = EXCLUDED.payload, proposed_by = 'agent',
+ serves = EXCLUDED.serves, signatures = EXCLUDED.signatures,
+ created_at = now()
+ WHERE ontology_proposals.status = 'open'",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(&it.section)
+ .bind(&it.key)
+ .bind(&it.payload)
+ .bind(&it.serves)
+ .bind(&it.signatures)
+ .execute(pool)
+ .await?;
+ }
+ Ok(())
+}
+
+/// 代理已经提过的形状(不论人怎么表的态):下一轮不再为它们提——被拒的尤其不再提
+pub async fn signatures_already_proposed(
+ pool: &PgPool,
+ kb_id: Uuid,
+) -> AppResult<Vec<serde_json::Value>> {
+ Ok(sqlx::query_scalar(
+ "SELECT signatures FROM ontology_proposals WHERE kb_id = $1 AND proposed_by = 'agent'",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 一条提案被拒了,连理由。改状态不删行(同 `decide_proposal`)
+pub async fn reject_proposal(
+ pool: &PgPool,
+ kb_id: Uuid,
+ section: &str,
+ key: &str,
+ reason: Option<&str>,
+ actor: Uuid,
+) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE ontology_proposals
+ SET status = 'rejected', reason = $4, decided_by = $5, decided_at = now()
+ WHERE kb_id = $1 AND section = $2 AND key = $3 AND status = 'open'",
+ )
+ .bind(kb_id)
+ .bind(section)
+ .bind(key)
+ .bind(reason.map(str::trim).filter(|r| !r.is_empty()))
+ .bind(actor)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 一条还开着的提案,按键取(采纳时要读它的 payload)
+pub async fn open_proposal(
+ pool: &PgPool,
+ kb_id: Uuid,
+ section: &str,
+ key: &str,
+) -> AppResult<Option<StoredProposal>> {
+ Ok(sqlx::query_as(
+ "SELECT section, key, payload, proposed_by, serves, signatures FROM ontology_proposals
+ WHERE kb_id = $1 AND section = $2 AND key = $3 AND status = 'open'",
+ )
+ .bind(kb_id)
+ .bind(section)
+ .bind(key)
+ .fetch_optional(pool)
+ .await?)
}
/// 把一轮 Suggest 的结果写下来。
@@ -2077,7 +2177,7 @@ pub async fn save_proposals(
/// 还等着人看的提案。新的排前面——旧的那批已经被看过好几眼了。
pub async fn open_proposals(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<StoredProposal>> {
Ok(sqlx::query_as(
- "SELECT section, key, payload FROM ontology_proposals
+ "SELECT section, key, payload, proposed_by, serves, signatures FROM ontology_proposals
WHERE kb_id = $1 AND status = 'open'
ORDER BY created_at DESC, key",
)
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 438be79c..9987d2af 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**: Proposed 2026-09-26 · 0044 cut 5 · nothing built · 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 · 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 41506191..ccad7e06 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) | Proposed 2026-09-26 · 0044 cut 5 · 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 · 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 |
@@ -141,7 +141,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) | ontology | current |
| 0054 | [A source may push statements in the open contract](0054-a-source-may-push-statements-in-the-open-contract.md) | sources | proposed |
| 0060 | [A rule's definition has a history](0060-a-rule-definition-has-a-history.md) | rules | current |
-| 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) | ontology | proposed |
+| 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) | ontology | current |
| 0062 | [The export says what is contested](0062-the-export-says-what-is-contested.md) | ontology | proposed |
The status word is whether a later record has overtaken this one; what is built is in the record's own status line. Domains are the files of [../design/](../design/README.md), where every record is dated and the status words are defined.
diff --git a/migrations/0077_the_ontology_is_judged_by_its_questions.sql b/migrations/0077_the_ontology_is_judged_by_its_questions.sql
new file mode 100644
index 00000000..a24d01ff
--- /dev/null
+++ b/migrations/0077_the_ontology_is_judged_by_its_questions.sql
@@ -0,0 +1,37 @@
+-- 0061 · The ontology is proposed from the open graph and judged by its questions (cut 1).
+--
+-- 一个库该回答什么问题,从前没有地方写;本体的一个元素值不值得批,也就无从判断。
+-- 能力问题成为库里的行、成为判据;本体代理从开放图谱里对不上本体的签名和类别词出发,
+-- 对着这些问题提案。提案落在 0003 的 `ontology_proposals` 里,多带三样东西:谁提的、
+-- 它服务哪些问题、它会绑上哪些签名;被拒时记下理由,下一轮不再提同一条。
+CREATE TABLE competency_questions (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ -- 人的原话
+ question TEXT NOT NULL,
+ -- 期望的答案(可空);或答案要走的形状:{"classes": [...], "properties": [...]}
+ expected_answer TEXT,
+ needs JSONB,
+ -- person 写的,或 agent 从开放图谱里提的(proposed,等人认)
+ origin TEXT NOT NULL DEFAULT 'person' CHECK (origin IN ('person', 'agent')),
+ status TEXT NOT NULL DEFAULT 'accepted'
+ CHECK (status IN ('accepted', 'proposed', 'rejected', 'retired')),
+ created_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ -- 上次按它检查本体的时间与结果(cut 3 的度量写这里)
+ last_checked_at TIMESTAMPTZ,
+ last_result JSONB
+);
+CREATE INDEX competency_questions_kb ON competency_questions (kb_id, status);
+
+ALTER TABLE ontology_proposals
+ ADD COLUMN proposed_by TEXT NOT NULL DEFAULT 'suggest'
+ CHECK (proposed_by IN ('suggest', 'agent')),
+ -- 拒绝的理由(人写的);代理下一轮不再为同一批签名提同一条
+ ADD COLUMN reason TEXT,
+ -- 它服务的能力问题
+ ADD COLUMN serves UUID[] NOT NULL DEFAULT '{}',
+ -- 它会绑上的形状:{"phrases": [{phrase, subject_type_id, object_type_id, object_is_value,
+ -- statement_count}], "kind_words": [{kind_word, count}]}
+ ADD COLUMN signatures JSONB NOT NULL DEFAULT '{}';
diff --git a/web/src/api.ts b/web/src/api.ts
index 9a64171a..681d7e91 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1223,6 +1223,21 @@ export interface RelationTypeView {
usage: number;
}
+/** 一条能力问题(0061 决定 1):本体该答得上来的问题,代理提本体时照着看 */
+export interface CompetencyQuestion {
+ id: string;
+ kb_id: string;
+ question: string;
+ expected_answer: string | null;
+ needs: unknown | null;
+ origin: "person" | "agent";
+ status: "accepted" | "proposed" | "rejected" | "retired";
+ created_at: string;
+ updated_at: string;
+ last_checked_at: string | null;
+ last_result: unknown | null;
+}
+
export interface OntologyMiss {
kind: "entity_type" | "relation_type";
key: string;
@@ -1264,14 +1279,38 @@ export interface UniquenessCandidate {
/** `description` 与 `reason` 不是一回事:description 逐字进抽取提示词,是模型判断
"什么算这个类"的唯一依据;reason 只是给人看的"为什么该加"。喂错了这个类会成为
下一个倾倒场——实测 technology 就是这么来的。 */
+/** 代理提的一条多带的几格(0061):谁提的、服务哪些问题、会绑上哪些形状。
+ Suggest 的一份没有这些,渲染照旧 */
+export interface AgentProposalFields {
+ proposed_by?: "suggest" | "agent";
+ /** 服务的能力问题 id */
+ serves?: string[];
+ /** 会归到这个类下的类别词 */
+ kind_words?: string[];
+ /** 原文里的几句,给人核对定义用 */
+ examples?: string[];
+ domains?: string[];
+ ranges?: string[];
+ parents?: string[];
+ signatures?: {
+ phrases?: {
+ phrase: string;
+ subject: string | null;
+ object: string | null;
+ value: boolean;
+ }[];
+ kind_words?: string[];
+ };
+}
+
export interface OntologyProposals {
- entity_types: {
+ entity_types: (AgentProposalFields & {
key: string;
label: string;
description?: string;
reason?: string;
- }[];
- relation_types: {
+ })[];
+ relation_types: (AgentProposalFields & {
key: string;
label: string;
temporal?: string;
@@ -1280,7 +1319,7 @@ export interface OntologyProposals {
reason?: string;
/** 这条关系归并了哪些表层说法。有它才谈得上把等待的事实改写过去 */
forms?: string[];
- }[];
+ })[];
/**
* 宾语是字面值的说法("成立日期 = 2015")。
*
@@ -1288,7 +1327,7 @@ export interface OntologyProposals {
* 而把它当关系建出来,那个值就会变成一个假实体。domain 不在这里——
* 服务端从事实的主语类型里取,猜错会让整条被丢弃
*/
- attribute_types?: {
+ attribute_types?: (AgentProposalFields & {
key: string;
label: string;
datatype?: string;
@@ -1296,7 +1335,7 @@ export interface OntologyProposals {
description?: string;
reason?: string;
forms?: string[];
- }[];
+ })[];
/**
* 本体里**已经有**这个意思,只需把说法挂过去。
*
@@ -2159,10 +2198,64 @@ export const api = {
section: string,
key: string,
status: "adopted" | "rejected",
+ /** 拒绝的理由(0061):下一轮代理读得到 */
+ reason?: string,
) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/proposals`, {
method: "POST",
- body: JSON.stringify({ section, key, status }),
+ body: JSON.stringify({ section, key, status, reason }),
+ }),
+ /** 叫本体代理来看一眼(0061 决定 2):排一份任务,结果落在 storedProposals */
+ proposeOntology: (kbId: string) =>
+ request<{ queued: boolean }>(`/api/v1/kbs/${kbId}/ontology/propose`, {
+ method: "POST",
+ body: "{}",
+ }),
+ /** 采纳代理的一条提案(0061 决定 3):服务端建元素、标记、排对齐 */
+ adoptProposal: (
+ kbId: string,
+ section: string,
+ key: string,
+ edits?: {
+ label?: string;
+ description?: string;
+ datatype?: string;
+ domains?: string[];
+ ranges?: string[];
+ parents?: string[];
+ },
+ ) =>
+ request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/proposals/adopt`, {
+ method: "POST",
+ body: JSON.stringify({ section, key, ...(edits ?? {}) }),
+ }),
+ /** 能力问题(0061 决定 1) */
+ listQuestions: (kbId: string) =>
+ request<CompetencyQuestion[]>(`/api/v1/kbs/${kbId}/questions`),
+ createQuestion: (
+ kbId: string,
+ body: { question: string; expected_answer?: string },
+ ) =>
+ request<{ id: string }>(`/api/v1/kbs/${kbId}/questions`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ updateQuestion: (
+ kbId: string,
+ qid: string,
+ body: {
+ question?: string;
+ expected_answer?: string;
+ status?: "accepted" | "rejected" | "retired";
+ },
+ ) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/questions/${qid}`, {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
+ deleteQuestion: (kbId: string, qid: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/questions/${qid}`, {
+ method: "DELETE",
}),
dismissMiss: (kbId: string, kind: string, key: string) =>
request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 156ea3bd..ebd5ccec 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1665,6 +1665,34 @@ export const en = {
`Some could not be added: ${keys.join(", ")} — the rest went through.`,
proposals: "AI proposals",
keyHint: "lowercase_snake_case",
+ /* ---- 0061: the ontology agent and its questions ---- */
+ askAgent: "Ask the agent",
+ askAgentHint:
+ "Proposes classes and properties from phrases and kind words the ontology does not cover yet, judged against the competency questions.",
+ agentQueued: "The agent is looking — proposals appear here when it is done.",
+ agentWaiting: "Agent working…",
+ agentChip: "agent",
+ servesQuestions: (n: number) =>
+ n === 1 ? "serves 1 question" : `serves ${n} questions`,
+ bindsShapes: (n: number) =>
+ n === 1 ? "binds 1 phrase shape" : `binds ${n} phrase shapes`,
+ bindsKindWords: (n: number) =>
+ n === 1 ? "1 kind word" : `${n} kind words`,
+ rejectProposal: "Reject",
+ rejectReasonPrompt:
+ "Why not? (optional — the agent reads it before proposing again)",
+ rejectedProposal: "Rejected",
+ 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.",
+ questionPlaceholder: "e.g. Which companies did each founder start, and when?",
+ addQuestion: "Add",
+ noQuestions:
+ "No questions yet. Without them the agent judges proposals only by the phrases documents use.",
+ retireQuestion: "Retire",
+ deleteQuestion: "Delete",
+ questionAdded: "Question added",
+ questionRetired: "Question retired",
/* ---- Schema diagram ---- */
schemaDiagram: "Schema diagram",
/* 从前这句把「先加个类或导入 OWL 文件」说成了开始的前提,而本体本来就
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 3f22a885..929946bb 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1463,6 +1463,29 @@ export const zh: Strings = {
`有几个没能加入:${keys.join("、")}——其余的已经成功。`,
proposals: "AI 提案",
keyHint: "小写下划线命名",
+ /* ---- 0061:本体代理与能力问题 ---- */
+ askAgent: "请代理提案",
+ askAgentHint:
+ "从本体还没覆盖的短语和类别词里提出该建的类与属性,对着能力问题判断。",
+ agentQueued: "代理在看——看完了提案会出现在这里。",
+ agentWaiting: "代理在看…",
+ agentChip: "代理",
+ servesQuestions: (n: number) => `服务 ${n} 个问题`,
+ bindsShapes: (n: number) => `会绑 ${n} 种短语形状`,
+ bindsKindWords: (n: number) => `${n} 个类别词`,
+ rejectProposal: "拒绝",
+ rejectReasonPrompt: "为什么不要?(可不填——代理下次提案前会读)",
+ rejectedProposal: "已拒绝",
+ questions: "能力问题",
+ questionsHint:
+ "这个知识库应该答得上来的问题。代理提的类与属性要服务它们;它们就是本体的验收标准。",
+ questionPlaceholder: "例:每位创始人创办了哪些公司、什么时候?",
+ addQuestion: "添加",
+ noQuestions: "还没有问题。没有它们,代理只能按文档里的说法判断提案。",
+ retireQuestion: "退役",
+ deleteQuestion: "删除",
+ questionAdded: "已添加问题",
+ questionRetired: "问题已退役",
/* ---- 模式图 ---- */
schemaDiagram: "模式图",
schemaEmpty: "还没有类。文档进来时会自动补上。",
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index 3df699b7..91965fc6 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -29,6 +29,8 @@ import {
type ImportPlan,
type OntologyImportView,
type OntologyMiss,
+ type AgentProposalFields,
+ type CompetencyQuestion,
type PlannedItem,
type OntologyProposals,
type ResolutionOutcome,
@@ -532,6 +534,7 @@ export function Ontology() {
onChanged={refresh}
onError={onError}
/>
+ <QuestionsPanel kbId={kb.id} onError={onError} />
</div>
)}
</div>
@@ -1806,6 +1809,176 @@ function UniquenessPanel({
);
}
+/** 库里现在有几条代理提的提案:等代理答完的判据 */
+function agentCount(d: OntologyProposals | null | undefined): number {
+ if (!d) return 0;
+ return [
+ ...d.entity_types,
+ ...d.relation_types,
+ ...(d.attribute_types ?? []),
+ ].filter((p) => p.proposed_by === "agent").length;
+}
+
+/** 代理提案多带的几格(0061):定义、会绑的形状、类别词、服务的问题。
+ Suggest 的一份没有 proposed_by,什么都不画 */
+function AgentMeta({
+ p,
+}: {
+ p: AgentProposalFields & { description?: string; forms?: string[] };
+}) {
+ if (p.proposed_by !== "agent") return null;
+ const shapes = p.signatures?.phrases ?? [];
+ const shapeText = shapes
+ .map(
+ (sh) =>
+ `${sh.subject ?? "?"} — ${sh.phrase} → ${sh.value ? "value" : (sh.object ?? "?")}`,
+ )
+ .join("\n");
+ const examples = (p.examples ?? []).join("\n");
+ return (
+ <>
+ <Chip tone="success" title={S.ontology.askAgentHint}>
+ {S.ontology.agentChip}
+ </Chip>
+ {p.description && (
+ <span className="text-small text-ink-2 truncate" title={p.description}>
+ {p.description}
+ </span>
+ )}
+ {shapes.length > 0 && (
+ <span
+ className="text-small text-accent whitespace-nowrap"
+ title={examples ? `${shapeText}\n\n${examples}` : shapeText}
+ >
+ {S.ontology.bindsShapes(shapes.length)}
+ </span>
+ )}
+ {!!p.kind_words?.length && (
+ <span
+ className="text-small text-accent whitespace-nowrap"
+ title={p.kind_words.join(" · ")}
+ >
+ {S.ontology.bindsKindWords(p.kind_words.length)}
+ </span>
+ )}
+ {!!p.serves?.length && (
+ <Chip tone="info">{S.ontology.servesQuestions(p.serves.length)}</Chip>
+ )}
+ </>
+ );
+}
+
+/** 能力问题(0061 决定 1):本体该答得上来的问题。人写下即 accepted;退役的留着看 */
+function QuestionsPanel({
+ kbId,
+ onError,
+}: {
+ kbId: string;
+ onError: (e: unknown) => void;
+}) {
+ const qc = useQueryClient();
+ const questions = useQuery({
+ queryKey: ["questions", kbId],
+ queryFn: () => api.listQuestions(kbId),
+ });
+ const [draft, setDraft] = useState("");
+ const refresh = () => qc.invalidateQueries({ queryKey: ["questions", kbId] });
+ const add = useMutation({
+ mutationFn: (question: string) => api.createQuestion(kbId, { question }),
+ onSuccess: () => {
+ toast.success(S.ontology.questionAdded);
+ setDraft("");
+ refresh();
+ },
+ onError,
+ });
+ const retire = useMutation({
+ mutationFn: (q: CompetencyQuestion) =>
+ api.updateQuestion(kbId, q.id, { status: "retired" }),
+ onSuccess: () => {
+ toast.success(S.ontology.questionRetired);
+ refresh();
+ },
+ onError,
+ });
+ const remove = useMutation({
+ mutationFn: (q: CompetencyQuestion) => api.deleteQuestion(kbId, q.id),
+ onSuccess: refresh,
+ onError,
+ });
+ const rows = (questions.data ?? []).filter((q) => q.status !== "rejected");
+ const submit = () => {
+ const text = draft.trim();
+ if (text) add.mutate(text);
+ };
+ return (
+ <div className="mt-6 border-t border-line pt-3">
+ <h4 className="text-small font-semibold text-ink-2">{S.ontology.questions}</h4>
+ <p className="mb-2 text-small text-ink-2">{S.ontology.questionsHint}</p>
+ <div className="mb-2 flex items-center gap-2">
+ <Input
+ size="sm"
+ className="flex-1"
+ value={draft}
+ placeholder={S.ontology.questionPlaceholder}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") submit();
+ }}
+ />
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={submit}
+ disabled={add.isPending || !draft.trim()}
+ >
+ {S.ontology.addQuestion}
+ </Button>
+ </div>
+ {rows.length === 0 ? (
+ <p className="text-body text-ink-2">{S.ontology.noQuestions}</p>
+ ) : (
+ <div className="space-y-1">
+ {rows.map((q) => (
+ <div key={q.id} className="flex items-center gap-2 text-body">
+ <span
+ className={cn(
+ "flex-1 min-w-0 truncate",
+ q.status === "retired" ? "text-ink-2 line-through" : "text-ink",
+ )}
+ title={q.question}
+ >
+ {q.question}
+ </span>
+ {q.origin === "agent" && (
+ <Chip tone="success">{S.ontology.agentChip}</Chip>
+ )}
+ {q.status === "accepted" && (
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => retire.mutate(q)}
+ disabled={retire.isPending}
+ >
+ {S.ontology.retireQuestion}
+ </Button>
+ )}
+ <IconButton
+ size="sm"
+ label={S.ontology.deleteQuestion}
+ onClick={() => remove.mutate(q)}
+ disabled={remove.isPending}
+ >
+ <X size={13} />
+ </IconButton>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
function MissesPanel({
kbId,
misses,
@@ -1827,10 +2000,26 @@ function MissesPanel({
// 从前这里只有上面那个 useState——刷新一次、切走一次,整批提议就没了,
// 想再看只能重跑一次模型,而重跑未必给出同一批归并。归并了哪些说法正是
// 唯一能查证过并的东西(0003 的 optimized_for → runs_on 就是这么抓出来的)
+ // 叫了代理之后等它:任务在后台跑,隔几秒看一眼库里有没有新提案(0061)。
+ // 记的是叫它那一刻代理提案的条数——多出来了就是它答完了;两分钟没动静就不等了
+ const [awaitingAgent, setAwaitingAgent] = useState<{
+ since: number;
+ had: number;
+ } | null>(null);
const storedProposals = useQuery({
queryKey: ["storedProposals", kbId],
queryFn: () => api.storedProposals(kbId),
+ refetchInterval: awaitingAgent ? 4000 : false,
});
+ useEffect(() => {
+ if (!awaitingAgent || !storedProposals.data) return;
+ const d = storedProposals.data;
+ const now = agentCount(d);
+ if (now > awaitingAgent.had || Date.now() - awaitingAgent.since > 120_000) {
+ setProposals(d);
+ setAwaitingAgent(null);
+ }
+ }, [awaitingAgent, storedProposals.data]);
useEffect(() => {
// 只在还没有本地结果时回填。刚点完 Suggest 的那一批更新,不该被覆盖
if (proposals === null && storedProposals.data) {
@@ -1871,6 +2060,47 @@ function MissesPanel({
return forms.reduce((n, f) => n + (byForm.get(f) ?? 0), 0);
};
+ const askAgent = useMutation({
+ mutationFn: () => api.proposeOntology(kbId),
+ onSuccess: () => {
+ toast.info(S.ontology.agentQueued);
+ setAwaitingAgent({
+ since: Date.now(),
+ had: agentCount(storedProposals.data ?? proposals),
+ });
+ },
+ onError,
+ });
+ // 拒绝连理由:改状态不删行,理由下一轮代理读得到(0061)
+ const rejectProposal = useMutation({
+ mutationFn: ({
+ section,
+ key,
+ reason,
+ }: {
+ section: "entity_types" | "relation_types" | "attribute_types";
+ key: string;
+ reason?: string;
+ }) => api.decideProposal(kbId, section, key, "rejected", reason),
+ onSuccess: (_d, v) => {
+ toast.success(S.ontology.rejectedProposal);
+ setProposals(
+ (prev) =>
+ prev && {
+ ...prev,
+ [v.section]: (prev[v.section] ?? []).filter((x) => x.key !== v.key),
+ },
+ );
+ },
+ onError,
+ });
+ const reject = (
+ section: "entity_types" | "relation_types" | "attribute_types",
+ key: string,
+ ) => {
+ const reason = window.prompt(S.ontology.rejectReasonPrompt) ?? "";
+ rejectProposal.mutate({ section, key, reason: reason.trim() || undefined });
+ };
const suggest = useMutation({
mutationFn: () => api.suggestOntology(kbId),
onSuccess: setProposals,
@@ -1889,12 +2119,20 @@ function MissesPanel({
onError,
});
const approveEntity = useMutation({
- mutationFn: (p: { key: string; label: string; description?: string }) =>
- api.createEntityType(kbId, {
- key: p.key,
- label: p.label,
- description: p.description,
- }),
+ // 代理提的走采纳端点:服务端建类、标记提案、排对齐(0061 决定 3)
+ mutationFn: (p: {
+ key: string;
+ label: string;
+ description?: string;
+ proposed_by?: string;
+ }) =>
+ p.proposed_by === "agent"
+ ? api.adoptProposal(kbId, "entity_types", p.key)
+ : api.createEntityType(kbId, {
+ key: p.key,
+ label: p.label,
+ description: p.description,
+ }),
onSuccess: (_data, p) => {
// 已采纳:从提案列表移除,并顺带清掉对应的未匹配统计 chip(本体已覆盖)
toast.success(S.toast.added);
@@ -1922,8 +2160,11 @@ function MissesPanel({
functional?: boolean;
description?: string;
forms?: string[];
+ proposed_by?: string;
}) =>
- p.forms?.length
+ p.proposed_by === "agent"
+ ? api.adoptProposal(kbId, "relation_types", p.key)
+ : p.forms?.length
? api.adoptPredicate(kbId, {
key: p.key,
label: p.label,
@@ -1972,8 +2213,13 @@ function MissesPanel({
unit?: string;
description?: string;
forms?: string[];
+ proposed_by?: string;
}) =>
- api.adoptPredicate(kbId, {
+ p.proposed_by === "agent"
+ ? api
+ .adoptProposal(kbId, "attribute_types", p.key)
+ .then(() => ({}) as Awaited<ReturnType<typeof api.adoptPredicate>>)
+ : api.adoptPredicate(kbId, {
key: p.key,
kind: "attribute",
label: p.label,
@@ -2158,16 +2404,27 @@ function MissesPanel({
title={S.ontology.misses}
sub={S.ontology.missesHint}
actions={
- misses.length > 0 && (
+ <>
+ {misses.length > 0 && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => suggest.mutate()}
+ disabled={suggest.isPending}
+ >
+ {suggest.isPending ? S.ontology.suggesting : S.ontology.suggest}
+ </Button>
+ )}
<Button
size="sm"
variant="secondary"
- onClick={() => suggest.mutate()}
- disabled={suggest.isPending}
+ title={S.ontology.askAgentHint}
+ onClick={() => askAgent.mutate()}
+ disabled={askAgent.isPending || awaitingAgent !== null}
>
- {suggest.isPending ? S.ontology.suggesting : S.ontology.suggest}
+ {awaitingAgent ? S.ontology.agentWaiting : S.ontology.askAgent}
</Button>
- )
+ </>
}
/>
@@ -2391,6 +2648,7 @@ function MissesPanel({
{p.reason}
</span>
)}
+ <AgentMeta p={p} />
<Button variant="primary"
size="sm"
className="ml-auto"
@@ -2399,6 +2657,16 @@ function MissesPanel({
>
{S.ontology.approve}
</Button>
+ {p.proposed_by === "agent" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => reject("entity_types", p.key)}
+ disabled={rejectProposal.isPending}
+ >
+ {S.ontology.rejectProposal}
+ </Button>
+ )}
</div>
))}
{proposals.relation_types.map((p) => (
@@ -2422,6 +2690,7 @@ function MissesPanel({
{p.reason}
</span>
)}
+ <AgentMeta p={p} />
<Button variant="primary"
size="sm"
className="ml-auto"
@@ -2430,6 +2699,16 @@ function MissesPanel({
>
{S.ontology.approve}
</Button>
+ {p.proposed_by === "agent" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => reject("relation_types", p.key)}
+ disabled={rejectProposal.isPending}
+ >
+ {S.ontology.rejectProposal}
+ </Button>
+ )}
</div>
))}
{(proposals.attribute_types ?? []).map((p) => (
@@ -2453,6 +2732,7 @@ function MissesPanel({
{p.reason}
</span>
)}
+ <AgentMeta p={p} />
<Button variant="primary"
size="sm"
className="ml-auto"
@@ -2461,6 +2741,16 @@ function MissesPanel({
>
{S.ontology.approve}
</Button>
+ {p.proposed_by === "agent" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => reject("attribute_types", p.key)}
+ disabled={rejectProposal.isPending}
+ >
+ {S.ontology.rejectProposal}
+ </Button>
+ )}
</div>
))}
{proposals.entity_types.length === 0 &&