import sqlite3,shutil,hashlib,json,datetime,os
from pathlib import Path
stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'); root=Path('/home/hermes')/f'Wissenspipeline-Retrieval-Repair-Phase-1-Backup-{stamp}'; root.mkdir()
for s in ['/home/hermes/knowledge_query.py','/opt/struktur/knowledge-pipeline-aggregator-staging/knowledge_query.py','/opt/struktur/knowledge-pipeline-aggregator-staging/app.py','/opt/struktur/knowledge-pipeline-aggregator-staging/dashboard.html']:
p=Path(s); d=root/'files'/s.lstrip('/'); d.parent.mkdir(parents=True,exist_ok=True); shutil.copy2(p,d)
DB='/opt/struktur/youtube-research/knowledge.db'; src=sqlite3.connect(f'file:{DB}?mode=ro',uri=True); dst=sqlite3.connect(root/'knowledge.db'); src.backup(dst); dst.close(); src.close()
meta={'created_at_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'db_source':DB,'db_size':os.path.getsize(DB),'db_backup_size':(root/'knowledge.db').stat().st_size,'source_wal_exists':Path(DB+'-wal').exists(),'source_shm_exists':Path(DB+'-shm').exists()}; (root/'manifest.json').write_text(json.dumps(meta,indent=2))
h=[]
for p in root.rglob('*'):
if p.is_file(): h.append({'path':str(p),'size':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()})
(root/'SHA256SUMS.json').write_text(json.dumps(h,indent=2)); print(json.dumps({'path':str(root),'timestamp':meta['created_at_utc'],'files':len(h),'db_sha256':next(x['sha256'] for x in h if x['path'].endswith('/knowledge.db'))},indent=2))