"""OpenAgentWorks reference validator. Never executes package source or accesses network. Two conformance scopes. A package that requires standard_catalogs_v1 is judged in full: trusted standard schemas, references, graphs, bindings. A package that does not is a custom profile and is judged in the declared-profile scope: the envelope and manifest as always, every resource against the schema the package registers for it, and its catalogs for kind, ids and version. Nothing the reference does not understand is interpreted, and the report names each thing it did not check: profile features, native formats, the business validator.""" import sys sys.dont_write_bytecode=True from pathlib import Path,PurePosixPath import json,hashlib,base64,re,unicodedata from jsonschema import Draft202012Validator,FormatChecker VERSION='1.4.0-pilot.1' DIALECT='https://json-schema.org/draft/2020-12/schema' SUPPORTED={'bagit_sha256','catalog_schema_2020_12','trace_graph_v1','standard_catalogs_v1','agentic_tools_v1','typed_workflow_bindings_v1','projection_digest_v1','autonomous_build_v1','agent_runtime_contracts_v1','build_pilot_v1','scenario_request_bindings_v1','scenario_coherence_v1'} class Invalid(ValueError): def __init__(self,code,msg):self.code=code;super().__init__(msg) def fail(code,msg):raise Invalid(code,msg) def require(ok,code,msg): if not ok:fail(code,msg) def sha(b):return hashlib.sha256(b).hexdigest() def path(s): require(isinstance(s,str) and s and not any(ord(c)<32 for c in s),'UNSAFE_PATH','Control or empty path') p=PurePosixPath(s) require(not p.is_absolute() and all(x not in ('','.','..') for x in s.split('/')) and '\\' not in s and ':' not in s,'UNSAFE_PATH',s) return s def pairs(ps): d={} for k,v in ps: require(k not in d,'INVALID_SCHEMA','Duplicate JSON key '+k);d[k]=v return d def load(p): try:return json.loads(p.read_text('utf-8'),object_pairs_hook=pairs,parse_constant=lambda x:fail('INVALID_SCHEMA','Non-finite JSON number')) except Invalid:raise except Exception as e:fail('INVALID_SCHEMA',str(p)+': '+str(e)) def assert_schema(s,v,label): try: Draft202012Validator.check_schema(s) # Reference implementation supports only fragment $ref; other adapters must explicitly map local external schemas. def check(x): if isinstance(x,dict): if '$ref' in x:require(x['$ref'].startswith('#/'),'UNSUPPORTED_PROFILE','External schema reference '+x['$ref']) require('$dynamicRef' not in x,'UNSUPPORTED_PROFILE','dynamicRef adapter unavailable') for k,y in x.items(): if k not in ('const','enum','examples','default'):check(y) elif isinstance(x,list): for y in x:check(y) check(s) errs=sorted(Draft202012Validator(s,format_checker=FormatChecker()).iter_errors(v),key=lambda e:str(e.path)) require(not errs,'INVALID_SCHEMA',label+': '+(errs[0].message if errs else '')) except Invalid:raise except Exception as e:fail('INVALID_SCHEMA',label+': '+str(e)) def inspect_schema(s,label): Draft202012Validator.check_schema(s) def walk(x): if isinstance(x,dict): if '$ref' in x:require(x['$ref'].startswith('#/'),'UNSUPPORTED_PROFILE','External schema reference in '+label) require('$dynamicRef' not in x,'UNSUPPORTED_PROFILE','dynamicRef adapter unavailable in '+label) for k,v in x.items(): if k not in ('const','enum','default','examples'):walk(v) elif isinstance(x,list): for v in x:walk(v) walk(s) def dag(edges,label): states={} def visit(n): require(n in edges,'INVALID_DEPENDENCY_GRAPH',label+' missing vertex '+str(n)) require(states.get(n)!=1,'INVALID_DEPENDENCY_GRAPH',label+' cycle '+str(n)) if states.get(n)==2:return states[n]=1 for d in edges[n]:visit(d) states[n]=2 for n in edges:visit(n) def snapshot(data,paths): return sha(b''.join((p+'\0'+sha((data/path(p)).read_bytes())+'\n').encode('utf-8') for p in sorted(paths))) def outside_bag(output,bag): require(not Path(output).resolve().is_relative_to(Path(bag).resolve()),'UNSAFE_PATH','Output must be outside the sealed bag') def validate(root,standard_root=None): root=Path(root).resolve();data=root/'data';checks=0 def ck(ok,code,msg): nonlocal checks;checks+=1;require(ok,code,msg) ck(root.is_dir(),'INVALID_INTEGRITY','Missing bag directory') files={} for p in root.rglob('*'): ck(not p.is_symlink(),'UNSAFE_PATH','Symlink '+str(p)) if p.is_file():files[path(p.relative_to(root).as_posix())]=p else:ck(p.is_dir(),'UNSAFE_PATH','Special file') ck(len(files)<=10000 and sum(p.stat().st_size for p in files.values())<=100*1024*1024 and all(p.stat().st_size<=20*1024*1024 for p in files.values()),'UNSAFE_PATH','Unpacked bag size limit') aliases={} for n in files: a=unicodedata.normalize('NFC',n).casefold();ck(a not in aliases,'UNSAFE_PATH','Path collision '+n);aliases[a]=n ck(set(files).issuperset({'bagit.txt','bag-info.txt','manifest-sha256.txt','tagmanifest-sha256.txt','data/package.json'}),'INVALID_INTEGRITY','Missing bag control files') ck(set(files)-{n for n in files if n.startswith('data/')}=={'bagit.txt','bag-info.txt','manifest-sha256.txt','tagmanifest-sha256.txt'},'INVALID_INTEGRITY','Unexpected tag file') ck(files['bagit.txt'].read_bytes()==b'BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n','INVALID_INTEGRITY','Bag version/encoding') def manifest(name): found={} for line in files[name].read_text('utf-8').splitlines(): m=re.fullmatch(r'([0-9a-f]{64}) (.+)',line);ck(m is not None,'INVALID_INTEGRITY','Malformed manifest line') h,n=m.groups();path(n);ck(n not in found,'INVALID_INTEGRITY','Duplicate manifest entry '+n) ck(n in files and sha(files[n].read_bytes())==h,'INVALID_INTEGRITY','Digest '+n);found[n]=h return found payload=manifest('manifest-sha256.txt');tags=manifest('tagmanifest-sha256.txt') ck(set(payload)=={n for n in files if n.startswith('data/')},'INVALID_INTEGRITY','Payload manifest incomplete') ck(set(tags)=={'bagit.txt','bag-info.txt','manifest-sha256.txt'},'INVALID_INTEGRITY','Tag manifest incomplete') oxum=str(sum(files[n].stat().st_size for n in payload))+'.'+str(len(payload)) ck('Payload-Oxum: '+oxum in files['bag-info.txt'].read_text().splitlines(),'INVALID_INTEGRITY','Payload oxum') pkg=load(data/'package.json');std=Path(standard_root) if standard_root else Path(__file__).resolve().parents[1] assert_schema(load(std/'schemas/package.schema.json'),pkg,'package.json');checks+=1 ck(pkg['profile']['version']=='1.0.0','UNSUPPORTED_PROFILE','Profile version') # A package that claims the standard catalogs is judged as one. One that does # not is a custom profile, judged in the declared-profile scope (docs/custom-profiles.md). declared='standard_catalogs_v1' not in pkg['required_features'];unknown=sorted(set(pkg['required_features'])-SUPPORTED);native=[] if not declared: ck(not unknown,'UNSUPPORTED_PROFILE','Required feature not supported') ck(pkg['business_validator_id'] is None,'UNSUPPORTED_PROFILE','Product-specific validator requires reviewed adapter: '+str(pkg['business_validator_id'])) def unchecked(run,n): """In a custom profile, a schema using what this reference cannot evaluate safely (an external or dynamic reference) is kept and named as not checked; anywhere else it is refused.""" try:run();return False except Invalid as e: if declared and e.code=='UNSUPPORTED_PROFILE':native.append(n);return True raise resources=pkg['resources'];index={r['path']:r for r in resources} ck(len(index)==len(resources),'INVALID_SCHEMA','Duplicate resource paths') ck(set(index)=={n[5:] for n in payload},'INVALID_INTEGRITY','Resource registration mismatch') ck(set(pkg['canonical_catalogs'])=={n for n,r in index.items() if r['role']=='canonical_catalog'},'INVALID_SCHEMA','Catalog index mismatch') ck(len(pkg['canonical_catalogs'])==len(set(pkg['canonical_catalogs'])),'INVALID_SCHEMA','Duplicate canonical catalog') for n,r in index.items(): path(n) for src in r['source_paths']:ck(src in index,'UNRESOLVED_REFERENCE','Source '+src) mode=r['validation'];sp=r['schema_path'] if sp is not None:ck(path(sp) in index,'UNRESOLVED_REFERENCE','Schema '+sp) if mode=='json_schema': s=load(data/n) # A custom profile may carry a third party's schema in that party's own dialect: kept, named as not checked. if declared and s.get('$schema')!=DIALECT:native.append(n) else: ck(s.get('$schema')==DIALECT,'UNSUPPORTED_PROFILE','Schema dialect adapter unavailable: '+n) if not unchecked(lambda:inspect_schema(s,n),n):checks+=1 elif mode=='json': ck(sp is not None,'INVALID_SCHEMA','Missing schema_path '+n) if declared and load(data/sp).get('$schema')!=DIALECT:native.append(n) elif not unchecked(lambda:assert_schema(load(data/sp),load(data/n),n),n):checks+=1 elif mode in ('python_source','dependency_lock'): pass # Stored as inert bytes; no execution or installation. elif r['required']: if declared:native.append(n) # Kept as inert bytes; named in the report as not checked. else:fail('UNSUPPORTED_PROFILE','Native adapter required: '+mode+' at '+n) if declared:return declared_profile(pkg,data,index,files,checks,unknown,native,root,std) catalogs={};records={};kindof={} for n in pkg['canonical_catalogs']: cat=load(data/n);kind=cat['kind'];ck(kind not in catalogs,'INVALID_SCHEMA','Duplicate catalog kind '+kind) # Check against trusted standard schema as well as producer-declared schema. assert_schema(load(std/'schemas/catalogs'/f'{kind}.schema.json'),cat,n);checks+=1 ck(cat['product_version']==pkg['product_version'],'INVALID_SCHEMA','Product version drift '+n);catalogs[kind]=cat['records'] for rec in cat['records']: ck(rec['id'] not in records,'UNRESOLVED_REFERENCE','Duplicate global ID '+rec['id']);records[rec['id']]=rec;kindof[rec['id']]=kind for k in ['sources','product','capabilities','requirements','acceptance_tests','releases','work_packages','traceability']:ck(k in catalogs,'INVALID_COVERAGE','Required catalog '+k) for k in ['product','capabilities','requirements','releases','work_packages']:ck(bool(catalogs[k]),'INVALID_COVERAGE','Empty required catalog '+k) def ref(x,kind=None):ck(x in records and (kind is None or kindof[x]==kind),'UNRESOLVED_REFERENCE','Reference '+str(x)+' expected '+str(kind)) # Explicit keys avoid treating literal constraints or embedded JSON Schemas as ID links. kinds={'source_refs':'sources','capability_refs':'capabilities','acceptance_refs':'acceptance_tests','requirement_refs':'requirements','release_ref':'releases','domain_refs':'domains','persona_refs':'personas','target_persona_refs':'personas','success_metric_refs':'metrics','tool_refs':'tools','policy_refs':'policies','agent_refs':'agents','evaluation_refs':'evaluations','asset_refs':'assets','metric_refs':'metrics','entity_ref':'entities','state_machine_ref':'state_machines','source_entity_refs':'entities','mitigation_refs':'requirements','dataset_refs':'fixtures'} for rid,rec in records.items(): for key,expected in kinds.items(): if key in rec and rec[key] is not None: for x in rec[key] if isinstance(rec[key],list) else [rec[key]]:ref(x,expected) for key in ('permissions_refs','evidence_refs','producer_refs','consumer_refs','record_refs','affected_refs','test_refs','output_refs','supersedes','source_refs_extra'): for x in rec.get(key,[]):ref(x) for key in ('from_id','to_id'): if key in rec:ref(rec[key]) if kindof[rid] in ('tools','agents'): for key in ('input_schema','output_schema'):inspect_schema(rec[key],rid+'/'+key);checks+=1 for rid,rec in records.items(): for key in ('trigger_schema','context_schema','payload_schema'): if key in rec:inspect_schema(rec[key],rid+'/'+key);checks+=1 if kindof[rid]=='entities': for field in rec['fields']:inspect_schema(field['schema'],rid+'/'+field['name']);checks+=1 releases={x['id']:x['sequence'] for x in catalogs['releases']};ck(len(set(releases.values()))==len(releases),'INVALID_DEPENDENCY_GRAPH','Duplicate release sequence') wp=catalogs['work_packages'];owners={};partition_owners={};edges={} for p in wp: ck(len(p['requirement_refs'])==len(set(p['requirement_refs'])),'INVALID_COVERAGE','Duplicate WP requirement') flat=[] for part in p['release_partitions']: release=part['release_ref'];ref(release,'releases');vertex=(p['id'],release);ck(vertex not in edges,'INVALID_DEPENDENCY_GRAPH','Duplicate release partition');edges[vertex]=[] for dep in part['depends_on']: ref(dep['work_package_ref'],'work_packages');ref(dep['release_ref'],'releases') ck(releases[dep['release_ref']]<=releases[release],'INVALID_DEPENDENCY_GRAPH','Future release prerequisite');edges[vertex].append((dep['work_package_ref'],dep['release_ref'])) for req in part['requirement_refs']: ref(req,'requirements');flat.append(req);partition_owners.setdefault(req,[]).append(vertex) ck(records[req]['release_ref']==release,'INVALID_COVERAGE','Requirement partition release mismatch') ck(sorted(flat)==sorted(p['requirement_refs']),'INVALID_COVERAGE','WP union mismatch') for req in p['requirement_refs']:owners.setdefault(req,[]).append(p['id']) dag(edges,'work_packages');checks+=1 traces={(t['from_id'],t['relationship'],t['to_id']) for t in catalogs['traceability']} for req in catalogs['requirements']: if req['status']=='retired':continue rid=req['id'];ck(len(owners.get(rid,[]))==1 and len(partition_owners.get(rid,[]))==1,'INVALID_COVERAGE','Exactly one owner/partition '+rid) if req['priority']=='MUST':ck(bool(req['acceptance_refs']) and bool(req['capability_refs']),'INVALID_COVERAGE','MUST acceptance/capability '+rid) for aid in req['acceptance_refs']: ck(rid in records[aid]['requirement_refs'],'INVALID_COVERAGE','Reciprocal acceptance '+aid);ck((aid,'verifies',rid) in traces,'INVALID_COVERAGE','Verifies edge '+rid) for cap in req['capability_refs']:ck((rid,'realises',cap) in traces,'INVALID_COVERAGE','Realises edge '+rid) ck((owners[rid][0],'implements',rid) in traces,'INVALID_COVERAGE','Owner trace '+rid) for a in catalogs['acceptance_tests']: if a['status']=='passed':ck(a['execution_kind']!='natural_language' and bool(a['evidence_refs']),'INVALID_COVERAGE','Passing test lacks evidence '+a['id']) if catalogs.get('workflows'): ck({'agentic_tools_v1','typed_workflow_bindings_v1'}<=set(pkg['required_features']),'UNSUPPORTED_PROFILE','Workflow features not declared') for wf in catalogs.get('workflows',[]): steps={s['id']:s for s in wf['steps']};ck(len(steps)==len(wf['steps']),'INVALID_DEPENDENCY_GRAPH','Duplicate step ID');dag({k:s['depends_on'] for k,s in steps.items()},wf['id']);checks+=1 def ancestors(k): out=set(steps[k]['depends_on']) for d in steps[k]['depends_on']:out|=ancestors(d) return out for sid,s in steps.items(): ref(s['agent_ref'],'agents');ref(s['tool_ref'],'tools');agent=records[s['agent_ref']];tool=records[s['tool_ref']] ck(s['tool_ref'] in agent['tool_refs'],'INVALID_BINDING','Agent tool not allowed') ck(releases[wf['release_ref']]>=max(releases[agent['release_ref']],releases[tool['release_ref']]),'INVALID_BINDING','Tool release') inp=tool['input_schema'];bindings=s['input_bindings'];ck(set(inp.get('required',[]))<=set(bindings)<=set(inp.get('properties',{})),'INVALID_BINDING','Missing or unknown input binding') for key,b in bindings.items(): m=re.fullmatch(r'\$\.(context|trigger)\.([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)|\$\.steps\.([A-Za-z_][A-Za-z0-9_]*)\.output\.([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)',b) ck(m is not None,'INVALID_BINDING','Unsupported binding '+b) if m.group(1):sch=wf[m.group(1)+'_schema'];segments=m.group(2).split('.') else: pred=m.group(3);ck(pred in ancestors(sid),'INVALID_BINDING','Non-prerequisite output binding');sch=records[steps[pred]['tool_ref']]['output_schema'];segments=m.group(4).split('.') for seg in segments:ck(seg in sch.get('properties',{}),'INVALID_BINDING','Missing schema path '+b);sch=sch['properties'][seg] # Structural path checks only. Runtime validates resolved values, including refinements/oneOf. if tool['effect_class']=='external_write':ck(s['failure_path']=='outcome_inquiry','INVALID_BINDING','External write must inquire ambiguous outcome') asset_paths=set() for a in catalogs.get('assets',[]): alias=unicodedata.normalize('NFC',path(a['relative_path'])).casefold();ck(alias not in asset_paths,'INVALID_ASSET','Colliding asset output path');asset_paths.add(alias) try:b=base64.b64decode(a['content'],validate=True) if a['encoding']=='base64' else a['content'].encode() except Exception:fail('INVALID_ASSET','Invalid asset encoding') path(a['relative_path']);ck(len(b)==a['byte_length'] and sha(b)==a['sha256'],'INVALID_ASSET','Asset digest/length '+a['id']) for n,r in index.items(): if r['role']=='projection' and n.endswith('.json'): ck('projection_digest_v1' in pkg['required_features'],'UNSUPPORTED_PROFILE','Projection algorithm not declared');p=load(data/n) ck(len(p['source_paths'])==len(set(p['source_paths'])),'STALE_PROJECTION','Duplicate projection source') ck(bool(p['source_paths']) and all(src in index for src in p['source_paths']),'STALE_PROJECTION','Projection sources missing') ck(p['source_snapshot_sha256']==snapshot(data,p['source_paths']),'STALE_PROJECTION','Projection snapshot') try:b=base64.b64decode(p['content'],validate=True) if p['encoding']=='base64' else p['content'].encode() except Exception:fail('STALE_PROJECTION','Invalid projection encoding') ck(sha(b)==p['sha256'],'STALE_PROJECTION','Projection bytes') if 'autonomous_build_v1' in pkg['required_features']: from build_validate import check check(root,standard_root=std) return {'tool':'openagentworks-reference-validator','tool_version':VERSION,'package_id':pkg['package_id'],'manifest_sha256':sha(files['manifest-sha256.txt'].read_bytes()),'valid':True,'checks':checks,'diagnostics':[],'claims':['bag_integrity_validated','standard_catalog_schema_validated','references_resolved','dependency_graphs_validated'],'nonclaims':['application_tests_passed','native_factory_import','external_write_executed','native_contract_adapter_conformance']} def declared_profile(pkg,data,index,files,checks,unknown,native,root,std): """A custom profile: what can be checked without knowing the product, and a report of the rest.""" def ck(ok,code,msg): nonlocal checks;checks+=1;require(ok,code,msg) kinds=set();records=0 for n in pkg['canonical_catalogs']: # Every catalog was already checked against the schema the package registers for it. ck(index[n]['validation']=='json' and index[n]['schema_path'] is not None,'INVALID_SCHEMA','Custom catalog without a registered schema '+n) cat=load(data/n);ck(isinstance(cat,dict) and isinstance(cat.get('kind'),str) and isinstance(cat.get('records'),list),'INVALID_SCHEMA','Catalog needs kind and records '+n) ck(cat['kind'] not in kinds,'INVALID_SCHEMA','Duplicate catalog kind '+cat['kind']);kinds.add(cat['kind']) ck(cat.get('product_version')==pkg['product_version'],'INVALID_SCHEMA','Product version drift '+n) ids=[r.get('id') for r in cat['records'] if isinstance(r,dict)];ck(len(ids)==len(cat['records']) and all(isinstance(i,str) and i for i in ids),'INVALID_SCHEMA','Record without an id in '+n) ck(len(ids)==len(set(ids)),'UNRESOLVED_REFERENCE','Duplicate ID in '+n);records+=len(ids) ck(bool(kinds),'INVALID_COVERAGE','A package needs at least one catalog') if 'autonomous_build_v1' in pkg['required_features']: from build_validate import check check(root,standard_root=std) evidence=[{'path':n,'sha256':sha((data/n).read_bytes())} for n,r in sorted(index.items()) if r['role']=='validation_evidence'] return {'tool':'openagentworks-reference-validator','tool_version':VERSION,'package_id':pkg['package_id'],'manifest_sha256':sha(files['manifest-sha256.txt'].read_bytes()),'valid':True,'checks':checks,'diagnostics':[], 'scope':'declared_profile', 'claims':['bag_integrity_validated','package_manifest_validated','registered_schemas_validated','catalog_identity_validated']+(['build_contract_validated'] if 'autonomous_build_v1' in pkg['required_features'] else []), 'nonclaims':['application_tests_passed','native_factory_import','standard_catalog_semantics_validated','profile_features_interpreted','business_rules_validated','native_formats_validated'], 'profile':{'catalog_kinds':sorted(kinds),'records':records,'features_not_interpreted':unknown,'business_validator_not_run':pkg['business_validator_id'],'native_resources_not_checked':sorted(native),'producer_validation_evidence':evidence}} if __name__=='__main__': import argparse a=argparse.ArgumentParser();a.add_argument('bag');a.add_argument('--report');args=a.parse_args() try:r=validate(args.bag);code=0 except Exception as e:r={'tool':'openagentworks-reference-validator','tool_version':VERSION,'package_id':None,'manifest_sha256':None,'valid':False,'checks':0,'diagnostics':[{'code':getattr(e,'code','INVALID_SCHEMA'),'message':str(e)}],'claims':[],'nonclaims':['application_tests_passed','native_factory_import']};code=2 if args.report:outside_bag(args.report,args.bag);Path(args.report).write_text(json.dumps(r,indent=2)+'\n') print(json.dumps(r));sys.exit(code)