TNFR Logo
TheoryLearnSoftwareResearch

On this page

TNFR

Resonant Fractal Nature Theory — a mathematical framework for coherent patterns on graph-coupled networks.

About
  • Project history
  • Editorial policy
  • Contact
Resources
  • GitHub
  • PyPI
  • DOI · Zenodo
Legal
  • MIT License
  • Citation
© 2026 TNFR project — MIT licensed.DOI 10.5281/zenodo.17602860
docs
grammar
PHYSICS_VERIFICATION.md
API_CONTRACTS.mdCANONICAL_OZ_SEQUENCES.mdEMPIRICAL_CONFRONTATION_EEG.mdREADME.mdSTRUCTURAL_FIELDS_TETRAD.mdSTRUCTURAL_INTERFACE_THEORY.md
theory
APPLIED_STRUCTURAL_ANALYSIS.mdCATALOG_TYPE_HYGIENE_PROGRAMME.mdDISSIPATIVE_AND_OPEN_SYSTEMS.mdEMERGENT_ONTOLOGY.mdEXTENDED_FIELDS_AND_DERIVED_QUANTITIES.mdFUNDAMENTAL_THEORY.mdGAUGE_SYMMETRY_AND_UNIFICATION.mdGLOSSARY.mdMATHEMATICAL_DYNAMICS_BASIS.mdMINIMAL_STRUCTURAL_DEGREES.mdNUCLEUS_A_PRIME_LADDER_ATLAS.mdNUCLEUS_B_EQUIVARIANCE_OBSTRUCTIONS.mdPHYSICAL_REGIME_CORRESPONDENCES.mdREADME.mdREMESH_INFINITY_DERIVATION.mdSTRUCTURAL_CONSERVATION_THEOREM.mdSTRUCTURAL_OPERATORS.mdSTRUCTURAL_STABILITY_AND_DYNAMICS.mdTNFR_BSD_RESEARCH_NOTES.mdTNFR_HODGE_RESEARCH_NOTES.mdTNFR_NAVIER_STOKES_RESEARCH_NOTES.mdTNFR_NUMBER_THEORY.mdTNFR_P_VS_NP_RESEARCH_NOTES.mdTNFR_RIEMANN_RESEARCH_NOTES.mdTNFR_VARIATIONAL_PRINCIPLE.mdTNFR_YANG_MILLS_RESEARCH_NOTES.mdTNFR.pdfUNIFIED_GRAMMAR_RULES.md
factorization-lab
analysis
analyze_patterns.pycertificate_manifest.py
benchmarks
benchmark_analysis.pybenchmark_expansion_suite.pyfull_spectrum_factorization.pypaley_gap_extended.pypaley_gap_smoke.pytest_benchmark_suite.py
demos
experiment_contexts
exp_0b1663cd19b7.jsonexp_0bf0054b7474.jsonexp_75a4c8ca616a.jsonexp_848ee0fd1857.jsonexp_f6fe00562193.jsonexp_fdf3da424e1e.json
failure_telemetry_batch.pyfeedback_integration_demo.pyintegration_demo_snapshots.dbseed_management_integration_demo.pysnapshot_integration_demo.pytrajectory_143.jsontrajectory_77.jsontrajectory_89.jsontrajectory_91.jsontrajectory_97.json
docs
FACTORING_PLAYBOOK.mdFALSE_POSITIVE_TEST_SUITE.mdOPERATOR_CERTIFICATES.mdROADMAP.mdSPECTRAL_ROUTE.md
experiment_contexts
exp_cebe1d9e7d8e.json
notebooks
spectral_history.ipynb
scripts
run_false_positive_tests.py
tests
run_false_positive_test_suite.pytest_cli.pytest_false_positive_methodology.pytest_false_positive_verifier.pytest_feedback_integration.pytest_partitioning.pytest_seed_management.pytest_self_opt_support.pytest_snapshot_system.pytest_spectral_paley.pytest_verification_robustness.py
tnfr_factorization
__init__.pyapi.pycli.pyfailure_telemetry.pyfeedback_adapter.pyfeedback_integration.pypartitioning.pyself_opt_support.pyspectral_paley.py
demo_snapshots.dbLICENSE_SNAPSHOT.mdPACKAGE_SUMMARY.mdREADME.mdseed_management.pysnapshot_system.pytest_certificate_hashing.pytest_installation.pyverification_trajectory_77.json
benchmarks
analyze_tetrad_universality.pyb0star_alpha_canonical_product_graphs.pybenchmark_optimization_tracks.pybenchmark_utils.pyboundary_vibration.pybridge_primes_riemann.pychiral_involution.pycli_utils.pycoherence_projector_sense_index.pycommutant_bridge.pycomposition_arithmetic.pyconfinement_zones_test.pyconservation_law_validation.pydirected_paley_bridge.pyemergent_arithmetic_pulse.pyemergent_atom_dynamics.pyemergent_atomic_shells.pyemergent_base_dimension.pyemergent_dimension_dynamics.pyemergent_fractal_pulse.pyemergent_fractal_simplex_dimension.pyemergent_integers_symmetry.pyemergent_musical_nfr.pyemergent_nfr_geometry.pyemergent_nfr_where.pyemergent_rationals.pyemergent_rhythm.pyemergent_screening.pyemergent_shell_cardinals.pyemergent_shell_ordering.pyemergent_simplex_dimension.pyemergent_substrate_symmetry.pyequivariance_wall.pyexternal_phase_gate_validation.pyfield_methods_battery.pygolden_residue_remesh_bridge.pyintegrated_force_regime_study.pyinverse_spectrum_to_symmetry.pyk_phi_safety_demo.pykuramoto_farey_bridge.pymissing_piece_bridge.pymultichannel_interface_benchmark.pynavier_stokes_recipe_bridge.pynodal_propagator_residue_bridge.pyns_moment_hierarchy_cascade.pyoperational_irreducibility.pypaley_bridge.pyphase_curvature_investigation.pyphase_wall.pyphi_s_confinement_investigation.pyprimes_as_consequence.pypulse_phase_coherence_budget.pyREADME.mdremesh_infinity_riemann_baseline.pyremesh_infinity_riemann_composed.pyremesh_infinity_riemann_modified_graph.pyremesh_infinity_riemann_operator.pyremesh_infinity_riemann_spectral_basis.pyremesh_infinity_riemann_spectral_robustness.pyremesh_infinity_riemann_spectral.pyresidue_phase_vs_riemann.pystructural_interface_benchmark.pytemporal_interface_benchmark.pytetrad_results_aggregate.pyu2_destabilization_irreversibility.pyuniversality_clusters.pyxi_c_fast_experiment.py
primality-test
benchmarks
comprehensive_benchmark.py
docs
ADVANCED_INTEGRATION.mdmathematical_foundation.mdperformance_analysis.md
examples
advanced_examples.pybasic_usage.py
tnfr_primality
__init__.py__main__.pyadvanced_cli.pyadvanced_core.pycli.pyconstants.pycore.pyoptimized.py
MANIFEST.inPACKAGE_SUMMARY.mdREADME.mdRELEASE_NOTES_v1.0.mdsetup.pytest_installation.py
tests
core_physics
__init__.pytest_conservation_laws.pytest_delta_nfr_computation_paths.pytest_delta_nfr.pytest_dispersion_coherence_sign_invariance.pytest_emergent_constants_guard.pytest_lyapunov_operators.pytest_nodal_equation.pytest_structural_triad.py
data
replay_manifests
sample_run
_manifest_summary.json_manifest.json_partition_files.txt.gz
self_opt_validation
seed_alpha
paley.json
seed_beta
integration.json
seed_gamma
unknown.json
self_optimization
test_run
partitioned
test_run
test_run_p0.jsontest_run_p1.json
_manifest_summary.json_manifest.json
engines
test_pattern_discovery_manifest.pytest_self_optimization_engine.py
mathematics
__init__.pytest_autodiff.pytest_backends.pytest_dissipative_dynamics.pytest_epi.pytest_factory_patterns.pytest_metrics.pytest_navier_stokes_refounded.pytest_number_theory_canonical.pytest_operators.pytest_residue_networks.pytest_riemann_nodal_pulse.pytest_riemann_pulse_coherence.pytest_spaces.pytest_transforms.pytest_validator.py
operators
test_canonical_operators_modern.pytest_grammar_canon.pytest_grammar_canonical_consistency.pytest_grammar_dynamics.pytest_operator_contracts.pytest_operator_strategies.py
parallel
test_fractal_partition_manifest.py
physics
test_conservation_gauge_unification.pytest_dissipative_conservation.pytest_emergent_chemistry.pytest_field_cache_invalidation.pytest_gauge.pytest_phase_transition.pytest_signatures.pytest_spectral_conservation.pytest_structural_diffusion.pytest_structural_integrity.pytest_symplectic_substrate.pytest_tetrad_bounds.pytest_variational.pytest_yang_mills_closure.pytest_yang_mills_derivability.pytest_yang_mills_scaling.pytest_yang_mills_structural_gap.pytest_yang_mills_u6_sweep.py
scripts
test_run_self_opt_validation.pytest_run_self_optimization.py
sdk
__init__.pytest_simple_advanced.py
__init__.pyconftest.pyREADME.mdtest_breast_cancer_phase_gate_demo.pytest_classical_mechanics.pytest_distributed_fft.pytest_external_phase_gate_validation.pytest_factorization_entrypoint.pytest_multichannel_interface.pytest_nodal_optimizer.pytest_phase_gate_api.pytest_replay_register_manifest.pytest_signal_confrontation.pytest_structural_interface_api.pytest_structural_interface_baselines.pytest_structural_interface_benchmark.pytest_temporal_interface.pytest_vectorized_coherence_length_regression.pytest_wine_quality_phase_gate_demo.pyutils.py
examples
01_foundations
01_hello_world.py02_musical_resonance.py03_network_formation.py04_operator_sequences.py05_coherence_evolution.py06_network_topologies.py07_phase_transitions.py08_emergent_phenomena.py09_visualization_suite.py10_simplified_sdk_showcase.py
02_physics_regimes
11_classical_limit_comparison.py115_operator_contract_audit.py12_classical_mechanics_demo.py13_quantum_mechanics_demo.py14_uncertainty_and_interference.py15_train_crossing_demo.py17_conservation_law_demo.py26_gauge_structure_demo.py27_variational_principle_demo.py28_dissipative_systems_demo.py29_lyapunov_stability_demo.py30_self_optimization_demo.py31_mathematical_constants_basis.py33_complex_field_unification.py34_conservation_protocol_suite.py35_tetrad_irreducibility.py36_grammar_violation_detector.py37_operator_tetrad_synergy.py38_grammar_energy_landscape.py39_nodal_equation_decomposition.py
03_riemann_zeta
157_nodal_pulse_phase_attack.py41_von_mangoldt_zeta_demo.py42_riemann_zeros_as_resonances.py43_prime_ladder_hamiltonian_demo.py44_weil_explicit_formula_demo.py45_li_keiper_demo.py46_weil_tnfr_positivity_demo.py47_alpha_sweep_demo.py48_admissible_family_sweep_demo.py49_nodeaware_gauge_sweep_demo.py50_uniform_coercivity_demo.py51_adaptive_coercivity_demo.py52_paley_gap_coercivity_demo.py53_lyapunov_spectral_positivity_demo.py54_hilbert_polya_demo.py55_structural_zero_density_demo.py56_spectral_emergence_demo.py57_admissible_rescaling_demo.py58_oscillatory_correction_demo.py
04_riemann_L_twisted
59_dirichlet_l_function_demo.py60_dirichlet_l_continuation_demo.py61_dirichlet_l_hamiltonian_demo.py62_dirichlet_weil_explicit_formula_demo.py63_dirichlet_li_keiper_demo.py64_twisted_weil_positivity_demo.py65_twisted_alpha_sweep_demo.py66_twisted_admissible_family_sweep_demo.py67_twisted_nodeaware_gauge_sweep_demo.py68_twisted_hermite_family_demo.py69_twisted_coercivity_uniform_demo.py70_twisted_paley_gap_coercivity_demo.py71_twisted_lyapunov_spectral_demo.py72_twisted_hilbert_polya_demo.py73_twisted_structural_zero_density_demo.py74_twisted_spectral_emergence_demo.py75_twisted_admissible_rescaling_demo.py76_twisted_oscillatory_correction_demo.py
05_type_hygiene
77_remesh_infinity_residue_split_demo.py78_nuf_type_signature_demo.py79_epi_type_signature_demo.py80_phi_type_signature_demo.py81_dnfr_type_signature_demo.py82_remesh_window_type_signature_demo.py83_delta_phi_max_type_signature_demo.py84_coupling_weights_type_signature_demo.py85_tetrad_closure_signature_demo.py86_currents_closure_signature_demo.py87_aggregates_closure_signature_demo.py88_urules_consistency_signature_demo.py89_operator_catalog_discipline_signature_demo.py
06_navier_stokes
158_navier_stokes_two_face_refounded.py
07_number_theory
100_prime_families_orbits.py101_numbers_as_coupled_network.py102_nodal_flow_primes_equilibria.py116_nuf_emergent_prime_visibility.py146_primality_grammatical_inertness.py147_numbers_as_free_monoid_words.py148_capacity_arm_carries_von_mangoldt.py149_p14_is_the_capacity_arm_operator.py153_structural_frequency_rank_cyclotomy.py40_arithmetic_number_theory.py94_generative_number_construction.py95_primes_from_spectral_waves.py96_spectral_vibration_of_coherence.py97_goldbach_additive_multiplicative.pyemergent_chemistry_particles_demo.py
08_emergent_geometry
103_emergent_substrate_meets_riemann.py106_per_node_polarization_geometry.py107_orthogonal_structure_emergent_geometry.py108_emergent_field_generating_structure.py112_structure_predicts_coherence_flow.py113_overdamped_projection_bridge.py114_substrate_conserved_quantities.py117_emergent_geometry_residue_graph.py118_emergent_vs_classical_operator.py119_phase_sector_directed_residue.py120_symmetry_wall_substrate_vs_spectrum.py121_canonical_symmetry_break_negative.py122_factorization_phase_sector.py123_symmetry_sector_decomposition.py124_emergent_metric_fractal_consistency.py125_node_is_the_emergent_substrate.py126_two_layers_base_fiber.py127_base_is_emergent_not_imposed.py128_base_substrate_coemergence.py129_spectral_gap_base_fiber_clock.py130_operators_break_substrate_charges.py131_coemergent_loop_convergence.py132_geometric_phase_holonomy.py133_psi_topological_defects.py134_spectral_dimension_heat_kernel.py135_arrow_of_time_h_theorem.py136_heat_kernel_coefficients.py137_synchronization_transition.py138_structure_frequency_synchronization.py139_grammar_formal_language.py140_grammar_automaton.py141_grammar_rule_decomposition.py142_grammar_operator_quotient.py143_glyphic_function_sublanguage.py144_branching_combinator.py145_syntactic_monoid_starfree.py150_emergent_grammatical_pattern_parry.py151_grammar_in_emergent_geometry.py152_operator_contract_tetrahedron.py154_conductor_annotated_qr_spectrum.py155_ontological_position_of_numbers.py156_emergence_directness_law.py98_emergent_symplectic_substrate.py99_structural_diffusion.pyunified_fields_showcase.py
09_millennium
109_p_vs_np_coherence_synthesis.py110_bsd_rank_structural_pressure.py111_hodge_discrete_and_honest_gap.py
10_applications
159_empirical_confrontation_pipeline.py90_phase_gate_monitor_demo.py91_breast_cancer_phase_gate_demo.py92_wine_quality_phase_gate_demo.py93_structural_interface_demo.pypytorch_cuda_demo.py
README.md
scripts
replay
__init__.pyregister_manifest.py
__init__.pyREADME.mdrebuild_failure_manifest.pyrun_reproducible_benchmarks.pyrun_self_opt_validation.pyrun_self_optimization.pytnfr_is_prime.pyvalidate_conservation_law.pyverify_internal_references.py
src
core
__init__.pyevaluation.py
tnfr
backends
__init__.pyjax_backend.pynumpy_backend.pyoptimized_numpy.pyREADME.mdtorch_backend.py
cli
__init__.py__init__.pyiarguments.pyarguments.pyiexecution.pyexecution.pyiinteractive_validator.pyREADME.mdutils.pyutils.pyi
compat
__init__.pydataclass.pyjsonschema_stub.pymatplotlib_stub.pynumpy_stub.pyREADME.md
config
__init__.py__init__.pyiconstants.pyconstants.pyidefaults_core.pydefaults_init.pydefaults_metric.pydefaults.pyfeature_flags.pyfeature_flags.pyiglyph_constants.pyoperator_names.pyoperator_names.pyiphysics_derivation.pyprecision_modes.pypresets.pypresets.pyiREADME.mdsecurity.pythresholds.pytnfr_config.py
constants
__init__.py__init__.pyialiases.pyaliases.pyicanonical.pymetric.pymetric.pyioperational.py
core
__init__.pycontainer.pydefault_implementations.pyexceptions.pyinterfaces.pyREADME.md
dynamics
__init__.py__init__.pyiadaptation.pyadaptation.pyiadaptive_sequences.pyadaptive_sequences.pyiadelic.pyadvanced_cache_optimizer.pyadvanced_fft_arithmetic.pyaliases.pyaliases.pyibifurcation.pycache_aware_fft_engine.pycanonical.pycanonical.pyicomputational_hub.pycoordination.pycoordination.pyidistributed_fft.pydnfr.pydnfr.pyidynamic_limits.pyemergent_centralization.pyemergent_integration_engine.pyfeedback.pyfeedback.pyifft_backend.pyfft_cache_coordinator.pyfft_dispatchers.pyfft_engine.pyfft_workers.pyfused_dnfr.pyhomeostasis.pyhomeostasis.pyiintegrators.pyintegrators.pyilearning.pylearning.pyimetabolism.pymulti_modal_cache.pynbody_tnfr.pynbody.pynodal_optimizer.pyoptimization_orchestrator.pypropagation.pyREADME.mdruntime.pyruntime.pyisampling.pysampling.pyiselectors.pyselectors.pyiself_optimizing_engine.pyspectral_structural_fusion.pystructural_cache.pystructural_clip.pysymplectic.pyunified_backend.pyunified_mathematical_cache_orchestrator.py
engines
computation
__init__.pyfft_engine.pyunified_fft_engine.pyunified_gpu_system.py
constants
__init__.pycanonical.pyoperational.py
integration
__init__.pyemergent_integration.py
pattern_discovery
__init__.pymathematical_patterns.pymulti_modal_cache.py
self_optimization
__init__.pyengine.py
__init__.pyREADME.md
errors
__init__.pycontextual.py
factorization
__init__.py
flatten
README.md
gamma
README.md
glyph_history
README.md
glyph_runtime
README.md
immutable
README.md
initialization
README.md
io
README.md
math
__init__.pyfields_symbolic.pygrammar_validators.pyoptimizer.pyREADME.mdsymbolic.py
mathematics
__init__.pybackend.pybackend.pyidynamics.pydynamics.pyiepi.pyepi.pyigenerators.pygenerators.pyiliouville.pymetrics.pymetrics.pyinumber_theory.pyoperators_factory.pyoperators_factory.pyioperators.pyoperators.pyioptimized_primality.pyprojection.pyprojection.pyiREADME.mdruntime.pyruntime.pyispaces.pyspaces.pyispectral.pytransforms.pytransforms.pyiunified_cache.pyunified_numerical.pyzeta.py
metrics
__init__.py__init__.pyibuffer_cache.pybuffer_cache.pyicache_utils.pycoherence.pycoherence.pyicommon.pycommon.pyicore.pycore.pyidiagnosis.pydiagnosis.pyiemergence.pyexport.pyexport.pyiglyph_timing.pyglyph_timing.pyilearning_metrics.pylearning_metrics.pyilocal_coherence.pyphase_coherence.pyphase_compatibility.pyREADME.mdreporting.pyreporting.pyisense_index.pysense_index.pyitelemetry.pytetrad.pytrig_cache.pytrig_cache.pyitrig.pytrig.pyi
multiscale
__init__.pyhierarchical.pyREADME.md
navier_stokes
__init__.pyconservative_face.pyoperator.py
node
README.md
observers
README.md
operators
network_analysis
__init__.pysource_detection.py
postconditions
__init__.pymutation.py
preconditions
__init__.pycoherence.pydissonance.pyemission.pymutation.pyreception.pyresonance.py
strategies
__init__.pydefaults.pygpu_strategies.pystrategy.py
__init__.py__init__.pyialgebra.pycanonical_patterns.pycascade.pycoherence.pycontraction.pycoupling.pycycle_detection.pydefinitions_base.pydefinitions.pydefinitions.pyidissonance.pyemission.pyexpansion.pygrammar_application.pygrammar_canon.pygrammar_context.pygrammar_core.pygrammar_dynamics.pygrammar_error_factory.pygrammar_memoization.pygrammar_patterns.pygrammar_telemetry.pygrammar_types.pygrammar_u6.pygrammar_validate.pygrammar.pygrammar.pyihamiltonian.pyhealth_analyzer.pyintrospection.pyjitter.pyjitter.pyilifecycle.pymetabolism.pymetrics_basic.pymetrics_core.pymetrics_network.pymetrics_structural.pymetrics_u6.pymetrics.pymutation.pynodal_equation.pyoperator_contracts.pypattern_detection.pypatterns.pyREADME.mdreception.pyrecursivity.pyregistry.pyregistry.pyiremesh.pyremesh.pyiresonance.pyself_organization.pysilence.pystructural_units.pytransition.py
parallel
__init__.pyauto_scaler.pydistributed.pyengine.pymonitoring.pypartitioner.pyREADME.md
performance
guardrails.py
physics
__init__.py_helpers.pycalibration.pycanonical.pycell.pyclassical_mechanics.pyconservation_gauge_unification.pyconservation.pydissipative_conservation.pyemergent_chemistry.pyemergent_particles.pyextended.pyfields.pygauge.pyintegrity.pyinteractions.pylife.pylyapunov.pypatterns.pyphase_transition.pyquantum_mechanics.pyREADME.mdsignatures.pyspectral_conservation.pyspectral_metrics.pystructural_diffusion.pysymplectic_substrate.pytelemetry.pyunified.pyvariational.pyvectorized_ops.py
primality
__init__.py
recipes
__init__.pycookbook.pyREADME.md
riemann
__init__.pyadmissible_family_sweep.pyadmissible_rescaling.pyaggregates_closure_signature.pyalpha_sweep.pyanalytic_continuation_dirichlet.pyanalytic_continuation.pycoercivity_uniform.pycoupling_weights_type_signature.pycurrents_closure_signature.pydelta_phi_max_type_signature.pydirichlet_l.pydnfr_type_signature.pyepi_type_signature.pyhilbert_polya.pyli_keiper.pylyapunov_spectral_positivity.pynodal_pulse.pynodeaware_gauge_sweep.pynuf_type_signature.pyoperator_catalog_discipline_signature.pyoperator.pyoscillatory_correction.pypaley_gap_coercivity.pyphi_type_signature.pyprime_ladder_hamiltonian.pypulse_coherence.pyremesh_infinity_residue_split.pyremesh_window_type_signature.pyspectral_emergence.pystructural_zero_density.pytelemetry.pytetrad_closure_signature.pytwisted_admissible_family_sweep.pytwisted_admissible_rescaling.pytwisted_alpha_sweep.pytwisted_coercivity_uniform.pytwisted_hermite_family.pytwisted_hilbert_polya.pytwisted_li_keiper.pytwisted_lyapunov_spectral_positivity.pytwisted_nodeaware_gauge_sweep.pytwisted_oscillatory_correction.pytwisted_paley_gap_coercivity.pytwisted_prime_ladder_hamiltonian.pytwisted_spectral_emergence.pytwisted_structural_zero_density.pytwisted_weil_explicit_formula.pytwisted_weil_positivity.pyurules_consistency_signature.pyvon_mangoldt.pyweil_explicit_formula.pyweil_positivity.py
schemas
__init__.pygrammar.jsonREADME.md
sdk
__init__.py__init__.pyiadaptive_system.pyadaptive_system.pyibuilders.pybuilders.pyifluent.pyfluent.pyiREADME.mdself_opt.pysimple.pytemplates.pytemplates.pyiutils.py
security
__init__.pycrypto.pydatabase.pyREADME.mdsubprocess.pyvalidation.py
sequencing
__init__.pypatterns.pyREADME.md
services
__init__.pyorchestrator.pyREADME.md
sparse
__init__.pyREADME.mdrepresentations.py
structural
README.md
telemetry
__init__.pycache_metrics.pycache_metrics.pyiconstants.pynu_f.pynu_f.pyiREADME.mdunified_telemetry_system.pyverbosity.pyverbosity.pyi
tools
__init__.pydomain_templates.pyREADME.mdsequence_generator.pytnfr_is_prime_cli_optimized.pytnfr_is_prime_cli.py
topology
__init__.pyasymmetry.pyREADME.md
utils
cache_layers.pycache.pycache.pyicallbacks.pycallbacks.pyichunks.pychunks.pyidata.pydata.pyifast_diameter.pygraph.pygraph.pyiinit.pyinit.pyiio.pyio.pyinumeric.pynumeric.pyiREADME.mdtopology.pyunified_cache.py
validation
__init__.py__init__.pyiaggregator.pybase.pycompatibility.pycompatibility.pyiconfig.pygraph.pygraph.pyihealth.pyinput_validation.pyinterface_baselines.pyinvariants.pymultichannel_interface.pyphase_gate.pyREADME.mdrules.pyrules.pyiruntime.pyruntime.pyisequence_validator.pysignal_confrontation.pysoft_filters.pysoft_filters.pyispectral.pyspectral.pyistructural_interface.pytemporal_interface.pyunified_validation_system.pyvalidator.pywindow.pywindow.pyi
visualization
__init__.pycascade_viz.pyhierarchy.pyREADME.mdsequence_plotter.py
yang_mills
__init__.pyclosure.pyderivability.pyscaling.pystructural_gap.pyu6_sweep.py
__init__.py__init__.pyi_compat.py_version.py_version.pyialias.pyalias.pyibackend_config.pycache.pycache.pyiexecution.pyexecution.pyiflatten.pyflatten.pyigamma.pygamma.pyiglyph_history.pyglyph_history.pyiglyph_runtime.pyglyph_runtime.pyiimmutable.pyimmutable.pyiinitialization.pyinitialization.pyiio.pyio.pyilocking.pylocking.pyinode.pynode.pyiobservers.pyobservers.pyiontosim.pyontosim.pyipy.typedrng.pyrng.pyisecure_config.pyselector.pyselector.pyisense.pysense.pyistructural.pystructural.pyitokens.pytokens.pyitrace.pytrace.pyitypes.pytypes.pyiunits.pyunits.pyi
tetrad_evaluator.py
.pre-commit-config.yaml.semgrep.yaml.zenodo.jsonARCHITECTURE.mdbandit.yamlCHANGELOG.mdCITATION.cffCONTRIBUTING.mdEMERGENT_CANON_AUDIT.mdEMERGENT_DERIVATION_PLAN.mdLICENSE.mdMakefileMANIFEST.inpyproject.tomlpyrightconfig.jsonPYTORCH_CUDA_INTEGRATION.mdREADME.mdSECURITY.mdTESTING.mdTNFR_Website_Content_Brief.md
FILE: src/tnfr/operators/preconditions/__init__.py

