Загрузка данных


;;; ============================================================
;;; BLKREACTOR.lsp
;;; Consolidated monolithic build assembled from latest module milestones
;;; Build: 17.1
;;; Date: 2026-04-12T20:58:00
;;; Encoding target: UTF-8 with BOM
;;; ============================================================

(setq *brx-build-id* "17.1")
(setq *brx-build-modules* nil)

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Core_Formula_Engine_v1_0a.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Core_Formula_Engine_v1_0a.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

(defun brx-make-ok (typ val /)
  (list
    (cons :kind "OK")
    (cons :type typ)
    (cons :value val)
  )
)

(defun brx-make-err (code / name)
  (setq name (cdr (assoc code *brx-error-codes*)))
  (list
    (cons :kind "ERR")
    (cons :type "ERROR")
    (cons :code code)
    (cons :name (if name name "UNKNOWN"))
  )
)

(defun brx-ok-p (rv /)
  (= (cdr (assoc :kind rv)) "OK")
)

(defun brx-err-p (rv /)
  (= (cdr (assoc :kind rv)) "ERR")
)

(defun brx-rv-type (rv /)
  (cdr (assoc :type rv))
)

(defun brx-rv-value (rv /)
  (cdr (assoc :value rv))
)

(defun brx-rv-code (rv /)
  (cdr (assoc :code rv))
)

(defun brx-rv-name (rv /)
  (cdr (assoc :name rv))
)

;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------

(defun brx-ctx-get (ctx key /)
  (cdr (assoc key ctx))
)

(defun brx-ctx-put (ctx key val / pair)
  (setq pair (assoc key ctx))
  (if pair
    (subst (cons key val) pair ctx)
    (append ctx (list (cons key val)))
  )
)

(defun brx-ctx-push-stack (ctx node / stk)
  (setq stk (brx-ctx-get ctx :stack))
  (brx-ctx-put ctx :stack (cons node stk))
)

(defun brx-ctx-in-stack-p (ctx node / stk)
  (setq stk (brx-ctx-get ctx :stack))
  (if (member node stk) T nil)
)

;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------

(defun brx-string-trim (s /)
  (if (and s (= (type s) 'STR))
    (vl-string-trim " \t\r\n" s)
    s
  )
)

(defun brx-char-at (s i /)
  (substr s i 1)
)

(defun brx-strlen (s /)
  (if s (strlen s) 0)
)

(defun brx-char-code (ch /)
  (if (and ch (> (strlen ch) 0))
    (ascii ch)
    0
  )
)

(defun brx-space-p (ch /)
  (member ch '(" " "\t" "\r" "\n"))
)

(defun brx-digit-p (ch / a)
  (setq a (brx-char-code ch))
  (and (>= a 48) (<= a 57))
)

(defun brx-letter-p (ch / a)
  (setq a (brx-char-code (strcase ch)))
  (and (>= a 65) (<= a 90))
)

(defun brx-ident-start-p (ch /)
  (or (brx-letter-p ch) (= ch "_"))
)

(defun brx-ident-char-p (ch /)
  (or (brx-ident-start-p ch) (brx-digit-p ch))
)

(defun brx-join (lst sep / out)
  (setq out "")
  (while lst
    (setq out (strcat out (car lst) (if (cdr lst) sep "")))
    (setq lst (cdr lst))
  )
  out
)

(defun brx-number-p (x /)
  (or (numberp x) (= (type x) 'INT) (= (type x) 'REAL))
)

(defun brx-normalize-decimal-string (s /)
  (if (= (type s) 'STR)
    (vl-string-translate "," "." s)
    s
  )
)

(defun brx-try-parse-number (s / n)
  (cond
    ((brx-number-p s) s)
    ((/= (type s) 'STR) nil)
    (T
      (setq s (brx-string-trim (brx-normalize-decimal-string s)))
      (setq n (distof s 2))
      n
    )
  )
)

(defun brx-bool-rv (flag /)
  (brx-make-ok "BOOL" (if flag T nil))
)

;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------

(defun brx-make-tok (typ val /)
  (list (cons :t typ) (cons :v val))
)

(defun brx-tok-type (tok /)
  (cdr (assoc :t tok))
)

(defun brx-tok-val (tok /)
  (cdr (assoc :v tok))
)

(defun brx-tokenize (expr / s len i ch buf tokens startch)
  (setq s (brx-string-trim expr))
  (setq len (brx-strlen s))
  (setq i 1)
  (setq tokens nil)

  (while (<= i len)
    (setq ch (brx-char-at s i))
    (cond
      ((brx-space-p ch)
        (setq i (1+ i))
      )

      ((= ch "(")
        (setq tokens (cons (brx-make-tok "LPAREN" ch) tokens))
        (setq i (1+ i))
      )
      ((= ch ")")
        (setq tokens (cons (brx-make-tok "RPAREN" ch) tokens))
        (setq i (1+ i))
      )
      ((= ch ",")
        (setq tokens (cons (brx-make-tok "COMMA" ch) tokens))
        (setq i (1+ i))
      )
      ((= ch ".")
        (setq tokens (cons (brx-make-tok "DOT" ch) tokens))
        (setq i (1+ i))
      )
      ((= ch ":")
        (setq tokens (cons (brx-make-tok "COLON" ch) tokens))
        (setq i (1+ i))
      )

      ((= ch "\"")
        (setq i (1+ i))
        (setq buf "")
        (while (and (<= i len) (/= (brx-char-at s i) "\""))
          (setq buf (strcat buf (brx-char-at s i)))
          (setq i (1+ i))
        )
        (if (> i len)
          (progn
            (setq tokens (list (brx-make-tok "ERR" "UNCLOSED-STRING")))
            (setq i (+ len 1))
          )
          (progn
            (setq tokens (cons (brx-make-tok "STRING" buf) tokens))
            (setq i (1+ i))
          )
        )
      )

      ((or (brx-digit-p ch)
           (and (member ch '("+" "-"))
                (< i len)
                (brx-digit-p (brx-char-at s (1+ i)))))
        (setq buf ch)
        (setq i (1+ i))
        (while (and (<= i len)
                    (member (brx-char-at s i) '("0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "." ",")))
          (setq buf (strcat buf (brx-char-at s i)))
          (setq i (1+ i))
        )
        (setq buf (brx-normalize-decimal-string buf))
        (setq tokens (cons (brx-make-tok "NUMBER" buf) tokens))
      )

      ((brx-ident-start-p ch)
        (setq buf (strcase ch T))
        (setq i (1+ i))
        (while (and (<= i len) (brx-ident-char-p (brx-char-at s i)))
          (setq buf (strcat buf (strcase (brx-char-at s i) T)))
          (setq i (1+ i))
        )
        (setq tokens (cons (brx-make-tok "IDENT" buf) tokens))
      )

      (T
        (setq tokens (list (brx-make-tok "ERR" (strcat "BAD-CHAR:" ch))))
        (setq i (+ len 1))
      )
    )
  )

  (reverse tokens)
)

(defun brx-tokens->canon (tokens / out typ val)
  (setq out nil)
  (while tokens
    (setq typ (brx-tok-type (car tokens)))
    (setq val (brx-tok-val (car tokens)))
    (cond
      ((= typ "STRING") (setq out (cons (strcat "\"" val "\"") out)))
      (T                (setq out (cons val out)))
    )
    (setq tokens (cdr tokens))
  )
  (brx-join (reverse out) "")
)

(defun brx-expr-normalize (expr / toks)
  (if (/= (type expr) 'STR)
    ""
    (progn
      (setq toks (brx-tokenize expr))
      (if (and toks (= (brx-tok-type (car toks)) "ERR"))
        ""
        (brx-tokens->canon toks)
      )
    )
  )
)

;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------

(defun brx-ast-lit (rv /)
  (list (cons :node "LIT") (cons :value rv))
)

(defun brx-ast-ref (scope kind name /)
  (list
    (cons :node "REF")
    (cons :scope scope)
    (cons :kind kind)
    (cons :name name)
  )
)

(defun brx-ast-call (fname args /)
  (list
    (cons :node "CALL")
    (cons :name (strcase fname T))
    (cons :args args)
  )
)

(defun brx-ast-error (code message /)
  (list
    (cons :node "PERR")
    (cons :code code)
    (cons :message message)
  )
)

(defun brx-ast-node (ast /)
  (cdr (assoc :node ast))
)

;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

(defun brx-parser-init (tokens /)
  (setq *brx-ptoks* tokens)
  (setq *brx-pidx* 0)
)

(defun brx-pcur ( / )
  (nth *brx-pidx* *brx-ptoks*)
)

(defun brx-ppeek (n /)
  (nth (+ *brx-pidx* n) *brx-ptoks*)
)

(defun brx-padvance ( / tok)
  (setq tok (brx-pcur))
  (setq *brx-pidx* (1+ *brx-pidx*))
  tok
)

(defun brx-paccept (typ / tok)
  (setq tok (brx-pcur))
  (if (and tok (= (brx-tok-type tok) typ))
    (brx-padvance)
    nil
  )
)

(defun brx-pexpect (typ / tok)
  (setq tok (brx-pcur))
  (if (and tok (= (brx-tok-type tok) typ))
    (brx-padvance)
    (brx-ast-error "009" (strcat "Expected " typ))
  )
)

(defun brx-scope-normalize (scope / u)
  (setq u (strcase scope T))
  (cond
    ((= u "ROWDRIVER")   "ROW")
    ((= u "COLDRIVER")   "COL")
    ((= u "MATCHEDBLOCK") "MATCH")
    (T u)
  )
)

(defun brx-cell-addr-p (s / i len ch seenDigit seenLetter)
  (if (or (null s) (/= (type s) 'STR))
    nil
    (progn
      (setq s (strcase s T))
      (setq len (strlen s))
      (setq i 1)
      (setq seenDigit nil)
      (setq seenLetter nil)
      (while (<= i len)
        (setq ch (brx-char-at s i))
        (cond
          ((and (not seenDigit) (brx-letter-p ch))
            (setq seenLetter T)
          )
          ((and seenLetter (brx-digit-p ch))
            (setq seenDigit T)
          )
          (T
            (setq i (+ len 1))
            (setq seenLetter nil)
            (setq seenDigit nil)
          )
        )
        (if (<= i len) (setq i (1+ i)))
      )
      (and seenLetter seenDigit)
    )
  )
)

(defun brx-kind-from-path (path / u)
  (setq u (strcase path T))
  (cond
    ((wcmatch u "ATTR*")      (list "ATTR" (substr path 5)))
    ((wcmatch u "PARAM*")     (list "PARAM" (substr path 6)))
    ((wcmatch u "FIELD*")     (list "FIELD" (substr path 6)))
    ((wcmatch u "CELL*")      (list "CELL" (substr path 5)))
    ((wcmatch u "HANDLE*")    (list "HANDLE" (substr path 7)))
    ((wcmatch u "BLOCKNAME*") (list "BLOCKNAME" (substr path 10)))
    ((member u '("OBJECTS" "SLAVES" "TABLES" "MATCHES" "SET" "VALUE"))
      (list u "")
    )
    (T (list "AUTO" path))
  )
)

(defun brx-make-scoped-ref (scope path / kk)
  (setq kk (brx-kind-from-path path))
  (brx-ast-ref (brx-scope-normalize scope) (car kk) (cadr kk))
)

(defun brx-parse-args ( / args ast done tok)
  (setq args nil)
  (setq done nil)
  (if (brx-paccept "RPAREN")
    (reverse args)
    (progn
      (while (not done)
        (setq ast (brx-parse-expr))
        (if (= (brx-ast-node ast) "PERR")
          (progn
            (setq args (list ast))
            (setq done T)
          )
          (setq args (cons ast args))
        )
        (if (not done)
          (cond
            ((brx-paccept "COMMA") nil)
            ((brx-paccept "RPAREN") (setq done T))
            (T
              (setq args (list (brx-ast-error "009" "Expected COMMA or RPAREN")))
              (setq done T)
            )
          )
        )
      )
      (reverse args)
    )
  )
)

(defun brx-parse-ident-primary (name / tok2 path rhs args)
  (cond
    ((member name '("TRUE" "FALSE"))
      (brx-ast-lit (brx-bool-rv (= name "TRUE")))
    )

    ((brx-paccept "LPAREN")
      (setq args (brx-parse-args))
      (if (and args (= (brx-ast-node (car args)) "PERR"))
        (car args)
        (brx-ast-call name args)
      )
    )

    ((brx-cell-addr-p name)
      (if (brx-paccept "COLON")
        (progn
          (setq rhs (brx-pexpect "IDENT"))
          (if (= (brx-ast-node rhs) "PERR")
            rhs
            (if (brx-cell-addr-p (brx-tok-val rhs))
              (brx-ast-ref "TABLE" "RANGE" (strcat name ":" (brx-tok-val rhs)))
              (brx-ast-error "009" "Invalid range end"))
          )
        )
        (brx-ast-ref "TABLE" "CELL" name)
      )
    )

    ((brx-paccept "DOT")
      (setq rhs (brx-pexpect "IDENT"))
      (if (= (brx-ast-node rhs) "PERR")
        rhs
        (brx-make-scoped-ref name (brx-tok-val rhs))
      )
    )

    (T
      (brx-ast-ref "SELF" "ALIAS" name)
    )
  )
)

(defun brx-parse-dot-primary ( / rhs)
  (setq rhs (brx-pexpect "IDENT"))
  (if (= (brx-ast-node rhs) "PERR")
    rhs
    (brx-make-scoped-ref "SELF" (brx-tok-val rhs))
  )
)

(defun brx-parse-primary ( / tok typ val ast)
  (setq tok (brx-pcur))
  (if (null tok)
    (brx-ast-error "009" "Unexpected end of expression")
    (progn
      (setq typ (brx-tok-type tok))
      (setq val (brx-tok-val tok))
      (cond
        ((= typ "NUMBER")
          (brx-padvance)
          (setq val (brx-try-parse-number val))
          (if val
            (brx-ast-lit (brx-make-ok "NUMBER" val))
            (brx-ast-error "009" "Invalid number")
          )
        )

        ((= typ "STRING")
          (brx-padvance)
          (brx-ast-lit (brx-make-ok "TEXT" val))
        )

        ((= typ "IDENT")
          (brx-padvance)
          (brx-parse-ident-primary val)
        )

        ((= typ "DOT")
          (brx-padvance)
          (brx-parse-dot-primary)
        )

        ((= typ "LPAREN")
          (brx-padvance)
          (setq ast (brx-parse-expr))
          (if (= (brx-ast-node ast) "PERR")
            ast
            (progn
              (setq tok (brx-pexpect "RPAREN"))
              (if (= (brx-ast-node tok) "PERR") tok ast)
            )
          )
        )

        (T
          (brx-ast-error "009" (strcat "Unexpected token: " typ))
        )
      )
    )
  )
)

(defun brx-parse-expr ( /)
  ;; Current grammar is functional/prefix, no infix operators yet.
  (brx-parse-primary)
)

(defun brx-parse (expr / toks ast)
  (setq toks (brx-tokenize expr))
  (if (null toks)
    (brx-make-err "009")
    (if (= (brx-tok-type (car toks)) "ERR")
      (brx-make-err "009")
      (progn
        (brx-parser-init toks)
        (setq ast (brx-parse-expr))
        (cond
          ((= (brx-ast-node ast) "PERR") (brx-make-err "009"))
          ((brx-pcur)                     (brx-make-err "009"))
          (T ast)
        )
      )
    )
  )
)

;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------

(defun brx-resolve-ref (ctx scope kind name /)
  ;; Planned logic based on spec:
  ;; SELF/MASTER/ROW/COL/MATCH/GROUP/TABLE/CELL + ATTR/PARAM/FIELD/CELL/HANDLE/BLOCKNAME/AUTO/ALIAS
  ;; Current version intentionally returns REF until owner-aware resolver is implemented.
  (brx-make-err "003")
)

;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------

(defun brx-fn-if (ctx args / c)
  (if (/= (length args) 3)
    (brx-make-err "005")
    (progn
      (setq c (brx-eval-ast ctx (nth 0 args)))
      (if (brx-err-p c)
        c
        (if (brx-rv-value c)
          (brx-eval-ast ctx (nth 1 args))
          (brx-eval-ast ctx (nth 2 args))
        )
      )
    )
  )
)

(defun brx-fn-and (ctx args / one)
  (while args
    (setq one (brx-eval-ast ctx (car args)))
    (if (brx-err-p one)
      (progn (setq args nil) (setq one one))
      (if (not (brx-rv-value one))
        (progn (setq args nil) (setq one (brx-bool-rv nil)))
        (setq args (cdr args))
      )
    )
  )
  (if one one (brx-bool-rv T))
)

(defun brx-fn-or (ctx args / one hit)
  (setq hit nil)
  (while args
    (setq one (brx-eval-ast ctx (car args)))
    (if (brx-err-p one)
      (progn (setq args nil) (setq hit one))
      (if (brx-rv-value one)
        (progn (setq args nil) (setq hit (brx-bool-rv T)))
        (setq args (cdr args))
      )
    )
  )
  (if hit hit (brx-bool-rv nil))
)

(defun brx-fn-not (ctx args / v)
  (if (/= (length args) 1)
    (brx-make-err "005")
    (progn
      (setq v (brx-eval-ast ctx (car args)))
      (if (brx-err-p v)
        v
        (brx-bool-rv (not (brx-rv-value v)))
      )
    )
  )
)

(defun brx-dispatch-fn (ctx fname args / u)
  (setq u (strcase fname T))
  (cond
    ((= u "IF")    (brx-fn-if ctx args))
    ((= u "AND")   (brx-fn-and ctx args))
    ((= u "OR")    (brx-fn-or ctx args))
    ((= u "NOT")   (brx-fn-not ctx args))
    ((= u "TRUE")  (brx-bool-rv T))
    ((= u "FALSE") (brx-bool-rv nil))
    (T              (brx-make-err "005"))
  )
)

;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------

(defun brx-eval-ast (ctx ast / node)
  (cond
    ((null ast) (brx-make-err "005"))
    (T
      (setq node (cdr (assoc :node ast)))
      (cond
        ((= node "LIT")
          (cdr (assoc :value ast))
        )
        ((= node "REF")
          (brx-resolve-ref
            ctx
            (cdr (assoc :scope ast))
            (cdr (assoc :kind ast))
            (cdr (assoc :name ast))
          )
        )
        ((= node "CALL")
          (brx-dispatch-fn
            ctx
            (cdr (assoc :name ast))
            (cdr (assoc :args ast))
          )
        )
        (T
          (brx-make-err "005")
        )
      )
    )
  )
)

(defun brx-eval-expr (ctx expr / ast)
  (setq ast (brx-parse expr))
  (if (and (listp ast) (assoc :kind ast))
    ast
    (brx-eval-ast ctx ast)
  )
)

;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------

(defun brx-rv->string (rv /)
  (cond
    ((null rv) "<nil>")
    ((brx-ok-p rv)
      (strcat "[OK " (brx-rv-type rv) " " (vl-princ-to-string (brx-rv-value rv)) "]")
    )
    ((brx-err-p rv)
      (strcat "[ERR " (brx-rv-code rv) " " (brx-rv-name rv) "]")
    )
    (T
      (vl-princ-to-string rv)
    )
  )
)

(defun brx-ast->string (ast / node args out one)
  (if (null ast)
    "<nil>"
    (progn
      (setq node (brx-ast-node ast))
      (cond
        ((= node "LIT")
          (strcat "LIT(" (brx-rv->string (cdr (assoc :value ast))) ")")
        )
        ((= node "REF")
          (strcat
            "REF("
            (cdr (assoc :scope ast)) ":"
            (cdr (assoc :kind ast)) ":"
            (cdr (assoc :name ast))
            ")"
          )
        )
        ((= node "CALL")
          (setq args (cdr (assoc :args ast)))
          (setq out nil)
          (while args
            (setq one (brx-ast->string (car args)))
            (setq out (cons one out))
            (setq args (cdr args))
          )
          (strcat "CALL(" (cdr (assoc :name ast)) " [" (brx-join (reverse out) ", ") "])" )
        )
        ((= node "PERR")
          (strcat "PERR(" (cdr (assoc :message ast)) ")")
        )
        (T
          (vl-princ-to-string ast)
        )
      )
    )
  )
)

(defun c:BRX-TEST-TOKENIZE ( / expr toks )
  (setq expr "IF(MASTER.PARAMDistance1,\"OK\",\"NO\")")
  (setq toks (brx-tokenize expr))
  (princ (strcat "\nCANON: " (brx-tokens->canon toks)))
  (while toks
    (princ (strcat "\n" (brx-tok-type (car toks)) " -> " (brx-tok-val (car toks))))
    (setq toks (cdr toks))
  )
  (princ)
)

(defun c:BRX-TEST-PARSE ( / samples ast )
  (setq samples
    '(
      "IF(TRUE,\"YES\",\"NO\")"
      "MASTER.PARAMDistance1"
      ".TAG"
      "A1"
      "A1:B3"
      "COUNTIFATTR(CUBE,NUM,1)"
    )
  )
  (while samples
    (setq ast (brx-parse (car samples)))
    (princ (strcat "\nEXPR: " (car samples)))
    (if (and (listp ast) (assoc :kind ast))
      (princ (strcat "\n  => " (brx-rv->string ast)))
      (princ (strcat "\n  => " (brx-ast->string ast)))
    )
    (setq samples (cdr samples))
  )
  (princ)
)

(defun c:BRX-TEST-EVAL ( / rv )
  (setq rv (brx-eval-expr nil "IF(TRUE,\"YES\",\"NO\")"))
  (princ (strcat "\n" (brx-rv->string rv)))
  (princ)
)


;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================

(defun brx-alist-get (al key / p)
  (setq p (assoc key al))
  (if p (cdr p) nil)
)

(defun brx-object-p (obj /)
  (and (listp obj) (or (assoc :handle obj) (assoc :name obj) (assoc :role obj)))
)

(defun brx-object-role (obj /)
  (brx-alist-get obj :role)
)

(defun brx-object-name (obj /)
  (brx-alist-get obj :name)
)

(defun brx-object-handle (obj /)
  (brx-alist-get obj :handle)
)

(defun brx-object-attrs (obj /)
  (or (brx-alist-get obj :attrs) nil)
)

(defun brx-object-params (obj /)
  (or (brx-alist-get obj :params) nil)
)

(defun brx-object-fields (obj /)
  (or (brx-alist-get obj :fields) nil)
)

(defun brx-object-get-attr (obj tag /)
  (cdr (assoc (strcase tag T) (brx-object-attrs obj)))
)

(defun brx-object-get-param (obj name /)
  (cdr (assoc (strcase name T) (brx-object-params obj)))
)

(defun brx-object-get-field (obj name /)
  (cdr (assoc (strcase name T) (brx-object-fields obj)))
)

(defun brx-object-get-auto (obj name / v)
  (setq v (brx-object-get-param obj name))
  (if v v
    (progn
      (setq v (brx-object-get-attr obj name))
      (if v v
        (brx-object-get-field obj name)
      )
    )
  )
)

(defun brx-wrap-host-value (v /)
  (cond
    ((and (listp v) (assoc :kind v)) v)
    ((null v) (brx-make-err "001"))
    ((brx-number-p v) (brx-make-ok "NUMBER" v))
    ((= (type v) 'STR) (brx-make-ok "TEXT" v))
    ((or (= v T) (= v nil)) (brx-make-ok "BOOL" (if v T nil)))
    ((listp v) (brx-make-ok "LIST" v))
    (T (brx-make-ok "OBJECT" v))
  )
)

(defun brx-ctx-scope-object (ctx scope / s)
  (setq s (strcase scope T))
  (cond
    ((= s "SELF")   (brx-ctx-get ctx :self))
    ((= s "MASTER") (brx-ctx-get ctx :master))
    ((= s "ROW")    (brx-ctx-get ctx :row))
    ((= s "COL")    (brx-ctx-get ctx :col))
    ((= s "MATCH")  (brx-ctx-get ctx :match))
    ((= s "TABLE")  (brx-ctx-get ctx :table))
    ((= s "CELL")   (brx-ctx-get ctx :cell))
    ((= s "GROUP")  (brx-ctx-get ctx :group))
    (T nil)
  )
)

(defun brx-group-object-list (grp key /)
  (or (cdr (assoc key grp)) nil)
)

(defun brx-resolve-structural-ref (ctx scope kind name / obj grp)
  (setq obj (brx-ctx-scope-object ctx scope))
  (setq grp (brx-ctx-get ctx :group))
  (cond
    ((= kind "OBJECTS") (brx-wrap-host-value (brx-group-object-list grp :objects)))
    ((= kind "SLAVES")  (brx-wrap-host-value (brx-group-object-list grp :slaves)))
    ((= kind "TABLES")  (brx-wrap-host-value (brx-group-object-list grp :tables)))
    ((= kind "MATCHES") (brx-wrap-host-value (or (brx-alist-get obj :matches) nil)))
    ((= kind "SET")     (brx-wrap-host-value (or (brx-alist-get obj :set) nil)))
    ((= kind "VALUE")   (brx-wrap-host-value (or (brx-alist-get obj :value) nil)))
    (T nil)
  )
)

(defun brx-resolve-basic-ref (ctx scope kind name / obj v)
  (setq obj (brx-ctx-scope-object ctx scope))
  (cond
    ((null obj) (brx-make-err "008"))
    ((= kind "ATTR")      (brx-wrap-host-value (brx-object-get-attr obj name)))
    ((= kind "PARAM")     (brx-wrap-host-value (brx-object-get-param obj name)))
    ((= kind "FIELD")     (brx-wrap-host-value (brx-object-get-field obj name)))
    ((= kind "HANDLE")    (brx-wrap-host-value (brx-object-handle obj)))
    ((= kind "BLOCKNAME") (brx-wrap-host-value (brx-object-name obj)))
    ((= kind "AUTO")      (brx-wrap-host-value (brx-object-get-auto obj name)))
    ((or (= kind "OBJECTS") (= kind "SLAVES") (= kind "TABLES") (= kind "MATCHES") (= kind "SET") (= kind "VALUE"))
      (brx-resolve-structural-ref ctx scope kind name)
    )
    (T (brx-make-err "003"))
  )
)

(defun brx-resolve-ref (ctx scope kind name /)
  (brx-resolve-basic-ref ctx scope kind name)
)


;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================

(defun brx-stack-key (scope kind name /)
  (strcat (strcase scope T) ":" (strcase kind T) ":" (strcase name T))
)

(defun brx-alias-table (ctx /)
  (or (brx-ctx-get ctx :aliases) nil)
)

(defun brx-alias-expr (ctx name /)
  (cdr (assoc (strcase name T) (brx-alias-table ctx)))
)

(defun brx-exact-object-by-handle (ctx handle / objs hit)
  (setq objs (append
               (or (brx-group-object-list (brx-ctx-get ctx :group) :objects) nil)
               (or (brx-group-object-list (brx-ctx-get ctx :group) :tables) nil)
             ))
  (setq hit nil)
  (while objs
    (if (= (strcase (vl-princ-to-string (brx-object-handle (car objs))) T)
           (strcase (vl-princ-to-string handle) T))
      (progn (setq hit (car objs)) (setq objs nil))
      (setq objs (cdr objs))
    )
  )
  hit
)

(defun brx-ensure-singleton (lst /)
  (cond
    ((null lst) (brx-make-err "001"))
    ((and (listp lst) (= (length lst) 1)) (brx-wrap-host-value (car lst)))
    ((listp lst) (brx-make-err "002"))
    (T (brx-wrap-host-value lst))
  )
)

(defun brx-eval-alias (ctx aliasName / expr key)
  (setq key (brx-stack-key "SELF" "ALIAS" aliasName))
  (cond
    ((brx-ctx-in-stack-p ctx key) (brx-make-err "007"))
    (T
      (setq expr (brx-alias-expr ctx aliasName))
      (if (null expr)
        (brx-make-err "003")
        (brx-eval-expr (brx-ctx-push-stack ctx key) expr)
      )
    )
  )
)

(defun brx-resolve-special-ref (ctx scope kind name / h)
  (cond
    ((and (= (strcase scope T) "SELF") (= kind "ALIAS"))
      (brx-eval-alias ctx name)
    )
    ((and (= kind "HANDLE") name (/= name ""))
      (setq h (brx-exact-object-by-handle ctx name))
      (if h (brx-wrap-host-value h) (brx-make-err "003"))
    )
    (T nil)
  )
)

(defun brx-resolve-ref (ctx scope kind name / rv)
  (setq rv (brx-resolve-special-ref ctx scope kind name))
  (if rv rv (brx-resolve-basic-ref ctx scope kind name))
)


;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================

(defun brx-rv-number (rv / n)
  (cond
    ((brx-err-p rv) rv)
    ((= (brx-rv-type rv) "NUMBER") rv)
    (T
      (setq n (brx-try-parse-number (brx-rv-value rv)))
      (if n (brx-make-ok "NUMBER" n) (brx-make-err "004"))
    )
  )
)

(defun brx-rv-text (rv /)
  (cond
    ((brx-err-p rv) rv)
    ((= (brx-rv-type rv) "TEXT") rv)
    (T (brx-make-ok "TEXT" (vl-princ-to-string (brx-rv-value rv))))
  )
)

(defun brx-eval-args (ctx args / out one)
  (setq out nil)
  (while args
    (setq one (brx-eval-ast ctx (car args)))
    (setq out (cons one out))
    (setq args (cdr args))
  )
  (reverse out)
)

(defun brx-any-error (lst / hit)
  (setq hit nil)
  (while lst
    (if (brx-err-p (car lst)) (progn (setq hit (car lst)) (setq lst nil)) (setq lst (cdr lst)))
  )
  hit
)

(defun brx-fn-abs (ctx args / vals x)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 1) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn (setq x (brx-rv-number (car vals))) (if (brx-err-p x) x (brx-make-ok "NUMBER" (abs (brx-rv-value x)))))
  )
)

(defun brx-fn-int (ctx args / vals x)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 1) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn (setq x (brx-rv-number (car vals))) (if (brx-err-p x) x (brx-make-ok "NUMBER" (fix (brx-rv-value x)))))
  )
)

(defun brx-fn-round (ctx args / vals x n p)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq x (brx-rv-number (nth 0 vals)))
      (setq n (brx-rv-number (nth 1 vals)))
      (if (or (brx-err-p x) (brx-err-p n))
        (or (if (brx-err-p x) x nil) (if (brx-err-p n) n nil))
        (progn
          (setq p (expt 10 (fix (brx-rv-value n))))
          (brx-make-ok "NUMBER" (/ (float (fix (+ 0.5 (* (brx-rv-value x) p)))) p))
        )
      )
    )
  )
)

(defun brx-fn-roundup (ctx args / vals x n p)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq x (brx-rv-number (nth 0 vals)))
      (setq n (brx-rv-number (nth 1 vals)))
      (if (or (brx-err-p x) (brx-err-p n))
        (or (if (brx-err-p x) x nil) (if (brx-err-p n) n nil))
        (progn
          (setq p (expt 10 (fix (brx-rv-value n))))
          (brx-make-ok "NUMBER" (/ (float (fix (+ (* (brx-rv-value x) p) 0.999999))) p))
        )
      )
    )
  )
)

(defun brx-fn-rounddown (ctx args / vals x n p)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq x (brx-rv-number (nth 0 vals)))
      (setq n (brx-rv-number (nth 1 vals)))
      (if (or (brx-err-p x) (brx-err-p n))
        (or (if (brx-err-p x) x nil) (if (brx-err-p n) n nil))
        (progn
          (setq p (expt 10 (fix (brx-rv-value n))))
          (brx-make-ok "NUMBER" (/ (float (fix (* (brx-rv-value x) p))) p))
        )
      )
    )
  )
)

(defun brx-fn-sqrt (ctx args / vals x)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 1) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq x (brx-rv-number (car vals)))
      (if (or (brx-err-p x) (< (brx-rv-value x) 0.0)) (brx-make-err "005") (brx-make-ok "NUMBER" (sqrt (brx-rv-value x))))
    )
  )
)

(defun brx-fn-power (ctx args / vals a b)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (brx-rv-number (nth 0 vals)))
      (setq b (brx-rv-number (nth 1 vals)))
      (if (or (brx-err-p a) (brx-err-p b)) (or (if (brx-err-p a) a nil) (if (brx-err-p b) b nil))
        (brx-make-ok "NUMBER" (expt (brx-rv-value a) (brx-rv-value b)))
      )
    )
  )
)

(defun brx-fn-mod (ctx args / vals a b)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (brx-rv-number (nth 0 vals)))
      (setq b (brx-rv-number (nth 1 vals)))
      (if (or (brx-err-p a) (brx-err-p b))
        (or (if (brx-err-p a) a nil) (if (brx-err-p b) b nil))
        (if (= (brx-rv-value b) 0) (brx-make-err "006") (brx-make-ok "NUMBER" (rem (fix (brx-rv-value a)) (fix (brx-rv-value b)))))
      )
    )
  )
)

(defun brx-fn-sign (ctx args / vals x)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 1) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq x (brx-rv-number (car vals)))
      (if (brx-err-p x) x
        (brx-make-ok "NUMBER" (cond ((> (brx-rv-value x) 0) 1) ((< (brx-rv-value x) 0) -1) (T 0)))
      )
    )
  )
)

(defun brx-fn-minmax (ctx args wantMax / vals nums one acc)
  (setq vals (brx-eval-args ctx args))
  (if (or (null vals) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq nums nil)
      (while vals
        (setq one (brx-rv-number (car vals)))
        (if (brx-err-p one) (progn (setq nums (list one)) (setq vals nil))
          (setq nums (cons (brx-rv-value one) nums))
        )
        (if vals (setq vals (cdr vals)))
      )
      (if (and nums (listp nums) (brx-err-p (car nums)))
        (car nums)
        (progn
          (setq acc (car nums))
          (foreach one (cdr nums)
            (if wantMax
              (if (> one acc) (setq acc one))
              (if (< one acc) (setq acc one))
            )
          )
          (brx-make-ok "NUMBER" acc)
        )
      )
    )
  )
)

(defun brx-dispatch-fn (ctx fname args / u)
  (setq u (strcase fname T))
  (cond
    ((= u "IF")        (brx-fn-if ctx args))
    ((= u "AND")       (brx-fn-and ctx args))
    ((= u "OR")        (brx-fn-or ctx args))
    ((= u "NOT")       (brx-fn-not ctx args))
    ((= u "TRUE")      (brx-bool-rv T))
    ((= u "FALSE")     (brx-bool-rv nil))
    ((= u "ABS")       (brx-fn-abs ctx args))
    ((= u "INT")       (brx-fn-int ctx args))
    ((= u "ROUND")     (brx-fn-round ctx args))
    ((= u "ROUNDUP")   (brx-fn-roundup ctx args))
    ((= u "ROUNDDOWN") (brx-fn-rounddown ctx args))
    ((= u "SQRT")      (brx-fn-sqrt ctx args))
    ((= u "POWER")     (brx-fn-power ctx args))
    ((= u "MOD")       (brx-fn-mod ctx args))
    ((= u "SIGN")      (brx-fn-sign ctx args))
    ((= u "MAX")       (brx-fn-minmax ctx args T))
    ((= u "MIN")       (brx-fn-minmax ctx args nil))
    ((= u "PI")        (brx-make-ok "NUMBER" pi))
    (T                  (brx-make-err "005"))
  )
)


;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================

(defun brx-rv-bool (rv /)
  (cond
    ((brx-err-p rv) rv)
    ((= (brx-rv-type rv) "BOOL") rv)
    ((= (brx-rv-type rv) "NUMBER") (brx-bool-rv (/= (brx-rv-value rv) 0)))
    ((= (brx-rv-type rv) "TEXT")   (brx-bool-rv (/= (strlen (brx-rv-value rv)) 0)))
    ((= (brx-rv-type rv) "LIST")   (brx-bool-rv (> (length (brx-rv-value rv)) 0)))
    (T (brx-bool-rv (if (brx-rv-value rv) T nil)))
  )
)

