Commit 78ee3f27 by 黄南光

大幅优化本体论系统

1 parent b26c5a10
Showing 88 changed files with 6771 additions and 670 deletions
...@@ -36,6 +36,28 @@ ...@@ -36,6 +36,28 @@
"scripts/serve_8103.py" "scripts/serve_8103.py"
], ],
"port": 8103 "port": 8103
},
{
"name": "onto-8104",
"runtimeExecutable": "./.venv/Scripts/python.exe",
"runtimeArgs": [
"scripts/serve_8103.py"
],
"env": {
"PORT": "8104"
},
"port": 8104
},
{
"name": "onto-8105",
"runtimeExecutable": "./.venv/Scripts/python.exe",
"runtimeArgs": [
"scripts/serve_8103.py"
],
"env": {
"PORT": "8105"
},
"port": 8105
} }
] ]
} }
\ No newline at end of file \ No newline at end of file
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
from fastapi import APIRouter, HTTPException, Request from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
from sse_starlette.sse import EventSourceResponse from sse_starlette.sse import EventSourceResponse
from ..core import db, llm from ..core import db, identity, llm
from ..jobs.queue import runner from ..jobs.queue import runner
from ..schemas import ( from ..schemas import (
AskRequest, ColumnUpdate, DataSourceCreate, DataSourceUpdate, DescribeRequest, AskRequest, ColumnUpdate, DataSourceCreate, DataSourceUpdate, DescribeRequest,
...@@ -19,7 +19,8 @@ from ..text2sql.pipeline import run_ask ...@@ -19,7 +19,8 @@ from ..text2sql.pipeline import run_ask
from . import deps from . import deps
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/sql", tags=["text2sql"]) # 数据源按本体空间归属:每个请求都要先解析身份(带出 X-Workspace)
router = APIRouter(prefix="/api/sql", tags=["text2sql"], dependencies=[Depends(identity.resolve)])
def _need_ds(ds_id: int) -> dict: def _need_ds(ds_id: int) -> dict:
...@@ -57,6 +58,38 @@ async def create_datasource(payload: DataSourceCreate): ...@@ -57,6 +58,38 @@ async def create_datasource(payload: DataSourceCreate):
return semantic.get_datasource(ds_id) return semantic.get_datasource(ds_id)
@router.post("/datasources/file")
async def create_file_datasource(name: str = Form(...), ds_id: int = Form(0),
files: list[UploadFile] = File(...)):
"""本地文件数据源:CSV / Excel / JSON 导入成一个只读 SQLite 库。传 ds_id 表示往已有的文件数据源里追加。"""
from ..core.config import get_settings
from ..text2sql.connectors import sqlite_file
ups = [(f.filename or "data.csv", await f.read()) for f in files]
bad = [n for n, _ in ups if not n.lower().endswith(sqlite_file.FILE_TYPES)]
if bad:
raise HTTPException(422, f"不支持的文件:{'、'.join(bad)}(支持 {'、'.join(sqlite_file.FILE_TYPES)})")
if ds_id:
ds = _need_ds(ds_id)
if ds["ds_type"] != "sqlite":
raise HTTPException(422, "只能往本地文件数据源里追加文件")
path = ds["db_name"]
else:
ds_id = semantic.create_datasource(name=name[:128], ds_type="sqlite", host="local", port=0,
db_name="", username="")
path = str(get_settings().data_path / "files" / f"ds_{ds_id}.sqlite")
semantic.update_datasource(ds_id, db_name=path)
from pathlib import Path
try:
tables = sqlite_file.import_files(Path(path), ups)
except (ValueError, KeyError) as e:
if not semantic.list_models(ds_id):
semantic.delete_datasource(ds_id)
raise HTTPException(422, f"文件导入失败:{e}") from e
registry.evict(ds_id)
semantic.mark_datasource(ds_id, "ok", "")
return {**semantic.get_datasource(ds_id), "imported": tables}
@router.get("/datasources/{ds_id}") @router.get("/datasources/{ds_id}")
async def get_datasource(ds_id: int): async def get_datasource(ds_id: int):
return _need_ds(ds_id) return _need_ds(ds_id)
......
...@@ -30,6 +30,9 @@ def setup() -> None: ...@@ -30,6 +30,9 @@ def setup() -> None:
from .sop import engine as sop_engine from .sop import engine as sop_engine
from .sop import service as sop_service from .sop import service as sop_service
from .kernel import linker
ksvc.on_publish(lambda rev: linker.invalidate()) # 新版本生效:概念链接器重建索引
ksvc.on_publish(_sync_after_publish) # 新版本生效:骨架与关系边跟着刷新
ksvc.register_usage_provider(defs.usage_provider) ksvc.register_usage_provider(defs.usage_provider)
ksvc.register_usage_provider(sop_service.usage_provider) ksvc.register_usage_provider(sop_service.usage_provider)
kernel_api.register_object_section(actions.object_section) kernel_api.register_object_section(actions.object_section)
...@@ -37,6 +40,25 @@ def setup() -> None: ...@@ -37,6 +40,25 @@ def setup() -> None:
templates.register_section("sops", _import_sops, _export_sops) templates.register_section("sops", _import_sops, _export_sops)
def _sync_after_publish(rev) -> None:
"""发布后自动补齐数据管道并在后台同步一次:对象搜索、影响分析马上可用,不用再去数据管道页手点。"""
from .core import db as core_db
if core_db.get_config("PIPELINE_AUTO_SYNC", "1").lower() not in ("1", "true", "yes"):
return
from .jobs.queue import submit_background
from .kernel import pipeline
def gen():
created = pipeline.ensure_all()["created"]
if created:
yield {"stage": "pipeline", "progress": 1, "message": f"新建 {len(created)} 条数据管道"}
yield from pipeline.run_all_events()
try:
submit_background("pipeline", gen)
except RuntimeError:
pass # 队列满:不影响发布本身,稍后可在数据管道页手动同步
def _export_sops() -> list[dict]: def _export_sops() -> list[dict]:
from .sop import service as sop_service from .sop import service as sop_service
out = [] out = []
......
...@@ -50,6 +50,8 @@ def _dict(r: ActionRun, approvals: list[dict] | None = None) -> dict: ...@@ -50,6 +50,8 @@ def _dict(r: ActionRun, approvals: list[dict] | None = None) -> dict:
"initiator_kind": r.initiator_kind, "initiator_id": r.initiator_id, "initiator_kind": r.initiator_kind, "initiator_id": r.initiator_id,
"submitted_by": r.submitted_by, "source_ref": r.source_ref, "reason": r.reason, "submitted_by": r.submitted_by, "source_ref": r.source_ref, "reason": r.reason,
"status": r.status, "preview": jload(r.preview_json, {}), "status": r.status, "preview": jload(r.preview_json, {}),
"priority": r.priority or "P2", "evidence": jload(r.evidence_json, []) or [],
"impact": jload(r.impact_json, {}) or {},
"result": jload(r.result_json, {}), "error": r.error, "result": jload(r.result_json, {}), "error": r.error,
"created_at": iso(r.created_at), "decided_at": iso(r.decided_at), "created_at": iso(r.created_at), "decided_at": iso(r.decided_at),
"finished_at": iso(r.finished_at), "approvals": approvals or []} "finished_at": iso(r.finished_at), "approvals": approvals or []}
...@@ -76,13 +78,36 @@ def _lookup(path: str, env: dict) -> Any: ...@@ -76,13 +78,36 @@ def _lookup(path: str, env: dict) -> Any:
return cur return cur
def _readable(v: Any, max_rows: int = 20) -> str:
"""把引用值嵌进给人看的文字(任务说明、通知正文):取数结果变成表格,而不是一大段字典。"""
if v is None:
return ""
if isinstance(v, dict) and isinstance(v.get("rows"), list) and v.get("columns"):
cols, rows = [str(c) for c in v["columns"]], v["rows"]
lines = [f"(共 {len(rows)} 行)", "| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)]
lines += ["| " + " | ".join("" if x is None else str(x) for x in r) + " |" for r in rows[:max_rows]]
if len(rows) > max_rows:
lines.append(f"……另有 {len(rows) - max_rows} 行")
return "\n\n" + "\n".join(lines) + "\n\n" # 表格前后空一行,嵌在列表项里也能渲染成表
if isinstance(v, dict) and ("summary" in v or "value" in v):
return str(v.get("summary") or v.get("value"))
if isinstance(v, (list, tuple)):
return "、".join(_readable(x) for x in v)
return str(v)
def render(v: Any, env: dict) -> Any: def render(v: Any, env: dict) -> Any:
"""效果参数的模板:`$参数` / `$obj.属性` 取值;以 `=` 开头的是表达式(如 `=qty * obj.unit_price`)。"""
if isinstance(v, str): if isinstance(v, str):
if v.startswith("="):
try:
return rules.evaluate(v[1:], env)
except rules.RuleError as e:
raise HTTPException(422, f"参数表达式「{v}」算不出来:{e}") from e
m = _WHOLE.match(v.strip()) m = _WHOLE.match(v.strip())
if m: if m:
return _lookup(m.group(1), env) return _lookup(m.group(1), env)
return _INNER.sub(lambda mm: "" if _lookup(mm.group(1), env) is None return _INNER.sub(lambda mm: _readable(_lookup(mm.group(1), env)), v)
else str(_lookup(mm.group(1), env)), v)
if isinstance(v, dict): if isinstance(v, dict):
return {k: render(x, env) for k, x in v.items()} return {k: render(x, env) for k, x in v.items()}
if isinstance(v, list): if isinstance(v, list):
...@@ -138,7 +163,9 @@ def prepare(action_ref: str, params: dict, object_key: str = "") -> dict: ...@@ -138,7 +163,9 @@ def prepare(action_ref: str, params: dict, object_key: str = "") -> dict:
def _prepare(action: dict, params: dict, object_key: str = "") -> dict: def _prepare(action: dict, params: dict, object_key: str = "") -> dict:
spec = action["spec"] spec = action["spec"]
p = _coerce_params(action, params or {}) p = _coerce_params(action, params or {})
env: dict[str, Any] = dict(p) stamp = now()
# 内置变量:$today 今天、$now_id 时间戳编号(新建单据的单号用,如 PO$now_id)
env: dict[str, Any] = {"today": stamp.date().isoformat(), "now_id": stamp.strftime("%Y%m%d%H%M%S"), **p}
target_ref = "" target_ref = ""
if spec.get("target_type"): if spec.get("target_type"):
key = object_key or str(params.get("obj_key") or params.get("key") or "") key = object_key or str(params.get("obj_key") or params.get("key") or "")
...@@ -179,10 +206,49 @@ def _prepare(action: dict, params: dict, object_key: str = "") -> dict: ...@@ -179,10 +206,49 @@ def _prepare(action: dict, params: dict, object_key: str = "") -> dict:
# ---------------- 提议 ---------------- # ---------------- 提议 ----------------
PRIORITIES = ("P0", "P1", "P2", "P3")
_RISK_PRIORITY = {"high": "P1", "medium": "P2", "low": "P3"}
def _impact(target_ref: str) -> dict:
"""提议时顺带算影响面:这个对象在关系网上会波及谁(骨架没同步就跳过)。"""
if not target_ref.startswith("object:"):
return {}
_, type_id, key = target_ref.split(":", 2)
try:
from ..kernel import traverse
t = traverse.traverse(type_id, key, depth=2, limit=200)
except HTTPException:
return {}
except Exception: # noqa: BLE001
log.debug("计算影响面失败", exc_info=True)
return {}
return {"by_type": t["by_type"], "total": sum(t["by_type"].values()),
"sample": [{"type_name": n["type_name"], "label": n["label"], "depth": n["depth"]}
for n in t["nodes"] if n["depth"]][:12],
"synced_at": t["synced_at"]}
def _evidence(items: Any) -> list[dict]:
out = []
for it in items or []:
if isinstance(it, str):
it = {"text": it}
if isinstance(it, dict) and (it.get("text") or it.get("ref")):
out.append({"kind": str(it.get("kind") or "note"), "text": str(it.get("text") or "")[:1000],
"ref": str(it.get("ref") or "")[:255]})
return out[:20]
def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str = "", def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str = "",
initiator_kind: str = "user", source_ref: str = "") -> dict: initiator_kind: str = "user", source_ref: str = "", priority: str = "",
evidence: Any = None) -> dict:
actor = identity.current() actor = identity.current()
prep = prepare(action_ref, params, object_key) prep = prepare(action_ref, params, object_key)
prio = (priority or "").upper()
if prio and prio not in PRIORITIES:
raise HTTPException(422, f"优先级只能是 {'/'.join(PRIORITIES)}")
prio = prio or _RISK_PRIORITY.get(prep["action"]["risk_level"], "P2")
key_src = jdump({"a": prep["action"]["id"], "p": prep["params"], "t": prep["target_ref"], key_src = jdump({"a": prep["action"]["id"], "p": prep["params"], "t": prep["target_ref"],
"s": source_ref}) "s": source_ref})
idem = hashlib.sha1(key_src.encode("utf-8")).hexdigest() idem = hashlib.sha1(key_src.encode("utf-8")).hexdigest()
...@@ -202,7 +268,9 @@ def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str ...@@ -202,7 +268,9 @@ def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str
else actor.id[3:] if actor.id.startswith("ai:") else "", else actor.id[3:] if actor.id.startswith("ai:") else "",
source_ref=source_ref, reason=reason or "", source_ref=source_ref, reason=reason or "",
status="pending_approval", preview_json=jdump(prep), status="pending_approval", preview_json=jdump(prep),
idempotency_key=idem) idempotency_key=idem, priority=prio,
evidence_json=jdump(_evidence(evidence)),
impact_json=jdump(_impact(prep["target_ref"])))
s.add(run) s.add(run)
roles = prep["action"]["approver_roles"] roles = prep["action"]["approver_roles"]
s.add(ApprovalTask(id=new_id("ap"), workspace=actor.workspace, run_id=run.id, s.add(ApprovalTask(id=new_id("ap"), workspace=actor.workspace, run_id=run.id,
...@@ -257,7 +325,8 @@ def _can_approve(actor: identity.Actor, run: dict, roles: list[str]) -> str: ...@@ -257,7 +325,8 @@ def _can_approve(actor: identity.Actor, run: dict, roles: list[str]) -> str:
run["initiator_id"] == f"ai:{actor.id}": run["initiator_id"] == f"ai:{actor.id}":
return "不能审批自己发起的动作(四眼原则)" return "不能审批自己发起的动作(四眼原则)"
if roles and not set(roles) & set(actor.biz_roles + actor.roles): if roles and not set(roles) & set(actor.biz_roles + actor.roles):
return f"此动作需要「{'、'.join(roles)}」审批" return (f"此动作需要「{'、'.join(roles)}」审批,你目前不担任这个角色"
f"(管理员可在「成员与角色」里给你加上)")
return "" return ""
...@@ -274,6 +343,7 @@ def pending_for(actor: identity.Actor) -> list[dict]: ...@@ -274,6 +343,7 @@ def pending_for(actor: identity.Actor) -> list[dict]:
r["can_approve"] = not why r["can_approve"] = not why
r["cannot_reason"] = why r["cannot_reason"] = why
out.append(r) out.append(r)
out.sort(key=lambda r: r["priority"]) # 稳定排序:同优先级仍按提议时间倒序
return out return out
......
...@@ -35,6 +35,8 @@ class ProposeIn(BaseModel): ...@@ -35,6 +35,8 @@ class ProposeIn(BaseModel):
reason: str = "" reason: str = ""
initiator_kind: str = "user" # user / ai(用户提交 AI 建议的动作卡时) initiator_kind: str = "user" # user / ai(用户提交 AI 建议的动作卡时)
source_ref: str = "" source_ref: str = ""
priority: str = "" # P0~P3,不填按动作风险定
evidence: list = Field(default_factory=list)
class DecideIn(BaseModel): class DecideIn(BaseModel):
...@@ -143,11 +145,12 @@ async def propose_action(ref: str, body: ProposeIn, ...@@ -143,11 +145,12 @@ async def propose_action(ref: str, body: ProposeIn,
try: try:
return actions.propose(ref, body.params, object_key=body.object_key, return actions.propose(ref, body.params, object_key=body.object_key,
reason=body.reason, initiator_kind="ai", reason=body.reason, initiator_kind="ai",
source_ref=body.source_ref) source_ref=body.source_ref, priority=body.priority,
evidence=body.evidence)
finally: finally:
identity.reset(tok) identity.reset(tok)
return actions.propose(ref, body.params, object_key=body.object_key, reason=body.reason, return actions.propose(ref, body.params, object_key=body.object_key, reason=body.reason,
source_ref=body.source_ref) source_ref=body.source_ref, priority=body.priority, evidence=body.evidence)
@router.get("/runs") @router.get("/runs")
...@@ -209,10 +212,55 @@ async def claim_task(task_id: str, _: identity.Actor = Depends(require("operate" ...@@ -209,10 +212,55 @@ async def claim_task(task_id: str, _: identity.Actor = Depends(require("operate"
return tasks.claim(task_id) return tasks.claim(task_id)
# ---------- 运行时总览 ----------
@router.get("/runtime/overview")
async def runtime_overview(actor: identity.Actor = Depends(require("view"))):
import datetime as dt
from ..governance import audit
from ..kernel import pipeline
from ..sop import engine as sop_engine
since = (dt.datetime.now() - dt.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
calls = audit.query(workspace=actor.workspace, event="mcp.call", since=since, limit=2000,
full=True)["items"]
by_tool: dict[str, dict] = {}
by_via: dict[str, int] = {}
ok = 0
for c in calls:
a = c.get("after") or {}
t = by_tool.setdefault(c["target_id"], {"tool": c["target_id"], "calls": 0, "failed": 0,
"total_ms": 0})
t["calls"] += 1
t["total_ms"] += int(a.get("duration_ms") or 0)
if a.get("ok"):
ok += 1
else:
t["failed"] += 1
via = a.get("via") or "agent"
by_via[via] = by_via.get(via, 0) + 1
tools = sorted(by_tool.values(), key=lambda x: -x["calls"])
for t in tools:
t["avg_ms"] = int(t["total_ms"] / t["calls"]) if t["calls"] else 0
pending = actions.pending_for(actor)
by_prio: dict[str, int] = {}
for r in pending:
by_prio[r["priority"]] = by_prio.get(r["priority"], 0) + 1
return {"mcp": {"calls_24h": len(calls), "success_rate": round(ok / len(calls), 3) if calls else None,
"by_via": by_via, "top_tools": tools[:10]},
"approvals": {"pending": len(pending), "by_priority": by_prio,
"top": [{k: r[k] for k in ("id", "action_name", "priority", "reason", "created_at")}
for r in pending[:5]]},
"actions": actions.stats(actor), "runcards": sop_engine.stats(),
"pipelines": {**pipeline.status(), "items": pipeline.list_pipelines()}}
# ---------- 收件箱汇总 ---------- # ---------- 收件箱汇总 ----------
@router.get("/inbox") @router.get("/inbox")
async def inbox(actor: identity.Actor = Depends(require("view"))): async def inbox(actor: identity.Actor = Depends(require("view"))):
from ..kernel import service as ksvc
counts = review.counts() if actor.can("review") else {} counts = review.counts() if actor.can("review") else {}
counts.pop("release", None)
releases = sum(1 for r in ksvc.list_releases("pending") if r["can_decide"]) if actor.can("review") or actor.can("approve") else 0
return {"approvals": actions.count_pending(actor), "tasks": tasks.count_open(actor), return {"approvals": actions.count_pending(actor), "tasks": tasks.count_open(actor),
"reviews": sum(counts.values()), "review_counts": counts, "reviews": sum(counts.values()), "review_counts": counts, "releases": releases,
"notifications": notify.unread_count(actor)} "notifications": notify.unread_count(actor)}
...@@ -65,7 +65,16 @@ def knowledge_search(args: dict, emit: Emit | None) -> dict: ...@@ -65,7 +65,16 @@ def knowledge_search(args: dict, emit: Emit | None) -> dict:
def concept_lookup(args: dict, emit: Emit | None) -> dict: def concept_lookup(args: dict, emit: Emit | None) -> dict:
c = service.rt_find(args["name"]) c = service.rt_find(args["name"])
if c is None: if c is None:
return {"found": False, "summary": f"本体中没有「{args['name']}」"} # 叫法对不上(「补货规则」vs「补货数量计算」):按两字片段重合找相近的积木给规划器参考
name = str(args["name"])
grams = {name[i:i + 2] for i in range(len(name) - 1)} - {"规则", "规定", "计算", "情况"}
near = [x for k in ("object_type", "link_type", "function", "action") for x in service.rt_by_kind(k) if grams & {x["name"][i:i + 2] for i in range(len(x["name"]) - 1)}][:6]
if len(near) == 1:
c = near[0]
else:
return {"found": False, "candidates": [{"name": x["name"], "kind_label": x.get("kind_label", x["kind"]),
"description": x.get("description", "")} for x in near],
"summary": f"本体中没有「{name}」" + (f",相近的有:{'、'.join(x['name'] for x in near)}" if near else "")}
ev = service.evidence_for([c["id"]]).get(c["id"], [])[:5] ev = service.evidence_for([c["id"]]).get(c["id"], [])[:5]
return {"found": True, "concept": {k: c.get(k) for k in return {"found": True, "concept": {k: c.get(k) for k in
("id", "kind", "kind_label", "name", "description", ("id", "kind", "kind_label", "name", "description",
...@@ -74,7 +83,7 @@ def concept_lookup(args: dict, emit: Emit | None) -> dict: ...@@ -74,7 +83,7 @@ def concept_lookup(args: dict, emit: Emit | None) -> dict:
@function("metric.query", "指标取数", "按已发布聚合函数(指标)的定义确定性地取数(不让模型写 SQL)。" @function("metric.query", "指标取数", "按已发布聚合函数(指标)的定义确定性地取数(不让模型写 SQL)。"
"一般直接用 data.ask;已经确切知道指标名和参数时可以直接调它。" "一般直接用 data_ask;已经确切知道指标名和参数时可以直接调它。"
"可按维度拆分、按维度值过滤、按时间(current/last/YYYY-MM 或 {start,end})过滤、按单个对象取值。", "可按维度拆分、按维度值过滤、按时间(current/last/YYYY-MM 或 {start,end})过滤、按单个对象取值。",
{"type": "object", "properties": { {"type": "object", "properties": {
"metric": _s("指标名称"), "metric": _s("指标名称"),
...@@ -228,6 +237,9 @@ def eval_function(fn: dict, args: dict, *, draft: bool = False) -> dict: ...@@ -228,6 +237,9 @@ def eval_function(fn: dict, args: dict, *, draft: bool = False) -> dict:
r["summary"] = (f"{fn['name']} = {r['value']}{r['metric']['unit']}" if r["value"] is not None r["summary"] = (f"{fn['name']} = {r['value']}{r['metric']['unit']}" if r["value"] is not None
else f"{fn['name']} 共 {len(r['rows'])} 行") else f"{fn['name']} 共 {len(r['rows'])} 行")
return r return r
if cat == "ml":
from ..kernel import ml
return ml.evaluate(fn, args.get("inputs") or args)
if cat == "ai": if cat == "ai":
from . import skills from . import skills
if not fn.get("id"): if not fn.get("id"):
...@@ -236,8 +248,8 @@ def eval_function(fn: dict, args: dict, *, draft: bool = False) -> dict: ...@@ -236,8 +248,8 @@ def eval_function(fn: dict, args: dict, *, draft: bool = False) -> dict:
raise HTTPException(422, f"未知的函数类别:{cat}") raise HTTPException(422, f"未知的函数类别:{cat}")
@function("function.eval", "执行函数", "按名称执行本体里任意一个已发布函数(规则 / 决策表 / 周期 / 聚合 / AI 分析)," @function("function.eval", "执行函数", "按名称执行本体里任意一个已发布函数(规则 / 决策表 / 周期 / 聚合 / 模型推理 / AI 分析),"
"参数按函数类别给:规则 vars、决策表 inputs、周期 ref、聚合 dimensions/filters/time/object_key。", "参数按函数类别给:规则 vars、决策表与模型推理 inputs、周期 ref、聚合 dimensions/filters/time/object_key。",
{"type": "object", "properties": {"name": _s("函数名称"), {"type": "object", "properties": {"name": _s("函数名称"),
"args": {"type": "object", "description": "按函数类别给的参数"}}, "args": {"type": "object", "description": "按函数类别给的参数"}},
"required": ["name"]}, category="logic") "required": ["name"]}, category="logic")
...@@ -250,19 +262,19 @@ def function_eval(args: dict, emit: Emit | None) -> dict: ...@@ -250,19 +262,19 @@ def function_eval(args: dict, emit: Emit | None) -> dict:
return out return out
@function("ontology.overview", "本体概览", "列出本体里有哪些对象、关系、函数(指标/规则/周期/决策表/AI 分析)、动作," @function("ontology.overview", "本体概览", "列出本体里有哪些对象、关系、函数(指标/规则/周期/决策表/模型推理/AI 分析)、动作,"
"回答「能问什么 / 有哪些指标」。", "回答「能问什么 / 有哪些指标」。",
{"type": "object", "properties": {"kind": _s( {"type": "object", "properties": {"kind": _s(
"只看某类:object_type / link_type / aggregate / rule / calendar / decision / ai / action")}, "只看某类:object_type / link_type / aggregate / rule / calendar / decision / ml / ai / action")},
"required": []}, category="knowledge") "required": []}, category="knowledge")
def ontology_overview(args: dict, emit: Emit | None) -> dict: def ontology_overview(args: dict, emit: Emit | None) -> dict:
keys = ["object_type", "link_type", "aggregate", "rule", "calendar", "decision", "ai", "action"] fn_cats = ("aggregate", "rule", "calendar", "decision", "ml", "ai")
keys = ["object_type", "link_type", *fn_cats, "action"]
if args.get("kind") in keys: if args.get("kind") in keys:
keys = [args["kind"]] keys = [args["kind"]]
out: dict[str, list] = {} out: dict[str, list] = {}
for k in keys: for k in keys:
items = (service.rt_by_kind("function", k) if k in ("aggregate", "rule", "calendar", "decision", "ai") items = (service.rt_by_kind("function", k) if k in fn_cats else service.rt_by_kind(k))
else service.rt_by_kind(k))
out[k] = [{"name": c["name"], "description": c.get("description", "")[:80]} for c in items][:80] out[k] = [{"name": c["name"], "description": c.get("description", "")[:80]} for c in items][:80]
return {"concepts": out, "summary": "、".join(f"{k}:{len(v)}" for k, v in out.items())} return {"concepts": out, "summary": "、".join(f"{k}:{len(v)}" for k, v in out.items())}
...@@ -284,7 +296,7 @@ def _object_write_revert(args: dict, result: dict) -> None: ...@@ -284,7 +296,7 @@ def _object_write_revert(args: dict, result: dict) -> None:
objects.revert_edit(int(result["edit_id"])) objects.revert_edit(int(result["edit_id"]))
@tool("object.write", "写回对象属性", "修改对象的可写属性(写在本系统写回层,业务库不动)。", @tool("object.write", "写回对象属性", "修改对象的可写属性(数据源开了「写回业务库」就直接改业务表,否则写在本系统写回层)。",
{"type": "object", "properties": {"object_type": _s("对象类型"), "key": _s("对象主键"), {"type": "object", "properties": {"object_type": _s("对象类型"), "key": _s("对象主键"),
"property": _s("属性名"), "value": {"description": "新值"}}, "property": _s("属性名"), "value": {"description": "新值"}},
"required": ["object_type", "key", "property"]}, "required": ["object_type", "key", "property"]},
...@@ -295,6 +307,29 @@ def object_write(args: dict, ctx: dict) -> dict: ...@@ -295,6 +307,29 @@ def object_write(args: dict, ctx: dict) -> dict:
return {"edit_id": e["id"], "from": e["prev"], "to": e["value"]} return {"edit_id": e["id"], "from": e["prev"], "to": e["value"]}
def _object_create_preview(args: dict) -> dict:
ot = objects.object_type(args["object_type"])
vals = args.get("values") or {}
shown = ",".join(f"{k}={v}" for k, v in list(vals.items())[:8])
return {"summary": f"在业务库新建{ot['name']}:{shown}",
"changes": [{"object": ot["name"], "property": k, "from": None, "to": v} for k, v in vals.items()]}
def _object_create_revert(args: dict, result: dict) -> None:
if result.get("edit_id"):
objects.revert_edit(int(result["edit_id"]))
@tool("object.create", "新建对象", "在业务库里新建一个对象(一行),如采购单、工单。数据源必须开启「写回业务库」。",
{"type": "object", "properties": {"object_type": _s("对象类型"),
"values": {"type": "object", "description": "属性名 → 值(含主键)"}},
"required": ["object_type", "values"]},
preview=_object_create_preview, revert=_object_create_revert, risk_level="high")
def object_create(args: dict, ctx: dict) -> dict:
e = objects.create(args["object_type"], args.get("values") or {}, action_run_id=ctx.get("run_id", ""))
return {"edit_id": e["id"], "key": e["object_key"]}
def _task_preview(args: dict) -> dict: def _task_preview(args: dict) -> dict:
who = args.get("assignee") or f"角色「{args.get('role') or '未指定'}」" who = args.get("assignee") or f"角色「{args.get('role') or '未指定'}」"
return {"summary": f"给 {who} 派发任务「{args.get('title')}」" return {"summary": f"给 {who} 派发任务「{args.get('title')}」"
......
...@@ -53,6 +53,17 @@ def _ws() -> str: ...@@ -53,6 +53,17 @@ def _ws() -> str:
# ---------------- 校验 ---------------- # ---------------- 校验 ----------------
def _exprs(v) -> list[str]:
"""效果参数里以 = 开头的表达式。"""
if isinstance(v, str):
return [v[1:]] if v.startswith("=") else []
if isinstance(v, dict):
return [x for item in v.values() for x in _exprs(item)]
if isinstance(v, list):
return [x for item in v for x in _exprs(item)]
return []
def validate_action(spec: dict) -> tuple[dict, str]: def validate_action(spec: dict) -> tuple[dict, str]:
params = [] params = []
names = set() names = set()
...@@ -70,7 +81,7 @@ def validate_action(spec: dict) -> tuple[dict, str]: ...@@ -70,7 +81,7 @@ def validate_action(spec: dict) -> tuple[dict, str]:
"enum": [str(x) for x in p.get("enum") or []], "enum": [str(x) for x in p.get("enum") or []],
"description": p.get("description") or ""}) "description": p.get("description") or ""})
target = str(spec.get("target_type") or "") target = str(spec.get("target_type") or "")
env_names = names | ({"obj", "obj_key"} if target else set()) env_names = names | {"today", "now_id"} | ({"obj", "obj_key"} if target else set())
criteria = [] criteria = []
for c in spec.get("criteria") or []: for c in spec.get("criteria") or []:
expr = str(c.get("expression") or "").strip() expr = str(c.get("expression") or "").strip()
...@@ -97,6 +108,13 @@ def validate_action(spec: dict) -> tuple[dict, str]: ...@@ -97,6 +108,13 @@ def validate_action(spec: dict) -> tuple[dict, str]:
head = ref.split(".")[0] head = ref.split(".")[0]
if head not in env_names: if head not in env_names:
raise HTTPException(422, f"工具 {tool.name} 的参数引用了未定义的变量 ${ref}") raise HTTPException(422, f"工具 {tool.name} 的参数引用了未定义的变量 ${ref}")
for expr in _exprs(args):
try:
unknown = [x for x in rules.free_names(expr) if x not in env_names]
except rules.RuleError as ex:
raise HTTPException(422, f"工具 {tool.name} 的参数表达式「={expr}」有误:{ex}") from ex
if unknown:
raise HTTPException(422, f"工具 {tool.name} 的参数表达式引用了未定义的变量:{'、'.join(unknown)}")
effects.append({"tool": tool.name, "args": args, "label": e.get("label") or tool.title}) effects.append({"tool": tool.name, "args": args, "label": e.get("label") or tool.title})
if order[tool.risk_level] > order[risk]: if order[tool.risk_level] > order[risk]:
risk = tool.risk_level risk = tool.risk_level
......
"""MCP 接口(JSON-RPC over HTTP,Streamable HTTP 的最小实现):让外部 Agent 安全地使用本体能力。 """MCP 服务:本体对外的唯一能力出口(JSON-RPC over HTTP,Streamable HTTP 的最小实现)。
暴露的工具: 外部 Agent、「MCP 服务」页的在线调试、系统自带的「提问」都走这同一份工具目录和同一个
- 所有只读函数(名称里的 `.` 换成 `_`,如 data_ask、function_eval、object_get) `call_logged` —— 提问能做的,外部 Agent 一定也能做;每次调用都记一条 `mcp.call` 审计,
- ask:统一提问(非流式) `via` 区分来源(agent / console / ask)。
- impact_analysis:改一块积木会波及什么
- propose_action:提议一个动作 —— 和界面上一样只进审批队列,**外部 Agent 也不能直接执行动作**
- get_action_status:查审批单状态(Agent 不能审批,只能查)
每次调用(成功或失败、来自外部 Agent 或「MCP 服务」页的在线调试)都记一条 mcp.call 审计。 工具按本体的四种积木组织:
- 类型与知识:list_ontology_types、lookup_concept、search_knowledge
- 对象与关系:query_objects、get_object、get_linked_objects、traverse_link、impact_analysis
- 函数与数据:execute_function、query_metric、data_ask、run_analysis
- 流程卡:find_runcard、execute_runcard
- 动作:propose_action(只进审批队列)、get_action_status —— **不提供审批工具,Agent 不能批**
- 其他:schema_impact(改积木会波及什么)、ask(统一提问,只给外部 Agent)
鉴权:`Authorization: Bearer <MCP_TOKEN>`(设置页配置,留空即关闭); 鉴权:`Authorization: Bearer <MCP_TOKEN>`(设置页配置,留空即关闭);
身份:`X-User-Id` 指定代表哪个用户(数据范围、审计都按他),缺省为 viewer。 身份:`X-User-Id` 指定代表哪个用户(数据范围、审计都按他),缺省为 viewer;`X-Workspace` 指定本体。
""" """
from __future__ import annotations from __future__ import annotations
import json import json
import logging import logging
import time import time
from dataclasses import dataclass
from typing import Any, Callable
from fastapi import APIRouter, HTTPException, Request from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
...@@ -30,60 +35,208 @@ log = logging.getLogger(__name__) ...@@ -30,60 +35,208 @@ log = logging.getLogger(__name__)
router = APIRouter(tags=["mcp"]) router = APIRouter(tags=["mcp"])
PROTOCOL = "2025-06-18" PROTOCOL = "2025-06-18"
Emit = Callable[[dict], None] | None
def _tools() -> list[dict]:
out = [{"name": f.name.replace(".", "_"), "description": f"{f.title}:{f.description}", @dataclass
"inputSchema": {"type": "object", "properties": f.input_schema.get("properties") or {}, class Tool:
"required": f.input_schema.get("required") or []}} name: str
for f in registry.FUNCTIONS.values()] group: str
out.append({"name": "ask", "description": "统一提问:自动选择取数、检索、查流程,返回带引用的答案", description: str
"inputSchema": {"type": "object", "properties": {"question": {"type": "string"}}, properties: dict
"required": ["question"]}}) required: list[str]
out.append({"name": "impact_analysis", run: Callable[[dict, Emit], Any]
"description": "影响分析:改某块积木(对象/关系/函数/动作)会波及哪些积木、流程卡与动作", planner: bool = True # 提问的规划器能不能把它排进步骤
"inputSchema": {"type": "object", "properties": {"name": {"type": "string"}},
"required": ["name"]}}) def as_mcp(self) -> dict:
out.append({"name": "get_action_status", "description": "查询一张动作审批单的状态与审批记录", return {"name": self.name, "description": self.description,
"inputSchema": {"type": "object", "properties": {"run_id": {"type": "string"}}, "inputSchema": {"type": "object", "properties": self.properties,
"required": ["run_id"]}}) "required": self.required},
out.append({"name": "propose_action", "annotations": {"group": self.group}}
"description": "提议一个业务动作。动作不会立即执行,而是进入人工审批队列,返回审批单。",
"inputSchema": {"type": "object", "properties": {
"action": {"type": "string"}, "params": {"type": "object"}, def _s(desc: str, **kw) -> dict:
"object_key": {"type": "string"}, "reason": {"type": "string"}}, return {"type": "string", "description": desc, **kw}
"required": ["action", "reason"]}})
def _fn(name: str) -> Callable[[dict, Emit], Any]:
return lambda args, emit: registry.call_function(name, args, emit)
def _traverse(args: dict, emit: Emit) -> dict:
from ..kernel import traverse
out = traverse.traverse(str(args["object_type"]), str(args["key"]),
depth=int(args.get("depth") or 2), links=args.get("links") or None)
out["summary"] = f"{out['root']['label']} 周边 {len(out['nodes']) - 1} 个关联对象"
return out return out
def _call(name: str, args: dict) -> dict: def _impact(args: dict, emit: Emit) -> dict:
if name == "ask": from ..kernel import traverse
from ..orchestrator import runner return traverse.instance_impact(str(args["object_type"]), str(args["key"]),
out = runner.run_collect(str(args.get("question") or "")) depth=int(args.get("depth") or 3))
return {"answer": out.get("answer"), "citations": out.get("citations"),
"data_refs": [{k: v for k, v in d.items() if k != "rows"} for d in out.get("data_refs") or []],
"suggested_actions": out.get("actions")} def _schema_impact(args: dict, emit: Emit) -> dict:
if name == "impact_analysis":
from ..kernel import service as ksvc from ..kernel import service as ksvc
c = ksvc.find(str(args.get("name") or "")) c = ksvc.find(str(args.get("name") or ""))
if c is None: if c is None:
raise HTTPException(404, f"本体里没有「{args.get('name')}」") raise HTTPException(404, f"本体里没有「{args.get('name')}」")
return ksvc.impact(c["id"]) return ksvc.impact(c["id"])
if name == "get_action_status":
r = actions.get(str(args.get("run_id") or ""))
return {k: r[k] for k in ("id", "action_name", "status", "reason", "error", "created_at", def _run_analysis(args: dict, emit: Emit) -> dict:
"decided_at", "finished_at", "approvals")} from . import skills
if name == "propose_action": return skills.run(str(args["name"]), args.get("inputs") or {}, emit=emit)
def _execute_runcard(args: dict, emit: Emit) -> dict:
ref = str(args.get("runcard") or args.get("sop") or "")
params = args.get("params") or {}
if (args.get("mode") or "readonly") != "live":
return registry.call_function("sop.playbook", {"sop": ref, "params": params}, emit)
from ..sop import engine, service as sop_service
target = next((d for d in sop_service.list_defs(status="published")
if ref in (d["id"], d["title"])), None)
if target is None:
raise HTTPException(404, f"没有已发布的流程卡「{ref}」")
run = engine.start(target["id"], params, mode="live", trigger="mcp")
return {"run_id": run["id"], "status": run["status"], "runcard": target["title"],
"summary": f"已启动流程卡「{target['title']}」({run['status']});其中的动作仍需人工审批"}
def _propose(args: dict, emit: Emit) -> dict:
actor = identity.current() actor = identity.current()
tok = identity.set_current(identity.as_ai(actor)) tok = identity.set_current(identity.as_ai(actor))
try: try:
return actions.propose(str(args["action"]), args.get("params") or {}, return actions.propose(str(args["action"]), args.get("params") or {},
object_key=str(args.get("object_key") or ""), object_key=str(args.get("object_key") or ""),
reason=f"[MCP] {args.get('reason', '')}", initiator_kind="ai", reason=f"[MCP] {args.get('reason', '')}", initiator_kind="ai",
source_ref="mcp") source_ref="mcp", priority=str(args.get("priority") or ""),
evidence=args.get("evidence"))
finally: finally:
identity.reset(tok) identity.reset(tok)
fname = name.replace("_", ".", 1)
return registry.call_function(fname, args)
def _status(args: dict, emit: Emit) -> dict:
r = actions.get(str(args.get("run_id") or ""))
return {k: r[k] for k in ("id", "action_name", "status", "priority", "reason", "error", "created_at",
"decided_at", "finished_at", "approvals")}
def _ask(args: dict, emit: Emit) -> dict:
from ..orchestrator import runner
out = runner.run_collect(str(args.get("question") or ""))
return {"answer": out.get("answer"), "citations": out.get("citations"),
"data_refs": [{k: v for k, v in d.items() if k != "rows"} for d in out.get("data_refs") or []],
"suggested_actions": out.get("actions")}
_OBJ = {"object_type": _s("对象类型名"), "key": _s("对象主键")}
TOOLS: dict[str, Tool] = {t.name: t for t in [
Tool("list_ontology_types", "类型与知识",
"列出本体里有哪些对象、关系、函数(聚合/规则/周期/决策表/模型推理/AI 分析)、动作,回答「能问什么 / 有哪些指标」。",
{"kind": _s("只看某类:object_type / link_type / aggregate / rule / calendar / decision / ml / ai / action")},
[], _fn("ontology.overview")),
Tool("lookup_concept", "类型与知识",
"查某块积木(对象、关系、函数、动作)的定义、口径与出处。问「X 是什么 / 怎么算 / 口径是什么」时用。",
{"name": _s("积木名称或别名")}, ["name"], _fn("concept.lookup")),
Tool("search_knowledge", "类型与知识",
"在文档知识库里检索原文片段、实体与关系。适合定义细节、规则原文、流程说明、为什么这类问题。",
{"query": _s("检索问题,用完整的自然语言"),
"concepts": {"type": "array", "description": "已识别的相关概念名,帮助定位"}},
["query"], _fn("knowledge.search")),
Tool("query_objects", "对象与关系", "按名称模糊查找某类对象的实例。",
{"object_type": _s("对象类型名"), "q": _s("关键词"), "limit": {"type": "integer"}},
["object_type"], _fn("object.search")),
Tool("get_object", "对象与关系", "读取一个对象实例的全部属性(业务库实时数据 + 写回层)。",
_OBJ, ["object_type", "key"], _fn("object.get")),
Tool("get_linked_objects", "对象与关系", "按关系类型实时查一个对象的直接关联对象(一跳)。",
_OBJ, ["object_type", "key"], _fn("object.linked")),
Tool("traverse_link", "对象与关系", "沿关系网多跳遍历,返回周边的对象与关系边(基于数据管道同步的骨架)。",
{**_OBJ, "depth": {"type": "integer", "description": "跳数,1~4,默认 2"},
"links": {"type": "array", "description": "只沿这些关系走,不填走全部"}},
["object_type", "key"], _traverse),
Tool("impact_analysis", "对象与关系",
"实例级影响分析:某个对象出问题时,顺着关系网往外推,哪些对象受影响、最外层的最新状态、可采取的动作。",
{**_OBJ, "depth": {"type": "integer", "description": "跳数,1~4,默认 3"}},
["object_type", "key"], _impact),
Tool("execute_function", "函数与数据",
"按名称执行已发布函数(规则 vars / 决策表与模型推理 inputs / 周期 ref / 聚合 dimensions,filters,time,object_key)。",
{"name": _s("函数名称"), "args": {"type": "object", "description": "按函数类别给的参数"}},
["name"], _fn("function.eval")),
Tool("query_metric", "函数与数据",
"按已发布聚合函数(指标)的定义确定性取数。一般直接用 data_ask;确切知道指标名和参数时可以用它。",
{"metric": _s("指标名称"), "dimensions": {"type": "array", "description": "拆分维度名"},
"filters": {"type": "object", "description": "{维度名: 值或值列表}"},
"time": {"type": ["string", "object"], "description": "current / last / YYYY-MM / {start,end}"},
"object_key": _s("只取某个对象的值时填对象主键"), "calendar": _s("统计周期名"),
"limit": {"type": "integer"}},
["metric"], _fn("metric.query")),
Tool("data_ask", "函数与数据",
"问数 Agent:用自然语言描述要什么数,它自己决定按指标确定性取数还是生成只读 SQL,并对结果做体检。所有数据类问题都交给它。",
{"question": _s("取数需求,把时间、对象、口径、拆分方式都写清楚"),
"ds_id": {"type": "integer", "description": "数据源编号,一般不填"}},
["question"], _fn("data.ask")),
Tool("run_analysis", "函数与数据", "运行一个 AI 分析函数(只读,结果仅供参考)。",
{"name": _s("AI 分析函数名"), "inputs": {"type": "object", "description": "输入"}},
["name"], _run_analysis),
Tool("find_runcard", "流程卡", "按关键词查已发布的流程卡(SOP),返回步骤、角色与参数。问「X 怎么做」时用。",
{"q": _s("流程关键词")}, [], _fn("sop.find")),
Tool("execute_runcard", "流程卡",
"执行流程卡。mode=readonly(默认)只跑取数/分析/判断部分并给出建议;mode=live 真正启动,其中的动作仍进人工审批。",
{"runcard": _s("流程卡名称或 id"), "params": {"type": "object", "description": "流程参数"},
"mode": _s("readonly / live", enum=["readonly", "live"])},
["runcard"], _execute_runcard),
Tool("propose_action", "动作",
"提议一个业务动作。动作不会立即执行,而是带着依据与影响面进入人工审批队列,返回审批单。",
{"action": _s("动作名"), "params": {"type": "object"}, "object_key": _s("作用对象主键"),
"reason": _s("提议理由"), "priority": _s("P0~P3,不填按动作风险定"),
"evidence": {"type": "array", "description": "依据:[{kind,text,ref}] 或文字列表"}},
["action", "reason"], _propose, planner=False),
Tool("get_action_status", "动作", "查询一张动作审批单的状态与审批记录(Agent 只能查,不能批)。",
{"run_id": _s("审批单编号")}, ["run_id"], _status, planner=False),
Tool("schema_impact", "其他", "改某块积木(对象/关系/函数/动作)会波及哪些积木、流程卡与动作。",
{"name": _s("积木名称")}, ["name"], _schema_impact),
Tool("ask", "其他", "统一提问:自动选择取数、检索、查流程,返回带引用的答案。",
{"question": _s("问题")}, ["question"], _ask, planner=False),
]}
# 老名字(注册表函数名、早期工具名)→ 新工具名
ALIASES = {
"knowledge.search": "search_knowledge", "knowledge_search": "search_knowledge",
"concept.lookup": "lookup_concept", "concept_lookup": "lookup_concept",
"ontology.overview": "list_ontology_types", "ontology_overview": "list_ontology_types",
"metric.query": "query_metric", "metric_query": "query_metric",
"data.ask": "data_ask",
"object.get": "get_object", "object_get": "get_object",
"object.search": "query_objects", "object_search": "query_objects",
"object.linked": "get_linked_objects", "object_linked": "get_linked_objects",
"function.eval": "execute_function", "function_eval": "execute_function",
"sop.find": "find_runcard", "sop_find": "find_runcard",
"sop.playbook": "execute_runcard", "sop_playbook": "execute_runcard",
}
def resolve(name: str, args: dict) -> tuple[Tool, dict]:
"""工具名 → 工具。兼容老名字与规划器的 `skill:名称` 写法;其余只读注册表函数也能调,但不在目录里。"""
name = (name or "").strip()
if name.startswith("skill:"):
return TOOLS["run_analysis"], {"name": name.split(":", 1)[1], "inputs": args}
name = ALIASES.get(name, name)
if name in TOOLS:
return TOOLS[name], args
dotted = name if name in registry.FUNCTIONS else name.replace("_", ".", 1)
if dotted in registry.FUNCTIONS:
f = registry.FUNCTIONS[dotted]
return Tool(dotted, "内部", f.description, f.input_schema.get("properties") or {},
f.input_schema.get("required") or [], _fn(dotted), planner=False), args
raise HTTPException(404, f"没有这个工具:{name}")
def tools(planner: bool = False) -> list[dict]:
return [t.as_mcp() for t in TOOLS.values() if not planner or t.planner]
def _rpc_result(rid, result) -> dict: def _rpc_result(rid, result) -> dict:
...@@ -113,14 +266,14 @@ async def mcp(request: Request): ...@@ -113,14 +266,14 @@ async def mcp(request: Request):
rid, method, params = msg.get("id"), msg.get("method", ""), msg.get("params") or {} rid, method, params = msg.get("id"), msg.get("method", ""), msg.get("params") or {}
if method == "initialize": if method == "initialize":
return JSONResponse(_rpc_result(rid, { return JSONResponse(_rpc_result(rid, {
"protocolVersion": PROTOCOL, "capabilities": {"tools": {"listChanged": False}}, "protocolVersion": PROTOCOL, "capabilities": {"tools": {"listChanged": True}},
"serverInfo": {"name": "onto-kernel", "version": "3.0.0"}})) "serverInfo": {"name": "onto-engine", "version": "5.0.0"}}))
if method.startswith("notifications/"): if method.startswith("notifications/"):
return JSONResponse({}, status_code=202) return JSONResponse({}, status_code=202)
if method == "ping": if method == "ping":
return JSONResponse(_rpc_result(rid, {})) return JSONResponse(_rpc_result(rid, {}))
if method == "tools/list": if method == "tools/list":
return JSONResponse(_rpc_result(rid, {"tools": _tools()})) return JSONResponse(_rpc_result(rid, {"tools": tools()}))
if method == "tools/call": if method == "tools/call":
name, args = params.get("name", ""), params.get("arguments") or {} name, args = params.get("name", ""), params.get("arguments") or {}
if not actor.can("ask"): if not actor.can("ask"):
...@@ -136,18 +289,21 @@ async def mcp(request: Request): ...@@ -136,18 +289,21 @@ async def mcp(request: Request):
return JSONResponse(_rpc_error(rid, -32601, f"method not found: {method}")) return JSONResponse(_rpc_error(rid, -32601, f"method not found: {method}"))
def tools() -> list[dict]: _VIA = {"console": "在线调试", "agent": "外部 Agent", "ask": "提问"}
return _tools()
def call_logged(actor: identity.Actor, name: str, args: dict, via: str) -> tuple[bool, object]: def call_logged(actor: identity.Actor, name: str, args: dict, via: str,
emit: Emit = None) -> tuple[bool, object]:
"""执行一个 MCP 工具并写审计。返回 (成功?, 结果或错误信息)。""" """执行一个 MCP 工具并写审计。返回 (成功?, 结果或错误信息)。"""
tok = identity.set_current(actor) tok = identity.set_current(actor)
started = time.time() started = time.time()
tool_name = name
try: try:
if name not in {t["name"] for t in _tools()}: tool, args = resolve(name, dict(args or {}))
raise HTTPException(404, f"没有这个工具:{name}") tool_name = tool.name
out: object = _call(name, args) args = registry.validate_args({"properties": tool.properties, "required": tool.required},
args, f"工具 {tool.name}")
out: object = tool.run(args, emit)
ok = True ok = True
except HTTPException as e: except HTTPException as e:
ok, out = False, str(e.detail) ok, out = False, str(e.detail)
...@@ -157,8 +313,8 @@ def call_logged(actor: identity.Actor, name: str, args: dict, via: str) -> tuple ...@@ -157,8 +313,8 @@ def call_logged(actor: identity.Actor, name: str, args: dict, via: str) -> tuple
finally: finally:
identity.reset(tok) identity.reset(tok)
ms = int((time.time() - started) * 1000) ms = int((time.time() - started) * 1000)
audit.record("mcp.call", "mcp", name, audit.record("mcp.call", "mcp", tool_name,
f"MCP {'调用' if ok else '调用失败'} {name}({'在线调试' if via == 'console' else '外部 Agent'},{ms} ms)", f"MCP {'调用' if ok else '调用失败'} {tool_name}({_VIA.get(via, via)},{ms} ms)",
after={"args": args, "ok": ok, "via": via, "duration_ms": ms, after={"args": args, "ok": ok, "via": via, "duration_ms": ms,
**({} if ok else {"error": out})}, actor=actor) **({} if ok else {"error": out})}, actor=actor)
return ok, out return ok, out
...@@ -52,6 +52,9 @@ class ActionRun(Base): ...@@ -52,6 +52,9 @@ class ActionRun(Base):
result_json: Mapped[str] = mapped_column(_LONGTEXT, default="{}") result_json: Mapped[str] = mapped_column(_LONGTEXT, default="{}")
error: Mapped[str] = mapped_column(Text, default="") error: Mapped[str] = mapped_column(Text, default="")
idempotency_key: Mapped[str] = mapped_column(String(64), default="", index=True) idempotency_key: Mapped[str] = mapped_column(String(64), default="", index=True)
priority: Mapped[str] = mapped_column(String(8), default="P2", index=True) # P0 最紧急 ~ P3
evidence_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]") # 依据:数据 / 规则 / 原文
impact_json: Mapped[str] = mapped_column(_LONGTEXT, default="{}") # 影响面:关系网上会波及谁
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now, index=True) created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now, index=True)
decided_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True) decided_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True) finished_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
......
...@@ -119,6 +119,9 @@ DEFAULT_RUNTIME: dict[str, str] = { ...@@ -119,6 +119,9 @@ DEFAULT_RUNTIME: dict[str, str] = {
"EVAL_GATE": "0", # 发布本体前必须对待发布版本跑过评测 "EVAL_GATE": "0", # 发布本体前必须对待发布版本跑过评测
"EVAL_GATE_MIN_PASS": "0.7", # 评测通过率门槛 "EVAL_GATE_MIN_PASS": "0.7", # 评测通过率门槛
"MCP_TOKEN": "", # MCP 接口的访问令牌,留空则关闭 MCP "MCP_TOKEN": "", # MCP 接口的访问令牌,留空则关闭 MCP
"RELEASE_SELF_APPROVE": "0", # 变更提案是否允许提交人自己审批(单人团队用)
"PIPELINE_ROW_LIMIT": "20000", # 数据管道每个对象类型最多同步的骨架行数
"PIPELINE_AUTO_SYNC": "1", # 发布新版本后自动给已映射对象建管道并同步一次
} }
# 设置页分组 / 说明 / 校验(前端据此渲染带说明和校验的表单,替掉裸 text input) # 设置页分组 / 说明 / 校验(前端据此渲染带说明和校验的表单,替掉裸 text input)
...@@ -129,6 +132,12 @@ RUNTIME_META: dict[str, dict] = { ...@@ -129,6 +132,12 @@ RUNTIME_META: dict[str, dict] = {
"min": 0, "max": 1}, "min": 0, "max": 1},
"MCP_TOKEN": {"group": "治理", "label": "MCP 访问令牌", "type": "text", "MCP_TOKEN": {"group": "治理", "label": "MCP 访问令牌", "type": "text",
"help": "外部 Agent 通过 /mcp 调用本体能力时用 Bearer 令牌鉴权;留空关闭"}, "help": "外部 Agent 通过 /mcp 调用本体能力时用 Bearer 令牌鉴权;留空关闭"},
"RELEASE_SELF_APPROVE": {"group": "治理", "label": "允许自审变更提案", "type": "bool",
"help": "默认提交人不能审批自己的变更提案(四眼原则);只有一两个人的团队可以打开"},
"PIPELINE_ROW_LIMIT": {"group": "数据管道", "label": "骨架同步行数上限", "type": "int", "min": 100,
"max": 1000000, "help": "每个对象类型最多同步这么多行主键 / 显示名 / 关系键,用于对象搜索与影响分析"},
"PIPELINE_AUTO_SYNC": {"group": "数据管道", "label": "发布后自动同步", "type": "bool",
"help": "新版本发布后,自动给已映射的对象建管道并同步一次骨架与关系边,不用再去数据管道页手点"},
"QWEN_MODEL": {"group": "模型", "label": "对话模型", "type": "text", "help": "DashScope 模型名,如 qwen-plus / qwen-max"}, "QWEN_MODEL": {"group": "模型", "label": "对话模型", "type": "text", "help": "DashScope 模型名,如 qwen-plus / qwen-max"},
"EMBED_MODEL": {"group": "模型", "label": "向量模型", "type": "text", "help": "text-embedding-v4,维度 1024"}, "EMBED_MODEL": {"group": "模型", "label": "向量模型", "type": "text", "help": "text-embedding-v4,维度 1024"},
"EMBED_DIM": {"group": "模型", "label": "向量维度", "type": "int", "min": 64, "max": 4096}, "EMBED_DIM": {"group": "模型", "label": "向量维度", "type": "int", "min": 64, "max": 4096},
......
...@@ -112,12 +112,28 @@ _ADD_COLUMNS: dict[str, dict[str, str]] = { ...@@ -112,12 +112,28 @@ _ADD_COLUMNS: dict[str, dict[str, str]] = {
"otlgt3_sm_column": { "otlgt3_sm_column": {
"null_ratio": "DOUBLE NOT NULL DEFAULT 0", "null_ratio": "DOUBLE NOT NULL DEFAULT 0",
}, },
"otlgt3_sm_metric": {
"category": "VARCHAR(64) NOT NULL DEFAULT ''",
},
"otlgt3_sm_instruction": { "otlgt3_sm_instruction": {
"category": "VARCHAR(64) NOT NULL DEFAULT ''", "category": "VARCHAR(64) NOT NULL DEFAULT ''",
}, },
# 数据源按本体空间归属;空串 = 老数据,所有空间共用
"otlgt3_ds": {
"workspace": "VARCHAR(64) NOT NULL DEFAULT ''",
},
# 对象骨架(数据管道)
"onto_instance": {
"props_json": "TEXT",
"synced_at": "DATETIME NULL",
},
# 审批单:优先级、依据、影响面
"onto_action_run": {
"priority": "VARCHAR(8) NOT NULL DEFAULT 'P2'",
"evidence_json": "LONGTEXT",
"impact_json": "LONGTEXT",
},
# 写回记录:overlay = 写回层(业务库不动)/ db = 已写进业务库 / create = 在业务库新建的行
"onto_object_edit": {
"mode": "VARCHAR(16) NOT NULL DEFAULT 'overlay'",
},
} }
......
...@@ -147,8 +147,11 @@ def grade(case: dict, out: dict, judge: bool = True) -> dict: ...@@ -147,8 +147,11 @@ def grade(case: dict, out: dict, judge: bool = True) -> dict:
checks["keywords"] = {"hit": hit, "total": len(case["must_include"])} checks["keywords"] = {"hit": hit, "total": len(case["must_include"])}
parts.append(len(hit) / len(case["must_include"])) parts.append(len(hit) / len(case["must_include"]))
if case["expected_calls"]: if case["expected_calls"]:
alias = {"data.ask": {"metric.query"}, "metric.query": {"data.ask"}} # 两种取数入口等价 from ..capability.mcp import ALIASES
used = [c for c in case["expected_calls"] if c in calls or alias.get(c, set()) & set(calls)] canon = {ALIASES.get(c, c) for c in calls} # 评测集里可能还写着老工具名
same = {"data_ask": {"query_metric"}, "query_metric": {"data_ask"}} # 两种取数入口等价
used = [c for c in case["expected_calls"]
if ALIASES.get(c, c) in canon or same.get(ALIASES.get(c, c), set()) & canon]
checks["calls"] = {"used": used, "expected": case["expected_calls"], "actual": calls} checks["calls"] = {"used": used, "expected": case["expected_calls"], "actual": calls}
parts.append(len(used) / len(case["expected_calls"])) parts.append(len(used) / len(case["expected_calls"]))
if case["expected_action"]: if case["expected_action"]:
......
...@@ -31,6 +31,7 @@ KIND_LABELS = { ...@@ -31,6 +31,7 @@ KIND_LABELS = {
"conflict": "知识冲突", "conflict": "知识冲突",
"sql_pair": "SQL 沉淀", "sql_pair": "SQL 沉淀",
"sop_publish": "SOP 发布", "sop_publish": "SOP 发布",
"release": "变更提案",
"feedback": "答案反馈", "feedback": "答案反馈",
} }
...@@ -76,7 +77,7 @@ def propose(kind: str, title: str, payload: dict, *, source: str = "user", ...@@ -76,7 +77,7 @@ def propose(kind: str, title: str, payload: dict, *, source: str = "user",
return out return out
def list_items(*, status: str = "pending", kind: str = "", q: str = "", def list_items(*, status: str = "pending", kind: str = "", q: str = "", source: str = "",
limit: int = 200, offset: int = 0) -> dict: limit: int = 200, offset: int = 0) -> dict:
ws = identity.current().workspace ws = identity.current().workspace
with session() as s: with session() as s:
...@@ -87,6 +88,8 @@ def list_items(*, status: str = "pending", kind: str = "", q: str = "", ...@@ -87,6 +88,8 @@ def list_items(*, status: str = "pending", kind: str = "", q: str = "",
stmt = stmt.where(ReviewItem.kind == kind) stmt = stmt.where(ReviewItem.kind == kind)
if q: if q:
stmt = stmt.where(ReviewItem.title.like(f"%{q}%")) stmt = stmt.where(ReviewItem.title.like(f"%{q}%"))
if source:
stmt = stmt.where(ReviewItem.source == source)
total = s.scalar(select(func.count()).select_from(stmt.subquery())) or 0 total = s.scalar(select(func.count()).select_from(stmt.subquery())) or 0
rows = s.scalars(stmt.order_by(ReviewItem.created_at.desc()) rows = s.scalars(stmt.order_by(ReviewItem.created_at.desc())
.offset(offset).limit(limit)).all() .offset(offset).limit(limit)).all()
...@@ -102,6 +105,19 @@ def counts() -> dict[str, int]: ...@@ -102,6 +105,19 @@ def counts() -> dict[str, int]:
return {k: int(n) for k, n in rows} return {k: int(n) for k, n in rows}
def update_payload(item_id: str, payload: dict, confidence: float | None = None) -> dict:
"""未决项的 payload 被加工过(如业务建模的规则深化)就原地更新,不另起一条。"""
with session() as s:
r = s.get(ReviewItem, item_id)
if r is None or r.status != "pending":
raise HTTPException(409, "审核项不存在或已处理")
r.payload_json = jdump(payload)
if confidence is not None:
r.confidence = float(confidence)
s.commit()
return _dict(r)
def get(item_id: str) -> dict | None: def get(item_id: str) -> dict | None:
with session() as s: with session() as s:
r = s.get(ReviewItem, item_id) r = s.get(ReviewItem, item_id)
......
...@@ -20,7 +20,7 @@ def list_roles() -> list[dict]: ...@@ -20,7 +20,7 @@ def list_roles() -> list[dict]:
rows = s.scalars(select(BizRole).where(BizRole.workspace == _ws()) rows = s.scalars(select(BizRole).where(BizRole.workspace == _ws())
.order_by(BizRole.name)).all() .order_by(BizRole.name)).all()
members: dict[str, list[str]] = {} members: dict[str, list[str]] = {}
for u in s.scalars(select(User).where(User.workspace == _ws())).all(): for u in s.scalars(select(User)).all(): # 账号是全局的,不按本体过滤(见 users.list_users)
for r in jload(u.biz_roles_json, []): for r in jload(u.biz_roles_json, []):
members.setdefault(r, []).append(u.name or u.id) members.setdefault(r, []).append(u.name or u.id)
return [{"id": r.id, "name": r.name, "description": r.description or "", return [{"id": r.id, "name": r.name, "description": r.description or "",
......
...@@ -3,7 +3,9 @@ from __future__ import annotations ...@@ -3,7 +3,9 @@ from __future__ import annotations
from typing import Any, Callable from typing import Any, Callable
from fastapi import APIRouter, Depends, HTTPException, Query, Request import json
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import PlainTextResponse from fastapi.responses import PlainTextResponse
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from sse_starlette.sse import EventSourceResponse from sse_starlette.sse import EventSourceResponse
...@@ -15,7 +17,8 @@ from ..governance import audit ...@@ -15,7 +17,8 @@ from ..governance import audit
from ..jobs.queue import submit_background from ..jobs.queue import submit_background
from . import calendar as cal from . import calendar as cal
from . import draft as drafting from . import draft as drafting
from . import graphlink, linker, metrics, objects, propose, rules, schema, service, templates from . import (graphlink, linker, metrics, modeling, objects, pipeline, propose, rules, schema,
service, templates, traverse, workspaces)
router = APIRouter(prefix="/api/kernel", tags=["kernel"]) router = APIRouter(prefix="/api/kernel", tags=["kernel"])
...@@ -47,7 +50,6 @@ class BindingIn(BaseModel): ...@@ -47,7 +50,6 @@ class BindingIn(BaseModel):
class PublishIn(BaseModel): class PublishIn(BaseModel):
note: str = "" note: str = ""
concept_ids: list[str] | None = None concept_ids: list[str] | None = None
force: bool = False
class ImportIn(BaseModel): class ImportIn(BaseModel):
...@@ -96,6 +98,79 @@ class DraftIn(BaseModel): ...@@ -96,6 +98,79 @@ class DraftIn(BaseModel):
category: str = "" category: str = ""
class WorkspaceIn(BaseModel):
id: str = ""
display_name: str = ""
description: str = ""
industry: str = ""
template: str = ""
class PipelineIn(BaseModel):
object_type: str = ""
schedule: str | None = None
row_limit: int | None = None
enabled: bool | None = None
class DecideIn(BaseModel):
approve: bool
comment: str = ""
# ---------- 表 ↔ 实体映射 ----------
@router.get("/mappings")
async def mappings(ds_id: int, _: identity.Actor = Depends(require("view"))):
"""某个数据源的每张表映射到了哪个对象类型(数据连接页「配置实体映射」用)。"""
from sqlalchemy import select as _select
from ..core.dbx import jload, session
from .models import Binding, Concept
out: dict[str, list[dict]] = {}
with session() as s:
rows = s.execute(_select(Binding, Concept).join(Concept, Concept.id == Binding.concept_id).where(
Binding.workspace == identity.current().workspace, Binding.ds_id == ds_id,
Binding.target_kind == "table", Concept.status != "deprecated")).all()
for b, c in rows:
t = (jload(b.ref_json, {}) or {}).get("table") or ""
out.setdefault(t, []).append({"concept_id": c.id, "name": c.name, "status": c.status})
return out
# ---------- 本体空间 / 首页 ----------
@router.get("/workspaces")
async def list_workspaces(_: identity.Actor = Depends(require("view"))):
return workspaces.list_all()
@router.post("/workspaces")
async def create_workspace(body: WorkspaceIn, _: identity.Actor = Depends(require("build"))):
return workspaces.create(body.id, body.display_name, body.description, body.industry, body.template)
@router.put("/workspaces/{ws_id}")
async def update_workspace(ws_id: str, body: WorkspaceIn, _: identity.Actor = Depends(require("build"))):
return workspaces.update(ws_id, display_name=body.display_name or None,
description=body.description, industry=body.industry)
@router.delete("/workspaces/{ws_id}")
async def archive_workspace(ws_id: str, _: identity.Actor = Depends(require("admin"))):
return workspaces.archive(ws_id)
@router.get("/home")
async def home(_: identity.Actor = Depends(require("view"))):
return workspaces.overview()
@router.get("/workbench")
async def workbench_view(_: identity.Actor = Depends(require("view"))):
"""业务人员的工作台:关键数字、待我处理、我提交的、常用流程与问题、最近动态。"""
from . import workbench
return workbench.workbench()
@router.get("/meta") @router.get("/meta")
async def meta(_: identity.Actor = Depends(require("view"))): async def meta(_: identity.Actor = Depends(require("view"))):
from ..capability import registry from ..capability import registry
...@@ -270,12 +345,29 @@ async def pending_diff(_: identity.Actor = Depends(require("view"))): ...@@ -270,12 +345,29 @@ async def pending_diff(_: identity.Actor = Depends(require("view"))):
@router.post("/publish") @router.post("/publish")
async def publish(body: PublishIn, actor: identity.Actor = Depends(require("build"))): async def publish(body: PublishIn, _: identity.Actor = Depends(require("build"))):
if body.force and "admin" not in actor.roles: """提交变更提案。发布不再一步到位:别人审批通过后才生成新版本。"""
raise HTTPException(403, "只有管理员可以跳过发布闸门") return service.propose_release(body.note, body.concept_ids)
out = service.publish(body.note, body.concept_ids, body.force)
linker.invalidate()
return out @router.get("/releases")
async def releases(status: str = "", _: identity.Actor = Depends(require("view"))):
return service.list_releases(status)
@router.post("/releases/{item_id}/decide")
async def decide_release(item_id: str, body: DecideIn, _: identity.Actor = Depends(require("view"))):
"""审批(通过 / 驳回)变更提案;提交人自己可以撤回(驳回自己的提案)。"""
from ..governance import review
item = review.get(item_id)
if item is None or item["kind"] != "release":
raise HTTPException(404, "变更提案不存在")
actor = identity.current()
if not body.approve and item["created_by"] != actor.id:
why = service.can_decide_release(actor, item)
if why:
raise HTTPException(403, why)
return review.decide(item_id, body.approve, body.comment or ("" if body.approve else "提交人撤回"))
@router.get("/revisions") @router.get("/revisions")
...@@ -295,10 +387,9 @@ async def revision(rev: int, _: identity.Actor = Depends(require("view"))): ...@@ -295,10 +387,9 @@ async def revision(rev: int, _: identity.Actor = Depends(require("view"))):
@router.post("/revisions/{rev}/rollback") @router.post("/revisions/{rev}/rollback")
async def rollback(rev: int, _: identity.Actor = Depends(require("build"))): async def rollback(rev: int, body: dict | None = None, _: identity.Actor = Depends(require("build"))):
out = service.rollback(rev) """回滚同样是一份变更提案,审批通过后才生效。"""
linker.invalidate() return service.propose_rollback(rev, (body or {}).get("note", ""))
return out
# ---------- 链接 / 求值 ---------- # ---------- 链接 / 求值 ----------
...@@ -410,7 +501,126 @@ async def search_objects(type_ref: str, q: str = "", limit: int = 20, offset: in ...@@ -410,7 +501,126 @@ async def search_objects(type_ref: str, q: str = "", limit: int = 20, offset: in
@router.post("/objects/{type_ref}/sync") @router.post("/objects/{type_ref}/sync")
async def sync_objects(type_ref: str, _: identity.Actor = Depends(require("build"))): async def sync_objects(type_ref: str, _: identity.Actor = Depends(require("build"))):
return {"synced": objects.sync_instances(type_ref)} return pipeline.sync_type(type_ref)
@router.get("/objects/{type_ref}/{key}/traverse")
async def traverse_object(type_ref: str, key: str, depth: int = 2,
_: identity.Actor = Depends(require("view"))):
return traverse.traverse(type_ref, key, depth=depth)
@router.get("/objects/{type_ref}/{key}/impact")
async def impact_object(type_ref: str, key: str, depth: int = 3,
_: identity.Actor = Depends(require("view"))):
return traverse.instance_impact(type_ref, key, depth=depth)
# ---------- 数据管道 / 本体数据集 ----------
@router.get("/pipelines")
async def list_pipelines(_: identity.Actor = Depends(require("view"))):
return {"items": pipeline.list_pipelines(), "status": pipeline.status()}
@router.post("/pipelines")
async def create_pipeline(body: PipelineIn, _: identity.Actor = Depends(require("build"))):
return pipeline.create(body.object_type, body.schedule or "manual", body.row_limit or 0)
@router.post("/pipelines/ensure")
async def ensure_pipelines(_: identity.Actor = Depends(require("build"))):
return pipeline.ensure_all()
@router.post("/pipelines/run-all")
async def run_all_pipelines(_: identity.Actor = Depends(require("build"))):
"""全部同步是后台任务(表多、行多时要几分钟),返回 job_id;各管道状态实时写回列表。"""
try:
return {"job_id": submit_background("pipeline", pipeline.run_all_events)}
except RuntimeError as e:
raise HTTPException(503, str(e)) from e
@router.put("/pipelines/{pid}")
async def update_pipeline(pid: str, body: PipelineIn, _: identity.Actor = Depends(require("build"))):
return pipeline.update(pid, schedule=body.schedule, row_limit=body.row_limit, enabled=body.enabled)
@router.delete("/pipelines/{pid}")
async def delete_pipeline(pid: str, _: identity.Actor = Depends(require("build"))):
pipeline.delete_pipeline(pid)
return {"ok": True}
@router.post("/pipelines/{pid}/run")
async def run_pipeline(pid: str, actor: identity.Actor = Depends(require("build"))):
import asyncio
return await asyncio.to_thread(_as(actor, lambda: pipeline.run(pid)))
def _as(actor: identity.Actor, fn):
"""线程池里跑的函数要带上当前身份(contextvar 不会自动跟过去)。"""
def run():
tok = identity.set_current(actor)
try:
return fn()
finally:
identity.reset(tok)
return run
@router.get("/datasets/{type_ref}")
async def dataset(type_ref: str, q: str = "", limit: int = 50, offset: int = 0,
_: identity.Actor = Depends(require("view"))):
return pipeline.dataset(type_ref, q, limit, offset)
# ---------- 业务建模 ----------
@router.get("/modeling/stages")
async def modeling_stages(_: identity.Actor = Depends(require("view"))):
return {"stages": modeling.STAGES, "templates": templates.list_templates()}
@router.get("/modeling/runs")
async def modeling_runs(_: identity.Actor = Depends(require("view"))):
return modeling.list_runs()
@router.post("/modeling/runs")
async def create_modeling_run(title: str = Form("业务建模"), doc_ids: str = Form("[]"),
template: str = Form(""), stages: str = Form(""), ds_ids: str = Form(""),
start: bool = Form(True), files: list[UploadFile] | None = File(None),
_: identity.Actor = Depends(require("build"))):
try:
ids = [int(x) for x in json.loads(doc_ids or "[]")]
st = json.loads(stages) if stages else None
dss = [int(x) for x in json.loads(ds_ids)] if ds_ids else None
except (ValueError, TypeError) as e:
raise HTTPException(422, "doc_ids / stages 应为 JSON 数组") from e
ups = [(f.filename or "upload.txt", await f.read()) for f in files or []]
run = modeling.create(title, doc_ids=ids, files=ups, template=template, stages=st, ds_ids=dss)
return modeling.start(run["id"]) if start else run
@router.get("/modeling/runs/{run_id}")
async def get_modeling_run(run_id: str, _: identity.Actor = Depends(require("view"))):
return modeling.get(run_id)
@router.post("/modeling/runs/{run_id}/start")
async def start_modeling_run(run_id: str, _: identity.Actor = Depends(require("build"))):
return modeling.start(run_id)
@router.delete("/modeling/runs/{run_id}")
async def delete_modeling_run(run_id: str, _: identity.Actor = Depends(require("build"))):
modeling.delete(run_id)
return {"ok": True}
@router.get("/modeling/runs/{run_id}/export", response_class=PlainTextResponse)
async def export_modeling_run(run_id: str, _: identity.Actor = Depends(require("view"))):
return PlainTextResponse(modeling.export_md(run_id), media_type="text/markdown; charset=utf-8")
@router.get("/objects/{type_ref}/{key}") @router.get("/objects/{type_ref}/{key}")
......
...@@ -94,7 +94,8 @@ samples 留空数组。""", ...@@ -94,7 +94,8 @@ samples 留空数组。""",
"effects":[{"tool":"系统效果名","args":{...}}], "effects":[{"tool":"系统效果名","args":{...}}],
"approval":{"mode":"manual","approver_roles":["业务角色名"]},"reversible":true} "approval":{"mode":"manual","approver_roles":["业务角色名"]},"reversible":true}
效果只能从下面的系统效果里选,args 按其参数填写;引用参数写 "$参数名",引用对象写 "$obj_key"、"$obj.属性"、"$obj.label"。 效果只能从下面的系统效果里选,args 按其参数填写;引用参数写 "$参数名",引用对象写 "$obj_key"、"$obj.属性"、"$obj.label"。
object.write 只能写对象上标了「可写」的属性。 以 "=" 开头的值是表达式,可做计算,如 "=qty * obj.unit_price";内置 "$today"(今天)、"$now_id"(时间戳编号,新单号写 "PO$now_id")。
object.write 改已有对象的属性(会自动开放写回);新建单据(采购单、工单等)用 object.create,values 写全主键和必填属性。
【系统效果】 【系统效果】
{tools} {tools}
【业务角色】{roles} 【业务角色】{roles}
......
...@@ -13,7 +13,7 @@ from fastapi import HTTPException ...@@ -13,7 +13,7 @@ from fastapi import HTTPException
from ..core import identity from ..core import identity
from . import calendar as cal from . import calendar as cal
from . import service from . import service
from .sqlutil import ident, jsonable, lit from .sqlutil import ident, jsonable, lit, to_dialect
def metric(ref: str) -> dict: def metric(ref: str) -> dict:
...@@ -126,7 +126,7 @@ def query(ref: str | dict, *, dimensions: list[str] | None = None, filters: dict ...@@ -126,7 +126,7 @@ def query(ref: str | dict, *, dimensions: list[str] | None = None, filters: dict
ds = semantic.get_datasource(compiled["ds_id"]) ds = semantic.get_datasource(compiled["ds_id"])
if ds is None: if ds is None:
raise HTTPException(422, f"数据源 {compiled['ds_id']} 不存在") raise HTTPException(422, f"数据源 {compiled['ds_id']} 不存在")
out = executor.execute(compiled["ds_id"], compiled["sql"], ds["ds_type"]) out = executor.execute(compiled["ds_id"], to_dialect(compiled["sql"], ds["ds_type"]), ds["ds_type"])
status = "ok" if out.ok else "failed" status = "ok" if out.ok else "failed"
rows = [[jsonable(v) for v in r] for r in (out.result.rows if out.result else [])] rows = [[jsonable(v) for v in r] for r in (out.result.rows if out.result else [])]
run_id = executor.log_run( run_id = executor.log_run(
......
"""模型推理函数(category=ml):调用登记过的模型端点,按输入 / 输出定义取预测值。
模型本身在外面(MLflow、自建推理服务……),本体只管:参数按声明校验、凭据由系统保管、
结果按声明取字段、每次调用可追溯。和 AI 分析不同,它的结果是确定的模型输出,可以作为依据。
"""
from __future__ import annotations
from typing import Any
import requests
from fastapi import HTTPException
from ..core.dbx import jload
def _pick(body: Any, path: str) -> Any:
cur = body
for part in [p for p in (path or "").split(".") if p]:
if isinstance(cur, dict):
cur = cur.get(part)
elif isinstance(cur, list) and part.isdigit() and int(part) < len(cur):
cur = cur[int(part)]
else:
return None
return cur
def evaluate(fn: dict, inputs: dict) -> dict:
from ..capability import defs
spec = fn.get("spec") or {}
if not spec.get("endpoint"):
raise HTTPException(422, "模型推理函数还没有选择模型端点")
ep = defs.find(spec["endpoint"], "endpoint")
if ep is None or ep["status"] != "published":
raise HTTPException(422, f"模型端点「{spec['endpoint']}」不存在或未发布")
args = {}
for f in spec.get("inputs") or []:
v = (inputs or {}).get(f["name"])
if v in (None, ""):
raise HTTPException(422, f"缺少输入「{f.get('label') or f['name']}」")
if f.get("type") == "number":
try:
v = float(v)
except (TypeError, ValueError) as e:
raise HTTPException(422, f"输入「{f.get('label') or f['name']}」应为数字") from e
args[f["name"]] = v
secret = defs.endpoint_secret(ep["id"])
headers = {"Content-Type": "application/json", **(jload(secret, {}) if secret else {})}
try:
resp = requests.request(ep["spec"].get("method", "POST"), ep["spec"]["url"],
json={"inputs": args}, headers=headers,
timeout=float(ep["spec"].get("timeout") or 15))
except requests.RequestException as e:
raise HTTPException(502, f"模型端点调用失败:{str(e)[:200]}") from e
if resp.status_code >= 400:
raise HTTPException(502, f"模型端点返回 {resp.status_code}:{resp.text[:200]}")
try:
body = resp.json()
except ValueError as e:
raise HTTPException(502, "模型端点没有返回 JSON") from e
data = _pick(body, spec.get("result_path") or "") if spec.get("result_path") else body
outs = spec.get("outputs") or []
if outs and isinstance(data, dict):
result = {o["name"]: data.get(o["name"]) for o in outs}
else:
result = data
return {"result": result, "inputs": args, "endpoint": ep["name"],
"summary": f"{fn.get('name')} → {result}"}
"""业务建模管道:一张经业务专家梳理过的业务文档 → 四元组草案 + 流程卡草稿。
输入(知识库文档 / 临时上传)
→ ① 行业路由:选一个行业模板当先验(只帮助命名,不强加内容)
→ ① 数据对齐:已接入的数据表翻译成对象 / 关系(带表绑定),作为 LLM 转换的种子
→ ② LLM 转换:按四元组找积木,每条带出处(kernel/propose.from_documents);
文档里说的是同一张表时并进种子,草案一出来就绑好了表
→ ③ 规则深化:文字规则 / 决策表写成可求值的表达式与表格;指标写出取数表达式并在业务库实跑;
动作骨架补全成参数 + 前置条件 + 效果。确定性校验不过就不采用
→ ④ SOP 编排:从同一批文档蒸馏出可执行的流程卡草稿(sop/draft)
→ ⑤ 建草稿:汇总成四列草案(对象 / 关系 / 函数 / 动作),人审核微调后采纳
每次运行存一条 `onto_model_run`,阶段进度实时写回,页面刷新也不丢。
AI 只产出草案:积木进审核队列,流程卡是草稿,都要人确认、再经变更提案发布才生效。
"""
from __future__ import annotations
import logging
import re
import tempfile
from pathlib import Path
from typing import Iterator
from fastapi import HTTPException
from sqlalchemy import select
from ..core import identity, llm
from ..core.dbx import iso, jdump, jload, new_id, session
from ..governance import audit, llmlog, review
from . import propose, schema, service, templates
from .models import ModelRun
log = logging.getLogger(__name__)
STAGES = [
{"key": "route", "label": "行业路由", "desc": "识别行业,选参考模板作为命名先验"},
{"key": "data", "label": "数据对齐", "desc": "读取已接入的数据表,对象与关系直接绑定到表"},
{"key": "convert", "label": "LLM 转换", "desc": "按四元组抽取对象、关系、函数、动作,带出处"},
{"key": "deepen", "label": "规则深化", "desc": "文字规则 → 可求值表达式 / 决策表,确定性校验"},
{"key": "sop", "label": "SOP 编排", "desc": "蒸馏可执行的流程卡草稿"},
{"key": "draft", "label": "建草稿", "desc": "汇总四元组草案,等人审核采纳"},
]
MAX_DEEPEN = 12
MAX_SOPS = 5
def _ws() -> str:
return identity.current().workspace
def _source(run_id: str) -> str:
return f"modeling:{run_id}"
def _dict(r: ModelRun, full: bool = False) -> dict:
inputs = jload(r.inputs_json, {}) or {}
out = {"id": r.id, "title": r.title, "status": r.status, "job_id": r.job_id, "error": r.error or "",
"options": jload(r.options_json, {}) or {}, "stages": jload(r.stages_json, []) or [],
"counts": jload(r.counts_json, {}) or {}, "created_by": r.created_by,
"created_at": iso(r.created_at), "updated_at": iso(r.updated_at),
"inputs": {"doc_ids": inputs.get("doc_ids") or [],
"files": [f["name"] for f in inputs.get("files") or []],
"chunks": len(inputs.get("chunks") or [])}}
if full:
out["sop_ids"] = inputs.get("sop_ids") or []
return out
def _load(run_id: str) -> ModelRun:
with session() as s:
r = s.get(ModelRun, run_id)
if r is None or r.workspace != _ws():
raise HTTPException(404, "建模记录不存在")
s.expunge(r)
return r
def list_runs() -> list[dict]:
with session() as s:
rows = s.scalars(select(ModelRun).where(ModelRun.workspace == _ws())
.order_by(ModelRun.created_at.desc())).all()
return [_dict(r) for r in rows]
def get(run_id: str) -> dict:
"""运行记录 + 本次草案(按四种积木分列)+ 流程卡草稿。"""
out = _dict(_load(run_id), full=True)
items = review.list_items(status="", source=_source(run_id), limit=1000)["items"]
cols: dict[str, list] = {"object_type": [], "link_type": [], "function": [], "action": [], "other": []}
for it in items:
p = it["payload"] or {}
k = p.get("kind") if it["kind"] == "concept_create" else "other"
cols.setdefault(k if k in cols else "other", []).append(it)
out["items"] = cols
from ..sop import service as sop_service
sops = []
for sid in out.pop("sop_ids"):
try:
d = sop_service.get(sid)
sops.append({k: d[k] for k in ("id", "title", "description", "status", "step_count")})
except HTTPException:
continue
out["sops"] = sops
return out
# ---------------- 输入 ----------------
def _upload_chunks(run_id: str, files: list[tuple[str, bytes]]) -> tuple[list[dict], list[dict]]:
"""临时上传:只解析、切块,不进知识库,也不抽图谱。"""
from ..ingest.chunk import chunk_text
from ..ingest.parse import ParseError, parse_file
chunks, meta = [], []
tag = run_id.split("_")[-1][:6]
for i, (name, raw) in enumerate(files):
suffix = Path(name).suffix.lower() or ".txt"
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / f"upload{suffix}"
path.write_bytes(raw)
try:
doc = parse_file(path)
except ParseError as e:
raise HTTPException(400, f"「{name}」解析失败:{e}") from e
for n, c in enumerate(chunk_text(doc.text, 0)):
c["id"] = f"u{tag}{i}:c{n}"
c["heading"] = c.get("heading") or name
c["doc_id"] = 0
chunks.append({k: c[k] for k in ("id", "heading", "text", "doc_id")})
meta.append({"name": name, "size": len(raw)})
return chunks, meta
def _doc_chunks(doc_ids: list[int]) -> list[dict]:
from ..api import deps
want = {int(x) for x in doc_ids}
return [c for c in deps.index().chunks.records if c.get("doc_id") in want]
def _default_ds_ids() -> list[int]:
"""当前本体可见、已经内省过的数据源。"""
from ..text2sql import semantic
return [d["id"] for d in semantic.list_datasources() if d.get("last_introspect_at")]
def create(title: str, *, doc_ids: list[int] | None = None, files: list[tuple[str, bytes]] | None = None,
template: str = "", stages: list[str] | None = None, ds_ids: list[int] | None = None) -> dict:
"""ds_ids:参与「数据对齐」的数据源;None = 当前本体下所有已内省的数据源。"""
run_id = new_id("mr")
up_chunks, up_meta = _upload_chunks(run_id, files or [])
if not doc_ids and not up_chunks:
raise HTTPException(422, "请选择知识库文档或上传业务文档")
keys = [s["key"] for s in STAGES]
chosen = [k for k in (stages or keys) if k in keys]
for must in ("convert", "draft"):
if must not in chosen:
chosen.append(must)
stage_rows = [{**s, "status": "pending" if s["key"] in chosen else "skipped", "log": [],
"counts": {}} for s in STAGES]
actor = identity.current()
with session() as s:
s.add(ModelRun(id=run_id, workspace=actor.workspace, title=(title or "业务建模")[:255],
inputs_json=jdump({"doc_ids": list(doc_ids or []), "files": up_meta,
"chunks": up_chunks}),
options_json=jdump({"template": template or "", "stages": chosen,
"ds_ids": _default_ds_ids() if ds_ids is None else ds_ids}),
stages_json=jdump(stage_rows), status="draft", created_by=actor.id))
s.commit()
audit.record("modeling.create", "model_run", run_id, f"新建业务建模「{title}」")
return _dict(_load(run_id))
def start(run_id: str) -> dict:
r = _load(run_id)
if r.status == "running":
raise HTTPException(409, "这次建模正在运行")
from ..jobs.queue import submit_background
try:
job_id = submit_background("modeling", lambda: execute(run_id))
except RuntimeError as e:
raise HTTPException(503, str(e)) from e
with session() as s:
row = s.get(ModelRun, run_id)
row.job_id = job_id
row.status = "running"
row.error = ""
s.commit()
return _dict(_load(run_id))
def delete(run_id: str) -> None:
_load(run_id)
with session() as s:
s.delete(s.get(ModelRun, run_id))
s.commit()
# ---------------- 执行 ----------------
class _Stages:
"""阶段状态落库:每条日志都写回 stages_json,前端轮询运行记录即可看到进度。"""
def __init__(self, run_id: str):
self.run_id = run_id
self.rows = jload(_load(run_id).stages_json, []) or []
def _save(self) -> None:
with session() as s:
row = s.get(ModelRun, self.run_id)
row.stages_json = jdump(self.rows)
s.commit()
def row(self, key: str) -> dict:
return next(r for r in self.rows if r["key"] == key)
def active(self, key: str) -> bool:
return self.row(key)["status"] != "skipped"
def set(self, key: str, status: str, msg: str = "", **counts) -> None:
r = self.row(key)
r["status"] = status
if msg:
r["log"] = (r["log"] + [msg])[-30:]
if counts:
r["counts"] = {**r["counts"], **counts}
self._save()
def _finish(run_id: str, status: str, error: str = "", counts: dict | None = None) -> None:
with session() as s:
row = s.get(ModelRun, run_id)
row.status = status
row.error = error[:2000]
if counts is not None:
row.counts_json = jdump(counts)
s.commit()
def execute(run_id: str) -> Iterator[dict]:
st = _Stages(run_id)
run = _load(run_id)
inputs = jload(run.inputs_json, {}) or {}
opts = jload(run.options_json, {}) or {}
chunks = _doc_chunks(inputs.get("doc_ids") or []) + (inputs.get("chunks") or [])
chunks = [c for c in chunks if (c.get("text") or "").strip()]
if not chunks:
_finish(run_id, "failed", "没有可用的文档片段:知识库文档要先完成解析")
yield {"stage": "error", "error": "没有可用的文档片段"}
return
try:
hint = ""
if st.active("route"):
st.set("route", "running", f"共 {len(chunks)} 个片段")
tpl, why = _route(chunks, opts.get("template") or "")
hint = _template_hint(tpl) if tpl else ""
st.set("route", "done", f"参考模板:{tpl or '无(按文档原样建模)'}{(',' + why) if why else ''}",
template=tpl or "")
yield {"stage": "route", "progress": 5, "message": f"行业路由:{tpl or '无'}"}
seed: list[dict] = []
if st.active("data"):
st.set("data", "running")
for ds_id in opts.get("ds_ids") or []:
try:
seed += propose.datasource_proposals(int(ds_id))
except Exception as e: # noqa: BLE001
st.set("data", "running", f"数据源 #{ds_id} 读取失败:{str(e)[:120]}")
objs = [p["name"] for p in seed if p["kind"] == "object_type"]
links = sum(1 for p in seed if p["kind"] == "link_type")
st.set("data", "done", f"{len(objs)} 张表 → 对象({'、'.join(objs[:8])}),{links} 条表间关联"
if seed else "没有已内省的数据表:对象先不绑定,之后在对象页绑定", tables=len(objs), joins=links)
yield {"stage": "data", "progress": 8, "message": f"数据对齐:{len(objs)} 张表"}
st.set("convert", "running")
result = {}
for ev in propose.from_documents(chunks, source=_source(run_id), hint=hint, seed=seed):
if ev.get("message"):
st.set("convert", "running", ev["message"])
if ev.get("stage") == "done":
result = ev.get("result") or {}
yield {**ev, "stage": "convert", "progress": 5 + int((ev.get("progress") or 0) * 0.55)}
st.set("convert", "done", f"提议 {result.get('proposed', 0)} 块新积木({result.get('bound', 0)} 块已绑定数据表)、"
f"{result.get('conflicts', 0)} 个冲突",
**{k: v for k, v in result.items() if isinstance(v, int)})
if st.active("deepen"):
st.set("deepen", "running")
note = lambda m: st.set("deepen", "running", m) # noqa: E731
n, tried = _deepen(run_id, note)
bound, btried = _bind_metrics(run_id, note)
acts, atried = _complete_actions(run_id, note)
st.set("deepen", "done", f"深化 {n}/{tried} 条规则与决策表,绑定 {bound}/{btried} 个指标的取数表达式,"
f"补全 {acts}/{atried} 个动作", deepened=n, tried=tried,
metrics_bound=bound, actions_completed=acts)
yield {"stage": "deepen", "progress": 75, "message": f"规则深化 {n} 条"}
if st.active("sop"):
st.set("sop", "running")
sop_ids = _sops(chunks, lambda m: st.set("sop", "running", m), run_id)
with session() as s:
row = s.get(ModelRun, run_id)
inp = jload(row.inputs_json, {}) or {}
inp["sop_ids"] = sop_ids
row.inputs_json = jdump(inp)
s.commit()
st.set("sop", "done", f"生成 {len(sop_ids)} 张流程卡草稿", sops=len(sop_ids))
yield {"stage": "sop", "progress": 92, "message": f"流程卡 {len(sop_ids)} 张"}
g = get(run_id)
counts = {k: len(v) for k, v in g["items"].items()}
counts["sop"] = len(g["sops"])
st.set("draft", "done", "四元组草案:" + "、".join(
f"{schema.KINDS[k]['label']} {counts[k]}" for k in schema.KINDS), **counts)
_finish(run_id, "done", counts=counts)
audit.record("modeling.done", "model_run", run_id, f"业务建模完成:{counts}")
yield {"stage": "done", "progress": 100, "message": "建模完成", "result": counts}
except Exception as e: # noqa: BLE001
log.exception("业务建模 %s 失败", run_id)
for r in st.rows:
if r["status"] == "running":
r["status"] = "failed"
st._save()
_finish(run_id, "failed", str(getattr(e, "detail", e))[:500])
yield {"stage": "error", "error": str(getattr(e, "detail", e))[:300]}
# ---------------- ① 行业路由 ----------------
ROUTE_PROMPT = """下面是一份业务文档的章节标题。从候选行业模板里选一个最贴近的,没有合适的就选 none。
候选:
{cands}
章节:
{heads}
输出 JSON:{{"template":"模板 id 或 none","reason":"一句话"}}"""
def _route(chunks: list[dict], chosen: str) -> tuple[str, str]:
tpls = {t["id"]: t for t in templates.list_templates()}
if chosen:
if chosen not in tpls and chosen != "none":
raise HTTPException(422, f"模板「{chosen}」不存在")
return ("" if chosen == "none" else chosen), "人工指定"
cands = [t for t in tpls.values() if t["id"] != "generic_starter"]
if not cands:
return "", ""
heads = list(dict.fromkeys(c.get("heading") or "" for c in chunks))[:60]
try:
with llmlog.feature("modeling_route"):
res = llm.chat_json([{"role": "user", "content": ROUTE_PROMPT.format(
cands="\n".join(f"- {t['id']}:{t['name']},{t['description']}" for t in cands),
heads="\n".join(f"- {h}" for h in heads if h))}], temperature=0)
except Exception as e: # noqa: BLE001
log.warning("行业路由失败:%s", e)
return "", ""
tid = str((res or {}).get("template") or "") if isinstance(res, dict) else ""
return (tid if tid in tpls else ""), str((res or {}).get("reason") or "") if isinstance(res, dict) else ""
def _template_hint(tid: str, limit: int = 120) -> str:
import yaml
p = templates.TEMPLATE_DIR / f"{tid}.yaml"
try:
doc = yaml.safe_load(p.read_text(encoding="utf-8")) or {}
except Exception: # noqa: BLE001
return ""
return "、".join(str(c.get("name")) for c in (doc.get("concepts") or [])[:limit] if c.get("name"))
# ---------------- ③ 规则深化 ----------------
DEEPEN_PROMPT = """把下面这条业务规则写成可执行的定义。
名称:{name}
类别:{category}
原文要点:{text}
说明:{desc}
- rule:写成 Python 风格表达式,变量用英文标识符,例如 actual >= target * 0.9;只能用算术、比较、and/or/not、
min/max/abs/round、if-else 表达式。输出 {{"expression":"...","params":["变量名"]}}
- decision:写成决策表。输出 {{"inputs":[{{"name":英文名,"label":中文}}],"outputs":[{{"name":英文名,"label":中文}}],
"rows":[{{"when":{{输入名:"> 3"}},"then":{{输出名:值}}}}]}}
原文信息不足以写出时输出 {{"skip":true}}。只输出 JSON。"""
def _deepen(run_id: str, note) -> tuple[int, int]:
items = review.list_items(status="pending", kind="concept_create", source=_source(run_id),
limit=500)["items"]
todo = []
for it in items:
p = it["payload"] or {}
spec = p.get("spec") or {}
if p.get("kind") != "function":
continue
cat = spec.get("category")
if (cat == "rule" and not spec.get("expression")) or (cat == "decision" and not spec.get("rows")):
todo.append(it)
done = 0
for it in todo[:MAX_DEEPEN]:
p = dict(it["payload"])
spec = dict(p.get("spec") or {})
try:
with llmlog.feature("modeling_deepen"):
res = llm.chat_json([{"role": "user", "content": DEEPEN_PROMPT.format(
name=p["name"], category=spec.get("category"), text=spec.get("text") or "",
desc=p.get("description") or "")}], temperature=0.1)
except Exception as e: # noqa: BLE001
note(f"「{p['name']}」深化失败:{str(e)[:80]}")
continue
if not isinstance(res, dict) or res.get("skip"):
note(f"「{p['name']}」原文信息不足,保留文字描述")
continue
try:
new_spec = schema.normalize_spec("function", {**spec, **res})
except schema.SpecError as e:
note(f"「{p['name']}」深化结果没通过校验({e}),不采用")
continue
p["spec"] = new_spec
p["deepened"] = True
review.update_payload(it["id"], p)
done += 1
note(f"「{p['name']}」已写成{'表达式' if spec.get('category') == 'rule' else '决策表'}")
return done, min(len(todo), MAX_DEEPEN)
METRIC_PROMPT = """把下面这个指标写成一条 SQL 聚合表达式,基于数据表 {table}(方言 {dialect})。
指标:{name}(单位:{unit})
口径:{formula}
说明:{desc}
表的列(列名 类型 含义):
{columns}
要求:
- expression 是 SELECT 里的一个聚合表达式,只能用这张表的列,如 SUM(on_hand + in_transit)、
AVG(CASE WHEN a < b THEN 1.0 ELSE 0 END)、COUNT(*)。单位是 % 时算成 0~100 的数。
- 这张表的列算不出这个口径(需要别的表)时输出 {{"skip": true, "reason": "一句话"}}。
- dimensions:可以按哪些列拆分,{{属性名: 列名}},挑 2~4 个类别型的列(编号、状态、品类、城市等)。
- time_column:口径涉及时间窗口且表里有日期列时填,否则空串。
- object_key_column:按单个对象取数用的键列,一般是主键。
- filters:口径里固定的过滤条件(SQL 片段数组,如 "status = '已到货'"),没有就空数组。
只输出 JSON:{{"expression":"...","dimensions":{{}},"time_column":"","object_key_column":"","filters":[]}}"""
def _run_objects(run_id: str) -> dict[str, dict]:
"""这次草案 + 已有积木里的对象:名称 / 别名 → {name, properties, binding}。"""
out: dict[str, dict] = {}
for c in service.list_concepts(kind="object_type", limit=300):
full = service.get_concept(c["id"])
b = next((x for x in full.get("bindings") or [] if x["target_kind"] == "table"), None)
rec = {"name": c["name"], "id": c["id"], "properties": (full.get("spec") or {}).get("properties") or [],
"binding": b, "item": None}
for n in [c["id"], c["name"], *(c.get("synonyms") or [])]:
out[n] = rec
items = review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=500)["items"]
for it in items:
p = it["payload"] or {}
if p.get("kind") != "object_type":
continue
b = next((x for x in p.get("bindings") or [] if x.get("target_kind") == "table"), None)
rec = {"name": p["name"], "id": "", "properties": (p.get("spec") or {}).get("properties") or [],
"binding": b, "item": it}
for n in [p["name"], *(p.get("synonyms") or [])]:
out[n] = rec
return out
def _try_metric_sql(ds_id: int, table: str, ref: dict) -> str:
"""在业务库上真跑一次,跑得通才采用。返回错误信息,空串 = 通过。"""
from ..text2sql import executor, semantic
from .sqlutil import ident, to_dialect
ds = semantic.get_datasource(ds_id) or {}
sql = f"SELECT {ref['expression']} AS v FROM {ident(table)}"
if ref.get("filters"):
sql += " WHERE " + " AND ".join(f"({f})" for f in ref["filters"])
out = executor.execute(ds_id, to_dialect(sql, ds.get("ds_type") or "mysql"), ds.get("ds_type") or "mysql")
return "" if out.ok else str(out.error or "执行失败")[:300]
def _bind_metrics(run_id: str, note) -> tuple[int, int]:
"""聚合函数只有口径文字、没有取数方式。对象已经绑了表,就让 AI 写出取数表达式并实跑校验,
省掉「人去绑定页手写 SQL」这一步;写不出或跑不通的保持未绑定,由人补。"""
from ..text2sql import semantic
objs = _run_objects(run_id)
items = review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=500)["items"]
todo = [it for it in items if (it["payload"] or {}).get("kind") == "function"
and ((it["payload"].get("spec") or {}).get("category") == "aggregate")
and not any(b.get("target_kind") == "metric_expr" for b in it["payload"].get("bindings") or [])]
done = 0
for it in todo[:MAX_DEEPEN]:
p = dict(it["payload"])
spec = p.get("spec") or {}
obj = objs.get(str(spec.get("object_type") or ""))
if not obj or not obj.get("binding"):
note(f"「{p['name']}」的对象没有绑定数据表,取数表达式留给人补")
continue
b = obj["binding"]
table = b["ref"]["table"]
ds = semantic.get_datasource(int(b["ds_id"])) or {}
cols = {c["name"]: c for m in semantic.models_with_columns(int(b["ds_id"]))
if (m.get("physical_table") or m["name"]) == table for c in m.get("columns") or []}
col_text = "\n".join(f"- {c.get('physical_column') or n} {c.get('data_type')} {c.get('description') or ''}"
for n, c in cols.items())
msgs = [{"role": "user", "content": METRIC_PROMPT.format(
table=table, dialect=ds.get("ds_type") or "mysql", name=p["name"], unit=spec.get("unit") or "",
formula=spec.get("formula_text") or "", desc=p.get("description") or "", columns=col_text)}]
ref: dict = {}
err = ""
for attempt in (1, 2):
try:
with llmlog.feature("modeling_metric"):
res = llm.chat_json(msgs, temperature=0.1)
except Exception as e: # noqa: BLE001
err = str(e)[:120]
break
if not isinstance(res, dict) or res.get("skip"):
err = (res or {}).get("reason") or "这张表算不出这个口径" if isinstance(res, dict) else "输出无效"
break
try:
ref = schema.normalize_binding("metric_expr", {**res, "base_table": table})
except schema.SpecError as e:
err = str(e)
else:
err = _try_metric_sql(int(b["ds_id"]), table, ref)
if not err:
break
msgs += [{"role": "assistant", "content": jdump(res)},
{"role": "user", "content": f"执行报错:{err}\n请修正后输出完整 JSON。"}]
if err or not ref:
note(f"「{p['name']}」没绑上取数表达式:{err}")
continue
p["bindings"] = [*(p.get("bindings") or []),
{"ds_id": int(b["ds_id"]), "target_kind": "metric_expr", "ref": ref}]
review.update_payload(it["id"], p)
done += 1
note(f"「{p['name']}」= {ref['expression']}(已在业务库实跑通过)")
return done, min(len(todo), MAX_DEEPEN)
def _complete_actions(run_id: str, note) -> tuple[int, int]:
"""文档只说明了「要有这个动作」。对象和系统效果都已知,就让 AI 写出参数、前置条件和效果,
过一遍动作校验再采用;用到 object.write 的属性顺手标成可写,否则执行时才发现写不进去。"""
from ..governance import roles
from . import draft
objs = _run_objects(run_id)
items = review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=500)["items"]
todo = [it for it in items if (it["payload"] or {}).get("kind") == "action"
and (it["payload"].get("spec") or {}).get("_stub")]
if not todo:
return 0, 0
seen, lines = set(), []
for rec in objs.values():
if id(rec) in seen:
continue
seen.add(id(rec))
props = "、".join(f"{x['name']}({x.get('display_name') or x.get('description') or ''})"
for x in rec["properties"][:30])
lines.append(f"- {rec['name']}:{props}")
guide = (draft.GUIDES["action"].replace("{tools}", draft._tools_text())
.replace("{roles}", "、".join(roles.names()) or "(无,可留空)"))
system = draft.GENERATE_SYSTEM.format(guide=guide, objects="\n".join(lines) or "(无)",
functions=draft._functions_text())
done = 0
for it in todo[:MAX_DEEPEN]:
p = dict(it["payload"])
msgs = [{"role": "system", "content": system},
{"role": "user", "content": f"动作:{p['name']}\n说明:{p.get('description') or ''}\n"
f"原文要点:{(p.get('spec') or {}).get('text') or ''}"}]
spec, err = {}, ""
for attempt in (1, 2, 3):
try:
with llmlog.feature("modeling_action"):
res = llm.chat_json(msgs, temperature=0.1)
except Exception as e: # noqa: BLE001
err = str(e)[:120]
break
spec = dict((res or {}).get("spec") or {}) if isinstance(res, dict) else {}
err = _check_action_refs(spec, objs)
if not err:
_open_writes(spec, objs)
try:
schema.normalize_spec("action", spec)
break
except schema.SpecError as e:
err = str(e)
if err:
msgs += [{"role": "assistant", "content": jdump(res)},
{"role": "user", "content": f"校验失败:{err}\n请修正后输出完整 JSON。"}]
if err or not spec:
note(f"「{p['name']}」没能补全:{err}(采纳后在动作页补)")
continue
p["spec"] = spec
p["completed"] = True
review.update_payload(it["id"], p)
done += 1
tools = "、".join(e.get("tool", "") for e in spec.get("effects") or [])
note(f"「{p['name']}」已补全:{len(spec.get('params') or [])} 个参数,效果 {tools}")
return done, min(len(todo), MAX_DEEPEN)
def _resolve_obj(ref: str, objs: dict[str, dict]) -> dict | None:
"""AI 引用对象时常用英文 / 表名(supplier、otlgt3_dm_supplier):按名称、别名、表名后缀找回来。"""
if not ref:
return None
if ref in objs:
return objs[ref]
low = ref.lower()
for rec in objs.values():
table = str(((rec.get("binding") or {}).get("ref") or {}).get("table") or "").lower()
if table and (table == low or table.endswith("_" + low)):
return rec
return None
def _check_action_refs(spec: dict, objs: dict[str, dict]) -> str:
"""对象名换成规范名称;写 / 建的属性必须真的存在。返回错误(喂回给 AI 修),空串 = 通过。"""
if spec.get("target_type"):
rec = _resolve_obj(str(spec["target_type"]), objs)
if rec is None:
return f"找不到对象「{spec['target_type']}」,只能用这些对象:{'、'.join(sorted({r['name'] for r in objs.values()}))}"
spec["target_type"] = rec["name"]
props = {p["name"] for p in rec["properties"]}
text = " ".join(str(c.get("expression") or "") for c in spec.get("criteria") or []) + jdump(spec.get("effects"))
ghost = sorted({m for m in re.findall(r"obj\.([A-Za-z_一-鿿][\w一-鿿]*)", text)
if m not in props and m not in ("key", "label")})
if ghost:
return (f"{rec['name']} 没有属性 {'、'.join(ghost)}(obj 只能取它自己的属性:{'、'.join(sorted(props))});"
f"取不到的信息就改成参数,或者删掉这条条件")
for e in spec.get("effects") or []:
args = e.get("args") or {}
if e.get("tool") not in ("object.write", "object.create"):
continue
rec = _resolve_obj(str(args.get("object_type") or spec.get("target_type") or ""), objs)
if rec is None:
return f"效果 {e.get('tool')} 的对象「{args.get('object_type')}」不存在"
args["object_type"] = rec["name"]
names = [p["name"] for p in rec["properties"]]
want = [str(args.get("property") or "")] if e["tool"] == "object.write" else list(args.get("values") or {})
bad = [w for w in want if w not in names]
if bad:
return f"{rec['name']} 没有属性 {'、'.join(bad)},可用属性:{'、'.join(names)}"
return ""
def _open_writes(spec: dict, objs: dict[str, dict]) -> None:
"""动作要写的属性标成可写(草案里的对象改草案,已有对象改工作副本),校验才能过。"""
for e in spec.get("effects") or []:
if e.get("tool") != "object.write":
continue
args = e.get("args") or {}
rec = objs.get(str(args.get("object_type") or spec.get("target_type") or ""))
prop = str(args.get("property") or "")
if not rec or not prop:
continue
hit = next((x for x in rec["properties"] if x["name"] == prop), None)
if hit is None or hit.get("is_writable"):
continue
hit["is_writable"] = True
if rec["item"] is not None:
payload = dict(rec["item"]["payload"])
payload["spec"] = {**(payload.get("spec") or {}), "properties": rec["properties"]}
review.update_payload(rec["item"]["id"], payload)
elif rec["id"]:
service.update_concept(rec["id"], spec={**(service.get_concept(rec["id"]).get("spec") or {}),
"properties": rec["properties"]})
# ---------------- ④ SOP 编排 ----------------
SOP_TOPICS_PROMPT = """下面是业务文档的片段(方括号里是片段编号)。找出其中描述了「有先后步骤、有角色分工、有判断分支」的业务流程,
最多 {n} 个,只挑文档里写得比较完整的。
{text}
只挑跨多个步骤的流程(如每日巡检、月度对账);单个操作(创建某单据、标记某状态)是动作,不要当成流程。
输出 JSON:{{"processes":[{{"title":"流程名","chunks":["片段编号"]}}]}},没有就输出空数组。"""
def _draft_catalog(run_id: str) -> dict:
"""这次草案里的积木(还没采纳):流程卡按这些名字引用,采纳发布后就能跑。"""
items = review.list_items(status="pending", kind="concept_create", source=_source(run_id), limit=500)["items"]
by: dict[str, list[str]] = {"actions": [], "metrics": [], "rules": [], "object_types": []}
for it in items:
p = it["payload"] or {}
sp = p.get("spec") or {}
if p.get("kind") == "action" and not sp.get("_stub"):
by["actions"].append(f"- {p['name']}:{p.get('description') or ''} 参数:{[x.get('name') for x in sp.get('params') or []]}"
+ (f" 作用对象:{sp.get('target_type')}" if sp.get("target_type") else ""))
elif p.get("kind") == "function" and sp.get("category") == "aggregate":
by["metrics"].append(p["name"])
elif p.get("kind") == "function" and sp.get("category") in ("rule", "decision"):
by["rules"].append(p["name"])
elif p.get("kind") == "object_type":
by["object_types"].append(p["name"])
return {k: ("\n" if k == "actions" else "、").join(v) for k, v in by.items()}
def _sops(chunks: list[dict], note, run_id: str = "") -> list[str]:
from ..sop import draft as sop_draft
extra = _draft_catalog(run_id) if run_id else None
text = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】{c['text'][:1500]}" for c in chunks[:80])
try:
with llmlog.feature("modeling_sop"):
res = llm.chat_json([{"role": "user", "content": SOP_TOPICS_PROMPT.format(
n=MAX_SOPS, text=llm.truncate_to_tokens(text, 12000))}], temperature=0.1)
except Exception as e: # noqa: BLE001
note(f"识别流程失败:{str(e)[:100]}")
return []
by_id = {c["id"]: c for c in chunks}
out = []
for proc in ((res or {}).get("processes") or [])[:MAX_SOPS] if isinstance(res, dict) else []:
title = str((proc or {}).get("title") or "").strip()
if not title:
continue
sub = [by_id[x] for x in proc.get("chunks") or [] if x in by_id] or chunks[:8]
try:
d = sop_draft.generate(title, chunks=sub[:8], extra_catalog=extra)
out.append(d["id"])
note(f"流程卡「{d['title']}」{d['step_count']} 步")
except HTTPException as e:
note(f"「{title}」起草失败:{e.detail}")
return out
# ---------------- 导出 ----------------
def export_md(run_id: str) -> str:
g = get(run_id)
lines = [f"# {g['title']}", "", f"> 业务建模草案 · {g['created_at']} · 状态 {g['status']}", ""]
for k, meta in schema.KINDS.items():
items = g["items"].get(k) or []
lines += [f"## {meta['label']}({len(items)})", ""]
for it in items:
p = it["payload"] or {}
spec = p.get("spec") or {}
head = f"- **{p.get('name')}**"
if k == "function":
head += f"({schema.FN_CATEGORIES.get(spec.get('category') or '', {}).get('label', '')})"
if it["status"] != "pending":
head += f" `{'已采纳' if it['status'] == 'accepted' else '已驳回'}`"
lines.append(head + (f":{p.get('description')}" if p.get("description") else ""))
if k == "object_type":
props = [x.get("name") for x in spec.get("properties") or []]
if props:
lines.append(f" - 属性:{'、'.join(props)}")
elif k == "link_type":
lines.append(f" - {spec.get('from_type')} → {spec.get('to_type')}({spec.get('cardinality')})")
elif spec.get("expression"):
lines.append(f" - 表达式:`{spec['expression']}`")
elif spec.get("formula_text"):
lines.append(f" - 公式:{spec['formula_text']}")
for e in (p.get("evidence") or [])[:2]:
lines.append(f" - 出处:{e.get('heading') or ''} {(e.get('snippet') or '')[:80]}")
lines.append("")
if g["sops"]:
lines += [f"## 流程卡({len(g['sops'])})", ""]
lines += [f"- **{s['title']}**({s['step_count']} 步):{s['description']}" for s in g["sops"]]
return "\n".join(lines) + "\n"
...@@ -90,15 +90,86 @@ class ObjectEdit(Base): ...@@ -90,15 +90,86 @@ class ObjectEdit(Base):
prev_json: Mapped[str] = mapped_column(Text, default="null") prev_json: Mapped[str] = mapped_column(Text, default="null")
action_run_id: Mapped[str] = mapped_column(String(64), default="") action_run_id: Mapped[str] = mapped_column(String(64), default="")
active: Mapped[int] = mapped_column(Integer, default=1) active: Mapped[int] = mapped_column(Integer, default=1)
# overlay:写在写回层、读取时覆盖;db:已写进业务库(只留痕、可撤销);create:在业务库新建的行
mode: Mapped[str] = mapped_column(String(16), default="overlay")
created_by: Mapped[str] = mapped_column(String(128), default="") created_by: Mapped[str] = mapped_column(String(128), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now) created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
class InstanceCache(Base): class InstanceCache(Base):
"""对象实例名录(从绑定表同步的 key/label),给问句里点名的具体对象(某个客户、某个网点)做链接用。""" """对象骨架(数据管道从绑定表同步):主键、显示名、关系键列与维度属性。
用途只有两个:问句里点名具体对象时做链接;在关系边上做多跳遍历 / 影响分析。
业务明细永远实时查业务库,这里不存。
"""
__tablename__ = "onto_instance" __tablename__ = "onto_instance"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True) workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
concept_id: Mapped[str] = mapped_column(String(64), index=True) concept_id: Mapped[str] = mapped_column(String(64), index=True)
obj_key: Mapped[str] = mapped_column(String(255)) obj_key: Mapped[str] = mapped_column(String(255))
label: Mapped[str] = mapped_column(String(255), index=True) label: Mapped[str] = mapped_column(String(255), index=True)
# {"p": {属性: 值}, "j": {关系键列: 值}}
props_json: Mapped[str] = mapped_column(Text, default="{}")
synced_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
class LinkEdge(Base):
"""关系实例:同步时按关系的 join 绑定物化出来,遍历只走这张表。"""
__tablename__ = "onto_link_edge"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
link_id: Mapped[str] = mapped_column(String(64), index=True)
from_type: Mapped[str] = mapped_column(String(64), index=True)
from_key: Mapped[str] = mapped_column(String(255), index=True)
to_type: Mapped[str] = mapped_column(String(64), index=True)
to_key: Mapped[str] = mapped_column(String(255), index=True)
class Workspace(Base):
"""本体空间:一个行业 / 一个业务域一套本体,积木、版本、动作、审计都按空间隔离。"""
__tablename__ = "onto_workspace"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
display_name: Mapped[str] = mapped_column(String(255), default="")
description: Mapped[str] = mapped_column(Text, default="")
industry: Mapped[str] = mapped_column(String(64), default="")
status: Mapped[str] = mapped_column(String(16), default="active") # active / archived
created_by: Mapped[str] = mapped_column(String(128), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now, onupdate=now)
class Pipeline(Base):
"""数据管道:把一个对象类型的骨架从业务库同步进来(手动 / 定时)。"""
__tablename__ = "onto_pipeline"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
object_type_id: Mapped[str] = mapped_column(String(64), index=True)
schedule: Mapped[str] = mapped_column(String(16), default="manual") # manual / hourly / daily
row_limit: Mapped[int] = mapped_column(Integer, default=20000)
enabled: Mapped[int] = mapped_column(Integer, default=1)
status: Mapped[str] = mapped_column(String(16), default="idle") # idle / running / ok / failed
last_rows: Mapped[int] = mapped_column(Integer, default=0)
last_edges: Mapped[int] = mapped_column(Integer, default=0)
last_error: Mapped[str] = mapped_column(Text, default="")
last_run_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
last_duration_ms: Mapped[int] = mapped_column(Integer, default=0)
created_by: Mapped[str] = mapped_column(String(128), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
class ModelRun(Base):
"""一次业务建模:输入文档 → 行业路由 → LLM 转换 → 规则深化 → SOP 编排 → 四元组草案。"""
__tablename__ = "onto_model_run"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
title: Mapped[str] = mapped_column(String(255), default="")
inputs_json: Mapped[str] = mapped_column(_LONGTEXT, default="{}") # doc_ids / 临时上传文件与片段
options_json: Mapped[str] = mapped_column(Text, default="{}")
stages_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]")
counts_json: Mapped[str] = mapped_column(Text, default="{}")
status: Mapped[str] = mapped_column(String(16), default="draft", index=True) # draft/running/done/failed
job_id: Mapped[int] = mapped_column(Integer, default=0)
error: Mapped[str] = mapped_column(Text, default="")
created_by: Mapped[str] = mapped_column(String(128), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now, onupdate=now)
"""对象实例:按 ObjectType 的数据绑定从业务库读(只读),叠加写回层。 """对象实例:按 ObjectType 的数据绑定从业务库读,叠加写回层。
业务库永远只读 —— Action 对对象的修改只写 `onto_object_edit`,读取时按属性覆盖。 写有两种模式,按数据源的「写回业务库」开关(extra.writeback)决定:
所有 SQL 都经 text2sql.executor(同一套 guard + 行数上限 + 超时),不另开执行通道。 - 关(默认):Action 的修改只写 `onto_object_edit`,读取时按属性覆盖,业务库不动;
- 开:审批通过的 Action 直接 UPDATE / INSERT 业务表(只限绑定过的表与列),
`onto_object_edit` 只留痕(mode=db / create),撤销时写回原值或删掉新建的行。
读取的 SQL 都经 text2sql.executor(同一套 guard + 行数上限 + 超时),不另开执行通道。
""" """
from __future__ import annotations from __future__ import annotations
...@@ -9,14 +12,14 @@ import logging ...@@ -9,14 +12,14 @@ import logging
from typing import Any from typing import Any
from fastapi import HTTPException from fastapi import HTTPException
from sqlalchemy import delete, select from sqlalchemy import select
from ..core import identity from ..core import identity
from ..core.dbx import iso, jdump, jload, session from ..core.dbx import iso, jdump, jload, session
from ..governance import audit from ..governance import audit
from . import service from . import service
from .models import InstanceCache, ObjectEdit from .models import InstanceCache, ObjectEdit
from .sqlutil import ident, jsonable, lit from .sqlutil import ident, jsonable, lit, to_dialect
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
...@@ -40,7 +43,7 @@ def _run(ds_id: int, sql: str) -> tuple[list[str], list[list[Any]]]: ...@@ -40,7 +43,7 @@ def _run(ds_id: int, sql: str) -> tuple[list[str], list[list[Any]]]:
ds = semantic.get_datasource(ds_id) ds = semantic.get_datasource(ds_id)
if ds is None: if ds is None:
raise HTTPException(422, f"数据源 {ds_id} 不存在") raise HTTPException(422, f"数据源 {ds_id} 不存在")
out = executor.execute(ds_id, sql, ds["ds_type"]) out = executor.execute(ds_id, to_dialect(sql, ds["ds_type"]), ds["ds_type"])
if not out.ok or out.result is None: if not out.ok or out.result is None:
raise HTTPException(422, f"查询失败:{out.error}") raise HTTPException(422, f"查询失败:{out.error}")
return out.result.columns, [[jsonable(v) for v in row] for row in out.result.rows] return out.result.columns, [[jsonable(v) for v in row] for row in out.result.rows]
...@@ -65,10 +68,25 @@ def _to_obj(ot: dict, ref: dict, cols: list[str], row: list[Any]) -> dict: ...@@ -65,10 +68,25 @@ def _to_obj(ot: dict, ref: dict, cols: list[str], row: list[Any]) -> dict:
props = {col2prop.get(k, k): v for k, v in raw.items()} props = {col2prop.get(k, k): v for k, v in raw.items()}
key = raw.get(ref["key_column"]) key = raw.get(ref["key_column"])
label = raw.get(ref.get("label_column") or "") if ref.get("label_column") else None label = raw.get(ref.get("label_column") or "") if ref.get("label_column") else None
if label in (None, "") and not ref.get("label_column"):
# 没有名称列:用关系键(xx_id)拼一个,比光秃秃的自增主键好认
fks = [str(v) for c, v in raw.items() if c != ref["key_column"] and c.lower().endswith("_id") and v is not None]
label = " · ".join(fks[:3]) or None
return {"type_id": ot["id"], "type_name": ot["name"], "key": "" if key is None else str(key), return {"type_id": ot["id"], "type_name": ot["name"], "key": "" if key is None else str(key),
"label": str(label) if label not in (None, "") else str(key), "properties": props} "label": str(label) if label not in (None, "") else str(key), "properties": props}
def _writeback(ds_id: int) -> bool:
from ..text2sql import semantic
ds = semantic.get_datasource(ds_id) or {}
return bool((ds.get("extra") or {}).get("writeback"))
def _connector(ds_id: int):
from ..text2sql import semantic
return semantic.connector_for(ds_id)
def _overlay(obj: dict) -> dict: def _overlay(obj: dict) -> dict:
edits = active_edits(obj["type_id"], obj["key"]) edits = active_edits(obj["type_id"], obj["key"])
if edits: if edits:
...@@ -107,34 +125,6 @@ def search(type_ref: str, q: str = "", limit: int = 20, offset: int = 0) -> list ...@@ -107,34 +125,6 @@ def search(type_ref: str, q: str = "", limit: int = 20, offset: int = 0) -> list
return [_overlay(_to_obj(ot, ref, cols, r)) for r in rows] return [_overlay(_to_obj(ot, ref, cols, r)) for r in rows]
def sync_instances(type_ref: str, limit: int = 5000) -> int:
"""把对象的 key/label 名录拉进本地,供问句里的实例链接使用。"""
ot = object_type(type_ref)
b = table_binding(ot)
ref = b["ref"]
label_col = ref.get("label_column") or ref["key_column"]
cols, rows = _run(b["ds_id"], f"SELECT {ident(ref['key_column'])}, {ident(label_col)} "
f"FROM {ident(ref['table'])} LIMIT {int(limit)}")
ws = identity.current().workspace
with session() as s:
s.execute(delete(InstanceCache).where(InstanceCache.workspace == ws,
InstanceCache.concept_id == ot["id"]))
seen = set()
for k, lab in rows:
if k is None:
continue
label = str(lab if lab not in (None, "") else k)[:255]
if (str(k), label) in seen:
continue
seen.add((str(k), label))
s.add(InstanceCache(workspace=ws, concept_id=ot["id"], obj_key=str(k)[:255],
label=label))
s.commit()
from . import linker
linker.invalidate()
return len(seen)
def instances(workspace: str) -> list[dict]: def instances(workspace: str) -> list[dict]:
with session() as s: with session() as s:
return [{"concept_id": r.concept_id, "key": r.obj_key, "label": r.label} return [{"concept_id": r.concept_id, "key": r.obj_key, "label": r.label}
...@@ -146,7 +136,7 @@ def instances(workspace: str) -> list[dict]: ...@@ -146,7 +136,7 @@ def instances(workspace: str) -> list[dict]:
def _edit_dict(e: ObjectEdit) -> dict: def _edit_dict(e: ObjectEdit) -> dict:
return {"id": e.id, "object_type": e.object_type, "object_key": e.object_key, return {"id": e.id, "object_type": e.object_type, "object_key": e.object_key,
"property": e.property, "value": jload(e.value_json, None), "property": e.property, "value": jload(e.value_json, None),
"prev": jload(e.prev_json, None), "action_run_id": e.action_run_id, "prev": jload(e.prev_json, None), "action_run_id": e.action_run_id, "mode": e.mode or "overlay",
"active": bool(e.active), "created_by": e.created_by, "created_at": iso(e.created_at)} "active": bool(e.active), "created_by": e.created_by, "created_at": iso(e.created_at)}
...@@ -155,7 +145,7 @@ def active_edits(type_id: str, key: str) -> list[dict]: ...@@ -155,7 +145,7 @@ def active_edits(type_id: str, key: str) -> list[dict]:
rows = s.scalars(select(ObjectEdit).where( rows = s.scalars(select(ObjectEdit).where(
ObjectEdit.workspace == identity.current().workspace, ObjectEdit.workspace == identity.current().workspace,
ObjectEdit.object_type == type_id, ObjectEdit.object_key == str(key), ObjectEdit.object_type == type_id, ObjectEdit.object_key == str(key),
ObjectEdit.active == 1).order_by(ObjectEdit.id)).all() ObjectEdit.active == 1, ObjectEdit.mode == "overlay").order_by(ObjectEdit.id)).all()
latest: dict[str, dict] = {} latest: dict[str, dict] = {}
for e in rows: for e in rows:
latest[e.property] = _edit_dict(e) latest[e.property] = _edit_dict(e)
...@@ -192,10 +182,18 @@ def write(type_ref: str, key: str, prop: str, value: Any, action_run_id: str = " ...@@ -192,10 +182,18 @@ def write(type_ref: str, key: str, prop: str, value: Any, action_run_id: str = "
raise HTTPException(422, f"「{prop}」只能取 {'/'.join(enum)}") raise HTTPException(422, f"「{prop}」只能取 {'/'.join(enum)}")
prev = current_value(ot["id"], key, prop) prev = current_value(ot["id"], key, prop)
actor = identity.current() actor = identity.current()
b = table_binding(ot)
mode = "overlay"
if _writeback(b["ds_id"]):
col = (b["ref"].get("columns") or {}).get(prop) or prop
n = _connector(b["ds_id"]).write_row(b["ref"]["table"], {col: value}, b["ref"]["key_column"], key)
if not n:
raise HTTPException(404, f"{ot['name']}「{key}」在业务库里不存在,未写回")
mode = "db"
with session() as s: with session() as s:
e = ObjectEdit(workspace=actor.workspace, object_type=ot["id"], object_key=str(key), e = ObjectEdit(workspace=actor.workspace, object_type=ot["id"], object_key=str(key),
property=prop, value_json=jdump(value), prev_json=jdump(prev), property=prop, value_json=jdump(value), prev_json=jdump(prev),
action_run_id=action_run_id, created_by=actor.id) action_run_id=action_run_id, created_by=actor.id, mode=mode)
s.add(e) s.add(e)
s.commit() s.commit()
out = _edit_dict(e) out = _edit_dict(e)
...@@ -205,11 +203,49 @@ def write(type_ref: str, key: str, prop: str, value: Any, action_run_id: str = " ...@@ -205,11 +203,49 @@ def write(type_ref: str, key: str, prop: str, value: Any, action_run_id: str = "
return out return out
def create(type_ref: str, values: dict[str, Any], action_run_id: str = "") -> dict:
"""在业务库新建一个对象(一行)。只能被 Tool `object.create` 调用,且数据源必须开了写回。"""
ot = object_type(type_ref)
b = table_binding(ot)
ref = b["ref"]
if not _writeback(b["ds_id"]):
raise HTTPException(422, f"「{ot['name']}」所在的数据源没有开启「写回业务库」,不能新建对象"
f"(在数据连接里编辑数据源,打开写回开关)")
cols = ref.get("columns") or {}
props = {p["name"] for p in (ot.get("spec") or {}).get("properties") or []}
unknown = [k for k in values if k not in props and k not in cols]
if unknown:
raise HTTPException(422, f"{ot['name']} 没有属性:{'、'.join(unknown)}")
row = {cols.get(k, k): v for k, v in values.items() if v is not None}
key = row.get(ref["key_column"])
_connector(b["ds_id"]).write_row(ref["table"], row)
actor = identity.current()
with session() as s:
e = ObjectEdit(workspace=actor.workspace, object_type=ot["id"], object_key=str(key or ""),
property="*", value_json=jdump(values), prev_json="null",
action_run_id=action_run_id, created_by=actor.id, mode="create")
s.add(e)
s.commit()
out = _edit_dict(e)
audit.record("object.create", "object", f"{ot['id']}:{key}", f"新建{ot['name']}「{key}」",
after=values)
return out
def revert_edit(edit_id: int) -> dict: def revert_edit(edit_id: int) -> dict:
with session() as s: with session() as s:
e = s.get(ObjectEdit, edit_id) e = s.get(ObjectEdit, edit_id)
if e is None: if e is None:
raise HTTPException(404, "写回记录不存在") raise HTTPException(404, "写回记录不存在")
if e.mode in ("db", "create") and e.active:
b = table_binding(object_type(e.object_type))
ref = b["ref"]
conn = _connector(b["ds_id"])
if e.mode == "create":
conn.delete_row(ref["table"], ref["key_column"], e.object_key)
else:
col = (ref.get("columns") or {}).get(e.property) or e.property
conn.write_row(ref["table"], {col: jload(e.prev_json, None)}, ref["key_column"], e.object_key)
e.active = 0 e.active = 0
s.commit() s.commit()
out = _edit_dict(e) out = _edit_dict(e)
......
"""数据管道:把对象骨架从业务库同步进来,并按关系物化出关系边。
业务数据永远实时查业务库 —— 这里只同步「骨架」:
- 主键、显示名:问句里点名具体对象时做链接、全局搜对象;
- 关系键列:按关系的 join 绑定物化成 `onto_link_edge`,多跳遍历 / 影响分析只走这张表;
- 维度属性:遍历结果按数据范围过滤、按维度分组。
跨表多跳 JOIN 在业务库上实时做既慢、跨数据源还做不了;骨架表上 BFS 很便宜。
代价是有同步延迟,所以每个结果都带「数据截至」时间。
"""
from __future__ import annotations
import datetime as dt
import logging
import time
from typing import Any
from fastapi import HTTPException
from sqlalchemy import delete, func, insert, select
from ..core import db as core_db
from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from . import objects, service
from .models import InstanceCache, LinkEdge, Pipeline
from .sqlutil import ident
log = logging.getLogger(__name__)
SCHEDULES = ("manual", "hourly", "daily")
MAX_EDGES = 500_000
_BATCH = 2000 # 批量写入:远程元数据库上逐行 INSERT 太慢
def _ws() -> str:
return identity.current().workspace
def _type_id(ref: str) -> str:
try:
return objects.object_type(ref)["id"]
except HTTPException:
return ""
def _links_of(ot_id: str) -> list[tuple[dict, dict, str, str]]:
"""涉及这个对象类型的已发布关系:(关系, join 绑定, from 类型 id, to 类型 id)。"""
out = []
for lt in service.rt_by_kind("link_type"):
jb = service.rt_binding(lt, "join")
if not jb:
continue
spec = lt.get("spec") or {}
f, t = _type_id(spec.get("from_type") or ""), _type_id(spec.get("to_type") or "")
if f and t and ot_id in (f, t):
out.append((lt, jb["ref"], f, t))
return out
def _skeleton_columns(ot: dict, ref: dict) -> tuple[list[str], dict[str, str]]:
"""要同步的列:主键、显示列、所有关系键列、维度属性列。返回 (列, 维度列→属性名)。"""
cols = [ref["key_column"]]
if ref.get("label_column"):
cols.append(ref["label_column"])
for _, j, f, t in _links_of(ot["id"]):
if f == ot["id"]:
cols.append(j["from_column"])
if t == ot["id"]:
cols.append(j["to_column"])
prop_cols: dict[str, str] = {}
for p in (ot.get("spec") or {}).get("properties") or []:
if p.get("is_dimension") or p.get("is_key"):
col = (ref.get("columns") or {}).get(p["name"]) or (ref["key_column"] if p.get("is_key") else "")
if col:
prop_cols[col] = p["name"]
cols.append(col)
return list(dict.fromkeys(cols)), prop_cols
def _parent_labels(ot_id: str, ws: str) -> list[tuple[str, dict[str, str]]]:
"""这个对象通过外键指向的上级对象:[(外键列, {上级主键: 上级显示名})](上级要先同步过)。"""
out = []
with session() as s:
for _, j, f, t in _links_of(ot_id):
if f != ot_id or t == ot_id:
continue
labels = {r.obj_key: r.label for r in s.scalars(select(InstanceCache).where(
InstanceCache.workspace == ws, InstanceCache.concept_id == t)).all()}
out.append((j["from_column"], labels))
return out
def sync_type(type_ref: str, limit: int | None = None) -> dict:
"""同步一个对象类型的骨架,然后重建和它有关的关系边。"""
ot = objects.object_type(type_ref)
b = objects.table_binding(ot)
ref = b["ref"]
limit = int(limit or core_db.get_config("PIPELINE_ROW_LIMIT", "20000") or 20000)
cols, prop_cols = _skeleton_columns(ot, ref)
# 执行器对每条查询都有行数上限(SQL_ROW_LIMIT),按主键排序分页拉,直到拉满 limit 或拉完
from ..text2sql import executor
page = max(1, min(int(executor.limits()[0] or 1000), limit))
names: list[str] = []
rows: list[list[Any]] = []
while len(rows) < limit:
sql = (f"SELECT {', '.join(ident(c) for c in cols)} FROM {ident(ref['table'])} "
f"ORDER BY {ident(ref['key_column'])} LIMIT {page} OFFSET {len(rows)}")
names, chunk = objects._run(b["ds_id"], sql)
rows += chunk
if len(chunk) < page:
break
rows = rows[:limit]
ws = _ws()
at = now()
key_col, label_col = ref["key_column"], ref.get("label_column") or ref["key_column"]
parents = [] if ref.get("label_column") else _parent_labels(ot["id"], ws)
seen: set[str] = set()
batch: list[dict] = []
for row in rows:
raw = dict(zip(names, row))
k = raw.get(key_col)
if k is None or str(k) in seen:
continue
seen.add(str(k))
lab = raw.get(label_col)
if parents:
# 没有名称列的对象(如「仓库 × 商品」的库存行):用它指向的上级对象名称拼一个人看得懂的名字
lab = " · ".join(labels.get(str(raw.get(col)), str(raw.get(col)))
for col, labels in parents if raw.get(col) is not None) or lab
props = {prop_cols[c]: raw.get(c) for c in prop_cols if c in raw}
joins = {c: raw.get(c) for c in cols if c not in (key_col,)}
batch.append({"workspace": ws, "concept_id": ot["id"], "obj_key": str(k)[:255],
"label": str(lab if lab not in (None, "") else k)[:255],
"props_json": jdump({"p": props, "j": joins}), "synced_at": at})
with session() as s:
s.execute(delete(InstanceCache).where(InstanceCache.workspace == ws,
InstanceCache.concept_id == ot["id"]))
for i in range(0, len(batch), _BATCH):
s.execute(insert(InstanceCache), batch[i:i + _BATCH])
s.commit()
edges = sum(rebuild_edges(lt, j, f, t) for lt, j, f, t in _links_of(ot["id"]))
from . import linker
linker.invalidate()
return {"object_type": ot["name"], "rows": len(seen), "edges": edges,
"truncated": len(rows) >= limit, "synced_at": iso(at)}
def _cache_rows(ws: str, type_id: str) -> list[tuple[str, dict]]:
with session() as s:
return [(r.obj_key, jload(r.props_json, {}) or {}) for r in s.scalars(select(InstanceCache).where(
InstanceCache.workspace == ws, InstanceCache.concept_id == type_id)).all()]
def _val(v: Any) -> str | None:
if v is None or v == "":
return None
if isinstance(v, float) and v.is_integer():
v = int(v)
return str(v)
def rebuild_edges(lt: dict, join: dict, from_type: str, to_type: str) -> int:
"""按 join 绑定物化一条关系的所有边:from 表的 from_column = to 表的 to_column。"""
ws = _ws()
def col_value(key: str, props: dict, col: str) -> str | None:
j = props.get("j") or {}
return _val(j[col]) if col in j else key # 不在关系键里的就是主键列本身
to_index: dict[str, list[str]] = {}
for k, p in _cache_rows(ws, to_type):
v = col_value(k, p, join["to_column"])
if v is not None:
to_index.setdefault(v, []).append(k)
edges: list[dict] = []
if to_index:
for k, p in _cache_rows(ws, from_type):
v = col_value(k, p, join["from_column"])
if v is None:
continue
for tk in to_index.get(v, []):
if from_type == to_type and tk == k:
continue
edges.append({"workspace": ws, "link_id": lt["id"], "from_type": from_type, "from_key": k,
"to_type": to_type, "to_key": tk})
if len(edges) >= MAX_EDGES:
log.warning("关系「%s」的边超过 %d 条,已截断", lt["name"], MAX_EDGES)
edges = edges[:MAX_EDGES]
break
with session() as s:
s.execute(delete(LinkEdge).where(LinkEdge.workspace == ws, LinkEdge.link_id == lt["id"]))
for i in range(0, len(edges), _BATCH):
s.execute(insert(LinkEdge), edges[i:i + _BATCH])
s.commit()
return len(edges)
# ---------------- 管道的登记与运行 ----------------
def _dict(p: Pipeline, names: dict[str, str] | None = None) -> dict:
return {"id": p.id, "object_type_id": p.object_type_id,
"object_type": (names or {}).get(p.object_type_id, p.object_type_id),
"schedule": p.schedule, "row_limit": p.row_limit, "enabled": bool(p.enabled),
"status": p.status, "last_rows": p.last_rows, "last_edges": p.last_edges,
"last_error": p.last_error or "", "last_run_at": iso(p.last_run_at),
"last_duration_ms": p.last_duration_ms, "created_at": iso(p.created_at)}
def _type_names() -> dict[str, str]:
return {c["id"]: c["name"] for c in service.list_concepts(kind="object_type")}
def list_pipelines() -> list[dict]:
names = _type_names()
with session() as s:
rows = s.scalars(select(Pipeline).where(Pipeline.workspace == _ws())
.order_by(Pipeline.created_at)).all()
return [_dict(p, names) for p in rows]
def get(pid: str) -> Pipeline:
with session() as s:
p = s.get(Pipeline, pid)
if p is None or p.workspace != _ws():
raise HTTPException(404, "数据管道不存在")
s.expunge(p)
return p
def create(object_type: str, schedule: str = "manual", row_limit: int = 0) -> dict:
ot = objects.object_type(object_type)
objects.table_binding(ot)
if schedule not in SCHEDULES:
raise HTTPException(422, f"调度只能是 {'/'.join(SCHEDULES)}")
with session() as s:
dup = s.scalars(select(Pipeline).where(Pipeline.workspace == _ws(),
Pipeline.object_type_id == ot["id"])).first()
if dup:
raise HTTPException(409, f"「{ot['name']}」已经有数据管道了")
p = Pipeline(id=new_id("pl"), workspace=_ws(), object_type_id=ot["id"], schedule=schedule,
row_limit=int(row_limit or 0), created_by=identity.current().id)
s.add(p)
s.commit()
out = _dict(p, {ot["id"]: ot["name"]})
audit.record("pipeline.create", "pipeline", out["id"], f"新建数据管道「{ot['name']}」({schedule})")
return out
def update(pid: str, *, schedule: str | None = None, row_limit: int | None = None,
enabled: bool | None = None) -> dict:
get(pid)
with session() as s:
p = s.get(Pipeline, pid)
if schedule is not None:
if schedule not in SCHEDULES:
raise HTTPException(422, f"调度只能是 {'/'.join(SCHEDULES)}")
p.schedule = schedule
if row_limit is not None:
p.row_limit = max(0, int(row_limit))
if enabled is not None:
p.enabled = 1 if enabled else 0
s.commit()
return _dict(p, _type_names())
def delete_pipeline(pid: str) -> None:
p = get(pid)
with session() as s:
s.execute(delete(Pipeline).where(Pipeline.id == pid))
s.execute(delete(InstanceCache).where(InstanceCache.workspace == p.workspace,
InstanceCache.concept_id == p.object_type_id))
s.execute(delete(LinkEdge).where(LinkEdge.workspace == p.workspace,
(LinkEdge.from_type == p.object_type_id)
| (LinkEdge.to_type == p.object_type_id)))
s.commit()
audit.record("pipeline.delete", "pipeline", pid, "删除数据管道(骨架与关系边一并清除)")
def run(pid: str) -> dict:
p = get(pid)
started = time.time()
with session() as s:
row = s.get(Pipeline, pid)
row.status = "running"
s.commit()
try:
out = sync_type(p.object_type_id, p.row_limit or None)
status, err = "ok", ""
except HTTPException as e:
out, status, err = {}, "failed", str(e.detail)
except Exception as e: # noqa: BLE001
log.exception("数据管道 %s 运行失败", pid)
out, status, err = {}, "failed", str(e)[:500]
ms = int((time.time() - started) * 1000)
with session() as s:
row = s.get(Pipeline, pid)
row.status = status
row.last_error = err
row.last_run_at = now()
row.last_duration_ms = ms
if status == "ok":
row.last_rows = out["rows"]
row.last_edges = out["edges"]
s.commit()
res = _dict(row, _type_names())
audit.record("pipeline.run", "pipeline", pid,
f"数据管道同步「{res['object_type']}」:"
+ (f"{out['rows']} 个对象、{out['edges']} 条关系边,{ms} ms" if status == "ok" else f"失败:{err}"),
after=out or {"error": err})
return {**res, "result": out}
def ensure_all(schedule: str = "manual") -> dict:
"""给所有已映射、还没有管道的对象类型建管道。"""
have = {p["object_type_id"] for p in list_pipelines()}
created = []
for c in service.list_concepts(kind="object_type"):
if c["id"] in have or not c.get("mapped") or not service.rt_get(c["id"]):
continue
try:
created.append(create(c["id"], schedule)["id"])
except HTTPException:
continue
return {"created": created}
def run_all_events():
"""后台任务:逐条同步,yield 进度。每条都会重建相关的边,所以跑完一轮两端都在的边都齐了。"""
items = [p for p in list_pipelines() if p["enabled"]]
# 上级对象先同步(外键指向别人的少的排前面),下级拼显示名时才取得到上级的名称
ups = {p["object_type_id"]: sum(1 for _, _, f, t in _links_of(p["object_type_id"])
if f == p["object_type_id"] and t != f) for p in items}
items.sort(key=lambda p: ups.get(p["object_type_id"], 0))
ok = 0
for i, p in enumerate(items, 1):
r = run(p["id"])
ok += r["status"] == "ok"
yield {"stage": "pipeline", "progress": int(i / max(1, len(items)) * 100),
"message": f"{r['object_type']}:{'%d 个对象、%d 条边' % (r['last_rows'], r['last_edges']) if r['status'] == 'ok' else r['last_error']}"}
yield {"stage": "done", "progress": 100, "message": f"同步完成 {ok}/{len(items)}",
"result": {"ok": ok, "total": len(items)}}
def run_all() -> dict:
out = list(run_all_events())
return out[-1]["result"]
def status() -> dict:
ws = _ws()
with session() as s:
objs = s.scalar(select(func.count(InstanceCache.id)).where(InstanceCache.workspace == ws)) or 0
edges = s.scalar(select(func.count(LinkEdge.id)).where(LinkEdge.workspace == ws)) or 0
last = s.scalar(select(func.max(InstanceCache.synced_at)).where(InstanceCache.workspace == ws))
return {"objects": int(objs), "edges": int(edges), "synced_at": iso(last)}
def dataset(type_ref: str, q: str = "", limit: int = 50, offset: int = 0) -> dict:
"""本体数据集:浏览某个对象类型已同步的骨架。"""
ot = objects.object_type(type_ref)
ws = _ws()
with session() as s:
stmt = select(InstanceCache).where(InstanceCache.workspace == ws,
InstanceCache.concept_id == ot["id"])
if q:
stmt = stmt.where(InstanceCache.label.like(f"%{q}%") | (InstanceCache.obj_key == q))
total = s.scalar(select(func.count()).select_from(stmt.subquery())) or 0
rows = s.scalars(stmt.order_by(InstanceCache.id).offset(offset).limit(min(limit, 500))).all()
items = [{"key": r.obj_key, "label": r.label, "properties": (jload(r.props_json, {}) or {}).get("p") or {},
"synced_at": iso(r.synced_at)} for r in rows]
return {"object_type": {"id": ot["id"], "name": ot["name"]}, "total": int(total), "items": items}
def reap_stale() -> int:
"""进程重启后,上次没跑完的管道 / 业务建模还标着 running:改成失败,免得界面永远转圈、定时永远跳过。"""
from sqlalchemy import update
from .models import ModelRun
with session() as s:
n = s.execute(update(Pipeline).where(Pipeline.status == "running").values(
status="failed", last_error="服务重启,同步中断")).rowcount or 0
n += s.execute(update(ModelRun).where(ModelRun.status == "running").values(
status="failed", error="服务重启,建模中断,可以重新运行")).rowcount or 0
s.commit()
return n
# ---------------- 定时 ----------------
def _due(p: Pipeline, at: dt.datetime) -> bool:
if not p.enabled or p.schedule == "manual" or p.status == "running":
return False
if p.last_run_at is None:
return True
gap = dt.timedelta(hours=1) if p.schedule == "hourly" else dt.timedelta(days=1)
return at - p.last_run_at >= gap
def tick(at: dt.datetime | None = None) -> list[str]:
at = at or dt.datetime.now()
with session() as s:
items = [(p.id, p.workspace) for p in s.scalars(select(Pipeline)).all() if _due(p, at)]
fired = []
for pid, ws in items:
tok = identity.set_current(identity.Actor(id="system", name="系统 · 数据管道", kind="system",
roles=["admin"], workspace=ws))
try:
run(pid)
fired.append(pid)
except Exception: # noqa: BLE001
log.exception("定时数据管道失败 %s", pid)
finally:
identity.reset(tok)
return fired
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
import re
from typing import Iterator from typing import Iterator
from ..core import llm from ..core import llm
...@@ -46,6 +47,7 @@ PROPOSE_SYSTEM = """你是一名本体(Ontology)建模专家。本体只有 ...@@ -46,6 +47,7 @@ PROPOSE_SYSTEM = """你是一名本体(Ontology)建模专家。本体只有
(动作的执行细节由人补全,这里只提议它存在) (动作的执行细节由人补全,这里只提议它存在)
另外:文中出现的岗位 / 职责主体,放进顶层 "roles":[{"name":角色名,"description":职责}],不要当成积木。 另外:文中出现的岗位 / 职责主体,放进顶层 "roles":[{"name":角色名,"description":职责}],不要当成积木。
name 用文档里的中文业务叫法(如「机台」「批次」);英文名、代码名、缩写一律放进 synonyms。
术语、缩写、别称不要单独建积木,写进被指向积木的 synonyms。流程(有先后步骤的事)不要建积木,会另行生成流程卡。 术语、缩写、别称不要单独建积木,写进被指向积木的 synonyms。流程(有先后步骤的事)不要建积木,会另行生成流程卡。
判定要点: 判定要点:
...@@ -99,7 +101,7 @@ def _merge(bucket: dict, item: dict, chunk_map: dict[str, dict]) -> None: ...@@ -99,7 +101,7 @@ def _merge(bucket: dict, item: dict, chunk_map: dict[str, dict]) -> None:
if kind == "action": if kind == "action":
# 文档里只能看出「要有这个动作」,效果要人补;先记成动作草稿的说明,采纳后在动作编辑器里补全 # 文档里只能看出「要有这个动作」,效果要人补;先记成动作草稿的说明,采纳后在动作编辑器里补全
item["spec"] = {"_stub": True, "text": str(spec0.get("text") or item.get("description") or "")} item["spec"] = {"_stub": True, "text": str(spec0.get("text") or item.get("description") or "")}
key = (kind, name) key = _bucket_key(bucket, kind, name, item.get("synonyms") or [])
ev = [] ev = []
for cid in item.get("evidence") or []: for cid in item.get("evidence") or []:
ch = chunk_map.get(str(cid)) ch = chunk_map.get(str(cid))
...@@ -108,13 +110,17 @@ def _merge(bucket: dict, item: dict, chunk_map: dict[str, dict]) -> None: ...@@ -108,13 +110,17 @@ def _merge(bucket: dict, item: dict, chunk_map: dict[str, dict]) -> None:
"heading": ch.get("heading", ""), "snippet": ch.get("text", "")[:400]}) "heading": ch.get("heading", ""), "snippet": ch.get("text", "")[:400]})
cur = bucket.get(key) cur = bucket.get(key)
if cur is None: if cur is None:
bucket[key] = {"kind": kind, "name": name, "synonyms": list(item.get("synonyms") or []), bucket[key] = {"kind": kind, "name": key[1], "synonyms": list(item.get("synonyms") or []),
"description": str(item.get("description") or ""), "description": str(item.get("description") or ""),
"spec": item.get("spec") if isinstance(item.get("spec"), dict) else {}, "spec": item.get("spec") if isinstance(item.get("spec"), dict) else {},
"evidence": ev, "confidence": float(item.get("confidence") or 0.6)} "evidence": ev, "confidence": float(item.get("confidence") or 0.6)}
return return
for s in item.get("synonyms") or []: if cur.pop("_seed", False) and name != cur["name"]:
if s not in cur["synonyms"]: # 数据表起的名字(取自表注释)让位给文档里的业务叫法,原名留作别名
cur["synonyms"].append(cur["name"])
cur["name"] = name
for s in [name, *(item.get("synonyms") or [])]:
if s != cur["name"] and s not in cur["synonyms"]:
cur["synonyms"].append(s) cur["synonyms"].append(s)
if len(str(item.get("description") or "")) > len(cur["description"]): if len(str(item.get("description") or "")) > len(cur["description"]):
cur["description"] = str(item["description"]) cur["description"] = str(item["description"])
...@@ -127,6 +133,80 @@ def _merge(bucket: dict, item: dict, chunk_map: dict[str, dict]) -> None: ...@@ -127,6 +133,80 @@ def _merge(bucket: dict, item: dict, chunk_map: dict[str, dict]) -> None:
cur["confidence"] = max(cur["confidence"], float(item.get("confidence") or 0)) cur["confidence"] = max(cur["confidence"], float(item.get("confidence") or 0))
def _bucket_key(bucket: dict, kind: str, name: str, synonyms: list) -> tuple[str, str]:
"""同一个东西的不同叫法合并到一条:名称或别名(含表名)撞上已有候选就归到它名下。"""
if (kind, name) in bucket:
return (kind, name)
names = {name, *[str(x) for x in synonyms]}
for (k, n), cur in bucket.items():
if k == kind and ({n, cur["name"]} & names or names & set(cur.get("synonyms") or [])):
return (k, n)
return (kind, name)
def _object_names(bucket: dict) -> dict[str, str]:
"""对象的任一叫法 → 规范名称(关系两端按它对齐)。"""
out: dict[str, str] = {}
for (k, n), cur in bucket.items():
if k == "object_type":
for alias in (n, cur["name"], *(cur.get("synonyms") or [])):
out[str(alias)] = cur["name"]
return out
def _align_links(bucket: dict) -> int:
"""文档里的关系没有取数方式;数据表推出来的关系有 join 但名字是机器起的。
两端对得上就合成一条:用文档的名字和说法,带上表的 join 绑定。返回合并条数。"""
names = _object_names(bucket)
for (k, _), cur in bucket.items():
if k == "link_type":
sp = cur["spec"]
for end in ("from_type", "to_type"):
if sp.get(end) in names:
sp[end] = names[sp[end]]
table_links = {key: cur for key, cur in bucket.items() if key[0] == "link_type" and cur.get("bindings")}
merged = 0
for key, cur in list(bucket.items()):
if key[0] != "link_type" or cur.get("bindings"):
continue
a, b = cur["spec"].get("from_type"), cur["spec"].get("to_type")
for tkey, t in list(table_links.items()):
ta, tb = t["spec"].get("from_type"), t["spec"].get("to_type")
if (a, b) == (ta, tb):
cur["bindings"] = t["bindings"]
elif (a, b) == (tb, ta): # 文档说的方向和外键相反:join 两列对调
cur["bindings"] = [{**bd, "ref": {"from_column": bd["ref"].get("to_column"),
"to_column": bd["ref"].get("from_column")}}
for bd in t["bindings"]]
else:
continue
cur["confidence"] = max(cur["confidence"], t.get("confidence") or 0)
bucket.pop(tkey, None)
table_links.pop(tkey, None)
merged += 1
break
return merged
def _same_join_link(p: dict) -> bool:
"""提议的关系和已有关系连的是同一对对象、用的是同一组关联列(任一方向)。"""
jb = next((b for b in p.get("bindings") or [] if b.get("target_kind") == "join"), None)
if not jb:
return False
sp = p.get("spec") or {}
ends = {(service.find(str(sp.get("from_type") or ""), "object_type") or {}).get("id"),
(service.find(str(sp.get("to_type") or ""), "object_type") or {}).get("id")}
cols = {jb["ref"].get("from_column"), jb["ref"].get("to_column")}
for c in service.list_concepts(kind="link_type", limit=500):
full = service.get_concept(c["id"])
fs = full.get("spec") or {}
b = next((x for x in full.get("bindings") or [] if x["target_kind"] == "join"), None)
if b and {fs.get("from_type"), fs.get("to_type")} == ends and \
{b["ref"].get("from_column"), b["ref"].get("to_column")} == cols:
return True
return False
def _definition(kind: str, spec: dict) -> str: def _definition(kind: str, spec: dict) -> str:
cat = spec.get("category") if kind == "function" else "" cat = spec.get("category") if kind == "function" else ""
if cat == "rule": if cat == "rule":
...@@ -159,6 +239,9 @@ def submit_proposals(proposals: list[dict], source: str) -> dict: ...@@ -159,6 +239,9 @@ def submit_proposals(proposals: list[dict], source: str) -> dict:
spec = {} spec = {}
p["spec"] = spec p["spec"] = spec
existing = service.find(p["name"], p["kind"]) existing = service.find(p["name"], p["kind"])
if existing is None and p["kind"] == "link_type" and _same_join_link(p):
enriched += 1 # 同一对对象、同一组关联列的关系已经有了(名字不同而已):不重复提议
continue
if existing: if existing:
old_def = _definition(p["kind"], existing.get("spec") or {}) old_def = _definition(p["kind"], existing.get("spec") or {})
new_def = _definition(p["kind"], spec) new_def = _definition(p["kind"], spec)
...@@ -171,6 +254,11 @@ def submit_proposals(proposals: list[dict], source: str) -> dict: ...@@ -171,6 +254,11 @@ def submit_proposals(proposals: list[dict], source: str) -> dict:
source=source, confidence=p.get("confidence", 0.5), target_ref=existing["id"]) source=source, confidence=p.get("confidence", 0.5), target_ref=existing["id"])
conflicts += 1 conflicts += 1
else: else:
if p.get("bindings") and not service.get_concept(existing["id"]).get("bindings"):
for b in p["bindings"]:
review.propose("binding", f"为「{existing['name']}」绑定数据表",
{"concept_id": existing["id"], **b}, source=source,
confidence=p.get("confidence", 0.8), target_ref=existing["id"])
if p.get("evidence"): if p.get("evidence"):
service.add_evidence(existing["id"], p["evidence"]) service.add_evidence(existing["id"], p["evidence"])
new_syn = [s for s in p.get("synonyms") or [] new_syn = [s for s in p.get("synonyms") or []
...@@ -190,18 +278,35 @@ def submit_proposals(proposals: list[dict], source: str) -> dict: ...@@ -190,18 +278,35 @@ def submit_proposals(proposals: list[dict], source: str) -> dict:
return {"proposed": created, "conflicts": conflicts, "enriched": enriched} return {"proposed": created, "conflicts": conflicts, "enriched": enriched}
def from_documents(chunks: list[dict]) -> Iterator[dict]: def from_documents(chunks: list[dict], *, source: str = "extract", hint: str = "",
"""后台任务:分批让 LLM 提议概念。yield 进度事件,最后一条带统计。""" seed: list[dict] | None = None) -> Iterator[dict]:
"""后台任务:分批让 LLM 提议概念。yield 进度事件,最后一条带统计。
source:提议的来源标记(业务建模用 `modeling:<run_id>` 找回自己这次的草案);
hint:行业路由给的先验(参考模板里的常见积木名),只帮助命名,不强加内容;
seed:已接入数据表翻译出的对象 / 关系(带绑定)。文档里说的是同一个东西时并进去,
草案一出来就绑好了表,不会出现「文档一套对象、数据表又一套对象」。
"""
chunks = [c for c in chunks if (c.get("text") or "").strip()] chunks = [c for c in chunks if (c.get("text") or "").strip()]
if not chunks: if not chunks:
yield {"stage": "error", "error": "没有可用的文档片段,请先上传并抽取文档"} yield {"stage": "error", "error": "没有可用的文档片段,请先上传并抽取文档"}
return return
batches = _batches(chunks) batches = _batches(chunks)
chunk_map = {c["id"]: c for c in chunks} chunk_map = {c["id"]: c for c in chunks}
bucket: dict = {} bucket: dict = {(p["kind"], p["name"]): {**p, "evidence": list(p.get("evidence") or []),
"synonyms": list(p.get("synonyms") or []), "_seed": True}
for p in seed or []}
role_bucket: dict[str, str] = {} role_bucket: dict[str, str] = {}
yield {"stage": "propose", "message": f"共 {len(chunks)} 个片段,分 {len(batches)} 批", "progress": 2} yield {"stage": "propose", "message": f"共 {len(chunks)} 个片段,分 {len(batches)} 批", "progress": 2}
existing = _existing_names() existing = _existing_names()
if hint:
existing += f"\n\n行业参考(该行业常见的积木名,文档里有对应内容时优先沿用这些名称):{hint}"
tables = [f"{p['name']}(表 {p['bindings'][0]['ref']['table']},列 "
f"{'、'.join(list(p['bindings'][0]['ref'].get('columns') or {})[:12])})"
for p in seed or [] if p["kind"] == "object_type"]
if tables:
existing += ("\n\n已接入的数据表(文档里指的是同一个东西时,对象名必须沿用这里的名称,"
"关系的两端也用这些名称):\n" + "\n".join(tables))
with llmlog.feature("ontology_propose"): with llmlog.feature("ontology_propose"):
for i, batch in enumerate(batches, 1): for i, batch in enumerate(batches, 1):
text = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】\n{c['text']}" for c in batch) text = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】\n{c['text']}" for c in batch)
...@@ -225,7 +330,12 @@ def from_documents(chunks: list[dict]) -> Iterator[dict]: ...@@ -225,7 +330,12 @@ def from_documents(chunks: list[dict]) -> Iterator[dict]:
role_bucket.setdefault(str(r["name"]).strip(), str(r.get("description") or "")) role_bucket.setdefault(str(r["name"]).strip(), str(r.get("description") or ""))
yield {"stage": "propose", "message": f"第 {i}/{len(batches)} 批,累计 {len(bucket)} 个候选", yield {"stage": "propose", "message": f"第 {i}/{len(batches)} 批,累计 {len(bucket)} 个候选",
"progress": int(i / len(batches) * 90)} "progress": int(i / len(batches) * 90)}
stats = submit_proposals(list(bucket.values()), "extract") aligned = _align_links(bucket)
for p in bucket.values():
p.pop("_seed", None)
stats = submit_proposals(list(bucket.values()), source)
stats["bound"] = sum(1 for p in bucket.values() if p.get("bindings"))
stats["aligned_links"] = aligned
from ..governance import roles from ..governance import roles
have = set(roles.names()) have = set(roles.names())
new_roles = [n for n in role_bucket if n and n not in have and len(n) <= 30] new_roles = [n for n in role_bucket if n and n not in have and len(n) <= 30]
...@@ -233,7 +343,7 @@ def from_documents(chunks: list[dict]) -> Iterator[dict]: ...@@ -233,7 +343,7 @@ def from_documents(chunks: list[dict]) -> Iterator[dict]:
roles.upsert(n, role_bucket[n]) roles.upsert(n, role_bucket[n])
stats["roles"] = len(new_roles) stats["roles"] = len(new_roles)
yield {"stage": "done", "progress": 100, yield {"stage": "done", "progress": 100,
"message": f"提议 {stats['proposed']} 块新积木,{stats['conflicts']} 个冲突," "message": f"提议 {stats['proposed']} 块新积木({stats['bound']} 块已绑定数据表),{stats['conflicts']} 个冲突,"
f"{stats['enriched']} 块已有积木补充了出处,登记 {len(new_roles)} 个业务角色", f"{stats['enriched']} 块已有积木补充了出处,登记 {len(new_roles)} 个业务角色",
"result": stats} "result": stats}
...@@ -269,7 +379,7 @@ def datasource_proposals(ds_id: int) -> list[dict]: ...@@ -269,7 +379,7 @@ def datasource_proposals(ds_id: int) -> list[dict]:
props.append({"name": c["name"], "display_name": (c.get("description") or "")[:40], props.append({"name": c["name"], "display_name": (c.get("description") or "")[:40],
"data_type": dt_, "is_key": c["name"] == key, "data_type": dt_, "is_key": c["name"] == key,
"description": c.get("description") or ""}) "description": c.get("description") or ""})
name = (m.get("description") or "").split(",")[0].split("。")[0][:30] or m["name"] name = re.split(r"[((,,。;;]", m.get("description") or "")[0].strip()[:30] or m["name"]
proposals.append({ proposals.append({
"kind": "object_type", "name": name, "synonyms": [m["name"]] if name != m["name"] else [], "kind": "object_type", "name": name, "synonyms": [m["name"]] if name != m["name"] else [],
"description": m.get("description") or "", "description": m.get("description") or "",
...@@ -290,7 +400,7 @@ def datasource_proposals(ds_id: int) -> list[dict]: ...@@ -290,7 +400,7 @@ def datasource_proposals(ds_id: int) -> list[dict]:
continue continue
proposals.append({ proposals.append({
"kind": "link_type", "name": f"{a}-{b}", "description": r.get("description") or "", "kind": "link_type", "name": f"{a}-{b}", "description": r.get("description") or "",
"spec": {"from_type": a, "to_type": b, "cardinality": r.get("cardinality") or "n:1"}, "spec": {"from_type": a, "to_type": b, "cardinality": (r.get("cardinality") or "n:1").lower()},
"bindings": [{"ds_id": ds_id, "target_kind": "join", "bindings": [{"ds_id": ds_id, "target_kind": "join",
"ref": {"from_column": r["from_column"], "to_column": r["to_column"]}}], "ref": {"from_column": r["from_column"], "to_column": r["to_column"]}}],
"confidence": 0.75}) "confidence": 0.75})
...@@ -341,7 +451,7 @@ def _accept_create(payload: dict, item: dict) -> dict: ...@@ -341,7 +451,7 @@ def _accept_create(payload: dict, item: dict) -> dict:
c = service.create_concept(kind, payload["name"], display_name=payload.get("display_name", ""), c = service.create_concept(kind, payload["name"], display_name=payload.get("display_name", ""),
description=desc, description=desc,
synonyms=payload.get("synonyms"), spec=spec, synonyms=payload.get("synonyms"), spec=spec,
origin=item.get("source") or "ai", origin=(item.get("source") or "ai").split(":")[0][:24],
evidence=payload.get("evidence"), evidence=payload.get("evidence"),
bindings=payload.get("bindings")) bindings=payload.get("bindings"))
return {"concept_id": c["id"], "name": c["name"]} return {"concept_id": c["id"], "name": c["name"]}
......
...@@ -10,6 +10,7 @@ from __future__ import annotations ...@@ -10,6 +10,7 @@ from __future__ import annotations
import ast import ast
import datetime as dt import datetime as dt
import math import math
import re
from typing import Any from typing import Any
...@@ -73,11 +74,16 @@ _ALLOWED = (ast.Expression, ast.BoolOp, ast.BinOp, ast.UnaryOp, ast.Compare, ast ...@@ -73,11 +74,16 @@ _ALLOWED = (ast.Expression, ast.BoolOp, ast.BinOp, ast.UnaryOp, ast.Compare, ast
ast.Slice, *_BIN.keys(), *_CMP.keys()) ast.Slice, *_BIN.keys(), *_CMP.keys())
_DOLLAR = re.compile(r"\$(?=[A-Za-z_一-鿿])")
def _prep(expr: str) -> str: def _prep(expr: str) -> str:
# 业务人员常写中文标点与 && ||,这里宽容一下 # 业务人员(和 AI)常写中文标点、&& ||,动作里又惯用 $参数 引用变量、= 开头表示表达式。
return (expr.replace("(", "(").replace(")", ")").replace(",", ",") # 这些写法意思都明确,这里宽容一下,不让它们变成「语法错误」(null / true 由 CONSTS 兜住)
s = (expr.replace("(", "(").replace(")", ")").replace(",", ",")
.replace("≥", ">=").replace("≤", "<=").replace("≠", "!=") .replace("≥", ">=").replace("≤", "<=").replace("≠", "!=")
.replace("&&", " and ").replace("||", " or ").strip()) .replace("&&", " and ").replace("||", " or ").strip())
return _DOLLAR.sub("", s.lstrip("=").strip())
def parse(expr: str) -> ast.Expression: def parse(expr: str) -> ast.Expression:
...@@ -187,7 +193,10 @@ def _ev(node: ast.AST, env: dict) -> Any: ...@@ -187,7 +193,10 @@ def _ev(node: ast.AST, env: dict) -> Any:
v = _num(v) v = _num(v)
return -v if isinstance(node.op, ast.USub) else +v return -v if isinstance(node.op, ast.USub) else +v
if isinstance(node, ast.BinOp): if isinstance(node, ast.BinOp):
a, b = _num(_ev(node.left, env)), _num(_ev(node.right, env)) ra, rb = _ev(node.left, env), _ev(node.right, env)
if isinstance(node.op, ast.Add) and any(isinstance(x, str) and isinstance(_num(x), str) for x in (ra, rb)):
return f"{'' if ra is None else ra}{'' if rb is None else rb}" # 'PO' + 单号:拼字符串
a, b = _num(ra), _num(rb)
if isinstance(node.op, ast.Pow) and isinstance(b, (int, float)) and abs(b) > 100: if isinstance(node.op, ast.Pow) and isinstance(b, (int, float)) and abs(b) > 100:
raise RuleError("指数过大") raise RuleError("指数过大")
try: try:
......
...@@ -7,10 +7,13 @@ ...@@ -7,10 +7,13 @@
- 关系 link_type:两个对象之间的关系,带方向与基数,绑定到 join。 - 关系 link_type:两个对象之间的关系,带方向与基数,绑定到 join。
- 函数 function:对对象的计算,按 category 走各自的确定性引擎: - 函数 function:对对象的计算,按 category 走各自的确定性引擎:
aggregate 聚合(指标,编译成 SQL)· rule 规则(安全表达式)· calendar 周期(统计窗口)· aggregate 聚合(指标,编译成 SQL)· rule 规则(安全表达式)· calendar 周期(统计窗口)·
decision 决策表(多维查表 / 分级)· ai AI 分析(提示 + 只读函数白名单,结果仅供参考)。 decision 决策表(多维查表 / 分级)· ml 模型推理(调用登记过的模型端点)·
ai AI 分析(提示 + 只读函数白名单,结果仅供参考,不作为权威结果)。
原则:大模型只起草、只做参考分析;权威结果一律来自确定性引擎。
- 动作 action:改变业务状态的操作 = 参数 + 前置校验 + 效果(只能调用已注册的系统效果),一律人工审批。 - 动作 action:改变业务状态的操作 = 参数 + 前置校验 + 效果(只能调用已注册的系统效果),一律人工审批。
角色放在「成员与角色」,流程放在「流程卡(SOP)」,术语就是任意积木上的同义词 —— 都不再是单独的概念。 角色放在「成员与角色」,流程放在「流程卡(SOP)」,术语就是任意积木上的同义词 —— 都不再是单独的概念。
每块积木可以标一个「域」(spec.domain,如 财务 / 质量 / 订单),只用于分组浏览。
""" """
from __future__ import annotations from __future__ import annotations
...@@ -30,13 +33,15 @@ FN_CATEGORIES: dict[str, dict[str, str]] = { ...@@ -30,13 +33,15 @@ FN_CATEGORIES: dict[str, dict[str, str]] = {
"rule": {"label": "规则", "desc": "口径、判定或计算,写成可求值表达式", "engine": "安全 AST 求值"}, "rule": {"label": "规则", "desc": "口径、判定或计算,写成可求值表达式", "engine": "安全 AST 求值"},
"calendar": {"label": "周期", "desc": "统计窗口,如自然月、自定义起止日的业务月", "engine": "周期解析"}, "calendar": {"label": "周期", "desc": "统计窗口,如自然月、自定义起止日的业务月", "engine": "周期解析"},
"decision": {"label": "决策表", "desc": "多条件查表 / 分级,一行一条规则", "engine": "决策表引擎"}, "decision": {"label": "决策表", "desc": "多条件查表 / 分级,一行一条规则", "engine": "决策表引擎"},
"ai": {"label": "AI 分析", "desc": "提示词 + 允许使用的只读函数,产出结构化结论", "ml": {"label": "模型推理", "desc": "调用登记过的机器学习模型端点,按输入输出定义取预测值",
"engine": "模型端点"},
"ai": {"label": "AI 分析(参考)", "desc": "提示词 + 允许使用的只读函数,产出结构化结论;结果仅供参考",
"engine": "大模型(只读)"}, "engine": "大模型(只读)"},
} }
# 旧写法(模板、AI 提议、导入)里的类别 → 新的四元组 # 旧写法(模板、AI 提议、导入)里的类别 → 新的四元组
LEGACY_FN = {"metric": "aggregate", "rule": "rule", "calendar": "calendar", "skill": "ai", LEGACY_FN = {"metric": "aggregate", "rule": "rule", "calendar": "calendar", "skill": "ai",
"decision": "decision"} "decision": "decision", "ml": "ml"}
DATA_TYPES = ("string", "number", "integer", "boolean", "date", "datetime", "enum", "text") DATA_TYPES = ("string", "number", "integer", "boolean", "date", "datetime", "enum", "text")
RULE_KINDS = ("judgement", "calibre", "calculation") RULE_KINDS = ("judgement", "calibre", "calculation")
...@@ -93,6 +98,9 @@ def normalize_spec(kind: str, spec: dict | None) -> dict: ...@@ -93,6 +98,9 @@ def normalize_spec(kind: str, spec: dict | None) -> dict:
spec = dict(spec or {}) spec = dict(spec or {})
ui = spec.get("ui") if isinstance(spec.get("ui"), dict) else None ui = spec.get("ui") if isinstance(spec.get("ui"), dict) else None
out = _NORMALIZERS[kind](spec) out = _NORMALIZERS[kind](spec)
domain = _str(spec.get("domain"))[:32]
if domain:
out["domain"] = domain
pos = (ui or {}).get("pos") pos = (ui or {}).get("pos")
if isinstance(pos, dict): # 画布位置:纯展示信息,原样保留 if isinstance(pos, dict): # 画布位置:纯展示信息,原样保留
try: try:
...@@ -222,8 +230,24 @@ def _fn_ai(spec: dict) -> dict: ...@@ -222,8 +230,24 @@ def _fn_ai(spec: dict) -> dict:
raise SpecError(str(e.detail)) from e raise SpecError(str(e.detail)) from e
def _fn_ml(spec: dict) -> dict:
def fields(v: Any, what: str) -> list[dict]:
out = []
for x in v or []:
if isinstance(x, str):
x = {"name": x}
if not isinstance(x, dict) or not _str(x.get("name")):
continue
out.append({"name": check_ident(x["name"], what), "label": _str(x.get("label")),
"type": _str(x.get("type"), "number") or "number"})
return out
return {"endpoint": _str(spec.get("endpoint")), "inputs": fields(spec.get("inputs"), "输入名"),
"outputs": fields(spec.get("outputs"), "输出名"),
"result_path": _str(spec.get("result_path")), "text": _str(spec.get("text"))}
_FN = {"aggregate": _fn_aggregate, "rule": _fn_rule, "calendar": _fn_calendar, _FN = {"aggregate": _fn_aggregate, "rule": _fn_rule, "calendar": _fn_calendar,
"decision": _fn_decision, "ai": _fn_ai} "decision": _fn_decision, "ml": _fn_ml, "ai": _fn_ai}
def _function(spec: dict) -> dict: def _function(spec: dict) -> dict:
......
...@@ -39,6 +39,7 @@ def _concept_dict(c: Concept, brief: bool = False) -> dict: ...@@ -39,6 +39,7 @@ def _concept_dict(c: Concept, brief: bool = False) -> dict:
"category": spec.get("category", "") if c.kind == "function" else "", "category": spec.get("category", "") if c.kind == "function" else "",
"object_type": (spec.get("object_type") or spec.get("target_type") or "") "object_type": (spec.get("object_type") or spec.get("target_type") or "")
if c.kind in ("function", "action") else "", if c.kind in ("function", "action") else "",
"domain": spec.get("domain", ""),
"name": c.name, "display_name": c.display_name or "", "name": c.name, "display_name": c.display_name or "",
"description": c.description or "", "synonyms": jload(c.synonyms_json, []), "description": c.description or "", "synonyms": jload(c.synonyms_json, []),
"parent_id": c.parent_id or "", "status": c.status, "dirty": bool(c.dirty), "parent_id": c.parent_id or "", "status": c.status, "dirty": bool(c.dirty),
...@@ -167,7 +168,27 @@ def list_concepts(kind: str = "", status: str = "", q: str = "", limit: int = 10 ...@@ -167,7 +168,27 @@ def list_concepts(kind: str = "", status: str = "", q: str = "", limit: int = 10
stmt = stmt.where(or_(Concept.name.like(like), Concept.display_name.like(like), stmt = stmt.where(or_(Concept.name.like(like), Concept.display_name.like(like),
Concept.synonyms_json.like(like), Concept.description.like(like))) Concept.synonyms_json.like(like), Concept.description.like(like)))
rows = s.scalars(stmt.order_by(Concept.kind, Concept.name).limit(limit)).all() rows = s.scalars(stmt.order_by(Concept.kind, Concept.name).limit(limit)).all()
return [_concept_dict(c, brief=True) for c in rows] bound: dict[str, set[str]] = {}
for cid, tk in s.execute(select(Binding.concept_id, Binding.target_kind).where(
Binding.workspace == _ws())).all():
bound.setdefault(cid, set()).add(tk)
out = []
for c in rows:
d = _concept_dict(c, brief=True)
d["mapped"] = is_mapped(d, bound.get(c.id, set()))
out.append(d)
return out
def is_mapped(c: dict, target_kinds: set[str]) -> bool | None:
"""这块积木是否已落到真实数据。不需要绑定的积木(规则、决策表、动作……)返回 None。"""
if c["kind"] == "object_type":
return "table" in target_kinds
if c["kind"] == "link_type":
return "join" in target_kinds
if c["kind"] == "function" and c.get("category") == "aggregate":
return "metric_expr" in target_kinds
return None
def stats() -> dict: def stats() -> dict:
...@@ -457,12 +478,27 @@ def evidence_for(cids: list[str]) -> dict[str, list[dict]]: ...@@ -457,12 +478,27 @@ def evidence_for(cids: list[str]) -> dict[str, list[dict]]:
# ---------------- 发布 / 回滚 ---------------- # ---------------- 发布 / 回滚 ----------------
# 发布闸门:fn(diff) -> (ok, message)。评测模块会注册一个「回归不能掉点」的闸门。 # 发布闸门:fn(diff) -> (ok, message)。评测模块会注册一个「回归不能掉点」的闸门。
_gates: list[Callable[[dict], tuple[bool, str]]] = [] _gates: list[Callable[[dict], tuple[bool, str]]] = []
# 发布监听:新版本生效后通知运行时各部分刷新(链接器、MCP 目录……)。进程内事件,不需要消息队列。
_listeners: list[Callable[[int], None]] = []
def register_publish_gate(fn: Callable[[dict], tuple[bool, str]]) -> None: def register_publish_gate(fn: Callable[[dict], tuple[bool, str]]) -> None:
_gates.append(fn) _gates.append(fn)
def on_publish(fn: Callable[[int], None]) -> None:
_listeners.append(fn)
def _released(revision: int) -> None:
invalidate_runtime()
for fn in _listeners:
try:
fn(revision)
except Exception: # noqa: BLE001
log.exception("发布监听处理失败")
def _publish_copy(s, c: Concept) -> dict: def _publish_copy(s, c: Concept) -> dict:
d = _concept_dict(c) d = _concept_dict(c)
d["bindings"] = [_binding_dict(b) for b in s.scalars( d["bindings"] = [_binding_dict(b) for b in s.scalars(
...@@ -588,7 +624,7 @@ def publish(note: str = "", concept_ids: list[str] | None = None, force: bool = ...@@ -588,7 +624,7 @@ def publish(note: str = "", concept_ids: list[str] | None = None, force: bool =
s.commit() s.commit()
out = {"revision": r.revision, "note": r.note, "diff": real_diff, out = {"revision": r.revision, "note": r.note, "diff": real_diff,
"concepts": len(snapshot)} "concepts": len(snapshot)}
invalidate_runtime() _released(out["revision"])
audit.record("ontology.publish", "revision", str(out["revision"]), audit.record("ontology.publish", "revision", str(out["revision"]),
f"发布本体第 {out['revision']} 版:新增 {len(real_diff['added'])}," f"发布本体第 {out['revision']} 版:新增 {len(real_diff['added'])},"
f"修改 {len(real_diff['changed'])},移除 {len(real_diff['removed'])}" f"修改 {len(real_diff['changed'])},移除 {len(real_diff['removed'])}"
...@@ -656,11 +692,103 @@ def rollback(rev: int) -> dict: ...@@ -656,11 +692,103 @@ def rollback(rev: int) -> dict:
s.add(r) s.add(r)
s.commit() s.commit()
new_rev = r.revision new_rev = r.revision
invalidate_runtime() _released(new_rev)
audit.record("ontology.rollback", "revision", str(new_rev), f"回滚到第 {rev} 版", after=diff) audit.record("ontology.rollback", "revision", str(new_rev), f"回滚到第 {rev} 版", after=diff)
return {"revision": new_rev, "diff": diff} return {"revision": new_rev, "diff": diff}
# ---------------- 变更提案(发布与回滚都要人审) ----------------
# 规则:提交人不能审批自己的提案;AI / 外部 Agent 不能审批;审批时如果草稿又被改过,要重新提交。
def _dirty_fingerprint(concept_ids: list[str] | None = None) -> list[list]:
with session() as s:
stmt = select(Concept.id, Concept.version).where(Concept.workspace == _ws(), Concept.dirty == 1)
if concept_ids:
stmt = stmt.where(Concept.id.in_(concept_ids))
return sorted([cid, int(v)] for cid, v in s.execute(stmt).all())
def _pending_release() -> dict | None:
from ..governance import review
items = review.list_items(status="pending", kind="release", limit=1)["items"]
return items[0] if items else None
def propose_release(note: str = "", concept_ids: list[str] | None = None) -> dict:
from ..governance import review
diff = pending_diff()
if not (diff["added"] or diff["removed"] or diff["changed"]):
raise HTTPException(409, "没有待发布的变更")
if _pending_release():
raise HTTPException(409, "已有一份待审批的变更提案,请先处理它(或撤回后重新提交)")
with session() as s:
rev, _ = _last_snapshot(s)
title = f"发布第 {rev + 1} 版:新增 {len(diff['added'])},修改 {len(diff['changed'])},移除 {len(diff['removed'])}"
return review.propose("release", title, {
"op": "publish", "note": note or "", "concept_ids": concept_ids or [], "diff": diff,
"fingerprint": _dirty_fingerprint(concept_ids), "base_revision": rev},
source="user", target_ref="release", assignee_role="builder", dedupe=False)
def propose_rollback(rev: int, note: str = "") -> dict:
from ..governance import review
get_revision(rev)
if _pending_release():
raise HTTPException(409, "已有一份待审批的变更提案,请先处理它")
with session() as s:
cur, _ = _last_snapshot(s)
diff = compare_revisions(cur, rev) if cur else {}
return review.propose("release", f"回滚到第 {rev} 版", {
"op": "rollback", "rev": rev, "note": note or "", "diff": diff, "base_revision": cur},
source="user", target_ref="release", assignee_role="builder", dedupe=False)
def can_decide_release(actor: identity.Actor, item: dict) -> str:
"""返回不能审批的原因;空串表示可以。"""
from ..core import db as core_db
if actor.kind != "user":
return "AI 与外部 Agent 不能审批变更提案"
if not (actor.can("review") or actor.can("approve")):
return "变更提案要由实施工程师或审批人来批,你的角色没有这个权限"
self_ok = core_db.get_config("RELEASE_SELF_APPROVE", "0").lower() in ("1", "true", "yes")
if item.get("created_by") == actor.id and not self_ok:
return "不能审批自己提交的变更提案(在系统设置里可以为单人团队放开)"
return ""
def _accept_release(payload: dict, item: dict) -> dict:
why = can_decide_release(identity.current(), item)
if why:
raise HTTPException(403, why)
with session() as s:
cur, _ = _last_snapshot(s)
if int(payload.get("base_revision") or 0) != cur:
raise HTTPException(409, "提交之后本体已经发布过新版本,请重新提交变更提案")
if payload.get("op") == "rollback":
return rollback(int(payload["rev"]))
if _dirty_fingerprint(payload.get("concept_ids") or None) != payload.get("fingerprint"):
raise HTTPException(409, "提交之后草稿又被修改过,请重新提交变更提案")
return publish(payload.get("note") or item["title"], payload.get("concept_ids") or None)
def list_releases(status: str = "", limit: int = 50) -> list[dict]:
from ..governance import review
items = review.list_items(status=status, kind="release", limit=limit)["items"]
actor = identity.current()
for it in items:
why = can_decide_release(actor, it) if it["status"] == "pending" else ""
it["can_decide"] = it["status"] == "pending" and not why
it["cannot_reason"] = why
return items
def _register_release_handler() -> None:
from ..governance import review
review.register_handler("release", _accept_release)
_register_release_handler()
# ---------------- 引用 / 影响 / 血缘 ---------------- # ---------------- 引用 / 影响 / 血缘 ----------------
# 其他模块(能力、SOP、编排)注册自己的引用查找:fn(concept_id, names) -> [{type,id,name}] # 其他模块(能力、SOP、编排)注册自己的引用查找:fn(concept_id, names) -> [{type,id,name}]
_usage_providers: list[Callable[[str, list[str]], list[dict]]] = [] _usage_providers: list[Callable[[str, list[str]], list[dict]]] = []
......
...@@ -25,6 +25,17 @@ def lit(v: Any) -> str: ...@@ -25,6 +25,17 @@ def lit(v: Any) -> str:
return f"'{s}'" return f"'{s}'"
def to_dialect(sql: str, ds_type: str) -> str:
"""本体编译出来的 SQL 按 MySQL 写(反引号标识符);目标库是别的方言时转写一次。"""
if not ds_type or ds_type == "mysql":
return sql
import sqlglot
try:
return sqlglot.transpile(sql, read="mysql", write=ds_type)[0]
except Exception: # noqa: BLE001 转不了就原样交给 guard,它会给出明确的报错
return sql
def jsonable(v: Any) -> Any: def jsonable(v: Any) -> Any:
if isinstance(v, Decimal): if isinstance(v, Decimal):
return float(v) return float(v)
......
"""关系遍历与实例级影响分析:顺着关系网从一个对象往外推。
「这台机台出了问题 → 哪些批次受影响 → 连累哪些订单 → 交期会不会破」——
过去要跨好几个系统人肉查,这里在数据管道同步好的关系边(onto_link_edge)上做 BFS。
最后一层的对象再回业务库实时取一次最新属性,保证结论用的是现在的数据。
"""
from __future__ import annotations
from collections import deque
from fastapi import HTTPException
from sqlalchemy import func, or_, select
from ..core import identity
from ..core.dbx import iso, jload, session
from . import objects, service
from .models import InstanceCache, LinkEdge
MAX_DEPTH = 4
def _names() -> tuple[dict[str, str], dict[str, str]]:
types = {c["id"]: c["name"] for c in service.rt_by_kind("object_type")}
links = {c["id"]: c["name"] for c in service.rt_by_kind("link_type")}
return types, links
def _parent_side() -> dict[str, str]:
"""每条关系哪一端是「上级」:关联列正好是那一端的主键(被外键指向的一方)。返回 {link_id: from/to}。
关系的方向是业务起的名字(供应商「供货」商品),不代表外键方向,所以不能按 from/to 判断。"""
out: dict[str, str] = {}
for lt in service.rt_by_kind("link_type"):
jb = service.rt_binding(lt, "join")
spec = lt.get("spec") or {}
if not jb:
continue
for side in ("from", "to"):
ot = service.rt_get(spec.get(f"{side}_type") or "") or {}
tb = service.rt_binding(ot, "table") if ot else None
if tb and jb["ref"].get(f"{side}_column") == tb["ref"].get("key_column"):
out[lt["id"]] = side
break
return out
def _allowed(actor: identity.Actor, type_id: str, props: dict) -> bool:
"""数据范围:设了范围的对象类型,骨架里对应属性不在允许值里(或没同步到)就不给看。"""
scope = (actor.scope or {}).get(type_id) or {}
for prop, vals in scope.items():
if vals and str(props.get(prop)) not in {str(v) for v in vals}:
return False
return True
def _cache(ws: str, keys: dict[str, set[str]]) -> dict[tuple[str, str], tuple[str, dict, object]]:
out = {}
with session() as s:
for t, ks in keys.items():
for r in s.scalars(select(InstanceCache).where(
InstanceCache.workspace == ws, InstanceCache.concept_id == t,
InstanceCache.obj_key.in_(list(ks)))).all():
out[(t, r.obj_key)] = (r.label, (jload(r.props_json, {}) or {}).get("p") or {}, r.synced_at)
return out
def traverse(type_ref: str, key: str, *, depth: int = 3, links: list[str] | None = None,
limit: int = 300, hub_stop: bool = False) -> dict:
"""hub_stop:沿外键「往上」走到的上级对象(库存 → 仓库)只记录、不再往外扩。
影响分析要这样:供应商出问题波及它的商品、商品的库存,但不会绕道仓库把全仓库存都算进来。"""
ot = objects.object_type(type_ref)
actor = identity.current()
ws = actor.workspace
depth = max(1, min(int(depth or 3), MAX_DEPTH))
types, link_names = _names()
link_ids = None
if links:
link_ids = {lid for lid, n in link_names.items() if lid in links or n in links}
parent = _parent_side() if hub_stop else {}
root = (ot["id"], str(key))
root_cache = _cache(ws, {root[0]: {root[1]}})
if root not in root_cache:
raise HTTPException(422, f"{ot['name']}「{key}」不在已同步的骨架里:请先在「数据管道」里同步这个对象类型")
seen: dict[tuple[str, str], dict] = {root: {"depth": 0, "via": None}}
edges_out: list[dict] = []
frontier = [root]
truncated = False
with session() as s:
for d in range(1, depth + 1):
if not frontier:
break
by_type: dict[str, list[str]] = {}
for t, k in frontier:
by_type.setdefault(t, []).append(k)
conds = []
for t, ks in by_type.items():
conds.append((LinkEdge.from_type == t) & LinkEdge.from_key.in_(ks))
conds.append((LinkEdge.to_type == t) & LinkEdge.to_key.in_(ks))
stmt = select(LinkEdge).where(LinkEdge.workspace == ws, or_(*conds))
if link_ids is not None:
stmt = stmt.where(LinkEdge.link_id.in_(link_ids or {"-"}))
nxt = []
fset = set(frontier)
for e in s.scalars(stmt.limit(limit * 20)).all():
a, b = (e.from_type, e.from_key), (e.to_type, e.to_key)
src, dst, direction = (a, b, "out") if a in fset else (b, a, "in")
edges_out.append({"link_id": e.link_id, "link": link_names.get(e.link_id, e.link_id),
"from": f"{a[0]}:{a[1]}", "to": f"{b[0]}:{b[1]}"})
if dst in seen:
continue
if len(seen) >= limit:
truncated = True
continue
seen[dst] = {"depth": d, "via": {"link": link_names.get(e.link_id, e.link_id),
"direction": direction, "from": f"{src[0]}:{src[1]}"},
"context": bool(parent) and parent.get(e.link_id) == ("to" if direction == "out" else "from")}
if not seen[dst]["context"]:
nxt.append(dst)
frontier = nxt
keys: dict[str, set[str]] = {}
for t, k in seen:
keys.setdefault(t, set()).add(k)
cache = _cache(ws, keys)
nodes, hidden = [], 0
for (t, k), info in seen.items():
label, props, _ = cache.get((t, k), (k, {}, None))
if (t, k) != root and not _allowed(actor, t, props):
hidden += 1
continue
nodes.append({"id": f"{t}:{k}", "type_id": t, "type_name": types.get(t, t), "key": k,
"label": label, "depth": info["depth"], "via": info["via"], "properties": props,
"context": bool(info.get("context"))})
visible = {n["id"] for n in nodes}
edges_out = list({(e["from"], e["to"], e["link_id"]): e for e in edges_out
if e["from"] in visible and e["to"] in visible}.values())
by_type: dict[str, int] = {}
for n in nodes:
if n["depth"]:
by_type[n["type_name"]] = by_type.get(n["type_name"], 0) + 1
with session() as s2:
synced = s2.scalar(select(func.max(InstanceCache.synced_at)).where(
InstanceCache.workspace == ws, InstanceCache.concept_id.in_(list(keys))))
return {"root": {"id": f"{root[0]}:{root[1]}", "type_name": ot["name"], "key": root[1],
"label": root_cache[root][0]},
"depth": depth, "nodes": nodes, "edges": edges_out, "by_type": by_type,
"hidden": hidden, "truncated": truncated, "synced_at": iso(synced)}
def instance_impact(type_ref: str, key: str, *, depth: int = 3, refresh: int = 10) -> dict:
"""影响分析:遍历 + 按层汇总 + 最外层实时取最新属性 + 能对受影响对象做的动作。"""
t = traverse(type_ref, key, depth=depth, hub_stop=True)
layers: dict[int, dict[str, list[dict]]] = {}
context: dict[str, int] = {} # 只是「涉及」的上级对象,不算受影响
for n in t["nodes"]:
if not n["depth"]:
continue
if n.get("context"):
context[n["type_name"]] = context.get(n["type_name"], 0) + 1
continue
layers.setdefault(n["depth"], {}).setdefault(n["type_name"], []).append(n)
far = max(layers) if layers else 0
live = []
if far:
for n in [x for grp in layers[far].values() for x in grp][:refresh]:
try:
o = objects.get(n["type_id"], n["key"])
dn = {p["name"]: p.get("display_name") or p["name"]
for p in (objects.object_type(n["type_id"]).get("spec") or {}).get("properties") or []}
live.append({"id": n["id"], "type_name": n["type_name"], "key": n["key"], "label": n["label"] or o["label"],
"properties": {dn.get(k, k): v for k, v in o["properties"].items()}})
except HTTPException:
continue
affected_types = {n["type_id"] for n in t["nodes"] if n["depth"] and not n.get("context")}
acts = [{"name": a["name"], "display_name": a.get("display_name") or a["name"],
"object_type": (a.get("spec") or {}).get("target_type")}
for a in service.rt_by_kind("action")
if (a.get("spec") or {}).get("target_type") in affected_types]
affected: dict[str, int] = {}
for g in layers.values():
for name, items in g.items():
affected[name] = affected.get(name, 0) + len(items)
parts = [f"{name} {cnt}" for name, cnt in affected.items()]
summary = (f"从{t['root']['type_name']}「{t['root']['label']}」出发 {t['depth']} 跳内影响:"
+ ("、".join(parts) if parts else "没有找到受影响的对象")
+ (f";涉及 {'、'.join(f'{k} {v}' for k, v in context.items())}" if context else ""))
return {**t, "layers": [{"depth": d, "groups": [{"type_name": k, "count": len(v),
"items": v[:50]} for k, v in g.items()]}
for d, g in sorted(layers.items())],
"by_type": affected, "context": context, "live": live, "actions": acts, "summary": summary}
"""工作台:老板和员工每天打开系统看到的第一页。
搭建者看「本体首页」(资产、映射、下一步);业务人员只关心四件事:
1. 今天的关键数字怎么样(已发布指标的当前值);
2. 有什么等我处理(待我审批的动作、变更提案、派给我的待办);
3. 我提交的事办得怎么样;
4. 常用的流程和问题,一点就能用。
全部只读、按当前身份过滤,指标取数失败的直接跳过,不让一个坏指标拖垮整页。
"""
from __future__ import annotations
import logging
from ..core import identity
from . import metrics, service
log = logging.getLogger(__name__)
MAX_KPIS = 8
def _kpis() -> list[dict]:
out = []
for m in service.rt_by_kind("function", "aggregate"):
if len(out) >= MAX_KPIS:
break
if not service.rt_binding(m, "metric_expr"):
continue
sp = m.get("spec") or {}
try:
r = metrics.query(m["name"], limit=1, question=f"[工作台] {m['name']}")
except Exception as e: # noqa: BLE001 —— 单个指标失败不影响整页
log.info("工作台指标 %s 取数失败:%s", m["name"], str(e)[:120])
continue
v = r.get("value")
if v is None and r.get("rows"):
v = r["rows"][0][-1]
dims = list(((service.rt_binding(m, "metric_expr") or {}).get("ref") or {}).get("dimensions") or {})
ot = service.rt_get(sp.get("object_type") or "") or {}
label = {p["name"]: p.get("display_name") or p["name"] for p in (ot.get("spec") or {}).get("properties") or []}
dims = [label.get(d, d) for d in dims] # 维度用业务叫法(仓库编号),取数时按显示名也认
out.append({"name": m["name"], "value": v, "unit": sp.get("unit") or "",
"direction": sp.get("direction") or "neutral", "formula": sp.get("formula_text") or "",
"dimensions": dims, "run_id": r.get("run_id")})
return out
def _questions(kpis: list[dict]) -> list[str]:
"""按本体里真有的东西给几个能直接问的问题(不瞎编指标名,不带指标不支持的时间范围)。"""
qs = []
for k in kpis[:3]:
qs.append(f"{k['name']}按{k['dimensions'][0]}拆开看是多少?" if k["dimensions"] else f"现在的{k['name']}是多少?")
for a in service.rt_by_kind("action")[:2]:
qs.append(f"哪些情况需要{a.get('display_name') or a['name']}?帮我发起")
objs = service.rt_by_kind("object_type")
if len(objs) >= 2:
qs.append(f"某个{objs[0]['name']}出问题会影响哪些对象?")
return qs[:6]
def workbench() -> dict:
from ..capability import actions, tasks
from ..governance import audit
from ..sop import service as sop_service
actor = identity.current()
kpis = _kpis()
approvals = [r for r in actions.pending_for(actor) if r.get("can_approve")] if actor.can("approve") else []
releases = [r for r in service.list_releases("pending") if r.get("can_decide")] \
if actor.can("review") or actor.can("approve") else []
my_tasks = tasks.list_tasks(scope="mine", status="open", limit=5)
mine = [r for r in actions.list_runs(limit=50) if actor.id in (r["initiator_id"], r["submitted_by"])][:5]
sops = [{"id": d["id"], "title": d["title"], "description": d.get("description") or "",
"run_count": d.get("run_count") or 0}
for d in sop_service.list_defs(status="published")][:6]
feed = audit.query(workspace=actor.workspace, limit=8)["items"]
def brief(r: dict) -> dict:
return {"id": r["id"], "action_name": r["action_name"], "priority": r["priority"], "status": r["status"],
"summary": (r.get("preview") or {}).get("summary") or r.get("reason") or "",
"created_at": r["created_at"], "initiator_id": r["initiator_id"]}
return {"user": {"id": actor.id, "name": actor.name, "roles": actor.roles, "biz_roles": actor.biz_roles,
"can_run": actor.can("operate")},
"kpis": kpis,
"todo": {"approvals": [brief(r) for r in approvals[:5]], "approvals_total": len(approvals),
"releases": [{"id": r["id"], "title": r["title"], "created_by": r.get("created_by")}
for r in releases[:3]],
"tasks": [{"id": t["id"], "title": t["title"], "due_at": t.get("due_at"),
"role": t.get("role")} for t in my_tasks]},
"mine": [brief(r) for r in mine], "sops": sops,
"questions": _questions(kpis),
"feed": [{"ts": x.get("ts"), "actor": x.get("actor_name") or x.get("actor_id"),
"summary": x.get("summary")} for x in feed]}
"""本体空间:一个行业 / 业务域一套本体。
积木、版本、动作、审批、SOP、审计、数据管道本来就按 `workspace` 隔离(身份里带着),
这里只补空间本身的登记、首页卡片统计和「当前本体总览」。
"""
from __future__ import annotations
import dataclasses
import re
from fastapi import HTTPException
from sqlalchemy import func, select
from ..core import identity
from ..core.dbx import iso, new_id, session
from ..governance import audit
from .models import Concept, Pipeline, Workspace
_ID = re.compile(r"^[a-z][a-z0-9_]{1,40}$")
def _dict(w: Workspace) -> dict:
return {"id": w.id, "display_name": w.display_name or w.id, "description": w.description or "",
"industry": w.industry or "", "status": w.status, "created_by": w.created_by,
"created_at": iso(w.created_at), "updated_at": iso(w.updated_at)}
def ensure(ws_id: str) -> None:
"""当前身份所在的空间没有登记过(老数据 / 环境变量指定的默认空间)就补登记。"""
with session() as s:
if s.get(Workspace, ws_id) is None:
# 环境变量指定的空间(如 v4)是部署细节,对用户一律叫「默认本体」
s.add(Workspace(id=ws_id, display_name="默认本体", created_by="system"))
s.commit()
def counts(ws_id: str) -> dict:
from ..sop.models import SopDefinition
with session() as s:
rows = s.execute(select(Concept.kind, Concept.spec_json).where(
Concept.workspace == ws_id, Concept.status != "deprecated")).all()
sops = s.scalar(select(func.count(SopDefinition.id)).where(
SopDefinition.workspace == ws_id, SopDefinition.status != "archived")) or 0
out = {"object_type": 0, "link_type": 0, "function": 0, "action": 0, "sop": int(sops)}
for kind, _ in rows:
out[kind] = out.get(kind, 0) + 1
return out
def list_all() -> list[dict]:
ensure(identity.current().workspace)
with session() as s:
rows = s.scalars(select(Workspace).where(Workspace.status == "active")
.order_by(Workspace.created_at)).all()
items = [_dict(w) for w in rows]
for it in items:
it["counts"] = counts(it["id"])
it["current"] = it["id"] == identity.current().workspace
return items
def get(ws_id: str) -> dict:
with session() as s:
w = s.get(Workspace, ws_id)
if w is None:
raise HTTPException(404, f"本体空间「{ws_id}」不存在")
out = _dict(w)
out["counts"] = counts(ws_id)
return out
def create(ws_id: str, display_name: str, description: str = "", industry: str = "",
template: str = "") -> dict:
ws_id = (ws_id or "").strip().lower()
if not ws_id: # 中文名起不出英文标识:不填就自动生成
ws_id = f"ws_{new_id('')[-8:].lower()}"
if not _ID.match(ws_id):
raise HTTPException(422, "空间标识只能用小写字母开头的字母、数字、下划线(2~41 位),如 manufacturing")
actor = identity.current()
with session() as s:
if s.get(Workspace, ws_id) is not None:
raise HTTPException(409, f"本体空间「{ws_id}」已存在")
s.add(Workspace(id=ws_id, display_name=(display_name or ws_id)[:255],
description=description or "", industry=industry or "",
created_by=actor.id))
s.commit()
audit.record("workspace.create", "workspace", ws_id, f"新建本体「{display_name or ws_id}」")
if template:
from . import templates
tok = identity.set_current(dataclasses.replace(actor, workspace=ws_id))
try:
templates.apply_template(template)
finally:
identity.reset(tok)
return get(ws_id)
def update(ws_id: str, **fields) -> dict:
with session() as s:
w = s.get(Workspace, ws_id)
if w is None:
raise HTTPException(404, f"本体空间「{ws_id}」不存在")
for k in ("display_name", "description", "industry"):
if fields.get(k) is not None:
setattr(w, k, str(fields[k]))
s.commit()
return get(ws_id)
def archive(ws_id: str) -> dict:
if ws_id == identity.current().workspace:
raise HTTPException(409, "不能归档当前正在使用的本体,请先切换到别的本体")
with session() as s:
w = s.get(Workspace, ws_id)
if w is None:
raise HTTPException(404, f"本体空间「{ws_id}」不存在")
w.status = "archived"
s.commit()
audit.record("workspace.archive", "workspace", ws_id, f"归档本体「{ws_id}」")
return {"ok": True}
def overview() -> dict:
"""当前本体的首页:资产计数、映射情况、数据与运行时状态、建议的下一步。"""
from ..capability import actions
from ..governance import review
from ..text2sql import semantic
from . import service
actor = identity.current()
ws = actor.workspace
ensure(ws)
c = counts(ws)
items = service.list_concepts()
unmapped = [x for x in items if x["kind"] == "object_type" and not x.get("mapped")]
dss = semantic.list_datasources()
with session() as s:
pipes = s.scalars(select(Pipeline).where(Pipeline.workspace == ws)).all()
pipe_info = {"total": len(pipes), "ok": sum(1 for p in pipes if p.status == "ok"),
"failed": sum(1 for p in pipes if p.status == "failed"),
"last_run_at": iso(max((p.last_run_at for p in pipes if p.last_run_at), default=None))}
st = service.stats()
pending_reviews = sum(review.counts().values()) if actor.can("review") else 0
steps = []
if not dss:
steps.append({"key": "data", "title": "接入数据连接", "hint": "先接一个业务库,本体才能落到真实数据"})
if c["object_type"] == 0:
steps.append({"key": "modeling", "title": "业务建模", "hint": "上传业务文档,AI 生成四元组草案"})
if unmapped:
steps.append({"key": "b_object", "title": f"完善对象映射({len(unmapped)} 个未映射)",
"hint": "对象要绑定到数据表,才能被查询、遍历与写回"})
if dss and c["object_type"] and not pipe_info["total"]:
steps.append({"key": "pipeline", "title": "配置数据管道", "hint": "同步对象骨架,打开影响分析与对象搜索"})
if st["dirty"]:
steps.append({"key": "publish", "title": f"提交变更提案({st['dirty']} 处未发布)",
"hint": "变更经审批后发布成新版本,运行时才会生效"})
# 动作要某个业务角色审批,却没人担任这个角色:审批单会一直卡着没人能批
from ..governance import roles as biz_roles
members = {r["name"]: r["members"] for r in biz_roles.list_roles()}
need = sorted({r for a in service.rt_by_kind("action")
for r in ((a.get("spec") or {}).get("approval") or {}).get("approver_roles") or []
if not members.get(r)})
if need:
steps.append({"key": "members", "title": f"给审批角色指派人员({'、'.join(need)})",
"hint": "动作要这些角色审批,现在没人担任,审批单会没人能批"})
if pending_reviews:
steps.append({"key": "modeling", "title": f"审核 AI 草案({pending_reviews} 条)",
"hint": "采纳后进入草稿,再走变更提案"})
return {"workspace": get(ws), "counts": c,
"mapped": {"object_total": c["object_type"], "object_unmapped": len(unmapped)},
"revision": st["revision"], "dirty": st["dirty"], "datasources": len(dss),
"pipelines": pipe_info, "pending_approvals": actions.count_pending(actor),
"pending_reviews": pending_reviews, "next_steps": steps[:5]}
...@@ -48,13 +48,16 @@ async def lifespan(app: FastAPI): ...@@ -48,13 +48,16 @@ async def lifespan(app: FastAPI):
log.warning("清理了 %d 个上次进程残留的未完成任务", reaped) log.warning("清理了 %d 个上次进程残留的未完成任务", reaped)
init_state() init_state()
bootstrap_setup() bootstrap_setup()
from .kernel import pipeline
if pipeline.reap_stale():
log.warning("清理了上次进程残留的数据管道 / 业务建模运行")
gov_users.seed() gov_users.seed()
sop_triggers.start_scheduler() sop_triggers.start_scheduler()
log.info("服务启动完成,数据目录 %s", settings.data_path) log.info("服务启动完成,数据目录 %s", settings.data_path)
yield yield
app = FastAPI(title="Ontology 本体系统", version="3.0.0", lifespan=lifespan) app = FastAPI(title="本体认知引擎 Ontology Engine", version="5.0.0", lifespan=lifespan)
bootstrap_setup() bootstrap_setup()
......
...@@ -2,19 +2,23 @@ ...@@ -2,19 +2,23 @@
PLAN_SYSTEM = """你是企业本体系统的问答规划器。用户的问题可能是: PLAN_SYSTEM = """你是企业本体系统的问答规划器。用户的问题可能是:
- 知识类:定义、口径、规则、流程怎么做 —— 查本体概念、检索文档、查流程 - 知识类:定义、口径、规则、流程怎么做 —— 查本体概念、检索文档、查流程
- 数据类:查数、排名、趋势 —— 一律交给问数 Agent data.ask(它自己决定按指标取数还是写 SQL) - 数据类:查数、排名、趋势 —— 一律交给问数 Agent data_ask(它自己决定按指标取数还是写 SQL)
- 混合类:既要数据又要解释(为什么没达标 / 差多少 / 该怎么办)—— 取数 + 查规则/口径 + 检索依据 - 混合类:既要数据又要解释(为什么没达标 / 差多少 / 该怎么办)—— 取数 + 查规则/口径 + 检索依据
- 影响类:某个对象出了问题会波及谁 —— 用 impact_analysis(沿关系网多跳推)
- 行动类:要做点什么(标记、派任务、通知)—— 只能「建议」已登记的动作,系统会让人审批后才执行 - 行动类:要做点什么(标记、派任务、通知)—— 只能「建议」已登记的动作,系统会让人审批后才执行
你要输出一个执行计划(JSON),系统会按计划调用函数,然后另一位同事根据结果写答案。 你要输出一个执行计划(JSON),系统会按计划通过 MCP 调用工具,然后另一位同事根据结果写答案。
【可用函数】(只读,可以放进 steps) 【可用工具】(只读,可以放进 steps)
{functions} {functions}
【可用 AI 分析函数】(调用写 "skill:函数名") 【已发布的函数与指标】(execute_function 的 name 只能用这里的名称;规则按 vars 传参)
{ontology}
【可用 AI 分析函数】(结果仅供参考;调用写 run_analysis,args {{"name":函数名,"inputs":{{...}}}})
{skills} {skills}
【已发布 SOP】(标准流程;需要按流程排查时用 sop.playbook,问流程怎么做用 sop.find) 【已发布流程卡】(标准流程;需要按流程排查时用 execute_runcard,问流程怎么做用 find_runcard)
{sops} {sops}
【可建议的动作】(不能放进 steps!只能放进 suggest_actions,由人审批) 【可建议的动作】(不能放进 steps!只能放进 suggest_actions,由人审批)
...@@ -24,19 +28,23 @@ PLAN_SYSTEM = """雿隡雿頂蝏蝑憸 ...@@ -24,19 +28,23 @@ PLAN_SYSTEM = """雿隡雿頂蝏蝑憸
{{ {{
"intent": "knowledge|data|mixed|process|action|meta|chitchat", "intent": "knowledge|data|mixed|process|action|meta|chitchat",
"rewrite": "把省略、指代补全后的完整问题", "rewrite": "把省略、指代补全后的完整问题",
"steps": [{{"id":"s1","call":"函数名 或 skill:技能名","args":{{...}},"why":"为什么要这一步"}}], "steps": [{{"id":"s1","call":"工具名","args":{{...}},"why":"为什么要这一步"}}],
"suggest_actions": [{{"action":"动作名","params":{{...}},"object_key":"对象主键(动作作用于对象时)","reason":"建议理由"}}], "suggest_actions": [{{"action":"动作名","params":{{...}},"object_key":"对象主键(动作作用于对象时)","reason":"建议理由"}}],
"suggest_sops": [{{"sop":"SOP 标题","params":{{...}},"reason":"..."}}], "suggest_sops": [{{"sop":"SOP 标题","params":{{...}},"reason":"..."}}],
"clarify": "问题信息不足、无法规划时,向用户追问的一句话;否则为空" "clarify": "问题信息不足、无法规划时,向用户追问的一句话;否则为空"
}} }}
规则: 规则:
1. steps 最多 5 步。后面的步骤可以用 "$s1.字段" 引用前一步结果(例如 "$s1.value")。 1. steps 最多 5 步。后面的步骤可以用 "$s1.字段" 引用前一步结果(例如 "$s1.value")。
2. 取数一律用 data.ask,把时间、对象、拆分方式写进 question;规则/决策表求值用 function.eval; 2. 取数一律用 data_ask,把时间、对象、拆分方式写进 question;规则/决策表/模型推理求值用 execute_function;
问定义/口径用 concept.lookup + knowledge.search; 问定义/口径用 lookup_concept + search_knowledge;
问流程用 sop.find + knowledge.search(流程库里可能还没有,文档里一定有描述)。 问流程用 find_runcard + search_knowledge(流程库里可能还没有,文档里一定有描述)。
概念定义往往只有一句话,细节(取值、阈值、例外情况)要靠 knowledge.search 找原文。 概念定义往往只有一句话,细节(取值、阈值、例外情况)要靠 search_knowledge 找原文。
3. 数据问题一定要取数(data.ask),不要只检索文档。 3. 数据问题一定要取数(data_ask),不要只检索文档。
4. 只在用户明确要求处理/行动、或数据显示明显异常且有对应动作时,才给 suggest_actions;参数必须是能从问题或链接结果中确定的值。 4. 只在用户明确要求处理/行动、或数据显示明显异常且有对应动作时,才给 suggest_actions。
参数要靠数据才定得下来时(如补多少、缺口多大),先在 steps 里安排取数,参数写成 "$s1.字段" 或留空,
系统会在取数之后按结果补全参数,再给人确认;不要因为参数还没算出来就不给动作建议。
对象里没有名称列时(如「仓库 × 商品」的库存行),用 data_ask 把条件写清楚去查,不要用 query_objects 按名称搜。
为动作取数时,把算参数要用到的字段一次问全(如在库、在途、安全库存、补货批量、单价),再用规则函数计算。
5. 闲聊或与业务无关的问题:intent=chitchat,steps 为空。 5. 闲聊或与业务无关的问题:intent=chitchat,steps 为空。
6. 只输出 JSON。 6. 只输出 JSON。
""" """
...@@ -60,9 +68,12 @@ ANSWER_SYSTEM = """雿隡雿頂蝏銵 ...@@ -60,9 +68,12 @@ ANSWER_SYSTEM = """雿隡雿頂蝏銵
3. 引用文档原文或概念出处时在句末加原文角标,直接用方括号里的片段编号,例如原文前缀是 [d2:c17] 就写 [^d2:c17], 3. 引用文档原文或概念出处时在句末加原文角标,直接用方括号里的片段编号,例如原文前缀是 [d2:c17] 就写 [^d2:c17],
不要加 run: 前缀;只能用执行结果里出现过的编号。概念定义本身不需要角标。 不要加 run: 前缀;只能用执行结果里出现过的编号。概念定义本身不需要角标。
4. 涉及指标时,说明口径(统计周期、分母怎么取)—— 口径信息在执行结果的概念定义/指标口径里。 4. 涉及指标时,说明口径(统计周期、分母怎么取)—— 口径信息在执行结果的概念定义/指标口径里。
5. 如果有「建议的动作」或「建议的流程」,在最后用一小段说明「可以做什么」,并明确这些需要人工审批/确认后才会执行。 5. 如果有「建议的动作」或「建议的流程」,在最后用一小段说明「可以做什么」:动作已经在答案下方生成了审批卡,
6. 执行失败或拿不到数据的,如实说明缺什么、可能的原因,不要硬答。 请用户核对参数后点「提交审批」,审批通过才会执行。不要让用户「去业务系统里操作」。
7. 使用 Markdown,表格数据超过 3 行时用表格展示前几行。 6. 执行失败或拿不到数据的,如实说明缺什么、可能的原因,不要硬答。读者是业务人员:不要写步骤编号(s1、s3)
和技术报错原文,换成业务语言(如「规则计算没跑通,按手册公式手算为 200」)。
7. 执行结果里没有查到的事实(如供应商当前状态)不要下结论,说明「未查询」或建议核对。
8. 使用 Markdown,表格数据超过 3 行时用表格展示前几行。
""" """
ANSWER_USER = """【问题】 ANSWER_USER = """【问题】
......
...@@ -7,7 +7,10 @@ ...@@ -7,7 +7,10 @@
→ [4] 作答(流式):结论 + 数据 + 口径 + 原文角标 [^chunk] + 数据角标 [^run:id] → [4] 作答(流式):结论 + 数据 + 口径 + 原文角标 [^chunk] + 数据角标 [^run:id]
→ [5] 动作建议卡:系统先做预览(将改什么),用户点「提交审批」才会进入审批 → [5] 动作建议卡:系统先做预览(将改什么),用户点「提交审批」才会进入审批
同步生成器 yield 事件,由 deps.sse 桥接成 SSE(和旧的两条管线同一套机制)。 提问是本体的一个 **MCP 客户端**:规划器看到的是 MCP 工具目录,每一步都经 `mcp.call_logged`
执行(审计 via=ask)—— 和外部 Agent 同一份能力、同一套权限与数据范围、同一条审计链,没有内部特权通道。
同步生成器 yield 事件,由 deps.sse 桥接成 SSE。
""" """
from __future__ import annotations from __future__ import annotations
...@@ -23,7 +26,7 @@ from typing import Any, Iterator ...@@ -23,7 +26,7 @@ from typing import Any, Iterator
from fastapi import HTTPException from fastapi import HTTPException
from sqlalchemy import func, select from sqlalchemy import func, select
from ..capability import actions, defs, registry, skills from ..capability import actions, defs, mcp
from ..core import identity, llm from ..core import identity, llm
from ..core.dbx import iso, jdump, jload, new_id, now, session from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit, llmlog from ..governance import audit, llmlog
...@@ -118,10 +121,10 @@ def get_turn(turn_id: str) -> dict: ...@@ -118,10 +121,10 @@ def get_turn(turn_id: str) -> dict:
# ---------------- 规划 ---------------- # ---------------- 规划 ----------------
def _catalog_text() -> dict: def _catalog_text() -> dict:
fns = [] fns = []
for f in registry.FUNCTIONS.values(): for t in mcp.tools(planner=True):
props = "; ".join(f"{k}: {v.get('description', '')}" props = "; ".join(f"{k}: {v.get('description', '')}"
for k, v in (f.input_schema.get("properties") or {}).items()) for k, v in (t["inputSchema"].get("properties") or {}).items())
fns.append(f"- {f.name}:{f.description} 参数 {{{props}}}") fns.append(f"- {t['name']}:{t['description']} 参数 {{{props}}}")
sk = [f"- {s['name']}:{s['description']} 输入 {[i['name'] for i in s['spec'].get('inputs') or []]}" sk = [f"- {s['name']}:{s['description']} 输入 {[i['name'] for i in s['spec'].get('inputs') or []]}"
for s in defs.list_defs("skill", "published")] for s in defs.list_defs("skill", "published")]
acts = [] acts = []
...@@ -135,7 +138,26 @@ def _catalog_text() -> dict: ...@@ -135,7 +138,26 @@ def _catalog_text() -> dict:
from ..sop import service as sop_service from ..sop import service as sop_service
sops = [f"- {d['title']}:{d['description']}" for d in sop_service.list_defs(status="published")][:30] sops = [f"- {d['title']}:{d['description']}" for d in sop_service.list_defs(status="published")][:30]
return {"functions": "\n".join(fns), "skills": "\n".join(sk) or "(无)", return {"functions": "\n".join(fns), "skills": "\n".join(sk) or "(无)",
"actions": "\n".join(acts) or "(无)", "sops": "\n".join(sops) or "(无)"} "actions": "\n".join(acts) or "(无)", "sops": "\n".join(sops) or "(无)",
"ontology": _ontology_text()}
def _ontology_text(limit: int = 40) -> str:
"""已发布的函数与指标:规划器按真实名称调用,而不是猜一个「补货规则」出来。"""
out = []
for c in ksvc.rt_by_kind("function")[:limit]:
sp = c.get("spec") or {}
cat = sp.get("category")
if cat == "aggregate":
sig = f"指标,单位 {sp.get('unit') or '-'},口径:{sp.get('formula_text') or ''}(取数用 data_ask 或 query_metric)"
elif cat == "rule":
sig = f"规则,vars {sp.get('params') or []}:{sp.get('expression') or sp.get('text') or ''}"
elif cat == "decision":
sig = f"决策表,inputs {[i.get('name') for i in sp.get('inputs') or []]}"
else:
sig = c.get("kind_label") or cat or ""
out.append(f"- {c['name']}:{sig}")
return "\n".join(out) or "(无)"
def _links_text(links: dict) -> str: def _links_text(links: dict) -> str:
...@@ -191,17 +213,20 @@ def plan(question: str, links: dict, hist: list[dict]) -> dict: ...@@ -191,17 +213,20 @@ def plan(question: str, links: dict, hist: list[dict]) -> dict:
p = {} p = {}
if not isinstance(p, dict) or not isinstance(p.get("steps"), list): if not isinstance(p, dict) or not isinstance(p.get("steps"), list):
p = {"intent": "knowledge", "steps": [ p = {"intent": "knowledge", "steps": [
{"id": "s1", "call": "knowledge.search", "args": {"query": question}, {"id": "s1", "call": "search_knowledge", "args": {"query": question},
"why": "规划失败,先做知识检索"}]} "why": "规划失败,先做知识检索"}]}
steps = [] steps = []
for i, st in enumerate(p.get("steps") or []): for i, st in enumerate(p.get("steps") or []):
if not isinstance(st, dict) or not st.get("call"): if not isinstance(st, dict) or not st.get("call"):
continue continue
call = str(st["call"]) args = st.get("args") if isinstance(st.get("args"), dict) else {}
if call in registry.TOOLS: # 规划器越权:工具不能直接调 try:
tool, args = mcp.resolve(str(st["call"]), args)
except HTTPException: # 目录里没有(含有副作用的工具):规划器越权,丢掉
continue
if tool.name in _NOT_A_STEP:
continue continue
steps.append({"id": str(st.get("id") or f"s{i + 1}"), "call": call, steps.append({"id": str(st.get("id") or f"s{i + 1}"), "call": tool.name, "args": args,
"args": st.get("args") if isinstance(st.get("args"), dict) else {},
"why": str(st.get("why") or "")}) "why": str(st.get("why") or "")})
p["steps"] = steps[:MAX_STEPS] p["steps"] = steps[:MAX_STEPS]
_ensure_evidence(p, question, links) _ensure_evidence(p, question, links)
...@@ -210,6 +235,10 @@ def plan(question: str, links: dict, hist: list[dict]) -> dict: ...@@ -210,6 +235,10 @@ def plan(question: str, links: dict, hist: list[dict]) -> dict:
return p return p
# 提议动作只能进 suggest_actions 让人确认;ask 会递归
_NOT_A_STEP = {"propose_action", "get_action_status", "ask"}
def _ensure_evidence(p: dict, question: str, links: dict) -> None: def _ensure_evidence(p: dict, question: str, links: dict) -> None:
"""兜底:知识 / 流程 / 混合类问题一定要有原文检索。 """兜底:知识 / 流程 / 混合类问题一定要有原文检索。
...@@ -221,11 +250,11 @@ def _ensure_evidence(p: dict, question: str, links: dict) -> None: ...@@ -221,11 +250,11 @@ def _ensure_evidence(p: dict, question: str, links: dict) -> None:
if intent == "chitchat": if intent == "chitchat":
return return
calls = [s["call"] for s in p["steps"]] calls = [s["call"] for s in p["steps"]]
if "knowledge.search" in calls: if "search_knowledge" in calls:
return return
if intent in ("knowledge", "process", "mixed", "meta", "action") or not calls: if intent in ("knowledge", "process", "mixed", "meta", "action") or not calls:
p["steps"].append({ p["steps"].append({
"id": f"s{len(p['steps']) + 1}", "call": "knowledge.search", "id": f"s{len(p['steps']) + 1}", "call": "search_knowledge",
"args": {"query": p.get("rewrite") or question, "args": {"query": p.get("rewrite") or question,
"concepts": [c["name"] for c in links.get("concepts") or []][:8]}, "concepts": [c["name"] for c in links.get("concepts") or []][:8]},
"why": "补充文档原文证据"}) "why": "补充文档原文证据"})
...@@ -237,21 +266,17 @@ def _resolve_args(v: Any, results: dict[str, Any]) -> Any: ...@@ -237,21 +266,17 @@ def _resolve_args(v: Any, results: dict[str, Any]) -> Any:
def _stream_call(call: str, args: dict) -> Iterator[dict]: def _stream_call(call: str, args: dict) -> Iterator[dict]:
"""在后台线程里调用能力,把它的进度事件实时吐出来;最后一条是 {"_result"} 或 {"_error"}。""" """在后台线程里经 MCP 调用工具,把它的进度事件实时吐出来;最后一条是 {"_result"} 或 {"_error"}。"""
q: queue.Queue = queue.Queue() q: queue.Queue = queue.Queue()
ctx = contextvars.copy_context() ctx = contextvars.copy_context()
actor = identity.current()
def work(): def work():
try: try:
if call.startswith("skill:"): ok, res = mcp.call_logged(actor, call, args, "ask", emit=q.put)
res = skills.run(call.split(":", 1)[1], args, emit=q.put) q.put({"_result": res} if ok else {"_error": str(res)})
else:
res = registry.call_function(call, args, emit=q.put)
q.put({"_result": res})
except HTTPException as e:
q.put({"_error": str(e.detail)})
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
log.exception("能力调用失败 %s", call) log.exception("工具调用失败 %s", call)
q.put({"_error": str(e)[:400]}) q.put({"_error": str(e)[:400]})
threading.Thread(target=lambda: ctx.run(work), daemon=True).start() threading.Thread(target=lambda: ctx.run(work), daemon=True).start()
...@@ -328,31 +353,87 @@ def _result_text(step: dict, res: Any) -> str: ...@@ -328,31 +353,87 @@ def _result_text(step: dict, res: Any) -> str:
return "\n".join(parts) return "\n".join(parts)
def _prepare_suggestions(p: dict, links: dict) -> list[dict]: def _prepare_suggestions(p: dict, links: dict, results: dict | None = None,
results_text: str = "") -> list[dict]:
"""把规划里的动作建议变成可提交的卡片。参数常常要等取数之后才定得下来(补多少、给哪个仓):
先替换 $s1.字段 引用;还不能通过校验,就拿执行结果让模型补一次参数。卡片带上参数定义,人可以改了再提交。"""
out = [] out = []
for s in p.get("suggest_actions") or []: for s in p.get("suggest_actions") or []:
ref = str(s.get("action") or "") ref = str(s.get("action") or "")
a = defs.find(ref, "action") a = defs.find(ref, "action")
params = _resolve_args(s.get("params") or {}, results or {})
card = {"action": ref, "display_name": (a or {}).get("display_name") or ref, card = {"action": ref, "display_name": (a or {}).get("display_name") or ref,
"params": s.get("params") or {}, "object_key": str(s.get("object_key") or ""), "params": params if isinstance(params, dict) else {},
"object_key": str(_resolve_args(s.get("object_key") or "", results or {}) or ""),
"reason": s.get("reason") or ""} "reason": s.get("reason") or ""}
if a is None or a["status"] != "published": if a is None or a["status"] != "published":
card["error"] = "动作不存在或未发布" card["error"] = "动作不存在或未发布"
else: out.append(card)
if not card["object_key"] and a["spec"].get("target_type"): continue
spec = a["spec"]
card["action_id"] = a["id"]
card["param_defs"] = spec.get("params") or []
card["target_type"] = spec.get("target_type") or ""
if not card["object_key"] and spec.get("target_type"):
inst = next((i for i in links.get("instances") or [] inst = next((i for i in links.get("instances") or []
if i["concept_id"] == a["spec"]["target_type"]), None) if i["concept_id"] == spec["target_type"]), None)
if inst: if inst:
card["object_key"] = inst["key"] card["object_key"] = inst["key"]
try: try:
card["preview"] = actions.prepare(a["id"], card["params"], card["object_key"]) card["preview"] = actions.prepare(a["id"], card["params"], card["object_key"])
card["action_id"] = a["id"]
except HTTPException as e: except HTTPException as e:
card["error"] = str(e.detail) card["error"] = str(e.detail)
fixed = _fill_params(a, card, results_text, links) if results_text else None
if fixed:
try:
card["preview"] = actions.prepare(a["id"], fixed["params"], fixed["object_key"])
card.update(params=fixed["params"], object_key=fixed["object_key"])
card.pop("error", None)
except HTTPException as e2:
card["error"] = str(e2.detail)
out.append(card) out.append(card)
return out return out
FILL_PROMPT = """根据执行结果,给业务动作「{name}」填参数。
动作说明:{desc}
作用对象:{target}(object_key 填它的主键;从本体链接或执行结果里找)
参数定义:{params}
前置条件:{criteria}
用户问题:{question}
已识别的对象:{links}
执行结果:
{results}
规则:数字参数只写数字;枚举参数只能取给定值;算出来的量按业务规则算(如补货量按批量向上取整)。
确实定不下来的参数留空字符串。只输出 JSON:{{"object_key":"...","params":{{...}},"why":"一句话说明怎么算的"}}"""
def _fill_params(a: dict, card: dict, results_text: str, links: dict) -> dict | None:
spec = a["spec"]
target = ""
if spec.get("target_type"):
ot = ksvc.rt_get(spec["target_type"]) or {}
target = ot.get("name") or spec["target_type"]
try:
res = llm.chat_json([{"role": "user", "content": FILL_PROMPT.format(
name=a.get("display_name") or a["name"], desc=a.get("description") or "", target=target or "无",
params=json.dumps(spec.get("params") or [], ensure_ascii=False),
criteria=";".join(c["expression"] for c in spec.get("criteria") or []) or "无",
question=card.get("reason") or "", links=_links_text(links),
results=llm.truncate_to_tokens(results_text, 6000))}], temperature=0)
except Exception as e: # noqa: BLE001
log.info("补全动作参数失败:%s", str(e)[:120])
return None
if not isinstance(res, dict):
return None
params = {k: v for k, v in (res.get("params") or {}).items() if v not in ("", None)}
if res.get("why"):
card["reason"] = f"{card.get('reason') or ''}({res['why']})".strip()
return {"params": params, "object_key": str(res.get("object_key") or card.get("object_key") or "")}
def run(question: str, conversation_id: str = "", overrides: dict | None = None) -> Iterator[dict]: def run(question: str, conversation_id: str = "", overrides: dict | None = None) -> Iterator[dict]:
started = time.time() started = time.time()
actor = identity.current() actor = identity.current()
...@@ -432,15 +513,15 @@ def run(question: str, conversation_id: str = "", overrides: dict | None = None) ...@@ -432,15 +513,15 @@ def run(question: str, conversation_id: str = "", overrides: dict | None = None)
yield {"type": "step_event", "step_id": st["id"], "event": ev} yield {"type": "step_event", "step_id": st["id"], "event": ev}
step_log.append(rec) step_log.append(rec)
# 4) 动作建议(只预览) # 4) 动作建议(只预览):参数依赖取数结果的,拿结果补全
cards = _prepare_suggestions(p, links) results_text = "\n\n".join(_result_text(rec, results.get(rec["id"])) for rec in step_log) \
or "(没有执行任何步骤)"
cards = _prepare_suggestions(p, links, results, results_text)
sops = p["suggest_sops"] sops = p["suggest_sops"]
if cards: if cards:
yield {"type": "actions", "items": cards} yield {"type": "actions", "items": cards}
# 5) 作答 # 5) 作答
results_text = "\n\n".join(_result_text(rec, results.get(rec["id"])) for rec in step_log) \
or "(没有执行任何步骤)"
cards_text = "\n".join(f"- {c['display_name']}:{c.get('preview', {}).get('summary') or c.get('error')}" cards_text = "\n".join(f"- {c['display_name']}:{c.get('preview', {}).get('summary') or c.get('error')}"
f"(理由:{c['reason']})" for c in cards) or "(无)" f"(理由:{c['reason']})" for c in cards) or "(无)"
sops_text = "\n".join(f"- {s.get('sop')}:{s.get('reason', '')}" for s in sops) or "(无)" sops_text = "\n".join(f"- {s.get('sop')}:{s.get('reason', '')}" for s in sops) or "(无)"
......
...@@ -300,7 +300,7 @@ def run_query(question: str, graph: GraphStore, index: HybridIndex, ...@@ -300,7 +300,7 @@ def run_query(question: str, graph: GraphStore, index: HybridIndex,
"""深挖检索主入口。 """深挖检索主入口。
`answer=False`:只检索不作答,最后吐一条 `retrieved`(上下文 + 证据), `answer=False`:只检索不作答,最后吐一条 `retrieved`(上下文 + 证据),
供统一提问把它当作 knowledge.search 函数调用。 供统一提问把它当作 search_knowledge 工具调用。
`seeds_hint`:编排层已经链接到的概念名,补进理解结果的实体词里,定位更准。 `seeds_hint`:编排层已经链接到的概念名,补进理解结果的实体词里,定位更准。
""" """
started = time.time() started = time.time()
......
...@@ -61,12 +61,13 @@ class DeleteNodesRequest(BaseModel): ...@@ -61,12 +61,13 @@ class DeleteNodesRequest(BaseModel):
# ---------------- 数据问答(Text-to-SQL)---------------- # ---------------- 数据问答(Text-to-SQL)----------------
class DataSourceCreate(BaseModel): class DataSourceCreate(BaseModel):
name: str = Field(min_length=1, max_length=128) name: str = Field(min_length=1, max_length=128)
ds_type: Literal["mysql"] = "mysql" ds_type: Literal["mysql", "postgres"] = "mysql" # 本地文件走 /datasources/file 上传
host: str = Field(min_length=1, max_length=255) host: str = Field(min_length=1, max_length=255)
port: int = Field(default=3306, ge=1, le=65535) port: int = Field(default=3306, ge=1, le=65535)
db_name: str = Field(min_length=1, max_length=128) db_name: str = Field(min_length=1, max_length=128)
username: str = Field(min_length=1, max_length=128) username: str = Field(min_length=1, max_length=128)
password: str = "" password: str = ""
extra: dict = Field(default_factory=dict) # {"schema": "public"}(PG)、{"tables": "otlgt3_dm_*"}(表范围)
class DataSourceUpdate(BaseModel): class DataSourceUpdate(BaseModel):
...@@ -77,6 +78,7 @@ class DataSourceUpdate(BaseModel): ...@@ -77,6 +78,7 @@ class DataSourceUpdate(BaseModel):
username: str | None = Field(default=None, max_length=128) username: str | None = Field(default=None, max_length=128)
# None = 不改(前端不回显明文);"" = 清空。这两种情况必须能区分开。 # None = 不改(前端不回显明文);"" = 清空。这两种情况必须能区分开。
password: str | None = None password: str | None = None
extra: dict | None = None
class ModelUpdate(BaseModel): class ModelUpdate(BaseModel):
......
...@@ -68,8 +68,11 @@ DRAFT_USER = """要生成的流程:{topic} ...@@ -68,8 +68,11 @@ DRAFT_USER = """要生成的流程:{topic}
""" """
def _catalog() -> dict: def _catalog(extra: dict | None = None) -> dict:
fns = "\n".join(f"- {f.name}:{f.description}" for f in registry.FUNCTIONS.values()) """extra:业务建模时这次草案里的积木(还没采纳成概念,但流程卡要按它们的名字引用)。"""
# 带上参数名:不写清楚模型就会自己起名字(data.ask 写成 prompt),运行时才报错
fns = "\n".join(f"- {f.name}:{f.description} 参数 {list((f.input_schema or {}).get('properties') or {})}"
for f in registry.FUNCTIONS.values())
sk = "\n".join(f"- {s['name']}:{s['description']}" for s in defs.list_defs("skill")) or "(无)" sk = "\n".join(f"- {s['name']}:{s['description']}" for s in defs.list_defs("skill")) or "(无)"
ac = "\n".join( ac = "\n".join(
f"- {a['name']}:{a['description']} 参数:{[p['name'] for p in a['spec'].get('params') or []]}" f"- {a['name']}:{a['description']} 参数:{[p['name'] for p in a['spec'].get('params') or []]}"
...@@ -80,13 +83,20 @@ def _catalog() -> dict: ...@@ -80,13 +83,20 @@ def _catalog() -> dict:
return "、".join(c["name"] for c in ksvc.list_concepts(kind=kind, limit=300) return "、".join(c["name"] for c in ksvc.list_concepts(kind=kind, limit=300)
if not category or c.get("category") == category) or "(无)" if not category or c.get("category") == category) or "(无)"
from ..governance import roles from ..governance import roles
return {"functions": fns, "skills": sk, "actions": ac, out = {"functions": fns, "skills": sk, "actions": ac,
"roles": "、".join(roles.names()) or "(无)", "roles": "、".join(roles.names()) or "(无)",
"metrics": names("function", "aggregate"), "rules": names("function", "rule"), "metrics": names("function", "aggregate"), "rules": names("function", "rule"),
"calendars": names("function", "calendar"), "object_types": names("object_type")} "calendars": names("function", "calendar"), "object_types": names("object_type")}
for k, v in (extra or {}).items():
if v:
base = "" if out.get(k) in ("(无)", "", None) else out[k]
out[k] = (base + ("\n" if k == "actions" else "、") + v).lstrip("、\n")
return out
def generate(topic: str, process_concept_id: str = "") -> dict: def generate(topic: str, process_concept_id: str = "", chunks: list[dict] | None = None,
extra_catalog: dict | None = None) -> dict:
"""chunks 给了就直接拿它当依据(业务建模的 SOP 编排阶段),否则去知识库检索。"""
from ..capability.builtins import knowledge_search from ..capability.builtins import knowledge_search
topic = (topic or "").strip() topic = (topic or "").strip()
concept = None concept = None
...@@ -96,6 +106,7 @@ def generate(topic: str, process_concept_id: str = "") -> dict: ...@@ -96,6 +106,7 @@ def generate(topic: str, process_concept_id: str = "") -> dict:
topic += f"({concept.get('description', '')})" if concept.get("description") else "" topic += f"({concept.get('description', '')})" if concept.get("description") else ""
if not topic: if not topic:
raise HTTPException(422, "请说明要生成哪个流程") raise HTTPException(422, "请说明要生成哪个流程")
if chunks is None:
try: try:
found = knowledge_search({"query": f"{topic} 的流程、步骤、角色、判定条件"}, None) found = knowledge_search({"query": f"{topic} 的流程、步骤、角色、判定条件"}, None)
chunks = found.get("chunks") or [] chunks = found.get("chunks") or []
...@@ -106,7 +117,7 @@ def generate(topic: str, process_concept_id: str = "") -> dict: ...@@ -106,7 +117,7 @@ def generate(topic: str, process_concept_id: str = "") -> dict:
for c in chunks[:8]) or "(没有检索到文档依据,请基于常识给出最小可用流程)" for c in chunks[:8]) or "(没有检索到文档依据,请基于常识给出最小可用流程)"
messages = [{"role": "system", "content": DRAFT_SYSTEM}, messages = [{"role": "system", "content": DRAFT_SYSTEM},
{"role": "user", "content": DRAFT_USER.format(topic=topic, evidence=evidence, {"role": "user", "content": DRAFT_USER.format(topic=topic, evidence=evidence,
**_catalog())}] **_catalog(extra_catalog))}]
with llmlog.feature("sop_draft"): with llmlog.feature("sop_draft"):
try: try:
raw = llm.chat_json(messages, temperature=0.2) raw = llm.chat_json(messages, temperature=0.2)
......
...@@ -34,6 +34,8 @@ def _dict(d: SopDefinition, full: bool = True) -> dict: ...@@ -34,6 +34,8 @@ def _dict(d: SopDefinition, full: bool = True) -> dict:
"ai_generated": bool(d.ai_generated), "created_by": d.created_by, "ai_generated": bool(d.ai_generated), "created_by": d.created_by,
"created_at": iso(d.created_at), "updated_at": iso(d.updated_at), "created_at": iso(d.created_at), "updated_at": iso(d.updated_at),
"step_count": len(spec.get("steps") or []), "step_count": len(spec.get("steps") or []),
"step_types": [st.get("type") for st in spec.get("steps") or []],
"priority": spec.get("priority") or "P2", "domain": spec.get("domain") or "",
"trigger_kind": (spec.get("trigger") or {}).get("kind", "manual")} "trigger_kind": (spec.get("trigger") or {}).get("kind", "manual")}
dr = out["last_dry_run"] dr = out["last_dry_run"]
out["dry_run_ok"] = bool(dr.get("ok") and dr.get("hash") == d.draft_hash) out["dry_run_ok"] = bool(dr.get("ok") and dr.get("hash") == d.draft_hash)
......
...@@ -97,7 +97,10 @@ def normalize(spec: dict | None) -> dict: ...@@ -97,7 +97,10 @@ def normalize(spec: dict | None) -> dict:
"condition": str(m.get("condition") or ""), "condition": str(m.get("condition") or ""),
"object_param": str(m.get("object_param") or ""), "object_param": str(m.get("object_param") or ""),
"at": str(m.get("at") or "08:00")} "at": str(m.get("at") or "08:00")}
return {"params": params, "roles": [str(r) for r in spec.get("roles") or [] if r], prio = str(spec.get("priority") or "P2").upper()
return {"priority": prio if prio in ("P0", "P1", "P2", "P3") else "P2",
"domain": str(spec.get("domain") or "")[:32],
"params": params, "roles": [str(r) for r in spec.get("roles") or [] if r],
"trigger": trigger, "start": str(spec.get("start") or (steps[0]["id"] if steps else "")), "trigger": trigger, "start": str(spec.get("start") or (steps[0]["id"] if steps else "")),
"steps": steps, "evidence": list(spec.get("evidence") or [])} "steps": steps, "evidence": list(spec.get("evidence") or [])}
......
"""SOP 触发器:定时、指标条件。 """SOP 触发器:定时、指标条件;顺带驱动数据管道的定时同步。
- schedule:每天/每周/每月的某个时刻启动一次; - schedule:每天/每周/每月的某个时刻启动一次;
- metric:到点后按指标取数(按对象维度拆分),对满足条件的每个对象各启动一次, - metric:到点后按指标取数(按对象维度拆分),对满足条件的每个对象各启动一次,
...@@ -125,6 +125,11 @@ def start_scheduler() -> None: ...@@ -125,6 +125,11 @@ def start_scheduler() -> None:
tick() tick()
except Exception: # noqa: BLE001 except Exception: # noqa: BLE001
log.exception("SOP 调度异常") log.exception("SOP 调度异常")
try:
from ..kernel import pipeline
pipeline.tick()
except Exception: # noqa: BLE001
log.exception("数据管道调度异常")
threading.Thread(target=loop, name="sop-scheduler", daemon=True).start() threading.Thread(target=loop, name="sop-scheduler", daemon=True).start()
"""连接器抽象。 """连接器抽象。
首期只有 MySQL,但接口按「能再加一种就加一种」的粒度切好: 已有 MySQL(含 MariaDB)、PostgreSQL、本地文件(导入 SQLite)。接口按「能再加一种就加一种」的粒度切好:
方言名、连接测试、schema 内省、只读执行。P3 加 PG/Doris 时只要再实现一个子类。 方言名、连接测试、schema 内省、只读执行。再加一种(Doris、ClickHouse……)只要再实现一个子类。
注意这些连接完全独立于 `core.db.engine`(那个是本系统自己的元数据库)。 注意这些连接完全独立于 `core.db.engine`(那个是本系统自己的元数据库)。
业务库的凭据、权限、超时都是另一套,绝不能混用同一个 engine。 业务库的凭据、权限、超时都是另一套,绝不能混用同一个 engine。
...@@ -93,5 +93,28 @@ class Connector: ...@@ -93,5 +93,28 @@ class Connector:
def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult: def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
raise NotImplementedError raise NotImplementedError
def write_row(self, table: str, values: dict[str, Any], key_column: str = "", key: Any = None) -> int:
"""写回业务库:key 为 None 时 INSERT,否则按主键 UPDATE。返回影响行数。
run_sql 永远只读;只有数据源开启了「写回业务库」、并且是审批通过的动作,才会走到这里
(调用方 kernel/objects 负责校验)。表名、列名走 SQLAlchemy 的标识符转义,值全部参数化。
"""
from sqlalchemy import column, insert, table as sa_table, update
t = sa_table(table, *[column(c) for c in dict.fromkeys([*values, key_column]) if c])
engine = getattr(self, "engine", None)
if engine is None:
raise QueryFailed(f"{self.dialect} 数据源不支持写回")
with engine.begin() as c:
if key is None:
return c.execute(insert(t).values(**values)).rowcount or 0
return c.execute(update(t).where(t.c[key_column] == key).values(**values)).rowcount or 0
def delete_row(self, table: str, key_column: str, key: Any) -> int:
"""只用于撤销「在业务库新建」的动作。"""
from sqlalchemy import column, delete, table as sa_table
t = sa_table(table, column(key_column))
with self.engine.begin() as c: # type: ignore[attr-defined]
return c.execute(delete(t).where(t.c[key_column] == key)).rowcount or 0
def dispose(self) -> None: def dispose(self) -> None:
pass pass
"""PostgreSQL 连接器(驱动 psycopg2,按需安装:pip install psycopg2-binary)。
和 MySQL 一样三层防护:只读事务 + statement_timeout + fetchmany 硬截断;SQL 只读性在 guard.py。
内省走 information_schema(只看 extra.schema 指定的 schema,默认 public)。
"""
from __future__ import annotations
import logging
import time
from sqlalchemy import create_engine, text as sa_text
from sqlalchemy.engine import Engine
from sqlalchemy.exc import SQLAlchemyError
from .base import (
ColumnInfo, ConnectionFailed, Connector, ForeignKeyInfo, Introspection,
QueryFailed, QueryResult, TableInfo,
)
from .mysql import _clean, _is_pii, _jsonable, _short
log = logging.getLogger(__name__)
def _q(name: str) -> str:
return '"' + str(name).replace('"', '""') + '"'
class PostgresConnector(Connector):
dialect = "postgres"
def __init__(self, ds: dict, password: str):
super().__init__(ds, password)
self._engine: Engine | None = None
@property
def schema(self) -> str:
return str((self.ds.get("extra") or {}).get("schema") or "public")
@property
def engine(self) -> Engine:
if self._engine is None:
try:
import psycopg2 # noqa: F401
except ImportError as e:
raise ConnectionFailed("服务器没有安装 PostgreSQL 驱动:pip install psycopg2-binary") from e
from urllib.parse import quote_plus
url = (f"postgresql+psycopg2://{quote_plus(self.ds['username'])}:{quote_plus(self.password)}"
f"@{self.ds['host']}:{int(self.ds['port'] or 5432)}/{self.ds['db_name']}")
self._engine = create_engine(url, pool_pre_ping=True, pool_recycle=1800, pool_size=3,
max_overflow=2, future=True,
connect_args={"connect_timeout": 10,
"options": "-c default_transaction_read_only=on"})
return self._engine
def dispose(self) -> None:
if self._engine is not None:
self._engine.dispose()
self._engine = None
def test(self) -> dict:
try:
with self.engine.connect() as c:
version = c.execute(sa_text("SELECT version()")).scalar_one()
db = c.execute(sa_text("SELECT current_database()")).scalar_one()
n = c.execute(sa_text("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = :s"),
{"s": self.schema}).scalar_one()
writable = c.execute(sa_text(
"SELECT has_database_privilege(current_user, current_database(), 'CREATE')")).scalar_one()
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
return {"version": str(version).split(",")[0], "database": str(db), "table_count": int(n),
"account_writable": bool(writable)}
def introspect(self) -> Introspection:
try:
with self.engine.connect() as c:
tables: dict[str, TableInfo] = {}
for name, ttype in c.execute(sa_text(
"SELECT table_name, table_type FROM information_schema.tables "
"WHERE table_schema = :s ORDER BY table_name"), {"s": self.schema}).fetchall():
tables[name] = TableInfo(name=name, kind="view" if "VIEW" in str(ttype) else "table")
for name, comment, rows in c.execute(sa_text(
"SELECT c.relname, obj_description(c.oid), c.reltuples::bigint FROM pg_class c "
"JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :s"),
{"s": self.schema}).fetchall():
if name in tables:
tables[name].comment = comment or ""
tables[name].row_count_est = max(0, int(rows or 0))
for t, col, dtype, nullable, default, comment in c.execute(sa_text(
"SELECT c.table_name, c.column_name, c.data_type, c.is_nullable, c.column_default, "
"col_description((quote_ident(c.table_schema)||'.'||quote_ident(c.table_name))::regclass, "
"c.ordinal_position) FROM information_schema.columns c WHERE c.table_schema = :s "
"ORDER BY c.table_name, c.ordinal_position"), {"s": self.schema}).fetchall():
if t in tables:
tables[t].columns.append(ColumnInfo(name=col, data_type=str(dtype), nullable=nullable == "YES",
comment=comment or "",
default="" if default is None else str(default)))
fks = []
for kind, t, col, rt, rc in c.execute(sa_text(
"SELECT tc.constraint_type, kcu.table_name, kcu.column_name, ccu.table_name, ccu.column_name "
"FROM information_schema.table_constraints tc "
"JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name "
"AND tc.table_schema = kcu.table_schema "
"LEFT JOIN information_schema.constraint_column_usage ccu "
"ON tc.constraint_name = ccu.constraint_name AND tc.table_schema = ccu.table_schema "
"WHERE tc.table_schema = :s AND tc.constraint_type IN ('PRIMARY KEY','FOREIGN KEY')"),
{"s": self.schema}).fetchall():
if kind == "PRIMARY KEY" and t in tables and col not in tables[t].primary_key:
tables[t].primary_key.append(col)
elif kind == "FOREIGN KEY" and rt:
fks.append(ForeignKeyInfo(from_table=t, from_column=col, to_table=rt, to_column=rc))
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
return Introspection(tables=list(tables.values()), foreign_keys=fks)
def sample_values(self, table: str, column: str, limit: int, max_distinct: int) -> tuple[list[str], int]:
if limit <= 0 or _is_pii(column):
return [], 0
t, c_ = f"{_q(self.schema)}.{_q(table)}", _q(column)
try:
with self.engine.connect() as c:
c.execute(sa_text("SET statement_timeout = 5000"))
total = int(c.execute(sa_text(
f"SELECT COUNT(*) FROM (SELECT DISTINCT {c_} FROM {t} WHERE {c_} IS NOT NULL "
f"LIMIT {int(max_distinct) + 1}) x")).scalar_one() or 0)
if total == 0 or total > max_distinct:
return [], total
rows = c.execute(sa_text(f"SELECT {c_}, COUNT(*) AS n FROM {t} WHERE {c_} IS NOT NULL "
f"GROUP BY {c_} ORDER BY n DESC LIMIT {int(limit)}")).fetchall()
except SQLAlchemyError:
return [], 0
return [_short(r[0]) for r in rows], total
def null_ratios(self, table: str, columns: list[str], sample: int = 50000) -> dict[str, float]:
if not columns:
return {}
parts = ", ".join(f"SUM(CASE WHEN {_q(c)} IS NULL THEN 1 ELSE 0 END)" for c in columns)
try:
with self.engine.connect() as c:
c.execute(sa_text("SET statement_timeout = 30000"))
row = c.execute(sa_text(f"SELECT COUNT(*), {parts} FROM (SELECT * FROM "
f"{_q(self.schema)}.{_q(table)} LIMIT {int(sample)}) x")).fetchone()
except SQLAlchemyError:
return {}
total = int((row or [0])[0] or 0)
return {col: float(row[i + 1] or 0) / total for i, col in enumerate(columns)} if total else {}
def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
started = time.time()
try:
with self.engine.connect() as c:
c.execute(sa_text(f"SET statement_timeout = {int(timeout_ms)}"))
c.execute(sa_text(f"SET search_path TO {_q(self.schema)}"))
cur = c.execute(sa_text(sql))
cols = list(cur.keys())
rows = cur.fetchmany(row_limit + 1)
except SQLAlchemyError as e:
raise QueryFailed(_clean(e)) from e
truncated = len(rows) > row_limit
rows = rows[:row_limit]
return QueryResult(columns=cols, rows=[[_jsonable(v) for v in r] for r in rows],
row_count=len(rows), duration_ms=int((time.time() - started) * 1000),
truncated=truncated)
...@@ -9,9 +9,14 @@ import threading ...@@ -9,9 +9,14 @@ import threading
from .base import Connector from .base import Connector
from .mysql import MySQLConnector from .mysql import MySQLConnector
from .postgres import PostgresConnector
from .sqlite_file import SQLiteFileConnector
# 键就是 sqlglot 的方言名:guard 与执行都按它解析 SQL。MariaDB 用 mysql。
_REGISTRY: dict[str, type[Connector]] = { _REGISTRY: dict[str, type[Connector]] = {
"mysql": MySQLConnector, "mysql": MySQLConnector,
"postgres": PostgresConnector,
"sqlite": SQLiteFileConnector, # 本地文件(CSV / Excel / JSON 导入)
} }
_lock = threading.RLock() _lock = threading.RLock()
......
"""本地文件数据源:上传的 CSV / Excel / JSON 导进一个只属于该数据源的 SQLite 库,之后就是普通的 SQL 数据源。
内省、问数、对象绑定、数据管道全部复用同一套管线 —— 只是方言换成 sqlite。
运行时用只读 URI 打开(mode=ro),生成的 SQL 就算绕过了 guard 也写不进去。
"""
from __future__ import annotations
import csv
import io
import json
import logging
import re
import sqlite3
import time
from pathlib import Path
from typing import Any
from sqlalchemy import create_engine, text as sa_text
from sqlalchemy.engine import Engine
from sqlalchemy.exc import SQLAlchemyError
from .base import (
ColumnInfo, ConnectionFailed, Connector, ForeignKeyInfo, Introspection,
QueryFailed, QueryResult, TableInfo,
)
from .mysql import _clean, _is_pii, _jsonable, _short
log = logging.getLogger(__name__)
FILE_TYPES = (".csv", ".tsv", ".xlsx", ".xlsm", ".json")
_BAD = re.compile(r"[^\w一-鿿]+")
def _q(name: str) -> str:
return '"' + str(name).replace('"', '""') + '"'
class SQLiteFileConnector(Connector):
dialect = "sqlite"
def __init__(self, ds: dict, password: str):
super().__init__(ds, password)
self._engine: Engine | None = None
@property
def path(self) -> Path:
return Path(self.ds.get("db_name") or "")
@property
def engine(self) -> Engine:
if self._engine is None:
if not self.path.exists():
raise ConnectionFailed(f"数据文件不存在:{self.path.name}(请重新上传)")
uri = f"file:{self.path.as_posix()}?mode=ro"
self._engine = create_engine("sqlite://", future=True,
creator=lambda: sqlite3.connect(uri, uri=True,
check_same_thread=False))
return self._engine
def dispose(self) -> None:
if self._engine is not None:
self._engine.dispose()
self._engine = None
def test(self) -> dict:
try:
with self.engine.connect() as c:
n = c.execute(sa_text("SELECT COUNT(*) FROM sqlite_master WHERE type IN ('table','view')")).scalar_one()
ver = c.execute(sa_text("SELECT sqlite_version()")).scalar_one()
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
return {"version": f"SQLite {ver}(本地文件)", "database": self.path.name,
"table_count": int(n), "account_writable": False}
def introspect(self) -> Introspection:
try:
with self.engine.connect() as c:
tables = []
fks: list[ForeignKeyInfo] = []
for name, ttype in c.execute(sa_text(
"SELECT name, type FROM sqlite_master WHERE type IN ('table','view') "
"AND name NOT LIKE 'sqlite_%' AND name != '_onto_files' ORDER BY name")).fetchall():
t = TableInfo(name=name, kind=ttype, comment="")
t.row_count_est = int(c.execute(sa_text(f"SELECT COUNT(*) FROM {_q(name)}")).scalar_one() or 0)
for _, cname, ctype, notnull, default, pk in c.execute(
sa_text(f"PRAGMA table_info({_q(name)})")).fetchall():
t.columns.append(ColumnInfo(name=cname, data_type=str(ctype or "TEXT"),
nullable=not notnull,
default="" if default is None else str(default)))
if pk:
t.primary_key.append(cname)
for row in c.execute(sa_text(f"PRAGMA foreign_key_list({_q(name)})")).fetchall():
fks.append(ForeignKeyInfo(from_table=name, from_column=row[3], to_table=row[2],
to_column=row[4]))
tables.append(t)
meta = {}
try:
meta = {r[0]: r[1] for r in c.execute(sa_text(
"SELECT table_name, source FROM _onto_files")).fetchall()}
except SQLAlchemyError:
pass
for t in tables:
if t.name in meta:
t.comment = f"来自文件 {meta[t.name]}"
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
return Introspection(tables=tables, foreign_keys=fks)
def sample_values(self, table: str, column: str, limit: int, max_distinct: int) -> tuple[list[str], int]:
if limit <= 0 or _is_pii(column):
return [], 0
try:
with self.engine.connect() as c:
total = int(c.execute(sa_text(
f"SELECT COUNT(*) FROM (SELECT DISTINCT {_q(column)} FROM {_q(table)} "
f"WHERE {_q(column)} IS NOT NULL LIMIT {int(max_distinct) + 1})")).scalar_one() or 0)
if total == 0 or total > max_distinct:
return [], total
rows = c.execute(sa_text(
f"SELECT {_q(column)}, COUNT(*) AS c FROM {_q(table)} WHERE {_q(column)} IS NOT NULL "
f"GROUP BY {_q(column)} ORDER BY c DESC LIMIT {int(limit)}")).fetchall()
except SQLAlchemyError:
return [], 0
return [_short(r[0]) for r in rows], total
def null_ratios(self, table: str, columns: list[str], sample: int = 50000) -> dict[str, float]:
if not columns:
return {}
parts = ", ".join(f"SUM(CASE WHEN {_q(c)} IS NULL OR {_q(c)} = '' THEN 1 ELSE 0 END)"
for c in columns)
try:
with self.engine.connect() as c:
row = c.execute(sa_text(f"SELECT COUNT(*), {parts} FROM "
f"(SELECT * FROM {_q(table)} LIMIT {int(sample)})")).fetchone()
except SQLAlchemyError:
return {}
total = int((row or [0])[0] or 0)
if not total:
return {}
return {col: float(row[i + 1] or 0) / total for i, col in enumerate(columns)}
def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
started = time.time()
deadline = started + timeout_ms / 1000.0
try:
with self.engine.connect() as c:
raw = c.connection.driver_connection
raw.set_progress_handler(lambda: 1 if time.time() > deadline else 0, 10000)
cur = c.execute(sa_text(sql))
cols = list(cur.keys())
rows = cur.fetchmany(row_limit + 1)
raw.set_progress_handler(None, 0)
except SQLAlchemyError as e:
msg = _clean(e)
raise QueryFailed("查询超时" if "interrupted" in msg else msg) from e
truncated = len(rows) > row_limit
rows = rows[:row_limit]
return QueryResult(columns=cols, rows=[[_jsonable(v) for v in r] for r in rows],
row_count=len(rows), duration_ms=int((time.time() - started) * 1000),
truncated=truncated)
# ---------------- 导入 ----------------
def _table_name(stem: str, used: set[str]) -> str:
base = _BAD.sub("_", stem).strip("_").lower() or "sheet"
if base[0].isdigit():
base = f"t_{base}"
name, i = base[:48], 2
while name in used:
name = f"{base[:44]}_{i}"
i += 1
used.add(name)
return name
def _rows_from(name: str, raw: bytes) -> list[tuple[str, list[str], list[list[Any]]]]:
"""返回 [(表名来源, 表头, 行)]。Excel 每个工作表一张表。"""
suffix = Path(name).suffix.lower()
stem = Path(name).stem
if suffix in (".csv", ".tsv"):
from ...ingest.parse import decode_text
text, _ = decode_text(raw)
reader = list(csv.reader(io.StringIO(text), delimiter="\t" if suffix == ".tsv" else ","))
reader = [r for r in reader if any(str(x).strip() for x in r)]
return [(stem, reader[0], reader[1:])] if reader else []
if suffix in (".xlsx", ".xlsm"):
import openpyxl
wb = openpyxl.load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
out = []
for ws in wb.worksheets:
rows = [list(r) for r in ws.iter_rows(values_only=True) if any(v not in (None, "") for v in r)]
if rows:
out.append((f"{stem}_{ws.title}" if len(wb.worksheets) > 1 else stem,
[str(x or f"col{i + 1}") for i, x in enumerate(rows[0])], rows[1:]))
return out
if suffix == ".json":
data = json.loads(raw.decode("utf-8-sig"))
if isinstance(data, dict):
data = next((v for v in data.values() if isinstance(v, list)), [data])
data = [x for x in data if isinstance(x, dict)]
head = list(dict.fromkeys(k for x in data for k in x))
return [(stem, head, [[x.get(k) for k in head] for x in data])] if head else []
raise ValueError(f"暂不支持的文件类型:{suffix}(支持 {'、'.join(FILE_TYPES)})")
def _col_type(vals: list[Any]) -> str:
seen = [v for v in vals if v not in (None, "")]
if not seen:
return "TEXT"
def isint(v):
return isinstance(v, bool) is False and (isinstance(v, int) or (isinstance(v, str) and re.fullmatch(r"-?\d{1,18}", v.strip())))
def isnum(v):
if isinstance(v, (int, float)) and not isinstance(v, bool):
return True
try:
float(str(v).replace(",", ""))
return True
except ValueError:
return False
if all(isint(v) for v in seen):
return "INTEGER"
if all(isnum(v) for v in seen):
return "REAL"
return "TEXT"
def import_files(path: Path, files: list[tuple[str, bytes]]) -> list[dict]:
"""把文件导进 SQLite 库(同名表覆盖)。返回每张表的导入结果。"""
path.parent.mkdir(parents=True, exist_ok=True)
con = sqlite3.connect(path)
out = []
try:
con.execute("CREATE TABLE IF NOT EXISTS _onto_files (table_name TEXT PRIMARY KEY, source TEXT)")
used = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
for fname, raw in files:
for stem, head, rows in _rows_from(fname, raw):
prev = con.execute("SELECT table_name FROM _onto_files WHERE source = ?",
(f"{fname}:{stem}",)).fetchone()
table = prev[0] if prev else _table_name(stem, used)
cols, seen = [], set()
for i, h in enumerate(head):
c = _BAD.sub("_", str(h or "")).strip("_") or f"col{i + 1}"
while c in seen:
c = f"{c}_{i + 1}"
seen.add(c)
cols.append(c)
width = len(cols)
rows = [list(r[:width]) + [None] * (width - len(r)) for r in rows]
types = [_col_type([r[i] for r in rows[:2000]]) for i in range(width)]
def conv(v, t):
if v in (None, ""):
return None
if t == "INTEGER":
return int(str(v).strip()) if not isinstance(v, int) else v
if t == "REAL":
return float(str(v).replace(",", "")) if not isinstance(v, (int, float)) else v
return v.isoformat() if hasattr(v, "isoformat") else str(v)
con.execute(f"DROP TABLE IF EXISTS {_q(table)}")
con.execute(f"CREATE TABLE {_q(table)} ("
+ ", ".join(f"{_q(c)} {t}" for c, t in zip(cols, types)) + ")")
con.executemany(f"INSERT INTO {_q(table)} VALUES ({', '.join('?' * width)})",
[[conv(v, t) for v, t in zip(r, types)] for r in rows])
con.execute("INSERT OR REPLACE INTO _onto_files VALUES (?, ?)", (table, f"{fname}:{stem}"))
out.append({"table": table, "file": fname, "rows": len(rows), "columns": width})
con.commit()
finally:
con.close()
return out
...@@ -11,7 +11,9 @@ ...@@ -11,7 +11,9 @@
已经采过的列除非明确要求,否则跳过。 已经采过的列除非明确要求,否则跳过。
""" """
from __future__ import annotations from __future__ import annotations
import fnmatch
import json import json
import re
import logging import logging
import datetime as dt import datetime as dt
from typing import Iterator from typing import Iterator
...@@ -30,6 +32,8 @@ log = logging.getLogger(__name__) ...@@ -30,6 +32,8 @@ log = logging.getLogger(__name__)
# 一次内省最多处理多少张表。超过就截断并警告 —— 几千张表的库不该整库建模, # 一次内省最多处理多少张表。超过就截断并警告 —— 几千张表的库不该整库建模,
# 应该先在建模页里挑出真正要查的那些。 # 应该先在建模页里挑出真正要查的那些。
MAX_TABLES = 600 MAX_TABLES = 600
# 表数不超过它时,内省会自动推导并启用表间关系(每条候选要对业务库发两条抽样 SQL)
AUTO_RELATION_MAX_TABLES = 40
def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]: def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
...@@ -64,7 +68,15 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]: ...@@ -64,7 +68,15 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
yield {"stage": "error", "error": f"读取表结构失败:{str(e)[:400]}"} yield {"stage": "error", "error": f"读取表结构失败:{str(e)[:400]}"}
return return
tables = intro.tables # 表范围:业务库往往有几百张表,只内省用户圈定的那些(如 otlgt3_dm_*)。
# 圈定过范围就说明这些表是要用的,直接启用,省掉再去逐张勾选。
scope = table_scope(semantic.get_datasource(ds_id) or {})
tables = [t for t in intro.tables if in_scope(t.name, scope)]
if scope:
intro.foreign_keys = [fk for fk in intro.foreign_keys
if in_scope(fk.from_table, scope) and in_scope(fk.to_table, scope)]
yield {"stage": "tables", "progress": 7,
"message": f"表范围 {'、'.join(scope)}:命中 {len(tables)}/{len(intro.tables)} 张表"}
truncated = False truncated = False
if len(tables) > MAX_TABLES: if len(tables) > MAX_TABLES:
tables = tables[:MAX_TABLES] tables = tables[:MAX_TABLES]
...@@ -87,7 +99,7 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]: ...@@ -87,7 +99,7 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
row_count_est=t.row_count_est, row_count_est=t.row_count_est,
# 新表默认不启用:几百张表全打开会把提示词撑爆, # 新表默认不启用:几百张表全打开会把提示词撑爆,
# 也让「启用 = 授权可查」这个语义站不住。让用户显式挑。 # 也让「启用 = 授权可查」这个语义站不住。让用户显式挑。
enabled=0) enabled=1 if scope else 0)
s.add(m) s.add(m)
stats["new_models"] += 1 stats["new_models"] += 1
else: else:
...@@ -169,6 +181,10 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]: ...@@ -169,6 +181,10 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
# ---------- 外键 → 关系 ---------- # ---------- 外键 → 关系 ----------
yield {"stage": "relations", "progress": 90, "message": "正在推导表间关系…"} yield {"stage": "relations", "progress": 90, "message": "正在推导表间关系…"}
stats["new_relations"] = _sync_relations(ds_id, intro.foreign_keys, model_id_by_table) stats["new_relations"] = _sync_relations(ds_id, intro.foreign_keys, model_id_by_table)
# 业务库大多不建外键:表不多时顺手按「列名像键 + 目标唯一 + 取值重叠」推关系并启用,
# 否则建模时对象之间连不起来,影响分析、多跳查询都用不了。
if not intro.foreign_keys and len(tables) <= AUTO_RELATION_MAX_TABLES:
stats["new_relations"] += _sync_recommended(ds_id)
semantic.update_datasource(ds_id, status="ok", last_error="", semantic.update_datasource(ds_id, status="ok", last_error="",
last_introspect_at=dt.datetime.now()) last_introspect_at=dt.datetime.now())
...@@ -178,13 +194,23 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]: ...@@ -178,13 +194,23 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
f"推导出 {stats['new_relations']} 条关系。") f"推导出 {stats['new_relations']} 条关系。")
if stats.get("disabled_empty_columns"): if stats.get("disabled_empty_columns"):
msg += f" 另有 {stats['disabled_empty_columns']} 个整列全空的列已自动停用。" msg += f" 另有 {stats['disabled_empty_columns']} 个整列全空的列已自动停用。"
if stats["new_models"]: if stats["new_models"] and not scope:
msg += " 新表默认是停用的,请在建模页里挑出要查的表并启用。" msg += " 新表默认是停用的,请在建模页里挑出要查的表并启用。"
if truncated: if truncated:
msg += f" 注意:表数超过 {MAX_TABLES},只处理了前 {MAX_TABLES} 张。" msg += f" 注意:表数超过 {MAX_TABLES},只处理了前 {MAX_TABLES} 张。"
yield {"stage": "done", "progress": 100, "message": msg, "stats": stats} yield {"stage": "done", "progress": 100, "message": msg, "stats": stats}
def table_scope(ds: dict) -> list[str]:
"""数据源的表范围:extra.tables,逗号或换行分隔的通配符(如 otlgt3_dm_*)。空 = 全部表。"""
raw = str((ds.get("extra") or {}).get("tables") or "")
return [p.strip() for p in re.split(r"[,,\s]+", raw) if p.strip()]
def in_scope(table: str, scope: list[str]) -> bool:
return not scope or any(fnmatch.fnmatch(table.lower(), p.lower()) for p in scope)
# ---------------- 内部 ---------------- # ---------------- 内部 ----------------
def _looks_numeric(data_type: str) -> bool: def _looks_numeric(data_type: str) -> bool:
low = (data_type or "").lower() low = (data_type or "").lower()
...@@ -283,3 +309,22 @@ def _sync_relations(ds_id: int, fks, model_id_by_table: dict[str, int]) -> int: ...@@ -283,3 +309,22 @@ def _sync_relations(ds_id: int, fks, model_id_by_table: dict[str, int]) -> int:
added += 1 added += 1
s.commit() s.commit()
return added return added
def _sync_recommended(ds_id: int) -> int:
"""没有外键时,把推荐出来的关联路径(已过唯一度与重叠率两道校验)直接建成关系。"""
added = 0
try:
recs = semantic.recommend_relations(ds_id)
except Exception as e: # noqa: BLE001
log.warning("推导表间关系失败:%s", str(e)[:200])
return 0
for r in recs:
semantic.upsert_relation(
ds_id, name=f"{r['from_table']}_{r['to_table']}", from_model_id=r["from_model_id"],
from_column=r["from_column"], to_model_id=r["to_model_id"], to_column=r["to_column"],
join_type="inner", cardinality="N:1",
condition_sql=f"{r['from_table']}.{r['from_column']} = {r['to_table']}.{r['to_column']}",
description=f"按列名与取值推导(重叠率 {r['overlap']:.0%})", enabled=1)
added += 1
return added
...@@ -23,6 +23,8 @@ class DataSource(Base): ...@@ -23,6 +23,8 @@ class DataSource(Base):
__tablename__ = "otlgt3_ds" __tablename__ = "otlgt3_ds"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(128)) name: Mapped[str] = mapped_column(String(128))
# 归属的本体空间;空串 = 所有空间共用(老数据)
workspace: Mapped[str] = mapped_column(String(64), default="", index=True)
ds_type: Mapped[str] = mapped_column(String(32), default="mysql") ds_type: Mapped[str] = mapped_column(String(32), default="mysql")
host: Mapped[str] = mapped_column(String(255), default="") host: Mapped[str] = mapped_column(String(255), default="")
port: Mapped[int] = mapped_column(Integer, default=3306) port: Mapped[int] = mapped_column(Integer, default=3306)
......
...@@ -41,6 +41,7 @@ def _ds_dict(r: DataSource, with_secret: bool = False) -> dict: ...@@ -41,6 +41,7 @@ def _ds_dict(r: DataSource, with_secret: bool = False) -> dict:
out = { out = {
"id": r.id, "name": r.name, "ds_type": r.ds_type, "host": r.host, "port": r.port, "id": r.id, "name": r.name, "ds_type": r.ds_type, "host": r.host, "port": r.port,
"db_name": r.db_name, "username": r.username, "read_only": bool(r.read_only), "db_name": r.db_name, "username": r.username, "read_only": bool(r.read_only),
"workspace": r.workspace or "",
"status": r.status, "last_error": r.last_error or "", "status": r.status, "last_error": r.last_error or "",
"has_password": bool(r.password_enc), "has_password": bool(r.password_enc),
"extra": _j(r.extra_json, {}), "extra": _j(r.extra_json, {}),
...@@ -52,9 +53,16 @@ def _ds_dict(r: DataSource, with_secret: bool = False) -> dict: ...@@ -52,9 +53,16 @@ def _ds_dict(r: DataSource, with_secret: bool = False) -> dict:
return out return out
def _ws() -> str:
from ..core import identity
return identity.current().workspace
def list_datasources() -> list[dict]: def list_datasources() -> list[dict]:
"""当前本体空间能用的数据源:本空间的 + 共用的(workspace 为空)。"""
with Session(engine) as s: with Session(engine) as s:
rows = s.scalars(select(DataSource).order_by(DataSource.id.desc())).all() rows = s.scalars(select(DataSource).where(DataSource.workspace.in_(("", _ws())))
.order_by(DataSource.id.desc())).all()
return [_ds_dict(r) for r in rows] return [_ds_dict(r) for r in rows]
...@@ -66,6 +74,8 @@ def get_datasource(ds_id: int, with_secret: bool = False) -> Optional[dict]: ...@@ -66,6 +74,8 @@ def get_datasource(ds_id: int, with_secret: bool = False) -> Optional[dict]:
def create_datasource(**fields: Any) -> int: def create_datasource(**fields: Any) -> int:
password = fields.pop("password", "") or "" password = fields.pop("password", "") or ""
fields["extra_json"] = json.dumps(fields.pop("extra", None) or {}, ensure_ascii=False)
fields.setdefault("workspace", _ws())
with Session(engine) as s: with Session(engine) as s:
d = DataSource(password_enc=crypto.encrypt(password), **fields) d = DataSource(password_enc=crypto.encrypt(password), **fields)
s.add(d) s.add(d)
...@@ -79,6 +89,9 @@ def update_datasource(ds_id: int, **fields: Any) -> None: ...@@ -79,6 +89,9 @@ def update_datasource(ds_id: int, **fields: Any) -> None:
password = fields.pop("password", None) password = fields.pop("password", None)
if password is not None: if password is not None:
fields["password_enc"] = crypto.encrypt(password) fields["password_enc"] = crypto.encrypt(password)
if fields.get("extra") is not None:
fields["extra_json"] = json.dumps(fields.pop("extra"), ensure_ascii=False)
fields.pop("extra", None)
if not fields: if not fields:
return return
with Session(engine) as s: with Session(engine) as s:
......
# 鲜达商贸 · 库存补货业务手册(V1.2)
> 适用范围:采购部、仓储部、运营管理层。本手册是库存补货相关的统一口径,系统建模、报表与审批均以此为准。
## 一、业务概述
鲜达商贸是一家日用快消品分销商,在上海、杭州、南京设有三个仓库,向 5 家核心供应商采购洗护、纸品、粮油、饮品四大品类共 20 个商品,再配送给下游门店。
补货的目标是:**不断货、不压货**。断货会直接损失门店订单,压货会占用资金和库容。
## 二、核心业务对象
| 对象 | 说明 | 唯一标识 | 业务系统表 |
|---|---|---|---|
| 供应商 | 为我们供货的厂商或经销商 | 供应商编号(如 S003) | otlgt3_dm_supplier |
| 商品 | 我们经营的 SKU,每个商品有一个主供应商 | 商品编号(如 P005) | otlgt3_dm_product |
| 仓库 | 存放商品的物理仓 | 仓库编号(如 W01) | otlgt3_dm_warehouse |
| 库存 | 某个仓库里某个商品的库存状况,一条记录对应「仓库 × 商品」 | 库存记录编号 | otlgt3_dm_stock |
| 采购单 | 向供应商下的补货订单 | 采购单号(如 PO20260019) | otlgt3_dm_purchase_order |
## 三、对象之间的关系
- 商品 **由** 供应商供货(商品.主供应商编号 → 供应商)。
- 库存 **属于** 某个仓库(库存.仓库编号 → 仓库),**记录** 某个商品(库存.商品编号 → 商品)。
- 采购单 **采购** 某个商品,**发往** 某个仓库,**下给** 某个供应商。
因此,当一个供应商出现交付问题时,影响链路是:
**供应商 → 它供货的商品 → 这些商品在各仓的库存 → 相关仓库**,以及该供应商名下未完成的采购单。
## 四、业务术语与指标口径
| 术语 | 口径 |
|---|---|
| 在库数量 | 仓库当前实物数量,每日早 7 点盘点更新 |
| 在途数量 | 已下单、尚未到货的采购数量 |
| 可用库存 | 在库数量 + 在途数量 |
| 安全库存 | 每个「仓库 × 商品」单独设定的最低保有量,由仓库主管维护 |
| 库存缺口 | 安全库存 − 可用库存(小于 0 记为 0) |
| 缺货风险 | 可用库存 < 安全库存 |
| 缺货率 | 存在缺货风险的「仓库 × 商品」数 ÷ 全部「仓库 × 商品」数 |
| 供应商准时率 | 近 90 天按时到货的采购单数 ÷ 已到货采购单数;低于 80% 视为交付风险 |
| 超期采购单 | 状态为「已下单」且预计到货日期早于今天的采购单 |
## 五、业务规则
1. **补货触发**:可用库存低于安全库存时,必须发起补货。
2. **补货数量**:补货数量 = 向上取整(库存缺口 ÷ 补货批量) × 补货批量。例如缺口 115、批量 100,应补 200。
3. **供应商选择**:默认向商品的主供应商下单;若主供应商状态为「延期」或「暂停」,补货单需标注风险,并由采购经理决定是否临时换供。
4. **采购金额** = 采购数量 × 采购单价。
5. **超期跟进**:采购单超过预计到货日期仍未到货,采购员需当天联系供应商,并在系统中登记延期原因。
6. **供应商风险**:供应商准时率低于 80%,或存在 2 张及以上超期采购单时,应将其标记为「延期」状态。
## 六、审批规则
| 场景 | 审批人 | 优先级 |
|---|---|---|
| 补货采购单金额 < 5 万元 | 采购员自行确认 | P3 |
| 补货采购单金额 ≥ 5 万元 | 采购经理审批 | P1 |
| 涉及「延期」供应商的补货单 | 采购经理审批 | P0(当天必须处理) |
| 标记 / 解除供应商风险 | 运营总监审批 | P1 |
所有审批必须留痕:审批人、时间、意见和依据数据。
## 七、管理动作
1. **创建补货采购单**
- 输入:商品、仓库、数量。
- 系统按规则计算金额并带出供应商。
- 按审批规则进入审批,通过后生成状态为「待审批 → 已下单」的采购单,并增加对应库存的在途数量。
2. **标记供应商风险**
- 输入:供应商和原因。
- 审批通过后,把供应商状态改为「延期」。
3. **登记采购单延期原因**
- 输入:采购单号和原因。
- 采购员直接登记,无需审批。
## 八、每日补货巡检 SOP(采购员,每天 9:00)
1. 查出所有存在缺货风险的「仓库 × 商品」,按库存缺口从大到小排序。
2. 查出所有超期采购单,逐一联系供应商,登记延期原因。
3. 检查涉及的供应商是否处于「延期」状态,若是,在补货单上标注风险。
4. 对每条缺货记录按补货规则计算建议补货量,发起「创建补货采购单」。
5. 汇总当日巡检结果(缺货条数、建议补货金额、超期单数),发给采购经理。
## 九、管理层关注
- 老板每天关心:**今天有多少商品缺货风险?预计要花多少钱补货?哪个供应商在拖后腿?**
- 采购经理关心:待我审批的单子有哪些?哪些是 P0?
- 仓库主管关心:我仓里哪些商品快不够了?在途什么时候到?
# 库存补货场景 · 全流程走查报告(2026-09-22)
我以真实用户的身份,从一个清空的系统开始,把「鲜达商贸 · 库存补货」这个小场景完整走了一遍:
1. 接入数据;
2. 用业务手册建模;
3. 审核并发布;
4. 老板看数,员工提问、发起补货;
5. 采购经理审批,采购单写回业务库;
6. 跑流程卡;
7. 外部 Agent 调用 MCP。
遇到的问题当场修复,所有修改都补了测试(`pytest tests/` 共 255 个用例,全部通过)。
- 业务手册:[库存补货业务手册.md](库存补货业务手册.md)
- 造数脚本:`scripts/seed_inventory_demo.py`(5 张 `otlgt3_dm_*` 表,数据里故意埋了缺货、供应商延期和超期采购单)
- 整库清空:`scripts/wipe_all.py --yes`(只保留用户、业务角色和运行设置)
- 演示实例:`.claude/launch.json` 里的 `onto-8105`;本体空间是「鲜达商贸·库存补货」(`xianda_inv`)
---
## 一、一句话结论
**改之前**:每个模块单独看都没问题,但串不起来。
- 文档建模出来的对象不绑表;
- 指标没有取数口径,要人手写 SQL;
- 动作只有空壳,而且只能改属性,建不了单据;
- 发布后要手动去数据管道页点同步;
- 提问算不出该补多少货,动作卡提示「暂不能提交」;
- 审批人批不了自己该批的单。
所以用起来「看着很强,实际走不通」。
**改之后**,整条链路能闭环:
- 手册 + 数据库一次建模,草案里对象和关系全部绑好表,指标的取数口径实跑校验过,动作可以直接执行;
- 审核、发布后自动同步数据;
- 员工一句「帮我给上海中心仓补清风抽纸」,系统自己取数,算出补 200 提、9000 元,生成审批卡;
- 采购经理批准后,采购单真正写进业务表 `otlgt3_dm_purchase_order`,而且可以撤销;
- 老板打开「工作台」,就能看到缺货率、库存缺口、供应商准时率。
---
## 二、发现的缺陷与修复
### A. 串不起来的断点(最影响可用性)
| # | 现象 | 原因 | 修复 |
|---|---|---|---|
| A1 | 文档建模出来的对象、关系没有绑定数据表;数据源的「提议到本体」又会生成另一套同名或近名对象 | 建模管道只读文档,不看已接入的数据 | 建模新增 **「数据对齐」** 阶段:已内省的表先翻译成带绑定的种子对象和关系,LLM 必须沿用这些名称;文档叫法优先(「库存(仓库 × 商品)」会被改成「库存」,原名留作别名);文档里的关系按两端自动并入表的关联列,方向相反时列对调。本场景 5 个对象、6 条关系全部自动绑定(`kernel/modeling.py`、`kernel/propose.py`) |
| A2 | 指标(聚合函数)只有口径文字,没有取数表达式,业务人员得去绑定页手写 SQL | 规则深化阶段只处理规则和决策表 | 深化阶段让 AI 写出取数表达式,**在业务库上实跑通过才采用**,跑不通就把报错喂回去重写一次;4/4 个指标自动绑定成功 |
| A3 | 文档里的动作只生成一个「发通知」空壳,要人从头配置参数和效果 | 同上 | 深化阶段补全动作:参数、前置条件、效果。**确定性地校验**:`obj.属性` 必须真实存在、写入的属性必须存在、对象名自动纠正(`supplier` 纠正为「供应商」);校验不通过就反馈给模型,最多重试 3 次。3/3 个动作补全成功 |
| A4 | 动作只能「改属性,而且只写在系统写回层」,不能新建单据;审批通过的补货单在业务里看不到 | 没有新建对象的工具,也没有写回业务库的能力 | 新增 **`object.create`** 工具;数据源增加 **「允许审批通过的动作写回业务库」** 开关(默认关闭)。打开后,`object.write` 和 `object.create` 直接 UPDATE / INSERT 绑定的表和列,写回记录标注 `mode=db/create`,撤销时回滚原值或删除新建的行(`text2sql/connectors/base.py`、`kernel/objects.py`) |
| A5 | 动作参数只能是 `$参数`,算不了「金额 = 数量 × 单价」,也生成不了单号 | 模板能力不够 | 效果参数支持 `=表达式`(沿用规则引擎的安全求值),新增 `$today`、`$now_id` 两个内置变量 |
| A6 | 内省业务库时会把整个库的 120 张表都拉进来 | 没有表范围 | 数据源新增 **「表范围」**(例如 `otlgt3_dm_*`);圈定的表直接启用。数据源编辑时 `extra` 字段也不再丢失(原来编辑一次 PostgreSQL 数据源,schema 就没了) |
| A7 | 业务库没建外键时,表之间连不起来,影响分析和多跳查询都用不了 | 关系推荐功能存在,但只能手动触发 | 内省时如果没有外键、表数 ≤ 40,就自动推导关系并启用(列名像键、目标端唯一、取值重叠率三道校验);本场景 6 条关系全部推对 |
| A8 | 发布后还要到数据管道页手动建管道、点同步,对象搜索和影响分析才能用 | 发布与管道没有联动 | 发布后在后台自动补齐管道并同步一次(设置项 `PIPELINE_AUTO_SYNC`,默认开启) |
| A9 | 员工问「帮我给上海中心仓补清风抽纸」,系统算不出数量,动作卡提示「暂不能提交」 | ① 动作参数必须在规划时就定下来,而那时还没取数;② 规划器看不到已发布的函数和指标名,只能靠猜;③ 找概念时叫法对不上(「补货规则」vs「补货数量计算」) | ① 执行完取数步骤后再补全参数:先替换 `$s1.字段`,还不行就根据结果让模型算一次,再预览;② 规划器的目录里加入已发布的函数和指标(名称、变量、表达式);③ `lookup_concept` 找不到时,按两字片段返回相近的积木;④ 动作卡的参数**可以直接修改**:枚举用下拉、数字直接填,改完点「重新预览」再提交。实测:系统自动算出补 200 提、9000 元,提交后经采购经理批准,采购单写入了业务表 |
| A10 | 以「审批人」身份提示「你没有审批变更的权限」 | 变更提案只认「审核」权限(实施工程师) | 实施工程师或审批人都可以批(提交人本人仍然不能批);待办计数里也把审批人算进来 |
| A11 | 动作要「采购经理」审批,但没人担任这个角色,审批单卡住没人能批;成员页的角色卡片也永远显示「还没有成员」 | ① 业务角色是从文档自动登记的,但没人提醒去指派人员;② 统计角色成员时按本体过滤了用户,而账号是全局的 | ① 首页「建议下一步」新增「给审批角色指派人员」;审批页的提示改成「管理员可在成员与角色里给你加上」;② 统计成员时不再按本体过滤 |
| A12 | `reset_ontology` 清空本体后,审核队列、流程卡草稿、审批单都还留着,而且引用的是已删除的积木 | 清理范围不完整 | 清理范围扩展到当前本体下的审核队列、流程卡及运行记录、动作审批单和待办 |
| A13 | 数据源「提议到本体」会生成和已发布关系重复的关系提议 | 只按名称去重 | 两端对象和关联列都相同,就只补出处、不新建(本次走查中出现的 6 条重复提议已驳回) |
### B. 结果不对、不好懂
| # | 现象 | 修复 |
|---|---|---|
| B1 | 影响分析第 3 跳绕过「仓库」,把所有库存和采购单都算作受影响(库存 48、采购单 20),全是噪音 | 影响分析沿外键「往上」走到的上级对象(库存→仓库)只标为「涉及」,不再从它往外扩散。怎么判断上级:关联列正好是哪一端的主键,哪一端就是上级(不看关系方向,因为「供货」这种名字是业务起的)。现在的结果是:商品 4、采购单 5、库存 12,涉及仓库 3,正好就是手册里写的影响链 |
| B2 | 库存这类没有名称列的对象,显示成「1」「2」「25」 | 管道同步时,用它指向的上级对象名称拼一个显示名(「清风抽纸 3层×24包 · 上海中心仓」),并且让上级对象先同步 |
| B3 | 对象 360 页、影响分析里的属性显示英文列名(`supplier_id`、`lead_days`) | 改用属性的中文显示名(「供应商编号」「标准交期(天)」) |
| B4 | 回答里写「步骤 s3 规则求值失败」这类技术细节;让用户「去业务系统里提交」;没查供应商状态就说「未标记为延期」 | 作答提示词:不暴露步骤编号和技术报错;动作要点答案下方的「提交审批」;没查到的事实不下结论 |
| B5 | AI 写的表达式里混用了 `$qty`、`= 'PO' + $now_id`、`&&`、`null`,导致「语法错误」 | 表达式求值时容忍这些写法(去掉 `$` 和前导 `=`);字符串相加改为拼接;保存动作时也会校验 `=表达式` 里引用的变量 |
| B6 | 流程卡的待办说明里嵌着一大段取数结果的原始字典 | 引用到的取数结果渲染成 Markdown 表格;待办详情按 Markdown 显示;新增「让 AI 帮我处理」按钮,带着待办内容跳到提问页 |
| B7 | 建模时生成的流程卡几乎全是人工任务占位,`data.ask` 参数写错成 `prompt`,还把单个动作也做成了流程 | 函数目录带上参数名;本次草案里的动作和指标也提供给流程卡起草器;单个操作不当作流程。按已发布本体重新起草的「每日补货巡检」,试运行 6/6 通过(缺货 7 条、超期 2 条) |
| B8 | 提问页的示例问题是「本月供应商准时率是多少?」,但这个指标没有时间列,一问就报错 | 示例问题和工作台共用同一份,按真实的指标、维度(中文名)和动作生成 |
| B9 | 草稿审核页看不到积木绑定了哪张表、取数表达式是什么、动作会做什么,审核的人没法把关 | 草案详情显示数据表、关联列、取数 SQL、动作的参数、前置条件、效果和审批人;列表里显示「已绑表 / 取数已校验 / 可执行 / 待补全」 |
### C. 体验问题
| # | 现象 | 修复 |
|---|---|---|
| C1 | 22 个菜单全是搭建期术语(骨架、物化关系边、四元组、MCP),老板和员工不知道从哪里下手 | 新增 **「工作台」** 作为默认首页:打开就看到关键指标、「等我处理」、「我提交的」、可一键运行的常用流程、建议问题和最近动态;**侧栏按权限精简**:业务运营看到 5 个入口,管理层(只读)只看到工作台、提问、对象 360 |
| C2 | 数据源保存后还要回列表点「测试」、再点「内省」 | 保存后自动测试连接,连通了直接内省 |
| C3 | 新建本体必须手填英文标识 | 标识可以不填,由系统自动生成;环境变量里的默认空间统一叫「默认本体」,不再显示「v4」 |
| C4 | 「全部同步」之后页面一直停在「未运行」 | 点击后按时间轮询,直到同步完成 |
| C5 | 「新建对象」的字段要手写 JSON | 选好对象类型后,按属性逐行填值 |
| C6 | 流程卡没有删除或归档入口,做坏的草稿删不掉;「AI 起草」「新建」按钮只有图标 | 新增「归档」按钮;两个按钮都加上文字 |
| C7 | 右侧打开编辑器时,列表名称被挤成一字一行;工作台在窄屏下横向溢出;行删除按钮没有无障碍标签 | 编辑器打开时收起描述列和时间列;网格子元素加 `min-w-0`;删除按钮补上 `title` 和 `aria-label` |
---
## 三、没改、只提建议的
1. **提问太慢**:一次提问要 40 到 70 秒,包括规划、问数写 SQL、补参数、作答,每一步都要调模型。其中 `data_ask` 约 36 秒,检索 6 到 25 秒。我试过把补充检索换成单次检索,实测没有更快,就撤回了。建议:
- 常见问题直接走已发布指标的确定性取数,不经过 LLM 写 SQL;
- 各步骤能并行的并行执行;
- 作答先流式返回结论。
2. **审批优先级没有按手册规则走**:补货单涉及「延期」供应商应该是 P0,现在是按工具风险定成 P1。建议动作支持用「补货审批决策」这张决策表来决定优先级和审批人。
3. **新建采购单后,库存的在途数量不会更新**。所以第二天的巡检还会把上海中心仓的抽纸算作缺货。在真实系统里,在途数量由 ERP 维护,这次演示没有接 ERP。可以选的做法:
- 让「可用库存」按「在库 + 未到货采购单」实时计算;
- 或者给 `object.write` 增加「按条件定位对象」的能力。
4. **流程卡不能按行循环**:比如「对每条缺货各发起一张补货单」做不到,现在只能交给人或者「让 AI 帮我处理」。建议增加 foreach 步骤。
5. **单号不一致**:预览时生成的单号和提交时重新生成的单号不同(`$now_id` 在提交时重新计算),建议提议时把预览的参数冻结下来。
6. **没有登录体系**:身份靠右上角切换,只适合演示。上线前要接 SSO。
7. **AI 起草的内容仍然要人审**:本次「库存缺口」漏算了在途数量,「供应商准时率」没有乘 100,都是我在审核时发现并改掉的。现在审核界面能看到表达式,这类错误一眼就能看出来,但靠的仍是人。
---
## 四、作为人类用户,我会怎么用这个系统
### 实施工程师(一次性搭建,约 1 小时,大部分时间在等 AI)
1. **本体首页 → 新建本体**:填名称即可。
2. **数据连接 → 新建 MySQL**:
- 填连接信息和「表范围」(`otlgt3_dm_*`);
- 需要动作写回业务库的,勾选「允许写回」;
- 保存后系统自动测试连接、读取表结构、推导表间关系。
3. **知识库**:上传业务手册,点「抽取」。
4. **业务建模 → 新建画布**:
- 勾选手册,勾选刚接入的数据源,点运行;
- 大约 4 分钟后拿到草案:对象和关系已绑表,指标的取数口径已实跑校验,动作可以执行,流程卡是草稿。
5. **逐个过一遍草案**,这是最该花时间的地方:
- 指标口径对不对,比如在途有没有算进去、单位对不对;
- 动作的前置条件是否合理;
- 采纳,再到函数页或动作页微调。
6. **成员与角色**:给「采购经理」「采购员」等业务角色指派人员,首页会提醒你。
7. **变更提案 → 提交**:由审批人或另一位实施工程师审批发布。发布后自动同步数据。
8. **流程卡**:用「AI 起草」按当前本体起草日常流程,试运行通过后提交发布。
之后日常只需要看首页的「建议下一步」。
### 老板 / 管理层(每天 1 分钟)
- 打开就是 **工作台**:缺货率 11.7%、库存缺口 495 件、供应商准时率 89%,点任意一个指标就能看按仓库或按供应商拆开的明细。
- 想知道「华南纸品一直延期会影响什么」,直接在输入框里问,或者到对象 360 页对这个供应商跑影响分析:波及 4 个商品、12 条库存、5 张采购单。
- 不需要,也看不到建模、管道、MCP 这些页面。
### 采购员(每天早上 9 点)
1. 工作台 →「每日补货巡检」→ **运行**:缺货清单和超期采购单自动查好,待办里出现「处理超期采购单」「计算补货量并创建补货采购单」。
2. 在待办里点 **「让 AI 帮我处理」**,或者直接问「帮我给上海中心仓的清风抽纸发起补货」:
- 系统查出库存数据,按手册公式算出补货量和金额,生成审批卡;
- 核对或修改数量后点「提交审批」。
3. 在工作台的「我提交的」里查看进度:待审批、已执行、已驳回。
### 采购经理 / 运营总监(审批人)
- 工作台的「等我处理」里会列出审批单,按 P0 到 P3 排序;
- 每张审批单上能看到依据、影响面,以及批准后具体会写什么(「在业务库新建采购单:P005 / W01 / 200 提 / 9000 元」);
- 批准后立即执行,结果写进业务库;写错了可以发起撤销,撤销同样需要审批。
### 外部 Agent(如企业微信机器人、Claude Desktop)
- 在系统设置里填上 MCP 令牌后,就能连接 `/mcp`,共有 18 个工具(查指标、影响分析、提议动作等);
- 它和系统内的「提问」走同一套权限、审计和审批:Agent 只能提议,不能批准;前置条件不满足时直接拒绝(例如 S003 已经是延期状态,不能重复标记)。
---
## 五、复现
```bash
./.venv/Scripts/python.exe scripts/wipe_all.py --yes # 整库清空(只保留用户、角色和设置)
./.venv/Scripts/python.exe scripts/seed_inventory_demo.py # 建 otlgt3_dm_* 业务表并灌数据
cd web && npm run build:8103 # 构建前端,然后用 launch.json 的 onto-8105 启动
./.venv/Scripts/python.exe -m pytest tests/ # 255 个用例
```
# 本体认知引擎(第五版):借鉴「本体认知引擎」演示的调整
分支 `ontology_dev_merge_8103`。上一版见 [ontology_four_tuple.md](ontology_four_tuple.md),四元组积木模型不变。
## 为什么改
对照 2026-09-22 的产品演示,四元组已经对齐了,差距在:
- 没有「本体空间」;
- 建模只是一个向导;
- 只有积木级的影响分析;
- 发布一步到位;
- 运行时有两条通道(提问直调内部函数,MCP 另开一个出口)。
对方的定位是企业的「业务大脑」,只做三件事:
1. 把业务接进来;
2. 建成一个可以推理的世界;
3. 安全地执行管理动作。
## 已确定的取舍
- **提问保留,改成 MCP 客户端。** 编排器只通过 MCP 工具目录调用能力,和外部 Agent 同一份目录、同一个 `call_logged`、同一条审计(`via=ask`)。仍然单体部署。
- **对象数据实时查,另同步骨架。** 业务明细永远实时查业务库。数据管道只同步「骨架」(主键、显示名、关系键、维度属性)到 MySQL,并物化关系边,用于对象搜索和多跳影响分析。元数据库不换 Postgres。
- **知识图谱全部保留。** 抽取、消歧、社区、图谱页都保留,作为「知识库」。
## 变化一览
| 能力 | 做法 | 代码 |
|---|---|---|
| 本体空间 | 首页列出本体卡片,侧栏切换「当前本体」;请求头 `X-Workspace` 隔离积木、版本、动作、审计、管道、数据源 | `kernel/workspaces.py`,`features/home/HomePage.tsx`,`lib/identity.ts` |
| 数据连接 | MySQL / MariaDB / PostgreSQL / 本地文件(CSV、Excel、JSON 导入只读 SQLite)/ REST API(外部端点);「实体映射」页签可以把表一键建成对象 | `text2sql/connectors/{postgres,sqlite_file}.py`,`features/sql/{DataSourcePanel,MappingPanel}.tsx` |
| 数据管道 | 按对象类型同步骨架(分页拉取,突破执行器的行数上限),物化 `onto_link_edge`;支持手动、每小时、每天;「本体数据集」可浏览骨架 | `kernel/pipeline.py`,`features/data/PipelinePage.tsx` |
| 实例级影响分析 | 在关系边上做 BFS,按数据范围过滤,最外层回业务库实时取数;对象 360 和 MCP 的 `impact_analysis` 都用它 | `kernel/traverse.py` |
| 业务建模管道 | 行业路由 → LLM 转换 → 规则深化 → SOP 编排 → 建草稿;每次运行存档,产出四列草案,可导出 .md;支持临时上传(不进知识库) | `kernel/modeling.py`,`features/ontology/ModelingPage.tsx` |
| 变更提案 | 发布和回滚都先提成提案;提交人不能自审(可在设置里放开),AI 不能审;提交后草稿又改过就要重提 | `kernel/service.propose_release / _accept_release` |
| 发布热加载 | `service.on_publish` 进程内事件:刷新运行时缓存和链接器 | `kernel/service.py`,`bootstrap.py` |
| 域 / 映射状态 | 积木加 `spec.domain`;列表返回 `mapped`;对象页可按域分卡片、按映射状态筛选 | `kernel/schema.py`,`BlockListPage.tsx` |
| 函数类别 | 新增 `ml` 模型推理(调用登记过的端点);`ai` 标为「参考」,不作为权威结果 | `kernel/ml.py` |
| MCP 目录 | 按对象、关系、函数、流程卡、动作分组,共 18 个工具;老名字保留别名;目录里没有审批工具 | `capability/mcp.py` |
| 审批单 | 带优先级 P0~P3、依据、影响面(两跳),按优先级排序 | `capability/actions.py` |
| 运行时总览 | 24 小时 MCP 调用量和成功率、Top 工具、待审批、流程卡运行、管道状态 | `features/runtime/OverviewPage.tsx` |
| 流程卡 | 加优先级、域;列表显示步骤类型,可筛选;业务建模会自动蒸馏流程卡草稿 | `sop/spec.py`,`SopPage.tsx` |
## 删掉 / 合并的
- 三步向导 `WizardPage.tsx` 删除,由建模画布取代。
- 「外部系统连接」不再是单独页面,并入「数据连接 → 外部系统 / API」。
- 编排器里直接调用 `registry.call_function` 的路径删除。
- `objects.sync_instances` 删除,统一走 `pipeline.sync_type`。
- 旧路由兼容:`#/wizard` 跳到 `modeling`,`#/endpoints` 和 `#/capability` 跳到 `data?tab=api`。
## 导航
- 本体首页
- 数据集成:数据连接、数据管道、知识库
- 本体建模:业务建模、变更提案、版本管理
- 本体浏览:画布(卡片 / 图谱)、对象、关系、函数、动作、流程卡
- 运行时:总览、MCP 服务、行动审批、调用日志
- 应用:提问、对象 360
- 设置
## 运行
```bash
cd web && npm run build:8103
./.venv/Scripts/python.exe scripts/serve_8103.py # 或 launch.json 的 onto-8103(端口被占时用 onto-8104)
./.venv/Scripts/python.exe -m pytest tests/ # 新能力的测试在 tests/test_engine_v5.py
```
- PostgreSQL 数据源需要安装驱动:`pip install psycopg2-binary`,已写进 requirements。
- 设置里新增两项:
- `RELEASE_SELF_APPROVE`:是否允许单人团队自审;
- `PIPELINE_ROW_LIMIT`:每个对象类型最多同步多少行骨架。
# 本体简化:收成「对象 · 关系 · 函数 · 动作」四种积木 # 本体简化:收成「对象 · 关系 · 函数 · 动作」四种积木
分支 `ontology_dev_merge_8103`,端口 8103。前一版设计见 [ontology_redesign.md](ontology_redesign.md)。 分支 `ontology_dev_merge_8103`,端口 8103。前一版设计见 [ontology_redesign.md](ontology_redesign.md);下一版(本体空间、数据管道、影响分析、变更提案、MCP 唯一出口)见 [ontology_engine_v5.md](ontology_engine_v5.md)。
## 为什么改 ## 为什么改
......
...@@ -20,3 +20,4 @@ SQLAlchemy==2.0.36 ...@@ -20,3 +20,4 @@ SQLAlchemy==2.0.36
PyMySQL==1.1.1 PyMySQL==1.1.1
sqlglot==26.6.0 sqlglot==26.6.0
cryptography>=44.0.0 cryptography>=44.0.0
psycopg2-binary>=2.9 # PostgreSQL 数据源(可选)
...@@ -108,8 +108,10 @@ def main() -> int: ...@@ -108,8 +108,10 @@ def main() -> int:
failed += 1 failed += 1
print(f"采纳失败:{it['title']}:{e}") print(f"采纳失败:{it['title']}:{e}")
try: try:
pub = admin.post("/api/kernel/publish", {"note": f"评测:采纳 {ok} 个提议", "force": True}) # 发布走变更提案:建设者提交,另一个人(管理员)审批
rev = pub["revision"] item = builder.post("/api/kernel/publish", {"note": f"评测:采纳 {ok} 个提议"})
pub = admin.post(f"/api/kernel/releases/{item['id']}/decide", {"approve": True})
rev = (pub.get("result") or {}).get("revision")
except RuntimeError as e: except RuntimeError as e:
rev = f"未发布({e})" rev = f"未发布({e})"
report += ["## 3. 采纳与发布", "", f"- 采纳 {ok} 个,失败 {failed} 个", f"- 发布版本:{rev}", ""] report += ["## 3. 采纳与发布", "", f"- 采纳 {ok} 个,失败 {failed} 个", f"- 发布版本:{rev}", ""]
......
"""清空本体(四元组改造后旧数据不兼容,用它重建)。 """清空本体(四元组改造后旧数据不兼容,用它重建)。
会删除:积木(onto_concept)、绑定、证据、发布版本、写回层、实例名录,以及旧的能力表里的技能/动作定义。 会删除(只限 --workspace 指定的本体):积木、绑定、证据、发布版本、写回层、骨架与关系边、数据管道、建模记录、
审核队列(AI 草案 / 变更提案)、流程卡及其运行、动作审批单与待办,以及旧能力表里的技能 / 动作定义。
保留:数据源与内省结果、文档与图谱、外部端点、用户与角色、审计日志(审计只追加,永不删除)。 保留:数据源与内省结果、文档与图谱、外部端点、用户与角色、审计日志(审计只追加,永不删除)。
整库重置(连数据源、文档、审计一起清)用 scripts/wipe_all.py。
./.venv/Scripts/python.exe scripts/reset_ontology.py --yes ./.venv/Scripts/python.exe scripts/reset_ontology.py --yes
./.venv/Scripts/python.exe scripts/reset_ontology.py --yes --template generic_starter # 顺带导入起步包 ./.venv/Scripts/python.exe scripts/reset_ontology.py --yes --template generic_starter # 顺带导入起步包
...@@ -25,10 +27,12 @@ def main() -> None: ...@@ -25,10 +27,12 @@ def main() -> None:
if not args.yes: if not args.yes:
raise SystemExit("这会清空本体的所有积木与发布版本。确认请加 --yes") raise SystemExit("这会清空本体的所有积木与发布版本。确认请加 --yes")
from sqlalchemy import delete from sqlalchemy import delete, select
from app import bootstrap from app import bootstrap
from app.capability.models import CapabilityDef from app.capability.models import ActionRun, ApprovalTask, CapabilityDef, Task
from app.governance.models import ReviewItem
from app.sop.models import SopDefinition, SopStepRun, SopRun, SopVersion
from app.core import db as core_db from app.core import db as core_db
from app.core import identity from app.core import identity
from app.core.dbx import session from app.core.dbx import session
...@@ -41,7 +45,15 @@ def main() -> None: ...@@ -41,7 +45,15 @@ def main() -> None:
identity.set_current(identity.Actor(workspace=args.workspace)) identity.set_current(identity.Actor(workspace=args.workspace))
with session() as s: with session() as s:
n = 0 n = 0
for table in (km.Concept, km.Binding, km.Evidence, km.Revision, km.ObjectEdit, km.InstanceCache): runs = select(SopRun.id).where(SopRun.workspace == args.workspace)
n += s.execute(delete(SopStepRun).where(SopStepRun.run_id.in_(runs))).rowcount or 0
defs = select(SopDefinition.id).where(SopDefinition.workspace == args.workspace)
n += s.execute(delete(SopVersion).where(SopVersion.def_id.in_(defs))).rowcount or 0
actions = select(ActionRun.id).where(ActionRun.workspace == args.workspace)
n += s.execute(delete(ApprovalTask).where(ApprovalTask.run_id.in_(actions))).rowcount or 0
for table in (km.Concept, km.Binding, km.Evidence, km.Revision, km.ObjectEdit, km.InstanceCache,
km.LinkEdge, km.Pipeline, km.ModelRun, ReviewItem, SopRun, SopDefinition,
ActionRun, Task):
n += s.execute(delete(table).where(table.workspace == args.workspace)).rowcount or 0 n += s.execute(delete(table).where(table.workspace == args.workspace)).rowcount or 0
n += s.execute(delete(CapabilityDef).where(CapabilityDef.workspace == args.workspace, n += s.execute(delete(CapabilityDef).where(CapabilityDef.workspace == args.workspace,
CapabilityDef.kind.in_(("skill", "action")))).rowcount or 0 CapabilityDef.kind.in_(("skill", "action")))).rowcount or 0
......
"""演示场景「库存补货」:在业务库里建 5 张伪业务表 otlgt3_dm_*,并灌入带问题的样例数据。
业务背景:鲜达商贸,一家做日用快消品分销的公司,有 3 个仓、5 家供应商、20 个商品。
数据里故意埋了几个问题,让提问、影响分析、流程卡能查出东西:
- S003 华南纸品交付延期,准时率只有 62%,名下还有一张超期未到的采购单;
- 有若干「仓库 × 商品」的可用库存(在库 + 在途)低于安全库存;
- 一张金额超过 5 万元的采购单待审批。
业务表建在元数据库所在的 MySQL 上(演示用),可重复执行(先 DROP 再建)。
./.venv/Scripts/python.exe scripts/seed_inventory_demo.py
"""
from __future__ import annotations
import datetime as dt
import random
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.stdout.reconfigure(encoding="utf-8")
TODAY = dt.date(2026, 9, 22)
DDL = [
"""CREATE TABLE otlgt3_dm_supplier (
supplier_id VARCHAR(16) PRIMARY KEY COMMENT '供应商编号',
supplier_name VARCHAR(64) NOT NULL COMMENT '供应商名称',
contact VARCHAR(32) COMMENT '联系人',
phone VARCHAR(32) COMMENT '联系电话',
lead_days INT COMMENT '标准交期(天)',
on_time_rate DECIMAL(5,2) COMMENT '近90天准时交付率',
status VARCHAR(16) COMMENT '合作状态:正常/延期/暂停'
) COMMENT='供应商'""",
"""CREATE TABLE otlgt3_dm_warehouse (
warehouse_id VARCHAR(16) PRIMARY KEY COMMENT '仓库编号',
warehouse_name VARCHAR(64) NOT NULL COMMENT '仓库名称',
city VARCHAR(32) COMMENT '所在城市',
manager VARCHAR(32) COMMENT '仓库主管'
) COMMENT='仓库'""",
"""CREATE TABLE otlgt3_dm_product (
product_id VARCHAR(16) PRIMARY KEY COMMENT '商品编号',
product_name VARCHAR(64) NOT NULL COMMENT '商品名称',
category VARCHAR(32) COMMENT '品类',
unit VARCHAR(8) COMMENT '单位',
unit_price DECIMAL(10,2) COMMENT '采购单价(元)',
supplier_id VARCHAR(16) COMMENT '主供应商编号',
reorder_qty INT COMMENT '补货批量(每次补货按它的整数倍下单)'
) COMMENT='商品'""",
"""CREATE TABLE otlgt3_dm_stock (
stock_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '库存记录编号',
warehouse_id VARCHAR(16) NOT NULL COMMENT '仓库编号',
product_id VARCHAR(16) NOT NULL COMMENT '商品编号',
on_hand INT COMMENT '在库数量',
in_transit INT COMMENT '在途数量(已下单未到货)',
safety_stock INT COMMENT '安全库存',
updated_at DATETIME COMMENT '最后盘点时间'
) COMMENT='库存(仓库 × 商品)'""",
"""CREATE TABLE otlgt3_dm_purchase_order (
po_no VARCHAR(20) PRIMARY KEY COMMENT '采购单号',
product_id VARCHAR(16) NOT NULL COMMENT '商品编号',
warehouse_id VARCHAR(16) NOT NULL COMMENT '收货仓库编号',
supplier_id VARCHAR(16) NOT NULL COMMENT '供应商编号',
qty INT COMMENT '采购数量',
amount DECIMAL(12,2) COMMENT '采购金额(元)',
status VARCHAR(16) COMMENT '状态:待审批/已下单/已到货/已取消',
order_date DATE COMMENT '下单日期',
expected_date DATE COMMENT '预计到货日期',
arrived_date DATE COMMENT '实际到货日期'
) COMMENT='采购单'""",
]
SUPPLIERS = [
("S001", "蓝月日化", "王磊", "021-60001001", 5, 0.97, "正常"),
("S002", "清风生活用品", "李娜", "0571-8800202", 7, 0.93, "正常"),
("S003", "华南纸品", "陈志强", "020-3300303", 10, 0.62, "延期"),
("S004", "金龙鱼粮油华东", "赵敏", "021-5500404", 4, 0.98, "正常"),
("S005", "农夫饮品", "周杰", "0571-2200505", 3, 0.95, "正常"),
]
WAREHOUSES = [
("W01", "上海中心仓", "上海", "刘洋"),
("W02", "杭州仓", "杭州", "孙悦"),
("W03", "南京仓", "南京", "吴昊"),
]
PRODUCTS = [ # id, name, category, unit, price, supplier, reorder_qty
("P001", "蓝月亮洗衣液 3kg", "洗护", "瓶", 39.9, "S001", 120),
("P002", "蓝月亮洗手液 500ml", "洗护", "瓶", 12.5, "S001", 200),
("P003", "蓝月亮消毒液 1.2L", "洗护", "瓶", 18.0, "S001", 150),
("P004", "清风洗洁精 1.5kg", "洗护", "瓶", 11.8, "S002", 200),
("P005", "清风抽纸 3层×24包", "纸品", "提", 45.0, "S003", 100),
("P006", "清风卷纸 4层×27卷", "纸品", "提", 52.0, "S003", 100),
("P007", "清风湿巾 80抽×10包", "纸品", "箱", 36.0, "S003", 80),
("P008", "厨房纸巾 2卷装", "纸品", "袋", 9.9, "S003", 300),
("P009", "金龙鱼大米 10kg", "粮油", "袋", 59.0, "S004", 100),
("P010", "金龙鱼调和油 5L", "粮油", "桶", 68.0, "S004", 80),
("P011", "金龙鱼面粉 5kg", "粮油", "袋", 28.0, "S004", 100),
("P012", "香满园挂面 1kg", "粮油", "袋", 8.5, "S004", 300),
("P013", "农夫山泉 550ml×24", "饮品", "箱", 28.8, "S005", 200),
("P014", "东方树叶 500ml×15", "饮品", "箱", 55.0, "S005", 100),
("P015", "尖叫运动饮料 550ml×15", "饮品", "箱", 48.0, "S005", 100),
("P016", "清风牙膏 180g", "洗护", "支", 9.8, "S002", 300),
("P017", "清风牙刷 4支装", "洗护", "盒", 15.9, "S002", 200),
("P018", "清风沐浴露 1L", "洗护", "瓶", 29.9, "S002", 120),
("P019", "金龙鱼玉米油 4L", "粮油", "桶", 72.0, "S004", 60),
("P020", "农夫果园 1.8L×6", "饮品", "箱", 42.0, "S005", 100),
]
# 故意偏低的库存:(仓, 商品) -> (在库, 在途, 安全库存)
LOW = {
("W01", "P005"): (40, 0, 150), # 上海缺抽纸(S003 延期)
("W02", "P005"): (35, 0, 160), # 杭州抽纸:有 100 在途(超期)也不够
("W01", "P006"): (60, 0, 120),
("W03", "P007"): (20, 0, 90),
("W01", "P010"): (30, 0, 80), # 上海调和油低(正常供应商)
("W02", "P013"): (90, 0, 220), # 杭州矿泉水低
("W03", "P001"): (50, 0, 100),
}
def main() -> None:
from sqlalchemy import create_engine, text
from app.core.config import get_settings
rnd = random.Random(20260922)
eng = create_engine(get_settings().sqlalchemy_url, future=True)
with eng.begin() as c:
for t in ("purchase_order", "stock", "product", "warehouse", "supplier"):
c.execute(text(f"DROP TABLE IF EXISTS otlgt3_dm_{t}"))
for ddl in DDL:
c.execute(text(ddl))
c.execute(text("INSERT INTO otlgt3_dm_supplier VALUES (:a,:b,:c,:d,:e,:f,:g)"),
[dict(zip("abcdefg", r)) for r in SUPPLIERS])
c.execute(text("INSERT INTO otlgt3_dm_warehouse VALUES (:a,:b,:c,:d)"),
[dict(zip("abcd", r)) for r in WAREHOUSES])
c.execute(text("INSERT INTO otlgt3_dm_product VALUES (:a,:b,:c,:d,:e,:f,:g)"),
[dict(zip("abcdefg", r)) for r in PRODUCTS])
stock = []
for w, *_ in WAREHOUSES:
for p in PRODUCTS:
pid = p[0]
if (w, pid) in LOW:
on_hand, transit, safety = LOW[(w, pid)]
else:
safety = rnd.choice([60, 80, 100, 120, 150])
on_hand = safety + rnd.randint(20, 300)
transit = 0
stock.append({"w": w, "p": pid, "h": on_hand, "t": transit, "s": safety,
"u": dt.datetime(2026, 9, 22, 7, rnd.randint(0, 59))})
c.execute(text("INSERT INTO otlgt3_dm_stock (warehouse_id, product_id, on_hand, in_transit, "
"safety_stock, updated_at) VALUES (:w,:p,:h,:t,:s,:u)"), stock)
price = {p[0]: p[4] for p in PRODUCTS}
sup = {p[0]: p[5] for p in PRODUCTS}
lead = {s[0]: s[4] for s in SUPPLIERS}
pos = []
n = 0
def po(pid, wid, qty, status, order_days_ago, arrived_late=None):
nonlocal n
n += 1
od = TODAY - dt.timedelta(days=order_days_ago)
ed = od + dt.timedelta(days=lead[sup[pid]])
ad = None
if status == "已到货":
ad = ed + dt.timedelta(days=arrived_late or 0)
pos.append({"no": f"PO2026{n:04d}", "p": pid, "w": wid, "s": sup[pid], "q": qty,
"a": round(qty * price[pid], 2), "st": status, "od": od, "ed": ed, "ad": ad})
# 历史已到货(S003 经常晚到)
for _ in range(18):
pid = rnd.choice(PRODUCTS)[0]
late = rnd.choice([3, 5, 6, 8]) if sup[pid] == "S003" else rnd.choice([0, 0, 0, 1])
po(pid, rnd.choice(WAREHOUSES)[0], rnd.choice([100, 200, 300]), "已到货",
rnd.randint(20, 80), late)
# 在途:杭州抽纸 100(S003,已超期)、其他正常在途
po("P005", "W02", 100, "已下单", 16) # 预计 9/16 到,已超期 6 天
po("P006", "W03", 100, "已下单", 12) # 预计 9/20 到,已超期
po("P009", "W01", 100, "已下单", 2)
po("P013", "W01", 200, "已下单", 1)
# 待审批:一张大额(> 5 万)
po("P010", "W01", 800, "待审批", 0) # 800 × 68 = 54,400
po("P002", "W03", 200, "待审批", 0)
po("P014", "W02", 100, "已取消", 30)
c.execute(text("INSERT INTO otlgt3_dm_purchase_order VALUES "
"(:no,:p,:w,:s,:q,:a,:st,:od,:ed,:ad)"), pos)
# 在途 = 已下单未到货的采购数量,和采购单保持一致
c.execute(text("""UPDATE otlgt3_dm_stock s SET in_transit = COALESCE((
SELECT SUM(qty) FROM otlgt3_dm_purchase_order o WHERE o.status = '已下单'
AND o.product_id = s.product_id AND o.warehouse_id = s.warehouse_id), 0)"""))
for t in ("supplier", "warehouse", "product", "stock", "purchase_order"):
k = c.execute(text(f"SELECT COUNT(*) FROM otlgt3_dm_{t}")).scalar()
print(f"otlgt3_dm_{t:16s} {k} 行")
if __name__ == "__main__":
main()
"""整库清空:把系统恢复成一个干净环境(只清数据,不删表结构)。
会清空:元数据库里所有 onto_* / otlgt3_* 表的行(本体、数据源、文档、流程卡、动作、审批、
对话、审计、评测、调用日志……),以及本地的知识图谱、向量索引、上传文件、LLM 缓存。
保留:用户(onto_user)、业务角色(onto_biz_role)、运行设置(otlgt3_config),
以及伪业务表 otlgt3_dm_*(它们是「业务库」,不是系统数据)。
注意:审计日志平时只追加、永不删除;这个脚本会连它一起清掉,只用于重置演示环境。
./.venv/Scripts/python.exe scripts/wipe_all.py # 只打印各表行数
./.venv/Scripts/python.exe scripts/wipe_all.py --yes # 真的清空
"""
from __future__ import annotations
import argparse
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.stdout.reconfigure(encoding="utf-8")
KEEP = {"onto_user", "onto_biz_role", "otlgt3_config"}
BUSINESS_PREFIX = "otlgt3_dm_"
LOCAL_FILES = ["index", "uploads", "cache/llm", "graph.json", "communities.json", "sop.json"]
def _tables(conn) -> list[str]:
from sqlalchemy import inspect
names = inspect(conn).get_table_names()
return sorted(n for n in names
if (n.startswith("onto_") or n.startswith("otlgt3_"))
and not n.startswith(BUSINESS_PREFIX) and n not in KEEP)
def _counts(conn, tables: list[str]) -> dict[str, int]:
from sqlalchemy import text
return {t: conn.execute(text(f"SELECT COUNT(*) FROM `{t}`")).scalar() or 0 for t in tables}
def main() -> None:
ap = argparse.ArgumentParser(description="整库清空")
ap.add_argument("--yes", action="store_true", help="确认清空")
args = ap.parse_args()
from sqlalchemy import text
from app.core import db as core_db
from app.core.config import get_settings
core_db.init_db()
with core_db.engine.begin() as conn:
tables = _tables(conn)
before = _counts(conn, tables)
total = sum(before.values())
print(f"待清空 {len(tables)} 张表,共 {total} 行:")
for t, n in before.items():
if n:
print(f" {t:32s} {n}")
if not args.yes:
print("\n只做了统计。确认清空请加 --yes(审计日志也会被清掉)。")
return
with core_db.engine.begin() as conn:
conn.execute(text("SET FOREIGN_KEY_CHECKS=0"))
for t in tables:
conn.execute(text(f"DELETE FROM `{t}`"))
conn.execute(text("SET FOREIGN_KEY_CHECKS=1"))
left = sum(_counts(conn, tables).values())
print(f"\n数据库已清空:删除 {total} 行,剩余 {left} 行")
data = get_settings().data_path
for rel in LOCAL_FILES:
p = data / rel
if p.is_dir():
shutil.rmtree(p, ignore_errors=True)
p.mkdir(parents=True, exist_ok=True)
elif p.exists():
p.unlink()
for log in data.glob("*.log"):
try:
log.unlink(missing_ok=True)
except PermissionError: # 正在运行的服务占着日志文件:清空内容即可
log.write_text("", encoding="utf-8")
print(f"本地文件已清空:{data.resolve()}({', '.join(LOCAL_FILES)}、*.log)")
if __name__ == "__main__":
main()
"""借鉴「本体认知引擎」的第五版能力:本体空间、数据管道与关系边、实例级影响分析、变更提案、
MCP 工具目录(提问是 MCP 客户端)、审批单的优先级 / 依据 / 影响面、模型推理函数、业务建模管道、
本地文件数据源、积木的域与映射状态。
复用 test_platform 的夹具:SQLite 元数据库 + 假业务库(store / order_item)+ 打桩 LLM。
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
from fastapi import HTTPException
sys.path.insert(0, str(Path(__file__).parent))
from app.core import identity, llm # noqa: E402
from test_platform import as_user, build_basics, env, make_action # noqa: E402,F401
def add_orders(ds_id: int, store_type_id: str) -> dict:
"""订单对象 + 「订单属于网点」关系,并发布。"""
from app.kernel import service
order = service.create_concept("object_type", "订单", spec={
"domain": "订单",
"properties": [{"name": "编号", "is_key": True}, {"name": "金额", "data_type": "number"},
{"name": "网点", "is_dimension": True}]})
service.set_binding(order["id"], ds_id, "table", {
"table": "order_item", "key_column": "id", "columns": {"编号": "id", "金额": "amount",
"网点": "store_id"}})
link = service.create_concept("link_type", "下单网点", spec={
"from_type": order["id"], "to_type": store_type_id, "cardinality": "n:1"})
service.set_binding(link["id"], ds_id, "join", {"from_column": "store_id", "to_column": "id"})
service.publish("订单")
return {"order": order, "link": link}
# =========================== 积木的域与映射状态 ===========================
def test_域与映射状态(env):
from app.kernel import service
b = build_basics(env["ds_id"])
free = service.create_concept("object_type", "供应商", spec={"domain": "采购", "properties": [{"name": "名称"}]})
items = {c["name"]: c for c in service.list_concepts()}
assert items["网点"]["mapped"] is True and items["供应商"]["mapped"] is False
assert items["供应商"]["domain"] == "采购"
assert items["成交金额"]["mapped"] is True and items["达标判定"]["mapped"] is None
assert service.get_concept(free["id"])["spec"]["domain"] == "采购"
assert b["ot"]
# =========================== 本体空间 ===========================
def test_本体空间隔离_首页总览(env):
from app.kernel import service, workspaces
build_basics(env["ds_id"])
ws = workspaces.create("retail", "零售", "零售行业本体", "零售")
assert ws["counts"]["object_type"] == 0
all_ids = {w["id"] for w in workspaces.list_all()}
assert {"default", "retail"} <= all_ids
tok = identity.set_current(identity.Actor(workspace="retail"))
try:
assert service.list_concepts() == [] # 另一个空间看不到积木
from app.text2sql import semantic
assert semantic.list_datasources() == [] # 数据源按空间归属
semantic.create_datasource(name="共用库", ds_type="mysql", host="h", port=3306, db_name="x",
username="u", workspace="")
assert [d["name"] for d in semantic.list_datasources()] == ["共用库"] # 老数据(未归属)共用
home = workspaces.overview()
assert home["counts"]["object_type"] == 0
assert any(s["key"] == "modeling" for s in home["next_steps"])
finally:
identity.reset(tok)
home = workspaces.overview()
assert home["counts"]["object_type"] == 1 and home["revision"] >= 1
with pytest.raises(HTTPException):
workspaces.create("Bad Id", "x")
with pytest.raises(HTTPException):
workspaces.archive("default") # 不能归档正在用的
# =========================== 数据管道 / 关系边 / 影响分析 ===========================
def test_数据管道同步骨架并物化关系边(env):
from app.kernel import pipeline
b = build_basics(env["ds_id"])
o = add_orders(env["ds_id"], b["ot"]["id"])
p1 = pipeline.create(b["ot"]["id"])
p2 = pipeline.create(o["order"]["id"], "daily")
with pytest.raises(HTTPException):
pipeline.create(b["ot"]["id"]) # 一个对象类型一条管道
r1 = pipeline.run(p1["id"])
assert r1["status"] == "ok" and r1["last_rows"] == 3
r2 = pipeline.run(p2["id"])
assert r2["last_rows"] == 6 and r2["last_edges"] == 6 # 每个订单一条「下单网点」边
st = pipeline.status()
assert st["objects"] == 9 and st["edges"] == 6 and st["synced_at"]
ds = pipeline.dataset(o["order"]["id"])
assert ds["total"] == 6 and "网点" in ds["items"][0]["properties"]
assert pipeline.ensure_all()["created"] == [] # 都有管道了
# 定时:daily 的刚跑过不到期,manual 的永远不自动跑
assert pipeline.tick() == []
assert pipeline.run_all() == {"ok": 2, "total": 2}
# 执行器单条查询有行数上限:骨架同步要分页拉全,不能停在上限
from app.core import db as core_db
core_db.set_config({"SQL_ROW_LIMIT": "4"})
assert pipeline.sync_type(o["order"]["id"])["rows"] == 6
def test_遍历与实例级影响分析(env, monkeypatch):
from app.kernel import pipeline, traverse
b = build_basics(env["ds_id"])
o = add_orders(env["ds_id"], b["ot"]["id"])
make_action(b["ot"]["id"])
pipeline.sync_type(b["ot"]["id"])
pipeline.sync_type(o["order"]["id"])
t = traverse.traverse(o["order"]["id"], "1", depth=2)
names = {(n["type_name"], n["key"]) for n in t["nodes"]}
# 订单 1 → 网点 2(1 % 3 + 1)→ 同网点的订单 4
assert ("网点", "2") in names and ("订单", "4") in names
assert t["by_type"] == {"网点": 1, "订单": 1}
# 影响分析沿外键往上走到的网点只算「涉及」,不再绕道网点扩到同网点的其他订单
imp1 = traverse.instance_impact(o["order"]["id"], "1", depth=2)
assert imp1["by_type"] == {} and imp1["context"] == {"网点": 1}
imp = traverse.instance_impact(b["ot"]["id"], "2", depth=1)
assert imp["by_type"] == {"订单": 2} and "订单 2" in imp["summary"]
assert imp["live"] and imp["live"][0]["properties"] # 最外层回业务库取了最新属性
with pytest.raises(HTTPException):
traverse.traverse(b["ot"]["id"], "999") # 不在骨架里
# 数据范围:只能看网点 1 的人,遍历结果里看不到别的网点
tok = identity.set_current(identity.Actor(id="u", roles=["viewer"],
scope={b["ot"]["id"]: {"编号": ["1"]}}))
try:
t2 = traverse.traverse(o["order"]["id"], "1", depth=1)
assert all(n["type_name"] != "网点" for n in t2["nodes"]) and t2["hidden"] == 1
finally:
identity.reset(tok)
# =========================== 变更提案 ===========================
def test_变更提案_不能自审_AI不能批_草稿变动要重提(env):
from app.governance import review
from app.kernel import service
build_basics(env["ds_id"])
tok = as_user("builder")
try:
c = service.create_concept("function", "新规则", spec={"category": "rule", "expression": "a > 1"})
item = service.propose_release("加一条规则")
with pytest.raises(HTTPException) as e:
service.propose_release("再来一份")
assert e.value.status_code == 409 # 同时只能有一份待审
with pytest.raises(HTTPException) as e:
review.decide(item["id"], True)
assert "自己" in str(e.value.detail)
finally:
identity.reset(tok)
tok = identity.set_current(identity.as_ai(identity.Actor()))
try:
with pytest.raises(HTTPException) as e:
review.decide(item["id"], True)
assert "AI" in str(e.value.detail)
finally:
identity.reset(tok)
# 提交后又改了草稿:审批时拒绝
service.update_concept(c["id"], description="改了")
with pytest.raises(HTTPException) as e:
review.decide(item["id"], True)
assert e.value.status_code == 409
review.decide(item["id"], False, "请重提")
tok = as_user("builder")
try:
item = service.propose_release("重提")
finally:
identity.reset(tok)
rels = service.list_releases("pending")
assert rels[0]["can_decide"] # 管理员审批别人的提案
out = review.decide(item["id"], True)
rev = out["result"]["revision"]
assert service.rt_fn("新规则", "rule") is not None
# 回滚也走提案
tok = as_user("builder")
try:
rb = service.propose_rollback(rev - 1)
finally:
identity.reset(tok)
review.decide(rb["id"], True)
assert service.rt_fn("新规则", "rule") is None
def test_变更提案接口(env):
from fastapi.testclient import TestClient
from app.main import app
from app.kernel import service
build_basics(env["ds_id"])
service.create_concept("function", "阈值", spec={"category": "rule", "expression": "x > 2"})
c = TestClient(app)
item = c.post("/api/kernel/publish", json={"note": "加阈值"}, headers={"X-User-Id": "builder"}).json()
assert item["kind"] == "release" and item["status"] == "pending"
r = c.post(f"/api/kernel/releases/{item['id']}/decide", json={"approve": True},
headers={"X-User-Id": "builder"})
assert r.status_code == 403
inbox = c.get("/api/cap/inbox").json()
assert inbox["releases"] == 1
r = c.post(f"/api/kernel/releases/{item['id']}/decide", json={"approve": True})
assert r.status_code == 200 and r.json()["status"] == "accepted"
assert c.get("/api/kernel/revisions").json()[0]["note"] == "加阈值"
# =========================== MCP 与提问 ===========================
def test_MCP目录_别名_影响分析工具(env):
from app.capability import mcp
from app.kernel import pipeline
b = build_basics(env["ds_id"])
o = add_orders(env["ds_id"], b["ot"]["id"])
pipeline.sync_type(b["ot"]["id"])
pipeline.sync_type(o["order"]["id"])
names = {t["name"] for t in mcp.tools()}
planner = {t["name"] for t in mcp.tools(planner=True)}
assert "propose_action" in names and "propose_action" not in planner and "ask" not in planner
assert mcp.resolve("knowledge.search", {})[0].name == "search_knowledge"
assert mcp.resolve("skill:归因", {"x": 1}) [1] == {"name": "归因", "inputs": {"x": 1}}
assert mcp.resolve("rule_eval", {})[0].name == "rule.eval" # 其余只读函数仍可调,但不在目录
with pytest.raises(HTTPException):
mcp.resolve("object.write", {}) # 有副作用的工具永远调不到
ok, out = mcp.call_logged(identity.Actor(), "impact_analysis",
{"object_type": "网点", "key": "1"}, "agent")
assert ok and out["by_type"] == {"订单": 2}
ok, out = mcp.call_logged(identity.Actor(), "traverse_link",
{"object_type": "订单", "key": "1", "depth": "1"}, "console")
assert ok and len(out["nodes"]) == 2
ok, out = mcp.call_logged(identity.Actor(), "get_object", {"object_type": "网点"}, "agent")
assert not ok and "key" in out # 按工具声明校验必填参数
def test_审批单带优先级_依据_影响面(env):
from app.capability import actions, mcp
from app.kernel import pipeline
b = build_basics(env["ds_id"])
o = add_orders(env["ds_id"], b["ot"]["id"])
make_action(b["ot"]["id"])
pipeline.sync_type(b["ot"]["id"])
pipeline.sync_type(o["order"]["id"])
tok = as_user("operator")
try:
ok, run = mcp.call_logged(identity.current(), "propose_action", {
"action": "mark_follow", "params": {"reason": "连续下滑"}, "object_key": "1",
"reason": "成交下滑", "priority": "P0",
"evidence": ["近三月成交下降 40%", {"kind": "rule", "text": "达标判定未通过"}]}, "agent")
finally:
identity.reset(tok)
assert ok, run
assert run["priority"] == "P0" and len(run["evidence"]) == 2
assert run["impact"]["by_type"] == {"订单": 2}
with pytest.raises(HTTPException):
actions.propose("mark_follow", {"reason": "x"}, object_key="2", priority="P9")
pend = actions.pending_for(identity.current())
assert pend[0]["priority"] == "P0"
def test_运行时总览(env):
from fastapi.testclient import TestClient
from app.main import app
build_basics(env["ds_id"])
c = TestClient(app)
c.post("/api/cap/mcp/call/list_ontology_types", json={"args": {}})
c.post("/api/cap/mcp/call/nope", json={"args": {}})
ov = c.get("/api/cap/runtime/overview").json()
assert ov["mcp"]["calls_24h"] == 2 and ov["mcp"]["success_rate"] == 0.5
assert ov["mcp"]["by_via"] == {"console": 2}
assert "pipelines" in ov and "approvals" in ov
# =========================== 模型推理函数 ===========================
def test_模型推理函数调端点(env, monkeypatch):
from app.capability import builtins, defs
from app.kernel import schema, service
defs.upsert("endpoint", "良率模型", spec={"url": "http://ml.local/predict", "method": "POST"})
ep = defs.find("良率模型", "endpoint")
defs.set_status(ep["id"], "published")
seen = {}
class Resp:
status_code = 200
text = "{}"
def json(self):
return {"data": {"yield_rate": 0.93, "risk": "low"}}
def fake(method, url, json=None, headers=None, timeout=None):
seen.update(url=url, json=json)
return Resp()
monkeypatch.setattr("app.kernel.ml.requests.request", fake)
fn = service.create_concept("function", "良率预测", spec={
"category": "ml", "endpoint": "良率模型", "result_path": "data",
"inputs": [{"name": "temp"}, {"name": "pressure"}], "outputs": ["yield_rate"]})
assert fn["kind_label"] == "函数·模型推理"
out = builtins.eval_function(fn, {"inputs": {"temp": "80", "pressure": 1.2}})
assert out["result"] == {"yield_rate": 0.93} and seen["json"] == {"inputs": {"temp": 80.0, "pressure": 1.2}}
with pytest.raises(HTTPException):
builtins.eval_function(fn, {"inputs": {"temp": 80}}) # 缺输入
with pytest.raises(schema.SpecError):
schema.normalize_spec("function", {"category": "ml", "inputs": [{"name": "bad name"}]})
# =========================== 业务建模管道 ===========================
def test_业务建模管道_上传文档到四元组草案(env, monkeypatch):
from app.governance import review
from app.kernel import modeling
def fake_json(msgs, **k):
text = msgs[-1]["content"]
if "候选" in text and "章节" in text:
return {"template": "store_ops", "reason": "门店运营"}
if "文档片段" in text:
return {"concepts": [
{"kind": "object_type", "name": "工单", "description": "维修工单",
"spec": {"properties": [{"name": "编号", "is_key": True}]}, "confidence": 0.9},
{"kind": "function", "name": "超时判定", "description": "超过 48 小时未关闭算超时",
"spec": {"category": "rule", "text": "处理时长超过 48 小时"}, "confidence": 0.8},
{"kind": "action", "name": "升级工单", "spec": {"text": "超时后由主管升级"}, "confidence": 0.7}],
"roles": [{"name": "维修主管"}]}
if "可执行的定义" in text:
return {"expression": "hours > 48", "params": ["hours"]}
if "业务流程" in text:
return {"processes": [{"title": "工单超时升级", "chunks": []}]}
if "可执行的 SOP" in msgs[0]["content"] or "SOP" in text:
return {"title": "工单超时升级", "description": "超时工单的处理",
"steps": [{"id": "s1", "type": "human_task", "title": "主管复核", "role": "维修主管",
"next": "end"}, {"id": "end", "type": "end", "title": "结束"}]}
return {}
monkeypatch.setattr(llm, "chat_json", fake_json)
doc = "# 工单管理\n\n## 超时规则\n工单处理时长超过 48 小时未关闭即为超时,由维修主管升级。\n".encode("utf-8")
run = modeling.create("工单建模", files=[("工单.md", doc)], ds_ids=[])
assert run["inputs"]["files"] == ["工单.md"] and run["inputs"]["chunks"] >= 1
events = list(modeling.execute(run["id"]))
assert events[-1]["stage"] == "done", events[-1]
g = modeling.get(run["id"])
assert g["status"] == "done"
stages = {s["key"]: s for s in g["stages"]}
assert stages["route"]["counts"]["template"] == "store_ops"
assert stages["deepen"]["counts"]["deepened"] == 1
assert [x["payload"]["name"] for x in g["items"]["object_type"]] == ["工单"]
rule = g["items"]["function"][0]["payload"]
assert rule["spec"]["expression"] == "hours > 48" and rule["deepened"]
assert len(g["sops"]) == 1 and g["counts"]["sop"] == 1
md = modeling.export_md(run["id"])
assert "## 对象(1)" in md and "hours > 48" in md and "工单超时升级" in md
# 采纳后成为草稿积木,来源记为 modeling
out = review.decide(g["items"]["object_type"][0]["id"], True)
from app.kernel import service
assert service.get_concept(out["result"]["concept_id"])["origin"] == "modeling"
with pytest.raises(HTTPException):
modeling.create("空", doc_ids=[])
def test_业务建模_数据对齐_指标绑定_动作补全_写回业务库(env, monkeypatch):
"""文档 + 已接入的表:对象 / 关系直接绑表并用文档叫法;指标写出取数表达式实跑通过;
动作骨架补全成「新建订单」,审批后真的写进业务表,撤销会删掉。"""
from app.capability import actions
from app.governance import review
from app.kernel import modeling, service
from app.text2sql import semantic
from sqlalchemy import text as sa_text
rels = semantic.list_relations(env["ds_id"])
assert any(r["from_column"] == "store_id" for r in rels) # 没有外键也推出了「订单 → 门店」
def fake_json(msgs, **k):
text = msgs[-1]["content"]
if "文档片段" in text:
assert "已接入的数据表" in text # 表作为命名约束喂给了模型
return {"concepts": [
{"kind": "object_type", "name": "门店", "synonyms": ["store"], "confidence": 0.9},
{"kind": "object_type", "name": "订单", "synonyms": ["order_item"], "confidence": 0.9},
{"kind": "link_type", "name": "成交门店", "confidence": 0.8,
"spec": {"from_type": "订单", "to_type": "门店", "cardinality": "n:1"}},
{"kind": "function", "name": "成交额", "confidence": 0.8,
"spec": {"category": "aggregate", "object_type": "订单", "unit": "元",
"formula_text": "订单金额求和"}},
{"kind": "action", "name": "补录订单", "spec": {"text": "门店可以补录一笔订单"}}]}
if "SQL 聚合表达式" in text:
return {"expression": "SUM(amount)", "dimensions": {"store_id": "store_id"},
"time_column": "created_at", "object_key_column": "id", "filters": []}
if text.startswith("动作:"):
return {"name": "补录订单", "spec": {
"target_type": "门店",
"params": [{"name": "order_id", "label": "订单号", "type": "number", "required": True},
{"name": "amount", "label": "金额", "type": "number", "required": True}],
"effects": [{"tool": "object.create", "args": {"object_type": "订单", "values": {
"id": "$order_id", "store_id": "$obj_key", "amount": "=amount * 1", "created_at": "$today"}}}],
"approval": {"mode": "manual", "approver_roles": []}}}
return {}
monkeypatch.setattr(llm, "chat_json", fake_json)
doc = "# 门店订单\n门店每天有订单成交,成交额是订单金额之和。门店可以补录订单。".encode("utf-8")
run = modeling.create("门店建模", files=[("门店.md", doc)], stages=["data", "convert", "deepen", "draft"])
assert run["options"]["ds_ids"] == [env["ds_id"]] # 默认对齐所有已内省的数据源
events = list(modeling.execute(run["id"]))
assert events[-1]["stage"] == "done", events[-1]
g = modeling.get(run["id"])
objs = {x["payload"]["name"]: x["payload"] for x in g["items"]["object_type"]}
assert set(objs) == {"门店", "订单"} # 文档叫法,没有重复的表对象
assert objs["门店"]["bindings"][0]["ref"]["table"] == "store" and "门店主数据" in objs["门店"]["synonyms"]
links = [x["payload"] for x in g["items"]["link_type"]]
assert [x["name"] for x in links] == ["成交门店"] # 表推出的关系并进了文档的关系
assert links[0]["bindings"][0]["ref"] == {"from_column": "store_id", "to_column": "id"}
metric = g["items"]["function"][0]["payload"]
assert metric["bindings"][0]["target_kind"] == "metric_expr"
assert metric["bindings"][0]["ref"]["expression"] == "SUM(amount)"
act = g["items"]["action"][0]["payload"]
assert act["completed"] and act["spec"]["effects"][0]["tool"] == "object.create"
order = {"object_type": 0, "link_type": 1, "function": 2, "action": 3}
for it in sorted([x for col in g["items"].values() for x in col], key=lambda x: order.get(x["payload"].get("kind"), 9)):
review.decide(it["id"], True)
service.publish("门店建模")
# 已经有文档命名的同一条关系:再从数据源「提议到本体」不会冒出重复的「订单成交明细-门店主数据」
from app.kernel import propose
assert propose.from_datasource(env["ds_id"])["proposed"] == 0
from app.kernel import metrics, workbench
assert metrics.query("成交额")["rows"][0][0] == 2100.0
wb = workbench.workbench() # 工作台:已发布指标的当前值 + 能直接问的问题
assert [k["name"] for k in wb["kpis"]] == ["成交额"] and wb["kpis"][0]["value"] == 2100.0
assert any("成交额" in q for q in wb["questions"])
# 数据源没开写回:审批通过也执行失败,并说清楚原因
run1 = actions.propose("补录订单", {"order_id": 99, "amount": 88}, object_key="1", reason="补录")
tok = as_user("approver")
try:
failed = actions.decide(run1["id"], True)
finally:
identity.reset(tok)
assert failed["status"] == "failed" and "写回业务库" in failed["error"], failed
semantic.update_datasource(env["ds_id"], extra={"writeback": True})
run2 = actions.propose("补录订单", {"order_id": 100, "amount": 66}, object_key="2", reason="补录")
tok = as_user("approver")
try:
done = actions.decide(run2["id"], True)
finally:
identity.reset(tok)
assert done["status"] == "done", done
with env["conn"].engine.connect() as c:
assert c.execute(sa_text("SELECT store_id, amount FROM order_item WHERE id = 100")).one() == (2, 66.0)
actions.propose_revert(run2["id"], "录错了")
tok = as_user("approver")
try:
rv = [r for r in actions.list_runs(status="pending_approval") if r.get("revert_of") == run2["id"]]
actions.decide(rv[0]["id"], True)
finally:
identity.reset(tok)
with env["conn"].engine.connect() as c:
assert c.execute(sa_text("SELECT COUNT(*) FROM order_item WHERE id = 100")).scalar() == 0
# =========================== 本地文件数据源 ===========================
def test_本地文件数据源_导入与只读查询(tmp_path):
from app.text2sql.connectors import sqlite_file
from app.text2sql.connectors.base import QueryFailed
csv_bytes = "编号,名称,金额\n1,杭州店,100.5\n2,南京店,80\n".encode("utf-8")
res = sqlite_file.import_files(tmp_path / "ds.sqlite", [("门店.csv", csv_bytes),
("x.json", b'[{"a": 1, "b": "x"}]')])
assert [r["rows"] for r in res] == [2, 1]
conn = sqlite_file.SQLiteFileConnector({"id": 9, "db_name": str(tmp_path / "ds.sqlite")}, "")
intro = conn.introspect()
t = next(x for x in intro.tables if x.name == "门店")
assert [c.data_type for c in t.columns] == ["INTEGER", "TEXT", "REAL"] and t.row_count_est == 2
out = conn.run_sql('SELECT SUM("金额") FROM "门店"', 10, 5000)
assert out.rows == [[180.5]]
with pytest.raises(QueryFailed):
conn.run_sql('DELETE FROM "门店"', 10, 5000) # 只读打开
# 同名文件再导一次:覆盖同一张表,不新增
res2 = sqlite_file.import_files(tmp_path / "ds.sqlite", [("门店.csv", "编号,名称,金额\n3,苏州店,1\n".encode())])
assert res2[0]["table"] == "门店" and res2[0]["rows"] == 1
conn.dispose()
def test_本体SQL按目标方言转写():
from app.kernel.sqlutil import to_dialect
assert to_dialect("SELECT `a` FROM `t` LIMIT 5", "mysql") == "SELECT `a` FROM `t` LIMIT 5"
assert to_dialect("SELECT `a` FROM `t` LIMIT 5", "postgres") == 'SELECT "a" FROM "t" LIMIT 5'
# =========================== 流程卡 ===========================
def test_流程卡带优先级与域():
from app.sop import spec as sop_spec
n = sop_spec.normalize({"priority": "p1", "domain": "质量", "steps": [{"id": "e", "type": "end"}]})
assert n["priority"] == "P1" and n["domain"] == "质量"
assert sop_spec.normalize({"priority": "urgent"})["priority"] == "P2"
...@@ -235,7 +235,10 @@ def test_MCP在线调用写审计_提议只进审批(env): ...@@ -235,7 +235,10 @@ def test_MCP在线调用写审计_提议只进审批(env):
c = TestClient(app) c = TestClient(app)
tools = c.get("/api/cap/mcp/tools").json() tools = c.get("/api/cap/mcp/tools").json()
names = {t["name"] for t in tools["tools"]} names = {t["name"] for t in tools["tools"]}
assert {"data_ask", "function_eval", "impact_analysis", "propose_action", "get_action_status"} <= names assert {"data_ask", "execute_function", "impact_analysis", "traverse_link", "execute_runcard",
"propose_action", "get_action_status"} <= names
assert not {n for n in names if "approve" in n or "reject" in n} # 目录里没有审批工具
# 老名字 function_eval 仍可调用(别名),审计记成新名字
r = c.post("/api/cap/mcp/call/function_eval", json={"args": {"name": "达标判定", r = c.post("/api/cap/mcp/call/function_eval", json={"args": {"name": "达标判定",
"args": {"vars": {"actual": 2, "target": 1}}}}) "args": {"vars": {"actual": 2, "target": 1}}}})
assert r.json()["ok"] and r.json()["result"]["result"] is True assert r.json()["ok"] and r.json()["result"]["result"] is True
......
...@@ -40,7 +40,8 @@ def env(tmp_path, monkeypatch): ...@@ -40,7 +40,8 @@ def env(tmp_path, monkeypatch):
core_db.Base.metadata.create_all(meta) core_db.Base.metadata.create_all(meta)
with Session(meta) as s: with Session(meta) as s:
for k, v in DEFAULT_RUNTIME.items(): for k, v in DEFAULT_RUNTIME.items():
s.add(core_db.Config(cfg_key=k, cfg_value=v)) # 发布后自动同步走后台线程,测试里关掉,需要时显式调用 pipeline
s.add(core_db.Config(cfg_key=k, cfg_value="0" if k == "PIPELINE_AUTO_SYNC" else v))
s.commit() s.commit()
monkeypatch.setattr(core_db, "engine", meta) monkeypatch.setattr(core_db, "engine", meta)
for mod in (semantic, library, executor, introspect): for mod in (semantic, library, executor, introspect):
...@@ -172,7 +173,8 @@ def test_同名冲突与spec校验(env): ...@@ -172,7 +173,8 @@ def test_同名冲突与spec校验(env):
def test_链接_最长匹配_实例_时间(env): def test_链接_最长匹配_实例_时间(env):
from app.kernel import linker, objects from app.kernel import linker, objects
b = build_basics(env["ds_id"]) b = build_basics(env["ds_id"])
assert objects.sync_instances(b["ot"]["id"]) == 3 from app.kernel import pipeline
assert pipeline.sync_type(b["ot"]["id"])["rows"] == 3
linker.invalidate() linker.invalidate()
r = linker.link("上个月杭州体验中心的销售额是多少") r = linker.link("上个月杭州体验中心的销售额是多少")
assert [c["name"] for c in r["concepts"]] == ["成交金额"] assert [c["name"] for c in r["concepts"]] == ["成交金额"]
...@@ -428,7 +430,11 @@ def test_统一提问_取数加引用加动作建议(env, monkeypatch): ...@@ -428,7 +430,11 @@ def test_统一提问_取数加引用加动作建议(env, monkeypatch):
yield f"网点 1 成交最高 [^run:{run_id}]。" yield f"网点 1 成交最高 [^run:{run_id}]。"
monkeypatch.setattr(llm, "chat_stream", fake_stream) monkeypatch.setattr(llm, "chat_stream", fake_stream)
out = runner.run_collect("各网点成交金额,偏低的怎么办") out = runner.run_collect("各网点成交金额,偏低的怎么办")
assert [s["call"] for s in out["plan"]["steps"]] == ["metric.query"] # 规划器写的老名字 metric.query 被归一成 MCP 工具名;每一步都经 MCP 执行并写审计(via=ask)
assert [s["call"] for s in out["plan"]["steps"]] == ["query_metric"]
from app.governance import audit
logs = audit.query(event="mcp.call", full=True)["items"]
assert logs and logs[0]["target_id"] == "query_metric" and logs[0]["after"]["via"] == "ask"
assert out["data_refs"] and out["data_refs"][0]["cited"] assert out["data_refs"] and out["data_refs"][0]["cited"]
card = out["actions"][0] card = out["actions"][0]
assert card["preview"]["effects"][0]["tool"] == "object.write" assert card["preview"]["effects"][0]["tool"] == "object.write"
...@@ -577,10 +583,10 @@ def test_知识类问题一定补原文检索(): ...@@ -577,10 +583,10 @@ def test_知识类问题一定补原文检索():
from app.orchestrator.runner import _ensure_evidence from app.orchestrator.runner import _ensure_evidence
p = {"intent": "process", "steps": [{"id": "s1", "call": "sop.find", "args": {}}]} p = {"intent": "process", "steps": [{"id": "s1", "call": "sop.find", "args": {}}]}
_ensure_evidence(p, "流程是什么", {"concepts": [{"name": "盘点"}]}) _ensure_evidence(p, "流程是什么", {"concepts": [{"name": "盘点"}]})
assert [s["call"] for s in p["steps"]] == ["sop.find", "knowledge.search"] assert [s["call"] for s in p["steps"]] == ["sop.find", "search_knowledge"]
q = {"intent": "data", "steps": []} q = {"intent": "data", "steps": []}
_ensure_evidence(q, "x", {}) _ensure_evidence(q, "x", {})
assert [s["call"] for s in q["steps"]] == ["knowledge.search"] # 空计划也兜底 assert [s["call"] for s in q["steps"]] == ["search_knowledge"] # 空计划也兜底
r = {"intent": "chitchat", "steps": []} r = {"intent": "chitchat", "steps": []}
_ensure_evidence(r, "你好", {}) _ensure_evidence(r, "你好", {})
assert r["steps"] == [] assert r["steps"] == []
This diff could not be displayed because it is too large.
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Ontology 本体系统</title> <title>本体认知引擎</title>
<meta name="description" content="上传业务文档,抽取实体与关系,图谱可视化,并让大模型逐步深挖检索、全程可溯源。" /> <meta name="description" content="上传业务文档,抽取实体与关系,图谱可视化,并让大模型逐步深挖检索、全程可溯源。" />
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><circle cx='16' cy='16' r='13' fill='none' stroke='%234f46e5' stroke-width='3'/><circle cx='16' cy='16' r='5' fill='%234f46e5'/></svg>" /> <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><circle cx='16' cy='16' r='13' fill='none' stroke='%234f46e5' stroke-width='3'/><circle cx='16' cy='16' r='5' fill='%234f46e5'/></svg>" />
</head> </head>
......
import { import {
Blocks, Bot, Boxes, ChevronDown, ChevronLeft, ClipboardCheck, Database, FileText, FlaskConical, FunctionSquare, GitBranch, Activity, Blocks, Bot, Boxes, ChevronDown, ChevronLeft, ClipboardCheck, Database, FileText, FlaskConical, FunctionSquare,
GitCommit, Globe, LayoutGrid, ListChecks, Menu, MessageSquareText, Monitor, Moon, Network, Rocket, ScrollText, Settings, GitBranch, GitCommit, Home, LayoutDashboard, LayoutGrid, ListChecks, Menu, MessageSquareText, Monitor, Moon, Network, Rocket, ScrollText,
ShieldCheck, Sun, Users, Wand2, Zap, Settings, ShieldCheck, Sun, Users, Wand2, Workflow, Zap,
} from "lucide-react"; } from "lucide-react";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Badge, Segmented, Toaster } from "@/components/ui"; import { Badge, Segmented, Toaster } from "@/components/ui";
import { AskPage } from "@/features/ask/AskPage"; import { AskPage } from "@/features/ask/AskPage";
import { AuditPage } from "@/features/audit/AuditPage"; import { AuditPage } from "@/features/audit/AuditPage";
import { CapabilityPage } from "@/features/capability/CapabilityPage"; import { PipelinePage } from "@/features/data/PipelinePage";
import { DocumentsPage } from "@/features/documents/DocumentsPage"; import { DocumentsPage } from "@/features/documents/DocumentsPage";
import { EvalPage } from "@/features/eval/EvalPage"; import { EvalPage } from "@/features/eval/EvalPage";
import { GraphPage } from "@/features/graph/GraphPage"; import { GraphPage } from "@/features/graph/GraphPage";
import { HomePage } from "@/features/home/HomePage";
import { InboxPage } from "@/features/inbox/InboxPage"; import { InboxPage } from "@/features/inbox/InboxPage";
import { MembersPage } from "@/features/members/MembersPage"; import { MembersPage } from "@/features/members/MembersPage";
import { ObjectsPage } from "@/features/objects/ObjectsPage"; import { ObjectsPage } from "@/features/objects/ObjectsPage";
import { BlockListPage } from "@/features/ontology/BlockListPage"; import { BlockListPage } from "@/features/ontology/BlockListPage";
import { CanvasPage } from "@/features/ontology/CanvasPage"; import { CanvasPage } from "@/features/ontology/CanvasPage";
import { McpPage } from "@/features/ontology/McpPage"; import { McpPage } from "@/features/ontology/McpPage";
import { ModelingPage } from "@/features/ontology/ModelingPage";
import { PublishPage, VersionsPage } from "@/features/ontology/ReleasePages"; import { PublishPage, VersionsPage } from "@/features/ontology/ReleasePages";
import { pageOfKind } from "@/features/ontology/routes"; import { pageOfKind } from "@/features/ontology/routes";
import { WizardPage } from "@/features/ontology/WizardPage"; import { OverviewPage } from "@/features/runtime/OverviewPage";
import { SettingsPage } from "@/features/settings/SettingsPage"; import { SettingsPage } from "@/features/settings/SettingsPage";
import { SopPage } from "@/features/sop/SopPage"; import { SopPage } from "@/features/sop/SopPage";
import { SqlPage } from "@/features/sql/SqlPage"; import { SqlPage } from "@/features/sql/SqlPage";
import { WorkbenchPage } from "@/features/workbench/WorkbenchPage";
import { DialogHost } from "@/lib/dialog"; import { DialogHost } from "@/lib/dialog";
import { currentUserId, onUserChange, setCurrentUserId } from "@/lib/identity"; import {
currentUserId, currentWorkspace, onUserChange, onWorkspaceChange, setCurrentUserId, setCurrentWorkspace,
} from "@/lib/identity";
import { go, parseHash } from "@/lib/nav"; import { go, parseHash } from "@/lib/nav";
import { onto, type InboxCounts, type Me, type UserRec } from "@/lib/onto"; import { onto, type InboxCounts, type Me, type UserRec, type WorkspaceRec } from "@/lib/onto";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { applyTheme, useAppStore, type Theme } from "@/store/useAppStore"; import { applyTheme, useAppStore, type Theme } from "@/store/useAppStore";
type PageKey = "data" | "documents" | "graph" | "endpoints" type PageKey = "desk" | "home"
| "wizard" | "publish" | "versions" | "data" | "pipeline" | "documents" | "graph"
| "modeling" | "publish" | "versions"
| "canvas" | "b_object" | "b_link" | "b_function" | "b_action" | "sop" | "canvas" | "b_object" | "b_link" | "b_function" | "b_action" | "sop"
| "ask" | "objects" | "inbox" | "mcp" | "audit" | "runtime" | "mcp" | "inbox" | "audit"
| "ask" | "objects"
| "members" | "eval" | "settings"; | "members" | "eval" | "settings";
interface NavItem { key: PageKey; label: string; icon: React.ReactNode; hint: string } /** biz:业务人员(没有搭建权限的老板、员工、审批人)也能看到的入口;其余只给实施和管理员。 */
interface NavItem { key: PageKey; label: string; icon: React.ReactNode; hint: string; biz?: boolean; perm?: string[] }
const I = "h-4 w-4"; const I = "h-4 w-4";
/** 导航按本体的生命周期排:数据集成 → 本体建模 → 本体浏览 → 运行时 → 设置。 */ /**
* 导航按本体的生命周期排:数据集成 → 本体建模 → 本体浏览 → 运行时 → 应用 → 设置。
* 运行时只有一个出口:MCP。「提问」「对象 360」是跑在它上面的应用。
*/
const NAV: { group: string; items: NavItem[] }[] = [ const NAV: { group: string; items: NavItem[] }[] = [
{ group: "", items: [
{ key: "desk", label: "工作台", icon: <LayoutDashboard className={I} />, hint: "今天的关键数字、等我处理的事、常用流程与问题", biz: true },
{ key: "home", label: "本体首页", icon: <Home className={I} />, hint: "全部本体、当前本体的资产与建议下一步" },
] },
{ group: "数据集成", items: [ { group: "数据集成", items: [
{ key: "data", label: "数据源", icon: <Database className={I} />, hint: "接入数据库、内省表结构、启用表、SQL 调试" }, { key: "data", label: "数据连接", icon: <Database className={I} />, hint: "数据库 / 本地文件 / 外部系统 API;表 → 实体映射" },
{ key: "documents", label: "文档与证据", icon: <FileText className={I} />, hint: "上传业务文档、抽取知识图谱,作为本体的原文出处" }, { key: "pipeline", label: "数据管道", icon: <Workflow className={I} />, hint: "同步对象骨架、物化关系边;本体数据集" },
{ key: "endpoints", label: "外部系统连接", icon: <Globe className={I} />, hint: "动作可调用的外部端点(地址 + 加密凭据)" }, { key: "documents", label: "知识库", icon: <FileText className={I} />, hint: "业务文档、知识图谱,作为本体的原文出处" },
] }, ] },
{ group: "本体建模", items: [ { group: "本体建模", items: [
{ key: "wizard", label: "业务建模", icon: <Wand2 className={I} />, hint: "三步:选数据与文档 → 审核四元组草案 → 发布" }, { key: "modeling", label: "业务建模", icon: <Wand2 className={I} />, hint: "文档 → 行业路由 → LLM 转换 → 规则深化 → SOP 编排 → 四元组草案" },
{ key: "publish", label: "变更与发布", icon: <Rocket className={I} />, hint: "所有积木共用一套草稿与发布;AI 提议、模板、导入导出" }, { key: "publish", label: "变更提案", icon: <Rocket className={I} />, hint: "草稿 → 提案 → 他人审批 → 发布;禁自审,Agent 不可批" },
{ key: "versions", label: "版本管理", icon: <GitCommit className={I} />, hint: "每次发布一份快照:任意两版对比、回滚" }, { key: "versions", label: "版本管理", icon: <GitCommit className={I} />, hint: "每次发布一份快照:任意两版对比、回滚(回滚也走提案)" },
] }, ] },
{ group: "本体浏览", items: [ { group: "本体浏览", items: [
{ key: "canvas", label: "本体画布", icon: <LayoutGrid className={I} />, hint: "对象、关系、函数、动作同图管理" }, { key: "canvas", label: "本体画布", icon: <LayoutGrid className={I} />, hint: "卡片视图 / 图谱视图:对象、关系、函数、动作同图管理" },
{ key: "b_object", label: "对象类型", icon: <Boxes className={I} />, hint: "业务里可被指认、有属性的实体" }, { key: "b_object", label: "对象类型", icon: <Boxes className={I} />, hint: "业务里可被指认、有属性的实体;按域分组、映射状态" },
{ key: "b_link", label: "关系类型", icon: <GitBranch className={I} />, hint: "对象之间的关系" }, { key: "b_link", label: "关系类型", icon: <GitBranch className={I} />, hint: "对象之间的关系" },
{ key: "b_function", label: "函数类型", icon: <FunctionSquare className={I} />, hint: "聚合 / 规则 / 决策表 / 周期 / AI 分析,各走确定性引擎" }, { key: "b_function", label: "函数类型", icon: <FunctionSquare className={I} />, hint: "聚合 / 规则 / 决策表 / 周期 / 模型推理 / AI 分析,各走确定性引擎" },
{ key: "b_action", label: "动作类型", icon: <Zap className={I} />, hint: "改变业务状态的操作,执行前一律人工审批" }, { key: "b_action", label: "动作类型", icon: <Zap className={I} />, hint: "改变业务状态的操作,执行前一律人工审批" },
{ key: "sop", label: "流程卡", icon: <ListChecks className={I} />, hint: "可执行的标准流程:编排函数、AI 分析、人工任务与动作" }, { key: "sop", label: "流程卡", icon: <ListChecks className={I} />, hint: "可执行的标准流程:编排函数、AI 分析、人工任务与动作", biz: true, perm: ["operate"] },
] }, ] },
{ group: "运行时", items: [ { group: "运行时", items: [
{ key: "ask", label: "提问", icon: <MessageSquareText className={I} />, hint: "问知识、问数据、问怎么办,一个入口" }, { key: "runtime", label: "总览", icon: <Activity className={I} />, hint: "MCP 调用、待审批、流程卡运行、数据管道状态" },
{ key: "objects", label: "对象 360", icon: <Blocks className={I} />, hint: "任一业务对象的属性、指标、关联、动作与审计" }, { key: "mcp", label: "MCP 服务", icon: <Bot className={I} />, hint: "Agent 可调用的工具目录、在线调用、调用日志" },
{ key: "inbox", label: "行动审批", icon: <ShieldCheck className={I} />, hint: "待我审批、我的待办、AI 提议审核、通知" }, { key: "inbox", label: "行动审批", icon: <ShieldCheck className={I} />, hint: "审批中心:动作提案(优先级 / 依据 / 影响面)、变更提案、待办", biz: true, perm: ["operate", "approve"] },
{ key: "mcp", label: "MCP 服务", icon: <Bot className={I} />, hint: "外部 Agent 可调用的工具目录、在线调用、调用日志" }, { key: "audit", label: "调用日志", icon: <ScrollText className={I} />, hint: "谁、何时、通过哪里、做了什么;模型用量" },
{ key: "audit", label: "调用与审计", icon: <ScrollText className={I} />, hint: "谁、何时、做了什么;模型用量" }, ] },
{ group: "应用", items: [
{ key: "ask", label: "提问", icon: <MessageSquareText className={I} />, hint: "问知识、问数据、问怎么办 —— 经 MCP 调用本体", biz: true },
{ key: "objects", label: "对象 360", icon: <Blocks className={I} />, hint: "任一业务对象的属性、指标、关联、影响分析、动作与审计", biz: true },
] }, ] },
{ group: "设置", items: [ { group: "设置", items: [
{ key: "members", label: "成员与角色", icon: <Users className={I} />, hint: "系统角色、业务角色(审批与派单用)、数据范围" }, { key: "members", label: "成员与角色", icon: <Users className={I} />, hint: "系统角色、业务角色(审批与派单用)、数据范围" },
{ key: "eval", label: "评测中心", icon: <FlaskConical className={I} />, hint: "问答与本体评测,发布前回归" }, { key: "eval", label: "评测中心", icon: <FlaskConical className={I} />, hint: "问答与本体评测,发布前回归" },
{ key: "settings", label: "系统设置", icon: <Settings className={I} />, hint: "模型、抽取、检索与治理参数" }, { key: "settings", label: "系统设置", icon: <Settings className={I} />, hint: "模型、抽取、检索、治理与数据管道参数" },
] }, ] },
]; ];
const ALL = NAV.flatMap((g) => g.items); const ALL = NAV.flatMap((g) => g.items);
/** 旧链接(#/kernel?id=…、#/capability、#/home)兼容到新页面。 */ /** 旧链接兼容到新页面。 */
const ALIAS: Record<string, PageKey> = { home: "wizard", kernel: "b_object", capability: "endpoints" }; const ALIAS: Record<string, PageKey> = {
wizard: "modeling", kernel: "b_object", capability: "data", endpoints: "data",
};
const THEME_ICON: Record<Theme, React.ReactNode> = { const THEME_ICON: Record<Theme, React.ReactNode> = {
light: <Sun className={I} />, dark: <Moon className={I} />, system: <Monitor className={I} />, light: <Sun className={I} />, dark: <Moon className={I} />, system: <Monitor className={I} />,
...@@ -82,7 +102,7 @@ const THEME_ICON: Record<Theme, React.ReactNode> = { ...@@ -82,7 +102,7 @@ const THEME_ICON: Record<Theme, React.ReactNode> = {
function pageFromHash(): PageKey { function pageFromHash(): PageKey {
const p = parseHash().page; const p = parseHash().page;
if (p === "graph") return "graph"; if (p === "graph") return "graph";
return (ALL.find((n) => n.key === p)?.key ?? ALIAS[p] ?? "wizard") as PageKey; return (ALL.find((n) => n.key === p)?.key ?? ALIAS[p] ?? "desk") as PageKey;
} }
export default function App() { export default function App() {
...@@ -96,6 +116,8 @@ export default function App() { ...@@ -96,6 +116,8 @@ export default function App() {
try { return JSON.parse(localStorage.getItem("onto.nav.folded") || "{}"); } catch { return {}; } try { return JSON.parse(localStorage.getItem("onto.nav.folded") || "{}"); } catch { return {}; }
}); });
const [uid, setUid] = useState(currentUserId()); const [uid, setUid] = useState(currentUserId());
const [ws, setWs] = useState(currentWorkspace());
const [spaces, setSpaces] = useState<WorkspaceRec[]>([]);
const { theme, setTheme, sidebarCollapsed, toggleSidebar, graphFocus } = useAppStore(); const { theme, setTheme, sidebarCollapsed, toggleSidebar, graphFocus } = useAppStore();
const refresh = useCallback(() => { const refresh = useCallback(() => {
...@@ -104,7 +126,9 @@ export default function App() { ...@@ -104,7 +126,9 @@ export default function App() {
}, []); }, []);
useEffect(() => { applyTheme(theme); }, [theme]); useEffect(() => { applyTheme(theme); }, [theme]);
useEffect(() => { refresh(); }, [refresh, page, uid]); useEffect(() => { refresh(); }, [refresh, page, uid, ws]);
useEffect(() => { void onto.workspaces().then(setSpaces).catch(() => undefined); }, [uid, ws, page]);
useEffect(() => onWorkspaceChange(setWs), []);
useEffect(() => { void onto.users().then((r) => setUsers(r.users)).catch(() => undefined); }, [uid]); useEffect(() => { void onto.users().then((r) => setUsers(r.users)).catch(() => undefined); }, [uid]);
useEffect(() => onUserChange(setUid), []); useEffect(() => onUserChange(setUid), []);
useEffect(() => { useEffect(() => {
...@@ -117,6 +141,7 @@ export default function App() { ...@@ -117,6 +141,7 @@ export default function App() {
useEffect(() => { useEffect(() => {
const on = () => { const on = () => {
const { page: raw, params } = parseHash(); const { page: raw, params } = parseHash();
if (raw === "capability" || raw === "endpoints") { go("data", { tab: "api" }); return; }
if (raw === "kernel" && params.get("id")) { if (raw === "kernel" && params.get("id")) {
const id = params.get("id")!; const id = params.get("id")!;
void onto.concept(id).then((c) => go(pageOfKind(c.kind), { id })).catch(() => go("b_object")); void onto.concept(id).then((c) => go(pageOfKind(c.kind), { id })).catch(() => go("b_object"));
...@@ -130,15 +155,23 @@ export default function App() { ...@@ -130,15 +155,23 @@ export default function App() {
}, []); // eslint-disable-line react-hooks/exhaustive-deps }, []); // eslint-disable-line react-hooks/exhaustive-deps
const nav = (k: PageKey) => { go(k); setMobileNavOpen(false); }; const nav = (k: PageKey) => { go(k); setMobileNavOpen(false); };
// 业务人员只看业务入口:搭建期的概念(管道、积木、提案、MCP)对他们没有意义,只会让人不知道从哪下手
const builder = !me || me.permissions.includes("build") || me.roles?.includes("admin");
const allowed = (n: NavItem) => builder || (n.biz && (!n.perm || n.perm.some((p) => me?.permissions.includes(p))))
const navGroups = NAV.map((g) => ({ ...g, items: g.items.filter(allowed) }))
.filter((g) => g.items.length)
.map((g) => (!builder && g.group ? { ...g, group: g.items.length === 1 ? "" : g.group } : g));
const navKey: PageKey = page === "graph" ? "documents" : page; const navKey: PageKey = page === "graph" ? "documents" : page;
const current = ALL.find((n) => n.key === navKey)!; const current = ALL.find((n) => n.key === navKey)!;
const inboxTotal = (counts?.approvals || 0) + (counts?.tasks || 0) + (counts?.reviews || 0); const inboxTotal = (counts?.approvals || 0) + (counts?.tasks || 0) + (counts?.reviews || 0) + (counts?.releases || 0);
const curSpace = spaces.find((x) => x.current) || spaces.find((x) => x.id === ws);
const fold = (g: string) => { const fold = (g: string) => {
const n = { ...folded, [g]: !folded[g] }; const n = { ...folded, [g]: !folded[g] };
setFolded(n); setFolded(n);
try { localStorage.setItem("onto.nav.folded", JSON.stringify(n)); } catch { /* 隐私模式 */ } try { localStorage.setItem("onto.nav.folded", JSON.stringify(n)); } catch { /* 隐私模式 */ }
}; };
const fullBleed = ["ask", "canvas", "b_object", "b_link", "b_function", "b_action", "versions", "mcp"].includes(page); const fullBleed = ["ask", "canvas", "b_object", "b_link", "b_function", "b_action", "versions", "mcp"].includes(page);
const switchSpace = (id: string) => { setCurrentWorkspace(id); go("home"); };
return ( return (
<div className="flex h-full"> <div className="flex h-full">
...@@ -153,19 +186,32 @@ export default function App() { ...@@ -153,19 +186,32 @@ export default function App() {
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand text-white"><Network className={I} /></span> <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand text-white"><Network className={I} /></span>
{!sidebarCollapsed && ( {!sidebarCollapsed && (
<div className="min-w-0"> <div className="min-w-0">
<p className="truncate text-[13px] font-semibold leading-tight">Ontology 本体系统</p> <p className="truncate text-[13px] font-semibold leading-tight">本体认知引擎</p>
<p className="truncate text-[10.5px] text-muted">对象 · 关系 · 函数 · 动作</p> <p className="truncate text-[10.5px] text-muted">Ontology Engine</p>
</div> </div>
)} )}
</div> </div>
{!sidebarCollapsed && (
<div className="border-b border-line p-2">
<label className="block rounded-lg border border-line bg-elevated px-2 py-1.5" title="当前本体:积木、版本、动作、审计都按本体隔离">
<span className="block text-[10px] text-muted">当前本体</span>
<select className="w-full truncate bg-transparent text-[13px] font-semibold outline-none" value={curSpace?.id || ws}
onChange={(e) => switchSpace(e.target.value)}>
{!spaces.some((x) => x.id === (curSpace?.id || ws)) && <option value={curSpace?.id || ws}>{curSpace?.display_name || ws || "默认本体"}</option>}
{spaces.map((x) => <option key={x.id} value={x.id}>{x.display_name}</option>)}
</select>
<span className="block truncate font-mono text-[10px] text-muted">{curSpace?.id || ws}</span>
</label>
</div>
)}
<nav className="flex-1 space-y-2 overflow-auto p-2"> <nav className="flex-1 space-y-2 overflow-auto p-2">
{NAV.map((g) => { {navGroups.map((g) => {
const hasActive = g.items.some((n) => n.key === navKey); const hasActive = g.items.some((n) => n.key === navKey);
const closed = folded[g.group] && !hasActive && !sidebarCollapsed; const closed = folded[g.group] && !hasActive && !sidebarCollapsed;
return ( return (
<div key={g.group}> <div key={g.group}>
{!sidebarCollapsed && ( {!sidebarCollapsed && g.group && (
<button className="flex w-full items-center px-2.5 pb-1 text-[10.5px] font-medium uppercase tracking-wide text-muted/70 hover:text-muted" <button className="flex w-full items-center px-2.5 pb-1 text-[10.5px] font-medium uppercase tracking-wide text-muted/70 hover:text-muted"
onClick={() => fold(g.group)}> onClick={() => fold(g.group)}>
<span className="flex-1 text-left">{g.group}</span> <span className="flex-1 text-left">{g.group}</span>
...@@ -235,19 +281,21 @@ export default function App() { ...@@ -235,19 +281,21 @@ export default function App() {
<main className={cn("min-h-0 flex-1 p-4", fullBleed ? "overflow-hidden" : "overflow-auto")}> <main className={cn("min-h-0 flex-1 p-4", fullBleed ? "overflow-hidden" : "overflow-auto")}>
{/* 切换身份时整页重挂,所有数据按新身份重新加载 */} {/* 切换身份时整页重挂,所有数据按新身份重新加载 */}
<div key={uid} className="h-full"> <div key={`${uid}@${ws}`} className="h-full">
{page === "data" && <SqlPage />} {page === "desk" && <WorkbenchPage />}
{page === "home" && <HomePage me={me} />}
{page === "data" && <SqlPage me={me} />}
{page === "pipeline" && <PipelinePage me={me} />}
{(page === "documents" || page === "graph") && ( {(page === "documents" || page === "graph") && (
<div className="flex h-full flex-col gap-3"> <div className="flex h-full flex-col gap-3">
<Segmented value={page === "graph" ? "graph" : "documents"} onChange={(k) => go(k)} <Segmented value={page === "graph" ? "graph" : "documents"} onChange={(k) => go(k)}
options={[{ key: "documents", label: "文档" }, { key: "graph", label: "证据图谱" }]} /> options={[{ key: "documents", label: "文档" }, { key: "graph", label: "知识图谱" }]} />
<div className="min-h-0 flex-1"> <div className="min-h-0 flex-1">
{page === "documents" ? <DocumentsPage onExtracted={refresh} /> : <GraphPage />} {page === "documents" ? <DocumentsPage onExtracted={refresh} /> : <GraphPage />}
</div> </div>
</div> </div>
)} )}
{page === "endpoints" && <CapabilityPage me={me} />} {page === "modeling" && <ModelingPage me={me} />}
{page === "wizard" && <WizardPage me={me} />}
{page === "publish" && <PublishPage me={me} />} {page === "publish" && <PublishPage me={me} />}
{page === "versions" && <VersionsPage me={me} />} {page === "versions" && <VersionsPage me={me} />}
{page === "canvas" && <CanvasPage me={me} />} {page === "canvas" && <CanvasPage me={me} />}
...@@ -259,6 +307,7 @@ export default function App() { ...@@ -259,6 +307,7 @@ export default function App() {
{page === "ask" && <AskPage />} {page === "ask" && <AskPage />}
{page === "objects" && <ObjectsPage me={me} />} {page === "objects" && <ObjectsPage me={me} />}
{page === "inbox" && <InboxPage onChanged={refresh} />} {page === "inbox" && <InboxPage onChanged={refresh} />}
{page === "runtime" && <OverviewPage />}
{page === "mcp" && <McpPage />} {page === "mcp" && <McpPage />}
{page === "audit" && <AuditPage />} {page === "audit" && <AuditPage />}
{page === "members" && <MembersPage me={me} />} {page === "members" && <MembersPage me={me} />}
......
...@@ -36,12 +36,27 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s ...@@ -36,12 +36,27 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
const [reason, setReason] = useState(card.reason); const [reason, setReason] = useState(card.reason);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [runId, setRunId] = useState<string>(""); const [runId, setRunId] = useState<string>("");
// AI 填的参数只是建议:人可以改,改完重新预览再提交
const [params, setParams] = useState<Record<string, any>>(card.params || {});
const [objKey, setObjKey] = useState(card.object_key || "");
const [preview, setPreview] = useState(card.preview);
const [err, setErr] = useState(card.error || "");
const [dirty, setDirty] = useState(false);
const defs = card.param_defs || [];
const repreview = async () => {
setBusy(true);
try {
setPreview(await onto.prepareAction(card.action_id || card.action, params, objKey));
setErr(""); setDirty(false);
} catch (e) { setPreview(undefined); setErr(errText(e)); } finally { setBusy(false); }
};
const submit = async () => { const submit = async () => {
setBusy(true); setBusy(true);
try { try {
const run = await onto.proposeAction(card.action_id || card.action, { const run = await onto.proposeAction(card.action_id || card.action, {
params: card.params, object_key: card.object_key, reason, params, object_key: objKey, reason,
initiator_kind: "ai", source_ref: `turn:${turnId}`, initiator_kind: "ai", source_ref: `turn:${turnId}`,
}); });
setRunId(run.id); setRunId(run.id);
...@@ -58,16 +73,39 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s ...@@ -58,16 +73,39 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<ShieldCheck className="h-4 w-4 text-brand" /> <ShieldCheck className="h-4 w-4 text-brand" />
<span className="text-[13px] font-medium">建议动作:{card.display_name}</span> <span className="text-[13px] font-medium">建议动作:{card.display_name}</span>
{card.preview && <Badge tone={RISK_TONE[card.preview.action.risk_level]}>{RISK[card.preview.action.risk_level]}</Badge>} {preview && <Badge tone={RISK_TONE[preview.action.risk_level]}>{RISK[preview.action.risk_level]}</Badge>}
{card.preview?.action.reversible && <Badge tone="bg-ink/5 text-muted"><Undo2 className="h-3 w-3" />可撤销</Badge>} {preview?.action.reversible && <Badge tone="bg-ink/5 text-muted"><Undo2 className="h-3 w-3" />可撤销</Badge>}
</div>
{(defs.length > 0 || card.target_type) && !runId && (
<div className="mt-2 grid gap-2 sm:grid-cols-2">
{card.target_type && (
<label className="flex items-center gap-2 text-[12px]"><span className="w-20 shrink-0 text-muted">作用对象</span>
<input className="input h-8 flex-1 font-mono text-[12px]" value={objKey} placeholder="对象主键"
onChange={(e) => { setObjKey(e.target.value); setDirty(true); }} /></label>
)}
{defs.map((d) => (
<label key={d.name} className="flex items-center gap-2 text-[12px]">
<span className="w-20 shrink-0 truncate text-muted" title={d.name}>{d.label || d.name}{d.required && <span className="text-bad">*</span>}</span>
{d.enum?.length ? (
<select className="input h-8 flex-1" value={params[d.name] ?? ""} onChange={(e) => { setParams({ ...params, [d.name]: e.target.value }); setDirty(true); }}>
<option value="">请选择</option>{d.enum.map((x) => <option key={x}>{x}</option>)}
</select>
) : (
<input className="input h-8 flex-1 text-[12.5px]" value={params[d.name] ?? ""} inputMode={d.type === "number" || d.type === "integer" ? "decimal" : undefined}
onChange={(e) => { setParams({ ...params, [d.name]: e.target.value }); setDirty(true); }} />
)}
</label>
))}
{(dirty || err) && <button className="btn btn-sm w-fit" disabled={busy} onClick={() => void repreview()}>{busy && <Spinner className="h-3.5 w-3.5" />}重新预览</button>}
</div> </div>
{card.error ? ( )}
{err ? (
<p className="mt-2 flex items-center gap-1.5 text-[12.5px] text-warn"> <p className="mt-2 flex items-center gap-1.5 text-[12.5px] text-warn">
<AlertTriangle className="h-3.5 w-3.5" /> 暂不能提交:{card.error} <AlertTriangle className="h-3.5 w-3.5" /> 暂不能提交:{err}{defs.length > 0 && "(改一下上面的参数再预览)"}
</p> </p>
) : card.preview && ( ) : preview && (
<> <>
<div className="mt-2"><EffectList preview={card.preview} /></div> <div className="mt-2"><EffectList preview={preview} /></div>
<div className="mt-2 flex flex-wrap items-center gap-2"> <div className="mt-2 flex flex-wrap items-center gap-2">
<input className="input h-8 min-w-0 flex-1 text-[12.5px]" value={reason} <input className="input h-8 min-w-0 flex-1 text-[12.5px]" value={reason}
onChange={(e) => setReason(e.target.value)} placeholder="提交理由(审批人会看到)" /> onChange={(e) => setReason(e.target.value)} placeholder="提交理由(审批人会看到)" />
...@@ -76,14 +114,14 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s ...@@ -76,14 +114,14 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
已提交,查看审批单 <ExternalLink className="h-3 w-3" /> 已提交,查看审批单 <ExternalLink className="h-3 w-3" />
</button> </button>
) : ( ) : (
<button className="btn btn-primary btn-sm" disabled={busy || !reason.trim()} onClick={submit}> <button className="btn btn-primary btn-sm" disabled={busy || dirty || !reason.trim()} title={dirty ? "参数改过了,先重新预览" : ""} onClick={submit}>
{busy && <Spinner className="h-3.5 w-3.5" />} 提交审批 {busy && <Spinner className="h-3.5 w-3.5" />} 提交审批
</button> </button>
)} )}
</div> </div>
<p className="mt-1.5 text-[11px] text-muted"> <p className="mt-1.5 text-[11px] text-muted">
AI 只能建议,不能执行。提交后由{card.preview.action.approver_roles.length AI 只能建议,不能执行。提交后由{preview.action.approver_roles.length
? `「${card.preview.action.approver_roles.join("、")}」` : "有审批权限的人"}审批,你本人不能审批自己提交的动作。 ? `「${preview.action.approver_roles.join("、")}」` : "有审批权限的人"}审批,你本人不能审批自己提交的动作。
</p> </p>
</> </>
)} )}
......
...@@ -4,7 +4,7 @@ import { ...@@ -4,7 +4,7 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { Badge, Collapse, Empty, Modal, Pill } from "@/components/ui"; import { Badge, Collapse, Empty, Modal, Pill } from "@/components/ui";
import { go } from "@/lib/nav"; import { go, useHashParams } from "@/lib/nav";
import { import {
errText, KIND_COLOR, onto, type AskCard, type Citation, type DataRef, type LinkResult, type Turn, errText, KIND_COLOR, onto, type AskCard, type Citation, type DataRef, type LinkResult, type Turn,
} from "@/lib/onto"; } from "@/lib/onto";
...@@ -58,18 +58,9 @@ export function AskPage() { ...@@ -58,18 +58,9 @@ export function AskPage() {
const loadConvs = useCallback(() => { void onto.conversations().then(setConvs).catch(() => setConvs([])); }, []); const loadConvs = useCallback(() => { void onto.conversations().then(setConvs).catch(() => setConvs([])); }, []);
useEffect(() => { useEffect(() => {
loadConvs(); loadConvs();
void Promise.all([onto.concepts({ kind: "function", status: "published" }), onto.sops({ status: "published" })]) // 示例问题和工作台同一份:按本体里真有的指标、维度、动作生成,不带指标不支持的时间范围
.then(([fs, sops]) => { void onto.workbench().then((w) => setExamples(w.questions.length ? w.questions : ["本体里有哪些指标?", "能帮我做什么?"]))
const ms = fs.filter((f) => f.category === "aggregate"); .catch(() => setExamples(["本体里有哪些指标?"]));
const rs = fs.filter((f) => f.category === "rule" || f.category === "decision");
const ps = sops.map((s) => ({ name: s.title }));
const ex: string[] = [];
ms.slice(0, 2).forEach((m) => ex.push(`本月${m.name}是多少?`));
rs.slice(0, 1).forEach((r) => ex.push(`${r.name}是怎么规定的?`));
ps.slice(0, 1).forEach((p) => ex.push(`${p.name}的流程是怎样的?`));
if (ms[0]) ex.push(`上个月${ms[0].name}最低的是哪些,应该怎么处理?`);
setExamples(ex.length ? ex : ["本体里有哪些指标?", "能帮我做什么?"]);
}).catch(() => setExamples(["本体里有哪些指标?"]));
return () => handle.current?.abort(); return () => handle.current?.abort();
}, [loadConvs]); }, [loadConvs]);
...@@ -85,6 +76,14 @@ export function AskPage() { ...@@ -85,6 +76,14 @@ export function AskPage() {
} catch (e) { toast("error", "打开会话失败", errText(e)); } } catch (e) { toast("error", "打开会话失败", errText(e)); }
}; };
// 从工作台带着问题跳过来(#/ask?q=...):直接问
const hp = useHashParams();
const asked = useRef("");
useEffect(() => {
const q = hp.get("q");
if (q && asked.current !== q && !running) { asked.current = q; ask(q); go("ask"); }
}, [hp]); // eslint-disable-line react-hooks/exhaustive-deps
const newConv = () => { handle.current?.abort(); setRunning(false); setConvId(""); setTurns([]); }; const newConv = () => { handle.current?.abort(); setRunning(false); setConvId(""); setTurns([]); };
const patchLast = (fn: (t: LiveTurn) => LiveTurn) => const patchLast = (fn: (t: LiveTurn) => LiveTurn) =>
......
...@@ -11,7 +11,8 @@ type Tab = "endpoint" | "builtin"; ...@@ -11,7 +11,8 @@ type Tab = "endpoint" | "builtin";
const RISK_TONE: Record<string, string> = { low: "bg-ok/10 text-ok", medium: "bg-warn/10 text-warn", high: "bg-bad/10 text-bad" }; const RISK_TONE: Record<string, string> = { low: "bg-ok/10 text-ok", medium: "bg-warn/10 text-warn", high: "bg-bad/10 text-bad" };
/** /**
* 外部系统连接:动作通过 webhook.call 效果调用的外部端点(地址 + 加密凭据),以及系统内置函数与效果的参考清单。 * 外部系统 / API(数据连接页的一个页签):动作通过 webhook.call 回写外部系统、模型推理函数调用推理服务时用的
* 外部端点(地址 + 加密凭据),以及系统内置函数与效果的参考清单。
* 动作、AI 分析函数已经是本体积木,在「动作类型」「函数类型」里编辑。 * 动作、AI 分析函数已经是本体积木,在「动作类型」「函数类型」里编辑。
*/ */
export function CapabilityPage({ me }: { me: Me | null }) { export function CapabilityPage({ me }: { me: Me | null }) {
......
import {
ArrowRight, Blocks, Bot, Boxes, Database, FileText, FunctionSquare, GitBranch, LayoutGrid, ListChecks,
Network, Plus, ShieldCheck, Wand2, Workflow, Zap,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Card, CardHeader, Field, Modal, Spinner } from "@/components/ui";
import { setCurrentWorkspace } from "@/lib/identity";
import { go } from "@/lib/nav";
import { errText, fmtTime, onto, type HomeOverview, type Me, type WorkspaceRec } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
const ASSETS: { key: keyof WorkspaceRec["counts"]; label: string; page: string; icon: React.ReactNode; color: string }[] = [
{ key: "object_type", label: "对象类型", page: "b_object", icon: <Boxes className="h-4 w-4" />, color: "#6366f1" },
{ key: "link_type", label: "关系类型", page: "b_link", icon: <GitBranch className="h-4 w-4" />, color: "#8b5cf6" },
{ key: "function", label: "函数类型", page: "b_function", icon: <FunctionSquare className="h-4 w-4" />, color: "#0ea5e9" },
{ key: "action", label: "动作类型", page: "b_action", icon: <Zap className="h-4 w-4" />, color: "#ef4444" },
{ key: "sop", label: "流程卡", page: "sop", icon: <ListChecks className="h-4 w-4" />, color: "#10b981" },
];
const CAPS = [
{ page: "pipeline", title: "数据管道", tag: "集成", desc: "同步对象骨架,物化关系边", icon: <Workflow className="h-4 w-4" /> },
{ page: "canvas", title: "本体画布", tag: "建模", desc: "对象、关系、函数、动作同图管理", icon: <LayoutGrid className="h-4 w-4" /> },
{ page: "b_object", title: "对象类型", tag: "建模", desc: "实体 · 属性 · 映射到数据表", icon: <Boxes className="h-4 w-4" /> },
{ page: "mcp", title: "MCP 服务", tag: "运行", desc: "给 Agent 暴露本体能力", icon: <Bot className="h-4 w-4" /> },
{ page: "inbox", title: "行动审批", tag: "运行", desc: "人机回路:动作先成提案,再由人批", icon: <ShieldCheck className="h-4 w-4" /> },
{ page: "sop", title: "流程卡", tag: "编排", desc: "编排函数、分析、人工任务与动作", icon: <ListChecks className="h-4 w-4" /> },
];
/**
* 本体首页:上面是所有本体空间(一个行业 / 业务域一套本体),下面是当前本体的总览 ——
* 资产计数、常用能力、快捷入口、建议下一步。
*/
export function HomePage({ me }: { me: Me | null }) {
const [list, setList] = useState<WorkspaceRec[] | null>(null);
const [home, setHome] = useState<HomeOverview | null>(null);
const [creating, setCreating] = useState(false);
const load = useCallback(() => {
void onto.workspaces().then(setList).catch(() => setList([]));
void onto.home().then(setHome).catch((e) => toast("error", "加载失败", errText(e)));
}, []);
useEffect(load, [load]);
const canBuild = !!me?.permissions.includes("build");
const cur = home?.workspace;
return (
<div className="mx-auto max-w-6xl space-y-5">
<Card className="overflow-hidden">
<div className="flex flex-wrap items-center gap-4 p-5" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.12), rgb(var(--brand2) / 0.05) 55%, transparent)" }}>
<span className="grid h-12 w-12 place-items-center rounded-xl bg-brand text-[18px] font-bold text-white">{(cur?.display_name || "本")[0]}</span>
<div className="min-w-0 flex-1">
<p className="text-[11px] text-muted">当前本体</p>
<p className="text-[20px] font-semibold leading-tight">{cur?.display_name || "…"}</p>
<p className="mt-0.5 text-[12px] text-muted">在统一本体上完成数据集成、建模与运行时治理。<span className="font-mono">{cur?.id}</span>
{home && <> · 线上 v{home.revision}{home.dirty ? ` · ${home.dirty} 处未发布` : ""}</>}</p>
</div>
{home && (
<div className="flex gap-2">
<Badge tone={home.pipelines.failed ? "bg-bad/10 text-bad" : "bg-ok/10 text-ok"}>
<Network className="h-3 w-3" />{home.pipelines.failed ? `${home.pipelines.failed} 条管道失败` : "引擎健康"}</Badge>
</div>
)}
</div>
</Card>
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_300px]">
<div className="space-y-4">
<Card>
<CardHeader title="本体资产" right={<button className="btn btn-ghost btn-sm" onClick={() => go("canvas")}>查看全部 <ArrowRight className="h-3.5 w-3.5" /></button>} />
<div className="grid grid-cols-2 gap-3 p-4 sm:grid-cols-5">
{ASSETS.map((a) => (
<button key={a.key} className="rounded-xl border border-line p-3 text-left hover:border-brand/40" onClick={() => go(a.page)}>
<p className="flex items-center gap-1.5 text-[12px] text-muted"><span style={{ color: a.color }}>{a.icon}</span>{a.label}</p>
<p className="mt-1 text-[26px] font-semibold leading-none tabular-nums">{home ? home.counts[a.key] : "-"}</p>
{a.key === "object_type" && home && home.mapped.object_unmapped > 0 && (
<p className="mt-1 text-[11px] text-warn">{home.mapped.object_unmapped} 个未映射</p>)}
</button>
))}
</div>
</Card>
<Card>
<CardHeader title="常用能力" />
<div className="grid gap-2 p-4 sm:grid-cols-3">
{CAPS.map((c) => (
<button key={c.page + c.title} className="flex items-start gap-2.5 rounded-xl border border-line p-3 text-left hover:border-brand/40" onClick={() => go(c.page)}>
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand/10 text-brand">{c.icon}</span>
<span className="min-w-0"><span className="flex items-center gap-1.5 text-[13px] font-semibold">{c.title}<Badge>{c.tag}</Badge></span>
<span className="text-[11.5px] text-muted">{c.desc}</span></span>
</button>
))}
</div>
</Card>
</div>
<div className="space-y-4">
<Card>
<CardHeader title="快捷入口" />
<div className="grid grid-cols-3 gap-2 p-4">
{[{ p: "data", l: "数据连接", i: <Database className="h-5 w-5" /> }, { p: "modeling", l: "业务建模", i: <Wand2 className="h-5 w-5" /> },
{ p: "documents", l: "知识库", i: <FileText className="h-5 w-5" /> }].map((x) => (
<button key={x.p} className="flex flex-col items-center gap-1.5 rounded-xl p-2 text-[12px] hover:bg-ink/[0.03]" onClick={() => go(x.p)}>
<span className="grid h-10 w-10 place-items-center rounded-xl bg-brand text-white">{x.i}</span>{x.l}</button>
))}
</div>
</Card>
<Card>
<CardHeader title="建议下一步" />
<div className="space-y-1 p-3">
{!home ? <Spinner /> : home.next_steps.length ? home.next_steps.map((s, i) => (
<button key={i} className="flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-ink/[0.03]" onClick={() => go(s.key)}>
<span className="mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full bg-brand/10 text-[11px] font-semibold text-brand">{i + 1}</span>
<span className="min-w-0"><span className="block text-[12.5px] font-medium">{s.title}</span><span className="block text-[11px] text-muted">{s.hint}</span></span>
</button>
)) : <p className="px-2 py-3 text-[12px] text-muted">一切就绪。可以去「提问」或把 MCP 服务接给你的 Agent。</p>}
</div>
</Card>
<Card className="grid grid-cols-2 gap-3 p-4 text-[12px]">
<button className="text-left" onClick={() => go("inbox")}><p className="text-muted">待审批动作</p><p className="text-[20px] font-semibold">{home?.pending_approvals ?? "-"}</p></button>
<button className="text-left" onClick={() => go("modeling")}><p className="text-muted">待审核草案</p><p className="text-[20px] font-semibold">{home?.pending_reviews ?? "-"}</p></button>
<button className="text-left" onClick={() => go("data")}><p className="text-muted">数据连接</p><p className="text-[20px] font-semibold">{home?.datasources ?? "-"}</p></button>
<button className="text-left" onClick={() => go("pipeline")}><p className="text-muted">数据管道</p><p className="text-[20px] font-semibold">{home?.pipelines.total ?? "-"}</p>
<p className="text-[10.5px] text-muted">{home?.pipelines.last_run_at ? `同步于 ${fmtTime(home.pipelines.last_run_at)}` : "未同步"}</p></button>
</Card>
</div>
</div>
<Card>
<CardHeader title={<span className="flex items-center gap-2"><Blocks className="h-4 w-4" />全部本体 · {list?.length ?? 0}</span>}
desc="一个行业 / 业务域一套本体;积木、版本、动作、审计、数据连接都按本体隔离"
right={canBuild && <button className="btn btn-primary btn-sm" onClick={() => setCreating(true)}><Plus className="h-3.5 w-3.5" />新建本体</button>} />
<div className="grid gap-3 p-4 sm:grid-cols-2 xl:grid-cols-3">
{!list ? <Spinner /> : list.map((w) => (
<button key={w.id} onClick={() => { if (!w.current) { setCurrentWorkspace(w.id); toast("ok", `已切换到「${w.display_name}」`); } }}
className={cn("rounded-xl border p-3 text-left transition-colors", w.current ? "border-brand bg-brand/5" : "border-line hover:border-brand/40")}>
<div className="flex items-center gap-2">
<span className="grid h-7 w-7 place-items-center rounded-lg bg-brand/15 text-[12px] font-bold text-brand">{w.display_name[0]}</span>
<span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold">{w.display_name}</span>
{w.current ? <Badge tone="bg-brand/10 text-brand">当前</Badge> : <Badge tone="bg-ok/10 text-ok">可切换</Badge>}
</div>
<p className="mt-1 line-clamp-1 min-h-[1.4em] text-[11.5px] text-muted">{w.description || w.industry || "(无描述)"}</p>
<div className="mt-3 grid grid-cols-5 text-center">
{ASSETS.map((a) => <div key={a.key}><p className="text-[16px] font-semibold tabular-nums">{w.counts[a.key]}</p><p className="text-[10.5px] text-muted">{a.label.replace("类型", "")}</p></div>)}
</div>
<p className="mt-2 font-mono text-[10.5px] text-muted">{w.id}</p>
</button>
))}
</div>
</Card>
{creating && <NewWorkspace onClose={() => setCreating(false)} onDone={(id) => { setCreating(false); setCurrentWorkspace(id); }} />}
</div>
);
}
function NewWorkspace({ onClose, onDone }: { onClose: () => void; onDone: (id: string) => void }) {
const [f, setF] = useState({ id: "", display_name: "", description: "", industry: "", template: "" });
const [tpls, setTpls] = useState<{ id: string; name: string }[]>([]);
const [busy, setBusy] = useState(false);
useEffect(() => { void onto.templates().then(setTpls).catch(() => undefined); }, []);
const create = async () => {
setBusy(true);
try { const w = await onto.createWorkspace(f); toast("ok", `已创建本体「${w.display_name}」`); onDone(w.id); }
catch (e) { toast("error", "创建失败", errText(e)); } finally { setBusy(false); }
};
return (
<Modal open onClose={onClose} title="新建本体"
footer={<><button className="btn" onClick={onClose}>取消</button>
<button className="btn btn-primary" disabled={busy || !f.display_name} onClick={() => void create()}>{busy && <Spinner className="h-3.5 w-3.5" />}创建并切换</button></>}>
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<Field label="名称" required><input className="input" placeholder="如:半导体高端制造" value={f.display_name} onChange={(e) => setF({ ...f, display_name: e.target.value })} /></Field>
<Field label="标识" hint="可不填,系统自动生成;填的话用小写字母开头的字母数字下划线"><input className="input font-mono" placeholder="自动生成" value={f.id}
onChange={(e) => setF({ ...f, id: e.target.value.toLowerCase() })} /></Field>
</div>
<Field label="行业"><input className="input" placeholder="制造 / 零售 / 金融 / 医药…" value={f.industry} onChange={(e) => setF({ ...f, industry: e.target.value })} /></Field>
<Field label="说明"><textarea className="input" value={f.description} onChange={(e) => setF({ ...f, description: e.target.value })} /></Field>
<Field label="起步模板" hint="可选:套用行业模板或通用起步包作为草稿">
<select className="input" value={f.template} onChange={(e) => setF({ ...f, template: e.target.value })}>
<option value="">空本体</option>
{tpls.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
</Field>
</div>
</Modal>
);
}
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { import {
Bell, Bot, CheckCircle2, ClipboardList, ExternalLink, GitPullRequest, ShieldCheck, Undo2, User, Workflow, XCircle, Bell, Bot, CheckCircle2, ClipboardList, ExternalLink, GitPullRequest, Radar, Rocket, ShieldCheck, Undo2, User, Workflow,
XCircle,
} from "lucide-react"; } from "lucide-react";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Badge, Card, CardHeader, Empty, Field, Modal, Segmented, Spinner } from "@/components/ui"; import { Badge, Card, CardHeader, Empty, Field, Modal, Segmented, Spinner } from "@/components/ui";
import { go, useHashParams } from "@/lib/nav"; import { go, useHashParams } from "@/lib/nav";
import { import {
errText, fmtTime, onto, STATUS_LABEL, STATUS_TONE, type ActionRun, type InboxCounts, type NotificationRec, errText, fmtTime, onto, PRIORITY_TONE, STATUS_LABEL, STATUS_TONE, type ActionRun, type InboxCounts, type NotificationRec,
type ReviewItem, type TaskRec, type ReleaseItem, type ReviewItem, type TaskRec,
} from "@/lib/onto"; } from "@/lib/onto";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { promptText } from "@/lib/dialog"; import { promptText } from "@/lib/dialog";
import { toast } from "@/store/useAppStore"; import { toast } from "@/store/useAppStore";
import { EffectList } from "../ask/ActionCard"; import { EffectList } from "../ask/ActionCard";
type Tab = "approvals" | "tasks" | "reviews" | "runs" | "notifications"; type Tab = "approvals" | "releases" | "tasks" | "reviews" | "runs" | "notifications";
export function InboxPage({ onChanged }: { onChanged?: () => void }) { export function InboxPage({ onChanged }: { onChanged?: () => void }) {
const params = useHashParams(); const params = useHashParams();
...@@ -29,14 +32,22 @@ export function InboxPage({ onChanged }: { onChanged?: () => void }) { ...@@ -29,14 +32,22 @@ export function InboxPage({ onChanged }: { onChanged?: () => void }) {
const badge = (n?: number) => (n ? <Badge tone="bg-bad/10 text-bad">{n}</Badge> : undefined); const badge = (n?: number) => (n ? <Badge tone="bg-bad/10 text-bad">{n}</Badge> : undefined);
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
<p className="text-[16px] font-semibold">审批中心</p>
<p className="text-[12px] text-muted">任何写操作都不会被偷偷执行:AI、流程卡、外部 Agent 提议的动作先成审批单,附上依据和影响面,人批了才执行,拒绝就关闭,全程留痕。</p>
</div>
</div>
<Segmented value={tab} onChange={setTab} options={[ <Segmented value={tab} onChange={setTab} options={[
{ key: "approvals", label: "待我审批", badge: badge(counts?.approvals) }, { key: "approvals", label: "待审批动作", badge: badge(counts?.approvals) },
{ key: "releases", label: "变更提案", badge: badge(counts?.releases) },
{ key: "tasks", label: "我的待办", badge: badge(counts?.tasks) }, { key: "tasks", label: "我的待办", badge: badge(counts?.tasks) },
{ key: "reviews", label: "审核队列", badge: badge(counts?.reviews) }, { key: "reviews", label: "审核队列", badge: badge(counts?.reviews) },
{ key: "runs", label: "动作记录" }, { key: "runs", label: "审批历史" },
{ key: "notifications", label: "通知", badge: badge(counts?.notifications) }, { key: "notifications", label: "通知", badge: badge(counts?.notifications) },
]} /> ]} />
{tab === "approvals" && <Approvals focus={params.get("run") || ""} onChanged={refreshCounts} />} {tab === "approvals" && <Approvals focus={params.get("run") || ""} onChanged={refreshCounts} />}
{tab === "releases" && <Releases />}
{tab === "tasks" && <Tasks focus={params.get("task") || ""} onChanged={refreshCounts} />} {tab === "tasks" && <Tasks focus={params.get("task") || ""} onChanged={refreshCounts} />}
{tab === "reviews" && <Reviews onChanged={refreshCounts} />} {tab === "reviews" && <Reviews onChanged={refreshCounts} />}
{tab === "runs" && <Runs focus={params.get("run") || ""} onChanged={refreshCounts} />} {tab === "runs" && <Runs focus={params.get("run") || ""} onChanged={refreshCounts} />}
...@@ -77,10 +88,28 @@ export function RunDetail({ run, onDone }: { run: ActionRun; onDone: () => void ...@@ -77,10 +88,28 @@ export function RunDetail({ run, onDone }: { run: ActionRun; onDone: () => void
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<Badge tone={STATUS_TONE[run.status]}>{STATUS_LABEL[run.status] || run.status}</Badge> <Badge tone={STATUS_TONE[run.status]}>{STATUS_LABEL[run.status] || run.status}</Badge>
<Badge tone="bg-brand/10 text-brand">{ini.icon}{ini.label}</Badge> <Badge tone="bg-brand/10 text-brand">{ini.icon}{ini.label}</Badge>
<Badge tone={PRIORITY_TONE[run.priority] || PRIORITY_TONE.P2}>{run.priority || "P2"}</Badge>
{run.kind === "revert" && <Badge tone="bg-warn/10 text-warn"><Undo2 className="h-3 w-3" />撤销申请</Badge>} {run.kind === "revert" && <Badge tone="bg-warn/10 text-warn"><Undo2 className="h-3 w-3" />撤销申请</Badge>}
<span className="text-muted">发起:{run.submitted_by || run.initiator_id} · {fmtTime(run.created_at)}</span> <span className="text-muted">发起:{run.submitted_by || run.initiator_id} · {fmtTime(run.created_at)}</span>
</div> </div>
{run.reason && <p className="rounded-md bg-ink/[0.03] p-2"><b>理由:</b>{run.reason}</p>} {run.reason && <p className="rounded-md bg-ink/[0.03] p-2"><b>理由:</b>{run.reason}</p>}
{run.evidence?.length > 0 && (
<div>
<p className="mb-1 text-[12px] font-medium text-muted">依据</p>
<ul className="space-y-0.5">{run.evidence.map((e, i) => (
<li key={i} className="flex gap-1.5"><Badge>{{ data: "数据", rule: "规则", doc: "原文", note: "说明" }[e.kind] || e.kind}</Badge>
<span className="min-w-0 flex-1">{e.text}</span>{e.ref && <code className="text-[11px] text-muted">{e.ref}</code>}</li>
))}</ul>
</div>
)}
{run.impact?.total ? (
<div className="rounded-md border border-warn/30 bg-warn/5 p-2">
<p className="flex items-center gap-1.5 text-[12px] font-medium"><Radar className="h-3.5 w-3.5 text-warn" />影响面(关系网两跳内):
{Object.entries(run.impact.by_type || {}).map(([k, v]) => <Badge key={k} tone="bg-warn/10 text-warn">{k} {v}</Badge>)}</p>
<p className="mt-1 text-[11.5px] text-muted">{(run.impact.sample || []).map((x) => `${x.type_name}「${x.label}」`).join("、")}
{run.impact.synced_at ? ` · 骨架截至 ${fmtTime(run.impact.synced_at)}` : ""}</p>
</div>
) : null}
{run.target_ref && ( {run.target_ref && (
<p className="text-muted">作用对象: <p className="text-muted">作用对象:
<button className="text-brand underline" onClick={() => { <button className="text-brand underline" onClick={() => {
...@@ -150,7 +179,9 @@ function RunList({ runs, focus, onDone, empty }: { runs: ActionRun[]; focus: str ...@@ -150,7 +179,9 @@ function RunList({ runs, focus, onDone, empty }: { runs: ActionRun[]; focus: str
<button key={r.id} onClick={() => setSel(r.id)} <button key={r.id} onClick={() => setSel(r.id)}
className={cn("block w-full px-3 py-2.5 text-left hover:bg-ink/[0.03]", sel === r.id && "bg-brand/5")}> className={cn("block w-full px-3 py-2.5 text-left hover:bg-ink/[0.03]", sel === r.id && "bg-brand/5")}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Badge tone={PRIORITY_TONE[r.priority] || PRIORITY_TONE.P2}>{r.priority || "P2"}</Badge>
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">{r.action_name}</span> <span className="min-w-0 flex-1 truncate text-[13px] font-medium">{r.action_name}</span>
{r.impact?.total ? <Badge tone="bg-warn/10 text-warn">影响 {r.impact.total}</Badge> : null}
<Badge tone={STATUS_TONE[r.status]}>{STATUS_LABEL[r.status] || r.status}</Badge> <Badge tone={STATUS_TONE[r.status]}>{STATUS_LABEL[r.status] || r.status}</Badge>
</div> </div>
<p className="mt-0.5 truncate text-[12px] text-muted">{r.preview.summary}</p> <p className="mt-0.5 truncate text-[12px] text-muted">{r.preview.summary}</p>
...@@ -181,6 +212,26 @@ function Approvals({ focus, onChanged }: { focus: string; onChanged: () => void ...@@ -181,6 +212,26 @@ function Approvals({ focus, onChanged }: { focus: string; onChanged: () => void
onDone={() => { load(); onChanged(); }} />; onDone={() => { load(); onChanged(); }} />;
} }
/** 本体的变更提案也在审批中心里露出;审批细节(逐项 diff)在「变更提案」页。 */
function Releases() {
const [items, setItems] = useState<ReleaseItem[] | null>(null);
useEffect(() => { void onto.releases().then(setItems).catch(() => setItems([])); }, []);
if (!items) return <Spinner />;
return (
<Card className="divide-y divide-line">
{!items.length && <Empty icon={<Rocket className="h-10 w-10" />} title="还没有变更提案" />}
{items.map((it) => (
<button key={it.id} className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-[12.5px] hover:bg-ink/[0.03]" onClick={() => go("publish")}>
<Badge tone={STATUS_TONE[it.status]}>{STATUS_LABEL[it.status] || it.status}</Badge>
<span className="min-w-0 flex-1 truncate font-medium">{it.title}{it.payload?.note ? ` · ${it.payload.note}` : ""}</span>
{it.status === "pending" && (it.can_decide ? <Badge tone="bg-brand/10 text-brand">可审批</Badge> : <Badge>{it.cannot_reason}</Badge>)}
<span className="text-muted">{it.created_by} · {fmtTime(it.created_at)}</span>
</button>
))}
</Card>
);
}
function Runs({ focus, onChanged }: { focus: string; onChanged: () => void }) { function Runs({ focus, onChanged }: { focus: string; onChanged: () => void }) {
const [runs, setRuns] = useState<ActionRun[] | null>(null); const [runs, setRuns] = useState<ActionRun[] | null>(null);
const [status, setStatus] = useState(""); const [status, setStatus] = useState("");
...@@ -273,9 +324,20 @@ function TaskDetail({ t, onDone }: { t: TaskRec; onDone: () => void }) { ...@@ -273,9 +324,20 @@ function TaskDetail({ t, onDone }: { t: TaskRec; onDone: () => void }) {
return ( return (
<> <>
<CardHeader title={t.title} desc={`任务 ${t.id}`} <CardHeader title={t.title} desc={`任务 ${t.id}`}
right={sopRun && <button className="btn btn-sm" onClick={() => go("sop", { run: sopRun })}>查看流程 <ExternalLink className="h-3 w-3" /></button>} /> right={<div className="flex gap-1.5">
{t.status === "open" && (
<button className="btn btn-sm" title="把待办内容带到提问页,让 AI 查数、算量、生成动作审批卡"
onClick={() => go("ask", { q: `帮我处理这个待办:${t.title}\n${(t.description || "").slice(0, 1500)}` })}>
让 AI 帮我处理</button>
)}
{sopRun && <button className="btn btn-sm" onClick={() => go("sop", { run: sopRun })}>查看流程 <ExternalLink className="h-3 w-3" /></button>}
</div>} />
<div className="space-y-3 p-4 text-[13px]"> <div className="space-y-3 p-4 text-[13px]">
{t.description && <p className="whitespace-pre-wrap">{t.description}</p>} {t.description && (
<div className="prose-sm max-w-none text-[12.5px] [&_table]:my-1 [&_table]:text-[12px] [&_td]:border [&_td]:border-line [&_td]:px-1.5 [&_th]:border [&_th]:border-line [&_th]:px-1.5">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{t.description}</ReactMarkdown>
</div>
)}
{t.object_ref && <p className="text-muted">关联对象:{t.object_ref}</p>} {t.object_ref && <p className="text-muted">关联对象:{t.object_ref}</p>}
{t.context?.vars && Object.keys(t.context.vars).length > 0 && ( {t.context?.vars && Object.keys(t.context.vars).length > 0 && (
<details className="rounded-md border border-line p-2"> <details className="rounded-md border border-line p-2">
......
import { Boxes, ExternalLink, History, RefreshCw, ShieldCheck, Workflow, Zap } from "lucide-react"; import { Boxes, ExternalLink, History, Radar, RefreshCw, ShieldCheck, Workflow, Zap } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Badge, Card, CardHeader, Empty, Field, Modal, Spinner, Stat } from "@/components/ui"; import { Badge, Card, CardHeader, Empty, Field, Modal, Spinner, Stat } from "@/components/ui";
import { go, useHashParams } from "@/lib/nav"; import { go, useHashParams } from "@/lib/nav";
import { import {
errText, fmtTime, onto, STATUS_LABEL, STATUS_TONE, type CapDef, type ConceptBrief, type Me, type ObjectRec, errText, fmtTime, onto, PRIORITY_TONE, STATUS_LABEL, STATUS_TONE, type CapDef, type ConceptBrief, type ImpactResult,
type Me, type ObjectRec,
} from "@/lib/onto"; } from "@/lib/onto";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore"; import { toast } from "@/store/useAppStore";
...@@ -56,8 +57,8 @@ export function ObjectsPage({ me }: { me: Me | null }) { ...@@ -56,8 +57,8 @@ export function ObjectsPage({ me }: { me: Me | null }) {
<div className="flex gap-1.5"> <div className="flex gap-1.5">
<input className="input" placeholder="按名称搜索" value={q} onChange={(e) => setQ(e.target.value)} /> <input className="input" placeholder="按名称搜索" value={q} onChange={(e) => setQ(e.target.value)} />
{me?.permissions.includes("build") && ( {me?.permissions.includes("build") && (
<button className="btn btn-sm" title="同步对象名录(问句里的对象名识别用)" onClick={async () => { <button className="btn btn-sm" title="同步这类对象的骨架(对象搜索、影响分析用;定时同步在「数据管道」里配)" onClick={async () => {
try { const r = await onto.syncObjects(type); toast("ok", `已同步 ${r.synced} 个对象名`); } try { const r = await onto.syncObjects(type); toast("ok", `已同步 ${r.rows} 个对象、${r.edges} 条关系边`); }
catch (e) { toast("error", errText(e)); } catch (e) { toast("error", errText(e)); }
}}><RefreshCw className="h-3.5 w-3.5" /></button> }}><RefreshCw className="h-3.5 w-3.5" /></button>
)} )}
...@@ -104,7 +105,7 @@ function Object360({ type, objKey, me }: { type: string; objKey: string; me: Me ...@@ -104,7 +105,7 @@ function Object360({ type, objKey, me }: { type: string; objKey: string; me: Me
<div className="grid gap-x-6 gap-y-2 p-4 sm:grid-cols-2 xl:grid-cols-3"> <div className="grid gap-x-6 gap-y-2 p-4 sm:grid-cols-2 xl:grid-cols-3">
{Object.entries(o.properties).map(([k, v]) => ( {Object.entries(o.properties).map(([k, v]) => (
<div key={k} className="min-w-0"> <div key={k} className="min-w-0">
<p className="text-[11px] text-muted">{k}{o.overridden?.includes(k) && <Badge tone="bg-brand/10 text-brand" className="ml-1">写回</Badge>} <p className="text-[11px] text-muted" title={k}>{props.find((p) => p.name === k)?.display_name || k}{o.overridden?.includes(k) && <Badge tone="bg-brand/10 text-brand" className="ml-1">写回</Badge>}
{props.find((p) => p.name === k)?.is_writable && !o.overridden?.includes(k) && <span className="ml-1 text-[10px]">可写</span>}</p> {props.find((p) => p.name === k)?.is_writable && !o.overridden?.includes(k) && <span className="ml-1 text-[10px]">可写</span>}</p>
<p className="truncate text-[13px]">{v === null || v === undefined ? "—" : String(v)}</p> <p className="truncate text-[13px]">{v === null || v === undefined ? "—" : String(v)}</p>
</div> </div>
...@@ -122,9 +123,11 @@ function Object360({ type, objKey, me }: { type: string; objKey: string; me: Me ...@@ -122,9 +123,11 @@ function Object360({ type, objKey, me }: { type: string; objKey: string; me: Me
</Card> </Card>
)} )}
<ImpactPanel type={type} objKey={objKey} />
<div className="grid gap-4 xl:grid-cols-2"> <div className="grid gap-4 xl:grid-cols-2">
<Card> <Card>
<CardHeader title="关联对象" /> <CardHeader title="关联对象(一跳,实时)" />
<div className="space-y-3 p-4"> <div className="space-y-3 p-4">
{!d.links.length && <p className="text-[12px] text-muted">本体里没有涉及它的关系类型,或关系未绑定关联列</p>} {!d.links.length && <p className="text-[12px] text-muted">本体里没有涉及它的关系类型,或关系未绑定关联列</p>}
{d.links.map((g: any) => ( {d.links.map((g: any) => (
...@@ -200,10 +203,88 @@ function Object360({ type, objKey, me }: { type: string; objKey: string; me: Me ...@@ -200,10 +203,88 @@ function Object360({ type, objKey, me }: { type: string; objKey: string; me: Me
); );
} }
/**
* 实例级影响分析:顺着关系网往外推 —— 这台机台出问题,哪些批次受影响、连累哪些订单、交期会不会破。
* 遍历走数据管道同步的骨架;最外层对象回业务库实时取一次最新属性。
*/
function ImpactPanel({ type, objKey }: { type: string; objKey: string }) {
const [depth, setDepth] = useState(3);
const [r, setR] = useState<ImpactResult | null>(null);
const [err, setErr] = useState("");
const [busy, setBusy] = useState(false);
const run = async () => {
setBusy(true); setErr("");
try { setR(await onto.impactObject(type, objKey, depth)); } catch (e) { setR(null); setErr(errText(e)); } finally { setBusy(false); }
};
return (
<Card>
<CardHeader title={<span className="flex items-center gap-1.5"><Radar className="h-4 w-4 text-brand" />影响分析</span>}
desc={r ? `${r.summary}${r.synced_at ? ` · 骨架数据截至 ${fmtTime(r.synced_at)}` : ""}${r.hidden ? ` · ${r.hidden} 个不在你的数据范围内` : ""}`
: "沿关系网多跳推演:会波及哪些对象、最外层的最新状态、可以采取的动作"}
right={<>
<select className="input h-8 w-24 py-0 text-[12px]" value={depth} onChange={(e) => setDepth(Number(e.target.value))}>
{[1, 2, 3, 4].map((d) => <option key={d} value={d}>{d} 跳</option>)}
</select>
<button className="btn btn-sm btn-primary" disabled={busy} onClick={() => void run()}>
{busy ? <Spinner className="h-3.5 w-3.5" /> : <Radar className="h-3.5 w-3.5" />}跑一次</button>
</>} />
{(err || r) && (
<div className="space-y-3 p-4 text-[12.5px]">
{err && <p className="rounded-md bg-warn/10 p-2 text-warn">{err}{err.includes("数据管道") &&
<button className="ml-2 text-brand underline" onClick={() => go("pipeline")}>去数据管道</button>}</p>}
{r && (
<>
<div className="flex flex-wrap items-center gap-2">
<span className="rounded-lg border border-brand/40 bg-brand/5 px-2 py-1 font-medium">{r.root.type_name}「{r.root.label}」</span>
{r.layers.map((l) => (
<span key={l.depth} className="flex items-center gap-2">
<span className="text-muted">→ 第 {l.depth} 跳</span>
{l.groups.map((g) => <Badge key={g.type_name} tone="bg-warn/10 text-warn">{g.type_name} {g.count}</Badge>)}
</span>
))}
{Object.entries(r.context || {}).map(([k, v]) => <span key={k} className="chip text-muted" title="沿外键往上走到的上级对象,只列出、不再往外推">涉及{k} {v}</span>)}
{!r.layers.length && <span className="text-muted">没有找到关联对象(检查关系是否绑定了关联列、两端是否都同步了)</span>}
{r.truncated && <Badge>结果已截断</Badge>}
</div>
{r.layers.map((l) => l.groups.map((g) => (
<div key={`${l.depth}:${g.type_name}`}>
<p className="mb-1 text-[11.5px] text-muted">第 {l.depth} 跳 · {g.type_name}({g.count})</p>
<div className="flex flex-wrap gap-1.5">
{g.items.map((n) => (
<button key={n.id} className="chip" title={n.via ? `经「${n.via.link}」` : ""}
onClick={() => go("objects", { type: n.type_id, key: n.key })}>{n.label}</button>
))}
</div>
</div>
)))}
{r.live.length > 0 && (
<div className="rounded-lg border border-line">
<p className="border-b border-line bg-ink/[0.02] px-2 py-1 text-[11.5px] font-medium">最外层对象的最新状态(实时)</p>
<div className="max-h-48 overflow-auto">
{r.live.map((x) => (
<p key={x.id} className="border-b border-line/50 px-2 py-1 last:border-0">
<b>{x.type_name}「{x.label}」</b>
<span className="ml-2 text-muted">{Object.entries(x.properties).slice(0, 6).map(([k, v]) => `${k} ${v ?? "—"}`).join(" · ")}</span></p>
))}
</div>
</div>
)}
{r.actions.length > 0 && (
<p className="text-muted">可以对受影响对象采取的动作:{r.actions.map((a) => a.display_name).join("、")}(在对应对象页发起,进审批)</p>
)}
</>
)}
</div>
)}
</Card>
);
}
/** 从对象页直接发起动作:填参数 → 看预览 → 提交审批。 */ /** 从对象页直接发起动作:填参数 → 看预览 → 提交审批。 */
export function ProposeActionModal({ action, objKey, onClose, onDone }: { action: CapDef; objKey: string; onClose: () => void; onDone: () => void }) { export function ProposeActionModal({ action, objKey, onClose, onDone }: { action: CapDef; objKey: string; onClose: () => void; onDone: () => void }) {
const [vals, setVals] = useState<Record<string, any>>({}); const [vals, setVals] = useState<Record<string, any>>({});
const [reason, setReason] = useState(""); const [reason, setReason] = useState("");
const [priority, setPriority] = useState("");
const [preview, setPreview] = useState<any>(null); const [preview, setPreview] = useState<any>(null);
const [err, setErr] = useState(""); const [err, setErr] = useState("");
const params = action.spec.params || []; const params = action.spec.params || [];
...@@ -218,7 +299,7 @@ export function ProposeActionModal({ action, objKey, onClose, onDone }: { action ...@@ -218,7 +299,7 @@ export function ProposeActionModal({ action, objKey, onClose, onDone }: { action
<button className="btn" onClick={() => void doPreview()}>预览</button> <button className="btn" onClick={() => void doPreview()}>预览</button>
<button className="btn btn-primary" disabled={!preview || !reason.trim()} onClick={async () => { <button className="btn btn-primary" disabled={!preview || !reason.trim()} onClick={async () => {
try { try {
const r = await onto.proposeAction(action.id, { params: vals, object_key: objKey, reason }); const r = await onto.proposeAction(action.id, { params: vals, object_key: objKey, reason, priority });
toast("ok", "已提交审批"); onDone(); go("inbox", { tab: "runs", run: r.id }); toast("ok", "已提交审批"); onDone(); go("inbox", { tab: "runs", run: r.id });
} catch (e) { toast("error", "提交失败", errText(e)); } } catch (e) { toast("error", "提交失败", errText(e)); }
}}>提交审批 <ExternalLink className="h-3 w-3" /></button> }}>提交审批 <ExternalLink className="h-3 w-3" /></button>
...@@ -235,7 +316,14 @@ export function ProposeActionModal({ action, objKey, onClose, onDone }: { action ...@@ -235,7 +316,14 @@ export function ProposeActionModal({ action, objKey, onClose, onDone }: { action
)} )}
</Field> </Field>
))} ))}
<Field label="提交理由" required><input className="input" value={reason} onChange={(e) => setReason(e.target.value)} /></Field> <div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_120px]">
<Field label="提交理由(审批人看到的依据)" required><input className="input" value={reason} onChange={(e) => setReason(e.target.value)} /></Field>
<Field label="优先级" hint="不选按动作风险定">
<select className={`input ${priority ? PRIORITY_TONE[priority] : ""}`} value={priority} onChange={(e) => setPriority(e.target.value)}>
<option value="">自动</option>{["P0", "P1", "P2", "P3"].map((p) => <option key={p}>{p}</option>)}
</select>
</Field>
</div>
{err && <p className="rounded-md bg-bad/10 p-2 text-[12.5px] text-bad">{err}</p>} {err && <p className="rounded-md bg-bad/10 p-2 text-[12.5px] text-bad">{err}</p>}
{preview && <EffectList preview={preview} />} {preview && <EffectList preview={preview} />}
<p className="text-[11px] text-muted">所有动作都需要人工审批后才执行;你不能审批自己提交的动作。</p> <p className="text-[11px] text-muted">所有动作都需要人工审批后才执行;你不能审批自己提交的动作。</p>
......
...@@ -60,7 +60,7 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: { ...@@ -60,7 +60,7 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: {
setBusy(true); setBusy(true);
try { try {
await onto.updateConcept(c.id, { ...draft, synonyms: draft.synonyms }); await onto.updateConcept(c.id, { ...draft, synonyms: draft.synonyms });
toast("ok", "已保存到草稿", "到「变更与发布」发布后,问答、取数、流程卡才会用到新定义"); toast("ok", "已保存到草稿", "到「变更提案」提交、审批通过后,问答、取数、流程卡才会用到新定义");
await load(); onChanged(); await load(); onChanged();
} catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); } } catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
}; };
...@@ -110,6 +110,9 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: { ...@@ -110,6 +110,9 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: {
<textarea className="input min-h-[52px]" value={draft.description} disabled={!canEdit} <textarea className="input min-h-[52px]" value={draft.description} disabled={!canEdit}
onChange={(e) => setDraft({ ...draft, description: e.target.value })} /> onChange={(e) => setDraft({ ...draft, description: e.target.value })} />
</Field> </Field>
<Field label="域" hint="业务分组(财务 / 质量 / 订单 / 设备……),用于浏览与画布分组">
<input className="input" value={draft.spec.domain || ""} disabled={!canEdit} onChange={(e) => set("domain", e.target.value)} />
</Field>
{c.kind === "object_type" && <ObjectFields spec={draft.spec} set={set} canEdit={canEdit} meta={meta} />} {c.kind === "object_type" && <ObjectFields spec={draft.spec} set={set} canEdit={canEdit} meta={meta} />}
...@@ -131,7 +134,9 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: { ...@@ -131,7 +134,9 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: {
<button key={x.category} disabled={!canEdit} <button key={x.category} disabled={!canEdit}
className={cn("chip", draft.spec.category === x.category && "border-brand text-brand")} className={cn("chip", draft.spec.category === x.category && "border-brand text-brand")}
onClick={() => setDraft({ ...draft, spec: { category: x.category, object_type: draft.spec.object_type, onClick={() => setDraft({ ...draft, spec: { category: x.category, object_type: draft.spec.object_type,
domain: draft.spec.domain,
...(x.category === "decision" ? EMPTY_DECISION : {}), ...(x.category === "decision" ? EMPTY_DECISION : {}),
...(x.category === "ml" ? EMPTY_ML : {}),
...(x.category === "ai" ? EMPTY_AI : {}) } })}> ...(x.category === "ai" ? EMPTY_AI : {}) } })}>
<i className="h-1.5 w-1.5 rounded-full" style={{ background: KIND_COLOR[x.category] }} />{x.label} <i className="h-1.5 w-1.5 rounded-full" style={{ background: KIND_COLOR[x.category] }} />{x.label}
</button> </button>
...@@ -154,6 +159,7 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: { ...@@ -154,6 +159,7 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: {
{draft.spec.category === "rule" && <RuleFields spec={draft.spec} set={set} canEdit={canEdit} meta={meta} />} {draft.spec.category === "rule" && <RuleFields spec={draft.spec} set={set} canEdit={canEdit} meta={meta} />}
{draft.spec.category === "calendar" && <CalendarFields spec={draft.spec} set={set} canEdit={canEdit} />} {draft.spec.category === "calendar" && <CalendarFields spec={draft.spec} set={set} canEdit={canEdit} />}
{draft.spec.category === "decision" && <DecisionEditor spec={draft.spec} onChange={(s) => setDraft({ ...draft, spec: s })} canEdit={canEdit} />} {draft.spec.category === "decision" && <DecisionEditor spec={draft.spec} onChange={(s) => setDraft({ ...draft, spec: s })} canEdit={canEdit} />}
{draft.spec.category === "ml" && <MlFields spec={draft.spec} set={set} canEdit={canEdit} />}
{draft.spec.category === "ai" && <AiFields spec={draft.spec} set={set} canEdit={canEdit} meta={meta} />} {draft.spec.category === "ai" && <AiFields spec={draft.spec} set={set} canEdit={canEdit} meta={meta} />}
</> </>
)} )}
...@@ -381,6 +387,44 @@ export function DecisionEditor({ spec, onChange, canEdit }: { spec: any; onChang ...@@ -381,6 +387,44 @@ export function DecisionEditor({ spec, onChange, canEdit }: { spec: any; onChang
); );
} }
const EMPTY_ML = { endpoint: "", inputs: [{ name: "x", label: "输入", type: "number" }],
outputs: [{ name: "y", label: "预测值", type: "number" }], result_path: "" };
/** 模型推理:选一个已登记的模型端点,声明输入输出。结果是确定的模型输出,可以当依据。 */
function MlFields({ spec, set, canEdit }: { spec: any; set: (k: string, v: any) => void; canEdit: boolean }) {
const [eps, setEps] = useState<{ name: string; display_name: string; status: string }[]>([]);
useEffect(() => { void onto.capDefs("endpoint").then(setEps).catch(() => undefined); }, []);
const io = (key: "inputs" | "outputs", label: string) => (
<Field label={label}>
<Rows items={spec[key] || []} disabled={!canEdit} onChange={(v) => set(key, v)} empty={{ name: "", label: "", type: "number" }}
render={(it: any, up) => (<>
<input className="input h-7 w-28 font-mono text-[12px]" placeholder="英文标识" value={it.name} onChange={(e) => up({ ...it, name: e.target.value })} />
<input className="input h-7 flex-1" placeholder="中文名" value={it.label} onChange={(e) => up({ ...it, label: e.target.value })} />
<select className="input h-7 w-24" value={it.type || "number"} onChange={(e) => up({ ...it, type: e.target.value })}>
<option value="number">数字</option><option value="string">文本</option>
</select>
</>)} />
</Field>
);
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<Field label="模型端点" required hint="在「数据连接 → 外部系统 / API」里登记推理服务地址与凭据">
<select className="input" value={spec.endpoint || ""} disabled={!canEdit} onChange={(e) => set("endpoint", e.target.value)}>
<option value="">(选择端点)</option>
{eps.map((e) => <option key={e.name} value={e.name}>{e.display_name || e.name}{e.status !== "published" ? "(未发布)" : ""}</option>)}
</select>
</Field>
<Field label="结果路径" hint="响应 JSON 里预测值所在位置,如 data.predictions.0;留空取整个响应">
<input className="input font-mono text-[12px]" value={spec.result_path || ""} disabled={!canEdit} onChange={(e) => set("result_path", e.target.value)} />
</Field>
</div>
<div className="grid gap-3 sm:grid-cols-2">{io("inputs", "输入")}{io("outputs", "输出")}</div>
<p className="text-[11.5px] text-muted">调用时发送 <code>{"{\"inputs\": {…}}"}</code>,按输出名从结果里取字段。</p>
</div>
);
}
function AiFields({ spec, set, canEdit, meta }: { spec: any; set: (k: string, v: any) => void; canEdit: boolean; meta: KernelMeta }) { function AiFields({ spec, set, canEdit, meta }: { spec: any; set: (k: string, v: any) => void; canEdit: boolean; meta: KernelMeta }) {
const fs: string[] = spec.functions || []; const fs: string[] = spec.functions || [];
return ( return (
...@@ -475,7 +519,9 @@ function ActionFields({ spec, set, canEdit, meta, objects }: { ...@@ -475,7 +519,9 @@ function ActionFields({ spec, set, canEdit, meta, objects }: {
{tool?.reversible && <Badge>可撤销</Badge>} {tool?.reversible && <Badge>可撤销</Badge>}
{tool?.external && <Badge tone="bg-bad/10 text-bad">调用外部系统</Badge>} {tool?.external && <Badge tone="bg-bad/10 text-bad">调用外部系统</Badge>}
</div> </div>
{tool && <SchemaForm schema={tool.input_schema} value={e.args || {}} onChange={(v) => up({ ...e, args: v })} disabled={!canEdit} compact />} {tool && e.tool === "object.create"
? <CreateObjectArgs objects={objects} value={e.args || {}} onChange={(v) => up({ ...e, args: v })} disabled={!canEdit} />
: tool && <SchemaForm schema={tool.input_schema} value={e.args || {}} onChange={(v) => up({ ...e, args: v })} disabled={!canEdit} compact />}
</div> </div>
); );
}} /> }} />
...@@ -494,7 +540,7 @@ export function TryPanel({ concept, kind, spec, name }: { concept?: Concept; kin ...@@ -494,7 +540,7 @@ export function TryPanel({ concept, kind, spec, name }: { concept?: Concept; kin
const init = () => { const init = () => {
if (kind === "action") return Object.fromEntries((spec.params || []).map((p: any) => [p.name, ""])); if (kind === "action") return Object.fromEntries((spec.params || []).map((p: any) => [p.name, ""]));
if (cat === "rule") return Object.fromEntries((spec.params || []).map((p: string) => [p, ""])); if (cat === "rule") return Object.fromEntries((spec.params || []).map((p: string) => [p, ""]));
if (cat === "decision") return Object.fromEntries((spec.inputs || []).map((p: any) => [p.name, ""])); if (cat === "decision" || cat === "ml") return Object.fromEntries((spec.inputs || []).map((p: any) => [p.name, ""]));
if (cat === "calendar") return { ref: "current" }; if (cat === "calendar") return { ref: "current" };
if (cat === "ai") return Object.fromEntries((spec.inputs || []).map((p: any) => [p.name, ""])); if (cat === "ai") return Object.fromEntries((spec.inputs || []).map((p: any) => [p.name, ""]));
return {}; return {};
...@@ -513,7 +559,7 @@ export function TryPanel({ concept, kind, spec, name }: { concept?: Concept; kin ...@@ -513,7 +559,7 @@ export function TryPanel({ concept, kind, spec, name }: { concept?: Concept; kin
const clean = Object.fromEntries(Object.entries(vals).filter(([, v]) => v !== "").map(([k, v]) => [k, num(v)])); const clean = Object.fromEntries(Object.entries(vals).filter(([, v]) => v !== "").map(([k, v]) => [k, num(v)]));
let args: any = clean; let args: any = clean;
if (cat === "rule") args = { vars: clean }; if (cat === "rule") args = { vars: clean };
if (cat === "decision") args = { inputs: clean }; if (cat === "decision" || cat === "ml") args = { inputs: clean };
if (cat === "ai") args = { inputs: vals }; if (cat === "ai") args = { inputs: vals };
if (cat === "aggregate") args = { dimensions: aggArgs.dimensions, time: aggArgs.time || undefined, object_key: objKey || undefined }; if (cat === "aggregate") args = { dimensions: aggArgs.dimensions, time: aggArgs.time || undefined, object_key: objKey || undefined };
const needSaved = cat === "aggregate" || cat === "ai"; const needSaved = cat === "aggregate" || cat === "ai";
...@@ -584,3 +630,50 @@ function LineageView({ data }: { data: { nodes: any[]; edges: any[] } }) { ...@@ -584,3 +630,50 @@ function LineageView({ data }: { data: { nodes: any[]; edges: any[] } }) {
</div> </div>
); );
} }
/**
* 「新建对象」的参数:选对象类型,再按它的属性逐行填值(值可以是 $参数、$obj.属性、=表达式),
* 而不是让业务人员手写一段 JSON。
*/
function CreateObjectArgs({ objects, value, onChange, disabled }: {
objects: { id: string; name: string }[]; value: Record<string, any>;
onChange: (v: Record<string, any>) => void; disabled?: boolean;
}) {
const ref = String(value.object_type || "");
const ot = objects.find((o) => o.id === ref || o.name === ref);
const [props, setProps] = useState<{ name: string; display_name?: string; is_key?: boolean }[]>([]);
useEffect(() => {
if (!ot) { setProps([]); return; }
void onto.concept(ot.id).then((c) => setProps(((c.spec as any)?.properties || []) as any[])).catch(() => setProps([]));
}, [ot?.id]); // eslint-disable-line react-hooks/exhaustive-deps
const vals: Record<string, any> = value.values || {};
const setVal = (k: string, v: string) => {
const next = { ...vals };
if (v === "") delete next[k]; else next[k] = v;
onChange({ ...value, values: next });
};
return (
<div className="space-y-2">
<label className="flex items-center gap-2 text-[12px]"><span className="w-16 text-muted">新建</span>
<select className="input h-8 w-48" value={ot?.name || ref} disabled={disabled}
onChange={(e) => onChange({ object_type: e.target.value, values: {} })}>
<option value="">选对象类型</option>
{objects.map((o) => <option key={o.id} value={o.name}>{o.name}</option>)}
</select>
</label>
{props.length > 0 && (
<div className="grid gap-1.5 sm:grid-cols-2">
{props.map((p) => (
<label key={p.name} className="flex items-center gap-2 text-[12px]">
<span className="w-28 shrink-0 truncate" title={p.name}>{p.display_name || p.name}{p.is_key && <span className="text-bad">*</span>}</span>
<input className="input h-8 flex-1 font-mono text-[12px]" disabled={disabled} value={vals[p.name] ?? ""}
placeholder={p.is_key ? "如 PO$now_id" : "留空不填"} onChange={(e) => setVal(p.name, e.target.value)} />
</label>
))}
</div>
)}
<p className="text-[11px] text-muted">值可以写固定值、$参数、$obj.属性、$today、$now_id,或以 = 开头的表达式(如 =qty * obj.unit_price)。</p>
</div>
);
}
import { Plus, Search, Sparkles, Wand2 } from "lucide-react"; import { LayoutGrid, Plus, Search, Sparkles, Table2, Wand2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { Badge, Card, Empty, Field, Modal, Spinner } from "@/components/ui"; import { Badge, Card, Empty, Field, Modal, Segmented, Spinner } from "@/components/ui";
import { go, useHashParams } from "@/lib/nav"; import { go, useHashParams } from "@/lib/nav";
import { import {
errText, fmtTime, KIND_COLOR, onto, STATUS_LABEL, STATUS_TONE, typeKey, errText, fmtTime, KIND_COLOR, onto, STATUS_LABEL, STATUS_TONE, typeKey,
...@@ -17,7 +17,7 @@ const TITLE: Record<ConceptKind, { title: string; desc: string; empty: string }> ...@@ -17,7 +17,7 @@ const TITLE: Record<ConceptKind, { title: string; desc: string; empty: string }>
object_type: { title: "对象类型", desc: "业务里可被指认、有属性的实体。绑定到表后,问答能认出具体对象,动作能写回属性。", object_type: { title: "对象类型", desc: "业务里可被指认、有属性的实体。绑定到表后,问答能认出具体对象,动作能写回属性。",
empty: "从数据源让 AI 提议(表 → 对象),或手动新建。" }, empty: "从数据源让 AI 提议(表 → 对象),或手动新建。" },
link_type: { title: "关系类型", desc: "两个对象之间的关系。绑定关联列后,对象 360 能看到关联对象。", empty: "在画布上从一个对象拖到另一个对象即可建关系。" }, link_type: { title: "关系类型", desc: "两个对象之间的关系。绑定关联列后,对象 360 能看到关联对象。", empty: "在画布上从一个对象拖到另一个对象即可建关系。" },
function: { title: "函数类型", desc: "对对象的计算。五类函数各走自己的确定性引擎:聚合编译 SQL、规则安全求值、决策表查表、周期解析;AI 分析只读、仅供参考。", function: { title: "函数类型", desc: "对对象的计算。各类函数走自己的确定性引擎:聚合编译 SQL、规则安全求值、决策表查表、周期解析、模型推理调端点;AI 分析只读、仅供参考,不作为权威结果。",
empty: "试试「一句话生成」:描述你想算什么,AI 起草、系统校验、当场试跑。" }, empty: "试试「一句话生成」:描述你想算什么,AI 起草、系统校验、当场试跑。" },
action: { title: "动作类型", desc: "改变业务状态的操作。只能调用系统效果,执行前一律人工审批,全程审计。", empty: "试试「一句话生成」:描述要做什么,AI 起草参数、前置条件与效果。" }, action: { title: "动作类型", desc: "改变业务状态的操作。只能调用系统效果,执行前一律人工审批,全程审计。", empty: "试试「一句话生成」:描述要做什么,AI 起草参数、前置条件与效果。" },
}; };
...@@ -34,6 +34,9 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -34,6 +34,9 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
const [cat, setCat] = useState<string>(""); const [cat, setCat] = useState<string>("");
const [obj, setObj] = useState(""); const [obj, setObj] = useState("");
const [status, setStatus] = useState(""); const [status, setStatus] = useState("");
const [domain, setDomain] = useState("");
const [mapped, setMapped] = useState("");
const [view, setView] = useState<"table" | "cards">(kind === "object_type" ? "cards" : "table");
const [sel, setSel] = useState(params.get("id") || ""); const [sel, setSel] = useState(params.get("id") || "");
const [modal, setModal] = useState<"" | "new" | "draft">(""); const [modal, setModal] = useState<"" | "new" | "draft">("");
...@@ -45,11 +48,18 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -45,11 +48,18 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
useEffect(() => { setSel(params.get("id") || ""); }, [params]); useEffect(() => { setSel(params.get("id") || ""); }, [params]);
const objName = useMemo(() => Object.fromEntries(all.filter((c) => c.kind === "object_type").map((c) => [c.id, c.name])), [all]); const objName = useMemo(() => Object.fromEntries(all.filter((c) => c.kind === "object_type").map((c) => [c.id, c.name])), [all]);
const items = useMemo(() => all.filter((c) => c.kind === kind const mine = useMemo(() => all.filter((c) => c.kind === kind), [all, kind]);
&& (!cat || c.category === cat) const domains = useMemo(() => [...new Set(mine.map((c) => c.domain || "").filter(Boolean))].sort(), [mine]);
const mappable = mine.some((c) => c.mapped !== null && c.mapped !== undefined);
const items = useMemo(() => mine.filter((c) => (!cat || c.category === cat)
&& (!domain || (domain === "-" ? !c.domain : c.domain === domain))
&& (!mapped || (mapped === "yes" ? c.mapped === true : c.mapped === false))
&& (!obj || c.object_type === obj || objName[c.object_type] === objName[obj]) && (!obj || c.object_type === obj || objName[c.object_type] === objName[obj])
&& (!status || (status === "dirty" ? c.dirty && c.published : c.status === status)) && (!status || (status === "dirty" ? c.dirty && c.published : c.status === status))
&& (!q || [c.name, c.display_name, c.description, ...c.synonyms].some((s) => s?.includes(q)))), [all, kind, cat, obj, status, q, objName]); && (!q || [c.name, c.display_name, c.description, ...c.synonyms].some((s) => s?.includes(q)))),
[mine, cat, domain, mapped, obj, status, q, objName]);
const mappedCount = mine.filter((c) => c.mapped === true).length;
const unmappedCount = mine.filter((c) => c.mapped === false).length;
const open = (id: string) => go(pageOfKind(kind), { id }); const open = (id: string) => go(pageOfKind(kind), { id });
const info = TITLE[kind]; const info = TITLE[kind];
...@@ -60,9 +70,16 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -60,9 +70,16 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
<Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.07), transparent 60%)" }}> <Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.07), transparent 60%)" }}>
<div className="flex flex-wrap items-center gap-3"> <div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-[16px] font-semibold">{info.title} · {items.length}/{all.filter((c) => c.kind === kind).length}</p> <p className="text-[16px] font-semibold">{info.title} · {items.length}/{mine.length}</p>
<p className="mt-0.5 max-w-3xl text-[12px] text-muted">{info.desc}</p> <p className="mt-0.5 max-w-3xl text-[12px] text-muted">{info.desc}</p>
</div> </div>
{mappable && (
<div className="flex gap-4 text-[12px]">
<button onClick={() => setMapped("")}><b className="text-[18px] tabular-nums">{mine.length}</b> 全部</button>
<button onClick={() => setMapped("yes")} className="text-ok"><b className="text-[18px] tabular-nums">{mappedCount}</b> 已映射</button>
<button onClick={() => setMapped("no")} className={unmappedCount ? "text-warn" : "text-muted"}><b className="text-[18px] tabular-nums">{unmappedCount}</b> 未映射</button>
</div>
)}
{canEdit && (kind === "function" || kind === "action") && ( {canEdit && (kind === "function" || kind === "action") && (
<button className="btn btn-primary btn-sm" onClick={() => setModal("draft")}><Wand2 className="h-3.5 w-3.5" />一句话生成</button> <button className="btn btn-primary btn-sm" onClick={() => setModal("draft")}><Wand2 className="h-3.5 w-3.5" />一句话生成</button>
)} )}
...@@ -85,15 +102,33 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -85,15 +102,33 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
{all.filter((c) => c.kind === "object_type").map((c) => <option key={c.id} value={c.id}>{c.name}</option>)} {all.filter((c) => c.kind === "object_type").map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
</select> </select>
)} )}
{domains.length > 0 && (
<select className="input h-8 w-32" value={domain} onChange={(e) => setDomain(e.target.value)}>
<option value="">全部域</option>
{domains.map((d) => <option key={d} value={d}>{d}</option>)}
<option value="-">未分域</option>
</select>
)}
{mappable && (
<select className="input h-8 w-28" value={mapped} onChange={(e) => setMapped(e.target.value)}>
<option value="">映射:全部</option><option value="yes">已映射</option><option value="no">未映射</option>
</select>
)}
<select className="input h-8 w-32" value={status} onChange={(e) => setStatus(e.target.value)}> <select className="input h-8 w-32" value={status} onChange={(e) => setStatus(e.target.value)}>
<option value="">全部状态</option><option value="draft">草稿</option><option value="published">已发布</option> <option value="">全部状态</option><option value="draft">草稿</option><option value="published">已发布</option>
<option value="dirty">有未发布修改</option> <option value="dirty">有未发布修改</option>
</select> </select>
{kind === "object_type" && (
<Segmented className="ml-auto" value={view} onChange={setView} options={[
{ key: "cards", label: <><LayoutGrid className="h-3.5 w-3.5" />卡片</> },
{ key: "table", label: <><Table2 className="h-3.5 w-3.5" />表格</> }]} />
)}
</div> </div>
</Card> </Card>
<Card className="min-h-0 flex-1 overflow-auto"> <Card className="min-h-0 flex-1 overflow-auto">
{!items.length ? <Empty icon={<Sparkles className="h-10 w-10" />} title={`还没有${info.title}`} desc={info.empty} /> : ( {!items.length ? <Empty icon={<Sparkles className="h-10 w-10" />} title={`还没有${info.title}`} desc={info.empty} />
: view === "cards" ? <ObjectCards items={items} sel={sel} onOpen={open} /> : (
<table className="w-full text-[12.5px]"> <table className="w-full text-[12.5px]">
<thead className="sticky top-0 z-10 bg-surface text-[11.5px] text-muted"> <thead className="sticky top-0 z-10 bg-surface text-[11.5px] text-muted">
<tr className="border-b border-line"> <tr className="border-b border-line">
...@@ -101,9 +136,11 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -101,9 +136,11 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
{kind === "function" && <th className="px-2 text-left">类别</th>} {kind === "function" && <th className="px-2 text-left">类别</th>}
{(kind === "function" || kind === "action") && <th className="px-2 text-left">作用对象</th>} {(kind === "function" || kind === "action") && <th className="px-2 text-left">作用对象</th>}
{kind === "link_type" && <th className="px-2 text-left">起点 → 终点</th>} {kind === "link_type" && <th className="px-2 text-left">起点 → 终点</th>}
<th className="px-2 text-left">域</th>
{mappable && <th className="px-2 text-left">映射</th>}
<th className="px-2 text-left">状态</th> <th className="px-2 text-left">状态</th>
<th className="px-2 text-left">描述</th> {!sel && <th className="px-2 text-left">描述</th>}
<th className="px-2 text-left">更新</th> {!sel && <th className="px-2 text-left">更新</th>}
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
...@@ -113,19 +150,22 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -113,19 +150,22 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
<td className="px-3 py-2"> <td className="px-3 py-2">
<p className="flex items-center gap-1.5 font-medium"> <p className="flex items-center gap-1.5 font-medium">
<i className="h-2 w-2 shrink-0 rounded-full" style={{ background: KIND_COLOR[typeKey(c)] }} /> <i className="h-2 w-2 shrink-0 rounded-full" style={{ background: KIND_COLOR[typeKey(c)] }} />
<span className="font-mono text-[12px]">{c.display_name || c.name}</span> <span className="whitespace-nowrap font-mono text-[12px]">{c.display_name || c.name}</span>
</p> </p>
{c.synonyms.length > 0 && <p className="truncate pl-3.5 text-[11px] text-muted">{c.synonyms.slice(0, 4).join("、")}</p>} {c.synonyms.length > 0 && <p className="truncate pl-3.5 text-[11px] text-muted">{c.synonyms.slice(0, 4).join("、")}</p>}
</td> </td>
{kind === "function" && <td className="px-2"><TypeBadge t={typeKey(c)} /></td>} {kind === "function" && <td className="px-2"><TypeBadge t={typeKey(c)} /></td>}
{(kind === "function" || kind === "action") && <td className="px-2 text-muted">{objName[c.object_type] || c.object_type || "-"}</td>} {(kind === "function" || kind === "action") && <td className="px-2 text-muted">{objName[c.object_type] || c.object_type || "-"}</td>}
{kind === "link_type" && <td className="px-2 text-muted"><LinkEnds c={c} objName={objName} /></td>} {kind === "link_type" && <td className="px-2 text-muted"><LinkEnds c={c} objName={objName} /></td>}
<td className="px-2">{c.domain ? <Badge>{c.domain}</Badge> : <span className="text-muted">-</span>}</td>
{mappable && <td className="px-2"><MappedBadge v={c.mapped} /></td>}
<td className="px-2"> <td className="px-2">
<Badge tone={STATUS_TONE[c.status]}>{STATUS_LABEL[c.status]}</Badge> <Badge tone={STATUS_TONE[c.status]}>{STATUS_LABEL[c.status]}</Badge>
{c.dirty && c.published && <Badge tone="bg-warn/10 text-warn" className="ml-1">改</Badge>} {c.dirty && c.published && <Badge tone="bg-warn/10 text-warn" className="ml-1">改</Badge>}
</td> </td>
<td className="max-w-[420px] truncate px-2 text-muted">{c.description || "-"}</td> {/* 右侧打开编辑器时收起描述和时间列,否则名称会被挤成一字一行 */}
<td className="whitespace-nowrap px-2 text-[11px] text-muted">{fmtTime(c.updated_at)}</td> {!sel && <td className="max-w-[420px] truncate px-2 text-muted">{c.description || "-"}</td>}
{!sel && <td className="whitespace-nowrap px-2 text-[11px] text-muted">{fmtTime(c.updated_at)}</td>}
</tr> </tr>
))} ))}
</tbody> </tbody>
...@@ -149,6 +189,48 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -149,6 +189,48 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
); );
} }
function MappedBadge({ v }: { v?: boolean | null }) {
if (v === null || v === undefined) return <span className="text-muted">-</span>;
return v ? <Badge tone="bg-ok/10 text-ok">已映射</Badge> : <Badge tone="bg-warn/10 text-warn">未映射</Badge>;
}
/** 对象类型卡片:按域分组,一眼看出哪些对象还没落到数据。 */
function ObjectCards({ items, sel, onOpen }: { items: ConceptBrief[]; sel: string; onOpen: (id: string) => void }) {
const groups = useMemo(() => {
const m = new Map<string, ConceptBrief[]>();
items.forEach((c) => { const k = c.domain || "未分域"; m.set(k, [...(m.get(k) || []), c]); });
return [...m.entries()].sort((a, b) => (a[0] === "未分域" ? 1 : b[0] === "未分域" ? -1 : a[0].localeCompare(b[0])));
}, [items]);
return (
<div className="space-y-4 p-4">
{groups.map(([g, xs]) => (
<div key={g}>
<p className="mb-2 text-[12px] font-semibold text-muted">{g} <span className="font-normal">{xs.length}</span></p>
<div className="grid gap-2.5 sm:grid-cols-2 xl:grid-cols-4">
{xs.map((c) => (
<button key={c.id} onClick={() => onOpen(c.id)}
className={cn("rounded-xl border border-line bg-surface p-3 text-left transition-colors hover:border-brand/40",
sel === c.id && "border-brand bg-brand/5")}
style={{ borderTop: `3px solid ${KIND_COLOR.object_type}` }}>
<div className="flex items-center gap-1.5">
<span className="truncate font-mono text-[13px] font-semibold">{c.display_name || c.name}</span>
<span className="ml-auto"><MappedBadge v={c.mapped} /></span>
</div>
<p className="mt-1 line-clamp-2 min-h-[2.2em] text-[11.5px] text-muted">{c.description || c.synonyms.join("、") || "(无描述)"}</p>
<div className="mt-2 flex items-center gap-1.5 text-[11px]">
<Badge tone={STATUS_TONE[c.status]}>{STATUS_LABEL[c.status]}</Badge>
{c.dirty && c.published && <Badge tone="bg-warn/10 text-warn">改</Badge>}
<span className="ml-auto text-muted">{fmtTime(c.updated_at)}</span>
</div>
</button>
))}
</div>
</div>
))}
</div>
);
}
function LinkEnds({ c, objName }: { c: ConceptBrief; objName: Record<string, string> }) { function LinkEnds({ c, objName }: { c: ConceptBrief; objName: Record<string, string> }) {
const [spec, setSpec] = useState<any>(null); const [spec, setSpec] = useState<any>(null);
useEffect(() => { void onto.concept(c.id).then((x) => setSpec(x.spec)).catch(() => undefined); }, [c.id, c.updated_at]); useEffect(() => { void onto.concept(c.id).then((x) => setSpec(x.spec)).catch(() => undefined); }, [c.id, c.updated_at]);
...@@ -168,12 +250,15 @@ export function NewBlockModal({ kind, meta, objects, onClose, onCreated, initial ...@@ -168,12 +250,15 @@ export function NewBlockModal({ kind, meta, objects, onClose, onCreated, initial
const [desc, setDesc] = useState(""); const [desc, setDesc] = useState("");
const [cat, setCat] = useState<FnCategory>(initialCategory || "rule"); const [cat, setCat] = useState<FnCategory>(initialCategory || "rule");
const [obj, setObj] = useState(""); const [obj, setObj] = useState("");
const [domain, setDomain] = useState("");
const create = async () => { const create = async () => {
try { try {
const spec: any = kind === "function" ? { category: cat, object_type: obj, const spec: any = kind === "function" ? { category: cat, object_type: obj,
...(cat === "decision" ? { inputs: [{ name: "x", label: "输入" }], outputs: [{ name: "result", label: "结果" }], rows: [] } : {}), ...(cat === "decision" ? { inputs: [{ name: "x", label: "输入" }], outputs: [{ name: "result", label: "结果" }], rows: [] } : {}),
...(cat === "ml" ? { endpoint: "", inputs: [{ name: "x", label: "输入" }], outputs: [{ name: "y", label: "预测值" }] } : {}),
...(cat === "ai" ? { instructions: desc || "请分析", functions: ["data.ask", "knowledge.search"] } : {}) } ...(cat === "ai" ? { instructions: desc || "请分析", functions: ["data.ask", "knowledge.search"] } : {}) }
: kind === "action" ? { ...EMPTY_ACTION, target_type: obj } : {}; : kind === "action" ? { ...EMPTY_ACTION, target_type: obj } : {};
if (domain.trim()) spec.domain = domain.trim();
const c = await onto.createConcept({ kind, name, description: desc, spec }); const c = await onto.createConcept({ kind, name, description: desc, spec });
onCreated(c.id); onCreated(c.id);
} catch (e) { toast("error", "创建失败", errText(e)); } } catch (e) { toast("error", "创建失败", errText(e)); }
...@@ -206,6 +291,7 @@ export function NewBlockModal({ kind, meta, objects, onClose, onCreated, initial ...@@ -206,6 +291,7 @@ export function NewBlockModal({ kind, meta, objects, onClose, onCreated, initial
</select> </select>
</Field> </Field>
)} )}
<Field label="域" hint="业务分组,如 财务 / 质量 / 订单 / 设备;只用于浏览分组"><input className="input" value={domain} onChange={(e) => setDomain(e.target.value)} /></Field>
<Field label="定义 / 说明"><textarea className="input" value={desc} onChange={(e) => setDesc(e.target.value)} /></Field> <Field label="定义 / 说明"><textarea className="input" value={desc} onChange={(e) => setDesc(e.target.value)} /></Field>
</div> </div>
</Modal> </Modal>
......
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
import "@xyflow/react/dist/style.css"; import "@xyflow/react/dist/style.css";
import { KeyRound, LayoutGrid, Pencil, Plus, RefreshCw } from "lucide-react"; import { KeyRound, LayoutGrid, Pencil, Plus, RefreshCw } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Badge, Card, Empty, Spinner } from "@/components/ui"; import { Badge, Card, Empty, Segmented, Spinner } from "@/components/ui";
import { go, useHashParams } from "@/lib/nav"; import { go, useHashParams } from "@/lib/nav";
import { import {
errText, KIND_COLOR, onto, TYPE_LABEL, type ConceptBrief, type GraphEdge, type GraphNode, type KernelMeta, type Me, errText, KIND_COLOR, onto, TYPE_LABEL, type ConceptBrief, type GraphEdge, type GraphNode, type KernelMeta, type Me,
...@@ -68,7 +68,23 @@ function SatelliteNode({ data }: NodeProps<Node<SatData>>) { ...@@ -68,7 +68,23 @@ function SatelliteNode({ data }: NodeProps<Node<SatData>>) {
); );
} }
const nodeTypes = { object: ObjectNode, sat: SatelliteNode }; /** 图谱视图:对象画成圆点(大小随关联数),适合看整张关系网,而不是逐个看属性。 */
function DotNode({ data }: NodeProps<Node<ObjData & { degree: number }>>) {
const g = data.g;
const size = Math.min(96, 44 + (data.degree || 0) * 6);
return (
<div className={cn("grid place-items-center rounded-full border-2 bg-surface text-center shadow-sm", data.selected && "ring-2 ring-brand/40",
!g.bound && "border-dashed")}
style={{ width: size, height: size, borderColor: KIND_COLOR.object_type, background: "#6366f114" }} title={g.description}>
<Handle type="target" position={Position.Left} className="!opacity-0" />
<span className="px-1 text-[11px] font-semibold leading-tight">{g.name}</span>
<Handle type="source" position={Position.Right} className="!opacity-0" />
<Handle id="sat" type="source" position={Position.Bottom} className="!opacity-0" />
</div>
);
}
const nodeTypes = { object: ObjectNode, sat: SatelliteNode, dot: DotNode };
/** 没有保存过位置的对象:按网格摆;函数与动作围在所属对象下方;没有所属对象的放最右一列。 */ /** 没有保存过位置的对象:按网格摆;函数与动作围在所属对象下方;没有所属对象的放最右一列。 */
function layout(nodes: GraphNode[], showSat: boolean, force: boolean): Record<string, { x: number; y: number }> { function layout(nodes: GraphNode[], showSat: boolean, force: boolean): Record<string, { x: number; y: number }> {
...@@ -106,6 +122,8 @@ export function CanvasPage({ me }: { me: Me | null }) { ...@@ -106,6 +122,8 @@ export function CanvasPage({ me }: { me: Me | null }) {
const [all, setAll] = useState<ConceptBrief[]>([]); const [all, setAll] = useState<ConceptBrief[]>([]);
const [graph, setGraph] = useState<{ nodes: GraphNode[]; edges: GraphEdge[] } | null>(null); const [graph, setGraph] = useState<{ nodes: GraphNode[]; edges: GraphEdge[] } | null>(null);
const [showSat, setShowSat] = useState(true); const [showSat, setShowSat] = useState(true);
const [view, setView] = useState<"card" | "graph">("card");
const [mappedOnly, setMappedOnly] = useState(false);
const [sel, setSel] = useState(params.get("id") || ""); const [sel, setSel] = useState(params.get("id") || "");
const [modal, setModal] = useState<"" | "object" | "function" | "action" | "draft">(""); const [modal, setModal] = useState<"" | "object" | "function" | "action" | "draft">("");
const [nodes, setNodes, onNodesChange] = useNodesState<Node>([]); const [nodes, setNodes, onNodesChange] = useNodesState<Node>([]);
...@@ -121,11 +139,16 @@ export function CanvasPage({ me }: { me: Me | null }) { ...@@ -121,11 +139,16 @@ export function CanvasPage({ me }: { me: Me | null }) {
const build = useCallback((force = false) => { const build = useCallback((force = false) => {
if (!graph) return; if (!graph) return;
const pos = layout(graph.nodes, showSat, force); const objIds = new Set(graph.nodes.filter((n) => n.kind === "object_type" && (!mappedOnly || n.bound)).map((n) => n.id));
const shown = graph.nodes.filter((n) => showSat || n.kind === "object_type"); const pool = graph.nodes.filter((n) => n.kind === "object_type" ? objIds.has(n.id) : !mappedOnly || (n.owner && objIds.has(n.owner)));
const sat = showSat && view === "card";
const pos = layout(pool, sat, force);
const shown = pool.filter((n) => sat || n.kind === "object_type");
const degree: Record<string, number> = {};
graph.edges.forEach((e) => { if (e.kind === "link") { degree[e.source] = (degree[e.source] || 0) + 1; degree[e.target] = (degree[e.target] || 0) + 1; } });
setNodes(shown.map((g) => ({ setNodes(shown.map((g) => ({
id: g.id, type: g.kind === "object_type" ? "object" : "sat", position: pos[g.id] || { x: 0, y: 0 }, id: g.id, type: g.kind === "object_type" ? (view === "graph" ? "dot" : "object") : "sat", position: pos[g.id] || { x: 0, y: 0 },
data: { g, selected: g.id === sel }, data: { g, selected: g.id === sel, degree: degree[g.id] || 0 },
}))); })));
const ids = new Set(shown.map((n) => n.id)); const ids = new Set(shown.map((n) => n.id));
setEdges(graph.edges.filter((e) => ids.has(e.source) && ids.has(e.target)).map((e) => e.kind === "link" ? { setEdges(graph.edges.filter((e) => ids.has(e.source) && ids.has(e.target)).map((e) => e.kind === "link" ? {
...@@ -140,7 +163,7 @@ export function CanvasPage({ me }: { me: Me | null }) { ...@@ -140,7 +163,7 @@ export function CanvasPage({ me }: { me: Me | null }) {
if (force && canEdit) { if (force && canEdit) {
void onto.saveLayout(Object.fromEntries(shown.map((g) => [g.id, pos[g.id]]))).catch(() => undefined); void onto.saveLayout(Object.fromEntries(shown.map((g) => [g.id, pos[g.id]]))).catch(() => undefined);
} }
}, [graph, showSat, sel, setNodes, setEdges, canEdit]); }, [graph, showSat, sel, setNodes, setEdges, canEdit, view, mappedOnly]);
useEffect(() => build(false), [build]); useEffect(() => build(false), [build]);
const onConnect = useCallback(async (c: Connection) => { const onConnect = useCallback(async (c: Connection) => {
...@@ -168,25 +191,27 @@ export function CanvasPage({ me }: { me: Me | null }) { ...@@ -168,25 +191,27 @@ export function CanvasPage({ me }: { me: Me | null }) {
<Card className="relative min-w-0 flex-1 overflow-hidden"> <Card className="relative min-w-0 flex-1 overflow-hidden">
<div className="absolute left-3 top-3 z-10 flex flex-wrap items-center gap-1.5 rounded-lg border border-line bg-surface/95 p-1.5 shadow-sm"> <div className="absolute left-3 top-3 z-10 flex flex-wrap items-center gap-1.5 rounded-lg border border-line bg-surface/95 p-1.5 shadow-sm">
<span className="px-1 text-[12px] font-semibold">本体画布</span> <span className="px-1 text-[12px] font-semibold">本体画布</span>
{(["object_type", "link_type", "aggregate", "rule", "decision", "calendar", "ai", "action"] as const).map((k) => ( <Segmented value={view} onChange={setView} options={[{ key: "card", label: "卡片视图" }, { key: "graph", label: "图谱视图" }]} />
{(["object_type", "link_type", "aggregate", "rule", "decision", "calendar", "ml", "ai", "action"] as const).map((k) => (
<span key={k} className="flex items-center gap-1 text-[11px] text-muted"> <span key={k} className="flex items-center gap-1 text-[11px] text-muted">
<i className="h-2 w-2 rounded-full" style={{ background: KIND_COLOR[k] }} />{TYPE_LABEL[k]} {counts[k] || 0} <i className="h-2 w-2 rounded-full" style={{ background: KIND_COLOR[k] }} />{TYPE_LABEL[k]} {counts[k] || 0}
</span> </span>
))} ))}
<label className="ml-1 flex items-center gap-1 text-[11.5px]"><input type="checkbox" checked={showSat} onChange={(e) => setShowSat(e.target.checked)} />函数与动作</label> {view === "card" && <label className="ml-1 flex items-center gap-1 text-[11.5px]"><input type="checkbox" checked={showSat} onChange={(e) => setShowSat(e.target.checked)} />函数与动作</label>}
<label className="ml-1 flex items-center gap-1 text-[11.5px]" title="只看已绑定数据表的对象"><input type="checkbox" checked={mappedOnly} onChange={(e) => setMappedOnly(e.target.checked)} />仅已映射</label>
</div> </div>
<div className="absolute right-3 top-3 z-10 flex gap-1.5"> <div className="absolute right-3 top-3 z-10 flex gap-1.5">
{canEdit && <> {canEdit && <>
<button className="btn btn-sm" onClick={() => setModal("object")}><Plus className="h-3.5 w-3.5" />对象</button> <button className="btn btn-sm" onClick={() => setModal("object")}><Plus className="h-3.5 w-3.5" />对象</button>
<button className="btn btn-sm" onClick={() => setModal("draft")}><Plus className="h-3.5 w-3.5" />一句话生成函数</button> <button className="btn btn-sm" onClick={() => setModal("draft")}><Plus className="h-3.5 w-3.5" />一句话生成函数</button>
<button className="btn btn-sm" title="重新自动布局" onClick={() => build(true)}><LayoutGrid className="h-3.5 w-3.5" /></button> <button className="btn btn-sm" title="按网格重新排布并保存位置(清空之前手动拖动的布局)" onClick={() => build(true)}><LayoutGrid className="h-3.5 w-3.5" />自动布局</button>
</>} </>}
<button className="btn btn-sm" title="刷新" onClick={load}><RefreshCw className="h-3.5 w-3.5" /></button> <button className="btn btn-sm" title="刷新" onClick={load}><RefreshCw className="h-3.5 w-3.5" /></button>
</div> </div>
{!graph.nodes.length ? ( {!graph.nodes.length ? (
<div className="flex h-full items-center justify-center"> <div className="flex h-full items-center justify-center">
<Empty title="画布还是空的" desc="先去「业务建模」让 AI 从文档和数据库生成对象、关系、函数、动作的草案,或在这里手动添加对象。" <Empty title="画布还是空的" desc="先去「业务建模」让 AI 从文档和数据库生成对象、关系、函数、动作的草案,或在这里手动添加对象。"
action={<button className="btn btn-primary btn-sm" onClick={() => go("wizard")}>去业务建模</button>} /> action={<button className="btn btn-primary btn-sm" onClick={() => go("modeling")}>去业务建模</button>} />
</div> </div>
) : ( ) : (
<ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} <ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange}
...@@ -208,7 +233,7 @@ export function CanvasPage({ me }: { me: Me | null }) { ...@@ -208,7 +233,7 @@ export function CanvasPage({ me }: { me: Me | null }) {
</ReactFlow> </ReactFlow>
)} )}
<p className="absolute bottom-2 left-1/2 z-10 -translate-x-1/2 rounded bg-surface/90 px-2 py-0.5 text-[11px] text-muted"> <p className="absolute bottom-2 left-1/2 z-10 -translate-x-1/2 rounded bg-surface/90 px-2 py-0.5 text-[11px] text-muted">
拖动调整位置(自动保存,不算修改)· 从对象右侧圆点拖到另一个对象即新建关系 · 虚线 = 草稿 拖动调整位置(自动保存,不算修改)· 从对象右侧圆点拖到另一个对象即新建关系 · 虚线 = 草稿 / 未映射
</p> </p>
</Card> </Card>
{sel && ( {sel && (
......
...@@ -9,7 +9,8 @@ import { ResultView, SchemaForm } from "./common"; ...@@ -9,7 +9,8 @@ import { ResultView, SchemaForm } from "./common";
/** /**
* MCP 服务:已发布的本体以 MCP 工具暴露给外部 Agent。 * MCP 服务:已发布的本体以 MCP 工具暴露给外部 Agent。
* 这里能看工具目录与参数、以当前身份在线调用、看最近的调用日志(每次调用都进审计)。 * 这里能看工具目录与参数、以当前身份在线调用、看最近的调用日志(每次调用都进审计)。
* 外部 Agent 只能「提议」动作,审批仍然由人在「行动审批」里做。 * 系统自带的「提问」也是这份目录的一个客户端(调用日志里 via=提问)。
* 外部 Agent 只能「提议」动作,目录里没有审批工具,审批仍然由人在「行动审批」里做。
*/ */
export function McpPage() { export function McpPage() {
const [info, setInfo] = useState<{ enabled: boolean; endpoint: string; protocol: string; tools: McpTool[] } | null>(null); const [info, setInfo] = useState<{ enabled: boolean; endpoint: string; protocol: string; tools: McpTool[] } | null>(null);
...@@ -56,12 +57,17 @@ export function McpPage() { ...@@ -56,12 +57,17 @@ export function McpPage() {
<input className="input h-8 pl-7" placeholder="搜索工具" value={q} onChange={(e) => setQ(e.target.value)} /> <input className="input h-8 pl-7" placeholder="搜索工具" value={q} onChange={(e) => setQ(e.target.value)} />
</div> </div>
<div className="min-h-0 flex-1 overflow-auto"> <div className="min-h-0 flex-1 overflow-auto">
{tools.map((t) => ( {tools.map((t, i) => (
<button key={t.name} onClick={() => { setSel(t.name); setArgs({}); setOut(null); }} <div key={t.name}>
{(i === 0 || tools[i - 1].annotations?.group !== t.annotations?.group) && (
<p className="bg-ink/[0.03] px-3 py-1 text-[11px] font-medium text-muted">{t.annotations?.group || "其他"}</p>
)}
<button onClick={() => { setSel(t.name); setArgs({}); setOut(null); }}
className={cn("block w-full border-b border-line/60 px-3 py-2 text-left hover:bg-ink/[0.03]", sel === t.name && "bg-brand/5")}> className={cn("block w-full border-b border-line/60 px-3 py-2 text-left hover:bg-ink/[0.03]", sel === t.name && "bg-brand/5")}>
<p className="font-mono text-[12.5px] font-medium">{t.name}</p> <p className="font-mono text-[12.5px] font-medium">{t.name}</p>
<p className="line-clamp-2 text-[11.5px] text-muted">{t.description}</p> <p className="line-clamp-2 text-[11.5px] text-muted">{t.description}</p>
</button> </button>
</div>
))} ))}
</div> </div>
</Card> </Card>
......
import {
ArrowRight, CheckCircle2, Circle, Database, Download, FileText, FileUp, GitBranch, Layers, ListChecks,
Loader2, Play, Plus, Rocket, Route, Sparkles, Trash2, Wand2, XCircle,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Badge, Card, CardHeader, Empty, Field, Spinner, Stat } from "@/components/ui";
import { api } from "@/lib/api";
import { confirmDialog } from "@/lib/dialog";
import { go, useHashParams } from "@/lib/nav";
import {
errText, fmtTime, KIND_COLOR, onto, STATUS_LABEL, STATUS_TONE,
type Me, type ModelRunFull, type ModelRunRec, type ModelStage, type ReviewItem,
} from "@/lib/onto";
import type { DataSource, DocumentItem } from "@/lib/types";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { TypeBadge } from "./common";
import { ImportExport } from "./tools";
const STAGE_ICON: Record<string, React.ReactNode> = {
route: <Route className="h-4 w-4" />, convert: <Sparkles className="h-4 w-4" />, deepen: <Layers className="h-4 w-4" />,
sop: <ListChecks className="h-4 w-4" />, draft: <GitBranch className="h-4 w-4" />,
};
const COLS: { key: "object_type" | "link_type" | "function" | "action"; label: string }[] = [
{ key: "object_type", label: "对象" }, { key: "link_type", label: "关系" },
{ key: "function", label: "函数" }, { key: "action", label: "动作" },
];
/**
* 业务建模:一张经业务专家梳理过的业务文档(BRD / 业务逻辑图)拉进来,
* 管道自动走完「行业路由 → LLM 转换 → 规则深化 → SOP 编排 → 建草稿」,得到四元组草案与流程卡草稿。
* 人只需审核、微调;采纳后是草稿,再经变更提案审批发布。
*/
export function ModelingPage({ me }: { me: Me | null }) {
const params = useHashParams();
const run = params.get("run");
if (params.get("new")) return <NewRun me={me} />;
if (run) return <RunDetail id={run} me={me} />;
return <RunList me={me} />;
}
function RunList({ me }: { me: Me | null }) {
const canEdit = !!me?.permissions.includes("build");
const [runs, setRuns] = useState<ModelRunRec[] | null>(null);
const [dss, setDss] = useState<DataSource[]>([]);
const [busy, setBusy] = useState("");
const [tpl, setTpl] = useState(false);
const load = useCallback(() => {
void onto.modelingRuns().then(setRuns).catch(() => setRuns([]));
void api.datasources().then(setDss).catch(() => setDss([]));
}, []);
useEffect(load, [load]);
const proposeDs = async (d: DataSource) => {
setBusy(`ds${d.id}`);
try {
const r = await onto.proposeFromDatasource(d.id);
toast("ok", `从「${d.name}」提议 ${r.proposed} 块积木`, "到「行动审批 → 审核队列」或建模记录里采纳");
} catch (e) { toast("error", "提议失败", errText(e)); } finally { setBusy(""); }
};
return (
<div className="mx-auto max-w-6xl space-y-4">
<Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.08), transparent 60%)" }}>
<div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1">
<p className="text-[16px] font-semibold">业务建模 · {runs?.length ?? 0} 次</p>
<p className="mt-0.5 max-w-3xl text-[12px] text-muted">建本体不是几个月的定制开发:把业务专家梳理过的文档拉进来,AI 起草对象、关系、函数、动作与流程卡,人审核微调即可。每次建模独立成画布,可回看全过程。</p>
</div>
{canEdit && <button className="btn btn-sm" onClick={() => setTpl(true)}><FileUp className="h-3.5 w-3.5" />模板 / 导入</button>}
{canEdit && <button className="btn btn-primary btn-sm" onClick={() => go("modeling", { new: 1 })}><Plus className="h-3.5 w-3.5" />新建画布</button>}
</div>
</Card>
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
{canEdit && (
<button className="card flex min-h-[132px] flex-col items-center justify-center gap-1.5 border-dashed text-muted hover:border-brand/50 hover:text-brand"
onClick={() => go("modeling", { new: 1 })}>
<Plus className="h-6 w-6" /><span className="text-[13px] font-medium">新建画布</span>
<span className="text-[11.5px]">从一次业务建模开始</span>
</button>
)}
{!runs ? <Spinner /> : runs.map((r) => (
<button key={r.id} className="card p-3 text-left hover:border-brand/40" onClick={() => go("modeling", { run: r.id })}>
<div className="flex items-center gap-2">
<FileText className="h-4 w-4 shrink-0 text-brand" />
<span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold">{r.title}</span>
<Badge tone={STATUS_TONE[r.status] || "bg-ink/5 text-muted"}>{r.status === "done" ? "已完成" : STATUS_LABEL[r.status] || r.status}</Badge>
</div>
<p className="mt-1 truncate text-[11.5px] text-muted">{[...r.inputs.files, ...r.inputs.doc_ids.map((d) => `文档 #${d}`)].join("、") || "-"}</p>
<div className="mt-3 grid grid-cols-5 gap-1 text-center">
{[...COLS.map((c) => [c.label, r.counts[c.key]] as const), ["流程卡", r.counts.sop] as const].map(([l, n]) => (
<div key={l}><p className="text-[16px] font-semibold tabular-nums">{n ?? "-"}</p><p className="text-[10.5px] text-muted">{l}</p></div>
))}
</div>
<p className="mt-2 text-[11px] text-muted">{fmtTime(r.created_at)} · {r.created_by}</p>
</button>
))}
</div>
<Card>
<CardHeader title={<span className="flex items-center gap-2"><Database className="h-4 w-4" />从数据库起步</span>}
desc="已启用的表 → 对象(带表绑定),表间关联 → 关系。确定性翻译,不花模型额度,结果进审核队列。" />
<div className="grid gap-2 p-4 sm:grid-cols-2">
{dss.map((d) => (
<div key={d.id} className="flex items-center gap-2 rounded-lg border border-line px-3 py-2">
<span className="min-w-0 flex-1 truncate text-[13px]">{d.name} <span className="text-[11px] text-muted">{d.ds_type} · {d.db_name}</span></span>
{canEdit && <button className="btn btn-sm" disabled={!!busy} onClick={() => void proposeDs(d)}>
{busy === `ds${d.id}` ? <Spinner className="h-3.5 w-3.5" /> : <Wand2 className="h-3.5 w-3.5" />}提议对象与关系</button>}
</div>
))}
{!dss.length && <Empty title="还没有接入数据" action={<button className="btn btn-sm" onClick={() => go("data")}>去接入</button>} />}
</div>
</Card>
{tpl && <ImportExport onClose={() => setTpl(false)} onDone={load} />}
</div>
);
}
/** 管道图:节点横向排开,状态实时着色。 */
function Pipeline({ stages, active, onToggle }: {
stages: { key: string; label: string; desc: string; status?: string; counts?: any }[];
active?: Set<string>; onToggle?: (k: string) => void;
}) {
const inputOn = true;
const tone = (st?: string, on = true) => !on ? "border-dashed border-line text-muted/60"
: st === "done" ? "border-ok/50 bg-ok/5" : st === "running" ? "border-brand bg-brand/5 ring-2 ring-brand/20"
: st === "failed" ? "border-bad/50 bg-bad/5" : st === "skipped" ? "border-dashed border-line text-muted/60" : "border-line bg-surface";
const icon = (st?: string) => st === "done" ? <CheckCircle2 className="h-3.5 w-3.5 text-ok" /> : st === "running"
? <Loader2 className="h-3.5 w-3.5 animate-spin text-brand" /> : st === "failed" ? <XCircle className="h-3.5 w-3.5 text-bad" />
: <Circle className="h-3.5 w-3.5 text-muted/50" />;
return (
<div className="flex items-stretch gap-1.5 overflow-x-auto pb-1">
<div className={cn("w-32 shrink-0 rounded-xl border p-2.5", tone(inputOn ? "done" : ""))}>
<p className="flex items-center gap-1.5 text-[12.5px] font-semibold"><FileText className="h-4 w-4 text-brand" />文档输入</p>
<p className="mt-1 text-[11px] text-muted">知识库文档 / 临时上传</p>
</div>
{stages.map((s) => {
const on = !active || active.has(s.key);
const fixed = s.key === "convert" || s.key === "draft";
return (
<div key={s.key} className="flex items-stretch gap-1.5">
<ArrowRight className="mt-6 h-4 w-4 shrink-0 text-muted" />
<button disabled={!onToggle || fixed} onClick={() => onToggle?.(s.key)} title={fixed ? "必需阶段" : onToggle ? "点击启用 / 跳过" : ""}
className={cn("w-36 shrink-0 rounded-xl border p-2.5 text-left", tone(s.status, on))}>
<p className="flex items-center gap-1.5 text-[12.5px] font-semibold"><span className="text-brand">{STAGE_ICON[s.key]}</span>{s.label}
<span className="ml-auto">{onToggle ? (on ? <CheckCircle2 className="h-3.5 w-3.5 text-brand" /> : <Circle className="h-3.5 w-3.5" />) : icon(s.status)}</span></p>
<p className="mt-1 line-clamp-2 text-[11px] text-muted">{s.desc}</p>
</button>
</div>
);
})}
</div>
);
}
function NewRun({ me }: { me: Me | null }) {
const canEdit = !!me?.permissions.includes("build");
const [meta, setMeta] = useState<{ stages: { key: string; label: string; desc: string }[]; templates: { id: string; name: string; description: string }[] } | null>(null);
const [docs, setDocs] = useState<DocumentItem[]>([]);
const [picked, setPicked] = useState<Set<number>>(new Set());
const [dss, setDss] = useState<DataSource[]>([]);
const [dsPicked, setDsPicked] = useState<Set<number>>(new Set());
const [files, setFiles] = useState<File[]>([]);
const [title, setTitle] = useState("");
const [template, setTemplate] = useState("");
const [active, setActive] = useState<Set<string>>(new Set());
const [busy, setBusy] = useState(false);
const input = useRef<HTMLInputElement>(null);
useEffect(() => {
void onto.modelingStages().then((m) => { setMeta(m); setActive(new Set(m.stages.map((s) => s.key))); });
void api.documents().then((d) => {
setDocs(d);
const ok = d.filter((x) => x.status === "done");
if (ok.length === 1) setPicked(new Set([ok[0].id])); // 只有一份文档就替用户勾上
}).catch(() => setDocs([]));
void api.datasources().then((d) => {
setDss(d);
setDsPicked(new Set(d.filter((x) => x.last_introspect_at).map((x) => x.id)));
}).catch(() => setDss([]));
}, []);
const ready = docs.filter((d) => d.status === "done");
const start = async () => {
const fd = new FormData();
fd.append("title", title || files[0]?.name || "业务建模");
fd.append("doc_ids", JSON.stringify([...picked]));
fd.append("template", template);
fd.append("stages", JSON.stringify([...active]));
fd.append("ds_ids", JSON.stringify([...dsPicked]));
files.forEach((f) => fd.append("files", f));
setBusy(true);
try {
const r = await onto.createModelingRun(fd);
toast("info", "开始建模", "可以离开这个页面,进度会一直保存");
go("modeling", { run: r.id });
} catch (e) { toast("error", "启动失败", errText(e)); } finally { setBusy(false); }
};
if (!meta) return <Spinner />;
return (
<div className="mx-auto max-w-6xl space-y-4">
<div className="flex items-center gap-2">
<button className="btn btn-ghost btn-sm" onClick={() => go("modeling")}>← 返回列表</button>
<span className="text-[14px] font-semibold">新建建模画布</span>
</div>
<Card className="p-4">
<p className="mb-2 text-[12px] text-muted">管道(点击处理节点可跳过;LLM 转换与建草稿是必需的)</p>
<Pipeline stages={meta.stages} active={active}
onToggle={(k) => { const n = new Set(active); if (n.has(k)) n.delete(k); else n.add(k); setActive(n); }} />
</Card>
<div className="grid gap-4 lg:grid-cols-2">
<Card>
<CardHeader title="输入:业务文档" desc="最好是业务专家梳理过的 BRD / 业务逻辑说明;越结构化,草案越准" />
<div className="space-y-3 p-4">
<div>
<p className="mb-1.5 text-[12px] font-medium">临时上传(只用于这次建模,不进知识库)</p>
<input ref={input} type="file" multiple hidden accept=".md,.txt,.docx,.pdf,.xlsx,.pptx,.html,.csv"
onChange={(e) => setFiles([...files, ...Array.from(e.target.files || [])])} />
<button className="btn btn-sm" onClick={() => input.current?.click()}><FileUp className="h-3.5 w-3.5" />选择文件</button>
<div className="mt-2 space-y-1">
{files.map((f, i) => (
<p key={i} className="flex items-center gap-2 text-[12.5px]"><FileText className="h-3.5 w-3.5 text-muted" />{f.name}
<span className="text-[11px] text-muted">{Math.ceil(f.size / 1024)} KB</span>
<button className="ml-auto text-muted hover:text-bad" onClick={() => setFiles(files.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button></p>
))}
</div>
</div>
<div className="border-t border-line pt-3">
<p className="mb-1.5 text-[12px] font-medium">知识库文档(已解析 {ready.length}/{docs.length})</p>
<div className="max-h-56 space-y-1 overflow-auto">
{ready.map((d) => (
<label key={d.id} className="flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 text-[12.5px] hover:bg-ink/[0.03]">
<input type="checkbox" checked={picked.has(d.id)} onChange={(e) => {
const n = new Set(picked); if (e.target.checked) n.add(d.id); else n.delete(d.id); setPicked(n);
}} />
<span className="min-w-0 flex-1 truncate">{d.filename}</span>
<span className="text-[11px] text-muted">{d.chunk_count} 片段</span>
</label>
))}
{!ready.length && <p className="text-[12px] text-muted">知识库里还没有解析好的文档,可以直接临时上传。</p>}
</div>
</div>
</div>
</Card>
<Card>
<CardHeader title="设置" />
<div className="space-y-3 p-4">
<Field label="画布名称"><input className="input" placeholder={files[0]?.name || "如:订单业务逻辑-0728"} value={title} onChange={(e) => setTitle(e.target.value)} /></Field>
<Field label="对齐数据表" hint="文档里的对象、关系会直接绑定到这些库里的表;不勾就只按文档起草,之后要逐个绑定">
<div className="space-y-1">
{dss.map((d) => (
<label key={d.id} className={cn("flex items-center gap-2 text-[12.5px]", !d.last_introspect_at && "opacity-50")}>
<input type="checkbox" disabled={!d.last_introspect_at} checked={dsPicked.has(d.id)} onChange={(e) => {
const n = new Set(dsPicked); if (e.target.checked) n.add(d.id); else n.delete(d.id); setDsPicked(n);
}} />
<span className="min-w-0 flex-1 truncate">{d.name}</span>
<span className="text-[11px] text-muted">{d.last_introspect_at ? d.db_name : "未内省"}</span>
</label>
))}
{!dss.length && <p className="text-[12px] text-muted">还没有接入数据。<button className="text-brand" onClick={() => go("data")}>去接入</button>,草案就能直接落到表上。</p>}
</div>
</Field>
<Field label="行业路由" hint="自动:AI 看文档结构选最贴近的行业模板,模板里的常见积木名作为命名先验;不会把模板内容强加进来">
<select className="input" value={template} onChange={(e) => setTemplate(e.target.value)}>
<option value="">自动识别</option>
<option value="none">不参考模板</option>
{meta.templates.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
</Field>
<div className="rounded-lg bg-ink/[0.03] p-3 text-[12px] text-muted">
产出全部是草案:积木进审核队列,流程卡是草稿。采纳后再提交变更提案,别人审批通过才上线。
</div>
{canEdit && (
<button className="btn btn-primary w-full justify-center" disabled={busy || (!files.length && !picked.size)} onClick={() => void start()}>
{busy ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}运行建模
</button>
)}
</div>
</Card>
</div>
</div>
);
}
function itemName(it: ReviewItem) { return it.payload?.name || it.title; }
function itemTypeKey(it: ReviewItem) {
const p = it.payload || {};
return p.kind === "function" ? (p.spec?.category || "rule") : p.kind || "object_type";
}
function RunDetail({ id, me }: { id: string; me: Me | null }) {
const canEdit = !!me?.permissions.includes("build");
const [run, setRun] = useState<ModelRunFull | null>(null);
const [picked, setPicked] = useState<Set<string>>(new Set());
const [busy, setBusy] = useState("");
const [open, setOpen] = useState<ReviewItem | null>(null);
const load = useCallback(async () => {
try {
const r = await onto.modelingRun(id);
setRun(r);
return r;
} catch (e) { toast("error", "加载失败", errText(e)); return null; }
}, [id]);
useEffect(() => {
let alive = true;
let timer = 0;
const tick = async () => {
const r = await load();
if (alive && r && r.status === "running") timer = window.setTimeout(tick, 2000);
};
void tick();
return () => { alive = false; window.clearTimeout(timer); };
}, [load]);
const pending = useMemo(() => COLS.flatMap((c) => run?.items[c.key] || []).filter((x) => x.status === "pending"), [run]);
useEffect(() => {
if (run?.status === "done") setPicked(new Set(pending.filter((x) => x.confidence >= 0.6).map((x) => x.id)));
}, [run?.status, pending.length]); // eslint-disable-line react-hooks/exhaustive-deps
if (!run) return <Spinner />;
const decide = async (accept: boolean) => {
// 先采纳对象,再关系、函数、动作:后者按名称引用对象,对象先落库才能解析成 id
const rank: Record<string, number> = { object_type: 0, link_type: 1, function: 2, action: 3 };
const ids = pending.filter((x) => picked.has(x.id))
.sort((a, b) => (rank[a.payload?.kind] ?? 2) - (rank[b.payload?.kind] ?? 2)).map((x) => x.id);
if (!ids.length) return;
if (!accept && !(await confirmDialog(`驳回 ${ids.length} 条草案?`, { danger: true }))) return;
setBusy(accept ? "accept" : "reject");
try {
const r = await onto.batchReview(ids, accept, accept ? `业务建模「${run.title}」采纳` : `业务建模「${run.title}」驳回`);
toast(r.failed.length ? "warn" : "ok", `${accept ? "采纳" : "驳回"} ${r.ok.length} 条`,
r.failed.length ? `${r.failed.length} 条失败:${r.failed[0].error}` : accept ? "已成为草稿积木,提交变更提案后生效" : undefined);
setPicked(new Set());
void load();
} catch (e) { toast("error", errText(e)); } finally { setBusy(""); }
};
const allItems = COLS.flatMap((c) => run.items[c.key] || []);
const accepted = allItems.filter((x) => x.status === "accepted").length;
return (
<div className="mx-auto max-w-7xl space-y-4">
<div className="flex flex-wrap items-center gap-2">
<button className="btn btn-ghost btn-sm" onClick={() => go("modeling")}>← 返回列表</button>
<span className="text-[15px] font-semibold">{run.title}</span>
<Badge tone={STATUS_TONE[run.status] || "bg-ink/5 text-muted"}>{run.status === "done" ? "已完成" : STATUS_LABEL[run.status] || run.status}</Badge>
<span className="text-[11.5px] text-muted">{fmtTime(run.created_at)} · {[...run.inputs.files, ...run.inputs.doc_ids.map((d) => `文档 #${d}`)].join("、")} · {run.inputs.chunks || ""}</span>
<div className="ml-auto flex gap-1.5">
<a className="btn btn-sm" href={onto.modelingExportUrl(run.id)} download={`${run.title}-四元组草案.md`}><Download className="h-3.5 w-3.5" />导出 .md</a>
{canEdit && run.status !== "running" && (
<button className="btn btn-sm" onClick={async () => {
if (!(await confirmDialog("删除这条建模记录?", { desc: "已经采纳的积木不受影响", danger: true }))) return;
await onto.deleteModelingRun(run.id); go("modeling");
}}><Trash2 className="h-3.5 w-3.5" /></button>
)}
</div>
</div>
<Card className="p-4">
<Pipeline stages={run.stages} />
{run.error && <p className="mt-2 text-[12.5px] text-bad">{run.error}</p>}
<div className="mt-3 grid gap-2 md:grid-cols-5">
{run.stages.map((s: ModelStage) => (
<div key={s.key} className="max-h-28 overflow-auto rounded-lg bg-ink/[0.03] p-2 text-[11.5px] text-muted">
<p className="mb-0.5 font-medium text-ink">{s.label}</p>
{s.log.length ? s.log.slice(-6).map((l, i) => <p key={i}>{l}</p>) : <p>{s.status === "skipped" ? "已跳过" : "等待中"}</p>}
</div>
))}
</div>
</Card>
<Card className="grid gap-4 p-4 sm:grid-cols-4">
<Stat label="草案积木" value={allItems.length} />
<Stat label="待审核" value={pending.length} tone={pending.length ? "text-warn" : ""} />
<Stat label="已采纳" value={accepted} tone={accepted ? "text-ok" : ""} />
<Stat label="流程卡草稿" value={run.sops.length} />
</Card>
<Card>
<div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-3">
<div className="min-w-0 flex-1">
<p className="text-[14px] font-semibold">四元组草案</p>
<p className="text-[12px] text-muted">默认勾选置信度 ≥ 0.6 的;「规则深化」写出表达式的会标「已深化」。采纳后成为草稿积木,到「变更提案」提交审批后生效。</p>
</div>
<button className="btn btn-sm" onClick={() => setPicked(new Set(pending.map((x) => x.id)))}>全选</button>
<button className="btn btn-sm" onClick={() => setPicked(new Set())}>全不选</button>
{canEdit && <>
<button className="btn btn-sm" disabled={!picked.size || !!busy} onClick={() => void decide(false)}>驳回所选</button>
<button className="btn btn-primary btn-sm" disabled={!picked.size || !!busy} onClick={() => void decide(true)}>
{busy === "accept" && <Spinner className="h-3.5 w-3.5" />}采纳所选 {picked.size}</button>
{accepted > 0 && <button className="btn btn-sm" onClick={() => go("publish")}><Rocket className="h-3.5 w-3.5" />去提交变更提案</button>}
</>}
</div>
{run.status === "running" && !allItems.length ? <div className="p-6"><Spinner /></div> : (
<div className="grid gap-3 p-3 md:grid-cols-2 xl:grid-cols-4">
{COLS.map((col) => {
const xs = run.items[col.key] || [];
return (
<div key={col.key} className="flex min-h-[200px] flex-col rounded-xl border border-line">
<p className="flex items-center gap-2 border-b border-line px-3 py-2 text-[13px] font-semibold">
<i className="h-2 w-2 rounded-full" style={{ background: KIND_COLOR[col.key === "function" ? "aggregate" : col.key] }} />
{col.label}<span className="text-muted">({xs.length})</span></p>
<div className="max-h-[52vh] flex-1 space-y-0.5 overflow-auto p-1.5">
{xs.map((it) => (
<div key={it.id} className={cn("flex items-center gap-1.5 rounded-md px-1.5 py-1 text-[12.5px] hover:bg-ink/[0.03]",
open?.id === it.id && "bg-brand/5")}>
<input type="checkbox" disabled={it.status !== "pending"} checked={picked.has(it.id)} onChange={(e) => {
const n = new Set(picked); if (e.target.checked) n.add(it.id); else n.delete(it.id); setPicked(n);
}} />
<button className="min-w-0 flex-1 truncate text-left font-mono text-[12px]" onClick={() => setOpen(open?.id === it.id ? null : it)}>{itemName(it)}</button>
{col.key === "function" && <TypeBadge t={itemTypeKey(it)} />}
{it.payload?.deepened && <Badge tone="bg-brand/10 text-brand">已深化</Badge>}
{bindLabel(it) && <Badge tone="bg-ok/10 text-ok">{bindLabel(it)}</Badge>}
{it.payload?.kind === "action" && (it.payload?.spec?._stub
? <Badge tone="bg-warn/10 text-warn">待补全</Badge> : <Badge tone="bg-ok/10 text-ok">可执行</Badge>)}
{it.status !== "pending" && <Badge tone={STATUS_TONE[it.status]}>{STATUS_LABEL[it.status]}</Badge>}
</div>
))}
{!xs.length && <p className="p-2 text-[12px] text-muted">无</p>}
</div>
</div>
);
})}
</div>
)}
{open && <ItemDetail it={open} />}
{(run.items.other || []).length > 0 && (
<p className="border-t border-line px-4 py-2 text-[12px] text-muted">
另有 {(run.items.other || []).length} 条补别名 / 知识冲突,到 <button className="text-brand" onClick={() => go("inbox", { tab: "reviews" })}>审核队列</button> 逐条处理。</p>
)}
</Card>
<Card>
<CardHeader title="流程卡草稿(SOP 编排)" desc="从同一批文档蒸馏出的可执行流程;在流程卡页试运行通过后提交发布" />
<div className="divide-y divide-line">
{run.sops.map((s) => (
<button key={s.id} className="flex w-full items-center gap-3 px-4 py-2 text-left text-[12.5px] hover:bg-ink/[0.02]" onClick={() => go("sop", { id: s.id })}>
<ListChecks className="h-4 w-4 text-brand" /><span className="font-medium">{s.title}</span>
<span className="min-w-0 flex-1 truncate text-muted">{s.description}</span>
<Badge>{s.step_count} 步</Badge><Badge tone={STATUS_TONE[s.status]}>{STATUS_LABEL[s.status]}</Badge>
</button>
))}
{!run.sops.length && <Empty title={run.stages.find((s) => s.key === "sop")?.status === "skipped" ? "这次跳过了 SOP 编排" : "文档里没有识别出完整的流程"} />}
</div>
</Card>
</div>
);
}
/** 草案落到了哪里:对象 / 关系绑了表,指标写好了取数表达式。 */
function bindLabel(it: ReviewItem): string {
const kinds = (it.payload?.bindings || []).map((b: any) => b.target_kind);
if (kinds.includes("metric_expr")) return "取数已校验";
if (kinds.includes("table") || kinds.includes("join")) return "已绑表";
return "";
}
function ItemDetail({ it }: { it: ReviewItem }) {
const p = it.payload || {};
const spec = p.spec || {};
const binds: any[] = p.bindings || [];
return (
<div className="space-y-2 border-t border-line px-4 py-3 text-[12.5px]">
<p className="flex items-center gap-2 font-semibold"><TypeBadge t={itemTypeKey(it)} />{p.name}
<span className="text-[11px] font-normal text-muted">置信度 {it.confidence?.toFixed(2)}</span></p>
{p.description && <p className="text-muted">{p.description}</p>}
{p.synonyms?.length > 0 && <p><span className="text-muted">别名:</span>{p.synonyms.join("、")}</p>}
{spec.properties?.length > 0 && <p><span className="text-muted">属性:</span>{spec.properties.map((x: any) => x.name).join("、")}</p>}
{spec.expression && <p><span className="text-muted">表达式:</span><code>{spec.expression}</code></p>}
{spec.text && <p><span className="text-muted">原文要点:</span>{spec.text}</p>}
{spec.from_type && <p><span className="text-muted">关系:</span>{spec.from_type} → {spec.to_type}({spec.cardinality})</p>}
{spec.formula_text && <p><span className="text-muted">口径:</span>{spec.formula_text}{spec.unit ? `(${spec.unit})` : ""}</p>}
{binds.map((b, i) => (
<p key={i}><span className="text-muted">{b.target_kind === "table" ? "数据表:" : b.target_kind === "join" ? "关联:" : "取数:"}</span>
<code className="text-[11.5px]">{b.target_kind === "table" ? `${b.ref.table}(主键 ${b.ref.key_column})`
: b.target_kind === "join" ? `${b.ref.from_column} = ${b.ref.to_column}`
: `${b.ref.expression} FROM ${b.ref.base_table}${(b.ref.filters || []).length ? ` WHERE ${b.ref.filters.join(" AND ")}` : ""}`}</code></p>
))}
{p.kind === "action" && !spec._stub && (
<div className="space-y-1 rounded bg-ink/[0.03] px-2 py-1.5">
<p><span className="text-muted">作用对象:</span>{spec.target_type || "无"} <span className="text-muted">参数:</span>
{(spec.params || []).map((x: any) => `${x.label || x.name}${x.required ? "*" : ""}`).join("、") || "无"}</p>
{(spec.criteria || []).map((c: any, i: number) => <p key={i}><span className="text-muted">前置条件:</span><code>{c.expression}</code></p>)}
{(spec.effects || []).map((e: any, i: number) => (
<p key={i}><span className="text-muted">效果:</span>{e.tool} <code className="text-[11px]">{JSON.stringify(e.args)}</code></p>))}
<p><span className="text-muted">审批:</span>{(spec.approval?.approver_roles || []).join("、") || "审批人"}</p>
</div>
)}
{(p.evidence || []).slice(0, 3).map((e: any, i: number) => (
<p key={i} className="rounded bg-ink/[0.03] px-2 py-1 text-[11.5px] text-muted">【{e.heading || "出处"}】{e.snippet}</p>
))}
</div>
);
}
import { ArrowRight, FileUp, GitCommit, GitCompare, Link2, Rocket, RotateCcw, Search, Wand2 } from "lucide-react"; import { ArrowRight, FileUp, GitCommit, GitCompare, Link2, Rocket, RotateCcw, Search, Send, ShieldCheck, Wand2, X } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { Badge, Card, CardHeader, Empty, Spinner, Stat } from "@/components/ui"; import { Badge, Card, CardHeader, Empty, Segmented, Spinner, Stat } from "@/components/ui";
import { go } from "@/lib/nav"; import { go } from "@/lib/nav";
import { errText, fmtTime, onto, type Diff, type KernelStats, type Me, type RevisionRec } from "@/lib/onto"; import {
import { confirmDialog } from "@/lib/dialog"; errText, fmtTime, onto, STATUS_LABEL, STATUS_TONE, type Diff, type KernelStats, type Me, type ReleaseItem,
type RevisionRec,
} from "@/lib/onto";
import { confirmDialog, promptText } from "@/lib/dialog";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore"; import { toast } from "@/store/useAppStore";
import { TypeBadge } from "./common"; import { TypeBadge } from "./common";
...@@ -11,52 +14,84 @@ import { pageOfKind } from "./routes"; ...@@ -11,52 +14,84 @@ import { pageOfKind } from "./routes";
import { DiffView, FIELD_LABEL, ImportExport, LinkTester, ProposeModal } from "./tools"; import { DiffView, FIELD_LABEL, ImportExport, LinkTester, ProposeModal } from "./tools";
/** /**
* 变更与发布:所有积木(对象、关系、函数、动作)共用一套草稿 → 发布 → 版本。 * 变更提案:所有积木(对象、关系、函数、动作)共用一套草稿 → 提案 → 审批 → 版本。
* 发布前能看到这次会变什么;开启评测闸门后,回归掉点会被拦下。 * 发布不再一步到位:提交人不能审批自己的提案,AI 与外部 Agent 不能审批;
* 审批时草稿若又被改过,要重新提交 —— 上线的一定是被审过的那一版。
*/ */
export function PublishPage({ me }: { me: Me | null }) { export function PublishPage({ me }: { me: Me | null }) {
const canEdit = !!me?.permissions.includes("build"); const canEdit = !!me?.permissions.includes("build");
const [diff, setDiff] = useState<Diff | null>(null); const [diff, setDiff] = useState<Diff | null>(null);
const [stats, setStats] = useState<KernelStats | null>(null); const [stats, setStats] = useState<KernelStats | null>(null);
const [reviews, setReviews] = useState(0); const [reviews, setReviews] = useState(0);
const [items, setItems] = useState<ReleaseItem[] | null>(null);
const [tab, setTab] = useState<"pending" | "history">("pending");
const [note, setNote] = useState(""); const [note, setNote] = useState("");
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState("");
const [modal, setModal] = useState<"" | "io" | "propose" | "link">(""); const [modal, setModal] = useState<"" | "io" | "propose" | "link">("");
const load = useCallback(() => { const load = useCallback(() => {
void onto.pendingDiff().then(setDiff); void onto.pendingDiff().then(setDiff);
void onto.kernelStats().then(setStats); void onto.kernelStats().then(setStats);
void onto.reviewCounts().then((r) => setReviews(Object.values(r).reduce((a, b) => a + b, 0))).catch(() => undefined); void onto.releases().then(setItems).catch(() => setItems([]));
void onto.reviewCounts().then((r) => setReviews(Object.entries(r).filter(([k]) => k !== "release")
.reduce((a, [, b]) => a + b, 0))).catch(() => undefined);
}, []); }, []);
useEffect(load, [load]); useEffect(load, [load]);
const total = diff ? diff.added.length + diff.changed.length + diff.removed.length : 0; const total = diff ? diff.added.length + diff.changed.length + diff.removed.length : 0;
const pending = (items || []).filter((x) => x.status === "pending");
const history = (items || []).filter((x) => x.status !== "pending");
const publish = async (force = false) => { const submit = async () => {
setBusy(true); setBusy("submit");
try { try {
const r = await onto.publish(note, force); await onto.proposeRelease(note);
toast("ok", `已发布第 ${r.revision} 版`, "问答、取数、流程卡、动作立即使用新定义"); toast("ok", "已提交变更提案", "请另一位有建设权限的同事审批,通过后发布成新版本");
setNote(""); load(); setNote(""); load();
} catch (e) { } catch (e) { toast("error", "提交失败", errText(e)); } finally { setBusy(""); }
const msg = errText(e); };
if (msg.includes("闸门") && me?.roles.includes("admin") const decide = async (it: ReleaseItem, approve: boolean) => {
&& await confirmDialog("发布被评测闸门拦下", { desc: `${msg}。管理员可以跳过闸门强制发布,确定吗?`, danger: true })) { let comment = "";
setBusy(false); return publish(true); if (!approve) {
} const mine = it.created_by === me?.id;
toast("error", "发布失败", msg); const v = await promptText(mine ? "撤回这份提案?" : "驳回原因", { placeholder: mine ? "原因(可空)" : "必填,方便提交人修改" });
} finally { setBusy(false); } if (v === null || (!mine && !v.trim())) return;
comment = v.trim() || "提交人撤回";
} else if (!(await confirmDialog("通过并发布?", { desc: `${it.title}。通过后立即生成新版本,问答、取数、流程卡、动作使用新定义。` }))) return;
setBusy(it.id);
try {
const r = await onto.decideRelease(it.id, approve, comment);
toast("ok", approve ? `已发布第 ${r.result?.revision} 版` : "已驳回");
load();
} catch (e) { toast("error", approve ? "审批失败" : "驳回失败", errText(e)); } finally { setBusy(""); }
}; };
return ( return (
<div className="mx-auto max-w-5xl space-y-4"> <div className="mx-auto max-w-5xl space-y-4">
<Card className="grid gap-4 p-4 sm:grid-cols-4"> <Card className="grid gap-4 p-4 sm:grid-cols-4">
<Stat label="线上版本" value={`v${stats?.revision ?? 0}`} /> <Stat label="线上版本" value={`v${stats?.revision ?? 0}`} />
<Stat label="待发布修改" value={total} tone={total ? "text-warn" : ""} /> <Stat label="未提交的修改" value={total} tone={total ? "text-warn" : ""} />
<button className="text-left" onClick={() => go("inbox", { tab: "reviews" })}><Stat label="待审核的 AI 提议" value={reviews} tone={reviews ? "text-warn" : ""} hint="采纳后才进入草稿" /></button> <Stat label="待审批提案" value={pending.length} tone={pending.length ? "text-warn" : ""} hint="提交人不能自审" />
<button className="text-left" onClick={() => go("versions")}><Stat label="历史版本" value={stats?.revision ?? 0} hint="可对比、可回滚" /></button> <button className="text-left" onClick={() => go("modeling")}><Stat label="待审核的 AI 草案" value={reviews} tone={reviews ? "text-warn" : ""} hint="采纳后才进入草稿" /></button>
</Card> </Card>
{pending.map((it) => (
<Card key={it.id} className="border-warn/40">
<CardHeader title={<span className="flex items-center gap-2"><ShieldCheck className="h-4 w-4 text-warn" />{it.title}</span>}
desc={`${it.created_by} 提交于 ${fmtTime(it.created_at)}${it.payload?.note ? ` · ${it.payload.note}` : ""}`}
right={<>
{it.created_by === me?.id && <button className="btn btn-sm" disabled={!!busy} onClick={() => void decide(it, false)}><X className="h-3.5 w-3.5" />撤回</button>}
{it.can_decide && <>
<button className="btn btn-sm" disabled={!!busy} onClick={() => void decide(it, false)}>驳回</button>
<button className="btn btn-sm btn-primary" disabled={!!busy} onClick={() => void decide(it, true)}>
{busy === it.id ? <Spinner className="h-3.5 w-3.5" /> : <Rocket className="h-3.5 w-3.5" />}通过并发布</button>
</>}
{!it.can_decide && it.created_by !== me?.id && <Badge>{it.cannot_reason}</Badge>}
</>} />
<div className="p-4">{it.payload?.diff ? <DiffView diff={it.payload.diff} /> : <p className="text-[12.5px] text-muted">回滚到 v{it.payload?.rev}</p>}</div>
</Card>
))}
<Card> <Card>
<CardHeader title="本次将发布的变更" desc="草稿不影响线上;发布 = 把草稿转正并冻结一份全量快照" <CardHeader title="当前草稿的变更" desc="草稿不影响线上;提交成提案、审批通过后才冻结成新版本"
right={canEdit && <> right={canEdit && <>
<button className="btn btn-sm" onClick={() => setModal("propose")}><Wand2 className="h-3.5 w-3.5" />AI 提议</button> <button className="btn btn-sm" onClick={() => setModal("propose")}><Wand2 className="h-3.5 w-3.5" />AI 提议</button>
<button className="btn btn-sm" onClick={() => setModal("io")}><FileUp className="h-3.5 w-3.5" />模板 / 导入导出</button> <button className="btn btn-sm" onClick={() => setModal("io")}><FileUp className="h-3.5 w-3.5" />模板 / 导入导出</button>
...@@ -76,15 +111,33 @@ export function PublishPage({ me }: { me: Me | null }) { ...@@ -76,15 +111,33 @@ export function PublishPage({ me }: { me: Me | null }) {
)} )}
{canEdit && ( {canEdit && (
<div className="flex gap-2 border-t border-line pt-3"> <div className="flex gap-2 border-t border-line pt-3">
<input className="input flex-1" placeholder="发布说明(给同事看这一版改了什么)" value={note} onChange={(e) => setNote(e.target.value)} /> <input className="input flex-1" placeholder="变更说明(给审批人看这一版改了什么、为什么)" value={note} onChange={(e) => setNote(e.target.value)} />
<button className="btn btn-primary" disabled={busy || !total} onClick={() => void publish()}> <button className="btn btn-primary" disabled={!!busy || !total || pending.length > 0} title={pending.length ? "已有待审批的提案" : ""}
{busy ? <Spinner className="h-3.5 w-3.5" /> : <Rocket className="h-3.5 w-3.5" />}发布 onClick={() => void submit()}>
{busy === "submit" ? <Spinner className="h-3.5 w-3.5" /> : <Send className="h-3.5 w-3.5" />}提交变更提案
</button> </button>
</div> </div>
)} )}
</div> </div>
</Card> </Card>
<Card>
<CardHeader title="提案记录" right={<Segmented value={tab} onChange={setTab}
options={[{ key: "pending", label: `待审批 ${pending.length}` }, { key: "history", label: `历史 ${history.length}` }]} />} />
<div className="divide-y divide-line">
{!items ? <div className="p-4"><Spinner /></div> : (tab === "pending" ? pending : history).length === 0
? <Empty title={tab === "pending" ? "没有待审批的提案" : "还没有提案记录"} />
: (tab === "pending" ? pending : history).map((it) => (
<div key={it.id} className="flex items-center gap-3 px-4 py-2 text-[12.5px]">
<Badge tone={STATUS_TONE[it.status]}>{STATUS_LABEL[it.status] || it.status}</Badge>
<span className="min-w-0 flex-1 truncate">{it.title}{it.payload?.note ? ` · ${it.payload.note}` : ""}</span>
<span className="text-muted">{it.created_by}{it.decided_by ? ` → ${it.decided_by}` : ""}</span>
<span className="w-32 text-right text-muted">{fmtTime(it.decided_at || it.created_at)}</span>
</div>
))}
</div>
</Card>
{modal === "io" && <ImportExport onClose={() => setModal("")} onDone={load} />} {modal === "io" && <ImportExport onClose={() => setModal("")} onDone={load} />}
{modal === "propose" && <ProposeModal onClose={() => setModal("")} />} {modal === "propose" && <ProposeModal onClose={() => setModal("")} />}
{modal === "link" && <LinkTester onClose={() => setModal("")} />} {modal === "link" && <LinkTester onClose={() => setModal("")} />}
...@@ -116,7 +169,7 @@ export function VersionsPage({ me }: { me: Me | null }) { ...@@ -116,7 +169,7 @@ export function VersionsPage({ me }: { me: Me | null }) {
const shown = useMemo(() => (revs || []).filter((r) => !q || `v${r.revision} ${r.note} ${r.published_by}`.includes(q)), [revs, q]); const shown = useMemo(() => (revs || []).filter((r) => !q || `v${r.revision} ${r.note} ${r.published_by}`.includes(q)), [revs, q]);
if (!revs) return <Spinner />; if (!revs) return <Spinner />;
if (!revs.length) return <Card><Empty icon={<GitCommit className="h-10 w-10" />} title="还没有发布过" desc="在「变更与发布」发布第一版后,这里会出现可对比、可回滚的版本快照。" /></Card>; if (!revs.length) return <Card><Empty icon={<GitCommit className="h-10 w-10" />} title="还没有发布过" desc="第一份变更提案审批通过后,这里会出现可对比、可回滚的版本快照。" /></Card>;
return ( return (
<div className="grid h-full gap-4 lg:grid-cols-[300px_minmax(0,1fr)]"> <div className="grid h-full gap-4 lg:grid-cols-[300px_minmax(0,1fr)]">
<Card className="flex min-h-0 flex-col"> <Card className="flex min-h-0 flex-col">
...@@ -148,8 +201,8 @@ export function VersionsPage({ me }: { me: Me | null }) { ...@@ -148,8 +201,8 @@ export function VersionsPage({ me }: { me: Me | null }) {
</select> </select>
{canEdit && to !== revs[0].revision && ( {canEdit && to !== revs[0].revision && (
<button className="btn btn-sm" onClick={async () => { <button className="btn btn-sm" onClick={async () => {
if (!(await confirmDialog(`回滚到 v${to}?`, { desc: "会恢复该版本的全部积木定义(含动作与函数),并记为一个新版本" }))) return; if (!(await confirmDialog(`提交回滚到 v${to} 的提案?`, { desc: "回滚也是一份变更提案:另一位同事审批通过后,恢复该版本的全部积木定义并记为一个新版本" }))) return;
try { await onto.rollback(to); toast("ok", "已回滚"); setTo(0); load(); } catch (e) { toast("error", "回滚失败", errText(e)); } try { await onto.rollback(to); toast("ok", "已提交回滚提案", "到「变更提案」页等待审批"); go("publish"); } catch (e) { toast("error", "提交失败", errText(e)); }
}}><RotateCcw className="h-3.5 w-3.5" />回滚到 v{to}</button> }}><RotateCcw className="h-3.5 w-3.5" />回滚到 v{to}</button>
)} )}
</>} /> </>} />
......
import { CheckCircle2, Database, FileText, FileUp, LayoutGrid, MessageSquareText, Rocket, Wand2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Badge, Card, Empty, Progress, Spinner, Stat } from "@/components/ui";
import { api } from "@/lib/api";
import { go } from "@/lib/nav";
import { errText, onto, type Diff, type KernelStats, type Me, type ReviewItem } from "@/lib/onto";
import type { DataSource } from "@/lib/types";
import { useJobPoll } from "@/lib/useJobPoll";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { TypeBadge } from "./common";
import { DiffView, ImportExport } from "./tools";
type Step = 1 | 2 | 3;
function itemType(it: ReviewItem): string {
const p = it.payload || {};
if (it.kind === "binding") return p.target_kind === "metric_expr" ? "aggregate" : "object_type";
const k = p.kind || "";
return k === "function" ? (p.spec?.category || "rule") : k || "object_type";
}
/**
* 业务建模:三步从零到可问。
* 1 选数据源与文档 → 2 AI 生成四元组草案,一张表里批量采纳 → 3 看差异、发布。
*/
export function WizardPage({ me }: { me: Me | null }) {
const canEdit = !!me?.permissions.includes("build");
const [step, setStep] = useState<Step>(1);
const [dss, setDss] = useState<DataSource[]>([]);
const [docs, setDocs] = useState({ count: 0, done: 0 });
const [stats, setStats] = useState<KernelStats | null>(null);
const [items, setItems] = useState<ReviewItem[] | null>(null);
const [picked, setPicked] = useState<Set<string>>(new Set());
const [diff, setDiff] = useState<Diff | null>(null);
const [jobId, setJobId] = useState<number | null>(null);
const [busy, setBusy] = useState("");
const [tpl, setTpl] = useState(false);
const job = useJobPoll(jobId);
const loadReviews = useCallback(() => {
void onto.reviews({ status: "pending", limit: 500 }).then((r) => {
const xs = r.items.filter((x) => ["concept_create", "conflict", "binding", "concept_update"].includes(x.kind));
setItems(xs);
setPicked(new Set(xs.filter((x) => x.kind !== "conflict" && x.confidence >= 0.6).map((x) => x.id)));
}).catch(() => setItems([]));
}, []);
const load = useCallback(() => {
void api.datasources().then(setDss).catch(() => setDss([]));
void api.info().then((i) => setDocs({ count: i.doc_count, done: i.doc_done })).catch(() => undefined);
void onto.kernelStats().then(setStats).catch(() => undefined);
void onto.pendingDiff().then(setDiff).catch(() => undefined);
loadReviews();
}, [loadReviews]);
useEffect(load, [load]);
useEffect(() => { if (job?.status === "done") { loadReviews(); toast("ok", "AI 提议完成", job.message); } }, [job?.status]); // eslint-disable-line react-hooks/exhaustive-deps
const blocks = useMemo(() => Object.values(stats?.by_kind || {}).reduce((a, b) => a + (b.total || 0), 0), [stats]);
const pendingTotal = diff ? diff.added.length + diff.changed.length + diff.removed.length : 0;
const proposeDs = async (d: DataSource) => {
setBusy(`ds${d.id}`);
try { const r = await onto.proposeFromDatasource(d.id); toast("ok", `从「${d.name}」提议 ${r.proposed} 块积木`, `冲突 ${r.conflicts},补充 ${r.enriched}`); loadReviews(); }
catch (e) { toast("error", "提议失败", errText(e)); } finally { setBusy(""); }
};
const decide = async (accept: boolean) => {
// 先采纳对象,再关系、函数、动作:后者按名称引用对象,对象先落库才能解析成 id
const rank: Record<string, number> = { object_type: 0, link_type: 1, action: 3 };
const ids = (items || []).filter((x) => picked.has(x.id))
.sort((a, b) => (rank[itemType(a)] ?? 2) - (rank[itemType(b)] ?? 2)).map((x) => x.id);
if (!ids.length) return;
setBusy(accept ? "accept" : "reject");
try {
const r = await onto.batchReview(ids, accept, accept ? "业务建模向导批量采纳" : "业务建模向导批量驳回");
toast(r.failed.length ? "warn" : "ok", `${accept ? "采纳" : "驳回"} ${r.ok.length} 条`,
r.failed.length ? `${r.failed.length} 条失败:${r.failed[0].error}` : undefined);
load();
} catch (e) { toast("error", errText(e)); } finally { setBusy(""); }
};
const publish = async () => {
setBusy("publish");
try { const r = await onto.publish("业务建模向导发布"); toast("ok", `已发布第 ${r.revision} 版`); load(); }
catch (e) { toast("error", "发布失败", errText(e)); } finally { setBusy(""); }
};
const STEPS: { n: Step; title: string; desc: string; done: boolean }[] = [
{ n: 1, title: "选数据与文档", desc: "让 AI 读数据库结构和业务文档", done: (items?.length || 0) > 0 || blocks > 0 },
{ n: 2, title: "审核四元组草案", desc: "对象 · 关系 · 函数 · 动作,一张表批量采纳", done: blocks > 0 && !(items?.length) },
{ n: 3, title: "发布", desc: "看清改了什么,发布后即可提问", done: (stats?.revision || 0) > 0 && !pendingTotal },
];
return (
<div className="mx-auto max-w-5xl space-y-4">
<Card className="grid gap-4 p-4 sm:grid-cols-4">
<Stat label="本体积木" value={blocks} hint={`对象 ${stats?.by_kind.object_type?.total || 0} · 函数 ${stats?.by_kind.function?.total || 0} · 动作 ${stats?.by_kind.action?.total || 0}`} />
<Stat label="待审核草案" value={items?.length ?? "-"} tone={items?.length ? "text-warn" : ""} />
<Stat label="待发布修改" value={pendingTotal} tone={pendingTotal ? "text-warn" : ""} />
<Stat label="线上版本" value={`v${stats?.revision ?? 0}`} />
</Card>
<div className="grid gap-2 sm:grid-cols-3">
{STEPS.map((s) => (
<button key={s.n} onClick={() => setStep(s.n)}
className={cn("card flex items-start gap-3 p-3 text-left transition-colors", step === s.n ? "border-brand ring-1 ring-brand/30" : "hover:bg-ink/[0.02]")}>
<span className={cn("grid h-7 w-7 shrink-0 place-items-center rounded-full text-[13px] font-semibold",
s.done ? "bg-ok text-white" : step === s.n ? "bg-brand text-white" : "bg-ink/10 text-muted")}>
{s.done ? <CheckCircle2 className="h-4 w-4" /> : s.n}
</span>
<span><p className="text-[13.5px] font-semibold">{s.title}</p><p className="text-[12px] text-muted">{s.desc}</p></span>
</button>
))}
</div>
{step === 1 && (
<div className="grid gap-4 md:grid-cols-2">
<Card className="p-4">
<p className="flex items-center gap-2 text-[14px] font-semibold"><Database className="h-4 w-4 text-brand" />数据库</p>
<p className="mt-1 text-[12px] text-muted">已启用的表 → 对象(带表绑定),表间关联 → 关系。确定性翻译,不花模型额度。</p>
<div className="mt-3 space-y-2">
{dss.map((d) => (
<div key={d.id} className="flex items-center gap-2 rounded-lg border border-line px-3 py-2">
<span className="min-w-0 flex-1 truncate text-[13px]">{d.name} <span className="text-[11px] text-muted">{d.ds_type} · {d.db_name}</span></span>
{canEdit && <button className="btn btn-sm" disabled={!!busy} onClick={() => void proposeDs(d)}>
{busy === `ds${d.id}` ? <Spinner className="h-3.5 w-3.5" /> : <Wand2 className="h-3.5 w-3.5" />}提议对象与关系</button>}
</div>
))}
{!dss.length && <Empty title="还没有接入数据库" action={<button className="btn btn-sm" onClick={() => go("data")}>去接入</button>} />}
</div>
</Card>
<Card className="p-4">
<p className="flex items-center gap-2 text-[14px] font-semibold"><FileText className="h-4 w-4 text-brand" />业务文档</p>
<p className="mt-1 text-[12px] text-muted">从已抽取的 {docs.done}/{docs.count} 份文档里找对象、指标、规则、决策表、周期、动作,每条带原文出处;文中岗位登记为业务角色。</p>
<div className="mt-3 space-y-2">
{job ? (
<div className="space-y-1">
<Progress value={job.progress} />
<p className="text-[12px] text-muted">{job.message || job.stage}</p>
{job.status === "done" && <button className="btn btn-primary btn-sm" onClick={() => setStep(2)}>去审核草案</button>}
</div>
) : canEdit && (
<button className="btn btn-primary btn-sm" disabled={!docs.done} onClick={async () => {
try { const r = await onto.proposeFromDocs(); setJobId(r.job_id); toast("info", `开始分析 ${r.chunks} 个片段`); }
catch (e) { toast("error", errText(e)); }
}}><Wand2 className="h-3.5 w-3.5" />AI 从文档提议</button>
)}
{!docs.count && <button className="btn btn-sm" onClick={() => go("documents")}>去上传文档</button>}
</div>
<div className="mt-4 border-t border-line pt-3">
<p className="text-[12px] text-muted">没有文档?也可以直接套用行业模板或通用起步包。</p>
{canEdit && <button className="btn btn-sm mt-2" onClick={() => setTpl(true)}><FileUp className="h-3.5 w-3.5" />模板 / 导入</button>}
</div>
</Card>
<div className="md:col-span-2 flex justify-end">
<button className="btn btn-primary" onClick={() => setStep(2)}>下一步:审核草案</button>
</div>
</div>
)}
{step === 2 && (
<Card>
<div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-3">
<div className="min-w-0 flex-1">
<p className="text-[14px] font-semibold">四元组草案 · {items?.length ?? 0} 条</p>
<p className="text-[12px] text-muted">默认勾选了置信度 ≥ 0.6 的新增项;「知识冲突」需要逐条去「行动审批 → 审核队列」裁决。采纳后成为草稿积木,还要发布才生效。</p>
</div>
<button className="btn btn-sm" onClick={() => setPicked(new Set((items || []).filter((x) => x.kind !== "conflict").map((x) => x.id)))}>全选</button>
<button className="btn btn-sm" onClick={() => setPicked(new Set())}>全不选</button>
{canEdit && <>
<button className="btn btn-sm" disabled={!picked.size || !!busy} onClick={() => void decide(false)}>驳回所选</button>
<button className="btn btn-primary btn-sm" disabled={!picked.size || !!busy} onClick={() => void decide(true)}>
{busy === "accept" && <Spinner className="h-3.5 w-3.5" />}采纳所选 {picked.size}
</button>
</>}
</div>
{!items ? <Spinner /> : !items.length ? (
<Empty icon={<CheckCircle2 className="h-10 w-10" />} title="没有待审核的草案"
action={<button className="btn btn-primary btn-sm" onClick={() => setStep(3)}>下一步:发布</button>} />
) : (
<div className="max-h-[60vh] overflow-auto">
<table className="w-full text-[12.5px]">
<thead className="sticky top-0 bg-surface text-[11.5px] text-muted">
<tr className="border-b border-line"><th className="w-8" /><th className="px-2 py-2 text-left">类型</th><th className="px-2 text-left">名称</th>
<th className="px-2 text-left">说明</th><th className="px-2 text-left">来源</th><th className="px-2 text-left">置信度</th></tr>
</thead>
<tbody>
{items.map((it) => (
<tr key={it.id} className="border-b border-line/60 hover:bg-ink/[0.02]">
<td className="text-center">
<input type="checkbox" disabled={it.kind === "conflict"} checked={picked.has(it.id)} onChange={(e) => {
const n = new Set(picked); if (e.target.checked) n.add(it.id); else n.delete(it.id); setPicked(n);
}} />
</td>
<td className="px-2 py-1.5">
{it.kind === "conflict" ? <Badge tone="bg-bad/10 text-bad">知识冲突</Badge> : <TypeBadge t={itemType(it)} />}
{it.kind === "concept_update" && <Badge className="ml-1">补别名</Badge>}
</td>
<td className="px-2 font-medium">{it.payload?.name || it.title}</td>
<td className="max-w-[360px] truncate px-2 text-muted">{it.payload?.description || it.title}</td>
<td className="px-2 text-muted">{{ extract: "文档", introspect: "数据库", ai: "AI", user: "人工", feedback: "反馈" }[it.source] || it.source}</td>
<td className="px-2 tabular-nums">{it.confidence ? it.confidence.toFixed(2) : "-"}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="flex justify-between border-t border-line px-4 py-3">
<button className="btn btn-sm" onClick={() => go("inbox", { tab: "reviews" })}>逐条审核(含冲突)</button>
<button className="btn btn-primary btn-sm" onClick={() => setStep(3)}>下一步:发布</button>
</div>
</Card>
)}
{step === 3 && (
<Card className="p-4">
<p className="text-[14px] font-semibold">本次将发布的变更</p>
<div className="mt-2">{diff ? <DiffView diff={diff} /> : <Spinner />}</div>
<div className="mt-4 flex flex-wrap gap-2 border-t border-line pt-3">
<button className="btn btn-sm" onClick={() => go("canvas")}><LayoutGrid className="h-3.5 w-3.5" />先在画布上看看</button>
<button className="btn btn-sm" onClick={() => go("b_function")}>补全函数(绑定取数、试跑)</button>
{canEdit && <button className="btn btn-primary btn-sm ml-auto" disabled={!pendingTotal || busy === "publish"} onClick={() => void publish()}>
{busy === "publish" ? <Spinner className="h-3.5 w-3.5" /> : <Rocket className="h-3.5 w-3.5" />}发布</button>}
{!pendingTotal && (stats?.revision || 0) > 0 && (
<button className="btn btn-primary btn-sm ml-auto" onClick={() => go("ask")}><MessageSquareText className="h-3.5 w-3.5" />去提问</button>
)}
</div>
</Card>
)}
{tpl && <ImportExport onClose={() => setTpl(false)} onDone={load} />}
</div>
);
}
...@@ -102,7 +102,7 @@ export function Rows<T>({ items, onChange, render, empty, disabled, addText = " ...@@ -102,7 +102,7 @@ export function Rows<T>({ items, onChange, render, empty, disabled, addText = "
{render(it, (v) => { const n = [...items]; n[i] = v; onChange(n); }, i)} {render(it, (v) => { const n = [...items]; n[i] = v; onChange(n); }, i)}
</fieldset> </fieldset>
{!disabled && ( {!disabled && (
<button className="btn btn-ghost btn-sm ml-auto" onClick={() => onChange(items.filter((_, j) => j !== i))}> <button className="btn btn-ghost btn-sm ml-auto" title="删除这一行" aria-label="删除这一行" onClick={() => onChange(items.filter((_, j) => j !== i))}>
<Trash2 className="h-3.5 w-3.5" /> <Trash2 className="h-3.5 w-3.5" />
</button> </button>
)} )}
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
export const KIND_PAGE: Record<string, string> = { export const KIND_PAGE: Record<string, string> = {
object_type: "b_object", link_type: "b_link", function: "b_function", action: "b_action", object_type: "b_object", link_type: "b_link", function: "b_function", action: "b_action",
metric: "b_function", rule: "b_function", calendar: "b_function", aggregate: "b_function", metric: "b_function", rule: "b_function", calendar: "b_function", aggregate: "b_function",
decision: "b_function", ai: "b_function", skill: "b_function", decision: "b_function", ml: "b_function", ai: "b_function", skill: "b_function",
}; };
export function pageOfKind(kind: string): string { export function pageOfKind(kind: string): string {
......
import { Activity, Bot, ListChecks, RefreshCw, ShieldCheck, Workflow } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Card, CardHeader, Empty, Spinner, Stat } from "@/components/ui";
import { go } from "@/lib/nav";
import { errText, fmtTime, onto, PRIORITY_TONE, STATUS_LABEL, type RuntimeOverview } from "@/lib/onto";
import { toast } from "@/store/useAppStore";
const VIA: Record<string, string> = { agent: "外部 Agent", console: "在线调试", ask: "提问" };
/**
* 运行时总览:本体上线后,Agent 怎么在用它 —— MCP 调用量与成功率、最常用的工具、
* 待审批动作(按优先级)、流程卡运行、数据管道同步状态。
*/
export function OverviewPage() {
const [d, setD] = useState<RuntimeOverview | null>(null);
const load = useCallback(() => { void onto.runtimeOverview().then(setD).catch((e) => toast("error", errText(e))); }, []);
useEffect(load, [load]);
if (!d) return <Spinner />;
const rate = d.mcp.success_rate === null ? "-" : `${Math.round(d.mcp.success_rate * 100)}%`;
const live = Object.entries(d.runcards).reduce((a, [, n]) => a + n, 0);
return (
<div className="mx-auto max-w-6xl space-y-4">
<div className="flex items-center gap-2">
<p className="flex-1 text-[12px] text-muted">本体经 MCP 暴露给 Agent(含系统自带的「提问」):所有调用都可追溯,写操作一律先成审批单。</p>
<button className="btn btn-sm" onClick={load}><RefreshCw className="h-3.5 w-3.5" />刷新</button>
</div>
<Card className="grid gap-4 p-4 sm:grid-cols-5">
<Stat label="24h MCP 调用" value={d.mcp.calls_24h} hint={Object.entries(d.mcp.by_via).map(([k, v]) => `${VIA[k] || k} ${v}`).join(" · ") || "暂无"} />
<Stat label="成功率" value={rate} tone={d.mcp.success_rate !== null && d.mcp.success_rate < 0.9 ? "text-warn" : ""} />
<Stat label="待审批动作" value={d.approvals.pending} tone={d.approvals.pending ? "text-warn" : ""}
hint={Object.entries(d.approvals.by_priority).map(([k, v]) => `${k} ${v}`).join(" · ")} />
<Stat label="流程卡运行" value={live} hint={Object.entries(d.runcards).map(([k, v]) => `${STATUS_LABEL[k] || k} ${v}`).join(" · ")} />
<Stat label="关系边" value={d.pipelines.edges} hint={d.pipelines.synced_at ? `骨架截至 ${fmtTime(d.pipelines.synced_at)}` : "未同步"} />
</Card>
<div className="grid gap-4 lg:grid-cols-2">
<Card>
<CardHeader title={<span className="flex items-center gap-2"><Bot className="h-4 w-4" />最常用的工具(24h)</span>}
right={<button className="btn btn-ghost btn-sm" onClick={() => go("mcp")}>MCP 服务</button>} />
{!d.mcp.top_tools.length ? <Empty title="还没有调用" desc="在「MCP 服务」里在线调用,或把 MCP 地址接给你的 Agent。" /> : (
<table className="w-full text-[12.5px]">
<thead className="text-[11.5px] text-muted"><tr className="border-b border-line">
<th className="px-4 py-2 text-left">工具</th><th className="px-2 text-right">调用</th><th className="px-2 text-right">失败</th><th className="px-4 text-right">平均耗时</th></tr></thead>
<tbody>{d.mcp.top_tools.map((t) => (
<tr key={t.tool} className="border-b border-line/60">
<td className="px-4 py-1.5 font-mono">{t.tool}</td><td className="px-2 text-right tabular-nums">{t.calls}</td>
<td className="px-2 text-right tabular-nums">{t.failed ? <span className="text-bad">{t.failed}</span> : 0}</td>
<td className="px-4 text-right tabular-nums text-muted">{t.avg_ms} ms</td></tr>
))}</tbody>
</table>
)}
</Card>
<Card>
<CardHeader title={<span className="flex items-center gap-2"><ShieldCheck className="h-4 w-4" />待审批(按优先级)</span>}
right={<button className="btn btn-ghost btn-sm" onClick={() => go("inbox")}>审批中心</button>} />
<div className="divide-y divide-line">
{!d.approvals.top.length && <Empty title="没有待审批的动作" />}
{d.approvals.top.map((r) => (
<button key={r.id} className="flex w-full items-center gap-2 px-4 py-2 text-left text-[12.5px] hover:bg-ink/[0.03]" onClick={() => go("inbox", { run: r.id })}>
<Badge tone={PRIORITY_TONE[r.priority]}>{r.priority}</Badge>
<span className="font-medium">{r.action_name}</span>
<span className="min-w-0 flex-1 truncate text-muted">{r.reason}</span>
<span className="text-[11px] text-muted">{fmtTime(r.created_at)}</span>
</button>
))}
</div>
</Card>
<Card>
<CardHeader title={<span className="flex items-center gap-2"><Workflow className="h-4 w-4" />数据管道</span>}
right={<button className="btn btn-ghost btn-sm" onClick={() => go("pipeline")}>管理</button>} />
<div className="divide-y divide-line">
{!d.pipelines.items.length && <Empty title="还没有数据管道" />}
{d.pipelines.items.map((p) => (
<div key={p.id} className="flex items-center gap-2 px-4 py-2 text-[12.5px]">
<Activity className={`h-3.5 w-3.5 ${p.status === "failed" ? "text-bad" : p.status === "ok" ? "text-ok" : "text-muted"}`} />
<span className="font-medium">{p.object_type}</span>
<span className="text-muted">{p.last_rows} 个 · {p.last_edges} 边</span>
<span className="ml-auto text-[11px] text-muted">{fmtTime(p.last_run_at)}</span>
</div>
))}
</div>
</Card>
<Card>
<CardHeader title={<span className="flex items-center gap-2"><ListChecks className="h-4 w-4" />动作执行</span>} />
<div className="flex flex-wrap gap-2 p-4">
{Object.entries(d.actions).map(([k, v]) => <Badge key={k}>{STATUS_LABEL[k] || k} {v}</Badge>)}
{!Object.keys(d.actions).length && <p className="text-[12px] text-muted">还没有动作</p>}
</div>
</Card>
</div>
</div>
);
}
...@@ -5,11 +5,11 @@ import { useCallback, useEffect, useMemo, useState } from "react"; ...@@ -5,11 +5,11 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import { Badge, Card, CardHeader, Empty, Field, Modal, Segmented, Spinner } from "@/components/ui"; import { Badge, Card, CardHeader, Empty, Field, Modal, Segmented, Spinner } from "@/components/ui";
import { go, useHashParams } from "@/lib/nav"; import { go, useHashParams } from "@/lib/nav";
import { import {
errText, fmtTime, onto, STATUS_LABEL, STATUS_TONE, type ConceptBrief, type Me, type SopBrief, type SopDef, type SopRun, errText, fmtTime, onto, PRIORITY_TONE, STATUS_LABEL, STATUS_TONE, type ConceptBrief, type Me, type SopBrief, type SopDef, type SopRun,
type SopSpec, type SopStep, type SopSpec, type SopStep,
} from "@/lib/onto"; } from "@/lib/onto";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { promptText } from "@/lib/dialog"; import { confirmDialog, promptText } from "@/lib/dialog";
import { toast } from "@/store/useAppStore"; import { toast } from "@/store/useAppStore";
import { SopFlow, STEP_COLOR, STEP_LABEL } from "./SopFlow"; import { SopFlow, STEP_COLOR, STEP_LABEL } from "./SopFlow";
import { StepEditor, type Catalog } from "./StepEditor"; import { StepEditor, type Catalog } from "./StepEditor";
...@@ -27,6 +27,10 @@ export function SopPage({ me }: { me: Me | null }) { ...@@ -27,6 +27,10 @@ export function SopPage({ me }: { me: Me | null }) {
const [runId, setRunId] = useState(params.get("run") || ""); const [runId, setRunId] = useState(params.get("run") || "");
const [cat, setCat] = useState<Catalog | null>(null); const [cat, setCat] = useState<Catalog | null>(null);
const [draftOpen, setDraftOpen] = useState(false); const [draftOpen, setDraftOpen] = useState(false);
const [q, setQ] = useState("");
const [only, setOnly] = useState<"" | "published" | "draft">("");
const shown = list.filter((s) => (!q || `${s.title} ${s.description} ${s.domain || ""}`.includes(q))
&& (!only || (only === "published" ? s.status === "published" : s.status !== "published")));
const load = useCallback(() => { void onto.sops().then(setList); }, []); const load = useCallback(() => { void onto.sops().then(setList); }, []);
useEffect(() => { useEffect(() => {
...@@ -47,22 +51,32 @@ export function SopPage({ me }: { me: Me | null }) { ...@@ -47,22 +51,32 @@ export function SopPage({ me }: { me: Me | null }) {
<div className="grid gap-4 lg:grid-cols-[280px_minmax(0,1fr)]"> <div className="grid gap-4 lg:grid-cols-[280px_minmax(0,1fr)]">
<Card className="flex max-h-[calc(100vh-140px)] flex-col self-start"> <Card className="flex max-h-[calc(100vh-140px)] flex-col self-start">
<CardHeader title="流程库" right={canEdit && <> <CardHeader title="流程库" right={canEdit && <>
<button className="btn btn-sm" onClick={() => setDraftOpen(true)} title="AI 从文档起草"><Wand2 className="h-3.5 w-3.5" /></button> <button className="btn btn-sm" onClick={() => setDraftOpen(true)} title="AI 从文档起草"><Wand2 className="h-3.5 w-3.5" />AI 起草</button>
<button className="btn btn-sm" onClick={async () => { <button className="btn btn-sm" onClick={async () => {
const title = await promptText("流程名称"); if (!title) return; const title = await promptText("流程名称"); if (!title) return;
const d = await onto.createSop({ title }); load(); go("sop", { id: d.id }); const d = await onto.createSop({ title }); load(); go("sop", { id: d.id });
}}><Plus className="h-3.5 w-3.5" /></button> }} title="手动新建"><Plus className="h-3.5 w-3.5" />新建</button>
</>} /> </>} />
<div className="space-y-1.5 border-b border-line p-2">
<input className="input h-8" placeholder="搜索名称 / 说明 / 域" value={q} onChange={(e) => setQ(e.target.value)} />
<Segmented value={only} onChange={setOnly} options={[{ key: "", label: "全部" }, { key: "published", label: "已发布" }, { key: "draft", label: "草稿" }]} />
</div>
<div className="min-h-0 flex-1 overflow-auto"> <div className="min-h-0 flex-1 overflow-auto">
{!list.length && <Empty icon={<ListChecks className="h-10 w-10" />} title="还没有流程" desc="手动新建,或让 AI 从文档里起草。" />} {!list.length && <Empty icon={<ListChecks className="h-10 w-10" />} title="还没有流程" desc="手动新建,让 AI 从文档里起草,或在「业务建模」里从业务文档蒸馏。" />}
{list.map((s) => ( {shown.map((s) => (
<button key={s.id} onClick={() => go("sop", { id: s.id })} <button key={s.id} onClick={() => go("sop", { id: s.id })}
className={cn("block w-full border-b border-line/60 px-3 py-2.5 text-left hover:bg-ink/[0.03]", sel === s.id && !runId && "bg-brand/5")}> className={cn("block w-full border-b border-line/60 px-3 py-2.5 text-left hover:bg-ink/[0.03]", sel === s.id && !runId && "bg-brand/5")}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">{s.title}</span> <span className="min-w-0 flex-1 truncate text-[13px] font-medium">{s.title}</span>
{s.ai_generated && <Sparkles className="h-3 w-3 text-brand" />} {s.ai_generated && <Sparkles className="h-3 w-3 text-brand" />}
{s.priority && s.priority !== "P2" && <Badge tone={PRIORITY_TONE[s.priority]}>{s.priority}</Badge>}
<Badge tone={STATUS_TONE[s.status]}>{s.status === "published" ? `v${s.current_version}` : STATUS_LABEL[s.status]}</Badge> <Badge tone={STATUS_TONE[s.status]}>{s.status === "published" ? `v${s.current_version}` : STATUS_LABEL[s.status]}</Badge>
</div> </div>
{(s.step_types || []).length > 0 && (
<p className="mt-0.5 flex flex-wrap items-center gap-0.5">{(s.step_types || []).filter((t) => t !== "end").map((t, i) => (
<span key={i} className="rounded bg-ink/[0.05] px-1 text-[10px] text-muted">{STEP_LABEL[t] || t}</span>))}
{s.domain && <span className="ml-1 text-[10.5px] text-brand">#{s.domain}</span>}</p>
)}
<p className="text-[11px] text-muted">{s.step_count} 步 · {s.trigger_kind === "manual" ? "手动" : s.trigger_kind === "schedule" ? "定时" : "指标触发"} · 运行 {s.run_count || 0} 次</p> <p className="text-[11px] text-muted">{s.step_count} 步 · {s.trigger_kind === "manual" ? "手动" : s.trigger_kind === "schedule" ? "定时" : "指标触发"} · 运行 {s.run_count || 0} 次</p>
</button> </button>
))} ))}
...@@ -148,6 +162,10 @@ function SopEditor({ id, cat, canEdit, me, onChanged }: { id: string; cat: Catal ...@@ -148,6 +162,10 @@ function SopEditor({ id, cat, canEdit, me, onChanged }: { id: string; cat: Catal
{dirty && <Badge tone="bg-warn/10 text-warn">未保存</Badge>}</span>} {dirty && <Badge tone="bg-warn/10 text-warn">未保存</Badge>}</span>}
desc={d.description || "(无说明)"} desc={d.description || "(无说明)"}
right={<> right={<>
{canEdit && <button className="btn btn-ghost btn-sm" title="不再使用:从流程库里移走(运行记录保留)" onClick={async () => {
if (!(await confirmDialog(`归档流程「${d.title}」?`, { desc: "归档后不再出现在流程库,也不能再运行;历史运行记录保留。", danger: true }))) return;
try { await onto.archiveSop(id); toast("ok", "已归档"); onChanged(); go("sop"); } catch (e) { toast("error", errText(e)); }
}}>归档</button>}
{canEdit && <button className="btn btn-sm" disabled={busy || !dirty} onClick={() => void save()}><Save className="h-3.5 w-3.5" />保存草稿</button>} {canEdit && <button className="btn btn-sm" disabled={busy || !dirty} onClick={() => void save()}><Save className="h-3.5 w-3.5" />保存草稿</button>}
{canEdit && <button className="btn btn-sm" disabled={dirty || val.errors.length > 0} title={dirty ? "先保存" : ""} {canEdit && <button className="btn btn-sm" disabled={dirty || val.errors.length > 0} title={dirty ? "先保存" : ""}
onClick={() => setRunModal("dry")}><FlaskConical className="h-3.5 w-3.5" />试运行</button>} onClick={() => setRunModal("dry")}><FlaskConical className="h-3.5 w-3.5" />试运行</button>}
...@@ -262,6 +280,11 @@ function SetupTab({ spec, meta, canEdit, cat, onSpec, onMeta, defId, published } ...@@ -262,6 +280,11 @@ function SetupTab({ spec, meta, canEdit, cat, onSpec, onMeta, defId, published }
<Field label="名称"><input className="input" value={meta.title} disabled={!canEdit} onChange={(e) => onMeta({ ...meta, title: e.target.value })} /></Field> <Field label="名称"><input className="input" value={meta.title} disabled={!canEdit} onChange={(e) => onMeta({ ...meta, title: e.target.value })} /></Field>
<Field label="负责角色(审核发布)"><input className="input" list="sop-roles-2" value={meta.owner_role} disabled={!canEdit} onChange={(e) => onMeta({ ...meta, owner_role: e.target.value })} /> <Field label="负责角色(审核发布)"><input className="input" list="sop-roles-2" value={meta.owner_role} disabled={!canEdit} onChange={(e) => onMeta({ ...meta, owner_role: e.target.value })} />
<datalist id="sop-roles-2">{cat.roles.map((r) => <option key={r.id} value={r.name} />)}</datalist></Field> <datalist id="sop-roles-2">{cat.roles.map((r) => <option key={r.id} value={r.name} />)}</datalist></Field>
<div className="grid grid-cols-2 gap-2">
<Field label="优先级"><select className="input" value={spec.priority || "P2"} disabled={!canEdit} onChange={(e) => onSpec({ ...spec, priority: e.target.value })}>
{["P0", "P1", "P2", "P3"].map((x) => <option key={x}>{x}</option>)}</select></Field>
<Field label="域"><input className="input" placeholder="如 质量" value={spec.domain || ""} disabled={!canEdit} onChange={(e) => onSpec({ ...spec, domain: e.target.value })} /></Field>
</div>
<Field label="说明" className="sm:col-span-3"><textarea className="input" value={meta.description} disabled={!canEdit} onChange={(e) => onMeta({ ...meta, description: e.target.value })} /></Field> <Field label="说明" className="sm:col-span-3"><textarea className="input" value={meta.description} disabled={!canEdit} onChange={(e) => onMeta({ ...meta, description: e.target.value })} /></Field>
</Card> </Card>
<Card className="p-4"> <Card className="p-4">
......
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react"; import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
import { Field } from "@/components/ui"; import { Field } from "@/components/ui";
import type { CapDef, ConceptBrief, FunctionBrief, SopSpec, SopStep } from "@/lib/onto"; import type { CapDef, FunctionBrief, SopSpec, SopStep } from "@/lib/onto";
import { JsonBox } from "../ontology/common"; import { JsonBox } from "../ontology/common";
import { STEP_COLOR, STEP_LABEL } from "./SopFlow"; import { STEP_COLOR, STEP_LABEL } from "./SopFlow";
......
...@@ -11,7 +11,7 @@ import { api } from "@/lib/api"; ...@@ -11,7 +11,7 @@ import { api } from "@/lib/api";
import { cn, formatDuration } from "@/lib/utils"; import { cn, formatDuration } from "@/lib/utils";
import { toast, useAppStore } from "@/store/useAppStore"; import { toast, useAppStore } from "@/store/useAppStore";
import { useSqlStore, type SqlTurn } from "@/store/useSqlStore"; import { useSqlStore, type SqlTurn } from "@/store/useSqlStore";
import { Badge, Card, Collapse, CopyButton, Empty, Spinner } from "@/components/ui"; import { Badge, Card, Collapse, CopyButton, Empty } from "@/components/ui";
import type { SqlPair } from "@/lib/types"; import type { SqlPair } from "@/lib/types";
import { SqlTrace } from "./SqlTrace"; import { SqlTrace } from "./SqlTrace";
......
import { import {
AlertTriangle, Database, Loader2, Plug, RefreshCw, ShieldCheck, Trash2, AlertTriangle, Database, FileSpreadsheet, FileUp, Globe, Loader2, Plug, RefreshCw, ShieldCheck, Trash2,
} from "lucide-react"; } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { api, ApiError } from "@/lib/api"; import { api, ApiError } from "@/lib/api";
...@@ -10,18 +10,33 @@ import { ...@@ -10,18 +10,33 @@ import {
} from "@/components/ui"; } from "@/components/ui";
import type { DataSource, JobItem } from "@/lib/types"; import type { DataSource, JobItem } from "@/lib/types";
const BLANK = { name: "", ds_type: "mysql", host: "", port: 3306, db_name: "", username: "", password: "" }; const BLANK = { name: "", ds_type: "mysql", host: "", port: 3306, db_name: "", username: "", password: "", schema: "public", tables: "", writeback: false };
export function DataSourcePanel({ selectedId, onSelect, onChanged }: { /** 新建连接时可选的类型。键是后端的 ds_type(= SQL 方言);MariaDB 走 MySQL 协议。 */
const KINDS: { key: string; ds_type: string; label: string; desc: string; port: number; group: string; soon?: boolean }[] = [
{ key: "mysql", ds_type: "mysql", label: "MySQL", desc: "5.7 / 8.x", port: 3306, group: "关系型数据库" },
{ key: "mariadb", ds_type: "mysql", label: "MariaDB", desc: "10.x / 11.x", port: 3306, group: "关系型数据库" },
{ key: "postgres", ds_type: "postgres", label: "PostgreSQL", desc: "13 / 14 / 15 / 16", port: 5432, group: "关系型数据库" },
{ key: "api", ds_type: "", label: "REST API", desc: "HTTP GET / POST · JSON 响应", port: 0, group: "API" },
{ key: "file", ds_type: "sqlite", label: "本地文件", desc: "CSV · Excel · JSON", port: 0, group: "文件" },
{ key: "nosql", ds_type: "", label: "MongoDB · Redis · ClickHouse · Elasticsearch", desc: "非关系型数据库", port: 0, group: "即将上线", soon: true },
];
const TYPE_LABEL: Record<string, string> = { mysql: "MySQL", postgres: "PostgreSQL", sqlite: "本地文件" };
export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }: {
selectedId: number | null; selectedId: number | null;
onSelect: (id: number) => void; onSelect: (id: number) => void;
onChanged: () => void; onChanged: () => void;
/** 选了 REST API:跳到「外部系统 / API」页签登记端点 */
onOpenApi?: () => void;
}) { }) {
const [items, setItems] = useState<DataSource[] | null>(null); const [items, setItems] = useState<DataSource[] | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [cryptoReady, setCryptoReady] = useState(true); const [cryptoReady, setCryptoReady] = useState(true);
const [editing, setEditing] = useState<DataSource | null>(null); const [editing, setEditing] = useState<DataSource | null>(null);
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
const [picking, setPicking] = useState(false);
const [fileDs, setFileDs] = useState<DataSource | "new" | null>(null);
const [confirmDel, setConfirmDel] = useState<DataSource | null>(null); const [confirmDel, setConfirmDel] = useState<DataSource | null>(null);
const [busy, setBusy] = useState<number | null>(null); const [busy, setBusy] = useState<number | null>(null);
const [job, setJob] = useState<{ dsId: number; item: JobItem | null } | null>(null); const [job, setJob] = useState<{ dsId: number; item: JobItem | null } | null>(null);
...@@ -120,15 +135,14 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged }: { ...@@ -120,15 +135,14 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged }: {
title="数据源" title="数据源"
desc="建议使用只读账号连接业务库。口令加密存储,不会明文落库,也不会回显。" desc="建议使用只读账号连接业务库。口令加密存储,不会明文落库,也不会回显。"
right={ right={
<button className="btn btn-primary btn-sm" disabled={!cryptoReady} <button className="btn btn-primary btn-sm" onClick={() => setPicking(true)}>
onClick={() => { setEditing({ ...BLANK } as unknown as DataSource); setCreating(true); }}> <Database className="h-3.5 w-3.5" /> 新建连接
<Database className="h-3.5 w-3.5" /> 新建
</button> </button>
} /> } />
{items.length === 0 ? ( {items.length === 0 ? (
<Empty icon={<Database className="h-6 w-6" />} title="还没有数据源" <Empty icon={<Database className="h-6 w-6" />} title="还没有数据源"
desc="添加一个 MySQL 连接,做一次内省,就能开始用自然语言提问了。" /> desc="接一个业务库(MySQL / PostgreSQL)或上传 CSV / Excel,做一次内省,就能映射对象、开始提问了。" />
) : ( ) : (
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{items.map((ds) => ( {items.map((ds) => (
...@@ -148,7 +162,8 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged }: { ...@@ -148,7 +162,8 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged }: {
)} )}
</span> </span>
<span className="mt-0.5 block truncate font-mono text-[11.5px] text-muted"> <span className="mt-0.5 block truncate font-mono text-[11.5px] text-muted">
{ds.username}@{ds.host}:{ds.port}/{ds.db_name} <Badge className="mr-1.5 font-sans">{TYPE_LABEL[ds.ds_type] || ds.ds_type}</Badge>
{ds.ds_type === "sqlite" ? "上传文件导入的只读库" : `${ds.username}@${ds.host}:${ds.port}/${ds.db_name}`}
</span> </span>
<span className="mt-0.5 block text-[11.5px] text-muted"> <span className="mt-0.5 block text-[11.5px] text-muted">
{ds.last_introspect_at {ds.last_introspect_at
...@@ -175,8 +190,10 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged }: { ...@@ -175,8 +190,10 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged }: {
onClick={() => introspect(ds)} title="抓取表结构并采样枚举列"> onClick={() => introspect(ds)} title="抓取表结构并采样枚举列">
<RefreshCw className="h-3.5 w-3.5" /> 内省 <RefreshCw className="h-3.5 w-3.5" /> 内省
</button> </button>
<button className="btn btn-ghost btn-sm" {ds.ds_type === "sqlite"
onClick={() => { setEditing(ds); setCreating(false); }}>编辑</button> ? <button className="btn btn-ghost btn-sm" onClick={() => setFileDs(ds)}><FileUp className="h-3.5 w-3.5" />追加文件</button>
: <button className="btn btn-ghost btn-sm"
onClick={() => { setEditing(ds); setCreating(false); }}>编辑</button>}
<button className="btn btn-ghost btn-sm text-bad" onClick={() => setConfirmDel(ds)} <button className="btn btn-ghost btn-sm text-bad" onClick={() => setConfirmDel(ds)}
title="删除数据源及其全部建模"> title="删除数据源及其全部建模">
<Trash2 className="h-3.5 w-3.5" /> <Trash2 className="h-3.5 w-3.5" />
...@@ -196,6 +213,37 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged }: { ...@@ -196,6 +213,37 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged }: {
)} )}
</Card> </Card>
<Modal open={picking} onClose={() => setPicking(false)} title="新建连接" width="max-w-2xl"
desc="关系型数据库直接连;API 在「外部系统 / API」登记;表格文件导入成只读库。">
<div className="space-y-3">
{[...new Set(KINDS.map((k) => k.group))].map((g) => (
<div key={g}>
<p className="mb-1.5 text-[11.5px] font-medium text-muted">{g}</p>
<div className="grid gap-2 sm:grid-cols-2">
{KINDS.filter((k) => k.group === g).map((k) => (
<button key={k.key} disabled={k.soon || (!cryptoReady && !!k.port)}
className="flex items-center gap-2.5 rounded-lg border border-line p-2.5 text-left hover:border-brand/40 disabled:opacity-50"
onClick={() => {
setPicking(false);
if (k.key === "api") { onOpenApi?.(); return; }
if (k.key === "file") { setFileDs("new"); return; }
setEditing({ ...BLANK, ds_type: k.ds_type, port: k.port } as unknown as DataSource); setCreating(true);
}}>
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand/10 text-brand">
{k.key === "api" ? <Globe className="h-4 w-4" /> : k.key === "file" ? <FileSpreadsheet className="h-4 w-4" /> : <Database className="h-4 w-4" />}</span>
<span className="min-w-0"><span className="block text-[13px] font-medium">{k.label}</span>
<span className="block text-[11.5px] text-muted">{k.desc}{k.port ? ` · 默认端口 ${k.port}` : ""}</span></span>
</button>
))}
</div>
</div>
))}
</div>
</Modal>
{fileDs && <FileSourceForm ds={fileDs === "new" ? null : fileDs} onClose={() => setFileDs(null)}
onSaved={(id) => { setFileDs(null); load(); onChanged(); onSelect(id); }} />}
<DataSourceForm <DataSourceForm
open={!!editing} creating={creating} initial={editing} open={!!editing} creating={creating} initial={editing}
onClose={() => setEditing(null)} onClose={() => setEditing(null)}
...@@ -225,21 +273,38 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: { ...@@ -225,21 +273,38 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
name: initial.name ?? "", ds_type: initial.ds_type ?? "mysql", host: initial.host ?? "", name: initial.name ?? "", ds_type: initial.ds_type ?? "mysql", host: initial.host ?? "",
port: initial.port ?? 3306, db_name: initial.db_name ?? "", port: initial.port ?? 3306, db_name: initial.db_name ?? "",
username: initial.username ?? "", password: "", username: initial.username ?? "", password: "",
schema: String((initial.extra as any)?.schema || "public"),
tables: String((initial.extra as any)?.tables || ""),
writeback: !!(initial.extra as any)?.writeback,
}); });
setPassword(""); setPassword("");
setErr(""); setErr("");
}, [initial]); }, [initial]);
const set = (k: string, v: string | number) => setForm((f) => ({ ...f, [k]: v })); const set = (k: string, v: string | number | boolean) => setForm((f) => ({ ...f, [k]: v }));
const save = async () => { const save = async () => {
setSaving(true); setSaving(true);
setErr(""); setErr("");
try { try {
const { schema, tables, writeback, ...rest } = form;
const extra: Record<string, string | boolean> = form.ds_type === "postgres" ? { schema: schema || "public" } : {};
if (tables.trim()) extra.tables = tables.trim();
if (writeback) extra.writeback = true;
if (creating) { if (creating) {
await api.createDatasource({ ...form, password }); const ds = await api.createDatasource({ ...rest, password, extra });
// 建完直接测连通、连通就内省:用户不必再回列表点两下
try {
await api.testDatasource(ds.id);
await api.introspect(ds.id);
toast("ok", "数据源已创建,连接成功", "正在读取表结构,完成后到「实体映射」把表建成对象");
} catch (e) {
toast("error", "数据源已保存,但连接失败", e instanceof Error ? e.message : String(e));
}
onSaved();
return;
} else if (initial) { } else if (initial) {
const body: Record<string, unknown> = { ...form }; const body: Record<string, unknown> = { ...rest, extra };
delete body.ds_type; delete body.ds_type;
// 留空 = 不改口令。前端不回显明文,所以必须能表达"没动过" // 留空 = 不改口令。前端不回显明文,所以必须能表达"没动过"
if (password) body.password = password; if (password) body.password = password;
...@@ -258,8 +323,8 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: { ...@@ -258,8 +323,8 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
return ( return (
<Modal <Modal
open={open} onClose={onClose} width="max-w-xl" open={open} onClose={onClose} width="max-w-xl"
title={creating ? "新建数据源" : "编辑数据源"} title={`${creating ? "新建" : "编辑"}${TYPE_LABEL[form.ds_type] || ""}数据源`}
desc="连上业务库之后,还要做一次内省才能开始提问。" desc="保存后自动测试连接、读取表结构;接着到「业务建模」让 AI 按业务文档起草本体。"
footer={ footer={
<> <>
{err && <p className="mr-auto min-w-0 flex-1 text-[12.5px] text-bad">{err}</p>} {err && <p className="mr-auto min-w-0 flex-1 text-[12.5px] text-bad">{err}</p>}
...@@ -290,6 +355,11 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: { ...@@ -290,6 +355,11 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
</Field> </Field>
</div> </div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{form.ds_type === "postgres" && (
<Field label="Schema" hint="只内省这个 schema 下的表">
<input className="input" value={form.schema} onChange={(e) => set("schema", e.target.value)} />
</Field>
)}
<Field label="数据库" required> <Field label="数据库" required>
<input className="input" value={form.db_name} placeholder="库名" <input className="input" value={form.db_name} placeholder="库名"
onChange={(e) => set("db_name", e.target.value)} /> onChange={(e) => set("db_name", e.target.value)} />
...@@ -309,10 +379,54 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: { ...@@ -309,10 +379,54 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
</Field> </Field>
</div> </div>
<Field label="表范围" hint="只接入这些表,逗号分隔,支持通配符,如 otlgt3_dm_*;留空 = 整个库。圈定的表会直接启用。">
<input className="input" value={form.tables} placeholder="otlgt3_dm_*"
onChange={(e) => set("tables", e.target.value)} />
</Field>
<label className="flex items-start gap-2 rounded-lg border border-line p-3 text-[12.5px]">
<input type="checkbox" className="mt-0.5" checked={form.writeback} onChange={(e) => set("writeback", e.target.checked)} />
<span><span className="font-medium">允许审批通过的动作写回业务库</span>
<span className="block text-[11.5px] text-muted">打开后,「新建采购单」「改状态」这类动作在人工审批通过后直接写进业务表(只限已绑定的表和列,可撤销);
关闭时只写在本系统的写回层,业务库不动。需要账号有写权限。</span></span>
</label>
<p className="text-[11.5px] leading-relaxed text-muted"> <p className="text-[11.5px] leading-relaxed text-muted">
目前只支持 MySQL。保存后回到列表点「测试」确认连得通,再点「内省」抓表结构。 保存后会自动测试连接并读取表结构。PostgreSQL 需要服务器装有 psycopg2 驱动。
</p> </p>
</div> </div>
</Modal> </Modal>
); );
} }
/** 本地文件:CSV / Excel(每个工作表一张表)/ JSON 导入成只读库,之后和数据库一样内省、映射、提问。 */
function FileSourceForm({ ds, onClose, onSaved }: { ds: DataSource | null; onClose: () => void; onSaved: (id: number) => void }) {
const [name, setName] = useState(ds?.name || "");
const [files, setFiles] = useState<File[]>([]);
const [busy, setBusy] = useState(false);
const save = async () => {
setBusy(true);
try {
const r = await api.createFileDatasource(name || files[0]?.name || "本地文件", files, ds?.id || 0);
toast("ok", `已导入 ${r.imported.length} 张表`, r.imported.map((t) => `${t.table}(${t.rows} 行)`).join("、"));
await api.introspect(r.id).catch(() => undefined);
onSaved(r.id);
} catch (e) { toast("error", "导入失败", e instanceof Error ? e.message : String(e)); } finally { setBusy(false); }
};
return (
<Modal open onClose={onClose} title={ds ? `向「${ds.name}」追加文件` : "本地文件数据源"}
desc="同名文件再次上传会覆盖原来那张表。导入后自动内省。"
footer={<><button className="btn btn-sm" onClick={onClose}>取消</button>
<button className="btn btn-primary btn-sm" disabled={busy || !files.length} onClick={() => void save()}>
{busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}导入</button></>}>
<div className="space-y-3">
{!ds && <Field label="名称"><input className="input" placeholder="如:产线日报(Excel)" value={name} onChange={(e) => setName(e.target.value)} /></Field>}
<Field label="文件" hint="支持 .csv .tsv .xlsx .xlsm .json;第一行是表头">
<input type="file" multiple accept=".csv,.tsv,.xlsx,.xlsm,.json" className="input"
onChange={(e) => setFiles(Array.from(e.target.files || []))} />
</Field>
{files.map((f) => <p key={f.name} className="text-[12px] text-muted">{f.name} · {Math.ceil(f.size / 1024)} KB</p>)}
</div>
</Modal>
);
}
import { Boxes, ChevronDown, ChevronRight, Link2, Plus, Search } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Badge, Card, CardHeader, Empty, Spinner } from "@/components/ui";
import { api } from "@/lib/api";
import { go } from "@/lib/nav";
import { errText, onto } from "@/lib/onto";
import type { SmModel } from "@/lib/types";
import { toast } from "@/store/useAppStore";
/**
* 表 → 实体映射:数据源里的每张表映射到了哪个对象类型。
* 没映射的表可以一键建成对象(属性 = 列,并绑定这张表),之后在对象编辑器里微调。
*/
export function MappingPanel({ dsId, canEdit }: { dsId: number; canEdit: boolean }) {
const [models, setModels] = useState<SmModel[] | null>(null);
const [map, setMap] = useState<Record<string, { concept_id: string; name: string; status: string }[]>>({});
const [q, setQ] = useState("");
const [open, setOpen] = useState<Set<number>>(new Set());
const [busy, setBusy] = useState(0);
const load = useCallback(() => {
void api.sqlModels(dsId).then(setModels).catch(() => setModels([]));
void onto.mappings(dsId).then(setMap).catch(() => setMap({}));
}, [dsId]);
useEffect(load, [load]);
const shown = useMemo(() => (models || []).filter((m) => !q || `${m.name} ${m.description}`.includes(q)), [models, q]);
const mappedN = (models || []).filter((m) => map[m.physical_table || m.name]?.length).length;
const createObject = async (m: SmModel) => {
setBusy(m.id);
try {
const cols = m.columns || [];
const key = m.primary_key || cols.find((c) => c.name.toLowerCase() === "id")?.name || cols[0]?.name || "";
const label = cols.find((c) => /name|title|label|名称/i.test(c.name))?.name || "";
const props = cols.slice(0, 60).map((c) => ({
name: c.name, display_name: (c.description || "").slice(0, 40), description: c.description || "",
data_type: c.is_measure || /int|dec|double|float|real|numeric/i.test(c.data_type) ? "number"
: /date|time/i.test(c.data_type) ? "date" : "string",
is_key: c.name === key, is_dimension: !!c.is_dimension,
}));
const name = (m.description || "").split(/[,。,]/)[0].slice(0, 30) || m.name;
const c = await onto.createConcept({ kind: "object_type", name, synonyms: name !== m.name ? [m.name] : [],
description: m.description, spec: { properties: props, label_property: label } });
await onto.setBinding(c.id, { ds_id: dsId, target_kind: "table", ref: {
table: m.physical_table || m.name, key_column: cols.find((x) => x.name === key)?.physical_column || key,
label_column: cols.find((x) => x.name === label)?.physical_column || label,
columns: Object.fromEntries(cols.slice(0, 60).map((x) => [x.name, x.physical_column || x.name])) } });
toast("ok", `已建对象「${c.name}」并绑定到 ${m.name}`, "是草稿:在对象类型里补属性含义,再提交变更提案");
load();
} catch (e) { toast("error", "创建失败", errText(e)); } finally { setBusy(0); }
};
if (!models) return <Card className="p-4"><Spinner /></Card>;
return (
<Card>
<CardHeader title={`表 · ${models.length} 张 · 已映射 ${mappedN}`}
desc="每张表映射成一个对象类型(表 = 对象,行 = 实例,列 = 属性)。映射后才能被查询、遍历、写回。"
right={<div className="relative"><Search className="absolute left-2 top-2 h-3.5 w-3.5 text-muted" />
<input className="input h-8 w-52 pl-7" placeholder="搜表名 / 描述" value={q} onChange={(e) => setQ(e.target.value)} /></div>} />
{!models.length ? <Empty title="还没有内省过" desc="回到「数据源」点「内省」抓表结构。" /> : (
<div className="divide-y divide-line">
{shown.map((m) => {
const hit = map[m.physical_table || m.name] || [];
const isOpen = open.has(m.id);
return (
<div key={m.id}>
<div className="flex items-center gap-2 px-4 py-2 text-[12.5px]">
<button className="text-muted" onClick={() => { const n = new Set(open); if (isOpen) n.delete(m.id); else n.add(m.id); setOpen(n); }}>
{isOpen ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}</button>
<span className="font-mono font-medium">{m.name}</span>
<span className="min-w-0 flex-1 truncate text-muted">{m.description || ""}</span>
<span className="w-14 text-right text-[11px] text-muted">{m.columns?.length || 0} 列</span>
{!m.enabled && <Badge>未启用</Badge>}
{hit.length ? hit.map((h) => (
<button key={h.concept_id} className="chip text-ok" onClick={() => go("b_object", { id: h.concept_id })}>
<Link2 className="h-3 w-3" />{h.name}</button>
)) : canEdit ? (
<button className="btn btn-sm" disabled={!!busy} onClick={() => void createObject(m)}>
{busy === m.id ? <Spinner className="h-3.5 w-3.5" /> : <Plus className="h-3.5 w-3.5" />}配置实体映射</button>
) : <Badge tone="bg-warn/10 text-warn">未映射</Badge>}
</div>
{isOpen && (
<div className="flex flex-wrap gap-1 bg-ink/[0.02] px-10 py-2">
{(m.columns || []).map((c) => (
<span key={c.id} className="rounded border border-line bg-surface px-1.5 py-0.5 font-mono text-[11px]" title={c.description}>
{c.name}<span className="ml-1 text-muted">{c.data_type}</span></span>
))}
</div>
)}
</div>
);
})}
</div>
)}
<p className="flex items-center gap-1.5 border-t border-line px-4 py-2 text-[11.5px] text-muted"><Boxes className="h-3.5 w-3.5" />
也可以在「业务建模」里让 AI 一次把所有已启用的表提议成对象与关系。</p>
</Card>
);
}
import { BookmarkCheck, Database, Gauge, MessagesSquare, Table2 } from "lucide-react"; import { BookmarkCheck, Boxes, Database, Gauge, Globe, MessagesSquare, Table2 } from "lucide-react";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { api } from "@/lib/api"; import { api } from "@/lib/api";
import { go } from "@/lib/nav"; import { go, useHashParams } from "@/lib/nav";
import { errText, onto } from "@/lib/onto"; import { errText, onto, type Me } from "@/lib/onto";
import { toast } from "@/store/useAppStore"; import { toast } from "@/store/useAppStore";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Card, Empty, Segmented, Spinner } from "@/components/ui"; import { Card, Empty, Segmented, Spinner } from "@/components/ui";
import type { DataSource } from "@/lib/types"; import type { DataSource } from "@/lib/types";
import { CapabilityPage } from "../capability/CapabilityPage";
import { AskPanel } from "./AskPanel"; import { AskPanel } from "./AskPanel";
import { DataSourcePanel } from "./DataSourcePanel"; import { DataSourcePanel } from "./DataSourcePanel";
import { LibraryPanel } from "./LibraryPanel"; import { LibraryPanel } from "./LibraryPanel";
import { MappingPanel } from "./MappingPanel";
import { ModelingPanel } from "./ModelingPanel"; import { ModelingPanel } from "./ModelingPanel";
import { RulesPanel } from "./RulesPanel"; import { RulesPanel } from "./RulesPanel";
type Tab = "ask" | "sources" | "modeling" | "metrics" | "library"; type Tab = "ask" | "sources" | "mapping" | "modeling" | "metrics" | "library" | "api";
// 业务提问已经统一到「提问」页;这里是数据连接与物理建模的建设台, // 数据连接:数据库 / 文件数据源、表 → 实体映射、外部系统 / API。
// 「SQL 调试台」保留给实施人员直接调试取数。 // 业务提问统一在「提问」页;「SQL 调试台」保留给实施人员直接调试取数。
const TABS: { key: Tab; label: string; icon: React.ReactNode }[] = [ const TABS: { key: Tab; label: string; icon: React.ReactNode }[] = [
{ key: "sources", label: "数据源", icon: <Database className="h-3.5 w-3.5" /> }, { key: "sources", label: "数据源", icon: <Database className="h-3.5 w-3.5" /> },
{ key: "modeling", label: "建模", icon: <Table2 className="h-3.5 w-3.5" /> }, { key: "mapping", label: "实体映射", icon: <Boxes className="h-3.5 w-3.5" /> },
{ key: "modeling", label: "表结构", icon: <Table2 className="h-3.5 w-3.5" /> },
{ key: "metrics", label: "取数规则", icon: <Gauge className="h-3.5 w-3.5" /> }, { key: "metrics", label: "取数规则", icon: <Gauge className="h-3.5 w-3.5" /> },
{ key: "library", label: "沉淀库", icon: <BookmarkCheck className="h-3.5 w-3.5" /> }, { key: "library", label: "沉淀库", icon: <BookmarkCheck className="h-3.5 w-3.5" /> },
{ key: "ask", label: "SQL 调试台", icon: <MessagesSquare className="h-3.5 w-3.5" /> }, { key: "ask", label: "SQL 调试台", icon: <MessagesSquare className="h-3.5 w-3.5" /> },
{ key: "api", label: "外部系统 / API", icon: <Globe className="h-3.5 w-3.5" /> },
]; ];
export function SqlPage() { export function SqlPage({ me }: { me: Me | null }) {
const [tab, setTab] = useState<Tab>("sources"); const params = useHashParams();
const [tab, setTab] = useState<Tab>((params.get("tab") as Tab) || "sources");
useEffect(() => { const t = params.get("tab") as Tab | null; if (t && TABS.some((x) => x.key === t)) setTab(t); }, [params]);
const [sources, setSources] = useState<DataSource[] | null>(null); const [sources, setSources] = useState<DataSource[] | null>(null);
const [dsId, setDsId] = useState<number | null>(null); const [dsId, setDsId] = useState<number | null>(null);
...@@ -41,7 +47,7 @@ export function SqlPage() { ...@@ -41,7 +47,7 @@ export function SqlPage() {
// 一个数据源都没有时,直接把人带到数据源页 —— 其余几个页签这时都是空的 // 一个数据源都没有时,直接把人带到数据源页 —— 其余几个页签这时都是空的
useEffect(() => { useEffect(() => {
if (sources && sources.length === 0) setTab("sources"); if (sources && sources.length === 0) setTab((t) => (t === "api" ? t : "sources"));
}, [sources]); }, [sources]);
const current = sources?.find((s) => s.id === dsId) ?? null; const current = sources?.find((s) => s.id === dsId) ?? null;
...@@ -74,7 +80,7 @@ export function SqlPage() { ...@@ -74,7 +80,7 @@ export function SqlPage() {
try { try {
const r = await onto.proposeFromDatasource(current.id); const r = await onto.proposeFromDatasource(current.id);
toast("ok", `提议 ${r.proposed} 块积木`, `冲突 ${r.conflicts},补充 ${r.enriched}。到业务建模里审核`); toast("ok", `提议 ${r.proposed} 块积木`, `冲突 ${r.conflicts},补充 ${r.enriched}。到业务建模里审核`);
go("wizard"); go("modeling");
} catch (e) { toast("error", "提议失败", errText(e)); } } catch (e) { toast("error", "提议失败", errText(e)); }
}}>提议到本体</button> }}>提议到本体</button>
)} )}
...@@ -84,12 +90,14 @@ export function SqlPage() { ...@@ -84,12 +90,14 @@ export function SqlPage() {
<div className={cn("min-h-0 flex-1", tab === "ask" ? "overflow-hidden" : "overflow-auto")}> <div className={cn("min-h-0 flex-1", tab === "ask" ? "overflow-hidden" : "overflow-auto")}>
{!sources ? ( {!sources ? (
<Card className="p-4"><Spinner /></Card> <Card className="p-4"><Spinner /></Card>
) : tab === "api" ? (
<CapabilityPage me={me} />
) : tab === "sources" ? ( ) : tab === "sources" ? (
<DataSourcePanel selectedId={dsId} onSelect={setDsId} onChanged={load} /> <DataSourcePanel selectedId={dsId} onSelect={setDsId} onChanged={load} onOpenApi={() => setTab("api")} />
) : !current ? ( ) : !current ? (
<Card> <Card>
<Empty icon={<Database className="h-6 w-6" />} title="还没有数据源" <Empty icon={<Database className="h-6 w-6" />} title="还没有数据源"
desc="先到「数据源」页添加一个 MySQL 连接。" desc="先到「数据源」页添加一个数据库连接或上传表格文件。"
action={ action={
<button className="btn btn-primary btn-sm" onClick={() => setTab("sources")}> <button className="btn btn-primary btn-sm" onClick={() => setTab("sources")}>
去添加 去添加
...@@ -98,6 +106,8 @@ export function SqlPage() { ...@@ -98,6 +106,8 @@ export function SqlPage() {
</Card> </Card>
) : tab === "ask" ? ( ) : tab === "ask" ? (
<AskPanel dsId={current.id} dsName={current.name} /> <AskPanel dsId={current.id} dsName={current.name} />
) : tab === "mapping" ? (
<MappingPanel dsId={current.id} canEdit={!!me?.permissions.includes("build")} />
) : tab === "modeling" ? ( ) : tab === "modeling" ? (
<ModelingPanel dsId={current.id} /> <ModelingPanel dsId={current.id} />
) : tab === "metrics" ? ( ) : tab === "metrics" ? (
......
import { ArrowRight, CheckCircle2, ClipboardList, MessageSquareText, Play, Send, ShieldCheck, Sparkles, TrendingDown, TrendingUp } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Card, CardHeader, Empty, Spinner } from "@/components/ui";
import { go } from "@/lib/nav";
import { errText, fmtTime, onto, PRIORITY_TONE, type Workbench } from "@/lib/onto";
import { toast } from "@/store/useAppStore";
const RUN_STATUS: Record<string, [string, string]> = {
pending_approval: ["待审批", "bg-warn/10 text-warn"], done: ["已执行", "bg-ok/10 text-ok"],
rejected: ["已驳回", "bg-bad/10 text-bad"], failed: ["执行失败", "bg-bad/10 text-bad"],
cancelled: ["已撤回", "bg-ink/5 text-muted"], reverted: ["已撤销", "bg-ink/5 text-muted"],
};
function fmtValue(v: any, unit: string) {
if (v === null || v === undefined || v === "") return "—";
const n = Number(v);
if (Number.isNaN(n)) return String(v);
const s = Math.abs(n) >= 1000 ? n.toLocaleString("zh-CN", { maximumFractionDigits: 0 })
: n.toLocaleString("zh-CN", { maximumFractionDigits: 1 });
return unit === "%" ? `${s}%` : s;
}
/**
* 工作台:老板和员工每天打开系统的第一页。不讲本体、积木、管道这些搭建期的概念,
* 只回答「数字怎么样、有什么等我处理、我提交的办得怎样、常用的事一点就做」。
*/
export function WorkbenchPage() {
const [w, setW] = useState<Workbench | null>(null);
const [q, setQ] = useState("");
const [running, setRunning] = useState("");
const load = useCallback(() => { void onto.workbench().then(setW).catch((e) => toast("error", "加载失败", errText(e))); }, []);
useEffect(load, [load]);
if (!w) return <div className="p-8"><Spinner /></div>;
const askNow = (text: string) => { if (text.trim()) go("ask", { q: text.trim() }); };
const runSop = async (id: string, title: string) => {
setRunning(id);
try {
const r = await onto.runSop(id, {});
toast("ok", `已启动「${title}」`, "取数会自动跑完,需要人处理的步骤会出现在待办里");
go("sop", { id, run: r.id });
} catch (e) { toast("error", "启动失败", errText(e)); } finally { setRunning(""); }
};
const today = new Date().toLocaleDateString("zh-CN", { month: "long", day: "numeric", weekday: "long" });
const todoCount = w.todo.approvals_total + w.todo.releases.length + w.todo.tasks.length;
return (
<div className="mx-auto max-w-6xl space-y-4">
<Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.08), transparent 60%)" }}>
<p className="text-[16px] font-semibold">{w.user.name},你好</p>
<p className="mt-0.5 text-[12.5px] text-muted">
{today}{w.user.biz_roles.length ? ` · ${w.user.biz_roles.join("、")}` : ""}
{todoCount ? ` · 有 ${todoCount} 件事等你处理` : " · 暂时没有等你处理的事"}
</p>
<div className="mt-3 flex gap-2">
<div className="relative min-w-0 flex-1">
<MessageSquareText className="absolute left-2.5 top-2.5 h-4 w-4 text-muted" />
<input className="input h-10 pl-8 text-[13.5px]" value={q} placeholder="直接问:哪些商品快缺货了?帮我给上海仓补抽纸……"
onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") askNow(q); }} />
</div>
<button className="btn btn-primary h-10" disabled={!q.trim()} onClick={() => askNow(q)}><Send className="h-4 w-4" />提问</button>
</div>
{w.questions.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1.5">
{w.questions.map((x) => (
<button key={x} className="chip hover:border-brand/50 hover:text-brand" onClick={() => askNow(x)}><Sparkles className="h-3 w-3" />{x}</button>
))}
</div>
)}
</Card>
{w.kpis.length > 0 ? (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{w.kpis.map((k) => (
<button key={k.name} className="card p-3 text-left hover:border-brand/40" title={k.formula}
onClick={() => askNow(k.dimensions[0] ? `${k.name}按${k.dimensions[0]}拆开看` : `${k.name}是怎么算出来的?`)}>
<p className="flex items-center gap-1 text-[12px] text-muted">{k.name}
{k.direction === "higher_better" && <TrendingUp className="h-3 w-3" />}
{k.direction === "lower_better" && <TrendingDown className="h-3 w-3" />}</p>
<p className="mt-1 text-[24px] font-semibold tabular-nums">{fmtValue(k.value, k.unit)}
{k.unit && k.unit !== "%" && <span className="ml-1 text-[12px] font-normal text-muted">{k.unit}</span>}</p>
<p className="mt-0.5 truncate text-[11px] text-muted">{k.formula || "点击查看明细"}</p>
</button>
))}
</div>
) : (
<Card className="p-4 text-[12.5px] text-muted">还没有可展示的指标。实施人员在「业务建模」里发布带取数口径的指标后,这里会显示当天的数字。</Card>
)}
<div className="grid gap-4 lg:grid-cols-2 [&>*]:min-w-0">
<Card>
<CardHeader title={<span className="flex items-center gap-1.5"><ShieldCheck className="h-4 w-4" />等我处理</span>}
right={todoCount > 0 && <button className="btn btn-ghost btn-sm" onClick={() => go("inbox")}>全部<ArrowRight className="h-3.5 w-3.5" /></button>} />
<div className="divide-y divide-line">
{w.todo.approvals.map((r) => (
<button key={r.id} className="flex w-full items-start gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]"
onClick={() => go("inbox", { tab: "approvals", run: r.id })}>
<Badge tone={PRIORITY_TONE[r.priority]}>{r.priority}</Badge>
<span className="min-w-0 flex-1">
<span className="block text-[13px] font-medium">审批:{r.action_name}</span>
<span className="block truncate text-[11.5px] text-muted">{r.summary}</span>
</span>
<span className="shrink-0 text-[11px] text-muted">{fmtTime(r.created_at)}</span>
</button>
))}
{w.todo.releases.map((r) => (
<button key={r.id} className="flex w-full items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" onClick={() => go("inbox", { tab: "releases" })}>
<Badge>变更</Badge><span className="min-w-0 flex-1 truncate text-[13px]">{r.title}</span>
</button>
))}
{w.todo.tasks.map((t) => (
<button key={t.id} className="flex w-full items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" onClick={() => go("inbox", { tab: "tasks" })}>
<ClipboardList className="h-4 w-4 text-brand" /><span className="min-w-0 flex-1 truncate text-[13px]">待办:{t.title}</span>
{t.due_at && <span className="text-[11px] text-muted">截止 {fmtTime(t.due_at)}</span>}
</button>
))}
{!todoCount && <Empty icon={<CheckCircle2 className="h-8 w-8" />} title="都处理完了" desc="有新的审批和待办会出现在这里" />}
</div>
</Card>
<Card>
<CardHeader title="我提交的" desc="提交的动作走到哪一步了" />
<div className="divide-y divide-line">
{w.mine.map((r) => {
const [label, tone] = RUN_STATUS[r.status] || [r.status, "bg-ink/5 text-muted"];
return (
<button key={r.id} className="flex w-full items-start gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]"
onClick={() => go("inbox", { tab: "runs", run: r.id })}>
<Badge tone={tone}>{label}</Badge>
<span className="min-w-0 flex-1">
<span className="block text-[13px] font-medium">{r.action_name}</span>
<span className="block truncate text-[11.5px] text-muted">{r.summary}</span>
</span>
<span className="shrink-0 text-[11px] text-muted">{fmtTime(r.created_at)}</span>
</button>
);
})}
{!w.mine.length && <Empty title="还没有提交过动作" desc="在提问里让 AI 帮你发起,或在对象页上直接发起" />}
</div>
</Card>
</div>
<div className="grid gap-4 lg:grid-cols-2 [&>*]:min-w-0">
<Card>
<CardHeader title="常用流程" desc="一点就跑:取数自动完成,需要人判断的步骤会派到待办" />
<div className="divide-y divide-line">
{w.sops.map((s) => (
<div key={s.id} className="flex items-center gap-2 px-4 py-2.5">
<span className="min-w-0 flex-1">
<span className="block text-[13px] font-medium">{s.title}</span>
<span className="block truncate text-[11.5px] text-muted">{s.description}</span>
</span>
<span className="text-[11px] text-muted">已运行 {s.run_count} 次</span>
{w.user.can_run
? <button className="btn btn-sm" disabled={!!running} onClick={() => void runSop(s.id, s.title)}>
{running === s.id ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}运行</button>
: <button className="btn btn-ghost btn-sm" onClick={() => go("sop", { id: s.id })}>查看</button>}
</div>
))}
{!w.sops.length && <Empty title="还没有发布的流程" />}
</div>
</Card>
<Card>
<CardHeader title="最近动态" right={<button className="btn btn-ghost btn-sm" onClick={() => go("audit")}>全部<ArrowRight className="h-3.5 w-3.5" /></button>} />
<div className="divide-y divide-line">
{w.feed.map((f, i) => (
<p key={i} className="flex gap-2 px-4 py-2 text-[12.5px]">
<span className="w-24 shrink-0 text-[11px] text-muted">{fmtTime(f.ts)}</span>
<span className="w-16 shrink-0 truncate text-muted">{f.actor}</span>
<span className="min-w-0 flex-1 truncate">{f.summary}</span>
</p>
))}
{!w.feed.length && <Empty title="暂无动态" />}
</div>
</Card>
</div>
</div>
);
}
...@@ -146,6 +146,15 @@ export const api = { ...@@ -146,6 +146,15 @@ export const api = {
datasources: () => req<DataSource[]>("/api/sql/datasources"), datasources: () => req<DataSource[]>("/api/sql/datasources"),
createDatasource: (body: Record<string, unknown>) => req<DataSource>("/api/sql/datasources", json(body)), createDatasource: (body: Record<string, unknown>) => req<DataSource>("/api/sql/datasources", json(body)),
/** 本地文件数据源:CSV / Excel / JSON 导入成只读 SQLite。传 dsId 表示追加到已有的文件数据源。 */
createFileDatasource: (name: string, files: File[], dsId = 0) => {
const fd = new FormData();
fd.append("name", name);
fd.append("ds_id", String(dsId));
files.forEach((f) => fd.append("files", f));
return req<DataSource & { imported: { table: string; file: string; rows: number; columns: number }[] }>(
"/api/sql/datasources/file", { method: "POST", body: fd });
},
updateDatasource: (id: number, body: Record<string, unknown>) => updateDatasource: (id: number, body: Record<string, unknown>) =>
req<DataSource>(`/api/sql/datasources/${id}`, put(body)), req<DataSource>(`/api/sql/datasources/${id}`, put(body)),
deleteDatasource: (id: number) => deleteDatasource: (id: number) =>
......
/** /**
* 当前身份。没有登录体系:界面右上角切换「以谁的身份操作」, * 当前身份。没有登录体系:界面右上角切换「以谁的身份操作」,
* 通过请求头 X-User-Id 带给后端 —— 审计、审批(四眼原则)、数据范围都按它算。 * 通过请求头 X-User-Id 带给后端 —— 审计、审批(四眼原则)、数据范围都按它算;
* 当前本体空间通过 X-Workspace 带上。
* *
* 在这里给全局 fetch 打一层补丁,而不是逐个调用点传头:SSE、下载、老页面的请求都自动带上。 * 在这里给全局 fetch 打一层补丁,而不是逐个调用点传头:SSE、下载、老页面的请求都自动带上。
*/ */
...@@ -25,6 +26,31 @@ export function onUserChange(fn: (id: string) => void): () => void { ...@@ -25,6 +26,31 @@ export function onUserChange(fn: (id: string) => void): () => void {
return () => listeners.delete(fn); return () => listeners.delete(fn);
} }
/**
* 当前本体空间。同一套系统里可以有多个本体(制造、零售……),积木、版本、动作、审计都按空间隔离。
* 没选过就不带请求头,由后端的默认空间(ONTO_WORKSPACE)决定。
*/
const WS_KEY = "onto.workspace";
const wsListeners = new Set<(id: string) => void>();
export function currentWorkspace(): string {
try {
return localStorage.getItem(WS_KEY) || "";
} catch {
return "";
}
}
export function setCurrentWorkspace(id: string) {
try { localStorage.setItem(WS_KEY, id); } catch { /* 隐私模式 */ }
wsListeners.forEach((fn) => fn(id));
}
export function onWorkspaceChange(fn: (id: string) => void): () => void {
wsListeners.add(fn);
return () => wsListeners.delete(fn);
}
let installed = false; let installed = false;
export function installIdentityFetch() { export function installIdentityFetch() {
...@@ -37,6 +63,8 @@ export function installIdentityFetch() { ...@@ -37,6 +63,8 @@ export function installIdentityFetch() {
if (!sameOrigin) return orig(input, init); if (!sameOrigin) return orig(input, init);
const headers = new Headers(init?.headers || (input instanceof Request ? input.headers : undefined)); const headers = new Headers(init?.headers || (input instanceof Request ? input.headers : undefined));
if (!headers.has("X-User-Id")) headers.set("X-User-Id", currentUserId()); if (!headers.has("X-User-Id")) headers.set("X-User-Id", currentUserId());
const ws = currentWorkspace();
if (ws && !headers.has("X-Workspace")) headers.set("X-Workspace", ws);
return orig(input, { ...init, headers }); return orig(input, { ...init, headers });
}; };
} }
/** /**
* 本体平台(v3)的类型与接口:内核、能力、SOP、统一提问、治理、评测。 * 本体平台的类型与接口:本体空间、内核、数据管道、业务建模、能力(动作 / MCP)、SOP、统一提问、治理、评测。
* 老的文档 / 图谱 / 数据连接接口仍在 api.ts。 * 老的文档 / 图谱 / 数据连接接口仍在 api.ts。
*/ */
import { ApiError } from "./api"; import { ApiError } from "./api";
...@@ -34,7 +34,7 @@ const qs = (p: Record<string, unknown>) => { ...@@ -34,7 +34,7 @@ const qs = (p: Record<string, unknown>) => {
// ============================== 类型 ============================== // ============================== 类型 ==============================
/** 本体只有四种积木;函数再按类别细分。 */ /** 本体只有四种积木;函数再按类别细分。 */
export type ConceptKind = "object_type" | "link_type" | "function" | "action"; export type ConceptKind = "object_type" | "link_type" | "function" | "action";
export type FnCategory = "aggregate" | "rule" | "calendar" | "decision" | "ai"; export type FnCategory = "aggregate" | "rule" | "calendar" | "decision" | "ml" | "ai";
/** 细分类型:函数取类别,其余就是积木种类。颜色、图标、分组都按它。 */ /** 细分类型:函数取类别,其余就是积木种类。颜色、图标、分组都按它。 */
export type TypeKey = "object_type" | "link_type" | FnCategory | "action"; export type TypeKey = "object_type" | "link_type" | FnCategory | "action";
...@@ -54,7 +54,9 @@ export interface ConceptBrief { ...@@ -54,7 +54,9 @@ export interface ConceptBrief {
category: FnCategory | ""; object_type: string; category: FnCategory | ""; object_type: string;
description: string; synonyms: string[]; status: "draft" | "published" | "deprecated"; description: string; synonyms: string[]; status: "draft" | "published" | "deprecated";
dirty: boolean; version: number; origin: string; published: boolean; updated_at: string | null; dirty: boolean; version: number; origin: string; published: boolean; updated_at: string | null;
created_by?: string; created_by?: string; domain?: string;
/** 是否已落到数据:对象有表、关系有 join、聚合有取数表达式;不需要绑定的积木为 null */
mapped?: boolean | null;
} }
export interface Concept extends ConceptBrief { export interface Concept extends ConceptBrief {
spec: any; bindings: Binding[]; evidence: Evidence[]; published_copy: any; spec: any; bindings: Binding[]; evidence: Evidence[]; published_copy: any;
...@@ -91,7 +93,7 @@ export interface DraftEvent { ...@@ -91,7 +93,7 @@ export interface DraftEvent {
ok?: boolean; error?: string; draft?: { kind: ConceptKind; name: string; description: string; synonyms: string[]; spec: any }; ok?: boolean; error?: string; draft?: { kind: ConceptKind; name: string; description: string; synonyms: string[]; spec: any };
samples?: { input: any; expect?: any }[]; samples?: { input: any; expect?: any }[];
} }
export interface McpTool { name: string; description: string; inputSchema: any } export interface McpTool { name: string; description: string; inputSchema: any; annotations?: { group?: string } }
export interface RoleRec { id: number; name: string; description: string; members: string[] } export interface RoleRec { id: number; name: string; description: string; members: string[] }
export interface RevisionRec { revision: number; note: string; diff: Diff; published_by: string; created_at: string; concepts: number } export interface RevisionRec { revision: number; note: string; diff: Diff; published_by: string; created_at: string; concepts: number }
export interface LinkResult { export interface LinkResult {
...@@ -121,6 +123,9 @@ export interface ActionRun { ...@@ -121,6 +123,9 @@ export interface ActionRun {
created_at: string; decided_at: string | null; finished_at: string | null; created_at: string; decided_at: string | null; finished_at: string | null;
approvals: { id: string; status: string; decided_by: string; comment: string; decided_at: string | null; approver_roles: string[] }[]; approvals: { id: string; status: string; decided_by: string; comment: string; decided_at: string | null; approver_roles: string[] }[];
can_approve?: boolean; cannot_reason?: string; can_approve?: boolean; cannot_reason?: string;
priority: "P0" | "P1" | "P2" | "P3";
evidence: { kind: string; text: string; ref: string }[];
impact: { by_type?: Record<string, number>; total?: number; sample?: { type_name: string; label: string; depth: number }[]; synced_at?: string };
} }
export interface TaskRec { export interface TaskRec {
id: string; title: string; description: string; role: string; assignee: string; id: string; title: string; description: string; role: string; assignee: string;
...@@ -135,7 +140,68 @@ export interface ReviewItem { ...@@ -135,7 +140,68 @@ export interface ReviewItem {
decided_by: string; comment: string; created_at: string; decided_at: string | null; decided_by: string; comment: string; created_at: string; decided_at: string | null;
} }
export interface NotificationRec { id: number; title: string; body: string; link: string; read: boolean; created_at: string } export interface NotificationRec { id: number; title: string; body: string; link: string; read: boolean; created_at: string }
export interface InboxCounts { approvals: number; tasks: number; reviews: number; review_counts: Record<string, number>; notifications: number } export interface InboxCounts { approvals: number; tasks: number; reviews: number; releases: number; review_counts: Record<string, number>; notifications: number }
export interface ReleaseItem extends ReviewItem { can_decide: boolean; cannot_reason: string }
export interface WorkspaceRec {
id: string; display_name: string; description: string; industry: string; status: string;
created_by: string; created_at: string; current?: boolean;
counts: { object_type: number; link_type: number; function: number; action: number; sop: number };
}
export interface HomeOverview {
workspace: WorkspaceRec; counts: WorkspaceRec["counts"];
mapped: { object_total: number; object_unmapped: number }; revision: number; dirty: number;
datasources: number; pipelines: { total: number; ok: number; failed: number; last_run_at: string | null };
pending_approvals: number; pending_reviews: number;
next_steps: { key: string; title: string; hint: string }[];
}
export interface PipelineRec {
id: string; object_type_id: string; object_type: string; schedule: "manual" | "hourly" | "daily";
row_limit: number; enabled: boolean; status: string; last_rows: number; last_edges: number;
last_error: string; last_run_at: string | null; last_duration_ms: number;
}
export interface TraverseNode {
id: string; type_id: string; type_name: string; key: string; label: string; depth: number;
via: { link: string; direction: "in" | "out"; from: string } | null; properties: Record<string, any>;
}
export interface TraverseResult {
root: { id: string; type_name: string; key: string; label: string }; depth: number;
nodes: TraverseNode[]; edges: { link_id: string; link: string; from: string; to: string }[];
by_type: Record<string, number>; hidden: number; truncated: boolean; synced_at: string | null;
}
export interface ImpactResult extends TraverseResult {
layers: { depth: number; groups: { type_name: string; count: number; items: TraverseNode[] }[] }[];
live: { id: string; type_name: string; key: string; label: string; properties: Record<string, any> }[];
actions: { name: string; display_name: string; object_type: string }[]; summary: string;
context?: Record<string, number>;
}
export interface WorkbenchRun { id: string; action_name: string; priority: string; status: string; summary: string; created_at: string; initiator_id: string }
export interface Workbench {
user: { id: string; name: string; roles: string[]; biz_roles: string[]; can_run: boolean };
kpis: { name: string; value: any; unit: string; direction: string; formula: string; dimensions: string[]; run_id?: number }[];
todo: { approvals: WorkbenchRun[]; approvals_total: number; releases: { id: string; title: string; created_by?: string }[];
tasks: { id: string; title: string; due_at?: string | null; role?: string }[] };
mine: WorkbenchRun[]; sops: { id: string; title: string; description: string; run_count: number }[];
questions: string[]; feed: { ts: string; actor: string; summary: string }[];
}
export interface ModelStage { key: string; label: string; desc: string; status: string; log: string[]; counts: Record<string, any> }
export interface ModelRunRec {
id: string; title: string; status: string; job_id: number; error: string; options: any;
stages: ModelStage[]; counts: Record<string, number>; created_by: string; created_at: string; updated_at: string;
inputs: { doc_ids: number[]; files: string[]; chunks: number };
}
export interface ModelRunFull extends ModelRunRec {
items: Record<"object_type" | "link_type" | "function" | "action" | "other", ReviewItem[]>;
sops: { id: string; title: string; description: string; status: string; step_count: number }[];
}
export interface RuntimeOverview {
mcp: { calls_24h: number; success_rate: number | null; by_via: Record<string, number>;
top_tools: { tool: string; calls: number; failed: number; avg_ms: number }[] };
approvals: { pending: number; by_priority: Record<string, number>;
top: { id: string; action_name: string; priority: string; reason: string; created_at: string }[] };
actions: Record<string, number>; runcards: Record<string, number>;
pipelines: { objects: number; edges: number; synced_at: string | null; items: PipelineRec[] };
}
export interface AuditRec { export interface AuditRec {
id: number; ts: string; actor_kind: string; actor_id: string; actor_name: string; event: string; id: number; ts: string; actor_kind: string; actor_id: string; actor_name: string; event: string;
target_type: string; target_id: string; summary: string; before?: any; after?: any; target_type: string; target_id: string; summary: string; before?: any; after?: any;
...@@ -155,9 +221,11 @@ export interface SopStep { ...@@ -155,9 +221,11 @@ export interface SopStep {
export interface SopParam { name: string; label: string; type: string; object_type: string; calendar: string; required: boolean; default?: any } export interface SopParam { name: string; label: string; type: string; object_type: string; calendar: string; required: boolean; default?: any }
export interface SopSpec { export interface SopSpec {
params: SopParam[]; roles: string[]; trigger: any; start: string; steps: SopStep[]; evidence: any[]; params: SopParam[]; roles: string[]; trigger: any; start: string; steps: SopStep[]; evidence: any[];
priority?: string; domain?: string;
} }
export interface SopBrief { export interface SopBrief {
id: string; title: string; description: string; status: string; current_version: number; id: string; title: string; description: string; status: string; current_version: number;
priority?: string; domain?: string; step_types?: string[];
step_count: number; trigger_kind: string; dry_run_ok: boolean; ai_generated: boolean; step_count: number; trigger_kind: string; dry_run_ok: boolean; ai_generated: boolean;
run_count?: number; updated_at: string; owner_role: string; process_concept_id: string; run_count?: number; updated_at: string; owner_role: string; process_concept_id: string;
} }
...@@ -180,6 +248,7 @@ export interface SopRun { ...@@ -180,6 +248,7 @@ export interface SopRun {
export interface AskCard { export interface AskCard {
action: string; action_id?: string; display_name: string; params: Record<string, any>; action: string; action_id?: string; display_name: string; params: Record<string, any>;
object_key: string; reason: string; preview?: ActionPreview; error?: string; object_key: string; reason: string; preview?: ActionPreview; error?: string;
param_defs?: { name: string; label: string; type: string; required: boolean; enum: string[] }[]; target_type?: string;
} }
export interface DataRef { export interface DataRef {
run_id: number; sql: string; columns: string[]; rows: any[][]; metric?: any; period?: any; run_id: number; sql: string; columns: string[]; rows: any[][]; metric?: any; period?: any;
...@@ -242,9 +311,14 @@ export const onto = { ...@@ -242,9 +311,14 @@ export const onto = {
req<Binding>(`/api/kernel/concepts/${enc(id)}/bindings`, put(body)), req<Binding>(`/api/kernel/concepts/${enc(id)}/bindings`, put(body)),
deleteBinding: (bid: string) => req<{ ok: boolean }>(`/api/kernel/bindings/${enc(bid)}`, del), deleteBinding: (bid: string) => req<{ ok: boolean }>(`/api/kernel/bindings/${enc(bid)}`, del),
pendingDiff: () => req<Diff>("/api/kernel/diff"), pendingDiff: () => req<Diff>("/api/kernel/diff"),
publish: (note: string, force = false) => req<{ revision: number; diff: Diff }>("/api/kernel/publish", post({ note, force })), /** 提交变更提案(别人审批通过后才发布) */
proposeRelease: (note: string) => req<ReviewItem>("/api/kernel/publish", post({ note })),
releases: (status = "") => req<ReleaseItem[]>(`/api/kernel/releases${qs({ status })}`),
decideRelease: (id: string, approve: boolean, comment = "") =>
req<ReviewItem & { result: any }>(`/api/kernel/releases/${enc(id)}/decide`, post({ approve, comment })),
revisions: () => req<RevisionRec[]>("/api/kernel/revisions"), revisions: () => req<RevisionRec[]>("/api/kernel/revisions"),
rollback: (rev: number) => req<{ revision: number }>(`/api/kernel/revisions/${rev}/rollback`, post()), /** 回滚也是一份变更提案 */
rollback: (rev: number, note = "") => req<ReviewItem>(`/api/kernel/revisions/${rev}/rollback`, post({ note })),
compareRevisions: (from: number, to: number) => req<Diff & { from: number; to: number }>( compareRevisions: (from: number, to: number) => req<Diff & { from: number; to: number }>(
`/api/kernel/revisions/compare?from=${from}&to=${to}`), `/api/kernel/revisions/compare?from=${from}&to=${to}`),
graph: () => req<{ nodes: GraphNode[]; edges: GraphEdge[] }>("/api/kernel/graph"), graph: () => req<{ nodes: GraphNode[]; edges: GraphEdge[] }>("/api/kernel/graph"),
...@@ -272,7 +346,44 @@ export const onto = { ...@@ -272,7 +346,44 @@ export const onto = {
req<{ object_type: { id: string; name: string; spec: any }; items: ObjectRec[] }>( req<{ object_type: { id: string; name: string; spec: any }; items: ObjectRec[] }>(
`/api/kernel/objects/${enc(type)}${qs({ q, limit })}`), `/api/kernel/objects/${enc(type)}${qs({ q, limit })}`),
object360: (type: string, key: string) => req<any>(`/api/kernel/objects/${enc(type)}/${enc(key)}`), object360: (type: string, key: string) => req<any>(`/api/kernel/objects/${enc(type)}/${enc(key)}`),
syncObjects: (type: string) => req<{ synced: number }>(`/api/kernel/objects/${enc(type)}/sync`, post()), syncObjects: (type: string) => req<{ rows: number; edges: number }>(`/api/kernel/objects/${enc(type)}/sync`, post()),
traverse: (type: string, key: string, depth = 2) =>
req<TraverseResult>(`/api/kernel/objects/${enc(type)}/${enc(key)}/traverse?depth=${depth}`),
impactObject: (type: string, key: string, depth = 3) =>
req<ImpactResult>(`/api/kernel/objects/${enc(type)}/${enc(key)}/impact?depth=${depth}`),
mappings: (dsId: number) => req<Record<string, { concept_id: string; name: string; status: string }[]>>(`/api/kernel/mappings?ds_id=${dsId}`),
// 本体空间 / 首页
workspaces: () => req<WorkspaceRec[]>("/api/kernel/workspaces"),
createWorkspace: (body: { id: string; display_name: string; description?: string; industry?: string; template?: string }) =>
req<WorkspaceRec>("/api/kernel/workspaces", post(body)),
updateWorkspace: (id: string, body: Partial<WorkspaceRec>) => req<WorkspaceRec>(`/api/kernel/workspaces/${enc(id)}`, put(body)),
archiveWorkspace: (id: string) => req<{ ok: boolean }>(`/api/kernel/workspaces/${enc(id)}`, del),
home: () => req<HomeOverview>("/api/kernel/home"),
workbench: () => req<Workbench>("/api/kernel/workbench"),
// 数据管道 / 本体数据集
pipelines: () => req<{ items: PipelineRec[]; status: { objects: number; edges: number; synced_at: string | null } }>("/api/kernel/pipelines"),
createPipeline: (object_type: string, schedule = "manual") => req<PipelineRec>("/api/kernel/pipelines", post({ object_type, schedule })),
ensurePipelines: () => req<{ created: string[] }>("/api/kernel/pipelines/ensure", post()),
runAllPipelines: () => req<{ job_id: number }>("/api/kernel/pipelines/run-all", post()),
updatePipeline: (id: string, body: Partial<PipelineRec>) => req<PipelineRec>(`/api/kernel/pipelines/${enc(id)}`, put(body)),
deletePipeline: (id: string) => req<{ ok: boolean }>(`/api/kernel/pipelines/${enc(id)}`, del),
runPipeline: (id: string) => req<PipelineRec & { result: any }>(`/api/kernel/pipelines/${enc(id)}/run`, post()),
dataset: (type: string, q = "", limit = 50, offset = 0) =>
req<{ object_type: { id: string; name: string }; total: number; items: { key: string; label: string; properties: any; synced_at: string }[] }>(
`/api/kernel/datasets/${enc(type)}${qs({ q, limit, offset })}`),
// 业务建模
modelingStages: () => req<{ stages: { key: string; label: string; desc: string }[];
templates: { id: string; name: string; description: string; concepts: number }[] }>("/api/kernel/modeling/stages"),
modelingRuns: () => req<ModelRunRec[]>("/api/kernel/modeling/runs"),
modelingRun: (id: string) => req<ModelRunFull>(`/api/kernel/modeling/runs/${enc(id)}`),
createModelingRun: (fd: FormData) => req<ModelRunRec>("/api/kernel/modeling/runs", { method: "POST", body: fd }),
startModelingRun: (id: string) => req<ModelRunRec>(`/api/kernel/modeling/runs/${enc(id)}/start`, post()),
deleteModelingRun: (id: string) => req<{ ok: boolean }>(`/api/kernel/modeling/runs/${enc(id)}`, del),
modelingExportUrl: (id: string) => `/api/kernel/modeling/runs/${enc(id)}/export`,
// 能力 // 能力
catalog: () => req<{ functions: FunctionBrief[]; tools: ToolBrief[]; defs: CapDef[] }>("/api/cap/catalog"), catalog: () => req<{ functions: FunctionBrief[]; tools: ToolBrief[]; defs: CapDef[] }>("/api/cap/catalog"),
...@@ -285,7 +396,8 @@ export const onto = { ...@@ -285,7 +396,8 @@ export const onto = {
runSkill: (ref: string, args: any) => req<any>(`/api/cap/skills/${enc(ref)}/run`, post({ args })), runSkill: (ref: string, args: any) => req<any>(`/api/cap/skills/${enc(ref)}/run`, post({ args })),
prepareAction: (ref: string, params: any, object_key = "") => prepareAction: (ref: string, params: any, object_key = "") =>
req<ActionPreview>(`/api/cap/actions/${enc(ref)}/prepare`, post({ params, object_key })), req<ActionPreview>(`/api/cap/actions/${enc(ref)}/prepare`, post({ params, object_key })),
proposeAction: (ref: string, body: { params: any; object_key?: string; reason?: string; initiator_kind?: string; source_ref?: string }) => proposeAction: (ref: string, body: { params: any; object_key?: string; reason?: string; initiator_kind?: string;
source_ref?: string; priority?: string; evidence?: any[] }) =>
req<ActionRun>(`/api/cap/actions/${enc(ref)}/propose`, post(body)), req<ActionRun>(`/api/cap/actions/${enc(ref)}/propose`, post(body)),
actionRuns: (p: Record<string, unknown> = {}) => req<ActionRun[]>(`/api/cap/runs${qs(p)}`), actionRuns: (p: Record<string, unknown> = {}) => req<ActionRun[]>(`/api/cap/runs${qs(p)}`),
actionRun: (id: string) => req<ActionRun>(`/api/cap/runs/${enc(id)}`), actionRun: (id: string) => req<ActionRun>(`/api/cap/runs/${enc(id)}`),
...@@ -302,6 +414,7 @@ export const onto = { ...@@ -302,6 +414,7 @@ export const onto = {
mcpCall: (name: string, args: any) => req<{ ok: boolean; result: any; error: string | null }>( mcpCall: (name: string, args: any) => req<{ ok: boolean; result: any; error: string | null }>(
`/api/cap/mcp/call/${enc(name)}`, post({ args })), `/api/cap/mcp/call/${enc(name)}`, post({ args })),
mcpLogs: (limit = 50) => req<AuditRec[]>(`/api/cap/mcp/logs?limit=${limit}`), mcpLogs: (limit = 50) => req<AuditRec[]>(`/api/cap/mcp/logs?limit=${limit}`),
runtimeOverview: () => req<RuntimeOverview>("/api/cap/runtime/overview"),
// SOP // SOP
sopMeta: () => req<{ step_types: { type: string; label: string }[]; param_types: string[] }>("/api/sop/meta"), sopMeta: () => req<{ step_types: { type: string; label: string }[]; param_types: string[] }>("/api/sop/meta"),
...@@ -364,14 +477,18 @@ export const STATUS_TONE: Record<string, string> = { ...@@ -364,14 +477,18 @@ export const STATUS_TONE: Record<string, string> = {
/** 颜色按细分类型(对象 / 关系 / 函数五类 / 动作)。旧键保留给历史数据与图谱实体。 */ /** 颜色按细分类型(对象 / 关系 / 函数五类 / 动作)。旧键保留给历史数据与图谱实体。 */
export const KIND_COLOR: Record<string, string> = { export const KIND_COLOR: Record<string, string> = {
object_type: "#6366f1", link_type: "#8b5cf6", action: "#ef4444", object_type: "#6366f1", link_type: "#8b5cf6", action: "#ef4444",
aggregate: "#0ea5e9", rule: "#f59e0b", calendar: "#10b981", decision: "#d946ef", ai: "#14b8a6", aggregate: "#0ea5e9", rule: "#f59e0b", calendar: "#10b981", decision: "#d946ef", ml: "#ec4899", ai: "#14b8a6",
function: "#0ea5e9", metric: "#0ea5e9", table: "#64748b", column: "#94a3b8", datasource: "#475569", function: "#0ea5e9", metric: "#0ea5e9", table: "#64748b", column: "#94a3b8", datasource: "#475569",
document: "#a16207", document: "#a16207",
}; };
export const TYPE_LABEL: Record<string, string> = { export const TYPE_LABEL: Record<string, string> = {
object_type: "对象", link_type: "关系", action: "动作", function: "函数", object_type: "对象", link_type: "关系", action: "动作", function: "函数",
aggregate: "聚合", rule: "规则", calendar: "周期", decision: "决策表", ai: "AI 分析", aggregate: "聚合", rule: "规则", calendar: "周期", decision: "决策表", ml: "模型推理", ai: "AI 分析(参考)",
};
export const PRIORITY_TONE: Record<string, string> = {
P0: "bg-bad/15 text-bad", P1: "bg-warn/15 text-warn", P2: "bg-brand/10 text-brand", P3: "bg-ink/5 text-muted",
}; };
export function typeKey(c: { kind: string; category?: string }): TypeKey { export function typeKey(c: { kind: string; category?: string }): TypeKey {
......
{"root":["./src/app.tsx","./src/main.tsx","./src/components/ui.tsx","./src/features/ask/actioncard.tsx","./src/features/ask/askanswer.tsx","./src/features/ask/askpage.tsx","./src/features/audit/auditpage.tsx","./src/features/capability/capabilitypage.tsx","./src/features/documents/documentspage.tsx","./src/features/documents/usejobstream.ts","./src/features/eval/evalpage.tsx","./src/features/graph/duplicatespanel.tsx","./src/features/graph/filterpanel.tsx","./src/features/graph/grapheditor.tsx","./src/features/graph/graphpage.tsx","./src/features/graph/nodesearch.tsx","./src/features/graph/propertypanel.tsx","./src/features/graph/sigmagraph.tsx","./src/features/inbox/inboxpage.tsx","./src/features/kernel/bindingeditor.tsx","./src/features/members/memberspage.tsx","./src/features/objects/objectspage.tsx","./src/features/ontology/blockeditor.tsx","./src/features/ontology/blocklistpage.tsx","./src/features/ontology/canvaspage.tsx","./src/features/ontology/draftmodal.tsx","./src/features/ontology/mcppage.tsx","./src/features/ontology/releasepages.tsx","./src/features/ontology/wizardpage.tsx","./src/features/ontology/common.tsx","./src/features/ontology/routes.ts","./src/features/ontology/tools.tsx","./src/features/settings/settingspage.tsx","./src/features/sop/sopflow.tsx","./src/features/sop/soppage.tsx","./src/features/sop/stepeditor.tsx","./src/features/sql/askpanel.tsx","./src/features/sql/datasourcepanel.tsx","./src/features/sql/librarypanel.tsx","./src/features/sql/modelingpanel.tsx","./src/features/sql/rulespanel.tsx","./src/features/sql/sqlpage.tsx","./src/features/sql/sqltrace.tsx","./src/lib/api.ts","./src/lib/colors.ts","./src/lib/dialog.tsx","./src/lib/identity.ts","./src/lib/nav.ts","./src/lib/onto.ts","./src/lib/sse.ts","./src/lib/types.ts","./src/lib/usejobpoll.ts","./src/lib/utils.ts","./src/store/useappstore.ts","./src/store/usesqlstore.ts"],"version":"5.9.3"}
\ No newline at end of file \ No newline at end of file
{"root":["./src/app.tsx","./src/main.tsx","./src/components/ui.tsx","./src/features/ask/actioncard.tsx","./src/features/ask/askanswer.tsx","./src/features/ask/askpage.tsx","./src/features/audit/auditpage.tsx","./src/features/capability/capabilitypage.tsx","./src/features/data/pipelinepage.tsx","./src/features/documents/documentspage.tsx","./src/features/documents/usejobstream.ts","./src/features/eval/evalpage.tsx","./src/features/graph/duplicatespanel.tsx","./src/features/graph/filterpanel.tsx","./src/features/graph/grapheditor.tsx","./src/features/graph/graphpage.tsx","./src/features/graph/nodesearch.tsx","./src/features/graph/propertypanel.tsx","./src/features/graph/sigmagraph.tsx","./src/features/home/homepage.tsx","./src/features/inbox/inboxpage.tsx","./src/features/kernel/bindingeditor.tsx","./src/features/members/memberspage.tsx","./src/features/objects/objectspage.tsx","./src/features/ontology/blockeditor.tsx","./src/features/ontology/blocklistpage.tsx","./src/features/ontology/canvaspage.tsx","./src/features/ontology/draftmodal.tsx","./src/features/ontology/mcppage.tsx","./src/features/ontology/modelingpage.tsx","./src/features/ontology/releasepages.tsx","./src/features/ontology/common.tsx","./src/features/ontology/routes.ts","./src/features/ontology/tools.tsx","./src/features/runtime/overviewpage.tsx","./src/features/settings/settingspage.tsx","./src/features/sop/sopflow.tsx","./src/features/sop/soppage.tsx","./src/features/sop/stepeditor.tsx","./src/features/sql/askpanel.tsx","./src/features/sql/datasourcepanel.tsx","./src/features/sql/librarypanel.tsx","./src/features/sql/mappingpanel.tsx","./src/features/sql/modelingpanel.tsx","./src/features/sql/rulespanel.tsx","./src/features/sql/sqlpage.tsx","./src/features/sql/sqltrace.tsx","./src/features/workbench/workbenchpage.tsx","./src/lib/api.ts","./src/lib/colors.ts","./src/lib/dialog.tsx","./src/lib/identity.ts","./src/lib/nav.ts","./src/lib/onto.ts","./src/lib/sse.ts","./src/lib/types.ts","./src/lib/usejobpoll.ts","./src/lib/utils.ts","./src/store/useappstore.ts","./src/store/usesqlstore.ts"],"checkPending":true,"version":"5.9.3"}
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!