We have some ordered processing that we need to do that can involve reading through 10s of thousands of records, with a lot of conditional processing. We use functions almost exclusively for this, returning a table of results.
It might be just very simple and I have tried but somehow I am blocked.
The feature you need is a recursive CTE (WITH RECURSIVE clause). It requires an initial row (which in this case is task 3, the only task that doesn't appear as a task_order value) and a query to retrieve the next row(s) using the information available in the previous iteration.
The documentation and/or online resources can walk you through the specifics.