#!/usr/bin/env python3
"""Ingest a single DMN-TCK literal-expression or boxed-context test into a feel-core fixture.

Source: https://github.com/dmn-tck/tck

Scope: this is NOT a general DMN/XML harness. It handles two decision forms:

1. **Literal-expression** decisions (`<literalExpression><text>EXPR</text>`):
   each decision emits one fixture case whose expression is the bare FEEL text.

2. **Boxed-context** decisions (`<decision><context><contextEntry>…</context>`):
   each decision emits one fixture case whose expression is the assembled FEEL
   context literal `{k1: e1, k2: e2, …}` and whose expected value is the
   structured `{key: scalar, …}` context. Every individual entry expression must
   pass `fits_slice_grammar`; if any entry is out-of-slice the whole decision is
   skipped.

Both forms only emit cases whose expression(s) fit feel-core's core-language
slice: arithmetic, comparison, `between`/`in`, `instance of`, three-valued
`and`/`or`/`not`, `if/then/else`, `for … return`, `some/every … satisfies`,
context literals, path access, and the full set of built-in functions. Each
case's `<inputNode>` values are captured as a `context` object and bound during
evaluation. See `fits_slice_grammar` for the exact predicate.

Anything outside the slice — or free names we could not bind — is skipped (and
reported), so we never produce false negatives for expressions the engine cannot
yet evaluate.

It also applies a *deviation registry*: a list of rules, each pairing a
predicate ("does this case match?") with a transform ("rewrite the expectation /
comparison mode"). Today only the DECIMAL/F64 rule is live; the others are
documented placeholders that future deviations hang off.

Usage:
    python tools/ingest_tck.py <path-to-tck-test> -o <fixture.json>

<path-to-tck-test> may be a TCK test directory (containing the .dmn and the
matching *-test-*.xml) or the .dmn file itself.
"""

from __future__ import annotations

import argparse
import json
import sys
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional

# --------------------------------------------------------------------------- #
# Slice grammar predicate: which expressions can feel-core actually evaluate?
# --------------------------------------------------------------------------- #

import re

# Keywords of the core-language slice. Any identifier that is NOT one of these
# (and not a for/some/every loop variable) is a *free* name — an input variable
# or a built-in function — which puts the expression outside the self-contained
# slice we ingest.
_KEYWORDS = {
    "for", "return", "in", "if", "then", "else", "some", "every", "satisfies",
    "and", "or", "not", "between", "true", "false", "null",
}

# Built-in / Any / Null type-name words allowed on the right of `instance of`
# (DMN §10.3.2.9). Multi-word names contribute several words (`date and time` ->
# date, time; `years and months duration` -> years, months, duration), joined by the
# `and` keyword. `list`/`context`/`range`/`function` are the generic heads. A type
# name outside this set is a model itemDefinition type (e.g. `t255`) the standalone
# engine cannot resolve, so the case is left outside the slice.
_TYPE_WORDS = {
    "Any", "Null", "number", "string", "boolean", "date", "time",
    "years", "months", "days", "duration", "list", "context", "range", "function",
}

# Built-in functions feel-core implements (DECISIONS.md ADR-15/ADR-17). A name
# immediately followed by `(` is a call head, not a free identifier; we blank
# those before the free-name scan so function calls fit the slice. Multi-word
# heads (`string length`) are included now (ADR-17); temporal (`date`/`now`),
# ranges, and user-defined functions are deliberately absent, so calls to them
# stay "free names" and the expression is (correctly) skipped.
_BUILTINS = frozenset({
    # conversion
    "string", "number",
    # string
    "substring", "contains", "replace", "split", "matches",
    "string length", "upper case", "lower case", "substring before",
    "substring after", "starts with", "ends with", "string join",
    # list
    "count", "min", "max", "sum", "mean", "product", "median", "stddev",
    "mode", "all", "any", "append", "concatenate", "union", "remove",
    "reverse", "flatten", "sublist",
    "list contains", "index of", "distinct values", "insert before",
    "list replace", "sort",
    # context
    "get value", "get entries", "context", "context put", "context merge",
    # numeric
    "decimal", "floor", "ceiling", "abs", "modulo",
    "sqrt", "exp", "log", "even", "odd",
    "round up", "round down", "round half up", "round half down",
    # boolean
    "is",
    # range (DMN §10.3.4.6) — first-class range values + Allen interval relations
    "range",
    "before", "after", "meets", "met by", "overlaps", "overlaps before",
    "overlaps after", "finishes", "finished by", "includes", "during",
    "starts", "started by", "coincides",
    # temporal constructors & clock (ADR-18)
    "date", "time", "date and time", "duration", "years and months duration",
    "now", "today",
    # temporal component functions (ADR-18)
    "day of week", "day of year", "week of year", "month of year",
})

# Built-ins that have **no** named-parameter form (feel-core, ADR-23): the purely
# variadic / dual-form aggregates and the varargs list builders. The spec gives
# them no single named-parameter signature, so feel-core's `builtin_param_names`
# table omits them and a named call to one (`sum(list: …)`, `all(list: …)`) is an
# error-null — even though the spec result would be a real value. A named call to
# one of these is therefore *not* in the slice and must stay skipped (keeping it
# would be a false positive: the TCK expects the real result, feel-core returns
# null). Every name here is single-word, which keeps the reject scan simple.
_NO_NAMED_FORM_BUILTINS = frozenset({
    "min", "max", "sum", "mean", "product", "median", "stddev", "mode",
    "all", "any", "append", "concatenate", "union",
})


def _balanced_bracket_group(rhs: str) -> bool:
    """`rhs` begins with `[` or `(`: true iff that opening bracket has a matching close
    (a balanced leading group). Covers both a *single* interval `[a..b]` and the
    comma-list / parenthesised test-list forms (`[2,3,1]`, `(false,true)`,
    `(1,<5,>=10)`, `[[a..b],[c..d]]`, `(=10)`) — all positive unary tests after `in`
    (Form 1). A close with nothing open (the reverse-bracket `]a..b]`) is rejected; the
    broader reverse-bracket / unbalanced detection lives in the `..` scan in
    `fits_slice_grammar`."""
    depth = 0
    for c in rhs:
        if c in "[(":
            depth += 1
        elif c in "])":
            depth -= 1
            if depth < 0:
                return False
            if depth == 0:
                return True
    return False  # unbalanced


def _value_range_brackets_ok(s: str) -> bool:
    """True if every `..` in value-position `s` sits inside a bracketed range literal /
    interval feel-core parses — INCLUDING the reverse-bracket spellings `]a..b]`
    (exclusive lower, ≡ `(a..b]`) and `[a..b[` (exclusive upper, ≡ `[a..b)`) and the
    UNBOUNDED spellings `[1..)` / `(..10]` / `(..)` (an omitted endpoint is `±∞`, valid
    only behind an OPEN bracket per grammar rule 66; a closed `[1..]` / `[..10]` does NOT
    parse — ADR-31), all shipped now. The structural balance check accepts the unbounded
    `..` (it still sits inside its bracket group); the open-bracket requirement on an
    omitted endpoint is enforced by the parser, not here (and the DMN-TCK has no
    value-position unbounded literal anyway — `range("[1..]")` is a blanked string). A
    scan that does NOT require bracket *types* to match: FEEL intervals legitimately mix
    `[`/`(`/`]` (`(1..2]`), so an opener and a closer pair by nesting alone. Reverse
    roles resolve positionally — a `]` with nothing open is a reverse-open opener; a `[`
    whose innermost group already holds a `..` is a reverse-close closer. Rejects a bare
    top-level `..` and stray / unbalanced brackets;
    a few exotic shapes not in the TCK (a reverse-open as a list's first element,
    `[a..[list]]`) are conservatively skipped rather than risk a false positive (which
    would crash the closed-loop fixture test)."""
    stack: list[bool] = []  # one flag per open group: has a `..` been seen inside it
    i = 0
    while i < len(s):
        if s[i : i + 2] == "..":
            if not stack:
                return False  # bare top-level `..`
            stack[-1] = True
            i += 2
            continue
        c = s[i]
        if c == "(":
            stack.append(False)
        elif c == "[":
            if stack and stack[-1]:  # inside a `..` group -> reverse-close `[a..b[`
                stack.pop()
            else:
                stack.append(False)
        elif c == "]":
            if stack:
                stack.pop()
            else:  # nothing open -> reverse-open `]a..b]`
                stack.append(False)
        elif c == ")":
            if not stack:
                return False  # close with nothing open
            stack.pop()
        i += 1
    return not stack  # leftover open group -> unbalanced


def _in_rhs_supported(after: str) -> bool:
    """True if the text after a membership `in` is a slice-supported positive unary
    test: a single comparison `<op> endpoint` (`< 10`, `= e`, `!= e`), a bracket/paren
    group — a single interval `[a..b]`/`(a..b)` OR a comma-list / parenthesised list of
    tests (`[2,3,1]`, `(false,true)`, `(1,<5,>=10)`, `[[a..b],[c..d]]`, `(=10)`), all
    now parsed as positive unary tests (Form 1) — a `not(…)` *test negation*
    (`not(1,2,3)`, `not(<5)`, `not([1..10])`; DMN rule 49, ≡ `not(x satisfies t)`) — or
    a *bare endpoint* expression: a scalar (`1 in 1` is `1 = 1`) or an expression
    yielding a range (`2 in range("[1..3]")` is membership). Endpoints may be function
    calls; names are pre-validated by the free-name scan in `fits_slice_grammar`."""
    t = after.lstrip()
    # `not(…)` after `in` is unary-test negation, parsed by the dedicated `InRhs`
    # production (never the boolean built-in). Validate the parenthesised test list as
    # a balanced group, exactly like a bare bracket group.
    m = re.match(r"not\b\s*", t)
    if m:
        rest = t[m.end() :]
        return rest[:1] == "(" and _balanced_bracket_group(rest)
    if re.match(r"<=|>=|!=|<|>|=", t):
        return True
    if t[:1] in "[(":
        return _balanced_bracket_group(t)
    # A bare non-bracket endpoint (a scalar, a variable, or a `range(…)` call): the
    # free-name scan in `fits_slice_grammar` has already validated every name here.
    return True


