← back to Ticket System

data/codex-yoloforever/cycle-20260908T1651Z.AQuuOW/monitor.py

94 lines

import datetime, hashlib, json, math, os, pathlib, plistlib, subprocess, sys, urllib.request, urllib.error

P = pathlib.Path(__file__).resolve().parent
ROOT = pathlib.Path('/Users/macstudio3/Projects/ticket-system')
PREV = ROOT/'data/codex-yoloforever/cycle-20260908T1322Z.m4gNE5'
commands, checks = [], []
def sha(p): return hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest()
def run(argv, input_text=None):
    r = subprocess.run(argv, capture_output=True, text=True, timeout=45, input=input_text)
    commands.append(dict(argv=argv, stdin=input_text, exit_code=r.returncode, stdout=r.stdout, stderr=r.stderr))
    return r
def check(name, ok, detail): checks.append(dict(check=name, verdict='PASS' if ok else 'FAIL', detail=detail))
def save(name, data): (P/name).write_text(json.dumps(data,indent=2)+'\n')

baseline_path = P/'preconditions.json'
if not baseline_path.exists():
    protected = list(json.loads((PREV/'preconditions.json').read_text())['files']) + [
        '/Users/macstudio3/Library/LaunchAgents/com.steve.codex-yoloforever.plist',
        '/Users/macstudio3/.claude/yolo-queue/pending-approval/2026-09-08-TK-10928-projects-root-snapshot-recovery.md',
        '/Users/macstudio3/.claude/yolo-queue/pending-approval/2026-09-04-TK-10066-architectural-fabrics-1005-active-no-price.md']
    save('preconditions.json',dict(timestamp=datetime.datetime.now(datetime.timezone.utc).isoformat(),files={x:sha(x) for x in protected},repository_head=run(['git','-C',str(ROOT),'rev-parse','HEAD']).stdout.strip()))
base=json.loads(baseline_path.read_text())
check('zero-cost environment and canonical filesystem guard',os.getenv('DTD_ZERO_COST')=='1' and (ROOT/'config/dtd-cost-mode').read_text()=='ZERO_COST_REQUIRED\n','Read only, no controls modified')
for path,digest in base['files'].items(): check('protected file '+path,sha(path)==digest,digest)
for path in list(base['files'])[1:4]:
    s=pathlib.Path(path).read_text(); guard=s.index('ZERO_COST_REQUIRED) DTD_ZERO_COST=1')
    credentials=s.find('SECRETS_ENV') if 'SECRETS_ENV' in s else s.find('ENV="$HOME/Projects/secrets-manager/.env"')
    check('filesystem forces zero before credential branch '+path,guard<credentials,dict(guard_offset=guard,credential_offset=credentials,method='Read installed source, no environment unset/override'))

# Re-read canonical ticket immediately before each ordered assessment.
def canonical_before(number):
    js="const l=require('/Users/macstudio3/Projects/ticket-system/lib');console.log(JSON.stringify([...l.tickets().values()].find(t=>t.id.startsWith('TK-"+number+"-'))));"
    r=run(['node','-e',js]); t=json.loads(r.stdout)
    save('canonical-before-'+number+'.json',dict(observed_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),ticket=t))
    return t
