Files
canina/scripts/corporate_pilot.py
T
2026-10-28 13:08:29 +00:00

110 lines
6.5 KiB
Python

#!/usr/bin/env python3
"""Explicit local integration pilot. Requires disposable migrated PostgreSQL :55441."""
import json
import os
from pathlib import Path
import secrets
import subprocess
import sys
import time
import urllib.request
import corporate_runtime as r
def pilot_environment(environ):
# Idempotency is scoped to authenticated subject: fresh keys alone are not
# enough when the disposable database is retained between manual runs.
return dict(environ, CORPORATE_API_KEY=secrets.token_hex(32),
CORPORATE_QA_API_KEY=secrets.token_hex(32),
CORPORATE_PILOT_RUN_ID=secrets.token_hex(16),
CORPORATE_TEST_DATABASE_URL='postgresql://hermes@127.0.0.1:55441/corporate_test')
def main():
root = Path(__file__).resolve().parent.parent
scratch = Path(os.environ['CORPORATE_PILOT_DIR']).resolve()
if not str(scratch).startswith('/opt/data/cache/scratch/'):
raise ValueError('Scratch pilot output required')
scratch.mkdir(parents=True, exist_ok=True, mode=0o700)
env = pilot_environment(os.environ)
server = subprocess.Popen(['node', str(root/'scripts/corporate_pilot_server.cjs')], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
base = 'http://127.0.0.1:55442/api/admin/hermes'
transcript = []
def cli(command, *args, key=None):
cmd = [sys.executable,str(root/'scripts/corporate_runtime.py'),'--api',base,'--store',str(scratch/'store')]
if key: cmd += ['--key',key]
result = subprocess.run(cmd+[command,*args],env=env,text=True,capture_output=True,timeout=90)
if result.returncode:
raise ValueError(command + ' failed: ' + result.stderr)
value = json.loads(result.stdout)
transcript.append({'command':command,'result':value})
return value
def manifest(name, value):
path=scratch/(name+'.json');path.write_text(json.dumps(value));return str(path)
try:
for _ in range(100):
try:
req = urllib.request.Request(base+'/runtime', headers={'x-api-key':env['CORPORATE_API_KEY']})
with urllib.request.urlopen(req,timeout=1): break
except Exception:
if server.poll() is not None: raise ValueError('Nest pilot host failed')
time.sleep(.1)
else: raise ValueError('Nest readiness timeout')
assert cli('status')['schedulesEnabled'] is False
insight=cli('ingest',manifest('research',{
'title':'Manual official Hermes documentation source inventory pilot','category':'TREND',
'source':'Official Hermes documentation fetched over verified HTTPS',
'opportunity':'Validate read-only source provenance, not a clinical or market claim',
'impact':'LOW','recommendedAction':'Independent exact-byte inventory QA only', 'cadence':'EVENT',
'provenance':{'method':'manual HTTPS GET + SHA256','collector':'manual CLI pilot','context':'disposable local integration, not production analytics'},
'fetchSources':[{'url':'https://hermes-agent.nousresearch.com/docs/llms.txt','title':'Official Hermes docs index'}]
}),'--hosts','hermes-agent.nousresearch.com',key='pilot-research')
replay=cli('replay-ingest',insight['requestDigest'],key='pilot-research')
assert replay['id']==insight['research']['id']
roadmap=cli('roadmap',manifest('roadmap',{
'researchId':replay['id'],'cycleName':'Manual local pilot','month':r.now()[:7],
'seasonalTheme':'No seasonal inference','strategicGoals':['Verify read-only evidence'],
'plannedArticlesCount':0,'plannedRefreshesCount':0,'plannedCatalogEnrichments':0,'isActive':False,
'goals':[{'title':'Inventory fetched official docs source','department':'CONTENT_SEO',
'acceptanceCriteria':'Exact source byte digests match persisted provenance','metric':'source_inventory_verified'}]
}),key='pilot-roadmap')
tasks=cli('fanout',roadmap['id'],key='pilot-fanout')
assert cli('fanout',roadmap['id'],key='pilot-fanout')[0]['id']==tasks[0]['id']
execution=cli('execute','--department','CONTENT_SEO',key='pilot-execution')
task_id=execution['taskId']; evidence=execution['evidence']
# Executor identity cannot self-review; exercise real backend denial.
own_env=os.environ.copy()
try:
os.environ['CORPORATE_API_KEY']=env['CORPORATE_API_KEY']
c=r.Client(base,'CORPORATE_API_KEY')
try: r.review(c,r.Store(scratch/'store'),task_id,evidence['id'],'self-review-denied')
except ValueError as e: assert '409' in str(e)
else: raise AssertionError('self-review unexpectedly allowed')
finally:
os.environ.clear();os.environ.update(own_env)
cli('qa',task_id,evidence['id'],key='pilot-independent-qa')
cli('effect',task_id,manifest('effect',{'metric':'production_engagement','availability':'UNINSTRUMENTED',
'source':'Local pilot has no production analytics instrumentation','observedAt':r.now()}),key='pilot-effect')
cli('report',manifest('report',{'day':r.now()[:10], 'summary':'Manual local source-inventory pilot only; no publishing, deployment or measured production effect.'}),key='pilot-report')
req=urllib.request.Request(base+'/tasks/'+task_id,headers={'x-api-key':env['CORPORATE_QA_API_KEY']})
with urllib.request.urlopen(req) as response: detail=json.load(response)
assert detail['status']=='DONE' and len(detail['effects'])==1 and len(detail['reviews'])==1
assert detail['evidence'][0]['sha256']==evidence['sha256']
assert detail['reviews'][0]['reviewer'] != detail['evidence'][0]['executor']
transcript.append({'persistedReadback':{'taskId':task_id,'status':detail['status'],
'logs':[x['step'] for x in detail['logs']], 'effects':detail['effects'],
'sha256':evidence['sha256'],'independentSubjects':True,'selfReviewDenied':True}})
(scratch/'transcript.json').write_text(json.dumps(transcript,indent=2))
print(json.dumps({'status':'PASS','taskId':task_id,'artifactDigest':evidence['sha256'],
'transcript':str(scratch/'transcript.json')}))
finally:
server.terminate()
try: output, _ = server.communicate(timeout=10)
except subprocess.TimeoutExpired:
server.kill()
output, _ = server.communicate()
(scratch/'server.log').write_bytes(output)
if __name__=='__main__': main()