def strip_comments(expr: str) -> str:
    """Remove FEEL Java-style comments (`//…\\n` and `/*…*/`) from `expr`.

    String-aware: characters inside double-quoted literals are preserved as-is,
    so `"http://x"` and `"/* not a comment */"` are never mangled.
    Block comments do not nest (per the FEEL spec).
    """
    out: list[str] = []
    i = 0
    n = len(expr)
    while i < n:
        c = expr[i]
        if c == '"':
            # consume the whole quoted string verbatim
            j = i + 1
            while j < n and expr[j] != '"':
                if expr[j] == '\\':
                    j += 1  # skip escaped char
                j += 1
            out.append(expr[i : j + 1])
            i = j + 1
        elif expr[i : i + 2] == "//":
            # EOL comment — skip to (but not including) the newline
            i += 2
            while i < n and expr[i] != '\n':
                i += 1
        elif expr[i : i + 2] == "/*":
            # block comment — skip to closing */
            i += 2
            while i < n and expr[i : i + 2] != "*/":
                i += 1
            i += 2  # skip the closing */
        else:
            out.append(c)
            i += 1
    return "".join(out)


def _fn_literal_params_and_blank(scan: str) -> tuple[set[str], str]:
    """Find all ``function(…)`` heads in *scan*, extract formal parameter *names*
    (stripping any ``: type`` annotation — including nested ``context<…>`` generics
    — from typed params), and return the combined set of parameter names together
    with a copy of *scan* in which every ``function(…)`` head has been replaced by
    spaces.  The body that follows each head is left intact so the outer free-name
    scan can validate it; the parameter names are added to the ``allowed`` set so
    references to them inside the body are not flagged as free identifiers.

    Examples::

        function(a, b) body                         → params={a, b},  head blanked
        function(arg: number) body                  → params={arg},   head blanked
        function(ctx: context<name: string>) body   → params={ctx},   head blanked
        function() body                             → params={},      head blanked
    """
    params: set[str] = set()
    result = list(scan)
    for m in re.finditer(r"\bfunction\s*\(", scan):
        # Locate the matching closing ')' of the parameter list using depth tracking.
        paren_open = m.end() - 1  # index of the '(' in scan
        depth = 0
        j = paren_open
        while j < len(scan):
            c = scan[j]
            if c == "(":
                depth += 1
            elif c == ")":
                depth -= 1
                if depth == 0:
                    break
            j += 1
        # scan[paren_open + 1 : j] is the raw parameter list, e.g.
        # "" or "a, b" or "arg: number" or "ctx: context<name: string, age: number>".
        params_str = scan[paren_open + 1 : j]
        # Split by top-level commas (not those nested inside `< … >`).
        parts: list[str] = []
        cur: list[str] = []
        angle = 0
        for ch in params_str:
            if ch == "<":
                angle += 1
                cur.append(ch)
            elif ch == ">":
                angle -= 1
                cur.append(ch)
            elif ch == "," and angle == 0:
                parts.append("".join(cur))
                cur = []
            else:
                cur.append(ch)
        if cur:
            parts.append("".join(cur))
        for part in parts:
            part = part.strip()
            # The name is the token before the first `:` (typed param) or the
            # whole token (bare param).
            name_part = part.split(":")[0].strip() if ":" in part else part
            if re.match(r"^[A-Za-z_]\w*$", name_part):
                params.add(name_part)
        # Blank the entire `function(…)` head so type annotations and param names
        # inside the parens can never be mistaken for free identifiers.
        for k in range(m.start(), j + 1):
            result[k] = " "
    return params, "".join(result)


def fits_slice_grammar(expression: str, input_names: frozenset[str] = frozenset()) -> bool:
    """True if feel-core's core-language grammar can parse AND evaluate
    `expression` against a context built from `input_names` (the case's
    `<inputNode>` names). A name is acceptable if it is a keyword, a
    for/some/every loop variable, a context-literal key, a member access
    (`.field`), or one of `input_names`. Any other free name (a built-in
    function such as `date`/`abs`, or an input we did not capture) puts the
    expression outside the slice. Out-of-scope syntax (temporal `@` literals,
    filters, parenthesised range tests, multiple iteration contexts, …) is also
    rejected.

    This is a conservative heuristic: it prefers to skip a borderline case over
    keeping one feel-core cannot handle (a false positive would crash the
    fixture test). The closed loop validates the rest — `cargo test -p feel-core`
    asserts every kept case actually evaluates."""
    # Strip Java-style comments before any other scan so comment text is never
    # mistaken for free identifiers or operators.
    expression = strip_comments(expression)
    # Blank out string literals so their contents never look like identifiers,
    # operators or brackets. Temporal `@"…"` literals are in scope now (ADR-18);
    # blanking the quoted part leaves a lone `@`, which the scans below ignore.
    s = re.sub(r'"[^"]*"', " ", expression)

    # `instance of` type predicate (DMN §10.3.2.9). The right operand is a restricted
    # type expression, not a general expression, so validate it on its own and then
    # reduce `s` to the value expression for the remaining scans. Only the single
    # `value instance of type` form is in the slice (no trailing `and`/`or`, which
    # 0070 never uses). The type must use only built-in/`Any`/`Null` type words plus
    # the generic punctuation `< > , : ->`; context-type field keys (`k:`) are blanked
    # first, exactly like context-literal keys on the value side. An unrecognised type
    # name (a model itemDefinition type) puts the case outside the self-contained
    # slice, as does an unimplemented built-in.
    if re.search(r"\binstance\s+of\b", s):
        parts = re.split(r"\binstance\s+of\b", s)
        if len(parts) != 2:
            return False
        value_expr, type_expr = parts
        type_scan = re.sub(r"[A-Za-z_]\w*\s*:", " ", type_expr)  # drop `k:` field keys
        type_idents = re.findall(r"[A-Za-z_]\w*", type_scan)
        if any(tok not in (_TYPE_WORDS | {"and"}) for tok in type_idents):
            return False
        s = value_expr

    # A parenthesised comparison test in *value* position — `(< 10)`, `(=10)`,
    # `(!=10)` — is now an OPAQUE unary-test value (ADR-32): `Primary → "(" CmpOp Sum
    # ")"`, an opaque `Value::UnaryTestVal` with reflexive, range-incompatible equality.
    # So the paren form is SUPPORTED, in value position as well as directly after a
    # membership `in` (the one-element paren test-list `x in (=10)`; ADR-28). Only the
    # bracket-led leading comparison `[< 10]` has no grammar production, so it stays out
    # of the slice — and, as before, only when it does not directly follow an `in` (a
    # bracket test-list `x in [<5, >10]` is a supported positive unary test).
    for _m in re.finditer(r"\[\s*(?:<=|>=|!=|<|>|=)", s):
        if not re.search(r"(?:^|[^\w])in\s*$", s[: _m.start()]):
            return False

    # Multiple iteration contexts (`for i in a, j in b …`; ADR-25) are in the slice
    # now. The subsequent `, name in` variables are added to `bound` below and the
    # `, name in` clause is recognised as an iterator `in` in the membership scan.

    # Named-argument calls `f(name: value)` are in the slice now (ADR-23): feel-core
    # binds them via a per-built-in parameter-name table (FEEL spec §10.3.2.13.5).
    # The parameter names themselves are blanked alongside context-literal keys in
    # the free-name scan below, so an in-scope named call to a built-in fits. Two
    # named forms stay out of the slice, both handled here:
    #   * a named call to a variadic aggregate / varargs builder, which has no named
    #     form in feel-core (error-null vs. the spec's real result) — see
    #     `_NO_NAMED_FORM_BUILTINS`;
    #   * a named call whose head is not a built-in (a user-defined function), which
    #     the free-name scan rejects anyway because the head is a free name.
    # The pattern is anchored on `(` (context literals open with `{`), so it never
    # matches `{key: …}`.
    _variadic_heads = "|".join(sorted(_NO_NAMED_FORM_BUILTINS, key=len, reverse=True))
    if re.search(r"\b(?:" + _variadic_heads + r")\s*\(\s*[A-Za-z_][\w ]*?\s*:", s):
        return False

    # Postfix list filter / index `value[…]` (`[1,2,3][1]`, `xs[item > 2]`) is in
    # the slice now (DMN §10.3.2.5). The implicit element name `item` it binds is
    # handled as an allowed free name below; the `[…]` itself needs no special
    # casing here (a `[` in value position is a list literal, after a value a
    # subscript — both parse).

    # Free identifiers: not a keyword, not a loop variable bound by an enclosing
    # for/some/every, not a captured input name. Member segments (`.field`) and
    # context-literal keys (`field:`) are structural, not free names, so blank
    # them out before scanning. The single-dot match excludes `..` ranges. A member
    # name may be multi-word (`.start included`, `.end included`, `.time offset`; the
    # lexer joins adjacent name words, ADR-17), so consume a run of words after the
    # dot — stopping at a keyword, exactly as the lexer's join stops at a keyword
    # token (so `a.b and c` keeps `and c`).
    _kw_alt = "|".join(sorted(_KEYWORDS, key=len, reverse=True))
    scan = re.sub(
        r"(?<!\.)\.(?!\.)\s*[A-Za-z_]\w*(?:\s+(?!(?:" + _kw_alt + r")\b)[A-Za-z_]\w*)*",
        " ",
        s,
    )  # drop `.field` (incl. multi-word members)
    # Extract function-literal formal parameters and blank all `function(…)` heads.
    # IMPORTANT: this must happen BEFORE the context-key blanker below, because a
    # typed formal parameter `arg: number` looks exactly like a `key: value` pair to
    # that regex — if the key blanker ran first, it would destroy `arg` before we
    # could record it as a bound name.  By running here, we blank the entire
    # `function(…)` head (param list + type annotations) and collect the raw param
    # names, so neither the names nor the type annotations can trigger a false
    # "free identifier" alarm later.
    fn_params, scan = _fn_literal_params_and_blank(scan)
    # Drop context-literal keys and named-argument parameter names (`key:`). Both
    # may be multi-word FEEL names (`{full name: …}`, `substring(start position: …)`,
    # `number(decimal separator: …)`), so consume the whole space-separated run up to
    # the colon — a `:` only follows a context key or a named-argument name (string
    # and temporal literals are already blanked), and `{`/`(`/`,` break the run, so
    # this never swallows a keyword or operand.
    scan = re.sub(r"(?:[A-Za-z_]\w*\s+)*[A-Za-z_]\w*\s*:", " ", scan)
    # Drop implemented built-in call heads (`abs(`, `string length(`, …) so they
    # aren't treated as free names. Arguments keep being scanned, so a call whose
    # args reference an unknown name is still skipped. Multi-word heads (ADR-17)
    # may have any whitespace between parts, and are tried longest-first so a
    # multi-word head wins over a single-word prefix (`substring before` over
    # `substring`).
    heads = sorted(_BUILTINS, key=len, reverse=True)
    head_pat = "|".join(re.escape(b).replace(r"\ ", r"\s+") for b in heads)
    scan = re.sub(r"\b(?:" + head_pat + r")\s*\(", "(", scan)
    # Multi-word input names (`full name`, ADR-17) are single names; blank them
    # before the per-word scan so their parts aren't seen as free identifiers.
    for n in sorted((n for n in input_names if " " in n), key=len, reverse=True):
        scan = re.sub(r"\b" + re.escape(n).replace(r"\ ", r"\s+") + r"\b", " ", scan)
    bound = set(re.findall(r"\b(?:for|some|every)\s+([A-Za-z_]\w*)\s+in\b", scan))
    # Subsequent iteration contexts `…, j in b` bind further loop variables (ADR-25).
    bound |= set(re.findall(r",\s*([A-Za-z_]\w*)\s+in\b", scan))
    # `item` is the implicit element name a filter predicate `xs[item > 2]` binds
    # (DMN §10.3.2.5). It is only in scope inside a `[…]`, but allowing it globally
    # here is a safe over-approximation: an `item` used outside a filter would just
    # evaluate to null, and the TCK filter cases all reference it inside `[…]`.
    allowed = _KEYWORDS | {"item"} | bound | set(input_names) | fn_params
    idents = re.findall(r"[A-Za-z_]\w*", scan)
    if any(tok not in allowed for tok in idents):
        return False

    # `..` is only valid as a bare iteration range (`for i in a..b`) or inside a
    # membership interval (`x in [a..b]`).
    if ".." in s:
        if re.search(r"\b(?:for|some|every)\b", s):
            # In an iteration, ranges must be bare — reject any bracketed `..`.
            if re.search(r"[\[(][^\[\]()]*\.\.", s):
                return False
            # Note: iteration ranges are integer-only in feel-core. The two *date*
            # ranges the TCK expects to yield a day-by-day list are skipped by id
            # (`TEMPORAL_FOR_RANGE_SKIPS`); datetime/time/duration ranges yield null
            # in both the TCK and feel-core, so they stay in the slice.
        else:
            # Outside an iteration, a `..` is legal inside a *bracketed* range literal
            # / interval — a first-class range value (`[18..21] = [18..21]`,
            # `[1..10] instance of range<number>`, `]1..10].start`) or a
            # membership-interval RHS (`x in [a..b]`, validated further by the
            # membership scan below). The reverse-bracket spellings `]a..b]` / `[a..b[`
            # and the open-bracket unbounded spellings `[1..)` / `(..10]` (ADR-31) are in
            # scope now (shipped), so the structural scan accepts them and
            # rejects only a bare top-level `..` or genuinely unbalanced brackets.
            if not _value_range_brackets_ok(s):
                return False

    # Membership `in` (not a for/some/every iterator). The slice supports a single
    # comparison test (`x in < y`, `x in = y`) or a single interval (`x in [a..b]`,
    # endpoints may be function calls). The comma-list and bare-equality forms are
    # out of slice (deferred) — see `_in_rhs_supported`.
    for m in re.finditer(r"\bin\b", s):
        before = s[: m.start()]
        if re.search(r"\b(?:for|some|every)\s+[A-Za-z_]\w*\s*$", before):
            continue  # the first iterator `in`, handled above
        # A subsequent multi-context iterator `in` (`…, j in b`; ADR-25): `before`
        # ends with `, name`, and a for/some/every keyword opens the expression.
        if re.search(r",\s*[A-Za-z_]\w*\s*$", before) and re.search(
            r"\b(?:for|some|every)\b", before
        ):
            continue
        if not _in_rhs_supported(s[m.end() :]):
            return False

    return True


