From 1dfa341f99800db6d1cc7568387b3b4d44f0f1ec Mon Sep 17 00:00:00 2001 From: Dylan Roy Date: Mon, 21 Sep 2026 12:02:16 -0500 Subject: [PATCH 1/4] Add scoped support-withdrawal pilot and adaptive R17 handoff Owner-authorized operational implementation only. Adds loss-only AND/OR support validation, 36 synthetic tests, read-only legacy inventory, an isolated CI workflow, protocol/work order/reconnaissance, and an AGENTS pointer. Existing scientific graph, frozen sources, registers, other branches and repository settings are unchanged. Technical review and live graph migration remain open. --- .github/workflows/withdrawal-governance.yml | 26 ++ AGENTS.md | 13 + governance/withdrawal/PROTOCOL.md | 153 ++++++++++ governance/withdrawal/RECONNAISSANCE.md | 29 ++ governance/withdrawal/WORK_ORDER.json | 26 ++ governance/withdrawal/examples/after.json | 90 ++++++ governance/withdrawal/examples/before.json | 90 ++++++ governance/withdrawal/examples/ticket.json | 29 ++ tests/test_withdrawal.py | 247 +++++++++++++++++ tools/withdrawal_check.py | 291 ++++++++++++++++++++ 10 files changed, 994 insertions(+) create mode 100644 .github/workflows/withdrawal-governance.yml create mode 100644 governance/withdrawal/PROTOCOL.md create mode 100644 governance/withdrawal/RECONNAISSANCE.md create mode 100644 governance/withdrawal/WORK_ORDER.json create mode 100644 governance/withdrawal/examples/after.json create mode 100644 governance/withdrawal/examples/before.json create mode 100644 governance/withdrawal/examples/ticket.json create mode 100644 tests/test_withdrawal.py create mode 100644 tools/withdrawal_check.py diff --git a/.github/workflows/withdrawal-governance.yml b/.github/workflows/withdrawal-governance.yml new file mode 100644 index 000000000..4884e749f --- /dev/null +++ b/.github/workflows/withdrawal-governance.yml @@ -0,0 +1,26 @@ +name: withdrawal-governance-pilot +on: + push: + pull_request: +permissions: + contents: read +jobs: + loss-only-controls: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + - name: Synthetic negative controls (normal and optimized) + run: | + python3 -m unittest discover -s tests -p test_withdrawal.py -v + python3 -O -m unittest discover -s tests -p test_withdrawal.py -v + - name: Synthetic loss-only transition + run: >- + python3 tools/withdrawal_check.py check + --before governance/withdrawal/examples/before.json + --after governance/withdrawal/examples/after.json + --ticket governance/withdrawal/examples/ticket.json + - name: Read-only research enrolment inventory (not migration) + run: python3 tools/withdrawal_check.py inventory --legacy-graph claims/graph.json diff --git a/AGENTS.md b/AGENTS.md index cf15b999f..2767fe715 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,3 +42,16 @@ whatever its provider or name. Dylan Roy is the single final authority for canonical promotion, external release, permanent deletion and machine-root replacement. + +## Support withdrawal and scheduling — 2026-09-21 operational addendum + +Read [OP-WITHDRAWAL-20260921-v1.0](governance/withdrawal/PROTOCOL.md) before +proposing abandonment, retiring a proof route, changing admissibility or resuming +affected work. Revalidate current R17 Work Events and exact source/head identities; +the historical bridge descriptions above are not a substitute for live records. +Drive delivery folder: `1VfuXdkyIi0VIsmz42WS6ALEhlc2qneM_`. +Closing a workstream is not refuting a claim. Withdrawing a warrant cannot erase +its parent's premises. Preserve alternative proofs and require exact survivor +warrants. The executable checker is an unreviewed loss-only pilot, not a verdict +engine. Existing scientific records are NOT_MIGRATED. Apply the safeguards to new +work; do not bulk-convert historical statuses. Use the existing R17 event log. diff --git a/governance/withdrawal/PROTOCOL.md b/governance/withdrawal/PROTOCOL.md new file mode 100644 index 000000000..973a7d149 --- /dev/null +++ b/governance/withdrawal/PROTOCOL.md @@ -0,0 +1,153 @@ +# OP-WITHDRAWAL-20260921-v1.0 + +**Operational safeguards active under the current owner instruction. Executable +implementation: isolated pilot, unreviewed. Existing scientific records are NOT +MIGRATED. No claim is killed, refuted, restored, discharged or promoted here.** + +## Authority and scope + +Drive remains the governing record. The R17 Work Events tab in GP-REG-032-v1.2 is +the sole claim/disposition log; this directory is an execution/readback mirror, +not another register. R17, frozen-source rules, scientific gates and independent +review requirements remain in force. Current implementation claim: +`CLAIM-WITHDRAWAL-20260921-2d6f8acc`. + +Drive delivery folder: `1VfuXdkyIi0VIsmz42WS6ALEhlc2qneM_`. +Base commit: `28475939319653e149d1a49ca10a6d58b551de7e`. +Isolated branch: `chatgpt/withdrawal-governance-20260921`. +Do not write to, merge, reset or seize another worker's branch from this order. + +The owner requested implementation of the discussed safeguards on 21 September +2026. This authorizes the operational pilot, entry notices, tests and review +handoff. It does not authorize this implementation to decide mathematical truth, +change permissions, publish unrelated material or replace a frozen source. + +## Rules for activity beginning or resuming now + +Read the current Research Home and relevant R17 Work Events before acting. Match +the exact object, source version, hypothesis/measure/domain/quantifiers, active +lease and output head. A stale cached instruction or branch name is not authority. +Use the rules below on new work without relabeling historical rows. A workflow +pause or closed scheduling task is never discharge of its mathematical target. + +1. Separate object kind, source evidential status, present admissibility, + scheduling state and review provenance. HOLD is unresolved; suspension is + protective; invalid proof, refuted contract and closed strategy are different. + Avoid an unqualified KILLED label. Cost, time and an unknown next step justify + scheduling decisions, not claims of falsity or impossibility. +2. A documented material defect can immediately suspend affected use through an + additive, scope-specific event. Preserve the source. Final negative verdicts + require a separate evidence-bound nonauthor review and the existing operator + decision path. Distinct providers do not by themselves prove independence; + record coauthorship, shared evidence and prior exposure. Never invent review. +3. Withdrawal disables whole proof routes. It does not erase their requirements. + Requirements within a route are AND; alternative valid routes are OR. The + parent loses support only if no admissible route remains. Loss of support + does not establish the parent's falsity. For a pure withdrawal, recorded + support after must be a subset of recorded support before. +4. Preserve every node, source, failed route and refuting artifact. Keep the + search terms, exact failed assumptions, explanation and conditions for a + materially different retry. Scheduling shutdown is not a memory deletion. +5. A qualitative survivor needs its own supported statement and quantifiers. + Lost decimal certification proves neither qualitative falsity nor survival. + Reuse existing valid lemma IDs; newly extracted statements require explicit + contracts, dependency lists and warrants. Do not silently change measures, + dimensions, intervals or all-small-radius quantifiers under the same ID. +6. Restoring an old pointer requires revalidation of that exact old route. A + historical predecessor may share the defect. Unknown validity routes to a + named open obligation, not to the previous allegedly good version. +7. Keep dashboard target populations fixed within a withdrawal. Closing two + workstreams must not silently change eight-of-ten scientific completion to + eight-of-eight. A changed reporting basis is a separate explicit event. +8. Freeze the affected graph slice and assess dependency coverage. A checker + cannot find dependencies never entered. PARTIAL/UNASSESSED coverage supports + investigation, not an assertion that all effects have been reconciled. + +## Transition record and publication + +Before a substantive withdrawal, pin: event/object IDs; contract and typed scope; +old/new snapshot digests; reason and exact evidence; author; every changed item; +affected dependents; named surviving routes or unresolved obligations; and review +requirements. Attach this payload to an R17 event. Generate impact views from it. +Do not independently maintain competing status truth in README, lane and graph +files. Preserve the original frozen carrier; use overlays or numbered successors. + +Use PREPARED -> EXECUTED -> RECORDED -> ACCEPTED as distinct publication concepts. +GitHub execution and Drive recording are not an atomic distributed transaction. +Bind the same transition ID, payload digest and exact source/commit identities on +both surfaces; read back both; only then record publication. A missing or mismatched +side is a hold on that transition, not a freeze of unrelated research. Identical +retries reuse an event identity; conflicting retries remain separately visible +for reconciliation. Never rewrite an old receipt to make a retry appear original. +Owner acceptance and scientific review remain separate from implementation/tests. + +## Executable v1 boundary + +`tools/withdrawal_check.py check` validates loss-only candidate snapshots and +explicit scheduling changes. It preserves contracts, scopes, route requirements, +artifact identities and dashboard membership. Support is derived as a least fixed +point of named grounds and proof routes, not from status labels or empty lists. +It reports lost support, surviving witnesses and disabled routes. It has no write +or network capability. JSON unknown fields, unknown versions, duplicate keys, +non-finite values, missing coverage and stale payload bindings fail closed. + +The checker **does not** adjudicate final falsity, accept new evidence, restore a +route, migrate scientific records, authenticate a review or verify Drive/GitHub +receipt references over the network. It will reject these unsupported operations +rather than pretend they are implemented. Its success is STRUCTURALLY_VALID with +scientific_acceptance=false, even for a structurally complete RECORDED payload. +Grounds are externally admitted warrants, not raw numerical run receipts. + +`inventory` is a read-only enrolment aid. It hashes individual source records, +exposes declared dependencies and marks every item NOT_MIGRATED / NOT_ASSESSED. +It does not convert existing depends_on lists into complete proof routes, invent +unconditional grounds, reconcile frozen/current-note statuses or move a gate. + +Synthetic examples carry SYNTHETIC identifiers and placeholder review/artifact +hashes. They are tests, not scientific evidence or authentic review records. + +## Execute and review + +```sh +python -m unittest discover -s tests -p test_withdrawal.py -v +python -O -m unittest discover -s tests -p test_withdrawal.py -v +python tools/withdrawal_check.py check \ + --before governance/withdrawal/examples/before.json \ + --after governance/withdrawal/examples/after.json \ + --ticket governance/withdrawal/examples/ticket.json +python tools/withdrawal_check.py inventory --legacy-graph claims/graph.json +``` + +The isolated workflow runs these commands with read-only repository permissions +and no retained checkout credentials. It does not alter existing protections or +make itself a required branch check. Existing CI is retained. Review the actual +remote run, not merely the presence of a workflow file. + +## Adaptive rollout and acceptance backlog + +Stage 1: entry guidance + versioned operational record + tested isolated pilot. +Stage 2: nonauthor technical review of code, negative controls and the coverage +boundary; disclose exposure and do not claim organizational independence casually. +Stage 3: map one bounded research slice from exact current sources, retaining all +source statuses; review AND/OR routes, typed scope, evidence grade and coverage. +Stage 4: replay before/after transitions in shadow mode, reconcile generated views +and duplicate/conflicting event handling, then obtain explicit scoped acceptance. +Only after that acceptance may an integration branch propose a guarded live +adapter. Broader migration, final-refutation/restoration adapters, automatic +publication and required-check settings remain OPEN, not implied deployments. + +Future improvements use numbered successors, explicit compatibility/migration +rules, regression fixtures and a reconciled R17 event. Unknown versions remain +HOLD. Do not auto-upgrade old records or change old tests to erase a failure. +Rollback disables this pilot's use and restores only revision-checked navigation +pointers; it does not delete its evidence or reactivate withdrawn scientific use. + +## Primary-source reconnaissance + +W3C PROV-DM distinguishes entities, activities, invalidation and derivation: +https://www.w3.org/TR/prov-dm/ . This motivates separation, not mathematical truth. +GitHub recommends immutable action pins and restricted token permissions: +https://docs.github.com/en/actions/reference/security/secure-use and +https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax . +These are established techniques; no architecture novelty is claimed. The local +contribution is the bounded integration and its explicit failure controls. diff --git a/governance/withdrawal/RECONNAISSANCE.md b/governance/withdrawal/RECONNAISSANCE.md new file mode 100644 index 000000000..8b93a2a32 --- /dev/null +++ b/governance/withdrawal/RECONNAISSANCE.md @@ -0,0 +1,29 @@ +# Reconnaissance memo — OP-WITHDRAWAL-20260921 + +Scope: provenance-safe support withdrawal and loss-only dependency validation, +not a scientific theorem or a novelty claim. Inspected on 2026-09-21. + +Primary sources: W3C PROV-DM (https://www.w3.org/TR/prov-dm/), GitHub secure-use +reference (https://docs.github.com/en/actions/reference/security/secure-use), +and GitHub workflow syntax +(https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax). +The official actions/checkout v4.2.2 ref was independently fetched through the +GitHub connector and resolved to 11bd71901bbe5b1630ceea73d27597364c9af683. +This is a verified existing pin, not a claim that v4 is the latest release. + +PROV-DM separates activity termination from entity invalidation and derivation. +That distinction is reused to separate scheduling from support and truth. +GitHub's guidance supports immutable action references, minimal permissions and +avoiding privilege-bearing execution of untrusted contributions. The dedicated +pilot workflow uses contents: read and persist-credentials: false; it neither +changes repository settings nor gives the checker Drive credentials. + +No external source proves the research dependency map complete, supplies the +research-specific verdicts, or makes a model review independent. The implementation +therefore retains source statuses, records coverage as a separate obligation and +marks legacy objects unmigrated. The AND/OR support model and loss monotonicity are +standard reasoning mechanisms; no claim of a new general architecture is made. + +Disposition: proceed with a scoped operational pilot and nonauthor review. Final +refutation, restoration, live graph migration and automatic cross-system commits +are outside v1. Existing frozen-source and scientific gates remain unchanged. diff --git a/governance/withdrawal/WORK_ORDER.json b/governance/withdrawal/WORK_ORDER.json new file mode 100644 index 000000000..032e49985 --- /dev/null +++ b/governance/withdrawal/WORK_ORDER.json @@ -0,0 +1,26 @@ +{ + "order_id": "OP-WITHDRAWAL-WO-20260921-01", + "authorization_basis": "Current direct user instruction, transcribed by the receiving assistant; not a signature or independent review.", + "authorization_text": "@GitHub @Google Drive go ahead and start taking the necessary steps to implement this to where the activity in both of these can adapt and modify as we make these changes", + "authorization_sha256": "cb4c504ddb035a4b458022eb14fcf3b6092b430f4dc990c298c22f40e8307ee9", + "claim_id": "CLAIM-WITHDRAWAL-20260921-2d6f8acc", + "session_id": "CHATGPT-WITHDRAWAL-20260921-2b090452", + "base_commit": "28475939319653e149d1a49ca10a6d58b551de7e", + "branch": "chatgpt/withdrawal-governance-20260921", + "allowed_work": [ + "isolated loss-only validator, tests and workflow", + "new Drive operational addendum and exact reading artifacts", + "guarded Home/router navigation notices", + "append-only R17 event and review request" + ], + "excluded_work": [ + "scientific status changes or source migration", + "frozen/exported-source edits", + "merge or write to another worker branch", + "settings, permissions or visibility changes", + "unattended deployment or new recurring task" + ], + "review_status": "UNREVIEWED", + "scientific_effect": "NONE", + "deployment": "ISOLATED_PILOT" +} diff --git a/governance/withdrawal/examples/after.json b/governance/withdrawal/examples/after.json new file mode 100644 index 000000000..50142aaef --- /dev/null +++ b/governance/withdrawal/examples/after.json @@ -0,0 +1,90 @@ +{ + "schema_version": 1, + "snapshot_id": "SYNTHETIC-AFTER", + "coverage": { + "scope_id": "SYNTHETIC-ONLY", + "status": "COMPLETE", + "review_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "nodes": { + "A": { + "kind": "CLAIM", + "contract_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "evidential_status": "UNASSESSED", + "admissibility": "ELIGIBLE", + "scheduling": "ACTIVE" + }, + "B": { + "kind": "CLAIM", + "contract_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "evidential_status": "UNASSESSED", + "admissibility": "ELIGIBLE", + "scheduling": "ACTIVE" + }, + "C": { + "kind": "CLAIM", + "contract_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "evidential_status": "UNASSESSED", + "admissibility": "ELIGIBLE", + "scheduling": "ACTIVE" + }, + "D": { + "kind": "CLAIM", + "contract_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "evidential_status": "UNASSESSED", + "admissibility": "ELIGIBLE", + "scheduling": "ACTIVE" + } + }, + "grounds": { + "GA": { + "conclusion": "A", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "SUSPENDED" + }, + "GB": { + "conclusion": "B", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE" + }, + "GD": { + "conclusion": "D", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE" + } + }, + "routes": { + "ABC": { + "conclusion": "C", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE", + "requires": [ + "A", + "B" + ] + }, + "DC": { + "conclusion": "C", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE", + "requires": [ + "D" + ] + } + }, + "dashboard_population": [ + "A", + "B", + "C", + "D" + ] +} diff --git a/governance/withdrawal/examples/before.json b/governance/withdrawal/examples/before.json new file mode 100644 index 000000000..2e7225a69 --- /dev/null +++ b/governance/withdrawal/examples/before.json @@ -0,0 +1,90 @@ +{ + "schema_version": 1, + "snapshot_id": "SYNTHETIC-BEFORE", + "coverage": { + "scope_id": "SYNTHETIC-ONLY", + "status": "COMPLETE", + "review_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "nodes": { + "A": { + "kind": "CLAIM", + "contract_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "evidential_status": "UNASSESSED", + "admissibility": "ELIGIBLE", + "scheduling": "ACTIVE" + }, + "B": { + "kind": "CLAIM", + "contract_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "evidential_status": "UNASSESSED", + "admissibility": "ELIGIBLE", + "scheduling": "ACTIVE" + }, + "C": { + "kind": "CLAIM", + "contract_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "evidential_status": "UNASSESSED", + "admissibility": "ELIGIBLE", + "scheduling": "ACTIVE" + }, + "D": { + "kind": "CLAIM", + "contract_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "evidential_status": "UNASSESSED", + "admissibility": "ELIGIBLE", + "scheduling": "ACTIVE" + } + }, + "grounds": { + "GA": { + "conclusion": "A", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE" + }, + "GB": { + "conclusion": "B", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE" + }, + "GD": { + "conclusion": "D", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE" + } + }, + "routes": { + "ABC": { + "conclusion": "C", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE", + "requires": [ + "A", + "B" + ] + }, + "DC": { + "conclusion": "C", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "scope_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "admissibility": "ELIGIBLE", + "requires": [ + "D" + ] + } + }, + "dashboard_population": [ + "A", + "B", + "C", + "D" + ] +} diff --git a/governance/withdrawal/examples/ticket.json b/governance/withdrawal/examples/ticket.json new file mode 100644 index 000000000..6155c2863 --- /dev/null +++ b/governance/withdrawal/examples/ticket.json @@ -0,0 +1,29 @@ +{ + "schema_version": 1, + "transition_id": "SYNTHETIC-WITHDRAWAL-001", + "operation": "WITHDRAW_SUPPORT", + "author_session": "SYNTHETIC-AUTHOR", + "before_sha256": "ffa156e2e6e2786ae6902a2665f53fb5ff045f7829a917278994057798280196", + "after_sha256": "5219511b5d342d2c0486e12b5456bdbefd5ee1b404c439ae7a5b9c16b0a08822", + "reason": { + "kind": "PROOF_DEFECT", + "description": "Synthetic defective warrant.", + "evidence_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "changed_objects": [ + "grounds/GA" + ], + "expected_lost_support": [ + "A" + ], + "expected_supported_nodes": [ + "B", + "C", + "D" + ], + "publication": { + "phase": "PREPARED", + "drive": null, + "github": null + } +} diff --git a/tests/test_withdrawal.py b/tests/test_withdrawal.py new file mode 100644 index 000000000..e30860f8b --- /dev/null +++ b/tests/test_withdrawal.py @@ -0,0 +1,247 @@ +"""Synthetic structural tests only. No research theorem is adjudicated.""" +from __future__ import annotations +import copy +import importlib.util +import itertools +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +SCRIPT = Path(__file__).resolve().parents[1] / 'tools' / 'withdrawal_check.py' +spec = importlib.util.spec_from_file_location('withdrawal_pilot', SCRIPT) +w = importlib.util.module_from_spec(spec) +spec.loader.exec_module(w) +H = 'a' * 64 + + +def fixture(alternative=False): + def node(): + return {'kind': 'CLAIM', 'contract_sha256': H, 'scope_sha256': H, + 'evidential_status': 'UNASSESSED', 'admissibility': 'ELIGIBLE', + 'scheduling': 'ACTIVE'} + def warrant(n): + return {'conclusion': n, 'artifact_sha256': H, 'scope_sha256': H, + 'admissibility': 'ELIGIBLE'} + before = {'schema_version': 1, 'snapshot_id': 'SYNTHETIC-BEFORE', + 'coverage': {'scope_id': 'SYNTHETIC-ONLY', 'status': 'COMPLETE', 'review_sha256': H}, + 'nodes': {x: node() for x in 'ABCD'}, + 'grounds': {'GA': warrant('A'), 'GB': warrant('B'), 'GD': warrant('D')}, + 'routes': {'ABC': dict(warrant('C'), requires=['A', 'B'])}, + 'dashboard_population': list('ABCD')} + if alternative: + before['routes']['DC'] = dict(warrant('C'), requires=['D']) + after = copy.deepcopy(before) + after['snapshot_id'] = 'SYNTHETIC-AFTER' + after['grounds']['GA']['admissibility'] = 'SUSPENDED' + ticket = {'schema_version': 1, 'transition_id': 'SYNTHETIC-WITHDRAWAL-001', + 'operation': 'WITHDRAW_SUPPORT', 'author_session': 'SYNTHETIC-AUTHOR', + 'before_sha256': '', 'after_sha256': '', + 'reason': {'kind': 'PROOF_DEFECT', 'description': 'Synthetic defective warrant.', 'evidence_sha256': H}, + 'changed_objects': ['grounds/GA'], 'expected_lost_support': [], + 'expected_supported_nodes': [], + 'publication': {'phase': 'PREPARED', 'drive': None, 'github': None}} + seal(before, after, ticket) + return before, after, ticket + + +def seal(b, a, t): + t['before_sha256'] = w.canonical_sha(b) + t['after_sha256'] = w.canonical_sha(a) + sb, _ = w.support(b) + sa, _ = w.support(a) + t['expected_lost_support'] = sorted(sb - sa) + t['expected_supported_nodes'] = sorted(sa) + + +class WithdrawalTests(unittest.TestCase): + def reject(self, mutate): + b, a, t = fixture() + mutate(b, a, t) + with self.assertRaises((w.Invalid, TypeError, KeyError)): + w.validate_transition(b, a, t) + + def test_required_premise_loss(self): + b, a, t = fixture() + out = w.validate_transition(b, a, t) + self.assertEqual(out['lost_support'], ['A', 'C']) + self.assertEqual(out['disabled_routes']['ABC'], ['A', 'B']) + self.assertFalse(out['scientific_acceptance']) + + def test_alternative_route_survives(self): + b, a, t = fixture(True) + out = w.validate_transition(b, a, t) + self.assertEqual(out['lost_support'], ['A']) + self.assertEqual(out['surviving_witnesses']['C'], ['routes/DC']) + + def test_premise_evaporation(self): + def mutate(b, a, t): + a['routes']['ABC']['requires'] = ['B']; seal(b, a, t) + self.reject(mutate) + + def test_survivor_laundering(self): + self.reject(lambda b, a, t: t['expected_supported_nodes'].append('C')) + + def test_impact_omission(self): + self.reject(lambda b, a, t: t.update(expected_lost_support=['A'])) + + def test_no_deletion(self): + def mutate(b, a, t): + del a['grounds']['GA']; seal(b, a, t) + self.reject(mutate) + + def test_no_new_warrant(self): + def mutate(b, a, t): + a['grounds']['NEW'] = dict(a['grounds']['GB'], conclusion='C'); seal(b, a, t) + self.reject(mutate) + + def test_no_scope_change(self): + def mutate(b, a, t): + a['nodes']['C']['scope_sha256'] = 'b' * 64; seal(b, a, t) + self.reject(mutate) + + def test_no_contract_change(self): + def mutate(b, a, t): + a['nodes']['C']['contract_sha256'] = 'b' * 64; seal(b, a, t) + self.reject(mutate) + + def test_no_falsehood_from_proof_failure(self): + def mutate(b, a, t): + a['nodes']['A']['evidential_status'] = 'REFUTED' + a['nodes']['A']['admissibility'] = 'INELIGIBLE'; seal(b, a, t) + self.reject(mutate) + + def test_no_dashboard_denominator_shrink(self): + def mutate(b, a, t): + a['dashboard_population'].remove('A'); seal(b, a, t) + self.reject(mutate) + + def test_scheduling_is_not_truth(self): + b, a, t = fixture() + a = copy.deepcopy(b); a['snapshot_id'] = 'SYNTHETIC-PAUSED' + a['nodes']['A']['scheduling'] = 'CLOSED' + t.update(operation='CHANGE_SCHEDULE', changed_objects=['nodes/A']) + t['reason'].update(kind='RESOURCE_ALLOCATION', evidence_sha256=None) + seal(b, a, t) + self.assertEqual(w.validate_transition(b, a, t)['lost_support'], []) + + def test_resource_reason_cannot_withdraw(self): + self.reject(lambda b, a, t: t['reason'].update(kind='RESOURCE_ALLOCATION')) + + def test_stale_binding(self): + self.reject(lambda b, a, t: t.update(before_sha256='f' * 64)) + + def test_uncovered_change(self): + self.reject(lambda b, a, t: t.update(changed_objects=[])) + + def test_no_restoration(self): + b, a, t = fixture() + b['grounds']['GA']['admissibility'] = 'INELIGIBLE'; seal(b, a, t) + with self.assertRaises(w.Invalid): w.validate_transition(b, a, t) + + def test_partial_publication(self): + self.reject(lambda b, a, t: t['publication'].update(phase='RECORDED')) + + def test_mixed_transaction(self): + self.reject(lambda b, a, t: t['publication'].update(drive={ + 'transaction_id': 'WRONG', 'snapshot_sha256': t['after_sha256'], 'reference': 'synthetic'})) + + def test_mixed_snapshot(self): + self.reject(lambda b, a, t: t['publication'].update(github={ + 'transaction_id': t['transition_id'], 'snapshot_sha256': H, 'reference': 'synthetic'})) + + def test_recorded_is_not_accepted(self): + b, a, t = fixture() + t['publication'] = {'phase': 'RECORDED', **{x: { + 'transaction_id': t['transition_id'], 'snapshot_sha256': t['after_sha256'], + 'reference': f'synthetic:{x}'} for x in ('drive', 'github')}} + self.assertFalse(w.validate_transition(b, a, t)['scientific_acceptance']) + + def test_missing_coverage_review(self): + self.reject(lambda b, a, t: a['coverage'].update(review_sha256=None)) + + def test_partial_coverage_cannot_be_recorded(self): + b, a, t = fixture() + for s in (b, a): s['coverage'].update(status='PARTIAL') + seal(b, a, t) + t['publication'] = {'phase': 'RECORDED', **{x: { + 'transaction_id': t['transition_id'], 'snapshot_sha256': t['after_sha256'], + 'reference': 'synthetic'} for x in ('drive', 'github')}} + with self.assertRaises(w.Invalid): w.validate_transition(b, a, t) + + def test_unknown_fields_fail_closed(self): + self.reject(lambda b, a, t: t.update(accept=True)) + + def test_wrong_version(self): + self.reject(lambda b, a, t: t.update(schema_version=2)) + + def test_boolean_not_integer_version(self): + self.reject(lambda b, a, t: t.update(schema_version=True)) + + def test_duplicate_dependency(self): + self.reject(lambda b, a, t: a['routes']['ABC'].update(requires=['A', 'A'])) + + def test_dangling_dependency(self): + self.reject(lambda b, a, t: a['routes']['ABC'].update(requires=['MISSING'])) + + def test_no_unconditional_empty_route(self): + self.reject(lambda b, a, t: a['routes']['ABC'].update(requires=[])) + + def test_unseeded_cycle_has_no_support(self): + b, _, _ = fixture() + b['grounds'] = {} + b['routes']['CA'] = dict(b['routes']['ABC'], conclusion='A', requires=['C']) + self.assertEqual(w.support(b)[0], set()) + + def test_legacy_inventory_never_promotes_empty_dependency_list(self): + result = w.inventory({'claims': {'A': {'depends_on': [], 'grade': 'LIVE_ROOT_THEOREM'}}, 'premises': {}}) + self.assertEqual(result['objects'][0]['support_verdict'], 'NOT_ASSESSED') + self.assertEqual(result['scientific_status_changes'], []) + + def test_empty_legacy_inventory_fails(self): + with self.assertRaises(w.Invalid): w.inventory({'claims': {}, 'premises': {}}) + + def test_exhaustive_monotonicity_81_assignments(self): + b, _, _ = fixture(True) + baseline = w.support(b)[0] + for values in itertools.product(w.ADM, repeat=4): + a = copy.deepcopy(b) + for key, value in zip(('GA', 'GB', 'GD'), values[:3]): + a['grounds'][key]['admissibility'] = value + a['routes']['ABC']['admissibility'] = values[3] + self.assertLessEqual(w.support(a)[0], baseline) + + def test_cli_actual_paths_and_optimized_mode(self): + b, a, t = fixture() + with tempfile.TemporaryDirectory() as d: + paths = [Path(d) / name for name in ('before.json', 'after.json', 'ticket.json')] + for path, obj in zip(paths, (b, a, t)): path.write_text(json.dumps(obj)) + args = ['check', '--before', str(paths[0]), '--after', str(paths[1]), '--ticket', str(paths[2])] + for mode in ([], ['-O']): + run = subprocess.run([sys.executable, *mode, str(SCRIPT), *args], capture_output=True, text=True) + self.assertEqual(run.returncode, 0, run.stderr) + t['expected_lost_support'] = [] + paths[2].write_text(json.dumps(t)) + for mode in ([], ['-O']): + run = subprocess.run([sys.executable, *mode, str(SCRIPT), *args], capture_output=True, text=True) + self.assertEqual(run.returncode, 2, run.stdout) + + def test_cli_missing_input(self): + run = subprocess.run([sys.executable, str(SCRIPT), 'inventory', '--legacy-graph', '/nonexistent/withdrawal.json'], capture_output=True) + self.assertEqual(run.returncode, 2) + + def test_json_duplicate_key_rejected(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / 'bad.json'; p.write_text('{"x": 1, "x": 2}') + with self.assertRaises(w.Invalid): w.load(p) + + def test_json_nonfinite_rejected(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / 'bad.json'; p.write_text('{"x": NaN}') + with self.assertRaises(w.Invalid): w.load(p) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/withdrawal_check.py b/tools/withdrawal_check.py new file mode 100644 index 000000000..df8fe77e7 --- /dev/null +++ b/tools/withdrawal_check.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Loss-only transition pilot. Structural validation, never scientific acceptance. + +Python 3.11+, standard library only. No writes, network, credentials or execution +of referenced artifacts. Enrolment of the research graph is a separate review. +""" +from __future__ import annotations +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path +from typing import Any + + +class Invalid(ValueError): + """A malformed, unsafe, stale, or unsupported transition.""" + + +def need(condition: bool, message: str) -> None: + if not condition: + raise Invalid(message) + + +def keys(obj: Any, expected: set[str], where: str) -> None: + need(isinstance(obj, dict), f'{where}: expected object') + need(set(obj) == expected, f'{where}: unexpected/missing fields') + + +def text(value: Any, where: str) -> None: + need(isinstance(value, str) and bool(value.strip()), f'{where}: empty/non-string') + + +def digest(value: Any, where: str) -> None: + need(isinstance(value, str) and re.fullmatch(r'[0-9a-f]{64}', value) is not None, + f'{where}: expected lowercase SHA-256') + + +def unique_ids(value: Any, where: str) -> None: + need(isinstance(value, list), f'{where}: expected list') + for item in value: + text(item, where) + need(len(value) == len(set(value)), f'{where}: duplicate IDs') + + +def canonical_sha(obj: Any) -> str: + """Version-1 canonical JSON: sorted keys, compact UTF-8, no NaN/Infinity.""" + return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(',', ':'), + ensure_ascii=False, allow_nan=False).encode()).hexdigest() + + +def _pairs(pairs: list[tuple[str, Any]]) -> dict: + out: dict[str, Any] = {} + for key, value in pairs: + need(key not in out, f'duplicate JSON key: {key}') + out[key] = value + return out + + +def load(path: Path) -> Any: + def reject_constant(value: str) -> None: + raise Invalid(f'non-finite JSON token: {value}') + return json.loads(path.read_text(encoding='utf-8'), object_pairs_hook=_pairs, + parse_constant=reject_constant) + + +ADM = {'ELIGIBLE': 0, 'SUSPENDED': 1, 'INELIGIBLE': 2} +SCHEDULE = {'ACTIVE', 'BLOCKED', 'PAUSED', 'CLOSED'} +KINDS = {'CLAIM', 'PREMISE', 'PROOF', 'STRATEGY', 'CARRIER'} +EVIDENCE = {'UNASSESSED', 'OPEN', 'CONDITIONAL', 'ESTABLISHED', 'REFUTED', 'INVALID'} + + +def validate_state(state: Any) -> None: + keys(state, {'schema_version', 'snapshot_id', 'coverage', 'nodes', 'grounds', + 'routes', 'dashboard_population'}, 'snapshot') + need(type(state['schema_version']) is int and state['schema_version'] == 1, + 'unsupported snapshot version') + text(state['snapshot_id'], 'snapshot_id') + c = state['coverage'] + keys(c, {'scope_id', 'status', 'review_sha256'}, 'coverage') + text(c['scope_id'], 'coverage.scope_id') + need(c['status'] in {'COMPLETE', 'PARTIAL', 'UNASSESSED'}, 'coverage.status') + if c['review_sha256'] is not None: + digest(c['review_sha256'], 'coverage.review_sha256') + need(c['status'] != 'COMPLETE' or c['review_sha256'] is not None, + 'COMPLETE coverage needs a bound review artifact (not verified here)') + for group in ('nodes', 'grounds', 'routes'): + need(isinstance(state[group], dict), f'{group}: expected object') + nodes = state['nodes'] + need(bool(nodes), 'empty scope is not a successful audit') + for nid, node in nodes.items(): + text(nid, 'node ID') + need('/' not in nid, 'node ID may not contain /') + keys(node, {'kind', 'contract_sha256', 'scope_sha256', 'evidential_status', + 'admissibility', 'scheduling'}, f'node {nid}') + need(node['kind'] in KINDS, f'{nid}: kind') + need(node['evidential_status'] in EVIDENCE, f'{nid}: evidential_status') + need(node['admissibility'] in ADM, f'{nid}: admissibility') + need(node['scheduling'] in SCHEDULE, f'{nid}: scheduling') + digest(node['contract_sha256'], f'{nid}: contract') + digest(node['scope_sha256'], f'{nid}: scope') + need(node['evidential_status'] not in {'REFUTED', 'INVALID'} or + node['admissibility'] != 'ELIGIBLE', f'{nid}: refuted/invalid yet eligible') + for group in ('grounds', 'routes'): + for oid, obj in state[group].items(): + text(oid, f'{group} ID') + need('/' not in oid, f'{group} ID may not contain /') + expected = {'conclusion', 'artifact_sha256', 'scope_sha256', 'admissibility'} + if group == 'routes': + expected |= {'requires'} + keys(obj, expected, f'{group}/{oid}') + need(obj['conclusion'] in nodes, f'{oid}: unknown conclusion') + need(obj['admissibility'] in ADM, f'{oid}: admissibility') + digest(obj['artifact_sha256'], f'{oid}: artifact') + digest(obj['scope_sha256'], f'{oid}: scope') + need(obj['scope_sha256'] == nodes[obj['conclusion']]['scope_sha256'], + f'{oid}: conclusion scope mismatch') + if group == 'routes': + unique_ids(obj['requires'], f'{oid}: requires') + need(bool(obj['requires']), 'unconditional warrant belongs in grounds') + need(all(x in nodes for x in obj['requires']), f'{oid}: dangling premise') + unique_ids(state['dashboard_population'], 'dashboard_population') + need(set(state['dashboard_population']) <= set(nodes), 'unknown dashboard member') + + +def support(state: dict) -> tuple[set[str], dict[str, list[str]]]: + """Least fixed point: AND within each route; OR between routes/grounds. + + Labels alone provide no support. In particular, an empty dependency list + in an imported graph is not an unconditional proof. Unseeded cycles add none. + These are available recorded support paths, not a theorem prover's verdict. + """ + nodes = state['nodes'] + eligible = {n for n, obj in nodes.items() if obj['admissibility'] == 'ELIGIBLE'} + available = {g['conclusion'] for g in state['grounds'].values() + if g['admissibility'] == 'ELIGIBLE' and g['conclusion'] in eligible} + while True: + expanded = available | {r['conclusion'] for r in state['routes'].values() + if r['admissibility'] == 'ELIGIBLE' + and r['conclusion'] in eligible + and set(r['requires']) <= available} + if expanded == available: + break + available = expanded + witnesses: dict[str, list[str]] = {n: [] for n in sorted(available)} + for group in ('grounds', 'routes'): + for oid, obj in state[group].items(): + n = obj['conclusion'] + if obj['admissibility'] == 'ELIGIBLE' and n in available and ( + group == 'grounds' or set(obj['requires']) <= available): + witnesses[n].append(f'{group}/{oid}') + return available, witnesses + + +def validate_transition(before: Any, after: Any, ticket: Any) -> dict: + validate_state(before) + validate_state(after) + keys(ticket, {'schema_version', 'transition_id', 'operation', 'author_session', + 'before_sha256', 'after_sha256', 'reason', 'changed_objects', + 'expected_lost_support', 'expected_supported_nodes', 'publication'}, 'ticket') + need(type(ticket['schema_version']) is int and ticket['schema_version'] == 1, + 'unsupported ticket version') + for field in ('transition_id', 'author_session'): + text(ticket[field], field) + need(ticket['operation'] in {'WITHDRAW_SUPPORT', 'CHANGE_SCHEDULE'}, + 'v1 does not adjudicate falsity, restore support, replace contracts or add evidence') + for name, obj in (('before', before), ('after', after)): + digest(ticket[f'{name}_sha256'], f'{name} digest') + need(ticket[f'{name}_sha256'] == canonical_sha(obj), f'stale {name} binding') + need(before['snapshot_id'] != after['snapshot_id'], 'successor needs a new snapshot ID') + for field in ('schema_version', 'coverage', 'dashboard_population'): + need(before[field] == after[field], f'{field} cannot change in a loss-only transaction') + reason = ticket['reason'] + keys(reason, {'kind', 'description', 'evidence_sha256'}, 'reason') + text(reason['description'], 'reason.description') + if ticket['operation'] == 'CHANGE_SCHEDULE': + need(reason['kind'] == 'RESOURCE_ALLOCATION', 'schedule reason must be resource allocation') + if reason['evidence_sha256'] is not None: + digest(reason['evidence_sha256'], 'schedule evidence') + else: + need(reason['kind'] in {'PROOF_DEFECT', 'TYPING_UNCERTAINTY', + 'STRATEGY_LIMIT', 'COUNTEREXAMPLE_CANDIDATE'}, + 'time, cost, or boredom cannot withdraw scientific support') + digest(reason['evidence_sha256'], 'withdrawal evidence') + changed: set[str] = set() + for group in ('nodes', 'grounds', 'routes'): + need(set(before[group]) == set(after[group]), f'{group}: no deletion, addition or renaming') + for oid, old in before[group].items(): + new = after[group][oid] + allowed = {'scheduling'} if ticket['operation'] == 'CHANGE_SCHEDULE' and group == 'nodes' else set() + if ticket['operation'] == 'WITHDRAW_SUPPORT': + allowed = {'admissibility'} + for field in old: + if field not in allowed: + need(old[field] == new[field], f'{group}/{oid}: forbidden change to {field}') + if 'admissibility' in allowed: + need(ADM[new['admissibility']] >= ADM[old['admissibility']], + f'{group}/{oid}: restoration needs a separate reviewed transition') + if new != old: + changed.add(f'{group}/{oid}') + need(bool(changed), 'empty change is not a transition') + unique_ids(ticket['changed_objects'], 'changed_objects') + need(changed == set(ticket['changed_objects']), 'changed object coverage mismatch') + prior, _ = support(before) + current, witnesses = support(after) + need(current <= prior, 'premise evaporation: withdrawal increased support') + if ticket['operation'] == 'CHANGE_SCHEDULE': + need(current == prior, 'scheduling changed support') + for field, actual in (('expected_lost_support', prior - current), + ('expected_supported_nodes', current)): + unique_ids(ticket[field], field) + need(set(ticket[field]) == actual, f'{field}: dependent rewrite or survivor mismatch') + pub = ticket['publication'] + keys(pub, {'phase', 'drive', 'github'}, 'publication') + need(pub['phase'] in {'PREPARED', 'RECORDED'}, 'v1 cannot confer ACCEPTED status') + for surface in ('drive', 'github'): + binding = pub[surface] + if binding is not None: + keys(binding, {'transaction_id', 'snapshot_sha256', 'reference'}, surface) + need(binding['transaction_id'] == ticket['transition_id'], f'{surface}: mixed transaction') + need(binding['snapshot_sha256'] == ticket['after_sha256'], f'{surface}: mixed snapshot') + text(binding['reference'], f'{surface}: reference') + if pub['phase'] == 'RECORDED': + need(binding is not None, 'interrupted cross-system publication: recorded side missing') + if pub['phase'] == 'RECORDED': + need(after['coverage']['status'] == 'COMPLETE', 'incomplete dependency coverage: HOLD') + return { + 'result': 'STRUCTURALLY_VALID', 'scientific_acceptance': False, + 'authority': 'NONE', 'transition_id': ticket['transition_id'], + 'coverage': after['coverage'], 'publication_phase': pub['phase'], + 'lost_support': sorted(prior - current), 'available_support': sorted(current), + 'surviving_witnesses': witnesses, + 'disabled_routes': {rid: r['requires'] for rid, r in after['routes'].items() + if r['admissibility'] != 'ELIGIBLE' + or r['conclusion'] not in current + or not set(r['requires']) <= current}, + 'dashboard_population': after['dashboard_population'], + 'limitations': ['Input provenance and review authenticity require external verification.', + 'Coverage completeness and mathematical correctness are not proved here.', + 'No live research record is changed; no final refutation or restoration is authorized.']} + + +def inventory(graph: Any) -> dict: + """Read-only enrolment inventory; never infer proof routes from depends_on.""" + need(isinstance(graph, dict), 'legacy graph must be an object') + for group in ('claims', 'premises'): + need(isinstance(graph.get(group), dict), f'legacy graph missing {group}') + need(bool(graph['claims']) or bool(graph['premises']), 'empty legacy scope') + names = set(graph['claims']) | set(graph['premises']) + need(not (set(graph['claims']) & set(graph['premises'])), 'ambiguous legacy object IDs') + rows = [] + for group in ('claims', 'premises'): + for oid, obj in sorted(graph[group].items()): + need(isinstance(obj, dict), f'{oid}: invalid legacy record') + deps = obj.get('depends_on', []) + unique_ids(deps, f'{oid}: legacy dependencies') + rows.append({'id': oid, 'source_section': group, + 'source_record_sha256': canonical_sha(obj), + 'declared_dependencies': deps, + 'unresolved_references': [x for x in deps if x not in names], + 'enrolment': 'NOT_MIGRATED', 'support_verdict': 'NOT_ASSESSED'}) + return {'mode': 'READ_ONLY_SHADOW', 'dependency_coverage': 'UNASSESSED', + 'source_graph_sha256': canonical_sha(graph), 'object_count': len(rows), + 'objects': rows, 'scientific_status_changes': [], + 'warning': 'Declared edges are not a complete proof-route map. No empty list is promoted to a warrant.'} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest='command', required=True) + check = sub.add_parser('check') + for name in ('before', 'after', 'ticket'): + check.add_argument(f'--{name}', type=Path, required=True) + inv = sub.add_parser('inventory') + inv.add_argument('--legacy-graph', type=Path, required=True) + args = parser.parse_args(argv) + try: + if args.command == 'check': + result = validate_transition(load(args.before), load(args.after), load(args.ticket)) + else: + result = inventory(load(args.legacy_graph)) + print(json.dumps(result, sort_keys=True, indent=2, ensure_ascii=False)) + return 0 + except (Invalid, ValueError, OSError, TypeError, KeyError, RecursionError) as exc: + print(f'WITHDRAWAL HOLD: {exc}', file=sys.stderr) + return 2 + + +if __name__ == '__main__': + raise SystemExit(main()) From 4353db4aa511062ba7cbfb0f4b2d43180f9d9946 Mon Sep 17 00:00:00 2001 From: Dylan Roy Date: Mon, 21 Sep 2026 17:00:03 -0500 Subject: [PATCH 2/4] Add phased governance rollout compatibility overlay --- AGENTS.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 2767fe715..5ac876123 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,3 +55,15 @@ its parent's premises. Preserve alternative proofs and require exact survivor warrants. The executable checker is an unreviewed loss-only pilot, not a verdict engine. Existing scientific records are NOT_MIGRATED. Apply the safeguards to new work; do not bulk-convert historical statuses. Use the existing R17 event log. + +## Governance rollout compatibility — 2026-09-21 + +Drive governance is being re-audited for premature or overly broad activation. Read the +Governance Rollout Audit (Drive id `1QQOu8r9FBnYZL3XxURSHqsu0mkqcK5P466dXUtpklu8`) before +interpreting a newly installed rule as universally active. Default adoption is +`PROPOSED -> SHADOW -> PILOT -> REVIEWED -> ACTIVE_SCOPED -> ACTIVE_GENERAL`. +Immediate containment is reserved for narrow integrity/safety hazards. Words such as +`mandatory`, `automatic`, `superseded`, `complete`, `abandoned`, `retired`, and `HOLD` +do not cross object types: an operational state is not a scientific verdict. Preserve +predecessor rules as compatibility evidence while affected consumers are audited. Do not +pause unrelated research solely because the governance audit is open. From db39ac3d72643669d46cc43e07a95716d1c68097 Mon Sep 17 00:00:00 2001 From: Dylan Roy Date: Mon, 21 Sep 2026 17:17:17 -0500 Subject: [PATCH 3/4] Stage scoped rollout clarification (code candidate prepared separately) --- AGENTS.md | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5ac876123..510fbd462 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,14 +56,20 @@ warrants. The executable checker is an unreviewed loss-only pilot, not a verdict engine. Existing scientific records are NOT_MIGRATED. Apply the safeguards to new work; do not bulk-convert historical statuses. Use the existing R17 event log. -## Governance rollout compatibility — 2026-09-21 +## Governance rollout compatibility — scoped correction v1.1 -Drive governance is being re-audited for premature or overly broad activation. Read the -Governance Rollout Audit (Drive id `1QQOu8r9FBnYZL3XxURSHqsu0mkqcK5P466dXUtpklu8`) before -interpreting a newly installed rule as universally active. Default adoption is -`PROPOSED -> SHADOW -> PILOT -> REVIEWED -> ACTIVE_SCOPED -> ACTIVE_GENERAL`. -Immediate containment is reserved for narrow integrity/safety hazards. Words such as -`mandatory`, `automatic`, `superseded`, `complete`, `abandoned`, `retired`, and `HOLD` -do not cross object types: an operational state is not a scientific verdict. Preserve -predecessor rules as compatibility evidence while affected consumers are audited. Do not -pause unrelated research solely because the governance audit is open. +Read [the scoped rollout correction](governance/rollout/OP-ROLLOUT-AUDIT-20260921-v1.1.md) +for changed governance behavior. R17's expressly authorized clause replacements remain +controlling; incomplete uptake evidence does not revive retired budgets or provider +restrictions. Historical rules are evidence, not "stricter-wins" fallback authority. +Material behavior changes need phased, cohort-bound tests and review. A verified +semantics-preserving link/range repair does not require six new approval stages. +The rollout checker is read-only author-side shadow tooling, not a live admission engine. + +Use current Home/Start Here metadata and stable keys, not stale prefix ranges. Qualify +binding classes by protocol/version; OP-PROT-013 class A and OP-PROT-014 class A differ. +Recheck source policy, expected base and candidate before publication. A clean Git merge +is not semantic reconciliation, and an ordinary fast-forward update is not a distributed +lock or cross-system transaction. A schedule only in a nondefault branch is not a deployed +scheduled workflow. No settings, broad migration, or scientific status moves are authorized +by this notice. Preserve exact existing review targets; amendments get separate identities. From 63eb5baadd7526a7842c43f2d391aad55b01cac9 Mon Sep 17 00:00:00 2001 From: Dylan Roy Date: Mon, 21 Sep 2026 17:17:37 -0500 Subject: [PATCH 4/4] Publish complete R2 rollout candidate after staged entry notice Complete the already prepared nine-file tree without rewriting the pointer-only predecessor. Adds read-only rollout guards, 46 synthetic/real-Git regression tests, scoped v1.1 correction and evidence references. Existing 36 withdrawal tests retained. Author-side pilot only; no scientific status migration, no merge or settings changes. --- .github/workflows/withdrawal-governance.yml | 5 + governance/rollout/FINDINGS_R2.json | 128 ++++++++++ .../rollout/OP-ROLLOUT-AUDIT-20260921-v1.1.md | 168 +++++++++++++ governance/rollout/RECONNAISSANCE_R2.md | 34 +++ .../rollout/SYNTHETIC_metadata_plan.json | 39 +++ governance/rollout/WORK_ORDER_R2.json | 25 ++ tests/test_rollout_guard.py | 223 ++++++++++++++++++ tools/rollout_guard.py | 205 ++++++++++++++++ 8 files changed, 827 insertions(+) create mode 100644 governance/rollout/FINDINGS_R2.json create mode 100644 governance/rollout/OP-ROLLOUT-AUDIT-20260921-v1.1.md create mode 100644 governance/rollout/RECONNAISSANCE_R2.md create mode 100644 governance/rollout/SYNTHETIC_metadata_plan.json create mode 100644 governance/rollout/WORK_ORDER_R2.json create mode 100644 tests/test_rollout_guard.py create mode 100644 tools/rollout_guard.py diff --git a/.github/workflows/withdrawal-governance.yml b/.github/workflows/withdrawal-governance.yml index 4884e749f..480211afc 100644 --- a/.github/workflows/withdrawal-governance.yml +++ b/.github/workflows/withdrawal-governance.yml @@ -24,3 +24,8 @@ jobs: --ticket governance/withdrawal/examples/ticket.json - name: Read-only research enrolment inventory (not migration) run: python3 tools/withdrawal_check.py inventory --legacy-graph claims/graph.json + - name: Rollout shadow controls (normal and optimized; no live admission) + run: | + python3 -m unittest discover -s tests -p test_rollout_guard.py -v + python3 -O -m unittest discover -s tests -p test_rollout_guard.py -v + python3 tools/rollout_guard.py governance/rollout/SYNTHETIC_metadata_plan.json diff --git a/governance/rollout/FINDINGS_R2.json b/governance/rollout/FINDINGS_R2.json new file mode 100644 index 000000000..ac7ad6332 --- /dev/null +++ b/governance/rollout/FINDINGS_R2.json @@ -0,0 +1,128 @@ +{ + "audit_id": "ROLLOUT-R2-20260921", + "scientific_effect": "NONE", + "coverage": "TARGETED_CRITICAL_PATH_NOT_WORKSPACE_COMPLETE", + "findings": [ + { + "id": "R2-01", + "classification": "CONFIRMED_ROUTING_GAP", + "source_scope": "Home; Start Here C8; active Drive Review Pickup", + "observation": "Entry prefixes end at row31 and row24, while rollout key is row32 in the100-row compact sheet.", + "proposed_response": "Bound reads to current allocated compact view; retain stable-key/tail reads elsewhere." + }, + { + "id": "R2-02", + "classification": "INTERPRETATION_RISK", + "source_scope": "Audit v1.0 DEFAULT ADOPTION/GLOBAL COMPATIBILITY and R17 opening", + "observation": "Treating authorized R17 supersession as only an intended end-state could revive explicitly retired restrictions. No actual revival by another model proved.", + "proposed_response": "Clarify authority versus uptake; source-specific supersession, no stricter-wins fallback." + }, + { + "id": "R2-03", + "classification": "INTERPRETATION_RISK", + "source_scope": "Audit v1.0 DEFAULT ADOPTION/FLOW REQUIREMENT", + "observation": "Six mandatory phases for every minor maintenance repair could create a new workflow bottleneck.", + "proposed_response": "Separate bounded semantics-preserving maintenance from material behavior changes." + }, + { + "id": "R2-04", + "classification": "CONFIRMED_VOCABULARY_COLLISION", + "source_scope": "OP-PROT-013 §8; OP-PROT-014 binding classes", + "observation": "A=raw/B=embedded in013, A=metadata/B=marker body in014; no downstream misbinding incident proved.", + "proposed_response": "Require standard/version-qualified classes; preserve historic records and extraction rules." + }, + { + "id": "R2-05", + "classification": "CONFIRMED_DOCUMENTATION_OVERCLAIM", + "source_scope": "governance/GIT_ADAPTATION.md claim lease/publication conflict rows", + "observation": "Ordinary merges/fast-forward checks do not guarantee base-head compare-and-swap or semantic reconciliation across Drive/GitHub.", + "proposed_response": "Qualify guide through the current AGENTS correction; retain real clean-merge semantic mismatch test." + }, + { + "id": "R2-06", + "classification": "CONFIRMED_SOURCE_DEPLOYMENT_GAP", + "source_scope": "Working-branch research.yml; default branch main root listing", + "observation": "Research schedule source is present on working branch but no workflow directory on observed default branch. This does not prove execution in external schedulers.", + "proposed_response": "Do not claim GitHub scheduled deployment or activate it just to match prior prose." + }, + { + "id": "R2-07", + "classification": "CONFIRMED_CHRONOLOGY_BINDING_DEFECT", + "source_scope": "R17 Work Events row122; rollout v1.0 provider metadata", + "observation": "Event timestamp17:20Z/expiry19:20Z predates Doc creation21:58:49Z; digest field is a placeholder. It is not proof of a valid contemporaneous claim.", + "proposed_response": "Append corrected chronology and source binding; preserve original; new actual-time claim for R2." + }, + { + "id": "R2-08", + "classification": "RETAINED_CONTROL", + "source_scope": "OP-PROT-017-SUP-C/LS-STD-001", + "observation": "Existing LMC/BRH scope qualification prevents one extraction family from being imposed universally.", + "proposed_response": "Reuse qualification; no rehash or invalidation of previously reproduced LMC objects." + }, + { + "id": "R2-09", + "classification": "RETAINED_CONTROL", + "source_scope": "OP-PROT-016 §9; OP-PROT-015 export appendix", + "observation": "A failed XLSX route need not invalidate explicitly qualified native control use.", + "proposed_response": "Keep export/native status separate; no formula edits in this round." + }, + { + "id": "R2-10", + "classification": "RETAINED_CONTROL", + "source_scope": "R17 review rules; OP-PROT-018 collision semantics; original withdrawal pilot", + "observation": "Review age and operational ABANDONED/HOLD cannot prove/refute science. Current lane checker invocation is already direct/failure-propagating.", + "proposed_response": "Retain safeguards; original scientific and nonauthor review gates remain open." + } + ], + "not_audited": [ + "all historical registry formulas", + "all branch variants and workers", + "external or local Codex schedulers", + "all package-level governance", + "all consuming model behavior", + "all scientific proofs" + ], + "input_sources": [ + { + "id": "1hBph5Fpxd5dVrolNkvzU8nb7xpxUiUdc", + "role": "R17 raw source", + "sha256": "04987ba47b58be623a3b2a5a8a21236f43d4393cc04009e87f4a62b59a787390", + "bytes": 14073 + }, + { + "id": "1QQOu8r9FBnYZL3XxURSHqsu0mkqcK5P466dXUtpklu8", + "role": "audit predecessor", + "binding": "native revision recorded in v1.1; text extraction is not original raw bytes", + "created_utc": "2026-09-21T21:58:49.926Z" + }, + { + "id": "1fnDuNgkWyaUsfphMaaZfAJHECHLJmuKYjgD6qdFFQrw", + "role": "OP013 semantic full read" + }, + { + "id": "1WFOMp3C5nHvPkZS9oOwQsn2ejZMpLbYrtckphEIkBo0", + "role": "OP014 semantic full read" + }, + { + "id": "1U155GYd-MlPvnqXQtzTMRdtu7T1x6vsEPSNjC1LQOm0", + "role": "OP015 semantic full read" + }, + { + "id": "1ITLtjJXHx9bEYMLqcExvrYnG9LHjS3tsX8MCfnbsVDQ", + "role": "OP016 semantic full read" + }, + { + "id": "1-raBN4fKaUqtqPw7Mz7szGE2ZNA4qVW0skOYn2zVvRs", + "role": "OP017SUPC semantic full read" + }, + { + "repo": "d6g8k5htny-coder/main", + "commit": "4353db4aa511062ba7cbfb0f4b2d43180f9d9946", + "files": { + "AGENTS.md": "5ac876123b8f4e4bf29d0df0d76a6a619a91de2c", + "governance/GIT_ADAPTATION.md": "0280a3deae700da3e54988a03443af046ba70ade", + ".github/workflows/research.yml": "181042ecd3b2b4741d4f7fabe62b72fb9439007d" + } + } + ] +} diff --git a/governance/rollout/OP-ROLLOUT-AUDIT-20260921-v1.1.md b/governance/rollout/OP-ROLLOUT-AUDIT-20260921-v1.1.md new file mode 100644 index 000000000..3701d39c6 --- /dev/null +++ b/governance/rollout/OP-ROLLOUT-AUDIT-20260921-v1.1.md @@ -0,0 +1,168 @@ +# Governance rollout audit — scoped correction v1.1 + +**ID:** OP-ROLLOUT-AUDIT-20260921-v1.1 +**Scope:** Correction of this audit's v1.0 precedence and rollout wording; bounded +navigation repairs and an author-side shadow validator. **Not a replacement of R17.** +The owner's 21 September continuation authorizes this work. Scientific status, +independence, frozen evidence, permissions and release predicates are unchanged. + +## 1. What this corrects + +The predecessor is the native Doc `1QQOu8r9FBnYZL3XxURSHqsu0mkqcK5P466dXUtpklu8`, +revision `ANLCKQkj5Kd9PKeLt3ghaX_Vp2S_SMztmf7CzbvLt05QUEooR7hog38oBDHKSwkFQbXuGqel1saGEqlPteK00vNWt0kRCZnHFfrNLOuXuYY`. +Its body is preserved. This successor qualifies its DEFAULT ADOPTION MODEL, +R17 HIGH-RISK FINDING, GLOBAL COMPATIBILITY RULE and FLOW REQUIREMENT. It does not +reinterpret historical events or turn every named risk into a demonstrated failure. + +**Authorization, implementation, observation and scientific acceptance are separate.** +An explicitly authorized rule can govern its stated scope before every consumer +has been observed obeying it. Conversely, a document, successful test or installed +configuration does not establish consumer uptake. Neither fact cancels the other. + +R17's explicit replacement of older entry budgets, compulsory full-Drive preflight, +blanket same-provider technical-review exclusions, recursive draft registration +and routine whole-package re-download remains effective. The audit does not reduce +that authorization to a merely hoped-for end-state. Older controls are history and +scope/compatibility evidence, not fallback authority merely because they are stricter. +Retain an older scientific definition or extraction rule where R17 explicitly +preserves it; do not revive an expressly replaced operational clause. + +## 2. Risk-proportionate change paths + +**Semantics-preserving maintenance:** correct a stale link, bounded entry range, +format or inaccurate deployment description using an identified old value, current +source, guarded edit, exact readback and rollback record. This does not need six +fresh ceremonies or a new routine human-approval dependency. A maintenance edit may +not change admission criteria, scheduled purpose, permissions, scientific status, +review independence, or the meaning of evidence. Classify a doubtful edit as a +behavior change rather than hiding it as maintenance. + +**Material behavior changes:** use PROPOSED -> SHADOW -> PILOT -> REVIEWED -> +ACTIVE_SCOPED -> ACTIVE_GENERAL, with a named finite consumer cohort, representative +acceptance/negative cases, evidence and rollback. Observation does not grant authority; +existing delegated decision authority remains separate and must be stated. General +activation means the explicitly inventoried supported cohort, not every possible +model or inaccessible executor. Expand coverage by a reviewed successor. The new +validator is author-side SHADOW/ISOLATED TESTING, not an enforced admission service. + +**Containment:** a demonstrated integrity, privacy, source or collision defect may +justify promptly stopping the specific unsafe use or write. Record the exact defect, +affected target and recovery condition. This neither enables a replacement globally +nor freezes unrelated work. Failed tooling or incomplete adoption evidence alone +cannot convert valid existing mathematical work into a refutation or a global HOLD. + +Normal source revalidation and already-authorized research continue throughout. +No new approval stage is inserted into unrelated work by the existence of this audit. + +## 3. Critical repairs and retained controls + +### Entry routing + +The current compact Start Here sheet has 100 allocated rows, 8 columns and the new +rollout route at row 32. Home/C8's A1:H31 and the daily pickup's A1:H24 omit it. +Read the allocated compact view after metadata validation (currently A1:H100), or +resolve the required stable keys with bounded complete discovery. An omitted or +truncated range is not evidence that the rule or work item does not exist. Do not +replace 31 by 32 and leave the same predictable failure for the next addition. +Review Queue and Work Events remain target-key/tail reads, not a full-Drive crawl. + +The daily pickup correction changes only entry routing and source freshness. Its +existing cadence, one bounded review/reconciliation purpose, publication safeguards +and independence constraints remain. Configuration readback is not an observed +unattended execution; the next executed run is a separate validation obligation. + +### Binding classes and extraction + +Qualify every shorthand binding class by its defining protocol/version. In +OP-PROT-013 (2026-07-26) A means raw content and B embedded payload. In +OP-PROT-014-v1.0 A means metadata and B marker-delimited body. C means native export +in both, but matching letters still do not prove identical extraction requirements. +Record the exact declared standard and representation; do not bulk-convert old rows. +An ambiguous declaration is a hold on that identity-dependent use, not on unrelated +research. The small code crosswalk is documentary and never rehashes a scientific body. + +Retain the existing OP-PROT-017-SUP-C/LS-STD-001 family distinction: LMC-1 literal +marker extraction and BRH-1 carrier-declared blank-run transformation are not +interchangeable. The carrier declaration selects the extraction family, never the +hash that a trial transformation happens to match. Existing successful LMC receipts +remain valid at their original scope. This is an existing useful qualification, not +a newly discovered failure of those receipts. + +### Git and cross-system publication + +The repository's governance/GIT_ADAPTATION.md describes merge as compare-and-swap +on the base head and ordinary merge conflicts as the same guarantee as governance +conflict reconciliation. Those assertions are too strong. Nonoverlapping file edits +can merge cleanly while introducing a contradictory interface or decision. The local +regression suite reproduces that counterexample in a temporary Git repository. + +Pin source-policy identity, expected base and exact candidate; revalidate all before +publication; record the actual resulting commit and reconcile semantic consequences. +A preflight read alone is still not atomic. A fast-forward ref update does not +constitute a lock across GitHub and Drive. GitHub's merge `sha` parameter checks the +PR head, not a Drive state or an arbitrary expected base snapshot. Preserve both +contending outputs. No merge/CAS service is installed by this correction. + +The research schedule is present on a working branch. The observed default branch +`main` currently has no workflow directory. GitHub schedules run from the default +branch; source presence here is not a deployed scheduled service. Leave the workflow +read-only and do not merge or enable it merely to make an earlier description true. +Its direct failure-propagating lane checks are already present and must be retained. + +### Historical records and review + +R17's queue is the pickup surface. Historical dispatch, claim and advisory-lane +records remain relevant collision or scientific inputs where applicable; their old +status words do not establish current validity or revive retired entry restrictions. +A collision-related ABANDONED event releases work ownership, not a mathematical claim. +Age prioritizes review; it does not approve, refute or create independence. Hashes +prove identity, not truth. An XLSX compatibility defect concerns the exported path; +OP-PROT-016 itself permits explicitly qualified valid native use. Do not impose a +whole-workbook migration on a plain text navigation repair. + +The prior rollout event recorded 17:20Z and an expiry of 19:20Z, while provider +metadata dates its new Doc to 21:58:49Z and its Git successor near 22:00Z. It also +contains a placeholder rather than a source digest. Preserve that event as an +inaccurate chronology/binding record; do not treat it as proof of a valid contemporaneous +lease. This round obtained a fresh actual-time claim before its material changes. +A separate correction event supplies verified dates without rewriting the log. + +## 4. Coverage and rollout state + +This is a targeted critical-path audit, not a completed inventory of the entire +Drive, every registry formula, all branch variants, hidden app schedulers, external +model sessions or all prior decisions. FINDINGS_R2.json records the inspected +sources, precise issue classifications and residual tasks. A keyword such as +"mandatory" or "superseded" is not itself a defect. Evidence of actual harm must +not be inferred merely from the possibility of a misleading interpretation. + +Live changes in this round are limited to this audit's navigation/precedence +clarification and the existing daily task's bounded routing correction. The code +is read-only and author-side tested. Its result is PLAN_CONSISTENT, not permission +to execute, a review verdict, scientific acceptance or verification of remote references. +The original withdrawal review remains open. Nonauthor review of the new rollout +controls and the next observed scheduled pickup remain separate open obligations. + +## 5. Verification and rollback + +Run normal and optimized Python tests, including actual CLI-mutated inputs, the +binding collision, incomplete-cohort refusal, stale commit/lease rejection and a real +Git clean-merge semantic mismatch. Retain failures and actual skip counts. Verify +saved payload hashes and each changed native pointer/configuration by readback. +Do not mark an unchanged entire workspace verified because these tests passed. + +Rollback restores only identified prior navigation/configuration values after a +fresh head/revision check. Retain this successor and its evidence. Do not roll back +mathematical status, resurrect an unsafe proof, delete history, or revive superseded +controls. Reuse the existing R17 Work Events and Review Queue; no second live ledger. + +## Primary technical references + +Google SRE, Canarying Releases: https://sre.google/workbook/canarying-releases/ +GitHub references API: https://docs.github.com/en/rest/git/refs +GitHub pull requests API: https://docs.github.com/en/rest/pulls/pulls +GitHub workflow events: https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows +Google Docs WriteControl: https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/batchUpdate + +These motivate and delimit the engineering controls; they do not adjudicate the +research or authenticate an operator decision. No architecture novelty is claimed. diff --git a/governance/rollout/RECONNAISSANCE_R2.md b/governance/rollout/RECONNAISSANCE_R2.md new file mode 100644 index 000000000..5070d553f --- /dev/null +++ b/governance/rollout/RECONNAISSANCE_R2.md @@ -0,0 +1,34 @@ +# Reconnaissance — ROLLOUT-R2-20260921 + +Scope: risk-proportionate governance adoption, typed identity, scoped publication, +not a mathematical theorem. Inspected 21 September 2026. Primary-source reading. + +Queries executed included: "site.sre.google workbook canarying releases config +rollback"; "docs.github actions secure pin"; "docsGoogle writeControl"; +"site.docs.github.com REST git references update a reference force false fast forward"; +"site.docs.github.com REST pulls merge sha head branch compare base". The first +three are summarized query labels from this round's reconnaissance; the final two +are exact literal queries. No private source text was submitted to web search. + +Google SRE Canarying Releases (https://sre.google/workbook/canarying-releases/) +describes limited release cohorts and evaluation. We apply that idea to material +behavior changes, not to make every link repair wait through a new governance chain. +GitHub's reference API (https://docs.github.com/en/rest/git/refs), Update a reference, +uses force=false to require a fast-forward update. It is not a distributed lock. +The pull-request API (https://docs.github.com/en/rest/pulls/pulls), Merge a pull +request, binds its sha parameter to the PR head; it does not authenticate a Drive +snapshot or guarantee semantic compatibility of a clean merge. The workflow-events +document (https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows), +schedule section, limits scheduled workflows to the default branch. This matters +because the observed default branch lacks the working branch's workflows. + +Google Docs documents.batchUpdate +(https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/batchUpdate) +provides requiredRevisionId guarding. GitHub secure-use guidance +(https://docs.github.com/en/actions/reference/security/secure-use) supports pinned +actions and restricted permissions. Existing read-only CI safeguards are retained. + +Findings are application-specific. No source proves our dependency map complete, +verifies all consumers adopted policy, authenticates independent review, or supplies +a theorem verdict. The new tests are author-side regression evidence. This audit +reuses current R17 authority; broader behavior rollout remains scoped and reviewed. diff --git a/governance/rollout/SYNTHETIC_metadata_plan.json b/governance/rollout/SYNTHETIC_metadata_plan.json new file mode 100644 index 000000000..d20eb46ce --- /dev/null +++ b/governance/rollout/SYNTHETIC_metadata_plan.json @@ -0,0 +1,39 @@ +{ + "schema_version": 1, + "change_id": "SYNTHETIC-METADATA", + "change_kind": "METADATA_REPAIR", + "from_stage": "BASELINE", + "to_stage": "APPLIED_SCOPED", + "policy_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "authority_ref": "SYNTHETIC-AUTHORITY-ONLY", + "target_consumers": [ + "home", + "router" + ], + "coverage_complete": true, + "rollback_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "review_sha256": null, + "effects": [ + "navigation" + ], + "scientific_status_unchanged": true, + "frozen_bytes_preserved": true, + "reactivate_superseded": false, + "blocked_consumers": [], + "observations": [ + { + "consumer": "home", + "mode": "READBACK", + "policy_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "PASS" + }, + { + "consumer": "router", + "mode": "READBACK", + "policy_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "artifact_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "result": "PASS" + } + ] +} diff --git a/governance/rollout/WORK_ORDER_R2.json b/governance/rollout/WORK_ORDER_R2.json new file mode 100644 index 000000000..a33a72a0a --- /dev/null +++ b/governance/rollout/WORK_ORDER_R2.json @@ -0,0 +1,25 @@ +{ + "session_id": "ROLLOUT-R2-20260921-e4ea82e2", + "claim_id": "CLAIM-ROLLOUT-R2-20260921-d1d2c8a8", + "utc": "2026-09-21T22:03:40.424510Z", + "lease_until": "2026-09-22T00:03:40.424510Z", + "authorization_text": "Excellent. Continue to project with ultra effort in all aspects starting with the most critical", + "base_commit": "4353db4aa511062ba7cbfb0f4b2d43180f9d9946", + "authorization_sha256": "b01984629a92796ea7e29fd020b20f36929df31061ea6cdeefa98721ddab30ab", + "allowed": [ + "own audit successor", + "bounded native navigation corrections", + "existing daily task routing correction, cadence/purpose unchanged", + "own PR4 branch code and tests", + "append R17 events and scoped review request" + ], + "excluded": [ + "scientific status changes", + "forced pushes or merges", + "settings or visibility changes", + "global migration", + "new scheduled task", + "independent review credit" + ], + "review": "AUTHOR_SIDE_ONLY" +} diff --git a/tests/test_rollout_guard.py b/tests/test_rollout_guard.py new file mode 100644 index 000000000..56549718f --- /dev/null +++ b/tests/test_rollout_guard.py @@ -0,0 +1,223 @@ +"""Synthetic author-side controls; no review/authority is fabricated.""" +import copy +import importlib.util +import json +import shutil +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +SCRIPT = Path(__file__).resolve().parents[1] / 'tools' / 'rollout_guard.py' +spec = importlib.util.spec_from_file_location('rollout_guard_pilot', SCRIPT) +g = importlib.util.module_from_spec(spec) +spec.loader.exec_module(g) +H = 'a' * 64 + + +def sample(): + return {'schema_version': 1, 'change_id': 'SYNTHETIC-METADATA', 'change_kind': 'METADATA_REPAIR', + 'from_stage': 'BASELINE', 'to_stage': 'APPLIED_SCOPED', 'policy_sha256': H, + 'authority_ref': 'SYNTHETIC-AUTHORITY-ONLY', 'target_consumers': ['home', 'router'], + 'coverage_complete': True, 'rollback_sha256': H, 'review_sha256': None, + 'effects': ['navigation'], 'scientific_status_unchanged': True, + 'frozen_bytes_preserved': True, 'reactivate_superseded': False, 'blocked_consumers': [], + 'observations': [{'consumer': x, 'mode': 'READBACK', 'policy_sha256': H, + 'artifact_sha256': H, 'result': 'PASS'} for x in ('home', 'router')]} + + +class RolloutControls(unittest.TestCase): + def reject(self, change): + p = sample(); change(p) + with self.assertRaises((g.Invalid, ValueError, TypeError)): + g.assess(p) + + def test_small_repair_does_not_require_six_new_stages(self): + result = g.assess(sample()) + self.assertEqual(result['result'], 'PLAN_CONSISTENT') + self.assertFalse(result['live_admission']) + self.assertFalse(result['scientific_acceptance']) + + def test_start_here_24_misses_two_current_keys(self): + self.assertEqual(g.entry_coverage(100, 24, {'withdrawal': 31, 'rollout': 32}, True), ['rollout', 'withdrawal']) + + def test_start_here_31_still_misses_audit(self): + self.assertEqual(g.entry_coverage(100, 31, {'withdrawal': 31, 'rollout': 32}, True), ['rollout']) + + def test_allocated_compact_view_covers_new_rows(self): + self.assertEqual(g.entry_coverage(100, 100, {'withdrawal': 31, 'rollout': 32, 'future': 99}, True), []) + + def test_truncated_discovery_not_complete(self): + with self.assertRaises(g.Invalid): g.entry_coverage(100, 100, {'rollout': 32}, False) + + def test_unknown_grid_bound_fails(self): + with self.assertRaises(g.Invalid): g.entry_coverage(100, 101, {'rollout': 32}, True) + + def test_empty_key_inventory_fails(self): + with self.assertRaises(g.Invalid): g.entry_coverage(100, 100, {}, True) + + def test_out_of_bounds_required_key_fails(self): + with self.assertRaises(g.Invalid): g.entry_coverage(100, 100, {'future': 101}, True) + + def test_boolean_row_rejected(self): + with self.assertRaises(g.Invalid): g.entry_coverage(100, 100, {'future': True}, True) + + def test_binding_letter_a_is_not_globally_typed(self): + self.assertEqual(g.binding_kind('OP-PROT-013@2026-07-26', 'A'), 'RAW_CONTENT') + self.assertEqual(g.binding_kind('OP-PROT-014-v1.0', 'A'), 'METADATA_ONLY') + + def test_binding_letter_b_is_not_globally_typed(self): + self.assertNotEqual(g.binding_kind('OP-PROT-013@2026-07-26', 'B'), g.binding_kind('OP-PROT-014-v1.0', 'B')) + + def test_unqualified_binding_fails(self): + with self.assertRaises(g.Invalid): g.binding_kind('', 'A') + + def test_new_binding_version_needs_explicit_mapping(self): + with self.assertRaises(g.Invalid): g.binding_kind('OP-PROT-014-v2.0', 'A') + + def test_current_authorization_not_revoked_by_unobserved_uptake(self): + g.effective_rule('R17:entry', True, 'R17:entry', ['R16:entry']) + + def test_stricter_old_rule_cannot_resurrect(self): + with self.assertRaises(g.Invalid): g.effective_rule('R17:entry', True, 'R16:entry', ['R16:entry']) + + def test_no_authority_from_newer_name(self): + with self.assertRaises(g.Invalid): g.effective_rule('R18:entry', False, 'R18:entry', []) + + def test_no_global_metadata_block(self): + self.reject(lambda p: p.update(blocked_consumers=['unrelated-math'])) + + def test_no_new_local_block_disguised_as_metadata(self): + self.reject(lambda p: p.update(blocked_consumers=['home'])) + + def test_no_scientific_status_change(self): + self.reject(lambda p: p.update(scientific_status_unchanged=False)) + + def test_no_frozen_edit(self): + self.reject(lambda p: p.update(frozen_bytes_preserved=False)) + + def test_no_retired_control_reactivation(self): + self.reject(lambda p: p.update(reactivate_superseded=True)) + + def test_no_semantic_change_called_metadata(self): + self.reject(lambda p: p.update(effects=['admission'])) + + def test_missing_readback_is_not_applied(self): + self.reject(lambda p: p['observations'].pop()) + + def test_wrong_policy_observation(self): + self.reject(lambda p: p['observations'][0].update(policy_sha256='b' * 64)) + + def test_failed_consumer_is_not_pass(self): + self.reject(lambda p: p['observations'][0].update(result='FAIL')) + + def test_empty_cohort_cannot_pass_vacuously(self): + self.reject(lambda p: p.update(target_consumers=[], observations=[])) + + def test_duplicate_consumer(self): + self.reject(lambda p: p['target_consumers'].append('home')) + + def test_duplicate_observation(self): + self.reject(lambda p: p['observations'].append(p['observations'][0])) + + def test_unknown_schema(self): + self.reject(lambda p: p.update(schema_version=2)) + + def test_boolean_schema_version(self): + self.reject(lambda p: p.update(schema_version=True)) + + def test_unknown_field(self): + self.reject(lambda p: p.update(auto_approve=True)) + + def test_incomplete_coverage(self): + self.reject(lambda p: p.update(coverage_complete=False)) + + def test_material_rollout_cannot_skip_to_global(self): + self.reject(lambda p: p.update(change_kind='BEHAVIOR_CHANGE', from_stage='PROPOSED', to_stage='ACTIVE_GENERAL')) + + def test_material_pilot_needs_actual_supplied_pilot_observations(self): + self.reject(lambda p: p.update(change_kind='BEHAVIOR_CHANGE', from_stage='SHADOW', to_stage='PILOT')) + + def test_supplied_shadow_plan_remains_non_authoritative(self): + p = sample(); p.update(change_kind='BEHAVIOR_CHANGE', from_stage='PROPOSED', to_stage='SHADOW') + for x in p['observations']: x['mode'] = 'SHADOW' + self.assertFalse(g.assess(p)['live_admission']) + + def test_review_stage_needs_review_reference(self): + p = sample(); p.update(change_kind='BEHAVIOR_CHANGE', from_stage='PILOT', to_stage='REVIEWED') + p['observations'] = [dict(x, mode=m) for x in p['observations'] for m in ('SHADOW', 'PILOT')] + with self.assertRaises(g.Invalid): g.assess(p) + + def test_containment_not_automatic_global_replacement(self): + self.reject(lambda p: p.update(change_kind='EMERGENCY_CONTAINMENT')) + + def test_fresh_pinned_execution_observation(self): + s = {'base_head': 'a'*40, 'candidate_head': 'b'*40, 'policy_sha256': H} + g.execution_snapshot(s, s, '2026-09-21T22:00:00Z', '2026-09-22T00:00:00Z', '2026-09-21T23:00:00Z') + + def test_changed_base_head_rejected_even_without_text_conflict(self): + s = {'base_head': 'a'*40, 'candidate_head': 'b'*40, 'policy_sha256': H} + with self.assertRaises(g.Invalid): + g.execution_snapshot(s, dict(s, base_head='c'*40), '2026-09-21T22:00:00Z', '2026-09-22T00:00:00Z', '2026-09-21T23:00:00Z') + + def test_expired_lease_cannot_be_renewed_retroactively(self): + s = {'base_head': 'a'*40, 'candidate_head': 'b'*40, 'policy_sha256': H} + with self.assertRaises(g.Invalid): + g.execution_snapshot(s, s, '2026-09-21T17:20:00Z', '2026-09-21T19:20:00Z', '2026-09-21T22:00:00Z') + + def test_timestamp_requires_timezone(self): + with self.assertRaises(g.Invalid): g.timestamp('2026-09-21T22:00:00') + + def test_duplicate_json_keys_rejected(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d)/'a.json'; p.write_text('{"a":1,"a":2}') + with self.assertRaises(g.Invalid): g.load(p) + + def test_cli_checks_actual_mutated_file_in_both_modes(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d)/'plan.json' + for valid in (True, False): + p = sample() + if not valid: p['scientific_status_unchanged'] = False + path.write_text(json.dumps(p)) + for mode in ([], ['-O']): + r = subprocess.run([sys.executable, *mode, str(SCRIPT), str(path)], capture_output=True) + self.assertEqual(r.returncode, 0 if valid else 2, r.stderr) + + def test_real_git_clean_merge_can_break_semantic_interface(self): + if shutil.which('git') is None: + self.skipTest('git unavailable; no merge experiment claimed') + with tempfile.TemporaryDirectory() as d: + root = Path(d) + def git(*args): + return subprocess.run(['git', *args], cwd=root, capture_output=True, text=True, check=True).stdout.strip() + git('init', '-q', '-b', 'base') + git('config', 'user.name', 'Synthetic test') + git('config', 'user.email', 'synthetic@example.invalid') + (root/'producer.json').write_text(json.dumps({'interface': 1})) + (root/'consumer.json').write_text(json.dumps({'expects': 1, 'uses': 'old'})) + git('add', '.'); git('commit', '-qm', 'synthetic baseline') + baseline = git('rev-parse', 'HEAD') + git('checkout', '-qb', 'producer-change') + (root/'producer.json').write_text(json.dumps({'interface': 2})) + git('commit', '-qam', 'new producer interface') + git('checkout', '-qb', 'consumer-change', baseline) + (root/'consumer.json').write_text(json.dumps({'expects': 1, 'uses': 'new-dependent'})) + git('commit', '-qam', 'old interface still assumed') + git('merge', '--no-ff', '-m', 'syntactically clean merge', 'producer-change') + self.assertNotEqual(json.loads((root/'producer.json').read_text())['interface'], + json.loads((root/'consumer.json').read_text())['expects']) + self.assertEqual(git('status', '--porcelain'), '') + + def test_missing_file_fails_cli(self): + r = subprocess.run([sys.executable, str(SCRIPT), '/nonexistent/rollout-plan.json'], capture_output=True) + self.assertEqual(r.returncode, 2) + + def test_nonfinite_json_rejected(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d)/'a.json'; p.write_text('{"a":NaN}') + with self.assertRaises(g.Invalid): g.load(p) + + +if __name__ == '__main__': unittest.main() diff --git a/tools/rollout_guard.py b/tools/rollout_guard.py new file mode 100644 index 000000000..f43248943 --- /dev/null +++ b/tools/rollout_guard.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Read-only, author-side rollout-plan controls. Not a policy or truth engine. + +Explicit declarations and supplied observation references are checked, not +cryptographically authenticated. No network, writes, execution of referenced +artifacts, deployment, scientific decision, or live admission is performed. +""" +from __future__ import annotations +import argparse +import hashlib +import json +import re +import sys +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +class Invalid(ValueError): + """A declared plan does not satisfy this pilot's structural controls.""" + + +def require(ok: bool, why: str) -> None: + if not ok: + raise Invalid(why) + + +def fields(obj: Any, names: set[str], where: str) -> None: + require(isinstance(obj, dict) and set(obj) == names, f'{where}: missing/unknown fields') + + +def nonempty(value: Any, where: str) -> None: + require(isinstance(value, str) and bool(value.strip()), f'{where}: empty/non-string') + + +def sha(value: Any, where: str) -> None: + require(isinstance(value, str) and re.fullmatch('[0-9a-f]{64}', value) is not None, + f'{where}: expected full SHA-256') + + +def ids(value: Any, where: str) -> None: + require(isinstance(value, list) and bool(value), f'{where}: nonempty list required') + for item in value: + nonempty(item, where) + require(len(value) == len(set(value)), f'{where}: duplicate IDs') + + +def timestamp(value: Any) -> datetime: + nonempty(value, 'UTC timestamp') + parsed = datetime.fromisoformat(value.replace('Z', '+00:00')) + require(parsed.tzinfo is not None, 'timezone required') + return parsed.astimezone(timezone.utc) + + +# Version-scoped documentary vocabulary, NOT a converter of old scientific data. +BINDINGS = { + 'OP-PROT-013@2026-07-26': {'A': 'RAW_CONTENT', 'B': 'EMBEDDED_PAYLOAD', 'C': 'NATIVE_EXPORT'}, + 'OP-PROT-014-v1.0': {'A': 'METADATA_ONLY', 'B': 'MARKER_BODY', 'C': 'NATIVE_EXPORT', + 'D': 'RAW_CONTENT', 'E': 'EMBEDDED_PAYLOAD'}, +} + + +def binding_kind(standard: str, label: str) -> str: + require(standard in BINDINGS, 'unknown/unqualified binding standard') + require(label in BINDINGS[standard], 'unknown binding class for this standard') + return BINDINGS[standard][label] + + +def entry_coverage(capacity: int, read_end: int, key_rows: dict[str, int], + complete: bool) -> list[str]: + """Check a supplied bounded navigation observation; never infer unseen rows.""" + require(type(capacity) is int and capacity > 0, 'invalid allocated row count') + require(type(read_end) is int and 0 < read_end <= capacity, 'invalid read range') + require(complete is True, 'partial/truncated discovery cannot establish coverage') + require(isinstance(key_rows, dict) and bool(key_rows), 'empty required key inventory') + for key, row in key_rows.items(): + nonempty(key, 'navigation key') + require(type(row) is int and 1 <= row <= capacity, 'key outside allocation') + return sorted(key for key, row in key_rows.items() if row > read_end) + + +def execution_snapshot(expected: dict, observed: dict, claim_time: str, + expires: str, now: str) -> None: + """Validate a preflight observation. This is NOT compare-and-swap.""" + names = {'base_head', 'candidate_head', 'policy_sha256'} + fields(expected, names, 'expected snapshot') + fields(observed, names, 'observed snapshot') + for obj in (expected, observed): + sha(obj['policy_sha256'], 'policy') + for key in ('base_head', 'candidate_head'): + require(isinstance(obj[key], str) and re.fullmatch('[0-9a-f]{40}', obj[key]) is not None, + 'invalid Git commit identity') + require(expected == observed, 'stale source/base/candidate: reconcile this target') + start, stop, clock = map(timestamp, (claim_time, expires, now)) + require(start <= clock < stop, 'future or expired claim; new claim required') + + +def effective_rule(current: str, authority_verified: bool, selected: str, + superseded: list[str]) -> None: + """An uptake audit cannot undo an already-authorized clause replacement.""" + nonempty(current, 'current rule') + nonempty(selected, 'selected rule') + require(authority_verified is True, 'authority must be resolved outside this checker') + require(isinstance(superseded, list), 'superseded clauses must be explicit') + require(selected == current and selected not in superseded, + 'retired control cannot be revived through compatibility or stricter-wins') + + +STAGES = ['PROPOSED', 'SHADOW', 'PILOT', 'REVIEWED', 'ACTIVE_SCOPED', 'ACTIVE_GENERAL'] + + +def assess(plan: Any) -> dict: + fields(plan, {'schema_version', 'change_id', 'change_kind', 'from_stage', 'to_stage', + 'policy_sha256', 'authority_ref', 'target_consumers', 'observations', + 'coverage_complete', 'rollback_sha256', 'review_sha256', 'effects', + 'scientific_status_unchanged', 'frozen_bytes_preserved', + 'reactivate_superseded', 'blocked_consumers'}, 'plan') + require(type(plan['schema_version']) is int and plan['schema_version'] == 1, + 'unsupported schema version') + nonempty(plan['change_id'], 'change_id') + sha(plan['policy_sha256'], 'policy') + sha(plan['rollback_sha256'], 'rollback') + nonempty(plan['authority_ref'], 'authority_ref') + ids(plan['target_consumers'], 'target_consumers') + cohort = set(plan['target_consumers']) + require(plan['coverage_complete'] is True, 'declared cohort coverage incomplete') + require(plan['scientific_status_unchanged'] is True, 'scientific decision is outside this pilot') + require(plan['frozen_bytes_preserved'] is True, 'frozen evidence cannot be modified') + require(plan['reactivate_superseded'] is False, 'compatibility cannot resurrect retired controls') + require(isinstance(plan['blocked_consumers'], list), 'blocked consumers must be explicit') + require(len(set(plan['blocked_consumers'])) == len(plan['blocked_consumers']), 'duplicate blocked IDs') + require(set(plan['blocked_consumers']) <= cohort, 'block escapes the named cohort') + ids(plan['effects'], 'effects') + require(set(plan['effects']) <= {'navigation', 'documentation', 'scheduling', 'admission', 'publication'}, + 'unknown effect or scientific/permission change') + require(isinstance(plan['observations'], list), 'observations must be a list') + passed: dict[str, set[str]] = {x: set() for x in cohort} + seen = set() + for observation in plan['observations']: + fields(observation, {'consumer', 'mode', 'policy_sha256', 'artifact_sha256', 'result'}, 'observation') + who, mode = observation['consumer'], observation['mode'] + require(who in cohort, 'observation outside target cohort') + require(mode in {'SHADOW', 'PILOT', 'READBACK'}, 'unknown observation mode') + require((who, mode) not in seen, 'duplicate observation') + seen.add((who, mode)) + require(observation['policy_sha256'] == plan['policy_sha256'], 'observation has stale policy identity') + sha(observation['artifact_sha256'], 'observation artifact') + require(observation['result'] == 'PASS', 'failed/unknown consumer observation') + passed[who].add(mode) + old, new, kind = plan['from_stage'], plan['to_stage'], plan['change_kind'] + if kind == 'METADATA_REPAIR': + require((old, new) == ('BASELINE', 'APPLIED_SCOPED'), 'metadata repair has a separate bounded path') + require(set(plan['effects']) <= {'navigation', 'documentation'}, 'metadata repair masks changed behavior') + require(not plan['blocked_consumers'], 'metadata repair may not introduce a block') + required = {'READBACK'} + elif kind == 'BEHAVIOR_CHANGE': + require(old in STAGES and new in STAGES, 'unknown material rollout stage') + require(STAGES.index(new) == STAGES.index(old) + 1, 'material change skipped a stage') + require(not plan['blocked_consumers'], 'behavior rollout cannot impose containment blocks') + target = STAGES.index(new) + required = {'SHADOW'} if target >= 1 else set() + if target >= 2: + required.add('PILOT') + if target >= 3: + sha(plan['review_sha256'], 'material rollout review') + if target >= 4: + required.add('READBACK') + else: + # Containment is not smuggled into this author-side rollout validator. + raise Invalid('unsupported kind; containment requires its own exact defect/authority record') + require(all(required <= modes for modes in passed.values()), 'missing required per-consumer observations') + return {'result': 'PLAN_CONSISTENT', 'authority': 'NONE', 'live_admission': False, + 'scientific_acceptance': False, 'consumer_count': len(cohort), + 'declared_stage': new, 'limits': [ + 'Reference authenticity, authority, and scope completeness require external review.', + 'A preflight read is not an atomic commit guard or a deployment.', + 'This validates the supplied cohort only; it makes no global adoption claim.']} + + +def load(path: Path) -> Any: + def pairs(items): + out = {} + for k, v in items: + require(k not in out, 'duplicate JSON key') + out[k] = v + return out + def constant(value): + raise Invalid('nonfinite JSON is not supported') + return json.loads(path.read_text(encoding='utf-8'), object_pairs_hook=pairs, parse_constant=constant) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('plan', type=Path) + args = parser.parse_args(argv) + try: + print(json.dumps(assess(load(args.plan)), indent=2, sort_keys=True)) + return 0 + except (Invalid, ValueError, TypeError, KeyError, OSError, RecursionError) as error: + print(f'ROLLOUT PLAN HOLD: {error}', file=sys.stderr) + return 2 + + +if __name__ == '__main__': + raise SystemExit(main())