diff --git a/api/core/workflow_copilot/handlers_build.py b/api/core/workflow_copilot/handlers_build.py index e2ca127beda..b51d5c46e34 100644 --- a/api/core/workflow_copilot/handlers_build.py +++ b/api/core/workflow_copilot/handlers_build.py @@ -13,6 +13,8 @@ import uuid from core.workflow_copilot.contract import ( AssistantTurnItem, ChallengeCard, + ChangeSetCard, + CheckpointCard, ConflictPolicyOption, DecisionItem, FormCard, @@ -20,13 +22,22 @@ from core.workflow_copilot.contract import ( PlanCard, ResourceSelectCard, Trace, + TraceStep, ) from core.workflow_copilot.handlers_fix import action_string, append_card -from core.workflow_copilot.models import CopilotContext, Session, Turn +from core.workflow_copilot.models import ChangeSet, Checkpoint, CopilotContext, Session, Snapshot, Turn from core.workflow_copilot.runner import Env, Handler, StepResult from core.workflow_copilot.state import PcState -__all__ = ["build_registry", "handle_capability_check", "handle_goal_analysis", "handle_initial_plan"] +__all__ = [ + "build_registry", + "handle_capability_check", + "handle_execution", + "handle_goal_analysis", + "handle_initial_plan", + "handle_plan_approval", + "handle_resource_recommendation", +] def _emit_canvas(env: Env, event: str, **extra) -> None: @@ -175,6 +186,138 @@ def handle_initial_plan(env: Env, turn: Turn, s: Session, fc: CopilotContext) -> ) +def handle_resource_recommendation(env: Env, turn: Turn, s: Session, fc: CopilotContext) -> StepResult: + """(waiting) On ``confirm_resources`` bind resources into plan v2 and + snapshot the pre-build graph as the restore checkpoint (self-minted id so + the CheckpointCard shown at plan_approval carries a real id -- mirrors + handle_verify's self-minted run id). Transition to build.plan_approval.""" + kind = turn.action.kind if turn.action is not None else "" + if kind != "confirm_resources": + return StepResult(next=PcState.BUILD_RESOURCE_RECOMMENDATION, context=fc) + + resource_ids: list[str] = [] + conflict_policy = "" + if turn.action is not None and isinstance(turn.action.payload, dict): + raw_ids = turn.action.payload.get("resource_ids") + if isinstance(raw_ids, list): + resource_ids = [r for r in raw_ids if isinstance(r, str)] + cp = turn.action.payload.get("conflict_policy") + if isinstance(cp, str): + conflict_policy = cp + fc.resource_selection = {"resource_ids": resource_ids, "conflict_policy": conflict_policy} + fc.plan_items = env.agent.bind_resources(list(fc.plan_items), resource_ids, conflict_policy) + fc.plan_version_tag = "v2" + + graph, graph_hash = env.dify.read_graph(s.app_id, turn.actor) + checkpoint = Checkpoint(id=str(uuid.uuid4()), session_id=s.id, state=PcState.BUILD_PLAN_APPROVAL) + env.repo.create_checkpoint(checkpoint, Snapshot(session_id=s.id, hash=graph_hash, graph=graph)) + fc.checkpoint_id = checkpoint.id + fc.last_snapshot_hash = graph_hash + + decision_items = append_card(fc, DecisionItem(text="Confirmed resources")) + plan_items = append_card(fc, PlanCard(title="Build plan", version_tag="v2", items=list(fc.plan_items))) + checkpoint_items = append_card( + fc, CheckpointCard(checkpoint_id=checkpoint.id, label="Pre-build checkpoint", created_at="") + ) + turn_items = append_card( + fc, + AssistantTurnItem( + turn_id=str(uuid.uuid4()), + stage_id="build.plan_approval", + trace=Trace(status="completed", steps=[]), + reply_text="Plan v2 ready for approval.", + cards=["plan", "checkpoint"], + ), + ) + return StepResult( + next=PcState.BUILD_PLAN_APPROVAL, + context=fc, + items=[*decision_items, *plan_items, *checkpoint_items, *turn_items], + ) + + +_BUILD_TRACE_STEPS = [ + TraceStep(id="build-start", label="Create Start node", state="done", tone="success", canvas_event="add_start_node"), + TraceStep( + id="build-knowledge", + label="Create Knowledge Retrieval node", + state="done", + tone="success", + canvas_event="add_knowledge_node", + ), + TraceStep(id="build-llm", label="Create LLM node", state="done", tone="success", canvas_event="add_llm_node"), + TraceStep(id="build-end", label="Create End node", state="done", tone="success", canvas_event="add_output_node"), +] + + +def handle_plan_approval(env: Env, turn: Turn, s: Session, fc: CopilotContext) -> StepResult: + """(waiting) THE BUILD. Only ``approve_repair`` (resolved from approve_plan) + builds: drive apply_repair once with all create_node/connect intents + (node-by-node canvas reveal via env.emit_canvas), emit the change_set + + plan v2.x + assistant_turn(with Trace.steps), transition to build.execution.""" + kind = turn.action.kind if turn.action is not None else "" + if kind != "approve_repair": + return StepResult(next=PcState.BUILD_PLAN_APPROVAL, context=fc) + + _emit_canvas(env, "create_checkpoint") + intents = env.agent.build_nodes(list(fc.plan_items)) + result = env.dify.apply_repair(s.app_id, turn.actor, intents, on_canvas=env.emit_canvas) + fc.last_snapshot_hash = result.new_hash + fc.built_node_ids = [ + intent.args["node_id"] + for intent in intents + if intent.op == "create_node" and isinstance(intent.args.get("node_id"), str) + ] + changes = list(result.changes) if result.changes else list(result.changed_nodes) + scope = result.scope or "structure" + fc.change_set = ChangeSet(changed_nodes=result.changed_nodes, diff="; ".join(changes) or "graph built") + + change_set_items = append_card( + fc, ChangeSetCard(count=len(changes), changes=changes, scope=scope, full_diff_open=False) + ) + plan_items = append_card(fc, PlanCard(title="Build plan", version_tag="v2.1", items=list(fc.plan_items))) + decision_items = append_card(fc, DecisionItem(text="Approved the plan")) + turn_items = append_card( + fc, + AssistantTurnItem( + turn_id=str(uuid.uuid4()), + stage_id="build.execution", + trace=Trace(status="completed", steps=list(_BUILD_TRACE_STEPS)), + reply_text="Workflow built on the canvas.", + cards=["change_set", "plan"], + ), + ) + return StepResult( + next=PcState.BUILD_EXECUTION, + context=fc, + items=[*change_set_items, *plan_items, *decision_items, *turn_items], + ) + + +def handle_execution(env: Env, turn: Turn, s: Session, fc: CopilotContext) -> StepResult: + """(waiting) At rest after the build. ``run_test`` -> build.test_and_repair; + ``revert`` (resolved to ``undo``) -> build.reverted (intent only).""" + kind = turn.action.kind if turn.action is not None else "" + if kind == "undo": + _emit_canvas(env, "revert_checkpoint") + items = append_card(fc, DecisionItem(text="Requested a revert")) + return StepResult(next=PcState.BUILD_REVERTED, context=fc, items=items) + if kind == "run_test": + _emit_canvas(env, "start_test_run") + items = append_card( + fc, + AssistantTurnItem( + turn_id=str(uuid.uuid4()), + stage_id="build.test_and_repair", + trace=Trace(status="running", steps=[]), + reply_text="Running tests.", + cards=[], + ), + ) + return StepResult(next=PcState.BUILD_TEST_AND_REPAIR, context=fc, items=items) + return StepResult(next=PcState.BUILD_EXECUTION, context=fc) + + def build_registry() -> dict[PcState, Handler]: """The Build handler table. Grows across Slice 2 tasks; ``build.complete`` is terminal and intentionally absent (the loop returns before lookup).""" @@ -182,4 +325,7 @@ def build_registry() -> dict[PcState, Handler]: PcState.BUILD_CAPABILITY_CHECK: handle_capability_check, PcState.BUILD_GOAL_ANALYSIS: handle_goal_analysis, PcState.BUILD_INITIAL_PLAN: handle_initial_plan, + PcState.BUILD_RESOURCE_RECOMMENDATION: handle_resource_recommendation, + PcState.BUILD_PLAN_APPROVAL: handle_plan_approval, + PcState.BUILD_EXECUTION: handle_execution, } diff --git a/api/tests/unit_tests/core/workflow_copilot/fakes.py b/api/tests/unit_tests/core/workflow_copilot/fakes.py index 5025ef88314..a29e7cb618c 100644 --- a/api/tests/unit_tests/core/workflow_copilot/fakes.py +++ b/api/tests/unit_tests/core/workflow_copilot/fakes.py @@ -57,8 +57,17 @@ from core.workflow_copilot.models import ( TestInput, ) from core.workflow_copilot.state import PcState +from services.workflow_copilot.graph_ops import ( + apply_connect, + apply_create_node, + apply_delete_node, + apply_insert_between, + apply_set_node_config, + diff_graphs, + validate_intent_args, +) -__all__ = ["FakeDifyPort", "InMemoryRepository", "StubAgent"] +__all__ = ["FakeBuildDifyPort", "FakeDifyPort", "InMemoryRepository", "StubAgent"] # ---- in-memory Repository ---------------------------------------------- @@ -329,3 +338,92 @@ class StubAgent: def propose_build_repair(self, _built_node_ids): return [] + + +# ---- fake DifyPort that actually builds the graph ------------------------- + +_BUILD_APPLY_FNS = { + "set_node_config": apply_set_node_config, + "create_node": apply_create_node, + "delete_node": apply_delete_node, + "connect": apply_connect, + "insert_between": apply_insert_between, +} + +_ADD_NODE_EVENTS = { + "start": "add_start_node", + "knowledge-retrieval": "add_knowledge_node", + "llm": "add_llm_node", + "end": "add_output_node", +} + + +def _fake_canvas_payload(intent: MutationIntent, changed: list[str]) -> dict: + """Replicate services.workflow_copilot.dify_port._canvas_payload without + importing that (SQLAlchemy-heavy) module into the core test fakes.""" + if intent.op == "create_node": + event = _ADD_NODE_EVENTS.get(str(intent.args.get("node_type", "")), "apply_edit_plan") + return {"event": event, "node_id": changed[0] if changed else None} + if intent.op == "connect": + return { + "event": "apply_edit_plan", + "edge": {"source": intent.args.get("from_node"), "target": intent.args.get("to_node")}, + } + if intent.op == "set_node_config": + return {"event": "apply_error_fix", "node_id": intent.args.get("node_id")} + if intent.op == "delete_node": + return {"event": "apply_edit_plan", "node_id": intent.args.get("node_id")} + return {"event": "apply_edit_plan", "node_id": changed[0] if changed else None} + + +class FakeBuildDifyPort: + """A ``DifyPort`` that genuinely applies Build's verbs to an accumulating + in-memory graph via the pure ``graph_ops`` helpers and emits the same + per-intent canvas payloads the real adapter does. Distinct from + ``FakeDifyPort`` (which records intents without applying them) so Build + tests can assert the graph was actually built and the reveal fired.""" + + def __init__(self) -> None: + self.graph: Graph = {"nodes": [], "edges": []} + self.hash: str = "h0" + self.applied: list[MutationIntent] = [] + self.published: bool = False + + def read_graph(self, _app_id: str, _actor: Actor) -> tuple[Graph, str]: + return copy.deepcopy(self.graph), self.hash + + def node_outputs(self, _app_id: str, _actor: Actor, _run_id: str) -> list[NodeOutput]: + return [] + + def apply_repair( + self, + _app_id: str, + _actor: Actor, + intents: list[MutationIntent], + on_canvas: Callable[[dict], None] | None = None, + ) -> ApplyResult: + self.applied.extend(copy.deepcopy(intents)) + before = copy.deepcopy(self.graph) + graph = self.graph + changed_nodes: list[str] = [] + for intent in intents: + validate_intent_args(intent) + apply_fn = _BUILD_APPLY_FNS[intent.op] + graph, changed = apply_fn(graph, **intent.args) + changed_nodes.extend(changed) + if on_canvas is not None: + on_canvas(_fake_canvas_payload(intent, changed)) + self.graph = graph + self.hash = "h1" + if not changed_nodes: + return ApplyResult(changed_nodes=[], new_hash=self.hash, changes=[], scope="") + changes, scope = diff_graphs(before, graph) + return ApplyResult(changed_nodes=changed_nodes, new_hash=self.hash, changes=changes, scope=scope) + + def run_draft( + self, _app_id: str, _actor: Actor, _inputs: Inputs, _on_event: Callable[[NodeEvent], None] + ) -> Run: + return Run(dify_run_id="build-run-1", status="succeeded") + + def publish(self, _app_id: str, _actor: Actor) -> None: + self.published = True diff --git a/api/tests/unit_tests/core/workflow_copilot/test_handlers_build.py b/api/tests/unit_tests/core/workflow_copilot/test_handlers_build.py index 4f7fce3f87d..a3f684051f5 100644 --- a/api/tests/unit_tests/core/workflow_copilot/test_handlers_build.py +++ b/api/tests/unit_tests/core/workflow_copilot/test_handlers_build.py @@ -130,3 +130,100 @@ def test_initial_plan_find_resources_advances_to_resource_recommendation(): rs = next(i for i in res.items if i.kind == "resource_select") assert rs.payload["recommended"][0]["readiness"] == "ready" assert len(rs.payload["conflict_policy_options"]) == 2 + + +def test_resource_recommendation_confirm_creates_checkpoint_and_plan_v2(): + from core.workflow_copilot.handlers_build import handle_resource_recommendation + from tests.unit_tests.core.workflow_copilot.fakes import FakeBuildDifyPort + + env, repo = _new_env(dify=FakeBuildDifyPort()) + s = _seed_build_session( + repo, PcState.BUILD_RESOURCE_RECOMMENDATION, plan_items=["Retrieve", "Summarize"], plan_version_tag="v1" + ) + turn = Turn( + action=Action( + kind="confirm_resources", + payload={"resource_ids": ["kb-company"], "conflict_policy": "audited"}, + base_version=1, + ), + actor=_actor(), + ) + res = handle_resource_recommendation(env, turn, *repo.get_session(s.id)) + + assert res.next == PcState.BUILD_PLAN_APPROVAL + assert res.context.plan_version_tag == "v2" + assert res.context.resource_selection == {"resource_ids": ["kb-company"], "conflict_policy": "audited"} + assert res.context.checkpoint_id + cp, _snap = repo.get_checkpoint(res.context.checkpoint_id) + assert cp.session_id == s.id + checkpoint_card = next(i for i in res.items if i.kind == "checkpoint") + assert checkpoint_card.payload["checkpoint_id"] == res.context.checkpoint_id + assert {i.kind for i in res.items} >= {"decision", "plan", "checkpoint", "assistant_turn"} + + +def test_plan_approval_approve_builds_graph_and_reveals_nodes(): + from core.workflow_copilot.handlers_build import handle_plan_approval + from tests.unit_tests.core.workflow_copilot.fakes import FakeBuildDifyPort + + events: list[dict] = [] + dify = FakeBuildDifyPort() + env, repo = _new_env(dify=dify, emit_canvas=events.append) + s = _seed_build_session( + repo, PcState.BUILD_PLAN_APPROVAL, plan_items=["Retrieve", "Summarize"], plan_version_tag="v2" + ) + # approve_plan resolves (via service.resolve_action_kind) to "approve_repair". + turn = Turn(action=Action(kind="approve_repair", base_version=1), actor=_actor()) + res = handle_plan_approval(env, turn, *repo.get_session(s.id)) + + assert res.next == PcState.BUILD_EXECUTION + assert res.context.built_node_ids == ["start", "knowledge_retrieval", "llm", "end"] + assert len(dify.graph["nodes"]) == 4 + assert len(dify.graph["edges"]) == 3 + names = [e["event"] for e in events] + assert names[0] == "create_checkpoint" + assert [n for n in names if n.startswith("add_")] == [ + "add_start_node", + "add_knowledge_node", + "add_llm_node", + "add_output_node", + ] + change_set = next(i for i in res.items if i.kind == "change_set") + assert change_set.payload["scope"] == "structure" + assistant = next(i for i in res.items if i.kind == "assistant_turn") + assert len(assistant.payload["trace"]["steps"]) == 4 + + +def test_plan_approval_ignores_non_approve_action(): + from core.workflow_copilot.handlers_build import handle_plan_approval + from tests.unit_tests.core.workflow_copilot.fakes import FakeBuildDifyPort + + env, repo = _new_env(dify=FakeBuildDifyPort()) + s = _seed_build_session(repo, PcState.BUILD_PLAN_APPROVAL, plan_items=["Retrieve"], plan_version_tag="v2") + turn = Turn(action=Action(kind="message", base_version=1), actor=_actor()) + res = handle_plan_approval(env, turn, *repo.get_session(s.id)) + assert res.next == PcState.BUILD_PLAN_APPROVAL + + +def test_execution_run_test_advances_to_test_and_repair(): + from core.workflow_copilot.handlers_build import handle_execution + + events: list[dict] = [] + env, repo = _new_env(emit_canvas=events.append) + s = _seed_build_session(repo, PcState.BUILD_EXECUTION, built_node_ids=["start", "llm", "end"]) + turn = Turn(action=Action(kind="run_test", base_version=1), actor=_actor()) + res = handle_execution(env, turn, *repo.get_session(s.id)) + assert res.next == PcState.BUILD_TEST_AND_REPAIR + assert {"event": "start_test_run"} in events + + +def test_execution_revert_records_intent_only(): + from core.workflow_copilot.handlers_build import handle_execution + + events: list[dict] = [] + env, repo = _new_env(emit_canvas=events.append) + s = _seed_build_session(repo, PcState.BUILD_EXECUTION, built_node_ids=["start", "llm", "end"]) + turn = Turn(action=Action(kind="undo", base_version=1), actor=_actor()) # revert -> undo + res = handle_execution(env, turn, *repo.get_session(s.id)) + assert res.next == PcState.BUILD_REVERTED + assert any(i.kind == "decision" for i in res.items) + assert {"event": "revert_checkpoint"} in events