# --------------------------------------------------------------------------- #
# Extracted, pre-deviation test case
# --------------------------------------------------------------------------- #


@dataclass
class Case:
    id: str
    expression: str
    expected: object  # JSON-serialisable: number | bool | None
    expected_type: str  # "number" | "boolean" | "null"
    comparison: str = "exact"
    deviation: Optional[str] = None
    epsilon: Optional[float] = None
    # Optional §10.3.2.9.4 coercion target type (structural FEEL type string, e.g.
    # "string", "list<number>", "context<name: string, age: number>"). When set, the
    # fixture test applies `coerce(result, parse_type(coerce_to))` after evaluation,
    # modelling the decision-variable / literalExpression `typeRef` boundary
    # (0082-feel-coercion).
    coerce_to: Optional[str] = None
    # The case's `<inputNode>` values, mapped name -> JSON value. Bound as the
    # evaluation context by the fixture test. Omitted from the fixture if empty.
    context: dict = field(default_factory=dict)

    def to_fixture(self) -> dict:
        out = {
            "id": self.id,
            "expression": self.expression,
            "expected": self.expected,
            "expected_type": self.expected_type,
            "comparison": self.comparison,
            "deviation": self.deviation,
        }
        if self.coerce_to is not None:
            out["coerce_to"] = self.coerce_to
        if self.context:
            out["context"] = self.context
        if self.epsilon is not None:
            out["epsilon"] = self.epsilon
        return out


# --------------------------------------------------------------------------- #
# Deviation registry
# --------------------------------------------------------------------------- #

# feel-core uses f64 where the spec uses decimal128. For numeric results we
# therefore compare with a tolerance instead of exact equality. The tolerance
# also has to absorb the TCK's own rounding: non-terminating results (e.g.
# `exp`/`log`) are given to a fixed number of decimal places (8 -> up to 5e-9 of
# truncation error), which a 1e-9 tolerance would reject as a false negative.
F64_EPSILON = 1e-8
F64_DEVIATION_NOTE = (
    "feel-core uses f64 arithmetic while the DMN/FEEL spec mandates decimal128, "
    "and the TCK rounds non-terminating results to a fixed number of decimal "
    "places; numeric results are therefore compared with an epsilon tolerance "
    "instead of exact equality to avoid false negatives from either source."
)


@dataclass
class DeviationRule:
    name: str
    description: str
    applies: Callable[[Case], bool]
    transform: Callable[[Case], None]
    # Filled in at runtime for the summary.
    applied_count: int = field(default=0)


def _decimal_f64_applies(case: Case) -> bool:
    return case.expected_type == "number"


def _decimal_f64_transform(case: Case) -> None:
    case.comparison = "f64_epsilon"
    case.epsilon = F64_EPSILON
    case.deviation = F64_DEVIATION_NOTE


_TEMPORAL_TYPES = {"date", "time", "date and time", "duration"}
TEMPORAL_DEVIATION_NOTE = (
    "Temporal result compared in feel-core's canonical ISO-8601 form (ADR-18). "
    "feel-core backs temporal values with jiff; at the wrappers they cross the "
    "boundary as ISO-8601 strings, so PostgreSQL can cast to date/timestamptz/"
    "interval (ADR-5's interval mapping) and WASM can return JS Date objects."
)


def _temporal_applies(case: Case) -> bool:
    return case.expected_type in _TEMPORAL_TYPES


def _temporal_transform(case: Case) -> None:
    # The expectation is kept as the canonical ISO string; the fixture test parses
    # it into a temporal Value and compares structurally. Only the provenance note
    # is attached (no value rewrite — the TCK lexical form is already canonical).
    case.deviation = TEMPORAL_DEVIATION_NOTE


# Registry: add future deviations here as additional DeviationRule entries.
# Only the DECIMAL/F64 rule is implemented; the rest are intentional, documented
# placeholders (their predicate never matches yet).
DEVIATION_RULES: list[DeviationRule] = [
    DeviationRule(
        name="decimal-vs-f64",
        description="Numeric results: compare with epsilon (decimal128 vs f64).",
        applies=_decimal_f64_applies,
        transform=_decimal_f64_transform,
    ),
    # --- Placeholders (not yet implemented) ----------------------------------
    DeviationRule(
        name="temporal-interval-mapping",
        description=(
            "date/time/duration results compared in feel-core's canonical "
            "ISO-8601 form; documents the wrappers' boundary mapping (ADR-18, "
            "and ADR-5's PostgreSQL interval mapping)."
        ),
        applies=_temporal_applies,
        transform=_temporal_transform,
    ),
    DeviationRule(
        name="string-edge-cases",
        description=(
            "PLACEHOLDER: string normalisation / unicode edge cases once strings "
            "are a runtime Value."
        ),
        applies=lambda _case: False,
        transform=lambda _case: None,
    ),
    DeviationRule(
        name="regex-xpath-dialect",
        description=(
            "DOCUMENTED: replace/split/matches use Rust's `regex` crate, whose "
            "dialect differs from the spec's normative XQuery/XPath 2.0 F&O regex "
            "(backreferences in the pattern, the `q` flag, XML-schema character "
            "classes). The common TCK cases match identically; any case that fails "
            "purely from a dialect difference is excluded via REGEX_DIALECT_SKIPS "
            "below (not silently rewritten). Revisit with a dialect translator."
        ),
        applies=lambda _case: False,
        transform=lambda _case: None,
    ),
]