__init__.py

Precondition validators for TNFR structural operators.

Each operator has specific requirements that must be met before execution to maintain TNFR structural invariants. This package provides validators for each of the 13 canonical operators.

The preconditions package has been restructured to support both legacy imports (from ..preconditions import validate_*) and new modular imports (from ..preconditions.emission import validate_emission_strict).

Source Code

python
"""Precondition validators for TNFR structural operators.

Each operator has specific requirements that must be met before execution
to maintain TNFR structural invariants. This package provides validators
for each of the 13 canonical operators.

The preconditions package has been restructured to support both legacy
imports (from ..preconditions import validate_*) and new modular imports
(from ..preconditions.emission import validate_emission_strict).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ...types import NodeId, TNFRGraph
    import logging

from ...constants.aliases import ALIAS_DNFR, ALIAS_EPI, ALIAS_THETA, ALIAS_VF
from ...constants.canonical import DELTA_PHI_MAX, VAL_MIN_EPI

__all__ = [
    "OperatorPreconditionError",
    "validate_emission",
    "validate_reception",
    "validate_coherence",
    "validate_dissonance",
    "validate_coupling",
    "validate_resonance",
    "validate_silence",
    "validate_expansion",
    "validate_contraction",
    "validate_self_organization",
    "validate_mutation",
    "validate_transition",
    "validate_recursivity",
    "diagnose_coherence_readiness",
    "diagnose_resonance_readiness",
    "diagnose_mutation_readiness",
]


class OperatorPreconditionError(Exception):
    """Raised when an operator's preconditions are not met."""

    def __init__(self, operator: str, reason: str) -> None:
        """Initialize precondition error.

        Parameters
        ----------
        operator : str
            Name of the operator that failed validation
        reason : str
            Description of why the precondition failed
        """
        self.operator = operator
        self.reason = reason
        super().__init__(f"{operator}: {reason}")