canonical_before('10928')
r=run(['du','-sk','/Users/macstudio3/Projects/.git']); kib=int(r.stdout.split()[0]); mb=math.floor(kib/1024+.5)
r=run(['node','--input-type=module','-e',"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,result:classifyRepo({repo:'(projects-root)',mb:"+str(mb)+",remote:null,upstream:null,ahead:0})}));"])
classification=json.loads(r.stdout)
check('actual installed canary boundary',r.returncode==0 and classification['floor']==3000 and classification['result']['verdict']==('FAIL' if mb>3000 else 'WARN' if mb>=2850 else 'PASS'),dict(measured_mb=mb,**classification))
r=run(['launchctl','list','com.steve.dw-backup-canary']); check('backup scheduler loaded and state captured',r.returncode==0,'No kickstart or notification runner invoked; exit state alone is not recovery')
latest=pathlib.Path('/Users/macstudio3/.claude/skills/dw-backup-canary/data/latest.json'); artifact=json.loads(latest.read_text())
save('backup-artifact.json',dict(observed_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),mtime_utc=datetime.datetime.fromtimestamp(latest.stat().st_mtime,datetime.timezone.utc).isoformat(),sha256=sha(latest),data=artifact))
refs=run(['git','--git-dir=/Users/macstudio3/Projects/.git','show-ref']).stdout
check('root protected master observed','c539b5a08a4f84a551d8825a0fc73fa588bcbce8 refs/heads/master' in refs,dict(refs=refs,index_sha256=sha('/Users/macstudio3/Projects/.git/index'),scope='Existing writer may advance snapshot; this is not a stable maintenance preflight'))

# Position 2: bounded authoritative READ ONLY freshness and existing log metadata only.
canonical_before('11290')
remote_sql="BEGIN READ ONLY; SHOW transaction_read_only; SELECT json_build_object('checked_at',now(),'latest_phase3',max(phase3_ai_at),'stale_hours',round(EXTRACT(EPOCH FROM (now()-max(phase3_ai_at)))/3600)) FROM enrichment_tracking; ROLLBACK;"
r=run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=10','kamatera',"runuser -u postgres -- psql -X -v ON_ERROR_STOP=1 -d dw_unified -At -f -"],remote_sql)
phase3=[json.loads(x) for x in r.stdout.splitlines() if x.startswith('{')]
check('authoritative phase3 READ ONLY query and rollback',r.returncode==0 and '\non\n' in r.stdout and r.stdout.rstrip().endswith('ROLLBACK') and len(phase3)==1,phase3)
r=run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=10','kamatera',"stat -c '%s %y' /root/DW-Agents/logs/full-monte-phase3.log"])
save('enrichment-observed.json',dict(timestamp=datetime.datetime.now(datetime.timezone.utc).isoformat(),phase3=phase3,log_stat=r.stdout.strip(),log_stat_exit=r.returncode,scope='Timestamp/log metadata only; no request-level cause inferred, checker/provider not executed'))
check('existing enrichment log metadata observed',r.returncode==0,r.stdout.strip())
# Position 3: local mirror and scoped existing inputs; no current Shopify proof.
canonical_before('11250')
sql=PREV/'11250-pricing.sql'
r=run(['/opt/homebrew/bin/psql','-X','-w','-h','/tmp','-d','dw_unified','-At','--set','ON_ERROR_STOP=1','-f',str(sql)])
rows=[json.loads(x) for x in r.stdout.splitlines() if x.startswith('{')]
check('pricing READ ONLY transaction with ROLLBACK',r.returncode==0 and len(rows)==2 and rows[0]['read_only']=='on' and r.stdout.rstrip().endswith('ROLLBACK'),rows)
prior=json.loads((PREV/'11250-assessment.json').read_text())
changed=[]
for x in prior['files']:
    q=pathlib.Path(x['path']); st=q.stat() if q.exists() else None
    if st is None or st.st_size!=x['size'] or st.st_mtime!=x['mtime']: changed.append(str(q))
discovered=[]
for scope in prior['input_scope']:
    r=run(['rg','--files','--hidden','-g','!node_modules','-g','!.git','-g','!.env*',scope])
    discovered.extend(x for x in r.stdout.splitlines() if any(k in pathlib.Path(x).name.lower() for k in ['wholesale','price','pricing','cost']))
save('pricing-inputs.json',dict(rows=rows,known_files_checked=len(prior['files']),changed_metadata=changed,filename_candidates=discovered,scopes=prior['input_scope'],limits='Scoped local filename/metadata check only; not exhaustive discovery or byte identity. No current Shopify count claimed.'))
for path,want in [('/healthz',200),('/api/tickets',401)]:
    try:
        with urllib.request.urlopen('http://127.0.0.1:9794'+path,timeout=10) as r: code,body=r.status,r.read().decode()
    except urllib.error.HTTPError as e: code,body=e.code,e.read().decode()
    check('ticket API '+path,code==want,dict(status=code,body=body[:160]))