# Case ids (model_stem:testCase:resultNode) whose only failure is the regex
# dialect gap documented by the `regex-xpath-dialect` deviation above. These are
# skipped during extraction so the closed loop stays green without faking a
# result. Each needs an XQuery/XPath 2.0 F&O regex feature Rust's `regex` crate
# cannot reproduce (backreferences; XML-Schema class subtraction `[A-Z-[OI]]`;
# `\p{IsBasicLatin}` block names; `x`-flag whitespace handling inside classes),
# or an XPath string escape (`K`, `\n`) the slice's string lexer does not
# decode yet (note: basic FEEL string escapes — `\n`/`\t`/`\uXXXX`/… — ARE decoded
# by the lexer now, so the remaining entries are true regex-dialect gaps). Revisit
# alongside a dialect translator.
REGEX_DIALECT_SKIPS: frozenset[str] = frozenset({
    "1111-feel-matches-function:K2-MatchesFunc-1:K2-MatchesFunc-1",
    "1111-feel-matches-function:K2-MatchesFunc-2:K2-MatchesFunc-2",
    "1111-feel-matches-function:K2-MatchesFunc-3:K2-MatchesFunc-3",
    "1111-feel-matches-function:K2-MatchesFunc-4:K2-MatchesFunc-4",
    "1111-feel-matches-function:K2-MatchesFunc-5:K2-MatchesFunc-5",
    "1111-feel-matches-function:K2-MatchesFunc-6:K2-MatchesFunc-6",
    "1111-feel-matches-function:K2-MatchesFunc-17:K2-MatchesFunc-17",
    "1111-feel-matches-function:caselessmatch07:caselessmatch07",
    "1111-feel-matches-function:caselessmatch10:caselessmatch10",
    "1111-feel-matches-function:caselessmatch11:caselessmatch11",
    "1111-feel-matches-function:fn-matches-27:fn-matches-27",
    "1111-feel-matches-function:fn-matches-28:fn-matches-28",
    # `matches("Mary\\u000DJones", "Mary.Jones")`: now that the lexer decodes the
    # `\\u000D` carriage return, this exposes the `.` dialect difference — XPath's
    # `.` excludes CR (TCK expects false), Rust's `.` matches CR (would give true).
    # Before escape decoding the literal text failed to match, so the case passed by
    # accident; it is a genuine regex-dialect skip now.
    "1111-feel-matches-function:fn-matches-45:fn-matches-45",
})

# Case ids whose only failure is jiff's representable range, not a semantics gap
# (ADR-18). jiff's `civil::Date` caps the year at ±9999 and its `Span` caps the
# years/months magnitude, so the TCK's extreme-range dates/durations (and the
# odd `duration("PT0.S")` lexical form jiff rejects) cannot round-trip. Skipped
# here so the closed loop stays green without faking a result. Revisit if jiff
# widens its range or we special-case the parser.
TEMPORAL_RANGE_SKIPS: frozenset[str] = frozenset({
    # years beyond ±9999 (date / date and time)
    "1115-feel-date-function:015_1dd66594cf:feel-date-function_015_1dd66594cf",
    "1115-feel-date-function:016_31f3fef4a0:feel-date-function_016_31f3fef4a0",
    "1115-feel-date-function:029_88f5c7c90f:feel-date-function_029_88f5c7c90f",
    "1115-feel-date-function:030_9184a7bfc3:feel-date-function_030_9184a7bfc3",
    "1117-feel-date-and-time-function:011_eec2d5bdcd:feel-date-and-time-function_011_eec2d5bdcd",
    "1117-feel-date-and-time-function:012_225a105eef:feel-date-and-time-function_012_225a105eef",
    "1117-feel-date-and-time-function:027_ae365197dd:feel-date-and-time-function_027_ae365197dd",
    "1117-feel-date-and-time-function:028_1c3d56275f:feel-date-and-time-function_028_1c3d56275f",
    # durations beyond jiff's Span range, and the `PT0.S` lexical form jiff rejects
    "1120-feel-duration-function:011_2169615b94:feel-duration-function_011_2169615b94",
    "1120-feel-duration-function:034_aa9cbb21a6:feel-duration-function_034_aa9cbb21a6",
    "1120-feel-duration-function:035_93eef01ae7:feel-duration-function_035_93eef01ae7",
    "1120-feel-duration-function:036_5f2775875e:feel-duration-function_036_5f2775875e",
    "1120-feel-duration-function:037_8c9ea9c0e6:feel-duration-function_037_8c9ea9c0e6",
})

# Case ids that assert time/date-and-time equality at *second* resolution — the
# TCK treats values differing only in sub-second fraction as equal ("value
# resolution is seconds"). feel-core backs temporal values with jiff at
# nanosecond precision and compares them structurally (ADR-18), so `.0001` and
# `.0002` are genuinely distinct; matching the TCK here would mean discarding
# sub-second precision from equality, a lossy change we decline to make. Skipped
# so the closed loop stays green without weakening the comparison.
TEMPORAL_SUBSECOND_EQUALITY_SKIPS: frozenset[str] = frozenset({
    "0068-feel-equality:datetime_003_a:datetime_003_a",
    "0068-feel-equality:time_005:time_005",
})

# Case ids asserting that a *cross-type* equality test is `false` (DMN reads
# `true = 2`, `[1,2,3] = 1`, … as false). feel-core deliberately makes a non-null
# type mismatch under `=`/`!=` an error-null instead — a conscious "incomparable ⇒
# unknown" reading (ADR-14), unit-tested as `100 = "100"` → error and `{a: 1} = 1`
# → null. So `true in [false, 2, 3]` OR-folds to null where the TCK wants false.
# Exactly one 0072 membership case rides on this (the bracket/paren list parsing
# itself, Form 1, is unaffected). Skipped so the closed loop stays green without
# weakening `=`; aligning cross-type equality with the TCK's `false` is a separate
# semantics decision (its own ADR) — see ROADMAP.
CROSS_TYPE_EQUALITY_SKIPS: frozenset[str] = frozenset({
    "0072-feel-in:boolean_001_a:boolean_001_a",
})

# Named-argument calls that name a built-in *overload* whose parameter name
# feel-core's single-row parameter table cannot carry (ADR-23). The grammar parses
# these and the head is an in-slice built-in, but the bind fails, so the result is
# error-null instead of the spec value — skipped so the closed loop stays green
# without faking a result (positional forms of all of these are ingested and pass).
#   * Temporal constructors `date`/`time`/`date and time` invoked as `(from: …)`:
#     each has a `from` single-arg overload, but feel-core's table holds the
#     *component* names (`year`/`month`/`day`, `hour`/`minute`/`second`/`offset`,
#     `date`/`time`) so the two overloads can share one positional row — there is
#     no slot named `from`, so `from` is an unknown name → null.
#   * `context put` invoked with the deep-put overload by name: feel-core carries a
#     single `key` parameter and resolves the key-vs-keys (string-vs-list) overload
#     by the value's type, so the spec's distinct `keys` name is unknown (`nested007`
#     → null instead of a deep put) and a list passed to `key` deep-puts where the
#     spec wants a type-error null (`nested008`).
NAMED_ARG_OVERLOAD_SKIPS: frozenset[str] = frozenset({
    # temporal constructors: the `from` overload's name is absent from the table
    "1115-feel-date-function:050_8f1e299951:feel-date-function_050_8f1e299951",
    "1115-feel-date-function:051_ad98079864:feel-date-function_051_ad98079864",
    "1116-feel-time-function:080_2bbb8c86af:feel-time-function_080_2bbb8c86af",
    "1116-feel-time-function:081_69f4e0231e:feel-time-function_081_69f4e0231e",
    "1117-feel-date-and-time-function:086_12ca8ac1d3:feel-date-and-time-function_086_12ca8ac1d3",
    # `context put` deep-put overload reached by name (key/keys, string/list)
    "1146-feel-context-put-function:nested007:nested007",
    "1146-feel-context-put-function:nested008:nested008",
})

# `for`/`some`/`every` iteration ranges (`a..b`) are implemented only over
# integers (README "What the slice can evaluate"; spec §10.3.2.10). A *date* range
# iterates day-by-day in the spec, so the TCK expects `for i in
# @"1980-01-01"..@"1980-01-03"` (and its descending twin) to yield the three
# dates — but feel-core builds no temporal range iterator, so it evaluates to null.
# The grammar parses the range (the `@` literals are in scope, ADR-18), so the
# slice detector keeps it; these two ascending/descending date-range cases are
# skipped here instead. The datetime / time / duration range cases in the same dir
# (`decision_020`-`022`) are *not* skipped: the TCK yields null for them too, so
# feel-core's null already matches.
TEMPORAL_FOR_RANGE_SKIPS: frozenset[str] = frozenset({
    "0084-feel-for-loops:decision_017:decision_017",
    "0084-feel-for-loops:decision_018:decision_018",
})

# Individually out-of-scope cases whose *expression* fits the slice but whose
# *expected* result comes from a DMN feature feel-core does not model (so the bare
# expression evaluates to a different, correct-for-the-expression value). Not bugs
# in the engine and not broken TCK cases — just outside a FEEL-expression engine.
#   * 0021 `decision2`/`decision4`/`decision5`: implicit singleton-list ↔ scalar
#     coercion (§10.3.2.9.4). `sublist(…)`/`Employees[item="Bob"]` yield a singleton
#     *list*, which the TCK coerces to a scalar at the decision's declared scalar
#     output type (`decision2`/`decision4`) or as a string function argument
#     (`decision5`: `upper case(["Bob"]) = "BOB"`). feel-core does not auto-coerce a
#     singleton list to its element, so its `["…"]`/null is the right *expression*
#     value. The list-typed twins `decision1`/`decision3` are kept (and pass).
OUT_OF_SCOPE_EXPR_SKIPS: frozenset[str] = frozenset({
    "0021-singleton-list:001:decision2",
    "0021-singleton-list:001:decision4",
    "0021-singleton-list:001:decision5",
    # 1131 decision002 (`null()`) was here until ADR-38 added value-invocation.
})

# Named-zone literals feel-core's eager `TimeZone::get` validation rejects in the
# build's tzdb, so the `@"…@Zone"` literal is an error-null and any expression over
# it is null. A temporal-parsing/tzdb limitation (ADR-18), independent of the
# function under test. `Etc/GMT` fails here while ordinary `Area/City` zones (e.g.
# `Australia/Melbourne`) resolve, so only this one `is`-case is affected.
TZDB_ZONE_SKIPS: frozenset[str] = frozenset({
    "0103-feel-is-function:time_007:time_007",  # is(@"23:00:50@Etc/GMT", @"23:00:50Z")
})

# Context keys written as a bare *emoji* (`{🐎: "bar"}`). feel-core's name lexer
# accepts a Unicode identifier (XID-start then XID-continue), but an emoji is not an
# XID character, so a bare emoji key does not parse — the same "no special
# characters in names" scope boundary the README documents (ADR-17). The
# string-valued unicode cases in the same suite (`string length("🐎😀")`,
# `"\U01F40E" = "🐎"`, …) are kept and pass — emoji in *strings* work fine.
NON_XID_NAME_SKIPS: frozenset[str] = frozenset({
    "0083-feel-unicode:decision_006:decision_006",  # {🐎: "bar"}
    "0083-feel-unicode:decision_007:decision_007",  # {🐎: "😀"}
})