(defun brx-value-equal-p (a b /)
  (equal (vl-princ-to-string a) (vl-princ-to-string b))
)

(defun brx-fn-compare (ctx args op / vals a b na nb)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (nth 0 vals))
      (setq b (nth 1 vals))
      (setq na (brx-rv-number a))
      (setq nb (brx-rv-number b))
      (if (and (not (brx-err-p na)) (not (brx-err-p nb)))
        (brx-bool-rv
          (cond
            ((= op "EQ") (= (brx-rv-value na) (brx-rv-value nb)))
            ((= op "NE") (/= (brx-rv-value na) (brx-rv-value nb)))
            ((= op "GT") (> (brx-rv-value na) (brx-rv-value nb)))
            ((= op "GE") (>= (brx-rv-value na) (brx-rv-value nb)))
            ((= op "LT") (< (brx-rv-value na) (brx-rv-value nb)))
            ((= op "LE") (<= (brx-rv-value na) (brx-rv-value nb)))
            (T nil)
          )
        )
        (brx-bool-rv
          (cond
            ((= op "EQ") (brx-value-equal-p (brx-rv-value a) (brx-rv-value b)))
            ((= op "NE") (not (brx-value-equal-p (brx-rv-value a) (brx-rv-value b))))
            ((member op '("GT" "GE" "LT" "LE")) nil)
            (T nil)
          )
        )
      )
    )
  )
)

(defun brx-text-find (txt part /)
  (if (and txt part)
    (vl-string-search (strcase part T) (strcase txt T))
    nil
  )
)

(defun brx-fn-contains-text (ctx args / vals a b)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (brx-rv-text (nth 0 vals)))
      (setq b (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p a) (brx-err-p b)) (or (if (brx-err-p a) a nil) (if (brx-err-p b) b nil))
        (brx-bool-rv (if (brx-text-find (brx-rv-value a) (brx-rv-value b)) T nil))
      )
    )
  )
)

(defun brx-fn-startswith (ctx args / vals a b)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (brx-rv-text (nth 0 vals)))
      (setq b (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p a) (brx-err-p b)) (or (if (brx-err-p a) a nil) (if (brx-err-p b) b nil))
        (brx-bool-rv (= 0 (vl-string-search (strcase (brx-rv-value b) T) (strcase (brx-rv-value a) T))))
      )
    )
  )
)

(defun brx-fn-endswith (ctx args / vals a b ta tb la lb)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (brx-rv-text (nth 0 vals)))
      (setq b (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p a) (brx-err-p b)) (or (if (brx-err-p a) a nil) (if (brx-err-p b) b nil))
        (progn
          (setq ta (strcase (brx-rv-value a) T))
          (setq tb (strcase (brx-rv-value b) T))
          (setq la (strlen ta))
          (setq lb (strlen tb))
          (brx-bool-rv (and (>= la lb) (= (substr ta (- (+ la 1) lb)) tb)))
        )
      )
    )
  )
)

(defun brx-fn-isblank (ctx args / vals a)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1)
    (brx-make-err "005")
    (progn
      (setq a (car vals))
      (if (brx-err-p a)
        (brx-bool-rv nil)
        (brx-bool-rv (or (null (brx-rv-value a)) (= (vl-princ-to-string (brx-rv-value a)) "")))
      )
    )
  )
)

(defun brx-fn-iserror (ctx args / vals)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1) (brx-make-err "005") (brx-bool-rv (brx-err-p (car vals))))
)

(defun brx-fn-istype (ctx args tname / vals a)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1)
    (brx-make-err "005")
    (progn (setq a (car vals)) (brx-bool-rv (and (not (brx-err-p a)) (= (brx-rv-type a) tname))))
  )
)

(defun brx-fn-iferror (ctx args / first)
  (if (/= (length args) 2)
    (brx-make-err "005")
    (progn
      (setq first (brx-eval-ast ctx (nth 0 args)))
      (if (brx-err-p first)
        (brx-eval-ast ctx (nth 1 args))
        first
      )
    )
  )
)

(defun brx-dispatch-fn (ctx fname args / u)
  (setq u (strcase fname T))
  (cond
    ((= u "IF")           (brx-fn-if ctx args))
    ((= u "AND")          (brx-fn-and ctx args))
    ((= u "OR")           (brx-fn-or ctx args))
    ((= u "NOT")          (brx-fn-not ctx args))
    ((= u "TRUE")         (brx-bool-rv T))
    ((= u "FALSE")        (brx-bool-rv nil))
    ((= u "ABS")          (brx-fn-abs ctx args))
    ((= u "INT")          (brx-fn-int ctx args))
    ((= u "ROUND")        (brx-fn-round ctx args))
    ((= u "ROUNDUP")      (brx-fn-roundup ctx args))
    ((= u "ROUNDDOWN")    (brx-fn-rounddown ctx args))
    ((= u "SQRT")         (brx-fn-sqrt ctx args))
    ((= u "POWER")        (brx-fn-power ctx args))
    ((= u "MOD")          (brx-fn-mod ctx args))
    ((= u "SIGN")         (brx-fn-sign ctx args))
    ((= u "MAX")          (brx-fn-minmax ctx args T))
    ((= u "MIN")          (brx-fn-minmax ctx args nil))
    ((= u "PI")           (brx-make-ok "NUMBER" pi))
    ((= u "EQ")           (brx-fn-compare ctx args "EQ"))
    ((= u "NE")           (brx-fn-compare ctx args "NE"))
    ((= u "GT")           (brx-fn-compare ctx args "GT"))
    ((= u "GE")           (brx-fn-compare ctx args "GE"))
    ((= u "LT")           (brx-fn-compare ctx args "LT"))
    ((= u "LE")           (brx-fn-compare ctx args "LE"))
    ((= u "CONTAINSTEXT") (brx-fn-contains-text ctx args))
    ((= u "STARTSWITH")   (brx-fn-startswith ctx args))
    ((= u "ENDSWITH")     (brx-fn-endswith ctx args))
    ((= u "ISBLANK")      (brx-fn-isblank ctx args))
    ((= u "ISERROR")      (brx-fn-iserror ctx args))
    ((= u "ISNUMBER")     (brx-fn-istype ctx args "NUMBER"))
    ((= u "ISTEXT")       (brx-fn-istype ctx args "TEXT"))
    ((= u "ISLIST")       (brx-fn-istype ctx args "LIST"))
    ((= u "IFERROR")      (brx-fn-iferror ctx args))
    (T                     (brx-make-err "005"))
  )
)


;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================

(defun brx-repeat (ch n / out)
  (setq out "")
  (repeat (max 0 n) (setq out (strcat out ch)))
  out
)

(defun brx-format-number (num pattern / dec p txt pos need have)
  (setq txt (rtos num 2 8))
  (if (and pattern (vl-string-search "." pattern))
    (progn
      (setq pos (vl-string-search "." pattern))
      (setq dec (- (strlen pattern) pos 1))
      (rtos num 2 dec)
    )
    txt
  )
)

(defun brx-fn-format (ctx args / vals a pat)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (nth 0 vals))
      (setq pat (brx-rv-text (nth 1 vals)))
      (if (brx-err-p pat)
        pat
        (if (= (brx-rv-type a) "NUMBER")
          (brx-make-ok "TEXT" (brx-format-number (brx-rv-value a) (brx-rv-value pat)))
          (brx-rv-text a)
        )
      )
    )
  )
)

(defun brx-fn-prefix (ctx args / vals a p)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (brx-rv-text (nth 0 vals)))
      (setq p (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p a) (brx-err-p p)) (or (if (brx-err-p a) a nil) (if (brx-err-p p) p nil))
        (brx-make-ok "TEXT" (strcat (brx-rv-value p) (brx-rv-value a)))
      )
    )
  )
)

(defun brx-fn-suffix (ctx args / vals a p)
  (setq vals (brx-eval-args ctx args))
  (if (or (/= (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq a (brx-rv-text (nth 0 vals)))
      (setq p (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p a) (brx-err-p p)) (or (if (brx-err-p a) a nil) (if (brx-err-p p) p nil))
        (brx-make-ok "TEXT" (strcat (brx-rv-value a) (brx-rv-value p)))
      )
    )
  )
)

(defun brx-fn-hidezero (ctx args / vals a)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1)
    (brx-make-err "005")
    (progn
      (setq a (car vals))
      (if (brx-err-p a)
        a
        (if (and (= (brx-rv-type a) "NUMBER") (= (brx-rv-value a) 0))
          (brx-make-ok "TEXT" "")
          a
        )
      )
    )
  )
)

(defun brx-fn-ifempty (ctx args / a b)
  (if (/= (length args) 2)
    (brx-make-err "005")
    (progn
      (setq a (brx-eval-ast ctx (nth 0 args)))
      (if (and (not (brx-err-p a)) (/= (vl-princ-to-string (brx-rv-value a)) ""))
        a
        (brx-eval-ast ctx (nth 1 args))
      )
    )
  )
)

(defun brx-fn-jointext (ctx args / vals delim out one)
  (setq vals (brx-eval-args ctx args))
  (if (or (< (length vals) 2) (brx-any-error vals))
    (or (brx-any-error vals) (brx-make-err "005"))
    (progn
      (setq delim (brx-rv-text (car vals)))
      (if (brx-err-p delim)
        delim
        (progn
          (setq vals (cdr vals))
          (setq out nil)
          (while vals
            (setq one (brx-rv-text (car vals)))
            (if (not (brx-err-p one)) (setq out (cons (brx-rv-value one) out)))
            (setq vals (cdr vals))
          )
          (brx-make-ok "TEXT" (brx-join (reverse out) (brx-rv-value delim)))
        )
      )
    )
  )
)

(defun brx-dispatch-fn (ctx fname args / u)
  (setq u (strcase fname T))
  (cond
    ((= u "IF")           (brx-fn-if ctx args))
    ((= u "AND")          (brx-fn-and ctx args))
    ((= u "OR")           (brx-fn-or ctx args))
    ((= u "NOT")          (brx-fn-not ctx args))
    ((= u "TRUE")         (brx-bool-rv T))
    ((= u "FALSE")        (brx-bool-rv nil))
    ((= u "ABS")          (brx-fn-abs ctx args))
    ((= u "INT")          (brx-fn-int ctx args))
    ((= u "ROUND")        (brx-fn-round ctx args))
    ((= u "ROUNDUP")      (brx-fn-roundup ctx args))
    ((= u "ROUNDDOWN")    (brx-fn-rounddown ctx args))
    ((= u "SQRT")         (brx-fn-sqrt ctx args))
    ((= u "POWER")        (brx-fn-power ctx args))
    ((= u "MOD")          (brx-fn-mod ctx args))
    ((= u "SIGN")         (brx-fn-sign ctx args))
    ((= u "MAX")          (brx-fn-minmax ctx args T))
    ((= u "MIN")          (brx-fn-minmax ctx args nil))
    ((= u "PI")           (brx-make-ok "NUMBER" pi))
    ((= u "EQ")           (brx-fn-compare ctx args "EQ"))
    ((= u "NE")           (brx-fn-compare ctx args "NE"))
    ((= u "GT")           (brx-fn-compare ctx args "GT"))
    ((= u "GE")           (brx-fn-compare ctx args "GE"))
    ((= u "LT")           (brx-fn-compare ctx args "LT"))
    ((= u "LE")           (brx-fn-compare ctx args "LE"))
    ((= u "CONTAINSTEXT") (brx-fn-contains-text ctx args))
    ((= u "STARTSWITH")   (brx-fn-startswith ctx args))
    ((= u "ENDSWITH")     (brx-fn-endswith ctx args))
    ((= u "ISBLANK")      (brx-fn-isblank ctx args))
    ((= u "ISERROR")      (brx-fn-iserror ctx args))
    ((= u "ISNUMBER")     (brx-fn-istype ctx args "NUMBER"))
    ((= u "ISTEXT")       (brx-fn-istype ctx args "TEXT"))
    ((= u "ISLIST")       (brx-fn-istype ctx args "LIST"))
    ((= u "IFERROR")      (brx-fn-iferror ctx args))
    ((or (= u "FORMAT") (= u "FMT")) (brx-fn-format ctx args))
    ((or (= u "PREFIX") (= u "PFX")) (brx-fn-prefix ctx args))
    ((or (= u "SUFFIX") (= u "SFX") (= u "UNIT")) (brx-fn-suffix ctx args))
    ((= u "HIDEZERO")     (brx-fn-hidezero ctx args))
    ((= u "IFEMPTY")      (brx-fn-ifempty ctx args))
    ((or (= u "JOIN") (= u "JOINTEXT")) (brx-fn-jointext ctx args))
    (T                     (brx-make-err "005"))
  )
)


;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================

(defun brx-list-contains-p (lst val / hit)
  (setq hit nil)
  (while lst
    (if (brx-value-equal-p (car lst) val) (progn (setq hit T) (setq lst nil)) (setq lst (cdr lst)))
  )
  hit
)

(defun brx-fn-in (ctx args / vals needle hay)
  (setq vals (brx-eval-args ctx args))
  (if (< (length vals) 2)
    (brx-make-err "005")
    (progn
      (setq needle (brx-rv-value (car vals)))
      (setq hay nil)
      (foreach one (cdr vals) (setq hay (cons (brx-rv-value one) hay)))
      (brx-bool-rv (brx-list-contains-p hay needle))
    )
  )
)

(defun brx-fn-contains (ctx args / vals set needle)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 2)
    (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (nth 0 vals)))
      (setq needle (nth 1 vals))
      (if (brx-err-p set) set (brx-bool-rv (brx-list-contains-p (brx-rv-value set) (brx-rv-value needle))))
    )
  )
)

(defun brx-dispatch-fn (ctx fname args / u)
  (setq u (strcase fname T))
  (cond
    ((= u "IN")           (brx-fn-in ctx args))
    ((= u "CONTAINS")     (brx-fn-contains ctx args))
    (T (eval (list 'brx-dispatch-fn ctx fname args)))
  )
)


(defun brx-dispatch-fn (ctx fname args / u)
  (setq u (strcase fname T))
  (cond
    ((= u "IF")           (brx-fn-if ctx args))
    ((= u "AND")          (brx-fn-and ctx args))
    ((= u "OR")           (brx-fn-or ctx args))
    ((= u "NOT")          (brx-fn-not ctx args))
    ((= u "TRUE")         (brx-bool-rv T))
    ((= u "FALSE")        (brx-bool-rv nil))
    ((= u "ABS")          (brx-fn-abs ctx args))
    ((= u "INT")          (brx-fn-int ctx args))
    ((= u "ROUND")        (brx-fn-round ctx args))
    ((= u "ROUNDUP")      (brx-fn-roundup ctx args))
    ((= u "ROUNDDOWN")    (brx-fn-rounddown ctx args))
    ((= u "SQRT")         (brx-fn-sqrt ctx args))
    ((= u "POWER")        (brx-fn-power ctx args))
    ((= u "MOD")          (brx-fn-mod ctx args))
    ((= u "SIGN")         (brx-fn-sign ctx args))
    ((= u "MAX")          (brx-fn-minmax ctx args T))
    ((= u "MIN")          (brx-fn-minmax ctx args nil))
    ((= u "PI")           (brx-make-ok "NUMBER" pi))
    ((= u "EQ")           (brx-fn-compare ctx args "EQ"))
    ((= u "NE")           (brx-fn-compare ctx args "NE"))
    ((= u "GT")           (brx-fn-compare ctx args "GT"))
    ((= u "GE")           (brx-fn-compare ctx args "GE"))
    ((= u "LT")           (brx-fn-compare ctx args "LT"))
    ((= u "LE")           (brx-fn-compare ctx args "LE"))
    ((= u "CONTAINSTEXT") (brx-fn-contains-text ctx args))
    ((= u "STARTSWITH")   (brx-fn-startswith ctx args))
    ((= u "ENDSWITH")     (brx-fn-endswith ctx args))
    ((= u "ISBLANK")      (brx-fn-isblank ctx args))
    ((= u "ISERROR")      (brx-fn-iserror ctx args))
    ((= u "ISNUMBER")     (brx-fn-istype ctx args "NUMBER"))
    ((= u "ISTEXT")       (brx-fn-istype ctx args "TEXT"))
    ((= u "ISLIST")       (brx-fn-istype ctx args "LIST"))
    ((= u "IFERROR")      (brx-fn-iferror ctx args))
    ((or (= u "FORMAT") (= u "FMT")) (brx-fn-format ctx args))
    ((or (= u "PREFIX") (= u "PFX")) (brx-fn-prefix ctx args))
    ((or (= u "SUFFIX") (= u "SFX") (= u "UNIT")) (brx-fn-suffix ctx args))
    ((= u "HIDEZERO")     (brx-fn-hidezero ctx args))
    ((= u "IFEMPTY")      (brx-fn-ifempty ctx args))
    ((or (= u "JOIN") (= u "JOINTEXT")) (brx-fn-jointext ctx args))
    ((= u "IN")           (brx-fn-in ctx args))
    ((= u "CONTAINS")     (brx-fn-contains ctx args))
    (T                     (brx-make-err "005"))
  )
)


;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================

(defun brx-listify-rv (rv /)
  (cond
    ((brx-err-p rv) rv)
    ((= (brx-rv-type rv) "LIST") rv)
    ((null (brx-rv-value rv)) (brx-make-ok "LIST" nil))
    (T (brx-make-ok "LIST" (list (brx-rv-value rv))))
  )
)

(defun brx-unique-strings (lst / seen out key)
  (setq seen nil out nil)
  (while lst
    (setq key (strcase (vl-princ-to-string (car lst)) T))
    (if (not (member key seen))
      (progn (setq seen (cons key seen)) (setq out (cons (car lst) out)))
    )
    (setq lst (cdr lst))
  )
  (reverse out)
)

(defun brx-filter-by-name (objs name / out o)
  (setq out nil)
  (while objs
    (setq o (car objs))
    (if (= (strcase (vl-princ-to-string (brx-object-name o)) T) (strcase (vl-princ-to-string name) T))
      (setq out (cons o out))
    )
    (setq objs (cdr objs))
  )
  (reverse out)
)

(defun brx-filter-by-role (objs role / out o)
  (setq out nil)
  (while objs
    (setq o (car objs))
    (if (= (strcase (vl-princ-to-string (brx-object-role o)) T) (strcase (vl-princ-to-string role) T))
      (setq out (cons o out))
    )
    (setq objs (cdr objs))
  )
  (reverse out)
)

(defun brx-attr-list (objs tag / out o v)
  (setq out nil)
  (while objs
    (setq o (car objs))
    (setq v (brx-object-get-attr o tag))
    (if v (setq out (cons v out)))
    (setq objs (cdr objs))
  )
  (reverse out)
)

(defun brx-param-list (objs pname / out o v)
  (setq out nil)
  (while objs
    (setq o (car objs))
    (setq v (brx-object-get-param o pname))
    (if v (setq out (cons v out)))
    (setq objs (cdr objs))
  )
  (reverse out)
)

(defun brx-field-list (objs fname / out o v)
  (setq out nil)
  (while objs
    (setq o (car objs))
    (setq v (brx-object-get-field o fname))
    (if v (setq out (cons v out)))
    (setq objs (cdr objs))
  )
  (reverse out)
)

(defun brx-fn-first (ctx args / vals a)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1) (brx-make-err "005")
    (progn (setq a (brx-listify-rv (car vals))) (if (brx-err-p a) a (brx-ensure-singleton (if (brx-rv-value a) (list (car (brx-rv-value a))) nil))))
  )
)

(defun brx-fn-last (ctx args / vals a lst)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1) (brx-make-err "005")
    (progn
      (setq a (brx-listify-rv (car vals)))
      (if (brx-err-p a) a
        (progn (setq lst (brx-rv-value a)) (brx-ensure-singleton (if lst (list (last lst)) nil)))
      )
    )
  )
)

(defun brx-fn-countlist (ctx args / vals a)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1) (brx-make-err "005")
    (progn (setq a (brx-listify-rv (car vals))) (if (brx-err-p a) a (brx-make-ok "NUMBER" (length (brx-rv-value a)))))
  )
)

(defun brx-fn-unique (ctx args / vals a)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1) (brx-make-err "005")
    (progn (setq a (brx-listify-rv (car vals))) (if (brx-err-p a) a (brx-make-ok "LIST" (brx-unique-strings (brx-rv-value a)))))
  )
)

(defun brx-fn-filterbyname (ctx args / vals set name)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 2)
    (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (nth 0 vals)))
      (setq name (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p set) (brx-err-p name)) (or (if (brx-err-p set) set nil) (if (brx-err-p name) name nil))
        (brx-make-ok "LIST" (brx-filter-by-name (brx-rv-value set) (brx-rv-value name)))
      )
    )
  )
)

(defun brx-fn-filterbyrole (ctx args / vals set role)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 2)
    (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (nth 0 vals)))
      (setq role (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p set) (brx-err-p role)) (or (if (brx-err-p set) set nil) (if (brx-err-p role) role nil))
        (brx-make-ok "LIST" (brx-filter-by-role (brx-rv-value set) (brx-rv-value role)))
      )
    )
  )
)

(defun brx-fn-takefirst (ctx args / vals set)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1) (brx-make-err "005")
    (progn (setq set (brx-listify-rv (car vals))) (if (brx-err-p set) set (brx-ensure-singleton (if (brx-rv-value set) (list (car (brx-rv-value set))) nil))))
  )
)

(defun brx-fn-takelast (ctx args / vals set lst)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1) (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (car vals)))
      (if (brx-err-p set) set
        (progn (setq lst (brx-rv-value set)) (brx-ensure-singleton (if lst (list (last lst)) nil)))
      )
    )
  )
)

(defun brx-fn-takeindex (ctx args / vals set idx lst)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 2)
    (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (nth 0 vals)))
      (setq idx (brx-rv-number (nth 1 vals)))
      (if (or (brx-err-p set) (brx-err-p idx)) (or (if (brx-err-p set) set nil) (if (brx-err-p idx) idx nil))
        (progn
          (setq lst (brx-rv-value set))
          (setq idx (fix (brx-rv-value idx)))
          (if (or (< idx 1) (> idx (length lst))) (brx-make-err "001") (brx-wrap-host-value (nth (1- idx) lst)))
        )
      )
    )
  )
)

(defun brx-fn-takeonly (ctx args / vals set)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1) (brx-make-err "005")
    (progn (setq set (brx-listify-rv (car vals))) (if (brx-err-p set) set (brx-ensure-singleton (brx-rv-value set))))
  )
)

(defun brx-fn-attrlist (ctx args / vals set tag)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 2)
    (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (nth 0 vals)))
      (setq tag (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p set) (brx-err-p tag)) (or (if (brx-err-p set) set nil) (if (brx-err-p tag) tag nil))
        (brx-make-ok "LIST" (brx-attr-list (brx-rv-value set) (brx-rv-value tag)))
      )
    )
  )
)

(defun brx-fn-paramlist (ctx args / vals set tag)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 2)
    (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (nth 0 vals)))
      (setq tag (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p set) (brx-err-p tag)) (or (if (brx-err-p set) set nil) (if (brx-err-p tag) tag nil))
        (brx-make-ok "LIST" (brx-param-list (brx-rv-value set) (brx-rv-value tag)))
      )
    )
  )
)

(defun brx-fn-fieldlist (ctx args / vals set tag)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 2)
    (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (nth 0 vals)))
      (setq tag (brx-rv-text (nth 1 vals)))
      (if (or (brx-err-p set) (brx-err-p tag)) (or (if (brx-err-p set) set nil) (if (brx-err-p tag) tag nil))
        (brx-make-ok "LIST" (brx-field-list (brx-rv-value set) (brx-rv-value tag)))
      )
    )
  )
)

(defun brx-fn-blocknamelist (ctx args / vals set out)
  (setq vals (brx-eval-args ctx args))
  (if (/= (length vals) 1)
    (brx-make-err "005")
    (progn
      (setq set (brx-listify-rv (car vals)))
      (if (brx-err-p set) set
        (progn
          (setq out nil)
          (foreach o (brx-rv-value set) (setq out (cons (brx-object-name o) out)))
          (brx-make-ok "LIST" (reverse out))
        )
      )
    )
  )
)

(defun brx-dispatch-fn (ctx fname args / u)
  (setq u (strcase fname T))
  (cond
    ((= u "IF")           (brx-fn-if ctx args))
    ((= u "AND")          (brx-fn-and ctx args))
    ((= u "OR")           (brx-fn-or ctx args))
    ((= u "NOT")          (brx-fn-not ctx args))
    ((= u "TRUE")         (brx-bool-rv T))
    ((= u "FALSE")        (brx-bool-rv nil))
    ((= u "ABS")          (brx-fn-abs ctx args))
    ((= u "INT")          (brx-fn-int ctx args))
    ((= u "ROUND")        (brx-fn-round ctx args))
    ((= u "ROUNDUP")      (brx-fn-roundup ctx args))
    ((= u "ROUNDDOWN")    (brx-fn-rounddown ctx args))
    ((= u "SQRT")         (brx-fn-sqrt ctx args))
    ((= u "POWER")        (brx-fn-power ctx args))
    ((= u "MOD")          (brx-fn-mod ctx args))
    ((= u "SIGN")         (brx-fn-sign ctx args))
    ((= u "MAX")          (brx-fn-minmax ctx args T))
    ((= u "MIN")          (brx-fn-minmax ctx args nil))
    ((= u "PI")           (brx-make-ok "NUMBER" pi))
    ((= u "EQ")           (brx-fn-compare ctx args "EQ"))
    ((= u "NE")           (brx-fn-compare ctx args "NE"))
    ((= u "GT")           (brx-fn-compare ctx args "GT"))
    ((= u "GE")           (brx-fn-compare ctx args "GE"))
    ((= u "LT")           (brx-fn-compare ctx args "LT"))
    ((= u "LE")           (brx-fn-compare ctx args "LE"))
    ((= u "CONTAINSTEXT") (brx-fn-contains-text ctx args))
    ((= u "STARTSWITH")   (brx-fn-startswith ctx args))
    ((= u "ENDSWITH")     (brx-fn-endswith ctx args))
    ((= u "ISBLANK")      (brx-fn-isblank ctx args))
    ((= u "ISERROR")      (brx-fn-iserror ctx args))
    ((= u "ISNUMBER")     (brx-fn-istype ctx args "NUMBER"))
    ((= u "ISTEXT")       (brx-fn-istype ctx args "TEXT"))
    ((= u "ISLIST")       (brx-fn-istype ctx args "LIST"))
    ((= u "IFERROR")      (brx-fn-iferror ctx args))
    ((or (= u "FORMAT") (= u "FMT")) (brx-fn-format ctx args))
    ((or (= u "PREFIX") (= u "PFX")) (brx-fn-prefix ctx args))
    ((or (= u "SUFFIX") (= u "SFX") (= u "UNIT")) (brx-fn-suffix ctx args))
    ((= u "HIDEZERO")     (brx-fn-hidezero ctx args))
    ((= u "IFEMPTY")      (brx-fn-ifempty ctx args))
    ((or (= u "JOIN") (= u "JOINTEXT")) (brx-fn-jointext ctx args))
    ((= u "FIRST")        (brx-fn-first ctx args))
    ((= u "LAST")         (brx-fn-last ctx args))
    ((= u "COUNTLIST")    (brx-fn-countlist ctx args))
    ((= u "UNIQUE")       (brx-fn-unique ctx args))
    ((= u "FILTERBYNAME") (brx-fn-filterbyname ctx args))
    ((= u "FILTERBYROLE") (brx-fn-filterbyrole ctx args))
    ((= u "TAKEFIRST")    (brx-fn-takefirst ctx args))
    ((= u "TAKELAST")     (brx-fn-takelast ctx args))
    ((= u "TAKEINDEX")    (brx-fn-takeindex ctx args))
    ((= u "TAKEONLY")     (brx-fn-takeonly ctx args))
    ((= u "ATTRLIST")     (brx-fn-attrlist ctx args))
    ((= u "PARAMLIST")    (brx-fn-paramlist ctx args))
    ((= u "FIELDLIST")    (brx-fn-fieldlist ctx args))
    ((= u "BLOCKNAMELIST") (brx-fn-blocknamelist ctx args))
    (T                     (brx-make-err "005"))
  )
)


;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================

(defun brx-required-keys-p (al keys / ok)
  (setq ok T)
  (while keys
    (if (null (assoc (car keys) al)) (setq ok nil))
    (setq keys (cdr keys))
  )
  ok
)

(defun brx-enum-member-p (v allowed /)
  (member (strcase (vl-princ-to-string v) T) allowed)
)

