Skip to content

World's first open-source enterprise world model.

Preserve computed definitions when editing rule metadata (#829)

Maya Kid8d70aebe00e8
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 38fe98d5..cd947a02 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -610,3 +610,6 @@ async fn jobs_noop(
let id = utopia_store::jobs::enqueue(&state.pool, "noop", json!({})).await?;
Ok(Json(json!({ "job_id": id })))
}
+
+#[cfg(test)]
+mod rule_metadata_tests;
diff --git a/crates/utopia-server/src/api/rule_metadata_tests.rs b/crates/utopia-server/src/api/rule_metadata_tests.rs
new file mode 100644
index 00000000..06958428
--- /dev/null
+++ b/crates/utopia-server/src/api/rule_metadata_tests.rs
@@ -0,0 +1,97 @@
+//! The metadata-only form must not replace any part of a computed definition.
+use crate::state::AppState;
+use axum::{
+ body::Body,
+ http::{Request, StatusCode},
+};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use tower::ServiceExt;
+use uuid::Uuid;
+
+#[tokio::test]
+async fn metadata_patch_preserves_computed_definition_through_authenticated_routes(
+) -> anyhow::Result<()> {
+ let Some(url) = utopia_store::test_db::url() else {
+ return Ok(());
+ };
+ let pool = sqlx::PgPool::connect(&url).await?;
+ utopia_store::db::migrate(&pool).await?;
+ let (org, ws, kb, user, class, input, output) = (
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ Uuid::now_v7(),
+ );
+ let dir = tempfile::tempdir()?;
+ let cfg = utopia_core::config::AppConfig {
+ data_dir: dir.path().to_string_lossy().into_owned(),
+ ..Default::default()
+ };
+ let state = AppState::new(
+ pool.clone(),
+ &cfg,
+ Arc::new(utopia_search::SearchIndex::open(
+ &dir.path().join("search"),
+ )?),
+ "test-only".into(),
+ );
+ let result = async {
+ sqlx::raw_sql(&format!("INSERT INTO organizations(id,name) VALUES('{org}','metadata-test');
+ INSERT INTO workspaces(id,org_id,name) VALUES('{ws}','{org}','metadata-test');
+ INSERT INTO knowledge_bases(id,workspace_id,name) VALUES('{kb}','{ws}','metadata-test');
+ INSERT INTO users(id,org_id,email,password_hash,display_name) VALUES('{user}','{org}','{user}@example.test','unused','Test');
+ INSERT INTO kb_members(kb_id,user_id,role) VALUES('{kb}','{user}','editor');
+ INSERT INTO entity_types(id,kb_id,key,label) VALUES('{class}','{kb}','thing','Thing');
+ INSERT INTO relation_types(id,kb_id,key,label,kind,datatype) VALUES('{input}','{kb}','input','Input','attribute','number'),('{output}','{kb}','output','Output','attribute','number');"))
+ .execute(&pool).await?;
+ let token = crate::auth::issue_token(&state, user)?;
+ let call = |method: &'static str, path: String, body: Value| {
+ let state = state.clone(); let token = token.clone();
+ async move {
+ let request = Request::builder().method(method).uri(path).header("authorization", format!("Bearer {token}"))
+ .header("content-type","application/json").body(Body::from(body.to_string()))?;
+ let response = super::router(state, &Default::default()).oneshot(request).await?;
+ let status = response.status();
+ let body = axum::body::to_bytes(response.into_body(), 65536).await?;
+ anyhow::Ok((status, serde_json::from_slice::<Value>(&body)?))
+ }
+ };
+ let base = format!("/api/v1/kbs/{kb}/rules");
+ let expr = json!({"op":"div","l":{"op":"sub","l":{"attr":input},"r":{"const":2}},"r":{"attr":input}});
+ let definition = json!({"name":"Original", "subject_type_id":class, "conclusion":"computed", "conclude_predicate_id":output,"conclude_expr":expr,"conditions":[{"predicate_id":input,"op":"gt","operand":3,"group":2},{"predicate_id":input,"op":"lt","operand":-1,"group":7}]});
+ let (status, created) = call("POST",base.clone(),definition.clone()).await?;
+ anyhow::ensure!(status.is_success(), "create: {status} {created}");
+ let id = created["id"].as_str().unwrap();
+ let (_, before) = call("GET",base.clone(),json!(null)).await?;
+ let snapshot = |value: &Value| { let r=&value["rules"][0]; json!({"expr":r["conclude_expr"],"conditions":r["conditions"],"conclusion":r["conclusion"],"predicate":r["conclude_predicate_id"],"subject":r["subject_type_id"]}) };
+ let path = format!("{base}/{id}");
+ // The previous form sent the entire conclusion without its expression.
+ let mut old_editor = definition;
+ old_editor.as_object_mut().unwrap().remove("conclude_expr");
+ let (old_status, old_error) = call("PATCH", path.clone(), old_editor).await?;
+ anyhow::ensure!(old_status == StatusCode::UNPROCESSABLE_ENTITY);
+ anyhow::ensure!(old_error["code"] == "no_expression");
+
+ let (status, _) = call("PATCH", path.clone(), json!({"name":"Renamed","description":"Only metadata"})).await?;
+ anyhow::ensure!(status == StatusCode::OK);
+ let (_, after) = call("GET",base.clone(),json!(null)).await?;
+ anyhow::ensure!(snapshot(&before) == snapshot(&after));
+ anyhow::ensure!(after["rules"][0]["name"] == "Renamed");
+ // Rejecting a name or permission never writes a partial definition.
+ anyhow::ensure!(call("PATCH",path.clone(),json!({"name":" "})).await?.0 == StatusCode::UNPROCESSABLE_ENTITY);
+ sqlx::query("UPDATE kb_members SET role='viewer' WHERE user_id=$1").bind(user).execute(&pool).await?;
+ anyhow::ensure!(call("PATCH",path,json!({"name":"Forbidden"})).await?.0 == StatusCode::FORBIDDEN);
+ let (_, unchanged) = call("GET",base,json!(null)).await?;
+ anyhow::ensure!(unchanged == after);
+ anyhow::Ok(())
+ }.await;
+ sqlx::query("DELETE FROM organizations WHERE id=$1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ result
+}
diff --git a/web/src/api.ts b/web/src/api.ts
index 6d63cc32..d1d5c92c 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -382,7 +382,10 @@ export interface RuleMatch {
premises: string[];
}
-export interface BusinessRule extends RuleInput {
+export interface BusinessRule extends Omit<RuleInput, "conclusion"> {
+ conclusion: "typing" | "attribute" | "computed";
+ /** Raw server tree; unsupported nodes must remain read-only. */
+ conclude_expr?: unknown;
id: string;
enabled: boolean;
subject_label: string;
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 9dd22dbb..a84edb05 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1222,6 +1222,8 @@ export const en = {
refineShort: "Refine types",
/* ---- 业务规则(0021 / #277)---- */
rulesShort: "Business rules",
+ ruleExpressionReadOnly: "This definition is read-only in this form. You can edit its name and description without changing its expressions or conditions.",
+ ruleUnknownExpression: "Unsupported expression (read-only)",
rulesTitle: "Business rules",
/* 说清三件事:谁写的、结论是什么身份、什么时候重算。第三件最容易被误解成
「保存就生效」,而它其实等下一轮物化 */
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 50678b9a..67593ffb 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -1098,6 +1098,8 @@ export const zh: Strings = {
uniquenessShort: "并存",
refineShort: "类型消解",
rulesShort: "业务规则",
+ ruleExpressionReadOnly: "此表单只读展示这条规则的定义。可修改名称和说明,表达式和条件保持原样。",
+ ruleUnknownExpression: "暂不支持的表达式(只读)",
rulesTitle: "业务规则",
rulesHint: "按实体自己的属性判定类别、或算出取值的规则。结论是派生的,依据没了就自动失效。",
rulesEmpty: "还没有规则。",
diff --git a/web/src/pages/RulesPanel.tsx b/web/src/pages/RulesPanel.tsx
index e0139274..f04245ae 100644
--- a/web/src/pages/RulesPanel.tsx
+++ b/web/src/pages/RulesPanel.tsx
@@ -8,7 +8,7 @@
*
* 样式按 web/DESIGN.md 那五条:字号五档、间距六档、颜色只用 token、控件与状态
* 一律从 ui/ 来。 */
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Pencil, Play, Plus, Search, Trash2 } from "lucide-react";
import {
@@ -39,6 +39,7 @@ import {
Tr,
} from "../ui";
import { toast } from "../toast";
+import { expressionText, metadataOnly, metadataPatch } from "./ruleExpressions";
/** op → 那句话里的动词。**数字与集合两类分开**,因为它们的操作数长得不一样 */
const OPS: {
@@ -61,15 +62,16 @@ const operandKind = (op: string) =>
/** 一条规则可以被搜到的全部文本。**判据也算**——「哪条规则用到了 Clearance」
是找规则最常见的问法,只搜名字的话得先记住自己当初叫它什么 */
-function searchText(r: BusinessRule): string {
+function searchText(r: BusinessRule, attributes: RelationTypeView[]): string {
return [
r.name,
r.description ?? "",
r.subject_label,
r.conclude_type_label ?? "",
r.conclude_predicate_label ?? "",
+ r.conclusion === "computed" ? expressionText(r.conclude_expr, attributes, S.ontology.ruleUnknownExpression) : "",
...r.conditions.map(
- (c) => `${c.predicate_label} ${operandText(c.op, c.operand)}`,
+ (c) => `${c.predicate_label} ${operandText(c.op, c.operand, attributes)}`,
),
]
.join(" ")
@@ -77,7 +79,10 @@ function searchText(r: BusinessRule): string {
}
/** 条件的操作数 → 输入框里的文本。回读要与写入是同一套,否则编辑一次就变形 */
-function operandText(op: string, operand: unknown): string {
+function operandText(op: string, operand: unknown, attributes: RelationTypeView[] = []): string {
+ if (operand && typeof operand === "object" && !Array.isArray(operand)) {
+ return expressionText(operand, attributes, S.ontology.ruleUnknownExpression);
+ }
const kind = operandKind(op);
if (kind === "none") return "";
if (kind === "set") return Array.isArray(operand) ? operand.join(", ") : "";
@@ -152,6 +157,7 @@ const emptyDraft = (
/** 已有规则 → 草稿。**回读要与写入是同一套形状**,否则编辑一次就变形。 */
function draftOf(r: BusinessRule): Draft {
+ if (metadataOnly(r)) throw new Error(S.ontology.ruleExpressionReadOnly);
const groups = byGroup(r.conditions).map((g) =>
g.map((c) => ({
predicate_id: c.predicate_id,
@@ -164,7 +170,7 @@ function draftOf(r: BusinessRule): Draft {
name: r.name,
description: r.description ?? "",
subject_type_id: r.subject_type_id,
- conclusion: r.conclusion,
+ conclusion: r.conclusion as Draft["conclusion"],
conclude_type_id: r.conclude_type_id ?? "",
conclude_predicate_id: r.conclude_predicate_id ?? "",
conclude_value:
@@ -245,6 +251,8 @@ export function RulesPanel({
queryFn: () => api.rules(kbId),
});
const [draft, setDraft] = useState<Draft | null>(null);
+ const [metadataRule, setMetadataRule] = useState<BusinessRule | null>(null);
+ useEffect(() => { setDraft(null); setMetadataRule(null); }, [kbId]);
/** 待确认删除的那一条。删规则会带走它推出的全部结论,值得停一下 */
const [doomed, setDoomed] = useState<BusinessRule | null>(null);
/** 展开了哪条规则的命中列表。一次只展开一条——两份长列表并排读不了 */
@@ -338,7 +346,7 @@ export function RulesPanel({
const all = rules.data?.rules ?? [];
const needle = filter.trim().toLowerCase();
const list = needle
- ? all.filter((r) => searchText(r).includes(needle))
+ ? all.filter((r) => searchText(r, attributes).includes(needle))
: all;
/** 命中列表看的是哪一条。一次一条——两份长列表并排读不了 */
const opening = list.find((r) => r.id === opened) ?? null;
@@ -436,15 +444,13 @@ export function RulesPanel({
)}
</Td>
<Td>
- <RuleCriterion rule={r} />
+ <RuleCriterion rule={r} attributes={attributes} />
</Td>
{/* **主类跟结论写在一起**:一条规则说的是「这样的 Person 是个
Veteran」,主类是这句话的左半边,不是判据的一部分 */}
- <Td className="whitespace-nowrap text-small text-ink">
+ <Td className="max-w-96 break-words text-small text-ink">
<span className="text-ink-2">{r.subject_label} → </span>
- {r.conclusion === "typing"
- ? r.conclude_type_label
- : `${r.conclude_predicate_label} = ${JSON.stringify(r.conclude_value)}`}
+ <RuleConclusion rule={r} attributes={attributes} />
</Td>
<Td className="whitespace-nowrap">
{/* 此刻凭它成立的结论条数。**点得动**——二十个实体还能一个个
@@ -487,7 +493,7 @@ export function RulesPanel({
<IconButton
label={S.ontology.ruleEdit}
size="sm"
- onClick={() => setDraft(draftOf(r))}
+ onClick={() => metadataOnly(r) ? setMetadataRule(r) : setDraft(draftOf(r))}
>
<Pencil size={12} />
</IconButton>
@@ -518,6 +524,10 @@ export function RulesPanel({
{opening && <Matches kbId={kbId} ruleId={opening.id} />}
</Dialog>
+ {metadataRule && (
+ <RuleMetadataDialog key={`${kbId}/${metadataRule.id}`} kbId={kbId} rule={metadataRule}
+ attributes={attributes} onClose={() => setMetadataRule(null)} onSaved={invalidate} />
+ )}
{draft && (
<RuleDialog
draft={draft}
@@ -540,7 +550,7 @@ export function RulesPanel({
*
* 从前这里是一句连排的话,`A and B or C` 里两个连词一样重,谁先结合读不出来
* ——而那正是规则最容易被误读的地方。 */
-function RuleCriterion({ rule }: { rule: BusinessRule }) {
+function RuleCriterion({ rule, attributes }: { rule: BusinessRule; attributes: RelationTypeView[] }) {
const groups = byGroup(rule.conditions);
return (
<div className="space-y-1">
@@ -555,7 +565,7 @@ function RuleCriterion({ rule }: { rule: BusinessRule }) {
<span className="text-small text-ink-2">
<span className="text-ink">{c.predicate_label}</span>{" "}
{OPS.find((o) => o.value === c.op)?.label() ?? c.op}{" "}
- <span className="u-num text-ink">{operandText(c.op, c.operand)}</span>
+ <span className="u-num text-ink">{operandText(c.op, c.operand, attributes)}</span>
</span>
</div>
)),
@@ -805,3 +815,36 @@ function RuleDialog({
</Dialog>
);
}
+
+
+function RuleConclusion({ rule: r, attributes }: { rule: BusinessRule; attributes: RelationTypeView[] }) {
+ if (r.conclusion === "typing") return <>{r.conclude_type_label}</>;
+ if (r.conclusion === "computed") return <>{r.conclude_predicate_label} = {expressionText(r.conclude_expr, attributes, S.ontology.ruleUnknownExpression)}</>;
+ if (r.conclusion === "attribute") return <>{r.conclude_predicate_label} = {JSON.stringify(r.conclude_value)}</>;
+ return <>{S.ontology.ruleUnknownExpression}</>;
+}
+
+function RuleMetadataDialog({ kbId, rule, attributes, onClose, onSaved }: {
+ kbId: string; rule: BusinessRule; attributes: RelationTypeView[]; onClose: () => void; onSaved: () => void;
+}) {
+ const [name, setName] = useState(rule.name);
+ const [description, setDescription] = useState(rule.description ?? "");
+ const save = useMutation({
+ mutationFn: () => api.updateRule(kbId, rule.id, metadataPatch(name, description)),
+ onSuccess: () => { toast.success(S.ontology.ruleSaved); onSaved(); onClose(); },
+ });
+ return <Dialog open onOpenChange={(open) => !open && onClose()} title={S.ontology.ruleEditing}
+ closeLabel={S.ui.close} width="lg" footer={<>
+ <Button size="sm" variant="secondary" onClick={onClose}>{S.graph.editCancel}</Button>
+ <Button size="sm" variant="primary" disabled={save.isPending || !name.trim()} onClick={() => save.mutate()}>{S.ontology.ruleSave}</Button>
+ </>}>
+ <div className="space-y-4">
+ <Field label={S.ontology.ruleName}><Input autoFocus className="w-full" value={name} onChange={(e) => setName(e.target.value)} /></Field>
+ <Field label={S.ontology.ruleDescription}><Input className="w-full" value={description} onChange={(e) => setDescription(e.target.value)} /></Field>
+ <p className="text-small text-ink-2">{S.ontology.ruleExpressionReadOnly}</p>
+ <Field label={S.ontology.ruleConditions}><RuleCriterion rule={rule} attributes={attributes} /></Field>
+ <Field label={S.ontology.ruleConcludes}><p className="break-words text-body text-ink">{rule.subject_label} → <RuleConclusion rule={rule} attributes={attributes} /></p></Field>
+ {save.error && <p role="alert" className="text-small text-danger">{(save.error as Error).message}</p>}
+ </div>
+ </Dialog>;
+}
diff --git a/web/src/pages/ruleExpressions.test.ts b/web/src/pages/ruleExpressions.test.ts
new file mode 100644
index 00000000..2d6cef8b
--- /dev/null
+++ b/web/src/pages/ruleExpressions.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it, vi } from "vitest";
+import { api, type BusinessRule } from "../api";
+import { expressionText, metadataOnly, metadataPatch, readExpression } from "./ruleExpressions";
+const a = "00000000-0000-0000-0000-000000000001", b = "00000000-0000-0000-0000-000000000002";
+const attrs = [{ id: a, key: "revenue", label: "收入" }, { id: b, key: "cost", label: "成本" }];
+const expr = { op: "div", l: { op: "sub", l: { attr: a }, r: { attr: b } }, r: { attr: a } };
+const rule: BusinessRule = {
+ id: "rule", name: "Margin", subject_type_id: "class", subject_label: "Company",
+ conclusion: "computed", conclude_expr: expr, conclude_type_label: null,
+ conclude_predicate_label: "Margin", conclude_predicate_id: a,
+ conditions: [{ predicate_id: a, op: "gt", operand: 0, group: 4 }], enabled: true, derived_count: 0, capped: 0,
+};
+describe("reading existing rule expressions", () => {
+ it("keeps nested noncommutative structure and resolves IDs", () => {
+ expect(expressionText(expr, attrs, "unknown")).toBe("((收入 − 成本) ÷ 收入)");
+ const nested = { op: "sub", l: { attr: a }, r: { op: "sub", l: { attr: b }, r: { const: 3 } } };
+ expect(expressionText(nested, attrs, "unknown")).toBe("(收入 − (成本 − 3))");
+ expect(readExpression(nested)).toEqual(nested);
+ expect(expressionText({ const: "2.50" }, attrs, "unknown")).toBe("2.50");
+ });
+ it("distinguishes repeated labels and keeps missing IDs visible", () => {
+ expect(expressionText(expr, attrs.map((x) => ({ ...x, label: "值" })), "unknown")).toBe("((值 (revenue) − 值 (cost)) ÷ 值 (revenue))");
+ expect(expressionText({ attr: a }, [], "unknown")).toBe(a);
+ });
+ it("does not coerce unsupported nodes to zero", () => {
+ for (const raw of [null, {}, { const: "" }, { const: Infinity }, { const: "NaN" }, { const: "0x20" }, { op: "sum", l: { attr: a }, r: { const: 1 } }, { attr: a, extra: true }, { attr: "missing" }]) {
+ expect(readExpression(raw)).toBeNull();
+ expect(expressionText(raw, attrs, "unknown")).toBe("unknown");
+ }
+ });
+ it("uses the store's root-at-zero depth limit", () => {
+ let tree: unknown = { attr: a };
+ for (let i = 0; i < 4; i++) tree = { op: "add", l: tree, r: { const: 1 } };
+ expect(readExpression(tree)).not.toBeNull();
+ expect(readExpression({ op: "add", l: tree, r: { const: 1 } })).toBeNull();
+ });
+ it("guards definitions the constant form cannot round-trip", () => {
+ expect(metadataOnly(rule)).toBe(true);
+ expect(metadataOnly({ ...rule, conclusion: "typing", conditions: [{ predicate_id: a, op: "gt", operand: expr }] })).toBe(true);
+ expect(metadataOnly({ ...rule, conclusion: "attribute", conclude_value: 4 })).toBe(true);
+ expect(metadataOnly({ ...rule, conclusion: "attribute", conclude_value: "A" })).toBe(false);
+ expect(metadataOnly({ ...rule, conclusion: "typing" })).toBe(false);
+ });
+ it("sends only metadata via the API adapter, including after an error", async () => {
+ const before = JSON.stringify(rule);
+ const fetcher = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({ error: "denied" }), { status: 403 })).mockResolvedValue(new Response(JSON.stringify({ ok: true })));
+ vi.stubGlobal("fetch", fetcher);
+ try {
+ const patch = metadataPatch("New name", "New description");
+ await expect(api.updateRule("kb", rule.id, patch)).rejects.toThrow("denied");
+ await api.updateRule("kb", rule.id, patch);
+ for (const [url, init] of fetcher.mock.calls) {
+ expect(url).toBe("/api/v1/kbs/kb/rules/rule");
+ expect(init.method).toBe("PATCH");
+ expect(JSON.parse(init.body)).toEqual({ name: "New name", description: "New description" });
+ }
+ expect(JSON.stringify(rule)).toBe(before);
+ } finally { vi.unstubAllGlobals(); }
+ });
+});
diff --git a/web/src/pages/ruleExpressions.ts b/web/src/pages/ruleExpressions.ts
new file mode 100644
index 00000000..96f60606
--- /dev/null
+++ b/web/src/pages/ruleExpressions.ts
@@ -0,0 +1,63 @@
+import type { BusinessRule, RelationTypeView } from "../api";
+
+export type RuleExpression =
+ | { attr: string }
+ | { const: number | string }
+ | { op: "add" | "sub" | "mul" | "div"; l: RuleExpression; r: RuleExpression };
+
+// Match the store's root-at-zero validation bound. Unknown nodes stay unknown;
+// a reader must never replace them with a constant or simplify their structure.
+export function readExpression(raw: unknown, depth = 0): RuleExpression | null {
+ if (depth > 4 || !raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const node = raw as Record<string, unknown>;
+ if (Object.keys(node).length === 1 && typeof node.attr === "string" &&
+ /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(node.attr)) {
+ return { attr: node.attr };
+ }
+ if (Object.keys(node).length === 1 &&
+ (typeof node.const === "number" || typeof node.const === "string") &&
+ /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(String(node.const).trim()) && Number.isFinite(Number(node.const))) {
+ return { const: node.const };
+ }
+ if (Object.keys(node).length !== 3 || !["add", "sub", "mul", "div"].includes(String(node.op))) return null;
+ const l = readExpression(node.l, depth + 1), r = readExpression(node.r, depth + 1);
+ return l && r ? { op: node.op as "add" | "sub" | "mul" | "div", l, r } : null;
+}
+
+export function expressionText(raw: unknown, attributes: Pick<RelationTypeView, "id" | "label" | "key">[], unknownText: string): string {
+ const expr = readExpression(raw);
+ if (!expr) return unknownText;
+ const labels = new Map(attributes.map((a) => [a.id, a]));
+ const counts = new Map<string, number>();
+ for (const a of attributes) counts.set(a.label, (counts.get(a.label) ?? 0) + 1);
+ const render = (node: RuleExpression): string => {
+ if ("attr" in node) {
+ const attr = labels.get(node.attr);
+ return attr ? (counts.get(attr.label)! > 1 ? `${attr.label} (${attr.key})` : attr.label) : node.attr;
+ }
+ if ("const" in node) return String(node.const);
+ return `(${render(node.l)} ${{ add: "+", sub: "−", mul: "×", div: "÷" }[node.op]} ${render(node.r)})`;
+ };
+ return render(expr);
+}
+
+/** The constant form cannot round-trip these definitions. It may edit their
+ * name and description through PATCH, leaving every semantic field on the server. */
+export function metadataOnly(rule: BusinessRule): boolean {
+ if (!["typing", "attribute"].includes(rule.conclusion)) return true;
+ if (rule.conclusion === "attribute" && typeof rule.conclude_value !== "string") return true;
+ return rule.conditions.some((c) => {
+ if (["gt", "gte", "lt", "lte"].includes(c.op)) {
+ return !["number", "string"].includes(typeof c.operand);
+ }
+ if (["in", "not_in"].includes(c.op)) {
+ return !Array.isArray(c.operand) || c.operand.some((v) => typeof v !== "string" || v.trim() !== v || !v || v.includes(","));
+ }
+ if (c.op === "between") return !Array.isArray(c.operand) || c.operand.length !== 2 || c.operand.some((v) => typeof v !== "number");
+ return c.op !== "present" || c.operand != null;
+ });
+}
+
+export function metadataPatch(name: string, description: string) {
+ return { name, description };
+}