# ADR-24 (filter) and ADR-13/ADR-14 (quantifier short-circuit / sticky provenance):
# Three cases where feel-core's documented design produces a result that differs from
# the TCK expectation for a non-true predicate / short-circuiting quantifier.
#
# 1151-boxed-filter:004 — [1,2,3,4,5]["not a boolean"]
#   TCK expects null; feel-core returns [] (non-true predicate silently drops the
#   element per ADR-24 "Filter scope … Non-true predicate results drop the element").
#
# 1151-boxed-filter:005 — [1,2,3,4,5][if (item<=3) then true else "not a boolean"]
#   TCK expects null; feel-core returns [1,2,3] (same ADR-24 rule).
#
# 1153-boxed-some:006 — some element in [1,2] satisfies if (element=2) then true else …
#   TCK expects null; feel-core returns true because `some` short-circuits on the
#   first true (ADR-13/14 sticky-provenance: the dominating true wins regardless of
#   a subsequent non-boolean taint).
# The f64_epsilon comparison mode only works for scalar numbers; list results that
# contain floating-point numbers computed from decimal128 by the TCK reference
# implementation cannot be compared element-wise with epsilon tolerance.  These
# cases are skipped until the harness gains a list-numeric epsilon mode.
DECIMAL_LIST_SKIPS: frozenset[str] = frozenset({
    "0003-iteration:001:MonthlyPayment",  # [PMT2(loan1), PMT2(loan2)] — list of f64-imprecise numbers
})

BOXED_PREDICATE_DEVIATION_SKIPS: frozenset[str] = frozenset({
    "1151-boxed-filter:004:decision004",
    "1151-boxed-filter:005:decision005",
    "1153-boxed-some:006:decision006",
})


def apply_deviations(case: Case) -> None:
    """Run every registry rule whose predicate matches `case` (mutates in place)."""
    for rule in DEVIATION_RULES:
        if rule.applies(case):
            rule.transform(case)
            rule.applied_count += 1


# --------------------------------------------------------------------------- #
# XML extraction (hard-wired to the literal-expression test form)
# --------------------------------------------------------------------------- #


def _local(tag: str) -> str:
    """Strip the XML namespace from a tag, leaving the local name."""
    return tag.rsplit("}", 1)[-1]


def resolve_inputs(path: Path) -> tuple[Path, Path]:
    """Return (dmn_path, test_xml_path) from a directory or .dmn file path."""
    if path.is_dir():
        dmns = sorted(path.glob("*.dmn"))
        if not dmns:
            sys.exit(f"no .dmn file found in {path}")
        dmn = dmns[0]
    elif path.suffix == ".dmn":
        dmn = path
    else:
        sys.exit(f"expected a TCK test directory or a .dmn file, got {path}")

    tests = sorted(dmn.parent.glob("*-test-*.xml"))
    if not tests:
        sys.exit(f"no *-test-*.xml file found next to {dmn}")
    return dmn, tests[0]


def parse_decisions(dmn_path: Path) -> dict[str, str]:
    """Map decision name -> literalExpression text.

    Only decisions whose *direct* logic child is a `<literalExpression>` are
    kept. Decisions backed by a `<relation>`, `<context>` or `<decisionTable>`
    are skipped — descending into them would wrongly mine an inner expression
    cell (e.g. a relation row value) as if it were the decision's expression.
    Boxed-context decisions are handled by `parse_context_decisions`."""
    root = ET.parse(dmn_path).getroot()
    decisions: dict[str, str] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        logic = _first_child(elem, "literalExpression")
        if name is None or logic is None:
            continue
        text_elem = _first_child(logic, "text")
        if text_elem is not None and text_elem.text is not None:
            decisions[name] = text_elem.text.strip()
    return decisions


def parse_context_decisions(dmn_path: Path) -> dict[str, list[tuple[str, str]]]:
    """Map decision name -> ordered (key, expression) list for boxed-context decisions.

    Only decisions whose direct logic child is a `<context>` are returned. Each
    `<contextEntry>` must have both a `<variable name="…">` and a
    `<literalExpression><text>…</text></literalExpression>`; decisions with any
    malformed or missing entry are silently skipped. The assembled FEEL context
    literal `{k1: e1, …}` is built by `extract_cases` after every entry
    expression passes `fits_slice_grammar`."""
    root = ET.parse(dmn_path).getroot()
    result: dict[str, list[tuple[str, str]]] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        ctx = _first_child(elem, "context")
        if name is None or ctx is None:
            continue
        entries: list[tuple[str, str]] = []
        ok = True
        for entry in ctx:
            if _local(entry.tag) != "contextEntry":
                continue
            var = _first_child(entry, "variable")
            lit = _first_child(entry, "literalExpression")
            if var is None or lit is None:
                ok = False
                break
            key = var.get("name", "")
            text_elem = _first_child(lit, "text")
            if text_elem is None or text_elem.text is None:
                ok = False
                break
            entries.append((key, text_elem.text.strip()))
        if ok and entries:
            result[name] = entries
    return result


# --------------------------------------------------------------------------- #
# 0082-specific: typeRef resolution, BKM parsing, invocation form, result cell
# --------------------------------------------------------------------------- #

# Primitive FEEL type names that appear as `typeRef` strings in DMN without a
# matching `<itemDefinition>`.
_FEEL_PRIMITIVE_TYPES: dict[str, str] = {
    "string": "string",
    "number": "number",
    "boolean": "boolean",
    "date": "date",
    "time": "time",
    "date and time": "date and time",
    "years and months duration": "years and months duration",
    "days and time duration": "days and time duration",
    "Any": "Any",
    "Null": "Null",
}


def parse_item_definitions(dmn_path: Path) -> dict[str, str]:
    """Parse ``<itemDefinition>`` elements and return a mapping from definition
    name to structural FEEL type string.

    Handles:
    * ``isCollection="true"`` → ``list<inner>``
    * ``<itemComponent>`` children → ``context<k: T, …>``
    * bare ``<typeRef>`` → primitive pass-through or recursive lookup
    * ``<functionItem>`` → skipped (DRG function-item type, no FEEL structural form)
    """
    root = ET.parse(dmn_path).getroot()
    raw: dict[str, ET.Element] = {}
    for elem in root.iter():
        if _local(elem.tag) == "itemDefinition":
            name = elem.get("name")
            if name:
                raw[name] = elem

    resolved: dict[str, str] = {}

    def resolve_typeref(ref: str) -> Optional[str]:
        if ref in _FEEL_PRIMITIVE_TYPES:
            return _FEEL_PRIMITIVE_TYPES[ref]
        if ref in resolved:
            return resolved[ref]
        if ref in raw:
            result = resolve_elem(raw[ref])
            if result:
                resolved[ref] = result
            return result
        return None

    def resolve_elem(elem: ET.Element) -> Optional[str]:
        is_collection = elem.get("isCollection", "false").lower() == "true"
        # functionItem: a DRG function-item type, no structural FEEL equivalent.
        if _first_child(elem, "functionItem") is not None:
            return None
        # itemComponent children → context<k: T, …>
        components = [c for c in elem if _local(c.tag) == "itemComponent"]
        if components:
            fields: list[str] = []
            for comp in components:
                cname = comp.get("name", "")
                ctype_elem = _first_child(comp, "typeRef")
                if ctype_elem is None or not ctype_elem.text:
                    return None
                ctype = resolve_typeref(ctype_elem.text.strip())
                if ctype is None:
                    return None
                fields.append(f"{cname}: {ctype}")
            inner = "context<" + ", ".join(fields) + ">"
            return f"list<{inner}>" if is_collection else inner
        # bare typeRef
        typeref_elem = _first_child(elem, "typeRef")
        if typeref_elem is not None and typeref_elem.text:
            inner = resolve_typeref(typeref_elem.text.strip())
            if inner is None:
                return None
            return f"list<{inner}>" if is_collection else inner
        return None

    for name, elem in raw.items():
        if name not in resolved:
            result = resolve_elem(elem)
            if result:
                resolved[name] = result
    return resolved


def _resolve_typeref_to_feel(typeref: Optional[str], item_defs: dict[str, str]) -> Optional[str]:
    """Resolve a DMN ``typeRef`` string to a structural FEEL type string, or
    ``None`` when the reference is absent or unresolvable."""
    if typeref is None:
        return None
    if typeref in _FEEL_PRIMITIVE_TYPES:
        return _FEEL_PRIMITIVE_TYPES[typeref]
    return item_defs.get(typeref)


def parse_decision_typerefs(dmn_path: Path, item_defs: dict[str, str]) -> dict[str, str]:
    """Return a mapping from decision name to resolved FEEL type string for
    decisions that carry a ``<variable typeRef="…">`` or
    ``<literalExpression typeRef="…">``.  The ``literalExpression`` typeRef
    takes precedence (it is more specific than the variable's declared type)."""
    root = ET.parse(dmn_path).getroot()
    result: dict[str, str] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        if name is None:
            continue
        # Prefer literalExpression typeRef (most specific).
        lit = _first_child(elem, "literalExpression")
        var = _first_child(elem, "variable")
        typeref: Optional[str] = None
        if lit is not None:
            typeref = lit.get("typeRef")
        if typeref is None and var is not None:
            typeref = var.get("typeRef")
        if typeref:
            resolved = _resolve_typeref_to_feel(typeref, item_defs)
            if resolved:
                result[name] = resolved
    return result


@dataclass
class BKMDef:
    """Parsed representation of a ``<businessKnowledgeModel>`` element."""
    name: str
    params: list[tuple[str, Optional[str]]]  # (param_name, feel_type_str | None)
    body: str  # the encapsulated literalExpression text
    return_type: Optional[str] = None  # structural FEEL type from the literalExpression typeRef


def parse_bkms(dmn_path: Path, item_defs: dict[str, str]) -> dict[str, BKMDef]:
    """Parse ``<businessKnowledgeModel>`` elements; return a mapping from BKM
    name to :class:`BKMDef`."""
    root = ET.parse(dmn_path).getroot()
    bkms: dict[str, BKMDef] = {}
    for elem in root.iter():
        if _local(elem.tag) != "businessKnowledgeModel":
            continue
        name = elem.get("name")
        if name is None:
            continue
        logic = _first_child(elem, "encapsulatedLogic")
        if logic is None:
            continue
        lit = _first_child(logic, "literalExpression")
        if lit is None:
            continue
        text_elem = _first_child(lit, "text")
        if text_elem is None or not text_elem.text:
            continue
        body = text_elem.text.strip()
        return_type = _resolve_typeref_to_feel(lit.get("typeRef"), item_defs)
        params: list[tuple[str, Optional[str]]] = []
        for child in logic:
            if _local(child.tag) == "formalParameter":
                p_name = child.get("name", "")
                p_type = _resolve_typeref_to_feel(child.get("typeRef"), item_defs)
                params.append((p_name, p_type))
        bkms[name] = BKMDef(name=name, params=params, body=body, return_type=return_type)
    return bkms


