Metadata-Version: 2.4
Name: onyx-axiom
Version: 1.4.0
Summary: Hybrid symbolic–neural execution graph compiler and trainer
License:                     GNU AFFERO GENERAL PUBLIC LICENSE
                               Version 3, 19 November 2007
        
         Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
         Everyone is permitted to copy and distribute verbatim copies
         of this license document, but changing it is not allowed.
        
                                    Preamble
        
          The GNU Affero General Public License is a free, copyleft license for
        software and other kinds of works, specifically designed to ensure
        cooperation with the community in the case of network server software.
        
          The licenses for most software and other practical works are designed
        to take away your freedom to share and change the works.  By contrast,
        our General Public Licenses are intended to guarantee your freedom to
        share and change all versions of a program--to make sure it remains free
        software for all its users.
        
          When we speak of free software, we are referring to freedom, not
        price.  Our General Public Licenses are designed to make sure that you
        have the freedom to distribute copies of free software (and charge for
        them if you wish), that you receive source code or can get it if you
        want it, that you can change the software or use pieces of it in new
        free programs, and that you know you can do these things.
        
          Developers that use our General Public Licenses protect your rights
        with two steps: (1) assert copyright on the software, and (2) offer
        you this License which gives you legal permission to copy, distribute
        and/or modify the software.
        
          A secondary benefit of defending all users' freedom is that
        improvements made in alternate versions of the program, if they
        receive widespread use, become available for other developers to
        incorporate.  Many developers of free software are heartened and
        encouraged by the resulting cooperation.  However, in the case of
        software used on network servers, this result may fail to come about.
        The GNU General Public License permits making a modified version and
        letting the public access it on a server without ever releasing its
        source code to the public.
        
          The GNU Affero General Public License is designed specifically to
        ensure that, in such cases, the modified source code becomes available
        to the community.  It requires the operator of a network server to
        provide the source code of the modified version running there to the
        users of that server.  Therefore, public use of a modified version, on
        a publicly accessible server, gives the public access to the source
        code of the modified version.
        
          An older license, called the Affero General Public License and
        published by Affero, was designed to accomplish similar goals.  This is
        a different license, not a version of the Affero GPL, but Affero has
        released a new version of the Affero GPL which permits relicensing under
        this license.
        
          The precise terms and conditions for copying, distribution and
        modification follow.
        
                               TERMS AND CONDITIONS
        
          0. Definitions.
        
          "This License" refers to version 3 of the GNU Affero General Public License.
        
          "Copyright" also means copyright-like laws that apply to other kinds of
        works, such as semiconductor masks.
        
          "The Program" refers to any copyrightable work licensed under this
        License.  Each licensee is addressed as "you".  "Licensees" and
        "recipients" may be individuals or organizations.
        
          To "modify" a work means to copy from or adapt all or part of the work
        in a fashion requiring copyright permission, other than the making of an
        exact copy.  The resulting work is called a "modified version" of the
        earlier work or a work "based on" the earlier work.
        
          A "covered work" means either the unmodified Program or a work based
        on the Program.
        
          To "propagate" a work means to do anything with it that, without
        permission, would make you directly or secondarily liable for
        infringement under applicable copyright law, except executing it on a
        computer or modifying a private copy.  Propagation includes copying,
        distribution (with or without modification), making available to the
        public, and in some countries other activities as well.
        
          To "convey" a work means any kind of propagation that enables other
        parties to make or receive copies.  Mere interaction with a user through
        a computer network, with no transfer of a copy, is not conveying.
        
          An interactive user interface displays "Appropriate Legal Notices"
        to the extent that it includes a convenient and prominently visible
        feature that (1) displays an appropriate copyright notice, and (2)
        tells the user that there is no warranty for the work (except to the
        extent that warranties are provided), that licensees may convey the
        work under this License, and how to view a copy of this License.  If
        the interface presents a list of user commands or options, such as a
        menu, a prominent item in the list meets this criterion.
        
          1. Source Code.
        
          The "source code" for a work means the preferred form of the work
        for making modifications to it.  "Object code" means any non-source
        form of a work.
        
          A "Standard Interface" means an interface that either is an official
        standard defined by a recognized standards body, or, in the case of
        interfaces specified for a particular programming language, one that
        is widely used among developers working in that language.
        
          The "System Libraries" of an executable work include anything, other
        than the work as a whole, that (a) is included in the normal form of
        packaging a Major Component, but which is not part of that Major
        Component, and (b) serves only to enable use of the work with that
        Major Component, or to implement a Standard Interface for which an
        implementation is available to the public in source code form.  A
        "Major Component", in this context, means a major essential component
        (kernel, window system, and so on) of the specific operating system
        (if any) on which the executable work runs, or a compiler used to
        produce the work, or an object code interpreter used to run it.
        
          The "Corresponding Source" for a work in object code form means all
        the source code needed to generate, install, and (for an executable
        work) run the object code and to modify the work, including scripts to
        control those activities.  However, it does not include the work's
        System Libraries, or general-purpose tools or generally available free
        programs which are used unmodified in performing those activities but
        which are not part of the work.  For example, Corresponding Source
        includes interface definition files associated with source files for
        the work, and the source code for shared libraries and dynamically
        linked subprograms that the work is specifically designed to require,
        such as by intimate data communication or control flow between those
        subprograms and other parts of the work.
        
          The Corresponding Source need not include anything that users
        can regenerate automatically from other parts of the Corresponding
        Source.
        
          The Corresponding Source for a work in source code form is that
        same work.
        
          2. Basic Permissions.
        
          All rights granted under this License are granted for the term of
        copyright on the Program, and are irrevocable provided the stated
        conditions are met.  This License explicitly affirms your unlimited
        permission to run the unmodified Program.  The output from running a
        covered work is covered by this License only if the output, given its
        content, constitutes a covered work.  This License acknowledges your
        rights of fair use or other equivalent, as provided by copyright law.
        
          You may make, run and propagate covered works that you do not
        convey, without conditions so long as your license otherwise remains
        in force.  You may convey covered works to others for the sole purpose
        of having them make modifications exclusively for you, or provide you
        with facilities for running those works, provided that you comply with
        the terms of this License in conveying all material for which you do
        not control copyright.  Those thus making or running the covered works
        for you must do so exclusively on your behalf, under your direction
        and control, on terms that prohibit them from making any copies of
        your copyrighted material outside their relationship with you.
        
          Conveying under any other circumstances is permitted solely under
        the conditions stated below.  Sublicensing is not allowed; section 10
        makes it unnecessary.
        
          3. Protecting Users' Legal Rights From Anti-Circumvention Law.
        
          No covered work shall be deemed part of an effective technological
        measure under any applicable law fulfilling obligations under article
        11 of the WIPO copyright treaty adopted on 20 December 1996, or
        similar laws prohibiting or restricting circumvention of such
        measures.
        
          When you convey a covered work, you waive any legal power to forbid
        circumvention of technological measures to the extent such circumvention
        is effected by exercising rights under this License with respect to
        the covered work, and you disclaim any intention to limit operation or
        modification of the work as a means of enforcing, against the work's
        users, your or third parties' legal rights to forbid circumvention of
        technological measures.
        
          4. Conveying Verbatim Copies.
        
          You may convey verbatim copies of the Program's source code as you
        receive it, in any medium, provided that you conspicuously and
        appropriately publish on each copy an appropriate copyright notice;
        keep intact all notices stating that this License and any
        non-permissive terms added in accord with section 7 apply to the code;
        keep intact all notices of the absence of any warranty; and give all
        recipients a copy of this License along with the Program.
        
          You may charge any price or no price for each copy that you convey,
        and you may offer support or warranty protection for a fee.
        
          5. Conveying Modified Source Versions.
        
          You may convey a work based on the Program, or the modifications to
        produce it from the Program, in the form of source code under the
        terms of section 4, provided that you also meet all of these conditions:
        
            a) The work must carry prominent notices stating that you modified
            it, and giving a relevant date.
        
            b) The work must carry prominent notices stating that it is
            released under this License and any conditions added under section
            7.  This requirement modifies the requirement in section 4 to
            "keep intact all notices".
        
            c) You must license the entire work, as a whole, under this
            License to anyone who comes into possession of a copy.  This
            License will therefore apply, along with any applicable section 7
            additional terms, to the whole of the work, and all its parts,
            regardless of how they are packaged.  This License gives no
            permission to license the work in any other way, but it does not
            invalidate such permission if you have separately received it.
        
            d) If the work has interactive user interfaces, each must display
            Appropriate Legal Notices; however, if the Program has interactive
            interfaces that do not display Appropriate Legal Notices, your
            work need not make them do so.
        
          A compilation of a covered work with other separate and independent
        works, which are not by their nature extensions of the covered work,
        and which are not combined with it such as to form a larger program,
        in or on a volume of a storage or distribution medium, is called an
        "aggregate" if the compilation and its resulting copyright are not
        used to limit the access or legal rights of the compilation's users
        beyond what the individual works permit.  Inclusion of a covered work
        in an aggregate does not cause this License to apply to the other
        parts of the aggregate.
        
          6. Conveying Non-Source Forms.
        
          You may convey a covered work in object code form under the terms
        of sections 4 and 5, provided that you also convey the
        machine-readable Corresponding Source under the terms of this License,
        in one of these ways:
        
            a) Convey the object code in, or embodied in, a physical product
            (including a physical distribution medium), accompanied by the
            Corresponding Source fixed on a durable physical medium
            customarily used for software interchange.
        
            b) Convey the object code in, or embodied in, a physical product
            (including a physical distribution medium), accompanied by a
            written offer, valid for at least three years and valid for as
            long as you offer spare parts or customer support for that product
            model, to give anyone who possesses the object code either (1) a
            copy of the Corresponding Source for all the software in the
            product that is covered by this License, on a durable physical
            medium customarily used for software interchange, for a price no
            more than your reasonable cost of physically performing this
            conveying of source, or (2) access to copy the
            Corresponding Source from a network server at no charge.
        
            c) Convey individual copies of the object code with a copy of the
            written offer to provide the Corresponding Source.  This
            alternative is allowed only occasionally and noncommercially, and
            only if you received the object code with such an offer, in accord
            with subsection 6b.
        
            d) Convey the object code by offering access from a designated
            place (gratis or for a charge), and offer equivalent access to the
            Corresponding Source in the same way through the same place at no
            further charge.  You need not require recipients to copy the
            Corresponding Source along with the object code.  If the place to
            copy the object code is a network server, the Corresponding Source
            may be on a different server (operated by you or a third party)
            that supports equivalent copying facilities, provided you maintain
            clear directions next to the object code saying where to find the
            Corresponding Source.  Regardless of what server hosts the
            Corresponding Source, you remain obligated to ensure that it is
            available for as long as needed to satisfy these requirements.
        
            e) Convey the object code using peer-to-peer transmission, provided
            you inform other peers where the object code and Corresponding
            Source of the work are being offered to the general public at no
            charge under subsection 6d.
        
          A separable portion of the object code, whose source code is excluded
        from the Corresponding Source as a System Library, need not be
        included in conveying the object code work.
        
          A "User Product" is either (1) a "consumer product", which means any
        tangible personal property which is normally used for personal, family,
        or household purposes, or (2) anything designed or sold for incorporation
        into a dwelling.  In determining whether a product is a consumer product,
        doubtful cases shall be resolved in favor of coverage.  For a particular
        product received by a particular user, "normally used" refers to a
        typical or common use of that class of product, regardless of the status
        of the particular user or of the way in which the particular user
        actually uses, or expects or is expected to use, the product.  A product
        is a consumer product regardless of whether the product has substantial
        commercial, industrial or non-consumer uses, unless such uses represent
        the only significant mode of use of the product.
        
          "Installation Information" for a User Product means any methods,
        procedures, authorization keys, or other information required to install
        and execute modified versions of a covered work in that User Product from
        a modified version of its Corresponding Source.  The information must
        suffice to ensure that the continued functioning of the modified object
        code is in no case prevented or interfered with solely because
        modification has been made.
        
          If you convey an object code work under this section in, or with, or
        specifically for use in, a User Product, and the conveying occurs as
        part of a transaction in which the right of possession and use of the
        User Product is transferred to the recipient in perpetuity or for a
        fixed term (regardless of how the transaction is characterized), the
        Corresponding Source conveyed under this section must be accompanied
        by the Installation Information.  But this requirement does not apply
        if neither you nor any third party retains the ability to install
        modified object code on the User Product (for example, the work has
        been installed in ROM).
        
          The requirement to provide Installation Information does not include a
        requirement to continue to provide support service, warranty, or updates
        for a work that has been modified or installed by the recipient, or for
        the User Product in which it has been modified or installed.  Access to a
        network may be denied when the modification itself materially and
        adversely affects the operation of the network or violates the rules and
        protocols for communication across the network.
        
          Corresponding Source conveyed, and Installation Information provided,
        in accord with this section must be in a format that is publicly
        documented (and with an implementation available to the public in
        source code form), and must require no special password or key for
        unpacking, reading or copying.
        
          7. Additional Terms.
        
          "Additional permissions" are terms that supplement the terms of this
        License by making exceptions from one or more of its conditions.
        Additional permissions that are applicable to the entire Program shall
        be treated as though they were included in this License, to the extent
        that they are valid under applicable law.  If additional permissions
        apply only to part of the Program, that part may be used separately
        under those permissions, but the entire Program remains governed by
        this License without regard to the additional permissions.
        
          When you convey a copy of a covered work, you may at your option
        remove any additional permissions from that copy, or from any part of
        it.  (Additional permissions may be written to require their own
        removal in certain cases when you modify the work.)  You may place
        additional permissions on material, added by you to a covered work,
        for which you have or can give appropriate copyright permission.
        
          Notwithstanding any other provision of this License, for material you
        add to a covered work, you may (if authorized by the copyright holders of
        that material) supplement the terms of this License with terms:
        
            a) Disclaiming warranty or limiting liability differently from the
            terms of sections 15 and 16 of this License; or
        
            b) Requiring preservation of specified reasonable legal notices or
            author attributions in that material or in the Appropriate Legal
            Notices displayed by works containing it; or
        
            c) Prohibiting misrepresentation of the origin of that material, or
            requiring that modified versions of such material be marked in
            reasonable ways as different from the original version; or
        
            d) Limiting the use for publicity purposes of names of licensors or
            authors of the material; or
        
            e) Declining to grant rights under trademark law for use of some
            trade names, trademarks, or service marks; or
        
            f) Requiring indemnification of licensors and authors of that
            material by anyone who conveys the material (or modified versions of
            it) with contractual assumptions of liability to the recipient, for
            any liability that these contractual assumptions directly impose on
            those licensors and authors.
        
          All other non-permissive additional terms are considered "further
        restrictions" within the meaning of section 10.  If the Program as you
        received it, or any part of it, contains a notice stating that it is
        governed by this License along with a term that is a further
        restriction, you may remove that term.  If a license document contains
        a further restriction but permits relicensing or conveying under this
        License, you may add to a covered work material governed by the terms
        of that license document, provided that the further restriction does
        not survive such relicensing or conveying.
        
          If you add terms to a covered work in accord with this section, you
        must place, in the relevant source files, a statement of the
        additional terms that apply to those files, or a notice indicating
        where to find the applicable terms.
        
          Additional terms, permissive or non-permissive, may be stated in the
        form of a separately written license, or stated as exceptions;
        the above requirements apply either way.
        
          8. Termination.
        
          You may not propagate or modify a covered work except as expressly
        provided under this License.  Any attempt otherwise to propagate or
        modify it is void, and will automatically terminate your rights under
        this License (including any patent licenses granted under the third
        paragraph of section 11).
        
          However, if you cease all violation of this License, then your
        license from a particular copyright holder is reinstated (a)
        provisionally, unless and until the copyright holder explicitly and
        finally terminates your license, and (b) permanently, if the copyright
        holder fails to notify you of the violation by some reasonable means
        prior to 60 days after the cessation.
        
          Moreover, your license from a particular copyright holder is
        reinstated permanently if the copyright holder notifies you of the
        violation by some reasonable means, this is the first time you have
        received notice of violation of this License (for any work) from that
        copyright holder, and you cure the violation prior to 30 days after
        your receipt of the notice.
        
          Termination of your rights under this section does not terminate the
        licenses of parties who have received copies or rights from you under
        this License.  If your rights have been terminated and not permanently
        reinstated, you do not qualify to receive new licenses for the same
        material under section 10.
        
          9. Acceptance Not Required for Having Copies.
        
          You are not required to accept this License in order to receive or
        run a copy of the Program.  Ancillary propagation of a covered work
        occurring solely as a consequence of using peer-to-peer transmission
        to receive a copy likewise does not require acceptance.  However,
        nothing other than this License grants you permission to propagate or
        modify any covered work.  These actions infringe copyright if you do
        not accept this License.  Therefore, by modifying or propagating a
        covered work, you indicate your acceptance of this License to do so.
        
          10. Automatic Licensing of Downstream Recipients.
        
          Each time you convey a covered work, the recipient automatically
        receives a license from the original licensors, to run, modify and
        propagate that work, subject to this License.  You are not responsible
        for enforcing compliance by third parties with this License.
        
          An "entity transaction" is a transaction transferring control of an
        organization, or substantially all assets of one, or subdividing an
        organization, or merging organizations.  If propagation of a covered
        work results from an entity transaction, each party to that
        transaction who receives a copy of the work also receives whatever
        licenses to the work the party's predecessor in interest had or could
        give under the previous paragraph, plus a right to possession of the
        Corresponding Source of the work from the predecessor in interest, if
        the predecessor has it or can get it with reasonable efforts.
        
          You may not impose any further restrictions on the exercise of the
        rights granted or affirmed under this License.  For example, you may
        not impose a license fee, royalty, or other charge for exercise of
        rights granted under this License, and you may not initiate litigation
        (including a cross-claim or counterclaim in a lawsuit) alleging that
        any patent claim is infringed by making, using, selling, offering for
        sale, or importing the Program or any portion of it.
        
          11. Patents.
        
          A "contributor" is a copyright holder who authorizes use under this
        License of the Program or a work on which the Program is based.  The
        work thus licensed is called the contributor's "contributor version".
        
          A contributor's "essential patent claims" are all patent claims
        owned or controlled by the contributor, whether already acquired or
        hereafter acquired, that would be infringed by some manner, permitted
        by this License, of making, using, or selling its contributor version,
        but do not include claims that would be infringed only as a
        consequence of further modification of the contributor version.  For
        purposes of this definition, "control" includes the right to grant
        patent sublicenses in a manner consistent with the requirements of
        this License.
        
          Each contributor grants you a non-exclusive, worldwide, royalty-free
        patent license under the contributor's essential patent claims, to
        make, use, sell, offer for sale, import and otherwise run, modify and
        propagate the contents of its contributor version.
        
          In the following three paragraphs, a "patent license" is any express
        agreement or commitment, however denominated, not to enforce a patent
        (such as an express permission to practice a patent or covenant not to
        sue for patent infringement).  To "grant" such a patent license to a
        party means to make such an agreement or commitment not to enforce a
        patent against the party.
        
          If you convey a covered work, knowingly relying on a patent license,
        and the Corresponding Source of the work is not available for anyone
        to copy, free of charge and under the terms of this License, through a
        publicly available network server or other readily accessible means,
        then you must either (1) cause the Corresponding Source to be so
        available, or (2) arrange to deprive yourself of the benefit of the
        patent license for this particular work, or (3) arrange, in a manner
        consistent with the requirements of this License, to extend the patent
        license to downstream recipients.  "Knowingly relying" means you have
        actual knowledge that, but for the patent license, your conveying the
        covered work in a country, or your recipient's use of the covered work
        in a country, would infringe one or more identifiable patents in that
        country that you have reason to believe are valid.
        
          If, pursuant to or in connection with a single transaction or
        arrangement, you convey, or propagate by procuring conveyance of, a
        covered work, and grant a patent license to some of the parties
        receiving the covered work authorizing them to use, propagate, modify
        or convey a specific copy of the covered work, then the patent license
        you grant is automatically extended to all recipients of the covered
        work and works based on it.
        
          A patent license is "discriminatory" if it does not include within
        the scope of its coverage, prohibits the exercise of, or is
        conditioned on the non-exercise of one or more of the rights that are
        specifically granted under this License.  You may not convey a covered
        work if you are a party to an arrangement with a third party that is
        in the business of distributing software, under which you make payment
        to the third party based on the extent of your activity of conveying
        the work, and under which the third party grants, to any of the
        parties who would receive the covered work from you, a discriminatory
        patent license (a) in connection with copies of the covered work
        conveyed by you (or copies made from those copies), or (b) primarily
        for and in connection with specific products or compilations that
        contain the covered work, unless you entered into that arrangement,
        or that patent license was granted, prior to 28 March 2007.
        
          Nothing in this License shall be construed as excluding or limiting
        any implied license or other defenses to infringement that may
        otherwise be available to you under applicable patent law.
        
          12. No Surrender of Others' Freedom.
        
          If conditions are imposed on you (whether by court order, agreement or
        otherwise) that contradict the conditions of this License, they do not
        excuse you from the conditions of this License.  If you cannot convey a
        covered work so as to satisfy simultaneously your obligations under this
        License and any other pertinent obligations, then as a consequence you may
        not convey it at all.  For example, if you agree to terms that obligate you
        to collect a royalty for further conveying from those to whom you convey
        the Program, the only way you could satisfy both those terms and this
        License would be to refrain entirely from conveying the Program.
        
          13. Remote Network Interaction; Use with the GNU General Public License.
        
          Notwithstanding any other provision of this License, if you modify the
        Program, your modified version must prominently offer all users
        interacting with it remotely through a computer network (if your version
        supports such interaction) an opportunity to receive the Corresponding
        Source of your version by providing access to the Corresponding Source
        from a network server at no charge, through some standard or customary
        means of facilitating copying of software.  This Corresponding Source
        shall include the Corresponding Source for any work covered by version 3
        of the GNU General Public License that is incorporated pursuant to the
        following paragraph.
        
          Notwithstanding any other provision of this License, you have
        permission to link or combine any covered work with a work licensed
        under version 3 of the GNU General Public License into a single
        combined work, and to convey the resulting work.  The terms of this
        License will continue to apply to the part which is the covered work,
        but the work with which it is combined will remain governed by version
        3 of the GNU General Public License.
        
          14. Revised Versions of this License.
        
          The Free Software Foundation may publish revised and/or new versions of
        the GNU Affero General Public License from time to time.  Such new versions
        will be similar in spirit to the present version, but may differ in detail to
        address new problems or concerns.
        
          Each version is given a distinguishing version number.  If the
        Program specifies that a certain numbered version of the GNU Affero General
        Public License "or any later version" applies to it, you have the
        option of following the terms and conditions either of that numbered
        version or of any later version published by the Free Software
        Foundation.  If the Program does not specify a version number of the
        GNU Affero General Public License, you may choose any version ever published
        by the Free Software Foundation.
        
          If the Program specifies that a proxy can decide which future
        versions of the GNU Affero General Public License can be used, that proxy's
        public statement of acceptance of a version permanently authorizes you
        to choose that version for the Program.
        
          Later license versions may give you additional or different
        permissions.  However, no additional obligations are imposed on any
        author or copyright holder as a result of your choosing to follow a
        later version.
        
          15. Disclaimer of Warranty.
        
          THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
        APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
        HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
        OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
        THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
        IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
        ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
        
          16. Limitation of Liability.
        
          IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
        WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
        THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
        GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
        USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
        DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
        PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
        EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
        SUCH DAMAGES.
        
          17. Interpretation of Sections 15 and 16.
        
          If the disclaimer of warranty and limitation of liability provided
        above cannot be given local legal effect according to their terms,
        reviewing courts shall apply local law that most closely approximates
        an absolute waiver of all civil liability in connection with the
        Program, unless a warranty or assumption of liability accompanies a
        copy of the Program in return for a fee.
        
                             END OF TERMS AND CONDITIONS
        
                    How to Apply These Terms to Your New Programs
        
          If you develop a new program, and you want it to be of the greatest
        possible use to the public, the best way to achieve this is to make it
        free software which everyone can redistribute and change under these terms.
        
          To do so, attach the following notices to the program.  It is safest
        to attach them to the start of each source file to most effectively
        state the exclusion of warranty; and each file should have at least
        the "copyright" line and a pointer to where the full notice is found.
        
            <one line to give the program's name and a brief idea of what it does.>
            Copyright (C) <year>  <name of author>
        
            This program is free software: you can redistribute it and/or modify
            it under the terms of the GNU Affero General Public License as published by
            the Free Software Foundation, either version 3 of the License, or
            (at your option) any later version.
        
            This program is distributed in the hope that it will be useful,
            but WITHOUT ANY WARRANTY; without even the implied warranty of
            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
            GNU Affero General Public License for more details.
        
            You should have received a copy of the GNU Affero General Public License
            along with this program.  If not, see <https://www.gnu.org/licenses/>.
        
        Also add information on how to contact you by electronic and paper mail.
        
          If your software can interact with users remotely through a computer
        network, you should also make sure that it provides a way for users to
        get its source.  For example, if your program is a web application, its
        interface could display a "Source" link that leads users to an archive
        of the code.  There are many ways you could offer source, and different
        solutions will be better for different programs; see section 13 for the
        specific requirements.
        
          You should also get your employer (if you work as a programmer) or school,
        if any, to sign a "copyright disclaimer" for the program, if necessary.
        For more information on this, and how to apply and follow the GNU AGPL, see
        <https://www.gnu.org/licenses/>.
        
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0.0
Requires-Dist: lark>=1.1.0
Requires-Dist: networkx>=3.0
Provides-Extra: spy
Requires-Dist: pandas>=2.0; extra == "spy"
Requires-Dist: yfinance>=0.2.36; extra == "spy"
Provides-Extra: cartpole
Requires-Dist: gymnasium>=0.29.0; extra == "cartpole"
Provides-Extra: inspect
Requires-Dist: streamlit>=1.28.0; extra == "inspect"
Requires-Dist: graphviz>=0.20.0; extra == "inspect"
Provides-Extra: gateway
Requires-Dist: requests>=2.28.0; extra == "gateway"
Requires-Dist: streamlit>=1.28.0; extra == "gateway"
Requires-Dist: fastapi>=0.110.0; extra == "gateway"
Requires-Dist: uvicorn[standard]>=0.27.0; extra == "gateway"
Provides-Extra: serve
Requires-Dist: fastapi>=0.110.0; extra == "serve"
Requires-Dist: uvicorn[standard]>=0.27.0; extra == "serve"
Provides-Extra: lock
Requires-Dist: cryptography>=42.0.0; extra == "lock"
Provides-Extra: export
Requires-Dist: onnx>=1.16.0; extra == "export"
Provides-Extra: copilot
Requires-Dist: requests>=2.28.0; extra == "copilot"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: streamlit>=1.28.0; extra == "dev"
Requires-Dist: graphviz>=0.20.0; extra == "dev"
Provides-Extra: bench
Requires-Dist: scikit-learn>=1.3.0; extra == "bench"
Dynamic: license-file

