import json,hashlib,re,html,shutil
from pathlib import Path
from datetime import datetime,timezone
P=Path('outputs');R=P/'recovery';W=Path('work/recovery-input');now=datetime.now(timezone.utc).isoformat()
counts=json.load(open('work/current-chat-counts.json'));assert sum(c['base']+c['additional'] for c in counts)==1566
p=P/'audit-source-register.json';d=json.loads(p.read_text());old={c['id']:c for c in d['chats']}
for c in counts:
 e=old.get(c['id'],{'id':c['id'],'title':c['title'],'url':'https://chatgpt.com/c/'+c['id']});e.update(retrieved_turns=c['base']+c['additional'],next_cursor=None,has_more=False,scope='All returned history pages retrieved for this identified conversation. Substantive full review, truncated items and original attachments are separate incomplete checks.');old[c['id']]=e
d['chats']=list(old.values());d['updated_utc']=now;d['full_enterprise_review']='INCOMPLETE — retrieval is not review; complete account source population unavailable';d['expanded_library_register']='expanded-library-inventory.json';p.write_text(json.dumps(d,indent=2))
ledger=[]
for folder in ['pages','library','library-expanded','chats','chat-history']:
 for f in sorted((W/folder).glob('*.json')):
  raw=f.read_bytes();x=json.loads(raw);ledger.append({'path':str(f),'sha256':hashlib.sha256(raw).hexdigest(),'bytes':len(raw),'type':folder,'retrieved':True,'full_substantive_review':'pending unless separately evidenced','requirements_mapping':'pending unless separately evidenced','implementation':'not implied','tested':'not implied'})
