World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A rule may say or, once (#484)
WaylandYangcae429104638
diff --git a/crates/utopia-reason/src/rules.rs b/crates/utopia-reason/src/rules.rsindex f815ec03..e8d66901 100644--- a/crates/utopia-reason/src/rules.rs+++ b/crates/utopia-reason/src/rules.rs@@ -33,6 +33,9 @@ pub enum Op {Lte,Between,In,+ /// 反过来的 In。**它判的仍然是一条存在的事实**,所以照样有前提、有区间;+ /// 「压根没有这个属性」是另一件事,不在这套里(0029 末节)+ NotIn,Present,}@@ -45,6 +48,7 @@ impl Op {Op::Lte => "lte",Op::Between => "between",Op::In => "in",+ Op::NotIn => "not_in",Op::Present => "present",}}@@ -57,6 +61,7 @@ impl Op {"lte" => Op::Lte,"between" => Op::Between,"in" => Op::In,+ "not_in" => Op::NotIn,"present" => Op::Present,_ => return None,})@@ -77,6 +82,8 @@ pub enum Operand {#[derive(Debug, Clone, PartialEq)]pub struct Condition {+ /// 同组的条件用「与」连,组与组之间用「或」连(0029)。老规则全是第 0 组+ pub group: i32,pub predicate: Uuid,pub op: Op,pub operand: Operand,@@ -98,7 +105,8 @@ pub enum Conclusion {pub struct BusinessRule {pub id: Uuid,pub conclusion: Conclusion,- /// 合取:全部满足才算命中。空条件集永不命中——一条没有判据的规则应当+ /// 条件。**组内合取、组间析取**(0029):同一组里全部满足才算这一组成立,+ /// 任何一组成立这条规则就命中。空条件集永不命中——一条没有判据的规则应当/// 什么都不推,而不是把整个类都归进去pub conditions: Vec<Condition>,}@@ -140,6 +148,11 @@ const MAX_COMBOS: usize = 64;/// 求区间交集,交集非空即一次命中。**所以同一条规则可以在同一个实体上产出/// 多段区间**——2023 那次读数命中、2025 那次不命中,得到的是两段各自成立的/// 结论,而不是一行翻来覆去改(0021 决策 4)。+///+/// **组内与、组间或**(0029):上面那一段是一组的算法,整条规则就是把它按组+/// 跑几遍。封顶按组算——一组展不开不该拖累另一组;两组推出同一区间时按区间+/// 去重,留先到的那组当证明(多条证明路径对读的人没有区别,全存下来只会让+/// 证明树跟着路径数长)。pub fn evaluate(rules: &[BusinessRule],facts: &[AttrFact],@@ -161,50 +174,64 @@ pub fn evaluate(if rule.conditions.is_empty() {continue;}+ // 按组切开,组序保持稳定:同一区间被两组同时推出时,留下的是**组序在前**+ // 的那条证明,而不是 HashMap 顺序决定的随机一条+ let groups = group_conditions(&rule.conditions);for (subject, own) in &by_subject {- // 每个条件的命中集。任何一个为空,这条规则在这个实体上就不成立- let mut per_condition: Vec<Vec<Uuid>> = Vec::with_capacity(rule.conditions.len());- let mut satisfiable = true;- for c in &rule.conditions {- let matched: Vec<Uuid> = own- .iter()- .filter(|f| f.predicate == c.predicate && satisfies(c, &f.value))- .map(|f| f.id)- .collect();- if matched.is_empty() {- satisfiable = false;- break;- }- per_condition.push(matched);- }- if !satisfiable {- continue;- }-- let combos: usize = per_condition.iter().map(|v| v.len()).product();- if combos > MAX_COMBOS {- report.capped += 1;- continue;- }-- // 笛卡尔积。同一区间可能由多个组合得出(同一读数报了两遍),- // 按区间去重——它们本来就会落成同一行+ // 同一实体上,一条规则的多个组可能推出同一段区间。去重跨组,+ // 因为它们落成的是同一行派生事实let mut seen: Vec<(Option<i64>, Option<i64>)> = Vec::new();- for combo in cartesian(&per_condition) {- let Some((from, to)) = validity(&combo, spans) else {+ // 这条规则在这个实体上有没有哪一组因组合太多没展开完。**按 (规则, 实体)+ // 记一次**:报出来的是「这里少推了东西」,不是「少推了几组」+ let mut capped_here = false;+ for group in &groups {+ // 每个条件的命中集。任何一个为空,这一组在这个实体上就不成立+ let mut per_condition: Vec<Vec<Uuid>> = Vec::with_capacity(group.len());+ let mut satisfiable = true;+ for c in group {+ let matched: Vec<Uuid> = own+ .iter()+ .filter(|f| f.predicate == c.predicate && satisfies(c, &f.value))+ .map(|f| f.id)+ .collect();+ if matched.is_empty() {+ satisfiable = false;+ break;+ }+ per_condition.push(matched);+ }+ if !satisfiable {continue;- };- if seen.contains(&(from, to)) {+ }++ // 封顶按组算:一组展不开,不该把另一组也拦下+ let combos: usize = per_condition.iter().map(|v| v.len()).product();+ if combos > MAX_COMBOS {+ capped_here = true;continue;}- seen.push((from, to));- hits.push(RuleHit {- rule: rule.id,- subject: *subject,- premises: combo,- from,- to,- });++ // 笛卡尔积。同一区间可能由多个组合得出(同一读数报了两遍),+ // 按区间去重——它们本来就会落成同一行+ for combo in cartesian(&per_condition) {+ let Some((from, to)) = validity(&combo, spans) else {+ continue;+ };+ if seen.contains(&(from, to)) {+ continue;+ }+ seen.push((from, to));+ hits.push(RuleHit {+ rule: rule.id,+ subject: *subject,+ premises: combo,+ from,+ to,+ });+ }+ }+ if capped_here {+ report.capped += 1;}}}@@ -212,6 +239,17 @@ pub fn evaluate((hits, report)}+/// 按 `group` 切成几组,**组序按 group_seq 升序**——两组推出同一区间时,+/// 留下的证明得是稳定的那一条,不能随存储顺序变。+fn group_conditions(conditions: &[Condition]) -> Vec<Vec<&Condition>> {+ let mut keys: Vec<i32> = conditions.iter().map(|c| c.group).collect();+ keys.sort_unstable();+ keys.dedup();+ keys.into_iter()+ .map(|g| conditions.iter().filter(|c| c.group == g).collect())+ .collect()+}+/// 每个条件取一条,穷举组合。调用方已经把上限挡在外面。fn cartesian(sets: &[Vec<Uuid>]) -> Vec<Vec<Uuid>> {let mut out: Vec<Vec<Uuid>> = vec![Vec::new()];@@ -236,6 +274,10 @@ fn cartesian(sets: &[Vec<Uuid>]) -> Vec<Vec<Uuid>> {fn satisfies(c: &Condition, value: &serde_json::Value) -> bool {match (&c.op, &c.operand) {(Op::Present, _) => !value.is_null(),+ // 值不在集合里就算满足;**没有值不算**——那是「没记」,不是「不是它」+ (Op::NotIn, Operand::Set(set)) => {+ !value.is_null() && text(value).is_some_and(|v| !set.iter().any(|s| s == &v))+ }(Op::Gt, Operand::Num(n)) => num(value).is_some_and(|v| v > *n),(Op::Gte, Operand::Num(n)) => num(value).is_some_and(|v| v >= *n),(Op::Lt, Operand::Num(n)) => num(value).is_some_and(|v| v < *n),@@ -296,11 +338,13 @@ mod tests {},conditions: vec![Condition {+ group: 0,predicate: id(10),op: Op::Gt,operand: Operand::Num(8.0),},Condition {+ group: 0,predicate: id(11),op: Op::In,operand: Operand::Set(vec!["气测异常".into(), "气测异常后效".into()]),@@ -331,11 +375,13 @@ mod tests {},conditions: vec![Condition {+ group: 0,predicate: id(10),op: Op::Gt,operand: Operand::Num(8.0),},Condition {+ group: 0,predicate: id(11),op: Op::Present,operand: Operand::None,@@ -357,6 +403,7 @@ mod tests {class: "GasBearingWell".into(),},conditions: vec![Condition {+ group: 0,predicate: id(10),op: Op::Gt,operand: Operand::Num(8.0),@@ -389,11 +436,13 @@ mod tests {},conditions: vec![Condition {+ group: 0,predicate: id(10),op: Op::Gt,operand: Operand::Num(8.0),},Condition {+ group: 0,predicate: id(11),op: Op::In,operand: Operand::Set(vec!["气测异常".into()]),@@ -412,6 +461,160 @@ mod tests {assert!(hits.is_empty(), "两条前提没有同时成立的时段");}+ /// 两组「或」:任一组成立就命中。第二组的前提里**没有**第一组那条读数——+ /// 一条派生事实带的是真正让它成立的那几条,不是这个实体的全部属性+ #[test]+ fn either_group_can_fire_and_carries_only_its_own_premises() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "GasBearingWell".into(),+ },+ conditions: vec![+ // 第 0 组:全烃 > 8 且 解释 ∈ {气测异常}+ Condition {+ group: 0,+ predicate: id(10),+ op: Op::Gt,+ operand: Operand::Num(8.0),+ },+ Condition {+ group: 0,+ predicate: id(11),+ op: Op::In,+ operand: Operand::Set(vec!["气测异常".into()]),+ },+ // 第 1 组:综合解释 ∈ {气层}+ Condition {+ group: 1,+ predicate: id(12),+ op: Op::In,+ operand: Operand::Set(vec!["气层".into()]),+ },+ ],+ };+ // 只有第二组的那条读数+ let facts = vec![fact(3, 50, 12, json!("气层"))];+ let spans = HashMap::from([(id(3), (Some(100), Some(200)))]);+ let (hits, _) = evaluate(&[rule], &facts, &spans);+ assert_eq!(hits.len(), 1, "第二组独自成立");+ assert_eq!(hits[0].premises, vec![id(3)]);+ assert_eq!((hits[0].from, hits[0].to), (Some(100), Some(200)));+ }++ /// 两组同时成立、且推出同一段区间:**一条命中,不是两条**——它们落成的是+ /// 同一行派生事实,留下的证明是组序在前的那一组+ #[test]+ fn two_groups_on_the_same_interval_are_one_hit() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "GasBearingWell".into(),+ },+ conditions: vec![+ Condition {+ group: 0,+ predicate: id(10),+ op: Op::Gt,+ operand: Operand::Num(8.0),+ },+ Condition {+ group: 1,+ predicate: id(11),+ op: Op::In,+ operand: Operand::Set(vec!["气层".into()]),+ },+ ],+ };+ let facts = vec![fact(1, 50, 10, json!(12.3)), fact(2, 50, 11, json!("气层"))];+ // 同一段区间+ let spans = HashMap::from([+ (id(1), (Some(100), Some(200))),+ (id(2), (Some(100), Some(200))),+ ]);+ let (hits, report) = evaluate(&[rule], &facts, &spans);+ assert_eq!(hits.len(), 1);+ assert_eq!(+ hits[0].premises,+ vec![id(1)],+ "留下的是组序在前那一组的证明"+ );+ assert_eq!(report.hits, 1);+ }++ /// 一组展不开不该拖累另一组:**封顶按组算**,而且这个 (规则, 实体) 对+ /// 只报一次「没展完」+ #[test]+ fn a_capped_group_does_not_stop_the_other() {+ let mut facts: Vec<AttrFact> = Vec::new();+ let mut spans = HashMap::new();+ // 第 0 组:同一个属性上 100 条读数,组合数 100 > 64+ for i in 1..=100u8 {+ facts.push(fact(i, 50, 10, json!(12.3)));+ spans.insert(id(i), (Some(100), Some(200)));+ }+ // 第 1 组:一条就够+ facts.push(fact(200, 50, 11, json!("气层")));+ spans.insert(id(200), (Some(100), Some(200)));+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "GasBearingWell".into(),+ },+ conditions: vec![+ Condition {+ group: 0,+ predicate: id(10),+ op: Op::Gt,+ operand: Operand::Num(8.0),+ },+ Condition {+ group: 1,+ predicate: id(11),+ op: Op::In,+ operand: Operand::Set(vec!["气层".into()]),+ },+ ],+ };+ let (hits, report) = evaluate(&[rule], &facts, &spans);+ assert_eq!(hits.len(), 1, "第二组照样出结论");+ assert_eq!(hits[0].premises, vec![id(200)]);+ assert_eq!(report.capped, 1, "(规则, 实体) 只报一次");+ }++ /// `is not one of`:值在集合外算满足;**没有这条读数不算**——那是「没记」,+ /// 不是「不是它」+ #[test]+ fn not_one_of_needs_a_reading_to_be_true() {+ let rule = BusinessRule {+ id: id(90),+ conclusion: Conclusion::Typing {+ class: "NonGas".into(),+ },+ conditions: vec![Condition {+ group: 0,+ predicate: id(11),+ op: Op::NotIn,+ operand: Operand::Set(vec!["气层".into()]),+ }],+ };+ let spans = HashMap::from([(id(1), (None, None))]);+ let (hit, _) = evaluate(+ std::slice::from_ref(&rule),+ &[fact(1, 50, 11, json!("水层"))],+ &spans,+ );+ assert_eq!(hit.len(), 1, "读数在集合外");+ let (miss, _) = evaluate(+ std::slice::from_ref(&rule),+ &[fact(1, 50, 11, json!("气层"))],+ &spans,+ );+ assert!(miss.is_empty(), "读数在集合里");+ let (none, _) = evaluate(&[rule], &[], &HashMap::new());+ assert!(none.is_empty(), "没有这条读数:不成立,而不是「不是它」");+ }+/// 数字被抽成字符串照样比得动。**这一条挡的是最难发现的失效**:/// 规则从不报错,只是永远不命中#[test]@@ -423,6 +626,7 @@ mod tests {value: json!("good"),},conditions: vec![Condition {+ group: 0,predicate: id(10),op: Op::Gte,operand: Operand::Num(12.0),@@ -445,6 +649,7 @@ mod tests {class: "GasBearingWell".into(),},conditions: vec![Condition {+ group: 0,predicate: id(10),op: Op::Gt,operand: Operand::Num(threshold),@@ -477,11 +682,13 @@ mod tests {conclusion: Conclusion::Typing { class: "X".into() },conditions: vec![Condition {+ group: 0,predicate: id(10),op: Op::Present,operand: Operand::None,},Condition {+ group: 0,predicate: id(11),op: Op::Present,operand: Operand::None,diff --git a/crates/utopia-store/src/business_rules.rs b/crates/utopia-store/src/business_rules.rsindex dcbf63e0..295feb56 100644--- a/crates/utopia-store/src/business_rules.rs+++ b/crates/utopia-store/src/business_rules.rs@@ -68,9 +68,10 @@ type RuleRow = (i32,);-/// 条件查询回来的一行:规则、属性谓词及其标签、比较方式、操作数+/// 条件查询回来的一行:规则、组号、属性谓词及其标签、比较方式、操作数type ConditionRow = (Uuid,+ i32,Uuid,Option<String>,String,@@ -80,6 +81,10 @@ type ConditionRow = (/// 一条条件,界面与 API 共用的形状。#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct ConditionInput {+ /// 组号:同组「与」,组间「或」(0029)。**缺省 0**——不带组的调用方+ /// 送来的就是一组合取,与从前一模一样+ #[serde(default)]+ pub group: i32,pub predicate_id: Uuid,pub op: String,#[serde(default)]@@ -285,11 +290,11 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Value}let ids: Vec<Uuid> = rules.iter().map(|r| r.0).collect();let conds: Vec<ConditionRow> = sqlx::query_as(- "SELECT c.rule_id, c.predicate_id, p.label, c.op, c.operand+ "SELECT c.rule_id, c.group_seq, c.predicate_id, p.label, c.op, c.operandFROM attribute_rule_conditions cJOIN relation_types p ON p.id = c.predicate_idWHERE c.rule_id = ANY($1)- ORDER BY c.rule_id, c.seq",+ ORDER BY c.rule_id, c.group_seq, c.seq",).bind(&ids).fetch_all(pool)@@ -317,8 +322,9 @@ pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<serde_json::Valuelet conditions: Vec<serde_json::Value> = conds.iter().filter(|c| c.0 == id)- .map(|(_, pid, plabel, op, operand)| {+ .map(|(_, group, pid, plabel, op, operand)| {json!({+ "group": group,"predicate_id": pid,"predicate_label": plabel,"op": op,@@ -436,19 +442,25 @@ async fn insert_conditions(rule_id: Uuid,conditions: &[ConditionInput],) -> AppResult<()> {- for (seq, c) in conditions.iter().enumerate() {+ // seq 在**组内**编号:(rule, group, seq) 才是一条条件的位置,两组各自从 0 起+ let mut next: std::collections::HashMap<i32, i32> = std::collections::HashMap::new();+ for c in conditions {+ let seq = next.entry(c.group).or_insert(0);sqlx::query(- "INSERT INTO attribute_rule_conditions (id, rule_id, seq, predicate_id, op, operand)- VALUES ($1, $2, $3, $4, $5, $6)",+ "INSERT INTO attribute_rule_conditions+ (id, rule_id, group_seq, seq, predicate_id, op, operand)+ VALUES ($1, $2, $3, $4, $5, $6, $7)",).bind(Uuid::now_v7()).bind(rule_id)- .bind(seq as i32)+ .bind(c.group)+ .bind(*seq).bind(c.predicate_id).bind(&c.op).bind(&c.operand).execute(&mut **tx).await?;+ *seq += 1;}Ok(())}@@ -506,12 +518,17 @@ async fn validate_conditions(let op = utopia_reason::rules::Op::parse(&c.op).ok_or_else(|| {AppError::invalid("bad_op",- "A condition compares with >, >=, <, <=, a range, a set, or presence.",+ "A condition compares with >, >=, <, <=, a range, a set (in or not in), or presence.",)})?;attribute_predicate(pool, kb_id, c.predicate_id).await?;let shaped = match op {utopia_reason::rules::Op::Present => c.operand.is_none(),+ utopia_reason::rules::Op::NotIn => c+ .operand+ .as_ref()+ .and_then(|v| v.as_array())+ .is_some_and(|a| !a.is_empty()),utopia_reason::rules::Op::Between => c.operand.as_ref()diff --git a/crates/utopia-store/src/reasoning.rs b/crates/utopia-store/src/reasoning.rsindex b30309cc..2ba7d2ee 100644--- a/crates/utopia-store/src/reasoning.rs+++ b/crates/utopia-store/src/reasoning.rs@@ -1182,18 +1182,19 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<LoadedRule.await?;let ids: Vec<Uuid> = rows.iter().map(|r| r.0).collect();- let conds: Vec<(Uuid, Uuid, String, Option<serde_json::Value>)> = sqlx::query_as(- "SELECT rule_id, predicate_id, op, operand+ // 组序在前:两组推出同一区间时,留下的证明得是稳定的那一条(0029)+ let conds: Vec<(Uuid, i32, Uuid, String, Option<serde_json::Value>)> = sqlx::query_as(+ "SELECT rule_id, group_seq, predicate_id, op, operandFROM attribute_rule_conditionsWHERE rule_id = ANY($1)- ORDER BY rule_id, seq",+ ORDER BY rule_id, group_seq, seq",).bind(&ids).fetch_all(pool).await?;let mut by_rule: HashMap<Uuid, Vec<Condition>> = HashMap::new();let mut broken: HashSet<Uuid> = HashSet::new();- for (rule_id, predicate, op, operand) in conds {+ for (rule_id, group, predicate, op, operand) in conds {let Some(op) = Op::parse(&op) else {broken.insert(rule_id);continue;@@ -1203,6 +1204,7 @@ async fn attribute_rules(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<LoadedRulecontinue;};by_rule.entry(rule_id).or_default().push(Condition {+ group,predicate,op,operand,diff --git a/crates/utopia-store/tests/a_rule_concludes_a_type.rs b/crates/utopia-store/tests/a_rule_concludes_a_type.rsindex 12c60809..dc92ed59 100644--- a/crates/utopia-store/tests/a_rule_concludes_a_type.rs+++ b/crates/utopia-store/tests/a_rule_concludes_a_type.rs@@ -251,6 +251,83 @@ async fn a_rule_types_a_well_and_says_which_readings_did_it() -> anyhow::Result<run}+/// 两组「或」(0029 / #476):第二组独自成立时,落下的结论只挂**它自己那条**读数。+///+/// 钉的是纯逻辑那层看不见的一件事:前提链进 `fact_derivations` 的是这一组的+/// 前提,不是这条规则全部条件碰过的事实——「凭哪条读数」在库里也得是真的。+#[tokio::test]+async fn either_group_concludes_and_names_only_its_own_reading() -> anyhow::Result<()> {+ let Some(url) = utopia_store::test_db::url() else {+ return Ok(());+ };+ let pool = PgPool::connect(&url).await?;+ let f = seed(&pool).await?;++ let run = async {+ // 只有一条全烃读数,没有解释结论:第 0 组(全烃 > 8 且 解释 ∈ {…})+ // 不成立,第 1 组(全烃 > 20)成立+ let a = attr(+ &pool,+ &f,+ f.thc,+ serde_json::json!(25.0),+ "2023-06-01T00:00:00Z",+ )+ .await?;+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO attribute_rules (id, kb_id, name, subject_type_id, conclusion, conclude_type_id)+ VALUES ($1, $2, 'gas-bearing (two ways)', $3, 'typing', $4)",+ )+ .bind(id)+ .bind(f.kb)+ .bind(f.well)+ .bind(f.gas_bearing)+ .execute(&pool)+ .await?;+ sqlx::query(+ "INSERT INTO attribute_rule_conditions+ (id, rule_id, group_seq, seq, predicate_id, op, operand)+ VALUES ($1, $2, 0, 0, $3, 'gt', $4),+ ($5, $2, 0, 1, $6, 'in', $7),+ ($8, $2, 1, 0, $3, 'gt', $9)",+ )+ .bind(Uuid::now_v7())+ .bind(id)+ .bind(f.thc)+ .bind(serde_json::json!(8.0))+ .bind(Uuid::now_v7())+ .bind(f.category)+ .bind(serde_json::json!(["气测异常"]))+ .bind(Uuid::now_v7())+ .bind(serde_json::json!(20.0))+ .execute(&pool)+ .await?;++ let report = utopia_store::reasoning::materialize(&pool, f.kb).await?;+ assert_eq!(report.rule_hits, 1, "第二组独自成立,一次命中");++ let rows = derived(&pool, &f).await?;+ assert_eq!(rows.len(), 1);+ let premises: Vec<(Uuid,)> = sqlx::query_as(+ "SELECT premise_fact_id FROM fact_derivations WHERE derived_fact_id = $1",+ )+ .bind(rows[0].id)+ .fetch_all(&pool)+ .await?;+ let got: Vec<Uuid> = premises.into_iter().map(|(x,)| x).collect();+ assert_eq!(got, vec![a], "前提只有这一组用到的那条读数");+ Ok::<_, anyhow::Error>(())+ }+ .await;++ sqlx::query("DELETE FROM organizations WHERE id = $1")+ .bind(f.org)+ .execute(&pool)+ .await?;+ run+}+/// 阈值抬到读数之上再跑:结论**作废而不是删除**——记录轴上留着「我们曾据此推出」#[tokio::test]async fn raising_the_threshold_invalidates_without_deleting() -> anyhow::Result<()> {diff --git a/docs/decisions/0029-a-rule-may-say-or-once.md b/docs/decisions/0029-a-rule-may-say-or-once.mdnew file mode 100644index 00000000..684ef6d8--- /dev/null+++ b/docs/decisions/0029-a-rule-may-say-or-once.md@@ -0,0 +1,47 @@+# 0029 · A rule may say "or", once++- **Status**: implemented · `group_seq` on `attribute_rule_conditions` (migration `0039`, existing conditions default to group 0 so every rule keeps its meaning), the evaluator runs group by group with the combination cap per group and one dedupe by interval across groups, `not_in` beside `in` · the API carries `group` on a condition and defaults it to 0, so a caller that sends a flat list still sends one conjunction · the rule editor writes blocks and the table reads the sentence back with its "or" in it+- **Written**: 2026-09-08 (conventions in the [README](README.md))+- **Related**: [0021](0021-a-rule-reads-attributes-and-concludes-a-type.md) built the rule and made its conditions a conjunction; this record widens that shape by exactly one level and says why not further. [0002](0002-reasoning-engine.md) ruled out a user-defined rule language, which is the boundary this record stays inside. From #476.++> A criterion is rarely one pattern. A gas-bearing well is one whose total hydrocarbon is above 8 **and** whose interpretation reads as a gas anomaly — **or** one whose composite interpretation already says gas-bearing. Today that is two rules, with two names, concluding the same class, and nothing in the base says they are one criterion. Delete one and the other keeps firing; read the ontology and you cannot tell they belong together.++## The shape: groups, one level++A condition carries a **group**. Conditions in a group are joined with **and**; groups are joined with **or**. `(A and B) or (C)`. There is no nesting below that.++This is not a concession to keep the editor simple. It is the shape the evaluator already has.++A hit does not report "true". It reports **which facts made it true** and the interval on which they all hold — that is what `derived_facts` stores, what `fact_derivations` chains, and what the entity panel shows a person when they ask why. To get there, `evaluate()` collects the facts matching each condition, walks the cartesian product of those sets, and intersects their intervals (`validity()`), capped at 64 combinations because the product grows with re-reported readings. **That computation is a conjunction.** Running it once per group and emitting hits per group keeps every property it has: the premises are the readings of the group that fired, the interval is their intersection, and the conclusion retires when any of them changes.++An arbitrary `and`/`or`/`not` tree would have to answer a question with no good answer: *what are the premises of a disjunction?* Either the fired branch's (which is what groups already give, without the tree) or all of them (which would attach a well's conclusion to readings that had nothing to do with it, and retire the conclusion when an irrelevant reading changes). Depth beyond one level buys expressive power that nobody writing these criteria has asked for, at the cost of the one property this ledger exists to keep.++## Three consequences worth writing down++**The cap is per group.** A group whose combinations blow past 64 is skipped and reported; the other groups still conclude. The report counts a `(rule, entity)` pair once, not once per group — what a person needs to know is "something was not expanded here", and a second number would not change what they do about it.++**Two groups on the same interval are one conclusion.** They land on the same row: same subject, same predicate, same value, same interval. The evaluator dedupes by interval and keeps the premises of the **first group in group order** — so the proof is stable across runs rather than dependent on storage order. It is *a* proof, not the only one. Recording every path would grow the proof tree with the number of ways a criterion can be met, and a reader who asks "why is this well gas-bearing" is served by one true answer.++**Group numbers are not a sequence to maintain.** `(rule, group_seq, seq)` locates a condition; the API takes whatever integers a caller sends and the evaluator sorts them. Deleting the middle group of three does not renumber anything.++## `not in`, and the negation we are not doing++`not_in` joins the ops. It reads a value that **is** there and asks whether it falls outside a set, so it has a premise fact and an interval like any other condition. A reading of "water zone" satisfies "is not one of {gas zone}".++**"This entity has no such attribute at all" is not in this record, and not by oversight.** Two reasons, either one sufficient:++- It has no premise. Every derived fact in this system points at the readings that made it true and retires when they change. A conclusion drawn from *absence* points at nothing, so nothing can retire it — it would sit there until someone re-ran the job and noticed the absence had ended.+- The base is open-world. A missing reading means nobody wrote it down, not that the value is false. Extraction lags documents, documents lag the world, and a rule that concludes from silence concludes from the lag.++If it is ever wanted, it needs its own record answering what makes it true, what its premise is, and when it retires.++## What the page shows++The editor is blocks: rows inside a block joined by `and` written at the head of the row, blocks divided by a rule and the word `or`, one button per block to add a row and one at the bottom to add a block. A block is not drawn as a box — the connectives already say how far it reaches, and a border around a run of form fields is a panel spent on nothing (DESIGN.md 6). Deleting the last row of a block takes the block with it, which is why no block is ever empty except the first one before anything is written; an empty conjunction is true of everything, and there is no state in which one can be saved.++The rule reads as one sentence in the table — `A and B or C` — because it is one criterion however many ways it can be met. The schema diagram draws a rule as a single edge from the subject class to the concluded class, and that does not change: `or` is inside the criterion, not a second edge.++## Open++- **Chaining is a separate question** (#477): a rule still cannot read what another rule concluded, and this record does not change that. The two are independent — this one is the shape of one rule, that one is how rules feed each other.+- **Set membership is still literal.** `in` and `not_in` compare strings exactly, so the same category in another language does not match. 0021 left this open and it stays open.diff --git a/docs/decisions/README.md b/docs/decisions/README.mdindex 354ec88c..6c680777 100644--- a/docs/decisions/README.md+++ b/docs/decisions/README.md@@ -52,6 +52,7 @@ The test for writing one: if someone (including us) looks at a piece of code in| 0026 | [A decision records why](0026-a-decision-records-why.md) | Implemented · `resolution_reviews.rationale` and `why` on the ledger event from every human decide path, precedents quote it into the prompt and the `ledger_search` tool, the batch adjudicator reads precedents and keys its cache on them, one confident pair in ten goes to a person anyway (`escalate_sample`), the model's own why is kept beside machine decisions · the impact gate (#357) and the investigating adjudicator (#358) follow || 0027 | [An automatic merge is gated by what it can undo](0027-an-automatic-merge-is-gated-by-what-it-can-undo.md) | Implemented · `execution_gate` in the store, asked by the batch adjudicator and the governor before an automatic merge: a contradiction the consistency check would open, a derivation resting on either side, or an answer that named either side holds the pair for a person as `escalate_impact` whatever the confidence · keeps are not gated · exports and a per-deployment opt-in stay open || 0028 | [The adjudicator looks before it asks](0028-the-adjudicator-looks-before-it-asks.md) | Implemented · `consequences` joins the second look's tools (what a merge would touch, from 0027's gate, and whether the types share a family) · with governance off the batch adjudicator sends its unsettled pairs through the same loop under the same budget, each look a row in `agent_decisions` · the number that justifies or retires it comes from 0026's sample split by `via` |+| 0029 | [A rule may say "or", once](0029-a-rule-may-say-or-once.md) | Implemented · a `group_seq` on a rule's conditions (migration `0039`): same group joins with **and**, groups join with **or**, one level and no nesting — because a hit carries the readings that made it true and a disjunction has no premises of its own · the combination cap is per group, two groups on one interval are one conclusion with the first group's proof, `not_in` joins the ops · "no such attribute at all" is deliberately not here (no premise, and a missing reading means nobody wrote it down) · the editor writes blocks and the table reads the sentence back with its "or" in it || 0031 | [An event holds at the moment it names](0031-an-event-holds-at-the-moment-it-names.md) | Implemented (#486) · `Validity::under` normalises every write by the predicate's `temporal` (an event is one moment written at both ends, an eternal fact has no dates), `world_axis` and `read_span` read an event as the bucket it names and an undated event at no moment, an eternal fact at every moment · the prompt marks `[event]` / `[eternal]` and says what to write · no schema change, old rows read correctly · the panel's point rendering and the ontology hint are the UI cut |## Not a decision recorddiff --git a/migrations/0039_a_rule_can_say_or.sql b/migrations/0039_a_rule_can_say_or.sqlnew file mode 100644index 00000000..8410da1b--- /dev/null+++ b/migrations/0039_a_rule_can_say_or.sql@@ -0,0 +1,36 @@+-- 0039 · 一条规则可以说「或」(#476,决定记录 0029)+--+-- 编号让开 0038:另一条分支已经占了那个号(「a decision records why」),+-- 而共享的开发库里它已经落过库了。+--+-- 从前一条规则的条件是一串合取:全都成立才算数。真实的判据常常是+-- 「这样,或者那样」——今天只能写成两条同名规则推出同一个类,而本体里+-- 没有任何地方说得出它们是同一个判据。+--+-- 加一列 `group_seq`:同组的条件用「与」连,组与组之间用「或」连。+-- 一层,不做任意嵌套——**因为求值器的形状就是一组「与」**:一条命中带着+-- 让它成立的那些前提读数与它们交出来的区间(`derived_facts` / `validity()`),+-- 而「一个析取的前提是哪几条」没有好答案。一组「与」跑一遍今天的算法,+-- 每组各出各的命中,前提、区间、前提一没就退休,全部原样保住。+--+-- **老数据全归第 0 组**:默认值就是它,没有数据迁移要判断,既有规则的+-- 语义一个字不变。+ALTER TABLE attribute_rule_conditions+ ADD COLUMN group_seq INT NOT NULL DEFAULT 0;++-- 同一条规则里,(组, 序) 才是一条条件的位置。原来的 (rule_id, seq) 唯一约束+-- 会挡住两组各自从 0 编号+ALTER TABLE attribute_rule_conditions+ DROP CONSTRAINT attribute_rule_conditions_rule_id_seq_key;+ALTER TABLE attribute_rule_conditions+ ADD CONSTRAINT attribute_rule_conditions_rule_group_seq_key+ UNIQUE (rule_id, group_seq, seq);++-- `is not one of`:对一条**存在的**事实做值判断,所以照样有前提、有区间,+-- 与别的条件同构。而「压根没有这个属性」不在这里——缺失没有前提事实可挂+-- 区间,开放世界里「没记」也不等于「没有」(见 0029 末节)+ALTER TABLE attribute_rule_conditions+ DROP CONSTRAINT attribute_rule_conditions_op_check;+ALTER TABLE attribute_rule_conditions+ ADD CONSTRAINT attribute_rule_conditions_op_check+ CHECK (op IN ('gt', 'gte', 'lt', 'lte', 'between', 'in', 'not_in', 'present'));diff --git a/web/src/api.ts b/web/src/api.tsindex ad665720..73b50ab5 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -324,8 +324,10 @@ export interface ChunkFact {* 在界面上看不出区别,而那正是「推理污染知识」的样子。 *//** 一条条件:这个属性、这样比、跟这个值比 */export interface RuleCondition {+ /** 组号:同组「与」,组间「或」(决定记录 0029)。不带 = 第 0 组 */+ group?: number;predicate_id: string;- /** gt | gte | lt | lte | between | in | present */+ /** gt | gte | lt | lte | between | in | not_in | present */op: string;/** 数字 / [lo,hi] / 字符串数组;present 不带 */operand?: unknown;diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex bae391bd..894b6ef0 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1128,6 +1128,8 @@ export const en = {/* 条件之间是合取。**写「并且」而不是一个点号**——符号读不出「全都要成立」,而那正是规则最容易被误读的地方 */ruleAnd: "and",+ /** 组与组之间。**读起来是「或者」而不是符号**——同一条判据的另一种满足方式 */+ ruleOr: "or",ruleWhere: "where",ruleDropCondition: "Remove this condition",ruleOperandPlaceholder: (kind: string): string =>@@ -1144,14 +1146,21 @@ export const en = {ruleConcludes: "Concludes",ruleConcludesTyping: "the class",ruleConcludesAttribute: "the attribute",- ruleConditions: "When all of",+ /* 从前是「当以下全部成立」。**一条规则现在可以写第二种情况**,那句话就+ 不再是真的——标签退回一个「当」,全不全由下面那句说明交代 */+ ruleConditions: "When",+ ruleConditionsHint:+ "The conditions in a block must all hold. Add another way and any one block is enough.",ruleAddCondition: "Add a condition",+ /** 加一整块:同一条判据的另一种满足方式,不是另一条规则 */+ ruleAddGroup: "Another way",ruleOpGt: "is above",ruleOpGte: "is at least",ruleOpLt: "is below",ruleOpLte: "is at most",ruleOpBetween: "is between",ruleOpIn: "is one of",+ ruleOpNotIn: "is not one of",ruleOpPresent: "is recorded",ruleOperandNumber: "12.0",ruleOperandSet: "gas anomaly, post-effect gas anomaly",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex e5012cb7..177451bb 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -1004,6 +1004,7 @@ export const zh: Strings = {ruleColDerived: "推出",ruleColStatus: "状态",ruleAnd: "并且",+ ruleOr: "或者",ruleWhere: "满足",ruleDropCondition: "删掉这个条件",ruleOperandPlaceholder: (kind: string) =>@@ -1016,14 +1017,17 @@ export const zh: Strings = {ruleConcludes: "得出",ruleConcludesTyping: "这个类",ruleConcludesAttribute: "这个属性",- ruleConditions: "当以下全部成立",+ ruleConditions: "当满足",+ ruleConditionsHint: "一块里的条件要同时成立;再加一块就是另一种情况,任意一块成立即可。",ruleAddCondition: "加一个条件",+ ruleAddGroup: "另一种情况",ruleOpGt: "大于",ruleOpGte: "不小于",ruleOpLt: "小于",ruleOpLte: "不大于",ruleOpBetween: "介于",ruleOpIn: "属于",+ ruleOpNotIn: "不属于",ruleOpPresent: "有记录",ruleOperandNumber: "12.0",ruleOperandSet: "气测异常, 气测异常后效",diff --git a/web/src/pages/RulesPanel.tsx b/web/src/pages/RulesPanel.tsxindex 66e7a4ff..e6cd7052 100644--- a/web/src/pages/RulesPanel.tsx+++ b/web/src/pages/RulesPanel.tsx@@ -52,6 +52,7 @@ const OPS: {{ value: "lte", label: () => S.ontology.ruleOpLte, operand: "num" },{ value: "between", label: () => S.ontology.ruleOpBetween, operand: "range" },{ value: "in", label: () => S.ontology.ruleOpIn, operand: "set" },+ { value: "not_in", label: () => S.ontology.ruleOpNotIn, operand: "set" },{ value: "present", label: () => S.ontology.ruleOpPresent, operand: "none" },];@@ -106,6 +107,19 @@ function parseOperand(op: string, text: string): unknown | undefined {return Number.isFinite(n) ? n : undefined;}+/** 条件按组切开,组序升序——与求值器读它的顺序一致(决定记录 0029)。+ 没带组号的当第 0 组:0029 之前写下的规则本来就是一整个合取 */+function byGroup<T extends { group?: number }>(conditions: T[]): T[][] {+ const g = (c: T) => c.group ?? 0;+ return [...new Set(conditions.map(g))]+ .sort((a, b) => a - b)+ .map((n) => conditions.filter((c) => g(c) === n));+}++/** 表单里的一行条件。**文本原样留着**——解析放到保存那一刻,否则打字打到+ 一半的「1」会被当成写完的数 */+type Row = { predicate_id: string; op: string; text: string };+type Draft = {/** 改的是哪一条;新建时为 null。**同一份草稿两种用途**——两套表单会漂移 */id: string | null;@@ -116,7 +130,9 @@ type Draft = {conclude_type_id: string;conclude_predicate_id: string;conclude_value: string;- conditions: { predicate_id: string; op: string; text: string }[];+ /** 一块是一个合取,块之间是析取。**空数组只允许出现在唯一一块上**——+ 那是「还没写条件」,不是「无条件成立」(空合取恒真,会归进整个类) */+ groups: Row[][];};const emptyDraft = (@@ -131,13 +147,18 @@ const emptyDraft = (conclude_type_id: classes[0]?.id ?? "",conclude_predicate_id: attrs[0]?.id ?? "",conclude_value: "",- conditions: attrs[0]- ? [{ predicate_id: attrs[0].id, op: "gt", text: "" }]- : [],+ groups: attrs[0] ? [[{ predicate_id: attrs[0].id, op: "gt", text: "" }]] : [[]],});/** 已有规则 → 草稿。**回读要与写入是同一套形状**,否则编辑一次就变形。 */function draftOf(r: BusinessRule): Draft {+ const groups = byGroup(r.conditions).map((g) =>+ g.map((c) => ({+ predicate_id: c.predicate_id,+ op: c.op,+ text: operandText(c.op, c.operand),+ })),+ );return {id: r.id,name: r.name,@@ -152,11 +173,9 @@ function draftOf(r: BusinessRule): Draft {: r.conclude_value === undefined || r.conclude_value === null? "": String(r.conclude_value),- conditions: r.conditions.map((c) => ({- predicate_id: c.predicate_id,- op: c.op,- text: operandText(c.op, c.operand),- })),+ // 一条条件都没有的规则服务端不收,可草稿要撑得住这一格——空着的那一块+ // 就是「还没写」,界面靠它摆得出「加一个条件」+ groups: groups.length ? groups : [[]],};}@@ -241,14 +260,18 @@ export function RulesPanel({const save = useMutation({mutationFn: async () => {const d = draft!;- if (!d.conditions.length) throw new Error(S.ontology.ruleNeedsCondition);- const conditions: RuleCondition[] = d.conditions.map((c) => {- const operand = parseOperand(c.op, c.text);- if (operandKind(c.op) !== "none" && operand === undefined) {- throw new Error(S.ontology.ruleNeedsCondition);- }- return { predicate_id: c.predicate_id, op: c.op, operand };- });+ // 组号就是块在表单里的位置。**不必维护成一串连号**——服务端收下发来的+ // 整数,求值器自己排序(0029);这里从 0 数起只是因为最省事+ const conditions: RuleCondition[] = d.groups.flatMap((g, gi) =>+ g.map((c) => {+ const operand = parseOperand(c.op, c.text);+ if (operandKind(c.op) !== "none" && operand === undefined) {+ throw new Error(S.ontology.ruleNeedsCondition);+ }+ return { group: gi, predicate_id: c.predicate_id, op: c.op, operand };+ }),+ );+ if (!conditions.length) throw new Error(S.ontology.ruleNeedsCondition);const conclusion = {conclusion: d.conclusion,conclude_type_id:@@ -504,21 +527,25 @@ export function RulesPanel({}/** 规则读成一句话。**这一段就是它的全部语义**,没有别处再藏着条件。- 条件之间是合取——所以中间写的是「并且」,不是一个点号:符号读不出- 「全都要成立」,而这正是规则最容易被误读的地方。 */+ 组内是合取、组间是析取(决定记录 0029),所以中间写的是「并且」与「或者」,+ 不是一个点号:符号读不出「全都要成立」,而那正是规则最容易被误读的地方。 */function RuleSentence({ rule }: { rule: BusinessRule }) {+ const groups = byGroup(rule.conditions);return (<p className="text-small leading-relaxed text-ink-2"><span>{rule.subject_label}</span><span> {S.ontology.ruleWhere} </span>- {rule.conditions.map((c, i) => (- <span key={i}>- {i > 0 && (- <span className="text-ink-2"> {S.ontology.ruleAnd} </span>- )}- <span className="text-ink">{c.predicate_label}</span>{" "}- <span>{OPS.find((o) => o.value === c.op)?.label() ?? c.op}</span>{" "}- <span className="u-num text-ink">{operandText(c.op, c.operand)}</span>+ {groups.map((group, gi) => (+ <span key={gi}>+ {gi > 0 && <span className="text-ink"> {S.ontology.ruleOr} </span>}+ {group.map((c, i) => (+ <span key={i}>+ {i > 0 && <span> {S.ontology.ruleAnd} </span>}+ <span className="text-ink">{c.predicate_label}</span>{" "}+ <span>{OPS.find((o) => o.value === c.op)?.label() ?? c.op}</span>{" "}+ <span className="u-num text-ink">{operandText(c.op, c.operand)}</span>+ </span>+ ))}</span>))}</p>@@ -543,7 +570,35 @@ function RuleDialog({onSave: () => void;}) {const ready =- !!draft.name.trim() && !!draft.subject_type_id && draft.conditions.length > 0;+ !!draft.name.trim() &&+ !!draft.subject_type_id &&+ draft.groups.some((g) => g.length > 0);++ const newRow = (): Row => ({+ predicate_id: attributes[0]?.id ?? "",+ op: "gt",+ text: "",+ });+ const setGroups = (groups: Row[][]) =>+ // 空块只有在它是唯一一块时才算数(「还没写条件」)。别的地方留一个空块+ // 就是留一个恒真的合取,会把整个主类归进结论里+ setDraft({ ...draft, groups: groups.some((g) => g.length) ? groups.filter((g) => g.length) : [[]] });+ const editRow = (gi: number, ri: number, patch: Partial<Row>) =>+ setGroups(+ draft.groups.map((g, j) =>+ j === gi ? g.map((r, k) => (k === ri ? { ...r, ...patch } : r)) : g,+ ),+ );+ const dropRow = (gi: number, ri: number) =>+ setGroups(+ draft.groups.map((g, j) => (j === gi ? g.filter((_, k) => k !== ri) : g)),+ );+ const addRow = (gi: number) =>+ setGroups(draft.groups.map((g, j) => (j === gi ? [...g, newRow()] : g)));+ // 新的一块自带一行:空块在别处没有意义,让它一出生就不是空的,+ // 比事后拦一次「这块还空着」少一条规则+ const addGroup = () => setGroups([...draft.groups, [newRow()]]);+return (<Dialogopen@@ -605,93 +660,92 @@ function RuleDialog({/></Field>- <Field label={S.ontology.ruleConditions} className="mb-0">+ {/* 条件是一块一块写的:块里的行同时成立,块与块任一成立即可(0029)。+ **块不画框**——行首的「并且」和块间那条「或者」已经把范围说清楚了,+ 再套一圈边框就是给表单里的一段字段发面板(DESIGN.md 6) */}+ <Field+ label={S.ontology.ruleConditions}+ hint={S.ontology.ruleConditionsHint}+ className="mb-0"+ ><div className="space-y-2">- {draft.conditions.map((c, i) => (- <div key={i} className="flex items-center gap-2">- {/* 合取写在行首而不是行尾:读的人先知道「还要同时成立」,- 再读这一行说了什么 */}- <span className="w-10 shrink-0 text-right text-fine text-ink-2">- {i === 0 ? "" : S.ontology.ruleAnd}- </span>- <Dropdown- className="flex-1"- value={c.predicate_id}- onChange={(v) =>- setDraft({- ...draft,- conditions: draft.conditions.map((x, j) =>- j === i ? { ...x, predicate_id: v } : x,- ),- })- }- options={attributes.map((a) => ({ value: a.id, label: a.label }))}- />- <Dropdown- className="w-32"- value={c.op}- onChange={(v) =>- setDraft({- ...draft,- conditions: draft.conditions.map((x, j) =>- j === i ? { ...x, op: v, text: "" } : x,- ),- })- }- options={OPS.map((o) => ({ value: o.value, label: o.label() }))}- />- {operandKind(c.op) !== "none" && (- <Input- className="w-40"- placeholder={S.ontology.ruleOperandPlaceholder(operandKind(c.op))}- value={c.text}- onChange={(e) =>- setDraft({- ...draft,- conditions: draft.conditions.map((x, j) =>- j === i ? { ...x, text: e.target.value } : x,- ),- })- }- />+ {draft.groups.map((group, gi) => (+ <div key={gi} className="space-y-2">+ {/* 析取不写成又一个行首连词:跟「并且」长得一样的话,谁先谁后+ 就读不出来了。一条线把两块分开,词落在同一条竖列上 */}+ {gi > 0 && (+ <div className="flex items-center gap-2 pt-1">+ <span className="w-10 shrink-0 text-right text-fine text-ink">+ {S.ontology.ruleOr}+ </span>+ <span className="h-px flex-1 bg-line-strong" />+ </div>+ )}+ {group.map((c, i) => (+ <div key={i} className="flex items-center gap-2">+ {/* 合取写在行首而不是行尾:读的人先知道「还要同时成立」,+ 再读这一行说了什么 */}+ <span className="w-10 shrink-0 text-right text-fine text-ink-2">+ {i === 0 ? "" : S.ontology.ruleAnd}+ </span>+ <Dropdown+ className="flex-1"+ value={c.predicate_id}+ onChange={(v) => editRow(gi, i, { predicate_id: v })}+ options={attributes.map((a) => ({ value: a.id, label: a.label }))}+ />+ <Dropdown+ className="w-32"+ value={c.op}+ onChange={(v) => editRow(gi, i, { op: v, text: "" })}+ options={OPS.map((o) => ({ value: o.value, label: o.label() }))}+ />+ {operandKind(c.op) !== "none" && (+ <Input+ className="w-40"+ placeholder={S.ontology.ruleOperandPlaceholder(operandKind(c.op))}+ value={c.text}+ onChange={(e) => editRow(gi, i, { text: e.target.value })}+ />+ )}+ <IconButton+ label={S.ontology.ruleDropCondition}+ size="sm"+ onClick={() => dropRow(gi, i)}+ >+ <Trash2 size={11} />+ </IconButton>+ </div>+ ))}+ {/* 加行的按钮一块一个:有两块的时候,「加到哪一块」只有它答得出 */}+ {attributes.length > 0 && (+ <div className="flex items-center gap-2">+ <span className="w-10 shrink-0" />+ <Button size="sm" variant="ghost" onClick={() => addRow(gi)}>+ <Plus size={11} />+ {S.ontology.ruleAddCondition}+ </Button>+ </div>)}- <IconButton- label={S.ontology.ruleDropCondition}- size="sm"- onClick={() =>- setDraft({- ...draft,- conditions: draft.conditions.filter((_, j) => j !== i),- })- }- >- <Trash2 size={11} />- </IconButton></div>))}{/* 一个条件判的是属性的值。没有属性时,「加一个条件」只会加出一行选不了东西的空条件——所以这里说清缺的是什么,按钮不摆 */}- {attributes.length === 0 ? (+ {attributes.length === 0 && (<p className="text-small text-ink-2">{S.ontology.ruleNeedsAttribute}</p>- ) : (- <Button- size="sm"- variant="ghost"- onClick={() =>- setDraft({- ...draft,- conditions: [- ...draft.conditions,- { predicate_id: attributes[0].id, op: "gt", text: "" },- ],- })- }- >- <Plus size={11} />- {S.ontology.ruleAddCondition}- </Button>+ )}+ {/* 加一整块。**不跟行缩进对齐**——缩进进去就跟上一块的「加一个条件」+ 成了并排的两个按钮,一个加行一个加块,看不出管的不是一件事。+ 第一个条件都没写时不摆:没有第一种情况,「另一种情况」无从谈起 */}+ {draft.groups.some((g) => g.length > 0) && (+ <div className="pt-2">+ <Button size="sm" variant="ghost" onClick={addGroup}>+ <Plus size={11} />+ {S.ontology.ruleAddGroup}+ </Button>+ </div>)}</div></Field>