diff --git a/deploy/windows/console_access_recovery.py b/deploy/windows/console_access_recovery.py
new file mode 100644
index 0000000..4f28cb0
--- /dev/null
+++ b/deploy/windows/console_access_recovery.py
@@ -0,0 +1,189 @@
+#!/usr/bin/env python3
+"""Expired development tunnel recovery: server-only CAS + fixed public console code.
+
+No Windows access, key generation, SSH profile edit, port/download/RMM change.
+Root renews the one expired restricted authorized key first, then hands the
+reviewed public PowerShell to the User's elevated Windows console.
+"""
+import argparse
+import base64
+import datetime as dt
+import hashlib
+import inspect
+import json
+import os
+from pathlib import Path
+import subprocess
+import uuid
+import zipfile
+import client_bootstrap as cb
+import system_pipe_upgrade as pair
+import dev_access_renewal as previous
+require,sha,save=pair.require,pair.sha,pair.save
+STATE=cb.EVIDENCE/'dev-access-console-recovery'
+OLD_EXPIRY='2026-11-14T12:55:31.254999+00:00'
+
+def recover_server(payload):
+ import datetime as dt
+ import re
+ import stat
+ root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
+ authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
+ profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf')
+ ident=str(uuid.UUID(payload['id']));case=root/('console-recovery-'+ident)
+ require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase')
+ def check(path,mode):
+ s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file')
+ def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
+ check(authorized,0o644);check(profile,0o644)
+ account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account')
+ public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2])
+ fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1]
+ require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key')
+ raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw)
+ require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options')
+ effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout
+ for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile')
+ def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell)
+ if payload['phase']=='state':return state()
+ if payload['phase']=='readback':
+ value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value
+ old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc)
+ require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and old
dt.datetime.fromisoformat(OLD_EXPIRY),'original lease actually expired')
+ ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700,parents=True)
+ expiry=(cb.contract.now()+dt.timedelta(hours=24)).replace(microsecond=0)
+ console=cb.contract.protected_json(access.root/'devstate/windows-bootstrap/console-registration.json')
+ with zipfile.ZipFile(access.root/'devstate/windows-bootstrap/windows-dev-access.zip') as bundle:
+ original=bundle.read('bootstrap-public.json')
+ public=json.loads(original,object_pairs_hook=cb.contract.strict_object)
+ require(public['expires_at']==OLD_EXPIRY and public['server']=='discovery.ease-technologies.de','original public-only bundle')
+ payload=dict(id=ident,phase='state',old_expiry=OLD_EXPIRY,new_expiry=expiry.isoformat(),tunnel_public_key=console['tunnel_public_key'])
+ save(folder/'prepare-intent.json',dict(id=ident,source_sha256=sha(__file__),new_expiry=payload['new_expiry'],no_windows_access=True))
+ baseline=access.rpc(payload);require(baseline['expiry']==dt.datetime.fromisoformat(OLD_EXPIRY).strftime('%Y%m%d%H%M%SZ'),'only original expired key')
+ payload['server_before']=baseline
+ script=CONSOLE
+ for key,value in {'ID':ident,'EXPIRY':payload['new_expiry'],'CONFIG':hashlib.sha256(original).hexdigest(),'BOOTSTRAP':sha(cb.ROOT/'deploy/windows/Bootstrap-DevAccess.ps1'),'TUNNEL':console['tunnel_public_key'],'HOST':console['windows_host_public_key'],'FILETIME':str((int(expiry.timestamp())+11644473600)*10000000)}.items():
+ token='@@'+key+'@@';require(script.count(token)==1,'exact fixed public console field');script=script.replace(token,value)
+ require('@@' not in script,'complete fixed public instructions')
+ pair.write_bytes(folder/'Recover-ExistingDevAccess.ps1',script.encode())
+ save(folder/'public-recovery.json',dict(id=ident,new_expiry=payload['new_expiry'],script_sha256=pair.raw_sha(script.encode()),no_private_keys=True))
+ readme=('Bestehenden Windows-Entwicklungszugang wiederherstellen\r\n\r\n'
+ 'Nur in dieser Windows-Test-VM ausfuehren, in einer als Administrator gestarteten PowerShell.\r\n'
+ 'Der Cloudserver muss zuvor durch den Entwickler fuer diese feste Frist erneuert worden sein.\r\n'
+ 'Neue UTC-Frist: '+payload['new_expiry']+'\r\n'
+ 'ZIP-SHA256 mit dem unabhaengig mitgeteilten Downloadhash vergleichen; dann hier entpacken.\r\n'
+ 'Folgende Befehle im entpackten Verzeichnis ausfuehren:\r\n\r\n'
+ "$recoveryScript = Join-Path (Get-Location) 'Recover-ExistingDevAccess.ps1'\r\n"
+ "if ((Get-FileHash -LiteralPath $recoveryScript -Algorithm SHA256).Hash.ToLowerInvariant() -cne '"+pair.raw_sha(script.encode())+"') { throw 'Falsche Recoverydatei' }\r\n"
+ 'Unblock-File -LiteralPath $recoveryScript\r\n'
+ 'powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File $recoveryScript\r\n\r\n'
+ 'Unblock-File betrifft nur diese exakt gepruefte heruntergeladene Datei; RemoteSigned nur diesen Bootstrapprozess.\r\n'
+ 'Keine globale Policy/GPO aendern. Falls eine Richtlinie oder Pruefung verweigert: stoppen, Fehlermeldung melden, nicht erneut ausfuehren.\r\n'
+ 'Das Skript behaelt Schluessel, Pins, SSH-Profil und Taskdefinition bei, erneuert nur die Ablaufzeit und startet den Originaltunnel einmal.\r\n'
+ 'Keine Installation, ACL-Reparatur, RMM-Aktion, Reboot oder Update. Private Schluessel werden nicht gelesen/ausgegeben.\r\n'
+ 'Nach Erfolg bitte nur die Abschlusszeile melden, keine Schluessel oder Zugangsdaten. Bei Fehler den Zustand fuer lesende Kontrolle behalten.\r\n')
+ pair.write_bytes(folder/'README.txt',readme.encode('utf-8'))
+ bundle=folder/'windows-dev-access-recovery.zip'
+ with zipfile.ZipFile(bundle,'x',compression=zipfile.ZIP_DEFLATED) as archive:
+ for name in ('Recover-ExistingDevAccess.ps1','public-recovery.json','README.txt'):
+ archive.write(folder/name,name)
+ bundle.chmod(0o600)
+ intent=dict(id=ident,source_sha256=sha(__file__),access_root=str(access.root),payload=payload,console_sha256=pair.raw_sha(script.encode()),bundle_sha256=sha(bundle),readme_sha256=sha(folder/'README.txt'),public_json_sha256=sha(folder/'public-recovery.json'))
+ save(folder/'intent.json',intent)
+ print(json.dumps(dict(id=ident,review_sha256=sha(folder/'intent.json'),console_source=str((folder/'Recover-ExistingDevAccess.ps1').resolve()),console_sha256=intent['console_sha256'],bundle=str(bundle.resolve()),bundle_sha256=sha(bundle),new_expiry=payload['new_expiry'],windows_not_accessed=True)))
+
+
+def run(access,ident,phase,review_sha):
+ require(str(uuid.UUID(ident))==ident,'canonical original recovery');folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json')
+ require(intent['source_sha256']==sha(__file__) and intent['access_root']==str(access.root) and sha(folder/'Recover-ExistingDevAccess.ps1')==intent['console_sha256'] and sha(folder/'windows-dev-access-recovery.zip')==intent['bundle_sha256'] and sha(folder/'README.txt')==intent['readme_sha256'] and sha(folder/'public-recovery.json')==intent['public_json_sha256'],'same immutable console recovery source/public package')
+ if phase=='server-enter':
+ require(review_sha==sha(folder/'intent.json'),'explicit reviewed server-only CAS');save(folder/'server-enter-intent.json',dict(once=True))
+ payload=dict(intent['payload'],phase='enter' if phase=='server-enter' else 'readback')
+ result=access.rpc(payload);save(folder/('server-entered.json' if phase=='server-enter' else 'readback-'+str(uuid.uuid4())+'.json'),result)
+ print(json.dumps(dict(id=ident,result=result,windows_not_accessed=True,console_handoff_allowed=result.get('completed') is True)))
+
+
+def main():
+ os.umask(0o077);parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('phase',choices=('prepare','server-enter','readback'));parser.add_argument('--access-root',required=True,type=Path);parser.add_argument('--id');parser.add_argument('--review-sha256');args=parser.parse_args();access=ServerAccess(args.access_root)
+ if args.phase=='prepare':require(not(args.id or args.review_sha256),'fresh server-only preparation');prepare(access)
+ else:require(args.id and ((args.phase=='server-enter')==bool(args.review_sha256)),'same case, reviewed CAS once');run(access,args.id,args.phase,args.review_sha256)
+
+
+if __name__=='__main__':
+ try:main()
+ except Exception as error:print('CONSOLE_ACCESS_RECOVERY_INCOMPLETE:'+type(error).__name__);raise SystemExit(2) from None
diff --git a/deploy/windows/dev_access_renewal.py b/deploy/windows/dev_access_renewal.py
new file mode 100644
index 0000000..53dd070
--- /dev/null
+++ b/deploy/windows/dev_access_renewal.py
@@ -0,0 +1,238 @@
+#!/usr/bin/env python3
+"""One 24h renewal of the existing restricted development SSH transport.
+
+No new key, port, shell, RMM setting, download lease, stop/kill or reboot.
+The unchanged tunnel expires naturally; one SYSTEM worker starts its original
+scheduled task at original expiry+60s. This deliberately permits a short gap.
+Lost mutation replies allow readback only. Main config publication is Root work.
+"""
+import argparse
+import base64
+import datetime as dt
+import inspect
+import json
+import os
+from pathlib import Path
+import subprocess
+import uuid
+
+import client_bootstrap as cb
+import system_pipe_upgrade as pair
+
+require, sha, canonical, save = pair.require, pair.sha, pair.canonical, pair.save
+STATE = cb.EVIDENCE / 'dev-access-renewal'
+OLD_EXPIRY = '2026-11-14T12:55:31.254999+00:00'
+OLD_UTC = dt.datetime.fromisoformat(OLD_EXPIRY)
+NEW_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(hours=24)
+START_UTC = OLD_UTC.replace(microsecond=0) + dt.timedelta(seconds=60)
+
+
+def server(payload):
+ import datetime as dt
+ import re
+ import stat
+ root=Path('/opt/rust-discovery/devstate/windows-bootstrap')
+ authorized=Path('/var/lib/rmm-win-tunnel/.ssh/authorized_keys')
+ profile=Path('/etc/ssh/sshd_config.d/80-rmm-windows-tunnel.conf')
+ ident=str(uuid.UUID(payload['id']));case=root/('renew-'+ident)
+ require(payload['phase'] in ('state','enter','readback'),'fixed renewal phase')
+ def check(path,mode):
+ s=path.lstat();require(not path.is_symlink() and stat.S_ISREG(s.st_mode) and s.st_uid==0 and stat.S_IMODE(s.st_mode)==mode and s.st_size<65536,'protected original transport file')
+ def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
+ check(authorized,0o644);check(profile,0o644)
+ account=pwd.getpwnam('rmm-win-tunnel');require(account.pw_dir=='/var/lib/rmm-win-tunnel' and account.pw_shell=='/usr/sbin/nologin','existing forwarding-only account')
+ public=' '.join(Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()[:2])
+ fingerprint=subprocess.run(['ssh-keygen','-lf','/etc/ssh/ssh_host_ed25519_key.pub'],capture_output=True,check=True,timeout=10).stdout.decode().split()[1]
+ require(fingerprint=='SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw','confirmed original server host key')
+ raw=authorized.read_text();match=re.fullmatch(r'restrict,port-forwarding,permitlisten="127\.0\.0\.1:22240",expiry-time="(\d{14}Z)" (ssh-ed25519 [A-Za-z0-9+/=]{68})\n',raw)
+ require(match is not None and match[2]==payload['tunnel_public_key'],'exact unchanged forwarding key/options')
+ effective=subprocess.run(['/usr/sbin/sshd','-T','-C','user=rmm-win-tunnel,host=localhost,addr=127.0.0.1'],capture_output=True,check=True,timeout=10).stdout
+ for line in (b'allowtcpforwarding remote\n',b'permitlisten 127.0.0.1:22240\n',b'permitopen none\n',b'gatewayports no\n',b'maxsessions 0\n',b'passwordauthentication no\n'):require(line in effective,'same restricted forwarding-only profile')
+ def state():return dict(read_only=True,authorized_sha256=digest(authorized),profile_sha256=digest(profile),effective_sha256=hashlib.sha256(effective).hexdigest(),server_host_key_sha256=hashlib.sha256(public.encode()).hexdigest(),tunnel_public_key_sha256=hashlib.sha256(match[2].encode()).hexdigest(),expiry=match[1],uid=account.pw_uid,gid=account.pw_gid,home=account.pw_dir,shell=account.pw_shell)
+ if payload['phase']=='state':return state()
+ if payload['phase']=='readback':
+ value=state();value['case_exists']=case.exists();value['replace_intent']=case.exists() and (case/'replace-intent.json').exists();value['completed']=case.exists() and (case/'completed.json').exists();return value
+ old=dt.datetime.fromisoformat(payload['old_expiry']).astimezone(dt.timezone.utc);new=dt.datetime.fromisoformat(payload['new_expiry']).astimezone(dt.timezone.utc)
+ require(old.isoformat()=='2026-11-14T12:55:31.254999+00:00' and new==old.replace(microsecond=0)+dt.timedelta(hours=24) and dt.datetime.now(dt.timezone.utc)65536)throw new InvalidOperationException("Token size");
+ IntPtr p=Marshal.AllocHGlobal(needed);if(!GetTokenInformation(token,kind,p,needed,out bytes)){Marshal.FreeHGlobal(p);throw new Win32Exception();}return p;
+ }
+ public static Dictionary Proof(Held h,int pid,string owner,string serviceSid,string image){
+ if(!Alive(h))throw new InvalidOperationException("Process not alive");
+ long creation,exit,kernel,user;if(!GetProcessTimes(h,out creation,out exit,out kernel,out user))throw new Win32Exception();
+ StringBuilder path=new StringBuilder(32768);uint length=32768;if(!QueryFullProcessImageName(h,0,path,ref length)||!String.Equals(path.ToString(),image,StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("Process image");
+ IntPtr token;if(!OpenProcessToken(h,8,out token))throw new Win32Exception();
+ try {
+ int bytes;IntPtr info=Info(token,1,out bytes);string actual;
+ try {actual=new SecurityIdentifier(Marshal.ReadIntPtr(info)).Value;}finally{Marshal.FreeHGlobal(info);}
+ if(actual!=owner)throw new InvalidOperationException("Process owner");
+ info=Info(token,2,out bytes);bool found=false;
+ try {int count=Marshal.ReadInt32(info);int offset=(int)Marshal.OffsetOf(typeof(Groups),"First");int stride=Marshal.SizeOf(typeof(SidAndAttributes));
+ if(count<0||count>1024||offset+(long)count*stride>bytes)throw new InvalidOperationException("Groups size");
+ for(int n=0;n{{"pid",pid},{"creation_filetime",creation.ToString(System.Globalization.CultureInfo.InvariantCulture)},{"owner_sid",actual},{"service_sid",serviceSid},{"service_sid_enabled",true},{"image",path.ToString()},{"kernel_handle_bound",true}};
+ }finally{CloseHandle(token);}
+ }
+}
+'@
+function FileIdentity($path,[bool]$actor=$false){
+ Check $path $false $actor;$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
+ try{$id=New-Object RmmPipeNative+FileId;$size=[Runtime.InteropServices.Marshal]::SizeOf([type][RmmPipeNative+FileId]);if($size-ne24-or![RmmPipeNative]::GetFileInformationByHandleEx($file.SafeFileHandle,18,[ref]$id,[uint32]$size)){throw 'Native file identity'}
+ return [ordered]@{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$file.Length;acl_sha256=(AclHash $path);sha256=(Hash $path $actor)}
+ }finally{$file.Dispose()}
+}
+function Kernel($role,$record,$held){
+ $owner='S-1-5-19';$sid=$agentSid;$image=$agentBinary;if($role-ceq'helper'){$owner=$sys;$sid=$helperSid;$image=$helperBinary}
+ $proof=[RmmPipeNative]::Proof($held,[int]$record.pid,$owner,$sid,$image)
+ if($proof.creation_filetime-cne$record.creation_filetime-or$proof.owner_sid-cne$record.owner_sid){throw 'SCM/kernel process identity mismatch'};return $proof
+}
+function ActualState([bool]$new){
+ $value=State $new
+ $value['files']=[ordered]@{agent=(FileIdentity $agentBinary);helper=(FileIdentity $helperBinary);settings=(FileIdentity $settings);pin=(FileIdentity $pin);config=(FileIdentity $config);ca=(FileIdentity (Join-Path $agentRoot 'server-ca.pem') $true);identity=(FileIdentity (Join-Path $agentState 'identity.json') $true);certificate=(FileIdentity (Join-Path $agentState 'device.pem') $true);private_key=(FileIdentityMetadata (Join-Path $agentState 'device.key'))}
+ foreach($role in @('agent','helper')){$record=$value.service;if($role-ceq'helper'){$record=$value.helper_service}
+ $proof=$null;if($record.state-ceq'Running'){$held=[RmmPipeNative]::Open([int]$record.pid);try{$proof=Kernel $role $record $held;if(!(JsonEqual $record (Service $role))-or![RmmPipeNative]::Alive($held)){throw 'SCM/kernel generation changed during proof'}}finally{$held.Dispose()}}
+ $value[$role+'_kernel']=$proof
+ };return $value
+}
+# FILE_READ_ATTRIBUTES only: no key content read/hash/export. This also binds
+# the private key's actual native FileID, not merely a timestamp/name.
+function FileIdentityMetadata($path){
+ Check $path $false $true;$i=Get-Item -LiteralPath $path -Force;$h=[RmmPipeNative]::CreateFile($path,0x80,7,[IntPtr]::Zero,3,0,[IntPtr]::Zero)
+ try{if($h.IsInvalid){throw 'Private metadata-only handle'};$id=New-Object RmmPipeNative+FileId;if(![RmmPipeNative]::GetFileInformationByHandleEx($h,18,[ref]$id,24)){throw 'Private metadata-only native FileID'};return @{volume_serial=$id.Volume.ToString([Globalization.CultureInfo]::InvariantCulture);file_id=([BitConverter]::ToString($id.Id)).Replace('-','').ToLowerInvariant();bytes=$i.Length;creation_ticks=$i.CreationTimeUtc.Ticks.ToString();last_write_ticks=$i.LastWriteTimeUtc.Ticks.ToString();acl_sha256=(AclHash $path);private_key_read=$false}}finally{$h.Dispose()}
+}
+function SameOriginal($before,$after){
+ Preserved $before $after $false
+ if(!(JsonEqual $before.files $after.files)){throw 'Original four files/config/private metadata CAS'}
+ foreach($role in @('service','helper_service','agent_kernel','helper_kernel')){if(!(JsonEqual $before.$role $after.$role)){throw 'Fresh original kernel/SCM generation changed; new reviewed baseline required'}}
+}
+function PreserveImmutableFiles($before,$after,[bool]$frozen){
+ Preserved $before $after $frozen
+ foreach($label in @('config','ca','identity','certificate','private_key')){if(!(JsonEqual $before.files.$label $after.files.$label)){throw 'Original immutable PKI/config native FileID/metadata changed'}}
+}
+'''
+
+# The original fixed-role SCM configuration checks are reused exactly. Unlike
+# Service(), this readback projection makes no running-process proof claim and
+# honestly exposes pending/raw State/PID without changing a service.
+READBACK_SERVICE = "\nfunction ReadbackService($role){" + u.SCRIPT.split('function Service($role){', 1)[1].split(' $processId=', 1)[0] + r'''
+ $state=[string]$service.State;if(!$state-or$state.Length-gt64){throw 'Bounded raw SCM state'}
+ return [ordered]@{state=$state;pid=[uint32]$service.ProcessId;start_name=$service.StartName;start_mode=$service.StartMode;path=$service.PathName;service_type=$service.ServiceType;sid_type=$sidType;service_acl_sha256=(BytesHash ([Text.Encoding]::UTF8.GetBytes($text)));process_identity_verified=$false;read_only=$true}
+}
+'''
+
+PHASES = r'''
+CheckControl $boot $true
+if($p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$PSCommandPath-cne(Join-Path (Join-Path $boot $p.script_sha256) 'SystemPipeUpgrade.ps1')-or(Hash $PSCommandPath)-cne$p.script_sha256){throw 'Actual executing pipe-upgrade source'}
+if($p.action-ceq'baseline'){$before=ActualState $false;if($before.service.state-cne'Running'-or$before.helper_service.state-notin@('Running','Stopped')-or$before.journal.pending_inventory_events-ne0){throw 'Settled original passive baseline'};$before|ConvertTo-Json -Depth 40 -Compress;exit 0}
+function ReadCase{
+ CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false;CheckControl $active $false
+ $i=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json;$a=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json
+ if((($i.payload.PSObject.Properties.Name|Sort-Object)-join',')-cne(($p.PSObject.Properties.Name|Sort-Object)-join',')){throw 'Original exact pipe payload shape'}
+ foreach($field in $p.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $i.payload.$field $p.$field)){throw 'Original exact pipe intent'}}
+ if($a.id-cne$p.id-or$a.script_sha256-cne$p.script_sha256-or$a.baseline_sha256-cne$p.baseline_sha256){throw 'Original active pipe intent'};return $i
+}
+if($p.action-ceq'readback'){
+ function MaybeHash($path){if(!(Test-Path -LiteralPath $path)){return $null};return Hash $path}
+ $i=ReadCase;$phases=[ordered]@{};foreach($label in @('agent-stop-attempt','agent-stopped','helper-stop-attempt','helper-stopped','helper-already-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replace-attempt','agent-replaced','helper-replace-attempt','helper-replaced','settings-replace-attempt','settings-replaced','pin-replace-attempt','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$phases[$label]=Test-Path -LiteralPath (Join-Path $folder ($label+'.json'))}
+ @{read_only=$true;id=$p.id;phase_receipts=$phases;service=(ReadbackService 'agent');helper_service=(ReadbackService 'helper');hashes=@{agent=(MaybeHash $agentBinary);helper=(MaybeHash $helperBinary);settings=(MaybeHash $settings);pin=(MaybeHash $pin)}}|ConvertTo-Json -Depth 40 -Compress;exit 0
+}
+if($p.action-ceq'finish'){
+ $i=ReadCase;$after=ActualState $true;PreserveImmutableFiles $i.before $after $false
+ CheckControl (Join-Path $folder 'frozen.json') $false;$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json;PreserveImmutableFiles $frozen $after $false
+ foreach($role in @('agent','helper')){CheckControl (Join-Path $folder ($role+'-started.json')) $false;$started=Get-Content -LiteralPath (Join-Path $folder ($role+'-started.json')) -Raw|ConvertFrom-Json;$live=$after.service;if($role-ceq'helper'){$live=$after.helper_service};if($live.state-cne'Running'-or!(JsonEqual $started.service $live)-or!(JsonEqual $started.kernel $after.($role+'_kernel'))){throw 'Same single-start actual component instance required'}}
+ @{read_only=$true;completed=$true;id=$p.id;native=$after;original=$i.before;frozen=$frozen}|ConvertTo-Json -Depth 40 -Compress;exit 0
+}
+if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing pipe intent: readback only'}
+$baselineBytes=[Convert]::FromBase64String($p.baseline_base64);if((BytesHash $baselineBytes)-cne$p.baseline_sha256){throw 'Exact separately reviewed baseline bytes'};$baseline=[Text.Encoding]::UTF8.GetString($baselineBytes)|ConvertFrom-Json
+$before=ActualState $false;SameOriginal $baseline $before
+if($before.journal.pending_inventory_events-ne0-or$before.service.state-cne'Running'){throw 'Original ACK and running agent required'}
+$heldAgent=[RmmPipeNative]::Open([int]$before.service.pid);$heldHelper=$null
+try{
+ $null=Kernel 'agent' $before.service $heldAgent
+ if($before.helper_service.state-ceq'Running'){$heldHelper=[RmmPipeNative]::Open([int]$before.helper_service.pid);$null=Kernel 'helper' $before.helper_service $heldHelper}
+ New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
+ WriteNew (Join-Path $folder 'intent.json') @{payload=$p;before=$before};WriteNew $active @{id=$p.id;script_sha256=$p.script_sha256;baseline_sha256=$p.baseline_sha256;no_jobs=$true}
+ function StopHeld($role,$record,$held){
+ $live=Service $role;if(!(JsonEqual $record $live)){throw 'SCM identity changed before own stop'};$null=Kernel $role $record $held
+ $name=$agentName;if($role-ceq'helper'){$name=$helperName};WriteNew (Join-Path $folder ($role+'-stop-attempt.json')) @{stop_once=$true;service=$record}
+ Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20));if(![RmmPipeNative]::Exited($held,20000)){throw 'Pinned original process not exited'}
+ WriteNew (Join-Path $folder ($role+'-stopped.json')) @{original=$record;kernel_process_exited=$true}
+ }
+ StopHeld 'agent' $before.service $heldAgent
+ if($null-ne$heldHelper){StopHeld 'helper' $before.helper_service $heldHelper}else{if((Service 'helper').state-cne'Stopped'){throw 'Manual helper changed since reviewed stopped baseline'};WriteNew (Join-Path $folder 'helper-already-stopped.json') @{observed_stopped=$true;stop_called=$false;start_called=$false}}
+ $frozen=ActualState $false;Preserved $before $frozen $false;if($frozen.service.state-cne'Stopped'-or$frozen.helper_service.state-cne'Stopped'-or$frozen.journal.pending_inventory_events-ne0-or!(JsonEqual $before.files $frozen.files)){throw 'Stopped original complete pair/file identities'};WriteNew (Join-Path $folder 'frozen.json') $frozen
+ function Backup($label,$path,$expected){
+ $identity=FileIdentity $path;if(!(JsonEqual $identity $before.files.$label)-or$identity.sha256-cne$expected){throw 'Original backup file identity/hash/ACL'}
+ $backup=Join-Path $folder ($label+'-original');[IO.File]::Copy($path,$backup,$false);PrivateBackupAcl $backup;FlushCopy $backup
+ if((Hash $backup)-cne$expected){throw 'Exact private backup bytes'};WriteNew (Join-Path $folder ($label+'-backup.json')) @{original=$identity;backup=(FileIdentity $backup);original_sddl=(Get-Acl -LiteralPath $path).Sddl}
+ }
+ Backup 'agent' $agentBinary $p.old_agent;Backup 'helper' $helperBinary $p.old_helper;Backup 'settings' $settings $p.old_policy;Backup 'pin' $pin $p.old_pin
+ $settingBytes=[Convert]::FromBase64String($p.settings_base64);$pinBytes=[Convert]::FromBase64String($p.pin_base64);if((BytesHash $settingBytes)-cne$p.new_policy-or(BytesHash $pinBytes)-cne$p.new_pin){throw 'Deterministic closed reciprocal settings'}
+ WriteBytes (Join-Path $folder 'new-helper.json') $settingBytes;WriteBytes (Join-Path $folder 'new-agent-pin.json') $pinBytes
+ function Swap($label,$destination,$source,$oldHash,$newHash){
+ if((Service 'agent').state-cne'Stopped'-or(Service 'helper').state-cne'Stopped'){throw 'Both stopped for all four file replacements'}
+ foreach($other in @('agent','helper','settings','pin')){CheckControl (Join-Path $folder ($other+'-backup.json')) $false;if(!(Test-Path -LiteralPath (Join-Path $folder ($other+'-original')))){throw 'All four private backups precede first replacement'}}
+ $old=FileIdentity $destination;$sddl=(Get-Acl -LiteralPath $destination).Sddl;$nativeBackup=Join-Path $folder ($label+'-native-original');$candidate=Join-Path $folder ($label+'-candidate')
+ if(!(JsonEqual $old $before.files.$label)-or$old.sha256-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash-or(Test-Path -LiteralPath $nativeBackup)){throw 'Fresh destination/source/backup CAS'}
+ [IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate;$candidateId=FileIdentity $candidate;if($candidateId.sha256-cne$newHash){throw 'Complete staged replacement'}
+ WriteNew (Join-Path $folder ($label+'-replace-attempt.json')) @{old=$old;candidate=$candidateId;native_backup=$nativeBackup;source_sha256=$p.script_sha256}
+ if(!(JsonEqual (FileIdentity $destination) $old)-or!(JsonEqual (FileIdentity $candidate) $candidateId)-or(Test-Path -LiteralPath $nativeBackup)){throw 'Immediate file-ID/hash/ACL CAS'}
+ [IO.File]::Replace($candidate,$destination,$nativeBackup)
+ PrivateBackupAcl $nativeBackup;$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;FlushCopy $destination
+ if((Hash $destination)-cne$newHash-or(Hash $nativeBackup)-cne$oldHash-or(AclHash $destination)-cne$old.acl_sha256){throw 'Exact actual replacement/explicit native backup/ACL'}
+ WriteNew (Join-Path $folder ($label+'-replaced.json')) @{original=$old;current=(FileIdentity $destination);native_backup=(FileIdentity $nativeBackup);original_backup=(FileIdentity (Join-Path $folder ($label+'-original')))}
+ }
+ Swap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent
+ Swap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper
+ Swap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy
+ Swap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin
+ $swapped=ActualState $true;PreserveImmutableFiles $frozen $swapped $true;if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'All four new files while both stopped'};WriteNew (Join-Path $folder 'swapped.json') $swapped
+ function StartOnce($role){
+ $checked=ActualState $true;PreserveImmutableFiles $frozen $checked $false;if((Service $role).state-cne'Stopped'){throw 'First exact selected start only'};$name=$helperName;if($role-ceq'agent'){$name=$agentName}
+ WriteNew (Join-Path $folder ($role+'-start-attempt.json')) @{start_once=$true;all_four_files_verified=$true}
+ Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
+ $s=Service $role;$held=[RmmPipeNative]::Open([int]$s.pid);try{$kernel=Kernel $role $s $held;WriteNew (Join-Path $folder ($role+'-started.json')) @{service=$s;kernel=$kernel}}finally{$held.Dispose()}
+ }
+ StartOnce 'helper';StartOnce 'agent';$after=ActualState $true;PreserveImmutableFiles $before $after $false;WriteNew (Join-Path $folder 'entered.json') $after
+ @{entered=$true;id=$p.id;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Compress
+}finally{$heldAgent.Dispose();if($null-ne$heldHelper){$heldHelper.Dispose()}}
+'''
+SCRIPT = PREFIX + '\n' + NATIVE + READBACK_SERVICE + '\n' + PHASES
+PREPARE = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1')
+LAUNCH = u.transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemPipeUpgrade.ps1').replace('RmmTransportPayload', 'RmmPipeUpgradePayload')
+
+
+class Access:
+ """Explicit read-only access roots; never redirects source/manifest globals."""
+ def __init__(self, root):
+ self.root = Path(root).absolute()
+ require(self.root == self.root.resolve() and self.root != ROOT.resolve(), 'separate real access root, no symlink/copy')
+ self.evidence = self.root / 'devstate/windows-client'
+
+ def powershell(self, source, payload, timeout=180):
+ access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
+ wrapped = "try {\n" + source + "\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}"
+ command = 'powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -EncodedCommand ' + base64.b64encode(wrapped.encode('utf-16le')).decode()
+ result = subprocess.run(access['ssh_prefix'] + [command], input=canonical(payload) + b'\n', capture_output=True, timeout=timeout)
+ if result.returncode:
+ # Fixed error identifiers/line only; never raw stderr/payload/commands.
+ safe = dict(returncode=result.returncode, stdout_bytes=len(result.stdout), stderr_bytes=len(result.stderr))
+ try:
+ error = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
+ if error.get('bootstrap_error') is True:
+ safe.update(error_id=error.get('error_id'), line=error.get('line'))
+ except (ValueError, AttributeError):
+ pass
+ save(STATE / ('remote-error-' + str(uuid.uuid4()) + '.json'), safe)
+ raise RuntimeError('fixed pipe upgrade bootstrap incomplete; readback only')
+ return json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=cb.contract.strict_object)
+
+ def stage(self, path, name):
+ require(name in ('rmm-agent-windows.exe', 'rmm-helper-windows.exe', 'RuntimeStateProbe.exe', 'SystemStateProbe.exe', 'SystemPipeUpgrade.ps1'), 'fixed stage names')
+ path = Path(path)
+ digest = sha(path)
+ prepare = u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name)
+ observed = self.powershell(prepare, dict(sha256=digest))
+ if not observed['already_uploaded']:
+ access = cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
+ prefix = access['ssh_prefix']
+ args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]]
+ target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name
+ result = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
+ require(result.returncode == 0, 'immutable exact bootstrap transfer; no retry')
+ observed = self.powershell(prepare, dict(sha256=digest))
+ require(observed['already_uploaded'] is True and observed['sha256'] == digest, 'same exact existing-or-new stage')
+
+ def server(self, function, payload):
+ cloud = u.transport.cloud
+ require(function in (cloud.server, u.auto.server_state, u.transport.server_transport.server_evidence), 'fixed read-only server witnesses')
+ # The inherited parser is strict data parsing, not source/eval. Its ROOT
+ # only checks the source .gitignore; its supplied path remains Main.
+ cfg = cloud.bootstrap.access.load_config(self.root / 'credentials/server.conf')
+ ssh = ['ssh', '-F', '/dev/null', '-T', '-p', cfg.get('port', '22'), '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), cfg['username'] + '@' + cfg['address'], 'python3 -']
+ code = ('import os,json,subprocess,base64,hashlib,ssl,http.client,socket,uuid,pwd\nfrom pathlib import Path\n' + inspect.getsource(cloud.bootstrap.require) + '\n' + inspect.getsource(function) + '\ntry:\n print(json.dumps(' + function.__name__ + '(' + repr(payload) + ')))\nexcept Exception as error:\n print(json.dumps(dict(error="READONLY_WITNESS_INCOMPLETE",kind=type(error).__name__)))\n')
+ result = subprocess.run(ssh, input=code.encode(), capture_output=True, timeout=60)
+ require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'bounded readonly server witness')
+ value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
+ require('error' not in value, 'readonly server witness incomplete')
+ return value
+
+ def server_state(self):
+ cloud = u.transport.cloud
+ linux = cb.contract.protected_json(self.root / 'devstate/cloud-mvp-final-closeout.json')
+ require(linux['verified'] is True, 'accepted Linux target only')
+ counts = {name: self.server(cloud.server, dict(kind='gate', tenant_id=tenant, agent_id=agent)) for name, tenant, agent in (
+ ('windows', cloud.TENANT, u.transport.AGENT), ('linux', linux['target']['tenant_id'], linux['target']['agent_id']))}
+ flags = self.server(u.auto.server_state, {})
+ require(u.auto.flags_disabled(flags) and counts['windows'] == dict(jobs=0, outbox=0, permits=0, unresolved=0), 'closed hooks and Windows zero-job gate')
+ return dict(counts=counts, flags=flags)
+
+ def observe(self, ident):
+ return self.server(u.transport.server_transport.server_evidence, dict(tenant_id=u.transport.cloud.TENANT, agent_id=u.transport.AGENT, fault_id=ident))
+
+ def device_and_denials(self):
+ bridge = self
+ class ReadBackend(u.transport.cloud.Backend):
+ def request(self, body):
+ if body['method'] == 'tools/call':
+ require(body['params']['name'] == 'inventory.get_device', 'only stored inventory reads')
+ else:
+ require(body['method'] in ('initialize', 'notifications/initialized'), 'only MCP read session')
+ return bridge.server(u.transport.cloud.server, dict(kind='http', path='/mcp', method='POST', headers=self.headers, body=body, principal=self.principal))
+ device = ReadBackend().call('inventory.get_device', dict(tenant_id=u.transport.cloud.TENANT, asset_id=u.transport.ASSET))
+ require(device['agent_id'] == u.transport.AGENT and device['source_id'] == 'windows.base' and set(device['capabilities']) == {'windows.base/1', 'heartbeat/1'} and device['presence'] == 'online', 'honest unchanged passive inventory')
+ denied = []
+ backend = ReadBackend('b')
+ for tenant in (u.transport.cloud.TENANT, '22222222-2222-4222-8222-222222222222'):
+ backend.sequence += 1
+ response = backend.request(dict(jsonrpc='2.0', id=backend.sequence, method='tools/call', params=dict(name='inventory.get_device', arguments=dict(tenant_id=tenant, asset_id=u.transport.ASSET))))
+ data = response.get('data', {})
+ require('error' in data or data.get('result', {}).get('isError'), 'foreign tenant denied')
+ denied.append(dict(tenant_id=tenant, denied=True))
+ return device, denied
+
+
+def dependencies():
+ modules = [cb, cb.contract, u, u.transport, u.auto, u.transport.cloud, u.transport.cloud.bootstrap, u.transport.cloud.bootstrap.access, u.transport.server_transport, u.qualification, u.qualification.feature, u.qualification.previous, u.original_helper]
+ return {str(Path(m.__file__).resolve().relative_to(ROOT)): sha(m.__file__) for m in modules}
+
+
+def guards():
+ require(sha(u.__file__) == ORIGINAL_RUNNER, 'immutable original read-only witness source')
+ require('function PinProcess' not in PREFIX and 'function Swap' not in PREFIX and 'function StopPinned' not in PREFIX and 'function StartOnce' not in PREFIX, 'historical mutations excluded')
+ require('[IO.File]::Replace($candidate,$destination,$nativeBackup)' in SCRIPT and '[IO.File]::Replace($candidate,$destination,$null)' not in SCRIPT, 'explicit additional absent native backup')
+ ordered = [SCRIPT.index(token) for token in (" StopHeld 'agent'", " Backup 'agent'", "Backup 'pin'", " Swap 'agent'", "Swap 'pin'", '$swapped=ActualState $true', " StartOnce 'helper'", "StartOnce 'agent'")]
+ require(ordered == sorted(ordered), 'all backups before any replacement; all replacements before helper/agent starts')
+ require(SCRIPT.count('Start-Service -Name $name') == SCRIPT.count('Stop-Service -Name $name') == 1, 'single fixed-role control primitives')
+ require(all(word not in SCRIPT + LAUNCH for word in ('Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Service', 'New-Service', 'Remove-Item', 'Invoke-Expression', 'Bypass')), 'no install/reconfigure/cleanup/reboot/automatic rollback')
+
+
+# Fresh isolated interpreter: the Pipe pack deliberately imports its transport
+# modules from Main. Reusing its module in this interpreter would accidentally
+# reuse our cached worktree client_bootstrap and corrupt the source/access split.
+# This code calls verification/read-only proof parsing ONLY, never native().
+VERIFY_PACK = r'''
+import hashlib,importlib.util,json,re,sys,uuid
+from pathlib import Path
+path=Path(sys.argv[1]);spec=importlib.util.spec_from_file_location('fixed_pipe_pack',path)
+pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
+manifest_path=Path(sys.argv[2]).resolve();proof_path=Path(sys.argv[3]).resolve()
+manifest=pack.verified(manifest_path) # full current code/access hashes + Linux80/Windows58 Core proofs
+proof=pack.cb.contract.protected_json(pack.private_file(proof_path));require=pack.require
+case=proof['case_id'];require(str(uuid.UUID(case))==case and proof_path==pack.NATIVE/case/'passed.json','exact native pipe case namespace')
+require(proof['verified'] is True and proof['manifest_path']==str(manifest_path) and proof['manifest_sha256']==pack.sha(manifest_path) and proof['no_jobs'] is True and proof['clock_adapter_qualified'] is False and proof['local_service_proof'] is False and proof['native_pipe_proof'] is False,'actual same pipe manifest units, no runtime capability')
+intent=pack.cb.contract.protected_json(proof_path.parent/'intent.json')
+require(intent['id']==case and intent['manifest_path']==str(manifest_path) and intent['manifest_sha256']==pack.sha(manifest_path) and intent['runner_sha256']==pack.sha(path) and intent['script_sha256']==hashlib.sha256(pack.SCRIPT.encode()).hexdigest(),'exact executed native unit source/manifest')
+require(pack.cb.contract.protected_json(proof_path.parent/'started-local.json')['start_once'] is True,'original create-once native execution intent')
+before=pack.cb.contract.protected_json(proof_path.parent/'server-before.json')
+require(pack.auto.flags_disabled(before['flags']) and before['counts']['windows']==dict(jobs=0,outbox=0,permits=0,unresolved=0),'original closed native zero-job scope')
+actual=proof['native']
+require(actual['completed'] is True and actual['manifest_sha256']==pack.sha(manifest_path) and set(actual['reports'])==set(pack.COUNTS) and actual['both_lists_verified_before_any_test'] is True and actual['bootstrap_administrator_units'] is True and actual['local_service_proof'] is False and actual['native_pipe_proof'] is False and actual['rmm_jobs'] is False and actual['product_state_writes'] is False,'actual completed narrow units only')
+for kind,count in pack.COUNTS.items():
+ report=actual['reports'][kind];listed=report['listed'];run=report['result']
+ names=re.findall(r'^(.+): test\r?$',listed['stdout'],re.M)
+ require(report['sha256']==manifest['artifacts'][kind]['sha256'] and names==report['names']==pack.TESTS[kind] and len(set(names))==count and type(listed['exit_code']) is int and listed['exit_code']==0 and type(run['exit_code']) is int and run['exit_code']==0 and listed['timed_out'] is False and run['timed_out'] is False and re.search(r'test result: ok\. '+str(count)+r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;',run['stdout']),'all exact 23/7 native cases, no ignored/filtered/timeout')
+print(json.dumps(manifest))
+'''
+
+
+def qualified(manifest_path, proof_path):
+ verifier = ROOT / 'deploy/windows/system_pipe_acceptance.py'
+ require(sha(verifier) == PIPE_VERIFIER_SHA, 'exact independently reviewed Pipe-v2 pack verifier')
+ result = subprocess.run([sys.executable, '-I', '-c', VERIFY_PACK, str(verifier), str(manifest_path), str(proof_path)], capture_output=True, timeout=60)
+ require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024, 'fresh isolated read-only Pipe verifier/native proof; details withheld')
+ value = json.loads(result.stdout, object_pairs_hook=cb.contract.strict_object)
+ require(value['type'] == 'rmm.windows.pipe-v2-build' and value['transport_version'] == 2 and value['native_counts_expected'] == dict(lib=23, bin=7), 'Pipe-v2 manifest, never historical delegation relabeling')
+ return value
+
+
+def prior(access):
+ runtime_path = access.evidence / 'current-runtime.json'
+ components_path = access.evidence / 'current-components.json'
+ runtime = cb.contract.protected_json(runtime_path)
+ components = cb.contract.protected_json(components_path)
+ result_path = access.evidence / ('system-delegation-upgrade/' + OLD_CASE + '/result.json')
+ require(sha(result_path) == OLD_RESULT_SHA, 'independently accepted original joint result')
+ result = cb.contract.protected_json(result_path)
+ require(result['verified'] is True and result['completed'] is True and result['no_jobs'] is True and result['windows_jobs_enabled'] is False and result['clock_adapter_qualified'] is False, 'accepted closed passive generation')
+ evidence = dict(path=str(result_path.resolve()), sha256=OLD_RESULT_SHA)
+ require(runtime['case_id'] == components['case_id'] == OLD_CASE and runtime['evidence'] == components['evidence'] == evidence and runtime['binary_sha256'] == components['agent_sha256'] == OLD_AGENT and components['helper_sha256'] == OLD_HELPER and components['policy_sha256'] == OLD_POLICY and components['pin_sha256'] == OLD_PIN and runtime['transport'] == 'auto' and runtime['windows_jobs_enabled'] is False and runtime['clock_adapter_qualified'] is False and runtime['system_helper_client_feature'] is True and components['windows_jobs_enabled'] is False and components['clock_adapter_qualified'] is False and components['helper_effects_enabled'] is False, 'current accepted four-file indices, no adoption of readback')
+ recovery = access.evidence / 'system-delegation-recovery/595dd1da-0d7f-4364-9040-a75e16c6da83/acceptance.json'
+ require(sha(recovery) == '5ad5925c8928f49cd0f9d48a64f81018281b5b6e3704c799bae64a42898322bb' and cb.contract.protected_json(recovery)['verified'] is True, 'accepted original explicit-backup recovery preserved')
+ original = cb.contract.protected_json(result_path.parent / 'intent.json')
+ settings = base64.b64decode(original['payload']['settings_base64'], validate=True)
+ require(raw_sha(settings) == OLD_POLICY and raw_sha(base64.b64decode(original['payload']['pin_base64'], validate=True)) == OLD_PIN, 'exact original reciprocal public settings')
+ return dict(runtime=runtime, components=components, runtime_sha256=sha(runtime_path), components_sha256=sha(components_path), result_sha256=OLD_RESULT_SHA), result, json.loads(settings, object_pairs_hook=cb.contract.strict_object)
+
+
+def passive_settings(old, agent, helper):
+ require(set(old) == {'schema_version', 'binding', 'agent', 'helper', 'allowed_services', 'max_runtime_seconds', 'enable_effects', 'allow_reboot'} and type(old['schema_version']) is int and old['schema_version'] == 1 and old['allowed_services'] == [] and old['enable_effects'] is False and old['allow_reboot'] is False and type(old['max_runtime_seconds']) is int and old['max_runtime_seconds'] == 30 and old['agent']['binary_sha256'] == OLD_AGENT and old['helper']['binary_sha256'] == OLD_HELPER, 'exact original closed public settings')
+ require(all(isinstance(h, str) and len(h) == 64 and all(c in '0123456789abcdef' for c in h) for h in (agent, helper)), 'qualified new image hashes')
+ new = json.loads(canonical(old)); new['agent']['binary_sha256'] = agent; new['helper']['binary_sha256'] = helper
+ settings = canonical(new); policy = raw_sha(settings)
+ pin = canonical(dict(schema_version=1, binding=new['binding'], policy_sha256=policy, agent=new['agent'], helper=new['helper']))
+ return settings, pin, policy
+
+
+def leaves(access):
+ path = access.evidence / 'system-intent-bootstrap/f322a4d2-c537-4842-bf04-658ad8f814b0/acceptance.json'
+ require(sha(path) == u.INTENT_PREPARATION_SHA, 'accepted original empty-leaf preparation')
+ proof = cb.contract.protected_json(path)
+ require(proof['verified'] is True and proof['sqlite_initialized'] is False, 'not a store/SQLite qualification')
+ created_path = path.parent / 'created.json'
+ require(sha(created_path) == proof['native_created_sha256'], 'original native empty-leaf receipt')
+ created = cb.contract.protected_json(created_path)
+ items = {v['name']: v for v in created['leaves']}
+ require(set(items) == {'system-intents.sqlite', 'system-intents.sqlite-journal'} and all(v['length'] == 0 for v in items.values()), 'exact two original zero-byte leaves')
+ return {label: dict(name=name, acl_sha256=raw_sha(items[name]['sddl'].encode())) for label, name in [('database', 'system-intents.sqlite'), ('journal', 'system-intents.sqlite-journal')]}
+
+
+def remote(access, intent, action):
+ require(intent['script_sha256'] == raw_sha(SCRIPT.encode()), 'immutable new pipe bootstrap source')
+ return access.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=dict(intent['payload'], action=action)))
+
+
+def load(ident, access):
+ require(str(uuid.UUID(ident)) == ident, 'canonical original case UUID')
+ folder = STATE / ident
+ intent = cb.contract.protected_json(folder / 'intent.json')
+ require(intent['id'] == ident and intent['runner_sha256'] == sha(__file__) and intent['script_sha256'] == raw_sha(SCRIPT.encode()) and intent['dependencies'] == dependencies() and intent['access_root'] == str(access.root), 'same source/dependencies/access root case')
+ manifest = qualified(Path(intent['manifest_path']), Path(intent['qualification_path']))
+ require(sha(intent['manifest_path']) == intent['payload']['manifest_sha256'] and sha(intent['qualification_path']) == intent['payload']['qualification_sha256'] and manifest['artifacts']['agent']['sha256'] == intent['payload']['new_agent'] and manifest['artifacts']['helper']['sha256'] == intent['payload']['new_helper'], 'same actually native-qualified new pair')
+ return folder, intent
+
+
+def prepare(access, manifest_path, proof_path):
+ guards()
+ manifest = qualified(manifest_path, proof_path)
+ indices, accepted, old = prior(access)
+ settings, pin, policy = passive_settings(old, manifest['artifacts']['agent']['sha256'], manifest['artifacts']['helper']['sha256'])
+ require(manifest['artifacts']['agent']['sha256'] != OLD_AGENT and manifest['artifacts']['helper']['sha256'] != OLD_HELPER, 'new coordinated pipe pair, no old source round')
+ ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
+ script_sha = raw_sha(SCRIPT.encode())
+ payload = dict(id=ident, old_agent=OLD_AGENT, old_helper=OLD_HELPER, old_policy=OLD_POLICY, old_pin=OLD_PIN, new_agent=manifest['artifacts']['agent']['sha256'], new_helper=manifest['artifacts']['helper']['sha256'], new_policy=policy, new_pin=raw_sha(pin), config_sha256=accepted['native']['config_sha256'], probe_sha256=manifest['artifacts']['probe']['sha256'], system_probe_sha256=manifest['artifacts']['system_probe']['sha256'], manifest_sha256=sha(manifest_path), qualification_sha256=sha(proof_path), script_sha256=script_sha, settings_base64=base64.b64encode(settings).decode(), pin_base64=base64.b64encode(pin).decode(), intent_leaves=leaves(access))
+ draft = dict(id=ident, started_at=cb.contract.now().isoformat(), access_root=str(access.root), runner_sha256=sha(__file__), script_sha256=script_sha, manifest_path=str(manifest_path.resolve()), qualification_path=str(proof_path.resolve()), dependencies=dependencies(), original_indices=indices, payload=payload, no_jobs=True)
+ save(folder / 'prepare-intent.json', draft)
+ for name, data in [('runner.py', Path(__file__).read_bytes()), ('SystemPipeUpgrade.ps1', SCRIPT.encode())]:
+ write_bytes(folder / name, data)
+ for kind in ('agent', 'helper', 'probe', 'system_probe'):
+ item = manifest['artifacts'][kind]
+ require(sha(item['path']) == item['sha256'], 'qualified staged artifact bytes')
+ access.stage(item['path'], item['name'])
+ access.stage(folder / 'SystemPipeUpgrade.ps1', 'SystemPipeUpgrade.ps1')
+ before = remote(access, draft, 'baseline')
+ expected = accepted['native']
+ for field in ('agent_id', 'asset_id', 'binary_sha256', 'helper_sha256', 'policy_sha256', 'pin_sha256', 'config_sha256', 'config_acl_sha256', 'binary_acl_sha256', 'helper_binary_acl_sha256', 'settings_acl_sha256', 'pin_acl_sha256', 'public_hashes', 'identity_acls', 'private_key_metadata'):
+ require(before[field] == expected[field], 'accepted original identity/PKI/config/four-file ACLs; no private key read')
+ for field in ('database_file_id', 'database_creation', 'identity_sha256', 'schema'):
+ require(before['journal'][field] == expected['journal'][field], 'same actual original telemetry database identity')
+ for field in ('helper_ledger', 'executor_lock', 'intent_store'):
+ require(before['helper_witness'][field] == expected['helper_witness'][field], 'same actual helper DB/lock/FileIDs/zero-byte leaves')
+ for role in ('service', 'helper_service'):
+ for field in ('start_name', 'start_mode', 'path', 'service_type', 'sid_type', 'service_acl_sha256'):
+ require(before[role][field] == expected[role][field], 'original exact SCM account/config/ACL')
+ baseline = canonical(before)
+ write_bytes(folder / 'baseline.json', baseline)
+ payload.update(baseline_base64=base64.b64encode(baseline).decode(), baseline_sha256=raw_sha(baseline))
+ draft['payload'] = payload
+ save(folder / 'intent.json', draft)
+ save(folder / 'server-before.json', access.server_state())
+ central = access.observe(ident)['device']; require(central and central['agent_id'] == u.transport.AGENT, 'original stored authenticated device')
+ save(folder / 'central-before.json', central)
+ print(json.dumps(dict(id=ident, prepared=True, no_component_mutation=True, baseline_sha256=raw_sha(baseline), needs_explicit_review_before_enter=True)))
+
+
+def enter(access, ident, baseline_sha):
+ folder, intent = load(ident, access)
+ require(sha(folder / 'baseline.json') == intent['payload']['baseline_sha256'] == baseline_sha, 'explicit reviewed exact baseline required')
+ indices, _, _ = prior(access)
+ require(indices == intent['original_indices'] and access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both original current indices and server gates unchanged')
+ save(folder / 'enter-attempt.json', dict(enter_once=True, baseline_sha256=baseline_sha, lost_reply_readback_only=True))
+ result = remote(access, intent, 'enter')
+ require(result.get('entered') is True and result['id'] == ident, 'actual same single transition reply')
+ save(folder / 'entered.json', result)
+ print(json.dumps(dict(id=ident, entered=True, continuation='finish/readback only; never repeat enter')))
+
+
+def finish(access, ident, read_only=False):
+ folder, intent = load(ident, access)
+ action = 'readback' if read_only else 'finish'
+ observed = remote(access, intent, action)
+ save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), observed)
+ require(observed['read_only'] is True and observed['id'] == ident, 'only existing case readback')
+ if read_only:
+ print(json.dumps(dict(id=ident, read_only=True, phase_receipts=observed['phase_receipts']))); return
+ require(observed['completed'] is True, 'actual complete pair preservation')
+ result_path = folder / 'result.json'
+ if result_path.exists():
+ previous = cb.contract.protected_json(result_path)
+ require(previous['verified'] is True and all(previous['native'][role] == observed['native'][role] for role in ('service', 'helper_service')), 'same completed current instances; no republication or mutation')
+ print(json.dumps(dict(id=ident, verified=True, retained_original_result=True, main_indices_published=False))); return
+ # Two genuinely new server heartbeats after both single starts, not cached
+ # contacts from baseline, and no new network-agent jobs/capabilities.
+ after = cb.contract.timestamp(intent['started_at']); baseline = cb.contract.protected_json(folder / 'central-before.json')
+ watermark = access.observe(ident)['device']
+ require(watermark and watermark['agent_id'] == u.transport.AGENT and watermark['last_contact_at'], 'post-finish server heartbeat watermark')
+ deadline = time.monotonic() + 150; first = None
+ while True:
+ evidence = access.observe(ident); device = evidence['device']
+ if device and device['transport'] == 'wss' and device['last_contact_at'] and cb.contract.timestamp(device['last_contact_at']) > cb.contract.timestamp(watermark['last_contact_at']):
+ require(all(device[k] == baseline[k] for k in ('agent_id', 'asset_id', 'enrollment_generation', 'assignment_version', 'certificate_sha256')), 'same original mTLS identity')
+ if first is None: first = evidence
+ elif device['last_contact_at'] != first['device']['last_contact_at']: break
+ require(time.monotonic() < deadline, 'two native post-upgrade heartbeats missing')
+ time.sleep(2)
+ final = remote(access, intent, 'finish'); native = final['native']
+ original = json.loads(base64.b64decode(intent['payload']['baseline_base64']), object_pairs_hook=cb.contract.strict_object)
+ require(native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > original['journal']['sequence'], 'fresh telemetry sequence and concrete inventory ACK')
+ device, denied = access.device_and_denials()
+ require(cb.contract.timestamp(device['observed_at']) >= after, 'fresh original stored inventory')
+ require(access.server_state() == cb.contract.protected_json(folder / 'server-before.json'), 'both target counts/policies/hooks unchanged')
+ indices, _, _ = prior(access)
+ require(indices == intent['original_indices'], 'Main current indices still original; Root owns later CAS publication')
+ pipe = u.actual_pipe_proof(native, intent)
+ result = dict(verified=True, completed=True, id=ident, original=final['original'], frozen=final['frozen'], native=native, online=dict(watermark=watermark, first=first, second=evidence), stored_inventory=device, foreign_denied=denied, native_pipe_peer_test=pipe, pipe_framing_version=2, no_jobs=True, windows_jobs_enabled=False, clock_adapter_qualified=False, system_helper_client_feature=True, helper_effects_enabled=False, no_reboot=True, no_clock_change=True, private_key_read=False, original_indices=intent['original_indices'], main_indices_published=False, manifest_path=intent['manifest_path'], manifest_sha256=intent['payload']['manifest_sha256'], qualification_sha256=intent['payload']['qualification_sha256'], runner_sha256=intent['runner_sha256'], script_sha256=intent['script_sha256'])
+ save(result_path, result)
+ print(json.dumps(dict(id=ident, verified=True, passive_preservation=True, native_pipe_peer_test=pipe, main_indices_published=False)))
+
+
+def main():
+ os.umask(0o077)
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('phase', choices=('prepare', 'enter', 'finish', 'readback', 'guards'))
+ parser.add_argument('--access-root', type=Path); parser.add_argument('--manifest', type=Path); parser.add_argument('--qualification', type=Path); parser.add_argument('--id'); parser.add_argument('--baseline-sha256')
+ args = parser.parse_args(); guards()
+ if args.phase == 'guards':
+ require(not any((args.access_root, args.manifest, args.qualification, args.id, args.baseline_sha256)), 'local source guards only'); print('PASS: local source guards; no VM action'); return
+ require(args.access_root, 'explicit separate read-only Main access root')
+ access = Access(args.access_root)
+ if args.phase == 'prepare':
+ require(args.manifest and args.qualification and not (args.id or args.baseline_sha256), 'qualified new pair and read-only baseline preparation')
+ prepare(access, args.manifest, args.qualification)
+ elif args.phase == 'enter':
+ require(args.id and args.baseline_sha256 and not (args.manifest or args.qualification), 'same prepared case and reviewed baseline hash')
+ enter(access, args.id, args.baseline_sha256)
+ else:
+ require(args.id and not (args.manifest or args.qualification or args.baseline_sha256), 'same original case readback/finish')
+ finish(access, args.id, args.phase == 'readback')
+
+
+if __name__ == '__main__':
+ try: main()
+ except Exception as error:
+ print('WINDOWS_PIPE_UPGRADE_INCOMPLETE:' + type(error).__name__)
+ raise SystemExit(2) from None
diff --git a/deploy/windows/test_system_pipe_upgrade.py b/deploy/windows/test_system_pipe_upgrade.py
new file mode 100644
index 0000000..825fc2a
--- /dev/null
+++ b/deploy/windows/test_system_pipe_upgrade.py
@@ -0,0 +1,70 @@
+"""Four local orchestration guards; no credentials/VM/Windows API calls."""
+import contextlib
+import copy
+import io
+import json
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import Mock, patch
+
+import system_pipe_upgrade as p
+
+
+def settings():
+ return dict(schema_version=1, binding={'public_fixture': True}, agent=dict(binary_sha256=p.OLD_AGENT), helper=dict(binary_sha256=p.OLD_HELPER), allowed_services=[], max_runtime_seconds=30, enable_effects=False, allow_reboot=False)
+
+
+class PipeUpgradeGuards(unittest.TestCase):
+ def test_closed_reciprocal_settings_only_change_two_image_pins(self):
+ original = settings(); preserved = copy.deepcopy(original)
+ raw, pin, policy = p.passive_settings(original, 'a' * 64, 'b' * 64)
+ changed = json.loads(raw); changed['agent']['binary_sha256'] = p.OLD_AGENT; changed['helper']['binary_sha256'] = p.OLD_HELPER
+ self.assertEqual(changed, preserved); self.assertEqual(original, preserved)
+ self.assertEqual(p.raw_sha(raw), policy); self.assertEqual(json.loads(pin)['policy_sha256'], policy)
+ for field, value in [('enable_effects', True), ('allow_reboot', True), ('allowed_services', ['foreign']), ('max_runtime_seconds', 120), ('schema_version', True)]:
+ bad = settings(); bad[field] = value
+ with self.subTest(field=field), self.assertRaises(RuntimeError): p.passive_settings(bad, 'a' * 64, 'b' * 64)
+
+ def test_historical_mutation_helpers_excluded_and_explicit_backups_ordered(self):
+ p.guards()
+ self.assertNotIn('function PinProcess', p.PREFIX)
+ self.assertNotIn('[IO.File]::Replace($candidate,$destination,$null)', p.SCRIPT)
+ self.assertIn('[RmmPipeNative]::Open([int]$before.service.pid)', p.SCRIPT)
+ self.assertNotIn('$expected=5140', p.SCRIPT)
+ self.assertIn("'helper-already-stopped.json'", p.SCRIPT)
+ self.assertIn('stop_called=$false;start_called=$false', p.SCRIPT)
+ self.assertIn("@('config','ca','identity','certificate','private_key')", p.SCRIPT)
+ self.assertEqual(p.SCRIPT.count('PreserveImmutableFiles '), 5)
+ readback = p.PHASES.split("if($p.action-ceq'readback'){", 1)[1].split("if($p.action-ceq'finish'){", 1)[0]
+ self.assertIn("(ReadbackService 'agent')", readback)
+ self.assertNotIn('(Service ', readback)
+ self.assertIn('process_identity_verified=$false', p.READBACK_SERVICE)
+ self.assertIn('pack.verified(manifest_path)', p.VERIFY_PACK)
+ self.assertIn("names==report['names']==pack.TESTS[kind]", p.VERIFY_PACK)
+ with patch.object(p.subprocess, 'run', return_value=Mock(returncode=0, stdout=b'{"type":"rmm.windows.system-delegation-build"}')):
+ with self.assertRaises(RuntimeError): p.qualified(Path('unused-fixture'), Path('unused-proof'))
+
+ def test_lost_enter_reply_cannot_repeat_target_mutation(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ folder = Path(temporary); p.write_bytes(folder / 'baseline.json', b'{}')
+ digest = p.sha(folder / 'baseline.json'); indices = {'unit_fixture': True}
+ intent = dict(payload=dict(baseline_sha256=digest), original_indices=indices)
+ p.save(folder / 'server-before.json', {'unit_counts': 0})
+ access = Mock(); access.server_state.return_value = {'unit_counts': 0}
+ with patch.object(p, 'load', return_value=(folder, intent)), patch.object(p, 'prior', return_value=(indices, {}, {})), patch.object(p, 'remote', side_effect=TimeoutError('unit fixture lost reply')) as remote:
+ with self.assertRaises(TimeoutError): p.enter(access, 'fixture', digest)
+ self.assertTrue((folder / 'enter-attempt.json').exists())
+ with self.assertRaises(FileExistsError): p.enter(access, 'fixture', digest)
+ self.assertEqual(remote.call_count, 1)
+
+ def test_readback_never_queries_server_starts_or_publishes_main_indices(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ access = Mock(); access.server_state.side_effect = AssertionError('server unavailable in readback')
+ with patch.object(p, 'load', return_value=(Path(temporary), {})), patch.object(p, 'remote', return_value=dict(read_only=True, id='fixture', phase_receipts={})) as remote, contextlib.redirect_stdout(io.StringIO()):
+ p.finish(access, 'fixture', read_only=True)
+ remote.assert_called_once_with(access, {}, 'readback')
+ self.assertFalse(access.server_state.called)
+
+
+if __name__ == '__main__': unittest.main()
diff --git a/docs/windows-dev-access-recovery.md b/docs/windows-dev-access-recovery.md
new file mode 100644
index 0000000..9a0594b
--- /dev/null
+++ b/docs/windows-dev-access-recovery.md
@@ -0,0 +1,97 @@
+# Windows-Entwicklungszugang: Ablauf und vorbereitete Konsolenwiederherstellung
+
+Stand: 2026-11-14. Der bisherige SSH-Entwicklungszugang lief am
+**2026-11-14T12:55:31.254999+00:00** ab. Die vorher vorbereitete automatische
+Verlängerung wurde **nicht betreten**: kein Server- oder Windows-Enter, keine
+Ablaufzeitänderung und kein angelegter Renewalworker. Die drei fehlgeschlagenen
+Vorbereitungen und ihre Quellen bleiben historische Belege.
+
+Diese Entwicklungshilfe ist SSH-Bootstrap, keine RMM-Aktion und kein Ersatz für
+Geräte-mTLS, Tenantgrenzen, TrustedClock, signierte Grants oder die
+WebUI-Genehmigung. Das Notebook bleibt ausschließlich Entwicklungsrechner.
+
+## Tatsächliche abgebrochene Vorbereitungen
+
+| Fall unter `devstate/windows-client/dev-access-renewal/` | Tatsächliches Ergebnis |
+| --- | --- |
+| `45626a0c-edc4-4f35-9f36-921692bccbc1` | Rein lesende Windows-Vorbereitung verweigerte `Transport owner` vor dem Serveraufruf. Die zwei öffentlichen `.pub`-Dateien gehörten dem tatsächlichen lokalen Builtin-Administrator mit SID-Endung `-500`; deren bestehende öffentlichen Leserechte waren für die ursprüngliche private Dateiprüfung zu weit. Nur die separate öffentliche Metadatenprüfung wurde später präzisiert; keine ACL-Reparatur. |
+| `d40c06a4-d6d3-4dc0-9ef6-b1ef1197bcc9` | Rein lesende Windows-Vorbereitung verweigerte `VariableNotWritable`: die Hilfsvariable `$host` kollidierte mit PowerShells schreibgeschütztem `$Host`. Die Quelle wurde anschließend auf `$hostPublic` korrigiert. Keine Server- oder Windowsmutation. |
+| `6988fd11-0e0a-4fd7-878d-96b130d83aee` | Der lokale Datums-/Fristguard verweigerte nach Ablauf der alten Frist, noch vor `prepare-intent.json`. Dies war kein weiterer ausgeführter Windows-Readonly-Test. Der leere lokale Fall bleibt erhalten. |
+
+Die ersten beiden Fälle enthalten nur Vorbereitungsintent und Controllerkopie;
+keiner enthält einen Server-/Windows-Enterintent. Root bestätigte zusätzlich,
+dass kein Renewal-Enter und kein Worker ausgeführt wurden. Ablauf und Fehler
+werden nicht nachträglich als erfolgreiche Verlängerung ausgegeben.
+
+## Getrennte Wiederherstellung des bereits abgelaufenen Zugangs
+
+Die neue Quelle
+[`console_access_recovery.py`](../deploy/windows/console_access_recovery.py)
+hat SHA-256
+`703fb5e4ae04d8555bad858c5d7b2ac4880e06d6fa951010acd43f7201a58053`.
+Sie trennt den Server-CAS von der erst anschließend durch den User in der
+Windows-Administratorkonsole auszuführenden Phase. Die frühere
+[`dev_access_renewal.py`](../deploy/windows/dev_access_renewal.py) wird für den
+abgelaufenen Lease nicht umgedeutet oder erneut gestartet.
+
+Root führte ausschließlich den Serverteil im neuen Fall
+`4b6506a7-6c3e-4cca-a497-618fa8666300` aus. Dessen `server-entered.json`
+meldet `completed=true`; ein getrennt gespeicherter lesender Readback bestätigt
+dieselbe neue Autorisierungsdatei und Frist:
+
+| Bindung | Tatsächlicher Beleg |
+| --- | --- |
+| Neue feste UTC-Frist | `2026-11-15T13:05:58+00:00` |
+| `authorized_keys` nach CAS | `fef4db300dd39fba9b52428817f453451c251c7768dd2fb6a76b39dd110dbbf2` |
+| Unverändertes SSH-Profil | `932adc2ad3e88c3a47054c3d09e44024f21918cf144f0bb349bd8763e844e482` |
+| Unveränderte effektive SSH-Konfiguration | `3a345912fdd4bb9bb29628d670a8bdbdfbbc22b3e308ab56fb3bafb7bc15533a` |
+| Server-Enterbeleg | SHA `2185a88fc32db72119a584d84a46fb25cfca5f32f6e0c4ee5b7cf0728a361317` |
+| Getrennter Readback | SHA `f6e3f69a6cd4f006d00c90cadd8bfd47f94e954f1297bea5f6eecc4fd27d3787` |
+
+Der Serverteil ersetzte ausschließlich den Ablaufwert des gleichen bestehenden
+restriktiven Tunnelkeys. Keybytes und Optionen, Loopbacklistener
+`127.0.0.1:22240`, SSH-Profil, Serverhostpin und der Account
+`rmm-win-tunnel` mit Shell `/usr/sbin/nologin` blieben gebunden. Historische
+`prepared.json`/`registered.json` wurden nicht überschrieben. Dieser CAS
+veränderte weder einen Downloadlease noch die RMM-Konfiguration.
+
+## Öffentliches Paket und noch offene Userphase
+
+Unter dem privaten Consolefall liegt ein öffentliches Paket mit genau
+`Recover-ExistingDevAccess.ps1`, `public-recovery.json` und `README.txt`.
+Es enthält öffentliche Pins und feste Parameter, keine privaten Schlüssel oder
+Tokens. Die Paketdateien sind zusätzlich im unveränderlichen Intent gebunden.
+
+| Datei | SHA-256 |
+| --- | --- |
+| `windows-dev-access-recovery.zip` | `7bf4f7bb8336fb50852f72eec2f3e370e96cb7009b14ee15aa7232c025a38ed7` |
+| `Recover-ExistingDevAccess.ps1` | `564da57d70ef06df7bd9adc37565b7e28ef446a6c69b984711c5b77b28441e8a` |
+| Consoleintent | `cd827d4056fb0045f23bff1fd9bd21b6137b53f063fe8215ad0945c2013cc44a` |
+
+Die Windows-Konsolenphase ist **noch nicht ausgeführt**. Sie prüft die alten
+Config-/Bootstrapbytes und öffentlichen Pins, den bestehenden Account sowie den
+unveränderten SYSTEM-Tunneltask. Erst bei `Ready` und ohne verbliebenen
+Maintainer/SSH-Kindprozess darf sie die vorhandene Konfigurations- und
+Accountablaufzeit erneuern und den Originaltask mit dauerhaftem Startintent
+**einmal** starten. Private Keydateien werden nur über Metadaten beobachtet,
+nicht inhaltlich gelesen. Keine Installation, ACL-Reparatur, neue Schlüssel,
+zusätzlichen SSH-Rechte, Prozesskills, Reboots oder RMM-Wirkungen.
+
+Die README verlangt den unabhängig mitgeteilten Downloadhash und den festen
+PS1-Hash. Ein etwaiges `Unblock-File` betrifft nur diese exakt geprüfte
+Download-Datei; `RemoteSigned` nur den separaten Bootstrapprozess. Eine
+verweigernde GPO oder ein fehlgeschlagener Guard wird nicht umgangen. Ein
+bereits vorhandener Recoveryfall bleibt zur lesenden Inspektion erhalten.
+
+Eine gesonderte, auf 45 Minuten begrenzte Veröffentlichung über den vorhandenen
+öffentlichen TLS-Bootstrapdienst wird durch Root separat behandelt. Dieser
+Server-CAS und diese Dokumentation belegen noch keine Downloadveröffentlichung.
+Nach der Userausführung bleiben tatsächliche Tunnelwiederkehr, ursprüngliche
+SSH-Hostidentität, erhaltene Schlüssel/Taskdefinition und die lokale
+Accessmetadatenfortschreibung durch Root zu prüfen. **Neuer Windowszugriff ist
+bis dahin nicht nachgewiesen.**
+
+Lokale Python-/AST- und Paketprüfungen sowie unabhängige Source-Reviews bestanden.
+Der lokale Paketfixture verwendete einen gemockten Serveraufruf und ist kein
+zusätzlicher nativer Recoverybeleg. Kein RMM-Job, keine Capability oder
+Clockbereitschaft folgt aus der Zugangswiederherstellung.
diff --git a/docs/windows-system-pipe-upgrade.md b/docs/windows-system-pipe-upgrade.md
new file mode 100644
index 0000000..4cb2755
--- /dev/null
+++ b/docs/windows-system-pipe-upgrade.md
@@ -0,0 +1,111 @@
+# Windows Pipe-v2: erhaltender Paarupgrade noch nicht betreten
+
+Stand: 2026-11-14. Der Paarupgrade wurde vorbereitet, aber **nicht betreten**.
+Die neue Agent-/Helpergeneration ist noch nicht als laufendes Paar nachgewiesen.
+Die Quellen- und nativen Unitbelege des Pipe-v2-Framings ersetzen weder einen
+tatsächlichen LocalService/SYSTEM-Pipeaustausch noch einen RMM-Jobnachweis.
+
+Die ursprüngliche quellengebundene
+[Framingdokumentation](windows-helper-pipe-drain.md) bleibt unverändert. Diese
+separate Datei beschreibt ausschließlich die späteren Upgradevorbereitungen.
+Der Notebookhost bleibt reiner Entwicklungsrechner; Ziel ist die eigene
+Windows-VM am endgültigen Cloudserver.
+
+## Geprüfter Kandidat und begrenzter Bootstrapvertrag
+
+Der neue Runner
+[`system_pipe_upgrade.py`](../deploy/windows/system_pipe_upgrade.py) ist mit
+SHA `e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0`
+eingefroren. Sein frischer isolierter Prüfer bindet den neuen Pipe-Packtyp und
+dessen Originalquellen, genaue native Listen mit **23 Library- und 7
+Binarytests** sowie die erhaltenen Linux-first-Corebelege mit 80 Linux- und
+58 Windowsfällen. Es gibt keine Umbenennung alter Delegationsmanifeste und
+keine Umleitung des eigenen Source-Roots auf Main.
+
+Der gebundene Pipe-Pack hat Manifest-SHA
+`b2f77713a4f70deddb6472fb1e869a85443ce1028914f62ccee71f8001fbadb4`.
+Die tatsächlichen 23+7 Windows-Administratorunits bestanden im Fall
+`db25cd4a-bfd2-45d5-9f80-1881950853f7`; dessen `passed.json` hat SHA
+`19a8ccd95b7225f7e8657a696055bea4b52ed2f80f6caa3f42c9396ce6272713`.
+Das sind Unitnachweise, kein LocalService-/Pipe-/Clock-Erfolgsbeleg.
+
+Die vorbereitete Mutation verlangt eine separat geprüfte frische Baseline mit
+SCM-/Kernel-PID und tatsächlicher Prozessgeburt, Konto, aktivem Service-SID,
+Imagehash und ACLs. Ein bereits gestoppter Manual-Helper erhält keinen
+Vorabstart. Vor der ersten Ersetzung werden vier private Sicherungen erstellt;
+jede Ersetzung verlangt zusätzlich einen eigenen zuvor fehlenden nativen
+Backupnamen und frische Datei-ID-/Hash-/ACL-CAS-Prüfungen. Beide Dienste bleiben
+bis zur vollständigen neuen EXE-/Policy-/Pingeneration gestoppt. Danach sind
+Helper- und Agentstart jeweils create-once. Config-/CA-/Identitäts-/Zertifikats-
+und Private-Key-Metadaten samt Datei-IDs werden auch nach den Ersetzungen,
+vor dem Start und beim Finish unverändert verlangt.
+
+`readback` ist rein lesend und kann auch einen fehlenden Zielpfad sowie einen
+SCM-Pendingzustand ehrlich zeigen. Baseline, Enter und Finish behalten ihre
+strengen Identitätsprüfungen. Nach verlorener Mutationsantwort gibt es keinen
+automatischen Enter-/Start-/Rollbackretry. Ein Finish benötigt neue passive
+Heartbeats und konkrete Inventar-ACKs; es schreibt nur einen lokalen Beleg.
+Main-Indizes werden ausschließlich durch Root separat per CAS fortgeschrieben.
+
+## Tatsächlicher Fall 14fb: Timeout und geprüfte erste Fortsetzung
+
+Fallverzeichnis:
+`devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020/`.
+Der erste `prepare`-Aufruf begann am `2026-11-14T12:39:48.414511+00:00`
+und endete nach 180 Sekunden mit `TimeoutExpired` während des ersten
+Stagingaufrufs. Zu diesem Zeitpunkt gab es lokal nur den Prepareintent und
+Quellkopien, keine Baseline und keinen Enterintent. Die genaue Ursache des
+SSH-/Bootstraptimeouts ist nicht nachgewiesen.
+
+Ein danach gesondert ausgeführter lesender Check bestätigte: beide neuen
+EXE-Stagingverzeichnisse, der neue entfernte Komponentenfall und der neue
+Active-Marker waren noch nicht vorhanden. Der alte Agent lief, der alte Helper
+war gestoppt. Auf dieser Abwesenheit beruhte die explizite create-once
+Fortsetzung der tatsächlich noch unerreichten Vorbereitungsphase im selben
+Fall; kein neuer Upgradefall und kein wiederholtes Enter.
+
+| Erhaltener Beleg | SHA-256 |
+| --- | --- |
+| `prepare-first-stage-timeout.json` | `535faf7c6c4c7b3dba1f8d7b7889bc59acdee09fd51c2830fe397c3c9076f1e9` |
+| `first-prepare-readonly-absence.json` | `983b38fcc2cdc8e907436eb3053f32ad2cd131e765a82dd1e9930346e1c6877b` |
+| Private Fortsetzungsquelle `continue-first-prepare.py` | `86453aef4a1d59f73e423993b548e58ad0541205961a5952c80807403881cf3b` |
+| `continue-first-prepare-intent.json` | `7420622b7866e7b43b34087d5334599444a046b95a89e7f48503aca0f4e03be0` |
+| Neue lesende `baseline.json` | `57b79e9c918df6165cac0bb451b33fcd0c207933f15351afcd2ad6c400f4e2d7` |
+
+Die Fortsetzung erzeugte schließlich den Baseline-/Intentbeleg und die
+serverseitigen Vorherbeobachtungen. Das ursprüngliche Timeout und seine
+Abwesenheitsmessung wurden nicht überschrieben.
+
+## Baseline und verbleibende tatsächliche Abnahme
+
+Die frische Baseline zeigt den weiterhin vorhandenen Agenten `89004ad3…`
+unter LocalService (`S-1-5-19`), `Running/Auto`, PID `3172`, mit exakter
+Kernel-FILETIME `134391328200102621`. Der vorhandene Helper `e6aacbdd…`
+ist `Stopped/Manual`, PID `0`; dafür wird kein laufender Prozess behauptet.
+Policy `007adf5f…` und Pin `126670bc…` gehören weiterhin zur alten Generation.
+Die Telemetriedatenbank wurde lesend mit `integrity=ok`, Sequenz `2564` und
+`pending_inventory_events=0` beobachtet. Ursprüngliche PKI-/DB-/Lock-Datei-IDs,
+ACLs und die beiden uninitialisierten Nullbyte-Intentleaves sind im privaten
+Baselinebeleg gebunden.
+
+Vorherige Serverzählungen blieben:
+Windows `jobs/outbox/permits/unresolved = 0/0/0/0`, Linux
+`30/30/26/0`. Die beobachteten API-/Gateway-Transportfaultflags waren geschlossen;
+dies ist eine konkrete Vorhermessung, kein künftiger Nachherbeleg.
+
+Der vorbereitete Kandidat umfasst Agent `f10c78dd…`, Helper `5f8c62fa…`,
+Policy `a3024467…` und Pin `af518db8…`. **Es existiert für diesen Fall noch kein
+Enterintent oder tatsächlicher Stop-/Swap-/Start-/Finishbeleg.** Staging ist
+keine Installation oder laufende Nutzung der neuen EXEs. Der alte SSH-Zugang
+lief anschließend aus; seine getrennte
+[Konsolenwiederherstellung](windows-dev-access-recovery.md) ist eine notwendige
+Zugangsstrecke und kein Paarupgrade.
+
+Nach tatsächlicher Wiederherstellung des Zugangs muss Root die Baseline vor
+Mutation erneut bewerten. Geänderte PID/Birth-, Datei-, Index- oder andere
+gebundene Werte dürfen nicht still übernommen werden. Erst danach können der
+einmalige erhaltende Paarupgrade, zwei neue tatsächliche WSS-Heartbeats,
+Inventar-ACK, Tenantverweigerung und unveränderte Job-/Policygrenzen geprüft
+werden. Ein tatsächlicher authentisierter Austausch des laufenden
+LocalService-Agenten mit dem neuen SYSTEM-Helper bleibt offen. Jobfreigabe,
+Helperwirkungen und Clockqualifikation bleiben geschlossen.