How do I filter block that are nested under page referenc

I’m using this query by Siferiax to get unplanned tasks from my journal page:

#+BEGIN_QUERY
    {:title [:h3 "☑ Unplanned"]
    :query [:find (pull ?b [*])
    :in $ ?day
    :where
      [?p :block/journal-day ?d]
      [(< ?d ?day)]
      [?b :block/page ?p]
      [?b :block/marker "TODO"]
      (not [?b :block/scheduled _])
      (not [?b :block/ref _])
    ]
    :result-transform (fn [result] (sort-by (fn [r] (get-in r [:block/page :block/journal-day])) result))
    :inputs [:today]
    :table-view? false
    :breadcrumb-show? true
    :collapsed? false
    }

#+END_QUERY

But I would like to filter out (i.e. not show) tasks that reference or are nested under blocked which reference a page (any page, not specific). Is it possible?

Sorry didn’t see this post sooner!

First thing to understand is that a task state (aka TODO etc) is actually secretly a page reference. So all tasks always reference a page.

Second thing to understand the block attribute :block/path-refs contains all references this block or its parents have. However this includes a reference to the page the block is on.

So we have to expand our not to take care of those two things.

#+BEGIN_QUERY
    {:title [:h3 "☑ Unplanned"]
    :query [:find (pull ?b [*])
    :in $ ?day
    :where
      [?p :block/journal-day ?d]
      [(< ?d ?day)]
      [?b :block/page ?p]
      [?b :block/marker ?mark]
      [(contains? #{"TODO"} ?mark)]
      [?m :block/original-name ?mark] ; get the task page
      (not [?b :block/scheduled _])
      (not 
        [?b :block/path-refs ?r] ; references for this block
        [(!= ?p ?r)] ; the reference is not the page the block is on 
        [(!= ?m ?r)] ; the reference is not the task page
      )
    ]
    :result-transform (fn [result] (sort-by (fn [r] (get-in r [:block/page :block/journal-day])) result))
    :inputs [:today]
    :table-view? false
    :breadcrumb-show? true
    :collapsed? false
    }

#+END_QUERY