diff --git a/research/h25-passive-guard-primary-preservation/.gitattributes b/research/h25-passive-guard-primary-preservation/.gitattributes new file mode 100644 index 0000000000..d8f4f5e052 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/.gitattributes @@ -0,0 +1 @@ +* -text -filter -ident diff --git a/research/h25-passive-guard-primary-preservation/ARCHIVE.json b/research/h25-passive-guard-primary-preservation/ARCHIVE.json new file mode 100644 index 0000000000..5e1cb61a1d --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/ARCHIVE.json @@ -0,0 +1,34 @@ +{ + "schema": "h25-passive-guard-source-archive-v1", + "status": "CONDITIONAL_LOCAL_SOURCE_AND_PARENT_OBSERVED_FINITE_FAKE_RESULTS", + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "format": "unregistered-source-archive", + "registered_replay_hook": false, + "source_disposition": "CONDITIONAL_LOCAL_CALLABLE_SOURCE_PASS", + "fake_plan_disposition": "EXACT_INERT_FAKE_PLAN_PASS", + "fake_execution": "NORMAL14_OF14_AND_OPTIMIZED14_OF14_ONCE_EACH", + "actual_C10_or_full_RUN01_02_03": false, + "actual_guard_or_runtime_native_decoder": false, + "full_C05": false, + "full_V03": false, + "C07": "UNBOUND_HOLD", + "capture_call_availability_is_additional_premise": true, + "unadmitted_timer_disarm_side_effect_unqualified": true, + "original_progress": { + "percent": 43.5, + "items": "22/49", + "stages": "2/10", + "milestones": "1/10", + "components": 24, + "helpers": 52, + "credit_added": 0 + }, + "costs": "OPEN_NOT_ZERO", + "parent_owns_controls_and_remote_publication": true, + "hard_stop_utc": "2026-11-03T05:20:29Z", + "independent_raw_result_review": "PENDING_AT_AUTHORING_FREEZE; parent must retain any material HOLD before remote delivery", + "additional_policy_debit_seconds": 2, + "canonical_policy_seconds": "94.550533479", + "supplemental_combined_seconds": "106.890533479", + "complete_physical_cost": false +} diff --git a/research/h25-passive-guard-primary-preservation/LICENSE b/research/h25-passive-guard-primary-preservation/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/research/h25-passive-guard-primary-preservation/MANIFEST.json b/research/h25-passive-guard-primary-preservation/MANIFEST.json new file mode 100644 index 0000000000..74def05f8d --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/MANIFEST.json @@ -0,0 +1,210 @@ +{ + "schema": "h25-passive-guard-archive-manifest-v1", + "scope": "ARCHIVE_INTEGRITY_ONLY", + "files": [ + { + "path": ".gitattributes", + "bytes": 23, + "sha256": "aca07970df50b15cddb5333b18259deb2a0c6efb48c494c55a7dfdb37fcba5a5", + "mode": "100644" + }, + { + "path": "ARCHIVE.json", + "bytes": 1353, + "sha256": "a95c39372160c0d36272fdfbbd92ebc76a9106eebf04c22a9a920df77b149bd9", + "mode": "100644" + }, + { + "path": "LICENSE", + "bytes": 11357, + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "mode": "100644" + }, + { + "path": "NOTICE.md", + "bytes": 1017, + "sha256": "20dad9de1208ee91161ec8d09d5bb57e4d1126e62bf0a9f3d6cceb96decb2757", + "mode": "100644" + }, + { + "path": "README.md", + "bytes": 8387, + "sha256": "510d6e1b5c882b1ebebed09ac839f3fe4cc60fb9d5b6f8820453b33e11cc70ff", + "mode": "100644" + }, + { + "path": "SOURCE-MAP.json", + "bytes": 10366, + "sha256": "edee7be6aead18d8b80ea5a7c9e28c15e77255a222216b4e8f01c8fbbfcad730", + "mode": "100644" + }, + { + "path": "adapter/ADAPTER.diff", + "bytes": 3320, + "sha256": "5df4c0b139c5c93ddd7404fb2af84154f202e6f5e75c89635713c175c90495ec", + "mode": "100644" + }, + { + "path": "adapter/ADAPTER.json", + "bytes": 2992, + "sha256": "8562dbfb27b63525abcae37b5be43252cbabb6a14622c041659cb8e1b925c96c", + "mode": "100644" + }, + { + "path": "adapter/original/parent_passive_supervisor_v4.py.txt", + "bytes": 29659, + "sha256": "83e31e2705b949750f5ea6bd07ebafff4c2b5dbdbe578a87058eda7ca0e600f5", + "mode": "100644" + }, + { + "path": "adapter/original/passive_image_candidates_v3.py.txt", + "bytes": 12726, + "sha256": "166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41", + "mode": "100644" + }, + { + "path": "adapter/original/verify_guard_fake_v1.py.txt", + "bytes": 20897, + "sha256": "357ca2b8788438fe32e32f9c7bfa171e74eca12d3183ee7aebbd540bbe7e72f1", + "mode": "100644" + }, + { + "path": "evidence/ADMISSION-v1.json", + "bytes": 1059, + "sha256": "60471dcfab6e7442de3bd51f7b084473b2900ad4790ccada5b0544f8d9225e65", + "mode": "100644" + }, + { + "path": "evidence/CONTROLS-PLAN.json", + "bytes": 1630, + "sha256": "cc2064646eedba19392ec7f9a221eace47081b4925d7ae1079d1f45f5a66968e", + "mode": "100644" + }, + { + "path": "evidence/LEDGER-v1.json", + "bytes": 9086, + "sha256": "21eb6e432a1a9eaf1be303fab70cfe886bcc888143b7c388c548450e79f9868c", + "mode": "100644" + }, + { + "path": "evidence/TOOL-OBSERVATIONS.json", + "bytes": 690, + "sha256": "1dd4b9fc952b5c235253a4d7367f8b0ade19a4bf3b3ef47190509285010cd8d5", + "mode": "100644" + }, + { + "path": "evidence/normal.stderr", + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mode": "100644" + }, + { + "path": "evidence/normal.stdout", + "bytes": 1527, + "sha256": "9f83227b4bed95c37e0a151219c1e70bdc8dae1129d0ebf6274c9d27bc3ea7a1", + "mode": "100644" + }, + { + "path": "evidence/normal.time", + "bytes": 1007, + "sha256": "1f999309a6f8f28ffd4b1a3cfdc2e3fe2a899e383dc1e10f3c7380d34ef389f9", + "mode": "100644" + }, + { + "path": "evidence/optimized.stderr", + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mode": "100644" + }, + { + "path": "evidence/optimized.stdout", + "bytes": 1527, + "sha256": "9f83227b4bed95c37e0a151219c1e70bdc8dae1129d0ebf6274c9d27bc3ea7a1", + "mode": "100644" + }, + { + "path": "evidence/optimized.time", + "bytes": 1012, + "sha256": "aac3d0c462b6b4163aa124778672f5cd8e30fad6af1d41c52b8908371c30ad42", + "mode": "100644" + }, + { + "path": "integrity.py", + "bytes": 5758, + "sha256": "c8c9b5eb5a3228642b3e542fb0ca6ed85f17a64da630634c42b5546864eca8be", + "mode": "100644" + }, + { + "path": "reviews/CURRENT-PRS.json", + "bytes": 2521, + "sha256": "9d96f4cbe1d1d290a36e813ca46952c36822096e0ecc3eb4ac27dabe6868b6e5", + "mode": "100644" + }, + { + "path": "reviews/PREDECESSOR-CONTROL-REVIEW.json", + "bytes": 2949, + "sha256": "7f7b240bfdf3c47ae0f29ac3e67d750048e69e66262d9a327f4f3fe2c14aaf33", + "mode": "100644" + }, + { + "path": "reviews/PUBLICATION-ADAPTER-REVIEW-v1.json", + "bytes": 3354, + "sha256": "eeb528e60d0beb132ef15ca69b2861f9a9e04478bd30f0f11a389abd14e2505e", + "mode": "100644" + }, + { + "path": "reviews/SOURCE-CONTROL-REVIEW-v1.json", + "bytes": 9872, + "sha256": "c9e39e36cb08f51f02a27e64e27bf6dd80afebdd3d07aac39774a63a1ff7b91c", + "mode": "100644" + }, + { + "path": "snapshot/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/parent_passive_supervisor_v3.py", + "bytes": 20881, + "sha256": "2a9581442b8cd6802f45c7ae4c523165fa19297f7fe1d8c616c74f65da9b628a", + "mode": "100644" + }, + { + "path": "snapshot/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/passive_image_candidates_v2.py", + "bytes": 11809, + "sha256": "56b44235f55685d61e5c8b8099d825b4ec5a53987910f506dffad309c12ffb53", + "mode": "100644" + }, + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/RECONCILIATION.json", + "bytes": 18718, + "sha256": "9776a5e6ae575593fda27d549ffebb432f9b3fc4b4d9b1e5cdf77bacf8cebdaf", + "mode": "100644" + }, + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/SOURCE-FREEZE-v1.json", + "bytes": 9782, + "sha256": "e1a6251d5a73362e1608cfb952d72ac3b382dd2f1e811823c8d74596b3febe3f", + "mode": "100644" + }, + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py", + "bytes": 29904, + "sha256": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", + "mode": "100644" + }, + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/passive_image_candidates_v3.py", + "bytes": 12983, + "sha256": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", + "mode": "100644" + }, + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/reference-g12-parent-v3.py.txt", + "bytes": 96341, + "sha256": "8b6b196c50d616e12d7966ea35bf6d65fd799a18556f362a7e17d2b1273a8bb8", + "mode": "100644" + }, + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "bytes": 20897, + "sha256": "c71dcf2dfd944282210f105ef54d23a4deb6e1eaaa0a9068a2ea584292ea365e", + "mode": "100644" + } + ] +} diff --git a/research/h25-passive-guard-primary-preservation/NOTICE.md b/research/h25-passive-guard-primary-preservation/NOTICE.md new file mode 100644 index 0000000000..cd7a6bf72d --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/NOTICE.md @@ -0,0 +1,5 @@ +Apache-2.0. Prepared for Chris R / Clear1nsight with substantial OpenAI Codex / Sol Max and ChatGPT Pro assistance. + +Retain unpaidmoon / Cursor Grok PR #6339 at 608ad23adc6c01264c8195daf7f18e29c17464a7; Clear1nsight PR #6346 abff67b31fa781e950c82d95eccb6f168950943c, PR #6347 59140439e7f791876159e2f3838f1dead2e54953, PR #6351 1e9db2d08be4551ffe0bcfc573574851530eb4ca; PR #6434 edc2820ba023b804ef1351a88e2fe31bf8d489dd and PR #6476 44749c3a6ddc8cde48c5aa83073f6794e3546b00. Retain Douglas R. Colkitt and all inherited lineage, including PR6321/6029/5864 and their source notices/AI disclosures. Predecessor authorship or approval of this successor is not claimed. + +The two original repair-v2 sources and reference-g12-parent-v3.py.txt are INERT REFERENCE SOURCE. They may be read as text by the exact separately approved fake AST harness. They must not be imported or invoked as guard/helper CLIs. The dated publication adapter changes notices and dependent byte pins only; see adapter/ADAPTER.diff and ADAPTER.json. diff --git a/research/h25-passive-guard-primary-preservation/README.md b/research/h25-passive-guard-primary-preservation/README.md new file mode 100644 index 0000000000..0a4c60adad --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/README.md @@ -0,0 +1,51 @@ +# Conditional passive guard source and finite fake controls + +This archive retains a complete local passive-guard successor, selected helper entry, exact source-correspondent fake harness, independent conditional source/plan and publication-adapter reviews, raw parent-run finite results, and inert predecessor/reference sources. + +The local source method assumes **adequate capture-call and recording/unwind availability after handler delivery**, in addition to protected exact-list/private state, original native primitives, no concurrent/async/tracing/hostile-finalizer interference and adequate delivery/unwind. The added capture-call sufficiency assumption does not discharge original C10 inline first-slot requirements. **Unadmitted main still disarms the timer after initial gate failure; it is not certified side-effect-free and must not be invoked.** CLI, asynchronous signal/os._exit, actual admission and runtime routes remain unqualified. + +The parent observed `PASS_BOUNDED_FAKE_ONLY` for all 14 cases in normal mode and all 14 in optimized mode, once each, on the exact adapted guard/helper hashes below. F12 retains all three stronger 6346 ledger/snapshot/recording RED witnesses as RED. The results do not qualify actual native acquisitions, descriptors/processes, proc parsing, pre-return delivery, enclosing teardown authority, original C10/C11, complete RUN-01/02/03 exits, C07, original C05 or full V03. The selected guard remains `OPERATION_ADMITTED=False` with its original expired epoch. No actual guard/helper CLI or target/decoder/native/compiler operation was performed. + +Original progress remains 43.5%, 22/49 items, 2/10 stages, 1/10 milestones, 24 components and 52 helpers. Original-completion credit added is zero. Canonical policy accounting remains 94.550533479 seconds; the two conservative 1-second fake-run debits bring the supplemental combined ledger to 106.890533479 seconds. These are policy accounting, not complete physical cost. All outside/unaccounted costs remain `OPEN_NOT_ZERO`; no performance or kappa claim is made. + +## Exact scope and evidence + +The accepted local source definitions are `read_pin`, `Guard.write/register/cleanup/run`, guard callable main and locator callable main. Under the stated additional premises, the selected source and finite fakes preserve the first delivered raw exception object and its rooted first traceback, keep ordered raw secondaries, attempt known independent releases once, retire numeric owners before ambiguous close, preserve pending acquisition, quarantine new I/O/launch/publication after uncertainty and withhold success after cleanup failure. Actual original caller/Gamma, configured stage, currentness/custody, external parent lifetime/teardown and C07 remain unbound. + +- Adapted guard SHA256: `355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd`. +- Adapted helper SHA256: `8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d`. +- Adapted harness SHA256: `c71dcf2dfd944282210f105ef54d23a4deb6e1eaaa0a9068a2ea584292ea365e`. +- `reviews/SOURCE-CONTROL-REVIEW-v1.json` is the exact original conditional source/fake-plan review; it binds the pre-publication source bytes. `adapter/original/` retains those bytes inert. `adapter/ADAPTER.diff` and `ADAPTER.json` describe only required modification notices and derived byte-pin updates. Normalized program AST is equal after reversing those exact pin updates. The unchanged helper first 10370 bytes hash to d5161cc51d5818dd70938214b4067ddc4af2e0fec513b8a255b50615a3da7b50; the full 10371-byte pre-main split prefix hashes to 3aca049fd68bf4e9c2185a6a318bebef8bb0d518963ba551c169cab2a04582a9. +- `reviews/PUBLICATION-ADAPTER-REVIEW-v1.json` binds the exact adapted source/harness hashes for inert fake execution. `evidence/` retains stdout/stderr/time, admission, operation plan, tool observations and ledger from the parent runs. +- `snapshot/c05-v03-completion-20261102T055710Z/.../repair-v2/` and `reference-g12-parent-v3.py.txt` are inert text dependencies for retained failure controls. They are not admitted executable guards. Relative source bindings are preserved without a new path adapter. + +Independent review of raw finite outcomes and parent metadata/commit checks were pending at archive authoring freeze; delivery must preserve any material HOLD. Source authorship, conditional source review, parent-executed finite results, independent result review, committed bytes, publication and hosted CI are distinct states. + +## Reproduction and integrity + +No registered replay hook, `TASK.json` or `VERIFY.json` is supplied. From the repository root, the bounded archive-only command is: + +```sh +python3 -I -B research/h25-passive-guard-primary-preservation/integrity.py +``` + +It checks declared regular-file inventory, exact paths, modes, sizes and SHA256 only. It never imports or executes the archived candidates or harness. MANIFEST.json itself is authenticated by the publication commit/external freeze. Keep the archive stable during checking; this is byte integrity, not semantic qualification or proof of complete Git source history. + +The parent ran the following exact harness file once with `/usr/bin/python3.12 -I -S -B` and once with `/usr/bin/python3.12 -I -O -S -B` (absolute original paths/environment and raw times are in `evidence/`): + +```text +research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py +``` + +The harness parses exact hash-pinned texts and extracts complete named definitions into reviewed inert fakes. It omits candidate module imports, top-level assignments, CLI/alarm execution and real proc/process/native operations. Full builtins are present; safety relies on these exact reviewed hashes, not a general safe AST executor. Finite assertions use explicit require checks and survive -O. Reproduction requires separate authorization and the same exact source/relative dependency boundary. No new run is authorized by this archive. + +## Provenance and credit + +Canonical policy/base is 7c49fe32c55de02c2c873655c804b16e4c3fef0a, refreshed by the parent this round and read at that stored commit. This is explicit W1/RUN-01–03 work; no task picker was run. Scope is refined from original actual-path completion to a conditional local source/fake prerequisite. The existing reconciliation records exact ADAPT/INCOMPATIBLE/reuse decisions and retained failure controls; bounded 2026-11-03T04:38:46–48Z relevant-head freshness is not a novelty claim. + +Retain unpaidmoon / Cursor Grok PR #6339 at 608ad23adc6c01264c8195daf7f18e29c17464a7, Clear1nsight PR #6346 at abff67b31fa781e950c82d95eccb6f168950943c, PR #6347 at 59140439e7f791876159e2f3838f1dead2e54953, PR #6351 at 1e9db2d08be4551ffe0bcfc573574851530eb4ca, PR #6434 at edc2820ba023b804ef1351a88e2fe31bf8d489dd and PR #6476 at 44749c3a6ddc8cde48c5aa83073f6794e3546b00. Primary-preserving cleanup is adapted from #6339; private raw state, independent release/retirement and three stronger RED witnesses follow #6346. Formatted OperationStop records from #6434 cannot substitute for the same-object oracle. Existing #6476 locator pure semantics remain unchanged and are not newly qualified. See LICENSE, NOTICE.md and exact SOURCE-MAP.json. Prepared for Chris R / Clear1nsight with substantial OpenAI Codex / Sol Max and ChatGPT Pro assistance. All Douglas R. Colkitt and inherited PR6321/6029/5864 lineage/notices remain; predecessor authorship or approval of this successor is not claimed. + +## Open next questions + +1. **What exact original-compatible caller/admission/currentness/custody/teardown and C07 lifetime instance can support an actual operation?** It is necessary before original qualification. First step: source-review one genuine bound external caller and lifetime mechanism against the original conditions. Blocked by the currently absent/unadmitted instance; fake tokens and local error cells do not supply authority. +2. **Can an admitted actual operation bind the original joined compiler-root bridge?** This is the dependency connecting this guard leaf to the original C05/V03 acceptance condition. First step: only after the external authority/lifetime gate passes, identify the exact reviewed operation and bridge. Blocked by the earlier original caller/lifetime gate. No closed decoder/native round, new budget, goal resume or operation is authorized here. diff --git a/research/h25-passive-guard-primary-preservation/SOURCE-MAP.json b/research/h25-passive-guard-primary-preservation/SOURCE-MAP.json new file mode 100644 index 0000000000..0d87ad2ff6 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/SOURCE-MAP.json @@ -0,0 +1,208 @@ +{ + "schema": "h25-passive-guard-source-map-v1", + "files": [ + { + "package_path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py", + "source_sha256": "83e31e2705b949750f5ea6bd07ebafff4c2b5dbdbe578a87058eda7ca0e600f5", + "adaptation": "publication-only comment and derived byte pins; see adapter/ADAPTER.json", + "bytes": 29904, + "sha256": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", + "mode": "100644" + }, + { + "package_path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/passive_image_candidates_v3.py", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/passive_image_candidates_v3.py", + "source_sha256": "166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41", + "adaptation": "publication-only comment and derived byte pins; see adapter/ADAPTER.json", + "bytes": 12983, + "sha256": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", + "mode": "100644" + }, + { + "package_path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "source_sha256": "357ca2b8788438fe32e32f9c7bfa171e74eca12d3183ee7aebbd540bbe7e72f1", + "adaptation": "publication-only comment and derived byte pins; see adapter/ADAPTER.json", + "bytes": 20897, + "sha256": "c71dcf2dfd944282210f105ef54d23a4deb6e1eaaa0a9068a2ea584292ea365e", + "mode": "100644" + }, + { + "package_path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/reference-g12-parent-v3.py.txt", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/reference-g12-parent-v3.py.txt", + "adaptation": "exact bytes", + "bytes": 96341, + "sha256": "8b6b196c50d616e12d7966ea35bf6d65fd799a18556f362a7e17d2b1273a8bb8", + "mode": "100644" + }, + { + "package_path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/SOURCE-FREEZE-v1.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/SOURCE-FREEZE-v1.json", + "adaptation": "exact bytes", + "bytes": 9782, + "sha256": "e1a6251d5a73362e1608cfb952d72ac3b382dd2f1e811823c8d74596b3febe3f", + "mode": "100644" + }, + { + "package_path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/RECONCILIATION.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/RECONCILIATION.json", + "adaptation": "exact bytes", + "bytes": 18718, + "sha256": "9776a5e6ae575593fda27d549ffebb432f9b3fc4b4d9b1e5cdf77bacf8cebdaf", + "mode": "100644" + }, + { + "package_path": "snapshot/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/parent_passive_supervisor_v3.py", + "source_path": "outputs/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/parent_passive_supervisor_v3.py", + "adaptation": "exact inert predecessor; AST-read only", + "bytes": 20881, + "sha256": "2a9581442b8cd6802f45c7ae4c523165fa19297f7fe1d8c616c74f65da9b628a", + "mode": "100644" + }, + { + "package_path": "snapshot/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/passive_image_candidates_v2.py", + "source_path": "outputs/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/passive_image_candidates_v2.py", + "adaptation": "exact inert predecessor; AST-read only", + "bytes": 11809, + "sha256": "56b44235f55685d61e5c8b8099d825b4ec5a53987910f506dffad309c12ffb53", + "mode": "100644" + }, + { + "package_path": "reviews/SOURCE-CONTROL-REVIEW-v1.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/review/SOURCE-CONTROL-REVIEW-v1.json", + "adaptation": "exact bytes", + "bytes": 9872, + "sha256": "c9e39e36cb08f51f02a27e64e27bf6dd80afebdd3d07aac39774a63a1ff7b91c", + "mode": "100644" + }, + { + "package_path": "reviews/PREDECESSOR-CONTROL-REVIEW.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/review/PREDECESSOR-CONTROL-REVIEW.json", + "adaptation": "exact bytes", + "bytes": 2949, + "sha256": "7f7b240bfdf3c47ae0f29ac3e67d750048e69e66262d9a327f4f3fe2c14aaf33", + "mode": "100644" + }, + { + "package_path": "adapter/original/parent_passive_supervisor_v4.py.txt", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py", + "adaptation": "exact accepted source before publication-only notice/pin adapter; inert", + "bytes": 29659, + "sha256": "83e31e2705b949750f5ea6bd07ebafff4c2b5dbdbe578a87058eda7ca0e600f5", + "mode": "100644" + }, + { + "package_path": "adapter/original/passive_image_candidates_v3.py.txt", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/passive_image_candidates_v3.py", + "adaptation": "exact accepted source before publication-only notice/pin adapter; inert", + "bytes": 12726, + "sha256": "166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41", + "mode": "100644" + }, + { + "package_path": "adapter/original/verify_guard_fake_v1.py.txt", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "adaptation": "exact accepted source before publication-only notice/pin adapter; inert", + "bytes": 20897, + "sha256": "357ca2b8788438fe32e32f9c7bfa171e74eca12d3183ee7aebbd540bbe7e72f1", + "mode": "100644" + }, + { + "package_path": "reviews/CURRENT-PRS.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/evidence/CURRENT-PRS.json", + "adaptation": "exact retained bounded head observation", + "bytes": 2521, + "sha256": "9d96f4cbe1d1d290a36e813ca46952c36822096e0ecc3eb4ac27dabe6868b6e5", + "mode": "100644" + }, + { + "package_path": "evidence/normal.stdout", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/normal.stdout", + "bytes": 1527, + "sha256": "9f83227b4bed95c37e0a151219c1e70bdc8dae1129d0ebf6274c9d27bc3ea7a1", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/normal.stderr", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/normal.stderr", + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/normal.time", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/normal.time", + "bytes": 1007, + "sha256": "1f999309a6f8f28ffd4b1a3cfdc2e3fe2a899e383dc1e10f3c7380d34ef389f9", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/optimized.stdout", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/optimized.stdout", + "bytes": 1527, + "sha256": "9f83227b4bed95c37e0a151219c1e70bdc8dae1129d0ebf6274c9d27bc3ea7a1", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/optimized.stderr", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/optimized.stderr", + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/optimized.time", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/optimized.time", + "bytes": 1012, + "sha256": "aac3d0c462b6b4163aa124778672f5cd8e30fad6af1d41c52b8908371c30ad42", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/LEDGER-v1.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/LEDGER-v1.json", + "bytes": 9086, + "sha256": "21eb6e432a1a9eaf1be303fab70cfe886bcc888143b7c388c548450e79f9868c", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/TOOL-OBSERVATIONS.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/TOOL-OBSERVATIONS.json", + "bytes": 690, + "sha256": "1dd4b9fc952b5c235253a4d7367f8b0ade19a4bf3b3ef47190509285010cd8d5", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/ADMISSION-v1.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/ADMISSION-v1.json", + "bytes": 1059, + "sha256": "60471dcfab6e7442de3bd51f7b084473b2900ad4790ccada5b0544f8d9225e65", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "evidence/CONTROLS-PLAN.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/controls/CONTROLS-PLAN.json", + "bytes": 1630, + "sha256": "cc2064646eedba19392ec7f9a221eace47081b4925d7ae1079d1f45f5a66968e", + "mode": "100644", + "adaptation": "exact parent-run final-export fake-only receipt; no publication-worker rerun" + }, + { + "package_path": "reviews/PUBLICATION-ADAPTER-REVIEW-v1.json", + "source_path": "outputs/c05-v03-pro-workitems-20261103T0435Z/review/PUBLICATION-ADAPTER-REVIEW-v1.json", + "bytes": 3354, + "sha256": "eeb528e60d0beb132ef15ca69b2861f9a9e04478bd30f0f11a389abd14e2505e", + "mode": "100644", + "adaptation": "exact peer adapter review; prefix metadata corrected separately, source3 unchanged" + } + ] +} diff --git a/research/h25-passive-guard-primary-preservation/adapter/ADAPTER.diff b/research/h25-passive-guard-primary-preservation/adapter/ADAPTER.diff new file mode 100644 index 0000000000..3fb2b76850 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/adapter/ADAPTER.diff @@ -0,0 +1,54 @@ +--- original/parent_passive_supervisor_v4.py ++++ adapted/parent_passive_supervisor_v4.py +@@ -1,3 +1,6 @@ ++# Modified 2026-11-03 for Clear1nsight with substantial OpenAI Codex assistance. ++# Publication-only notice/pin adapter of the independently reviewed local source. ++# Retains unpaidmoon/Cursor Grok PR6339 and Clear1nsight PR6346/6347/6351 credit. + """SOURCE ONLY until separately admitted by parent. One offline discovery pass. + Linux 7.0.0-42-generic / Python3.12 POSIX subprocess/process-group semantics. + This is sampled accounting and bounded capture, not a universal OS proof. +@@ -19,8 +22,8 @@ + + HERE = Path(__file__).resolve().parent + HELPER = HERE / 'passive_image_candidates_v3.py' +-HELPER_SHA = '166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41' +-HELPER_SIZE = 12726 ++HELPER_SHA = '8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d' ++HELPER_SIZE = 12983 + OPERATION_ADMITTED = False + TARGET = '/usr/bin/x86_64-linux-gnu-gcc-13' + TARGET_SHA = '1b99826121ae6682a634e5efe09bd3e3df58ce58e0b28f849114ab5b89139c26' +--- original/passive_image_candidates_v3.py ++++ adapted/passive_image_candidates_v3.py +@@ -209,6 +209,9 @@ + + + def main(): ++ # Modified 2026-11-03 for Clear1nsight with substantial OpenAI Codex assistance. ++ # Publication-only notice/pin adapter of the independently reviewed local source. ++ # Retains unpaidmoon/Cursor Grok PR6339 and Clear1nsight PR6346/6347/6351 credit. + # Source-only C10 local entry adaptation: private cells precede acquisition. + # Pure inspect/data definitions above are unchanged from accepted v2. + first = [None, None] +--- original/verify_guard_fake_v1.py ++++ adapted/verify_guard_fake_v1.py +@@ -18,8 +18,8 @@ + PREDECESSOR=ROOT.parents[1]/'c05-v03-completion-20261102T055710Z'/'driver-libexec-property-slice-v1'/'repair-v2'/'parent_passive_supervisor_v3.py' + OLD_HELPER=PREDECESSOR.parent/'passive_image_candidates_v2.py' + REFERENCE=ROOT/'reference-g12-parent-v3.py.txt' +-SOURCE_SHA='83e31e2705b949750f5ea6bd07ebafff4c2b5dbdbe578a87058eda7ca0e600f5' +-HELPER_SHA='166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41' ++SOURCE_SHA='355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd' ++HELPER_SHA='8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d' + PREDECESSOR_SHA='2a9581442b8cd6802f45c7ae4c523165fa19297f7fe1d8c616c74f65da9b628a' + REFERENCE_SHA='8b6b196c50d616e12d7966ea35bf6d65fd799a18556f362a7e17d2b1273a8bb8' + NAMES=('Stop','need','digest','RawErrors','acquire','close_slot','read_pin','Guard','bind_window','main') +@@ -174,7 +174,7 @@ + 'RAW_ERROR_CAP':4096,'KNOWN_CAP':128,'RAW_CAP':786432,'TOTAL_CAP':1048576,'RESERVE':262144, + 'MEM_CAP':1073741824,'TOOLS':{'/FAKE/tool':(3,hashlib.sha256(b'abc').hexdigest())}, + 'TARGET':'/FAKE/target','TARGET_SHA':'0'*64,'HELPER':TokenPath('/FAKE/helper'), +- 'HELPER_SHA':HELPER_SHA,'HELPER_SIZE':12726,'OPERATION_ADMITTED':True, ++ 'HELPER_SHA':HELPER_SHA,'HELPER_SIZE':12983,'OPERATION_ADMITTED':True, + 'stat':SimpleNamespace(S_ISREG=lambda mode:True), + 'selectors':SimpleNamespace(DefaultSelector=lambda:TokenSelector(self),EVENT_READ=1), + 'subprocess':SimpleNamespace(Popen=self.popen,DEVNULL=-3,PIPE=-1, diff --git a/research/h25-passive-guard-primary-preservation/adapter/ADAPTER.json b/research/h25-passive-guard-primary-preservation/adapter/ADAPTER.json new file mode 100644 index 0000000000..3f5237bdcb --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/adapter/ADAPTER.json @@ -0,0 +1,53 @@ +{ + "schema": "h25-passive-guard-publication-only-adapter-v1", + "frozen_utc": "2026-11-03T05:08:53.038154+00:00", + "status": "PUBLICATION_SOURCE_ADAPTER_PEER_ACCEPTED; PARENT_FAKE_NORMAL_AND_OPTIMIZED_PASS", + "changes": [ + "guard top modification notice", + "helper modification notice immediately after def main;10370-byte pure prefix unchanged", + "derived guard HELPER_SHA/HELPER_SIZE", + "derived harness SOURCE_SHA/HELPER_SHA/fake HELPER_SIZE" + ], + "all_other_program_ast_equal_after_exact_pin_normalization": true, + "candidate_import_compile_execution": false, + "original_source_preserved_outside_package": true, + "original_sources_retained_inert_in_package": true, + "files": [ + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py", + "original_bytes": 29659, + "original_sha256": "83e31e2705b949750f5ea6bd07ebafff4c2b5dbdbe578a87058eda7ca0e600f5", + "adapted_bytes": 29904, + "adapted_sha256": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", + "normalized_ast_sha256": "ef97c32a2610b1ae09496eac3fdc82d78cadba40317c3e2a7669d7aa71bda4aa", + "normalized_ast_equal": true + }, + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/passive_image_candidates_v3.py", + "original_bytes": 12726, + "original_sha256": "166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41", + "adapted_bytes": 12983, + "adapted_sha256": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", + "normalized_ast_sha256": "2af508ea0f08a46d53b8d3d09d70a285bc6eb4ebec35d5bff6dbb2a9f9f7f1c1", + "normalized_ast_equal": true + }, + { + "path": "snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "original_bytes": 20897, + "original_sha256": "357ca2b8788438fe32e32f9c7bfa171e74eca12d3183ee7aebbd540bbe7e72f1", + "adapted_bytes": 20897, + "adapted_sha256": "c71dcf2dfd944282210f105ef54d23a4deb6e1eaaa0a9068a2ea584292ea365e", + "normalized_ast_sha256": "a68d09c9d5b3d7785d9ae47e793e0a56faa9e1e60e2917e30dc72726e7b7e6e8", + "normalized_ast_equal": true + } + ], + "helper_pure_prefix_bytes": 10371, + "helper_pure_prefix_sha256": "3aca049fd68bf4e9c2185a6a318bebef8bb0d518963ba551c169cab2a04582a9", + "selected_operation_admitted": false, + "expired_epoch_changed": false, + "fake_results": "evidence/LEDGER-v1.json: fourteen PASS_FAKE_ONLY cases in each of normal and optimized, once each", + "semantic_credit": 0, + "helper_reviewed_first_prefix_bytes": 10370, + "helper_reviewed_first_prefix_sha256": "d5161cc51d5818dd70938214b4067ddc4af2e0fec513b8a255b50615a3da7b50", + "prefix_metadata_correction": "Full pre-main split prefix is10371bytes/3aca049fd68bf4e9c2185a6a318bebef8bb0d518963ba551c169cab2a04582a9; reviewed first10370bytes ared5161cc51d5818dd70938214b4067ddc4af2e0fec513b8a255b50615a3da7b50. Originalv1 freeze length/hash pairing corrected; source3 unchanged." +} diff --git a/research/h25-passive-guard-primary-preservation/adapter/original/parent_passive_supervisor_v4.py.txt b/research/h25-passive-guard-primary-preservation/adapter/original/parent_passive_supervisor_v4.py.txt new file mode 100644 index 0000000000..2c8833be51 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/adapter/original/parent_passive_supervisor_v4.py.txt @@ -0,0 +1,596 @@ +"""SOURCE ONLY until separately admitted by parent. One offline discovery pass. +Linux 7.0.0-42-generic / Python3.12 POSIX subprocess/process-group semantics. +This is sampled accounting and bounded capture, not a universal OS proof. +Never executes GCC. No imports of prior controllers or the helper in-process. +""" +import argparse +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import selectors +import signal +import stat +import subprocess +import sys +import time + +HERE = Path(__file__).resolve().parent +HELPER = HERE / 'passive_image_candidates_v3.py' +HELPER_SHA = '166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41' +HELPER_SIZE = 12726 +OPERATION_ADMITTED = False +TARGET = '/usr/bin/x86_64-linux-gnu-gcc-13' +TARGET_SHA = '1b99826121ae6682a634e5efe09bd3e3df58ce58e0b28f849114ab5b89139c26' +TOOLS = { + '/usr/bin/python3.12': (8020928, 'e50d468e8b0adfb05733f5b87b3cff34829c4a8c1aea50c865aa8bdfe4bb150f'), + '/usr/bin/x86_64-linux-gnu-readelf': (789280, '64c58e15274bbbb5153f31078e455e9e77ee5f51489e709bba5bb788ce9df2b0'), + '/usr/bin/x86_64-linux-gnu-objdump': (390848, '325c4205a4c658a9d1e1ebc469ae55975a2b897a3d3c1e79d9b158612d37f745')} +RAW_CAP, TOTAL_CAP, RESERVE = 786432, 1048576, 262144 +MEM_CAP = 1073741824 +KNOWN_CAP = 128 +RAW_ERROR_CAP = 4096 + +class Stop(RuntimeError): + pass + +def need(ok, reason): + if not ok: + raise Stop(reason) + +def digest(b): + return hashlib.sha256(b).hexdigest() + +class RawErrors: + """C10 delivered-error cells, conditional on private state/adequate unwind. + + No universal allocation, async, pre-handler or inherited-helper claim. + The first traceback cell is never replaced by a later rethrow traceback. + With at most128 known pidfds, one failed step and no next launch,4096 + secondary cells exceed the finite independent cleanup attempt sites. + Capacity exhaustion itself remains quarantine/INCOMPLETE, never success. + """ + def __init__(self): + self.first = [None, None] + self.errors = [None] * RAW_ERROR_CAP + self.tracebacks = [None] * RAW_ERROR_CAP + self.count = 0 + self.overflow = [None, None] + self.quarantined = False + def capture(self, error): + if self.first[0] is None: + self.first[0] = error + self.first[1] = error.__traceback__ + elif error is not self.first[0]: + index = self.count + if index >= RAW_ERROR_CAP: + self.quarantined = True + if self.overflow[0] is None: + self.overflow[0] = error + self.overflow[1] = error.__traceback__ + return + self.errors[index] = error + self.tracebacks[index] = error.__traceback__ + self.count = index + 1 + def deliver(self): + if self.first[0] is not None: + raise BaseException.with_traceback(self.first[0], self.first[1]) + def ready(self): + self.deliver() + need(not self.quarantined, 'uncertain acquisition/close; no further operation') + +def acquire(slot, errors, operation, *args, allow_primary=False, **kwargs): + """Slot exists before native return; pending remains pending on ambiguity.""" + if allow_primary: + need(not errors.quarantined, 'uncertainty forbids even failure-capture acquisition') + else: + errors.ready() + need(slot[0] is None, 'owner slot already used') + slot[0] = 'PENDING' + try: + slot[1] = operation(*args, **kwargs) + slot[0] = 'KNOWN' + return slot[1] + except BaseException as error: + errors.capture(error) + errors.quarantined = True + errors.deliver() + +def close_slot(slot, errors, object_close=False): + """Retire ownership before one close; no blind numeric retry after error.""" + if slot[0] == 'PENDING': + errors.quarantined = True + return False + if slot[0] != 'KNOWN': + return True + value = slot[1] + slot[1] = None + slot[0] = 'RETIRED' + try: + if object_close: + value.close() + else: + os.close(value) + return True + except BaseException as error: + errors.capture(error) + errors.quarantined = True + return False + +def read_pin(path, count, expected, errors=None, owner=None): + if errors is None: errors = RawErrors() + errors.ready() + if owner is None: owner = [None, None] + failed = False + result = None + try: + fd = acquire(owner, errors, os.open, path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW) + before = os.fstat(fd) + need(stat.S_ISREG(before.st_mode) and before.st_size == count, 'pin size/type: '+str(path)) + data = bytearray() + while len(data) <= count: + chunk = os.read(fd, min(65536, count+1-len(data))) + if not chunk: + break + data.extend(chunk) + after = os.fstat(fd) + fields = ('st_dev','st_ino','st_mode','st_size','st_mtime_ns','st_ctime_ns') + need(all(getattr(before,k)==getattr(after,k) for k in fields), 'pin changed: '+str(path)) + need(len(data)==count and digest(data)==expected, 'pin mismatch: '+str(path)) + os.lseek(fd,0,0) + result = fd, bytes(data), {k:getattr(after,k) for k in fields} + except BaseException as error: + errors.capture(error) + failed = True + if failed: + close_slot(owner, errors) + errors.deliver() + return result + +def proc_identity(pid): + try: + text=Path('/proc/'+str(pid)+'/stat').read_text() + except FileNotFoundError: + return None + need(len(text)<=4096,'proc stat bound') + parts=text.rsplit(')',1)[1].split() + return (int(parts[19]),int(parts[1]),int(parts[2]),int(parts[3])) + +class Guard: + def __init__(self, out, started, already_retained, errors=None): + self.errors = RawErrors() if errors is None else errors + self.pidfd_owners = [[None, None] for unused in range(KNOWN_CAP)] + self.pipe_owners = [[None, None], [None, None]] + self.process_owner = [None, None] + self.poller_owner = [None, None] + self.write_owner = [None, None] + self.out, self.raw, self.total = out, 0, already_retained + self.started = started + self.deadline = self.started + 55 # final five seconds reserved for cleanup/receipt + self.child = None + self.known = {} + self.pidfds = {} + self.steps = [] + self.peak_sampled_rss = 0 + self.launches = 0 + def write(self, name, data, raw=False, failure_capture=False): + owner = self.write_owner + failed = False + try: + if failure_capture: + need(not self.errors.quarantined,'uncertainty forbids failure capture') + else: + self.errors.ready() + need(owner[0] in (None,'RETIRED'),'write owner not reusable') + owner[0]=None + owner[1]=None + need('/' not in name and len(name)<100, 'output name') + if raw: + need(self.raw+len(data)<=RAW_CAP and self.total+len(data)<=TOTAL_CAP-RESERVE, + 'shared raw/retention cap') + need(self.total+len(data)<=TOTAL_CAP, 'all new output cap') + fd = acquire(owner, self.errors, os.open, self.out/name, + os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_CLOEXEC,0o600, + allow_primary=failure_capture) + view=memoryview(data) + while view: + n=os.write(fd,view) + need(n>0,'short output write') + self.total += n + if raw: self.raw += n + view=view[n:] + except BaseException as error: + self.errors.capture(error) + failed = True + closed = close_slot(owner, self.errors) + if failed or not closed: + self.errors.deliver() + def register(self,pid,identity): + self.errors.ready() + owner = None + for slot in self.pidfd_owners: + if slot[0] is None: + owner = slot + break + try: + need(owner is not None, 'known process ownership capacity') + fd=acquire(owner,self.errors,os.pidfd_open,pid,0) + again=proc_identity(pid) + need(again is not None and again[0]==identity, 'pidfd adoption identity uncertain') + self.known[pid]=identity + self.pidfds[pid]=fd + except BaseException as error: + self.errors.capture(error) + self.errors.quarantined = True + if owner is not None: close_slot(owner,self.errors) + self.errors.deliver() + def sample(self): + need(time.monotonic()0,'stream cap+1: '+name) + block=os.read(key.fileobj.fileno(),min(8192,remaining)) + if not block: + sel.unregister(key.fileobj); continue + buffers[index].extend(block) + need(len(buffers[index])<=caps[index],'stream cap+1: '+name) + need(self.raw+sum(map(len,buffers))<=RAW_CAP,'combined raw cap') + rec['returncode']=self.child.wait(timeout=.1) + rec['status']='EXITED' + need(rec['returncode']==0,'nonzero exit: '+name) + except BaseException as error: + self.errors.capture(error) + finally: + active=self.child + try: + self.cleanup() + except BaseException as error: + self.errors.capture(error) + # These are independent attempts, never a shared short-circuit statement. + close_slot(selector_owner,self.errors,True) + close_slot(tool_owner,self.errors) + try: + if rec is not None: + rec['status']='STOP' if self.errors.first[0] is not None else rec['status'] + if active is not None: rec['returncode']=active.returncode + rec['wall_seconds']=time.monotonic()-began + rec['capture_complete']=False + # A failed/unqualified capture remains incomplete. Do not + # open raw or receipt files after any delivered uncertainty. + if not self.errors.quarantined: + for index,buf in enumerate(buffers): + over=len(buf)>caps[index] + self.write(name+('.stdout' if index==0 else '.stderr'),bytes(buf),raw=not over, + failure_capture=self.errors.first[0] is not None) + rec['raw_retained_bytes'][index]=len(buf) + rec['sha256']=[digest(buf) for buf in buffers] + rec['capture_complete']=self.errors.first[0] is None + except BaseException as error: + self.errors.capture(error) + if rec is not None: + rec['capture_complete']=False + self.errors.deliver() + need(not self.errors.quarantined,'step cleanup uncertain; no next launch') + return bytes(buffers[0]) + +def bind_window(text, B, load, start, stop, candidate): + covered=set() + for line in text.decode('ascii','strict').splitlines(): + m=re.match(r'^\s*([0-9a-fA-F]+):\s+(.*)$',line) + if not m: continue + addr=int(m.group(1),16) + raw=re.match(r'^((?:[0-9a-fA-F]{2}(?:\s+|$))+)',m.group(2)) + need(raw is not None,'decoder address row without raw bytes') + b=bytes.fromhex(raw.group(1)) + need(start<=addr and addr+len(b)<=stop,'decoder raw outside nominated window') + off=load['offset']+addr-load['vaddr'] + need(B[off:off+len(b)]==b,'decoder raw differs from authoritative B') + covered.update(range(off,off+len(b))) + off=candidate['file_offset'] + need(set(range(off,off+candidate['span_bytes']))<=covered,'candidate raw not present in decoder rows') + +def main(): + """Actual local callable. No formatted replacement or renewed admission. + + C10 claims exclude signal interference, hard os._exit, inherited helpers, + pre-return uncertainty and genuine enclosing process/namespace authority. + """ + errors=RawErrors() + owners=[[None,None] for unused in range(6)] + started=time.monotonic() + active_guard=[None] + g=None + status='STOP' + metadata=hs=None + baseline=0 + args=None + def alarm(signum,frame): + # Retained deadline path, explicitly OUTSIDE the no-async C10 claim. + if time.monotonic()-started>=59.9: + current=active_guard[0] + if current is not None and current.child is not None: + for descriptor in current.pidfds.values(): + try: signal.pidfd_send_signal(descriptor,signal.SIGKILL) + except ProcessLookupError: pass + for pid,born in current.known.items(): + info=proc_identity(pid) + if info is not None and info[0]==born and info[2:]==(current.child.pid,current.child.pid): + try: os.killpg(current.child.pid,signal.SIGKILL) + except ProcessLookupError: pass + break + try: os.write(2,b'STOP: hard60s deadline; terminal may be incomplete\n') + finally: os._exit(124) + signal.setitimer(signal.ITIMER_REAL,max(.001,60-(time.monotonic()-started))) + raise Stop('wall/signal stop '+str(signum)) + try: + # This successor is source-only. A fake namespace may replace this + # literal for isolated controls; no genuine operation is admitted here. + need(OPERATION_ADMITTED is True,'source-only successor; actual operation withheld') + signal.signal(signal.SIGALRM,alarm) + signal.signal(signal.SIGTERM,alarm) + signal.signal(signal.SIGINT,alarm) + signal.setitimer(signal.ITIMER_REAL,55) + ap=argparse.ArgumentParser() + ap.add_argument('--admission',required=True) + ap.add_argument('--admission-sha256',required=True) + ap.add_argument('--token',required=True) + args=ap.parse_args() + need(re.fullmatch(r'[A-Za-z0-9_-]{8,64}',args.token),'fresh token format') + admission_path=Path(args.admission) + need(admission_path.is_absolute(),'absolute admission path') + admission_size=admission_path.stat().st_size + need(0=60 and a.get('remaining_total_seconds',0)>=60,'remaining budgets') + need(a.get('supervisor_sha256')==digest(Path(__file__).read_bytes()),'supervisor source pin') + need(a.get('helper_sha256')==HELPER_SHA,'helper source pin') + baseline=a.get('already_retained_new_bytes') + need(type(baseline) is int and 0<=baseline<=262144,'existing new output reservation') + # The original closed round epoch is retained, never renewed. + need(a.get('round_hard_stop_epoch')==1793664771.401519,'fixed round hardstop') + need(time.time()+60<=a['round_hard_stop_epoch'],'insufficient fixed round time') + lockfd=acquire(owners[1],errors,os.open,HERE/'private-one-pass.lock', + os.O_CREAT|os.O_RDWR|os.O_CLOEXEC|os.O_NOFOLLOW,0o600) + ls=os.fstat(lockfd) + need(stat.S_ISREG(ls.st_mode) and ls.st_uid==os.getuid() and ls.st_mode&0o077==0,'private lock ownership/mode') + fcntl.flock(lockfd,fcntl.LOCK_EX|fcntl.LOCK_NB) + marker=acquire(owners[2],errors,os.open,HERE/'ONE-PASS-STARTED', + os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_CLOEXEC,0o600) + need(os.write(marker,args.token.encode())==len(args.token),'short permanent marker write') + close_slot(owners[2],errors) + errors.ready() + out=HERE/('run-'+args.token) + out.mkdir(mode=0o700) + g=Guard(out,started,baseline+len(args.token),errors) + active_guard[0]=g + fd,B,metadata=read_pin(TARGET,1023032,TARGET_SHA,errors,owners[3]) + hf,hb,hs=read_pin(HELPER,HELPER_SIZE,HELPER_SHA,errors,owners[4]) + del hb + need(time.monotonic()-started<=10,'setup identity capture allocation') + helper=g.run('helper',['/usr/bin/python3.12','-B','-S','/proc/self/fd/'+str(hf)],5,(65536,16384),(hf,)) + r=json.loads(helper) + need(r.get('status')=='PARTIAL_LOCALISATION_DATA_ONLY' and r.get('candidate_overflow') is False, + 'structured helper STOP/overflow') + need(r.get('image_sha256')==TARGET_SHA and r.get('image_bytes')==len(B),'helper B binding') + need(r.get('certificate_feasible') is False and r.get('full_C05') is False and r.get('full_V03') is False,'helper scope') + refs=r['references'] + need(len(refs)<=8,'candidate count') + for candidate in refs: + off=candidate['file_offset'] + n=candidate['span_bytes'] + need(0<=off<=len(B) and 0=n,'window VA binding') + need(not any(row is not load and max(start,row['vaddr'])','exec'),env) + return env + +class Poison(Exception): + calls=0 + def __str__(self): + type(self).calls+=1 + raise RuntimeError('formatter must not be called') + def __repr__(self): + type(self).calls+=1 + raise RuntimeError('formatter must not be called') + +class TokenPath: + def __init__(self,value): self.value=str(value) + def __truediv__(self,value): return TokenPath(self.value+'/'+str(value)) + def __str__(self): return self.value + def is_absolute(self): return True + def stat(self): return SimpleNamespace(st_size=3) + def read_text(self): return '' if self.value.endswith('children') else '0 1' + def read_bytes(self): raise RuntimeError('fake path byte read not admitted') + def mkdir(self,**kwargs): raise RuntimeError('fake main must fail before directory creation') + +class TokenOS: + O_RDONLY=0; O_CLOEXEC=1; O_NOFOLLOW=2; O_WRONLY=4; O_CREAT=8; O_EXCL=16; O_RDWR=32 + def __init__(self): + self.events=[]; self.next=500; self.blocks={}; self.close_errors={} + self.fstat_error=None; self.write_plan=[]; self.close_observer=None + def open(self,path,*args): + self.next+=1; token=self.next + self.events.append(('open',token)); self.blocks[token]=[b'abc',b''] + return token + def fstat(self,fd): + if self.fstat_error is not None: raise self.fstat_error + return SimpleNamespace(st_dev=1,st_ino=fd,st_mode=0,st_size=3, + st_mtime_ns=0,st_ctime_ns=0,st_uid=1000) + def read(self,fd,count): + self.events.append(('read',fd)) + blocks=self.blocks.get(fd) + return blocks.pop(0) if blocks else b'' + def write(self,fd,data): + self.events.append(('write',fd)) + if self.write_plan: + item=self.write_plan.pop(0) + if isinstance(item,BaseException): raise item + return item + return len(data) + def close(self,fd): + if self.close_observer is not None: self.close_observer(fd) + self.events.append(('close',fd)) + if fd in self.close_errors: raise self.close_errors[fd] + def lseek(self,*args): return 0 + def pidfd_open(self,pid,flags): + self.events.append(('pidfd',pid)); return 1500+pid + def set_blocking(self,*args): return None + def killpg(self,*args): self.events.append(('killpg',args[0])) + def getpid(self): return 1 + def getuid(self): return 1000 + def sysconf(self,name): return 4096 + +class Clock: + def __init__(self): self.value=0 + def monotonic(self): self.value+=0.001; return self.value + def time(self): return 0 + +class TokenStream: + def __init__(self,fixture,label,fd): self.fixture=fixture; self.label=label; self.fd=fd + def fileno(self): return self.fd + def close(self): + self.fixture.events.append(('stream-close',self.label)) + error=self.fixture.stream_errors.get(self.label) + if error is not None: raise error + +class TokenProcess: + pid=3; returncode=0 + def __init__(self,fixture): + self.fixture=fixture + self.stdout=TokenStream(fixture,'stdout',701) + self.stderr=TokenStream(fixture,'stderr',702) + def wait(self,**kwargs): return 0 + def poll(self): return 0 + +class TokenSelector: + def __init__(self,fixture): + self.fixture=fixture; fixture.selector_count+=1; self.ordinal=fixture.selector_count; self.rows={} + def register(self,obj,event,data=None): + fd=obj if type(obj) is int else obj.fileno() + self.rows[fd]=SimpleNamespace(fd=fd,fileobj=obj,data=data) + def unregister(self,obj): + fd=obj if type(obj) is int else obj.fileno() + del self.rows[fd] + def get_map(self): return self.rows + def select(self,timeout): return [(row,1) for row in list(self.rows.values())] + def close(self): + self.fixture.events.append(('selector-close',self.ordinal)) + error=self.fixture.selector_errors.get(self.ordinal) + if error is not None: raise error + +class Fixture: + def __init__(self): + self.os=TokenOS(); self.clock=Clock(); self.events=[]; self.stream_errors={}; self.selector_errors={} + self.selector_count=0; self.spawn_error=None; self.disarm_error=None; self.json_calls=0 + def popen(self,*args,**kwargs): + self.events.append(('launch',1)) + if self.spawn_error is not None: raise self.spawn_error + return TokenProcess(self) + def setitimer(self,which,seconds): + self.events.append(('timer',seconds)) + if seconds==0 and self.disarm_error is not None: raise self.disarm_error + def namespace(self): + def forbidden(*args,**kwargs): raise RuntimeError('unreviewed fake boundary called') + def loads(raw): + self.json_calls+=1 + raise RuntimeError('main must fail before JSON body') + parser=SimpleNamespace(add_argument=lambda *a,**k:None, + parse_args=lambda:SimpleNamespace(admission='/FAKE/admission', + admission_sha256=hashlib.sha256(b'abc').hexdigest(),token='token123')) + signals=SimpleNamespace(SIGTERM=15,SIGKILL=9,SIGALRM=14,SIGINT=2,ITIMER_REAL=0, + signal=lambda *a:None,setitimer=self.setitimer, + pidfd_send_signal=lambda *a:None) + return {'os':self.os,'time':self.clock,'hashlib':hashlib, + 'Path':TokenPath,'HERE':TokenPath('/FAKE'),'__file__':'/FAKE/guard.py', + 'RAW_ERROR_CAP':4096,'KNOWN_CAP':128,'RAW_CAP':786432,'TOTAL_CAP':1048576,'RESERVE':262144, + 'MEM_CAP':1073741824,'TOOLS':{'/FAKE/tool':(3,hashlib.sha256(b'abc').hexdigest())}, + 'TARGET':'/FAKE/target','TARGET_SHA':'0'*64,'HELPER':TokenPath('/FAKE/helper'), + 'HELPER_SHA':HELPER_SHA,'HELPER_SIZE':12726,'OPERATION_ADMITTED':True, + 'stat':SimpleNamespace(S_ISREG=lambda mode:True), + 'selectors':SimpleNamespace(DefaultSelector=lambda:TokenSelector(self),EVENT_READ=1), + 'subprocess':SimpleNamespace(Popen=self.popen,DEVNULL=-3,PIPE=-1, + TimeoutExpired=type('TokenTimeout',(Exception,),{})), + 'signal':signals,'proc_identity':lambda pid:(10+pid,1,pid,pid), + 'argparse':SimpleNamespace(ArgumentParser=lambda:parser),'re':__import__('re'), + 'fcntl':SimpleNamespace(flock=forbidden,LOCK_EX=1,LOCK_NB=2), + 'json':SimpleNamespace(loads=loads,dumps=forbidden),'sys':SimpleNamespace(stderr=forbidden)} + def env(self,text): return definitions(text,NAMES,self.namespace()) + def guard(self,env): return env['Guard'](TokenPath('/FAKE/out'),0,0) + + +def raw_frame(error, raw_type): + tb=error.__traceback__ + while tb is not None: + candidate=tb.tb_frame.f_locals.get('errors') + if isinstance(candidate,raw_type): return candidate + tb=tb.tb_next + raise RuntimeError('raw state absent from actual caller traceback') + +def body_failure(errors,error): + try: raise error + except BaseException as caught: errors.capture(caught) + return errors.first[1] + +def record(name,details=None): ROWS.append({'id':name,'status':'PASS_FAKE_ONLY','details':details}) + +def main(): + source=bound_text(SOURCE,SOURCE_SHA) + predecessor=bound_text(PREDECESSOR,PREDECESSOR_SHA) + helper=bound_text(HELPER,HELPER_SHA) + reference=bound_text(REFERENCE,REFERENCE_SHA) + old_helper=OLD_HELPER.read_text() + require(helper.split('def main():',1)[0]==old_helper.split('def main():',1)[0], + 'pure locator body/data drift; prior23 controls cannot transfer') + + # F01 independent original oracle, exact read_pin plus selected locator main. + f=Fixture(); env=f.env(source); errors=env['RawErrors'](); owner=[None,None] + A=ValueError('A'); B=OSError('B'); f.os.fstat_error=A; f.os.close_errors[501]=B + first_tb_seen=[None] + def observe_root(fd): first_tb_seen[0]=errors.first[1] + f.os.close_observer=observe_root + actual=capture(lambda:env['read_pin']('/FAKE/input',3,'ignored',errors,owner)) + require(actual is A and errors.first[0] is A and errors.first[1] is not None and + errors.first[1] is first_tb_seen[0] and errors.errors[0] is B and + f.os.events.count(('close',501))==1,'F01 read identity/order') + oldf=Fixture(); oldf.os.fstat_error=A; oldf.os.close_errors[501]=B + oldenv=definitions(predecessor,('Stop','need','digest','read_pin'),oldf.namespace()) + require(capture(lambda:oldenv['read_pin']('/FAKE/input',3,'ignored')) is B,'F01 predecessor negative lost') + helperf=Fixture(); helperf.os.fstat_error=A; helperf.os.close_errors[501]=B + helper_ns=helperf.namespace(); helper_ns.update(EXPECTED_PATH='/FAKE/input',EXPECTED_SIZE=3, + EXPECTED_SHA='ignored',MAX_INPUT=3) + helperenv=definitions(helper,('Stop','need','main'),helper_ns) + helper_actual=capture(helperenv['main']) + require(helper_actual is A,'F01 actual helper main replaced A') + helper_tb=helper_actual.__traceback__ + while helper_tb is not None and 'secondary' not in helper_tb.tb_frame.f_locals: helper_tb=helper_tb.tb_next + require(helper_tb is not None and helper_tb.tb_frame.f_locals['secondary'][0] is B, + 'F01 helper raw secondary absent') + record('F01') + + # F02 write progress + ENOSPC A / EIO B; old actual write still refutes it. + f=Fixture(); env=f.env(source); g=f.guard(env); A=OSError('ENOSPC'); B=OSError('EIO') + f.os.write_plan=[1,A]; f.os.close_errors[501]=B + require(capture(lambda:g.write('part',b'abc',raw=True)) is A and g.total==1 and g.raw==1 and + g.errors.errors[0] is B and f.os.events.count(('close',501))==1,'F02 write primary/progress') + oldf=Fixture(); oldenv=definitions(predecessor,('Stop','need','Guard'),oldf.namespace()) + oldg=oldenv['Guard'](TokenPath('/FAKE/out'),0,0); oldf.os.write_plan=[1,A]; oldf.os.close_errors[501]=B + require(capture(lambda:oldg.write('part',b'abc',raw=True)) is B,'F02 predecessor negative lost') + record('F02') + + # F03/F04 complete actual cleanup; raw B,C identities, no formatted oracle. + for prior in (True,False): + f=Fixture(); env=f.env(source); g=f.guard(env); p=TokenProcess(f) + g.child=p; g.process_owner[:]=['KNOWN',p] + g.pipe_owners[0][:]=['KNOWN',p.stdout]; g.pipe_owners[1][:]=['KNOWN',p.stderr] + A=ValueError('A'); B=OSError('B'); C=OSError('C'); f.stream_errors={'stdout':B,'stderr':C} + first_tb=body_failure(g.errors,A) if prior else None + actual=capture(g.cleanup) + require(actual is (A if prior else B),'F03/F04 same outward primary') + expected=[B,C] if prior else [C] + require([g.errors.errors[i] for i in range(g.errors.count)]==expected, + 'F03/F04 ordered raw secondaries') + require(f.events.count(('stream-close','stdout'))==1 and f.events.count(('stream-close','stderr'))==1, + 'F03/F04 independent closes') + if prior: require(g.errors.first[1] is first_tb,'F03 first traceback root replaced') + capture(g.cleanup) + require(f.events.count(('stream-close','stdout'))==1,'F03/F04 blind retry') + require(capture(lambda:g.run('next',['/FAKE/tool'],1,(3,3))) is (A if prior else B) + and not any(row[0]=='launch' for row in f.events),'F03/F04 later launch') + record('F03' if prior else 'F04') + + # F05 complete run: selector B must not skip independent toolfd C. + f=Fixture(); env=f.env(source); g=f.guard(env); B=OSError('selector B'); C=OSError('tool C') + f.selector_errors[1]=B; f.os.close_errors[501]=C + actual=capture(lambda:g.run('one',['/FAKE/tool'],1,(3,3))) + require(actual is B and g.errors.errors[0] is C and f.os.events.count(('close',501))==1, + 'F05 independent selector/tool close') + require(not g.steps[0]['capture_complete'],'F05 capture incorrectly successful') + record('F05') + + # F06 actual register: returned pidfd rooted before failing observation. + f=Fixture(); env=f.env(source); g=f.guard(env); A=PermissionError('post-return A') + def denied(pid): raise A + env['proc_identity']=denied + require(capture(lambda:g.register(3,13)) is A and g.pidfd_owners[0][0]=='RETIRED' and + f.os.events.count(('close',1503))==1,'F06 returned-owner gap') + record('F06') + + # F07 complete actual run with ambiguous Popen pre-return failure. + f=Fixture(); env=f.env(source); g=f.guard(env); A=OSError('uncertain spawn'); f.spawn_error=A + require(capture(lambda:g.run('one',['/FAKE/tool'],1,(3,3))) is A,'F07 outward identity') + require(g.process_owner[0]=='PENDING' and g.process_owner[1] is None and g.errors.quarantined, + 'F07 pending owner erased') + require(not any(row[0]=='write' for row in f.os.events) and f.os.events.count(('close',501))==1, + 'F07 new I/O or missing known close') + require(capture(lambda:g.run('two',['/FAKE/tool'],1,(3,3))) is A and + len([row for row in f.events if row[0]=='launch'])==1,'F07 subsequent launch') + record('F07') + + # F08 numeric owner removed before ambiguous close; no retry. + f=Fixture(); env=f.env(source); errors=env['RawErrors'](); slot=['KNOWN',901]; B=OSError('ambiguous') + f.os.close_errors[901]=B + def retired(fd): require(slot[0]=='RETIRED' and slot[1] is None,'F08 numeric owner still live') + f.os.close_observer=retired + env['close_slot'](slot,errors); env['close_slot'](slot,errors) + require(errors.first[0] is B and errors.quarantined and f.os.events==[('close',901)],'F08 retry') + record('F08') + + # F09 actual selected main over exact read_pin; str/repr poison never called. + f=Fixture(); env=f.env(source); A=Poison(); f.os.fstat_error=A; Poison.calls=0 + actual=capture(env['main']); errors=raw_frame(actual,env['RawErrors']) + require(actual is A and errors.first[0] is A and errors.first[1] is not None and + Poison.calls==0 and f.json_calls==0,'F09 raw main/formatting boundary') + record('F09') + + # F10 cleanup-only fault on successful complete actual run, no next payload. + f=Fixture(); env=f.env(source); g=f.guard(env); B=OSError('pipe close'); f.stream_errors['stdout']=B + require(capture(lambda:g.run('one',['/FAKE/tool'],1,(3,3))) is B and + not g.steps[0]['capture_complete'],'F10 cleanup-only success') + require(capture(lambda:g.run('two',['/FAKE/tool'],1,(3,3))) is B and + len([row for row in f.events if row[0]=='launch'])==1 and + len([row for row in f.os.events if row[0]=='open'])==1,'F10 next launch/publication') + record('F10') + + # F11 source-fixed known-owner bound and conservative independent-site count. + f=Fixture(); env=f.env(source); g=f.guard(env); errors=g.errors + require(len(g.pidfd_owners)==128 and len(errors.errors)==4096,'F11 preallocated capacity') + arrays=(errors.first,errors.errors,errors.tracebacks) + first_tb=body_failure(errors,ValueError('A')); B=OSError('B') + maximum=2*128+2*128+2+1+1+128+2+2+6+20 + require(maximum<4096,'F11 finite close-site bound exceeds cells') + for unused in range(maximum): errors.capture(B) + require(errors.first is arrays[0] and errors.errors is arrays[1] and errors.tracebacks is arrays[2] + and errors.first[1] is first_tb and errors.count==maximum,'F11 raw storage changed') + record('F11',{'conditional_secondary_site_bound':maximum,'capacity':4096, + 'no_universal_allocation_claim':True}) + + # F12 exact6346 helper RED ledger/snapshot/recording counterexamples. + red=[] + for fault in ('ledger','snapshot','record'): + attempts=[]; A=ValueError('A'); allocation=MemoryError('retained stronger witness') + B=OSError('close B') + def close(fd): attempts.append(fd); raise B + env=definitions(reference,('_RawG12Errors','_close_known_descriptors','_finally_close_known'), + {'os':SimpleNamespace(close=close),'sys':sys}) + def bad(*args): raise allocation + if fault=='ledger': env['_RawG12Errors']=bad + elif fault=='snapshot': env['tuple']=bad + else: env['_RawG12Errors']=type('BadRecorder',(),{'append':lambda self,value:bad()}) + def witness(): + try: raise A + finally: env['_finally_close_known']([901,902,903],[]) + actual=capture(witness) + require(actual is allocation and actual is not A and attempts==([903] if fault=='record' else []), + 'F12 retained RED counterexample changed') + red.append({'fault':fault,'status':'RED_RETAINED_STRONGER_CONTRACT','close_attempts':attempts}) + record('F12',red) + + # F13 unfaulted actual read/write/run; no spurious quarantine or credit. + f=Fixture(); env=f.env(source); errors=env['RawErrors'](); owner=[None,None] + result=env['read_pin']('/FAKE/input',3,hashlib.sha256(b'abc').hexdigest(),errors,owner) + require(result[0]==501 and result[1]==b'abc' and owner[0]=='KNOWN','F13 read/owner transfer') + env['close_slot'](owner,errors) + g=f.guard(env); g.write('raw',b'abc',raw=True) + require(g.raw==3 and g.total==3 and g.errors.first[0] is None and not g.errors.quarantined,'F13 write') + f=Fixture(); env=f.env(source); g=f.guard(env) + require(g.run('one',['/FAKE/tool'],1,(3,3))==b'' and g.steps[0]['capture_complete'] and + not g.errors.quarantined,'F13 actual run success baseline') + record('F13') + + # F14 outer actual main itself faults after nested A is protected. No JSON. + f=Fixture(); env=f.env(source); A=ValueError('A'); B=OSError('close B'); C=OSError('outer timer C') + f.os.fstat_error=A; f.os.close_errors[501]=B; f.disarm_error=C + actual=capture(env['main']); errors=raw_frame(actual,env['RawErrors']) + require(actual is A and errors.first[0] is A and errors.errors[0] is B and errors.errors[1] is C + and f.json_calls==0 and len([row for row in f.os.events if row[0]=='open'])==1, + 'F14 outer finalization replaced A or continued publication') + record('F14') + require(len(ROWS)==14 and len({row['id'] for row in ROWS})==14,'fourteen independent cases changed') + print(json.dumps({'status':'PASS_BOUNDED_FAKE_ONLY','cases':ROWS,'source_sha256':SOURCE_SHA, + 'helper_sha256':HELPER_SHA,'actual_operation':False,'original_credit':0, + 'full_C05':False,'full_V03':False,'costs':'OPEN_NOT_ZERO'},sort_keys=True)) + +if __name__=='__main__': main() diff --git a/research/h25-passive-guard-primary-preservation/evidence/ADMISSION-v1.json b/research/h25-passive-guard-primary-preservation/evidence/ADMISSION-v1.json new file mode 100644 index 0000000000..43fc40d136 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/evidence/ADMISSION-v1.json @@ -0,0 +1,24 @@ +{ + "schema": "parent-only-inert-controls-admission-v1", + "issued_utc": "2026-11-03T05:11:26.431Z", + "status": "ADMITTED_EXACT_FAKE_ONLY", + "scope": "Complete definitions extracted into reviewed inert fake namespace; no whole candidate import, native/process/proc/decoder/compiler/target operation", + "source_hashes": { + "parent_passive_supervisor_v4.py": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", + "passive_image_candidates_v3.py": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", + "verify_guard_fake_v1.py": "c71dcf2dfd944282210f105ef54d23a4deb6e1eaaa0a9068a2ea584292ea365e" + }, + "review": "outputs/c05-v03-pro-workitems-20261103T0435Z/review/PUBLICATION-ADAPTER-REVIEW-v1.json", + "modes": [ + "normal", + "optimized" + ], + "per_mode_once": true, + "per_command_seconds": 10, + "policy_reservation_seconds": 20, + "policy_minimum_seconds_per_attempt": 1, + "source_grant": false, + "scientific_grant": false, + "actual_operation_admitted": false, + "hard_stop_utc": "2026-11-03T05:20:29Z" +} diff --git a/research/h25-passive-guard-primary-preservation/evidence/CONTROLS-PLAN.json b/research/h25-passive-guard-primary-preservation/evidence/CONTROLS-PLAN.json new file mode 100644 index 0000000000..6ed88d4a02 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/evidence/CONTROLS-PLAN.json @@ -0,0 +1,27 @@ +{ + "schema": "new-fake-only-controls-plan-v1", + "created_utc": "2026-11-03T04:57:55.033Z", + "status": "DRAFT_NOT_EXECUTION_GRANT_PENDING_EXACT_SOURCE_AND_INDEPENDENT_REVIEW", + "scope": "Complete selected source definitions extracted by AST into inert manually controlled fake capabilities; no whole candidate imports/CLI, no actual process/syscall/target/native/compiler/decoder", + "modes": [ + "normal", + "optimized" + ], + "runs_per_mode": 1, + "retry": false, + "per_command_seconds": 10, + "outer_kill_tail_seconds": 1, + "serial_queue": "Only parent; fresh private workitems controls queue; never touch historical locks", + "required_review": "Exact harness/guard/helper hashes, extraction safety and all fake dependencies; independent14case oracles plus retained predecessor negatives", + "raw_outputs": "Unique exclusive mode.stdout/mode.stderr/mode.time; retain failures unchanged", + "policy_reservation_seconds": 20, + "new_budget": false, + "canonical_old_seconds": 94.550533479, + "prior_supplemental_combined_seconds": 104.890533479, + "policy_charge_rule": "Each attempted controlled command debits max(1 second, ceiling(observed parent tool call wall milliseconds)/1000). This conservative policy debit is not a complete physical measurement.", + "measurements": "Retain GNUtime elapsed/user/system/maxRSS/exit plus toolwall and all stdout/stderr. MaxRSS only covers timed test process, not a complete runtime family or original qualification.", + "physical_costs": "OPEN_NOT_ZERO", + "hard_stop_utc": "2026-11-03T05:20:29Z", + "source_freeze_utc": "2026-11-03T05:05:29Z", + "operation_admitted": false +} diff --git a/research/h25-passive-guard-primary-preservation/evidence/LEDGER-v1.json b/research/h25-passive-guard-primary-preservation/evidence/LEDGER-v1.json new file mode 100644 index 0000000000..033f6e6a12 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/evidence/LEDGER-v1.json @@ -0,0 +1,263 @@ +{ + "schema": "bounded-fake-controls-ledger-v1", + "created_utc": "2026-11-03T05:12:14.875Z", + "scope": "Fourteen fake-only cases per normal and optimized interpreter; actualsourcefunctions/inertcapabilities; no original/native/decoder/candidateCLI operation", + "modes": [ + { + "mode": "normal", + "status": "PASS_BOUNDED_FAKE_ONLY", + "cases": 14, + "all_cases": [ + { + "details": null, + "id": "F01", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F02", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F03", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F04", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F05", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F06", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F07", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F08", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F09", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F10", + "status": "PASS_FAKE_ONLY" + }, + { + "details": { + "capacity": 4096, + "conditional_secondary_site_bound": 674, + "no_universal_allocation_claim": true + }, + "id": "F11", + "status": "PASS_FAKE_ONLY" + }, + { + "details": [ + { + "close_attempts": [], + "fault": "ledger", + "status": "RED_RETAINED_STRONGER_CONTRACT" + }, + { + "close_attempts": [], + "fault": "snapshot", + "status": "RED_RETAINED_STRONGER_CONTRACT" + }, + { + "close_attempts": [ + 903 + ], + "fault": "record", + "status": "RED_RETAINED_STRONGER_CONTRACT" + } + ], + "id": "F12", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F13", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F14", + "status": "PASS_FAKE_ONLY" + } + ], + "source_sha256": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", + "helper_sha256": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", + "actual_operation": false, + "policy_debit_seconds": 1, + "tool_observed_seconds": 0.337, + "time_raw": "\tCommand being timed: \"/usr/bin/python3.12 -I -S -B /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-pro-workitems-20261103T0435Z/publication/stage/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py\"\n\tUser time (seconds): 0.26\n\tSystem time (seconds): 0.00\n\tPercent of CPU this job got: 99%\n\tElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.27\n\tAverage shared text size (kbytes): 0\n\tAverage unshared data size (kbytes): 0\n\tAverage stack size (kbytes): 0\n\tAverage total size (kbytes): 0\n\tMaximum resident set size (kbytes): 29000\n\tAverage resident set size (kbytes): 0\n\tMajor (requiring I/O) page faults: 0\n\tMinor (reclaiming a frame) page faults: 9226\n\tVoluntary context switches: 1\n\tInvoluntary context switches: 2\n\tSwaps: 0\n\tFile system inputs: 0\n\tFile system outputs: 2\n\tSocket messages sent: 0\n\tSocket messages received: 0\n\tSignals delivered: 0\n\tPage size (bytes): 4096\n\tExit status: 0\n", + "raw_files": [ + { + "file": "normal.stdout", + "bytes": 1527, + "sha256": "9f83227b4bed95c37e0a151219c1e70bdc8dae1129d0ebf6274c9d27bc3ea7a1" + }, + { + "file": "normal.stderr", + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "file": "normal.time", + "bytes": 1007, + "sha256": "1f999309a6f8f28ffd4b1a3cfdc2e3fe2a899e383dc1e10f3c7380d34ef389f9" + } + ] + }, + { + "mode": "optimized", + "status": "PASS_BOUNDED_FAKE_ONLY", + "cases": 14, + "all_cases": [ + { + "details": null, + "id": "F01", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F02", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F03", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F04", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F05", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F06", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F07", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F08", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F09", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F10", + "status": "PASS_FAKE_ONLY" + }, + { + "details": { + "capacity": 4096, + "conditional_secondary_site_bound": 674, + "no_universal_allocation_claim": true + }, + "id": "F11", + "status": "PASS_FAKE_ONLY" + }, + { + "details": [ + { + "close_attempts": [], + "fault": "ledger", + "status": "RED_RETAINED_STRONGER_CONTRACT" + }, + { + "close_attempts": [], + "fault": "snapshot", + "status": "RED_RETAINED_STRONGER_CONTRACT" + }, + { + "close_attempts": [ + 903 + ], + "fault": "record", + "status": "RED_RETAINED_STRONGER_CONTRACT" + } + ], + "id": "F12", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F13", + "status": "PASS_FAKE_ONLY" + }, + { + "details": null, + "id": "F14", + "status": "PASS_FAKE_ONLY" + } + ], + "source_sha256": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", + "helper_sha256": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", + "actual_operation": false, + "policy_debit_seconds": 1, + "tool_observed_seconds": 0.407, + "time_raw": "\tCommand being timed: \"/usr/bin/python3.12 -I -O -S -B /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-pro-workitems-20261103T0435Z/publication/stage/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py\"\n\tUser time (seconds): 0.33\n\tSystem time (seconds): 0.01\n\tPercent of CPU this job got: 100%\n\tElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.34\n\tAverage shared text size (kbytes): 0\n\tAverage unshared data size (kbytes): 0\n\tAverage stack size (kbytes): 0\n\tAverage total size (kbytes): 0\n\tMaximum resident set size (kbytes): 29160\n\tAverage resident set size (kbytes): 0\n\tMajor (requiring I/O) page faults: 0\n\tMinor (reclaiming a frame) page faults: 9604\n\tVoluntary context switches: 1\n\tInvoluntary context switches: 26\n\tSwaps: 0\n\tFile system inputs: 0\n\tFile system outputs: 2\n\tSocket messages sent: 0\n\tSocket messages received: 0\n\tSignals delivered: 0\n\tPage size (bytes): 4096\n\tExit status: 0\n", + "raw_files": [ + { + "file": "optimized.stdout", + "bytes": 1527, + "sha256": "9f83227b4bed95c37e0a151219c1e70bdc8dae1129d0ebf6274c9d27bc3ea7a1" + }, + { + "file": "optimized.stderr", + "bytes": 0, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "file": "optimized.time", + "bytes": 1012, + "sha256": "aac3d0c462b6b4163aa124778672f5cd8e30fad6af1d41c52b8908371c30ad42" + } + ] + } + ], + "prior_canonical_seconds": 94.550533479, + "prior_supplemental_combined_seconds": 104.890533479, + "additional_policy_debit_seconds": 2, + "supplemental_combined_seconds": 106.890533479, + "policy_is_not_complete_physical_cost": true, + "all_outside_costs": "OPEN_NOT_ZERO", + "new_budget": false, + "retry": false, + "original_credit_added": 0, + "original_weighted_percent": 43.5, + "full_C05": false, + "full_V03": false +} diff --git a/research/h25-passive-guard-primary-preservation/evidence/TOOL-OBSERVATIONS.json b/research/h25-passive-guard-primary-preservation/evidence/TOOL-OBSERVATIONS.json new file mode 100644 index 0000000000..d5a581c21f --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/evidence/TOOL-OBSERVATIONS.json @@ -0,0 +1,28 @@ +[ + { + "mode": "normal", + "observed_start_utc": "2026-11-03T05:11:26.464Z", + "observed_end_utc": "2026-11-03T05:11:26.801Z", + "observed_tool_call_seconds": 0.337, + "result": { + "chunk_id": "884dd9", + "wall_time_seconds": 0.168224905, + "exit_code": 0, + "original_token_count": 0, + "output": "" + } + }, + { + "mode": "optimized", + "observed_start_utc": "2026-11-03T05:11:48.268Z", + "observed_end_utc": "2026-11-03T05:11:48.675Z", + "observed_tool_call_seconds": 0.407, + "result": { + "chunk_id": "9229f0", + "wall_time_seconds": 0.238911422, + "exit_code": 0, + "original_token_count": 0, + "output": "" + } + } +] diff --git a/research/h25-passive-guard-primary-preservation/evidence/normal.stderr b/research/h25-passive-guard-primary-preservation/evidence/normal.stderr new file mode 100644 index 0000000000..e69de29bb2 diff --git a/research/h25-passive-guard-primary-preservation/evidence/normal.stdout b/research/h25-passive-guard-primary-preservation/evidence/normal.stdout new file mode 100644 index 0000000000..5496e96f67 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/evidence/normal.stdout @@ -0,0 +1 @@ +{"actual_operation": false, "cases": [{"details": null, "id": "F01", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F02", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F03", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F04", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F05", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F06", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F07", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F08", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F09", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F10", "status": "PASS_FAKE_ONLY"}, {"details": {"capacity": 4096, "conditional_secondary_site_bound": 674, "no_universal_allocation_claim": true}, "id": "F11", "status": "PASS_FAKE_ONLY"}, {"details": [{"close_attempts": [], "fault": "ledger", "status": "RED_RETAINED_STRONGER_CONTRACT"}, {"close_attempts": [], "fault": "snapshot", "status": "RED_RETAINED_STRONGER_CONTRACT"}, {"close_attempts": [903], "fault": "record", "status": "RED_RETAINED_STRONGER_CONTRACT"}], "id": "F12", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F13", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F14", "status": "PASS_FAKE_ONLY"}], "costs": "OPEN_NOT_ZERO", "full_C05": false, "full_V03": false, "helper_sha256": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", "original_credit": 0, "source_sha256": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", "status": "PASS_BOUNDED_FAKE_ONLY"} diff --git a/research/h25-passive-guard-primary-preservation/evidence/normal.time b/research/h25-passive-guard-primary-preservation/evidence/normal.time new file mode 100644 index 0000000000..b345608de2 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/evidence/normal.time @@ -0,0 +1,23 @@ + Command being timed: "/usr/bin/python3.12 -I -S -B /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-pro-workitems-20261103T0435Z/publication/stage/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py" + User time (seconds): 0.26 + System time (seconds): 0.00 + Percent of CPU this job got: 99% + Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.27 + 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): 29000 + Average resident set size (kbytes): 0 + Major (requiring I/O) page faults: 0 + Minor (reclaiming a frame) page faults: 9226 + Voluntary context switches: 1 + Involuntary context switches: 2 + Swaps: 0 + File system inputs: 0 + File system outputs: 2 + Socket messages sent: 0 + Socket messages received: 0 + Signals delivered: 0 + Page size (bytes): 4096 + Exit status: 0 diff --git a/research/h25-passive-guard-primary-preservation/evidence/optimized.stderr b/research/h25-passive-guard-primary-preservation/evidence/optimized.stderr new file mode 100644 index 0000000000..e69de29bb2 diff --git a/research/h25-passive-guard-primary-preservation/evidence/optimized.stdout b/research/h25-passive-guard-primary-preservation/evidence/optimized.stdout new file mode 100644 index 0000000000..5496e96f67 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/evidence/optimized.stdout @@ -0,0 +1 @@ +{"actual_operation": false, "cases": [{"details": null, "id": "F01", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F02", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F03", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F04", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F05", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F06", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F07", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F08", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F09", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F10", "status": "PASS_FAKE_ONLY"}, {"details": {"capacity": 4096, "conditional_secondary_site_bound": 674, "no_universal_allocation_claim": true}, "id": "F11", "status": "PASS_FAKE_ONLY"}, {"details": [{"close_attempts": [], "fault": "ledger", "status": "RED_RETAINED_STRONGER_CONTRACT"}, {"close_attempts": [], "fault": "snapshot", "status": "RED_RETAINED_STRONGER_CONTRACT"}, {"close_attempts": [903], "fault": "record", "status": "RED_RETAINED_STRONGER_CONTRACT"}], "id": "F12", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F13", "status": "PASS_FAKE_ONLY"}, {"details": null, "id": "F14", "status": "PASS_FAKE_ONLY"}], "costs": "OPEN_NOT_ZERO", "full_C05": false, "full_V03": false, "helper_sha256": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", "original_credit": 0, "source_sha256": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", "status": "PASS_BOUNDED_FAKE_ONLY"} diff --git a/research/h25-passive-guard-primary-preservation/evidence/optimized.time b/research/h25-passive-guard-primary-preservation/evidence/optimized.time new file mode 100644 index 0000000000..ecf78640e3 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/evidence/optimized.time @@ -0,0 +1,23 @@ + Command being timed: "/usr/bin/python3.12 -I -O -S -B /home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/c05-v03-pro-workitems-20261103T0435Z/publication/stage/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py" + User time (seconds): 0.33 + System time (seconds): 0.01 + Percent of CPU this job got: 100% + Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.34 + 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): 29160 + Average resident set size (kbytes): 0 + Major (requiring I/O) page faults: 0 + Minor (reclaiming a frame) page faults: 9604 + Voluntary context switches: 1 + Involuntary context switches: 26 + Swaps: 0 + File system inputs: 0 + File system outputs: 2 + Socket messages sent: 0 + Socket messages received: 0 + Signals delivered: 0 + Page size (bytes): 4096 + Exit status: 0 diff --git a/research/h25-passive-guard-primary-preservation/integrity.py b/research/h25-passive-guard-primary-preservation/integrity.py new file mode 100644 index 0000000000..2232d82a32 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/integrity.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Check bounded archive inventory/bytes only; never import archived sources.""" + +import hashlib +import json +import os +import re +import stat +import sys + + +MAX_FILES = 128 +MAX_FILE_BYTES = 2 * 1024 * 1024 +MAX_TOTAL_BYTES = 8 * 1024 * 1024 +MAX_MANIFEST_BYTES = 512 * 1024 + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def unique_object(pairs): + result = {} + for key, value in pairs: + require(key not in result, "duplicate JSON key") + result[key] = value + return result + + +def main(): + require(len(sys.argv) == 1, "integrity checker accepts no arguments") + script = os.path.abspath(__file__) + root = os.path.dirname(script) + require(stat.S_ISREG(os.lstat(script).st_mode), "checker is not a regular file") + require(stat.S_ISDIR(os.lstat(root).st_mode), "archive root is not a directory") + manifest_path = os.path.join(root, "MANIFEST.json") + manifest_stat = os.lstat(manifest_path) + require(stat.S_ISREG(manifest_stat.st_mode), "manifest is not a regular file") + require(manifest_stat.st_size <= MAX_MANIFEST_BYTES, "manifest exceeds size bound") + with open(manifest_path, "rb") as handle: + manifest_bytes = handle.read(MAX_MANIFEST_BYTES + 1) + require(len(manifest_bytes) <= MAX_MANIFEST_BYTES, "manifest grew beyond size bound") + manifest = json.loads(manifest_bytes, object_pairs_hook=unique_object) + require(type(manifest) is dict, "manifest is not an object") + require(set(manifest) == {"schema", "scope", "files"}, "unexpected manifest fields") + require(manifest["schema"] == "h25-passive-guard-archive-manifest-v1", "unsupported manifest schema") + require(manifest["scope"] == "ARCHIVE_INTEGRITY_ONLY", "unsupported manifest scope") + rows = manifest["files"] + require(type(rows) is list and 1 <= len(rows) <= MAX_FILES, "invalid file count") + expected = {} + total_bytes = 0 + for row in rows: + require(type(row) is dict and set(row) == {"path", "bytes", "sha256", "mode"}, "invalid file row") + path = row["path"] + require(type(path) is str and len(path) <= 300, "invalid path") + require(re.fullmatch(r"[A-Za-z0-9._/-]+", path) is not None, "unsupported path spelling") + parts = path.split("/") + require(1 <= len(parts) <= 8 and all(part not in ("", ".", "..") for part in parts), "noncanonical path") + require(path != "MANIFEST.json" and path not in expected, "duplicate or self-referential path") + require(type(row["bytes"]) is int and 0 <= row["bytes"] <= MAX_FILE_BYTES, "invalid size") + require(type(row["sha256"]) is str and re.fullmatch(r"[0-9a-f]{64}", row["sha256"]) is not None, "invalid SHA256") + require(row["mode"] in ("100644", "100755"), "unsupported mode") + expected[path] = row + total_bytes += row["bytes"] + require(total_bytes <= MAX_TOTAL_BYTES, "archive exceeds total size bound") + expected_directories = set() + for path in expected: + parts = path.split("/") + for index in range(1, len(parts)): + expected_directories.add("/".join(parts[:index])) + actual = set() + for current, directories, files in os.walk(root, followlinks=False): + require(len(actual) + len(files) <= MAX_FILES + 1, "actual file count exceeds bound") + require(len(directories) <= len(expected_directories), "directory count exceeds bound") + for name in directories: + absolute = os.path.join(current, name) + relative = os.path.relpath(absolute, root).replace(os.sep, "/") + require(relative in expected_directories, "undeclared directory: " + relative) + require(stat.S_ISDIR(os.lstat(absolute).st_mode), "directory alias or special entry") + for name in files: + absolute = os.path.join(current, name) + info = os.lstat(absolute) + require(stat.S_ISREG(info.st_mode), "nonregular file in archive") + relative = os.path.relpath(absolute, root).replace(os.sep, "/") + require(relative not in actual, "duplicate inventory path") + actual.add(relative) + if relative == "MANIFEST.json": + continue + require(relative in expected, "undeclared file: " + relative) + row = expected[relative] + require(info.st_size == row["bytes"], "size mismatch: " + relative) + executable = bool(info.st_mode & 0o111) + require(executable == (row["mode"] == "100755"), "mode mismatch: " + relative) + digest = hashlib.sha256() + read_bytes = 0 + with open(absolute, "rb") as handle: + for chunk in iter(lambda: handle.read(65536), b""): + read_bytes += len(chunk) + require(read_bytes <= row["bytes"], "file grew: " + relative) + digest.update(chunk) + require(read_bytes == row["bytes"], "file shrank: " + relative) + require(digest.hexdigest() == row["sha256"], "SHA256 mismatch: " + relative) + require(actual == set(expected) | {"MANIFEST.json"}, "missing declared archive files") + print(json.dumps({ + "status": "PASS_ARCHIVE_INTEGRITY_ONLY", + "files": len(expected), + "payload_bytes": total_bytes, + "manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), + "candidate_import_or_execution": False, + "semantic_acceptance": False, + }, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + try: + result = main() + except Exception as error: + print(json.dumps({"status": "FAIL_ARCHIVE_INTEGRITY", "reason": str(error)}, sort_keys=True), file=sys.stderr) + result = 1 + raise SystemExit(result) diff --git a/research/h25-passive-guard-primary-preservation/reviews/CURRENT-PRS.json b/research/h25-passive-guard-primary-preservation/reviews/CURRENT-PRS.json new file mode 100644 index 0000000000..1540cb3551 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/reviews/CURRENT-PRS.json @@ -0,0 +1,90 @@ +[ + { + "number": 6339, + "head": "608ad23adc6c01264c8195daf7f18e29c17464a7", + "source_repo": "unpaidmoon/integer-mult-bounds", + "state": "closed", + "merged": true, + "observed_utc": "2026-11-03T04:38:46.888Z" + }, + { + "number": 6346, + "head": "abff67b31fa781e950c82d95eccb6f168950943c", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:46.988Z" + }, + { + "number": 6347, + "head": "59140439e7f791876159e2f3838f1dead2e54953", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:47.424Z" + }, + { + "number": 6351, + "head": "1e9db2d08be4551ffe0bcfc573574851530eb4ca", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:46.957Z" + }, + { + "number": 6358, + "head": "84b0e70ba4da44b7904fe8d13903c26a3a8239e1", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:48.581Z" + }, + { + "number": 6363, + "head": "a8cf650b7435ccea237084e491e339f725c0a35b", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:46.994Z" + }, + { + "number": 6374, + "head": "b02bfe3338f7fe57818262b33f8e5c77ac0f1c93", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:46.936Z" + }, + { + "number": 6377, + "head": "2a26450dea25d7648b585befce5ed375857a8f90", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:46.960Z" + }, + { + "number": 6397, + "head": "0b3b5d923a54808a13c3102657fc51ef2ec5ba3e", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:46.937Z" + }, + { + "number": 6434, + "head": "edc2820ba023b804ef1351a88e2fe31bf8d489dd", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:46.989Z" + }, + { + "number": 6476, + "head": "44749c3a6ddc8cde48c5aa83073f6794e3546b00", + "source_repo": "Clear1nsight/integer-mult-bounds", + "state": "open", + "merged": false, + "observed_utc": "2026-11-03T04:38:46.991Z" + } +] diff --git a/research/h25-passive-guard-primary-preservation/reviews/PREDECESSOR-CONTROL-REVIEW.json b/research/h25-passive-guard-primary-preservation/reviews/PREDECESSOR-CONTROL-REVIEW.json new file mode 100644 index 0000000000..73a55f1d67 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/reviews/PREDECESSOR-CONTROL-REVIEW.json @@ -0,0 +1,66 @@ +{ + "schema": "c05-v03-independent-predecessor-control-review-v1", + "observed_utc": "2026-11-03T04:48:07.028151+00:00", + "method": "Read exact primary-source GitHub file slices/full verifier via connector; no import, compile or execution.", + "sources": [ + { + "repository": "unpaidmoon/integer-mult-bounds", + "commit": "608ad23adc6c01264c8195daf7f18e29c17464a7", + "path": "research/h25-g12-identity-cleanup/corrected/g12_reference_parent_v2.py", + "returned_blob": "42795e5d3a224a35959df361493211ff0fbea9b1", + "lines_read": [ + [ + 65, + 100 + ], + [ + 205, + 240 + ] + ], + "decision": "ADAPT: raw-slot-before-format and all-close/successful-body promotion semantics; late helper-ledger/snapshot allocation does not meet a stronger universal promise." + }, + { + "repository": "Clear1nsight/integer-mult-bounds", + "commit": "abff67b31fa781e950c82d95eccb6f168950943c", + "path": "research/h25-g12-custody-repairs/verify.py", + "returned_blob": "564c7b35e421b5df4ded3ed4ea189170792498f5", + "full_source_read": true, + "relevant_line_ranges": [ + [ + 192, + 258 + ], + [ + 261, + 315 + ] + ], + "decision": "ADAPT finite fake same-object/ordered-error/no-retry/all-known-release oracles; do not copy source-window construction or execute prior harness." + } + ], + "independently_confirmed_controls": [ + { + "lines": "6346 verify192-225", + "requirement": "A is outward primary; close order903,902,901; first_close then late_close raw secondary order; successful body promotes first_close exactly once and retains only late_close as secondary." + }, + { + "lines": "6346 verify229-258", + "requirement": "Ledger/snapshot recording allocation faults remain three distinct retained RED witnesses: no closes/no closes/only first close, with MemoryError replacing pending A in the stronger old helper." + }, + { + "lines": "6346 verify261-284", + "requirement": "Known numeric owner removed before close, every known pidfd attempted once, ordered raw failures, repeated release has no retry." + }, + { + "lines": "6346 verify286-315", + "requirement": "Persistent observation denial cannot bypass independent recorded-owner release; unknown stays unknown." + } + ], + "fake_only_successor_interpretation": "Use complete actual source definitions in an approved AST extraction with inert external operations. No real descriptors, processes, proc, signals, target files or namespace operations; no copied-model equivalence claim.", + "candidate_or_control_execution": false, + "source_oracle_claim": "Applicable finite predecessor controls must remain meaningful in the adapted caller, while stronger original RED limits remain explicit.", + "original_credit": 0, + "original_score": 43.5, + "costs": "OPEN_NOT_ZERO" +} diff --git a/research/h25-passive-guard-primary-preservation/reviews/PUBLICATION-ADAPTER-REVIEW-v1.json b/research/h25-passive-guard-primary-preservation/reviews/PUBLICATION-ADAPTER-REVIEW-v1.json new file mode 100644 index 0000000000..49d04632a0 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/reviews/PUBLICATION-ADAPTER-REVIEW-v1.json @@ -0,0 +1,65 @@ +{ + "schema": "c05-v03-independent-publication-adapter-review-v1", + "review_utc": "2026-11-03T05:11:01.098460+00:00", + "disposition": "EXACT_FINAL_EXPORT_INERT_FAKE_PLAN_PASS; PUBLICATION_METADATA_PREFIX_PAIR_CORRECTION_REQUIRED", + "adapter_freeze": { + "path": "outputs/c05-v03-pro-workitems-20261103T0435Z/publication/ADAPTER-FREEZE-v1.json", + "sha256": "a61d77091519c75fdea0a5554cd2a9fc8fd4316a025d69b9520ba5d0efc0653d" + }, + "exact_exports": [ + { + "name": "parent_passive_supervisor_v4.py", + "original_sha256": "83e31e2705b949750f5ea6bd07ebafff4c2b5dbdbe578a87058eda7ca0e600f5", + "export_sha256": "355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd", + "export_bytes": 29904, + "exact_AST_equal_after_only_reviewed_metadata_normalization": true + }, + { + "name": "passive_image_candidates_v3.py", + "original_sha256": "166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41", + "export_sha256": "8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d", + "export_bytes": 12983, + "exact_AST_equal_after_only_reviewed_metadata_normalization": true + }, + { + "name": "verify_guard_fake_v1.py", + "original_sha256": "357ca2b8788438fe32e32f9c7bfa171e74eca12d3183ee7aebbd540bbe7e72f1", + "export_sha256": "c71dcf2dfd944282210f105ef54d23a4deb6e1eaaa0a9068a2ea584292ea365e", + "export_bytes": 20897, + "exact_AST_equal_after_only_reviewed_metadata_normalization": true + } + ], + "helper_pin_and_size_derived_correctly": true, + "harness_source_helper_pins_derived_correctly": true, + "source_AST_and_oracles_unchanged": true, + "withheld_gate_unchanged": true, + "expired_epoch_unchanged": true, + "path_adapter": "None; original relative snapshot inputs retained.", + "unchanged_pure_prefix": { + "bytes": 10370, + "sha256": "d5161cc51d5818dd70938214b4067ddc4af2e0fec513b8a255b50615a3da7b50", + "byte_equal": true + }, + "metadata_finding": { + "id": "ADAPTER-PREFIX-OFF-BY-ONE", + "status": "REQUIRES_METADATA_CORRECTION_BEFORE_FINAL_PUBLICATION", + "finding": "ADAPTER reports10370bytes with3aca049... SHA; that hash covers10371bytes (split before def main including extra newline). Correct10370-byte prefix SHAd5161cc51d5818dd70938214b4067ddc4af2e0fec513b8a255b50615a3da7b50. Both prefix variants are unchanged; source/harness safety unaffected.", + "allowed_resolution": "Correct only metadata length/hash pair; leave accepted3export source hashes unchanged." + }, + "README_scope": "Publication README explicitly preserves capture-call/recording availability as additional sufficiency, original inline C10 unqualified, unadmitted timer-disarm and CLI/signal/runtime/teardown/C07 HOLD. No broader accepted claim observed.", + "execution_recommendation": "Parent may execute exact finalexport harness once normal and once optimized in the already authorized bounded inert plan. No candidate module/CLI/native/proc/process/namespace operation is authorized.", + "reviewer_activity": { + "source_static_AST_parse_only": true, + "candidate_or_control_import_compile_execute": false, + "tests": false + }, + "boundaries": { + "original_score": 43.5, + "original_credit": 0, + "full_C05": false, + "full_V03": false, + "C10_discharged": false, + "C07_accepted": false, + "costs": "OPEN_NOT_ZERO" + } +} diff --git a/research/h25-passive-guard-primary-preservation/reviews/SOURCE-CONTROL-REVIEW-v1.json b/research/h25-passive-guard-primary-preservation/reviews/SOURCE-CONTROL-REVIEW-v1.json new file mode 100644 index 0000000000..cd9a39b446 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/reviews/SOURCE-CONTROL-REVIEW-v1.json @@ -0,0 +1,125 @@ +{ + "schema": "c05-v03-independent-source-and-fake-plan-review-v1", + "review_utc": "2026-11-03T05:04:44.011280+00:00", + "disposition": "CONDITIONAL_LOCAL_CALLABLE_SOURCE_PASS; EXACT_INERT_FAKE_PLAN_PASS; ACTUAL_C10_AND_COMPLETE_LEAF_EXITS_HOLD", + "subjects": [ + { + "path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/SOURCE-FREEZE-v1.json", + "bytes": 9782, + "sha256": "e1a6251d5a73362e1608cfb952d72ac3b382dd2f1e811823c8d74596b3febe3f" + }, + { + "path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py", + "bytes": 29659, + "sha256": "83e31e2705b949750f5ea6bd07ebafff4c2b5dbdbe578a87058eda7ca0e600f5" + }, + { + "path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/passive_image_candidates_v3.py", + "bytes": 12726, + "sha256": "166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41" + }, + { + "path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "bytes": 20897, + "sha256": "357ca2b8788438fe32e32f9c7bfa171e74eca12d3183ee7aebbd540bbe7e72f1" + }, + { + "path": "outputs/c05-v03-pro-workitems-20261103T0435Z/guard/reference-g12-parent-v3.py.txt", + "bytes": 96341, + "sha256": "8b6b196c50d616e12d7966ea35bf6d65fd799a18556f362a7e17d2b1273a8bb8" + } + ], + "method": "Read complete successor guard, selected locator entry and complete382-line harness; match exact file hashes to freeze. Independently compared the unchanged locator prefix and read original conditions and exact predecessor controls. No candidate/control import, compile, execution or target/system/process/namespace operation by reviewer.", + "accepted_source_scope": [ + "Actual local read_pin/Guard.write/register/cleanup/run/main and locator-main definitions preserve the first raw object and first traceback root under explicit C10 private-state/no-interference/adequate capture-call and recording/unwind premises.", + "Preallocated raw/returned-owner state, ordered B/C retention, independent known-close attempts, retire-before-close and no blind retry are present at selected sites.", + "Popen PENDING state is preserved after the one provisional finding; uncertain acquisition blocks later normal I/O, failed-capture acquisition and launches. Known-owner teardown attempts remain independent.", + "Main no longer formats primary into a string/Stop/SystemExit record before outward raw delivery. Final receipt is omitted after first error/uncertainty; local exception delivery and external interpreter rendering are distinguished.", + "Locator pure prefix before main is exactly10370bytes, SHAd5161cc51d5818dd70938214b4067ddc4af2e0fec513b8a255b50615a3da7b50, byte-identical to predecessor. No discovery/parser/decoder semantics are newly qualified." + ], + "provisional_finding": { + "id": "PENDING-POPEN-ERASURE", + "status": "RESOLVED_WITHIN_SINGLE_UNFROZEN_AUTHORING_WINDOW", + "original": "cleanup unconditionally rewrote pending process_owner to RETIRED/None", + "frozen_resolution": "cleanup now retires only KNOWN process_owner; F07 tests complete actual run with pre-return Popen failure and preserves PENDING" + }, + "fake_plan_safety": { + "status": "PASS_EXACT_HASHES_ONLY", + "candidate_loading": "Hash-pinned texts parsed; only complete named definitions compiled/executed by separately authorized parent harness. Candidate module imports, global assignments, __main__, CLI and alarm invocation omitted.", + "dependency_closure": "Candidate os/Path/process/proc/selector/stream/time/signal/argparse/fcntl/JSON interfaces are explicit inert tokens or fail-closed fakes. Actual proc_identity is replaced, so no proc reading is tested. Real imports are harness standard-library source-reading support and pure builtins/hash/re; retained6346 helper uses real sys.exc_info only.", + "full_builtins_caveat": "Namespace includes full builtins; safety depends on the exact inspected hashes containing no callable escape/import/open/eval/exec path. Drift is rejected before extraction. This is an exact plan acceptance, not a general safe AST executor.", + "assertion_oracle": "All checks use require and survive -O. Cases use is-object expectations, raw-root snapshots, explicit token close sequences/counters, no-next-launch/publication checks and distinct RED classifications.", + "cases": 14, + "F01_F02": "Same primary and raw close secondary at actual read_pin/write; retained exact old functions still demonstrate original replacement negatives.", + "F03_F04_F05": "Complete actual cleanup/run preserve A or promote first B once, keep raw B/C order, attempt independent closes and prevent next launch.", + "F06_F07_F08": "Post-return pidfd bookkeeping failure, full-run uncertain Popen PENDING, owner retired before ambiguous close/no retry.", + "F09_F14": "Actual main plus exact nested read_pin preserves poison A across close and outer timer failure, with no formatter/JSON continuation.", + "F10_F11_F13": "Cleanup-only failure, source-fixed finite capacity/source-method condition and unfaulted read/write/run baseline.", + "F12": "All3 exact6346 stronger ledger/snapshot/record RED witnesses retained, not credited as new C10 success.", + "allowed_parent_commands": [ + "/usr/bin/python3.12 -I -B outputs/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "/usr/bin/python3.12 -I -O -B outputs/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py" + ], + "parent_only": true, + "reviewer_execution": false + }, + "mandatory_scope_limits": [ + { + "id": "L01", + "limit": "Capture uses errors.capture(error), a Python helper call, rather than original adapter inline first-slot stores. The accepted local source method assumes adequate capture-call and recording/unwind availability after handler delivery. It is not a universal post-delivery frame-allocation guarantee, and it does not discharge original C10. This added sufficiency assumption must remain distinct from original requirements and inherited C11 gaps." + }, + { + "id": "L02", + "limit": "Actual original-native/currentness/private-state premises, configured stage/caller/Gamma, actual enclosing parent teardown and C07/file/namespace lifetime remain unadmitted. Source and fake controls cannot qualify those authorities." + }, + { + "id": "L03", + "limit": "Actual proc/path parsing, real Popen/native return, child disposal/unknown survivors, async signal/os._exit/default interpreter transport and inherited helper/TCB/cold-authority failures remain outside this pass." + }, + { + "id": "L04", + "limit": "Default OPERATION_ADMITTED=False and expired epoch remain. main finally still disarms timer even when the initial admission gate fails. The unadmitted entry is not certified side-effect-free or launchable; real invocation is withheld. Inert fake main controls do not qualify that boundary." + }, + { + "id": "L05", + "limit": "Raw error objects are in-process evidence, not a durable journal; full physical retention/costs remain OPEN_NOT_ZERO. Failed/uncertain capture never supplies success." + }, + { + "id": "L06", + "limit": "Fourteen finite fake cases do not execute original recipe cases, actual Python runtime profiles of the original target, decoder/compiler/native tools or C05/V03. Prior23 pure-inspect controls are only historical boundary-mapped evidence, not new runs." + } + ], + "source_check_mapping_pending_fake_results": { + "RUN-01-C01": "PARTIAL: exact new local source/caller identities bound; original actual selected caller/Gamma unbound", + "RUN-01-C02": "PARTIAL: local conditional source accepted; exact fake results pending and original actual premises unadmitted", + "RUN-01-C03": "PARTIAL: local conditional run/cleanup source accepted; method-added availability remains explicit", + "RUN-01-C04": "PARTIAL: selected local callable raw main/terminal source accepted; signal/admission/actual original boundary HOLD", + "RUN-01-C05": "PARTIAL: source retirement/no-retry accepted; fake results pending", + "RUN-01-C06": "PARTIAL: source stop/no-success-publication behavior accepted; fake results pending; no actual original grant", + "RUN-01-C07": "HOLD_PENDING_FAKE_RESULTS_AND_LIMITS", + "RUN-01-C08": "HOLD_COMPLETE_ORIGINAL_EXIT_NOT_ACCEPTED", + "RUN-02-C01": "PARTIAL: selected explicit owner acquisitions enumerated; inherited/pre-return/actual external scope unqualified", + "RUN-02-C02": "PARTIAL: protected source slots/pending quarantine accepted under added method premises; fake results pending", + "RUN-02-C03": "PARTIAL: source PENDING preserved/no reuse; fake results pending", + "RUN-02-C04": "HOLD_ACTUAL_ENCLOSING_TEARDOWN_UNBOUND", + "RUN-02-C05": "HOLD_COMPLETE_ORIGINAL_EXIT_NOT_ACCEPTED", + "RUN-03-C01": "PARTIAL: raw capture precedes formatting/cleanup under successful capture-call assumption; not original inline-first-store proof", + "RUN-03-C02": "PARTIAL: source same-object/first-tb local path accepted under premises; actual original path unbound", + "RUN-03-C03": "PARTIAL: bounded raw recording/no error formatting accepted under successful capture-call/unwind; universal recording faults excluded", + "RUN-03-C04": "PARTIAL: premises/exclusions explicit; actual native/currentness/private-state context remains unadmitted", + "RUN-03-C05": "HOLD_PENDING_EXACT_FAKE_RESULTS", + "RUN-03-C06": "HOLD_COMPLETE_ORIGINAL_EXIT_NOT_ACCEPTED" + }, + "boundaries": { + "actual_runtime_grant": false, + "full_RUN01_02_03": false, + "C10_discharged": false, + "C11_discharged": false, + "full_C05": false, + "full_V03": false, + "original_score": 43.5, + "original_credit": 0, + "costs": "OPEN_NOT_ZERO", + "hard_stop_utc": "2026-11-03T05:20:29Z" + } +} diff --git a/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/parent_passive_supervisor_v3.py b/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/parent_passive_supervisor_v3.py new file mode 100644 index 0000000000..2466526453 --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/parent_passive_supervisor_v3.py @@ -0,0 +1,391 @@ +"""SOURCE ONLY until separately admitted by parent. One offline discovery pass. +Linux 7.0.0-42-generic / Python3.12 POSIX subprocess/process-group semantics. +This is sampled accounting and bounded capture, not a universal OS proof. +Never executes GCC. No imports of prior controllers or the helper in-process. +""" +import argparse +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import selectors +import signal +import stat +import subprocess +import sys +import time + +HERE = Path(__file__).resolve().parent +HELPER = HERE / 'passive_image_candidates_v2.py' +HELPER_SHA = '56b44235f55685d61e5c8b8099d825b4ec5a53987910f506dffad309c12ffb53' +TARGET = '/usr/bin/x86_64-linux-gnu-gcc-13' +TARGET_SHA = '1b99826121ae6682a634e5efe09bd3e3df58ce58e0b28f849114ab5b89139c26' +TOOLS = { + '/usr/bin/python3.12': (8020928, 'e50d468e8b0adfb05733f5b87b3cff34829c4a8c1aea50c865aa8bdfe4bb150f'), + '/usr/bin/x86_64-linux-gnu-readelf': (789280, '64c58e15274bbbb5153f31078e455e9e77ee5f51489e709bba5bb788ce9df2b0'), + '/usr/bin/x86_64-linux-gnu-objdump': (390848, '325c4205a4c658a9d1e1ebc469ae55975a2b897a3d3c1e79d9b158612d37f745')} +RAW_CAP, TOTAL_CAP, RESERVE = 786432, 1048576, 262144 +MEM_CAP = 1073741824 + +class Stop(RuntimeError): + pass + +def need(ok, reason): + if not ok: + raise Stop(reason) + +def digest(b): + return hashlib.sha256(b).hexdigest() + +def read_pin(path, count, expected): + fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW) + try: + before = os.fstat(fd) + need(stat.S_ISREG(before.st_mode) and before.st_size == count, 'pin size/type: '+str(path)) + data = bytearray() + while len(data) <= count: + chunk = os.read(fd, min(65536, count+1-len(data))) + if not chunk: + break + data.extend(chunk) + after = os.fstat(fd) + fields = ('st_dev','st_ino','st_mode','st_size','st_mtime_ns','st_ctime_ns') + need(all(getattr(before,k)==getattr(after,k) for k in fields), 'pin changed: '+str(path)) + need(len(data)==count and digest(data)==expected, 'pin mismatch: '+str(path)) + os.lseek(fd,0,0) + return fd, bytes(data), {k:getattr(after,k) for k in fields} + except BaseException: + os.close(fd) + raise + +def proc_identity(pid): + try: + text=Path('/proc/'+str(pid)+'/stat').read_text() + except FileNotFoundError: + return None + need(len(text)<=4096,'proc stat bound') + parts=text.rsplit(')',1)[1].split() + return (int(parts[19]),int(parts[1]),int(parts[2]),int(parts[3])) + +class Guard: + def __init__(self, out, started, already_retained): + self.out, self.raw, self.total = out, 0, already_retained + self.started = started + self.deadline = self.started + 55 # final five seconds reserved for cleanup/receipt + self.child = None + self.known = {} + self.pidfds = {} + self.steps, self.secondary = [], [] + self.peak_sampled_rss = 0 + self.launches = 0 + def write(self, name, data, raw=False): + need('/' not in name and len(name)<100, 'output name') + if raw: + need(self.raw+len(data)<=RAW_CAP and self.total+len(data)<=TOTAL_CAP-RESERVE, + 'shared raw/retention cap') + need(self.total+len(data)<=TOTAL_CAP, 'all new output cap') + fd = os.open(self.out/name, os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_CLOEXEC,0o600) + try: + view=memoryview(data) + while view: + n=os.write(fd,view) + need(n>0,'short output write') + self.total += n + if raw: self.raw += n + view=view[n:] + finally: os.close(fd) + def register(self,pid,identity): + fd=os.pidfd_open(pid,0) + again=proc_identity(pid) + if again is None or again[0]!=identity: + os.close(fd); return + self.known[pid]=identity; self.pidfds[pid]=fd + def sample(self): + need(time.monotonic()0,'stream cap+1: '+name) + block=os.read(key.fileobj.fileno(),min(8192,remaining)) + if not block: + sel.unregister(key.fileobj); continue + buffers[index].extend(block) + need(len(buffers[index])<=caps[index],'stream cap+1: '+name) + need(self.raw+sum(map(len,buffers))<=RAW_CAP,'combined raw cap') + rec['returncode']=self.child.wait(timeout=.1) + rec['status']='EXITED' + need(rec['returncode']==0,'nonzero exit: '+name) + except BaseException as exc: + rec['status']='STOP'; rec['error']=type(exc).__name__+': '+str(exc)[:400] + failure=exc + finally: + active=self.child + try: + self.cleanup() + if self.secondary: + raise Stop("cleanup side failures; no subsequent step permitted") + except BaseException as exc: + self.secondary.append('step cleanup: '+type(exc).__name__+': '+str(exc)[:300]) + if failure is None: failure=exc + try: sel.close(); os.close(toolfd) + except BaseException as exc: + self.secondary.append('step fd close: '+type(exc).__name__+': '+str(exc)[:300]) + if failure is None: failure=exc + if active is not None: rec['returncode']=active.returncode + rec['wall_seconds']=time.monotonic()-began + for index,buf in enumerate(buffers): + # Bytes beyond an individual cap are counted against terminal reserve. + over=len(buf)>caps[index] + try: + self.write(name+('.stdout' if index==0 else '.stderr'),bytes(buf),raw=not over) + rec['raw_retained_bytes'][index]=len(buf) + except BaseException as exc: + self.secondary.append('raw retention: '+type(exc).__name__+': '+str(exc)[:300]) + if failure is None: failure=exc + rec.setdefault('sha256',[]).append(digest(buf)) + rec['capture_complete']=failure is None + if failure is not None: + rec['status']='STOP' + rec.setdefault('error',type(failure).__name__+': '+str(failure)[:400]) + raise failure + return bytes(buffers[0]) + +def bind_window(text, B, load, start, stop, candidate): + covered=set() + for line in text.decode('ascii','strict').splitlines(): + m=re.match(r'^\s*([0-9a-fA-F]+):\s+(.*)$',line) + if not m: continue + addr=int(m.group(1),16) + raw=re.match(r'^((?:[0-9a-fA-F]{2}(?:\s+|$))+)',m.group(2)) + need(raw is not None,'decoder address row without raw bytes') + b=bytes.fromhex(raw.group(1)) + need(start<=addr and addr+len(b)<=stop,'decoder raw outside nominated window') + off=load['offset']+addr-load['vaddr'] + need(B[off:off+len(b)]==b,'decoder raw differs from authoritative B') + covered.update(range(off,off+len(b))) + off=candidate['file_offset'] + need(set(range(off,off+candidate['span_bytes']))<=covered,'candidate raw not present in decoder rows') + +def main(): + started=time.monotonic() + active_guard=[None] + def alarm(signum,frame): + # Linux ITIMER_REAL deadline; no claim about an unavailable kernel/CPU. + if time.monotonic()-started>=59.9: + g=active_guard[0] + if g is not None and g.child is not None: + for fd in g.pidfds.values(): + try: signal.pidfd_send_signal(fd,signal.SIGKILL) + except ProcessLookupError: pass + for pid,born in g.known.items(): + info=proc_identity(pid) + if info is not None and info[0]==born and info[2:]==(g.child.pid,g.child.pid): + try: os.killpg(g.child.pid,signal.SIGKILL) + except ProcessLookupError: pass + break + try: os.write(2,b'STOP: hard60s deadline; terminal may be incomplete\n') + finally: os._exit(124) + signal.setitimer(signal.ITIMER_REAL,max(.001,60-(time.monotonic()-started))) + raise Stop('wall/signal stop '+str(signum)) + signal.signal(signal.SIGALRM,alarm) + signal.signal(signal.SIGTERM,alarm); signal.signal(signal.SIGINT,alarm) + signal.setitimer(signal.ITIMER_REAL,55) + ap=argparse.ArgumentParser() + ap.add_argument('--admission',required=True) + ap.add_argument('--admission-sha256',required=True) + ap.add_argument('--token',required=True) + args=ap.parse_args() + need(re.fullmatch(r'[A-Za-z0-9_-]{8,64}',args.token),'fresh token format') + admission_path=Path(args.admission) + need(admission_path.is_absolute(),'absolute admission path') + admission_size=admission_path.stat().st_size + need(0=60 and a.get('remaining_total_seconds',0)>=60,'remaining budgets') + need(a.get('supervisor_sha256')==digest(Path(__file__).read_bytes()),'supervisor source pin') + need(a.get('helper_sha256')==HELPER_SHA,'helper source pin') + baseline=a.get('already_retained_new_bytes') + need(type(baseline) is int and 0<=baseline<=262144,'existing new output reservation') + # Parent must supply the fixed round deadline; deadline cannot be reset by invocation. + need(a.get('round_hard_stop_epoch')==1793664771.401519,'fixed round hardstop') + need(time.time()+60<=a['round_hard_stop_epoch'],'insufficient fixed round time') + lockfd=os.open(HERE/'private-one-pass.lock',os.O_CREAT|os.O_RDWR|os.O_CLOEXEC|os.O_NOFOLLOW,0o600) + ls=os.fstat(lockfd) + need(stat.S_ISREG(ls.st_mode) and ls.st_uid==os.getuid() and ls.st_mode&0o077==0,'private lock ownership/mode') + fcntl.flock(lockfd,fcntl.LOCK_EX|fcntl.LOCK_NB) + # Exclusive permanent marker prevents retries even after a failed pass. + marker=os.open(HERE/'ONE-PASS-STARTED',os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_CLOEXEC,0o600) + os.write(marker,args.token.encode()); os.close(marker) + out=HERE/('run-'+args.token); out.mkdir(mode=0o700) + g=Guard(out,started,baseline+len(args.token)); active_guard[0]=g + fds=[]; status='STOP'; first=None; metadata=None; hs=None + try: + fd,B,metadata=read_pin(TARGET,1023032,TARGET_SHA); fds.append(fd) + hf,hb,hs=read_pin(HELPER,11809,HELPER_SHA); fds.append(hf); del hb + need(time.monotonic()-started<=10,'setup identity capture allocation') + helper=g.run('helper',['/usr/bin/python3.12','-B','-S','/proc/self/fd/'+str(hf)],5,(65536,16384),(hf,)) + r=json.loads(helper) + need(r.get('status')=='PARTIAL_LOCALISATION_DATA_ONLY' and r.get('candidate_overflow') is False, + 'structured helper STOP/overflow') + need(r.get('image_sha256')==TARGET_SHA and r.get('image_bytes')==len(B),'helper B binding') + need(r.get('certificate_feasible') is False and r.get('full_C05') is False and r.get('full_V03') is False,'helper scope') + refs=r['references']; need(len(refs)<=8,'candidate count') + for c in refs: + off=c['file_offset']; n=c['span_bytes'] + need(0<=off<=len(B) and 0=n,'window VA binding') + need(not any(x is not load and max(start,x['vaddr']) no closes; snapshot allocation -> no closes; recorder allocation -> first close only. These do not prove generic Python impossibility or create a stronger mandatory original C10 contract.", + "control_harness_decision": "REVIEW_ONLY_AS_WRITTEN: old verifier AST-extracts windows. New controls must exercise whole actual successor module functions/methods under approved fake boundaries; no AST-extracted execution." + }, + { + "pr": 6434, + "commit": "edc2820ba023b804ef1351a88e2fe31bf8d489dd", + "decision": "INCOMPATIBLE_FOR_C10_ERROR_ORACLE", + "reason": "Formatted records and OperationStop may be auxiliary capture evidence but cannot replace original same-object outward delivery. Parent owns any further6434 source audit; no adoption proposed here." + }, + { + "pr": 6476, + "commit": "44749c3a6ddc8cde48c5aa83073f6794e3546b00", + "decision": "REUSE_ACCEPTED_NARROW_HELPER_BODY_ADAPT_ITS_ENTRY_IF_SELECTED", + "reason": "Pure candidate locator semantics retain their prior narrow source acceptance. Actual selected locator main has finally-close replacement at234 and formatted CLI catch240-242, and so its entry cannot be adopted unchanged as a C10 same-object route. No new locator/decoder implementation is justified." + } + ], + "actual_source_failures_and_ownership": [ + {"site": "guard42-61 read_pin", "finding": "Returned fd owned locally until successful transfer; except os.close replaces read/pin/body A with close B. Raw A/TB must be saved before independent close; successful return must transfer without closing."}, + {"site": "guard83-98 write", "finding": "finally-close replaces ENOSPC/write A with EIO B. Count each positive write and preserve first A/raw TB; close failure after successful body is failure."}, + {"site": "guard99-104 register", "finding": "pidfd acquisition is not in enclosing owner before proc_identity or dictionary writes; exceptions can strand returned fd. Need preallocated returned-owner/pending slot and local finally transfer/close; ambiguous acquisition stays UNKNOWN and blocks next I/O."}, + {"site": "guard136-170 cleanup", "finding": "proc/signal/wait/poll/selector failures can bypass pipe/pidfd releases; pipe handlers format str and catch only Exception; numeric pidfd map is cleared only after whole close loop, permitting later blind retry if earlier close failed. Process disposal and known release phases must be independent; unknown exit stays unknown."}, + {"site": "guard171-247 run", "finding": "Tool pin before protected try, selector creation and bookkeeping can strand toolfd; primary formatting215 happens before failure assignment216; cleanup/selector/toolfd/retention/hash/rec writes can replace A; grouped226 skips toolfd after selector-close failure. Carry one raw primary/traceback through independent final phases; forbid next launch immediately on uncertainty."}, + {"site": "guard268-289 alarm", "finding": "Actual signal handler raises Stop and may os._exit124. Original C10 no-async premise does not justify this interval. Deadline/hard-exit paths must stay STOP/incomplete with explicit unqualified delivery; no universal async or hard-exit preservation claim."}, + {"site": "guard291-325 setup", "finding": "Admission close, lock/marker acquisition, marker write/close, mkdir and Guard allocation precede the main body try. Caller must register every Python-returned owner before fallible bookkeeping, independent release on setup failure, and quarantine ambiguous returns. Inherited argparse/json/Path formatting/allocation remains C11."}, + {"site": "guard352-385 main finally", "finding": "First error becomes string; catches format raw secondaries and only OSError for some closes; receipt construction/serialization/write/postwrite bound/timer cancellation can replace earlier A. Preserve raw outward A, keep formatted receipt supplementary, and independently attempt every known final owner once."}, + {"site": "guard387-391 CLI boundary", "finding": "catch writes formatted STOP then SystemExit2, replacing actual exception object. Required exact local caller successor must rethrow same object/raw TB after best-effort diagnostic. A subprocess parent cannot receive a Python object through JSON/stderr; no claim crosses that transport."}, + {"site": "locator211-242 main/CLI", "finding": "Unconditional close at234 and formatted exit at240-242 are reachable selected helper paths. If main is selected, adapt them as well; pure inspect-only fake tests cannot establish entry acceptance."} + ], + "proposed_exact_source_adaptation": [ + "Create one new successor of actual complete20881-byte guard in this owned guard directory; preserve predecessor bytes, tool/target semantics, caps, names, marker/no-retry policy and closed historical epoch. No wrapper-shaped alternative.", + "Use private preallocated raw primary-error/traceback and ordered secondary-error/traceback cells before owned acquisitions; save raw A before any str/repr/JSON/notes. Preserve the exact original error object and traceback tail; diagnostics are best effort after raw retention.", + "Adapt actual read_pin/write/register acquisition, transfer and close sites. A known owner is retired before its single close attempt; failed close is uncertain and never blindly retried. Unknown returned/pending acquisition blocks new I/O and remains for genuine enclosing teardown.", + "Adapt actual Guard.cleanup so process observation/disposal failure cannot bypass known-stream/selector/pidfd release attempts. Keep process exit qualification distinct from descriptor-release attempts and never label unknown cleanup successful.", + "Adapt actual Guard.run and main setup/body/finally so every close, failed retention, metadata/receipt/formatting failure is raw secondary after A, or first primary when no A exists. Protect each known close separately and immediately block later launch after uncertainty. Preserve failed raw partials and no overwrite/rebuild.", + "Replace local CLI formatted-primary/SystemExit conversion with same-object rethrow after supplementary diagnostic; keep normal successful exit status and scientific flags unchanged. This changes local error delivery intentionally and requires explicit parent source acceptance; it does not certify external transport.", + "If selected helper entry is retained, create one new exact locator successor changing only its error/close/entry handling; pure inspect body remains byte-equivalent. Pin its successor bytes only in unexecuted new guard source. No actual tool/helper launch or admission record is created.", + "Do not claim ledger/snapshot/record-allocation safety, async safety, pre-delivery recovery, inherited helper/native/TCB safety or actual external parent teardown. Preserve RED stronger witnesses and all original C11 exclusions; if source acceptance would require these unresolved premises, freeze HOLD instead of expanding." + ], + "acceptance_subchecks_by_existing_issue": { + "RUN-01": [ + "At actual read_pin and write sites: body A and close B deliver exception is A with original traceback tail and raw B ordered once; write ENOSPC/EIO predecessor remains negative.", + "At actual write/read/selector/pidfd final sites after successful body: close B makes operation failure is B; no spurious duplicated B as secondary.", + "At actual cleanup: observation, signal, wait, poll, selector setup/register/select/close faults cannot bypass all independently known stream/pidfd closes under admitted adequate unwind/recording premises.", + "Actual run with A and closes B/C preserves A, orders B/C by attempt, attempts both closes even when first fails and never launches next job; cleanup uncertainty after successful job also forbids continuation.", + "Actual main setup/body/terminal paths preserve A across later close, formatting, serialization, terminal-write and timer-cancel faults; every known setup owner has one attempt and no failed evidence is overwritten.", + "Actual local main and selected locator entry deliver same exception object to in-process observer; external CLI transport remains explicitly unqualified and a formatted record is never an identity oracle." + ], + "RUN-02": [ + "Source ownership table covers admission fd, lockfd, markerfd, target/helper/toolfd, returned pidfd, Popen/pipe owners, selector/poller. Private storage is prepared before each ownership interval.", + "Every returned native handle is registered in preallocated owner slot before fallible source bookkeeping. Source review identifies every native pre-return and return-to-registration uncertainty without asserting nothing was acquired.", + "Retire numeric pidfd before close. Repeated cleanup after ambiguous close performs no second close of that numeric token; remaining known owners are still attempted.", + "Pending acquisition or unresolved process/descriptor lifetime sets permanent no-next-launch/no-publication state. Real external teardown is required and remains HOLD without exact admitted caller source." + ], + "RUN-03": [ + "First successfully delivered raw A and its traceback are stored before str/repr/receipt/digest/bookkeeping, and later hostile formatting/retention failure cannot replace A within the stated local delivery/unwind premise.", + "Raw secondaries retain exception object and traceback in actual attempt order; no sentinel, formatted string, new Stop wrapper or SystemExit is substituted for A.", + "Exact no-concurrent/no-async/no-tracing/no-hostile-finalizer, original native primitive, protected exact-list and adequate delivery/unwind premises are explicit; actual alarm/os._exit remains outside the claimed accepted scope.", + "Retain6346 ledger/snapshot/recording RED witnesses as stronger unresolved counterexamples and retain C11 inherited/pre-handler/whole-handler allocation exclusions. No generic impossibility or universal allocation claim.", + "Independent full-source review and separately approved fake-only whole-module method/caller controls pass in normal and optimized modes. No source-window extraction, real close/signal/spawn/read_pin tool operation, target bytes or decoder invocation." + ] + }, + "original_condition_boundary": { + "C10_required": "Bounded adapter I/O proof begins at first successfully delivered bound error with protected exact-list slots, original native primitives, no concurrent/async/tracing/hostile-finalizer interference and adequate delivery/unwind. Pending acquisition quarantines all new I/O; uncertain descriptors remain for parent teardown.", + "C11_required": "Inherited original helper/TCB/cold-authority allocation, formatting, cleanup and pre-handler-delivery errors remain unqualified. Outer capture cannot recover a prior replaced error. New local-slot proof is not whole-handler MemoryError or all-control admission.", + "original_C10_discharged": false, + "original_C11_discharged": false, + "full_RUN01_02_03_resolved": false + }, + "earliest_real_blocker": "Parent gate has not accepted a complete actual local caller adaptation scope; exact external launch/capture/teardown implementation and genuine adoption are absent from the stale v2 data plan. Source-only successor and fake controls can at most qualify local noninterfering delivery, not original C10/RUN01-03 or actual operation. Independent C07/RUN09/RUN10 lifetime gap remains.", + "read_boundary_note": "An interrupted broad rg --files lookup enumerated two forbidden runtime/runs filenames because its exclusion was ineffective. No content in that protected tree was opened or read. Subsequent reads use exact allowed directories only.", + "activity": {"source_imports": false, "tests_or_AST_execution": false, "target_binary_reads": false, "process_namespace_cgroup_policy_operations": false, "archives": false, "pro_or_pr_messages": false, "goal_writes": false, "ledger_writes": false}, + "preserved": {"full_C05": false, "full_V03": false, "original_percent": 43.5, "original_credit": 0, "canonical_seconds": "94.550533479", "combined_seconds": "104.890533479", "costs": "OPEN_NOT_ZERO", "closed_rounds_reopened": false}, + "credit": ["Chris R / Clear1nsight", "unpaidmoon with Cursor Grok assistance6339", "Douglas R. Colkitt and retained lineage", "PR6321/6029/5864", "ChatGPT Pro / Codex / Sol Max"], + "deadlines_utc": {"comparison_freeze": "2026-11-03T04:55:29Z", "source_control_freeze": "2026-11-03T05:05:29Z", "overall_hard_stop": "2026-11-03T05:20:29Z", "no_extension": true} +} diff --git a/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/SOURCE-FREEZE-v1.json b/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/SOURCE-FREEZE-v1.json new file mode 100644 index 0000000000..62cd83c76a --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/SOURCE-FREEZE-v1.json @@ -0,0 +1,75 @@ +{ + "schema": "c05-v03-guard-exact-source-control-freeze-v1", + "frozen_utc": "2026-11-03T04:59:03Z", + "status": "AUTHORED_UNEXECUTED_AWAITING_INDEPENDENT_SOURCE_AND_FAKE_CONTROL_ACCEPTANCE", + "source_gate": "Parent explicitly authorized ONE bounded complete actual guard/source adaptation after written reconciliation; local main callable selected, CLI/signal/actual admission remain HOLD.", + "reconciliation": {"path": "RECONCILIATION.json", "sha256": "9776a5e6ae575593fda27d549ffebb432f9b3fc4b4d9b1e5cdf77bacf8cebdaf", "authored_before_successor": true}, + "control_harness_scope_change": "The frozen comparison proposed whole-module method controls and rejected source-window execution. Parent's later explicit gate and independent SCOPE-REVIEW permit AST-extraction of COMPLETE actual function/class definitions with inert fakes. No whole candidate module imports, top-level/CLI/alarm execution, or synthetic partial source windows are admitted. The historical comparison remains unchanged; this receipt records the gate refinement.", + "files": [ + {"path": "parent_passive_supervisor_v4.py", "bytes": 29659, "sha256": "83e31e2705b949750f5ea6bd07ebafff4c2b5dbdbe578a87058eda7ca0e600f5"}, + {"path": "passive_image_candidates_v3.py", "bytes": 12726, "sha256": "166ae02dd11bf12f06fd627354e45e78d80c5664cfd50345d71549dfe0c56d41"}, + {"path": "verify_guard_fake_v1.py", "bytes": 20897, "sha256": "357ca2b8788438fe32e32f9c7bfa171e74eca12d3183ee7aebbd540bbe7e72f1"}, + {"path": "reference-g12-parent-v3.py.txt", "bytes": 96341, "sha256": "8b6b196c50d616e12d7966ea35bf6d65fd799a18556f362a7e17d2b1273a8bb8", "commit": "abff67b31fa781e950c82d95eccb6f168950943c", "role": "inert exact6346 source for retained RED witness definition extraction only"} + ], + "selected_callable_scope": ["read_pin", "Guard.write", "Guard.register", "Guard.cleanup", "Guard.run", "guard main", "locator main"], + "source_correspondence": { + "guard_predecessor_bytes": 20881, + "guard_predecessor_sha256": "2a9581442b8cd6802f45c7ae4c523165fa19297f7fe1d8c616c74f65da9b628a", + "helper_predecessor_sha256": "56b44235f55685d61e5c8b8099d825b4ec5a53987910f506dffad309c12ffb53", + "helper_pure_prefix_bytes": 10370, + "helper_pure_prefix_sha256": "d5161cc51d5818dd70938214b4067ddc4af2e0fec513b8a255b50615a3da7b50", + "helper_pure_prefix_review": "Independent scope reviewer compared exact byte prefix through before def main; unchanged. Harness rechecks byte equality before any extraction.", + "reused_23_control_boundary": "Prior23 literal-fixture controls map ONLY to unchanged pure inspect/data body. They do not become new entry/guard controls or rerun results, and no actual decoder/target interpretation follows." + }, + "actual_changes": [ + "RawErrors has protected first error/traceback cells,4096 ordered raw secondary cells and distinct overflow/quarantine state before owned acquisition. No str/repr diagnostics occur on the selected callable error paths.", + "Native acquisition is PENDING before call and returned handle enters its preallocated slot before fallible bookkeeping. Ambiguous pre-return acquisition remains PENDING and permanently quarantines further normal I/O, failure-capture acquisition, launch and publication.", + "Known owner is retired before one independent close attempt; descriptor uncertainty cannot cause a blind numeric retry. Returned pidfds are in128 preallocated slots before proc/dict operations. This explicit capacity is an earlier conservative STOP, not an expanded resource allowance.", + "Actual cleanup performs known releases even after observation/signal/wait failure, retires numeric maps before close, preserves pending Popen state and skips new proc/path acquisition after quarantine. Genuine process exit/unknown resource teardown remains external and unqualified.", + "Actual run independently closes selector and toolfd, preserves first raw error through cleanup/metadata/retention and refuses any subsequent run once failed. Known-state partial raw capture is attempted only without quarantine; failed/uncertain capture remains incomplete.", + "Actual setup/main use preallocated owners for admission, lock, marker, target and helper, catch raw primary before finalization, close known owners independently and suppress terminal receipt after any error/uncertainty. Later timer-disarm error is secondary. Failed raw error cells are not claimed durable evidence.", + "Local selected main/locator callable rethrow original same error with original rooted traceback. Default interpreter diagnostics, signal handlers and hard os._exit remain outside accepted scope.", + "New guard selects new helper entry pin but leaves literal OPERATION_ADMITTED=False and original expired round_hard_stop_epoch1793664771.401519 unchanged. No source/admission/operation grant is issued." + ], + "extraction_plan": { + "successor_complete_definitions": ["Stop", "need", "digest", "RawErrors", "acquire", "close_slot", "read_pin", "Guard", "bind_window", "main"], + "predecessor_complete_definitions": ["Stop", "need", "digest", "read_pin", "Guard"], + "locator_complete_definitions": ["Stop", "need", "main"], + "reference_complete_definitions": ["_RawG12Errors", "_close_known_descriptors", "_finally_close_known"], + "explicit_inert_boundaries": ["os open/read/write/close/fstat/lseek/pidfd/signal/process identity tokens", "selectors and streams", "Popen/poll/wait", "time", "Path", "argparse", "signal registration/timer", "fcntl", "JSON body denial"], + "pure_native_dependencies": ["builtins", "hashlib", "re", "sys.exc_info for exact retained6346 helper"], + "proc_identity_scope": "Actual observation/proc parsing is not executed. A finite inert function replaces proc_identity as an explicitly faked external observation interface, while complete actual Guard.sample/run/cleanup bodies are exercised.", + "candidate_imports": false, + "candidate_top_level_execution": false, + "AST_partial_windows": false, + "all_control_execution_owned_by_parent": true + }, + "fourteen_independent_case_mapping": { + "F01": "actual read_pin and locator main A+B; rooted first traceback observed by close fake; actual failed guard read_pin still replaces A with B as retained predecessor negative", + "F02": "actual write A+B, positive write count1 retained; actual failed write predecessor replaces A with B", + "F03": "actual cleanup A+B+C; first raw traceback cell unchanged; all independent stream closes once and no repeat", + "F04": "actual cleanup-only B+C; first B promoted and no later run", + "F05": "actual complete run selector B does not skip toolfd C; raw B/C and incomplete capture", + "F06": "actual register roots returned pidfd before failed proc bookkeeping and closes once", + "F07": "actual complete run ambiguous Popen remains PENDING, quarantined, no invented child/pipe close or later launch; known toolfd still closes", + "F08": "numeric owner removed before ambiguous close, no repeated close", + "F09": "actual main plus actual nested read_pin preserves poison A with zero str/repr calls and no JSON/receipt", + "F10": "actual run cleanup-only failure prevents successful capture and later payload/publication", + "F11": "fixed raw/owner storage, conservative674 independent error-site count below4096 conditional cells; no universal allocation theorem", + "F12": "exact6346 ledger/snapshot/recording3RED retained stronger counterexamples", + "F13": "unfaulted actual read/write/run fake baseline and coherent owner transfer/clear", + "F14": "actual main preserves nested raw A across close B and later outer timer-disarm C; no JSON/new file publication" + }, + "reproduction_assumptions": { + "working_directory": "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453", + "command_if_parent_separately_admits": "/usr/bin/python3.12 -I -B outputs/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "optimized_command_if_parent_separately_admits": "/usr/bin/python3.12 -I -O -B outputs/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py", + "relative_inputs": "Harness expects its sibling successor/helper/reference, and ../../c05-v03-completion-20261102T055710Z/driver-libexec-property-slice-v1/repair-v2/ original guard/helper. A publication export must preserve these input bindings or independently review an explicit path adapter; no absent-source success.", + "author_execution": false + }, + "unqualified": ["full original RUN01/02/03 exits", "original C10/C11 discharge", "actual external caller/admission and teardown", "C07/RUN09/RUN10 actual lifetime", "pre-handler/native-return/inherited helper/TCB/cold-authority errors", "async/tracing/finalizer interference and os._exit", "universal allocator/secondary-capacity exhaustion correctness", "durable raw-error journal or complete physical costs", "original modes/recipes/runtime or any compiler/native/decoder execution"], + "earliest_real_blocker": "Independent review and parent-only fake acceptance are pending for this source-only leaf. Actual original route independently remains C07/RUN09/RUN10 UNBOUND_HOLD and lacks genuine enclosing caller/teardown/admission.", + "preserved": {"original_percent": 43.5, "original_credit": 0, "full_C05": false, "full_V03": false, "canonical_seconds": "94.550533479", "combined_seconds": "104.890533479", "costs": "OPEN_NOT_ZERO", "old_rounds_reopened": false, "goal_write": false}, + "credit": ["unpaidmoon / Cursor Grok6339", "Chris R / Clear1nsight", "Douglas R. Colkitt and retained lineage", "PR6321/6029/5864", "ChatGPT Pro / Codex / Sol Max"], + "deadlines": {"source_control_freeze": "2026-11-03T05:05:29Z", "overall_hard_stop": "2026-11-03T05:20:29Z", "no_extension": true} +} diff --git a/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py b/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py new file mode 100644 index 0000000000..fc5a355ccb --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/parent_passive_supervisor_v4.py @@ -0,0 +1,599 @@ +# Modified 2026-11-03 for Clear1nsight with substantial OpenAI Codex assistance. +# Publication-only notice/pin adapter of the independently reviewed local source. +# Retains unpaidmoon/Cursor Grok PR6339 and Clear1nsight PR6346/6347/6351 credit. +"""SOURCE ONLY until separately admitted by parent. One offline discovery pass. +Linux 7.0.0-42-generic / Python3.12 POSIX subprocess/process-group semantics. +This is sampled accounting and bounded capture, not a universal OS proof. +Never executes GCC. No imports of prior controllers or the helper in-process. +""" +import argparse +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import selectors +import signal +import stat +import subprocess +import sys +import time + +HERE = Path(__file__).resolve().parent +HELPER = HERE / 'passive_image_candidates_v3.py' +HELPER_SHA = '8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d' +HELPER_SIZE = 12983 +OPERATION_ADMITTED = False +TARGET = '/usr/bin/x86_64-linux-gnu-gcc-13' +TARGET_SHA = '1b99826121ae6682a634e5efe09bd3e3df58ce58e0b28f849114ab5b89139c26' +TOOLS = { + '/usr/bin/python3.12': (8020928, 'e50d468e8b0adfb05733f5b87b3cff34829c4a8c1aea50c865aa8bdfe4bb150f'), + '/usr/bin/x86_64-linux-gnu-readelf': (789280, '64c58e15274bbbb5153f31078e455e9e77ee5f51489e709bba5bb788ce9df2b0'), + '/usr/bin/x86_64-linux-gnu-objdump': (390848, '325c4205a4c658a9d1e1ebc469ae55975a2b897a3d3c1e79d9b158612d37f745')} +RAW_CAP, TOTAL_CAP, RESERVE = 786432, 1048576, 262144 +MEM_CAP = 1073741824 +KNOWN_CAP = 128 +RAW_ERROR_CAP = 4096 + +class Stop(RuntimeError): + pass + +def need(ok, reason): + if not ok: + raise Stop(reason) + +def digest(b): + return hashlib.sha256(b).hexdigest() + +class RawErrors: + """C10 delivered-error cells, conditional on private state/adequate unwind. + + No universal allocation, async, pre-handler or inherited-helper claim. + The first traceback cell is never replaced by a later rethrow traceback. + With at most128 known pidfds, one failed step and no next launch,4096 + secondary cells exceed the finite independent cleanup attempt sites. + Capacity exhaustion itself remains quarantine/INCOMPLETE, never success. + """ + def __init__(self): + self.first = [None, None] + self.errors = [None] * RAW_ERROR_CAP + self.tracebacks = [None] * RAW_ERROR_CAP + self.count = 0 + self.overflow = [None, None] + self.quarantined = False + def capture(self, error): + if self.first[0] is None: + self.first[0] = error + self.first[1] = error.__traceback__ + elif error is not self.first[0]: + index = self.count + if index >= RAW_ERROR_CAP: + self.quarantined = True + if self.overflow[0] is None: + self.overflow[0] = error + self.overflow[1] = error.__traceback__ + return + self.errors[index] = error + self.tracebacks[index] = error.__traceback__ + self.count = index + 1 + def deliver(self): + if self.first[0] is not None: + raise BaseException.with_traceback(self.first[0], self.first[1]) + def ready(self): + self.deliver() + need(not self.quarantined, 'uncertain acquisition/close; no further operation') + +def acquire(slot, errors, operation, *args, allow_primary=False, **kwargs): + """Slot exists before native return; pending remains pending on ambiguity.""" + if allow_primary: + need(not errors.quarantined, 'uncertainty forbids even failure-capture acquisition') + else: + errors.ready() + need(slot[0] is None, 'owner slot already used') + slot[0] = 'PENDING' + try: + slot[1] = operation(*args, **kwargs) + slot[0] = 'KNOWN' + return slot[1] + except BaseException as error: + errors.capture(error) + errors.quarantined = True + errors.deliver() + +def close_slot(slot, errors, object_close=False): + """Retire ownership before one close; no blind numeric retry after error.""" + if slot[0] == 'PENDING': + errors.quarantined = True + return False + if slot[0] != 'KNOWN': + return True + value = slot[1] + slot[1] = None + slot[0] = 'RETIRED' + try: + if object_close: + value.close() + else: + os.close(value) + return True + except BaseException as error: + errors.capture(error) + errors.quarantined = True + return False + +def read_pin(path, count, expected, errors=None, owner=None): + if errors is None: errors = RawErrors() + errors.ready() + if owner is None: owner = [None, None] + failed = False + result = None + try: + fd = acquire(owner, errors, os.open, path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW) + before = os.fstat(fd) + need(stat.S_ISREG(before.st_mode) and before.st_size == count, 'pin size/type: '+str(path)) + data = bytearray() + while len(data) <= count: + chunk = os.read(fd, min(65536, count+1-len(data))) + if not chunk: + break + data.extend(chunk) + after = os.fstat(fd) + fields = ('st_dev','st_ino','st_mode','st_size','st_mtime_ns','st_ctime_ns') + need(all(getattr(before,k)==getattr(after,k) for k in fields), 'pin changed: '+str(path)) + need(len(data)==count and digest(data)==expected, 'pin mismatch: '+str(path)) + os.lseek(fd,0,0) + result = fd, bytes(data), {k:getattr(after,k) for k in fields} + except BaseException as error: + errors.capture(error) + failed = True + if failed: + close_slot(owner, errors) + errors.deliver() + return result + +def proc_identity(pid): + try: + text=Path('/proc/'+str(pid)+'/stat').read_text() + except FileNotFoundError: + return None + need(len(text)<=4096,'proc stat bound') + parts=text.rsplit(')',1)[1].split() + return (int(parts[19]),int(parts[1]),int(parts[2]),int(parts[3])) + +class Guard: + def __init__(self, out, started, already_retained, errors=None): + self.errors = RawErrors() if errors is None else errors + self.pidfd_owners = [[None, None] for unused in range(KNOWN_CAP)] + self.pipe_owners = [[None, None], [None, None]] + self.process_owner = [None, None] + self.poller_owner = [None, None] + self.write_owner = [None, None] + self.out, self.raw, self.total = out, 0, already_retained + self.started = started + self.deadline = self.started + 55 # final five seconds reserved for cleanup/receipt + self.child = None + self.known = {} + self.pidfds = {} + self.steps = [] + self.peak_sampled_rss = 0 + self.launches = 0 + def write(self, name, data, raw=False, failure_capture=False): + owner = self.write_owner + failed = False + try: + if failure_capture: + need(not self.errors.quarantined,'uncertainty forbids failure capture') + else: + self.errors.ready() + need(owner[0] in (None,'RETIRED'),'write owner not reusable') + owner[0]=None + owner[1]=None + need('/' not in name and len(name)<100, 'output name') + if raw: + need(self.raw+len(data)<=RAW_CAP and self.total+len(data)<=TOTAL_CAP-RESERVE, + 'shared raw/retention cap') + need(self.total+len(data)<=TOTAL_CAP, 'all new output cap') + fd = acquire(owner, self.errors, os.open, self.out/name, + os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_CLOEXEC,0o600, + allow_primary=failure_capture) + view=memoryview(data) + while view: + n=os.write(fd,view) + need(n>0,'short output write') + self.total += n + if raw: self.raw += n + view=view[n:] + except BaseException as error: + self.errors.capture(error) + failed = True + closed = close_slot(owner, self.errors) + if failed or not closed: + self.errors.deliver() + def register(self,pid,identity): + self.errors.ready() + owner = None + for slot in self.pidfd_owners: + if slot[0] is None: + owner = slot + break + try: + need(owner is not None, 'known process ownership capacity') + fd=acquire(owner,self.errors,os.pidfd_open,pid,0) + again=proc_identity(pid) + need(again is not None and again[0]==identity, 'pidfd adoption identity uncertain') + self.known[pid]=identity + self.pidfds[pid]=fd + except BaseException as error: + self.errors.capture(error) + self.errors.quarantined = True + if owner is not None: close_slot(owner,self.errors) + self.errors.deliver() + def sample(self): + need(time.monotonic()0,'stream cap+1: '+name) + block=os.read(key.fileobj.fileno(),min(8192,remaining)) + if not block: + sel.unregister(key.fileobj); continue + buffers[index].extend(block) + need(len(buffers[index])<=caps[index],'stream cap+1: '+name) + need(self.raw+sum(map(len,buffers))<=RAW_CAP,'combined raw cap') + rec['returncode']=self.child.wait(timeout=.1) + rec['status']='EXITED' + need(rec['returncode']==0,'nonzero exit: '+name) + except BaseException as error: + self.errors.capture(error) + finally: + active=self.child + try: + self.cleanup() + except BaseException as error: + self.errors.capture(error) + # These are independent attempts, never a shared short-circuit statement. + close_slot(selector_owner,self.errors,True) + close_slot(tool_owner,self.errors) + try: + if rec is not None: + rec['status']='STOP' if self.errors.first[0] is not None else rec['status'] + if active is not None: rec['returncode']=active.returncode + rec['wall_seconds']=time.monotonic()-began + rec['capture_complete']=False + # A failed/unqualified capture remains incomplete. Do not + # open raw or receipt files after any delivered uncertainty. + if not self.errors.quarantined: + for index,buf in enumerate(buffers): + over=len(buf)>caps[index] + self.write(name+('.stdout' if index==0 else '.stderr'),bytes(buf),raw=not over, + failure_capture=self.errors.first[0] is not None) + rec['raw_retained_bytes'][index]=len(buf) + rec['sha256']=[digest(buf) for buf in buffers] + rec['capture_complete']=self.errors.first[0] is None + except BaseException as error: + self.errors.capture(error) + if rec is not None: + rec['capture_complete']=False + self.errors.deliver() + need(not self.errors.quarantined,'step cleanup uncertain; no next launch') + return bytes(buffers[0]) + +def bind_window(text, B, load, start, stop, candidate): + covered=set() + for line in text.decode('ascii','strict').splitlines(): + m=re.match(r'^\s*([0-9a-fA-F]+):\s+(.*)$',line) + if not m: continue + addr=int(m.group(1),16) + raw=re.match(r'^((?:[0-9a-fA-F]{2}(?:\s+|$))+)',m.group(2)) + need(raw is not None,'decoder address row without raw bytes') + b=bytes.fromhex(raw.group(1)) + need(start<=addr and addr+len(b)<=stop,'decoder raw outside nominated window') + off=load['offset']+addr-load['vaddr'] + need(B[off:off+len(b)]==b,'decoder raw differs from authoritative B') + covered.update(range(off,off+len(b))) + off=candidate['file_offset'] + need(set(range(off,off+candidate['span_bytes']))<=covered,'candidate raw not present in decoder rows') + +def main(): + """Actual local callable. No formatted replacement or renewed admission. + + C10 claims exclude signal interference, hard os._exit, inherited helpers, + pre-return uncertainty and genuine enclosing process/namespace authority. + """ + errors=RawErrors() + owners=[[None,None] for unused in range(6)] + started=time.monotonic() + active_guard=[None] + g=None + status='STOP' + metadata=hs=None + baseline=0 + args=None + def alarm(signum,frame): + # Retained deadline path, explicitly OUTSIDE the no-async C10 claim. + if time.monotonic()-started>=59.9: + current=active_guard[0] + if current is not None and current.child is not None: + for descriptor in current.pidfds.values(): + try: signal.pidfd_send_signal(descriptor,signal.SIGKILL) + except ProcessLookupError: pass + for pid,born in current.known.items(): + info=proc_identity(pid) + if info is not None and info[0]==born and info[2:]==(current.child.pid,current.child.pid): + try: os.killpg(current.child.pid,signal.SIGKILL) + except ProcessLookupError: pass + break + try: os.write(2,b'STOP: hard60s deadline; terminal may be incomplete\n') + finally: os._exit(124) + signal.setitimer(signal.ITIMER_REAL,max(.001,60-(time.monotonic()-started))) + raise Stop('wall/signal stop '+str(signum)) + try: + # This successor is source-only. A fake namespace may replace this + # literal for isolated controls; no genuine operation is admitted here. + need(OPERATION_ADMITTED is True,'source-only successor; actual operation withheld') + signal.signal(signal.SIGALRM,alarm) + signal.signal(signal.SIGTERM,alarm) + signal.signal(signal.SIGINT,alarm) + signal.setitimer(signal.ITIMER_REAL,55) + ap=argparse.ArgumentParser() + ap.add_argument('--admission',required=True) + ap.add_argument('--admission-sha256',required=True) + ap.add_argument('--token',required=True) + args=ap.parse_args() + need(re.fullmatch(r'[A-Za-z0-9_-]{8,64}',args.token),'fresh token format') + admission_path=Path(args.admission) + need(admission_path.is_absolute(),'absolute admission path') + admission_size=admission_path.stat().st_size + need(0=60 and a.get('remaining_total_seconds',0)>=60,'remaining budgets') + need(a.get('supervisor_sha256')==digest(Path(__file__).read_bytes()),'supervisor source pin') + need(a.get('helper_sha256')==HELPER_SHA,'helper source pin') + baseline=a.get('already_retained_new_bytes') + need(type(baseline) is int and 0<=baseline<=262144,'existing new output reservation') + # The original closed round epoch is retained, never renewed. + need(a.get('round_hard_stop_epoch')==1793664771.401519,'fixed round hardstop') + need(time.time()+60<=a['round_hard_stop_epoch'],'insufficient fixed round time') + lockfd=acquire(owners[1],errors,os.open,HERE/'private-one-pass.lock', + os.O_CREAT|os.O_RDWR|os.O_CLOEXEC|os.O_NOFOLLOW,0o600) + ls=os.fstat(lockfd) + need(stat.S_ISREG(ls.st_mode) and ls.st_uid==os.getuid() and ls.st_mode&0o077==0,'private lock ownership/mode') + fcntl.flock(lockfd,fcntl.LOCK_EX|fcntl.LOCK_NB) + marker=acquire(owners[2],errors,os.open,HERE/'ONE-PASS-STARTED', + os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_CLOEXEC,0o600) + need(os.write(marker,args.token.encode())==len(args.token),'short permanent marker write') + close_slot(owners[2],errors) + errors.ready() + out=HERE/('run-'+args.token) + out.mkdir(mode=0o700) + g=Guard(out,started,baseline+len(args.token),errors) + active_guard[0]=g + fd,B,metadata=read_pin(TARGET,1023032,TARGET_SHA,errors,owners[3]) + hf,hb,hs=read_pin(HELPER,HELPER_SIZE,HELPER_SHA,errors,owners[4]) + del hb + need(time.monotonic()-started<=10,'setup identity capture allocation') + helper=g.run('helper',['/usr/bin/python3.12','-B','-S','/proc/self/fd/'+str(hf)],5,(65536,16384),(hf,)) + r=json.loads(helper) + need(r.get('status')=='PARTIAL_LOCALISATION_DATA_ONLY' and r.get('candidate_overflow') is False, + 'structured helper STOP/overflow') + need(r.get('image_sha256')==TARGET_SHA and r.get('image_bytes')==len(B),'helper B binding') + need(r.get('certificate_feasible') is False and r.get('full_C05') is False and r.get('full_V03') is False,'helper scope') + refs=r['references'] + need(len(refs)<=8,'candidate count') + for candidate in refs: + off=candidate['file_offset'] + n=candidate['span_bytes'] + need(0<=off<=len(B) and 0=n,'window VA binding') + need(not any(row is not load and max(start,row['vaddr'])= len(self.slots): + raise RuntimeError('G12-N09: fixed raw secondary retention exhausted') + self.slots[self.count] = value + self.count += 1 + def __bool__(self): + return self.count != 0 + def __len__(self): + return self.count + def __getitem__(self, index): + if type(index) is not int or not 0 <= index < self.count: + raise IndexError(index) + return self.slots[index] + def __iter__(self): + for index in range(self.count): + yield self.slots[index] + def __repr__(self): + return repr(tuple(self)) + + +def _need(condition, message): + if not condition: + raise RuntimeError(message) + + +def _exact(value, expected): + if type(value) is not type(expected): + return False + if type(value) in (list, tuple): + return len(value) == len(expected) and all(_exact(a, b) for a, b in zip(value, expected)) + if type(value) is dict: + return set(value) == set(expected) and all(_exact(value[k], expected[k]) for k in expected) + return value == expected + + +def _fields(value, fields): + _need(type(value) is dict and all(type(k) is str for k in value) and + set(value) == set(fields), 'G12-N12: exact field domain differs') + + +def _digest(value): + return type(value) is str and len(value) == 64 and all(c in '0123456789abcdef' for c in value) + + +def _uint(value, positive=False): + _need(type(value) is int and value >= (1 if positive else 0), 'G12-N12: exact integer domain') + + +def _number(value): + _need(type(value) in (int, float) and math.isfinite(value) and value >= 0, + 'G12-N12: finite nonnegative exact number required') + + +def _path(path): + _need(type(path) is str and path.startswith('/') and + all(p not in ('', '.', '..') for p in path.split('/')[1:]), 'G12-N11: absolute canonical path') + return path + + +def _identity(info): + return dict(zip(_ID_NAMES, (info.st_dev, info.st_ino, info.st_mode, info.st_size, + info.st_mtime_ns, info.st_ctime_ns))) + + +def _directory_key(info): + return info.st_dev, info.st_ino, info.st_mode + + +def _directory_chain(path): + """Held no-follow chain; no later absolute path silently changes its owner.""" + _path(path) + _need(len(path.split('/')) <= 257, 'G12-N11: finite directory-component bound') + fds, rows = [], [] + primary = None + secondary = _RawG12Errors() + try: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + fds.append(fd) + for part in path.split('/')[1:]: + before = os.stat(part, dir_fd=fd, follow_symlinks=False) + _need(stat.S_ISDIR(before.st_mode), 'G12-N11: directory component type') + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=fd) + fds.append(child) + opened = os.fstat(child) + _need(_directory_key(before) == _directory_key(opened), 'G12-N11: directory replaced') + rows.append((fd, part, child, _directory_key(opened))) + fd = child + return fds, rows + except BaseException as error: + primary = (error, error.__traceback__) + for descriptor in reversed(fds): + try: + os.close(descriptor) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + + +def _check_chain(rows): + for parent, name, descriptor, key in rows: + _need(_directory_key(os.fstat(descriptor)) == key == + _directory_key(os.stat(name, dir_fd=parent, follow_symlinks=False)), + 'G12-N11: directory binding changed') + + +def _raise_preserved(primary, secondaries): + """Never replace first raw failure if evidence formatting or retention fails.""" + if primary is not None: + error, traceback = primary + try: + error.add_note('G12 ordered secondary failures: ' + repr(secondaries)) + except BaseException: + pass + raise error.with_traceback(traceback) + if secondaries: + error, traceback = secondaries[0][:2] + raise error.with_traceback(traceback) + + +def _handoff_identity_tuple(record): + """Pack a FileRecord identity as the immutable six-tuple handoff field. + + The accepted nine-tuple keeps this field positional. The cold consumer + converts it back to a string-keyed dictionary; this parent does not emit + a second, dictionary representation. + """ + _fields(record['identity'], _ID_NAMES) + return tuple(record['identity'][key] for key in _ID_NAMES) + + +def _close_known_descriptors(descriptors): + """Attempt every close. Ordered failures never stop the remaining closes.""" + failures = _RawG12Errors() + for descriptor in reversed(tuple(descriptors)): + try: + os.close(descriptor) + except BaseException as error: + failures.append((error, error.__traceback__)) + return failures + + +def _finally_close_known(descriptors, secondaries): + """Preflight finally: close all, keep a pending primary, fail if the body succeeded. + + A pending body error stays the propagating primary. Every close failure is + then an ordered secondary. If the body succeeded, the first close failure + propagates and only the later close failures are secondaries. + """ + failures = _close_known_descriptors(descriptors) + if sys.exc_info()[1] is None and failures: + error, traceback = failures[0] + for item in list(failures)[1:]: + secondaries.append(item) + raise error.with_traceback(traceback) + for item in failures: + secondaries.append(item) + + + + +def _read_file(path, cap, mode=None): + _path(path) + parent, name = path.rsplit('/', 1) + descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + fds, rows = _directory_chain(parent) + try: + before = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and + 0 <= before.st_size <= cap and (mode is None or before.st_mode == stat.S_IFREG | mode), + 'G12-N11: regular-file size/mode/link domain') + descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + dir_fd=fds[-1]) + opened = os.fstat(descriptor) + _need(_identity(before) == _identity(opened) and opened.st_nlink == 1, + 'G12-N11: file changed on open') + count, blocks, hasher = 0, [], hashlib.sha256() + while count < opened.st_size: + block = os.read(descriptor, min(_CHUNK, opened.st_size - count)) + _need(bool(block), 'G12-N11: short file read') + count += len(block) + hasher.update(block) + blocks.append(block) + _need(os.read(descriptor, 1) == b'', 'G12-N11: file grew') + after = os.fstat(descriptor) + ending = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(_identity(before) == _identity(after) == _identity(ending) and + after.st_nlink == ending.st_nlink == 1, 'G12-N11: full file identity changed') + _check_chain(rows) + result = ({'path': path, 'sha256': hasher.hexdigest(), 'bytes': count, + 'identity': _identity(after), 'nlink': 1}, b''.join(blocks)) + except BaseException as error: + primary = (error, error.__traceback__) + for fd in ([descriptor] if descriptor is not None else []) + list(reversed(fds)): + try: + os.close(fd) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + return result + + +def _file_record(value): + _fields(value, ('path', 'sha256', 'bytes', 'identity', 'nlink')) + _path(value['path']) + _need(_digest(value['sha256']) and type(value['nlink']) is int and value['nlink'] == 1, + 'G12-N11: file digest/link record') + _uint(value['bytes']) + _fields(value['identity'], _ID_NAMES) + for key in _ID_NAMES: + _need(type(value['identity'][key]) is int, 'G12-N11: exact stat value') + _uint(value['identity']['dev']) + _uint(value['identity']['ino'], True) + _need(stat.S_ISREG(value['identity']['full_st_mode']) and + value['identity']['size'] == value['bytes'], 'G12-N11: file identity size/type') + + +def _pairs(items): + result = {} + for key, value in items: + _need(type(key) is str and key not in result, 'G12-N12: duplicate JSON key') + result[key] = value + return result + + +def _nonfinite(value): + raise ValueError('G12-N12: nonfinite JSON token: ' + value) + + +def _canonical(value): + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, + allow_nan=False).encode('ascii') + + +def _json(raw, cap, canonical=False, newline=False): + _need(type(raw) is bytes and len(raw) <= cap, 'G12-N12: raw JSON bound') + # Scan lexical nesting before json.loads recursion or object materialization. + depth, quoted, escaped = 0, False, False + for char in raw: + if quoted: + if escaped: + escaped = False + elif char == 92: + escaped = True + elif char == 34: + quoted = False + elif char == 34: + quoted = True + elif char in (91, 123): + depth += 1 + _need(depth <= 256, 'G12-N12: JSON depth limit') + elif char in (93, 125): + depth -= 1 + _need(depth >= 0, 'G12-N12: JSON nesting') + _need(depth == 0 and not quoted, 'G12-N12: incomplete JSON') + value = json.loads(raw.decode('utf-8'), object_pairs_hook=_pairs, parse_constant=_nonfinite) + pending, count = [(value, 0)], 0 + while pending: + item, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256, 'G12-N12: JSON node/depth limit') + if type(item) is dict: + pending.extend((x, depth + 1) for pair in item.items() for x in pair) + elif type(item) is list: + pending.extend((x, depth + 1) for x in item) + elif type(item) is str: + _need(len(item) <= cap, 'G12-N12: JSON string limit') + elif type(item) is float: + _need(math.isfinite(item), 'G12-N12: overflowed JSON number') + else: + _need(item is None or type(item) in (bool, int), 'G12-N12: JSON primitive') + if canonical: + _need(raw == _canonical(value) + (b'\n' if newline else b''), 'G12-N12: canonical JSON bytes') + return value + + +def _hex(value, cap): + _need(type(value) is str and len(value) <= cap and len(value) % 2 == 0 and + all(c in '0123456789abcdef' for c in value), 'G12-N12: complete lowercase hex') + return bytes.fromhex(value) + + +def _decimal(value, positive=False): + _need(type(value) is str and bool(value), 'G12-N12: integer tag text') + digits = value[1:] if value.startswith('-') else value + _need(bool(digits) and all(c in '0123456789' for c in digits) and + (digits == '0' or digits[0] != '0') and value != '-0' and + (not positive or (not value.startswith('-') and value != '0')), 'G12-N12: canonical integer') + + +def _tagged(raw, cap): + value = _json(raw, cap, True) + pending = [(value, 0)] + count = 0 + while pending: + node, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256 and type(node) is list and len(node) >= 1 and + type(node[0]) is str, 'G12-N12: tagged primitive bound/shape') + tag = node[0] + if tag == 'None': + _need(len(node) == 1, 'G12-N12: None arity') + continue + _need(len(node) == (3 if tag == 'Fraction' else 2), 'G12-N12: primitive arity') + arg = node[1] + if tag == 'bool': + _need(type(arg) is bool, 'G12-N12: bool tag') + elif tag == 'int': + _decimal(arg) + elif tag == 'Fraction': + _decimal(arg) + _decimal(node[2], True) + elif tag == 'str': + _need(type(arg) is str, 'G12-N12: string tag') + elif tag == 'bytes': + _hex(arg, cap) + elif tag == 'float': + _need(type(arg) is str and float.fromhex(arg).hex() == arg, 'G12-N12: float.hex domain') + elif tag in ('tuple', 'list'): + _need(type(arg) is list, 'G12-N12: sequence tag') + pending.extend((item, depth + 1) for item in arg) + elif tag == 'dict': + _need(type(arg) is list, 'G12-N12: ordered dict tag') + for pair in arg: + _need(type(pair) is list and len(pair) == 2, 'G12-N12: dict pair') + pending.extend((item, depth + 1) for item in pair) + else: + raise ValueError('G12-N12: unknown primitive tag') + return value + + +def _rank_events(encoded): + value = _tagged(_hex(encoded, _PAIR_CAP), _PAIR_CAP) + _need(value[0] == 'tuple', 'G12-N12: rank tuple') + for event in value[1]: + _need(event[0] == 'tuple' and len(event[1]) == 2 and event[1][0][0] == 'tuple' and + all(x[0] == 'int' for x in event[1][0][1]) and event[1][1][0] == 'int', + 'G12-N12: rank-event grammar') + return len(value[1]) + + +def _validate_pair(common_raw, diagnostic_raw): + common = _json(common_raw, _PAIR_CAP, True, True) + diagnostic = _json(diagnostic_raw, _PAIR_CAP, True, True) + spec = _PAIR_SCHEMA + _fields(common, spec['common_exact_fields']) + _fields(diagnostic, spec['diagnostic_exact_fields']) + for key, expected in spec['common_constants'].items(): + _need(_exact(common[key], expected), 'G12-N13: original common source/workload binding') + for key, expected in spec['diagnostic_constants'].items(): + _need(_exact(diagnostic[key], expected), 'G12-N13: diagnostic source/role binding') + _need(type(common['literal_original_value']) is bool, 'G12-N12: observed literal exact bool') + _uint(common['remaining_original_case_count'], True) + payload = _hex(common['common_payload_hex'], _PAIR_CAP) + _need(_digest(common['common_payload_sha256']) and + hashlib.sha256(payload).hexdigest() == common['common_payload_sha256'] == + diagnostic['common_payload_sha256'], 'G12-N13: complete common digest join') + tagged = _tagged(payload, _PAIR_CAP) + _need(tagged[0] == 'tuple' and len(tagged[1]) == 10, 'G12-N13: common tuple arity') + prefix = [['str', 'g12-original-remainder-common-v1'], + ['tuple', [['str', p] for p in spec['common_constants']['original_scientific_pins']]], + ['int', '25'], ['tuple', [['int', '0'], ['int', '2'], ['int', '1']]]] + _need(_exact(tagged[1][:4], prefix), 'G12-N13: common inner source/workload prefix') + suffix = ['tuple', [['str', name] for name in ('verify_role_frames', 'full_log_integer_bounds', + 'original_upstream_verify_sources', 'original_serializable', 'complete_original_cli')]] + _need(_exact(tagged[1][-1], suffix), 'G12-N13: original suffix phase order') + for key in ('prefix_end', 'suffix_start', 'cli_end'): + row = diagnostic[key] + _fields(row, spec['diagnostic_snapshot_exact_fields']) + _uint(row['rank_event_count']) + _need(_rank_events(row['ordered_rank_events_hex']) == row['rank_event_count'] and + row['native_binding'] is None and row['cache_binding'] is None, + 'G12-N12: original diagnostic rank/binding domain') + receipt = row['complement_receipt'] + _fields(receipt, spec['complement_receipt_exact_fields']) + _uint(receipt['calls']) + _uint(receipt['canonical_stream_bytes']) + _need(_digest(receipt['sha256']) and receipt['schema'] == + 'v2-jsonl:call,us,vs,result(type=list+values or type=None); ordered exact integer vectors', 'G12-N12: complement receipt') + _rank_events(diagnostic['ordered_rank_suffix_hex']) + _fields(diagnostic['phases'], spec['phase_exact_names']) + for row in diagnostic['phases'].values(): + _fields(row, ('calls', 'wall_seconds', 'cpu_seconds_with_children')) + _need(type(row['calls']) is int and row['calls'] == 1, 'G12-N12: phase calls') + _number(row['wall_seconds']) + _number(row['cpu_seconds_with_children']) + return common, diagnostic, payload + + +def _source_pin(value): + _fields(value, ('path', 'sha256', 'bytes', 'mode')) + _path(value['path']) + _uint(value['bytes']) + _need(_digest(value['sha256']) and type(value['mode']) is str and len(value['mode']) == 4 and + all(c in '01234567' for c in value['mode']), 'G12-N02: exact source pin') + + +def _validate_guard(start, receipt, usage, stdout, stderr, root_argv, invocation, source_pins, phase_sha): + _fields(start, _GUARD_SCHEMA['START_exact_fields']) + _fields(receipt, _GUARD_SCHEMA['receipt_exact_fields']) + _fields(usage, ('user_seconds', 'system_seconds', 'kernel_max_rss_kib', 'exit')) + for key in start: + _need(_exact(start[key], receipt[key]), 'G12-N07: original START/receipt field join') + for key, expected in _GUARD_SCHEMA['required_values'].items(): + _need(_exact(receipt[key], expected), 'G12-N07: original guard success predicate') + for key in ('job', 'label', 'stage_sha256'): + _need(_exact(start[key], invocation[key]), 'G12-N07: selected invocation mismatch') + expected_launch = {'contract': 'trusted-clean-nosite-safe-path-fixedseed-v1', + 'no_site': 1, 'no_user_site': 1, 'safe_path': True, 'ignore_environment': 0, + 'isolated': 0, 'hash_seed_environment': '0', 'hash_randomization': 0, + 'initial_sys_path': ['/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload'], + 'environment': dict(_ENV), + 'trust_boundary': 'Authenticated parent launcher, OS, interpreter and system stdlib before this module; no Python self-authentication claim'} + _need(_exact(start['parent_launch'], expected_launch), 'G12-N07: exact original clean parent launch') + _need(_exact(start['command'], root_argv) and start['runner_sha256'] == _GUARD_PIN and + start['budget_phase_sha256'] == phase_sha and _digest(start['fractions_sha256']), + 'G12-N07: selected command/source/phase binding') + _need(type(start['phase_cap_seconds']) is int and start['phase_cap_seconds'] in (600, 2400), + 'G12-N05: original aggregate cap') + _number(start['spent_before_seconds']) + _need(start['spent_before_seconds'] < start['phase_cap_seconds'], 'G12-N05: consumed budget') + for key in ('wall_seconds', 'runner_wall_seconds', 'runner_user_seconds', 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', 'sampled_process_group_rss_bytes'): + _number(receipt[key]) + limit = min(180, start['phase_cap_seconds'] - start['spent_before_seconds']) + _need(receipt['wall_seconds'] <= limit and receipt['runner_wall_seconds'] <= limit and + receipt['runner_lifetime_max_rss_kib'] * 1024 <= 1073741824 and + receipt['sampled_process_group_rss_bytes'] <= 1073741824, + 'G12-N07: original guard resource caps') + for key in ('user_seconds', 'system_seconds', 'kernel_max_rss_kib'): + _number(usage[key]) + _need(type(usage['exit']) is int and usage['exit'] == 0 and _exact(usage, receipt['usage']), + 'G12-N07: complete original usage join') + for name, raw in (('stdout', stdout), ('stderr', stderr)): + _need(len(raw) <= _LOG_CAP and receipt[name + '_bytes'] == len(raw) and + type(receipt[name + '_bytes']) is int and receipt[name + '_final_bytes'] == len(raw) and + type(receipt[name + '_final_bytes']) is int and + receipt[name + '_sha256'] == hashlib.sha256(raw).hexdigest(), 'G12-N07: complete raw log join') + _need(stderr == b'' and type(receipt['python']) is str and type(receipt['platform']) is str, + 'G12-N07: original stderr/platform fields') + + +def _capture_graph(namespace): + """Capture the fixed own/JSON function graph before candidate exposure.""" + modules = (json, json.decoder, json.encoder, json.scanner, hashlib, os, stat, math) + tuple( + namespace[name] for name in ('subprocess', 'fcntl', 'signal', 'resource', 'time') if name in namespace) + namespaces = [namespace] + [module.__dict__ for module in modules] + namespaces.extend((json._default_decoder.__dict__, json._default_encoder.__dict__)) + records, members, seen = [], [], set() + for mapping in namespaces: + members.append((mapping, tuple(mapping.items()))) + for value in mapping.values(): + candidates = [value] + if type(value) is type: + candidates.extend(value.__dict__.values()) + if value.__module__ in (__name__, 'json.decoder', 'json.encoder', 'subprocess'): + members.append((value.__dict__, tuple(value.__dict__.items()))) + for function in candidates: + if type(function) is not FunctionType or id(function) in seen: + continue + seen.add(id(function)) + records.append((function, function.__code__, function.__globals__, function.__builtins__, + function.__defaults__, function.__kwdefaults__, function.__closure__, + tuple(function.__dict__.items()), + () if function.__kwdefaults__ is None else tuple(function.__kwdefaults__.items()), + () if function.__closure__ is None else tuple((c, c.cell_contents) for c in function.__closure__))) + data = tuple((name, _canonical(namespace[name])) for name in + ('_PAIR_SCHEMA', '_MANIFEST_SCHEMA', '_GUARD_SCHEMA', '_PUBLICATION_SCHEMA', + '_ENGINE_PINS', '_OTHER_SOURCE_PINS', '_ENV', '_EVIDENCE_NAMES') if name in namespace) + return tuple(records), tuple(members), data + + + +def _current_graph(graph): + records, members, data = graph + for mapping, rows in members: + # The capture itself is assigned once after this snapshot. + expected = dict(rows) + for name, value in rows: + _need(mapping.get(name, _MISSING) is value, 'G12-N04: captured namespace member changed: ' + name) + extra = set(mapping) - set(expected) + _need(not extra or mapping is globals() and extra == {'_INITIAL_GRAPH'}, + 'G12-N04: captured namespace census changed') + for name, expected in data: + _need(_canonical(globals()[name]) == expected, 'G12-N04: source-owned schema constant changed') + for f, code, namespace, builtin, defaults, kw, cells, attrs, kws, contents in records: + _need(f.__code__ is code and f.__globals__ is namespace and f.__builtins__ is builtin and + f.__defaults__ is defaults and f.__kwdefaults__ is kw and f.__closure__ is cells and + len(f.__dict__) == len(attrs), 'G12-N04: captured function graph changed') + for name, value in attrs: + _need(f.__dict__.get(name, _MISSING) is value, 'G12-N04: function attributes changed') + if kw is not None: + _need(len(kw) == len(kws), 'G12-N04: keyword-default census changed') + for name, value in kws: + _need(kw.get(name, _MISSING) is value, 'G12-N04: keyword defaults changed') + for cell, value in contents: + _need(cell.cell_contents is value, 'G12-N04: captured closure changed') + + + +_PAIR_SCHEMA = {'common_constants': {'authority_source_sha256': 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10', + 'extra_target': [0, 2, 1], + 'h': 25, + 'literal_original_type': 'bool', + 'original_driver_sha256': '0d976d2eb6b845f20d4a3396591a806f966688b88693cd6a5f8a0c9e48925e36', + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-envelope-v1', + 'scope': 'Actual original N22 literal and P07 common remainder observations only; ' + 'no original PROFILE_ANCHOR_PASS, FULL_PASS, native qualification or G12 ' + 'approval.', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'common_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'original_driver_sha256', + 'authority_source_sha256', + 'original_scientific_pins', + 'h', + 'extra_target', + 'literal_original_type', + 'literal_original_value', + 'remaining_original_case_count', + 'common_payload_sha256', + 'common_payload_hex', + 'scope'], + 'complement_receipt_exact_fields': ['calls', 'canonical_stream_bytes', 'sha256', 'schema'], + 'diagnostic_constants': {'complement_suffix_limit': 'Only cumulative original start/end receipts; no ' + 'digest subtraction or suffix-stream claim.', + 'completion': 'Exact source-owned intentional marker followed by original ' + 'finally, exact observer restoration, both cold2 checks and ' + 'original source/output custody.', + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-diagnostics-v1', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'diagnostic_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'common_payload_sha256', + 'prefix_end', + 'suffix_start', + 'cli_end', + 'ordered_rank_suffix_hex', + 'complement_suffix_limit', + 'phases', + 'completion'], + 'diagnostic_snapshot_exact_fields': ['rank_event_count', + 'ordered_rank_events_hex', + 'complement_receipt', + 'native_binding', + 'cache_binding'], + 'phase_exact_names': ['input_custody', + 'engine_custody', + 'fresh_root_copy', + 'fresh_engine_copy', + 'cold_engine_import', + 'cold_complex_module_load', + 'cold_certify_import', + 'cold_prepare_import', + 'side_construction', + 'checks_initialization', + 'compile_roles', + 'verify_map', + 'verify_labels', + 'verify_role_frames', + 'original_upstream_verify_sources', + 'full_log_integer_bounds', + 'original_serializable', + 'complete_original_cli']} + + +_MANIFEST_SCHEMA = {'accounting_exact_fields': ['clock', + 'parent_entry_ns', + 'preseal_end_ns', + 'parent_preseal_wall_ns', + 'parent_self_user_seconds', + 'parent_self_system_seconds', + 'parent_children_user_seconds', + 'parent_children_system_seconds', + 'parent_lifetime_max_rss_kib', + 'guard_usage', + 'guard_runner_wall_seconds', + 'categories', + 'complete_tail_accounting_required', + 'unmeasured_final_tail'], + 'cleanup_exact_fields': ['operating_premises', + 'owned_generations', + 'observed_groups', + 'remaining', + 'current_children', + 'known_streams_closed', + 'known_pidfds_closed', + 'io_unknown', + 'lease_identity', + 'science_directory_identity', + 'observations_record'], + 'custody_exact_fields': ['retained_directory', + 'retained_directory_identity', + 'retained_file_mode', + 'created_after_known_cleanup', + 'source_selection_required', + 'known_close_policy'], + 'exact_top_level_fields': ['schema', + 'invocation', + 'selected_sources', + 'workload', + 'launch', + 'terminal', + 'guard', + 'cleanup', + 'pair', + 'retained_evidence', + 'custody', + 'accounting', + 'scope'], + 'guard_exact_fields': ['start', + 'receipt', + 'start_fields', + 'receipt_fields', + 'stdout', + 'stderr', + 'usage'], + 'invocation_exact_fields': ['stage', + 'job', + 'label', + 'stage_sha256', + 'jobs_sha256', + 'launch_selection_sha256'], + 'launch_exact_fields': ['parent_pid', + 'parent_start_ticks', + 'guard_pid', + 'guard_start_ticks', + 'guard_pgid', + 'guard_sid', + 'parent_guard_argv', + 'guard_root_argv', + 'adapter_producer_argv', + 'cwd', + 'environment', + 'flags', + 'launch_record'], + 'pair_exact_fields': ['common', 'diagnostics', 'common_payload_sha256'], + 'retained_evidence_exact_keys': ['guard_START', + 'guard_receipt', + 'guard_stdout', + 'guard_stderr', + 'guard_usage', + 'parent_launch', + 'parent_outer_stdout', + 'parent_outer_stderr', + 'parent_owned_observations', + 'parent_preseal_accounting'], + 'schema_literal': 'g12-parent-two-export-custody-v2', + 'selected_sources_exact_fields': ['parent', + 'guard', + 'root', + 'provider', + 'adapter', + 'producer', + 'authority', + 'source_pins', + 'reference', + 'engine', + 'runtime_profile', + 'cleanup_leaf_origin'], + 'terminal_exact_fields': ['actual_popen_returncode', + 'wait_completed', + 'parent_stop', + 'primary_error', + 'secondary_errors', + 'guard_receipt_missing'], + 'workload_exact_fields': ['role', + 'h', + 'extra_target', + 'mode', + 'anchor', + 'optimize', + 'original_scientific_pins'], + 'workload_values': {'anchor': None, + 'extra_target': [0, 2, 1], + 'h': 25, + 'mode': 'profile', + 'optimize': 0, + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'role': 'independent-original-uncached'}} + + +_GUARD_SCHEMA = {'START_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label'], + 'receipt_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label', + 'exit', + 'wall_seconds', + 'usage', + 'termination', + 'sampled_process_group_rss_bytes', + 'source_bytes_and_modes_unchanged', + 'stdout_sha256', + 'stdout_bytes', + 'stderr_sha256', + 'stderr_bytes', + 'stdout_final_bytes', + 'stderr_final_bytes', + 'retained_log_bytes_stable', + 'output_cap_observed_at', + 'log_read_chunk_bytes', + 'runner_wall_seconds', + 'runner_user_seconds', + 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', + 'python', + 'platform', + 'status'], + 'required_values': {'exit': 0, + 'log_read_chunk_bytes': 65536, + 'output_cap_observed_at': None, + 'retained_log_bytes_stable': True, + 'source_bytes_and_modes_unchanged': True, + 'status': 'PASS', + 'stderr_bytes': 0, + 'stderr_final_bytes': 0, + 'termination': None}} + + +_PUBLICATION_SCHEMA = {'exact_fields': ['schema', + 'parent_source_sha256', + 'launch_selection_sha256', + 'manifest_path', + 'manifest_sha256', + 'manifest_bytes', + 'manifest_identity', + 'retained_pair_sha256', + 'final_pair_recheck_complete', + 'known_lease_close_completed', + 'primary_error', + 'secondary_errors', + 'measured_through_ns', + 'actual_costs_through_ns', + 'unmeasured_final_tail', + 'complete_cost_qualification'], + 'schema_literal': 'g12-parent-custody-publication-v2'} + + +_COST_CATEGORIES = ('source/stage/plan/authentication and dependency preflight', 'parent invocation setup and known lease operations', 'adapter bootstrap source read/hash/compile/exec and argv/module alias custody/restoration', 'entire independent uncached reference including fresh copies/engine imports/original CLI/trace capture/original checks/finally/restoration/cold2', 'guard launch/time/monitoring/STOP/final original source inventory/usage/raw-log hashing/receipt', 'actual parent wait and known descendant/group/FD cleanup', 'canonical receipt and START joins plus all complete raw evidence retention', 'both exports full reads/hashes/JSON/schema/payload decode/crosslinks and repeated pair checks', 'new parent copies/write/fsync/chmod/close/directory sync/readback', 'manifest schema/write/hash/fsync/close/readback and source-selection publication tail', 'parent failure/secondary-error retention and necessary cleanup after deadline', 'cold consumer complete manifest/pair/publication read/hash/parse/decode/recheck and all retained alias lifetimes') + + +def _validate_manifest(manifest, parent_path, parent_sha): + spec = _MANIFEST_SCHEMA + _fields(manifest, spec['exact_top_level_fields']) + _need(manifest['schema'] == spec['schema_literal'], 'G12-N12: custody schema') + for name in ('invocation', 'selected_sources', 'workload', 'launch', 'terminal', 'guard', + 'cleanup', 'pair', 'custody', 'accounting'): + _fields(manifest[name], spec[name + '_exact_fields']) + _fields(manifest['retained_evidence'], spec['retained_evidence_exact_keys']) + _need(_exact(manifest['workload'], spec['workload_values']), 'G12-N13: fixed workload') + invocation = manifest['invocation'] + _need(invocation['stage'] == 'g12-reference-custody-v1' and invocation['job'] == 'g12-reference' and + type(invocation['label']) is str and bool(invocation['label']) and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in invocation['label']), + 'G12-N13: fixed invocation role') + for name in ('stage_sha256', 'jobs_sha256', 'launch_selection_sha256'): + _need(_digest(invocation[name]), 'G12-N12: invocation digest') + sources = manifest['selected_sources'] + for name, pin in sources.items(): + if name != 'engine': + _source_pin(pin) + for name, expected in (('guard', _GUARD_PIN), ('root', _ROOT_PIN), ('provider', _PROVIDER_PIN), + ('producer', _PRODUCER_PIN), ('authority', _AUTHORITY_PIN)): + _need(sources[name]['sha256'] == expected and sources[name]['mode'] == '0444', + 'G12-N02: selected original source mismatch') + _need(sources['producer']['bytes'] == 70246 and sources['parent']['path'] == parent_path and + sources['parent']['sha256'] == parent_sha, 'G12-N02: selected producer/parent identity') + _need(_exact(sources['engine'], _ENGINE_PINS), 'G12-N02: exact original engine source pins') + for name, expected in _OTHER_SOURCE_PINS.items(): + _need(sources[name]['sha256'] == expected, 'G12-N02: selected original dependency mismatch') + terminal = {'actual_popen_returncode': 0, 'wait_completed': True, 'parent_stop': None, + 'primary_error': None, 'secondary_errors': [], 'guard_receipt_missing': False} + _need(_exact(manifest['terminal'], terminal), 'G12-N06: authenticated terminal data rejects') + cleanup = manifest['cleanup'] + _need(_exact(cleanup['remaining'], []) and _exact(cleanup['current_children'], []) and + cleanup['known_streams_closed'] is True and cleanup['known_pidfds_closed'] is True and + cleanup['io_unknown'] is False and type(cleanup['owned_generations']) is list and + bool(cleanup['owned_generations']) and _exact(cleanup['operating_premises'], _OPERATING_PREMISES), + 'G12-N08: known selected chain custody rejects') + for name in ('parent_pid', 'parent_start_ticks', 'guard_pid', 'guard_start_ticks', 'guard_pgid', 'guard_sid'): + _uint(manifest['launch'][name], True) + label = invocation['label'] + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent_argv, root_argv, producer_argv = _fixed_argv(label, sources) + launch = manifest['launch'] + _need(_exact(launch['parent_guard_argv'], parent_argv) and _exact(launch['guard_root_argv'], root_argv) and + _exact(launch['adapter_producer_argv'], producer_argv) and launch['cwd'] == _R and + _exact(launch['environment'], _ENV) and _exact(launch['flags'], list(_FLAGS)), + 'G12-N03: exact fixed launch/adapter argv') + retained = _R + '/runtime/g12-reference-parent-custody-v1/' + label + custody = manifest['custody'] + _need(custody['retained_directory'] == retained and custody['retained_file_mode'] == '0444' and + custody['created_after_known_cleanup'] is True and custody['source_selection_required'] is True and + custody['known_close_policy'] == 'Any unknown close rejects publication', 'G12-N14: custody ownership') + _fields(custody['retained_directory_identity'], _ID_NAMES) + _need(custody['retained_directory_identity']['full_st_mode'] == stat.S_IFDIR | 0o500, + 'G12-N14: final retained directory mode') + for name in ('common', 'diagnostics'): + pair = manifest['pair'][name] + _fields(pair, ('original', 'retained')) + _file_record(pair['original']) + _file_record(pair['retained']) + filename = 'g12-reference.' + name + '.json' + _need(pair['original']['path'] == science + '/' + filename and + pair['retained']['path'] == retained + '/' + filename and + pair['original']['sha256'] == pair['retained']['sha256'] and + pair['original']['bytes'] == pair['retained']['bytes'] and + pair['retained']['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N13: original/retained complete pair join') + _need(_digest(manifest['pair']['common_payload_sha256']), 'G12-N13: payload pin') + for name, record in manifest['retained_evidence'].items(): + _file_record(record) + _need(record['path'] == retained + '/' + _EVIDENCE_NAMES[name] and + record['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N14: retained raw evidence path/mode') + for name, evidence_name in (('start', 'guard_START'), ('receipt', 'guard_receipt'), + ('stdout', 'guard_stdout'), ('stderr', 'guard_stderr'), ('usage', 'guard_usage')): + _need(_exact(manifest['guard'][name], manifest['retained_evidence'][evidence_name]), + 'G12-N07: guard retained record join') + _need(_exact(launch['launch_record'], manifest['retained_evidence']['parent_launch']) and + _exact(cleanup['observations_record'], manifest['retained_evidence']['parent_owned_observations']), + 'G12-N08: parent observation record join') + account = manifest['accounting'] + _need(account['clock'] == 'monotonic_ns' and account['complete_tail_accounting_required'] is True and + _exact(account['categories'], list(_COST_CATEGORIES)), 'G12-N15: full cost categories/tail') + for name in ('parent_entry_ns', 'preseal_end_ns', 'parent_preseal_wall_ns'): + _uint(account[name]) + _need(account['preseal_end_ns'] >= account['parent_entry_ns'] and + account['parent_preseal_wall_ns'] == account['preseal_end_ns'] - account['parent_entry_ns'], + 'G12-N15: actual parent clock endpoints') + for name in ('parent_self_user_seconds', 'parent_self_system_seconds', 'parent_children_user_seconds', + 'parent_children_system_seconds', 'parent_lifetime_max_rss_kib', 'guard_runner_wall_seconds'): + _number(account[name]) + _need(account['unmeasured_final_tail'] is None, 'G12-N15: unmeasured tail must stay explicitly unknown') + _need(_exact(account['guard_usage'], manifest['guard']['receipt_fields']['usage']) and + _exact(account['guard_runner_wall_seconds'], manifest['guard']['receipt_fields']['runner_wall_seconds']), + 'G12-N15: actual guard cost join') + _need(manifest['scope'] == _SCOPE, 'G12-N18: custody scope cannot become scientific approval') + + +def _fixed_argv(label, sources): + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent = ['/usr/bin/python3.12', *_FLAGS, _R + '/run_guarded_v3.py', + 'g12-reference-custody-v1', 'g12-reference', label] + root = ['/usr/bin/python3.12', *_FLAGS, stage + '/integration/full_driver.py', + '--root-sha256', _ROOT_PIN, '--provider', stage + '/integration/probe_binding_v3.py', + _PROVIDER_PIN, '--driver', stage + '/integration/g12_reference_adapter_v1.py', + sources['adapter']['sha256'], '--integration', stage + '/integration', '--', + '--output', science, '--lanes', 'g12-reference'] + producer = [stage + '/baseline/full_driver.py', '--frozen-root', stage + '/baseline/frozen', + '--reference', stage + '/baseline/reference/certificates/complex-network.json', + '--mode', 'profile', '--output', science] + return parent, root, producer + + +def _validate_publication(publication, manifest, manifest_record): + _fields(publication, _PUBLICATION_SCHEMA['exact_fields']) + _need(publication['schema'] == _PUBLICATION_SCHEMA['schema_literal'] and + publication['parent_source_sha256'] == manifest['selected_sources']['parent']['sha256'] and + publication['launch_selection_sha256'] == manifest['invocation']['launch_selection_sha256'] and + publication['manifest_path'] == manifest_record['path'] and + publication['manifest_sha256'] == manifest_record['sha256'] and + publication['manifest_bytes'] == manifest_record['bytes'] and + _exact(publication['manifest_identity'], manifest_record['identity']) and + _exact(publication['retained_pair_sha256'], {name: manifest['pair'][name]['retained']['sha256'] + for name in ('common', 'diagnostics')}) and + publication['final_pair_recheck_complete'] is True and publication['known_lease_close_completed'] is True and + publication['primary_error'] is None and _exact(publication['secondary_errors'], []) and + publication['complete_cost_qualification'] is False and + _exact(publication['unmeasured_final_tail'], manifest['accounting']['unmeasured_final_tail']), + 'G12-N15: exact publication/manifest/final-tail join') + _uint(publication['measured_through_ns']) + _need(publication['measured_through_ns'] >= manifest['accounting']['preseal_end_ns'], + 'G12-N15: publication clock precedes preseal') + costs = publication['actual_costs_through_ns'] + _fields(costs, ('entry_ns', 'through_ns', 'wall_ns', 'self_user_seconds', 'self_system_seconds', + 'children_user_seconds', 'children_system_seconds', 'lifetime_max_rss_kib')) + for name in ('entry_ns', 'through_ns', 'wall_ns'): + _uint(costs[name]) + _need(costs['entry_ns'] == manifest['accounting']['parent_entry_ns'] and + costs['through_ns'] == publication['measured_through_ns'] and + costs['wall_ns'] == costs['through_ns'] - costs['entry_ns'], 'G12-N15: publication actual clock join') + for name in ('self_user_seconds', 'self_system_seconds', 'children_user_seconds', + 'children_system_seconds', 'lifetime_max_rss_kib'): + _number(costs[name]) + + +def _source_code_shape(code): + _need(type(code) is CodeType, 'G12-N04: exact code type') + def constant(value): + kind = type(value) + if value is None or value is Ellipsis: + return ('singleton', value is Ellipsis) + if kind in (int, bool, str, bytes): + return (kind.__name__, value) + if kind is float: + return ('float', value.hex()) + if kind is tuple: + return ('tuple', tuple(constant(item) for item in value)) + if kind is frozenset: + return ('frozenset', tuple(sorted(constant(item) for item in value))) + if kind is CodeType: + return ('code', _source_code_shape(value)) + raise RuntimeError('G12-N04: unsupported source code constant') + return tuple(constant(value) for value in ( + code.co_argcount, code.co_posonlyargcount, code.co_kwonlyargcount, + code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, + code.co_names, code.co_varnames, code.co_freevars, code.co_cellvars, + code.co_exceptiontable, code.co_linetable, code.co_firstlineno, + code.co_filename, code.co_name, code.co_qualname, code.co_consts)) + + +_R = '/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028' + + +_ENGINE_PINS = {'compare_side_verifier.py': '6e507bb0c7e00d090a60289fddb6c55e90c946d0850c42c3c5e3e15c27604a68', + 'finite_controls.py': 'df989a831aac43cc1af95169dad8c64a7548760e6e1f96976da996703f2c8f7a', + 'native_backend.py': 'e473c38245c3668715b5a78dfe980b2fe3ed0d0c9b8c97c666fbae6ecf1fffd5', + 'native_gf2.c': 'e9c3c9194a08718bd1575c1cf08c6c6772d3b644c2e274c25a84a1f9249d06cc', + 'profile_side_verifier.py': '9c994378171c20a91539418d93cb8387e1daa93465d6862beefea90e12999c2a', + 'source/complex_circuit.py': 'd623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + 'source/complex_network.py': '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b'} + + +_OTHER_SOURCE_PINS = {'cleanup_leaf_origin': '7b3304eaf4884e3029df5095e2b0950c18d1544ad21431a07c033b85e53bd4f7', + 'reference': '1f763d95c7ff163aa71d13cd82784f16665be8afb21f75e76941e2119562098f', + 'runtime_profile': 'ad0ec2aea01b83f97bdeafd9e9208360127fee870d024d353879b5ed99237109', + 'source_pins': '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7'} + + +_OPERATING_PREMISES = ('Selected fixed scientific sources, adapter and ordinary profile branch do not fork/spawn threads, ' + 'daemonize, pass writable descriptors to outsiders, or enlist external writers. Trusted ' + 'OS/loader/interpreter/stdlib and cooperating same-user parent launch domain exclude unrelated writer ' + 'interference. This is an explicit finite source/operating premise, not established merely by a clean /proc ' + 'snapshot.') + + +_SCOPE = ('Fixed source-data custody only. No G12/P02/full-positive/native/performance/scientific admission; no ' + 'universal writers theorem.') + + +_FLAGS = ('-S', '-s', '-P', '-B') + + +_ENV = {'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', + 'PATH': '/usr/bin:/bin', + 'PYTHONDONTWRITEBYTECODE': '1', + 'PYTHONHASHSEED': '0', + 'TZ': 'UTC'} + + +_EVIDENCE_NAMES = {'guard_START': 'guard-START.json', + 'guard_receipt': 'guard-receipt.json', + 'guard_stderr': 'guard-stderr.txt', + 'guard_stdout': 'guard-stdout.txt', + 'guard_usage': 'guard-usage.json', + 'parent_launch': 'parent-LAUNCH.json', + 'parent_outer_stderr': 'parent-outer-stderr.txt', + 'parent_outer_stdout': 'parent-outer-stdout.txt', + 'parent_owned_observations': 'parent-owned-observations.json', + 'parent_preseal_accounting': 'parent-preseal-accounting.json'} + + + +def _proc(pid): + # Derived from original supervisor proc; PermissionError is never absence. + descriptor, primary, secondaries, result = None, None, _RawG12Errors(), None + try: + descriptor = os.open('/proc/' + str(pid) + '/stat', os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + raw = os.read(descriptor, 8193) + _need(len(raw) <= 8192 and os.read(descriptor, 1) == b'', 'G12-N08: process-stat finite bound') + end = raw.rfind(b') ') + _need(end >= 0 and raw.split(b' ', 1)[0] == str(pid).encode('ascii'), 'G12-N08: process-stat PID') + fields = raw[end + 2:].split() + _need(len(fields) >= 22 and fields[0] in (b'R', b'S', b'D', b'Z', b'T', b't', b'X', b'x', b'I', b'K', b'W', b'P'), + 'G12-N08: process-stat shape/state') + result = {'pid': pid, 'ppid': int(fields[1]), 'pgid': int(fields[2]), 'sid': int(fields[3]), + 'start_ticks': int(fields[19]), 'state': fields[0].decode('ascii'), + 'rss_bytes': int(fields[21]) * os.sysconf('SC_PAGE_SIZE')} + for key in ('pid', 'ppid', 'pgid', 'sid', 'start_ticks', 'rss_bytes'): + _uint(result[key], key in ('pid', 'start_ticks')) + except (FileNotFoundError, ProcessLookupError): + result = None + except BaseException as error: + primary = error, error.__traceback__ + if descriptor is not None: + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + return result + + +def _census(): + rows = {} + with os.scandir('/proc') as entries: + for entry in entries: + if entry.name.isdecimal(): + _need(len(rows) < 65536, 'G12-N08: finite process census bound') + row = _proc(int(entry.name)) + if row is not None: + rows[row['pid']] = row + return rows + + +def _children(): + return [row for row in _census().values() if row['ppid'] == os.getpid()] + + +class _KnownG12Chain: + """Scoped generation/pidfd observation only; never universal writer proof.""" + def __init__(self): + _need(not _children(), 'G12-N08: initial parent child domain must be empty') + _need(os.listdir('/proc/self/task') == [str(os.getpid())], 'G12-N08: single initial parent task') + self.rows, self.fds, self.groups, self.observations = {}, {}, set(), [] + self.parent_pid = os.getpid() + self.parent_group = os.getpgrp() + self.closed = False + self.unknown = False + + def add(self, row): + key = row['pid'], row['start_ticks'] + if key in self.rows: + _need(self.rows[key]['pid'] == row['pid'], 'G12-N08: owned generation identity') + if row['pgid'] != self.parent_group: + self.groups.add((row['pgid'], row['sid'])) + return + _need(row['pid'] != self.parent_pid and len(self.rows) < 128, 'G12-N08: fixed owned process bound') + descriptor = os.pidfd_open(row['pid'], 0) + # A failed/ambiguous adoption rejects; never treat it as known closure. + self.fds[key] = descriptor + current = _proc(row['pid']) + _need(current is not None and (current['pid'], current['start_ticks']) == key, + 'G12-N08: process generation changed during pidfd adoption') + self.rows[key] = dict(current) + if current['pgid'] != self.parent_group: + self.groups.add((current['pgid'], current['sid'])) + + def observe(self): + _need(not self.closed, 'G12-N08: closed observation domain') + rows = _census() + known = {pid for pid, start in self.rows if pid in rows and rows[pid]['start_ticks'] == start} + for pid in known: + self.add(rows[pid]) + changed = True + while changed: + changed = False + for pid, row in rows.items(): + if pid not in known and (row['ppid'] == self.parent_pid or row['ppid'] in known): + self.add(row) + known.add(pid) + changed = True + occupied = [row for row in rows.values() if (row['pgid'], row['sid']) in self.groups] + current = [rows[pid] for pid in known] + _need(len(self.observations) < 4096, 'G12-N08: finite observation retention') + self.observations.append({'monotonic_ns': time.monotonic_ns(), 'current': current, 'occupied_groups': occupied}) + return rows, current, occupied + + def stop_known(self): + self.observe() + for key, descriptor in self.fds.items(): + current = _proc(key[0]) + if current is not None: + _need((current['pid'], current['start_ticks']) == key, 'G12-N08: generation ambiguity before signal') + if current['state'] != 'Z': + try: + signal.pidfd_send_signal(descriptor, signal.SIGKILL, None, 0) + except ProcessLookupError: + pass + + def release_known_pidfds(self, secondaries): + """Release known descriptors after the final process-disposal attempt. + + A close error leaves custody unknown. Retire numeric ownership before + close so that an ambiguous close cannot cause a later blind FD retry. + This does not establish process exit or turn unknown cleanup into success. + """ + for key, descriptor in tuple(self.fds.items()): + del self.fds[key] + try: + os.close(descriptor) + except BaseException as error: + self.unknown = True + secondaries.append((error, error.__traceback__)) + + def finish(self, process, deadline, failed): + _need(type(deadline) is int, 'G12-N08: selected paid cleanup deadline') + current, occupied = [], [] + while True: + if failed: + self.stop_known() + if process is not None: + process.poll() + _, current, occupied = self.observe() + if not current and not occupied and not _children(): + break + if not failed or time.monotonic_ns() >= deadline: + raise RuntimeError('G12-N08: selected-chain cleanup UNKNOWN') + time.sleep(0.01) + primary, secondaries = None, _RawG12Errors() + self.release_known_pidfds(secondaries) + self.closed = not self.fds and not self.unknown + _raise_preserved(primary, secondaries) + return {'operating_premises': _OPERATING_PREMISES, + 'owned_generations': list(self.rows.values()), + 'observed_groups': [{'pgid': g, 'sid': s} for g, s in sorted(self.groups)], + 'remaining': [], 'current_children': [], 'known_streams_closed': False, + 'known_pidfds_closed': self.closed, 'io_unknown': self.unknown, + 'lease_identity': None, 'science_directory_identity': None, + 'observations_record': None} + + +def _trusted_parent_launch(): + _need(sys.executable == '/usr/bin/python3.12' and sys.flags.optimize == 0 and + sys.flags.no_site == sys.flags.no_user_site == sys.flags.dont_write_bytecode == 1 and + sys.flags.safe_path and sys.flags.ignore_environment == sys.flags.isolated == sys.flags.hash_randomization == 0, + 'G12-N02: original clean parent interpreter flags') + _need(dict(os.environ) == _ENV and tuple(sys.path) == + ('/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload'), + 'G12-N02: original clean environment/search path') + _need(sys.gettrace() is None and sys.getprofile() is None, 'G12-N04: no parent tracing callbacks') + + +def _exclusive_directory(path): + parent, name = _path(path).rsplit('/', 1) + primary, secondaries, result = None, _RawG12Errors(), None + fds, rows = _directory_chain(parent) + try: + os.mkdir(name, 0o700, dir_fd=fds[-1]) + descriptor = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=fds[-1]) + fds.append(descriptor) + current = os.fstat(descriptor) + _need(current.st_mode == stat.S_IFDIR | 0o700, 'G12-N14: new parent directory mode') + rows.append((fds[-2], name, descriptor, _directory_key(current))) + _check_chain(rows) + result = fds, rows + except BaseException as error: + primary = error, error.__traceback__ + if primary is not None: + for descriptor in reversed(fds): + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + return result + + +def _write_fd(descriptor, raw): + _need(type(raw) is bytes, 'G12-N14: exact retained byte copy') + offset, hasher = 0, hashlib.sha256() + while offset < len(raw): + block = raw[offset:offset + _CHUNK] + written = os.write(descriptor, block) + _need(type(written) is int and 0 < written <= len(block), 'G12-N14: complete copy write progress') + hasher.update(block[:written]) + offset += written + _need(offset == len(raw) and hasher.hexdigest() == hashlib.sha256(raw).hexdigest(), + 'G12-N14: complete copied byte digest') + os.fsync(descriptor) + os.fchmod(descriptor, 0o444) + os.fsync(descriptor) + + +def _copy_file(directory, name, raw): + fds, rows = directory + primary, secondaries = None, _RawG12Errors() + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=fds[-1]) + try: + _write_fd(descriptor, raw) + _check_chain(rows) + except BaseException as error: + primary = error, error.__traceback__ + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + os.fsync(fds[-1]) + + +def _actual_costs(entry_ns, own_start, children_start): + through = time.monotonic_ns() + own, children = resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN) + return {'entry_ns': entry_ns, 'through_ns': through, 'wall_ns': through - entry_ns, + 'self_user_seconds': own.ru_utime - own_start.ru_utime, + 'self_system_seconds': own.ru_stime - own_start.ru_stime, + 'children_user_seconds': children.ru_utime - children_start.ru_utime, + 'children_system_seconds': children.ru_stime - children_start.ru_stime, + 'lifetime_max_rss_kib': own.ru_maxrss} + + +def run_g12_reference(): + """P01: one source-private invocation; accepts no caller completion data.""" + configured = G12_REFERENCE_LAUNCH_SELECTION + _need(type(configured) is dict, 'G12-N01: exact immutable launch source literal remains None') + _need(type(_INITIAL_PARENT_SOURCE_PIN) is dict and configured['source_pins']['parent'] is None, + 'G12-N02: independent initial external parent source pin; no self-hash literal') + _source_pin(_INITIAL_PARENT_SOURCE_PIN) + configured_bytes = _canonical(configured) + selection = dict(configured) + selection['source_pins'] = dict(configured['source_pins']) + selection['source_pins']['parent'] = dict(_INITIAL_PARENT_SOURCE_PIN) + # Actual launch remains closed. The independently reviewed source scope + # correction requires the complete symbolic bill, not a new financial API. + entry_ns = time.monotonic_ns() + own_start, children_start = resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN) + selection_bytes = _canonical(selection) + selection_sha = hashlib.sha256(selection_bytes).hexdigest() + parent_graph = _capture_graph(globals()) + phase, stage_data, stage_record, jobs_record, phase_record = None, None, None, None, None + source_records, originals, evidence, retained_records = {}, {}, {}, {} + parent_identity = _proc(os.getpid()) + process, chain, lease, lease_identity = None, None, None, None + lease_closed, attempted, wait_completed = False, False, False + outer = {} + observation, retained, science_directory, run_directory = None, None, None, None + primary, secondaries, parent_stop = None, _RawG12Errors(), None + cleanup, common, diagnostic, common_payload = None, None, None, None + start, receipt, usage, launch = None, None, None, None + manifest, manifest_record, publication_record = None, None, None + reserved = {} + candidate_pin = None + + def current(): + _need(G12_REFERENCE_LAUNCH_SELECTION is configured and _canonical(configured) == configured_bytes and + _canonical(selection) == selection_bytes and _exact(selection['source_pins']['parent'], _INITIAL_PARENT_SOURCE_PIN), + 'G12-N16: selected launch source changed') + _current_graph(parent_graph) + _need(_proc(os.getpid())['start_ticks'] == parent_identity['start_ticks'], 'G12-N08: parent generation') + _need(os.listdir('/proc/self/task') == [str(os.getpid())], 'G12-N08: parent thread domain changed') + if lease is not None and not lease_closed: + _need(_identity(os.fstat(lease)) == lease_identity and os.fstat(lease).st_nlink == 1, + 'G12-N08: actual parent lease identity changed') + for domain in (observation, retained, science_directory, run_directory): + if domain is not None: + _check_chain(domain[1]) + + def _g12_preflight_and_claim(): + """P02: exact source/phase/namespace gate; separate parent-queue lease.""" + nonlocal phase, stage_data, stage_record, jobs_record, phase_record, chain + nonlocal lease, lease_identity, observation + _fields(selection, ('schema', 'stage', 'job', 'label', 'stage_sha256', 'jobs_sha256', 'source_pins', + 'phase_pin', 'body_deadline_ns', 'retention_tail_allowance_ns', + 'parent_observation_directory', 'parent_retained_directory')) + _need(selection['schema'] == 'g12-one-reference-launch-selection-v1' and + selection['stage'] == 'g12-reference-custody-v1' and selection['job'] == 'g12-reference', + 'G12-N02: fixed G12 launch role') + label = selection['label'] + _need(type(label) is str and bool(label) and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in label), + 'G12-N03: fixed selected guard label') + _need(selection['parent_observation_directory'] == _R + '/runtime/g12-reference-parent-observation-v1/' + label and + selection['parent_retained_directory'] == _R + '/runtime/g12-reference-parent-custody-v1/' + label, + 'G12-N02: fixed parent namespace') + _uint(selection['body_deadline_ns'], True) + _uint(selection['retention_tail_allowance_ns'], True) + _need(selection['body_deadline_ns'] > entry_ns, 'G12-N05: no remaining complete body allowance') + _trusted_parent_launch() + sources = selection['source_pins'] + _fields(sources, _MANIFEST_SCHEMA['selected_sources_exact_fields']) + _need(_exact(sources['engine'], _ENGINE_PINS), 'G12-N02: exact seven original engine pins') + for name, pin in sources.items(): + if name == 'engine': + continue + _source_pin(pin) + observed, raw = _read_file(pin['path'], max(pin['bytes'], 1), int(pin['mode'], 8)) + _need(observed['sha256'] == pin['sha256'] and observed['bytes'] == pin['bytes'], + 'G12-N02: selected source bytes/modes') + source_records[name] = observed, raw + _need(sources['parent']['path'] == __file__, 'G12-N04: external parent source selection') + for name, expected in (('guard', _GUARD_PIN), ('root', _ROOT_PIN), ('provider', _PROVIDER_PIN), + ('producer', _PRODUCER_PIN), ('authority', _AUTHORITY_PIN)): + _need(sources[name]['sha256'] == expected and sources[name]['mode'] == '0444', 'G12-N02: original source pin') + for name, expected in _OTHER_SOURCE_PINS.items(): + _need(sources[name]['sha256'] == expected, 'G12-N02: original dependency pin') + _source_pin(selection['phase_pin']) + phase_record, phase_raw = _read_file(selection['phase_pin']['path'], _META_CAP, + int(selection['phase_pin']['mode'], 8)) + _need(selection['phase_pin']['path'] == _R + '/control/EXECUTION-PHASE.json' and + phase_record['sha256'] == selection['phase_pin']['sha256'] and + phase_record['bytes'] == selection['phase_pin']['bytes'], 'G12-N05: original phase identity') + phase = _json(phase_raw, _META_CAP) + _need(type(phase['aggregate_cap_seconds']) is int and phase['aggregate_cap_seconds'] in (600, 2400), + 'G12-N05: original unchanged aggregate cap') + stage = _R + '/stages/g12-reference-custody-v1' + stage_record, stage_raw = _read_file(stage + '/STAGE.json', _META_CAP, 0o444) + jobs_record, jobs_raw = _read_file(stage + '/JOBS.json', _META_CAP, 0o444) + _need(stage_record['sha256'] == selection['stage_sha256'] and + jobs_record['sha256'] == selection['jobs_sha256'], 'G12-N02: independently selected stage/jobs') + stage_data = _json(stage_raw, _META_CAP) + jobs = _json(jobs_raw, _META_CAP) + _need(_exact(jobs, {'g12-reference': {'bootstrap': {'driver': 'integration/g12_reference_adapter_v1.py', + 'provider': 'integration/probe_binding_v3.py'}, 'lanes': 'g12-reference', 'optimized': False}}), + 'G12-N03: exact only-job bootstrap/lanes/no-finite/no-optimization') + _need(stage_data['runner_sha256'] == _GUARD_PIN, 'G12-N02: original runner source') + for relative, row in stage_data['files'].items(): + _need(type(relative) is str and all(x not in ('', '.', '..') for x in relative.split('/')) and + not relative.startswith('/'), 'G12-N02: stage closure relative path') + _fields(row, ('sha256', 'mode')) + _need(type(row['mode']) is int, 'G12-N02: original source mode') + observed, _ = _read_file(stage + '/' + relative, 16777216, row['mode']) + _need(observed['sha256'] == row['sha256'], 'G12-N02: complete staged source closure') + # Exact census rejects undeclared files/directories/symlinks, including an + # alternate staged authority. Walk source paths only; no runtime payloads. + actual = set() + for path, dirs, files in os.walk(stage, followlinks=False): + for name in dirs: + _need(stat.S_ISDIR(os.lstat(path + '/' + name).st_mode), 'G12-N02: stage directory symlink') + for name in files: + full = path + '/' + name + _need(stat.S_ISREG(os.lstat(full).st_mode), 'G12-N02: stage nonregular source') + relative = full[len(stage) + 1:] + if relative != 'STAGE.json': + actual.add(relative) + _need(actual == set(stage_data['files']), 'G12-N02: exact staged closure census') + for name, pin in sources.items(): + if name not in ('engine', 'parent', 'guard', 'cleanup_leaf_origin'): + _need(pin['path'].startswith(stage + '/'), 'G12-N02: selected source outside new stage') + relative = pin['path'][len(stage) + 1:] + _need(stage_data['files'][relative] == {'sha256': pin['sha256'], 'mode': int(pin['mode'], 8)}, + 'G12-N02: selected source/stage binding') + chain = _KnownG12Chain() + for path in (_R + '/runtime/runs/' + label, selection['parent_observation_directory'], + selection['parent_retained_directory']): + parent, name = path.rsplit('/', 1) + fds, rows = _directory_chain(parent) + try: + try: + os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise RuntimeError('G12-N05: prior output/evidence/custody path exists') + _check_chain(rows) + finally: + _finally_close_known(fds, secondaries) + # Separate from the original guard's science.lock. No contention wait. + lock_path = _R + '/runtime/parent-queue.lock' + parent_fds, parent_rows = _directory_chain(_R + '/runtime') + try: + lease = os.open('parent-queue.lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=parent_fds[-1]) + info = os.fstat(lease) + _need(stat.S_ISREG(info.st_mode) and info.st_nlink == 1, 'G12-N08: parent lease type/link') + lease_identity = _identity(info) + fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB) + _check_chain(parent_rows) + _need(_identity(os.stat('parent-queue.lock', dir_fd=parent_fds[-1], follow_symlinks=False)) == lease_identity, + 'G12-N08: parent lease name identity') + finally: + _finally_close_known(parent_fds, secondaries) + observation = _exclusive_directory(selection['parent_observation_directory']) + current() + + def _g12_launch_once(): + """P03: retain the actual Popen, actual descriptors and generation.""" + nonlocal process, attempted, launch + _need(not attempted and process is None, 'G12-N06: no second launch attempt') + current() + parent_argv, root_argv, producer_argv = _fixed_argv(selection['label'], selection['source_pins']) + for name in ('stdout', 'stderr'): + outer[name] = os.open('outer-' + name + '.txt', + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=observation[0][-1]) + attempted = True + process = subprocess.Popen(parent_argv, cwd=_R, env=dict(_ENV), stdout=outer['stdout'], + stderr=outer['stderr'], close_fds=True, start_new_session=True) + _need(type(process) is subprocess.Popen and type(process.pid) is int and process.pid > 0, + 'G12-N06: actual Popen object/PID') + row = _proc(process.pid) + _need(row is not None and row['ppid'] == os.getpid() and + row['pgid'] == process.pid and row['sid'] == process.pid, 'G12-N06: actual new guard generation/session') + chain.add(row) + launch = {'parent_pid': parent_identity['pid'], 'parent_start_ticks': parent_identity['start_ticks'], + 'guard_pid': row['pid'], 'guard_start_ticks': row['start_ticks'], + 'guard_pgid': row['pgid'], 'guard_sid': row['sid'], 'parent_guard_argv': parent_argv, + 'guard_root_argv': root_argv, 'adapter_producer_argv': producer_argv, + 'cwd': _R, 'environment': dict(_ENV), 'flags': list(_FLAGS), 'launch_record': None} + raw = _canonical({'schema': 'g12-parent-actual-launch-v1', 'selection_sha256': selection_sha, 'source_selection': selection, + 'launch': {k: v for k, v in launch.items() if k != 'launch_record'}}) + b'\n' + _copy_file(observation, 'LAUNCH.json', raw) + evidence['parent_launch'] = _read_file(selection['parent_observation_directory'] + '/LAUNCH.json', _META_CAP, 0o444) + + def _g12_observe_wait_and_close(): + """P04: actual wait and scoped known-chain closure; no status substitute.""" + nonlocal wait_completed, cleanup, parent_stop + _need(process is not None and type(process) is subprocess.Popen, 'G12-N06: missing retained actual Popen') + while process.poll() is None: + _, children, occupied = chain.observe() + if time.monotonic_ns() >= selection['body_deadline_ns']: + parent_stop = 'selected_complete_body_deadline' + elif sum(row['rss_bytes'] for row in children) > 1073741824: + parent_stop = 'selected_known_chain_rss_cap' + elif resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024 > 1073741824: + parent_stop = 'parent_lifetime_rss_cap' + elif any(os.fstat(descriptor).st_size > _LOG_CAP for descriptor in outer.values()): + parent_stop = 'parent_outer_log_cap' + if parent_stop: + raise RuntimeError('G12-N06: parent STOP: ' + parent_stop) + current() + time.sleep(0.05) + code = process.wait() + wait_completed = True + _need(type(code) is int and code == 0 and type(process.returncode) is int and process.returncode == 0, + 'G12-N06: actual guard wait returncode') + cleanup = chain.finish(process, selection['body_deadline_ns'] + selection['retention_tail_allowance_ns'], False) + for name, descriptor in tuple(outer.items()): + os.fsync(descriptor) + os.close(descriptor) + del outer[name] + cleanup['known_streams_closed'] = not outer + cleanup['lease_identity'] = lease_identity + _need(parent_stop is None and cleanup['known_pidfds_closed'] and not cleanup['io_unknown'], + 'G12-N08: complete known closes') + current() + + def _g12_join_original_guard_evidence(): + """P05: retain complete canonical originals; never reconstruct receipt.""" + nonlocal start, receipt, usage, science_directory, run_directory + run = _R + '/runtime/runs/' + selection['label'] + run_directory = _directory_chain(run) + science_directory = _directory_chain(run + '/science') + cleanup['science_directory_identity'] = _identity(os.fstat(science_directory[0][-1])) + fixed = {'guard_START': ('START.json', _META_CAP), 'guard_receipt': ('receipt.json', _META_CAP), + 'guard_stdout': ('stdout.txt', _LOG_CAP), 'guard_stderr': ('stderr.txt', _LOG_CAP), + 'guard_usage': ('usage.json', 16384)} + for name, (filename, cap) in fixed.items(): + evidence[name] = _read_file(run + '/' + filename, cap) + for name in ('stdout', 'stderr'): + evidence['parent_outer_' + name] = _read_file(selection['parent_observation_directory'] + '/outer-' + name + '.txt', _LOG_CAP) + start = _json(evidence['guard_START'][1], _META_CAP) + receipt = _json(evidence['guard_receipt'][1], _META_CAP) + usage = _json(evidence['guard_usage'][1], 16384) + invocation = {'job': selection['job'], 'label': selection['label'], 'stage_sha256': selection['stage_sha256']} + _validate_guard(start, receipt, usage, evidence['guard_stdout'][1], evidence['guard_stderr'][1], + launch['guard_root_argv'], invocation, selection['source_pins'], selection['phase_pin']['sha256']) + fraction, _ = _read_file('/usr/lib/python3.12/fractions.py', 1048576) + _need(start['fractions_sha256'] == fraction['sha256'], 'G12-N07: original fractions source join') + _need(_exact(_json(evidence['parent_outer_stdout'][1], _LOG_CAP), receipt) and + evidence['parent_outer_stderr'][1] == b'', 'G12-N07: actual outer stdout/empty stderr') + current() + + def _g12_collect_complete_pair(): + """P06: complete original common AND diagnostics, followed by joint recheck.""" + nonlocal common, diagnostic, common_payload + _need(wait_completed and process.returncode == 0 and cleanup is not None and receipt is not None, + 'G12-N10: original successful owner/receipt join must precede pair') + science = _R + '/runtime/runs/' + selection['label'] + '/science' + for name in ('common', 'diagnostics'): + originals[name] = _read_file(science + '/g12-reference.' + name + '.json', _PAIR_CAP) + common, diagnostic, common_payload = _validate_pair(originals['common'][1], originals['diagnostics'][1]) + for name in ('common', 'diagnostics'): + _need(_read_file(originals[name][0]['path'], _PAIR_CAP) == originals[name], 'G12-N11: original joint pair changed') + current() + + def _g12_retain_parent_pair_and_evidence(): + """P07: fresh parent directory only after all selected writers are known closed.""" + nonlocal retained + _need(not _children() and cleanup['known_pidfds_closed'] and cleanup['known_streams_closed'], + 'G12-N08: no retained directory until known selected cleanup') + current() + retained = _exclusive_directory(selection['parent_retained_directory']) + for name in ('common', 'diagnostics'): + filename = 'g12-reference.' + name + '.json' + _copy_file(retained, filename, originals[name][1]) + record, raw = _read_file(selection['parent_retained_directory'] + '/' + filename, _PAIR_CAP, 0o444) + _need(raw == originals[name][1] and record['sha256'] == originals[name][0]['sha256'], 'G12-N14: complete retained pair readback') + retained_records[name] = record + observation_raw = _canonical({'schema': 'g12-known-chain-observations-v1', 'cleanup': cleanup, + 'observations': chain.observations}) + b'\n' + _copy_file(observation, 'owned-observations.json', observation_raw) + evidence['parent_owned_observations'] = _read_file(selection['parent_observation_directory'] + '/owned-observations.json', _META_CAP, 0o444) + costs = _actual_costs(entry_ns, own_start, children_start) + accounting_raw = _canonical(costs) + b'\n' + _copy_file(observation, 'preseal-accounting.json', accounting_raw) + evidence['parent_preseal_accounting'] = _read_file(selection['parent_observation_directory'] + '/preseal-accounting.json', _META_CAP, 0o444) + for name in _MANIFEST_SCHEMA['retained_evidence_exact_keys']: + _copy_file(retained, _EVIDENCE_NAMES[name], evidence[name][1]) + record, raw = _read_file(selection['parent_retained_directory'] + '/' + _EVIDENCE_NAMES[name], + max(len(evidence[name][1]), 1), 0o444) + _need(raw == evidence[name][1], 'G12-N14: raw evidence copy differs') + retained_records[name] = record + # Reserve BOTH metadata names before recording final directory identity. + # Existing FD writes/file chmod do not change parent directory entries. + for name in ('manifest.json', 'publication.json'): + reserved[name] = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=retained[0][-1]) + os.fsync(retained[0][-1]) + current() + + def _g12_seal_once(): + """P08: private actual owner seal; returns only a candidate for later adoption.""" + nonlocal manifest, manifest_record, publication_record, candidate_pin, lease_closed + _need(process is not None and type(process) is subprocess.Popen and process.returncode == 0 and + wait_completed and primary is None and not secondaries and parent_stop is None and not _children() and + not outer and not chain.fds and not chain.unknown, 'G12-N08: actual owner final conjunction') + current() + for name, original in originals.items(): + _need(_read_file(original[0]['path'], _PAIR_CAP) == original, 'G12-N11: original pair final drift') + _need(_read_file(retained_records[name]['path'], _PAIR_CAP, 0o444)[0] == retained_records[name], + 'G12-N14: retained pair final drift') + for name, (record, raw) in source_records.items(): + _need(_read_file(record['path'], max(record['bytes'], 1), record['identity']['full_st_mode'] & 0o7777) == (record, raw), + 'G12-N02: complete selected source drift') + for record, raw in evidence.values(): + _need(_read_file(record['path'], max(record['bytes'], 1), record['identity']['full_st_mode'] & 0o7777) == (record, raw), + 'G12-N07: final complete original raw evidence drift') + for record in (stage_record, jobs_record, phase_record): + _need(_read_file(record['path'], _META_CAP, record['identity']['full_st_mode'] & 0o7777)[0] == record, + 'G12-N02: stage/jobs/phase final identity drift') + os.fchmod(retained[0][-1], 0o500) + # Update exactly our owned mode transition, retaining dev/inode binding. + parent, name, descriptor, old = retained[1][-1] + final_dir_info = os.fstat(descriptor) + _need((final_dir_info.st_dev, final_dir_info.st_ino) == old[:2], 'G12-N14: retained directory owner transition') + retained[1][-1] = (parent, name, descriptor, _directory_key(final_dir_info)) + os.fsync(descriptor) + directory_identity = _identity(final_dir_info) + costs = _actual_costs(entry_ns, own_start, children_start) + account = {'clock': 'monotonic_ns', 'parent_entry_ns': entry_ns, + 'preseal_end_ns': costs['through_ns'], 'parent_preseal_wall_ns': costs['wall_ns'], + 'parent_self_user_seconds': costs['self_user_seconds'], 'parent_self_system_seconds': costs['self_system_seconds'], + 'parent_children_user_seconds': costs['children_user_seconds'], 'parent_children_system_seconds': costs['children_system_seconds'], + 'parent_lifetime_max_rss_kib': costs['lifetime_max_rss_kib'], 'guard_usage': usage, + 'guard_runner_wall_seconds': receipt['runner_wall_seconds'], 'categories': list(_COST_CATEGORIES), + 'complete_tail_accounting_required': True, 'unmeasured_final_tail': None} + launch['launch_record'] = retained_records['parent_launch'] + cleanup['observations_record'] = retained_records['parent_owned_observations'] + manifest = {'schema': 'g12-parent-two-export-custody-v2', + 'invocation': {'stage': selection['stage'], 'job': selection['job'], 'label': selection['label'], + 'stage_sha256': selection['stage_sha256'], 'jobs_sha256': selection['jobs_sha256'], + 'launch_selection_sha256': selection_sha}, + 'selected_sources': selection['source_pins'], 'workload': _MANIFEST_SCHEMA['workload_values'], + 'launch': launch, 'terminal': {'actual_popen_returncode': process.returncode, 'wait_completed': wait_completed, + 'parent_stop': parent_stop, 'primary_error': None, 'secondary_errors': [], 'guard_receipt_missing': False}, + 'guard': {'start': retained_records['guard_START'], 'receipt': retained_records['guard_receipt'], + 'start_fields': start, 'receipt_fields': receipt, 'stdout': retained_records['guard_stdout'], + 'stderr': retained_records['guard_stderr'], 'usage': retained_records['guard_usage']}, + 'cleanup': cleanup, + 'pair': {name: {'original': originals[name][0], 'retained': retained_records[name]} for name in ('common', 'diagnostics')}, + 'retained_evidence': {name: retained_records[name] for name in _MANIFEST_SCHEMA['retained_evidence_exact_keys']}, + 'custody': {'retained_directory': selection['parent_retained_directory'], 'retained_directory_identity': directory_identity, + 'retained_file_mode': '0444', 'created_after_known_cleanup': True, 'source_selection_required': True, + 'known_close_policy': 'Any unknown close rejects publication'}, 'accounting': account, 'scope': _SCOPE} + manifest['pair']['common_payload_sha256'] = common['common_payload_sha256'] + _validate_manifest(manifest, selection['source_pins']['parent']['path'], selection['source_pins']['parent']['sha256']) + raw = _canonical(manifest) + b'\n' + _need(len(raw) <= _META_CAP, 'G12-N14: manifest finite metadata cap') + _write_fd(reserved['manifest.json'], raw) + os.close(reserved['manifest.json']) + del reserved['manifest.json'] + os.fsync(retained[0][-1]) + manifest_record, reread = _read_file(selection['parent_retained_directory'] + '/manifest.json', _META_CAP, 0o444) + _need(reread == raw, 'G12-N14: complete manifest readback') + current() + _need(not _children(), 'G12-N08: unexpected child at final lease close') + fcntl.flock(lease, fcntl.LOCK_UN) + os.close(lease) + lease_closed = True + costs = _actual_costs(entry_ns, own_start, children_start) + publication = {'schema': 'g12-parent-custody-publication-v2', + 'parent_source_sha256': selection['source_pins']['parent']['sha256'], 'launch_selection_sha256': selection_sha, + 'manifest_path': manifest_record['path'], 'manifest_sha256': manifest_record['sha256'], + 'manifest_bytes': manifest_record['bytes'], 'manifest_identity': manifest_record['identity'], + 'retained_pair_sha256': {name: retained_records[name]['sha256'] for name in ('common', 'diagnostics')}, + 'final_pair_recheck_complete': True, 'known_lease_close_completed': lease_closed, + 'primary_error': None, 'secondary_errors': [], 'measured_through_ns': costs['through_ns'], + 'actual_costs_through_ns': costs, 'unmeasured_final_tail': None, + 'complete_cost_qualification': False} + _validate_publication(publication, manifest, manifest_record) + publication_raw = _canonical(publication) + b'\n' + _need(len(publication_raw) <= _META_CAP, 'G12-N15: publication metadata cap') + _write_fd(reserved['publication.json'], publication_raw) + os.close(reserved['publication.json']) + del reserved['publication.json'] + os.fsync(retained[0][-1]) + publication_record, observed = _read_file(selection['parent_retained_directory'] + '/publication.json', _META_CAP, 0o444) + _need(observed == publication_raw and _identity(os.fstat(retained[0][-1])) == directory_identity, + 'G12-N15: final publication readback/directory identity') + current() + # This candidate is not a source selection or completed enclosing invoice. + candidate_pin = (manifest_record['path'], manifest_record['sha256'], manifest_record['bytes'], + _handoff_identity_tuple(manifest_record), selection['source_pins']['parent']['path'], + selection['source_pins']['parent']['sha256'], publication_record['path'], + publication_record['sha256'], publication_record['bytes']) + + def _g12_finish_failure(): + """P09: always preserve actual first failure, known cleanup and partial originals.""" + nonlocal lease_closed + # Every later error is retained separately; no receipt or PASS replacement. + if chain is not None and not chain.closed: + try: + chain.finish(process, selection['body_deadline_ns'] + selection['retention_tail_allowance_ns'], True) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + finally: + if chain.fds: + # No further process-disposal retry follows this point. + # Retained pidfds must still be attempted when observation + # or signalling failed; closed processes remain unproved. + chain.unknown = True + chain.release_known_pidfds(secondaries) + for name, descriptor in tuple(outer.items()): + try: + os.close(descriptor) + del outer[name] + except BaseException as error: + secondaries.append((error, error.__traceback__)) + for name, descriptor in tuple(reserved.items()): + try: + os.close(descriptor) + del reserved[name] + except BaseException as error: + secondaries.append((error, error.__traceback__)) + if lease is not None and not lease_closed: + try: + os.close(lease) + lease_closed = True + except BaseException as error: + secondaries.append((error, error.__traceback__)) + # Failure-tail raw records are never advertised as canonical guard data. + if observation is not None and (primary is not None or secondaries): + try: + failures = {'schema': 'g12-parent-failed-attempt-v1', 'attempted': attempted, + 'actual_returncode': None if process is None else process.returncode, + 'primary': None if primary is None else repr(primary[0]), + 'ordered_secondaries': [repr(item[0]) for item in secondaries], + 'known_cleanup': 'UNKNOWN' if chain is None or not chain.closed else 'KNOWN_SELECTED_CHAIN_ONLY', + 'actual_costs_through_prewrite': _actual_costs(entry_ns, own_start, children_start), + 'enclosing_full_failure_tail_required': True} + _copy_file(observation, 'FAILED-ATTEMPT.json', _canonical(failures) + b'\n') + except BaseException as error: + secondaries.append((error, error.__traceback__)) + for domain in (science_directory, run_directory, retained, observation): + if domain is not None: + for descriptor in reversed(domain[0]): + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + + try: + _g12_preflight_and_claim() + _g12_launch_once() + _g12_observe_wait_and_close() + _g12_join_original_guard_evidence() + _g12_collect_complete_pair() + _g12_retain_parent_pair_and_evidence() + _g12_seal_once() + except BaseException as error: + primary = error, error.__traceback__ + try: + _g12_finish_failure() + except BaseException as error: + # Preserve primary even if a secondary bookkeeping append itself failed. + if primary is None: + primary = error, error.__traceback__ + else: + try: + primary[0].add_note('P09 bookkeeping failure: ' + repr(error)) + except BaseException: + pass + _raise_preserved(primary, secondaries) + _need(candidate_pin is not None and lease_closed and not outer and not reserved, + 'G12-N15: final tail incomplete; manifest remains unselected') + return candidate_pin diff --git a/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py b/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py new file mode 100644 index 0000000000..3a7bbb09eb --- /dev/null +++ b/research/h25-passive-guard-primary-preservation/snapshot/c05-v03-pro-workitems-20261103T0435Z/guard/verify_guard_fake_v1.py @@ -0,0 +1,382 @@ +"""UNEXECUTED by author. Parent-only, separately admitted AST-definition fakes. + +Only complete named definitions are extracted. No candidate import/top-level/CLI +or source-window execution. All candidate system/process/path/signal boundaries +are inert tokens. Fourteen independent scope-review cases; RED witnesses retained. +""" +import ast +import builtins +import hashlib +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +ROOT=Path(__file__).resolve().parent +SOURCE=ROOT/'parent_passive_supervisor_v4.py' +HELPER=ROOT/'passive_image_candidates_v3.py' +PREDECESSOR=ROOT.parents[1]/'c05-v03-completion-20261102T055710Z'/'driver-libexec-property-slice-v1'/'repair-v2'/'parent_passive_supervisor_v3.py' +OLD_HELPER=PREDECESSOR.parent/'passive_image_candidates_v2.py' +REFERENCE=ROOT/'reference-g12-parent-v3.py.txt' +SOURCE_SHA='355c10dbe920373e25a3ebb080d771c9388abe6f5e5e8db5b69b1cea8cd025cd' +HELPER_SHA='8ba6eaaa43916cb38002c50231c6309afd0e1b5e58dc72658be10f4ab6c4626d' +PREDECESSOR_SHA='2a9581442b8cd6802f45c7ae4c523165fa19297f7fe1d8c616c74f65da9b628a' +REFERENCE_SHA='8b6b196c50d616e12d7966ea35bf6d65fd799a18556f362a7e17d2b1273a8bb8' +NAMES=('Stop','need','digest','RawErrors','acquire','close_slot','read_pin','Guard','bind_window','main') +ROWS=[] + +def require(ok, message): + if not ok: raise RuntimeError(message) + +def capture(operation): + try: operation() + except BaseException as error: return error + raise RuntimeError('expected raw exception was not raised') + +def bound_text(path, expected): + raw=path.read_bytes() + require(hashlib.sha256(raw).hexdigest()==expected,'source identity mismatch') + return raw.decode('utf-8') + +def definitions(text, names, namespace): + tree=ast.parse(text) + found={node.name:node for node in tree.body if isinstance(node,(ast.FunctionDef,ast.ClassDef))} + require(all(name in found for name in names),'complete definition absent') + # Only named complete definitions; imports, global assignments, __main__, + # decorators and defaults with ambient calls are never run accidentally. + selected=[found[name] for name in names] + for node in selected: + require(not node.decorator_list,'unreviewed decorator') + env={'__builtins__':builtins.__dict__} + env.update(namespace) + module=ast.Module(body=selected,type_ignores=[]) + exec(compile(module,'','exec'),env) + return env + +class Poison(Exception): + calls=0 + def __str__(self): + type(self).calls+=1 + raise RuntimeError('formatter must not be called') + def __repr__(self): + type(self).calls+=1 + raise RuntimeError('formatter must not be called') + +class TokenPath: + def __init__(self,value): self.value=str(value) + def __truediv__(self,value): return TokenPath(self.value+'/'+str(value)) + def __str__(self): return self.value + def is_absolute(self): return True + def stat(self): return SimpleNamespace(st_size=3) + def read_text(self): return '' if self.value.endswith('children') else '0 1' + def read_bytes(self): raise RuntimeError('fake path byte read not admitted') + def mkdir(self,**kwargs): raise RuntimeError('fake main must fail before directory creation') + +class TokenOS: + O_RDONLY=0; O_CLOEXEC=1; O_NOFOLLOW=2; O_WRONLY=4; O_CREAT=8; O_EXCL=16; O_RDWR=32 + def __init__(self): + self.events=[]; self.next=500; self.blocks={}; self.close_errors={} + self.fstat_error=None; self.write_plan=[]; self.close_observer=None + def open(self,path,*args): + self.next+=1; token=self.next + self.events.append(('open',token)); self.blocks[token]=[b'abc',b''] + return token + def fstat(self,fd): + if self.fstat_error is not None: raise self.fstat_error + return SimpleNamespace(st_dev=1,st_ino=fd,st_mode=0,st_size=3, + st_mtime_ns=0,st_ctime_ns=0,st_uid=1000) + def read(self,fd,count): + self.events.append(('read',fd)) + blocks=self.blocks.get(fd) + return blocks.pop(0) if blocks else b'' + def write(self,fd,data): + self.events.append(('write',fd)) + if self.write_plan: + item=self.write_plan.pop(0) + if isinstance(item,BaseException): raise item + return item + return len(data) + def close(self,fd): + if self.close_observer is not None: self.close_observer(fd) + self.events.append(('close',fd)) + if fd in self.close_errors: raise self.close_errors[fd] + def lseek(self,*args): return 0 + def pidfd_open(self,pid,flags): + self.events.append(('pidfd',pid)); return 1500+pid + def set_blocking(self,*args): return None + def killpg(self,*args): self.events.append(('killpg',args[0])) + def getpid(self): return 1 + def getuid(self): return 1000 + def sysconf(self,name): return 4096 + +class Clock: + def __init__(self): self.value=0 + def monotonic(self): self.value+=0.001; return self.value + def time(self): return 0 + +class TokenStream: + def __init__(self,fixture,label,fd): self.fixture=fixture; self.label=label; self.fd=fd + def fileno(self): return self.fd + def close(self): + self.fixture.events.append(('stream-close',self.label)) + error=self.fixture.stream_errors.get(self.label) + if error is not None: raise error + +class TokenProcess: + pid=3; returncode=0 + def __init__(self,fixture): + self.fixture=fixture + self.stdout=TokenStream(fixture,'stdout',701) + self.stderr=TokenStream(fixture,'stderr',702) + def wait(self,**kwargs): return 0 + def poll(self): return 0 + +class TokenSelector: + def __init__(self,fixture): + self.fixture=fixture; fixture.selector_count+=1; self.ordinal=fixture.selector_count; self.rows={} + def register(self,obj,event,data=None): + fd=obj if type(obj) is int else obj.fileno() + self.rows[fd]=SimpleNamespace(fd=fd,fileobj=obj,data=data) + def unregister(self,obj): + fd=obj if type(obj) is int else obj.fileno() + del self.rows[fd] + def get_map(self): return self.rows + def select(self,timeout): return [(row,1) for row in list(self.rows.values())] + def close(self): + self.fixture.events.append(('selector-close',self.ordinal)) + error=self.fixture.selector_errors.get(self.ordinal) + if error is not None: raise error + +class Fixture: + def __init__(self): + self.os=TokenOS(); self.clock=Clock(); self.events=[]; self.stream_errors={}; self.selector_errors={} + self.selector_count=0; self.spawn_error=None; self.disarm_error=None; self.json_calls=0 + def popen(self,*args,**kwargs): + self.events.append(('launch',1)) + if self.spawn_error is not None: raise self.spawn_error + return TokenProcess(self) + def setitimer(self,which,seconds): + self.events.append(('timer',seconds)) + if seconds==0 and self.disarm_error is not None: raise self.disarm_error + def namespace(self): + def forbidden(*args,**kwargs): raise RuntimeError('unreviewed fake boundary called') + def loads(raw): + self.json_calls+=1 + raise RuntimeError('main must fail before JSON body') + parser=SimpleNamespace(add_argument=lambda *a,**k:None, + parse_args=lambda:SimpleNamespace(admission='/FAKE/admission', + admission_sha256=hashlib.sha256(b'abc').hexdigest(),token='token123')) + signals=SimpleNamespace(SIGTERM=15,SIGKILL=9,SIGALRM=14,SIGINT=2,ITIMER_REAL=0, + signal=lambda *a:None,setitimer=self.setitimer, + pidfd_send_signal=lambda *a:None) + return {'os':self.os,'time':self.clock,'hashlib':hashlib, + 'Path':TokenPath,'HERE':TokenPath('/FAKE'),'__file__':'/FAKE/guard.py', + 'RAW_ERROR_CAP':4096,'KNOWN_CAP':128,'RAW_CAP':786432,'TOTAL_CAP':1048576,'RESERVE':262144, + 'MEM_CAP':1073741824,'TOOLS':{'/FAKE/tool':(3,hashlib.sha256(b'abc').hexdigest())}, + 'TARGET':'/FAKE/target','TARGET_SHA':'0'*64,'HELPER':TokenPath('/FAKE/helper'), + 'HELPER_SHA':HELPER_SHA,'HELPER_SIZE':12983,'OPERATION_ADMITTED':True, + 'stat':SimpleNamespace(S_ISREG=lambda mode:True), + 'selectors':SimpleNamespace(DefaultSelector=lambda:TokenSelector(self),EVENT_READ=1), + 'subprocess':SimpleNamespace(Popen=self.popen,DEVNULL=-3,PIPE=-1, + TimeoutExpired=type('TokenTimeout',(Exception,),{})), + 'signal':signals,'proc_identity':lambda pid:(10+pid,1,pid,pid), + 'argparse':SimpleNamespace(ArgumentParser=lambda:parser),'re':__import__('re'), + 'fcntl':SimpleNamespace(flock=forbidden,LOCK_EX=1,LOCK_NB=2), + 'json':SimpleNamespace(loads=loads,dumps=forbidden),'sys':SimpleNamespace(stderr=forbidden)} + def env(self,text): return definitions(text,NAMES,self.namespace()) + def guard(self,env): return env['Guard'](TokenPath('/FAKE/out'),0,0) + + +def raw_frame(error, raw_type): + tb=error.__traceback__ + while tb is not None: + candidate=tb.tb_frame.f_locals.get('errors') + if isinstance(candidate,raw_type): return candidate + tb=tb.tb_next + raise RuntimeError('raw state absent from actual caller traceback') + +def body_failure(errors,error): + try: raise error + except BaseException as caught: errors.capture(caught) + return errors.first[1] + +def record(name,details=None): ROWS.append({'id':name,'status':'PASS_FAKE_ONLY','details':details}) + +def main(): + source=bound_text(SOURCE,SOURCE_SHA) + predecessor=bound_text(PREDECESSOR,PREDECESSOR_SHA) + helper=bound_text(HELPER,HELPER_SHA) + reference=bound_text(REFERENCE,REFERENCE_SHA) + old_helper=OLD_HELPER.read_text() + require(helper.split('def main():',1)[0]==old_helper.split('def main():',1)[0], + 'pure locator body/data drift; prior23 controls cannot transfer') + + # F01 independent original oracle, exact read_pin plus selected locator main. + f=Fixture(); env=f.env(source); errors=env['RawErrors'](); owner=[None,None] + A=ValueError('A'); B=OSError('B'); f.os.fstat_error=A; f.os.close_errors[501]=B + first_tb_seen=[None] + def observe_root(fd): first_tb_seen[0]=errors.first[1] + f.os.close_observer=observe_root + actual=capture(lambda:env['read_pin']('/FAKE/input',3,'ignored',errors,owner)) + require(actual is A and errors.first[0] is A and errors.first[1] is not None and + errors.first[1] is first_tb_seen[0] and errors.errors[0] is B and + f.os.events.count(('close',501))==1,'F01 read identity/order') + oldf=Fixture(); oldf.os.fstat_error=A; oldf.os.close_errors[501]=B + oldenv=definitions(predecessor,('Stop','need','digest','read_pin'),oldf.namespace()) + require(capture(lambda:oldenv['read_pin']('/FAKE/input',3,'ignored')) is B,'F01 predecessor negative lost') + helperf=Fixture(); helperf.os.fstat_error=A; helperf.os.close_errors[501]=B + helper_ns=helperf.namespace(); helper_ns.update(EXPECTED_PATH='/FAKE/input',EXPECTED_SIZE=3, + EXPECTED_SHA='ignored',MAX_INPUT=3) + helperenv=definitions(helper,('Stop','need','main'),helper_ns) + helper_actual=capture(helperenv['main']) + require(helper_actual is A,'F01 actual helper main replaced A') + helper_tb=helper_actual.__traceback__ + while helper_tb is not None and 'secondary' not in helper_tb.tb_frame.f_locals: helper_tb=helper_tb.tb_next + require(helper_tb is not None and helper_tb.tb_frame.f_locals['secondary'][0] is B, + 'F01 helper raw secondary absent') + record('F01') + + # F02 write progress + ENOSPC A / EIO B; old actual write still refutes it. + f=Fixture(); env=f.env(source); g=f.guard(env); A=OSError('ENOSPC'); B=OSError('EIO') + f.os.write_plan=[1,A]; f.os.close_errors[501]=B + require(capture(lambda:g.write('part',b'abc',raw=True)) is A and g.total==1 and g.raw==1 and + g.errors.errors[0] is B and f.os.events.count(('close',501))==1,'F02 write primary/progress') + oldf=Fixture(); oldenv=definitions(predecessor,('Stop','need','Guard'),oldf.namespace()) + oldg=oldenv['Guard'](TokenPath('/FAKE/out'),0,0); oldf.os.write_plan=[1,A]; oldf.os.close_errors[501]=B + require(capture(lambda:oldg.write('part',b'abc',raw=True)) is B,'F02 predecessor negative lost') + record('F02') + + # F03/F04 complete actual cleanup; raw B,C identities, no formatted oracle. + for prior in (True,False): + f=Fixture(); env=f.env(source); g=f.guard(env); p=TokenProcess(f) + g.child=p; g.process_owner[:]=['KNOWN',p] + g.pipe_owners[0][:]=['KNOWN',p.stdout]; g.pipe_owners[1][:]=['KNOWN',p.stderr] + A=ValueError('A'); B=OSError('B'); C=OSError('C'); f.stream_errors={'stdout':B,'stderr':C} + first_tb=body_failure(g.errors,A) if prior else None + actual=capture(g.cleanup) + require(actual is (A if prior else B),'F03/F04 same outward primary') + expected=[B,C] if prior else [C] + require([g.errors.errors[i] for i in range(g.errors.count)]==expected, + 'F03/F04 ordered raw secondaries') + require(f.events.count(('stream-close','stdout'))==1 and f.events.count(('stream-close','stderr'))==1, + 'F03/F04 independent closes') + if prior: require(g.errors.first[1] is first_tb,'F03 first traceback root replaced') + capture(g.cleanup) + require(f.events.count(('stream-close','stdout'))==1,'F03/F04 blind retry') + require(capture(lambda:g.run('next',['/FAKE/tool'],1,(3,3))) is (A if prior else B) + and not any(row[0]=='launch' for row in f.events),'F03/F04 later launch') + record('F03' if prior else 'F04') + + # F05 complete run: selector B must not skip independent toolfd C. + f=Fixture(); env=f.env(source); g=f.guard(env); B=OSError('selector B'); C=OSError('tool C') + f.selector_errors[1]=B; f.os.close_errors[501]=C + actual=capture(lambda:g.run('one',['/FAKE/tool'],1,(3,3))) + require(actual is B and g.errors.errors[0] is C and f.os.events.count(('close',501))==1, + 'F05 independent selector/tool close') + require(not g.steps[0]['capture_complete'],'F05 capture incorrectly successful') + record('F05') + + # F06 actual register: returned pidfd rooted before failing observation. + f=Fixture(); env=f.env(source); g=f.guard(env); A=PermissionError('post-return A') + def denied(pid): raise A + env['proc_identity']=denied + require(capture(lambda:g.register(3,13)) is A and g.pidfd_owners[0][0]=='RETIRED' and + f.os.events.count(('close',1503))==1,'F06 returned-owner gap') + record('F06') + + # F07 complete actual run with ambiguous Popen pre-return failure. + f=Fixture(); env=f.env(source); g=f.guard(env); A=OSError('uncertain spawn'); f.spawn_error=A + require(capture(lambda:g.run('one',['/FAKE/tool'],1,(3,3))) is A,'F07 outward identity') + require(g.process_owner[0]=='PENDING' and g.process_owner[1] is None and g.errors.quarantined, + 'F07 pending owner erased') + require(not any(row[0]=='write' for row in f.os.events) and f.os.events.count(('close',501))==1, + 'F07 new I/O or missing known close') + require(capture(lambda:g.run('two',['/FAKE/tool'],1,(3,3))) is A and + len([row for row in f.events if row[0]=='launch'])==1,'F07 subsequent launch') + record('F07') + + # F08 numeric owner removed before ambiguous close; no retry. + f=Fixture(); env=f.env(source); errors=env['RawErrors'](); slot=['KNOWN',901]; B=OSError('ambiguous') + f.os.close_errors[901]=B + def retired(fd): require(slot[0]=='RETIRED' and slot[1] is None,'F08 numeric owner still live') + f.os.close_observer=retired + env['close_slot'](slot,errors); env['close_slot'](slot,errors) + require(errors.first[0] is B and errors.quarantined and f.os.events==[('close',901)],'F08 retry') + record('F08') + + # F09 actual selected main over exact read_pin; str/repr poison never called. + f=Fixture(); env=f.env(source); A=Poison(); f.os.fstat_error=A; Poison.calls=0 + actual=capture(env['main']); errors=raw_frame(actual,env['RawErrors']) + require(actual is A and errors.first[0] is A and errors.first[1] is not None and + Poison.calls==0 and f.json_calls==0,'F09 raw main/formatting boundary') + record('F09') + + # F10 cleanup-only fault on successful complete actual run, no next payload. + f=Fixture(); env=f.env(source); g=f.guard(env); B=OSError('pipe close'); f.stream_errors['stdout']=B + require(capture(lambda:g.run('one',['/FAKE/tool'],1,(3,3))) is B and + not g.steps[0]['capture_complete'],'F10 cleanup-only success') + require(capture(lambda:g.run('two',['/FAKE/tool'],1,(3,3))) is B and + len([row for row in f.events if row[0]=='launch'])==1 and + len([row for row in f.os.events if row[0]=='open'])==1,'F10 next launch/publication') + record('F10') + + # F11 source-fixed known-owner bound and conservative independent-site count. + f=Fixture(); env=f.env(source); g=f.guard(env); errors=g.errors + require(len(g.pidfd_owners)==128 and len(errors.errors)==4096,'F11 preallocated capacity') + arrays=(errors.first,errors.errors,errors.tracebacks) + first_tb=body_failure(errors,ValueError('A')); B=OSError('B') + maximum=2*128+2*128+2+1+1+128+2+2+6+20 + require(maximum<4096,'F11 finite close-site bound exceeds cells') + for unused in range(maximum): errors.capture(B) + require(errors.first is arrays[0] and errors.errors is arrays[1] and errors.tracebacks is arrays[2] + and errors.first[1] is first_tb and errors.count==maximum,'F11 raw storage changed') + record('F11',{'conditional_secondary_site_bound':maximum,'capacity':4096, + 'no_universal_allocation_claim':True}) + + # F12 exact6346 helper RED ledger/snapshot/recording counterexamples. + red=[] + for fault in ('ledger','snapshot','record'): + attempts=[]; A=ValueError('A'); allocation=MemoryError('retained stronger witness') + B=OSError('close B') + def close(fd): attempts.append(fd); raise B + env=definitions(reference,('_RawG12Errors','_close_known_descriptors','_finally_close_known'), + {'os':SimpleNamespace(close=close),'sys':sys}) + def bad(*args): raise allocation + if fault=='ledger': env['_RawG12Errors']=bad + elif fault=='snapshot': env['tuple']=bad + else: env['_RawG12Errors']=type('BadRecorder',(),{'append':lambda self,value:bad()}) + def witness(): + try: raise A + finally: env['_finally_close_known']([901,902,903],[]) + actual=capture(witness) + require(actual is allocation and actual is not A and attempts==([903] if fault=='record' else []), + 'F12 retained RED counterexample changed') + red.append({'fault':fault,'status':'RED_RETAINED_STRONGER_CONTRACT','close_attempts':attempts}) + record('F12',red) + + # F13 unfaulted actual read/write/run; no spurious quarantine or credit. + f=Fixture(); env=f.env(source); errors=env['RawErrors'](); owner=[None,None] + result=env['read_pin']('/FAKE/input',3,hashlib.sha256(b'abc').hexdigest(),errors,owner) + require(result[0]==501 and result[1]==b'abc' and owner[0]=='KNOWN','F13 read/owner transfer') + env['close_slot'](owner,errors) + g=f.guard(env); g.write('raw',b'abc',raw=True) + require(g.raw==3 and g.total==3 and g.errors.first[0] is None and not g.errors.quarantined,'F13 write') + f=Fixture(); env=f.env(source); g=f.guard(env) + require(g.run('one',['/FAKE/tool'],1,(3,3))==b'' and g.steps[0]['capture_complete'] and + not g.errors.quarantined,'F13 actual run success baseline') + record('F13') + + # F14 outer actual main itself faults after nested A is protected. No JSON. + f=Fixture(); env=f.env(source); A=ValueError('A'); B=OSError('close B'); C=OSError('outer timer C') + f.os.fstat_error=A; f.os.close_errors[501]=B; f.disarm_error=C + actual=capture(env['main']); errors=raw_frame(actual,env['RawErrors']) + require(actual is A and errors.first[0] is A and errors.errors[0] is B and errors.errors[1] is C + and f.json_calls==0 and len([row for row in f.os.events if row[0]=='open'])==1, + 'F14 outer finalization replaced A or continued publication') + record('F14') + require(len(ROWS)==14 and len({row['id'] for row in ROWS})==14,'fourteen independent cases changed') + print(json.dumps({'status':'PASS_BOUNDED_FAKE_ONLY','cases':ROWS,'source_sha256':SOURCE_SHA, + 'helper_sha256':HELPER_SHA,'actual_operation':False,'original_credit':0, + 'full_C05':False,'full_V03':False,'costs':'OPEN_NOT_ZERO'},sort_keys=True)) + +if __name__=='__main__': main()