← back to Ticket System

data/codex-yoloforever/cycle-20260908T1508Z.kSOq7u/cody-run.py

58 lines

import pathlib,subprocess,json,hashlib,datetime,os,urllib.request,urllib.error
P=pathlib.Path(__file__).parent
S=pathlib.Path(subprocess.check_output(['mktemp','-d','/private/tmp/cody-1508-XXXXXX'],text=True).strip())
checks=[];commands=[]
def check(n,b,d): checks.append({'check':n,'verdict':'PASS' if b else 'FAIL','detail':d})
def run(argv):
 r=subprocess.run(argv,capture_output=True,text=True,timeout=25);commands.append({'argv':argv,'exit_code':r.returncode,'stdout':r.stdout,'stderr':r.stderr});return r
sha=lambda p:hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest()
base=json.loads((P/'preconditions.json').read_text());protected={p:sha(p) for p in base['files']}
inputs={f:sha(P/f) for f in ['assessment.json','ordered-dispositions.json','monitor-initial.json','canonical-start.json','preconditions.json','pricing-inputs.json']}
check('canonical mode exact',pathlib.Path('/Users/macstudio3/Projects/ticket-system/config/dtd-cost-mode').read_text().strip()=='ZERO_COST_REQUIRED','Read first; no override/unset')
for p,h in protected.items():check('protected baseline '+p,h==base['files'][p],h)
for p in list(base['files'])[1:4]:
 t=pathlib.Path(p).read_text();g=t.index('ZERO_COST_REQUIRED) DTD_ZERO_COST=1');c=t.index('for SECRETS_ENV in' if 'post-decision' in p else ('ENV=\"$HOME/Projects/secrets-manager/.env\"' if '/.claude/' in p else 'SECRETS_ENV='));check('guard precedes credentials '+p,g<c,{'guard_offset':g,'credential_offset':c,'source_semantics':'file forces 1 regardless of absent child environment; credential reads guarded'})
 r=run(['bash','-n',p]);check('shell syntax '+p,r.returncode==0,r.stderr)
r=run(['du','-sk','/Users/macstudio3/Projects/.git']);mb=int(int(r.stdout.split()[0])/1024+0.5)
js="import {classifyRepo,KNOWN_LEGIT} from '/Users/macstudio3/.claude/skills/dw-backup-canary/lib.mjs'; console.log(JSON.stringify({floor:KNOWN_LEGIT['(projects-root)'].floor_mb,results:[3000,3001,"+str(mb)+"].map(mb=>({mb,...classifyRepo({repo:'(projects-root)',mb,remote:null,upstream:null,ahead:0})}))}));"
r=run(['node','--input-type=module','-e',js]);c=json.loads(r.stdout);check('installed canary actual+negative threshold',c['floor']==3000 and [x['verdict'] for x in c['results']]==['WARN','FAIL','FAIL'],c)
check('monitor measured root',mb==json.loads((P/'monitor-initial.json').read_text())['root_mb'],{'independent_mb':mb,'time':datetime.datetime.now(datetime.timezone.utc).isoformat()})
sql="BEGIN READ ONLY; SET LOCAL statement_timeout='10s'; SELECT json_build_object('read_only',current_setting('transaction_read_only'),'rows',count(*),'positive_cost',count(*) FILTER(WHERE cost>0),'positive_price',count(*) FILTER(WHERE NULLIF(price,'')::numeric>0)) FROM rwltd_catalog; SELECT json_build_object('price_columns',count(*)) FROM information_schema.columns WHERE table_name='vahallan_catalog' AND column_name ~ '(price|cost)'; ROLLBACK;"
(S/'pricing.sql').write_text(sql)
r=run(['/opt/homebrew/bin/psql','-X','-w','-h','/tmp','-d','dw_unified','-At','--set','ON_ERROR_STOP=1','-f',str(S/'pricing.sql')]);rows=[json.loads(x) for x in r.stdout.splitlines() if x.startswith('{')];check('fresh READ ONLY local pricing and rollback',r.returncode==0 and rows==[{'read_only':'on','rows':1470,'positive_cost':0,'positive_price':0},{'price_columns':0}] and 'ROLLBACK' in r.stdout,rows)
for path,want in [('/healthz',200),('/api/tickets',401)]:
 try:
  with urllib.request.urlopen('http://127.0.0.1:9794'+path,timeout=10) as z:status=z.status;body=z.read().decode()
 except urllib.error.HTTPError as e:status=e.code;body=e.read().decode()
 check('actual localhost '+path,status==want,{'status':status,'body':body})
