Files
canina/infra/hermes-pilot/executor.py

65 lines
3.7 KiB
Python

"""Fixed Tech/Dev pilot. Adapter must supply a fresh authenticated PREPARE lease."""
import datetime, hashlib, json, os, pathlib, re, subprocess, tempfile, time
TASK='tech-dev-clamp-quantity-v1'
IMAGE='sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f'
def validate_lease(lease):
if (set(lease) != {'taskId','runId','leaseToken','leaseUntil','commitSha','environment','maxCostCents','attempt'}
or lease['environment']!='staging' or lease['maxCostCents']!=20 or lease['attempt']!=1
or not re.fullmatch('[a-f0-9]{40}',lease['commitSha'])):
raise ValueError('Bounded PREPARE lease required')
for k in ('taskId','runId','leaseToken'):
if not re.fullmatch('[a-f0-9-]{36}',lease[k]): raise ValueError('Invalid lease binding')
expiry=datetime.datetime.fromisoformat(lease['leaseUntil'].replace('Z','+00:00')).timestamp()
if not 5 < expiry-time.time() <= 31: raise ValueError('Fresh 30-second lease required')
return lease
def _execute(lease, artifact_root, infer, heartbeat):
"""No claim/approval generation. heartbeat must call trusted server; errors abort.
infer is the pinned runner, not a browser-supplied command or prompt.
Completion is deliberately NOT sent: existing transport accepts tracer JSON only.
"""
validate_lease(lease)
heartbeat(lease)
root=pathlib.Path(tempfile.mkdtemp(prefix='real-pilot-',dir=artifact_root))
def git(*args):
return subprocess.check_output(['git','-C',str(root),*args],stderr=subprocess.DEVNULL,text=True,timeout=1).strip()
git('init','-q'); git('config','user.email','pilot@invalid'); git('config','user.name','Bounded Hermes Pilot')
(root/'README').write_text('Disposable fixture; PREPARE source '+lease['commitSha']+'\n')
git('add','README'); git('commit','-qm','Seed isolated pilot fixture')
base=git('rev-parse','HEAD')
# One cancellable inference, no tools; ongoing authenticated guard.
source=infer()
heartbeat(lease)
if not isinstance(source,str) or len(source.encode())>2048: raise ValueError('Invalid generated artifact')
(root/'quantity.py').write_text(source)
qa=subprocess.check_output(['python3','-I',str(pathlib.Path(__file__).with_name('qa.py')),str(root)],timeout=3,text=True)
heartbeat(lease)
git('add','quantity.py'); git('commit','-qm','Hermes generated quantity clamp; independent QA passed')
patch=git('diff',base,'HEAD','--','quantity.py')+'\n'
(root/'artifact.patch').write_text(patch)
report={'kind':'REAL_HERMES_TECH_DEV_PILOT','task':TASK,'taskId':lease['taskId'],'runId':lease['runId'],
'sourceCommit':lease['commitSha'],'artifactCommit':git('rev-parse','HEAD'),'baseCommit':base,
'patchSha256':hashlib.sha256(patch.encode()).hexdigest(),'qa':json.loads(qa),
'costCents':None,'costStatus':'UNKNOWN_RETAIN_FULL_20_CENT_RESERVATION',
'gate1':'EXTERNAL_LEASE_REQUIRED','published':False,'deploymentExecuted':False}
(root/'evidence.json').write_text(json.dumps(report,indent=2)+'\n')
return root,report
from runtime import LeaseGuard, ProcessInference, pinned_inference
def execute(lease, artifact_root, infer, heartbeat):
validate_lease(lease)
with LeaseGuard(lease, heartbeat) as guard:
guard.check()
if not isinstance(infer, ProcessInference):
raise TypeError("Cancellable ProcessInference required")
def generate():
response = json.loads(infer.run(guard))
if not isinstance(response,dict) or response.get("tools") != 0 or response.get("model") != "Free":
raise ValueError("Pinned tool-less model required")
return response["source"]
result = _execute(lease, artifact_root, generate, lambda _: guard.check())
guard.check()
return result