def parse_knowledge_requirements(dmn_path: Path) -> dict[str, list[str]]:
    """Return a mapping from decision name to a list of *BKM* names it requires
    (via ``<knowledgeRequirement><requiredKnowledge href="#…"/>``)`.

    Only ``<businessKnowledgeModel>`` targets are included; references to
    ``<decisionService>`` are silently ignored (DS is out of scope)."""
    root = ET.parse(dmn_path).getroot()
    # Build id -> name for BKMs only.
    id_to_bkm: dict[str, str] = {}
    for elem in root.iter():
        if _local(elem.tag) == "businessKnowledgeModel":
            bkm_id = elem.get("id")
            bkm_name = elem.get("name")
            if bkm_id and bkm_name:
                id_to_bkm[bkm_id] = bkm_name
    result: dict[str, list[str]] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        if name is None:
            continue
        bkm_names: list[str] = []
        for req in elem:
            if _local(req.tag) == "knowledgeRequirement":
                rk = _first_child(req, "requiredKnowledge")
                if rk is not None:
                    href = rk.get("href", "").lstrip("#")
                    bkm_name = id_to_bkm.get(href)
                    if bkm_name:
                        bkm_names.append(bkm_name)
        if bkm_names:
            result[name] = bkm_names
    return result


def parse_invocation_decisions(
    dmn_path: Path, item_defs: dict[str, str]
) -> dict[str, tuple[str, Optional[str]]]:
    """Parse ``<invocation>`` form decisions; return a mapping from decision name
    to ``(call_expression, coerce_to)`` where:

    * ``call_expression`` is the equivalent FEEL named-argument call, e.g.
      ``bkm_001(nameAndAge: {name: "foo", age: 10})``.
    * ``coerce_to`` is the resolved FEEL type from the ``<invocation typeRef="…">``,
      or ``None`` when absent.
    """
    root = ET.parse(dmn_path).getroot()
    result: dict[str, tuple[str, Optional[str]]] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        if name is None:
            continue
        invoc = _first_child(elem, "invocation")
        if invoc is None:
            continue
        callee_lit = _first_child(invoc, "literalExpression")
        if callee_lit is None:
            continue
        callee_text = _first_child(callee_lit, "text")
        if callee_text is None or not callee_text.text:
            continue
        callee = callee_text.text.strip()
        args: list[str] = []
        for child in invoc:
            if _local(child.tag) == "binding":
                param = _first_child(child, "parameter")
                lit = _first_child(child, "literalExpression")
                if param is None or lit is None:
                    continue
                param_name = param.get("name", "")
                text_elem = _first_child(lit, "text")
                if text_elem is None or not text_elem.text:
                    continue
                args.append(f"{param_name}: {text_elem.text.strip()}")
        call_expr = f"{callee}({', '.join(args)})"
        coerce_to = _resolve_typeref_to_feel(invoc.get("typeRef"), item_defs)
        result[name] = (call_expr, coerce_to)
    return result


def parse_context_result_decisions(
    dmn_path: Path,
) -> dict[str, tuple[list[tuple[str, str]], str]]:
    """Parse boxed-context decisions that carry a trailing *result cell* — a
    ``<contextEntry>`` with no ``<variable>`` as the final entry.

    Returns a mapping from decision name to ``(named_entries, result_expr)`` where:

    * ``named_entries`` is an ordered list of ``(key, expression)`` pairs for all
      named entries (every entry *except* the last).
    * ``result_expr`` is the FEEL expression text of the unnamed result cell.

    Decisions where every entry has a ``<variable>`` (no result cell), or where
    any entry is malformed, are silently omitted."""
    root = ET.parse(dmn_path).getroot()
    result: dict[str, tuple[list[tuple[str, str]], str]] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        ctx = _first_child(elem, "context")
        if name is None or ctx is None:
            continue
        all_entries = [c for c in ctx if _local(c.tag) == "contextEntry"]
        if not all_entries:
            continue
        # Last entry must have no <variable> (the result cell).
        last = all_entries[-1]
        if _first_child(last, "variable") is not None:
            continue
        last_lit = _first_child(last, "literalExpression")
        if last_lit is None:
            continue
        last_text = _first_child(last_lit, "text")
        if last_text is None or not last_text.text:
            continue
        result_expr = last_text.text.strip()
        # Extract named entries (all but the last).
        named_entries: list[tuple[str, str]] = []
        ok = True
        for entry in all_entries[:-1]:
            var = _first_child(entry, "variable")
            lit = _first_child(entry, "literalExpression")
            if var is None or lit is None:
                ok = False
                break
            key = var.get("name", "")
            text_elem = _first_child(lit, "text")
            if text_elem is None or not text_elem.text:
                ok = False
                break
            named_entries.append((key, text_elem.text.strip()))
        if ok and result_expr:
            result[name] = (named_entries, result_expr)
    return result


def parse_conditional_decisions(dmn_path: Path) -> dict[str, tuple[str, str, str]]:
    """Parse ``<conditional>`` form decisions; return a mapping from decision name
    to ``(if_expr, then_expr, else_expr)`` where each expression is the FEEL text
    of the corresponding ``<literalExpression><text>`` child.

    Only decisions whose direct logic child is ``<conditional>`` are returned.
    Decisions with a missing or malformed child are silently omitted."""
    root = ET.parse(dmn_path).getroot()
    result: dict[str, tuple[str, str, str]] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        cond = _first_child(elem, "conditional")
        if name is None or cond is None:
            continue
        if_branch = _first_child(cond, "if")
        then_branch = _first_child(cond, "then")
        else_branch = _first_child(cond, "else")
        if if_branch is None or then_branch is None or else_branch is None:
            continue
        def _text_of(branch: ET.Element) -> Optional[str]:
            lit = _first_child(branch, "literalExpression")
            if lit is None:
                return None
            t = _first_child(lit, "text")
            return t.text.strip() if t is not None and t.text is not None else None
        if_expr = _text_of(if_branch)
        then_expr = _text_of(then_branch)
        else_expr = _text_of(else_branch)
        if if_expr is None or then_expr is None or else_expr is None:
            continue
        result[name] = (if_expr, then_expr, else_expr)
    return result


def parse_filter_decisions(dmn_path: Path) -> dict[str, tuple[str, str]]:
    """Parse ``<filter>`` form decisions; return a mapping from decision name to
    ``(in_expr, match_expr)`` where each expression is the FEEL text of the
    corresponding ``<literalExpression><text>`` child.

    Only decisions whose direct logic child is ``<filter>`` are returned."""
    root = ET.parse(dmn_path).getroot()
    result: dict[str, tuple[str, str]] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        filt = _first_child(elem, "filter")
        if name is None or filt is None:
            continue
        in_branch = _first_child(filt, "in")
        match_branch = _first_child(filt, "match")
        if in_branch is None or match_branch is None:
            continue
        def _text_of_lit(branch: ET.Element) -> Optional[str]:
            lit = _first_child(branch, "literalExpression")
            if lit is None:
                return None
            t = _first_child(lit, "text")
            return t.text.strip() if t is not None and t.text is not None else None
        in_expr = _text_of_lit(in_branch)
        match_expr = _text_of_lit(match_branch)
        if in_expr is None or match_expr is None:
            continue
        result[name] = (in_expr, match_expr)
    return result


def parse_iterator_decisions(
    dmn_path: Path,
) -> dict[str, tuple[str, str, str, str]]:
    """Parse ``<for>``, ``<some>``, and ``<every>`` form decisions; return a
    mapping from decision name to ``(kind, var, in_expr, body_expr)`` where:

    * ``kind`` is ``"for"``, ``"some"``, or ``"every"``.
    * ``var`` is the ``iteratorVariable`` attribute value.
    * ``in_expr`` is the FEEL text of the ``<in><literalExpression><text>`` cell.
    * ``body_expr`` is the FEEL text of the ``<return>`` (for ``for``) or
      ``<satisfies>`` (for ``some``/``every``) cell.

    Only decisions whose direct logic child is one of the three iterator elements
    are returned. Decisions with missing attributes or cells are silently omitted."""
    _ITERATOR_TAGS = {"for": "return", "some": "satisfies", "every": "satisfies"}
    root = ET.parse(dmn_path).getroot()
    result: dict[str, tuple[str, str, str, str]] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        if name is None:
            continue
        iter_elem: Optional[ET.Element] = None
        kind: Optional[str] = None
        for tag in _ITERATOR_TAGS:
            child = _first_child(elem, tag)
            if child is not None:
                iter_elem = child
                kind = tag
                break
        if iter_elem is None or kind is None:
            continue
        var = iter_elem.get("iteratorVariable")
        if not var:
            continue
        in_branch = _first_child(iter_elem, "in")
        body_tag = _ITERATOR_TAGS[kind]
        body_branch = _first_child(iter_elem, body_tag)
        if in_branch is None or body_branch is None:
            continue
        def _text_of_iter(branch: ET.Element) -> Optional[str]:
            lit = _first_child(branch, "literalExpression")
            if lit is None:
                return None
            t = _first_child(lit, "text")
            return t.text.strip() if t is not None and t.text is not None else None
        in_expr = _text_of_iter(in_branch)
        body_expr = _text_of_iter(body_branch)
        if in_expr is None or body_expr is None:
            continue
        result[name] = (kind, var, in_expr, body_expr)
    return result


def parse_list_decisions(dmn_path: Path) -> dict[str, list[str]]:
    """Parse ``<list>`` form decisions (boxed list literal); return a mapping from
    decision name to an ordered list of FEEL text strings, one per direct
    ``<literalExpression>`` child of the ``<list>`` element.

    Only decisions whose direct logic child is a ``<list>`` are returned.
    Rows with a missing or empty ``<text>`` are silently omitted from the row
    list; decisions with zero valid rows are excluded."""
    root = ET.parse(dmn_path).getroot()
    result: dict[str, list[str]] = {}
    for elem in root.iter():
        if _local(elem.tag) != "decision":
            continue
        name = elem.get("name")
        lst = _first_child(elem, "list")
        if name is None or lst is None:
            continue
        rows: list[str] = []
        for child in lst:
            if _local(child.tag) != "literalExpression":
                continue
            t = _first_child(child, "text")
            if t is None or not t.text:
                continue
            rows.append(t.text.strip())
        if rows:
            result[name] = rows
    return result


