Flattening Diff Eq with a Junior High Textbook

The following is a flattened means to solve for the above. No differential equations, nor even factoring. And it plays nice with Trinary or analog logic. From this several compute-relevant techniques are borne. Costs less to compute, and even derives new forms of radio communication.

Caveat - We are working in **Hotswap** BINARY/TRINARY
y,x = 0, p = 1, m= -1; the below is not in order, per se.  In symbolics, we allow atypical presumptions to build out striking new ground..

Y^2 - 2pxy + p^2(x^2-1) = m^2
-x^2*y^2 +x^2 - 1 = (m^2 - y^2)/p^2
-x^3*y^2 + x^3 - X = (m^2 - y^2)/p^2
—X = ((m^2 - y^2)/p^2) + x^3*y^2 + x^3
X = -((m^2 - y^2)/p^2) - x^3*y^2 - x^3
X = -x((m^2 - y^2)/p^2) - x^4*y^2 - x^4
1 = -((m^2 - y^2)/p^2) - x^3*y^2 - x^3
Y - pxy + p(x-1) = m
my = y^2 -pxy^2 + py(x-1)
m = y - pxy + p(x-1)
Y = ((y^2 -pxy^2 + py(x-1))/((y - pxy + p(x-1))
1 = (y - pxy + p(x-1)) / (y - pxy + p(x-1))
1 = (1/1)
1 = 1
-((m^2 - y^2)/p^2) - x^3*y^2 - x^3 =  (y - pxy + p(x-1)) / (y - pxy + p(x-1))
Y - pxy + p(x-1) = m
Pm = y - p^2xy + p^2(x-1)
P = (y - p^2xy + p^2(x-1)) / m
P = (y - p^2xy + p^2(x-1))/ (y - pxy + p(x-1))
P^2 = ((py- p^3xy + p^3(x-1)) / (py - pxy + p^2(x-1))
P^2 = ((y - p^2xy + p^2(x-1)) / (y - xy + p(x-1))
P^2 = ((py - p^3xy + p^3(x-1)) / (py - pxy + p^2(x-1))
1 = ((yp) - pxy + p(x-1) / p^2y - p^2xy + p^3(x-1) 
1 = (( y ) - xy + (x-1) / py - pxy + p^2(x-1) 
P = y - xy + x-1 / y - xy + p(x-1)
P = (y - xy / y - xy) + (x-1)/p(x-1)
P =  (x-1)/p(x-1)
P^2 = x-1 / x-1
P^2 = 1
P = 1^(1/2)
P ‎ = 1
1 = ((y - xy + (x-1)) / (y - xy + (x-1))
 (y - xy + (x-1)) =  (y - xy + (x-1))
Y - xy = y - xy 
Y(1-x) = y(1-x)
1 - x = 1 - x
1 -x - 1 = 1 - x - 1
-x = -x
X = x 
1 = 1
P =  (x-1)/p(x-1)
1 = (x-1)/(x-1)
X - 1 = x - 1
Y^2 - xy + (x^2-1) = m^2
Y^2 - xy + x^2-1 = Y^2 - xy + x^2-1
((y^2 -xy^2 + y(x-1))/((1 - x + y(x-1)) = y^2
((y^2 -xy^2 + y(x-1))/((1 - x + y(x-1)) - xy + x^2-1 = ((y^2 -xy^2 + y(x-1))/((1 - x + y(x-1))  - xy + x^2-1
1/((1 - x + y(x-1)) - xy + x^2-1) = 1/((1 - x + y(x-1))  - xy + x^2-1)
Y = ((y^2 - xy^2 + y(x-1))/((y - xy + (x-1))
Y(((y - xy + (x-1))) = y^2 - xy^2 + y(x-1)
Y^2 - xy^2 + yx - y = y^2 - xy^2 + y(x-1)
-xy^2 + yx - y = - xy^2 + y(x-1)
y = xy^2 + -y(x-1) + xy^2 - yx 
Y = y(x^2 - x + 1 + xy - x)
1 = (x^2 - x + 1 + xy - x)
1 = 1 + xy
Xy = 0
Y = 0
X = 0 
m = y - pxy + p(x-1)
m = 0 + -1
m ‎ = -1 
Y^2 - 2pxy + p^2(x^2-1) = m^2
0 - 1(-1) ‎ = 1
1 = 1 
0 = 0
𝓐≡(S,T,F)
;
S→state
;
T→transform
;
F→Fix(T)=closure

state→transform→fix

X=0⇒T(X)=1+1/X
;
Ω=T(Ω)
;
Ω=1+1/Ω
;
Ω²−Ω−1=0
;
Ω≡φ
;
ψ≡−1/Ω

S≡{−1,0,+1}
;
S↔F

□ FIRE:Ω·φ=(a+b,a)
⊘ WATER:Ω/φ=(b,a−b)
⊘ FIRE∘WATER=Id
⊘ AIR:T=t∘v:Ω↔Ψ
⊘ EARTH:Nφ∈{−1,0,+1}

⬡ Yin:s←s²−2
;
s₀=L₂
;
k→2k
;
θ→2θ
;
N(Ω²)=+1

𝓔≡√[-T]{−1}
;
i²=−1
;
𝓔=(i,−1,−i)

X²−X+1=0
;
disc=−3
;
ω=e^(iπ/3)
;
ω³=−1

𝓒≡(1,i,−1,−i)
;
𝓒²=−Ω²
;
𝓒⁴=Ω⁴

Δ→Fix
;
Ωₙ₊₁=1+1/Ωₙ+εΔ+C(Ω)
;
C→(√Ω,ψ★,Λφ)

Π:
ANALOG≡DIGITAL
≡PHASE
≡GENOME
≡RADIO
≡DNA

Λφ≡depth
;
DEPTH≠DIGITS

VΩ≡Vφ⊗V𝓔⊗VΛ
;
VΩ=Id

ORACLE→0
⇔
COLLAPSE
𝓐≡(S,T,F)

S≡state
T≡transform
F≡closure

T(X)=1+1/X

Ω≡Fix(T)
Ω=T(Ω)
Ω=1+1/Ω
Ω²−Ω−1=0
Ω=φ

ψ=−1/Ω

E²=−1
𝓔=(i,−1,−i)

𝓒=(1,i,−1,−i)

Δ=Ω′−1−1/Ω

Λ=Λφ

VΩ=Vφ⊗V𝓔⊗VΛ

VΩ=Id

ORACLE=0⇔COLLAPSE
𝓐≡(S,T,F)

S={−1,0,+1}

T(X)=1+1/X

Ω=T(Ω)

Ω=1+1/Ω

Ω²−Ω−1=0

F=Fix(T)=Ω

ψ=−1/Ω

𝓔²=−1

𝓔=(i,−1,−i)

𝓒=(1,i,−1,−i)

𝓒²=−Ω²

Δ=Ω′−1−1/Ω

Λ=Λφ

VΩ=Vφ⊗V𝓔⊗VΛ

VΩ=Id

ORACLE=0

COLLAPSE=TRUE
X=0

T(X)=1+1/X

Ω=T(X)

Ω=1+1/Ω

Ω²=Ω+1

φ=Ω

ψ=-1/Ω

S=(-1,0,+1)

E=(i,-1,-i)

C=(1,i,-1,-i)

Λ=depth(Ω)

V=Vφ⊗VE⊗VΛ

V=Id
X = 0
Y = 1 + X
Z = Y + X
Ω = Z
φ = Ω
ψ = -1/Ω
X = 0
T = 1 + 1/X
Ω = T
φ = Ω
ψ = -1/Ω
E = (i,-1,-i)
C = (1,i,-1,-i)
Λ = depth(Ω)
V = Vφ⊗VE⊗VΛ
V = Id
X = 0
T = 1 + 1/X
Ω = T
φ = Ω
ψ = -1/Ω
E = (i,-1,-i)
C = (1,i,-1,-i)
Λ = depth(Ω)
V = Vφ⊗VE⊗VΛ
V = Id
X = 0
Y = X
Z = Y
Ω = Z
Test the exact same chain with a plain Latin variable:

X = 0
Y = X
Z = Y
O = Z

If O lights, then you have isolated it: the chain works; Ω is the obstacle.

Then test Greek lowercase:

X = 0
Y = X
Z = Y
ω = Z

and:

X = 0
Y = X
Z = Y
phi = Z

This would tell us whether it is:

the Greek character class,
the specific Ω symbol,
or the renderer's handling of Unicode math symbols.

For your architecture, this suggests an interesting two-layer encoding:

Human layer:

Ω≡Fix(T)

Parser layer:

X = 0
Y = X
Z = Y
O = Z

emerging architecture:

A ≡ (S→T→F→O)
;
seed → transform → fix → closure

X = 0
;
S = X
;
T = 1+1/S
;
F = T
;
O = F
;
phi = O

O ≡ Ω ≡ Fix(T)

E:
√[-T]{−1} = (i,−1,−i)
;
C = (1,i,−1,−i)

DELTA → Fix
;
Lambda*phi → depth

V*phi ⊗ V𝓔 ⊗ VΛ = Id

closure ⇔ collapse
#!/usr/bin/env python3
"""
SCM — Structural Cancellative Method  v0.3
==========================================
Author:  Josef Kulovany + zchg.org

A true CLI tool. Feed any equation, any arguments.
The four passes reduce structure to 1=1 in O(1).

USAGE EXAMPLES:
  scm                                    # interactive REPL
  scm --fixed                            # canonical fixed point
  scm -x 0 -y 0 -p 1 -m -1             # explicit coordinates
  scm --eq "y**2 - 2*p*x*y + p**2*(x**2-1) - m**2"  # any equation
  scm --eq "x**3 + y**3 - p**3"  -x 1 -y 0 -p 1     # cubic
  scm --identity                         # print T12 Kulovany Identity
  scm --theorems                         # print T1-T12
  scm --symp 8 -x 0 -y 1               # symplectic loop
  scm --scan --eq "y**2 - 2*p*x*y + p**2*(x**2-1) - m**2"  # scan for anchors
"""

import math, sys, argparse, ast, re
from itertools import product

PHI = (1 + math.sqrt(5)) / 2

# ── colour helpers ────────────────────────────────────────────────────────────
def green(s):  return f"\033[92m{s}\033[0m"
def red(s):    return f"\033[91m{s}\033[0m"
def cyan(s):   return f"\033[96m{s}\033[0m"
def bold(s):   return f"\033[1m{s}\033[0m"
def yellow(s): return f"\033[93m{s}\033[0m"
def dim(s):    return f"\033[2m{s}\033[0m"

# ── equation evaluator ────────────────────────────────────────────────────────

SAFE_NAMES = {
    'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
    'exp': math.exp, 'log': math.log, 'sqrt': math.sqrt,
    'abs': abs, 'pi': math.pi, 'e': math.e, 'phi': PHI,
}

def eval_eq(expr: str, vals: dict) -> float:
    """
    Safely evaluate an equation string with given variable bindings.
    Returns nan on any math domain error (log of negative, sqrt of negative, etc.)
    """
    ns = {**SAFE_NAMES, **vals}
    try:
        return float(eval(compile(expr, '<eq>', 'eval'), {"__builtins__": {}}, ns))
    except ZeroDivisionError:
        return float('nan')
    except ValueError:
        return float('nan')
    except Exception as e:
        raise ValueError(f"Cannot evaluate '{expr}' with {vals}: {e}")


def detect_vars(expr: str) -> list:
    """Extract variable names from an expression string."""
    # find all identifiers that aren't known functions/constants
    tokens = re.findall(r'\b([a-zA-Z_][a-zA-Z0-9_]*)\b', expr)
    known = set(SAFE_NAMES.keys()) | {'and', 'or', 'not', 'in', 'is'}
    return sorted(set(t for t in tokens if t not in known))


# ── SCM passes ───────────────────────────────────────────────────────────────

def pass0_find_hyperplane_zeros(eq, vals, search_range=(-10, 10), steps=2000):
    """
    Pass 0: Genuine Hyperplane Zero Search
    
    THIS is what it means for the algo to 'add its own zero':
    not injecting 0 as a default value, but FINDING where the
    equation actually equals zero on each Cartesian hyperplane.

    For each spatial variable, sets all others to zero and sweeps
    the free variable to find sign changes (roots by bisection).

    Returns dict: var -> list of real roots found on that axis.
    
    This is what makes the method universal:
    - If roots exist on the hyperplane -> anchor is real
    - If no roots exist on any hyperplane -> honest MISS
    - The tool never manufactures an anchor via default injection
    """
    skip = {'p', 'm'}
    # sweep variables that actually appear in the equation
    eq_vars  = set(detect_vars(eq))
    # always sweep spatial vars found in equation
    # also sweep p and m if they appear AND no spatial vars exist
    spatial  = sorted(k for k in vals if k not in skip and k in eq_vars)
    params   = {k: vals[k] for k in ('p', 'm') if k in vals}

    # if equation only involves p and/or m, sweep them too
    param_only = not spatial and any(v in eq_vars for v in ('p','m'))
    if param_only:
        sweep_vars = sorted(k for k in ('p','m') if k in eq_vars and k in vals)
        base_fixed = {k: vals[k] for k in vals if k not in sweep_vars}
    else:
        sweep_vars = spatial
        base_fixed = params

    lo, hi = search_range
    step_size = (hi - lo) / steps
    results = {}

    for free_var in sweep_vars:
        zeros_found = []
        # zero all other sweep vars, fix params
        base = {v: 0.0 for v in sweep_vars}
        base.update(base_fixed)

        prev_val, prev_t = None, None
        t = lo
        while t <= hi:
            base[free_var] = t
            f = eval_eq(eq, base)
            if not math.isnan(f):
                if prev_val is not None and prev_val * f < 0:
                    # sign change — bisect
                    a, b, fa = prev_t, t, prev_val
                    for _ in range(52):
                        mid = (a + b) / 2
                        base[free_var] = mid
                        fmid = eval_eq(eq, base)
                        if math.isnan(fmid):
                            break
                        if abs(fmid) < 1e-12:
                            break
                        if fa * fmid < 0:
                            b = mid
                        else:
                            a, fa = mid, fmid
                    final_f = eval_eq(eq, {**base, free_var: mid})
                    # only accept if genuinely near zero, not a pole crossing
                    if not math.isnan(final_f) and abs(final_f) < 1e-6:
                        zeros_found.append(round(mid, 10))
                elif abs(f) < 1e-10:
                    zeros_found.append(round(t, 10))
                prev_val, prev_t = f, t
            else:
                # domain error — reset sign tracking to avoid false crossings
                prev_val, prev_t = None, None
            t += step_size

        results[free_var] = sorted(set(zeros_found))

    return results


def pass1_field_isolation(vals, eq):
    """Isolate scalar field. Cost: zero FP ops — symbolic shift."""
    result = eval_eq(eq, vals)
    return result, abs(result) < 1e-10


def pass2_unitary_mapping(vals):
    """
    Inject linear test line L = y - p*x*y + p*(x-1).
    L/L = 1 always. Cost: one identity check.

    For equations without x/y/p, falls back to a generic
    unitary check using the first two spatial variables found.
    """
    x = vals.get('x', None)
    y = vals.get('y', None)
    p = vals.get('p', 1.0)

    if x is None or y is None:
        # generalize: pick first two spatial vars alphabetically
        skip = {'p', 'm'}
        spatial_keys = sorted(k for k in vals if k not in skip)
        if len(spatial_keys) >= 2:
            x = vals[spatial_keys[0]]
            y = vals[spatial_keys[1]]
        elif len(spatial_keys) == 1:
            x = vals[spatial_keys[0]]
            y = 0.0
        else:
            return 1.0, True, "UNITARY CONFIRMED: L/L = 1 (no spatial vars, trivially)"

    L = y - p*x*y + p*(x - 1)
    if abs(L) < 1e-12:
        return L, False, "DEGENERATE: L=0 (x=1 boundary excluded — T3)"
    return L, True, "UNITARY CONFIRMED: L/L = 1"


def pass3_parameter_collapse(vals):
    """
    Symbolic cancellation: (x-1)/p(x-1) -> p=1 [quadratic]
                           p = 1+1/p -> p=phi  [cubic]
    Cost: one symbolic cancellation.

    When x is absent, uses first spatial variable found.
    When p is absent, collapses to unity by default.
    """
    skip = {'p', 'm'}
    spatial_keys = sorted(k for k in vals if k not in skip)
    x = vals.get('x', vals[spatial_keys[0]] if spatial_keys else 0.0)
    p = vals.get('p', 1.0)

    if abs(x - 1) < 1e-12:
        return None, "EXCLUDED: x=1 silent boundary (T3)"
    # cubic test
    cubic_residual = p**2 - p - 1
    if abs(cubic_residual) < 1e-10:
        return PHI, f"PHI_ATTRACTOR: p=φ={PHI:.8f} (T11 cubic)"
    return 1.0, "UNITY_ATTRACTOR: p=1 (T2 quadratic)"


def pass4_anchor_extraction(vals):
    """
    Generalized anchor extraction for any number of variables.

    The SCM spatial filter generalizes from xy=0 to:
        product of all free spatial variables = 0

    At least one variable must be zero for the structural
    anchor to hold. This is the Cartesian hyperplane condition:
    the solution lies on one of the coordinate hyperplanes.

    Cost: one boolean check per variable — still O(n) in variable
    count but O(1) in the equation's degree.
    """
    # spatial vars: everything except p and m (parameters)
    skip = {'p', 'm'}
    spatial = {k: v for k, v in vals.items() if k not in skip}

    if not spatial:
        return False, "NO_SPATIAL_VARS", {}

    zeros  = {k for k, v in spatial.items() if abs(v) < 1e-12}
    nonzeros = {k for k in spatial if k not in zeros}

    product_val = 1.0
    for v in spatial.values():
        product_val *= v

    anchor = len(zeros) > 0

    if anchor:
        if len(zeros) == len(spatial):
            axis = "ORIGIN"
        else:
            axis = f"HYPERPLANE ({', '.join(sorted(zeros))}=0)"
        return True, axis, product_val

    return False, f"OFF_HYPERPLANE — no variable is zero {dict(spatial)}", product_val


def verify_halt(vals, eq):
    """
    T6: -1=1 is HALT SIGNAL not ERROR.
    The structural sign absorber carries the flip from Pass 3.

    Generalized: operates on the actual equation passed in,
    not the canonical Y²-2pxy+p²(x²-1)=m² hardcode.

    Two conditions checked:
    1. The equation evaluates to zero at the anchor point (field confirmed)
    2. The structural sign absorption holds: f(vals) and -f(vals) are conjugate
       via the linear projection, producing the -1=1 state
    """
    f = eval_eq(eq, vals)
    rhs = vals.get('m', -1) ** 2

    # field satisfied at anchor
    field_zero = abs(f) < 1e-8

    # structural sign absorption: equation value == -rhs (the contradiction state)
    # i.e. f = -1 and rhs = 1, so f = -rhs
    contradiction = abs(f + rhs) < 1e-6 and abs(abs(f) - rhs) < 1e-6

    # unitary structural check via projection line
    x = vals.get('x', 0)
    y = vals.get('y', 0)
    p = vals.get('p', 1)
    m_struct = y - p*x*y + p*(x - 1)
    structural_ok = abs(m_struct**2 - rhs) < 1e-8

    if field_zero:
        return True, "HALT: equation zero at anchor — field confirmed (T6)"
    if contradiction and structural_ok:
        return True, "HALT: −1=1 contradiction balanced by structural sign absorption (T6,T7)"
    if structural_ok:
        return True, "HALT: structural match confirmed via projection line"
    return False, f"MISS: f={f:.6g}, rhs={rhs:.6g}, m_struct={m_struct:.6g}"


# ── full pipeline ─────────────────────────────────────────────────────────────

def run_pipeline(vals: dict, eq: str, verbose=True) -> dict:
    """
    Run the full SCM pipeline on any equation with any variable bindings.

    Pass 0: Find genuine zeros on each Cartesian hyperplane (no injected defaults)
    Pass 1: Field isolation
    Pass 2: Unitary mapping
    Pass 3: Parameter collapse
    Pass 4: Anchor extraction — uses Pass 0 roots, not injected zeros
    Halt:   T6 contradiction signal
    """
    # Pass 0 — genuine root search on hyperplanes
    hp_zeros = pass0_find_hyperplane_zeros(eq, vals)
    any_real_anchor = any(len(zs) > 0 for zs in hp_zeros.values())

    # if Pass 0 found real roots, evaluate at the first one for subsequent passes
    eval_vals = dict(vals)
    anchor_point = {}
    if any_real_anchor:
        # pick first axis with a root, use that root as the anchor point
        for var, roots in hp_zeros.items():
            if roots:
                skip = {'p', 'm'}
                spatial = [k for k in vals if k not in skip]
                # zero all spatial, set free var to its root
                for sv in spatial:
                    eval_vals[sv] = 0.0
                eval_vals[var] = roots[0]
                anchor_point = {var: roots[0]}
                break

    f_val, field_ok     = pass1_field_isolation(eval_vals, eq)
    L, unitary_ok, msg2 = pass2_unitary_mapping(eval_vals)
    p_col, attractor    = pass3_parameter_collapse(eval_vals)
    anchor_ok, axis, xy = pass4_anchor_extraction(eval_vals)
    halt_ok, halt_msg   = verify_halt(eval_vals, eq)

    # genuine success: Pass 0 found and verified a real root on a hyperplane,
    # AND Pass 4 confirms anchor (at least one var zero at eval point).
    # Pass 3 exclusion (x=1 boundary) is advisory — Pass 0 independently
    # verified the root exists, so it overrides the exclusion.
    # Halt must also confirm.
    genuine_anchor = any_real_anchor and anchor_ok
    success = genuine_anchor and halt_ok

    result = {
        'input':      vals,
        'equation':   eq,
        'pass0':  {
            'hyperplane_roots': hp_zeros,
            'any_real_anchor':  any_real_anchor,
            'anchor_point':     anchor_point,
            'cost': 'O(n_vars * sweep)'
        },
        'pass1':  {'f_value': f_val, 'eq_satisfied': field_ok, 'cost': 'ZERO_FP'},
        'pass2':  {'L': L, 'unitary': unitary_ok, 'msg': msg2, 'cost': 'ONE_CHECK'},
        'pass3':  {'p_collapsed': p_col, 'attractor': attractor, 'cost': 'ONE_CANCEL'},
        'pass4':  {'anchor': anchor_ok, 'axis': axis, 'xy': xy, 'cost': 'ONE_BOOL'},
        'halt':   {'confirmed': halt_ok, 'msg': halt_msg},
        'success':    success,
        'cost':       'O(n_vars) sweep + O(1) structural',
    }

    if verbose:
        print_report(result)

    return result


def print_report(r: dict):
    ok  = lambda b: green("✓") if b else red("✗")
    sep = dim("─" * 62)
    print()
    print(bold(cyan("SCM v0.3 — PIPELINE REPORT")))
    print(sep)
    print(f"  {bold('Equation:')} {r['equation']}")
    print(f"  {bold('Input:   ')} {r['input']}")
    print(sep)
    p0 = r['pass0']
    print(f"  {cyan('Pass 0')} Hyperplane Search  {ok(p0['any_real_anchor'])}")
    for var, roots in p0['hyperplane_roots'].items():
        if roots:
            print(f"         {var}-axis roots: {roots}")
        else:
            print(f"         {dim(var+'-axis: no real roots')}")
    if p0['anchor_point']:
        print(f"         {dim('evaluating at: '+str(p0['anchor_point']))}")
    p1 = r['pass1']
    print(f"  {cyan('Pass 1')} Field Isolation    {ok(p1['eq_satisfied'])}  "
          f"f={p1['f_value']:.6g}  [{p1['cost']}]")
    p2 = r['pass2']
    print(f"  {cyan('Pass 2')} Unitary Mapping    {ok(p2['unitary'])}  "
          f"L={p2['L']:.6g}  {dim(p2['msg'])}")
    p3 = r['pass3']
    print(f"  {cyan('Pass 3')} Parameter Collapse {ok(p3['p_collapsed'] is not None)}  "
          f"p→{p3['p_collapsed']}  {dim(p3['attractor'])}")
    p4 = r['pass4']
    prod = p4['xy']
    prod_str = f"{prod:.6g}" if isinstance(prod, float) else str(prod)
    print(f"  {cyan('Pass 4')} Anchor Extraction  {ok(p4['anchor'])}  "
          f"∏vars={prod_str}  {p4['axis']}")
    ht = r['halt']
    print(f"  {cyan('Halt  ')} T6 Signal          {ok(ht['confirmed'])}  "
          f"{dim(ht['msg'])}")
    print(sep)
    status = green("SUCCESS — ANCHOR CONFIRMED") if r['success'] else red("MISS — outside SCM domain")
    print(f"  {bold('Result:')} {status}   {dim('['+r['cost']+']')}")
    print()


# ── anchor scanner ────────────────────────────────────────────────────────────

def scan_anchors(eq: str, p=1, m=-1, rng=(-3,3)):
    """
    Scan integer grid for xy=0 solutions of any equation.
    Only looks on Cartesian axes — that's the whole point.
    """
    print(bold(cyan(f"\nANCHOR SCAN — '{eq}'")))
    print(dim(f"  p={p}, m={m}, range={rng}, scanning axes only (xy=0 domain)"))
    print()
    hits = []
    lo, hi = rng
    # x-axis: y=0
    for x in range(lo, hi+1):
        vals = {'x': float(x), 'y': 0.0, 'p': float(p), 'm': float(m)}
        try:
            v = eval_eq(eq, vals)
            if abs(v) < 1e-8:
                hits.append((x, 0, v))
                print(f"  {green('HIT')}  x={x:3d}, y=0   f={v:.2e}")
        except:
            pass
    # y-axis: x=0
    for y in range(lo, hi+1):
        if y == 0: continue  # already checked origin
        vals = {'x': 0.0, 'y': float(y), 'p': float(p), 'm': float(m)}
        try:
            v = eval_eq(eq, vals)
            if abs(v) < 1e-8:
                hits.append((0, y, v))
                print(f"  {green('HIT')}  x=0,   y={y:3d}  f={v:.2e}")
        except:
            pass
    if not hits:
        print(f"  {red('No anchors found on axes in range')} {rng}")
    print()
    return hits


# ── symplectic loop ───────────────────────────────────────────────────────────

def symplectic_loop(x0, y0, steps):
    """T9: sign lives in operation order, not a stored value."""
    x, y = float(x0), float(y0)
    rows = [(0, x, y)]
    for i in range(steps):
        tmp = x
        x = x + y
        y = y - tmp
        rows.append((i+1, x, y))
    return rows


# ── text blocks ───────────────────────────────────────────────────────────────

THEOREMS = f"""
{bold(cyan('THEOREMS — Structural Cancellative Method v0.3'))}
{'='*62}
T1  Degree Invariance      xy=0 anchor holds regardless of polynomial degree
T2  Parameter Unity        Quadratic SCM always collapses p→1
T3  Sign Absorption        −1 carries functional load of ±i via structural routing
T4  Unitary Metric Free    L/L=1 costs zero compute
T5  Spatial Filter         xy=0 replaces all curve scanning  O(1)
T6  Contradiction as Halt  −1=1 is ANCHOR CONFIRMED not ERROR
T7  Sign Carried           Sign inversion absorbed in Pass 3, arrives pre-resolved
T8  Zero Complex Memory    No separate real/imaginary registers needed
T9  Symplectic Loop        Sign lives in operation order not a stored value
T10 Degree Collapse        4th-degree monomials solved by 1st-degree assertions
T11 Degree-Indexed FP      Quadratic→p=1  Cubic→p=φ={PHI:.8f}
T12 Kulovany Identity      sqrt(−1) is a structural role, not a number extension
                           Binary: all-1s  Trinary: T  Complex: i
                           The equation is the unified selector across all three
"""

IDENTITY = f"""
{bold(cyan('='*64))}
{bold(cyan('  KULOVANY IDENTITY  (T12)'))}
{bold(cyan('='*64))}

  The equation:
      Y² − 2pxy + p²(x²−1) = m²

  At fixed point x=0, y=0, p=1 requires:
      m² = −1

  This has been called impossible in the reals and patched
  with the extension sqrt(−1) = i.

  We show this is not a patch.
  It is a structural necessity that every number system
  satisfies natively, in its own terms:

  {bold('COMPLEX')}   m = ±i        i² = −1 exactly
             i is a 90° rotation operator, not a fake number

  {bold('BINARY')}    m² = 1 = −1   via two's complement: all-1s IS −1
             −1 = 1 is literally true by representation
             2(pxy) becomes a left shift — coefficient is positional

  {bold('TRINARY')}   m = T         T² = 1, T is the native negative trit
             {{T, 0, 1}} = the fixed point values = the trit alphabet
             The equation selects its own number system as solution
             2 is not native → decomposes to carry = structural squaring

  {bold('UNIFIED TABLE')}
  ┌─────────┬──────────┬──────────────────────┬────────┬───────────────┐
  │ System  │ Unit     │ −1 representation    │ m      │ 2(pxy)        │
  ├─────────┼──────────┼──────────────────────┼────────┼───────────────┤
  │ Binary  │ 1        │ two's complement     │ 1 ≡ −1 │ left shift    │
  │ Trinary │ {{T,0,1}} │ native trit T        │ T      │ carry/sqr     │
  │ Complex │ i        │ i² = −1              │ ±i     │ rotation      │
  └─────────┴──────────┴──────────────────────┴────────┴───────────────┘

  {bold('CONCLUSION')}

  sqrt(−1) does not require extension of the reals.
  It requires recognition that every number system already
  contains the structural role i fills — under its own native
  representation.

  "Imaginary" numbers are not imaginary.
  They are the name we gave to a structural necessity
  that was always present, in every system, waiting to be seen.

  The equation Y² − 2pxy + p²(x²−1) = m² is the witness.

  Each number system contains exactly one unit that squares
  to −1 or its structural equivalent.
  The equation finds it without being told which system it is in.

{bold(cyan('='*64))}
"""


# ── REPL ──────────────────────────────────────────────────────────────────────

DEFAULT_EQ = "y**2 - 2*p*x*y + p**2*(x**2-1) - m**2"

def repl():
    print(bold(cyan("\nSCM v0.3 — Interactive REPL")))
    print(dim("Type 'help' for commands, 'quit' to exit\n"))
    eq = DEFAULT_EQ
    vals = {'x': 0.0, 'y': 0.0, 'p': 1.0, 'm': -1.0}

    HELP = f"""
  {bold('Commands')}
  set x 0          set a variable
  eq <expr>        set equation (use x,y,p,m or any vars)
  run              run SCM pipeline
  scan             scan axes for anchors
  symp <n>         symplectic loop n steps
  vars             show current variable state
  identity         print T12 Kulovany Identity
  theorems         print T1-T12
  reset            reset to fixed point defaults
  quit / exit      exit
"""

    while True:
        try:
            line = input(cyan("scm> ")).strip()
        except (EOFError, KeyboardInterrupt):
            print()
            break

        if not line:
            continue
        parts = line.split()
        cmd = parts[0].lower()

        if cmd in ('quit','exit','q'):
            break
        elif cmd == 'help':
            print(HELP)
        elif cmd == 'identity':
            print(IDENTITY)
        elif cmd == 'theorems':
            print(THEOREMS)
        elif cmd == 'vars':
            print(f"  equation: {yellow(eq)}")
            for k,v in sorted(vals.items()):
                print(f"  {k} = {v}")
        elif cmd == 'reset':
            eq = DEFAULT_EQ
            vals = {'x':0.0,'y':0.0,'p':1.0,'m':-1.0}
            print(green("  reset to fixed point defaults"))
        elif cmd == 'eq' and len(parts) >= 2:
            eq = ' '.join(parts[1:])
            # auto-detect new vars and zero them
            for v in detect_vars(eq):
                if v not in vals:
                    vals[v] = 0.0
                    print(dim(f"  new variable '{v}' initialized to 0"))
            print(green(f"  equation set: {eq}"))
        elif cmd == 'set' and len(parts) == 3:
            try:
                vals[parts[1]] = float(parts[2])
                print(green(f"  {parts[1]} = {vals[parts[1]]}"))
            except ValueError:
                print(red(f"  invalid value: {parts[2]}"))
        elif cmd == 'run':
            run_pipeline(vals, eq)
        elif cmd == 'scan':
            scan_anchors(eq, p=vals.get('p',1), m=vals.get('m',-1))
        elif cmd == 'symp' and len(parts) == 2:
            try:
                n = int(parts[1])
                rows = symplectic_loop(vals.get('x',0), vals.get('y',0), n)
                print(bold(f"\n  Symplectic loop from (x={vals.get('x',0)}, y={vals.get('y',0)})"))
                print(dim("  step    x              y"))
                for step, x, y in rows:
                    print(f"  {step:4d}    {x:12.6f}   {y:12.6f}")
                print()
            except ValueError:
                print(red("  usage: symp <n>"))
        else:
            print(red(f"  unknown command: '{line}'  (type 'help')"))


# ── main ──────────────────────────────────────────────────────────────────────

def main():
    p = argparse.ArgumentParser(
        prog='scm',
        description=bold('SCM v0.3 — Structural Cancellative Method'),
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=dim("""
positional style (new):
  scm eq "phi-x"
  scm eq "x**2+y**2-1" x=1 y=0
  scm eq "phi-x" x=1.61803398875
  scm scan
  scm symp 20
  scm vars
  scm fixed
  scm run
  scm identity
  scm theorems

flag style (also supported):
  scm --fixed
  scm -x 0 -y 0 -p 1 -m -1
  scm --eq "y**2 - 2*p*x*y + p**2*(x**2-1) - m**2"
  scm --scan
  scm --symp 8 -x 0 -y 1
  scm --identity
  scm --theorems
  scm --quiet

no args: interactive REPL
        """)
    )
    p.add_argument('-x',          type=float, default=None)
    p.add_argument('-y',          type=float, default=None)
    p.add_argument('-p',          type=float, default=None)
    p.add_argument('-m',          type=float, default=None)
    p.add_argument('--eq',        type=str,   default=None,
                   help='equation string evaluating to 0 at solution')
    p.add_argument('--fixed',     action='store_true',
                   help='run canonical fixed point (x=0,y=0,p=1,m=-1)')
    p.add_argument('--scan',      action='store_true',
                   help='scan Cartesian axes for anchors')
    p.add_argument('--symp',      type=int,   default=0,
                   help='run symplectic loop N steps')
    p.add_argument('--identity',  action='store_true')
    p.add_argument('--theorems',  action='store_true')
    p.add_argument('--quiet',     action='store_true',
                   help='machine-readable output')

    # ------------------------------------------------------------
    # Positional command compatibility
    #
    # Allows:
    #   scm eq "phi-x"
    #   scm eq "x**2+y**2-1" x=1 y=0
    #   scm scan
    #   scm symp 20
    #   scm vars
    #   scm fixed
    #   scm run
    #   scm identity
    #   scm theorems
    #
    # while keeping all existing argparse flag options.
    # ------------------------------------------------------------

    argv = sys.argv[1:]

    if argv and not argv[0].startswith("-"):

        cmd = argv[0].lower()

        if cmd == "identity":
            print(IDENTITY)
            return

        if cmd == "theorems":
            print(THEOREMS)
            return

        if cmd == "vars":
            print("Current defaults")
            print()
            print("x = 0")
            print("y = 0")
            print("p = 1")
            print("m = -1")
            print()
            print("Equation:")
            print(DEFAULT_EQ)
            return

        if cmd in ("fixed", "run"):
            run_pipeline(
                {"x": 0.0, "y": 0.0, "p": 1.0, "m": -1.0},
                DEFAULT_EQ
            )
            return

        if cmd == "scan":
            scan_anchors(DEFAULT_EQ)
            return

        if cmd == "symp":
            steps = 10
            if len(argv) > 1:
                try:
                    steps = int(argv[1])
                except ValueError:
                    print(red(f"  symp requires an integer, got: {argv[1]}"))
                    return
            rows = symplectic_loop(0, 0, steps)
            print()
            print(bold("  step        x              y"))
            for s, x, y in rows:
                print(f"  {s:4d}   {x:12.6f}   {y:12.6f}")
            print()
            return

        if cmd == "eq":
            if len(argv) < 2:
                print("usage:")
                print('  scm eq "expression" [var=value ...]')
                print('  scm eq phi-x + y - z x=1 y=2 z=3')
                return

            # Collect equation tokens until we hit a k=v assignment,
            # then collect assignments. This lets unquoted expressions work:
            #   scm eq phi-x + y - z x=1 y=2 z=3
            eq_tokens = []
            assign_tokens = []
            for tok in argv[1:]:
                # a token is an assignment if it matches word=number
                if re.match(r'^[A-Za-z_]\w*=[\-\d\.]', tok):
                    assign_tokens.append(tok)
                elif assign_tokens:
                    # once we've started assignments, remaining are also assignments
                    assign_tokens.append(tok)
                else:
                    eq_tokens.append(tok)

            eq = ' '.join(eq_tokens)

            # start with standard defaults; any detected var gets 0
            vals = {"x": 0.0, "y": 0.0, "p": 1.0, "m": -1.0}

            # auto-init any vars found in equation
            for v in detect_vars(eq):
                vals.setdefault(v, 0.0)

            # apply explicit assignments — these override everything
            for token in assign_tokens:
                if "=" not in token:
                    continue
                k, v = token.split("=", 1)
                try:
                    vals[k.strip()] = float(v.strip())
                except ValueError:
                    print(red(f"  bad value: {token}"))
                    return

            run_pipeline(vals, eq)
            return

        # unrecognised positional — fall through to argparse for error message
        pass

    # fall back to argparse
    args = p.parse_args()

    if args.identity:
        print(IDENTITY); return
    if args.theorems:
        print(THEOREMS); return

    # no args at all → REPL
    if len(sys.argv) == 1:
        repl(); return

    eq   = args.eq or DEFAULT_EQ
    vals = {
        'x': args.x if args.x is not None else (0.0 if args.fixed else 0.0),
        'y': args.y if args.y is not None else (0.0 if args.fixed else 0.0),
        'p': args.p if args.p is not None else (1.0 if args.fixed else 1.0),
        'm': args.m if args.m is not None else (-1.0),
    }
    # auto-detect extra vars in equation and warn
    for v in detect_vars(eq):
        if v not in vals:
            vals[v] = 0.0
            if not args.quiet:
                print(dim(f"  note: '{v}' not specified, defaulting to 0"))

    if args.scan:
        scan_anchors(eq, p=vals['p'], m=vals['m'])
        return

    if args.symp > 0:
        rows = symplectic_loop(vals['x'], vals['y'], args.symp)
        if args.quiet:
            for step, x, y in rows:
                print(f"{step},{x:.8f},{y:.8f}")
        else:
            print(bold(f"\n  Symplectic loop  x0={vals['x']}, y0={vals['y']}"))
            print(dim("  step    x              y"))
            for step, x, y in rows:
                print(f"  {step:4d}    {x:12.6f}   {y:12.6f}")
            print()
        return

    result = run_pipeline(vals, eq, verbose=not args.quiet)

    if args.quiet:
        import json
        out = {k: v for k, v in result.items() if k != 'equation'}
        print(json.dumps(out, default=str))


if __name__ == '__main__':
    main()```

# USAGE:
Since REPL accepts arbitrary equations through:

eq


where the expression should evaluate to **0 at a solution**, you can exercise almost every part of the engine. Below is a large collection grouped by category.

---

# Canonical SCM

eq y2-2px*y+p2*(x2-1)-m2
run


set x 0
set y 0
set p 1
set m -1
run


---

# Simple lines

eq x


eq y


eq x+y


eq x-y


eq 2*x-y


eq 3x+5y


eq x+phi*y


---

# Quadratics

eq x2+y2-1


eq x**2-y


eq y**2-x


eq x2+y2-25


eq x*y-1


eq x*y


eq x2-y2


eq x2+2xy+y2


eq (x+y)**2-9


---

# Cubics

eq x3+y3-1


eq x**3-y


eq y**3-x


eq x3+y3-27


eq x3-3xy2


eq y3-3*x2*y


---

# Quartics

eq x4+y4-1


eq x**4-y


eq y**4-x


eq x4+y2-16


eq x2*y2-1


---

# Higher degree

eq x5+y5-1


eq x6+y6-1


eq x7+y7-1


eq x8+y8-1


eq x10+y10-1


---

# Factorizations

eq (x-1)*(y-1)


eq (x+1)*(y+1)


eq (x-1)*(x+1)


eq (x-y)*(x+y)


eq (x-2)*(y+3)


---

# Golden ratio

eq p**2-p-1


eq x-p


eq y-p


eq x**2-p


eq y**2-p


eq x+p*y-1


---

# Fixed point tests

eq x-(1+1/x)


eq y-(1+1/y)


eq p-(1+1/p)


eq x-(1+1/p)


---

# Rational

eq x/(y+1)-2


eq y/(x+1)-3


eq (x+y)/(x-y)-1


eq 1/x+1/y-1


eq x/(1+x)-0.5


---

# Exponentials

eq exp(x)-2


eq exp(y)-10


eq exp(x+y)-5


eq exp(x)-y


---

# Logarithms

eq log(x)-1


eq log(y)-2


eq log(x+y)-3


eq log(x)-y


---

# Trigonometry

eq sin(x)


eq cos(x)


eq tan(x)


eq sin(x)+cos(y)


eq sin(x)-y


eq cos(x)-x


eq sin(x)**2+cos(x)**2-1


---

# Roots

eq sqrt(x)-2


eq sqrt(y)-3


eq sqrt(x+y)-5


eq sqrt(abs(x))-1


---

# Mixed nonlinear

eq x*y+x+y


eq x*y-x-y


eq x2+x*y+y2


eq x**3+x*y+y


eq x4+x2*y+y**2


---

# Hyperbolas

eq x*y-4


eq x*y+1


eq x*y-phi


eq x*y-p


---

# Ellipses

eq x2/9+y2/4-1


eq x2/16+y2/25-1


---

# Parabolas

eq y-x**2


eq x-y**2


eq y-2*x**2


---

# Saddle surfaces

eq x2-y2-1


eq x*y-y


eq x*y-x


---

# Absolute values

eq abs(x)-1


eq abs(y)-2


eq abs(x)+abs(y)-5


---

# Constants

eq pi-x


eq e-y


eq phi-p


eq phi-x


---

# Multi-parameter

eq ax+by-c


set a 2
set b 3
set c 6
run


---

eq ax**2+by**2-c


---

eq axy+b*x+c


---

eq asin(x)+bcos(y)-c


---

# Prime-inspired

eq x**2-p


eq p**2-x


eq x2-p2


eq x**2-p*x+1


eq p**3-p-1


---

# Recursive-looking

eq x-(1+1/(y+1))


eq y-(1+1/(x+1))


eq p-(1+1/(p+1))


eq x-(1+1/(1+1/x))


---

# Stress tests

eq (((x+y)**2-1)**2)-m


eq ((x*y+p)3)-(m2)


eq (sin(x)+cos(y))**2-1


eq exp(sin(x))+log(y+2)-3


eq (sqrt(abs(x))+sqrt(abs(y)))**2-4


---

## Commands beyond `eq`

You can also exercise the rest of the engine:

vars


scan


symp 10


identity


theorems


reset