端到端验收修复与指标出具:

- 身份与工具:登录页建第一个管理员(认人接口的 401 说明能不能建);搭建者有只读的人和组名录,选人给候选并核对名字;授权三行带标题;端点请求头名校验(空名、非法名存不进、发不出时说清原因);写入能力在工具页试运行一律演练、不发送,HTTP 状态照实说成败;写记忆不算只读、查询能力只能选同一端点上的只读能力;审批与遮罩的说法和实际规则一致;开登录时不要署名、导入和发布记登录的人;使用者不显示推演等只给搭建者的操作,403 按是否开登录说话;登录页只认一次人
- 流程与实例:图里用到的岗位(派给谁、超时升级给谁、发送确认派给谁)全部派生、没绑人的发布时报错;写外部系统的参数按能力声明的类型收拢后再算哈希和发送,收不成就不发;发起人的实例页只看这一步的状态,处理人才给待办卡;会签进度带登录核实和时间,升级后照实写规则;实例状态写流程的结论(已退回、未确认、等待核实写入结果),核实生效后不再挂失败原因;流程应用首页不派生最近封存运行的结果块,看板没数据时是安静的空态;样例⑩的金额带类型和下限、待办标题带金额,表单上下限前后端一起生效
- 看板与证据:定时任务模板加 ISO 周、上一 ISO 周、本月、上月;出处链穿过原样解析查询结果的整形节点,追不到原始数据的照实说停在哪里,样例⑨改用 cell();应用首页和版本历史都能做成应用;指标块单位不重复;版本列表带退役说明;定时任务页头跟着刷新;删视图要确认、新视图能起名;编辑器属性用中文名、术语带解释
- 指标出具(用户 2026-10-15 拍板):契约只写「指标来自」、上游没有报告撰写节点、成果里没有模型写的话时按指标出具——必需指标齐、指标输入追到原始数据、成果字段里的数回指得上才完整出具;受管级要求每个指标静态地追到原始数据(governed.metric_untraced);出具横幅和应用印章写明按指标
- 受管工作流降为已发布只给管理员(Q8 顺延,服务端同样拦);工作流接口带当前发布版的级别,画布上改过之后也认得出受管工作流
This commit is contained in:
ThearchyHelios
2026-10-15 07:15:37 +08:00
parent 5d42ffb62b
commit 941723b17c
116 changed files with 4917 additions and 631 deletions
+164 -29
View File
@@ -3,8 +3,8 @@
ActionRecord 是权威记录:先写记录再发送,结果未知永不自动重发。调用工具节点(engine/nodes/tools.py)在能力治理后
效果为 write 时走这里:
1. prepare:渲染好的参数 → payload_hash;按 action_key 查记录——已生效的交回存下的回执,已发出 / 结果未知的挂起,
失败且有人核实为「未生效,重新发送」的 attempt 加一;
1. prepare:先按 action_key 查记录——已生效的交回存下的回执,已发出 / 结果未知的挂起,失败且有人核实为「未生效,重新
发送」的 attempt 加一;真要发送时才把渲染好的参数按能力的参数定义收成声明的类型(typed_args)→ payload_hash;
2. (节点)需要确认时在 tool.start 之前中断(kind=action_confirm),恢复后重算哈希,对不上拒绝发送;
3. send:先写 pending 并提交 → 改成 sent 并提交 → 发请求(幂等键 {action_key}:{attempt})→ 2xx confirmed(回执落工件)、
4xx(429 除外)failed、超时 / 中断 / 5xx unknown(抛 ActionPending,运行挂起、不封存)。
@@ -21,7 +21,10 @@ from __future__ import annotations
import copy
import hashlib
import json
import logging
import math
import re
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any, Callable
@@ -90,6 +93,130 @@ def masked(doc: Any, pointers: list[str]) -> Any:
return out
# --------------------------------------------------------------------------
# 参数按声明的类型收好
# --------------------------------------------------------------------------
#: 参数类型的叫法(收不成声明的类型时说给人听)
_TYPE_TEXT = {"number": "数", "integer": "整数", "boolean": "是或否(true / false)", "object": "对象(JSON)",
"array": "列表(JSON)"}
_INTEGER = re.compile(r"[+-]?\d+")
#: 文字里的数:和前端表单读数的写法一样(lib/schemaForm),不认 nan、inf、带下划线的
_NUMBER = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?")
class _Untyped(Exception):
def __init__(self, where: str, kind: str, value: Any) -> None:
super().__init__(where)
self.where, self.kind, self.value = where, kind, value
def typed_args(capability: Any, args: dict[str, Any]) -> dict[str, Any]:
"""按能力登记的参数定义(params_schema,JSON Schema)把渲染好的参数收成声明的类型。确认卡的预览、内容指纹、发出去的
请求都用收好的这一份:看过的就是发出去的。
模板渲染出来的一律是文字:{"amount": "{{ input.amount }}"} 得到 "1280.5",照原样发,外部系统收到的金额是字符串。
这里只收 number / integer / boolean,以及 object / array(是 JSON 文字的先解开,再按里面的定义逐层收);声明为文字、
没写类型的原样不动,参数定义里没有的键也原样不动——没登记参数定义的能力发出去的和以前一字不差。
可选参数渲染出来是空的(模板没取到值):不发这个键,不拿空串冒充数;必填的空着照实失败。
收不成("abc" 填给数)抛 ActionFailed,说清是哪个参数,一次都不发。"""
schema = getattr(capability, "params_schema", None)
if not isinstance(args, dict) or not isinstance(schema, dict) or not isinstance(schema.get("properties"), dict):
return args
try:
return _typed_object(schema, args, "")
except _Untyped as e:
title = getattr(capability, "title", None) or capability.name
shown = e.value if isinstance(e.value, str) else json.dumps(e.value, ensure_ascii=False, default=str)
if e.kind == "required":
raise ActionFailed(f"「{title}」的必填参数 {e.where} 是空的(参数模板没有取到值),没有发送。"
"请检查节点里的参数和上游填的值") from e
raise ActionFailed(f"「{title}」的参数 {e.where} 应为{_TYPE_TEXT.get(e.kind, e.kind)},实际是「{shown[:80]}」,"
"没有发送。请检查节点里的参数和上游填的值") from e
def _kinds(spec: dict[str, Any]) -> list[str]:
kind = spec.get("type")
if isinstance(kind, list):
return [k for k in kind if isinstance(k, str)]
return [kind] if isinstance(kind, str) else []
def _typed_object(spec: dict[str, Any], obj: dict[str, Any], path: str) -> dict[str, Any]:
props = spec.get("properties") if isinstance(spec.get("properties"), dict) else {}
required = set(spec.get("required") or []) if isinstance(spec.get("required"), list) else set()
out: dict[str, Any] = {}
for key, value in obj.items():
sub = props.get(key)
where = f"{path}.{key}" if path else str(key)
kinds = _kinds(sub) if isinstance(sub, dict) else []
blank = value is None or (isinstance(value, str) and not value.strip())
if blank and kinds and "string" not in kinds:
if "null" in kinds:
out[key] = None
elif key in required:
raise _Untyped(where, "required", value)
continue
out[key] = _typed(value, sub, where) if isinstance(sub, dict) else value
return out
def _typed(value: Any, spec: dict[str, Any], where: str) -> Any:
kinds = [k for k in _kinds(spec) if k != "null"]
if not kinds or ("string" in kinds and isinstance(value, str)):
return value
first: _Untyped | None = None
for kind in kinds:
try:
return _as(kind, value, spec, where)
except _Untyped as e:
first = first or e
raise first or _Untyped(where, kinds[0], value)
def _as(kind: str, value: Any, spec: dict[str, Any], where: str) -> Any:
if kind == "string":
return value
if kind in ("number", "integer"):
number: Any = None
if isinstance(value, (int, float)) and not isinstance(value, bool):
number = value
elif isinstance(value, str):
text = value.strip()
if _INTEGER.fullmatch(text):
number = int(text)
elif _NUMBER.fullmatch(text):
number = float(text)
if number is None or isinstance(number, float) and not math.isfinite(number):
raise _Untyped(where, kind, value)
if kind == "integer":
if isinstance(number, float) and not number.is_integer():
raise _Untyped(where, kind, value)
return int(number)
return number
if kind == "boolean":
if isinstance(value, bool):
return value
if isinstance(value, str) and value.strip().lower() in ("true", "false"):
return value.strip().lower() == "true"
raise _Untyped(where, kind, value)
if kind in ("object", "array"):
if isinstance(value, str):
try:
value = json.loads(value)
except ValueError:
raise _Untyped(where, kind, value) from None
if kind == "object" and isinstance(value, dict):
return _typed_object(spec, value, where)
if kind == "array" and isinstance(value, list):
items = spec.get("items")
if not isinstance(items, dict):
return value
return [_typed(v, items, f"{where}[{i}]") for i, v in enumerate(value)]
raise _Untyped(where, kind, value)
return value
# --------------------------------------------------------------------------
# 准备与发送(调用工具节点用)
# --------------------------------------------------------------------------
@@ -107,6 +234,8 @@ class Prepared:
#: 已经生效(或演练过)的:存下的回执,节点直接交回,不再发
receipt: dict[str, Any] | None = None
run: dict[str, Any] = field(default_factory=dict)
#: 按参数定义收好类型的参数(typed_args):哈希、预览按它算,send 发的也是它
args: dict[str, Any] = field(default_factory=dict)
@property
def idem_key(self) -> str:
@@ -121,47 +250,53 @@ async def latest(session: AsyncSession, key: str) -> ActionRecord | None:
async def prepare(*, run_id: str, node_id: str, exec_no: int, capability: Any, args: dict[str, Any]) -> Prepared:
"""节点每次执行都先走这里:按 action_key 查记录,决定发不发、第几次发、走哪个环境。
sent / unknown 抛 ActionPending(不发);failed 且没有人核实为「重新发送」的抛 ActionFailed。"""
sent / unknown 抛 ActionPending(不发);failed 且没有人核实为「重新发送」的抛 ActionFailed。先查记录再收类型:已生效
(演练过)的交回存下的回执、已发出 / 结果未知的挂起,都和这一次渲染出来的参数无关——发出之后能力的参数定义改了、手上的
值收不成声明的类型(升级时停在结果未知的运行),已经生效的写入照样交回回执,不判成失败。只有真要发送(头一次、记下了
还没发出去、核实为未生效要重发)时才按参数定义收成声明的类型(typed_args),收不成的抛 ActionFailed;之后的哈希、
预览、发送都用收好的那一份(Prepared.args)。"""
from app.capabilities.registry import masked_paths
name = capability.name
key = action_key(run_id, node_id, exec_no)
digest = payload_hash(name, args)
async with SessionLocal() as session:
run = await session.get(Run, run_id)
endpoint = await _endpoint(session, capability)
prev = await latest(session, key)
facts = {"app_id": run.app_id, "workflow_id": run.workflow_id, "workflow_version": run.version,
"graph_hash": run.version_hash, "started_by": run.started_by} if run is not None else {}
endpoint_name = endpoint.name if endpoint is not None else None
if prev is not None and prev.state in ("confirmed", "simulated"):
# 交回的是生效的那一次:指纹、预览、环境、第几次都照记录,不按这一次的参数重算
return Prepared(key=key, attempt=prev.attempt, payload_hash=prev.payload_hash, preview=prev.preview,
environment=prev.environment, endpoint=endpoint_name, receipt=_receipt_of(prev), run=facts)
if prev is not None and prev.state in ("sent", "unknown"):
raise ActionPending(prev.id)
formal = run is not None and run.run_class == "formal"
attempt = 1
environment = "prod" if formal else "test" if endpoint is not None and (endpoint.environments or {}).get("test") \
else "simulated"
prep = Prepared(key=key, attempt=1, payload_hash=digest, preview=masked(args, masked_paths(capability)),
environment=environment, endpoint=endpoint.name if endpoint is not None else None,
run={"app_id": run.app_id, "workflow_id": run.workflow_id, "workflow_version": run.version,
"graph_hash": run.version_hash, "started_by": run.started_by} if run is not None else {})
if prev is None:
return prep
if prev.state in ("confirmed", "simulated"):
prep.receipt = _receipt_of(prev)
return prep
if prev.state in ("sent", "unknown"):
raise ActionPending(prev.id)
if prev.state == "pending":
if prev is not None and prev.state == "pending":
# 记下了、还没发出去(发之前进程没了):照原样再发,同一个幂等键
prep.attempt, prep.environment = prev.attempt, prev.environment
return prep
outcome = (prev.resolution or {}).get("outcome")
if outcome == "resend":
prep.attempt = prev.attempt + 1
return prep
if outcome == "abandon":
raise ActionFailed(f"「{name}」这次写入核实为未生效,已选择放弃发送")
raise ActionFailed(f"「{name}」上一次发送被外部系统拒绝({prev.error or '未生效'}),不会自动重发。"
"请检查上游的数据后重新发起运行")
attempt, environment = prev.attempt, prev.environment
elif prev is not None:
outcome = (prev.resolution or {}).get("outcome")
if outcome == "abandon":
raise ActionFailed(f"「{name}」这次写入核实为未生效,已选择放弃发送")
if outcome != "resend":
raise ActionFailed(f"「{name}」上一次发送被外部系统拒绝({prev.error or '未生效'}),不会自动重发。"
"请检查上游的数据后重新发起运行")
attempt = prev.attempt + 1
args = typed_args(capability, args)
return Prepared(key=key, attempt=attempt, payload_hash=payload_hash(name, args),
preview=masked(args, masked_paths(capability)), environment=environment, endpoint=endpoint_name,
run=facts, args=args)
async def send(prep: Prepared, capability: Any, args: dict[str, Any], *, run_id: str, node_id: str, exec_no: int,
async def send(prep: Prepared, capability: Any, *, run_id: str, node_id: str, exec_no: int,
emit: Callable[..., None], on_behalf: str | dict[str, Any] | None = None) -> dict[str, Any]:
"""先写记录再发送。返回节点的产出;结果未知抛 ActionPending,确定失败抛 ActionFailed。
"""先写记录再发送。返回节点的产出;结果未知抛 ActionPending,确定失败抛 ActionFailed。发的是 prepare 收好类型的
那一份参数(prep.args),和确认卡上的哈希是同一份。
on_behalf 原样交给平台执行器写身份断言:{"sub": 运行的发起人, "act": 确认人}(capabilities.endpoints.on_behalf_parts)。"""
from app.capabilities.registry import endpoint_request, masked_paths
@@ -200,7 +335,7 @@ async def send(prep: Prepared, capability: Any, args: dict[str, Any], *, run_id:
environment=prep.environment)
try:
async with SessionLocal() as session:
result = await endpoint_request(session, capability, args, environment=prep.environment,
result = await endpoint_request(session, capability, prep.args, environment=prep.environment,
idem_key=prep.idem_key, on_behalf=on_behalf, run_id=run_id,
node_id=node_id)
except Exception as e: # noqa: BLE001 - 请求可能已经发出去了:一律按结果未知处理,不能当成失败再发
+70 -7
View File
@@ -221,8 +221,11 @@ async def announce(task_id: str, event: EventType = EventType.TASK_OPENED) -> No
def _matches(a: TaskAssignment, principal: Any) -> bool:
if a.status != "pending":
return False
return a.status == "pending" and _for(a, principal)
def _for(a: TaskAssignment, principal: Any) -> bool:
"""这一份派的是不是这个人(不看回没回复)。"""
if getattr(principal, "mode", "off") == "off":
return True
if a.principal_kind == "user":
@@ -234,6 +237,14 @@ def _matches(a: TaskAssignment, principal: Any) -> bool:
return a.principal_kind == "hook" and principal.at_least("admin")
def handles(rows: list[TaskAssignment], principal: Any) -> bool:
"""这个人是不是这条待办的处理人:有一份没撤回的派给他(已经回复过的也算)。关登录时人人都算。
实例页的待办组件按它分:处理人给待办卡(能处理的给表单),别人只看这一步的状态,不去取待办——待办里带着中断内容
(报告概况、动作预览),按 id 读只给处理人和搭建者以上(visible)。"""
return any(a.status != "withdrawn" and _for(a, principal) for a in rows)
def _pick(task: Task, rows: list[TaskAssignment], principal: Any) -> TaskAssignment:
"""这个人回复的是哪一份。同一个人在一条会签待办上只能投一票(关登录时按自报的署名认,没署名的认不出)。"""
name = principal.username
@@ -344,6 +355,36 @@ def _tally(task: Task, rows: list[TaskAssignment], mine: TaskAssignment, verdict
return "approve" if yes >= m else "reject" if no > n - m else None
def progress(task: Task, rows: list[TaskAssignment]) -> dict[str, Any] | None:
"""会签进度(给人看的那一份,界面照着画):只算批准 / 驳回这一类。口径同 _tally——升级加派的那一份不算进会签人数,
它一人说了算;以前界面把它和原来的人算在一起,升级后写「0/3 已同意」,其实总监一人同意就通过。
voters 是会签的人数:待处理时按没撤回的算;判定之后剩下没回复的都撤回了,按判定那一刻记下的人数(outcome.voters),
老数据没记的按回复过的算。escalation 是升级加派的那几份:升级给的岗位、派给了谁、谁一人定了什么。"""
if task.kind not in VOTING:
return None
policy = task.policy or {"kind": "any"}
own = [a for a in rows if a.source != "escalation"]
said = [(a.response or {}).get("decision") for a in own if a.status == "responded"]
recorded = (task.outcome or {}).get("voters")
if task.status == "pending":
voters = len([a for a in own if a.status != "withdrawn"])
else:
voters = recorded if isinstance(recorded, int) else max(len(said), 1)
kind = policy.get("kind", "any")
need = voters if kind == "all" else min(int(policy.get("m") or 1), voters) if kind == "quorum" else 1
out: dict[str, Any] = {"policy": kind, "voters": voters, "need": need, "agreed": said.count("approve"),
"rejected": said.count("reject")}
escalated = [a for a in rows if a.source == "escalation"]
if escalated:
decider = next((a for a in escalated if a.status == "responded"), None)
out["escalation"] = {"slot": str((task.on_timeout or {}).get("to_slot") or "").strip() or None,
"assignees": [_who(a) for a in escalated],
"decided": (decider.response or {}).get("decision") if decider else None,
"by": decider.responded_by if decider else None}
return out
def _signoffs(rows: list[TaskAssignment]) -> list[dict[str, Any]]:
return [{"by": a.responded_by, "decision": (a.response or {}).get("decision"),
"note": (a.response or {}).get("note") or "", "at": _iso(a.responded_at), "verified": a.verified,
@@ -396,10 +437,12 @@ async def respond(task_id: str, principal: Any, *, decision: Any, values: dict[s
final = {"approved": decided == "approve",
"note": ";".join(s["note"] for s in signoffs if s["note"]),
"signoffs": signoffs, "policy": task.policy}
# 会签人数记在结论里:判定之后没回复的都撤回了,进度要按判定那一刻的人数说(progress)
claimed = await session.execute(
update(Task).where(Task.id == task.id, Task.status == "pending")
.values(status="resolving", resolved_by=principal.username,
outcome={"decision": decided, "by_assignment": mine.id, "signoffs": _signoffs(rows)}))
outcome={"decision": decided, "by_assignment": mine.id, "signoffs": _signoffs(rows),
"voters": len([a for a in voters if a.source != "escalation"])}))
if claimed.rowcount != 1:
await session.rollback()
raise TaskRefused(_closed("resolving"))
@@ -650,7 +693,8 @@ async def _on_timeout(task_id: str, now: datetime) -> int:
spawn(_notify(task_id, "task.reminded", [a.principal for a in pending if a.principal_kind == "user"]))
return 1
if action == "escalate" and task.escalation_level == 0:
slot = str(timeout.get("to_slot") or "")
# 和派生、检查认的是同一个岗位名(apps/tree.slot_refs 去掉了首尾空白)
slot = str(timeout.get("to_slot") or "").strip()
claimed = await session.execute(update(Task).where(
Task.id == task_id, Task.status == "pending", Task.escalation_level == 0)
.values(escalation_level=Task.escalation_level + 1))
@@ -668,8 +712,11 @@ async def _on_timeout(task_id: str, now: datetime) -> int:
return 1
if action != "reject" or task.due_at is None or _aware(task.due_at) > now:
return 0
rows = (await _assignments(session, [task_id])).get(task_id, [])
voters = len([a for a in rows if a.status != "withdrawn" and a.source != "escalation"])
claimed = await session.execute(update(Task).where(Task.id == task_id, Task.status == "pending")
.values(status="resolving", outcome={"decision": "expired_reject"}))
.values(status="resolving",
outcome={"decision": "expired_reject", "voters": voters}))
await session.commit()
if claimed.rowcount != 1:
return 0
@@ -858,7 +905,8 @@ async def _describe(session: AsyncSession, tasks: list[Task], principal: Any) ->
approvals = {a.id: a for a in (await session.execute(
select(Approval).where(Approval.id.in_([t.approval_id for t in tasks if t.approval_id])))).scalars()}
runs = {r.id: r for r in (await session.execute(
select(Run.id, Run.workflow_name, Run.graph).where(Run.id.in_({t.run_id for t in tasks})))).all()}
select(Run.id, Run.workflow_name, Run.graph, Run.origin)
.where(Run.id.in_({t.run_id for t in tasks})))).all()}
apps = dict((await session.execute(select(App.id, App.name).where(
App.id.in_({t.app_id for t in tasks if t.app_id})))).all())
out = []
@@ -872,7 +920,10 @@ async def _describe(session: AsyncSession, tasks: list[Task], principal: Any) ->
"id": task.id, "approval_id": task.approval_id, "run_id": task.run_id, "node_id": task.node_id,
"node_label": _node_label(run.graph if run else None, task.node_id),
"app_id": task.app_id, "app_name": apps.get(task.app_id), "app_version": task.app_version,
"workflow_name": run.workflow_name if run else None, "kind": task.kind, "title": task.title,
"workflow_name": run.workflow_name if run else None,
# 实例的标题(应用入口按 instance_title 起的):同一个人工节点的待办标题一样,列表里靠它分开
"instance_title": str((run.origin or {}).get("title") or "") or None if run else None,
"kind": task.kind, "title": task.title,
"form": task.form, "policy": task.policy or {"kind": "any"}, "status": task.status,
"due_at": _iso(task.due_at), "escalation_level": task.escalation_level, "payload": payload,
"assignments": [{
@@ -881,6 +932,8 @@ async def _describe(session: AsyncSession, tasks: list[Task], principal: Any) ->
"decision": (a.response or {}).get("decision"), "verified": a.verified} for a in rows],
"can_respond": task.status == "pending" and any(_matches(a, principal) for a in rows)
and not _voted(task, rows, principal),
"progress": progress(task, rows),
"my_response": my_response(rows, principal),
"outcome": task.outcome, "resolved_by": task.resolved_by, "resolved_at": _iso(task.resolved_at),
"created_at": _iso(task.created_at),
})
@@ -898,6 +951,16 @@ def visible(item: dict[str, Any], principal: Any) -> bool:
for a in item["assignments"])
def my_response(rows: list[TaskAssignment], principal: Any) -> dict[str, Any] | None:
"""这个人在这条待办上的回复(决定、时间、是否登录核实):处理过的人再打开,写「你已处理:同意(时间)」,不写
「没有派给你」。认不出是谁(关登录又没署名)的是 None。"""
name = getattr(principal, "username", None)
mine = next((a for a in rows if name and a.status == "responded" and a.responded_by == name), None)
if mine is None:
return None
return {"decision": (mine.response or {}).get("decision"), "at": _iso(mine.responded_at), "verified": mine.verified}
def _voted(task: Task, rows: list[TaskAssignment], principal: Any) -> bool:
name = getattr(principal, "username", None)
return bool(name) and task.kind in VOTING and any(a.status == "responded" and a.responded_by == name