File size: 7,558 Bytes
ef1ab71
4997b06
a64c042
4997b06
a64c042
 
4997b06
0cc127a
 
 
a64c042
 
 
4997b06
 
f60e55e
ef1ab71
4997b06
 
 
 
ef1ab71
 
4997b06
 
 
f60e55e
0cc127a
ef1ab71
 
0cc127a
ae716a9
 
 
 
0cc127a
 
ae716a9
 
 
 
0cc127a
 
 
 
ef1ab71
 
0cc127a
ef1ab71
 
0cc127a
 
 
 
 
 
 
 
 
 
29fb633
 
43963c7
ae716a9
29fb633
a64c042
 
 
ef1ab71
0cc127a
43963c7
 
 
 
 
0cc127a
43963c7
 
 
 
0cc127a
 
 
43963c7
 
0cc127a
 
43963c7
 
 
0cc127a
ae716a9
 
 
 
43963c7
0cc127a
 
 
 
 
 
 
43963c7
ef1ab71
 
0cc127a
ef1ab71
 
0cc127a
 
 
ef1ab71
0cc127a
 
 
 
 
43963c7
0cc127a
 
 
 
 
3929363
0cc127a
 
 
43963c7
0cc127a
43963c7
ae716a9
 
43963c7
ae716a9
 
0cc127a
 
43963c7
0cc127a
ae716a9
0cc127a
ae716a9
ef1ab71
 
 
 
 
 
 
 
 
 
 
0cc127a
ef1ab71
0cc127a
ef1ab71
0cc127a
ef1ab71
0cc127a
 
ef1ab71
 
 
 
 
29fb633
 
ae716a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef1ab71
 
ae716a9
 
 
ef1ab71
 
ae716a9
43963c7
 
ef1ab71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43963c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef1ab71
43963c7
 
 
 
 
 
 
 
ef1ab71
43963c7
 
 
 
 
ef1ab71
43963c7
 
 
 
 
 
 
 
 
 
 
 
ef1ab71
43963c7
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import logging
from typing import Any

from langchain_core.runnables import RunnableConfig
from langgraph.types import Command, Interrupt
from pydantic import BaseModel

from multi_agent_sdlc.presentation.terminal_plan_review import (
    collect_plan_review_decision,
)
from multi_agent_sdlc.presentation.terminal_verification_block_review import (
    collect_verification_block_review,
)

from .checkpointing import build_workflow_config, create_checkpointer
from .graph import build_graph
from .models import WorkflowTermination
from .run_repository import (
    WorkflowRun,
    WorkflowRunStatus,
    create_workflow_run,
    fail_workflow_run,
    finish_workflow_run,
    get_workflow_run,
    update_workflow_run_status,
)
from .state import build_initial_state

logger = logging.getLogger(__name__)


def run_new_workflow(
    request: str,
    configurable: dict[str, Any],
) -> None:
    workflow_run = create_workflow_run(request)

    config = build_workflow_config(
        workflow_run.thread_id,
        configurable,
    )
    initial_state = build_initial_state(request)

    with create_checkpointer() as checkpointer:
        graph = build_graph(checkpointer)
        result = _invoke_graph(
            graph,
            initial_state,
            config,
            workflow_run,
        )

        _process_workflow_result(
            graph,
            result,
            workflow_run,
            config,
        )


def resume_workflow(
    thread_id: str,
    checkpoint_id: str | None,
    configurable: dict[str, Any],
) -> None:
    workflow_run = get_workflow_run(thread_id)

    if workflow_run is None:
        raise ValueError(f"Workflow run not found: {thread_id}")

    checkpoint_config = build_workflow_config(
        workflow_run.thread_id,
        configurable,
        checkpoint_id,
    )

    thread_config = build_workflow_config(
        workflow_run.thread_id,
        configurable,
    )

    with create_checkpointer() as checkpointer:
        graph = build_graph(checkpointer)

        snapshot = graph.get_state(checkpoint_config)

        if snapshot.interrupts:
            interrupt = _get_first_interrupt(
                snapshot.interrupts,
            )

            result = _resume_interrupt(
                graph,
                interrupt,
                workflow_run,
                checkpoint_config,
            )

        elif snapshot.next:
            update_workflow_run_status(
                workflow_run.thread_id,
                WorkflowRunStatus.RUNNING,
            )

            result = _invoke_graph(
                graph,
                None,
                checkpoint_config,
                workflow_run,
            )

        else:
            raise ValueError(f"Workflow run {workflow_run.thread_id!r} has no pending work.")

        _process_workflow_result(
            graph,
            result,
            workflow_run,
            thread_config,
        )