from ..metrics_core import get_node_attr as _get_node_attr


def validate_emission(G: "TNFRGraph", node: "NodeId") -> None:
    """AL - Emission requires node in latent or low activation state.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If EPI is already too high for emission to be meaningful
    """
    epi = _get_node_attr(G, node, ALIAS_EPI)
    # Emission is meant to activate latent nodes, not boost already active ones
    # This is a soft threshold - configurable via graph metadata
    max_epi = float(G.graph.get("AL_MAX_EPI_FOR_EMISSION", 0.8))
    if epi >= max_epi:
        raise OperatorPreconditionError(
            "Emission", f"Node already active (EPI={epi:.3f} >= {max_epi:.3f})"
        )


def validate_reception(G: "TNFRGraph", node: "NodeId") -> None:
    """EN - Reception requires node to have neighbors to receive from.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If node has no neighbors to receive energy from
    """
    neighbors = list(G.neighbors(node))
    if not neighbors:
        raise OperatorPreconditionError(
            "Reception", "Node has no neighbors to receive energy from"
        )


def validate_coherence(G: "TNFRGraph", node: "NodeId") -> None:
    """IL - Coherence requires active EPI, νf, and manageable ΔNFR.

    This function delegates to the strict validation implementation
    in coherence.py module, which provides comprehensive canonical
    precondition checks according to TNFR.pdf §2.2.1.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    ValueError
        If critical preconditions are not met (active EPI, νf, non-saturated state)

    Warnings
    --------
    UserWarning
        For suboptimal conditions (zero ΔNFR, critical ΔNFR, isolated node)

    Notes
    -----
    For backward compatibility, this function maintains the same signature
    as the legacy validate_coherence but now provides enhanced validation.

    See Also
    --------
    tnfr.operators.preconditions.coherence.validate_coherence_strict : Full implementation
    """
    from .coherence import validate_coherence_strict

    validate_coherence_strict(G, node)


