diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..6a33b2ac99412f909e735899cf6d4df4d860bee4
--- /dev/null
+++ b/README.md
@@ -0,0 +1,15 @@
+---
+tags:
+- intermediate-representation
+- retained-checkpoint
+---
+
+# codebase_ir: 384D retained assets
+
+This lane contains 2 distinct original checkpoint variants. Each checkpoint uses a content-addressed path and an asset manifest preserving its schema, decoder role, available format/profile binding, codec, source declarations, and companion corpus or embedding assets. Unknown bindings remain unknown.
+
+Registration and publication do not qualify numerical quality, source-only reconstruction, teacher use, proof authority, or serving. No retained checkpoint is activated for inference. The Legal 768D checkpoint is inherited initialization only; Codebase, Intent, and Security 768D lanes have no retained checkpoints. Codebase 384D envelopes retain their borrowed Security payload identity and are not promoted as complete native Codebase decoders.
+
+See [releases/20261004-retained-checkpoints-v1/lane-manifest.json](releases/20261004-retained-checkpoints-v1/lane-manifest.json) for exact checkpoint hashes and source mappings. Matching listed implementation sources are preserved, but a complete executable closure is not asserted. Existing assets and embeddings are copied without recomputation.
+
+Source code retains the repository AGPL-3.0 license; original weights/data licensing is preserved and no new blanket grant is made.
diff --git a/releases/20261004-retained-checkpoints-v1/MODEL_CARD.md b/releases/20261004-retained-checkpoints-v1/MODEL_CARD.md
new file mode 100644
index 0000000000000000000000000000000000000000..6a33b2ac99412f909e735899cf6d4df4d860bee4
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/MODEL_CARD.md
@@ -0,0 +1,15 @@
+---
+tags:
+- intermediate-representation
+- retained-checkpoint
+---
+
+# codebase_ir: 384D retained assets
+
+This lane contains 2 distinct original checkpoint variants. Each checkpoint uses a content-addressed path and an asset manifest preserving its schema, decoder role, available format/profile binding, codec, source declarations, and companion corpus or embedding assets. Unknown bindings remain unknown.
+
+Registration and publication do not qualify numerical quality, source-only reconstruction, teacher use, proof authority, or serving. No retained checkpoint is activated for inference. The Legal 768D checkpoint is inherited initialization only; Codebase, Intent, and Security 768D lanes have no retained checkpoints. Codebase 384D envelopes retain their borrowed Security payload identity and are not promoted as complete native Codebase decoders.
+
+See [releases/20261004-retained-checkpoints-v1/lane-manifest.json](releases/20261004-retained-checkpoints-v1/lane-manifest.json) for exact checkpoint hashes and source mappings. Matching listed implementation sources are preserved, but a complete executable closure is not asserted. Existing assets and embeddings are copied without recomputation.
+
+Source code retains the repository AGPL-3.0 license; original weights/data licensing is preserved and no new blanket grant is made.
diff --git a/releases/20261004-retained-checkpoints-v1/SOURCE-LICENSE-AGPL-3.0.txt b/releases/20261004-retained-checkpoints-v1/SOURCE-LICENSE-AGPL-3.0.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0ad25db4bd1d86c452db3f9602ccdbe172438f52
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/SOURCE-LICENSE-AGPL-3.0.txt
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ 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.
+
+
+ Copyright (C)
+
+ 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 .
+
+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
+.
diff --git a/releases/20261004-retained-checkpoints-v1/lane-manifest.json b/releases/20261004-retained-checkpoints-v1/lane-manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..4ce4d797e4b8664077ac90f240a8b2bf3fa1b006
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/lane-manifest.json
@@ -0,0 +1,710 @@
+{
+ "authority": "Original byte identities and recorded provenance only.",
+ "checkpoints": [
+ {
+ "checkpoint": {
+ "bytes": 1009515,
+ "path_in_repo": "releases/retained-checkpoints/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f/checkpoint.json",
+ "sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
+ },
+ "codec": null,
+ "companion_assets": [],
+ "config": {
+ "embedding_provenance": {
+ "assets": [
+ {
+ "bytes": 190,
+ "name": "1_Pooling/config.json",
+ "sha256": "4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23"
+ },
+ {
+ "bytes": 583,
+ "name": "config.json",
+ "sha256": "00273cdfb3e05c7304d180270bdef8adae45023e7bdfc396338bdd815943dc59"
+ },
+ {
+ "bytes": 66746168,
+ "name": "model.safetensors",
+ "sha256": "9a1eb90bbac323ea08aa5629b624fe6ae75db121b904799c2266a1e2c2de22d2"
+ },
+ {
+ "bytes": 385,
+ "name": "modules.json",
+ "sha256": "73348a3d8f8ae4cc5f851dc6b98be3ea819390b814e83656d5eebbadf75fe43e"
+ },
+ {
+ "bytes": 57,
+ "name": "sentence_bert_config.json",
+ "sha256": "948201d8329907aae938fa62f9ceeed53f5694dacc2b87b9f3b78b37ee986529"
+ },
+ {
+ "bytes": 125,
+ "name": "special_tokens_map.json",
+ "sha256": "b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3"
+ },
+ {
+ "bytes": 711661,
+ "name": "tokenizer.json",
+ "sha256": "da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0"
+ },
+ {
+ "bytes": 394,
+ "name": "tokenizer_config.json",
+ "sha256": "e1790949631401af1bfb6c9c7aeec7fcf612e274d73579d99f704faea40c8ba7"
+ },
+ {
+ "bytes": 231508,
+ "name": "vocab.txt",
+ "sha256": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
+ }
+ ],
+ "batch_size": 32,
+ "device": "cuda",
+ "dimension": 384,
+ "dtype": "float32",
+ "encode_rows_per_second": 2155.864994796075,
+ "encode_seconds": 0.890593800926581,
+ "load_seconds": 0.6136547059286386,
+ "max_tokens_observed": 34,
+ "model_id": "thenlper/gte-small",
+ "normalized": true,
+ "revision": "17e1f347d17fe144873b1201da91788898c639cd",
+ "rows": 1920,
+ "truncated": false
+ },
+ "ridges": [
+ 0.0001,
+ 0.001,
+ 0.01,
+ 0.1
+ ]
+ },
+ "contract": null,
+ "declaration": {
+ "decoder_kind": "frozen projection and fixed-tree ridge readout",
+ "dimension_role": "input_embedding",
+ "input_width": 384,
+ "native_codebase_decoder_complete": false,
+ "owning_ir_family": "codebase_ir",
+ "payload_ir_family": "security_ir",
+ "receipt": {
+ "bytes": 1009515,
+ "path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
+ "sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
+ },
+ "role": "registered shared parent envelope"
+ },
+ "full_runtime_closure_verified": false,
+ "identity": {
+ "checkpoint_schema": "codebase-source-384-generation@1",
+ "dimension": 384,
+ "dimension_role": "input_embedding",
+ "donor": null,
+ "donor_pins": null,
+ "embedded_decoder_schema": "structured-source-384-autoencoder/v1",
+ "format_id": null,
+ "initialization_only": false,
+ "ir_family_id": "codebase_ir",
+ "legacy_profile": "codebase_ir/source_conditioned_384_v1",
+ "native_codebase_decoder_complete": false,
+ "original_checkpoint_pin": {
+ "bytes": 1009515,
+ "path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
+ "sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
+ },
+ "payload_ir_family": "security_ir",
+ "profile_id": null,
+ "proof_authority": false,
+ "record_id": "ir-model-asset-binding/v1:40237a9b6a4dd5723f36fcd80a37ba4d4cadb59067bc2de399c72ea9f96a99d2",
+ "retained_status": "borrowed_security_payload_unpromoted",
+ "role": "registered shared parent envelope",
+ "runtime_ready": false,
+ "schema_version": null,
+ "source_profile_id": null,
+ "task_id": null,
+ "teacher_qualified": false,
+ "trained": null
+ },
+ "license_scope": {
+ "repository_source": "AGPL-3.0, see SOURCE-LICENSE",
+ "weights_and_companions": "Original provenance retained; this release supplies no new blanket license grant."
+ },
+ "numerical_execution_performed": false,
+ "original_package": null,
+ "schema": "retained-ir-checkpoint-release/v1",
+ "source_binding_scope": "listed checkpoint implementation hashes only, not full import/native closure",
+ "source_map": [
+ {
+ "declaration_pointer": "/runtime_sha256",
+ "expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
+ "original_pin": {
+ "bytes": 27328,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
+ "sha256": "3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/legal_codec_sha256",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
+ "original_pin": {
+ "bytes": 14622,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
+ "sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.decoder",
+ "expected_relative_path": "ipfs_datasets_py/logic/intent_ir/decoder.py",
+ "original_pin": {
+ "bytes": 24220,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/decoder.py",
+ "sha256": "7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257/ipfs_datasets_py/logic/intent_ir/decoder.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.formalize.rich_grammar",
+ "expected_relative_path": "ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
+ "original_pin": {
+ "bytes": 11527,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
+ "sha256": "6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.schema",
+ "expected_relative_path": "ipfs_datasets_py/logic/intent_ir/schema.py",
+ "original_pin": {
+ "bytes": 27163,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/schema.py",
+ "sha256": "93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56/ipfs_datasets_py/logic/intent_ir/schema.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.security_ir.model",
+ "expected_relative_path": "ipfs_datasets_py/logic/security_ir/model.py",
+ "original_pin": {
+ "bytes": 37220,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/security_ir/model.py",
+ "sha256": "abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39/ipfs_datasets_py/logic/security_ir/model.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.software_verification.program",
+ "expected_relative_path": "ipfs_datasets_py/logic/software_verification/program.py",
+ "original_pin": {
+ "bytes": 58065,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/software_verification/program.py",
+ "sha256": "f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91/ipfs_datasets_py/logic/software_verification/program.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.decoder",
+ "expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
+ "original_pin": {
+ "bytes": 8008,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
+ "sha256": "d7be6bff3a1f1464d4783567b90942258ef718bc1c2b7e02938698ed4e619e57"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d7be6bff3a1f1464d4783567b90942258ef718bc1c2b7e02938698ed4e619e57/ipfs_datasets_py/logic/ui_ux_ir/decoder.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.schema",
+ "expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/schema.py",
+ "original_pin": {
+ "bytes": 120714,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/schema.py",
+ "sha256": "8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855/ipfs_datasets_py/logic/ui_ux_ir/schema.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.optimizers.logic_theorem_optimizer.modal_latent_formula",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
+ "original_pin": {
+ "bytes": 35427,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
+ "sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/runtime",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
+ "original_pin": {
+ "bytes": 34679,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
+ "sha256": "66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/canonical_contracts.py",
+ "expected_relative_path": "ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
+ "original_pin": {
+ "bytes": 109257,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
+ "sha256": "d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/legal_formula_codec.py",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
+ "original_pin": {
+ "bytes": 14622,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
+ "sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/legal_ir_grammar_decoder.py",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
+ "original_pin": {
+ "bytes": 146870,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
+ "sha256": "0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/modal_latent_formula.py",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
+ "original_pin": {
+ "bytes": 35427,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
+ "sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/tree_pin.py",
+ "expected_relative_path": "ipfs_datasets_py/logic/autoformal/tree_pin.py",
+ "original_pin": {
+ "bytes": 1948,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/autoformal/tree_pin.py",
+ "sha256": "587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/runtime_sha256",
+ "expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
+ "original_pin": {
+ "bytes": 31851,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
+ "sha256": "8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py"
+ }
+ ],
+ "unknown_schema_task_profile_policy": "Unknown fields remain null; no family-only alias or default serving route."
+ },
+ {
+ "checkpoint": {
+ "bytes": 304490,
+ "path_in_repo": "releases/retained-checkpoints/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930/checkpoint.json",
+ "sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
+ },
+ "codec": null,
+ "companion_assets": [],
+ "config": {
+ "embedding_provenance": {
+ "assets": [
+ {
+ "bytes": 190,
+ "name": "1_Pooling/config.json",
+ "sha256": "4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23"
+ },
+ {
+ "bytes": 583,
+ "name": "config.json",
+ "sha256": "00273cdfb3e05c7304d180270bdef8adae45023e7bdfc396338bdd815943dc59"
+ },
+ {
+ "bytes": 66746168,
+ "name": "model.safetensors",
+ "sha256": "9a1eb90bbac323ea08aa5629b624fe6ae75db121b904799c2266a1e2c2de22d2"
+ },
+ {
+ "bytes": 385,
+ "name": "modules.json",
+ "sha256": "73348a3d8f8ae4cc5f851dc6b98be3ea819390b814e83656d5eebbadf75fe43e"
+ },
+ {
+ "bytes": 57,
+ "name": "sentence_bert_config.json",
+ "sha256": "948201d8329907aae938fa62f9ceeed53f5694dacc2b87b9f3b78b37ee986529"
+ },
+ {
+ "bytes": 125,
+ "name": "special_tokens_map.json",
+ "sha256": "b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3"
+ },
+ {
+ "bytes": 711661,
+ "name": "tokenizer.json",
+ "sha256": "da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0"
+ },
+ {
+ "bytes": 394,
+ "name": "tokenizer_config.json",
+ "sha256": "e1790949631401af1bfb6c9c7aeec7fcf612e274d73579d99f704faea40c8ba7"
+ },
+ {
+ "bytes": 231508,
+ "name": "vocab.txt",
+ "sha256": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
+ }
+ ],
+ "batch_size": 32,
+ "device": "cuda",
+ "dimension": 384,
+ "dtype": "float32",
+ "encode_rows_per_second": 2155.864994796075,
+ "encode_seconds": 0.890593800926581,
+ "load_seconds": 0.6136547059286386,
+ "max_tokens_observed": 34,
+ "model_id": "thenlper/gte-small",
+ "normalized": true,
+ "revision": "17e1f347d17fe144873b1201da91788898c639cd",
+ "rows": 1920,
+ "truncated": false
+ },
+ "ridges": [
+ 0.0001,
+ 0.001,
+ 0.01,
+ 0.1
+ ]
+ },
+ "contract": null,
+ "declaration": {
+ "decoder_budget_unit": "fixed schema/scalar slots",
+ "development_child_exact": "0/9",
+ "development_parent_exact": "9/9",
+ "dimension_role": "input_embedding",
+ "input_width": 384,
+ "parent_pretraining_independence": "unknown",
+ "payload_ir_family": "security_ir",
+ "promoted": false,
+ "receipt": {
+ "bytes": 304490,
+ "path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
+ "sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
+ },
+ "role": "unpromoted repository child envelope"
+ },
+ "full_runtime_closure_verified": false,
+ "identity": {
+ "checkpoint_schema": "codebase-source-384-generation@1",
+ "dimension": 384,
+ "dimension_role": "input_embedding",
+ "donor": null,
+ "donor_pins": null,
+ "embedded_decoder_schema": "structured-source-384-autoencoder/v1",
+ "format_id": null,
+ "initialization_only": false,
+ "ir_family_id": "codebase_ir",
+ "legacy_profile": "codebase_ir/source_conditioned_384_v1",
+ "native_codebase_decoder_complete": false,
+ "original_checkpoint_pin": {
+ "bytes": 304490,
+ "path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
+ "sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
+ },
+ "payload_ir_family": "security_ir",
+ "profile_id": null,
+ "proof_authority": false,
+ "record_id": "ir-model-asset-binding/v1:327b68fdd5889632e5752370a9c168a80ada5597436264fb1d6fb5fc483e778f",
+ "retained_status": "borrowed_security_payload_unpromoted",
+ "role": "unpromoted repository child envelope",
+ "runtime_ready": false,
+ "schema_version": null,
+ "source_profile_id": null,
+ "task_id": null,
+ "teacher_qualified": false,
+ "trained": null
+ },
+ "license_scope": {
+ "repository_source": "AGPL-3.0, see SOURCE-LICENSE",
+ "weights_and_companions": "Original provenance retained; this release supplies no new blanket license grant."
+ },
+ "numerical_execution_performed": false,
+ "original_package": null,
+ "schema": "retained-ir-checkpoint-release/v1",
+ "source_binding_scope": "listed checkpoint implementation hashes only, not full import/native closure",
+ "source_map": [
+ {
+ "declaration_pointer": "/runtime_sha256",
+ "expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
+ "original_pin": {
+ "bytes": 27328,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
+ "sha256": "3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/legal_codec_sha256",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
+ "original_pin": {
+ "bytes": 14622,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
+ "sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.decoder",
+ "expected_relative_path": "ipfs_datasets_py/logic/intent_ir/decoder.py",
+ "original_pin": {
+ "bytes": 24220,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/decoder.py",
+ "sha256": "7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257/ipfs_datasets_py/logic/intent_ir/decoder.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.formalize.rich_grammar",
+ "expected_relative_path": "ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
+ "original_pin": {
+ "bytes": 11527,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
+ "sha256": "6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.schema",
+ "expected_relative_path": "ipfs_datasets_py/logic/intent_ir/schema.py",
+ "original_pin": {
+ "bytes": 27163,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/schema.py",
+ "sha256": "93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56/ipfs_datasets_py/logic/intent_ir/schema.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.security_ir.model",
+ "expected_relative_path": "ipfs_datasets_py/logic/security_ir/model.py",
+ "original_pin": {
+ "bytes": 37220,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/security_ir/model.py",
+ "sha256": "abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39/ipfs_datasets_py/logic/security_ir/model.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.software_verification.program",
+ "expected_relative_path": "ipfs_datasets_py/logic/software_verification/program.py",
+ "original_pin": {
+ "bytes": 58065,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/software_verification/program.py",
+ "sha256": "f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91/ipfs_datasets_py/logic/software_verification/program.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.decoder",
+ "expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
+ "original_pin": {
+ "bytes": 7300,
+ "path": "/home/barberb/lift_coding/artifacts/ir-original-corpus-replay-20261003/inputs/legal-original/ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
+ "sha256": "21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3/ipfs_datasets_py/logic/ui_ux_ir/decoder.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.schema",
+ "expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/schema.py",
+ "original_pin": {
+ "bytes": 120714,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/schema.py",
+ "sha256": "8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855/ipfs_datasets_py/logic/ui_ux_ir/schema.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.optimizers.logic_theorem_optimizer.modal_latent_formula",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
+ "original_pin": {
+ "bytes": 35427,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
+ "sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/native/runtime",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
+ "original_pin": {
+ "bytes": 34679,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
+ "sha256": "66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/canonical_contracts.py",
+ "expected_relative_path": "ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
+ "original_pin": {
+ "bytes": 109257,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
+ "sha256": "d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/legal_formula_codec.py",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
+ "original_pin": {
+ "bytes": 14622,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
+ "sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/legal_ir_grammar_decoder.py",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
+ "original_pin": {
+ "bytes": 146870,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
+ "sha256": "0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/modal_latent_formula.py",
+ "expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
+ "original_pin": {
+ "bytes": 35427,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
+ "sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/numerical/files/tree_pin.py",
+ "expected_relative_path": "ipfs_datasets_py/logic/autoformal/tree_pin.py",
+ "original_pin": {
+ "bytes": 1948,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/autoformal/tree_pin.py",
+ "sha256": "587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py"
+ },
+ {
+ "declaration_pointer": "/shared_runtime/runtime_sha256",
+ "expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
+ "original_pin": {
+ "bytes": 31851,
+ "path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
+ "sha256": "8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4"
+ },
+ "path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py"
+ }
+ ],
+ "unknown_schema_task_profile_policy": "Unknown fields remain null; no family-only alias or default serving route."
+ }
+ ],
+ "dimension": 384,
+ "empty_lane": false,
+ "input_audit_pins": [
+ {
+ "bytes": 661812,
+ "path": "/home/barberb/lift_coding/artifacts/ir-model-manager-hf-sync-20261004/publication_inventory_audit.json",
+ "sha256": "8e857941cee73c75e8dc4ac7aa5df604e8953aa9dc87ec00bd2f83c0677e93ae"
+ },
+ {
+ "bytes": 1033525,
+ "path": "/home/barberb/lift_coding/artifacts/ir-model-manager-hf-sync-20261004/publication_source_binding_audit.json",
+ "sha256": "1ae36985f031ac16fa989cb4ec27f1ec49fdebf2d769b771c7db491dec1f6d9a"
+ }
+ ],
+ "ir_family_id": "codebase_ir",
+ "original_lane_declaration": {
+ "cell_id": "codebase_ir_384d",
+ "checkpoint_count": 2,
+ "dimension": 384,
+ "dimension_profile": {
+ "dimension": 384,
+ "dimension_role_required": true,
+ "encoder_kind": "GTE-small source embedding for source-conditioned tasks",
+ "hard_encoder_token_limit": 512,
+ "model_id": "thenlper/gte-small",
+ "model_revision": "17e1f347d17fe144873b1201da91788898c639cd",
+ "normalization": "l2",
+ "pooling": "mean",
+ "qualified_source_token_limit": null,
+ "unknown_limit_policy": "freeze task/span-specific admitted budget within encoder ceiling; historical compiler profiles remain separate"
+ },
+ "empty_model_lane": false,
+ "huggingface_plan": {
+ "existing_descriptor_source": null,
+ "existing_read_only_descriptors": [],
+ "load_requires": [
+ "full immutable commit",
+ "manifest SHA256",
+ "matching family/dimension role/task/profile/codec",
+ "actual checkpoint SHA256"
+ ],
+ "namespace_write_access_verified": false,
+ "release_path_template": "releases////",
+ "repo_type": "model",
+ "repository_id_template": "/codebase-ir-autoencoder-384d",
+ "status": "proposed_not_created",
+ "suggested_namespace_from_existing_release_descriptors": "Publicus",
+ "suggested_repository_id": "Publicus/codebase-ir-autoencoder-384d",
+ "visibility": null,
+ "visibility_status": "explicit deployment configuration required; no visibility changes performed during planning"
+ },
+ "inventory_receipt": {
+ "bytes": 8393,
+ "path": "/home/barberb/lift_coding/artifacts/codebase-ir-numerical-replay-20261003/inputs/inventories/codebase_ir/384d.json",
+ "sha256": "d01836c6d11996d6d4e88a7d2722fca63004ed4fea19e08f331db65903b4fdc4"
+ },
+ "ir_family_id": "codebase_ir",
+ "reference_checks": [
+ {
+ "kind": "checkpoint",
+ "receipt": {
+ "bytes": 1009515,
+ "path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
+ "sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
+ },
+ "status": "verified"
+ },
+ {
+ "kind": "checkpoint",
+ "receipt": {
+ "bytes": 304490,
+ "path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
+ "sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
+ },
+ "status": "verified"
+ }
+ ],
+ "task_profiles_to_inventory": [
+ "source_to_native_ir",
+ "structural_reconstruction",
+ "native_ir_to_logic",
+ "native_ir_to_source",
+ "retained_source_byte_restoration"
+ ],
+ "unsupported_checkpoint_deserialization_for_runtime": false
+ },
+ "qualified_runtime_count": 0,
+ "repository_id": "Publicus/codebase-ir-autoencoder-384d",
+ "schema": "retained-ir-lane-release/v1",
+ "teacher_qualified_count": 0,
+ "trained_768_model_count": 0
+}
diff --git a/releases/20261004-retained-checkpoints-v1/original-lane-inventory.json b/releases/20261004-retained-checkpoints-v1/original-lane-inventory.json
new file mode 100644
index 0000000000000000000000000000000000000000..7b26176306dc50c66a580c50924f33b3fb5901e1
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/original-lane-inventory.json
@@ -0,0 +1,193 @@
+{
+ "schema": "ir-family-dimension-inventory-plan/v1",
+ "status": "declarative_plan_not_runtime_inventory",
+ "cell_id": "codebase_ir_384d",
+ "ir_family_id": "codebase_ir",
+ "dimension": 384,
+ "store_id_proposed": "ir-cell:codebase_ir:384d",
+ "store_identity_dimensions": [
+ "ir_family_id",
+ "dimension"
+ ],
+ "variant_identity_additions": [
+ "dimension_role",
+ "task_id",
+ "input_representation_profile",
+ "encoder_tokenizer_revisions",
+ "decoder_architecture",
+ "target_ir_family",
+ "target_schema",
+ "target_codec",
+ "input_budget",
+ "output_budget",
+ "span_profile",
+ "objective_implementation"
+ ],
+ "native_semantics": [
+ "observed code and source versions",
+ "typed ProgramIR/contracts",
+ "calls/effects/dependencies",
+ "native Codebase grammar and code inverse"
+ ],
+ "canonical_ir_identity_depends_on_model_dimension": false,
+ "storage": {
+ "status": "planned_not_created",
+ "root_template": "/codebase_ir/384d",
+ "inventory_export": "/codebase_ir/384d/inventory.json",
+ "registry_database": "/codebase_ir/384d/registry.duckdb",
+ "index_database": "/codebase_ir/384d/index.duckdb",
+ "ducklake_catalog_database": "/codebase_ir/384d/lake/catalog.duckdb",
+ "ducklake_data_prefix": "/codebase_ir/384d/lake/data/",
+ "mutable_artifact_root": "/codebase_ir/384d/artifacts/",
+ "run_namespace": "/codebase_ir/384d/runs////",
+ "database_writer_policy": "separate serialized owner per physical database; registry forbids foreign tables",
+ "canonical_repository_source_owner": "RepositoryCodebaseIndex captures repository code once; cell indexes reference exact admitted source/semantic heads when relevant",
+ "family_source_owner": "Canonical repository/source snapshot and source-correspondence owners",
+ "source_roots_required": [
+ "family source/corpus version and complete span/context manifest",
+ "repository source/semantic roots when code-grounding applies",
+ "applicability source revisions and both typed join endpoint roots"
+ ],
+ "ducklake_layout_adapter_required": true,
+ "current_isolated_history_limits": {
+ "metadata_name": "history.ducklake",
+ "byte_cap": 268435456,
+ "production_supported": false
+ }
+ },
+ "huggingface": {
+ "status": "proposed_not_created",
+ "repo_type": "model",
+ "repository_id_template": "/codebase-ir-autoencoder-384d",
+ "suggested_namespace_from_existing_release_descriptors": "Publicus",
+ "suggested_repository_id": "Publicus/codebase-ir-autoencoder-384d",
+ "namespace_write_access_verified": false,
+ "release_path_template": "releases////",
+ "load_requires": [
+ "full immutable commit",
+ "manifest SHA256",
+ "matching family/dimension role/task/profile/codec",
+ "actual checkpoint SHA256"
+ ],
+ "existing_read_only_descriptors": [],
+ "existing_descriptor_source": null,
+ "visibility": null,
+ "visibility_status": "explicit deployment configuration required; no visibility changes performed during planning"
+ },
+ "dimension_profile": {
+ "dimension": 384,
+ "encoder_kind": "GTE-small source embedding for source-conditioned tasks",
+ "model_id": "thenlper/gte-small",
+ "model_revision": "17e1f347d17fe144873b1201da91788898c639cd",
+ "hard_encoder_token_limit": 512,
+ "qualified_source_token_limit": null,
+ "pooling": "mean",
+ "normalization": "l2",
+ "unknown_limit_policy": "freeze task/span-specific admitted budget within encoder ceiling; historical compiler profiles remain separate",
+ "dimension_role_required": true
+ },
+ "task_profiles_to_inventory": [
+ "source_to_native_ir",
+ "structural_reconstruction",
+ "native_ir_to_logic",
+ "native_ir_to_source",
+ "retained_source_byte_restoration"
+ ],
+ "source_only_raw_text_decoder_admission": "not asserted by this plan; task/profile evidence and complete source access must be qualified independently",
+ "existing_checkpoint_evidence": [
+ {
+ "role": "registered shared parent envelope",
+ "receipt": {
+ "path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
+ "bytes": 1009515,
+ "sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
+ },
+ "dimension_role": "input_embedding",
+ "input_width": 384,
+ "owning_ir_family": "codebase_ir",
+ "payload_ir_family": "security_ir",
+ "decoder_kind": "frozen projection and fixed-tree ridge readout",
+ "native_codebase_decoder_complete": false
+ },
+ {
+ "role": "unpromoted repository child envelope",
+ "receipt": {
+ "path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
+ "bytes": 304490,
+ "sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
+ },
+ "dimension_role": "input_embedding",
+ "input_width": 384,
+ "payload_ir_family": "security_ir",
+ "development_parent_exact": "9/9",
+ "development_child_exact": "0/9",
+ "parent_pretraining_independence": "unknown",
+ "decoder_budget_unit": "fixed schema/scalar slots",
+ "promoted": false
+ }
+ ],
+ "checkpoint_discovery_complete": false,
+ "existing_cached_vector_rows": [],
+ "cached_codebase_rows_in_previous2640_transfer_inventory": 0,
+ "old_asset_policy": "Adopt authenticated read-only references. No recomputation, relabeling, in-place training or physical migration during planning.",
+ "span_curriculum": [
+ {
+ "stage_id": "S0",
+ "subject_scope": "same inherited expression cohort",
+ "qualified_input_budget": null,
+ "qualified_output_budget": null,
+ "budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
+ "requires_complete_span_accounting": true
+ },
+ {
+ "stage_id": "S1",
+ "subject_scope": "complete supported expression/function",
+ "qualified_input_budget": null,
+ "qualified_output_budget": null,
+ "budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
+ "requires_complete_span_accounting": true
+ },
+ {
+ "stage_id": "S2",
+ "subject_scope": "connected calls/import context",
+ "qualified_input_budget": null,
+ "qualified_output_budget": null,
+ "budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
+ "requires_complete_span_accounting": true
+ },
+ {
+ "stage_id": "S3",
+ "subject_scope": "complete supported function/module unit",
+ "qualified_input_budget": null,
+ "qualified_output_budget": null,
+ "budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
+ "requires_complete_span_accounting": true
+ },
+ {
+ "stage_id": "S4",
+ "subject_scope": "sealed module/dependency-slice aggregation",
+ "qualified_input_budget": null,
+ "qualified_output_budget": null,
+ "budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
+ "requires_complete_span_accounting": true
+ }
+ ],
+ "independent_heads": [
+ "source_applicability",
+ "serving_model_by_task_profile",
+ "candidate_training",
+ "lake_history_delivery",
+ "hub_publication"
+ ],
+ "promotion_policy": "Independent family/task/profile gate; original parent and shorter-span replay retained; another cell cannot grant qualification.",
+ "notes": [
+ "Existing wrapper retains SecurityIR numerical payload; native Codebase codec/head and source-successor coverage require separate qualification."
+ ],
+ "runtime_databases_created": false,
+ "remote_repository_created": false,
+ "model_or_embeddings_modified": false,
+ "continuation_and_transfer_policy": {
+ "same_variant_resume_parent_required": true,
+ "cross_cell_or_contract_transfer": "Use authenticated donor store/version/checkpoint refs and explicit transfer/KD edge, then initialize a new compatible variant; never fake same-variant parentage."
+ }
+}
diff --git a/releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py b/releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..446ea6eb734d8586a060f64fc56bf198e312aabe
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py
@@ -0,0 +1,4138 @@
+"""Typed constrained decoding for LegalIR candidates.
+
+The learned LegalIR heads are allowed to rank candidate productions, but they
+must not receive metric reward for output that a deterministic compiler could
+never consume. This module validates decoded LegalIR payloads against compact
+typed grammars before semantic metrics are scored. It is intentionally
+dependency-free and JSON-shape based so it can guard adapter outputs,
+autoencoder targets, and rollout artifacts uniformly.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import re
+from collections.abc import Callable, Mapping, Sequence
+from dataclasses import dataclass, field
+from typing import Any, Final, Optional
+
+from .legal_ir_family_evaluator import canonical_legal_ir_evaluation_family
+
+
+LEGAL_IR_GRAMMAR_DECODER_SCHEMA_VERSION: Final = "legal-ir-typed-grammar-decoder-v1"
+LEGAL_IR_CONSTRAINED_DECODER_SCHEMA: Final = "IRConstrainedDecoder@1"
+LEGAL_IR_CONSTRAINED_DECODER_INTERFACE: Final = (
+ "proof-grounded-ir-learning/constrained-decoder/v1"
+)
+LEGAL_IR_MAX_BEAM_WIDTH: Final = 16
+LEGAL_IR_MAX_DECODE_STEPS: Final = 64
+LEGAL_IR_CONSTRAINT_MASK_NAMES: Final[tuple[str, ...]] = (
+ "valid_token",
+ "grammar",
+ "binder",
+ "type",
+ "family",
+)
+LEGAL_IR_DECODE_FALLBACKS: Final[tuple[str, ...]] = (
+ "reject",
+ "eos",
+ "gold_if_admitted",
+)
+LEGAL_IR_FROZEN_TOKENIZER_SCHEMA_VERSION: Final = "legal-ir-frozen-tokenizer-v1"
+LEGAL_IR_FROZEN_VOCABULARY_SCHEMA: Final = "IRFrozenTokenizerVocabulary@1"
+LEGAL_IR_FROZEN_TOKENIZER_INTERFACE: Final = (
+ "proof-grounded-ir-learning/canonical-frozen-tokenizer/v1"
+)
+LEGAL_IR_IDENTIFIER_BUCKET_COUNT: Final = 32
+LEGAL_IR_CANONICAL_VOCABULARY_SIZE: Final = 143
+LEGAL_IR_CANONICAL_VOCABULARY_CID: Final = (
+ "sha256:8782ea363f422557c7a1f62442fe376fb6586f90a679bebb4ba60824de425c1b"
+)
+LEGAL_IR_TOKEN_CLASSES: Final[tuple[str, ...]] = (
+ "padding",
+ "special",
+ "binder",
+ "operator",
+ "type",
+ "family",
+ "proof",
+ "tactic",
+ "source",
+ "identifier",
+ "production",
+ "source_surface",
+)
+LEGAL_IR_CLOSED_TOKEN_CLASSES: Final[frozenset[str]] = frozenset(
+ {
+ "padding",
+ "special",
+ "binder",
+ "operator",
+ "type",
+ "family",
+ "proof",
+ "tactic",
+ "source",
+ "production",
+ }
+)
+LEGAL_IR_GRAMMAR_FAMILIES: Final[tuple[str, ...]] = (
+ "deontic",
+ "frame_logic",
+ "tdfol",
+ "knowledge_graphs",
+ "cec",
+ "external_provers",
+ "decompiler",
+ "temporal",
+ "provenance",
+)
+
+_FAMILY_ALIASES: Final[Mapping[str, str]] = {
+ "deontic": "deontic",
+ "deontic_ir": "deontic",
+ "deontic.ir": "deontic",
+ "frame": "frame_logic",
+ "frame_logic": "frame_logic",
+ "flogic": "frame_logic",
+ "modal.frame_logic": "frame_logic",
+ "tdfol": "tdfol",
+ "tdfol.prover": "tdfol",
+ "kg": "knowledge_graphs",
+ "knowledge_graph": "knowledge_graphs",
+ "knowledge_graphs": "knowledge_graphs",
+ "knowledge_graphs.neo4j_compat": "knowledge_graphs",
+ "cec": "cec",
+ "cec.native": "cec",
+ "external_prover": "external_provers",
+ "external_provers": "external_provers",
+ "prover": "external_provers",
+ "decompiler": "decompiler",
+ "decompiler_plan": "decompiler",
+ "temporal": "temporal",
+ "temporal_logic": "temporal",
+ "provenance": "provenance",
+}
+
+_PLACEHOLDER_RE: Final = re.compile(
+ r"(\{\{[^}]*\}\}|<[^>]*(?:source|placeholder|todo|copy)[^>]*>|"
+ r"\b(?:todo|tbd|placeholder|source_text|raw_source|copy_source|lorem ipsum)\b|"
+ r"__[^_]*(?:source|placeholder|todo)[^_]*__)",
+ re.IGNORECASE,
+)
+_SOURCE_TEXT_FIELD_RE: Final = re.compile(
+ r"^(?:raw_source|source_text|copied_text|verbatim_text|source_copy)$",
+ re.IGNORECASE,
+)
+_IDENT_RE: Final = re.compile(r"^[A-Za-z_][A-Za-z0-9_.:-]*$")
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRProductionSpec:
+ """One typed production admitted by a LegalIR family grammar."""
+
+ name: str
+ family: str
+ output_type: str
+ required_fields: tuple[str, ...]
+ optional_fields: tuple[str, ...] = ()
+ description: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "description": self.description,
+ "family": self.family,
+ "name": self.name,
+ "optional_fields": list(self.optional_fields),
+ "output_type": self.output_type,
+ "required_fields": list(self.required_fields),
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRGrammarRejection:
+ """Structured reason for rejecting a candidate or production."""
+
+ reason: str
+ path: str = "$"
+ family: str = "unscoped"
+ production: str = ""
+ detail: str = ""
+
+ def to_dict(self) -> dict[str, str]:
+ return {
+ "detail": self.detail,
+ "family": self.family,
+ "path": self.path,
+ "production": self.production,
+ "reason": self.reason,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRGrammarValidation:
+ """Validation result for one candidate IR object."""
+
+ accepted: bool
+ family: str
+ candidate_ir: Any
+ rejection_reasons: tuple[LegalIRGrammarRejection, ...] = ()
+ selected_productions: tuple[str, ...] = ()
+ masked_productions: tuple[str, ...] = ()
+ schema_version: str = LEGAL_IR_GRAMMAR_DECODER_SCHEMA_VERSION
+
+ @property
+ def rejection_reason_names(self) -> tuple[str, ...]:
+ return tuple(reason.reason for reason in self.rejection_reasons)
+
+ @property
+ def syntactic_validity_success_rate(self) -> float:
+ return 1.0 if self.accepted else 0.0
+
+ @property
+ def source_copy_placeholder_penalty(self) -> float:
+ return (
+ 1.0
+ if any(
+ reason.reason in {"source_copy_placeholder", "raw_source_copy_field"}
+ for reason in self.rejection_reasons
+ )
+ else 0.0
+ )
+
+ def metrics(self) -> dict[str, float]:
+ rejection_count = float(len(self.rejection_reasons))
+ invalid = 0.0 if self.accepted else 1.0
+ values: dict[str, float] = {
+ "legal_ir_grammar_accepted": 1.0 if self.accepted else 0.0,
+ "legal_ir_grammar_invalid_production_penalty": invalid,
+ "legal_ir_grammar_rejection_count": rejection_count,
+ "legal_ir_grammar_rejection_ratio": invalid,
+ "legal_ir_grammar_source_copy_placeholder_penalty": (
+ self.source_copy_placeholder_penalty
+ ),
+ "legal_ir_grammar_syntactic_validity_success_rate": (
+ self.syntactic_validity_success_rate
+ ),
+ }
+ for reason in self.rejection_reasons:
+ values[f"legal_ir_grammar_rejection_reason_{_metric_slug(reason.reason)}"] = 1.0
+ return values
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "accepted": self.accepted,
+ "candidate_digest": _stable_digest(self.candidate_ir),
+ "family": self.family,
+ "masked_productions": list(self.masked_productions),
+ "metrics": self.metrics(),
+ "rejection_reasons": [reason.to_dict() for reason in self.rejection_reasons],
+ "schema_version": self.schema_version,
+ "selected_productions": list(self.selected_productions),
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ConstrainedLegalIRDecode:
+ """Result of masking and selecting from scored LegalIR productions."""
+
+ accepted: bool
+ family: str
+ decoded_ir: Any
+ selected_production: str = ""
+ selected_score: float = 0.0
+ valid_scores: Mapping[str, float] = field(default_factory=dict)
+ masked_scores: Mapping[str, float] = field(default_factory=dict)
+ validation: LegalIRGrammarValidation = field(
+ default_factory=lambda: LegalIRGrammarValidation(
+ accepted=False,
+ family="unscoped",
+ candidate_ir=None,
+ rejection_reasons=(LegalIRGrammarRejection(reason="no_candidate", family="unscoped"),),
+ )
+ )
+ schema_version: str = LEGAL_IR_GRAMMAR_DECODER_SCHEMA_VERSION
+
+ @property
+ def rejection_reasons(self) -> tuple[LegalIRGrammarRejection, ...]:
+ return self.validation.rejection_reasons
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "accepted": self.accepted,
+ "decoded_ir": self.decoded_ir if self.accepted else None,
+ "family": self.family,
+ "masked_scores": {
+ str(name): round(float(score), 12)
+ for name, score in sorted(self.masked_scores.items())
+ },
+ "rejection_reasons": [reason.to_dict() for reason in self.rejection_reasons],
+ "schema_version": self.schema_version,
+ "selected_production": self.selected_production,
+ "selected_score": round(float(self.selected_score), 12),
+ "valid_scores": {
+ str(name): round(float(score), 12)
+ for name, score in sorted(self.valid_scores.items())
+ },
+ "validation": self.validation.to_dict(),
+ }
+
+
+class LegalIRGrammarDecoder:
+ """Validate and decode LegalIR candidates with family-specific grammars."""
+
+ def __init__(
+ self,
+ *,
+ production_specs: Optional[Sequence[LegalIRProductionSpec]] = None,
+ tokenizer: Optional["LegalIRFrozenTokenizer"] = None,
+ ) -> None:
+ specs = tuple(production_specs or default_legal_ir_production_specs())
+ self.production_specs: dict[str, LegalIRProductionSpec] = {
+ spec.name: spec for spec in specs
+ }
+ self._frozen_tokenizer = tokenizer
+ self.productions_by_family: dict[str, tuple[str, ...]] = {}
+ for spec in specs:
+ family = canonical_legal_ir_grammar_family(spec.family)
+ self.productions_by_family.setdefault(family, ())
+ self.productions_by_family[family] = (
+ *self.productions_by_family[family],
+ spec.name,
+ )
+
+ def validate(
+ self,
+ candidate_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ production: str = "",
+ ) -> LegalIRGrammarValidation:
+ family_name = infer_legal_ir_grammar_family(candidate_ir, family=family)
+ candidate = _mapping_or_sequence(candidate_ir)
+ rejections: list[LegalIRGrammarRejection] = []
+
+ if candidate is None:
+ rejections.append(
+ LegalIRGrammarRejection(
+ reason="candidate_not_structured",
+ family=family_name,
+ production=production,
+ detail=type(candidate_ir).__name__,
+ )
+ )
+ return _validation(candidate_ir, family_name, rejections, production)
+
+ rejections.extend(
+ _source_copy_rejections(
+ candidate,
+ source_text=source_text,
+ family=family_name,
+ production=production,
+ )
+ )
+ family_validator = _FAMILY_VALIDATORS.get(family_name)
+ if family_validator is None:
+ rejections.append(
+ LegalIRGrammarRejection(
+ reason="unsupported_family",
+ family=family_name,
+ production=production,
+ )
+ )
+ else:
+ rejections.extend(family_validator(candidate, family_name, production))
+ return _validation(candidate_ir, family_name, rejections, production)
+
+ def mask_invalid_productions(
+ self,
+ scored_productions: Mapping[str, Any] | Sequence[Any],
+ *,
+ family: str = "",
+ source_text: str = "",
+ context: Optional[Mapping[str, Any]] = None,
+ ) -> ConstrainedLegalIRDecode:
+ """Remove invalid productions before downstream metrics see them."""
+
+ rows = _production_rows(scored_productions, context=context)
+ valid_scores: dict[str, float] = {}
+ masked_scores: dict[str, float] = {}
+ validations: dict[str, LegalIRGrammarValidation] = {}
+ for row in rows:
+ name = row["name"]
+ score = row["score"]
+ output = row.get("output")
+ row_family = row.get("family") or family
+ validation = self.validate(
+ output,
+ family=str(row_family or ""),
+ source_text=source_text,
+ production=name,
+ )
+ validations[name] = validation
+ if validation.accepted:
+ valid_scores[name] = score
+ else:
+ masked_scores[name] = score
+
+ if valid_scores:
+ selected = max(valid_scores, key=lambda item: (valid_scores[item], item))
+ validation = validations[selected]
+ return ConstrainedLegalIRDecode(
+ accepted=True,
+ family=validation.family,
+ decoded_ir=validation.candidate_ir,
+ selected_production=selected,
+ selected_score=valid_scores[selected],
+ valid_scores=valid_scores,
+ masked_scores=masked_scores,
+ validation=validation,
+ )
+
+ reasons: list[LegalIRGrammarRejection] = []
+ selected_family = canonical_legal_ir_grammar_family(family or "decompiler")
+ for validation in validations.values():
+ selected_family = validation.family
+ reasons.extend(validation.rejection_reasons)
+ if not reasons:
+ reasons.append(
+ LegalIRGrammarRejection(
+ reason="no_productions",
+ family=selected_family,
+ )
+ )
+ validation = LegalIRGrammarValidation(
+ accepted=False,
+ family=selected_family,
+ candidate_ir=None,
+ rejection_reasons=tuple(_dedupe_rejections(reasons)),
+ masked_productions=tuple(sorted(masked_scores)),
+ )
+ return ConstrainedLegalIRDecode(
+ accepted=False,
+ family=selected_family,
+ decoded_ir=None,
+ valid_scores={},
+ masked_scores=masked_scores,
+ validation=validation,
+ )
+
+ def decode(
+ self,
+ scored_productions: Mapping[str, Any] | Sequence[Any],
+ *,
+ family: str = "",
+ source_text: str = "",
+ context: Optional[Mapping[str, Any]] = None,
+ ) -> ConstrainedLegalIRDecode:
+ return self.mask_invalid_productions(
+ scored_productions,
+ family=family,
+ source_text=source_text,
+ context=context,
+ )
+
+ def frozen_tokenizer(self) -> "LegalIRFrozenTokenizer":
+ """Return the decoder-bound frozen tokenizer without mutating vocabulary."""
+
+ if self._frozen_tokenizer is None:
+ self._frozen_tokenizer = LegalIRFrozenTokenizer.canonical()
+ return self._frozen_tokenizer
+
+ def encode_structured_output(
+ self,
+ candidate_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ ) -> "LegalIRTokenization":
+ """Validate then freeze-encode a structured LegalIR payload."""
+
+ validation = self.validate(
+ candidate_ir,
+ family=family,
+ source_text=source_text,
+ )
+ return self.frozen_tokenizer().encode_canonical(
+ candidate_ir,
+ family=validation.family,
+ source_text=source_text,
+ accepted=validation.accepted,
+ )
+
+ def compatible_learned_architectures(
+ self,
+ *,
+ seed: int = 0,
+ ) -> dict[str, Any]:
+ """Build both experiment arms on this decoder's frozen tokenizer."""
+
+ return compatible_architecture_suite(
+ seed=seed,
+ tokenizer=self.frozen_tokenizer(),
+ )
+
+ def constraint_masks(
+ self,
+ prefix_ids: Sequence[int] = (),
+ *,
+ family: str = "",
+ proof_state: Optional[Mapping[str, Any]] = None,
+ config: Optional["LegalIRConstrainedDecodeConfig"] = None,
+ ) -> "LegalIRConstraintMasks":
+ """Return inspectable valid-token/grammar/binder/type/family masks."""
+
+ return legal_ir_constraint_masks(
+ prefix_ids,
+ family=family,
+ tokenizer=self.frozen_tokenizer(),
+ proof_state=proof_state,
+ config=config,
+ )
+
+ def decode_tokens(
+ self,
+ logits: Any = None,
+ *,
+ family: str = "",
+ source_text: str = "",
+ gold_token_ids: Optional[Sequence[int]] = None,
+ gold_ir: Any = None,
+ proof_state: Optional[Mapping[str, Any]] = None,
+ architecture: Any = None,
+ config: Optional["LegalIRConstrainedDecodeConfig"] = None,
+ ) -> "LegalIRConstrainedTokenDecode":
+ """Run bounded, mask-constrained token decoding."""
+
+ return constrained_legal_ir_token_decode(
+ logits,
+ family=family,
+ source_text=source_text,
+ gold_token_ids=gold_token_ids,
+ gold_ir=gold_ir,
+ proof_state=proof_state,
+ architecture=architecture,
+ tokenizer=self.frozen_tokenizer(),
+ config=config,
+ )
+
+ def admit_gold_path(
+ self,
+ gold_token_ids: Sequence[int] | None = None,
+ *,
+ gold_ir: Any = None,
+ family: str = "",
+ proof_state: Optional[Mapping[str, Any]] = None,
+ config: Optional["LegalIRConstrainedDecodeConfig"] = None,
+ ) -> "LegalIRGoldPathAdmission":
+ """Admit a gold encoding only when every prefix stays legal."""
+
+ return admit_legal_ir_gold_path(
+ gold_token_ids,
+ gold_ir=gold_ir,
+ family=family,
+ tokenizer=self.frozen_tokenizer(),
+ proof_state=proof_state,
+ config=config,
+ )
+
+ def gate_prover_call(
+ self,
+ candidate_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ gold_token_ids: Optional[Sequence[int]] = None,
+ proof_state: Optional[Mapping[str, Any]] = None,
+ config: Optional["LegalIRConstrainedDecodeConfig"] = None,
+ prover: Optional[Callable[..., Any]] = None,
+ ) -> "LegalIRProverAdmission":
+ """Reject illegal candidates before they can spend proof budget."""
+
+ return gate_legal_ir_prover_call(
+ candidate_ir,
+ family=family,
+ source_text=source_text,
+ gold_token_ids=gold_token_ids,
+ tokenizer=self.frozen_tokenizer(),
+ proof_state=proof_state,
+ config=config,
+ prover=prover,
+ )
+
+
+def canonical_legal_ir_grammar_family(family: str) -> str:
+ """Normalize grammar families, including view-name aliases."""
+
+ normalized = str(family or "").strip().lower().replace("-", "_").replace("/", ".")
+ normalized = normalized.removeprefix("legal_ir_view.").removeprefix("legal-ir-view.")
+ canonical = _FAMILY_ALIASES.get(normalized)
+ if canonical:
+ return canonical
+ try:
+ return canonical_legal_ir_evaluation_family(normalized)
+ except ValueError:
+ return "unscoped" if not normalized else normalized
+
+
+def infer_legal_ir_grammar_family(candidate_ir: Any, *, family: str = "") -> str:
+ explicit = canonical_legal_ir_grammar_family(family)
+ if explicit and explicit != "unscoped":
+ return explicit
+ source = _object_to_mapping(candidate_ir)
+ for key in ("family", "legal_ir_family", "view_family", "logic_family"):
+ if key in source:
+ resolved = canonical_legal_ir_grammar_family(str(source.get(key) or ""))
+ if resolved != "unscoped":
+ return resolved
+ for key in ("legal_ir_view", "target_view", "view", "contract_id"):
+ if key in source:
+ resolved = canonical_legal_ir_grammar_family(str(source.get(key) or ""))
+ if resolved != "unscoped":
+ return resolved
+ if any(key in source for key in ("obligations", "deontic_rules")):
+ return "deontic"
+ if any(key in source for key in ("triples", "frames", "frame_logic")):
+ return "frame_logic"
+ if any(key in source for key in ("formulas", "quantifiers", "predicates")):
+ return "tdfol"
+ if any(key in source for key in ("nodes", "edges", "graph")):
+ return "knowledge_graphs"
+ if any(key in source for key in ("counterexamples", "contexts", "events")):
+ return "cec"
+ if any(key in source for key in ("intervals", "temporal_windows", "relations")):
+ return "temporal"
+ if any(key in source for key in ("source_refs", "citations", "evidence")):
+ return "provenance"
+ if any(key in source for key in ("steps", "plan", "round_trip")):
+ return "decompiler"
+ return "unscoped"
+
+
+def validate_legal_ir_candidate(
+ candidate_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+) -> LegalIRGrammarValidation:
+ """Convenience API for validating one LegalIR payload."""
+
+ return LegalIRGrammarDecoder().validate(
+ candidate_ir,
+ family=family,
+ source_text=source_text,
+ )
+
+
+def constrained_legal_ir_decode(
+ scored_productions: Mapping[str, Any] | Sequence[Any],
+ *,
+ family: str = "",
+ source_text: str = "",
+ context: Optional[Mapping[str, Any]] = None,
+) -> ConstrainedLegalIRDecode:
+ """Convenience API for masked production selection."""
+
+ return LegalIRGrammarDecoder().decode(
+ scored_productions,
+ family=family,
+ source_text=source_text,
+ context=context,
+ )
+
+
+_MASKED_LOGIT: Final = -1.0e9
+_CLOSED_PROOF_STATUSES: Final[frozenset[str]] = frozenset(
+ {"proved", "disproved", "counterexample"}
+)
+_OPERATOR_VALUE_FIELDS: Final[frozenset[str]] = frozenset(
+ {
+ "modality",
+ "operator",
+ "slot",
+ "label",
+ "connective",
+ "quantifier",
+ "op",
+ "operation",
+ "predicate",
+ "relation",
+ "backend",
+ "goal",
+ }
+)
+_FAMILY_VALUE_FIELDS: Final[frozenset[str]] = frozenset(
+ {
+ "family",
+ "legal_ir_family",
+ "target_view",
+ "view",
+ "legal_ir_view",
+ "contract_id",
+ }
+)
+_BINDER_VALUE_FIELDS: Final[frozenset[str]] = frozenset(
+ {
+ "quantifier",
+ "variables",
+ "bind",
+ "binder",
+ "lambda",
+ "let",
+ }
+)
+_CROSS_FAMILY_HOSTS: Final[frozenset[str]] = frozenset(
+ {
+ "decompiler",
+ "external_provers",
+ "provenance",
+ }
+)
+_SHARED_OPERATORS: Final[frozenset[str]] = frozenset(
+ {"and", "or", "not", "implies", "iff"}
+)
+_FAMILY_OWNED_OPERATORS: Final[Mapping[str, frozenset[str]]] = {
+ "deontic": frozenset(
+ {
+ "obligation",
+ "permission",
+ "prohibition",
+ "duty",
+ "right",
+ "must",
+ "may",
+ "shall",
+ "must_not",
+ }
+ ),
+ "tdfol": frozenset({"and", "or", "not", "implies", "iff"}),
+ "frame_logic": frozenset({"and", "or", "not", "implies"}),
+ "temporal": frozenset({"and", "or", "not", "implies"}),
+ "knowledge_graphs": frozenset({"and", "or", "not"}),
+ "cec": frozenset({"and", "or", "not"}),
+ "external_provers": frozenset({"and", "or", "not", "implies", "iff"}),
+ "decompiler": frozenset(),
+ "provenance": frozenset(),
+}
+_EXCLUSIVE_OPERATORS_BY_FAMILY: Final[Mapping[str, frozenset[str]]] = {
+ "deontic": frozenset(
+ {
+ "obligation",
+ "permission",
+ "prohibition",
+ "duty",
+ "right",
+ "must",
+ "may",
+ "shall",
+ "must_not",
+ }
+ ),
+}
+
+
+class UnboundedLegalIRBeamError(ValueError):
+ """Raised when a caller requests an unbounded or over-cap beam."""
+
+
+class LegalIRConstraintBypassError(ValueError):
+ """Raised when a caller tries to disable parser or type constraints."""
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRConstrainedDecodeConfig:
+ """Hard-bounded constrained decoder contract. Parser/type cannot be bypassed."""
+
+ beam_width: int = 4
+ max_steps: int = 32
+ max_expansions: int = 256
+ fallback: str = "reject"
+ proof_state_pruning: bool = False
+ parser_pruning: bool = True
+ type_checks: bool = True
+ family: str = ""
+
+ def __post_init__(self) -> None:
+ width = int(self.beam_width)
+ steps = int(self.max_steps)
+ expansions = int(self.max_expansions)
+ fallback = str(self.fallback or "reject").strip().lower()
+ if width < 1 or width > LEGAL_IR_MAX_BEAM_WIDTH:
+ raise UnboundedLegalIRBeamError(
+ f"beam_width must be in 1..{LEGAL_IR_MAX_BEAM_WIDTH}, got {width}"
+ )
+ if steps < 1 or steps > LEGAL_IR_MAX_DECODE_STEPS:
+ raise UnboundedLegalIRBeamError(
+ f"max_steps must be in 1..{LEGAL_IR_MAX_DECODE_STEPS}, got {steps}"
+ )
+ if expansions < 1:
+ raise UnboundedLegalIRBeamError("max_expansions must be a positive bound")
+ if fallback not in LEGAL_IR_DECODE_FALLBACKS:
+ raise ValueError(
+ "fallback must be one of " + ", ".join(LEGAL_IR_DECODE_FALLBACKS)
+ )
+ if not bool(self.parser_pruning):
+ raise LegalIRConstraintBypassError(
+ "parser pruning cannot be disabled; parser/type bypass is prohibited"
+ )
+ if not bool(self.type_checks):
+ raise LegalIRConstraintBypassError(
+ "type checks cannot be disabled; parser/type bypass is prohibited"
+ )
+ object.__setattr__(self, "beam_width", width)
+ object.__setattr__(self, "max_steps", steps)
+ object.__setattr__(self, "max_expansions", expansions)
+ object.__setattr__(self, "fallback", fallback)
+ object.__setattr__(self, "family", str(self.family or ""))
+
+ def bounds(self) -> dict[str, Any]:
+ return {
+ "beam_width": int(self.beam_width),
+ "fallback": self.fallback,
+ "max_beam_width": LEGAL_IR_MAX_BEAM_WIDTH,
+ "max_expansions": int(self.max_expansions),
+ "max_steps": int(self.max_steps),
+ "parser_pruning": True,
+ "proof_state_pruning": bool(self.proof_state_pruning),
+ "type_checks": True,
+ }
+
+ def to_dict(self) -> dict[str, Any]:
+ payload = self.bounds()
+ payload["family"] = self.family
+ payload["schema"] = LEGAL_IR_CONSTRAINED_DECODER_SCHEMA
+ return payload
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRConstraintMasks:
+ """Separately inspectable constraint masks over the frozen vocabulary."""
+
+ valid_token: tuple[bool, ...]
+ grammar: tuple[bool, ...]
+ binder: tuple[bool, ...]
+ type: tuple[bool, ...]
+ family: tuple[bool, ...]
+ family_name: str = ""
+ prefix_ids: tuple[int, ...] = ()
+ schema: str = LEGAL_IR_CONSTRAINED_DECODER_SCHEMA
+
+ def intersected(self) -> tuple[bool, ...]:
+ return tuple(
+ all(flags)
+ for flags in zip(
+ self.valid_token,
+ self.grammar,
+ self.binder,
+ self.type,
+ self.family,
+ strict=True,
+ )
+ )
+
+ def allowed_token_ids(self) -> tuple[int, ...]:
+ return tuple(
+ index for index, allowed in enumerate(self.intersected()) if allowed
+ )
+
+ def allowed_count(self) -> int:
+ return sum(1 for allowed in self.intersected() if allowed)
+
+ def layer(self, name: str) -> tuple[bool, ...]:
+ layers = {
+ "valid_token": self.valid_token,
+ "grammar": self.grammar,
+ "binder": self.binder,
+ "type": self.type,
+ "family": self.family,
+ }
+ if name not in layers:
+ raise KeyError(f"unknown constraint mask {name!r}")
+ return layers[name]
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "allowed_count": self.allowed_count(),
+ "allowed_token_ids": list(self.allowed_token_ids()),
+ "family": self.family_name,
+ "layers": {
+ name: sum(1 for allowed in self.layer(name) if allowed)
+ for name in LEGAL_IR_CONSTRAINT_MASK_NAMES
+ },
+ "prefix_ids": [int(token_id) for token_id in self.prefix_ids],
+ "schema": self.schema,
+ "vocabulary_size": len(self.valid_token),
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRConstraintRejectionTelemetry:
+ """Rejection telemetry for constrained decoding and prover admission."""
+
+ contract: str = LEGAL_IR_CONSTRAINED_DECODER_INTERFACE
+ schema: str = LEGAL_IR_CONSTRAINED_DECODER_SCHEMA
+ family: str = ""
+ rejection_reasons: tuple[str, ...] = ()
+ masked_token_count: int = 0
+ parser_pruned_count: int = 0
+ proof_state_pruned_count: int = 0
+ prover_calls: int = 0
+ prover_calls_avoided: int = 0
+ beam_width: int = 0
+ max_beam_width: int = LEGAL_IR_MAX_BEAM_WIDTH
+ fallback: str = "reject"
+ fallback_used: str = ""
+ bounds: Mapping[str, Any] = field(default_factory=dict)
+ gold_path_preserved: bool = False
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "beam_width": int(self.beam_width),
+ "bounds": dict(self.bounds),
+ "contract": self.contract,
+ "family": self.family,
+ "fallback": self.fallback,
+ "fallback_used": self.fallback_used,
+ "gold_path_preserved": bool(self.gold_path_preserved),
+ "masked_token_count": int(self.masked_token_count),
+ "max_beam_width": int(self.max_beam_width),
+ "parser_pruned_count": int(self.parser_pruned_count),
+ "proof_state_pruned_count": int(self.proof_state_pruned_count),
+ "prover_calls": int(self.prover_calls),
+ "prover_calls_avoided": int(self.prover_calls_avoided),
+ "rejection_reasons": list(self.rejection_reasons),
+ "schema": self.schema,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRBeamHypothesis:
+ """One bounded beam hypothesis."""
+
+ token_ids: tuple[int, ...]
+ score: float
+ finished: bool = False
+ fallback_used: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "fallback_used": self.fallback_used,
+ "finished": self.finished,
+ "score": round(float(self.score), 12),
+ "token_ids": [int(token_id) for token_id in self.token_ids],
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRConstrainedTokenDecode:
+ """Result of bounded grammar/binder/type/family/proof-state decoding."""
+
+ accepted: bool
+ family: str
+ token_ids: tuple[int, ...]
+ tokens: tuple[str, ...] = ()
+ score: float = 0.0
+ beam_width: int = 0
+ steps: int = 0
+ expansions: int = 0
+ fallback: str = "reject"
+ fallback_used: str = ""
+ gold_path_preserved: bool = False
+ parser_pruned: int = 0
+ proof_state_pruned: int = 0
+ hypotheses: tuple[LegalIRBeamHypothesis, ...] = ()
+ telemetry: LegalIRConstraintRejectionTelemetry = field(
+ default_factory=LegalIRConstraintRejectionTelemetry
+ )
+ schema: str = LEGAL_IR_CONSTRAINED_DECODER_SCHEMA
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "accepted": self.accepted,
+ "beam_width": int(self.beam_width),
+ "expansions": int(self.expansions),
+ "fallback": self.fallback,
+ "fallback_used": self.fallback_used,
+ "family": self.family,
+ "gold_path_preserved": self.gold_path_preserved,
+ "hypotheses": [item.to_dict() for item in self.hypotheses],
+ "parser_pruned": int(self.parser_pruned),
+ "proof_state_pruned": int(self.proof_state_pruned),
+ "schema": self.schema,
+ "score": round(float(self.score), 12),
+ "steps": int(self.steps),
+ "telemetry": self.telemetry.to_dict(),
+ "token_ids": [int(token_id) for token_id in self.token_ids],
+ "tokens": list(self.tokens),
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRGoldPathAdmission:
+ """Whether every gold prefix remains inside the constraint masks."""
+
+ admitted: bool
+ family: str
+ token_ids: tuple[int, ...]
+ illegal_index: int = -1
+ illegal_token_id: int = -1
+ rejection_reasons: tuple[str, ...] = ()
+ schema: str = LEGAL_IR_CONSTRAINED_DECODER_SCHEMA
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "admitted": self.admitted,
+ "family": self.family,
+ "illegal_index": int(self.illegal_index),
+ "illegal_token_id": int(self.illegal_token_id),
+ "rejection_reasons": list(self.rejection_reasons),
+ "schema": self.schema,
+ "token_ids": [int(token_id) for token_id in self.token_ids],
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRProverAdmission:
+ """Fail-closed prover gate: illegal candidates never spend proof budget."""
+
+ admitted: bool
+ family: str
+ prover_calls: int
+ candidate_ir: Any
+ rejection_reasons: tuple[str, ...] = ()
+ proof_result: Any = None
+ telemetry: LegalIRConstraintRejectionTelemetry = field(
+ default_factory=LegalIRConstraintRejectionTelemetry
+ )
+ schema: str = LEGAL_IR_CONSTRAINED_DECODER_SCHEMA
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "admitted": self.admitted,
+ "family": self.family,
+ "prover_calls": int(self.prover_calls),
+ "rejection_reasons": list(self.rejection_reasons),
+ "schema": self.schema,
+ "telemetry": self.telemetry.to_dict(),
+ }
+
+
+def legal_ir_constrained_decode_config(
+ **kwargs: Any,
+) -> LegalIRConstrainedDecodeConfig:
+ return LegalIRConstrainedDecodeConfig(**kwargs)
+
+
+def legal_ir_constraint_masks(
+ prefix_ids: Sequence[int] = (),
+ *,
+ family: str = "",
+ tokenizer: Optional["LegalIRFrozenTokenizer"] = None,
+ proof_state: Optional[Mapping[str, Any]] = None,
+ config: Optional[LegalIRConstrainedDecodeConfig] = None,
+) -> LegalIRConstraintMasks:
+ """Build valid-token, grammar, binder, type, and family masks for a prefix."""
+
+ frozen = tokenizer or LegalIRFrozenTokenizer.canonical()
+ settings = config or LegalIRConstrainedDecodeConfig(family=family)
+ family_name = canonical_legal_ir_grammar_family(family or settings.family)
+ prefix = tuple(int(token_id) for token_id in prefix_ids)
+ vocab_size = frozen.vocabulary_size
+ valid_token = [False] * vocab_size
+ grammar = [False] * vocab_size
+ binder = [False] * vocab_size
+ type_mask = [False] * vocab_size
+ family_mask = [False] * vocab_size
+ phase = _parser_phase(prefix, frozen, family=family_name)
+ last_piece, last_class = _prefix_tail(prefix, frozen)
+ proof = _normalize_proof_state(proof_state)
+ prune_tactics = bool(settings.proof_state_pruning) and _proof_state_closed(proof)
+ forbidden = set(proof.get("forbidden_token_ids") or ())
+ forbidden.update(
+ _token_id_for_piece(frozen, piece)
+ for piece in proof.get("forbidden_tokens") or ()
+ if _token_id_for_piece(frozen, piece) >= 0
+ )
+
+ for entry in frozen._entries: # noqa: SLF001 - sealed vocab walk
+ token_id = int(entry.token_id)
+ piece = entry.piece
+ token_class = entry.token_class
+ if token_id in forbidden:
+ continue
+ if token_class == "padding" and phase != "complete":
+ continue
+ if token_class == "source_surface":
+ continue
+ valid_token[token_id] = True
+
+ if token_class == "binder":
+ if _binder_allowed(phase, family_name, last_piece, last_class):
+ binder[token_id] = True
+ grammar[token_id] = True
+ type_mask[token_id] = True
+ family_mask[token_id] = True
+ continue
+ binder[token_id] = True
+
+ if token_class == "type":
+ if _type_allowed(phase, family_name, piece):
+ type_mask[token_id] = True
+ grammar[token_id] = True
+ family_mask[token_id] = True
+ continue
+ type_mask[token_id] = True
+
+ if token_class == "family" or _alias_family_piece(family_name, piece, token_class):
+ if _family_token_allowed(phase, family_name, piece, last_piece):
+ family_mask[token_id] = True
+ grammar[token_id] = True
+ continue
+ family_mask[token_id] = True
+
+ if not _grammar_token_allowed(
+ phase,
+ family_name,
+ piece,
+ token_class,
+ last_piece=last_piece,
+ prune_tactics=prune_tactics,
+ eos_id=frozen.eos_id,
+ bos_id=frozen.bos_id,
+ pad_id=frozen.pad_id,
+ ):
+ continue
+ grammar[token_id] = True
+
+ return LegalIRConstraintMasks(
+ valid_token=tuple(valid_token),
+ grammar=tuple(grammar),
+ binder=tuple(binder),
+ type=tuple(type_mask),
+ family=tuple(family_mask),
+ family_name=family_name,
+ prefix_ids=prefix,
+ )
+
+
+def apply_legal_ir_constraint_masks(
+ logits: Sequence[float],
+ masks: LegalIRConstraintMasks,
+) -> list[float]:
+ """Intersect masks and zero out illegal logits without mutating inputs."""
+
+ allowed = masks.intersected()
+ if len(logits) != len(allowed):
+ raise ValueError(
+ f"logit width {len(logits)} does not match vocabulary {len(allowed)}"
+ )
+ return [
+ float(logit) if flag else _MASKED_LOGIT
+ for logit, flag in zip(logits, allowed, strict=True)
+ ]
+
+
+def admit_legal_ir_gold_path(
+ gold_token_ids: Sequence[int] | None = None,
+ *,
+ gold_ir: Any = None,
+ family: str = "",
+ tokenizer: Optional["LegalIRFrozenTokenizer"] = None,
+ proof_state: Optional[Mapping[str, Any]] = None,
+ config: Optional[LegalIRConstrainedDecodeConfig] = None,
+) -> LegalIRGoldPathAdmission:
+ """Every gold prefix must remain a legal continuation."""
+
+ frozen = tokenizer or LegalIRFrozenTokenizer.canonical()
+ family_name = canonical_legal_ir_grammar_family(family)
+ try:
+ token_ids = _resolve_gold_token_ids(
+ gold_token_ids,
+ gold_ir=gold_ir,
+ family=family_name,
+ tokenizer=frozen,
+ )
+ except (UnknownFrozenTokenError, FrozenVocabularyMutationError, ValueError):
+ return LegalIRGoldPathAdmission(
+ admitted=False,
+ family=family_name,
+ token_ids=(),
+ rejection_reasons=("gold_unencodable",),
+ )
+ for index, token_id in enumerate(token_ids):
+ masks = legal_ir_constraint_masks(
+ token_ids[:index],
+ family=family_name,
+ tokenizer=frozen,
+ proof_state=proof_state,
+ config=config,
+ )
+ if int(token_id) not in set(masks.allowed_token_ids()):
+ reason = _gold_rejection_reason(frozen, int(token_id), index)
+ return LegalIRGoldPathAdmission(
+ admitted=False,
+ family=family_name,
+ token_ids=token_ids,
+ illegal_index=index,
+ illegal_token_id=int(token_id),
+ rejection_reasons=(reason,),
+ )
+ return LegalIRGoldPathAdmission(
+ admitted=bool(token_ids),
+ family=family_name,
+ token_ids=token_ids,
+ rejection_reasons=() if token_ids else ("empty_gold_path",),
+ )
+
+
+def constrained_legal_ir_token_decode(
+ logits: Any = None,
+ *,
+ family: str = "",
+ source_text: str = "",
+ gold_token_ids: Optional[Sequence[int]] = None,
+ gold_ir: Any = None,
+ proof_state: Optional[Mapping[str, Any]] = None,
+ architecture: Any = None,
+ tokenizer: Optional["LegalIRFrozenTokenizer"] = None,
+ config: Optional[LegalIRConstrainedDecodeConfig] = None,
+) -> LegalIRConstrainedTokenDecode:
+ """Bounded beam search under grammar/binder/type/family/proof-state masks."""
+
+ del source_text # source surface stays off the canonical decode path
+ frozen = tokenizer or LegalIRFrozenTokenizer.canonical()
+ settings = config or LegalIRConstrainedDecodeConfig(family=family)
+ family_name = canonical_legal_ir_grammar_family(family or settings.family)
+ gold_ids = _resolve_gold_token_ids(
+ gold_token_ids,
+ gold_ir=gold_ir,
+ family=family_name,
+ tokenizer=frozen,
+ )
+ gold_admission = (
+ admit_legal_ir_gold_path(
+ gold_ids,
+ family=family_name,
+ tokenizer=frozen,
+ proof_state=proof_state,
+ config=settings,
+ )
+ if gold_ids
+ else None
+ )
+ beams: list[LegalIRBeamHypothesis] = [
+ LegalIRBeamHypothesis(token_ids=(), score=0.0, finished=False)
+ ]
+ parser_pruned = 0
+ proof_pruned = 0
+ expansions = 0
+ steps = 0
+ finished: list[LegalIRBeamHypothesis] = []
+
+ for step in range(settings.max_steps):
+ steps = step + 1
+ live = [beam for beam in beams if not beam.finished]
+ if not live:
+ break
+ next_beams: list[LegalIRBeamHypothesis] = []
+ for beam in live:
+ masks = legal_ir_constraint_masks(
+ beam.token_ids,
+ family=family_name,
+ tokenizer=frozen,
+ proof_state=proof_state,
+ config=settings,
+ )
+ raw_logits = _logits_for_prefix(
+ logits,
+ prefix_ids=beam.token_ids,
+ step=step,
+ architecture=architecture,
+ tokenizer=frozen,
+ )
+ masked = apply_legal_ir_constraint_masks(raw_logits, masks)
+ ranked = _rank_allowed_tokens(masked, limit=settings.beam_width)
+ if not ranked:
+ parser_pruned += 1
+ continue
+ for token_id, token_score in ranked:
+ if expansions >= settings.max_expansions and finished:
+ break
+ expansions += 1
+ entry = frozen.entry_for_id(token_id)
+ if (
+ settings.proof_state_pruning
+ and entry.token_class == "tactic"
+ and _proof_state_closed(_normalize_proof_state(proof_state))
+ ):
+ proof_pruned += 1
+ continue
+ extended = (*beam.token_ids, int(token_id))
+ done = int(token_id) == frozen.eos_id
+ hypothesis = LegalIRBeamHypothesis(
+ token_ids=extended,
+ score=float(beam.score) + float(token_score),
+ finished=done,
+ )
+ if done:
+ finished.append(hypothesis)
+ else:
+ next_beams.append(hypothesis)
+ if expansions >= settings.max_expansions and finished:
+ break
+ next_beams.sort(key=lambda item: (-item.score, item.token_ids))
+ beams = next_beams[: settings.beam_width]
+ if expansions >= settings.max_expansions and finished:
+ break
+
+ selected, fallback_used, reasons = _select_decode_result(
+ finished=finished,
+ live=beams,
+ settings=settings,
+ gold_ids=gold_ids,
+ gold_admission=gold_admission,
+ tokenizer=frozen,
+ )
+ tokens = (
+ tuple(frozen.decode_ids(selected.token_ids)) if selected.token_ids else ()
+ )
+ gold_preserved = bool(
+ gold_admission
+ and gold_admission.admitted
+ and tuple(selected.token_ids) == gold_ids
+ )
+ accepted = bool(selected.finished and selected.token_ids and not reasons)
+ telemetry = LegalIRConstraintRejectionTelemetry(
+ family=family_name,
+ rejection_reasons=reasons,
+ masked_token_count=max(0, frozen.vocabulary_size - settings.beam_width),
+ parser_pruned_count=parser_pruned,
+ proof_state_pruned_count=proof_pruned,
+ prover_calls=0,
+ prover_calls_avoided=0 if accepted else 1,
+ beam_width=settings.beam_width,
+ fallback=settings.fallback,
+ fallback_used=fallback_used,
+ bounds=settings.bounds(),
+ gold_path_preserved=gold_preserved,
+ )
+ return LegalIRConstrainedTokenDecode(
+ accepted=accepted,
+ family=family_name,
+ token_ids=selected.token_ids,
+ tokens=tokens,
+ score=selected.score,
+ beam_width=settings.beam_width,
+ steps=steps,
+ expansions=expansions,
+ fallback=settings.fallback,
+ fallback_used=fallback_used,
+ gold_path_preserved=gold_preserved,
+ parser_pruned=parser_pruned,
+ proof_state_pruned=proof_pruned,
+ hypotheses=tuple((finished or beams)[: settings.beam_width]),
+ telemetry=telemetry,
+ )
+
+
+def gate_legal_ir_prover_call(
+ candidate_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ gold_token_ids: Optional[Sequence[int]] = None,
+ tokenizer: Optional["LegalIRFrozenTokenizer"] = None,
+ proof_state: Optional[Mapping[str, Any]] = None,
+ config: Optional[LegalIRConstrainedDecodeConfig] = None,
+ prover: Optional[Callable[..., Any]] = None,
+) -> LegalIRProverAdmission:
+ """Call the prover only after grammar, token, and optional gold checks pass."""
+
+ frozen = tokenizer or LegalIRFrozenTokenizer.canonical()
+ settings = config or LegalIRConstrainedDecodeConfig(family=family)
+ validation = validate_legal_ir_candidate(
+ candidate_ir,
+ family=family,
+ source_text=source_text,
+ )
+ reasons = list(validation.rejection_reason_names)
+ family_name = validation.family or canonical_legal_ir_grammar_family(family)
+ if gold_token_ids is not None or _looks_like_token_ids(candidate_ir):
+ token_ids = (
+ tuple(int(token_id) for token_id in gold_token_ids)
+ if gold_token_ids is not None
+ else tuple(int(token_id) for token_id in candidate_ir)
+ )
+ admission = admit_legal_ir_gold_path(
+ token_ids,
+ family=family_name,
+ tokenizer=frozen,
+ proof_state=proof_state,
+ config=settings,
+ )
+ if not admission.admitted:
+ reasons.extend(admission.rejection_reasons or ("illegal_token_path",))
+ admitted = not reasons
+ proof_result = None
+ prover_calls = 0
+ if admitted and prover is not None:
+ proof_result = prover(candidate_ir)
+ prover_calls = 1
+ telemetry = LegalIRConstraintRejectionTelemetry(
+ family=family_name,
+ rejection_reasons=tuple(dict.fromkeys(reasons)),
+ prover_calls=prover_calls,
+ prover_calls_avoided=0 if admitted else 1,
+ beam_width=settings.beam_width,
+ fallback=settings.fallback,
+ fallback_used="" if admitted else "reject",
+ bounds=settings.bounds(),
+ gold_path_preserved=admitted,
+ )
+ return LegalIRProverAdmission(
+ admitted=admitted,
+ family=family_name,
+ prover_calls=prover_calls,
+ candidate_ir=candidate_ir,
+ rejection_reasons=tuple(dict.fromkeys(reasons)),
+ proof_result=proof_result,
+ telemetry=telemetry,
+ )
+
+
+def compare_constrained_vs_unconstrained_proof_calls(
+ candidates: Sequence[Any],
+ *,
+ family: str = "",
+ source_text: str = "",
+ proof_state: Optional[Mapping[str, Any]] = None,
+ tokenizer: Optional["LegalIRFrozenTokenizer"] = None,
+ config: Optional[LegalIRConstrainedDecodeConfig] = None,
+ prover: Optional[Callable[..., Any]] = None,
+) -> dict[str, Any]:
+ """Compare prover spend with and without the constrained admission gate."""
+
+ unconstrained_calls = 0
+ constrained_calls = 0
+ avoided = 0
+ admissions: list[dict[str, Any]] = []
+ active_prover = prover or (lambda payload: {"accepted": True, "payload": payload})
+ for candidate in candidates:
+ unconstrained_calls += 1
+ admission = gate_legal_ir_prover_call(
+ candidate,
+ family=family,
+ source_text=source_text,
+ tokenizer=tokenizer,
+ proof_state=proof_state,
+ config=config,
+ prover=active_prover,
+ )
+ constrained_calls += admission.prover_calls
+ avoided += admission.telemetry.prover_calls_avoided
+ admissions.append(admission.to_dict())
+ return {
+ "constrained_prover_calls": constrained_calls,
+ "contract": LEGAL_IR_CONSTRAINED_DECODER_INTERFACE,
+ "schema": LEGAL_IR_CONSTRAINED_DECODER_SCHEMA,
+ "unconstrained_prover_calls": unconstrained_calls,
+ "prover_calls_avoided": avoided,
+ "saved_proof_budget": max(0, unconstrained_calls - constrained_calls),
+ "admissions": admissions,
+ }
+
+
+def _parser_phase(
+ prefix_ids: Sequence[int],
+ tokenizer: "LegalIRFrozenTokenizer",
+ *,
+ family: str = "",
+) -> str:
+ if not prefix_ids:
+ return "expect_bos"
+ pieces = []
+ classes = []
+ for token_id in prefix_ids:
+ entry = tokenizer.entry_for_id(int(token_id))
+ pieces.append(entry.piece)
+ classes.append(entry.token_class)
+ if pieces[0] != "":
+ return "invalid"
+ if any(piece == "" for piece in pieces):
+ return "complete"
+ if len(pieces) == 1:
+ return "expect_family"
+ if classes[1] != "family" and pieces[1] != family:
+ return "invalid"
+ if len(pieces) == 2:
+ return "expect_type"
+ if classes[2] != "type":
+ return "invalid"
+ return "body"
+
+
+def _alias_family_piece(family: str, piece: str, token_class: str) -> bool:
+ return token_class == "identifier" and bool(family) and piece == family
+
+
+def _prefix_tail(
+ prefix_ids: Sequence[int],
+ tokenizer: "LegalIRFrozenTokenizer",
+) -> tuple[str, str]:
+ if not prefix_ids:
+ return "", ""
+ entry = tokenizer.entry_for_id(int(prefix_ids[-1]))
+ return entry.piece, entry.token_class
+
+
+def _binder_allowed(phase: str, family: str, last_piece: str, last_class: str) -> bool:
+ if phase != "body":
+ return False
+ if last_piece in _BINDER_VALUE_FIELDS or last_class == "binder":
+ return True
+ return family in {"tdfol", "decompiler"}
+
+
+def _type_allowed(phase: str, family: str, piece: str) -> bool:
+ if phase != "expect_type":
+ return False
+ expected = _family_output_type(family)
+ return bool(expected) and piece == expected
+
+
+def _family_token_allowed(phase: str, family: str, piece: str, last_piece: str) -> bool:
+ if phase == "expect_family":
+ return (not family or family == "unscoped") or piece == family
+ if phase == "body" and last_piece in _FAMILY_VALUE_FIELDS:
+ if last_piece == "target_view":
+ return True
+ return (not family or family == "unscoped") or piece == family
+ return False
+
+
+def _grammar_token_allowed(
+ phase: str,
+ family: str,
+ piece: str,
+ token_class: str,
+ *,
+ last_piece: str,
+ prune_tactics: bool,
+ eos_id: int,
+ bos_id: int,
+ pad_id: int,
+) -> bool:
+ del eos_id, bos_id, pad_id
+ if phase == "expect_bos":
+ return piece == ""
+ if phase == "complete":
+ return token_class == "padding"
+ if phase in {"expect_family", "expect_type", "invalid"}:
+ return False
+ if piece == "":
+ return False
+ if piece == "":
+ return True
+ if token_class == "special":
+ return False
+ if token_class == "padding":
+ return False
+ if token_class == "tactic" and prune_tactics:
+ return False
+ if token_class == "operator":
+ return _operator_allowed(family, piece, last_piece)
+ if token_class == "production":
+ spec_family = next(
+ (
+ spec.family
+ for spec in default_legal_ir_production_specs()
+ if spec.name == piece
+ ),
+ "",
+ )
+ return (not family or family == "unscoped" or spec_family == family) or (
+ family in _CROSS_FAMILY_HOSTS
+ )
+ return token_class in {
+ "special",
+ "identifier",
+ "source",
+ "proof",
+ "tactic",
+ "production",
+ }
+
+
+def _operator_allowed(family: str, piece: str, last_piece: str) -> bool:
+ if family in _CROSS_FAMILY_HOSTS or last_piece in _OPERATOR_VALUE_FIELDS:
+ return True
+ if piece in _SHARED_OPERATORS:
+ return True
+ owned = _FAMILY_OWNED_OPERATORS.get(family, frozenset())
+ if piece in owned:
+ return True
+ for owner, exclusive in _EXCLUSIVE_OPERATORS_BY_FAMILY.items():
+ if piece in exclusive and owner != family:
+ return False
+ return False
+
+
+def _normalize_proof_state(proof_state: Optional[Mapping[str, Any]]) -> dict[str, Any]:
+ if not isinstance(proof_state, Mapping):
+ return {}
+ return dict(proof_state)
+
+
+def _proof_state_closed(proof_state: Mapping[str, Any]) -> bool:
+ status = str(
+ proof_state.get("status")
+ or proof_state.get("state")
+ or proof_state.get("proof_status")
+ or ""
+ ).strip().lower()
+ open_goals = proof_state.get("open_goals", proof_state.get("open_goal_count", 1))
+ try:
+ remaining = int(open_goals)
+ except (TypeError, ValueError):
+ remaining = 1
+ if status in _CLOSED_PROOF_STATUSES and remaining <= 0:
+ return True
+ return bool(proof_state.get("closed")) or bool(proof_state.get("goal_closed"))
+
+
+def _token_id_for_piece(tokenizer: "LegalIRFrozenTokenizer", piece: str) -> int:
+ entry = tokenizer.lookup(str(piece))
+ return -1 if entry is None else int(entry.token_id)
+
+
+def _resolve_gold_token_ids(
+ gold_token_ids: Sequence[int] | None,
+ *,
+ gold_ir: Any,
+ family: str,
+ tokenizer: "LegalIRFrozenTokenizer",
+) -> tuple[int, ...]:
+ if gold_token_ids is not None:
+ return tuple(int(token_id) for token_id in gold_token_ids)
+ if gold_ir is None:
+ return ()
+ encoding = tokenizer.encode_canonical(gold_ir, family=family)
+ return tuple(int(token_id) for token_id in encoding.token_ids)
+
+
+def _looks_like_token_ids(value: Any) -> bool:
+ if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)):
+ return False
+ return bool(value) and all(isinstance(item, int) and not isinstance(item, bool) for item in value)
+
+
+def _gold_rejection_reason(
+ tokenizer: "LegalIRFrozenTokenizer",
+ token_id: int,
+ index: int,
+) -> str:
+ try:
+ entry = tokenizer.entry_for_id(token_id)
+ except UnknownFrozenTokenError:
+ return f"gold_token_outside_freeze:{index}"
+ return f"gold_prefix_illegal:{entry.token_class}:{entry.piece}"
+
+
+def _logits_for_prefix(
+ logits: Any,
+ *,
+ prefix_ids: Sequence[int],
+ step: int,
+ architecture: Any,
+ tokenizer: "LegalIRFrozenTokenizer",
+) -> list[float]:
+ vocab = tokenizer.vocabulary_size
+ if callable(logits):
+ values = logits(tuple(prefix_ids), step)
+ return _coerce_logits(values, vocab)
+ if isinstance(logits, Sequence) and logits and isinstance(logits[0], Sequence):
+ row = logits[min(step, len(logits) - 1)]
+ return _coerce_logits(row, vocab)
+ if isinstance(logits, Sequence) and logits and not isinstance(logits[0], Sequence):
+ return _coerce_logits(logits, vocab)
+ if architecture is not None and hasattr(architecture, "encode_ids"):
+ hidden = architecture.encode_ids(prefix_ids or (tokenizer.bos_id,))
+ weight = architecture.parameters["reconstruction_weight"]
+ bias = architecture.parameters["reconstruction_bias"]
+ return _vec_add(_mat_vec(weight, hidden), bias)
+ return [0.0] * vocab
+
+
+def _coerce_logits(values: Sequence[Any], vocab_size: int) -> list[float]:
+ coerced = [_finite_float(value, default=_MASKED_LOGIT) for value in values]
+ if len(coerced) < vocab_size:
+ coerced.extend([_MASKED_LOGIT] * (vocab_size - len(coerced)))
+ return coerced[:vocab_size]
+
+
+def _rank_allowed_tokens(
+ masked_logits: Sequence[float],
+ *,
+ limit: int,
+) -> tuple[tuple[int, float], ...]:
+ ranked = [
+ (index, float(score))
+ for index, score in enumerate(masked_logits)
+ if float(score) > _MASKED_LOGIT / 2.0
+ ]
+ ranked.sort(key=lambda item: (-item[1], item[0]))
+ return tuple(ranked[: max(0, int(limit))])
+
+
+def _select_decode_result(
+ *,
+ finished: Sequence[LegalIRBeamHypothesis],
+ live: Sequence[LegalIRBeamHypothesis],
+ settings: LegalIRConstrainedDecodeConfig,
+ gold_ids: Sequence[int],
+ gold_admission: LegalIRGoldPathAdmission | None,
+ tokenizer: "LegalIRFrozenTokenizer",
+) -> tuple[LegalIRBeamHypothesis, str, tuple[str, ...]]:
+ if finished:
+ if gold_ids:
+ matching = [item for item in finished if tuple(item.token_ids) == tuple(gold_ids)]
+ if matching:
+ selected = max(
+ matching,
+ key=lambda item: (item.score, -len(item.token_ids), item.token_ids),
+ )
+ return selected, "", ()
+ selected = max(
+ finished,
+ key=lambda item: (item.score, -len(item.token_ids), item.token_ids),
+ )
+ return selected, "", ()
+ if settings.fallback == "gold_if_admitted" and gold_admission and gold_admission.admitted:
+ return (
+ LegalIRBeamHypothesis(
+ token_ids=tuple(gold_ids),
+ score=0.0,
+ finished=True,
+ fallback_used="gold_if_admitted",
+ ),
+ "gold_if_admitted",
+ (),
+ )
+ if settings.fallback == "eos":
+ base = live[0].token_ids if live else (tokenizer.bos_id,)
+ if tokenizer.eos_id in set(base):
+ return (
+ LegalIRBeamHypothesis(token_ids=tuple(base), score=0.0, finished=True),
+ "eos",
+ (),
+ )
+ masks = legal_ir_constraint_masks(
+ base,
+ family=settings.family,
+ tokenizer=tokenizer,
+ config=settings,
+ )
+ if tokenizer.eos_id in set(masks.allowed_token_ids()):
+ return (
+ LegalIRBeamHypothesis(
+ token_ids=(*base, tokenizer.eos_id),
+ score=live[0].score if live else 0.0,
+ finished=True,
+ fallback_used="eos",
+ ),
+ "eos",
+ (),
+ )
+ empty = LegalIRBeamHypothesis(token_ids=(), score=0.0, finished=False)
+ return empty, "reject", ("no_finished_hypothesis",)
+
+
+def default_legal_ir_production_specs() -> tuple[LegalIRProductionSpec, ...]:
+ return (
+ LegalIRProductionSpec(
+ name="emit_deontic_rule",
+ family="deontic",
+ output_type="DeonticRule",
+ required_fields=("modality", "subject", "action"),
+ optional_fields=("condition", "exception", "object", "provenance"),
+ description="obligation, permission, or prohibition over an actor/action",
+ ),
+ LegalIRProductionSpec(
+ name="emit_frame_logic_triples",
+ family="frame_logic",
+ output_type="FrameLogicTriples",
+ required_fields=("subject", "relation", "object"),
+ optional_fields=("frame", "qualifiers", "provenance"),
+ ),
+ LegalIRProductionSpec(
+ name="emit_tdfol_formula",
+ family="tdfol",
+ output_type="TDFOLFormula",
+ required_fields=("predicate", "arguments"),
+ optional_fields=("quantifier", "variables", "connective"),
+ ),
+ LegalIRProductionSpec(
+ name="emit_knowledge_graph",
+ family="knowledge_graphs",
+ output_type="KnowledgeGraph",
+ required_fields=("nodes", "edges"),
+ optional_fields=("labels", "properties"),
+ ),
+ LegalIRProductionSpec(
+ name="emit_cec_counterexample",
+ family="cec",
+ output_type="CounterexampleContext",
+ required_fields=("events", "counterexamples"),
+ optional_fields=("constraints", "contexts"),
+ ),
+ LegalIRProductionSpec(
+ name="emit_external_prover_plan",
+ family="external_provers",
+ output_type="ExternalProverPlan",
+ required_fields=("backend", "obligations"),
+ optional_fields=("theory", "timeout", "route"),
+ ),
+ LegalIRProductionSpec(
+ name="emit_temporal_window",
+ family="temporal",
+ output_type="TemporalWindow",
+ required_fields=("intervals", "relations"),
+ optional_fields=("bounds", "calendar", "timezone"),
+ ),
+ LegalIRProductionSpec(
+ name="emit_provenance_receipt",
+ family="provenance",
+ output_type="ProvenanceReceipt",
+ required_fields=("source_refs", "evidence"),
+ optional_fields=("citations", "span_hashes", "receipts"),
+ ),
+ LegalIRProductionSpec(
+ name="emit_decompiler_plan",
+ family="decompiler",
+ output_type="DecompilerPlan",
+ required_fields=("steps", "target_view"),
+ optional_fields=("round_trip", "source_copy_policy", "surface_template"),
+ ),
+ )
+
+
+def grammar_metrics_from_validation(
+ validation: LegalIRGrammarValidation,
+) -> dict[str, float]:
+ return validation.metrics()
+
+
+def grammar_rejection_reason_names(
+ validation: LegalIRGrammarValidation | ConstrainedLegalIRDecode,
+) -> tuple[str, ...]:
+ if isinstance(validation, ConstrainedLegalIRDecode):
+ validation = validation.validation
+ return validation.rejection_reason_names
+
+
+def _validation(
+ candidate_ir: Any,
+ family: str,
+ rejections: Sequence[LegalIRGrammarRejection],
+ production: str,
+) -> LegalIRGrammarValidation:
+ deduped = tuple(_dedupe_rejections(rejections))
+ return LegalIRGrammarValidation(
+ accepted=not deduped,
+ family=family,
+ candidate_ir=candidate_ir,
+ rejection_reasons=deduped,
+ selected_productions=(production,) if production and not deduped else (),
+ masked_productions=(production,) if production and deduped else (),
+ )
+
+
+def _dedupe_rejections(
+ rejections: Sequence[LegalIRGrammarRejection],
+) -> tuple[LegalIRGrammarRejection, ...]:
+ seen: set[tuple[str, str, str, str]] = set()
+ deduped: list[LegalIRGrammarRejection] = []
+ for rejection in rejections:
+ key = (
+ rejection.reason,
+ rejection.path,
+ rejection.family,
+ rejection.production,
+ )
+ if key in seen:
+ continue
+ seen.add(key)
+ deduped.append(rejection)
+ return tuple(deduped)
+
+
+def _family_rejection(
+ reason: str,
+ *,
+ family: str,
+ path: str = "$",
+ production: str = "",
+ detail: str = "",
+) -> LegalIRGrammarRejection:
+ return LegalIRGrammarRejection(
+ reason=reason,
+ path=path,
+ family=family,
+ production=production,
+ detail=detail,
+ )
+
+
+def _validate_deontic(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ rules = _items_from(source, "obligations", "deontic_rules", "rules", "clauses")
+ if not rules:
+ return (_family_rejection("missing_deontic_rule", family=family, production=production),)
+ rejections: list[LegalIRGrammarRejection] = []
+ allowed_modalities = {"obligation", "permission", "prohibition", "duty", "right"}
+ for index, rule in enumerate(rules):
+ entry = _object_to_mapping(rule)
+ modality = str(entry.get("modality") or entry.get("operator") or "").lower()
+ if modality not in allowed_modalities:
+ rejections.append(
+ _family_rejection(
+ "invalid_deontic_modality",
+ family=family,
+ path=f"$.rules[{index}].modality",
+ production=production,
+ detail=modality,
+ )
+ )
+ for key in ("subject", "action"):
+ if not _nonempty_text(entry.get(key)):
+ rejections.append(
+ _family_rejection(
+ f"missing_deontic_{key}",
+ family=family,
+ path=f"$.rules[{index}].{key}",
+ production=production,
+ )
+ )
+ return tuple(rejections)
+
+
+def _validate_frame_logic(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ triples = _items_from(source, "triples", "frame_logic", "relations")
+ if not triples and isinstance(source.get("frames"), Sequence):
+ triples = [
+ relation
+ for frame in _sequence(source.get("frames"))
+ for relation in _items_from(_object_to_mapping(frame), "triples", "relations")
+ ]
+ if not triples:
+ return (
+ _family_rejection("missing_frame_logic_triple", family=family, production=production),
+ )
+ return tuple(
+ rejection
+ for index, triple in enumerate(triples)
+ for rejection in _required_mapping_fields(
+ triple,
+ ("subject", "relation", "object"),
+ family=family,
+ path=f"$.triples[{index}]",
+ production=production,
+ reason_prefix="missing_frame_logic",
+ )
+ )
+
+
+def _validate_tdfol(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ formulas = _items_from(source, "formulas", "rules", "clauses")
+ if not formulas and ("predicate" in source or "formula" in source):
+ formulas = [source]
+ if not formulas:
+ return (_family_rejection("missing_tdfol_formula", family=family, production=production),)
+ rejections: list[LegalIRGrammarRejection] = []
+ for index, formula in enumerate(formulas):
+ entry = _object_to_mapping(formula)
+ predicate = str(entry.get("predicate") or entry.get("name") or "").strip()
+ if not _IDENT_RE.match(predicate):
+ rejections.append(
+ _family_rejection(
+ "invalid_tdfol_predicate",
+ family=family,
+ path=f"$.formulas[{index}].predicate",
+ production=production,
+ detail=predicate,
+ )
+ )
+ arguments = entry.get("arguments", entry.get("args"))
+ if not _sequence(arguments):
+ rejections.append(
+ _family_rejection(
+ "missing_tdfol_arguments",
+ family=family,
+ path=f"$.formulas[{index}].arguments",
+ production=production,
+ )
+ )
+ quantifier = str(entry.get("quantifier") or "").strip().lower()
+ if quantifier and quantifier not in {"forall", "exists", "none"}:
+ rejections.append(
+ _family_rejection(
+ "invalid_tdfol_quantifier",
+ family=family,
+ path=f"$.formulas[{index}].quantifier",
+ production=production,
+ detail=quantifier,
+ )
+ )
+ return tuple(rejections)
+
+
+def _validate_kg(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ graph = _object_to_mapping(source.get("graph")) if "graph" in source else source
+ nodes = _sequence(graph.get("nodes"))
+ edges = _sequence(graph.get("edges"))
+ rejections: list[LegalIRGrammarRejection] = []
+ if not nodes:
+ rejections.append(
+ _family_rejection("missing_kg_nodes", family=family, production=production)
+ )
+ if not edges:
+ rejections.append(
+ _family_rejection("missing_kg_edges", family=family, production=production)
+ )
+ node_ids = {
+ str(_object_to_mapping(node).get("id") or "").strip()
+ for node in nodes
+ if str(_object_to_mapping(node).get("id") or "").strip()
+ }
+ for index, node in enumerate(nodes):
+ rejections.extend(
+ _required_mapping_fields(
+ node,
+ ("id", "label"),
+ family=family,
+ path=f"$.nodes[{index}]",
+ production=production,
+ reason_prefix="missing_kg_node",
+ )
+ )
+ for index, edge in enumerate(edges):
+ entry = _object_to_mapping(edge)
+ rejections.extend(
+ _required_mapping_fields(
+ entry,
+ ("source", "target", "label"),
+ family=family,
+ path=f"$.edges[{index}]",
+ production=production,
+ reason_prefix="missing_kg_edge",
+ )
+ )
+ for endpoint in ("source", "target"):
+ value = str(entry.get(endpoint) or "").strip()
+ if value and node_ids and value not in node_ids:
+ rejections.append(
+ _family_rejection(
+ "kg_edge_endpoint_unbound",
+ family=family,
+ path=f"$.edges[{index}].{endpoint}",
+ production=production,
+ detail=value,
+ )
+ )
+ return tuple(rejections)
+
+
+def _validate_cec(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ events = _items_from(source, "events", "event_trace")
+ counterexamples = _items_from(source, "counterexamples", "counterexample")
+ rejections: list[LegalIRGrammarRejection] = []
+ if not events:
+ rejections.append(
+ _family_rejection("missing_cec_events", family=family, production=production)
+ )
+ if not counterexamples:
+ rejections.append(
+ _family_rejection("missing_cec_counterexample", family=family, production=production)
+ )
+ for index, event in enumerate(events):
+ rejections.extend(
+ _required_mapping_fields(
+ event,
+ ("id", "type"),
+ family=family,
+ path=f"$.events[{index}]",
+ production=production,
+ reason_prefix="missing_cec_event",
+ )
+ )
+ return tuple(rejections)
+
+
+def _validate_external_provers(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ backend = str(source.get("backend") or source.get("prover") or "").strip()
+ obligations = _items_from(source, "obligations", "proof_obligations", "goals")
+ rejections: list[LegalIRGrammarRejection] = []
+ if not backend:
+ rejections.append(
+ _family_rejection(
+ "missing_external_prover_backend", family=family, production=production
+ )
+ )
+ if not obligations:
+ rejections.append(
+ _family_rejection(
+ "missing_external_prover_obligation", family=family, production=production
+ )
+ )
+ return tuple(rejections)
+
+
+def _validate_temporal(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ intervals = _items_from(source, "intervals", "temporal_windows", "windows")
+ relations = _items_from(source, "relations", "temporal_relations")
+ rejections: list[LegalIRGrammarRejection] = []
+ if not intervals:
+ rejections.append(
+ _family_rejection("missing_temporal_interval", family=family, production=production)
+ )
+ if not relations:
+ rejections.append(
+ _family_rejection("missing_temporal_relation", family=family, production=production)
+ )
+ for index, interval in enumerate(intervals):
+ entry = _object_to_mapping(interval)
+ if not any(
+ _nonempty_text(entry.get(key))
+ for key in ("start", "end", "duration", "date", "deadline")
+ ):
+ rejections.append(
+ _family_rejection(
+ "missing_temporal_bound",
+ family=family,
+ path=f"$.intervals[{index}]",
+ production=production,
+ )
+ )
+ return tuple(rejections)
+
+
+def _validate_provenance(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ refs = _items_from(source, "source_refs", "citations", "references")
+ evidence = _items_from(source, "evidence", "receipts", "proof_evidence")
+ rejections: list[LegalIRGrammarRejection] = []
+ if not refs:
+ rejections.append(
+ _family_rejection("missing_provenance_source_ref", family=family, production=production)
+ )
+ if not evidence:
+ rejections.append(
+ _family_rejection("missing_provenance_evidence", family=family, production=production)
+ )
+ for index, ref in enumerate(refs):
+ entry = _object_to_mapping(ref)
+ if not any(
+ _nonempty_text(entry.get(key))
+ for key in ("citation", "document_id", "span_hash", "source_hash")
+ ):
+ rejections.append(
+ _family_rejection(
+ "missing_provenance_reference_identifier",
+ family=family,
+ path=f"$.source_refs[{index}]",
+ production=production,
+ )
+ )
+ return tuple(rejections)
+
+
+def _validate_decompiler(
+ candidate: Any,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(candidate)
+ plan = (
+ _object_to_mapping(source.get("plan"))
+ if isinstance(source.get("plan"), Mapping)
+ else source
+ )
+ steps = _items_from(plan, "steps", "operations")
+ target_view = str(plan.get("target_view") or plan.get("legal_ir_view") or "").strip()
+ rejections: list[LegalIRGrammarRejection] = []
+ if not steps:
+ rejections.append(
+ _family_rejection("missing_decompiler_steps", family=family, production=production)
+ )
+ if not target_view:
+ rejections.append(
+ _family_rejection(
+ "missing_decompiler_target_view", family=family, production=production
+ )
+ )
+ policy = str(plan.get("source_copy_policy") or "").strip().lower()
+ if policy and policy not in {"hash_only", "span_hash_only", "citation_only", "no_source_text"}:
+ rejections.append(
+ _family_rejection(
+ "unsafe_decompiler_source_copy_policy",
+ family=family,
+ path="$.source_copy_policy",
+ production=production,
+ detail=policy,
+ )
+ )
+ for index, step in enumerate(steps):
+ entry = _object_to_mapping(step)
+ if not _nonempty_text(entry.get("op", entry.get("operation"))):
+ rejections.append(
+ _family_rejection(
+ "missing_decompiler_step_operation",
+ family=family,
+ path=f"$.steps[{index}].op",
+ production=production,
+ )
+ )
+ return tuple(rejections)
+
+
+_FAMILY_VALIDATORS = {
+ "deontic": _validate_deontic,
+ "frame_logic": _validate_frame_logic,
+ "tdfol": _validate_tdfol,
+ "knowledge_graphs": _validate_kg,
+ "cec": _validate_cec,
+ "external_provers": _validate_external_provers,
+ "temporal": _validate_temporal,
+ "provenance": _validate_provenance,
+ "decompiler": _validate_decompiler,
+}
+
+
+def _required_mapping_fields(
+ value: Any,
+ fields: Sequence[str],
+ *,
+ family: str,
+ path: str,
+ production: str,
+ reason_prefix: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source = _object_to_mapping(value)
+ return tuple(
+ _family_rejection(
+ f"{reason_prefix}_{field}",
+ family=family,
+ path=f"{path}.{field}",
+ production=production,
+ )
+ for field in fields
+ if not _nonempty_text(source.get(field))
+ )
+
+
+def _source_copy_rejections(
+ candidate: Any,
+ *,
+ source_text: str,
+ family: str,
+ production: str,
+) -> tuple[LegalIRGrammarRejection, ...]:
+ source_norm = _normalize_text(source_text)
+ rejections: list[LegalIRGrammarRejection] = []
+
+ def visit(value: Any, path: str) -> None:
+ if isinstance(value, Mapping):
+ for key, child in value.items():
+ key_text = str(key)
+ child_path = f"{path}.{key_text}" if path else key_text
+ if _SOURCE_TEXT_FIELD_RE.search(key_text):
+ rejections.append(
+ _family_rejection(
+ "raw_source_copy_field",
+ family=family,
+ path=child_path,
+ production=production,
+ detail=key_text,
+ )
+ )
+ visit(child, child_path)
+ return
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
+ for index, child in enumerate(value):
+ visit(child, f"{path}[{index}]")
+ return
+ if not isinstance(value, str):
+ return
+ text = value.strip()
+ if not text:
+ return
+ if _PLACEHOLDER_RE.search(text):
+ rejections.append(
+ _family_rejection(
+ "source_copy_placeholder",
+ family=family,
+ path=path or "$",
+ production=production,
+ detail=text[:80],
+ )
+ )
+ return
+ if source_norm and len(_normalize_text(text)) >= 48:
+ text_norm = _normalize_text(text)
+ if text_norm == source_norm or text_norm in source_norm:
+ rejections.append(
+ _family_rejection(
+ "source_copy_placeholder",
+ family=family,
+ path=path or "$",
+ production=production,
+ detail="candidate copies source text",
+ )
+ )
+
+ visit(candidate, "$")
+ return tuple(rejections)
+
+
+def _production_rows(
+ scored_productions: Mapping[str, Any] | Sequence[Any],
+ *,
+ context: Optional[Mapping[str, Any]],
+) -> tuple[dict[str, Any], ...]:
+ payloads = {}
+ if isinstance(context, Mapping):
+ raw_payloads = context.get("productions") or context.get("outputs") or {}
+ if isinstance(raw_payloads, Mapping):
+ payloads = dict(raw_payloads)
+ rows: list[dict[str, Any]] = []
+ if isinstance(scored_productions, Mapping):
+ for name, value in scored_productions.items():
+ row = _row_from_value(str(name), value, payloads.get(name))
+ rows.append(row)
+ else:
+ for index, value in enumerate(_sequence(scored_productions)):
+ rows.append(_row_from_value(f"production_{index}", value, None))
+ return tuple(rows)
+
+
+def _row_from_value(name: str, value: Any, context_output: Any) -> dict[str, Any]:
+ source = _object_to_mapping(value)
+ if source:
+ row_name = str(source.get("name") or source.get("production") or name)
+ score = _finite_float(source.get("score", source.get("logit", 0.0)))
+ output = (
+ source.get("output")
+ if "output" in source
+ else source.get("candidate_ir")
+ if "candidate_ir" in source
+ else source.get("decoded_ir")
+ if "decoded_ir" in source
+ else context_output
+ )
+ return {
+ "family": source.get("family") or source.get("legal_ir_family") or "",
+ "name": row_name,
+ "output": output,
+ "score": score,
+ }
+ return {
+ "family": "",
+ "name": name,
+ "output": context_output,
+ "score": _finite_float(value),
+ }
+
+
+def _mapping_or_sequence(value: Any) -> Any:
+ if isinstance(value, Mapping):
+ return value
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
+ return value
+ source = _object_to_mapping(value)
+ return source or None
+
+
+def _object_to_mapping(value: Any) -> dict[str, Any]:
+ if isinstance(value, Mapping):
+ return dict(value)
+ if value is None or isinstance(value, (str, bytes, bytearray, int, float, bool)):
+ return {}
+ to_dict = getattr(value, "to_dict", None)
+ if callable(to_dict):
+ try:
+ mapped = to_dict()
+ except TypeError:
+ mapped = None
+ if isinstance(mapped, Mapping):
+ return dict(mapped)
+ slots = getattr(value, "__slots__", ())
+ if isinstance(slots, str):
+ slots = (slots,)
+ names = set(getattr(value, "__dict__", {}) or {})
+ names.update(str(name) for name in slots if str(name) != "__weakref__")
+ return {
+ name: getattr(value, name)
+ for name in sorted(names)
+ if hasattr(value, name) and not name.startswith("_")
+ }
+
+
+def _items_from(source: Mapping[str, Any], *keys: str) -> tuple[Any, ...]:
+ for key in keys:
+ if key not in source:
+ continue
+ value = source.get(key)
+ if isinstance(value, Mapping):
+ return (value,)
+ items = _sequence(value)
+ if items:
+ return items
+ return ()
+
+
+def _sequence(value: Any) -> tuple[Any, ...]:
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
+ return tuple(value)
+ if value is None:
+ return ()
+ return ()
+
+
+def _nonempty_text(value: Any) -> bool:
+ if isinstance(value, str):
+ return bool(value.strip()) and not _PLACEHOLDER_RE.search(value)
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return math.isfinite(float(value))
+ return value is not None
+
+
+def _finite_float(value: Any, default: float = 0.0) -> float:
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ return default
+ return number if math.isfinite(number) else default
+
+
+def _metric_slug(value: str) -> str:
+ return re.sub(r"[^a-z0-9]+", "_", str(value).lower()).strip("_") or "unknown"
+
+
+def _normalize_text(value: Any) -> str:
+ return re.sub(r"\s+", " ", str(value or "").strip().lower())
+
+
+def _stable_digest(value: Any) -> str:
+ return hashlib.sha256(repr(value).encode("utf-8", "replace")).hexdigest()
+
+
+def _canonical_json_bytes(value: Any) -> bytes:
+ return json.dumps(
+ value,
+ allow_nan=False,
+ ensure_ascii=True,
+ separators=(",", ":"),
+ sort_keys=True,
+ ).encode("utf-8")
+
+
+def _content_sha256(value: Any) -> str:
+ return hashlib.sha256(_canonical_json_bytes(value)).hexdigest()
+
+
+def _content_cid(value: Any) -> str:
+ return f"sha256:{_content_sha256(value)}"
+
+
+class FrozenVocabularyMutationError(ValueError):
+ """Raised when a caller attempts to mutate a frozen tokenizer vocabulary."""
+
+
+class UnknownFrozenTokenError(ValueError):
+ """Raised when a closed-class token is absent from the frozen vocabulary."""
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRVocabEntry:
+ """One frozen vocabulary row with an immutable token class."""
+
+ token_id: int
+ piece: str
+ token_class: str
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "piece": self.piece,
+ "token_class": self.token_class,
+ "token_id": int(self.token_id),
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRToken:
+ """One encoded token, including class and surface/canonical origin."""
+
+ token_id: int
+ piece: str
+ token_class: str
+ surface: str = "canonical"
+ source_hash: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "piece": self.piece,
+ "source_hash": self.source_hash,
+ "surface": self.surface,
+ "token_class": self.token_class,
+ "token_id": int(self.token_id),
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LegalIRTokenization:
+ """Deterministic encoding of one structured or source-surface payload."""
+
+ token_ids: tuple[int, ...]
+ tokens: tuple[LegalIRToken, ...]
+ token_class_counts: Mapping[str, int]
+ vocabulary_cid: str
+ vocabulary_sha256: str
+ source_surface_separated: bool
+ source_surface_token_count: int
+ canonical_token_count: int
+ accepted: bool = True
+ family: str = ""
+ schema_version: str = LEGAL_IR_FROZEN_TOKENIZER_SCHEMA_VERSION
+
+ def token_class_histogram(self) -> dict[str, int]:
+ return {
+ name: int(self.token_class_counts.get(name, 0)) for name in LEGAL_IR_TOKEN_CLASSES
+ }
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "accepted": self.accepted,
+ "canonical_token_count": int(self.canonical_token_count),
+ "family": self.family,
+ "schema_version": self.schema_version,
+ "source_surface_separated": self.source_surface_separated,
+ "source_surface_token_count": int(self.source_surface_token_count),
+ "token_class_counts": self.token_class_histogram(),
+ "token_ids": [int(token_id) for token_id in self.token_ids],
+ "tokens": [token.to_dict() for token in self.tokens],
+ "vocabulary_cid": self.vocabulary_cid,
+ "vocabulary_sha256": self.vocabulary_sha256,
+ }
+
+
+class LegalIRFrozenTokenizer:
+ """Canonical, fail-closed tokenizer with a frozen structured vocabulary.
+
+ Source-surface text is encoded on a separate path and never mutates the
+ canonical vocabulary. Closed-class unknowns fail closed. Open identifiers
+ hash into a fixed bucket table that is part of the freeze.
+ """
+
+ def __init__(
+ self,
+ *,
+ entries: Optional[Sequence[LegalIRVocabEntry]] = None,
+ frozen: bool = True,
+ ) -> None:
+ using_canonical_default = entries is None
+ resolved = tuple(entries or default_legal_ir_frozen_vocabulary())
+ self._entries = resolved
+ self._piece_to_entry = {entry.piece: entry for entry in resolved}
+ self._id_to_entry = {entry.token_id: entry for entry in resolved}
+ if len(self._piece_to_entry) != len(resolved):
+ raise ValueError("frozen vocabulary pieces must be unique")
+ if list(entry.token_id for entry in resolved) != list(range(len(resolved))):
+ raise ValueError("frozen vocabulary token ids must be contiguous from 0")
+ self._frozen = bool(frozen)
+ vocabulary_payload = self.vocabulary_manifest()
+ self._vocabulary_sha256 = _content_sha256(vocabulary_payload)
+ self._vocabulary_cid = _content_cid(vocabulary_payload)
+ if using_canonical_default:
+ if self._vocabulary_cid != LEGAL_IR_CANONICAL_VOCABULARY_CID:
+ raise ValueError(
+ "canonical frozen vocabulary CID drifted from the sealed digest"
+ )
+ if len(resolved) != LEGAL_IR_CANONICAL_VOCABULARY_SIZE:
+ raise ValueError(
+ "canonical frozen vocabulary size drifted from the sealed size"
+ )
+
+ @classmethod
+ def canonical(cls) -> "LegalIRFrozenTokenizer":
+ return cls()
+
+ @property
+ def frozen(self) -> bool:
+ return self._frozen
+
+ @property
+ def vocabulary_size(self) -> int:
+ return len(self._entries)
+
+ @property
+ def vocabulary_cid(self) -> str:
+ return self._vocabulary_cid
+
+ @property
+ def vocabulary_sha256(self) -> str:
+ return f"sha256:{self._vocabulary_sha256}"
+
+ @property
+ def pad_id(self) -> int:
+ return self._piece_to_entry[""].token_id
+
+ @property
+ def bos_id(self) -> int:
+ return self._piece_to_entry[""].token_id
+
+ @property
+ def eos_id(self) -> int:
+ return self._piece_to_entry[""].token_id
+
+ @property
+ def unk_id(self) -> int:
+ return self._piece_to_entry[""].token_id
+
+ @property
+ def source_ref_id(self) -> int:
+ return self._piece_to_entry[""].token_id
+
+ def freeze(self) -> "LegalIRFrozenTokenizer":
+ if self._frozen:
+ return self
+ return LegalIRFrozenTokenizer(entries=self._entries, frozen=True)
+
+ def lookup(self, piece: str) -> Optional[LegalIRVocabEntry]:
+ return self._piece_to_entry.get(str(piece))
+
+ def entry_for_id(self, token_id: int) -> LegalIRVocabEntry:
+ try:
+ return self._id_to_entry[int(token_id)]
+ except KeyError as exc:
+ raise UnknownFrozenTokenError(f"token id {token_id} is outside the freeze") from exc
+
+ def require(self, piece: str, *, token_class: str = "") -> LegalIRVocabEntry:
+ entry = self.lookup(piece)
+ if entry is None:
+ raise UnknownFrozenTokenError(
+ f"closed-class token {piece!r} is absent from the frozen vocabulary"
+ )
+ if token_class and entry.token_class != token_class:
+ raise UnknownFrozenTokenError(
+ f"token {piece!r} has class {entry.token_class!r}, expected {token_class!r}"
+ )
+ return entry
+
+ def add_token(self, piece: str, token_class: str) -> None:
+ raise FrozenVocabularyMutationError(
+ "frozen tokenizer vocabulary cannot be mutated; supersede with a new CID"
+ )
+
+ def encode_canonical(
+ self,
+ candidate_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ accepted: bool = True,
+ max_length: int = 64,
+ ) -> LegalIRTokenization:
+ if not self._frozen:
+ raise FrozenVocabularyMutationError("canonical encoding requires a frozen vocabulary")
+ family_name = infer_legal_ir_grammar_family(candidate_ir, family=family)
+ tokens: list[LegalIRToken] = [self._special_token("")]
+ if family_name and family_name != "unscoped":
+ tokens.append(self._closed_token(family_name, token_class="family"))
+ type_piece = _family_output_type(family_name)
+ if type_piece:
+ tokens.append(self._closed_token(type_piece, token_class="type"))
+ tokens.extend(self._walk_structured(candidate_ir, family=family_name))
+ tokens.append(self._special_token(""))
+ if len(tokens) > max_length:
+ tokens = [*tokens[: max_length - 1], self._special_token("")]
+ return self._finalize_tokenization(
+ tokens,
+ family=family_name,
+ accepted=accepted,
+ source_text=source_text,
+ )
+
+ def encode_source_surface(
+ self,
+ source_text: str,
+ *,
+ family: str = "",
+ max_length: int = 32,
+ ) -> LegalIRTokenization:
+ """Encode raw source without touching the canonical vocabulary."""
+
+ normalized = _normalize_text(source_text)
+ tokens: list[LegalIRToken] = [self._special_token("")]
+ tokens.append(self._special_token(""))
+ if normalized:
+ digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()
+ for index, chunk in enumerate(_chunks(digest, 8)[: max(0, max_length - 3)]):
+ tokens.append(
+ LegalIRToken(
+ token_id=self.source_ref_id,
+ piece="",
+ token_class="source_surface",
+ surface="source",
+ source_hash=f"{index:02d}:{chunk}",
+ )
+ )
+ tokens.append(self._special_token(""))
+ return self._finalize_tokenization(
+ tokens,
+ family=canonical_legal_ir_grammar_family(family),
+ accepted=True,
+ source_text=source_text,
+ source_surface_only=True,
+ )
+
+ def encode_pair(
+ self,
+ candidate_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ ) -> dict[str, LegalIRTokenization]:
+ """Return separately addressed canonical and source-surface encodings."""
+
+ return {
+ "canonical": self.encode_canonical(
+ candidate_ir,
+ family=family,
+ source_text=source_text,
+ ),
+ "source_surface": self.encode_source_surface(
+ source_text,
+ family=family,
+ ),
+ }
+
+ def pad_ids(self, token_ids: Sequence[int], *, max_length: int) -> list[int]:
+ bounded = [int(token_id) for token_id in token_ids[: max(0, int(max_length))]]
+ if len(bounded) < max_length:
+ bounded.extend([self.pad_id] * (int(max_length) - len(bounded)))
+ return bounded
+
+ def decode_ids(self, token_ids: Sequence[int]) -> tuple[str, ...]:
+ return tuple(self.entry_for_id(token_id).piece for token_id in token_ids)
+
+ def token_class_for_id(self, token_id: int) -> str:
+ return self.entry_for_id(token_id).token_class
+
+ def vocabulary_manifest(self) -> dict[str, Any]:
+ return {
+ "identifier_bucket_count": LEGAL_IR_IDENTIFIER_BUCKET_COUNT,
+ "interface": LEGAL_IR_FROZEN_TOKENIZER_INTERFACE,
+ "mutation_policy": "supersede_never_overwrite",
+ "schema": LEGAL_IR_FROZEN_VOCABULARY_SCHEMA,
+ "schema_version": LEGAL_IR_FROZEN_TOKENIZER_SCHEMA_VERSION,
+ "token_classes": list(LEGAL_IR_TOKEN_CLASSES),
+ "tokens": [entry.to_dict() for entry in self._entries],
+ "unknown_token_behavior": "fail_closed",
+ "vocabulary_size": len(self._entries),
+ }
+
+ def to_dict(self) -> dict[str, Any]:
+ manifest = self.vocabulary_manifest()
+ manifest["frozen"] = self._frozen
+ manifest["vocabulary_cid"] = self.vocabulary_cid
+ manifest["vocabulary_sha256"] = self.vocabulary_sha256
+ return manifest
+
+ @classmethod
+ def from_dict(cls, payload: Mapping[str, Any]) -> "LegalIRFrozenTokenizer":
+ tokens = payload.get("tokens")
+ if not isinstance(tokens, Sequence):
+ raise ValueError("tokenizer payload is missing tokens")
+ entries = []
+ for index, row in enumerate(tokens):
+ if not isinstance(row, Mapping):
+ raise ValueError("tokenizer token row must be a mapping")
+ entries.append(
+ LegalIRVocabEntry(
+ token_id=int(row.get("token_id", index)),
+ piece=str(row.get("piece") or ""),
+ token_class=str(row.get("token_class") or ""),
+ )
+ )
+ tokenizer = cls(entries=entries, frozen=bool(payload.get("frozen", True)))
+ expected_cid = str(payload.get("vocabulary_cid") or "")
+ if expected_cid and expected_cid != tokenizer.vocabulary_cid:
+ raise ValueError("tokenizer vocabulary CID does not match payload")
+ return tokenizer
+
+ def _special_token(self, piece: str) -> LegalIRToken:
+ entry = self.require(piece)
+ return LegalIRToken(
+ token_id=entry.token_id,
+ piece=entry.piece,
+ token_class=entry.token_class,
+ )
+
+ def _closed_token(self, piece: str, *, token_class: str) -> LegalIRToken:
+ entry = self.require(piece, token_class=token_class)
+ return LegalIRToken(
+ token_id=entry.token_id,
+ piece=entry.piece,
+ token_class=entry.token_class,
+ )
+
+ def _identifier_or_source_token(self, value: str, *, field_name: str) -> LegalIRToken:
+ text = str(value or "").strip()
+ if not text:
+ raise UnknownFrozenTokenError(f"empty identifier at {field_name}")
+ if _SOURCE_TEXT_FIELD_RE.match(field_name) or _PLACEHOLDER_RE.search(text):
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
+ return LegalIRToken(
+ token_id=self.source_ref_id,
+ piece="",
+ token_class="source",
+ surface="source",
+ source_hash=digest,
+ )
+ existing = self.lookup(text)
+ if existing is not None:
+ return LegalIRToken(
+ token_id=existing.token_id,
+ piece=existing.piece,
+ token_class=existing.token_class,
+ )
+ if " " in text or len(text) > 32:
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
+ return LegalIRToken(
+ token_id=self.source_ref_id,
+ piece="",
+ token_class="source",
+ surface="source",
+ source_hash=digest,
+ )
+ bucket = int(hashlib.sha256(text.encode("utf-8")).hexdigest(), 16) % (
+ LEGAL_IR_IDENTIFIER_BUCKET_COUNT
+ )
+ piece = f""
+ entry = self.require(piece, token_class="identifier")
+ return LegalIRToken(
+ token_id=entry.token_id,
+ piece=entry.piece,
+ token_class=entry.token_class,
+ source_hash=hashlib.sha256(text.encode("utf-8")).hexdigest(),
+ )
+
+ def _walk_structured(
+ self,
+ value: Any,
+ *,
+ family: str,
+ path: str = "$",
+ ) -> list[LegalIRToken]:
+ tokens: list[LegalIRToken] = []
+ if isinstance(value, Mapping):
+ for key in sorted(str(item) for item in value.keys()):
+ field_entry = self.lookup(key)
+ if field_entry is not None and field_entry.token_class in {
+ "identifier",
+ "operator",
+ "production",
+ "type",
+ "family",
+ }:
+ tokens.append(
+ LegalIRToken(
+ token_id=field_entry.token_id,
+ piece=field_entry.piece,
+ token_class=field_entry.token_class,
+ )
+ )
+ tokens.extend(
+ self._walk_structured(
+ value.get(key),
+ family=family,
+ path=f"{path}.{key}",
+ )
+ )
+ return tokens
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
+ for index, item in enumerate(value):
+ tokens.extend(
+ self._walk_structured(
+ item,
+ family=family,
+ path=f"{path}[{index}]",
+ )
+ )
+ return tokens
+ if isinstance(value, bool) or value is None:
+ return tokens
+ if isinstance(value, (int, float)):
+ return tokens
+ text = str(value).strip()
+ if not text:
+ return tokens
+ existing = self.lookup(text)
+ if existing is not None:
+ if existing.token_class in LEGAL_IR_CLOSED_TOKEN_CLASSES or existing.token_class in {
+ "identifier",
+ "source",
+ }:
+ tokens.append(
+ LegalIRToken(
+ token_id=existing.token_id,
+ piece=existing.piece,
+ token_class=existing.token_class,
+ )
+ )
+ return tokens
+ field_name = path.rsplit(".", 1)[-1]
+ if field_name in _CLOSED_VALUE_FIELDS and existing is None:
+ raise UnknownFrozenTokenError(
+ f"closed-class value {text!r} at {path} is absent from the freeze"
+ )
+ tokens.append(self._identifier_or_source_token(text, field_name=field_name))
+ return tokens
+
+ def _finalize_tokenization(
+ self,
+ tokens: Sequence[LegalIRToken],
+ *,
+ family: str,
+ accepted: bool,
+ source_text: str,
+ source_surface_only: bool = False,
+ ) -> LegalIRTokenization:
+ counts = {name: 0 for name in LEGAL_IR_TOKEN_CLASSES}
+ source_surface_count = 0
+ canonical_count = 0
+ for token in tokens:
+ counts[token.token_class] = counts.get(token.token_class, 0) + 1
+ if token.surface == "source" or token.token_class == "source_surface":
+ if not source_surface_only:
+ raise UnknownFrozenTokenError(
+ "source-surface tokens are rejected on the canonical IR path"
+ )
+ source_surface_count += 1
+ else:
+ canonical_count += 1
+ return LegalIRTokenization(
+ token_ids=tuple(token.token_id for token in tokens),
+ tokens=tuple(tokens),
+ token_class_counts=counts,
+ vocabulary_cid=self.vocabulary_cid,
+ vocabulary_sha256=self.vocabulary_sha256,
+ source_surface_separated=True,
+ source_surface_token_count=source_surface_count,
+ canonical_token_count=canonical_count,
+ accepted=accepted,
+ family=family,
+ )
+
+
+def default_legal_ir_frozen_vocabulary() -> tuple[LegalIRVocabEntry, ...]:
+ """Return the sealed canonical vocabulary used by both experiment arms."""
+
+ pieces: list[tuple[str, str]] = [
+ ("", "padding"),
+ ("", "special"),
+ ("", "special"),
+ ("", "special"),
+ ("", "special"),
+ ("", "special"),
+ ("", "source"),
+ ("forall", "binder"),
+ ("exists", "binder"),
+ ("lambda", "binder"),
+ ("let", "binder"),
+ ("bind", "binder"),
+ ("obligation", "operator"),
+ ("permission", "operator"),
+ ("prohibition", "operator"),
+ ("duty", "operator"),
+ ("right", "operator"),
+ ("and", "operator"),
+ ("or", "operator"),
+ ("not", "operator"),
+ ("implies", "operator"),
+ ("iff", "operator"),
+ ("must", "operator"),
+ ("may", "operator"),
+ ("shall", "operator"),
+ ("must_not", "operator"),
+ ("DeonticRule", "type"),
+ ("FrameLogicTriples", "type"),
+ ("TDFOLFormula", "type"),
+ ("KnowledgeGraph", "type"),
+ ("CounterexampleContext", "type"),
+ ("ExternalProverPlan", "type"),
+ ("TemporalWindow", "type"),
+ ("ProvenanceReceipt", "type"),
+ ("DecompilerPlan", "type"),
+ ("proved", "proof"),
+ ("disproved", "proof"),
+ ("timeout", "proof"),
+ ("unknown", "proof"),
+ ("counterexample", "proof"),
+ ("unchecked", "proof"),
+ ("intro", "tactic"),
+ ("apply", "tactic"),
+ ("simp", "tactic"),
+ ("cases", "tactic"),
+ ("rewrite", "tactic"),
+ ("hammer", "tactic"),
+ ("modality", "identifier"),
+ ("subject", "identifier"),
+ ("action", "identifier"),
+ ("condition", "identifier"),
+ ("exception", "identifier"),
+ ("object", "identifier"),
+ ("provenance", "identifier"),
+ ("relation", "identifier"),
+ ("frame", "identifier"),
+ ("qualifiers", "identifier"),
+ ("predicate", "identifier"),
+ ("arguments", "identifier"),
+ ("quantifier", "identifier"),
+ ("variables", "identifier"),
+ ("connective", "identifier"),
+ ("nodes", "identifier"),
+ ("edges", "identifier"),
+ ("labels", "identifier"),
+ ("properties", "identifier"),
+ ("events", "identifier"),
+ ("counterexamples", "identifier"),
+ ("constraints", "identifier"),
+ ("contexts", "identifier"),
+ ("backend", "identifier"),
+ ("obligations", "identifier"),
+ ("theory", "identifier"),
+ ("timeout", "identifier"),
+ ("route", "identifier"),
+ ("intervals", "identifier"),
+ ("relations", "identifier"),
+ ("bounds", "identifier"),
+ ("calendar", "identifier"),
+ ("timezone", "identifier"),
+ ("source_refs", "identifier"),
+ ("evidence", "identifier"),
+ ("citations", "identifier"),
+ ("span_hashes", "identifier"),
+ ("receipts", "identifier"),
+ ("steps", "identifier"),
+ ("target_view", "identifier"),
+ ("round_trip", "identifier"),
+ ("source_copy_policy", "identifier"),
+ ("surface_template", "identifier"),
+ ("family", "identifier"),
+ ("rules", "identifier"),
+ ("triples", "identifier"),
+ ("formulas", "identifier"),
+ ("hash_only", "identifier"),
+ ]
+ for family in LEGAL_IR_GRAMMAR_FAMILIES:
+ pieces.append((family, "family"))
+ for spec in default_legal_ir_production_specs():
+ pieces.append((spec.name, "production"))
+ for index in range(LEGAL_IR_IDENTIFIER_BUCKET_COUNT):
+ pieces.append((f"", "identifier"))
+
+ seen: set[str] = set()
+ entries: list[LegalIRVocabEntry] = []
+ for piece, token_class in pieces:
+ if piece in seen:
+ continue
+ if token_class not in LEGAL_IR_TOKEN_CLASSES:
+ raise ValueError(f"unknown token class {token_class!r}")
+ seen.add(piece)
+ entries.append(
+ LegalIRVocabEntry(
+ token_id=len(entries),
+ piece=piece,
+ token_class=token_class,
+ )
+ )
+ return tuple(entries)
+
+
+def canonical_legal_ir_frozen_tokenizer() -> LegalIRFrozenTokenizer:
+ """Return the process-local canonical freeze. Vocabulary is immutable."""
+
+ return LegalIRFrozenTokenizer.canonical()
+
+
+def _family_output_type(family: str) -> str:
+ mapping = {
+ spec.family: spec.output_type for spec in default_legal_ir_production_specs()
+ }
+ return mapping.get(family, "")
+
+
+def _chunks(value: str, size: int) -> tuple[str, ...]:
+ return tuple(value[index : index + size] for index in range(0, len(value), size))
+
+
+_CLOSED_VALUE_FIELDS: Final[frozenset[str]] = frozenset(
+ {
+ "family",
+ "modality",
+ "operator",
+ "quantifier",
+ "connective",
+ "backend",
+ }
+)
+
+
+SHARED_LATENT_ARCHITECTURE_ARM = "shared_latent"
+SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM = "shared_encoder_typed_head"
+COMPATIBLE_ARCHITECTURE_ARMS = (
+ SHARED_LATENT_ARCHITECTURE_ARM,
+ SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM,
+)
+COMPATIBLE_ARCHITECTURE_SCHEMA_VERSION = "legal-ir-compatible-architecture-v1"
+COMPATIBLE_ARCHITECTURE_INIT_CHECKPOINT_SCHEMA = "IRCompatibleArchitectureInitCheckpoint@1"
+SHARED_LATENT_ARCHITECTURE_VERSION = "shared_latent_v1"
+SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_VERSION = "shared_encoder_typed_head_v1"
+COMPATIBLE_ARCHITECTURE_DEFAULT_LATENT_DIM = 16
+COMPATIBLE_ARCHITECTURE_DEFAULT_HIDDEN_DIM = 16
+COMPATIBLE_ARCHITECTURE_DEFAULT_MAX_SEQ_LEN = 32
+COMPATIBLE_ARCHITECTURE_OUTPUT_HEADS = (
+ "family",
+ "view",
+ "reconstruction",
+ "uncertainty",
+)
+MODEL_LEGACY_1_IDENTITY = "MODEL-LEGACY-1"
+COMPATIBLE_LEGACY_ARCHITECTURE_VERSIONS = frozenset(
+ {
+ "legacy_dense_v1",
+ "proof_aware_auxiliary_heads_v2",
+ SHARED_LATENT_ARCHITECTURE_VERSION,
+ SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_VERSION,
+ }
+)
+
+
+class IncompatibleLegacyWarmStartError(ValueError):
+ """Raised when MODEL-LEGACY-1 fails compatibility or quarantine."""
+
+
+def evaluate_legacy_warm_start(
+ *,
+ compatibility_passed: bool,
+ quarantine_passed: bool,
+ architecture_version: str = "",
+ legacy_identity: str = MODEL_LEGACY_1_IDENTITY,
+) -> dict[str, Any]:
+ """Admit MODEL-LEGACY-1 only as a non-authoritative warm start."""
+
+ compatible = bool(compatibility_passed)
+ quarantined = bool(quarantine_passed)
+ allowed = compatible and quarantined
+ if architecture_version and architecture_version not in COMPATIBLE_LEGACY_ARCHITECTURE_VERSIONS:
+ allowed = False
+ reason = "architecture version is not in the compatible set"
+ elif not compatible:
+ reason = "legacy compatibility gate failed"
+ elif not quarantined:
+ reason = "legacy quarantine gate failed"
+ else:
+ reason = "warm-start admitted without promotion or semantic authority"
+ return {
+ "allowed": allowed,
+ "architecture_version": architecture_version,
+ "authority": False,
+ "identity": legacy_identity,
+ "promoted": False,
+ "reason": reason,
+ }
+
+
+def require_legacy_warm_start(**kwargs: Any) -> dict[str, Any]:
+ report = evaluate_legacy_warm_start(**kwargs)
+ if not report["allowed"]:
+ raise IncompatibleLegacyWarmStartError(str(report["reason"]))
+ return report
+
+
+def _compatible_architecture_arm_name(value: Optional[str]) -> str:
+ arm = str(value or SHARED_LATENT_ARCHITECTURE_ARM).strip()
+ if arm not in COMPATIBLE_ARCHITECTURE_ARMS:
+ raise ValueError(
+ "architecture arm must be one of " + ", ".join(COMPATIBLE_ARCHITECTURE_ARMS)
+ )
+ return arm
+
+
+def _architecture_version_for_arm(arm: str) -> str:
+ if arm == SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM:
+ return SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_VERSION
+ return SHARED_LATENT_ARCHITECTURE_VERSION
+
+
+def _zeros(size: int) -> list[float]:
+ return [0.0] * int(size)
+
+
+def _seeded_vector(size: int, *, seed: int, salt: str) -> list[float]:
+ digest = hashlib.sha256(f"{int(seed)}:{salt}".encode("utf-8")).digest()
+ values: list[float] = []
+ block = digest
+ while len(values) < size:
+ for index in range(0, len(block), 4):
+ chunk = block[index : index + 4]
+ if len(chunk) < 4 or len(values) >= size:
+ break
+ raw = int.from_bytes(chunk, "big") / 4294967295.0
+ values.append((raw * 2.0 - 1.0) * 0.05)
+ block = hashlib.sha256(block).digest()
+ return values
+
+
+def _seeded_matrix(rows: int, cols: int, *, seed: int, salt: str) -> list[list[float]]:
+ return [
+ _seeded_vector(cols, seed=seed, salt=f"{salt}:{row}")
+ for row in range(int(rows))
+ ]
+
+
+def _vec_add(left: Sequence[float], right: Sequence[float]) -> list[float]:
+ return [float(a) + float(b) for a, b in zip(left, right)]
+
+
+def _vec_sub(left: Sequence[float], right: Sequence[float]) -> list[float]:
+ return [float(a) - float(b) for a, b in zip(left, right)]
+
+
+def _vec_scale(values: Sequence[float], scale: float) -> list[float]:
+ return [float(value) * float(scale) for value in values]
+
+
+def _dot(left: Sequence[float], right: Sequence[float]) -> float:
+ return sum(float(a) * float(b) for a, b in zip(left, right))
+
+
+def _mat_vec(matrix: Sequence[Sequence[float]], vector: Sequence[float]) -> list[float]:
+ return [_dot(row, vector) for row in matrix]
+
+
+def _transpose_mat_vec(
+ matrix: Sequence[Sequence[float]],
+ vector: Sequence[float],
+) -> list[float]:
+ if not matrix:
+ return []
+ width = len(matrix[0])
+ result = [0.0] * width
+ for row_index, row in enumerate(matrix):
+ scale = float(vector[row_index])
+ for col_index, value in enumerate(row):
+ result[col_index] += float(value) * scale
+ return result
+
+
+def _outer(left: Sequence[float], right: Sequence[float]) -> list[list[float]]:
+ return [[float(a) * float(b) for b in right] for a in left]
+
+
+def _matrix_add(
+ left: Sequence[Sequence[float]],
+ right: Sequence[Sequence[float]],
+) -> list[list[float]]:
+ return [_vec_add(a, b) for a, b in zip(left, right)]
+
+
+def _matrix_scale(matrix: Sequence[Sequence[float]], scale: float) -> list[list[float]]:
+ return [_vec_scale(row, scale) for row in matrix]
+
+
+def _softmax_vector(logits: Sequence[float]) -> list[float]:
+ if not logits:
+ return []
+ peak = max(float(value) for value in logits)
+ exps = [math.exp(float(value) - peak) for value in logits]
+ total = sum(exps) or 1.0
+ return [value / total for value in exps]
+
+
+def _sigmoid_scalar(value: float) -> float:
+ clipped = max(-30.0, min(30.0, float(value)))
+ return 1.0 / (1.0 + math.exp(-clipped))
+
+
+def _entropy(probabilities: Sequence[float]) -> float:
+ total = 0.0
+ for probability in probabilities:
+ if probability > 0.0:
+ total -= float(probability) * math.log(float(probability))
+ return total
+
+
+def _l2_norm(values: Sequence[float]) -> float:
+ return math.sqrt(sum(float(value) * float(value) for value in values))
+
+
+def _matrix_l2_norm(matrix: Sequence[Sequence[float]]) -> float:
+ return math.sqrt(
+ sum(float(value) * float(value) for row in matrix for value in row)
+ )
+
+
+def _copy_matrix(matrix: Sequence[Sequence[float]]) -> list[list[float]]:
+ return [list(row) for row in matrix]
+
+
+def _copy_vector(values: Sequence[float]) -> list[float]:
+ return [float(value) for value in values]
+
+
+@dataclass
+class CompatibleArchitectureConfig:
+ """Smallest compatible experiment-arm configuration."""
+
+ arm: str = SHARED_LATENT_ARCHITECTURE_ARM
+ latent_dim: int = COMPATIBLE_ARCHITECTURE_DEFAULT_LATENT_DIM
+ hidden_dim: int = COMPATIBLE_ARCHITECTURE_DEFAULT_HIDDEN_DIM
+ max_seq_len: int = COMPATIBLE_ARCHITECTURE_DEFAULT_MAX_SEQ_LEN
+ seed: int = 0
+ families: tuple[str, ...] = LEGAL_IR_GRAMMAR_FAMILIES
+ views: tuple[str, ...] = (
+ "deontic.ir",
+ "modal.frame_logic",
+ "TDFOL.prover",
+ "knowledge_graphs.neo4j_compat",
+ "CEC.native",
+ "external_provers.router",
+ "temporal.ir",
+ "provenance.ir",
+ "decompiler.plan",
+ )
+
+ def __post_init__(self) -> None:
+ self.arm = _compatible_architecture_arm_name(self.arm)
+ self.latent_dim = max(2, int(self.latent_dim))
+ self.hidden_dim = max(2, int(self.hidden_dim))
+ self.max_seq_len = max(4, int(self.max_seq_len))
+ self.seed = int(self.seed)
+ self.families = tuple(str(item) for item in self.families)
+ self.views = tuple(str(item) for item in self.views)
+
+ @property
+ def representation_dim(self) -> int:
+ if self.arm == SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM:
+ return int(self.hidden_dim)
+ return int(self.latent_dim)
+
+ @property
+ def architecture_version(self) -> str:
+ return _architecture_version_for_arm(self.arm)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "architecture_version": self.architecture_version,
+ "arm": self.arm,
+ "families": list(self.families),
+ "hidden_dim": int(self.hidden_dim),
+ "latent_dim": int(self.latent_dim),
+ "max_seq_len": int(self.max_seq_len),
+ "seed": int(self.seed),
+ "views": list(self.views),
+ }
+
+
+class CompatibleLearnedArchitecture:
+ """Runnable shared-latent or shared-encoder/typed-head experiment arm.
+
+ Neither arm is a promotion winner. Proof labels stay nondifferentiable.
+ The frozen tokenizer is the only vocabulary authority.
+ """
+
+ def __init__(
+ self,
+ *,
+ config: Optional[CompatibleArchitectureConfig] = None,
+ tokenizer: Optional[LegalIRFrozenTokenizer] = None,
+ parameters: Optional[Mapping[str, Any]] = None,
+ ) -> None:
+ self.config = config or CompatibleArchitectureConfig()
+ self.tokenizer = tokenizer or LegalIRFrozenTokenizer.canonical()
+ if not self.tokenizer.frozen:
+ raise FrozenVocabularyMutationError(
+ "compatible architectures require a frozen tokenizer"
+ )
+ self.families = tuple(self.config.families)
+ self.views = tuple(self.config.views)
+ self.vocab_size = int(self.tokenizer.vocabulary_size)
+ self.dim = int(self.config.representation_dim)
+ self.parameters = self._initialize_parameters(parameters)
+
+ def _initialize_parameters(
+ self,
+ parameters: Optional[Mapping[str, Any]],
+ ) -> dict[str, Any]:
+ if parameters:
+ return self._hydrate_parameters(parameters)
+ seed = self.config.seed
+ arm = self.config.arm
+ typed_heads: dict[str, dict[str, Any]] = {}
+ if self.config.arm == SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM:
+ for family in self.families:
+ typed_heads[family] = {
+ "bias": _seeded_vector(
+ len(self.families),
+ seed=seed,
+ salt=f"{arm}:typed:{family}:bias",
+ ),
+ "uncertainty_bias": _seeded_vector(
+ 1,
+ seed=seed,
+ salt=f"{arm}:typed:{family}:uncertainty_bias",
+ )[0],
+ "uncertainty_weight": _seeded_vector(
+ self.dim,
+ seed=seed,
+ salt=f"{arm}:typed:{family}:uncertainty_weight",
+ ),
+ "weight": _seeded_matrix(
+ len(self.families),
+ self.dim,
+ seed=seed,
+ salt=f"{arm}:typed:{family}:weight",
+ ),
+ }
+ return {
+ "embedding": _seeded_matrix(
+ self.vocab_size, self.dim, seed=seed, salt=f"{arm}:embedding"
+ ),
+ "encoder_bias": _seeded_vector(self.dim, seed=seed, salt=f"{arm}:encoder_bias"),
+ "family_bias": _seeded_vector(
+ len(self.families), seed=seed, salt=f"{arm}:family_bias"
+ ),
+ "family_weight": _seeded_matrix(
+ len(self.families), self.dim, seed=seed, salt=f"{arm}:family_weight"
+ ),
+ "reconstruction_bias": _seeded_vector(
+ self.vocab_size, seed=seed, salt=f"{arm}:reconstruction_bias"
+ ),
+ "reconstruction_weight": _seeded_matrix(
+ self.vocab_size,
+ self.dim,
+ seed=seed,
+ salt=f"{arm}:reconstruction_weight",
+ ),
+ "typed_heads": typed_heads,
+ "uncertainty_bias": _seeded_vector(
+ 1, seed=seed, salt=f"{arm}:uncertainty_bias"
+ )[0],
+ "uncertainty_weight": _seeded_vector(
+ self.dim, seed=seed, salt=f"{arm}:uncertainty_weight"
+ ),
+ "view_bias": _seeded_vector(len(self.views), seed=seed, salt=f"{arm}:view_bias"),
+ "view_weight": _seeded_matrix(
+ len(self.views), self.dim, seed=seed, salt=f"{arm}:view_weight"
+ ),
+ }
+
+ def _hydrate_parameters(self, parameters: Mapping[str, Any]) -> dict[str, Any]:
+ typed_heads = {}
+ raw_heads = dict(parameters.get("typed_heads") or {})
+ for family, payload in raw_heads.items():
+ typed_heads[str(family)] = {
+ "bias": [float(value) for value in payload["bias"]],
+ "uncertainty_bias": float(payload["uncertainty_bias"]),
+ "uncertainty_weight": [
+ float(value) for value in payload["uncertainty_weight"]
+ ],
+ "weight": [[float(value) for value in row] for row in payload["weight"]],
+ }
+ return {
+ "embedding": [[float(value) for value in row] for row in parameters["embedding"]],
+ "encoder_bias": [float(value) for value in parameters["encoder_bias"]],
+ "family_bias": [float(value) for value in parameters["family_bias"]],
+ "family_weight": [
+ [float(value) for value in row] for row in parameters["family_weight"]
+ ],
+ "reconstruction_bias": [
+ float(value) for value in parameters["reconstruction_bias"]
+ ],
+ "reconstruction_weight": [
+ [float(value) for value in row]
+ for row in parameters["reconstruction_weight"]
+ ],
+ "typed_heads": typed_heads,
+ "uncertainty_bias": float(parameters["uncertainty_bias"]),
+ "uncertainty_weight": [
+ float(value) for value in parameters["uncertainty_weight"]
+ ],
+ "view_bias": [float(value) for value in parameters["view_bias"]],
+ "view_weight": [
+ [float(value) for value in row] for row in parameters["view_weight"]
+ ],
+ }
+
+ def tokenize(
+ self,
+ structured_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ ) -> LegalIRTokenization:
+ return self.tokenizer.encode_canonical(
+ structured_ir,
+ family=family,
+ source_text=source_text,
+ max_length=self.config.max_seq_len,
+ )
+
+ def encode_ids(self, token_ids: Sequence[int]) -> list[float]:
+ if not token_ids:
+ return list(self.parameters["encoder_bias"])
+ pooled = _zeros(self.dim)
+ count = 0
+ for token_id in token_ids:
+ if int(token_id) == self.tokenizer.pad_id:
+ continue
+ pooled = _vec_add(pooled, self.parameters["embedding"][int(token_id)])
+ count += 1
+ if count:
+ pooled = _vec_scale(pooled, 1.0 / float(count))
+ return _vec_add(pooled, self.parameters["encoder_bias"])
+
+ def _family_index(self, family: str) -> int:
+ resolved = str(family or self.families[0])
+ if resolved in self.families:
+ return self.families.index(resolved)
+ return 0
+
+ def _view_index(self, view: str) -> int:
+ resolved = str(view or self.views[0])
+ if resolved in self.views:
+ return self.views.index(resolved)
+ return 0
+
+ def _conditioning_vector(
+ self,
+ *,
+ family: str,
+ view: str,
+ source_text: str,
+ ) -> list[float]:
+ values = _zeros(self.dim)
+ values[self._family_index(family) % self.dim] += 1.0
+ values[self._view_index(view) % self.dim] += 0.5
+ if source_text:
+ digest = hashlib.sha256(
+ " ".join(str(source_text).split()).encode("utf-8")
+ ).digest()
+ for offset in range(min(8, self.dim)):
+ values[offset] += ((digest[offset] / 255.0) * 2.0 - 1.0) * 0.05
+ return values
+
+ def _select_family_head(self, family: str) -> tuple[list[list[float]], list[float]]:
+ if self.config.arm == SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM:
+ head = self.parameters["typed_heads"][self.families[self._family_index(family)]]
+ return head["weight"], head["bias"]
+ return self.parameters["family_weight"], self.parameters["family_bias"]
+
+ def _select_uncertainty_head(self, family: str) -> tuple[list[float], float]:
+ if self.config.arm == SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM:
+ head = self.parameters["typed_heads"][self.families[self._family_index(family)]]
+ return head["uncertainty_weight"], float(head["uncertainty_bias"])
+ return (
+ self.parameters["uncertainty_weight"],
+ float(self.parameters["uncertainty_bias"]),
+ )
+
+ def forward(
+ self,
+ structured_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ view: str = "",
+ target_family: str = "",
+ proof_label: str = "",
+ ) -> dict[str, Any]:
+ tokenization = self.tokenize(
+ structured_ir,
+ family=family,
+ source_text=source_text,
+ )
+ token_ids = self.tokenizer.pad_ids(
+ tokenization.token_ids,
+ max_length=self.config.max_seq_len,
+ )
+ hidden = self.encode_ids(token_ids)
+ conditioning = self._conditioning_vector(
+ family=tokenization.family or family,
+ view=view or f"{tokenization.family or family}.ir",
+ source_text=source_text,
+ )
+ latent = _vec_add(hidden, conditioning)
+ latent_norm = _l2_norm(latent) or 1.0
+ latent = _vec_scale(latent, 1.0 / latent_norm)
+ family_weight, family_bias = self._select_family_head(tokenization.family or family)
+ family_logits = _vec_add(_mat_vec(family_weight, latent), family_bias)
+ family_probabilities = _softmax_vector(family_logits)
+ view_logits = _vec_add(
+ _mat_vec(self.parameters["view_weight"], latent),
+ self.parameters["view_bias"],
+ )
+ view_probabilities = _softmax_vector(view_logits)
+ reconstruction_logits = _vec_add(
+ _mat_vec(self.parameters["reconstruction_weight"], latent),
+ self.parameters["reconstruction_bias"],
+ )
+ uncertainty_weight, uncertainty_bias = self._select_uncertainty_head(
+ tokenization.family or family
+ )
+ aleatoric = _sigmoid_scalar(_dot(uncertainty_weight, latent) + uncertainty_bias)
+ epistemic = _entropy(family_probabilities)
+ confidence = max(family_probabilities) if family_probabilities else 0.0
+ predicted_family = (
+ self.families[family_probabilities.index(confidence)]
+ if family_probabilities
+ else ""
+ )
+ target = str(target_family or tokenization.family or family or self.families[0])
+ target_index = self._family_index(target)
+ target_one_hot = [0.0] * len(self.families)
+ target_one_hot[target_index] = 1.0
+ loss = -math.log(max(family_probabilities[target_index], 1.0e-12))
+ return {
+ "accepted": tokenization.accepted,
+ "aleatoric_uncertainty": round(float(aleatoric), 12),
+ "architecture_version": self.config.architecture_version,
+ "arm": self.config.arm,
+ "canonical_token_count": tokenization.canonical_token_count,
+ "conditioning": {
+ "family": tokenization.family or family,
+ "proof_label": str(proof_label or ""),
+ "proof_label_differentiable": False,
+ "source_surface_separated": True,
+ "view": view or f"{tokenization.family or family}.ir",
+ },
+ "confidence": round(float(confidence), 12),
+ "epistemic_uncertainty": round(float(epistemic), 12),
+ "family_logits": [round(float(value), 12) for value in family_logits],
+ "family_probabilities": [
+ round(float(value), 12) for value in family_probabilities
+ ],
+ "heads": {
+ "family": {
+ "kind": "categorical",
+ "output_size": len(self.families),
+ "shared": self.config.arm == SHARED_LATENT_ARCHITECTURE_ARM,
+ },
+ "reconstruction": {
+ "kind": "token_softmax",
+ "output_size": self.vocab_size,
+ "shared": True,
+ },
+ "uncertainty": {
+ "kind": "aleatoric_epistemic",
+ "output_size": 2,
+ "shared": self.config.arm == SHARED_LATENT_ARCHITECTURE_ARM,
+ },
+ "view": {
+ "kind": "categorical",
+ "output_size": len(self.views),
+ "shared": True,
+ },
+ },
+ "hidden": [round(float(value), 12) for value in hidden],
+ "latent": [round(float(value), 12) for value in latent],
+ "latent_normalized": True,
+ "loss": round(float(loss), 12),
+ "predicted_family": predicted_family,
+ "reconstruction_logits": [
+ round(float(value), 12) for value in reconstruction_logits
+ ],
+ "schema_version": COMPATIBLE_ARCHITECTURE_SCHEMA_VERSION,
+ "shapes": {
+ "family_logits": [len(self.families)],
+ "latent": [self.dim],
+ "reconstruction_logits": [self.vocab_size],
+ "token_ids": [self.config.max_seq_len],
+ "view_logits": [len(self.views)],
+ },
+ "source_surface_token_count": tokenization.source_surface_token_count,
+ "target_family": target,
+ "target_one_hot": target_one_hot,
+ "token_class_counts": tokenization.token_class_histogram(),
+ "token_ids": token_ids,
+ "tokenization": tokenization.to_dict(),
+ "tokenizer_vocabulary_cid": self.tokenizer.vocabulary_cid,
+ "view_logits": [round(float(value), 12) for value in view_logits],
+ "view_probabilities": [
+ round(float(value), 12) for value in view_probabilities
+ ],
+ "winner": False,
+ }
+
+ def backward(self, forward_result: Mapping[str, Any]) -> dict[str, Any]:
+ latent = [float(value) for value in forward_result["latent"]]
+ probabilities = [float(value) for value in forward_result["family_probabilities"]]
+ target = [float(value) for value in forward_result["target_one_hot"]]
+ family = str(forward_result.get("conditioning", {}).get("family") or "")
+ family_weight, _family_bias = self._select_family_head(family)
+ d_logits = _vec_sub(probabilities, target)
+ d_weight = _outer(d_logits, latent)
+ d_bias = list(d_logits)
+ d_latent = _transpose_mat_vec(family_weight, d_logits)
+ token_ids = [int(value) for value in forward_result["token_ids"]]
+ active = [token_id for token_id in token_ids if token_id != self.tokenizer.pad_id]
+ scale = 1.0 / float(len(active) or 1)
+ d_embedding = [_zeros(self.dim) for _ in range(self.vocab_size)]
+ for token_id in active:
+ d_embedding[token_id] = _vec_add(
+ d_embedding[token_id],
+ _vec_scale(d_latent, scale),
+ )
+ return {
+ "d_embedding_norm": round(_matrix_l2_norm(d_embedding), 12),
+ "d_family_bias": [round(float(value), 12) for value in d_bias],
+ "d_family_weight": [
+ [round(float(value), 12) for value in row] for row in d_weight
+ ],
+ "d_latent": [round(float(value), 12) for value in d_latent],
+ "gradient_norm": round(
+ math.sqrt(
+ _matrix_l2_norm(d_weight) ** 2
+ + _l2_norm(d_bias) ** 2
+ + _l2_norm(d_latent) ** 2
+ ),
+ 12,
+ ),
+ "proof_in_gradient_path": False,
+ }
+
+ def step(
+ self,
+ structured_ir: Any,
+ *,
+ family: str = "",
+ source_text: str = "",
+ target_family: str = "",
+ learning_rate: float = 0.05,
+ ) -> dict[str, Any]:
+ forward_result = self.forward(
+ structured_ir,
+ family=family,
+ source_text=source_text,
+ target_family=target_family,
+ )
+ gradients = self.backward(forward_result)
+ family_name = str(forward_result["conditioning"]["family"] or family)
+ family_weight, family_bias = self._select_family_head(family_name)
+ updated_weight = _matrix_add(
+ family_weight,
+ _matrix_scale(gradients["d_family_weight"], -float(learning_rate)),
+ )
+ updated_bias = _vec_add(
+ family_bias,
+ _vec_scale(gradients["d_family_bias"], -float(learning_rate)),
+ )
+ if self.config.arm == SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM:
+ head = self.parameters["typed_heads"][
+ self.families[self._family_index(family_name)]
+ ]
+ head["weight"] = updated_weight
+ head["bias"] = updated_bias
+ else:
+ self.parameters["family_weight"] = updated_weight
+ self.parameters["family_bias"] = updated_bias
+ updated = self.forward(
+ structured_ir,
+ family=family,
+ source_text=source_text,
+ target_family=target_family,
+ )
+ return {
+ "after": updated,
+ "before": forward_result,
+ "gradients": gradients,
+ "loss_delta": round(float(updated["loss"]) - float(forward_result["loss"]), 12),
+ }
+
+ def parameter_count(self) -> int:
+ count = 0
+ count += self.vocab_size * self.dim
+ count += self.dim
+ count += len(self.families) * self.dim + len(self.families)
+ count += len(self.views) * self.dim + len(self.views)
+ count += self.vocab_size * self.dim + self.vocab_size
+ count += self.dim + 1
+ if self.config.arm == SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM:
+ count += len(self.families) * (
+ len(self.families) * self.dim + len(self.families) + self.dim + 1
+ )
+ return int(count)
+
+ def parameter_resource_estimate(self) -> dict[str, Any]:
+ parameter_count = self.parameter_count()
+ return {
+ "arm": self.config.arm,
+ "bytes_fp32": int(parameter_count * 4),
+ "device": "cpu",
+ "estimated_forward_flops": int(
+ self.config.max_seq_len * self.dim
+ + self.dim * (len(self.families) + len(self.views) + self.vocab_size)
+ ),
+ "gpu_required": False,
+ "hidden_dim": self.config.hidden_dim,
+ "latent_dim": self.config.latent_dim,
+ "max_seq_len": self.config.max_seq_len,
+ "parameter_count": parameter_count,
+ "tokenizer_vocabulary_size": self.vocab_size,
+ }
+
+ def architecture_manifest(self) -> dict[str, Any]:
+ return {
+ "architecture_version": self.config.architecture_version,
+ "arm": self.config.arm,
+ "compatible_with_advisor": True,
+ "config": self.config.to_dict(),
+ "heads": list(COMPATIBLE_ARCHITECTURE_OUTPUT_HEADS),
+ "legacy_promoted": False,
+ "output_heads": {
+ "conditioning": ["family", "view", "source_span_hash"],
+ "family": list(self.families),
+ "uncertainty": ["aleatoric", "epistemic"],
+ "view": list(self.views),
+ },
+ "parameter_resource_estimate": self.parameter_resource_estimate(),
+ "schema_version": COMPATIBLE_ARCHITECTURE_SCHEMA_VERSION,
+ "tokenizer_schema_version": LEGAL_IR_FROZEN_TOKENIZER_SCHEMA_VERSION,
+ "tokenizer_vocabulary_cid": self.tokenizer.vocabulary_cid,
+ "tokenizer_vocabulary_sha256": self.tokenizer.vocabulary_sha256,
+ "winner": False,
+ }
+
+ def initialization_checkpoint(self) -> dict[str, Any]:
+ return {
+ "architecture_manifest": self.architecture_manifest(),
+ "architecture_version": self.config.architecture_version,
+ "arm": self.config.arm,
+ "legacy_promoted": False,
+ "parameters": self.parameters_to_dict(),
+ "schema": COMPATIBLE_ARCHITECTURE_INIT_CHECKPOINT_SCHEMA,
+ "schema_version": COMPATIBLE_ARCHITECTURE_SCHEMA_VERSION,
+ "seed": self.config.seed,
+ "tokenizer_vocabulary_cid": self.tokenizer.vocabulary_cid,
+ "winner": False,
+ }
+
+ def parameters_to_dict(self) -> dict[str, Any]:
+ typed_heads = {
+ family: {
+ "bias": _copy_vector(payload["bias"]),
+ "uncertainty_bias": float(payload["uncertainty_bias"]),
+ "uncertainty_weight": _copy_vector(payload["uncertainty_weight"]),
+ "weight": _copy_matrix(payload["weight"]),
+ }
+ for family, payload in self.parameters["typed_heads"].items()
+ }
+ return {
+ "embedding": _copy_matrix(self.parameters["embedding"]),
+ "encoder_bias": _copy_vector(self.parameters["encoder_bias"]),
+ "family_bias": _copy_vector(self.parameters["family_bias"]),
+ "family_weight": _copy_matrix(self.parameters["family_weight"]),
+ "reconstruction_bias": _copy_vector(self.parameters["reconstruction_bias"]),
+ "reconstruction_weight": _copy_matrix(self.parameters["reconstruction_weight"]),
+ "typed_heads": typed_heads,
+ "uncertainty_bias": float(self.parameters["uncertainty_bias"]),
+ "uncertainty_weight": _copy_vector(self.parameters["uncertainty_weight"]),
+ "view_bias": _copy_vector(self.parameters["view_bias"]),
+ "view_weight": _copy_matrix(self.parameters["view_weight"]),
+ }
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "config": self.config.to_dict(),
+ "parameters": self.parameters_to_dict(),
+ "schema_version": COMPATIBLE_ARCHITECTURE_SCHEMA_VERSION,
+ "tokenizer": self.tokenizer.to_dict(),
+ }
+
+ @classmethod
+ def from_dict(cls, payload: Mapping[str, Any]) -> "CompatibleLearnedArchitecture":
+ config_payload = dict(payload.get("config") or {})
+ default_views = CompatibleArchitectureConfig().views
+ config = CompatibleArchitectureConfig(
+ arm=str(config_payload.get("arm") or SHARED_LATENT_ARCHITECTURE_ARM),
+ latent_dim=int(
+ config_payload.get("latent_dim")
+ or COMPATIBLE_ARCHITECTURE_DEFAULT_LATENT_DIM
+ ),
+ hidden_dim=int(
+ config_payload.get("hidden_dim")
+ or COMPATIBLE_ARCHITECTURE_DEFAULT_HIDDEN_DIM
+ ),
+ max_seq_len=int(
+ config_payload.get("max_seq_len")
+ or COMPATIBLE_ARCHITECTURE_DEFAULT_MAX_SEQ_LEN
+ ),
+ seed=int(config_payload.get("seed") or 0),
+ families=tuple(config_payload.get("families") or LEGAL_IR_GRAMMAR_FAMILIES),
+ views=tuple(config_payload.get("views") or default_views),
+ )
+ tokenizer_payload = payload.get("tokenizer")
+ tokenizer = (
+ LegalIRFrozenTokenizer.from_dict(tokenizer_payload)
+ if isinstance(tokenizer_payload, Mapping)
+ else LegalIRFrozenTokenizer.canonical()
+ )
+ return cls(
+ config=config,
+ tokenizer=tokenizer,
+ parameters=payload.get("parameters"),
+ )
+
+
+def build_compatible_learned_architecture(
+ arm: str = SHARED_LATENT_ARCHITECTURE_ARM,
+ *,
+ tokenizer: Optional[LegalIRFrozenTokenizer] = None,
+ seed: int = 0,
+ latent_dim: int = COMPATIBLE_ARCHITECTURE_DEFAULT_LATENT_DIM,
+ hidden_dim: int = COMPATIBLE_ARCHITECTURE_DEFAULT_HIDDEN_DIM,
+ max_seq_len: int = COMPATIBLE_ARCHITECTURE_DEFAULT_MAX_SEQ_LEN,
+) -> CompatibleLearnedArchitecture:
+ return CompatibleLearnedArchitecture(
+ config=CompatibleArchitectureConfig(
+ arm=arm,
+ latent_dim=latent_dim,
+ hidden_dim=hidden_dim,
+ max_seq_len=max_seq_len,
+ seed=seed,
+ ),
+ tokenizer=tokenizer or LegalIRFrozenTokenizer.canonical(),
+ )
+
+
+def compatible_architecture_suite(
+ *,
+ seed: int = 0,
+ tokenizer: Optional[LegalIRFrozenTokenizer] = None,
+) -> dict[str, Any]:
+ """Expose both runnable arms without choosing a winner or writing files."""
+
+ frozen = tokenizer or LegalIRFrozenTokenizer.canonical()
+ arms = {
+ name: build_compatible_learned_architecture(name, tokenizer=frozen, seed=seed)
+ for name in COMPATIBLE_ARCHITECTURE_ARMS
+ }
+ return {
+ "arms": {
+ name: architecture.architecture_manifest() for name, architecture in arms.items()
+ },
+ "initialization_roots": {
+ name: architecture.initialization_checkpoint()
+ for name, architecture in arms.items()
+ },
+ "instances": arms,
+ "legacy_promoted": False,
+ "legacy_warm_start": evaluate_legacy_warm_start(
+ compatibility_passed=False,
+ quarantine_passed=False,
+ ),
+ "parameter_resource_estimates": {
+ name: architecture.parameter_resource_estimate()
+ for name, architecture in arms.items()
+ },
+ "schema_version": COMPATIBLE_ARCHITECTURE_SCHEMA_VERSION,
+ "tokenizer_vocabulary_cid": frozen.vocabulary_cid,
+ "winner": False,
+ }
+
+
+def compatible_architecture_manifests(
+ *,
+ seed: int = 0,
+ tokenizer: Optional[LegalIRFrozenTokenizer] = None,
+) -> dict[str, Any]:
+ """Return serializable manifests, init roots, and resource estimates."""
+
+ suite = compatible_architecture_suite(seed=seed, tokenizer=tokenizer)
+ return {
+ "arms": suite["arms"],
+ "initialization_roots": suite["initialization_roots"],
+ "legacy_promoted": False,
+ "parameter_resource_estimates": suite["parameter_resource_estimates"],
+ "schema_version": suite["schema_version"],
+ "tokenizer_vocabulary_cid": suite["tokenizer_vocabulary_cid"],
+ "winner": False,
+ }
+
+
+def advisor_architecture_version(autoencoder: Any) -> str:
+ """Read the existing advisor architecture version without mutating it."""
+
+ if autoencoder is None:
+ return ""
+ state = getattr(autoencoder, "state", None)
+ version = getattr(state, "architecture_version", "") or getattr(
+ autoencoder, "architecture_version", ""
+ )
+ return str(version or "").strip()
+
+
+def extend_existing_advisor_architectures(
+ autoencoder: Any = None,
+ *,
+ seed: int = 0,
+ tokenizer: Optional[LegalIRFrozenTokenizer] = None,
+) -> dict[str, Any]:
+ """Extend the existing modal-autoencoder advisor into both experiment arms.
+
+ The advisor is not mutated, MODEL-LEGACY-1 is not promoted, and neither
+ arm is recorded as a winner.
+ """
+
+ frozen = tokenizer or LegalIRFrozenTokenizer.canonical()
+ suite = compatible_architecture_suite(seed=seed, tokenizer=frozen)
+ advisor_version = advisor_architecture_version(autoencoder)
+ compatible_with_advisor = (not advisor_version) or (
+ advisor_version in COMPATIBLE_LEGACY_ARCHITECTURE_VERSIONS
+ )
+ return {
+ "advisor_architecture_version": advisor_version or None,
+ "advisor_extended": autoencoder is not None,
+ "advisor_mutated": False,
+ "arms": suite["arms"],
+ "compatible_with_advisor": compatible_with_advisor,
+ "initialization_roots": suite["initialization_roots"],
+ "instances": suite["instances"],
+ "legacy_promoted": False,
+ "legacy_warm_start": evaluate_legacy_warm_start(
+ compatibility_passed=False,
+ quarantine_passed=False,
+ ),
+ "parameter_resource_estimates": suite["parameter_resource_estimates"],
+ "schema_version": suite["schema_version"],
+ "tokenizer_vocabulary_cid": frozen.vocabulary_cid,
+ "winner": False,
+ }
+
+
+__all__ = [
+ "COMPATIBLE_ARCHITECTURE_ARMS",
+ "COMPATIBLE_ARCHITECTURE_INIT_CHECKPOINT_SCHEMA",
+ "COMPATIBLE_ARCHITECTURE_SCHEMA_VERSION",
+ "COMPATIBLE_LEGACY_ARCHITECTURE_VERSIONS",
+ "CompatibleArchitectureConfig",
+ "CompatibleLearnedArchitecture",
+ "ConstrainedLegalIRDecode",
+ "FrozenVocabularyMutationError",
+ "IncompatibleLegacyWarmStartError",
+ "LEGAL_IR_CANONICAL_VOCABULARY_CID",
+ "LEGAL_IR_CANONICAL_VOCABULARY_SIZE",
+ "LEGAL_IR_CLOSED_TOKEN_CLASSES",
+ "LEGAL_IR_CONSTRAINED_DECODER_INTERFACE",
+ "LEGAL_IR_CONSTRAINED_DECODER_SCHEMA",
+ "LEGAL_IR_CONSTRAINT_MASK_NAMES",
+ "LEGAL_IR_DECODE_FALLBACKS",
+ "LEGAL_IR_FROZEN_TOKENIZER_INTERFACE",
+ "LEGAL_IR_FROZEN_TOKENIZER_SCHEMA_VERSION",
+ "LEGAL_IR_FROZEN_VOCABULARY_SCHEMA",
+ "LEGAL_IR_GRAMMAR_DECODER_SCHEMA_VERSION",
+ "LEGAL_IR_GRAMMAR_FAMILIES",
+ "LEGAL_IR_IDENTIFIER_BUCKET_COUNT",
+ "LEGAL_IR_MAX_BEAM_WIDTH",
+ "LEGAL_IR_MAX_DECODE_STEPS",
+ "LEGAL_IR_TOKEN_CLASSES",
+ "LegalIRBeamHypothesis",
+ "LegalIRConstrainedDecodeConfig",
+ "LegalIRConstrainedTokenDecode",
+ "LegalIRConstraintBypassError",
+ "LegalIRConstraintMasks",
+ "LegalIRConstraintRejectionTelemetry",
+ "LegalIRFrozenTokenizer",
+ "LegalIRGoldPathAdmission",
+ "LegalIRGrammarDecoder",
+ "LegalIRGrammarRejection",
+ "LegalIRGrammarValidation",
+ "LegalIRProductionSpec",
+ "LegalIRProverAdmission",
+ "LegalIRToken",
+ "LegalIRTokenization",
+ "LegalIRVocabEntry",
+ "MODEL_LEGACY_1_IDENTITY",
+ "SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_ARM",
+ "SHARED_ENCODER_TYPED_HEAD_ARCHITECTURE_VERSION",
+ "SHARED_LATENT_ARCHITECTURE_ARM",
+ "SHARED_LATENT_ARCHITECTURE_VERSION",
+ "UnboundedLegalIRBeamError",
+ "UnknownFrozenTokenError",
+ "admit_legal_ir_gold_path",
+ "advisor_architecture_version",
+ "apply_legal_ir_constraint_masks",
+ "build_compatible_learned_architecture",
+ "canonical_legal_ir_frozen_tokenizer",
+ "canonical_legal_ir_grammar_family",
+ "compare_constrained_vs_unconstrained_proof_calls",
+ "compatible_architecture_manifests",
+ "compatible_architecture_suite",
+ "constrained_legal_ir_decode",
+ "constrained_legal_ir_token_decode",
+ "default_legal_ir_frozen_vocabulary",
+ "default_legal_ir_production_specs",
+ "evaluate_legacy_warm_start",
+ "extend_existing_advisor_architectures",
+ "gate_legal_ir_prover_call",
+ "grammar_metrics_from_validation",
+ "grammar_rejection_reason_names",
+ "infer_legal_ir_grammar_family",
+ "legal_ir_constrained_decode_config",
+ "legal_ir_constraint_masks",
+ "require_legacy_warm_start",
+ "validate_legal_ir_candidate",
+]
diff --git a/releases/20261004-retained-checkpoints-v1/source/21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3/ipfs_datasets_py/logic/ui_ux_ir/decoder.py b/releases/20261004-retained-checkpoints-v1/source/21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3/ipfs_datasets_py/logic/ui_ux_ir/decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..77950b04c9e103410b66a4147981146ab7bebd70
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/source/21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3/ipfs_datasets_py/logic/ui_ux_ir/decoder.py
@@ -0,0 +1,157 @@
+"""Exact-version decoding of every declared UI/UX IR wire field.
+
+All nested records are constructed from the local schema's closed dataclasses.
+No field is silently dropped, no scalar is stringified/coerced, and ordered
+collections retain order. Schema validation remains the cross-reference owner.
+This wire codec does not claim neural decoding or source semantic fidelity.
+"""
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import MISSING, fields, is_dataclass
+from enum import Enum
+from functools import lru_cache
+import json
+import math
+from types import UnionType
+from typing import Any, get_args, get_origin, get_type_hints
+
+from . import schema
+from .schema import UIIRDocument, UIIRValidationError
+
+MAX_WIRE_BYTES = 16 * 1024 * 1024
+MAX_WIRE_NODES = 200000
+MAX_WIRE_DEPTH = 64
+_WIRE_CLASSES = frozenset(value for value in vars(schema).values()
+ if isinstance(value, type) and is_dataclass(value) and value.__module__ == schema.__name__)
+
+
+class UIIRDecodeError(UIIRValidationError):
+ """An untrusted payload cannot be decoded without loss or coercion."""
+
+
+def _require(condition, message):
+ if not condition:
+ raise UIIRDecodeError(message)
+
+
+def _unique_object(pairs):
+ result = {}
+ for key, value in pairs:
+ _require(key not in result, "duplicate UI/UX IR JSON field: " + key)
+ result[key] = value
+ return result
+
+
+def _snapshot(value, budget, depth=0):
+ budget[0] -= 1
+ _require(budget[0] >= 0 and depth <= MAX_WIRE_DEPTH, "UI/UX IR wire resource bound exceeded")
+ if isinstance(value, Mapping):
+ _require(all(type(key) is str for key in value), "UI/UX IR object keys must be strings")
+ return {key: _snapshot(item, budget, depth + 1) for key, item in value.items()}
+ if type(value) in (list, tuple):
+ return [_snapshot(item, budget, depth + 1) for item in value]
+ _require(value is None or type(value) in (str, bool, int, float), "UI/UX IR requires JSON values")
+ _require(type(value) is not float or math.isfinite(value), "UI/UX IR contains nonfinite number")
+ return value
+
+
+@lru_cache(maxsize=len(_WIRE_CLASSES))
+def _field_types(record_type):
+ _require(record_type in _WIRE_CLASSES, "unsupported UI/UX IR record type")
+ return get_type_hints(record_type)
+
+
+def _decode_value(value, expected, path):
+ origin, arguments = get_origin(expected), get_args(expected)
+ if origin is UnionType:
+ nonnull = tuple(item for item in arguments if item is not type(None))
+ _require(len(nonnull) == 1 and type(None) in arguments, "unsupported UI/UX IR union type")
+ return None if value is None else _decode_value(value, nonnull[0], path)
+ if origin is tuple:
+ _require(len(arguments) == 2 and arguments[1] is Ellipsis and type(value) is list,
+ path + " must be an array")
+ return tuple(_decode_value(item, arguments[0], path + "[" + str(index) + "]")
+ for index, item in enumerate(value))
+ if origin is Mapping:
+ _require(arguments == (str, Any) and type(value) is dict, path + " must be a JSON object")
+ # The complete JSON snapshot was bounded above. The existing schema
+ # owner freezes these extension/settings payloads and rejects code.
+ return value
+ if expected in _WIRE_CLASSES:
+ return _decode_record(value, expected, path)
+ if isinstance(expected, type) and issubclass(expected, Enum):
+ _require(expected.__module__ == schema.__name__ and type(value) is str,
+ path + " must be a declared enum string")
+ try:
+ return expected(value)
+ except ValueError as exc:
+ raise UIIRDecodeError(path + " has an unknown enum value") from exc
+ _require(expected in (str, bool, int) and type(value) is expected,
+ path + " has the wrong scalar type")
+ return value
+
+
+def _decode_record(payload, record_type, path):
+ _require(type(payload) is dict, path + " must be an object")
+ declared = {field.name: field for field in fields(record_type)}
+ unknown = sorted(set(payload) - set(declared))
+ _require(not unknown, path + " has unknown fields: " + ", ".join(unknown))
+ missing = [name for name, field in declared.items() if name not in payload
+ and field.default is MISSING and field.default_factory is MISSING]
+ _require(not missing, path + " is missing required fields: " + ", ".join(missing))
+ hints = _field_types(record_type)
+ return record_type(**{key: _decode_value(value, hints[key], path + "." + key)
+ for key, value in payload.items()})
+
+
+# Retain the original private helper names for local consumers, with exact
+# nested schemas and types instead of lossy str()/int() conversions.
+def _decode_source(payload):
+ return _decode_record(_snapshot(payload, [MAX_WIRE_NODES]), schema.UISourceRef, "UISourceRef")
+
+
+def _decode_component(payload):
+ return _decode_record(_snapshot(payload, [MAX_WIRE_NODES]), schema.UIComponent, "UIComponent")
+
+
+def _decode_terminal(payload):
+ return _decode_record(_snapshot(payload, [MAX_WIRE_NODES]), schema.UITerminalOutcome, "UITerminalOutcome")
+
+
+def _decode_locale(payload):
+ return _decode_record(_snapshot(payload, [MAX_WIRE_NODES]), schema.UILocaleDefaults, "UILocaleDefaults")
+
+
+def decode_ui_ir(payload: Mapping[str, Any] | str | bytes) -> UIIRDocument:
+ """Decode every schema field and validate the complete reference closure.
+
+ Omitted optional fields receive only schema-declared defaults. Present null,
+ false, zero or empty values never substitute for a missing field. Legacy
+ versions still require the explicit migration owner.
+ """
+ try:
+ if isinstance(payload, (str, bytes, bytearray)):
+ raw = payload.encode("utf-8") if isinstance(payload, str) else bytes(payload)
+ _require(len(raw) <= MAX_WIRE_BYTES, "UI/UX IR wire exceeds byte bound")
+ payload = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object)
+ payload = _snapshot(payload, [MAX_WIRE_NODES])
+ _require(type(payload) is dict, "UI/UX IR payload must decode to an object")
+ raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
+ _require(len(raw) <= MAX_WIRE_BYTES, "UI/UX IR wire exceeds byte bound")
+ version = payload.get("schema_version")
+ _require(type(version) is str and bool(version), "UI/UX IR payload missing schema_version")
+ if version == schema.LEGACY_UI_UX_IR_SCHEMA_VERSION:
+ raise UIIRDecodeError(f"Legacy schema_version {version!r} requires explicit migration before decode")
+ _require(version == schema.UI_UX_IR_SCHEMA_VERSION,
+ f"Unsupported schema_version {version!r}; expected {schema.UI_UX_IR_SCHEMA_VERSION!r}")
+ schema.reject_unknown_document_fields(payload)
+ document = _decode_record(payload, UIIRDocument, "UIIRDocument")
+ return schema.validate_ui_ir(document)
+ except UIIRDecodeError:
+ raise
+ except (UIIRValidationError, UnicodeError, ValueError, TypeError, KeyError, RecursionError) as exc:
+ raise UIIRDecodeError(f"Failed to decode UI/UX IR document: {exc}") from exc
+
+
+__all__ = ["UIIRDecodeError", "decode_ui_ir"]
diff --git a/releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py b/releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc60e3f43e9fe0bddcbea1f258a2e876284aee33
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py
@@ -0,0 +1,434 @@
+"""Experimental fixed-schema typed IR decoder over a trained Legal 384D encoder.
+
+A frozen inherited residual projection feeds parallel learned scalar classifiers.
+Training consensus supplies constants and the exact typed JSON tree. Inference
+combines independently predicted scalar classes, never retrieves whole targets.
+This intentionally rejects variable schemas, array lengths, and unseen classes.
+Native validation and held-out accuracy do not grant semantic or proof authority.
+"""
+from __future__ import annotations
+
+from contextlib import contextmanager
+from copy import deepcopy
+import hashlib
+import math
+from pathlib import Path
+import time
+
+from . import source_training_v2 as shared
+from ....optimizers.logic_theorem_optimizer import domain_384_autoencoder as native
+from ....optimizers.logic_theorem_optimizer import modal_latent_formula as legal
+
+SCHEMA = "structured-source-384-autoencoder/v1"
+DOMAINS, DIMENSION, FALSE = shared.DOMAINS, 384, native.FALSE
+MAX_BYTES = native.MAX_BYTES
+RIDGES = (.0001, .001, .01, .1)
+PROJECTION_KEYS = ("projection_down.weight", "projection_down.bias", "projection_up.weight", "projection_up.bias")
+_require, _raw, digest = native._require, native._raw, native.digest
+
+
+@contextmanager
+def _numeric():
+ import numpy as np
+ # Explicitly bound BLAS work without permanently changing caller settings.
+ try:
+ from threadpoolctl import threadpool_limits
+ except ImportError:
+ yield np
+ else:
+ with threadpool_limits(limits=1, user_api="blas"):
+ yield np
+
+
+def _implementation():
+ return {"runtime_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
+ "shared_runtime": shared._implementation()}
+
+
+def _shape(value):
+ if type(value) is dict:
+ return {"kind": "object", "fields": [[key, _shape(value[key])] for key in sorted(value)]}
+ if type(value) is list:
+ return {"kind": "array", "items": [_shape(item) for item in value]}
+ names = {str: "string", bool: "boolean", int: "integer", float: "float", type(None): "null"}
+ _require(type(value) in names, "non-JSON target scalar")
+ return {"kind": names[type(value)]}
+
+
+def _scalar_leaves(value, path=()):
+ if type(value) is dict:
+ return {key: leaf for field in sorted(value) for key, leaf in _scalar_leaves(value[field], (*path, field)).items()}
+ if type(value) is list:
+ return {key: leaf for index, item in enumerate(value) for key, leaf in _scalar_leaves(item, (*path, index)).items()}
+ return {path: value}
+
+
+def _replace(document, path, value):
+ _require(path, "root scalar IR is unsupported")
+ target = document
+ for part in path[:-1]:
+ target = target[part]
+ target[path[-1]] = deepcopy(value)
+
+
+def _fit_schema(rows):
+ shape = _shape(rows[0]["target"])
+ _require(all(_shape(row["target"]) == shape for row in rows),
+ "fixed typed JSON tree required; array lengths, keys, and scalar types may not vary")
+ leaves = [_scalar_leaves(row["target"]) for row in rows]
+ template, slots = deepcopy(rows[0]["target"]), []
+ for path in sorted(leaves[0], key=lambda item: _raw(list(item))):
+ classes = {_raw(row[path]): row[path] for row in leaves}
+ if len(classes) > 1:
+ _require(len(classes) <= 512, "too many training classes for one scalar")
+ slots.append({"path": list(path), "classes": [deepcopy(classes[key]) for key in sorted(classes)]})
+ _replace(template, path, None)
+ _require(1 <= len(slots) <= 256, "one to 256 varying training scalar slots required")
+ return {"schema": "fixed-typed-json-consensus/v1", "shape": shape, "template": template,
+ "slots": slots, "origin": "training_only", "whole_target_memory": False}
+
+
+def _targets(np, rows, schema):
+ target_ids, width = [], sum(len(slot["classes"]) for slot in schema["slots"])
+ _require(width <= 4096, "total training class vocabulary exceeds bound")
+ one_hot = np.zeros((len(rows), width), dtype=np.float64)
+ for row_index, row in enumerate(rows):
+ _require(_shape(row["target"]) == schema["shape"], "target fixed typed JSON tree differs")
+ leaves, ids, offset = _scalar_leaves(row["target"]), [], 0
+ masked = deepcopy(row["target"])
+ for slot in schema["slots"]:
+ path = tuple(slot["path"])
+ classes = [_raw(value) for value in slot["classes"]]
+ value = _raw(leaves[path])
+ _require(value in classes, "target scalar outside training vocabulary")
+ index = classes.index(value)
+ ids.append(index)
+ one_hot[row_index, offset+index] = 1.
+ offset += len(classes)
+ _replace(masked, slot["path"], None)
+ _require(_raw(masked) == _raw(schema["template"]), "target differs from training consensus constants")
+ target_ids.append(ids)
+ return one_hot, target_ids
+
+
+def _project(np, rows, projection, *, zero_residual=False):
+ values = np.asarray([row["embedding"] for row in rows], dtype=np.float64)
+ if zero_residual:
+ return values
+ down = np.asarray(projection["projection_down.weight"], dtype=np.float64)
+ down_bias = np.asarray(projection["projection_down.bias"], dtype=np.float64)
+ up = np.asarray(projection["projection_up.weight"], dtype=np.float64)
+ up_bias = np.asarray(projection["projection_up.bias"], dtype=np.float64)
+ projected = values + np.tanh(values @ down.T + down_bias) @ up.T + up_bias
+ _require(bool(np.isfinite(projected).all()), "nonfinite projected embedding")
+ return projected
+
+
+def _projection(parent):
+ state = {key: deepcopy(parent["model_state"][key]) for key in PROJECTION_KEYS}
+ _validate_projection(state, parent["config"]["projection_width"])
+ return state
+
+
+def _validate_projection(state, width):
+ import numpy as np
+ _require(type(width) is int and 1 <= width <= 64, "invalid inherited projection width")
+ _require(type(state) is dict and set(state) == set(PROJECTION_KEYS), "closed inherited projection required")
+ expected = dict(zip(PROJECTION_KEYS, ((width, DIMENSION), (width,), (DIMENSION, width), (DIMENSION,))))
+ for name, shape in expected.items():
+ try:
+ value = np.asarray(state[name], dtype=np.float64)
+ except (ValueError, TypeError) as exc:
+ raise ValueError("invalid projection tensor") from exc
+ _require(value.shape == shape and bool(np.isfinite(value).all()), "projection tensor shape or finiteness differs")
+
+
+def _normalize(np, projected, transform=None):
+ if transform is None:
+ mean = projected.mean(0)
+ scale = max(float(np.sqrt(np.mean(np.sum((projected-mean)**2, axis=1)))), .01)
+ transform = {"mean": mean.tolist(), "scale": scale, "origin": "training_projected_embeddings_only"}
+ return (projected-np.asarray(transform["mean"])) / transform["scale"], transform
+
+
+def _assemble(domain, scores, schema):
+ reports = []
+ for score in scores:
+ target, predicted, offset = deepcopy(schema["template"]), [], 0
+ for slot in schema["slots"]:
+ width = len(slot["classes"])
+ index = int(score[offset:offset+width].argmax())
+ predicted.append(index)
+ _replace(target, slot["path"], slot["classes"][index])
+ offset += width
+ candidate, reason = None, None
+ try:
+ candidate = shared.validate_target(domain, target)["canonical_ir"]
+ except (ValueError, TypeError, KeyError, RecursionError) as exc:
+ reason = str(exc)[:512]
+ reports.append({"candidate_ir": candidate, "predicted_classes": predicted, "reason": reason})
+ return reports
+
+
+def _score(domain, scores, rows, target_ids, schema):
+ generated = _assemble(domain, scores, schema)
+ slot_correct = sum(sum(actual == expected for actual, expected in zip(row["predicted_classes"], gold))
+ for row, gold in zip(generated, target_ids))
+ correct = sum(sum(actual == expected for actual, expected in zip(row["predicted_classes"], gold))
+ for row, gold in zip(generated, target_ids) if row["candidate_ir"] is not None)
+ count = len(rows)*len(schema["slots"])
+ return {"exact_targets": sum(row["candidate_ir"] is not None and _raw(row["candidate_ir"]) == _raw(gold["target"])
+ for row, gold in zip(generated, rows)),
+ "valid_candidates": sum(row["candidate_ir"] is not None for row in generated), "count": len(rows),
+ "semantic_leaf_correct": correct, "semantic_leaf_count": count,
+ "semantic_leaf_accuracy": correct/max(count, 1),
+ "classifier_slot_correct": slot_correct, "classifier_slot_accuracy": slot_correct/max(count, 1),
+ "semantic_metric_scope": "correct_variable_leaves_only_for_native_valid_candidates", "teacher_forcing": False}
+
+
+def _manifest(rows):
+ return [{"id": row["id"], "source_sha256": hashlib.sha256(row["source_text"].encode()).hexdigest(),
+ "normalized_source_sha256": hashlib.sha256(" ".join(row["source_text"].casefold().split()).encode()).hexdigest(),
+ "embedding_sha256": digest(row["embedding"]), "target_sha256": digest(row["target"])} for row in rows]
+
+
+def train(domain, training_rows, validation_rows, *, parent_projection, config=None):
+ """Fit parallel classifiers on training data; tuning selects a fixed ridge grid."""
+ started = time.monotonic()
+ options = {"ridges": list(RIDGES), "embedding_provenance": {"model_id": "caller_supplied", "verified_by_runtime": False}}
+ _require(config is None or type(config) is dict and set(config) <= set(options), "unknown structured training option")
+ options.update(config or {})
+ _require(type(options["ridges"]) is list and 1 <= len(options["ridges"]) <= 16
+ and all(type(value) in (int, float) and math.isfinite(value) and 0 < value <= 100 for value in options["ridges"])
+ and options["ridges"] == sorted(set(options["ridges"])), "finite increasing positive ridge grid required")
+ _require(type(options["embedding_provenance"]) is dict and len(_raw(options["embedding_provenance"])) <= 16384,
+ "bounded embedding provenance required")
+ training = shared._rows(domain, training_rows, training=True)
+ validation = shared._rows(domain, validation_rows, training=True)
+ _require(len(training) <= 2048, "dual ridge training is bounded to 2048 rows")
+ for key in (lambda row: row["id"], lambda row: " ".join(row["source_text"].casefold().split()), lambda row: digest(row["embedding"])):
+ _require(not {key(row) for row in training} & {key(row) for row in validation},
+ "training/validation identity, source, or embedding overlap")
+ parent, parent_sha, parent_file = shared._parent(parent_projection)
+ with native._cpu():
+ legal.validate_checkpoint(parent)
+ _require(parent["binding"]["dimension"] == DIMENSION and parent["progress"]["optimizer_steps"] > 0,
+ "trained 384D Legal parent required")
+ projection = _projection(parent)
+ schema = _fit_schema(training)
+ with _numeric() as np:
+ train_targets, _ = _targets(np, training, schema)
+ _, validation_ids = _targets(np, validation, schema)
+ train_x, transform = _normalize(np, _project(np, training, projection))
+ validation_x, _ = _normalize(np, _project(np, validation, projection), transform)
+ bias = train_targets.mean(0)
+ centered_targets = train_targets-bias
+ gram = train_x @ train_x.T
+ initial = _score(domain, np.zeros((len(validation), train_targets.shape[1])), validation, validation_ids, schema)
+ selected, best_rank, best_weights, history = None, None, None, []
+ fit_started = time.monotonic()
+ factorization_seconds = validation_seconds = 0.
+ for ridge in options["ridges"]:
+ tick = time.monotonic()
+ # One solve handles every class of every semantic slot. There is
+ # no independent factorization per classifier or target document.
+ dual = np.linalg.solve(gram + float(ridge)*np.eye(len(training)), centered_targets)
+ weights = train_x.T @ dual
+ factorization_seconds += time.monotonic()-tick
+ _require(bool(np.isfinite(weights).all()), "nonfinite learned decoder weights")
+ tick = time.monotonic()
+ observed = _score(domain, validation_x @ weights + bias, validation, validation_ids, schema)
+ validation_seconds += time.monotonic()-tick
+ rank = (observed["exact_targets"], observed["semantic_leaf_correct"])
+ chosen = best_rank is None or rank > best_rank
+ history.append({"ridge": ridge, **observed, "selected_at_step": chosen})
+ if chosen:
+ selected, best_rank, best_weights, best = ridge, rank, weights.copy(), observed
+ elapsed = time.monotonic()-fit_started
+ state = {"weights": best_weights.tolist(), "bias": bias.tolist()}
+ metrics = {"selected_ridge": selected, "selected_validation": best, "initial_zero_head_validation": initial,
+ "history": history, "factorizations": len(options["ridges"]), "factorization_seconds": factorization_seconds,
+ "validation_seconds": validation_seconds, "fit_seconds": elapsed,
+ "unique_training_examples": len(training), "fit_unique_examples_per_second": len(training)/max(elapsed, 1e-9),
+ "pre_checkpoint_seconds": time.monotonic()-started, "test_used_for_selection": False,
+ "selection": "free_running_exact_then_variable_leaf_accuracy_first_ridge_on_ties",
+ "optimizer_steps": 0, "gradient_training_used": False}
+ checkpoint = {"schema": SCHEMA, "domain_id": domain, "dimension": DIMENSION,
+ "implementation": _implementation(), "config": options, "parent_sha256": parent_sha,
+ "parent_binding": deepcopy(parent["binding"]), "projection_width": parent["config"]["projection_width"],
+ "projection_state": projection, "projection_sha256": digest(projection), "input_transform": transform,
+ "target_schema": schema, "head_state": state, "head_sha256": digest(state),
+ "training_manifest": _manifest(training), "validation_manifest": _manifest(validation), "training": metrics,
+ "lineage": {"parent_encoder_frozen": True, "projection_tensors_inherited_exactly": list(PROJECTION_KEYS),
+ "parent_modified": False, "random_parameters_used": False}, **FALSE}
+ _require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
+ if parent_file:
+ _require(parent_file[0].read_bytes() == parent_file[1], "parent changed during training")
+ Runtime(checkpoint)
+ return {"checkpoint": checkpoint, "metrics": deepcopy(metrics)}
+
+
+class Runtime:
+ """Independent learned scalar predictions assembled through a fixed schema."""
+ def __init__(self, checkpoint):
+ fields = {"schema", "domain_id", "dimension", "implementation", "config", "parent_sha256", "parent_binding",
+ "projection_width", "projection_state", "projection_sha256", "input_transform", "target_schema",
+ "head_state", "head_sha256", "training_manifest", "validation_manifest", "training", "lineage", *FALSE}
+ _require(type(checkpoint) is dict and set(checkpoint) == fields and checkpoint["schema"] == SCHEMA,
+ "closed structured source checkpoint required")
+ _require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
+ _require(checkpoint["domain_id"] in DOMAINS and type(checkpoint["dimension"]) is int and checkpoint["dimension"] == DIMENSION,
+ "checkpoint requires genuine 384D domain")
+ _require(all(checkpoint[key] is False for key in FALSE), "checkpoint cannot grant authority")
+ _require(checkpoint["implementation"] == _implementation(), "implementation pins differ")
+ _require(type(checkpoint["parent_sha256"]) is str and native._SHA.fullmatch(checkpoint["parent_sha256"])
+ and type(checkpoint["parent_binding"]) is dict and checkpoint["parent_binding"].get("dimension") == DIMENSION,
+ "invalid parent binding")
+ _require(digest(checkpoint["projection_state"]) == checkpoint["projection_sha256"], "projection digest differs")
+ _validate_projection(checkpoint["projection_state"], checkpoint["projection_width"])
+ transform = checkpoint["input_transform"]
+ _require(type(transform) is dict and set(transform) == {"mean", "scale", "origin"}
+ and transform["origin"] == "training_projected_embeddings_only", "invalid input transform")
+ native._vector(transform["mean"])
+ _require(type(transform["scale"]) in (int, float) and math.isfinite(transform["scale"]) and .01 <= transform["scale"] <= 1e8,
+ "invalid input scale")
+ schema = checkpoint["target_schema"]
+ _require(type(schema) is dict and set(schema) == {"schema", "shape", "template", "slots", "origin", "whole_target_memory"}
+ and schema["schema"] == "fixed-typed-json-consensus/v1" and schema["origin"] == "training_only"
+ and schema["whole_target_memory"] is False and type(schema["template"]) is dict, "invalid fixed target schema")
+ slots = schema["slots"]
+ _require(type(slots) is list and 1 <= len(slots) <= 256, "invalid varying scalar slots")
+ candidate, seen = deepcopy(schema["template"]), set()
+ canonical_paths = set(_scalar_leaves(schema["template"]))
+ for slot in slots:
+ _require(type(slot) is dict and set(slot) == {"path", "classes"} and type(slot["path"]) is list
+ and 1 <= len(slot["path"]) <= 128 and all(type(part) in (int, str) for part in slot["path"]), "invalid scalar path")
+ _require(tuple(slot["path"]) in canonical_paths, "noncanonical scalar path")
+ path = _raw(slot["path"])
+ _require(path not in seen, "duplicate scalar path")
+ seen.add(path)
+ classes = slot["classes"]
+ _require(type(classes) is list and 2 <= len(classes) <= 512
+ and all(type(value) in (str, int, float, bool, type(None)) for value in classes)
+ and all(type(value) is type(classes[0]) for value in classes)
+ and [_raw(value) for value in classes] == sorted(set(_raw(value) for value in classes)), "invalid scalar classes")
+ try:
+ existing = schema["template"]
+ for part in slot["path"]:
+ existing = existing[part]
+ _require(existing is None, "varying scalar must use an empty template slot")
+ _replace(candidate, slot["path"], classes[0])
+ except (TypeError, KeyError, IndexError) as exc:
+ raise ValueError("scalar path outside schema") from exc
+ _require(_shape(candidate) == schema["shape"], "stored typed target shape differs")
+ width = sum(len(slot["classes"]) for slot in slots)
+ _require(width <= 4096, "total class vocabulary exceeds bound")
+ state = checkpoint["head_state"]
+ _require(type(state) is dict and set(state) == {"weights", "bias"} and digest(state) == checkpoint["head_sha256"], "head digest differs")
+ with _numeric() as np:
+ weights, bias = np.asarray(state["weights"], dtype=np.float64), np.asarray(state["bias"], dtype=np.float64)
+ _require(weights.shape == (DIMENSION, width) and bias.shape == (width,)
+ and bool(np.isfinite(weights).all()) and bool(np.isfinite(bias).all()), "invalid head tensor shape or finiteness")
+ for name in ("training_manifest", "validation_manifest"):
+ rows = checkpoint[name]
+ _require(type(rows) is list and 1 <= len(rows) <= 4096, "invalid split manifest")
+ _require(all(type(row) is dict and set(row) == {"id", "source_sha256", "normalized_source_sha256", "embedding_sha256", "target_sha256"}
+ and type(row["id"]) is str and 0 < len(row["id"]) <= 256
+ and all(type(row[key]) is str and native._SHA.fullmatch(row[key]) for key in row if key != "id") for row in rows), "invalid split row")
+ _require(len({row["id"] for row in rows}) == len(rows), "duplicate split ID")
+ for key in ("id", "source_sha256", "normalized_source_sha256", "embedding_sha256"):
+ _require(not {row[key] for row in checkpoint["training_manifest"]} & {row[key] for row in checkpoint["validation_manifest"]}, "checkpoint split overlap")
+ options = checkpoint["config"]
+ _require(type(options) is dict and set(options) == {"ridges", "embedding_provenance"}
+ and type(options["ridges"]) is list and 1 <= len(options["ridges"]) <= 16
+ and all(type(value) in (int, float) and math.isfinite(value) and 0 < value <= 100 for value in options["ridges"])
+ and options["ridges"] == sorted(set(options["ridges"])) and type(options["embedding_provenance"]) is dict,
+ "invalid structured config")
+ training = checkpoint["training"]
+ _require(type(training) is dict and training.get("selected_ridge") in options["ridges"]
+ and training.get("test_used_for_selection") is False and training.get("gradient_training_used") is False,
+ "invalid training provenance")
+ lineage = checkpoint["lineage"]
+ _require(lineage == {"parent_encoder_frozen": True, "projection_tensors_inherited_exactly": list(PROJECTION_KEYS),
+ "parent_modified": False, "random_parameters_used": False}, "invalid transfer lineage")
+ self.checkpoint = deepcopy(checkpoint)
+ self.weights, self.bias = weights, bias
+
+ def describe(self):
+ return {"schema": SCHEMA, "domain_id": self.checkpoint["domain_id"], "dimension": DIMENSION,
+ "input_representation": "source_embedding_384", "source_text_is_neural_input": False,
+ "output_scope": "fixed_typed_json_schema_and_training_scalar_vocabulary",
+ "generation": "independent_learned_scalar_classes_assembled_through_training_consensus_schema",
+ "sample_memory_used": False, "whole_target_retrieval": False,
+ "head_sha256": self.checkpoint["head_sha256"], "projection_sha256": self.checkpoint["projection_sha256"],
+ "zero_projection_ablation": "zero_residual_branch_identity_embedding_retained",
+ "shuffle_embeddings_ablation": "cyclic_rotation_of_supplied_embedding_batch",
+ "independent_source_fidelity_check_required": True, **FALSE}
+
+ def infer(self, rows, *, weight_ablation=None):
+ rows = shared._rows(self.checkpoint["domain_id"], rows, training=False)
+ _require(weight_ablation in (None, "zero_head", "zero_projection", "shuffle_embeddings"), "unknown weight ablation")
+ if weight_ablation == "shuffle_embeddings":
+ _require(len(rows) > 1, "embedding shuffle requires at least two rows")
+ original = [row["embedding"] for row in rows]
+ for index, row in enumerate(rows):
+ row["embedding"] = original[(index+1) % len(rows)]
+ with _numeric() as np:
+ projected = _project(np, rows, self.checkpoint["projection_state"], zero_residual=weight_ablation == "zero_projection")
+ data, _ = _normalize(np, projected, self.checkpoint["input_transform"])
+ scores = (np.zeros((len(rows), len(self.bias))) if weight_ablation == "zero_head" else data @ self.weights + self.bias)
+ _require(bool(np.isfinite(scores).all()), "nonfinite classifier scores")
+ generated = _assemble(self.checkpoint["domain_id"], scores, self.checkpoint["target_schema"])
+ reports = []
+ for row, prediction, embedding in zip(rows, generated, projected):
+ reports.append({"id": row["id"], "source_sha256": hashlib.sha256(row["source_text"].encode()).hexdigest(),
+ **prediction, "status": "unqualified_candidate" if prediction["candidate_ir"] is not None else "fail_open_invalid_output",
+ "projected_embedding": embedding.tolist(), "weight_ablation": weight_ablation,
+ "head_sha256": self.checkpoint["head_sha256"], "projection_sha256": self.checkpoint["projection_sha256"],
+ "target_access": False, "teacher_forcing": False, "continue_planning": True, **FALSE})
+ return {"schema": SCHEMA, "domain_id": self.checkpoint["domain_id"], "dimension": DIMENSION, "rows": reports, **FALSE}
+
+
+def evaluate(checkpoint, rows, *, weight_ablation=None):
+ """Count every gold row, including targets outside the fitted decoder scope."""
+ gold = shared._rows(checkpoint["domain_id"], rows, training=True)
+ coverage = []
+ with _numeric() as np:
+ for row in gold:
+ try:
+ _targets(np, [row], checkpoint["target_schema"])
+ coverage.append((True, None))
+ except ValueError as exc:
+ coverage.append((False, str(exc)))
+ report = Runtime(checkpoint).infer([{key: row[key] for key in ("id", "source_text", "embedding")} for row in gold], weight_ablation=weight_ablation)
+ correct = slot_correct = 0
+ for actual, expected, (supported, reason) in zip(report["rows"], gold, coverage):
+ actual["exact_target"] = actual["candidate_ir"] is not None and _raw(actual["candidate_ir"]) == _raw(expected["target"])
+ actual["within_training_coverage"], actual["target_coverage_reason"] = supported, reason
+ leaves = _scalar_leaves(expected["target"])
+ for slot, predicted in zip(checkpoint["target_schema"]["slots"], actual["predicted_classes"]):
+ path = tuple(slot["path"])
+ matches = path in leaves and _raw(slot["classes"][predicted]) == _raw(leaves[path])
+ slot_correct += matches
+ correct += matches and actual["candidate_ir"] is not None
+ count = len(gold)*len(checkpoint["target_schema"]["slots"])
+ return {**report, "count": len(gold), "exact_targets": sum(row["exact_target"] for row in report["rows"]),
+ "valid_candidates": sum(row["candidate_ir"] is not None for row in report["rows"]),
+ "within_training_coverage": sum(supported for supported, _ in coverage),
+ "outside_training_coverage": sum(not supported for supported, _ in coverage),
+ "semantic_leaf_correct": correct, "semantic_leaf_count": count, "semantic_leaf_accuracy": correct/max(count, 1),
+ "classifier_slot_correct": slot_correct, "classifier_slot_accuracy": slot_correct/max(count, 1),
+ "semantic_metric_scope": "correct_variable_leaves_only_for_native_valid_candidates"}
+
+
+def load_checkpoint(path, *, expected_sha256, expected_domain):
+ path = Path(path)
+ _require(path.is_file() and not path.is_symlink() and 0 < path.stat().st_size <= MAX_BYTES, "bounded regular checkpoint required")
+ raw = path.read_bytes()
+ _require(hashlib.sha256(raw).hexdigest() == expected_sha256, "checkpoint bytes differ")
+ checkpoint = native._parse(raw)
+ _require(type(checkpoint) is dict and checkpoint.get("domain_id") == expected_domain, "checkpoint belongs to another domain")
+ return Runtime(checkpoint)
+
+
+__all__ = ["SCHEMA", "DOMAINS", "DIMENSION", "RIDGES", "train", "Runtime", "evaluate", "load_checkpoint"]
diff --git a/releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py b/releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py
new file mode 100644
index 0000000000000000000000000000000000000000..3faf283b3affc5eb38e716e8287502d4c90e088c
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py
@@ -0,0 +1,55 @@
+"""Fail closed when the legal compiler resolves outside this checkout.
+
+The check does not rewrite ``sys.path`` and does not retarget an editable
+install. Callers that need this tree put it on the path themselves.
+"""
+
+from __future__ import annotations
+
+import importlib
+from pathlib import Path
+
+
+class LogicTreePinError(RuntimeError):
+ """The compiler, decompiler, or parser loaded from a different checkout."""
+
+
+def workspace_root() -> Path:
+ """Return ``external/ipfs_datasets`` for this file's checkout."""
+
+ return Path(__file__).resolve().parents[3]
+
+
+_MODULES = (
+ ("compiler", "ipfs_datasets_py.logic.legal_ir.canonical_compiler"),
+ ("decompiler", "ipfs_datasets_py.logic.legal_ir.canonical_decompiler"),
+ ("parser", "ipfs_datasets_py.logic.deontic.utils.deontic_parser"),
+)
+
+
+def require_workspace_logic_tree() -> dict[str, str]:
+ """Import the compiler, decompiler, and parser and require this checkout.
+
+ Prints one resolved-path line. Raises ``LogicTreePinError`` when any
+ module file sits outside ``workspace_root()``.
+ """
+
+ root = workspace_root()
+ resolved: dict[str, str] = {}
+ outside: list[str] = []
+ for label, name in _MODULES:
+ module = importlib.import_module(name)
+ raw = getattr(module, "__file__", "") or ""
+ path = Path(raw).resolve() if raw else Path()
+ resolved[label] = str(path)
+ if not path.is_file() or root not in path.parents:
+ outside.append(f"{label}={path}")
+ if outside:
+ raise LogicTreePinError(
+ "Legal compiler, decompiler, and parser must load from "
+ f"{root}. Resolved outside that tree: {', '.join(outside)}. "
+ "Put that tree first on PYTHONPATH, or point the editable install "
+ "at it. This check does not rewrite the install."
+ )
+ print("logic tree pin " + " ".join(f"{label}={path}" for label, path in resolved.items()))
+ return resolved
diff --git a/releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py b/releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b0939ac4cbf8d0c588760869708193d27285464
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py
@@ -0,0 +1,919 @@
+"""Experimental source-embedding conditioned native IR decoding at 384 dimensions.
+
+Reuses modal_latent_formula's residual projection, conditioning layer and GRU.
+A trained Legal checkpoint supplies every recurrent/projection tensor. New
+target-token rows receive trained parent lexical means, never random weights.
+
+Generated documents and fragments remain unqualified candidates. Native shape
+validation establishes neither source fidelity nor proof correctness.
+"""
+from __future__ import annotations
+
+from contextlib import contextmanager
+from copy import deepcopy
+from dataclasses import fields
+import hashlib
+import json
+import math
+from pathlib import Path
+import re
+import threading
+import time
+
+SCHEMA = "domain-384-typed-autoencoder/v1"
+DIMENSION = 384
+DOMAINS = ("intent_ir", "security_ir", "ui_ux_ir")
+MAX_BYTES = 48 * 1024 * 1024
+SPECIAL = ("", "", "")
+FALSE = {
+ "qualified": False,
+ "admitted": False,
+ "proof_authority": False,
+ "source_semantics_verified": False,
+ "publication_performed": False,
+}
+_TOKEN = re.compile(
+ r'"(?:[^"\\\x00-\x1f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"'
+ r'|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?'
+ r'|true|false|null|[{}\[\],:]'
+)
+_SHA = re.compile(r"[0-9a-f]{64}\Z")
+_CPU_LOCK = threading.RLock()
+
+
+def _require(condition, message):
+ if not condition:
+ raise ValueError(message)
+
+
+def _raw(value):
+ return json.dumps(
+ value, sort_keys=True, separators=(",", ":"),
+ ensure_ascii=True, allow_nan=False,
+ ).encode()
+
+
+def digest(value):
+ return hashlib.sha256(_raw(value)).hexdigest()
+
+
+def _parse(raw):
+ def unique(pairs):
+ result = {}
+ for key, value in pairs:
+ _require(key not in result, "duplicate JSON key")
+ result[key] = value
+ return result
+
+ def invalid(_):
+ raise ValueError("nonfinite JSON value")
+
+ return json.loads(raw, object_pairs_hook=unique, parse_constant=invalid)
+
+
+def _preserved(original, native):
+ """Reject fields silently dropped or coerced by permissive native loaders."""
+ if type(original) is dict:
+ return (
+ type(native) is dict
+ and all(k in native and _preserved(v, native[k])
+ for k, v in original.items())
+ )
+ if type(original) is list:
+ return (
+ type(native) is list
+ and len(original) == len(native)
+ and all(_preserved(a, b) for a, b in zip(original, native))
+ )
+ return type(original) is type(native) and original == native
+
+
+def validate_target(domain, target):
+ """Validate a compact native document or explicitly named native fragment.
+
+ Supported fragment wrappers are ``{kind, document}`` with kinds
+ ``intent_rich_ast``, ``program_expression`` or ``ui_component``.
+
+ ProgramExpression validation is local: references still require a complete
+ ProgramIR to establish referential and type correctness. Missing defaults
+ may be omitted; supplied fields must survive the native loader exactly.
+ """
+ _require(
+ domain in DOMAINS and type(target) is dict,
+ "supported domain and typed target required",
+ )
+ _require(len(_raw(target)) <= 128 * 1024, "target exceeds bound")
+ kind, document = "document", target
+ if set(target) == {"kind", "document"}:
+ kind, document = target["kind"], target["document"]
+ _require(type(document) is dict, "fragment document must be an object")
+
+ if domain == "intent_ir":
+ if kind == "intent_rich_ast":
+ from ...logic.intent_ir.formalize.rich_grammar import validate_ast
+ native = deepcopy(validate_ast(document))
+ else:
+ _require(kind == "document", "unsupported Intent fragment")
+ from ...logic.intent_ir.decoder import decode_intent_ir
+ native = decode_intent_ir(document).to_dict()
+ elif domain == "security_ir":
+ if kind == "program_expression":
+ from ...logic.software_verification.program import ProgramExpression
+ native = ProgramExpression.from_dict(document).to_dict()
+ else:
+ _require(kind == "document", "unsupported Security fragment")
+ from ...logic.security_ir.model import SecurityIR
+ native = SecurityIR.from_dict(document).to_dict()
+ else:
+ if kind == "ui_component":
+ from ...logic.ui_ux_ir.schema import UIComponent
+ _require(
+ set(document) <= {field.name for field in fields(UIComponent)},
+ "unknown UI component field",
+ )
+ values = deepcopy(document)
+ for key, value in tuple(values.items()):
+ if key.endswith("_ids"):
+ _require(type(value) is list, "UI ID arrays must be lists")
+ values[key] = tuple(value)
+ component = UIComponent(**values)
+ component.validate()
+ native = component.to_dict()
+ else:
+ _require(kind == "document", "unsupported UI fragment")
+ from ...logic.ui_ux_ir.decoder import decode_ui_ir
+ native = decode_ui_ir(document).to_dict()
+
+ _require(
+ _preserved(document, native),
+ "native decoder dropped, reordered, or coerced target fields",
+ )
+ return {
+ "valid": True,
+ "domain_id": domain,
+ "kind": kind,
+ "canonical_ir": _parse(_raw(target)),
+ "native_ir": native,
+ "scope": (
+ "native_document" if kind == "document"
+ else "locally_validated_native_fragment"
+ ),
+ **FALSE,
+ }
+
+
+def _implementation():
+ from . import modal_latent_formula
+ from ...logic.intent_ir import decoder as intent_decoder, schema as intent_schema
+ from ...logic.intent_ir.formalize import rich_grammar
+ from ...logic.security_ir import model as security_model
+ from ...logic.software_verification import program
+ from ...logic.ui_ux_ir import decoder as ui_decoder, schema as ui_schema
+
+ modules = (
+ modal_latent_formula, intent_decoder, intent_schema, rich_grammar,
+ security_model, program, ui_decoder, ui_schema,
+ )
+ return {
+ "runtime": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
+ "dependencies": {
+ module.__name__: hashlib.sha256(Path(module.__file__).read_bytes()).hexdigest()
+ for module in modules
+ },
+ "scope": "listed_numerical_and_native_validator_modules_only",
+ }
+
+
+@contextmanager
+def _cpu():
+ """Serialize this runtime's thread-count changes and restore caller state."""
+ import torch
+ with _CPU_LOCK:
+ previous = torch.get_num_threads()
+ torch.set_num_threads(1)
+ try:
+ yield torch
+ finally:
+ torch.set_num_threads(previous)
+
+
+def _vector(value):
+ _require(
+ type(value) is list
+ and len(value) == DIMENSION
+ and all(
+ type(number) in (int, float)
+ and math.isfinite(number)
+ and abs(number) <= 1e6
+ for number in value
+ ),
+ "embedding must contain exactly 384 bounded finite numbers",
+ )
+
+
+def _rows(domain, rows, *, training):
+ _require(
+ type(rows) is list and 1 <= len(rows) <= 4096,
+ "bounded nonempty rows required",
+ )
+ expected = {"id", "source_text", "embedding"} | (
+ {"target"} if training else set()
+ )
+ seen = set()
+ for row in rows:
+ _require(
+ type(row) is dict and set(row) == expected,
+ "closed domain row schema required",
+ )
+ _require(
+ type(row["id"]) is str
+ and 0 < len(row["id"]) <= 256
+ and row["id"] not in seen,
+ "unique bounded row ID required",
+ )
+ _require(
+ type(row["source_text"]) is str
+ and 0 < len(row["source_text"]) <= 16384
+ and row["source_text"].strip(),
+ "bounded nonempty source provenance required",
+ )
+ _vector(row["embedding"])
+ if training:
+ validate_target(domain, row["target"])
+ seen.add(row["id"])
+ return deepcopy(rows)
+
+
+def _tokens(target):
+ raw = _raw(target).decode()
+ pieces = _TOKEN.findall(raw)
+ _require(
+ "".join(pieces) == raw and len(pieces) <= 1022,
+ "bounded JSON lexical target required",
+ )
+ return pieces
+
+
+def _config(options, parent_config):
+ defaults = {
+ "epochs": 80,
+ "max_seconds": 180.0,
+ "learning_rate": .003,
+ "batch_size": 8,
+ "seed": 1729,
+ "patience": 12,
+ "reconstruction_weight": .1,
+ "max_target_tokens": 512,
+ "embedding_provenance": {
+ "model_id": "caller_supplied",
+ "verified_by_runtime": False,
+ },
+ }
+ _require(
+ options is None
+ or type(options) is dict and set(options) <= set(defaults),
+ "unknown training option",
+ )
+ defaults.update(options or {})
+ for name, high in (
+ ("epochs", 1000), ("batch_size", 64), ("seed", 2**31 - 1),
+ ("patience", 1000), ("max_target_tokens", 1024),
+ ):
+ value = defaults[name]
+ _require(
+ type(value) is int
+ and (0 if name == "seed" else 1) <= value <= high,
+ "invalid " + name,
+ )
+ for name, high in (
+ ("max_seconds", 3600),
+ ("learning_rate", .1),
+ ("reconstruction_weight", 100),
+ ):
+ value = defaults[name]
+ _require(
+ type(value) in (int, float)
+ and math.isfinite(value)
+ and 0 < value <= high,
+ "invalid " + name,
+ )
+ _require(
+ type(defaults["embedding_provenance"]) is dict
+ and len(_raw(defaults["embedding_provenance"])) <= 16384,
+ "bounded embedding provenance required",
+ )
+ return {
+ **defaults,
+ **{
+ name: parent_config[name]
+ for name in ("hidden_size", "token_embedding_dim", "projection_width")
+ },
+ }
+
+
+def _transfer(parent, codec, config):
+ from . import modal_latent_formula as numerical
+ import torch
+
+ model = numerical._model({"dimension": DIMENSION}, codec, config)
+ prior = parent["model_state"]
+ old_vocab = parent["codec"]["target_vocabulary"]
+ positions = {token: index for index, token in enumerate(old_vocab)}
+ lexical = {"target_embedding.weight", "output.weight", "output.bias"}
+ transferred, inherited, mapped = {}, [], []
+ for name, template in model.state_dict().items():
+ _require(name in prior, "parent is missing numerical tensor " + name)
+ value = torch.tensor(prior[name], dtype=torch.float32)
+ _require(bool(torch.isfinite(value).all()), "nonfinite parent tensor")
+ if name in lexical:
+ _require(
+ value.shape[0] == len(old_vocab)
+ and value.shape[1:] == template.shape[1:],
+ "parent lexical shape differs",
+ )
+ mean = value.mean(0)
+ value = torch.stack([
+ value[positions[token]] if token in positions else mean
+ for token in codec["target_vocabulary"]
+ ])
+ mapped.append(name)
+ else:
+ _require(value.shape == template.shape, "parent architecture differs")
+ inherited.append(name)
+ transferred[name] = value
+ model.load_state_dict(transferred, strict=True)
+ return model, {
+ "exact_inherited_tensors": sorted(inherited),
+ "lexical_mapped_tensors": sorted(mapped),
+ "new_token_initialization": "trained_parent_lexical_row_mean",
+ "random_parameters_used": False,
+ "parent_modified": False,
+ "initial_state_sha256": digest({
+ name: tensor.tolist() for name, tensor in transferred.items()
+ }),
+ }
+
+
+def _batch(torch, rows, vocabulary, max_tokens):
+ positions = {token: index for index, token in enumerate(vocabulary)}
+ encoded = []
+ for row in rows:
+ tokens = _tokens(row["target"])
+ _require(
+ len(tokens) + 2 <= max_tokens,
+ "target exceeds configured token limit",
+ )
+ missing = sorted(set(tokens) - set(positions))
+ _require(
+ not missing,
+ "target token outside training vocabulary: " + str(missing[:3]),
+ )
+ encoded.append([1] + [positions[token] for token in tokens] + [2])
+ width = max(map(len, encoded))
+ return (
+ torch.tensor([row["embedding"] for row in rows], dtype=torch.float32),
+ torch.tensor([
+ row + [0] * (width - len(row)) for row in encoded
+ ], dtype=torch.long),
+ )
+
+
+def _loss(torch, model, data, targets, config):
+ projected, logits = model(data, targets[:, :-1])
+ ce = torch.nn.functional.cross_entropy(
+ logits.reshape(-1, logits.shape[-1]),
+ targets[:, 1:].reshape(-1),
+ ignore_index=0,
+ )
+ mse = torch.nn.functional.mse_loss(projected, data)
+ return ce + config["reconstruction_weight"] * mse, ce, mse
+
+
+def _metrics(torch, model, batch, config):
+ with torch.inference_mode():
+ loss, ce, mse = _loss(torch, model, *batch, config)
+ _require(
+ all(bool(torch.isfinite(value)) for value in (loss, ce, mse)),
+ "nonfinite evaluation",
+ )
+ return {
+ "objective": float(loss),
+ "token_cross_entropy": float(ce),
+ "embedding_mse": float(mse),
+ }
+
+
+def train(domain, training_rows, validation_rows, *, parent_projection, config=None):
+ """Fork a trained Legal 384D projection into a distinct domain checkpoint.
+
+ parent_projection is a complete modal-latent-formula checkpoint or its
+ {path, sha256} descriptor. Only embeddings condition the neural decoder.
+ Validation selects weights; test examples never enter this API.
+ """
+ from . import modal_latent_formula as numerical
+
+ original_parent = None
+ if type(parent_projection) is dict and set(parent_projection) == {"path", "sha256"}:
+ parent_path = Path(parent_projection["path"])
+ _require(
+ parent_path.is_file() and parent_path.stat().st_size <= MAX_BYTES,
+ "bounded parent file required",
+ )
+ original_parent = parent_path.read_bytes()
+ _require(
+ hashlib.sha256(original_parent).hexdigest() == parent_projection["sha256"],
+ "parent hash differs",
+ )
+ parent = _parse(original_parent)
+ parent_sha = parent_projection["sha256"]
+ else:
+ parent = deepcopy(parent_projection)
+ parent_sha = digest(parent)
+
+ with _cpu() as torch:
+ numerical.validate_checkpoint(parent)
+ _require(
+ parent["binding"]["dimension"] == DIMENSION
+ and parent["progress"]["optimizer_steps"] > 0,
+ "trained 384D Legal parent required",
+ )
+ train_rows = _rows(domain, training_rows, training=True)
+ validation = _rows(domain, validation_rows, training=True)
+ keys = (
+ lambda row: row["id"],
+ lambda row: " ".join(row["source_text"].casefold().split()),
+ lambda row: digest(row["embedding"]),
+ )
+ for key in keys:
+ _require(
+ not {key(row) for row in train_rows}
+ & {key(row) for row in validation},
+ "training/validation identity, source, or embedding overlap",
+ )
+
+ options = _config(config, parent["config"])
+ vocabulary = [
+ *SPECIAL,
+ *sorted({
+ token
+ for row in train_rows
+ for token in _tokens(row["target"])
+ }),
+ ]
+ _require(len(vocabulary) <= 4096, "training vocabulary exceeds bound")
+ codec = {
+ "schema": "typed-json-lexical/v1",
+ "target_vocabulary": vocabulary,
+ }
+ data, labels = _batch(
+ torch, train_rows, vocabulary, options["max_target_tokens"]
+ )
+ validation_batch = _batch(
+ torch, validation, vocabulary, options["max_target_tokens"]
+ )
+ model, lineage = _transfer(parent, codec, options)
+ optimizer = torch.optim.Adam(
+ model.parameters(), lr=options["learning_rate"]
+ )
+ before = _metrics(torch, model, validation_batch, options)
+ best, best_state, selected_epoch = before, deepcopy(model.state_dict()), 0
+ generator = torch.Generator().manual_seed(options["seed"])
+ started = time.monotonic()
+ steps = seen_tokens = examples_seen = stale = 0
+ optimizer_seconds = validation_seconds = 0.0
+ history, stop = [], "epoch_budget"
+
+ for epoch in range(options["epochs"]):
+ model.train()
+ order = torch.randperm(len(train_rows), generator=generator)
+ complete = True
+ for offset in range(0, len(train_rows), options["batch_size"]):
+ if time.monotonic() - started >= options["max_seconds"]:
+ complete, stop = False, "deadline"
+ break
+ step_started = time.monotonic()
+ index = order[offset:offset + options["batch_size"]]
+ batch_target = labels[index]
+ width = int((batch_target != 0).sum(1).max())
+ batch_target = batch_target[:, :width]
+ optimizer.zero_grad(set_to_none=True)
+ loss, _, _ = _loss(
+ torch, model, data[index], batch_target, options
+ )
+ _require(bool(torch.isfinite(loss)), "nonfinite training loss")
+ loss.backward()
+ norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
+ _require(bool(torch.isfinite(norm)), "nonfinite gradient")
+ optimizer.step()
+ optimizer_seconds += time.monotonic() - step_started
+ steps += 1
+ examples_seen += len(index)
+ seen_tokens += int((batch_target[:, 1:] != 0).sum())
+ if not complete:
+ break
+
+ validation_started = time.monotonic()
+ observed = _metrics(torch, model, validation_batch, options)
+ validation_seconds += time.monotonic() - validation_started
+ # A deadline-truncated epoch cannot become the selected checkpoint.
+ selected = (
+ time.monotonic() - started < options["max_seconds"]
+ and observed["objective"] < best["objective"]
+ )
+ if selected:
+ best = observed
+ best_state = deepcopy(model.state_dict())
+ selected_epoch, stale = epoch + 1, 0
+ else:
+ stale += 1
+ history.append({
+ "epoch": epoch + 1, **observed, "selected": selected,
+ })
+ if stale >= options["patience"]:
+ stop = "validation_patience"
+ break
+ if time.monotonic() - started >= options["max_seconds"]:
+ stop = "deadline"
+ break
+
+ elapsed = time.monotonic() - started
+ _require(steps > 0, "no training steps completed")
+ model.load_state_dict(best_state)
+ weights = {
+ name: tensor.detach().tolist()
+ for name, tensor in model.state_dict().items()
+ }
+
+ def manifest(rows):
+ return [{
+ "id": row["id"],
+ "source_sha256": hashlib.sha256(row["source_text"].encode()).hexdigest(),
+ "embedding_sha256": digest(row["embedding"]),
+ "target_sha256": digest(row["target"]),
+ } for row in rows]
+
+ metrics = {
+ "before_validation": before,
+ "selected_validation": best,
+ "selected_epoch": selected_epoch,
+ "optimizer_steps": steps,
+ "training_tokens": seen_tokens,
+ "examples_seen": examples_seen,
+ "optimizer_seconds": optimizer_seconds,
+ "validation_seconds": validation_seconds,
+ "fit_seconds": elapsed,
+ "optimizer_tokens_per_second": seen_tokens / max(optimizer_seconds, 1e-9),
+ "optimizer_examples_per_second": examples_seen / max(optimizer_seconds, 1e-9),
+ "fit_tokens_per_second": seen_tokens / max(elapsed, 1e-9),
+ "stopped_reason": stop,
+ "history": history,
+ "test_used_for_selection": False,
+ "training": _metrics(torch, model, (data, labels), options),
+ }
+ checkpoint = {
+ "schema": SCHEMA,
+ "domain_id": domain,
+ "dimension": DIMENSION,
+ "architecture": numerical.ARCHITECTURE,
+ "codec": codec,
+ "config": options,
+ "implementation": _implementation(),
+ "parent_sha256": parent_sha,
+ "parent_binding": deepcopy(parent["binding"]),
+ "lineage": lineage,
+ "model_state": weights,
+ "weights_sha256": digest(weights),
+ "training_manifest": manifest(train_rows),
+ "validation_manifest": manifest(validation),
+ "training": metrics,
+ **FALSE,
+ }
+ _require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
+ if original_parent is not None:
+ _require(
+ parent_path.read_bytes() == original_parent,
+ "parent changed during training",
+ )
+ Runtime(checkpoint)
+ return {"checkpoint": checkpoint, "metrics": deepcopy(metrics)}
+
+
+class Runtime:
+ """Inference consumes source embeddings; gold targets are never accepted."""
+
+ def __init__(self, checkpoint):
+ from . import modal_latent_formula as numerical
+
+ required = {
+ "schema", "domain_id", "dimension", "architecture", "codec", "config",
+ "implementation", "parent_sha256", "parent_binding", "lineage",
+ "model_state", "weights_sha256", "training_manifest",
+ "validation_manifest", "training", *FALSE,
+ }
+ _require(
+ type(checkpoint) is dict
+ and set(checkpoint) == required
+ and checkpoint["schema"] == SCHEMA,
+ "closed domain checkpoint required",
+ )
+ _require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
+ _require(
+ checkpoint["domain_id"] in DOMAINS
+ and type(checkpoint["dimension"]) is int
+ and checkpoint["dimension"] == DIMENSION,
+ "checkpoint requires genuine 384D domain binding",
+ )
+ _require(
+ all(checkpoint[key] is False for key in FALSE),
+ "checkpoint cannot grant authority",
+ )
+ _require(
+ checkpoint["implementation"] == _implementation(),
+ "domain implementation pins differ",
+ )
+ _require(
+ checkpoint["architecture"] == numerical.ARCHITECTURE,
+ "numerical architecture differs",
+ )
+ _require(
+ type(checkpoint["parent_binding"]) is dict
+ and checkpoint["parent_binding"].get("dimension") == DIMENSION
+ and type(checkpoint["parent_sha256"]) is str
+ and _SHA.fullmatch(checkpoint["parent_sha256"]),
+ "invalid parent binding",
+ )
+ codec = checkpoint["codec"]
+ _require(
+ type(codec) is dict
+ and set(codec) == {"schema", "target_vocabulary"}
+ and codec["schema"] == "typed-json-lexical/v1",
+ "invalid target codec",
+ )
+ vocabulary = codec["target_vocabulary"]
+ _require(
+ type(vocabulary) is list
+ and 4 <= len(vocabulary) <= 4096
+ and vocabulary[:3] == list(SPECIAL)
+ and all(type(token) is str and 0 < len(token) <= 16384 for token in vocabulary)
+ and vocabulary[3:] == sorted(set(vocabulary[3:]))
+ and not set(vocabulary[3:]) & set(SPECIAL),
+ "invalid training vocabulary",
+ )
+ _require(
+ all(_TOKEN.fullmatch(token) is not None for token in vocabulary[3:]),
+ "invalid JSON vocabulary token",
+ )
+ config = checkpoint["config"]
+ config_fields = {
+ "epochs", "max_seconds", "learning_rate", "batch_size", "seed",
+ "patience", "reconstruction_weight", "max_target_tokens",
+ "embedding_provenance", "hidden_size", "token_embedding_dim",
+ "projection_width",
+ }
+ _require(
+ type(config) is dict and set(config) == config_fields,
+ "closed model configuration required",
+ )
+ for key, low, high in (
+ ("hidden_size", 8, 128),
+ ("token_embedding_dim", 8, 64),
+ ("projection_width", 1, 64),
+ ):
+ _require(
+ type(config[key]) is int and low <= config[key] <= high,
+ "invalid model shape",
+ )
+ options = {
+ key: value for key, value in config.items()
+ if key not in {"hidden_size", "token_embedding_dim", "projection_width"}
+ }
+ _require(_config(options, config) == config, "configuration differs")
+ _require(
+ digest(checkpoint["model_state"]) == checkpoint["weights_sha256"],
+ "weight digest differs",
+ )
+ training = checkpoint["training"]
+ _require(
+ type(training) is dict
+ and type(training.get("optimizer_steps")) is int
+ and training["optimizer_steps"] > 0
+ and type(training.get("selected_epoch")) is int
+ and 0 <= training["selected_epoch"] <= config["epochs"]
+ and training.get("test_used_for_selection") is False,
+ "invalid training provenance",
+ )
+ for name in ("training_manifest", "validation_manifest"):
+ rows = checkpoint[name]
+ _require(
+ type(rows) is list and 1 <= len(rows) <= 4096,
+ "invalid split manifest",
+ )
+ seen = set()
+ for row in rows:
+ _require(
+ type(row) is dict
+ and set(row) == {
+ "id", "source_sha256", "embedding_sha256", "target_sha256"
+ }
+ and type(row["id"]) is str
+ and 0 < len(row["id"]) <= 256
+ and row["id"] not in seen,
+ "invalid split row",
+ )
+ _require(
+ all(
+ type(row[key]) is str and _SHA.fullmatch(row[key])
+ for key in ("source_sha256", "embedding_sha256", "target_sha256")
+ ),
+ "invalid split digest",
+ )
+ seen.add(row["id"])
+ for key in ("id", "source_sha256", "embedding_sha256"):
+ _require(
+ not {row[key] for row in checkpoint["training_manifest"]}
+ & {row[key] for row in checkpoint["validation_manifest"]},
+ "checkpoint split overlap",
+ )
+
+ with _cpu():
+ model = numerical._model({"dimension": DIMENSION}, codec, config)
+ state = checkpoint["model_state"]
+ _require(
+ type(state) is dict and set(state) == set(model.state_dict()),
+ "model tensor names differ",
+ )
+ model.load_state_dict({
+ name: numerical._tensor(state[name], template, name)
+ for name, template in model.state_dict().items()
+ }, strict=True)
+ self.checkpoint = deepcopy(checkpoint)
+ self.model = model.eval()
+
+ def describe(self):
+ checkpoint = self.checkpoint
+ return {
+ "schema": SCHEMA,
+ "domain_id": checkpoint["domain_id"],
+ "dimension": DIMENSION,
+ "input_representation": "explicit_source_embedding_384",
+ "architecture": checkpoint["architecture"],
+ "weights_sha256": checkpoint["weights_sha256"],
+ "parent_sha256": checkpoint["parent_sha256"],
+ "embedding_provenance": deepcopy(
+ checkpoint["config"]["embedding_provenance"]
+ ),
+ "embedding_provenance_verified_by_runtime": False,
+ "trained_optimizer_steps": checkpoint["training"]["optimizer_steps"],
+ "selected_epoch": checkpoint["training"]["selected_epoch"],
+ "output_scope": (
+ "native_documents_or_explicit_local_fragments"
+ "_in_training_target_vocabulary"
+ ),
+ "source_text_is_neural_input": False,
+ "sample_memory_used": False,
+ "independent_source_fidelity_check_required": True,
+ **FALSE,
+ }
+
+ def infer(self, rows, *, weight_ablation=None):
+ rows = _rows(self.checkpoint["domain_id"], rows, training=False)
+ _require(
+ weight_ablation in (
+ None, "zero_projection", "zero_condition", "zero_decoder"
+ ),
+ "unknown weight ablation",
+ )
+ model = self.model if weight_ablation is None else deepcopy(self.model)
+ vocabulary = self.checkpoint["codec"]["target_vocabulary"]
+ config = self.checkpoint["config"]
+ reports = []
+ with _cpu() as torch, torch.inference_mode():
+ if weight_ablation:
+ for name, parameter in model.named_parameters():
+ selected = (
+ weight_ablation == "zero_projection"
+ and name.startswith("projection_")
+ ) or (
+ weight_ablation == "zero_condition"
+ and name.startswith("condition.")
+ ) or (
+ weight_ablation == "zero_decoder"
+ and name.startswith(("decoder.", "output."))
+ )
+ if selected:
+ parameter.zero_()
+ for row in rows:
+ embedded = torch.tensor(
+ [row["embedding"]], dtype=torch.float32
+ )
+ projected = model.project(embedded)
+ _require(
+ bool(torch.isfinite(projected).all()),
+ "nonfinite reconstructed embedding",
+ )
+ hidden = model.start(projected)
+ current = torch.tensor([[1]], dtype=torch.long)
+ generated, ended = [], False
+ for _ in range(config["max_target_tokens"] - 1):
+ logits, hidden = model.next_logits(current, hidden)
+ _require(
+ bool(torch.isfinite(logits).all())
+ and bool(torch.isfinite(hidden).all()),
+ "nonfinite generated logits or hidden state",
+ )
+ index = int(logits[0, -1].argmax())
+ if index == 2:
+ ended = True
+ break
+ if index in (0, 1):
+ break
+ generated.append(vocabulary[index])
+ current = torch.tensor([[index]], dtype=torch.long)
+ candidate = None
+ status, reason = "fail_open_invalid_output", None
+ if ended:
+ try:
+ value = _parse("".join(generated))
+ candidate = validate_target(
+ self.checkpoint["domain_id"], value
+ )["canonical_ir"]
+ status = "unqualified_candidate"
+ except (
+ ValueError, TypeError, KeyError, RecursionError
+ ) as exc:
+ reason = str(exc)[:512]
+ reports.append({
+ "id": row["id"],
+ "source_sha256": hashlib.sha256(
+ row["source_text"].encode()
+ ).hexdigest(),
+ "status": status,
+ "reason": reason,
+ "candidate_ir": candidate,
+ "generated_tokens": generated,
+ "ended": ended,
+ "reconstructed_embedding": projected[0].tolist(),
+ "weight_ablation": weight_ablation,
+ "weights_sha256": self.checkpoint["weights_sha256"],
+ "target_access": False,
+ "teacher_forcing": False,
+ "continue_planning": True,
+ **FALSE,
+ })
+ return {
+ "schema": SCHEMA,
+ "domain_id": self.checkpoint["domain_id"],
+ "dimension": DIMENSION,
+ "rows": reports,
+ **FALSE,
+ }
+
+
+def evaluate(checkpoint, rows):
+ """Post-selection evaluation; gold targets never enter numerical inference."""
+ runtime = Runtime(checkpoint)
+ prepared = _rows(checkpoint["domain_id"], rows, training=True)
+ report = runtime.infer([
+ {key: row[key] for key in ("id", "source_text", "embedding")}
+ for row in prepared
+ ])
+ for actual, gold in zip(report["rows"], prepared):
+ actual["exact_target"] = actual["candidate_ir"] == gold["target"]
+ report["exact_targets"] = sum(
+ row["exact_target"] for row in report["rows"]
+ )
+ report["valid_candidates"] = sum(
+ row["candidate_ir"] is not None for row in report["rows"]
+ )
+ report["count"] = len(prepared)
+ return report
+
+
+def load_checkpoint(path, *, expected_sha256, expected_domain):
+ """Load bounded inert JSON with an explicit digest and expected domain."""
+ path = Path(path)
+ _require(
+ path.is_file()
+ and not path.is_symlink()
+ and 0 < path.stat().st_size <= MAX_BYTES,
+ "bounded regular checkpoint required",
+ )
+ raw = path.read_bytes()
+ _require(
+ len(raw) <= MAX_BYTES
+ and hashlib.sha256(raw).hexdigest() == expected_sha256,
+ "checkpoint bytes differ",
+ )
+ checkpoint = _parse(raw)
+ _require(
+ type(checkpoint) is dict
+ and checkpoint.get("domain_id") == expected_domain,
+ "checkpoint belongs to another domain",
+ )
+ return Runtime(checkpoint)
+
+
+__all__ = [
+ "SCHEMA", "DIMENSION", "DOMAINS", "Runtime", "train", "evaluate",
+ "validate_target", "load_checkpoint", "digest",
+]
diff --git a/releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py b/releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py
new file mode 100644
index 0000000000000000000000000000000000000000..18b61e862ca56d5dc162aa90486eda3f5bf13de9
--- /dev/null
+++ b/releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py
@@ -0,0 +1,209 @@
+"""Versioned bounded Intent syntax; training labels and post-inference checks.
+
+This parser is never a replacement for learned predictions. Its explicit
+source grammar supplies weak training supervision and checks complete model
+outputs after inference. No parser slots are passed to the neural encoder.
+"""
+from __future__ import annotations
+
+import re
+
+SCHEMA = "intent-rich-grammar/v1"
+MODALS = {"intended":"intends to", "required":"must", "prohibited":"must not",
+ "permitted":"may", "recommended":"should"}
+SURFACES = {"intends to":"intended", "must":"required", "shall":"required",
+ "must not":"prohibited", "shall not":"prohibited", "do not":"prohibited", "never":"prohibited",
+ "may":"permitted", "should":"recommended", "is required to":"required",
+ "is forbidden to":"prohibited", "is allowed to":"permitted"}
+_ATOM = r"[A-Za-z][A-Za-z0-9_-]*"
+_WORD = re.compile(_ATOM + r"\Z")
+_SLOT = re.compile(r"[A-Za-z0-9_./:`-]+(?: [A-Za-z0-9_./:`-]+)*\Z")
+_UNSUPPORTED = frozenset("unless until before after while once whenever wherever assuming provided given because whether whereas since notwithstanding except without otherwise meanwhile subsequently finally each every all any either neither both none no some a an only always eventually exactly least most whose which whom".split())
+_REFERENCES = frozenset("i me my mine myself you your yours yourself yourselves we us our ours ourselves he him his himself she her hers herself it its itself they them their theirs themselves this that these those former latter above below previous same such here there".split())
+_GRAMMAR_WORDS = frozenset("and or then if must shall may should not never intends is are was were be been being has have had does did can could would will to".split())
+
+
+def _slot(value, maximum=160, words=16):
+ if (type(value) is not str or not 0 < len(value) <= maximum or len(value.split()) > words
+ or not _SLOT.fullmatch(value) or " " in value or value.count('`') % 2):
+ raise ValueError("bounded case-preserving lexical slot required")
+ return value
+
+
+def validate_ast(ast):
+ if type(ast) is not dict:
+ raise ValueError("closed rich Intent AST required")
+ kind = ast.get("kind")
+ if type(kind) is not str:
+ raise ValueError("declared rich constructor required")
+ if kind == "atom" and set(ast) == {"kind","actor","action","object","modality"}:
+ _slot(ast["actor"], words=4); _slot(ast["object"])
+ if (type(ast['action']) is not str or not _WORD.fullmatch(ast["action"])
+ or ast["action"] != ast["action"].lower() or type(ast['modality']) is not str or ast["modality"] not in MODALS):
+ raise ValueError("stable action and declared modality required")
+ elif kind in {"and","or","then"} and set(ast) == {"kind","left","right"}:
+ for key in ("left","right"):
+ if type(ast[key]) is not dict or ast[key].get("kind") != "atom":
+ raise ValueError("first rich grammar permits only two atomic branches")
+ validate_ast(ast[key])
+ elif kind == "if" and set(ast) == {"kind","guard","body"}:
+ guard = ast["guard"]
+ if (type(guard) is not dict or set(guard) != {"subject","property","negated"}
+ or type(guard["negated"]) is not bool):
+ raise ValueError("closed atomic condition required")
+ _slot(guard["subject"], words=4)
+ if (type(guard["property"]) is not str or not _WORD.fullmatch(guard["property"])
+ or guard['property'].lower() in _GRAMMAR_WORDS | _UNSUPPORTED | _REFERENCES):
+ raise ValueError("atomic guard property required")
+ if type(ast['body']) is not dict or ast["body"].get("kind") != "atom":
+ raise ValueError("one guarded atomic norm required")
+ validate_ast(ast["body"])
+ else:
+ raise ValueError("unsupported rich Intent constructor or fields")
+ return ast
+
+
+def ast_to_sequence(ast):
+ validate_ast(ast)
+ kind = ast["kind"]
+ if kind == "atom":
+ return " ".join(f"<{key}> {ast[key]}" for key in ("actor","action","object","modality"))
+ if kind in {"and","or","then"}:
+ return f"<{kind}> {ast_to_sequence(ast['left'])} {ast_to_sequence(ast['right'])}"
+ guard = ast["guard"]
+ return (f" {guard['subject']} {guard['property']} "
+ f" {'negative' if guard['negated'] else 'positive'} {ast_to_sequence(ast['body'])}")
+
+
+def _unspace(value):
+ value = " ".join(value.split())
+ value = re.sub(r"\s*([./:_-])\s*",r"\1",value)
+ return re.sub(r"`\s*([^`]+?)\s*`", lambda m:'`'+m[1]+'`',value)
+
+
+def sequence_to_ast(text):
+ if type(text) is not str or not 0 < len(text) <= 4096:
+ raise ValueError("bounded predicted rich sequence required")
+ text = text.strip()
+ binary = re.fullmatch(r"<(and|or|then)>\s+(.+?)\s+\s+(.+)",text)
+ guard = re.fullmatch(r"\s+([^<>]+?)\s+\s+([^<>]+?)\s+\s+(positive|negative)\s+\s+(.+)",text)
+ if binary:
+ value = {"kind":binary[1],"left":sequence_to_ast(binary[2]),"right":sequence_to_ast(binary[3])}
+ elif guard:
+ value = {"kind":"if","guard":{"subject":_unspace(guard[1]),"property":_unspace(guard[2]),
+ "negated":guard[3]=="negative"},"body":sequence_to_ast(guard[4])}
+ else:
+ match = re.fullmatch(r"\s+([^<>]+?)\s+\s+([^<>]+?)\s+