diff --git a/api/core/workflow_copilot/recovery.py b/api/core/workflow_copilot/recovery.py new file mode 100644 index 00000000000..443ee561fc7 --- /dev/null +++ b/api/core/workflow_copilot/recovery.py @@ -0,0 +1,137 @@ +"""Structure-fingerprint recovery (C-1). + +Detect a canvas hand-edit made while a copilot session waited, classify the +drift, and drive continue-vs-restart. Triggered by three free-string action +ids (``check_recovery`` / ``recovery_continue`` / ``recovery_restart``) that +the runner short-circuits on, exactly like ``stop`` / ``resume``. + +Core-only: imports ``contract`` / ``models`` / ``ports`` / ``state`` and NEVER +``runner`` / ``handlers_fix`` / ``services`` -- the runner imports this module, +so importing back would cycle. For the same reason the recovery ``NoticeItem`` +is stamped inline via the ``fc.next_seq`` protocol rather than reusing +``handlers_fix.append_card``. +""" + +from core.workflow_copilot.contract import NoticeItem, RecoveryClass +from core.workflow_copilot.models import ConversationItem, CopilotContext, EntryMode, Session, Turn +from core.workflow_copilot.ports import DifyPort +from core.workflow_copilot.state import PcState + +__all__ = [ + "apply_recovery_action", + "classify", + "entry_state_for", + "target_node_ids", +] + +_ENTRY_STATE: dict[EntryMode, PcState] = { + EntryMode.FIX: PcState.FIX_DIAGNOSE, + EntryMode.FIX_CHECKLIST: PcState.CHECKLIST_DIAGNOSE, + EntryMode.BUILD: PcState.BUILD_CAPABILITY_CHECK, + EntryMode.EDIT: PcState.EDIT_CAPABILITY_CHECK, +} + +_RECOVERY_MESSAGE: dict[RecoveryClass, str] = { + RecoveryClass.UNCHANGED: "No changes since you last left — resuming where you were.", + RecoveryClass.CONFIG_ONLY: "Only node settings changed since you left — continue or restart.", + RecoveryClass.STRUCTURAL_COMPATIBLE: ( + "The workflow structure changed, but the nodes this task targets are still present — " + "continue or restart." + ), + RecoveryClass.STRUCTURAL_INVALIDATING: ( + "The nodes this task was working on are no longer in the workflow — restart to work " + "from the current draft." + ), +} + + +def entry_state_for(entry_mode: EntryMode) -> PcState: + """The state a fresh session of this mode starts in. Mirrors + ``service.create_*_session``; a parity test guards drift.""" + return _ENTRY_STATE[entry_mode] + + +def target_node_ids(fc: CopilotContext, entry_mode: EntryMode) -> list[str]: + """The node ids this task is about -- used to tell a structural edit that + LEAVES the targets intact (compatible) from one that removes them + (invalidating).""" + if entry_mode == EntryMode.BUILD: + return list(fc.built_node_ids) + if entry_mode == EntryMode.EDIT: + return list(fc.edit_target_node_ids) + ids: list[str] = [] + if entry_mode == EntryMode.FIX_CHECKLIST: + ids = [e.node_id for e in fc.checklist_errors if e.node_id] + if fc.diagnosis is not None and fc.diagnosis.culprit_node_id and fc.diagnosis.culprit_node_id not in ids: + ids.append(fc.diagnosis.culprit_node_id) + return ids + + +def classify( + cur_hash: str, + cur_fingerprint: str, + present_node_ids: list[str], + fc: CopilotContext, + entry_mode: EntryMode, +) -> RecoveryClass: + """Four-way drift classification (C-1).""" + if cur_hash == fc.last_snapshot_hash: + return RecoveryClass.UNCHANGED + if cur_fingerprint == fc.last_structure_fingerprint: + return RecoveryClass.CONFIG_ONLY + if set(target_node_ids(fc, entry_mode)) <= set(present_node_ids): + return RecoveryClass.STRUCTURAL_COMPATIBLE + return RecoveryClass.STRUCTURAL_INVALIDATING + + +def _append_notice(fc: CopilotContext, text: str) -> ConversationItem: + """Stamp one NoticeItem via the fc.next_seq protocol (see module docstring + for why this is inlined rather than using handlers_fix.append_card).""" + item = NoticeItem(text=text).to_item(seq=fc.next_seq, at_version=0) + fc.next_seq += 1 + return item + + +def _reset_working_fields(fc: CopilotContext) -> None: + """Clear per-flow working state for a clean re-entry. Preserves the + conversation, next_seq, and the mode's durable inputs (goal_text, + requirements, edit_rules, checklist_errors, failed_run_id, source).""" + fc.diagnosis = None + fc.staged_repair = [] + fc.risk = None + fc.change_set = None + fc.checkpoint_id = "" + fc.checkpoint_seq = 0 + fc.verify_run_id = "" + fc.test_input_ref = "" + fc.plan_items = [] + fc.plan_version_tag = "" + fc.resource_selection = {} + fc.built_node_ids = [] + fc.edit_target_node_ids = [] + fc.last_snapshot_hash = "" + fc.last_structure_fingerprint = "" + + +def apply_recovery_action( + dify: DifyPort, turn: Turn, s: Session, fc: CopilotContext +) -> tuple[PcState, list[ConversationItem]]: + """Handle check_recovery / recovery_continue / recovery_restart. Returns + ``(next_state, items)`` for the runner to commit in a single CAS step. + The runner guarantees ``turn.action.kind`` is one of the three.""" + kind = turn.action.kind if turn.action is not None else "" + if kind == "check_recovery": + graph, cur_hash = dify.read_graph(s.app_id, turn.actor) + cur_fp = dify.structural_fingerprint(graph) + present = dify.graph_node_ids(graph) + cls = classify(cur_hash, cur_fp, present, fc, s.entry_mode) + fc.recovery_class = str(cls) + return s.current_state, [_append_notice(fc, _RECOVERY_MESSAGE[cls])] + if kind == "recovery_continue": + fc.recovery_class = "" + return s.current_state, [_append_notice(fc, "Continuing on the current plan.")] + if kind == "recovery_restart": + fc.recovery_class = "" + _reset_working_fields(fc) + return entry_state_for(s.entry_mode), [_append_notice(fc, "Restarted from the current draft.")] + return s.current_state, [] # defensive: unreachable given the runner's guard diff --git a/api/core/workflow_copilot/runner.py b/api/core/workflow_copilot/runner.py index fa1d284075e..51fc51d34fa 100644 --- a/api/core/workflow_copilot/runner.py +++ b/api/core/workflow_copilot/runner.py @@ -23,6 +23,7 @@ from collections.abc import Callable from dataclasses import dataclass, field from datetime import datetime +from core.workflow_copilot import recovery from core.workflow_copilot.errors import ConflictError from core.workflow_copilot.models import ( Checkpoint, @@ -100,6 +101,11 @@ class Runner: fc.paused = action_kind == "stop" s.version = self._env.repo.compare_and_advance(s.id, s.version, s.current_state, fc, []) return s + if action_kind in ("check_recovery", "recovery_continue", "recovery_restart"): + next_state, items = recovery.apply_recovery_action(self._env.dify, turn, s, fc) + s.version = self._env.repo.compare_and_advance(s.id, s.version, next_state, fc, items) + s.current_state = next_state + return s first = True while True: diff --git a/api/tests/unit_tests/core/workflow_copilot/test_recovery.py b/api/tests/unit_tests/core/workflow_copilot/test_recovery.py new file mode 100644 index 00000000000..11a1cf3e82e --- /dev/null +++ b/api/tests/unit_tests/core/workflow_copilot/test_recovery.py @@ -0,0 +1,155 @@ +from datetime import datetime + +from core.workflow_copilot.contract import RecoveryClass +from core.workflow_copilot.models import ( + Action, ChecklistError, ConversationItem, CopilotContext, Diagnosis, EntryMode, Session, Turn, +) +from core.workflow_copilot.runner import Env, Runner +from core.workflow_copilot.state import PcState +from tests.unit_tests.core.workflow_copilot.fakes import FakeDifyPort, InMemoryRepository, StubAgent + + +def _actor(): + from core.workflow_copilot.models import Actor + return Actor(account_id="a", tenant_id="t") + + +# ---- entry_state_for ------------------------------------------------------- + +def test_entry_state_for_all_modes(): + from core.workflow_copilot import recovery + + assert recovery.entry_state_for(EntryMode.FIX) == PcState.FIX_DIAGNOSE + assert recovery.entry_state_for(EntryMode.FIX_CHECKLIST) == PcState.CHECKLIST_DIAGNOSE + assert recovery.entry_state_for(EntryMode.BUILD) == PcState.BUILD_CAPABILITY_CHECK + assert recovery.entry_state_for(EntryMode.EDIT) == PcState.EDIT_CAPABILITY_CHECK + + +# ---- target_node_ids ------------------------------------------------------- + +def test_target_node_ids_per_mode(): + from core.workflow_copilot import recovery + + build_fc = CopilotContext(built_node_ids=["n1", "n2"]) + assert recovery.target_node_ids(build_fc, EntryMode.BUILD) == ["n1", "n2"] + + edit_fc = CopilotContext(edit_target_node_ids=["e1"]) + assert recovery.target_node_ids(edit_fc, EntryMode.EDIT) == ["e1"] + + fix_fc = CopilotContext(diagnosis=Diagnosis(culprit_node_id="c1")) + assert recovery.target_node_ids(fix_fc, EntryMode.FIX) == ["c1"] + + checklist_fc = CopilotContext( + checklist_errors=[ChecklistError(node_id="k1"), ChecklistError(node_id="k2")], + diagnosis=Diagnosis(culprit_node_id="k2"), + ) + # checklist error node ids, with the culprit deduped in. + assert recovery.target_node_ids(checklist_fc, EntryMode.FIX_CHECKLIST) == ["k1", "k2"] + + +# ---- classify -------------------------------------------------------------- + +def test_classify_unchanged(): + from core.workflow_copilot import recovery + + fc = CopilotContext(last_snapshot_hash="h1", last_structure_fingerprint="fp1") + assert recovery.classify("h1", "fp-anything", [], fc, EntryMode.BUILD) == RecoveryClass.UNCHANGED + + +def test_classify_config_only(): + from core.workflow_copilot import recovery + + fc = CopilotContext(last_snapshot_hash="h1", last_structure_fingerprint="fp1") + assert recovery.classify("h2", "fp1", [], fc, EntryMode.BUILD) == RecoveryClass.CONFIG_ONLY + + +def test_classify_structural_compatible(): + from core.workflow_copilot import recovery + + fc = CopilotContext( + last_snapshot_hash="h1", last_structure_fingerprint="fp1", built_node_ids=["n1"], + ) + # hash + fingerprint changed, but target n1 still present. + assert recovery.classify("h2", "fp2", ["n1", "n2"], fc, EntryMode.BUILD) == RecoveryClass.STRUCTURAL_COMPATIBLE + + +def test_classify_structural_invalidating(): + from core.workflow_copilot import recovery + + fc = CopilotContext( + last_snapshot_hash="h1", last_structure_fingerprint="fp1", built_node_ids=["n1"], + ) + # target n1 gone from the current graph. + assert recovery.classify("h2", "fp2", ["n2"], fc, EntryMode.BUILD) == RecoveryClass.STRUCTURAL_INVALIDATING + + +# ---- apply_recovery_action via the runner ---------------------------------- + +def _seed(repo, entry_mode, state, fc): + s = Session(app_id="app", tenant_id="t", owner_account_id="a", entry_mode=entry_mode, current_state=state) + repo.create_session(s, fc, [ConversationItem(kind="user", seq=0)]) + return s + + +def test_check_recovery_sets_class_and_appends_notice(): + dify = FakeDifyPort() + dify.graph = {"nodes": [{"id": "n1", "data": {"type": "llm"}}], "edges": []} + dify.hash = "h-new" + repo = InMemoryRepository() + # last-known: different hash, matching fingerprint -> config_only. + fc = CopilotContext( + last_snapshot_hash="h-old", + last_structure_fingerprint=dify.structural_fingerprint(dify.graph), + next_seq=1, + ) + s = _seed(repo, EntryMode.BUILD, PcState.BUILD_REVIEW, fc) + runner = Runner(Env(dify=dify, agent=StubAgent(), repo=repo, now=lambda: datetime.min), {}) + + out = runner.advance(s.id, Turn(action=Action(kind="check_recovery", base_version=1), actor=_actor())) + + assert out.current_state == PcState.BUILD_REVIEW # same state + assert out.version == 2 # committed + _s, fc2 = repo.get_session(s.id) + assert fc2.recovery_class == "config_only" + convo = repo.list_conversation(s.id) + assert any(item.kind == "notice" for item in convo[1:]) # a notice was appended + + +def test_recovery_continue_clears_class(): + dify = FakeDifyPort() + repo = InMemoryRepository() + fc = CopilotContext(recovery_class="config_only", next_seq=1) + s = _seed(repo, EntryMode.BUILD, PcState.BUILD_REVIEW, fc) + runner = Runner(Env(dify=dify, agent=StubAgent(), repo=repo, now=lambda: datetime.min), {}) + + out = runner.advance(s.id, Turn(action=Action(kind="recovery_continue", base_version=1), actor=_actor())) + + assert out.current_state == PcState.BUILD_REVIEW + _s, fc2 = repo.get_session(s.id) + assert fc2.recovery_class == "" + + +def test_recovery_restart_resets_to_entry_state_and_preserves_conversation(): + dify = FakeDifyPort() + repo = InMemoryRepository() + fc = CopilotContext( + recovery_class="structural_invalidating", + built_node_ids=["n1"], + plan_items=["step"], + checkpoint_id="cp1", + goal_text="build me a thing", + next_seq=1, + ) + s = _seed(repo, EntryMode.BUILD, PcState.BUILD_REVIEW, fc) + runner = Runner(Env(dify=dify, agent=StubAgent(), repo=repo, now=lambda: datetime.min), {}) + + out = runner.advance(s.id, Turn(action=Action(kind="recovery_restart", base_version=1), actor=_actor())) + + assert out.current_state == PcState.BUILD_CAPABILITY_CHECK # entry state for BUILD + _s, fc2 = repo.get_session(s.id) + assert fc2.recovery_class == "" + assert fc2.built_node_ids == [] + assert fc2.plan_items == [] + assert fc2.checkpoint_id == "" + assert fc2.goal_text == "build me a thing" # preserved + assert len(repo.list_conversation(s.id)) >= 1 # conversation preserved (+ restart notice)