def diagnose_coherence_readiness(G: "TNFRGraph", node: "NodeId") -> dict:
    """Diagnose node readiness for IL (Coherence) operator.

    Provides comprehensive diagnostic report with readiness status and
    actionable recommendations for IL operator application.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to diagnose

    Returns
    -------
    dict
        Diagnostic report with readiness status, check results, values, and recommendations

    See Also
    --------
    tnfr.operators.preconditions.coherence.diagnose_coherence_readiness : Full implementation
    """
    from .coherence import diagnose_coherence_readiness as _diagnose

    return _diagnose(G, node)


def validate_dissonance(G: "TNFRGraph", node: "NodeId") -> None:
    """OZ - Dissonance requires comprehensive structural preconditions.

    This function delegates to the strict validation implementation in
    dissonance.py module, which provides canonical precondition checks:

    1. Minimum coherence base (EPI >= threshold)
    2. ΔNFR not critically high (avoid overload)
    3. Sufficient νf for reorganization response
    4. No overload pattern (sobrecarga disonante)
    5. Network connectivity (warning)

    Also detects bifurcation readiness when ∂²EPI/∂t² > τ, enabling
    alternative structural paths (ZHIR, NUL, IL, THOL).

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If critical preconditions are not met (EPI, ΔNFR, νf, overload)

    Notes
    -----
    For backward compatibility, this function maintains the same signature
    as the legacy validate_dissonance but now provides enhanced validation.

    When bifurcation threshold is exceeded, sets node['_bifurcation_ready'] = True
    and logs the event for telemetry.

    See Also
    --------
    tnfr.operators.preconditions.dissonance.validate_dissonance_strict : Full implementation
    """
    import logging

    logger = logging.getLogger(__name__)

    # First, apply strict canonical preconditions
    # This validates EPI, ΔNFR, νf, overload, and connectivity
    from .dissonance import validate_dissonance_strict

    try:
        validate_dissonance_strict(G, node)
    except ValueError as e:
        # Convert ValueError to OperatorPreconditionError for backward compatibility
        raise OperatorPreconditionError(
            "Dissonance", str(e).replace("OZ precondition failed: ", "")
        )

    # Check bifurcation readiness using existing THOL infrastructure
    # Reuse _compute_epi_acceleration from SelfOrganization
    from ..definitions import SelfOrganization

    thol_instance = SelfOrganization()
    d2_epi = thol_instance._compute_epi_acceleration(G, node)

    # Get bifurcation threshold
    tau = float(G.graph.get("BIFURCATION_THRESHOLD_TAU", 0.5))

    # Store d²EPI for telemetry (using existing ALIAS_D2EPI)
    from ...alias import set_attr
    from ...constants.aliases import ALIAS_D2EPI

    set_attr(G.nodes[node], ALIAS_D2EPI, d2_epi)

    # Check if bifurcation threshold exceeded
    if d2_epi > tau:
        # Mark node as bifurcation-ready
        G.nodes[node]["_bifurcation_ready"] = True
        logger.info(
            f"Node {node}: bifurcation threshold exceeded "
            f"(∂²EPI/∂t²={d2_epi:.3f} > τ={tau}). "
            f"Alternative structural paths enabled."
        )
    else:
        # Clear flag if previously set
        G.nodes[node]["_bifurcation_ready"] = False