def _inline_bkms(
    call_expr: str,
    bkm_names: frozenset[str],
    bkms: dict[str, BKMDef],
) -> tuple[str, Optional[str]]:
    """Inline the named BKMs as FEEL function literals in a context literal
    wrapping ``call_expr``, then project the result via the synthetic
    ``__result`` key.

    Output form::

        {bkm1: function(p: T, …) body1, …, __result: call_expr}.__result

    Returns ``(assembled_expression, bkm_return_type)`` where ``bkm_return_type``
    is the return type of the *first* BKM that declares one (``None`` otherwise)
    — used as a ``coerce_to`` fallback when neither the invocation nor the
    decision variable carries an explicit ``typeRef``."""
    entries: list[str] = []
    bkm_return_type: Optional[str] = None
    for bkm_name in sorted(bkm_names):  # deterministic output order
        bkm = bkms[bkm_name]
        param_parts: list[str] = []
        for p_name, p_type in bkm.params:
            param_parts.append(f"{p_name}: {p_type}" if p_type else p_name)
        fn_literal = f"function({', '.join(param_parts)}) {bkm.body}"
        entries.append(f"{bkm_name}: {fn_literal}")
        if bkm.return_type is not None and bkm_return_type is None:
            bkm_return_type = bkm.return_type
    entries.append(f"__result: {call_expr}")
    return "{" + ", ".join(entries) + "}.__result", bkm_return_type


_XSI = "{http://www.w3.org/2001/XMLSchema-instance}"


def _first_child(elem: ET.Element, *names: str) -> Optional[ET.Element]:
    """First direct child whose local tag is one of `names`."""
    for child in elem:
        if _local(child.tag) in names:
            return child
    return None


def parse_value_elem(value_elem: ET.Element) -> tuple[object, str]:
    """Parse a scalar <value> element -> (python value, type)."""
    if value_elem.get(f"{_XSI}nil") == "true":
        return None, "null"
    xsi_type = value_elem.get(f"{_XSI}type", "")
    raw = value_elem.text or ""
    text = raw.strip()
    # A declared string type is authoritative: a string result like "2" must not
    # be mis-read as the number 2 (e.g. `string(2)` returns the string "2").  It must
    # also win over the boolean text heuristic so `<value xsi:type="xsd:string">true</value>`
    # is the string "true", not the boolean true.  Keep the raw text un-stripped — a
    # string result may legitimately be whitespace (e.g. `substring("foob r", -2, 1) = " "`).
    if xsi_type.endswith("string"):
        return raw, "string"
    if xsi_type.endswith("boolean") or text in ("true", "false"):
        return text == "true", "boolean"
    # Temporal types (ADR-18). The lexical text is the canonical ISO-8601 form
    # feel-core round-trips. Check dateTime before date/time (it ends with "time"
    # and contains "date"). XSD uses one `duration` for both FEEL duration kinds;
    # feel-core re-derives the kind from the lexical form, so one tag suffices.
    low = xsi_type.lower()
    if low.endswith("datetime"):
        return text, "date and time"
    if low.endswith("date"):
        return text, "date"
    if low.endswith("time"):
        return text, "time"
    if low.endswith("duration"):
        return text, "duration"
    # decimal / double / integer, or anything that parses as a number
    try:
        return float(text), "number"
    except ValueError:
        return text, "string"


def parse_expected_node(node: ET.Element) -> tuple[object, str]:
    """Parse an <expected>/<item>/<component> node (recursive): a scalar <value>,
    a <list> of items, or a context expressed as one-or-more <component name="…">
    children (-> dict, e.g. the `{key, value}` entries `get entries` returns)."""
    child = _first_child(node, "value", "list")
    if child is None:
        components = [c for c in node if _local(c.tag) == "component"]
        if components:
            return {c.get("name"): parse_expected_node(c)[0] for c in components}, "context"
        return None, "null"
    if _local(child.tag) == "value":
        return parse_value_elem(child)
    # <list><item>...</item>...</list> -> a (possibly nested) JSON array.
    items = [parse_expected_node(it)[0] for it in child if _local(it.tag) == "item"]
    return items, "list"


def parse_expected(result_node: ET.Element) -> tuple[object, str]:
    """Extract (value, type) from a <resultNode>'s <expected> (scalar or list)."""
    expected = _first_child(result_node, "expected")
    if expected is None:
        return None, "null"
    return parse_expected_node(expected)


def parse_input_value(node: ET.Element) -> object:
    """Parse an <inputNode>/<item>/<component> into a JSON-serialisable value.

    Scalars come from a <value> child, lists from <list><item>…</item></list>,
    and contexts from one-or-more <component name="…"> children (-> dict)."""
    value_child = _first_child(node, "value")
    if value_child is not None:
        val, typ = parse_value_elem(value_child)
        # A temporal input is tagged so the fixture context can bind it as a
        # typed temporal value rather than a plain string (ADR-18).
        if typ in ("date", "time", "date and time", "duration"):
            return {"@type": typ, "@value": val}
        return val
    list_child = _first_child(node, "list")
    if list_child is not None:
        return [parse_input_value(it) for it in list_child if _local(it.tag) == "item"]
    components = [c for c in node if _local(c.tag) == "component"]
    if components:
        return {c.get("name"): parse_input_value(c) for c in components}
    return None  # nil / empty input


def parse_inputs(test_case: ET.Element) -> dict:
    """Map each direct <inputNode name="…"> of a testCase to its JSON value."""
    inputs: dict = {}
    for child in test_case:
        if _local(child.tag) == "inputNode":
            name = child.get("name")
            if name:
                inputs[name] = parse_input_value(child)
    return inputs


def collect_context_keys(value: object) -> set[str]:
    """Every context (component) key appearing anywhere in an input value. Inside a
    filter over a list of contexts these keys are referenceable without an `item.`
    prefix (`Employees[dept = 20]`), and via path access generally (§10.3.2.5), so
    they are bound names for the slice detector — not free identifiers. The `@type`/
    `@value` keys of a tagged temporal input never appear in expressions and contain
    `@`, so they are harmless even if collected."""
    keys: set[str] = set()
    if isinstance(value, dict):
        for k, v in value.items():
            keys.add(k)
            keys |= collect_context_keys(v)
    elif isinstance(value, list):
        for v in value:
            keys |= collect_context_keys(v)
    return keys


