test_v8.py 18.3 KB
"""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]["type"] == "query" and d["spec"]["steps"][0]["ui"]
    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