def validate_coupling(G: "TNFRGraph", node: "NodeId") -> None:
    """UM - Coupling requires active nodes with compatible phases.

    Validates comprehensive canonical preconditions for the UM (Coupling) operator
    according to TNFR theory:

    1. **Graph connectivity**: At least one other node exists for coupling
    2. **Active EPI**: Node has sufficient structural form (EPI > threshold)
    3. **Structural frequency**: Node has capacity for synchronization (νf > threshold)
    4. **Phase compatibility** (MANDATORY per Invariant #2): At least one neighbor within phase range

    Configuration Parameters
    ------------------------
    UM_MIN_EPI : float, default 0.05
        Minimum EPI magnitude required for coupling
    UM_MIN_VF : float, default 0.01
        Minimum structural frequency required for coupling
    UM_STRICT_PHASE_CHECK : bool, default True (changed from False per U3)
        Enable strict phase compatibility checking with existing neighbors.
        **MANDATORY per AGENTS.md Invariant #2**: "no coupling is valid without
        explicit phase verification (synchrony)"
    UM_MAX_PHASE_DIFF : float, default π/2
        Maximum phase difference for compatible coupling (radians)

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If node state is unsuitable for coupling:
        - Graph has no other nodes
        - EPI below threshold
        - Structural frequency below threshold
        - No phase-compatible neighbors (when strict checking enabled)

    Notes
    -----
    **IMPORTANT**: Phase compatibility check is now MANDATORY by default
    (UM_STRICT_PHASE_CHECK=True) to align with AGENTS.md Invariant #2 and U3.

    [Legacy note: Previously referenced RC3. See docs/grammar/DEPRECATION-INDEX.md]

    set UM_STRICT_PHASE_CHECK=False to disable (NOT RECOMMENDED - violates
    canonical physics requirements).

    Examples
    --------
    >>> from tnfr.structural import create_nfr
    >>> from tnfr.operators.preconditions import validate_coupling
    >>>
    >>> # Valid node for coupling
    >>> G, node = create_nfr("active", epi=0.15, vf=0.50)
    >>> validate_coupling(G, node)  # Passes
    >>>
    >>> # Invalid: EPI too low
    >>> G, node = create_nfr("inactive", epi=0.02, vf=0.50)
    >>> validate_coupling(G, node)  # Raises OperatorPreconditionError

    See Also
    --------
    Coupling : UM operator that uses this validation
    AGENTS.md : Invariant #2 (phase check mandatory)
    UNIFIED_GRAMMAR_RULES.md : U3 derivation

    [Legacy: Previously referenced EMERGENT_GRAMMAR_ANALYSIS.md RC3]
    """
    import math

    # Basic graph check - at least one other node required
    if G.number_of_nodes() <= 1:
        raise OperatorPreconditionError(
            "Coupling", "Graph has no other nodes to couple with"
        )

    # Node must be active (non-zero EPI)
    epi = _get_node_attr(G, node, ALIAS_EPI)
    min_epi = float(G.graph.get("UM_MIN_EPI", 0.05))
    if abs(epi) < min_epi:
        raise OperatorPreconditionError(
            "Coupling",
            f"Node EPI too low for coupling (|EPI|={abs(epi):.3f} < {min_epi:.3f})",
        )

    # Node must have structural frequency capacity
    vf = _get_node_attr(G, node, ALIAS_VF)
    min_vf = float(G.graph.get("UM_MIN_VF", 0.01))
    if vf < min_vf:
        raise OperatorPreconditionError(
            "Coupling", f"Structural frequency too low (νf={vf:.3f} < {min_vf:.3f})"
        )

    # U3: Phase compatibility check (was RC3)
    # Per AGENTS.md Invariant #2: "no coupling is valid without explicit phase verification"
    # Changed from False to True to align with canonical physics requirements
    strict_phase = bool(G.graph.get("UM_STRICT_PHASE_CHECK", True))
    if strict_phase:
        neighbors = list(G.neighbors(node))
        if neighbors:
            from ...utils.numeric import angle_diff

            theta_i = _get_node_attr(G, node, ALIAS_THETA)
            max_phase_diff = float(G.graph.get("UM_MAX_PHASE_DIFF", DELTA_PHI_MAX))

            # Check if at least one neighbor is phase-compatible
            has_compatible = False
            for neighbor in neighbors:
                theta_j = _get_node_attr(G, neighbor, ALIAS_THETA)
                phase_diff = abs(angle_diff(theta_i, theta_j))
                if phase_diff <= max_phase_diff:
                    has_compatible = True
                    break

            if not has_compatible:
                raise OperatorPreconditionError(
                    "Coupling",
                    f"No phase-compatible neighbors (all |Δθ| > {max_phase_diff:.3f})",
                )


def validate_resonance(G: "TNFRGraph", node: "NodeId") -> None:
    """RA - Resonance requires comprehensive canonical preconditions.

    This function delegates to the strict validation implementation in
    resonance.py module, which provides canonical precondition checks:

    1. Coherent source EPI (minimum structural form)
    2. Network connectivity (edges for propagation)
    3. Phase compatibility with neighbors (synchronization)
    4. Controlled dissonance (stable resonance state)
    5. Sufficient νf (propagation capacity)

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    ValueError
        If critical preconditions are not met (EPI, connectivity, νf, ΔNFR)

    Warnings
    --------
    UserWarning
        For suboptimal conditions (phase misalignment, isolated node)

    Notes
    -----
    For backward compatibility, this function maintains the same signature
    as the legacy validate_resonance but now provides enhanced validation.

    Typical canonical sequences that satisfy RA preconditions:
    - UM → RA: Coupling followed by propagation
    - AL → RA: Emission followed by propagation
    - IL → RA: Coherence stabilized then propagated

    See Also
    --------
    tnfr.operators.preconditions.resonance.validate_resonance_strict : Full implementation
    """
    from .resonance import validate_resonance_strict

    validate_resonance_strict(G, node)


def diagnose_resonance_readiness(G: "TNFRGraph", node: "NodeId") -> dict:
    """Diagnose node readiness for RA (Resonance) operator.

    Provides comprehensive diagnostic report with readiness status and
    actionable recommendations for RA operator application.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to diagnose

    Returns
    -------
    dict
        Diagnostic report with readiness status, check results, values, and recommendations

    See Also
    --------
    tnfr.operators.preconditions.resonance.diagnose_resonance_readiness : Full implementation
    """
    from .resonance import diagnose_resonance_readiness as _diagnose

    return _diagnose(G, node)


def validate_silence(G: "TNFRGraph", node: "NodeId") -> None:
    """SHA - Silence requires vf > 0 to reduce.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If structural frequency already near zero
    """
    vf = _get_node_attr(G, node, ALIAS_VF)
    min_vf = float(G.graph.get("SHA_MIN_VF", 0.01))
    if vf < min_vf:
        raise OperatorPreconditionError(
            "Silence",
            f"Structural frequency already minimal (νf={vf:.3f} < {min_vf:.3f})",
        )


def validate_expansion(G: "TNFRGraph", node: "NodeId") -> None:
    """VAL - Expansion requires comprehensive canonical preconditions.

    Canonical Requirements (TNFR Physics):
    1. **νf < max_vf**: Structural frequency below saturation
    2. **ΔNFR > 0**: Positive reorganization gradient (growth pressure)
    3. **EPI >= min_epi**: Sufficient base coherence for expansion
    4. **(Optional) Network capacity**: Check if network can support expansion

    Physical Basis:
    ----------------
    From nodal equation: ∂EPI/∂t = νf · ΔNFR(t)

    For coherent expansion:
    - ΔNFR > 0 required: expansion needs outward pressure
    - EPI > threshold: must have coherent base to expand from
    - νf < max: must have capacity for increased reorganization

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If any precondition fails:
        - Structural frequency at maximum
        - ΔNFR non-positive (no growth pressure)
        - EPI below minimum (insufficient coherence base)
        - (Optional) Network at capacity

    Configuration Parameters
    ------------------------
    VAL_MAX_VF : float, default 10.0
        Maximum structural frequency threshold
    VAL_MIN_DNFR : float, default 1e-6
        Minimum ΔNFR for expansion (must be positive, very low to minimize breaking changes)
    VAL_MIN_EPI : float, default 1/(2π) ≈ 0.159
        Minimum EPI for coherent expansion
    VAL_CHECK_NETWORK_CAPACITY : bool, default False
        Enable network capacity validation
    VAL_MAX_NETWORK_SIZE : int, default 1000
        Maximum network size if capacity checking enabled

    Examples
    --------
    >>> from tnfr.structural import create_nfr
    >>> from tnfr.operators.preconditions import validate_expansion
    >>>
    >>> # Valid node for expansion
    >>> G, node = create_nfr("expanding", epi=0.5, vf=2.0)
    >>> G.nodes[node]['delta_nfr'] = 0.1  # Positive ΔNFR
    >>> validate_expansion(G, node)  # Passes
    >>>
    >>> # Invalid: negative ΔNFR
    >>> G.nodes[node]['delta_nfr'] = -0.1
    >>> validate_expansion(G, node)  # Raises OperatorPreconditionError

    Notes
    -----
    VAL increases both EPI magnitude and νf, enabling exploration of new
    structural configurations while maintaining core identity (fractality).

    See Also
    --------
    Expansion : VAL operator implementation
    validate_contraction : NUL preconditions (inverse operation)
    """
    # 1. νf below maximum (existing check)
    vf = _get_node_attr(G, node, ALIAS_VF)
    max_vf = float(G.graph.get("VAL_MAX_VF", 10.0))
    if vf >= max_vf:
        raise OperatorPreconditionError(
            "Expansion",
            f"Structural frequency at maximum (νf={vf:.3f} >= {max_vf:.3f}). "
            f"Node at reorganization capacity limit.",
        )

    # 2. ΔNFR positivity check (NEW - CRITICAL)
    dnfr = _get_node_attr(G, node, ALIAS_DNFR)
    min_dnfr = float(G.graph.get("VAL_MIN_DNFR", 1e-6))
    if dnfr < min_dnfr:
        raise OperatorPreconditionError(
            "Expansion",
            f"ΔNFR must be positive for expansion (ΔNFR={dnfr:.3f} < {min_dnfr:.3f}). "
            f"No outward growth pressure detected. Consider OZ (Dissonance) to generate ΔNFR.",
        )

    # 3. EPI minimum check (NEW - IMPORTANT)
    epi = _get_node_attr(G, node, ALIAS_EPI)
    min_epi = float(G.graph.get("VAL_MIN_EPI", VAL_MIN_EPI))
    if epi < min_epi:
        raise OperatorPreconditionError(
            "Expansion",
            f"EPI too low for coherent expansion (EPI={epi:.3f} < {min_epi:.3f}). "
            f"Insufficient structural base. Consider AL (Emission) to activate node first.",
        )

    # 4. Network capacity check (OPTIONAL - for large-scale systems)
    check_capacity = bool(G.graph.get("VAL_CHECK_NETWORK_CAPACITY", False))
    if check_capacity:
        max_network_size = int(G.graph.get("VAL_MAX_NETWORK_SIZE", 1000))
        current_size = G.number_of_nodes()
        if current_size >= max_network_size:
            raise OperatorPreconditionError(
                "Expansion",
                f"Network at capacity (n={current_size} >= {max_network_size}). "
                f"Cannot support further expansion. set VAL_CHECK_NETWORK_CAPACITY=False to disable.",
            )