# Axiom Engine

[![Version](https://img.shields.io/badge/version-1.4.0-blue.svg)](https://github.com/Danny1218/Axiom)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)

**A Differentiable Neural Architecture Search (DNAS) compiler.** Write explicit symbolic rules, compile them into a continuous-time neural network, and let the AI evolve to handle the edge cases.

---

## Benchmarks: where Axiom wins (and where it doesn't)

Reproducible CPU benchmarks (fixed seeds, no network) live under `benchmarks/` and write committed evidence to `docs/evidence/`. Install extras: `pip install -e ".[bench]"`.

### Guarded Titanic — wrap the strong model, prove the clamp

**Claim:** Call your best tabular model via `expert()` and keep symbolic safety rules in `.ax`; holdout accuracy matches the wrapped model while constraints are machine-checkable.

```powershell
python benchmarks/titanic_hybrid/run_guarded_audit.py
```

| Model | Holdout accuracy | Rule violations (500 edge cases) |
|-------|------------------|----------------------------------|
| **Raw GradientBoosting** | ~0.85 | ~128 |
| **Guarded GBM (Axiom wrap)** | ~0.85 (Δ≈0) | **0** |
| v1.3 pure hybrid (neural) | ~0.63 | 0 |

Certificate excerpt from `docs/evidence/titanic_guarded_certificate.json`:

```json
{
  "input_region": {"Pclass": [3.0, 3.0], "Sex": [0.0, 0.0], "Age": [18.0, 100.0]},
  "assumptions": {"tabular_model": [0.0, 1.0]},
  "proven_output_bounds": {"survived_prob": [0.0, 0.15]}
}
```

### Guardrail pattern

1. Train or load a strong baseline (sklearn, custom Python, etc.).
2. Wrap in `.ax`: `raw = expert("your_model", features);` plus symbolic `if` / `min` / `max` rules.
3. Wire the handler at runtime (`ExpertRuntimeRegistry`) or in `axiom serve`.
4. Run **`axiom certify`** with input region + declared expert bounds → JSON safety certificate.

### Extrapolation showdown (symbolic recovery vs sklearn)

**Claim:** When labels come from a known formula plus modest noise, Axiom's **tolerant symbolic inference** recovers the closed form and extrapolates outside the training range.

```powershell
python benchmarks/baseline_showdown/run_showdown.py
```

| Result | Detail |
|--------|--------|
| **Wins** | **9/10** in-family extrapolation wins (`docs/evidence/baseline_showdown.md`) with **unclipped** 3% Gaussian noise |
| **Honest loss** | `clamped_affine_three` declines — noisy labels vs clamp family |
| **Sabotage** | `sin(x)` and `exp(-x)`: Axiom **declines** (2/2) |
| **Gates (v1.4)** | Scale-relative row tolerance + 5% relative RMSE; benchmark noise clipping removed |

### Titanic hybrid (v1.3 reference)

v1.3 neural hybrid (`examples/titanic_hybrid.ax`) enforced constraints but lagged GBM accuracy (~0.63). v1.4 **`titanic_guarded.ax`** wraps GBM instead (see above). Reproduce v1.3 numbers:

```powershell
python benchmarks/titanic_hybrid/run_hybrid_audit.py
```

---

## 60-second quickstart

```powershell
git clone https://github.com/Danny1218/Axiom.git
cd Axiom
py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -e ".[dev,copilot,serve]"

# Train hybrid Titanic example → bundle
axiom train examples/titanic.ax --dataset titanic --epochs 10 --out titanic_bundle

# Serve and predict (local dev; set AXIOM_ALLOW_INSECURE_SERVE=1)
$env:AXIOM_ALLOW_INSECURE_SERVE="1"
axiom serve --bundle titanic_bundle.axb --port 8010
axiom predict --bundle titanic_bundle.axb --inputs '{"Sex":0,"Pclass":3,"Fare":7.25,"Age":22}'

# Semantic copilot (local LM Studio with qwen/qwen3-8b on :1234)
axiom copilot-doctor --backend lmstudio
```

---

## What works / what's experimental

| Area | Status | Notes |
|------|--------|-------|
| **`.ax` → IR → train → `.axb`** | Stable | `axiom train`, `axiom load`, `AxiomModel.predict/explain` |
| **HTTP bundle serve** | Stable | `axiom serve` with optional API key |
| **Exact symbolic fast paths** | Stable | Deterministic draft for common affine / min-max families |
| **Tolerant symbolic inference (v1.2)** | Stable | Least-squares fit on noisy rows before LLM; no network required for robustness tasks |
| **LLM copilot (LM Studio / Onyx)** | Stable | Draft → evaluate → repair; output normalizer canonicalizes almost-valid `.ax` |
| **Offline benchmark gate** | Stable | `axiom copilot-benchmark --backend benchmark-dispatch` on four JSON suites |
| **`torch.compile(fullgraph=True)`** | Experimental | Some builds cannot trace strict-mode `ContextVar`; tests skip or use hoisted bools |
| **MetaCompiler / DNAS unmasking** | Experimental | Sinkhorn routing + shadow expert growth |
| **Policy gateway / ONNX export** | Optional extras | `[gateway]`, `[export]` — less CI coverage than core path |

---

## Understanding Axiom (the layman’s bridge)

Modern software sits between two broken extremes:

| **Traditional code** | **Standard AI (deep nets / LLMs)** |
|----------------------|-------------------------------------|
| You write strict rules (`if X > 5 then Y`). Reliable and obedient—but the real world is messy; when data doesn’t fit, logic fails hard. | You feed a huge black box millions of examples and hope it infers the rules. Great on messy data—but it can hallucinate; you can’t *force* it to obey physics or policy. |

**Axiom is the hybrid path:** a **symbolic–neural** engine. You write normal-looking rules in an **`.ax`** file (the **symbolic** skeleton). The compiler then **wraps** a fluid, trainable neural graph around that skeleton (the **neural** reflexes)—same program, one differentiable stack.

**Metaphor — self-driving:** Traditional code is a strict lane line: line disappears → crash. Pure AI is a blindfolded learner: crash 10,000 times and hope for intuition. **Axiom** is **GPS + reflexes**: the map is your explicit code (where the car *must* go); the nets learn potholes and edge cases the map never listed.

---

## Why Axiom?

Axiom is a **hybrid symbolic–neural** system: you program in a small language (`.ax` files) that looks like JavaScript; the compiler lowers `if`, `else`, and `while` into **differentiable** PyTorch graphs. Symbolic paths encode what you *know*; **Tensor-Train LoRA (TT-LoRA)** adapters on a shared trunk learn what you *don’t*.

### Core features

| | |
|--|--|
| **Hybrid execution** | Hardcoded logic runs as interpreted IR on the latent trunk; TT-LoRA experts learn probabilistic residuals so the net still fits data when symbolic rules are wrong or incomplete. |
| **Dynamic routing (MoE)** | `if` / `else` compiles to **Sinkhorn**-balanced mixture-of-experts routing. **MetaCompiler** can **unmask** shadow experts when router entropy signals high uncertainty—new capacity appears only when needed. |
| **Continuous memory** | `while` loops become **Liquid Kolmogorov–Arnold Networks (KANs)** over unrolled timesteps, with **high-dimensional RBF splines**—a differentiable alternative to stacking static RNN cells for sequence-shaped IR. |
| **The Glass Box** | The stack is **interpretable by design**: launch a **Streamlit** dashboard to see the graph, ABI variables, and routing weights evolve—not a black box. |

### Why it’s different from “just scale the Transformer”

Much of the industry optimizes **scaling laws**—bigger GPUs, bigger black boxes. Axiom optimizes **structure** instead:

- **Zero-shot human knowledge:** Encode facts and invariants in code so the model doesn’t waste capacity re-learning basics; nets focus on **residuals** and messy regions.
- **Glass-box audits:** Because execution sits on top of your IR, **`axiom inspect`** lets you see **which branch** was taken and **how much** neural routing moved the needle—valuable in regulated settings.
- **Physical growth (DNAS):** The graph can **raise** capacity when uncertain—Sinkhorn entropy feeds **MetaCompiler**, which can **unmask** shadow LoRA experts instead of freezing a single static brain.
- **Time as continuity:** Loops compile to **Liquid KANs** with **RBF splines** over unrolled time—closer to a continuous dynamical view than a purely discrete tick-tock RNN story (see `examples/sequence.ax`).

### What is an `.ax` file?

An **`.ax`** file is source code for Axiom: assignments, comparisons, **`if` / `else`**, and **`while`** with C/JavaScript-like syntax. The parser builds an AST → IR bytecode (`OP_ASSIGN`, `OP_CONDITIONAL`, `OP_LOOP`, …) → an **execution graph** (`ExecutionGraph`) of PyTorch modules. You train that graph like any other model; gradients flow through both symbolic and neural pieces where the IR is differentiable.

**External expert hook (in-program):** `expert("backend_name", feature_expr)` lowers to **`OP_EXPERT`** (not `neural()`). It is **not differentiable**. At runtime, pass **`InterpretedBlock(..., expert_handler=callable)`** or **`expert_fallback=float`**; otherwise execution raises a clear error. The handler receives `(backend_name, list[float])` for one batch row and must return a **scalar float**. **`model.explain(...)`** adds an **`expert_calls`** list (backend names used). **ONNX export** rejects bundles that contain `expert()`.

---

## Installation

```bash
git clone https://github.com/Danny1218/Axiom.git
cd Axiom
pip install -e .
```

This installs the **`onyx-axiom`** package (importable as `axiom`, also available on PyPI: `pip install onyx-axiom`) and the global **`axiom`** CLI. Requires **Python 3.10+** and **PyTorch 2+**. Core dependencies are **torch**, **lark**, and **networkx** only.

Optional extras:

| Extra | Purpose |
|-------|---------|
| **`[inspect]`** | Glass Box (`axiom inspect`) + Copilot Studio (`axiom copilot-studio`): Streamlit + `graphviz` bindings |
| **`[serve]`** | HTTP bundle API (`axiom serve`): FastAPI + uvicorn |
| **`[lock]`** | Genetic lock on **`.axb`** neural weights (`axiom lock-bundle`) |
| **`[export]`** | ONNX export (`axiom export-onnx`) |
| **`[gateway]`** | Policy gateway HTTP + examples (`requests`, Streamlit, overlaps `[serve]` on FastAPI) |
| **`[copilot]`** | Semantic copilot CLI (`axiom copilot-draft`, `axiom copilot-search`, `axiom copilot-run`) — `requests` for Onyx/Qwen-style chat APIs |
| **`[dev]`** | Run the test suite (`pytest` + Glass Box deps for `inspect` / `glass_box` tests) |
| **`[bench]`** | CPU baseline benchmarks (`scikit-learn` for sklearn baselines in `benchmarks/`) |

Run tests locally (CI-parity install):

```powershell
pip install -e ".[dev,copilot,serve]"
pip install -r constraints-dev.txt
python -m pytest tests -q
```

For a minimal dev-only install, `pip install -e ".[dev]"` still works but skips serve/copilot integration tests.

### Continuous integration

| Workflow | Platform | What it runs |
|----------|----------|--------------|
| [`.github/workflows/ci.yml`](.github/workflows/ci.yml) | Ubuntu, Python 3.10–3.12 | `python -m pytest tests -q`, plus targeted `test_copilot_golden.py` and `test_smoke_happy_path.py` |
| [`.github/workflows/copilot-milestone.yml`](.github/workflows/copilot-milestone.yml) | Windows, Python 3.12 | `pytest -q`, `scripts/smoke_copilot_draft.ps1`, four offline `axiom copilot-benchmark --backend benchmark-dispatch` suites |

**Execution overhead baseline (local diagnostic, not CI-gated):**

```powershell
python scripts/profile_execution_overhead.py --json-out debug_execution_overhead.json
```

Compare JSON before/after changes; entries include p50/p95/mean timings and `torch_compile_backend` with per-backend `errors`.

---

## From compile to production

1. **Compile & train** — **`axiom train`** on an **`.ax`** file; you get a **`.axb`** bundle (serialized `InterpretedBlock` + weights).  
2. **Bundle** — The **`.axb`** is the portable artifact. Unlocked neural bundles also write a **sidecar** **`model.axb.weights.pt`** — copy **both** files together when moving or deploying (locked bundles embed ciphertext in the JSON instead).  
3. **Serve** — Optional **`pip install -e ".[serve]"`**, then **`axiom serve`** exposes **`/health`**, **`/predict`**, **`/explain`**, **`/report`** over HTTP. Production binds (**`0.0.0.0`**, Docker) require **`AXIOM_API_KEY`** unless **`AXIOM_ALLOW_INSECURE_SERVE=1`** (local dev only).  
4. **Secure** — Optional **`pip install -e ".[lock]"`**, then **`axiom lock-bundle`** encrypts neural weights; **`AXIOM_BUNDLE_SECRET`** / device unlock at load time.  
5. **Export** — Optional **`pip install -e ".[export]"`**, then **`axiom export-onnx`** for inference-only ONNX (no **`explain`** parity).  
6. **Policy gateway** — Optional **`pip install -e ".[gateway]"`**, then **`axiom gateway-serve`** for **`POST /gateway/chat`** (scan + explain + allow/deny + optional downstream forward).
7. **Semantic copilot** — Optional **`pip install -e ".[copilot]"`**, then **`axiom copilot-draft`** / **`axiom copilot-search`** / **`axiom copilot-run`** to draft, repair, or run the full “goal → best **`.ax`** + reports” pipeline via an OpenAI-compatible chat endpoint (e.g. Onyx + Qwen). **`axiom copilot-stability-report`** (Phase 83 / 83b) recursively scans local artifact trees and pipeline **`*.json`** summaries — no network — to summarize sweep or multi-restart stability.

---

## Semantic copilot CLI

Install **`[copilot]`** so `requests` is available. For **local development**, start [LM Studio](https://lmstudio.ai/) with **`qwen/qwen3-8b`** on **`http://127.0.0.1:1234`**, then use **`--backend lmstudio`** (defaults: URL **`http://127.0.0.1:1234/v1/`**, model **`qwen/qwen3-8b`**, no API key). Remote/on-prem endpoints use **`--backend onyx-qwen`** with **`--expert-url`**, **`--expert-model`**, and optionally **`--expert-api-key`** or **`AXIOM_EXPERT_API_KEY`**.

**Qwen3 thinking blocks:** the backend strips `` spans before code extraction (metadata **`stripped_think_block: true`**) and sends **`enable_thinking: false`** plus a **`/no_think`** suffix on user prompts when the model id contains **`qwen`**.

**Smoke check:** **`axiom copilot-doctor`** (default **`--backend lmstudio`**) requests greedy sampling via internal **`temperature: 0`** → HTTP **`do_sample: false`**. It prints **`connection:`**, **`parse` / `ir` / `block`**, and optional example-row diagnostics. Use **`--validate-source path.ax`** to check local **`.ax`** without calling the expert.

```powershell
# Local LM Studio (default backend)
axiom copilot-doctor

# Remote OpenAI-compatible server
axiom copilot-doctor --backend onyx-qwen --expert-url "https://your-host/v1/" --expert-model "qwen-7b"
```

The **`onyx-qwen`** backend’s system prompts and response parsing are tuned for **this repository’s** **`.ax`** DSL (JavaScript-like **`=`** assignments, **`;`**-terminated statements, **`neural(...)`**, **`if`/`while`**): they explicitly disambiguate from Macaulay2, the Axiom computer algebra system, and generic pseudocode. Repair output is expected to be program text only; iteration artifacts record extraction metadata (e.g. **`extraction_mode`**, **`forbidden_tokens_detected`** when **`:=`** or **`print(`** slip through, **`stripped_language_tag`** / **`code_line_count`** when a stray fence language line was removed from the model text) for inspection. When **`--examples-json`** (or HTTP **`examples`**) supplies rows, draft/repair user prompts require **one** reusable program over the real variable names (**`x`**, **`y`**, …), forbid **row-indexed** names (**`x_0`**, **`y_1`**, …) and **`output(...)`** (not in this DSL), and ask for generalization beyond the sample rows. If the model still emits indexed names or **`output(`**, repair prompts add **collapse** hints; **`metadata`** may include **`indexed_variable_warning`** / **`output_call_warning`** without mutating the source text.

**Reproducible runs:** **`axiom copilot-search --artifact-dir path/to/run/`** writes a fixed bundle — **`best.ax`**, **`iterations.json`** (per-iteration source, metrics, failure summaries, expert **`metadata`**, optional **`semantic_trace_summary`**), **`search_report.json`** (run header + **`failures_metrics_summary`** + sibling **`semantic_summaries`** when summarization ran) — only when that flag is set (no silent writes).

**End-to-end pipeline (Phase 71):** **`axiom copilot-run`** runs the same draft→evaluate→repair loop as **`copilot-search`**, then optionally writes a **pipeline summary JSON** (**`--summary-out`**) with a short **disclaimer** (this path does **not** train **`.axb`** or export ONNX), runs an extra **compile-only** pass on the champion source by default (disable with **`--no-final-validate`**), and prints explicit **stderr** lines if that final validation fails. Use **`--artifact-dir`**, **`--out`**, and the same mode flags as search (**`--compile-only`**, **`--examples-json`**, **`--train-tabular`** / **`--tabular-json`**, **`--summarize-traces`**).

**Multi-restart best-of-N (Phase 80):** **`axiom copilot-run --restarts N`** (default **1**) runs **`N`** independent full searches and keeps the overall best candidate using the same ranking as within-search (including **`adjusted_sort_score`** when applicable). The pipeline summary JSON includes **`restarts`** (**`total`**, **`winning_index`**, **`per_restart`**). With **`--artifact-dir`** and **`N > 1`**, each run writes under **`restart_0/`**, **`restart_1/`**, …; **`POST /run`** accepts **`restarts`** and returns **`restarts_total`**, **`winning_restart_index`**, **`per_restart_summaries`**.

**Stability report (Phase 83 / 83b):** **`axiom copilot-stability-report`** recursively scans each path and **`--parent`** root for **`search_report.json`**, pipeline-style **`*.json`** (e.g. **`risk_score_run_1.json`** beside **`--summary-out`** from **`copilot-run`**), and multi-restart directories (**`restart_0/`** …). **`search_report.json`** files only under **`restart_*/`** are not separate runs (they belong to the parent bundle). Pipeline summary JSON that references **`artifact_dir`** dedupes against the same artifact directory so you are not double-counted. Prints exact/near-hit counts (for **`neg_mse`** vs **`--near-threshold`**, default **-1e-9**), convergence-reason tallies, winning-restart tallies, and the overall best **`best.ax`** path. Use **`--json-out report.json`** for machine-readable output (includes **`discovery`** stats). No **`[copilot]`** dependency required (filesystem only).

**Sampling controls (Phase 82 / 82b):** optional **`--temperature`** and **`--top-p`** on **`copilot-search`**, **`copilot-run`**, and **`copilot-doctor`** forward OpenAI-style parameters to the expert for **both** draft and repair calls (merged into an internal context key, not into the visible “Context (JSON)” prompt text). Omitted flags preserve prior behavior (no extra JSON fields on the HTTP payload). **`temperature` of 0 or lower** is sent to Onyx as **`do_sample: false`** with **`temperature` omitted** (and **`top_p` omitted** when greedy, to avoid conflicting sampling knobs). **`POST /search`** and **`POST /run`** accept **`temperature`** and **`top_p`** in the JSON body. **Copilot Studio:** optional sidebar fields for the same (parsed when non-empty).

**Trace summaries (optional):** pass **`--summarize-traces`** on **`copilot-search`** to call the expert’s **`summarize_trace`** after each iteration (natural-language narration of explain trace + metrics + failures). Default is off; if the call fails, search still completes and the summary field is empty. Scalar metrics stay in **`metrics`**; prose lives in **`semantic_trace_summary`** / **`semantic_summaries`** only.

**Copilot Studio (optional UI):** install **`[inspect]`** and **`[copilot]`** (`pip install -e ".[inspect,copilot]"`), then run **`axiom copilot-studio`**. It opens a separate Streamlit app from Glass Box (`axiom inspect`): enter expert URL / model / API key, goal, optional context, iteration limit, optional **Summarize traces**, search mode **`compile_only`** / **`predict_rows`** / **`train_tabular`** (plus JSON text areas for row examples or tabular train/eval), then use **Draft once** or **Run search** — nothing calls the network until you click. You get tables for iteration summaries, expandable eval/metrics/failure JSON, and download buttons for **`draft.ax`**, **`best.ax`**, and **`copilot_report.json`**.

**Copilot HTTP server (Phase 67+):** headless FastAPI app for **`/draft`**, **`/search`**, **`/run`** (Phase 71 — same body shape as **`/search`** plus optional **`final_validate`**, response includes **`disclaimer`** and **`final_validation`**), **`/benchmarks/run`**, **`/summarize`**, and **`/health`** — not **`axiom serve`** (bundles) and not the policy gateway. **`POST /search`** accepts optional **`train_tabular`** (target + train/eval row lists + optional Adam hyperparameters); it cannot be combined with **`compile_only`** or **`examples`** in the same request. Install **`pip install -e ".[serve,copilot]"`**, then e.g. **`axiom copilot-serve --expert-url https://your-host/v1/ --expert-model qwen-7b --port 8020`**. Optional **`AXIOM_COPILOT_API_KEY`**: when set, POST routes require **`Authorization: Bearer …`** or **`X-API-Key`** (health stays open). Downstream chat auth for the expert remains **`AXIOM_EXPERT_API_KEY`** / **`--expert-api-key`** as for the CLI.

**Draft** (goal → single program):

```powershell
pip install -e ".[copilot]"
axiom copilot-draft --backend onyx-qwen --goal "Binary classifier with neural([a,b]) output survived_prob" `
  --context "Titanic-style features" `
  --expert-url "https://api.example.com/v1/" --expert-model "qwen-7b" `
  --out drafted.ax
```

**Search** (draft → compile/evaluate → repair loop; optional row eval JSON):

Row file format (JSON array): each element is `{"inputs": {...}, "expected": {...}}` for **`predict_rows`** scoring (default metric: **`neg_mse`**, higher is better). With **`--compile-only`**, examples are still passed into the expert context but evaluation stays compile-only.

**Metric-driven repair (Phase 76):** for **`--examples-json`** or **`--train-tabular`**, the search loop keeps repairing after a **valid** candidate until the metric meets a threshold or iterations are exhausted (not merely “first compile success”). Default is **on**; disable with **`--no-repair-valid-with-metrics`**. Override the stop threshold with **`--metric-repair-if-below FLOAT`**; for the built-in **`neg_mse`** scorer, if you omit that flag the default is **`≈ -1e-9`** (near-perfect fit). Reports and pipeline summaries include **`metric_repair`** + **`convergence_reason`** (threshold met vs budget vs compile-only success).

**Row-wise repair signal (Phase 77):** when **`predict_rows`** runs with **`expected`** rows, evaluation records **`row_comparisons`** (inputs, predicted vs expected outputs, per-target **`abs_error`**, worst rows first). Repair prompts include a **`## Row-wise mismatches`** JSON block so the expert can correct coefficients; evaluation JSON and iteration artifacts include **`row_comparisons`** when present. For math-like goals, an extra hint prefers symbolic arithmetic over **`neural(...)`** for exact example fits (library default; not a new CLI flag).

**Exact-symbolic / anti-neural bias (Phase 78):** for small example-driven goals that look like affine or **`max`/`min`** clamps (e.g. **`risk_score`** in the goal), the draft/repair context sets **`exact_symbolic_examples_task`** so the Onyx prompts push **direct arithmetic** and **`REPAIR_NEURAL_TO_SYMBOLIC_BLOCK`** when the current program still uses **`neural(...)`**. Candidate selection uses **`adjusted_sort_score`** (raw metric minus small penalties for **`neural`** on these tasks, indexed **`x_0`** names, **`output(`**, and suspicious numerics like **`03`**); reports include **`ranking_penalty`** and **`adjusted_sort_score`**. No new CLI flags.

**Exact-symbolic / control-flow fast paths (deterministic):**
- **What they do:** before the first expert draft call, search runs a local symbolic inference over examples and emits canonical `.ax` immediately when it can prove an exact fit.
- **Tolerant inference (v1.2 headline):** when rows are *almost* exact (label noise, sparse anchors), **`tolerant_inference.py`** fits affine / interaction / abs families by least squares (default **5% relative RMSE**), picks the simplest model, and skips the LLM entirely. Robustness tasks like **`noisy_affine_thermometer`**, **`signed_cross_term_noisy`**, and **`near_abs_with_bias`** are solved deterministically in tests.
- **LLM output normalizer:** every expert response passes through **`compiler/normalizer.py`** (`else if` → nested blocks, `&&`/`||` → nested `if`s, `clip(...)` → `min`/`max`, shorthand assignments, comment/prose stripping) before parsing.
- **Why they exist:** they reduce latency and backend load for common symbolic tasks, avoid unnecessary LLM variance, and keep outputs deterministic when the examples already define a closed form.
- **When they activate:** only in **`predict_rows`** when **`exact_symbolic_examples_task`** is true.
- **Supported task shapes today:**
  - one-input affine (**double_x family**): **`y = a * x + b`**
  - one-input piecewise threshold identity / zero-floor (**piecewise_threshold family**): **`if (x < 0.0) y = 0.0 else y = x`**
  - exact three-region nested piecewise identity/cap: **`if (x < 0.0) y = 0.0 else { if (x < 1.0) y = x else y = 1.0 }`**
  - exact two-input max: **`score = max(a, b)`**
  - exact two-input min/max blend: **`out = max(0.0, min(a + b, 1.0));`**
  - clamped two-input affine (**risk_score family**): **`out = max(0.0, min(1.0, a * x1 + b * x2 + c));`**
  - exact two-input interaction: **`out = w_ab * a * b + w_a * a + w_b * b + c`**
  - exact three-input affine (**three_input_affine family**): **`out = sum(w_i * x_i) + b`**
  - exact three-way max/min: **`score = max(min(a, b), c)`**
- **Fallback to Onyx expert backend:** if inference is ambiguous/underdetermined, rows are non-numeric, shape constraints do not match, or any row fails exact validation (including clamp edge rows), search proceeds with normal expert draft/repair.
- **Concrete examples:** `double_x`, `piecewise_threshold`, `nested_piecewise`, `max_of_two`, `minmax_blend`, `risk_score`, `quadratic_with_cross_term`, `three_input_affine`, and `three_way_maxmin` are now covered by deterministic fast paths.

**What is now proven working:**
- deterministic fast-path emission for these symbolic/copilot task families when rows define an exact fit: `double_x`, `piecewise_threshold`, `nested_piecewise`, `max_of_two`, `minmax_blend`, `risk_score`, `quadratic_with_cross_term`, `three_input_affine`, and `three_way_maxmin`
- canonical `.ax` output for direct arithmetic and nested control-flow forms, including the required `else { if (...) { ... } else { ... } }` shape
- exact row validation gate before accepting a fast path
- full search benchmark quality on the current milestone: `10/10` compile and `10/10` metric
- backend-only smoke: `12/12` quality checks passed
- strict fallback to expert draft/repair when rows are ambiguous/noisy/out-of-shape

**What is still model-dependent:**
- draft-only quality on the current benchmark (`5/10` compile, `2/10` metric)
- tasks outside current exact fast-path families
- any noisy or underdetermined example set (intent cannot be proven exactly)
- generalization quality after fallback to LLM draft/repair
- prompt-following quality under different expert backends/models

**Non-blocking follow-up:** remaining ONNX tracer warnings are follow-up cleanup work, not a blocker for the completed symbolic copilot milestone.

**Current milestone snapshot (2026-06-17, local venv with CI-parity extras):**
- `pytest`: see [GitHub Actions](https://github.com/Danny1218/Axiom/actions) for authoritative green CI; local full suite may show environment-specific `torch.compile` / gateway gaps
- offline benchmark-dispatch (CI): symbolic **10/10**, next symbolic **9/9**, generalization stress **8/8**, robustness/ambiguity **8/8**
- live Onyx operator snapshot (not CI): draft quality varies by task; search symbolic suites are green offline

**Known local-only failures (not CI blockers):** some `torch.compile` fullgraph probes and `httpx` TestClient gateway tests fail on certain Windows/PyTorch builds — track via `plan.md` and open issues rather than treating as regressions.

**Recommended next milestone:** `HTTP serve polish, profiler baselines, copilot onboarding diagnostics`

```powershell
# Local smoke bundles (Windows PowerShell)
.\scripts\smoke_copilot_symbolic.ps1
.\scripts\smoke_copilot_non_fast_path.ps1

# double_x — copilot-search
axiom copilot-search --backend onyx-qwen --goal "Compute y as double of x." `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --examples-json ./examples/double_x.json --iterations 6 `
  --artifact-dir ./debug_double_x --out ./debug_double_x/best.ax --report-out ./debug_double_x/search_report.json

# double_x — copilot-run
axiom copilot-run --backend onyx-qwen --goal "Compute y as double of x." `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --examples-json ./examples/double_x.json --iterations 6 `
  --artifact-dir ./showcase_double_x --out ./showcase_double_x.ax --summary-out ./showcase_double_x/pipeline_summary.json

# risk_score — copilot-search
axiom copilot-search --backend onyx-qwen `
  --goal "Compute risk_score = max(0.0, min(1.0, 0.7 * risk_a + 0.3 * risk_b));" `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --examples-json ./examples/risk_score_v3.json --iterations 8 `
  --artifact-dir ./debug_risk_score --out ./debug_risk_score/best.ax --report-out ./debug_risk_score/search_report.json

# risk_score — copilot-run
axiom copilot-run --backend onyx-qwen `
  --goal "Compute risk_score = max(0.0, min(1.0, 0.7 * risk_a + 0.3 * risk_b));" `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --examples-json ./examples/risk_score_v3.json --iterations 8 `
  --artifact-dir ./showcase_risk_score --out ./showcase_risk_score.ax --summary-out ./showcase_risk_score/pipeline_summary.json

# piecewise_threshold — copilot-search
axiom copilot-search --backend onyx-qwen `
  --goal "Write a valid Axiom .ax program in this repo's DSL that computes y = x when x > 0, otherwise y = 0.0." `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --examples-json ./examples/piecewise_threshold.json --iterations 8 `
  --artifact-dir ./debug_piecewise_threshold --out ./debug_piecewise_threshold/best.ax --report-out ./debug_piecewise_threshold/search_report_cli.json

# piecewise_threshold — copilot-run
axiom copilot-run --backend onyx-qwen `
  --goal "Write a valid Axiom .ax program in this repo's DSL that computes y = x when x > 0, otherwise y = 0.0." `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --examples-json ./examples/piecewise_threshold.json --iterations 8 `
  --artifact-dir ./showcase_piecewise_threshold --out ./showcase_piecewise_threshold.ax --summary-out ./showcase_piecewise_threshold/pipeline_summary.json

# three_input_affine — copilot-search
axiom copilot-search --backend onyx-qwen `
  --goal "Write a valid Axiom .ax program in this repo's DSL that computes score = 0.5 * a + 0.3 * b + 0.2 * c." `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --examples-json ./examples/three_input_affine.json --iterations 8 `
  --artifact-dir ./debug_three_input_affine --out ./debug_three_input_affine/best.ax --report-out ./debug_three_input_affine/search_report_cli.json

# three_input_affine — copilot-run
axiom copilot-run --backend onyx-qwen `
  --goal "Write a valid Axiom .ax program in this repo's DSL that computes score = 0.5 * a + 0.3 * b + 0.2 * c." `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --examples-json ./examples/three_input_affine.json --iterations 8 `
  --artifact-dir ./showcase_three_input_affine --out ./showcase_three_input_affine.ax --summary-out ./showcase_three_input_affine/pipeline_summary.json
```

**Limitations / next targets:**
- no multi-output symbolic inference yet
- no symbolic inference for products/nonlinear terms beyond current bounded affine shape
- no robust symbolic handling for noisy-but-close data (current behavior requires exact fit and otherwise falls back)

**Train-tabular search:** use **`--train-tabular`** with **`--tabular-json path.json`** (do not combine with **`--compile-only`** or **`--examples-json`**). The file is one JSON **object**: **`target_var`**, **`train_rows`**, **`eval_rows`** (each row is **`{"inputs": {...}, "expected": {...}}`**; keys are merged for the evaluator), optional **`epochs`**, **`learning_rate`**, **`weight_decay`**, **`batch_size`**. Same schema as **`axiom.copilot.tabular_json`**. Metric-driven repair defaults **on** here as well (same CLI flags).

```powershell
$examples = @'
[{"inputs": {}, "expected": {"y": 0.5}}]
'@
Set-Content -Path examples.json -Value $examples -Encoding utf8
axiom copilot-search --backend onyx-qwen --goal "Output y from defaults" `
  --expert-url "https://api.example.com/v1/" --expert-model "qwen-7b" `
  --iterations 5 --examples-json examples.json `
  --out best.ax --report-out search_report.json --artifact-dir ./copilot_run_01 `
  --summarize-traces
```

Omit **`--summarize-traces`** to skip the extra expert round-trips.

**Pipeline (goal → best `.ax` + summary JSON + optional artifact dir):**

```powershell
axiom copilot-run --backend onyx-qwen --goal "Small policy on x" `
  --expert-url "https://api.example.com/v1/" --expert-model "qwen-7b" `
  --iterations 5 --compile-only `
  --artifact-dir ./copilot_e2e --summary-out pipeline_summary.json --out best.ax
```

**Multi-restart** (same flags; add **`--restarts N`** — artifacts go under **`restart_0/`** … when **`N > 1`**):

```powershell
axiom copilot-run --backend onyx-qwen --goal "…" `
  --expert-url "https://api.example.com/v1/" --expert-model "qwen-7b" `
  --iterations 10 --examples-json ./examples/risk_score_v3.json `
  --restarts 5 --artifact-dir ./copilot_run --summary-out ./pipeline.json --out ./best.ax
```

**Benchmark harness:** `axiom.copilot.benchmarks` defines tiny NL tasks (`DEFAULT_BENCHMARK_TASKS`), compares draft-only vs full search, and serializes with **`benchmark_suite_to_dict`**. **CLI:** **`axiom copilot-benchmark`** (expert flags like other copilot commands; optional **`--task-json`**, **`--out`**, **`--draft-only`** or **`--search`**, **`--max-iterations`**). **HTTP:** with **`pip install -e ".[serve,copilot]"`**, **`POST /benchmarks/run`** on the copilot server accepts optional inline **`tasks`**, **`max_iterations`**, **`draft_only`**, **`search_only`**; response wraps the same JSON document under **`suite`**. Extra tasks can be loaded from **`axiom/copilot/fixtures/benchmark_tasks.json`** or your own file matching that schema.

For local Onyx evaluation of symbolic + generalization tasks, use **`benchmarks/copilot_symbolic_and_generalization_tasks.json`** (includes labels like **`fast_path_expected`** and **`category`**; loader ignores unknown fields):

```powershell
axiom copilot-benchmark --backend onyx-qwen `
  --expert-url "http://127.0.0.1:8000" --expert-model "onyx-qwen-production-v1" `
  --task-json "./benchmarks/copilot_symbolic_and_generalization_tasks.json" `
  --max-iterations 6 --out "./benchmarks/copilot_symbolic_and_generalization_results.json"
```

**In-memory tabular training (library API):** **`evaluate_program(..., mode="train_tabular")`** trains a compiled **`InterpretedBlock`** on **`train_rows`** with Adam (numeric dict rows, ABI-aware trunk fill, **`target_var`** column blinded in inputs like **`AxiomDataset`**), reports **`train_mse`** / **`eval_mse`** on **`eval_rows`**, optional **`TrainTabularParams`** (**`epochs`**, **`learning_rate`**, **`weight_decay`**, **`batch_size`**) and **`max_unroll`**. Purely symbolic programs get a **`no_trainable_parameters`** warning and eval metrics only—no subprocess and not a replacement for full **`axiom train`**.

---

## `axiom serve`

Serves **one** `.axb` at startup via FastAPI: **`GET /health`**, **`POST /predict`**, **`POST /explain`**, **`POST /report`** (JSON **`inputs`**; report can return inline HTML). Install **`pip install -e ".[serve]"`**.

Programmatic **`serve.create_app(path, expert_registry=..., expert_handler=..., expert_fallback=...)`** mirrors **`axiom.load`** for bundles that use **`expert()`**; otherwise **`POST /predict`** (and **`/explain`** / **`/report`**) return **503** with an explicit message when **`expert()`** is present but unwired.

Optional **`AXIOM_API_KEY`**: mutating routes accept **`Authorization: Bearer …`** or **`X-API-Key`**; **`GET /health`** is unauthenticated. **`AXIOM_BUNDLE_PATH`** selects the bundle if **`--bundle`** is omitted.

**Examples:**

```powershell
pip install -e ".[serve]"
axiom serve --bundle examples/portfolio_trained.axb --host 127.0.0.1 --port 8000
```

```powershell
$env:AXIOM_BUNDLE_PATH = "examples/portfolio_trained.axb"
$env:AXIOM_API_KEY = "secret"
axiom serve --host 0.0.0.0 --port 8000
```

```bash
curl -s http://127.0.0.1:8000/health
curl -s -X POST http://127.0.0.1:8000/predict -H "Content-Type: application/json" -d "{\"inputs\": {\"volatility\": 0.6}}"
```

---

## Locked bundles

**Genetic lock** (`src/axiom/security/genetic_lock.py`) optionally encrypts **serialized neural weights** inside the **`.axb`** with AES-256-CTR; **topology / ABI / IR** stay readable. Modes include **`device`** (CUDA identity), **`host`**, and **`env-secret`** ( **`AXIOM_BUNDLE_SECRET`** ). Install **`pip install -e ".[lock]"`**.

**Examples:**

```powershell
pip install -e ".[lock]"
$env:AXIOM_BUNDLE_SECRET = "dev-secret"
axiom lock-bundle --input examples/portfolio_trained.axb --output examples/portfolio_locked.axb --mode env-secret
axiom predict --bundle examples/portfolio_locked.axb --input '{"volatility":0.6,"drawdown":0.1,"momentum":-0.8,"volume":1.5}'
```

In Docker, set **`AXIOM_BUNDLE_SECRET`** if the mounted bundle is **`env-secret`** locked (see **Docker deployment**).

---

## Docker deployment

Production-style image for **`axiom serve`**: one **`.axb`** (+ optional **`.axb.weights.pt`** sidecar for unlocked neural bundles), FastAPI on **`HOST`** / **`PORT`**. The **`Dockerfile`** installs **`pip install ".[serve,lock]"`** and sets **`AXIOM_REQUIRE_API_KEY=1`**. Required env: **`AXIOM_API_KEY`**. Optional: **`AXIOM_BUNDLE_SECRET`** (unlock **`env-secret`** locked bundles). No bundle is baked in—set **`AXIOM_BUNDLE_PATH`** at runtime.

### Build

```bash
docker build -t axiom-engine:latest .
```

**Building only creates the image.** Nothing listens on **`8000`** until you **run** a container (next section) or **`docker compose up`**.

### Run (start the server)

Mount a local **`.axb`** and set **`AXIOM_BUNDLE_PATH`** inside the container to match the mount path:

```bash
docker run --rm -p 8000:8000 \
  -e AXIOM_BUNDLE_PATH=/bundle/model.axb \
  -e HOST=0.0.0.0 \
  -e PORT=8000 \
  -v /absolute/path/to/model.axb:/bundle/model.axb:ro \
  axiom-engine:latest
```

**PowerShell** (repo root; uses **`examples/portfolio_trained.axb`** after **`python examples/train_portfolio.py`**):

```powershell
docker run --rm -p 8000:8000 `
  -e AXIOM_BUNDLE_PATH=/bundle/model.axb `
  -e HOST=0.0.0.0 `
  -e PORT=8000 `
  -v "${PWD}/examples/portfolio_trained.axb:/bundle/model.axb:ro" `
  axiom-engine:latest
```

Leave that terminal open while testing. Add optional **`AXIOM_API_KEY`** / **`AXIOM_BUNDLE_SECRET`** with **`-e`** as needed.

### Compose

Create **`bundles/`**, copy or symlink your **`model.axb`** there (compose expects **`/bundles/model.axb`**), then:

```bash
docker compose up --build
```

**Note:** set **`AXIOM_API_KEY`** in **`.env`** (see **`.env.example`**) before **`docker compose up`**, so **`POST /predict`** requires **`Authorization: Bearer …`** (see below). **`GET /health`** stays unauthenticated.

### Example `curl`

In another terminal, after the container is running:

```bash
curl -s http://localhost:8000/health
curl -s -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d '{"inputs": {}}'
```

When **`AXIOM_API_KEY`** is set (via **`.env`** or compose):

```bash
curl -s -X POST http://localhost:8000/predict \
  -H "Authorization: Bearer $AXIOM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {}}'
```

---

## ONNX export

InterpretedBlock **`.axb`** only: dense tensor in/out via **`torch.onnx.export`**; **inference-only**—it does **not** preserve **`explain`** / Glass Box semantics, and some IR graphs may fail to export.

```powershell
pip install -e ".[export]"
axiom export-onnx --bundle examples/portfolio_trained.axb --output examples/portfolio.onnx --opset 17
```

Optional round-trip tests use **`onnxruntime`** (not installed by **`[export]`**).

---

## Policy gateway

**`pip install -e ".[gateway]"`** pulls **`requests`**, Streamlit (for **`examples/enterprise_ui.py`**), FastAPI, and uvicorn. **`axiom.gateway`** scans text (or accepts pre-extracted signals), runs **`AxiomModel.explain`**, blocks or forwards to a downstream URL, and can emit Glass Box HTML on deny via **`export_report`** / **`render_html_report`**.

**HTTP server:**

```powershell
axiom gateway-serve --bundle policy.axb --downstream-url http://127.0.0.1:8000/api/chat --policy-source examples/enterprise_policy.ax --host 127.0.0.1 --port 8010
```

**`POST /gateway/chat`** accepts JSON **`message`** and optional **`signals`**. Examples **`examples/onyx_gateway.py`** and **`examples/enterprise_ui.py`** use **`default_scan_text`** from **`axiom.gateway.core`**.

---

## Quickstart — Native Python API (Jupyter / scripts)

Load a trained **`.axb`** bundle and run inference with ordinary Python dicts—no manual trunk layout. Batches are a **list of dicts**; **pandas** `DataFrame` rows work too (optional: install `pandas` separately).

```python
import axiom

model = axiom.load("examples/portfolio_trained.axb")  # after training
out = model.predict(
    {"volatility": 0.6, "drawdown": 0.1, "momentum": -0.8, "volume": 1.5}
)
# out is a dict of ABI names → floats (or lists for vector columns)

model.export_report({"volatility": 0.6, "drawdown": 0.1, "momentum": -0.8, "volume": 1.5}, "report.html")

batch = model.predict(
    [
        {"volatility": 0.5, "drawdown": 0.0, "momentum": 0.1, "volume": 1.0},
        {"volatility": 0.6, "drawdown": 0.1, "momentum": -0.8, "volume": 1.5},
    ]
)

# Optional: entire DataFrame (same column names as ABI inputs)
# import pandas as pd
# market = pd.read_csv("spy_daily.csv")
# preds = model.predict(market)
```

**`expert()` / `OP_EXPERT` (Phase 66, 72):** if the program calls **`expert("name", features)`**, the bundle does **not** store Python handlers. After **`axiom.load`**, attach runtime callables with **`model.set_expert_registry({"name": fn})`** (or **`ExpertRuntimeRegistry`**), **`model.set_expert_handler(fn)`** for one dispatch callable, or **`model.set_expert_fallback(float)`**. This registry is **not** the semantic copilot **`SemanticExpert`** (LLM HTTP). For **`axiom serve`**, pass **`expert_registry=`** / **`expert_handler=`** / **`expert_fallback=`** into **`serve.create_app(...)`**; **`POST /predict`**, **`/explain`**, and **`/report`** return **503** if the bundle uses **`expert()`** and nothing is wired.

---

## Quickstart 1 — Tabular crucible (Titanic)

The bundled `examples/titanic.ax` uses a **deliberate sabotage** rule (impossible Fare threshold) so symbolic logic alone is useless—the hybrid stack must learn from data. Your own programs use the same **`if` / `else`** shape (e.g. branching on `Sex`, `Pclass`, etc.).

```javascript
// examples/titanic.ax (excerpt)
if (Fare > 100000.0) {
  survived_prob = 1.0;
} else {
  survived_prob = 0.0;
}
```

Train on the built-in Titanic dataset (CSV is downloaded if missing), 80/20 split, then **test accuracy** on the holdout set:

```bash
axiom train examples/titanic.ax --dataset titanic --epochs 30
```

Optional: `--dim 32`, `--no-meta`, `--out my_bundle`, `--titanic-csv path/to.csv`.

---

## Quickstart 2 — Sequence crucible (sine wave)

`examples/sequence.ax` drives a **Liquid-KAN** loop: a prelude seeds the ABI (including `y_pred = x * 0.0` so `x` is not clobbered), then a **`while`** integrates `step` for 10 iterations—compiled to a fixed-unroll sequence fed to the KAN.

```javascript
// examples/sequence.ax (excerpt)
y_pred = x * 0.0;
step = 0.0;
while (step < 10.0) {
  step = step + 1.0;
}
```

```bash
axiom train examples/sequence.ax --dataset sine --epochs 30 --dim 32
```

`--dim 32` matches a comfortable trunk width for this example; you will see **test MSE** on the synthetic `sin(x)` task printed after training.

---

## Live SPY — neuro-symbolic trading (optional)

Install extras: **`pip install -e ".[spy]"`** (**pandas**, **yfinance**). **`examples/spy_alpha.ax`** feeds **six** features into **`neural(...)`** (momentum, daily range vol, **SMA 10/50** divergence vs price, **20d** return volatility), and **symbolically** forces **`prediction = 0.0`** (cash) when **daily** **`(High − Low) / Open > 2.5%`**. Training swaps in a **deeper custom PyTorch stack** (via **`custom_neural_registry`**) instead of the default tiny MLP. Run:

```bash
python examples/train_spy.py
```

This downloads ~6y of data, trains 50 epochs, writes **`examples/spy_trained.axb`**, reloads with **`axiom.load(..., custom_neural_registry=...)`** (same architecture as training), runs **`model.predict`** on the held-out last **500** trading days, and prints **cumulative returns**, **annualized Sharpe ratios**, and **max drawdowns** (strategy vs buy-and-hold)—better risk-aware readouts than raw return alone. It ends with an **Autopsy** on the worst single-day strategy loss: **`model.explain({...})`** dumps **`alpha_signal`**, **`prediction`**, and inputs so you can audit why the model traded.

For any **`.axb`**, **`model.explain({"feature": ...})`** returns a JSON-friendly dict of symbolic variable values after one forward pass (Phase 41).

---

## The Glass Box visualizer

After training, artifacts are written as **`{prefix}.pt`** + **`{prefix}_topology.json`** (default prefix `axiom_bundle`).

```powershell
pip install -e ".[inspect]"
axiom inspect
```

This starts **Streamlit**. In the UI, set the bundle path prefix (same as `--out` without extension), adjust ABI inputs if needed, and run inference. Expand **routing / signals** to watch **Sinkhorn weights** and entropy-style diagnostics shift as different inputs traverse **conditional** blocks—your “aha!” moment for how symbolic branches became continuous routing.

---

## More CLI (cheat sheet)

| Goal | Command |
|------|--------|
| Legacy synthetic sequence (no CSV) | `axiom train train.ax --epochs 10 --out axiom_bundle` |
| Custom CSV | `axiom train my.ax --csv data.csv --target_key label --target_var my_output_abi` |
| Load saved bundle, one-off inference | `axiom train --mode inference --out axiom_bundle` |
| HTTP bundle API (needs **`[serve]`**) | `axiom serve --bundle model.axb` |
| Lock weights (needs **`[lock]`**) | `axiom lock-bundle --input in.axb --output out.axb --mode env-secret` |
| ONNX (needs **`[export]`**) | `axiom export-onnx --bundle model.axb --output model.onnx` |
| Policy gateway (needs **`[gateway]`**) | `axiom gateway-serve --bundle policy.axb --downstream-url https://…` |

---

## Compiler pipeline (30 seconds)

1. **Parse** `.ax` → AST  
2. **Lower** → IR (`OP_*` bytecode)  
3. **Wire** → `ExecutionGraph` (NetworkX + PyTorch)  
4. **Train** → save **`.axb`**; **serve** / **lock** / **export** / **gateway** as optional deployment steps (see **From compile to production**)  
5. **Inspect** with **`axiom inspect`** (`[inspect]`) or **`AxiomRunner`** + Glass Box  

---

## Philosophy

Brute-force scaling hits walls; **structure** scales. Axiom gives you an algorithmic skeleton you can read and audit, and lets **DNAS-style** sparsity and meta-compilation grow the right neural “muscle” where uncertainty demands it—on hardware you already have.

---

## Where Axiom shines (example domains)

These are **illustrative**—not shipped products—but they match the design center: **hard constraints in code**, **learning in the gaps**.

| Domain | Symbolic (your rules) | Neural (adapters / KAN) |
|--------|------------------------|---------------------------|
| **Trading / risk** | Hard limits (`if loss > threshold then flatten`) | Momentum, microstructure, regime patterns |
| **Med / biotech** | Physiological impossibilities, contraindications | Subtle biomarker correlations inside guardrails |
| **Robotics** | Safety envelopes, no-go zones | Smooth motion, efficiency inside constraints |
| **Games / sims** | Gravity, collision, authored laws | NPCs, weather, adaptive behavior without breaking physics |

---

## Road ahead

Three honest forks after v1.0:

| Path | Idea | Trade-off |
|------|------|-----------|
| **A — Killer app** | Stop extending the compiler; ship a **domain vertical** (trading, sports, weather) that proves ROI. | Proves value; less time on core R&D. |
| **B — Language** | Grow **`.ax`** toward **functions, arrays, classes** (Turing-complete, reusable modules). | Huge compiler/graph-design lift; long horizon. |
| **C — Community** | **PyPI**, articles, tutorials, issues—grow users and contributors. | Recognition and help; maintainer time on support and docs. |

**Pragmatic default:** drive **Path A** once—pick a dataset you care about, beat or match a baseline, *then* invest in B or C with evidence. Reproducible starter: **`python scripts/run_path_a_portfolio_vertical.py`** (finance portfolio; writes **`artifacts/path_a_portfolio/report.json`** and a portable **`.axb`** + **`.weights.pt`** pair).

---

## Links

- **Repository:** [github.com/Danny1218/Axiom](https://github.com/Danny1218/Axiom)  
- **Tests:** CI-parity: `pip install -e ".[dev,copilot,serve]"` + `pip install -r constraints-dev.txt` then `python -m pytest tests -q`  
- **Project state (maintainers):** see `plan.md` in this repo.

## License

Axiom is licensed under the **GNU Affero General Public License v3.0** (see `LICENSE`).
In short: you may use, study, and modify it freely, but if you build a product or
service on it, your modifications must be open-sourced under the same license.
For a commercial license without AGPL obligations, contact Onyx Protocol.
