From 234a650277d286f2ebec104eb65ce9456f80667c Mon Sep 17 00:00:00 2001 From: Chris R Date: Mon, 2 Nov 2026 21:47:57 +1100 Subject: [PATCH] Audit finite input coverage and copied-stage source constraints --- .../ARTIFACTS.json | 186 +++ .../h25-c05-finite-cover-source-audit/LICENSE | 201 +++ .../NOTICE.md | 7 + .../README.md | 46 + .../SOURCE-FINDINGS.json | 843 ++++++++++ .../SOURCE-ORIGIN.json | 195 +++ .../SOURCES.json | 18 + .../TASK.json | 60 + .../VALIDATION.json | 78 + .../VERIFY.json | 32 + .../audit/SOURCE-GATE-CLOSE-v1.json | 49 + .../audit/channel-cap-review-v1.json | 173 ++ .../audit/channel-cap-review-v1.md | 59 + .../audit/compatibility-review-v1.json | 187 +++ .../audit/compatibility-review-v1.md | 57 + .../evidence/EXPORT-check-only.txt | 1 + .../evidence/EXPORT-cold-normal.txt | 1 + .../evidence/EXPORT-cold-optimized.txt | 1 + .../evidence/EXPORT-registered-static.txt | 5 + .../evidence/UNIT01-INDEPENDENT-REVIEW.json | 24 + .../evidence/UNIT01-SOURCE-CLOSE-v1.json | 68 + .../h25-c05-finite-cover-source-audit/run.py | 11 + .../snapshot/CONDITIONS.json | 108 ++ .../snapshot/INTERFACE.json | 180 +++ .../snapshot/cold_build_evidence.py.txt | 312 ++++ .../snapshot/full_driver.py.txt | 851 ++++++++++ .../snapshot/h25_parent_supervisor.py.txt | 475 ++++++ .../snapshot/native_tcb_controls_v1.py.txt | 97 ++ .../snapshot/native_tcb_v1.py.txt | 202 +++ .../snapshot/parent_closure_v1.py.txt | 270 ++++ .../snapshot/parent_completion_v1.py.txt | 880 +++++++++++ .../snapshot/parent_domain_v1.py.txt | 450 ++++++ .../snapshot/sealed_elf_profile_v2.py.txt | 1388 +++++++++++++++++ .../snapshot/v03_constructor_test_v1.py.txt | 259 +++ .../v03_source_refusal_observer_v1.py.txt | 290 ++++ .../snapshot/variant_driver_v1.py.txt | 819 ++++++++++ .../verify.py | 87 ++ 37 files changed, 8970 insertions(+) create mode 100644 research/h25-c05-finite-cover-source-audit/ARTIFACTS.json create mode 100644 research/h25-c05-finite-cover-source-audit/LICENSE create mode 100644 research/h25-c05-finite-cover-source-audit/NOTICE.md create mode 100644 research/h25-c05-finite-cover-source-audit/README.md create mode 100644 research/h25-c05-finite-cover-source-audit/SOURCE-FINDINGS.json create mode 100644 research/h25-c05-finite-cover-source-audit/SOURCE-ORIGIN.json create mode 100644 research/h25-c05-finite-cover-source-audit/SOURCES.json create mode 100644 research/h25-c05-finite-cover-source-audit/TASK.json create mode 100644 research/h25-c05-finite-cover-source-audit/VALIDATION.json create mode 100644 research/h25-c05-finite-cover-source-audit/VERIFY.json create mode 100644 research/h25-c05-finite-cover-source-audit/audit/SOURCE-GATE-CLOSE-v1.json create mode 100644 research/h25-c05-finite-cover-source-audit/audit/channel-cap-review-v1.json create mode 100644 research/h25-c05-finite-cover-source-audit/audit/channel-cap-review-v1.md create mode 100644 research/h25-c05-finite-cover-source-audit/audit/compatibility-review-v1.json create mode 100644 research/h25-c05-finite-cover-source-audit/audit/compatibility-review-v1.md create mode 100644 research/h25-c05-finite-cover-source-audit/evidence/EXPORT-check-only.txt create mode 100644 research/h25-c05-finite-cover-source-audit/evidence/EXPORT-cold-normal.txt create mode 100644 research/h25-c05-finite-cover-source-audit/evidence/EXPORT-cold-optimized.txt create mode 100644 research/h25-c05-finite-cover-source-audit/evidence/EXPORT-registered-static.txt create mode 100644 research/h25-c05-finite-cover-source-audit/evidence/UNIT01-INDEPENDENT-REVIEW.json create mode 100644 research/h25-c05-finite-cover-source-audit/evidence/UNIT01-SOURCE-CLOSE-v1.json create mode 100644 research/h25-c05-finite-cover-source-audit/run.py create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/CONDITIONS.json create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/INTERFACE.json create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/cold_build_evidence.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/full_driver.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/h25_parent_supervisor.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/native_tcb_controls_v1.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/native_tcb_v1.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/parent_closure_v1.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/parent_completion_v1.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/parent_domain_v1.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/sealed_elf_profile_v2.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/v03_constructor_test_v1.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/v03_source_refusal_observer_v1.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/snapshot/variant_driver_v1.py.txt create mode 100644 research/h25-c05-finite-cover-source-audit/verify.py diff --git a/research/h25-c05-finite-cover-source-audit/ARTIFACTS.json b/research/h25-c05-finite-cover-source-audit/ARTIFACTS.json new file mode 100644 index 0000000000..c24088d598 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/ARTIFACTS.json @@ -0,0 +1,186 @@ +{ + "files": [ + { + "bytes": 11357, + "path": "LICENSE", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4" + }, + { + "bytes": 1158, + "path": "NOTICE.md", + "sha256": "eaf6add076741a1a14600ee60e23fecbd5c35a8c887b506cee2b6714c66de2a7" + }, + { + "bytes": 8601, + "path": "README.md", + "sha256": "5cb9d50c13a07683f4227071adc8bb785cc8b3130214e0ae32f50cb54ba1a271" + }, + { + "bytes": 33945, + "path": "SOURCE-FINDINGS.json", + "sha256": "3190af32adeb3f502de93fc6e93d819d9f97da6fa43abc0f060d3c2b515cc31a" + }, + { + "bytes": 10347, + "path": "SOURCE-ORIGIN.json", + "sha256": "e7810fbd5aa14913cb66a592bf1a6cfdd935284c33e30d44f354686774fb9822" + }, + { + "bytes": 584, + "path": "SOURCES.json", + "sha256": "911ffe8b456c49ccd19ee42c8e21b226a56dacba515e857300aa28cc1db87be7" + }, + { + "bytes": 4136, + "path": "TASK.json", + "sha256": "ccc7233b2c8f3b73351b26a94a6e36ebf88705e93b51cae2b76e828921c1167d" + }, + { + "bytes": 2598, + "path": "VALIDATION.json", + "sha256": "70dc9a8b1bab1850c0c3a0d46ac91c0ef60defa609cb1e8f80aa6099da461e21" + }, + { + "bytes": 702, + "path": "VERIFY.json", + "sha256": "4b37d3ae792c72f438373053d008e8edb9053ec6ccdb72e55eddc2b4b3314584" + }, + { + "bytes": 2102, + "path": "audit/SOURCE-GATE-CLOSE-v1.json", + "sha256": "b26cff1bd0c70ecddb22efab21e5f8916c1985d79ae421e51308a438910db6fd" + }, + { + "bytes": 8168, + "path": "audit/channel-cap-review-v1.json", + "sha256": "b1c3dbee15a28d5ee9657ab3a113cd899a36ca737edf869de889469f467e14c7" + }, + { + "bytes": 13141, + "path": "audit/channel-cap-review-v1.md", + "sha256": "28512789545b2bca5bfa20e8b20100a882337b2b02237cde8643bc44b375b3f1" + }, + { + "bytes": 8664, + "path": "audit/compatibility-review-v1.json", + "sha256": "9dfa9168d69cba7adcd98bec567ee61db1ad98de90adc1c603195458f2164a49" + }, + { + "bytes": 10460, + "path": "audit/compatibility-review-v1.md", + "sha256": "62d2ef8657c06ca7816e5d625261af382d1b6e1eb1d7329dc0bf8d4ded2f1344" + }, + { + "bytes": 69, + "path": "evidence/EXPORT-check-only.txt", + "sha256": "5873404cb4424dca918a00d503569f3c29a3190fd029a007e1afb2006399f647" + }, + { + "bytes": 79, + "path": "evidence/EXPORT-cold-normal.txt", + "sha256": "74c7cad84f938c66a769504b1eb6eebb1ad7dc1ec154fbdc0c28959e9971d1d6" + }, + { + "bytes": 79, + "path": "evidence/EXPORT-cold-optimized.txt", + "sha256": "74c7cad84f938c66a769504b1eb6eebb1ad7dc1ec154fbdc0c28959e9971d1d6" + }, + { + "bytes": 477, + "path": "evidence/EXPORT-registered-static.txt", + "sha256": "73f32c8bb245dfa6cae2a6164faa5c1be7320b8f2fcadc90f34d0645ce46d4a7" + }, + { + "bytes": 1179, + "path": "evidence/UNIT01-INDEPENDENT-REVIEW.json", + "sha256": "84b94c41609b83f6307c553792c37ee29477a450fe3d09f2bd850318557071fd" + }, + { + "bytes": 2856, + "path": "evidence/UNIT01-SOURCE-CLOSE-v1.json", + "sha256": "4f41522472d31bb3904d24ddc0b0ac01aef63273e4f551575b6148457e23eed5" + }, + { + "bytes": 420, + "path": "run.py", + "sha256": "98f3169f75b721c10581a8f652a11e3d382f3758867b0812ab8e32d7007222c7" + }, + { + "bytes": 6940, + "path": "snapshot/CONDITIONS.json", + "sha256": "70e237d6ee4ac2ccaadf01615e8106999718eb1fbb3cf7644c9fc6d3fd4463fe" + }, + { + "bytes": 6956, + "path": "snapshot/INTERFACE.json", + "sha256": "30820f1f2d27d4d4306d8ba63db5329f89182912f7f915aede35b9ce62359491" + }, + { + "bytes": 16463, + "path": "snapshot/cold_build_evidence.py.txt", + "sha256": "aa0a315110e031e19291970c9611fe5e0f91465fa20eaec51e81186099563f78" + }, + { + "bytes": 38851, + "path": "snapshot/full_driver.py.txt", + "sha256": "f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0" + }, + { + "bytes": 23047, + "path": "snapshot/h25_parent_supervisor.py.txt", + "sha256": "cfb09a18dd10b597cc6d5a8139ee769bef679bc44ae029329755e3d97b055075" + }, + { + "bytes": 4889, + "path": "snapshot/native_tcb_controls_v1.py.txt", + "sha256": "63b1804caa7f89915662a1424f788c3becad13520e1f63212a338fb45aaa2c5a" + }, + { + "bytes": 11353, + "path": "snapshot/native_tcb_v1.py.txt", + "sha256": "865943df5cfdbf9383362d7fb2b76c6d0fd895cf0a0e20d550a26b579606b5d7" + }, + { + "bytes": 13400, + "path": "snapshot/parent_closure_v1.py.txt", + "sha256": "2d831cff8bd444de2d6941645d571e07618ede404a1f45692b557f61494b334a" + }, + { + "bytes": 54168, + "path": "snapshot/parent_completion_v1.py.txt", + "sha256": "d4ee1b7ce4a42b73261984ffb1b9ceb5bb0165223e04a253588f83b99f6981a5" + }, + { + "bytes": 20456, + "path": "snapshot/parent_domain_v1.py.txt", + "sha256": "9205e14d6661fb5df0597f0ad7b2206006f2d31f01f784805f64c13875663282" + }, + { + "bytes": 76453, + "path": "snapshot/sealed_elf_profile_v2.py.txt", + "sha256": "89ed8c777e6b72af2d6a3595037e7e92385924c6087d88010a27192633391016" + }, + { + "bytes": 14821, + "path": "snapshot/v03_constructor_test_v1.py.txt", + "sha256": "3f7aeb812e17a261062b378060964b1a1c45694e9258c177367ce6bb46623452" + }, + { + "bytes": 14205, + "path": "snapshot/v03_source_refusal_observer_v1.py.txt", + "sha256": "abf25690d3bee4a9783ee504567c29f7fb47da670e0ec95f57cb5944bf57264f" + }, + { + "bytes": 41337, + "path": "snapshot/variant_driver_v1.py.txt", + "sha256": "cdb1479253358508088f8aa0e1e92e6c75ffcc127e54552698598a02de061254" + }, + { + "bytes": 4473, + "path": "verify.py", + "sha256": "1b8028a50ea17aabc87d2cf7b66fc08da351addad68574c48d5f6406db36f3e9" + } + ], + "schema": "finite-cover-source-archive-artifacts-v1", + "scope": "Exact raw packet bytes excluding ARTIFACTS itself; no runtime or scientific admission" +} diff --git a/research/h25-c05-finite-cover-source-audit/LICENSE b/research/h25-c05-finite-cover-source-audit/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/research/h25-c05-finite-cover-source-audit/NOTICE.md b/research/h25-c05-finite-cover-source-audit/NOTICE.md new file mode 100644 index 0000000000..8d84c9b4ce --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/NOTICE.md @@ -0,0 +1,7 @@ +# Attribution and licenses + +Chris R / Clear1nsight, with substantial ChatGPT Pro / OpenAI Codex / GPT-6.1 Sol Max source consultation, independent agent review and archive preparation. Preserve original source authors and PR6321 / PR6029 / PR5864 lineage, unpaidmoon with Cursor/Grok for PR6339, and Douglas R. Colkitt's native/circuit/verification and research-package lineage. + +New audit/package glue is Apache-2.0 under the included repository LICENSE. Every inert source snapshot retains its complete original bytes and notices. Inclusion does not replace any source-specific notice. The packet contains Python/JSON source and decision records, with no GCC source/header corpus, native library, compiler binary, payload package or runtime image. + +The two frozen reviews refer to a private Pro consultation and other historical local records. Those references/hashes remain documentary external context. No chat, prompt, response or full workspace record is exported, opened by replay or required as a live input. Source/agent/archive acceptance is distinct from human, proof-kernel, original runtime, complete scientific or selected-frontier acceptance. diff --git a/research/h25-c05-finite-cover-source-audit/README.md b/research/h25-c05-finite-cover-source-audit/README.md new file mode 100644 index 0000000000..9c3f764828 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/README.md @@ -0,0 +1,46 @@ +# Finite-cover, copied-stage compatibility and channel-cap source audit + +The frozen Unit04 source gate closed without sufficient inputs for implementation. This archive preserves two independent source decision reviews and their exact original source basis. The useful result is conditional: a corrected exogenous-origin lemma, source-supported eligibility of a conforming fresh copied stage as a candidate class, an acyclic bootstrap/self-hash obligation, separate parent/child bounds, and confirmation that the earlier strict observer was already repaired. No concrete runtime layout, channel mechanism, cap fit, implementation, original activity completion or C05/V03 admission is established. + +## Accepted source decision and remaining premises + +For actual ordinary read occurrences, the conditional statement is `W_read ⊆ Occ(F) ∪ Occ(A)`, where F supplies frozen exogenous occurrences and A supplies earlier generated artifacts. Only exogenous ordinary-file origins satisfy `Origins_file(W_read) ⊆ Occ(F)`; non-file origins need separately represented namespace/launch/nonordinary facts N/L/K. Generated ordinary reads do not all become members of F. Closed generated provenance, dynamic determinants and a complete lifetime input/channel invariant remain premises. This source reading does not require a compiler-correctness theorem, and does not provide one. + +The original CONDITIONS C02/C07/C13 and INTERFACE contemplate independently admitted full installed/fresh stages and parent-owned immutable paths. The parent checks current bytes/modes and current directory identities; the reviewed predicates do not categorically freeze a historical host inode. A copied fresh-stage candidate may therefore be assessed under the unchanged objective. That does not admit any particular copied root, credentials, proc view, access policy or equivalence relation. All original configuration/source/command/stage/funding/execution and native/profile/first-refusal obligations remain independent and open; literal None/null gates are preserved. + +A driver embedding its own final source digest introduces the dependency that the interface's no-self-hash rule avoids. A compiler-input F / separately authenticated bootstrap P / generated A / nonordinary K partition helps only with a justified exclusion of compiler-relevant unrepresented P. Parent authentication alone does not prove compiler exclusion. Witness finalization must also be acyclic. The unchanged helper has no cwd/env or compiler-only policy installer argument at its Popen call; its original resource callback and inherited current producer context remain part of the exact source. No new confinement policy is implemented or inferred from these hashes. + +The child inventory remains 1..512 rows, 64 MiB per occurrence and 256 MiB per custody pass, with the original depth/node/text/container/wire limits. The separate parent limits are MAX_SOURCE_FILES=8192 and MAX_STAGE_ENTRIES=16384. Witness rows, bootstrap custody, generated areas, raw representation and physical work remain paid obligations. Authoring/payload corpus counts are not runtime occurrence counts and prove neither fit nor failure. No actual candidate bill or complete lifetime channel mechanism was supplied. Blanket read-only storage, proc denial/synthetic proc, an old serialized capability or an inherited token does not preserve the original mutable-control, genuine-process, native-mapping and same-parent requirements. + +The final strict observer's complete API was already repaired before Unit04: it statically corroborates complete Root/prefix/terminal frames, exact source lines and stream shape, while the legacy API remains terminal-site-only. Its retained source test rejects the three-line counterexample on the complete API, and the frozen independent review records the limited repair PASS. This archive parses that source/test and preserves the earlier receipt; it does not rerun either API or its old fixtures. Even the complete API grants no ownership, authenticity, currentness, first-error delivery or admission authority. + +## Exact archive and registered check + +The exact frozen compatibility/channel-cap Markdown and JSON records, plus SOURCE-GATE-CLOSE-v1.json, are under `audit/`. Essential original CONDITIONS/INTERFACE/variant, parent/domain/closure/supervisor, helper/native/control/static-ELF/Root and final observer/test sources are inert `.py.txt` or JSON snapshots under `snapshot/`. SOURCE-ORIGIN.json maps their exact local origins, sizes and SHA256 values. All notices and original bytes are retained. No original module is imported or executed. Selected source-function/text/JSON anchors and unchanged None gates are in SOURCE-FINDINGS.json. These structural checks support an inspectable source audit; they are not a general Python semantic proof or a proof of the conditional lemma's premises. + +Base/card provenance is pinned at `7c49fe32c55de02c2c873655c804b16e4c3fef0a`. This is an explicit changed-scope publication assignment under the historical portable-replay card; TASK.json records that distinction. SOURCES.json contains only historical Git provenance. Every live replay input is package-local, so VERIFY.inputs is empty. ARTIFACTS.json binds all packet files except itself. Documentary local paths and private consultation hashes in the frozen reviews do not become live dependencies; no private chat/prompt/response or full workspace record is included. The archive establishes retained byte availability, not complete original Git history. + +From the repository root, with standard-library Python 3.12: + +```sh +python3.12 -B scripts/research_package.py --package research/h25-c05-finite-cover-source-audit --check-only +python3.12 -B scripts/research_package.py --package research/h25-c05-finite-cover-source-audit +``` + +VERIFY.json runs only the new static checker through run.py, in normal and optimized Python with isolation and no bytecode writes. It checks complete inventory/hash identity, source anchors, exact source-gate metadata, literal None/null gates and helper call shape. It performs no original tests, archive decoding, source acquisition, compiler/native/namespace work or target inspection. VALIDATION.json records the actual archive checks. Post-commit byte/history preflight and hosted checks remain separate parent publication steps. + +## Scope, pause and costs + +Source Unit04 closed at 2026-11-02T10:31:17.769942+00:00 with zero complete C05/V03 milestones, zero implementation files and zero tests in that source round. Units01-04 remain closed. This archive preparation opens no source-construction milestone, restarts no source clock and grants no new research or execution budget. The app goal remains paused per the publication assignment and is not queried or changed by replay. + +Full C05=false; full V03=false; runtime/native/namespace qualification=false; original activity credit added=0. The original 43.5% / 22 of 49 checkpoint is unchanged. Null candidate row/byte/witness/representation/bootstrap bills remain null. All physical, outside, preparation, review and publication costs remain OPEN_NOT_ZERO. A source archive pass is not installation, ownership, execution, measured performance or original scientific completion. + +Canonical lineage and adjacent work are PR6321, PR6029, PR5864, PR6339 and the preceding input/interface/conditional source packets. This offline preparation did not refresh live overlap or public status and makes no novelty claim. No proposal to alter preserved native/profile behavior is adopted here. + +## Open next questions + +In a separately authorized source round, supply one exact F/P/A/K occurrence/role/access/alias/mount layout, acyclic driver/configuration/witness finalization order, actual child and separate parent row/byte/representation/physical-cost bill, and a concrete original-compatible lifetime channel proof. Choose either an adequately source-corresponding reachable-operation argument or a separately proposed sufficient policy with its original-profile/permission/authority obligations. Clean image-owner bootstrap and a distinct non-minting prefix supervisor remain missing. TASK.json records relevance, first step and blockers. Archive preparation does not authorize that work or any native installer. + +## Credit and license + +Chris R / Clear1nsight with substantial Pro / Codex / Sol Max assistance and independent agent source review. Preserve original authors, PR6321/6029/5864, unpaidmoon Cursor/Grok PR6339 and Douglas R. Colkitt's lineage. New package code is Apache-2.0; source notices are retained. See NOTICE.md and LICENSE. diff --git a/research/h25-c05-finite-cover-source-audit/SOURCE-FINDINGS.json b/research/h25-c05-finite-cover-source-audit/SOURCE-FINDINGS.json new file mode 100644 index 0000000000..f2f548bfa9 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/SOURCE-FINDINGS.json @@ -0,0 +1,843 @@ +{ + "full_C05": false, + "full_V03": false, + "function_anchors": [ + { + "ast_sha256": "ec245465bd25dadae4e748b30fc63fed52eb2d64d1480cc53267093fdc4f385d", + "first_line": 620, + "last_line": 631, + "path": "snapshot/variant_driver_v1.py.txt", + "qualified_name": "_vcustody", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "747f57d93537c590fda01abaa0d3c1b6b89ee9cd3396b7f776527d9d7d668633" + }, + { + "ast_sha256": "fe3175c9ceae107cae032e02dbbf6678092a947b7bd1f68892093a7eb4d244ca", + "first_line": 634, + "last_line": 640, + "path": "snapshot/variant_driver_v1.py.txt", + "qualified_name": "_vcheck_custody", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "ddea9ff401c1e2fb7a6549485d23444caf87121358b509f7b7d532c729f71c25" + }, + { + "ast_sha256": "be92caea80793d3116803cc1f31d1a484c1c644c679e9a8736bacf7a888a5c2d", + "first_line": 691, + "last_line": 810, + "path": "snapshot/variant_driver_v1.py.txt", + "qualified_name": "_variant_main", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "541fea08a77fcba070018c7fe941137584564989f3f725fcc45e7a37bbce84c6" + }, + { + "ast_sha256": "75f412687561aaf98efe392247ca1c0d89127bd13b43d3fb889ff6d5598a2e07", + "first_line": 146, + "last_line": 176, + "path": "snapshot/variant_driver_v1.py.txt", + "qualified_name": "_vplain", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "19d6a431ff4e8fecd345d58013f1bd13eca6d33f0a8ab383dce8e8e634ee9e55" + }, + { + "ast_sha256": "3a7d62779e4b1201a78b5d7b522ae42df2cccaeeb60c2593da4f934eba14f2d9", + "first_line": 179, + "last_line": 213, + "path": "snapshot/variant_driver_v1.py.txt", + "qualified_name": "_vencode", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "31d2acf5a5c2af1f06e559edcffae7f31570a78f49bb2d4ca5793bd7565010d7" + }, + { + "ast_sha256": "8135e9fd04ced95cb3414c9306661e89bbe0958634c0637fd474c03702093070", + "first_line": 206, + "last_line": 227, + "path": "snapshot/parent_completion_v1.py.txt", + "qualified_name": "_snapshot_sources", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "beefef6b453dc7617094c2c3af08729c154ad14f08021a323040e467e969d9fe" + }, + { + "ast_sha256": "054a056c28d923d6483426298b51917b0599dbbf5d18241a6297a41c857de0b3", + "first_line": 230, + "last_line": 289, + "path": "snapshot/parent_completion_v1.py.txt", + "qualified_name": "_tree", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "d4c57ef4f9d8ded53af7ae6f4617c88991e3a9ee692929e8bf5a4b34ef5cb2f8" + }, + { + "ast_sha256": "7d3367637c508da1e914b812b93263dbd1c9771bb851fee2154fa9a93cb2e192", + "first_line": 314, + "last_line": 403, + "path": "snapshot/parent_completion_v1.py.txt", + "qualified_name": "_validate_plan", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "67ddc2196758c15a2efa69d02038ed9e0a00b7f3c82d6696cde101b1f669474d" + }, + { + "ast_sha256": "6e2854c38ddf7306b4592408f4362603fd1ca09354c8e4abfb814231f9a5c2d2", + "first_line": 541, + "last_line": 690, + "path": "snapshot/parent_completion_v1.py.txt", + "qualified_name": "run_producer", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "cb9375c9ddbb5ca9cc2c279e39b14333d66522fb327b22a3adf126f00e65942a" + }, + { + "ast_sha256": "53a838001465b980fd4f329f9fa36027ad09bbe0b3062a4720138e1dc66f3422", + "first_line": 763, + "last_line": 852, + "path": "snapshot/parent_completion_v1.py.txt", + "qualified_name": "accept_producer", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "1a29d58a1522910f6ad705cdfbf5792604ed339bb9e0d973121786dd7e5f3299" + }, + { + "ast_sha256": "04cc5a295fbb61a20a22e527089eb1904266c20520b78ac4e5e26a712c92b228", + "first_line": 79, + "last_line": 134, + "path": "snapshot/parent_domain_v1.py.txt", + "qualified_name": "_proc", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "72156c6f469be8e73f3dee4c687dcbd84862fb3a88fab29c722b85078642f07e" + }, + { + "ast_sha256": "9d384ad8ca841181af79f0c4b22fe2cb04dc578b3d0867a8d8b1e877e683eae9", + "first_line": 137, + "last_line": 185, + "path": "snapshot/parent_domain_v1.py.txt", + "qualified_name": "_census", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "d5aa1877d0544e43689d6d567621d1d69dfdcdc0d8dc9a05da83c77d17dd6cec" + }, + { + "ast_sha256": "ba5ea339de2a307b65d72658ce595b429e6808af23fb9bc0a22871493f4710c8", + "first_line": 188, + "last_line": 231, + "path": "snapshot/parent_domain_v1.py.txt", + "qualified_name": "create_domain", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "9f4b1da61e1525a27d840817e01c1ca8a26b50286c55cb6572d69824a489c4b6" + }, + { + "ast_sha256": "2d172a64670cc199419857e18ada193f0733666856343a49e80b73b7f8ef9c3b", + "first_line": 414, + "last_line": 436, + "path": "snapshot/parent_domain_v1.py.txt", + "qualified_name": "terminal_facts", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "21aad1c669fb0f950fd35828c1c963ad678ea7dbe64bf4cf0c7fa996aa197cbe" + }, + { + "ast_sha256": "f43ed891d054a604e08db696d6ae441861cbcbc4339a712862eef80a5404d437", + "first_line": 131, + "last_line": 231, + "path": "snapshot/parent_closure_v1.py.txt", + "qualified_name": "bind_receivers", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "5652c6df1144f4633fbf29c2da04d2651353a7c5fdd74bdb1a685f652bf03918" + }, + { + "ast_sha256": "a679dc0ac49e362aa9158a3bdbab2d65b998015e2a71b5f0c0d695a36c1b3db3", + "first_line": 242, + "last_line": 259, + "path": "snapshot/parent_closure_v1.py.txt", + "qualified_name": "check_receivers", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "13ba39075a36466ae2cc8c0feaa6d4e632c640cc91accfb5a63e26312e711a80" + }, + { + "ast_sha256": "c3e3aa38f23f18b6b53e96085f5be559f4e2357f47836d7987e7aebbb2f9f359", + "first_line": 45, + "last_line": 54, + "path": "snapshot/h25_parent_supervisor.py.txt", + "qualified_name": "launch_contract", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "299c0057eb35a58c5301a59ea1b1ce055c9122ba1d2f2156627cdf0c9863b680" + }, + { + "ast_sha256": "00c7834dd8c3bb0a92cf75b4f2b958d6be241246a27abb24afd8b17a85421ce2", + "first_line": 143, + "last_line": 175, + "path": "snapshot/h25_parent_supervisor.py.txt", + "qualified_name": "install_subreaper", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "c2d48ea80f14462c8faff1180b44d06599abd8c057e53c42f7b8d97102483e22" + }, + { + "ast_sha256": "4377220ac100f00575cf8e14eda177d9cc2208dfa82084799d3675572006b480", + "first_line": 158, + "last_line": 202, + "path": "snapshot/native_tcb_v1.py.txt", + "qualified_name": "verify_native_tcb", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "15f93bcf43e0743bdb7950dab7541ad07a23de21397b3c40aa2c7c6e756d4dad" + }, + { + "ast_sha256": "343af1b3dd816ccd40eb85053f3e1f108943921d0c537a986ca8ddd9ac6293f2", + "first_line": 23, + "last_line": 97, + "path": "snapshot/native_tcb_controls_v1.py.txt", + "qualified_name": "run_controls", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "82cc9cad75869138d8517a729af47e0d54ae1ecf0d965acee406a4a9b5368c24" + }, + { + "ast_sha256": "6a5a63a0ed35977dd8f4b4ac5d3e399b80a2bf4fa2ccfbfdf64fa2a1d2e14020", + "first_line": 839, + "last_line": 841, + "path": "snapshot/sealed_elf_profile_v2.py.txt", + "qualified_name": "parse_static_profile", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "056cf9d6a892408a1fd5f11c82a2d3eb758f577e4e7d5cc94240f4627e7696b5" + }, + { + "ast_sha256": "7c7e75bf769ec52d966747dc858a7923792922bb60423c2a387658522e52d124", + "first_line": 844, + "last_line": 848, + "path": "snapshot/sealed_elf_profile_v2.py.txt", + "qualified_name": "admit_service_elf", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "d5769bdf195b736a4afcb6ce1254b679833f05d0c71ddc945f0625c63186e405" + }, + { + "ast_sha256": "04fdbc180871c91243dc5a7fed8127b5bc113647036de8c03a57c1fcd68c025e", + "first_line": 92, + "last_line": 115, + "path": "snapshot/cold_build_evidence.py.txt", + "qualified_name": "_limit_callback", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "7b737b95abd890009d32829e11b96b9128a082365236613483375e81b4409682" + }, + { + "ast_sha256": "850c20692b90f61a5bb1716efc37debeb431c256ead75914cf1c1a9f402075b9", + "first_line": 169, + "last_line": 312, + "path": "snapshot/cold_build_evidence.py.txt", + "qualified_name": "run", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "0a23f979db945e5a85f5fc58cdcad1b863b7d9b9c7fbd585667afde3dd36d124" + }, + { + "ast_sha256": "f0359704ba476f60322e8f4e8d57ceae39f6b4184a24b6d7bde0e79d0564d7c4", + "first_line": 804, + "last_line": 833, + "path": "snapshot/full_driver.py.txt", + "qualified_name": "_entry", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "4c917f19ab40bbe7ad8197403e1c9a8d36bba3821c735f88edfd9bdd0dd5a3b5" + }, + { + "ast_sha256": "047d2383de403012e2b0be4111536663814d93580ebed2af993b2edfe7cde108", + "first_line": 57, + "last_line": 88, + "path": "snapshot/v03_source_refusal_observer_v1.py.txt", + "qualified_name": "corroborate_raw_refusal", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "2ecb0c34d2b04ca6469ae73eb34d233af951720f8bd05e5c46c17dd8f98e41ad" + }, + { + "ast_sha256": "51fbd22b6914e845a35356f3fa05c423349196c52b8189bafc9a4d95148efbbc", + "first_line": 109, + "last_line": 177, + "path": "snapshot/v03_source_refusal_observer_v1.py.txt", + "qualified_name": "corroborate_complete_refusal", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "363fa78a08a2bf741f7c1e0bbb708ce435a91aeba3dc4dbb2e2c73dd1c659b65" + }, + { + "ast_sha256": "967144f92dfb61009c8429454fc8b82a0e4e03887d74c1cd5b4c12b18fc41929", + "first_line": 220, + "last_line": 240, + "path": "snapshot/v03_constructor_test_v1.py.txt", + "qualified_name": "NewConstructorControls.test_full_traceback_and_retained_three_line_counterexample", + "scope": "selected actual source function, statically located; no semantic/runtime proof", + "source_segment_sha256": "ef8e452fce8b57ef17478ab27b5bcd12844fa2b7e46ca19c530c28ff864720fc" + } + ], + "helper_Popen_keywords": [ + "stdin", + "stdout", + "stderr", + "close_fds", + "start_new_session", + "preexec_fn" + ], + "json_anchors": [ + { + "expected": "W_read subset Occ(F) union Occ(A); Origins_file(W_read) subset Occ(F); non-file origins require Facts(N,L,K)", + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "finite_cover", + "correction" + ] + }, + { + "expected": false, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "specific_copied_instance_explicitly_admitted" + ] + }, + { + "expected": false, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "copied_stage_categorically_forbidden" + ] + }, + { + "expected": false, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "new_native_policy_adopted" + ] + }, + { + "expected": false, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "full_C05" + ] + }, + { + "expected": false, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "full_V03" + ] + }, + { + "expected": false, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "runtime_qualification" + ] + }, + { + "expected": false, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "original_activity_credit" + ] + }, + { + "expected": 512, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "bounds", + "child_source_rows" + ] + }, + { + "expected": 67108864, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "bounds", + "child_file_bytes" + ] + }, + { + "expected": 268435456, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "bounds", + "child_custody_pass_bytes" + ] + }, + { + "expected": 8192, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "bounds", + "parent_MAX_SOURCE_FILES" + ] + }, + { + "expected": 16384, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "bounds", + "parent_MAX_STAGE_ENTRIES" + ] + }, + { + "expected": false, + "path": "audit/compatibility-review-v1.json", + "pointer": [ + "bounds", + "actual_runtime_bill_established" + ] + }, + { + "expected": false, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "concrete_cap_feasible_candidate_established" + ] + }, + { + "expected": false, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "concrete_channel_invariant_established" + ] + }, + { + "expected": false, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "authoring_counts_are_runtime_counts" + ] + }, + { + "expected": false, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "authoring_counts_prove_fit_or_failure" + ] + }, + { + "expected": false, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "full_C05" + ] + }, + { + "expected": false, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "full_V03" + ] + }, + { + "expected": false, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "runtime_qualified" + ] + }, + { + "expected": null, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "actual_candidate_bill", + "rows" + ] + }, + { + "expected": null, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "actual_candidate_bill", + "aggregate_bytes" + ] + }, + { + "expected": null, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "actual_candidate_bill", + "max_occurrence_bytes" + ] + }, + { + "expected": null, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "actual_candidate_bill", + "witness_shards" + ] + }, + { + "expected": null, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "actual_candidate_bill", + "raw_representation" + ] + }, + { + "expected": null, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "actual_candidate_bill", + "bootstrap_physical_cost" + ] + }, + { + "expected": "abf25690d3bee4a9783ee504567c29f7fb47da670e0ec95f57cb5944bf57264f", + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "observer", + "final_sha256" + ] + }, + { + "expected": true, + "path": "audit/channel-cap-review-v1.json", + "pointer": [ + "observer", + "complete_api_rejects_retained_three_line_counterexample_from_source_and_frozen_tests" + ] + }, + { + "expected": null, + "path": "snapshot/INTERFACE.json", + "pointer": [ + "configuration" + ] + }, + { + "expected": null, + "path": "snapshot/INTERFACE.json", + "pointer": [ + "execution" + ] + }, + { + "expected": null, + "path": "snapshot/INTERFACE.json", + "pointer": [ + "funding" + ] + }, + { + "expected": null, + "path": "snapshot/INTERFACE.json", + "pointer": [ + "source_review" + ] + }, + { + "expected": null, + "path": "snapshot/INTERFACE.json", + "pointer": [ + "stage_admission" + ] + }, + { + "expected": null, + "path": "snapshot/INTERFACE.json", + "pointer": [ + "command_admission" + ] + }, + { + "expected": [ + "driver digest", + "stage manifest digest", + "configuration own digest", + "full command digest" + ], + "path": "snapshot/INTERFACE.json", + "pointer": [ + "configuration_no_self_hash" + ] + }, + { + "expected": 0, + "path": "audit/SOURCE-GATE-CLOSE-v1.json", + "pointer": [ + "complete_C05_or_V03_milestones" + ] + }, + { + "expected": "closed_at_source_gate_insufficient_construction_inputs", + "path": "audit/SOURCE-GATE-CLOSE-v1.json", + "pointer": [ + "phase" + ] + }, + { + "expected": true, + "path": "audit/SOURCE-GATE-CLOSE-v1.json", + "pointer": [ + "no_installation_or_execution_gate_passed" + ] + }, + { + "expected": "OPEN_NOT_ZERO", + "path": "audit/SOURCE-GATE-CLOSE-v1.json", + "pointer": [ + "outside_costs" + ] + }, + { + "expected": "PASS limited source/frame/stream corroborator; exact generator/fixture bytes and conditional genuine route confirmed", + "path": "evidence/UNIT01-INDEPENDENT-REVIEW.json", + "pointer": [ + "v03_repair" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 0, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 1, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 2, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 3, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 4, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 5, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 6, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 7, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 8, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 9, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 10, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 11, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 12, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 13, + "discharged_by_this_source_packet" + ] + }, + { + "expected": false, + "path": "snapshot/CONDITIONS.json", + "pointer": [ + "conditions", + 14, + "discharged_by_this_source_packet" + ] + } + ], + "literal_constants": [ + { + "expected": 8192, + "name": "MAX_SOURCE_FILES", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "expected": 16384, + "name": "MAX_STAGE_ENTRIES", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "expected": null, + "name": "CONFIGURATION", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "expected": null, + "name": "SOURCE_REVIEW", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "expected": null, + "name": "STAGE_APPROVAL", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "expected": null, + "name": "COMMAND_APPROVAL", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "expected": null, + "name": "FUNDING", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "expected": null, + "name": "EXECUTION_APPROVAL", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "expected": null, + "name": "VARIANT_CONFIGURATION", + "path": "snapshot/variant_driver_v1.py.txt" + }, + { + "expected": null, + "name": "VARIANT_SOURCE_REVIEW", + "path": "snapshot/variant_driver_v1.py.txt" + }, + { + "expected": null, + "name": "VARIANT_STAGE_ADMISSION", + "path": "snapshot/variant_driver_v1.py.txt" + }, + { + "expected": null, + "name": "VARIANT_HEADER_ADMISSION", + "path": "snapshot/variant_driver_v1.py.txt" + }, + { + "expected": null, + "name": "VARIANT_COMMAND_ADMISSION", + "path": "snapshot/variant_driver_v1.py.txt" + }, + { + "expected": null, + "name": "VARIANT_FUNDING", + "path": "snapshot/variant_driver_v1.py.txt" + } + ], + "outside_costs": "OPEN_NOT_ZERO", + "runtime_qualification": false, + "schema": "finite-cover-static-source-findings-v1", + "scope": "Integrity and source-location checks substantiate the quoted audit basis; no execution or general Python semantic proof", + "source_clock_reopened": false, + "text_anchors": [ + { + "first_line": 620, + "last_line": 640, + "literal": "def _vcustody(plan):\n # All expected files are independently frozen source/header/compiler/link\n # closure, including full system header/search/macro/specs witness inputs.\n # This loop observes bytes; it cannot invent closure completeness.\n rows, total = [], 0\n for entry in plan['source_files']:\n raw, current = _vfile(entry['path'], 67108864)\n total += len(raw)\n if total > 268435456:\n raise RuntimeError('Variant custody aggregate byte bound exceeded')\n rows.append({'path': entry['path'], **current})\n return rows\n\n\ndef _vcheck_custody(observed, expected):\n if (not _vsame(len(observed), len(expected))):\n raise RuntimeError('Variant source inventory differs')\n for row, fixed in zip(observed, expected):\n if ((not _vsame(row['path'], fixed['path'])) or (not _vsame(row['sha256'], fixed['sha256'])) or\n (not _vsame(row['bytes'], fixed['bytes'])) or (not _vsame(row['mode'], fixed['mode']))):\n raise RuntimeError('Variant current source closure differs')", + "path": "snapshot/variant_driver_v1.py.txt" + }, + { + "first_line": 691, + "last_line": 696, + "literal": "def _variant_main():\n plan = _vplain(VARIANT_CONFIGURATION)\n if ((not _vsame(len(plan['roles']), 2)) or\n (not _vsame([row['role'] for row in plan['roles']], ['pyinit_failure', 'exec_failure'])) or\n not 1 <= len(plan['source_files']) <= 512):\n raise RuntimeError('Variant literal configuration differs')", + "path": "snapshot/variant_driver_v1.py.txt" + }, + { + "first_line": 55, + "last_line": 56, + "literal": "MAX_SOURCE_FILES = 8192\nMAX_STAGE_ENTRIES = 16384", + "path": "snapshot/parent_completion_v1.py.txt" + }, + { + "first_line": 220, + "last_line": 221, + "literal": " process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr,\n close_fds=True, start_new_session=False, preexec_fn=callback)", + "path": "snapshot/cold_build_evidence.py.txt" + }, + { + "first_line": 109, + "last_line": 118, + "literal": "def corroborate_complete_refusal(driver_bytes, root_bytes, driver_path,\n root_path, stderr_raw, function, message,\n original_log_bound):\n \"\"\"Check the full standard traceback shape for the exact f5 Root route.\n\n This is a strict source-derived corroborator. It grants no ownership,\n authenticity, currentness, error-delivery or admission credential. The parent\n must separately authenticate the exact selected driver and complete streams.\n Unavailable source lines, custom formatters, elision and nonstandard output\n are refused, rather than silently accepted as complete original evidence.", + "path": "snapshot/v03_source_refusal_observer_v1.py.txt" + }, + { + "first_line": 220, + "last_line": 240, + "literal": " def test_full_traceback_and_retained_three_line_counterexample(self):\n function,message = '_vcheck_custody','Variant current source closure differs'\n raw,line = formatted_refusal(function,message)\n args = (GENERATED,ROOT_BYTES,DRIVER_PATH,ROOT_PATH)\n self.assertTrue(observer.corroborate_complete_refusal(*args,raw,function,message,2097152))\n short = ('Traceback (most recent call last):\\n File \"'+DRIVER_PATH+'\", line '+\n str(line)+', in '+function+'\\nRuntimeError: '+message+'\\n').encode()\n self.assertTrue(observer.corroborate_raw_refusal(GENERATED,DRIVER_PATH,short,function,message,2097152))\n self.assertFalse(observer.corroborate_complete_refusal(*args,short,function,message,2097152))\n for changed in (raw.replace(b' _EXEC(code, driver_namespace)\\n',b'',1),\n raw.replace(b' _EXEC(code, driver_namespace)\\n',b' _EXEC(code, driver_namespace)\\n ^ ^\\n',1),\n raw.replace(b', in _entry\\n',b', in other\\n',1),\n raw.replace(b'Traceback (most recent call last):\\n',b'Traceback (most recent call last):\\njunk\\n',1),\n raw.replace(b' _EXEC(code, driver_namespace)\\n',b' wrong_source()\\n',1),\n raw[:-1],raw+raw):\n self.assertFalse(observer.corroborate_complete_refusal(*args,changed,function,message,2097152))\n for function,message in (('_vcheck_literal_sources','Variant source role path differs'),\n ('_v03_original_input_prefix','Variant literal configuration differs'),\n ('_v03_original_input_prefix','Variant original preflight differs')):\n raw,_=formatted_refusal(function,message)\n self.assertTrue(observer.corroborate_complete_refusal(*args,raw,function,message,2097152))", + "path": "snapshot/v03_constructor_test_v1.py.txt" + }, + { + "first_line": 158, + "last_line": 182, + "literal": "def verify_native_tcb(bootstrap_root, bootstrap_api, expected_files, expected_hashlib_origin):\n \"\"\"Corroborate the parent's declared initial native file closure, freshly.\"\"\"\n ops = _native_ops(bootstrap_root, bootstrap_api)\n inventory, expected_total = _expected_inventory(expected_files, expected_hashlib_origin)\n native_hash_module = ops['hash_module']\n origin = native_hash_module.__dict__.get('__file__')\n _need(type(origin) is str and origin == expected_hashlib_origin,\n 'Native TCB actual hashlib origin differs')\n mappings_before, maps_before_bytes, maps_before_sha = _read_maps(ops)\n mapped_paths = {row[0] for row in mappings_before}\n _need(mapped_paths == set(inventory), 'Native TCB declared/executable mapped file closure differs')\n files = []\n for path, expected_digest, expected_size in expected_files:\n observed = _hash_file(ops, path, expected_digest, expected_size)\n current = tuple(row for row in mappings_before if row[0] == path)\n _need(current and all(row[1] == observed['device_major'] and\n row[2] == observed['device_minor'] and row[3] == observed['inode']\n for row in current), 'Native TCB mapped/current file identity differs: ' + path)\n observed['executable_mapping_count'] = len(current)\n observed['executable_mappings'] = [\n {'start': hex(row[4]), 'end': hex(row[5]), 'offset': row[6], 'permissions': row[7]}\n for row in current]\n files.append(observed)\n mappings_after, maps_after_bytes, maps_after_sha = _read_maps(ops)\n _need(mappings_after == mappings_before, 'Native TCB executable mappings changed during audit')", + "path": "snapshot/native_tcb_v1.py.txt" + }, + { + "first_line": 45, + "last_line": 54, + "literal": "def launch_contract():\n need(sys.executable == '/usr/bin/python3.12', 'Pinned interpreter required')\n need(sys.flags.no_site == sys.flags.no_user_site == sys.flags.dont_write_bytecode == 1 and\n sys.flags.safe_path and sys.flags.ignore_environment == sys.flags.isolated ==\n sys.flags.hash_randomization == 0, 'Trusted no-site safe-path fixed-seed flags required')\n need(dict(os.environ) == ENV, 'Exact clean environment required')\n need(tuple(sys.path) == ('/usr/lib/python312.zip', '/usr/lib/python3.12',\n '/usr/lib/python3.12/lib-dynload'), 'Initial system stdlib path changed')\n need(list(Path('/proc/self/task').iterdir()) == [Path('/proc/self/task') / str(os.getpid())],\n 'Exactly one parent task required')", + "path": "snapshot/h25_parent_supervisor.py.txt" + }, + { + "first_line": 414, + "last_line": 436, + "literal": "def terminal_facts(capability):\n state = _state(capability)\n _fresh_acquisition(state)\n schema.need(state['phase'] == 'CLOSED' and state['quarantine'] is False and\n state['acquisition_in_flight'] is False and state['io_uncertain'] is False and state['root'] is not None and\n state['returncode'] == 0 and state['closure_confirmed'] is True and\n state['final_rows'] == () and not state['after_root'] and not state['reaped'] and\n all(fd is None or (state['fd_attempted'][index] and state['fd_closed'][index])\n for index, fd in enumerate(state['fds'])),\n 'owned terminal domain is incomplete, failed, orphaned or quarantined')\n # Fresh census after FD cleanup. This is independent of receipt booleans.\n rows = _census(state)\n schema.need(not any(row[1] == state['parent_pid'] or\n (row[2], row[3]) in state['groups'] for row in rows.values()),\n 'postcleanup owned child/group still present')\n return {'root': list(state['root']), 'returncode': state['returncode'],\n 'owned_generations': [list(row) for row in state['rows'][:state['count']]],\n 'groups': [list(pair) for pair in sorted(state['groups'])],\n 'remaining': [], 'adopted_reaps': [], 'observed_after_root_exit': [],\n 'pidfd_close_attempted': list(state['fd_attempted'][:state['count']]),\n 'pidfd_close_confirmed': list(state['fd_closed'][:state['count']]),\n 'source': 'original in-process Popen and owned generation registry',\n 'hostile_fork_or_privileged_host_resistance_claimed': False}", + "path": "snapshot/parent_domain_v1.py.txt" + } + ] +} diff --git a/research/h25-c05-finite-cover-source-audit/SOURCE-ORIGIN.json b/research/h25-c05-finite-cover-source-audit/SOURCE-ORIGIN.json new file mode 100644 index 0000000000..85527ded86 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/SOURCE-ORIGIN.json @@ -0,0 +1,195 @@ +{ + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "copies": [ + { + "byte_exact": true, + "bytes": 10460, + "from": "outputs/c05-v03-completion-20261102T055710Z/unit04/compatibility-review-v1.md", + "path": "audit/compatibility-review-v1.md", + "scope": "exact frozen unit04 source decision record; historic local paths are documentary", + "sha256": "62d2ef8657c06ca7816e5d625261af382d1b6e1eb1d7329dc0bf8d4ded2f1344" + }, + { + "byte_exact": true, + "bytes": 8664, + "from": "outputs/c05-v03-completion-20261102T055710Z/unit04/compatibility-review-v1.json", + "path": "audit/compatibility-review-v1.json", + "scope": "exact frozen unit04 source decision record; historic local paths are documentary", + "sha256": "9dfa9168d69cba7adcd98bec567ee61db1ad98de90adc1c603195458f2164a49" + }, + { + "byte_exact": true, + "bytes": 13141, + "from": "outputs/c05-v03-completion-20261102T055710Z/unit04/channel-cap-review-v1.md", + "path": "audit/channel-cap-review-v1.md", + "scope": "exact frozen unit04 source decision record; historic local paths are documentary", + "sha256": "28512789545b2bca5bfa20e8b20100a882337b2b02237cde8643bc44b375b3f1" + }, + { + "byte_exact": true, + "bytes": 8168, + "from": "outputs/c05-v03-completion-20261102T055710Z/unit04/channel-cap-review-v1.json", + "path": "audit/channel-cap-review-v1.json", + "scope": "exact frozen unit04 source decision record; historic local paths are documentary", + "sha256": "b1c3dbee15a28d5ee9657ab3a113cd899a36ca737edf869de889469f467e14c7" + }, + { + "byte_exact": true, + "bytes": 2102, + "from": "outputs/c05-v03-completion-20261102T055710Z/unit04/SOURCE-GATE-CLOSE-v1.json", + "path": "audit/SOURCE-GATE-CLOSE-v1.json", + "scope": "exact frozen unit04 source decision record; historic local paths are documentary", + "sha256": "b26cff1bd0c70ecddb22efab21e5f8916c1985d79ae421e51308a438910db6fd" + }, + { + "byte_exact": true, + "bytes": 6940, + "from": "outputs/resolved-questions-publication-20261102T025112Z/v03-publication/research/h25-v03-source-prerequisites/snapshot/areas/field-variant-producer-v2/CONDITIONS.json", + "path": "snapshot/CONDITIONS.json", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "70e237d6ee4ac2ccaadf01615e8106999718eb1fbb3cf7644c9fc6d3fd4463fe" + }, + { + "byte_exact": true, + "bytes": 6956, + "from": "outputs/resolved-questions-publication-20261102T025112Z/v03-publication/research/h25-v03-source-prerequisites/snapshot/areas/field-variant-producer-v2/INTERFACE.json", + "path": "snapshot/INTERFACE.json", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "30820f1f2d27d4d4306d8ba63db5329f89182912f7f915aede35b9ce62359491" + }, + { + "byte_exact": true, + "bytes": 41337, + "from": "outputs/resolved-questions-publication-20261102T025112Z/v03-publication/research/h25-v03-source-prerequisites/snapshot/areas/field-variant-producer-v2/variant_driver_v1.py.txt", + "path": "snapshot/variant_driver_v1.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "cdb1479253358508088f8aa0e1e92e6c75ffcc127e54552698598a02de061254" + }, + { + "byte_exact": true, + "bytes": 54168, + "from": "outputs/c05-v03-completion-20261102T055710Z/publication-audit-v1/research/h25-c05-v03-parent-interface-audit/snapshot/parent_completion_v1.py.txt", + "path": "snapshot/parent_completion_v1.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "d4ee1b7ce4a42b73261984ffb1b9ceb5bb0165223e04a253588f83b99f6981a5" + }, + { + "byte_exact": true, + "bytes": 20456, + "from": "outputs/c05-v03-completion-20261102T055710Z/publication-audit-v1/research/h25-c05-v03-parent-interface-audit/snapshot/parent_domain_v1.py.txt", + "path": "snapshot/parent_domain_v1.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "9205e14d6661fb5df0597f0ad7b2206006f2d31f01f784805f64c13875663282" + }, + { + "byte_exact": true, + "bytes": 13400, + "from": "outputs/c05-v03-completion-20261102T055710Z/unit02/prerequisite-source/field-parent-completion-v2--parent_closure_v1.py.txt", + "path": "snapshot/parent_closure_v1.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "2d831cff8bd444de2d6941645d571e07618ede404a1f45692b557f61494b334a" + }, + { + "byte_exact": true, + "bytes": 23047, + "from": "outputs/c05-v03-completion-20261102T055710Z/unit02/prerequisite-source/h25_parent_supervisor.py.txt", + "path": "snapshot/h25_parent_supervisor.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "cfb09a18dd10b597cc6d5a8139ee769bef679bc44ae029329755e3d97b055075" + }, + { + "byte_exact": true, + "bytes": 11353, + "from": "outputs/c05-v03-completion-20261102T055710Z/prerequisite-source/native_tcb_v1.py.txt", + "path": "snapshot/native_tcb_v1.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "865943df5cfdbf9383362d7fb2b76c6d0fd895cf0a0e20d550a26b579606b5d7" + }, + { + "byte_exact": true, + "bytes": 4889, + "from": "outputs/c05-v03-completion-20261102T055710Z/prerequisite-source/native_tcb_controls_v1.py.txt", + "path": "snapshot/native_tcb_controls_v1.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "63b1804caa7f89915662a1424f788c3becad13520e1f63212a338fb45aaa2c5a" + }, + { + "byte_exact": true, + "bytes": 76453, + "from": "outputs/c05-v03-completion-20261102T055710Z/prerequisite-source/sealed_elf_profile_v2.py.txt", + "path": "snapshot/sealed_elf_profile_v2.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "89ed8c777e6b72af2d6a3595037e7e92385924c6087d88010a27192633391016" + }, + { + "byte_exact": true, + "bytes": 16463, + "from": "outputs/c05-v03-completion-20261102T055710Z/unit03/binding/cold_build_evidence.py.txt", + "path": "snapshot/cold_build_evidence.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "aa0a315110e031e19291970c9611fe5e0f91465fa20eaec51e81186099563f78" + }, + { + "byte_exact": true, + "bytes": 38851, + "from": "outputs/c05-context-namespace-20261102T042817Z/publication/research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/full_driver.py.txt", + "path": "snapshot/full_driver.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0" + }, + { + "byte_exact": true, + "bytes": 14205, + "from": "outputs/c05-v03-completion-20261102T055710Z/implementation/v03_source_refusal_observer_v1.py", + "path": "snapshot/v03_source_refusal_observer_v1.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "abf25690d3bee4a9783ee504567c29f7fb47da670e0ec95f57cb5944bf57264f" + }, + { + "byte_exact": true, + "bytes": 14821, + "from": "outputs/c05-v03-completion-20261102T055710Z/tests/v03_constructor_test_v1.py", + "path": "snapshot/v03_constructor_test_v1.py.txt", + "scope": "inert reference bytes only; parsed as text/AST, never imported or executed", + "sha256": "3f7aeb812e17a261062b378060964b1a1c45694e9258c177367ce6bb46623452" + }, + { + "byte_exact": true, + "bytes": 1179, + "from": "outputs/c05-v03-completion-20261102T055710Z/publication-v2/research/h25-c05-v03-input-constructors/INDEPENDENT-REVIEW.json", + "path": "evidence/UNIT01-INDEPENDENT-REVIEW.json", + "scope": "frozen agent source-review disposition; not live replay or original runtime proof", + "sha256": "84b94c41609b83f6307c553792c37ee29477a450fe3d09f2bd850318557071fd" + }, + { + "byte_exact": true, + "bytes": 2856, + "from": "outputs/c05-v03-completion-20261102T055710Z/UNIT-01-SOURCE-CLOSE-v1.json", + "path": "evidence/UNIT01-SOURCE-CLOSE-v1.json", + "scope": "frozen observer final hash and scope; no Unit01 restart", + "sha256": "4f41522472d31bb3904d24ddc0b0ac01aef63273e4f551575b6148457e23eed5" + } + ], + "external_context": [ + { + "disposition": "external historical context; not exported, opened, verified or a live replay input", + "from": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/consultation/RESPONSE-v5.txt", + "sha256": "a3bc66f2d226053afaea669599a8986862be7465995aadef9390556cc82a2937" + }, + { + "disposition": "external historical context; not exported, opened, verified or a live replay input", + "from": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/consultation/ASSESSMENT-v5.md", + "sha256": "9bd8937634a2fd059800382e65c8318d7a309da3d5fdceae1963e53e58e95fbd" + }, + { + "disposition": "external historical context; not exported, opened, verified or a live replay input", + "from": "consultation/v03_source_refusal_observer_v1.py", + "sha256": "fa0ecf7d6574bfa1a8768079b163a7621c3d3765a0e48456fb14674582cb5c46" + } + ], + "omissions": "No private consultation chat/prompt/response, PLAN/STATE/full workspace, original runtime tree, native binaries, header corpus or payload archive is exported. Other named historical record paths remain documentary. Only included snapshots are live anchor inputs.", + "original_code_executed": false, + "original_modules_imported": false, + "schema": "finite-cover-source-archive-origin-v1", + "scope": "byte/path equality only; no full original Git history, runtime admission or privacy grant" +} diff --git a/research/h25-c05-finite-cover-source-audit/SOURCES.json b/research/h25-c05-finite-cover-source-audit/SOURCES.json new file mode 100644 index 0000000000..594089b9c7 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/SOURCES.json @@ -0,0 +1,18 @@ +{ + "schema_version": 1, + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "d59b5035e7b4cbaa9d688a1d32dd0d6eb79c466a", + "sha256": "9b8d0eea95b3bf0dfcb7938a732a6439b87a2685dec2a5ab9e525b3b34debbfa" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + } + ] +} diff --git a/research/h25-c05-finite-cover-source-audit/TASK.json b/research/h25-c05-finite-cover-source-audit/TASK.json new file mode 100644 index 0000000000..9d380bc19b --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/TASK.json @@ -0,0 +1,60 @@ +{ + "actual_scope": "Archive the frozen Unit04 finite-cover/source-compatibility/channel-cap decision audit, with exact inert sources and bounded static integrity/anchor replay only.", + "ai_assistance": "ChatGPT Pro source consultation and substantial OpenAI Codex source-audit/verification assistance. These are agent-assisted findings, not human or proof-kernel acceptance.", + "author": "Chris R / Clear1nsight", + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "bottleneck_link": "Distinguish source-compatible candidate classes from concrete finite-cover, channel, cap and runtime admission obligations before any successor construction.", + "budget_minutes": 20, + "evidence": "Exact compatibility/channel-cap md+json and SOURCE-GATE-CLOSE; minimal relevant inert source snapshots; SOURCE-ORIGIN, SOURCE-FINDINGS and ARTIFACTS; registered static normal/-O checks.", + "open_questions": [ + { + "blocked_by": "No complete concrete layout, compiler/bootstrap exclusion, lifetime channel mechanism, clean image owner/non-minting prefix supervisor or independent admissions. Any policy change preserving original profiles requires its own authority.", + "first_step": "In a separately authorized source round, write a candidate occurrence/role/access/alias/mount table, acyclic finalization order and exact row/byte/representation/physical-cost bill; leave missing entries explicit.", + "question": "Can one exact original-compatible F/P/A/K candidate and lifetime channel argument satisfy the child and separate parent bounds with acyclic witness finalization?", + "why_it_matters": "The corrected conditional origin lemma and source eligibility of fresh stages establish neither concrete cap fit nor an admitted runtime." + } + ], + "original_card": { + "acceptance_gate": "Preserve immutable source hashes and proof-relevant content; a different compressed byte stream alone is not a mathematical mismatch.", + "allowed_variations": [ + "One interpreter/version mismatch or one payload field comparison." + ], + "bottleneck_link": "Portable exact checks prevent environment failures from blocking valid contributions.", + "first_experiment": "Reproduce one specific mismatch or audit one canonical comparison for omitted proof-relevant fields.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Resolve the current selected review, separate complex/ordinary BIT/admitted BIT/outer budgets, and compare the card against live handoffs before starting. Historical ceilings require exact source/model equivalence.", + "scope": "Source-binding orientation only; not a scientific replay or all-size proof. Materialize selected inputs if this checkout is sparse." + }, + "id": "portable-replay", + "methods": [ + "Reproduce one portability failure and add a minimal cross-environment fix.", + "Audit one canonical-payload comparison for omitted proof-relevant fields." + ], + "overlap_terms": [ + "gzip container", + "reproducibility", + "canonical payload" + ], + "question": "Can one reproducible environment or artifact-comparison failure be repaired?", + "scope_change_triggers": [ + "Removing immutable-source pins because generated compressed bytes differ." + ], + "starting_points": [ + "research/gzip-container-reproducibility/README.md", + "docs/ci-verification.md" + ] + }, + "outcome": "partial", + "priority_revision": 8, + "schema_version": 1, + "scope_change_reason": "Explicit publication-only assignment preserves a conditional provenance correction and negative implementation-gate finding rather than repairing a portability failure or constructing a runtime.", + "scope_status": "changed", + "stop_rule": "Units01-04 source clocks are closed. Publication preparation cutoff 2026-11-02T10:55:00Z; aim 10:51Z. No construction, source acquisition, original/native/compiler/namespace/target execution or new research budget.", + "task_id": "portable-replay" +} diff --git a/research/h25-c05-finite-cover-source-audit/VALIDATION.json b/research/h25-c05-finite-cover-source-audit/VALIDATION.json new file mode 100644 index 0000000000..24a125ac2a --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/VALIDATION.json @@ -0,0 +1,78 @@ +{ + "cold_copy": [ + { + "exit_code": 0, + "log_sha256": "74c7cad84f938c66a769504b1eb6eebb1ad7dc1ec154fbdc0c28959e9971d1d6", + "mode": "normal", + "output": "PASS_FINITE_COVER_SOURCE_ARCHIVE_ONLY files=34 functions=28 text=9 metadata=56\n", + "scope": "separate directory with only packet bytes and no Git metadata; new static checker only" + }, + { + "exit_code": 0, + "log_sha256": "74c7cad84f938c66a769504b1eb6eebb1ad7dc1ec154fbdc0c28959e9971d1d6", + "mode": "optimized", + "output": "PASS_FINITE_COVER_SOURCE_ARCHIVE_ONLY files=34 functions=28 text=9 metadata=56\n", + "scope": "separate directory with only packet bytes and no Git metadata; new static checker only" + } + ], + "commands": [ + { + "argv": [ + "python3.12", + "-B", + "scripts/research_package.py", + "--package", + "research/h25-c05-finite-cover-source-audit", + "--check-only" + ], + "exit_code": 0, + "label": "check-only", + "output_sha256": "5873404cb4424dca918a00d503569f3c29a3190fd029a007e1afb2006399f647", + "started_utc": "2026-11-02T10:39:55.670904+00:00" + }, + { + "argv": [ + "python3.12", + "-B", + "scripts/research_package.py", + "--package", + "research/h25-c05-finite-cover-source-audit" + ], + "exit_code": 0, + "label": "registered-static", + "output_sha256": "73f32c8bb245dfa6cae2a6164faa5c1be7320b8f2fcadc90f34d0645ce46d4a7", + "started_utc": "2026-11-02T10:39:55.925864+00:00" + } + ], + "compiler_native_namespace_target_execution": false, + "copied_source_bytes_exact": true, + "full_C05": false, + "full_V03": false, + "observed_utc": "2026-11-02T10:40:52.021433+00:00", + "original_activity_checkpoint": "43.5% / 22 of 49 unchanged", + "original_activity_credit_added": 0, + "original_execution": false, + "original_imports": false, + "original_tests_executed": false, + "outside_costs": "OPEN_NOT_ZERO", + "private_consultation_exported": false, + "python": "3.12.3", + "registered_modes": [ + "normal", + "optimized" + ], + "remaining": [ + "Independent exact export review", + "Parent commit and committed-byte/source-history preflight", + "Chrome publication and exact-head hosted checks" + ], + "schema": "finite-cover-source-archive-validation-v1", + "scope": "New static archive checks only; no original source import/execution or original fixture tests", + "source_clocks_reopened": false, + "static_anchors": { + "functions": 28, + "literal_gates_and_caps": 14, + "metadata": 56, + "text_spans": 9 + } +} diff --git a/research/h25-c05-finite-cover-source-audit/VERIFY.json b/research/h25-c05-finite-cover-source-audit/VERIFY.json new file mode 100644 index 0000000000..fe0ac03555 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/VERIFY.json @@ -0,0 +1,32 @@ +{ + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "-S", + "{package}/run.py" + ], + "checks": "Source-archive raw bytes, exact decision metadata and selected actual text/AST anchors only; no original imports or execution", + "timeout_seconds": 30 + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-B", + "-S", + "{package}/run.py" + ], + "checks": "Same static source-archive check under optimized Python; no original or native execution", + "timeout_seconds": 30 + } + ], + "inputs": [], + "python": "3.12", + "requirements": [], + "schema_version": 1, + "status": "ready" +} diff --git a/research/h25-c05-finite-cover-source-audit/audit/SOURCE-GATE-CLOSE-v1.json b/research/h25-c05-finite-cover-source-audit/audit/SOURCE-GATE-CLOSE-v1.json new file mode 100644 index 0000000000..218864163c --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/audit/SOURCE-GATE-CLOSE-v1.json @@ -0,0 +1,49 @@ +{ + "unit": "04", + "closed_utc": "2026-11-02T10:31:17.769942+00:00", + "phase": "closed_at_source_gate_insufficient_construction_inputs", + "closed_before_input_deadline": true, + "complete_C05_or_V03_milestones": 0, + "new_implementation_files": 0, + "new_tests_executed": 0, + "original_execution": false, + "accepted_source_findings": [ + "Corrected conditional provenance lemma only; actualreads F union generatedA, externalfile origins F", + "Fresh copied installed stage is eligible as a candidate class under original conditions; no concrete instance/policy admission", + "Bootstrap self-hash exclusion and acyclic witness finalization are mandatory; parent8192/stage16384 distinct fromchild512", + "Unit01 strict complete observer repaired; terminal-onlylegacy API remains intentionally insufficient" + ], + "unmet_input_gate": [ + "Actual complete F/P/A/K runtime occurrence/role/access/alias/mount layout and all witness bytes", + "Actual child/parent inventory row/byte/raw representation bill and full physical cost bill", + "Concrete original-profile-compatible lifetime input-channel invariant and compiler/bootstrap exclusion", + "Implemented and separately source-admitted image owner/fresh bootstrap/non-minting prefix supervisor" + ], + "reports": [ + { + "path": "compatibility-review-v1.md", + "bytes": 10460, + "sha256": "62d2ef8657c06ca7816e5d625261af382d1b6e1eb1d7329dc0bf8d4ded2f1344" + }, + { + "path": "compatibility-review-v1.json", + "bytes": 8664, + "sha256": "9dfa9168d69cba7adcd98bec567ee61db1ad98de90adc1c603195458f2164a49" + }, + { + "path": "channel-cap-review-v1.md", + "bytes": 13141, + "sha256": "28512789545b2bca5bfa20e8b20100a882337b2b02237cde8643bc44b375b3f1" + }, + { + "path": "channel-cap-review-v1.json", + "bytes": 8168, + "sha256": "b1c3dbee15a28d5ee9657ab3a113cd899a36ca737edf869de889469f467e14c7" + } + ], + "no_progress_clock_reset": false, + "no_installation_or_execution_gate_passed": true, + "full_C05": false, + "full_V03": false, + "outside_costs": "OPEN_NOT_ZERO" +} diff --git a/research/h25-c05-finite-cover-source-audit/audit/channel-cap-review-v1.json b/research/h25-c05-finite-cover-source-audit/audit/channel-cap-review-v1.json new file mode 100644 index 0000000000..45c6bb71af --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/audit/channel-cap-review-v1.json @@ -0,0 +1,173 @@ +{ + "schema": "unit04-channel-cap-review-v1", + "recorded_utc": "2026-11-02 10:28:30 UTC", + "scope": "passive source-only independent cap/channel/observer review; no original imports, tests or runtime", + "decision": "SOURCE_INSUFFICIENT_FOR_CONCRETE_CAP_AND_CHANNEL_GATE", + "concrete_cap_feasible_candidate_established": false, + "concrete_channel_invariant_established": false, + "conditional_finite_cover_alternative": "available only after origin/channel/instance/cap premises are independently established", + "ordinary_read_semantics": "actual ordinary reads subset frozen exogenous F union earlier generated A; exogenous ordinary origins subset F", + "authoring_counts_are_runtime_counts": false, + "authoring_counts_prove_fit_or_failure": false, + "original_caps": { + "source_files_min": 1, + "source_files_max": 512, + "per_occurrence_bytes_max": 67108864, + "custody_capture_bytes_max": 268435456, + "raw_depth_max": 24, + "raw_nodes_max": 65536, + "string_chars_max": 8192, + "aggregate_string_chars_max": 524288, + "sequence_or_mapping_entries_max": 1024, + "wire_bytes_max": 1048576 + }, + "actual_candidate_bill": { + "rows": null, + "aggregate_bytes": null, + "max_occurrence_bytes": null, + "witness_shards": null, + "raw_representation": null, + "bootstrap_physical_cost": null + }, + "necessary_conditions": [ + "acyclic compiler/bootstrap/generated/nonordinary partition with actual compiler-read exclusions", + "fresh runtime exec loading copied native inode/device identities at exact paths", + "genuine proc census and permission errors preserved; actual PID/PPID/group/session/start/RSS ownership", + "same fresh parent subreaper and keeper, exact environment/flags/path and no preexisting children", + "owned mutable scratch/generated areas with closed input and writer provenance", + "all root/cwd/FD/mapping/proc/process/IPC/device/exec/dynamic channels covered over the entire lifetime", + "explicit source-admitted non-minting prefix supervisor; unchanged production two-build completion remains literal" + ], + "missing_evidence": [ + "actual runtime occurrence/role/consumer/payload/access/alias/mount table", + "actual source_files and witness count/size/raw representation bill", + "acyclic driver/configuration/witness finalization and compiler/bootstrap exclusion proof", + "actual permissions/policy and root/cwd/FD/mapping/process/IPC/device channel closure", + "source-to-executable correspondence adequate for chosen reachable-input exclusion argument", + "actual implemented clean executable parent/image owner and separately admitted prefix receiver", + "copied-instance admissibility relation and full physical cost bill" + ], + "smallest_next_operation": "Author an explicit candidate layout/partition and per-cap bill from exact retained pins with unresolved named entries, and select a concrete source-route channel proof or separately proposed policy; no native installer or original execution follows.", + "observer": { + "original_sha256": "fa0ecf7d6574bfa1a8768079b163a7621c3d3765a0e48456fb14674582cb5c46", + "final_sha256": "abf25690d3bee4a9783ee504567c29f7fb47da670e0ec95f57cb5944bf57264f", + "frozen_export_same_bytes": true, + "legacy_terminal_api_intentionally_accepts_retained_three_line_counterexample": true, + "complete_api_rejects_retained_three_line_counterexample_from_source_and_frozen_tests": true, + "disposition": "complete corroboration path repaired and legacy claim narrowed; no authority conferred", + "final_source_spans": [ + "57-88 terminal-site API", + "109-177 strict complete API", + "114-118 no authority" + ], + "retained_test_spans": [ + "220-240 three-line, omitted/malformed/source/stream controls" + ], + "pro5_line611": "stale if read as an outstanding defect in the final complete API; still applicable to legacy API misuse", + "tests_executed_in_this_review": 0 + }, + "source_pins": [ + { + "path": "unit04/PLAN.json", + "sha256": "fee0c5f1d0d5566293c65e0a81123bb6f2b5b8a163a5c1e12cc2fdac5df89727" + }, + { + "path": "consultation/RESPONSE-v5.txt", + "sha256": "a3bc66f2d226053afaea669599a8986862be7465995aadef9390556cc82a2937" + }, + { + "path": "consultation/ASSESSMENT-v5.md", + "sha256": "9bd8937634a2fd059800382e65c8318d7a309da3d5fdceae1963e53e58e95fbd" + }, + { + "path": "prerequisite-source/native_tcb_v1.py.txt", + "sha256": "865943df5cfdbf9383362d7fb2b76c6d0fd895cf0a0e20d550a26b579606b5d7" + }, + { + "path": "prerequisite-source/native_tcb_controls_v1.py.txt", + "sha256": "63b1804caa7f89915662a1424f788c3becad13520e1f63212a338fb45aaa2c5a" + }, + { + "path": "prerequisite-source/sealed_elf_profile_v2.py.txt", + "sha256": "89ed8c777e6b72af2d6a3595037e7e92385924c6087d88010a27192633391016" + }, + { + "path": "unit02/prerequisite-source/field-parent-completion-v2--parent_domain_v1.py.txt", + "sha256": "9205e14d6661fb5df0597f0ad7b2206006f2d31f01f784805f64c13875663282" + }, + { + "path": "unit02/prerequisite-source/field-parent-completion-v2--parent_completion_v1.py.txt", + "sha256": "d4ee1b7ce4a42b73261984ffb1b9ceb5bb0165223e04a253588f83b99f6981a5" + }, + { + "path": "unit02/prerequisite-source/field-parent-completion-v2--parent_closure_v1.py.txt", + "sha256": "2d831cff8bd444de2d6941645d571e07618ede404a1f45692b557f61494b334a" + }, + { + "path": "unit02/prerequisite-source/h25_parent_supervisor.py.txt", + "sha256": "cfb09a18dd10b597cc6d5a8139ee769bef679bc44ae029329755e3d97b055075" + }, + { + "path": "unit02/SOURCE-GATE-CLOSE-v1.json", + "sha256": "3abffbf85adae35018eab393d403493990640df862752e730445944d7764368a" + }, + { + "path": "source-artifacts/DEVELOPMENT-PAYLOAD-CORRESPONDENCE-v1.json", + "sha256": "c351813bea16d6cec73105eafae1717015c0c7800f4389a7b765148b90bd155f" + }, + { + "path": "unit03/gcc/header-member-pins-v1.json", + "sha256": "c0c6890ff27c90b5a919d8943a707d49497aa05f1329d7ab5b06fbe95ab2e47d" + }, + { + "path": "consultation/v03_source_refusal_observer_v1.py", + "sha256": "fa0ecf7d6574bfa1a8768079b163a7621c3d3765a0e48456fb14674582cb5c46" + }, + { + "path": "implementation/v03_source_refusal_observer_v1.py", + "sha256": "abf25690d3bee4a9783ee504567c29f7fb47da670e0ec95f57cb5944bf57264f" + }, + { + "path": "UNIT-01-SOURCE-CLOSE-v1.json", + "sha256": "4f41522472d31bb3904d24ddc0b0ac01aef63273e4f551575b6148457e23eed5" + }, + { + "path": "publication-v2/research/h25-c05-v03-input-constructors/implementation/v03_source_refusal_observer_v1.py", + "sha256": "abf25690d3bee4a9783ee504567c29f7fb47da670e0ec95f57cb5944bf57264f" + }, + { + "path": "publication-v2/research/h25-c05-v03-input-constructors/INDEPENDENT-REVIEW.json", + "sha256": "84b94c41609b83f6307c553792c37ee29477a450fe3d09f2bd850318557071fd" + }, + { + "path": "tests/v03_constructor_test_v1.py", + "sha256": "3f7aeb812e17a261062b378060964b1a1c45694e9258c177367ce6bb46623452" + } + ], + "external_exact_original_sources": [ + { + "path": "outputs/resolved-questions-publication-20261102T025112Z/v03-publication/research/h25-v03-source-prerequisites/snapshot/areas/field-variant-producer-v2/variant_driver_v1.py.txt", + "sha256": "cdb1479253358508088f8aa0e1e92e6c75ffcc127e54552698598a02de061254", + "spans": [ + "146-212 representation", + "620-640 custody", + "691-733 original prefix" + ] + }, + { + "path": "outputs/c05-context-namespace-20261102T042817Z/publication/research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/full_driver.py.txt", + "sha256": "f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0", + "spans": [ + "805-833 selected-driver authentication/execution" + ] + } + ], + "full_C05": false, + "full_V03": false, + "original_execution": false, + "runtime_qualified": false, + "original_activity_credit": 0, + "physical_costs": "OPEN_NOT_ZERO", + "previous_units_reopened": false, + "goal_or_automation_changed": false +} diff --git a/research/h25-c05-finite-cover-source-audit/audit/channel-cap-review-v1.md b/research/h25-c05-finite-cover-source-audit/audit/channel-cap-review-v1.md new file mode 100644 index 0000000000..eff08b20a9 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/audit/channel-cap-review-v1.md @@ -0,0 +1,59 @@ +# Unit04 copied-runtime cap and channel review + +Recorded 2026-11-02, before the 10:34 UTC review cutoff. This is a passive source review. No original imports, tests, compiler, native, namespace, target inspection, source acquisition or runtime admission occurred. Only this report and its JSON companion are owned by this reviewer. Units01–03 stay closed. + +**Decision: source-insufficient for a concrete cap-feasible copied-runtime candidate and for a concrete channel invariant under the unchanged original route.** The conditional coverage approach remains available for further source work; no construction, impossibility, full C05/V03 completion, runtime qualification or activity credit follows. + +Here F denotes the effort root `outputs/c05-v03-completion-20261102T055710Z`. Paths and line numbers below identify ordinary retained source text, not a claim that those modules ran. + +| Claim | Decision | Reason | +|---|---|---| +| A finite enclosure can replace complete compiler branch modelling | CONDITIONAL | It needs a closed input/channel invariant, namespace and dynamic-observation rules, generated-artifact provenance and an admitted instance relation. | +| Available 829 authoring occurrences or 472 plugin headers determine runtime cap fit | NOT SUPPORTED | They are authoring/payload corpora, not an actual runtime occurrence inventory. They prove neither fit nor failure. | +| Copying a read-only tree at the same absolute paths proves confinement | FAIL as a sufficient mechanism | Root/cwd, descriptors, mappings, proc aliases, IPC, writable areas, descendants and lifetime writers remain separate premises. | +| Freshly copied bytes can satisfy existing native mapping predicates | CONDITIONAL | The actual process must load from that copied view; hashes alone do not make host mappings match copied inodes. | +| The unchanged production parent accepts prefix-source refusals | FAIL | Its driver path/inventory, empty-stderr receiver, returncode-zero terminal facts and full two-build validation differ. A separately admitted successor route is still needed. | +| Unit01 merely documented the refusal-observer defect | FALSE | It narrowed the old API and added a strict complete-frame/source/stream corroborator. This repaired the identified omission acceptance on the complete API, with limited authority. | + +In set statements, F follows Pro5 and means the frozen exogenous occurrence set, rather than the effort-root path abbreviation. The finite-cover statement needs the precise origin distinction raised by the other independent reviewer: actual ordinary reads may come from frozen exogenous F **or** earlier generated A. Only exogenous ordinary origins must lie in F. Pro5 lines65–100 should not be read as asserting that generated ordinary reads themselves all belong to F. Pro5 lines18–63 already allow A. This review accepts that correction and does not promote the conditional lemma into an effective compiler configuration or a copied-instance equivalence result. + +## Original constraints established by actual source + +1. **Caps and self-reference.** The original variant driver lines691–696 requires 1..512 source-file rows. Lines620–640 charge every occurrence at most 67,108,864 bytes and at most 268,435,456 bytes per custody capture; the check compares path/hash/bytes/mode and expressly does not invent closure completeness. Lines146–175 impose depth24, node65,536, individual string8,192, aggregate string524,288 and sequence/mapping1,024 bounds; lines179–212 impose the existing 1MiB wire bound. Witness files are rows and their representation still pays these bounds. Equal bytes or hard links do not by themselves erase distinct inventory occurrences. These are not total physical-cost limits. + + Pro5 lines182–221 correctly identifies the acyclic-construction issue if the generated driver's own hash is inserted in its embedded source_files. The original INTERFACE.json lines15–20 and C07 exclude that self-hash construction. A bootstrap/compiler partition can avoid the cycle only with a justified exclusion of compiler-relevant unrepresented reads from bootstrap files. Parent authentication alone does not establish that exclusion. No actual candidate partition, witness finalization order or exclusion proof was supplied. + +2. **Genuine proc and process ownership.** Parent-domain source lines79–110 reads real /proc/PID/stat and derives PID, PPID, group, session, start ticks, state and RSS. Only its initial metadata operation's FileNotFoundError/ProcessLookupError establishes absence; a permission error is not an absent process. Lines137–158 enumerates real numeric /proc entries. Lines188–223 creates a process-local domain with an actual parent identity, exact unknown-resource owner and no preexisting children; the registry permits fewer than four earlier domains. Lines295–307 binds the exact Popen object and genuine generation/session. Lines414–436 requires actual CLOSED state, returncode0, closed pidfds, no remaining/reaped/orphan descendants and a fresh postcleanup census. These are lifecycle predicates, not filesystem confinement. + + Denying all proc access, substituting synthetic metadata, or serializing a successful census would fail to preserve these predicates. The source itself disclaims hostile privileged-host resistance. A specific outside-proc permission policy has not been established here. + +3. **Mappings, launch and mutable controls.** Native TCB lines158–188 requires the actual executable mapped-path set to equal the declared native inventory and every mapped device/inode to equal the current opened file. A fresh exec in the copied view may satisfy this; merely changing the tree beneath an already loaded process need not. Native controls lines55–97 creates, writes, reads, truncates and unlinks an owned scratch file. An entirely read-only filesystem is incompatible with that control; a distinct owned generated area needs closed incoming-data/writer provenance. + + Parent supervisor lines45–54 requires /usr/bin/python3.12, the exact original flags/environment/system stdlib path and one actual task. Lines143–175 rechecks native source supplements and libffi alias/import origins, installs/readbacks same-process subreaper state and retains the native keeper. An old host capability cannot be reconstructed from JSON after fresh exec. The copied view must include the named interpreter, loader/native/stdlib/control inputs with matching actual resolutions; exact bytes alone do not prove access, initial mappings or lifetime immutability. + + Sealed ELF profile lines1–6 and839–848 is explicitly a pure static byte/policy predicate. Preserving those exact inputs preserves that narrow parse question; it supplies neither filesystem confinement nor loader/process admission. Its static receipt cannot stand in for the native mapping or parent ownership checks. + +4. **Unchanged Root is usable conditionally; unchanged parent completion is not the prefix receiver.** Exact f5 Root lines805–833 hashes the selected driver against argv, compiles the authenticated bytes and executes that module through its real _entry route. It does not confer an unrestricted new parent authority. Parent completion lines387–396 fixes original variant driver/probe paths, launch binding and all26 raw names. Lines622–626 performs actual Popen with the original env/cwd/log FDs, stdin DEVNULL, close_fds, empty pass_fds, new session and child resource limit. Lines773–784 requires owned terminal facts and empty stderr before full producer validation. Lines836–842 is the original completion/accept mint site. A negative prefix traceback therefore cannot be admitted through this unchanged completion branch. + + The parent receiver closure is also concrete: parent_closure lines146–164 authenticates an exact module set, source origin and compiled function correspondence; lines193–229 binds concrete imports/literals and retains an in-process capability; lines242–258 checks namespace identity/census, bindings and source pins. Source-admitted successors require explicit updated source/pins/closure handling; replacing functions or presenting a serialized seal is insufficient. Unit02's frozen SOURCE-GATE-CLOSE-v1.json records no bootstrap implementation and no accepted complete milestone. + +5. **What channel evidence is absent.** No retained record supplies a concrete lookup/access policy for cwd/root/dirFD starts; alias/mount/propagation classes; initial ordinary FDs and mappings; subsequent descriptor transfer/process-memory/proc-root/namespace access; IPC/devices; owned writable output/tmp and all writers; exec descendants; or consequential clock/metadata/kernel observations. Pro5 lines325–388 correctly treats accessible outside-proc roots and later FD acquisition as conditional counterexamples to copying alone, not as observations that the fixed GCC route uses them. No relevant denial permissions, installed policy ABI or full policy were verified. Hashes and public package/source associations identify inputs but do not establish all reachable input operations or the source-to-executable correspondence needed for that particular exclusion proof. A new native policy remains a separate proposed instance and is not implicitly admitted by this review. + +## Smallest concrete next source operation + +Produce an explicit proposed layout/partition table from the already retained exact pins, leaving missing entries unresolved. For every actual runtime occurrence, record absolute path, role/consumer, exogenous/compiler/bootstrap/generated/nonordinary class, payload source/hash/size/mode, required uid/gid and access, alias/mount context and the justification for inventory inclusion or exclusion. Add the acyclic driver/configuration/witness build order, initially empty/known generated areas, and the exact process/exec transitions. + +Calculate the actual inventory count, maximum and aggregate bytes, witness shard count, serialized raw/plan node/depth/string/wire bills and separate total physical acquisition/copy/bootstrap/seal/supervision/failure costs. Do not replace occurrences with an archive row or treat the authoring count as that calculation. Record exact named missing bytes rather than starting a broad host census. + +Alongside that table, choose one concrete channel proof: either a source-specific reachable-operation argument under unchanged permissions (with correspondence adequate to that argument), or an explicitly proposed sufficient policy and its feature/permission/original-compatibility obligations. The latter needs a separate authority decision before native implementation. Both need the genuine proc/native/scratch/same-parent owner conditions above and a distinct non-minting prefix supervisor. These source records can be authored without executing the original target. There is currently no basis to implement a supposedly sealed image owner as though the channel and cap gate had passed. + +## Refusal-observer disposition + +The immutable consultation observer SHA fa0ecf7d6574bfa1a8768079b163a7621c3d3765a0e48456fb14674582cb5c46, lines63–64, and RESPONSE-v1.txt line475 claimed rejection of truncated/nonstandard tracebacks. Its lines78–85 checked only the first heading, final exception and last File header. The retained three-line heading/terminal-frame/exception counterexample lacks all intermediate Root/prefix frames and source lines but satisfies that API. + +The final Unit01 observer is14,205 bytes, SHA abf25690d3bee4a9783ee504567c29f7fb47da670e0ec95f57cb5944bf57264f. UNIT-01-SOURCE-CLOSE-v1.json pins it, and the exported publication-v2 copy has exactly the same hash. Lines57–88 retain corroborate_raw_refusal but explicitly restrict it to terminal-site corroboration. Lines109–177 add corroborate_complete_refusal: exact f5 Root bytes, actual AST-derived Root-module/_entry and driver-module/prefix/terminal frame sequence, exact printed source lines, optional restricted contiguous caret range, exact final exception and no extra stream content. Tests lines220–240 preserve old-API=true/complete-API=false for the three-line counterexample and reject omitted/mismatched frames, source, malformed caret, junk, truncation and duplication. The frozen INDEPENDENT-REVIEW.json accepts the repaired limited source/frame/stream corroborator and retains both original false positives as defects found. + +Therefore Pro5 line611's generic call to repair the known overclaim is stale if it describes the final complete API. The legacy API intentionally remains insufficient and must not be the sole route acceptance test. Even the complete API expressly grants no ownership, authenticity, currentness, error-delivery or admission authority (lines114–118); complete original streams, actual selected bytes/launch, earlier admissions and first-reached-error evidence remain parent obligations. This task re-read source and frozen review, and ran no tests. + +Source identities and machine-readable dispositions are recorded in the companion JSON. Full C05=false; full V03=false; original execution=false; original activity credit0; costs OPEN_NOT_ZERO. + diff --git a/research/h25-c05-finite-cover-source-audit/audit/compatibility-review-v1.json b/research/h25-c05-finite-cover-source-audit/audit/compatibility-review-v1.json new file mode 100644 index 0000000000..d84f5eeee3 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/audit/compatibility-review-v1.json @@ -0,0 +1,187 @@ +{ + "schema": "unit04-independent-copy-compatibility-review-v1", + "reviewed_utc": "2026-11-02 10:28:47 UTC", + "scope": "Exact retained source and finite-cover reasoning only; two report artifacts written", + "disposition": "CONDITIONAL_SOURCE_CANDIDATE_ONLY_IMPLEMENTATION_GATE_OPEN", + "source_text_required_for_assessment_present": true, + "copied_stage_categorically_forbidden": false, + "specific_copied_instance_explicitly_admitted": false, + "user_objective_change_required_merely_to_assess_conforming_copy": false, + "new_native_policy_adopted": false, + "finite_cover": { + "accepted": "Conditional ordinary-file-origin provenance enclosure, with represented namespace/launch/nonordinary facts and closed generated provenance", + "correction": "W_read subset Occ(F) union Occ(A); Origins_file(W_read) subset Occ(F); non-file origins require Facts(N,L,K)", + "actual_read_occurrence_inclusion_in_F_alone": false, + "original_C05_generated_artifact_disposition": "Prelaunch immutable source_files and separately captured outputs support a determinant interpretation; intermediate-input and dynamic-fact representation still need explicit original-compatible review", + "compiler_correctness_proof_required_by_this_lemma": false, + "detailed_GCC_query_reconstruction_explicitly_mandated_by_C05": false + }, + "eligibility": { + "positive_anchors": [ + "CONDITIONS C02 lines15-17", + "CONDITIONS C07 lines40-42", + "CONDITIONS C13 lines70-72", + "INTERFACE lines54-64,173", + "parent_completion _validate_plan314-340; _snapshot_sources206-227; _tree230-289" + ], + "conclusion": "An independently admitted fresh installed stage is contemplated; a private copy may be a conforming installation candidate. No exact Gamma_copy/access-policy admission follows.", + "preserved_requirements": [ + "C01 original Root/API4/provider/startup/native profile", + "C03 original helper/native bytes", + "C04 preserved earlier-failure behavior", + "C06 independent static/compiler/link profiles", + "C07 immutable parent-owned ancestors and separate full-stage custody" + ] + }, + "bootstrap_partition": { + "no_self_hash_supported": true, + "anchors": [ + "INTERFACE15-19,173", + "CONDITIONS C07:40-42", + "variant_driver _variant_main692, source_files625,695" + ], + "all_installed_files_in_child_inventory_accepted": false, + "parent_authentication_proves_compiler_exclusion": false, + "compiler_only_policy_hook_in_unchanged_helper": false, + "required": "Source exclusion or effective consumer-specific restriction for relevant P inputs; acyclic witness finalization" + }, + "bounds": { + "child_source_rows": 512, + "child_file_bytes": 67108864, + "child_custody_pass_bytes": 268435456, + "parent_MAX_SOURCE_FILES": 8192, + "parent_MAX_STAGE_ENTRIES": 16384, + "actual_runtime_bill_established": false, + "witness_artifacts_free": false, + "parent_bootstrap_custody_free": false + }, + "still_missing_for_construction": [ + "Exact candidate F/P/A/K and namespace/launch/access-policy instance", + "Original-compatible generated/dynamic determinant representation", + "Compiler exclusion from unrepresented bootstrap P", + "Acyclic namespace-witness finalization", + "Complete lifetime input-channel mechanism and authority", + "Exact unchanged-profile and intended-first-refusal compatibility", + "Actual row/byte/representation/resource/physical-cost bill and independent admissions" + ], + "sources": [ + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/resolved-questions-publication-20261102T025112Z/v03-publication/research/h25-v03-source-prerequisites/snapshot/areas/field-variant-producer-v2/CONDITIONS.json", + "sha256": "70e237d6ee4ac2ccaadf01615e8106999718eb1fbb3cf7644c9fc6d3fd4463fe", + "anchors": [ + "C01:10-12", + "C02:15-17", + "C03:20-22", + "C04:25-27", + "C05:30-32", + "C06:35-37", + "C07:40-42", + "C13:70-72" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/resolved-questions-publication-20261102T025112Z/v03-publication/research/h25-v03-source-prerequisites/snapshot/areas/field-variant-producer-v2/INTERFACE.json", + "sha256": "30820f1f2d27d4d4306d8ba63db5329f89182912f7f915aede35b9ce62359491", + "anchors": [ + "15-19", + "54-64", + "75-81", + "167-179" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/resolved-questions-publication-20261102T025112Z/v03-publication/research/h25-v03-source-prerequisites/snapshot/areas/field-variant-producer-v2/variant_driver_v1.py.txt", + "sha256": "cdb1479253358508088f8aa0e1e92e6c75ffcc127e54552698598a02de061254", + "anchors": [ + "23-35", + "620-640", + "660-695", + "728-797" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/publication-audit-v1/research/h25-c05-v03-parent-interface-audit/snapshot/parent_completion_v1.py.txt", + "sha256": "d4ee1b7ce4a42b73261984ffb1b9ceb5bb0165223e04a253588f83b99f6981a5", + "anchors": [ + "25-30", + "55-56", + "206-227", + "230-311", + "314-340" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/publication-audit-v1/research/h25-c05-v03-parent-interface-audit/snapshot/parent_domain_v1.py.txt", + "sha256": "9205e14d6661fb5df0597f0ad7b2206006f2d31f01f784805f64c13875663282", + "anchors": [ + "1-8", + "95-110", + "137-157" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/publication-audit-v1/research/h25-c05-v03-parent-interface-audit/snapshot/h25_parent_supervisor.py.txt", + "sha256": "cfb09a18dd10b597cc6d5a8139ee769bef679bc44ae029329755e3d97b055075", + "anchors": [ + "45-54", + "143-175" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/prerequisite-source/native_tcb_v1.py.txt", + "sha256": "865943df5cfdbf9383362d7fb2b76c6d0fd895cf0a0e20d550a26b579606b5d7", + "anchors": [ + "54-75", + "79-121", + "158-202" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/prerequisite-source/native_tcb_controls_v1.py.txt", + "sha256": "63b1804caa7f89915662a1424f788c3becad13520e1f63212a338fb45aaa2c5a", + "anchors": [ + "55-95" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/unit03/binding/cold_build_evidence.py.txt", + "sha256": "aa0a315110e031e19291970c9611fe5e0f91465fa20eaec51e81186099563f78", + "anchors": ["220-221"], + "scope": "Previously reviewed inert source; identity rechecked without reopening Unit03" + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/consultation/RESPONSE-v5.txt", + "sha256": "a3bc66f2d226053afaea669599a8986862be7465995aadef9390556cc82a2937", + "anchors": [ + "35-100", + "159-180", + "186-323", + "364-388", + "505-511", + "565-583" + ] + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/consultation/ASSESSMENT-v5.md", + "sha256": "9bd8937634a2fd059800382e65c8318d7a309da3d5fdceae1963e53e58e95fbd" + }, + { + "path": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/unit04/PLAN.json", + "sha256": "fee0c5f1d0d5566293c65e0a81123bb6f2b5b8a163a5c1e12cc2fdac5df89727" + } + ], + "original_modules_imported": false, + "original_code_executed": false, + "tests_executed": false, + "target_inspection": false, + "external_research": false, + "native_operations": false, + "namespace_operations": false, + "closed_units_resumed": false, + "full_C05": false, + "full_V03": false, + "runtime_qualification": false, + "original_activity_credit": false, + "costs": "OPEN_NOT_ZERO" +} + diff --git a/research/h25-c05-finite-cover-source-audit/audit/compatibility-review-v1.md b/research/h25-c05-finite-cover-source-audit/audit/compatibility-review-v1.md new file mode 100644 index 0000000000..c74957a28d --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/audit/compatibility-review-v1.md @@ -0,0 +1,57 @@ +# Unit04: finite-cover and copied-instance compatibility source review + +Disposition: **conditional source candidate accepted; concrete copied-instance admission and implementation gate remain open**. The exact sources permit independently reviewed fresh installed stages. They do not themselves admit the proposed copied root, altered credentials, proc view or a new confinement policy. No user objective change is needed merely to investigate a conforming copied-stage candidate; adopting a candidate that changes preserved native/profile/behavior requirements is a separate consequential decision. + +Read-only assessment of retained originals and Pro5; no original imports/execution, tests, target inspection, external research, native operations or namespace work. Only this report and its JSON companion were written. Closed Units01/02/03 remain closed. + +## Exact findings + +1. **Correct the finite-cover statement to distinguish reads from origins.** Pro5 lines35-63 permit reads from immutable F or generated A, but lines65-98 conclude literal W_file is a subset of F. For actual ordinary read occurrences, the implication is W_read subset Occ(F) union Occ(A). Only exogenous ordinary-file origins satisfy Origins_file(W_read) subset Occ(F); non-file origins require the separately represented N/L/K facts. A generated temporary subsequently read is an immediate counterexample to the stronger occurrence statement. This is not a compiler-correctness objection. + + Actual C05 uses independently frozen prelaunch path/hash/bytes/mode rows: producer `_vcustody`620-631 and `_vcheck_custody`634-640. Outputs are separately created/captured at741-787; the inventory is checked again at788-797. Thus generated binaries are not independently expected inventory inputs learned after compilation. A determinant/provenance interpretation is plausible, but a complete original-C05 argument must explicitly discharge generated intermediate reads and dynamic determinants. Neither file-set membership nor a later receipt alone supplies it. C05's text does not mandate reconstruction of every GCC search branch, so the corrected conditional cover remains a useful alternative. + +2. **Copying is a possible installation mechanism, not an already admitted experimental instance.** CONDITIONS C02:15-17 requires independent admission of a configured successor/full installed stage; C07:40-42 assigns immutable stage and ancestors to the parent; C13:70-72 expressly calls for a separately approved fresh stage. INTERFACE54-64 binds an actual owned immutable stage, and173 separates complete child closure from parent stage verification. The parent accepts approved stage/cwd/output path fields independently (`_validate_plan`314-340), hashes current file bytes/modes (`_snapshot_sources`206-227), and compares current directory identity during its census (`_tree`230-289). These predicates do not require preservation of a historical host device/inode number. + + Therefore the sources do not establish an immutable-host-only objective or categorically exclude private copies. They also contain no grant admitting this particular Gamma_copy. Parent CONFIGURATION/SOURCE_REVIEW/FUNDING/EXECUTION_APPROVAL and producer configuration/native/stage gates remain None. Necessary conclusion: candidate-class compatibility can be assessed without changing the user's objective; actual eligibility requires the exact instance and all original independent admissions. Equivalence to Gamma_host is neither established nor required by the reviewed literal stage predicates. + +3. **The no-self-hash objection is source-supported and specific.** INTERFACE15-19 excludes driver, stage-manifest, configuration-own and full-command digests from embedded configuration;173 assigns whole-stage driver checking to the parent. C07 explicitly says the child closure avoids self hashes. The producer copies embedded VARIANT_CONFIGURATION at692 and consumes its source_files at625/695. Rendering a driver that embeds its own final source_files digest creates the dependency the interface avoids. This is a bounded-construction/interface objection, not a theorem that cryptographic fixed points cannot exist. + + Partitioning installed U into compiler inputs F, separately authenticated bootstrap P, generated A and covered nonordinary K avoids that cycle only if compiler access to relevant unrepresented P is excluded by source or an effective consumer-specific mechanism. Parent authentication is not such exclusion. The unchanged cold helper has no compiler-only policy hook: its actual Popen220-221 passes command/stdin/stdout/stderr/close_fds/start_new_session/preexec_fn, with neither cwd/env nor a confinement installer. A single policy inherited by Root and GCC that allows the driver to Root does not by that fact deny it to GCC. + +4. **A namespace witness needs an acyclic finalization argument.** A witness may omit its own digest yet still become self-dependent if it purports to contain its own final write-sensitive metadata. Original C05 requires relevant witnesses, not an automatic universal self-description. Use a justified metadata projection, an outer parent-authenticated observation where the original custody boundary permits it, or an actual compiler-input exclusion proof. None has been constructed here. Sorting a certificate is not an observed kernel enumeration order; a finite cover may instead enclose every possible selected member. + +5. **Preserve exact native/owner behavior before classifying a policy as original-compatible.** C01 preserves pristine f5 Root/API4/provider, startup and the original native profile; C03 preserves helper/native bytes; C04 preserves reviewed earlier-failure behavior; C06 fixes independent compiler/link/ELF profiles. Native TCB158-182 compares declared file-backed executable mappings with current opened-file device/inode and repeats the mapping observation. Its anonymous/kernel mapping exclusion remains explicit at202. Fresh execution from copied runtime files can address that specific copied-inode mismatch, but does not authenticate the rest of a copied parent or its policy. + + The original owner needs genuine proc census (`parent_domain`137-157), and explicitly describes a closed child-domain premise rather than a sandbox (1-8). The original native control deliberately writes/truncates/unlinks its owned scratch file (`native_tcb_controls`55-95). Supervisor45-54 fixes startup paths/flags/env/one task;143-175 reconstructs real same-process subreaper state and retains its native keeper. A blanket read-only runtime, proc denial/synthetic proc, serialized native capability, or inherited domain token does not preserve these predicates. Landlock/seccomp, changed credentials/proc restrictions and exec-domain policy are proposed native/access-policy changes, not consequences of current hashes or C05 approval. No ABI, required rights, complete channel policy or authority is admitted by this review. + +6. **Keep parent and child bounds separate.** The child limit is512 rows (producer695),64MiB per custody read (626),256MiB per pass (628); witness files consume real rows/bytes. The parent's separate constants are MAX_SOURCE_FILES=8192 and MAX_STAGE_ENTRIES=16384 (55-56), with full source/stage/serialization checks still applicable. P cannot disappear from the parent bill merely because it is outside the child inventory. No actual fitting runtime cover, witness layout or physical-cost bill was supplied to this assessment. + +## Source gate outcome + +Accepted: the corrected conditional provenance lemma; absence of a source-level categorical prohibition on a conforming copied fresh stage; the exact no-self-hash/bootstrap partition obstruction and the separate parent/child bound distinction. + +Still conditional: the relevant determinant interpretation and N/L/K representation; exact Gamma_copy relation and admission; exclusion of compiler inputs from P; acyclic witnesses; a complete lifetime channel invariant; behavior/profile compatibility; and actual cap/cost fit. Essential source text for this assessment was present. Essential construction inputs remain missing, so this assessment does not pass an implementation or native execution gate. + +The smallest next source question is concrete: supply one exact F/P/A/K layout and original-profile-preserving channel mechanism, then establish its determinant relation, acyclic witnesses and complete budget. If that mechanism changes preserved native/profile/first-refusal behavior, identify that change before requesting adoption; do not infer user approval from Pro5. + +## Retained source basis + +F = /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z + +R = /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/resolved-questions-publication-20261102T025112Z/v03-publication/research/h25-v03-source-prerequisites/snapshot/areas/field-variant-producer-v2 + +P = /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-completion-20261102T055710Z/publication-audit-v1/research/h25-c05-v03-parent-interface-audit/snapshot + +- R/CONDITIONS.json SHA256 `70e237d6ee4ac2ccaadf01615e8106999718eb1fbb3cf7644c9fc6d3fd4463fe`. +- R/INTERFACE.json SHA256 `30820f1f2d27d4d4306d8ba63db5329f89182912f7f915aede35b9ce62359491`. +- R/variant_driver_v1.py.txt SHA256 `cdb1479253358508088f8aa0e1e92e6c75ffcc127e54552698598a02de061254`. +- P/parent_completion_v1.py.txt SHA256 `d4ee1b7ce4a42b73261984ffb1b9ceb5bb0165223e04a253588f83b99f6981a5`. +- P/parent_domain_v1.py.txt SHA256 `9205e14d6661fb5df0597f0ad7b2206006f2d31f01f784805f64c13875663282`. +- P/h25_parent_supervisor.py.txt SHA256 `cfb09a18dd10b597cc6d5a8139ee769bef679bc44ae029329755e3d97b055075`. +- F/prerequisite-source/native_tcb_v1.py.txt SHA256 `865943df5cfdbf9383362d7fb2b76c6d0fd895cf0a0e20d550a26b579606b5d7`. +- F/prerequisite-source/native_tcb_controls_v1.py.txt SHA256 `63b1804caa7f89915662a1424f788c3becad13520e1f63212a338fb45aaa2c5a`. +- F/unit03/binding/cold_build_evidence.py.txt SHA256 `aa0a315110e031e19291970c9611fe5e0f91465fa20eaec51e81186099563f78`; source-only Popen anchor220-221, previously reviewed and identity rechecked here. +- F/consultation/RESPONSE-v5.txt SHA256 `a3bc66f2d226053afaea669599a8986862be7465995aadef9390556cc82a2937`. + +Full C05=false; full V03=false; runtime/native/namespace qualification=false; original activity credit=false; costs=OPEN_NOT_ZERO. + diff --git a/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-check-only.txt b/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-check-only.txt new file mode 100644 index 0000000000..a6c9fb298a --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-check-only.txt @@ -0,0 +1 @@ +PASS_PACKAGE_METADATA_AND_PINS (not a mathematical acceptance check) diff --git a/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-cold-normal.txt b/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-cold-normal.txt new file mode 100644 index 0000000000..a2c5ac9600 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-cold-normal.txt @@ -0,0 +1 @@ +PASS_FINITE_COVER_SOURCE_ARCHIVE_ONLY files=34 functions=28 text=9 metadata=56 diff --git a/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-cold-optimized.txt b/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-cold-optimized.txt new file mode 100644 index 0000000000..a2c5ac9600 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-cold-optimized.txt @@ -0,0 +1 @@ +PASS_FINITE_COVER_SOURCE_ARCHIVE_ONLY files=34 functions=28 text=9 metadata=56 diff --git a/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-registered-static.txt b/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-registered-static.txt new file mode 100644 index 0000000000..145e2346b7 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/evidence/EXPORT-registered-static.txt @@ -0,0 +1,5 @@ +CHECK Source-archive raw bytes, exact decision metadata and selected actual text/AST anchors only; no original imports or execution +PASS_FINITE_COVER_SOURCE_ARCHIVE_ONLY files=31 functions=28 text=9 metadata=56 +CHECK Same static source-archive check under optimized Python; no original or native execution +PASS_FINITE_COVER_SOURCE_ARCHIVE_ONLY files=31 functions=28 text=9 metadata=56 +PASS_REGISTERED_RESEARCH_PACKAGE research/h25-c05-finite-cover-source-audit outcome=partial diff --git a/research/h25-c05-finite-cover-source-audit/evidence/UNIT01-INDEPENDENT-REVIEW.json b/research/h25-c05-finite-cover-source-audit/evidence/UNIT01-INDEPENDENT-REVIEW.json new file mode 100644 index 0000000000..f40a4815c0 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/evidence/UNIT01-INDEPENDENT-REVIEW.json @@ -0,0 +1,24 @@ +{ + "observed_utc": "2026-11-02T08:13:44.266384+00:00", + "reviewers": [ + "v03_source_route_review (SolMax)", + "c05_component_review (SolMax)" + ], + "scope": "Independent agent source review of exact new source increment; not human/proof-kernel or full original qualification", + "v03_repair": "PASS limited source/frame/stream corroborator; exact generator/fixture bytes and conditional genuine route confirmed", + "c05_delta": "Conditional PASS for passive incomplete increment after interior-parameter paste refusal and trailing-noLF rejection. ELF scopedPASS; all complete domain/loader/configured/namespace claims remainfalse.", + "retained_defects": [ + "original three-line traceback false positive", + "malformed separated caret false positive", + "multi-token macro argument splits source paste chain", + "trailing no-final-newline marker bypass", + "initial test .txt fixture-path error", + "GCC str.splitlines form-feed test-reader error", + "partial-clone promisor-object publication setup failure" + ], + "full_C05": false, + "full_V03": false, + "original_activity_credit": 0, + "runtime_qualified": false, + "physical_cost": "OPEN_NOT_ZERO" +} diff --git a/research/h25-c05-finite-cover-source-audit/evidence/UNIT01-SOURCE-CLOSE-v1.json b/research/h25-c05-finite-cover-source-audit/evidence/UNIT01-SOURCE-CLOSE-v1.json new file mode 100644 index 0000000000..291f6da0dc --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/evidence/UNIT01-SOURCE-CLOSE-v1.json @@ -0,0 +1,68 @@ +{ + "status": "SOURCE_WINDOW_CLOSED_PARTIAL_INCREMENT", + "recorded_utc": "2026-11-02T08:03:17.995474+00:00", + "source_hard_deadline_utc": "2026-11-02T08:00:58.143323+00:00", + "late_close_bookkeeping_preserved": true, + "last_repaired_corpus_complete_utc": "2026-11-02T07:59:59.793799+00:00", + "source_repair_tests_complete_utc": "2026-11-02T07:52:20.868026+00:00", + "source_rows": [ + { + "path": "implementation/v03_integrated_constructor_v1.py", + "bytes": 6087, + "sha256": "5e08ff84298fe1249be5e8790ea259e6179048f4736fb7eafdb6e170b8bc1cf9", + "mtime_utc": "2026-11-02T07:19:18.222409+00:00" + }, + { + "path": "implementation/v03_fixture_constructor_v1.py", + "bytes": 11065, + "sha256": "97737b9e09fe3103206588d383e62bc7fbef75caf944e88a5b8cbcda310a909e", + "mtime_utc": "2026-11-02T07:19:18.222409+00:00" + }, + { + "path": "implementation/v03_source_refusal_observer_v1.py", + "bytes": 14205, + "sha256": "abf25690d3bee4a9783ee504567c29f7fb47da670e0ec95f57cb5944bf57264f", + "mtime_utc": "2026-11-02T07:51:35.494255+00:00" + }, + { + "path": "implementation/c05_gcc_rules_v1.py", + "bytes": 33560, + "sha256": "b3b8c5229f6e1bfca8e903aae95ad306200fbdce9ebd3b80974117613f538697", + "mtime_utc": "2026-11-02T07:51:35.593255+00:00" + }, + { + "path": "implementation/c05_gcc_rules_tests_v1.py", + "bytes": 13844, + "sha256": "4141837fa615c9d1f703fd0083df3e4ff601a7b9af405b03a41ec0885a5b63e4", + "mtime_utc": "2026-11-02T07:52:19.205152+00:00" + }, + { + "path": "implementation/c05_header_edges_v1.py", + "bytes": 24920, + "sha256": "1ed7daadd2845ae2ac3047c1a3475cf76acd4b988925519a88f7385362e01d71", + "mtime_utc": "2026-11-02T07:51:35.544255+00:00" + }, + { + "path": "implementation/c05_header_edges_test_v1.py", + "bytes": 11098, + "sha256": "ffa888d5b04717cf437e90cde099607d7fb8a635fb07ca2f6cae2da656c1b012", + "mtime_utc": "2026-11-02T07:52:19.157152+00:00" + }, + { + "path": "implementation/c05_elf_edges_v1.py", + "bytes": 15905, + "sha256": "1ae92edd36b02a4fa2a17248cc97b555fc68e5147ceeae5540384ccc9659bb39", + "mtime_utc": "2026-11-02T07:26:37.799440+00:00" + } + ], + "source_changes_stopped": true, + "next_phase": "Publication preparation and independent delta review only; no automatic source extension. Assess completed namespace consultation for a distinct next dependency unit.", + "full_C05": false, + "full_V03": false, + "original_target_execution": false, + "original_activity_credit": 0, + "guarded_policy_seconds": "94.550533479", + "physical_costs": "OPEN_NOT_ZERO", + "publication_status": "NOT_YET_SUBMITTED", + "new_sources_validated": "V037testmethods+89DATAcases perprofile;header34,GCC23,ELF25 newtestmethods. All distinct from original control families." +} diff --git a/research/h25-c05-finite-cover-source-audit/run.py b/research/h25-c05-finite-cover-source-audit/run.py new file mode 100644 index 0000000000..8c0c46aece --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/run.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Run only the new static archive checker; archived code is never loaded.""" +from pathlib import Path +import importlib.util + +path = Path(__file__).resolve().with_name('verify.py') +spec = importlib.util.spec_from_file_location('finite_cover_archive_check', path) +checker = importlib.util.module_from_spec(spec) +spec.loader.exec_module(checker) +checker.main() diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/CONDITIONS.json b/research/h25-c05-finite-cover-source-audit/snapshot/CONDITIONS.json new file mode 100644 index 0000000000..fee8188ea8 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/CONDITIONS.json @@ -0,0 +1,108 @@ +{ + "additional_review_boundaries_preserved": [ + "The receiver32MiB aggregate limit is an admission check before parsing, not proof of a producer-wide disk/resource reservation.", + "Native I/O roots protect the first successfully delivered error under stated interpreter/private-state premises; inherited helper/TCB/cold-authority formatting, allocation and pre-delivery/unwind remain unqualified.", + "Parent alone supplies current launch/stage/source/terminal/domain/custody authority; child zero counters and JSON status are not that authority.", + "All25 recipe controls, full original/additive runtime union, complete configured closure, funding and execution remain open." + ], + "conditions": [ + { + "discharged_by_this_source_packet": false, + "id": "C01", + "required": "Actual parent authenticates pristine original f5 Root/API4/provider, interpreter flags/env/native startup and original native TCB profile before launch; no alternative Root or candidate bootstrap." + }, + { + "discharged_by_this_source_packet": false, + "id": "C02", + "required": "Configured successor and full installed stage receive independent source/command/review admission. Driver and receiver constants remain None here; literal configuration is never obtained from child raw data." + }, + { + "discharged_by_this_source_packet": false, + "id": "C03", + "required": "Preserve original six integration admissions and original helper/native packet bytes. Retain exact two extra control-name builds, role order, no retry, no positive triple rebuild and zero variant loads." + }, + { + "discharged_by_this_source_packet": false, + "id": "C04", + "required": "Install all six reviewed C/header variant bytes with literal hashes/sizes0444 adjacent at the source-fixed role paths. Preserve ImportError/RuntimeError and earlier failure behavior from review643892da." + }, + { + "discharged_by_this_source_packet": false, + "id": "C05", + "required": "Complete current project/system header, include search, macro, compiler, specs, linker and dependent-library witness closure must be independently approved and included in bounded source_files. Original dependency scan alone is insufficient." + }, + { + "discharged_by_this_source_packet": false, + "id": "C06", + "required": "Independently fix both complete ELFv2 static policies including required production method rows/data slots, all source/compiler/link profiles and exact changed-header bindings. Only actual build receipt SHA is populated after capture. No expected ELF answer may be learned from output." + }, + { + "discharged_by_this_source_packet": false, + "id": "C07", + "required": "Parent owns output ancestors and immutable source/stage directories. Leaf nofollow is not protection against mutable ancestor substitution. Parent verifies the full stage/driver/receiver separately before/after; child literal closure avoids self hashes." + }, + { + "discharged_by_this_source_packet": false, + "id": "C08", + "required": "Parent current receiver closure authenticates original module/function/default/builtin/source identities before and after direct validation, including exact ELFv2. Never call through an unverified arbitrary reader/checker." + }, + { + "discharged_by_this_source_packet": false, + "id": "C09", + "required": "Parent supplies actual Popen PID, generation/nonce/mode/argv and independent expected plan, reads all26 fixed current files with own identity/custody, corroborates stdout and final receipt, and alone creates terminal/ParentCompletion/epoch authority." + }, + { + "discharged_by_this_source_packet": false, + "id": "C10", + "required": "Bounded adapter I/O proof begins at first successfully delivered bound error with protected exact-list slots, original native primitives, no concurrent/async/tracing/hostile-finalizer interference and adequate delivery/unwind. Pending acquisition quarantines all new I/O; uncertain descriptors remain for parent teardown." + }, + { + "discharged_by_this_source_packet": false, + "id": "C11", + "required": "Inherited original helper/TCB/cold-authority allocation, formatting, cleanup and pre-handler-delivery errors remain unqualified. Outer capture cannot recover a prior replaced error. New local-slot proof is not whole-handler MemoryError or all-control admission." + }, + { + "discharged_by_this_source_packet": false, + "id": "C12", + "required": "Retain all raw/attempt/journal/log/partial files without overwrite/rebuild/delete. Missing/failed capture or close is STOP/incomplete, never inferred success. A returned helper object held only in process is not durable evidence." + }, + { + "discharged_by_this_source_packet": false, + "id": "C13", + "required": "Run the bounded source/control recipes in a separately approved fresh stage; preserve every failure and both execution modes. No target calls or tests occurred here." + }, + { + "discharged_by_this_source_packet": false, + "id": "C14", + "required": "Fund the complete cost and ordinary/negative/full-caller resource controls independently. This source implementation grants no execution, performance, runtime/bootstrap, scientific or final202-control admission." + }, + { + "discharged_by_this_source_packet": false, + "id": "C15", + "required": "Independently review exact-type comparator and all comparison replacements, gates before imports, exact V1/source inverses and additive type-substitution controls. Float values remain outside the original integer-only JSON domain. No target execution has qualified this source." + } + ], + "configuration": null, + "control_count_note": "The V1 review preserved all25 original recipe obligations; V2 adds8, total33 unexecuted. Receiver32MiB is an admission/parsing bound, not a producer-wide disk or resource reservation.", + "execution": null, + "parent_gate_boundary": "Current parent-completion source independently checks exact dictionaries/digests before either producer; these are externally authenticated bootstrap records, never child JSON authority. Parent V1 frozen source requires new version/review to adopt this V2 validator.", + "parent_gate_schema": { + "VALIDATION_CONFIGURATION": [ + "leaf_policy_sha256", + "configuration_sha256" + ], + "VALIDATION_EXECUTION": [ + "external_launch_policy_sha256" + ], + "VALIDATION_FUNDING": [ + "reservation_sha256" + ], + "VALIDATION_SOURCE_REVIEW": [ + "review_sha256" + ] + }, + "schema": "h25-negative-variant-producer-conditions-v2", + "source_only": true, + "v1_independent_conditions_sha256": "c844cc035df70c73223c3066d9f1f57aed2e5a37bc5fab580b0d890009ab8997", + "v1_independent_review_sha256": "978151bbce51a4ece02264cde8e8b5fcf170612d35c984246640485afbc9f22d" +} diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/INTERFACE.json b/research/h25-c05-finite-cover-source-audit/snapshot/INTERFACE.json new file mode 100644 index 0000000000..d02e2d681e --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/INTERFACE.json @@ -0,0 +1,180 @@ +{ + "builds_per_mode": 2, + "command_admission": null, + "command_hash_encoding": "sha256(canonical exact {argv: command} ASCII JSON sort_keys separators comma/colon ensure_ascii with terminal newline), matching epoch schema", + "configuration": null, + "configuration_keys": [ + "roles", + "source_files", + "additional_source_pins", + "include", + "expected_preflight", + "expected_dependencies", + "system_header_admission_sha256" + ], + "configuration_no_self_hash": [ + "driver digest", + "stage manifest digest", + "configuration own digest", + "full command digest" + ], + "configuration_role_keys": [ + "role", + "source_path", + "source", + "source_headers", + "static_policy", + "profile" + ], + "driver_install_relative": "integration/variant_driver_v1.py", + "driver_tail_argv": [ + "--output", + "", + "--generation", + "", + "--launch-nonce", + "" + ], + "elf_install_relative": "integration/sealed_elf_profile_v2.py", + "elf_module": "sealed_elf_profile_v2", + "elf_source_sha256": "89ed8c777e6b72af2d6a3595037e7e92385924c6087d88010a27192633391016", + "execution": null, + "expected_plan_keys": [ + "producer_process_id", + "configuration", + "preexec_code_sha256", + "parent_file_limits", + "initial_expected_files", + "hashlib_origin", + "binding", + "output", + "stage_root", + "raw_file_names" + ], + "expected_plan_values": { + "binding": "exact mode,generation,launch_nonce from parent plan/owned actual argv", + "configuration": "exact separately source-fixed VARIANT_CONFIGURATION values, cloned as plain JSON", + "hashlib_origin": "independent original hashlib origin", + "initial_expected_files": "independent original 8-row native profile as JSON lists", + "output": "parent-owned exclusive actual producer output root", + "parent_file_limits": "actual original parent limits captured before spawn, two exact ints", + "preexec_code_sha256": "independently approved original helper callback bytecode pin", + "producer_process_id": "actual owned Popen PID; parent supplies after launch", + "raw_file_names": "exact ordered list above; parent reads independently before receiver call", + "stage_root": "actual owned immutable stage root" + }, + "final_stdout": "exact same canonical JSON bytes as exclusive receipt.json, emitted only after durable file capture; borrowed FD1 never closed", + "funding": null, + "generation": "epoch label, 1..96 lowercase letters/digits/hyphen", + "mode": "actual sys.flags.optimize maps to normal or optimized; parent alone selects -O exactly", + "negative_only": true, + "nonce": "64 lowercase hex; data echo only, not capability", + "original_positive_builds_rebuilt": 0, + "original_provider_relative": "integration/probe_binding_v3.py", + "original_provider_sha256": "9cbb7368f89e71d1e6cc46db5dc77efed3e03ed2a801c98c88fe316e4d9f3ef2", + "parent_exclusive_authority": [ + "actual argv/env/cwd/PID/start ticks/generation", + "stage/config/root/full-command/startup/history pins", + "native/stdlib/header/compiler/link current admission", + "whole process domain terminal and source lifetime", + "ParentCompletion/ticket/epoch admission", + "current file identities and final stage/source custody" + ], + "parent_independent_elf_parses": 2, + "producer_candidate_image_loads": 0, + "profile_keys": [ + "source_manifest_sha256", + "project_headers_sha256", + "system_headers_sha256", + "compiler_link_sha256", + "link_profile_sha256" + ], + "raw_file_names": [ + "initial-tcb.raw.json", + "initial-controls.raw.json", + "initial-restoration.raw.json", + "root-before.raw.json", + "preflight-before.raw.json", + "custody-before.raw.json", + "pyinit_failure/control.attempt.json", + "pyinit_failure/control.attempt.jsonl", + "pyinit_failure/control.stdout.raw", + "pyinit_failure/control.stderr.raw", + "pyinit_failure/helper-return.raw.json", + "pyinit_failure/build.json", + "pyinit_failure/_h25_dict_probe.cpython-312-x86_64-linux-gnu.so", + "pyinit_failure/elf.raw.json", + "exec_failure/control.attempt.json", + "exec_failure/control.attempt.jsonl", + "exec_failure/control.stdout.raw", + "exec_failure/control.stderr.raw", + "exec_failure/helper-return.raw.json", + "exec_failure/build.json", + "exec_failure/_h25_dict_probe.cpython-312-x86_64-linux-gnu.so", + "exec_failure/elf.raw.json", + "preflight-after.raw.json", + "custody-after.raw.json", + "root-after.raw.json", + "receipt.json" + ], + "raw_group_relatives": [ + "initial-tcb.raw.json", + "initial-controls.raw.json", + "initial-restoration.raw.json", + "root-before.raw.json", + "preflight-before.raw.json", + "custody-before.raw.json", + "pyinit_failure/helper-return.raw.json", + "pyinit_failure/elf.raw.json", + "exec_failure/helper-return.raw.json", + "exec_failure/elf.raw.json", + "preflight-after.raw.json", + "custody-after.raw.json", + "root-after.raw.json" + ], + "receiver_export": "validate_variant_producer", + "receiver_module": "variant_validation_v1", + "result_build_file_keys": [ + "original_output", + "original_receipt", + "attempt", + "journal", + "stdout", + "stderr" + ], + "result_build_keys": [ + "role", + "command_sha256", + "profile", + "files" + ], + "result_keys": [ + "schema", + "raw_result_relative", + "raw_group_relatives", + "builds", + "zero_candidate_loads", + "not_runtime_authority" + ], + "result_schema": "h25-negative-variant-data-authentication-v1", + "schema": "h25-negative-variant-producer-interface-v1", + "signature": "validate_variant_producer(raw_files: exact dict[str, bytes], expected_plan: exact dict) -> bounded plain dict", + "source_file_layout": "/areas/field-negative-variants-v1//{dict_probe_fields_v1.c,field_service_v1.h,field_loader_snapshot_v1.h}, all0444; literal reviewed SHA/size enforced", + "source_files": [ + "variant_driver_v1.py", + "variant_validation_v1.py" + ], + "source_files_row_keys": [ + "path", + "sha256", + "bytes", + "mode" + ], + "source_files_scope": "complete independently reviewed project/source/header/compiler/search/macro/specs/link input closure with up to512 entries/256MiB per capture; parent independently verifies whole installed stage including this driver before and after, avoiding self hashes", + "source_review": null, + "stage_admission": null, + "static_policy": "exact pinned ELFv2 static policy with build_receipt_sha256 null only; actual captured build.json hash fills that binding after build, no learned expected ELF fields; source/compiler/link closure pins agree with profile", + "status": "SOURCE_ONLY_ALL_GATES_UNSET", + "unchanged_root": "stages/combined-finite-v8/integration/full_driver.py", + "unchanged_root_sha256": "f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0" +} diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/cold_build_evidence.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/cold_build_evidence.py.txt new file mode 100644 index 0000000000..9154e9300c --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/cold_build_evidence.py.txt @@ -0,0 +1,312 @@ +"""Retained evidence for only the three new native metadata compilations. + +The parent owns the outer process group, RSS guard and termination/join. Failure +snapshots are provisional while descendants can retain the raw-log descriptors. +No session or process group is created here. This module never runs on import. +""" +import hashlib +import json +import os +from pathlib import Path +import resource +import subprocess +import time +from types import BuiltinFunctionType, FunctionType + +OPERATIONAL_LOG_BYTES = 2 * 1024 * 1024 +CHILD_FILE_BYTES = 16 * 1024 * 1024 +READ_CHUNK_BYTES = 65536 +PREVIEW_BYTES = 512 +RECEIPT_BYTES = 65536 +POLL_SECONDS = 0.02 + + +class ColdBuildOutputLimit(RuntimeError): + pass + + +def _need(condition, message): + if not condition: + raise RuntimeError(message) + + +def _fingerprint(info): + return (info.st_dev, info.st_ino, info.st_mode, info.st_size, + info.st_mtime_ns, info.st_ctime_ns) + + +def _write_all(descriptor, raw): + offset = 0 + while offset < len(raw): + written = os.write(descriptor, raw[offset:]) + _need(written > 0, 'Cold build evidence write made no progress') + offset += written + + +def _encode(record): + raw = json.dumps(record, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode('ascii') + b'\n' + _need(len(raw) <= RECEIPT_BYTES, 'Cold build attempt receipt exceeded its declared bound') + return raw + + +def _record(journal_descriptor, attempt_path, record): + """Append intent first; atomic latest receipt cannot erase prior intent.""" + raw = _encode(record) + _write_all(journal_descriptor, raw) + os.fsync(journal_descriptor) + temporary = str(attempt_path) + '.pending' + descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600) + try: + _write_all(descriptor, raw) + os.fsync(descriptor) + finally: + os.close(descriptor) + os.replace(temporary, attempt_path) + + +def _secondary_notice(error, phase, attempt_path): + """Bounded independent outer-stderr evidence when local evidence I/O fails.""" + try: + message = str(error) + record = {'schema': 'h25-cold-build-secondary-error-v1', 'phase': phase, + 'attempt_path': str(attempt_path), 'type': type(error).__name__, + 'message_prefix': message[:1024], 'message_truncated': len(message) > 1024} + _write_all(2, _encode(record)) + except BaseException: + # A broken outer stderr cannot be repaired inside this failed process. + pass + + +def _one_thread(): + """Bounded actual task census, not threading.enumerate or a remembered PASS.""" + tasks = [] + with os.scandir('/proc/self/task') as entries: + for entry in entries: + tasks.append(entry.name) + _need(len(tasks) <= 1, 'Cold build preexec requires exactly one live process task') + expected = str(os.getpid()) + _need(tasks == [expected], 'Cold build preexec task identity differs') + return {'process_id': os.getpid(), 'task_ids': [int(expected)], 'task_count': 1} + + +def _limit_callback(): + """Capture one builtin and immutable values; this changes the child only.""" + setter, getter = resource.setrlimit, resource.getrlimit + for entry, name in ((setter, 'setrlimit'), (getter, 'getrlimit')): + _need(type(entry) is BuiltinFunctionType and entry.__self__ is resource and entry.__name__ == name, + 'Cold build resource primitive owner differs') + resource_id = resource.RLIMIT_FSIZE + _need(type(resource_id) is int and resource_id == 1, 'Cold build Linux RLIMIT_FSIZE differs') + original = getter(resource_id) + _need(type(original) is tuple and len(original) == 2 and + all(type(value) is int and (value == resource.RLIM_INFINITY or value >= CHILD_FILE_BYTES) + for value in original), 'Existing file limit is below the declared child cap') + limits = (CHILD_FILE_BYTES, CHILD_FILE_BYTES) + + def apply_child_limit(): + setter(resource_id, limits) + + captured = (apply_child_limit.__code__, apply_child_limit.__defaults__, + apply_child_limit.__kwdefaults__, + tuple(cell.cell_contents for cell in apply_child_limit.__closure__)) + _need(apply_child_limit.__code__.co_names == () and + apply_child_limit.__code__.co_freevars == ('limits', 'resource_id', 'setter'), + 'Cold build preexec closure unexpectedly reads globals') + return apply_child_limit, captured, original + + +def _check_limit_callback(callback, captured): + _need(type(callback) is FunctionType and callback.__code__ is captured[0] and + callback.__defaults__ is captured[1] is None and callback.__kwdefaults__ is captured[2] is None and + len(callback.__closure__) == len(captured[3]) and + all(cell.cell_contents is expected for cell, expected in zip(callback.__closure__, captured[3])), + 'Cold build preexec closure changed before fork') + limits, resource_id, setter = captured[3] + _need(type(limits) is tuple and limits == (CHILD_FILE_BYTES, CHILD_FILE_BYTES) and + type(resource_id) is int and resource_id == resource.RLIMIT_FSIZE == 1 and + type(setter) is BuiltinFunctionType and setter is resource.setrlimit and + setter.__self__ is resource and setter.__name__ == 'setrlimit', + 'Cold build captured native resource setter changed') + + +def _snapshot(path, writer_descriptor, *, success): + """At most 2 MiB hashed and 512 bytes previewed, even for a failed writer.""" + descriptor = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW) + try: + before = os.fstat(descriptor) + writer = os.fstat(writer_descriptor) + _need((before.st_dev, before.st_ino) == (writer.st_dev, writer.st_ino) and + (before.st_mode & 0o170000) == 0o100000, 'Cold build raw log ownership differs') + remaining = min(before.st_size, OPERATIONAL_LOG_BYTES) + digest, count, preview = hashlib.sha256(), 0, b'' + while remaining: + block = os.read(descriptor, min(READ_CHUNK_BYTES, remaining)) + if not block: + break + digest.update(block) + count += len(block) + remaining -= len(block) + if len(preview) < PREVIEW_BYTES: + preview += block[:PREVIEW_BYTES - len(preview)] + after = os.fstat(descriptor) + stable = _fingerprint(before) == _fingerprint(after) + if success: + _need(before.st_size <= OPERATIONAL_LOG_BYTES and stable and count == before.st_size, + 'Completed compiler log is oversized, short or changed while hashed') + return {'path': str(path), 'bytes_before': before.st_size, 'bytes_after': after.st_size, + 'prefix_bytes_hashed': count, 'prefix_sha256': digest.hexdigest(), + 'preview_bytes': len(preview), 'preview_utf8': preview.decode('utf-8', errors='replace'), + 'stable_during_snapshot': stable, + 'complete_file_sha256': digest.hexdigest() if success else None, + 'raw_finality': ('DIRECT_CHILD_EXIT0_AND_STABLE_COMPLETED_LOG' if success else + 'PROVISIONAL_UNTIL_OUTER_PROCESS_GROUP_TERMINATED_AND_JOINED'), + 'operational_threshold_bytes': OPERATIONAL_LOG_BYTES, + 'child_inherited_hard_file_limit_bytes': CHILD_FILE_BYTES} + finally: + os.close(descriptor) + + +def run(command, directory, name, timeout_seconds, context): + """Run a single pinned compiler or separately approved bounded toy command. + + Failure never kills or declares descendants joined. It records available raw + prefixes and raises the original exception for the outer guard to terminate + and join the complete existing process group. Native compilation sources and + binary custody are checked independently by native_packet.prepare. + """ + _need(type(command) is list and 1 <= len(command) <= 64 and + all(type(value) is str and len(value) <= 8192 for value in command) and + command[0].startswith('/'), 'Cold build command must be bounded with absolute executable') + _need(type(timeout_seconds) in (int, float) and 0 < timeout_seconds <= 15, + 'Cold build timeout is outside its declared bound') + _need(type(name) is str and name in ('production', 'watcher', 'bounds', 'control'), + 'Cold build evidence name differs') + directory = Path(directory) + _need(directory.is_absolute() and directory.is_dir() and not directory.is_symlink(), + 'Cold build evidence directory must be existing absolute regular directory') + stdout_path, stderr_path = directory / (name + '.stdout.raw'), directory / (name + '.stderr.raw') + attempt_path, journal_path = directory / (name + '.attempt.json'), directory / (name + '.attempt.jsonl') + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW + journal = os.open(journal_path, flags, 0o600) + stdout = stderr = None + process = None + phase, spawn_entered, spawn_returned = 'prelaunch', False, False + primary_in_flight = False + record = {'schema': 'h25-cold-build-attempt-v1', 'status': 'PRELAUNCH_INTENT', + 'command': list(command), 'timeout_seconds': timeout_seconds, 'context': context, + 'stdout_path': str(stdout_path), 'stderr_path': str(stderr_path), + 'attempt_path': str(attempt_path), 'journal_path': str(journal_path), + 'process_group_policy': 'INHERIT_OUTER_GROUP_NO_NEW_SESSION', + 'operational_log_threshold_bytes': OPERATIONAL_LOG_BYTES, + 'child_only_inherited_hard_file_limit_bytes': CHILD_FILE_BYTES, + 'returncode': None, 'process_id': None, 'direct_child_reaped': None, + 'spawn_entered': False, 'spawn_returned': False, + 'descendant_termination_joined': False, + 'failure_log_hashes_final': False} + try: + # Files and durable intent exist before any subprocess operation. + stdout = os.open(stdout_path, flags, 0o600) + stderr = os.open(stderr_path, flags, 0o600) + _record(journal, attempt_path, record) + callback, captured, original_limits = _limit_callback() + record['parent_file_limits_before'] = list(original_limits) + record['preexec_code_sha256'] = hashlib.sha256(callback.__code__.co_code).hexdigest() + _check_limit_callback(callback, captured) + record['single_thread_before_spawn'] = _one_thread() + # No callbacks, imports, thread starts or mutable configuration operations + # occur between this actual census/closure check and the subprocess call. + phase, spawn_entered = 'spawn', True + started = time.monotonic() + process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr, + close_fds=True, start_new_session=False, preexec_fn=callback) + spawn_returned = True + record.update(status='STARTED', process_id=process.pid, spawn_entered=True, spawn_returned=True) + _record(journal, attempt_path, record) + phase = 'wait' + while True: + code = process.poll() + sizes = (os.fstat(stdout).st_size, os.fstat(stderr).st_size) + if max(sizes) > OPERATIONAL_LOG_BYTES: + raise ColdBuildOutputLimit('Compiler raw log exceeded the 2 MiB operational threshold') + if code is not None: + code = process.wait() # actual completed wait, never an invented returncode + record.update(returncode=code, direct_child_reaped=True) + break + remaining = timeout_seconds - (time.monotonic() - started) + if remaining <= 0: + raise subprocess.TimeoutExpired(command, timeout_seconds) + time.sleep(min(POLL_SECONDS, remaining)) + if code != 0: + raise subprocess.CalledProcessError(code, command) + phase = 'success_log_snapshot' + os.fsync(stdout) + os.fsync(stderr) + logs = {'stdout': _snapshot(stdout_path, stdout, success=True), + 'stderr': _snapshot(stderr_path, stderr, success=True)} + _need(resource.getrlimit(resource.RLIMIT_FSIZE) == original_limits, + 'Compiler child limit changed the parent process limits') + record.update(status='EXIT0_LOGS_STABLE_PENDING_SOURCE_CUSTODY', logs=logs, + parent_file_limits_after=list(resource.getrlimit(resource.RLIMIT_FSIZE)), + failure_log_hashes_final=False) + _record(journal, attempt_path, record) + return record + except BaseException as primary_error: + primary_in_flight = True + # Metadata is secondary; it must never erase or replace a launch/wait error. + try: + code = None if process is None else process.poll() + record.update(status=('TIMEOUT' if isinstance(primary_error, subprocess.TimeoutExpired) else + 'NONZERO_EXIT' if isinstance(primary_error, subprocess.CalledProcessError) else + 'LOG_LIMIT' if isinstance(primary_error, ColdBuildOutputLimit) else + 'STARTUP_FAILURE' if phase == 'spawn' else + 'PRELAUNCH_REJECTION' if phase == 'prelaunch' else 'EVIDENCE_FAILURE'), + failure_phase=phase, spawn_entered=spawn_entered, spawn_returned=spawn_returned, + returncode=code, direct_child_reaped=(code is not None if process is not None else None), + error={'type': type(primary_error).__name__, 'message': str(primary_error)}, + timeout_output_policy='RAW_FILES_RETAINED_NO_PIPE_CAPTURE', + descendant_termination_joined=False, failure_log_hashes_final=False) + logs = {} + for key, path, descriptor in (('stdout', stdout_path, stdout), ('stderr', stderr_path, stderr)): + if descriptor is not None: + try: + logs[key] = _snapshot(path, descriptor, success=False) + except BaseException as snapshot_error: + logs[key] = {'path': str(path), 'complete_file_sha256': None, + 'raw_finality': 'PROVISIONAL_UNTIL_OUTER_PROCESS_GROUP_TERMINATED_AND_JOINED', + 'snapshot_error': {'type': type(snapshot_error).__name__, + 'message': str(snapshot_error)}} + record['logs'] = logs + _record(journal, attempt_path, record) + except BaseException as evidence_error: + # PRELAUNCH_INTENT/STARTED journal and raw files remain independent. + _secondary_notice(evidence_error, 'failure-evidence', attempt_path) + raise + finally: + close_errors = [] + for descriptor in (stdout, stderr): + if descriptor is not None: + try: + os.close(descriptor) + except OSError as close_error: + close_errors.append(close_error) + _secondary_notice(close_error, 'raw-log-parent-close', attempt_path) + if close_errors: + try: + record.update(prior_status=record.get('status'), status='EVIDENCE_FAILURE', + failure_phase='raw-log-parent-close', + close_errors=[{'type': type(error).__name__, 'message': str(error)} + for error in close_errors], + failure_log_hashes_final=False) + for row in record.get('logs', {}).values(): + row['complete_file_sha256'] = None + row['raw_finality'] = 'PROVISIONAL_UNTIL_OUTER_PROCESS_GROUP_TERMINATED_AND_JOINED' + _record(journal, attempt_path, record) + except BaseException as evidence_error: + _secondary_notice(evidence_error, 'close-evidence', attempt_path) + try: + os.close(journal) + except OSError as close_error: + close_errors.append(close_error) + _secondary_notice(close_error, 'journal-parent-close', attempt_path) + if close_errors and not primary_in_flight: + raise close_errors[0] diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/full_driver.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/full_driver.py.txt new file mode 100644 index 0000000000..89146269ee --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/full_driver.py.txt @@ -0,0 +1,851 @@ +"""Parent-owned pristine bootstrap; SOURCE ONLY until the parent execution gate. + +The parent authenticates this first script, executable and native dependency +closure before launch. Its clean -S -s -P -B process is the initial trust root; +these checks do not retrospectively prove that provenance. No candidate, +scientific, plugin or callback code may precede root capture. +""" +import builtins +import sys +import posix +import _imp +import _hashlib + +def _make_metadata_factory(): + # Capture these native operations before any candidate/provider code exists. + type0, id0, len0, next0 = type, id, len, next + dict0, tuple0, str0, int0, bool0, bytes0 = dict, tuple, str, int, bool, bytes + error, value_error, base_error = RuntimeError, ValueError, BaseException + function_type, module_type = type(lambda: None), type(sys) + builtin_type = type(len) + cell_type = type((lambda item: lambda: item)(None).__closure__[0]) + proxy_type = type(type.__dict__) + none_type = type(None) + function_fields = tuple((name, function_type.__dict__[name].__get__) for name in + ('__code__', '__globals__', '__builtins__', '__defaults__', + '__kwdefaults__', '__closure__')) + mro_get = type.__dict__['__mro__'].__get__ + module_dict_get = module_type.__dict__['__dict__'].__get__ + builtin_self_get = builtin_type.__dict__['__self__'].__get__ + cell_get = cell_type.__dict__['cell_contents'].__get__ + dict_get, dict_set, dict_clear = dict.get, dict.__setitem__, dict.clear + dict_iter, dict_len = dict.__iter__, dict.__len__ + proxy_get, proxy_iter, proxy_len = proxy_type.get, proxy_type.__iter__, proxy_type.__len__ + tuple_get, tuple_len = tuple.__getitem__, tuple.__len__ + missing = object() + missing_id = id0(missing) + + def new_scope(): + # Keys contain only source-owned names and identity integers. Values are + # integers, booleans or fixed tuples of those; never actual current data. + observations = {} + live = [True] + counters = [0, 0, 0, 0, 0, 0] + + def field_id(owner, selector): + try: + if not live[0]: + raise error('Metadata scope was already disposed') + if type0(selector) is not str0: + return -1 + token = ('field', id0(owner), selector) + prior = dict_get(observations, token, missing) + if prior is not missing: + counters[1] += 1 + return prior + kind = type0(owner) + actual_id = -1 + if kind is function_type: + for name, getter in function_fields: + if selector == name: + actual_id = id0(getter(owner, function_type)) + break + elif kind is type0 and selector == '__mro__': + actual_id = id0(mro_get(owner, type0)) + elif kind is module_type and selector == '__dict__': + actual_id = id0(module_dict_get(owner, module_type)) + elif kind is builtin_type and selector == '__self__': + actual_id = id0(builtin_self_get(owner, builtin_type)) + dict_set(observations, token, actual_id) + counters[0] += 1 + return actual_id + finally: + # Even a misuse or unexpected native exception cannot retain a + # newly supplied owner through this helper's traceback frame. + owner = kind = None + + def length(owner): + try: + if not live[0]: + raise error('Metadata scope was already disposed') + token = ('length', id0(owner)) + prior = dict_get(observations, token, missing) + if prior is not missing: + counters[1] += 1 + return prior + kind = type0(owner) + if kind is dict0: + value = dict_len(owner) + elif kind is proxy_type: + value = proxy_len(owner) + else: + value = -1 + dict_set(observations, token, value) + counters[0] += 1 + return value + finally: + owner = kind = None + + def domain(owner): + iterator = key = None + try: + if not live[0]: + raise error('Metadata scope was already disposed') + token = ('key-domain', id0(owner)) + prior = dict_get(observations, token, missing) + if prior is not missing: + counters[1] += 1 + return prior + kind = type0(owner) + if kind is dict0: + iterator = dict_iter(owner) + elif kind is proxy_type: + iterator = proxy_iter(owner) + else: + dict_set(observations, token, False) + counters[0] += 1 + return False + counters[2] += 1 + while True: + key = next0(iterator, missing) + if key is missing: + break + counters[3] += 1 + if type0(key) is not str0: + dict_set(observations, token, False) + counters[0] += 1 + return False + key = None + dict_set(observations, token, True) + counters[0] += 1 + return True + finally: + # The current key can be a foreign finalizable object. It must + # be dropped before the caller raises any rejection exception. + key = iterator = owner = kind = None + + def get_id(owner, name, absent): + try: + if not live[0]: + raise error('Metadata scope was already disposed') + if type0(name) is not str0 or not domain(owner): + return -1 + token = ('lookup', id0(owner), name) + observed_id = dict_get(observations, token, missing) + if observed_id is missing: + if type0(owner) is dict0: + observed_id = id0(dict_get(owner, name, missing)) + else: + observed_id = id0(proxy_get(owner, name, missing)) + if observed_id == missing_id: + observed_id = 0 + dict_set(observations, token, observed_id) + counters[0] += 1 + else: + counters[1] += 1 + return id0(absent) if observed_id == 0 else observed_id + finally: + owner = absent = None + + def cell_info(cell): + try: + if not live[0]: + raise error('Metadata scope was already disposed') + token = ('cell', id0(cell)) + prior = dict_get(observations, token, missing) + if prior is not missing: + counters[1] += 1 + return prior + if type0(cell) is not cell_type: + result = (False, -1) + else: + try: + result = (True, id0(cell_get(cell, cell_type))) + except value_error: + result = (False, 0) + dict_set(observations, token, result) + counters[0] += 1 + return result + finally: + cell = None + + def immutable_equal(actual, expected): + child = None + try: + kind = type0(actual) + if kind is not expected[0]: + return False + if (kind is none_type or kind is bool0 or kind is int0 or + kind is str0 or kind is bytes0): + return actual == expected[1] + if kind is not tuple0 or tuple_len(actual) != tuple_len(expected[2]): + return False + index = 0 + for expected_child in expected[2]: + child = tuple_get(actual, index) + if not immutable_equal(child, expected_child): + return False + child = None + index += 1 + return True + finally: + # Structural root defaults are deliberately compared afresh; + # observed trees and their contents never enter the scalar map. + child = actual = kind = None + + def keyword_equal(owner, name, expected): + actual = None + try: + if not live[0]: + raise error('Metadata scope was already disposed') + if type0(owner) is not dict0 or type0(name) is not str0 or not domain(owner): + return False + actual = dict_get(owner, name, missing) + counters[4] += 1 + if actual is missing: + return False + return immutable_equal(actual, expected) + finally: + actual = owner = None + + def statistics(): + # No object identity or observed current value escapes in a receipt. + return {'actual_reads': counters[0], 'reused_reads': counters[1], + 'key_domain_scans': counters[2], 'key_type_reads': counters[3], + 'structural_keyword_reads': counters[4], 'close_calls': counters[5], + 'live': live[0], 'retained_scalar_cells': dict_len(observations)} + + def close(): + # Idempotent disposal makes both normal and exceptional tail paths + # safe. There is no scope registry and no reuse by a later call. + dict_clear(observations) + live[0] = False + counters[5] += 1 + + return (field_id, length, get_id, cell_info, keyword_equal, statistics, close) + + return new_scope + +def _scope_factory_gate(factory): + """Cold private authenticator; returned gate has no effective global loads. + + The gate itself is captured only in private guard closures. The public + factory remains covered by normal root/provider records as well. These + direct native reads run before invoking any mutable collector code. + """ + type0, id0 = type, id + error, value_error = RuntimeError, ValueError + function_type = type(lambda: None) + cell_type = type((lambda item: lambda: item)(None).__closure__[0]) + fields = tuple((function_type.__dict__[name].__get__, getattr(factory, name)) for name in + ('__code__', '__globals__', '__builtins__', '__defaults__', + '__kwdefaults__', '__closure__')) + cells = () if factory.__closure__ is None else tuple( + (cell, cell.cell_contents) for cell in factory.__closure__) + cell_get = cell_type.__dict__['cell_contents'].__get__ + + def checked_scope(): + if type0(factory) is not function_type: + raise error('Metadata collector exact function changed') + for getter, expected in fields: + if id0(getter(factory, function_type)) != id0(expected): + raise error('Metadata collector calling environment changed') + for cell, expected in cells: + try: + observed_id = id0(cell_get(cell, cell_type)) + except value_error: + raise error('Metadata collector closure became empty') from None + if observed_id != id0(expected): + raise error('Metadata collector closure value changed') + return factory() + + return checked_scope + +_TYPE, _OBJECT, _DICT, _TUPLE, _STR, _INT = type, object, dict, tuple, str, int +_LEN, _ID, _GLOBALS = len, id, globals +_ERROR, _BASE_ERROR, _OSERROR = RuntimeError, BaseException, OSError +_COMPILE, _EXEC = compile, exec +ModuleType, FunctionType = type(sys), type(lambda: None) +CodeType, BuiltinFunctionType = type((lambda: None).__code__), type(len) +_OPEN, _READ, _FSTAT, _CLOSE, _GETPID = posix.open, posix.read, posix.fstat, posix.close, posix.getpid +_SHA256 = _hashlib.openssl_sha256 +_CREATE_DYNAMIC, _EXEC_DYNAMIC = _imp.create_dynamic, _imp.exec_dynamic +_GETTRACE, _GETPROFILE = sys.gettrace, sys.getprofile +_FLAGS = posix.O_RDONLY | posix.O_CLOEXEC | posix.O_NOFOLLOW +_PROC_FLAGS = posix.O_RDONLY | posix.O_CLOEXEC +_ENVIRONMENT = {b'PATH': b'/usr/bin:/bin', b'PYTHONHASHSEED': b'0', b'LANG': b'C.UTF-8', + b'LC_ALL': b'C.UTF-8', b'TZ': b'UTC', b'PYTHONDONTWRITEBYTECODE': b'1'} +_INITIAL_PATH = ('/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload') +_ROOT_NAME = '_h25_probe_bootstrap_v3' +_ROOT_MODULE = sys.modules[__name__] +_ROOT_NAMESPACE = globals() +_ROOT_PID = _GETPID() +_ROOT_SYS = sys +_ROOT_SYS_NAMESPACE = sys.__dict__ +_ROOT_MODULES = sys.modules +_ROOT_FLAGS = sys.flags +_OPTIMIZE = sys.flags.optimize +_MISSING = object() +_CAPABILITIES = {} +_LOADS = {} +_ROOT_CELL = [] +_ROOT_METADATA = {} +_MAX_SOURCE = 262144 +_MAX_BINARY = 16777216 +_NATIVE_NAME = '_h25_dict_probe' +_ROOT_RECORD_NAMES = ('builtins', 'sys', 'posix', '_imp', '_hashlib') +_ROOT_MODULE_RECORDS = tuple((name, sys.modules[name]) for name in _ROOT_RECORD_NAMES) +_NATIVE_RECORDS = ( + (builtins, 'type', type), (builtins, 'object', object), (builtins, 'dict', dict), + (builtins, 'tuple', tuple), (builtins, 'str', str), (builtins, 'int', int), + (builtins, 'len', len), (builtins, 'id', id), (builtins, 'globals', globals), + (builtins, 'compile', compile), (builtins, 'exec', exec), + (posix, 'open', _OPEN), (posix, 'read', _READ), (posix, 'fstat', _FSTAT), + (posix, 'close', _CLOSE), (posix, 'getpid', _GETPID), + (_hashlib, 'openssl_sha256', _SHA256), + (_imp, 'create_dynamic', _CREATE_DYNAMIC), (_imp, 'exec_dynamic', _EXEC_DYNAMIC), + (sys, 'gettrace', _GETTRACE), (sys, 'getprofile', _GETPROFILE)) + + +_NATIVE_NAMESPACES = tuple((module, module.__dict__, name, value) + for module, name, value in _NATIVE_RECORDS) +_NEW_SCOPE = _make_metadata_factory() + + +def _need(condition, message): + if not condition: + raise _ERROR(message) + + +def _code_names(code): + names = set(code.co_names) + for constant in code.co_consts: + if _TYPE(constant) is CodeType: + names.update(_code_names(constant)) + return names + + +def _immutable_default(value): + kind = _TYPE(value) + if value is None or kind in (bool, int, str, bytes): + return (kind, value) + if kind is tuple: + return (kind, value, tuple(_immutable_default(item) for item in value)) + raise _ERROR('Bootstrap source has unsupported mutable default contents') + + +def _function_record(function): + namespace, builtin_owner = function.__globals__, function.__builtins__ + defaults, keywords, closure = function.__defaults__, function.__kwdefaults__, function.__closure__ + default_record = _immutable_default(defaults) + keyword_record = () if keywords is None else tuple((name, _immutable_default(value)) for name, value in keywords.items()) + cells = () if closure is None else tuple((cell, cell.cell_contents) for cell in closure) + lookups = tuple((name, namespace.get(name, _MISSING), builtin_owner.get(name, _MISSING)) + for name in _code_names(function.__code__)) + return (function, function.__code__, namespace, builtin_owner, defaults, default_record, + keywords, keyword_record, closure, cells, lookups) + + +def _function_fresh(record, observations): + function, code, namespace, builtin_owner, defaults, default_record, keywords, keyword_record, closure, cells, lookups = record + field, length, get_id, cell_info, keyword_equal = observations[:5] + if not (_TYPE(function) is FunctionType and + field(function, '__code__') == _ID(code) and + field(function, '__globals__') == _ID(namespace) and + field(function, '__builtins__') == _ID(builtin_owner) and + field(function, '__defaults__') == _ID(defaults) and + field(function, '__kwdefaults__') == _ID(keywords) and + field(function, '__closure__') == _ID(closure)): + return False + # Default identity still binds recursively immutable initial contents. + # Root keyword contents retain their independent structural comparison. + if keywords is not None: + if length(keywords) != _LEN(keyword_record): + return False + for name, expected in keyword_record: + if not keyword_equal(keywords, name, expected): + return False + for cell, value in cells: + present, actual_id = cell_info(cell) + if not present or actual_id != _ID(value): + return False + for name, global_value, builtin_value in lookups: + if (get_id(namespace, name, _MISSING) != _ID(global_value) or + get_id(builtin_owner, name, _MISSING) != _ID(builtin_value)): + return False + return True + + +def _environment_guard(namespace, classes): + """Capture expected owners only in the pre-admitted pristine interval.""" + items = tuple(namespace.items()) + class_records = tuple((cls, cls.__mro__, cls.__dict__, tuple(cls.__dict__.items())) for cls in classes) + functions = [] + for _, value in items: + if type(value) is FunctionType and value not in functions: + functions.append(value) + for cls, mro, proxy, members in class_records: + for _, value in members: + if type(value) in (staticmethod, classmethod): + value = value.__func__ + if type(value) is FunctionType and value not in functions: + functions.append(value) + records = tuple(_function_record(function) for function in functions) + builtins_owner = builtins.__dict__ + builtin_items = tuple(builtins_owner.items()) + fresh, fresh_code = _function_fresh, _function_fresh.__code__ + defaults_check, defaults_code = _immutable_default, _immutable_default.__code__ + len0, id0, type0, error, missing = _LEN, _ID, _TYPE, _ERROR, _MISSING + function_type = FunctionType + code_get = FunctionType.__dict__['__code__'].__get__ + new_scope = _scope_factory_gate(_NEW_SCOPE) + def guard(observations=None): + # These original checker-code obligations precede the observation code. + if (code_get(fresh, function_type) is not fresh_code or + code_get(defaults_check, function_type) is not defaults_code): + raise error('Bootstrap checker source changed') + owned_scope = observations is None + if owned_scope: + observations = new_scope() + try: + field, length, get_id = observations[:3] + if length(namespace) != len0(items): + raise error('Bootstrap/provider namespace changed') + for name, value in items: + if get_id(namespace, name, missing) != id0(value): + raise error('Bootstrap/provider global changed: ' + name) + if length(builtins_owner) != len0(builtin_items): + raise error('Bootstrap builtins changed') + for name, value in builtin_items: + if get_id(builtins_owner, name, missing) != id0(value): + raise error('Bootstrap builtin changed: ' + name) + for cls, mro, proxy, members in class_records: + if field(cls, '__mro__') != id0(mro) or length(proxy) != len0(members): + raise error('Bootstrap/provider class changed') + for name, value in members: + if get_id(proxy, name, missing) != id0(value): + raise error('Bootstrap/provider class member changed: ' + name) + for record in records: + if not fresh(record, observations): + raise error('Bootstrap/provider function environment changed') + finally: + if owned_scope: + observations[6]() + return guard + + +def _check_root(observations=None): + owned_scope = observations is None + if owned_scope: + observations = _ROOT_CELL[1]() + try: + _ROOT_CELL[0](observations) + field, length, get_id = observations[:3] + _need(sys is _ROOT_SYS and + _TYPE(_ROOT_MODULE) is ModuleType and + field(_ROOT_MODULE, '__dict__') == _ID(_ROOT_NAMESPACE) and + field(_ROOT_SYS, '__dict__') == _ID(_ROOT_SYS_NAMESPACE) and + get_id(_ROOT_SYS_NAMESPACE, 'modules', _MISSING) == _ID(_ROOT_MODULES) and + get_id(_ROOT_SYS_NAMESPACE, 'flags', _MISSING) == _ID(_ROOT_FLAGS) and + _GETPID() == _ROOT_PID and + get_id(_ROOT_MODULES, _ROOT_NAME, _MISSING) == _ID(_ROOT_MODULE), + 'Bootstrap process/interpreter/registered root differs') + for name, module in _ROOT_MODULE_RECORDS: + _need(get_id(_ROOT_MODULES, name, _MISSING) == _ID(module), + 'Bootstrap module owner changed: ' + name) + for module, namespace, name, value in _NATIVE_NAMESPACES: + _need(field(module, '__dict__') == _ID(namespace) and + get_id(namespace, name, _MISSING) == _ID(value), + 'Bootstrap native primitive changed: ' + name) + _need(_GETTRACE() is None and _GETPROFILE() is None, 'Bootstrap trace/profile callback installed') + finally: + if owned_scope: + observations[6]() + + +def _fingerprint(info): + return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns) + + +def _hash_regular(path, limit, materialize): + _need(type(path) is str and path.startswith('/'), 'Bootstrap path must be absolute exact str') + descriptor = None + try: + descriptor = _OPEN(path, _PROC_FLAGS if path == '/proc/self/exe' else _FLAGS) + before = _FSTAT(descriptor) + _need((before.st_mode & 0o170000) == 0o100000 and 0 <= before.st_size <= limit, + 'Bootstrap file type/size differs') + digest, count, parts = _SHA256(), 0, [] + while True: + block = _READ(descriptor, min(1048576, limit + 1 - count)) + if not block: + break + count += len(block) + _need(count <= limit, 'Bootstrap file exceeded bound') + digest.update(block) + if materialize: + parts.append(block) + after = _FSTAT(descriptor) + _need(_fingerprint(before) == _fingerprint(after) and count == before.st_size, + 'Bootstrap file changed while reading') + return digest.hexdigest(), count, b''.join(parts) if materialize else None + except _OSERROR as error: + raise _ERROR('Bootstrap file could not be read: ' + path) from error + finally: + if descriptor is not None: + _CLOSE(descriptor) + + +def initialize(expected_root_sha256): + """Parent supplies its independently expected root source pin, once.""" + _check_root() + _need(not _ROOT_METADATA, 'Bootstrap root already initialized') + _need(type(expected_root_sha256) is str and len(expected_root_sha256) == 64, + 'Bootstrap root expected digest differs') + actual, size, _ = _hash_regular(__file__, _MAX_SOURCE, False) + _need(actual == expected_root_sha256, 'Bootstrap root source custody differs') + _ROOT_METADATA.update({'source_sha256': actual, 'source_bytes': size, + 'initial_sys_path': _INITIAL_PATH, 'initial_environment': tuple(sorted(_ENVIRONMENT.items())), + 'initial_flags': (sys.flags.no_site, sys.flags.no_user_site, sys.flags.safe_path, + sys.flags.dont_write_bytecode, sys.flags.ignore_environment, + sys.flags.isolated, sys.flags.hash_randomization, sys.flags.optimize)}) + return None + + +def _source_identity_scoped(observations): + _check_root(observations) + _need('source_sha256' in _ROOT_METADATA, 'Bootstrap root not initialized by parent') + return _ROOT_METADATA['source_sha256'] + + +def source_identity(): + observations = _ROOT_CELL[1]() + try: + return _source_identity_scoped(observations) + finally: + observations[6]() + + +class BootstrapCapability: + __slots__ = () + def __new__(cls): + raise _ERROR('BootstrapCapability requires source-authenticated admit_provider') + + +class _NativeSpec: + __slots__ = ('name', 'origin') + def __init__(self, name, origin): + self.name = name + self.origin = origin + + +def _capability_state(capability, observations=None): + owned_scope = observations is None + if owned_scope: + observations = _ROOT_CELL[1]() + try: + _check_root(observations) + _need(type(capability) is BootstrapCapability, 'Bootstrap capability exact class differs') + state = _CAPABILITIES.get(id(capability)) + _need(state is not None and state[0] is capability, 'Bootstrap capability not registered') + _need(_TYPE(state[1]) is ModuleType and + observations[0](state[1], '__dict__') == _ID(state[6]), + 'Bootstrap provider namespace owner differs') + state[2](observations) + return state + finally: + if owned_scope: + observations[6]() + + +def _validate_namespace(capability, namespace): + state = _capability_state(capability) + _need(state[6] is namespace, 'Bootstrap provider namespace owner differs') + return None + + +def admit_provider(provider_path, expected_provider_sha256): + _check_root() + source_identity() + _need(type(expected_provider_sha256) is str and len(expected_provider_sha256) == 64, + 'Bootstrap provider expected digest differs') + digest, _, source = _hash_regular(provider_path, _MAX_SOURCE, True) + _need(digest == expected_provider_sha256, 'Bootstrap provider source differs') + _check_root() + capability = object.__new__(BootstrapCapability) + provider = ModuleType('_h25_source_provider_v3_' + str(len(_CAPABILITIES))) + namespace = provider.__dict__ + namespace.update({'__file__': provider_path, '__builtins__': builtins.__dict__, + '_TYPE': _TYPE, '_OBJECT': _OBJECT, '_DICT': _DICT, '_TUPLE': _TUPLE, + '_STR': _STR, '_INT': _INT, '_LEN': _LEN, '_ID': _ID, '_GLOBALS': _GLOBALS, + '_ERROR': _ERROR, '_OSERROR': _OSERROR, '_OPEN': _OPEN, '_READ': _READ, + '_FSTAT': _FSTAT, '_CLOSE': _CLOSE, '_SHA256': _SHA256, + '_FLAGS': _FLAGS, '_PROC_FLAGS': _PROC_FLAGS, + 'BuiltinFunctionType': BuiltinFunctionType, 'CodeType': CodeType, + 'FunctionType': FunctionType, 'ModuleType': ModuleType, + '_BOOTSTRAP_CAPABILITY': capability, '_ROOT_VALIDATE': _validate_namespace, + '_ROOT_CREATE': _create_native, '_ROOT_EXEC': _exec_native, + '_ROOT_ACTIVATE': _activate_native, + '_MAKE_METADATA_SCOPE': _scope_factory_gate(_NEW_SCOPE)}) + code = _COMPILE(source, provider_path, 'exec', dont_inherit=True, optimize=_OPTIMIZE) + _check_root() + _EXEC(code, namespace) + _check_root() + _need(type(namespace.get('ProbeBinding')) is type and type(namespace.get('load_probe')) is FunctionType, + 'Bootstrap provider source interface differs') + guard = _environment_guard(namespace, (namespace['ProbeBinding'],)) + counts = dict(load_calls=0, native_creations=0, native_execs=0, activation_attempts=0, + successful_bindings=0, deactivation_attempts=0, cleanup_failures=0, control_module_creations=0) + _CAPABILITIES[id(capability)] = (capability, provider, guard, digest, provider_path, counts, namespace) + guard() + return capability + + +def _validate_capability_scoped(capability, expected_provider_sha256, observations): + state = _capability_state(capability, observations) + _need(type(expected_provider_sha256) is str and state[3] == expected_provider_sha256, + 'Bootstrap capability provider source pin differs') + return state[1] + + +def validate_capability(capability, expected_provider_sha256): + observations = _ROOT_CELL[1]() + try: + return _validate_capability_scoped(capability, expected_provider_sha256, observations) + finally: + observations[6]() + + +def _pending(capability): + state = _capability_state(capability) + pending = _LOADS.get(id(capability)) + _need(pending is not None and pending['capability'] is capability, + 'Bootstrap native creation requires an active authenticated load') + return state, pending + + +def _check_spec(spec, path): + _need(type(spec) is _NativeSpec and type(spec.name) is str and + type(spec.origin) is str and spec.name is _NATIVE_NAME and spec.origin is path, + 'Bootstrap narrow native specification differs') + + +def _create_native(capability, extension_path): + state, pending = _pending(capability) + _need(extension_path is pending['path'] and pending['native'] is None, + 'Bootstrap native creation path/lifecycle differs') + spec = _NativeSpec(_NATIVE_NAME, extension_path) + _check_spec(spec, extension_path) + # Final root/provider/spec checks immediately precede native creation. + _capability_state(capability) + _check_spec(spec, extension_path) + native = _CREATE_DYNAMIC(spec) + pending['native'], pending['spec'] = native, spec + state[5]['native_creations'] += 1 + _need(type(native) is ModuleType, 'Bootstrap native create returned non-module') + native.__dict__['__file__'] = extension_path + native.__dict__['__spec__'] = spec + pending['deactivate'] = native.__dict__.get('_deactivate') + return native + + +def _exec_native(capability, native): + state, pending = _pending(capability) + _need(native is pending['native'], 'Bootstrap native execution owner differs') + _check_spec(pending['spec'], pending['path']) + _EXEC_DYNAMIC(native) + state[5]['native_execs'] += 1 + return None + + +def _activate_native(capability, activate): + state, pending = _pending(capability) + native = pending['native'] + _check_spec(pending['spec'], pending['path']) + _need(type(activate) is BuiltinFunctionType and activate.__self__ is native and + activate.__name__ == '_activate' and native.__dict__.get('_activate') is activate, + 'Bootstrap activation entry owner differs') + # No arbitrary caller callback: only the authenticated owned native entry. + _capability_state(capability) + _check_spec(pending['spec'], pending['path']) + state[5]['activation_attempts'] += 1 + activate() + pending['activated'] = True + return None + + +def load_probe(capability, extension_path, expected_extension_sha256): + state = _capability_state(capability) + _need(type(extension_path) is str and extension_path.startswith('/') and + type(expected_extension_sha256) is str and len(expected_extension_sha256) == 64, + 'Bootstrap native load arguments differ') + _need(id(capability) not in _LOADS, 'Bootstrap capability already loading') + type0, module_type, builtin_type, base_error, id0 = _TYPE, ModuleType, BuiltinFunctionType, _BASE_ERROR, _ID + pending = {'capability': capability, 'path': extension_path, 'native': None, + 'spec': None, 'activated': False, 'deactivate': None} + _LOADS[id(capability)] = pending + state[5]['load_calls'] += 1 + try: + binding = state[1].load_probe(extension_path, expected_extension_sha256) + _capability_state(capability) + state[5]['successful_bindings'] += 1 + return binding + except base_error: + # Cleanup is intentionally independent of freshness validation. A module + # created but not yet executed has no active state; disarm may reject its + # missing state, which is retained as a secondary cleanup count. + native = pending['native'] + if type0(native) is module_type: + deactivate = pending['deactivate'] + if type0(deactivate) is builtin_type and deactivate.__self__ is native: + state[5]['deactivation_attempts'] += 1 + try: + deactivate() + except base_error: + state[5]['cleanup_failures'] += 1 + raise + finally: + del _LOADS[id0(capability)] + + + + +def load_control_module(capability, extension_path, expected_extension_sha256, module_name): + """Authenticated separate raw-disarmed/watcher/bounds modules for controls. + + Caller first invokes its sealed source_identity guard, then this source-bound + function without intervening callbacks. This is never scientific authority. + """ + state = _capability_state(capability) + _need(type(module_name) is str and module_name in + ('_h25_dict_probe', '_h25_probe_watch_fixture', '_h25_probe_bounds_fixture'), + 'Bootstrap control module name differs') + preflight(capability) + digest, size, _ = _hash_regular(extension_path, _MAX_BINARY, False) + _need(digest == expected_extension_sha256, 'Bootstrap control extension source differs') + spec = _NativeSpec(module_name, extension_path) + _capability_state(capability) + _need(type(spec) is _NativeSpec and spec.name is module_name and spec.origin is extension_path, + 'Bootstrap control specification differs') + native = _CREATE_DYNAMIC(spec) + state[5]['control_module_creations'] += 1 + _need(type(native) is ModuleType, 'Bootstrap control module type differs') + native.__dict__['__file__'] = extension_path + native.__dict__['__spec__'] = spec + _capability_state(capability) + _EXEC_DYNAMIC(native) + _capability_state(capability) + after_digest, after_size, _ = _hash_regular(extension_path, _MAX_BINARY, False) + _need((after_digest, after_size) == (digest, size), 'Bootstrap control extension changed') + expected_names = {'_h25_dict_probe': ('inspect', 'check', 'profile', 'counters', '_activate', '_deactivate'), + '_h25_probe_watch_fixture': ('attach', 'counts', 'detach', 'profile'), + '_h25_probe_bounds_fixture': ('bounds',)}[module_name] + for name in expected_names: + entry = native.__dict__.get(name) + _need(type(entry) is BuiltinFunctionType and entry.__self__ is native and entry.__name__ == name, + 'Bootstrap control native entry owner differs') + return native + + +def preflight(capability): + """Fresh public runtime/header/profile audit; never a reusable PASS.""" + state = _capability_state(capability) + return state[1].preflight_runtime() + + +def diagnostics(capability): + state = _capability_state(capability) + return dict(state[5]) + + + +def capture_api(): + """Sealed fourtuple; no caller receives or supplies an observation scope.""" + _check_root() + guard = _ROOT_CELL[0] + new_scope = _scope_factory_gate(_NEW_SCOPE) + identity, validate = _source_identity_scoped, _validate_capability_scoped + load, diagnostic = load_probe, diagnostics + def sealed_identity(): + observations = new_scope() + try: + guard(observations) + return identity(observations) + finally: + observations[6]() + def sealed_validate(capability, expected_provider_sha256): + observations = new_scope() + try: + guard(observations) + return validate(capability, expected_provider_sha256, observations) + finally: + observations[6]() + def sealed_load(capability, extension_path, expected_extension_sha256): + # Native creation/exec/activation can expose audit callbacks. Retain the + # original independent guards and scopes on each side of those calls. + guard() + return load(capability, extension_path, expected_extension_sha256) + def sealed_diagnostics(capability): + guard() + return diagnostic(capability) + return (sealed_identity, sealed_validate, sealed_load, sealed_diagnostics) + + +def _entry(): + args = sys.argv[1:] + _need(len(args) >= 11 and args[0] == '--root-sha256' and args[2] == '--provider' and + args[5] == '--driver' and args[8] == '--integration' and args[10] == '--', + 'Bootstrap launch argument schema differs') + initialize(args[1]) + provider_path, provider_sha = args[3], args[4] + driver_path, driver_sha, integration = args[6], args[7], args[9] + _need(type(integration) is str and integration.startswith('/') and + provider_path.rsplit('/', 1)[0] == integration and + driver_path.rsplit('/', 1)[0] == integration, + 'Bootstrap integration/source directory differs') + capability = admit_provider(provider_path, provider_sha) + api = capture_api() + preflight(capability) # reject unsupported profile before any driver/build work + _check_root() + digest, _, driver_source = _hash_regular(driver_path, _MAX_SOURCE, True) + _need(digest == driver_sha, 'Bootstrap scientific driver source differs') + _need(tuple(sys.path) == _INITIAL_PATH, 'Bootstrap initial search path changed before stage installation') + sys.path.insert(0, integration) + driver = ModuleType('__main__') + driver_namespace = driver.__dict__ + driver_namespace.update({'__file__': driver_path, '__builtins__': builtins.__dict__, + 'bootstrap_root': _ROOT_MODULE, + 'bootstrap_capability': capability, 'bootstrap_api': api}) + code = _COMPILE(driver_source, driver_path, 'exec', dont_inherit=True, optimize=_OPTIMIZE) + _check_root() + sys.argv = [driver_path] + args[11:] + sys.modules['__main__'] = driver + _EXEC(code, driver_namespace) + + +# This first capture is valid only under the parent's explicit fresh-process, +# authenticated-source/native-dependency and clean-launch provenance boundary. +_need(sys.executable == '/usr/bin/python3.12' and + sys.flags.no_site == 1 and sys.flags.no_user_site == 1 and + sys.flags.safe_path == 1 and sys.flags.dont_write_bytecode == 1 and + sys.flags.ignore_environment == 0 and sys.flags.isolated == 0 and + sys.flags.hash_randomization == 0 and sys.flags.optimize in (0, 1) and + tuple(sys.path) == _INITIAL_PATH and posix.environ == _ENVIRONMENT, + 'Bootstrap requires the exact reviewed clean seeded parent launch') +_need(_GETTRACE() is None and _GETPROFILE() is None, 'Bootstrap callback root is not pristine') +_need(_ROOT_MODULE.__dict__ is _ROOT_NAMESPACE, 'Bootstrap root module namespace differs') +sys.modules[_ROOT_NAME] = _ROOT_MODULE +_ROOT_CELL.append(_environment_guard(_ROOT_NAMESPACE, (BootstrapCapability, _NativeSpec))) +_ROOT_CELL.append(_scope_factory_gate(_NEW_SCOPE)) +if __name__ == '__main__': + _entry() diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/h25_parent_supervisor.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/h25_parent_supervisor.py.txt new file mode 100644 index 0000000000..73ed60fe21 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/h25_parent_supervisor.py.txt @@ -0,0 +1,475 @@ +"""Parent-only bounded process supervision; imports no candidate implementation. + +The runtime caller must establish the trusted clean launcher before calling us. +This source was prepared without loading ctypes or running any control. The +closed single-threaded child domain is an explicit premise, not a hostile-fork +sandbox. Numeric process IDs are never used as signal destinations. +""" +import fcntl +import hashlib +import json +import os +from pathlib import Path +import resource +import signal +import stat +import subprocess +import sys +import time + +FLAGS = ('-S', '-s', '-P', '-B') +ENV = {'PATH': '/usr/bin:/bin', 'PYTHONHASHSEED': '0', 'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', 'TZ': 'UTC', 'PYTHONDONTWRITEBYTECODE': '1'} +RUNNER_SHA = 'bd882e3dadb1b6aeaa63ee824f1a1c58f8ef2546b6840a2bffa46885a184d3eb' +QUEUE_SHA = '1348a7b4d7cc1f9fef556f5e0abdaf04411a998afdcd574d7812c76ab37dcf68' +TCB_SHA = '610492b3fc06baa0560175edc3ba27057de00d00b8fd3d58dbe55e5a371c042a' +LIBC = '/usr/lib/x86_64-linux-gnu/libc.so.6' +NATIVE_PINS = { + LIBC: '3a15d66867d83762c7f2f1e37359cb8f6c5743edb369c65285cb0b1c4f7498bf', + '/usr/lib/python3.12/lib-dynload/_ctypes.cpython-312-x86_64-linux-gnu.so': 'aad3e24f186e6c0a1c7efa8f16004f951f527db86f6451d30118657384a456c1', + '/usr/lib/x86_64-linux-gnu/libffi.so.8.1.4': '00f593fe192f2851b8ce23b25cec2488d769beb5a8f63e8c9e563071e1075153', + '/usr/lib/python3.12/ctypes/__init__.py': '0782592567ad71097198a3afe985ac3e2ea0b9b5e75452402c9460c89a86318a', + '/usr/lib/python3.12/ctypes/_endian.py': 'c5d692bdce10dfee242752620061bab684633bc72445a3def484961ef1bdbf3a', +} +CHUNK = 65536 +LOG_CAP = 2 * 1024 * 1024 +META_CAP = 256 * 1024 +CLEANUP_SECONDS = 2.0 + + +def need(condition, message): + if not condition: + raise RuntimeError(message) + + +def launch_contract(): + need(sys.executable == '/usr/bin/python3.12', 'Pinned interpreter required') + need(sys.flags.no_site == sys.flags.no_user_site == sys.flags.dont_write_bytecode == 1 and + sys.flags.safe_path and sys.flags.ignore_environment == sys.flags.isolated == + sys.flags.hash_randomization == 0, 'Trusted no-site safe-path fixed-seed flags required') + need(dict(os.environ) == ENV, 'Exact clean environment required') + need(tuple(sys.path) == ('/usr/lib/python312.zip', '/usr/lib/python3.12', + '/usr/lib/python3.12/lib-dynload'), 'Initial system stdlib path changed') + need(list(Path('/proc/self/task').iterdir()) == [Path('/proc/self/task') / str(os.getpid())], + 'Exactly one parent task required') + + +def identity(info): + return (info.st_dev, info.st_ino, info.st_mode, info.st_size, info.st_mtime_ns, info.st_ctime_ns) + + +def stable_file(path, limit, keep=False): + """Complete bounded snapshot; no file read can extend a growing snapshot.""" + path = Path(path) + before = path.stat(follow_symlinks=False) + need(stat.S_ISREG(before.st_mode) and before.st_size <= limit, 'File type/size bound: ' + str(path)) + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + h, count, blocks = hashlib.sha256(), 0, [] + try: + opened = os.fstat(fd) + need(identity(before) == identity(opened), 'File changed while opening') + while count < opened.st_size: + block = os.read(fd, min(CHUNK, opened.st_size - count)) + need(bool(block), 'Short retained-file read') + count += len(block) + h.update(block) + if keep: + blocks.append(block) + after_fd = os.fstat(fd) + finally: + os.close(fd) + after = path.stat(follow_symlinks=False) + need(identity(before) == identity(after_fd) == identity(after), 'File drift during retained snapshot') + row = {'path': str(path), 'sha256': h.hexdigest(), 'bytes': count, + 'identity': list(identity(after)), 'stable': True, 'read_chunk_bytes': CHUNK} + return (row, b''.join(blocks)) if keep else row + + +def read_json(path, limit=META_CAP): + row, raw = stable_file(path, limit, True) + return json.loads(raw), row + + +def write_new(path, row): + raw = json.dumps(row, sort_keys=True, indent=2).encode('ascii') + b'\n' + need(len(raw) <= META_CAP, 'Bounded metadata record exceeded') + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600) + try: + view = memoryview(raw) + while view: + written = os.write(fd, view) + need(written > 0, 'Metadata write made no progress') + view = view[written:] + os.fsync(fd) + finally: + os.close(fd) + + +def proc(pid): + try: + with open('/proc/' + str(pid) + '/stat', 'rb') as stream: + raw = stream.read(8193) + need(len(raw) <= 8192, 'Unexpected process-stat size') + end = raw.rfind(b') ') + need(end >= 0, 'Malformed process stat') + fields = raw[end + 2:].split() + return {'pid': int(pid), 'ppid': int(fields[1]), 'pgid': int(fields[2]), + 'sid': int(fields[3]), 'start_ticks': int(fields[19]), + 'state': fields[0].decode('ascii'), + 'rss_bytes': int(fields[21]) * os.sysconf('SC_PAGE_SIZE')} + except (FileNotFoundError, ProcessLookupError, PermissionError): + return None + + +def census(): + found = {} + with os.scandir('/proc') as entries: + for entry in entries: + if entry.name.isdecimal(): + row = proc(int(entry.name)) + if row is not None: + found[row['pid']] = row + return found + + +def generation(row): + return row['pid'], row['start_ticks'] + + +def children_now(): + return [row for row in census().values() if row['ppid'] == os.getpid()] + + +def install_subreaper(root): + """Called only by the future parent, before any controlled root exists.""" + launch_contract() + need(not children_now(), 'Parent must own no preexisting child processes') + tcb, tcb_row = read_json(root / 'control/NATIVE-INITIAL-TCB-v1.json') + need(tcb_row['sha256'] == TCB_SHA, 'Accepted initial TCB changed') + need(any(row['path'] == LIBC and row['sha256'] == NATIVE_PINS[LIBC] + for row in tcb['files']), 'Pinned libc absent from accepted TCB') + evidence = {path: stable_file(path, 16 * 1024 * 1024) for path in NATIVE_PINS} + need(all(evidence[path]['sha256'] == expected for path, expected in NATIVE_PINS.items()), + 'Subreaper native/stdlib source supplement changed') + # This import and native call have NOT been performed during source authoring. + need(Path('/usr/lib/x86_64-linux-gnu/libffi.so.8').resolve() == + Path('/usr/lib/x86_64-linux-gnu/libffi.so.8.1.4'), 'Foreign libffi SONAME resolution') + import ctypes + need(sys.modules['_ctypes'].__file__ == + '/usr/lib/python3.12/lib-dynload/_ctypes.cpython-312-x86_64-linux-gnu.so', 'Foreign _ctypes owner') + need(ctypes.__file__ == '/usr/lib/python3.12/ctypes/__init__.py', 'Foreign ctypes owner') + library = ctypes.CDLL(LIBC, use_errno=True) + call = library.prctl + call.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong] + call.restype = ctypes.c_int + prior, actual = ctypes.c_int(), ctypes.c_int() + need(call(37, ctypes.addressof(prior), 0, 0, 0) == 0, 'PR_GET_CHILD_SUBREAPER failed') + need(call(36, 1, 0, 0, 0) == 0, 'PR_SET_CHILD_SUBREAPER failed') + need(call(37, ctypes.addressof(actual), 0, 0, 0) == 0 and actual.value == 1, + 'Same-process subreaper readback failed') + for path, expected in NATIVE_PINS.items(): + need(stable_file(path, 16 * 1024 * 1024)['sha256'] == expected, 'TCB bytes changed across load') + # Retain the CDLL and typed function in the owning parent for its whole queue. + return {'pid': os.getpid(), 'prior': prior.value, 'actual': actual.value, + 'tcb_sha256': TCB_SHA, 'native_source_evidence': evidence, + 'trust': 'Trusted OS/loader/initial system stdlib; file pins do not authenticate native memory'}, (library, call) + + +def ledger(root, allow_unclosed=False): + result = {} + runs = root / 'runtime/runs' + for folder in sorted(runs.iterdir()): + need(folder.is_dir() and not folder.is_symlink(), 'Unexpected round run entry') + if allow_unclosed and not (folder / 'receipt.json').exists(): + continue + receipt, _ = read_json(folder / 'receipt.json', 4 * 1024 * 1024) + amount = receipt.get('runner_wall_seconds', receipt.get('wall_seconds')) + need(type(amount) in (int, float) and amount >= 0, 'Invalid ledger amount') + result[folder.name] = float(amount) + return result + + +def budget(root): + phase, _ = read_json(root / 'control/EXECUTION-PHASE.json') + cap = phase['aggregate_cap_seconds'] + need(type(cap) is int and cap in (600, 2400), 'Unrecognized budget phase') + current = ledger(root) + need(sum(current.values()) < cap, 'Round budget consumed') + return cap, current + + +def parent_lock(root): + lock = (root / 'runtime/parent-queue.lock').open('a') + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BaseException: + lock.close() + raise + return lock + + +class ExecutionDeadline(RuntimeError): + pass + + +def deadline_handler(signum, frame): + raise ExecutionDeadline('Outer execution deadline reached, including Popen/preexec') + + +class OwnedDomain: + """Only our new children and their observed descendants enter this domain.""" + def __init__(self): + need(not children_now(), 'Owned child domain was not initially empty') + self.rows, self.fds, self.groups, self.reaped = {}, {}, set(), [] + self.root = None + self.parent_group = os.getpgrp() + self.parent_session = os.getsid(0) + + def add(self, row): + key = generation(row) + if key in self.rows: + if row['pgid'] != self.parent_group: + self.groups.add((row['pgid'], row['sid'])) + return + need(len(self.rows) < 128, 'Owned process observation limit exceeded') + need(row['pid'] != os.getpid(), 'Parent cannot enter its own child domain') + try: + fd = os.pidfd_open(row['pid'], 0) + except ProcessLookupError: + return + current = proc(row['pid']) + if current is None or generation(current) != key: + os.close(fd) + return + self.rows[key], self.fds[key] = dict(current), fd + # During interrupted Popen a child can briefly precede setsid. Its + # individual pidfd is owned; the queue parent group never is. + if current['pgid'] != self.parent_group: + self.groups.add((current['pgid'], current['sid'])) + + def observe(self): + all_rows = census() + known = {pid for pid, start in self.rows if pid in all_rows and + all_rows[pid]['start_ticks'] == start} + for pid in known: + self.add(all_rows[pid]) + changed = True + while changed: + changed = False + for pid, row in all_rows.items(): + if pid not in known and (row['ppid'] == os.getpid() or row['ppid'] in known): + self.add(row) + if generation(row) in self.rows: + known.add(pid) + changed = True + return all_rows, [all_rows[pid] for pid in known] + + def kill_owned(self): + self.observe() + for key, fd in self.fds.items(): + current = proc(key[0]) + if current is not None and generation(current) == key and current['state'] != 'Z': + try: + signal.pidfd_send_signal(fd, signal.SIGKILL, None, 0) + except ProcessLookupError: + pass + + def cleanup(self, process): + start = time.monotonic() + seen_after_root = [] + completed = False + while True: + _, current = self.observe() + if process is not None and process.returncode is not None: + seen_after_root.extend(generation(row) for row in current if row['pid'] != process.pid) + self.kill_owned() + if process is not None: + process.poll() + for key in list(self.rows): + row = proc(key[0]) + if row is None or generation(row) != key or row['ppid'] != os.getpid(): + continue + if process is not None and row['pid'] == process.pid: + continue + try: + pid, status = os.waitpid(row['pid'], os.WNOHANG) + except ChildProcessError: + continue + if pid: + self.reaped.append({'pid': pid, 'start_ticks': key[1], 'wait_status': status}) + all_rows, current = self.observe() + occupied = [row for row in all_rows.values() if (row['pgid'], row['sid']) in self.groups] + if not current and not occupied and not children_now(): + completed = True + break + if time.monotonic() - start >= CLEANUP_SECONDS: + break + time.sleep(0.01) + final_rows = census() + remaining = [row for row in final_rows.values() if + generation(row) in self.rows or (row['pgid'], row['sid']) in self.groups or + row['ppid'] == os.getpid()] + for fd in self.fds.values(): + os.close(fd) + self.fds.clear() + return {'complete': completed and not remaining, + 'owned_generations': list(self.rows.values()), + 'groups': [{'pgid': g, 'sid': s} for g, s in sorted(self.groups)], + 'reaped_adopted': self.reaped, + 'observed_after_root_exit': [list(key) for key in sorted(set(seen_after_root))], + 'remaining': remaining, 'cleanup_seconds': time.monotonic() - start, + 'cleanup_tail_limit_seconds': CLEANUP_SECONDS, + 'group_empty_proved': completed and not remaining, + 'signal_method': 'SIGKILL via generation-checked pidfd only; never killpg'} + + +def reconcile_missing_receipt(root, label, began, cause, cleanup): + folder = root / 'runtime/runs' / label + folder.mkdir(exist_ok=True) + if not cleanup['complete'] and not (folder / 'receipt.json').exists(): + # A surviving root must never race a replacement canonical receipt. + # Leave its attempt unclosed, blocking the unchanged runner, and add a + # distinct charged STOP record for the parent to reconcile manually. + folder = root / 'runtime/runs' / (label + '-outer-unclosed-stop') + folder.mkdir() + path = folder / 'receipt.json' + if path.exists(): + return None + start = {} + if (folder / 'START.json').exists(): + start, _ = read_json(folder / 'START.json') + row = dict(start, schema='h25-outer-reconciled-stop-v1', status='STOP', label=label, + kind='outer_reconciled_incomplete_root', termination=cause, attempt_label=label, + wall_seconds=time.monotonic() - began, original_root_receipt_absent=True, + original_root_completion_claimed=False, cleanup_complete=cleanup['complete'], + all_prior_files_preserved=True) + row['label'] = folder.name + row['runner_wall_seconds'] = row['wall_seconds'] + if not (folder / 'START.json').exists(): + write_new(folder / 'START.json', {'kind': row['kind'], 'label': label}) + write_new(path, row) + return row + + +def run_root(root, case, evidence, seconds, shared_deadline, as_bytes=201326592, + rss_bytes=201326592): + """One root. Cleanup and stable custody finish before returning to a queue.""" + launch_contract() + need(stable_file(root / 'run_guarded_v3.py', META_CAP)['sha256'] == RUNNER_SHA, + 'Actual root runner changed') + need(time.monotonic() + CLEANUP_SECONDS < shared_deadline, 'No reserved cleanup tail remains') + command = ['/usr/bin/python3.12', *FLAGS, str(root / 'run_guarded_v3.py'), + case['stage'], case['job'], case['label']] + for value in (case['stage'], case['job'], case['label']): + need(type(value) is str and value and all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in value), + 'Unsafe case identity') + evidence.mkdir() + need(type(seconds) in (int, float) and 0 < seconds <= 190, 'Unadmitted root deadline') + need(type(as_bytes) is int and 0 < as_bytes <= 1024 ** 3, 'Unadmitted root address-space bound') + need(type(rss_bytes) is int and 0 < rss_bytes <= 1024 ** 3, 'Unadmitted aggregate RSS bound') + began = time.monotonic() + deadline = min(began + seconds, shared_deadline - CLEANUP_SECONDS) + domain = OwnedDomain() + process, failure, cleanup = None, None, None + peak, spawn_entered, captured = 0, False, None + setter, limit_kind, limits = resource.setrlimit, resource.RLIMIT_AS, (as_bytes, as_bytes) + need(list(Path('/proc/self/task').iterdir()) == [Path('/proc/self/task') / str(os.getpid())], + 'Root preexec requires exactly one task') + def child_limit(): + setter(limit_kind, limits) + old_handler = signal.getsignal(signal.SIGALRM) + need(signal.getitimer(signal.ITIMER_REAL) == (0.0, 0.0), 'Parent already has an execution alarm') + write_new(evidence / 'LAUNCH.json', {'command': command, 'parent_pid': os.getpid(), + 'parent_pgid': os.getpgrp(), 'parent_sid': os.getsid(0), + 'root_execution_seconds': seconds, 'address_space_bytes': as_bytes, + 'rss_sum_bytes': rss_bytes, 'new_session': True, 'cleanup_reserved_seconds': CLEANUP_SECONDS}) + try: + with (evidence / 'root.stdout.raw').open('xb') as out, (evidence / 'root.stderr.raw').open('xb') as err: + signal.signal(signal.SIGALRM, deadline_handler) + signal.setitimer(signal.ITIMER_REAL, max(0.000001, deadline - time.monotonic())) + try: + spawn_entered = True + process = subprocess.Popen(command, cwd=root, env=dict(ENV), stdout=out, + stderr=err, start_new_session=True, preexec_fn=child_limit) + # Popen leaves an exited root waitable; capture its generation BEFORE poll. + captured = proc(process.pid) + need(captured is not None and captured['pgid'] == captured['sid'] == process.pid, + 'New root process/session identity missing') + domain.root = generation(captured) + domain.add(captured) + write_new(evidence / 'ROOT-PROCESS.json', captured) + while True: + _, current = domain.observe() + peak = max(peak, sum(row['rss_bytes'] for row in current)) + need(peak <= rss_bytes, 'Owned process RSS sum exceeded') + need(max((evidence / name).stat().st_size for name in + ('root.stdout.raw', 'root.stderr.raw')) <= LOG_CAP, 'Outer raw log cap exceeded') + if process.poll() is not None: + break + time.sleep(0.01) + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, old_handler) + except BaseException as error: + failure = {'type': type(error).__name__, 'message': str(error)[:2048]} + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, old_handler) + # This is also required when Popen raised before returning an object. + try: + cleanup = domain.cleanup(process) + except BaseException as cleanup_error: + cleanup = {'complete': False, 'group_empty_proved': False, + 'owned_generations': list(domain.rows.values()), + 'groups': [{'pgid': g, 'sid': sid} for g, sid in sorted(domain.groups)], + 'reaped_adopted': domain.reaped, 'observed_after_root_exit': [], + 'remaining': 'UNKNOWN_AFTER_CLEANUP_ERROR', + 'error': {'type': type(cleanup_error).__name__, 'message': str(cleanup_error)[:2048]}} + for fd in domain.fds.values(): + os.close(fd) + domain.fds.clear() + if not cleanup['complete']: + failure = failure or {'type': 'CleanupIncomplete', 'message': 'Owned descendants/group remain after bounded cleanup tail'} + if time.monotonic() > shared_deadline: + failure = failure or {'type': 'SharedDeadline', 'message': 'Shared cap crossed; necessary cleanup charged'} + reconciled = reconcile_missing_receipt(root, case['label'], began, + failure or {'type': 'MissingRootReceipt', 'message': 'Root exited without receipt'}, cleanup) + if reconciled is not None: + failure = failure or {'type': 'MissingRootReceipt', 'message': 'New reconciled STOP receipt; no retry'} + logs = {} + for name in ('root.stdout.raw', 'root.stderr.raw'): + try: + logs[name] = stable_file(evidence / name, LOG_CAP) + except BaseException as error: + failure = failure or {'type': type(error).__name__, 'message': str(error)[:2048]} + logs[name] = {'path': str(evidence / name), 'complete_hash': None, 'stable': False} + result = {'schema': 'h25-parent-root-supervision-v1', 'label': case['label'], + 'status': 'STOP' if failure else 'ROOT_COMPLETED_AND_OWNED_DOMAIN_EMPTY', + 'failure': failure, 'spawn_entered': spawn_entered, + 'spawn_returned': process is not None, 'captured_root': captured, + 'returncode': None if process is None else process.returncode, + 'cleanup': cleanup, 'outer_logs': logs, 'sampled_owned_rss_bytes': peak, + 'execution_and_cleanup_seconds': time.monotonic() - began, + 'root_receipt_reconciled': reconciled is not None, + 'no_hostile_fork_or_concurrent_children_claim': True} + write_new(evidence / 'SUPERVISION.json', result) + return result + + +def stop_supplement(root, label, reason): + folder = root / 'runtime/runs' / (label + '-supervision-stop') + folder.mkdir() + row = {'status': 'STOP', 'label': folder.name, 'kind': 'supervision_failure_marker', + 'failure': reason, 'wall_seconds': 0.0, 'runner_wall_seconds': 0.0, + 'cost_accounted_by_enclosing_queue_overhead': True, 'original_receipts_preserved': True} + write_new(folder / 'START.json', {'kind': row['kind']}) + write_new(folder / 'receipt.json', row) + + +def packet_unchanged(directory, manifest): + for name, expected in manifest['files'].items(): + row = stable_file(directory / name, META_CAP) + need(row['sha256'] == expected['sha256'] and row['bytes'] == expected['bytes'], + 'Parent source packet changed: ' + name) + need(not (directory / name).stat().st_mode & 0o222, 'Parent source packet became writable') + return True diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/native_tcb_controls_v1.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/native_tcb_controls_v1.py.txt new file mode 100644 index 0000000000..91fb71164c --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/native_tcb_controls_v1.py.txt @@ -0,0 +1,97 @@ +"""Source-only planned controls; execute before later driver imports/builds. + +The isolated reader drift case writes only its exclusively created temporary +file. No system native library or live process mapping is mutated. +""" + + +def _need(condition, message): + if not condition: + raise RuntimeError(message) + + +def _reject(operation, expected_fragment): + try: + operation() + except RuntimeError as error: + message = str(error) + _need(expected_fragment in message, 'TCB control rejected for an unexpected reason: ' + message) + return message + raise RuntimeError('TCB negative control did not reject') + + +def run_controls(helper, bootstrap_root, bootstrap_api, expected_files, expected_hashlib_origin, temporary_directory): + bootstrap_api[0]() + records = [] + receipt = helper.verify_native_tcb(bootstrap_root, bootstrap_api, expected_files, expected_hashlib_origin) + _need(receipt['status'] == 'MATCHED_DECLARED_INITIAL_NATIVE_FILES' and + receipt['declared_file_count'] == len(expected_files) and + receipt['probe_private_abi_access'] is False, 'TCB positive receipt differs') + records.append({'case': 'TCB-positive-initial-native-closure', 'receipt': receipt}) + path, digest, size = expected_files[0] + wrong_digest = ('0' if digest[0] != '0' else '1') + digest[1:] + wrong = ((path, wrong_digest, size),) + expected_files[1:] + records.append({'case': 'TCB-wrong-file-digest', 'rejection': _reject( + lambda: helper.verify_native_tcb(bootstrap_root, bootstrap_api, wrong, expected_hashlib_origin), + 'file digest differs')}) + remove_index = next(index for index, row in enumerate(expected_files) if row[0] != expected_hashlib_origin) + missing = expected_files[:remove_index] + expected_files[remove_index + 1:] + records.append({'case': 'TCB-missing-declared-map', 'rejection': _reject( + lambda: helper.verify_native_tcb(bootstrap_root, bootstrap_api, missing, expected_hashlib_origin), + 'mapped file closure differs')}) + original_hash = bootstrap_root._SHA256 + def forbidden(*args, **kwargs): + raise RuntimeError('Corrupt hash alias must never execute') + bootstrap_root._SHA256 = forbidden + try: + rejection = _reject(lambda: helper.verify_native_tcb( + bootstrap_root, bootstrap_api, expected_files, expected_hashlib_origin), + 'Bootstrap/provider global changed') + finally: + bootstrap_root._SHA256 = original_hash + records.append({'case': 'TCB-root-hash-alias', 'rejection': rejection, + 'corrupt_function_executed': False}) + + bootstrap_api[0]() + ops = helper._native_ops(bootstrap_root, bootstrap_api) + posix = bootstrap_root.posix + _need(type(temporary_directory) is str and temporary_directory.startswith('/'), + 'TCB temporary control directory must be absolute') + temporary_path = temporary_directory.rstrip('/') + '/native-tcb-reader-drift.bin' + flags = posix.O_CREAT | posix.O_EXCL | posix.O_WRONLY | posix.O_CLOEXEC | posix.O_NOFOLLOW + initial = b'initial native TCB reader evidence\n' * 32 + descriptor = posix.open(temporary_path, flags, 0o600) + try: + offset = 0 + while offset < len(initial): + written = posix.write(descriptor, initial[offset:]) + _need(written > 0, 'TCB temporary fixture write made no progress') + offset += written + finally: + posix.close(descriptor) + expected_digest = ops['sha256'](initial).hexdigest() + state = {'changed': False} + original_read = ops['read'] + def read_and_truncate(descriptor, count): + data = original_read(descriptor, count) + if data and not state['changed']: + state['changed'] = True + writer = posix.open(temporary_path, posix.O_WRONLY | posix.O_TRUNC | posix.O_CLOEXEC | posix.O_NOFOLLOW) + try: + _need(posix.write(writer, b'x') == 1, 'TCB drift fixture write differs') + finally: + posix.close(writer) + return data + instrumented = dict(ops) + instrumented['read'] = read_and_truncate + try: + rejection = _reject(lambda: helper._hash_file( + instrumented, temporary_path, expected_digest, len(initial)), 'file changed during hashing') + _need(state['changed'], 'TCB reader drift instrumentation did not fire') + finally: + posix.unlink(temporary_path) + records.append({'case': 'TCB-isolated-reader-file-drift', 'rejection': rejection, + 'instrumentation_scope': 'Internal reader only, exclusively created temporary file; public TCB admission never accepts injected ops.', + 'system_native_files_mutated': False}) + return {'schema': 'h25-native-tcb-controls-v1', 'records': records, 'expected_records': 5, + 'scientific_calls': 0, 'probe_native_imports': 0} diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/native_tcb_v1.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/native_tcb_v1.py.txt new file mode 100644 index 0000000000..55a2f3320b --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/native_tcb_v1.py.txt @@ -0,0 +1,202 @@ +"""Initial native TCB corroboration, before other driver imports or native builds. + +No imports. The parent authenticates this source and the expected native closure +before launch, then calls after its captured sealed root guard. Native hashing, +POSIX, OS/loader integrity and the closed bootstrap interval are explicit trust +premises, not established by this check. The existing217file probe audit remains +separate. This receipt is never a scientific verdict or reusable private-ABI PASS. +""" +_MAX_FILES = 32 +_MAX_FILE_BYTES = 67108864 +_MAX_TOTAL_FILE_BYTES = 268435456 +_MAX_MAP_BYTES = 524288 +_MAX_MAP_LINES = 4096 +_MAX_LINE_BYTES = 8192 +_MAX_EXEC_MAPS = 256 +_CHUNK = 1048576 + + +def _need(condition, message): + if not condition: + raise RuntimeError(message) + + +def _native_ops(root, api): + _need(type(api) is tuple and len(api) == 4, 'Native TCB requires sealed bootstrap API') + root_sha = api[0]() + namespace = root.__dict__ + posix = namespace['posix'] + native_hash_module = namespace['_hashlib'] + function = namespace['_SHA256'] + builtin_type = namespace['BuiltinFunctionType'] + module_type = namespace['ModuleType'] + _need(type(posix) is module_type and type(native_hash_module) is module_type, + 'Native TCB module type differs') + _need(type(function) is builtin_type and function.__self__ is native_hash_module and + function.__name__ == 'openssl_sha256' and + native_hash_module.__dict__.get('openssl_sha256') is function, + 'Native TCB hash function owner differs') + functions = {} + for alias, name in (('open', 'open'), ('read', 'read'), ('fstat', 'fstat'), + ('close', 'close'), ('major', 'major'), ('minor', 'minor'), ('getpid', 'getpid')): + value = posix.__dict__.get(name) + _need(type(value) is builtin_type and value.__self__ is posix and value.__name__ == name, + 'Native TCB POSIX primitive owner differs: ' + name) + functions[alias] = value + _need(functions['open'] is namespace['_OPEN'] and functions['read'] is namespace['_READ'] and + functions['fstat'] is namespace['_FSTAT'] and functions['close'] is namespace['_CLOSE'], + 'Native TCB primitive differs from pristine root') + functions.update({'sha256': function, 'flags': namespace['_FLAGS'], 'posix': posix, + 'hash_module': native_hash_module, 'root_sha256': root_sha}) + return functions + + +def _expected_inventory(expected_files, expected_hashlib_origin): + _need(type(expected_files) is tuple and 1 <= len(expected_files) <= _MAX_FILES, + 'Native TCB expected file inventory type/count differs') + _need(type(expected_hashlib_origin) is str, 'Native TCB expected hashlib origin type differs') + inventory = {} + total = 0 + for row in expected_files: + _need(type(row) is tuple and len(row) == 3, 'Native TCB expected row shape differs') + path, digest, size = row + _need(type(path) is str and path.startswith('/') and len(path) <= 4096 and + all(32 < ord(character) < 127 for character in path) and + path not in inventory and not path.endswith(' (deleted)'), + 'Native TCB expected canonical path differs') + _need(type(digest) is str and len(digest) == 64 and + all(character in '0123456789abcdef' for character in digest), + 'Native TCB expected digest differs') + _need(type(size) is int and 0 < size <= _MAX_FILE_BYTES, + 'Native TCB expected size differs') + total += size + _need(total <= _MAX_TOTAL_FILE_BYTES, 'Native TCB expected total bytes exceed bound') + inventory[path] = (digest, size) + _need(expected_hashlib_origin in inventory, 'Native TCB hashlib origin is undeclared') + return inventory, total + + +def _read_maps(ops): + descriptor = ops['open']('/proc/self/maps', ops['flags']) + try: + info = ops['fstat'](descriptor) + _need((info.st_mode & 0o170000) == 0o100000, 'Native TCB maps pseudo-file type differs') + parts, count = [], 0 + while True: + block = ops['read'](descriptor, min(65536, _MAX_MAP_BYTES + 1 - count)) + if not block: + break + count += len(block) + _need(count <= _MAX_MAP_BYTES, 'Native TCB maps byte bound exceeded') + parts.append(block) + raw = b''.join(parts) + finally: + ops['close'](descriptor) + lines = raw.splitlines() + _need(len(lines) <= _MAX_MAP_LINES, 'Native TCB maps line bound exceeded') + executable = [] + for line in lines: + _need(len(line) <= _MAX_LINE_BYTES, 'Native TCB maps line byte bound exceeded') + fields = line.split(None, 5) + _need(len(fields) >= 5, 'Native TCB maps row shape differs') + address, permissions, offset, device, inode_text = fields[:5] + _need(len(permissions) == 4, 'Native TCB map permissions shape differs') + if permissions[2:3] != b'x': + continue + inode = int(inode_text, 10) + if inode == 0: + continue # anonymous/kernel executable mappings belong to explicit OS TCB + _need(len(fields) == 6 and fields[5].startswith(b'/') and + not fields[5].endswith(b' (deleted)'), 'Native TCB executable map path differs') + path = fields[5].decode('ascii') + span, pair = address.split(b'-'), device.split(b':') + _need(len(span) == 2 and len(pair) == 2, 'Native TCB map address/device shape differs') + start, end = int(span[0], 16), int(span[1], 16) + _need(0 <= start < end < (1 << 64), 'Native TCB map address bounds differ') + row = (path, int(pair[0], 16), int(pair[1], 16), inode, + start, end, int(offset, 16), permissions.decode('ascii')) + executable.append(row) + _need(len(executable) <= _MAX_EXEC_MAPS, 'Native TCB executable map count exceeded') + _need(executable, 'Native TCB no file-backed executable mappings observed') + return tuple(sorted(executable)), len(raw), ops['sha256'](raw).hexdigest() + + +def _fingerprint(info): + return (info.st_dev, info.st_ino, info.st_mode, info.st_size, info.st_mtime_ns, info.st_ctime_ns) + + +def _hash_file(ops, path, expected_digest, expected_size): + """Production uses only freshly captured native ops; controls may separately + instrument this internal reader on an exclusively created temporary file.""" + descriptor = ops['open'](path, ops['flags']) + try: + before = ops['fstat'](descriptor) + _need((before.st_mode & 0o170000) == 0o100000 and before.st_size == expected_size, + 'Native TCB regular-file type/size differs: ' + path) + digest, count = ops['sha256'](), 0 + while True: + block = ops['read'](descriptor, min(_CHUNK, expected_size + 1 - count)) + if not block: + break + count += len(block) + _need(count <= expected_size, 'Native TCB file grew during hashing: ' + path) + digest.update(block) + after = ops['fstat'](descriptor) + _need(_fingerprint(before) == _fingerprint(after) and count == expected_size, + 'Native TCB file changed during hashing: ' + path) + actual = digest.hexdigest() + _need(actual == expected_digest, 'Native TCB file digest differs: ' + path) + return {'path': path, 'expected_sha256': expected_digest, 'observed_sha256': actual, + 'expected_bytes': expected_size, 'observed_bytes': count, + 'device': after.st_dev, 'device_major': ops['major'](after.st_dev), + 'device_minor': ops['minor'](after.st_dev), 'inode': after.st_ino, + 'mode': after.st_mode, 'mtime_ns': after.st_mtime_ns, 'ctime_ns': after.st_ctime_ns} + finally: + ops['close'](descriptor) + + +def verify_native_tcb(bootstrap_root, bootstrap_api, expected_files, expected_hashlib_origin): + """Corroborate the parent's declared initial native file closure, freshly.""" + ops = _native_ops(bootstrap_root, bootstrap_api) + inventory, expected_total = _expected_inventory(expected_files, expected_hashlib_origin) + native_hash_module = ops['hash_module'] + origin = native_hash_module.__dict__.get('__file__') + _need(type(origin) is str and origin == expected_hashlib_origin, + 'Native TCB actual hashlib origin differs') + mappings_before, maps_before_bytes, maps_before_sha = _read_maps(ops) + mapped_paths = {row[0] for row in mappings_before} + _need(mapped_paths == set(inventory), 'Native TCB declared/executable mapped file closure differs') + files = [] + for path, expected_digest, expected_size in expected_files: + observed = _hash_file(ops, path, expected_digest, expected_size) + current = tuple(row for row in mappings_before if row[0] == path) + _need(current and all(row[1] == observed['device_major'] and + row[2] == observed['device_minor'] and row[3] == observed['inode'] + for row in current), 'Native TCB mapped/current file identity differs: ' + path) + observed['executable_mapping_count'] = len(current) + observed['executable_mappings'] = [ + {'start': hex(row[4]), 'end': hex(row[5]), 'offset': row[6], 'permissions': row[7]} + for row in current] + files.append(observed) + mappings_after, maps_after_bytes, maps_after_sha = _read_maps(ops) + _need(mappings_after == mappings_before, 'Native TCB executable mappings changed during audit') + final_ops = _native_ops(bootstrap_root, bootstrap_api) + _need(final_ops['hash_module'] is native_hash_module and final_ops['sha256'] is ops['sha256'] and + native_hash_module.__dict__.get('__file__') == origin and + final_ops['root_sha256'] == ops['root_sha256'], 'Native TCB root/hash provenance changed') + for name in ('open', 'read', 'fstat', 'close', 'major', 'minor', 'getpid'): + _need(final_ops[name] is ops[name], 'Native TCB captured primitive drifted: ' + name) + return {'schema': 'h25-initial-native-tcb-v1', 'status': 'MATCHED_DECLARED_INITIAL_NATIVE_FILES', + 'root_source_sha256': ops['root_sha256'], 'pid': ops['getpid'](), + 'hashlib_origin': origin, 'hashlib_module_id': id(native_hash_module), + 'hash_function_id': id(ops['sha256']), 'hash_function_name': 'openssl_sha256', + 'hash_function_owned_by_root_module': True, 'files': files, + 'declared_file_count': len(files), 'expected_total_file_bytes': expected_total, + 'observed_total_file_bytes': sum(row['observed_bytes'] for row in files), + 'executable_mapping_count': len(mappings_before), + 'maps_before_bytes': maps_before_bytes, 'maps_after_bytes': maps_after_bytes, + 'maps_before_sha256': maps_before_sha, 'maps_after_sha256': maps_after_sha, + 'executable_mappings_stable': True, 'probe_private_abi_access': False, + 'scientific_admission': False, 'reusable_pass': False, + 'trust_boundary': 'Parent-authenticated fresh startup and declared native/OS/loader primitives; corroboration does not self-prove hostile-OS or compromised-hash integrity.', + 'kernel_anonymous_executable_maps': 'Excluded from declared native file closure; remain in explicit OS trust boundary.'} diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/parent_closure_v1.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/parent_closure_v1.py.txt new file mode 100644 index 0000000000..ca541e94ca --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/parent_closure_v1.py.txt @@ -0,0 +1,270 @@ +"""Finite concrete receiver admission inside the original trusted parent. + +This verifies pinned source, bytecode derived from those bytes without executing +them, concrete local import edges, and the current captured object graph. It is +not a new Python sandbox or proof of the initial OS/interpreter/native memory. +The original parent must load these exact modules through its admitted bootstrap +before adverse input. No user supplied arbitrary checker is accepted. +""" +import ast +import builtins +import __future__ +import copy +import dataclasses +import fcntl +import gc +import hashlib +import json +import marshal +import math +import os +import pathlib +import posix +import resource +import signal +import struct +import subprocess +import sys +import time +import types +import epoch_schema_v5 as schema +import epoch_copy_v5 as copying + +_TYPE, _LEN, _COMPILE = type, len, compile +_MODULE_DICT = types.ModuleType.__dict__['__dict__'].__get__ +_FUNCTION_GETTERS = tuple(types.FunctionType.__dict__[name].__get__ for name in + ('__code__', '__globals__', '__builtins__', '__defaults__', '__kwdefaults__', '__closure__', '__dict__')) +_CELL_GET = types.CellType.__dict__['cell_contents'].__get__ +_CLASS_DICT = type.__dict__['__dict__'].__get__ +_STATIC_FUNCTION = staticmethod.__dict__['__func__'].__get__ +_CLASS_FUNCTION = classmethod.__dict__['__func__'].__get__ +_SOURCE_RECEIVERS = [] +_STDLIB_MODULES = {name: module for name, module in tuple(sys.modules.items()) + if _TYPE(name) is str and _TYPE(module) is types.ModuleType} +MAX_MODULES = 48 +MAX_GLOBALS = 512 + +# These exact registries are intentionally mutated only by their original +# source. Their object identities are still checked. Private-state sabotage +# by code already running in this trusted parent remains outside the boundary. +_MUTABLE_NAMES = { + 'epoch_parent_v5': ('_RESERVED_EPOCHS', '_PARENT_OWNERS'), + 'epoch_schema_v5': ('_ERROR_OWNERS',), + 'epoch_stop_v5': ('_SINK_REGISTRY',), + 'parent_domain_v1': ('_DOMAINS',), + 'parent_completion_v1': ('_PARENTS', '_PROCESS'), + 'parent_closure_v1': ('_SOURCE_RECEIVERS',), +} +_GATE_SUFFIXES = ('CONFIGURATION', 'SOURCE_REVIEW', 'EXECUTION_APPROVAL', 'FUNDING', + 'STAGE_APPROVAL', 'COMMAND_APPROVAL', 'VALIDATION_EXECUTION') + + +def _namespace(module): + schema.need(_TYPE(module) is types.ModuleType, 'exact original module required') + namespace = _MODULE_DICT(module, types.ModuleType) + schema.need(_TYPE(namespace) is dict and _LEN(namespace) <= MAX_GLOBALS, + 'original module namespace bound differs') + for key in namespace: + schema.text(key, 256) + return namespace + + +def _function_record(function): + schema.need(_TYPE(function) is types.FunctionType, 'exact source function required') + values = tuple(getter(function, types.FunctionType) for getter in _FUNCTION_GETTERS) + closure = values[5] + cells = () if closure is None else tuple((cell, _CELL_GET(cell, types.CellType)) for cell in closure) + schema.need(_LEN(cells) <= 64, 'source function closure bound exceeded') + return function, values, cells + + +def _function_check(record): + function, values, cells = record + schema.need(_TYPE(function) is types.FunctionType, 'source function identity changed') + for getter, expected in zip(_FUNCTION_GETTERS, values): + schema.need(getter(function, types.FunctionType) is expected, + 'source function code/globals/builtins/defaults/closure/dict changed') + for cell, expected in cells: + schema.need(_CELL_GET(cell, types.CellType) is expected, 'source function closure contents changed') + + +def _codes(code, result): + result.setdefault(code.co_qualname, []).append(code) + for child in code.co_consts: + if _TYPE(child) is types.CodeType: + _codes(child, result) + + +def _data(value, depth=0): + """Snapshot literal data only; no foreign repr/hash/eq/iteration protocols.""" + schema.need(depth <= 32, 'literal snapshot depth exceeded') + kind = _TYPE(value) + if value is None or kind in (str, int, bool, bytes, float): + return (kind, value) + if kind in (list, tuple): + schema.need(_LEN(value) <= 65536, 'literal sequence bound exceeded') + return (kind, tuple(_data(item, depth + 1) for item in value)) + if kind is dict: + schema.need(_LEN(value) <= 8192, 'literal mapping bound exceeded') + for key in value: + schema.need(_TYPE(key) in (str, int), 'nonliteral mapping key') + return (kind, tuple((_data(key, depth + 1), _data(item, depth + 1)) + for key, item in value.items())) + if kind in (set, frozenset): + schema.need(_LEN(value) <= 8192 and all(_TYPE(item) in (str, int) for item in value), + 'nonliteral set value') + return (kind, frozenset(value)) + raise schema.EpochStop('not literal data') + + +def _validate_code(function, compiled_codes, namespace): + values = tuple(getter(function, types.FunctionType) for getter in _FUNCTION_GETTERS) + code = values[0] + schema.need(values[1] is namespace and values[2] is builtins.__dict__, + 'source function original namespace/builtins differs') + candidates = compiled_codes.get(code.co_qualname, ()) + encoded = marshal.dumps(code) + schema.need(any(marshal.dumps(expected) == encoded for expected in candidates), + 'receiving function bytecode differs from pinned source') + + +def bind_receivers(modules, source_policy, error_owner): + """Only the source-fixed original parent calls this before child launch. + + source_policy is a separately pinned, prelaunch source inventory, never a + report supplied by a child. The two producer-specific validators have fixed + names; unsupported or absent variant source cannot be substituted by a + callable argument. Every received module must be listed in the policy. + """ + schema.owner_state(error_owner) + schema.need(_TYPE(modules) is dict and 1 <= _LEN(modules) <= MAX_MODULES and + _TYPE(source_policy) is dict, 'finite receiver module map required') + for name in modules: + schema.text(name, 128) + for name in source_policy: + schema.text(name, 128) + schema.need(set(modules) == set(source_policy), 'exact receiver closure differs') + records = [] + for name in sorted(modules): + module = modules[name] + namespace = _namespace(module) + pin = source_policy[name] + schema.blob(pin) + raw = copying.read_verified(pin, schema.FILE_BYTES, error_owner=error_owner) + schema.need(namespace.get('__name__') == name and namespace.get('__file__') == pin['path'], + 'original receiving module origin differs') + tree = ast.parse(raw, filename=pin['path']) + compiled = _COMPILE(raw, pin['path'], 'exec', dont_inherit=True, optimize=sys.flags.optimize) + compiled_codes = {} + _codes(compiled, compiled_codes) + functions, classes, literals, imports = [], [], [], [] + for node in tree.body: + if _TYPE(node) is ast.FunctionDef: + function = namespace[node.name] + _validate_code(function, compiled_codes, namespace) + functions.append(_function_record(function)) + elif _TYPE(node) is ast.ClassDef: + cls = namespace[node.name] + schema.need(_TYPE(cls) is type, 'source class type differs') + class_namespace = _CLASS_DICT(cls, type) + for item in node.body: + if _TYPE(item) is ast.FunctionDef: + method = class_namespace[item.name] + # The currently selected explicit methods have no + # property/classmethod/staticmethod decorators. + schema.need(not item.decorator_list, 'unreviewed decorated receiver method') + # Python implicitly wraps __new__ and two class hooks. + # No arbitrary descriptor protocol is invoked. + if item.name == '__new__' and _TYPE(method) is staticmethod: + method = _STATIC_FUNCTION(method, staticmethod) + elif item.name in ('__init_subclass__', '__class_getitem__') and _TYPE(method) is classmethod: + method = _CLASS_FUNCTION(method, classmethod) + _validate_code(method, compiled_codes, namespace) + functions.append(_function_record(method)) + # Dataclass-generated methods are part of the inherited + # dataclasses/initial-parent trust, not compiled from this + # class body. Their actual original code/environment remains + # captured and checked; they cannot be changed after capture. + for method in class_namespace.values(): + if _TYPE(method) is types.FunctionType and not any(method is r[0] for r in functions): + functions.append(_function_record(method)) + classes.append((cls, tuple(class_namespace.items()))) + elif _TYPE(node) in (ast.Import, ast.ImportFrom): + for alias in node.names: + schema.need(alias.name != '*', 'star receiver import unsupported') + if _TYPE(node) is ast.Import: + source_name = alias.name + local_name = alias.asname or source_name.split('.')[0] + expected = modules.get(source_name, _STDLIB_MODULES.get(source_name)) + else: + source_name = node.module + schema.need(node.level == 0, 'relative receiver import unsupported') + local_name = alias.asname or alias.name + source_module = modules.get(source_name, _STDLIB_MODULES.get(source_name)) + schema.need(source_module is not None, 'receiver import dependency absent') + expected = _namespace(source_module).get(alias.name) + schema.need(expected is not None and namespace.get(local_name) is expected, + 'concrete receiving import identity differs') + imports.append((local_name, expected)) + elif _TYPE(node) is ast.Assign: + if _LEN(node.targets) != 1 or _TYPE(node.targets[0]) is not ast.Name: + continue + key = node.targets[0].id + if key in _MUTABLE_NAMES.get(name, ()) or key.endswith(_GATE_SUFFIXES): + continue + try: + literal = ast.literal_eval(node.value) + except (ValueError, TypeError, SyntaxError): + continue + schema.need(_data(namespace[key]) == _data(literal), 'receiver literal differs from source') + literals.append((key, _data(literal))) + for function in namespace.values(): + if _TYPE(function) is types.FunctionType and not any(function is r[0] for r in functions): + functions.append(_function_record(function)) + records.append((name, module, namespace, pin, tuple(namespace.items()), + tuple(functions), tuple(classes), tuple(literals), tuple(imports))) + capability = object() + packet = (capability, tuple(records), error_owner) + schema.need(_LEN(_SOURCE_RECEIVERS) < 2, 'receiver closure finite parent bound exceeded') + _SOURCE_RECEIVERS.append(packet) + check_receivers(capability) + return capability + + +def _packet(capability): + schema.need(_TYPE(capability) is object, 'exact receiver capability required') + for packet in _SOURCE_RECEIVERS: + if packet[0] is capability: + return packet + raise schema.EpochStop('unknown original receiver closure') + + +def check_receivers(capability): + packet = _packet(capability) + for name, module, namespace, pin, original_items, functions, classes, literals, imports in packet[1]: + schema.need(_namespace(module) is namespace and _LEN(namespace) == _LEN(original_items), + 'receiver namespace identity/census changed') + for key, expected in original_items: + schema.need(namespace.get(key) is expected, 'receiver namespace binding changed') + for record in functions: + _function_check(record) + for cls, items in classes: + current = _CLASS_DICT(cls, type) + schema.need(_LEN(current) == _LEN(items), 'receiver class census changed') + for key, expected in items: + schema.need(current.get(key) is expected, 'receiver class binding changed') + for key, expected in literals: + schema.need(_data(namespace[key]) == expected, 'receiver literal data changed') + copying.verify(pin, error_owner=packet[2]) + return None + + +def receiver(capability, module_name, name): + """Return only a specifically named original from the registered closure.""" + schema.text(module_name, 128) + schema.text(name, 128) + for row in _packet(capability)[1]: + if row[0] == module_name: + schema.need(name in row[2], 'fixed receiving entry missing') + return row[2][name] + raise schema.EpochStop('fixed receiving module missing') diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/parent_completion_v1.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/parent_completion_v1.py.txt new file mode 100644 index 0000000000..3191be7570 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/parent_completion_v1.py.txt @@ -0,0 +1,880 @@ +"""Source-only two-producer completion owner for one future guarded parent. + +No configuration or execution gate is installed. The original trusted parent +must authenticate this source, its exact receiver closure and initial OS/runtime +before importing it. Capabilities are process local. This component never +invokes run_guarded, a queue wrapper, a global ledger writer, or a child report +as authority. The enclosing single orchestrator pays this entire component +once, including all child, validation, retention, failure and final-exit costs. +""" +import fcntl +import os +import resource +import signal +import stat +import subprocess +import sys +import time +import epoch_schema_v5 as schema +import epoch_copy_v5 as copying +import epoch_parent_v5 as epoch +import parent_closure_v1 as closure +import parent_domain_v1 as domain +import group01_evidence_v1 as group01 + +CONFIGURATION = None +SOURCE_REVIEW = None +STAGE_APPROVAL = None +COMMAND_APPROVAL = None +FUNDING = None +EXECUTION_APPROVAL = None + +FLAGS = ('-S', '-s', '-P', '-B') +ENV = {'PATH': '/usr/bin:/bin', 'PYTHONHASHSEED': '0', 'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', 'TZ': 'UTC', 'PYTHONDONTWRITEBYTECODE': '1'} +_TYPE, _LEN = type, len +_OPEN, _CLOSE, _MKDIR, _STAT, _SCANDIR = os.open, os.close, os.mkdir, os.stat, os.scandir +_POPEN = subprocess.Popen +_CLOCK, _SLEEP = time.monotonic, time.sleep +_SETRLIMIT, _GETRLIMIT = resource.setrlimit, resource.getrlimit +_SETTIMER, _GETTIMER = signal.setitimer, signal.getitimer +_SIGNAL, _GETSIGNAL = signal.signal, signal.getsignal +_PARENTS = [] +_PROCESS = [None] +# Shared before the first constructor read, including failures before a parent +# capability can be published. No mode can replace or reset this owner. +_UNKNOWN_OWNER = {'quarantine': [False], 'pending': [False], + 'iterator_uncertain': [False], 'primary': [None], + 'native_errors': [None] * 4} +_EPOCH_ENTRY = epoch._entry_state +_EPOCH_RESERVE = epoch.ParentEpoch.reserve_producer +_EPOCH_ACCEPT = epoch.ParentEpoch.accept_completed_producer +_EPOCH_COMPLETION = epoch.ParentCompletion +_EPOCH_COMMIT = epoch.ParentEpoch.commit_exports +_EPOCH_CLOSE = epoch.ParentEpoch.close +MAX_SOURCE_FILES = 8192 +MAX_STAGE_ENTRIES = 16384 +MAX_RAW_VARIANT_FILES = 64 +VARIANT_MODULE = 'variant_validation_v1' +VARIANT_FUNCTION = 'validate_variant_producer' +MAX_VARIANT_RAW_BYTES = 32 * 1024 * 1024 +# Source-literal inventory copied from the separately pinned concrete interface. +VARIANT_FILES = ('initial-tcb.raw.json', 'initial-controls.raw.json', 'initial-restoration.raw.json', 'root-before.raw.json', 'preflight-before.raw.json', 'custody-before.raw.json', 'pyinit_failure/control.attempt.json', 'pyinit_failure/control.attempt.jsonl', 'pyinit_failure/control.stdout.raw', 'pyinit_failure/control.stderr.raw', 'pyinit_failure/helper-return.raw.json', 'pyinit_failure/build.json', 'pyinit_failure/_h25_dict_probe.cpython-312-x86_64-linux-gnu.so', 'pyinit_failure/elf.raw.json', 'exec_failure/control.attempt.json', 'exec_failure/control.attempt.jsonl', 'exec_failure/control.stdout.raw', 'exec_failure/control.stderr.raw', 'exec_failure/helper-return.raw.json', 'exec_failure/build.json', 'exec_failure/_h25_dict_probe.cpython-312-x86_64-linux-gnu.so', 'exec_failure/elf.raw.json', 'preflight-after.raw.json', 'custody-after.raw.json', 'root-after.raw.json', 'receipt.json') +VARIANT_GROUPS = ('initial-tcb.raw.json', 'initial-controls.raw.json', 'initial-restoration.raw.json', 'root-before.raw.json', 'preflight-before.raw.json', 'custody-before.raw.json', 'pyinit_failure/helper-return.raw.json', 'pyinit_failure/elf.raw.json', 'exec_failure/helper-return.raw.json', 'exec_failure/elf.raw.json', 'preflight-after.raw.json', 'custody-after.raw.json', 'root-after.raw.json') +REQUIRED_MODULES = ( + 'epoch_schema_v5', 'epoch_copy_v5', 'epoch_parent_v5', 'epoch_stop_v5', + 'original_build_provenance_v5', 'h25_parent_supervisor', 'parent_closure_v1', + 'parent_domain_v1', 'parent_completion_v1', 'group01_evidence_v1', + 'group01_original_predicates_v1', 'receipt_contract_v1', 'native_field_controls_v1', + 'transport_controls_v1', 'collector_controls_v1', 'elf_literal_fixture_v1', + 'elf_controls_v1', 'provider_controls_v1', 'run_pure_controls_v1', + 'elf_literal_fixture_v2', 'elf_extended_controls_v2', 'run_pure_controls_v2', + 'restoration_contract_v1', 'loader_model_controls_v1', 'driver_model_body_sources_v3', + 'root_model_body_sources_v3', 'loader_model_controls_v3', 'group_evidence_v5', + 'close_model_controls_v5', 'projection_model_controls_v5', 'run_controls_v5', + 'variant_validation_v1', 'sealed_elf_profile_v2') + + +class ParentDeadline(RuntimeError): + pass + + +def _alarm(signum, frame): + raise ParentDeadline('owned producer deadline including Popen/preexec') + + +def _gate(): + schema.exact(CONFIGURATION, ('plans', 'receiver_policy', 'checker_source')) + schema.exact(CONFIGURATION['plans'], ('normal', 'optimized')) + for pin in tuple(CONFIGURATION['plans'].values()) + (CONFIGURATION['receiver_policy'], CONFIGURATION['checker_source']): + schema.blob(pin, schema.RECORD_BYTES) + for record, key in ((SOURCE_REVIEW, 'review_sha256'), (STAGE_APPROVAL, 'stage_review_sha256'), + (COMMAND_APPROVAL, 'command_review_sha256'), (FUNDING, 'reservation_sha256'), + (EXECUTION_APPROVAL, 'external_launch_policy_sha256')): + schema.exact(record, (key,)) + schema.digest(record[key]) + + +def _state(capability): + schema.need(_TYPE(capability) is object, 'exact parent capability required') + for token, state in _PARENTS: + if token is capability: + return state + raise schema.EpochStop('unregistered parent completion owner') + + +def _receiver_gate_values(receivers): + # Fail before any producer if the concrete downstream parsers are still + # source-only. These stronger parent envelopes are installed by the + # independently authenticated original bootstrap; hashes alone grant none. + specifications = ( + ('original_build_provenance_v5', 'PARSER_CONFIGURATION', + ('leaf_policy_sha256', 'configuration_sha256', 'original_helper_sha256')), + ('original_build_provenance_v5', 'PARSER_EXECUTION_APPROVAL', ('external_launch_policy_sha256',)), + ('original_build_provenance_v5', 'PARSER_FUNDING', ('reservation_sha256',)), + ('variant_validation_v1', 'VALIDATION_CONFIGURATION', ('leaf_policy_sha256', 'configuration_sha256')), + ('variant_validation_v1', 'VALIDATION_SOURCE_REVIEW', ('review_sha256',)), + ('variant_validation_v1', 'VALIDATION_EXECUTION', ('external_launch_policy_sha256',)), + ('variant_validation_v1', 'VALIDATION_FUNDING', ('reservation_sha256',))) + result = {} + for module, name, keys in specifications: + value = closure.receiver(receivers, module, name) + schema.exact(value, keys) + for item in value.values(): + schema.digest(item) + result[module + '.' + name] = schema.plain_copy(value) + schema.need(result['original_build_provenance_v5.PARSER_CONFIGURATION']['original_helper_sha256'] == + 'aa0a315110e031e19291970c9611fe5e0f91465fa20eaec51e81186099563f78', + 'original helper source protocol differs before producer launch') + return result + + +def _guard(state): + _gate() + schema.need(state['phase'] not in ('STOP', 'CLOSED'), 'parent completion owner is terminal') + domain.refresh_unknown_owner(state['unknown_owner']) + schema.need(state['io_quarantine'][0] is False and state['unknown_owner']['pending'][0] is False and + state['unknown_owner']['iterator_uncertain'][0] is False and + state['unknown_owner']['primary'][0] is None, + 'parent I/O ownership requires kernel teardown') + schema.need(os.getpid() == state['pid'], 'parent capability cannot cross exec/process') + schema.need(_POPEN is subprocess.Popen and _OPEN is os.open and _CLOSE is os.close and + _SETRLIMIT is resource.setrlimit and _GETRLIMIT is resource.getrlimit and + _CLOCK is time.monotonic and _SETTIMER is signal.setitimer and + _GETTIMER is signal.getitimer and _SIGNAL is signal.signal and + _GETSIGNAL is signal.getsignal, + 'original parent runtime primitive binding changed') + schema.need(epoch._entry_state is _EPOCH_ENTRY and epoch.ParentEpoch.reserve_producer is _EPOCH_RESERVE and + epoch.ParentEpoch.accept_completed_producer is _EPOCH_ACCEPT and + epoch.ParentCompletion is _EPOCH_COMPLETION and epoch.ParentEpoch.commit_exports is _EPOCH_COMMIT and + epoch.ParentEpoch.close is _EPOCH_CLOSE, 'original epoch receiving entry changed') + closure.check_receivers(state['receivers']) + schema.need(_receiver_gate_values(state['receivers']) == state['receiver_gate_snapshot'], + 'independently installed receiver gates changed') + for key in ('plan', 'receiver_policy', 'checker_source'): + current = CONFIGURATION['plans'][state['plan']['mode']] if key == 'plan' else CONFIGURATION[key] + schema.need(current == state['configuration'][key], 'configured source binding changed') + copying.verify(state['configuration'][key], error_owner=state['errors']) + schema.need(_CLOCK() <= state['shared_deadline'], 'complete parent reservation deadline exceeded') + + +def _stop(state, operation, primary): + # No formatting or instance dispatch on an exception. Capture failure is + # separate, never a reason to replace the already delivered primary. + state['phase'] = 'STOP' + # The shared slot was stored inline at the first delivered local/domain + # failure, before any optional retention helper or cleanup call. + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = primary + elif state['unknown_owner']['primary'][0] is not primary: + if state['fallback'][4] is None: + state['fallback'][4] = primary + primary = state['unknown_owner']['primary'][0] + if state['stop'][0] is None: + state['stop'][0] = primary + state['stop'][1] = operation + try: + domain.refresh_unknown_owner(state['unknown_owner']) + except BaseException as error: + # Failure even to inspect retained ownership cannot permit a writer. + state['io_quarantine'][0] = True + if state['fallback'][5] is None: + state['fallback'][5] = error + try: + schema.retain_primary(state['errors'], primary, operation) + except BaseException as error: + state['fallback'][0] = error + # An uncertain native acquisition prevents further diagnostic I/O. The + # outer guard must retain memory state and observe kernel parent teardown. + if (state['directory_created'] and not state['stop_write_attempted'] and not state['io_quarantine'][0] and + not state['unknown_owner']['pending'][0] and not state['unknown_owner']['iterator_uncertain'][0] and + not (_PROCESS[0] is not None and _PROCESS[0]['acquisition_in_flight'])): + try: + state['stop_write_attempted'] = True + record = {'schema': 'h25-parent-completion-stop-v1', 'operation': operation, + 'epoch_id': state['plan']['epoch_id'], 'mode': state['plan']['mode'], + 'status': 'STOP', 'retry_or_restore_allowed': False, + 'error': schema.error_snapshot(state['errors']), + 'domain_obligations_may_be_incomplete': True, + 'enclosing_guard_must_observe_parent_exit': True} + state['stop_file'] = copying.write_once(state['plan']['session_directory'] + '/STOP.json', + schema.canonical(record), error_owner=state['errors']) + except BaseException as error: + state['fallback'][1] = error + + +def _snapshot_sources(plan, error_owner): + schema.need(_TYPE(plan['source_files']) is list and 1 <= _LEN(plan['source_files']) <= MAX_SOURCE_FILES, + 'complete prelaunch source inventory bound differs') + rows, paths, categories = [], set(), set() + for expected in plan['source_files']: + schema.exact(expected, ('category', 'path', 'sha256', 'bytes', 'mode')) + schema.choice(expected['category'], ('parent', 'root', 'provider', 'driver', 'project', + 'system_headers', 'compiler_link', 'oracle', 'stage')) + schema.path(expected['path']) + schema.digest(expected['sha256']) + schema.integer(expected['bytes'], 1, schema.FILE_BYTES) + schema.integer(expected['mode'], 0, 0o7777) + schema.need(expected['path'] not in paths, 'duplicate prelaunch source path') + paths.add(expected['path']) + categories.add(expected['category']) + actual = copying.inspect(expected['path'], schema.FILE_BYTES, error_owner=error_owner) + schema.need(actual['sha256'] == expected['sha256'] and actual['bytes'] == expected['bytes'] and + actual['identity']['mode'] & 0o7777 == expected['mode'], 'source/profile/closure changed') + rows.append(actual) + schema.need(categories == {'parent', 'root', 'provider', 'driver', 'project', 'system_headers', + 'compiler_link', 'oracle', 'stage'}, 'a mandatory source category is absent') + return rows + + +def _tree(root, state): + """Bounded exact stage census; all actual file contents are separately read.""" + schema.path(root) + pending, files, directories = [('', root)], [], [] + count = 0 + while pending: + schema.need(state['io_quarantine'][0] is False and state['unknown_owner']['pending'][0] is False and + state['unknown_owner']['iterator_uncertain'][0] is False, + 'stage census cannot acquire after uncertain ownership') + relative, current = pending.pop() + before = _STAT(current, follow_symlinks=False) + schema.need(stat.S_ISDIR(before.st_mode) and not before.st_mode & 0o222, + 'immutable stage directory kind/mode differs') + entries, primary = None, None + state['unknown_owner']['pending'][0] = True + try: + entries = _SCANDIR(current) + state['unknown_owner']['pending'][0] = False + for entry in entries: + count += 1 + schema.need(count <= MAX_STAGE_ENTRIES, 'stage census bound exceeded') + name = entry.name + schema.need(_TYPE(name) is str and name not in ('.', '..') and '/' not in name, + 'stage entry name differs') + child = name if not relative else relative + '/' + name + info = entry.stat(follow_symlinks=False) + if stat.S_ISREG(info.st_mode): + files.append(child) + elif stat.S_ISDIR(info.st_mode): + directories.append(child) + pending.append((child, current + '/' + name)) + else: + raise schema.EpochStop('stage has symlink or special file') + except BaseException as error: + primary = error + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = error + state['io_quarantine'][0] = True + state['unknown_owner']['iterator_uncertain'][0] = True + state['fallback'][2] = error + raise + finally: + if entries is not None: + owned = entries + entries = None + try: + owned.close() + except BaseException as error: + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = error + state['io_quarantine'][0] = True + state['unknown_owner']['iterator_uncertain'][0] = True + state['fallback'][3] = error + if primary is None: + raise + after = _STAT(current, follow_symlinks=False) + schema.need((before.st_dev, before.st_ino, before.st_mode, before.st_mtime_ns, before.st_ctime_ns) == + (after.st_dev, after.st_ino, after.st_mode, after.st_mtime_ns, after.st_ctime_ns), + 'stage directory changed during census') + return sorted(files), sorted(directories) + + +def _stage(plan, error_owner, state): + copying.verify(plan['stage_manifest'], error_owner=error_owner) + raw = copying.read_verified(plan['stage_manifest'], schema.RECORD_BYTES, error_owner=error_owner) + declared = group01.decode(raw) + schema.need(_TYPE(declared.get('files')) is dict and + plan['stage_manifest']['path'] == plan['stage_directory'] + '/STAGE.json', + 'independent stage manifest origin differs') + files, directories = _tree(plan['stage_directory'], state) + schema.need(files == sorted(list(declared['files']) + ['STAGE.json']) and + directories == plan['stage_directories'], 'complete immutable stage census differs') + source_by_path = {row['path']: row for row in plan['source_files']} + for relative, expected in declared['files'].items(): + schema.need(_TYPE(relative) is str and not relative.startswith('/') and + all(part not in ('', '.', '..') for part in relative.split('/')), + 'stage relative path differs') + path = plan['stage_directory'] + '/' + relative + schema.need(path in source_by_path and expected == + {'sha256': source_by_path[path]['sha256'], 'mode': source_by_path[path]['mode']}, + 'stage file absent from independently fixed current source closure') + return {'manifest': plan['stage_manifest'], 'file_count': len(files), 'directories': directories} + + +def _validate_plan(plan): + schema.exact(plan, ('schema', 'epoch_id', 'mode', 'round_root', 'session_directory', + 'session_seconds', 'source_closure_admission_sha256', 'source_files', 'producers')) + schema.need(plan['schema'] == 'h25-parent-completion-plan-v1', 'parent plan schema differs') + schema.label(plan['epoch_id']) + schema.choice(plan['mode'], ('normal', 'optimized')) + schema.path(plan['round_root']) + schema.path(plan['session_directory']) + schema.integer(plan['session_seconds'], 1, 600) + schema.digest(plan['source_closure_admission_sha256']) + schema.exact(plan['producers'], ('group01', 'failure_variants')) + for role in schema.PRODUCERS: + row = plan['producers'][role] + schema.exact(row, ('epoch_plan', 'command', 'cwd', 'output', 'evidence_directory', + 'stage_directory', 'stage_manifest', 'stage_directories', 'launch_binding', 'launch_nonce', + 'root_seconds', 'address_space_bytes', 'rss_bytes', 'evidence_plan', 'launch_artifacts')) + epoch._plan(row['epoch_plan'], role) + schema.launch(row['launch_binding']) + schema.text(row['launch_nonce'], 64) + schema.need(_LEN(row['launch_nonce']) == 64 and + all(c in '0123456789abcdef' for c in row['launch_nonce']), 'one-use launch nonce differs') + for key in ('cwd', 'output', 'evidence_directory', 'stage_directory'): + schema.path(row[key]) + schema.blob(row['stage_manifest'], schema.RECORD_BYTES) + schema.need(row['stage_manifest']['sha256'] == row['epoch_plan']['stage_sha256'] == + row['launch_binding']['stage_sha256'], 'independent producer stage pins differ') + schema.need(row['launch_binding']['root_sha256'] == row['epoch_plan']['root_sha256'], + 'independent producer root pins differ') + schema.integer(row['root_seconds'], 1, 180) + schema.integer(row['address_space_bytes'], 1, 1024 ** 3) + schema.integer(row['rss_bytes'], 1, 1024 ** 3) + command = row['command'] + schema.need(_TYPE(command) is list and 6 <= _LEN(command) <= 128, 'bounded original root argv required') + for argument in command: + schema.text(argument, 8192) + schema.need(bool(argument), 'empty root argument') + prefix = ['/usr/bin/python3.12', *FLAGS] + (['-O'] if plan['mode'] == 'optimized' else []) + schema.need(command[:len(prefix)] == prefix, 'original root interpreter/flags/mode differs') + entry = command[len(prefix)] + schema.path(entry) + schema.need(entry.startswith(row['stage_directory'] + '/') and + entry == row['stage_directory'] + '/integration/full_driver.py', + 'source-fixed genuine root entry differs') + schema.need(command.count('--output') == 1 and + command[command.index('--output') + 1] == row['output'], 'independent root output differs') + args = command[len(prefix) + 1:] + schema.need(len(args) >= 11 and args[0] == '--root-sha256' and args[2] == '--provider' and + args[5] == '--driver' and args[8] == '--integration' and args[10] == '--', + 'original bootstrap argv positions differ') + by_path = {item['path']: item for item in plan['source_files']} + integration = row['stage_directory'] + '/integration' + schema.need(args[1] == row['epoch_plan']['root_sha256'] and args[9] == integration and + args[3].rsplit('/', 1)[0] == args[6].rsplit('/', 1)[0] == integration, + 'actual root/provider/driver source origins differ') + for path, digest, category in ((entry, args[1], 'root'), (args[3], args[4], 'provider'), + (args[6], args[7], 'driver')): + schema.need(path in by_path and by_path[path]['sha256'] == digest and + by_path[path]['category'] == category, 'bootstrap hash not in independent source closure') + schema.exact(row['launch_artifacts'], ('configuration_sha256', 'startup_tcb_sha256', 'expected_history_sha256')) + for key, pin in row['launch_artifacts'].items(): + schema.blob(pin, schema.RECORD_BYTES) + schema.need(pin['sha256'] == row['launch_binding'][key] and pin['path'] in by_path and + by_path[pin['path']]['sha256'] == pin['sha256'] and + by_path[pin['path']]['bytes'] == pin['bytes'], 'launch data binding lacks actual source pin') + evidence = row['evidence_plan'] + if role == 'group01': + schema.need(command.count('--finite-only') == 1 and command.count('--lanes') == 1 and + command[command.index('--lanes') + 1] == 'candidate', 'Group01 must use original finite candidate route') + schema.need(evidence['mode'] == plan['mode'] and evidence['generation'] == row['epoch_plan']['generation'] and + evidence['stage_sha256'] == row['epoch_plan']['stage_sha256'] and + evidence['root_sha256'] == args[1] and evidence['driver_sha256'] == args[7], + 'Group01 evidence expectation not bound to actual independent launch') + else: + schema.need(args[11:] == ['--output', row['output'], '--generation', row['epoch_plan']['generation'], + '--launch-nonce', row['launch_nonce']], 'variant exact tail argv differs') + schema.need(args[1] == 'f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0' and + args[3] == integration + '/probe_binding_v3.py' and + args[4] == '9cbb7368f89e71d1e6cc46db5dc77efed3e03ed2a801c98c88fe316e4d9f3ef2' and + args[6] == integration + '/variant_driver_v1.py', 'variant genuine original bootstrap differs') + schema.need(evidence['binding'] == {'mode': plan['mode'], 'generation': row['epoch_plan']['generation'], + 'launch_nonce': row['launch_nonce']} and evidence['output'] == row['output'] and + evidence['stage_root'] == row['stage_directory'] and evidence['raw_file_names'] == list(VARIANT_FILES), + 'variant expectation not bound to actual independent launch') + schema.need(schema.sha(schema.canonical({'argv': command})) == row['epoch_plan']['command_sha256'] == + row['launch_binding']['command_sha256'], 'independent exact root command digest differs') + schema.need(row['evidence_directory'] == plan['session_directory'] + '/' + role and + row['output'] == row['evidence_directory'] + '/producer-output', + 'source-fixed private producer origins differ') + schema.need(plan['producers']['group01']['launch_nonce'] != plan['producers']['failure_variants']['launch_nonce'], + 'producer exec launch nonce reused') + + +def make_parent(original_epoch, original_authority, original_receivers): + _gate() + schema.need(_LEN(_PARENTS) < 2, 'finite two-mode parent owner bound exceeded') + # A second mode shares the same process and therefore the same unknown + # resources. Check before the first configuration read can acquire an FD. + for unused, prior in _PARENTS: + owner = prior['unknown_owner'] + domain.refresh_unknown_owner(owner) + schema.need(prior['phase'] != 'STOP' and owner['primary'][0] is None and + owner['quarantine'][0] is False and owner['pending'][0] is False and + owner['iterator_uncertain'][0] is False, + 'prior parent failure forbids a new mode or configuration read') + schema.need(_PROCESS[0] is None or _PROCESS[0]['acquisition_in_flight'] is False, + 'uncertain process-owned lock acquisition requires kernel teardown') + owner = _UNKNOWN_OWNER + domain.refresh_unknown_owner(owner) + schema.need(owner['primary'][0] is None and owner['quarantine'][0] is False and + owner['pending'][0] is False and owner['iterator_uncertain'][0] is False, + 'earlier constructor failure prohibits configuration reads') + try: + errors = schema.make_error_owner() + native_index = 2 * len(_PARENTS) + owner['native_errors'][native_index] = schema.owner_state(errors) + original_state = _EPOCH_ENTRY(original_epoch, original_authority) + owner['native_errors'][native_index + 1] = schema.owner_state(original_state['_error_owner']) + domain.refresh_unknown_owner(owner) + schema.need(owner['quarantine'][0] is False, 'original V5 owner already requires teardown') + mode = original_state['_mode'] + schema.choice(mode, ('normal', 'optimized')) + schema.need(not any(item[1]['plan']['mode'] == mode for item in _PARENTS), 'mode parent already consumed') + configuration = schema.plain_copy({'plan': CONFIGURATION['plans'][mode], + 'receiver_policy': CONFIGURATION['receiver_policy'], 'checker_source': CONFIGURATION['checker_source']}) + plan = group01.decode(copying.read_verified(configuration['plan'], schema.RECORD_BYTES, error_owner=errors)) + _validate_plan(plan) + policy = group01.decode(copying.read_verified(configuration['receiver_policy'], schema.RECORD_BYTES, error_owner=errors)) + schema.need(set(policy) == set(REQUIRED_MODULES), 'exact fixed parent/producer receiving closure differs') + schema.need(policy['parent_completion_v1'] == configuration['checker_source'], + 'actual completion source differs from configured checker') + receivers = closure.bind_receivers(original_receivers, policy, errors) + receiver_gate_snapshot = _receiver_gate_values(receivers) + schema.need(closure.receiver(receivers, 'epoch_parent_v5', 'ParentEpoch') is epoch.ParentEpoch and + closure.receiver(receivers, 'epoch_schema_v5', 'need') is schema.need and + closure.receiver(receivers, 'epoch_copy_v5', 'inspect') is copying.inspect, + 'parent/checker epoch module identities differ') + source_guard = closure.receiver(receivers, 'h25_parent_supervisor', 'launch_contract') + source_guard() + closure.check_receivers(receivers) + original_state = _EPOCH_ENTRY(original_epoch, original_authority) + schema.need(original_state['_epoch_id'] == plan['epoch_id'] and original_state['_mode'] == plan['mode'] and + original_state['_state'] == 'PRODUCERS_PENDING' and + original_state['_plans'] == {role: row['epoch_plan'] for role, row in plan['producers'].items()} and + epoch.CONFIGURATION['parent_checker_sha256'] == configuration['checker_source']['sha256'], + 'original constructor registry is not this prelaunch epoch/plan/checker') + token = object() + state = {'pid': os.getpid(), 'phase': 'CONSTRUCTING', 'epoch': original_epoch, + 'authority': original_authority, 'errors': errors, 'plan': plan, 'configuration': configuration, + 'receivers': receivers, 'receiver_gate_snapshot': receiver_gate_snapshot, + 'runs': {}, 'next': 0, 'directory_created': False, + 'stop': [None, None], 'fallback': [None] * 8, 'stop_file': None, + 'stop_write_attempted': False, 'io_quarantine': owner['quarantine'], + 'unknown_owner': owner, + 'began': _CLOCK(), 'shared_deadline': _CLOCK() + plan['session_seconds'], + 'subreaper': None, 'native_keeper': None, 'lock_fds': [None, None], + 'lock_attempted': [False, False], 'initial_sources': None} + _PARENTS.append((token, state)) + except BaseException as error: + # Reserve the original error before another call or native cleanup. + # This also covers failures before _PARENTS receives a capability. + if owner['primary'][0] is None: + owner['primary'][0] = error + owner['quarantine'][0] = True + raise + try: + # Exclusive creation is the persistent no-restore marker. It is never + # deleted by this source; a crashed/partial same-plan session cannot run. + _MKDIR(plan['session_directory'], 0o700) + state['directory_created'] = True + if _PROCESS[0] is None: + process_record = {'pid': state['pid'], 'locks': [None, None], 'keeper': None, + 'subreaper': None, 'acquisition_in_flight': False} + _PROCESS[0] = process_record + for index, name in enumerate(('parent-queue.lock', 'science.lock')): + process_record['acquisition_in_flight'] = True + process_record['locks'][index] = _OPEN(plan['round_root'] + '/runtime/' + name, + os.O_RDWR | os.O_CREAT | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600) + process_record['acquisition_in_flight'] = False + fcntl.flock(process_record['locks'][index], fcntl.LOCK_EX | fcntl.LOCK_NB) + installer = closure.receiver(receivers, 'h25_parent_supervisor', 'install_subreaper') + # Original installer has a concrete pinned source/TCB/native closure. + # Its path interface is the original pathlib.Path contract. + from pathlib import Path + subreaper, keeper = installer(Path(plan['round_root'])) + process_record['subreaper'], process_record['keeper'] = subreaper, keeper + process_record = _PROCESS[0] + schema.need(process_record['pid'] == state['pid'] and process_record['keeper'] is not None, + 'original same-process subreaper ownership missing') + state['subreaper'], state['native_keeper'] = process_record['subreaper'], process_record['keeper'] + closure.check_receivers(receivers) + state['initial_sources'] = _snapshot_sources(plan, errors) + copying.verify(configuration['checker_source'], error_owner=errors) + copying.write_once(plan['session_directory'] + '/PARENT-INTENT.json', + schema.canonical({'schema': 'h25-parent-completion-intent-v1', 'epoch_id': plan['epoch_id'], + 'mode': plan['mode'], 'configuration': configuration, 'parent_pid': state['pid'], + 'source_closure_admission_sha256': plan['source_closure_admission_sha256'], + 'retry_or_restore_allowed': False, 'accounting': 'nested non-additive; paid by one outer orchestrator'}), + error_owner=errors) + state['phase'] = 'READY' + _guard(state) + return token + except BaseException as primary: + _stop(state, 'make_parent', primary) + raise + + +def _close_logs(run, primary): + first = None + for index in range(2): + descriptor = run['log_fds'][index] + if descriptor is None or run['log_close_attempted'][index]: + continue + run['log_close_attempted'][index] = True + try: + _CLOSE(descriptor) + run['log_close_confirmed'][index] = True + except BaseException as error: + if run['unknown_owner']['primary'][0] is None: + run['unknown_owner']['primary'][0] = primary if primary is not None else error + run['unknown_owner']['quarantine'][0] = True + run['errors'][index] = error + if first is None: + first = error + if primary is None and first is not None: + raise first + + +def run_producer(owner_capability, producer_role): + state = _state(owner_capability) + try: + _guard(state) + schema.choice(producer_role, schema.PRODUCERS) + schema.need(state['phase'] == 'READY' and state['next'] < 2 and + producer_role == schema.PRODUCERS[state['next']] and producer_role not in state['runs'], + 'producer order, replay or prior completion differs') + except BaseException as primary: + _stop(state, 'run_producer_entry', primary) + raise + row = state['plan']['producers'][producer_role] + # Burn the actual epoch ticket before any later preparation or launch. + try: + ticket = _EPOCH_RESERVE(state['epoch'], state['authority'], producer_role) + run_token = object() + run = {'token': run_token, 'ticket': ticket, 'role': producer_role, 'phase': 'RESERVED', + 'unknown_owner': state['unknown_owner'], + 'plan': row, 'domain': None, 'process': None, 'root': None, 'terminal': None, + 'log_fds': [None, None], 'log_close_attempted': [False, False], + 'log_close_confirmed': [False, False], 'errors': [None] * 8, + 'primary': [None], 'acquisition_in_flight': False, 'spawn_entered': False, + 'spawn_returned': False, 'source_before': None, 'stage_before': None, + 'began': _CLOCK(), 'peak_rss': 0, 'file_limits': tuple(_GETRLIMIT(resource.RLIMIT_FSIZE))} + state['runs'][producer_role] = run + state['phase'] = 'PRODUCER_IN_FLIGHT' + except BaseException as primary: + _stop(state, 'run_producer_reservation', primary) + raise + primary = None + old_handler = None + alarm_installed = False + try: + _guard(state) + _MKDIR(row['evidence_directory'], 0o700) + # output remains absent; the genuine original Root creates it exclusively. + try: + _STAT(row['output'], follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise schema.EpochStop('producer output already exists') + local_plan = dict(state['plan'], **row) + run['source_before'] = _snapshot_sources(state['plan'], state['errors']) + run['stage_before'] = _stage(local_plan, state['errors'], state) + # Reject oversized complete-custody records BEFORE any child launch. + run['source_bytes_before'] = _source_custody_bytes(state, run['source_before'], run['stage_before']) + for pin in row['launch_artifacts'].values(): + copying.verify(pin, schema.RECORD_BYTES, error_owner=state['errors']) + run['domain'] = domain.create_domain(state['unknown_owner']) + launch = {'schema': 'h25-owned-producer-launch-v1', 'epoch_id': state['plan']['epoch_id'], + 'mode': state['plan']['mode'], 'role': producer_role, + 'generation': row['epoch_plan']['generation'], 'launch_nonce': row['launch_nonce'], + 'parent_pid': state['pid'], 'command': row['command'], 'environment': ENV, 'cwd': row['cwd'], + 'launch_binding': row['launch_binding'], 'parent_file_limits': list(run['file_limits']), + 'new_session': True, 'close_fds': True, 'pass_fds': [], + 'root_seconds': row['root_seconds'], 'rss_bytes': row['rss_bytes'], + 'address_space_bytes': row['address_space_bytes']} + run['launch'] = copying.write_once(row['evidence_directory'] + '/LAUNCH.json', + schema.canonical(launch), error_owner=state['errors']) + for index, name in enumerate(('stdout.raw', 'stderr.raw')): + schema.need(state['io_quarantine'][0] is False and state['unknown_owner']['pending'][0] is False and + state['unknown_owner']['iterator_uncertain'][0] is False, + 'raw stream cannot acquire after uncertain ownership') + run['acquisition_in_flight'] = True + state['unknown_owner']['pending'][0] = True + run['log_fds'][index] = _OPEN(row['evidence_directory'] + '/' + name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600) + run['acquisition_in_flight'] = False + state['unknown_owner']['pending'][0] = False + setter, kind, limits = _SETRLIMIT, resource.RLIMIT_AS, (row['address_space_bytes'], row['address_space_bytes']) + def child_limit(): + setter(kind, limits) + schema.need(_GETTIMER(signal.ITIMER_REAL) == (0.0, 0.0), 'existing parent timer cannot be replaced') + old_handler = _GETSIGNAL(signal.SIGALRM) + _SIGNAL(signal.SIGALRM, _alarm) + alarm_installed = True + deadline = min(run['began'] + row['root_seconds'], state['shared_deadline'] - domain.CLEANUP_SECONDS) + schema.need(_CLOCK() < deadline, 'no funded root/cleanup interval remains') + _SETTIMER(signal.ITIMER_REAL, max(0.000001, deadline - _CLOCK())) + run['spawn_entered'] = True + run['process'] = _POPEN(row['command'], cwd=row['cwd'], env=dict(ENV), + stdout=run['log_fds'][0], stderr=run['log_fds'][1], stdin=subprocess.DEVNULL, + close_fds=True, pass_fds=(), start_new_session=True, preexec_fn=child_limit) + run['spawn_returned'] = True + run['root'] = domain.adopt_popen(run['domain'], run['process']) + while True: + unused, current = domain.observe(run['domain']) + run['peak_rss'] = max(run['peak_rss'], sum(item[6] for item in current)) + schema.need(run['peak_rss'] <= row['rss_bytes'], 'owned process RSS sum exceeded') + schema.need(max(_STAT(row['evidence_directory'] + '/' + name, follow_symlinks=False).st_size + for name in ('stdout.raw', 'stderr.raw')) <= schema.LOG_BYTES, 'root output bound exceeded') + if domain.poll_owned(run['domain']) is not None: + break + _SLEEP(0.01) + except BaseException as error: + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = error + primary = state['unknown_owner']['primary'][0] + run['primary'][0] = primary + if primary is not error: + run['errors'][4] = error + if (run['acquisition_in_flight'] or state['unknown_owner']['pending'][0] or + state['unknown_owner']['iterator_uncertain'][0] or _TYPE(error) is MemoryError): + state['io_quarantine'][0] = True + raise primary + finally: + # Preserve the first locally delivered primary through all cleanup. + first_cleanup = None + if alarm_installed: + try: + _SETTIMER(signal.ITIMER_REAL, 0) + _SIGNAL(signal.SIGALRM, old_handler) + except BaseException as error: + run['errors'][2] = error + first_cleanup = error + if run['domain'] is not None: + try: + domain.finish_domain(run['domain']) + except BaseException as error: + run['errors'][3] = error + state['io_quarantine'][0] = True + if first_cleanup is None: + first_cleanup = error + try: + _close_logs(run, primary if primary is not None else first_cleanup) + except BaseException as error: + if first_cleanup is None: + first_cleanup = error + for index in range(2): + if run['log_close_attempted'][index] and not run['log_close_confirmed'][index]: + state['io_quarantine'][0] = True + if primary is not None: + _stop(state, 'run_producer', primary) + elif first_cleanup is not None: + _stop(state, 'run_producer_cleanup', first_cleanup) + raise first_cleanup + try: + schema.need(run['spawn_entered'] is True and run['spawn_returned'] is True and + run['acquisition_in_flight'] is False and all(run['log_close_confirmed']), + 'root spawn or raw stream ownership incomplete') + run['terminal'] = domain.terminal_facts(run['domain']) + schema.need(tuple(_GETRLIMIT(resource.RLIMIT_FSIZE)) == run['file_limits'], 'parent file limit drift') + run['phase'] = 'JOINED' + state['phase'] = 'PRODUCER_JOINED' + _guard(state) + return run_token + except BaseException as primary: + _stop(state, 'postcleanup_terminal', primary) + raise + + +def _source_custody_bytes(state, files, stage): + raw = group01.encode({'schema': 'h25-parent-current-source-custody-v1', 'files': files, + 'stage': stage, 'source_closure_admission_sha256': state['plan']['source_closure_admission_sha256'], + 'historical_compiler_interval_proof_claimed_by_this_record': False}) + schema.need(len(raw) <= schema.RECORD_BYTES, 'complete source custody record exceeds admitted writer bound') + return raw + + +def _variant(state, run, stdout_raw): + """Dedicated concrete typed receiver; source remains external until frozen.""" + expected = group01.decode(group01.encode(run['plan']['evidence_plan'])) + expected['producer_process_id'] = run['root'][0] + expected['parent_file_limits'] = list(run['file_limits']) + files = expected['raw_file_names'] + schema.need(_TYPE(files) is list and files == list(VARIANT_FILES), + 'fixed variant raw file inventory missing') + raw_files, pins, total = {}, [], 0 + for relative in files: + schema.text(relative, 256) + schema.need(not relative.startswith('/') and all(part not in ('', '.', '..') for part in relative.split('/')), + 'variant raw origin differs') + path = run['plan']['output'] + '/' + relative + limit = 8388608 if relative.endswith('.so') else schema.LOG_BYTES if relative.endswith('.raw') else schema.RECORD_BYTES + pin = copying.inspect(path, limit, error_owner=state['errors']) + total += pin['bytes'] + schema.need(total <= MAX_VARIANT_RAW_BYTES, 'variant aggregate byte bound exceeded before allocation') + raw_files[relative] = copying.read_verified(pin, limit, error_owner=state['errors']) + pins.append(pin) + closure.check_receivers(state['receivers']) + validator = closure.receiver(state['receivers'], VARIANT_MODULE, VARIANT_FUNCTION) + result = validator(raw_files, expected) + closure.check_receivers(state['receivers']) + # Exact result schema is fixed with the separately frozen variant source. + # This branch cannot run before that complete source/interface is admitted. + schema.exact(result, ('schema', 'raw_result_relative', 'raw_group_relatives', 'builds', + 'zero_candidate_loads', 'not_runtime_authority')) + schema.need(result['schema'] == 'h25-negative-variant-data-authentication-v1' and + result['zero_candidate_loads'] is True and result['not_runtime_authority'] is True, + 'variant data-validation scope differs') + pin_by_relative = dict(zip(files, pins)) + schema.need(result['raw_result_relative'] == 'receipt.json' and + group01.same_json(group01.decode(stdout_raw), group01.decode(raw_files['receipt.json'])), + 'variant original stdout/final raw result differs') + builds = [] + schema.sequence(result['builds'], 2) + for role, row in zip(schema.ROLES[3:], result['builds']): + schema.exact(row, ('role', 'command_sha256', 'profile', 'files')) + schema.need(row['role'] == role, 'variant build role order differs') + schema.exact(row['files'], ('original_output', 'original_receipt', 'attempt', 'journal', 'stdout', 'stderr')) + build = {'role': role, 'producer_role': 'failure_variants', + 'producer_generation': run['plan']['epoch_plan']['generation'], + 'producer_stage_sha256': run['plan']['epoch_plan']['stage_sha256'], + 'command_sha256': row['command_sha256'], 'profile': row['profile']} + for key, relative in row['files'].items(): + schema.text(relative, 256) + schema.need(relative in pin_by_relative, 'variant validator returned unowned file') + build[key] = pin_by_relative[relative] + schema.build(build) + builds.append(build) + schema.need(result['raw_group_relatives'] == list(VARIANT_GROUPS), 'variant exact raw group census differs') + raw_groups = [] + for relative in result['raw_group_relatives']: + schema.text(relative, 256) + schema.need(relative in pin_by_relative, 'variant validator returned unowned raw group') + raw_groups.append({'file': relative, 'raw': pin_by_relative[relative]}) + return {'raw_result': pin_by_relative['receipt.json'], 'group_rows': raw_groups, + 'builds': builds, 'additional_raw': pins, + 'native_runtime_or_full_union_qualified': False} + + +def accept_producer(owner_capability, completed_run_capability): + state = _state(owner_capability) + try: + _guard(state) + schema.need(_TYPE(completed_run_capability) is object and state['phase'] == 'PRODUCER_JOINED', + 'joined original producer capability required') + matches = [run for run in state['runs'].values() if run['token'] is completed_run_capability] + schema.need(_LEN(matches) == 1 and matches[0]['phase'] == 'JOINED', 'unknown or replayed producer completion') + run = matches[0] + run['phase'] = 'COMPLETION_CONSUMED' + terminal = domain.terminal_facts(run['domain']) + schema.need(terminal == run['terminal'], 'owned terminal facts changed') + row, errors = run['plan'], state['errors'] + stdout = copying.inspect(row['evidence_directory'] + '/stdout.raw', schema.LOG_BYTES, error_owner=errors) + stderr = copying.inspect(row['evidence_directory'] + '/stderr.raw', schema.LOG_BYTES, error_owner=errors) + schema.need(stderr['bytes'] == 0, 'original producer stderr is not empty') + stdout_raw = copying.read_verified(stdout, schema.LOG_BYTES, error_owner=errors) + if run['role'] == 'group01': + actual = group01.authenticate_group01(row['output'], row['evidence_plan'], run['root'][0], + run['file_limits'], state['receivers'], errors, stdout_raw) + else: + actual = _variant(state, run, stdout_raw) + # These facts are parent-derived from current bytes and real owned + # cleanup, never child status flags or an imported ParentCompletion. + source_after = _snapshot_sources(state['plan'], errors) + schema.need(source_after == run['source_before'] == state['initial_sources'], 'complete current source identity changed') + stage_after = _stage(dict(state['plan'], **row), errors, state) + schema.need(stage_after == run['stage_before'], 'late complete stage custody changed') + closure.check_receivers(state['receivers']) + schema.need(domain.terminal_facts(run['domain']) == terminal, 'late parent-domain cleanup changed') + copying.verify(stdout, schema.LOG_BYTES, error_owner=errors) + copying.verify(stderr, schema.LOG_BYTES, error_owner=errors) + for build in actual['builds']: + for key, limit in (('original_output', schema.FILE_BYTES), ('original_receipt', 65536), + ('attempt', 65536), ('journal', schema.JOURNAL_BYTES), ('stdout', schema.LOG_BYTES), ('stderr', schema.LOG_BYTES)): + copying.verify(build[key], limit, error_owner=errors) + for pin in actual['additional_raw']: + copying.verify(pin, schema.FILE_BYTES, error_owner=errors) + copying.verify(actual['raw_result'], schema.RAW_RESULT_BYTES, error_owner=errors) + for pin in row['launch_artifacts'].values(): + copying.verify(pin, schema.RECORD_BYTES, error_owner=errors) + for group in actual['group_rows']: + copying.verify(group['raw'], schema.RECORD_BYTES, error_owner=errors) + if run['role'] == 'group01': + copying.verify(group['validation'], 8192, error_owner=errors) + directory = row['evidence_directory'] + terminal_pin = copying.write_once(directory + '/TERMINAL.json', schema.canonical({ + 'schema': 'h25-owned-producer-terminal-v1', 'launch': run['launch'], + 'generation': row['epoch_plan']['generation'], 'launch_nonce': row['launch_nonce'], + 'actual': terminal, 'stdout': stdout, 'stderr': stderr, + 'root_wall_before_completion_diagnostic_nanoseconds': int((_CLOCK() - run['began']) * 1000000000), + 'diagnostic_is_nested_not_additive': True}), error_owner=errors) + raw_groups = copying.write_once(directory + '/RAW-GROUPS.json', + group01.encode({'schema': 'h25-parent-retained-raw-groups-v1', 'rows': actual['group_rows'], + 'additional_raw': actual['additional_raw'], 'returned_groups_checked_before_mint': True}), error_owner=errors) + source_bytes_after = _source_custody_bytes(state, source_after, stage_after) + schema.need(source_bytes_after == run['source_bytes_before'], 'source custody changed after prelaunch size gate') + source_pin = copying.write_once(directory + '/FINAL-SOURCE-CUSTODY.json', source_bytes_after, error_owner=errors) + _guard(state) + schema.need(_CLOCK() - run['began'] <= row['root_seconds'], 'complete root including validation/custody exceeded bound') + observation = {'schema': 'h25-owned-parent-observation-v1', 'epoch_id': state['plan']['epoch_id'], + 'mode': state['plan']['mode'], 'producer_role': run['role'], 'generation': row['epoch_plan']['generation'], + 'launch_nonce': row['launch_nonce'], 'launch': run['launch'], 'terminal': terminal_pin, + 'raw_result': actual['raw_result'], 'raw_groups': raw_groups, 'final_source_custody': source_pin, + 'root_pid': run['root'][0], 'root_start_ticks': run['root'][4], + 'later_cross_root_aggregate_required_before_export': False, + 'native_full_or_gain_qualification': False} + observed_pin = copying.write_once(directory + '/PARENT-OBSERVATION.json', schema.canonical(observation), error_owner=errors) + record = {key: row['epoch_plan'][key] for key in ('role', 'generation', 'stage_sha256', 'command_sha256', 'root_sha256')} + record.update(terminal=terminal_pin, raw_result=actual['raw_result'], raw_groups=raw_groups, + final_source_custody=source_pin, parent_observation=observed_pin, + completion_checker_sha256=state['configuration']['checker_source']['sha256'], builds=actual['builds']) + schema.producer(record) + # The only mint site is below every actual launch/domain/raw/source + # check. Neither ticket nor completion is ever returned to a caller. + _guard(state) + completion = _EPOCH_COMPLETION(run['ticket'], state['configuration']['checker_source']['sha256'], + observed_pin['sha256'], row['epoch_plan']['generation'], state['plan']['mode'], run['role'], + run['root'][0], run['root'][4], True, True, True, True, True, True) + _EPOCH_ACCEPT(state['epoch'], state['authority'], run['ticket'], completion, record) + _guard(state) + schema.need(_CLOCK() - run['began'] <= row['root_seconds'], + 'complete root plus acceptance tail exceeded bound') + run['phase'], run['record'] = 'ACCEPTED', record + state['next'] += 1 + state['phase'] = 'READY' if state['next'] < 2 else 'PRODUCERS_ACCEPTED' + return schema.plain_copy(record) + except BaseException as primary: + _stop(state, 'accept_producer', primary) + raise + + +def commit_exports(owner_capability): + state = _state(owner_capability) + try: + _guard(state) + schema.need(state['phase'] == 'PRODUCERS_ACCEPTED' and state['next'] == 2 and + all(run['phase'] == 'ACCEPTED' for run in state['runs'].values()), + 'only two genuinely accepted producer records may export') + result = _EPOCH_COMMIT(state['epoch'], state['authority']) + _guard(state) + state['phase'] = 'EXPORTED' + return result + except BaseException as primary: + _stop(state, 'commit_exports', primary) + raise + + +def stop_evidence(owner_capability): + state = _state(owner_capability) + summaries = [{'role': run['role'], 'phase': run['phase'], + 'spawn_entered': run['spawn_entered'], 'spawn_returned': run['spawn_returned'], + 'log_close_attempted': list(run['log_close_attempted']), + 'log_close_confirmed': list(run['log_close_confirmed'])} + for run in state['runs'].values()] + # Never expose the epoch ticket, Popen object, domain capability or private + # run sidecar through diagnostic return values. + return state['stop'], state['errors'], state['fallback'], summaries diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/parent_domain_v1.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/parent_domain_v1.py.txt new file mode 100644 index 0000000000..55f0103208 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/parent_domain_v1.py.txt @@ -0,0 +1,450 @@ +"""Owned Linux child domains for one trusted, single-threaded parent process. + +Source proposal only. No target was imported or run during authoring. The +external launcher must authenticate the OS, interpreter, system modules and +original subreaper installer before importing this module. This is the original +closed child-domain premise, not a sandbox against hostile forking or a hostile +host. Acquisition/unwind ambiguity quarantines the parent; it never authorizes +another launch or a completion. The enclosing guard must observe parent exit. +""" +import os +import signal +import subprocess +import time +import epoch_schema_v5 as schema + +_TYPE, _LEN = type, len +_OPEN, _READ, _CLOSE = os.open, os.read, os.close +_STAT = os.stat +_SCANDIR, _GETPID, _GETPGRP, _GETSID = os.scandir, os.getpid, os.getpgrp, os.getsid +_PIDFD_OPEN, _PIDFD_SIGNAL = os.pidfd_open, signal.pidfd_send_signal +_WAITPID, _CLOCK, _SLEEP = os.waitpid, time.monotonic, time.sleep +_POPEN, _POLL = subprocess.Popen, subprocess.Popen.poll +_PAGE_BYTES = os.sysconf('SC_PAGE_SIZE') +_DOMAINS = [] +MAX_GENERATIONS = 128 +MAX_PROC_ENTRIES = 131072 +MAX_PROC_BYTES = 8192 +CLEANUP_SECONDS = 2.0 + + +def _state(capability): + schema.need(_TYPE(capability) is object, 'exact owned domain capability required') + for token, state in _DOMAINS: + if token is capability: + return state + raise schema.EpochStop('unregistered owned domain') + + +def refresh_unknown_owner(owner): + # These are exact V5 ErrorOwner state references captured by the original + # parent before use. Read only the pinned private shape; no projection, + # callback, native I/O or interpretation of historical release slot9. + for native in owner['native_errors']: + if native is None: + continue + io = native[7] + if (io[0] or io[1] or io[2] or io[4] or io[6] or io[10] or io[11] or + io[5] is not None or native[5][1] or io[7][4] == 1): + owner['quarantine'][0] = True + if io[5] is not None: + owner['iterator_uncertain'][0] = True + + +def _fresh_acquisition(state): + # This shares the original parent's preallocated unknown-resource owner. + # Pending acquisition and delivered census failure are independent of a + # later Python close return. Neither flag is cleared by cleanup. + owner = state['unknown_owner'] + refresh_unknown_owner(owner) + schema.need(state['quarantine'] is False and state['acquisition_in_flight'] is False and + state['io_uncertain'] is False and owner['quarantine'][0] is False and + owner['pending'][0] is False and owner['iterator_uncertain'][0] is False, + 'uncertain ownership prohibits a fresh native acquisition') + + +def _opaque(state, error, slot): + # Preallocated slots retain the actual delivered object, without formatting. + # A secondary never replaces the first primary. Slots are finite and an + # overflow means quarantine, not a successful evidence projection. + state['quarantine'] = True + if state['primary'][0] is None: + state['primary'][0] = error + elif state['secondary'][slot] is None: + state['secondary'][slot] = error + else: + state['overflow'][0] = error + + +def _proc(pid, state): + schema.integer(pid, 1, (1 << 31) - 1) + descriptor = None + primary = None + _fresh_acquisition(state) + # The uncertain acquisition flag is set before the native entry. If open + # raises after an undisclosed descriptor acquisition, parent exit is needed. + try: + try: + _STAT('/proc/' + str(pid) + '/stat', dir_fd=None, follow_symlinks=False) + except (FileNotFoundError, ProcessLookupError): + # Only the pinned metadata-only primitive establishes absence. + # An exception from a later acquisition never proves no FD existed. + return None + state['acquisition_in_flight'] = True + state['unknown_owner']['pending'][0] = True + descriptor = _OPEN('/proc/' + str(pid) + '/stat', + os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW | os.O_NONBLOCK) + state['acquisition_in_flight'] = False + state['unknown_owner']['pending'][0] = False + raw = _READ(descriptor, MAX_PROC_BYTES + 1) + schema.need(_TYPE(raw) is bytes and _LEN(raw) <= MAX_PROC_BYTES, + 'bounded proc stat read differs') + end = raw.rfind(b') ') + schema.need(end >= 0, 'malformed proc stat') + fields = raw[end + 2:].split() + schema.need(_LEN(fields) >= 22 and raw[:raw.find(b' ')] == str(pid).encode('ascii'), + 'proc stat identity or shape differs') + row = (pid, int(fields[1]), int(fields[2]), int(fields[3]), + int(fields[19]), fields[0].decode('ascii'), int(fields[21]) * _PAGE_BYTES) + schema.need(row[4] > 0 and row[6] >= 0, 'proc generation or RSS differs') + return row + except BaseException as error: + primary = error + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = error + state['quarantine'] = True + state['unknown_owner']['quarantine'][0] = True + _opaque(state, error, 0) + raise + finally: + if descriptor is not None: + # Burn before entry; a failed native close is not retried. + owned = descriptor + descriptor = None + try: + _CLOSE(owned) + except BaseException as close_error: + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = close_error + state['quarantine'] = True + state['unknown_owner']['quarantine'][0] = True + state['io_uncertain'] = True + _opaque(state, close_error, 1) + if primary is None: + raise + + +def _census(state): + iterator = None + primary = None + rows = {} + _fresh_acquisition(state) + state['acquisition_in_flight'] = True + state['unknown_owner']['pending'][0] = True + try: + iterator = _SCANDIR('/proc') + state['acquisition_in_flight'] = False + state['unknown_owner']['pending'][0] = False + count = 0 + for entry in iterator: + count += 1 + schema.need(count <= MAX_PROC_ENTRIES, 'proc census entry bound exceeded') + name = entry.name + if name.isdecimal(): + row = _proc(int(name), state) + if row is not None: + rows[row[0]] = row + return rows + except BaseException as error: + primary = error + # All delivered iteration/body failures latch before optional helper + # entry. A no-op/successful close cannot establish release afterward. + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = error + state['quarantine'] = True + state['io_uncertain'] = True + state['unknown_owner']['quarantine'][0] = True + state['unknown_owner']['iterator_uncertain'][0] = True + _opaque(state, error, 2) + raise + finally: + if iterator is not None: + owned = iterator + iterator = None + try: + owned.close() + except BaseException as close_error: + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = close_error + state['quarantine'] = True + state['unknown_owner']['quarantine'][0] = True + state['unknown_owner']['iterator_uncertain'][0] = True + state['io_uncertain'] = True + _opaque(state, close_error, 3) + if primary is None: + raise + + +def create_domain(unknown_owner): + """Called only after the original same-process subreaper was installed.""" + schema.need(_LEN(_DOMAINS) < 4, 'two modes by two producers domain bound exceeded') + schema.exact(unknown_owner, ('quarantine', 'pending', 'iterator_uncertain', 'primary', 'native_errors')) + for key in ('quarantine', 'pending', 'iterator_uncertain', 'primary'): + schema.need(_TYPE(unknown_owner[key]) is list and _LEN(unknown_owner[key]) == 1, + 'original parent unknown-resource slot differs') + schema.need(_TYPE(unknown_owner['native_errors']) is list and _LEN(unknown_owner['native_errors']) == 4, + 'exact two-mode V5 error-owner registry required') + for native in unknown_owner['native_errors']: + schema.need(native is None or (_TYPE(native) is list and _LEN(native) == 9 and + _TYPE(native[7]) is list and _LEN(native[7]) == 13), + 'original captured V5 error-owner shape differs') + refresh_unknown_owner(unknown_owner) + schema.need(all(unknown_owner[key][0] is False for key in + ('quarantine', 'pending', 'iterator_uncertain')) and unknown_owner['primary'][0] is None, + 'unknown-resource parent already requires teardown') + token = object() + state = {'rows': [None] * MAX_GENERATIONS, 'fds': [None] * MAX_GENERATIONS, + 'fd_attempted': [False] * MAX_GENERATIONS, + 'fd_closed': [False] * MAX_GENERATIONS, 'count': 0, + 'groups': set(), 'reaped': [], 'after_root': set(), + 'process': None, 'root': None, 'returncode': None, + 'parent_pid': _GETPID(), 'parent_group': _GETPGRP(), 'parent_session': _GETSID(0), + 'phase': 'CONSTRUCTING', 'quarantine': False, + 'acquisition_in_flight': False, 'io_uncertain': False, 'primary': [None], + 'unknown_owner': unknown_owner, + 'secondary': [None] * 16, 'overflow': [None], + 'final_rows': None, 'closure_confirmed': False} + _DOMAINS.append((token, state)) + try: + rows = _census(state) + schema.need(not any(row[1] == state['parent_pid'] for row in rows.values()), + 'parent has preexisting child processes') + state['phase'] = 'RESERVED' + return token + except BaseException as error: + if unknown_owner['primary'][0] is None: + unknown_owner['primary'][0] = error + unknown_owner['quarantine'][0] = True + state['quarantine'] = True + _opaque(state, error, 4) + state['phase'] = 'STOP' + raise + + +def _add(state, row): + _fresh_acquisition(state) + key = row[0], row[4] + schema.need(row[0] != state['parent_pid'], 'parent cannot enter own child domain') + for index in range(state['count']): + prior = state['rows'][index] + if prior is not None and (prior[0], prior[4]) == key: + if row[2] != state['parent_group']: + state['groups'].add((row[2], row[3])) + return True + index = state['count'] + schema.need(index < MAX_GENERATIONS, 'owned process generation bound exceeded') + # Reserve the slot before native acquisition. No role/generation slot is + # recycled after a failed or disappeared acquisition. + state['count'] = index + 1 + state['rows'][index] = row + state['acquisition_in_flight'] = True + state['unknown_owner']['pending'][0] = True + try: + state['fds'][index] = _PIDFD_OPEN(row[0], 0) + state['acquisition_in_flight'] = False + state['unknown_owner']['pending'][0] = False + current = _proc(row[0], state) + if current is None or (current[0], current[4]) != key: + return False # The actual FD stays owned for one terminal close. + if current[2] != state['parent_group']: + state['groups'].add((current[2], current[3])) + return True + except BaseException as error: + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = error + state['quarantine'] = True + state['unknown_owner']['quarantine'][0] = True + _opaque(state, error, 5) + raise + + +def observe(capability): + state = _state(capability) + all_rows = _census(state) + known = set() + for index in range(state['count']): + prior = state['rows'][index] + current = None if prior is None else all_rows.get(prior[0]) + if current is not None and current[4] == prior[4]: + known.add(current[0]) + _add(state, current) + for unused in range(MAX_GENERATIONS + 1): + changed = False + for pid, row in all_rows.items(): + if pid not in known and (row[1] == state['parent_pid'] or row[1] in known): + if _add(state, row): + known.add(pid) + changed = True + if not changed: + break + else: + raise schema.EpochStop('child-domain closure iteration bound exceeded') + return all_rows, tuple(all_rows[pid] for pid in sorted(known)) + + +def adopt_popen(capability, process): + state = _state(capability) + schema.need(state['phase'] == 'RESERVED' and state['process'] is None and + _TYPE(process) is _POPEN, 'Popen ownership or one-attempt state differs') + state['process'] = process # Exact original return, never a supplied proxy. + row = _proc(process.pid, state) + schema.need(row is not None and row[1] == state['parent_pid'] and + row[2] == row[3] == process.pid, + 'new child PID/session/generation missing before first poll') + state['root'] = row + schema.need(_add(state, row) is True, 'original child pidfd generation not owned') + state['phase'] = 'RUNNING' + return row + + +def poll_owned(capability): + state = _state(capability) + schema.need(state['phase'] == 'RUNNING' and _TYPE(state['process']) is _POPEN, + 'original running Popen required') + result = _POLL(state['process']) + if result is not None: + schema.integer(result, -128, 255) + state['returncode'] = result + return result + + +def _kill(state): + for index in range(state['count']): + fd, prior = state['fds'][index], state['rows'][index] + if fd is None or state['fd_attempted'][index]: + continue + current = _proc(prior[0], state) + if current is not None and current[4] == prior[4] and current[5] != 'Z': + try: + _PIDFD_SIGNAL(fd, signal.SIGKILL, None, 0) + except ProcessLookupError: + pass + + +def finish_domain(capability): + """Always attempted, including Popen exceptions; no caller closure claims.""" + state = _state(capability) + schema.need(state['phase'] in ('RESERVED', 'RUNNING'), 'domain cleanup replay') + state['phase'] = 'CLEANUP_CONSUMED' + started = _CLOCK() + primary = None + try: + _fresh_acquisition(state) + while True: + all_rows, current = observe(capability) + process = state['process'] + if process is not None and process.returncode is not None: + for row in current: + if row[0] != process.pid: + state['after_root'].add((row[0], row[4])) + _kill(state) + if process is not None: + result = _POLL(process) + if result is not None: + state['returncode'] = result + for index in range(state['count']): + prior = state['rows'][index] + row = _proc(prior[0], state) + if (row is None or row[4] != prior[4] or row[1] != state['parent_pid'] or + (process is not None and row[0] == process.pid)): + continue + try: + pid, status = _WAITPID(row[0], os.WNOHANG) + except ChildProcessError: + continue + if pid: + state['reaped'].append((pid, prior[4], status)) + all_rows, current = observe(capability) + remaining = tuple(row for row in all_rows.values() + if row[1] == state['parent_pid'] or (row[2], row[3]) in state['groups'] or + any(prior is not None and (row[0], row[4]) == (prior[0], prior[4]) + for prior in state['rows'][:state['count']])) + state['final_rows'] = remaining + if not current and not remaining: + state['closure_confirmed'] = True + break + if _CLOCK() - started >= CLEANUP_SECONDS: + break + _SLEEP(0.01) + except BaseException as error: + primary = error + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = error + state['quarantine'] = True + state['unknown_owner']['quarantine'][0] = True + _opaque(state, error, 6) + raise + finally: + # Every known FD gets one attempt even if a prior close failed. Native + # return/boxing, Python call-entry and final unwind still have no total + # recovery theorem; any such failure forbids minting and parent reuse. + first_close = None + for index in range(state['count']): + descriptor = state['fds'][index] + if descriptor is None or state['fd_attempted'][index]: + continue + state['fd_attempted'][index] = True + try: + _CLOSE(descriptor) + state['fd_closed'][index] = True + except BaseException as error: + if state['unknown_owner']['primary'][0] is None: + state['unknown_owner']['primary'][0] = error + state['quarantine'] = True + state['unknown_owner']['quarantine'][0] = True + state['io_uncertain'] = True + _opaque(state, error, 7) + if first_close is None: + first_close = error + state['phase'] = 'CLOSED' if primary is None and first_close is None else 'STOP' + if primary is None and first_close is not None: + raise first_close + + +def terminal_facts(capability): + state = _state(capability) + _fresh_acquisition(state) + schema.need(state['phase'] == 'CLOSED' and state['quarantine'] is False and + state['acquisition_in_flight'] is False and state['io_uncertain'] is False and state['root'] is not None and + state['returncode'] == 0 and state['closure_confirmed'] is True and + state['final_rows'] == () and not state['after_root'] and not state['reaped'] and + all(fd is None or (state['fd_attempted'][index] and state['fd_closed'][index]) + for index, fd in enumerate(state['fds'])), + 'owned terminal domain is incomplete, failed, orphaned or quarantined') + # Fresh census after FD cleanup. This is independent of receipt booleans. + rows = _census(state) + schema.need(not any(row[1] == state['parent_pid'] or + (row[2], row[3]) in state['groups'] for row in rows.values()), + 'postcleanup owned child/group still present') + return {'root': list(state['root']), 'returncode': state['returncode'], + 'owned_generations': [list(row) for row in state['rows'][:state['count']]], + 'groups': [list(pair) for pair in sorted(state['groups'])], + 'remaining': [], 'adopted_reaps': [], 'observed_after_root_exit': [], + 'pidfd_close_attempted': list(state['fd_attempted'][:state['count']]), + 'pidfd_close_confirmed': list(state['fd_closed'][:state['count']]), + 'source': 'original in-process Popen and owned generation registry', + 'hostile_fork_or_privileged_host_resistance_claimed': False} + + +def stop_slots(capability): + state = _state(capability) + return state['primary'], state['secondary'], state['overflow'], { + 'phase': state['phase'], 'quarantine': state['quarantine'], + 'acquisition_in_flight': state['acquisition_in_flight'], + 'io_uncertain': state['io_uncertain'], + 'shared_pending': state['unknown_owner']['pending'][0], + 'shared_iterator_uncertain': state['unknown_owner']['iterator_uncertain'][0], + 'shared_quarantine': state['unknown_owner']['quarantine'][0], + 'closure_confirmed': state['closure_confirmed'], + 'pidfd_close_attempted': list(state['fd_attempted'][:state['count']]), + 'pidfd_close_confirmed': list(state['fd_closed'][:state['count']])} diff --git a/research/h25-c05-finite-cover-source-audit/snapshot/sealed_elf_profile_v2.py.txt b/research/h25-c05-finite-cover-source-audit/snapshot/sealed_elf_profile_v2.py.txt new file mode 100644 index 0000000000..67967f85b0 --- /dev/null +++ b/research/h25-c05-finite-cover-source-audit/snapshot/sealed_elf_profile_v2.py.txt @@ -0,0 +1,1388 @@ +"""Source-only bounded ELF/profile predicates; no file, loader, or process APIs. + +This module is NOT an authentication boundary. The original Root authenticates +this source, its builtin/stdlib environment, input bytes, launch policy and native +helper provenance before calling it. Its exact-builtin inputs/outputs stay private +in the no-callback bootstrap interval. A successful static parse is not permission +to load. See INTERFACE-v2.md for the separately required runtime admission stages. +""" +from hashlib import sha256 as _sha256 +from struct import unpack_from as _unpack_from + +ABI = "h25-elf-profile-v2" +INITIALIZER = "PyInit__h25_field_service_v1" +ORIGINAL_INITIALIZER = "PyInit__h25_dict_probe" +PRODUCTION_DATA_LINKS = ( + ("probe_module", 64, "probe_methods"), + ("probe_module", 72, "probe_slots"), + ("h25_field_module", 64, "h25_field_methods"), + ("h25_field_module", 72, "h25_field_slots"), + ("h25_field_context_type", 232, "h25_field_context_methods"), +) +MAX_FILE = 8 * 1024 * 1024 +MAX_MEMORY = 64 * 1024 * 1024 +MAX_PH = 64 +MAX_SH = 256 +MAX_DYNAMIC = 1024 +MAX_SYMBOLS = 4096 +MAX_RELOCATIONS = 16384 +MAX_IMPORTS = 512 +MAX_MAPS = 256 +MAX_SEGMENTS = 64 +MAX_STRING = 4096 +PAGE = 4096 +U64 = (1 << 64) - 1 + + +class ELFAdmissionError(ValueError): + """Closed-profile rejection; messages never format untrusted objects.""" + + +def _need(condition, reason): + if not condition: + raise ELFAdmissionError(reason) + + +def _int(value, maximum=U64): + _need(type(value) is int and 0 <= value <= maximum, "integer type/range") + return value + + +def _text(value, maximum=MAX_STRING, empty=False): + _need(type(value) is str and len(value) <= maximum, "string type/size") + _need((empty or len(value) > 0) and all(32 <= ord(c) < 127 for c in value), + "string alphabet") + return value + + +def _digest(value): + _need(type(value) is str and len(value) == 64 and + all(c in "0123456789abcdef" for c in value), "digest type/value") + return value + + +def _tuple(value, maximum, minimum=0): + _need(type(value) is tuple and minimum <= len(value) <= maximum, "tuple type/size") + return value + + +def _record(value, keys): + _need(type(value) is dict, "record type") + _need(all(type(k) is str for k in value), "record key type") + _need(set(value) == set(keys), "record key set") + return value + + +def _plain(value): + """Bound the whole graph BEFORE comparing or indexing external structures.""" + count = [0, 0] + def visit(v, depth): + count[0] += 1 + _need(depth <= 16 and count[0] <= 200000, "record nesting/count") + t = type(v) + if t is dict: + _need(len(v) <= 4096 and all(type(k) is str for k in v), "plain dictionary") + for k, x in v.items(): + visit(k, depth + 1) + visit(x, depth + 1) + elif t is tuple: + _need(len(v) <= MAX_RELOCATIONS, "plain tuple count") + for x in v: + visit(x, depth + 1) + elif t is str or t is bytes: + _need(len(v) <= MAX_FILE, "plain byte/string size") + count[1] += len(v) + _need(count[1] <= 64 * 1024 * 1024, "plain aggregate bytes") + elif t is int: + _need(-U64 <= v <= U64, "plain integer range") + else: + _need(v is None or t is bool, "non-builtin input") + visit(value, 0) + + +def _fingerprint(value): + """Canonical, bounded exact-data hash; no repr, pickle, or user hooks.""" + _plain(value) + h = _sha256() + def put(v): + t = type(v) + if t is dict: + h.update(b"d" + str(len(v)).encode("ascii") + b":") + for k in sorted(v): + put(k) + put(v[k]) + elif t is tuple: + h.update(b"t" + str(len(v)).encode("ascii") + b":") + for x in v: + put(x) + elif t is bytes or t is str: + b = v if t is bytes else v.encode("utf-8") + h.update((b"b" if t is bytes else b"s") + str(len(b)).encode("ascii") + b":" + b) + elif t is int: + h.update(b"i" + str(v).encode("ascii") + b";") + else: + h.update(b"n" if v is None else b"y" if v else b"z") + put(value) + return h.hexdigest() + + +def _end(start, size, limit=U64): + _int(start) + _int(size) + _need(start <= limit and size <= limit - start, "range overflow/out of bounds") + return start + size + + +def _overlap(a, b): + return a[0] < b[1] and b[0] < a[1] + + +def _disjoint(ranges, reason): + ordered = sorted(ranges) + for a, b in zip(ordered, ordered[1:]): + _need(a[1] <= b[0], reason) + + +def _elf_hash(name): + h = 0 + for c in name.encode("ascii"): + h = (h << 4) + c + g = h & 0xF0000000 + if g: + h ^= g >> 24 + h &= ~g + return h & 0xFFFFFFFF + + +def _gnu_hash(name): + h = 5381 + for c in name.encode("ascii"): + h = ((h << 5) + h + c) & 0xFFFFFFFF + return h + + +def _static_policy(policy): + _plain(policy) + _record(policy, ("schema", "source_closure_sha256", "compiler_closure_sha256", + "link_profile_sha256", "build_receipt_sha256", "expected_exports", + "needed", "required_local_functions", "required_local_objects", + "method_tables", "pointer_slots", "page_profile")) + _need(policy["schema"] == "h25-static-elf-policy-v2", "static policy schema") + _record(policy["page_profile"], ("schema", "page_size")) + _need(policy["page_profile"]["schema"] == "h25-amd64-page-profile-v1" and + type(policy["page_profile"]["page_size"]) is int and + policy["page_profile"]["page_size"] == PAGE, "unsupported admitted page profile") + for k in ("source_closure_sha256", "compiler_closure_sha256", "link_profile_sha256", + "build_receipt_sha256"): + _digest(policy[k]) + for k in ("expected_exports", "needed", "required_local_functions", "required_local_objects"): + values = _tuple(policy[k], 512) + for v in values: + _text(v, 256) + _need(len(set(values)) == len(values), "duplicate static policy name") + _need(INITIALIZER in policy["expected_exports"], "initializer absent from policy") + _need(len(policy["required_local_functions"]) > 0, "no source helper facts") + _tuple(policy["method_tables"], 32, 1) + for n in policy["needed"]: + _need("/" not in n and "$" not in n and ":" not in n, "needed name profile") + _tuple(policy["method_tables"], 32, 1) + table_names = set() + for table in policy["method_tables"]: + _record(table, ("symbol", "entries")) + n = _text(table["symbol"], 256) + _need(n not in table_names, "duplicate method table") + table_names.add(n) + _need(n in policy["required_local_objects"], "method table missing object fact") + for entry in _tuple(table["entries"], 128, 1): + _tuple(entry, 4, 4) + _text(entry[0], 256) + _text(entry[1], 256) + _int(entry[2], 0xFFFF) + _need(entry[1] in policy["required_local_functions"], "method target missing function fact") + if entry[3] is not None: + _text(entry[3], MAX_STRING, empty=True) + _need(len({e[0] for e in table["entries"]}) == len(table["entries"]), "duplicate method name") + _tuple(policy["pointer_slots"], 512) + for slot in policy["pointer_slots"]: + _tuple(slot, 3, 3) + _text(slot[0], 256) + _int(slot[1], MAX_MEMORY) + _text(slot[2], 256) + _need(slot[0] in policy["required_local_objects"] and + slot[2] in policy["required_local_functions"] + policy["required_local_objects"], + "pointer slot missing local facts") + _need(len(set(policy["pointer_slots"])) == len(policy["pointer_slots"]), "duplicate pointer slot") + if ORIGINAL_INITIALIZER in policy["expected_exports"]: + _need(set(policy["expected_exports"]) == {INITIALIZER, ORIGINAL_INITIALIZER}, "production initializer export set") + _need(set(PRODUCTION_DATA_LINKS).issubset(set(policy["pointer_slots"])), + "missing production module/type data linkage") + return policy + + +class _ELF: + def __init__(self, raw, policy): + _need(type(raw) is bytes and 64 <= len(raw) <= MAX_FILE, "ELF byte type/size") + self.raw = raw + self.policy = _static_policy(policy) + self.page_size = self.policy["page_profile"]["page_size"] + self.loads = [] + self.sections = [] + self.protected = [] + self.dynamic = {} + self.needed = [] + self.relocations = [] + self.by_destination = {} + + def read(self, offset, size): + return self.raw[offset:_end(offset, size, len(self.raw))] + + def unpack(self, fmt, offset, size): + self.read(offset, size) + return _unpack_from(fmt, self.raw, offset) + + def cstring(self, section, offset, empty=False): + _need(0 <= offset < section["size"], "string offset") + start = section["offset"] + offset + limit = min(section["offset"] + section["size"], start + MAX_STRING + 1) + end = self.raw.find(b"\0", start, limit) + _need(end >= start, "unterminated/oversized string") + b = self.raw[start:end] + _need((empty or b) and all(32 <= c < 127 for c in b), "ELF string alphabet") + return b.decode("ascii") + + def load_at(self, address, size, file_backed=False, executable=None, writable=None): + end = _end(address, size) + matches = [] + for p in self.loads: + stop = p["vaddr"] + (p["filesz"] if file_backed else p["memsz"]) + if p["vaddr"] <= address and end <= stop: + if executable is not None and bool(p["flags"] & 1) != executable: + continue + if writable is not None and bool(p["flags"] & 2) != writable: + continue + matches.append(p) + _need(len(matches) == 1 and size > 0, "ambiguous/unmapped address range") + return matches[0] + + def file_at(self, address, size): + p = self.load_at(address, size, file_backed=True) + return p["offset"] + address - p["vaddr"] + + def section_at(self, address, size, writable=None): + end = _end(address, size) + found = [s for s in self.sections if s["flags"] & 2 and s["addr"] <= address + and end <= s["addr"] + s["size"] and + (writable is None or bool(s["flags"] & 1) == writable)] + _need(size > 0 and len(found) == 1, "ambiguous/unsectioned address range") + return found[0] + + def section_type(self, kind, mandatory=True): + found = [s for s in self.sections if s["type"] == kind] + _need(len(found) == 1 if mandatory else len(found) <= 1, "section cardinality") + return found[0] if found else None + + def headers(self): + _need(self.raw[:16] == b"\x7fELF\x02\x01\x01\x00" + b"\0" * 8, "ELF identity/profile") + h = self.unpack("= phend, "header table overlap") + self.header_ranges = [(0, phend), (shoff, shend)] + allowed_ph = {0, 1, 2, 4, 6, 0x6474E550, 0x6474E551, 0x6474E552} + programs = [] + for i in range(phnum): + kind, f, off, va, pa, fs, ms, align = self.unpack(" 0 and fs > 0 and f in (4, 5, 6) and align >= PAGE and + va % align == off % align, "PT_LOAD profile") + _need(not (f & 1) or fs == ms, "executable zero fill") + self.loads.append(p) + _need(2 <= len(self.loads) <= 8, "PT_LOAD count") + _need(self.loads == sorted(self.loads, key=lambda p: p["vaddr"]), "PT_LOAD ordering") + _disjoint([(p["vaddr"] // PAGE * PAGE, + (p["vaddr"] + p["memsz"] + PAGE - 1) // PAGE * PAGE) for p in self.loads], + "PT_LOAD mapped-page overlap") + _disjoint([(p["offset"], p["offset"] + p["filesz"]) for p in self.loads], "PT_LOAD file overlap") + _need(sum(p["memsz"] for p in self.loads) <= MAX_MEMORY, "aggregate mapped memory") + _need(any(p["flags"] == 5 for p in self.loads) and any(p["flags"] == 6 for p in self.loads), + "missing code/data segment") + first = self.loads[0] + _need(first["vaddr"] == 0 and first["offset"] == 0 and first["flags"] == 4 and + first["filesz"] >= phend, "header load mapping") + by_kind = {} + for p in programs: + by_kind.setdefault(p["type"], []).append(p) + if p["type"] in (0, 1, 0x6474E551): + continue + _need(p["filesz"] > 0 and p["memsz"] == p["filesz"], "auxiliary program range") + owner = self.load_at(p["vaddr"], p["filesz"], file_backed=True) + _need(p["offset"] == owner["offset"] + p["vaddr"] - owner["vaddr"], + "auxiliary program mapping") + _need(p["flags"] & ~owner["flags"] == 0, "auxiliary segment permissions") + _need(len(by_kind.get(2, ())) == 1 and len(by_kind.get(0x6474E551, ())) == 1 and + len(by_kind.get(0x6474E552, ())) == 1, "dynamic/stack/RELRO cardinality") + for k in (6, 0x6474E550, 0x6474E553): + _need(len(by_kind.get(k, ())) <= 1, "auxiliary program cardinality") + stack = by_kind[0x6474E551][0] + _need(stack["flags"] == 6 and stack["offset"] == stack["vaddr"] == + stack["filesz"] == stack["memsz"] == 0, "executable/noncanonical stack") + self.dynamic_segment = by_kind[2][0] + _need(self.dynamic_segment["flags"] == 6, "dynamic segment permissions") + self.relro = by_kind[0x6474E552][0] + self.load_at(self.relro["vaddr"], self.relro["memsz"], writable=True) + # glibc 2.39 _dl_protect_relro floors BOTH endpoints, not the end up. + # The admitted first PT_LOAD and p_align establish a page-aligned load + # bias under the independently admitted 4096-byte loader page profile. + relro_start = self.relro["vaddr"] + relro_end = _end(relro_start, self.relro["memsz"], MAX_MEMORY) + self.nominal_relro = (relro_start, relro_end) + self.effective_relro = (relro_start // self.page_size * self.page_size, + relro_end // self.page_size * self.page_size) + _need(self.effective_relro[0] < self.effective_relro[1], "RELRO protects no complete pages") + if by_kind.get(6): + p = by_kind[6][0] + _need(p["offset"] == phoff and p["vaddr"] == phoff and p["filesz"] == phnum * 56, + "PT_PHDR mismatch") + for i in range(shnum): + n, t, f, a, o, z, link, info, align, ent = self.unpack(" 1: + _need((a if f & 2 else o) % align == 0, "section misalignment") + if f & 2 and z: + p = self.load_at(a, z, file_backed=t != 8) + _need(bool(f & 1) == bool(p["flags"] & 2) or not (f & 1), "section write mapping") + _need(not (f & 4) or p["flags"] == 5, "section execute mapping") + _need(not (f & 1) or not (p["flags"] & 1), "writable code mapping") + if t != 8: + _need(o == p["offset"] + a - p["vaddr"], "section file/virtual mapping") + else: + _need(a >= p["vaddr"] + p["filesz"], "NOBITS overlaps file bytes") + elif not (f & 2): + _need(a == 0, "nonallocated section address") + self.sections.append(dict(index=i, name_offset=n, type=t, flags=f, addr=a, offset=o, + size=z, link=link, info=info, align=align, entsize=ent)) + strsec = self.sections[shstr] + _need(strsec["type"] == 3 and strsec["flags"] == 0, "section-name table") + self.string_table(strsec) + names = set() + for s in self.sections: + s["name"] = self.cstring(strsec, s["name_offset"], empty=s["index"] == 0) + _need(s["name"] not in names, "duplicate section name") + names.add(s["name"]) + _need(not any(x in s["name"] for x in ("init_array", "fini_array", "preinit_array")) + and s["name"] not in (".init", ".fini", ".ctors", ".dtors"), "constructor section") + file_ranges = [(s["offset"], s["offset"] + s["size"]) for s in self.sections + if s["type"] != 8 and s["size"]] + _disjoint(file_ranges + self.header_ranges, "section/header file overlap") + _disjoint([(s["addr"], s["addr"] + s["size"]) for s in self.sections if s["flags"] & 2 and s["size"]], + "allocated section overlap") + for s in self.sections: + if s["type"] in (3, 4, 5, 6, 11, 0x6FFFFFF6, 0x6FFFFFFE, 0x6FFFFFFF) and s["flags"] & 2: + self.protected.append((s["addr"], s["addr"] + s["size"])) + if s["type"] != 6 and s["size"]: + owner = self.load_at(s["addr"], s["size"], file_backed=True) + _need(owner["flags"] == 4, "loader metadata not read-only") + self.protected.append((0, phend)) + # Narrow production profile: GNU build-id notes only. GNU properties, + # ABI notes and unknown processor features require a separate profile. + note_sections = [s for s in self.sections if s["type"] == 7] + _need(len(note_sections) <= 1 and len(by_kind.get(4, ())) == len(note_sections), + "note section/program cardinality") + for note, program in zip(note_sections, by_kind.get(4, ())): + _need(note["name"] == ".note.gnu.build-id" and note["flags"] == 2 and + note["align"] == 4 and note["entsize"] == 0 and note["size"] >= 16 and + (note["offset"], note["addr"], note["size"]) == + (program["offset"], program["vaddr"], program["filesz"]), "note profile") + namesz, descsz, kind = self.unpack(" 0 and self.effective_relro[0] <= address and end <= self.effective_relro[1], reason) + + def string_table(self, s): + _need(s["type"] == 3 and 1 <= s["size"] <= MAX_FILE and s["entsize"] == 0, + "string table profile") + b = self.read(s["offset"], s["size"]) + _need(b[0] == b[-1] == 0, "string table endpoints") + + def dynamics(self): + s = self.section_type(6) + p = self.dynamic_segment + _need(s["flags"] == 3 and s["addr"] == p["vaddr"] and s["offset"] == p["offset"] + and s["size"] == p["filesz"] and s["entsize"] == 16 and + 1 <= s["size"] // 16 <= MAX_DYNAMIC, "dynamic section/segment mismatch") + self.dynamic_section = s + _need(self.relro["vaddr"] <= s["addr"] and s["addr"] + s["size"] <= + self.relro["vaddr"] + self.relro["memsz"], "dynamic table outside nominal RELRO") + self.require_effective_relro(s["addr"], s["size"], "dynamic table outside effective RELRO") + allowed = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 23, 24, 30, + 0x6FFFFEF5, 0x6FFFFFF0, 0x6FFFFFF9, 0x6FFFFFFB, 0x6FFFFFFE, 0x6FFFFFFF} + ended = False + for o in range(s["offset"], s["offset"] + s["size"], 16): + tag, val = self.unpack("> 4, info & 15, other & 3 + _need(other == vis and bind in (0, 1, 2) and typ in (0, 1, 2, 3, 4), + "symbol binding/type/visibility") + _need((i < s["info"]) == (bind == 0), "symbol local partition") + name = self.cstring(st, no, empty=i == 0 or typ == 3) + if i == 0: + _need((no, info, other, sh, value, size) == (0,) * 6, "nonnull zero symbol") + elif dynamic: + _need(bind in (1, 2) and typ in (0, 1, 2) and name, "dynamic symbol profile") + if sh == 0: + _need(value == 0 and size == 0 and (i == 0 or bind in (1, 2)) and vis == 0, + "undefined symbol profile") + elif sh == 0xFFF1 and not dynamic and typ == 4 and bind == 0: + _need(value == size == 0, "FILE symbol profile") + else: + _need(0 < sh < len(self.sections), "absolute/common/reserved symbol section") + sec = self.sections[sh] + if typ == 4: + _need(False, "nonabsolute FILE symbol") + if sec["flags"] & 2: + _need(sec["addr"] <= value and _end(value, size) <= sec["addr"] + sec["size"], + "defined symbol extent/section") + if typ == 2: + _need(size > 0 and sec["flags"] & 4, + "function extent/section") + self.load_at(value, size, file_backed=True, executable=True, writable=False) + else: + _need(not dynamic and typ in (0, 3), "unallocated dynamic/object/function symbol") + result.append(dict(index=i, name=name, binding=bind, type=typ, visibility=vis, + section=sh, value=value, size=size)) + return result + + def symbol_tables(self): + self.dynsyms = self.symbols(self.dynsym_section, True) + full = self.section_type(2) + _need(full["flags"] == 0, "full symbol table profile") + self.fullsyms = self.symbols(full, False) + self.versions() + self.full_by_name = {} + for sym in self.fullsyms[1:]: + self.full_by_name.setdefault(sym["name"], []).append(sym) + names = [s["name"] for s in self.dynsyms[1:]] + _need(len(set(names)) == len(names), "duplicate dynamic symbol name") + exports = [] + for sym in self.dynsyms[1:]: + if sym["section"]: + _need(sym["binding"] == 1 and sym["type"] == 2 and sym["visibility"] == 0, + "unexpected exported definition") + exports.append(sym["name"]) + full_names = (sym["name"],) if sym["version"] is None else (sym["name"], sym["name"] + "@" + sym["version"]) + matches = [candidate for name in full_names for candidate in self.full_by_name.get(name, ())] + _need(len(matches) == 1, "dynamic/full symbol ambiguity") + match = matches[0] + _need(all(match[k] == sym[k] for k in ("binding", "type", "visibility", "section", "value", "size")), + "dynamic/full symbol mismatch") + _need(set(exports) == set(self.policy["expected_exports"]), "export closure mismatch") + for sym in self.fullsyms[1:]: + if 0 < sym["section"] < len(self.sections) and sym["type"] in (1, 2) and sym["name"] not in exports: + _need(sym["binding"] == 0 or sym["binding"] == 1 and sym["visibility"] == 2, + "interposable internal function/data") + self.initializer = next(s for s in self.dynsyms if s["name"] == INITIALIZER) + _need(self.initializer["size"] > 0, "empty initializer") + for k, typ in (("required_local_functions", 2), ("required_local_objects", 1)): + for name in self.policy[k]: + matches = self.full_by_name.get(name, ()) + _need(len(matches) == 1, "source helper missing/ambiguous") + s = matches[0] + _need(s["type"] == typ and s["size"] > 0 and 0 < s["section"] < len(self.sections) + and (s["binding"] == 0 or s["binding"] == 1 and s["visibility"] == 2), + "interposable/invalid source helper") + self.load_at(s["value"], s["size"], file_backed=True, executable=typ == 2) + + def hashes(self): + d, syms = self.dynamic, self.dynsyms + n = len(syms) + reachable_sets = [] + for tag, kind in ((4, 5), (0x6FFFFEF5, 0x6FFFFFF6)): + section = self.section_type(kind, False) + _need((tag in d) == (section is not None), "hash section/tag mismatch") + if section is None: + continue + _need(section["flags"] == 2 and section["addr"] == d[tag] and + section["link"] == self.dynsym_section["index"], "hash link/address") + off = section["offset"] + visited = set() + if tag == 4: + nb, nc = self.unpack("> shift) % 64)) + if chain & 1: + break + i += 1 + _need(visited == set(range(first, n)) and tuple(expected_blooms) == blooms, + "GNU unreachable symbol/bloom mismatch") + _need(all(s["section"] == 0 for s in syms[1:first]), "GNU omitted definition") + _need(self.initializer["index"] in visited and + all(s["index"] in visited for s in syms[1:] if s["section"]), "initializer/export not hash reachable") + reachable_sets.append(tuple(sorted(visited))) + self.hash_reachability = tuple(reachable_sets) + + def versions(self): + d = self.dynamic + vs = self.section_type(0x6FFFFFFF, False) + vn = self.section_type(0x6FFFFFFE, False) + _need((0x6FFFFFF0 in d) == (vs is not None) and + (0x6FFFFFFE in d) == (vn is not None), "version section/tag mismatch") + version_map = {} + self.version_requirements = [] + version_pairs = set() + if vn is not None: + _need(vs is not None and vn["flags"] == 2 and vn["addr"] == d[0x6FFFFFFE] and + vn["link"] == self.dynstr["index"] and vn["info"] == d[0x6FFFFFFF] + and 1 <= vn["info"] <= 64, "verneed metadata") + pos = 0 + seen_files = set() + for ni in range(vn["info"]): + ver, cnt, no, aux, nxt = self.unpack("