def validate_contraction(G: "TNFRGraph", node: "NodeId") -> None:
    """NUL - Enhanced precondition validation with over-compression check.

    Canonical Requirements (TNFR Physics):
    1. **νf > min_vf**: Structural frequency above minimum for reorganization
    2. **EPI >= min_epi**: Sufficient structural form to contract safely
    3. **density <= max_density**: Not already at critical compression

    Physical Basis:
    ----------------
    From nodal equation: ∂EPI/∂t = νf · ΔNFR(t)

    For safe contraction:
    - EPI must have sufficient magnitude (can't compress vacuum)
    - Density ρ = |ΔNFR| / EPI must not exceed critical threshold
    - Over-compression (ρ → ∞) causes structural collapse

    Density is the structural pressure per unit form. When EPI contracts
    while ΔNFR increases (canonical densification), density rises. If already
    at critical density, further contraction risks fragmentation.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If any precondition fails:
        - Structural frequency at minimum
        - EPI too low for safe contraction
        - Node already at critical density

    Configuration Parameters
    ------------------------
    NUL_MIN_VF : float, default 0.1
        Minimum structural frequency threshold
    NUL_MIN_EPI : float, default 0.1
        Minimum EPI for safe contraction
    NUL_MAX_DENSITY : float, default 10.0
        Maximum density threshold (ρ = |ΔNFR| / max(EPI, ε))

    Examples
    --------
    >>> from tnfr.structural import create_nfr
    >>> from tnfr.operators.preconditions import validate_contraction
    >>>
    >>> # Valid node for contraction
    >>> G, node = create_nfr("contracting", epi=0.5, vf=1.0)
    >>> G.nodes[node]['delta_nfr'] = 0.2
    >>> validate_contraction(G, node)  # Passes
    >>>
    >>> # Invalid: EPI too low
    >>> G, node = create_nfr("too_small", epi=0.05, vf=1.0)
    >>> validate_contraction(G, node)  # Raises OperatorPreconditionError
    >>>
    >>> # Invalid: density too high
    >>> G, node = create_nfr("over_compressed", epi=0.1, vf=1.0)
    >>> G.nodes[node]['delta_nfr'] = 2.0  # High ΔNFR
    >>> validate_contraction(G, node)  # Raises OperatorPreconditionError

    See Also
    --------
    Contraction : NUL operator implementation
    validate_expansion : VAL preconditions (inverse operation)
    """
    vf = _get_node_attr(G, node, ALIAS_VF)
    epi = _get_node_attr(G, node, ALIAS_EPI)
    dnfr = _get_node_attr(G, node, ALIAS_DNFR)

    # Check 1: νf must be above minimum
    min_vf = float(G.graph.get("NUL_MIN_VF", 0.1))
    if vf <= min_vf:
        raise OperatorPreconditionError(
            "Contraction",
            f"Structural frequency at minimum (νf={vf:.3f} <= {min_vf:.3f})",
        )

    # Check 2: EPI must be above minimum for contraction
    min_epi = float(G.graph.get("NUL_MIN_EPI", 0.1))
    if epi < min_epi:
        raise OperatorPreconditionError(
            "Contraction",
            f"EPI too low for safe contraction (EPI={epi:.3f} < {min_epi:.3f}). "
            f"Cannot compress structure below minimum coherent form.",
        )

    # Check 3: Density must not exceed critical threshold
    # Density ρ = |ΔNFR| / max(EPI, ε) - structural pressure per unit form
    epsilon = 1e-9
    density = abs(dnfr) / max(epi, epsilon)
    max_density = float(G.graph.get("NUL_MAX_DENSITY", 10.0))
    if density > max_density:
        raise OperatorPreconditionError(
            "Contraction",
            f"Node already at critical density (ρ={density:.3f} > {max_density:.3f}). "
            f"Further contraction risks structural collapse. "
            f"Consider IL (Coherence) to stabilize or reduce ΔNFR first.",
        )