(defun brx-validate-paramn (rec / errs)
  (setq errs nil)
  (if (not (brx-required-keys-p rec '(PARAMNID PARAMNNAME PARAMNMODE PARAMNVALUETYPE)))
    (setq errs (cons "PARAMN missing required keys" errs))
  )
  (if (and (assoc 'PARAMNMODE rec)
           (not (brx-enum-member-p (cdr (assoc 'PARAMNMODE rec)) '("DIRECT" "CONST" "FORMULA" "ALIAS"))))
    (setq errs (cons "PARAMNMODE invalid" errs))
  )
  (if (and (assoc 'PARAMNVALUETYPE rec)
           (not (brx-enum-member-p (cdr (assoc 'PARAMNVALUETYPE rec)) '("NUMBER" "TEXT" "BOOL" "ANGLE" "LENGTH" "ENUM"))))
    (setq errs (cons "PARAMNVALUETYPE invalid" errs))
  )
  (if (and (= (strcase (vl-princ-to-string (cdr (assoc 'PARAMNMODE rec))) T) "FORMULA")
           (null (assoc 'PARAMNFORMULAID rec)))
    (setq errs (cons "FORMULA mode requires PARAMNFORMULAID" errs))
  )
  (reverse errs)
)

(defun brx-validate-formulan (rec / errs)
  (setq errs nil)
  (if (not (brx-required-keys-p rec '(FORMULANID FORMULANNAME FORMULANRAW FORMULANCANON FORMULANTARGETKIND)))
    (setq errs (cons "FORMULAN missing required keys" errs))
  )
  (if (and (assoc 'FORMULANMULTIPOLICY rec)
           (not (brx-enum-member-p (cdr (assoc 'FORMULANMULTIPOLICY rec)) '("ERRORIFMULTI" "TAKEONLY" "TAKEFIRST"))))
    (setq errs (cons "FORMULANMULTIPOLICY invalid" errs))
  )
  (if (and (assoc 'FORMULANRAW rec) (assoc 'FORMULANCANON rec)
           (= (vl-princ-to-string (cdr (assoc 'FORMULANCANON rec))) ""))
    (setq errs (cons "FORMULANCANON empty" errs))
  )
  (reverse errs)
)

(defun brx-validate-fieldn (rec / errs)
  (setq errs nil)
  (if (not (brx-required-keys-p rec '(FIELDID FIELDTARGETKIND FIELDVALUETYPE FIELDMODE FIELDDIRECTION)))
    (setq errs (cons "FIELDN missing required keys" errs))
  )
  (if (and (assoc 'FIELDMODE rec)
           (not (brx-enum-member-p (cdr (assoc 'FIELDMODE rec)) '("FIELDEXCEL" "FIELDNATIVE"))))
    (setq errs (cons "FIELDMODE invalid" errs))
  )
  (if (and (assoc 'FIELDDIRECTION rec)
           (not (brx-enum-member-p (cdr (assoc 'FIELDDIRECTION rec)) '("ONEWAY" "BIDIR"))))
    (setq errs (cons "FIELDDIRECTION invalid" errs))
  )
  (if (and (= (strcase (vl-princ-to-string (cdr (assoc 'FIELDDIRECTION rec))) T) "BIDIR")
           (null (assoc 'FIELDREVERSERULE rec)))
    (setq errs (cons "BIDIR requires FIELDREVERSERULE" errs))
  )
  (reverse errs)
)

(defun c:BRX-VALIDATE-SPEC-SAMPLE ( / p f fld )
  (setq p '((PARAMNID . "P1") (PARAMNNAME . "Distance1") (PARAMNMODE . "FORMULA") (PARAMNVALUETYPE . "NUMBER") (PARAMNFORMULAID . "F1")))
  (setq f '((FORMULANID . "F1") (FORMULANNAME . "Len") (FORMULANRAW . "MASTER.PARAMK1") (FORMULANCANON . "MASTER.PARAMK1") (FORMULANTARGETKIND . "MASTERPARAM") (FORMULANMULTIPOLICY . "TAKEFIRST")))
  (setq fld '((FIELDID . "FIELD1") (FIELDTARGETKIND . "ATTRIB") (FIELDVALUETYPE . "FORMULA") (FIELDMODE . "FIELDEXCEL") (FIELDDIRECTION . "BIDIR") (FIELDREVERSERULE . "TEXT")))
  (princ (strcat "\nPARAMN errors: " (vl-princ-to-string (brx-validate-paramn p))))
  (princ (strcat "\nFORMULAN errors: " (vl-princ-to-string (brx-validate-formulan f))))
  (princ (strcat "\nFIELDN errors: " (vl-princ-to-string (brx-validate-fieldn fld))))
  (princ)
)


;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================

(defun brx-formulan-deps (formRec / ast)
  (setq ast (brx-parse (cdr (assoc 'FORMULANCANON formRec))))
  (if (and (listp ast) (assoc :kind ast)) nil (brx-collect-ref-nodes ast))
)

(defun brx-paramn-deps (paramRec formulas / fid frec)
  (if (= (strcase (vl-princ-to-string (cdr (assoc 'PARAMNMODE paramRec))) T) "FORMULA")
    (progn
      (setq fid (cdr (assoc 'PARAMNFORMULAID paramRec)))
      (setq frec (cdr (assoc fid formulas)))
      (if frec (brx-formulan-deps frec) nil)
    )
    nil
  )
)

;;; END MODULE: output/BLK_REACTOR_Core_Formula_Engine_v1_0a.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Runtime_v2_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Runtime_v2_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================

(defun brx-collect-ref-nodes (ast / node out args)
  (setq out nil)
  (if ast
    (progn
      (setq node (brx-ast-node ast))
      (cond
        ((= node "REF")
          (setq out (list (brx-stack-key (cdr (assoc :scope ast)) (cdr (assoc :kind ast)) (cdr (assoc :name ast)))))
        )
        ((= node "CALL")
          (setq args (cdr (assoc :args ast)))
          (while args
            (setq out (append out (brx-collect-ref-nodes (car args))))
            (setq args (cdr args))
          )
        )
      )
    )
  )
  out
)

(defun brx-build-alias-graph (ctx / aliases out one expr ast deps)
  (setq aliases (brx-alias-table ctx))
  (setq out nil)
  (while aliases
    (setq one (car aliases))
    (setq expr (cdr one))
    (setq ast (brx-parse expr))
    (setq deps (if (and (listp ast) (assoc :kind ast)) nil (brx-collect-ref-nodes ast)))
    (setq out (cons (cons (strcat "SELF:ALIAS:" (car one)) deps) out))
    (setq aliases (cdr aliases))
  )
  (reverse out)
)

(defun brx-graph-neighbors (graph node /)
  (cdr (assoc node graph))
)

(defun brx-dfs-cycle (graph node visiting visited / nbrs hit)
  (cond
    ((member node visiting) T)
    ((member node visited) nil)
    (T
      (setq nbrs (brx-graph-neighbors graph node))
      (setq hit nil)
      (while nbrs
        (if (brx-dfs-cycle graph (car nbrs) (cons node visiting) (cons node visited))
          (progn (setq hit T) (setq nbrs nil))
          (setq nbrs (cdr nbrs))
        )
      )
      hit
    )
  )
)

(defun brx-graph-has-cycle (graph / items hit)
  (setq items graph)
  (setq hit nil)
  (while items
    (if (brx-dfs-cycle graph (caar items) nil nil)
      (progn (setq hit T) (setq items nil))
      (setq items (cdr items))
    )
  )
  hit
)

(defun c:BRX-TEST-ALIAS-GRAPH ( / ctx g )
  (setq ctx (list (cons :aliases '(("A" . "B") ("B" . "C") ("C" . "A")))))
  (setq g (brx-build-alias-graph ctx))
  (princ (strcat "\nGRAPH: " (vl-princ-to-string g)))
  (princ (strcat "\nHAS-CYCLE: " (vl-princ-to-string (brx-graph-has-cycle g))))
  (princ)
)


;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)

(defun brx-xd-master-keys ( / )
  '(ROLE GROUPID MASTERPARAM BRGROUPLOCK BRGROUPFLIP BRPRECISION GROUPVERSION GROUPSTATE COPYSTATE)
)

(defun brx-xd-slave-keys ( / )
  '(ROLE GROUPID MASTERPARAM GROUPVERSION GROUPSTATE COPYSTATE MARKERHANDLE)
)

(defun brx-xd-table-keys ( / )
  '(ROLE GROUPID TABLEHANDLE GROUPVERSION GROUPSTATE COPYSTATE MARKERHANDLE)
)

(defun brx-role-valid-p (role /)
  (member (strcase (vl-princ-to-string role) T) '("MASTER" "SLAVE" "TABLE"))
)

(defun brx-groupstate-valid-p (v /)
  (member (strcase (vl-princ-to-string v) T) '("ACTIVE" "DISABLED" "ERROR" "UNRESOLVED"))
)

(defun brx-copystate-valid-p (v /)
  (member (strcase (vl-princ-to-string v) T) '("NORMAL" "PARTIAL" "UNRESOLVED" "RELINKING"))
)

(defun brx-db-put (storeSym key value / p)
  (if (boundp storeSym)
    (progn
      (setq p (assoc key (eval storeSym)))
      (if p
        (set storeSym (subst (cons key value) p (eval storeSym)))
        (set storeSym (cons (cons key value) (eval storeSym)))
      )
      value
    )
    nil
  )
)

(defun brx-db-get (storeSym key /)
  (cdr (assoc key (eval storeSym)))
)

(defun brx-xdata-put (handle al /)
  (brx-db-put '*brx-xdata-store* (strcase (vl-princ-to-string handle) T) al)
)

(defun brx-xdata-get (handle /)
  (brx-db-get '*brx-xdata-store* (strcase (vl-princ-to-string handle) T))
)

(defun brx-xdata-prop (handle key / rec)
  (setq rec (brx-xdata-get handle))
  (if rec (cdr (assoc key rec)) nil)
)

(defun brx-xdata-prop-put (handle key value / rec p)
  (setq rec (or (brx-xdata-get handle) nil))
  (setq p (assoc key rec))
  (if p
    (setq rec (subst (cons key value) p rec))
    (setq rec (cons (cons key value) rec))
  )
  (brx-xdata-put handle rec)
)

(defun brx-make-xd-record (role groupid /)
  (list
    (cons 'ROLE (strcase role T))
    (cons 'GROUPID groupid)
    (cons 'GROUPVERSION "1.0")
    (cons 'GROUPSTATE "ACTIVE")
    (cons 'COPYSTATE "NORMAL")
  )
)

(defun brx-bind-master-xdata (handle groupid masterParam / rec)
  (setq rec (append (brx-make-xd-record "MASTER" groupid) (list (cons 'MASTERPARAM masterParam) (cons 'BRGROUPLOCK "OFF") (cons 'BRGROUPFLIP "OFF") (cons 'BRPRECISION 2))))
  (brx-xdata-put handle rec)
)

(defun brx-bind-slave-xdata (handle groupid masterParam / rec)
  (setq rec (append (brx-make-xd-record "SLAVE" groupid) (list (cons 'MASTERPARAM masterParam))))
  (brx-xdata-put handle rec)
)

(defun brx-bind-table-xdata (handle groupid tableHandle / rec)
  (setq rec (append (brx-make-xd-record "TABLE" groupid) (list (cons 'TABLEHANDLE tableHandle))))
  (brx-xdata-put handle rec)
)


;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================

(defun brx-nod-put (dict key value / bucket p)
  (setq bucket (or (brx-db-get '*brx-nod-store* dict) nil))
  (setq p (assoc key bucket))
  (if p
    (setq bucket (subst (cons key value) p bucket))
    (setq bucket (cons (cons key value) bucket))
  )
  (brx-db-put '*brx-nod-store* dict bucket)
)

(defun brx-nod-get (dict key / bucket)
  (setq bucket (or (brx-db-get '*brx-nod-store* dict) nil))
  (cdr (assoc key bucket))
)

(defun brx-grouprec-make (groupid master members blocknames /)
  (list
    (cons 'GROUPID groupid)
    (cons 'MASTER master)
    (cons 'MEMBERS members)
    (cons 'BLOCKNAMES blocknames)
    (cons 'BRVERSION "1.0")
    (cons 'MAXITER 3)
    (cons 'GROUPSTATE "ACTIVE")
    (cons 'COPYSTATE "NORMAL")
    (cons 'HASTABLES (if (member "TABLE" (mapcar '(lambda (x) (strcase (vl-princ-to-string (brx-xdata-prop x 'ROLE)) T)) members)) 1 0))
    (cons 'LASTVALIDATION "")
  )
)

(defun brx-grouprec-put (rec / gid)
  (setq gid (cdr (assoc 'GROUPID rec)))
  (brx-nod-put 'BRGROUPS gid rec)
)

(defun brx-grouprec-get (groupid /)
  (brx-nod-get 'BRGROUPS groupid)
)

(defun brx-grouprec-valid-errors (rec / errs members)
  (setq errs nil)
  (if (not (brx-required-keys-p rec '(GROUPID MASTER MEMBERS BLOCKNAMES BRVERSION MAXITER GROUPSTATE COPYSTATE HASTABLES LASTVALIDATION)))
    (setq errs (cons "BRGROUPS record missing required keys" errs))
  )
  (if (and (assoc 'GROUPSTATE rec) (not (brx-groupstate-valid-p (cdr (assoc 'GROUPSTATE rec)))))
    (setq errs (cons "GROUPSTATE invalid" errs))
  )
  (if (and (assoc 'COPYSTATE rec) (not (brx-copystate-valid-p (cdr (assoc 'COPYSTATE rec)))))
    (setq errs (cons "COPYSTATE invalid" errs))
  )
  (setq members (cdr (assoc 'MEMBERS rec)))
  (if (or (null members) (not (listp members)))
    (setq errs (cons "MEMBERS must be list" errs))
  )
  (reverse errs)
)

(defun brx-grouprec-touch-validation (groupid stamp / rec)
  (setq rec (brx-grouprec-get groupid))
  (if rec
    (progn
      (setq rec (subst (cons 'LASTVALIDATION stamp) (assoc 'LASTVALIDATION rec) rec))
      (brx-grouprec-put rec)
    )
  )
)


;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================

(defun brx-code-installstate-valid-p (v /)
  (member (strcase (vl-princ-to-string v) T) '("EMBEDDEDONLY" "INSTALLED" "OUTDATED" "ERROR"))
)

(defun brx-code-loaderstate-valid-p (v /)
  (member (strcase (vl-princ-to-string v) T) '("AVAILABLE" "MISSING" "BLOCKEDBYSECURITY" "ERROR"))
)

(defun brx-code-rec-make (version hash parts /)
  (list
    (cons 'BRCODEINFO "BLKREACTOR.lsp")
    (cons 'BRCODEVERSION version)
    (cons 'BRCODEHASH hash)
    (cons 'BRCODEPARTCOUNT (length parts))
    (cons 'BRCODEBUILDDATE "")
    (cons 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
    (cons 'BRCODELOADERSTATE "AVAILABLE")
    (cons 'BRCODEPARTS parts)
  )
)

(defun brx-code-rec-put (rec /)
  (brx-nod-put 'BRCODE 'INFO rec)
)

(defun brx-code-rec-get ( /)
  (brx-nod-get 'BRCODE 'INFO)
)

(defun brx-code-rec-errors (rec / errs)
  (setq errs nil)
  (if (not (brx-required-keys-p rec '(BRCODEINFO BRCODEVERSION BRCODEHASH BRCODEPARTCOUNT BRCODEBUILDDATE BRCODEINSTALLSTATE BRCODELOADERSTATE BRCODEPARTS)))
    (setq errs (cons "BRCODE missing required keys" errs))
  )
  (if (and (assoc 'BRCODEINSTALLSTATE rec) (not (brx-code-installstate-valid-p (cdr (assoc 'BRCODEINSTALLSTATE rec)))))
    (setq errs (cons "BRCODEINSTALLSTATE invalid" errs))
  )
  (if (and (assoc 'BRCODELOADERSTATE rec) (not (brx-code-loaderstate-valid-p (cdr (assoc 'BRCODELOADERSTATE rec)))))
    (setq errs (cons "BRCODELOADERSTATE invalid" errs))
  )
  (reverse errs)
)

(defun brx-force-install-stub ( / rec)
  (setq rec (or (brx-code-rec-get) (brx-code-rec-make "0.0" "UNKNOWN" nil)))
  (setq rec (subst (cons 'BRCODEINSTALLSTATE "INSTALLED") (assoc 'BRCODEINSTALLSTATE rec) rec))
  (setq rec (subst (cons 'BRCODELOADERSTATE "AVAILABLE") (assoc 'BRCODELOADERSTATE rec) rec))
  (brx-code-rec-put rec)
)


;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================

(defun brx-cache-put (groupid value /)
  (brx-db-put '*brx-runtime-cache* groupid value)
)

(defun brx-cache-get (groupid /)
  (brx-db-get '*brx-runtime-cache* groupid)
)

(defun brx-object-from-xdata (handle / xd)
  (setq xd (brx-xdata-get handle))
  (if xd
    (list
      (cons :handle handle)
      (cons :role (cdr (assoc 'ROLE xd)))
      (cons :name (or (cdr (assoc 'BLOCKNAME xd)) ""))
      (cons :attrs (or (cdr (assoc 'ATTRS xd)) nil))
      (cons :params (or (cdr (assoc 'PARAMS xd)) nil))
      (cons :fields (or (cdr (assoc 'FIELDS xd)) nil))
      (cons :raw xd)
    )
    nil
  )
)

(defun brx-build-group-cache (groupid / grec members objs master h o)
  (setq grec (brx-grouprec-get groupid))
  (if grec
    (progn
      (setq members (cdr (assoc 'MEMBERS grec)))
      (setq objs nil)
      (while members
        (setq h (car members))
        (setq o (brx-object-from-xdata h))
        (if o (setq objs (cons o objs)))
        (setq members (cdr members))
      )
      (setq objs (reverse objs))
      (setq master (brx-object-from-xdata (cdr (assoc 'MASTER grec))))
      (brx-cache-put groupid (list (cons :group grec) (cons :objects objs) (cons :master master)))
    )
  )
)

(defun brx-bootstrap-all-groups ( / bucket)
  (setq bucket (or (brx-db-get '*brx-nod-store* 'BRGROUPS) nil))
  (while bucket
    (brx-build-group-cache (caar bucket))
    (setq bucket (cdr bucket))
  )
)


;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================

(defun brx-remap-pair (old new /)
  (cons (strcase (vl-princ-to-string old) T) (strcase (vl-princ-to-string new) T))
)

(defun brx-remap-resolve (mapping old /)
  (cdr (assoc (strcase (vl-princ-to-string old) T) mapping))
)

(defun brx-mark-copy-unresolved (handle / xd)
  (setq xd (or (brx-xdata-get handle) nil))
  (if xd
    (progn
      (setq xd (subst (cons 'COPYSTATE "UNRESOLVED") (assoc 'COPYSTATE xd) xd))
      (brx-xdata-put handle xd)
    )
  )
)

(defun brx-remap-group-record (groupid mapping / rec members out one nm)
  (setq rec (brx-grouprec-get groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (setq out nil)
      (while members
        (setq one (car members))
        (setq nm (or (brx-remap-resolve mapping one) one))
        (setq out (cons nm out))
        (setq members (cdr members))
      )
      (setq rec (subst (cons 'MASTER (or (brx-remap-resolve mapping (cdr (assoc 'MASTER rec))) (cdr (assoc 'MASTER rec)))) (assoc 'MASTER rec) rec))
      (setq rec (subst (cons 'MEMBERS (reverse out)) (assoc 'MEMBERS rec) rec))
      (setq rec (subst (cons 'COPYSTATE "RELINKING") (assoc 'COPYSTATE rec) rec))
      (brx-grouprec-put rec)
      rec
    )
  )
)

(defun brx-owner-aware-remap-stub (groupid mapping / rec)
  (setq rec (brx-remap-group-record groupid mapping))
  (if rec
    (progn
      (foreach h (cdr (assoc 'MEMBERS rec))
        (brx-xdata-prop-put h 'GROUPID (cdr (assoc 'GROUPID rec)))
        (brx-xdata-prop-put h 'COPYSTATE "RELINKING")
      )
      rec
    )
    nil
  )
)


;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================

(defun brx-master-of-group-errors (groupid / rec master xd errs)
  (setq errs nil)
  (setq rec (brx-grouprec-get groupid))
  (if (null rec)
    (setq errs (cons "BRGROUPS record missing" errs))
    (progn
      (setq master (cdr (assoc 'MASTER rec)))
      (setq xd (brx-xdata-get master))
      (if (null xd) (setq errs (cons "Master xData missing" errs)))
      (if (and xd (/= (strcase (vl-princ-to-string (cdr (assoc 'ROLE xd))) T) "MASTER"))
        (setq errs (cons "Master ROLE mismatch" errs))
      )
      (if (and xd (/= (vl-princ-to-string (cdr (assoc 'GROUPID xd))) (vl-princ-to-string groupid)))
        (setq errs (cons "Master GROUPID mismatch" errs))
      )
    )
  )
  (reverse errs)
)

(defun brx-member-errors (groupid handle / xd errs)
  (setq errs nil)
  (setq xd (brx-xdata-get handle))
  (if (null xd)
    (setq errs (cons (strcat "Member xData missing: " (vl-princ-to-string handle)) errs))
    (progn
      (if (not (brx-role-valid-p (cdr (assoc 'ROLE xd))))
        (setq errs (cons (strcat "Member ROLE invalid: " (vl-princ-to-string handle)) errs))
      )
      (if (/= (vl-princ-to-string (cdr (assoc 'GROUPID xd))) (vl-princ-to-string groupid))
        (setq errs (cons (strcat "Member GROUPID mismatch: " (vl-princ-to-string handle)) errs))
      )
      (if (not (brx-groupstate-valid-p (cdr (assoc 'GROUPSTATE xd))))
        (setq errs (cons (strcat "Member GROUPSTATE invalid: " (vl-princ-to-string handle)) errs))
      )
      (if (not (brx-copystate-valid-p (cdr (assoc 'COPYSTATE xd))))
        (setq errs (cons (strcat "Member COPYSTATE invalid: " (vl-princ-to-string handle)) errs))
      )
    )
  )
  (reverse errs)
)

(defun brx-validate-group (groupid / rec errs members one)
  (setq errs nil)
  (setq rec (brx-grouprec-get groupid))
  (if rec
    (setq errs (append errs (brx-grouprec-valid-errors rec)))
    (setq errs (cons "Group record missing" errs))
  )
  (setq errs (append errs (brx-master-of-group-errors groupid)))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (while members
        (setq one (car members))
        (setq errs (append errs (brx-member-errors groupid one)))
        (setq members (cdr members))
      )
    )
  )
  errs
)

(defun brx-validate-all-groups ( / bucket out gid errs)
  (setq bucket (or (brx-db-get '*brx-nod-store* 'BRGROUPS) nil))
  (setq out nil)
  (while bucket
    (setq gid (caar bucket))
    (setq errs (brx-validate-group gid))
    (setq out (cons (cons gid errs) out))
    (setq bucket (cdr bucket))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================

(defun brx-field-mode-valid-p (v /)
  (member (strcase (vl-princ-to-string v) T) '("FIELDEXCEL" "FIELDNATIVE"))
)

(defun brx-field-state-make (fieldid mode value text /)
  (list
    (cons 'FIELDID fieldid)
    (cons 'FIELDMODE mode)
    (cons 'FIELDLASTVALUE value)
    (cons 'FIELDLASTTEXT text)
    (cons 'FIELDSTATE "ACTIVE")
    (cons 'ERROR "")
  )
)

(defun brx-object-fieldstates (handle / xd)
  (setq xd (or (brx-xdata-get handle) nil))
  (or (cdr (assoc 'FIELDSTATES xd)) nil)
)

(defun brx-object-fieldstate-put (handle fieldid state / xd lst p)
  (setq xd (or (brx-xdata-get handle) nil))
  (setq lst (or (cdr (assoc 'FIELDSTATES xd)) nil))
  (setq p (assoc fieldid lst))
  (if p
    (setq lst (subst (cons fieldid state) p lst))
    (setq lst (cons (cons fieldid state) lst))
  )
  (if (assoc 'FIELDSTATES xd)
    (setq xd (subst (cons 'FIELDSTATES lst) (assoc 'FIELDSTATES xd) xd))
    (setq xd (cons (cons 'FIELDSTATES lst) xd))
  )
  (brx-xdata-put handle xd)
)

(defun brx-field-bridge-pull-stub (handle fieldid / st)
  (setq st (brx-field-state-make fieldid "FIELDEXCEL" nil ""))
  (brx-object-fieldstate-put handle fieldid st)
  st
)

(defun brx-field-bridge-push-stub (handle fieldid newText / st)
  (setq st (brx-field-state-make fieldid "FIELDNATIVE" nil newText))
  (setq st (subst (cons 'FIELDLASTTEXT newText) (assoc 'FIELDLASTTEXT st) st))
  (brx-object-fieldstate-put handle fieldid st)
  st
)


;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================

(defun brx-lockset-rec-make (locksetid groupid anchor members /)
  (list
    (cons 'LOCKSETID locksetid)
    (cons 'GROUPID groupid)
    (cons 'ANCHOR anchor)
    (cons 'MEMBERS members)
    (cons 'LOCKSTATE "ACTIVE")
  )
)

(defun brx-lockset-put (rec /)
  (brx-nod-put 'BRLOCKSETS (cdr (assoc 'LOCKSETID rec)) rec)
)

(defun brx-lockset-get (locksetid /)
  (brx-nod-get 'BRLOCKSETS locksetid)
)

(defun brx-group-lock-set (masterHandle onoff / xd)
  (setq xd (or (brx-xdata-get masterHandle) nil))
  (if xd
    (progn
      (setq xd (subst (cons 'BRGROUPLOCK (strcase onoff T)) (assoc 'BRGROUPLOCK xd) xd))
      (brx-xdata-put masterHandle xd)
      xd
    )
  )
)

(defun brx-create-lockset-stub (locksetid groupid anchor members / rec)
  (setq rec (brx-lockset-rec-make locksetid groupid anchor members))
  (brx-lockset-put rec)
  (foreach h members
    (brx-xdata-prop-put h 'LOCALLOCKSETID locksetid)
    (brx-xdata-prop-put h 'LOCALLOCKANCHOR anchor)
  )
  rec
)

(defun brx-break-lockset-stub (locksetid / rec members)
  (setq rec (brx-lockset-get locksetid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (foreach h members
        (brx-xdata-prop-put h 'LOCALLOCKSETID nil)
        (brx-xdata-prop-put h 'LOCALLOCKANCHOR nil)
      )
      (setq rec (subst (cons 'LOCKSTATE "DISBANDED") (assoc 'LOCKSTATE rec) rec))
      (brx-lockset-put rec)
    )
  )
)


;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================

(defun brx-mark-group-state (groupid gstate cstate / rec)
  (setq rec (brx-grouprec-get groupid))
  (if rec
    (progn
      (setq rec (subst (cons 'GROUPSTATE gstate) (assoc 'GROUPSTATE rec) rec))
      (setq rec (subst (cons 'COPYSTATE cstate) (assoc 'COPYSTATE rec) rec))
      (brx-grouprec-put rec)
    )
  )
)

(defun brx-relink-member-masterparam (groupid / rec master members)
  (setq rec (brx-grouprec-get groupid))
  (if rec
    (progn
      (setq master (cdr (assoc 'MASTER rec)))
      (setq members (cdr (assoc 'MEMBERS rec)))
      (foreach h members
        (if (/= (strcase (vl-princ-to-string h) T) (strcase (vl-princ-to-string master) T))
          (brx-xdata-prop-put h 'MASTERPARAM master)
        )
      )
    )
  )
)

(defun brx-rebuild-group-from-members (groupid / rec members bnames out h xd)
  (setq rec (brx-grouprec-get groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (setq bnames nil)
      (while members
        (setq h (car members))
        (setq xd (brx-xdata-get h))
        (if xd (setq bnames (cons (or (cdr (assoc 'BLOCKNAME xd)) "") bnames)))
        (setq members (cdr members))
      )
      (setq rec (subst (cons 'BLOCKNAMES (reverse bnames)) (assoc 'BLOCKNAMES rec) rec))
      (brx-grouprec-put rec)
      rec
    )
  )
)

(defun brx-relink-group-stub (groupid / errs)
  (brx-relink-member-masterparam groupid)
  (brx-rebuild-group-from-members groupid)
  (setq errs (brx-validate-group groupid))
  (if errs
    (brx-mark-group-state groupid "ERROR" "PARTIAL")
    (brx-mark-group-state groupid "ACTIVE" "NORMAL")
  )
  errs
)


;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================

(defun brx-show-info-stub (groupid / rec cache)
  (setq rec (brx-grouprec-get groupid))
  (setq cache (brx-cache-get groupid))
  (list
    (cons 'GROUPREC rec)
    (cons 'CACHE cache)
    (cons 'VALIDATION (if rec (brx-validate-group groupid) (list "Group missing")))
  )
)

(defun c:BR-SHOW-INFO-STUB ( / gid out )
  (setq gid (getstring T "\nGROUPID: "))
  (setq out (brx-show-info-stub gid))
  (princ (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

(defun c:BR-VALIDATE-STUB ( / report )
  (setq report (brx-validate-all-groups))
  (princ (strcat "\nVALIDATION: " (vl-princ-to-string report)))
  (princ)
)

(defun c:BR-FORCE-INSTALL-STUB ( / )
  (brx-force-install-stub)
  (princ "\nBRCODE marked as INSTALLED / AVAILABLE")
  (princ)
)

(defun c:BRX-RUNTIME-DEMO ( / gid )
  (setq gid "GRP-DEMO")
  (brx-bind-master-xdata "2A4F" gid "2A4F")
  (brx-xdata-prop-put "2A4F" 'BLOCKNAME "PIPE")
  (brx-xdata-prop-put "2A4F" 'PARAMS '(("DISTANCE1" . 1200.0)))
  (brx-bind-slave-xdata "3B12" gid "2A4F")
  (brx-xdata-prop-put "3B12" 'BLOCKNAME "VALVE")
  (brx-bind-table-xdata "4C89" gid "4C89")
  (brx-xdata-prop-put "4C89" 'BLOCKNAME "TABLE")
  (brx-grouprec-put (brx-grouprec-make gid "2A4F" '("2A4F" "3B12" "4C89") '("PIPE" "VALVE" "TABLE")))
  (brx-code-rec-put (brx-code-rec-make "2.0" "HASH-DEMO" '("part1" "part2")))
  (brx-bootstrap-all-groups)
  (princ (strcat "\nINFO: " (vl-princ-to-string (brx-show-info-stub gid))))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_Runtime_v2_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Backend_v3_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Backend_v3_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================

(defun brx-acad-appid (/) "BLKREACTOR")

(defun brx-safe-ename (e /)
  (cond
    ((= (type e) 'ENAME) e)
    ((and (= (type e) 'STR) (handent e)) (handent e))
    (T nil)
  )
)

(defun brx-ensure-regapp (/)
  (if (not (tblsearch "APPID" (brx-acad-appid)))
    (regapp (brx-acad-appid))
  )
  (brx-acad-appid)
)

(defun brx-entget-all (e / en)
  (setq en (brx-safe-ename e))
  (if en (entget en '("*")) nil)
)

(defun brx-entget-xd (e / en data app hit out)
  (setq en (brx-safe-ename e))
  (setq app (brx-acad-appid))
  (if en
    (progn
      (setq data (entget en (list app)))
      (setq hit nil out nil)
      (while data
        (cond
          ((and (= (caar data) 1001) (= (cdar data) app)) (setq hit T))
          ((and hit (= (caar data) 1001)) (setq data nil))
          (hit (setq out (cons (car data) out)))
        )
        (if data (setq data (cdr data)))
      )
      (reverse out)
    )
    nil
  )
)

(defun brx-entmod-safe (alist / ok)
  (setq ok (vl-catch-all-apply 'entmod (list alist)))
  (if (vl-catch-all-error-p ok) nil ok)
)

(defun brx-entupd-safe (e / en)
  (setq en (brx-safe-ename e))
  (if en (vl-catch-all-apply 'entupd (list en)))
)


;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================

(defun brx->s (v /)
  (cond
    ((null v) "")
    ((= (type v) 'STR) v)
    ((= (type v) 'INT) (itoa v))
    ((= (type v) 'REAL) (vl-princ-to-string v))
    (T (vl-princ-to-string v))
  )
)

(defun brx-join-comma (lst /)
  (if lst (brx-join (mapcar 'brx->s lst) ",") "")
)

(defun brx-split-comma (s / p out work)
  (setq out nil work s)
  (while (and work (/= work "") (setq p (vl-string-search "," work)))
    (setq out (cons (substr work 1 p) out))
    (setq work (substr work (+ p 2)))
  )
  (if work (setq out (cons work out)))
  (reverse (vl-remove "" out))
)

(defun brx-xd-pairs->typed (pairs / out k v)
  (setq out (list (cons 1001 (brx-acad-appid))))
  (while pairs
    (setq k (car pairs) v (cdr pairs))
    (setq out (append out (list (cons 1000 (strcat (brx->s k) "=" (brx->s v))))))
    (setq pairs (cddr pairs))
  )
  out
)

(defun brx-xd-typed->alist (typed / out s p k v)
  (setq out nil)
  (while typed
    (if (= (caar typed) 1000)
      (progn
        (setq s (cdar typed))
        (setq p (vl-string-search "=" s))
        (if p
          (progn
            (setq k (read (substr s 1 p)))
            (setq v (substr s (+ p 2)))
            (setq out (cons (cons k v) out))
          )
        )
      )
    )
    (setq typed (cdr typed))
  )
  (reverse out)
)

(defun brx-xd-set-alist (e al / en ed cleaned typed)
  (setq en (brx-safe-ename e))
  (if en
    (progn
      (brx-ensure-regapp)
      (setq ed (entget en '("*")))
      (setq cleaned (vl-remove-if '(lambda (x) (and (= (car x) 1001) (= (cdr x) (brx-acad-appid)))) ed))
      (setq typed (brx-xd-pairs->typed (apply 'append (mapcar '(lambda (p) (list (car p) (cdr p))) al))))
      (brx-entmod-safe (append cleaned typed))
      (brx-entupd-safe en)
      T
    )
    nil
  )
)

(defun brx-xd-get-alist (e /)
  (brx-xd-typed->alist (brx-entget-xd e))
)


;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================

(defun brx-nod-root (/)
  (namedobjdict)
)

(defun brx-dict-ensure (name / nod found en)
  (setq nod (brx-nod-root))
  (setq found (dictsearch nod name))
  (if found
    (cdr (assoc -1 found))
    (dictadd nod name (entmakex '((0 . "DICTIONARY") (100 . "AcDbDictionary"))))
  )
)

(defun brx-xrec-make (pairs / data)
  (setq data '((0 . "XRECORD") (100 . "AcDbXrecord") (280 . 1)))
  (while pairs
    (setq data (append data (list (cons 1000 (strcat (brx->s (caar pairs)) "=" (brx->s (cdar pairs)))))))
    (setq pairs (cdr pairs))
  )
  (entmakex data)
)

(defun brx-xrec-read (ename / ed out s p)
  (setq ed (entget ename))
  (setq out nil)
  (while ed
    (if (= (caar ed) 1000)
      (progn
        (setq s (cdar ed))
        (setq p (vl-string-search "=" s))
        (if p (setq out (cons (cons (read (substr s 1 p)) (substr s (+ p 2))) out)))
      )
    )
    (setq ed (cdr ed))
  )
  (reverse out)
)

(defun brx-dict-put-rec (dictName key al / dict found old xr)
  (setq dict (brx-dict-ensure dictName))
  (setq found (dictsearch dict key))
  (if found (entdel (cdr (assoc -1 found))))
  (setq xr (brx-xrec-make al))
  (dictadd dict key xr)
  xr
)

(defun brx-dict-get-rec (dictName key / dict found)
  (setq dict (brx-dict-ensure dictName))
  (setq found (dictsearch dict key))
  (if found (brx-xrec-read (cdr (assoc -1 found))) nil)
)


;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================

(defun brx-grouprec-put-real (rec / gid)
  (setq gid (cdr (assoc 'GROUPID rec)))
  (brx-dict-put-rec "BRGROUPS" gid rec)
  (brx-nod-put 'BRGROUPS gid rec)
)

(defun brx-grouprec-get-real (groupid / rec)
  (setq rec (brx-dict-get-rec "BRGROUPS" groupid))
  (if rec rec (brx-grouprec-get groupid))
)

(defun brx-code-rec-put-real (rec /)
  (brx-dict-put-rec "BRCODE" "INFO" rec)
  (brx-code-rec-put rec)
)

(defun brx-code-rec-get-real ( / rec)
  (setq rec (brx-dict-get-rec "BRCODE" "INFO"))
  (if rec rec (brx-code-rec-get))
)

(defun brx-lockset-put-real (rec / id)
  (setq id (cdr (assoc 'LOCKSETID rec)))
  (brx-dict-put-rec "BRLOCKSETS" id rec)
  (brx-lockset-put rec)
)

(defun brx-lockset-get-real (locksetid / rec)
  (setq rec (brx-dict-get-rec "BRLOCKSETS" locksetid))
  (if rec rec (brx-lockset-get locksetid))
)


;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================

(defun brx-handle-of (e / en ed)
  (setq en (brx-safe-ename e))
  (if en (cdr (assoc 5 (entget en))) nil)
)

(defun brx-blockref-p (e / en ed)
  (setq en (brx-safe-ename e))
  (if en (= (cdr (assoc 0 (entget en))) "INSERT") nil)
)

(defun brx-pick-blockref (msg / sel en)
  (setq sel (entsel msg))
  (if sel
    (progn
      (setq en (car sel))
      (if (brx-blockref-p en) en nil)
    )
    nil
  )
)

(defun brx-pick-many-blockrefs (msg / ss i out e)
  (prompt msg)
  (setq ss (ssget '((0 . "INSERT"))))
  (setq i 0 out nil)
  (if ss
    (repeat (sslength ss)
      (setq e (ssname ss i))
      (setq out (cons e out))
      (setq i (1+ i))
    )
  )
  (reverse out)
)

(defun brx-unique-handles (enames / out h)
  (setq out nil)
  (foreach e enames
    (setq h (brx-handle-of e))
    (if (and h (not (member h out))) (setq out (cons h out)))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================

(defun brx-new-groupid (/)
  (strcat "GRP-" (menucmd "m=$(edtime,$(getvar,date),YYYYMMDDHHMMSS)"))
)

(defun brx-blockname-of (e / en ed)
  (setq en (brx-safe-ename e))
  (if en (cdr (assoc 2 (entget en))) nil)
)

(defun brx-create-group-from-entities (master slaves / gid mh sh all handles names)
  (setq gid (brx-new-groupid))
  (setq mh (brx-handle-of master))
  (setq sh (mapcar 'brx-handle-of slaves))
  (setq all (cons mh sh))
  (setq handles (brx-unique-strings all))
  (setq names (mapcar 'brx-blockname-of (cons master slaves)))
  (brx-bind-master-xdata mh gid mh)
  (foreach h sh (brx-bind-slave-xdata h gid mh))
  (brx-grouprec-put-real (brx-grouprec-make gid mh handles names))
  gid
)

(defun c:BR-NEW-GROUP-WORK ( / m slaves gid)
  (setq m (brx-pick-blockref "\nPick master block: "))
  (if m
    (progn
      (setq slaves (vl-remove m (brx-pick-many-blockrefs "\nSelect slave blocks: ")))
      (setq gid (brx-create-group-from-entities m slaves))
      (prompt (strcat "\nCreated group: " gid))
    )
  )
  (princ)
)

(defun c:BR-ADD-SLAVE-WORK ( / s gid mh)
  (setq s (brx-pick-blockref "\nPick slave block: "))
  (if s
    (progn
      (setq gid (getstring T "\nTarget GROUPID: "))
      (setq mh (cdr (assoc 'MASTER (brx-grouprec-get-real gid))))
      (if mh
        (progn
          (brx-bind-slave-xdata (brx-handle-of s) gid mh)
          (prompt "\nSlave linked.")
        )
      )
    )
  )
  (princ)
)

(defun c:BR-SET-MASTER-WORK ( / m gid rec members)
  (setq m (brx-pick-blockref "\nPick new master block: "))
  (if m
    (progn
      (setq gid (getstring T "\nTarget GROUPID: "))
      (setq rec (brx-grouprec-get-real gid))
      (if rec
        (progn
          (setq rec (subst (cons 'MASTER (brx-handle-of m)) (assoc 'MASTER rec) rec))
          (brx-grouprec-put-real rec)
          (brx-bind-master-xdata (brx-handle-of m) gid (brx-handle-of m))
          (brx-relink-member-masterparam gid)
        )
      )
    )
  )
  (princ)
)


;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)

(defun brx-dcmap-put (oldH newH /)
  (setq *brx-deepclone-map* (cons (cons (strcase oldH T) (strcase newH T)) *brx-deepclone-map*))
)

(defun brx-dcmap-get (oldH /)
  (cdr (assoc (strcase oldH T) *brx-deepclone-map*))
)

(defun brx-capture-copy-pair (oldE newE /)
  (if (and oldE newE)
    (brx-dcmap-put (brx-handle-of oldE) (brx-handle-of newE))
  )
)

(defun brx-mark-group-unresolved-copy (groupid / rec members)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq rec (subst (cons 'GROUPSTATE "UNRESOLVED") (assoc 'GROUPSTATE rec) rec))
      (setq rec (subst (cons 'COPYSTATE "UNRESOLVED") (assoc 'COPYSTATE rec) rec))
      (brx-grouprec-put-real rec)
      (setq members (cdr (assoc 'MEMBERS rec)))
      (foreach h members
        (brx-xdata-prop-put h 'GROUPSTATE "UNRESOLVED")
        (brx-xdata-prop-put h 'COPYSTATE "UNRESOLVED")
      )
    )
  )
)

(defun brx-apply-deepclone-remap (groupid / rec pairs)
  (setq pairs *brx-deepclone-map*)
  (if pairs (brx-owner-aware-remap-stub groupid pairs))
)


;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)

(defun brx-reactor-clear (/)
  (foreach r *brx-reactors* (if r (vlr-remove r)))
  (setq *brx-reactors* nil)
)

(defun brx-on-object-modified (reactor params /)
  (setq params params)
)

(defun brx-on-object-copied (reactor params /)
  (setq params params)
)

(defun brx-on-command-ended (reactor params / cmd)
  (setq cmd (strcase (car params) T))
  (if (member cmd '("COPY" "PASTECLIP" "PASTEBLOCK" "MIRROR" "ARRAY" "ARRAYPATH" "ARRAYPOLAR"))
    (setq *brx-deepclone-map* *brx-deepclone-map*)
  )
)

(defun brx-install-reactors-stub (/ r1)
  (brx-reactor-clear)
  (setq r1 (vlr-command-reactor nil '((:vlr-commandEnded . brx-on-command-ended))))
  (setq *brx-reactors* (list r1))
  *brx-reactors*
)


;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================

(defun brx-member-exists-p (h /)
  (if (handent h) T nil)
)

(defun brx-validate-group-real (groupid / rec errs members h)
  (setq rec (brx-grouprec-get-real groupid))
  (setq errs (brx-validate-group groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (while members
        (setq h (car members))
        (if (not (brx-member-exists-p h))
          (setq errs (cons (strcat "Missing handle in DWG: " h) errs))
        )
        (setq members (cdr members))
      )
      (if (and (brx-member-exists-p (cdr (assoc 'MASTER rec)))
               (/= (brx-xdata-prop (cdr (assoc 'MASTER rec)) 'ROLE) "MASTER"))
        (setq errs (cons "Real master xData ROLE mismatch" errs))
      )
    )
  )
  (reverse errs)
)

(defun c:BR-VALIDATE-REAL ( / d out gid)
  (setq d (dictsearch (brx-dict-ensure "BRGROUPS") ""))
  (setq out (brx-validate-all-groups))
  (princ (strcat "\nVALIDATION-REAL: " (vl-princ-to-string out)))
  (princ)
)


;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================

(defun c:BRX-BACKEND-DEMO ( / gid m s1 s2 )
  (prompt "\nBackend demo expects existing INSERT entities selected by user.")
  (setq m (brx-pick-blockref "\nPick master: "))
  (if m
    (progn
      (setq s1 (brx-pick-blockref "\nPick slave #1: "))
      (setq s2 (brx-pick-blockref "\nPick slave #2: "))
      (setq gid (brx-create-group-from-entities m (vl-remove nil (list s1 s2))))
      (prompt (strcat "\nGROUPID=" gid))
      (prompt (strcat "\nGROUPREC=" (vl-princ-to-string (brx-grouprec-get-real gid))))
      (prompt (strcat "\nXDATA MASTER=" (vl-princ-to-string (brx-xd-get-alist m))))
      (prompt (strcat "\nVALIDATE=" (vl-princ-to-string (brx-validate-group-real gid))))
    )
  )
  (princ)
)

(defun c:BRX-INSTALL-BACKEND-STUBS ( / )
  (brx-ensure-regapp)
  (brx-dict-ensure "BRGROUPS")
  (brx-dict-ensure "BRCODE")
  (brx-dict-ensure "BRLOCKSETS")
  (brx-install-reactors-stub)
  (prompt "\nBackend stubs installed.")
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_Backend_v3_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Commands_v4_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Commands_v4_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================

(defun brx-list-remove-str (lst val / out)
  (setq out nil)
  (while lst
    (if (/= (strcase (vl-princ-to-string (car lst)) T) (strcase (vl-princ-to-string val) T))
      (setq out (cons (car lst) out))
    )
    (setq lst (cdr lst))
  )
  (reverse out)
)

(defun brx-grouprec-members-add (groupid handle / rec members)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (if (not (member handle members))
        (setq members (append members (list handle)))
      )
      (setq rec (subst (cons 'MEMBERS members) (assoc 'MEMBERS rec) rec))
      (brx-grouprec-put-real rec)
      rec
    )
  )
)

(defun brx-grouprec-members-remove (groupid handle / rec members)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq members (brx-list-remove-str (cdr (assoc 'MEMBERS rec)) handle))
      (setq rec (subst (cons 'MEMBERS members) (assoc 'MEMBERS rec) rec))
      (brx-grouprec-put-real rec)
      rec
    )
  )
)

(defun brx-grouprec-blocknames-refresh (groupid / rec members names h)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (setq names nil)
      (foreach h members
        (setq names (cons (or (cdr (assoc 'BLOCKNAME (brx-xd-get-alist h))) (brx-blockname-of h) "") names))
      )
      (setq rec (subst (cons 'BLOCKNAMES (reverse names)) (assoc 'BLOCKNAMES rec) rec))
      (setq rec (subst (cons 'HASTABLES (if (member "TABLE" (mapcar 'strcase (reverse names))) 1 0)) (assoc 'HASTABLES rec) rec))
      (brx-grouprec-put-real rec)
      rec
    )
  )
)


;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================

(defun brx-bind-entity-role (e role groupid masterHandle / h bn al)
  (setq h (brx-handle-of e))
  (setq bn (brx-blockname-of e))
  (cond
    ((= (strcase role T) "MASTER") (setq al (brx-make-xd-record "MASTER" groupid)))
    ((= (strcase role T) "SLAVE")  (setq al (brx-make-xd-record "SLAVE" groupid)))
    ((= (strcase role T) "TABLE")  (setq al (brx-make-xd-record "TABLE" groupid)))
    (T (setq al (brx-make-xd-record role groupid)))
  )
  (setq al (append al (list (cons 'MASTERPARAM masterHandle) (cons 'BLOCKNAME bn))))
  (brx-xd-set-alist e al)
  (brx-xdata-put h al)
  h
)

(defun brx-rebind-master-handle (groupid masterHandle / rec members h)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (foreach h members
        (if (/= (strcase (vl-princ-to-string h) T) (strcase (vl-princ-to-string masterHandle) T))
          (brx-xdata-prop-put h 'MASTERPARAM masterHandle)
        )
      )
      T
    )
  )
)


;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================

(defun brx-clear-entity-link (handle / xd)
  (setq xd (brx-xdata-get handle))
  (if xd
    (progn
      (setq xd (brx-list-remove-str xd '(ROLE . "")))
      (brx-xdata-put handle nil)
    )
  )
  T
)

(defun c:BR-REMOVE-SLAVE-WORK ( / e gid h rec master )
  (setq e (brx-pick-blockref "\nPick slave to remove: "))
  (if e
    (progn
      (setq h (brx-handle-of e))
      (setq gid (brx-xdata-prop h 'GROUPID))
      (setq rec (brx-grouprec-get-real gid))
      (setq master (cdr (assoc 'MASTER rec)))
      (if (and rec (/= (strcase h T) (strcase master T)))
        (progn
          (brx-grouprec-members-remove gid h)
          (brx-clear-entity-link h)
          (brx-grouprec-blocknames-refresh gid)
          (prompt "\nSlave removed.")
        )
        (prompt "\nCannot remove master with REMOVE-SLAVE.")
      )
    )
  )
  (princ)
)

(defun c:BR-CLEAR-WORK ( / e h gid rec members)
  (setq e (brx-pick-blockref "\nPick entity to clear BLKREACTOR link: "))
  (if e
    (progn
      (setq h (brx-handle-of e))
      (setq gid (brx-xdata-prop h 'GROUPID))
      (if gid
        (progn
          (setq rec (brx-grouprec-get-real gid))
          (if rec
            (progn
              (setq members (cdr (assoc 'MEMBERS rec)))
              (foreach m members (brx-clear-entity-link m))
              (brx-dict-put-rec "BRGROUPS" gid '((GROUPID . "DELETED")))
              (prompt "\nGroup cleared.")
            )
            (brx-clear-entity-link h)
          )
        )
      )
    )
  )
  (princ)
)


;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================

(defun brx-entity-info (h / xd)
  (setq xd (or (brx-xd-get-alist h) (brx-xdata-get h)))
  (list
    (cons 'HANDLE h)
    (cons 'ROLE (cdr (assoc 'ROLE xd)))
    (cons 'GROUPID (cdr (assoc 'GROUPID xd)))
    (cons 'MASTERPARAM (cdr (assoc 'MASTERPARAM xd)))
    (cons 'BLOCKNAME (cdr (assoc 'BLOCKNAME xd)))
    (cons 'GROUPSTATE (cdr (assoc 'GROUPSTATE xd)))
    (cons 'COPYSTATE (cdr (assoc 'COPYSTATE xd)))
  )
)

(defun c:BR-SHOW-INFO-WORK ( / e h out )
  (setq e (brx-pick-blockref "\nPick BLKREACTOR block: "))
  (if e
    (progn
      (setq h (brx-handle-of e))
      (setq out (brx-entity-info h))
      (prompt (strcat "\n" (vl-princ-to-string out)))
    )
  )
  (princ)
)

(defun c:BR-GROUP-INFO-WORK ( / gid rec )
  (setq gid (getstring T "\nGROUPID: "))
  (setq rec (brx-grouprec-get-real gid))
  (if rec (prompt (strcat "\n" (vl-princ-to-string rec))))
  (princ)
)


;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================

(defun brx-find-first-existing-member (members / h out)
  (setq out nil)
  (while (and members (null out))
    (setq h (car members))
    (if (handent h) (setq out h))
    (setq members (cdr members))
  )
  out
)

(defun brx-repair-missing-master (groupid / rec members newm)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (setq newm (brx-find-first-existing-member members))
      (if newm
        (progn
          (setq rec (subst (cons 'MASTER newm) (assoc 'MASTER rec) rec))
          (brx-grouprec-put-real rec)
          (brx-rebind-master-handle groupid newm)
          newm
        )
      )
    )
  )
)

(defun brx-repair-orphan-members (groupid / rec members master h)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq master (cdr (assoc 'MASTER rec)))
      (setq members (cdr (assoc 'MEMBERS rec)))
      (foreach h members
        (if (and (handent h) (/= (strcase h T) (strcase master T)))
          (brx-xdata-prop-put h 'MASTERPARAM master)
        )
      )
      T
    )
  )
)


;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================

(defun brx-group-needs-relink-p (groupid / rec gs cs)
  (setq rec (brx-grouprec-get-real groupid))
  (setq gs (strcase (vl-princ-to-string (cdr (assoc 'GROUPSTATE rec))) T))
  (setq cs (strcase (vl-princ-to-string (cdr (assoc 'COPYSTATE rec))) T))
  (or (= gs "UNRESOLVED") (= cs "UNRESOLVED") (= cs "PARTIAL") (= cs "RELINKING"))
)

(defun brx-run-relink-pipeline (groupid / errs newm)
  (if (brx-group-needs-relink-p groupid)
    (progn
      (if (not (handent (cdr (assoc 'MASTER (brx-grouprec-get-real groupid)))))
        (setq newm (brx-repair-missing-master groupid))
      )
      (brx-repair-orphan-members groupid)
      (brx-grouprec-blocknames-refresh groupid)
      (setq errs (brx-validate-group-real groupid))
      (if errs
        (brx-mark-group-state groupid "ERROR" "PARTIAL")
        (brx-mark-group-state groupid "ACTIVE" "NORMAL")
      )
      errs
    )
  )
)

(defun c:BR-RELINK-WORK ( / gid errs )
  (setq gid (getstring T "\nGROUPID to relink: "))
  (setq errs (brx-run-relink-pipeline gid))
  (prompt (strcat "\nRELINK: " (vl-princ-to-string errs)))
  (princ)
)


;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================

(defun brx-list-groupids-real ( / dict item out)
  (setq dict (brx-dict-ensure "BRGROUPS"))
  (setq item (dictnext dict T))
  (setq out nil)
  (while item
    (if (assoc 3 item) (setq out (cons (cdr (assoc 3 item)) out)))
    (setq item (dictnext dict))
  )
  (reverse out)
)

(defun brx-batch-validate-real ( / gids out gid )
  (setq gids (brx-list-groupids-real))
  (setq out nil)
  (foreach gid gids
    (setq out (cons (cons gid (brx-validate-group-real gid)) out))
  )
  (reverse out)
)

(defun brx-batch-repair-real ( / gids out gid errs)
  (setq gids (brx-list-groupids-real))
  (setq out nil)
  (foreach gid gids
    (setq errs (if (brx-group-needs-relink-p gid) (brx-run-relink-pipeline gid) (brx-validate-group-real gid)))
    (setq out (cons (cons gid errs) out))
  )
  (reverse out)
)

(defun c:BR-VALIDATE-BATCH-WORK ( / out )
  (setq out (brx-batch-validate-real))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

(defun c:BR-REPAIR-BATCH-WORK ( / out )
  (setq out (brx-batch-repair-real))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)


;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================

(defun brx-refresh-fieldstate-real (handle fieldid / st)
  (setq st (or (cdr (assoc fieldid (brx-object-fieldstates handle))) (brx-field-state-make fieldid "FIELDEXCEL" nil "")))
  (setq st (subst (cons 'FIELDSTATE "ACTIVE") (assoc 'FIELDSTATE st) st))
  (brx-object-fieldstate-put handle fieldid st)
  st
)

(defun brx-writeback-real-stub (handle fieldid newText / st)
  (setq st (brx-field-bridge-push-stub handle fieldid newText))
  (setq st (subst (cons 'FIELDSTATE "ACTIVE") (assoc 'FIELDSTATE st) st))
  (brx-object-fieldstate-put handle fieldid st)
  st
)

(defun c:BR-FIELD-REFRESH-WORK ( / e fid )
  (setq e (brx-pick-blockref "\nPick block with FIELDN: "))
  (if e
    (progn
      (setq fid (getstring T "\nFIELDID: "))
      (prompt (strcat "\n" (vl-princ-to-string (brx-refresh-fieldstate-real (brx-handle-of e) fid))))
    )
  )
  (princ)
)


;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================

(defun brx-loader-health-report ( / rec )
  (setq rec (brx-code-rec-get-real))
  (if (null rec)
    '((STATE . "MISSING"))
    (list
      (cons 'BRCODEVERSION (cdr (assoc 'BRCODEVERSION rec)))
      (cons 'INSTALLSTATE (cdr (assoc 'BRCODEINSTALLSTATE rec)))
      (cons 'LOADERSTATE (cdr (assoc 'BRCODELOADERSTATE rec)))
      (cons 'HASH (cdr (assoc 'BRCODEHASH rec)))
    )
  )
)

(defun c:BR-FORCE-INSTALL-WORK ( / rec )
  (setq rec (or (brx-code-rec-get-real) (brx-code-rec-make "0.0" "UNKNOWN" nil)))
  (setq rec (subst (cons 'BRCODEINSTALLSTATE "INSTALLED") (assoc 'BRCODEINSTALLSTATE rec) rec))
  (setq rec (subst (cons 'BRCODELOADERSTATE "AVAILABLE") (assoc 'BRCODELOADERSTATE rec) rec))
  (brx-code-rec-put-real rec)
  (prompt (strcat "\n" (vl-princ-to-string (brx-loader-health-report))))
  (princ)
)

(defun c:BR-LOADER-INFO-WORK ( / )
  (prompt (strcat "\n" (vl-princ-to-string (brx-loader-health-report))))
  (princ)
)


;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================

(defun c:BRX-COMMANDS-DEMO ( / gid rec )
  (prompt "\n1) Run BR-NEW-GROUP-WORK")
  (prompt "\n2) Run BR-SHOW-INFO-WORK or BR-GROUP-INFO-WORK")
  (prompt "\n3) Simulate copy issue -> set GROUPSTATE/COPYSTATE to UNRESOLVED")
  (prompt "\n4) Run BR-RELINK-WORK")
  (prompt "\n5) Run BR-VALIDATE-BATCH-WORK")
  (princ)
)

(defun c:BRX-MARK-UNRESOLVED ( / gid rec )
  (setq gid (getstring T "\nGROUPID: "))
  (setq rec (brx-grouprec-get-real gid))
  (if rec
    (progn
      (setq rec (subst (cons 'GROUPSTATE "UNRESOLVED") (assoc 'GROUPSTATE rec) rec))
      (setq rec (subst (cons 'COPYSTATE "UNRESOLVED") (assoc 'COPYSTATE rec) rec))
      (brx-grouprec-put-real rec)
      (prompt "\nGroup marked unresolved.")
    )
  )
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_Commands_v4_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Hardening_v5_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Hardening_v5_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================

(defun brx-dict-item-exists-p (dictName key / dict found)
  (setq dict (brx-dict-ensure dictName))
  (setq found (dictsearch dict key))
  (if found T nil)
)

(defun brx-dict-del-rec-safe (dictName key / dict found xr ok)
  (setq dict (brx-dict-ensure dictName))
  (setq found (dictsearch dict key))
  (if found
    (progn
      (setq xr (cdr (assoc -1 found)))
      (setq ok (vl-catch-all-apply 'dictremove (list dict key)))
      (if (not (vl-catch-all-error-p ok))
        (if xr (vl-catch-all-apply 'entdel (list xr)))
      )
      (if (vl-catch-all-error-p ok) nil T)
    )
    T
  )
)

(defun brx-delete-group-record-safe (groupid /)
  (brx-dict-del-rec-safe "BRGROUPS" groupid)
)

(defun brx-delete-lockset-record-safe (locksetid /)
  (brx-dict-del-rec-safe "BRLOCKSETS" locksetid)
)


;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================

(defun brx-strip-app-xdata (e / en ed out app skip)
  (setq en (brx-safe-ename e))
  (setq app (brx-acad-appid))
  (if en
    (progn
      (setq ed (entget en '("*")))
      (setq out nil skip nil)
      (while ed
        (cond
          ((and (= (caar ed) 1001) (= (cdar ed) app)) (setq skip T))
          ((and skip (= (caar ed) 1001)) (setq skip nil) (setq out (cons (car ed) out)))
          ((not skip) (setq out (cons (car ed) out)))
        )
        (setq ed (cdr ed))
      )
      (setq out (reverse out))
      (brx-entmod-safe out)
      (brx-entupd-safe en)
      T
    )
    nil
  )
)

(defun brx-clear-entity-link-real (handle / en)
  (setq en (brx-safe-ename handle))
  (if en (brx-strip-app-xdata en))
  (brx-xdata-put handle nil)
  T
)

(defun brx-clear-group-links-real (groupid / rec members)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (foreach h members (brx-clear-entity-link-real h))
      T
    )
    nil
  )
)


;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)

(defun brx-log-event (kind code message payload / rec)
  (setq rec (list
    (cons 'TIME (menucmd "m=$(edtime,$(getvar,date),YYYY-MM-DDTHH:MM:SS)"))
    (cons 'KIND kind)
    (cons 'CODE code)
    (cons 'MESSAGE message)
    (cons 'PAYLOAD payload)
  ))
  (setq *brx-error-log* (cons rec *brx-error-log*))
  rec
)

(defun brx-log-error (code message payload /)
  (brx-log-event "ERROR" code message payload)
)

(defun brx-log-info (code message payload /)
  (brx-log-event "INFO" code message payload)
)






;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================

(defun brx-no-duplicate-members-p (members / seen ok h)
  (setq seen nil ok T)
  (foreach h members
    (if (member (strcase (vl-princ-to-string h) T) seen)
      (setq ok nil)
      (setq seen (cons (strcase (vl-princ-to-string h) T) seen))
    )
  )
  ok
)

(defun brx-validate-group-strict (groupid / rec errs members master)
  (setq rec (brx-grouprec-get-real groupid))
  (setq errs (brx-validate-group-real groupid))
  (if rec
    (progn
      (setq members (cdr (assoc 'MEMBERS rec)))
      (setq master (cdr (assoc 'MASTER rec)))
      (if (not (member master members))
        (setq errs (cons "MASTER not present in MEMBERS" errs))
      )
      (if (not (brx-no-duplicate-members-p members))
        (setq errs (cons "Duplicate handles in MEMBERS" errs))
      )
      (if (/= (length (cdr (assoc 'BLOCKNAMES rec))) (length members))
        (setq errs (cons "BLOCKNAMES count mismatch" errs))
      )
      (if (null (handent master))
        (setq errs (cons "Fatal: master handle absent in DWG" errs))
      )
    )
  )
  (reverse errs)
)

(defun brx-group-fatal-p (errs /)
  (if (vl-some '(lambda (e) (wcmatch (strcase e T) "FATAL*")) errs) T nil)
)


;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================

(defun brx-cell-address-p (s /)
  (and (= (type s) 'STR) (> (strlen s) 1) (wcmatch (strcase s T) "[A-Z]#,*"))
)

(defun brx-cell-split (addr / i ch col row)
  (setq i 1 col "" row "")
  (while (<= i (strlen addr))
    (setq ch (substr addr i 1))
    (if (wcmatch ch "[0-9]")
      (setq row (strcat row ch))
      (setq col (strcat col ch))
    )
    (setq i (1+ i))
  )
  (list col row)
)

(defun brx-table-cell-ref-make (tableHandle addr / rc)
  (setq rc (brx-cell-split (strcase addr T)))
  (list
    (cons 'TABLEHANDLE tableHandle)
    (cons 'CELLADDR (strcase addr T))
    (cons 'COL (car rc))
    (cons 'ROW (cadr rc))
  )
)

(defun brx-table-cell-resolve-stub (tableHandle addr /)
  (brx-table-cell-ref-make tableHandle addr)
)


;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================

(defun brx-simulate-copy-remap (groupid oldNewPairs /)
  (setq *brx-deepclone-map* oldNewPairs)
  (brx-mark-group-unresolved-copy groupid)
  (brx-apply-deepclone-remap groupid)
  (brx-run-relink-pipeline groupid)
)




;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)

(defun brx-set-dry-run (flag /)
  (setq *brx-dry-run* (if flag T nil))
)

(defun brx-destructive-allowed-p (/)
  (not *brx-dry-run*)
)





(defun brx-delete-group-safe-guarded (groupid /)
  (if (brx-destructive-allowed-p)
    (progn
      (brx-clear-group-links-real groupid)
      (brx-delete-group-record-safe groupid)
      T
    )
    (progn
      (brx-log-info "DRYRUN" "Delete group skipped" (list (cons 'GROUPID groupid)))
      nil
    )
  )
)


;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================

(defun brx-quarantine-group (groupid errs / rec)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq rec (subst (cons 'GROUPSTATE "ERROR") (assoc 'GROUPSTATE rec) rec))
      (setq rec (subst (cons 'COPYSTATE "PARTIAL") (assoc 'COPYSTATE rec) rec))
      (brx-grouprec-put-real rec)
      (brx-log-error "QUARANTINE" "Group quarantined" (list (cons 'GROUPID groupid) (cons 'ERRORS errs)))
      T
    )
    nil
  )
)

(defun brx-disable-group (groupid / rec)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (progn
      (setq rec (subst (cons 'GROUPSTATE "DISABLED") (assoc 'GROUPSTATE rec) rec))
      (brx-grouprec-put-real rec)
      T
    )
  )
)


;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================

(defun brx-group-snapshot (groupid / rec)
  (setq rec (brx-grouprec-get-real groupid))
  (if rec
    (list
      (cons 'GROUPID (cdr (assoc 'GROUPID rec)))
      (cons 'MASTER (cdr (assoc 'MASTER rec)))
      (cons 'MEMBERCOUNT (length (cdr (assoc 'MEMBERS rec))))
      (cons 'BLOCKNAMES (cdr (assoc 'BLOCKNAMES rec)))
      (cons 'GROUPSTATE (cdr (assoc 'GROUPSTATE rec)))
      (cons 'COPYSTATE (cdr (assoc 'COPYSTATE rec)))
    )
  )
)

(defun brx-snapshot-diff (a b / out ka kb)
  (setq out nil)
  (foreach ka a
    (setq kb (assoc (car ka) b))
    (if (/= (vl-princ-to-string (cdr ka)) (vl-princ-to-string (cdr kb)))
      (setq out (cons (list (car ka) (cdr ka) (cdr kb)) out))
    )
  )
  (reverse out)
)




;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================

(defun brx-stabilize-group (groupid / errs)
  (setq errs (brx-validate-group-strict groupid))
  (cond
    ((null errs)
      (brx-log-info "STABLE" "Group passed strict validation" (list (cons 'GROUPID groupid)))
      nil
    )
    ((brx-group-fatal-p errs)
      (brx-quarantine-group groupid errs)
      errs
    )
    (T
      (brx-run-relink-pipeline groupid)
      (setq errs (brx-validate-group-strict groupid))
      (if errs (brx-quarantine-group groupid errs))
      errs
    )
  )
)

(defun c:BR-STABILIZE-ALL ( / gids out gid errs )
  (setq gids (brx-list-groupids-real))
  (setq out nil)
  (foreach gid gids
    (setq errs (brx-stabilize-group gid))
    (setq out (cons (cons gid errs) out))
  )
  (prompt (strcat "\n" (vl-princ-to-string (reverse out))))
  (princ)
)



;;; END MODULE: output/BLK_REACTOR_Hardening_v5_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Tests_v6_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Tests_v6_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)

(defun brx-test-reset ( / )
  (setq *brx-test-results* nil)
)

(defun brx-test-record (name ok actual expected / rec)
  (setq rec (list
    (cons 'NAME name)
    (cons 'PASS (if ok T nil))
    (cons 'ACTUAL actual)
    (cons 'EXPECTED expected)
  ))
  (setq *brx-test-results* (cons rec *brx-test-results*))
  rec
)

(defun brx-assert-equal (name actual expected / ok)
  (setq ok (= (vl-princ-to-string actual) (vl-princ-to-string expected)))
  (brx-test-record name ok actual expected)
)

(defun brx-assert-true (name value /)
  (brx-test-record name (if value T nil) value T)
)

(defun brx-assert-false (name value /)
  (brx-test-record name (if value nil T) value nil)
)

(defun brx-test-summary ( / pass fail )
  (setq pass 0 fail 0)
  (foreach r *brx-test-results*
    (if (cdr (assoc 'PASS r)) (setq pass (1+ pass)) (setq fail (1+ fail)))
  )
  (list (cons 'PASS pass) (cons 'FAIL fail) (cons 'TOTAL (+ pass fail)))
)


;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================

(defun brx-fixture-clear-all ( / )
  (setq *brx-xdata-store* nil)
  (setq *brx-nod-store* nil)
  (setq *brx-runtime-cache* nil)
  (setq *brx-deepclone-map* nil)
)

(defun brx-fixture-master (h gid /)
  (brx-xdata-put h (list
    (cons 'ROLE "MASTER")
    (cons 'GROUPID gid)
    (cons 'MASTERPARAM h)
    (cons 'GROUPVERSION "1.0")
    (cons 'GROUPSTATE "ACTIVE")
    (cons 'COPYSTATE "NORMAL")
    (cons 'BLOCKNAME "PIPE")
    (cons 'PARAMS '(("DISTANCE1" . 1200.0) ("K1" . 2.5)))
    (cons 'ATTRS '(("TAG1" . "M1") ("NAME" . "PIPE")))
    (cons 'FIELDS '(("RESULT" . "OK")))
  ))
)

(defun brx-fixture-slave (h gid master /)
  (brx-xdata-put h (list
    (cons 'ROLE "SLAVE")
    (cons 'GROUPID gid)
    (cons 'MASTERPARAM master)
    (cons 'GROUPVERSION "1.0")
    (cons 'GROUPSTATE "ACTIVE")
    (cons 'COPYSTATE "NORMAL")
    (cons 'BLOCKNAME "VALVE")
    (cons 'PARAMS '(("WIDTH" . 300.0)))
    (cons 'ATTRS '(("TAG1" . "S1") ("NAME" . "VALVE")))
    (cons 'FIELDS '(("RESULT" . "SL")))
  ))
)

(defun brx-fixture-table (h gid /)
  (brx-xdata-put h (list
    (cons 'ROLE "TABLE")
    (cons 'GROUPID gid)
    (cons 'MASTERPARAM h)
    (cons 'GROUPVERSION "1.0")
    (cons 'GROUPSTATE "ACTIVE")
    (cons 'COPYSTATE "NORMAL")
    (cons 'BLOCKNAME "TABLE")
    (cons 'FIELDS '(("A1" . "X") ("B2" . "Y")))
  ))
)

(defun brx-fixture-group-basic ( / gid )
  (setq gid "GRP-TEST-001")
  (brx-fixture-clear-all)
  (brx-fixture-master "2A4F" gid)
  (brx-fixture-slave "3B12" gid "2A4F")
  (brx-fixture-table "4C89" gid)
  (brx-grouprec-put (brx-grouprec-make gid "2A4F" '("2A4F" "3B12" "4C89") '("PIPE" "VALVE" "TABLE")))
  gid
)


;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================

(defun brx-run-parser-tests ( / gid ctx rv )
  (setq gid (brx-fixture-group-basic))
  (setq ctx (brx-sample-ctx))
  (setq *brx-test-results* nil)
  (setq rv (brx-eval-expr ctx "IF(TRUE,\"YES\",\"NO\")"))
  (brx-assert-equal "parser-if" (brx-rv-value rv) "YES")
  (setq rv (brx-eval-expr ctx "MASTER.PARAMDISTANCE1"))
  (brx-assert-equal "resolver-master-param" (brx-rv-value rv) 1200.0)
  (setq rv (brx-eval-expr ctx "FMT(MASTER.PARAMDISTANCE1,\"0.0\")"))
  (brx-assert-true "format-nonempty" (> (strlen (vl-princ-to-string (brx-rv-value rv))) 0))
  (brx-test-summary)
)


;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================

(defun brx-run-alias-tests ( / ctx rv )
  (setq *brx-test-results* nil)
  (setq ctx (list
    (cons :self nil)
    (cons :master nil)
    (cons :group nil)
    (cons :aliases '(("A" . "B") ("B" . "C") ("C" . "A") ("X" . "UNKNOWNREF")))
  ))
  (setq rv (brx-eval-alias ctx "A"))
  (brx-assert-equal "alias-cycle-code" (brx-rv-code rv) "007")
  (setq rv (brx-eval-alias ctx "NOPE"))
  (brx-assert-equal "alias-missing-code" (brx-rv-code rv) "003")
  (brx-test-summary)
)


;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================

(defun brx-fixture-ctx-from-group (gid / master slave table grp aliases)
  (setq master (brx-sample-object "2A4F" "MASTER" "PIPE" '(("NAME" . "PIPE")) '(("DISTANCE1" . 1200.0)) '(("RESULT" . "OK"))))
  (setq slave  (brx-sample-object "3B12" "SLAVE" "VALVE" '(("NAME" . "VALVE")) '(("WIDTH" . 300.0)) '(("RESULT" . "SL"))))
  (setq table  (brx-sample-object "4C89" "TABLE" "TABLE" nil nil '(("A1" . "X"))))
  (setq grp (list (cons :objects (list master slave table)) (cons :slaves (list slave)) (cons :tables (list table))))
  (setq aliases nil)
  (list (cons :self slave) (cons :master master) (cons :row slave) (cons :col table) (cons :match master) (cons :table table) (cons :group grp) (cons :aliases aliases))
)

(defun brx-run-typeset-tests ( / gid ctx rv )
  (setq gid (brx-fixture-group-basic))
  (setq ctx (brx-fixture-ctx-from-group gid))
  (setq *brx-test-results* nil)
  (setq rv (brx-eval-expr ctx "COUNTLIST(GROUP.OBJECTS)"))
  (brx-assert-equal "countlist-group-objects" (brx-rv-value rv) 3)
  (setq rv (brx-eval-expr ctx "BLOCKNAMELIST(GROUP.OBJECTS)"))
  (brx-assert-true "blocknamelist-is-list" (= (brx-rv-type rv) "LIST"))
  (setq rv (brx-eval-expr ctx "TAKEONLY(GROUP.SLAVES)"))
  (brx-assert-true "takeonly-singleton" (not (brx-err-p rv)))
  (brx-test-summary)
)


;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================

(defun brx-run-validate-relink-tests ( / gid errs )
  (setq gid (brx-fixture-group-basic))
  (setq *brx-test-results* nil)
  (setq errs (brx-validate-group gid))
  (brx-assert-equal "validate-basic-empty" errs nil)
  (brx-mark-group-state gid "UNRESOLVED" "UNRESOLVED")
  (setq errs (brx-run-relink-pipeline gid))
  (brx-assert-true "relink-returns-list-or-nil" (or (null errs) (listp errs)))
  (brx-test-summary)
)


;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================

(defun brx-run-bidir-tests ( / fieldRec rv )
  (setq *brx-test-results* nil)
  (setq fieldRec '((FIELDID . "F1") (FIELDTARGETKIND . "ATTRIB") (FIELDVALUETYPE . "FORMULA") (FIELDMODE . "FIELDEXCEL") (FIELDDIRECTION . "BIDIR") (FIELDREVERSERULE . "TEXT") (WRITEBACKTARGETREF . "MASTER.PARAMK1")))
  (setq rv (brx-writeback-stub fieldRec "42"))
  (brx-assert-false "writeback-not-error" (brx-err-p rv))
  (setq rv (brx-writeback-real-stub "2A4F" "F1" "42"))
  (brx-assert-equal "fieldstate-active" (cdr (assoc 'FIELDSTATE rv)) "ACTIVE")
  (brx-test-summary)
)


;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================

(defun brx-run-copy-tests ( / gid rec )
  (setq gid (brx-fixture-group-basic))
  (setq *brx-test-results* nil)
  (brx-simulate-copy-remap gid (list (cons "2A4F" "9Z99")))
  (setq rec (brx-grouprec-get gid))
  (brx-assert-true "copy-remap-has-record" (not (null rec)))
  (brx-assert-true "copy-remap-copystate-present" (not (null (assoc 'COPYSTATE rec))))
  (brx-test-summary)
)


;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================

(defun brx-format-test-report (title results / lines)
  (setq lines (list (strcat "TESTSUITE=" title) (strcat "SUMMARY=" (vl-princ-to-string (brx-test-summary)))))
  (foreach r (reverse results)
    (setq lines (append lines (list (strcat (if (cdr (assoc 'PASS r)) "PASS: " "FAIL: ") (vl-princ-to-string (cdr (assoc 'NAME r)))))))
  )
  lines
)

(defun brx-run-all-regressions ( / reports )
  (setq reports nil)
  (brx-run-parser-tests)
  (setq reports (cons (brx-format-test-report "parser" *brx-test-results*) reports))
  (brx-run-alias-tests)
  (setq reports (cons (brx-format-test-report "alias" *brx-test-results*) reports))
  (brx-run-typeset-tests)
  (setq reports (cons (brx-format-test-report "typeset" *brx-test-results*) reports))
  (brx-run-validate-relink-tests)
  (setq reports (cons (brx-format-test-report "validate-relink" *brx-test-results*) reports))
  (brx-run-bidir-tests)
  (setq reports (cons (brx-format-test-report "bidir" *brx-test-results*) reports))
  (brx-run-copy-tests)
  (setq reports (cons (brx-format-test-report "copy" *brx-test-results*) reports))
  (reverse reports)
)


;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================











;;; END MODULE: output/BLK_REACTOR_Tests_v6_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Scenarios_v7_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Scenarios_v7_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)

(defun brx-scenario-make (id title category setup runner expected /)
  (list
    (cons 'ID id)
    (cons 'TITLE title)
    (cons 'CATEGORY category)
    (cons 'SETUP setup)
    (cons 'RUNNER runner)
    (cons 'EXPECTED expected)
  )
)

(defun brx-scenario-register (sc /)
  (setq *brx-scenarios* (cons sc *brx-scenarios*))
  sc
)

(defun brx-scenario-clear ( / )
  (setq *brx-scenarios* nil)
)

(defun brx-scenario-list ( / )
  (reverse *brx-scenarios*)
)


;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================

(defun brx-scenario-setup-basic ( / gid )
  (setq gid (brx-fixture-group-basic))
  gid
)

(defun brx-scenario-setup-unresolved ( / gid )
  (setq gid (brx-fixture-group-basic))
  (brx-mark-group-state gid "UNRESOLVED" "UNRESOLVED")
  gid
)

(defun brx-scenario-setup-copy ( / gid )
  (setq gid (brx-fixture-group-basic))
  (brx-mark-group-unresolved-copy gid)
  gid
)

(defun brx-scenario-setup-bidir ( / gid )
  (setq gid (brx-fixture-group-basic))
  gid
)


;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================

(defun brx-scenario-run-validate (gid / errs)
  (setq errs (brx-validate-group gid))
  (list (cons 'GROUPID gid) (cons 'ERRORS errs) (cons 'PASS (null errs)))
)

(defun brx-scenario-run-relink (gid / errs rec)
  (setq errs (brx-run-relink-pipeline gid))
  (setq rec (brx-grouprec-get gid))
  (list
    (cons 'GROUPID gid)
    (cons 'ERRORS errs)
    (cons 'GROUPSTATE (cdr (assoc 'GROUPSTATE rec)))
    (cons 'COPYSTATE (cdr (assoc 'COPYSTATE rec)))
    (cons 'PASS (or (null errs) (= errs nil)))
  )
)

(defun brx-scenario-run-copy (gid / rec)
  (brx-simulate-copy-remap gid (list (cons "2A4F" "9Z99")))
  (setq rec (brx-grouprec-get gid))
  (list
    (cons 'GROUPID gid)
    (cons 'COPYSTATE (cdr (assoc 'COPYSTATE rec)))
    (cons 'GROUPSTATE (cdr (assoc 'GROUPSTATE rec)))
    (cons 'PASS (not (null rec)))
  )
)

(defun brx-scenario-run-bidir (gid / rv)
  (setq rv (brx-writeback-real-stub "2A4F" "F1" "42"))
  (list
    (cons 'GROUPID gid)
    (cons 'FIELDSTATE (cdr (assoc 'FIELDSTATE rv)))
    (cons 'PASS (= (cdr (assoc 'FIELDSTATE rv)) "ACTIVE"))
  )
)


;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================

(defun brx-scenario-bootstrap ( / )
  (brx-scenario-clear)
  (brx-scenario-register (brx-scenario-make "SCN-001" "basic validate" "VALIDATE" 'brx-scenario-setup-basic 'brx-scenario-run-validate '((PASS . T))))
  (brx-scenario-register (brx-scenario-make "SCN-002" "unresolved relink" "RELINK" 'brx-scenario-setup-unresolved 'brx-scenario-run-relink '((GROUPSTATE . "ACTIVE") (COPYSTATE . "NORMAL"))))
  (brx-scenario-register (brx-scenario-make "SCN-003" "copy remap" "COPY" 'brx-scenario-setup-copy 'brx-scenario-run-copy '((PASS . T))))
  (brx-scenario-register (brx-scenario-make "SCN-004" "bidir refresh" "BIDIR" 'brx-scenario-setup-bidir 'brx-scenario-run-bidir '((FIELDSTATE . "ACTIVE"))))
  (brx-scenario-list)
)


;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================

(defun brx-kv-equal-p (a b /)
  (= (vl-princ-to-string a) (vl-princ-to-string b))
)

(defun brx-expected-actual-diff (expected actual / out kv got)
  (setq out nil)
  (foreach kv expected
    (setq got (assoc (car kv) actual))
    (if (not (brx-kv-equal-p (cdr kv) (cdr got)))
      (setq out (cons (list (car kv) (cdr kv) (cdr got)) out))
    )
  )
  (reverse out)
)

(defun brx-scenario-pass-p (expected actual /)
  (null (brx-expected-actual-diff expected actual))
)


;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)

(defun brx-transcript-reset ( / )
  (setq *brx-scenario-transcript* nil)
)

(defun brx-transcript-add (entry /)
  (setq *brx-scenario-transcript* (cons entry *brx-scenario-transcript*))
  entry
)

(defun brx-run-scenario (sc / gid actual diffs pass entry)
  (setq gid (apply (cdr (assoc 'SETUP sc)) nil))
  (setq actual (apply (cdr (assoc 'RUNNER sc)) (list gid)))
  (setq diffs (brx-expected-actual-diff (cdr (assoc 'EXPECTED sc)) actual))
  (setq pass (null diffs))
  (setq entry (list
    (cons 'ID (cdr (assoc 'ID sc)))
    (cons 'TITLE (cdr (assoc 'TITLE sc)))
    (cons 'CATEGORY (cdr (assoc 'CATEGORY sc)))
    (cons 'GROUPID gid)
    (cons 'PASS pass)
    (cons 'EXPECTED (cdr (assoc 'EXPECTED sc)))
    (cons 'ACTUAL actual)
    (cons 'DIFFS diffs)
  ))
  (brx-transcript-add entry)
  entry
)

(defun brx-run-scenario-matrix ( / out )
  (setq out nil)
  (brx-transcript-reset)
  (foreach sc (brx-scenario-list)
    (setq out (cons (brx-run-scenario sc) out))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================

(defun brx-csv-escape (s / t)
  (setq t (vl-string-subst '"" "\"" (vl-princ-to-string s)))
  (strcat "\"" t "\"")
)

(defun brx-scenario-report-csv-lines (rows / lines actual)
  (setq lines (list "ID,TITLE,CATEGORY,GROUPID,PASS,DIFFCOUNT"))
  (foreach r rows
    (setq lines
      (append lines
        (list
          (strcat
            (brx-csv-escape (cdr (assoc 'ID r))) ","
            (brx-csv-escape (cdr (assoc 'TITLE r))) ","
            (brx-csv-escape (cdr (assoc 'CATEGORY r))) ","
            (brx-csv-escape (cdr (assoc 'GROUPID r))) ","
            (brx-csv-escape (if (cdr (assoc 'PASS r)) "TRUE" "FALSE")) ","
            (brx-csv-escape (itoa (length (cdr (assoc 'DIFFS r)))))
          )
        )
      )
    )
  )
  lines
)

(defun brx-scenario-report-md-lines (rows / lines)
  (setq lines (list "# BLK_REACTOR Scenario Report" "" "| ID | Title | Category | Pass | Diff count |" "|---|---|---|---|---|"))
  (foreach r rows
    (setq lines
      (append lines
        (list
          (strcat "| " (vl-princ-to-string (cdr (assoc 'ID r)))
                  " | " (vl-princ-to-string (cdr (assoc 'TITLE r)))
                  " | " (vl-princ-to-string (cdr (assoc 'CATEGORY r)))
                  " | " (if (cdr (assoc 'PASS r)) "PASS" "FAIL")
                  " | " (itoa (length (cdr (assoc 'DIFFS r)))) " |")
        )
      )
    )
  )
  lines
)


;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================

(defun brx-smoke-test-command-symbols ( / syms out s )
  (setq syms '(c:BR-SELFTEST c:BR-VALIDATE-BATCH-WORK c:BR-REPAIR-BATCH-WORK c:BR-STABILIZE-ALL c:BR-LOG-SHOW c:BR-FIELD-REFRESH-WORK))
  (setq out nil)
  (foreach s syms
    (setq out (cons (cons s (if (fboundp s) T nil)) out))
  )
  (reverse out)
)

(defun brx-run-command-smoke-tests ( / out allok)
  (setq out (brx-smoke-test-command-symbols))
  (setq allok (not (member nil (mapcar 'cdr out))))
  (list (cons 'COMMANDS out) (cons 'PASS allok))
)


;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================

(defun brx-write-lines-file (path lines / f)
  (setq f (open path "w"))
  (foreach line lines (write-line line f))
  (close f)
  path
)

(defun brx-export-scenario-report-stub (basePath / rows csv md txt)
  (setq rows (brx-run-scenario-matrix))
  (setq csv (strcat basePath ".csv"))
  (setq md  (strcat basePath ".md"))
  (setq txt (strcat basePath ".txt"))
  (brx-write-lines-file csv (brx-scenario-report-csv-lines rows))
  (brx-write-lines-file md  (brx-scenario-report-md-lines rows))
  (brx-write-lines-file txt (list (vl-princ-to-string rows)))
  (list (cons 'CSV csv) (cons 'MD md) (cons 'TXT txt))
)


;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================









;;; END MODULE: output/BLK_REACTOR_Scenarios_v7_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_TableAlias_v8_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_TableAlias_v8_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================

(defun brx-col->num (col / i n ch)
  (setq i 1 n 0 col (strcase col T))
  (while (<= i (strlen col))
    (setq ch (ascii (substr col i 1)))
    (setq n (+ (* n 26) (- ch 64)))
    (setq i (1+ i))
  )
  n
)

(defun brx-num->col (n / out r)
  (setq out "")
  (while (> n 0)
    (setq r (rem (1- n) 26))
    (setq out (strcat (chr (+ 65 r)) out))
    (setq n (/ (- n r 1) 26))
  )
  out
)

(defun brx-parse-celladdr (addr / rc)
  (setq rc (brx-cell-split (strcase addr T)))
  (list
    (cons 'ADDR (strcase addr T))
    (cons 'COLNAME (car rc))
    (cons 'ROWNAME (cadr rc))
    (cons 'COLNUM (brx-col->num (car rc)))
    (cons 'ROWNUM (atoi (cadr rc)))
  )
)

(defun brx-parse-cellrange (rng / p a b)
  (if (setq p (vl-string-search ":" rng))
    (progn
      (setq a (substr rng 1 p))
      (setq b (substr rng (+ p 2)))
      (list (cons 'FROM (brx-parse-celladdr a)) (cons 'TO (brx-parse-celladdr b)))
    )
    nil
  )
)


;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)

(defun brx-table-key (tableHandle addr /)
  (strcat (strcase (vl-princ-to-string tableHandle) T) "|" (strcase addr T))
)

(defun brx-table-cell-put (tableHandle addr rec / key)
  (setq key (brx-table-key tableHandle addr))
  (setq *brx-table-store* (cons (cons key rec) (vl-remove-if '(lambda (x) (= (car x) key)) *brx-table-store*)))
  rec
)

(defun brx-table-cell-get (tableHandle addr /)
  (cdr (assoc (brx-table-key tableHandle addr) *brx-table-store*))
)

(defun brx-table-cell-make (tableHandle addr value mode / rc)
  (setq rc (brx-parse-celladdr addr))
  (append
    (list (cons 'TABLEHANDLE tableHandle) (cons 'CELLADDR (strcase addr T)) (cons 'VALUE value) (cons 'CELLMODE mode))
    rc
  )
)

(defun brx-resolve-table-exact-stub (tableHandle addr / rec)
  (setq rec (brx-table-cell-get tableHandle addr))
  (if rec
    (brx-rv-ok rec "OBJECT" nil)
    (brx-rv-err "003" (strcat "No table cell: " (vl-princ-to-string tableHandle) "." (strcase addr T)) nil)
  )
)


;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================

(defun brx-table-merge-put (tableHandle addr anchorAddr / rec)
  (setq rec (or (brx-table-cell-get tableHandle addr) (brx-table-cell-make tableHandle addr "" "DISPLAY")))
  (setq rec (append rec (list (cons 'MERGED T) (cons 'MERGEANCHORADDR (strcase anchorAddr T)))))
  (brx-table-cell-put tableHandle addr rec)
)

(defun brx-table-anchor-addr (tableHandle addr / rec)
  (setq rec (brx-table-cell-get tableHandle addr))
  (cond
    ((null rec) nil)
    ((cdr (assoc 'MERGED rec)) (cdr (assoc 'MERGEANCHORADDR rec)))
    (T (cdr (assoc 'CELLADDR rec)))
  )
)

(defun brx-table-anchor-cell (tableHandle addr / a)
  (setq a (brx-table-anchor-addr tableHandle addr))
  (if a (brx-table-cell-get tableHandle a) nil)
)

(defun brx-table-writeback-allowed-p (tableHandle addr / rec)
  (setq rec (brx-table-cell-get tableHandle addr))
  (cond
    ((null rec) nil)
    ((and (cdr (assoc 'MERGED rec)) (/= (strcase addr T) (strcase (cdr (assoc 'MERGEANCHORADDR rec)) T))) nil)
    (T T)
  )
)


;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================

(defun brx-alias-owner-key (ownerHandle alias /)
  (strcat (strcase (vl-princ-to-string ownerHandle) T) "::" (strcase alias T))
)

(defun brx-alias-lookup-owner (ctx ownerHandle alias / amap)
  (setq amap (cdr (assoc :owner-aliases ctx)))
  (cdr (assoc (brx-alias-owner-key ownerHandle alias) amap))
)

(defun brx-eval-owner-alias (ctx ownerHandle alias / seen cur nxt)
  (setq seen nil cur (strcase alias T))
  (while cur
    (if (member cur seen)
      (progn (setq cur nil nxt (brx-rv-err "007" "Owner alias cycle" nil)))
      (progn
        (setq seen (cons cur seen))
        (setq nxt (brx-alias-lookup-owner ctx ownerHandle cur))
        (cond
          ((null nxt) (setq cur nil nxt (brx-rv-err "003" "Owner alias ref missing" nil)))
          ((wcmatch (strcase (vl-princ-to-string nxt) T) "MASTER.*,SELF.*,ROW.*,COL.*,MATCH.*,TABLE.*,CELL.*")
            (setq cur nil nxt (brx-rv-ok nxt "REF" nil))
          )
          (T (setq cur (strcase (vl-princ-to-string nxt) T)))
        )
      )
    )
  )
  nxt
)


;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================

(defun brx-targetref-make (ownerHandle ownerRole targetKind targetName targetIndex targetHandle targetPath /)
  (list
    (cons 'OWNERHANDLE ownerHandle)
    (cons 'OWNERROLE ownerRole)
    (cons 'TARGETKIND targetKind)
    (cons 'TARGETNAME targetName)
    (cons 'TARGETINDEX targetIndex)
    (cons 'TARGETHANDLE targetHandle)
    (cons 'TARGETPATH targetPath)
  )
)

(defun brx-targetref-cell (tableHandle addr / rc)
  (setq rc (brx-parse-celladdr addr))
  (brx-targetref-make tableHandle "TABLE" "TABLECELL" (strcase addr T) nil tableHandle (list rc))
)

(defun brx-targetref-nested (ownerHandle ownerRole kind name idx nestedHandle nestedPath /)
  (brx-targetref-make ownerHandle ownerRole kind name idx nestedHandle nestedPath)
)


;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================

(defun brx-normalize-text-basic (s /)
  (vl-string-trim " \t\r\n" (vl-princ-to-string s))
)

(defun brx-normalize-number-basic (s / v)
  (setq s (vl-string-subst "." "," (vl-princ-to-string s)))
  (setq v (distof s 2))
  v
)

(defun brx-table-writeback-normalize (value valueType /)
  (cond
    ((= (strcase (vl-princ-to-string valueType) T) "NUMBER") (brx-normalize-number-basic value))
    (T (brx-normalize-text-basic value))
  )
)

(defun brx-table-writeback-stub (tableHandle addr value valueType / cell norm)
  (if (not (brx-table-writeback-allowed-p tableHandle addr))
    (brx-rv-err "011" "Merged non-anchor cell is read-only for writeback" nil)
    (progn
      (setq cell (or (brx-table-anchor-cell tableHandle addr) (brx-table-cell-get tableHandle addr)))
      (setq norm (brx-table-writeback-normalize value valueType))
      (setq cell (subst (cons 'VALUE norm) (assoc 'VALUE cell) cell))
      (brx-table-cell-put tableHandle (cdr (assoc 'CELLADDR cell)) cell)
      (brx-rv-ok cell valueType nil)
    )
  )
)


;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================

(defun brx-fixture-table-grid ( / th )
  (setq th "TBL-001")
  (setq *brx-table-store* nil)
  (brx-table-cell-put th "A1" (brx-table-cell-make th "A1" "100" "BIDIR"))
  (brx-table-cell-put th "B1" (brx-table-cell-make th "B1" "200" "DISPLAY"))
  (brx-table-cell-put th "A2" (brx-table-cell-make th "A2" "X" "DISPLAY"))
  (brx-table-cell-put th "B2" (brx-table-cell-make th "B2" "Y" "DISPLAY"))
  (brx-table-merge-put th "B2" "A2")
  th
)

(defun brx-run-table-tests ( / th rv )
  (setq *brx-test-results* nil)
  (setq th (brx-fixture-table-grid))
  (setq rv (brx-resolve-table-exact-stub th "A1"))
  (brx-assert-false "table-exact-a1-not-error" (brx-err-p rv))
  (setq rv (brx-table-writeback-stub th "A2" "ZZ" "TEXT"))
  (brx-assert-false "anchor-writeback-allowed" (brx-err-p rv))
  (setq rv (brx-table-writeback-stub th "B2" "QQ" "TEXT"))
  (brx-assert-equal "merged-nonanchor-writeback-blocked" (brx-rv-code rv) "011")
  (brx-test-summary)
)


;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================

(defun brx-run-owner-alias-tests ( / ctx rv )
  (setq *brx-test-results* nil)
  (setq ctx (list
    (cons :owner-aliases (list
      (cons "2A4F::A" "B")
      (cons "2A4F::B" "MASTER.PARAMDISTANCE1")
      (cons "3B12::X" "Y")
      (cons "3B12::Y" "X")
    ))
  ))
  (setq rv (brx-eval-owner-alias ctx "2A4F" "A"))
  (brx-assert-equal "owner-alias-resolves-ref" (brx-rv-type rv) "REF")
  (setq rv (brx-eval-owner-alias ctx "3B12" "X"))
  (brx-assert-equal "owner-alias-cycle" (brx-rv-code rv) "007")
  (brx-test-summary)
)


;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================

(defun brx-run-table-regressions ( / reports )
  (setq reports nil)
  (brx-run-table-tests)
  (setq reports (cons (brx-format-test-report "table" *brx-test-results*) reports))
  (brx-run-owner-alias-tests)
  (setq reports (cons (brx-format-test-report "owner-alias" *brx-test-results*) reports))
  (reverse reports)
)






;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================





;;; END MODULE: output/BLK_REACTOR_TableAlias_v8_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_TableBridge_v9_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_TableBridge_v9_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================

(defun brx-ename->vla-safe (e / en obj)
  (setq en (brx-safe-ename e))
  (if en
    (progn
      (setq obj (vl-catch-all-apply 'vlax-ename->vla-object (list en)))
      (if (vl-catch-all-error-p obj) nil obj)
    )
    nil
  )
)

(defun brx-vla-objectname-safe (obj / r)
  (if obj
    (progn
      (setq r (vl-catch-all-apply 'vla-get-ObjectName (list obj)))
      (if (vl-catch-all-error-p r) nil r)
    )
    nil
  )
)

(defun brx-table-vla-p (obj / n)
  (setq n (brx-vla-objectname-safe obj))
  (if n (= (strcase n T) "ACDBTABLE") nil)
)

(defun brx-table-ename-p (e /)
  (brx-table-vla-p (brx-ename->vla-safe e))
)


;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================

(defun brx-vla-get-rows-safe (tbl / r)
  (setq r (vl-catch-all-apply 'vla-get-Rows (list tbl)))
  (if (vl-catch-all-error-p r) nil r)
)

(defun brx-vla-get-cols-safe (tbl / r)
  (setq r (vl-catch-all-apply 'vla-get-Columns (list tbl)))
  (if (vl-catch-all-error-p r) nil r)
)

(defun brx-vla-gettext-safe (tbl row col / r)
  (setq r (vl-catch-all-apply 'vla-GetText (list tbl row col)))
  (if (vl-catch-all-error-p r) nil r)
)

(defun brx-table-cell-read-real (tableE addr / tbl rc row col txt)
  (setq tbl (brx-ename->vla-safe tableE))
  (setq rc (brx-parse-celladdr addr))
  (setq row (1- (cdr (assoc 'ROWNUM rc))))
  (setq col (1- (cdr (assoc 'COLNUM rc))))
  (if (and tbl (brx-table-vla-p tbl))
    (brx-vla-gettext-safe tbl row col)
    nil
  )
)


;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================

(defun brx-vla-settext-safe (tbl row col txt / r)
  (setq r (vl-catch-all-apply 'vla-SetText (list tbl row col txt)))
  (if (vl-catch-all-error-p r) nil T)
)

(defun brx-table-regen-safe (tableE / en)
  (setq en (brx-safe-ename tableE))
  (if en (brx-entupd-safe en) nil)
)

(defun brx-table-cell-write-real (tableE addr txt / tbl rc row col ok)
  (setq tbl (brx-ename->vla-safe tableE))
  (setq rc (brx-parse-celladdr addr))
  (setq row (1- (cdr (assoc 'ROWNUM rc))))
  (setq col (1- (cdr (assoc 'COLNUM rc))))
  (if (and tbl (brx-table-vla-p tbl))
    (progn
      (setq ok (brx-vla-settext-safe tbl row col (vl-princ-to-string txt)))
      (if ok (brx-table-regen-safe tableE))
      ok
    )
    nil
  )
)


;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================

(defun brx-vla-ismerged-safe (tbl row col / r)
  (setq r (vl-catch-all-apply 'vla-IsMergedCell (list tbl row col)))
  (if (vl-catch-all-error-p r) nil r)
)

(defun brx-table-cell-merged-real (tableE addr / tbl rc row col r)
  (setq tbl (brx-ename->vla-safe tableE))
  (setq rc (brx-parse-celladdr addr))
  (setq row (1- (cdr (assoc 'ROWNUM rc))))
  (setq col (1- (cdr (assoc 'COLNUM rc))))
  (if (and tbl (brx-table-vla-p tbl))
    (progn
      (setq r (brx-vla-ismerged-safe tbl row col))
      (if (null r)
        (if (brx-table-cell-get (brx-handle-of tableE) addr) (cdr (assoc 'MERGED (brx-table-cell-get (brx-handle-of tableE) addr))) nil)
        r
      )
    )
    nil
  )
)


;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================

(defun brx-vla-mergeanchor-safe (tbl row col / r)
  (setq r (vl-catch-all-apply 'vla-GetMergeRange (list tbl row col)))
  (if (vl-catch-all-error-p r) nil r)
)

(defun brx-mergeanchor->addr-stub (row col /)
  (strcat (brx-num->col (1+ col)) (itoa (1+ row)))
)

(defun brx-table-anchor-addr-real (tableE addr / tbl rc row col mr a)
  (setq tbl (brx-ename->vla-safe tableE))
  (setq rc (brx-parse-celladdr addr))
  (setq row (1- (cdr (assoc 'ROWNUM rc))))
  (setq col (1- (cdr (assoc 'COLNUM rc))))
  (if (and tbl (brx-table-vla-p tbl))
    (progn
      (setq mr (brx-vla-mergeanchor-safe tbl row col))
      (cond
        (mr (brx-mergeanchor->addr-stub row col))
        ((brx-table-cell-get (brx-handle-of tableE) addr) (brx-table-anchor-addr (brx-handle-of tableE) addr))
        (T (strcase addr T))
      )
    )
    (brx-table-anchor-addr (brx-handle-of tableE) addr)
  )
)


;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================

(defun brx-sync-table-cell-real (tableE addr mode / h txt rec)
  (setq h (brx-handle-of tableE))
  (setq txt (brx-table-cell-read-real tableE addr))
  (setq rec (brx-table-cell-make h addr txt mode))
  (if (brx-table-cell-merged-real tableE addr)
    (setq rec (append rec (list (cons 'MERGED T) (cons 'MERGEANCHORADDR (brx-table-anchor-addr-real tableE addr)))))
  )
  (brx-table-cell-put h addr rec)
  rec
)

(defun brx-sync-table-range-real (tableE range mode / rg r1 r2 c1 c2 r c out addr)
  (setq rg (brx-parse-cellrange range))
  (setq r1 (cdr (assoc 'ROWNUM (cdr (assoc 'FROM rg)))))
  (setq r2 (cdr (assoc 'ROWNUM (cdr (assoc 'TO rg)))))
  (setq c1 (cdr (assoc 'COLNUM (cdr (assoc 'FROM rg)))))
  (setq c2 (cdr (assoc 'COLNUM (cdr (assoc 'TO rg)))))
  (setq out nil r r1)
  (while (<= r r2)
    (setq c c1)
    (while (<= c c2)
      (setq addr (strcat (brx-num->col c) (itoa r)))
      (setq out (cons (brx-sync-table-cell-real tableE addr mode) out))
      (setq c (1+ c))
    )
    (setq r (1+ r))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================

(defun brx-validate-table-cell-real (tableE addr / rec errs)
  (setq errs nil)
  (setq rec (brx-sync-table-cell-real tableE addr "DISPLAY"))
  (if (null rec) (setq errs (cons (strcat "No table cell synced: " addr) errs)))
  (if (and (cdr (assoc 'MERGED rec))
           (/= (strcase addr T) (strcase (cdr (assoc 'MERGEANCHORADDR rec)) T))
           (brx-table-writeback-allowed-p (brx-handle-of tableE) addr))
    (setq errs (cons (strcat "Merged non-anchor writeback flag mismatch: " addr) errs))
  )
  (reverse errs)
)






;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================

(defun brx-table-writeback-real (tableE addr value valueType / h rv)
  (setq h (brx-handle-of tableE))
  (setq rv (brx-table-writeback-stub h addr value valueType))
  (if (brx-err-p rv)
    rv
    (if (brx-table-cell-write-real tableE (cdr (assoc 'CELLADDR (brx-rv-value rv))) (cdr (assoc 'VALUE (brx-rv-value rv))))
      rv
      (brx-rv-err "011" "Real TABLE write failed" nil)
    )
  )
)




;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================

(defun brx-scenario-run-table-local ( / th rv)
  (setq th (brx-fixture-table-grid))
  (setq rv (brx-table-writeback-stub th "A2" "LOCAL" "TEXT"))
  (list
    (cons 'TABLEHANDLE th)
    (cons 'PASS (not (brx-err-p rv)))
    (cons 'ANCHORB2 (brx-table-anchor-addr th "B2"))
  )
)

(defun brx-scenario-bootstrap-tableplus ( / rows)
  (setq rows (brx-scenario-bootstrap))
  (brx-scenario-register (brx-scenario-make "SCN-005" "table local anchor" "TABLE" 'brx-fixture-table-grid 'brx-scenario-run-table-local '((PASS . T) (ANCHORB2 . "A2"))))
  (brx-scenario-list)
)


;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================

(defun c:BR-TABLE-SYNC-RANGE ( / e rng out)
  (setq e (car (entsel "\nPick TABLE: ")))
  (if (and e (brx-table-ename-p e))
    (progn
      (setq rng (getstring T "\nRange (A1:B3): "))
      (setq out (brx-sync-table-range-real e rng "DISPLAY"))
      (prompt (strcat "\nSynced cells: " (itoa (length out))))
    )
    (prompt "\nSelected object is not TABLE.")
  )
  (princ)
)

(defun c:BR-TABLE-BRIDGE-DEMO ( / reps)
  (setq reps (brx-run-table-regressions))
  (prompt (strcat "\n" (vl-princ-to-string reps)))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_TableBridge_v9_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Diag_v10_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Diag_v10_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================










;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================










;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================








;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================






;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================








;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================






;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================








;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================






;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================






;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================






;;; ============================================================
;;; Step v9.1 - table field state records and mode helpers
;;; ============================================================

(defun brx-table-fieldstate-key (tableHandle addr fieldid /)
  (strcat (strcase (vl-princ-to-string tableHandle) T) "|" (strcase addr T) "|" (strcase fieldid T))
)

(defun brx-table-fieldstate-get (tableHandle addr fieldid /)
  (brx-object-fieldstate-get (brx-table-fieldstate-key tableHandle addr fieldid) fieldid)
)

(defun brx-table-fieldstate-put (tableHandle addr fieldid rec / owner)
  (setq owner (brx-table-fieldstate-key tableHandle addr fieldid))
  (brx-object-fieldstate-put owner fieldid rec)
)

(defun brx-table-fieldmode-normalize (mode / m)
  (setq m (strcase (vl-princ-to-string mode) T))
  (cond
    ((= m "TABLEFIELDNATIVE") "FIELDNATIVE")
    ((= m "TABLEFIELDEXCEL") "FIELDEXCEL")
    (T m)
  )
)


;;; ============================================================
;;; Step v9.2 - real table field sync for FIELDNATIVE and FIELDEXCEL
;;; ============================================================

(defun brx-table-fieldstate-sync-real (tableE addr fieldid mode / h cell txt st nmode)
  (setq h (brx-handle-of tableE))
  (setq cell (brx-sync-table-cell-real tableE addr "DISPLAY"))
  (setq txt (cdr (assoc 'VALUE cell)))
  (setq nmode (brx-table-fieldmode-normalize mode))
  (setq st (brx-field-state-make fieldid nmode txt (vl-princ-to-string txt)))
  (setq st (subst (cons 'FIELDSTATE "ACTIVE") (assoc 'FIELDSTATE st) st))
  (setq st (append st (list (cons 'TABLEHANDLE h) (cons 'CELLADDR (strcase addr T)))))
  (brx-table-fieldstate-put h addr fieldid st)
  st
)

(defun brx-table-fieldstate-refresh-native (tableE addr fieldid /)
  (brx-table-fieldstate-sync-real tableE addr fieldid "TABLEFIELDNATIVE")
)

(defun brx-table-fieldstate-refresh-excel (tableE addr fieldid /)
  (brx-table-fieldstate-sync-real tableE addr fieldid "TABLEFIELDEXCEL")
)


;;; ============================================================
;;; Step v9.3 - table field reverse writeback bridge
;;; ============================================================

(defun brx-table-field-writeback-real (tableE addr fieldid value valueType / rv st h)
  (setq rv (brx-table-writeback-real tableE addr value valueType))
  (setq h (brx-handle-of tableE))
  (if (brx-err-p rv)
    (progn
      (setq st (brx-field-state-make fieldid "FIELDEXCEL" nil ""))
      (setq st (subst (cons 'FIELDSTATE "ERROR") (assoc 'FIELDSTATE st) st))
      (setq st (append st (list (cons 'TABLEHANDLE h) (cons 'CELLADDR (strcase addr T)) (cons 'FIELDLASTTEXT (vl-princ-to-string value)))))
      (brx-table-fieldstate-put h addr fieldid st)
      rv
    )
    (progn
      (setq st (brx-table-fieldstate-sync-real tableE addr fieldid "TABLEFIELDEXCEL"))
      (brx-rv-ok st valueType nil)
    )
  )
)


;;; ============================================================
;;; Step v9.4 - field diagnostics for groups and tables
;;; ============================================================

(defun brx-diag-fieldstate-basic (owner fieldid st /)
  (list
    (cons 'OWNER owner)
    (cons 'FIELDID fieldid)
    (cons 'FIELDMODE (cdr (assoc 'FIELDMODE st)))
    (cons 'FIELDSTATE (cdr (assoc 'FIELDSTATE st)))
    (cons 'FIELDLASTTEXT (cdr (assoc 'FIELDLASTTEXT st)))
  )
)

(defun brx-diag-group-fields (groupid / rec members out h fs)
  (setq rec (brx-grouprec-get-real groupid))
  (setq out nil)
  (if rec
    (foreach h (cdr (assoc 'MEMBERS rec))
      (setq fs (brx-object-fieldstates h))
      (foreach pair fs
        (setq out (cons (brx-diag-fieldstate-basic h (car pair) (cdr pair)) out))
      )
    )
  )
  (reverse out)
)

(defun brx-diag-table-fields (tableHandle / out fs)
  (setq out nil)
  (setq fs (brx-object-fieldstates tableHandle))
  (foreach pair fs
    (setq out (cons (brx-diag-fieldstate-basic tableHandle (car pair) (cdr pair)) out))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v9.5 - global diagnostics aggregators
;;; ============================================================

(defun brx-diag-groups-all ( / gids out gid errs)
  (setq gids (brx-list-groupids-real))
  (setq out nil)
  (foreach gid gids
    (setq errs (brx-validate-group-strict gid))
    (setq out (cons (list (cons 'GROUPID gid) (cons 'ERRORS errs) (cons 'PASS (null errs))) out))
  )
  (reverse out)
)

(defun brx-diag-tables-all ( / out kv rec handle)
  (setq out nil)
  (foreach kv *brx-table-store*
    (setq rec (cdr kv))
    (setq handle (cdr (assoc 'TABLEHANDLE rec)))
    (if (not (assoc handle out))
      (setq out (cons (cons handle (brx-diag-table-fields handle)) out))
    )
  )
  (reverse out)
)

(defun brx-diag-loader-basic ( /)
  (brx-loader-health-report)
)


;;; ============================================================
;;; Step v9.6 - unified BR-DIAG report model
;;; ============================================================

(defun brx-diag-build-report ( /)
  (list
    (cons 'TIME (menucmd "m=$(edtime,$(getvar,date),YYYY-MM-DDTHH:MM:SS)"))
    (cons 'LOADER (brx-diag-loader-basic))
    (cons 'GROUPS (brx-diag-groups-all))
    (cons 'TABLES (brx-diag-tables-all))
    (cons 'LOG (reverse *brx-error-log*))
  )
)

(defun brx-diag-summary (rep / groups pass fail)
  (setq groups (cdr (assoc 'GROUPS rep)))
  (setq pass 0 fail 0)
  (foreach g groups
    (if (cdr (assoc 'PASS g)) (setq pass (1+ pass)) (setq fail (1+ fail)))
  )
  (list
    (cons 'GROUPPASS pass)
    (cons 'GROUPFAIL fail)
    (cons 'TABLECOUNT (length (cdr (assoc 'TABLES rep))))
    (cons 'LOGCOUNT (length (cdr (assoc 'LOG rep))))
  )
)


;;; ============================================================
;;; Step v9.7 - diagnostic export writers
;;; ============================================================

(defun brx-diag-report-md-lines (rep / sum lines)
  (setq sum (brx-diag-summary rep))
  (setq lines (list
    "# BLK_REACTOR Diagnostic Report"
    ""
    (strcat "- Time: " (vl-princ-to-string (cdr (assoc 'TIME rep))))
    (strcat "- Group pass: " (itoa (cdr (assoc 'GROUPPASS sum))))
    (strcat "- Group fail: " (itoa (cdr (assoc 'GROUPFAIL sum))))
    (strcat "- Table count: " (itoa (cdr (assoc 'TABLECOUNT sum))))
    (strcat "- Log count: " (itoa (cdr (assoc 'LOGCOUNT sum))))
    ""
    "## Loader"
    (vl-princ-to-string (cdr (assoc 'LOADER rep)))
    ""
    "## Groups"
    (vl-princ-to-string (cdr (assoc 'GROUPS rep)))
    ""
    "## Tables"
    (vl-princ-to-string (cdr (assoc 'TABLES rep)))
  ))
  lines
)

(defun brx-diag-report-csv-lines (rep / lines groups g)
  (setq lines (list "GROUPID,PASS,ERRORCOUNT"))
  (setq groups (cdr (assoc 'GROUPS rep)))
  (foreach g groups
    (setq lines
      (append lines
        (list
          (strcat
            (vl-princ-to-string (cdr (assoc 'GROUPID g))) ","
            (if (cdr (assoc 'PASS g)) "TRUE" "FALSE") ","
            (itoa (length (cdr (assoc 'ERRORS g))))
          )
        )
      )
    )
  )
  lines
)

(defun brx-diag-export-stub (basePath / rep md csv txt)
  (setq rep (brx-diag-build-report))
  (setq md (strcat basePath ".md"))
  (setq csv (strcat basePath ".csv"))
  (setq txt (strcat basePath ".txt"))
  (brx-write-lines-file md (brx-diag-report-md-lines rep))
  (brx-write-lines-file csv (brx-diag-report-csv-lines rep))
  (brx-write-lines-file txt (list (vl-princ-to-string rep)))
  (list (cons 'MD md) (cons 'CSV csv) (cons 'TXT txt))
)


;;; ============================================================
;;; Step v9.8 - table field tests and diagnostics tests
;;; ============================================================

(defun brx-run-table-field-tests ( / th rv st rep)
  (setq *brx-test-results* nil)
  (setq th (brx-fixture-table-grid))
  (setq rv (brx-table-field-writeback-real th "A1" "TF1" "555" "TEXT"))
  (brx-assert-false "table-field-writeback-no-error" (brx-err-p rv))
  (setq st (brx-table-fieldstate-get th "A1" "TF1"))
  (brx-assert-true "table-fieldstate-present" (not (null st)))
  (setq rep (brx-diag-build-report))
  (brx-assert-true "diag-report-has-loader" (not (null (assoc 'LOADER rep))))
  (brx-test-summary)
)


;;; ============================================================
;;; Step v9.9 - scenario and selftest integration for diagnostics
;;; ============================================================

(defun brx-scenario-run-diag-local ( / rep sum)
  (setq rep (brx-diag-build-report))
  (setq sum (brx-diag-summary rep))
  (list
    (cons 'PASS T)
    (cons 'GROUPFAIL (cdr (assoc 'GROUPFAIL sum)))
    (cons 'TABLECOUNT (cdr (assoc 'TABLECOUNT sum)))
  )
)

(defun brx-scenario-bootstrap-diagplus ( /)
  (brx-scenario-bootstrap-tableplus)
  (brx-scenario-register (brx-scenario-make "SCN-006" "diag summary" "DIAG" 'brx-fixture-group-basic 'brx-scenario-run-diag-local '((PASS . T))))
  (brx-scenario-list)
)




;;; ============================================================
;;; Step v10.0 - public BR-DIAG commands and exported report artifacts
;;; ============================================================

(defun c:BR-DIAG ( / rep)
  (setq rep (brx-diag-build-report))
  (prompt (strcat "\n" (vl-princ-to-string rep)))
  (princ)
)

(defun c:BR-DIAG-SUMMARY ( / rep sum)
  (setq rep (brx-diag-build-report))
  (setq sum (brx-diag-summary rep))
  (prompt (strcat "\n" (vl-princ-to-string sum)))
  (princ)
)

(defun c:BR-DIAG-EXPORT ( / out)
  (setq out (brx-diag-export-stub "output/brx_diag_report"))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

(defun c:BR-VALIDATE-ALL-PLUS ( / rep)
  (setq rep (brx-diag-build-report))
  (prompt (strcat "\n" (vl-princ-to-string (cdr (assoc 'GROUPS rep)))))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_Diag_v10_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Fix_v11_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Fix_v11_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================










;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================










;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================








;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================






;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================








;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================






;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================








;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================






;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================






;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================






;;; ============================================================
;;; Step v9.1 - table field state records and mode helpers
;;; ============================================================










;;; ============================================================
;;; Step v9.2 - real table field sync for FIELDNATIVE and FIELDEXCEL
;;; ============================================================








;;; ============================================================
;;; Step v9.3 - table field reverse writeback bridge
;;; ============================================================




;;; ============================================================
;;; Step v9.4 - field diagnostics for groups and tables
;;; ============================================================








;;; ============================================================
;;; Step v9.5 - global diagnostics aggregators
;;; ============================================================








;;; ============================================================
;;; Step v9.6 - unified BR-DIAG report model
;;; ============================================================






;;; ============================================================
;;; Step v9.7 - diagnostic export writers
;;; ============================================================








;;; ============================================================
;;; Step v9.8 - table field tests and diagnostics tests
;;; ============================================================




;;; ============================================================
;;; Step v9.9 - scenario and selftest integration for diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.0 - public BR-DIAG commands and exported report artifacts
;;; ============================================================










;;; ============================================================
;;; Step v10.1 - diagnostic issue classifiers and routing
;;; ============================================================

(defun brx-diag-error-kind (msg / m)
  (setq m (strcase (vl-princ-to-string msg) T))
  (cond
    ((wcmatch m "*MASTER*") "MASTER")
    ((wcmatch m "*MEMBER*") "MEMBER")
    ((wcmatch m "*BLOCKNAMES*") "BLOCKNAMES")
    ((wcmatch m "*COPY*" ) "COPY")
    ((wcmatch m "*TABLE*" ) "TABLE")
    ((wcmatch m "*FIELD*" ) "FIELD")
    (T "GENERIC")
  )
)

(defun brx-diag-group-fixes-needed (groupDiag / errs out e)
  (setq errs (cdr (assoc 'ERRORS groupDiag)))
  (setq out nil)
  (foreach e errs
    (setq out (cons (brx-diag-error-kind e) out))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v10.2 - field reset and table field reset helpers
;;; ============================================================

(defun brx-reset-object-fieldstates (owner / fs pair out)
  (setq fs (brx-object-fieldstates owner))
  (setq out nil)
  (foreach pair fs
    (brx-object-fieldstate-put owner (car pair) (brx-field-state-make (car pair) "FIELDEXCEL" nil ""))
    (setq out (cons (car pair) out))
  )
  (reverse out)
)

(defun brx-reset-group-fields (groupid / rec out h)
  (setq rec (brx-grouprec-get-real groupid))
  (setq out nil)
  (if rec
    (foreach h (cdr (assoc 'MEMBERS rec))
      (setq out (append out (brx-reset-object-fieldstates h)))
    )
  )
  out
)

(defun brx-reset-table-fields (tableHandle /)
  (brx-reset-object-fieldstates tableHandle)
)


;;; ============================================================
;;; Step v10.3 - recovery helpers driven by group diagnostics
;;; ============================================================

(defun brx-recover-group-master (groupid / newm)
  (setq newm (brx-repair-missing-master groupid))
  (if newm
    (brx-log-info "RECOVER-MASTER" "Recovered missing master" (list (cons 'GROUPID groupid) (cons 'MASTER newm)))
    (brx-log-error "RECOVER-MASTER" "Failed to recover master" (list (cons 'GROUPID groupid)))
  )
  newm
)

(defun brx-recover-group-members (groupid / ok)
  (setq ok (brx-repair-orphan-members groupid))
  (if ok
    (brx-log-info "RECOVER-MEMBERS" "Recovered orphan member links" (list (cons 'GROUPID groupid)))
    (brx-log-error "RECOVER-MEMBERS" "Failed member recovery" (list (cons 'GROUPID groupid)))
  )
  ok
)

(defun brx-recover-group-fields (groupid / out)
  (setq out (brx-reset-group-fields groupid))
  (brx-log-info "RECOVER-FIELDS" "Reset group field states" (list (cons 'GROUPID groupid) (cons 'FIELDS out)))
  out
)


;;; ============================================================
;;; Step v10.4 - table recovery and resync commands
;;; ============================================================

(defun brx-recover-table-cache (tableE range / out)
  (setq out (brx-sync-table-range-real tableE range "DISPLAY"))
  (brx-log-info "RECOVER-TABLE" "Resynced table cache" (list (cons 'TABLEHANDLE (brx-handle-of tableE)) (cons 'COUNT (length out))))
  out
)

(defun brx-recover-table-fields-real (tableE addr fieldid / st)
  (setq st (brx-table-fieldstate-refresh-excel tableE addr fieldid))
  (brx-log-info "RECOVER-TABLE-FIELD" "Refreshed table field state" (list (cons 'TABLEHANDLE (brx-handle-of tableE)) (cons 'CELLADDR addr) (cons 'FIELDID fieldid)))
  st
)

(defun c:BR-TABLE-RECOVER ( / e rng out)
  (setq e (car (entsel "\nPick TABLE: ")))
  (if (and e (brx-table-ename-p e))
    (progn
      (setq rng (getstring T "\nRange (A1:B3): "))
      (setq out (brx-recover-table-cache e rng))
      (prompt (strcat "\nRecovered cells: " (itoa (length out))))
    )
    (prompt "\nSelected object is not TABLE."))
  (princ)
)


;;; ============================================================
;;; Step v10.5 - group fix engine
;;; ============================================================

(defun brx-fix-group-from-diag (groupid / errs kinds out)
  (setq errs (brx-validate-group-strict groupid))
  (setq kinds (mapcar 'strcase (brx-diag-group-fixes-needed (list (cons 'GROUPID groupid) (cons 'ERRORS errs)))))
  (setq out nil)
  (if (member "MASTER" kinds) (setq out (cons (cons 'MASTER (brx-recover-group-master groupid)) out)))
  (if (member "MEMBER" kinds) (setq out (cons (cons 'MEMBER (brx-recover-group-members groupid)) out)))
  (if (or (member "FIELD" kinds) (member "COPY" kinds)) (setq out (cons (cons 'FIELDS (brx-recover-group-fields groupid)) out)))
  (if (or errs kinds) (setq out (cons (cons 'RELINK (brx-run-relink-pipeline groupid)) out)))
  (setq errs (brx-validate-group-strict groupid))
  (if errs
    (brx-quarantine-group groupid errs)
    (brx-mark-group-state groupid "ACTIVE" "NORMAL")
  )
  (reverse out)
)


;;; ============================================================
;;; Step v10.6 - batch fix orchestrators
;;; ============================================================

(defun brx-fix-all-groups ( / gids out gid)
  (setq gids (brx-list-groupids-real))
  (setq out nil)
  (foreach gid gids
    (setq out (cons (cons gid (brx-fix-group-from-diag gid)) out))
  )
  (reverse out)
)

(defun brx-fix-report-summary (rows / ok bad r)
  (setq ok 0 bad 0)
  (foreach r rows
    (if (null (brx-validate-group-strict (car r)))
      (setq ok (1+ ok))
      (setq bad (1+ bad))
    )
  )
  (list (cons 'FIXED ok) (cons 'REMAIN bad) (cons 'TOTAL (+ ok bad)))
)


;;; ============================================================
;;; Step v10.7 - public fix and recover commands
;;; ============================================================

(defun c:BR-FIX ( / gid out)
  (setq gid (getstring T "\nGROUPID: "))
  (setq out (brx-fix-group-from-diag gid))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

(defun c:BR-RECOVER ( / gid out)
  (setq gid (getstring T "\nGROUPID: "))
  (setq out (list
    (cons 'MASTER (brx-recover-group-master gid))
    (cons 'MEMBERS (brx-recover-group-members gid))
    (cons 'FIELDS (brx-recover-group-fields gid))
    (cons 'RELINK (brx-run-relink-pipeline gid))
  ))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

(defun c:BR-DIAG-FIX ( / out)
  (setq out (brx-fix-all-groups))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)


;;; ============================================================
;;; Step v10.8 - repair report export
;;; ============================================================

(defun brx-fix-report-md-lines (rows / sum)
  (setq sum (brx-fix-report-summary rows))
  (list
    "# BLK_REACTOR Repair Report"
    ""
    (strcat "- Fixed: " (itoa (cdr (assoc 'FIXED sum))))
    (strcat "- Remain: " (itoa (cdr (assoc 'REMAIN sum))))
    (strcat "- Total: " (itoa (cdr (assoc 'TOTAL sum))))
    ""
    (vl-princ-to-string rows)
  )
)

(defun brx-fix-report-csv-lines (rows / lines r)
  (setq lines (list "GROUPID,POSTVALIDATEPASS"))
  (foreach r rows
    (setq lines (append lines (list (strcat (vl-princ-to-string (car r)) "," (if (null (brx-validate-group-strict (car r))) "TRUE" "FALSE")))))
  )
  lines
)

(defun brx-fix-export-stub (basePath / rows md csv txt)
  (setq rows (brx-fix-all-groups))
  (setq md (strcat basePath ".md"))
  (setq csv (strcat basePath ".csv"))
  (setq txt (strcat basePath ".txt"))
  (brx-write-lines-file md (brx-fix-report-md-lines rows))
  (brx-write-lines-file csv (brx-fix-report-csv-lines rows))
  (brx-write-lines-file txt (list (vl-princ-to-string rows)))
  (list (cons 'MD md) (cons 'CSV csv) (cons 'TXT txt))
)


;;; ============================================================
;;; Step v10.9 - fix tests and scenario integration
;;; ============================================================

(defun brx-run-fix-tests ( / gid out rows)
  (setq *brx-test-results* nil)
  (setq gid (brx-fixture-group-basic))
  (brx-mark-group-state gid "UNRESOLVED" "UNRESOLVED")
  (setq out (brx-fix-group-from-diag gid))
  (brx-assert-true "fix-command-returned" (listp out))
  (setq rows (list (cons gid out)))
  (brx-assert-true "fix-summary-total" (> (cdr (assoc 'TOTAL (brx-fix-report-summary rows))) 0))
  (brx-test-summary)
)

(defun brx-scenario-run-fix-local ( / gid out)
  (setq gid (brx-fixture-group-basic))
  (brx-mark-group-state gid "UNRESOLVED" "UNRESOLVED")
  (setq out (brx-fix-group-from-diag gid))
  (list (cons 'PASS T) (cons 'ACTIONCOUNT (length out)))
)

(defun brx-scenario-bootstrap-fixplus ( /)
  (brx-scenario-bootstrap-diagplus)
  (brx-scenario-register (brx-scenario-make "SCN-007" "diag fix" "FIX" 'brx-fixture-group-basic 'brx-scenario-run-fix-local '((PASS . T))))
  (brx-scenario-list)
)


;;; ============================================================
;;; Step v11.0 - public repair selftests and exported fix artifacts
;;; ============================================================



(defun c:BR-FIX-EXPORT ( / out)
  (setq out (brx-fix-export-stub "output/brx_fix_report"))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

(defun c:BR-RECOVER-TABLE-FIELD ( / e addr fid out)
  (setq e (car (entsel "\nPick TABLE: ")))
  (if (and e (brx-table-ename-p e))
    (progn
      (setq addr (getstring T "\nCell addr (A1): "))
      (setq fid (getstring T "\nFIELDID: "))
      (setq out (brx-recover-table-fields-real e addr fid))
      (prompt (strcat "\n" (vl-princ-to-string out)))
    )
    (prompt "\nSelected object is not TABLE."))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_Fix_v11_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Install_v12_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Install_v12_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================










;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================










;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================








;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================






;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================








;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================






;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================








;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================






;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================






;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================






;;; ============================================================
;;; Step v9.1 - table field state records and mode helpers
;;; ============================================================










;;; ============================================================
;;; Step v9.2 - real table field sync for FIELDNATIVE and FIELDEXCEL
;;; ============================================================








;;; ============================================================
;;; Step v9.3 - table field reverse writeback bridge
;;; ============================================================




;;; ============================================================
;;; Step v9.4 - field diagnostics for groups and tables
;;; ============================================================








;;; ============================================================
;;; Step v9.5 - global diagnostics aggregators
;;; ============================================================








;;; ============================================================
;;; Step v9.6 - unified BR-DIAG report model
;;; ============================================================






;;; ============================================================
;;; Step v9.7 - diagnostic export writers
;;; ============================================================








;;; ============================================================
;;; Step v9.8 - table field tests and diagnostics tests
;;; ============================================================




;;; ============================================================
;;; Step v9.9 - scenario and selftest integration for diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.0 - public BR-DIAG commands and exported report artifacts
;;; ============================================================










;;; ============================================================
;;; Step v10.1 - diagnostic issue classifiers and routing
;;; ============================================================






;;; ============================================================
;;; Step v10.2 - field reset and table field reset helpers
;;; ============================================================








;;; ============================================================
;;; Step v10.3 - recovery helpers driven by group diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.4 - table recovery and resync commands
;;; ============================================================








;;; ============================================================
;;; Step v10.5 - group fix engine
;;; ============================================================




;;; ============================================================
;;; Step v10.6 - batch fix orchestrators
;;; ============================================================






;;; ============================================================
;;; Step v10.7 - public fix and recover commands
;;; ============================================================








;;; ============================================================
;;; Step v10.8 - repair report export
;;; ============================================================








;;; ============================================================
;;; Step v10.9 - fix tests and scenario integration
;;; ============================================================








;;; ============================================================
;;; Step v11.0 - public repair selftests and exported fix artifacts
;;; ============================================================








;;; ============================================================
;;; Step v11.1 - BRCODE state accessors and normalization
;;; ============================================================

(setq *brx-code-meta* nil)

(defun brx-code-meta-put (key val /)
  (setq *brx-code-meta* (cons (cons (strcase (vl-princ-to-string key) T) val)
                              (vl-remove-if '(lambda (x) (= (car x) (strcase (vl-princ-to-string key) T))) *brx-code-meta*)))
  val
)

(defun brx-code-meta-get (key /)
  (cdr (assoc (strcase (vl-princ-to-string key) T) *brx-code-meta*))
)

(defun brx-code-state-normalize (s / v)
  (setq v (strcase (vl-princ-to-string s) T))
  (cond
    ((member v '("INSTALLED" "EMBEDDEDONLY" "OUTDATED" "ERROR")) v)
    ((member v '("AVAILABLE" "MISSING" "BLOCKEDBYSECURITY" "ERROR")) v)
    (T "UNKNOWN")
  )
)


;;; ============================================================
;;; Step v11.2 - embed metadata writers and hash placeholders
;;; ============================================================

(defun brx-code-hash-stub (text /)
  (strcat "HASH-" (itoa (strlen (vl-princ-to-string text))))
)

(defun brx-code-partition-stub (text /)
  (list (cons 'COUNT 1) (cons 'PART001 (vl-princ-to-string text)))
)

(defun brx-code-embed-record (codeText version buildDate / parts hash)
  (setq parts (brx-code-partition-stub codeText))
  (setq hash (brx-code-hash-stub codeText))
  (brx-code-meta-put 'BRCODEVERSION version)
  (brx-code-meta-put 'BRCODEHASH hash)
  (brx-code-meta-put 'BRCODEBUILDDATE buildDate)
  (brx-code-meta-put 'BRCODEPARTCOUNT (cdr (assoc 'COUNT parts)))
  (brx-code-meta-put 'BRCODEPART001 (cdr (assoc 'PART001 parts)))
  (brx-code-meta-put 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
  (brx-code-meta-put 'BRCODELOADERSTATE "MISSING")
  (list (cons 'VERSION version) (cons 'HASH hash) parts)
)


;;; ============================================================
;;; Step v11.3 - loader health and security policy checks
;;; ============================================================

(defun brx-loader-security-blocked-p ( / s)
  (setq s (brx-loader-health-report))
  (if (wcmatch (strcase (vl-princ-to-string s) T) "*BLOCKEDBYSECURITY*") T nil)
)

(defun brx-loader-available-p ( / s)
  (setq s (brx-loader-health-report))
  (if (wcmatch (strcase (vl-princ-to-string s) T) "*AVAILABLE*") T nil)
)

(defun brx-code-sync-loaderstate ( /)
  (cond
    ((brx-loader-security-blocked-p) (brx-code-meta-put 'BRCODELOADERSTATE "BLOCKEDBYSECURITY"))
    ((brx-loader-available-p) (brx-code-meta-put 'BRCODELOADERSTATE "AVAILABLE"))
    (T (brx-code-meta-put 'BRCODELOADERSTATE "MISSING"))
  )
)


;;; ============================================================
;;; Step v11.4 - force install and embed restore primitives
;;; ============================================================

(defun brx-force-install-stub ( / ls is)
  (setq ls (or (brx-code-sync-loaderstate) (brx-code-meta-get 'BRCODELOADERSTATE)))
  (setq is (brx-code-meta-get 'BRCODEINSTALLSTATE))
  (cond
    ((= ls "BLOCKEDBYSECURITY") (brx-rv-err "SECURITY" "Loader blocked by security" nil))
    ((= ls "AVAILABLE")
      (progn
        (brx-code-meta-put 'BRCODEINSTALLSTATE "INSTALLED")
        (brx-rv-ok "INSTALLED" "STATE" nil)
      )
    )
    ((= is "EMBEDDEDONLY")
      (brx-rv-ok "EMBEDDEDONLY" "STATE" nil)
    )
    (T (brx-rv-err "INSTALL" "No loader available for install" nil))
  )
)

(defun brx-embed-restore-stub ( / part)
  (setq part (brx-code-meta-get 'BRCODEPART001))
  (if part
    (progn
      (brx-code-meta-put 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
      (brx-rv-ok part "CODE" nil)
    )
    (brx-rv-err "RESTORE" "No embedded code payload" nil)
  )
)


;;; ============================================================
;;; Step v11.5 - install recovery pipeline for unresolved DWG state
;;; ============================================================

(defun brx-install-recover-pipeline ( / rv)
  (setq rv (brx-force-install-stub))
  (if (brx-err-p rv)
    (progn
      (setq rv (brx-embed-restore-stub))
      (if (brx-err-p rv)
        (progn
          (brx-code-meta-put 'BRCODEINSTALLSTATE "ERROR")
          rv
        )
        (progn
          (brx-code-meta-put 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
          rv
        )
      )
    )
    rv
  )
)

(defun brx-ensure-code-ready ( / rv)
  (setq rv (brx-install-recover-pipeline))
  (if (brx-err-p rv)
    (brx-log-error "CODE-READY" "BLKREACTOR code not ready" (list (cons 'STATE *brx-code-meta*)))
    (brx-log-info "CODE-READY" "BLKREACTOR code ready" (list (cons 'STATE *brx-code-meta*)))
  )
  rv
)


;;; ============================================================
;;; Step v11.6 - selective fix policy by error kind and loader state
;;; ============================================================

(defun brx-fix-policy-for-kind (kind / ls)
  (setq ls (or (brx-code-meta-get 'BRCODELOADERSTATE) (brx-code-sync-loaderstate)))
  (cond
    ((= ls "BLOCKEDBYSECURITY") '(:allow-local-fix T :allow-install nil :allow-embed T))
    ((= (strcase (vl-princ-to-string kind) T) "COPY") '(:allow-local-fix T :allow-install T :allow-embed T))
    ((= (strcase (vl-princ-to-string kind) T) "FIELD") '(:allow-local-fix T :allow-install T :allow-embed T))
    (T '(:allow-local-fix T :allow-install T :allow-embed T))
  )
)

(defun brx-policy-allows-p (plist key / a)
  (setq a (member key plist))
  (if a (cadr a) nil)
)


;;; ============================================================
;;; Step v11.7 - policy-aware repair orchestration
;;; ============================================================

(defun brx-fix-group-from-diag-policy (groupid / errs kinds kind pol out)
  (setq errs (brx-validate-group-strict groupid))
  (setq kinds (brx-diag-group-fixes-needed (list (cons 'GROUPID groupid) (cons 'ERRORS errs))))
  (setq out nil)
  (foreach kind kinds
    (setq pol (brx-fix-policy-for-kind kind))
    (if (brx-policy-allows-p pol :allow-install) (brx-ensure-code-ready))
    (if (brx-policy-allows-p pol :allow-local-fix)
      (setq out (append out (brx-fix-group-from-diag groupid)))
    )
    (if (and (not (brx-policy-allows-p pol :allow-install)) (brx-policy-allows-p pol :allow-embed))
      (setq out (cons (cons 'EMBEDRESTORE (brx-embed-restore-stub)) out))
    )
  )
  out
)


;;; ============================================================
;;; Step v11.8 - public install and embed commands
;;; ============================================================

(defun c:BR-FORCE-INSTALL ( / rv)
  (setq rv (brx-force-install-stub))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-EMBED ( / rv)
  (setq rv (brx-code-embed-record ";;; BLKREACTOR embedded code placeholder" "11.8" "2026-04-12T20:48:00"))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-EMBED-RESTORE ( / rv)
  (setq rv (brx-embed-restore-stub))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)


;;; ============================================================
;;; Step v11.9 - install and security diagnostics export
;;; ============================================================

(defun brx-code-diagnostics-report ( /)
  (list
    (cons 'BRCODEVERSION (brx-code-meta-get 'BRCODEVERSION))
    (cons 'BRCODEHASH (brx-code-meta-get 'BRCODEHASH))
    (cons 'BRCODEINSTALLSTATE (brx-code-meta-get 'BRCODEINSTALLSTATE))
    (cons 'BRCODELOADERSTATE (brx-code-meta-get 'BRCODELOADERSTATE))
    (cons 'ERRORLOG (reverse *brx-error-log*))
  )
)

(defun brx-code-export-stub (basePath / rep md txt)
  (setq rep (brx-code-diagnostics-report))
  (setq md (strcat basePath ".md"))
  (setq txt (strcat basePath ".txt"))
  (brx-write-lines-file md (list "# BLK_REACTOR Code Install Report" "" (vl-princ-to-string rep)))
  (brx-write-lines-file txt (list (vl-princ-to-string rep)))
  (list (cons 'MD md) (cons 'TXT txt))
)


;;; ============================================================
;;; Step v12.0 - selftests and orchestrated recovery commands
;;; ============================================================

(defun brx-run-install-tests ( / rv rep)
  (setq *brx-test-results* nil)
  (brx-code-embed-record ";; EMBED" "12.0" "2026-04-12T20:48:00")
  (setq rv (brx-install-recover-pipeline))
  (brx-assert-true "install-recover-returned" (not (null rv)))
  (setq rep (brx-code-diagnostics-report))
  (brx-assert-true "code-report-present" (not (null (assoc 'BRCODEINSTALLSTATE rep))))
  (brx-test-summary)
)



(defun c:BR-RECOVER-ALL ( /)
  (prompt (strcat "\n" (vl-princ-to-string (list
    (cons 'CODE (brx-ensure-code-ready))
    (cons 'FIXES (brx-fix-all-groups))
  ))))
  (princ)
)

(defun c:BR-CODE-EXPORT ( / out)
  (setq out (brx-code-export-stub "output/brx_code_report"))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_Install_v12_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_NOD_v13_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_NOD_v13_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================










;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================










;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================








;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================






;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================








;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================






;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================








;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================






;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================






;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================






;;; ============================================================
;;; Step v9.1 - table field state records and mode helpers
;;; ============================================================










;;; ============================================================
;;; Step v9.2 - real table field sync for FIELDNATIVE and FIELDEXCEL
;;; ============================================================








;;; ============================================================
;;; Step v9.3 - table field reverse writeback bridge
;;; ============================================================




;;; ============================================================
;;; Step v9.4 - field diagnostics for groups and tables
;;; ============================================================








;;; ============================================================
;;; Step v9.5 - global diagnostics aggregators
;;; ============================================================








;;; ============================================================
;;; Step v9.6 - unified BR-DIAG report model
;;; ============================================================






;;; ============================================================
;;; Step v9.7 - diagnostic export writers
;;; ============================================================








;;; ============================================================
;;; Step v9.8 - table field tests and diagnostics tests
;;; ============================================================




;;; ============================================================
;;; Step v9.9 - scenario and selftest integration for diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.0 - public BR-DIAG commands and exported report artifacts
;;; ============================================================










;;; ============================================================
;;; Step v10.1 - diagnostic issue classifiers and routing
;;; ============================================================






;;; ============================================================
;;; Step v10.2 - field reset and table field reset helpers
;;; ============================================================








;;; ============================================================
;;; Step v10.3 - recovery helpers driven by group diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.4 - table recovery and resync commands
;;; ============================================================








;;; ============================================================
;;; Step v10.5 - group fix engine
;;; ============================================================




;;; ============================================================
;;; Step v10.6 - batch fix orchestrators
;;; ============================================================






;;; ============================================================
;;; Step v10.7 - public fix and recover commands
;;; ============================================================








;;; ============================================================
;;; Step v10.8 - repair report export
;;; ============================================================








;;; ============================================================
;;; Step v10.9 - fix tests and scenario integration
;;; ============================================================








;;; ============================================================
;;; Step v11.0 - public repair selftests and exported fix artifacts
;;; ============================================================








;;; ============================================================
;;; Step v11.1 - BRCODE state accessors and normalization
;;; ============================================================

(setq *brx-code-meta* nil)








;;; ============================================================
;;; Step v11.2 - embed metadata writers and hash placeholders
;;; ============================================================








;;; ============================================================
;;; Step v11.3 - loader health and security policy checks
;;; ============================================================








;;; ============================================================
;;; Step v11.4 - force install and embed restore primitives
;;; ============================================================






;;; ============================================================
;;; Step v11.5 - install recovery pipeline for unresolved DWG state
;;; ============================================================






;;; ============================================================
;;; Step v11.6 - selective fix policy by error kind and loader state
;;; ============================================================






;;; ============================================================
;;; Step v11.7 - policy-aware repair orchestration
;;; ============================================================




;;; ============================================================
;;; Step v11.8 - public install and embed commands
;;; ============================================================








;;; ============================================================
;;; Step v11.9 - install and security diagnostics export
;;; ============================================================






;;; ============================================================
;;; Step v12.0 - selftests and orchestrated recovery commands
;;; ============================================================










;;; ============================================================
;;; Step v12.1 - NOD and XRECORD in-memory bridge
;;; ============================================================

(setq *brx-nod-store* nil)

(defun brx-nod-record-put (dict key val / dk rec)
  (setq dk (strcat (strcase (vl-princ-to-string dict) T) "::" (strcase (vl-princ-to-string key) T)))
  (setq *brx-nod-store* (cons (cons dk val) (vl-remove-if '(lambda (x) (= (car x) dk)) *brx-nod-store*)))
  val
)

(defun brx-nod-record-get (dict key /)
  (cdr (assoc (strcat (strcase (vl-princ-to-string dict) T) "::" (strcase (vl-princ-to-string key) T)) *brx-nod-store*))
)

(defun brx-xrecord-write-stub (dict key pairs /)
  (brx-nod-record-put dict key pairs)
)

(defun brx-xrecord-read-stub (dict key /)
  (brx-nod-record-get dict key)
)


;;; ============================================================
;;; Step v12.2 - BRCODE NOD read write helpers
;;; ============================================================

(defun brx-brcode-write-meta-stub ( /)
  (foreach k '(BRCODEINFO BRCODEVERSION BRCODEHASH BRCODEPARTCOUNT BRCODEPART001 BRCODEBUILDDATE BRCODEINSTALLSTATE BRCODELOADERSTATE)
    (brx-xrecord-write-stub "BRCODE" k (list (cons k (brx-code-meta-get k))))
  )
)

(defun brx-brcode-read-meta-stub ( / k v)
  (foreach k '(BRCODEINFO BRCODEVERSION BRCODEHASH BRCODEPARTCOUNT BRCODEPART001 BRCODEBUILDDATE BRCODEINSTALLSTATE BRCODELOADERSTATE)
    (setq v (brx-xrecord-read-stub "BRCODE" k))
    (if v (brx-code-meta-put k (cdr (assoc k v))))
  )
  *brx-code-meta*
)


;;; ============================================================
;;; Step v12.3 - UTF-8 BOM chunking stubs for BRCODEPART001..N
;;; ============================================================

(defun brx-str-chunk-stub (text maxlen / out i n)
  (setq out nil i 1 n (strlen text))
  (while (<= i n)
    (setq out (cons (substr text i (min maxlen (1+ (- n i)))) out))
    (setq i (+ i maxlen))
  )
  (reverse out)
)

(defun brx-brcode-parts-write-stub (text / parts idx)
  (setq parts (brx-str-chunk-stub (vl-princ-to-string text) 120))
  (brx-code-meta-put 'BRCODEPARTCOUNT (length parts))
  (setq idx 1)
  (foreach p parts
    (brx-code-meta-put (read (strcat "BRCODEPART" (substr (strcat "00" (itoa idx)) (- (strlen (strcat "00" (itoa idx))) 2) 3))) p)
    (brx-xrecord-write-stub "BRCODE" (read (strcat "BRCODEPART" (substr (strcat "00" (itoa idx)) (- (strlen (strcat "00" (itoa idx))) 2) 3))) (list (cons 'TEXT p)))
    (setq idx (1+ idx))
  )
  parts
)


;;; ============================================================
;;; Step v12.4 - payload restore and hash verification stubs
;;; ============================================================

(defun brx-brcode-restore-payload-stub ( / cnt idx out rec key)
  (setq cnt (atoi (vl-princ-to-string (or (brx-code-meta-get 'BRCODEPARTCOUNT) 0))))
  (setq idx 1 out "")
  (while (<= idx cnt)
    (setq key (read (strcat "BRCODEPART" (substr (strcat "00" (itoa idx)) (- (strlen (strcat "00" (itoa idx))) 2) 3))))
    (setq rec (brx-xrecord-read-stub "BRCODE" key))
    (if rec (setq out (strcat out (cdr (assoc 'TEXT rec)))))
    (setq idx (1+ idx))
  )
  out
)

(defun brx-brcode-verify-hash-stub (payload / h)
  (setq h (brx-code-hash-stub payload))
  (if (= h (brx-code-meta-get 'BRCODEHASH)) T nil)
)


;;; ============================================================
;;; Step v12.5 - NOD-backed embed and restore pipeline
;;; ============================================================

(defun brx-code-embed-nod-stub (codeText version buildDate / hash)
  (brx-code-meta-put 'BRCODEINFO "BLKREACTOR")
  (brx-code-meta-put 'BRCODEVERSION version)
  (brx-code-meta-put 'BRCODEBUILDDATE buildDate)
  (setq hash (brx-code-hash-stub codeText))
  (brx-code-meta-put 'BRCODEHASH hash)
  (brx-brcode-parts-write-stub codeText)
  (brx-code-meta-put 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
  (brx-brcode-write-meta-stub)
  (brx-rv-ok hash "HASH" nil)
)

(defun brx-code-restore-nod-stub ( / payload)
  (brx-brcode-read-meta-stub)
  (setq payload (brx-brcode-restore-payload-stub))
  (if (brx-brcode-verify-hash-stub payload)
    (brx-rv-ok payload "CODE" nil)
    (brx-rv-err "HASH" "Embedded payload hash mismatch" nil)
  )
)


;;; ============================================================
;;; Step v12.6 - live NOD bridge wrappers and fallback
;;; ============================================================

(defun brx-nod-dict-get-live-stub (name /)
  (brx-xrecord-read-stub "NOD" name)
)

(defun brx-nod-dict-put-live-stub (name val /)
  (brx-xrecord-write-stub "NOD" name val)
)

(defun brx-brcode-installstate-from-nod ( /)
  (or (brx-code-meta-get 'BRCODEINSTALLSTATE)
      (cdr (assoc 'BRCODEINSTALLSTATE (brx-xrecord-read-stub "BRCODE" 'BRCODEINSTALLSTATE))))
)

(defun brx-brcode-loaderstate-from-nod ( /)
  (or (brx-code-meta-get 'BRCODELOADERSTATE)
      (cdr (assoc 'BRCODELOADERSTATE (brx-xrecord-read-stub "BRCODE" 'BRCODELOADERSTATE))))
)


;;; ============================================================
;;; Step v12.7 - commands for NOD embed restore verify
;;; ============================================================

(defun c:BR-NOD-EMBED ( / rv)
  (setq rv (brx-code-embed-nod-stub ";;; BLKREACTOR NOD payload" "12.7" "2026-04-12T20:49:00"))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-NOD-RESTORE ( / rv)
  (setq rv (brx-code-restore-nod-stub))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-NOD-VERIFY ( / p ok)
  (setq p (brx-brcode-restore-payload-stub))
  (setq ok (brx-brcode-verify-hash-stub p))
  (prompt (strcat "\n" (vl-princ-to-string ok)))
  (princ)
)


;;; ============================================================
;;; Step v12.8 - NOD diagnostics export and summary
;;; ============================================================

(defun brx-nod-diagnostics-report ( /)
  (list
    (cons 'BRCODEINFO (brx-code-meta-get 'BRCODEINFO))
    (cons 'BRCODEVERSION (brx-code-meta-get 'BRCODEVERSION))
    (cons 'BRCODEHASH (brx-code-meta-get 'BRCODEHASH))
    (cons 'BRCODEPARTCOUNT (brx-code-meta-get 'BRCODEPARTCOUNT))
    (cons 'BRCODEINSTALLSTATE (brx-brcode-installstate-from-nod))
    (cons 'BRCODELOADERSTATE (brx-brcode-loaderstate-from-nod))
  )
)

(defun brx-nod-export-stub (basePath / rep md txt)
  (setq rep (brx-nod-diagnostics-report))
  (setq md (strcat basePath ".md"))
  (setq txt (strcat basePath ".txt"))
  (brx-write-lines-file md (list "# BLK_REACTOR NOD Report" "" (vl-princ-to-string rep)))
  (brx-write-lines-file txt (list (vl-princ-to-string rep)))
  (list (cons 'MD md) (cons 'TXT txt))
)


;;; ============================================================
;;; Step v12.9 - NOD selftests and scenario integration
;;; ============================================================

(defun brx-run-nod-tests ( / rv p rep)
  (setq *brx-test-results* nil)
  (setq *brx-nod-store* nil)
  (setq rv (brx-code-embed-nod-stub ";; NOD TEST PAYLOAD" "12.9" "2026-04-12T20:49:00"))
  (brx-assert-false "nod-embed-no-error" (brx-err-p rv))
  (setq p (brx-brcode-restore-payload-stub))
  (brx-assert-true "nod-payload-nonempty" (> (strlen p) 0))
  (brx-assert-true "nod-hash-ok" (brx-brcode-verify-hash-stub p))
  (setq rep (brx-nod-diagnostics-report))
  (brx-assert-true "nod-report-has-version" (not (null (assoc 'BRCODEVERSION rep))))
  (brx-test-summary)
)




;;; ============================================================
;;; Step v13.0 - unified recover all plus NOD export
;;; ============================================================

(defun c:BR-RECOVER-ALL-PLUS ( / out)
  (setq out (list
    (cons 'CODE (brx-ensure-code-ready))
    (cons 'NODRESTORE (brx-code-restore-nod-stub))
    (cons 'FIXES (brx-fix-all-groups))
  ))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

(defun c:BR-NOD-EXPORT ( / out)
  (setq out (brx-nod-export-stub "output/brx_nod_report"))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_NOD_v13_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_RealAPI_v14_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_RealAPI_v14_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================










;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================










;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================








;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================






;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================








;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================






;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================








;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================






;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================






;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================






;;; ============================================================
;;; Step v9.1 - table field state records and mode helpers
;;; ============================================================










;;; ============================================================
;;; Step v9.2 - real table field sync for FIELDNATIVE and FIELDEXCEL
;;; ============================================================








;;; ============================================================
;;; Step v9.3 - table field reverse writeback bridge
;;; ============================================================




;;; ============================================================
;;; Step v9.4 - field diagnostics for groups and tables
;;; ============================================================








;;; ============================================================
;;; Step v9.5 - global diagnostics aggregators
;;; ============================================================








;;; ============================================================
;;; Step v9.6 - unified BR-DIAG report model
;;; ============================================================






;;; ============================================================
;;; Step v9.7 - diagnostic export writers
;;; ============================================================








;;; ============================================================
;;; Step v9.8 - table field tests and diagnostics tests
;;; ============================================================




;;; ============================================================
;;; Step v9.9 - scenario and selftest integration for diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.0 - public BR-DIAG commands and exported report artifacts
;;; ============================================================










;;; ============================================================
;;; Step v10.1 - diagnostic issue classifiers and routing
;;; ============================================================






;;; ============================================================
;;; Step v10.2 - field reset and table field reset helpers
;;; ============================================================








;;; ============================================================
;;; Step v10.3 - recovery helpers driven by group diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.4 - table recovery and resync commands
;;; ============================================================








;;; ============================================================
;;; Step v10.5 - group fix engine
;;; ============================================================




;;; ============================================================
;;; Step v10.6 - batch fix orchestrators
;;; ============================================================






;;; ============================================================
;;; Step v10.7 - public fix and recover commands
;;; ============================================================








;;; ============================================================
;;; Step v10.8 - repair report export
;;; ============================================================








;;; ============================================================
;;; Step v10.9 - fix tests and scenario integration
;;; ============================================================








;;; ============================================================
;;; Step v11.0 - public repair selftests and exported fix artifacts
;;; ============================================================








;;; ============================================================
;;; Step v11.1 - BRCODE state accessors and normalization
;;; ============================================================

(setq *brx-code-meta* nil)








;;; ============================================================
;;; Step v11.2 - embed metadata writers and hash placeholders
;;; ============================================================








;;; ============================================================
;;; Step v11.3 - loader health and security policy checks
;;; ============================================================








;;; ============================================================
;;; Step v11.4 - force install and embed restore primitives
;;; ============================================================






;;; ============================================================
;;; Step v11.5 - install recovery pipeline for unresolved DWG state
;;; ============================================================






;;; ============================================================
;;; Step v11.6 - selective fix policy by error kind and loader state
;;; ============================================================






;;; ============================================================
;;; Step v11.7 - policy-aware repair orchestration
;;; ============================================================




;;; ============================================================
;;; Step v11.8 - public install and embed commands
;;; ============================================================








;;; ============================================================
;;; Step v11.9 - install and security diagnostics export
;;; ============================================================






;;; ============================================================
;;; Step v12.0 - selftests and orchestrated recovery commands
;;; ============================================================










;;; ============================================================
;;; Step v12.1 - NOD and XRECORD in-memory bridge
;;; ============================================================

(setq *brx-nod-store* nil)










;;; ============================================================
;;; Step v12.2 - BRCODE NOD read write helpers
;;; ============================================================






;;; ============================================================
;;; Step v12.3 - UTF-8 BOM chunking stubs for BRCODEPART001..N
;;; ============================================================






;;; ============================================================
;;; Step v12.4 - payload restore and hash verification stubs
;;; ============================================================






;;; ============================================================
;;; Step v12.5 - NOD-backed embed and restore pipeline
;;; ============================================================






;;; ============================================================
;;; Step v12.6 - live NOD bridge wrappers and fallback
;;; ============================================================










;;; ============================================================
;;; Step v12.7 - commands for NOD embed restore verify
;;; ============================================================








;;; ============================================================
;;; Step v12.8 - NOD diagnostics export and summary
;;; ============================================================






;;; ============================================================
;;; Step v12.9 - NOD selftests and scenario integration
;;; ============================================================






;;; ============================================================
;;; Step v13.0 - unified recover all plus NOD export
;;; ============================================================






;;; ============================================================
;;; Step v13.1 - real dictionary lookup and creation wrappers
;;; ============================================================

(defun brx-nod-root-safe ( / r)
  (setq r (vl-catch-all-apply 'namedobjdict '()))
  (if (vl-catch-all-error-p r) nil r)
)

(defun brx-dictsearch-safe (dict key / r)
  (if dict
    (progn
      (setq r (vl-catch-all-apply 'dictsearch (list dict (vl-princ-to-string key))))
      (if (vl-catch-all-error-p r) nil r)
    )
    nil
  )
)

(defun brx-dictadd-safe (dict key en / r)
  (if (and dict en)
    (progn
      (setq r (vl-catch-all-apply 'dictadd (list dict (vl-princ-to-string key) en)))
      (if (vl-catch-all-error-p r) nil r)
    )
    nil
  )
)

(defun brx-get-or-create-dictionary-real (name / nod hit en)
  (setq nod (brx-nod-root-safe))
  (setq hit (brx-dictsearch-safe nod name))
  (cond
    (hit (cdr (assoc -1 hit)))
    (nod
      (progn
        (setq en (entmakex '((0 . "DICTIONARY") (100 . "AcDbDictionary"))))
        (if en (brx-dictadd-safe nod name en) nil)
        en
      )
    )
    (T nil)
  )
)


;;; ============================================================
;;; Step v13.2 - real XRECORD creation and read wrappers
;;; ============================================================

(defun brx-entmakex-safe (elist / r)
  (setq r (vl-catch-all-apply 'entmakex (list elist)))
  (if (vl-catch-all-error-p r) nil r)
)

(defun brx-entget-safe2 (en / r)
  (if en
    (progn
      (setq r (vl-catch-all-apply 'entget (list en)))
      (if (vl-catch-all-error-p r) nil r)
    )
    nil
  )
)

(defun brx-xrecord-make-real (pairs / el)
  (setq el (append (list '(0 . "XRECORD") '(100 . "AcDbXrecord")) pairs))
  (brx-entmakex-safe el)
)

(defun brx-xrecord-read-real (dictName key / dict hit en)
  (setq dict (brx-get-or-create-dictionary-real dictName))
  (setq hit (brx-dictsearch-safe dict key))
  (if hit (brx-entget-safe2 (cdr (assoc -1 hit))) nil)
)


;;; ============================================================
;;; Step v13.3 - real XRECORD write replace helpers
;;; ============================================================

(defun brx-ename-safe-p (en /)
  (and en (= (type en) 'ENAME))
)

(defun brx-xrecord-write-real (dictName key pairs / dict hit old en)
  (setq dict (brx-get-or-create-dictionary-real dictName))
  (if dict
    (progn
      (setq hit (brx-dictsearch-safe dict key))
      (if hit
        (progn
          (setq old (cdr (assoc -1 hit)))
          (if old (entdel old))
        )
      )
      (setq en (brx-xrecord-make-real pairs))
      (if en (brx-dictadd-safe dict key en) nil)
      en
    )
    nil
  )
)


;;; ============================================================
;;; Step v13.4 - BRCODE meta write to real XRECORD keys
;;; ============================================================

(defun brx-meta->xrec-pairs (key val /)
  (list (cons 1 (vl-princ-to-string val)))
)

(defun brx-brcode-write-meta-real ( / key val)
  (foreach key '(BRCODEINFO BRCODEVERSION BRCODEHASH BRCODEBUILDDATE BRCODEINSTALLSTATE BRCODELOADERSTATE)
    (setq val (brx-code-meta-get key))
    (brx-xrecord-write-real "BRCODE" key (brx-meta->xrec-pairs key val))
  )
  (brx-xrecord-write-real "BRCODE" 'BRCODEPARTCOUNT (list (cons 90 (atoi (vl-princ-to-string (or (brx-code-meta-get 'BRCODEPARTCOUNT) 0))))))
)


;;; ============================================================
;;; Step v13.5 - BRCODE part write and read via real XRECORD keys
;;; ============================================================

(defun brx-brcode-part-key (idx / s)
  (setq s (itoa idx))
  (while (< (strlen s) 3) (setq s (strcat "0" s)))
  (read (strcat "BRCODEPART" s))
)

(defun brx-brcode-parts-write-real (parts / idx key)
  (setq idx 1)
  (foreach p parts
    (setq key (brx-brcode-part-key idx))
    (brx-xrecord-write-real "BRCODE" key (list (cons 1 p)))
    (setq idx (1+ idx))
  )
  (brx-code-meta-put 'BRCODEPARTCOUNT (length parts))
  (brx-xrecord-write-real "BRCODE" 'BRCODEPARTCOUNT (list (cons 90 (length parts))))
)

(defun brx-brcode-parts-read-real ( / idx cnt out rec)
  (setq cnt (atoi (vl-princ-to-string (or (brx-code-meta-get 'BRCODEPARTCOUNT) 0))))
  (setq idx 1 out nil)
  (while (<= idx cnt)
    (setq rec (brx-xrecord-read-real "BRCODE" (brx-brcode-part-key idx)))
    (setq out (cons (cdr (assoc 1 rec)) out))
    (setq idx (1+ idx))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v13.6 - real embed restore bridge on top of XRECORD APIs
;;; ============================================================

(defun brx-code-embed-realapi (codeText version buildDate / parts hash)
  (setq parts (brx-str-chunk-stub (vl-princ-to-string codeText) 120))
  (setq hash (brx-code-hash-stub codeText))
  (brx-code-meta-put 'BRCODEINFO "BLKREACTOR")
  (brx-code-meta-put 'BRCODEVERSION version)
  (brx-code-meta-put 'BRCODEHASH hash)
  (brx-code-meta-put 'BRCODEBUILDDATE buildDate)
  (brx-code-meta-put 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
  (brx-brcode-write-meta-real)
  (brx-brcode-parts-write-real parts)
  (brx-rv-ok hash "HASH" nil)
)

(defun brx-code-restore-realapi ( / parts payload)
  (brx-brcode-read-meta-real)
  (setq parts (brx-brcode-parts-read-real))
  (setq payload (apply 'strcat parts))
  (if (brx-brcode-verify-hash-stub payload)
    (brx-rv-ok payload "CODE" nil)
    (brx-rv-err "HASH" "Real XRECORD payload hash mismatch" nil)
  )
)


;;; ============================================================
;;; Step v13.7 - real meta readback from XRECORDs
;;; ============================================================

(defun brx-brcode-read-meta-real ( / rec)
  (setq rec (brx-xrecord-read-real "BRCODE" 'BRCODEINFO))
  (if rec (brx-code-meta-put 'BRCODEINFO (cdr (assoc 1 rec))))
  (setq rec (brx-xrecord-read-real "BRCODE" 'BRCODEVERSION))
  (if rec (brx-code-meta-put 'BRCODEVERSION (cdr (assoc 1 rec))))
  (setq rec (brx-xrecord-read-real "BRCODE" 'BRCODEHASH))
  (if rec (brx-code-meta-put 'BRCODEHASH (cdr (assoc 1 rec))))
  (setq rec (brx-xrecord-read-real "BRCODE" 'BRCODEBUILDDATE))
  (if rec (brx-code-meta-put 'BRCODEBUILDDATE (cdr (assoc 1 rec))))
  (setq rec (brx-xrecord-read-real "BRCODE" 'BRCODEINSTALLSTATE))
  (if rec (brx-code-meta-put 'BRCODEINSTALLSTATE (cdr (assoc 1 rec))))
  (setq rec (brx-xrecord-read-real "BRCODE" 'BRCODELOADERSTATE))
  (if rec (brx-code-meta-put 'BRCODELOADERSTATE (cdr (assoc 1 rec))))
  (setq rec (brx-xrecord-read-real "BRCODE" 'BRCODEPARTCOUNT))
  (if rec (brx-code-meta-put 'BRCODEPARTCOUNT (cdr (assoc 90 rec))))
  *brx-code-meta*
)


;;; ============================================================
;;; Step v13.8 - public real API commands
;;; ============================================================

(defun c:BR-REALAPI-EMBED ( / rv)
  (setq rv (brx-code-embed-realapi ";;; BLKREACTOR REALAPI PAYLOAD" "13.8" "2026-04-12T20:51:00"))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-REALAPI-RESTORE ( / rv)
  (setq rv (brx-code-restore-realapi))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-REALAPI-SHOW ( / rv)
  (setq rv (brx-brcode-read-meta-real))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)


;;; ============================================================
;;; Step v13.9 - real API diagnostics and selftests
;;; ============================================================

(defun brx-run-realapi-tests ( / rv rep)
  (setq *brx-test-results* nil)
  (setq rv (brx-code-embed-realapi ";; REALAPI TEST PAYLOAD" "13.9" "2026-04-12T20:51:00"))
  (brx-assert-false "realapi-embed-no-error" (brx-err-p rv))
  (setq rv (brx-code-restore-realapi))
  (brx-assert-false "realapi-restore-no-error" (brx-err-p rv))
  (setq rep (brx-brcode-read-meta-real))
  (brx-assert-true "realapi-meta-present" (not (null (assoc 'BRCODEVERSION rep))))
  (brx-test-summary)
)




;;; ============================================================
;;; Step v14.0 - unified NOD real API export
;;; ============================================================

(defun brx-realapi-report ( / rep)
  (setq rep (brx-brcode-read-meta-real))
  (list
    (cons 'META rep)
    (cons 'PARTS (brx-brcode-parts-read-real))
  )
)

(defun c:BR-REALAPI-EXPORT ( / out rep)
  (setq rep (brx-realapi-report))
  (setq out (brx-write-lines-file "output/brx_realapi_report.txt" (list (vl-princ-to-string rep))))
  (prompt (strcat "\n" (vl-princ-to-string rep)))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_RealAPI_v14_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_ByteAPI_v15_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_ByteAPI_v15_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================










;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================










;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================








;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================






;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================








;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================






;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================








;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================






;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================






;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================






;;; ============================================================
;;; Step v9.1 - table field state records and mode helpers
;;; ============================================================










;;; ============================================================
;;; Step v9.2 - real table field sync for FIELDNATIVE and FIELDEXCEL
;;; ============================================================








;;; ============================================================
;;; Step v9.3 - table field reverse writeback bridge
;;; ============================================================




;;; ============================================================
;;; Step v9.4 - field diagnostics for groups and tables
;;; ============================================================








;;; ============================================================
;;; Step v9.5 - global diagnostics aggregators
;;; ============================================================








;;; ============================================================
;;; Step v9.6 - unified BR-DIAG report model
;;; ============================================================






;;; ============================================================
;;; Step v9.7 - diagnostic export writers
;;; ============================================================








;;; ============================================================
;;; Step v9.8 - table field tests and diagnostics tests
;;; ============================================================




;;; ============================================================
;;; Step v9.9 - scenario and selftest integration for diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.0 - public BR-DIAG commands and exported report artifacts
;;; ============================================================










;;; ============================================================
;;; Step v10.1 - diagnostic issue classifiers and routing
;;; ============================================================






;;; ============================================================
;;; Step v10.2 - field reset and table field reset helpers
;;; ============================================================








;;; ============================================================
;;; Step v10.3 - recovery helpers driven by group diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.4 - table recovery and resync commands
;;; ============================================================








;;; ============================================================
;;; Step v10.5 - group fix engine
;;; ============================================================




;;; ============================================================
;;; Step v10.6 - batch fix orchestrators
;;; ============================================================






;;; ============================================================
;;; Step v10.7 - public fix and recover commands
;;; ============================================================








;;; ============================================================
;;; Step v10.8 - repair report export
;;; ============================================================








;;; ============================================================
;;; Step v10.9 - fix tests and scenario integration
;;; ============================================================








;;; ============================================================
;;; Step v11.0 - public repair selftests and exported fix artifacts
;;; ============================================================








;;; ============================================================
;;; Step v11.1 - BRCODE state accessors and normalization
;;; ============================================================

(setq *brx-code-meta* nil)








;;; ============================================================
;;; Step v11.2 - embed metadata writers and hash placeholders
;;; ============================================================








;;; ============================================================
;;; Step v11.3 - loader health and security policy checks
;;; ============================================================








;;; ============================================================
;;; Step v11.4 - force install and embed restore primitives
;;; ============================================================






;;; ============================================================
;;; Step v11.5 - install recovery pipeline for unresolved DWG state
;;; ============================================================






;;; ============================================================
;;; Step v11.6 - selective fix policy by error kind and loader state
;;; ============================================================






;;; ============================================================
;;; Step v11.7 - policy-aware repair orchestration
;;; ============================================================




;;; ============================================================
;;; Step v11.8 - public install and embed commands
;;; ============================================================








;;; ============================================================
;;; Step v11.9 - install and security diagnostics export
;;; ============================================================






;;; ============================================================
;;; Step v12.0 - selftests and orchestrated recovery commands
;;; ============================================================










;;; ============================================================
;;; Step v12.1 - NOD and XRECORD in-memory bridge
;;; ============================================================

(setq *brx-nod-store* nil)










;;; ============================================================
;;; Step v12.2 - BRCODE NOD read write helpers
;;; ============================================================






;;; ============================================================
;;; Step v12.3 - UTF-8 BOM chunking stubs for BRCODEPART001..N
;;; ============================================================






;;; ============================================================
;;; Step v12.4 - payload restore and hash verification stubs
;;; ============================================================






;;; ============================================================
;;; Step v12.5 - NOD-backed embed and restore pipeline
;;; ============================================================






;;; ============================================================
;;; Step v12.6 - live NOD bridge wrappers and fallback
;;; ============================================================










;;; ============================================================
;;; Step v12.7 - commands for NOD embed restore verify
;;; ============================================================








;;; ============================================================
;;; Step v12.8 - NOD diagnostics export and summary
;;; ============================================================






;;; ============================================================
;;; Step v12.9 - NOD selftests and scenario integration
;;; ============================================================






;;; ============================================================
;;; Step v13.0 - unified recover all plus NOD export
;;; ============================================================






;;; ============================================================
;;; Step v13.1 - real dictionary lookup and creation wrappers
;;; ============================================================










;;; ============================================================
;;; Step v13.2 - real XRECORD creation and read wrappers
;;; ============================================================










;;; ============================================================
;;; Step v13.3 - real XRECORD write replace helpers
;;; ============================================================






;;; ============================================================
;;; Step v13.4 - BRCODE meta write to real XRECORD keys
;;; ============================================================






;;; ============================================================
;;; Step v13.5 - BRCODE part write and read via real XRECORD keys
;;; ============================================================








;;; ============================================================
;;; Step v13.6 - real embed restore bridge on top of XRECORD APIs
;;; ============================================================






;;; ============================================================
;;; Step v13.7 - real meta readback from XRECORDs
;;; ============================================================




;;; ============================================================
;;; Step v13.8 - public real API commands
;;; ============================================================








;;; ============================================================
;;; Step v13.9 - real API diagnostics and selftests
;;; ============================================================






;;; ============================================================
;;; Step v14.0 - unified NOD real API export
;;; ============================================================






;;; ============================================================
;;; Step v14.1 - host capability and LISPSYS gates
;;; ============================================================

(defun brx-getvar-safe (name / r)
  (setq r (vl-catch-all-apply 'getvar (list name)))
  (if (vl-catch-all-error-p r) nil r)
)

(defun brx-lispsys-safe ( /)
  (brx-getvar-safe 'LISPSYS)
)

(defun brx-unicode-env-p ( / v)
  (setq v (brx-lispsys-safe))
  (if (= v 1) T nil)
)

(defun brx-host-capability-report ( /)
  (list
    (cons 'LISPSYS (brx-lispsys-safe))
    (cons 'UNICODEENV (brx-unicode-env-p))
    (cons 'REALNOD (not (null (brx-nod-root-safe))))
  )
)


;;; ============================================================
;;; Step v14.2 - UTF-8 byte encoder with BOM support
;;; ============================================================

(defun brx-utf8-char-bytes (cp /)
  (cond
    ((< cp 128) (list cp))
    ((< cp 2048)
      (list (+ 192 (/ cp 64)) (+ 128 (rem cp 64)))
    )
    ((< cp 65536)
      (list (+ 224 (/ cp 4096)) (+ 128 (rem (/ cp 64) 64)) (+ 128 (rem cp 64)))
    )
    (T
      (list (+ 240 (/ cp 262144)) (+ 128 (rem (/ cp 4096) 64)) (+ 128 (rem (/ cp 64) 64)) (+ 128 (rem cp 64)))
    )
  )
)

(defun brx-string->utf8-bytes-basic (s addbom / i out cp)
  (setq i 1 out nil s (vl-princ-to-string s))
  (if addbom (setq out (append out '(239 187 191))))
  (while (<= i (strlen s))
    (setq cp (ascii (substr s i 1)))
    (setq out (append out (brx-utf8-char-bytes cp)))
    (setq i (1+ i))
  )
  out
)

(defun brx-utf8-byte-length-basic (s addbom /)
  (length (brx-string->utf8-bytes-basic s addbom))
)


;;; ============================================================
;;; Step v14.3 - byte-aware chunking for BRCODE payload
;;; ============================================================

(defun brx-string-chunk-bytes-basic (s maxBytes addbom / i cur out next bytes)
  (setq i 1 cur "" out nil s (vl-princ-to-string s))
  (while (<= i (strlen s))
    (setq next (substr s i 1))
    (setq bytes (brx-utf8-byte-length-basic (strcat cur next) addbom))
    (if (> bytes maxBytes)
      (progn
        (setq out (cons cur out))
        (setq cur next)
        (setq addbom nil)
      )
      (setq cur (strcat cur next))
    )
    (setq i (1+ i))
  )
  (if (/= cur "") (setq out (cons cur out)))
  (reverse out)
)

(defun brx-brcode-byteparts-build (text /)
  (brx-string-chunk-bytes-basic text 120 T)
)


;;; ============================================================
;;; Step v14.4 - byte hash adapters and checksum fallback
;;; ============================================================

(defun brx-byte-list-sum32 (lst / acc)
  (setq acc 0)
  (foreach b lst
    (setq acc (rem (+ (* acc 131) b) 4294967291))
  )
  acc
)

(defun brx-int->hex8 (n / hex out d)
  (setq hex "0123456789ABCDEF" out "")
  (repeat 8
    (setq d (rem n 16))
    (setq out (strcat (substr hex (1+ d) 1) out))
    (setq n (/ n 16))
  )
  out
)

(defun brx-bytehash-fallback (bytes /)
  (strcat "SUM32-" (brx-int->hex8 (brx-byte-list-sum32 bytes)))
)

(defun brx-bytehash-md5-adapter (bytes /)
  (if (and (fboundp 'LM:MD5) bytes)
    (LM:MD5 bytes)
    (brx-bytehash-fallback bytes)
  )
)


;;; ============================================================
;;; Step v14.5 - byte accurate payload hash and verify
;;; ============================================================

(defun brx-code-hash-bytes-realish (text / bytes)
  (setq bytes (brx-string->utf8-bytes-basic text T))
  (brx-bytehash-md5-adapter bytes)
)

(defun brx-brcode-verify-hash-bytes (payload / h)
  (setq h (brx-code-hash-bytes-realish payload))
  (if (= h (brx-code-meta-get 'BRCODEHASH)) T nil)
)

(defun brx-brcode-part-bytes-summary (parts / out p)
  (setq out nil)
  (foreach p parts
    (setq out (cons (cons p (brx-utf8-byte-length-basic p nil)) out))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v14.6 - byte-aware real API embed write
;;; ============================================================

(defun brx-code-embed-byteapi (codeText version buildDate / parts hash)
  (setq parts (brx-brcode-byteparts-build (vl-princ-to-string codeText)))
  (setq hash (brx-code-hash-bytes-realish codeText))
  (brx-code-meta-put 'BRCODEINFO "BLKREACTOR")
  (brx-code-meta-put 'BRCODEVERSION version)
  (brx-code-meta-put 'BRCODEHASH hash)
  (brx-code-meta-put 'BRCODEBUILDDATE buildDate)
  (brx-code-meta-put 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
  (brx-brcode-write-meta-real)
  (brx-brcode-parts-write-real parts)
  (brx-rv-ok (list (cons 'HASH hash) (cons 'PARTS (length parts))) "EMBED" nil)
)


;;; ============================================================
;;; Step v14.7 - byte-aware restore verify and LT gates
;;; ============================================================

(defun brx-byteapi-allowed-p ( / cap)
  (setq cap (brx-host-capability-report))
  (if (cdr (assoc 'REALNOD cap)) T nil)
)

(defun brx-code-restore-byteapi ( / parts payload)
  (if (not (brx-byteapi-allowed-p))
    (brx-rv-err "CAP" "Byte API restore unavailable in current host" nil)
    (progn
      (brx-brcode-read-meta-real)
      (setq parts (brx-brcode-parts-read-real))
      (setq payload (apply 'strcat parts))
      (if (brx-brcode-verify-hash-bytes payload)
        (brx-rv-ok payload "CODE" nil)
        (brx-rv-err "HASH" "Byte-aware payload hash mismatch" nil)
      )
    )
  )
)


;;; ============================================================
;;; Step v14.8 - public byte-aware commands
;;; ============================================================

(defun c:BR-BYTE-EMBED ( / rv)
  (setq rv (brx-code-embed-byteapi ";;; BLKREACTOR BYTE PAYLOAD" "14.8" "2026-04-12T20:52:00"))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-BYTE-RESTORE ( / rv)
  (setq rv (brx-code-restore-byteapi))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-BYTE-CAP ( / rv)
  (setq rv (brx-host-capability-report))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)


;;; ============================================================
;;; Step v14.9 - byte-aware diagnostics and selftests
;;; ============================================================

(defun brx-byteapi-report ( / parts)
  (setq parts (brx-brcode-parts-read-real))
  (list
    (cons 'HOST (brx-host-capability-report))
    (cons 'HASH (brx-code-meta-get 'BRCODEHASH))
    (cons 'PARTCOUNT (length parts))
    (cons 'PARTBYTES (brx-brcode-part-bytes-summary parts))
  )
)

(defun brx-run-byteapi-tests ( / rv rep)
  (setq *brx-test-results* nil)
  (setq rv (brx-code-embed-byteapi "Привет UTF-8 payload" "14.9" "2026-04-12T20:52:00"))
  (brx-assert-false "byteapi-embed-no-error" (brx-err-p rv))
  (setq rv (brx-code-restore-byteapi))
  (brx-assert-false "byteapi-restore-no-error" (brx-err-p rv))
  (setq rep (brx-byteapi-report))
  (brx-assert-true "byteapi-report-has-host" (not (null (assoc 'HOST rep))))
  (brx-test-summary)
)




;;; ============================================================
;;; Step v15.0 - byte-aware export bundle
;;; ============================================================

(defun c:BR-BYTE-EXPORT ( / rep)
  (setq rep (brx-byteapi-report))
  (brx-write-lines-file "output/brx_byteapi_report.txt" (list (vl-princ-to-string rep)))
  (prompt (strcat "\n" (vl-princ-to-string rep)))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_ByteAPI_v15_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_Production_v16_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_Production_v16_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================










;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================










;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================








;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================






;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================








;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================






;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================








;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================






;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================






;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================






;;; ============================================================
;;; Step v9.1 - table field state records and mode helpers
;;; ============================================================










;;; ============================================================
;;; Step v9.2 - real table field sync for FIELDNATIVE and FIELDEXCEL
;;; ============================================================








;;; ============================================================
;;; Step v9.3 - table field reverse writeback bridge
;;; ============================================================




;;; ============================================================
;;; Step v9.4 - field diagnostics for groups and tables
;;; ============================================================








;;; ============================================================
;;; Step v9.5 - global diagnostics aggregators
;;; ============================================================








;;; ============================================================
;;; Step v9.6 - unified BR-DIAG report model
;;; ============================================================






;;; ============================================================
;;; Step v9.7 - diagnostic export writers
;;; ============================================================








;;; ============================================================
;;; Step v9.8 - table field tests and diagnostics tests
;;; ============================================================




;;; ============================================================
;;; Step v9.9 - scenario and selftest integration for diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.0 - public BR-DIAG commands and exported report artifacts
;;; ============================================================










;;; ============================================================
;;; Step v10.1 - diagnostic issue classifiers and routing
;;; ============================================================






;;; ============================================================
;;; Step v10.2 - field reset and table field reset helpers
;;; ============================================================








;;; ============================================================
;;; Step v10.3 - recovery helpers driven by group diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.4 - table recovery and resync commands
;;; ============================================================








;;; ============================================================
;;; Step v10.5 - group fix engine
;;; ============================================================




;;; ============================================================
;;; Step v10.6 - batch fix orchestrators
;;; ============================================================






;;; ============================================================
;;; Step v10.7 - public fix and recover commands
;;; ============================================================








;;; ============================================================
;;; Step v10.8 - repair report export
;;; ============================================================








;;; ============================================================
;;; Step v10.9 - fix tests and scenario integration
;;; ============================================================








;;; ============================================================
;;; Step v11.0 - public repair selftests and exported fix artifacts
;;; ============================================================








;;; ============================================================
;;; Step v11.1 - BRCODE state accessors and normalization
;;; ============================================================

(setq *brx-code-meta* nil)








;;; ============================================================
;;; Step v11.2 - embed metadata writers and hash placeholders
;;; ============================================================








;;; ============================================================
;;; Step v11.3 - loader health and security policy checks
;;; ============================================================








;;; ============================================================
;;; Step v11.4 - force install and embed restore primitives
;;; ============================================================






;;; ============================================================
;;; Step v11.5 - install recovery pipeline for unresolved DWG state
;;; ============================================================






;;; ============================================================
;;; Step v11.6 - selective fix policy by error kind and loader state
;;; ============================================================






;;; ============================================================
;;; Step v11.7 - policy-aware repair orchestration
;;; ============================================================




;;; ============================================================
;;; Step v11.8 - public install and embed commands
;;; ============================================================








;;; ============================================================
;;; Step v11.9 - install and security diagnostics export
;;; ============================================================






;;; ============================================================
;;; Step v12.0 - selftests and orchestrated recovery commands
;;; ============================================================










;;; ============================================================
;;; Step v12.1 - NOD and XRECORD in-memory bridge
;;; ============================================================

(setq *brx-nod-store* nil)










;;; ============================================================
;;; Step v12.2 - BRCODE NOD read write helpers
;;; ============================================================






;;; ============================================================
;;; Step v12.3 - UTF-8 BOM chunking stubs for BRCODEPART001..N
;;; ============================================================






;;; ============================================================
;;; Step v12.4 - payload restore and hash verification stubs
;;; ============================================================






;;; ============================================================
;;; Step v12.5 - NOD-backed embed and restore pipeline
;;; ============================================================






;;; ============================================================
;;; Step v12.6 - live NOD bridge wrappers and fallback
;;; ============================================================










;;; ============================================================
;;; Step v12.7 - commands for NOD embed restore verify
;;; ============================================================








;;; ============================================================
;;; Step v12.8 - NOD diagnostics export and summary
;;; ============================================================






;;; ============================================================
;;; Step v12.9 - NOD selftests and scenario integration
;;; ============================================================






;;; ============================================================
;;; Step v13.0 - unified recover all plus NOD export
;;; ============================================================






;;; ============================================================
;;; Step v13.1 - real dictionary lookup and creation wrappers
;;; ============================================================










;;; ============================================================
;;; Step v13.2 - real XRECORD creation and read wrappers
;;; ============================================================










;;; ============================================================
;;; Step v13.3 - real XRECORD write replace helpers
;;; ============================================================






;;; ============================================================
;;; Step v13.4 - BRCODE meta write to real XRECORD keys
;;; ============================================================






;;; ============================================================
;;; Step v13.5 - BRCODE part write and read via real XRECORD keys
;;; ============================================================








;;; ============================================================
;;; Step v13.6 - real embed restore bridge on top of XRECORD APIs
;;; ============================================================






;;; ============================================================
;;; Step v13.7 - real meta readback from XRECORDs
;;; ============================================================




;;; ============================================================
;;; Step v13.8 - public real API commands
;;; ============================================================








;;; ============================================================
;;; Step v13.9 - real API diagnostics and selftests
;;; ============================================================






;;; ============================================================
;;; Step v14.0 - unified NOD real API export
;;; ============================================================






;;; ============================================================
;;; Step v14.1 - host capability and LISPSYS gates
;;; ============================================================










;;; ============================================================
;;; Step v14.2 - UTF-8 byte encoder with BOM support
;;; ============================================================








;;; ============================================================
;;; Step v14.3 - byte-aware chunking for BRCODE payload
;;; ============================================================






;;; ============================================================
;;; Step v14.4 - byte hash adapters and checksum fallback
;;; ============================================================










;;; ============================================================
;;; Step v14.5 - byte accurate payload hash and verify
;;; ============================================================








;;; ============================================================
;;; Step v14.6 - byte-aware real API embed write
;;; ============================================================




;;; ============================================================
;;; Step v14.7 - byte-aware restore verify and LT gates
;;; ============================================================






;;; ============================================================
;;; Step v14.8 - public byte-aware commands
;;; ============================================================








;;; ============================================================
;;; Step v14.9 - byte-aware diagnostics and selftests
;;; ============================================================








;;; ============================================================
;;; Step v15.0 - byte-aware export bundle
;;; ============================================================




;;; ============================================================
;;; Step v15.1 - payload manifest and storage invariants
;;; ============================================================

(defun brx-brcode-manifest-build (parts / total)
  (setq total 0)
  (foreach p parts
    (setq total (+ total (brx-utf8-byte-length-basic p nil)))
  )
  (list
    (cons 'PARTCOUNT (length parts))
    (cons 'TOTALBYTES total)
    (cons 'HASBOM T)
  )
)

(defun brx-brcode-manifest-write-real (parts / man)
  (setq man (brx-brcode-manifest-build parts))
  (brx-xrecord-write-real "BRCODE" 'BRCODEMANIFEST
    (list
      (cons 90 (cdr (assoc 'PARTCOUNT man)))
      (cons 91 (cdr (assoc 'TOTALBYTES man)))
      (cons 290 (if (cdr (assoc 'HASBOM man)) 1 0))
    )
  )
  man
)

(defun brx-brcode-manifest-read-real ( / rec)
  (setq rec (brx-xrecord-read-real "BRCODE" 'BRCODEMANIFEST))
  (if rec
    (list
      (cons 'PARTCOUNT (cdr (assoc 90 rec)))
      (cons 'TOTALBYTES (cdr (assoc 91 rec)))
      (cons 'HASBOM (/= 0 (cdr (assoc 290 rec))))
    )
    nil
  )
)


;;; ============================================================
;;; Step v15.2 - round-trip byte invariants and compare helpers
;;; ============================================================

(defun brx-byte-list-equal-p (a b / ok)
  (setq ok T)
  (if (/= (length a) (length b))
    nil
    (progn
      (while (and ok a b)
        (if (/= (car a) (car b)) (setq ok nil))
        (setq a (cdr a) b (cdr b))
      )
      ok
    )
  )
)

(defun brx-verify-roundtrip-bytes (text rebuilt / a b)
  (setq a (brx-string->utf8-bytes-basic text T))
  (setq b (brx-string->utf8-bytes-basic rebuilt T))
  (brx-byte-list-equal-p a b)
)

(defun brx-brcode-verify-manifest-vs-parts ( / man parts total)
  (setq man (brx-brcode-manifest-read-real))
  (setq parts (brx-brcode-parts-read-real))
  (setq total 0)
  (foreach p parts (setq total (+ total (brx-utf8-byte-length-basic p nil))))
  (if man
    (and (= (cdr (assoc 'PARTCOUNT man)) (length parts))
         (= (cdr (assoc 'TOTALBYTES man)) total))
    nil
  )
)


;;; ============================================================
;;; Step v15.3 - production embed pipeline with manifest
;;; ============================================================

(defun brx-code-embed-production (codeText version buildDate / parts hash)
  (setq parts (brx-brcode-byteparts-build (vl-princ-to-string codeText)))
  (setq hash (brx-code-hash-bytes-realish codeText))
  (brx-code-meta-put 'BRCODEINFO "BLKREACTOR")
  (brx-code-meta-put 'BRCODEVERSION version)
  (brx-code-meta-put 'BRCODEHASH hash)
  (brx-code-meta-put 'BRCODEBUILDDATE buildDate)
  (brx-code-meta-put 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
  (brx-code-meta-put 'BRCODELOADERSTATE (or (brx-code-meta-get 'BRCODELOADERSTATE) "MISSING"))
  (brx-brcode-write-meta-real)
  (brx-brcode-parts-write-real parts)
  (brx-brcode-manifest-write-real parts)
  (brx-rv-ok
    (list
      (cons 'HASH hash)
      (cons 'PARTCOUNT (length parts))
      (cons 'MANIFEST (brx-brcode-manifest-read-real))
    )
    "EMBED" nil)
)


;;; ============================================================
;;; Step v15.4 - production restore pipeline with full checks
;;; ============================================================

(defun brx-code-restore-production ( / parts payload ok1 ok2)
  (if (not (brx-byteapi-allowed-p))
    (brx-rv-err "CAP" "Production restore unavailable in current host" nil)
    (progn
      (brx-brcode-read-meta-real)
      (setq parts (brx-brcode-parts-read-real))
      (setq payload (apply 'strcat parts))
      (setq ok1 (brx-brcode-verify-manifest-vs-parts))
      (setq ok2 (brx-brcode-verify-hash-bytes payload))
      (cond
        ((not ok1) (brx-rv-err "MANIFEST" "Manifest mismatch against stored parts" nil))
        ((not ok2) (brx-rv-err "HASH" "Production payload hash mismatch" nil))
        ((not (brx-verify-roundtrip-bytes payload payload)) (brx-rv-err "ROUNDTRIP" "Round-trip byte mismatch" nil))
        (T (brx-rv-ok payload "CODE" nil))
      )
    )
  )
)


;;; ============================================================
;;; Step v15.5 - unified public BR-EMBED and BR-RESTORE commands
;;; ============================================================

(defun c:BR-EMBED ( / rv)
  (setq rv (brx-code-embed-production ";;; BLKREACTOR PRODUCTION PAYLOAD" "15.5" "2026-04-12T20:54:00"))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-RESTORE ( / rv)
  (setq rv (brx-code-restore-production))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-VERIFY-CODE ( / rv)
  (setq rv (list
    (cons 'META (brx-brcode-read-meta-real))
    (cons 'MANIFESTOK (brx-brcode-verify-manifest-vs-parts))
  ))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)


;;; ============================================================
;;; Step v15.6 - recovery orchestration uses production restore
;;; ============================================================

(defun brx-install-recover-production ( / rv)
  (setq rv (brx-force-install-stub))
  (if (brx-err-p rv)
    (setq rv (brx-code-restore-production))
  )
  (if (brx-err-p rv)
    (brx-code-meta-put 'BRCODEINSTALLSTATE "ERROR")
    (if (= (brx-code-meta-get 'BRCODEINSTALLSTATE) "EMBEDDEDONLY")
      (brx-code-meta-put 'BRCODEINSTALLSTATE "EMBEDDEDONLY")
      (brx-code-meta-put 'BRCODEINSTALLSTATE "INSTALLED")
    )
  )
  rv
)

(defun c:BR-RECOVER-CODE ( / rv)
  (setq rv (brx-install-recover-production))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)


;;; ============================================================
;;; Step v15.7 - corpus-based round-trip tests
;;; ============================================================

(setq *brx-byte-corpus*
  (list
    "ASCII payload 123"
    "Русский текст 123"
    "Mix ASCII + Кириллица + symbols _-+=()"
    "TABLE:A1,B2,C3"
  )
)

(defun brx-run-byte-corpus-tests ( / item ok out)
  (setq out nil)
  (foreach item *brx-byte-corpus*
    (setq ok (brx-verify-roundtrip-bytes item item))
    (setq out (cons (list (cons 'TEXT item) (cons 'OK ok) (cons 'BYTES (brx-utf8-byte-length-basic item T))) out))
  )
  (reverse out)
)


;;; ============================================================
;;; Step v15.8 - production selftests and final pipeline smoke
;;; ============================================================

(defun brx-run-production-tests ( / rv rep)
  (setq *brx-test-results* nil)
  (setq rv (brx-code-embed-production "Тест production UTF-8 payload" "15.8" "2026-04-12T20:54:00"))
  (brx-assert-false "prod-embed-no-error" (brx-err-p rv))
  (setq rv (brx-code-restore-production))
  (brx-assert-false "prod-restore-no-error" (brx-err-p rv))
  (brx-assert-true "prod-manifest-ok" (brx-brcode-verify-manifest-vs-parts))
  (setq rep (brx-run-byte-corpus-tests))
  (brx-assert-true "prod-corpus-has-rows" (> (length rep) 0))
  (brx-test-summary)
)




;;; ============================================================
;;; Step v15.9 - production diagnostics export
;;; ============================================================

(defun brx-production-report ( / payload)
  (setq payload (apply 'strcat (brx-brcode-parts-read-real)))
  (list
    (cons 'HOST (brx-host-capability-report))
    (cons 'META (brx-brcode-read-meta-real))
    (cons 'MANIFEST (brx-brcode-manifest-read-real))
    (cons 'MANIFESTOK (brx-brcode-verify-manifest-vs-parts))
    (cons 'HASHOK (brx-brcode-verify-hash-bytes payload))
    (cons 'CORPUS (brx-run-byte-corpus-tests))
  )
)

(defun c:BR-PRODUCTION-EXPORT ( / rep)
  (setq rep (brx-production-report))
  (brx-write-lines-file "output/brx_production_report.txt" (list (vl-princ-to-string rep)))
  (prompt (strcat "\n" (vl-princ-to-string rep)))
  (princ)
)


;;; ============================================================
;;; Step v16.0 - unified recover-all final command
;;; ============================================================

(defun c:BR-RECOVER-ALL-FINAL ( / out)
  (setq out (list
    (cons 'CODE (brx-install-recover-production))
    (cons 'VERIFY (brx-production-report))
    (cons 'FIXES (brx-fix-all-groups))
  ))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_Production_v16_0.lsp

;;; ------------------------------------------------------------
;;; BEGIN MODULE: output/BLK_REACTOR_LiveSource_v17_0.lsp
;;; ------------------------------------------------------------
(setq *brx-build-modules* (append *brx-build-modules* (list "output/BLK_REACTOR_LiveSource_v17_0.lsp")))
;;; ============================================================
;;; BLK_REACTOR Core Formula Engine - Stage 2
;;; Tokenizer + canonicalizer + parser + static self-check helpers
;;; Version: v0.2
;;; Notes:
;;; - v0.1 is preserved separately.
;;; - This stage tackles the hardest layer first: formula grammar.
;;; - Resolver/integration with DWG/xData/FIELDN remains staged for next versions.
;;; ============================================================

(vl-load-com)

;; ------------------------------------------------------------
;; Constants
;; ------------------------------------------------------------

(setq *brx-error-codes*
  '(
    ("001" . "NA")
    ("002" . "MULTI")
    ("003" . "REF")
    ("004" . "TYPE")
    ("005" . "VALUE")
    ("006" . "DIV0")
    ("007" . "CYCLE")
    ("008" . "CTX")
    ("009" . "PARSE")
    ("010" . "INTERNAL")
    ("011" . "WRITEBACK")
   )
)

(setq *brx-bool-true*  T)
(setq *brx-bool-false* nil)

;; ------------------------------------------------------------
;; Runtime value model
;; ------------------------------------------------------------

















;; ------------------------------------------------------------
;; Context model
;; ------------------------------------------------------------









;; ------------------------------------------------------------
;; Small string helpers
;; ------------------------------------------------------------





























;; ------------------------------------------------------------
;; Token model
;; ------------------------------------------------------------













;; ------------------------------------------------------------
;; AST constructors
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Parser state
;; ------------------------------------------------------------

(setq *brx-ptoks* nil)
(setq *brx-pidx*  0)

































;; ------------------------------------------------------------
;; Resolver stubs (next stage will bind to DWG/xData/FIELDN/PARAMN)
;; ------------------------------------------------------------



;; ------------------------------------------------------------
;; Function dispatch (base logical core first)
;; ------------------------------------------------------------











;; ------------------------------------------------------------
;; Evaluator
;; ------------------------------------------------------------





;; ------------------------------------------------------------
;; Debug / introspection helpers
;; ------------------------------------------------------------












;;; ============================================================
;;; Step v0.3 - resolver core for context/scope/object access
;;; ============================================================






































;;; ============================================================
;;; Step v0.4 - alias resolver, recursion stack, CYCLE/REF/MULTI guards
;;; ============================================================


















;;; ============================================================
;;; Step v0.5 - numeric coercion and math functions
;;; ============================================================
































;;; ============================================================
;;; Step v0.6 - comparisons, predicates, IFERROR, text containment
;;; ============================================================


























;;; ============================================================
;;; Step v0.7 - formatting and text composition functions
;;; ============================================================




















;;; ============================================================
;;; Step v0.8a - IN/CONTAINS predicates
;;; ============================================================













;;; ============================================================
;;; Step v0.8 - list and typeset functions for GROUP/ROW/COL sets
;;; ============================================================














































;;; ============================================================
;;; Step v0.9 - canonical validator helpers for PARAMN FORMULAN FIELDN
;;; ============================================================














;;; ============================================================
;;; Step v1.0a - static formula dependency extractor for PARAMN/FORMULAN
;;; ============================================================






;;; ============================================================
;;; Step v1.0 - dependency graph and static cycle analysis
;;; ============================================================














;;; ============================================================
;;; Step v1.1 - xData key map, group roles, and sandbox persistence facade
;;; ============================================================

(setq *brx-xdata-store* nil)
(setq *brx-nod-store* nil)
(setq *brx-runtime-cache* nil)


































;;; ============================================================
;;; Step v1.2 - BRGROUPS named-dictionary records and validators
;;; ============================================================
















;;; ============================================================
;;; Step v1.3 - BRCODE metadata and embedded loader state model
;;; ============================================================
















;;; ============================================================
;;; Step v1.4 - runtime bootstrap from xData and NOD into group cache
;;; ============================================================












;;; ============================================================
;;; Step v1.5 - owner-aware copy/paste remap plan and unresolved states
;;; ============================================================












;;; ============================================================
;;; Step v1.6 - BR-VALIDATE core for xData, BRGROUPS, and membership consistency
;;; ============================================================










;;; ============================================================
;;; Step v1.7 - FIELD bridge state for FIELDNATIVE and FIELDEXCEL modes
;;; ============================================================














;;; ============================================================
;;; Step v1.8 - BRGROUPLOCK and lockset dictionary scaffolding
;;; ============================================================














;;; ============================================================
;;; Step v1.9 - relink and rebuild helpers for unresolved copied groups
;;; ============================================================










;;; ============================================================
;;; Step v2.0 - runtime command facade for SHOW-INFO VALIDATE FORCE-INSTALL
;;; ============================================================












;;; ============================================================
;;; Step v2.1 - AutoCAD entity/xData low-level wrappers
;;; ============================================================
















;;; ============================================================
;;; Step v2.2 - canonical xData serialization and parse helpers
;;; ============================================================
















;;; ============================================================
;;; Step v2.3 - Named Object Dictionary and XRECORD wrappers
;;; ============================================================














;;; ============================================================
;;; Step v2.4 - real BRGROUPS and BRCODE persistence on NOD/XRECORD
;;; ============================================================














;;; ============================================================
;;; Step v2.5 - entity selection helpers and command-safe pick wrappers
;;; ============================================================












;;; ============================================================
;;; Step v2.6 - working command skeletons for NEW-GROUP ADD-SLAVE SET-MASTER
;;; ============================================================














;;; ============================================================
;;; Step v2.7 - copy/deepclone remap capture and unresolved transfer markers
;;; ============================================================

(setq *brx-deepclone-map* nil)












;;; ============================================================
;;; Step v2.8 - reactor scaffolding and event entry points
;;; ============================================================

(setq *brx-reactors* nil)












;;; ============================================================
;;; Step v2.9 - BR-VALIDATE real pass with xData/NOD cross-checks
;;; ============================================================








;;; ============================================================
;;; Step v3.0 - integrated backend demo and migration notes entry point
;;; ============================================================






;;; ============================================================
;;; Step v3.1 - membership mutation helpers for add/remove/update
;;; ============================================================










;;; ============================================================
;;; Step v3.2 - entity binding helpers for master slave table roles
;;; ============================================================






;;; ============================================================
;;; Step v3.3 - working REMOVE-SLAVE and CLEAR command layer
;;; ============================================================








;;; ============================================================
;;; Step v3.4 - SHOW-INFO and GROUP-INFO enriched reporting
;;; ============================================================








;;; ============================================================
;;; Step v3.5 - repair helpers for orphaned members and missing masters
;;; ============================================================








;;; ============================================================
;;; Step v3.6 - relink pipeline for unresolved and partial copied groups
;;; ============================================================








;;; ============================================================
;;; Step v3.7 - validation repair commands and batch fixer
;;; ============================================================












;;; ============================================================
;;; Step v3.8 - FIELD refresh and reverse-writeback stubs on real entities
;;; ============================================================








;;; ============================================================
;;; Step v3.9 - install/restore checks and security-aware loader reporting
;;; ============================================================








;;; ============================================================
;;; Step v4.0 - integrated command workflow demo and end-to-end repair path
;;; ============================================================






;;; ============================================================
;;; Step v4.1 - safe dictionary delete and XRECORD cleanup helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.2 - real xData cleanup and unlink helpers
;;; ============================================================








;;; ============================================================
;;; Step v4.3 - structured error log and event journal
;;; ============================================================

(setq *brx-error-log* nil)












;;; ============================================================
;;; Step v4.4 - stricter validation rules and fatal consistency checks
;;; ============================================================








;;; ============================================================
;;; Step v4.5 - table exact-object routing and cell address helpers
;;; ============================================================










;;; ============================================================
;;; Step v4.6 - copy paste simulation and remap test harness
;;; ============================================================






;;; ============================================================
;;; Step v4.7 - dry run guards and protected destructive commands
;;; ============================================================

(setq *brx-dry-run* T)












;;; ============================================================
;;; Step v4.8 - quarantine and disable broken groups
;;; ============================================================






;;; ============================================================
;;; Step v4.9 - snapshot diff and consistency comparison helpers
;;; ============================================================








;;; ============================================================
;;; Step v5.0 - stabilization suite command orchestrator
;;; ============================================================








;;; ============================================================
;;; Step v5.1 - minimal assertion framework and test result store
;;; ============================================================

(setq *brx-test-results* nil)














;;; ============================================================
;;; Step v5.2 - synthetic fixture builders for master slave table
;;; ============================================================












;;; ============================================================
;;; Step v5.3 - parser and evaluator test suite
;;; ============================================================




;;; ============================================================
;;; Step v5.4 - alias cycle and REF error tests
;;; ============================================================




;;; ============================================================
;;; Step v5.5 - typeset and list function tests
;;; ============================================================






;;; ============================================================
;;; Step v5.6 - validation and relink regression tests
;;; ============================================================




;;; ============================================================
;;; Step v5.7 - BIDIR writeback and field bridge tests
;;; ============================================================




;;; ============================================================
;;; Step v5.8 - copy paste unresolved and remap simulation tests
;;; ============================================================




;;; ============================================================
;;; Step v5.9 - end to end regression runner and report formatter
;;; ============================================================






;;; ============================================================
;;; Step v6.0 - public self test commands and audit entry points
;;; ============================================================












;;; ============================================================
;;; Step v6.1 - scenario case registry and deterministic suite descriptors
;;; ============================================================

(setq *brx-scenarios* nil)










;;; ============================================================
;;; Step v6.2 - scenario fixtures for create validate relink copy and field flows
;;; ============================================================










;;; ============================================================
;;; Step v6.3 - scenario runners with expected actual payloads
;;; ============================================================










;;; ============================================================
;;; Step v6.4 - scenario bootstrap matrix
;;; ============================================================




;;; ============================================================
;;; Step v6.5 - expected actual diff engine for scenario outputs
;;; ============================================================








;;; ============================================================
;;; Step v6.6 - scenario execution engine and transcript store
;;; ============================================================

(setq *brx-scenario-transcript* nil)










;;; ============================================================
;;; Step v6.7 - CSV and markdown report string generators
;;; ============================================================








;;; ============================================================
;;; Step v6.8 - smoke tests for public command workflows
;;; ============================================================






;;; ============================================================
;;; Step v6.9 - scenario report exporters to workspace files
;;; ============================================================






;;; ============================================================
;;; Step v7.0 - public scenario test and export commands
;;; ============================================================










;;; ============================================================
;;; Step v7.1 - table cell address parser and range helpers
;;; ============================================================










;;; ============================================================
;;; Step v7.2 - table cell store and exact-object resolution
;;; ============================================================

(setq *brx-table-store* nil)












;;; ============================================================
;;; Step v7.3 - merged-cell anchor model and anchor resolution
;;; ============================================================










;;; ============================================================
;;; Step v7.4 - owner-aware alias chain resolver
;;; ============================================================








;;; ============================================================
;;; Step v7.5 - owner-path target references for nested objects and cells
;;; ============================================================








;;; ============================================================
;;; Step v7.6 - table writeback normalization and limits
;;; ============================================================










;;; ============================================================
;;; Step v7.7 - table scenario fixtures and merged-cell tests
;;; ============================================================






;;; ============================================================
;;; Step v7.8 - alias owner-chain tests and exact-object tests
;;; ============================================================




;;; ============================================================
;;; Step v7.9 - table scenario export coverage and selftests
;;; ============================================================








;;; ============================================================
;;; Step v8.0 - integrated table and alias hardening bundle
;;; ============================================================






;;; ============================================================
;;; Step v8.1 - VLA object wrappers and TABLE detection
;;; ============================================================










;;; ============================================================
;;; Step v8.2 - real row column accessors and cell text readers
;;; ============================================================










;;; ============================================================
;;; Step v8.3 - real cell writers and regeneration helpers
;;; ============================================================








;;; ============================================================
;;; Step v8.4 - merged-cell detection bridge with fallback
;;; ============================================================






;;; ============================================================
;;; Step v8.5 - anchor resolution bridge for live TABLE and cache
;;; ============================================================








;;; ============================================================
;;; Step v8.6 - live TABLE cache sync into BLKREACTOR cell store
;;; ============================================================






;;; ============================================================
;;; Step v8.7 - TABLE-aware validate and show-info commands
;;; ============================================================








;;; ============================================================
;;; Step v8.8 - TABLE writeback bridge commands and protections
;;; ============================================================






;;; ============================================================
;;; Step v8.9 - TABLE regressions integrated into scenario reports
;;; ============================================================






;;; ============================================================
;;; Step v9.0 - integrated real TABLE bridge bundle and diagnostics
;;; ============================================================






;;; ============================================================
;;; Step v9.1 - table field state records and mode helpers
;;; ============================================================










;;; ============================================================
;;; Step v9.2 - real table field sync for FIELDNATIVE and FIELDEXCEL
;;; ============================================================








;;; ============================================================
;;; Step v9.3 - table field reverse writeback bridge
;;; ============================================================




;;; ============================================================
;;; Step v9.4 - field diagnostics for groups and tables
;;; ============================================================








;;; ============================================================
;;; Step v9.5 - global diagnostics aggregators
;;; ============================================================








;;; ============================================================
;;; Step v9.6 - unified BR-DIAG report model
;;; ============================================================






;;; ============================================================
;;; Step v9.7 - diagnostic export writers
;;; ============================================================








;;; ============================================================
;;; Step v9.8 - table field tests and diagnostics tests
;;; ============================================================




;;; ============================================================
;;; Step v9.9 - scenario and selftest integration for diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.0 - public BR-DIAG commands and exported report artifacts
;;; ============================================================










;;; ============================================================
;;; Step v10.1 - diagnostic issue classifiers and routing
;;; ============================================================






;;; ============================================================
;;; Step v10.2 - field reset and table field reset helpers
;;; ============================================================








;;; ============================================================
;;; Step v10.3 - recovery helpers driven by group diagnostics
;;; ============================================================








;;; ============================================================
;;; Step v10.4 - table recovery and resync commands
;;; ============================================================








;;; ============================================================
;;; Step v10.5 - group fix engine
;;; ============================================================




;;; ============================================================
;;; Step v10.6 - batch fix orchestrators
;;; ============================================================






;;; ============================================================
;;; Step v10.7 - public fix and recover commands
;;; ============================================================








;;; ============================================================
;;; Step v10.8 - repair report export
;;; ============================================================








;;; ============================================================
;;; Step v10.9 - fix tests and scenario integration
;;; ============================================================








;;; ============================================================
;;; Step v11.0 - public repair selftests and exported fix artifacts
;;; ============================================================








;;; ============================================================
;;; Step v11.1 - BRCODE state accessors and normalization
;;; ============================================================

(setq *brx-code-meta* nil)








;;; ============================================================
;;; Step v11.2 - embed metadata writers and hash placeholders
;;; ============================================================








;;; ============================================================
;;; Step v11.3 - loader health and security policy checks
;;; ============================================================








;;; ============================================================
;;; Step v11.4 - force install and embed restore primitives
;;; ============================================================






;;; ============================================================
;;; Step v11.5 - install recovery pipeline for unresolved DWG state
;;; ============================================================






;;; ============================================================
;;; Step v11.6 - selective fix policy by error kind and loader state
;;; ============================================================






;;; ============================================================
;;; Step v11.7 - policy-aware repair orchestration
;;; ============================================================




;;; ============================================================
;;; Step v11.8 - public install and embed commands
;;; ============================================================








;;; ============================================================
;;; Step v11.9 - install and security diagnostics export
;;; ============================================================






;;; ============================================================
;;; Step v12.0 - selftests and orchestrated recovery commands
;;; ============================================================










;;; ============================================================
;;; Step v12.1 - NOD and XRECORD in-memory bridge
;;; ============================================================

(setq *brx-nod-store* nil)










;;; ============================================================
;;; Step v12.2 - BRCODE NOD read write helpers
;;; ============================================================






;;; ============================================================
;;; Step v12.3 - UTF-8 BOM chunking stubs for BRCODEPART001..N
;;; ============================================================






;;; ============================================================
;;; Step v12.4 - payload restore and hash verification stubs
;;; ============================================================






;;; ============================================================
;;; Step v12.5 - NOD-backed embed and restore pipeline
;;; ============================================================






;;; ============================================================
;;; Step v12.6 - live NOD bridge wrappers and fallback
;;; ============================================================










;;; ============================================================
;;; Step v12.7 - commands for NOD embed restore verify
;;; ============================================================








;;; ============================================================
;;; Step v12.8 - NOD diagnostics export and summary
;;; ============================================================






;;; ============================================================
;;; Step v12.9 - NOD selftests and scenario integration
;;; ============================================================






;;; ============================================================
;;; Step v13.0 - unified recover all plus NOD export
;;; ============================================================






;;; ============================================================
;;; Step v13.1 - real dictionary lookup and creation wrappers
;;; ============================================================










;;; ============================================================
;;; Step v13.2 - real XRECORD creation and read wrappers
;;; ============================================================










;;; ============================================================
;;; Step v13.3 - real XRECORD write replace helpers
;;; ============================================================






;;; ============================================================
;;; Step v13.4 - BRCODE meta write to real XRECORD keys
;;; ============================================================






;;; ============================================================
;;; Step v13.5 - BRCODE part write and read via real XRECORD keys
;;; ============================================================








;;; ============================================================
;;; Step v13.6 - real embed restore bridge on top of XRECORD APIs
;;; ============================================================






;;; ============================================================
;;; Step v13.7 - real meta readback from XRECORDs
;;; ============================================================




;;; ============================================================
;;; Step v13.8 - public real API commands
;;; ============================================================








;;; ============================================================
;;; Step v13.9 - real API diagnostics and selftests
;;; ============================================================






;;; ============================================================
;;; Step v14.0 - unified NOD real API export
;;; ============================================================






;;; ============================================================
;;; Step v14.1 - host capability and LISPSYS gates
;;; ============================================================










;;; ============================================================
;;; Step v14.2 - UTF-8 byte encoder with BOM support
;;; ============================================================








;;; ============================================================
;;; Step v14.3 - byte-aware chunking for BRCODE payload
;;; ============================================================






;;; ============================================================
;;; Step v14.4 - byte hash adapters and checksum fallback
;;; ============================================================










;;; ============================================================
;;; Step v14.5 - byte accurate payload hash and verify
;;; ============================================================








;;; ============================================================
;;; Step v14.6 - byte-aware real API embed write
;;; ============================================================




;;; ============================================================
;;; Step v14.7 - byte-aware restore verify and LT gates
;;; ============================================================






;;; ============================================================
;;; Step v14.8 - public byte-aware commands
;;; ============================================================








;;; ============================================================
;;; Step v14.9 - byte-aware diagnostics and selftests
;;; ============================================================








;;; ============================================================
;;; Step v15.0 - byte-aware export bundle
;;; ============================================================




;;; ============================================================
;;; Step v15.1 - payload manifest and storage invariants
;;; ============================================================








;;; ============================================================
;;; Step v15.2 - round-trip byte invariants and compare helpers
;;; ============================================================








;;; ============================================================
;;; Step v15.3 - production embed pipeline with manifest
;;; ============================================================




;;; ============================================================
;;; Step v15.4 - production restore pipeline with full checks
;;; ============================================================




;;; ============================================================
;;; Step v15.5 - unified public BR-EMBED and BR-RESTORE commands
;;; ============================================================








;;; ============================================================
;;; Step v15.6 - recovery orchestration uses production restore
;;; ============================================================






;;; ============================================================
;;; Step v15.7 - corpus-based round-trip tests
;;; ============================================================

(setq *brx-byte-corpus*
  (list
    "ASCII payload 123"
    "Русский текст 123"
    "Mix ASCII + Кириллица + symbols _-+=()"
    "TABLE:A1,B2,C3"
  )
)




;;; ============================================================
;;; Step v15.8 - production selftests and final pipeline smoke
;;; ============================================================






;;; ============================================================
;;; Step v15.9 - production diagnostics export
;;; ============================================================






;;; ============================================================
;;; Step v16.0 - unified recover-all final command
;;; ============================================================




;;; ============================================================
;;; Step v16.1 - source path config and candidate resolution
;;; ============================================================

(setq *brx-source-path* nil)
(setq *brx-source-candidates* '("BLKREACTOR.lsp" "./BLKREACTOR.lsp" "./output/BLKREACTOR.lsp"))

(defun brx-set-source-path (p /)
  (setq *brx-source-path* p)
)

(defun brx-source-candidates-all ( /)
  (append (if *brx-source-path* (list *brx-source-path*) nil) *brx-source-candidates*)
)


;;; ============================================================
;;; Step v16.2 - file existence and text read helpers
;;; ============================================================

(defun brx-file-readable-p (path / fh ok)
  (setq fh (vl-catch-all-apply 'open (list path "r")))
  (if (vl-catch-all-error-p fh)
    nil
    (progn (close fh) T)
  )
)

(defun brx-read-text-file-safe (path / fh line out)
  (setq fh (vl-catch-all-apply 'open (list path "r")))
  (if (vl-catch-all-error-p fh)
    nil
    (progn
      (setq out nil)
      (while (setq line (read-line fh))
        (setq out (cons line out))
      )
      (close fh)
      (apply 'strcat
        (if out
          (append (list (car (reverse out)))
                  (mapcar '(lambda (x) (strcat "\n" x)) (cdr (reverse out))))
          (list "")
        )
      )
    )
  )
)


;;; ============================================================
;;; Step v16.3 - find first live source path
;;; ============================================================

(defun brx-find-live-source-path ( / lst hit)
  (setq lst (brx-source-candidates-all))
  (while (and lst (not hit))
    (if (brx-file-readable-p (car lst))
      (setq hit (car lst))
    )
    (setq lst (cdr lst))
  )
  hit
)

(defun brx-live-source-status ( / p)
  (setq p (brx-find-live-source-path))
  (list
    (cons 'CONFIG *brx-source-path*)
    (cons 'FOUND p)
    (cons 'CANDIDATES (brx-source-candidates-all))
  )
)


;;; ============================================================
;;; Step v16.4 - live source metadata snapshot
;;; ============================================================

(defun brx-live-source-snapshot ( / p txt)
  (setq p (brx-find-live-source-path))
  (if p
    (progn
      (setq txt (brx-read-text-file-safe p))
      (list
        (cons 'PATH p)
        (cons 'CHARS (strlen txt))
        (cons 'BYTES (brx-utf8-byte-length-basic txt T))
        (cons 'HASH (brx-code-hash-bytes-realish txt))
      )
    )
    nil
  )
)


;;; ============================================================
;;; Step v16.5 - live source embed pipeline
;;; ============================================================

(defun brx-code-embed-live-source ( / p txt snap rv)
  (setq p (brx-find-live-source-path))
  (if (not p)
    (brx-rv-err "SOURCE" "Live BLKREACTOR.lsp source not found" nil)
    (progn
      (setq txt (brx-read-text-file-safe p))
      (setq snap (brx-live-source-snapshot))
      (setq rv (brx-code-embed-production txt "16.5" "2026-04-12T20:56:00"))
      (if (brx-err-p rv)
        rv
        (brx-rv-ok (list (cons 'SOURCE snap) (cons 'EMBED rv)) "LIVE" nil)
      )
    )
  )
)


;;; ============================================================
;;; Step v16.6 - live restore and install decision wrappers
;;; ============================================================

(defun brx-live-install-decision ( / ls is)
  (setq ls (or (brx-code-meta-get 'BRCODELOADERSTATE) (brx-code-sync-loaderstate)))
  (setq is (brx-code-meta-get 'BRCODEINSTALLSTATE))
  (cond
    ((= ls "AVAILABLE") 'USE-INSTALL)
    ((= ls "BLOCKEDBYSECURITY") 'USE-EMBED)
    ((= is "EMBEDDEDONLY") 'USE-RESTORE)
    (T 'USE-RESTORE)
  )
)

(defun brx-recover-live-source ( / mode rv)
  (setq mode (brx-live-install-decision))
  (cond
    ((= mode 'USE-INSTALL) (brx-force-install-stub))
    ((= mode 'USE-EMBED) (brx-code-restore-production))
    (T (brx-code-restore-production))
  )
)


;;; ============================================================
;;; Step v16.7 - public live source commands
;;; ============================================================

(defun c:BR-SET-SOURCE-PATH ( / p)
  (setq p (getstring T "\nPath to BLKREACTOR.lsp: "))
  (if (/= p "") (brx-set-source-path p))
  (prompt (strcat "\n" (vl-princ-to-string (brx-live-source-status))))
  (princ)
)

(defun c:BR-SHOW-SOURCE ( / rv)
  (setq rv (brx-live-source-status))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)

(defun c:BR-EMBED-LIVE ( / rv)
  (setq rv (brx-code-embed-live-source))
  (prompt (strcat "\n" (vl-princ-to-string rv)))
  (princ)
)


;;; ============================================================
;;; Step v16.8 - live source selftests
;;; ============================================================

(defun brx-run-live-source-tests ( / rv stat)
  (setq *brx-test-results* nil)
  (setq stat (brx-live-source-status))
  (brx-assert-true "live-status-has-candidates" (not (null (assoc 'CANDIDATES stat))))
  (setq rv (if (cdr (assoc 'FOUND stat))
             (brx-code-embed-live-source)
             (brx-rv-ok "NO-SOURCE-IN-WORKSPACE" "INFO" nil)))
  (brx-assert-false "live-test-no-hard-error" (brx-err-p rv))
  (brx-test-summary)
)




;;; ============================================================
;;; Step v16.9 - live source diagnostics export
;;; ============================================================

(defun brx-live-source-report ( /)
  (list
    (cons 'STATUS (brx-live-source-status))
    (cons 'SNAPSHOT (brx-live-source-snapshot))
    (cons 'DECISION (brx-live-install-decision))
    (cons 'META (brx-brcode-read-meta-real))
  )
)

(defun c:BR-LIVE-EXPORT ( / rep)
  (setq rep (brx-live-source-report))
  (brx-write-lines-file "output/brx_live_source_report.txt" (list (vl-princ-to-string rep)))
  (prompt (strcat "\n" (vl-princ-to-string rep)))
  (princ)
)


;;; ============================================================
;;; Step v17.0 - final live recover-all command
;;; ============================================================

(defun c:BR-RECOVER-LIVE-ALL ( / out)
  (setq out (list
    (cons 'SOURCE (brx-live-source-status))
    (cons 'EMBED (if (cdr (assoc 'FOUND (brx-live-source-status)))
                   (brx-code-embed-live-source)
                   (brx-rv-ok "SKIPPED" "NOSOURCE" nil)))
    (cons 'RECOVER (brx-recover-live-source))
    (cons 'FIXES (brx-fix-all-groups))
  ))
  (prompt (strcat "\n" (vl-princ-to-string out)))
  (princ)
)

;;; END MODULE: output/BLK_REACTOR_LiveSource_v17_0.lsp

;;; ============================================================
;;; Build footer
;;; ============================================================
(defun c:BR-BUILD-INFO ( / )
  (prompt (strcat "\nBLKREACTOR build: " *brx-build-id*))
  (prompt (strcat "\nModules: " (vl-princ-to-string *brx-build-modules*)))
  (princ)
)