 
 ;; For now, just do simplest thing, PostFireAttempt and PostAchieveAttempt
 
-(defn make-if-deadlock-hla [hierarchy var dl-plan nodl-plan]
-  (let [name [:if-deadlock var (map env/action-name dl-plan) (map env/action-name nodl-plan)]
-        av   (action-var var)
-        pc   (util/safe-get-in hierarchy [:precondition-context-map var])]
-    (reify :as this
-      env/Action
-       (action-name [] name)
-       (primitive?  [] false)
-      env/ContextualAction 
-       (precondition-context [s] pc)
-      hierarchy/HighLevelAction
-       (immediate-refinements- [s] (if (env/get-var s av) [dl-plan] [nodl-plan]))
-       (cycle-level-           [s] nil))))
+;; TODO: think about adaptive contexts.  
+
+;; TODO: speed up somehow?
+
+(declare precond-deadlocked?)
+(defn action-deadlocked? [s var]
+  (when-let [a (env/get-var s (action-var var))]
+    (some #(precond-deadlocked? s % var) (remove #{var} (keys (:precond-map a))))))
+
+(defn precond-deadlocked? [s precond e-var]
+  (or (and (not (env/get-var s (free-var precond)))
+           (not (env/get-var s (parent-var precond e-var))))
+      (action-deadlocked? s precond)))
+
+(defn precond-deadlocked-ooc? [s precond e-var child-var-map context]
+  (or (and (not (env/get-var s (free-var precond)))
+           (not (env/get-var s (parent-var precond e-var)))
+           (not (contains? context (current-child s child-var-map precond))))
+      (when-let [a (env/get-var s (action-var precond))]
+        (some #(precond-deadlocked-ooc? s % precond child-var-map context) 
+              (remove #{precond} (keys (:precond-map a)))))))
+
+
+
 
 (declare make-fire-action-hla)
 


(deftype ASPlanEnv [init actions-fn g-map 
                    ; Following stuff is used by hierarchy.
                    causal-graph dtgs child-var-map acyclic-succ-fn]
  env/Env 
    (initial-state [] init)
    (actions-fn    [] actions-fn)







(comment
 (defn make-if-deadlock-hla [hierarchy var dl-plan nodl-plan]
   (let [name [:if-deadlock var (map env/action-name dl-plan) (map env/action-name nodl-plan)]
         av   (action-var var)
         pc   (util/safe-get-in hierarchy [:precondition-context-map var])]
     (reify :as this
            env/Action
            (action-name [] name)
            (primitive?  [] false)
            env/ContextualAction 
            (precondition-context [s] pc)
            hierarchy/HighLevelAction
            (immediate-refinements- [s] (if (env/get-var s av) [dl-plan] [nodl-plan]))
            (cycle-level-           [s] nil)))))