def validate_self_organization(G: "TNFRGraph", node: "NodeId") -> None:
    """THOL - Enhanced validation: connectivity, metabolic context, acceleration.

    Self-organization requires:
    1. Sufficient EPI for bifurcation
    2. Positive reorganization pressure (ΔNFR > 0)
    3. Structural reorganization capacity (νf > 0)
    4. Network connectivity for metabolism (degree ≥ 1)
    5. EPI history for acceleration computation (≥3 points)
    6. **NEW**: Bifurcation threshold check (∂²EPI/∂t² vs τ) with telemetry

    Also detects and records the destabilizer that enabled this
    self-organization for telemetry and structural tracing purposes.

    **Bifurcation Threshold Validation (∂²EPI/∂t² > τ):**

    According to TNFR.pdf §2.2.10, THOL bifurcation occurs only when structural
    acceleration exceeds threshold τ. This function now explicitly validates this
    condition and sets telemetry flags:

    - If ∂²EPI/∂t² > τ: Bifurcation will occur (normal THOL behavior)
    - If ∂²EPI/∂t² ≤ τ: THOL executes but no sub-EPIs generated (warning logged)

    The validation is NON-BLOCKING (warning only) because THOL can meaningfully
    execute without bifurcation - it still applies coherence and metabolic effects.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If any structural requirement is not met

    Notes
    -----
    This function implements R4 Extended telemetry by analyzing the glyph_history
    to determine which destabilizer enabled the self-organization.

    Configuration Parameters
    ------------------------
    THOL_MIN_EPI : float, default 0.2
        Minimum EPI for bifurcation
    THOL_MIN_VF : float, default 0.1
        Minimum structural frequency for reorganization
    THOL_MIN_DEGREE : int, default 1
        Minimum network connectivity
    THOL_MIN_HISTORY_LENGTH : int, default 3
        Minimum EPI history for acceleration computation
    THOL_ALLOW_ISOLATED : bool, default False
        Allow isolated nodes for internal-only bifurcation
    THOL_METABOLIC_ENABLED : bool, default True
        Require metabolic network context
    BIFURCATION_THRESHOLD_TAU : float, default 0.1
        Bifurcation threshold for ∂²EPI/∂t² (see THOL_BIFURCATION_THRESHOLD)
    THOL_BIFURCATION_THRESHOLD : float, default 0.1
        Alias for BIFURCATION_THRESHOLD_TAU (operator-specific config)
    """
    import logging

    logger = logging.getLogger(__name__)

    epi = _get_node_attr(G, node, ALIAS_EPI)
    dnfr = _get_node_attr(G, node, ALIAS_DNFR)
    vf = _get_node_attr(G, node, ALIAS_VF)

    # 1. EPI sufficiency
    min_epi = float(G.graph.get("THOL_MIN_EPI", 0.2))
    if epi < min_epi:
        raise OperatorPreconditionError(
            "Self-organization",
            f"EPI too low for bifurcation (EPI={epi:.3f} < {min_epi:.3f})",
        )

    # 2. Reorganization pressure
    if dnfr <= 0:
        raise OperatorPreconditionError(
            "Self-organization",
            f"ΔNFR non-positive, no reorganization pressure (ΔNFR={dnfr:.3f})",
        )

    # 3. Structural frequency validation
    min_vf = float(G.graph.get("THOL_MIN_VF", 0.1))
    if vf < min_vf:
        raise OperatorPreconditionError(
            "Self-organization",
            f"Structural frequency too low for reorganization (νf={vf:.3f} < {min_vf:.3f})",
        )

    # 4. Connectivity requirement (ELEVATED FROM WARNING)
    min_degree = int(G.graph.get("THOL_MIN_DEGREE", 1))
    node_degree = G.degree(node)

    # Allow isolated THOL if explicitly enabled
    allow_isolated = bool(G.graph.get("THOL_ALLOW_ISOLATED", False))

    if node_degree < min_degree and not allow_isolated:
        raise OperatorPreconditionError(
            "Self-organization",
            f"Node insufficiently connected for network metabolism "
            f"(degree={node_degree} < {min_degree}). "
            f"set THOL_ALLOW_ISOLATED=True to enable internal-only bifurcation.",
        )

    # 5. EPI history validation (for d²EPI/dt² computation)
    epi_history = G.nodes[node].get("epi_history", [])
    min_history_length = int(G.graph.get("THOL_MIN_HISTORY_LENGTH", 3))

    if len(epi_history) < min_history_length:
        raise OperatorPreconditionError(
            "Self-organization",
            f"Insufficient EPI history for acceleration computation "
            f"(have {len(epi_history)}, need ≥{min_history_length}). "
            f"Apply operators to build history before THOL.",
        )

    # 6. Metabolic context validation (if metabolism enabled)
    if G.graph.get("THOL_METABOLIC_ENABLED", True):
        # If network metabolism is expected, verify neighbors exist
        if node_degree == 0:
            raise OperatorPreconditionError(
                "Self-organization",
                "Metabolic mode enabled but node is isolated. "
                "Disable THOL_METABOLIC_ENABLED or add network connections.",
            )

    # R4 Extended: Detect and record destabilizer type for telemetry
    _record_destabilizer_context(G, node, logger)

    # NEW: Bifurcation threshold validation (∂²EPI/∂t² > τ)
    # This is NON-BLOCKING - THOL can execute without bifurcation
    # Note: SelfOrganization uses its own _compute_epi_acceleration which looks at 'epi_history'
    # while compute_d2epi_dt2 looks at '_epi_history'. We check both for compatibility.

    # Get EPI history from node (try both keys for compatibility)
    history = G.nodes[node].get("_epi_history") or G.nodes[node].get("epi_history", [])

    # Compute d²EPI/dt² directly from history (same logic as both functions)
    if len(history) >= 3:
        epi_t = float(history[-1])
        epi_t1 = float(history[-2])
        epi_t2 = float(history[-3])
        d2_epi_signed = epi_t - 2.0 * epi_t1 + epi_t2
        d2_epi = abs(d2_epi_signed)
    else:
        # Insufficient history - should have been caught earlier, but handle gracefully
        d2_epi = 0.0

    # Get bifurcation threshold from graph configuration
    # Try BIFURCATION_THRESHOLD_TAU first (canonical), then THOL_BIFURCATION_THRESHOLD
    tau = G.graph.get("BIFURCATION_THRESHOLD_TAU")
    if tau is None:
        tau = float(G.graph.get("THOL_BIFURCATION_THRESHOLD", 0.1))
    else:
        tau = float(tau)

    # Check if bifurcation threshold will be exceeded
    if d2_epi <= tau:
        # Log warning but allow execution - THOL can be meaningful without bifurcation
        logger.warning(
            f"Node {node}: THOL applied with ∂²EPI/∂t²={d2_epi:.3f} ≤ τ={tau:.3f}. "
            f"No bifurcation will occur (empty THOL window expected). "
            f"Sub-EPIs will not be generated. "
            f"Consider stronger destabilizer (OZ, VAL) to increase acceleration."
        )
        # set telemetry flag for post-hoc analysis
        G.nodes[node]["_thol_no_bifurcation_expected"] = True
    else:
        # Clear flag if previously set
        G.nodes[node]["_thol_no_bifurcation_expected"] = False
        logger.debug(
            f"Node {node}: THOL bifurcation threshold exceeded "
            f"(∂²EPI/∂t²={d2_epi:.3f} > τ={tau:.3f}). "
            f"Sub-EPI generation expected."
        )


# Moved to mutation.py module for modularity
# Import here for backward compatibility
try:
    from .mutation import record_destabilizer_context as _record_destabilizer_context
except ImportError:
    # Fallback if mutation.py not available (shouldn't happen)
    def _record_destabilizer_context(
        G: "TNFRGraph", node: "NodeId", logger: "logging.Logger"
    ) -> None:
        """Fallback implementation - see mutation.py for canonical version."""
        G.nodes[node]["_mutation_context"] = {
            "destabilizer_operator": None,
            "destabilizer_distance": None,
            "recent_history": [],
        }


def validate_mutation(G: "TNFRGraph", node: "NodeId") -> None:
    """ZHIR - Mutation requires node to be in valid structural state.

    Implements canonical TNFR requirements for mutation (AGENTS.md §11, TNFR.pdf §2.2.11):

    1. Minimum νf for phase transformation capacity
    2. **∂EPI/∂t > ξ: Structural change velocity exceeds threshold**
    3. **U4b Part 1: Prior IL (Coherence) for stable transformation base**
    4. **U4b Part 2: Recent destabilizer (~3 ops) for threshold energy**

    Also detects and records the destabilizer that enabled this mutation
    for telemetry and structural tracing purposes.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If node state is unsuitable for mutation or U4b requirements not met

    Configuration Parameters
    ------------------------
    ZHIR_MIN_VF : float, default 0.05
        Minimum structural frequency for phase transformation
    ZHIR_THRESHOLD_XI : float, default 0.1
        Threshold for ∂EPI/∂t velocity check
    VALIDATE_OPERATOR_PRECONDITIONS : bool, default False
        Enable strict U4b validation (IL precedence + destabilizer requirement)
    ZHIR_REQUIRE_IL_PRECEDENCE : bool, default False
        Require prior IL even if VALIDATE_OPERATOR_PRECONDITIONS=False
    ZHIR_REQUIRE_DESTABILIZER : bool, default False
        Require recent destabilizer even if VALIDATE_OPERATOR_PRECONDITIONS=False

    Notes
    -----
    **Canonical threshold verification (∂EPI/∂t > ξ)**:

    ZHIR is a phase transformation that requires sufficient structural reorganization
    velocity to justify the transition. The threshold ξ represents the minimum rate
    of structural change needed for a phase shift to be physically meaningful.

    - If ∂EPI/∂t < ξ: Logs warning (soft check for backward compatibility)
    - If ∂EPI/∂t ≥ ξ: Logs success, sets validation flag
    - If insufficient history: Logs warning, cannot verify

    **U4b Validation (Grammar Rule)**:

    When strict validation enabled (VALIDATE_OPERATOR_PRECONDITIONS=True):
    - **Part 1**: Prior IL (Coherence) required for stable base
    - **Part 2**: Recent destabilizer (OZ/VAL/etc) required within ~3 ops

    Without strict validation: Only telemetry/warnings logged.

    This function implements R4 Extended telemetry by analyzing the glyph_history
    to determine which destabilizer (strong/moderate/weak) enabled the mutation.
    The destabilizer context is stored in node metadata for structural tracing.
    """
    import logging

    logger = logging.getLogger(__name__)

    # Mutation is a phase change, require minimum vf for meaningful transition
    vf = _get_node_attr(G, node, ALIAS_VF)
    min_vf = float(G.graph.get("ZHIR_MIN_VF", 0.05))
    if vf < min_vf:
        raise OperatorPreconditionError(
            "Mutation",
            f"Structural frequency too low for mutation (νf={vf:.3f} < {min_vf:.3f})",
        )

    # NEW: Threshold crossing validation (∂EPI/∂t > ξ)
    # Get EPI history - check both keys for compatibility
    epi_history = G.nodes[node].get("epi_history") or G.nodes[node].get(
        "_epi_history", []
    )

    if len(epi_history) >= 2:
        # Compute ∂EPI/∂t (discrete approximation using last two points)
        # For discrete operator applications with Δt=1: ∂EPI/∂t ≈ EPI_t - EPI_{t-1}
        depi_dt = abs(epi_history[-1] - epi_history[-2])

        # Get threshold from configuration
        xi_threshold = float(G.graph.get("ZHIR_THRESHOLD_XI", 0.1))

        # Verify threshold crossed
        if depi_dt < xi_threshold:
            # Allow mutation but log warning (soft check for backward compatibility)
            logger.warning(
                f"Node {node}: ZHIR applied with ∂EPI/∂t={depi_dt:.3f} < ξ={xi_threshold}. "
                f"Mutation may lack structural justification. "
                f"Consider increasing dissonance (OZ) first."
            )
            G.nodes[node]["_zhir_threshold_warning"] = True
        else:
            # Threshold met - log success
            logger.info(
                f"Node {node}: ZHIR threshold crossed (∂EPI/∂t={depi_dt:.3f} > ξ={xi_threshold})"
            )
            G.nodes[node]["_zhir_threshold_met"] = True
    else:
        # Insufficient history - cannot verify threshold
        logger.warning(
            f"Node {node}: ZHIR applied without sufficient EPI history "
            f"(need ≥2 points, have {len(epi_history)}). Cannot verify threshold."
        )
        G.nodes[node]["_zhir_threshold_unknown"] = True

    # U4b Part 1: IL Precedence Check (stable base for transformation)
    # Check if strict validation enabled
    strict_validation = bool(G.graph.get("VALIDATE_OPERATOR_PRECONDITIONS", False))
    require_il = strict_validation or bool(
        G.graph.get("ZHIR_REQUIRE_IL_PRECEDENCE", False)
    )

    if require_il:
        # Get glyph history
        glyph_history = G.nodes[node].get("glyph_history", [])

        # Import glyph_function_name to convert glyphs to operator names
        from ..grammar import glyph_function_name

        # Convert history to operator names
        history_names = [glyph_function_name(g) for g in glyph_history]

        # Check for prior IL (coherence)
        il_found = "coherence" in history_names

        if not il_found:
            raise OperatorPreconditionError(
                "Mutation",
                "U4b violation: ZHIR requires prior IL (Coherence) for stable transformation base. "
                "Apply Coherence before mutation sequence. "
                f"Recent history: {history_names[-5:] if len(history_names) > 5 else history_names}",
            )

        logger.debug(
            f"Node {node}: ZHIR IL precedence satisfied (prior Coherence found)"
        )

    # U4b Part 2: Recent Destabilizer Check (threshold energy for bifurcation)
    # R4 Extended: Detect and record destabilizer type for telemetry
    _record_destabilizer_context(G, node, logger)

    # If strict validation enabled, enforce destabilizer requirement
    require_destabilizer = strict_validation or bool(
        G.graph.get("ZHIR_REQUIRE_DESTABILIZER", False)
    )

    if require_destabilizer:
        context = G.nodes[node].get("_mutation_context", {})
        destabilizer_found = context.get("destabilizer_operator")

        if destabilizer_found is None:
            recent_history = context.get("recent_history", [])
            raise OperatorPreconditionError(
                "Mutation",
                "U4b violation: ZHIR requires recent destabilizer (OZ/VAL/etc) within ~3 ops. "
                f"Recent history: {recent_history}. "
                "Apply Dissonance or Expansion to elevate ΔNFR first.",
            )


