import json,os,gzip,hashlib,collections,subprocess,sys,io CREATED='2026-10-22T10:00:00Z' def dumps(o): return json.dumps(o,ensure_ascii=False,separators=(',',':')) def write_lines(path,records,gz): raw=('\n'.join(dumps(r) for r in records)+('\n' if records else '')).encode('utf-8') h=hashlib.sha256(raw).hexdigest() if gz: with open(path+'.gz','wb') as f: with gzip.GzipFile(fileobj=f,mode='wb',mtime=0,compresslevel=9) as g: g.write(raw) else: open(path,'wb').write(raw) return h def write_package(outdir,manifest,events,entities,relations,links,omitted,omitted_counts,gz=()): os.makedirs(outdir,exist_ok=True) for f in os.listdir(outdir): os.remove(os.path.join(outdir,f)) events=sorted(events,key=lambda e:(e['time']['start'],e['id'])) entities=sorted(entities,key=lambda e:e['id']) relations=sorted(relations,key=lambda r:(r['source'],r['target'],r['type'])) links=sorted(links,key=lambda l:(l['from'],l['to'],l['kind'],l.get('relation',''))) files={} for name,recs in (('events.jsonl',events),('entities.jsonl',entities),('entity_relations.jsonl',relations),('links.jsonl',links),('omitted.jsonl',omitted)): if name in('entity_relations.jsonl','omitted.jsonl') and not recs: continue h=write_lines(os.path.join(outdir,name),recs,name in gz) files[name]=dict(records=len(recs),sha256=h) ev_ids={e['id'] for e in events};ref=set(r['entity'] for e in events for r in e['refs']) has=set();bk=collections.Counter();bl=collections.Counter();br=collections.Counter();prop=0 for l in links: has.add(l['from']);has.add(l['to']);bk[l['kind']]+=1;bl[l['evidence']['existence']['level']]+=1 if 'relation' in l: br[l['relation']]+=1 if l['propagates']: prop+=1 st=dict(events=len(events),entities=len(entities),entity_relations=len(relations), links=dict(total=len(links),propagating=prop,by_kind=dict(bk),by_level=dict(bl)), omitted=dict(by_reason=dict(omitted_counts)),events_without_links=len([e for e in ev_ids if e not in has]), unreferenced_entities=len([e for e in entities if e['id'] not in ref]), merged_duplicates=sum(len(e['provenance'].get('merged_from',[])) for e in events)) if br: st['links']['by_relation']=dict(br) manifest=dict(manifest);manifest['statistics']=st;manifest['files']=files;manifest.setdefault('warnings',[]);manifest['created_at']=CREATED json.dump(manifest,open(os.path.join(outdir,'manifest.json'),'w',encoding='utf-8'),ensure_ascii=False,indent=1) return st def validate(outdir,report=None): r=subprocess.run([sys.executable,'/home/claude/pkg/validate_package.py',outdir,'--schema','/home/claude/pkg/cascade_package.schema.json','--max-messages','4']+(['--report',report] if report else []),capture_output=True,text=True) return r.returncode,r.stdout EXPL={'cycle':"Pairs or groups of events at the same minute or year that link to each other in both directions. The links carry direction 'evidence'; the algorithm contracts such a cycle into one compound event", 'statistics':"omitted.jsonl lists at most 10,000 items per reason; the counts in statistics.omitted are complete", 'window':"Some events lie just outside the stated window because of the operating-day convention or imputed year dates; the window is the range of the source files", 'direction':"Links between events that are not simultaneous at the stated precision but carry direction 'evidence' because the evidence gives the order", 'judge':"Judge type is unspecified for some links",'truncated_evidence':"Evidence text ends with an ellipsis",'flags':"Imputed time without the flag time_imputed",'order':"Events are not sorted by start time",'propagation':"Propagation differs from the declared default",'relation':"Link of a kind with relations carries no relation",'pii':"String that looks like an e-mail address or credential; checked by hand",'provenance':"Event without source ids"} def finalize(outdir,extra=None): rc,o=validate(outdir,outdir+'.report.json') rep=json.load(open(outdir+'.report.json')) m=json.load(open(os.path.join(outdir,'manifest.json'))) ex=dict(EXPL);ex.update(extra or {}) m['warnings']=[dict(code=k,message=ex.get(k,'See validator output'),count=v) for k,v in sorted(rep['summary']['warnings'].items())] json.dump(m,open(os.path.join(outdir,'manifest.json'),'w',encoding='utf-8'),ensure_ascii=False,indent=1) import jsonschema sch=json.load(open('/home/claude/pkg/cascade_package.schema.json')) jsonschema.Draft202012Validator({'$schema':sch['$schema'],'$defs':sch['$defs'],'$ref':'#/$defs/manifest'}).validate(m) return rc,rep['summary']