"""Read-only inventory of the current matrix, routes, documents and QA proofs.""" from pathlib import Path from collections import Counter,defaultdict from datetime import datetime,timezone import csv,hashlib,json,re ROOT=Path(__file__).resolve().parents[2];DOCS=ROOT/'docs/investmoz/v2/auditoria-portal';OUT=Path(__file__).resolve().parent csv.field_size_limit(10000000) def readcsv(p): with p.open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f)) def digest(p):return hashlib.sha256(p.read_bytes()).hexdigest() matrix=readcsv(DOCS/'matriz-requisitos.csv') backlog=readcsv(DOCS/'backlog-priorizado.csv') sources=readcsv(DOCS/'inventario-fontes.csv') assert len({r['ID'] for r in matrix})==len(matrix) summary={'at':datetime.now(timezone.utc).isoformat(),'matrix_headers':list(matrix[0]),'backlog_headers':list(backlog[0]),'requirements':len(matrix),'backlog_rows':len(backlog),'sources':len(sources),'matrix_sha256':digest(DOCS/'matriz-requisitos.csv'),'states':dict(Counter(r['Estado'] for r in matrix)),'prefixes':dict(Counter(r['ID'].split('-')[0] for r in matrix))} for key in ['Módulo/rota','Módulo','Prioridade']: if key in matrix[0]:summary[key]=dict(Counter(r[key] for r in matrix)) summary['sample_requirements']=[{k:v[:380] for k,v in r.items()} for r in matrix if r['ID'].startswith(('AUD-','COUNTRY','GEO-','STATS','DESK','SIM-','V2-'))] summary['closed']=[{k:v[:450] for k,v in r.items()} for r in matrix if r['Estado']=='concluído e demonstrado'] sources_result=[] for row in sources: raw=row['Exemplar/caminho'];p=Path(raw.split('#')[0]);base=p if not p.exists() and str(p).lower().startswith('c:\\mac\\home\\'): base=Path('\\\\mac\\home\\'+str(p)[12:]) entry={'reference':raw,'expected_sha256':row['SHA256'],'original_exists':base.is_file(),'embedded_member':'#' in raw,'resolved_path':str(base)} if base.is_file() and '#' not in raw: try:entry.update(current_sha256=digest(base),size=base.stat().st_size,same_bytes=digest(base)==row['SHA256']) except OSError as e:entry.update(read_error=type(e).__name__) sources_result.append(entry) summary['source_availability']=dict(Counter('embedded' if r['embedded_member'] else 'available_same' if r.get('same_bytes') else 'available_changed' if r['original_exists'] else 'unavailable' for r in sources_result)) proof_candidates=[] for p in (ROOT/'outputs').rglob('*.json'): if any(x in p.name.lower() for x in ['private','actors','password','credentials','baseline']):continue try: data=json.loads(p.read_text(encoding='utf-8-sig')) if isinstance(data,dict): proof_candidates.append({'path':p.relative_to(ROOT).as_posix(),'sha256':digest(p),'result':data.get('result',data.get('status')),'at':data.get('at',data.get('verified_at',data.get('finished_at'))),'target':data.get('target',data.get('base',data.get('destination'))),'criteria_keys':list(data.get('checks',data.get('criteria',{}))) if isinstance(data.get('checks',data.get('criteria',{})),dict) else []}) except (OSError,ValueError):pass route_lines=[] for p in (ROOT/'routes').glob('*.php'): for i,line in enumerate(p.read_text(encoding='utf-8').splitlines(),1): if 'Route::' in line and not line.lstrip().startswith('//'):route_lines.append({'file':p.relative_to(ROOT).as_posix(),'line':i,'code':line.strip()}) summary['route_declarations']=len(route_lines) summary['evidence_json_files']=len(proof_candidates) summary['files_in_docs_v2']=len(list((ROOT/'docs/investmoz/v2').rglob('*.*'))) for name,data in [('inventory.json',summary),('source-availability.json',sources_result),('evidence-index.json',proof_candidates),('route-declarations.json',route_lines)]: (OUT/name).write_text(json.dumps(data,ensure_ascii=False,indent=2),encoding='utf-8') print(json.dumps({k:v for k,v in summary.items() if k not in ['sample_requirements','closed','Módulo/rota']},ensure_ascii=False))