def validate_transition(G: "TNFRGraph", node: "NodeId") -> None:
    """NAV - Comprehensive canonical preconditions for transition.

    Validates comprehensive preconditions for NAV (Transition) operator according
    to TNFR.pdf §2.3.11:

    1. **Minimum νf**: Structural frequency must exceed threshold
    2. **Controlled ΔNFR**: |ΔNFR| must be below maximum for stable transition
    3. **Regime validation**: Warns if transitioning from deep latency (EPI < 0.05)
    4. **Sequence compatibility** (optional): Warns if NAV applied after incompatible operators

    Configuration Parameters
    ------------------------
    NAV_MIN_VF : float, default 0.01
        Minimum structural frequency for transition
    NAV_MAX_DNFR : float, default 1.0
        Maximum |ΔNFR| for stable transition
    NAV_STRICT_SEQUENCE_CHECK : bool, default False
        Enable strict sequence compatibility checking
    NAV_MIN_EPI_FROM_LATENCY : float, default 0.05
        Minimum EPI for smooth transition from latency

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If node lacks necessary dynamics for transition:
        - νf below minimum threshold
        - |ΔNFR| exceeds maximum threshold (unstable state)

    Warnings
    --------
    UserWarning
        For suboptimal but valid conditions:
        - Transitioning from deep latency (EPI < 0.05)
        - NAV applied after incompatible operator (when strict checking enabled)

    Notes
    -----
    NAV requires controlled ΔNFR to prevent instability during regime transitions.
    High |ΔNFR| indicates significant reorganization pressure that could cause
    structural disruption during transition. Apply IL (Coherence) first to reduce
    ΔNFR before attempting regime transition.

    Deep latency transitions (EPI < 0.05 after SHA) benefit from prior AL (Emission)
    to provide smoother reactivation path.

    Examples
    --------
    >>> from tnfr.structural import create_nfr
    >>> from tnfr.operators.preconditions import validate_transition
    >>>
    >>> # Valid transition - controlled state
    >>> G, node = create_nfr("test", epi=0.5, vf=0.6)
    >>> G.nodes[node]['delta_nfr'] = 0.3  # Controlled ΔNFR
    >>> validate_transition(G, node)  # Passes
    >>>
    >>> # Invalid - ΔNFR too high
    >>> G.nodes[node]['delta_nfr'] = 1.5
    >>> validate_transition(G, node)  # Raises OperatorPreconditionError

    See Also
    --------
    Transition : NAV operator implementation
    validate_coherence : IL preconditions for ΔNFR reduction
    TNFR.pdf : §2.3.11 for NAV canonical requirements
    """
    import warnings

    # 1. νf minimum (existing check - preserved for backward compatibility)
    vf = _get_node_attr(G, node, ALIAS_VF)
    min_vf = float(G.graph.get("NAV_MIN_VF", 0.01))
    if vf < min_vf:
        raise OperatorPreconditionError(
            "Transition",
            f"Structural frequency too low (νf={vf:.3f} < {min_vf:.3f})",
        )

    # 2. ΔNFR positivity and bounds check (NEW - CRITICAL)
    dnfr = _get_node_attr(G, node, ALIAS_DNFR)
    max_dnfr = float(G.graph.get("NAV_MAX_DNFR", 1.0))
    if abs(dnfr) > max_dnfr:
        raise OperatorPreconditionError(
            "Transition",
            f"ΔNFR too high for stable transition (|ΔNFR|={abs(dnfr):.3f} > {max_dnfr}). "
            f"Apply IL (Coherence) first to reduce reorganization pressure.",
        )

    # 3. Regime origin validation (NEW - WARNING)
    latent = G.nodes[node].get("latent", False)
    epi = _get_node_attr(G, node, ALIAS_EPI)
    min_epi_from_latency = float(G.graph.get("NAV_MIN_EPI_FROM_LATENCY", 0.05))

    if latent and epi < min_epi_from_latency:
        # Warning: transitioning from deep latency
        warnings.warn(
            f"Node {node} in deep latency (EPI={epi:.3f} < {min_epi_from_latency:.3f}). "
            f"Consider AL (Emission) before NAV for smoother activation.",
            UserWarning,
            stacklevel=2,
        )

    # 4. Sequence compatibility check (NEW - OPTIONAL)
    if G.graph.get("NAV_STRICT_SEQUENCE_CHECK", False):
        history = G.nodes[node].get("glyph_history", [])
        if history:
            from ..grammar import glyph_function_name

            last_op = glyph_function_name(history[-1]) if history else None

            # NAV works best after stabilizers or generators
            # Valid predecessors per TNFR.pdf §2.3.11 and AGENTS.md
            valid_predecessors = {
                "emission",  # AL → NAV (activation-transition)
                "coherence",  # IL → NAV (stable-transition)
                "silence",  # SHA → NAV (latency-transition)
                "self_organization",  # THOL → NAV (bifurcation-transition)
            }

            if last_op and last_op not in valid_predecessors:
                warnings.warn(
                    f"NAV applied after {last_op}. "
                    f"More coherent after: {', '.join(sorted(valid_predecessors))}",
                    UserWarning,
                    stacklevel=2,
                )


def validate_recursivity(G: "TNFRGraph", node: "NodeId") -> None:
    """REMESH - Recursivity requires global network coherence threshold.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node
    node : NodeId
        Node to validate

    Raises
    ------
    OperatorPreconditionError
        If network is not ready for remesh operation
    """
    # REMESH is a network-scale operation, check graph state
    min_nodes = int(G.graph.get("REMESH_MIN_NODES", 2))
    if G.number_of_nodes() < min_nodes:
        raise OperatorPreconditionError(
            "Recursivity",
            f"Network too small for remesh (n={G.number_of_nodes()} < {min_nodes})",
        )


# Import diagnostic functions from modular implementations
from .mutation import diagnose_mutation_readiness  # noqa: E402