Files
jason.woltje 4ac6f13bcf fix(case2): row 227 R4 source overlay as reviewed (packet 4eb60915, #1728)
Commits the 5 product paths and 7 gate helpers of the row 227 R4 source overlay on top of HEAD 5a0c801cb. scripts/case2/console.mjs is already committed at HEAD and is not part of this commit. The R4 independent review is sha256 6667baaa6af9d6d78a3ec7c64d9f3163ecbc350b94050f62899d9c01deabe002, verdict APPROVE source-only. Packet hashes: PACKET.sha256 4eb60915b2144137df9b5a42afd0c5b266718d71de051fb8be53a27430a2cad4, CURRENT-SOURCE.sha256 0cfd47c2073bc18a3ba7bff1ce6fdf39fe33a64b7fca209be71517b9feb89020. The 12 committed files match the review hash table, the applied overlay JSON (size, mode, hash) and the saved overlay tar. No scripts/test-case2.sh run exists on these bytes.
2026-11-02 13:39:29 -06:00

167 lines
10 KiB
Python

# Static-prepared admitted1014-only gate. No local execution; existing900/-k10 ceiling.
import sys
sys.dont_write_bytecode=True
import os,json,time,hashlib,subprocess,signal,secrets,shutil,re
from pathlib import Path
from evidence import Evidence
from inputs import Inputs
from owned import Owned
from association import Association
ROOT=Path.cwd().resolve();BASE=ROOT/'agents/steelbeak/work/queue-227';GATE=BASE/'gate'
E=Evidence(Path(sys.argv[1]).resolve());private=None;child=None;root_key=None;owner=None;control=None;assoc=None;frozen=None
handles={};pins_before=None;rc=None;sent=False;start=time.monotonic();cleanup=dict(disposition='not-started',private=None,survivors=None)
def guarded(code,fn,default=None):
try:return fn()
except Exception as exc:E.fail(code+'-'+type(exc).__name__);return default
def preserve_control():
if control is None:return
directories=[(control,'root-control'),(control/'host','host-control'),(control/'launches','launch-control'),(control/'authorizations','host-authorization')]
if assoc:
for run in assoc.launches:
path=Path(run)
for name in ['.row227-native-control.json','session.json','runner.log']:
E.raw(path/name,'run-control',missing_ok=True)
for pending in path.glob('*.pending'):E.raw(pending,'run-control',missing_ok=True)
directories += [(Path(run)/'.row227-native','sandbox-control') for run in assoc.launches]
directories += [(Path(launch['registry']),'runtime-control') for launch in assoc.launches.values()]
for directory,category in directories:
def capture_directory():
for path in directory.iterdir():
if path.is_file() or path.is_symlink():E.raw(path,category,missing_ok=True)
if directory.exists():guarded('raw-directory-capture',capture_directory)
def capture_driver():
if private is None:return
for sandbox in (private/'T').glob('tmp.*'):
if sandbox.is_symlink():E.fail('sandbox-symlink');continue
for name in ['steps.txt','stderr.txt']:
if name not in handles:
try:handles[name]=(sandbox/name).open('rb')
except FileNotFoundError:pass
def stop_owned():
global sent
if child is None or child.poll() is not None or sent:return
# No PID or signal selection from a JSON record.
if owner is None or root_key is None or not owner.valid(root_key):E.fail('root-stop-identity-unresolved');return
os.killpg(root_key[0],signal.SIGTERM);sent=True
try:
os.setpriority(os.PRIO_PROCESS,0,19)
if os.getpriority(os.PRIO_PROCESS,0)!=19:raise RuntimeError('driver-native-priority-refused')
if len(sys.argv)!=4:raise RuntimeError('admitted-run-needs-output-admission-and-sha')
# Copies raw admission/list before parsing. Checks already admitted joined identities,
# complete execution closure and consumed manifest digest before any test process exists.
frozen=Inputs(ROOT,sys.argv[2],sys.argv[3],E)
pins_before=frozen.measure();E.write('pins.before.json',pins_before)
if E.failures:raise RuntimeError('admitted-source-inputs-refused')
private=Path(subprocess.check_output(['mktemp','-d','/tmp/R227XXXXXX'],text=True).strip());cleanup.update(private=str(private),disposition='retained-until-verified')
for name in ['H','C','T','G']:(private/name).mkdir(mode=0o700)
control=private/'G'
for name in ['host','launches','authorizations']:(control/name).mkdir(mode=0o700)
nonce=secrets.token_hex(16);boot=Path('/proc/sys/kernel/random/boot_id').read_text().strip()
config=dict(version=1,nonce=nonce,private=str(private));(control/'control.json').write_text(json.dumps(config)+'\n');os.chmod(control/'control.json',0o600)
env=dict(os.environ)
for key in list(env):
if any(word in key for word in ['TOKEN','SECRET','PASSWORD','API_KEY','AUTH_SOCK','BUS_CAP','CREDENTIAL']):env.pop(key)
env.update(HOME=str(private/'H'),XDG_CONFIG_HOME=str(private/'C'),TMPDIR=str(private/'T'),MOSAIC_CONFIG=str(private/'C/config.json'),NO_COLOR='1',NODE_OPTIONS='--import='+str(GATE/'priority.mjs'),ROW227_CONTROL_ROOT=str(control),ROW227_CONTROLLER_CLEANUP='1')
os.setpriority(os.PRIO_PROCESS,0,19)
if os.getpriority(os.PRIO_PROCESS,0)!=19:raise RuntimeError('driver-native-priority-refused')
def preexec():
os.setpriority(os.PRIO_PROCESS,0,19)
if os.getpriority(os.PRIO_PROCESS,0)!=19:os._exit(125)
os.setsid()
owner=Owned(boot,E);assoc=Association(ROOT,private,control,nonce,boot,frozen,owner,E)
argv=['timeout','-k','10','900','bash','scripts/test-case2.sh']
E.write('command.json',dict(argv=argv,private=str(private),driverNice=os.getpriority(os.PRIO_PROCESS,0),controllerOwnsScratchRemoval=True,admissionSha256=sys.argv[3],joinedIdentity=frozen.profile['joinedIdentity']))
with (E.root/'stdout.raw').open('wb') as out,(E.root/'stderr.raw').open('wb') as err:
child=subprocess.Popen(argv,cwd=ROOT,env=env,stdout=out,stderr=err,preexec_fn=preexec);root_key=owner.root(child.pid,os.getpid())
while True:
try:
if os.getpriority(os.PRIO_PROCESS,0)!=19:E.fail('driver-native-priority-drift')
fresh=owner.traverse();preserve_control();fresh=assoc.poll(fresh);capture_driver()
for key,row in fresh.items():
if row['state']!='Z' and row['exe']==frozen.execs['node'] and key not in assoc.accepted and time.monotonic()-owner.first[key]>=5:E.fail('required-associated-node-timeout')
except Exception as exc:E.fail('monitor-error-'+type(exc).__name__)
if E.failures:guarded('owned-stop',stop_owned)
if child.poll() is not None:break
time.sleep(.01)
rc=child.wait()
except Exception as exc:E.fail('gate-error-'+str(exc) if isinstance(exc,RuntimeError) else 'gate-error-'+type(exc).__name__)
finally:
# Each action is separately guarded; malformed control, pins, observation or cleanup may
# never bypass the best-effort raw/failure/cleanup/result records below.
final_nice=guarded('driver-final-native-readback',lambda:os.getpriority(os.PRIO_PROCESS,0))
E.write('driver-final-native.json',dict(nice=final_nice))
if final_nice!=19:E.fail('driver-final-native-priority-refused')
guarded('final-raw-capture',preserve_control)
if child is not None and child.poll() is None:
guarded('final-owned-stop',stop_owned)
rc=guarded('child-not-reaped',lambda:child.wait(timeout=10),rc)
if child is not None and child.poll() is None:E.fail('owned-child-still-live')
for name,handle in handles.items():
def finish_stream(name=name,handle=handle):
handle.seek(0);data=handle.read();E.write('driver-'+name,data);handle.close()
guarded('driver-capture-finalization',finish_stream)
if child is not None and set(handles)!=set(['steps.txt','stderr.txt']):E.fail('required-driver-capture-missing')
if frozen:
measured=guarded('pin-finalization',frozen.measure)
E.write('pins.after.json',measured)
if measured!=pins_before:E.fail('source-input-pins-changed')
if assoc:
guarded('association-finalization',assoc.complete)
E.write('association.json',dict(accepted=[dict(pid=k[0],start=k[1],binding=v) for k,v in assoc.accepted.items()],pending=[repr(k) for k in assoc.pending],launches=assoc.launches,registries=assoc.registries))
if control:
def verify_closure():
closure=E.parse(control/'fixture-cleanup.json','fixture-closure')
if not isinstance(closure,dict) or closure.get('runtimeEntries')!=[]:E.fail('fixture-closure-unresolved')
elif not Path(closure.get('dataRoot','/')).resolve().is_relative_to(private):E.fail('fixture-closure-root-refused')
if (control/'fixture-cleanup.pending').exists():E.fail('fixture-closure-publication-incomplete')
guarded('fixture-closure-finalization',verify_closure)
if owner:
survivors=guarded('survivor-observation',owner.fresh_survivors)
cleanup['survivors']=survivors
if survivors is None or survivors:E.fail('owned-cleanup-unresolved')
E.write('process-history.json',list(owner.history.values()))
guarded('final-raw-capture',preserve_control)
if assoc:
for registry in set(v['registry'] for v in assoc.launches.values()):
def verify_registry(registry=registry):
path=Path(registry)
if path.exists() and list(path.iterdir()):E.fail('runtime-registry-cleanup-unresolved')
guarded('registry-cleanup-observation',verify_registry)
def hashes():
rows=[]
for p in sorted(E.root.iterdir()):
if p.is_file() and (p.suffix=='.raw' or p.name.startswith('driver-')):
data=p.read_bytes();rows.append(dict(path=p.name,bytes=len(data),sha256=hashlib.sha256(data).hexdigest()))
E.write('raw-hashes.json',rows)
guarded('raw-hash-finalization',hashes);E.inventory_write()
def leak_guard():
values=[]
for source in [ROOT/'scripts/case2/e2e.mjs',ROOT/'scripts/case2/fixture-credentials.mjs']:
values+=re.findall(r"const (?:FETCH_TOKEN|SEAT_TOKEN|HUMAN_TOKEN|FAKE_ZAI_KEY) = '([^']+)'",source.read_text())
# Raw-control bytes may include private fixture data; retain them as evidence, but no token
# is permitted in user-facing streams or metadata/history output.
for p in E.root.rglob('*'):
if p.is_file() and 'raw-inputs' not in p.parts and p.suffix in ['.raw','.json','.jsonl']:
if any(v.encode() in p.read_bytes() for v in values):E.fail('fixture-value-in-output-history')
guarded('leak-guard-finalization',leak_guard)
if rc!=0:E.fail('whole-script-nonzero',unknown=False)
cleanup['disposition']='retained-unresolved' if E.failures or E.unknown else 'verified-ready-to-remove'
# Commit failure/ownership disposition before removal. All failures retain the private root.
E.reserved(E.cleanup,cleanup);E.reserved(E.final,dict(exit=rc,acceptance=False,stage='before-cleanup',failures=E.failures,cleanup=cleanup))
if private is not None and not E.failures and not E.unknown:
try:shutil.rmtree(private);cleanup['disposition']='removed';cleanup['privateRootRemoved']=not private.exists()
except Exception as exc:E.fail('private-removal-'+type(exc).__name__);cleanup['disposition']='removal-error-retain-remainder';cleanup['privateRootRemoved']=False
elif private is not None:
cleanup['privateRootRemoved']=guarded('private-root-observation',lambda:not private.exists(),False)
E.reserved(E.cleanup,cleanup)
ok=rc==0 and not E.failures and cleanup.get('privateRootRemoved') is True
if not E.reserved(E.final,dict(exit=rc,acceptance=ok,elapsed=time.monotonic()-start,failures=E.failures,cleanup=cleanup)):ok=False
try:print(json.dumps(dict(exit=rc,acceptance=ok,failures=E.failures,cleanupDisposition=cleanup['disposition'])))
except Exception:ok=False
sys.exit(0 if ok else 1)