feat(position-roundtable): add delivery rejection workflow

This commit is contained in:
fengxiangdebaozi committed 2026-07-21 20:16:52 +08:00
1 parent 2ca8a23102
commit 1cd99a5a90
9 files changed
+1422 -148

No files matched your search

@@ -9,6 +9,7 @@ messages and artifacts stay in the established LangGraph thread stores.
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -52,6 +53,9 @@ class NodeResponse(BaseModel):
artifact_manifest: list[dict[str, Any]] = Field(default_factory=list)
revision: int = 0
upstream_revision: dict[str, Any] | None = None
rejection_count: int = 0
last_rejection: dict[str, Any] | None = None
invalidated_by: str | None = None
created_at: str | None = None
updated_at: str | None = None
@@ -64,6 +68,8 @@ class SessionResponse(BaseModel):
chain_snapshot: dict[str, Any] | None = None
intent_thread_id: str | None = None
intent_snapshot: dict[str, Any] | None = None
summary_snapshot: dict[str, Any] | None = None
action_plan_snapshot: dict[str, Any] | None = None
status: str
created_at: str | None = None
updated_at: str | None = None
@@ -101,6 +107,11 @@ class CompleteTurnRequest(BaseModel):
upstream_revision: dict[str, Any] | None = None
class RejectNodeRequest(BaseModel):
title: str = Field(min_length=1, max_length=120)
reason: str = Field(min_length=1, max_length=5_000)
def _current_user_id(request: Request) -> str:
user = getattr(request.state, "user", None)
return str(user.id) if user is not None else get_effective_user_id()
@@ -229,6 +240,175 @@ def _truncate_text(value: Any, limit: int) -> str:
return f"{text[:limit]}\n…(已按交接上下文长度截断)"
def _text_from_keys(source: dict[str, Any], keys: list[str], fallback: str = "") -> str:
for key in keys:
value = source.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return fallback
def _seat_meta(session: dict[str, Any], node: dict[str, Any]) -> tuple[str, str]:
chain = session.get("chain_snapshot") if isinstance(session.get("chain_snapshot"), dict) else {}
seats = chain.get("seats") if isinstance(chain.get("seats"), list) else []
seat = next(
(
item
for item in seats
if isinstance(item, dict) and str(item.get("agent_id") or "") == str(node.get("agent_id") or "")
),
{},
)
agent_name = str(seat.get("name") or node.get("agent_id") or "未命名智能体")
position_id = str(node.get("position_id") or seat.get("position_id") or "未配置岗位")
return agent_name, position_id
def _delivered_nodes(nodes: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [node for node in nodes if node.get("status") == "done"]
def _all_nodes_delivered(nodes: list[dict[str, Any]]) -> bool:
return bool(nodes) and all(node.get("status") == "done" for node in nodes)
def _artifact_lines(node: dict[str, Any]) -> list[str]:
artifacts = node.get("artifact_manifest")
if not isinstance(artifacts, list) or not artifacts:
return []
lines: list[str] = []
for artifact in artifacts[:8]:
if not isinstance(artifact, dict):
continue
name = artifact.get("name") or artifact.get("filename") or artifact.get("path") or "未命名产物"
path = artifact.get("path") or artifact.get("artifact_url") or ""
lines.append(f" - {name}{f'({path})' if path else ''}")
return lines
def _build_summary_snapshot(session: dict[str, Any], nodes: list[dict[str, Any]]) -> dict[str, Any]:
now = datetime.now(UTC).isoformat()
task = session.get("task_snapshot") if isinstance(session.get("task_snapshot"), dict) else {}
intent = session.get("intent_snapshot") if isinstance(session.get("intent_snapshot"), dict) else {}
title = _text_from_keys(task, ["title", "taskName", "name"], "未命名任务")
direction = _text_from_keys(task, ["direction", "taskDirection", "category"], "未填写")
description = _text_from_keys(task, ["description", "taskContent", "overview", "content"], "暂无任务描述")
objective = _text_from_keys(intent, ["objective", "goal"], "暂无意图结论")
constraints = intent.get("constraints") if isinstance(intent.get("constraints"), list) else []
lines = [
"# 岗位会商方案总结报告",
"",
f"生成时间:{now}",
"",
"## 一、任务概况",
"",
f"- 任务名称:{title}",
f"- 任务方向:{direction}",
f"- 任务描述:{description}",
"",
"## 二、意图理解",
"",
f"- 核心目标:{objective}",
]
if constraints:
lines.append("- 关键约束:")
lines.extend(f" - {item}" for item in constraints if isinstance(item, str) and item.strip())
lines.extend(["", "## 三、岗位交付汇总", ""])
for index, node in enumerate(_delivered_nodes(nodes), start=1):
agent_name, position_id = _seat_meta(session, node)
answer = _truncate_text(node.get("latest_answer"), 1_200) or "暂无文本回答"
lines.extend(
[
f"### {index}. {agent_name}",
"",
f"- 岗位:{position_id}",
f"- 节点版本:第 {node.get('revision', 0)} 版",
"",
answer,
"",
]
)
artifacts = _artifact_lines(node)
if artifacts:
lines.extend(["产物文件:", *artifacts, ""])
lines.extend(
[
"## 四、综合判断",
"",
"本报告基于当前所有有效岗位交付产物自动汇总生成,可作为后续行动规划的输入材料。若任一前序岗位产物被驳回,本报告将自动标记为失效并需要重新生成。",
]
)
return {
"kind": "summary",
"status": "done",
"title": "岗位会商方案总结报告",
"content": "\n".join(lines),
"generated_at": now,
"source_revisions": {node["node_key"]: node.get("revision", 0) for node in _delivered_nodes(nodes)},
}
def _build_action_plan_snapshot(session: dict[str, Any], nodes: list[dict[str, Any]]) -> dict[str, Any]:
now = datetime.now(UTC).isoformat()
summary = session.get("summary_snapshot") if isinstance(session.get("summary_snapshot"), dict) else {}
delivered = _delivered_nodes(nodes)
tasks: list[dict[str, Any]] = []
for index, node in enumerate(delivered, start=1):
agent_name, position_id = _seat_meta(session, node)
tasks.append(
{
"id": f"subtask-{index:02d}",
"title": f"落实{agent_name}交付建议",
"owner_position": position_id,
"basis_node": node.get("node_key"),
"deliverable": f"{agent_name}整改/执行清单",
"acceptance": "补齐输入依据,形成可验证的阶段成果并回填岗位会商产物。",
}
)
lines = [
"# 岗位会商行动规划",
"",
f"生成时间:{now}",
"",
"## 一、规划依据",
"",
f"- 方案总结:{summary.get('title') or '岗位会商方案总结报告'}",
f"- 有效岗位产物数量:{len(delivered)}",
"",
"## 二、子任务拆解",
"",
]
for task in tasks:
lines.extend(
[
f"### {task['id']} {task['title']}",
"",
f"- 建议责任岗位:{task['owner_position']}",
f"- 输入依据节点:{task['basis_node']}",
f"- 交付物:{task['deliverable']}",
f"- 验收标准:{task['acceptance']}",
"",
]
)
lines.extend(
[
"## 三、执行提示",
"",
"若前序岗位产物被驳回,本行动规划会自动失效;请先完成被驳回节点及后续节点的重新交付,再重新生成行动规划。",
]
)
return {
"kind": "action_plan",
"status": "done",
"title": "岗位会商行动规划",
"content": "\n".join(lines),
"generated_at": now,
"source_revisions": {node["node_key"]: node.get("revision", 0) for node in delivered},
"subtasks": tasks,
}
def _artifact_refs(artifacts: Any) -> list[dict[str, Any]]:
if not isinstance(artifacts, list):
return []
@@ -342,6 +522,8 @@ async def _handoff_context(request: Request, session_id: str, node_key: str) ->
raise HTTPException(status_code=404, detail="Position roundtable node not found")
if current["status"] == "locked":
raise HTTPException(status_code=409, detail="上游节点尚未完成,当前节点未解锁")
if current.get("invalidated_by"):
raise HTTPException(status_code=409, detail="上游产物已被驳回或重做,当前节点需等待前序节点重新完成")
# Same-stage nodes are intentionally excluded. The business chain only
# hands off completed previous stages, in stage/seat order.
@@ -350,7 +532,7 @@ async def _handoff_context(request: Request, session_id: str, node_key: str) ->
node
for node in nodes
if node["stage_index"] < current["stage_index"]
and node["status"] in {"done", "stale"}
and node["status"] == "done"
]
upstream_nodes: list[dict[str, Any]] = []
for index, node in enumerate(upstream_candidates):
@@ -509,6 +691,8 @@ async def bind_node_thread(
raise HTTPException(status_code=404, detail="Position roundtable node not found")
if current["status"] == "locked":
raise HTTPException(status_code=409, detail="上游节点尚未完成,当前节点未解锁")
if current.get("invalidated_by"):
raise HTTPException(status_code=409, detail="上游产物已被驳回或重做,当前节点需等待前序节点重新完成")
if current.get("thread_id") and current["thread_id"] != body.thread_id:
raise HTTPException(status_code=409, detail="该节点已绑定另一条对话线程")
row = await store.update_node(
@@ -537,6 +721,8 @@ async def complete_node_turn(
raise HTTPException(status_code=404, detail="Position roundtable node not found")
if node["status"] == "locked":
raise HTTPException(status_code=409, detail="上游节点尚未完成,当前节点未解锁")
if node.get("invalidated_by"):
raise HTTPException(status_code=409, detail="上游产物已被驳回或重做,当前节点需等待前序节点重新完成")
row = await store.update_node(
session_id,
node_key,
@@ -545,6 +731,7 @@ async def complete_node_turn(
latest_answer=body.latest_answer,
artifact_manifest=body.artifact_manifest,
upstream_revision=body.upstream_revision,
invalidated_by=None,
increment_revision=True,
)
if row is None:
@@ -562,13 +749,19 @@ async def complete_node_turn(
for downstream in nodes:
if (
downstream["stage_index"] > row["stage_index"]
and downstream["status"] in {"ready", "running", "done", "stale"}
and downstream["status"] in {"ready", "running", "done", "stale", "rejected", "error"}
):
has_material = (
downstream.get("revision", 0) > 0
or bool(downstream.get("latest_answer"))
or bool(downstream.get("artifact_manifest"))
)
await store.update_node(
session_id,
downstream["node_key"],
user_id,
status="stale",
status="stale" if has_material else "locked",
invalidated_by=row["node_key"],
)
nodes = await store.list_nodes(session_id, user_id) or []
@@ -579,16 +772,93 @@ async def complete_node_turn(
if current_stage and all(item["status"] == "done" for item in current_stage) and later_stages:
next_stage = later_stages[0]
for next_node in nodes:
if next_node["stage_index"] == next_stage and next_node["status"] == "locked":
if next_node["stage_index"] == next_stage and next_node["status"] in {"locked", "stale"}:
await store.update_node(
session_id,
next_node["node_key"],
user_id,
status="ready",
status="ready" if next_node["status"] == "locked" else "stale",
invalidated_by=None,
)
return _project_node(row)
@router.post("/sessions/{session_id}/nodes/{node_key}/reject", response_model=SessionDetailResponse)
async def reject_node(
request: Request, session_id: str, node_key: str, body: RejectNodeRequest
) -> SessionDetailResponse:
title = body.title.strip()
reason = body.reason.strip()
if not title or not reason:
raise HTTPException(status_code=400, detail="驳回标题和理由不能为空")
store, user_id, _ = await _require_writable_session(request, session_id)
current = await store.get_node(session_id, node_key, user_id)
if current is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
if current["status"] == "locked":
raise HTTPException(status_code=409, detail="当前节点尚未解锁,暂无可驳回的交付产物")
if current.get("revision", 0) <= 0 and not current.get("latest_answer") and not current.get("artifact_manifest"):
raise HTTPException(status_code=409, detail="当前节点暂无可驳回的交付产物")
rejected = await store.reject_node(
session_id,
node_key,
user_id,
title=title,
reason=reason,
rejected_by=user_id,
)
if rejected is None:
raise HTTPException(status_code=404, detail="Position roundtable node not found")
row, node_rows = rejected
return SessionDetailResponse(**row, nodes=[_project_node(node) for node in node_rows])
@router.post("/sessions/{session_id}/summary/start", response_model=SessionDetailResponse)
async def start_summary(request: Request, session_id: str) -> SessionDetailResponse:
store, user_id, session = await _require_writable_session(request, session_id)
nodes = await store.list_nodes(session_id, user_id)
if nodes is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
if not _all_nodes_delivered(nodes):
raise HTTPException(status_code=409, detail="所有岗位产物完成后才能生成方案总结")
snapshot = _build_summary_snapshot(session, nodes)
row = await store.update_session(
session_id,
user_id,
summary_snapshot=snapshot,
action_plan_snapshot=None,
status="active",
)
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
node_rows = await store.list_nodes(session_id, user_id) or []
return SessionDetailResponse(**row, nodes=[_project_node(node) for node in node_rows])
@router.post("/sessions/{session_id}/action-plan/start", response_model=SessionDetailResponse)
async def start_action_plan(request: Request, session_id: str) -> SessionDetailResponse:
store, user_id, session = await _require_writable_session(request, session_id)
nodes = await store.list_nodes(session_id, user_id)
if nodes is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
if not _all_nodes_delivered(nodes):
raise HTTPException(status_code=409, detail="所有岗位产物完成后才能生成行动规划")
summary = session.get("summary_snapshot")
if not isinstance(summary, dict) or summary.get("status") != "done":
raise HTTPException(status_code=409, detail="请先生成有效的方案总结")
snapshot = _build_action_plan_snapshot(session, nodes)
row = await store.update_session(
session_id,
user_id,
action_plan_snapshot=snapshot,
status="completed",
)
if row is None:
raise HTTPException(status_code=404, detail="Position roundtable session not found")
node_rows = await store.list_nodes(session_id, user_id) or []
return SessionDetailResponse(**row, nodes=[_project_node(node) for node in node_rows])
@router.get("/sessions/{session_id}/results", response_model=list[NodeResponse])
async def list_results(request: Request, session_id: str) -> list[NodeResponse]:
rows = await _get_store(request).list_results(session_id, _current_user_id(request))