def extract_cases(dmn_path: Path, test_path: Path) -> tuple[list[Case], list[tuple[str, str]]]:
    """Return (kept cases, skipped (id, reason) pairs)."""
    # Parse type infrastructure for coerce_to resolution.
    item_defs = parse_item_definitions(dmn_path)
    decision_typerefs = parse_decision_typerefs(dmn_path, item_defs)
    # Parse decision expressions (eight forms).
    decisions = parse_decisions(dmn_path)
    context_decisions = parse_context_decisions(dmn_path)
    context_result_decisions = parse_context_result_decisions(dmn_path)
    bkms = parse_bkms(dmn_path, item_defs)
    knowledge_reqs = parse_knowledge_requirements(dmn_path)
    invocation_decisions = parse_invocation_decisions(dmn_path, item_defs)
    # Boxed element-form decisions (DMN 1.5 §10.2.1.5 / §10.2.1.8–10).
    conditional_decisions = parse_conditional_decisions(dmn_path)
    filter_decisions = parse_filter_decisions(dmn_path)
    iterator_decisions = parse_iterator_decisions(dmn_path)
    list_decisions = parse_list_decisions(dmn_path)
    model_stem = dmn_path.stem

    root = ET.parse(test_path).getroot()
    kept: list[Case] = []
    skipped: list[tuple[str, str]] = []

    for test_case in root.iter():
        if _local(test_case.tag) != "testCase":
            continue
        tc_id = test_case.get("id", "?")
        # A decision-service test case (`type="decisionService"`) invokes a whole
        # DRG decision service, not a standalone literal expression: its result is
        # governed by service encapsulation (an output not exposed by the service is
        # null, regardless of the underlying decision's literal). feel-core is a FEEL
        # *expression* engine with no DRG, so extracting the bare expression would
        # compare against the service's value, not the expression's. Skip the whole
        # case structurally (the expression-only siblings in the same dir are kept).
        if test_case.get("type") == "decisionService":
            skipped.append((tc_id, "decision-service invocation (DRG, out of scope)"))
            continue
        inputs = parse_inputs(test_case)
        # Input node names plus the context keys of their (possibly nested, possibly
        # list-element) values: all are bound names a filter/path may reference.
        member_keys: set[str] = set()
        for value in inputs.values():
            member_keys |= collect_context_keys(value)
        input_names = frozenset(inputs) | member_keys
        for result_node in test_case.iter():
            if _local(result_node.tag) != "resultNode":
                continue
            name = result_node.get("name")
            if name is None:
                continue

            expression: Optional[str] = None
            case_coerce_to: Optional[str] = None
            case_id = f"{model_stem}:{tc_id}:{name}"

            # ----------------------------------------------------------------- #
            # Resolve the decision to an expression (eight forms):               #
            #                                                                     #
            # 1. Literal-expression decision (possibly BKM-backed)               #
            # 2. Boxed-context decision with no result cell                      #
            # 3. Boxed-context decision with a trailing result cell (fd_*)       #
            # 4. Invocation-form decision                                         #
            # 5. Boxed-conditional decision (<conditional> element form)         #
            # 6. Boxed-filter decision (<filter> element form)                   #
            # 7. Boxed-iterator decision (<for>/<some>/<every> element forms)    #
            # 8. Boxed-list decision (<list> element form)                       #
            # ----------------------------------------------------------------- #

            if name in decisions:
                raw_expr = decisions[name]
                bkm_names = frozenset(knowledge_reqs.get(name, []))
                if bkm_names:
                    # BKM-backed literal-expression: check the raw call expression
                    # with the BKM names treated as bound names, then inline.
                    if not fits_slice_grammar(raw_expr, input_names | bkm_names):
                        skipped.append((case_id, f"outside slice grammar: {raw_expr!r}"))
                        continue
                    # Also validate each BKM body against its own param names.
                    bkm_body_ok = True
                    for bkm_name in bkm_names:
                        bkm = bkms.get(bkm_name)
                        if bkm is None:
                            bkm_body_ok = False
                            break
                        bkm_param_names = frozenset(p for p, _ in bkm.params)
                        if not fits_slice_grammar(bkm.body, bkm_param_names):
                            bkm_body_ok = False
                            break
                    if not bkm_body_ok:
                        skipped.append((case_id, f"BKM body outside slice for {name!r}"))
                        continue
                    expression, bkm_return_type = _inline_bkms(raw_expr, bkm_names, bkms)
                    # coerce_to priority: decision variable typeRef > BKM return typeRef
                    case_coerce_to = decision_typerefs.get(name) or bkm_return_type
                else:
                    # NB: `errorResult="true"` is *not* skipped wholesale. Many such
                    # cases are genuine expression errors feel-core reproduces (a
                    # malformed regex, a bad argument → error-null, collapsed to null at
                    # the lenient boundary, which matches the expected nil) — valuable
                    # coverage. The few where the error comes from DMN *decision
                    # output-type* validation rather than the expression are handled via
                    # the `coerce_to` mechanism (0082-feel-coercion).
                    if not fits_slice_grammar(raw_expr, input_names):
                        skipped.append((case_id, f"outside slice grammar: {raw_expr!r}"))
                        continue
                    expression = raw_expr
                    case_coerce_to = decision_typerefs.get(name)

            elif name in context_decisions:
                entries = context_decisions[name]
                skip_reason: Optional[str] = None
                for key, entry_expr in entries:
                    if not fits_slice_grammar(entry_expr, input_names):
                        skip_reason = f"context entry {key!r} outside slice: {entry_expr!r}"
                        break
                if skip_reason:
                    skipped.append((case_id, skip_reason))
                    continue
                expression = "{" + ", ".join(f"{k}: {e}" for k, e in entries) + "}"
                # Regular boxed-context decisions carry no result-cell coercion.

            elif name in context_result_decisions:
                # Boxed-context with a trailing unnamed result cell:
                #   {k1: e1, …, __result: result_expr}.__result
                named_entries, result_expr = context_result_decisions[name]
                prior_keys = frozenset(k for k, _ in named_entries)
                skip_reason2: Optional[str] = None
                for key, entry_expr in named_entries:
                    if not fits_slice_grammar(entry_expr, input_names):
                        skip_reason2 = f"context entry {key!r} outside slice: {entry_expr!r}"
                        break
                if not skip_reason2 and not fits_slice_grammar(
                    result_expr, input_names | prior_keys
                ):
                    skip_reason2 = f"result cell outside slice: {result_expr!r}"
                if skip_reason2:
                    skipped.append((case_id, skip_reason2))
                    continue
                all_entries = list(named_entries) + [("__result", result_expr)]
                expression = "{" + ", ".join(f"{k}: {e}" for k, e in all_entries) + "}.__result"
                case_coerce_to = decision_typerefs.get(name)

            elif name in invocation_decisions:
                call_expr, inv_coerce_to = invocation_decisions[name]
                bkm_names = frozenset(knowledge_reqs.get(name, []))
                # The call names a BKM directly; treat BKM names as bound during
                # the slice check of the call expression.
                if not fits_slice_grammar(call_expr, input_names | bkm_names):
                    skipped.append((case_id, f"outside slice grammar: {call_expr!r}"))
                    continue
                # Validate each BKM body.
                bkm_body_ok2 = True
                for bkm_name in bkm_names:
                    bkm = bkms.get(bkm_name)
                    if bkm is None:
                        bkm_body_ok2 = False
                        break
                    bkm_param_names = frozenset(p for p, _ in bkm.params)
                    if not fits_slice_grammar(bkm.body, bkm_param_names):
                        bkm_body_ok2 = False
                        break
                if not bkm_body_ok2:
                    skipped.append((case_id, f"BKM body outside slice for {name!r}"))
                    continue
                expression, bkm_return_type2 = _inline_bkms(call_expr, bkm_names, bkms)
                # coerce_to priority: invocation typeRef > BKM return typeRef > variable typeRef
                case_coerce_to = inv_coerce_to or bkm_return_type2 or decision_typerefs.get(name)

            elif name in conditional_decisions:
                # Boxed conditional: if (IF) then (THEN) else (ELSE)
                if_expr, then_expr, else_expr = conditional_decisions[name]
                assembled = f"if ({if_expr}) then ({then_expr}) else ({else_expr})"
                if not fits_slice_grammar(assembled, input_names):
                    skipped.append((case_id, f"outside slice grammar: {assembled!r}"))
                    continue
                expression = assembled
                case_coerce_to = decision_typerefs.get(name)

            elif name in filter_decisions:
                # Boxed filter: (IN)[MATCH]  (predicate uses `item`)
                in_expr, match_expr = filter_decisions[name]
                assembled = f"({in_expr})[{match_expr}]"
                # `item` is always bound in filter scope; include it so the slice
                # detector does not reject its implicit use inside `match_expr`.
                if not fits_slice_grammar(assembled, input_names | frozenset({"item"})):
                    skipped.append((case_id, f"outside slice grammar: {assembled!r}"))
                    continue
                expression = assembled
                case_coerce_to = decision_typerefs.get(name)

            elif name in iterator_decisions:
                # Boxed iterator: for VAR in (IN) return (BODY)
                #                 some/every VAR in (IN) satisfies (BODY)
                kind, var, in_expr, body_expr = iterator_decisions[name]
                if kind == "for":
                    assembled = f"for {var} in ({in_expr}) return ({body_expr})"
                else:
                    assembled = f"{kind} {var} in ({in_expr}) satisfies ({body_expr})"
                # The iterator variable is bound inside the body; include it in the
                # slice check so the grammar detector treats it as known.
                iter_bound = input_names | frozenset({var})
                if not fits_slice_grammar(assembled, iter_bound):
                    skipped.append((case_id, f"outside slice grammar: {assembled!r}"))
                    continue
                expression = assembled
                case_coerce_to = decision_typerefs.get(name)

            elif name in list_decisions:
                # Boxed list literal: [row1, row2, …]
                rows = list_decisions[name]
                assembled = "[" + ", ".join(rows) + "]"
                if not fits_slice_grammar(assembled, input_names):
                    skipped.append((case_id, f"outside slice grammar: {assembled!r}"))
                    continue
                expression = assembled
                case_coerce_to = decision_typerefs.get(name)

            else:
                continue

            if case_id in REGEX_DIALECT_SKIPS:
                skipped.append((case_id, "regex-xpath-dialect deviation"))
                continue

            if case_id in TEMPORAL_RANGE_SKIPS:
                skipped.append((case_id, "temporal value outside jiff's range (ADR-18)"))
                continue

            if case_id in TEMPORAL_SUBSECOND_EQUALITY_SKIPS:
                skipped.append((case_id, "second-resolution temporal equality (ADR-18)"))
                continue

            if case_id in CROSS_TYPE_EQUALITY_SKIPS:
                skipped.append((case_id, "cross-type `=` is error-null in feel-core, not false (ADR-14)"))
                continue

            if case_id in NAMED_ARG_OVERLOAD_SKIPS:
                skipped.append((case_id, "named-arg overload not in feel-core's param table (ADR-23)"))
                continue

            if case_id in TEMPORAL_FOR_RANGE_SKIPS:
                skipped.append((case_id, "date `for` range iteration not implemented (integer ranges only)"))
                continue

            if case_id in OUT_OF_SCOPE_EXPR_SKIPS:
                skipped.append((case_id, "expected result needs a DMN feature outside a FEEL-expression engine"))
                continue

            if case_id in TZDB_ZONE_SKIPS:
                skipped.append((case_id, "named zone not resolvable in this build's tzdb (ADR-18)"))
                continue

            if case_id in NON_XID_NAME_SKIPS:
                skipped.append((case_id, "emoji / non-XID bare name not in the slice (ADR-17)"))
                continue

            if case_id in DECIMAL_LIST_SKIPS:
                skipped.append((
                    case_id,
                    "list of decimal128 numbers — f64_epsilon mode only covers scalar results; "
                    "element-wise epsilon for list results not yet supported by the harness",
                ))
                continue

            if case_id in BOXED_PREDICATE_DEVIATION_SKIPS:
                skipped.append((
                    case_id,
                    "boxed predicate deviation: non-true filter predicate drops element "
                    "(ADR-24) / some short-circuits on true before non-boolean taint (ADR-13/14)",
                ))
                continue

            expected, expected_type = parse_expected(result_node)

            case = Case(
                id=case_id,
                expression=expression,
                expected=expected,
                expected_type=expected_type,
                coerce_to=case_coerce_to,
                context=inputs,
            )
            apply_deviations(case)
            kept.append(case)

    kept.sort(key=lambda c: c.id)
    return kept, skipped


# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #


def main(argv: Optional[list[str]] = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("path", type=Path, help="TCK test directory or .dmn file")
    parser.add_argument("-o", "--output", type=Path, required=True, help="fixture JSON output path")
    args = parser.parse_args(argv)

    dmn_path, test_path = resolve_inputs(args.path)
    cases, skipped = extract_cases(dmn_path, test_path)

    if not cases:
        print("No cases matched the slice grammar — nothing written.", file=sys.stderr)
        for case_id, reason in skipped:
            print(f"  skipped {case_id}: {reason}", file=sys.stderr)
        return 1

    args.output.parent.mkdir(parents=True, exist_ok=True)
    fixture = [c.to_fixture() for c in cases]
    args.output.write_text(json.dumps(fixture, indent=2) + "\n", encoding="utf-8")

    # ----------------------------- summary --------------------------------- #
    print(f"DMN model:   {dmn_path}")
    print(f"Test cases:  {test_path}")
    print(f"Fixture:     {args.output}  ({len(cases)} case(s))")
    print()
    print("Processed cases:")
    for case in cases:
        extra = f"  (epsilon={case.epsilon})" if case.epsilon is not None else ""
        print(f"  + {case.id}: {case.expression!r} -> {case.expected} "
              f"[{case.expected_type}, {case.comparison}]{extra}")
    print()
    print("Deviation rules:")
    for rule in DEVIATION_RULES:
        status = f"applied to {rule.applied_count} case(s)" if rule.applied_count else "not applied"
        print(f"  - {rule.name}: {status}")
    if skipped:
        print()
        print(f"Skipped {len(skipped)} decision(s) outside the slice:")
        for case_id, reason in skipped:
            print(f"  - {case_id}: {reason}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