def _process_workflow_result(
    graph,
    result: dict[str, object],
    workflow_run: WorkflowRun,
    config: RunnableConfig,
) -> None:
    interrupts = _get_interrupts(result)

    while interrupts:
        result = _resume_interrupt(
            graph,
            interrupts[0],
            workflow_run,
            config,
        )

        interrupts = _get_interrupts(result)

    snapshot = graph.get_state(config)

    if snapshot.next:
        raise RuntimeError(f"Workflow run {workflow_run.thread_id} stopped with pending nodes: {snapshot.next!r}.")

    termination = snapshot.values.get("workflow_termination")

    if not isinstance(termination, WorkflowTermination):
        error = RuntimeError("Workflow reached END without structured termination information.")
        fail_workflow_run(
            workflow_run.thread_id,
            reason=str(error),
            node="finalize_workflow",
            error_type=type(error).__name__,
        )
        raise error

    finish_workflow_run(
        workflow_run.thread_id,
        termination,
    )

    print("\nWorkflow execution finished.")
    print(f"Outcome: {termination.outcome.value}")
    print(f"Terminal node: {termination.node}")
    print(f"Reason: {termination.reason}")
    print(f"Thread ID: {workflow_run.thread_id}")


def _resume_interrupt(
    graph,
    interrupt: Interrupt,
    workflow_run: WorkflowRun,
    config: RunnableConfig,
) -> dict[str, object]:
    update_workflow_run_status(
        workflow_run.thread_id,
        WorkflowRunStatus.INTERRUPTED,
    )

    response = _collect_interrupt_response(interrupt.value)

    update_workflow_run_status(
        workflow_run.thread_id,
        WorkflowRunStatus.RUNNING,
    )

    return _invoke_graph(
        graph,
        Command(
            resume=response.model_dump(mode="json"),
        ),
        config,
        workflow_run,
    )


def _invoke_graph(
    graph,
    graph_input: object,
    config: RunnableConfig,
    workflow_run: WorkflowRun,
) -> dict[str, object]:
    try:
        return graph.invoke(
            graph_input,
            config=config,
        )
    except Exception as error:
        terminal_node = _get_pending_node(graph, config)

        try:
            fail_workflow_run(
                workflow_run.thread_id,
                reason=str(error) or type(error).__name__,
                node=terminal_node,
                error_type=type(error).__name__,
            )
        except Exception:
            logger.exception(
                "Could not persist failure for workflow run %s.",
                workflow_run.thread_id,
            )

        raise


def _get_pending_node(graph, config: RunnableConfig) -> str:
    try:
        snapshot = graph.get_state(config)
    except Exception:
        logger.exception("Could not inspect graph state after execution failure.")
        return "unknown"

    return snapshot.next[0] if snapshot.next else "unknown"


def _collect_interrupt_response(
    interrupt_value: dict[str, Any],
) -> BaseModel:
    interrupt_type = interrupt_value.get("type")
    content = interrupt_value.get("content")

    if not isinstance(interrupt_type, str):
        raise ValueError("Interrupt type is missing or invalid.")

    if not isinstance(content, str):
        raise ValueError("Interrupt content is missing or invalid.")

    print()
    print(content)

    match interrupt_type:
        case "plan_review":
            print("\nGraph paused for plan review.")
            return collect_plan_review_decision()

        case "verification_block_review":
            print("\nGraph paused because verification is blocked.")
            return collect_verification_block_review()

        case _:
            raise ValueError(f"Unsupported interrupt type: {interrupt_type!r}")


def _get_interrupts(
    result: dict[str, object],
) -> list[Interrupt]:
    value = result.get("__interrupt__", ())

    if not isinstance(value, (list, tuple)):
        raise TypeError(f"Expected __interrupt__ to be a list or tuple, got {type(value).__name__}.")

    interrupts: list[Interrupt] = []

    for item in value:
        if not isinstance(item, Interrupt):
            raise TypeError(f"Expected Interrupt, got {type(item).__name__}.")

        interrupts.append(item)

    return interrupts


def _get_first_interrupt(
    interrupts: tuple[Interrupt, ...],
) -> Interrupt:
    interrupt = interrupts[0]

    if not isinstance(interrupt, Interrupt):
        raise TypeError(f"Expected Interrupt, got {type(interrupt).__name__}.")

    return interrupt