"""Fixed T05 remote script; source preparation never dispatches it."""
PROGRAM = '\nimport copy,datetime,hashlib,json,os,re,subprocess,sys\nif sys.flags.optimize:raise RuntimeError(\'optimized interpreter refused\')\npayload=json.loads(__PAYLOAD__)\nexec(__GUARD__)\nphase=payload[\'phase\']\nif phase not in (\'drill-backup\',\'cutover-backup\',\'drill-copy\',\'cutover-copy\',\'release\',\'verify\',\'rollback\',\'rollback-verify\'):raise ValueError(\'fixed native phase required\')\ndeadline=datetime.datetime.fromisoformat(\'2026-10-12T23:59:59+00:00\')\ndef require(value,reason):\n if not value:raise ValueError(reason)\nrequire(datetime.datetime.now(datetime.timezone.utc)<deadline,\'execution window expired\')\nenv={**os.environ,\'KUBECONFIG\':\'/etc/rancher/k3s/k3s.yaml\'}\ndef run(argv,body=None,timeout=90):\n return subprocess.run(argv,input=body,text=True,capture_output=True,timeout=timeout,env=env)\ndef read(kind,name,namespace):\n result=run([\'kubectl\',\'get\',kind,name,\'-n\',namespace,\'-o\',\'json\'])\n require(result.returncode==0,\'fixed metadata read refused\')\n return json.loads(result.stdout)\nsealed=payload[\'sealed\']; dependencies=payload[\'dependencies\']\nlive=read(\'deployment\',\'informed-decision\',\'informed-decision\')\ncm=read(\'configmap\',\'informed-decision-runtime-6c221878d051\',\'informed-decision\')\npvc=read(\'pvc\',\'informed-decision-data\',\'informed-decision\')\ncheck_dependencies(cm,pvc,dependencies)\napp=read(\'application\',\'informed-decision\',\'argocd\')\nrequire(app[\'metadata\'][\'uid\']==\'499868f2-eabc-4df4-ae31-b89ce58d750d\',\'Application UID changed\')\nrequire(app[\'spec\'][\'source\'][\'repoURL\']==\'https://forgejo.coulomb.social/coulomb/informed-decision.git\'\n and app[\'spec\'][\'source\'][\'path\']==\'deploy/lifecycle\'\n and app[\'spec\'][\'destination\']=={\'namespace\':\'informed-decision\',\'server\':\'https://kubernetes.default.svc\'}\n and app[\'spec\'].get(\'syncPolicy\',{}).get(\'automated\') is None\n and set(app[\'spec\'][\'source\'])=={\'repoURL\',\'path\',\'targetRevision\'} and not app[\'spec\'].get(\'sources\'),\'Application owner/scope changed\')\nexpected=copy.deepcopy(sealed)\nif phase==\'verify\':expected[\'spec\'][\'template\'][\'spec\'][\'containers\'][0][\'image\']=CANDIDATE\nif phase==\'rollback\':\n image=live[\'spec\'][\'template\'][\'spec\'][\'containers\'][0][\'image\']\n require(image in (BASE,CANDIDATE),\'rollback image is outside same-schema pair\')\n expected[\'spec\'][\'template\'][\'spec\'][\'containers\'][0][\'image\']=image\ncheck_current(live,expected)\nif phase!=\'rollback\':\n require(live.get(\'status\',{}).get(\'readyReplicas\')==1\n  and live[\'status\'].get(\'updatedReplicas\')==1\n  and live[\'status\'].get(\'observedGeneration\')==live[\'metadata\'][\'generation\'],\'service not Ready1\')\ntarget=payload[\'source_revision\'] if phase==\'verify\' else \'c96b0c6d881e855d1d158003c6de90ef390262e2\'\nif phase==\'rollback\':require(app[\'spec\'][\'source\'][\'targetRevision\'] in (target,payload[\'source_revision\']),\'rollback source is outside pair\')\nelse:require(app[\'spec\'][\'source\'][\'targetRevision\']==target,\'unexpected source pin\')\nresult={\'phase\':phase,\'all_checks_pass\':False,\'raw_output_withheld\':True,\n \'native_approval_verified_by_root\':payload[\'approval\'],\'native_authenticated_grant\':False}\ntry:\n if phase in (\'drill-backup\',\'cutover-backup\',\'drill-copy\',\'cutover-copy\',\'release\',\'verify\',\'rollback-verify\'):\n  podlist=run([\'kubectl\',\'get\',\'pods\',\'-n\',\'informed-decision\',\'-l\',\'app.kubernetes.io/name=informed-decision\',\'-o\',\'json\'])\n  require(podlist.returncode==0,\'pod metadata query refused\')\n  pods=[p for p in json.loads(podlist.stdout)[\'items\'] if not p[\'metadata\'].get(\'deletionTimestamp\')]\n  require(len(pods)==1,\'exact single live owner pod required\');pod=pods[0]\n  require(pod[\'status\'].get(\'phase\')==\'Running\' and len(pod[\'spec\'][\'containers\'])==1\n   and pod[\'spec\'][\'containers\'][0][\'image\']==expected[\'spec\'][\'template\'][\'spec\'][\'containers\'][0][\'image\']\n   and len(pod[\'status\'].get(\'containerStatuses\',[]))==1\n   and pod[\'status\'][\'containerStatuses\'][0].get(\'name\')==\'informed-decision\'\n   and pod[\'status\'][\'containerStatuses\'][0].get(\'ready\') is True\n   and pod[\'status\'][\'containerStatuses\'][0].get(\'imageID\',\'\').endswith(\'@\'+expected[\'spec\'][\'template\'][\'spec\'][\'containers\'][0][\'image\'].split(\'@\',1)[1]),\'owner pod readiness/image changed\')\n  if phase in (\'drill-backup\',\'drill-copy\',\'cutover-backup\',\'cutover-copy\',\'release\'):require(pod[\'metadata\'][\'uid\']==\'c4cb1550-feda-4097-9de4-d891a657b662\',\'original backup Pod identity changed\')\n  template=expected[\'spec\'][\'template\'][\'spec\']\n  controlled=set(template)|{\'initContainers\',\'hostNetwork\',\'hostPID\',\'hostIPC\',\'runtimeClassName\',\'shareProcessNamespace\'}\n  require(all(pod[\'spec\'].get(key)==template.get(key) for key in controlled),\'actual owner Pod configuration drifted\')\n  owners=pod[\'metadata\'].get(\'ownerReferences\',[]);require(len(owners)==1 and owners[0][\'kind\']==\'ReplicaSet\',\'pod owner chain changed\')\n  rs=read(\'replicaset\',owners[0][\'name\'],\'informed-decision\')\n  require(rs[\'metadata\'][\'uid\']==owners[0][\'uid\'] and any(o.get(\'uid\')==sealed[\'metadata\'][\'uid\']\n   and o.get(\'kind\')==\'Deployment\' for o in rs[\'metadata\'].get(\'ownerReferences\',[])),\'ReplicaSet ownership changed\')\n  inner=r"""\nimport hashlib,json,os,stat,subprocess,sys\nif sys.flags.optimize:raise RuntimeError(\'optimized interpreter refused\')\nexec(__READONLY__)\nexec(__SAFETY__)\naction=__ACTION__;db=\'/data/private/review.sqlite\';folder=\'/data/private/zlib85091-r1\'\ndef require(v,r):\n if not v:raise ValueError(r)\nrequire(os.getuid()==10001 and os.getgid()==10001,\'native owner UID/GID required\')\ndef private(p,directory=False):\n s=os.lstat(p);require((stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode))\n  and s.st_uid==10001 and stat.S_IMODE(s.st_mode)==(0o700 if directory else 0o600)\n  and (directory or s.st_nlink==1),\'private native custody required\')\nprivate(\'/data/private\',True);private(db)\nbaseline=counts(inspect_readonly(db)) # MUST precede any Store/admin open.\nif action in (\'drill-backup\',\'cutover-backup\'):\n size=os.stat(db).st_size\n if os.path.exists(db+\'-wal\'):size+=os.stat(db+\'-wal\').st_size\n v=os.statvfs(\'/data/private\');free=v.f_bavail*v.f_frsize\n require(size>0 and size<=512*1024**2 and free>=size*(2 if action==\'drill-backup\' else 1)+16*1024**2,\'bounded native snapshot capacity required\')\n if action==\'drill-backup\':\n  require(not os.path.lexists(folder),\'native case directory must be unique\')\n  os.mkdir(folder,0o700);os.chmod(folder,0o700)\n private(folder,True)\n filename=\'drill.sqlite\' if action==\'drill-backup\' else \'cutover.sqlite\';output=folder+\'/\'+filename\n require(not os.path.lexists(output),\'snapshot output must be unique\')\n admin=subprocess.run([\'informed-decision-admin\',\'backup\',\'--db\',db,\'--output\',output],capture_output=True,text=True,timeout=120)\n require(admin.returncode==0 and json.loads(admin.stdout)=={\'status\':\'backed_up\',\'consistent_snapshot\':True},\'backup completion not verified; do not retry\')\n private(output)\n for suffix in (\'-wal\',):\n  require(not os.path.exists(output+suffix) or os.stat(output+suffix).st_size==0,\'snapshot has WAL frames; immutable read refused\')\n digest=hashlib.sha256()\n with open(output,\'rb\') as stream:\n  for block in iter(lambda:stream.read(1024**2),b\'\'):digest.update(block)\n frozen_digest=digest.hexdigest()\n snapshot=counts(inspect_closed_snapshot(output,frozen_digest))\n size=os.stat(output).st_size;require(0<size<=512*1024**2,\'snapshot outside bounded copy size\')\n digest=hashlib.sha256()\n with open(output,\'rb\') as stream:\n  for block in iter(lambda:stream.read(1024**2),b\'\'):digest.update(block)\n print(json.dumps({\'all_checks_pass\':True,\'source_readonly_baseline\':baseline,\'snapshot_readonly\':snapshot,\'snapshot_sha256\':digest.hexdigest(),\'snapshot_bytes\':size,\'snapshot_file\':filename,\'native_parent_private\':True,\'native_uid\':os.getuid()}))\nelif action in (\'verify\',\'release\',\'rollback-verify\'):\n proof={\'all_checks_pass\':True,\'live_readonly_schema_integrity_counts\':baseline,\'live_counts_may_include_concurrent_commits\':True}\n if action==\'verify\':\n  import urllib.request\n  module=\'/opt/venv/lib/python3.12/site-packages/informed_decision/policy.py\';info=os.lstat(module)\n  require(stat.S_ISREG(info.st_mode) and info.st_uid==0 and stat.S_IMODE(info.st_mode)==0o644,\'installed policy metadata differs\')\n  with open(module,\'rb\') as source:module_digest=hashlib.sha256(source.read()).hexdigest()\n  require(module_digest==\'9d7c1be4cb6199d14ef0aaead5f85951f45b0ccbd7c800a7fde922a253566b62\',\'installed source module differs\')\n  purpose=subprocess.run([sys.executable,\'-\'],input=__PURPOSE__,text=True,capture_output=True,timeout=30)\n  require(purpose.returncode==0,\'installed native-placement purpose checks failed\')\n  tested=json.loads(purpose.stdout)\n  require(tested=={\'installed_image_purpose_variants\':10,\'binding_forms_allowed\':2,\'advisory_or_malformed_refused\':8,\'synthetic_only\':True,\'native_provider\':False},\'purpose result differs\')\n  class NoRedirect(urllib.request.HTTPRedirectHandler):\n   def redirect_request(self,*args,**kwargs):raise ValueError(\'health redirect refused\')\n  opener=urllib.request.build_opener(NoRedirect());statuses={}\n  for route in (\'/healthz\',\'/readyz\'):\n   with opener.open(\'http://127.0.0.1:8080\'+route,timeout=10) as response:\n    require(response.status==200 and len(response.read(8193))<=8192,\'bounded health check refused\');statuses[route]=200\n  zlib_expected=__ZLIB__;require(zlib_expected[\'zlib_package\']==\'1.3.2-r1\',\'exact fixed package proof required\');installed_zlib={}\n  for relative,meta in zlib_expected[\'files\'].items():\n   require(relative in (\'lib/apk/db/installed\',\'usr/lib/libz.so.1.3.2\'),\'fixed zlib source path required\')\n   path=\'/\'+relative;info=os.lstat(path);require(meta[0]==\'file\' and stat.S_ISREG(info.st_mode) and stat.S_IMODE(info.st_mode)==meta[1] and info.st_uid==meta[2] and info.st_gid==meta[3],\'installed zlib file metadata differs\')\n   with open(path,\'rb\') as handle:digest=hashlib.sha256(handle.read()).hexdigest()\n   require(digest==meta[4],\'installed zlib file digest differs\');installed_zlib[relative]=digest\n  proof.update(installed_zlib_files=installed_zlib,zlib_package=\'1.3.2-r1\')\n  proof.update(installed_purpose_checks=tested,policy_sha256=module_digest,policy_mode=\'0644\',policy_uid=0,health_statuses=statuses,native_provider_probe=False)\n print(json.dumps(proof))\nelif action in (\'drill-copy\',\'cutover-copy\'):\n private(folder,True);filename=\'drill.sqlite\' if action==\'drill-copy\' else \'cutover.sqlite\';output=folder+\'/\'+filename;private(output)\n identity=__SNAPSHOT__;require(isinstance(identity,dict) and identity.get(\'snapshot_file\')==filename,\'recorded original frozen snapshot identity required\')\n snapshot=counts(inspect_closed_snapshot(output,identity[\'snapshot_sha256\']));size=os.stat(output).st_size;require(size==identity[\'snapshot_bytes\'] and 0<size<=512*1024**2,\'snapshot size outside frozen bound\')\n require(snapshot==identity[\'snapshot_readonly\'],\'frozen snapshot proof differs\')\n digest=hashlib.sha256()\n with open(output,\'rb\') as stream:\n  for block in iter(lambda:stream.read(1024**2),b\'\'):digest.update(block)\n print(json.dumps({\'all_checks_pass\':True,\'snapshot_file\':filename,\'snapshot_bytes\':size,\'snapshot_sha256\':digest.hexdigest(),\'snapshot_readonly\':snapshot}))\nelse:raise ValueError(\'fixed native backup/verify phase required\')\n"""\n  # Strip the CLI branch: exec only the verified stdlib function, never Store.\n  readonly=payload[\'readonly\'].split("if __name__ == \'__main__\':",1)[0]\n  inner=inner.replace(\'__READONLY__\',repr(readonly)).replace(\'__SAFETY__\',repr(payload[\'receipt_safety\'])).replace(\'__ACTION__\',repr(\'drill-copy\' if phase==\'drill-copy\' else phase)).replace(\'__PURPOSE__\',repr(payload[\'purpose_checks\'])).replace(\'__SNAPSHOT__\',repr(payload.get(\'snapshot_identity\'))).replace(\'__ZLIB__\',repr(payload[\'installed_zlib\']))\n  p=run([\'kubectl\',\'exec\',\'-i\',\'-n\',\'informed-decision\',pod[\'metadata\'][\'name\'],\'-c\',\'informed-decision\',\'--\',\'python\',\'-\'],inner,150)\n  require(p.returncode==0,\'native phase outcome unverified; raw output withheld, do not retry\')\n  outcome=json.loads(p.stdout);require(outcome.get(\'all_checks_pass\') is True,\'native phase gate refused\')\n  result.update(outcome,pod_name=pod[\'metadata\'][\'name\'],pod_uid=pod[\'metadata\'][\'uid\'])\n if phase in (\'release\',\'rollback\'):\n  node_read=run([\'kubectl\',\'get\',\'nodes\',\'-o\',\'json\']);require(node_read.returncode==0,\'node metadata unavailable\')\n  nodes=json.loads(node_read.stdout)[\'items\'];require(len(nodes)==1,\'one target node required\');node=nodes[0]\n  require(any(a.get(\'address\')==\'92.205.62.239\' for a in node[\'status\'][\'addresses\']),\'target node address changed\')\n  conditions={c[\'type\']:c[\'status\'] for c in node[\'status\'][\'conditions\']}\n  require(conditions.get(\'Ready\')==\'True\' and all(conditions.get(k)==\'False\' for k in (\'MemoryPressure\',\'DiskPressure\',\'PIDPressure\')),\'node unhealthy or pressured\')\n  description=run([\'kubectl\',\'describe\',\'node\',node[\'metadata\'][\'name\']]);require(description.returncode==0,\'headroom capture unavailable\')\n  table=description.stdout.split(\'Allocated resources:\',1)[1];requested=int(re.search(r\'cpu\\s+(\\d+)m\',table).group(1));alloc=node[\'status\'][\'allocatable\'][\'cpu\'];capacity=int(alloc[:-1]) if alloc.endswith(\'m\') else int(alloc)*1000\n  require(requested<=capacity,\'Recreate requested CPU exceeds capacity\')\n  require(not app.get(\'operation\') and app.get(\'status\',{}).get(\'operationState\',{}).get(\'phase\') not in (\'Running\',\'Terminating\'),\'existing Argo operation must be settled\')\n  destination=payload[\'source_revision\'] if phase==\'release\' else \'c96b0c6d881e855d1d158003c6de90ef390262e2\'\n  body=copy.deepcopy(payload[\'candidate\'] if phase==\'release\' else payload[\'rollback\'])\n  dry=run([\'kubectl\',\'apply\',\'--dry-run=server\',\'-f\',\'-\',\'-o\',\'json\'],json.dumps(body))\n  require(dry.returncode==0,\'fresh owner server admission refused\')\n  admitted=json.loads(dry.stdout);wanted=copy.deepcopy(sealed)\n  wanted[\'spec\'][\'template\'][\'spec\'][\'containers\'][0][\'image\']=CANDIDATE if phase==\'release\' else BASE\n  require(projection(admitted)==wanted,\'dry-run changed anything beyond exact image\')\n  diff=run([\'kubectl\',\'diff\',\'-f\',\'-\'],json.dumps(body));require(diff.returncode in (0,1),\'client diff unavailable\')\n  operation={\'initiatedBy\':{\'username\':\'custodian-codex\'},\'sync\':{\'revision\':destination,\'prune\':False,\n   \'resources\':[{\'group\':\'apps\',\'kind\':\'Deployment\',\'name\':\'informed-decision\',\'namespace\':\'informed-decision\'}]}}\n  patch=[{\'op\':\'test\',\'path\':\'/metadata/uid\',\'value\':app[\'metadata\'][\'uid\']},\n   {\'op\':\'test\',\'path\':\'/metadata/resourceVersion\',\'value\':app[\'metadata\'][\'resourceVersion\']},\n   {\'op\':\'test\',\'path\':\'/spec/source/targetRevision\',\'value\':app[\'spec\'][\'source\'][\'targetRevision\']},\n   {\'op\':\'replace\',\'path\':\'/spec/source/targetRevision\',\'value\':destination},\n   {\'op\':\'add\',\'path\':\'/operation\',\'value\':operation}]\n  argv=[\'kubectl\',\'patch\',\'application\',\'informed-decision\',\'-n\',\'argocd\',\'--type=json\',\'--patch-file=/dev/stdin\',\'-o\',\'name\']\n  patchdry=run(argv+[\'--dry-run=server\'],json.dumps(patch));require(patchdry.returncode==0,\'Application operation dry-run refused\')\n  change=run(argv,json.dumps(patch))\n  require(change.returncode==0,\'Application patch outcome ambiguous; do not retry\')\n  result.update(all_checks_pass=True,operation_requested=True,source_revision=destination,\n   resources=operation[\'sync\'][\'resources\'],prune=False,rollout_verified=False,\n   latest_live_database_retained=True,client_diff_sha256=hashlib.sha256(diff.stdout.encode()).hexdigest())\n if phase in (\'verify\',\'rollback-verify\'):\n  op=app.get(\'status\',{}).get(\'operationState\',{});sync=op.get(\'operation\',{}).get(\'sync\',{})\n  intent=payload.get(\'operation_intent\');require(isinstance(intent,dict) and intent.get(\'state\')==\'COMPLETE\',\'verified matching operation intent required\')\n  request=intent.get(\'result\',{});require(request.get(\'operation_requested\') is True and request.get(\'prune\') is False and request.get(\'source_revision\')==target,\'recorded request must explicitly disable prune\')\n  started=datetime.datetime.fromisoformat(intent[\'started_at\']);finished=datetime.datetime.fromisoformat(op.get(\'finishedAt\',\'\').replace(\'Z\',\'+00:00\'));observed_start=datetime.datetime.fromisoformat(op.get(\'startedAt\',\'\').replace(\'Z\',\'+00:00\'))\n  require(started.tzinfo is not None and observed_start.tzinfo is not None and finished.tzinfo is not None and started<=observed_start<=finished,\'operation completion is not from this attempt\')\n  require(op.get(\'phase\')==\'Succeeded\' and sync.get(\'revision\')==target and (\'prune\' not in sync or sync[\'prune\'] is False)\n   and op.get(\'operation\',{}).get(\'initiatedBy\')=={\'username\':\'custodian-codex\'}\n   and sync.get(\'resources\')==request.get(\'resources\')==[{\'group\':\'apps\',\'kind\':\'Deployment\',\'name\':\'informed-decision\',\'namespace\':\'informed-decision\'}],\'exact native Argo operation completion unverified\')\n  synced=op.get(\'syncResult\',{});require(synced.get(\'revision\')==target and len(synced.get(\'resources\',[]))==1,\'matching single-object sync result required\')\n  resource=synced[\'resources\'][0];require(all(resource.get(k)==v for k,v in request[\'resources\'][0].items()) and resource.get(\'status\')==\'Synced\',\'exact Deployment sync result required\')\n  require(live[\'status\'].get(\'observedGeneration\')==live[\'metadata\'][\'generation\'],\'controller generation not settled\')\n  result.update(native_rollout_verified=True,current_schema5_database_retained=True,recovery_verification=phase==\'rollback-verify\')\nexcept BaseException as error:\n result.update(all_checks_pass=False,failure_class=type(error).__name__,\n  failure=\'fixed phase outcome refused or ambiguous; raw output withheld; no retry\')\nprint(json.dumps(result));sys.exit(0 if result.get(\'all_checks_pass\') is True else 1)\n'