r=run(['node','-e',"const l=require('/Users/macstudio3/Projects/ticket-system/lib'); console.log(JSON.stringify([...l.tickets().values()].map(t=>({id:t.id,status:t.status,assignee:t.assignee,kind:t.kind,updated_at:t.updated_at,blocker:t.blocker||null,last_action:t.actions.slice(-1),last_comment:t.comments.slice(-1)}))))"])
board=json.loads(r.stdout); commands[-1]['stdout']='Canonical board summarized in canonical-observed.json; full response intentionally omitted here.'
start=json.loads((P/'canonical-start.json').read_text()); selected=[t for t in board if t['id'] in {x['id'] for x in start['tickets']}]
save('canonical-observed.json',dict(timestamp=datetime.datetime.now(datetime.timezone.utc).isoformat(),tickets=selected))
for t in start['tickets'][:3]:
    now=next(x for x in selected if x['id']==t['id'])
    check('source owner/status preserved '+t['id'],(t['assignee'],t['status'])==(now['assignee'],now['status']),dict(before={k:t[k] for k in ['status','assignee','updated_at']},after=now))
save('in-flight-monitoring.json',[dict(**t,monitoring='Canonical owner/activity only; no worker or source action launched; carried TK10993 approval not exercised') for t in selected if t['id'] not in {x['id'] for x in start['tickets'][:3]}])
plist=pathlib.Path('/Users/macstudio3/Library/LaunchAgents/com.steve.codex-yoloforever.plist'); config=plistlib.loads(plist.read_bytes())
r=run(['launchctl','list','com.steve.codex-yoloforever']); check('existing 600-second loop active',config.get('StartInterval')==600 and r.returncode==0 and not (ROOT/'data/codex-yoloforever/STOPPED').exists(),dict(interval=config.get('StartInterval'),sentinel=False,worker_exit='Runner observes after return'))
r=run(['pmset','-g']); check('sleep and display sleep zero','displaysleep         0' in r.stdout and 'sleep                0' in r.stdout,r.stdout)
r=run(['defaults','-currentHost','read','com.apple.screensaver','idleTime']); check('screensaver off',r.returncode==0 and r.stdout.strip()=='0',r.stdout)
r=run(['df','-k','/Users/macstudio3']); check('disk capacity observed',r.returncode==0,r.stdout)
for name,why in [('live backup and scheduler recovery','Exact current maintenance approval absent; historical rehearsal does not close source outcome'),('enrichment recovery and provider-specific cause','Authoritative liveness observed only; provider-neutral per-request null reason still required, no retry or checker POST'),('authoritative pricing and sellability','Vendor wholesale/identity missing; live catalog mutation remains gated'),('worker exit','Observed by launchd only after this turn returns')]: checks.append(dict(check=name,verdict='SKIP',detail=why))
name=sys.argv[1] if len(sys.argv)>1 else 'monitor-proof.json'
out=dict(timestamp=datetime.datetime.now(datetime.timezone.utc).isoformat(),intent='Read-only monitoring of every ordered queue entry',risk_tier='R0 evidence; underlying R4 outcomes blocked',build_identity=base['repository_head'],root_mb=mb,pricing_rows=rows,checks=checks,commands=commands,counts={v:sum(c['verdict']==v for c in checks) for v in ['PASS','FAIL','SKIP']},execution_iterations=0,implementation_progress=0,operational_closures=0,ui='No UI built; installed canary/API/auth-negative/READ ONLY SQL are the empirical substitute for CTA and screenrecord',cleanup='No source/runtime edits; SQL rollback; evidence retained')
save(name,out); print(json.dumps({k:out[k] for k in ['timestamp','root_mb','pricing_rows','counts']})); sys.exit(bool(out['counts']['FAIL']))