Commit 0a91ca92 by 黄南光

大幅优化本体论系统

1 parent 006919cf
Showing 74 changed files with 4469 additions and 1622 deletions
......@@ -83,6 +83,19 @@
"ONTO_WORKSPACE": "xianda_inv"
},
"port": 8107
},
{
"name": "onto-8101",
"runtimeExecutable": "./.venv/Scripts/python.exe",
"runtimeArgs": [
"scripts/serve_8101.py"
],
"env": {
"PORT": "8101",
"WEB_DIST": "dist_8101",
"ONTO_WORKSPACE": "default"
},
"port": 8101
}
]
}
\ No newline at end of file
}
# 2026-09-24
## SOP 端到端链路诊断(老大提问「sop 流程没跑通」)
实测结论:**引擎没坏**。用 8101 实例把「创建补货采购单流程」(sop_9e036138e5274012affb)
从草稿跑到 done:试运行 → 提交发布 → 审批(rv_05413933f60b472d85d2)→ 发布 v1 →
正式运行 sr_3121de3ddab847d7b34d → 5 个人工任务依次完成 → done。
(过程中我替他发布了 v1 并跑完了一次 live run,需知会。)
真正断点在三层:
1. 本体层:3 个 action 全是 draft(`创建补货采购单` 参数只有 reason、target_type 为空、
effect 只是 notify.send,根本没建单);skill 数量 = 0。action 一 propose 就 409(actions.py
`_load_action` 校验 published),所以 SOP 里用 action 必然失败。
2. 起草层:`app/sop/draft.py` 的 `_catalog` 没标 action 发布状态,prompt 只说「没有合适动作时
用 human_task」,没说优先用 action → 起草结果 11 步里 8 步 human_task,0 action / 0 skill /
0 foreach;且让人手填「需经理审批的补货单列表」当分支条件,判定建立在自由文本上。
3. 运行层:流程只是 5 次人工点确认,没有动作提议、没有审批、没有写回。
改造方向(未实施,等老大确认):
- P0 本体:补全并发布 3 个 action(尤其「创建补货采购单」要有商品/仓库/数量/供应商/金额参数
与写回 effect),建 1~2 个 skill(补货建议分析、巡检汇总)。
- P1 draft.py:`_catalog` 标注 action/skill 发布状态;prompt 改成「能用 action 就不许用
human_task」;起草后加退化检查(human_task 占比过高 → validation warning)。
- P2 编排范式:function 取数 → skill 分析 → foreach 逐行 propose action → rule.decision 分支
→ 审批(走 action 审批,不是 human_task)→ skill 汇总。
- P3 体验:运行视图 waiting_human 步骤给「去办理」直达链接 + 显示「等谁」;
试运行支持给 decision 指定模拟值以覆盖两条分支。
## 环境备忘
- 服务跑在 8101 / 8102 两个实例(uvicorn_8101.log / uvicorn_8102.log), data 目录共享。
- pytest 必须用 `--basetemp=/tmp/oq_pt`:pytest.ini 默认 `.pytest_tmp` 会触发
safe-delete 批量删除守卫(>50 文件)导致 SystemExit。
- Git Bash 里 curl -d 带中文会因 GBK 编码报 "error parsing the body",诊断时用 ASCII body。
......@@ -34,40 +34,93 @@ def actions_catalog() -> str:
def sops_catalog() -> str:
"""已发布流程卡:标题、说明、要填的参数、步骤概要。
以前只给标题和一句说明,模型既不知道该填哪些参数,也不知道批了之后会发生什么,
给出来的流程卡建议全是自创的参数名,对不上号。"""
from ..sop import propose as sop_propose
from ..sop import service as sop_service
return "\n".join(f"- {d['title']}:{d['description']}"
for d in sop_service.list_defs(status="published")[:30]) or "(无)"
out = []
for brief in sop_service.list_defs(status="published")[:20]:
try:
d = sop_service.get(brief["id"])
except Exception: # noqa: BLE001
continue
ps = "、".join(f"{p['name']}({p.get('label') or p['name']}"
f"{',必填' if p.get('required', True) else ',可选'})"
for p in d["spec"].get("params") or []) or "无"
steps = "→".join(st["title"] for st in sop_propose.outline(d)[:6])
out.append(f"- {d['title']}:{d['description'] or '(无说明)'};参数 [{ps}];步骤:{steps}")
return "\n".join(out) or "(无)"
def run(tracer: Tracer, question: str, links: dict, links_text: str, results: dict,
results_text: str) -> dict:
results_text: str, task: str = "") -> dict:
span = tracer.span("agent")
started = time.time()
label = AGENT_META["action"]["label"]
tracer.emit({"type": "agent_start", "span": span, "parent": "lead", "agent": "action", "label": label,
"task": "根据结论给出可提交的动作与可运行的流程卡"})
"task": task or "根据结论给出可提交审批的动作与要发起的流程卡"})
try:
d = think_json(tracer, span, "action", [
{"role": "system", "content": prompts.ACTION_SYSTEM.format(actions=actions_catalog(),
sops=sops_catalog())},
{"role": "user", "content": prompts.ACTION_USER.format(
question=question, links=links_text, results=llm.truncate_to_tokens(results_text, 9000))}])
task=task or "(主 Agent 没有特别交代,自己判断)", question=question, links=links_text,
results=llm.truncate_to_tokens(results_text, 9000))}])
except Exception as e: # noqa: BLE001
log.warning("行动 Agent 失败:%s", str(e)[:200])
d = {}
suggest = [a for a in d.get("suggest_actions") or [] if isinstance(a, dict)][:3]
sops = [s for s in d.get("suggest_sops") or [] if isinstance(s, dict)][:2]
cards = prepare_cards(suggest, links, results, results_text, question)
sops = prepare_sop_cards([x for x in d.get("suggest_sops") or [] if isinstance(x, dict)][:2], results)
ok_cards = [c for c in cards if not c.get("error")]
summary = (f"建议 {len(ok_cards)} 个动作" + (f"、{len(sops)} 个流程卡" if sops else "")
if (ok_cards or sops) else "没有需要执行的动作")
ok_sops = [c for c in sops if not c.get("error")]
summary = ("、".join(x for x in (f"建议 {len(ok_cards)} 个动作" if ok_cards else "",
f"建议发起 {len(ok_sops)} 张流程卡" if ok_sops else "") if x)
or "没有需要执行的动作")
tracer.emit({"type": "agent_done", "span": span, "parent": "lead", "agent": "action", "label": label,
"summary": summary, "findings": [f"{c['display_name']}:{c.get('reason', '')}" for c in ok_cards],
"insights": [], "confidence": 0.8 if ok_cards else 0.5, "ok": True,
"summary": summary,
"findings": [f"{c['display_name']}:{c.get('reason', '')}" for c in ok_cards + ok_sops],
"insights": [], "confidence": 0.8 if (ok_cards or ok_sops) else 0.5, "ok": True,
"ms": int((time.time() - started) * 1000)})
return {"cards": cards, "sops": sops, "summary": summary}
def prepare_sop_cards(suggest: list[dict], results: dict) -> list[dict]:
"""流程卡建议 → 可提交审批的「发起流程卡」卡片。
以前这里把模型写的标题和参数原样返回,界面上只是一个跳到流程卡页面的小标签 —— 人还得自己
找那张卡、自己填参数、自己点运行,行动 Agent 到这里就断了。现在解析成真实的已发布流程卡,
参数按定义过滤(模型爱自创参数名),再走一次动作预览;人核对后点「提交审批」,
批准了才由 sop.start 把流程真正跑起来,之后的步骤归流程卡自己推进。"""
from ..sop import propose as sop_propose
out = []
for s in suggest:
ref = str(s.get("sop") or s.get("title") or "")
params = actions.render(s.get("params") or {}, results or {})
card = {"kind": "sop", "sop": ref, "display_name": ref, "object_key": "",
"params": params if isinstance(params, dict) else {},
"reason": s.get("reason") or ""}
d = sop_propose.find_published(ref)
if d is None:
card["error"] = "没有找到这张已发布的流程卡"
out.append(card)
continue
a = sop_propose.as_action(d["id"])
names = {x["name"] for x in a["spec"]["params"]}
card.update(sop_id=d["id"], sop=d["title"], display_name=d["title"],
description=d["description"], action=a["id"], action_id=a["id"],
param_defs=a["spec"]["params"], steps=sop_propose.outline(d),
params={k: v for k, v in card["params"].items() if k in names})
try:
card["preview"] = actions.prepare(a["id"], card["params"])
except HTTPException as e:
card["error"] = str(e.detail)
out.append(card)
return out
def prepare_cards(suggest: list[dict], links: dict, results: dict, results_text: str,
question: str) -> list[dict]:
"""动作建议 → 可提交的卡片。参数常常要等取数之后才定得下来:先替换 $k1.字段 引用;
......
......@@ -138,9 +138,7 @@ def result_text(rec: dict, res: Any) -> str:
if isinstance(res.get("metric"), dict):
parts.append(f"指标:{res['metric'].get('name')}(单位 {res['metric'].get('unit') or '无'})")
if isinstance(res.get("calibre"), dict):
parts.append(f"指标口径:{res['calibre'].get('name')}:{res['calibre'].get('text')}")
if isinstance(res.get("calibre"), str) and res["calibre"]:
parts.append(f"取数口径:{res['calibre']}")
parts.append(f"口径({res['calibre'].get('name')}):{res['calibre'].get('text')}")
if res.get("route"):
parts.append("取数方式:" + ("按已定义指标确定性取数" if res["route"] == "metric"
else "问数 Agent 生成 SQL"))
......@@ -324,8 +322,8 @@ KNOWLEDGE = SubAgent(
DATA = SubAgent(
"data", prompts.DATA_ROLE,
["data_ask", "query_metric", "execute_function", "run_analysis", "query_objects", "get_object",
"get_linked_objects", "execute_runcard"],
["data_ask", "query_metric", "execute_function", "run_analysis", "lookup_concept", "query_objects",
"get_object", "get_linked_objects", "execute_runcard"],
prefix="d", extra=prompts.DATA_EXTRA, max_rounds=2) # 一次取数 + 最多一次下钻:每次问数 20~30 秒
SUB_AGENTS = {"knowledge": KNOWLEDGE, "data": DATA}
......@@ -54,7 +54,9 @@ def ontology_text(limit: int = 40) -> str:
else:
sig = c.get("kind_label") or cat or ""
out.append(f"- {c['name']}:{sig}")
return "\n".join(out) or "(无)"
# 对象、属性(中文名)、关系:建模时花力气最多的部分,以前提问时从来不进提示词
from ..kernel import grounding
return ("\n".join(out) or "(无)") + "\n\n〔对象与关系〕\n" + grounding.digest()
def skills_text() -> str:
......@@ -161,6 +163,24 @@ def _dispatch(tracer: Tracer, question: str, links: dict, hist: list[dict], mem:
return p
# 用户在让系统「做一件事」的说法。主 Agent 分派时漏掉 action 是常事(尤其「如果……就……」这种
# 条件句,它以为要先查完再说),漏了行动 Agent 就整轮不出审批卡 —— 这里兜一道底。
_ACTION_WORDS = re.compile(r"(发起|创建|新建|下单|补货|派单|派发|提单|开单|标记|登记|启动|走一?[下个]?流程|"
r"流程卡|提交审批|帮我(处理|办|搞定))")
def _wants_action(p: dict, question: str) -> bool:
if any(d["agent"] == "action" for d in p["delegations"]):
return True
if p.get("intent") in ("action", "process"):
return True
return bool(_ACTION_WORDS.search(question))
def _action_task(p: dict) -> str:
return next((d["task"] for d in p["delegations"] if d["agent"] == "action" and d.get("task")), "")
def _reflect(tracer: Tracer, question: str, reports: list[dict]) -> dict:
text = "\n\n".join(_report_text(r) for r in reports)
msgs = [{"role": "system", "content": prompts.REFLECT_SYSTEM.format(
......@@ -282,6 +302,11 @@ def _orchestrate(tracer: Tracer, question: str, conv_id: str, turn_id: str, stat
records = [rec for r in reports for rec in r["records"]]
results = {rec["id"]: rec["_result"] for rec in records}
# 「本次用到的本体」:实际执行过的指标 / 规则 / 决策表 / 概念,而不只是问句里匹配到的
from ..kernel import grounding
used = grounding.used_concepts(list(results.values()))
if used:
tracer.emit({"type": "onto_used", "span": "lead", "items": used})
steps = [{k: v for k, v in rec.items() if k != "_result"} for rec in records]
state["steps"] = steps
p["steps"] = [{"id": s["id"], "call": s["call"], "args": s["args"], "why": s.get("why", ""),
......@@ -292,9 +317,8 @@ def _orchestrate(tracer: Tracer, question: str, conv_id: str, turn_id: str, stat
# 5) 行动建议
cards: list[dict] = []
sops: list[dict] = []
wants_action = any(d["agent"] == "action" for d in p["delegations"]) or p.get("intent") == "action"
if wants_action and not tracer.cancel.is_set():
act = action_agent.run(tracer, q2, links, ltext, results, results_text)
if _wants_action(p, f"{question} {q2}") and not tracer.cancel.is_set():
act = action_agent.run(tracer, q2, links, ltext, results, results_text, task=_action_task(p))
cards, sops = act["cards"], act["sops"]
if cards:
tracer.emit({"type": "actions", "items": cards})
......@@ -307,7 +331,8 @@ def _orchestrate(tracer: Tracer, question: str, conv_id: str, turn_id: str, stat
# 6) 作答
cards_text = "\n".join(f"- {c['display_name']}:{(c.get('preview') or {}).get('summary') or c.get('error')}"
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('preview') or {}).get('summary') or s.get('error') or ''}"
f"(理由:{s.get('reason', '')})" for s in sops) or "(无)"
msgs = [{"role": "system", "content": prompts.ANSWER_SYSTEM},
{"role": "user", "content": prompts.ANSWER_USER.format(
question=q2, links=ltext, facts=memory.facts_text(mem),
......@@ -345,9 +370,14 @@ def _pools(records: list[dict]) -> tuple[dict, dict]:
if isinstance(e, dict) and e.get("chunk_id"):
chunk_pool.setdefault(e["chunk_id"], {"id": e["chunk_id"], "heading": e.get("heading", ""),
"doc_id": e.get("doc_id"), "text": e.get("snippet", "")})
if res.get("run_id"):
data_pool[int(res["run_id"])] = {
"run_id": int(res["run_id"]), "sql": res.get("sql", ""), "columns": res.get("columns") or [],
# 取数记录编号是整数。别的工具也叫 run_id(流程卡运行 sr_xxx、审批单 ar_xxx),
# 以前一律 int() 转,一碰上就整轮报错,答案都没了。
rid = res.get("run_id")
if isinstance(rid, bool) or not (isinstance(rid, int) or (isinstance(rid, str) and rid.isdigit())):
continue
if res.get("columns") is not None:
data_pool[int(rid)] = {
"run_id": int(rid), "sql": res.get("sql", ""), "columns": res.get("columns") or [],
"rows": (res.get("rows") or [])[:50], "metric": res.get("metric"), "period": res.get("period"),
"calibre": res.get("calibre"), "step_id": rec["id"], "route": res.get("route", ""),
"notes": res.get("notes") or []}
......@@ -390,6 +420,7 @@ def _finish(tracer: Tracer, turn_id: str, conv_id: str, question: str, links: di
audit.record("ask", "turn", turn_id, f"提问:{question[:200]}",
after={"intent": p.get("intent"), "agents": [a["agent"] for a in agents],
"steps": [s["call"] for s in steps], "suggested_actions": [c["action"] for c in cards],
"suggested_sops": [s.get("sop") for s in sops],
"from_case": p.get("from_case", "")})
if status == "done" and not clarify:
memory.learn_async(turn_id)
......
......@@ -31,7 +31,8 @@ LEAD_SYSTEM = """你是企业本体系统的「主 Agent」,负责理解问题
【子 Agent 可用工具】
{tools}
【已发布的函数与指标】(execute_function 的 name 只能用这里的名称)
【本体:已发布的函数与指标、对象与关系】(execute_function 的 name 只能用这里的名称;
取数时用对象和属性的业务名称描述需求)
{ontology}
【AI 分析函数】(run_analysis,args {{"name":函数名,"inputs":{{...}}}})
......@@ -63,7 +64,13 @@ JSON 格式:
规则:
1. 数据问题一定要交给 data 并取数(data_ask,把时间、对象、拆分方式写进 question),不要只检索文档。
2. 知识/流程/口径类问题,knowledge 的第一步一般是 search_knowledge(文档里一定有描述)+ 必要时 lookup_concept。
3. 行动类:data 的任务里写清算参数要用到的字段(如在库、在途、安全库存、补货批量、单价),并交给 action。
3. 行动类(用户说了「帮我 / 发起 / 创建 / 提交 / 补货 / 走某个流程」,包括「如果……就……」这种带条件的):
**delegations 里必须同时有 knowledge、data、action 三个**(前两个并行跑,action 在它们之后)。
- knowledge:把判断标准与规则查清楚(什么算缺货、补货量怎么算、金额到多少要谁批、该走哪张流程卡);
- data:写清算参数要用到的字段(如在库、在途、安全库存、补货批量、单价);
- action:task 写清「拿到数之后要做什么、条件是什么」,例如「如果有缺货商品,就发起流程卡
『创建补货采购单流程』」。action 不写 calls(它不调工具,只出审批卡)。
条件成不成立由行动 Agent 看完数据自己判断,不要因为「还不知道有没有缺货」就不派 action。
4. 对象里没有名称列时(如「仓库 × 商品」的库存行),用 data_ask 把条件写清楚,不要用 query_objects 按名称搜。
5. 只输出一次 JSON。
""" + THINK_FORMAT
......@@ -105,7 +112,7 @@ AGENT_SYSTEM = """你是企业本体系统的「{label}」。{role}
【你的工具】
{tools}
【已发布的函数与指标】
【本体:已发布的函数与指标、对象与关系】
{ontology}
JSON 格式二选一:
......@@ -136,28 +143,41 @@ DATA_ROLE = ("你擅长实时取数与数据分析:用问数工具取数,读
"必要时按维度下钻再查一次,给出有数字的解读。")
DATA_EXTRA = ("3. 取数一律优先 data_ask(它自己选按指标取数还是写 SQL);规则/决策表求值用 execute_function。\n"
"4. 看到异常时,想想领导会追问什么(按仓库?按供应商?占比多少?),值得就下钻一次。\n"
"5. insights 要写具体数字,例如「上海中心仓缺口 120 提,占全部缺口的 38%」。")
"5. insights 要写具体数字,例如「上海中心仓缺口 120 提,占全部缺口的 38%」。\n"
"6. 你只负责把数取准、把结论讲清楚。发起流程、提交动作是行动 Agent 的事,别用 "
"execute_runcard 的 live 模式去发起流程(它只是拿流程卡当剧本做诊断,用默认的 readonly)。")
# ---------------------------------------------------------------- 行动 Agent
ACTION_SYSTEM = """你是企业本体系统的「行动 Agent」。根据用户问题和其他 Agent 查到的结果,
给出可以提交审批的业务动作(只建议、不执行,人审批后才执行)和可以运行的流程卡。
ACTION_SYSTEM = """你是企业本体系统的「行动 Agent」。其他 Agent 已经把知识和数据查回来了,
你负责最后一步:把结论变成**可以提交审批的动作**,或者**要发起的流程卡**。
【可建议的动作】
你只提议,不执行:动作和流程卡都要人审批,批准后才由系统执行。
发起流程卡之后就不归你管了 —— 流程卡自己会按步骤往下走(派人工任务、走审批),你不要再重复建议
流程卡里已经包含的那些动作。
【可建议的动作】(单个动作,批准后立即执行它的效果)
{actions}
【已发布流程卡】
【已发布流程卡】(一整套流程,批准后从第一步开始跑)
{sops}
JSON 格式:
{{"suggest_actions": [{{"action":"动作名","params":{{...}},"object_key":"作用对象主键","reason":"建议理由(带依据的数字)"}}],
"suggest_sops": [{{"sop":"流程卡标题","params":{{...}},"reason":"..."}}]}}
"suggest_sops": [{{"sop":"流程卡标题(从上面列表里原样照抄)","params":{{...}},"reason":"为什么要发起它(带依据的数字)"}}]}}
规则:
1. 只在用户明确要求处理/行动、或数据显示明显异常且有对应动作时才建议动作;没有合适的就给空列表。
2. 参数按执行结果和业务规则算好(如补货量按批量向上取整);数字只写数字;枚举只能取给定值;实在定不下来的留空字符串。
3. 最多 3 个动作、2 个流程卡。
1. 用户明确要求处理 / 行动,或数据显示明显异常且有对应手段时才建议;没有合适的就给空列表。
用户说的是「如果……就……」时,先看数据条件成不成立:成立才建议,不成立就都给空列表,并在思考里说清楚。
2. 一件事只建议一种做法:流程卡能覆盖的,就只给流程卡,不要再单独给里面的动作。
3. 流程卡的 sop 必须是上面列表里的标题,一个字都不要改;params 只能用该流程卡列出的参数名,
它没有参数就给 {{}}。不要自创参数名。
4. 动作参数按执行结果和业务规则算好(如补货量按批量向上取整);数字只写数字;枚举只能取给定值;
实在定不下来的留空字符串。
5. 最多 3 个动作、2 张流程卡。
""" + THINK_FORMAT
ACTION_USER = """【问题】{question}
ACTION_USER = """【主 Agent 交给你的任务】{task}
【用户原问题】{question}
【本体链接】
{links}
......@@ -187,8 +207,9 @@ ANSWER_SYSTEM = """你是企业本体系统的主 Agent,现在根据各子 Age
1. 第一段直接给**结论**(一两句话,加粗关键数字),不要写「根据查询结果」这类套话。
2. `#### 依据`:口径、规则、原文要点。
3. `#### 数据与分析`(有数据时):关键数字、异常点、对比;超过 3 行用表格展示前几行。
4. `#### 建议下一步`(有动作或流程卡时):动作已在答案下方生成审批卡,请用户核对参数后点「提交审批」,
审批通过才会执行;不要让用户「去业务系统里操作」。
4. `#### 建议下一步`(有动作或流程卡时):动作和流程卡都已在答案下方生成卡片,请用户核对参数后点
「提交审批」,审批通过才会执行 / 才会把流程跑起来;流程卡启动后由流程自己派任务、走后续审批。
不要让用户「去业务系统里操作」,也不要说「已经发起了」—— 还没批就还没发起。
引用规则:
- 数字只能来自【执行结果】,**绝不编造**;引用取数结果时在句末加 [^run:编号],编号只能是「数据编号 run:数字」里的数字。
......
......@@ -35,6 +35,8 @@ def setup() -> None:
ksvc.on_publish(_sync_after_publish) # 新版本生效:骨架与关系边跟着刷新
ksvc.register_usage_provider(defs.usage_provider)
ksvc.register_usage_provider(sop_service.usage_provider)
from .watch import service as watch_service
ksvc.register_usage_provider(watch_service.usage_provider)
kernel_api.register_object_section(actions.object_section)
kernel_api.register_object_section(sop_engine.object_section)
templates.register_section("sops", _import_sops, _export_sops)
......
"""动作生命周期:提议 → 校验 → 预览 → 人工审批 → 执行 → 完成/失败 →(可逆则可撤销)。
"""动作生命周期:提议 → 校验 → 预览 → 审批(人工 / 自动)→ 执行 → 完成/失败 →(可逆则可撤销)。
硬约束:
1. 动作只能调用已注册的 Tool,参数经模板替换后再过一次 Tool 的入参校验;
2. **任何动作都要人工审批**(当前阶段的策略),AI 与 SOP 只能提议;
2. 审批策略由动作自己定(approval.mode):manual 人工审批;auto 提议即执行;
conditional 满足 auto_when(或审批决策表输出 auto)就自动执行,否则走人工。
**AI 提议的动作一律人工审批**,自动执行只对人、流程卡、监控发起的生效;
3. 提议人不能审批自己的提议(四眼原则,管理员除外);
4. 同一动作 + 同参数 + 同来源的未决提议不重复创建(幂等键);
5. 每一步状态变化都写审计。
......@@ -19,7 +21,7 @@ from sqlalchemy import func, or_, select
from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit, notify
from ..governance import audit, notify, permissions
from ..kernel import objects, rules
from . import defs, registry
from .models import ActionRun, ApprovalTask
......@@ -117,6 +119,10 @@ def render(v: Any, env: dict) -> Any:
# ---------------- 准备:校验 + 预览 ----------------
def _load_action(ref: str) -> dict:
# `sop:<流程卡>`:把一张已发布的流程卡当成「发起流程」这个动作来审批(见 sop.propose)
if str(ref).startswith("sop:"):
from ..sop import propose as sop_propose
return sop_propose.as_action(str(ref))
a = defs.find(ref, "action")
if a is None:
raise HTTPException(404, f"动作「{ref}」不存在")
......@@ -213,18 +219,43 @@ def _prepare(action: dict, params: dict, object_key: str = "") -> dict:
"approver_roles": spec["approval"]["approver_roles"]},
"params": p, "target_ref": target_ref, "effects": effects,
"summary": ";".join(e["preview"].get("summary", "") for e in effects)}
if (spec["approval"].get("decision") or {}).get("function"):
appr = spec["approval"]
dec: dict = {}
if (appr.get("decision") or {}).get("function") or "rel" in (appr.get("auto_when") or ""):
env["rel"] = _related(spec.get("target_type") or "", env.get("obj_key") or "")
dec = _approval_decision(spec["approval"]["decision"], env)
if (appr.get("decision") or {}).get("function"):
dec = _approval_decision(appr["decision"], env)
if dec:
out["approval_decision"] = dec
if dec.get("priority"):
out["action"]["priority"] = dec["priority"]
if dec.get("approver_roles"):
out["action"]["approver_roles"] = dec["approver_roles"]
env["priority"] = out["action"].get("priority") or _RISK_PRIORITY.get(action["risk_level"], "P2")
out["auto"] = _auto_policy(appr, env, dec)
return out
def _auto_policy(appr: dict, env: dict, dec: dict) -> dict:
"""这一单能不能不等人批、直接执行。条件算不出来一律退回人工审批。"""
mode = appr.get("mode") or "manual"
if mode == "auto":
return {"mode": mode, "eligible": True, "why": "动作设为「自动执行」"}
if mode != "conditional":
return {"mode": "manual", "eligible": False, "why": "动作设为「人工审批」"}
if dec.get("auto") is True:
return {"mode": mode, "eligible": True, "why": f"审批决策表「{dec['function']}」判定可自动执行"}
cond = appr.get("auto_when") or ""
if cond:
try:
if rules.evaluate(cond, env):
return {"mode": mode, "eligible": True, "why": f"满足自动执行条件:{cond}"}
return {"mode": mode, "eligible": False, "why": f"不满足自动执行条件({cond}),转人工审批"}
except rules.RuleError as e:
return {"mode": mode, "eligible": False, "why": f"自动执行条件算不出来({e}),转人工审批"}
return {"mode": mode, "eligible": False, "why": "没有满足自动执行的条件,转人工审批"}
def _related(type_id: str, key: str) -> dict:
"""目标对象沿 n:1 关系走一跳,按关系名放进 rel,供审批决策写
`rel.供货.status == '延期'` 这类跨对象条件。查不到就给空,不让审批流程挂掉。"""
......@@ -278,9 +309,10 @@ def _approval_decision(cfg: dict, env: dict) -> dict:
prio = str(res.get("priority") or "").upper()
approver = res.get("approver_roles") or res.get("approver") or ""
roles = [str(x) for x in approver] if isinstance(approver, list) else ([str(approver)] if approver else [])
auto = res.get("auto")
return {"function": name, "inputs": values, "matched": r.get("matched") or [],
"priority": prio if prio in PRIORITIES else "",
"approver_roles": roles,
"approver_roles": roles, "auto": auto in (True, 1, "true", "True", "是", "yes", "Y"),
"why": f"按决策表「{name}」:" + ",".join(f"{k}={v}" for k, v in values.items())}
......@@ -333,6 +365,13 @@ def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str
if dec.get("why"):
evidence = list(evidence or []) + [{"kind": "rule", "text": dec["why"],
"ref": dec.get("function", "")}]
auto = prep.get("auto") or {}
# AI 提议的一律等人批:自动执行只给人、流程卡、监控发起的
auto_ok = bool(auto.get("eligible")) and initiator_kind != "ai"
if auto.get("mode") in ("auto", "conditional"):
evidence = list(evidence or []) + [{"kind": "rule", "text": (auto.get("why") or "") +
("" if auto_ok or initiator_kind != "ai" else ";AI 提议的动作一律人工审批"),
"ref": "approval.auto"}]
key_src = jdump({"a": prep["action"]["id"], "p": prep["params"], "t": prep["target_ref"],
"s": source_ref})
idem = hashlib.sha1(key_src.encode("utf-8")).hexdigest()
......@@ -351,33 +390,47 @@ def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str
submitted_by=actor.id if actor.kind == "user"
else actor.id[3:] if actor.id.startswith("ai:") else "",
source_ref=source_ref, reason=reason or "",
status="pending_approval", preview_json=jdump(prep),
status="executing" if auto_ok else "pending_approval", preview_json=jdump(prep),
decided_at=now() if auto_ok else None,
idempotency_key=idem, priority=prio,
evidence_json=jdump(_evidence(evidence)),
impact_json=jdump(_impact(prep["target_ref"])))
s.add(run)
roles = prep["action"]["approver_roles"]
s.add(ApprovalTask(id=new_id("ap"), workspace=actor.workspace, run_id=run.id,
approver_roles_json=jdump(roles)))
approver_roles_json=jdump(roles),
**({"status": "auto", "decided_by": "system:auto", "comment": auto.get("why", ""),
"decided_at": now()} if auto_ok else {})))
s.commit()
rid = run.id
out = get(rid)
who = {"ai": "AI", "sop": "流程卡", "watch": "监控"}.get(initiator_kind, "")
audit.record("action.propose", "action_run", rid,
f"{'AI' if initiator_kind == 'ai' else 'SOP' if initiator_kind == 'sop' else ''}"
f"提议动作「{out['action_name']}」:{prep['summary']}",
f"{who}提议动作「{out['action_name']}」:{prep['summary']}",
after={"params": prep["params"], "preview": prep, "reason": reason})
if auto_ok:
audit.record("action.auto_approve", "action_run", rid,
f"自动执行动作「{out['action_name']}」:{auto.get('why', '')}")
out = _execute(rid)
_record_habit(initiator_kind, prep, out, reason)
return out
for r in roles or ["approver"]:
notify.send(f"role:{r}", f"待审批:{out['action_name']}", prep["summary"],
link=f"#/inbox?run={rid}")
if initiator_kind == "user":
from ..memory import service as memory
try:
memory.record_pattern("action", prep["action"]["name"], out["action_name"], reason or prep["summary"])
except Exception: # noqa: BLE001
log.debug("记录操作习惯失败", exc_info=True)
_record_habit(initiator_kind, prep, out, reason)
return out
def _record_habit(initiator_kind: str, prep: dict, out: dict, reason: str) -> None:
if initiator_kind != "user":
return
from ..memory import service as memory
try:
memory.record_pattern("action", prep["action"]["name"], out["action_name"], reason or prep["summary"])
except Exception: # noqa: BLE001
log.debug("记录操作习惯失败", exc_info=True)
# ---------------- 查询 ----------------
def get(run_id: str) -> dict:
with session() as s:
......@@ -401,23 +454,30 @@ def list_runs(*, status: str = "", action_id: str = "", target_ref: str = "",
stmt = stmt.where(ActionRun.target_ref == target_ref)
if source_ref:
stmt = stmt.where(ActionRun.source_ref.like(f"{source_ref}%"))
return [_dict(r) for r in s.scalars(stmt.order_by(ActionRun.created_at.desc())
runs = [_dict(r) for r in s.scalars(stmt.order_by(ActionRun.created_at.desc())
.limit(limit)).all()]
# 列表里的按钮要和后端判断一致:以前审批历史里的「批准」对谁都显示,点了才 403
actor = identity.current()
for r in runs:
if r["status"] == "pending_approval":
why = _can_approve(actor, r, r["preview"].get("action", {}).get("approver_roles") or [])
r["can_approve"], r["cannot_reason"] = not why, why
else:
r["can_approve"], r["cannot_reason"] = False, ""
return runs
def _can_approve(actor: identity.Actor, run: dict, roles: list[str]) -> str:
"""返回不能审批的原因;空串表示可以。"""
if "admin" in actor.roles:
return ""
if not actor.can("approve"):
return "你没有审批权限"
if actor.id in (run["initiator_id"], run["submitted_by"]) or \
run["initiator_id"] == f"ai:{actor.id}":
return "不能审批自己发起的动作(四眼原则)"
if roles and not set(roles) & set(actor.biz_roles + actor.roles):
return (f"此动作需要「{'、'.join(roles)}」审批,你目前不担任这个角色"
f"(管理员可在「成员与角色」里给你加上)")
return ""
"""返回不能审批的原因;空串表示可以(规则统一在 governance.permissions)。
流程卡和监控发起的动作,提议人算流程 / 监控本身,不算「启动它的那个人」—— 参数是已发布的
流程卡定义算出来的,不是谁现填的。否则批准了「发起补货流程」的采购经理,就再也批不了这条
流程里的补货单,整条流程卡在半路上(审批角色该担的责任一点没少,这一单他还是要看过才放行)。
"""
submitters = () if run["initiator_kind"] in ("sop", "watch") \
else (run["initiator_id"], run["submitted_by"])
return permissions.can_decide(actor, perm="approve", roles=roles, what="动作",
submitters=submitters)
def pending_for(actor: identity.Actor) -> list[dict]:
......@@ -465,9 +525,10 @@ def decide(run_id: str, approve: bool, comment: str = "") -> dict:
r.status = "executing" if approve else "rejected"
r.decided_at = now()
s.commit()
exempt = permissions.self_decided(actor, (run["initiator_id"], run["submitted_by"]))
audit.record("action.approve" if approve else "action.reject", "action_run", run_id,
f"{'批准' if approve else '驳回'}动作「{run['action_name']}」"
+ (f":{comment}" if comment else ""))
+ (f":{comment}" if comment else "") + (f"({permissions.ADMIN_NOTE})" if exempt else ""))
notify.send(run["initiator_id"] if not run["initiator_id"].startswith("ai:")
else run["initiator_id"][3:],
f"动作{'已批准' if approve else '被驳回'}:{run['action_name']}", comment,
......@@ -484,12 +545,15 @@ def _execute(run_id: str) -> dict:
return _execute_revert(run_id) if run["kind"] == "revert" else _execute_normal(run_id)
def _execute_normal(run_id: str) -> dict:
"""按批准时冻结的预览逐个执行效果。执行的是被审批过的那组参数,不重新渲染。"""
def _execute_normal(run_id: str, done_before: list[dict] | None = None) -> dict:
"""按批准时冻结的预览逐个执行效果。执行的是被审批过的那组参数,不重新渲染。
done_before:重试时上次已成功的效果结果,这些效果不再重复执行。"""
run = get(run_id)
results = []
results = list(done_before or [])
error = ""
for i, e in enumerate(run["preview"].get("effects") or []):
if i < len(results):
continue
tool = registry.TOOLS.get(e["tool"])
if tool is None:
error = f"工具 {e['tool']} 已不存在"
......@@ -522,6 +586,44 @@ def _execute_normal(run_id: str) -> dict:
return out
def retry(run_id: str) -> dict:
"""执行失败的动作重试:已经成功的效果不再重复,从失败的那一个接着执行。
它已经批过了,所以发起人自己或有审批资格的人都可以点重试。"""
actor = identity.current()
run = get(run_id)
if run["status"] != "failed" or run["kind"] == "revert":
raise HTTPException(409, "只有执行失败的动作可以重试")
if actor.id not in (run["initiator_id"], run["submitted_by"]):
why = _can_approve(actor, run, run["preview"].get("action", {}).get("approver_roles") or [])
if why:
raise HTTPException(403, f"不能重试:{why}")
ok = [e for e in (run["result"] or {}).get("effects") or [] if e.get("ok")]
with session() as s:
r = s.get(ActionRun, run_id)
r.status, r.error, r.finished_at = "executing", "", None
s.commit()
audit.record("action.retry", "action_run", run_id,
f"重试动作「{run['action_name']}」(跳过已成功的 {len(ok)} 个效果)")
return _execute_normal(run_id, ok)
def recover_stuck(minutes: int = 10) -> int:
"""服务重启时,把卡在「执行中」的动作标成失败(可重试)。执行在请求线程里同步进行,
进程中途退出就会留下这种半截状态,以前它们永远停在执行中。"""
import datetime as dt
cutoff = now() - dt.timedelta(minutes=minutes)
n = 0
with session() as s:
for r in s.scalars(select(ActionRun).where(ActionRun.status == "executing",
ActionRun.decided_at < cutoff)).all():
r.status, r.error, r.finished_at = "failed", "服务中断,执行结果未知,可检查后重试", now()
n += 1
s.commit()
if n:
log.warning("把 %d 个卡在执行中的动作标为失败", n)
return n
def cancel(run_id: str, reason: str = "") -> dict:
actor = identity.current()
run = get(run_id)
......
......@@ -54,7 +54,25 @@ class CompleteIn(BaseModel):
async def catalog(_: identity.Actor = Depends(require("view"))):
return {"functions": [f.brief() for f in registry.FUNCTIONS.values()],
"tools": [t.brief() for t in registry.TOOLS.values()],
"defs": defs.list_defs()}
"defs": defs.list_defs(working=True)}
@router.get("/ref-options")
async def ref_options(ref: str, of: str = "", _: identity.Actor = Depends(require("view"))):
"""参数下拉的选项(含草稿,带 status)。ref 见 refs 模块说明,of 为依赖参数当前的值。"""
from . import refs
return refs.options(ref, of)
@router.post("/ref-scan")
async def ref_scan(body: dict, _: identity.Actor = Depends(require("view"))):
"""一组参数引用了哪些还没发布 / 不存在的积木:{function|tool: 名, args}。"""
from . import refs
name = str(body.get("function") or body.get("tool") or "")
d = registry.FUNCTIONS.get(name) or registry.TOOLS.get(name)
if d is None:
raise HTTPException(404, f"没有名为「{name}」的函数或效果")
return refs.scan_refs(d.input_schema, body.get("args") or {})
@router.post("/functions/{name}/call")
......@@ -64,8 +82,9 @@ async def call_function(name: str, body: CallIn, _: identity.Actor = Depends(req
# ---------- 定义 ----------
@router.get("/defs")
async def list_defs(kind: str = "", status: str = "", _: identity.Actor = Depends(require("view"))):
return defs.list_defs(kind, status)
async def list_defs(kind: str = "", status: str = "", working: bool = False,
_: identity.Actor = Depends(require("view"))):
return defs.list_defs(kind, status, working)
@router.post("/defs")
......@@ -132,7 +151,10 @@ async def run_skill(ref: str, body: CallIn, actor: identity.Actor = Depends(requ
# ---------- 动作 ----------
@router.post("/actions/{ref}/prepare")
async def prepare_action(ref: str, body: ProposeIn, _: identity.Actor = Depends(require("ask"))):
return actions.prepare(ref, body.params, body.object_key)
# 预览可以引用草稿(动作本身、它用到的决策表),正式提议仍只认已发布的
from ..kernel import service as ksvc
with ksvc.draft_runtime():
return actions.prepare(ref, body.params, body.object_key)
@router.post("/actions/{ref}/propose")
......@@ -172,6 +194,11 @@ async def decide(run_id: str, body: DecideIn, _: identity.Actor = Depends(requir
return actions.decide(run_id, body.approve, body.comment)
@router.post("/runs/{run_id}/retry")
async def retry(run_id: str, _: identity.Actor = Depends(require("operate"))):
return actions.retry(run_id)
@router.post("/runs/{run_id}/cancel")
async def cancel(run_id: str, body: dict | None = None,
_: identity.Actor = Depends(require("operate"))):
......
......@@ -31,6 +31,15 @@ def _s(desc: str, **kw) -> dict:
return {"type": "string", "description": desc, **kw}
def _r(desc: str, ref: str, *, primary: bool = False, **kw) -> dict:
"""引用本体里某样东西的参数:前端据 x-ref 渲染成下拉选择,而不是让人手填名字。
x-ref 取值见 refs.options;「dimension:metric」这类带冒号的表示「选项依赖同表单里 metric 参数的值」。"""
out = {"type": "string", "description": desc, "x-ref": ref, **kw}
if primary:
out["x-primary"] = True
return out
# =====================================================================
# 函数(只读)
# =====================================================================
......@@ -38,7 +47,7 @@ def _s(desc: str, **kw) -> dict:
"适合回答定义、规则原文、流程说明、为什么这类问题。",
{"type": "object", "properties": {
"query": _s("检索问题,用完整的自然语言"),
"concepts": {"type": "array", "description": "已识别的相关概念名,帮助定位"}},
"concepts": {"type": "array", "description": "已识别的相关概念名,帮助定位", "x-ref": "concept"}},
"required": ["query"]}, category="knowledge",
output_desc="chunks[{id,heading,text}]、entities、relations")
def knowledge_search(args: dict, emit: Emit | None) -> dict:
......@@ -60,7 +69,7 @@ def knowledge_search(args: dict, emit: Emit | None) -> dict:
@function("concept.lookup", "查概念定义", "查本体里某块积木(对象、关系、函数:指标/规则/周期/决策表,动作)的定义、口径与出处。"
"问「X 是什么 / 怎么算 / 口径是什么」时优先用它。",
{"type": "object", "properties": {"name": _s("概念名称或别名")}, "required": ["name"]},
{"type": "object", "properties": {"name": _r("概念名称或别名", "concept", primary=True)}, "required": ["name"]},
category="knowledge", output_desc="概念定义 + spec + 出处")
def concept_lookup(args: dict, emit: Emit | None) -> dict:
c = service.rt_find(args["name"])
......@@ -86,12 +95,13 @@ def concept_lookup(args: dict, emit: Emit | None) -> dict:
"一般直接用 data_ask;已经确切知道指标名和参数时可以直接调它。"
"可按维度拆分、按维度值过滤、按时间(current/last/YYYY-MM 或 {start,end})过滤、按单个对象取值。",
{"type": "object", "properties": {
"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("按哪个统计周期解析时间,不填用指标默认"),
"metric": _r("指标(取哪个数)", "metric", primary=True),
"dimensions": {"type": "array", "description": "按什么拆分(维度)", "x-ref": "dimension:metric"},
"filters": {"type": "object", "description": "只看哪些(维度 = 值)", "x-ref": "filters:metric"},
"time": {"type": ["string", "object"], "description": "统计时间,如 本期 / 上期 / 上周 / 2026-08",
"x-ref": "time"},
"object_key": _s("只取某一个对象的值时填它的主键"),
"calendar": _r("按哪个统计周期解析时间,不填用指标默认", "calendar"),
"limit": {"type": "integer"}},
"required": ["metric"]}, category="data",
output_desc="columns/rows/value/period/sql/run_id")
......@@ -121,7 +131,7 @@ def default_ds_id() -> int:
"还是生成只读 SQL(有校验与自愈),并对结果做体检。所有数据类问题都交给它。",
{"type": "object", "properties": {
"question": _s("取数需求,用完整自然语言,把时间、对象、口径、拆分方式都写清楚"),
"ds_id": {"type": "integer", "description": "数据源编号,一般不填"}},
"ds_id": {"type": "integer", "description": "数据源,一般不填", "x-ref": "datasource"}},
"required": ["question"]}, category="data",
output_desc="route/sql/columns/rows/value/run_id/period/calibre/notes")
def data_ask(args: dict, emit: Emit | None) -> dict:
......@@ -130,7 +140,7 @@ def data_ask(args: dict, emit: Emit | None) -> dict:
@function("object.get", "查对象", "读取一个对象实例的全部属性(业务库 + 写回层)。",
{"type": "object", "properties": {"object_type": _s("对象类型名"),
{"type": "object", "properties": {"object_type": _r("对象类型", "object_type", primary=True),
"key": _s("对象主键")},
"required": ["object_type", "key"]}, category="data")
def object_get(args: dict, emit: Emit | None) -> dict:
......@@ -140,7 +150,7 @@ def object_get(args: dict, emit: Emit | None) -> dict:
@function("object.search", "找对象", "按名称模糊查找对象实例。",
{"type": "object", "properties": {"object_type": _s("对象类型名"), "q": _s("关键词"),
{"type": "object", "properties": {"object_type": _r("对象类型", "object_type", primary=True), "q": _s("关键词"),
"limit": {"type": "integer"}},
"required": ["object_type"]}, category="data")
def object_search(args: dict, emit: Emit | None) -> dict:
......@@ -150,7 +160,8 @@ def object_search(args: dict, emit: Emit | None) -> dict:
@function("object.linked", "查关联对象", "按本体里的关系类型查某个对象的关联对象。",
{"type": "object", "properties": {"object_type": _s("对象类型名"), "key": _s("对象主键")},
{"type": "object", "properties": {"object_type": _r("对象类型", "object_type", primary=True),
"key": _s("对象主键")},
"required": ["object_type", "key"]}, category="data")
def object_linked(args: dict, emit: Emit | None) -> dict:
groups = objects.linked(args["object_type"], str(args["key"]))
......@@ -158,8 +169,9 @@ def object_linked(args: dict, emit: Emit | None) -> dict:
@function("rule.eval", "规则求值", "用本体里的规则(口径/判定/计算)对给定变量求值。",
{"type": "object", "properties": {"rule": _s("规则名称"),
"vars": {"type": "object", "description": "{变量名: 值}"}},
{"type": "object", "properties": {"rule": _r("规则", "rule", primary=True),
"vars": {"type": "object", "description": "规则里的变量取值",
"x-ref": "vars:rule"}},
"required": ["rule"]}, category="logic")
def rule_eval(args: dict, emit: Emit | None) -> dict:
r = service.rt_fn(args["rule"], "rule")
......@@ -178,8 +190,8 @@ def rule_eval(args: dict, emit: Emit | None) -> dict:
@function("calendar.resolve", "解析周期", "把「本期 / 上期 / 某年某月」按统计周期定义解析成起止日期。",
{"type": "object", "properties": {"calendar": _s("统计周期名称,不填为自然月"),
"ref": _s("current / last / prev:N / YYYY-MM / YYYY-MM-DD")},
{"type": "object", "properties": {"calendar": _r("统计周期,不填为自然月", "calendar", primary=True),
"ref": _r("哪一期,如 本期 / 上期 / 2026-08", "time")},
"required": []}, category="logic")
def calendar_resolve(args: dict, emit: Emit | None) -> dict:
spec = None
......@@ -194,8 +206,9 @@ def calendar_resolve(args: dict, emit: Emit | None) -> dict:
@function("decision.eval", "决策表求值", "用本体里的决策表(多条件查表 / 分级)对给定输入求值,返回命中的行与输出。",
{"type": "object", "properties": {"table": _s("决策表名称"),
"inputs": {"type": "object", "description": "{输入列名: 值}"}},
{"type": "object", "properties": {"table": _r("决策表", "decision", primary=True),
"inputs": {"type": "object", "description": "决策表的输入取值",
"x-ref": "vars:table"}},
"required": ["table"]}, category="logic")
def decision_eval(args: dict, emit: Emit | None) -> dict:
d = service.rt_fn(args["table"], "decision")
......@@ -250,8 +263,9 @@ def eval_function(fn: dict, args: dict, *, draft: bool = False) -> dict:
@function("function.eval", "执行函数", "按名称执行本体里任意一个已发布函数(规则 / 决策表 / 周期 / 聚合 / 模型推理 / AI 分析),"
"参数按函数类别给:规则 vars、决策表与模型推理 inputs、周期 ref、聚合 dimensions/filters/time/object_key。",
{"type": "object", "properties": {"name": _s("函数名称"),
"args": {"type": "object", "description": "按函数类别给的参数"}},
{"type": "object", "properties": {"name": _r("函数", "function", primary=True),
"args": {"type": "object", "description": "按函数类别给的参数",
"x-ref": "vars:name"}},
"required": ["name"]}, category="logic")
def function_eval(args: dict, emit: Emit | None) -> dict:
fn = service.rt_find(args["name"], "function")
......@@ -265,7 +279,8 @@ def function_eval(args: dict, emit: Emit | None) -> dict:
@function("ontology.overview", "本体概览", "列出本体里有哪些对象、关系、函数(指标/规则/周期/决策表/模型推理/AI 分析)、动作,"
"回答「能问什么 / 有哪些指标」。",
{"type": "object", "properties": {"kind": _s(
"只看某类:object_type / link_type / aggregate / rule / calendar / decision / ml / ai / action")},
"只看某类", enum=["object_type", "link_type", "aggregate", "rule", "calendar", "decision", "ml",
"ai", "action"])},
"required": []}, category="knowledge")
def ontology_overview(args: dict, emit: Emit | None) -> dict:
fn_cats = ("aggregate", "rule", "calendar", "decision", "ml", "ai")
......@@ -297,8 +312,9 @@ def _object_write_revert(args: dict, result: dict) -> None:
@tool("object.write", "写回对象属性", "修改对象的可写属性(数据源开了「写回业务库」就直接改业务表,否则写在本系统写回层)。",
{"type": "object", "properties": {"object_type": _s("对象类型"), "key": _s("对象主键"),
"property": _s("属性名"), "value": {"description": "新值"}},
{"type": "object", "properties": {"object_type": _r("对象类型", "object_type"), "key": _s("对象主键"),
"property": _r("改哪个属性", "property:object_type"),
"value": {"description": "新值"}},
"required": ["object_type", "key", "property"]},
preview=_object_write_preview, revert=_object_write_revert, risk_level="medium")
def object_write(args: dict, ctx: dict) -> dict:
......@@ -321,8 +337,9 @@ def _object_create_revert(args: dict, result: dict) -> None:
@tool("object.create", "新建对象", "在业务库里新建一个对象(一行),如采购单、工单。数据源必须开启「写回业务库」。",
{"type": "object", "properties": {"object_type": _s("对象类型"),
"values": {"type": "object", "description": "属性名 → 值(含主键)"}},
{"type": "object", "properties": {"object_type": _r("对象类型", "object_type"),
"values": {"type": "object", "description": "各属性的值(含主键)",
"x-ref": "values:object_type"}},
"required": ["object_type", "values"]},
preview=_object_create_preview, revert=_object_create_revert, risk_level="high")
def object_create(args: dict, ctx: dict) -> dict:
......@@ -346,7 +363,7 @@ def _task_revert(args: dict, result: dict) -> None:
@tool("task.create", "派发人工任务", "给某个角色或人派一项待办,可带表单与检查清单。",
{"type": "object", "properties": {
"title": _s("任务标题"), "description": _s("任务说明"),
"role": _s("派给哪个角色"), "assignee": _s("派给具体用户 id"),
"role": _r("派给哪个角色", "role"), "assignee": _r("派给具体的人(可不填)", "user"),
"form": {"type": "array", "description": "[{name,label,type,required}]"},
"checklist": {"type": "array", "description": "检查项列表"},
"due_hours": {"type": "number"}, "object_ref": _s("关联对象 type:key")},
......@@ -372,7 +389,7 @@ def _notify_preview(args: dict) -> dict:
@tool("notify.send", "站内通知", "给用户或角色(role:角色名)发一条站内通知。",
{"type": "object", "properties": {"recipient": _s("用户 id 或 role:角色名"),
{"type": "object", "properties": {"recipient": _r("发给谁(人或角色)", "recipient"),
"title": _s("标题"), "body": _s("正文")},
"required": ["recipient", "title"]},
preview=_notify_preview, risk_level="low")
......@@ -382,6 +399,35 @@ def notify_send(args: dict, ctx: dict) -> dict:
return {"notification_id": nid}
def _sop_start_preview(args: dict) -> dict:
from ..sop import propose as sop_propose
d = sop_propose.require_published(str(args.get("sop") or ""))
steps = sop_propose.outline(d)
return {"summary": f"启动流程卡「{d['title']}」v{d['current_version']},共 {len(steps)} 步:"
+ "→".join(st["title"] for st in steps[:6])
+ ("…" if len(steps) > 6 else ""),
"changes": [{"sop": d["title"], "steps": len(steps),
"params": args.get("params") or {}}],
"sop": {"id": d["id"], "title": d["title"], "description": d["description"],
"steps": steps}}
@tool("sop.start", "发起流程卡", "正式启动一张已发布的流程卡。启动后由流程自己往下走,"
"其中的人工任务会派给对应角色、动作步骤仍各自进人工审批。",
{"type": "object", "properties": {"sop": _r("要发起的流程卡", "sop"),
"params": {"type": "object", "description": "流程参数"}},
"required": ["sop"]},
preview=_sop_start_preview, risk_level="medium")
def sop_start(args: dict, ctx: dict) -> dict:
from ..sop import engine, propose as sop_propose
d = sop_propose.require_published(str(args["sop"]))
params = {k: v for k, v in (args.get("params") or {}).items() if v not in (None, "")}
run = engine.start(d["id"], params, mode="live",
trigger=f"approval:{ctx.get('run_id', '')}" if ctx.get("run_id") else "manual")
return {"sop_run_id": run["id"], "status": run["status"], "sop": d["title"],
"summary": f"已启动流程卡「{d['title']}」,后续步骤由流程自己推进"}
def _endpoint(ref: str) -> dict:
from . import defs
ep = defs.find(ref, "endpoint")
......@@ -400,7 +446,7 @@ def _webhook_preview(args: dict) -> dict:
@tool("webhook.call", "调用外部系统", "调用在能力库里登记过的外部 HTTP 端点(凭据由系统保管)。",
{"type": "object", "properties": {"endpoint": _s("端点名称"),
{"type": "object", "properties": {"endpoint": _r("外部端点", "endpoint"),
"payload": {"type": "object", "description": "请求体"}},
"required": ["endpoint"]},
preview=_webhook_preview, risk_level="high", external=True)
......
......@@ -12,7 +12,9 @@
"params": [{"name","label","type":"string|number|boolean|object|text|enum","required","enum"}],
"criteria": [{"expression": "规则表达式,变量为参数与 obj", "message": "不满足时的提示"}],
"effects": [{"tool": "object.write", "args": {"object_type": "...", "key": "$obj_key", ...}}],
"approval": {"mode": "manual", "approver_roles": ["角色名"]},
"approval": {"mode": "manual|auto|conditional", "approver_roles": ["角色名"],
"decision": {"function": "审批决策表", "inputs": {...}},
"auto_when": "条件自动时的条件表达式,如 priority == 'P3' and eff.amount < 5000"},
"reversible": true
}
参数引用写法:`$参数名`、`$obj.属性`;字符串里也可以内嵌("跟进 $obj.name")。
......@@ -33,6 +35,9 @@ from . import registry
from .models import CapabilityDef
KINDS = {"skill": "AI 分析函数", "action": "动作", "endpoint": "外部端点"}
# 审批策略:manual 一律人工审批;auto 提议即执行(仍留审计、可撤销);
# conditional 满足条件(auto_when 为真,或审批决策表输出 auto=是)自动执行,否则走人工审批。
APPROVAL_MODES = {"manual": "人工审批", "auto": "自动执行", "conditional": "条件自动"}
PARAM_TYPES = ("string", "text", "number", "integer", "boolean", "enum", "object", "date")
_NAME = re.compile(r"^[\w一-鿿.\-]{2,64}$")
_SECRET_KEY = "__secret__"
......@@ -121,7 +126,8 @@ def validate_action(spec: dict) -> tuple[dict, str]:
if not effects:
raise HTTPException(422, "动作至少要有一个效果(调用一个工具)")
appr = spec.get("approval") or {}
approval = {"mode": "manual", # 当前阶段:所有动作一律人工审批
mode = str(appr.get("mode") or "manual")
approval = {"mode": mode if mode in APPROVAL_MODES else "manual",
"approver_roles": [str(x) for x in appr.get("approver_roles") or [] if x]}
# 审批决策函数:用本体里的决策表按「这一单的实际情况」算优先级和审批人。
# 没有它的话优先级只能取动作的静态 risk_level —— 手册里「金额≥5万归采购经理、
......@@ -142,6 +148,19 @@ def validate_action(spec: dict) -> tuple[dict, str]:
if unknown:
raise HTTPException(422, f"审批决策输入「{k}」引用了未定义的变量:{'、'.join(unknown)}")
approval["decision"] = {"function": str(dec["function"]).strip(), "inputs": inputs}
auto_when = str(appr.get("auto_when") or "").strip()
if auto_when:
try:
unknown = [x for x in rules.free_names(auto_when)
if x not in env_names | {"eff", "rel", "priority"}]
except rules.RuleError as ex:
raise HTTPException(422, f"自动执行条件有误:{ex}") from ex
if unknown:
raise HTTPException(422, f"自动执行条件引用了未定义的变量:{'、'.join(unknown)}"
f"(可用:参数、obj、eff(效果里算出的值)、rel(关联对象)、priority)")
approval["auto_when"] = auto_when
if approval["mode"] == "conditional" and not auto_when and "decision" not in approval:
raise HTTPException(422, "「条件自动」要写自动执行条件,或配一张输出 auto 列的审批决策表")
reversible = bool(spec.get("reversible", True)) and all(
registry.TOOLS[e["tool"]].revert is not None for e in effects)
return ({"target_type": target, "params": params, "criteria": criteria, "effects": effects,
......@@ -219,17 +238,23 @@ def _concept_matches(c: dict, kind: str) -> bool:
return False
def list_defs(kind: str = "", status: str = "") -> list[dict]:
def list_defs(kind: str = "", status: str = "", working: bool = False) -> list[dict]:
"""working=True 给配置界面用:发布过但又改了的动作 / AI 函数,返回正在编辑的工作副本
(带 pending_changes 标记),而不是线上那一版 —— 刚给动作加了参数,流程卡里马上就要能填。"""
from ..kernel import service as ksvc
out: list[dict] = []
if kind in ("", "action", "skill"):
rt = ksvc.runtime()
kinds = [kind] if kind else ["skill", "action"]
seen = set()
dirty = {b["id"] for b in ksvc.list_concepts(status="dirty")} if working else set()
for c in rt.values():
for k in kinds:
if _concept_matches(c, k):
out.append(_from_concept(c, True))
if c["id"] in dirty:
out.append({**_from_concept(ksvc.get_concept(c["id"]), True), "pending_changes": True})
else:
out.append(_from_concept(c, True))
seen.add(c["id"])
if status != "published":
for brief in ksvc.list_concepts(kind="action" if kind == "action" else
......
......@@ -8,7 +8,7 @@
- 类型与知识: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
- 流程卡:find_runcard、execute_runcard(live 也只提交审批单,不直接把流程跑起来)
- 动作:propose_action(只进审批队列)、get_action_status —— **不提供审批工具,Agent 不能批**
- 其他:schema_impact(改积木会波及什么)、recall_memory(组织经验)
- 智能体(A2A,只给外部 Agent):ask(主 Agent 统一提问)、ask_knowledge_agent、ask_data_agent
......@@ -92,18 +92,19 @@ def _run_analysis(args: dict, emit: Emit) -> dict:
def _execute_runcard(args: dict, emit: Emit) -> dict:
"""readonly:只跑取数/分析/判断,给诊断结论。live:**不直接启动**,而是提交一张
「发起流程卡」的审批单 —— 跟动作一个规矩,AI 只能提议,人批准了流程才真的跑起来。"""
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']});其中的动作仍需人工审批"}
from ..sop import propose as sop_propose
d = sop_propose.require_published(ref)
ar = _propose({"action": f"sop:{d['id']}", "params": params,
"reason": str(args.get("reason") or f"按流程卡「{d['title']}」处理")}, emit)
return {"action_run_id": ar["id"], "status": ar["status"], "runcard": d["title"],
"summary": f"已提交「发起流程卡『{d['title']}』」的审批单({ar['status']});"
"人批准后流程才会开始跑,之后的每一步由流程自己推进"}
def _propose(args: dict, emit: Emit) -> dict:
......@@ -198,9 +199,11 @@ TOOLS: dict[str, Tool] = {t.name: t for t in [
Tool("find_runcard", "流程卡", "按关键词查已发布的流程卡(SOP),返回步骤、角色与参数。问「X 怎么做」时用。",
{"q": _s("流程关键词")}, [], _fn("sop.find")),
Tool("execute_runcard", "流程卡",
"执行流程卡。mode=readonly(默认)只跑取数/分析/判断部分并给出建议;mode=live 真正启动,其中的动作仍进人工审批。",
"按流程卡处理。mode=readonly(默认)只跑取数/分析/判断部分并给出建议;"
"mode=live 提交一张「发起流程卡」的审批单,人批准后流程才真正开始跑。",
{"runcard": _s("流程卡名称或 id"), "params": {"type": "object", "description": "流程参数"},
"mode": _s("readonly / live", enum=["readonly", "live"])},
"mode": _s("readonly / live", enum=["readonly", "live"]),
"reason": _s("mode=live 时给审批人看的理由")},
["runcard"], _execute_runcard),
Tool("propose_action", "动作",
"提议一个业务动作。动作不会立即执行,而是带着依据与影响面进入人工审批队列,返回审批单。",
......
"""引用选项:函数 / 效果参数上的 x-ref 在这里变成「可选的东西」。
前端所有「填一个本体里的名字」的地方(SOP 步骤参数、动作效果、监控策略、MCP 试调用)都不再让人手填,
而是按参数的 x-ref 取这里的选项。选项包含草稿(status=draft),前端会标出来,
「引用了草稿」的地方在试运行时可用、正式运行前要先发布。
x-ref 取值:
concept / object_type / link_type / action / function / metric / rule / decision / calendar / ml / ai
dimension:<参数> —— 同表单里 <参数>(指标)可拆分的维度
filters:<参数> —— 同上,用于「只看哪些」
property:<参数> / values:<参数> —— 同表单里 <参数>(对象类型)的属性
vars:<参数> —— 同表单里 <参数>(规则 / 决策表 / 函数)需要的输入变量
role / user / recipient / endpoint / datasource / sop / time
"""
from __future__ import annotations
from typing import Any
from fastapi import HTTPException
from ..kernel import schema
from ..kernel import service as ksvc
_FN_CATS = ("aggregate", "rule", "decision", "calendar", "ml", "ai")
# x-ref 的别名 → 函数类别
_CAT_OF = {"metric": "aggregate", "rule": "rule", "decision": "decision", "calendar": "calendar",
"ml": "ml", "ai": "ai"}
TIME_OPTIONS = [
("current", "本期(本月)"), ("last", "上期(上月)"), ("prev:2", "上上期"),
("today", "今天"), ("yesterday", "昨天"), ("this_week", "本周"), ("last_week", "上周"),
("days:7", "近 7 天"), ("days:30", "近 30 天"), ("weeks:4", "近 4 周"),
("this_quarter", "本季度"), ("last_quarter", "上季度"), ("this_year", "今年"),
]
SYSTEM_ROLES = {"approver": "审批人", "builder": "实施工程师", "operator": "业务操作员", "admin": "管理员"}
# ---------------- 概念查找:已发布优先,其次工作副本 ----------------
def lookup(ref: str, kind: str | None = None, category: str | None = None) -> dict | None:
"""按 id / 名称 / 同义词找概念,取**工作副本**(含未发布的修改):配置时看到的应该是正在编辑的样子
(刚给指标绑了维度,下拉里马上就该能选),「是否已发布」由 scan_refs 另行判断。"""
if not ref:
return None
w = ksvc.find(ref, kind)
if w is not None and (not category or (w.get("spec") or {}).get("category") == category):
return ksvc.get_concept(w["id"])
return ksvc.rt_find(ref, kind, category)
def resolve_id(ref: str, kind: str | None = None) -> str:
"""名称或 id → 概念 id;找不到原样返回(让调用方按「不存在」处理)。"""
c = lookup(ref, kind)
return c["id"] if c else (ref or "")
def same_ref(ref: str, concept: dict | None) -> bool:
"""ref(id 或名称或同义词)是否指这个概念。所有「按对象类型比较」的地方都走这里,
不再各自比 id 或比名字(业务建模存名字、编辑器存 id,以前两边对不上)。"""
if not ref or not concept:
return False
r = str(ref).strip().lower()
names = [concept.get("id") or "", concept.get("name") or "", concept.get("display_name") or ""]
names += list(concept.get("synonyms") or [])
return any(r == str(x).strip().lower() for x in names if x)
def object_column(target_type: str, columns: list[str]) -> str:
"""动作作用于某类对象时,一行数据里哪一列是那个对象的主键:列名与对象名 / 主键属性名对得上的优先,
都对不上就取第一列。流程卡配方和监控「按行提议动作」共用。"""
if not target_type or not columns:
return ""
ot = lookup(target_type, "object_type") or {}
spec = ot.get("spec") or {}
key = spec.get("key_property") or ""
cands = [ot.get("name") or "", ot.get("display_name") or "", key]
cands += [p.get("display_name") or "" for p in spec.get("properties") or [] if p.get("name") == key]
for c in columns:
if c in cands or any(x and (x in c or c in x) for x in cands):
return c
return columns[0]
# ---------------- 选项 ----------------
def _concept_opt(c: dict, hint: str = "") -> dict:
published = c.get("status") == "published" or bool(c.get("published"))
return {"value": c["name"], "label": c.get("display_name") or c["name"], "id": c["id"],
"status": "published" if published else "draft",
"group": c.get("kind_label") or schema.kind_label(c["kind"], c.get("spec")),
"hint": hint or (c.get("description") or "")[:60]}
def _concepts(kind: str, category: str | None = None) -> list[dict]:
"""工作副本里的概念(含草稿,不含已废弃)。已发布但工作副本有改动的也算已发布。"""
items = ksvc.list_concepts(kind=kind)
if category:
items = [c for c in items if c.get("category") == category]
return items
def _metric_hint(c: dict) -> str:
full = lookup(c["id"], "function", "aggregate") or {}
b = ksvc.rt_binding(full, "metric_expr") or {}
unit = (full.get("spec") or {}).get("unit") or ""
dims = list((b.get("ref") or {}).get("dimensions") or {})
if not b:
return "还没绑定取数表达式,取不了数"
return ";".join(x for x in [f"单位 {unit}" if unit else "",
f"可按 {'、'.join(dims[:4])} 拆分" if dims else "不可拆分"] if x)
def metric_dimensions(metric_ref: str) -> list[dict]:
m = lookup(metric_ref, "function", "aggregate")
if not m:
return []
b = ksvc.rt_binding(m, "metric_expr") or {}
ref = b.get("ref") or {}
out, seen = [], set()
for name, col in (ref.get("dimensions") or {}).items():
seen.add(name)
out.append({"value": name, "label": name, "hint": f"列 {col}" if col and col != name else ""})
for name in (m.get("spec") or {}).get("dimensions") or []:
if name not in seen:
out.append({"value": name, "label": name, "hint": "(在定义里声明,取数表达式还没绑定这一列)"})
return out
def object_properties(ot_ref: str, writable_only: bool = False) -> list[dict]:
ot = lookup(ot_ref, "object_type")
if not ot:
return []
out = []
for p in (ot.get("spec") or {}).get("properties") or []:
if writable_only and not p.get("is_writable"):
continue
tags = [t for t, on in (("主键", p.get("is_key")), ("时间", p.get("is_time")),
("维度", p.get("is_dimension")), ("可写", p.get("is_writable"))) if on]
out.append({"value": p["name"], "label": p.get("display_name") or p["name"],
"hint": "、".join(tags), "type": p.get("data_type") or "string",
"enum": p.get("enum_values") or []})
return out
def function_inputs(fn_ref: str, category: str | None = None) -> list[dict]:
fn = lookup(fn_ref, "function", category)
if not fn:
return []
spec = fn.get("spec") or {}
cat = spec.get("category")
if cat == "rule":
return [{"value": p, "label": p} for p in spec.get("params") or []]
if cat in ("decision", "ml", "ai"):
return [{"value": i["name"], "label": i.get("label") or i["name"], "type": i.get("type") or ""}
for i in spec.get("inputs") or [] if i.get("name")]
if cat == "calendar":
return [{"value": "ref", "label": "哪一期"}]
if cat == "aggregate":
return [{"value": "time", "label": "统计时间"}, {"value": "object_key", "label": "对象主键"}]
return []
def options(ref: str, of: str = "") -> list[dict]:
"""ref 见模块说明;of 是依赖参数当前的值(如指标名、对象类型名)。"""
base, _, _param = (ref or "").partition(":")
if base in ("dimension", "filters"):
return metric_dimensions(of)
if base in ("property", "values"):
return object_properties(of, writable_only=(base == "property"))
if base == "vars":
return function_inputs(of)
if base == "time":
return [{"value": v, "label": label} for v, label in TIME_OPTIONS]
if base == "concept":
return [_concept_opt(c) for c in _concepts("")]
if base in ("object_type", "link_type", "action"):
return [_concept_opt(c) for c in _concepts(base)]
if base == "function":
return [_concept_opt(c) for c in _concepts("function")]
if base in _CAT_OF:
cat = _CAT_OF[base]
items = _concepts("function", cat)
return [_concept_opt(c, _metric_hint(c) if cat == "aggregate" else "") for c in items]
if base == "role":
from ..governance import roles
biz = [{"value": r["name"], "label": r["name"], "group": "业务角色",
"hint": "、".join(r["members"][:3]) or "还没有人担任"} for r in roles.list_roles()]
return biz + [{"value": k, "label": v, "group": "系统角色"} for k, v in SYSTEM_ROLES.items()]
if base in ("user", "recipient"):
from ..governance import users
us = [{"value": u["id"], "label": u["name"] or u["id"], "group": "人",
"hint": "、".join(u["biz_roles"] or u["roles"])} for u in users.list_users() if u["enabled"]]
if base == "user":
return us
return [{**o, "value": f"role:{o['value']}"} for o in options("role")] + us
if base == "endpoint":
from . import defs
return [{"value": e["name"], "label": e.get("display_name") or e["name"],
"status": "published" if e["status"] == "published" else "draft",
"hint": f"{(e.get('spec') or {}).get('method', 'POST')} {(e.get('spec') or {}).get('url', '')}"[:60]}
for e in defs.list_defs("endpoint")]
if base == "datasource":
from ..text2sql import semantic
return [{"value": d["id"], "label": d.get("name") or f"数据源 {d['id']}",
"hint": d.get("db_type") or d.get("kind") or ""} for d in semantic.list_datasources()]
if base == "sop":
from ..sop import service as sop_service
return [{"value": d["title"], "label": d["title"], "id": d["id"],
"status": "published" if d["current_version"] > 0 else "draft",
"hint": (d.get("description") or "")[:60]} for d in sop_service.list_defs()]
raise HTTPException(422, f"不认识的引用类型:{ref}")
# ---------------- 扫描:一组参数引用了哪些本体积木(用于「引用了草稿」提示) ----------------
def _ref_kind(ref: str) -> tuple[str | None, str | None]:
base = (ref or "").split(":")[0]
if base in _CAT_OF:
return "function", _CAT_OF[base]
if base in ("object_type", "link_type", "action"):
return base, None
if base in ("function", "concept"):
return ("function" if base == "function" else None), None
return None, None
def scan_refs(schema_: dict, args: dict) -> list[dict]:
"""按 input_schema 的 x-ref 找出 args 引用的概念:[{param, ref, name, id, status}]。
status=missing 表示名字对不上任何积木,draft 表示还没发布,changed 表示发布过但又改了还没发布
(如刚给指标绑了取数表达式)—— 这两种试运行都能用,正式运行拿到的还是旧的。$变量 / =表达式 跳过。"""
out = []
for k, p in ((schema_ or {}).get("properties") or {}).items():
ref = p.get("x-ref") or ""
kind, cat = _ref_kind(ref)
if kind is None and ref.split(":")[0] != "concept":
continue
vals: Any = (args or {}).get(k)
for v in (vals if isinstance(vals, list) else [vals]):
if not isinstance(v, str) or not v.strip() or v.startswith(("$", "=")):
continue
out += [{"param": k, "ref": ref, **x} for x in [pending(v, kind, cat)] if x]
return out
def pending(name: str, kind: str | None, category: str | None = None) -> dict | None:
"""这块积木在正式运行时是不是「看不到 / 看到的是旧的」:{name, id, status},都发布了返回 None。"""
w = ksvc.find(name, kind)
if w is not None and category and (w.get("spec") or {}).get("category") != category:
w = None
if ksvc.rt_find(name, kind, category):
return {"name": name, "id": w["id"], "status": "changed"} if w and w.get("dirty") else None
return {"name": name, "id": (w or {}).get("id", ""), "status": "draft" if w else "missing"}
......@@ -35,7 +35,7 @@ class FunctionDef:
def brief(self) -> dict:
return {"kind": "function", "name": self.name, "title": self.title,
"description": self.description, "input_schema": self.input_schema,
"category": self.category, "output": self.output_desc}
"category": self.category, "output": self.output_desc, "binds": primary_param(self.input_schema)}
@dataclass
......@@ -58,6 +58,15 @@ class ToolDef:
"external": self.external}
def primary_param(schema: dict) -> dict | None:
"""函数的「身份参数」(标了 x-primary 的那个):指标取数的 metric、规则求值的 rule……
SOP 编辑器据此把「我的指标 / 规则」直接映射成对内置函数的调用。"""
for k, p in ((schema or {}).get("properties") or {}).items():
if p.get("x-primary"):
return {"param": k, "ref": p.get("x-ref") or ""}
return None
FUNCTIONS: dict[str, FunctionDef] = {}
TOOLS: dict[str, ToolDef] = {}
......
......@@ -110,7 +110,8 @@ def count_open(actor: identity.Actor) -> int:
def _can_handle(actor: identity.Actor, t: dict) -> bool:
if "admin" in actor.roles or t["assignee"] == actor.id:
from ..governance import permissions
if permissions.is_super(actor) or t["assignee"] == actor.id:
return True
return not t["assignee"] and t["role"] in (actor.roles + actor.biz_roles)
......
......@@ -45,6 +45,8 @@ ROUTE_SYSTEM = """你是取数路由器。系统已从问题里识别出一些
1. 能用聚合函数:{{"route":"metric","metric":"函数名","dimensions":["拆分维度"],"filters":{{"维度名":"值"}},
"time":"current|last|YYYY-MM|null","object_key":"只取某个对象时填主键,否则空","order":"desc|asc","limit":数字}}
- dimensions / filters 只能用该函数列出的可拆分维度
- 问题带了时间(上周、本月……)但该函数「不能按时间过滤」(库存、缺口这类时点数)时,**仍然走 metric**,
time 填 null —— 系统会说明按当前值回答;不要因此改走 sql,自己写 SQL 很容易算错口径
- 问排名、分布、各 X 的时候要给 dimensions;问单个对象时给 object_key
2. 聚合函数覆盖不到(要的是明细、要跨多个指标运算、要的维度不支持……):{{"route":"sql","why":"原因"}}
3. 问题缺关键信息、无法取数:{{"route":"clarify","clarify":"向用户追问的一句话"}}
......@@ -110,6 +112,46 @@ def _route(question: str, funcs: list[dict], links: dict) -> dict:
return r if isinstance(r, dict) else {"route": "sql"}
def _with_names(res: dict) -> None:
"""维度本身就是对象(「仓库」「商品」)时,在编号后面补一列名称。
指标按编号拆分,答案里全是 W02 / P013,读的人还得自己去查是哪个仓库、哪个商品 ——
本体里明明知道每个对象的显示名。只加列不改原列,SQL 与口径不变。"""
from ..kernel import objects
cols, rows = list(res.get("columns") or []), [list(r) for r in res.get("rows") or []]
for dim in [c for c in cols if c != "value"]:
if dim not in cols or not ksvc.rt_find(dim, "object_type"):
continue
i = cols.index(dim)
names = objects.labels(dim, [r[i] for r in rows])
if not names:
continue
cols.insert(i + 1, f"{dim}名称")
for r in rows:
r.insert(i + 1, names.get(str(r[i]), ""))
res["columns"], res["rows"] = cols, rows
def _metric_time(r: dict, links: dict, notes: list[str]) -> Any:
"""按指标取数用的时间。
- 问句里识别出了具体起止(上周、近 2 周、今天、本季度……),直接用识别结果:路由器只会说
current/last/YYYY-MM(月粒度),「上周」曾被它说成 last,结果查成了上个月;
- 指标没有时间列(库存、缺口这类时点数)时不带时间,并在备注里说明按当前值回答,
而不是报错降级到自由 SQL。"""
t = r.get("time")
lt = links.get("time") or {}
if lt.get("start") and lt.get("end"):
t = {"start": lt["start"], "end": lt["end"], "period": lt.get("phrase") or ""}
if t in (None, "", "null"):
return None
m = ksvc.rt_fn(str(r["metric"]), "aggregate") or {}
b = ksvc.rt_binding(m, "metric_expr") or {}
if m and not (b.get("ref") or {}).get("time_column"):
notes.append(f"「{m['name']}」是时点数(没有时间列),按当前值回答,没有按「{lt.get('phrase') or t}」过滤")
return None
return t
def _default_ds() -> int:
from ..text2sql import semantic
items = semantic.list_datasources()
......@@ -149,13 +191,14 @@ def ask(question: str, *, ds_id: int = 0, history: list[dict] | None = None,
"summary": f"需要补充信息:{r['clarify']}"}
if r.get("route") == "metric" and r.get("metric"):
try:
t = r.get("time")
t = _metric_time(r, links, notes)
res = metrics.query(str(r["metric"]), dimensions=list(r.get("dimensions") or []),
filters=r.get("filters") if isinstance(r.get("filters"), dict) else {},
time=None if t in (None, "", "null") else t,
object_key=str(r.get("object_key") or ""),
order="asc" if r.get("order") == "asc" else "desc",
limit=int(r.get("limit") or 200), question=question)
_with_names(res)
say({"type": "sql", "sql": res["sql"], "run_id": res["run_id"]})
say({"type": "rows", "columns": res["columns"], "rows": res["rows"][:200]})
res["route"] = "metric"
......@@ -192,7 +235,9 @@ def ask(question: str, *, ds_id: int = 0, history: list[dict] | None = None,
out["truncated"] = ev.get("truncated")
elif t == "plan":
out["plan"] = ev.get("plan")
out["calibre"] = ev.get("calibre")
# 与指标路同形:{name, text}(前端按这个形状显示口径,以前 SQL 路给的是裸字符串,显示成空)
c = ev.get("calibre")
out["calibre"] = {"name": "取数口径", "text": c} if isinstance(c, str) and c else (c or None)
elif t == "answer":
out["answer"] = ev.get("text")
elif t == "error":
......
"""谁能审批 / 办理什么 —— 全系统唯一的判定。
动作审批单、变更提案(发布 / 回滚)、流程卡发布审核、各类审核项、人工任务,以前各自写了一套规则,
导致管理员在一处能批、另一处要「切换身份」才能批。现在统一成:
1. AI 与外部 Agent(kind != user)永远不能审批 —— 它们只能提议;
2. **超级管理员(admin)什么都能批、什么都能办**,包括自己提交的(审计里会注明「管理员审批,豁免四眼原则」);
3. 其他人:要有对应权限;不能批自己提交的(变更提案可在系统设置里为单人团队放开);
指定了审批 / 办理角色的,要担任其中之一。
"""
from __future__ import annotations
from typing import Iterable
from ..core import identity
ADMIN_NOTE = "管理员审批(豁免四眼原则)"
def is_super(actor: identity.Actor) -> bool:
return actor.kind == "user" and "admin" in actor.roles
def can_decide(actor: identity.Actor, *, perm: str = "approve", submitters: Iterable[str] = (),
roles: Iterable[str] = (), allow_self: bool = False, what: str = "这一项") -> str:
"""返回不能审批的原因;空串表示可以。
perm:需要的系统权限(approve 动作审批 / review 审核与提案 / operate 办理任务);
submitters:提交人(含 AI 代提时的 ai:用户 id);roles:指定的审批 / 办理角色(空 = 不限)。"""
if actor.kind != "user":
return "AI 与外部 Agent 不能审批,只能提议"
if "admin" in actor.roles:
return ""
if not actor.can(perm):
return {"approve": "你没有审批权限", "review": "你的角色不能处理审核与变更提案",
"operate": "你的角色不能办理任务"}.get(perm, "你没有这个权限")
mine = {actor.id, f"ai:{actor.id}"}
if not allow_self and any(s in mine for s in submitters if s):
return f"不能审批自己提交的{what}(四眼原则)"
roles = [r for r in roles if r]
if roles and not set(roles) & set(actor.biz_roles + actor.roles):
return (f"{what}需要「{'、'.join(roles)}」处理,你目前不担任这个角色"
f"(管理员可在「成员与角色」里给你加上)")
return ""
def self_decided(actor: identity.Actor, submitters: Iterable[str]) -> bool:
"""管理员批的是不是自己提交的 —— 审计里要注明豁免了四眼原则。"""
return is_super(actor) and any(s in (actor.id, f"ai:{actor.id}") for s in submitters if s)
......@@ -137,6 +137,12 @@ def decide(item_id: str, accept: bool, comment: str = "",
item = _dict(r)
if not accept and not comment.strip():
raise HTTPException(422, "驳回时请填写意见,方便提议方改进")
from . import permissions
why = permissions.can_decide(actor, perm="review", allow_self=True, what="审核项")
if why:
raise HTTPException(403, why)
if accept and permissions.self_decided(actor, [item.get("created_by") or ""]):
comment = (comment + ";" if comment else "") + permissions.ADMIN_NOTE
result: dict[str, Any] = {}
final_payload = payload if payload is not None else item["payload"]
......
......@@ -11,6 +11,7 @@ from pydantic import BaseModel, Field
from sse_starlette.sse import EventSourceResponse
from ..api import deps
from ..capability import refs
from ..core import identity
from ..core.identity import require
from ..governance import audit
......@@ -50,6 +51,7 @@ class BindingIn(BaseModel):
class PublishIn(BaseModel):
note: str = ""
concept_ids: list[str] | None = None
approve_now: bool = False # 提交后如果按审批规则自己就能批(如管理员),直接批准并发布
class ImportIn(BaseModel):
......@@ -346,9 +348,17 @@ async def pending_diff(_: identity.Actor = Depends(require("view"))):
@router.post("/publish")
async def publish(body: PublishIn, _: identity.Actor = Depends(require("build"))):
"""提交变更提案。发布不再一步到位:别人审批通过后才生成新版本。"""
return service.propose_release(body.note, body.concept_ids)
async def publish(body: PublishIn, actor: identity.Actor = Depends(require("build"))):
"""提交变更提案;approve_now=True 且自己有资格批(管理员 / 开了单人自审)时,直接批准并发布。"""
item = service.propose_release(body.note, body.concept_ids)
if not body.approve_now:
return item
why = service.can_decide_release(actor, item)
if why:
return {**item, "published": None, "cannot_reason": why}
from ..governance import review
done = review.decide(item["id"], True, "提交并直接发布")
return {**item, "status": "accepted", "published": done.get("result")}
@router.get("/releases")
......@@ -638,7 +648,7 @@ async def object_360(type_ref: str, key: str, _: identity.Actor = Depends(requir
out["metrics"] = []
for m in service.rt_by_kind("function", "aggregate"):
b = service.rt_binding(m, "metric_expr")
if (m.get("spec") or {}).get("object_type") == ot["id"] and b and b["ref"].get("object_key_column"):
if refs.same_ref((m.get("spec") or {}).get("object_type") or "", ot) and b and b["ref"].get("object_key_column"):
try:
r = metrics.query(m["id"], object_key=key, time="current",
question=f"[对象360] {ot['name']} {key}") \
......@@ -648,6 +658,10 @@ async def object_360(type_ref: str, key: str, _: identity.Actor = Depends(requir
except HTTPException as e:
out["metrics"].append({"metric": {"id": m["id"], "name": m["name"]},
"error": e.detail})
# 可以对它发起的动作:动作的「作用于对象」可能存的是 id 也可能是名称(业务建模存名称),统一按 same_ref 比
from ..capability import defs
out["actions"] = [a for a in defs.list_defs("action", "published")
if refs.same_ref(a["spec"].get("target_type") or "", ot)]
out["edits"] = objects.edit_history(ot["id"], key)
try:
hits = deps.index().search_chunks(obj["label"], k=5)
......
......@@ -44,11 +44,58 @@ def period_of(spec: dict, day: dt.date) -> tuple[int, int]:
return day.year, day.month
_REL_LABEL = {"today": "今天", "yesterday": "昨天", "this_week": "本周", "last_week": "上周",
"this_quarter": "本季度", "last_quarter": "上季度", "this_year": "今年", "last_year": "去年"}
def relative(ref: str, today: dt.date | None = None) -> dict | None:
"""与统计周期无关的相对时间:today / yesterday / this_week / last_week / days:N / weeks:N /
this_quarter / last_quarter / this_year / last_year。认不出返回 None。"""
today = today or dt.date.today()
ref = (ref or "").strip()
s = e = None
if ref == "today":
s = e = today
elif ref == "yesterday":
s = e = today - dt.timedelta(days=1)
elif ref in ("this_week", "last_week"):
mon = today - dt.timedelta(days=today.weekday())
if ref == "last_week":
mon -= dt.timedelta(days=7)
s, e = mon, mon + dt.timedelta(days=6)
elif re.fullmatch(r"(days|weeks):\d{1,4}", ref):
unit, n = ref.split(":")
n = int(n) * (7 if unit == "weeks" else 1)
s, e = today - dt.timedelta(days=n - 1), today
elif ref in ("this_quarter", "last_quarter"):
q0 = (today.month - 1) // 3 * 3 + 1
y, m = _shift(today.year, q0, -3 if ref == "last_quarter" else 0)
s = dt.date(y, m, 1)
ey, em = _shift(y, m, 2)
e = _day(ey, em, "last")
elif ref in ("this_year", "last_year"):
y = today.year - (1 if ref == "last_year" else 0)
s, e = dt.date(y, 1, 1), dt.date(y, 12, 31)
if s is None:
return None
if ref.startswith("days:"):
label = f"近 {ref.split(':')[1]} 天"
elif ref.startswith("weeks:"):
label = f"近 {ref.split(':')[1]} 周"
else:
label = _REL_LABEL[ref]
return {"period": label, "start": s.isoformat(), "end": e.isoformat()}
def resolve(spec: dict | None, ref: str = "current", today: dt.date | None = None) -> dict:
"""ref: current / last / prev:N / next / YYYY-MM / YYYY-MM-DD(该日所在期)。"""
"""ref: current / last / prev:N / next / YYYY-MM / YYYY-MM-DD(该日所在期),
以及与周期无关的相对时间(见 relative)。"""
today = today or dt.date.today()
spec = spec or NATURAL_MONTH
ref = (ref or "current").strip()
rel = relative(ref, today)
if rel:
return rel
if re.fullmatch(r"\d{4}-\d{1,2}", ref):
y, m = (int(x) for x in ref.split("-"))
elif re.fullmatch(r"\d{4}-\d{1,2}-\d{1,2}", ref):
......@@ -100,9 +147,21 @@ def parse_time_phrase(text: str, today: dt.date | None = None) -> dict | None:
m = re.search(r"(本|这个?|当)(月|期)", t)
if m:
return {"ref": "current", "phrase": m.group(0)}
if "昨天" in t:
d = (today - dt.timedelta(days=1)).isoformat()
return {"start": d, "end": d, "phrase": "昨天"}
if "今年" in t:
return {"start": f"{today.year}-01-01", "end": today.isoformat(), "phrase": "今年"}
m = re.search(r"(近|最近|过去)\s*([一二两三四五六七八九十]|\d{1,2})\s*个?(周|星期)", t)
if m:
raw = m.group(2)
n = int(raw) if raw.isdigit() else _CN_NUM.get(raw, 1)
return _rel_hint(f"weeks:{n}", m.group(0), today)
for pat, ref in ((r"上个?(周|星期|礼拜)", "last_week"), (r"(本|这个?)(周|星期|礼拜)", "this_week"),
(r"上个?季度", "last_quarter"), (r"(本|这个?)季度", "this_quarter"),
(r"去年", "last_year"), (r"今年", "this_year"), (r"昨天|昨日", "yesterday"),
(r"今天|今日|当天", "today")):
m = re.search(pat, t)
if m:
return _rel_hint(ref, m.group(0), today)
return None
def _rel_hint(ref: str, phrase: str, today: dt.date) -> dict:
r = relative(ref, today) or {}
return {"ref": ref, "start": r.get("start"), "end": r.get("end"), "phrase": phrase}
"""把本体「喂」给提问:大模型看见的是业务语言(对象、属性、关系),不只是物理表名。
以前提问链路里本体只进了两处:命中的函数名,以及问句里恰好点到的概念(每个 80 字描述)。
对象类型有哪些属性、属性的中文名、对象之间怎么关联 —— 这些建模时花最多力气的东西,
在「提问」里从来没用上;自由 SQL 那一路更是完全绕开本体,只看另一套 sm_* 表结构说明。
这里提供三样东西,都只读已发布版本:
- digest():本体结构摘要(对象 + 关键属性 + 关系),进主 Agent 与问数路由的提示词;
- sql_overlay(ds_id):给自由 SQL 的伪 DDL 加注「这张表是哪个对象、这一列是哪个属性」,
并把本体里的关系(join 绑定)并进允许的关联路径;
- scope_sql(ds_id, sql):按当前用户的数据范围改写 SQL。以前只有指标路和对象查询做了范围过滤,
自由 SQL 路直接查全表 —— 限定了「只看华南仓」的人,换个问法就能看到全部。
"""
from __future__ import annotations
import logging
from . import service as ksvc
log = logging.getLogger(__name__)
def _tables_by_type(ds_id: int | None = None) -> dict[str, dict]:
"""对象类型 id → {concept, table, ref}(只取绑定了表的)。"""
out = {}
for ot in ksvc.rt_by_kind("object_type"):
b = ksvc.rt_binding(ot, "table", ds_id)
if b and (b.get("ref") or {}).get("table"):
out[ot["id"]] = {"concept": ot, "table": b["ref"]["table"], "ref": b["ref"], "ds_id": b["ds_id"]}
return out
def _type_of(ref: str) -> dict | None:
return ksvc.rt_find(ref, "object_type") if ref else None
def digest(limit_chars: int = 1800) -> str:
"""本体结构摘要:对象(主键 + 最多 8 个属性,带中文名 / 单位 / 可选值)与关系(A —关系→ B)。"""
lines: list[str] = []
for ot in ksvc.rt_by_kind("object_type"):
spec = ot.get("spec") or {}
props = []
for p in (spec.get("properties") or [])[:8]:
label = p["name"] + (f"({p['display_name']})" if p.get("display_name") else "")
tags = [t for t, on in (("主键", p.get("is_key")), ("维度", p.get("is_dimension")),
("时间", p.get("is_time"))) if on]
if p.get("enum_values"):
tags.append("取值 " + "/".join(p["enum_values"][:5]))
props.append(label + (f"[{','.join(tags)}]" if tags else ""))
desc = (ot.get("description") or "")[:30]
lines.append(f"- 对象「{ot['name']}」{(':' + desc) if desc else ''} 属性:{'、'.join(props) or '(未定义)'}")
for lt in ksvc.rt_by_kind("link_type"):
spec = lt.get("spec") or {}
a, b = _type_of(spec.get("from_type") or ""), _type_of(spec.get("to_type") or "")
if not a or not b:
continue
lines.append(f"- 关系「{lt['name']}」:{a['name']} → {b['name']}({spec.get('cardinality') or 'n:1'})")
text = "\n".join(lines)
if len(text) > limit_chars:
text = text[:limit_chars].rsplit("\n", 1)[0] + "\n- ……(其余略,可用 list_ontology_types / lookup_concept 查)"
return text or "(还没有已发布的对象)"
def sql_overlay(ds_id: int) -> dict:
"""{tables: {表名小写: {concept, cols: {列名小写: 属性说明}}}, joins: [{from, to, name}]}。"""
tables: dict[str, dict] = {}
by_type = _tables_by_type(ds_id)
for tid, t in by_type.items():
ot, ref = t["concept"], t["ref"]
props = {p["name"]: p for p in (ot.get("spec") or {}).get("properties") or []}
cols = {}
for prop, col in (ref.get("columns") or {}).items():
p = props.get(prop) or {}
label = prop + (f"({p['display_name']})" if p.get("display_name") else "")
cols[str(col).lower()] = f"本体属性:{ot['name']}.{label}"
if ref.get("key_column"):
cols.setdefault(str(ref["key_column"]).lower(), f"本体属性:{ot['name']} 的主键")
tables[t["table"].lower()] = {"concept": ot["name"], "cols": cols}
joins = []
for lt in ksvc.rt_by_kind("link_type"):
spec = lt.get("spec") or {}
b = ksvc.rt_binding(lt, "join", ds_id)
a_ot, b_ot = _type_of(spec.get("from_type") or ""), _type_of(spec.get("to_type") or "")
if not b or not a_ot or not b_ot or a_ot["id"] not in by_type or b_ot["id"] not in by_type:
continue
ref = b.get("ref") or {}
if not ref.get("from_column") or not ref.get("to_column"):
continue
joins.append({"from": f"{by_type[a_ot['id']]['table']}.{ref['from_column']}".lower(),
"to": f"{by_type[b_ot['id']]['table']}.{ref['to_column']}".lower(),
"name": f"{a_ot['name']} —{lt['name']}→ {b_ot['name']}"})
return {"tables": tables, "joins": joins}
def scope_sql(ds_id: int, sql: str, dialect: str = "mysql") -> str:
"""按当前用户的数据范围改写 SQL:受限对象的表替换成「带范围条件的子查询」,别名不变。
没有范围限制时原样返回;改写失败时拒绝执行(宁可不给数,也不越权给数)。"""
from ..core import identity
from .objects import _scope_where
scope = identity.current().scope or {}
if not scope:
return sql
restricted: dict[str, list[str]] = {}
for tid, t in _tables_by_type(ds_id).items():
if tid not in scope:
continue
conds = _scope_where(t["concept"], t["ref"])
if conds:
restricted[t["table"].lower()] = conds
if not restricted:
return sql
import sqlglot
from sqlglot import exp
try:
tree = sqlglot.parse_one(sql, dialect=dialect)
except Exception as e: # noqa: BLE001
raise ValueError(f"无法按数据范围改写这条 SQL:{e}") from e
ctes = {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
for tbl in list(tree.find_all(exp.Table)):
name = tbl.name.lower()
if name in ctes or name not in restricted:
continue
alias = tbl.alias_or_name
base = exp.Table(this=tbl.this.copy(), db=tbl.args["db"].copy() if tbl.args.get("db") else None)
# 范围条件是按 MySQL 引号拼的(sqlutil.ident / lit),按 mysql 读进来,输出时再转成目标方言
cond = sqlglot.condition(" AND ".join("(" + c + ")" for c in restricted[name]), dialect="mysql")
sub = exp.select("*").from_(base).where(cond)
tbl.replace(exp.Subquery(this=sub, alias=exp.TableAlias(this=exp.to_identifier(alias))))
return tree.sql(dialect=dialect)
def used_concepts(results: list[dict]) -> list[dict]:
"""从一轮提问里各工具的结果中,摘出**实际执行过**的本体积木(而不是问句里匹配到的)。"""
seen: dict[str, dict] = {}
def add(name: str, kind: str, how: str) -> None:
if not name:
return
c = ksvc.rt_find(name)
if c is None and kind == "口径": # 自由 SQL 路的「取数口径」只是一段说明,不是本体里的积木
return
key = (c or {}).get("id") or f"{kind}:{name}"
if key not in seen:
seen[key] = {"id": (c or {}).get("id", ""), "name": (c or {}).get("name") or name,
"kind_label": (c or {}).get("kind_label") or kind, "how": how}
for r in results or []:
if not isinstance(r, dict):
continue
m = r.get("metric")
if isinstance(m, dict) and m.get("name"):
add(m["name"], "指标", "取数")
calibre = r.get("calibre")
if isinstance(calibre, dict) and calibre.get("name"):
add(calibre["name"], "口径", "口径")
for k, how in (("rule", "规则求值"), ("table", "决策表"), ("function", "函数")):
v = r.get(k)
if isinstance(v, str):
add(v, how, how)
elif isinstance(v, dict) and v.get("name"):
add(v["name"], how, how)
c = r.get("concept")
if isinstance(c, dict) and c.get("name"):
add(c["name"], c.get("kind_label") or "概念", "查定义")
if r.get("type_name"):
add(r["type_name"], "对象", "查对象")
return list(seen.values())
......@@ -24,7 +24,7 @@ def invalidate() -> None:
def _lexicon(ws: str) -> list[tuple[str, dict]]:
key = ws + ("#draft" if service._draft_mode.get() else "")
key = ws + ("#draft" if service.in_draft_mode() else "")
with _lock:
hit = _cache.get(key)
if hit and time.time() - hit[0] < _TTL:
......
......@@ -125,6 +125,25 @@ 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]
def labels(type_ref: str, keys: list[Any]) -> dict[str, str]:
"""一批主键 → 显示名(一条 SQL)。对象没有名称列、没绑表或查不到时返回空,调用方照原样显示主键。"""
ot = service.rt_find(type_ref, "object_type")
if not ot or not keys:
return {}
b = service.rt_binding(ot, "table")
ref = (b or {}).get("ref") or {}
if not ref.get("label_column"):
return {}
ks = list(dict.fromkeys(str(k) for k in keys if k not in (None, "")))[:200]
sql = (f"SELECT {ident(ref['key_column'])}, {ident(ref['label_column'])} FROM {ident(ref['table'])} "
f"WHERE {ident(ref['key_column'])} IN ({', '.join(lit(k) for k in ks)})")
try:
_, rows = _run(b["ds_id"], sql)
except HTTPException:
return {}
return {str(r[0]): str(r[1]) for r in rows if r[1] not in (None, "")}
def instances(workspace: str) -> list[dict]:
with session() as s:
return [{"concept_id": r.concept_id, "key": r.obj_key, "label": r.label}
......
......@@ -439,14 +439,14 @@ def _accept_create(payload: dict, item: dict) -> dict:
spec = _resolve_refs(kind, dict(payload.get("spec") or {}))
desc = payload.get("description", "")
if kind == "action" and spec.get("_stub"):
# 文档只说明了「要有这个动作」:建成待补全的草稿(效果先用通知占位,审批人需在动作编辑器里改)
# 文档只说明了「要有这个动作」:建成待补全的草稿。效果先设成「派一项待办」——
# 批准后至少会真的落成一件有人跟进的事,而不是只发一条通知就结束。
text = spec.get("text") or desc
desc = f"{desc}(AI 从文档提议,请补全参数与效果:{text})" if text and text != desc else desc
spec = {"target_type": "", "params": [{"name": "reason", "label": "原因", "type": "text",
"required": True}],
"effects": [{"tool": "notify.send", "args": {"recipient": "role:approver",
"title": payload["name"],
"body": "$reason"}}],
"effects": [{"tool": "task.create", "args": {"title": payload["name"], "role": "operator",
"description": "$reason"}}],
"approval": {"mode": "manual", "approver_roles": []}}
c = service.create_concept(kind, payload["name"], display_name=payload.get("display_name", ""),
description=desc,
......
......@@ -61,19 +61,27 @@ _rt_lock = threading.Lock()
_RT_TTL = 30.0
# 评测「待发布版本」时,运行时临时改读工作副本(含未发布的修改)
_draft_mode: contextvars.ContextVar[bool] = contextvars.ContextVar("onto_draft_mode", default=False)
# 预演(SOP 试运行、单步试跑、监控试扫描、动作预览、评测「待发布版本」)时,运行时改读工作副本(含草稿)。
# 值是这次预演自己的缓存 {workspace: {id: 概念}},None 表示正常模式;正式运行永远只认已发布的。
_draft_mode: contextvars.ContextVar[dict | None] = contextvars.ContextVar("onto_draft_mode", default=None)
@contextlib.contextmanager
def draft_runtime():
tok = _draft_mode.set(True)
if _draft_mode.get() is not None: # 已在预演里(如子流程):沿用同一份缓存
yield
return
tok = _draft_mode.set({})
try:
yield
finally:
_draft_mode.reset(tok)
def in_draft_mode() -> bool:
return _draft_mode.get() is not None
def invalidate_runtime() -> None:
with _rt_lock:
_rt_cache.clear()
......@@ -82,10 +90,19 @@ def invalidate_runtime() -> None:
def runtime(workspace: str | None = None) -> dict[str, dict]:
"""已发布、未废弃的概念:id → 概念 dict(含 spec 与 bindings)。"""
ws = workspace or _ws()
if _draft_mode.get():
with session() as s:
return {c.id: _publish_copy(s, c) for c in s.scalars(select(Concept).where(
Concept.workspace == ws, Concept.status != "deprecated")).all()}
draft_cache = _draft_mode.get()
if draft_cache is not None:
if ws not in draft_cache:
with session() as s:
out = {}
for c in s.scalars(select(Concept).where(Concept.workspace == ws,
Concept.status != "deprecated")).all():
try:
out[c.id] = _publish_copy(s, c)
except Exception: # noqa: BLE001 坏草稿不拖垮整次预演
log.warning("预演时读取草稿 %s 失败", c.id, exc_info=True)
draft_cache[ws] = out
return draft_cache[ws]
with _rt_lock:
hit = _rt_cache.get(ws)
if hit and time.time() - hit[0] < _RT_TTL:
......@@ -752,16 +769,16 @@ def propose_rollback(rev: int, note: str = "") -> dict:
def can_decide_release(actor: identity.Actor, item: dict) -> str:
"""返回不能审批的原因;空串表示可以。"""
"""返回不能审批的原因;空串表示可以。管理员什么都能批(含自己提交的,审计里注明);
其他人不能批自己的,单人团队可在系统设置里放开(RELEASE_SELF_APPROVE)。"""
from ..core import db as core_db
if actor.kind != "user":
return "AI 与外部 Agent 不能审批变更提案"
if not (actor.can("review") or actor.can("approve")):
return "变更提案要由实施工程师或审批人来批,你的角色没有这个权限"
from ..governance import permissions
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 ""
why = permissions.can_decide(actor, perm="review", submitters=[item.get("created_by") or ""],
allow_self=self_ok, what="变更提案")
if why.startswith("不能审批自己"):
why += ";单人团队可在「系统设置 → 治理」里打开「允许自审变更提案」"
return why
def _accept_release(payload: dict, item: dict) -> dict:
......
......@@ -22,7 +22,7 @@ from .governance import api as gov_api, users as gov_users
from .kernel import api as kernel_api
from .memory import api as memory_api
from .orchestrator import api as ask_api
from .sop import api as sop_api, triggers as sop_triggers
from .sop import api as sop_api
from .watch import api as watch_api, scheduler as watch_scheduler
from .core import db
from .core.config import get_settings
......@@ -53,6 +53,8 @@ async def lifespan(app: FastAPI):
if pipeline.reap_stale():
log.warning("清理了上次进程残留的数据管道 / 业务建模运行")
gov_users.seed()
from .capability import actions as cap_actions
cap_actions.recover_stuck()
try:
from .watch import service as watch_service
watch_service.migrate_sop_triggers()
......
......@@ -6,8 +6,7 @@ from pydantic import BaseModel, Field
from ..core import identity
from ..core.identity import require
from ..governance import audit
from . import draft, engine, service, spec as sop_spec, triggers
from . import draft, engine, recipes, service, spec as sop_spec
router = APIRouter(prefix="/api/sop", tags=["sop"])
......@@ -116,13 +115,16 @@ async def run(def_id: str, body: RunIn, _: identity.Actor = Depends(require("ope
wait=(mode == "ai_readonly"))
@router.post("/defs/{def_id}/trigger-scan")
async def trigger_scan(def_id: str, body: dict | None = None,
_: identity.Actor = Depends(require("operate"))):
out = triggers.metric_scan(def_id, dry=bool((body or {}).get("dry", True)))
audit.record("sop.trigger_scan", "sop", def_id,
f"指标触发扫描:命中 {len(out['hits'])},启动 {len(out['started'])}")
return out
@router.get("/recipes")
async def list_recipes(_: identity.Actor = Depends(require("view"))):
"""场景配方:选几样本体里已有的东西,直接生成一张能跑的流程卡。"""
return recipes.list_recipes()
@router.post("/recipes/{recipe_id}")
async def create_from_recipe(recipe_id: str, body: dict, _: identity.Actor = Depends(require("build"))):
built = recipes.build(recipe_id, body.get("fields") or {})
return service.create(body.get("title") or built["title"], built["description"], built["spec"])
@router.get("/runs")
......
......@@ -26,6 +26,7 @@ from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit, notify
from ..kernel import objects, rules
from ..kernel import service as ksvc
from . import service
from . import spec as sop_spec
from .models import SopRun, SopStepRun
......@@ -120,6 +121,23 @@ def _rows_of(v: Any) -> list[dict]:
return []
def _pick_rows(step: dict, src: Any, env: dict, default_limit: int = 20) -> list[dict]:
"""逐行处理要处理的行:先按「只处理满足条件的行」筛(如 value > 0,条件里可直接写列名或 item.列名),再截上限。
以前没法筛,缺口为 0 的行也逐个去发动作,结果一半是「前置条件不满足」。"""
rows = _rows_of(src)
cond = str(step.get("when") or "").strip()
if cond:
kept = []
for r in rows:
try:
if rules.evaluate(cond, {**env, **r, "item": r}):
kept.append(r)
except rules.RuleError as e:
raise HTTPException(422, f"「{step['title']}」的筛选条件「{cond}」求值失败:{e}") from e
rows = kept
return rows[: int(step.get("limit") or default_limit)]
def _foreach(run: dict, step: dict, sid: str, rows: list[dict], env: dict, mode: str) -> tuple[list[dict], int]:
"""逐行发起动作。正式运行时每行一张审批单(不等审批,流程继续往下走);试运行 / AI 剧本只做预览。"""
results: list[dict] = []
......@@ -317,202 +335,251 @@ def _finish(run_id: str, status: str, outcome: str = "", error: str = "") -> Non
def advance(run_id: str) -> dict:
"""从当前步骤一直往下走,直到需要等待(人工/审批/子流程)或结束。"""
"""从当前步骤一直往下走,直到需要等待(人工/审批/子流程)或结束。
试运行读工作副本(草稿里的指标、规则、动作都能用上);正式运行只认已发布的积木。"""
with _lock(run_id):
run = get_run(run_id)
if run["status"] not in ("running",):
return run
spec = run["spec"]
by_id = {st["id"]: st for st in spec["steps"]}
env = dict(run["vars"])
cur = run["current_step"]
mode = run["mode"]
for _ in range(MAX_STEPS):
step = by_id.get(cur)
if step is None:
_finish(run_id, "failed", error=f"步骤 {cur} 不存在")
if run["mode"] == "dry_run":
with ksvc.draft_runtime():
return _advance(run_id, run)
return _advance(run_id, run)
def _action_outcome(step: dict, sr_id: str, ar: dict) -> tuple[str, str, dict] | None:
"""动作已经有结果时(自动执行的动作在提议当下就执行完了)决定流程往哪走。
返回 (下一步, 说明, 输出);返回 None 表示动作还在等审批。下一步为空串表示流程应当结束(失败 / 驳回)。
审批后回调 _on_action 与提议当下内联继续共用这一套判断。"""
out = {"status": ar["status"], "action_run_id": ar["id"], "result": ar.get("result")}
if ar["status"] == "done":
how = "自动执行完成" if (ar.get("approvals") or [{}])[0].get("status") == "auto" else "动作已批准并执行"
return step["next"], how, out
if ar["status"] in ("rejected", "cancelled"):
if step.get("on_reject"):
return step["on_reject"], "动作被驳回,走驳回分支", out
comment = (ar.get("approvals") or [{}])[0].get("comment", "")
return "", f"动作被驳回:{comment}", out
if ar["status"] == "failed":
return "", f"动作执行失败:{ar.get('error')}", out
return None
def _advance(run_id: str, run: dict) -> dict:
spec = run["spec"]
by_id = {st["id"]: st for st in spec["steps"]}
env = dict(run["vars"])
cur = run["current_step"]
mode = run["mode"]
for _ in range(MAX_STEPS):
step = by_id.get(cur)
if step is None:
_finish(run_id, "failed", error=f"步骤 {cur} 不存在")
break
_set_run(run_id, current_step=cur)
t = step["type"]
if t == "end":
sid = _new_step(run_id, step)
_update_step(sid, status="done", note=step.get("outcome", ""))
_set_run(run_id, vars=env)
_finish(run_id, "done", outcome=step.get("outcome") or step["title"])
break
if t == "decision":
chosen, label = step.get("default"), "默认"
for b in step.get("branches") or []:
try:
if rules.evaluate(b["when"], env):
chosen, label = b["next"], b.get("label") or b["when"]
break
except rules.RuleError as e:
sid = _new_step(run_id, step)
_update_step(sid, status="failed", error=f"条件「{b['when']}」求值失败:{e}")
_finish(run_id, "failed", error=f"判断「{step['title']}」求值失败:{e}")
return get_run(run_id)
sid = _new_step(run_id, step, {"env_keys": list(env)})
_update_step(sid, status="done", output={"branch": label, "next": chosen},
note=f"走「{label}」分支")
cur = chosen
continue
if t == "function":
args = _render(step.get("args") or {}, env)
sid = _new_step(run_id, step, args)
try:
res = registry.call_function(step["function"], args)
except HTTPException as e:
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=f"「{step['title']}」失败:{e.detail}")
break
_set_run(run_id, current_step=cur)
t = step["type"]
if t == "end":
sid = _new_step(run_id, step)
_update_step(sid, status="done", note=step.get("outcome", ""))
_set_run(run_id, vars=env)
_finish(run_id, "done", outcome=step.get("outcome") or step["title"])
_update_step(sid, status="done", output=_compact(res), note=res.get("summary", ""))
if step.get("output"):
env[step["output"]] = res
_set_run(run_id, vars=env)
cur = step["next"]
continue
if t == "skill":
inputs = _render(step.get("inputs") or {}, env)
sid = _new_step(run_id, step, inputs)
try:
res = skills.run(step["skill"], inputs, require_published=(mode == "live"))
except HTTPException as e:
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=f"「{step['title']}」失败:{e.detail}")
break
if t == "decision":
chosen, label = step.get("default"), "默认"
for b in step.get("branches") or []:
try:
if rules.evaluate(b["when"], env):
chosen, label = b["next"], b.get("label") or b["when"]
break
except rules.RuleError as e:
sid = _new_step(run_id, step)
_update_step(sid, status="failed", error=f"条件「{b['when']}」求值失败:{e}")
_finish(run_id, "failed", error=f"判断「{step['title']}」求值失败:{e}")
return get_run(run_id)
sid = _new_step(run_id, step, {"env_keys": list(env)})
_update_step(sid, status="done", output={"branch": label, "next": chosen},
note=f"走「{label}」分支")
cur = chosen
continue
if t == "function":
args = _render(step.get("args") or {}, env)
sid = _new_step(run_id, step, args)
try:
res = registry.call_function(step["function"], args)
except HTTPException as e:
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=f"「{step['title']}」失败:{e.detail}")
break
_update_step(sid, status="done", output=_compact(res), note=res.get("summary", ""))
_update_step(sid, status="done", output=res, note=res.get("summary", ""))
if step.get("output"):
env[step["output"]] = res.get("output")
_set_run(run_id, vars=env)
cur = step["next"]
continue
if t == "human_task":
ctx = {"sop_run": run_id, "title": run["title"],
"vars": {k: _compact(v) for k, v in env.items()}}
if mode == "dry_run":
sid = _new_step(run_id, step, ctx)
fake = {f["name"]: f"(试运行:{f.get('label') or f['name']})" for f in step.get("form") or []}
_update_step(sid, status="done", output=fake, note="试运行:人工任务视为已完成")
if step.get("output"):
env[step["output"]] = res
_set_run(run_id, vars=env)
env[step["output"]] = fake
cur = step["next"]
continue
if t == "skill":
inputs = _render(step.get("inputs") or {}, env)
sid = _new_step(run_id, step, inputs)
if mode == "ai_readonly":
sid = _new_step(run_id, step, ctx)
_update_step(sid, status="suggested",
note=f"需要「{step.get('role')}」处理:{step.get('instructions') or step['title']}")
_set_run(run_id, vars=env)
_finish(run_id, "paused", outcome=f"下一步需要人工:{step['title']}")
break
sid = _new_step(run_id, step, ctx)
due = None
if step.get("sla_hours"):
import datetime as dt
due = dt.datetime.now() + dt.timedelta(hours=step["sla_hours"])
obj_ref = ""
for p in spec.get("params") or []:
if p["type"] == "object" and isinstance(env.get(p["name"]), dict):
obj_ref = f"{p['object_type']}:{env[p['name']].get('key')}"
break
task = tasks.create(
title=f"{run['title']} · {step['title']}",
description=_render(step.get("instructions") or step.get("description") or "", env),
role=step.get("role", ""), form=step.get("form"),
checklist=step.get("checklist"), due_at=due, object_ref=obj_ref,
source_type="sop", source_id=sid, context=ctx)
_update_step(sid, status="waiting_human", task_id=task["id"])
_set_run(run_id, status="waiting", vars=env)
break
if t == "action":
params = _render(step.get("params") or {}, env)
okey = _render(step.get("object_key") or "", env)
if isinstance(okey, dict):
okey = okey.get("key", "")
sid = _new_step(run_id, step, {"params": params, "object_key": okey})
if mode in ("dry_run", "ai_readonly"):
try:
res = skills.run(step["skill"], inputs, require_published=(mode == "live"))
prep = actions.prepare(step["action"], params, str(okey or ""))
except HTTPException as e:
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=f"「{step['title']}」失败:{e.detail}")
_update_step(sid, status="failed", error=f"动作预览失败:{e.detail}")
_finish(run_id, "failed", error=f"「{step['title']}」动作预览失败:{e.detail}")
break
if mode == "ai_readonly":
_update_step(sid, status="suggested", output={"preview": prep},
note=f"建议发起动作:{prep['summary']}")
_finish(run_id, "paused", outcome=f"建议动作:{prep['summary']}")
break
_update_step(sid, status="done", output=res, note=res.get("summary", ""))
_update_step(sid, status="done", output={"preview": prep},
note=f"试运行:仅预览,视为批准。{prep['summary']}")
if step.get("output"):
env[step["output"]] = res.get("output")
_set_run(run_id, vars=env)
env[step["output"]] = {"status": "approved", "preview": prep}
cur = step["next"]
continue
if t == "human_task":
ctx = {"sop_run": run_id, "title": run["title"],
"vars": {k: _compact(v) for k, v in env.items()}}
if mode == "dry_run":
sid = _new_step(run_id, step, ctx)
fake = {f["name"]: f"(试运行:{f.get('label') or f['name']})" for f in step.get("form") or []}
_update_step(sid, status="done", output=fake, note="试运行:人工任务视为已完成")
if step.get("output"):
env[step["output"]] = fake
cur = step["next"]
continue
if mode == "ai_readonly":
sid = _new_step(run_id, step, ctx)
_update_step(sid, status="suggested",
note=f"需要「{step.get('role')}」处理:{step.get('instructions') or step['title']}")
_set_run(run_id, vars=env)
_finish(run_id, "paused", outcome=f"下一步需要人工:{step['title']}")
break
sid = _new_step(run_id, step, ctx)
due = None
if step.get("sla_hours"):
import datetime as dt
due = dt.datetime.now() + dt.timedelta(hours=step["sla_hours"])
obj_ref = ""
for p in spec.get("params") or []:
if p["type"] == "object" and isinstance(env.get(p["name"]), dict):
obj_ref = f"{p['object_type']}:{env[p['name']].get('key')}"
break
task = tasks.create(
title=f"{run['title']} · {step['title']}",
description=_render(step.get("instructions") or step.get("description") or "", env),
role=step.get("role", ""), form=step.get("form"),
checklist=step.get("checklist"), due_at=due, object_ref=obj_ref,
source_type="sop", source_id=sid, context=ctx)
_update_step(sid, status="waiting_human", task_id=task["id"])
_set_run(run_id, status="waiting", vars=env)
break
if t == "action":
params = _render(step.get("params") or {}, env)
okey = _render(step.get("object_key") or "", env)
if isinstance(okey, dict):
okey = okey.get("key", "")
sid = _new_step(run_id, step, {"params": params, "object_key": okey})
if mode in ("dry_run", "ai_readonly"):
try:
prep = actions.prepare(step["action"], params, str(okey or ""))
except HTTPException as e:
_update_step(sid, status="failed", error=f"动作预览失败:{e.detail}")
_finish(run_id, "failed", error=f"「{step['title']}」动作预览失败:{e.detail}")
break
if mode == "ai_readonly":
_update_step(sid, status="suggested", output={"preview": prep},
note=f"建议发起动作:{prep['summary']}")
_finish(run_id, "paused", outcome=f"建议动作:{prep['summary']}")
break
_update_step(sid, status="done", output={"preview": prep},
note=f"试运行:仅预览,视为批准。{prep['summary']}")
if step.get("output"):
env[step["output"]] = {"status": "approved", "preview": prep}
cur = step["next"]
continue
sop_actor = identity.Actor(id=run["started_by"] or "system",
name=f"SOP「{run['title']}」", kind="system",
roles=["operator"], workspace=identity.current().workspace)
tok = identity.set_current(sop_actor)
try:
ar = actions.propose(step["action"], params, object_key=str(okey or ""),
reason=f"SOP「{run['title']}」步骤「{step['title']}」",
initiator_kind="sop", source_ref=f"sop_step:{sid}",
evidence=_step_evidence(run, step, env))
except HTTPException as e:
identity.reset(tok)
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=f"「{step['title']}」提交动作失败:{e.detail}")
break
sop_actor = identity.Actor(id=run["started_by"] or "system",
name=f"SOP「{run['title']}」", kind="system",
roles=["operator"], workspace=identity.current().workspace)
tok = identity.set_current(sop_actor)
try:
ar = actions.propose(step["action"], params, object_key=str(okey or ""),
reason=f"SOP「{run['title']}」步骤「{step['title']}」",
initiator_kind="sop", source_ref=f"sop_step:{sid}",
evidence=_step_evidence(run, step, env))
except HTTPException as e:
identity.reset(tok)
_update_step(sid, status="waiting_approval", action_run_id=ar["id"],
note=ar["preview"].get("summary", ""))
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=f"「{step['title']}」提交动作失败:{e.detail}")
break
identity.reset(tok)
_update_step(sid, action_run_id=ar["id"])
decided = _action_outcome(step, sid, ar)
if decided is None:
_update_step(sid, status="waiting_approval", note=ar["preview"].get("summary", ""))
_set_run(run_id, status="waiting", vars=env)
break
if t == "foreach":
src = _render(step.get("items") or "", env)
rows = _rows_of(src)[: int(step.get("limit") or 20)]
sid = _new_step(run_id, step, {"rows": len(rows)})
results, ok = _foreach(run, step, sid, rows, env, mode)
verb = "已提交审批" if mode == "live" else "预览通过"
note = f"共 {len(rows)} 行,{verb} {ok} 条" + (f",{len(rows) - ok} 条失败" if ok < len(rows) else "")
out = {"total": len(rows), "ok": ok, "items": results}
if mode == "ai_readonly" and rows:
_update_step(sid, status="suggested", output=out, note=f"建议逐行发起动作:{note}")
_finish(run_id, "paused", outcome=f"建议逐行发起动作:{note}")
break
_update_step(sid, status="done", output=out, note=note)
if step.get("output"):
env[step["output"]] = out
nxt, how, out = decided
if not nxt:
_update_step(sid, status="failed", output=out, note=how, error=ar.get("error", ""))
_set_run(run_id, vars=env)
_finish(run_id, "rejected" if ar["status"] in ("rejected", "cancelled") else "failed",
error=how)
break
_update_step(sid, status="done", output=out, note=f"{how}:{ar['preview'].get('summary', '')}")
if step.get("output"):
env[step["output"]] = out
_set_run(run_id, vars=env)
cur = nxt
continue
if t == "foreach":
src = _render(step.get("items") or "", env)
try:
rows = _pick_rows(step, src, env)
except HTTPException as e:
sid = _new_step(run_id, step)
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=str(e.detail))
break
sid = _new_step(run_id, step, {"rows": len(rows)})
results, ok = _foreach(run, step, sid, rows, env, mode)
verb = "已提交审批" if mode == "live" else "预览通过"
note = f"共 {len(rows)} 行,{verb} {ok} 条" + (f",{len(rows) - ok} 条失败" if ok < len(rows) else "")
out = {"total": len(rows), "ok": ok, "items": results}
if mode == "ai_readonly" and rows:
_update_step(sid, status="suggested", output=out, note=f"建议逐行发起动作:{note}")
_finish(run_id, "paused", outcome=f"建议逐行发起动作:{note}")
break
_update_step(sid, status="done", output=out, note=note)
if step.get("output"):
env[step["output"]] = out
_set_run(run_id, vars=env)
cur = step["next"]
continue
if t == "subprocess":
params = _render(step.get("params") or {}, env)
sid = _new_step(run_id, step, params)
try:
child = start(step["sop"], params, mode=mode, trigger=f"subprocess:{run_id}",
parent_step_run=sid, wait=True)
except HTTPException as e:
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=f"子流程启动失败:{e.detail}")
break
_update_step(sid, child_run_id=child["id"])
if child["status"] == "done":
_update_step(sid, status="done", output=child["vars"], note=child["outcome"])
if step.get("output"):
env[step["output"]] = child["vars"]
cur = step["next"]
continue
if t == "subprocess":
params = _render(step.get("params") or {}, env)
sid = _new_step(run_id, step, params)
try:
child = start(step["sop"], params, mode=mode, trigger=f"subprocess:{run_id}",
parent_step_run=sid, wait=True)
except HTTPException as e:
_update_step(sid, status="failed", error=str(e.detail))
_finish(run_id, "failed", error=f"子流程启动失败:{e.detail}")
break
_update_step(sid, child_run_id=child["id"])
if child["status"] == "done":
_update_step(sid, status="done", output=child["vars"], note=child["outcome"])
if step.get("output"):
env[step["output"]] = child["vars"]
cur = step["next"]
continue
if child["status"] in ("failed", "cancelled", "rejected"):
_update_step(sid, status="failed", error=child["error"])
_finish(run_id, "failed", error=f"子流程失败:{child['error']}")
break
_update_step(sid, status="waiting_child")
_set_run(run_id, status="waiting", vars=env)
if child["status"] in ("failed", "cancelled", "rejected"):
_update_step(sid, status="failed", error=child["error"])
_finish(run_id, "failed", error=f"子流程失败:{child['error']}")
break
_finish(run_id, "failed", error=f"未知步骤类型 {t}")
_update_step(sid, status="waiting_child")
_set_run(run_id, status="waiting", vars=env)
break
else:
_finish(run_id, "failed", error="步骤数超过上限")
_finish(run_id, "failed", error=f"未知步骤类型 {t}")
break
else:
_finish(run_id, "failed", error="步骤数超过上限")
return get_run(run_id)
......@@ -580,21 +647,16 @@ def _on_action(ar: dict) -> None:
sr, run, step = found
if sr["status"] != "waiting_approval" or run["status"] != "waiting":
return
out = {"status": ar["status"], "action_run_id": ar["id"], "result": ar.get("result")}
if ar["status"] == "done":
_resume(run["id"], sr["id"], step["next"], out, step.get("output", ""), note="动作已批准并执行")
elif ar["status"] in ("rejected", "cancelled"):
if step.get("on_reject"):
_resume(run["id"], sr["id"], step["on_reject"], out, step.get("output", ""),
status="done", note="动作被驳回,走驳回分支")
else:
_update_step(sr["id"], status="failed", output=out, note="动作被驳回")
_set_run(run["id"], status="running")
_finish(run["id"], "rejected", error=f"动作被驳回:{(ar.get('approvals') or [{}])[0].get('comment', '')}")
elif ar["status"] == "failed":
_update_step(sr["id"], status="failed", output=out, error=ar.get("error", ""))
_set_run(run["id"], status="running")
_finish(run["id"], "failed", error=f"动作执行失败:{ar.get('error')}")
decided = _action_outcome(step, sr["id"], ar)
if decided is None:
return
nxt, how, out = decided
if nxt:
_resume(run["id"], sr["id"], nxt, out, step.get("output", ""), note=how)
return
_update_step(sr["id"], status="failed", output=out, note=how, error=ar.get("error", ""))
_set_run(run["id"], status="running")
_finish(run["id"], "rejected" if ar["status"] in ("rejected", "cancelled") else "failed", error=how)
def _child_finished(child: dict) -> None:
......@@ -659,7 +721,12 @@ def try_step(def_id: str, step_id: str, env: dict | None = None) -> dict:
step = next((s for s in spec.get("steps") or [] if s["id"] == step_id), None)
if step is None:
raise HTTPException(404, f"步骤「{step_id}」不存在")
env = dict(env or {})
with ksvc.draft_runtime():
return _try_step(def_id, step, dict(env or {}))
def _try_step(def_id: str, step: dict, env: dict) -> dict:
step_id = step["id"]
t = step["type"]
started = time.time()
......@@ -684,8 +751,7 @@ def try_step(def_id: str, step_id: str, env: dict | None = None) -> dict:
return done({"branch": -1, "next": step.get("default")}, "走默认分支")
if t in ("action", "foreach"):
if t == "foreach":
rows = _rows_of(env.get(str(step.get("items") or "").lstrip("$")))
rows = rows[: int(step.get("limit") or 10)]
rows = _pick_rows(step, env.get(str(step.get("items") or "").lstrip("$")), env, 10)
out = []
for i, row in enumerate(rows, 1):
env_i = {**env, "item": row, "index": i}
......
......@@ -18,7 +18,7 @@ def sop_find(args: dict, emit: Emit | None) -> dict:
@function("sop.playbook", "按流程诊断", "以只读方式跑一遍已发布 SOP 的取数/分析/判断部分(遇到人工或动作就停),"
"返回每一步的结果与建议的下一步。适合「为什么/怎么处理」这类需要按标准流程排查的问题。",
{"type": "object", "properties": {
"sop": {"type": "string", "description": "SOP 名称或 id"},
"sop": {"type": "string", "description": "流程卡", "x-ref": "sop", "x-primary": True},
"params": {"type": "object", "description": "流程参数"}},
"required": ["sop"]}, category="process")
def sop_playbook(args: dict, emit: Emit | None) -> dict:
......
"""把流程卡包装成「可提交审批的发起提案」。
提问里 AI 说「该走某张流程卡」时,不能直接把流程跑起来 —— 跟动作一个规矩:先带着依据进人工
审批队列,批准了才真正启动,之后的每一步(人工任务、动作)由流程卡自己往下推。
实现办法是给流程卡造一个**合成动作**:参数就是流程卡的参数,唯一的效果是 `sop.start` 工具。
这样预览、四眼原则、优先级、审计、通知全部复用动作那一套,不必再造一条审批链路。
动作引用写作 `sop:<流程卡 id>`(也认标题)。
"""
from __future__ import annotations
from fastapi import HTTPException
from . import service
from . import spec as sop_spec
PREFIX = "sop:"
# 流程卡的参数类型 → 动作的参数类型。对象、周期在卡片上都是填一个主键 / 期号,按字符串收。
_PARAM_TYPE = {"number": "number", "boolean": "boolean", "text": "text"}
_PRIORITY_RISK = {"P0": "high", "P1": "high", "P2": "medium", "P3": "low"}
def find_published(ref: str) -> dict | None:
"""按 id / 标题找一张已发布的流程卡。AI 报的标题常常差几个字,所以精确匹配不上时再按包含找,
只有唯一命中才算数 —— 宁可让人自己挑,也不能发起错的流程。"""
ref = (ref or "").strip()
if ref.startswith(PREFIX):
ref = ref[len(PREFIX):].strip()
if not ref:
return None
pool = service.list_defs(status="published")
hit = next((d for d in pool if ref in (d["id"], d["title"])), None)
if hit is None:
loose = [d for d in pool if ref in d["title"] or d["title"] in ref]
if len(loose) != 1:
return None
hit = loose[0]
return service.get(hit["id"])
def require_published(ref: str) -> dict:
d = find_published(ref)
if d is None:
raise HTTPException(404, f"没有已发布的流程卡「{ref}」")
return d
def outline(d: dict) -> list[dict]:
"""给人看的步骤概要:审批人要知道「批了之后会发生什么」。"""
return [{"id": st["id"], "title": st["title"], "type": st["type"],
"type_label": sop_spec.STEP_TYPES.get(st["type"], st["type"]), "lane": st.get("lane", "")}
for st in d["spec"].get("steps") or [] if st["type"] != "end"]
def as_action(ref: str) -> dict:
"""流程卡 → 合成动作定义(喂给 capability.actions 的 _prepare / propose)。"""
d = require_published(ref)
spec = d["spec"]
params = [{"name": p["name"], "label": p.get("label") or p["name"],
"type": _PARAM_TYPE.get(p.get("type") or "", "string"),
"required": bool(p.get("required", True)), "enum": [],
"description": f"流程卡参数({p.get('type')})"}
for p in spec.get("params") or []]
return {"id": f"{PREFIX}{d['id']}", "name": d["title"],
"display_name": f"发起流程卡「{d['title']}」", "version": d["current_version"],
"risk_level": _PRIORITY_RISK.get(spec.get("priority") or "P2", "medium"),
"status": "published",
"spec": {"target_type": "", "params": params, "criteria": [],
"effects": [{"tool": "sop.start", "label": f"启动流程卡「{d['title']}」",
"args": {"sop": d["id"],
"params": {p["name"]: f"${p['name']}" for p in params}}}],
# 发起一条流程的影响面比单个动作大,一律人工审批;负责人角色就是审批角色
"approval": {"mode": "manual",
"approver_roles": [d["owner_role"]] if d["owner_role"] else []},
"reversible": False}}
"""场景配方:选几样本体里已有的东西,直接生成一张能跑的流程卡。
以前新建流程卡只给一个空画布(外加一个没用的「本体概览」步骤),用户得自己知道
取数要调哪个函数、参数怎么填、判断条件怎么写、逐行处理的变量叫什么 —— 这正是「像 demo」的根源。
配方把最常见的三种业务闭环固化下来,生成的是确定性的步骤(指标取数、决策表),不经过大模型。
生成后仍是普通草稿,可以在画布里继续改。
"""
from __future__ import annotations
from typing import Any
from fastapi import HTTPException
from ..capability import defs, refs
RECIPES: list[dict] = [
{"id": "metric_patrol", "title": "指标巡检 → 逐行发起动作",
"desc": "按维度取一个指标,结果里的每一行各发起一次动作。例:库存缺口按仓库×商品拆开,每条缺口提一张补货单。",
"fields": [
{"name": "metric", "label": "巡检哪个指标", "ref": "metric", "required": True},
{"name": "dimensions", "label": "按什么拆分(每一行对应一个组合)", "ref": "dimension:metric", "multi": True},
{"name": "action", "label": "每一行发起什么动作", "ref": "action", "required": True},
{"name": "limit", "label": "一次最多处理几行", "type": "number", "default": 20},
]},
{"id": "object_review", "title": "对象复核 → 人工确认 → 动作",
"desc": "选一个对象,先查它的现状,派给某个角色确认,确认后发起动作;驳回就结束。例:供应商风险复核。",
"fields": [
{"name": "object_type", "label": "复核哪类对象", "ref": "object_type", "required": True},
{"name": "role", "label": "谁来确认", "ref": "role", "required": True},
{"name": "action", "label": "确认后发起什么动作", "ref": "action", "required": True},
]},
{"id": "metric_decision", "title": "指标 → 决策表分级 → 分支处理",
"desc": "取一个指标的值,交给决策表分级;需要处理时派人工任务,否则直接结束。例:缺货率分级预警。",
"fields": [
{"name": "metric", "label": "看哪个指标", "ref": "metric", "required": True},
{"name": "decision", "label": "用哪张决策表分级", "ref": "decision", "required": True},
{"name": "role", "label": "需要处理时派给谁", "ref": "role", "required": True},
]},
]
def list_recipes() -> list[dict]:
return RECIPES
def _need(fields: dict, name: str, label: str) -> Any:
v = fields.get(name)
if v in (None, "", []):
raise HTTPException(422, f"请选择「{label}」")
return v
def _action(ref: str) -> dict:
"""按正在编辑的版本生成(刚改的参数也要能映射上);正式运行前发布即可。"""
c = refs.lookup(ref, "action")
if c is None:
raise HTTPException(404, f"动作「{ref}」不存在")
return defs._from_concept(c, c.get("status") == "published")
def _map_params(action: dict, columns: list[str], var: str) -> dict:
"""动作参数 ← 结果行的列:同名(或中文名相同)的列直接对上,数字参数兜底用 value 列。"""
out: dict[str, str] = {}
low = {c.lower(): c for c in columns}
for p in action["spec"].get("params") or []:
label = str(p.get("label") or "").lower()
hit = low.get(p["name"].lower()) or low.get(label) or next(
(c for lc, c in low.items() if lc != "value" and label and (lc in label or label in lc)), None)
if hit:
out[p["name"]] = f"${var}.{hit}"
elif p["type"] in ("number", "integer") and "value" in columns:
out[p["name"]] = f"${var}.value"
return out
def build(recipe_id: str, fields: dict) -> dict:
"""返回 {title, description, spec}。"""
fields = dict(fields or {})
if recipe_id == "metric_patrol":
metric = _need(fields, "metric", "巡检哪个指标")
dims = [d for d in fields.get("dimensions") or [] if d]
act = _action(_need(fields, "action", "每一行发起什么动作"))
cols = dims + ["value"]
okey = refs.object_column(act["spec"].get("target_type") or "", dims)
return {"title": f"{metric}巡检 · {act['display_name'] or act['name']}",
"description": f"按{'、'.join(dims) or '整体'}取「{metric}」,每一行发起「{act['display_name'] or act['name']}」",
"spec": {"params": [], "start": "fetch", "steps": [
{"id": "fetch", "type": "function", "title": f"取{metric}", "function": "metric.query",
"args": {"metric": metric, **({"dimensions": dims} if dims else {})},
"output": "data", "next": "check", "lane": "系统"},
{"id": "check", "type": "decision", "title": "有没有要处理的行",
"branches": [{"when": "len(data.rows) > 0", "next": "each", "label": "有"}],
"default": "none"},
{"id": "each", "type": "foreach", "title": f"逐行{act['display_name'] or act['name']}",
"items": "$data", "action": act["name"], "params": _map_params(act, cols, "item"),
"object_key": f"$item.{okey}" if okey else "", "when": "value > 0",
"limit": int(fields.get("limit") or 20), "output": "handled", "next": "done"},
{"id": "done", "type": "end", "title": "已发起", "outcome": "已按每一行发起动作"},
{"id": "none", "type": "end", "title": "无需处理", "outcome": f"「{metric}」没有需要处理的行"},
]}}
if recipe_id == "object_review":
ot = _need(fields, "object_type", "复核哪类对象")
role = _need(fields, "role", "谁来确认")
act = _action(_need(fields, "action", "确认后发起什么动作"))
params = {p["name"]: "" for p in act["spec"].get("params") or [] if p.get("required")}
return {"title": f"{ot}复核",
"description": f"查看{ot}现状 → {role}确认 → 发起「{act['display_name'] or act['name']}」",
"spec": {"params": [{"name": "target", "label": ot, "type": "object", "object_type": ot,
"required": True}],
"start": "look", "steps": [
{"id": "look", "type": "function", "title": f"查看{ot}", "function": "object.get",
"args": {"object_type": ot, "key": "$target.key"}, "output": "obj", "next": "confirm",
"lane": "系统"},
{"id": "confirm", "type": "human_task", "title": "人工确认", "role": role,
"instructions": f"请核对{ot}「$target.label」的情况,确认是否需要处理。",
"form": [{"name": "ok", "label": "需要处理", "type": "boolean", "required": True},
{"name": "note", "label": "说明", "type": "text", "required": False}],
"output": "review", "next": "gate"},
{"id": "gate", "type": "decision", "title": "确认结果",
"branches": [{"when": "review.ok == True or review.ok == 'true'", "next": "act",
"label": "需要处理"}], "default": "skip"},
{"id": "act", "type": "action", "title": act["display_name"] or act["name"],
"action": act["name"], "params": params, "object_key": "$target.key",
"next": "done", "on_reject": "skip"},
{"id": "done", "type": "end", "title": "已处理", "outcome": "已发起处理"},
{"id": "skip", "type": "end", "title": "不处理", "outcome": "确认无需处理"},
]}}
if recipe_id == "metric_decision":
metric = _need(fields, "metric", "看哪个指标")
table = _need(fields, "decision", "用哪张决策表分级")
role = _need(fields, "role", "需要处理时派给谁")
inputs = refs.function_inputs(table, "decision")
first = inputs[0]["value"] if inputs else "value"
return {"title": f"{metric}分级处理",
"description": f"取「{metric}」→ 按决策表「{table}」分级 → 需要处理时派给{role}",
"spec": {"params": [], "start": "fetch", "steps": [
{"id": "fetch", "type": "function", "title": f"取{metric}", "function": "metric.query",
"args": {"metric": metric}, "output": "m", "next": "grade", "lane": "系统"},
{"id": "grade", "type": "function", "title": f"按{table}分级", "function": "decision.eval",
"args": {"table": table, "inputs": {first: "$m.value"}}, "output": "level",
"next": "gate", "lane": "系统"},
{"id": "gate", "type": "decision", "title": "要不要处理",
"branches": [{"when": "level.matched", "next": "handle", "label": "命中分级"}],
"default": "ok"},
{"id": "handle", "type": "human_task", "title": "处理", "role": role,
"instructions": f"「{metric}」当前为 $m.value,分级结果 $level.result,请处理。",
"form": [{"name": "measure", "label": "处理措施", "type": "text", "required": True}],
"output": "handled", "next": "done"},
{"id": "done", "type": "end", "title": "已处理", "outcome": "已派人处理"},
{"id": "ok", "type": "end", "title": "正常", "outcome": f"「{metric}」正常"},
]}}
raise HTTPException(404, f"没有这个场景:{recipe_id}")
......@@ -42,8 +42,7 @@ def _dict(d: SopDefinition, full: bool = True) -> dict:
"created_at": iso(d.created_at), "updated_at": iso(d.updated_at),
"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")}
"priority": spec.get("priority") or "P2", "domain": spec.get("domain") or ""}
dr = out["last_dry_run"]
out["dry_run_ok"] = bool(dr.get("ok") and dr.get("hash") == d.draft_hash)
if full:
......@@ -88,9 +87,10 @@ def get(def_id: str) -> dict:
def create(title: str, description: str = "", spec: dict | None = None,
process_concept_id: str = "", owner_role: str = "", ai_generated: bool = False) -> dict:
actor = identity.current()
# 空白流程卡从「取数」开始:选一个指标就能试跑(以前默认是一个对业务没用的「本体概览」)
norm = sop_spec.normalize(spec or {"steps": [
{"id": "start", "type": "function", "title": "第一步", "function": "ontology.overview",
"next": "end"},
{"id": "fetch", "type": "function", "title": "取数", "function": "metric.query", "args": {},
"output": "data", "next": "end"},
{"id": "end", "type": "end", "title": "结束"}]})
with session() as s:
d = SopDefinition(id=new_id("sop"), workspace=actor.workspace,
......@@ -195,6 +195,10 @@ def submit_publish(def_id: str, note: str = "") -> dict:
raise HTTPException(422, "草稿还有错误:" + ";".join(d["validation"]["errors"][:5]))
if not d["dry_run_ok"]:
raise HTTPException(412, "请先对当前草稿做一次试运行,并确保试运行走到结束")
if d["validation"].get("draft_refs"):
names = "、".join(f"「{x['name']}」" for x in d["validation"]["draft_refs"][:8])
raise HTTPException(412, f"流程卡引用了还没发布的积木 {names},正式运行时会找不到它们。"
"请先到「发布」页把本体发布出去,再提交流程卡")
item = review.propose("sop_publish", f"发布 SOP「{d['title']}」第 {d['current_version'] + 1} 版", {
"def_id": def_id, "hash": d["draft_hash"], "note": note,
"warnings": d["validation"]["warnings"], "dry_run": d["last_dry_run"]},
......
......@@ -88,6 +88,7 @@ def normalize(spec: dict | None) -> dict:
limit = 20
step.update(items=str(st.get("items") or ""), action=str(st.get("action") or ""),
params=st.get("params") or {}, object_key=str(st.get("object_key") or ""),
when=str(st.get("when") or ""),
limit=max(1, min(FOREACH_LIMIT, limit)))
elif t == "subprocess":
step.update(sop=str(st.get("sop") or ""), params=st.get("params") or {})
......@@ -143,6 +144,7 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
"""返回 {errors, warnings}。check_refs 时还核对函数/技能/动作/角色/子流程是否存在;
def_id 是这张流程卡自己的编号,用来拦住「子流程调用自己」。"""
from ..capability import defs, registry
from ..capability.refs import pending as refs_pending
from ..kernel import service
errors: list[str] = []
warnings: list[str] = []
......@@ -150,6 +152,12 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
# 以前只有一串字符串,前端靠「在文案里找步骤标题」来定位 —— 标题重名或为空就挂错、挂丢,
# 成环、缺开始步骤这类全局错误更是永远挂不上去。errors 保留,兼容老调用方。
issues: list[dict] = []
# 引用了还没发布的积木:试运行可以(读工作副本),正式运行 / 发布前要先发布本体
draft_refs: list[dict] = []
def draft(sid: str, kind: str, name: str) -> None:
if not any(d["name"] == name and d["kind"] == kind for d in draft_refs):
draft_refs.append({"step_id": sid, "kind": kind, "name": name})
def err(msg: str, sid: str = "") -> None:
errors.append(msg)
......@@ -161,7 +169,7 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
steps = spec.get("steps") or []
if not steps:
return {"errors": ["流程还没有任何步骤"], "warnings": [],
return {"errors": ["流程还没有任何步骤"], "warnings": [], "draft_refs": [],
"issues": [{"level": "error", "step_id": "", "message": "流程还没有任何步骤"}]}
by_id: dict[str, dict] = {}
for st in steps:
......@@ -180,7 +188,7 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
err(f"参数名不合法:{p['name']}")
if spec.get("start") not in by_id:
err("开始步骤不存在")
return {"errors": errors, "warnings": warnings, "issues": issues}
return {"errors": errors, "warnings": warnings, "issues": issues, "draft_refs": draft_refs}
# 引用与出口
for st in steps:
......@@ -204,12 +212,31 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
f = st.get("function")
if f not in registry.FUNCTIONS:
err(f"步骤「{st['title']}」调用的函数「{f}」不存在(SOP 只能调用已注册的只读函数)", st["id"])
else:
fs = registry.FUNCTIONS[f].input_schema
props = fs.get("properties") or {}
for req in fs.get("required") or []:
if (st.get("args") or {}).get(req) in (None, "", [], {}):
label = str((props.get(req) or {}).get("description") or req).split("(")[0].split(",")[0]
err(f"步骤「{st['title']}」还没填「{label}」", st["id"])
if check_refs:
from ..capability import refs
for r in refs.scan_refs(fs, st.get("args") or {}):
if r["status"] == "missing":
err(f"步骤「{st['title']}」引用的「{r['name']}」在本体里找不到", st["id"])
else:
draft(st["id"], r["ref"].split(":")[0], r["name"])
if t == "human_task" and not st.get("role"):
err(f"人工任务「{st['title']}」没有指定执行角色", st["id"])
if t in ("action", "foreach") and not st.get("action"):
err(f"步骤「{st['title']}」没有选择动作", st["id"])
if t == "foreach" and not _refs(st.get("items")):
err(f"逐行处理「{st['title']}」没有指定按哪份数据逐行处理(例如 $缺货清单)", st["id"])
if t == "foreach" and st.get("when"):
try:
rules.parse(st["when"])
except rules.RuleError as e:
err(f"逐行处理「{st['title']}」的筛选条件「{st['when']}」有误:{e}", st["id"])
if t == "subprocess":
if not st.get("sop"):
err(f"子流程「{st['title']}」没有选择要调用的流程卡", st["id"])
......@@ -222,8 +249,8 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
sk = defs.find(st["skill"], "skill")
if sk is None:
err(f"AI 分析函数「{st['skill']}」不存在", st["id"])
elif sk["status"] != "published":
warn(f"AI 分析函数「{st['skill']}」尚未发布,正式运行前需要发布本体", st["id"])
elif refs_pending(st["skill"], "function", "ai"):
draft(st["id"], "ai", st["skill"])
if t == "subprocess" and st.get("sop"):
from . import service as sop_service
try:
......@@ -234,12 +261,15 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
if sub["status"] == "archived":
err(f"子流程「{st['title']}」调用的流程卡「{sub['title']}」已归档,"
"先恢复它或改调别的流程卡", st["id"])
for p in (sub.get("spec") or {}).get("params") or []:
if p.get("required") and p.get("default") in (None, "") and (st.get("params") or {}).get(p["name"]) in (None, ""):
err(f"子流程「{st['title']}」没给「{sub['title']}」的必填参数「{p['label']}」", st["id"])
if t in ("action", "foreach") and st.get("action"):
ac = defs.find(st["action"], "action")
if ac is None:
err(f"动作「{st['action']}」不存在", st["id"])
elif ac["status"] != "published":
warn(f"动作「{st['action']}」尚未发布,正式运行前需要发布本体", st["id"])
elif refs_pending(st["action"], "action"):
draft(st["id"], "action", st["action"])
if t == "human_task" and st.get("role"):
from ..governance import roles
if not roles.exists(st["role"]) and st["role"] not in (
......@@ -271,7 +301,7 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
if not any(by_id[n]["type"] == "end" for n in seen):
err("流程没有可达的「结束」步骤")
if any(e.startswith("流程有环") for e in errors):
return {"errors": errors, "warnings": warnings, "issues": issues}
return {"errors": errors, "warnings": warnings, "issues": issues, "draft_refs": draft_refs}
# 变量先定义后使用:在所有路径上都一定已定义才算
topo = list(reversed(order))
......@@ -308,4 +338,7 @@ def validate(spec: dict, *, check_refs: bool = True, def_id: str = "") -> dict:
if st.get("output"):
dout.add(st["output"])
defined_out[n] = dout
return {"errors": errors, "warnings": warnings, "issues": issues}
if draft_refs:
names = "、".join(f"「{d['name']}」" for d in draft_refs[:6])
warn(f"引用了还没发布的积木 {names}:试运行可用,正式运行和发布流程卡前要先发布本体")
return {"errors": errors, "warnings": warnings, "issues": issues, "draft_refs": draft_refs}
"""指标条件扫描。
「什么时候跑」已经整体搬到 `app/watch/` —— 一张流程卡只能配一个触发器、没有管理界面、
没有下次执行时间、失败只写日志、多进程还会重复触发,这些问题在那边一并解决了。
这里只留下 `metric_scan`,给流程卡编辑页的「试扫描」按钮用;调度线程已经删掉。
"""
from __future__ import annotations
import logging
from fastapi import HTTPException
from sqlalchemy import select
from ..core.dbx import session
from ..kernel import metrics, rules
from . import engine, service
from .models import SopRun
log = logging.getLogger(__name__)
def metric_scan(def_id: str, *, dry: bool = False) -> dict:
"""按指标触发器扫描一次。dry=True 只返回会命中哪些对象,不启动。"""
d = service.get(def_id)
_, _, spec = service.version_spec(def_id)
trig = spec.get("trigger") or {}
if trig.get("kind") != "metric":
raise HTTPException(422, "这个 SOP 不是指标触发的")
mt = trig["metric"]
dims = [mt["dimension"]] if mt.get("dimension") else []
res = metrics.query(mt["metric"], dimensions=dims, time=mt.get("time") or "",
question=f"[触发器] {d['title']}")
period = (res.get("period") or {}).get("period", "")
hits, started = [], []
for row in res["rows"]:
key = row[0] if dims else ""
value = row[-1]
try:
ok = rules.evaluate(mt["condition"], {"value": value, "key": key})
except rules.RuleError as e:
raise HTTPException(422, f"触发条件有误:{e}") from e
if not ok:
continue
hits.append({"key": key, "value": value})
if dry:
continue
tag = f"metric:{period}:{key}"
with session() as s:
exists = s.scalars(select(SopRun.id).where(SopRun.def_id == def_id,
SopRun.trigger == tag)).first()
if exists:
continue
params = {mt["object_param"]: key} if mt.get("object_param") and key != "" else {}
try:
run = engine.start(def_id, params, trigger=tag)
started.append(run["id"])
except HTTPException as e:
log.warning("触发器启动 SOP 失败 %s %s:%s", def_id, key, e.detail)
return {"period": period, "hits": hits, "started": started, "rows": len(res["rows"])}
......@@ -111,10 +111,16 @@ def execute(ds_id: int, sql: str, dialect: str = "mysql") -> ExecOutcome:
return ExecOutcome(False, g, None,
";".join(i.msg for i in g.errors), "guard")
# 数据范围:受限对象的表换成带范围条件的子查询(对指标路和自由 SQL 路一视同仁)
from ..kernel import grounding
try:
final_sql = grounding.scope_sql(ds_id, g.sql, dialect)
except ValueError as e:
return ExecOutcome(False, g, None, str(e), "guard")
row_limit, timeout_ms = limits()
try:
conn = semantic.connector_for(ds_id)
result = conn.run_sql(g.sql, row_limit=row_limit, timeout_ms=timeout_ms)
result = conn.run_sql(final_sql, row_limit=row_limit, timeout_ms=timeout_ms)
except ConnectionFailed as e:
return ExecOutcome(False, g, None, str(e), "connect")
except QueryFailed as e:
......
......@@ -64,7 +64,8 @@ def run_ask(ds_id: int, question: str, history: list[dict] | None = None,
yield _done(thread_id, "failed", started)
return
schema = semantic.render_schema(ctx["models"], ctx["relations"], ctx["metrics"])
schema = semantic.render_schema(ctx["models"], ctx["relations"], ctx["metrics"],
semantic.ontology_overlay(ds_id))
yield {"type": "retrieve", **ctx["hits"],
"schema_tokens": llm.count_tokens(schema), "flags": ctx["flags"]}
......
......@@ -335,12 +335,26 @@ def guard_context(ds_id: int) -> tuple[set[str], dict[str, set[str]], set[str]]:
for b in ordered[i + 1:]:
if a.split(".")[0] != b.split(".")[0]:
joins.add(join_key(a, b))
# 本体里定义过的关系(关系类型的 join 绑定)也是合法的关联路径
for j in ontology_overlay(ds_id).get("joins") or []:
joins.add(join_key(j["from"], j["to"]))
return tables, columns, joins
# ---------------- 渲染给提示词 ----------------
def ontology_overlay(ds_id: int) -> dict:
"""本体对这个数据源的注解(表是哪个对象、列是哪个属性、本体关系给出的关联路径)。
本体没发布或元数据库异常时返回空 —— 问数照样能跑,只是少了业务语言的提示。"""
try:
from ..kernel import grounding
return grounding.sql_overlay(ds_id)
except Exception: # noqa: BLE001
log.debug("读取本体注解失败", exc_info=True)
return {"tables": {}, "joins": []}
def render_schema(models: list[dict], relations: list[dict] | None = None,
metrics: list[dict] | None = None) -> str:
metrics: list[dict] | None = None, overlay: dict | None = None) -> str:
"""把语义模型渲染成带注释的伪 DDL。
刻意不用 JSON:同样的信息,DDL 文本大概省一半 token,而且模型对 DDL 的先验强得多。
......@@ -348,14 +362,18 @@ def render_schema(models: list[dict], relations: list[dict] | None = None,
才知道过滤条件该怎么写。这是 WrenAI 最大的准确率漏洞,别重蹈。
"""
blocks: list[str] = []
otables = (overlay or {}).get("tables") or {}
for m in models:
table = m["physical_table"] or m["name"]
onto = otables.get(table.lower()) or {}
head = f"CREATE TABLE {table} ("
lines: list[str] = []
for c in m.get("columns", []):
col = c["physical_column"] or c["name"]
dtype = c["data_type"] or "varchar"
notes: list[str] = []
if (onto.get("cols") or {}).get(col.lower()):
notes.append(onto["cols"][col.lower()])
if c.get("description"):
notes.append(c["description"])
if c.get("synonyms"):
......@@ -375,11 +393,20 @@ def render_schema(models: list[dict], relations: list[dict] | None = None,
lines.append(f" PRIMARY KEY ({m['primary_key']})")
body = "\n".join(lines).rstrip(",")
tail = ");"
desc = f" -- 表说明:{m['description']}" if m.get("description") else ""
desc_parts = ([f"本体对象:{onto['concept']}"] if onto.get("concept") else []) + \
([f"表说明:{m['description']}"] if m.get("description") else [])
desc = f" -- {';'.join(desc_parts)}" if desc_parts else ""
blocks.append(f"{head}{desc}\n{body}\n{tail}")
out = "\n\n".join(blocks)
present = {(m["physical_table"] or m["name"]).lower() for m in models}
onto_joins = [j for j in (overlay or {}).get("joins") or []
if j["from"].split(".")[0] in present and j["to"].split(".")[0] in present]
if onto_joins:
out += ("\n\n-- 本体里定义的对象关系(可直接用作关联路径):\n"
+ "\n".join(f"- {j['name']}:JOIN ON {j['from']} = {j['to']}" for j in onto_joins))
if relations:
by_id = {m["id"]: (m["physical_table"] or m["name"]) for m in models}
rel_lines = []
......
......@@ -8,6 +8,7 @@ from __future__ import annotations
import datetime as dt
import logging
import os
from typing import Any
from fastapi import HTTPException
......@@ -88,7 +89,7 @@ def _fire(w: dict, row: dict, run_id: str) -> list[dict]:
"text": "启动流程卡「" + target["title"] + "」"})
elif kind == "propose_action":
params = {k: actions.render(v, row) for k, v in (st.get("params") or {}).items()}
okey = str(actions.render(st.get("object_key") or "$key", row) or "")
okey = str(actions.render(st.get("object_key") or _default_object_key(w, st), row) or "")
ar = actions.propose(
st["action"], params, object_key=okey,
reason=st.get("reason") or ("监控「" + w["title"] + "」命中"),
......@@ -113,11 +114,33 @@ def _fire(w: dict, row: dict, run_id: str) -> list[dict]:
return fired
def _default_object_key(w: dict, st: dict) -> str:
"""没指定对象主键时:指标按维度拆开的行,key 是各维度值拼起来的(如「W01-SKU9」),
不是任何一个对象的主键;按动作作用的对象类型挑出对应的那一列。"""
src = w["source"]
dims = [d for d in src.get("dimensions") or [] if d] if src.get("kind") == "metric" else []
if dims:
from ..capability import defs, refs
a = defs.find(st.get("action") or "", "action") or {}
col = refs.object_column((a.get("spec") or {}).get("target_type") or "", dims)
if col:
return "$" + col
return "$key"
# ---------------------------------------------------------------- 扫一次
def scan(wid: str, *, dry: bool = False, trigger: str = "manual", force: bool = False) -> dict:
"""扫描一次。dry=True 只告诉你现在会命中哪些行,不触发任何策略、不写抑制状态。
"""扫描一次。dry=True 只告诉你现在会命中哪些行,不触发任何策略、不写抑制状态;
试扫描读工作副本,草稿里的指标也能先看效果。
force=True 忽略冷却抑制 —— 人工排查时常常就是要「不管冷却,现在给我再跑一遍」。"""
if dry:
with ksvc.draft_runtime():
return _scan(wid, dry=True, trigger=trigger, force=force)
return _scan(wid, dry=False, trigger=trigger, force=force)
def _scan(wid: str, *, dry: bool, trigger: str, force: bool) -> dict:
w = _load(wid)
started = dt.datetime.now()
run_id = new_id("wr")
......@@ -260,9 +283,12 @@ def due(at: dt.datetime | None = None) -> list[tuple[str, str]]:
at = at or dt.datetime.now()
out: list[tuple[str, str]] = []
with session() as s:
rows = s.scalars(select(Watch).where(Watch.enabled == 1,
Watch.next_fire_at.isnot(None),
Watch.next_fire_at <= at)).all()
stmt = select(Watch).where(Watch.enabled == 1, Watch.next_fire_at.isnot(None),
Watch.next_fire_at <= at)
# 同一个元数据库上并行跑多个实例(各自 ONTO_WORKSPACE)时,只领自己工作区的,互不抢跑
if os.environ.get("ONTO_WORKSPACE", "").strip():
stmt = stmt.where(Watch.workspace == identity.DEFAULT_WORKSPACE)
rows = s.scalars(stmt).all()
for w in rows:
sched = jload(w.schedule_json, {}) or {}
planned = w.next_fire_at
......@@ -291,12 +317,16 @@ def tick(at: dt.datetime | None = None) -> list[str]:
tok = identity.set_current(identity.Actor(id="system", name="系统 · 监控", kind="system",
roles=["admin"], workspace=ws))
try:
scan(wid, trigger="schedule")
r = scan(wid, trigger="schedule")
fired.append(wid)
# 只有真的命中 / 触发了才进动态:以前每分钟一条「定时触发 1 个监控」,把工作台动态刷满了
done = len([f for f in r["fired"] if f.get("ok")])
if r["hit_count"] or done:
audit.record("watch.scan", "watch", wid,
f"监控「{r['watch']}」定时扫描 {r['scanned']} 行,命中 {r['hit_count']},"
f"执行 {done} 项" + (f",冷却中跳过 {r['suppressed']}" if r["suppressed"] else ""))
except Exception: # noqa: BLE001
log.exception("监控执行失败 watch=%s", wid)
finally:
identity.reset(tok)
if fired:
audit.record("watch.tick", "watch", "", "定时触发 " + str(len(fired)) + " 个监控")
return fired
......@@ -273,3 +273,15 @@ def migrate_sop_triggers() -> int:
if moved:
log.info("已把 %d 个流程卡触发器迁移成监控器", moved)
return moved
def usage_provider(concept_id: str, names: list[str]) -> list[dict]:
"""「被谁引用」:盯着这个指标 / 对象、或命中后发起这个动作的监控器。
废弃或改名一块积木前,要让人知道有监控依赖它(以前监控不在引用分析里,改了也没提示)。"""
out = []
with session() as s:
for w in s.scalars(select(Watch).where(Watch.workspace == _ws())).all():
text = (w.source_json or "") + (w.strategies_json or "")
if concept_id in text or any(n and f'"{n}"' in text for n in names):
out.append({"type": "watch", "id": w.id, "name": w.title, "kind": "watch"})
return out
# 本体引擎 v8:可用性诊断与改造报告
> 2026-09-28 · 分支 `ontology_dev_merge_8103` · 运行实例 **http://127.0.0.1:8101**(工作区 `default`)
> 启动:`./.venv/Scripts/python.exe scripts/serve_8101.py`(前端产物 `web/dist_8101`,`cd web && npm run build:8101`)
## 一句话结论
系统的「零件」大多是真的(取数引擎、流程引擎、审批、审计都能跑),不好用的根源是**零件之间没接上**:
1. **草稿永远跑不起来,而发布又几乎发不出去**:运行时只认已发布的积木,发布要「另一个人」审批,
单人(包括超级管理员)没法自己发布 → `default` 工作区 23 块积木全停在草稿 → 提问拿不到指标、监控下拉为空、流程卡试运行 404。
2. **该选的地方全是空白框**:流程卡「取数」步骤里要手填指标名(就是你说的「查数方法名」空白框),规则名、对象类型、维度、角色、动作效果参数、监控参数都要手填或写 JSON。
3. **动作被写死为人工审批**:没有「自动执行」这条路,编辑器还会把审批决策表悄悄抹掉。
4. **提问只用上了本体的一小半**:指标路用得好,但对象、属性中文名、关系从不进提示词,自由 SQL 路完全绕开本体(还绕开了数据范围权限)。
v8 把这几处都接上了,并在 8101 上用 `default` 工作区从「发布 → 建流程 → 试运行 → 正式运行 → 动作自动执行 → 提问」走通了一遍(见第 4 节)。
---
## 1. 诊断(按你的反馈逐条对照)
### 1.1 「很多都跑不了」——草稿/发布死结
| 现象 | 根因(代码位置) |
|---|---|
| 提问里用不上刚建的指标 | 运行时 `kernel/service.py` `rt_*` 只读已发布版本 |
| 流程卡试运行报「找不到已发布的指标」 | 试运行也只读已发布;而试运行不通过又不能发布流程卡 → 死结 |
| 流程卡选了草稿动作,试运行必失败 | `capability/actions.py` `_load_action` 拒绝未发布动作 |
| 管理员也发布不了 | `can_decide_release` 不许审批自己提交的提案,且**没有管理员例外**(动作审批有),开关藏在系统设置 |
| `default` 工作区 | 23 块积木(5 对象 / 6 关系 / 9 函数 / 3 动作)**从未发布过** |
### 1.2 「查数方法名的空白框不知道填什么」——配置靠手填
- 流程卡「函数」步骤的下拉只列 13 个**系统内置函数**,不是你建的指标 / 规则。选了「指标取数」后,参数 `metric` 是个文本框 —— 你得自己记住指标的准确名字。
- 同类问题:`rule.eval` 的规则名、`decision.eval` 的决策表名、`object.*` 的对象类型、维度(要手写 JSON 数组)、过滤条件(JSON 对象)、时间(`current/last/YYYY-MM` 这种内部写法);动作效果里的对象 / 属性 / 端点 / 角色;监控「提议动作」的参数是一个**受控 JSON 输入框 —— 打一个字就被还原,根本输不进去**。
- 下拉为空的三类原因:① 积木没发布;② 依赖项没建(没有业务角色、没有外部端点);③ id / 名称对不上(业务建模存名称、编辑器存 id → 对象页永远看不到 AI 建的动作按钮,动作编辑器显示「不作用于具体对象」)。
### 1.3 「action 层不会自己执行」
- `defs.validate_action` 强制 `approval.mode = manual`;`actions.propose` 一律写 `pending_approval`;菜单文案也写着「执行前一律人工审批」。
- 编辑器里点一下审批角色,会用 `{mode, approver_roles}` **整个覆盖** approval —— v7 配的审批决策表就这样被抹掉。
- AI 从文档抽出来的动作、手动「新建」的动作模板,效果都只是「发一条站内通知」—— 批了也等于什么都没做。
- 执行失败不能重试;进程中途退出的动作永远停在「执行中」。
### 1.4 「SOP 像 demo」
- 新建流程卡的默认第一步是「本体概览」(对业务毫无用处)。
- 子流程没有参数输入框 → 试运行能过(不校验参数),正式运行 422。
- 点变量插入的是 `$x`,但判断条件不认 `$` → 语法错误。
- 看不到上一步输出里有哪些字段(`.value` 还是 `.rows`?)。
- 提问里点「运行这个流程」会跳到流程卡,但 AI 建议的参数在跳转时丢了。
- 逐行处理没法筛行:缺口为 0 的行也逐个去发动作,结果一半是「前置条件不满足」。
- 模板里一张预置流程卡都没有。
### 1.5 「从建模到 SOP 到应用没有连起来」
- 监控每分钟往工作台「最近动态」写一条「定时触发 1 个监控」,真正有用的动态被刷没了。
- 监控不在「被谁引用」里:删 / 改一个指标,不会提示有监控依赖它。
- 同一个元数据库上跑着 8099 / 8107 / 8101 多个实例,**旧实例的调度器会领所有工作区的监控**。
- 工作区下拉里 `default` 和 `xianda_inv` 都叫「默认本体」,分不清。
### 1.6 「提问真的用上本体了吗?」——用了一半
| 本体里的东西 | 提问里用上了吗(v8 之前) |
|---|---|
| 指标(有取数绑定的) | ✅ 指标路确定性编译 SQL,口径、周期、数据范围都用上 |
| 规则 / 决策表 | ✅ 可以被 `execute_function` 调用 |
| 动作 | ✅ 行动 Agent 生成审批卡 |
| **对象类型、属性中文名、关系** | ❌ 只有问句里恰好点到名字时,给一句 80 字描述;从不进提示词 |
| **自由 SQL 路** | ❌ 走另一套 `sm_*` 表结构说明,不用本体的表映射、属性中文名、关系 join;**不做数据范围过滤(安全漏洞)** |
| 时间 | ⚠️ 只认月粒度;「上周」会被当成「上个月」 |
| 轨迹展示 | ⚠️ 只显示「问句匹配到的」概念,不是「实际用到的」;SQL 路口径显示为空 |
### 1.7 `default` 工作区本身的数据质量(AI 起草的半成品)
走查中发现,这批积木多数「看起来完整、实际跑不了」:
- 4 个指标**全部没绑定取数表达式**(取不了数);6 个关系都没绑定 join。
- 「库存缺口」的口径字段填的是公式文本而不是规则名;统计周期「日」不存在;「补货数量计算」规则没有表达式。
- 「审批规则」决策表的输入声明为数字,条件里却写字符串和布尔值。
- 「仓库」对象绑在数据源 5 上,而本工作区只能看到数据源 6 → 仓库名称查不到。
**建议**:加一个「积木体检」页(见第 5 节),把这些问题在发布前一次性列出来。
---
## 2. 本次改了什么
### 2.1 引用选择器:不再对着空白框猜名字
- 内置函数 / 效果的参数加 `x-ref`(`app/capability/builtins.py`),新增 `app/capability/refs.py` 统一提供选项(含草稿,标「草稿」)和 `GET /api/cap/ref-options`。
- 前端新组件 `web/src/features/ontology/RefSelect.tsx`:分组下拉(已发布 / 草稿 / 流程变量 / 自定义…)、多选、时间选择(本期 / 上周 / 近 30 天 / 指定月 / 起止日期)、键值编辑器(过滤条件、决策表输入、对象属性值)。选项为空时直接给出「去建一个 →」。
- `SchemaForm` 遇到 `x-ref` 自动用选择器 → **流程卡、动作效果、监控、MCP 在线调用一起受益**;普通输入框也能下拉选变量。
- 流程卡「取什么数」下拉顶部直接列「我的指标 / 我的规则 / 我的决策表 / 我的统计周期」,选「库存缺口」即等于「指标取数 · metric=库存缺口」。
- id / 名称统一比较(`refs.same_ref`):对象页的动作按钮、对象 360 指标、动作编辑器的「作用于对象」、列表筛选全部修好。
### 2.2 草稿可试、发布可达、超级管理员全能审批
- 试运行 / 单步试跑 / 监控试扫描 / 动作预览读**工作副本**(`kernel/service.draft_runtime`,带单次缓存);正式运行仍只认已发布。
- 流程卡校验返回 `draft_refs`:引用了未发布或「发布后又改过」的积木时顶部横幅提示 +「去发布本体」按钮;提交发布时直接拦下并列出清单。
- 新增 `app/governance/permissions.py`,全系统唯一的「谁能批」判定:**超级管理员什么都能批**(动作、变更提案、流程卡发布、审核项、人工任务),包括自己提交的,审计里注明「管理员审批(豁免四眼原则)」;AI / 外部 Agent 永远不能批;其他人照旧守四眼原则。
- 发布页给管理员加了「立即发布」(提交 + 批准一步完成)。
- 编辑必填参数没填、名字在本体里找不到、子流程必填参数没给 —— 编辑时就标红,不再等运行时报错。
### 2.3 动作审批策略:动作能自己执行了
- 每个动作可选 **人工审批 / 自动执行 / 条件自动**(`defs.APPROVAL_MODES`)。条件自动:写 `qty <= 200`、`priority == 'P3'`、`eff.amount < 5000` 这类条件,或让审批决策表输出 `auto` 列。
- 满足条件的提议当场执行,审批单记为「自动执行」并写审计;**AI 提议的动作一律仍走人工审批**。
- 流程卡里的动作步骤如果自动执行完了,流程直接往下走(不再卡在「等审批」)。
- 失败可「重试」(跳过已成功的效果);服务重启时把卡在「执行中」的动作标成失败(可重试)。
- 编辑器新的「审批与执行」卡片:模式、条件、审批角色(标出不存在的角色)、审批决策表 + 输入映射;修复抹掉决策表的 bug。
- 空壳动作(AI 抽取 / 新建模板)的默认效果从「发通知」改为「派一项待办」。
### 2.4 流程卡
- 新增 **「从场景新建」**(`app/sop/recipes.py`):指标巡检 → 逐行发起动作 / 对象复核 → 人工确认 → 动作 / 指标 → 决策表分级 → 分支处理。选几样东西直接生成确定性流程(不经过大模型),参数和对象列自动对上。
- 逐行处理新增「只处理满足条件的行」(如 `value > 0`)。
- 新建空白流程从「取数」开始;子流程有参数表单;判断条件插变量自动去 `$`;变量列表展示每个变量的可用字段(`.value` / `.rows` / 表单字段 / `$item.列名`)。
- 从提问跳转带参数,自动打开预填好的运行框。
- 模板 `templates/store_ops.yaml` 带上一张预置流程卡「门店重点跟进复核」。
- 删除失效代码:`app/sop/triggers.py`、trigger-scan 接口、列表里恒为「手动」的触发方式标签。
### 2.5 监控
- 参数不再是手写 JSON:按动作 / 流程卡的参数生成表单,可直接选命中行的字段(`$key`、`$value`、各维度);对象主键不填就按动作的对象类型自动从维度里挑。
- 指标、维度、角色都是选择器。
- 定时扫描只在真的命中 / 执行时写一条汇总动态,不再每分钟刷屏。
- 设了 `ONTO_WORKSPACE` 的实例只领自己工作区的监控;监控进入「被谁引用」。
### 2.6 提问真正用上本体
- `app/kernel/grounding.py`:
- `digest()` 本体结构摘要(对象 + 属性中文名 + 关系)进主 Agent 与子 Agent 的提示词;
- `sql_overlay()` 给自由 SQL 的表结构加注「本体对象:库存 / 本体属性:库存.on_hand(在库数量)」,本体关系并入允许的关联路径;
- `scope_sql()` **自由 SQL 路也按数据范围改写**(受限表换成带条件的子查询),修掉越权漏洞;
- `used_concepts()` → 推理轨迹新增「本次用到的本体」。
- 时间:认得 今天 / 昨天 / 本周 / 上周 / 近 N 周 / 本季度 / 上季度 / 今年;时点指标(库存、缺口)问到时间时仍走指标路并说明「按当前值」,不再降级去自己写 SQL 算错口径。
- 维度本身是对象时,结果自动补「名称」列(不再全是 W02 / P013)。
- 问数 Agent 也能查概念定义;SQL 路口径统一成 `{name, text}`,界面不再显示空口径;审批卡提交时带上取数依据。
### 2.7 其它
- 工作区下拉同名时显示编号和积木数:「默认本体(default)· 26 块积木」。
- 审批与待办:来源多了「监控」徽标、自动执行的记录单独标注、失败的动作有「重试」按钮、审批历史里的按钮与后端权限一致(不再点了 403)。
---
## 3. 验证
- 后端:`pytest tests/` **323 个全部通过**;新增 `tests/test_v8.py`(27 个用例,覆盖上面每一项)。
- 前端:`tsc -b` 通过,`vitest` 11 个通过,`npm run build:8101` 成功。
## 4. 8101 上的真人走查(`default` 工作区)
| 步骤 | 结果 |
|---|---|
| 实施工程师提交变更提案,管理员在「发布」页通过 | v1 发布 23 块积木 |
| 给「库存缺口」绑定取数表达式(按仓库、商品拆分);把「创建补货采购单」从空壳改成:作用于商品、参数「补货数量 / 收货仓库」、效果「派单给采购员」、**条件自动 `qty <= 200`** | 编辑器新卡片正常;维度立刻出现在下拉里 |
| 流程卡「从场景新建」→ 指标巡检:库存缺口 × 仓库、商品 → 创建补货采购单 | 自动生成 5 步流程,参数自动映射 `qty ← $item.value`、`warehouse_id ← $item.仓库`、对象 `← $item.商品`;横幅提示引用了 2 个未发布修改 |
| 试运行 | 通过:60 行里筛出 6 行真有缺口,6 条预览全部通过 |
| 管理员「立即发布」 | v2 一步发布(无需切换身份) |
| 流程卡提交发布、管理员批准、正式运行 | 完成;**6 张补货单全部自动执行**(数量 25~130 都 ≤ 200),采购员收到 6 条待办,审批依据里写着「满足自动执行条件:qty <= 200」 |
| 提问「上周哪些仓库哪些商品缺货最严重?」 | 走指标路(口径正确),答案带商品名称,并说明「时点数,按当前值回答」;轨迹显示「本次用到的本体:库存缺口 · 取数」 |
## 5. 还没做 / 建议下一步(按优先级)
1. **积木体检页**:发布前一次性列出「指标没绑定、口径字段填的不是规则、周期不存在、规则没表达式、决策表类型不一致、对象绑在不可见的数据源上」这类问题,每条带「去修」。1.7 节列的问题都能被它抓到。
2. **一键补全绑定**:AI 起草时顺手给指标 / 关系生成取数绑定草稿(现在只给对象绑表)。
3. **多表指标**:指标现在只能单表(`FROM base_table`),「采购金额 = 数量 × 单价」这类要跨表的算不了。
4. **周 / 日粒度统计周期**:周期函数目前只有「月」一种形态。
5. **sm_* 语义层与本体合一**:v8 用「注解」把本体叠到自由 SQL 上,长期应让表结构说明直接来自本体。
6. **旧实例调度**:8099 / 8107 运行的是旧代码,仍会领所有工作区的监控;建议停掉不用的实例,或也设上 `ONTO_WORKSPACE`。
7. **动作写回业务库**:`object.write / object.create` 默认只写本系统的写回层,数据源要勾「写回业务库」才真正改业务表;建议在动作编辑器里直接显示这个开关的状态。
8. **对象页 360 补全**:列出对象相关的规则 / 决策表结果、盯着它的监控、引用它的流程卡。
## 6. 推荐的上手路径(给业务同事)
1. **数据连接**:接一个库,在「表结构」里启用要用的表。
2. **业务建模**:上传业务手册,AI 起草对象 / 关系 / 指标 / 规则 / 动作。
3. **补绑定**:对象绑表、指标绑取数表达式(维度在这里配)、关系绑 join。
4. **发布**:管理员直接「立即发布」;团队协作时由另一位实施工程师审批。
5. **流程卡 → 从场景新建**:选指标、维度、动作 → 试运行 → 提交发布 → 运行。
6. **动作 → 审批与执行**:低风险的设「自动执行」或「条件自动」。
7. **监控与定时**:把流程卡或「命中就发起动作」挂到定时上。
8. **提问**:直接问业务问题,看轨迹里「本次用到的本体」核对依据。
This diff could not be displayed because it is too large.
{
"blue_moon_turns": [
{
"id": "tn_4b20fd03abad4df182c0",
"question": "蓝月亮我想补货10单,你帮我创建个补货单吧",
"answer": "蓝月亮(蓝月亮洗衣液3kg)在**W03仓库**存在缺货风险(可用库存**50件**,低于安全库存**100件**),已按您指定的**10件**数量在W03仓库生成补货采购单。\n\n#### 依据\n- 创建补货采购单的输入参数为:商品、仓库、数量 [^d10:c2]\n- 安全库存口径:每个「仓库×商品」单独设定的最低保有量 [^d10:c1]\n- 补货规则:可用库存<安全库存时必须发起补货 [^d10:c1]\n\n#### 数据与分析\n蓝月亮洗衣液3kg(商品编号P001)各仓库库存情况:\n\n| 仓库 | 在库数量 | 在途数量 | 安全库存 | 可用库存 | 是否缺货 |\n|------|---------|---------|---------|---------|---------|\n| W01 | 172 | 0 | 100 | 172 | 否 |\n| W02 | 131 | 0 | 80 | 131 | 否 |\n| W03 | 50 | 0 | 100 | 50 | **是**(缺口50件) |\n\n- W03仓库**唯一**缺货 [^run:737]\n- 按系统规则(缺口50件、补货批量未知)应补货50件,但您已指定10件,按您的要求执行\n- 补货后W03可用库存将变为60件,仍低于安全库存,建议后续关注是否需要再次补货\n\n#### 建议下一步\n已自动发起创建补货采购单流程,并在下方生成审批卡。请您核对以下参数:\n- **商品**:蓝月亮洗衣液3kg\n- **仓库**:W03\n- **数量**:10件\n- **审批路径**:采购员自行确认(数量小、金额预计低于5万元,且供应商状态正常)\n\n确认无误后点击「**提交审批**」,审批通过后系统将自动生成采购单并增加在途数量。",
"actions_json": "[]"
},
{
"id": "tn_3897416a7313484c8216",
"question": "蓝月亮我想补货10单,你帮我创建个补货单吧",
"answer": "蓝月亮洗衣液3kg当前在W03仓库**可用库存50件**,低于安全库存100件,缺口50件。补货10件可以缓解缺口,符合补货场景,我已为您生成补货采购单草稿,请核对。\n\n#### 依据\n- **判断标准**:当商品可用库存低于安全库存时,视为存在缺货风险,需要发起补货 。\n- **库存数据**:蓝月亮洗衣液3kg在W03仓库的可用库存为50件,安全库存为100件,在途为0件 [^run:740]。\n\n#### 数据与分析\n各仓库库存情况:\n\n| 仓库 | 可用库存 | 安全库存 | 在途 | 是否缺货 |\n|------|----------|----------|------|----------|\n| W01 | 172 | 100 | 0 | 否 |\n| W02 | 131 | 80 | 0 | 否 |\n| W03 | 50 | 100 | 0 | **是(缺口50件)** |\n\n- 仅W03仓库缺货,其他仓库库存充足。\n\n#### 建议下一步\n补货采购单已生成,请您核对以下参数:\n- **商品**:蓝月亮洗衣液3kg\n- **补货数量**:10件\n- **目标仓库**:W03\n- **供应商**:(请补充)\n- **备注**:目前仅补货10件,W03仓库仍有40件缺口,如需一次补足可修改数量。\n\n> 请点「提交审批」启动单据,审批通过后由采购员自行确认(金额<5万且无延期供应商时)即执行。",
"actions_json": "[]"
}
]
}
\ No newline at end of file
This diff could not be displayed because it is too large.
import sys
import os
import json
sys.path.append('d:/code/onto_query')
from dotenv import load_dotenv
load_dotenv('d:/code/onto_query/.env')
from sqlalchemy import create_engine, text
def default_serializer(obj):
return str(obj)
try:
engine = create_engine(f'mysql+pymysql://{os.getenv("DB_USER")}:{os.getenv("DB_PASSWORD")}@{os.getenv("DB_HOST")}:{os.getenv("DB_PORT")}/{os.getenv("DB_NAME")}?charset=utf8mb4')
out = {}
with engine.connect() as conn:
res = conn.execute(text("SELECT id, question, answer, actions_json FROM onto_turn ORDER BY id DESC LIMIT 50"))
turns = [dict(r._mapping) for r in res]
blue_moon_turns = [t for t in turns if '蓝月亮' in str(t['question']) or '蓝月亮' in str(t['answer'])]
out['blue_moon_turns'] = blue_moon_turns
with open('results_blue_moon.json', 'w', encoding='utf-8') as f:
json.dump(out, f, ensure_ascii=False, indent=2, default=default_serializer)
except Exception as e:
print(e)
"""把「创建补货采购单流程」做成一条能一口气走完的演示闭环,并清干净演示数据。
./.venv/Scripts/python.exe scripts/seed_replenish_demo.py
跑完之后的链路(default 工作区):
提问「哪些商品缺货?有的话发起创建补货采购单流程」
→ 知识 Agent 查口径 + 问数 Agent 查缺口(并行)
→ 行动 Agent 出一张「发起流程卡」的审批卡 ← 第 1 道人工审批
→ 人批准 → 流程卡启动
1. 核对库存缺口(按本体口径确定性取数)
2. 创建补货采购单(动作):数量 ≥ 1000 要采购经理审批 ← 第 2 道人工审批
批准 / 自动执行后,往 otlgt3_dm_purchase_order 插一行
3. 结束
这个脚本会重置演示数据(撤回未决审批、取消挂起的流程与待办、删掉测试采购单),
可以反复跑。它只动 default 工作区和 otlgt3_dm_* 演示表。
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
os.chdir(ROOT)
sys.path.insert(0, str(ROOT))
os.environ.setdefault("ONTO_WORKSPACE", "default")
from app.core import identity # noqa: E402
from app.governance import users # noqa: E402
identity.set_current(users.load_actor("admin", "default"))
import app.main # noqa: E402,F401 注册函数/工具/表
from app.capability import actions, tasks # noqa: E402
from app.kernel import service as ksvc # noqa: E402
from app.sop import engine, service as sop_service # noqa: E402
from app.text2sql import semantic # noqa: E402
from app.watch import service as watch_service # noqa: E402
ACTION = "创建补货采购单"
SOP_TITLE = "创建补货采购单流程"
# 演示要能同时走到两条分支:一个仓库×商品的缺口 ≥ 1000(走审批),其余的都小(自动执行)
BIG_GAP = {"warehouse_id": "W02", "product_id": "P013", "safety_stock": 1300}
def log(msg: str) -> None:
print(msg, flush=True)
# ---------------------------------------------------------------- 1. 清演示痕迹
def reset_runtime() -> None:
for w in watch_service.list_watches():
if w["enabled"] and "测试" in w["title"]:
watch_service.set_enabled(w["id"], False)
log(f" 停用监控器「{w['title']}」(每分钟跑一次,一直在刷待办)")
for r in engine.list_runs(status="running,waiting", limit=500):
try:
engine.cancel(r["id"], "重置演示数据")
except Exception as e: # noqa: BLE001
log(f" 取消流程运行 {r['id']} 失败:{e}")
log(f" 取消挂起的流程运行")
for t in tasks.list_tasks(scope="all", status="open"):
try:
tasks.cancel(t["id"], "重置演示数据")
except Exception as e: # noqa: BLE001
log(f" 取消待办 {t['id']} 失败:{e}")
log(" 取消未完成的待办")
for r in actions.list_runs(status="pending_approval", limit=500):
try:
actions.cancel(r["id"], "重置演示数据")
except Exception as e: # noqa: BLE001
log(f" 撤回审批单 {r['id']} 失败:{e}")
log(" 撤回未决的审批单")
def reset_memory_cases() -> None:
"""废弃自动沉淀的补货类案例。
案例库会把「以前是怎么答的」当参考喂给主 Agent。流程卡和动作刚刚改过,旧案例里的
分派路径和结论(「已自动生成补货采购单,无需审批」之类)现在是错的,留着只会带偏这一轮。
人工点过「有用」的(verified)不动。"""
from sqlalchemy import select
from app.core.dbx import session
from app.memory.models import MemCase
words = ("补货", "缺货", "采购", "流程卡", "sop", "SOP")
n = 0
with session() as s:
for c in s.scalars(select(MemCase).where(MemCase.workspace == "default",
MemCase.status == "draft")).all():
if any(w in f"{c.question}{c.answer_summary}" for w in words):
c.status = "deprecated"
n += 1
s.commit()
log(f" 废弃 {n} 条已经过时的补货类问答案例(人工确认过的不动)")
def reset_business_data() -> None:
"""演示表回到种子状态:删掉测试跑出来的采购单,并把一条库存的安全库存调高,
让「缺口 ≥ 1000 要审批」这条分支在真实数据上就能走到。"""
from sqlalchemy import text
ds = next((d for d in semantic.list_datasources() if d["db_name"]), None)
if ds is None:
raise SystemExit("没有配置业务数据源")
eng = semantic.connector_for(ds["id"]).engine
with eng.begin() as c:
# 种子单号是 PO2026xxxx(10 位),跑出来的是 PO+时间戳(16 位)
n = c.execute(text("SELECT COUNT(*) FROM otlgt3_dm_purchase_order "
"WHERE CHAR_LENGTH(po_no) > 12")).scalar()
c.execute(text("DELETE FROM otlgt3_dm_purchase_order WHERE CHAR_LENGTH(po_no) > 12"))
log(f" 删掉 {n} 张测试跑出来的采购单,只留 25 张种子单")
c.execute(text("UPDATE otlgt3_dm_stock SET safety_stock = :s "
"WHERE warehouse_id = :w AND product_id = :p"),
{"s": BIG_GAP["safety_stock"], "w": BIG_GAP["warehouse_id"],
"p": BIG_GAP["product_id"]})
log(f" {BIG_GAP['warehouse_id']}×{BIG_GAP['product_id']} 安全库存设为 "
f"{BIG_GAP['safety_stock']}(缺口过千,用来演示审批分支)")
# ---------------------------------------------------------------- 2. 动作:真往业务库写
ACTION_SPEC = {
"target_type": "商品", # rebuild_action 会换成对象类型的 id
"params": [
{"name": "qty", "label": "采购数量", "type": "number", "required": True, "enum": [],
"description": "本次采购件数。≥ 1000 要采购经理审批,小于 1000 直接执行"},
{"name": "warehouse_id", "label": "收货仓库", "type": "string", "required": True, "enum": [],
"description": "仓库编号,如 W01"},
{"name": "reason", "label": "采购原因", "type": "text", "required": False, "enum": [],
"description": "写给审批人看的依据"},
],
"criteria": [{"expression": "qty > 0", "message": "采购数量要大于 0"}],
"effects": [{
"tool": "object.create", "label": "写入采购单",
"args": {"object_type": "采购单", "values": {
"po_no": "PO$now_id", "product_id": "$obj_key", "warehouse_id": "$warehouse_id",
"supplier_id": "$obj.supplier_id", "qty": "$qty", "amount": "=qty * obj.unit_price",
"status": "已下单", "order_date": "$today"}}}],
# 这一条就是「大于等于 1000 要审批、小于 1000 直接执行」:条件不成立时自动转人工
"approval": {"mode": "conditional", "approver_roles": ["采购经理"], "auto_when": "qty < 1000"},
"reversible": True,
}
def rebuild_action() -> str:
c = ksvc.find(ACTION, "action")
if c is None:
raise SystemExit(f"本体里没有动作「{ACTION}」")
product = ksvc.find("商品", "object_type")
if product is None:
raise SystemExit("本体里没有对象类型「商品」")
spec = {**ACTION_SPEC, "target_type": product["id"]}
ksvc.update_concept(
c["id"], display_name=ACTION,
description="往业务库的采购单表插入一张补货采购单(供应商和金额按商品本体带出)。"
"采购数量 ≥ 1000 件要采购经理审批,小于 1000 件直接执行。",
spec=spec)
log(f" 动作「{ACTION}」:效果改成 object.create → otlgt3_dm_purchase_order,"
f"审批条件 qty < 1000 自动执行")
return c["id"]
def repair_bindings() -> None:
"""演示库里「仓库」的表绑定指向了一个已经删掉的数据源,查仓库对象会直接报错。
先把绑定补到还在的数据源上,再把指向死数据源的那条删掉 —— 留着它,取哪一条就看运气了。"""
ok_ds = {d["id"] for d in semantic.list_datasources()}
target = next(iter(sorted(ok_ds)), None)
if target is None:
return
for c in ksvc.list_concepts(kind="object_type"):
stale = [b for b in ksvc.list_bindings(c["id"]) if b["ds_id"] not in ok_ds]
for b in stale:
if not any(x["ds_id"] in ok_ds and x["target_kind"] == b["target_kind"]
for x in ksvc.list_bindings(c["id"])):
ksvc.set_binding(c["id"], target, b["target_kind"], b["ref"])
ksvc.delete_binding(b["id"])
log(f" 修复「{c['name']}」的表绑定:数据源 {b['ds_id']} 已不存在,改到 {target}")
# ---------------------------------------------------------------- 3. 流程卡:三步走完
SOP_SPEC = {
"priority": "P2",
"domain": "库存补货",
"params": [
{"name": "product_id", "label": "商品编号", "type": "string", "required": True, "default": ""},
{"name": "warehouse_id", "label": "收货仓库", "type": "string", "required": True, "default": ""},
{"name": "qty", "label": "采购数量", "type": "number", "required": True, "default": None},
],
"roles": ["采购员", "采购经理"],
"trigger": {"kind": "manual"},
"start": "check_gap",
"steps": [
{"id": "check_gap", "type": "function", "title": "核对库存缺口", "lane": "采购员",
"description": "按本体里「库存缺口」的口径,确认这个商品在这个仓库确实缺货",
"function": "metric.query",
"args": {"metric": "库存缺口", "filters": {"商品": "$product_id", "仓库": "$warehouse_id"}},
"output": "gap", "next": "create_po"},
{"id": "create_po", "type": "action", "title": "创建补货采购单", "lane": "采购员",
"description": "写入采购单。数量 ≥ 1000 件的要采购经理审批,批准后才写;小于 1000 件直接写",
"action": ACTION, "object_key": "$product_id",
"params": {"qty": "$qty", "warehouse_id": "$warehouse_id",
"reason": "补货流程创建:$product_id 在 $warehouse_id 的库存缺口 $gap.value 件"},
"output": "po", "next": "end"},
{"id": "end", "type": "end", "title": "结束", "lane": "采购员",
"outcome": "补货采购单已写入业务库"},
],
"layout": {"check_gap": {"x": 0, "y": 0}, "create_po": {"x": 0, "y": 150},
"end": {"x": 0, "y": 300}},
}
SOP_DESC = ("给一个商品在一个仓库建一张补货采购单:先按本体口径核对库存缺口,再写入采购单。"
"采购数量 ≥ 1000 件要采购经理审批,小于 1000 件直接执行。")
def tidy_other_sops(keep_id: str) -> None:
"""演示时流程库里只留这一张已发布的卡,免得行动 Agent 在几张相似的卡之间挑错。"""
for d in sop_service.list_defs(status="published"):
if d["id"] == keep_id:
continue
try:
sop_service.archive(d["id"])
log(f" 归档流程卡「{d['title']}」(演示期间只留一张)")
except Exception as e: # noqa: BLE001
log(f" 归档「{d['title']}」失败:{e}")
def rebuild_sop() -> str:
from app.sop import spec as sop_spec
d = next((x for x in sop_service.list_defs() if x["title"] == SOP_TITLE), None)
if d is not None and d["status"] == "published":
try:
_, ver, published = sop_service.version_spec(d["id"])
if published == sop_spec.normalize(SOP_SPEC):
log(f" 流程卡「{SOP_TITLE}」已经是这一版(v{ver}),不用重新发布")
return d["id"]
except Exception: # noqa: BLE001
pass
if d is None:
d = sop_service.create(SOP_TITLE, SOP_DESC, SOP_SPEC, owner_role="采购经理")
log(f" 新建流程卡「{SOP_TITLE}」")
else:
sop_service.update(d["id"], title=SOP_TITLE, description=SOP_DESC, spec=SOP_SPEC,
owner_role="采购经理")
log(f" 流程卡「{SOP_TITLE}」:{d['step_count']} 步 → 3 步")
did = d["id"]
cur = sop_service.get(did)
if cur["validation"]["errors"]:
raise SystemExit("流程卡校验不过:" + ";".join(cur["validation"]["errors"]))
for w in cur["validation"]["warnings"]:
log(f" ⚠ {w}")
run = engine.start(did, {"product_id": BIG_GAP["product_id"],
"warehouse_id": BIG_GAP["warehouse_id"], "qty": 1400},
mode="dry_run", trigger="dry_run", wait=True)
sop_service.record_dry_run(did, run, cur["draft_hash"])
if run["status"] != "done":
raise SystemExit(f"试运行没走到结束:{run['status']} {run.get('error')}")
log(f" 试运行通过:{'→'.join(s['title'] for s in engine.get_run(run['id'])['steps'])}")
item = sop_service.submit_publish(did, "简化为三步:核对缺口 → 创建采购单 → 结束")
from app.governance import review
review.decide(item["id"], True, "演示环境直接发布")
log(f" 已发布 v{sop_service.get(did)['current_version']}")
return did
# ---------------------------------------------------------------- main
if __name__ == "__main__":
log("① 清演示痕迹")
reset_runtime()
reset_memory_cases()
log("② 重置业务数据")
reset_business_data()
log("③ 重建动作")
rebuild_action()
repair_bindings()
log("④ 发布本体")
try:
pub = ksvc.publish("补货演示:采购单动作改为写入业务库")
log(f" 本体已发布,修订号 {pub['revision']}")
except Exception as e: # noqa: BLE001
log(f" 本体没有需要发布的变更({e})")
log("⑤ 重建流程卡")
sid = rebuild_sop()
tidy_other_sops(sid)
log("完成。现在可以在「提问」里问:查一下我们商品有哪些东西是缺少库存的,"
"如果有就发起一个「创建补货采购单流程」")
"""启动 8101 实例(v8 可用性改造版),用 default 工作区的本体,与 8099 / 8107 并行、互不干扰。
- 工作区 ONTO_WORKSPACE=default(元数据库共享,本体、动作、流程卡、监控按工作区隔离);
- 前端产物 web/dist_8101(`cd web && npm run build:8101`);
- 设了 ONTO_WORKSPACE 后,本实例的监控调度只领 default 工作区的监控器。
./.venv/Scripts/python.exe scripts/serve_8101.py
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
os.chdir(ROOT)
sys.path.insert(0, str(ROOT))
os.environ.setdefault("ONTO_WORKSPACE", "default")
os.environ.setdefault("WEB_DIST", "dist_8101")
if __name__ == "__main__":
import uvicorn
uvicorn.run("app.main:app", host="0.0.0.0", port=int(os.environ.get("PORT", "8101")))
"""启动 8102 实例。
python scripts/serve_8102.py
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
os.chdir(ROOT)
sys.path.insert(0, str(ROOT))
os.environ.setdefault("ONTO_WORKSPACE", "default")
os.environ.setdefault("WEB_DIST", "dist")
if __name__ == "__main__":
import uvicorn
uvicorn.run("app.main:app", host="0.0.0.0", port=int(os.environ.get("PORT", "8102")))
......@@ -172,3 +172,35 @@ concepts:
form: [{name: measures, label: 整改措施, type: text, required: true}]}}
approval: {mode: manual, approver_roles: [区域运营]}
reversible: true
# ---------- 流程卡(导入后是草稿,发布本体后即可试运行、发布) ----------
sops:
- title: 门店重点跟进复核
description: 查看门店现状 → 飞行督导确认 → 标记重点跟进并派整改任务;确认不需要就结束
owner_role: 区域运营
spec:
params:
- {name: target, label: 门店, type: object, object_type: 门店, required: true}
start: look
steps:
- {id: look, type: function, title: 查看门店, function: object.get, lane: 系统,
args: {object_type: 门店, key: "$target.key"}, output: obj, next: confirm}
- id: confirm
type: human_task
title: 督导确认
role: 飞行督导
instructions: "请核对门店「$target.label」的达标与整改情况,确认是否需要重点跟进。"
form:
- {name: ok, label: 需要重点跟进, type: boolean, required: true}
- {name: reason, label: 跟进原因, type: text, required: true}
output: review
next: gate
- id: gate
type: decision
title: 确认结果
branches: [{when: "review.ok == True or review.ok == 'true'", next: act, label: 需要跟进}]
default: skip
- {id: act, type: action, title: 标记重点跟进, action: mark_follow_up,
params: {reason: "$review.reason"}, object_key: "$target.key", next: done, on_reject: skip}
- {id: done, type: end, title: 已跟进, outcome: 已标记重点跟进并派发整改任务}
- {id: skip, type: end, title: 不跟进, outcome: 确认无需重点跟进}
"""v8:配完就能跑 —— 引用选择器、草稿可试运行、动作审批策略(自动 / 条件自动)、
流程卡场景配方、监控不刷屏、提问真正用上本体(结构摘要、SQL 注解、数据范围、周粒度时间)。"""
from __future__ import annotations
import datetime as dt
import sys
from pathlib import Path
import pytest
from fastapi import HTTPException
sys.path.insert(0, str(Path(__file__).parent))
from test_platform import as_user, build_basics, env, make_action # noqa: E402,F401
from app.core import identity # noqa: E402
def _auto_action(ot_id: str, mode: str = "auto", auto_when: str = "", publish: bool = True) -> dict:
from app.kernel import service
appr = {"mode": mode, "approver_roles": []}
if auto_when:
appr["auto_when"] = auto_when
a = service.create_concept("action", "dispatch_check", display_name="派人复核", spec={
"target_type": ot_id,
"params": [{"name": "reason", "label": "原因", "type": "text", "required": True},
{"name": "qty", "label": "数量", "type": "number", "required": False}],
"effects": [{"tool": "task.create", "args": {"title": "复核:$obj.label", "description": "$reason",
"role": "operator"}}],
"approval": appr})
if publish:
service.publish("动作")
return a
# ---------------------------------------------------------------- 引用选择器
def test_内置函数参数带引用类型_前端据此渲染下拉(env):
from app.capability import registry
mq = registry.FUNCTIONS["metric.query"]
props = mq.input_schema["properties"]
assert props["metric"]["x-ref"] == "metric"
assert props["dimensions"]["x-ref"] == "dimension:metric"
assert mq.brief()["binds"] == {"param": "metric", "ref": "metric"}
assert registry.TOOLS["object.write"].input_schema["properties"]["property"]["x-ref"] == "property:object_type"
def test_引用选项包含草稿并标出来_维度来自指标绑定(env):
from app.capability import refs
from app.kernel import service
b = build_basics(env["ds_id"])
service.create_concept("function", "草稿指标", spec={"category": "aggregate"})
opts = {o["value"]: o for o in refs.options("metric")}
assert opts["成交金额"]["status"] == "published"
assert opts["草稿指标"]["status"] == "draft"
assert "网点" in [o["value"] for o in refs.options("dimension:metric", "成交金额")]
writable = [o["value"] for o in refs.options("property:object_type", b["ot"]["name"])]
assert set(writable) == {"等级", "跟进状态"} # 只列可写属性
assert refs.options("time")[0]["value"] == "current"
def test_同一个对象_按id或名称都认(env):
from app.capability import refs
b = build_basics(env["ds_id"])
ot = refs.lookup(b["ot"]["id"], "object_type")
assert refs.same_ref(b["ot"]["id"], ot) and refs.same_ref("网点", ot) and refs.same_ref("店", ot)
assert not refs.same_ref("门店", ot)
def test_对象页能看到按名称关联的动作(env):
from fastapi.testclient import TestClient
from app.kernel import service
from app.main import app
build_basics(env["ds_id"])
service.create_concept("action", "按名称的动作", spec={
"target_type": "网点", "params": [],
"effects": [{"tool": "task.create", "args": {"title": "看看 $obj.label", "role": "operator"}}],
"approval": {"mode": "manual", "approver_roles": []}})
service.publish("动作")
r = TestClient(app).get("/api/kernel/objects/网点/1").json()
assert "按名称的动作" in [a["name"] for a in r["actions"]]
# ---------------------------------------------------------------- 草稿可试运行
def test_流程卡引用草稿_试运行能跑_发布被拦并列出草稿(env):
from app.kernel import service as ksvc
from app.sop import engine, service
b = build_basics(env["ds_id"])
m = ksvc.create_concept("function", "草稿成交", spec={"category": "aggregate", "object_type": b["ot"]["id"]})
ksvc.set_binding(m["id"], env["ds_id"], "metric_expr", {
"base_table": "order_item", "expression": "SUM(amount)", "dimensions": {"网点": "store_id"}})
d = service.create("草稿巡检", spec={"steps": [
{"id": "q", "type": "function", "title": "取数", "function": "metric.query",
"args": {"metric": "草稿成交", "dimensions": ["网点"]}, "output": "x", "next": "end"},
{"id": "end", "type": "end", "title": "完成"}]})
got = service.get(d["id"])
assert [r["name"] for r in got["validation"]["draft_refs"]] == ["草稿成交"]
run = engine.start(d["id"], {}, mode="dry_run", wait=True)
assert run["status"] == "done", run["error"]
with pytest.raises(HTTPException) as e:
service.submit_publish(d["id"])
assert e.value.status_code == 412 and "草稿成交" in str(e.value.detail)
def test_流程卡参数没填或名字不存在_编辑时就报出来(env):
from app.sop import service
build_basics(env["ds_id"])
d = service.create("空取数") # 新建的空白流程卡从「取数」开始
assert d["spec"]["steps"][0]["function"] == "metric.query"
errs = service.get(d["id"])["validation"]["errors"]
assert any("还没填" in e for e in errs)
service.update(d["id"], spec={"steps": [
{"id": "q", "type": "function", "title": "取数", "function": "metric.query",
"args": {"metric": "不存在的指标"}, "next": "end"}, {"id": "end", "type": "end", "title": "完"}]})
assert any("找不到" in e for e in service.get(d["id"])["validation"]["errors"])
def test_子流程没给必填参数_编辑时报错(env):
from app.sop import service
build_basics(env["ds_id"])
child = service.create("子", spec={"params": [{"name": "who", "label": "对象", "type": "string", "required": True}],
"steps": [{"id": "end", "type": "end", "title": "完"}]})
parent = service.create("父", spec={"steps": [
{"id": "sub", "type": "subprocess", "title": "调子", "sop": child["id"], "next": "end"},
{"id": "end", "type": "end", "title": "完"}]})
assert any("必填参数" in e for e in service.get(parent["id"])["validation"]["errors"])
# ---------------------------------------------------------------- 动作审批策略
def test_自动执行的动作_提议即执行并留审计(env):
from app.capability import actions, tasks
from app.governance import audit
b = build_basics(env["ds_id"])
_auto_action(b["ot"]["id"])
tok = as_user("operator")
run = actions.propose("dispatch_check", {"reason": "抽查"}, object_key="1")
identity.reset(tok)
assert run["status"] == "done"
assert run["approvals"][0]["status"] == "auto"
assert tasks.list_tasks(scope="all")[0]["title"].startswith("复核")
events = [x["event"] for x in audit.query(target_type="action_run", target_id=run["id"])["items"]]
assert "action.auto_approve" in events
def test_条件自动_满足就执行_不满足转人工(env):
from app.capability import actions
b = build_basics(env["ds_id"])
_auto_action(b["ot"]["id"], mode="conditional", auto_when="qty < 10")
tok = as_user("operator")
small = actions.propose("dispatch_check", {"reason": "少量", "qty": 3}, object_key="1")
big = actions.propose("dispatch_check", {"reason": "大量", "qty": 30}, object_key="1")
identity.reset(tok)
assert small["status"] == "done"
assert big["status"] == "pending_approval"
assert any("不满足自动执行条件" in e["text"] for e in big["evidence"])
def test_AI提议的动作_即使设了自动也要人批(env):
from app.capability import actions
b = build_basics(env["ds_id"])
_auto_action(b["ot"]["id"])
tok = identity.set_current(identity.as_ai(identity.Actor(id="operator", roles=["operator"])))
run = actions.propose("dispatch_check", {"reason": "AI 觉得该查"}, object_key="1", initiator_kind="ai")
identity.reset(tok)
assert run["status"] == "pending_approval"
def test_审批策略校验_条件写错当场报错_决策表配置不丢(env):
from app.capability import defs
base = {"params": [{"name": "qty", "type": "number"}],
"effects": [{"tool": "task.create", "args": {"title": "x"}}]}
with pytest.raises(HTTPException):
defs.validate_action({**base, "approval": {"mode": "conditional", "auto_when": "nope > 1"}})
with pytest.raises(HTTPException):
defs.validate_action({**base, "approval": {"mode": "conditional"}})
spec, _ = defs.validate_action({**base, "approval": {
"mode": "conditional", "auto_when": "priority == 'P3' and qty < 5",
"decision": {"function": "审批规则", "inputs": {"数量": "$qty"}}}})
assert spec["approval"]["mode"] == "conditional"
assert spec["approval"]["decision"]["function"] == "审批规则"
def test_流程卡里的自动动作_不用等审批直接走完(env):
from app.sop import engine, service
b = build_basics(env["ds_id"])
_auto_action(b["ot"]["id"])
d = service.create("自动派单", spec={"steps": [
{"id": "a", "type": "action", "title": "派单", "action": "dispatch_check",
"params": {"reason": "流程"}, "object_key": "1", "output": "r", "next": "end"},
{"id": "end", "type": "end", "title": "完", "outcome": "好了"}]})
engine.start(d["id"], {}, mode="dry_run", wait=True)
service.submit_publish(d["id"])
from app.governance import review
item = review.list_items(kind="sop_publish")["items"][0]
review.decide(item["id"], True)
run = engine.start(d["id"], {}, mode="live", wait=True)
assert run["status"] == "done", run["error"]
assert [s["status"] for s in run["steps"]] == ["done", "done"]
def test_执行失败可以重试_已成功的效果不重复(env, monkeypatch):
from app.capability import actions, registry
b = build_basics(env["ds_id"])
_auto_action(b["ot"]["id"])
tool = registry.TOOLS["task.create"]
real = tool.run
calls = {"n": 0}
def flaky(args, ctx):
calls["n"] += 1
if calls["n"] == 1:
raise RuntimeError("外部系统超时")
return real(args, ctx)
monkeypatch.setattr(tool, "run", flaky)
run = actions.propose("dispatch_check", {"reason": "重试"}, object_key="1")
assert run["status"] == "failed"
again = actions.retry(run["id"])
assert again["status"] == "done" and calls["n"] == 2
with pytest.raises(HTTPException):
actions.retry(run["id"]) # 成功了就不能再重试
def test_卡在执行中的动作_重启时标成失败可重试(env):
from app.capability import actions
from app.capability.models import ActionRun
from app.core.dbx import session
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
tok = as_user("operator")
run = actions.propose("mark_follow", {"reason": "卡住"}, object_key="1")
identity.reset(tok)
with session() as s:
r = s.get(ActionRun, run["id"])
r.status, r.decided_at = "executing", dt.datetime.now() - dt.timedelta(hours=1)
s.commit()
assert actions.recover_stuck() == 1
assert actions.get(run["id"])["status"] == "failed"
# ---------------------------------------------------------------- 流程卡场景配方
def test_场景配方_指标巡检逐行发起动作_生成即可试运行(env):
from app.sop import engine, recipes, service
b = build_basics(env["ds_id"])
_auto_action(b["ot"]["id"])
built = recipes.build("metric_patrol", {"metric": "成交金额", "dimensions": ["网点"], "action": "dispatch_check"})
each = next(s for s in built["spec"]["steps"] if s["type"] == "foreach")
assert each["object_key"] == "$item.网点" # 维度名和对象名对上了
d = service.create(built["title"], built["description"], built["spec"])
assert not service.get(d["id"])["validation"]["errors"]
run = engine.start(d["id"], {}, mode="dry_run", wait=True)
assert run["status"] == "done", run["error"]
# ---------------------------------------------------------------- 监控
def test_定时扫描没命中_不写动态(env):
from app.governance import audit
from app.watch import engine, service
build_basics(env["ds_id"])
w = service.create({"title": "永远不命中", "schedule": {"kind": "interval", "every_minutes": 5},
"source": {"kind": "metric", "metric": "成交金额", "dimensions": ["网点"]},
"condition": "value < 0",
"strategies": [{"kind": "notify", "role": "operator", "title": "看看"}], "dedup": {"key": "$key", "cooldown_hours": 1}})
from app.core.dbx import session
from app.watch.models import Watch
with session() as s:
s.get(Watch, w["id"]).next_fire_at = dt.datetime.now() - dt.timedelta(minutes=1)
s.commit()
assert engine.tick() == [w["id"]]
assert not [x for x in audit.query(limit=50)["items"] if x["event"].startswith("watch.")
and x["event"] not in ("watch.create",)]
def test_监控被当作引用方(env):
from app.kernel import service as ksvc
from app.watch import service
b = build_basics(env["ds_id"])
service.create({"title": "盯成交", "schedule": {"kind": "daily", "at": "08:00"},
"source": {"kind": "metric", "metric": "成交金额"}, "condition": "value > 0",
"strategies": [{"kind": "notify", "role": "operator", "title": "看看"}], "dedup": {"key": "$key", "cooldown_hours": 1}})
assert "盯成交" in [u["name"] for u in ksvc.usage(b["metric"]["id"])]
# ---------------------------------------------------------------- 提问用上本体
def test_时间短语_上周本周近几周(env):
from app.kernel import calendar as cal
d = dt.date(2026, 9, 28) # 周一
assert cal.parse_time_phrase("上周各仓库缺货", d)["start"] == "2026-09-21"
assert cal.parse_time_phrase("本周", d)["end"] == "2026-10-04"
assert cal.parse_time_phrase("近2周", d)["start"] == "2026-09-15"
assert cal.parse_time_phrase("上季度", d)["start"] == "2026-04-01"
assert cal.resolve(None, "last_week", d)["period"] == "上周"
assert cal.resolve(None, "2026-08", d)["start"] == "2026-08-01" # 老写法照旧
def test_本体结构摘要_进提问提示词(env):
from app.agents import lead
build_basics(env["ds_id"])
text = lead.ontology_text()
assert "对象「网点」" in text and "编号(" not in text # 没中文名的属性不硬加括号
assert "成交金额" in text
def test_自由SQL路_按数据范围改写(env):
from app.kernel import grounding
b = build_basics(env["ds_id"])
tok = identity.set_current(identity.Actor(id="u", roles=["viewer"], scope={b["ot"]["id"]: {"编号": ["1"]}}))
try:
out = grounding.scope_sql(env["ds_id"], "SELECT s.store_name FROM store AS s WHERE s.level = 'A'")
finally:
identity.reset(tok)
assert "WHERE" in out and "'1'" in out and " AS s" in out
assert grounding.scope_sql(env["ds_id"], "SELECT 1 FROM store") == "SELECT 1 FROM store" # 管理员无限制
def test_SQL提示里注明表是哪个对象_列是哪个属性(env):
from app.text2sql import semantic
b = build_basics(env["ds_id"])
ov = semantic.ontology_overlay(env["ds_id"])
assert ov["tables"]["store"]["concept"] == "网点"
models = [m for m in semantic.models_with_columns(env["ds_id"], enabled_only=True) if m["physical_table"] == "store"]
ddl = semantic.render_schema(models, [], [], ov)
assert "本体对象:网点" in ddl and "本体属性:网点.名称" in ddl
assert b["ot"]["id"]
def test_实际用到的本体_从工具结果里摘出来(env):
from app.kernel import grounding
build_basics(env["ds_id"])
used = grounding.used_concepts([{"metric": {"name": "成交金额"}}, {"rule": "达标判定", "result": True}])
assert [u["name"] for u in used] == ["成交金额", "达标判定"]
# ---------------------------------------------------------------- 管理员全能审批
def test_管理员能批自己提交的变更提案_审计注明豁免(env):
from app.governance import audit, review
from app.kernel import service
service.create_concept("object_type", "临时", spec={"properties": [{"name": "编号", "is_key": True}]})
item = service.propose_release("管理员自己提的")
assert service.can_decide_release(identity.current(), item) == ""
review.decide(item["id"], True)
assert service.list_revisions()[0]["revision"] == 1
assert any("豁免四眼" in (x["summary"] or "") or "豁免四眼" in str(x.get("after") or "")
for x in audit.query(limit=20)["items"])
def test_管理员能批自己发起的动作和别的角色的动作_审批人仍守四眼(env):
from app.capability import actions
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
mine = actions.propose("mark_follow", {"reason": "管理员自己发起"}, object_key="1")
assert actions.decide(mine["id"], True)["status"] == "done"
tok = as_user("approver")
run = actions.propose("mark_follow", {"reason": "审批人自己发起"}, object_key="2")
with pytest.raises(HTTPException) as e:
actions.decide(run["id"], True)
assert "四眼" in str(e.value.detail)
identity.reset(tok)
assert actions.decide(run["id"], True)["status"] == "done" # 管理员不用切身份就能批
def test_管理员一步发布接口(env):
from fastapi.testclient import TestClient
from app.kernel import service
from app.main import app
service.create_concept("object_type", "一步发布", spec={"properties": [{"name": "编号", "is_key": True}]})
r = TestClient(app).post("/api/kernel/publish", json={"note": "直接发", "approve_now": True}).json()
assert r["status"] == "accepted" and r["published"]["revision"] == 1
def test_逐行处理可以只处理满足条件的行(env):
from app.sop import engine
rows = {"columns": ["网点", "value"], "rows": [["1", 5], ["2", 0], ["3", 7]]}
got = engine._pick_rows({"title": "逐行", "when": "value > 0", "limit": 20}, rows, {})
assert [r["网点"] for r in got] == ["1", "3"]
assert len(engine._pick_rows({"title": "逐行", "limit": 2}, rows, {})) == 2
def test_问数结果里维度是对象时补上名称(env):
from app.data_agent import agent
build_basics(env["ds_id"])
res = {"columns": ["网点", "value"], "rows": [["1", 10]]}
agent._with_names(res)
assert res["columns"] == ["网点", "网点名称", "value"]
assert res["rows"][0][1] # 网点 1 的名称来自对象的显示列
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
INFO: 127.0.0.1:60676 - "GET /healthz HTTP/1.1" 200 OK
INFO: 127.0.0.1:52097 - "GET /api/documents/6/content HTTP/1.1" 200 OK
INFO: 127.0.0.1:49908 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:61642 - "GET /api/info HTTP/1.1" 200 OK
INFO: 127.0.0.1:61642 - "GET /api/sql/pairs?ds_id=2&status=verified&limit=6 HTTP/1.1" 200 OK
INFO: 127.0.0.1:61642 - "POST /api/sql/ask HTTP/1.1" 200 OK
INFO: 127.0.0.1:61642 - "GET /api/queries?limit=20 HTTP/1.1" 200 OK
INFO: 127.0.0.1:52793 - "GET /api/info HTTP/1.1" 200 OK
INFO: 127.0.0.1:52793 - "POST /api/query HTTP/1.1" 200 OK
INFO: 127.0.0.1:52793 - "GET /api/queries?limit=20 HTTP/1.1" 200 OK
INFO: 192.168.1.203:62105 - "GET / HTTP/1.1" 304 Not Modified
INFO: 192.168.1.203:62105 - "GET /assets/index-DCPzhX7I.js HTTP/1.1" 304 Not Modified
INFO: 192.168.1.203:62523 - "GET /assets/md-D5DOzBok.js HTTP/1.1" 304 Not Modified
INFO: 192.168.1.203:53622 - "GET /assets/graph-CcVUCUcP.js HTTP/1.1" 304 Not Modified
INFO: 192.168.1.203:52810 - "GET /assets/editor-DzW7VISe.js HTTP/1.1" 304 Not Modified
INFO: 192.168.1.203:60941 - "GET /assets/index-Cv9LQWac.css HTTP/1.1" 304 Not Modified
INFO: 192.168.1.203:60941 - "GET /api/queries?limit=20 HTTP/1.1" 200 OK
INFO: 192.168.1.203:52810 - "GET /api/info HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/config HTTP/1.1" 200 OK
INFO: 127.0.0.1:63930 - "PUT /api/config HTTP/1.1" 200 OK
INFO: 127.0.0.1:52352 - "GET /api/info HTTP/1.1" 200 OK
INFO: 127.0.0.1:61629 - "GET /api/cap/ref-options?ref=time HTTP/1.1" 200 OK
INFO: 127.0.0.1:61630 - "POST /api/ask HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52582 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:51428 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52217 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64932 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59453 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:49951 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51989 - "GET /api/cap/approvals HTTP/1.1" 200 OK
INFO: 127.0.0.1:62708 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60157 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61603 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:51989 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60157 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61603 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61603 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:60157 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:51989 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:62708 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61771 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:61603 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:60157 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51989 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56457 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:62708 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:61603 - "GET /api/kernel/concepts?kind=object_type&status=published HTTP/1.1" 200 OK
INFO: 127.0.0.1:61771 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:61751 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60157 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51989 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56457 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:62708 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:61771 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61603 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60157 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:62708 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:56457 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51989 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61603 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:60157 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:62708 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51989 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56457 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:50282 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61531 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61540 - "GET / HTTP/1.1" 200 OK
INFO: 127.0.0.1:61541 - "GET /api/cap/ref-options?ref=metric HTTP/1.1" 200 OK
INFO: 127.0.0.1:62980 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:51635 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55572 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60531 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50117 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50117 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:60099 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:56493 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:50780 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:50117 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:56425 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60777 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:60777 - "GET /api/sop/defs/sop_e068619c2c264dcaa183 HTTP/1.1" 200 OK
INFO: 127.0.0.1:60777 - "GET /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:60777 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60777 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:58003 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:53538 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:54435 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/ask/conversations/cv_8081a05d52294810a0e8 HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/ask/turns/tn_b518e74e3865406589db/trace HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/ask/conversations/cv_309dcc9a50194c2db812 HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/ask/turns/tn_24a1a45bf36e447ba488/trace HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/ask/conversations/cv_923b2a54b2f9457bbecb HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/ask/turns/tn_8afaefa787d445199baf/trace HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/ask/conversations/cv_4d64f93c95844ef8bf62 HTTP/1.1" 200 OK
INFO: 127.0.0.1:56291 - "GET /api/ask/turns/tn_89dcefc3cc48469ea3d9/trace HTTP/1.1" 200 OK
INFO: 127.0.0.1:59336 - "GET /api/ask/turns/tn_9cd37a71b6754952b97b/trace HTTP/1.1" 200 OK
INFO: 127.0.0.1:62129 - "GET /api/ask/turns/tn_4b20fd03abad4df182c0/trace HTTP/1.1" 200 OK
INFO: 192.168.1.203:62891 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51705 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60564 - "POST /api/ask HTTP/1.1" 200 OK
INFO: 127.0.0.1:50801 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54301 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63792 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:55646 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51490 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62739 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63434 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59517 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:53810 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60564 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:50639 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63097 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51189 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64777 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:50962 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53284 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62617 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63550 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55481 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:64731 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57071 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49564 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56504 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49256 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:53374 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65528 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52010 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64932 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:56504 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56792 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:49524 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:54052 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:63576 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:52077 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56792 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:59475 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:59475 - "GET /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:50985 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50146 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63981 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62721 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:65472 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55190 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59569 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54965 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:51774 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57032 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52864 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58537 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:64461 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55679 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58111 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56301 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:54187 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52063 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60348 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55557 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:54024 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49299 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61059 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62957 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:63785 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58517 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54011 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62599 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:52342 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56826 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49482 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56756 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:54463 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63691 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53600 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56008 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51828 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:55209 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56906 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49290 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61028 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64777 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:54155 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63594 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54044 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51595 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:55047 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61979 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57076 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61770 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57131 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:50704 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:58577 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:59862 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61010 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:54408 - "POST /api/ask HTTP/1.1" 200 OK
INFO: 127.0.0.1:58443 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:55342 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60810 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53305 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62761 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63578 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:51337 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52000 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50060 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58490 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54718 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:56985 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58535 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58070 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:59911 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59911 - "GET /api/cap/approvals HTTP/1.1" 200 OK
INFO: 127.0.0.1:52858 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51002 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61176 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:59911 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52858 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61176 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61176 - "GET /api/cap/tasks?scope=mine&status=open HTTP/1.1" 200 OK
INFO: 127.0.0.1:52858 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59911 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:52858 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52858 - "GET /api/gov/notifications?unread=false HTTP/1.1" 200 OK
INFO: 127.0.0.1:54450 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56125 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:54450 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54450 - "GET /api/cap/tasks?scope=mine&status=open HTTP/1.1" 200 OK
INFO: 127.0.0.1:56125 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52858 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:52858 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64932 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51110 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:62935 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:58440 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:59967 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51110 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61528 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:61528 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61528 - "GET /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:61528 - "GET /api/cap/ref-options?ref=metric HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/ref-options?ref=rule HTTP/1.1" 200 OK
INFO: 127.0.0.1:51110 - "GET /api/cap/ref-options?ref=role HTTP/1.1" 200 OK
INFO: 127.0.0.1:59967 - "GET /api/cap/ref-options?ref=calendar HTTP/1.1" 200 OK
INFO: 127.0.0.1:58440 - "GET /api/cap/ref-options?ref=decision HTTP/1.1" 200 OK
INFO: 192.168.1.203:62457 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53937 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58835 - "GET /api/cap/approvals HTTP/1.1" 200 OK
INFO: 127.0.0.1:59829 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56957 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56280 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:58835 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56957 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56280 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56280 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56280 - "GET /api/cap/tasks?scope=mine&status=open HTTP/1.1" 200 OK
INFO: 127.0.0.1:56957 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58835 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:58835 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58835 - "GET /api/cap/runs?limit=200 HTTP/1.1" 200 OK
INFO: 127.0.0.1:56957 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56280 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56957 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56957 - "GET /api/gov/notifications?unread=false HTTP/1.1" 200 OK
INFO: 127.0.0.1:56280 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58835 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56280 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56280 - "GET /api/cap/tasks?scope=mine&status=open HTTP/1.1" 200 OK
INFO: 127.0.0.1:58835 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56957 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56957 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57636 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64029 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:61034 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64521 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62684 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:55809 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51153 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62463 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:62463 - "GET /api/kernel/concepts?kind=object_type&status=published HTTP/1.1" 200 OK
INFO: 127.0.0.1:51153 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55809 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:55809 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55809 - "GET /api/kernel/objects/obj_0a94698f4e0f4a29ae8a?limit=50 HTTP/1.1" 422 Unprocessable Entity
INFO: 127.0.0.1:55809 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:51153 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:62463 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62684 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:62463 - "GET /api/kernel/concepts?kind=object_type&status=published HTTP/1.1" 200 OK
INFO: 127.0.0.1:62684 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51153 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/kernel/objects/obj_0a94698f4e0f4a29ae8a?limit=50 HTTP/1.1" 422 Unprocessable Entity
INFO: 127.0.0.1:55875 - "GET /api/kernel/objects/obj_a541aa32226345f68ae6?limit=50 HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/kernel/objects/obj_82d232d118b940adab2e?limit=50 HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/cap/approvals HTTP/1.1" 200 OK
INFO: 127.0.0.1:49622 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54853 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:58426 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54853 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:58426 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58426 - "GET /api/cap/tasks?scope=mine&status=open HTTP/1.1" 200 OK
INFO: 127.0.0.1:54853 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55875 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:54853 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52562 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55155 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:60509 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65224 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56534 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56534 - "GET /api/watch HTTP/1.1" 200 OK
INFO: 127.0.0.1:61024 - "GET /api/watch/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:57017 - "GET /api/kernel/concepts?kind=object_type HTTP/1.1" 200 OK
INFO: 127.0.0.1:57960 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:49218 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58786 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57017 - "GET /api/cap/approvals HTTP/1.1" 200 OK
INFO: 127.0.0.1:61024 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:49218 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57960 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:58786 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:49218 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49218 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49218 - "GET /api/cap/tasks?scope=mine&status=open HTTP/1.1" 200 OK
INFO: 127.0.0.1:58786 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57960 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57960 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50985 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54122 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:60020 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62073 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51023 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58933 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:60920 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55340 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62892 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64932 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:64177 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60526 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61319 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62898 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:56904 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57558 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:62667 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:64932 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:56940 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:52685 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57558 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:53680 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:53680 - "GET /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:54597 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63097 - "GET /api/sop/defs/sop_e068619c2c264dcaa183 HTTP/1.1" 200 OK
INFO: 127.0.0.1:63097 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63097 - "GET /api/sop/defs/sop_c7ea1848a8e1483d9647 HTTP/1.1" 200 OK
INFO: 127.0.0.1:63097 - "GET /api/sop/defs/sop_e068619c2c264dcaa183 HTTP/1.1" 200 OK
INFO: 127.0.0.1:58074 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57380 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62443 - "GET /api/cap/approvals HTTP/1.1" 200 OK
INFO: 127.0.0.1:57795 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61710 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:52351 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:62443 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61710 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:62443 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62443 - "GET /api/cap/tasks?scope=mine&status=open HTTP/1.1" 200 OK
INFO: 127.0.0.1:61710 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52351 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:52351 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52351 - "GET /api/gov/notifications?unread=false HTTP/1.1" 200 OK
INFO: 127.0.0.1:61710 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62443 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61710 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:64275 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61710 - "GET /api/cap/tasks?scope=mine&status=open HTTP/1.1" 200 OK
INFO: 127.0.0.1:62443 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52351 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61710 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49751 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65493 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49749 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64268 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:50961 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51719 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61512 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52629 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50177 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:60969 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55469 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56148 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57117 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:63778 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63030 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51359 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59201 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:62712 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61914 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52645 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59824 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:54002 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59582 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59475 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51526 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59709 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:55876 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63289 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62341 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55745 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58899 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:60329 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57801 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:50060 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:56321 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:57801 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:63579 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51843 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56383 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:56383 - "GET /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:53199 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "POST /api/sop/validate HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "POST /api/sop/validate HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "POST /api/sop/validate HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "POST /api/sop/validate HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "POST /api/sop/validate HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "POST /api/sop/validate HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "POST /api/sop/validate HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "POST /api/sop/validate HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "PUT /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "GET /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:53458 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:58667 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50833 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:56923 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56888 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59687 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56763 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52077 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:63710 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62259 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56055 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64094 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52950 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:55666 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59891 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60681 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49394 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:61538 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50060 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62641 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55038 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:55562 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49162 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60526 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57261 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:53624 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63500 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50060 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56769 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:53093 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65472 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60917 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61764 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:62242 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63695 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62941 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62526 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:53961 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57504 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61244 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49839 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:56037 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55357 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/kernel/concepts?kind=object_type&status=published HTTP/1.1" 200 OK
INFO: 127.0.0.1:54378 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:62435 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59438 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/kernel/objects/obj_0a94698f4e0f4a29ae8a?limit=50 HTTP/1.1" 422 Unprocessable Entity
INFO: 127.0.0.1:55100 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:59438 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:62435 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:54378 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61954 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63692 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/cap/approvals HTTP/1.1" 200 OK
INFO: 127.0.0.1:59438 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:62435 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:54378 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:61954 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:63692 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:59438 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:62435 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:54378 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:61954 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:63692 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:59438 - "GET /api/kernel/concepts?kind=object_type&status=published HTTP/1.1" 200 OK
INFO: 127.0.0.1:62435 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:54378 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:61954 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:63692 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:61954 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:63692 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:61954 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:54378 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:63692 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:61954 - "GET /api/kernel/objects/obj_0a94698f4e0f4a29ae8a?limit=50 HTTP/1.1" 422 Unprocessable Entity
INFO: 127.0.0.1:62435 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62435 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58605 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62875 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:64718 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62274 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/modeling/runs HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/graph HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/concepts/lin_fdaa08edfaaf4221a305 HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/concepts/lin_8355ac8fa6204166a43f HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/concepts/lin_fb322b9cb6c84d169fa4 HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/kernel/concepts/lin_c8045b295f1c4ce8910e HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/concepts/lin_368baf30c53e4fbc9950 HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/concepts/lin_657239ee543b4cd387f4 HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/concepts/lin_fdaa08edfaaf4221a305 HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/concepts/lin_8355ac8fa6204166a43f HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/kernel/concepts/lin_fb322b9cb6c84d169fa4 HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/concepts/lin_c8045b295f1c4ce8910e HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/concepts/lin_368baf30c53e4fbc9950 HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/concepts/lin_657239ee543b4cd387f4 HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/kernel/graph HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/modeling/runs HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/diff HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/kernel/stats HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/releases HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/gov/review/counts HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/kernel/revisions HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/revisions/compare?from=1&to=2 HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/diff HTTP/1.1" 200 OK
INFO: 127.0.0.1:57156 - "GET /api/kernel/stats HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/releases HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/gov/review/counts HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:59039 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:57739 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/kernel/concepts/act_f33cd0813fba4b40a9d3 HTTP/1.1" 200 OK
INFO: 127.0.0.1:49772 - "GET /api/cap/ref-options?ref=decision HTTP/1.1" 200 OK
INFO: 127.0.0.1:55166 - "GET /api/cap/ref-options?ref=role HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/ref-options?ref=user HTTP/1.1" 200 OK
INFO: 127.0.0.1:59974 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49181 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:57824 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58075 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55357 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50317 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61942 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:63545 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58031 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59507 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51699 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64266 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:50961 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61490 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55334 - "GET /api/cap/ref-options?ref=object_type HTTP/1.1" 200 OK
INFO: 127.0.0.1:49589 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54384 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65161 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:50960 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59105 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49994 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:57918 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:51105 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:59814 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55377 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53108 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:49994 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:49994 - "GET /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:49994 - "GET /api/sop/defs/sop_98935fd6348a45e38626 HTTP/1.1" 200 OK
INFO: 127.0.0.1:49994 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53277 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52975 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:58241 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55100 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50839 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56057 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60073 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:52247 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65222 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57178 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63627 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:58674 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58659 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55779 - "GET /api/sop/defs/sop_9e036138e5274012affb HTTP/1.1" 200 OK
INFO: 127.0.0.1:57368 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56069 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:65140 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60574 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56077 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59464 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49614 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49614 - "GET /api/kernel/modeling/runs HTTP/1.1" 200 OK
INFO: 127.0.0.1:62917 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:54238 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56238 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62162 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:62162 - "GET /api/kernel/modeling/runs/mr_d94dac1029d645aab61e HTTP/1.1" 200 OK
INFO: 127.0.0.1:62162 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:56238 - "GET /api/kernel/graph HTTP/1.1" 200 OK
INFO: 127.0.0.1:54238 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:62917 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:49614 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63539 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:63539 - "PUT /api/kernel/layout HTTP/1.1" 200 OK
INFO: 192.168.1.203:56546 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61817 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60528 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:51168 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:62194 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56566 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49163 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:49163 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:56566 - "GET /api/kernel/graph HTTP/1.1" 200 OK
INFO: 127.0.0.1:62194 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:51168 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:60528 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50212 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:50212 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64266 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54552 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:56168 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58365 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59166 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56534 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60190 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:65094 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54470 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:55693 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:64057 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:52788 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53188 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:54470 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:55693 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:64097 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:64057 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52788 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:52788 - "GET /api/kernel/modeling/runs HTTP/1.1" 200 OK
INFO: 127.0.0.1:64057 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:64097 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55693 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54470 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:64477 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54470 - "GET /api/kernel/modeling/runs/mr_d94dac1029d645aab61e HTTP/1.1" 200 OK
INFO: 127.0.0.1:60173 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60173 - "GET /api/kernel/pipelines HTTP/1.1" 200 OK
INFO: 127.0.0.1:54690 - "GET /api/kernel/concepts?kind=object_type HTTP/1.1" 200 OK
INFO: 127.0.0.1:49599 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64479 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:58123 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:58123 - "GET /api/documents HTTP/1.1" 200 OK
INFO: 127.0.0.1:64479 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:49599 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54690 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:54690 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:49599 - "GET /api/kernel/graph HTTP/1.1" 200 OK
INFO: 127.0.0.1:64479 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:58123 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:60173 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52235 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:54690 - "GET /api/kernel/modeling/runs HTTP/1.1" 200 OK
INFO: 127.0.0.1:49599 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:64479 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:58123 - "GET /api/kernel/graph HTTP/1.1" 200 OK
INFO: 127.0.0.1:60173 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:52235 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:54690 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49599 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:64479 - "GET /api/kernel/modeling/runs HTTP/1.1" 200 OK
INFO: 127.0.0.1:58123 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:60173 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:54690 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64479 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:58123 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:54690 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64479 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:54825 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:62511 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:49347 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:62511 - "GET /api/kernel/graph HTTP/1.1" 200 OK
INFO: 127.0.0.1:60104 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:49347 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:62511 - "GET /api/cap/catalog HTTP/1.1" 200 OK
INFO: 127.0.0.1:60104 - "GET /api/gov/roles HTTP/1.1" 200 OK
INFO: 127.0.0.1:49347 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/sop/defs HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:49347 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60104 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:62511 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49347 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:49347 - "GET /api/kernel/concepts/lin_fdaa08edfaaf4221a305 HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/kernel/concepts/lin_8355ac8fa6204166a43f HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/kernel/concepts/lin_fb322b9cb6c84d169fa4 HTTP/1.1" 200 OK
INFO: 127.0.0.1:62511 - "GET /api/kernel/concepts/lin_c8045b295f1c4ce8910e HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/kernel/concepts/lin_368baf30c53e4fbc9950 HTTP/1.1" 200 OK
INFO: 127.0.0.1:60104 - "GET /api/kernel/concepts/lin_657239ee543b4cd387f4 HTTP/1.1" 200 OK
INFO: 127.0.0.1:60104 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/kernel/graph HTTP/1.1" 200 OK
INFO: 127.0.0.1:62511 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49347 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:60104 - "GET /api/kernel/modeling/runs HTTP/1.1" 200 OK
INFO: 127.0.0.1:58030 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:62511 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57756 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:56300 - "GET /api/kernel/modeling/runs/mr_d94dac1029d645aab61e HTTP/1.1" 200 OK
INFO: 192.168.1.203:56998 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57161 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51526 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:54982 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:52548 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:51112 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50571 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:51526 - "GET /api/kernel/meta HTTP/1.1" 200 OK
INFO: 127.0.0.1:54982 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57390 - "GET /api/kernel/concepts HTTP/1.1" 200 OK
INFO: 127.0.0.1:52548 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51112 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:54988 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54988 - "GET /api/kernel/modeling/runs HTTP/1.1" 200 OK
INFO: 127.0.0.1:62978 - "GET /api/sql/datasources HTTP/1.1" 200 OK
INFO: 127.0.0.1:64266 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:57906 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53211 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:62943 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:49452 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:60150 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:50060 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:63591 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:52138 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55880 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:57591 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59193 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65472 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65188 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61908 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:52773 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53416 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61596 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59193 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55618 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:63217 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51324 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61257 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64778 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:50226 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:60394 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49465 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57860 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64641 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:50960 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64473 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54399 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:54226 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62647 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:64327 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55724 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:61141 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62498 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57147 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:49704 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59888 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52736 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53319 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:62198 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52982 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53499 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:51622 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:56303 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:55721 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58625 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:65482 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:49193 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49743 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59878 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49203 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:57249 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:60198 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62517 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57932 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:53004 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 192.168.1.203:51112 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64640 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:49696 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:58994 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59127 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:59127 - "GET / HTTP/1.1" 200 OK
INFO: 127.0.0.1:59127 - "GET /assets/index-ui3DG8U2.js HTTP/1.1" 200 OK
INFO: 127.0.0.1:56679 - "GET /assets/index-C5QfbCSO.css HTTP/1.1" 200 OK
INFO: 127.0.0.1:55920 - "GET /assets/md-CZ1ZucyD.js HTTP/1.1" 200 OK
INFO: 127.0.0.1:57245 - "GET /assets/editor-Cr0Oc3ER.js HTTP/1.1" 200 OK
INFO: 127.0.0.1:59271 - "GET /assets/graph-Dcqm_V6o.js HTTP/1.1" 200 OK
INFO: 127.0.0.1:59127 - "GET /api/ask/conversations HTTP/1.1" 200 OK
INFO: 127.0.0.1:57245 - "GET /api/kernel/workbench HTTP/1.1" 200 OK
INFO: 127.0.0.1:59271 - "GET /api/gov/me HTTP/1.1" 200 OK
INFO: 127.0.0.1:55920 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:56679 - "GET /api/kernel/workspaces HTTP/1.1" 200 OK
INFO: 127.0.0.1:50359 - "GET /api/gov/users HTTP/1.1" 200 OK
INFO: 192.168.1.203:53719 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:52896 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:64778 - "GET /api/ask/conversations/cv_8862cfc5c6d04d39adce HTTP/1.1" 200 OK
INFO: 127.0.0.1:64778 - "GET /api/ask/turns/tn_055611ffea084c4bb228/trace HTTP/1.1" 200 OK
INFO: 127.0.0.1:64778 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:57602 - "GET /api/cap/inbox HTTP/1.1" 200 OK
INFO: 127.0.0.1:62864 - "GET /api/cap/inbox HTTP/1.1" 200 OK
File mode changed
File mode changed
......@@ -10,7 +10,8 @@
"typecheck": "tsc -b",
"preview": "vite preview",
"test": "vitest run",
"build:8107": "tsc -b && vite build --outDir dist_8107 --emptyOutDir"
"build:8107": "tsc -b && vite build --outDir dist_8107 --emptyOutDir",
"build:8101": "tsc -b && vite build --outDir dist_8101 --emptyOutDir"
},
"dependencies": {
"@codemirror/lang-sql": "^6.10.0",
......
......@@ -77,8 +77,8 @@ const NAV: { group: string; items: NavItem[] }[] = [
{ key: "b_object", label: "对象", icon: <Boxes className={I} />, hint: "业务里可被指认、有属性的实体(门店、商品、供应商…)" },
{ key: "b_link", label: "关系", icon: <GitBranch className={I} />, hint: "对象之间的关系(供货、归属…)" },
{ key: "b_function", label: "函数", icon: <FunctionSquare className={I} />, hint: "对对象的计算:指标、规则、决策表、统计周期、模型推理与 AI 分析,各走确定性引擎" },
{ key: "b_action", label: "动作", icon: <Zap className={I} />, hint: "改变业务状态的操作(补货、标记、派单),执行前一律人工审批" },
{ key: "publish", label: "发布", icon: <Rocket className={I} />, hint: "草稿 → 提交变更 → 他人审批 → 发布;禁止自审,Agent 不可批" },
{ key: "b_action", label: "动作", icon: <Zap className={I} />, hint: "改变业务状态的操作(补货、标记、派单);按每个动作的审批策略:人工审批、自动执行或条件自动" },
{ key: "publish", label: "发布", icon: <Rocket className={I} />, hint: "草稿 → 提交变更 → 审批 → 发布;一般人不能批自己的,管理员可直接发布,Agent 不可批" },
{ key: "versions", label: "版本", icon: <GitCommit className={I} />, hint: "每次发布一份快照:任意两版对比、回滚(回滚也走审批)" },
] },
{ group: "运行", items: [
......@@ -211,7 +211,10 @@ export default function App() {
<select className="w-full truncate bg-transparent text-body 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>)}
{/* 两个本体同名时(如都叫「默认本体」)带上编号,不然根本分不清选的是哪个 */}
{spaces.map((x) => <option key={x.id} value={x.id}>
{x.display_name}{spaces.filter((y) => y.display_name === x.display_name).length > 1 ? `(${x.id})` : ""}
{x.counts ? ` · ${Object.values(x.counts as Record<string, number>).reduce((n, v) => n + v, 0)} 块积木` : ""}</option>)}
</select>
<span className="block truncate font-mono text-caption text-muted">{curSpace?.id || ws}</span>
</label>
......
import { AlertTriangle, ExternalLink, ShieldCheck, Undo2, Zap } from "lucide-react";
import { AlertTriangle, ExternalLink, ListChecks, ShieldCheck, Undo2, Zap } from "lucide-react";
import { useState } from "react";
import { Badge, Spinner } from "@/components/ui";
import { go } from "@/lib/nav";
......@@ -14,6 +14,11 @@ const RISK_TONE: Record<string, string> = {
export function EffectList({ preview }: { preview: ActionPreview }) {
return (
<ul className="space-y-1.5">
{preview.auto && (
<li className={`rounded-md px-2 py-1 text-caption ${preview.auto.eligible ? "bg-ok/10 text-ok" : "bg-ink/[0.03] text-muted"}`}>
{preview.auto.eligible ? "提交后将自动执行:" : "需要人工审批:"}{preview.auto.why}
</li>
)}
{(preview.effects || []).map((e, i) => (
<li key={i} className="flex items-start gap-2 rounded-md bg-ink/[0.03] px-2 py-1.5 text-label">
<Zap className="mt-0.5 h-3.5 w-3.5 shrink-0 text-brand" />
......@@ -31,8 +36,28 @@ export function EffectList({ preview }: { preview: ActionPreview }) {
);
}
/** 答案里 AI 建议的动作。只能「提交审批」,不能直接执行。 */
export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: string }) {
/** 流程卡提案里的步骤概要:审批人要先看清「批了之后会发生什么」。 */
function StepOutline({ steps }: { steps: { id: string; title: string; type_label: string; lane?: string }[] }) {
return (
<ol className="mt-2 space-y-1">
{steps.map((s, i) => (
<li key={s.id} className="flex items-start gap-2 text-caption">
<span className="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-ink/[0.06] text-[10px] text-muted">{i + 1}</span>
<span className="min-w-0 flex-1 truncate">{s.title}</span>
<span className="shrink-0 text-muted">{s.type_label}{s.lane ? ` · ${s.lane}` : ""}</span>
</li>
))}
</ol>
);
}
/** 答案里 AI 建议的动作,或建议发起的流程卡(card.kind === "sop")。
* 两者都只能「提交审批」:动作批准后执行它的效果,流程卡批准后才真正跑起来。 */
export function SuggestedActionCard({ card, turnId, evidence = [] }: {
card: AskCard; turnId: string;
/** 这一轮取到的数与口径:审批人要看到「凭什么建议我批」 */
evidence?: { kind: string; text: string; ref: string }[];
}) {
const [reason, setReason] = useState(card.reason);
const [busy, setBusy] = useState(false);
const [runId, setRunId] = useState<string>("");
......@@ -43,6 +68,7 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
const [err, setErr] = useState(card.error || "");
const [dirty, setDirty] = useState(false);
const defs = card.param_defs || [];
const isSop = card.kind === "sop";
const repreview = async () => {
setBusy(true);
......@@ -58,9 +84,11 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
const run = await onto.proposeAction(card.action_id || card.action, {
params, object_key: objKey, reason,
initiator_kind: "ai", source_ref: `turn:${turnId}`,
evidence: [{ kind: "ask", text: `由提问中的 AI 建议:${card.reason || ""}`.slice(0, 900), ref: `turn:${turnId}` }, ...evidence],
});
setRunId(run.id);
toast("ok", "已提交审批", "审批人在「审批与待办」里处理,批准后才会执行");
toast("ok", "已提交审批", isSop ? "审批人在「审批与待办」里处理,批准后流程才会跑起来"
: "审批人在「审批与待办」里处理,批准后才会执行");
} catch (e) {
toast("error", "提交失败", errText(e));
} finally {
......@@ -71,11 +99,18 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
return (
<div className="rounded-lg border border-brand/30 bg-brand/[0.03] p-3">
<div className="flex items-center gap-2">
<ShieldCheck className="h-4 w-4 text-brand" />
<span className="text-body font-medium">建议动作:{card.display_name}</span>
{isSop ? <ListChecks className="h-4 w-4 text-brand" /> : <ShieldCheck className="h-4 w-4 text-brand" />}
<span className="text-body font-medium">{isSop ? "建议发起流程" : "建议动作"}:{card.display_name}</span>
{preview && <Badge tone={RISK_TONE[preview.action.risk_level]}>{RISK[preview.action.risk_level]}</Badge>}
{preview?.action.reversible && <Badge tone="bg-ink/5 text-muted"><Undo2 className="h-3 w-3" />可撤销</Badge>}
{isSop && card.sop_id && (
<button className="ml-auto text-caption text-muted hover:text-brand" onClick={() => go("sop", { id: card.sop_id! })}>
查看流程卡 <ExternalLink className="inline h-3 w-3" />
</button>
)}
</div>
{isSop && card.description && <p className="mt-1 text-caption text-muted">{card.description}</p>}
{isSop && card.steps?.length ? <StepOutline steps={card.steps} /> : null}
{(defs.length > 0 || card.target_type) && !runId && (
<div className="mt-2 grid gap-2 sm:grid-cols-2">
{card.target_type && (
......@@ -120,8 +155,10 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
)}
</div>
<p className="mt-1.5 text-caption text-muted">
AI 只能建议,不能执行。提交后由{preview.action?.approver_roles?.length
? `「${preview.action.approver_roles.join("、")}」` : "有审批权限的人"}审批,你本人不能审批自己提交的动作。
AI 只能建议,不能{isSop ? "发起" : "执行"}。提交后由{preview.action?.approver_roles?.length
? `「${preview.action.approver_roles.join("、")}」` : "有审批权限的人"}审批
{isSop ? ",批准后流程才会开始跑 —— 里面的人工任务会派给对应角色,动作步骤各自再走一次审批"
: ",你本人不能审批自己提交的动作"}。
</p>
</>
)}
......
......@@ -196,6 +196,19 @@ export function TraceView({ trace, onOpenChunk }: { trace: TraceState; onOpenChu
</div>
</Section>
)}
{trace.used.length > 0 && (
<Section icon={<Target className="h-3.5 w-3.5" />} title="本次用到的本体">
<div className="flex flex-wrap gap-1.5">
{trace.used.map((u) => (
<button key={u.id || u.name} className="chip border-brand/40" disabled={!u.id}
onClick={() => u.id && go(pageOfKind(u.kind_label.includes("动作") ? "action" : u.kind_label.includes("对象") ? "object_type" : "function"), { id: u.id })}
title={`${u.kind_label} · ${u.how}`}>
<span className="text-caption text-muted">{u.how}</span>{u.name}
</button>
))}
</div>
</Section>
)}
{trace.memory && (trace.memory.cases.length > 0 || trace.memory.facts.length > 0) && (
<Section icon={<History className="h-3.5 w-3.5" />} title="经验召回">
<ul className="space-y-1 text-label">
......
import {
BookOpen, Brain, ChevronRight, Database, GitBranch, History, ListChecks, MessageSquarePlus, PanelRightClose,
BookOpen, Brain, ChevronRight, Database, GitBranch, History, MessageSquarePlus, PanelRightClose,
PanelRightOpen, Pin, RotateCcw, Send, Sparkles, Square, ThumbsDown, ThumbsUp, Trash2, Workflow, XCircle, Zap,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
......@@ -22,7 +22,7 @@ type TurnStatus = "running" | "done" | "aborted" | "error";
interface LiveTurn {
key: string; id: string; question: string; status: TurnStatus;
trace: TraceState; events: any[]; hasTrace: boolean;
answer: string; citations: Citation[]; data_refs: DataRef[]; actions: AskCard[]; sops: any[];
answer: string; citations: Citation[]; data_refs: DataRef[]; actions: AskCard[]; sops: AskCard[];
follow_ups: string[]; plan: any; error?: string; duration_ms?: number; rating: number;
replaying?: boolean;
}
......@@ -481,21 +481,13 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: {
</div>
)}
{t.actions.length > 0 && t.status !== "running" && (
{/* 动作卡与流程卡一视同仁:都要人核对参数、提交审批,批准后才由系统执行 */}
{t.actions.length + t.sops.length > 0 && t.status !== "running" && (
<div className="mt-3 space-y-2">
{t.actions.map((c, i) => <SuggestedActionCard key={i} card={c} turnId={t.id} />)}
</div>
)}
{t.sops.length > 0 && t.status !== "running" && (
<div className="mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-line p-2.5 text-label">
<ListChecks className="h-4 w-4 text-brand" /> 建议按流程处理:
{t.sops.map((s: any, i: number) => (
<button key={i} className="chip hover:border-brand/40" title={s.reason}
onClick={() => go("sop", { q: s.sop, params: JSON.stringify(s.params || {}) })}>
{s.sop} <ChevronRight className="h-3 w-3" />
</button>
))}
{[...t.actions, ...t.sops].map((c, i) => <SuggestedActionCard key={i} card={c} turnId={t.id} evidence={
t.data_refs.slice(0, 5).map((d) => ({
kind: "data", ref: d.sql || "",
text: `${d.metric?.name || "自由取数"}:${d.rows.length} 行${d.calibre?.text ? `;口径:${d.calibre.text}` : ""}`.slice(0, 900) }))} />)}
</div>
)}
......
......@@ -23,6 +23,8 @@ export interface TraceState {
order: string[]; // agent span 顺序
tools: Record<string, ToolNode>;
links: { concepts: any[]; instances: any[]; time: any } | null;
/** 这一轮实际执行过的本体积木(指标、规则、决策表、查过定义的概念),区别于问句里「匹配到」的 */
used: { id: string; name: string; kind_label: string; how: string }[];
memory: { cases: any[]; facts: any[]; fast: string } | null;
plan: any | null;
reflect: any[];
......@@ -31,7 +33,7 @@ export interface TraceState {
}
export const emptyTrace = (): TraceState => ({
agents: {}, order: [], tools: {}, links: null, memory: null, plan: null, reflect: [], lastTs: 0, events: 0,
agents: {}, order: [], tools: {}, links: null, used: [], memory: null, plan: null, reflect: [], lastTs: 0, events: 0,
});
const arr = <T,>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);
......@@ -45,6 +47,9 @@ export function applyEvent(s: TraceState, ev: any): TraceState {
case "link":
next.links = { concepts: arr(ev.concepts), instances: arr(ev.instances), time: ev.time ?? null };
return next;
case "onto_used":
next.used = arr(ev.items);
return next;
case "memory":
next.memory = { cases: arr(ev.cases), facts: arr(ev.facts), fast: ev.fast || "" };
return next;
......
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
Bell, Bot, CheckCircle2, ClipboardList, ExternalLink, GitPullRequest, Radar, Rocket, ShieldCheck, Undo2, User, Workflow,
AlarmClock, Bell, Bot, CheckCircle2, ClipboardList, ExternalLink, GitPullRequest, Radar, RefreshCw, Rocket, ShieldCheck, Undo2, User, Workflow,
XCircle,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
......@@ -59,7 +59,8 @@ export function InboxPage({ onChanged }: { onChanged?: () => void }) {
// ---------------------------------------------------------------- 审批
const INITIATOR: Record<string, { label: string; icon: React.ReactNode }> = {
ai: { label: "AI 建议", icon: <Bot className="h-3 w-3" /> },
sop: { label: "SOP 流程", icon: <Workflow className="h-3 w-3" /> },
sop: { label: "流程卡", icon: <Workflow className="h-3 w-3" /> },
watch: { label: "监控", icon: <AlarmClock className="h-3 w-3" /> },
user: { label: "人工", icon: <User className="h-3 w-3" /> },
};
......@@ -139,9 +140,21 @@ export function RunDetail({ run, onDone }: { run: ActionRun; onDone: () => void
</div>
)}
{run.approvals.filter((a) => a.status !== "pending").map((a) => (
<p key={a.id} className="text-muted">审批:{a.decided_by} {STATUS_LABEL[a.status] || a.status}
{a.comment ? `(${a.comment})` : ""} · {fmtTime(a.decided_at)}</p>
<p key={a.id} className="text-muted">
{a.status === "auto" ? <>自动执行(按动作的审批策略):{a.comment}</>
: <>审批:{a.decided_by} {STATUS_LABEL[a.status] || a.status}{a.comment ? `(${a.comment})` : ""}</>}
{" · "}{fmtTime(a.decided_at)}</p>
))}
{run.status === "failed" && run.kind === "normal" && (
<div className="flex items-center justify-end gap-2 border-t border-line pt-3">
<span className="mr-auto text-caption text-muted">已经成功的效果不会重复执行,从失败的那一步接着来</span>
<button className="btn btn-sm" disabled={busy} onClick={async () => {
setBusy(true);
try { const r = await onto.retryAction(run.id); toast(r.status === "done" ? "ok" : "error", r.status === "done" ? "重试成功" : "仍然失败", r.error || undefined); onDone(); }
catch (e) { toast("error", "重试失败", errText(e)); } finally { setBusy(false); }
}}><RefreshCw className="h-3.5 w-3.5" />重试</button>
</div>
)}
{run.status === "pending_approval" && (
run.can_approve === false ? (
<p className="rounded-md bg-warn/10 p-2 text-warn">{run.cannot_reason}</p>
......@@ -420,7 +433,7 @@ function Reviews({ onChanged }: { onChanged: () => void }) {
<select className="input w-36" value={kind} onChange={(e) => setKind(e.target.value)}>
<option value="">全部类型</option>
{[["concept_create", "新概念"], ["concept_update", "概念修改"], ["conflict", "知识冲突"], ["sop_publish", "SOP 发布"],
["feedback", "答案反馈"], ["binding", "数据绑定"]].map(([k, l]) => <option key={k} value={k}>{l}</option>)}
["feedback", "答案反馈"], ["binding", "数据绑定"], ["memory_fact", "经验沉淀"], ["release", "变更提案"]].map(([k, l]) => <option key={k} value={k}>{l}</option>)}
</select>
<Segmented value={status} onChange={setStatus} options={[
{ key: "pending", label: "待处理" }, { key: "accepted", label: "已采纳" }, { key: "rejected", label: "已驳回" }]} />
......
......@@ -97,14 +97,12 @@ export function ObjectsPage({ me }: { me: Me | null }) {
function Object360({ type, objKey, me }: { type: string; objKey: string; me: Me | null }) {
const [d, setD] = useState<any>(null);
const [actions, setActions] = useState<CapDef[]>([]);
const [act, setAct] = useState<CapDef | null>(null);
const load = () => { void onto.object360(type, objKey).then(setD).catch((e) => toast("error", "加载失败", errText(e))); };
useEffect(() => {
load();
void onto.capDefs("action").then((a) => setActions(a.filter((x) => x.status === "published" && x.spec.target_type === type)));
}, []); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { load(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
if (!d) return <Card className="p-6"><Spinner /></Card>;
// 能对它发起的动作由后端按「作用于对象」匹配(id 和名称都认),以前前端只比 id,业务建模生成的动作永远不出现
const actions: CapDef[] = d.actions || [];
const o = d.object;
const props = (d.object_type.spec?.properties || []) as any[];
return (
......@@ -312,9 +310,11 @@ export function ProposeActionModal({ action, objKey, onClose, onDone }: { action
<button className="btn btn-primary" disabled={!preview || !reason.trim()} onClick={async () => {
try {
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", r.status === "done" ? "已自动执行" : r.status === "failed" ? "自动执行失败" : "已提交审批",
r.status === "failed" ? r.error : undefined);
onDone(); go("inbox", { tab: "runs", run: r.id });
} catch (e) { toast("error", "提交失败", errText(e)); }
}}>提交审批 <ExternalLink className="h-3 w-3" /></button>
}}>{preview?.auto?.eligible ? "执行" : "提交审批"} <ExternalLink className="h-3 w-3" /></button>
</>}>
<div className="space-y-3">
{params.map((p: any) => (
......
......@@ -13,6 +13,7 @@ import { cn } from "@/lib/utils";
import { useAppStore, toast } from "@/store/useAppStore";
import { BindingEditor } from "../kernel/BindingEditor";
import { JsonBox, ResultView, Rows, SchemaForm, TypeBadge } from "./common";
import { invalidateRefOptions, RefSelect, useRefOptions } from "./RefSelect";
import { pageOfKind } from "./routes";
const DIR = [["higher_better", "越高越好"], ["lower_better", "越低越好"], ["neutral", "中性"]];
......@@ -70,6 +71,7 @@ export function BlockEditor({ id, meta, all, canEdit, onChanged, onClose }: {
setBusy(true);
try {
await onto.updateConcept(c.id, { ...draft, synonyms: draft.synonyms });
invalidateRefOptions();
toast("ok", "已保存到草稿", "到「发布」页提交、审批通过后,问答、取数、流程卡才会用到新定义");
await load(); onChanged();
} catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
......@@ -493,24 +495,14 @@ function ActionFields({ spec, set, canEdit, meta, objects }: {
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
<Field label="作用于对象" hint="设置后,提议时要指定对象;条件与效果里可用 $obj.属性、$obj_key">
<select className="input" value={spec.target_type || ""} disabled={!canEdit} onChange={(e) => set("target_type", e.target.value)}>
<select className="input" disabled={!canEdit} onChange={(e) => set("target_type", e.target.value)}
value={objects.find((t) => t.id === spec.target_type || t.name === spec.target_type)?.id || ""}>
<option value="">(不作用于具体对象)</option>
{objects.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
</Field>
<Field label="审批角色" hint="所有动作执行前都要人工审批;提议人不能批自己的,AI 也不能批">
<div className="flex flex-wrap gap-1.5">
{meta.roles.map((r) => (
<label key={r} className={cn("chip cursor-pointer", roles.includes(r) && "border-brand text-brand")}>
<input type="checkbox" className="hidden" disabled={!canEdit} checked={roles.includes(r)}
onChange={(e) => set("approval", { mode: "manual", approver_roles: e.target.checked ? [...roles, r] : roles.filter((x) => x !== r) })} />
{r}
</label>
))}
{!meta.roles.length && <span className="text-label text-muted">还没有业务角色(在「成员与角色」里加),不设则任何审批人可批</span>}
</div>
</Field>
</div>
<ApprovalFields spec={spec} set={set} canEdit={canEdit} meta={meta} params={params} roles={roles} />
<Field label="参数">
<Rows items={params} disabled={!canEdit} onChange={(v) => set("params", v)} addText="加参数"
empty={{ name: "", label: "", type: "string", required: false, enum: [] as string[] }}
......@@ -562,6 +554,85 @@ function ActionFields({ spec, set, canEdit, meta, objects }: {
);
}
const APPROVAL_MODES: [string, string, string][] = [
["manual", "人工审批", "每一单都等审批人批准后才执行"],
["auto", "自动执行", "提议即执行(仍全程审计,可撤销)。适合低风险、高频的动作,如派任务、打标记"],
["conditional", "条件自动", "满足条件就自动执行,否则转人工审批。如「金额 < 5000 且供应商正常」自动下单"],
];
/**
* 审批策略。以前这里只有一排角色勾选,而且勾一下会把整个 approval 覆盖掉 ——
* v7 配好的审批决策表就这样被悄悄抹掉了;动作也只能人工审批,永远不会「自己执行」。
*/
function ApprovalFields({ spec, set, canEdit, meta, params, roles }: {
spec: any; set: (k: string, v: any) => void; canEdit: boolean; meta: KernelMeta; params: any[]; roles: string[];
}) {
const appr = spec.approval || { mode: "manual", approver_roles: [] };
const upd = (patch: any) => set("approval", { ...appr, ...patch });
const mode = appr.mode || "manual";
const dec = appr.decision || null;
const decInputs = useRefOptions(dec?.function ? "vars:table" : undefined, dec?.function || "");
const envHint = ["priority", ...params.map((p: any) => p.name), ...(spec.target_type ? ["obj.属性"] : []), "eff.金额等效果值", "rel.关联对象.属性"];
return (
<div className="space-y-3 rounded-lg border border-line p-3">
<p className="text-label font-medium">审批与执行</p>
<div className="grid gap-2 sm:grid-cols-3">
{APPROVAL_MODES.map(([k, label, desc]) => (
<button key={k} type="button" disabled={!canEdit} onClick={() => upd({ mode: k })}
className={cn("rounded-lg border p-2 text-left transition", mode === k ? "border-brand bg-brand/5" : "border-line hover:border-brand/40")}>
<p className="text-label font-medium">{label}</p>
<p className="mt-0.5 text-caption leading-relaxed text-muted">{desc}</p>
</button>
))}
</div>
{mode === "conditional" && (
<Field label="满足什么条件自动执行" hint={<>可用:{envHint.map((x) => <code key={x} className="mr-1">{x}</code>)};如 <code>priority == 'P3'</code>、<code>eff.amount &lt; 5000</code>。也可以让审批决策表输出一列 <code>auto</code>(是/否)</>}>
<input className="input font-mono text-label" value={appr.auto_when || ""} disabled={!canEdit}
placeholder="priority == 'P3'" onChange={(e) => upd({ auto_when: e.target.value })} />
</Field>
)}
{mode !== "auto" && (
<Field label="审批角色" hint="提议人不能批自己的,AI 也不能批;不设则任何有审批权限的人都可批">
<div className="flex flex-wrap gap-1.5">
{meta.roles.map((r) => (
<label key={r} className={cn("chip cursor-pointer", roles.includes(r) && "border-brand text-brand")}>
<input type="checkbox" className="hidden" disabled={!canEdit} checked={roles.includes(r)}
onChange={(e) => upd({ approver_roles: e.target.checked ? [...roles, r] : roles.filter((x) => x !== r) })} />
{r}
</label>
))}
{roles.filter((r) => !meta.roles.includes(r)).map((r) => (
<label key={r} className="chip cursor-pointer border-warn text-warn" title="这个角色不在「成员与角色」里,可能没人能批">
<input type="checkbox" className="hidden" disabled={!canEdit} checked
onChange={() => upd({ approver_roles: roles.filter((x) => x !== r) })} />
{r}(未建)
</label>
))}
{!meta.roles.length && <span className="text-label text-muted">还没有业务角色(在「成员与角色」里加)</span>}
</div>
</Field>
)}
<Field label="审批决策表(可选)" hint="按「这一单」的实际情况算优先级(P0~P3)、审批人,以及能否自动执行(输出列 priority / approver / auto)">
<RefSelect refKind="decision" value={dec?.function || ""} disabled={!canEdit} allowCustom={false} placeholder="不用决策表"
onChange={(v) => upd({ decision: v ? { function: String(v), inputs: dec?.function === v ? dec.inputs || {} : {} } : undefined })} />
</Field>
{dec?.function && (
<div className="space-y-1">
<p className="text-caption text-muted">决策表的每个输入从哪里取(可写 $参数、$obj.属性,或 = 表达式,如 =eff.amount)</p>
{(decInputs || []).map((o) => (
<div key={String(o.value)} className="flex items-center gap-2">
<span className="w-28 shrink-0 truncate text-label">{o.label}</span>
<input className="input h-8 flex-1 font-mono text-label" disabled={!canEdit} value={dec.inputs?.[String(o.value)] ?? ""}
placeholder="$参数 / $obj.属性 / =eff.amount"
onChange={(e) => upd({ decision: { ...dec, inputs: { ...(dec.inputs || {}), [String(o.value)]: e.target.value } } })} />
</div>
))}
</div>
)}
</div>
);
}
/** 试跑:规则、决策表、周期、动作用当前表单里的定义;聚合与 AI 分析用已保存的工作副本(要查数据/调模型)。 */
export function TryPanel({ concept, kind, spec, name }: { concept?: Concept; kind: string; spec: any; name: string }) {
const cat = spec.category;
......
......@@ -57,7 +57,8 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
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])
// 对象引用可能存 id(编辑器)也可能存名称(业务建模),两种都要认
&& (!obj || c.object_type === obj || c.object_type === objName[obj])
&& (!status || status === "deprecated" || (status === "dirty" ? c.dirty && c.published : c.status === status))
&& (!q || [c.name, c.display_name, c.description, ...c.synonyms].some((s) => s?.includes(q)))),
[mine, cat, domain, mapped, obj, status, q, objName]);
......@@ -242,7 +243,7 @@ function LinkEnds({ c, objName }: { c: ConceptBrief; objName: Record<string, str
}
const EMPTY_ACTION = { target_type: "", params: [{ name: "reason", label: "原因", type: "text", required: true, enum: [] }],
criteria: [], effects: [{ tool: "notify.send", args: { recipient: "role:approver", title: "待处理", body: "$reason" } }],
criteria: [], effects: [{ tool: "task.create", args: { title: "待处理", role: "operator", description: "$reason" } }],
approval: { mode: "manual", approver_roles: [] }, reversible: true };
export function NewBlockModal({ kind, meta, objects, onClose, onCreated, initialCategory }: {
......
/**
* 引用选择器:凡是「填一个本体里的名字」的地方都用它,不再让人对着空白框猜。
*
* 选项来自 /api/cap/ref-options(参数上的 x-ref 决定取什么):已发布的在前,草稿标「草稿」
* (试运行可用、正式运行前要发布),流程里可引用的变量($xxx)单独一组,实在不在列表里的可以「自定义…」手填。
* 选项为空时直接告诉人去哪里建,而不是给一个空下拉。
*/
import { Trash2, X } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { go } from "@/lib/nav";
import { onto, type RefOption } from "@/lib/onto";
import { cn } from "@/lib/utils";
const cache = new Map<string, { at: number; p: Promise<RefOption[]> }>();
const TTL = 20_000;
export function refOptions(ref: string, of = ""): Promise<RefOption[]> {
const k = `${ref}|${of}`;
const hit = cache.get(k);
if (hit && Date.now() - hit.at < TTL) return hit.p;
const p = onto.refOptions(ref, of).catch(() => [] as RefOption[]);
cache.set(k, { at: Date.now(), p });
return p;
}
/** 新建 / 发布了积木之后调用,下拉马上能看到新东西。 */
export function invalidateRefOptions() { cache.clear(); }
export function useRefOptions(ref?: string, of = ""): RefOption[] | null {
const [opts, setOpts] = useState<RefOption[] | null>(null);
useEffect(() => {
if (!ref) { setOpts([]); return; }
let alive = true;
setOpts(null);
void refOptions(ref, of).then((o) => { if (alive) setOpts(o); });
return () => { alive = false; };
}, [ref, of]);
return opts;
}
/** 选项为空时告诉人去哪里建。 */
const EMPTY_HINT: Record<string, [string, string]> = {
metric: ["还没有聚合函数(指标)", "b_function"], rule: ["还没有规则", "b_function"],
decision: ["还没有决策表", "b_function"], calendar: ["还没有统计周期", "b_function"],
function: ["还没有函数", "b_function"], object_type: ["还没有对象类型", "b_object"],
action: ["还没有动作", "b_action"], role: ["还没有业务角色", "members"], user: ["还没有成员", "members"],
recipient: ["还没有成员或角色", "members"], endpoint: ["还没有登记外部端点", "data"],
datasource: ["还没有接入数据源", "data"], sop: ["还没有流程卡", "sop"], concept: ["本体还是空的", "modeling"],
dimension: ["这个指标还没有可拆分的维度(在指标的取数绑定里配)", "b_function"],
filters: ["这个指标还没有可拆分的维度", "b_function"],
property: ["这个对象还没有可写属性(在对象属性里勾「可写」)", "b_object"],
};
const DEP_LABEL: Record<string, string> = { dimension: "指标", filters: "指标", property: "对象类型", values: "对象类型", vars: "函数" };
function isExpr(v: unknown) { return typeof v === "string" && (v.startsWith("$") || v.startsWith("=")); }
export function RefSelect({ refKind, of, value, onChange, disabled, vars = [], placeholder, className, allowCustom = true }: {
refKind: string; of?: string; value: any; onChange: (v: any) => void; disabled?: boolean;
/** 可引用的变量,如 ["$shortage", "$item.仓库"] */
vars?: string[]; placeholder?: string; className?: string; allowCustom?: boolean;
}) {
const base = refKind.split(":")[0];
const needsDep = refKind.includes(":");
const depMissing = needsDep && (!of || String(of).startsWith("$"));
const opts = useRefOptions(depMissing ? undefined : refKind, of || "");
const [custom, setCustom] = useState(false);
const known = useMemo(() => new Set((opts || []).map((o) => String(o.value))), [opts]);
const str = value === undefined || value === null ? "" : String(value);
const showCustom = custom || (str !== "" && opts !== null && !known.has(str) && !vars.includes(str));
if (depMissing) {
return <select className={cn("input h-8", className)} disabled><option>先选上面的{DEP_LABEL[base] || "依赖项"}</option></select>;
}
if (showCustom && allowCustom) {
return (
<div className={cn("flex items-center gap-1", className)}>
<input className={cn("input h-8 flex-1", isExpr(str) && "font-mono text-label")} value={str} disabled={disabled}
placeholder={placeholder || "手填名称,或 $变量"} autoFocus={custom}
onChange={(e) => onChange(e.target.value)} />
{!disabled && (
<button className="btn btn-ghost btn-sm" title="改为从列表选" onClick={() => { setCustom(false); onChange(""); }}>
<X className="h-3.5 w-3.5" />
</button>
)}
</div>
);
}
const published = (opts || []).filter((o) => o.status !== "draft");
const drafts = (opts || []).filter((o) => o.status === "draft");
const groups = new Map<string, RefOption[]>();
for (const o of published) groups.set(o.group || "", [...(groups.get(o.group || "") || []), o]);
const sel = (opts || []).find((o) => String(o.value) === str);
const empty = opts !== null && !opts.length && !vars.length;
const hint = EMPTY_HINT[base];
return (
<div className={cn("min-w-0", className)}>
<select className={cn("input h-8 w-full", sel?.status === "draft" && "border-warn/60")} value={str} disabled={disabled || opts === null}
onChange={(e) => {
if (e.target.value === "__custom__") { setCustom(true); return; }
const o = (opts || []).find((x) => String(x.value) === e.target.value);
onChange(o && typeof o.value === "number" ? o.value : e.target.value);
}}>
<option value="">{opts === null ? "加载中…" : empty ? `(${hint?.[0] || "没有可选项"})` : placeholder || "请选择"}</option>
{[...groups].map(([g, os]) => {
const items = os.map((o) => <option key={String(o.value)} value={String(o.value)} title={o.hint}>{o.label}{o.label !== String(o.value) ? `(${o.value})` : ""}</option>);
return g ? <optgroup key={g} label={g}>{items}</optgroup> : items;
})}
{drafts.length > 0 && (
<optgroup label="草稿(试运行可用,正式运行前要发布)">
{drafts.map((o) => <option key={String(o.value)} value={String(o.value)} title={o.hint}>{o.label} · 草稿</option>)}
</optgroup>
)}
{vars.length > 0 && (
<optgroup label="流程里的变量">
{vars.map((v) => <option key={v} value={v}>{v}</option>)}
</optgroup>
)}
{allowCustom && <option value="__custom__">自定义…</option>}
</select>
{sel?.hint && <p className="mt-0.5 truncate text-caption text-muted" title={sel.hint}>{sel.hint}</p>}
{sel?.status === "draft" && <p className="mt-0.5 text-caption text-warn">草稿:试运行可以用,正式运行前要先发布本体</p>}
{empty && hint && (
<button className="mt-0.5 text-caption text-brand hover:underline" onClick={() => go(hint[1])}>去建一个 →</button>
)}
</div>
);
}
/** 多选(维度、概念列表):已选的显示成小标签,下拉里挑一个就加一个。 */
export function RefMulti({ refKind, of, value, onChange, disabled, vars = [] }: {
refKind: string; of?: string; value: any; onChange: (v: string[]) => void; disabled?: boolean; vars?: string[];
}) {
const list: string[] = Array.isArray(value) ? value.map(String) : value ? [String(value)] : [];
return (
<div className="space-y-1">
{list.length > 0 && (
<div className="flex flex-wrap gap-1">
{list.map((v) => (
<span key={v} className="chip">
{v}
{!disabled && <button aria-label={`移除 ${v}`} onClick={() => onChange(list.filter((x) => x !== v))}><X className="h-3 w-3" /></button>}
</span>
))}
</div>
)}
{!disabled && (
<RefSelect refKind={refKind} of={of} value="" vars={vars} placeholder={list.length ? "再加一个…" : "请选择"}
onChange={(v) => { if (v !== "" && !list.includes(String(v))) onChange([...list, String(v)]); }} />
)}
</div>
);
}
/** 统计时间:本期 / 上期 / 上周 / 近 N 天……存的是系统认得的写法(current / last_week / days:30 / 2026-08)。 */
export function TimeInput({ value, onChange, disabled, vars = [] }: {
value: any; onChange: (v: any) => void; disabled?: boolean; vars?: string[];
}) {
const str = value && typeof value === "object" ? `${value.start || ""}~${value.end || ""}` : String(value ?? "");
const range = typeof value === "object" && value !== null;
const [mode, setMode] = useState<"pick" | "month" | "range">(range ? "range" : /^\d{4}-\d{1,2}$/.test(str) ? "month" : "pick");
return (
<div className="space-y-1">
<div className="flex gap-1">
{([["pick", "常用"], ["month", "指定月"], ["range", "起止日期"]] as const).map(([k, l]) => (
<button key={k} type="button" disabled={disabled}
className={cn("rounded px-1.5 py-0.5 text-caption", mode === k ? "bg-brand/10 text-brand" : "text-muted hover:text-ink")}
onClick={() => { setMode(k); onChange(k === "range" ? { start: "", end: "" } : ""); }}>{l}</button>
))}
</div>
{mode === "pick" && <RefSelect refKind="time" value={range ? "" : value} onChange={onChange} disabled={disabled} vars={vars} placeholder="不限(全部时间)" />}
{mode === "month" && <input type="month" className="input h-8" value={str} disabled={disabled} onChange={(e) => onChange(e.target.value)} />}
{mode === "range" && (
<div className="flex items-center gap-1">
<input type="date" className="input h-8 min-w-0 flex-1" value={range ? value.start || "" : ""} disabled={disabled}
onChange={(e) => onChange({ ...(range ? value : {}), start: e.target.value })} />
<span className="text-caption text-muted">至</span>
<input type="date" className="input h-8 min-w-0 flex-1" value={range ? value.end || "" : ""} disabled={disabled}
onChange={(e) => onChange({ ...(range ? value : {}), end: e.target.value })} />
</div>
)}
</div>
);
}
/**
* 键值编辑器:键从选项里选(指标的维度 / 对象的属性 / 函数的输入),值手填或引用变量。
* 用于「只看哪些(过滤)」「新建对象的属性值」「规则 / 决策表的输入」。
*/
export function KeyValueEditor({ refKind, of, value, onChange, disabled, vars = [], valueHint = "值,或 $变量" }: {
refKind: string; of?: string; value: any; onChange: (v: Record<string, any>) => void; disabled?: boolean;
vars?: string[]; valueHint?: string;
}) {
const obj: Record<string, any> = value && typeof value === "object" && !Array.isArray(value) ? value : {};
const base = refKind.split(":")[0];
const depMissing = refKind.includes(":") && (!of || String(of).startsWith("$"));
const opts = useRefOptions(depMissing ? undefined : refKind, of || "");
const entries = Object.entries(obj);
const set = (k: string, v: any) => { const n = { ...obj }; if (v === "" || v === undefined) delete n[k]; else n[k] = v; onChange(n); };
if (depMissing) return <p className="text-caption text-muted">先选上面的{DEP_LABEL[base] || "依赖项"}</p>;
// 函数输入 / 对象属性:把每个可填项都列出来,一目了然;过滤条件只列已加的
const listAll = base === "vars" || base === "values";
const rows = listAll ? [...(opts || []).map((o) => String(o.value)), ...entries.map(([k]) => k).filter((k) => !(opts || []).some((o) => String(o.value) === k))] : entries.map(([k]) => k);
const unused = (opts || []).filter((o) => !(String(o.value) in obj));
return (
<div className="space-y-1">
{rows.map((k) => {
const o = (opts || []).find((x) => String(x.value) === k);
const v = obj[k];
return (
<div key={k} className="flex items-center gap-1">
<span className="w-28 shrink-0 truncate text-label" title={o?.hint || k}>{o?.label || k}</span>
{o?.enum?.length ? (
<select className="input h-8 min-w-0 flex-1" value={v ?? ""} disabled={disabled} onChange={(e) => set(k, e.target.value)}>
<option value="">(不填)</option>
{o.enum.map((x) => <option key={x}>{x}</option>)}
{vars.map((x) => <option key={x} value={x}>{x}</option>)}
</select>
) : (
<input className={cn("input h-8 min-w-0 flex-1", isExpr(v) && "font-mono text-label")} disabled={disabled}
list={vars.length ? `kv-vars-${base}` : undefined}
value={typeof v === "object" ? JSON.stringify(v) : v ?? ""} placeholder={valueHint}
onChange={(e) => {
const raw = e.target.value;
set(k, raw !== "" && !isExpr(raw) && !Number.isNaN(Number(raw)) && o?.type === "number" ? Number(raw) : raw);
}} />
)}
{!disabled && !listAll && (
<button className="btn btn-ghost btn-sm" aria-label="删除这一条" onClick={() => set(k, undefined)}><Trash2 className="h-3.5 w-3.5" /></button>
)}
</div>
);
})}
{vars.length > 0 && <datalist id={`kv-vars-${base}`}>{vars.map((x) => <option key={x} value={x} />)}</datalist>}
{!listAll && !disabled && unused.length > 0 && (
<select className="input h-8 w-auto text-label" value="" onChange={(e) => e.target.value && set(e.target.value, obj[e.target.value] ?? "")}>
<option value="">+ 加一条</option>
{unused.map((o) => <option key={String(o.value)} value={String(o.value)}>{o.label}</option>)}
</select>
)}
{opts !== null && !opts.length && !entries.length && (
<p className="text-caption text-muted">{EMPTY_HINT[base]?.[0] || "没有可填的项"}</p>
)}
</div>
);
}
/** 把 SOP 变量列表转成 RefSelect 能用的 $引用。 */
export function varRefs(vars: { name: string }[]): string[] {
return vars.map((v) => `$${v.name}`);
}
......@@ -10,6 +10,7 @@ import { confirmDialog, promptText } from "@/lib/dialog";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { TypeBadge } from "./common";
import { invalidateRefOptions } from "./RefSelect";
import { pageOfKind } from "./routes";
import { DiffView, FIELD_LABEL, ImportExport, LinkTester, ProposeModal } from "./tools";
......@@ -40,12 +41,15 @@ export function PublishPage({ me }: { me: Me | null }) {
const pending = (items || []).filter((x) => x.status === "pending");
const history = (items || []).filter((x) => x.status !== "pending");
const submit = async () => {
setBusy("submit");
const isAdmin = !!me?.roles.includes("admin");
const submit = async (now = false) => {
setBusy(now ? "now" : "submit");
try {
await onto.proposeRelease(note);
toast("ok", "已提交变更提案", "请另一位有建设权限的同事审批,通过后发布成新版本");
setNote(""); load();
const r = await onto.proposeRelease(note, now);
if (now && r.published) toast("ok", `已发布第 ${r.published.revision} 版`, "问答、取数、流程卡、动作马上用上新定义");
else if (now && r.cannot_reason) toast("error", "已提交,但你不能直接批", r.cannot_reason);
else toast("ok", "已提交变更提案", "请另一位有建设权限的同事审批,通过后发布成新版本");
setNote(""); load(); invalidateRefOptions();
} catch (e) { toast("error", "提交失败", errText(e)); } finally { setBusy(""); }
};
const decide = async (it: ReleaseItem, approve: boolean) => {
......@@ -116,6 +120,12 @@ export function PublishPage({ me }: { me: Me | null }) {
onClick={() => void submit()}>
{busy === "submit" ? <Spinner className="h-3.5 w-3.5" /> : <Send className="h-3.5 w-3.5" />}提交变更提案
</button>
{isAdmin && (
<button className="btn btn-primary" disabled={!!busy || !total || pending.length > 0}
title="管理员可以直接批准自己的提案(审计里会注明豁免四眼原则)" onClick={() => void submit(true)}>
{busy === "now" ? <Spinner className="h-3.5 w-3.5" /> : <Rocket className="h-3.5 w-3.5" />}立即发布
</button>
)}
</div>
)}
</div>
......
......@@ -5,9 +5,10 @@
* 都拿系统给出的 input_schema 渲染成字段,用户只填值。
*/
import { Plus, Trash2 } from "lucide-react";
import { useState, type ReactNode } from "react";
import { useId, useState, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { KIND_COLOR, TYPE_LABEL, type TypeKey } from "@/lib/onto";
import { KeyValueEditor, RefMulti, RefSelect, TimeInput } from "./RefSelect";
export function TypeBadge({ t, className }: { t: TypeKey | string; className?: string }) {
const color = KIND_COLOR[t] || "#64748b";
......@@ -26,19 +27,47 @@ export function TypeDot({ t }: { t: string }) {
type Schema = { properties?: Record<string, any>; required?: string[] };
/** 按 JSON-Schema 子集生成的表单。字符串值里可以写 `$参数名` 之类的引用,原样保留。 */
export function SchemaForm({ schema, value, onChange, disabled, hints, compact }: {
/** 动作参数定义 → 表单 schema(数字、枚举、必填都带上)。流程卡的动作步骤、监控的「提议动作」共用。 */
export function actionParamSchema(spec: any): Schema {
const props: Record<string, any> = {};
const req: string[] = [];
for (const p of spec?.params || []) {
props[p.name] = { type: p.type === "number" || p.type === "integer" ? "number" : "string",
description: p.label || "", ...(Array.isArray(p.enum) && p.enum.length ? { enum: p.enum } : {}) };
if (p.required) req.push(p.name);
}
return { properties: props, required: req };
}
/** 流程卡参数定义 → 表单 schema。子流程步骤、监控的「启动流程卡」共用。 */
export function sopParamSchema(params: { name: string; label: string; type: string; required: boolean; default?: any }[]): Schema {
return {
properties: Object.fromEntries((params || []).map((p) => [p.name, {
type: p.type === "number" ? "number" : "string", description: p.label || p.name,
...(p.type === "period" ? { "x-ref": "time" } : {}) }])),
required: (params || []).filter((p) => p.required && (p.default ?? "") === "").map((p) => p.name),
};
}
/**
* 按 JSON-Schema 子集生成的表单。字符串值里可以写 `$参数名` 之类的引用,原样保留。
* 参数带 x-ref(引用本体里的指标、对象、角色……)时渲染成下拉选择,不再让人对着空白框猜名字;
* vars 是此处可引用的变量(如流程里上一步的输出),会出现在下拉的「变量」分组里。
*/
export function SchemaForm({ schema, value, onChange, disabled, hints, compact, vars }: {
schema: Schema; value: Record<string, any>; onChange: (v: Record<string, any>) => void;
disabled?: boolean; hints?: Record<string, ReactNode>; compact?: boolean;
disabled?: boolean; hints?: Record<string, ReactNode>; compact?: boolean; vars?: string[];
}) {
const props = Object.entries(schema?.properties || {});
const req = new Set(schema?.required || []);
const listId = useId();
const set = (k: string, v: any) => {
const next = { ...value };
if (v === "" || v === undefined) delete next[k]; else next[k] = v;
onChange(next);
};
if (!props.length) return <p className="text-label text-muted">不需要参数</p>;
// 普通输入框也能下拉选变量($item.仓库、$value……),不用记变量名
return (
<div className={cn("grid gap-2", compact ? "sm:grid-cols-2" : "sm:grid-cols-2 lg:grid-cols-3")}>
{props.map(([k, p]) => {
......@@ -53,7 +82,26 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact }
</span>
);
let input: ReactNode;
if (p.enum) {
const xref: string = p["x-ref"] || "";
const [xbase, xdep] = xref.split(":");
const of = xdep ? String(value?.[xdep] ?? "") : undefined;
if (xref && xbase === "time") {
input = <TimeInput value={v} onChange={(x) => set(k, x)} disabled={disabled} vars={vars} />;
} else if (xref && (xbase === "filters" || xbase === "vars" || xbase === "values")) {
input = <KeyValueEditor refKind={xref} of={of} value={v} onChange={(x) => set(k, Object.keys(x).length ? x : undefined)}
disabled={disabled} vars={vars} />;
} else if (xref && t === "array") {
input = <RefMulti refKind={xref} of={of} value={v} onChange={(x) => set(k, x.length ? x : undefined)} disabled={disabled} vars={vars} />;
} else if (xref) {
input = <RefSelect refKind={xref} of={of} value={v} disabled={disabled} vars={vars}
onChange={(x) => {
// 换了指标 / 对象类型,依赖它的参数(维度、过滤、属性)就作废了
const next = { ...value };
if (x === "" || x === undefined) delete next[k]; else next[k] = x;
for (const [dk, dp] of props) if (String(dp["x-ref"] || "").endsWith(`:${k}`)) delete next[dk];
onChange(next);
}} />;
} else if (p.enum) {
input = (
<select className="input h-8" value={v ?? ""} disabled={disabled} onChange={(e) => set(k, e.target.value)}>
<option value="">(不填)</option>
......@@ -71,8 +119,8 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact }
input = <JsonBox key={k} value={v ?? (t === "array" ? [] : {})} disabled={disabled} onChange={(x) => set(k, x)} small />;
} else {
input = (
<input className="input h-8 font-mono text-label" value={v ?? ""} disabled={disabled}
placeholder={t === "integer" || t === "number" ? "数字,或 $参数" : "值,或 $参数 / $obj.属性"}
<input className="input h-8 font-mono text-label" value={v ?? ""} disabled={disabled} list={vars?.length ? listId : undefined}
placeholder={vars?.length ? `值,或选 ${vars[0]} 等变量` : t === "integer" || t === "number" ? "数字,或 $参数" : "值,或 $参数 / $obj.属性"}
onChange={(e) => {
const raw = e.target.value;
if ((t === "integer" || t === "number") && raw !== "" && !raw.startsWith("$") && !Number.isNaN(Number(raw))) set(k, Number(raw));
......@@ -88,6 +136,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact }
</div>
);
})}
{vars && vars.length > 0 && <datalist id={listId}>{vars.map((x) => <option key={x} value={x} />)}</datalist>}
</div>
);
}
......
......@@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Badge, Card, CardHeader, Empty, Field, Modal, Segmented, Spinner } from "@/components/ui";
import { go, useHashParams } from "@/lib/nav";
import {
errText, fmtTime, onto, PRIORITY_TONE, STATUS_LABEL, STATUS_TONE, type ConceptBrief, type Me, type SopBrief, type SopDef, type SopIssue, type SopRun,
errText, fmtTime, onto, PRIORITY_TONE, STATUS_LABEL, STATUS_TONE, type ConceptBrief, type DraftRef, type Me, type Recipe, type SopBrief, type SopDef, type SopIssue, type SopRun,
type SopSpec, type SopStep, type WatchDef,
} from "@/lib/onto";
import { cn } from "@/lib/utils";
......@@ -14,6 +14,7 @@ import { toast } from "@/store/useAppStore";
import { SopCanvas } from "./SopCanvas";
import { addStep, autoLayout, STEP_COLOR, STEP_LABEL, type StepType } from "./specOps";
import { StepInspector, type Catalog } from "./StepInspector";
import { SchemaForm } from "../ontology/common";
/**
* SOP:本体里「流程」的可执行定义。同一份定义三种用法 —— 人按它做(人工任务)、
......@@ -28,6 +29,7 @@ export function SopPage({ me }: { me: Me | null }) {
const [runId, setRunId] = useState(params.get("run") || "");
const [cat, setCat] = useState<Catalog | null>(null);
const [draftOpen, setDraftOpen] = useState(!!params.get("draft"));
const [recipeOpen, setRecipeOpen] = useState(false);
const [q, setQ] = useState("");
const [only, setOnly] = useState<"" | "published" | "draft" | "archived">("");
const shown = list.filter((s) => (!q || `${s.title} ${s.description} ${s.domain || ""}`.includes(q))
......@@ -51,13 +53,18 @@ export function SopPage({ me }: { me: Me | null }) {
const id = params.get("id"), run = params.get("run"), q = params.get("q");
if (id) { setSel(id); setRunId(""); }
if (run) setRunId(run);
if (q && list.length) { const f = list.find((s) => s.title.includes(q) || q.includes(s.title)); if (f) setSel(f.id); }
// 从提问跳过来:按名字找到流程卡,并带上 AI 建议的参数直接打开运行框(以前参数在跳转时丢了)
if (q && list.length) {
const f = list.find((s) => s.title.includes(q) || q.includes(s.title));
if (f) go("sop", { id: f.id, run_params: params.get("params") || "{}" });
}
}, [params, list]);
return (
<div className="grid h-full min-h-0 gap-4 overflow-auto lg:grid-cols-[260px_minmax(0,1fr)] lg:overflow-hidden">
<Card className="flex max-h-[calc(100vh-140px)] flex-col self-start">
<CardHeader title="流程库" right={canEdit && <>
<button className="btn btn-sm btn-primary" onClick={() => setRecipeOpen(true)} title="选一个常见场景,挑几样本体里的东西,直接生成能跑的流程"><Sparkles 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 () => {
const title = await promptText("流程名称"); if (!title) return;
......@@ -89,7 +96,7 @@ export function SopPage({ me }: { me: Me | null }) {
<span key={i} className="rounded bg-ink/[0.05] px-1 text-caption text-muted">{STEP_LABEL[t] || t}</span>))}
{s.domain && <span className="ml-1 text-caption text-brand">#{s.domain}</span>}</p>
)}
<p className="text-caption text-muted">{s.step_count} 步 · {s.trigger_kind === "manual" ? "手动" : s.trigger_kind === "schedule" ? "定时" : "指标触发"} · 运行 {s.run_count || 0} 次</p>
<p className="text-caption text-muted">{s.step_count} 步 · 运行 {s.run_count || 0} 次</p>
</button>
))}
</div>
......@@ -97,10 +104,13 @@ export function SopPage({ me }: { me: Me | null }) {
<div className="min-h-0 min-w-0 lg:overflow-auto">
{runId ? <RunView runId={runId} onBack={() => { setRunId(""); if (sel) go("sop", { id: sel }); }} />
: sel && cat ? <SopEditor key={sel} id={sel} cat={cat} canEdit={canEdit} me={me} onChanged={load} />
: sel && cat ? <SopEditor key={sel} id={sel} cat={cat} canEdit={canEdit} me={me} onChanged={load}
initialRun={params.get("run_params")} />
: <Card><Empty icon={<GitBranch className="h-10 w-10" />} title="选择一个流程"
desc="流程卡在画布上拖拽编排:取数、判断、派给人的任务、需要审批的动作、对每一行逐个处理。也可以让 AI 按手册起草。" /></Card>}
</div>
{recipeOpen && <RecipeModal onClose={() => setRecipeOpen(false)}
onDone={(id) => { setRecipeOpen(false); load(); go("sop", { id }); }} />}
{draftOpen && <DraftModal initial={params.get("draft") || ""} canEdit={canEdit}
onClose={() => { setDraftOpen(false); if (params.get("draft")) go("sop"); }}
onDone={(id) => { setDraftOpen(false); load(); go("sop", { id }); }} />}
......@@ -108,6 +118,50 @@ export function SopPage({ me }: { me: Me | null }) {
);
}
/** 从场景新建:选一个常见的业务闭环,挑几样本体里已有的东西,直接生成一张能试运行的流程卡。 */
function RecipeModal({ onClose, onDone }: { onClose: () => void; onDone: (id: string) => void }) {
const [recipes, setRecipes] = useState<Recipe[]>([]);
const [rid, setRid] = useState("");
const [fields, setFields] = useState<Record<string, any>>({});
const [title, setTitle] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => { void onto.sopRecipes().then((r) => { setRecipes(r); setRid(r[0]?.id || ""); }).catch(() => setRecipes([])); }, []);
const r = recipes.find((x) => x.id === rid);
const missing = (r?.fields || []).filter((f) => f.required && (fields[f.name] === undefined || fields[f.name] === "" ||
(Array.isArray(fields[f.name]) && !fields[f.name].length)));
const schema = r ? {
properties: Object.fromEntries(r.fields.map((f) => [f.name, {
type: f.multi ? "array" : f.type === "number" ? "number" : "string", description: f.label,
...(f.ref ? { "x-ref": f.ref } : {}) }])),
required: r.fields.filter((f) => f.required).map((f) => f.name),
} : { properties: {} };
return (
<Modal open onClose={onClose} width="max-w-2xl" title="从场景新建流程"
desc="选一个常见的业务闭环,再挑几样本体里已有的东西(指标、动作、角色……),系统直接生成流程卡:取数用确定性的指标,不经过大模型。生成后仍可在画布里修改。"
footer={<><button className="btn" onClick={onClose}>取消</button>
<button className="btn btn-primary" disabled={busy || !r || missing.length > 0}
title={missing.length ? `还没选:${missing.map((f) => f.label).join("、")}` : ""} onClick={async () => {
setBusy(true);
try { const d = await onto.createSopFromRecipe(rid, fields, title.trim()); toast("ok", "流程卡已生成", "先试运行看看效果"); onDone(d.id); }
catch (e) { toast("error", "生成失败", errText(e)); } finally { setBusy(false); }
}}>{busy && <Spinner className="h-3.5 w-3.5" />}生成流程卡</button></>}>
<div className="space-y-3">
<div className="grid gap-2 sm:grid-cols-3">
{recipes.map((x) => (
<button key={x.id} onClick={() => { setRid(x.id); setFields({}); }}
className={cn("rounded-lg border p-2.5 text-left transition", rid === x.id ? "border-brand bg-brand/5" : "border-line hover:border-brand/40")}>
<p className="text-label font-medium">{x.title}</p>
<p className="mt-1 text-caption leading-relaxed text-muted">{x.desc}</p>
</button>
))}
</div>
{r && <SchemaForm schema={schema} value={fields} onChange={setFields} />}
<Field label="流程名称" hint="不填就按选的内容自动起名"><input className="input" value={title} onChange={(e) => setTitle(e.target.value)} /></Field>
</div>
</Modal>
);
}
function DraftModal({ initial, canEdit, onClose, onDone }: { initial: string; canEdit: boolean; onClose: () => void; onDone: (id: string) => void }) {
const [topic, setTopic] = useState(initial);
const [busy, setBusy] = useState(false);
......@@ -136,11 +190,13 @@ function SaveState({ dirty, busy, saved }: { dirty: boolean; busy: boolean; save
return null;
}
function SopEditor({ id, cat, canEdit, me, onChanged }: { id: string; cat: Catalog; canEdit: boolean; me: Me | null; onChanged: () => void }) {
function SopEditor({ id, cat, canEdit, me, onChanged, initialRun }: {
id: string; cat: Catalog; canEdit: boolean; me: Me | null; onChanged: () => void; initialRun?: string | null;
}) {
const [d, setD] = useState<SopDef | null>(null);
const [spec, setSpec] = useState<SopSpec | null>(null);
const [meta, setMeta] = useState({ title: "", description: "", owner_role: "" });
const [val, setVal] = useState<{ errors: string[]; warnings: string[]; issues?: SopIssue[] }>({ errors: [], warnings: [] });
const [val, setVal] = useState<{ errors: string[]; warnings: string[]; issues?: SopIssue[]; draft_refs?: DraftRef[] }>({ errors: [], warnings: [] });
const hp = useHashParams();
const [tab, setTab] = useState<"flow" | "form" | "setup" | "runs">(hp.get("tab") === "trigger" ? "setup" : "flow");
const [past, setPast] = useState<SopSpec[]>([]);
......@@ -150,6 +206,13 @@ function SopEditor({ id, cat, canEdit, me, onChanged }: { id: string; cat: Catal
const [saved, setSaved] = useState(0);
const [busy, setBusy] = useState(false);
const [runModal, setRunModal] = useState<"" | "dry" | "live">("");
const [runPreset, setRunPreset] = useState<Record<string, any>>({});
// 带着参数进来(提问里的「运行这个流程」):已发布就开正式运行框,没发布就开试运行框,参数预先填好
useEffect(() => {
if (!initialRun || !d) return;
try { setRunPreset(JSON.parse(initialRun) || {}); } catch { setRunPreset({}); }
setRunModal(d.current_version > 0 ? "live" : "dry");
}, [initialRun, d?.id]); // eslint-disable-line react-hooks/exhaustive-deps
const [dryRun, setDryRun] = useState<SopRun | null>(null);
const [selStep, setSelStep] = useState("");
const names = useMemo(() => Object.fromEntries([
......@@ -173,7 +236,7 @@ function SopEditor({ id, cat, canEdit, me, onChanged }: { id: string; cat: Catal
if (!spec || !dirty) return;
const h = window.setTimeout(() => {
const my = ++valSeq.current; // 只认最后一次校验的结果,慢的旧请求回来不能覆盖新的
void onto.validateSop(spec).then((r) => { if (my === valSeq.current) setVal({ errors: r.errors, warnings: r.warnings, issues: r.issues }); })
void onto.validateSop(spec).then((r) => { if (my === valSeq.current) setVal({ errors: r.errors, warnings: r.warnings, issues: r.issues, draft_refs: r.draft_refs }); })
.catch(() => undefined);
}, 400);
return () => window.clearTimeout(h);
......@@ -274,6 +337,15 @@ function SopEditor({ id, cat, canEdit, me, onChanged }: { id: string; cat: Catal
{val.warnings.length > 0 && <span className="flex items-center gap-1 text-warn"><AlertTriangle className="h-3.5 w-3.5" />{val.warnings.length} 个提醒</span>}
<span className={d.dry_run_ok ? "text-ok" : "text-muted"}>试运行:{d.dry_run_ok ? `通过(${fmtTime(d.last_dry_run.at)})` : d.last_dry_run?.at ? "当前草稿未通过或已修改" : "未进行"}</span>
</div>
{(val.draft_refs || []).length > 0 && (
<div className="flex flex-wrap items-center gap-2 border-t border-line bg-warn/5 px-4 py-2 text-label">
<AlertTriangle className="h-3.5 w-3.5 text-warn" />
<span>引用了 {val.draft_refs!.length} 个还没发布的积木:
{val.draft_refs!.slice(0, 5).map((r) => <b key={`${r.kind}:${r.name}`} className="mx-0.5">「{r.name}」</b>)}
—— 试运行可以用,正式运行和提交发布前要先发布本体。</span>
<button className="btn btn-sm ml-auto" onClick={() => go("publish")}><Rocket className="h-3.5 w-3.5" />去发布本体</button>
</div>
)}
{(val.errors.length > 0 || val.warnings.length > 0) && (
<ul className="space-y-0.5 border-t border-line px-4 py-2 text-label">
{(val.issues && val.issues.length
......@@ -282,7 +354,7 @@ function SopEditor({ id, cat, canEdit, me, onChanged }: { id: string; cat: Catal
{val.issues && val.issues.some((i) => i.level === "error" && i.step_id) && (
<li className="text-muted">• 另有 {val.issues.filter((i) => i.level === "error" && i.step_id).length} 个错误已经标在对应步骤上(图里标红的那些)</li>
)}
{val.warnings.map((e) => <li key={e} className="text-warn">• {e}</li>)}
{val.warnings.filter((e) => !e.startsWith("引用了还没发布的积木")).map((e) => <li key={e} className="text-warn">• {e}</li>)}
</ul>
)}
</Card>
......@@ -344,8 +416,8 @@ function SopEditor({ id, cat, canEdit, me, onChanged }: { id: string; cat: Catal
onSpec={upd} onMeta={(m) => { setMeta(m); setDirty(true); }} defId={id} published={d.current_version > 0} />}
{tab === "runs" && <RunsTab defId={id} />}
{runModal && <RunParamsModal spec={runModal === "live" ? null : spec} defId={id} mode={runModal}
onClose={() => setRunModal("")}
{runModal && <RunParamsModal spec={runModal === "live" ? null : spec} defId={id} mode={runModal} preset={runPreset}
onClose={() => { setRunModal(""); setRunPreset({}); }}
onDone={(r) => {
setRunModal("");
if (runModal === "dry") { setDryRun(r); void load(); onChanged(); }
......@@ -379,8 +451,6 @@ function SetupTab({ spec, meta, canEdit, cat, onSpec, onMeta, defId, published }
}) {
const [types, setTypes] = useState<ConceptBrief[]>([]);
const [cals, setCals] = useState<ConceptBrief[]>([]);
const [metrics, setMetrics] = useState<ConceptBrief[]>([]);
const [scan, setScan] = useState<any>(null);
// 这张卡被哪些监控器驱动 —— 「什么时候跑」已经搬到监控与定时,这里只做展示与跳转
const [watches, setWatches] = useState<WatchDef[]>([]);
useEffect(() => {
......@@ -389,13 +459,8 @@ function SetupTab({ spec, meta, canEdit, cat, onSpec, onMeta, defId, published }
}, [defId]);
useEffect(() => {
void onto.concepts({ kind: "object_type" }).then(setTypes);
void onto.concepts({ kind: "function" }).then((fs) => {
setCals(fs.filter((f) => f.category === "calendar"));
setMetrics(fs.filter((f) => f.category === "aggregate"));
});
void onto.concepts({ kind: "function" }).then((fs) => setCals(fs.filter((f) => f.category === "calendar")));
}, []);
const trig = spec.trigger || { kind: "manual" };
const setTrig = (t: any) => onSpec({ ...spec, trigger: t });
return (
<div className="space-y-3">
<Card className="grid gap-3 p-4 sm:grid-cols-3">
......@@ -462,9 +527,12 @@ function SetupTab({ spec, meta, canEdit, cat, onSpec, onMeta, defId, published }
);
}
function RunParamsModal({ spec, defId, mode, onClose, onDone }: { spec: SopSpec | null; defId: string; mode: "dry" | "live"; onClose: () => void; onDone: (r: SopRun) => void }) {
function RunParamsModal({ spec, defId, mode, preset, onClose, onDone }: {
spec: SopSpec | null; defId: string; mode: "dry" | "live"; preset?: Record<string, any>;
onClose: () => void; onDone: (r: SopRun) => void;
}) {
const [s, setS] = useState<SopSpec | null>(spec);
const [vals, setVals] = useState<Record<string, any>>({});
const [vals, setVals] = useState<Record<string, any>>(preset || {});
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!spec) void onto.sop(defId).then(async (d) => setS((await onto.sopVersion(defId, d.current_version)).spec));
......
......@@ -3,14 +3,15 @@
* 参数按函数 / 动作的定义生成表单,不用手写 JSON;能引用的变量列在下面,点一下就复制。
*/
import { Copy, Play, Plus, Trash2 } from "lucide-react";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { Field, Spinner } from "@/components/ui";
import { errText, onto, type CapDef, type FunctionBrief, type SopSpec, type SopStep } from "@/lib/onto";
import { errText, onto, type CapDef, type FunctionBrief, type SopDef, type SopSpec, type SopStep } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { ResultView, SchemaForm } from "../ontology/common";
import { actionParamSchema, ResultView, SchemaForm, sopParamSchema } from "../ontology/common";
import { RefSelect, useRefOptions } from "../ontology/RefSelect";
import {
changeType, deleteStep, renameStep, STEP_COLOR, STEP_HINT, STEP_LABEL, updateStep, upstreamVars, type StepType,
changeType, deleteStep, renameStep, STEP_COLOR, STEP_HINT, STEP_LABEL, updateStep, upstreamVars, varPaths, type StepType,
} from "./specOps";
export interface Catalog {
......@@ -20,18 +21,6 @@ export interface Catalog {
type Schema = { properties: Record<string, any>; required: string[] };
/** 动作参数定义 → 表单 schema(数字、枚举、必填都带上)。 */
function actionSchema(a?: CapDef): Schema {
const props: Record<string, any> = {};
const req: string[] = [];
for (const p of a?.spec?.params || []) {
props[p.name] = { type: p.type === "number" || p.type === "integer" ? "number" : "string",
description: p.label || "", ...(Array.isArray(p.enum) && p.enum.length ? { enum: p.enum } : {}) };
if (p.required) req.push(p.name);
}
return { properties: props, required: req };
}
function skillSchema(s?: CapDef): Schema {
const props: Record<string, any> = {};
for (const i of s?.spec?.inputs || []) props[i.name] = { type: "string", description: i.label || i.description || "" };
......@@ -39,19 +28,29 @@ function skillSchema(s?: CapDef): Schema {
}
const FN_GROUP: Record<string, string> = {
metric: "取数", data: "取数", knowledge: "知识", object: "对象", rule: "规则与计算", sop: "流程", ontology: "本体",
data: "通用 · 取数", knowledge: "通用 · 知识", logic: "通用 · 规则与计算", process: "通用 · 流程",
};
/**
* 「我的」积木:直接列本体里的指标、规则、决策表、统计周期,选中即映射成对应内置函数的调用
* (选「库存缺口」= 指标取数,metric=库存缺口)。以前只能先选「指标取数」,再对着一个空白框猜指标名。
*/
const MINE: [ref: string, label: string][] = [
["metric", "我的指标"], ["rule", "我的规则"], ["decision", "我的决策表"], ["calendar", "我的统计周期"],
];
/**
* 把 $变量 插到用户最后点过的那个输入框里。
* React 受控组件直接改 value 不会触发 onChange,所以用原生 setter + input 事件。
*/
function insertVar(text: string) {
function insertVar(raw: string) {
const el = lastFocused;
if (!el || !document.contains(el)) {
void navigator.clipboard?.writeText(text).then(() => toast("ok", `已复制 ${text}`)).catch(() => undefined);
void navigator.clipboard?.writeText(raw).then(() => toast("ok", `已复制 ${raw}`)).catch(() => undefined);
return;
}
// 判断条件里变量不带 $(写 shortage.value > 0);插进条件框时自动去掉,免得条件解析报错
const text = el.dataset.bare ? raw.replace(/^\$/, "") : raw;
const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
const start = el.selectionStart ?? el.value.length;
......@@ -128,14 +127,21 @@ export function StepInspector({ spec, id, cat, disabled, defId, onChange, onSele
}) {
const step = spec.steps.find((s) => s.id === id);
const vars = useMemo(() => (step ? upstreamVars(spec, step.id) : []), [spec, step]);
const paths = useMemo(() => varPaths(vars), [vars]);
const fnGroups = useMemo(() => {
const g = new Map<string, FunctionBrief[]>();
for (const f of cat.functions) {
const k = FN_GROUP[f.category] || FN_GROUP[f.name.split(".")[0]] || "其他";
const k = FN_GROUP[f.category] || "通用 · 其他";
g.set(k, [...(g.get(k) || []), f]);
}
return [...g];
}, [cat.functions]);
const mine = [useRefOptions("metric"), useRefOptions("rule"), useRefOptions("decision"), useRefOptions("calendar")];
const [child, setChild] = useState<SopDef | null>(null);
useEffect(() => {
if (step?.type !== "subprocess" || !step.sop) { setChild(null); return; }
void onto.sop(step.sop).then(setChild).catch(() => setChild(null));
}, [step?.type, step?.sop]);
if (!step) return null;
const set = (patch: Partial<SopStep>) => onChange(updateStep(spec, step.id, patch));
const others = spec.steps.filter((s) => s.id !== step.id);
......@@ -174,22 +180,41 @@ export function StepInspector({ spec, id, cat, disabled, defId, onChange, onSele
<Field label="步骤名称"><input className="input h-8" value={step.title} disabled={disabled} onChange={(e) => set({ title: e.target.value })} /></Field>
{/* ------ 按类型 ------ */}
{step.type === "function" && (
<>
<Field label="调用哪个函数">
<select className="input h-8" value={step.function || ""} disabled={disabled}
onChange={(e) => set({ function: e.target.value, args: {} })}>
<option value="">请选择</option>
{fnGroups.map(([g, fs]) => (
<optgroup key={g} label={g}>{fs.map((f) => <option key={f.name} value={f.name}>{f.title}</option>)}</optgroup>
))}
</select>
</Field>
{fn && <p className="-mt-1 text-label text-muted">{fn.description}</p>}
{fn && <SchemaForm schema={fn.input_schema || {}} value={step.args || {}} disabled={disabled} compact
onChange={(v) => set({ args: v })} />}
</>
)}
{step.type === "function" && (() => {
// 当前步骤如果是「内置函数 + 身份参数」(如 metric.query + metric=库存缺口),在下拉里回显成「我的指标 · 库存缺口」
const bound = fn?.binds && MINE.some(([r]) => r === fn.binds!.ref) && step.args?.[fn.binds.param]
? `my:${fn.binds.ref}:${step.args[fn.binds.param]}` : step.function || "";
return (
<>
<Field label="取什么数 / 算什么" hint="上面几组是你在本体里建的;「通用」是系统自带的函数">
<select className="input h-8" value={bound} disabled={disabled}
onChange={(e) => {
const v = e.target.value;
if (v.startsWith("my:")) {
const [, ref, ...rest] = v.split(":");
const target = cat.functions.find((f) => f.binds?.ref === ref);
if (target?.binds) set({ function: target.name, args: { [target.binds.param]: rest.join(":") } });
} else set({ function: v, args: {} });
}}>
<option value="">请选择</option>
{MINE.map(([ref, label], i) => (mine[i] || []).length > 0 && (
<optgroup key={ref} label={label}>
{(mine[i] || []).map((o) => <option key={String(o.value)} value={`my:${ref}:${o.value}`} title={o.hint}>
{o.label}{o.status === "draft" ? " · 草稿" : ""}</option>)}
</optgroup>
))}
{fnGroups.map(([g, fs]) => (
<optgroup key={g} label={g}>{fs.map((f) => <option key={f.name} value={f.name}>{f.title}</option>)}</optgroup>
))}
</select>
</Field>
{fn && <p className="-mt-1 text-label text-muted">{fn.title}:{fn.description}</p>}
{fn && <SchemaForm schema={fn.input_schema || {}} value={step.args || {}} disabled={disabled} compact vars={paths}
onChange={(v) => set({ args: v })} />}
{fn?.output && <p className="text-caption text-muted">结果里有:{fn.output}</p>}
</>
);
})()}
{step.type === "skill" && (
<>
......@@ -199,7 +224,8 @@ export function StepInspector({ spec, id, cat, disabled, defId, onChange, onSele
{cat.skills.map((s) => <option key={s.id} value={s.name}>{s.display_name || s.name}{s.status !== "published" ? "(未发布)" : ""}</option>)}
</select>
</Field>
{skill && <SchemaForm schema={skillSchema(skill)} value={step.inputs || {}} disabled={disabled} compact onChange={(v) => set({ inputs: v })} />}
{skill && <SchemaForm schema={skillSchema(skill)} value={step.inputs || {}} disabled={disabled} compact vars={paths}
onChange={(v) => set({ inputs: v })} />}
</>
)}
......@@ -217,7 +243,7 @@ export function StepInspector({ spec, id, cat, disabled, defId, onChange, onSele
onClick={() => set({ branches: step.branches!.filter((_, j) => j !== i) })}><Trash2 className="h-3.5 w-3.5" /></button>
)}
</div>
<input className="input h-8 font-mono text-label" value={b.when} disabled={disabled}
<input className="input h-8 font-mono text-label" value={b.when} disabled={disabled} data-bare="1"
placeholder={vars[0] ? `例如 ${vars[vars.length - 1].name}.value < 0.8` : "例如 rate.value < 0.8"}
onChange={(e) => { const bs = [...step.branches!]; bs[i] = { ...b, when: e.target.value }; set({ branches: bs }); }} />
{target(b.next, (v) => { const bs = [...step.branches!]; bs[i] = { ...b, next: v }; set({ branches: bs }); }, "满足时去")}
......@@ -232,10 +258,9 @@ export function StepInspector({ spec, id, cat, disabled, defId, onChange, onSele
{step.type === "human_task" && (
<>
<Field label="谁来做">
<input className="input h-8" list="sop-role-list" value={step.role || ""} disabled={disabled} placeholder="业务角色,如 采购员"
onChange={(e) => set({ role: e.target.value, lane: e.target.value })} />
<datalist id="sop-role-list">{cat.roles.map((r) => <option key={r.id} value={r.name} />)}</datalist>
<Field label="谁来做" hint="派给这个角色的所有人,谁先认领谁处理">
<RefSelect refKind="role" value={step.role || ""} disabled={disabled}
onChange={(v) => set({ role: String(v || ""), lane: String(v || "") })} />
</Field>
<Field label="要做什么" hint="可以引用变量,如 $store.名称"><textarea className="input min-h-[60px]" value={step.instructions || ""} disabled={disabled}
onChange={(e) => set({ instructions: e.target.value })} /></Field>
......@@ -285,12 +310,22 @@ export function StepInspector({ spec, id, cat, disabled, defId, onChange, onSele
</select>
</Field>
{act && act.spec?.target_type && (
<Field label="作用于哪个对象" hint={step.type === "foreach" ? "一般写 $item.编号(当前行的主键列)" : "一般写 $参数.key 或上一步结果里的主键"}>
<input className="input h-8 font-mono text-label" value={step.object_key || ""} disabled={disabled}
placeholder={step.type === "foreach" ? "$item.编号" : "$store.key"} onChange={(e) => set({ object_key: e.target.value })} />
<Field label="作用于哪个对象"
hint={step.type === "foreach" ? "选当前行里是这个对象主键的那一列" : "选流程参数或上一步结果里的主键"}>
<RefSelect refKind="" value={step.object_key || ""} disabled={disabled}
vars={step.type === "foreach" ? paths.filter((p) => p.startsWith("$item.")) : paths}
placeholder="请选择" onChange={(v) => set({ object_key: String(v || "") })} />
</Field>
)}
{act && <SchemaForm schema={actionParamSchema(act.spec)} value={step.params || {}} disabled={disabled} compact vars={paths}
onChange={(v) => set({ params: v })} />}
{act?.status === "draft" && <p className="text-caption text-warn">这个动作还是草稿:试运行可以预览,正式运行前要先发布本体。</p>}
{step.type === "foreach" && (
<Field label="只处理满足条件的行(可选)" hint="条件里直接写列名,如 value > 0、仓库 == 'W01';不写就每一行都处理">
<input className="input h-8 font-mono text-label" value={step.when || ""} disabled={disabled} data-bare="1"
placeholder="value > 0" onChange={(e) => set({ when: e.target.value })} />
</Field>
)}
{act && <SchemaForm schema={actionSchema(act)} value={step.params || {}} disabled={disabled} compact onChange={(v) => set({ params: v })} />}
{step.type === "foreach" && (
<Field label="最多处理几行" hint="防止一次提交太多审批单,上限 50">
<input className="input h-8 w-24" type="number" min={1} max={50} value={step.limit || 20} disabled={disabled}
......@@ -310,6 +345,12 @@ export function StepInspector({ spec, id, cat, disabled, defId, onChange, onSele
</select>
</Field>
)}
{step.type === "subprocess" && child && (child.spec.params || []).length > 0 && (
<Field label={`传给「${child.title}」的参数`} hint="子流程的必填参数不给,正式运行时会失败">
<SchemaForm compact disabled={disabled} vars={paths} value={step.params || {}} onChange={(v) => set({ params: v })}
schema={sopParamSchema(child.spec.params)} />
</Field>
)}
{step.type === "end" && (
<Field label="结果说明" hint="运行结束时显示给发起人">
......@@ -339,11 +380,16 @@ export function StepInspector({ spec, id, cat, disabled, defId, onChange, onSele
<p className="mb-1 text-caption text-muted">这一步能用的变量(点一下插入到上面正在编辑的框里)</p>
<div className="flex flex-wrap gap-1">
{vars.map((v) => (
<button key={v.name} className="chip text-caption" title={`来自 ${v.from}`}
onClick={() => insertVar(`$${v.name}`)}>
<Copy className="h-3 w-3" />${v.name}
<span className="ml-0.5 text-muted">{v.from}</span>
</button>
<span key={v.name} className="inline-flex flex-wrap items-center gap-0.5">
<button className="chip text-caption" title={`来自 ${v.from}`} onClick={() => insertVar(`$${v.name}`)}>
<Copy className="h-3 w-3" />${v.name}
<span className="ml-0.5 text-muted">{v.from}</span>
</button>
{(v.fields || []).map((f) => (
<button key={f} className="rounded px-1 text-caption text-brand hover:bg-brand/10" title={`$${v.name}.${f}`}
onClick={() => insertVar(`$${v.name}.${f}`)}>.{f}</button>
))}
</span>
))}
</div>
</div>
......
......@@ -157,24 +157,65 @@ export function disconnect(spec: SopSpec, source: string, handle: string): SopSp
}
/** 「逐行处理」「动作」等步骤里能引用的变量:参数 + 所有上游步骤的输出。 */
export function upstreamVars(spec: SopSpec, id: string): { name: string; from: string }[] {
/** 一个步骤的输出里有哪些字段可以引用($变量.字段)。以前只告诉人有个 $shortage,至于该写 .value 还是 .rows 全靠猜。 */
export function outputFields(st: SopStep): string[] {
if (st.type === "function") {
const f = st.function || "";
if (f === "metric.query") return ["value", "rows", "summary"];
if (f === "data.ask") return ["value", "rows", "summary"];
if (f === "decision.eval") return ["result", "matched"];
if (f === "rule.eval" || f === "function.eval") return ["result"];
if (f === "object.get") return ["key", "label", "properties"];
if (f === "object.search") return ["items"];
return ["summary"];
}
if (st.type === "human_task") return (st.form || []).map((x) => x.name).filter(Boolean);
if (st.type === "action") return ["status", "result"];
if (st.type === "foreach") return ["total", "ok"];
if (st.type === "skill") return ["summary"];
return [];
}
/** 逐行处理时 $item 有哪些列:数据来自「指标取数」且按维度拆分时,列就是各维度 + value。 */
export function itemColumns(spec: SopSpec, st: SopStep): string[] {
const src = String(st.items || "").replace(/^\$/, "").split(".")[0];
const from = spec.steps.find((s) => s.output === src);
if (from?.type === "function" && from.function === "metric.query") {
const dims = Array.isArray(from.args?.dimensions) ? from.args!.dimensions.map(String) : [];
return [...dims, "value"];
}
return [];
}
export function upstreamVars(spec: SopSpec, id: string): { name: string; from: string; fields?: string[] }[] {
const byId = new Map(spec.steps.map((s) => [s.id, s]));
const preds = new Map<string, string[]>();
for (const s of spec.steps) for (const e of successors(s)) preds.set(e.to, [...(preds.get(e.to) || []), s.id]);
const seen = new Set<string>();
const stack = [...(preds.get(id) || [])];
const out: { name: string; from: string }[] = spec.params.map((p) => ({ name: p.name, from: `参数:${p.label || p.name}` }));
const out: { name: string; from: string; fields?: string[] }[] = spec.params.map((p) => ({
name: p.name, from: `参数:${p.label || p.name}`, fields: p.type === "object" ? ["key", "label"] : undefined }));
while (stack.length) {
const cur = stack.pop()!;
if (seen.has(cur)) continue;
seen.add(cur);
const st = byId.get(cur);
if (st?.output) out.push({ name: st.output, from: `步骤:${st.title}` });
if (st?.output) out.push({ name: st.output, from: `步骤:${st.title}`, fields: outputFields(st) });
stack.push(...(preds.get(cur) || []));
}
const self = byId.get(id);
if (self?.type === "foreach") {
const cols = itemColumns(spec, self);
out.push({ name: "item", from: "当前行", fields: cols.length ? cols : undefined });
}
return out;
}
/** 变量 + 字段展开成可直接引用的写法:$shortage、$shortage.value、$item.仓库…… */
export function varPaths(vars: { name: string; fields?: string[] }[]): string[] {
return vars.flatMap((v) => [`$${v.name}`, ...(v.fields || []).map((f) => `$${v.name}.${f}`)]);
}
/**
* 自动布局:按从开始步骤的最长路径分层,同层按上层父节点的平均位置排序(减少交叉),
* 从不到的步骤排在最右边一列。不引第三方布局库,二三十个步骤足够用。
......
......@@ -7,11 +7,13 @@ import { confirmDialog } from "@/lib/dialog";
import { go, useHashParams } from "@/lib/nav";
import {
errText, fmtTime, onto,
type ConceptBrief, type Me, type SopBrief, type WatchDef, type WatchMeta, type WatchRunRec,
type CapDef, type ConceptBrief, type Me, type SopBrief, type SopDef, type WatchDef, type WatchMeta, type WatchRunRec,
type WatchScanResult,
} from "@/lib/onto";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { actionParamSchema, SchemaForm, sopParamSchema } from "../ontology/common";
import { RefMulti, RefSelect } from "../ontology/RefSelect";
const BLANK = {
title: "", description: "", enabled: true, owner_role: "",
......@@ -140,18 +142,16 @@ function WatchEditor({ id, meta, canEdit, onClose, onSaved }: {
const [busy, setBusy] = useState("");
const [scan, setScan] = useState<WatchScanResult | null>(null);
const [preview, setPreview] = useState<{ ok: boolean; error?: string; text: string; next: string[] } | null>(null);
const [metrics, setMetrics] = useState<ConceptBrief[]>([]);
const [objects, setObjects] = useState<ConceptBrief[]>([]);
const [actions, setActions] = useState<ConceptBrief[]>([]);
const [actions, setActions] = useState<CapDef[]>([]);
const [sops, setSops] = useState<SopBrief[]>([]);
const [runs, setRuns] = useState<WatchRunRec[] | null>(null);
useEffect(() => {
if (id) void onto.watch(id).then(setD).catch((e) => toast("error", errText(e)));
void onto.concepts({ kind: "function", status: "published" })
.then((xs) => setMetrics(xs.filter((x) => x.category === "aggregate"))).catch(() => undefined);
void onto.concepts({ kind: "object_type", status: "published" }).then(setObjects).catch(() => undefined);
void onto.concepts({ kind: "action", status: "published" }).then(setActions).catch(() => undefined);
// 动作带上 spec:命中后提议动作时,参数按动作的定义生成表单(以前是一个手写 JSON 的输入框,还打不进字)
void onto.capDefs("action", true).then(setActions).catch(() => undefined);
void onto.sops({ status: "published" }).then(setSops).catch(() => undefined);
}, [id]);
......@@ -214,16 +214,12 @@ function WatchEditor({ id, meta, canEdit, onClose, onSaved }: {
{d.source.kind === "metric" && (
<div className="grid gap-2 sm:grid-cols-2">
<Field label="指标" required>
<select className="input" value={d.source.metric} disabled={!canEdit}
onChange={(e) => setSource({ metric: e.target.value })}>
<option value="">选择</option>
{metrics.map((m) => <option key={m.id} value={m.name}>{m.name}</option>)}
</select>
<RefSelect refKind="metric" value={d.source.metric} disabled={!canEdit} allowCustom={false}
onChange={(v) => setSource({ metric: String(v || ""), dimensions: [] })} />
</Field>
<Field label="按哪个维度逐个判" hint="留空就只看总值;填了就按维度拆开,每个值单独判">
<input className="input" value={(d.source.dimensions || []).join("、")} disabled={!canEdit}
placeholder="如 仓库、商品"
onChange={(e) => setSource({ dimensions: e.target.value.split(/[,,、]/).map((x) => x.trim()).filter(Boolean) })} />
<Field label="按哪个维度逐个判" hint="不选就只看总值;选了就按维度拆开,每一行单独判">
<RefMulti refKind="dimension:metric" of={d.source.metric} value={d.source.dimensions || []} disabled={!canEdit}
onChange={(v) => setSource({ dimensions: v })} />
</Field>
</div>
)}
......@@ -302,7 +298,11 @@ function WatchEditor({ id, meta, canEdit, onClose, onSaved }: {
<Step n={3} title="命中了做什么" desc="可以配多条,按顺序执行。审批单的优先级由本体里的审批决策表算。">
<StrategyList value={d.strategies} onChange={(v) => set("strategies", v)} canEdit={canEdit}
meta={meta} actions={actions} sops={sops} />
meta={meta} actions={actions} sops={sops}
rowVars={d.source.kind === "metric"
? ["$key", "$value", ...(d.source.dimensions || []).map((x: string) => `$${x}`)]
: d.source.kind === "object" ? ["$key", "$label", ...Object.keys(scan?.hits?.[0] || {})
.filter((k) => !["key", "label", "value"].includes(k)).map((k) => `$${k}`)] : []} />
<div className="mt-3 flex flex-wrap items-end gap-2">
<Field label="去重键" hint="同一个键在冷却期内只触发一次;可写 $字段">
<input className="input w-40 font-mono" value={d.dedup.key} disabled={!canEdit}
......@@ -361,11 +361,21 @@ function Step({ n, title, desc, children }: { n: number; title: string; desc: st
);
}
function StrategyList({ value, onChange, canEdit, meta, actions, sops }: {
function StrategyList({ value, onChange, canEdit, meta, actions, sops, rowVars }: {
value: any[]; onChange: (v: any[]) => void; canEdit: boolean; meta: WatchMeta;
actions: ConceptBrief[]; sops: SopBrief[];
actions: CapDef[]; sops: SopBrief[];
/** 命中的每一行里可以引用的字段:$key、$value、各维度 / 属性 */
rowVars: string[];
}) {
const up = (i: number, patch: any) => onChange(value.map((s, j) => (j === i ? { ...s, ...patch } : s)));
const [sopDefs, setSopDefs] = useState<Record<string, SopDef>>({});
useEffect(() => {
for (const s of value) {
if (s.kind === "run_sop" && s.sop && !sopDefs[s.sop]) {
void onto.sop(s.sop).then((x) => setSopDefs((m) => ({ ...m, [s.sop]: x }))).catch(() => undefined);
}
}
}, [value]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className="space-y-2">
{value.map((s, i) => (
......@@ -379,7 +389,7 @@ function StrategyList({ value, onChange, canEdit, meta, actions, sops }: {
<select className="input h-8 w-44" value={s.action || ""} disabled={!canEdit}
onChange={(e) => up(i, { action: e.target.value })}>
<option value="">选动作</option>
{actions.map((a) => <option key={a.id} value={a.name}>{a.display_name || a.name}</option>)}
{actions.map((a) => <option key={a.id} value={a.name}>{a.display_name || a.name}{a.status !== "published" ? "(草稿)" : ""}</option>)}
</select>
)}
{s.kind === "run_sop" && (
......@@ -391,8 +401,8 @@ function StrategyList({ value, onChange, canEdit, meta, actions, sops }: {
)}
{s.kind === "notify" && (
<>
<input className="input h-8 w-32" placeholder="给哪个角色" value={s.role || ""} disabled={!canEdit}
onChange={(e) => up(i, { role: e.target.value })} />
<RefSelect refKind="role" className="w-40" value={s.role || ""} disabled={!canEdit} placeholder="派给哪个角色"
onChange={(v) => up(i, { role: String(v || "") })} />
<input className="input h-8 min-w-[10rem] flex-1" placeholder="待办标题" value={s.title || ""}
disabled={!canEdit} onChange={(e) => up(i, { title: e.target.value })} />
</>
......@@ -401,21 +411,35 @@ function StrategyList({ value, onChange, canEdit, meta, actions, sops }: {
onClick={() => onChange(value.filter((_, j) => j !== i))}>
<Trash2 className="h-3.5 w-3.5" /></button>}
</div>
{(s.kind === "propose_action" || s.kind === "run_sop") && (
<input className="input mt-2 h-8 font-mono text-label" disabled={!canEdit}
placeholder='参数,如 {"qty": "$缺口", "warehouse_id": "$仓库"}'
value={JSON.stringify(s.params || {})}
onChange={(e) => { try { up(i, { params: JSON.parse(e.target.value) }); } catch { /* 还没输完 */ } }} />
)}
{s.kind === "propose_action" && (
<p className="mt-1 text-caption text-muted">
对象主键用 <code>$key</code>;优先级和审批人由动作上配的审批决策表按这一单的实际情况算。
</p>
{s.kind === "propose_action" && (() => {
const a = actions.find((x) => x.name === s.action);
if (!a) return null;
return (
<div className="mt-2 space-y-2">
{a.spec?.target_type && (
<Field label="作用于哪个对象(命中行里的哪一列是它的主键)" hint="不选就按动作的对象类型,从维度里自动挑对应的那一列">
<RefSelect refKind="" value={s.object_key || ""} disabled={!canEdit} vars={rowVars} placeholder="自动"
onChange={(v) => up(i, { object_key: String(v || "") })} />
</Field>
)}
<SchemaForm compact disabled={!canEdit} schema={actionParamSchema(a.spec)} value={s.params || {}} vars={rowVars}
onChange={(v) => up(i, { params: v })} />
<p className="text-caption text-muted">
审批方式按动作上配的策略:人工审批 / 自动执行 / 条件自动;优先级和审批人由审批决策表按这一单的实际情况算。
</p>
</div>
);
})()}
{s.kind === "run_sop" && sopDefs[s.sop] && (sopDefs[s.sop].spec.params || []).length > 0 && (
<div className="mt-2">
<SchemaForm compact disabled={!canEdit} schema={sopParamSchema(sopDefs[s.sop].spec.params)} value={s.params || {}}
vars={rowVars} onChange={(v) => up(i, { params: v })} />
</div>
)}
</div>
))}
{canEdit && (
<button className="btn btn-sm" onClick={() => onChange([...value, { kind: "propose_action", params: {}, object_key: "$key" }])}>
<button className="btn btn-sm" onClick={() => onChange([...value, { kind: "propose_action", params: {}, object_key: "" }])}>
<Plus className="h-3.5 w-3.5" />加一条策略
</button>
)}
......
......@@ -103,7 +103,14 @@ export interface LinkResult {
}
export interface ObjectRec { type_id: string; type_name: string; key: string; label: string; properties: Record<string, any>; overridden?: string[] }
export interface FunctionBrief { kind: "function"; name: string; title: string; description: string; input_schema: any; category: string; output: string }
/** binds:函数的「身份参数」(如指标取数的 metric),SOP 编辑器据此把「我的指标 / 规则」映射成对内置函数的调用 */
export interface FunctionBrief { kind: "function"; name: string; title: string; description: string; input_schema: any; category: string; output: string;
binds?: { param: string; ref: string } | null }
/** 参数下拉的一个选项(x-ref)。status=draft 表示引用的是还没发布的积木 */
export interface RefOption { value: string | number; label: string; id?: string; status?: "published" | "draft"; group?: string; hint?: string; type?: string; enum?: string[] }
export interface Recipe { id: string; title: string; desc: string;
fields: { name: string; label: string; ref?: string; required?: boolean; multi?: boolean; type?: string; default?: any }[] }
export interface DraftRef { step_id: string; kind: string; name: string }
export interface ToolBrief { kind: "tool"; name: string; title: string; description: string; input_schema: any; risk_level: string; reversible: boolean; external: boolean }
export interface CapDef {
id: string; kind: "skill" | "action" | "endpoint"; kind_label: string; name: string;
......@@ -111,13 +118,15 @@ export interface CapDef {
version: number; risk_level: string; updated_at: string;
}
export interface ActionPreview {
action: { id: string; name: string; display_name: string; version: number; reversible: boolean; risk_level: string; approver_roles: string[] };
action: { id: string; name: string; display_name: string; version: number; reversible: boolean; risk_level: string; approver_roles: string[]; priority?: string };
/** 审批策略算出来的结果:这一单会不会自动执行、为什么 */
auto?: { mode: string; eligible: boolean; why: string };
params: Record<string, any>; target_ref: string; summary: string;
effects: { tool: string; label: string; args: any; preview: { summary: string; changes?: any[]; external?: boolean }; risk_level: string; external: boolean }[];
}
export interface ActionRun {
id: string; action_id: string; action_name: string; kind: "normal" | "revert"; revert_of: string;
params: Record<string, any>; target_ref: string; initiator_kind: "user" | "ai" | "sop";
params: Record<string, any>; target_ref: string; initiator_kind: "user" | "ai" | "sop" | "watch";
initiator_id: string; submitted_by: string; source_ref: string; reason: string;
status: string; preview: ActionPreview; result: any; error: string;
created_at: string; decided_at: string | null; finished_at: string | null;
......@@ -221,6 +230,8 @@ export interface SopStep {
sop?: string; outcome?: string;
/** 逐行处理:按哪份数据逐行($变量),每行最多处理几条 */
items?: string; limit?: number;
/** 逐行处理:只处理满足条件的行,如 value > 0 */
when?: string;
}
export interface SopParam { name: string; label: string; type: string; object_type: string; calendar: string; required: boolean; default?: any }
/** 结构化校验结果:带 step_id,前端据此把错误标到对应节点上 */
......@@ -235,11 +246,11 @@ export interface SopSpec {
export interface SopBrief {
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; dry_run_ok: boolean; ai_generated: boolean;
run_count?: number; updated_at: string; owner_role: string; process_concept_id: string;
}
export interface SopDef extends SopBrief {
spec: SopSpec; validation: { errors: string[]; warnings: string[] }; draft_hash: string;
spec: SopSpec; validation: { errors: string[]; warnings: string[]; issues?: SopIssue[]; draft_refs?: DraftRef[] }; draft_hash: string;
last_dry_run: any; versions: { id: string; version: number; note: string; published_by: string; created_at: string }[];
}
export interface SopStepRun {
......@@ -258,6 +269,9 @@ export interface AskCard {
action: string; action_id?: string; display_name: string; params: Record<string, any>;
object_key: string; reason: string; preview?: ActionPreview; error?: string;
param_defs?: { name: string; label: string; type: string; required: boolean; enum: string[] }[]; target_type?: string;
/** "sop" = 建议发起的流程卡(动作引用写作 sop:<流程卡 id>),其余为普通动作 */
kind?: string; sop?: string; sop_id?: string; description?: string;
steps?: { id: string; title: string; type: string; type_label: string; lane?: string }[];
}
export interface DataRef {
run_id: number; sql: string; columns: string[]; rows: any[][]; metric?: any; period?: any;
......@@ -269,7 +283,7 @@ export interface Turn {
/** running / done / aborted(用户停止、切换对话、断线)/ error */
status: string;
links: LinkResult; plan: any; steps: any[]; answer: string; citations: Citation[];
data_refs: DataRef[]; actions: AskCard[]; sops: any[]; rating: number; feedback: string;
data_refs: DataRef[]; actions: AskCard[]; sops: AskCard[]; rating: number; feedback: string;
duration_ms: number; created_at: string; stats?: Record<string, number>; has_trace?: boolean;
}
export interface AskMeta {
......@@ -423,7 +437,8 @@ export const onto = {
deleteBinding: (bid: string) => req<{ ok: boolean }>(`/api/kernel/bindings/${enc(bid)}`, del),
pendingDiff: () => req<Diff>("/api/kernel/diff"),
/** 提交变更提案(别人审批通过后才发布) */
proposeRelease: (note: string) => req<ReviewItem>("/api/kernel/publish", post({ note })),
proposeRelease: (note: string, approve_now = false) =>
req<ReviewItem & { published?: any; cannot_reason?: string }>("/api/kernel/publish", post({ note, approve_now })),
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 })),
......@@ -502,7 +517,8 @@ export const onto = {
catalog: () => req<{ functions: FunctionBrief[]; tools: ToolBrief[]; defs: CapDef[] }>("/api/cap/catalog")
.then((c) => withArrays(c, ["functions", "tools", "defs"])),
callFunction: (name: string, args: any) => req<any>(`/api/cap/functions/${enc(name)}/call`, post({ args })),
capDefs: (kind = "") => req<CapDef[]>(`/api/cap/defs${qs({ kind })}`),
refOptions: (ref: string, of = "") => req<RefOption[]>(`/api/cap/ref-options${qs({ ref, of })}`).then((r) => _arr<RefOption>(r)),
capDefs: (kind = "", working = false) => req<CapDef[]>(`/api/cap/defs${qs({ kind, working: working || undefined })}`),
saveCapDef: (body: any, id?: string) => id
? req<CapDef>(`/api/cap/defs/${enc(id)}`, put(body)) : req<CapDef>("/api/cap/defs", post(body)),
setCapStatus: (id: string, status: string) => req<CapDef>(`/api/cap/defs/${enc(id)}/status`, post({ status })),
......@@ -519,6 +535,7 @@ export const onto = {
decideAction: (id: string, approve: boolean, comment = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/decide`, post({ approve, comment })),
cancelAction: (id: string, reason = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/cancel`, post({ reason })),
revertAction: (id: string, reason = "") => req<ActionRun>(`/api/cap/runs/${enc(id)}/revert`, post({ reason })),
retryAction: (id: string) => req<ActionRun>(`/api/cap/runs/${enc(id)}/retry`, post()),
approvals: () => req<ActionRun[]>("/api/cap/approvals"),
tasks: (p: Record<string, unknown> = {}) => req<TaskRec[]>(`/api/cap/tasks${qs(p)}`)
.then((ts) => _arr<TaskRec>(ts).map((t) => withArrays(t, ["checklist", "form"]))),
......@@ -555,7 +572,10 @@ export const onto = {
archiveSop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}/archive`, post()),
unarchiveSop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}/unarchive`, post()),
sopReferencedBy: (id: string) => req<{ id: string; title: string; step: string }[]>(`/api/sop/defs/${enc(id)}/referenced-by`),
validateSop: (spec: any) => req<{ spec: SopSpec; errors: string[]; warnings: string[]; issues?: SopIssue[] }>("/api/sop/validate", post({ spec })),
validateSop: (spec: any) => req<{ spec: SopSpec; errors: string[]; warnings: string[]; issues?: SopIssue[]; draft_refs?: DraftRef[] }>("/api/sop/validate", post({ spec })),
sopRecipes: () => req<Recipe[]>("/api/sop/recipes"),
createSopFromRecipe: (id: string, fields: Record<string, any>, title = "") =>
req<SopDef>(`/api/sop/recipes/${enc(id)}`, post({ fields, title })),
trySopStep: (id: string, stepId: string, env: Record<string, unknown> = {}) => req<{
step_id: string; type: string; title: string; ok: boolean; output?: any; note?: string;
var?: string; error?: string; ms: number }>(`/api/sop/defs/${enc(id)}/steps/${enc(stepId)}/try`, post({ env })),
......@@ -563,7 +583,6 @@ export const onto = {
submitSop: (id: string, note: string) => req<ReviewItem>(`/api/sop/defs/${enc(id)}/submit`, post({ note })),
runSop: (id: string, params: any, mode = "live") => req<SopRun>(`/api/sop/defs/${enc(id)}/run`, post({ params, mode })),
sopVersion: (id: string, v: number) => req<{ spec: SopSpec; version: number }>(`/api/sop/defs/${enc(id)}/versions/${v}`),
triggerScan: (id: string, dry = true) => req<any>(`/api/sop/defs/${enc(id)}/trigger-scan`, post({ dry })),
sopRuns: (p: Record<string, unknown> = {}) => req<SopRun[]>(`/api/sop/runs${qs(p)}`),
sopRun: (id: string) => req<SopRun>(`/api/sop/runs/${enc(id)}`),
cancelSopRun: (id: string, reason = "") => req<SopRun>(`/api/sop/runs/${enc(id)}/cancel`, post({ reason })),
......@@ -619,7 +638,7 @@ export const STATUS_LABEL: Record<string, string> = {
rejected: "已驳回", cancelled: "已撤回", reverted: "已撤销", pending: "待处理",
accepted: "已采纳", open: "待办", running: "运行中", waiting: "等待中", paused: "已暂停",
waiting_human: "等人工", waiting_approval: "等审批", waiting_child: "等子流程",
suggested: "建议", skipped: "跳过", archived: "已归档",
suggested: "建议", skipped: "跳过", archived: "已归档", auto: "自动执行",
};
export const STATUS_TONE: Record<string, string> = {
......
{"root":["./src/app.tsx","./src/main.tsx","./src/__tests__/asktrace.test.ts","./src/__tests__/specops.test.ts","./src/components/ui.tsx","./src/features/ask/actioncard.tsx","./src/features/ask/agenttrace.tsx","./src/features/ask/askanswer.tsx","./src/features/ask/askpage.tsx","./src/features/ask/trace.ts","./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/mcp/mcppage.tsx","./src/features/members/memberspage.tsx","./src/features/memory/memorypage.tsx","./src/features/monitor/monitorpage.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/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/sopcanvas.tsx","./src/features/sop/soppage.tsx","./src/features/sop/stepinspector.tsx","./src/features/sop/specops.ts","./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/watch/watchpage.tsx","./src/features/workbench/deskpage.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"],"version":"5.9.3"}
\ No newline at end of file
{"root":["./src/app.tsx","./src/main.tsx","./src/__tests__/asktrace.test.ts","./src/__tests__/specops.test.ts","./src/components/ui.tsx","./src/features/ask/actioncard.tsx","./src/features/ask/agenttrace.tsx","./src/features/ask/askanswer.tsx","./src/features/ask/askpage.tsx","./src/features/ask/trace.ts","./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/mcp/mcppage.tsx","./src/features/members/memberspage.tsx","./src/features/memory/memorypage.tsx","./src/features/monitor/monitorpage.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/modelingpage.tsx","./src/features/ontology/refselect.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/sopcanvas.tsx","./src/features/sop/soppage.tsx","./src/features/sop/stepinspector.tsx","./src/features/sop/specops.ts","./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/watch/watchpage.tsx","./src/features/workbench/deskpage.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"],"version":"5.9.3"}
\ No newline at end of file
# 问界 · 鸿蒙门店运营数据分析平台 产品需求文档(PRD)
| 项 | 内容 |
| --- | --- |
| 文档版本 | V1.0 |
| 文档类型 | 反向推导需求文档(基于现有系统已实现能力梳理) |
| 适用业务 | 问界(AITO)门店运营 + 鸿蒙智行门店运营 |
| 使用方 | 主机厂区域运营、飞行督导、线上运营、渠道运营管理人员、数据分析人员 |
| 编写日期 | 2026-09-11 |
> 说明:本文档以业务语言描述系统应当具备的能力、规则与产出,用于需求评审、交付验收与后续迭代立项。文档不涉及任何实现细节。
---
## 一、产品概述
### 1.1 业务背景
门店(4S 店 / 用户中心)的售后增值业务(整车延保、安心包、电池延保、轮胎险、无忧套餐等)是主机厂与经销商共同关注的利润来源。为拉动这类业务的成交率,主机厂会与门店签署**兜底协议**:
> 约定门店在某个周期内某项业务的转化率(渗透率)必须达标;若未达标,门店按约定的单价与阶梯标准"补齐差额",即由门店向主机厂赔付差额部分的金额。
这套规则在实际运作中带来三个突出的管理难题:
1. **数据来源分散**:门店兜底协议条款是线下 Excel 台账,主机厂交付/采购数据来自主机厂系统导出,而成交订单、产值、触客数据在生产业务系统里。三方数据口径、名称、粒度都不一致,逐月人工拼表极易出错。
2. **规则复杂且口径多变**:不同品牌(问界 / 鸿蒙智行)、不同子品牌(智界 / 享界 / 尊界 / 尚界)、不同门店的达标阈值、赔付单价、阶梯档位各不相同;还区分"交付口径"与"触客口径"两种分母;集团型门店(如华奥集团)需要按集团汇总产值但按单店保留基础信息。
3. **策略效果无法追踪**:区域运营会针对落后门店下发改善策略(带教、促销、人员更换评估等),但"策略下发前后指标到底有没有变好"缺乏客观、可复算的评估手段,也缺少统一的效果标签与督办看板。
本产品即为解决上述问题而建设:**把门店兜底核算从"人工拼表"升级为"自动取数 + 规则计算 + 一键出报表",把策略效果从"凭感觉"升级为"前后周期对比 + 自动效果判定 + 大模型总结"。**
### 1.2 产品定位
面向问界与鸿蒙智行渠道体系的一站式**运营数据分析平台**,核心提供四类能力:
| 能力域 | 一句话定位 |
| --- | --- |
| 数据底座 | 自动、定时地把生产业务数据汇集为可分析的门店运营数据资产 |
| 兜底核算 | 按门店协议自动核算生态系数、转化率达标情况与赔付金额,产出可直接对外使用的报表 |
| 策略盯防 | 对下发给门店的运营策略做执行前后效果评估,输出效果标签与结论 |
| 数据接入 | 对格式不固定的外部 Excel 明细,用大模型识别结构后自动入库,降低接入成本 |
### 1.3 产品目标
1. **核算效率**:门店兜底核算从"人工拼表(天级)"降到"上传文件后分钟级出报表"。
2. **核算准确性**:所有指标由统一口径自动计算,消除人工公式错误与口径不一致。
3. **责任可追溯**:每个周期、每个门店的达标情况、赔付金额、评定等级均可复算、可回溯。
4. **管理闭环**:策略下发 → 效果盯防 → 自动刷新 → 异常预警,形成管理闭环。
### 1.4 目标用户与角色
| 角色 | 关注点 | 典型操作 |
| --- | --- | --- |
| 区域运营负责人 | 本区域门店达标情况、赔付总额、落后门店 | 查看/导出分析报表,查看策略盯防列表 |
| 飞行督导 | 所辖门店的执行改善进展 | 查看策略详情、渗透率分析 |
| 线上运营 | 线上渠道触客与转化指标 | 查看门店指标与趋势 |
| 数据分析/运营支持岗 | 数据口径、数据完整性、报表产出 | 上传协议与主机厂数据、保存历史批次、生成报表 |
| 系统管理员 | 账号、任务运行、异常处理 | 账号维护、查看任务执行历史、处理失败任务 |
系统当前为**统一权限模型**:所有登录用户可见全部业务功能,未做按角色的数据行级隔离(后续迭代建议见第十一章)。
### 1.5 业务术语表
| 术语 | 业务含义 |
| --- | --- |
| 兜底协议 | 门店与主机厂签署的达标承诺,约定达标口径、达标阈值、未达标赔付单价 |
| 兜底指标 | 协议约定的考核口径,主要两类:**交付口径**(以主机厂交付数为分母)、**触客口径**(以门店触客数为分母) |
| 兜底类型 | 交付 / 触客,决定所有转化率与差额计算的分母 |
| 达标转化率 | 协议要求达到的最低转化率,可配置多级阶梯(如 11% 与 15% 两档) |
| 单均赔付金额 | 每缺 1 单需赔付的金额,与达标转化率阶梯一一对应 |
| 兜底截止日期 | 协议考核周期的截止日;截止日含"25 日"的门店归入**生态月**口径,其余归入**自然月**口径 |
| 自然月 | 每月 1 日至月末 |
| 生态月 | 以每月 20 日(业务实操为 26 日)为起点的滚动考核周期,截止日为次月 25 日 |
| 主机厂数据 | 主机厂系统导出的门店交付量、各产品采购量、单车产值 |
| 产值表 / 产值数据 | 生产业务系统内的订单成交明细汇总,含成交数、成交金额 |
| 产值 | 子订单成交金额扣除退款后的净额 |
| 渗透率 | 某产品成交订单数 ÷ 分母(主机厂交付数或触客数),用于衡量该产品在成交/触客中的覆盖比例 |
| 生态系数 | 针对整车延保、安心包、电池延保三项渗透率的分档评分(0~1.3 分/项) |
| 需达标订单数差额 | 为达到协议阈值,门店还差多少个成交订单 |
| 赔付金额 | 订单数差额 × 对应档位赔付单价 |
| 策略 | 区域运营针对门店下发的运营改善动作(学习、带教、促销、人员评估等) |
| 盯防 | 对策略执行过程与效果进行持续跟踪 |
| 盯防周期 T | 策略执行期;T-1 为等长前置对照期;T+1 为等长后置观察期 |
| 批次 | 一次成功导入的数据集合,带品牌、数据类型、数据周期,可被反复复用 |
---
## 二、业务全景
### 2.1 业务对象与关系
```
主机厂体系(品牌:问界 / 鸿蒙智行)
│ 下发
▼
┌───────────────────────┐
│ 门店兜底协议(协议台账) │ 达标口径 / 阈值 / 赔付单价 / 周期
└───────────┬───────────┘
│ 关联
▼
门店(4S 店 / 用户中心)───── 交付 · 触客 · 成交 ────► 生产业务系统
│ │ │ │
│ │ └── 收据:直营/服务商、区域运营、飞行督导、线上运营
│ └───── 下发给门店的运营策略 ──► 策略效果盯防
└──────── 从主机厂系统获得交付量 / 采购量 / 单车产值
```
三类数据源:
1. **门店侧**:门店主数据、门店兜底协议条款、门店运营策略。
2. **主机厂侧**:门店交付量、各产品采购量、单车产值。
3. **业务系统侧**:门店订单成交明细、门店与员工日报(交付、触客、成交)、产值。
平台把三者按**门店**为主键进行关联核算,产出报表与盯防结论。
### 2.2 品牌体系
| 层级 | 取值 | 说明 |
| --- | --- | --- |
| 一级品牌 | 鸿蒙智行 | 集团级品牌,全部新能源门店的归属 |
| 二级品牌 | 问界 | 参与"生态系数 + 兜底赔付"完整核算 |
| 二级品牌 | 智界、享界、尊界、尚界 | 统称"四界",参与鸿蒙生态与子品牌核算 |
品牌与门店的对应关系决定了取数范围:核算问界时只取二级品牌为问界的门店数据;核算鸿蒙时取四界数据;子品牌分析则在四界基础上再按单品牌拆分。
### 2.3 周期口径(关键业务约定)
周期口径是本产品最容易出错的业务概念,必须严格遵循:
| 周期类型 | 定义 | 判断规则 |
| --- | --- | --- |
| 自然月 | 每月 1 日 ~ 月末 | 周期起始日 **< 20 日** |
| 生态月 | 以每月 20 日(实操为 26 日)为起点、截止次月 25 日的滚动周期 | 周期起始日 **≥ 20 日** |
两类判断入口必须一致:
- **按门店判断**:门店兜底截止日期包含"25 日" → 该门店按**生态月**核算;否则按**自然月**核算。
- **按主机厂数据判断**:主机厂数据的工作表名或数据周期起始日 ≥ 20 日 → 该数据为生态月数据;否则为自然月数据;若一份文件同时包含两类,则标记为"生态 + 自然"混合。
一份分析任务中,**生态月门店使用生态月的主机厂数据,自然月门店使用自然月的主机厂数据**,两者可同时出现在同一张报表的不同区块。
盯防场景另有独立的三段周期口径:
| 阶段 | 定义 |
| --- | --- |
| T-1(前置对照期) | 长度与策略执行期相同、紧邻执行期之前的一段 |
| T(执行期) | 策略的生效起止日期 |
| T+1(后置观察期) | 长度与执行期相同、紧接执行期之后的一段,截止到今天为止(未过完则按已发生天数计算) |
### 2.4 端到端业务流程总览
```
① 数据底座(自动)
生产业务系统 ──定时同步──► 贴源数据 ──定时加工──► 门店/员工宽表 ──► 指标层 ──► 应用模型
② 兜底核算(人工触发 + 自动取数)
下载模板 → 填写门店协议 / 主机厂数据 → 上传(可保存为历史批次)
→ 系统自动从数据底座取产值与触客成交数据 → 合并计算系数/转化率/差额/赔付
→ 生成 Excel 报表 → 下载交付
③ 策略盯防(自动 + 人工触发)
策略录入(业务系统) → 定时批量评估 → 效果标签 + 结论
→ 盯防列表/详情/渗透率分析 → 超时未刷新自动刷新 → 异常预警
④ 数据接入(人工触发)
任意结构 Excel → 大模型识别结构与类型 → 自动建表入库 → 数据目录可查
```
### 2.5 功能地图
| 一级功能 | 二级功能 |
| --- | --- |
| 登录与账号安全 | 账号密码登录、图形验证码、失败锁定、记住登录状态、退出登录 |
| 数据同步任务 | 查看任务配置、手动触发同步、查看执行历史、查看执行明细 |
| 数仓加工任务 | 选择加工层级、增量/全量/日期范围、查看执行历史与明细 |
| 数据接入 | 固定结构表导入、任意结构智能导入、上传记录追溯 |
| 问界生态系数分析 | 协议文件上传/选批次、主机厂数据上传/选批次、数据预览、生成报表、下载报表、保存批次 |
| 鸿蒙生态分析 | 同上(产值自动取数,无需上传产值表) |
| 鸿蒙子品牌分析 | 协议选择、子品牌主机厂数据上传/选批次、预览(含品牌筛选与汇总)、生成报表、下载 |
| 策略效果盯防 | 统计看板、多维筛选、盯防列表、策略详情、渗透率分析、单条刷新分析、批量分析、盯防状态概览 |
| 批次管理 | 批次列表、按品牌/类型/周期筛选、批次数据复用 |
| 系统保障 | 定时调度、并发保护、超时保护、僵尸任务清理、日志留存 |
---
## 三、功能需求
### 3.1 登录与账号安全
#### FR-AUTH-01 账号登录
- 用户以"账号 + 密码"登录;账号格式为 **7~14 位字母或数字**;密码长度为 **9~19 位**,且必须同时包含小写字母、大写字母、数字、特殊符号四类字符。
- 登录成功后建立会话,会话默认有效 **30 分钟**;若勾选"记住登录状态"(默认勾选),会话有效 **7 天**。
- 登录成功自动进入首页;已登录用户访问登录页应直接跳转首页。
#### FR-AUTH-02 图形验证码(按账号风险触发)
- 验证码**不是固定必填**,而是按账号的登录风险动态触发。
- 触发条件:该账号历史累计失败次数达到 **2 次**,则下次登录必须输入验证码。
- 验证码规格:**4 位**字符,字符集剔除易混淆字符(不含 0、1、I、O 等);有效期 **5 分钟**;**一次性使用**,校验后立即失效,防止重放。
- 交互:账号输入框失焦即向服务端询问"该账号是否需要验证码";需要时才显示验证码区域并加载图片;点击验证码图片可刷新。
- 密码强度提示:按"长度 > 8、含小写、含大写、含数字、含特殊符号"五项计分,实时展示弱/中等/强/非常强。
#### FR-AUTH-03 失败锁定
- 同一账号连续失败 **5 次**即锁定,锁定时长 **10 分钟**。
- 锁定期内登录返回明确提示:"账号已锁定,请 X 分钟后重试"(分钟数向上取整,最少显示 1 分钟)。
- 登录成功后重置失败计数与锁定状态。
- **安全要求**:账号不存在、账号被禁用、密码错误三种情况必须返回**同一句提示**("账号或密码错误"),避免账号枚举。
#### FR-AUTH-04 会话与退出
- 登录凭证通过 HttpOnly 会话 Cookie 承载,前端所有请求自动携带;任何接口返回未授权时自动跳转登录页。
- 点击"退出"清除会话并跳转登录页。
- 系统初始化时自动准备两个默认账号(超级管理员、普通操作员),已存在则不覆盖。
#### FR-AUTH-05 部署形态要求
- 系统必须支持部署在**子路径**下(如通过反向代理挂载在某级目录),前端不得硬编码绝对地址,所有请求地址需基于当前部署根路径动态推导。
---
### 3.2 数据底座(同步与加工)
#### FR-DATA-01 生产数据自动同步(贴源)
- **能力**:自动、定时地把生产业务系统中的门店运营原始数据同步到分析侧,作为所有分析的基础数据源。
- **同步范围**:覆盖门店主数据、门店负责人配置、品牌车型配置、员工信息、商品与套餐、员工日报、门店日报、商品订单/子订单/订单客户、门店目标配置、员工成交率、运营策略等 **21 类业务数据**。
- **同步模式**:全部采用**增量同步**,以业务记录的"最后更新时间"为水位线,只同步水位线之后发生变更的数据。
- **写入方式**:按业务主键做**存在即更新、不存在则插入**,保证重复同步不产生重复数据。
- **数据清洗规则**(必须执行):
- 源系统中的非法日期(零值日期)统一按空值处理;
- **门店标识为空的数据视为无效数据,直接丢弃**,不进入分析侧;
- 系统维护的同步时间戳由系统自动生成,不被源数据覆盖。
- **性能与可靠性**:采用分批写入(1000 行/批);单表同步失败即判定整轮失败并记录失败原因;同步结果需记录涉及的数据范围、影响行数、涉及表数量。
- **同步水位记录**:每类数据需记录"上次同步时间(即源数据最后更新时间的最大值)""本次同步起始时间""本次同步结束时间""本次同步行数""同步模式(增量/全量)",用于断点续跑与对账。
#### FR-DATA-02 门店主数据自动补全
- 门店清单应**自动同步**,不得依赖人工维护:凡生产业务系统中存在的有效门店,都应自动出现在分析侧的门店配置中。
- 自动补全内容:门店名称、门店简称、编码、省/市、渠道类型。
- **经营模式自动判定**:当门店存在"指定合作商 + 指定场景 + 满足主/子商户类型组合"的园区店关联关系时判定为"直营",否则为"非直营"。
- **三类负责人自动回填**(多人以"/"连接并去重):
- 区域运营 ← 负责人类型为区域运营类;
- 飞行督导 ← 负责人类型为督导类;
- 线上运营 ← 负责人类型为线上运营类。
- 门店配置为"自动同步 + 人工增补"混合模式:门店清单自动同步,人工维护的字段不被清空。
#### FR-DATA-03 数仓分层加工
- **层级与产出**:
| 层级 | 业务定位 | 主要产出 |
| --- | --- | --- |
| 贴源层 | 与生产系统保持一致的原始数据 | 21 类业务原始数据 |
| 宽表层 | 按"天 + 门店 + 场景 + 品牌"、"天 + 员工 + 门店 + 场景 + 品牌"、"订单"等粒度把多表汇总成便于分析的明细宽表 | 员工日报宽表、门店日报宽表、订单明细宽表、门店每日目标达成宽表 |
| 指标层 | 面向管理指标的日粒度汇总 | 员工触客日指标、员工交易日指标、门店触客日指标、门店交易日指标、门店交付日指标、电池分析日指标、兜底赔付日指标、门店排行日指标 |
| 应用层 | 直接支撑报表的成品模型 | 电池延保分析模型、M6 人店分析模型、鸿蒙周度对比模型 |
- **加工参数**:
- 默认增量:未指定日期时默认加工"昨天"一天;
- 全量覆盖:勾选后整表重建;
- 指定日期范围:按范围先清除后写入;
- 定时任务默认范围:**上月 26 日 ~ 当天**(与生态月口径对齐,保证跨月不丢数)。
- **加工口径约定**:以"天 + 门店 + 场景类型 + 一级品牌 + 二级品牌"为聚合键;分析场景默认取**售前场景**;一级品牌默认取鸿蒙智行,二级品牌默认取问界。
- **产品口径(订单侧识别规则)**:按商品的升级品类字段识别产品归属,具体为:整车延保、安心包、轮胎险、电池延保四类各自对应固定的品类编码,且需同时兼容一级/二级/三级品类字段。
- **产值口径**:产值 = 子订单成交金额 − 退款金额;仅统计有效状态(未删除、已完成/已安装升级)的订单,按安装升级日期归集。
- **品牌归属口径**:订单的品牌归属通过订单客户信息中的车型品牌字段确定(避免仅按门店品牌归属造成错分)。
#### FR-DATA-04 手动触发同步与加工
- 用户可在界面手动触发同步与加工,并查看执行历史。
- **加工界面的参数优先级**:全量覆盖 > 指定日期范围 > 默认增量(最近一天)。勾选全量覆盖后忽略日期范围。
- 每次执行都要生成一条执行记录,包含:开始时间、数据范围、涉及数据表数量、状态(执行中/成功/失败)、详细执行明细(逐表的源/目标、时间范围、影响行数、状态)。
#### FR-DATA-05 任务执行明细可追溯
- 任务详情需展示:启动方式(手动/定时)、执行节点标识、每个对象的处理结果。
- 明细行状态需区分:成功、跳过(无数据/无有效数据)、失败。
- 失败任务需保留完整错误信息以便排查。
---
### 3.3 数据接入
#### FR-ING-01 固定结构数据导入
- 支持把结构已知的 Excel 明细直接导入到指定数据集,按业务主键做覆盖更新。
- 导入前需给出前若干行的预览,便于确认。
#### FR-ING-02 任意结构 Excel 智能导入
- **业务诉求**:外部提供的 Excel 格式不固定(多行合并表头、列名口语化、缺注释),人工逐张建表成本高。
- **能力**:上传后由大模型识别:
1. 还原真实业务列名(把多行合并表头合并为有意义的单一列名);
2. 推断每列的存储类型(文本/数值/整数/日期时间等);
3. 生成中文列注释;
4. 识别报表的分析周期字段(日报/周报/月报)。
- **落库规则**:
- 识别结果统一以系统扩展数据集的命名空间存放,与标准数据集物理隔离;
- 若同名数据集已存在,则**只做加列,不删列、不改类型**(宽松演进策略);
- 每批导入的数据都打上**上传标识**与创建时间,便于按批次回溯与清理。
- **降级策略**:大模型不可用(未配置、调用失败、返回解析失败)时,**跳过该工作表并继续处理其他工作表**,不得让整单导入失败;系统需记录每批上传的识别结果与状态(分析中/完成/失败)。
- **版本标识**:每次上传需记录版本标识(默认取时间戳),用于区分同一份数据的多个版本。
#### FR-ING-03 上传记录可查
- 提供上传记录列表,展示文件名、所属数据集、导入行数、状态、上传时间等。
---
### 3.4 问界生态系数分析
#### FR-WJ-01 输入数据准备
**(1)门店兜底协议文件**
- 提供标准模板下载;用户填写后上传,也可直接选用历史批次。
- 文件需支持两级表头(一级为分组名、二级为产品名),系统按**表头名称**识别列,不依赖固定列序,兼容模板演进。
- 必须能识别的业务字段:
| 分组 | 字段 | 业务含义 |
| --- | --- | --- |
| 门店 | 门店(店名) | 门店唯一名称,用于与主机厂数据、业务系统数据关联 |
| 协议 | 兜底指标 | 协议原文描述,用于辅助识别规则类型 |
| 协议 | 兜底类型 | 交付 / 触客 |
| 协议 | 特殊情况 1、特殊情况 2 | 集团汇总、安心包专岗等特殊处理标记 |
| 协议 | 兜底截止日期 | 决定归入生态月还是自然月 |
| 达标转化率 | 整车延保 / 安心包 / 电池(可多级,分号分隔) | 协议要求的达标阈值,可配置阶梯 |
| 每单赔付金额 | 整车 / 安心包 / 电池(与阈值一一对应) | 每缺 1 单的赔付单价 |
- **兼容性要求**:
- 旧的"赔付系数"合并写法(形如 `60%,1500;65%,1000`)需自动拆分为"达标转化率"与"每单赔付金额"两组字段;
- 二级表头中"电池电池"等历史笔误需归一化;
- 门店名重复时**只保留第一条**并记录告警。
**(2)主机厂数据文件**
- 支持一份文件包含多个工作表,工作表名形如日期范围(如 `626-722`、`5.26-6.21`),系统据此自动解析周期并判断生态月/自然月。
- 支持多行表头:系统在表头前若干行中按业务关键词打分,自动定位真实列名行。
- 必须能识别的业务字段:厅店代码、厅店名称、厅店简称、省区/省区别称、赋能商、交付量、整车延保采购量、驾行安心包采购量、电池延保采购量、轮胎保障服务采购量、臻享无忧套餐、单车产值。
- **兼容性要求**:同一业务含义的多种列名写法(如"整车延保采购量"与"整车延保"、"交付量"与"交付数"、"单车产值/台"与"单车产值")需自动归一;缺列时按 0 处理并记录告警;同一工作表内门店名重复需去重保留第一条。
**(3)日期范围**
- 允许分别指定"生态月"与"自然月"的起止日期;若上传文件的工作表名已包含日期,系统应自动回填。
#### FR-WJ-02 数据来源优先级(必须严格遵守)
| 数据 | 优先级 |
| --- | --- |
| 门店协议 | 历史批次数据 > 本次上传文件 > 最新标准模板 |
| 主机厂数据 | 对应周期(生态/自然)的历史批次 > 本次上传文件 > 按日期范围自动匹配的历史批次 |
| 产值与触客成交数据 | 一律从数据底座实时查询,不支持上传 |
若最终既无主机厂数据也无门店数据,需明确报错提示用户补充。
#### FR-WJ-03 数据预览
- 上传或选择批次后,右侧实时预览解析结果:数据类型、周期类型、时间范围、数据来源、行数。
- 多工作表文件需提供工作表切换页签,并标注每个工作表的周期类型与数据周期。
#### FR-WJ-04 生成报表
**(1)门店分组**
- 按门店兜底截止日期把门店分为"生态月门店"和"自然月门店"两组,分别取用对应周期的主机厂数据。
**(2)门店名称映射(关键业务适配)**
- 业务系统门店名与主机厂数据门店名长期存在差异,必须支持人工维护映射关系,典型差异类型:
- 全角/半角括号差异(`(河北)` ↔ `(河北)`);
- 名称中多出/缺少品牌后缀(如"…(鸿蒙)"↔ 无后缀);
- 主体名不同但为同一门店(如"华骏"↔"华骏天元")。
- 映射需**双向生效**:合并主机厂数据时用"业务系统名 → 主机厂名";查询产值数据时**同时用两套名称查询**,避免映射后查不到数据。
**(3)本产品需计算并输出的完整指标**(分组顺序即报表列顺序):
| 分组 | 指标 |
| --- | --- |
| 基础门店信息 | 门店名、兜底指标、兜底类型、特殊情况 1、特殊情况 2、区域(省)、直营与否、区域运营、飞行督导、线上运营 |
| 主机厂数据 | 交付数、整车延保采购数、安心包采购数、电池延保采购数、轮胎险采购数、无忧套餐采购数、单车产值 |
| 产值数据(自动取数) | 交付数(产值表)、触客数、触客率、整车延保成交订单数、安心包订单总成交数、电池延保订单成交数、轮胎险订单成交数、产值、单车产值(产值口径) |
| 月度渗透率 | 整车延保渗透率、安心包渗透率、电池延保渗透率、轮胎险渗透率(分母为主机厂交付数) |
| 生态系数 | 整车延保达标系数、安心包达标系数、电池延保达标系数、总分 |
| 主机厂采购差异 | 整车延保差异、安心包差异、电池差异(主机厂采购数 − 产值表订单数) |
| 当前转化率 | 整车延保、安心包、电池(分母按兜底类型取交付数或触客数) |
| 需达标转化率 | 整车延保、安心包、电池(取协议阶梯中的最高阈值) |
| 是否触发兜底 | 是 / 否 |
| 需达标订单数差额 | 整车延保、安心包、电池(缺口数,向上取整) |
| 赔付金额 | 整车延保、安心包、电池(按阶梯档位计算) |
| 是否需要赔付 | 是 / 否 / 不适用 |
| 赔付总金额 | 三项赔付金额之和 |
| 兜底月份 | 协议周期标识 |
| 门店等级 | 红色门店 / 黄色门店 / 绿色门店 |
| 人工核对列 | 人工审核、备注(已确定赔付金额)、去除服务商 |
**(4)特殊业务规则**
- **集团门店汇总**:当门店"特殊情况 1"标注为某集团(如华奥集团)时,该集团下所有门店的**产值类指标(交付数、触客数、各产品成交数等)按集团合计值填列**,但门店基础信息逐店保留。
- **安心包专岗限制**:兜底类型为"触客"且特殊情况含"安心包专岗"时,触客数**不得超过产值表交付数**(超出则截断,并同步重算触客率)。
- **服务商不赔付**:非直营(服务商)门店不参与赔付计算,赔付相关列显示"/",并在"去除服务商"列标注。
- **主机厂交付数兜底**:主机厂交付数为 0 时,以产值表交付数替代作为分母。
**(5)报表呈现要求**
- 输出 Excel,含表头分组说明行与冻结窗格、自动筛选;
- 表头分组需合并单元格,明确标注每组口径(如"月度渗透率(分母为主机厂交付数)");
- 需复刻参考模板的条件格式规则:
- 门店名重复标红;
- "是否触发兜底 = 否"的单元格高亮;
- 门店等级三色(红/黄/绿);
- 特定标记列值为"是"时高亮。
- 生态月区块与自然月区块在同表内上下排布,并以明显的标识行分割(如"▲ 生态月数据""▼ 自然月数据")。
- 报表文件名需体现品牌与数据周期,便于归档。
- 生成成功后返回门店分组统计(生态月门店数、自然月门店数)与下载入口。
#### FR-WJ-05 保存为历史批次
- 支持把本次上传的门店协议文件、主机厂数据保存为历史批次,供后续直接复用。
- 保存时按规范整理文件名(品牌 + 数据类型 + 周期标签 + 日期范围),并保证目录内文件名唯一。
- **同周期覆盖规则**:同一"品牌 + 数据周期"(主机厂数据还需含周期类型)再次上传时,**视为覆盖**:复用原批次号、清除旧明细、写入新明细。
- 门店协议批次的"数据周期"以上传当天为准。
- 上传的临时文件在入库完成后不保留副本(数据以批次形式留存)。
---
### 3.5 鸿蒙生态分析
#### FR-HM-01 输入数据准备
- **门店兜底配置**:模板含 16 个业务字段(门店、品牌、兜底指标、区域(省)、直营与否、区域运营、飞行督导、线上运营、兜底类型、特殊情况、需达标转化率(3 个产品)、预计赔付金额(3 个产品))。
- **品牌列**用于标识该门店归属的子品牌(智界/享界/尊界/尚界),鸿蒙体系需据此区分门店口径。
- **主机厂数据**:模板含省份、城市、门店编号、用户中心门店名称、门店名称、交车数量。
- 交车数量的多种写法(交付量/交付数量/交车数/交付)需自动归一。
- **产值与触客成交数据无需上传**,一律由系统自动取数。
#### FR-HM-02 数据自动取数
- 按"**用户中心门店名(法人名称) + 品牌**"双键从数据底座匹配:交付数、触客数、整车延保成交数、安心包成交数、电池延保成交数、累计成交金额、权益成交数、省/市、区域运营/飞行督导/线上运营、经营模式。
- 取数范围:一级品牌为鸿蒙智行,二级品牌为四界(智界/享界/尊界/尚界),场景为售前。
- **名称变体处理**:存在"门店名(鸿蒙)"这类带后缀的存储变体,需对白名单门店同时按原名称与带后缀名称查询。
#### FR-HM-03 生成报表
- 鸿蒙体系**不存在生态店概念,所有门店统一按自然月核算**。
- 报表字段(按列顺序):
| 列 | 字段 | 说明 |
| --- | --- | --- |
| 1–9 | 门店名、品牌、兜底指标、区域(省)、直营与否、区域运营、飞行督导、线上运营、特殊情况 | 基础信息,协议缺失时以数据底座信息兜底 |
| 10–12 | 复合交付数、主机厂交付数、产值交付数 | 复合交付数 = 主机厂交付数优先,为 0 时取产值表交付数 |
| 13–15 | 触客数、触客率 | 触客数优先取上传值,为 0 时取数据底座值 |
| 16–18 | 整车延保成交数、整车延保渗透率、触客成交率 | — |
| 19–22 | 安心包达成数量、安心包渗透率、电池延保成交数、电池延保渗透率 | — |
| 23 | 是否触发兜底 | 是 / 否 |
| 24 | 门店等级 | **服务商**(非直营)/ 暂无交车 / 不适用 / 绿色 / 黄色 / 红色 |
| 25 | 兜底类型 | 交付 / 触客 |
| 26–28 | 当前转化率(整车延保、安心包、电池) | 分母按兜底类型取触客数或复合交付数 |
| 29–31 | 需达标转化率(三项) | — |
| 32–34 | 需达标订单数差额(三项) | 向上取整 |
| 35–37 | 赔付金额(三项) | 差额 × 协议单价 |
| 38 | 总赔付金额 | — |
- **鸿蒙门店等级判定规则**(与问界不同,需单独实现):
1. 非直营 → "服务商";
2. 复合交付数为 0 → "暂无交车";
3. 整车延保渗透率缺失 → "不适用";
4. 整车延保渗透率 **≥ 50%** → 绿色门店;
5. 整车延保渗透率 **< 40%** → 红色门店;
6. 其余(40% ≤ 渗透率 < 50%)→ 黄色门店。
- **安心包专岗限制**同样适用(触客数与产值交付数的截断规则)。
- 非直营门店的赔付相关列显示"/"。
- 输出 Excel 需保留模板的条件格式,文件名体现品牌与周期。
#### FR-HM-04 预览与批次
- 上传门店/主机厂文件后可预览解析结果;支持保存为历史批次(品牌=鸿蒙),同周期覆盖规则与问界一致。
- 生成报表时数据来源优先级:历史批次 > 本次上传文件 > 最新标准模板。
---
### 3.6 鸿蒙子品牌分析
#### FR-SB-01 业务背景
鸿蒙智行下辖四个子品牌,主机厂数据按"门店 × 子品牌"给出交付数与出单数,需**按子品牌拆分核算**,并与门店兜底协议的三产品条款合并,输出可对比各子品牌表现的专项报表。
#### FR-SB-02 输入数据准备
- **门店兜底协议(可选)**:可选择历史批次;不选则自动取最新一批鸿蒙门店兜底配置。若完全没有协议数据,报表仍需生成,但兜底条款列留空并记录告警。
- **主机厂子品牌数据**:标准模板按"省份 / 城市 / 门店编号 / 用户中心门店名称 / 门店名称 / 门店级总交付 / 门店级总出单 / 各子品牌交付数 / 各子品牌出单数"组织;系统需解析为"每门店 × 每子品牌一行"的明细。
- 子品牌枚举固定为 **尊界、尚界、智界、享界**;交付数与出单数同时为 0 的组合不输出。
#### FR-SB-03 数据关联
- **第一步:确定法人门店名**。优先取模板中给出的"对应门店名称";若为空,则通过"用户中心门店名 → 法人门店名"的映射(来源于最新的鸿蒙主机厂数据)解析。
- **第二步:与门店协议关联**。按"**法人门店名 + 子品牌**"精确匹配协议条款;匹配不到时,**回退使用该门店"鸿蒙智行"或未标注品牌的通用兜底条款**。
- 名称映射规则(全角/半角括号、后缀等)同问界,且查询时需同时使用映射前后两套名称。
#### FR-SB-04 数据自动取数
- 按"**用户中心名/法人名/映射前名称 + 子品牌**"三种候选键依次尝试匹配数据底座的产值数据(交付数、触客数、三产品成交数),取到即用。
#### FR-SB-05 生成报表
- 报表结构:**顶部 5 行汇总 + 明细区**。
- 汇总行:**四界(全部)、尊界、尚界、智界、享界**,每行汇总主机厂交付数、产值表交付数、触客数、整车延保成交数、安心包达成数量、电池延保成交数;
- 明细区按"门店 + 子品牌"一行,字段 19 列:门店名(展示法人名,缺失回退用户中心名)、兜底指标、区域(省)、直营与否、区域运营、飞行督导、线上运营、品牌、主机厂交付数、产值表交付数、触客数、触客率、整车延保成交数、整车延保渗透率、触客成交率、安心包达成数量、安心包渗透率、电池延保成交数、电池延保渗透率。
- **排序规则**:先按门店名,再按品牌固定顺序 **尊界 → 尚界 → 智界 → 享界**。
- **指标取值优先级**:主机厂数据(交付数、出单数)优先;主机厂对应值为 0 时用数据底座值补足。
- **兜底条款解析**:除使用结构化列(需达标转化率、预计赔付金额)外,还需支持从"兜底指标"自由文本中解析:
- 兜底类型(触客 / 交付 / 无兜底);
- 达标阈值(识别"≥/≤/不低于/低于/达到/按 X%"等表述);
- 赔付单价(识别"X 元/台""赔付 X 元""按 X 元"等表述);
- 特殊情况("安心包专岗""尚界条款"等)。
- 结构化列优先,解析值作为兜底。
- **"无兜底"识别**:文本含"无兜底"或"合同还未签回"时,判定该门店无兜底条款。
#### FR-SB-06 预览
- 提供子品牌数据预览,包含:
- 明细表(默认展示前 150 行);
- 品牌筛选(全部 / 四界 / 尊界 / 尚界 / 智界 / 享界,带各品牌计数);
- 顶部汇总表(品牌、主机厂交付数、产值表交付数、触客数、整车延保成交数);
- 元信息:数据来源(数据库加载 / 本地文件加载)、统计周期、明细行数、已关联兜底条款的行数。
- 解析结果为 0 行时必须明确报错,提示"未解析到有效子品牌数据,请使用标准模板",不得生成空报表。
#### FR-SB-07 批次与生成
- 支持保存子品牌历史批次(未指定日期时,数据周期默认为当月 1 日至当天;周期类型标记为"子品牌")。
- 生成报表时数据来源优先级:**批次明细数据 > 原始上传文件**(文件丢失仍可基于批次生成);两者都无则报错。
---
### 3.7 策略效果盯防
#### FR-ST-01 数据来源
- 策略信息由生产业务系统提供,系统自动同步,包含:策略标题/副标题、策略类型、所属门店、执行起止日期、推送状态、策略描述、创建人、创建时间。
#### FR-ST-02 策略类型与状态枚举
| 枚举 | 取值 |
| --- | --- |
| 策略类型 | 学习类、优秀录音分享类、带教、任务型、销售精英到店提拉、强力促销、最终盘点与低客单价产品购入、留言、带教申请、人员更换评估、商务政策更新评估、多品类拓张、流量问题改善(共 13 类) |
| 推送状态 | 未推送、盯防中、未完成、审批中、已驳回、已结束 |
| 兜底类型 | 交付、触客 |
| 经营模式 | 直营、加盟 |
| 盯防类型 | 业绩下滑盯防、预警盯防、新店盯防 |
| 效果标签 | 显著提升、有所提升、基本持平、效果下降(另有"暂无数据""基线缺失"两种非效果态) |
#### FR-ST-03 效果评估算法
**(1)周期切分**:按策略执行起止日期计算 T-1(等长前置对照期)、T(执行期)、T+1(等长后置观察期,截止今天)。
**(2)指标口径**:
- 交付数:门店在周期内的交付量合计;
- 整车延保 / 安心包 / 电池延保渗透率 = 该产品成交订单数 ÷ 交付数 × 100%;
- 渗透率变化以**百分点(pp)**计。
**(3)评分与标签**:
| 条件 | 得分 |
| --- | --- |
| 某产品渗透率变化 > 3pp | +2 |
| 0 < 变化 ≤ 3pp | +1 |
| −3pp ≤ 变化 < 0 | −1 |
| 变化 < −3pp | −2 |
三项产品得分求和后判定:
| 总分 | 效果标签 |
| --- | --- |
| ≥ 4 | 显著提升 |
| ≥ 1 | 有所提升 |
| ≤ −1 | 效果下降 |
| 0 | 基本持平 |
- 执行期无数据 → "暂无数据";缺基线期数据 → "基线缺失"。
**(4)交付数变化**:展示基期与执行期的交付数绝对值与变化率,用于辅助判断(不作为效果标签的评分依据)。
**(5)结论生成**:自动生成文字结论,格式为"策略标题 + 交付数变化 + 各产品渗透率前→后(箭头 + 百分点)+ 整体效果标签"。
**(6)盯防类型自动判定**:
- 标题/描述含"新店""开业",或策略类型为"人员更换评估" → **新店盯防**;
- 效果下降,或文本含"下滑",或策略类型为"强力促销""最终盘点与低客单价产品购入" → **业绩下滑盯防**;
- 策略类型为"带教""销售精英到店提拉""带教申请""多品类拓张""流量问题改善",或文本含"预警""提升" → **预警盯防**;
- 其余按效果标签兜底判定。
**(7)兜底类型判定**:文本含"触客"且不含"交付" → 触客;文本含"交付" → 交付;否则取门店兜底配置中的兜底类型;仍无则默认"交付"。
#### FR-ST-04 盯防列表
- **统计看板**:盯防总数、盯防中、效果上升(显著提升 + 有所提升)、效果下降、已结束。
- **筛选维度**:门店名称关键词(匹配策略标题/门店名/接收人)、区域(省)、策略类型、兜底类型、盯防类型、盯防状态、直营/加盟、效果趋势、执行起止日期。
- **列表列**:序号、门店信息(门店名、直营/加盟标签、运营人)、兜底类型、策略类型、区域、盯防信息(标题、盯防类型、接收人)、盯防周期、状态、交付数变化、延保变化、安心包变化、电池变化、整体效果、数据刷新时间、操作。
- **分页**:默认每页 8 条。
- **展示原则**:**未完成分析的策略也必须出现在列表中**(展示基本信息),已完成分析的附加效果数据;不得因为"没分析"而隐藏记录。
#### FR-ST-05 数据新鲜度标识
盯防数据的刷新时间需以颜色区分新鲜度,帮助管理者识别"数据是否可信":
| 距上次刷新 | 展示 |
| --- | --- |
| ≤ 4 小时 | 绿色 |
| 4 ~ 24 小时 | 橙色 |
| > 24 小时 | 红色 |
| 从未刷新且策略仍在盯防中 | 红色"从未刷新" |
| 从未刷新且策略非盯防中 | 灰色 "-" |
#### FR-ST-06 策略详情
- **门店信息**:门店名、兜底指标、兜底类型、特殊情况 1/2、区域(省)、直营/加盟、区域运营、飞行督导、线上运营。
- **盯防信息**:盯防类型、盯防标题、盯防内容、盯防周期、数据刷新时间、任务接收人。
- **盯防效果摘要**:交付数变化率、三项产品渗透率变化(pp)。
- **业绩数据明细(周维表)**:按**自然周(周一为周起点)**聚合,列包含时间维度、交付数、三项产品渗透率、盯防状态(盯防前 / 盯防中)、环比变化;并提供"盯防前汇总"与"盯防中汇总"两行合计。
- **盯防前后业绩对比**:分别给出"前 N 周均值"与"后 N 周均值"的周均交付数与三项渗透率。
- **转化率周趋势图**:三条折线(三项产品渗透率),并标注盯防周期区间。
- **分析结论**:文字结论。
**UI 达标参考线**:详情与渗透率分析中,三项产品分别以 **15% / 20% / 7%** 作为界面上的达标参考线,达到显示为上升色,未达到显示为下降色,并在数值下方标注达标线。该参考线为界面展示标准,与门店协议阈值相互独立。
#### FR-ST-07 渗透率分析
- **按天维度**:列出 T-1/T/T+1 窗口内每一天的日期、所属阶段(盯防前 / 盯防中 / 盯防后)、交付数、三项产品渗透率;并提供阶段汇总(天数、总交付、各产品均值)。
- **按员工维度**:列出该门店驻店销售的姓名、交付数、三项产品渗透率,按交付数倒序。
- **按品牌维度**:列出该门店各品牌(问界、智界等)的交付数与三项渗透率。
- **按产品维度汇总**:以交付数加权的产品整体渗透率(总交付、三项渗透率)。
- **智能总结**:由大模型基于上述四个维度的数据生成 200 字以内的专业分析,覆盖"整体水平评价、品牌/产品差异、员工表现差异、趋势变化、改进建议"五个角度。总结生成失败时不影响数据展示,界面提示"暂无分析总结(请确认模型配置)"。
#### FR-ST-08 分析执行方式
| 方式 | 触发 | 范围 | 限制 |
| --- | --- | --- | --- |
| 单条刷新分析 | 用户点击某条策略的"刷新分析" | 仅该策略,同步完成 | 不受日期限制 |
| 批量分析 | 定时任务(每 2 小时)或手动触发 | 全部有效策略 | **自动跳过执行结束日期超过 7 天的策略**(结果分析意义已弱化) |
| 盯防数据自动刷新 | 定时任务(每 6 小时扫描) | 状态为盯防中/审批中/已驳回、且结束日期不早于今天、且超过 4 小时未刷新的策略 | 刷新间隔阈值默认 4 小时,支持 1~48 小时调整 |
| 任务进度查询 | 界面/接口 | 查询批量分析的实时进度:总数、已完成、失败、当前处理对象、开始/结束时间、错误摘要 | — |
- 批量分析并发保护:已在运行时不重复启动。
- 单条策略分析失败不影响其他策略;失败原因需记录(截断存储)。
#### FR-ST-09 盯防刷新状态概览
提供盯防总数、从未刷新数、新鲜数(4 小时内)、超时数四类统计,以及超时盯防策略清单,便于运营人员及时补数。
---
### 3.8 批次管理
#### FR-BATCH-01 批次列表
- 展示最近有效批次(最多 50 条):批次号、品牌、数据类型、周期类型、数据周期、文件名、文件大小、导入行数、状态、上传人、上传时间。
- 只有"导入行数 > 0 且未被删除"的批次才可被选用。
#### FR-BATCH-02 批次数据结构
每次导入都需固化的业务属性:
| 属性 | 说明 |
| --- | --- |
| 批次号 | 全局唯一标识 |
| 品牌 | 问界 / 鸿蒙 |
| 数据类型 | 门店兜底协议 / 主机厂交付数据 / 鸿蒙子品牌主机厂数据 |
| 周期类型 | 生态月 / 自然月 / 生态 + 自然 / 子品牌 |
| 数据周期 | 起止日期 |
| 状态 | 已导入 / 已覆盖 / 已删除 |
#### FR-BATCH-03 批次复用与覆盖
- 批次可被反复用于生成报表("选历史批次"路径)。
- 同"品牌 + 数据周期"再次导入视为**覆盖**:复用批次号、清除旧明细、写入新明细,并标记状态为"已覆盖"。
- 已删除批次不参与任何排重与选用。
#### FR-BATCH-04 批次号规则
批次号需全局唯一且可读,建议格式:`UB` + 14 位时间戳 + 4 位随机数。
---
### 3.9 系统运行保障
#### FR-OPS-01 定时任务清单
| 任务 | 频率 | 业务作用 |
| --- | --- | --- |
| 生产数据同步 | 每天 02:00 / 08:00 / 14:00 / 20:00 | 保证分析侧数据每天 4 次刷新,控制数据延迟 |
| 数仓宽表加工 | 每天 05:00 | 加工范围为**上月 26 日 ~ 当天**,与生态月口径对齐 |
| 策略效果批量分析 | 每 2 小时 | 持续更新策略效果标签 |
| 盯防数据自动刷新 | 每 6 小时 | 刷新超过 4 小时未更新的在期盯防数据 |
| 系统健康检查 | 每 30 分钟 | 运行状态巡检 |
| 僵尸任务清理 | 每天 06:30 | 清理异常中断遗留的任务记录 |
#### FR-OPS-02 并发与超时保护
- 同一任务不允许并发执行:既在调度层限制单实例,也在业务层判断"最近 120 分钟内是否已有同任务在执行"。
- 任务级超时保护:数据同步 1.5 小时、宽表加工 2 小时,超时记录失败并告警。
- 手工触发与定时任务使用不同的任务标识,两者互不阻塞(需注意同时运行对数据库的压力)。
#### FR-OPS-03 中断恢复
- 服务重启时,把超过 2 小时仍处于"执行中"的历史记录标记为失败,并注明"进程重启,任务被中断"。
- 定时任务额外每天 06:30 执行一次超过 120 分钟的僵尸记录清理。
- 失败记录的更新必须使用独立通道,避免主流程异常导致记录永久停留在"执行中"。
#### FR-OPS-04 环境隔离
- 开发/预发布环境的定时任务自动延后 **5 分钟**触发,避免与生产环境同时打库造成竞争。
#### FR-OPS-05 日志留存
- 日志按模块分类输出(主应用、数据同步、策略分析、报表分析、模型调用、数据库语句等)。
- 默认保留 **30 天**,支持配置日志目录与级别。
---
## 四、核心业务规则与算法说明
### 4.1 生态系数(问界)
**整车延保渗透率 → 系数**
| 渗透率区间 | 系数 |
| --- | --- |
| ≤ 45% | 0 |
| (45%, 50%) | 0.8 |
| [50%, 60%) | 1.0 |
| [60%, 70%) | 1.2 |
| ≥ 70% | 1.3 |
**安心包渗透率 → 系数**
| 渗透率区间 | 系数 |
| --- | --- |
| ≥ 500%(异常值) | 0 |
| ≥ 30% | 1.3 |
| [22%, 30%) | 1.2 |
| [17%, 22%) | 1.0 |
| [12%, 17%) | 0.8 |
| < 12% | 0 |
**电池延保渗透率 → 系数**
| 渗透率区间 | 系数 |
| --- | --- |
| ≥ 500%(异常值) | 0 |
| ≥ 22% | 1.3 |
| [16%, 22%) | 1.2 |
| [13%, 16%) | 1.0 |
| [10%, 13%) | 0.8 |
| < 10% | 0 |
**总分 = 三项系数之和**(理论区间 0 ~ 3.9,保留 1 位小数)。
> 异常值保护说明:当渗透率数值明显失真(≥ 500%)时,系数按 0 计,避免脏数据产生虚高评分。
### 4.2 兜底赔付阶梯算法
**输入**:门店协议中的"达标转化率"多级阈值序列(升序)、一一对应的"每单赔付金额"序列、当前转化率、计算基数、实际成交订单数。
**计算基数**:
| 兜底类型 | 基数 |
| --- | --- |
| 触客 | 触客数(受"安心包专岗"截断规则影响) |
| 交付 | 主机厂交付数(为 0 时取产值表交付数) |
**步骤**:
1. **是否触发兜底**:当前转化率低于任一项产品的**最高阈值**即触发(显示"是"),否则"否"。
2. **需达标订单数差额**:统一按**最高阈值**计算,公式为
`差额 = max(0, 向上取整(基数 × 最高阈值 − 实际订单数))`。
3. **赔付金额**:按阈值**从低到高**遍历档位,取第一个满足"当前转化率 < 该档阈值"的档位,用该档阈值重算差额,再乘以该档单价:
```
赔付金额 = 差额(基数 × 该档阈值 − 实际订单数) × 该档单价
```
- 若当前转化率 ≥ 最高阈值 → 不赔付(0);
- 若该档计算出的差额 ≤ 0 → 不赔付。
**示例**:某产品协议档位为 `11% → ¥800/单`、`15% → ¥600/单`,基数 100 台,实际成交 8 单:
| 当前转化率 | 命中档位 | 差额 | 赔付金额 |
| --- | --- | --- | --- |
| 8%(< 11%) | 11%/¥800 | ⌈100×11% − 8⌉ = 3 | ¥2,400 |
| 12%(≥11% 且 <15%) | 15%/¥600 | ⌈100×15% − 8⌉ = 7 | ¥4,200 |
| 16%(≥15%) | 不赔 | — | ¥0 |
4. **赔付总金额** = 三项赔付金额之和(保留 1 位小数)。
5. **是否需要赔付**:总金额 > 0 → "是";= 0 → "否";非直营门店 → "/"。
6. **非直营门店(服务商)不参与赔付**,赔付相关列一律显示"/"。
### 4.3 门店等级判定
**问界生态系数报表**
| 条件(按顺序判断) | 等级 |
| --- | --- |
| 触发兜底 且 三项订单差额合计 ≥ 3 | 红色门店 |
| 生态系数总分 < 2.8 或 三项订单差额合计 > 0 | 黄色门店 |
| 其他 | 绿色门店 |
**鸿蒙生态报表**
| 条件(按顺序判断) | 等级 |
| --- | --- |
| 非直营 | 服务商 |
| 复合交付数 = 0 | 暂无交车 |
| 整车延保渗透率缺失 | 不适用 |
| 整车延保渗透率 ≥ 50% | 绿色门店 |
| 整车延保渗透率 < 40% | 红色门店 |
| 40% ≤ 渗透率 < 50% | 黄色门店 |
### 4.4 转化率与渗透率口径汇总
| 指标 | 分子 | 分母 |
| --- | --- | --- |
| 触客率 | 触客数 | 产值表交付数 |
| 各产品渗透率(问界生态系数报表) | 该产品成交订单数 | 主机厂交付数 |
| 当前转化率(问界 / 鸿蒙) | 该产品成交订单数 | 兜底类型 = 触客 → 触客数;否则 → 交付数 |
| 售前交付成交率(鸿蒙产值口径) | 整车延保成交数 | 应触客数 |
| 单车产值(主机厂口径) | — | 主机厂提供 |
| 单车产值(产值口径) | 产值 ÷ 主机厂交付数 | — |
### 4.5 数值与格式处理规则
- 百分比、金额、数值在报表中需按业务惯例格式化(百分比两位小数、金额千分位、数量整数)。
- 空值、非数字、Excel 公式错误值(`#NAME?`、`#REF!`、`#VALUE!`、`#N/A`、`#DIV/0!`、`#NULL!`)一律按空/0 处理。
- 数值解析需兼容千分位逗号、百分号(全角与半角)。
- 日期解析需兼容 `YYYY-MM-DD`、`YYYY/MM/DD`、`YYYY.MM.DD`、`YYYYMMDD` 四种写法。
- 所有除法必须做分母为 0 的保护。
### 4.6 特殊门店标记规则
| 标记 | 规则 |
| --- | --- |
| 华奥(集团门店) | "特殊情况 1"含"华奥"的门店,其产值类指标按集团合计填列,基础信息逐店保留 |
| 安心包专岗 | 兜底类型 = 触客 且 特殊情况含"安心包专岗"时,触客数不超过产值表交付数 |
| 尚界条款 | 兜底文本含"尚界"时标记为尚界特殊条款 |
| 无兜底 | 兜底文本含"无兜底"或"合同还未签回"时,不做达标与赔付计算 |
---
## 五、报表产出规格
### 5.1 问界生态系数分析报表
- **形态**:单工作表,同表内分"生态月数据"与"自然月数据"两个区块(带标识行)。
- **表头**:三层结构 —— 第 1 行为分组说明行(含业务口径备注),第 2 行为分组名,第 3 行为列名。
- **列数**:57 列(分组见 3.4 FR-WJ-04)。
- **交互规格**:冻结前 3 行表头与 A–C 列;开启自动筛选;表头分组合并单元格。
- **条件格式**:门店名重复标红、触发兜底为"否"高亮、门店等级三色、特定标记列高亮。
- **文件命名**:体现品牌与数据周期(如"问界-分析-输出-0601~0625")。
### 5.2 鸿蒙生态分析报表
- **形态**:单工作表,单区块(无生态月概念)。
- **列数**:38 列(含序号列)。
- **交互规格**:开启自动筛选、冻结窗格;保留模板条件格式。
- **文件命名**:体现品牌与数据周期。
### 5.3 鸿蒙子品牌分析报表
- **形态**:单工作表,顶部 5 行汇总 + 明细区。
- **汇总行**:四界、尊界、尚界、智界、享界。
- **明细列数**:19 列。
- **排序**:门店名升序,同门店内按尊界 → 尚界 → 智界 → 享界。
- **交互规格**:冻结窗格至品牌列右侧;开启自动筛选。
---
## 六、页面(功能入口)清单
| 功能入口 | 承载能力 |
| --- | --- |
| 登录页 | 账号密码登录、验证码、密码强度提示、记住登录 |
| 平台首页 | 六大功能模块导航 |
| 数据同步任务页 | 同步任务配置展示、手动触发、执行历史、执行明细弹窗 |
| 数仓加工任务页 | 层级选择、增量/全量/日期范围、手动触发、执行历史与明细 |
| 问界生态系数分析页 | 左右分栏:左侧三步式操作(协议 → 主机厂数据 → 生成)+ 右侧实时预览(多工作表页签) |
| 鸿蒙生态分析页 | 左右分栏:协议 + 主机厂数据 + 生成 + 预览 |
| 鸿蒙子品牌分析页 | 左右分栏:协议选择 + 子品牌数据 + 品牌筛选预览 + 汇总表 + 生成 |
| 策略效果盯防页 | 统计看板 + 多维筛选 + 列表 + 分页 + 策略详情弹窗 + 渗透率分析弹窗 |
| 盯防效果数据查看页 | 单条策略详情独立页(可由外部链接直接打开) |
**统一交互规范**:
- 顶部导航含六大模块入口与右上角用户信息、退出入口。
- 上传区支持点击选择文件;已选文件需有明确的"已选择"视觉状态。
- 生成类操作需有进行中文案(如"正在生成报表…")与结果提示(成功/失败配色区分)。
- 历史批次下拉需以标签形式标示周期类型(如 `[生态月]`、`[自然月]`、`[生态+自然]`)。
---
## 七、非功能需求
| 类别 | 要求 |
| --- | --- |
| 部署 | 支持容器化部署;支持反向代理子路径挂载;支持通过环境变量切换环境配置 |
| 时区 | 全系统统一按中国标准时间(东八区)计算与存储 |
| 性能 | 单次报表生成应在分钟级完成(依赖数据规模);数据同步与加工任务需有超时保护(同步 1.5 小时、加工 2 小时) |
| 可靠性 | 任务失败必须落库记录;关键状态更新必须与主流程解耦;支持中断后自动清理僵尸任务 |
| 安全 | 密码加盐哈希存储;登录凭证使用 HttpOnly Cookie;会话过期自动跳转登录;统一错误提示防账号枚举;验证码一次性使用 |
| 可维护性 | 报表模板与输出逻辑解耦(模板可迭代升级);配置文件外置 |
| 可扩展性 | 新增分析报表应可复用"上传 → 预览 → 生成 → 下载 → 存批次"的通用链路 |
| 数据留存 | 上传文件按类别与日期分级归档;生成的报表按日期归档;日志保留 30 天 |
| 兼容性 | 主流浏览器可用;模板迭代需向后兼容旧版本文件 |
---
## 八、数据质量与异常处理
| 场景 | 期望行为 |
| --- | --- |
| 门店与主机厂数据无法匹配 | 该门店主机厂相关列留空,同时提供映射维护机制;报表需能识别未匹配门店 |
| 门店协议中门店名重复 | 去重保留第一条,记录告警 |
| 主机厂文件中门店名重复 | 去重保留第一条,记录告警 |
| 主机厂交付数为 0 | 以产值表交付数替代作为各类转化率分母 |
| 产值数据查不到 | 相关指标按 0 处理,报表仍生成,不得整体失败 |
| 兜底条款缺失(子品牌分析) | 回退使用通用条款;仍无则留空并记录告警 |
| 门店等级依赖字段缺失 | 按"不适用/暂无交车"等占位规则处理,避免出现错误等级 |
| 大模型不可用(智能导入) | 跳过该工作表继续处理,记录失败原因 |
| 大模型不可用(策略总结) | 返回基于数据自动拼接的结构化文本作为兜底,界面可提示 |
| 定时任务中断 | 重启后自动将超时"执行中"记录标记为失败,避免看板长期显示"进行中" |
| 报表生成失败 | 明确返回失败原因,便于用户定位(如缺门店数据、缺主机厂数据) |
---
## 九、验收标准
### 9.1 数据底座
- [ ] 21 类业务数据可按"最后更新时间"增量同步,重复执行不产生重复数据。
- [ ] 门店标识为空的数据被丢弃,非法日期被置空。
- [ ] 每类数据的同步水位(上次同步时间、本次行数、同步模式)可查询。
- [ ] 新增门店能自动出现在门店配置中,直营/非直营与三类负责人自动回填正确。
- [ ] 报表依赖的宽表可按"增量(昨天)/ 全量 / 指定日期范围"三种模式加工,且定时任务默认范围为"上月 26 日 ~ 当天"。
### 9.2 问界生态系数分析
- [ ] 一份含生态月与自然月多工作表的主机厂文件,可被自动识别并按周期拆分。
- [ ] 门店按兜底截止日期正确归入生态月 / 自然月区块。
- [ ] 生态系数三项分档与总分计算全部符合 4.1 规则。
- [ ] 阶梯赔付计算全部符合 4.2 规则(含多档位、边界值、差额为 0、超最高阈值不赔)。
- [ ] 非直营门店赔付列显示"/"。
- [ ] 集团门店产值类指标按集团汇总、基础信息逐店保留。
- [ ] "安心包专岗"门店触客数被正确截断且触客率同步更新。
- [ ] 门店等级三色判定正确,条件格式与参考模板一致。
- [ ] 输出报表结构(57 列、三层表头、冻结窗格、自动筛选)与模板一致。
- [ ] 同周期重复上传主机厂数据时,旧批次被正确覆盖。
### 9.3 鸿蒙生态分析
- [ ] 产值与触客成交数据完全由系统自动取数,无需上传。
- [ ] 报表 38 列字段齐全,门店等级按 4.3 鸿蒙规则判定正确。
- [ ] 品牌为四界的门店数据可正确取到。
### 9.4 鸿蒙子品牌分析
- [ ] 子品牌数据被正确解析为"门店 × 子品牌"明细,四个子品牌齐全。
- [ ] 法人门店名可通过模板映射或用户中心名映射两种方式解析。
- [ ] 协议条款精确匹配失败时可回退使用通用条款。
- [ ] 顶部 5 行汇总(四界 + 四子品牌)数据与明细汇总一致。
- [ ] 明细排序符合"门店 → 尊界/尚界/智界/享界"顺序。
- [ ] 明细为 0 行时明确报错,不生成空报表。
### 9.5 策略效果盯防
- [ ] 效果标签计算符合 4.3 评分规则(含边界值 3pp / −3pp)。
- [ ] T-1 / T / T+1 周期切分正确,T+1 未过完时按已发生天数计算。
- [ ] 未分析的策略仍出现在列表中。
- [ ] 数据刷新时间颜色规则正确(4 小时 / 24 小时阈值)。
- [ ] 批量分析自动跳过结束超过 7 天的策略;手工单条分析不受限。
- [ ] 自动刷新仅覆盖"在期且超过 4 小时未刷新"的盯防策略。
- [ ] 渗透率分析四个维度齐全,智能总结可正常生成与降级。
### 9.6 账号与安全
- [ ] 连续失败 2 次后要求验证码;连续失败 5 次锁定 10 分钟。
- [ ] 账号不存在 / 禁用 / 密码错误返回同一提示。
- [ ] 会话 30 分钟过期;勾选"记住登录状态"后 7 天有效。
- [ ] 验证码一次性有效、5 分钟过期、字符集剔除易混淆字符。
---
## 十、迭代建议与待明确事项
以下为在梳理过程中发现的、建议在下一版本明确或优化的点:
1. **权限分级缺失**:当前所有登录用户权限相同。建议按"区域运营 / 飞行督导 / 分析岗 / 管理员"做功能与数据范围隔离(如按省份过滤)。
2. **页面重复**:存在两个内容一致的单条策略详情入口,建议收敛为一个,并明确二者定位差异。
3. **模块成熟度标注**:策略盯防在导航上标注"开发中",建议明确定版范围与交付时间,或移除该标注。
4. **前端校验不一致**:问界分析页强制要求主机厂数据,鸿蒙分析页无强制校验。建议统一为"缺数据时给出明确提示"。
5. **未暴露的能力**:批量分析、盯防数据手动刷新、任务进度查询、超时盯防清单等已有能力未在界面提供入口,建议补充管理视图。
6. **详情页占位字段**:策略详情中的"特殊情况 1/2、区域运营、飞行督导、线上运营"目前多为占位,建议接入数据或移除。
7. **批次号与周期口径**:门店协议批次的"数据周期"目前取上传当天,与协议真实考核周期不等价,建议允许手工指定考核周期。
8. **指标口径统一**:界面上存在两套产品达标参考线(界面 15%/20%/7% 与协议阈值),建议明确二者关系并在界面给出说明。
9. **文件与体积限制**:当前未见上传文件大小与扩展名的统一限制,建议补充约束与提示。
10. **映射维护体验**:门店名称映射目前依赖人工维护常量,建议做成可配置的映射表并支持界面维护与命中率统计。
11. **盯防并发**:手工触发与定时任务标识不同,理论上可同时运行,建议统一互斥策略。
12. **统计口径扩展**:目前盯防效果仅覆盖整车延保、安心包、电池延保三项,建议评估是否纳入轮胎险、无忧套餐等。
---
## 附:核心业务闭环示意
```
┌──────────────── 数据底座(每天 4 次同步 + 每天 1 次加工)────────────────┐
│ 生产业务系统 → 原始数据 → 门店/员工宽表 → 指标层 → 应用分析模型 │
└───────────────────────────────┬───────────────────────────────────────┘
│ 自动取数(产值、触客、成交、交付)
门店协议(Excel)─┐ ▼
主机厂数据(Excel)┼─► 上传/选批次 ─► 合并计算 ─► 系数 / 转化率 / 差额 / 赔付 ─► 报表下载
集团规则 / 映射表 ─┘ │
▼
区域运营决策 · 赔付结算
策略下发 ─► 定时评估(每 2 小时) ─► 效果标签 + 结论 ─► 盯防看板
│ │
└── 超时未刷新(每 6 小时扫描,>4 小时)──► 自动刷新
```
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!