ids=[x['ticket'] for x in json.loads((P/'ordered-dispositions.json').read_text())]
js="const l=require('/Users/macstudio3/Projects/ticket-system/lib'); const ids="+json.dumps(ids)+"; console.log(JSON.stringify([...l.tickets().values()].filter(t=>ids.includes(t.id)||t.id==='TK-11287-drive-open-tickets-in-board-order-using').map(t=>({id:t.id,status:t.status,assignee:t.assignee,updated_at:t.updated_at,receipt:t.actions.filter(a=>a.agent==='codex-yoloforever-cody').slice(-1)}))))"
r=run(['node','-e',js]);current=json.loads(r.stdout)
canonical=json.loads((P/'canonical-start.json').read_text());allstart=canonical if isinstance(canonical,list) else canonical.get('tickets',canonical.get('rows',[]))
if not isinstance(allstart,list):allstart=[]
for t in current:
 if t['id'] in ids:
  old=next((x for x in allstart if x.get('id')==t['id']),None)
  if old is None:
   def find(z):
    if isinstance(z,dict):
     if z.get('id')==t['id']:return z
     for v in z.values():
      a=find(v)
      if a:return a
    if isinstance(z,list):
     for v in z:
      a=find(v)
      if a:return a
   old=find(canonical)
  check('canonical source status owner timestamp '+t['id'],old is not None and all(t[k]==old[k] for k in ['status','assignee','updated_at']),{'before':{k:old.get(k) for k in ['status','assignee','updated_at']} if old else None,'after':t})
receipt=next(x for x in current if x['id'].startswith('TK-11287'))['receipt'][-1]['correlation_id']
for label in ['com.steve.dw-backup-canary','com.steve.codex-yoloforever']:
 r=run(['launchctl','list',label]);check('loaded scheduler '+label,r.returncode==0,'Read-only state, no run/pause/restart; current worker exit not proven')
r=run(['pmset','-g']);check('sleep disabled','displaysleep         0' in r.stdout and 'sleep                0' in r.stdout,r.stdout)
r=run(['defaults','-currentHost','read','com.apple.screensaver','idleTime']);check('screensaver disabled',r.stdout.strip()=='0',r.stdout)
check('all protected hashes stable after',all(sha(p)==h for p,h in protected.items()),protected)
for n,why in [('live backup recovery','current maintenance preflight/window/exact plan approval absent'),('authoritative pricing and sellability','local mirror is scoped evidence; wholesale identity inputs and write approval absent'),('parent acceptance final DTD and worker exit','belongs to accountable finalizer/runner')]:checks.append({'check':n,'verdict':'SKIP','detail':why})
d={'task_id':'cycle-20260908T1508Z.kSOq7u/cody','packet':'M-02294','packet_correlation':'dm-mtst50ob-6900-2m8m0z','receipt_correlation':receipt,'timestamp':datetime.datetime.now(datetime.timezone.utc).isoformat(),'intent':'independent bounded monitoring-report accuracy review','risk_tier':'R0 evidence; R4 sources remain gated','build_identity':base['repository_head'],'source_outcomes':'Both UNRESOLVED','execution_iterations':0,'execution_cap':6,'implementation_progress':0,'input_hashes':inputs,'protected_before_after':protected,'checks':checks,'counts':{k:sum(x['verdict']==k for x in checks) for k in ['PASS','FAIL','SKIP']},'commands':commands,'scratch_retained':str(S),'cost':{'direct_paid_api_usd':0,'external_spend_usd':0,'subscription_tokens':'unmeasured','provider_key_reads':0,'claude_calls':0},'cleanup':'READ ONLY SQL ROLLBACK; scratch retained; no deletion, source/control/runtime/status/owner change, commit or descendants','limitations':['No duplicate historical restore/rehearsal run','No current Shopify counts or exhaustive pricing input discovery','Canonical snapshot check is a temporal observation; independent shared writers may advance later','Shared session color unchanged to preserve assigned cody-only write scope']}
(P/'cody-proof.json').write_text(json.dumps(d,indent=2)+'\n');print(json.dumps({'counts':d['counts'],'receipt':receipt,'root_mb':mb,'scratch':str(S)}))