"""Validate an administrator's metadata-only strict-admission impact report.""" import datetime as dt import hashlib import json import re from pathlib import Path def validate_report(path, *, namespace, database, cutoff, live_commit, now=None): path = Path(path) if path.stat().st_size > 8 * 1024 * 1024: raise ValueError('Readiness report too large.') body = path.read_bytes() r = json.loads(body) if not isinstance(r, dict): raise ValueError('Invalid readiness object.') if not isinstance(live_commit, str) or not re.fullmatch('[0-9a-f]{40}', live_commit): raise ValueError('Unknown live source commit.') if r.get('scope') != 'deployment' or r.get('organizationId') != '' or r.get('database') != database: raise ValueError('Strict activation requires complete deployment-wide database scope.') if r.get('schema') != 'droboticflow.source-readiness/v1' or r.get('namespace') != namespace or r.get('targetMode') != 'strict' or (r.get('complete') is not True) or (r.get('projectId') != '') or (r.get('legacySourceCutoff', '') != (cutoff or '')) or (r.get('buildCommit') != live_commit): raise ValueError('Incomplete, scoped or mismatched strict readiness report.') if not isinstance(r.get('generatedAt'), str): raise ValueError('Invalid readiness timestamp.') at = dt.datetime.fromisoformat(r['generatedAt'].replace('Z', '+00:00')) if at.tzinfo is None: raise ValueError('Readiness timestamp must include timezone.') age = ((now or dt.datetime.now(dt.timezone.utc)) - at).total_seconds() if not 0 <= age <= 3600: raise ValueError('Readiness report is expired or in the future.') totals = {k: 0 for k in ('total', 'allowed', 'unverified', 'pending', 'failed')} rows = r['rows'] if not isinstance(rows, list): raise ValueError('Invalid readiness rows.') seen = set() for row in rows: if not isinstance(row, dict): raise ValueError('Invalid readiness row.') key = (row.get('organizationId'), row.get('stage'), row.get('status')) if not all((isinstance(x, str) for x in key)) or key in seen: raise ValueError('Duplicate or invalid readiness group.') seen.add(key) if not isinstance(row.get('stage'), str) or not isinstance(row.get('status'), str): raise ValueError('Missing readiness stage/status.') for k in totals: v = row.get(k) if type(v) is not int or v < 0: raise ValueError('Invalid readiness count.') totals[k] += v if row['total'] != sum((row[k] for k in ('allowed', 'unverified', 'pending', 'failed'))): raise ValueError('Readiness counts do not reconcile.') if totals['total'] != totals['allowed']: raise ValueError('Strict mode would block existing tasks; keep advisory and review the impact.') return {'path': str(path.resolve()), 'sha256': hashlib.sha256(body).hexdigest(), 'scope': 'deployment', 'generatedAt': r['generatedAt'], 'totals': totals}