"""Post-initial-proof controls; preserve run.py and every earlier receipt unchanged."""
import importlib.util
from pathlib import Path
import sys
sys.dont_write_bytecode = True

SOURCE = Path(__file__).with_name('run.py')
spec = importlib.util.spec_from_file_location('initial302step2', SOURCE)
p = importlib.util.module_from_spec(spec)
spec.loader.exec_module(p)
for original in ('meet', 'guards', 'starve', 'attach'):
    p.SCOPES[original + '-restored'] = p.SCOPES[original]

class FollowupPhase(p.Phase):
    def prepare(self):
        super().prepare()
        self.receipt['followup_driver_sha256'] = p.g.digest(Path(__file__))
        self.receipt['inherited_driver_sha256'] = p.g.digest(SOURCE)
        self.flush()

    def execute(self):
        if self.name == 'meet-red-placement':
            scope, expression = p.SCOPES['meet']
            selected = self.inventory('inventory',['--locked',*scope],expression)
            if len(selected) != 1:
                raise RuntimeError('mutant must select exactly the lifecycle regression')
            self.run('tests',['cargo','nextest','run','--locked',*scope,'--profile','ci-windows',
                '--test-threads','2','--retries','0','--no-fail-fast','-E',expression],expected=100)
            evidence = (self.dir/'tests.stderr').read_text(encoding='utf-8')
            if 'two synchronous meet binds starved broker workers' not in evidence:
                raise RuntimeError('mutant failed for the wrong reason; expected lifecycle assertion absent')
            self.receipt['interpretation'] = 'Expected synthetic routing-mutant assertion failure, not field RCA or a passing test.'
        else:
            if self.name == 'checks':
                # The retained xtask was valid for pool control only. Rebuild it
                # so its compile-time repo_root resolves to this exact remedy tree.
                self.run('build-checker',['cargo','build','--locked','-p','xtask','--bin','xtask'])
            super().execute()

p.Phase = FollowupPhase
if __name__ == '__main__':
    sys.exit(p.main())
