diff --git a/backend/app/api/copilot_blueprint.py b/backend/app/api/copilot_blueprint.py index 8068edc0..32cc2064 100644 --- a/backend/app/api/copilot_blueprint.py +++ b/backend/app/api/copilot_blueprint.py @@ -293,7 +293,7 @@ async def blueprint_stream(payload: BlueprintStreamIn, session: AsyncSession = D system = "\n\n".join(part for part in ( BLUEPRINT_SYSTEM_PROMPT, _templates_text(personal=personal), await looks.overview(), BLUEPRINT_PROTOCOL_PROMPT, looks.guide(), BLUEPRINT_LOOK_WHEN_PROMPT) if part) - missing = [i for i in blueprint_issues(spec, for_="trial") if i["level"] == "error"] + missing = [i for i in blueprint_issues(spec, for_="trial", graph=row.graph) if i["level"] == "error"] human = copilot._with_history(BLUEPRINT_REQUEST_PROMPT.format( spec=json.dumps(spec, ensure_ascii=False), instruction=instruction, issues=BLUEPRINT_ISSUES_PROMPT.format(lines="\n".join(f"- {i['path']} {i['message']}" for i in missing)) diff --git a/backend/app/blueprints/instantiate.py b/backend/app/blueprints/instantiate.py index d7e966ab..1cb96967 100644 --- a/backend/app/blueprints/instantiate.py +++ b/backend/app/blueprints/instantiate.py @@ -198,7 +198,7 @@ def instantiate(blueprint: dict[str, Any], *, filled: dict[str, Any] | None = No spec = _spec_of(blueprint) ref = spec.get("template") or {} template = get_template(str(ref.get("id") or "")) - problems = [i for i in blueprint_issues(spec, for_="trial") if i["level"] == "error"] + problems = [i for i in blueprint_issues(spec, for_="trial", graph=graph) if i["level"] == "error"] if template is None: from app.apps.spec import empty_spec diff --git a/backend/app/blueprints/ops.py b/backend/app/blueprints/ops.py index a626fed5..59d1aaa4 100644 --- a/backend/app/blueprints/ops.py +++ b/backend/app/blueprints/ops.py @@ -520,8 +520,47 @@ def _container(spec: dict[str, Any], tokens: list[str]) -> tuple[dict[str, Any], raise BpRefused(f"不能改这个位置:/{'/'.join(tokens)}") -def _set(spec: dict[str, Any], tokens: list[str], value: Any, source: str) -> None: +def is_freeform(spec: dict[str, Any]) -> bool: + from app.blueprints.templates._common import is_freeform as imports_graph + + return imports_graph(spec) + + +#: 自由形的「谁来做」只定由谁做(05-已知遗留 (d)、遗留-Q5) +FREEFORM_PEOPLE_ONLY_WHO = "自由形蓝图的「谁来做」只定每一步由谁做;会签、时限、超时、加减步骤在画布上改" +FREEFORM_PEOPLE_USER = "「谁来做」要由你来定:派活给谁是人的决定,助手不替你选" + + +def _freeform_who(spec: dict[str, Any], tokens: list[str], value: Any, source: str, graph: Any) -> None: + """自由形的 /people//who:i 是按导入的图列出的第几个岗位(freeform.people_rows 的岗位行,界面照那一份的 path 写), + 绑定存进 spec.people[](id 就是岗位名、只有 who)。只收人和组:岗位、发起人在图上已经写定了。""" + from app.blueprints.templates import freeform + from app.blueprints.templates._common import with_graph + + if len(tokens) != 3 or tokens[2] != "who": + raise BpRefused(FREEFORM_PEOPLE_ONLY_WHO, code="bp.template_mismatch") + if source != "user": + raise BpRefused(FREEFORM_PEOPLE_USER) + if graph is None: + raise BpRefused("这张蓝图还没有导入的图,没法按图定谁来做") + rows = [r for r in freeform.people_rows(with_graph(spec, graph)) if r["kind"] == "slot"] + slot = rows[_index(tokens[1], len(rows))]["slot"] + checked = _checked("people", "who", value, spec) + if checked and any(p["kind"] not in ("user", "group") for p in checked): + raise BpRefused("这里只选人或组:岗位、发起人在图上已经定了") + entries = spec.setdefault("people", []) + entry = next((e for e in entries if e.get("id") == slot), None) + if entry is None: + entry = {"id": slot} + entries.append(entry) + entry["who"] = _item(checked, source) + + +def _set(spec: dict[str, Any], tokens: list[str], value: Any, source: str, graph: Any = None) -> None: card = tokens[0] + if card == "people" and is_freeform(spec): + _freeform_who(spec, tokens, value, source, graph) + return if card == "access": if len(tokens) != 2 or tokens[1] not in ACCESS_KINDS: raise BpRefused("「谁能看」只有使用、查看全部、管理三档") @@ -577,6 +616,8 @@ def _set(spec: dict[str, Any], tokens: list[str], value: Any, source: str) -> No def _add(spec: dict[str, Any], tokens: list[str], value: Any, source: str) -> None: card = tokens[0] + if card == "people" and is_freeform(spec): + raise BpRefused(FREEFORM_PEOPLE_ONLY_WHO, code="bp.template_mismatch") if card == "access": if len(tokens) not in (2, 3) or tokens[1] not in ACCESS_KINDS: raise BpRefused("「谁能看」只有使用、查看全部、管理三档") @@ -598,8 +639,13 @@ def _add(spec: dict[str, Any], tokens: list[str], value: Any, source: str) -> No entries.insert(at, _new_entry(card, value, source, spec)) -def _remove(spec: dict[str, Any], tokens: list[str], source: str) -> None: +def _remove(spec: dict[str, Any], tokens: list[str], source: str, graph: Any = None) -> None: card = tokens[0] + if card == "people" and is_freeform(spec): + if len(tokens) != 3: + raise BpRefused(FREEFORM_PEOPLE_ONLY_WHO, code="bp.template_mismatch") + _freeform_who(spec, tokens, None, source, graph) + return if card == "access": if len(tokens) != 3 or tokens[1] not in ACCESS_KINDS: raise BpRefused("「谁能看」要写明删哪一档的第几个") @@ -655,8 +701,9 @@ def _template(spec: dict[str, Any], op: BpOp, source: str) -> None: prefill(template.id, spec) -def apply_bp_op(spec: dict[str, Any], op: dict[str, Any], *, source: str) -> dict[str, Any]: - """把一个 bp_* 操作落到蓝图上,交回新的蓝图(不改入参)。source 是 user / assistant。不合规时抛 BpRefused。""" +def apply_bp_op(spec: dict[str, Any], op: dict[str, Any], *, source: str, graph: Any = None) -> dict[str, Any]: + """把一个 bp_* 操作落到蓝图上,交回新的蓝图(不改入参)。source 是 user / assistant。不合规时抛 BpRefused。 + graph 是蓝图存的图:自由形的「谁来做」按它列岗位(没给时那张卡片改不了)。""" if source not in BP_SOURCES: raise BpRefused(f"操作的来源只能是用户或助手,当前为「{source}」") if not isinstance(op, dict) or op.get("op") not in BP_OPS: @@ -677,11 +724,11 @@ def apply_bp_op(spec: dict[str, Any], op: dict[str, Any], *, source: str) -> dic if source != "user" and (only := next((k for k in USER_ONLY if tuple(tokens[:len(k)]) == k), None)): raise BpRefused(_USER_ONLY_TEXT[only[-1]]) if parsed.op == "bp_set": - _set(out, tokens, parsed.value, source) + _set(out, tokens, parsed.value, source, graph) elif parsed.op == "bp_add": _add(out, tokens, parsed.value, source) else: - _remove(out, tokens, source) + _remove(out, tokens, source, graph) try: return parse_blueprint(out).model_dump(mode="json", by_alias=True) except ValidationError as e: @@ -708,9 +755,9 @@ def _value(item: Any) -> Any: return item.get("value") if isinstance(item, dict) else None -def blueprint_issues(spec: dict[str, Any], *, for_: str) -> list[dict[str, Any]]: +def blueprint_issues(spec: dict[str, Any], *, for_: str, graph: Any = None) -> list[dict[str, Any]]: """蓝图检查(§3.13 bp.*):for_ = trial(缺项挡试运行)/ publish(待确认项挡发布)/ personal。 - 每条 {code, level, path, message}。""" + 每条 {code, level, path, message}。graph 是蓝图存的图:自由形的「谁来做」按它查(没给时不查这一张)。""" from app.blueprints.templates import get_template if for_ not in ISSUE_PURPOSES: @@ -743,7 +790,10 @@ def blueprint_issues(spec: dict[str, Any], *, for_: str) -> list[dict[str, Any]] _data_issues(spec, "data" in required, add) if "cadence" in required and _value(spec.get("cadence")) is None: add("bp.missing", "/cadence", "「多久更新」还没定:每天、每周还是每月,几点,统计哪一期") - if "people" in used: + if "people" in used and template.imports_graph: + if graph is not None and for_ != "personal": + out += _freeform_people_issues(spec, graph, publish) + elif "people" in used: _people_issues(spec, "people" in required, publish, add) if "fields" in used: _field_issues(spec, "fields" in required, add) @@ -836,6 +886,32 @@ def _people_issues(spec: dict[str, Any], required: bool, publish: bool, add: Cal f"「{label}」的条件拿「{threshold['field']}」比大小,它要是数字字段") +def _freeform_people_issues(spec: dict[str, Any], graph: Any, publish: bool) -> list[dict[str, Any]]: + """自由形的「谁来做」(freeform.people_rows):岗位、核实人没绑的报 bp.people_unbound(试运行 warning:待办派给试运行的 + 人自己;发布 error),路径就是那一行的 path,带上 slot(发布单据此去掉同一件事的 app.slot_unbound / app.reconciler_unbound)。 + 图里已经没有的岗位、卡片上还留着绑定的,照实提醒(warning),不静默删掉。""" + from app.blueprints.templates import freeform + from app.blueprints.templates._common import with_graph + + out: list[dict[str, Any]] = [] + level = "error" if publish else "warning" + rows = freeform.people_rows(with_graph(spec, graph)) + for row in rows: + if row["kind"] not in ("slot", "reconciler") or row["who"]: + continue + message = (f"{row['label']}还没定:{row['detail']},写入外部系统的结果不明时要有人去目标系统里核实" + if row["kind"] == "reconciler" else f"{row['label']}还没定谁来处理({row['detail']})") + out.append({"code": "bp.people_unbound", "level": level, "path": row["path"], "message": message, + "slot": row["slot"]}) + known = {r["slot"] for r in rows if r["kind"] == "slot"} + for step in spec.get("people") or []: + slot = str(step.get("id") or "") + if slot and slot not in known and _value(step.get("who")): + out.append({"code": "bp.template_mismatch", "level": "warning", "path": "/people", + "message": f"岗位「{slot}」在导入的图里已经没有了:卡片上留着的这条绑定不会生效"}) + return out + + def _field_issues(spec: dict[str, Any], required: bool, add: Callable[..., None]) -> None: fields = spec.get("fields") or [] if required and not fields: diff --git a/backend/app/blueprints/publish_plan.py b/backend/app/blueprints/publish_plan.py index cdc1749b..b3c7a289 100644 --- a/backend/app/blueprints/publish_plan.py +++ b/backend/app/blueprints/publish_plan.py @@ -75,6 +75,8 @@ TRIAL_REJECTED = "plan.trial_rejected" TRIAL_DIFFERS = "plan.trial_differs" #: 蓝图检查:写回的结果不明时没人核实(blueprints/ops.blueprint_issues) RECONCILER_UNBOUND = "bp.reconciler_unbound" +#: 蓝图检查:「谁来做」有一步还没定由谁处理;自由形的带着 slot(哪个岗位,核实人是 apps/derive.RECONCILER) +PEOPLE_UNBOUND = "bp.people_unbound" ADMIN_REQUIRED = "plan.admin_required" DOWNGRADE_ADMIN = "plan.downgrade_admin" PREFLIGHT = "plan.preflight" @@ -239,8 +241,10 @@ async def _simulated_pins(session: AsyncSession, spec: dict[str, Any], target: _ def bindings_of(bp: Blueprint) -> dict[str, Any]: """岗位绑定:「谁来做」卡片上写了具体的人或组的,按模板定的岗位名绑上(templates/_common.bindings_of)。""" from app.blueprints.templates._common import bindings_of as from_cards + from app.blueprints.templates._common import with_graph - return from_cards(bp.spec or {}) + # 带上蓝图存的图:自由形的核实人要不要绑按导入的图算(05-已知遗留 (d)) + return from_cards(with_graph(bp.spec or {}, bp.graph)) def grant_items(bp: Blueprint) -> list[tuple[str, str, str]]: @@ -354,6 +358,14 @@ async def _preflight(session: AsyncSession, bp: Blueprint, target: _Target, *, l issues = [i for i in issues if i.get("code") != "app.reconciler_unbound" and not (i.get("code") == "app.slot_unbound" and i.get("path") == f"slots.{RECONCILER}")] + if unbound := {str(i["slot"]) for i in out if i.get("code") == PEOPLE_UNBOUND and i.get("slot")}: + # 自由形的「谁来做」:岗位、核实人没绑,蓝图检查已经指到卡片上那一行(bp.people_unbound 带着 slot),应用检查说的是 + # 同一件事,不再重复列(同上面核实岗位的办法) + from app.apps.derive import RECONCILER + + issues = [i for i in issues if not (i.get("code") == "app.slot_unbound" + and str(i.get("path") or "").removeprefix("slots.") in unbound) + and not (i.get("code") == "app.reconciler_unbound" and RECONCILER in unbound)] out += [{**i, "source": "app"} for i in issues] # 授权:给的人和组要在名录里(同授权接口) _, problem = await grants_problem(session, grant_items(bp)) diff --git a/backend/app/blueprints/store.py b/backend/app/blueprints/store.py index a3ef2fc4..700711bc 100644 --- a/backend/app/blueprints/store.py +++ b/backend/app/blueprints/store.py @@ -183,7 +183,7 @@ async def apply_ops_and_save(session: AsyncSession, blueprint: Any, ops: list[di try: op = await _verified_reuse(session, raw) before = _at(spec, op.get("path")) - spec = apply_bp_op(spec, op, source=source) + spec = apply_bp_op(spec, op, source=source, graph=blueprint.graph) except BpRefused as e: if not partial: raise @@ -313,7 +313,7 @@ def blueprint_issues_of(blueprint: Any) -> list[dict[str, Any]]: from app.plain import with_plain spec = blueprint.spec or {} - issues = blueprint_issues(spec, for_="personal" if blueprint.scope == "personal" else "publish") + issues = blueprint_issues(spec, for_="personal" if blueprint.scope == "personal" else "publish", graph=blueprint.graph) for joint_id, state in (blueprint.joints or {}).items(): if isinstance(state, dict) and state.get("status") in ("pending", "refused"): issues.append({"code": "tpl.joint_unfilled" if state["status"] == "pending" else "tpl.joint_refused", @@ -375,11 +375,19 @@ async def blueprint_view(session: AsyncSession, blueprint: Any) -> dict[str, Any return blueprint_out(blueprint, extra=await data_source_issues(session, blueprint)) +def _derived_people(blueprint: Any) -> list[dict[str, Any]]: + from app.blueprints.templates import freeform + from app.blueprints.templates._common import with_graph + + return freeform.people_rows(with_graph(blueprint.spec or {}, blueprint.graph)) + + def blueprint_out(blueprint: Any, *, issues: bool = True, extra: list[dict[str, Any]] | None = None) -> dict[str, Any]: """一张蓝图交给前端的样子(frontend/src/typesBlueprint.ts 的 Blueprint)。关节只给状态和模板声明的说法、类型、分组 (JointState:status、by、note、label、kind、group),不给填的值(值在图上看)。reconciler_needed:写回卡片上要不要 - 摆「结果不明时谁去核实」(目标能力没登记查询,templates/_common.needs_reconciler),界面不自己判。""" - from app.blueprints.templates._common import needs_reconciler + 摆「结果不明时谁去核实」(目标能力没登记查询,templates/_common.needs_reconciler),界面不自己判。derived_people:自由形 + 按导入的图列出的「谁来做」(templates/freeform.people_rows,05-已知遗留 (d)),别的模板为空。""" + from app.blueprints.templates._common import is_freeform, needs_reconciler, with_graph joints = {jid: {k: v for k, v in state.items() if k in ("status", "by", "note", "label", "kind", "group")} for jid, state in (blueprint.joints or {}).items() if isinstance(state, dict)} @@ -389,7 +397,9 @@ def blueprint_out(blueprint: Any, *, issues: bool = True, extra: list[dict[str, "template_version": blueprint.template_version, "source": blueprint.source or {}, "conversation_id": blueprint.conversation_id, "workflow_id": blueprint.workflow_id, "app_id": blueprint.app_id, "last_trial_run_id": blueprint.last_trial_run_id, "graph_hash": blueprint.graph_hash, "joints": joints, - "copied_from": blueprint.copied_from, "reconciler_needed": needs_reconciler(blueprint.spec or {}), + "copied_from": blueprint.copied_from, + "reconciler_needed": needs_reconciler(with_graph(blueprint.spec or {}, blueprint.graph)), + "derived_people": _derived_people(blueprint) if is_freeform(blueprint.spec or {}) else None, "created_at": blueprint.created_at.isoformat() if blueprint.created_at else None, "updated_at": blueprint.updated_at.isoformat() if blueprint.updated_at else None, } diff --git a/backend/app/blueprints/templates/_common.py b/backend/app/blueprints/templates/_common.py index 589c221a..20ee6e0c 100644 --- a/backend/app/blueprints/templates/_common.py +++ b/backend/app/blueprints/templates/_common.py @@ -78,6 +78,19 @@ def context(bp: dict[str, Any]) -> dict[str, Any]: return ctx if isinstance(ctx, dict) else {} +def with_graph(spec: dict[str, Any], graph: Any) -> dict[str, Any]: + """只有卡片(Blueprint.spec)、没有实例化上下文的地方,带上蓝图存的图再交给模板的函数:自由形的「谁来做」、要不要 + 核实人都按导入的图算(freeform.people_rows / needs_reconciler)。""" + return {**spec, CONTEXT_KEY: {**context(spec), "graph": graph}} + + +def is_freeform(spec: dict[str, Any]) -> bool: + """卡片上选的是导入图的模板(自由形)。""" + ref = spec.get("template") + template = get_template(str(ref.get("id") or "")) if isinstance(ref, dict) else None + return template is not None and template.imports_graph + + def app_name(bp: dict[str, Any], fallback: str) -> str: """应用和工作流的名字:实例化时给的名字,没给就用目的的前一段。""" name = str(context(bp).get("name") or "").strip() @@ -434,6 +447,12 @@ def needs_reconciler(bp: dict[str, Any]) -> bool: 蓝图(reconciler_needed)共用这一份。""" ref = bp.get("template") template = get_template(str(ref.get("id") or "")) if isinstance(ref, dict) else None + if template is not None and template.imports_graph: + # 自由形没有「写回哪里」:按导入的图里的写入算(bp 要带着图,with_graph),核实人存在 /writeback/reconciler + # (05-已知遗留 (d)) + from app.blueprints.templates import freeform + + return freeform.needs_reconciler(bp) if template is None or "writeback" not in template.cards: return False capability = value((bp.get("writeback") or {}).get("capability")) diff --git a/backend/app/blueprints/templates/freeform.py b/backend/app/blueprints/templates/freeform.py index 42cc6c3a..db886bb4 100644 --- a/backend/app/blueprints/templates/freeform.py +++ b/backend/app/blueprints/templates/freeform.py @@ -1,5 +1,11 @@ """自由形 freeform(§3.3):从已有的运行(问数据的一轮回答,经 from-run 提取)或已发布的工作流版本导入,图原样用, -没有关节。蓝图只有目的、谁能看、多久更新三张卡片;要改图只能回画布(搭建者)。 +没有关节。蓝图有目的、谁能看、多久更新、谁来做四张卡片;要改图只能回画布(搭建者)。 + +「谁来做」(docs/design/next-round/05-已知遗留.md (d)):骨架就是导入的图,卡片只填「谁」这个关节——按图列出用到的岗位 +(人工节点派给谁、超时升级给谁、写入的发送确认派给谁,people_rows),写入能力没登记查询时再加一行「写入结果不明时谁去核实」。 +只定由谁做:会签、时限、超时在画布上改(改了会改图,图哈希就和发布的那一版对不上)。绑定存在 spec.people[](Step.id 就是 +岗位名、只写 who,_common.slot_of / bindings_of 原样生效),核实人存在 /writeback/reconciler。以前这张卡片不存在,第一次 +发布挡在 app.slot_unbound / app.reconciler_unbound 上,白话却叫人去「谁来做」里选人。 图由实例化的上下文给(graph,导入时存在蓝图上)。应用骨架按 apps/derive.py 的派生规则:有人工节点或写入的按流程, 否则按看板;写入节点按能力登记的进程内快照认(和运行时同一个判断,capabilities.registry.writes_externally)。 @@ -38,6 +44,65 @@ def _writes(graph: dict[str, Any]) -> dict[str, str]: return out +#: 「谁来做」一行里每处用途怎么说(apps/tree.SLOT_ROLES,加上核实) +USE_TEXT = {"assignee": "处理", "escalation": "超时升级", "confirm": "发送前确认", "reconcile": "写入结果不明时去核实"} +#: 不按岗位派的步骤(只读行):发起人自己、按表达式算出来的人、等外部系统回调 +FIXED_TEXT = {"initiator": "由发起人自己处理", "expression": "按图里的表达式算出由谁处理(在画布上改)", + "hook": "等外部系统回调,不派给人"} +#: 核实人那一行的名字 +RECONCILER_LABEL = "写入结果不明时谁去核实" + + +def people_rows(bp: dict[str, Any]) -> list[dict[str, Any]]: + """按导入的图列出「谁来做」:[{kind, slot, label, detail, path, who, uses}]。 + + kind=slot:图里引用的一个岗位(同一个岗位用在几处合成一行,按节点出现的顺序),path 是 /people//who(i 是岗位行的 + 序号),who 是卡片上绑的人或组;kind=reconciler:写入能力没登记查询时的核实人,path 是 /writeback/reconciler; + kind=initiator / expression / hook:不按岗位派的步骤,只读(path 为空)。label 用节点在图上的名字拼(岗位名是画布上 + 随手写的 id),detail 写全每一处用途。界面照这一份画,不自己从图里推。""" + from app.apps.derive import RECONCILER + from app.apps.tree import node_map, slot_refs + + graph = imported(bp) + writes = _writes(graph) + nodes = node_map(graph) + bound = {str(step.get("id")): c.value(step.get("who")) for step in bp.get("people") or [] if isinstance(step, dict)} + rows: list[dict[str, Any]] = [] + by_slot: dict[str, dict[str, Any]] = {} + for ref in slot_refs(graph, writes): + row = by_slot.get(ref["slot"]) + if row is None: + row = by_slot[ref["slot"]] = {"kind": "slot", "slot": ref["slot"], "path": f"/people/{len(by_slot)}/who", + "who": bound.get(ref["slot"]), "uses": []} + rows.append(row) + row["uses"].append({"node_id": ref["node_id"], "title": ref["title"], "role": ref["role"]}) + unchecked = [(nid, cap) for nid, cap in writes.items() if not c.write_lookup(cap)] + if unchecked: + rows.append({"kind": "reconciler", "slot": RECONCILER, "path": "/writeback/reconciler", + "who": c.value((bp.get("writeback") or {}).get("reconciler")), + "uses": [{"node_id": nid, "title": nodes[nid]["title"], "role": "reconcile"} for nid, _ in unchecked]}) + for nid, n in nodes.items(): + if n["type"] != "human" and nid not in writes: + continue + assignee = n["config"].get("assignee") + kind = assignee.get("kind") if isinstance(assignee, dict) else None + if kind in FIXED_TEXT: + rows.append({"kind": kind, "slot": None, "path": None, "who": None, + "uses": [{"node_id": nid, "title": n["title"], + "role": "assignee" if n["type"] == "human" else "confirm"}]}) + for row in rows: + titles = list(dict.fromkeys(u["title"] for u in row["uses"])) + row["label"] = RECONCILER_LABEL if row["kind"] == "reconciler" else "、".join(f"「{t}」" for t in titles) + row["detail"] = FIXED_TEXT[row["kind"]] if row["kind"] in FIXED_TEXT else ";".join( + f"「{u['title']}」{USE_TEXT[u['role']]}" for u in row["uses"]) + return rows + + +def needs_reconciler(bp: dict[str, Any]) -> bool: + """导入的图里有写入能力没登记查询(同 app_skeleton 加核实岗位的判断)。""" + return any(not c.write_lookup(cap) for cap in _writes(imported(bp)).values()) + + def app_skeleton(bp: dict[str, Any], graph: dict[str, Any]) -> dict[str, Any]: from app.apps.derive import ENTRY, INSTANCE_VIEW, PIN, VIEW, _entries, _results from app.apps.forms import input_schema @@ -103,6 +168,7 @@ TEMPLATE = register(TemplateDef( applies_when="用户已经有一次满意的问数据回答,或者一个已发布的工作流,想直接做成应用;需求在五个场景之外时也用它。", cards={"purpose": "必填:一句话说清这个应用做什么", "cadence": "可选:要不要定期自动出数", + "people": "可选:只定每一步由谁做;会签、时限、超时在画布上改", "access": "可选:谁能用、谁能看全部、谁能管理"}, personal="导入的图满足问数据的规则(只读、没有人工节点和写入)时可以", skeleton=skeleton, app_skeleton=app_skeleton, schedule=schedule, tags=["导入"], diff --git a/backend/app/blueprints/trial.py b/backend/app/blueprints/trial.py index 1142ece8..96578058 100644 --- a/backend/app/blueprints/trial.py +++ b/backend/app/blueprints/trial.py @@ -147,7 +147,7 @@ async def materialize(session: AsyncSession, bp: Blueprint, *, principal: Princi digest = graph_hash(graph or {}) app_spec = _draft_pins(result.app_spec, bp, digest) # 实例化交回的是挡路的 error;蓝图检查里的提醒(模板版本旧了之类)另外带上 - warnings = [i for i in blueprint_issues(bp.spec or {}, for_="trial") if i.get("level") != "error"] + warnings = [i for i in blueprint_issues(bp.spec or {}, for_="trial", graph=bp.graph) if i.get("level") != "error"] problems = [with_plain(p) for p in [*result.problems, *warnings]] bp.graph, bp.graph_hash, bp.joints = graph, digest, result.joints bp.updated_by = principal.username if principal else bp.updated_by diff --git a/backend/tests/test_blueprint_templates.py b/backend/tests/test_blueprint_templates.py index 2f054fdd..888d890f 100644 --- a/backend/tests/test_blueprint_templates.py +++ b/backend/tests/test_blueprint_templates.py @@ -265,3 +265,37 @@ def test_trial_inputs_follow_the_cadence(): inputs = trial_inputs(get_template("periodic_board").example(), at=datetime(2026, 10, 15, 3, tzinfo=timezone.utc)) assert inputs == {"period": "2026-W41", "period_start": "2026-10-05", "period_end": "2026-10-11"} assert trial_inputs(get_template("approval").example()) == {} + + +def test_freeform_people_rows_follow_the_imported_graph(): + """自由形的「谁来做」按导入的图列(05-已知遗留 (d)):同一个岗位用在几处合成一行、说明写全;发起人、表达式派单的步骤是 + 只读行;没有人工节点和写入的图一行都没有。卡片上留着、图里已经没有的岗位照实提醒,不静默删掉。""" + from app.blueprints.ops import blueprint_issues + from app.blueprints.templates import freeform + + graph = {"nodes": [ + c.node("start", "input", "发起", fields=[{"name": "q"}]), + c.node("a", "human", "初审", mode="approve", assignee={"kind": "slot", "slot": "finance"}, + on_timeout={"action": "escalate", "to_slot": "director"}, due="PT1H"), + c.node("b", "human", "复审", mode="approve", assignee={"kind": "slot", "slot": "finance"}), + c.node("me", "human", "本人确认", mode="approve", assignee={"kind": "initiator"}), + c.node("calc", "human", "按金额派", mode="approve", assignee={"kind": "expression", "expression": "input.q"}), + c.node("done", "output", "完成", fields=[])], + "edges": [c.edge("start", "a"), c.edge("a", "b"), c.edge("b", "me"), c.edge("me", "calc"), c.edge("calc", "done")]} + spec = {**get_template("freeform").example(), "people": [ + {"id": "finance", "who": c.user_item([{"kind": "user", "name": "zhang"}])}, + {"id": "gone", "who": c.user_item([{"kind": "user", "name": "li"}])}]} + rows = freeform.people_rows(c.with_graph(spec, graph)) + assert [(r["kind"], r["slot"], r["path"]) for r in rows] == [ + ("slot", "finance", "/people/0/who"), ("slot", "director", "/people/1/who"), + ("initiator", None, None), ("expression", None, None)] + assert rows[0]["label"] == "「初审」、「复审」" and rows[0]["detail"] == "「初审」处理;「复审」处理" + assert rows[1]["detail"] == "「初审」超时升级" and rows[0]["who"] == [{"kind": "user", "name": "zhang"}] + issues = blueprint_issues(spec, for_="publish", graph=graph) + unbound = [i for i in issues if i["code"] == "bp.people_unbound"] + assert [(i["path"], i["slot"], i["level"]) for i in unbound] == [("/people/1/who", "director", "error")] + assert [i["level"] for i in blueprint_issues(spec, for_="trial", graph=graph) if i["code"] == "bp.people_unbound"] \ + == ["warning"], "试运行时待办派给试运行的人自己,不挡" + stale = [i for i in issues if i["code"] == "bp.template_mismatch" and "gone" in i["message"]] + assert stale and stale[0]["level"] == "warning" + assert freeform.people_rows(c.with_graph(get_template("freeform").example(), freeform.example_graph())) == [] diff --git a/backend/tests/test_publish_plan.py b/backend/tests/test_publish_plan.py index 00afa3ea..4fcdf785 100644 --- a/backend/tests/test_publish_plan.py +++ b/backend/tests/test_publish_plan.py @@ -218,8 +218,12 @@ async def test_a_process_with_an_unbound_step_stops_at_preflight(client): assert (await client.post(f"/api/blueprints/{bp['id']}/instantiate")).status_code == 200 plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() assert plan["ok"] is False - unbound = [p for p in plan["problems"] if p["code"] == "app.slot_unbound"] - assert unbound and unbound[0]["plain"]["who"] == "you" and "谁来做" in unbound[0]["plain"]["action"] + # 自由形按导入的图列出「谁来做」(05-已知遗留 (d)):会签的 finance、超时升级的 director 各一行,没绑人报在那一行上; + # 应用检查说的是同一件事(app.slot_unbound),不再重复列——它指的「谁来做」以前在自由形蓝图上不存在 + unbound = {p["path"]: p for p in plan["problems"] if p["code"] == "bp.people_unbound"} + assert set(unbound) == {"/people/0/who", "/people/1/who"} + assert unbound["/people/0/who"]["plain"]["who"] == "you" and "谁来做" in unbound["/people/0/who"]["plain"]["action"] + assert "app.slot_unbound" not in {p["code"] for p in plan["problems"]} # 流程类不跑第一次;已发布的那一版按哈希复用,不另存 assert plan["options"]["first_run"] is False summary = {x["step"]: x["text"] for x in plan["summary"]} @@ -255,6 +259,59 @@ async def erp_write(): await registry.refresh_cache(session) +async def test_a_freeform_blueprint_binds_who_does_each_step_of_the_imported_graph(client, erp_write): + """从已发布的「财务审批(岗位 finance)+ 写回(没登记查询)」工作流建自由形蓝图(05-已知遗留 (d)):卡片上按图列出两行 + ——finance 和写入结果不明时的核实人;不选人时发布单在这两行上报 bp.people_unbound,不再有指不到卡片的 app.slot_unbound / + app.reconciler_unbound;选好人之后绑到应用的岗位,发布单不再挡。卡片上只定由谁做,改会签被拒(在画布上改)。""" + from app.blueprints.publish_plan import bindings_of + + graph = {"nodes": [ + s.node("start", "input", "发起", fields=[{"name": "amount", "type": "number"}]), + s.node("review", "human", "财务审批", mode="approve", title="审一下", assignee={"kind": "slot", "slot": "finance"}), + s.node("pay", "tool", "写回报销单", tool=erp_write, args={}), + s.node("done", "output", "完成", fields=[{"name": "结论", "value": "已写回"}])], + "edges": [{"source": "start", "target": "review"}, + {"source": "review", "target": "pay", "sourceHandle": "approved"}, + {"source": "pay", "target": "done"}]} + wf_id = await s.published_workflow(graph, f"写回-{uuid.uuid4().hex[:4]}", description="报销写回") + bp = (await client.post("/api/blueprints", json={"source": {"kind": "workflow_version", "id": wf_id}, + "scope": "shared"})).json() + await s.edit_spec(bp["id"], purpose=s.item("报销审批后写回")) + assert (await client.post(f"/api/blueprints/{bp['id']}/instantiate")).status_code == 200 + out = (await client.get(f"/api/blueprints/{bp['id']}")).json() + rows = out["derived_people"] + assert [(r["kind"], r["slot"], r["path"], r["who"]) for r in rows] == [ + ("slot", "finance", "/people/0/who", None), ("reconciler", "reconciler", "/writeback/reconciler", None)] + assert rows[0]["label"] == "「财务审批」" and rows[0]["detail"] == "「财务审批」处理" + assert rows[1]["detail"] == "「写回报销单」写入结果不明时去核实" + + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + assert plan["ok"] is False + codes = [p["code"] for p in plan["problems"]] + assert sorted(p["path"] for p in plan["problems"] if p["code"] == "bp.people_unbound") == [ + "/people/0/who", "/writeback/reconciler"] + assert "app.slot_unbound" not in codes and "app.reconciler_unbound" not in codes + summary_you = [p for p in plan["problems"] if p["code"] == "bp.people_unbound"] + assert all(p["who"] == "you" for p in summary_you) + + refused = await client.patch(f"/api/blueprints/{bp['id']}", json={"ops": [ + {"op": "bp_set", "path": "/people/0/policy", "value": {"kind": "all"}}]}) + assert refused.status_code == 422 and refused.json()["code"] == "bp.template_mismatch" + assert "在画布上改" in refused.json()["detail"] + r = await client.patch(f"/api/blueprints/{bp['id']}", json={"ops": [ + {"op": "bp_set", "path": "/people/0/who", "value": [{"kind": "user", "name": "zhang"}]}, + {"op": "bp_set", "path": "/writeback/reconciler", "value": [{"kind": "group", "name": "财务组"}]}]}) + assert r.status_code == 200, r.text + rows = r.json()["derived_people"] + assert rows[0]["who"] == [{"kind": "user", "name": "zhang"}] and rows[1]["who"] == [{"kind": "group", "name": "财务组"}] + assert not [i for i in r.json()["issues"] if i["code"] == "bp.people_unbound"] + assert bindings_of(await s.blueprint(bp["id"]))["slots"] == { + "finance": [{"kind": "user", "name": "zhang"}], "reconciler": [{"kind": "group", "name": "财务组"}]} + plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() + codes = [p["code"] for p in plan["problems"]] + assert "bp.people_unbound" not in codes and "app.slot_unbound" not in codes and "app.reconciler_unbound" not in codes + + async def test_the_reconciler_comes_from_the_writeback_card(client, erp_write): """审批通过后写回一项没登记查询的能力:结果不明时要人核实。发布单只列一条、指到「写回哪里」卡片上那一项(应用检查说的 核实岗位没绑、写入没人核实是同一件事,不再重复列);在卡片上选了人,绑到应用的核实岗位,这几条都不再有。""" @@ -524,8 +581,8 @@ async def test_problems_are_split_into_three_kinds(client): plan = (await client.post(f"/api/blueprints/{bp['id']}/publish-plan", json={"level": "published"})).json() assert all(p["who"] in ("you", "assistant", "admin") for p in plan["problems"]) assert {p["source"] for p in plan["problems"]} <= {"blueprint", "plan", "workflow", "schedule", "app", "grants"} - unbound = next(p for p in plan["problems"] if p["code"] == "app.slot_unbound") - assert unbound["who"] == "you" and unbound["source"] == "app" + unbound = next(p for p in plan["problems"] if p["code"] == "bp.people_unbound") + assert unbound["who"] == "you" and unbound["source"] == "blueprint" # --------------------------------------------------------------------------