(P/'file-review-ledger.json').write_text(json.dumps({'as_of':now,'rule':'Do not change review status merely because a file was fetched, indexed or backed up. Each completed review needs source, requirement mapping and exception disposition.','files':ledger},indent=2))
correction={'id':'AUDIT-CORRECTION-20261021-01','issue':'SUSTAIN-90 was retrieved but omitted from the initial task list until Founder correction.','cause':'Selective synthesis without a completed source-to-requirement reconciliation; retrieval and substantive review were conflated.','corrective_actions':['Recorded SUSTAIN-90 under A-201/IA-136/LL-020','Finished available history pagination for all 30 identified conversations','Added file-level review ledger separating retrieval, review, action mapping and tests','Expanded Library retrieval from selected references to every currently enumerated reference route','Retried and successfully saved hourly audit and encrypted-backup automation','Preserved the first-pass defect; no retroactive passing score'],'verification':'SUSTAIN mapping present; 1566 retrieved turns reconciled; hourly ACTIVE configuration read back. Full file review and recurrence test remain open.','learning_status':'Correction implemented in records; successful reuse and recurrence prevention not yet validated','effectiveness':'99% target; attainment not established','efficiency':'99% target; predeclared time/resource denominator not established','founder_avoidable_corrections':1}
(P/'audit-corrective-action.json').write_text(json.dumps(correction,indent=2))
summary={'as_of':now,'chat_history':{'identified_conversations':30,'returned_turns':1566,'known_history_cursors_remaining':0,'full_account_census':False,'all_contents_substantively_reviewed':False},'library':{'enumerated_page_references':108,'new_readable_text_documents':73,'complete_library_inventory_available':False},'automation':{'id':'enterprise-audit-follow-through','status':'ACTIVE','frequency':'hourly','backup_on_change':True,'downloaded_restore_cadence':'at least daily','saved_configuration_verified':True,'first_scheduled_backup_receipt':None},'server':{'blueprint_requirements_recovered':True,'five_stage_request_prepared':True,'active_intake_link_verified':False,'formal_request_submitted':False,'server_access_performed':False,'scope':'storage only'},'sustain_90':{'required_threshold':90,'actual_score':None,'ten_failed_points':False,'status':'Unscored — no validated readiness score'},'remaining_source_routes':['Full Library/account inventory is not exposed by current connector','Browser fallback is signed out','Unsupported archives, oversized text and repeated source-freshness failures are individually logged','Original attachments and previously truncated items require separate recovery and review']}
(R/'current-recovery-status.json').write_text(json.dumps(summary,indent=2))
p=R/'business-recovery-plan.html';s=p.read_text();start=s.index('<div class="notice">');end=s.index('</div>',start)+6;s=s[:start]+'<div class="notice"><strong>Scheduling correction:</strong> the supported app update succeeded on October 21. The existing audit-and-recovery task is ACTIVE hourly, with encrypted snapshots on change and at least daily downloaded restore checks. Saved configuration was read back. Scheduled-run reliability and missed-run escalation still require operating evidence; the earlier rejection is resolved at configuration level.</div>'+s[end:];s=s.replace('Complete enterprise coverage and continuous updating are not established.','Complete enterprise coverage remains open. Hourly updating is configured; successful scheduled execution remains to be evidenced.').replace('Initial snapshot only; schedule update rejected','Hourly update configured; first scheduled backup receipt pending').replace('Backup receipt captured; automatic backup update rejected.','Backup receipt captured; hourly update now configured.');p.write_text(s)
rows=''.join('<li>'+html.escape(x)+'</li>' for x in correction['corrective_actions'])
doc='<!doctype html><html lang="en"><meta charset="utf-8"><title>Enterprise audit correction and current execution</title><style>body{font:17px/1.6 system-ui;max-width:1000px;margin:40px auto;padding:20px;color:#172733}table{border-collapse:collapse;width:100%}td,th{padding:12px;border:1px solid #ddd;text-align:left}h2{margin-top:30px}</style><h1>Audit correction and current execution</h1><p>'+html.escape(correction['issue'])+' '+html.escape(correction['cause'])+'</p><h2>Completed corrections</h2><ul>'+rows+'</ul><h2>SUSTAIN-90: threshold versus result</h2><p>90/100 is the required readiness threshold. Actual readiness remains unscored, so there are no ten failed points to explain. Open evidence spans accepted operators and backups; alternate-operator runbooks; 72-hour continuity; alert receipts and escalation; source-backed financial continuity; instruction and learning reconciliation. These are unverified dimensions, not ten proven failures.</p><h2>ETV Blueprint</h2><p>The request follows preflight, approved public-link submission, host-issued temporary token and isolated destination, absolute 600-second expiry, and complete ingress closure. The former link was explicitly terminated. No current intake link or accepted storage adapter was verified; submission, token issuance and upload have not occurred. No server retrieval is permitted by this assignment.</p><h2>Review coverage</h2><p>30 identified conversations, 1,566 returned turns, and no remaining pagination cursor for those conversations. The complete account inventory, attachments and full substantive file review are still open. 108 linked Library references are enumerated; 73 additional text documents were retrieved this pass. A file-level ledger prevents retrieval from being counted as review.</p><h2>Administrative scheduling issue</h2><p>The earlier tool returned a rejected-call response, not a Google Drive outage. Retrying the supported update under the Founder’s renewed direction succeeded. The existing task is now ACTIVE hourly with backup-on-change instructions and daily restore verification. No second duplicate schedule was created. First scheduled-run proof remains pending.</p><h2>My performance accountability</h2><p>The SUSTAIN omission is retained as one avoidable Founder correction. The targets remain 99% effectiveness and 99% efficiency. Neither is claimed achieved: full instruction coverage and eligible work populations must be reconciled, and time/resource bounds must be defined before efficiency scoring. The repaired method must pass a subsequent review before the lesson is called validated.</p></html>'
(P/'audit-correction-and-current-execution.html').write_text(doc)
for f in [P/'audit-source-register.json',P/'expanded-library-inventory.json',P/'file-review-ledger.json',P/'audit-corrective-action.json',P/'audit-correction-and-current-execution.html',R/'current-recovery-status.json',R/'business-recovery-plan.html',R/'sustain-90-evidence-register.json']:
 shutil.copyfile(f,W/f.name)
shutil.copyfile('work/sustain-source.json',W/'sustain-source.json')
print(json.dumps({'files_indexed':len(ledger),'turns':1566,'chats':30,'scheduling':'active hourly'}))
