From 3bcf99910a95248452e955d382c59bd23792a39b Mon Sep 17 00:00:00 2001 From: Chris R Date: Fri, 6 Nov 2026 16:19:00 +1100 Subject: [PATCH] Add reviewed complete-outcome CLOSE source extension --- .../LICENSE-APACHE-2.0.txt | 201 +++ .../h25-complete-outcome-close/MANIFEST.json | 96 ++ .../PROVENANCE.json | 22 + research/h25-complete-outcome-close/README.md | 34 + .../h25-complete-outcome-close/SHA256SUMS | 18 + .../evidence/DISPATCH-normal-v1.json | 17 + .../evidence/DISPATCH-optimized-v1.json | 17 + .../evidence/normal-v1.stderr.txt | 0 .../evidence/normal-v1.stdout.json | 51 + .../evidence/normal-v1.time.txt | 23 + .../evidence/optimized-v1.stderr.txt | 0 .../evidence/optimized-v1.stdout.json | 51 + .../evidence/optimized-v1.time.txt | 23 + .../active_complete_close_v1.py | 1140 +++++++++++++++++ .../implementation/funding_current.py.txt | 660 ++++++++++ .../reference/active_original.py.txt | 883 +++++++++++++ .../review/REVIEW-v1-findings.md | 40 + .../review/REVIEW-v2-final-source.md | 58 + .../review/REVIEW-v3-control-outcome.md | 32 + .../validation/controls_v1.py | 224 ++++ 20 files changed, 3590 insertions(+) create mode 100644 research/h25-complete-outcome-close/LICENSE-APACHE-2.0.txt create mode 100644 research/h25-complete-outcome-close/MANIFEST.json create mode 100644 research/h25-complete-outcome-close/PROVENANCE.json create mode 100644 research/h25-complete-outcome-close/README.md create mode 100644 research/h25-complete-outcome-close/SHA256SUMS create mode 100644 research/h25-complete-outcome-close/evidence/DISPATCH-normal-v1.json create mode 100644 research/h25-complete-outcome-close/evidence/DISPATCH-optimized-v1.json create mode 100644 research/h25-complete-outcome-close/evidence/normal-v1.stderr.txt create mode 100644 research/h25-complete-outcome-close/evidence/normal-v1.stdout.json create mode 100644 research/h25-complete-outcome-close/evidence/normal-v1.time.txt create mode 100644 research/h25-complete-outcome-close/evidence/optimized-v1.stderr.txt create mode 100644 research/h25-complete-outcome-close/evidence/optimized-v1.stdout.json create mode 100644 research/h25-complete-outcome-close/evidence/optimized-v1.time.txt create mode 100644 research/h25-complete-outcome-close/implementation/active_complete_close_v1.py create mode 100644 research/h25-complete-outcome-close/implementation/funding_current.py.txt create mode 100644 research/h25-complete-outcome-close/reference/active_original.py.txt create mode 100644 research/h25-complete-outcome-close/review/REVIEW-v1-findings.md create mode 100644 research/h25-complete-outcome-close/review/REVIEW-v2-final-source.md create mode 100644 research/h25-complete-outcome-close/review/REVIEW-v3-control-outcome.md create mode 100644 research/h25-complete-outcome-close/validation/controls_v1.py diff --git a/research/h25-complete-outcome-close/LICENSE-APACHE-2.0.txt b/research/h25-complete-outcome-close/LICENSE-APACHE-2.0.txt new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/h25-complete-outcome-close/LICENSE-APACHE-2.0.txt @@ -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-complete-outcome-close/MANIFEST.json b/research/h25-complete-outcome-close/MANIFEST.json new file mode 100644 index 0000000000..52b97797c1 --- /dev/null +++ b/research/h25-complete-outcome-close/MANIFEST.json @@ -0,0 +1,96 @@ +{ + "schema": "complete-close-source-archive-v1", + "files": [ + { + "path": "LICENSE-APACHE-2.0.txt", + "bytes": 11357, + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4" + }, + { + "path": "PROVENANCE.json", + "bytes": 1199, + "sha256": "dad76e320204fbc030456e66f6fe9e43987541be5719e2cd16378c0c02e35683" + }, + { + "path": "README.md", + "bytes": 5859, + "sha256": "65002848ca5c20cb0d62b6d492f397ae6d30acef378bd5b7263c0c3af8f13993" + }, + { + "path": "evidence/DISPATCH-normal-v1.json", + "bytes": 720, + "sha256": "8409069d1ead47311cdbc428d7d60498f084da4618119a27398ff86f212862f7" + }, + { + "path": "evidence/DISPATCH-optimized-v1.json", + "bytes": 720, + "sha256": "a49714642e5dada5a08744873cf6ed6d180c10f8555bd7daeb1aab0b6c4a46b5" + }, + { + "path": "evidence/normal-v1.stderr.txt", + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "path": "evidence/normal-v1.stdout.json", + "bytes": 2566, + "sha256": "36f05c75b1a82e1a6518b99ad72fd69c72a3dca52f72d2f316f285facc83fa52" + }, + { + "path": "evidence/normal-v1.time.txt", + "bytes": 1122, + "sha256": "33746e69d269b74fc342722aa573d52f20003710e34330b57cdc20ba896e8a7f" + }, + { + "path": "evidence/optimized-v1.stderr.txt", + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "path": "evidence/optimized-v1.stdout.json", + "bytes": 2563, + "sha256": "8b528424889c825e1e5622907e7363059b3c002e6cb055a2a1b1d087d8cc06ba" + }, + { + "path": "evidence/optimized-v1.time.txt", + "bytes": 1125, + "sha256": "51c07b73033912f7c49ba679ad9fd910c5f8e38f52dc3b0795bd3f79274fe2eb" + }, + { + "path": "implementation/active_complete_close_v1.py", + "bytes": 73241, + "sha256": "9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380" + }, + { + "path": "implementation/funding_current.py.txt", + "bytes": 40590, + "sha256": "164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677" + }, + { + "path": "reference/active_original.py.txt", + "bytes": 54629, + "sha256": "e94ee23f4f66b16f9d5a0b7f1cc510952d1769247283062d9124737d7838ce3c" + }, + { + "path": "review/REVIEW-v1-findings.md", + "bytes": 7521, + "sha256": "e8eb3bad45b16ed56cd47bf892b107c19b7740acab204307993d60269e63e1d0" + }, + { + "path": "review/REVIEW-v2-final-source.md", + "bytes": 10455, + "sha256": "79bafd219db9b7b1076de462b2b3d91fb85a742236088482f3279a07953137de" + }, + { + "path": "review/REVIEW-v3-control-outcome.md", + "bytes": 4424, + "sha256": "38b675f43d62e5a7a43117a127b994472a2a8705f5075e93f65693c6e880343c" + }, + { + "path": "validation/controls_v1.py", + "bytes": 19372, + "sha256": "81ef02f0f8cb2b45fb03f6cbf2fee462a8b021602b2031699d3a31116cc5b25f" + } + ], + "scope": "Source component and inert finite controls; no genuine adoption or native qualification" +} diff --git a/research/h25-complete-outcome-close/PROVENANCE.json b/research/h25-complete-outcome-close/PROVENANCE.json new file mode 100644 index 0000000000..28c3593e5c --- /dev/null +++ b/research/h25-complete-outcome-close/PROVENANCE.json @@ -0,0 +1,22 @@ +{ + "base": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "owner_predecessor_commit": "0f2a86fa9ef0daf760b77c662a5b762e17848598", + "inputs": [ + { + "export_path": "reference/active_original.py.txt", + "bytes": 54629, + "sha256": "e94ee23f4f66b16f9d5a0b7f1cc510952d1769247283062d9124737d7838ce3c", + "url": "https://github.com/CrocSwap/integer-mult-bounds/blob/0f2a86fa9ef0daf760b77c662a5b762e17848598/research/h25-s03-retention-completion-source/snapshots/implementation/controller/active_current.py.txt" + }, + { + "export_path": "implementation/funding_current.py.txt", + "bytes": 40590, + "sha256": "164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677", + "url": "https://github.com/CrocSwap/integer-mult-bounds/blob/0f2a86fa9ef0daf760b77c662a5b762e17848598/research/h25-s03-retention-completion-source/snapshots/implementation/controller/funding_current.py.txt" + } + ], + "new_source_sha256": "9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380", + "new_harness_sha256": "81ef02f0f8cb2b45fb03f6cbf2fee462a8b021602b2031699d3a31116cc5b25f", + "genuine_bootstrap_adoption": "NOT_SUPPLIED", + "automatic_runtime_replay": false +} diff --git a/research/h25-complete-outcome-close/README.md b/research/h25-complete-outcome-close/README.md new file mode 100644 index 0000000000..b49ae54f84 --- /dev/null +++ b/research/h25-complete-outcome-close/README.md @@ -0,0 +1,34 @@ +# Complete-outcome CLOSE source extension + +This source extension lets the original ACTIVE owner record an independently accepted complete outcome through its existing formal CLOSE, append-only registry, and durable HEAD readback path. The old six-field STOP/UNKNOWN closure remains unchanged. The new optional `approved_complete_closure` selects a separate, once-only evidence path. The Context method set and full scientific source images remain unchanged. + +Original investigation: [PR #6321](https://github.com/CrocSwap/integer-mult-bounds/pull/6321). Owning source predecessor: [PR #6736](https://github.com/CrocSwap/integer-mult-bounds/pull/6736), exact head `0f2a86fa9ef0daf760b77c662a5b762e17848598`. Readable resource-contract evidence: [PR #6756](https://github.com/CrocSwap/integer-mult-bounds/pull/6756), `2818eb6f2343ef75bed10346790ce819332c6038`. + +The implementation keeps the closer's original operation separate from the target's request and reservation. It verifies request-to-START equality, source/profile/result-contract correlations, a complete outer interval, aggregate sampled resource scope, terminal/cleanup/custody facts, and an acyclic independent-review binding. It computes the prospective receipt pin, registry and HEAD images, validates append-only semantics and capacity, and only then calls the original publication functions. The receipt's original raw bytes are retained. Truthful resource-invalid PASS/STOP observations remain recordable; the original funding rules retain future-admission blockers. No fit or next-command grant is returned. + +The authenticated source-private parent must genuinely accept the complete raw evidence and its custody, fix the original result contract before observing the outcome, and authenticate clock lineage. Metadata consistency checks cannot establish these premises. The review manifest commits to bounded metadata and the full original raw inventory, including larger evidence verified by that parent/reviewer; the closer does not read arbitrary large captures. The original 131,072-byte metadata cap remains. + +## Contents and validation + +`implementation/active_complete_close_v1.py` is the owning source successor. `implementation/funding_current.py.txt` is the exact unchanged funding dependency. `reference/active_original.py.txt` retains the exact original owner needed for the static compatibility control. Frozen maps record their hashes and public acquisition URLs. This is a source archive; no installed caller, owner capability, current runtime grant, or automatic replay hook is supplied. + +The parent ran the reviewed finite controls once in each mode: **41 passed in assertion-on mode and 41 passed in optimized mode**, with no failures or skips. The controls extract whole actual changed functions and the actual unchanged registry-advance function. Native publication, lease, currentness and time ports are inert. They exercise publication boundaries, request/START mismatches, outcome-contract confusion, original error A through release error B and recorder error C, one-use rejection, separate reservations, untrimmed overruns, and exact static legacy compatibility. They do not exercise every internal write/link/fsync failure of the original publisher or the real bootstrap/native owner. + +From this directory, suggested reproduction commands are: + +```sh +python3 -S -s -P -B validation/controls_v1.py +python3 -S -s -P -B -O validation/controls_v1.py +``` + +The issued commands, stdout, empty stderr, and GNU time observations are retained under `evidence/`. They used CPython 3.12, a sanitized six-variable environment, a 20-second timeout with a 2-second termination grace, 256 MiB address-space and 20-second CPU limits, 1 MiB output file cap, and 256 descriptors. Normal wall time was 0.50 seconds and reported peak RSS was 29,340 kB; optimized wall time was 0.40 seconds and reported peak RSS was 29,356 kB. These are fixture observations, without a performance comparison. Conservative policy debit was 54 seconds including fees. Physical preparation, consultation, review, publication and historical costs remain OPEN_NOT_ZERO. + +## Remaining work + +Adopt the exact frozen successor in the genuine authenticated bootstrap/caller and detached source manifests; the old owner source hash cannot authenticate new code. Independently review those connected source bindings. Produce and independently accept a genuine complete outcome, retain the original complete workload receiver/command/guardian/barrier selection, fund its entire attempt envelope, and obtain current native/profile admission before target execution. No original full resource-bill, normal-fit or optimized-fit acceptance follows from this prerequisite alone. + +## Reuse and credit + +[PR #6709](https://github.com/CrocSwap/integer-mult-bounds/pull/6709), `24417a34746985dd110d70a42b2b863b96963c12`, supplied compatible ordering and once-only settlement ideas. Its separate financial namespace and builder do not replace the original formal CLOSE owner. The existing original-record writer retains COMMAND/START/BODY/terminal records and explicitly excludes formal registry/CLOSE publication. This extension addresses that specific missing return edge. + +Retain Douglas R. Colkitt, the CrocSwap contributors and all inherited source/license notices. Cleanup lineage includes [PR #6339](https://github.com/CrocSwap/integer-mult-bounds/pull/6339), `608ad23adc6c01264c8195daf7f18e29c17464a7`, and [PR #6346](https://github.com/CrocSwap/integer-mult-bounds/pull/6346), `abff67b31fa781e950c82d95eccb6f168950943c`, with unpaidmoon/Cursor Grok predecessor credit retained. New source and packaging are by Chris R / Clear1nsight with substantial OpenAI Codex and ChatGPT Pro assistance, Apache-2.0. Distinct GPT-6.1-sol Max source review is independent AI review, without human, proof-kernel or native acceptance. diff --git a/research/h25-complete-outcome-close/SHA256SUMS b/research/h25-complete-outcome-close/SHA256SUMS new file mode 100644 index 0000000000..dda3b0a3cd --- /dev/null +++ b/research/h25-complete-outcome-close/SHA256SUMS @@ -0,0 +1,18 @@ +c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 LICENSE-APACHE-2.0.txt +dad76e320204fbc030456e66f6fe9e43987541be5719e2cd16378c0c02e35683 PROVENANCE.json +65002848ca5c20cb0d62b6d492f397ae6d30acef378bd5b7263c0c3af8f13993 README.md +8409069d1ead47311cdbc428d7d60498f084da4618119a27398ff86f212862f7 evidence/DISPATCH-normal-v1.json +a49714642e5dada5a08744873cf6ed6d180c10f8555bd7daeb1aab0b6c4a46b5 evidence/DISPATCH-optimized-v1.json +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 evidence/normal-v1.stderr.txt +36f05c75b1a82e1a6518b99ad72fd69c72a3dca52f72d2f316f285facc83fa52 evidence/normal-v1.stdout.json +33746e69d269b74fc342722aa573d52f20003710e34330b57cdc20ba896e8a7f evidence/normal-v1.time.txt +e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 evidence/optimized-v1.stderr.txt +8b528424889c825e1e5622907e7363059b3c002e6cb055a2a1b1d087d8cc06ba evidence/optimized-v1.stdout.json +51c07b73033912f7c49ba679ad9fd910c5f8e38f52dc3b0795bd3f79274fe2eb evidence/optimized-v1.time.txt +9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380 implementation/active_complete_close_v1.py +164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677 implementation/funding_current.py.txt +e94ee23f4f66b16f9d5a0b7f1cc510952d1769247283062d9124737d7838ce3c reference/active_original.py.txt +e8eb3bad45b16ed56cd47bf892b107c19b7740acab204307993d60269e63e1d0 review/REVIEW-v1-findings.md +79bafd219db9b7b1076de462b2b3d91fb85a742236088482f3279a07953137de review/REVIEW-v2-final-source.md +38b675f43d62e5a7a43117a127b994472a2a8705f5075e93f65693c6e880343c review/REVIEW-v3-control-outcome.md +81ef02f0f8cb2b45fb03f6cbf2fee462a8b021602b2031699d3a31116cc5b25f validation/controls_v1.py diff --git a/research/h25-complete-outcome-close/evidence/DISPATCH-normal-v1.json b/research/h25-complete-outcome-close/evidence/DISPATCH-normal-v1.json new file mode 100644 index 0000000000..5b6f8b3d5a --- /dev/null +++ b/research/h25-complete-outcome-close/evidence/DISPATCH-normal-v1.json @@ -0,0 +1,17 @@ +{ + "schema": "complete-close-parent-control-dispatch-v1", + "recorded_utc": "2026-11-06T05:12:59.445589+00:00", + "mode": "assertion-on", + "source_sha256": "9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380", + "harness_sha256": "81ef02f0f8cb2b45fb03f6cbf2fee462a8b021602b2031699d3a31116cc5b25f", + "review": "complete_close_review GO_COMMAND_SOURCE_ONLY at05:12UTC", + "body_reservation_seconds": 25, + "administrative_debit_seconds": 2, + "policy_posted_before": "1354.890533479", + "policy_with_active_reservation": "1381.890533479", + "total_cap_seconds": 2400, + "physical_costs": "OPEN_NOT_ZERO", + "native_science_allowed": false, + "automatic_retry": false, + "raw_output_prefix": "normal-v1" +} diff --git a/research/h25-complete-outcome-close/evidence/DISPATCH-optimized-v1.json b/research/h25-complete-outcome-close/evidence/DISPATCH-optimized-v1.json new file mode 100644 index 0000000000..f84bc8a216 --- /dev/null +++ b/research/h25-complete-outcome-close/evidence/DISPATCH-optimized-v1.json @@ -0,0 +1,17 @@ +{ + "schema": "complete-close-parent-control-dispatch-v1", + "recorded_utc": "2026-11-06T05:13:22.857023+00:00", + "mode": "optimized", + "source_sha256": "9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380", + "harness_sha256": "81ef02f0f8cb2b45fb03f6cbf2fee462a8b021602b2031699d3a31116cc5b25f", + "review": "complete_close_review GO_COMMAND_SOURCE_ONLY at05:12UTC", + "body_reservation_seconds": 25, + "administrative_debit_seconds": 2, + "policy_posted_before": "1381.890533479", + "policy_with_active_reservation": "1408.890533479", + "total_cap_seconds": 2400, + "physical_costs": "OPEN_NOT_ZERO", + "native_science_allowed": false, + "automatic_retry": false, + "raw_output_prefix": "optimized-v1" +} diff --git a/research/h25-complete-outcome-close/evidence/normal-v1.stderr.txt b/research/h25-complete-outcome-close/evidence/normal-v1.stderr.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/research/h25-complete-outcome-close/evidence/normal-v1.stdout.json b/research/h25-complete-outcome-close/evidence/normal-v1.stdout.json new file mode 100644 index 0000000000..f6e570fecf --- /dev/null +++ b/research/h25-complete-outcome-close/evidence/normal-v1.stdout.json @@ -0,0 +1,51 @@ +{ + "schema": "complete-close-finite-control-result-v1", + "mode": "assertion-on", + "source_sha256": "9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380", + "funding_sha256": "164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677", + "passed": 41, + "cases": [ + "actual changed close and advance exact publication sequence, no grants, one use", + "whole validator complete positive", + "receipt mutation outcome", + "receipt mutation body_elapsed_ns", + "receipt mutation body_begin_ns", + "receipt mutation peak_sampled_rss_bytes", + "receipt mutation cleanup_known", + "receipt mutation custody_complete", + "receipt mutation nested_entries_complete", + "receipt mutation uncertainty", + "receipt mutation tail_state", + "receipt mutation administrative_debit_ns", + "receipt mutation label", + "receipt mutation start_sha256", + "accepted evidence mutation interval_scope", + "accepted evidence mutation rss_scope", + "accepted evidence mutation result_kind", + "accepted evidence mutation command_sha256", + "accepted evidence mutation source_manifest_sha256", + "accepted evidence mutation profile_sha256", + "accepted evidence mutation admission_sha256", + "accepted evidence mutation raw_inputs", + "actual advance publication boundary failure receipt", + "actual advance publication boundary failure registry", + "actual advance publication boundary failure history", + "actual advance publication boundary failure head", + "actual advance publication boundary failure readback", + "known resource-invalid STOP retains untrimmed actual values", + "original resource-invalid PASS retains untrimmed actual values", + "A remains primary through release B and recorder C", + "own reservation cannot borrow target", + "wrong role", + "stale reviewed HEAD", + "request command cannot substitute for actual registered START", + "original FIRST A survives initial verify B, release D, recorder C and one release", + "actual legacy STOP UNKNOWN branch result and publication retained", + "prospective exhausted registry generation before publication", + "oversized formal receipt metadata rejected", + "selected original expected-refusal oracle positive", + "selected original known-STOP disposition positive", + "static exact legacy close body and Context method set retained" + ], + "scope": "AST-extracted whole changed functions and actual advance with INERT ports; no native ownership, bootstrap authentication, genuine evidence or fit qualification" +} diff --git a/research/h25-complete-outcome-close/evidence/normal-v1.time.txt b/research/h25-complete-outcome-close/evidence/normal-v1.time.txt new file mode 100644 index 0000000000..e6dc8b1a0a --- /dev/null +++ b/research/h25-complete-outcome-close/evidence/normal-v1.time.txt @@ -0,0 +1,23 @@ + Command being timed: "timeout --signal=TERM --kill-after=2s 20s prlimit --as=268435456 --cpu=20 --fsize=1048576 --nofile=256 env -i PATH=/usr/bin:/bin LANG=C LC_ALL=C PYTHONHASHSEED=0 PYTHONDONTWRITEBYTECODE=1 PYTHONPYCACHEPREFIX=/tmp/s04-close-normal /usr/bin/python3 -S -s -P -B /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/s04-complete-close-20261106T0438Z/validation/controls_v1.py" + User time (seconds): 0.45 + System time (seconds): 0.02 + Percent of CPU this job got: 93% + Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.50 + Average shared text size (kbytes): 0 + Average unshared data size (kbytes): 0 + Average stack size (kbytes): 0 + Average total size (kbytes): 0 + Maximum resident set size (kbytes): 29340 + Average resident set size (kbytes): 0 + Major (requiring I/O) page faults: 2 + Minor (reclaiming a frame) page faults: 6538 + Voluntary context switches: 45 + Involuntary context switches: 1 + Swaps: 0 + File system inputs: 1744 + File system outputs: 5 + Socket messages sent: 0 + Socket messages received: 0 + Signals delivered: 0 + Page size (bytes): 4096 + Exit status: 0 diff --git a/research/h25-complete-outcome-close/evidence/optimized-v1.stderr.txt b/research/h25-complete-outcome-close/evidence/optimized-v1.stderr.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/research/h25-complete-outcome-close/evidence/optimized-v1.stdout.json b/research/h25-complete-outcome-close/evidence/optimized-v1.stdout.json new file mode 100644 index 0000000000..5ce57f8ca0 --- /dev/null +++ b/research/h25-complete-outcome-close/evidence/optimized-v1.stdout.json @@ -0,0 +1,51 @@ +{ + "schema": "complete-close-finite-control-result-v1", + "mode": "optimized", + "source_sha256": "9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380", + "funding_sha256": "164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677", + "passed": 41, + "cases": [ + "actual changed close and advance exact publication sequence, no grants, one use", + "whole validator complete positive", + "receipt mutation outcome", + "receipt mutation body_elapsed_ns", + "receipt mutation body_begin_ns", + "receipt mutation peak_sampled_rss_bytes", + "receipt mutation cleanup_known", + "receipt mutation custody_complete", + "receipt mutation nested_entries_complete", + "receipt mutation uncertainty", + "receipt mutation tail_state", + "receipt mutation administrative_debit_ns", + "receipt mutation label", + "receipt mutation start_sha256", + "accepted evidence mutation interval_scope", + "accepted evidence mutation rss_scope", + "accepted evidence mutation result_kind", + "accepted evidence mutation command_sha256", + "accepted evidence mutation source_manifest_sha256", + "accepted evidence mutation profile_sha256", + "accepted evidence mutation admission_sha256", + "accepted evidence mutation raw_inputs", + "actual advance publication boundary failure receipt", + "actual advance publication boundary failure registry", + "actual advance publication boundary failure history", + "actual advance publication boundary failure head", + "actual advance publication boundary failure readback", + "known resource-invalid STOP retains untrimmed actual values", + "original resource-invalid PASS retains untrimmed actual values", + "A remains primary through release B and recorder C", + "own reservation cannot borrow target", + "wrong role", + "stale reviewed HEAD", + "request command cannot substitute for actual registered START", + "original FIRST A survives initial verify B, release D, recorder C and one release", + "actual legacy STOP UNKNOWN branch result and publication retained", + "prospective exhausted registry generation before publication", + "oversized formal receipt metadata rejected", + "selected original expected-refusal oracle positive", + "selected original known-STOP disposition positive", + "static exact legacy close body and Context method set retained" + ], + "scope": "AST-extracted whole changed functions and actual advance with INERT ports; no native ownership, bootstrap authentication, genuine evidence or fit qualification" +} diff --git a/research/h25-complete-outcome-close/evidence/optimized-v1.time.txt b/research/h25-complete-outcome-close/evidence/optimized-v1.time.txt new file mode 100644 index 0000000000..a7555f6bfc --- /dev/null +++ b/research/h25-complete-outcome-close/evidence/optimized-v1.time.txt @@ -0,0 +1,23 @@ + Command being timed: "timeout --signal=TERM --kill-after=2s 20s prlimit --as=268435456 --cpu=20 --fsize=1048576 --nofile=256 env -i PATH=/usr/bin:/bin LANG=C LC_ALL=C PYTHONHASHSEED=0 PYTHONDONTWRITEBYTECODE=1 PYTHONPYCACHEPREFIX=/tmp/s04-close-optimized /usr/bin/python3 -S -s -P -B -O /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/s04-complete-close-20261106T0438Z/validation/controls_v1.py" + User time (seconds): 0.39 + System time (seconds): 0.01 + Percent of CPU this job got: 100% + Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.40 + Average shared text size (kbytes): 0 + Average unshared data size (kbytes): 0 + Average stack size (kbytes): 0 + Average total size (kbytes): 0 + Maximum resident set size (kbytes): 29356 + Average resident set size (kbytes): 0 + Major (requiring I/O) page faults: 0 + Minor (reclaiming a frame) page faults: 6549 + Voluntary context switches: 4 + Involuntary context switches: 4 + Swaps: 0 + File system inputs: 8 + File system outputs: 5 + Socket messages sent: 0 + Socket messages received: 0 + Signals delivered: 0 + Page size (bytes): 4096 + Exit status: 0 diff --git a/research/h25-complete-outcome-close/implementation/active_complete_close_v1.py b/research/h25-complete-outcome-close/implementation/active_complete_close_v1.py new file mode 100644 index 0000000000..be3660e565 --- /dev/null +++ b/research/h25-complete-outcome-close/implementation/active_complete_close_v1.py @@ -0,0 +1,1140 @@ +"""SOURCE ONLY: private ACTIVE ownership and durable registry publication. + +Trusted caller must authenticate the exact loaded controller/funding modules +before bind_api. Module names, hash strings, dictionaries and instance fields +are NOT that authentication. This code performs real GlobalLease acquisition +and verification; never restore an owner from DATA or pass it to a child. +Ordinary OS/CPython/fsync/rename/link and registered-writer exclusion are selected +operating premises, not universal hostile-admin or crash-storage theorems. +""" +import hashlib +import json +import os +import stat +import time +from pathlib import Path +from types import ModuleType, FunctionType, GetSetDescriptorType + +# Kernel-body predecessor provenance ONLY; actual selected C/profile authenticated externally. +CONTROLLER_SHA = 'be36f1427694c786efc1cf04958a6fb002776f586641828ce569f36e2f289895' +FUNDING_SHA = '164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677' +W = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453') +R = W / 'outputs/h25-data-handling-20261028' +CONTROL = R / 'control/fresh-metered-round-v1' +DOMAIN = R / 'runtime/fresh-metered-round-v1/attempts' +STAGE = CONTROL / '_active-staging' +HEADS = CONTROL / '_registry-heads' +HANDOFFS = CONTROL / '_handoff-intents' +CLAIMS = CONTROL / '_handoff-claims' +HEAD = CONTROL / 'ACTIVE-HEAD.json' +LOCK = W / 'outputs/h25-bookkeeping-swarm-20261028/runtime/science.lock' + + +class ActiveError(RuntimeError): + pass + + +def need(ok, text): + if ok is not True: + raise ActiveError(text) + + +def canonical(value): + return (json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) + '\n').encode('utf-8') + + + + +# Finite ordinary-Python kernel substitution boundary. These checks perform no +# filesystem/process/clock operation and never establish loaded-image identity. +def module_namespace(module): + need(type(module) is ModuleType, 'exact selected module type') + namespace = ModuleType.__getattribute__(module, '__dict__') + need(type(namespace) is dict, 'native module namespace') + keys = tuple(dict.__iter__(namespace)) + need(all(type(k) is str for k in keys), 'module keys before hashing/lookup') + need('__getattr__' not in keys, 'no selected module attribute fallback') + return namespace + + +def function_image(fn, namespace): + need(type(fn) is FunctionType and fn.__globals__ is namespace, 'actual source-owned function') + return (fn, fn.__code__, fn.__defaults__, fn.__kwdefaults__, fn.__closure__) + + +def unchanged_function(image, namespace): + fn, code, defaults, kwdefaults, closure = image + need(type(fn) is FunctionType and fn.__globals__ is namespace and + fn.__code__ is code and fn.__defaults__ is defaults and + fn.__kwdefaults__ is kwdefaults and fn.__closure__ is closure, + 'captured original function metadata') + + +def class_image(cls, methods, namespace, *, slotted=False): + need(type(cls) is type, 'ordinary exact class before native type inspection') + mro = type.__getattribute__(cls, '__mro__') + need(type(mro) is tuple and len(mro) == 2 and mro[0] is cls and mro[1] is object, 'direct object class') + native = type.__getattribute__(cls, '__dict__') + keys = tuple(native) + need(all(type(k) is str for k in keys), 'class keys before hashing/lookup') + image = {k: native[k] for k in keys} + allowed = {'__module__', '__doc__'} | set(methods) + if slotted: + allowed |= {'__slots__', '__new__'} + need(type(image.get('__slots__')) is tuple and len(image['__slots__']) == 0 and + type(image.get('__new__')) is staticmethod, 'private empty-slotted class') + function_image(staticmethod.__getattribute__(image['__new__'], '__func__'), namespace) + else: + allowed |= {'__dict__', '__weakref__'} + for name in ('__dict__', '__weakref__'): + descriptor = image.get(name) + need(type(descriptor) is GetSetDescriptorType and descriptor.__objclass__ is cls and + type(descriptor.__name__) is str and descriptor.__name__ == name, 'native actual-class dictionary descriptor') + need(set(image) == allowed and type(image['__module__']) is str and + (image['__doc__'] is None or type(image['__doc__']) is str), 'fixed class layout; no special hooks') + function_images = {name: function_image(image[name], namespace) for name in methods} + if slotted: + function_images['__new__'] = function_image(staticmethod.__getattribute__(image['__new__'], '__func__'), namespace) + return image, function_images + + +def unchanged_class(cls, image, function_images, namespace): + need(type(cls) is type, 'unchanged ordinary metaclass') + native = type.__getattribute__(cls, '__dict__'); keys = tuple(native) + need(all(type(k) is str for k in keys) and set(keys) == set(image) and + all(native[k] is image[k] for k in keys), 'no class namespace/descriptor substitution') + mro = type.__getattribute__(cls, '__mro__') + need(type(mro) is tuple and len(mro) == 2 and mro[0] is cls and mro[1] is object, 'unchanged direct class ancestry') + for value in function_images.values(): + unchanged_function(value, namespace) + + +def instance_state(value, cls, image, function_images, namespace, fields): + need(type(value) is cls, 'exact actual instance before descriptor access') + unchanged_class(cls, image, function_images, namespace) + # Direct native getset dispatch bypasses value.__getattribute__ entirely. + values = GetSetDescriptorType.__get__(image['__dict__'], value, cls) + need(type(values) is dict, 'exact native instance dictionary') + keys = tuple(dict.__iter__(values)) + need(all(type(k) is str for k in keys) and set(keys) == set(fields), 'no instance method/descriptor/special-hook shadow') + return values + + +def bounded_kernel_data(value, nodes=None, depth=0): + if nodes is None: + nodes = [0] + nodes[0] += 1 + need(nodes[0] <= 256 and depth <= 8, 'bounded kernel metadata state') + t = type(value) + if t is dict: + keys = tuple(dict.__iter__(value)) + need(len(keys) <= 64 and all(type(k) is str for k in keys), 'kernel dictionary keys before lookup') + for key in keys: + bounded_kernel_data(value[key], nodes, depth + 1) + elif t is list or t is tuple: + need(len(value) <= 64, 'kernel metadata sequence bound') + for item in value: + bounded_kernel_data(item, nodes, depth + 1) + elif t is str: + need(len(value) <= 16384, 'kernel metadata string bound') + else: + need(value is None or t is int or t is bool, 'exact scalar kernel metadata') + + +def exception_instance(value): + cls = type(value) + if type(cls) is not type: + return False + mro = type.__getattribute__(cls, '__mro__') + return type(mro) is tuple and any(base is BaseException for base in mro) + +def complete_close_data(F, closure, receipt_raw, review_raw, documents, own_request, + own_provenance, original_own_start, current, raw_head, raw_reg): + """Consistency of externally accepted evidence; never native authentication. + + The authenticated source-private parent has already accepted the full raw + inventory, fixed the result contract at original admission, and authenticated + the clock lineage. This bounded DATA check neither reconstructs those facts + nor verifies large raw files. Every selected metadata body is actually read. + """ + def exact(value, fields): + F.plain(value); F.exact(value, fields) + def digest(raw): + return hashlib.sha256(raw).hexdigest() + def document(name, fields, schema): + value = F.decode(documents[name]); exact(value, fields) + need(value['schema'] == schema, 'complete-close document schema') + return value + binding = closure['evidence_binding'] + exact(binding, ('schema', 'admission_pin', 'source_manifest_pin', 'profile_pin', + 'result_contract_pin', 'evidence_manifest_pin', 'clock_pin', + 'expected_head_pin', 'closer_start_clock_path')) + need(binding['schema'] == 'complete-close-evidence-binding-v1', 'complete binding version') + for key in ('admission_pin', 'source_manifest_pin', 'profile_pin', 'result_contract_pin', + 'evidence_manifest_pin', 'clock_pin', 'expected_head_pin'): + F.pin(binding[key]) + request = closure['request']; start = closure['start'] + need(request['schema'] == 'fresh-round-request-v1' and start['schema'] == 'fresh-round-start-v1', + 'original request and START schemas') + for key in ('round_id', 'label', 'command_sha256', 'body_reservation_ns', 'policy_sha256'): + need(type(request[key]) is type(start[key]) and request[key] == start[key], + 'request agrees with actual registered START') + need(request['round_id'] == F.ROUND_ID, 'same original round') + F.validate_pre_entry_provenance(start['pre_entry_provenance'], request['label'], + request['command_sha256'], request['body_reservation_ns']) + need(own_request['label'] != request['label'] and + own_request['command_sha256'] != request['command_sha256'], 'distinct own/target operations') + need(binding['expected_head_pin']['sha256'] == digest(raw_head), 'accepted current head') + admission = document('admission_pin', ('schema', 'request', 'start_pin', 'baseline_registry_pin', + 'source_manifest_pin', 'profile_pin', 'result_contract_pin', 'registration_pin'), + 'complete-close-original-admission-v1') + for key in ('request', 'start_pin', 'baseline_registry_pin'): + need(admission[key] == closure[key], 'original admission target binding') + for key in ('source_manifest_pin', 'profile_pin', 'result_contract_pin'): + need(admission[key] == binding[key], 'original admitted source/profile/oracle') + need(admission['registration_pin'] == start['pre_entry_provenance']['registration_pin'], + 'same original registration; pre-outcome selection is external accepted premise') + contract = document('result_contract_pin', ('schema', 'kind', 'command_sha256', + 'source_manifest_pin', 'profile_pin'), 'complete-close-result-contract-v1') + need(contract['kind'] in ('FULL_POSITIVE', 'EXPECTED_REFUSAL', 'KNOWN_STOP') and + contract['command_sha256'] == request['command_sha256'] and + contract['source_manifest_pin'] == binding['source_manifest_pin'] and + contract['profile_pin'] == binding['profile_pin'], 'original result contract binding') + evidence = document('evidence_manifest_pin', ('schema', 'round_id', 'label', 'command_sha256', + 'start_sha256', 'admission_sha256', 'source_manifest_sha256', 'profile_sha256', + 'result_contract_sha256', 'interval_scope', 'rss_scope', 'body_begin_ns', 'body_end_ns', + 'body_elapsed_ns', 'peak_sampled_rss_bytes', 'body_fully_observed', 'cleanup_known', + 'custody_complete', 'nested_entries_complete', 'outcome', 'result_kind', 'uncertainty', + 'tail_state', 'raw_inputs'), 'complete-close-accepted-evidence-v1') + need(evidence['round_id'] == F.ROUND_ID and evidence['label'] == request['label'] and + evidence['command_sha256'] == request['command_sha256'] and + evidence['start_sha256'] == closure['start_pin']['sha256'], 'whole evidence target') + for name in ('admission', 'source_manifest', 'profile', 'result_contract'): + need(evidence[name + '_sha256'] == binding[name + '_pin']['sha256'], 'exact accepted evidence inputs') + need(evidence['interval_scope'] == 'COMPLETE_OUTER_COMMAND' and + evidence['rss_scope'] == 'AGGREGATE_SAMPLED_ROOT' and + evidence['result_kind'] == contract['kind'], 'whole invocation and original outcome oracle') + receipt = F.decode(receipt_raw) + exact(receipt, ('schema', 'round_id', 'label', 'start_sha256', 'outcome', 'body_elapsed_ns', + 'administrative_debit_ns', 'body_begin_ns', 'body_end_ns', 'body_fully_observed', + 'cleanup_known', 'custody_complete', 'nested_entries_complete', 'uncertainty', + 'peak_sampled_rss_bytes', 'tail_state', 'independent_outcome_review_sha256')) + need(receipt['schema'] == 'fresh-round-receipt-v1' and receipt['round_id'] == F.ROUND_ID and + receipt['label'] == request['label'] and receipt['start_sha256'] == closure['start_pin']['sha256'], + 'unchanged formal receipt identity') + for key in ('outcome', 'body_elapsed_ns', 'body_begin_ns', 'body_end_ns', 'body_fully_observed', + 'cleanup_known', 'custody_complete', 'nested_entries_complete', 'uncertainty', + 'peak_sampled_rss_bytes', 'tail_state'): + need(type(receipt[key]) is type(evidence[key]) and receipt[key] == evidence[key], 'receipt/evidence correlation') + for key in ('body_fully_observed', 'cleanup_known', 'custody_complete', 'nested_entries_complete'): + need(receipt[key] is True, 'complete accepted terminal/custody facts') + begin = F.uint(receipt['body_begin_ns']); end = F.uint(receipt['body_end_ns']) + elapsed = F.uint(receipt['body_elapsed_ns']); F.uint(receipt['peak_sampled_rss_bytes']) + need(end >= begin and end - begin == elapsed, 'exact whole outer interval') + need(receipt['uncertainty'] == [] and receipt['tail_state'] in ('COMPLETE', 'ADMIN_ONLY_OPEN'), + 'no unknown nonadministrative tails') + need(receipt['outcome'] in ('PASS', 'STOP') and + (contract['kind'] != 'KNOWN_STOP' or receipt['outcome'] == 'STOP'), 'truthful original outcome') + need(type(evidence['raw_inputs']) is list and 1 <= len(evidence['raw_inputs']) <= F.MAX_ENTRIES, + 'complete bounded raw inventory accepted externally') + seen = set() + for item in evidence['raw_inputs']: + exact(item, ('path', 'bytes', 'sha256', 'mode')) + need(type(item['path']) is str and Path(item['path']).is_absolute() and + item['path'] not in seen, 'distinct original raw evidence') + seen.add(item['path']); F.uint(item['bytes']); F.digest(item['sha256']) + need(type(item['mode']) is int and item['mode'] in (0o444, 0o600), 'raw evidence custody mode') + clock = document('clock_pin', ('schema', 'clock_domain_sha256', 'target_start_sha256', + 'closer_start_sha256', 'target_end_ns', 'closer_begin_ns'), 'complete-close-clock-lineage-v1') + F.digest(clock['clock_domain_sha256']); F.uint(clock['closer_begin_ns']) + path = binding['closer_start_clock_path'] + need(type(path) is list and 1 <= len(path) <= 8 and all(type(x) is str for x in path), 'own original clock selector') + own_begin = F.select(original_own_start, path); F.uint(own_begin) + need(clock['target_start_sha256'] == closure['start_pin']['sha256'] and + clock['closer_start_sha256'] == own_provenance['original_start_pin']['sha256'] and + type(clock['target_end_ns']) is int and clock['target_end_ns'] == end and + clock['closer_begin_ns'] == own_begin and end <= own_begin, 'original terminal before own closer') + review = F.decode(review_raw) + exact(review, ('schema', 'decision', 'receipt_projection_sha256', 'evidence_binding_sha256')) + projection = dict(receipt); del projection['independent_outcome_review_sha256'] + need(review['schema'] == 'complete-close-independent-review-v1' and + review['decision'] == 'ACCEPT_COMPLETE_OUTCOME' and + review['receipt_projection_sha256'] == digest(canonical(projection)) and + review['evidence_binding_sha256'] == digest(canonical(binding)) and + receipt['independent_outcome_review_sha256'] == digest(review_raw), 'acyclic exact accepted review binding') + policy = documents['policy'] + need(receipt['administrative_debit_ns'] == F.uint(policy['administrative_debit_ns']) and + type(receipt['administrative_debit_ns']) is int, 'exact target policy fee') + # Actual overrun numbers remain untouched. Funding decides future eligibility. + # No fit boolean is issued here. Even an original PASS over reservation/RSS + # remains recordable verbatim; original assess_round retains its blockers. + need(type(current['sequence']) is int and current['sequence'] < 2 * F.MAX_ENTRIES, 'prospective generation cap') + rp = {'path': str(DOMAIN / request['label'] / 'receipt.json'), 'bytes': len(receipt_raw), + 'sha256': digest(receipt_raw), 'mode': 0o600}; F.pin(rp) + new = F.decode(raw_reg); new['predecessor_sha256'] = digest(raw_reg) + new['events'].append({'kind': 'CLOSE', 'label': request['label'], 'pin': rp}) + new_raw = canonical(new); F.registry(new_raw); F.require_append_only(raw_reg, new_raw) + sequence = current['sequence'] + 1 + reg_pin = {'path': str(CONTROL / ('REGISTRY-%06d.json' % sequence)), 'bytes': len(new_raw), + 'sha256': digest(new_raw), 'mode': 0o444}; F.pin(reg_pin) + next_head = {'schema': 'fresh-active-head-v1', 'sequence': sequence, + 'registry_pin': reg_pin, 'previous_head_sha256': digest(raw_head)} + next_raw = canonical(next_head) + need(0 < len(receipt_raw) <= F.META_CAP and 0 < len(new_raw) <= F.META_CAP and + 0 < len(next_raw) <= F.META_CAP, 'all prospective images bounded before publication') + return receipt, rp, new, new_raw, next_raw + + +def bind_api(controller, funding, *, role, expected_head_pin=None, + approved_handoff_pin=None, approved_closure=None, approved_opening=None, approved_manual_entry=None, guardian=None, approved_complete_closure=None): + """Called ONLY by the separately authenticated source-private parent role. + + Exact module/source/loaded-instance authentication is an external bootstrap + premise. Merely constructing ModuleType/FunctionType is not authentication. + approved_* are pinned permission/evidence DATA chosen by that trusted role; + they never create ownership. Every returned context first acquires its own + actual EX. No factory/caller/native command is authorized by this file. + """ + need(type(controller) is ModuleType and type(funding) is ModuleType, 'actual selected module objects') + need(type(role) is str and role in ('PUBLISHER', 'CONTROLLER', 'CLOSER'), 'fixed caller role') + C, F = controller, funding + cg, fg = module_namespace(C), module_namespace(F) + IOType, LeaseType, io = cg['OwnedIO'], cg['GlobalLease'], cg['IO'] + io_image, io_functions = class_image(IOType, ('__init__', 'acquire', 'close', 'read', 'names', 'write'), cg) + lease_image, lease_functions = class_image(LeaseType, ('__init__', 'acquire', 'verify', 'close'), cg) + instance_state(io, IOType, io_image, io_functions, cg, {'slots'}) + lock_reference, domain_reference, control_reference = cg['HISTORICAL_LOCK'], fg['DOMAIN'], fg['CONTROL'] + need(type(lock_reference) is type(LOCK) and lock_reference == LOCK and + type(domain_reference) is type(DOMAIN) and domain_reference == DOMAIN and + type(control_reference) is type(CONTROL) and control_reference == CONTROL, + 'actual original canonical lock/domain values') + first_state, secondary_state, unknown_state = cg['FIRST'], cg['SECONDARY'], cg['IO_UNKNOWN'] + need(type(first_state) is list and len(first_state) == 1 and type(secondary_state) is list and + len(secondary_state) == 256 and type(unknown_state) is list and len(unknown_state) == 1 and + type(unknown_state[0]) is bool, 'actual original error/uncertainty containers') + remember_image = function_image(cg['remember'], cg) + remember_original = remember_image[0] + continuation_image = function_image(cg['joined_continuation_check'], cg) + funding_names = ('snapshot_round', 'assess_round', 'registry', 'require_append_only', + 'read_opening', 'opening_evidence', 'validate_opening_binding', 'require_opening_append', + 'validate_opening_partition', 'validate_pre_entry_provenance', 'metadata_decode', 'select', + 'read_pinned', 'plain', 'decode', 'pin', 'uint', 'exact', 'digest') + funding_images = {name: function_image(fg[name], fg) for name in funding_names} + active_globals = globals() # Actual source-private A module; bootstrap authentication remains external. + # Fixed authenticated loader supplies actual source-private G, never DATA. + guardian_module, guardian_channel, guardian_namespace, guardian_image = None, None, None, None + if guardian is not None: + need(type(guardian) is tuple and len(guardian) == 2, 'actual fixed G association pair') + guardian_module, guardian_channel = guardian + guardian_namespace = module_namespace(guardian_module) + guardian_image = function_image(guardian_namespace['verify_association'], guardian_namespace) + guardian_globals = dict(guardian_namespace) if guardian_namespace is not None else None + guardian_class = guardian_namespace['GuardianChannel'] if guardian_namespace is not None else None + guardian_class_image = dict(type.__getattribute__(guardian_class, '__dict__')) if guardian_class is not None else None + guardian_function_images = [function_image(fn, guardian_namespace) for fn in guardian_class_image.values() + if type(fn) is FunctionType] if guardian_class_image is not None else [] + if guardian_class_image is not None: + for member in guardian_class_image.values(): + if type(member) is property: + guardian_function_images.extend(function_image(fn, guardian_namespace) + for fn in (member.fget,member.fset,member.fdel) if fn is not None) + need(guardian_image is not None or role == 'CLOSER', 'production owner requires actual G channel') + + def guard(record, phase): + if role == 'CLOSER': + return None # Separately funded metadata-only STOP/UNKNOWN; no G clearing. + need(guardian_image is not None, 'no source-private G association') + unchanged_function(guardian_image, guardian_namespace) + need(set(guardian_namespace) == set(guardian_globals) and + all(guardian_namespace[k] is guardian_globals[k] for k in guardian_globals), + 'actual G source globals unchanged') + native_class = type.__getattribute__(guardian_class, '__dict__') + need(set(native_class) == set(guardian_class_image) and + all(native_class[k] is guardian_class_image[k] for k in guardian_class_image), + 'actual G class/method/descriptor identities unchanged') + for image in guardian_function_images: + unchanged_function(image, guardian_namespace) + selected_request = record.get('request') or (manual['request'] if manual is not None else None) + selected_start = (record.get('manual_provenance') or + (manual['provenance'] if manual is not None else None)) + need(selected_request is not None and selected_start is not None, + 'immutable original manual request and GSTART before protected work') + return guardian_image[0](guardian_channel, role, selected_request, + selected_start['original_start_pin'], phase) + + def failure_state_valid(): + keys = tuple(dict.__iter__(cg)) + if not all(type(k) is str for k in keys): + return False + if not (cg.get('FIRST') is first_state and cg.get('SECONDARY') is secondary_state and + cg.get('IO_UNKNOWN') is unknown_state and cg.get('remember') is remember_original): + return False + if not (type(first_state) is list and len(first_state) == 1 and + type(secondary_state) is list and len(secondary_state) == 256 and + type(unknown_state) is list and len(unknown_state) == 1 and type(unknown_state[0]) is bool): + return False + return (first_state[0] is None or exception_instance(first_state[0])) and all( + e is None or exception_instance(e) for e in secondary_state) + + def io_state(allow_uncertain=False): + values = instance_state(io, IOType, io_image, io_functions, cg, {'slots'}) + slots = values['slots'] + need(type(slots) is list and len(slots) == 16, 'fixed original IO slots') + for item in slots: + need(type(item) is list and len(item) == 3 and type(item[1]) is str, + 'exact IO slot structure before field use') + need(item[1] in ('FREE', 'CLOSED', 'OWNED', 'PENDING', 'CLOSING'), 'original IO slot phase') + need(item[2] is None or type(item[2]) is bool, 'original IO directory flag') + if item[1] == 'FREE': + need(item[0] is None and item[2] is None, 'original free slot') + elif item[1] == 'OWNED' and not allow_uncertain: + # Owned scandir iterators exist only INSIDE the unchanged original + # names call. At these nonreentrant source-private entry points, + # only known ordinary OS descriptor slots may persist. + need(item[2] is False and type(item[0]) is int and item[0] >= 0, 'known owned OS descriptor') + elif item[1] in ('PENDING', 'CLOSING'): + need(allow_uncertain, 'uncertain IO blocks fresh dispatch') + return values + + def lease_state(held, fields=None): + wanted = {'fd', 'phase', 'birth', 'lock_info'} if fields is None else fields + values = instance_state(held, LeaseType, lease_image, lease_functions, cg, wanted) + if not wanted: + return values + need(type(values['phase']) is str and values['phase'] in + ('NEW', 'OPEN_PENDING', 'OPEN_RETURNED', 'EX_HELD', 'CLOSE_ENTERED', 'CLOSE_RETURNED', 'CLOSE_UNKNOWN'), + 'exact original lease phase before equality/dispatch') + need(values['fd'] is None or (type(values['fd']) is int and values['fd'] >= 0), 'exact owned descriptor field') + birth = values['birth'] + if birth is not None: + need(type(birth) is dict, 'actual process metadata dictionary') + keys = tuple(dict.__iter__(birth)) + need(all(type(k) is str for k in keys) and set(keys) == + {'pid', 'ppid', 'pgid', 'sid', 'start_ticks', 'rss_bytes'}, 'actual process metadata keys') + need(all(type(birth[k]) is int and birth[k] >= 0 for k in keys), 'actual process metadata exact ints') + bounded_kernel_data(values['lock_info']) + return values + + def kernel_integrity(held=None, *, allow_uncertain=False): + need(module_namespace(C) is cg and module_namespace(F) is fg and + cg.get('IO') is io and cg.get('OwnedIO') is IOType and cg.get('GlobalLease') is LeaseType and + cg.get('HISTORICAL_LOCK') is lock_reference and fg.get('DOMAIN') is domain_reference and + fg.get('CONTROL') is control_reference, 'same actual selected kernel objects') + unchanged_class(IOType, io_image, io_functions, cg) + unchanged_class(LeaseType, lease_image, lease_functions, cg) + unchanged_function(remember_image, cg) + need(failure_state_valid(), 'original error/uncertainty memory integrity') + for name, image in funding_images.items(): + need(fg.get(name) is image[0], 'same selected funding function') + unchanged_function(image, fg) + values = io_state(allow_uncertain) + if held is not None: + lease_state(held) + return values + + complete_validator = complete_close_data + complete_validator_image = function_image(complete_validator, active_globals) + + # No kernel instance/native method has been invoked before these snapshots. + kernel_integrity() + for value in (expected_head_pin, approved_handoff_pin, approved_closure, approved_opening, approved_manual_entry): + F.plain(value) + if approved_complete_closure is not None: + need(role == 'CLOSER' and approved_closure is None, 'one selected closer branch') + F.plain(approved_complete_closure) + F.exact(approved_complete_closure, ('request', 'start', 'start_pin', 'baseline_registry_pin', + 'receipt_pin', 'review_pin', 'evidence_binding')) + F.exact(approved_complete_closure['evidence_binding'], ('schema', 'admission_pin', + 'source_manifest_pin', 'profile_pin', 'result_contract_pin', 'evidence_manifest_pin', + 'clock_pin', 'expected_head_pin', 'closer_start_clock_path')) + need(approved_complete_closure['evidence_binding']['schema'] == 'complete-close-evidence-binding-v1', + 'complete closure selected version before native acquisition') + for key in ('start_pin', 'baseline_registry_pin', 'receipt_pin', 'review_pin'): + F.pin(approved_complete_closure[key]) + binding = approved_complete_closure['evidence_binding'] + for key in ('admission_pin', 'source_manifest_pin', 'profile_pin', 'result_contract_pin', + 'evidence_manifest_pin', 'clock_pin', 'expected_head_pin'): + F.pin(binding[key]) + F.exact(approved_complete_closure['request'], ('schema', 'round_id', 'label', + 'command_sha256', 'body_reservation_ns', 'policy_sha256', 'phase_release_sha256')) + F.exact(approved_complete_closure['start'], ('schema', 'round_id', 'label', + 'command_sha256', 'body_reservation_ns', 'policy_sha256', 'pre_entry_provenance')) + complete_closure = F.decode(canonical(approved_complete_closure)) if approved_complete_closure is not None else None + # Copy only strict DATA. No caller retains a mutable permission dictionary. + expected = F.decode(canonical(expected_head_pin)) if expected_head_pin is not None else None + handoff = F.decode(canonical(approved_handoff_pin)) if approved_handoff_pin is not None else None + closure = F.decode(canonical(approved_closure)) if approved_closure is not None else None + opening = F.decode(canonical(approved_opening)) if approved_opening is not None else None + manual = F.decode(canonical(approved_manual_entry)) if approved_manual_entry is not None else None + contexts, opened = {}, [False] + sentinel = object() + + def fail(record, error): + valid = failure_state_valid() + if record['first'] is None: + record['first'] = first_state[0] if valid and first_state[0] is not None else error + if error is not record['first'] and all(error is not e for e in record['secondary']): + if len(record['secondary']) < 32: + record['secondary'].append(error) + else: + record['secondary_saturated'] = True + record['phase'] = 'FAILED_UNCERTAIN_NO_RETRY' + # Never invoke replaced global state while reporting its integrity failure. + # The private first/secondary debt survives even when kernel memory is unsafe. + if valid: + try: + unchanged_function(remember_image, cg) + remember_original(error) + except BaseException as secondary: + if secondary is not record['first'] and len(record['secondary']) < 32: + record['secondary'].append(secondary) + else: + record['secondary_saturated'] = True + else: + record['kernel_memory_uncertain'] = True + return record['first'] + + def rec(ctx): + need(type(ctx) is Context, 'actual private context type before hashing') + unchanged_class(Context, context_image, context_functions, active_globals) + need(ctx in contexts, 'actual private context only') + return contexts[ctx] + + def verify(record, *, allow_original_failure=False): + need(record['phase'] not in ('FAILED_UNCERTAIN_NO_RETRY', 'RELEASED', 'CLOSE_UNKNOWN'), 'live private owner phase') + kernel_integrity(record['lease']) + need(unknown_state[0] is False and (first_state[0] is None or allow_original_failure is True), + 'no uncertain IO; prior original error only through source-owned cleanup/retention transition') + need(record['pid'] == os.getpid(), 'same actual process/context; no fork or DATA restoration') + values = lease_state(record['lease']) + need(values['fd'] is record['owned_fd'], 'same captured actual native descriptor field') + observation = lease_image['verify'](record['lease']) # Original real native verification. + kernel_integrity(record['lease']) + need(observation['parent']['start_ticks'] == record['birth']['start_ticks'] and + observation['parent']['pid'] == record['birth']['pid'], 'native generation unchanged') + return observation + + def close_actual(record): + need(record['lease_close_entered'] is False, 'one actual lease close; never replay a numeric FD') + record['lease_close_entered'] = True + if record['lease'] is None or record['lease_acquire_entered'] is False: + return # Original pure initializer never acquired any native descriptor. + kernel_integrity(record['lease'], allow_uncertain=True) + values = lease_state(record['lease']) + need(values['phase'] not in ('CLOSE_ENTERED', 'CLOSE_RETURNED', 'CLOSE_UNKNOWN'), + 'original source lease was already closed/uncertain; no repeated FD close') + if record['owned_fd'] is not None: + need(values['fd'] is record['owned_fd'], 'no replaced native descriptor on cleanup') + lease_image['close'](record['lease']) + + def guarded_io(name, *args, **kwargs): + cleanup = name == 'close' + kernel_integrity(allow_uncertain=cleanup) + for record in contexts.values(): + if record['lease'] is not None and record['lease_initialized']: + lease_state(record['lease']) + if cleanup: + slot = args[0] + slots = io_state(True)['slots'] + need(any(slot is item for item in slots) and type(slot) is list and len(slot) == 3 and + type(slot[1]) is str and slot[1] == 'OWNED' and slot[2] is False and + type(slot[0]) is int and slot[0] >= 0, 'actual ordinary owned IO slot before close') + return io_image[name](io, *args, **kwargs) + + def funding_io(name, *args): + kernel_integrity() + for record in contexts.values(): + if record['lease'] is not None and record['lease_initialized']: + lease_state(record['lease']) + # SAME real IO object, not a proxy or callback. Original internal self calls + # are covered by selected single-thread/nonreentrant private stability. + return funding_images[name][0](io, *args) + + def directory(path, *, private=True): + need(path.is_absolute() and path.resolve(strict=True) == path, 'canonical selected directory') + st = path.lstat() + need(stat.S_ISDIR(st.st_mode) and st.st_uid == os.getuid() and + ((stat.S_IMODE(st.st_mode) == 0o700) if private else not stat.S_IMODE(st.st_mode) & 0o022), + 'owned selected directory mode') + return (st.st_dev, st.st_ino, st.st_mode, st.st_uid, st.st_mtime_ns, st.st_ctime_ns) + + def sync_dir(record, path): + directory(path, private=path not in (CONTROL, DOMAIN.parent.parent)) + slot = guarded_io('acquire', path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC) + primary = None + try: + os.fsync(slot[0]) + except BaseException as e: + primary = fail(record, e) + finally: + if slot[1] == 'OWNED': + try: + guarded_io('close', slot) + except BaseException as e: + primary = fail(record, e) + if primary is not None: + raise primary + + def pinned(path, raw, mode): + return {'path': str(path), 'bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest(), 'mode': mode} + + def read(record, p): + verify(record) + return funding_io('read_pinned', p, os.getuid())[1] + + def stage_empty(): + directory(STAGE) + need(guarded_io('names', STAGE, 2) == [], 'no pending/orphan staging file; no cleanup by guessed name') + + def publish(record, path, raw, mode, *, replace_head=False): + verify(record); stage_empty() + need(type(raw) is bytes and 0 < len(raw) <= F.META_CAP and mode in (0o444, 0o600), 'bounded publication') + directory(path.parent, private=path.parent != CONTROL) + record['publication'] = {'path': path, 'slot': None, 'temporary': None, 'phase': 'BEFORE_CREATE'} + tmp = STAGE / ('pending-' + record['role'] + '-' + path.name) + record['publication']['temporary'] = tmp # Private identity exists BEFORE fallible open. + record['publication']['phase'] = 'OPEN_PENDING' + slot = guarded_io('acquire', tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC) + record['publication']['slot'] = slot + primary = None + try: + record['publication']['phase'] = 'WRITING' + offset = 0 + while offset < len(raw): + n = os.write(slot[0], raw[offset:offset + 65536]) + need(type(n) is int and 0 < n <= min(65536, len(raw) - offset), 'progressing exact write') + offset += n + os.fchmod(slot[0], mode) + os.fsync(slot[0]) + except BaseException as e: + primary = fail(record, e) + finally: + if slot[1] == 'OWNED': + try: + guarded_io('close', slot) + except BaseException as e: + primary = fail(record, e) + if primary is not None: + raise primary + # Keep all partial/failed artifacts; there is no automatic unlink/retry catch. + need(read(record, pinned(tmp, raw, mode)) == raw, 'complete staged readback') + sync_dir(record, STAGE) + record['publication']['phase'] = 'COMMIT_PENDING' + if replace_head: + need(path == HEAD, 'only exact HEAD is replaceable') + os.replace(tmp, path) + else: + os.link(tmp, path, follow_symlinks=False) # Atomic no-overwrite publication. + sync_dir(record, path.parent) + os.unlink(tmp) # Only the actual known-created, closed staged file. + sync_dir(record, STAGE) + sync_dir(record, path.parent) + result = pinned(path, raw, mode) + need(read(record, result) == raw, 'final publication/custody readback') + stage_empty() + record['publication']['phase'] = 'COMMITTED' + return result + + def head(record, pin_expected): + verify(record); stage_empty(); directory(HEADS); F.pin(pin_expected) + need(pin_expected['path'] == str(HEAD) and pin_expected['mode'] == 0o600, 'exact current HEAD pin') + raw = read(record, pin_expected); obj = F.decode(raw) + F.exact(obj, ('schema', 'sequence', 'registry_pin', 'previous_head_sha256')) + need(obj['schema'] == 'fresh-active-head-v1' and type(obj['sequence']) is int and + 0 <= obj['sequence'] <= 2 * F.MAX_ENTRIES, 'bounded head generation') + seq = obj['sequence']; F.pin(obj['registry_pin']) + need(obj['registry_pin']['path'] == str(CONTROL / ('REGISTRY-%06d.json' % seq)), 'head registry generation') + expected_heads = {'HEAD-%06d.json' % n for n in range(seq + 1)} + need(set(guarded_io('names', HEADS, 2 * F.MAX_ENTRIES + 2)) == expected_heads, 'exact head history census') + need(read(record, pinned(HEADS / ('HEAD-%06d.json' % seq), raw, 0o600)) == raw, 'current immutable head history') + names = guarded_io('names', CONTROL, 1024) + need({n for n in names if n.startswith('REGISTRY-')} == + {'REGISTRY-%06d.json' % n for n in range(seq + 1)}, 'no unadopted registry generation') + reg_raw = read(record, obj['registry_pin']); F.registry(reg_raw) + return obj, raw, reg_raw + + def advance(record, current, current_raw, old_registry_raw, new_registry, opening_transition=None): + verify(record); stage_empty() + F.plain(new_registry); new_raw = canonical(new_registry) + F.require_append_only(old_registry_raw, new_raw, opening_transition) + seq = current['sequence'] + 1 + need(seq <= 2 * F.MAX_ENTRIES, 'registry generation cap') + registry_pin = publish(record, CONTROL / ('REGISTRY-%06d.json' % seq), new_raw, 0o444) + next_head = {'schema': 'fresh-active-head-v1', 'sequence': seq, + 'registry_pin': registry_pin, 'previous_head_sha256': hashlib.sha256(current_raw).hexdigest()} + raw = canonical(next_head) + publish(record, HEADS / ('HEAD-%06d.json' % seq), raw, 0o600) + need(read(record, record['head_pin']) == current_raw, 'no stale head adoption') + record['head_pin'] = publish(record, HEAD, raw, 0o600, replace_head=True) + adopted, adopted_raw, adopted_registry = head(record, record['head_pin']) + need(adopted_raw == raw and adopted_registry == new_raw, 'durable exact head adopted') + return adopted, adopted_raw, adopted_registry + + def current_registry_pin(record): + current, _, _ = head(record, record['head_pin']) + return current['registry_pin'] + + def active_view(record): + verify(record) + guard(record, 'ACTIVE') + need(record['phase'] == 'ACTIVE' and record['request'] is not None, 'actual ACTIVE reservation') + current, current_raw, reg_raw = head(record, record['head_pin']) + snap = funding_io('snapshot_round', current['registry_pin'], os.getuid()) + old_raw = read(record, record['baseline_registry_pin']) + old, _, old_starts, old_closes = F.registry(old_raw) + reg, _, starts, closes = F.registry(reg_raw) + name = record['request']['label'] + F.require_append_only(old_raw, reg_raw) + need(reg['events'] == old['events'] + [{'kind': 'REGISTER', 'label': name, 'pin': record['start_pin']}] and + reg['policies'] == old['policies'] and reg['phase'] == old['phase'] and + set(old_starts) == set(old_closes) and set(starts) - set(closes) == {name}, + 'exact own pending reservation only; every other entry closed') + need(snap['records'][name]['receipt'] is None and + snap['records'][name]['start'] == record['start'], 'actual current START/source reservation') + # A separately checked accounting prefix, NOT a filtered current ledger. + # Own reservation remains in request and the current registry stays pending. + prefix = dict(snap, registry=old, registry_pin=record['baseline_registry_pin'], + records={k: snap['records'][k] for k in old_starts}) + result = F.assess_round(prefix, record['request']) + need(result['funding_data_eligible_only'] is True, 'prior debt/uncertainty or own reservation blocks') + return result + + def read_manual(record, expected_state_sha256=None): + verify(record) + guard(record, 'MANUAL') + need(manual is not None, 'same enclosing native operation original manual pre-entry binding is unconfigured') + F.exact(manual, ('schema', 'request', 'provenance', 'closed_state_pin', 'registration_checks', 'start_checks')) + need(manual['schema'] == 'fresh-active-manual-entry-binding-v1', 'selected original manual entry binding') + request, provenance = manual['request'], manual['provenance'] + F.validate_pre_entry_provenance(provenance, request['label'], request['command_sha256'], request['body_reservation_ns']) + state_raw = read(record, manual['closed_state_pin']) + F.metadata_decode(state_raw) # Current manually retained accepted-state DATA, not an owner. + if expected_state_sha256 is not None: + need(manual['closed_state_pin']['sha256'] == expected_state_sha256, 'all closed manual costs imported before new formal entry') + registration = F.metadata_decode(read(record, provenance['registration_pin'])) + original_start = F.metadata_decode(read(record, provenance['original_start_pin'])) + pending = F.metadata_decode(read(record, provenance['pending_manifest_pin'])) + F.exact(pending, ('schema', 'closed_state_sha256', 'operations')) + wanted = {'entry_id': request['label'], 'command_sha256': request['command_sha256'], + 'body_reservation_ns': request['body_reservation_ns'], + 'registration_pin': provenance['registration_pin'], 'original_start_pin': provenance['original_start_pin']} + need(pending['schema'] == 'fresh-current-manual-pending-v1' and + pending['closed_state_sha256'] == manual['closed_state_pin']['sha256'] and + pending['operations'] == [wanted], 'exact strongly-bound current enclosing pending operation only') + need(registration['attempt_id'] == request['label'], 'original one-use ID, never a new alias') + for document, checks in ((registration, manual['registration_checks']), (original_start, manual['start_checks'])): + need(type(checks) is list and 1 <= len(checks) <= 16, 'explicit original pre-entry field correlations') + for check in checks: + F.exact(check, ('path', 'expected')) + actual = F.select(document, check['path']) + need(type(actual) is type(check['expected']) and actual == check['expected'], 'original pre-entry provenance differs') + record['manual_request'] = F.decode(canonical(request)) + record['manual_provenance'] = F.decode(canonical(provenance)) + return record['manual_provenance'] + + def complete_failure(record, error): + # Protect raw identity before the inherited optional reporting path. + slots = record['complete_errors'] + if slots[0] is None: + slots[0] = record['first'] if record['first'] is not None else error + # First protect the caught error, then preserve any established actual + # kernel primary. Malformed kernel memory never becomes new authority. + try: + if (record['first'] is None and dict.get(cg, 'FIRST') is first_state and + type(first_state) is list and len(first_state) == 1 and + first_state[0] is not None and exception_instance(first_state[0])): + slots[0] = first_state[0] + except BaseException as inspection_error: + slots[record['complete_error_count']] = inspection_error + record['complete_error_count'] += 1 + record['first'] = slots[0] + record['phase'] = 'FAILED_UNCERTAIN_NO_RETRY' + if error is not slots[0] and all(error is not x for x in slots): + index = record['complete_error_count'] + if index < len(slots): + slots[index] = error; record['complete_error_count'] = index + 1 + else: + record['secondary_saturated'] = True + try: + fail(record, error) + except BaseException as reporting_error: + index = record['complete_error_count'] + if reporting_error is not slots[0] and all(reporting_error is not x for x in slots) and index < len(slots): + slots[index] = reporting_error; record['complete_error_count'] = index + 1 + return slots[0] + + def publish_complete(record): + try: + verify(record) + need(role == 'CLOSER' and record['phase'] == 'HELD' and + record['complete_used'] is False, 'one actual complete-close selection') + record['complete_used'] = True # Consumed before first fallible evidence read. + unchanged_function(complete_validator_image, active_globals) + need(active_globals.get('complete_close_data') is complete_validator, 'fixed selected validator') + read_manual(record) + own_request = F.decode(canonical(record['manual_request'])) + own_provenance = F.decode(canonical(record['manual_provenance'])) + record['complete_own_request'] = own_request + record['complete_own_provenance'] = own_provenance + own_start = F.metadata_decode(read(record, own_provenance['original_start_pin'])) + for key in ('request', 'start', 'start_pin', 'baseline_registry_pin'): + record[key] = complete_closure[key] + record['phase'] = 'ACTIVE'; active_view(record) + binding = complete_closure['evidence_binding'] + F.pin(complete_closure['receipt_pin']); F.pin(complete_closure['review_pin']) + need(Path(complete_closure['receipt_pin']['path']).parent == CONTROL and + Path(complete_closure['review_pin']['path']).is_relative_to(R / 'review') and + complete_closure['receipt_pin']['mode'] == complete_closure['review_pin']['mode'] == 0o444, + 'complete selected frozen receipt/review namespace') + need(binding['expected_head_pin'] == record['head_pin'], 'exact selected current HEAD') + review_raw = read(record, complete_closure['review_pin']) + receipt_raw = read(record, complete_closure['receipt_pin']) + documents = {} + for name in ('admission_pin', 'source_manifest_pin', 'profile_pin', 'result_contract_pin', + 'evidence_manifest_pin', 'clock_pin'): + F.pin(binding[name]); need(binding[name]['mode'] == 0o444, 'frozen accepted metadata') + documents[name] = read(record, binding[name]) + snapshot = funding_io('snapshot_round', current_registry_pin(record), os.getuid()) + documents['policy'] = snapshot['policies'][record['request']['policy_sha256']] + current, raw_head, raw_reg = head(record, record['head_pin']) + receipt, rp, new, new_raw, next_raw = complete_validator(F, complete_closure, + receipt_raw, review_raw, documents, own_request, own_provenance, own_start, + current, raw_head, raw_reg) + now = time.monotonic_ns() + need(type(now) is int and now >= record['protocol_anchor_ns'] and + now - record['protocol_anchor_ns'] <= own_request['body_reservation_ns'], + 'own closer local window, never target reservation; complete meter remains external') + # Recheck real currentness before the first publication. Existing EX + # and registered-writer exclusion cover the following publication. + checked, checked_head, checked_reg = head(record, record['head_pin']) + need(checked == current and checked_head == raw_head and checked_reg == raw_reg, + 'unchanged prevalidated publication generation') + record['phase'] = 'RECEIPT_PUBLICATION_PENDING' + actual = publish(record, DOMAIN / record['request']['label'] / 'receipt.json', receipt_raw, 0o600) + need(actual == rp, 'unchanged original receipt bytes and destination') + adopted, adopted_head, adopted_reg = advance(record, current, raw_head, raw_reg, new) + need(adopted_head == next_raw and adopted_reg == new_raw, 'exact prevalidated durable CLOSE readback') + record['phase'] = 'RECORDED_NOT_PHYSICALLY_SETTLED' + return {'receipt_pin': actual, 'head_pin': record['head_pin'], 'all_costs_settled': False, + 'native_capability': False, 'execution_permission': False} + except BaseException as error: + raise complete_failure(record, error) + + class Context: + __slots__ = () + def __new__(cls, key): + need(key is sentinel, 'source-private construction only') + return object.__new__(cls) + + def initialize(self, initial_registry_raw): + r = rec(self) + try: + verify(r); guard(r, 'INITIALIZE'); need(r['phase'] == 'HELD' and expected is None and role == 'PUBLISHER', 'one initial publisher') + need(opening is not None and opening['funding_source_sha256'] == FUNDING_SHA, 'current selected funding/opening binding') + selected = funding_io('validate_opening_binding', opening, os.getuid()) + read_manual(r, F.opening_evidence(selected)['state_sha256']) + reg, _, starts, closes = F.registry(initial_registry_raw) + need(not starts and not closes and reg['predecessor_sha256'] is None and + reg['opening_pin'] == selected['opening_pin'], 'empty new registry with complete selected current opening') + for p in (DOMAIN.parent, DOMAIN, STAGE, HEADS, HANDOFFS, CLAIMS): + if not p.exists(): + os.mkdir(p, 0o700) + directory(p) + sync_dir(r, p.parent) + need(guarded_io('names', DOMAIN, 2) == [] and guarded_io('names', HEADS, 2) == [] and + not HEAD.exists(), 'no prior/orphan initialization') + stage_empty() + rp = publish(r, CONTROL / 'REGISTRY-000000.json', initial_registry_raw, 0o444) + raw = canonical({'schema': 'fresh-active-head-v1', 'sequence': 0, + 'registry_pin': rp, 'previous_head_sha256': None}) + publish(r, HEADS / 'HEAD-000000.json', raw, 0o600) + r['head_pin'] = publish(r, HEAD, raw, 0o600) + head(r, r['head_pin']) + return F.decode(canonical(r['head_pin'])) + except BaseException as e: + raise fail(r, e) + + def refresh_opening(self): + r = rec(self) + try: + verify(r) + guard(r, 'REFRESH') + need(r['phase'] == 'HELD' and role in ('PUBLISHER', 'CONTROLLER') and opening is not None and + opening['funding_source_sha256'] == FUNDING_SHA, 'new actual owner and fixed approved current opening') + current, raw_head, raw_reg = head(r, r['head_pin']) + old_snapshot = funding_io('snapshot_round', current['registry_pin'], os.getuid()) + _, _, starts, closes = F.registry(raw_reg) + need(set(starts) == set(closes), 'every prior formal entry CLOSED before refresh') + selected = funding_io('validate_opening_binding', opening, os.getuid()) + read_manual(r, F.opening_evidence(selected)['state_sha256']) + need(old_snapshot['opening_snapshot']['opening_pin'] != selected['opening_pin'], 'new immutable closed-cost prefix required') + F.require_opening_append(old_snapshot['opening_snapshot'], selected) + transition = {'previous': old_snapshot['opening_snapshot'], 'current': selected, + 'records': old_snapshot['records']} + new = F.decode(raw_reg); new['predecessor_sha256'] = hashlib.sha256(raw_reg).hexdigest() + new['opening_pin'] = selected['opening_pin'] + advance(r, current, raw_head, raw_reg, new, transition) + refreshed = funding_io('snapshot_round', current_registry_pin(r), os.getuid()) + need(refreshed['opening_snapshot'] == selected and refreshed['records'] == old_snapshot['records'], + 'opening-only refresh readback preserves every prior record/price') + # The prelude is part of this actual enclosing body under its ORIGINAL + # manual pre-entry START. No formal START or cost is backdated. + return {'schema': 'fresh-current-opening-refresh-observation-v1', 'head_pin': r['head_pin'], + 'opening_pin': selected['opening_pin'], 'formal_start_backdated': False, + 'native_capability': False, 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def current_binding(self): + r = rec(self) + try: + active_view(r) + return F.decode(canonical({'schema': 'fresh-active-current-binding-v1', + 'request': r['request'], 'start': r['start'], 'start_pin': r['start_pin'], + 'head_pin': r['head_pin'], 'baseline_registry_pin': r['baseline_registry_pin'], + 'native_capability': False, 'execution_permission': False})) + except BaseException as e: + raise fail(r, e) + + def begin(self, request): + r = rec(self) + try: + verify(r); guard(r, 'HELD'); need(r['phase'] == 'HELD' and role in ('PUBLISHER', 'CONTROLLER'), 'begin once') + F.plain(request) + current, raw_head, raw_reg = head(r, r['head_pin']) + snapshot = funding_io('snapshot_round', current['registry_pin'], os.getuid()) + read_manual(r, F.opening_evidence(snapshot['opening_snapshot'])['state_sha256']) + need(request == r['manual_request'], 'formal entry is the SAME original manually reserved enclosing operation') + assessment = F.assess_round(snapshot, request) + need(assessment['funding_data_eligible_only'] is True, 'NEW admission blocked') + r['request'] = F.decode(canonical(request)); r['baseline_registry_pin'] = current['registry_pin'] + r['phase'] = 'START_PUBLICATION_PENDING' # Private role/request precedes any mkdir/open. + name = r['request']['label']; folder = DOMAIN / name + r['start'] = {'schema': 'fresh-round-start-v1', 'round_id': F.ROUND_ID, + 'label': name, 'command_sha256': request['command_sha256'], + 'body_reservation_ns': request['body_reservation_ns'], 'policy_sha256': request['policy_sha256'], + 'pre_entry_provenance': r['manual_provenance']} + os.mkdir(folder, 0o700); sync_dir(r, DOMAIN) + r['start_pin'] = publish(r, folder / 'START.json', canonical(r['start']), 0o600) + new = F.decode(raw_reg); new['predecessor_sha256'] = hashlib.sha256(raw_reg).hexdigest() + new['events'].append({'kind': 'REGISTER', 'label': name, 'pin': r['start_pin']}) + advance(r, current, raw_head, raw_reg, new) + r['phase'] = 'ACTIVE' + active_view(r) + return {'schema': 'active-registration-observation-v1', 'start_pin': r['start_pin'], + 'head_pin': r['head_pin'], 'native_capability': False, 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def native_lease_for_controller(self, caller_module, actual_registry=None, purpose='PRODUCTION'): + r = rec(self) + try: + need(role == 'CONTROLLER' and caller_module is C and r['phase'] == 'ACTIVE', + 'same authenticated controller module and ACTIVE actual owner') + if actual_registry is None: + need(purpose == 'PRODUCTION', 'no registry-free cleanup/retention exemption') + verify(r) + guard(r, 'ACTIVE') + else: + need(purpose in ('CLEANUP','RETENTION'), 'fixed source-owned continuation purpose') + kernel_integrity(r['lease']) + need(cg.get('joined_continuation_check') is continuation_image[0], + 'actual fixed C2 continuation verifier') + unchanged_function(continuation_image, cg) + # Actual source function, same private registry/ctx, no DATA + # Boolean grants. It proves the known lifecycle before this + # one narrow original-error continuation can exist. + need(continuation_image[0](self, actual_registry, purpose) is True, + 'actual known cleanup/sealed retention continuation absent') + old = r.get('continuation') + need(old is None or (old['registry'] is actual_registry and + (old['first'] is None or old['first'] is first_state[0])), 'same registry and retained actual original failure') + r['continuation'] = {'registry':actual_registry,'purpose':purpose,'first':first_state[0]} + verify(r, allow_original_failure=True) + guard(r, 'RETENTION' if purpose == 'RETENTION' else 'ACTIVE') + return r['lease'] # Same actual original C2 EX/OFD; never serialized to B. + except BaseException as e: + raise fail(r, e) + + def check(self, nested_ns, cleanup_ns): + r = rec(self) + try: + F.uint(nested_ns); F.uint(cleanup_ns) + assessment = active_view(r) + now = time.monotonic_ns() + need(type(now) is int and now >= r['protocol_anchor_ns'], 'actual local monotonic sample') + elapsed = now - r['protocol_anchor_ns'] + need(elapsed + nested_ns + cleanup_ns <= r['request']['body_reservation_ns'], 'retained body reservation locally exhausted') + return {'schema': 'active-local-reservation-observation-v1', 'elapsed_since_protocol_anchor_ns': elapsed, + 'local_reservation_check_passed': True, 'whole_outer_body_fit_proved': False, + 'clock_scope': 'private_protocol_anchor_to_local_sample_imports_and_final_exit_excluded', + 'unallocated_policy_ns': assessment['remaining_policy_ns'] - assessment['requested_reservation_ns'], + 'own_reservation_encumbered_ns': assessment['requested_reservation_ns'], 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def release_for_exec(self): + r = rec(self) + try: + active_view(r); need(role == 'PUBLISHER', 'separate publisher owner only') + intent = {'schema': 'fresh-active-handoff-intent-v1', 'source_role': role, 'destination_role': 'CONTROLLER', + 'request': r['request'], 'start': r['start'], 'start_pin': r['start_pin'], + 'head_pin': r['head_pin'], 'baseline_registry_pin': r['baseline_registry_pin'], + 'protocol_anchor_ns': r['protocol_anchor_ns'], 'native_capability_transferred': False} + r['phase'] = 'HANDOFF_PUBLICATION_PENDING' + p = publish(r, HANDOFFS / (r['request']['label'] + '.json'), canonical(intent), 0o444) + verify(r); r['phase'] = 'CLOSE_ENTERED'; close_actual(r); r['phase'] = 'RELEASED' + return p # Permission/timing DATA only. No FD/owner survives this API. + except BaseException as e: + raise fail(r, e) + + def adopt_handoff(self): + r = rec(self) + try: + verify(r); guard(r, 'ADOPT'); need(role == 'CONTROLLER' and r['phase'] == 'HELD' and handoff is not None, 'fresh actual controller owner plus approved intent') + intent = F.decode(read(r, handoff)) + F.exact(intent, ('schema', 'source_role', 'destination_role', 'request', 'start', 'start_pin', + 'head_pin', 'baseline_registry_pin', 'protocol_anchor_ns', 'native_capability_transferred')) + need(intent['schema'] == 'fresh-active-handoff-intent-v1' and intent['source_role'] == 'PUBLISHER' and + intent['destination_role'] == role and intent['native_capability_transferred'] is False and + intent['head_pin'] == r['head_pin'], 'exact data intent/current head') + for k in ('request', 'start', 'start_pin', 'baseline_registry_pin'): + r[k] = intent[k] + F.uint(intent['protocol_anchor_ns']) + # Cross-process clock-domain applicability is an external role-profile premise. + r['protocol_anchor_ns'] = intent['protocol_anchor_ns'] + r['phase'] = 'ACTIVE' + selected_head = current_registry_pin(r) + selected_snapshot = funding_io('snapshot_round', selected_head, os.getuid()) + read_manual(r, F.opening_evidence(selected_snapshot['opening_snapshot'])['state_sha256']) + need(r['request'] == r['manual_request'] and r['start']['pre_entry_provenance'] == r['manual_provenance'], + 'handoff is same original enclosing operation') + active_view(r) + claim = {'schema': 'fresh-active-handoff-claim-v1', 'handoff_sha256': handoff['sha256'], + 'start_sha256': r['start_pin']['sha256'], 'native_owner_is_not_this_record': True} + publish(r, CLAIMS / (r['request']['label'] + '.json'), canonical(claim), 0o444) + return {'handoff_claimed': True, 'new_real_lease_acquired': True, 'native_capability': False, 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def publish_reviewed_close(self): + r = rec(self) + if complete_closure is not None: + return publish_complete(r) + try: + verify(r); need(role == 'CLOSER' and r['phase'] == 'HELD' and closure is not None, + 'new actual closer plus independently accepted frozen evidence') + read_manual(r) # The CLOSER has its OWN separately funded native body, never admin-filled. + F.exact(closure, ('request', 'start', 'start_pin', 'baseline_registry_pin', 'receipt_pin', 'review_pin')) + for k in ('request', 'start', 'start_pin', 'baseline_registry_pin'): + r[k] = closure[k] + r['phase'] = 'ACTIVE'; active_view(r) + F.pin(closure['receipt_pin']); F.pin(closure['review_pin']) + need(Path(closure['receipt_pin']['path']).parent == CONTROL and + Path(closure['review_pin']['path']).is_relative_to(R / 'review') and + closure['receipt_pin']['mode'] == closure['review_pin']['mode'] == 0o444, + 'selected frozen close candidate/review namespace') + review_raw = read(r, closure['review_pin']) # Opaque independently accepted evidence, never native authority. + raw = read(r, closure['receipt_pin']); receipt = F.decode(raw) + need(receipt['schema'] == 'fresh-round-receipt-v1' and receipt['round_id'] == F.ROUND_ID and + receipt['label'] == r['request']['label'] and receipt['start_sha256'] == r['start_pin']['sha256'] and + receipt['independent_outcome_review_sha256'] == hashlib.sha256(review_raw).hexdigest(), 'exact reviewed body/uncertainty record') + F.exact(receipt, ('schema', 'round_id', 'label', 'start_sha256', 'outcome', 'body_elapsed_ns', + 'administrative_debit_ns', 'body_begin_ns', 'body_end_ns', 'body_fully_observed', + 'cleanup_known', 'custody_complete', 'nested_entries_complete', 'uncertainty', + 'peak_sampled_rss_bytes', 'tail_state', 'independent_outcome_review_sha256')) + need(receipt['outcome'] == 'STOP' and receipt['cleanup_known'] is False and + receipt['tail_state'] == 'UNKNOWN' and receipt['uncertainty'] is not None, + 'metadata-only CLOSER records STOP/UNKNOWN; native success needs separate source adoption') + need(receipt['outcome'] in ('PASS', 'STOP') and + receipt['tail_state'] in ('COMPLETE', 'ADMIN_ONLY_OPEN', 'UNKNOWN'), 'retained outcome/unknown scope') + for key in ('body_fully_observed', 'cleanup_known', 'custody_complete', 'nested_entries_complete'): + need(type(receipt[key]) is bool, 'exact qualification flag') + if receipt['body_elapsed_ns'] is not None: + F.uint(receipt['body_elapsed_ns']); F.uint(receipt['body_begin_ns']); F.uint(receipt['body_end_ns']) + need(receipt['body_end_ns'] >= receipt['body_begin_ns'] and + receipt['body_end_ns'] - receipt['body_begin_ns'] == receipt['body_elapsed_ns'], 'exact reviewed body interval') + F.uint(receipt['administrative_debit_ns']) + policy_snapshot = funding_io('snapshot_round', current_registry_pin(r), os.getuid()) + policy = policy_snapshot['policies'][r['request']['policy_sha256']] + need(receipt['administrative_debit_ns'] == policy['administrative_debit_ns'], 'separate exact admin policy') + # No field is invented from local check(), PID/FD observations, or caller booleans. + # Genuine whole-body/cleanup/review acceptance is the trusted closer-source premise. + current, raw_head, raw_reg = head(r, r['head_pin']) + r['phase'] = 'RECEIPT_PUBLICATION_PENDING' + rp = publish(r, DOMAIN / r['request']['label'] / 'receipt.json', raw, 0o600) + new = F.decode(raw_reg); new['predecessor_sha256'] = hashlib.sha256(raw_reg).hexdigest() + new['events'].append({'kind': 'CLOSE', 'label': r['request']['label'], 'pin': rp}) + advance(r, current, raw_head, raw_reg, new) + r['phase'] = 'RECORDED_NOT_PHYSICALLY_SETTLED' + return {'receipt_pin': rp, 'head_pin': r['head_pin'], 'all_costs_settled': False, 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def release(self): + r = rec(self) + need(r['phase'] not in ('RELEASED', 'CLOSE_UNKNOWN'), 'one actual close attempt') + try: + r['phase'] = 'CLOSE_ENTERED' + close_actual(r) + r['phase'] = 'RELEASED' + except BaseException as e: + r['phase'] = 'CLOSE_UNKNOWN' + if complete_closure is not None: + primary = complete_failure(r, e) + r['phase'] = 'CLOSE_UNKNOWN' + raise primary + if r['first'] is None: + r['first'] = e + raise r['first'] + + context_image, context_functions = class_image(Context, + ('initialize', 'refresh_opening', 'current_binding', 'begin', 'native_lease_for_controller', + 'check', 'release_for_exec', 'adopt_handoff', 'publish_reviewed_close', 'release'), + active_globals, slotted=True) + + def open_owner(): + need(opened[0] is False, 'one context per exact bound source-role invocation') + opened[0] = True + unchanged_class(Context, context_image, context_functions, active_globals) + ctx = Context(sentinel) + r = {'role': role, 'pid': os.getpid(), 'lease': None, 'birth': None, + 'phase': 'PRIVATE_BEFORE_ACQUIRE', 'first': None, 'secondary': [], 'secondary_saturated': False, + 'request': None, 'head_pin': expected, 'publication': None, + 'protocol_anchor_ns': None, 'lease_close_entered': False, + 'lease_initialized': False, 'lease_acquire_entered': False, 'owned_fd': None, + 'kernel_memory_uncertain': False, 'complete_used': False, + 'complete_errors': [None] * 34, 'complete_error_count': 1, + 'complete_own_request': None, 'complete_own_provenance': None} + contexts[ctx] = r # Private ownership/role identity BEFORE fallible initialization/acquire. + try: + guard(r, 'BOOTSTRAP') + values = kernel_integrity() + need(all(slot[1] in ('FREE', 'CLOSED') for slot in values['slots']), + 'fresh role begins with no borrowed/pending IO slot') + r['protocol_anchor_ns'] = time.monotonic_ns() # Partial local window only. + need(type(r['protocol_anchor_ns']) is int and r['protocol_anchor_ns'] >= 0, 'genuine finite local protocol anchor') + unchanged_class(LeaseType, lease_image, lease_functions, cg) + r['lease'] = object.__new__(LeaseType) # No metaclass/class __call__/foreign __new__ dispatch. + lease_state(r['lease'], fields=set()) + lease_image['__init__'](r['lease']) + r['lease_initialized'] = True + kernel_integrity(r['lease']) + r['phase'] = 'ACQUIRE_PENDING'; r['lease_acquire_entered'] = True + lease_image['acquire'](r['lease']) + kernel_integrity(r['lease']) + acquired = lease_state(r['lease']) + r['owned_fd'] = acquired['fd']; r['birth'] = dict(acquired['birth']) + r['phase'] = 'HELD'; verify(r) + return ctx + except BaseException as e: + fail(r, e) + # Exactly one actual cleanup entry; unsafe metadata remains unknown debt, + # never guessed/replayed descriptor cleanup or a reconstructed owner. + try: + close_actual(r) + except BaseException as close_error: + fail(r, close_error) + raise r['first'] + + return open_owner diff --git a/research/h25-complete-outcome-close/implementation/funding_current.py.txt b/research/h25-complete-outcome-close/implementation/funding_current.py.txt new file mode 100644 index 0000000000..0fc6baf1cf --- /dev/null +++ b/research/h25-complete-outcome-close/implementation/funding_current.py.txt @@ -0,0 +1,660 @@ +"""SOURCE ONLY: fresh-round data ledger; no legacy scan, clock, or native grant. + +Caller must authenticate this code/registry, hold the real selected global EX +lease, exclude competing registered writers, and provide the unchanged owned +IO implementation. Snapshot custody is scoped to those admitted premises. +Every entry is one NONOVERLAPPING OUTER guarded command. Its actual complete +body includes all nested execution/cleanup; nested diagnostics are not added. +This module cannot authenticate native handles or physical cleanup from DATA. +""" +import hashlib +import json +import os +import stat +from pathlib import Path + +W = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453') +R = W / 'outputs/h25-data-handling-20261028' +CONTROL = R / 'control/fresh-metered-round-v1' +DOMAIN = R / 'runtime/fresh-metered-round-v1/attempts' +ROUND_ID = 'fresh-metered-round-v1' +AUTHORIZATION_SHA256 = '28bc04ad98151cf6a52607e4271b4dcbcbd645d0c8c538a35bc37e3d5194d50f' +NS = 1000000000 +BODY_LIMIT_NS = 180 * NS +INITIAL_NS, TOTAL_NS = 600 * NS, 2400 * NS +RSS_LIMIT = 1073741824 +MAX_ENTRIES, META_CAP = 128, 131072 +MAX_VALUE = (1 << 63) - 1 + + +class FundingError(ValueError): + """Stop; preserve evidence. A missing number never becomes a zero receipt.""" + + +def need(condition, message): + if condition is not True: + raise FundingError(message) + + +def plain(value, depth=0): + need(depth <= 16, 'metadata depth cap') + t = type(value) + if t is dict: + need(len(value) <= 2 * MAX_ENTRIES, 'object cap') + for k, v in value.items(): + need(type(k) is str and len(k) <= 128, 'exact string key') + plain(v, depth + 1) + elif t is list: + need(len(value) <= 2 * MAX_ENTRIES, 'array cap') + for v in value: + plain(v, depth + 1) + elif t is str: + need(len(value) <= META_CAP, 'bounded metadata wire/string cap') + elif t is int: + need(0 <= value <= MAX_VALUE, 'bounded exact integer data') + else: + need(value is None or t is bool, 'only exact JSON integer/bool/null data') + + +def exact(value, keys): + need(type(value) is dict and set(value) == set(keys), 'exact object fields') + + +def uint(value): + need(type(value) is int and 0 <= value <= MAX_VALUE, 'bounded exact integer, not bool/float') + return value + + +def digest(value): + need(type(value) is str and len(value) == 64 and all(c in '0123456789abcdef' for c in value), 'sha256') + return value + + +def label(value): + need(type(value) is str and 1 <= len(value) <= 64 and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in value), 'simple label') + return value + + +def pin(value): + plain(value) + exact(value, ('path', 'bytes', 'sha256', 'mode')) + need(type(value['path']) is str and Path(value['path']).is_absolute(), 'absolute pin path') + uint(value['bytes']); digest(value['sha256']) + need(type(value['mode']) is int and value['mode'] in (0o444, 0o600), 'immutable control or private record mode') + need(value['bytes'] <= META_CAP, 'metadata byte cap') + return value + + +def pairs(items): + result = {} + for k, v in items: + need(k not in result, 'duplicate JSON key') + result[k] = v + return result + + +def forbidden_number(unused): + raise FundingError('JSON floating/nonfinite number forbidden') + + +def decode(raw): + need(type(raw) is bytes and 0 < len(raw) <= META_CAP, 'bounded exact bytes') + obj = json.loads(raw.decode('utf-8'), object_pairs_hook=pairs, + parse_float=forbidden_number, parse_constant=forbidden_number) + plain(obj) + return obj + + +def registry(raw): + obj = decode(raw) + exact(obj, ('schema', 'round_id', 'authorization_sha256', 'opening_pin', + 'predecessor_sha256', 'phase', 'phase_release_sha256', 'policies', 'events')) + need(obj['schema'] == 'fresh-round-registry-v2' and obj['round_id'] == ROUND_ID and + obj['authorization_sha256'] == AUTHORIZATION_SHA256, 'selected new round only') + pin(obj['opening_pin']); need(obj['opening_pin']['mode'] == 0o444, 'immutable selected opening') + if obj['predecessor_sha256'] is not None: + digest(obj['predecessor_sha256']) + need(obj['phase'] in ('INITIAL', 'FULL'), 'phase') + need((obj['phase'] == 'INITIAL' and obj['phase_release_sha256'] is None) or + (obj['phase'] == 'FULL' and type(obj['phase_release_sha256']) is str), 'explicit phase release') + if obj['phase'] == 'FULL': + digest(obj['phase_release_sha256']) + need(type(obj['policies']) is list and type(obj['events']) is list, 'bounded arrays') + need(len(obj['events']) <= 2 * MAX_ENTRIES, 'event cap') + policies, starts, closes = {}, {}, {} + for p in obj['policies']: + pin(p) + need(Path(p['path']).parent == CONTROL and p['mode'] == 0o444 and + p['sha256'] not in policies, 'selected distinct policy pin') + policies[p['sha256']] = p + for event in obj['events']: + exact(event, ('kind', 'label', 'pin')) + name = label(event['label']); p = pin(event['pin']) + need(p['mode'] == 0o600, 'private START/receipt') + if event['kind'] == 'REGISTER': + need(name not in starts and len(starts) < MAX_ENTRIES, 'one register, no reused/seed label') + need(p['path'] == str(DOMAIN / name / 'START.json'), 'only new START') + starts[name] = p + elif event['kind'] == 'CLOSE': + need(name in starts and name not in closes, 'close once after register') + need(p['path'] == str(DOMAIN / name / 'receipt.json'), 'only new receipt') + closes[name] = p + else: + raise FundingError('unexpected event') + return obj, policies, starts, closes + + +def require_append_only(previous_raw, current_raw, opening_transition=None): + old, _, _, _ = registry(previous_raw) + new, _, _, _ = registry(current_raw) + need(new['predecessor_sha256'] == hashlib.sha256(previous_raw).hexdigest(), 'genuine prior registry image pin') + need(new['events'][:len(old['events'])] == old['events'] and + new['policies'][:len(old['policies'])] == old['policies'], 'prior rows immutable, never deleted or repriced') + need(old['phase'] == new['phase'] or (old['phase'] == 'INITIAL' and new['phase'] == 'FULL'), 'no phase rollback') + if old['phase'] == new['phase']: + need(old['phase_release_sha256'] == new['phase_release_sha256'], 'phase authority unchanged') + if old['opening_pin'] != new['opening_pin']: + plain(opening_transition) + exact(opening_transition, ('previous', 'current', 'records')) + need(old['events'] == new['events'] and old['policies'] == new['policies'] and + old['phase'] == new['phase'] and old['phase_release_sha256'] == new['phase_release_sha256'], + 'opening-only refresh, preserve events/prices/phase') + _, _, starts, closes = registry(previous_raw) + need(set(starts) == set(closes) == set(opening_transition['records']), 'all formal records CLOSED before refresh') + need(opening_transition['previous']['opening_pin'] == old['opening_pin'] and + opening_transition['current']['opening_pin'] == new['opening_pin'], 'exact old/new opening evidence') + require_opening_append(opening_transition['previous'], opening_transition['current']) + validate_opening_partition(opening_transition['current'], old, opening_transition['records']) + else: + need(opening_transition is None, 'no unrelated transition proof') + return True + + +def directory_identity(io, path, owner_uid): + need(path.is_absolute() and path.resolve(strict=True) == path, 'canonical new directory') + st = path.lstat() + need(stat.S_ISDIR(st.st_mode) and st.st_uid == owner_uid and + stat.S_IMODE(st.st_mode) == 0o700, 'private current-owner directory') + return (st.st_dev, st.st_ino, st.st_mode, st.st_nlink, st.st_uid, + st.st_mtime_ns, st.st_ctime_ns) + + +def read_pinned(io, expected, owner_uid): + pin(expected) + row, raw = io.read(Path(expected['path']), META_CAP, mode=expected['mode'], + expected={'bytes': expected['bytes'], 'sha256': expected['sha256']}, materialize=True) + need(type(raw) is bytes and row['uid'] == owner_uid and row['nlink'] == 1 and + row['mode'] == expected['mode'] and row['bytes'] == expected['bytes'] and + row['sha256'] == expected['sha256'] and len(raw) == expected['bytes'] and + hashlib.sha256(raw).hexdigest() == expected['sha256'], 'actual owned stable file differs') + return row, raw + + +def snapshot_round(io, registry_pin, owner_uid): + """Future actual-IO operation; caller owns native lease, not any JSON flag. + + Failures propagate: do not retry, silently skip entries, or create receipts. + io.names and io.read must be the reviewed actual OwnedIO methods; read must + retain canonical/lstat/open/fstat/post-path and known-close guarantees. + """ + # The caller authenticates exact type(io), original source hash and module + # instance; this function does not turn an arbitrary reader into authority. + # It audits NEW admission only. It grants no in-flight/pending exemption. + uint(owner_uid); plain(registry_pin); pin(registry_pin) + rp = Path(registry_pin['path']) + middle = rp.name[len('REGISTRY-'):-len('.json')] + need(rp.parent == CONTROL and rp.name.startswith('REGISTRY-') and rp.name.endswith('.json') and + len(middle) == 6 and all(c in '0123456789' for c in middle) and + registry_pin['mode'] == 0o444, 'explicit new hash-selected registry file') + seen = [] + def take(p): + row, raw = read_pinned(io, p, owner_uid) + seen.append((p, row, raw)) + return raw + raw_registry = take(registry_pin) + reg, policy_pins, starts, closes = registry(raw_registry) + opening_snapshot = read_opening(io, reg['opening_pin'], owner_uid) + before = directory_identity(io, DOMAIN, owner_uid) + names = io.names(DOMAIN, MAX_ENTRIES + 1) + need(type(names) is list and all(type(n) is str for n in names) and + len(names) == len(set(names)) and set(names) == set(starts), 'every new entry exactly registered') + records, directories = {}, {} + for name in sorted(starts): + folder = DOMAIN / name + identity = directory_identity(io, folder, owner_uid) + members = io.names(folder, 3) + expected_members = {'START.json', 'receipt.json'} if name in closes else {'START.json'} + need(type(members) is list and len(members) == len(set(members)) and + set(members) == expected_members, 'exact new entry completeness; no hidden/missing receipt') + start = decode(take(starts[name])) + receipt = decode(take(closes[name])) if name in closes else None + directories[name] = (identity, expected_members) + records[name] = {'start': start, 'receipt': receipt} + policies = {k: decode(take(p)) for k, p in policy_pins.items()} + for p, row, raw in seen: + after_row, after_raw = read_pinned(io, p, owner_uid) + need(after_raw == raw and after_row == row, 'full pre/post immutable snapshot') + for name, (identity, members) in directories.items(): + need(directory_identity(io, DOMAIN / name, owner_uid) == identity and + set(io.names(DOMAIN / name, 3)) == members, 'new entry directory/census changed') + need(directory_identity(io, DOMAIN, owner_uid) == before and + set(io.names(DOMAIN, MAX_ENTRIES + 1)) == set(names), 'new round census changed') + opening_after = read_opening(io, reg['opening_pin'], owner_uid) + need(opening_after == opening_snapshot, 'whole snapshot opening remains current and unchanged') + validate_opening_partition(opening_snapshot, reg, records) + return {'schema': 'fresh-round-owned-snapshot-v2', 'registry': reg, + 'registry_pin': registry_pin, 'records': records, 'policies': policies, + 'opening_snapshot': opening_snapshot} + + +def assess_round(snapshot, request): + """Pure DATA assessment. Eligibility is NOT permission/native qualification.""" + plain(snapshot); plain(request) + exact(snapshot, ('schema', 'registry', 'registry_pin', 'records', 'policies', + 'opening_snapshot')) + exact(request, ('schema', 'round_id', 'label', 'command_sha256', + 'body_reservation_ns', 'policy_sha256', 'phase_release_sha256')) + need(snapshot['schema'] == 'fresh-round-owned-snapshot-v2' and + request['schema'] == 'fresh-round-request-v1' and request['round_id'] == ROUND_ID, + 'new round data only') + opening = opening_evidence(snapshot['opening_snapshot']) + need(snapshot['opening_snapshot']['opening_pin'] == snapshot['registry']['opening_pin'], 'selected opening snapshot') + reg = snapshot['registry'] + # Revalidate exact registry shape and event semantics for direct DATA callers. + _, policy_pins, starts, closes = registry((json.dumps(reg, separators=(',', ':')) + '\n').encode('utf-8')) + need(set(snapshot['records']) == set(starts) and set(snapshot['policies']) == set(policy_pins), 'snapshot closed domain') + need(request['phase_release_sha256'] == reg['phase_release_sha256'], 'separately authorized phase binding') + cap = INITIAL_NS if reg['phase'] == 'INITIAL' else TOTAL_NS + policies = snapshot['policies'] + for key, p in policies.items(): + exact(p, ('schema', 'round_id', 'command_sha256', 'administrative_debit_ns', + 'scope', 'adoption_sha256', 'claims_physical_upper_bound')) + need(p['schema'] == 'fresh-round-admin-policy-v1' and p['round_id'] == ROUND_ID and + p['scope'] == 'STARTUP_AND_FINAL_METADATA_PUBLICATION_ONLY' and + p['claims_physical_upper_bound'] is False, 'admin convention never body/cleanup cover') + digest(p['command_sha256']); digest(p['adoption_sha256']); uint(p['administrative_debit_ns']) + opening = validate_opening_partition(snapshot['opening_snapshot'], reg, snapshot['records']) + body, admin, reserved, unknown, blockers, commands, open_tails = ( + opening['manual_body_ns'], opening['manual_admin_ns'], 0, [], list(opening['blockers']), + set(opening['manual_command_sha256s']), []) + for name in starts: + bundle = snapshot['records'][name] + exact(bundle, ('start', 'receipt')) + s, r = bundle['start'], bundle['receipt'] + exact(s, ('schema', 'round_id', 'label', 'command_sha256', 'body_reservation_ns', 'policy_sha256', 'pre_entry_provenance')) + validate_pre_entry_provenance(s['pre_entry_provenance'], name, s['command_sha256'], s['body_reservation_ns']) + need(s['schema'] == 'fresh-round-start-v1' and s['round_id'] == ROUND_ID and s['label'] == name, 'START binding') + cmd = digest(s['command_sha256']); digest(s['policy_sha256']) + need(name not in opening['manual_entry_ids'] and cmd not in commands and + s['policy_sha256'] in policies, 'no imported/formal duplicate/reroll or undeclared policy') + commands.add(cmd); p = policies[s['policy_sha256']] + need(p['command_sha256'] == cmd and 0 < uint(s['body_reservation_ns']) <= BODY_LIMIT_NS, 'per-command body reservation') + fee = uint(p['administrative_debit_ns']) + if r is None: + need(name not in closes, 'CLOSE without receipt') + reserved += s['body_reservation_ns'] + fee + unknown.append(name); blockers.append(name + ':MISSING_NEW_RECEIPT') + continue + need(name in closes, 'unregistered new receipt') + exact(r, ('schema', 'round_id', 'label', 'start_sha256', 'outcome', 'body_elapsed_ns', + 'administrative_debit_ns', 'body_begin_ns', 'body_end_ns', 'body_fully_observed', 'cleanup_known', 'custody_complete', + 'nested_entries_complete', 'uncertainty', 'peak_sampled_rss_bytes', 'tail_state', + 'independent_outcome_review_sha256')) + need(r['schema'] == 'fresh-round-receipt-v1' and r['round_id'] == ROUND_ID and + r['label'] == name and r['start_sha256'] == starts[name]['sha256'] and + r['outcome'] in ('PASS', 'STOP') and uint(r['administrative_debit_ns']) == fee, 'receipt identity/fee') + for k in ('body_begin_ns', 'body_end_ns'): + if r[k] is not None: + uint(r[k]) + admin += fee # Failure fees and measured failure bodies are retained in full. + if r['body_elapsed_ns'] is None: + unknown.append(name); blockers.append(name + ':UNPRICED_BODY') + reserved += s['body_reservation_ns'] + else: + elapsed = uint(r['body_elapsed_ns']) + need(type(r['body_begin_ns']) is int and type(r['body_end_ns']) is int and + r['body_end_ns'] >= r['body_begin_ns'] and + r['body_end_ns'] - r['body_begin_ns'] == elapsed, 'exact own body endpoints/difference') + body += elapsed + if elapsed > BODY_LIMIT_NS or elapsed > s['body_reservation_ns']: + blockers.append(name + ':BODY_RESERVATION_OR180_EXCEEDED') + for k in ('body_fully_observed', 'cleanup_known', 'custody_complete', 'nested_entries_complete'): + need(type(r[k]) is bool, 'exact boolean qualification') + if r[k] is not True: + blockers.append(name + ':' + k.upper()) + need(type(r['uncertainty']) is list and all(type(x) is str for x in r['uncertainty']), 'uncertainty list') + if r['uncertainty']: + blockers.append(name + ':UNRESOLVED_UNCERTAINTY') + if r['peak_sampled_rss_bytes'] is None: + blockers.append(name + ':UNKNOWN_SAMPLED_RSS') + elif uint(r['peak_sampled_rss_bytes']) > RSS_LIMIT: + blockers.append(name + ':SAMPLED_RSS_EXCEEDED') + need(r['tail_state'] in ('COMPLETE', 'ADMIN_ONLY_OPEN', 'UNKNOWN'), 'tail state') + if r['tail_state'] == 'UNKNOWN': + blockers.append(name + ':UNKNOWN_NONADMIN_TAIL') + elif r['tail_state'] == 'ADMIN_ONLY_OPEN': + open_tails.append(name) + digest(r['independent_outcome_review_sha256']) + label(request['label']); cmd = digest(request['command_sha256']) + need(request['label'] not in starts and request['label'] not in opening['manual_entry_ids'] and cmd not in commands, 'one use, no automatic retry') + need(request['policy_sha256'] in policies, 'request separately adopted policy absent') + policy = policies[request['policy_sha256']] + need(policy['command_sha256'] == cmd, 'request exact policy/command') + wanted_body = uint(request['body_reservation_ns']) + need(0 < wanted_body <= BODY_LIMIT_NS, 'requested body <=180s; actual fit remains separate') + wanted = wanted_body + policy['administrative_debit_ns'] + charged = body + admin + remaining = cap - charged - reserved # No clipping, no unknown-body zero receipt. + if remaining < wanted: + blockers.append('INSUFFICIENT_POLICY_ALLOWANCE') + return {'schema': 'fresh-round-funding-assessment-v1', 'round_id': ROUND_ID, + 'funding_data_eligible_only': not blockers, 'blockers': blockers, + 'cap_ns': cap, 'known_observed_body_ns': body, 'administrative_policy_ns': admin, + 'known_policy_charged_ns': charged, 'outstanding_reservation_ns': reserved, + 'unpriced_new_entries': unknown, 'remaining_policy_ns': remaining, + 'requested_reservation_ns': wanted, 'new_admin_only_open_tail_entries': open_tails, + 'opening_physical_tail_open': True, 'complete_physical_total_ns': None, + 'old_historical_total_ns': None, 'all_costs_settled': False, + 'native_ownership_or_cleanup_authenticated': False, 'execution_permission': False, + 'command_resource_profile_or_economic_fit_proved': False} + + +# Closed immutable historical DATA. No imported row is a retrospective START. +OPENING_LIMIT = 32 +CORPUS_LIMIT = 2 * 1024 * 1024 +ADMIN_NS = 2 * NS + + +def metadata_decode(raw): + need(type(raw) is bytes and 0 < len(raw) <= META_CAP, 'bounded exact metadata bytes') + # Legacy diagnostic floats are retained as lexical strings, NEVER charges. + value = json.loads(raw.decode('utf-8'), object_pairs_hook=pairs, + parse_float=lambda text: text, parse_constant=forbidden_number) + metadata_plain(value) + return value + + +def metadata_plain(value, depth=0): + need(depth <= 16, 'metadata depth') + t = type(value) + if t is dict: + need(len(value) <= 256, 'metadata object bound') + for k, v in value.items(): + need(type(k) is str and len(k) <= 128, 'metadata key') + metadata_plain(v, depth + 1) + elif t is list: + need(len(value) <= 256, 'metadata array bound') + for v in value: + metadata_plain(v, depth + 1) + elif t is str: + need(len(value) <= META_CAP, 'metadata string bound') + elif t is int: + need(-MAX_VALUE <= value <= MAX_VALUE, 'bounded reported metadata integer') + else: + need(value is None or t is bool, 'exact metadata builtin types') + + +def select(value, path): + need(type(path) is list and 1 <= len(path) <= 8 and all(type(k) is str for k in path), 'literal field path') + for key in path: + need(type(value) is dict and key in value, 'original metadata field absent') + value = value[key] + return value + + +def seconds_ns(value): + need(type(value) is str and value.count('.') <= 1, 'canonical decimal seconds string') + parts = value.split('.') + whole = parts[0] + need(whole == '0' or (whole and whole[0] in '123456789' and all(c in '0123456789' for c in whole)), 'canonical whole seconds') + fraction = parts[1] if len(parts) == 2 else '' + need(len(fraction) <= 9 and all(c in '0123456789' for c in fraction), 'integer-ns decimal precision') + return uint(int(whole) * NS + (int(fraction.ljust(9, '0')) if fraction else 0)) + + +def origin_ref(file_record): + return {'path': str(Path(file_record['origin_path']).relative_to(R)), 'sha256': file_record['sha256']} + + +def opening_evidence(snapshot): + """Pure strict DATA revalidation, never native ownership/custody proof.""" + plain(snapshot) + exact(snapshot, ('schema', 'opening_pin', 'descriptor_wire', 'corpus_wires')) + need(snapshot['schema'] == 'fresh-current-opening-snapshot-v1', 'opening snapshot') + op = pin(snapshot['opening_pin']) + need(op['mode'] == 0o444 and type(snapshot['descriptor_wire']) is str and type(snapshot['corpus_wires']) is dict, 'immutable opening DATA') + raw = snapshot['descriptor_wire'].encode('utf-8') + need(len(raw) == op['bytes'] and hashlib.sha256(raw).hexdigest() == op['sha256'], 'opening wire pin') + desc = decode(raw) + exact(desc, ('schema', 'round_id', 'authorization_sha256', 'previous_opening_sha256', 'corpus_directory', + 'authorization_file', 'state_file', 'selection_file', 'files', 'observations', 'expected_totals', + 'physical_total_ns', 'old_complete_total_ns', 'physical_final_boundary')) + need(desc['schema'] == 'fresh-current-opening-corpus-v1' and desc['round_id'] == ROUND_ID and + desc['authorization_sha256'] == AUTHORIZATION_SHA256 and desc['corpus_directory'] == 'corpus' and + desc['physical_total_ns'] is None and desc['old_complete_total_ns'] is None and + desc['physical_final_boundary'] == 'OPEN_NOT_ZERO', 'selected opening scope') + if desc['previous_opening_sha256'] is not None: + digest(desc['previous_opening_sha256']) + need(type(desc['files']) is dict and set(snapshot['corpus_wires']) == set(desc['files']) and + len(desc['files']) <= 8 * OPENING_LIMIT, 'closed corpus census') + docs, total, origins = {}, 0, set() + for name, item in desc['files'].items(): + need(type(name) is str and name.endswith('.json') and '..' not in name and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.' for c in name), 'literal corpus name') + exact(item, ('bytes', 'sha256', 'origin_path', 'origin_mode')) + uint(item['bytes']); digest(item['sha256']) + need(type(item['origin_path']) is str and Path(item['origin_path']).is_relative_to(R) and + '..' not in Path(item['origin_path']).parts and item['origin_path'] not in origins and + type(item['origin_mode']) is int and item['origin_mode'] in (0o400, 0o444, 0o600), 'original evidence pin') + origins.add(item['origin_path']) + wire = snapshot['corpus_wires'][name] + need(type(wire) is str, 'literal original JSON wire') + data = wire.encode('utf-8'); total += len(data) + need(total <= CORPUS_LIMIT and len(data) == item['bytes'] and hashlib.sha256(data).hexdigest() == item['sha256'], 'complete original corpus bytes') + docs[name] = metadata_decode(data) + auth, state, selected = (docs[desc[k]] for k in ('authorization_file', 'state_file', 'selection_file')) + need(desc['files'][desc['authorization_file']]['sha256'] == AUTHORIZATION_SHA256 and + auth['limits']['total_guarded_seconds'] == 2400 and auth['limits']['initial_feasibility_seconds'] == 600 and + auth['limits']['per_command_seconds'] == 180 and auth['limits']['sampled_memory_bytes'] == RSS_LIMIT, + 'unchanged financial/resource limits') + need(type(desc['observations']) is list and 0 < len(desc['observations']) <= OPENING_LIMIT, 'bounded accepted operations') + views, ids, commands, shells, pairs_seen, regs, natives = [], set(), set(), set(), [], [], [] + body = admin = 0 + for row in desc['observations']: + exact(row, ('kind', 'entry_id', 'registration', 'cost', 'native', 'review', 'review_status', + 'command_sha256', 'formal_start_sha256', 'formal_receipt_sha256', 'selectors', 'closed_checks', 'candidate', 'exact_shell_sha256')) + name = label(row['entry_id']); command = digest(row['command_sha256']) + need(name not in ids and command not in commands, 'import each original identity/command once') + ids.add(name); commands.add(command) + registration, cost, native, review = (docs[row[k]] for k in ('registration', 'cost', 'native', 'review')) + need(registration['attempt_id'] == name and cost['attempt_id'] == name and + cost['reservation'] == origin_ref(desc['files'][row['registration']]) and + cost['native_tool_result'] == origin_ref(desc['files'][row['native']]), 'original pre-entry/outcome link') + candidate = docs[row['candidate']] + need(desc['files'][row['candidate']]['sha256'] == command and + type(candidate['exact_shell_command']) is str and + hashlib.sha256(candidate['exact_shell_command'].encode('utf-8')).hexdigest() == row['exact_shell_sha256'] and + row['exact_shell_sha256'] not in shells, 'candidate document versus distinct exact shell identity') + shells.add(row['exact_shell_sha256']) + q = row['selectors'] + exact(q, ('cost_body', 'cost_admin', 'cost_admin_multiplier', 'registration_admin', 'registration_admin_multiplier', + 'registration_candidate', 'registration_preentry', 'registration_preentry_value', 'registration_body_cap', + 'registration_cap_multiplier', 'review_begin', 'review_end', 'review_body', 'review_admin', + 'review_admin_multiplier', 'review_native_exit')) + for key in ('cost_admin_multiplier', 'registration_admin_multiplier', 'registration_cap_multiplier', 'review_admin_multiplier'): + need(type(q[key]) is int and q[key] in (1, NS), 'declared exact integer unit') + need(type(q['registration_preentry_value']) is bool and + select(registration, q['registration_preentry']) is q['registration_preentry_value'], 'original pre-entry reserved state') + need(select(registration, q['registration_candidate'])['sha256'] == command and + native['exact_command_candidate_sha256'] == command, 'original exact command correlation') + elapsed = uint(select(cost, q['cost_body'])) + debit = uint(select(cost, q['cost_admin'])) * q['cost_admin_multiplier'] + begin, end = uint(select(review, q['review_begin'])), uint(select(review, q['review_end'])) + need(end >= begin and end - begin == elapsed == uint(select(review, q['review_body'])) and + debit == ADMIN_NS and + uint(select(registration, q['registration_admin'])) * q['registration_admin_multiplier'] == debit and + uint(select(registration, q['registration_body_cap'])) * q['registration_cap_multiplier'] == BODY_LIMIT_NS and + uint(select(review, q['review_admin'])) * q['review_admin_multiplier'] == debit, + 'actual observed body and separate admin units') + selected_review_exit = select(review, q['review_native_exit']) + need(type(native['actual_tool_result']['exit_code']) is int and + type(selected_review_exit) is int and + native['actual_tool_result']['exit_code'] == selected_review_exit and + review['status'] == row['review_status'] and type(row['review_status']) is str and + row['review_status'].startswith('ACCEPT_') and cost['all_costs_settled'] is False, + 'genuine retained native result / accepted scoped review') + need(seconds_ns(cost['policy_charged_seconds']) == elapsed + debit, 'cost row exact policy amount') + review_pins = review['input_pins'] + review_pins = review_pins if type(review_pins) is list else list(review_pins.values()) + for key in ('registration', 'cost', 'native'): + expected = desc['files'][row[key]] + need(any(type(p) is dict and p.get('path') == expected['origin_path'] and + p.get('sha256') == expected['sha256'] and p.get('bytes') == expected['bytes'] for p in review_pins), + 'review binds each original provenance file') + if row['kind'] == 'ORIGINAL_MANUAL_OPERATION': + need(row['formal_start_sha256'] is None and row['formal_receipt_sha256'] is None, 'not a fabricated formal entry') + else: + need(row['kind'] == 'ALREADY_REGISTERED_OPERATION', 'immutable charge partition') + digest(row['formal_start_sha256']); digest(row['formal_receipt_sha256']) + blockers = [] + if elapsed > BODY_LIMIT_NS: + blockers.append(name + ':IMPORTED_BODY180_EXCEEDED') + need(type(row['closed_checks']) is list and 1 <= len(row['closed_checks']) <= 16, 'explicit scoped closure checks') + documents = {'review': review, 'cost': cost, 'registration': registration, 'native': native} + for check in row['closed_checks']: + exact(check, ('document', 'path', 'expected')) + need(check['document'] in documents and (type(check['expected']) is bool or check['expected'] is None), 'closed condition literal') + actual = select(documents[check['document']], check['path']) + if type(actual) is not type(check['expected']) or actual != check['expected']: + blockers.append(name + ':IMPORTED_UNCLOSED_CONDITION') + pair = {'cost': origin_ref(desc['files'][row['cost']]), 'independent_outcome_review': origin_ref(desc['files'][row['review']])} + pairs_seen.append(pair); regs.append(origin_ref(desc['files'][row['registration']])); natives.append(origin_ref(desc['files'][row['native']])) + views.append({'kind': row['kind'], 'entry_id': name, 'command_sha256': command, 'exact_shell_sha256': row['exact_shell_sha256'], 'body_ns': elapsed, + 'admin_ns': debit, 'blockers': blockers, 'formal_start_sha256': row['formal_start_sha256'], 'formal_receipt_sha256': row['formal_receipt_sha256']}) + body += elapsed; admin += debit + need(state['accepted_attempts'] == pairs_seen == selected['observations'] and + selected['pre_entry_registrations'] == regs and selected['genuine_native_results'] == natives and + selected['current_parent_state'] == origin_ref(desc['files'][desc['state_file']]), 'no accepted operation/provenance omitted') + need(type(state['guarded_attempts']) is int and state['guarded_attempts'] == len(views) and + state['observed_body_elapsed_ns_total'] == body and type(state['observed_body_elapsed_ns_total']) is int and + type(state['administrative_policy_debit_seconds_total']) is int and + state['administrative_policy_debit_seconds_total'] * NS == admin and + seconds_ns(state['policy_charged_seconds_total']) == body + admin and + selected['body_ns'] == body and selected['administrative_policy_ns'] == admin and + selected['policy_total_ns'] == body + admin and + state['complete_new_physical_total_seconds'] is None and state['old_complete_total_seconds'] is None and + state['physical_publication_boundary'] == 'OPEN_NOT_ZERO' and state['all_costs_settled'] is False, + 'current complete selected corpus totals, never physical total') + exact(desc['expected_totals'], ('body_ns', 'administrative_ns', 'policy_ns', 'operations')) + for amount in desc['expected_totals'].values(): + uint(amount) + need(desc['expected_totals'] == {'body_ns': body, 'administrative_ns': admin, 'policy_ns': body + admin, 'operations': len(views)}, 'independent literal expected totals') + manual = [v for v in views if v['kind'] == 'ORIGINAL_MANUAL_OPERATION'] + return {'descriptor': desc, 'state_sha256': desc['files'][desc['state_file']]['sha256'], 'views': views, + 'manual_body_ns': sum(v['body_ns'] for v in manual), 'manual_admin_ns': sum(v['admin_ns'] for v in manual), + 'manual_entry_ids': [v['entry_id'] for v in manual], 'manual_command_sha256s': [v['command_sha256'] for v in manual], + 'registry_rows': [v for v in views if v['kind'] == 'ALREADY_REGISTERED_OPERATION'], + 'parent_body_ns': body, 'parent_admin_ns': admin, + 'blockers': [reason for v in views for reason in v['blockers']]} + + +def read_opening(io, opening_pin, owner_uid): + """Actual source-authenticated OwnedIO boundary, not arbitrary reader authority.""" + pin(opening_pin); need(opening_pin['mode'] == 0o444, 'frozen selected opening') + row, raw = read_pinned(io, opening_pin, owner_uid) + desc = decode(raw); folder = Path(opening_pin['path']).parent / 'corpus' + need(folder.resolve(strict=True) == folder, 'canonical corpus directory') + before = folder.lstat() + need(stat.S_ISDIR(before.st_mode) and before.st_uid == owner_uid and stat.S_IMODE(before.st_mode) == 0o555, 'immutable current-owner corpus') + names = io.names(folder, 8 * OPENING_LIMIT + 1) + need(type(names) is list and all(type(n) is str for n in names) and + len(names) == len(set(names)) and set(names) == set(desc['files']), 'exact complete corpus census') + wires, observed = {}, [] + for name in sorted(names): + item = desc['files'][name] + need(type(name) is str and '/' not in name and '..' not in name, 'corpus basename') + p = {'path': str(folder / name), 'bytes': item['bytes'], 'sha256': item['sha256'], 'mode': 0o444} + actual, data = read_pinned(io, p, owner_uid); wires[name] = data.decode('utf-8'); observed.append((p, actual, data)) + snapshot = {'schema': 'fresh-current-opening-snapshot-v1', 'opening_pin': opening_pin, + 'descriptor_wire': raw.decode('utf-8'), 'corpus_wires': wires} + opening_evidence(snapshot) + for p, actual, data in observed: + after_row, after = read_pinned(io, p, owner_uid) + need(after_row == actual and after == data, 'immutable corpus pre/post custody') + after_row, after = read_pinned(io, opening_pin, owner_uid) + directory_after = folder.lstat() + need(after_row == row and after == raw and + (directory_after.st_dev, directory_after.st_ino, directory_after.st_mode, directory_after.st_uid, + directory_after.st_mtime_ns, directory_after.st_ctime_ns) == + (before.st_dev, before.st_ino, before.st_mode, before.st_uid, before.st_mtime_ns, before.st_ctime_ns) and + set(io.names(folder, 8 * OPENING_LIMIT + 1)) == set(names), 'opening/corpus current custody') + return snapshot + + +def require_opening_append(previous, current): + a, b = opening_evidence(previous), opening_evidence(current) + old, new = a['descriptor'], b['descriptor'] + need(new['previous_opening_sha256'] == previous['opening_pin']['sha256'] and + new['observations'][:len(old['observations'])] == old['observations'] and + all(new['files'].get(k) == v for k, v in old['files'].items()) and + new['authorization_sha256'] == old['authorization_sha256'], 'opening immutable prefix; no omission/reprice/reclassification') + return True + + +def validate_opening_partition(opening, reg, records): + evidence = opening_evidence(opening) + _, _, starts, closes = registry((json.dumps(reg, separators=(',', ':')) + '\n').encode('utf-8')) + formal_commands = set() + for name, bundle in records.items(): + s = bundle['start']; command = digest(s['command_sha256']); formal_commands.add(command) + need(name not in evidence['manual_entry_ids'] and command not in evidence['manual_command_sha256s'], 'manual/formal charges disjoint') + for v in evidence['registry_rows']: + name = v['entry_id'] + need(name in starts and name in closes and starts[name]['sha256'] == v['formal_start_sha256'] and + closes[name]['sha256'] == v['formal_receipt_sha256'] and records[name]['receipt'] is not None, + 'state formal partition bound to actual registered closed records') + receipt = records[name]['receipt'] + need(records[name]['start']['command_sha256'] == v['command_sha256'] and + receipt['body_elapsed_ns'] == v['body_ns'] and receipt['administrative_debit_ns'] == v['admin_ns'], 'formal body charged once by registry') + return evidence + + +def validate_opening_binding(io, binding, owner_uid): + plain(binding) + exact(binding, ('schema', 'opening_pin', 'adoption_pin', 'funding_source_sha256')) + need(binding['schema'] == 'fresh-current-opening-binding-v1', 'current opening binding') + digest(binding['funding_source_sha256']); snapshot = read_opening(io, binding['opening_pin'], owner_uid) + evidence = opening_evidence(snapshot); _, raw = read_pinned(io, binding['adoption_pin'], owner_uid) + adoption = decode(raw) + exact(adoption, ('schema', 'opening_sha256', 'state_sha256', 'manual_body_ns', 'manual_admin_ns', + 'operations', 'authorization_sha256', 'funding_source_sha256', 'authority_scope')) + for key in ('manual_body_ns', 'manual_admin_ns', 'operations'): + uint(adoption[key]) + need(adoption == {'schema': 'fresh-current-opening-adoption-v1', 'opening_sha256': binding['opening_pin']['sha256'], + 'state_sha256': evidence['state_sha256'], 'manual_body_ns': evidence['manual_body_ns'], + 'manual_admin_ns': evidence['manual_admin_ns'], 'operations': len(evidence['views']), + 'authorization_sha256': AUTHORIZATION_SHA256, 'funding_source_sha256': binding['funding_source_sha256'], + 'authority_scope': 'OPENING_DATA_SELECTION_ONLY_NOT_OPERATIONAL_GRANT'}, 'selected current opening adoption; not native grant') + return snapshot + + +def initial_registry(opening_pin, policy_pins, phase='INITIAL', phase_release_sha256=None): + plain(opening_pin); plain(policy_pins); plain(phase); plain(phase_release_sha256) + obj = {'schema': 'fresh-round-registry-v2', 'round_id': ROUND_ID, 'authorization_sha256': AUTHORIZATION_SHA256, + 'opening_pin': opening_pin, 'predecessor_sha256': None, 'phase': phase, + 'phase_release_sha256': phase_release_sha256, 'policies': policy_pins, 'events': []} + raw = (json.dumps(obj, sort_keys=True, separators=(',', ':')) + '\n').encode('utf-8'); registry(raw) + return raw + + + +def validate_pre_entry_provenance(value, name, command, reservation_ns): + plain(value) + exact(value, ('schema', 'entry_id', 'command_sha256', 'body_reservation_ns', 'registration_pin', 'original_start_pin', 'pending_manifest_pin')) + need(value['schema'] == 'fresh-original-preentry-provenance-v1' and value['entry_id'] == name and + value['command_sha256'] == command and type(value['body_reservation_ns']) is int and + value['body_reservation_ns'] == reservation_ns, 'same genuine enclosing manual/formal operation') + for key in ('registration_pin', 'original_start_pin', 'pending_manifest_pin'): + pin(value[key]) + return True diff --git a/research/h25-complete-outcome-close/reference/active_original.py.txt b/research/h25-complete-outcome-close/reference/active_original.py.txt new file mode 100644 index 0000000000..6ebe3eee48 --- /dev/null +++ b/research/h25-complete-outcome-close/reference/active_original.py.txt @@ -0,0 +1,883 @@ +"""SOURCE ONLY: private ACTIVE ownership and durable registry publication. + +Trusted caller must authenticate the exact loaded controller/funding modules +before bind_api. Module names, hash strings, dictionaries and instance fields +are NOT that authentication. This code performs real GlobalLease acquisition +and verification; never restore an owner from DATA or pass it to a child. +Ordinary OS/CPython/fsync/rename/link and registered-writer exclusion are selected +operating premises, not universal hostile-admin or crash-storage theorems. +""" +import hashlib +import json +import os +import stat +import time +from pathlib import Path +from types import ModuleType, FunctionType, GetSetDescriptorType + +# Kernel-body predecessor provenance ONLY; actual selected C/profile authenticated externally. +CONTROLLER_SHA = 'be36f1427694c786efc1cf04958a6fb002776f586641828ce569f36e2f289895' +FUNDING_SHA = '164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677' +W = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453') +R = W / 'outputs/h25-data-handling-20261028' +CONTROL = R / 'control/fresh-metered-round-v1' +DOMAIN = R / 'runtime/fresh-metered-round-v1/attempts' +STAGE = CONTROL / '_active-staging' +HEADS = CONTROL / '_registry-heads' +HANDOFFS = CONTROL / '_handoff-intents' +CLAIMS = CONTROL / '_handoff-claims' +HEAD = CONTROL / 'ACTIVE-HEAD.json' +LOCK = W / 'outputs/h25-bookkeeping-swarm-20261028/runtime/science.lock' + + +class ActiveError(RuntimeError): + pass + + +def need(ok, text): + if ok is not True: + raise ActiveError(text) + + +def canonical(value): + return (json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) + '\n').encode('utf-8') + + + + +# Finite ordinary-Python kernel substitution boundary. These checks perform no +# filesystem/process/clock operation and never establish loaded-image identity. +def module_namespace(module): + need(type(module) is ModuleType, 'exact selected module type') + namespace = ModuleType.__getattribute__(module, '__dict__') + need(type(namespace) is dict, 'native module namespace') + keys = tuple(dict.__iter__(namespace)) + need(all(type(k) is str for k in keys), 'module keys before hashing/lookup') + need('__getattr__' not in keys, 'no selected module attribute fallback') + return namespace + + +def function_image(fn, namespace): + need(type(fn) is FunctionType and fn.__globals__ is namespace, 'actual source-owned function') + return (fn, fn.__code__, fn.__defaults__, fn.__kwdefaults__, fn.__closure__) + + +def unchanged_function(image, namespace): + fn, code, defaults, kwdefaults, closure = image + need(type(fn) is FunctionType and fn.__globals__ is namespace and + fn.__code__ is code and fn.__defaults__ is defaults and + fn.__kwdefaults__ is kwdefaults and fn.__closure__ is closure, + 'captured original function metadata') + + +def class_image(cls, methods, namespace, *, slotted=False): + need(type(cls) is type, 'ordinary exact class before native type inspection') + mro = type.__getattribute__(cls, '__mro__') + need(type(mro) is tuple and len(mro) == 2 and mro[0] is cls and mro[1] is object, 'direct object class') + native = type.__getattribute__(cls, '__dict__') + keys = tuple(native) + need(all(type(k) is str for k in keys), 'class keys before hashing/lookup') + image = {k: native[k] for k in keys} + allowed = {'__module__', '__doc__'} | set(methods) + if slotted: + allowed |= {'__slots__', '__new__'} + need(type(image.get('__slots__')) is tuple and len(image['__slots__']) == 0 and + type(image.get('__new__')) is staticmethod, 'private empty-slotted class') + function_image(staticmethod.__getattribute__(image['__new__'], '__func__'), namespace) + else: + allowed |= {'__dict__', '__weakref__'} + for name in ('__dict__', '__weakref__'): + descriptor = image.get(name) + need(type(descriptor) is GetSetDescriptorType and descriptor.__objclass__ is cls and + type(descriptor.__name__) is str and descriptor.__name__ == name, 'native actual-class dictionary descriptor') + need(set(image) == allowed and type(image['__module__']) is str and + (image['__doc__'] is None or type(image['__doc__']) is str), 'fixed class layout; no special hooks') + function_images = {name: function_image(image[name], namespace) for name in methods} + if slotted: + function_images['__new__'] = function_image(staticmethod.__getattribute__(image['__new__'], '__func__'), namespace) + return image, function_images + + +def unchanged_class(cls, image, function_images, namespace): + need(type(cls) is type, 'unchanged ordinary metaclass') + native = type.__getattribute__(cls, '__dict__'); keys = tuple(native) + need(all(type(k) is str for k in keys) and set(keys) == set(image) and + all(native[k] is image[k] for k in keys), 'no class namespace/descriptor substitution') + mro = type.__getattribute__(cls, '__mro__') + need(type(mro) is tuple and len(mro) == 2 and mro[0] is cls and mro[1] is object, 'unchanged direct class ancestry') + for value in function_images.values(): + unchanged_function(value, namespace) + + +def instance_state(value, cls, image, function_images, namespace, fields): + need(type(value) is cls, 'exact actual instance before descriptor access') + unchanged_class(cls, image, function_images, namespace) + # Direct native getset dispatch bypasses value.__getattribute__ entirely. + values = GetSetDescriptorType.__get__(image['__dict__'], value, cls) + need(type(values) is dict, 'exact native instance dictionary') + keys = tuple(dict.__iter__(values)) + need(all(type(k) is str for k in keys) and set(keys) == set(fields), 'no instance method/descriptor/special-hook shadow') + return values + + +def bounded_kernel_data(value, nodes=None, depth=0): + if nodes is None: + nodes = [0] + nodes[0] += 1 + need(nodes[0] <= 256 and depth <= 8, 'bounded kernel metadata state') + t = type(value) + if t is dict: + keys = tuple(dict.__iter__(value)) + need(len(keys) <= 64 and all(type(k) is str for k in keys), 'kernel dictionary keys before lookup') + for key in keys: + bounded_kernel_data(value[key], nodes, depth + 1) + elif t is list or t is tuple: + need(len(value) <= 64, 'kernel metadata sequence bound') + for item in value: + bounded_kernel_data(item, nodes, depth + 1) + elif t is str: + need(len(value) <= 16384, 'kernel metadata string bound') + else: + need(value is None or t is int or t is bool, 'exact scalar kernel metadata') + + +def exception_instance(value): + cls = type(value) + if type(cls) is not type: + return False + mro = type.__getattribute__(cls, '__mro__') + return type(mro) is tuple and any(base is BaseException for base in mro) + +def bind_api(controller, funding, *, role, expected_head_pin=None, + approved_handoff_pin=None, approved_closure=None, approved_opening=None, approved_manual_entry=None, guardian=None): + """Called ONLY by the separately authenticated source-private parent role. + + Exact module/source/loaded-instance authentication is an external bootstrap + premise. Merely constructing ModuleType/FunctionType is not authentication. + approved_* are pinned permission/evidence DATA chosen by that trusted role; + they never create ownership. Every returned context first acquires its own + actual EX. No factory/caller/native command is authorized by this file. + """ + need(type(controller) is ModuleType and type(funding) is ModuleType, 'actual selected module objects') + need(type(role) is str and role in ('PUBLISHER', 'CONTROLLER', 'CLOSER'), 'fixed caller role') + C, F = controller, funding + cg, fg = module_namespace(C), module_namespace(F) + IOType, LeaseType, io = cg['OwnedIO'], cg['GlobalLease'], cg['IO'] + io_image, io_functions = class_image(IOType, ('__init__', 'acquire', 'close', 'read', 'names', 'write'), cg) + lease_image, lease_functions = class_image(LeaseType, ('__init__', 'acquire', 'verify', 'close'), cg) + instance_state(io, IOType, io_image, io_functions, cg, {'slots'}) + lock_reference, domain_reference, control_reference = cg['HISTORICAL_LOCK'], fg['DOMAIN'], fg['CONTROL'] + need(type(lock_reference) is type(LOCK) and lock_reference == LOCK and + type(domain_reference) is type(DOMAIN) and domain_reference == DOMAIN and + type(control_reference) is type(CONTROL) and control_reference == CONTROL, + 'actual original canonical lock/domain values') + first_state, secondary_state, unknown_state = cg['FIRST'], cg['SECONDARY'], cg['IO_UNKNOWN'] + need(type(first_state) is list and len(first_state) == 1 and type(secondary_state) is list and + len(secondary_state) == 256 and type(unknown_state) is list and len(unknown_state) == 1 and + type(unknown_state[0]) is bool, 'actual original error/uncertainty containers') + remember_image = function_image(cg['remember'], cg) + remember_original = remember_image[0] + continuation_image = function_image(cg['joined_continuation_check'], cg) + funding_names = ('snapshot_round', 'assess_round', 'registry', 'require_append_only', + 'read_opening', 'opening_evidence', 'validate_opening_binding', 'require_opening_append', + 'validate_opening_partition', 'validate_pre_entry_provenance', 'metadata_decode', 'select', + 'read_pinned', 'plain', 'decode', 'pin', 'uint') + funding_images = {name: function_image(fg[name], fg) for name in funding_names} + active_globals = globals() # Actual source-private A module; bootstrap authentication remains external. + # Fixed authenticated loader supplies actual source-private G, never DATA. + guardian_module, guardian_channel, guardian_namespace, guardian_image = None, None, None, None + if guardian is not None: + need(type(guardian) is tuple and len(guardian) == 2, 'actual fixed G association pair') + guardian_module, guardian_channel = guardian + guardian_namespace = module_namespace(guardian_module) + guardian_image = function_image(guardian_namespace['verify_association'], guardian_namespace) + guardian_globals = dict(guardian_namespace) if guardian_namespace is not None else None + guardian_class = guardian_namespace['GuardianChannel'] if guardian_namespace is not None else None + guardian_class_image = dict(type.__getattribute__(guardian_class, '__dict__')) if guardian_class is not None else None + guardian_function_images = [function_image(fn, guardian_namespace) for fn in guardian_class_image.values() + if type(fn) is FunctionType] if guardian_class_image is not None else [] + if guardian_class_image is not None: + for member in guardian_class_image.values(): + if type(member) is property: + guardian_function_images.extend(function_image(fn, guardian_namespace) + for fn in (member.fget,member.fset,member.fdel) if fn is not None) + need(guardian_image is not None or role == 'CLOSER', 'production owner requires actual G channel') + + def guard(record, phase): + if role == 'CLOSER': + return None # Separately funded metadata-only STOP/UNKNOWN; no G clearing. + need(guardian_image is not None, 'no source-private G association') + unchanged_function(guardian_image, guardian_namespace) + need(set(guardian_namespace) == set(guardian_globals) and + all(guardian_namespace[k] is guardian_globals[k] for k in guardian_globals), + 'actual G source globals unchanged') + native_class = type.__getattribute__(guardian_class, '__dict__') + need(set(native_class) == set(guardian_class_image) and + all(native_class[k] is guardian_class_image[k] for k in guardian_class_image), + 'actual G class/method/descriptor identities unchanged') + for image in guardian_function_images: + unchanged_function(image, guardian_namespace) + selected_request = record.get('request') or (manual['request'] if manual is not None else None) + selected_start = (record.get('manual_provenance') or + (manual['provenance'] if manual is not None else None)) + need(selected_request is not None and selected_start is not None, + 'immutable original manual request and GSTART before protected work') + return guardian_image[0](guardian_channel, role, selected_request, + selected_start['original_start_pin'], phase) + + def failure_state_valid(): + keys = tuple(dict.__iter__(cg)) + if not all(type(k) is str for k in keys): + return False + if not (cg.get('FIRST') is first_state and cg.get('SECONDARY') is secondary_state and + cg.get('IO_UNKNOWN') is unknown_state and cg.get('remember') is remember_original): + return False + if not (type(first_state) is list and len(first_state) == 1 and + type(secondary_state) is list and len(secondary_state) == 256 and + type(unknown_state) is list and len(unknown_state) == 1 and type(unknown_state[0]) is bool): + return False + return (first_state[0] is None or exception_instance(first_state[0])) and all( + e is None or exception_instance(e) for e in secondary_state) + + def io_state(allow_uncertain=False): + values = instance_state(io, IOType, io_image, io_functions, cg, {'slots'}) + slots = values['slots'] + need(type(slots) is list and len(slots) == 16, 'fixed original IO slots') + for item in slots: + need(type(item) is list and len(item) == 3 and type(item[1]) is str, + 'exact IO slot structure before field use') + need(item[1] in ('FREE', 'CLOSED', 'OWNED', 'PENDING', 'CLOSING'), 'original IO slot phase') + need(item[2] is None or type(item[2]) is bool, 'original IO directory flag') + if item[1] == 'FREE': + need(item[0] is None and item[2] is None, 'original free slot') + elif item[1] == 'OWNED' and not allow_uncertain: + # Owned scandir iterators exist only INSIDE the unchanged original + # names call. At these nonreentrant source-private entry points, + # only known ordinary OS descriptor slots may persist. + need(item[2] is False and type(item[0]) is int and item[0] >= 0, 'known owned OS descriptor') + elif item[1] in ('PENDING', 'CLOSING'): + need(allow_uncertain, 'uncertain IO blocks fresh dispatch') + return values + + def lease_state(held, fields=None): + wanted = {'fd', 'phase', 'birth', 'lock_info'} if fields is None else fields + values = instance_state(held, LeaseType, lease_image, lease_functions, cg, wanted) + if not wanted: + return values + need(type(values['phase']) is str and values['phase'] in + ('NEW', 'OPEN_PENDING', 'OPEN_RETURNED', 'EX_HELD', 'CLOSE_ENTERED', 'CLOSE_RETURNED', 'CLOSE_UNKNOWN'), + 'exact original lease phase before equality/dispatch') + need(values['fd'] is None or (type(values['fd']) is int and values['fd'] >= 0), 'exact owned descriptor field') + birth = values['birth'] + if birth is not None: + need(type(birth) is dict, 'actual process metadata dictionary') + keys = tuple(dict.__iter__(birth)) + need(all(type(k) is str for k in keys) and set(keys) == + {'pid', 'ppid', 'pgid', 'sid', 'start_ticks', 'rss_bytes'}, 'actual process metadata keys') + need(all(type(birth[k]) is int and birth[k] >= 0 for k in keys), 'actual process metadata exact ints') + bounded_kernel_data(values['lock_info']) + return values + + def kernel_integrity(held=None, *, allow_uncertain=False): + need(module_namespace(C) is cg and module_namespace(F) is fg and + cg.get('IO') is io and cg.get('OwnedIO') is IOType and cg.get('GlobalLease') is LeaseType and + cg.get('HISTORICAL_LOCK') is lock_reference and fg.get('DOMAIN') is domain_reference and + fg.get('CONTROL') is control_reference, 'same actual selected kernel objects') + unchanged_class(IOType, io_image, io_functions, cg) + unchanged_class(LeaseType, lease_image, lease_functions, cg) + unchanged_function(remember_image, cg) + need(failure_state_valid(), 'original error/uncertainty memory integrity') + for name, image in funding_images.items(): + need(fg.get(name) is image[0], 'same selected funding function') + unchanged_function(image, fg) + values = io_state(allow_uncertain) + if held is not None: + lease_state(held) + return values + + # No kernel instance/native method has been invoked before these snapshots. + kernel_integrity() + for value in (expected_head_pin, approved_handoff_pin, approved_closure, approved_opening, approved_manual_entry): + F.plain(value) + # Copy only strict DATA. No caller retains a mutable permission dictionary. + expected = F.decode(canonical(expected_head_pin)) if expected_head_pin is not None else None + handoff = F.decode(canonical(approved_handoff_pin)) if approved_handoff_pin is not None else None + closure = F.decode(canonical(approved_closure)) if approved_closure is not None else None + opening = F.decode(canonical(approved_opening)) if approved_opening is not None else None + manual = F.decode(canonical(approved_manual_entry)) if approved_manual_entry is not None else None + contexts, opened = {}, [False] + sentinel = object() + + def fail(record, error): + valid = failure_state_valid() + if record['first'] is None: + record['first'] = first_state[0] if valid and first_state[0] is not None else error + if error is not record['first'] and all(error is not e for e in record['secondary']): + if len(record['secondary']) < 32: + record['secondary'].append(error) + else: + record['secondary_saturated'] = True + record['phase'] = 'FAILED_UNCERTAIN_NO_RETRY' + # Never invoke replaced global state while reporting its integrity failure. + # The private first/secondary debt survives even when kernel memory is unsafe. + if valid: + try: + unchanged_function(remember_image, cg) + remember_original(error) + except BaseException as secondary: + if secondary is not record['first'] and len(record['secondary']) < 32: + record['secondary'].append(secondary) + else: + record['secondary_saturated'] = True + else: + record['kernel_memory_uncertain'] = True + return record['first'] + + def rec(ctx): + need(type(ctx) is Context, 'actual private context type before hashing') + unchanged_class(Context, context_image, context_functions, active_globals) + need(ctx in contexts, 'actual private context only') + return contexts[ctx] + + def verify(record, *, allow_original_failure=False): + need(record['phase'] not in ('FAILED_UNCERTAIN_NO_RETRY', 'RELEASED', 'CLOSE_UNKNOWN'), 'live private owner phase') + kernel_integrity(record['lease']) + need(unknown_state[0] is False and (first_state[0] is None or allow_original_failure is True), + 'no uncertain IO; prior original error only through source-owned cleanup/retention transition') + need(record['pid'] == os.getpid(), 'same actual process/context; no fork or DATA restoration') + values = lease_state(record['lease']) + need(values['fd'] is record['owned_fd'], 'same captured actual native descriptor field') + observation = lease_image['verify'](record['lease']) # Original real native verification. + kernel_integrity(record['lease']) + need(observation['parent']['start_ticks'] == record['birth']['start_ticks'] and + observation['parent']['pid'] == record['birth']['pid'], 'native generation unchanged') + return observation + + def close_actual(record): + need(record['lease_close_entered'] is False, 'one actual lease close; never replay a numeric FD') + record['lease_close_entered'] = True + if record['lease'] is None or record['lease_acquire_entered'] is False: + return # Original pure initializer never acquired any native descriptor. + kernel_integrity(record['lease'], allow_uncertain=True) + values = lease_state(record['lease']) + need(values['phase'] not in ('CLOSE_ENTERED', 'CLOSE_RETURNED', 'CLOSE_UNKNOWN'), + 'original source lease was already closed/uncertain; no repeated FD close') + if record['owned_fd'] is not None: + need(values['fd'] is record['owned_fd'], 'no replaced native descriptor on cleanup') + lease_image['close'](record['lease']) + + def guarded_io(name, *args, **kwargs): + cleanup = name == 'close' + kernel_integrity(allow_uncertain=cleanup) + for record in contexts.values(): + if record['lease'] is not None and record['lease_initialized']: + lease_state(record['lease']) + if cleanup: + slot = args[0] + slots = io_state(True)['slots'] + need(any(slot is item for item in slots) and type(slot) is list and len(slot) == 3 and + type(slot[1]) is str and slot[1] == 'OWNED' and slot[2] is False and + type(slot[0]) is int and slot[0] >= 0, 'actual ordinary owned IO slot before close') + return io_image[name](io, *args, **kwargs) + + def funding_io(name, *args): + kernel_integrity() + for record in contexts.values(): + if record['lease'] is not None and record['lease_initialized']: + lease_state(record['lease']) + # SAME real IO object, not a proxy or callback. Original internal self calls + # are covered by selected single-thread/nonreentrant private stability. + return funding_images[name][0](io, *args) + + def directory(path, *, private=True): + need(path.is_absolute() and path.resolve(strict=True) == path, 'canonical selected directory') + st = path.lstat() + need(stat.S_ISDIR(st.st_mode) and st.st_uid == os.getuid() and + ((stat.S_IMODE(st.st_mode) == 0o700) if private else not stat.S_IMODE(st.st_mode) & 0o022), + 'owned selected directory mode') + return (st.st_dev, st.st_ino, st.st_mode, st.st_uid, st.st_mtime_ns, st.st_ctime_ns) + + def sync_dir(record, path): + directory(path, private=path not in (CONTROL, DOMAIN.parent.parent)) + slot = guarded_io('acquire', path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC) + primary = None + try: + os.fsync(slot[0]) + except BaseException as e: + primary = fail(record, e) + finally: + if slot[1] == 'OWNED': + try: + guarded_io('close', slot) + except BaseException as e: + primary = fail(record, e) + if primary is not None: + raise primary + + def pinned(path, raw, mode): + return {'path': str(path), 'bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest(), 'mode': mode} + + def read(record, p): + verify(record) + return funding_io('read_pinned', p, os.getuid())[1] + + def stage_empty(): + directory(STAGE) + need(guarded_io('names', STAGE, 2) == [], 'no pending/orphan staging file; no cleanup by guessed name') + + def publish(record, path, raw, mode, *, replace_head=False): + verify(record); stage_empty() + need(type(raw) is bytes and 0 < len(raw) <= F.META_CAP and mode in (0o444, 0o600), 'bounded publication') + directory(path.parent, private=path.parent != CONTROL) + record['publication'] = {'path': path, 'slot': None, 'temporary': None, 'phase': 'BEFORE_CREATE'} + tmp = STAGE / ('pending-' + record['role'] + '-' + path.name) + record['publication']['temporary'] = tmp # Private identity exists BEFORE fallible open. + record['publication']['phase'] = 'OPEN_PENDING' + slot = guarded_io('acquire', tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC) + record['publication']['slot'] = slot + primary = None + try: + record['publication']['phase'] = 'WRITING' + offset = 0 + while offset < len(raw): + n = os.write(slot[0], raw[offset:offset + 65536]) + need(type(n) is int and 0 < n <= min(65536, len(raw) - offset), 'progressing exact write') + offset += n + os.fchmod(slot[0], mode) + os.fsync(slot[0]) + except BaseException as e: + primary = fail(record, e) + finally: + if slot[1] == 'OWNED': + try: + guarded_io('close', slot) + except BaseException as e: + primary = fail(record, e) + if primary is not None: + raise primary + # Keep all partial/failed artifacts; there is no automatic unlink/retry catch. + need(read(record, pinned(tmp, raw, mode)) == raw, 'complete staged readback') + sync_dir(record, STAGE) + record['publication']['phase'] = 'COMMIT_PENDING' + if replace_head: + need(path == HEAD, 'only exact HEAD is replaceable') + os.replace(tmp, path) + else: + os.link(tmp, path, follow_symlinks=False) # Atomic no-overwrite publication. + sync_dir(record, path.parent) + os.unlink(tmp) # Only the actual known-created, closed staged file. + sync_dir(record, STAGE) + sync_dir(record, path.parent) + result = pinned(path, raw, mode) + need(read(record, result) == raw, 'final publication/custody readback') + stage_empty() + record['publication']['phase'] = 'COMMITTED' + return result + + def head(record, pin_expected): + verify(record); stage_empty(); directory(HEADS); F.pin(pin_expected) + need(pin_expected['path'] == str(HEAD) and pin_expected['mode'] == 0o600, 'exact current HEAD pin') + raw = read(record, pin_expected); obj = F.decode(raw) + F.exact(obj, ('schema', 'sequence', 'registry_pin', 'previous_head_sha256')) + need(obj['schema'] == 'fresh-active-head-v1' and type(obj['sequence']) is int and + 0 <= obj['sequence'] <= 2 * F.MAX_ENTRIES, 'bounded head generation') + seq = obj['sequence']; F.pin(obj['registry_pin']) + need(obj['registry_pin']['path'] == str(CONTROL / ('REGISTRY-%06d.json' % seq)), 'head registry generation') + expected_heads = {'HEAD-%06d.json' % n for n in range(seq + 1)} + need(set(guarded_io('names', HEADS, 2 * F.MAX_ENTRIES + 2)) == expected_heads, 'exact head history census') + need(read(record, pinned(HEADS / ('HEAD-%06d.json' % seq), raw, 0o600)) == raw, 'current immutable head history') + names = guarded_io('names', CONTROL, 1024) + need({n for n in names if n.startswith('REGISTRY-')} == + {'REGISTRY-%06d.json' % n for n in range(seq + 1)}, 'no unadopted registry generation') + reg_raw = read(record, obj['registry_pin']); F.registry(reg_raw) + return obj, raw, reg_raw + + def advance(record, current, current_raw, old_registry_raw, new_registry, opening_transition=None): + verify(record); stage_empty() + F.plain(new_registry); new_raw = canonical(new_registry) + F.require_append_only(old_registry_raw, new_raw, opening_transition) + seq = current['sequence'] + 1 + need(seq <= 2 * F.MAX_ENTRIES, 'registry generation cap') + registry_pin = publish(record, CONTROL / ('REGISTRY-%06d.json' % seq), new_raw, 0o444) + next_head = {'schema': 'fresh-active-head-v1', 'sequence': seq, + 'registry_pin': registry_pin, 'previous_head_sha256': hashlib.sha256(current_raw).hexdigest()} + raw = canonical(next_head) + publish(record, HEADS / ('HEAD-%06d.json' % seq), raw, 0o600) + need(read(record, record['head_pin']) == current_raw, 'no stale head adoption') + record['head_pin'] = publish(record, HEAD, raw, 0o600, replace_head=True) + adopted, adopted_raw, adopted_registry = head(record, record['head_pin']) + need(adopted_raw == raw and adopted_registry == new_raw, 'durable exact head adopted') + return adopted, adopted_raw, adopted_registry + + def current_registry_pin(record): + current, _, _ = head(record, record['head_pin']) + return current['registry_pin'] + + def active_view(record): + verify(record) + guard(record, 'ACTIVE') + need(record['phase'] == 'ACTIVE' and record['request'] is not None, 'actual ACTIVE reservation') + current, current_raw, reg_raw = head(record, record['head_pin']) + snap = funding_io('snapshot_round', current['registry_pin'], os.getuid()) + old_raw = read(record, record['baseline_registry_pin']) + old, _, old_starts, old_closes = F.registry(old_raw) + reg, _, starts, closes = F.registry(reg_raw) + name = record['request']['label'] + F.require_append_only(old_raw, reg_raw) + need(reg['events'] == old['events'] + [{'kind': 'REGISTER', 'label': name, 'pin': record['start_pin']}] and + reg['policies'] == old['policies'] and reg['phase'] == old['phase'] and + set(old_starts) == set(old_closes) and set(starts) - set(closes) == {name}, + 'exact own pending reservation only; every other entry closed') + need(snap['records'][name]['receipt'] is None and + snap['records'][name]['start'] == record['start'], 'actual current START/source reservation') + # A separately checked accounting prefix, NOT a filtered current ledger. + # Own reservation remains in request and the current registry stays pending. + prefix = dict(snap, registry=old, registry_pin=record['baseline_registry_pin'], + records={k: snap['records'][k] for k in old_starts}) + result = F.assess_round(prefix, record['request']) + need(result['funding_data_eligible_only'] is True, 'prior debt/uncertainty or own reservation blocks') + return result + + def read_manual(record, expected_state_sha256=None): + verify(record) + guard(record, 'MANUAL') + need(manual is not None, 'same enclosing native operation original manual pre-entry binding is unconfigured') + F.exact(manual, ('schema', 'request', 'provenance', 'closed_state_pin', 'registration_checks', 'start_checks')) + need(manual['schema'] == 'fresh-active-manual-entry-binding-v1', 'selected original manual entry binding') + request, provenance = manual['request'], manual['provenance'] + F.validate_pre_entry_provenance(provenance, request['label'], request['command_sha256'], request['body_reservation_ns']) + state_raw = read(record, manual['closed_state_pin']) + F.metadata_decode(state_raw) # Current manually retained accepted-state DATA, not an owner. + if expected_state_sha256 is not None: + need(manual['closed_state_pin']['sha256'] == expected_state_sha256, 'all closed manual costs imported before new formal entry') + registration = F.metadata_decode(read(record, provenance['registration_pin'])) + original_start = F.metadata_decode(read(record, provenance['original_start_pin'])) + pending = F.metadata_decode(read(record, provenance['pending_manifest_pin'])) + F.exact(pending, ('schema', 'closed_state_sha256', 'operations')) + wanted = {'entry_id': request['label'], 'command_sha256': request['command_sha256'], + 'body_reservation_ns': request['body_reservation_ns'], + 'registration_pin': provenance['registration_pin'], 'original_start_pin': provenance['original_start_pin']} + need(pending['schema'] == 'fresh-current-manual-pending-v1' and + pending['closed_state_sha256'] == manual['closed_state_pin']['sha256'] and + pending['operations'] == [wanted], 'exact strongly-bound current enclosing pending operation only') + need(registration['attempt_id'] == request['label'], 'original one-use ID, never a new alias') + for document, checks in ((registration, manual['registration_checks']), (original_start, manual['start_checks'])): + need(type(checks) is list and 1 <= len(checks) <= 16, 'explicit original pre-entry field correlations') + for check in checks: + F.exact(check, ('path', 'expected')) + actual = F.select(document, check['path']) + need(type(actual) is type(check['expected']) and actual == check['expected'], 'original pre-entry provenance differs') + record['manual_request'] = F.decode(canonical(request)) + record['manual_provenance'] = F.decode(canonical(provenance)) + return record['manual_provenance'] + + class Context: + __slots__ = () + def __new__(cls, key): + need(key is sentinel, 'source-private construction only') + return object.__new__(cls) + + def initialize(self, initial_registry_raw): + r = rec(self) + try: + verify(r); guard(r, 'INITIALIZE'); need(r['phase'] == 'HELD' and expected is None and role == 'PUBLISHER', 'one initial publisher') + need(opening is not None and opening['funding_source_sha256'] == FUNDING_SHA, 'current selected funding/opening binding') + selected = funding_io('validate_opening_binding', opening, os.getuid()) + read_manual(r, F.opening_evidence(selected)['state_sha256']) + reg, _, starts, closes = F.registry(initial_registry_raw) + need(not starts and not closes and reg['predecessor_sha256'] is None and + reg['opening_pin'] == selected['opening_pin'], 'empty new registry with complete selected current opening') + for p in (DOMAIN.parent, DOMAIN, STAGE, HEADS, HANDOFFS, CLAIMS): + if not p.exists(): + os.mkdir(p, 0o700) + directory(p) + sync_dir(r, p.parent) + need(guarded_io('names', DOMAIN, 2) == [] and guarded_io('names', HEADS, 2) == [] and + not HEAD.exists(), 'no prior/orphan initialization') + stage_empty() + rp = publish(r, CONTROL / 'REGISTRY-000000.json', initial_registry_raw, 0o444) + raw = canonical({'schema': 'fresh-active-head-v1', 'sequence': 0, + 'registry_pin': rp, 'previous_head_sha256': None}) + publish(r, HEADS / 'HEAD-000000.json', raw, 0o600) + r['head_pin'] = publish(r, HEAD, raw, 0o600) + head(r, r['head_pin']) + return F.decode(canonical(r['head_pin'])) + except BaseException as e: + raise fail(r, e) + + def refresh_opening(self): + r = rec(self) + try: + verify(r) + guard(r, 'REFRESH') + need(r['phase'] == 'HELD' and role in ('PUBLISHER', 'CONTROLLER') and opening is not None and + opening['funding_source_sha256'] == FUNDING_SHA, 'new actual owner and fixed approved current opening') + current, raw_head, raw_reg = head(r, r['head_pin']) + old_snapshot = funding_io('snapshot_round', current['registry_pin'], os.getuid()) + _, _, starts, closes = F.registry(raw_reg) + need(set(starts) == set(closes), 'every prior formal entry CLOSED before refresh') + selected = funding_io('validate_opening_binding', opening, os.getuid()) + read_manual(r, F.opening_evidence(selected)['state_sha256']) + need(old_snapshot['opening_snapshot']['opening_pin'] != selected['opening_pin'], 'new immutable closed-cost prefix required') + F.require_opening_append(old_snapshot['opening_snapshot'], selected) + transition = {'previous': old_snapshot['opening_snapshot'], 'current': selected, + 'records': old_snapshot['records']} + new = F.decode(raw_reg); new['predecessor_sha256'] = hashlib.sha256(raw_reg).hexdigest() + new['opening_pin'] = selected['opening_pin'] + advance(r, current, raw_head, raw_reg, new, transition) + refreshed = funding_io('snapshot_round', current_registry_pin(r), os.getuid()) + need(refreshed['opening_snapshot'] == selected and refreshed['records'] == old_snapshot['records'], + 'opening-only refresh readback preserves every prior record/price') + # The prelude is part of this actual enclosing body under its ORIGINAL + # manual pre-entry START. No formal START or cost is backdated. + return {'schema': 'fresh-current-opening-refresh-observation-v1', 'head_pin': r['head_pin'], + 'opening_pin': selected['opening_pin'], 'formal_start_backdated': False, + 'native_capability': False, 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def current_binding(self): + r = rec(self) + try: + active_view(r) + return F.decode(canonical({'schema': 'fresh-active-current-binding-v1', + 'request': r['request'], 'start': r['start'], 'start_pin': r['start_pin'], + 'head_pin': r['head_pin'], 'baseline_registry_pin': r['baseline_registry_pin'], + 'native_capability': False, 'execution_permission': False})) + except BaseException as e: + raise fail(r, e) + + def begin(self, request): + r = rec(self) + try: + verify(r); guard(r, 'HELD'); need(r['phase'] == 'HELD' and role in ('PUBLISHER', 'CONTROLLER'), 'begin once') + F.plain(request) + current, raw_head, raw_reg = head(r, r['head_pin']) + snapshot = funding_io('snapshot_round', current['registry_pin'], os.getuid()) + read_manual(r, F.opening_evidence(snapshot['opening_snapshot'])['state_sha256']) + need(request == r['manual_request'], 'formal entry is the SAME original manually reserved enclosing operation') + assessment = F.assess_round(snapshot, request) + need(assessment['funding_data_eligible_only'] is True, 'NEW admission blocked') + r['request'] = F.decode(canonical(request)); r['baseline_registry_pin'] = current['registry_pin'] + r['phase'] = 'START_PUBLICATION_PENDING' # Private role/request precedes any mkdir/open. + name = r['request']['label']; folder = DOMAIN / name + r['start'] = {'schema': 'fresh-round-start-v1', 'round_id': F.ROUND_ID, + 'label': name, 'command_sha256': request['command_sha256'], + 'body_reservation_ns': request['body_reservation_ns'], 'policy_sha256': request['policy_sha256'], + 'pre_entry_provenance': r['manual_provenance']} + os.mkdir(folder, 0o700); sync_dir(r, DOMAIN) + r['start_pin'] = publish(r, folder / 'START.json', canonical(r['start']), 0o600) + new = F.decode(raw_reg); new['predecessor_sha256'] = hashlib.sha256(raw_reg).hexdigest() + new['events'].append({'kind': 'REGISTER', 'label': name, 'pin': r['start_pin']}) + advance(r, current, raw_head, raw_reg, new) + r['phase'] = 'ACTIVE' + active_view(r) + return {'schema': 'active-registration-observation-v1', 'start_pin': r['start_pin'], + 'head_pin': r['head_pin'], 'native_capability': False, 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def native_lease_for_controller(self, caller_module, actual_registry=None, purpose='PRODUCTION'): + r = rec(self) + try: + need(role == 'CONTROLLER' and caller_module is C and r['phase'] == 'ACTIVE', + 'same authenticated controller module and ACTIVE actual owner') + if actual_registry is None: + need(purpose == 'PRODUCTION', 'no registry-free cleanup/retention exemption') + verify(r) + guard(r, 'ACTIVE') + else: + need(purpose in ('CLEANUP','RETENTION'), 'fixed source-owned continuation purpose') + kernel_integrity(r['lease']) + need(cg.get('joined_continuation_check') is continuation_image[0], + 'actual fixed C2 continuation verifier') + unchanged_function(continuation_image, cg) + # Actual source function, same private registry/ctx, no DATA + # Boolean grants. It proves the known lifecycle before this + # one narrow original-error continuation can exist. + need(continuation_image[0](self, actual_registry, purpose) is True, + 'actual known cleanup/sealed retention continuation absent') + old = r.get('continuation') + need(old is None or (old['registry'] is actual_registry and + (old['first'] is None or old['first'] is first_state[0])), 'same registry and retained actual original failure') + r['continuation'] = {'registry':actual_registry,'purpose':purpose,'first':first_state[0]} + verify(r, allow_original_failure=True) + guard(r, 'RETENTION' if purpose == 'RETENTION' else 'ACTIVE') + return r['lease'] # Same actual original C2 EX/OFD; never serialized to B. + except BaseException as e: + raise fail(r, e) + + def check(self, nested_ns, cleanup_ns): + r = rec(self) + try: + F.uint(nested_ns); F.uint(cleanup_ns) + assessment = active_view(r) + now = time.monotonic_ns() + need(type(now) is int and now >= r['protocol_anchor_ns'], 'actual local monotonic sample') + elapsed = now - r['protocol_anchor_ns'] + need(elapsed + nested_ns + cleanup_ns <= r['request']['body_reservation_ns'], 'retained body reservation locally exhausted') + return {'schema': 'active-local-reservation-observation-v1', 'elapsed_since_protocol_anchor_ns': elapsed, + 'local_reservation_check_passed': True, 'whole_outer_body_fit_proved': False, + 'clock_scope': 'private_protocol_anchor_to_local_sample_imports_and_final_exit_excluded', + 'unallocated_policy_ns': assessment['remaining_policy_ns'] - assessment['requested_reservation_ns'], + 'own_reservation_encumbered_ns': assessment['requested_reservation_ns'], 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def release_for_exec(self): + r = rec(self) + try: + active_view(r); need(role == 'PUBLISHER', 'separate publisher owner only') + intent = {'schema': 'fresh-active-handoff-intent-v1', 'source_role': role, 'destination_role': 'CONTROLLER', + 'request': r['request'], 'start': r['start'], 'start_pin': r['start_pin'], + 'head_pin': r['head_pin'], 'baseline_registry_pin': r['baseline_registry_pin'], + 'protocol_anchor_ns': r['protocol_anchor_ns'], 'native_capability_transferred': False} + r['phase'] = 'HANDOFF_PUBLICATION_PENDING' + p = publish(r, HANDOFFS / (r['request']['label'] + '.json'), canonical(intent), 0o444) + verify(r); r['phase'] = 'CLOSE_ENTERED'; close_actual(r); r['phase'] = 'RELEASED' + return p # Permission/timing DATA only. No FD/owner survives this API. + except BaseException as e: + raise fail(r, e) + + def adopt_handoff(self): + r = rec(self) + try: + verify(r); guard(r, 'ADOPT'); need(role == 'CONTROLLER' and r['phase'] == 'HELD' and handoff is not None, 'fresh actual controller owner plus approved intent') + intent = F.decode(read(r, handoff)) + F.exact(intent, ('schema', 'source_role', 'destination_role', 'request', 'start', 'start_pin', + 'head_pin', 'baseline_registry_pin', 'protocol_anchor_ns', 'native_capability_transferred')) + need(intent['schema'] == 'fresh-active-handoff-intent-v1' and intent['source_role'] == 'PUBLISHER' and + intent['destination_role'] == role and intent['native_capability_transferred'] is False and + intent['head_pin'] == r['head_pin'], 'exact data intent/current head') + for k in ('request', 'start', 'start_pin', 'baseline_registry_pin'): + r[k] = intent[k] + F.uint(intent['protocol_anchor_ns']) + # Cross-process clock-domain applicability is an external role-profile premise. + r['protocol_anchor_ns'] = intent['protocol_anchor_ns'] + r['phase'] = 'ACTIVE' + selected_head = current_registry_pin(r) + selected_snapshot = funding_io('snapshot_round', selected_head, os.getuid()) + read_manual(r, F.opening_evidence(selected_snapshot['opening_snapshot'])['state_sha256']) + need(r['request'] == r['manual_request'] and r['start']['pre_entry_provenance'] == r['manual_provenance'], + 'handoff is same original enclosing operation') + active_view(r) + claim = {'schema': 'fresh-active-handoff-claim-v1', 'handoff_sha256': handoff['sha256'], + 'start_sha256': r['start_pin']['sha256'], 'native_owner_is_not_this_record': True} + publish(r, CLAIMS / (r['request']['label'] + '.json'), canonical(claim), 0o444) + return {'handoff_claimed': True, 'new_real_lease_acquired': True, 'native_capability': False, 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def publish_reviewed_close(self): + r = rec(self) + try: + verify(r); need(role == 'CLOSER' and r['phase'] == 'HELD' and closure is not None, + 'new actual closer plus independently accepted frozen evidence') + read_manual(r) # The CLOSER has its OWN separately funded native body, never admin-filled. + F.exact(closure, ('request', 'start', 'start_pin', 'baseline_registry_pin', 'receipt_pin', 'review_pin')) + for k in ('request', 'start', 'start_pin', 'baseline_registry_pin'): + r[k] = closure[k] + r['phase'] = 'ACTIVE'; active_view(r) + F.pin(closure['receipt_pin']); F.pin(closure['review_pin']) + need(Path(closure['receipt_pin']['path']).parent == CONTROL and + Path(closure['review_pin']['path']).is_relative_to(R / 'review') and + closure['receipt_pin']['mode'] == closure['review_pin']['mode'] == 0o444, + 'selected frozen close candidate/review namespace') + review_raw = read(r, closure['review_pin']) # Opaque independently accepted evidence, never native authority. + raw = read(r, closure['receipt_pin']); receipt = F.decode(raw) + need(receipt['schema'] == 'fresh-round-receipt-v1' and receipt['round_id'] == F.ROUND_ID and + receipt['label'] == r['request']['label'] and receipt['start_sha256'] == r['start_pin']['sha256'] and + receipt['independent_outcome_review_sha256'] == hashlib.sha256(review_raw).hexdigest(), 'exact reviewed body/uncertainty record') + F.exact(receipt, ('schema', 'round_id', 'label', 'start_sha256', 'outcome', 'body_elapsed_ns', + 'administrative_debit_ns', 'body_begin_ns', 'body_end_ns', 'body_fully_observed', + 'cleanup_known', 'custody_complete', 'nested_entries_complete', 'uncertainty', + 'peak_sampled_rss_bytes', 'tail_state', 'independent_outcome_review_sha256')) + need(receipt['outcome'] == 'STOP' and receipt['cleanup_known'] is False and + receipt['tail_state'] == 'UNKNOWN' and receipt['uncertainty'] is not None, + 'metadata-only CLOSER records STOP/UNKNOWN; native success needs separate source adoption') + need(receipt['outcome'] in ('PASS', 'STOP') and + receipt['tail_state'] in ('COMPLETE', 'ADMIN_ONLY_OPEN', 'UNKNOWN'), 'retained outcome/unknown scope') + for key in ('body_fully_observed', 'cleanup_known', 'custody_complete', 'nested_entries_complete'): + need(type(receipt[key]) is bool, 'exact qualification flag') + if receipt['body_elapsed_ns'] is not None: + F.uint(receipt['body_elapsed_ns']); F.uint(receipt['body_begin_ns']); F.uint(receipt['body_end_ns']) + need(receipt['body_end_ns'] >= receipt['body_begin_ns'] and + receipt['body_end_ns'] - receipt['body_begin_ns'] == receipt['body_elapsed_ns'], 'exact reviewed body interval') + F.uint(receipt['administrative_debit_ns']) + policy_snapshot = funding_io('snapshot_round', current_registry_pin(r), os.getuid()) + policy = policy_snapshot['policies'][r['request']['policy_sha256']] + need(receipt['administrative_debit_ns'] == policy['administrative_debit_ns'], 'separate exact admin policy') + # No field is invented from local check(), PID/FD observations, or caller booleans. + # Genuine whole-body/cleanup/review acceptance is the trusted closer-source premise. + current, raw_head, raw_reg = head(r, r['head_pin']) + r['phase'] = 'RECEIPT_PUBLICATION_PENDING' + rp = publish(r, DOMAIN / r['request']['label'] / 'receipt.json', raw, 0o600) + new = F.decode(raw_reg); new['predecessor_sha256'] = hashlib.sha256(raw_reg).hexdigest() + new['events'].append({'kind': 'CLOSE', 'label': r['request']['label'], 'pin': rp}) + advance(r, current, raw_head, raw_reg, new) + r['phase'] = 'RECORDED_NOT_PHYSICALLY_SETTLED' + return {'receipt_pin': rp, 'head_pin': r['head_pin'], 'all_costs_settled': False, 'execution_permission': False} + except BaseException as e: + raise fail(r, e) + + def release(self): + r = rec(self) + need(r['phase'] not in ('RELEASED', 'CLOSE_UNKNOWN'), 'one actual close attempt') + try: + r['phase'] = 'CLOSE_ENTERED' + close_actual(r) + r['phase'] = 'RELEASED' + except BaseException as e: + r['phase'] = 'CLOSE_UNKNOWN' + if r['first'] is None: + r['first'] = e + raise r['first'] + + context_image, context_functions = class_image(Context, + ('initialize', 'refresh_opening', 'current_binding', 'begin', 'native_lease_for_controller', + 'check', 'release_for_exec', 'adopt_handoff', 'publish_reviewed_close', 'release'), + active_globals, slotted=True) + + def open_owner(): + need(opened[0] is False, 'one context per exact bound source-role invocation') + opened[0] = True + unchanged_class(Context, context_image, context_functions, active_globals) + ctx = Context(sentinel) + r = {'role': role, 'pid': os.getpid(), 'lease': None, 'birth': None, + 'phase': 'PRIVATE_BEFORE_ACQUIRE', 'first': None, 'secondary': [], 'secondary_saturated': False, + 'request': None, 'head_pin': expected, 'publication': None, + 'protocol_anchor_ns': None, 'lease_close_entered': False, + 'lease_initialized': False, 'lease_acquire_entered': False, 'owned_fd': None, + 'kernel_memory_uncertain': False} + contexts[ctx] = r # Private ownership/role identity BEFORE fallible initialization/acquire. + try: + guard(r, 'BOOTSTRAP') + values = kernel_integrity() + need(all(slot[1] in ('FREE', 'CLOSED') for slot in values['slots']), + 'fresh role begins with no borrowed/pending IO slot') + r['protocol_anchor_ns'] = time.monotonic_ns() # Partial local window only. + need(type(r['protocol_anchor_ns']) is int and r['protocol_anchor_ns'] >= 0, 'genuine finite local protocol anchor') + unchanged_class(LeaseType, lease_image, lease_functions, cg) + r['lease'] = object.__new__(LeaseType) # No metaclass/class __call__/foreign __new__ dispatch. + lease_state(r['lease'], fields=set()) + lease_image['__init__'](r['lease']) + r['lease_initialized'] = True + kernel_integrity(r['lease']) + r['phase'] = 'ACQUIRE_PENDING'; r['lease_acquire_entered'] = True + lease_image['acquire'](r['lease']) + kernel_integrity(r['lease']) + acquired = lease_state(r['lease']) + r['owned_fd'] = acquired['fd']; r['birth'] = dict(acquired['birth']) + r['phase'] = 'HELD'; verify(r) + return ctx + except BaseException as e: + fail(r, e) + # Exactly one actual cleanup entry; unsafe metadata remains unknown debt, + # never guessed/replayed descriptor cleanup or a reconstructed owner. + try: + close_actual(r) + except BaseException as close_error: + fail(r, close_error) + raise r['first'] + + return open_owner diff --git a/research/h25-complete-outcome-close/review/REVIEW-v1-findings.md b/research/h25-complete-outcome-close/review/REVIEW-v1-findings.md new file mode 100644 index 0000000000..d09082480b --- /dev/null +++ b/research/h25-complete-outcome-close/review/REVIEW-v1-findings.md @@ -0,0 +1,40 @@ +# Independent source review, first findings + +This is a source-only review. No reviewed module was imported or executed, no native owner was acquired, and no tests, compiler, science job, network operation, or publication was run by this reviewer. The reviewer owns only this review directory and has not edited implementation files. + +Reviewed source snapshot: `active_complete_close.reviewed-v1.py.txt`, SHA256 `4f299555d97828b791540176311639803b58ca12061e3097e5aecc73737f7a2b`. The implementation was changing during initial reads, so this copied snapshot fixes the findings below. The originally supplied `68a410ec31ab47b7ae57dc6c675a8a59675c65f85714790d1aac8d3fa5f19778` was also observed by SHA256 before the snapshot was copied; this report's line references concern the fixed `4f299...` snapshot. + +Reference owner: `outputs/s04-resource-fit-20261106T0200Z/inputs/exact/selected_owner.py.txt`, SHA256 `e94ee23f4f66b16f9d5a0b7f1cc510952d1769247283062d9124737d7838ce3c`. + +Reference funding: `outputs/s04-resource-fit-20261106T0200Z/inputs/exact/selected_funding.py.txt`, SHA256 `164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677`. + +Completed advice: `outputs/s04-complete-close-20261106T0438Z/consultation/RESPONSE-v1-complete.md`, SHA256 `81b702ad20ac0dfcdac0a098b994748c897ffd09c5eafc1997de5b96329d0ea2`. + +## Blocking findings at this snapshot + +1. **The new complete validator lacks request-to-actual-START correlations.** Lines 176-188 correlate admission with the selected request and independently bind an admission registration pin to START provenance. They never require the request command, policy, reservation, round, and label to equal the actual START fields. The unchanged `active_view` checks the actual snapshot START equals the selected `start`, then assesses the proposed `request` against the predecessor prefix separately. In a registry with another valid adopted policy/command, same-label request B and actual START A can therefore satisfy those two checks independently. A receipt/evidence package can be internally bound to B while carrying A's START hash. Before publication, require exact shared request/START values, correct schemas/round, and `validate_pre_entry_provenance` for that same request. A mutation control must use an otherwise valid alternative request/policy so a generic malformed-request failure does not mask this gap. + +2. **The new protected primary slot ignores an established original primary when the private first slot is empty.** Lines 727-732 choose private `record['first']` or the newly caught exception, before consulting the original `first_state[0]`. If original error A already exists and initial `verify` rejects continuation with error B, B is promoted as private primary, whereas unchanged `fail` would preserve authenticated A. Preserve the established original primary under the captured error-container integrity contract before any optional recorder call. Do not claim universal allocation-safe capture; the review is limited to new bookkeeping after catch. + +3. **Release can miss complete-branch error custody when first verification fails before consumption.** At lines 750-753, `verify` may fail before `complete_used=True`; `complete_failure` still records the exception. Lines 1063-1068 then route a later cleanup error through protected handling only if `complete_used` is true. Otherwise an existing private primary causes that cleanup secondary to be discarded by the legacy branch. Select complete release handling from the privately selected complete branch, or from that branch's protected-error state, while preserving legacy behavior when no complete closure is selected. Preserve the once-only lease-close boundary if helper bookkeeping changes the `CLOSE_UNKNOWN` phase. + +These findings were sent immediately to the implementation owner. They require review of a new exact source hash before source-only acceptance. + +## Supported source properties and boundaries + +- The optional branch preserves the legacy six-field STOP/UNKNOWN method body and the ten-method `Context` set. `exact` and `digest` are included in captured funding function identities at this snapshot. +- The branch keeps the closer's original manual request/provenance separately, uses the closer's reservation for its local protocol-window check, and checks a selected clock lineage for target-terminal-before-closer ordering. That local sample does not measure startup, release, or final exit. +- Evidence acceptance remains an explicit authenticated source-private parent premise. Pinned JSON, a review decision, hashes, and raw-manifest entries are consistency data and do not authenticate native outcomes. The source does not reread large raw inventories; complete custody and genuine independent acceptance remain external obligations. +- The receipt projection omits only `independent_outcome_review_sha256`, avoiding a receipt/review digest cycle. The original final receipt bytes are passed unchanged to publication. +- The complete validator constructs receipt, registry, and next-HEAD images and checks registry/append semantics, generation capacity, and metadata limits before the first receipt publication. It reuses the selected original publication and advancement functions, and compares durable readback against precomputed bytes. Post-write IO or allocation failures remain uncertain evidence; there is no rollback or repair. +- Resource-invalid PASS and known STOP must retain their actual observed cost and RSS values. This snapshot correctly leaves them recordable without a fit grant; unchanged funding assessment adds reservation/RSS blockers on later admission. Rejecting all such PASS receipts would prevent truthful accounting. +- There is no G clearing or grant. Successful return keeps costs unsettled and native/execution capabilities false. Closing the target does not settle the closer's enclosing operation. +- No genuine bootstrap/caller adoption was supplied or reviewed. The copied owner extension is not proof that an authenticated caller loads it, that owner/loader/detached manifests name the new source, or that authentic accepted target evidence exists. Those bindings must be explicit before connected runtime adoption can be accepted. + +## Test-plan assessment + +The owner's proposed AST extraction of the whole actual pure validator, new complete method/helper, and actual dispatch/release methods into inert ports is appropriate for source-only behavioral evidence. No native execution is needed for those checks. Required additions are the three findings' exact counterexamples, including original A with private first empty, initial verification failure before consumption, cleanup B, and optional recorder C. Both smaller and larger own-versus-target reservation controls are needed. + +To claim failures at each registry publication, HEAD-history publication, HEAD replacement, and durable readback phase, run the actual unchanged `advance` source with inert ports; similarly use actual `publish` with inert native ports if claiming its individual internal write/link/readback phases. A single failing stub for `advance` or `publish` supports only failure at that exposed call boundary. Preserve that distinction in result labels. + +Current verdict: **CHANGES REQUIRED for the exact reviewed source; GO to build a bounded inert source harness after repairs.** No native ownership, complete original activity, resource fit, scientific acceptance, S04 completion, publication, or runtime adoption is accepted by this report. diff --git a/research/h25-complete-outcome-close/review/REVIEW-v2-final-source.md b/research/h25-complete-outcome-close/review/REVIEW-v2-final-source.md new file mode 100644 index 0000000000..f465bc3ed2 --- /dev/null +++ b/research/h25-complete-outcome-close/review/REVIEW-v2-final-source.md @@ -0,0 +1,58 @@ +# Independent complete-close source review + +Review finished at 2026-11-06 05:12 UTC, before the 05:23:11 UTC review checkpoint and 05:38:11 UTC hard source deadline. This reviewer read source and wrote review artifacts only. No reviewed module was imported or executed, and this reviewer ran no tests, native owner, compiler, science job, process inspection, network operation, or publication. + +## Exact reviewed inputs + +| Input | SHA256 | +|---|---| +| Frozen owning successor `implementation/active_complete_close_v1.py` | `9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380` | +| Frozen inert harness `validation/controls_v1.py` | `81ef02f0f8cb2b45fb03f6cbf2fee462a8b021602b2031699d3a31116cc5b25f` | +| Exact original owner `outputs/s04-resource-fit-20261106T0200Z/inputs/exact/selected_owner.py.txt` | `e94ee23f4f66b16f9d5a0b7f1cc510952d1769247283062d9124737d7838ce3c` | +| Portable copied owner `reference/active_original.py.txt` | `e94ee23f4f66b16f9d5a0b7f1cc510952d1769247283062d9124737d7838ce3c` | +| Exact original and unchanged copied funding | `164468176d2094fbd496eecfd0d0adf3b6ceaf89b2573456509157cc26256677` | +| Completed Pro advice `consultation/RESPONSE-v1-complete.md` | `81b702ad20ac0dfcdac0a098b994748c897ffd09c5eafc1997de5b96329d0ea2` | + +Paths without an absolute prefix in the table are relative to `outputs/s04-complete-close-20261106T0438Z/`. The independent frozen successor copy is `review/independent/active_complete_close.reviewed-v2.py.txt`; the final independent harness copy is `review/independent/controls.reviewed-v3.py.txt`. + +The earlier rejected source snapshot and `REVIEW-v1-findings.md` remain preserved. This report resolves those findings for the new exact source hash, rather than altering the earlier verdict. + +## Source verdict + +**GO_SOURCE_COMPONENT_ONLY.** The reviewed optional complete-close branch is source-consistent with the supplied original owner, unchanged funding source, and completed advice at the boundaries below. The three defects reported for the earlier `4f299...` snapshot are repaired: + +1. The validator now checks request/START schemas, exact shared round/label/command/reservation/policy values and types, the selected round, and pre-entry provenance against that same request. The actual registered START remains checked by unchanged `active_view`. +2. The complete error helper first protects a caught object, then preserves an established original primary from the captured actual `FIRST` list when the private primary is empty, before optional recorder work. It retains the new caught error as secondary when an earlier primary exists. This is a review of new bookkeeping after catch, not a universal allocation-safe exception theorem or a repair to every inherited pre-handler path. +3. Complete-branch release error handling now follows the privately selected complete branch even when initial verification failed before `complete_used` was set. It restores `CLOSE_UNKNOWN` after protected error recording, retaining the once-only release boundary. The unchanged actual close helper also preserves its native-close entry flag. + +No further blocking defect was found in that repaired source during this bounded review. This finding does not state that all required behavioral controls have passed; the parent has not supplied execution results to this reviewer at the time of this report. + +## Reviewed contracts and remaining premises + +- The optional new argument has a separate seven-field closure shape with a closed versioned binding. It is restricted to CLOSER and excludes the legacy closure argument. Native DATA validation and private copying occur before `open_owner` can acquire a lease. The legacy six-field STOP/UNKNOWN close body and ten-method Context interface remain intact. Funding `exact` and `digest` identities are captured along with the pre-existing selected functions. +- Every actual context still acquires its own selected native EX through the unchanged owner. JSON data, hashes, review decisions, result labels, and the bounded raw-input inventory do not manufacture that ownership or authenticate a native outcome. +- Genuine complete evidence acceptance, original pre-outcome result-contract selection, full raw-evidence custody, and clock lineage remain explicit authenticated source-private parent/reviewer premises. The closer reads pinned bounded metadata, not arbitrary large raw captures. The source cannot establish those external premises from a synthetically consistent packet. +- The closer retains separate original manual request/provenance slots. The continuation sample uses its own reservation; target elapsed time validates the target receipt. Target command and operation identity differ from the closer's, and the selected original clock selector establishes target terminal time no later than the closer's original start. Startup, release, final exit, and complete closer accounting remain responsibilities of the original enclosing meter/admission. +- Review binding is acyclic: the review commits to the canonical receipt projection omitting only the review-digest field and to the complete evidence binding. The final receipt carries the raw review digest. Publication passes the selected original final receipt bytes unchanged. +- Before first receipt publication, the new branch checks current target ownership/view, all selected metadata correlations, prospective receipt pin, exact single CLOSE append, registry and append-only semantics, generation capacity, and metadata size limits for the prospective registry and HEAD. It rechecks HEAD/current registry immediately before writing. It compares publication pins and durable registry/HEAD readback with the precomputed images. +- IO/allocation failures after publication begins remain uncertain evidence. The branch has one-use state and no automatic retry, rollback, deletion, or repair. Known owned cleanup remains available; unknown ownership is not guessed. +- A truthfully observed resource-invalid PASS or known STOP remains recordable with actual duration and sampled RSS unchanged. The extension makes no resource-fit grant. Unchanged funding assessment retains reservation and RSS blockers for later admission. Successful record publication does not supply scientific credit or settle the closer's own operation. +- The branch does not clear G or confer a native or execution capability. Successful return explicitly retains unsettled costs and false capability/permission fields. + +## Harness and proposed command source + +**GO_COMMAND_SOURCE_ONLY** for the exact final harness hash in the table and unchanged selected source/reference hashes, limited to the parent's two proposed serialized controls: one normal Python invocation, then one optimized invocation with `-O`. The reviewer does not execute these commands. + +The proposed command envelope is suitable for this source-only control scope: `/usr/bin/time` records bounded observations; `timeout --signal=TERM --kill-after=2s 20s` encloses `prlimit` with address space 268435456 bytes, CPU 20 seconds, file size 1048576 bytes, and descriptor cap 256. The sanitized environment and `/usr/bin/python3 -S -s -P -B` avoid site loading, user packages, and bytecode writes. Add `-O` only for the second invocation. Preserve the proposed two 25-second body reservations and two 2-second administrative fees, 54 seconds total posted policy amount, while recording actual observations truthfully. No unchanged retry or additional execution is covered by this verdict. + +The harness AST-extracts the whole actual complete validator, complete method/helper, dispatch/release methods, and unchanged `advance`, together with selected unchanged funding DATA functions. Publication, HEAD, ownership checks, manual entry, clock, UID, cleanup, and funding IO use inert ports. It does not import the archived owner/controller/funding modules or call their native ports. + +The final source includes positive full outcome, selected expected-refusal, and selected known-STOP cases; identity/evidence mutations; resource-invalid STOP and original PASS with actual figures; legacy body/method-set compatibility; replay; role/current-HEAD refusal; metadata and generation limits; primary/secondary custody including initial verification before consumption; and both own-versus-target reservation directions. The negative reservation discriminator is own=5, target=10, local sample=7; the reverse positive is own=2000, target=10, local sample=1000. + +Coverage limits must accompany any resulting count. The five staged failures exercise actual `advance` at the receipt, registry, history, HEAD, and final readback call boundaries through an inert publication port. They do not execute the internal write, fsync, link, or close phases of unchanged `publish`. Input binding before acquisition is source-reviewed, not executed by this harness. Real `active_view`, native ownership, independent acceptance, full raw-evidence custody, and live profile/funding state are not qualified by the inert fixture. Controls do not directly execute the downstream funding blocker path, whose retention is established here by comparison to unchanged original funding source. + +## Adoption and original-acceptance boundary + +**CONNECTED_CALLER_ADOPTION_NOT_ACCEPTED.** No actual source-private bootstrap/caller selection of this successor, updated owner/loader source pin, or detached source-manifest binding was supplied for review. Preserving method names and capturing the new fixed validator internally do not preserve the predecessor source identity automatically. The closer's actual authenticated load chain must explicitly select successor SHA256 `9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380` when adoption is performed. The unchanged funding source remains pinned to its unchanged hash. Historical target source/profile bindings must continue to describe the actual admitted target image; they must not be rewritten as if that target had executed the new closer source. + +Accordingly, this review accepts the owning extension only as a bounded source component and accepts the exact proposed inert commands as suitable source controls. It does not accept genuine native evidence, actual full-input execution, resource fit, scientific correctness, complete caller integration, a completed original S04.03/S04.04/S04.05 activity, publication, or S04 completion. The original decisive acceptance checks remain open beyond this component. diff --git a/research/h25-complete-outcome-close/review/REVIEW-v3-control-outcome.md b/research/h25-complete-outcome-close/review/REVIEW-v3-control-outcome.md new file mode 100644 index 0000000000..1ef54bab01 --- /dev/null +++ b/research/h25-complete-outcome-close/review/REVIEW-v3-control-outcome.md @@ -0,0 +1,32 @@ +# Independent finite-control outcome addendum + +At 2026-11-06 05:14 UTC, the reviewer read the two parent-produced bounded control outputs, GNU time records, empty stderr files, and selected `execution/LEDGER-002.json`. The reviewer did not execute either command. This addendum preserves and supplements `REVIEW-v2-final-source.md` and the earlier rejected evidence. + +**Verdict: ACCEPT_SOURCE_COMPONENT_AND_FINITE_CONTROLS_ONLY.** The owning successor remains SHA256 `9b4ddb537e46e0f7f5f09cab10e32cc9f8d1a6472b8612757b1da04a7155b380`; the reviewed harness remains SHA256 `81ef02f0f8cb2b45fb03f6cbf2fee462a8b021602b2031699d3a31116cc5b25f`. Current bytes were rehashed after execution and remain unchanged from source review. Both output records identify the same selected successor and unchanged funding source hashes. + +The normal and optimized reports each list the same **41 distinct defined checks: 40 finite behavioral controls and one static compatibility check**. Both report all 41 passed. This is 41 checks exercised in two modes, not 82 independent checks. The checks use the whole extracted validator and changed method/helper bodies, actual unchanged `advance`, and inert ports as detailed in the source report. The parent reports one execution per mode and no retry; the two supplied command records correspond to the normal invocation and its `-O` variant. + +| Supplied record | Normal | Optimized | +|---|---:|---:| +| Passed checks | 41 | 41 | +| Exit status | 0 | 0 | +| Stderr bytes | 0 | 0 | +| GNU time wall interval | 0.50 s | 0.40 s | +| GNU time user / system | 0.45 / 0.02 s | 0.39 / 0.01 s | +| GNU time maximum resident set | 29340 kB | 29356 kB | + +These observations concern only the two bounded finite-control invocations. They are not measurements of a full scientific invocation, original command/profile fit, aggregate target RSS, native ownership, or complete physical costs. + +Reviewed output SHA256 values: + +- `execution/normal-v1.stdout.json`: `36f05c75b1a82e1a6518b99ad72fd69c72a3dca52f72d2f316f285facc83fa52` +- `execution/optimized-v1.stdout.json`: `8b528424889c825e1e5622907e7363059b3c002e6cb055a2a1b1d087d8cc06ba` +- `execution/normal-v1.time.txt`: `33746e69d269b74fc342722aa573d52f20003710e34330b57cdc20ba896e8a7f` +- `execution/optimized-v1.time.txt`: `51c07b73033912f7c49ba679ad9fd910c5f8e38f52dc3b0795bd3f79274fe2eb` +- `execution/LEDGER-002.json`: `6224f7078f7b1eaa24c0db226fe380e0d67bdacc77e1766e9381fac38e731410` + +The selected ledger's arithmetic is consistent: reported prior recorded scope `1354.890533479` seconds plus the new conservative policy debit `54` seconds equals `1408.890533479` seconds; subtracting that from `2400` gives `991.109466521` seconds. The record states two completed attempts, no active batch, no outstanding reservation, no refunds, no new budget, and original-activity credit delta zero. This review checks that selected record and its arithmetic; it does not re-audit the prior ledger's complete custody or historical baseline. Physical costs and preparation, Pro, review, reporting, publication, final metadata, and historical costs remain `OPEN_NOT_ZERO` exactly as retained by the supplied record. + +No remaining blocking defect was found in the bounded reviewed extension after repairs and these finite controls. Coverage remains limited: the harness does not execute complete bind/acquisition validation, real `active_view`, native EX, authentic whole-body/custody evidence, current runtime/profile admission, or complete downstream funding eligibility. Its publication fault injection covers the exposed receipt/registry/history/HEAD/readback boundaries of actual `advance`; it does not execute internal filesystem writes, links, fsyncs, descriptor cleanup, or crash behavior inside actual `publish`. + +**Connected caller/source adoption remains unaccepted.** Genuine authenticated bootstrap selection, owner/loader and detached source-manifest bindings for the new closer hash, authentic target evidence production/acceptance, full original workload receiver/schedule, closer accounting and later original admission checks remain outstanding. This is a completed bounded source component plus finite-control assessment, with original activity credit zero. It is not S04.03/S04.04/S04.05 completion, scientific acceptance, native/runtime qualification, or publication approval. No further research execution or unchanged rerun is requested by this addendum. diff --git a/research/h25-complete-outcome-close/validation/controls_v1.py b/research/h25-complete-outcome-close/validation/controls_v1.py new file mode 100644 index 0000000000..f37e954d8a --- /dev/null +++ b/research/h25-complete-outcome-close/validation/controls_v1.py @@ -0,0 +1,224 @@ +"""New finite source-behaviour controls. Inert ports; NO native qualification. + +AST extracts complete actual changed functions and unchanged funding DATA +functions. It never imports an archived module or calls a real owner, process, +compiler, science command, filesystem publisher, or lock operation. +""" +import ast, copy, hashlib, json, os, stat, sys, types +from pathlib import Path + +ROOT=Path(__file__).resolve().parents[1] +SOURCE=ROOT/'implementation/active_complete_close_v1.py' +FUNDING=ROOT/'implementation/funding_current.py.txt' + +def extract(tree, names): + nodes=[x for x in ast.walk(tree) if isinstance(x,(ast.FunctionDef,ast.ClassDef)) and x.name in names] + if {x.name for x in nodes} != set(names): raise RuntimeError('missing exact source function') + return ast.Module(body=nodes,type_ignores=[]) + +ft=ast.parse(FUNDING.read_bytes());fg={'hashlib':hashlib,'json':json,'os':os,'stat':stat,'Path':Path} +constants=[x for x in ft.body if isinstance(x,ast.Assign)] +fnames=('need','plain','exact','uint','digest','label','pin','pairs','forbidden_number','decode','registry','require_append_only','select','validate_pre_entry_provenance') +exec(compile(ast.Module(body=constants+extract(ft,fnames+('FundingError',)).body,type_ignores=[]),str(FUNDING),'exec'),fg) +F=types.SimpleNamespace(**fg) +tree=ast.parse(SOURCE.read_bytes());ag={'hashlib':hashlib,'json':json,'Path':Path,'F':F,'os':os} +constants=[x for x in tree.body if isinstance(x,ast.Assign)] +exec(compile(ast.Module(body=constants+extract(tree,('ActiveError','need','canonical','exception_instance','complete_close_data')).body,type_ignores=[]),str(SOURCE),'exec'),ag) +canonical=ag['canonical'];sha=lambda b:hashlib.sha256(b).hexdigest() + +def pin(path,raw=b'x',mode=0o444): return dict(path=str(path),bytes=len(raw),sha256=sha(raw),mode=mode) + +def fixture(): + C,D=ag['CONTROL'],ag['DOMAIN'] + request=dict(schema='fresh-round-request-v1',round_id=F.ROUND_ID,label='target',command_sha256='1'*64,body_reservation_ns=10,policy_sha256='2'*64,phase_release_sha256=None) + registration=pin(C/'target-registration.json') + start=dict(schema='fresh-round-start-v1',round_id=F.ROUND_ID,label='target',command_sha256=request['command_sha256'],body_reservation_ns=10,policy_sha256='2'*64,pre_entry_provenance=dict(schema='fresh-original-preentry-provenance-v1',entry_id='target',command_sha256=request['command_sha256'],body_reservation_ns=10,registration_pin=registration,original_start_pin=pin(C/'original-target-start.json'),pending_manifest_pin=pin(C/'original-target-pending.json'))) + sp=pin(D/'target/START.json',canonical(start),0o600) + registry=dict(schema='fresh-round-registry-v2',round_id=F.ROUND_ID,authorization_sha256=F.AUTHORIZATION_SHA256,opening_pin=pin(C/'opening.json'),predecessor_sha256=None,phase='INITIAL',phase_release_sha256=None,policies=[dict(pin(C/'policy.json'),sha256='2'*64)],events=[dict(kind='REGISTER',label='target',pin=sp)]) + rr=canonical(registry);rh=canonical(dict(schema='fresh-active-head-v1',sequence=1,registry_pin=pin(C/'REGISTRY-000001.json',rr),previous_head_sha256='0'*64)) + hp=pin(ag['HEAD'],rh,0o600);base=pin(C/'REGISTRY-000000.json') + own=dict(request,label='closer',command_sha256='3'*64,body_reservation_ns=2000) + ownstart={'begin':100};ownprov={'original_start_pin':pin(C/'closer-start.json',canonical(ownstart))} + docs={'source_manifest_pin':b'original admitted source bytes','profile_pin':b'original admitted profile bytes','policy':{'administrative_debit_ns':2}} + b=dict(schema='complete-close-evidence-binding-v1',source_manifest_pin=pin(C/'source.json',docs['source_manifest_pin']),profile_pin=pin(C/'profile.json',docs['profile_pin']),expected_head_pin=hp,closer_start_clock_path=['begin']) + contract=dict(schema='complete-close-result-contract-v1',kind='FULL_POSITIVE',command_sha256=request['command_sha256'],source_manifest_pin=b['source_manifest_pin'],profile_pin=b['profile_pin']) + docs['result_contract_pin']=canonical(contract);b['result_contract_pin']=pin(C/'contract.json',docs['result_contract_pin']) + admission=dict(schema='complete-close-original-admission-v1',request=request,start_pin=sp,baseline_registry_pin=base,source_manifest_pin=b['source_manifest_pin'],profile_pin=b['profile_pin'],result_contract_pin=b['result_contract_pin'],registration_pin=registration) + docs['admission_pin']=canonical(admission);b['admission_pin']=pin(C/'admission.json',docs['admission_pin']) + receipt=dict(schema='fresh-round-receipt-v1',round_id=F.ROUND_ID,label='target',start_sha256=sp['sha256'],outcome='PASS',body_elapsed_ns=5,administrative_debit_ns=2,body_begin_ns=10,body_end_ns=15,body_fully_observed=True,cleanup_known=True,custody_complete=True,nested_entries_complete=True,uncertainty=[],peak_sampled_rss_bytes=1,tail_state='COMPLETE',independent_outcome_review_sha256='0'*64) + evidence={k:v for k,v in receipt.items() if k not in ('schema','administrative_debit_ns','independent_outcome_review_sha256')} + evidence.update(schema='complete-close-accepted-evidence-v1',command_sha256=request['command_sha256'],interval_scope='COMPLETE_OUTER_COMMAND',rss_scope='AGGREGATE_SAMPLED_ROOT',result_kind='FULL_POSITIVE',raw_inputs=[pin('/fixture/original-raw.bin',b'complete raw fixture')]) + for name in ('admission','source_manifest','profile','result_contract'): evidence[name+'_sha256']=b[name+'_pin']['sha256'] + docs['evidence_manifest_pin']=canonical(evidence);b['evidence_manifest_pin']=pin(C/'evidence.json',docs['evidence_manifest_pin']) + clock=dict(schema='complete-close-clock-lineage-v1',clock_domain_sha256='4'*64,target_start_sha256=sp['sha256'],closer_start_sha256=ownprov['original_start_pin']['sha256'],target_end_ns=15,closer_begin_ns=100) + docs['clock_pin']=canonical(clock);b['clock_pin']=pin(C/'clock.json',docs['clock_pin']) + closure=dict(request=request,start=start,start_pin=sp,baseline_registry_pin=base,receipt_pin={},review_pin={},evidence_binding=b) + x=dict(closure=closure,receipt=receipt,docs=docs,own=own,ownprov=ownprov,ownstart=ownstart,current=F.decode(rh),rh=rh,rr=rr) + refresh(x);return x + +def refresh(x): + b=x['closure']['evidence_binding'];proj=dict(x['receipt']);proj.pop('independent_outcome_review_sha256') + review=dict(schema='complete-close-independent-review-v1',decision='ACCEPT_COMPLETE_OUTCOME',receipt_projection_sha256=sha(canonical(proj)),evidence_binding_sha256=sha(canonical(b))) + x['review_raw']=canonical(review);x['receipt']['independent_outcome_review_sha256']=sha(x['review_raw']);x['raw']=canonical(x['receipt']) + x['closure']['receipt_pin']=pin(ag['CONTROL']/'accepted-receipt.json',x['raw']);x['closure']['review_pin']=pin(ag['R']/'review/complete-close.json',x['review_raw']) + +def validate(x):return ag['complete_close_data'](F,x['closure'],x['raw'],x['review_raw'],x['docs'],x['own'],x['ownprov'],x['ownstart'],x['current'],x['rh'],x['rr']) + +results=[] +def check(name,fn): + fn();results.append(name) +def require(ok): + if ok is not True:raise RuntimeError('independent fixture expectation failed') +def denied(x): + try:validate(x) + except (ValueError,RuntimeError,KeyError,TypeError):return + raise RuntimeError('mutation was not rejected') + +# Inert method environment; actual source function bodies including advance. +def environment(x,fail_at=None,report_failure=None): + e=dict(ag);events=[];files={};r=dict(role='CLOSER',phase='HELD',first=None,secondary=[],secondary_saturated=False,complete_errors=[None]*34,complete_error_count=1,complete_used=False,head_pin=x['closure']['evidence_binding']['expected_head_pin'],protocol_anchor_ns=0) + for name in ('admission_pin','source_manifest_pin','profile_pin','result_contract_pin','evidence_manifest_pin','clock_pin'):files[x['closure']['evidence_binding'][name]['path']]=x['docs'][name] + files[str(ag['HEAD'])]=x['rh'];files[x['current']['registry_pin']['path']]=x['rr'] + files[x['closure']['receipt_pin']['path']]=x['raw'];files[x['closure']['review_pin']['path']]=x['review_raw'];files[x['ownprov']['original_start_pin']['path']]=canonical(x['ownstart']) + def verify(r):require(r['phase'] not in ('FAILED_UNCERTAIN_NO_RETRY','RELEASED','CLOSE_UNKNOWN')) + def read_manual(r):r.update(manual_request=x['own'],manual_provenance=x['ownprov']) + def read(r,p): + raw=files[p['path']];require(len(raw)==p['bytes'] and sha(raw)==p['sha256']);return raw + def fail(r,error): + if report_failure is not None:raise report_failure + if r['first'] is None:r['first']=error + r['phase']='FAILED_UNCERTAIN_NO_RETRY';return r['first'] + def publish(r,path,raw,mode,replace_head=False): + tag='head' if replace_head else 'receipt' if path.name=='receipt.json' else 'history' if path.parent==ag['HEADS'] else 'registry' + events.append(tag) + if fail_at==tag:raise primary + p=pin(path,raw,mode);files[str(path)]=raw + if tag=='head':r['head_pin']=p + return p + def head(r,p): + if 'head' in events: + if fail_at=='readback':raise primary + h=files[str(ag['HEAD'])];obj=F.decode(h);return obj,h,files[obj['registry_pin']['path']] + return x['current'],x['rh'],x['rr'] + def close_actual(r): + events.append('release') + if fail_at=='release':raise primary + primary=RuntimeError('raw primary operation failure') + e.update(role='CLOSER',complete_closure=x['closure'],closure=None,complete_validator=ag['complete_close_data'],complete_validator_image=None,active_globals={'complete_close_data':ag['complete_close_data']},unchanged_function=lambda *a:None,verify=verify,read_manual=read_manual,read=read,funding_io=lambda *a: {'policies':{x['own']['policy_sha256']:x['docs']['policy']}},current_registry_pin=lambda r: x['current']['registry_pin'],active_view=lambda r:None,head=head,publish=publish,stage_empty=lambda:None,fail=fail,rec=lambda self:r,close_actual=close_actual,time=types.SimpleNamespace(monotonic_ns=lambda:1000)) + e.update(cg={'FIRST':[None]},first_state=None);e['first_state']=e['cg']['FIRST'] + e['F']=types.SimpleNamespace(**vars(F),metadata_decode=F.decode) + e['os']=types.SimpleNamespace(getuid=lambda:0) + code=extract(tree,('complete_failure','publish_complete','advance','publish_reviewed_close','release')) + exec(compile(code,str(SOURCE),'exec'),e) + return e,r,events,primary + +def method_success(): + e,r,events,_=environment(fixture());out=e['publish_reviewed_close'](object());require(events==['receipt','registry','history','head']);require(out['all_costs_settled'] is False and out['native_capability'] is False and out['execution_permission'] is False);require(r['complete_own_request']['label']=='closer');require(r['request']['label']=='target') + try:e['publish_reviewed_close'](object()) + except RuntimeError:pass + else:raise RuntimeError('replay accepted') + require(events==['receipt','registry','history','head']) +check('actual changed close and advance exact publication sequence, no grants, one use',method_success) +check('whole validator complete positive',lambda:require(validate(fixture())[0]['outcome']=='PASS')) +for key,value in [('outcome','STOP'),('body_elapsed_ns',True),('body_begin_ns',False),('peak_sampled_rss_bytes',None),('cleanup_known',False),('custody_complete',False),('nested_entries_complete',False),('uncertainty',['unknown']),('tail_state','UNKNOWN'),('administrative_debit_ns',True),('label','other'),('start_sha256','f'*64)]: + def case(key=key,value=value):x=fixture();x['receipt'][key]=value;refresh(x);denied(x) + check('receipt mutation '+key,case) +for key,value in [('interval_scope','PREFIX_ONLY'),('rss_scope','MAX_SINGLE_CHILD'),('result_kind','EXPECTED_REFUSAL'),('command_sha256','f'*64),('source_manifest_sha256','f'*64),('profile_sha256','f'*64),('admission_sha256','f'*64),('raw_inputs',[])]: + def case(key=key,value=value):x=fixture();d=F.decode(x['docs']['evidence_manifest_pin']);d[key]=value;x['docs']['evidence_manifest_pin']=canonical(d);x['closure']['evidence_binding']['evidence_manifest_pin']=pin(ag['CONTROL']/'evidence.json',x['docs']['evidence_manifest_pin']);refresh(x);denied(x) + check('accepted evidence mutation '+key,case) +for tag in ('receipt','registry','history','head','readback'): + def case(tag=tag): + e,r,events,a=environment(fixture(),tag) + try:e['publish_reviewed_close'](object()) + except BaseException as caught:require(caught is a) + else:raise RuntimeError('fault unobserved') + saved=list(events) + try:e['publish_reviewed_close'](object()) + except BaseException:pass + require(events==saved and r['first'] is a) + check('actual advance publication boundary failure '+tag,case) + +def resource_failure(outcome='STOP'): + x=fixture();x['receipt'].update(outcome=outcome,body_end_ns=40,body_elapsed_ns=30,peak_sampled_rss_bytes=F.RSS_LIMIT+1) + d=F.decode(x['docs']['evidence_manifest_pin']);d.update({k:x['receipt'][k] for k in ('outcome','body_end_ns','body_elapsed_ns','peak_sampled_rss_bytes')});x['docs']['evidence_manifest_pin']=canonical(d);x['closure']['evidence_binding']['evidence_manifest_pin']=pin(ag['CONTROL']/'evidence.json',x['docs']['evidence_manifest_pin']);d=F.decode(x['docs']['clock_pin']);d['target_end_ns']=40;x['docs']['clock_pin']=canonical(d);x['closure']['evidence_binding']['clock_pin']=pin(ag['CONTROL']/'clock.json',x['docs']['clock_pin']);refresh(x);require(validate(x)[0]['body_elapsed_ns']==30) +check('known resource-invalid STOP retains untrimmed actual values',resource_failure) +check('original resource-invalid PASS retains untrimmed actual values',lambda:resource_failure('PASS')) + +def custody(): + c=RuntimeError('recorder C');e,r,events,b=environment(fixture(),'release',c);a=RuntimeError('original A');r['first']=a;r['complete_errors'][0]=a;r['complete_used']=True + try:e['release'](object()) + except BaseException as caught:require(caught is a) + require(any(v is b for v in r['complete_errors']) and any(v is c for v in r['complete_errors'])) +check('A remains primary through release B and recorder C',custody) +for name,mutate in [('own reservation cannot borrow target',lambda x:x['own'].update(body_reservation_ns=5)),('wrong role',None),('stale reviewed HEAD',lambda x:x['closure']['evidence_binding']['expected_head_pin'].update(sha256='f'*64))]: + def case(name=name,mutate=mutate): + x=fixture() + if mutate:mutate(x) + e,r,events,_=environment(x) + if name=='own reservation cannot borrow target':e['time']=types.SimpleNamespace(monotonic_ns=lambda:7) + if name=='wrong role':e['role']='CONTROLLER' + try:e['publish_reviewed_close'](object()) + except BaseException:pass + else:raise RuntimeError('invalid admission accepted') + require(events==[]) + check(name,case) +def request_start_mismatch(): + x=fixture();x['closure']['request']['command_sha256']='5'*64 + try:validate(x) + except RuntimeError as error:require('request agrees with actual registered START' in str(error));return + raise RuntimeError('mismatched valid-looking alternate request accepted') +check('request command cannot substitute for actual registered START',request_start_mismatch) + +def first_state_custody(): + e,r,events,d=environment(fixture(),'release',RuntimeError('recorder C')) + a=RuntimeError('established original A');b=RuntimeError('initial verify B');e['first_state'][0]=a + def bad_verify(record):raise b + e['verify']=bad_verify + try:e['publish_reviewed_close'](object()) + except BaseException as caught:require(caught is a) + require(r['complete_used'] is False and any(v is b for v in r['complete_errors'])) + try:e['release'](object()) + except BaseException as caught:require(caught is a) + require(any(v is d for v in r['complete_errors']) and r['phase']=='CLOSE_UNKNOWN') + before=list(events) + try:e['release'](object()) + except BaseException:pass + require(events==before) +check('original FIRST A survives initial verify B, release D, recorder C and one release',first_state_custody) + +def legacy(): + x=fixture();x['receipt'].update(outcome='STOP',cleanup_known=False,tail_state='UNKNOWN',uncertainty=['unresolved original']) + refresh(x);e,r,events,_=environment(x);e['complete_closure']=None;e['closure']={k:v for k,v in x['closure'].items() if k!='evidence_binding'} + result=e['publish_reviewed_close'](object());require(events==['receipt','registry','history','head']) + require(set(result)=={'receipt_pin','head_pin','all_costs_settled','execution_permission'}) +check('actual legacy STOP UNKNOWN branch result and publication retained',legacy) + +def capacity(): + x=fixture();x['current']['sequence']=2*F.MAX_ENTRIES;denied(x) +check('prospective exhausted registry generation before publication',capacity) + +def large_metadata(): + x=fixture();x['raw']=b' '* (F.META_CAP+1);denied(x) +check('oversized formal receipt metadata rejected',large_metadata) + +def selected_result(kind, outcome): + x=fixture();b=x['closure']['evidence_binding'];contract=F.decode(x['docs']['result_contract_pin']);contract['kind']=kind + x['docs']['result_contract_pin']=canonical(contract);b['result_contract_pin']=pin(ag['CONTROL']/'contract.json',x['docs']['result_contract_pin']) + admission=F.decode(x['docs']['admission_pin']);admission['result_contract_pin']=b['result_contract_pin'];x['docs']['admission_pin']=canonical(admission);b['admission_pin']=pin(ag['CONTROL']/'admission.json',x['docs']['admission_pin']) + x['receipt']['outcome']=outcome;d=F.decode(x['docs']['evidence_manifest_pin']);d.update(outcome=outcome,result_kind=kind,result_contract_sha256=b['result_contract_pin']['sha256'],admission_sha256=b['admission_pin']['sha256']) + x['docs']['evidence_manifest_pin']=canonical(d);b['evidence_manifest_pin']=pin(ag['CONTROL']/'evidence.json',x['docs']['evidence_manifest_pin']);refresh(x) + require(validate(x)[0]['outcome']==outcome) +check('selected original expected-refusal oracle positive',lambda:selected_result('EXPECTED_REFUSAL','PASS')) +check('selected original known-STOP disposition positive',lambda:selected_result('KNOWN_STOP','STOP')) + +def static_compatibility(): + # These are static properties, not executed bind/native authentication. + old=ast.parse((ROOT/'reference/active_original.py.txt').read_bytes()) + def method(t):return next(x for x in ast.walk(t) if isinstance(x,ast.FunctionDef) and x.name=='publish_reviewed_close') + before=method(old).body;after=method(tree).body + require(ast.dump(ast.Module(body=before,type_ignores=[]))==ast.dump(ast.Module(body=[after[0]]+after[2:],type_ignores=[]))) + def methods(t):return [x.name for c in ast.walk(t) if isinstance(c,ast.ClassDef) and c.name=='Context' for x in c.body if isinstance(x,ast.FunctionDef)] + require(methods(old)==methods(tree)) +check('static exact legacy close body and Context method set retained',static_compatibility) + +print(json.dumps({'schema':'complete-close-finite-control-result-v1','mode':'assertion-on' if __debug__ else 'optimized','source_sha256':sha(SOURCE.read_bytes()),'funding_sha256':sha(FUNDING.read_bytes()),'passed':len(results),'cases':results,'scope':'AST-extracted whole changed functions and actual advance with INERT ports; no native ownership, bootstrap authentication, genuine evidence or fit qualification'},indent=2))