Files
vibemake-pcb-studio/backend/easyeda_backend/tools/check_request.py
T
2026-11-10 19:04:27 +08:00

107 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Validate a project intake and optionally its design-selection gate. No EDA writes."""
import argparse,hashlib,json,math,sys
from pathlib import Path
PACK=Path(__file__).resolve().parents[1]
def digest(data):
return hashlib.sha256(json.dumps(data,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False).encode('utf-8')).hexdigest()
def read(path):
return json.loads(Path(path).read_text(encoding='utf-8'),parse_constant=lambda v: (_ for _ in ()).throw(ValueError('Non-finite JSON number: '+v)))
def check(root,plan_path=None):
from jsonschema import Draft202012Validator,FormatChecker
root=Path(root).resolve();errors=[];pending=[]
def err(code,path,message): errors.append({'code':code,'path':path,'message':message})
def validate(data,name):
schema=read(PACK/'schemas'/f'{name}.schema.json')
issues=list(Draft202012Validator(schema,format_checker=FormatChecker()).iter_errors(data))
for e in issues:err('SCHEMA',name+'/'+ '/'.join(map(str,e.absolute_path)),e.message)
return not issues
request=read(root/'inputs/request.json');assets=read(root/'inputs/assets.json')
if not validate(request,'request') or not validate(assets,'assets'):
return {'status':'needs_input','errors':errors,'pending':pending,'design_allowed':False}
def unique(items,path):
ids=[x['id'] for x in items]
if len(ids)!=len(set(ids)):err('DUPLICATE_ID',path,'IDs must be unique within the collection')
for key in ['power_inputs','loads','interfaces']:unique(request[key],key)
unique(assets['assets'],'assets');asset_ids={a['id'] for a in assets['assets']}
for a in assets['assets']:
relative=Path(a['path']);target=(root/relative).resolve()
if relative.is_absolute() or not target.is_relative_to(root):err('ASSET_PATH',a['id'],'Asset must resolve inside the project root')
elif not target.is_file():err('ASSET_MISSING',a['id'],a['path'])
for power in request['power_inputs']:
v=power['voltage']; n=v['nominal_v'];lo=v['min_v'];hi=v['max_v']
if (lo is not None and lo>n) or (hi is not None and hi<n):err('VOLTAGE_RANGE',power['id'],'Require min <= nominal <= max')
if lo is None or hi is None:pending.append(f"supply_range:{power['id']}")
if power['type']=='ac':pending.append(f"out_of_scope_ac:{power['id']}")
for load in request['loads']:
for field in ['supply_v','continuous_a_each','peak_a_each']:
if load[field] is None:pending.append(f"{field}:{load['id']}")
if load['continuous_a_each'] is not None and load['peak_a_each'] is not None and load['peak_a_each']<load['continuous_a_each']:err('LOAD_CURRENT',load['id'],'Peak must not be below continuous current')
for aid in load['asset_ids']:
if aid not in asset_ids:err('ASSET_REFERENCE',load['id'],aid)
for item in request['interfaces']:
if item['protocol']=='unknown':pending.append(f"protocol:{item['id']}")
if item['compatibility']=='unknown' or (item['compatibility']=='existing_harness' and not item.get('pinout')):pending.append(f"pinout:{item['id']}")
if request['board']['shape']=='custom':
aid=request['board'].get('outline_asset_id')
if not aid or aid not in asset_ids:err('OUTLINE_REQUIRED','board','Custom outline needs an existing mechanical asset')
elif next(a for a in assets['assets'] if a['id']==aid)['kind']!='mechanical':err('OUTLINE_KIND','board','Outline asset kind must be mechanical')
mounting=request.get('mounting')
if mounting is None or mounting['requirement']=='unknown':
pending.append('mounting:requirements')
if mounting is not None:
holes=mounting['holes'];unique(holes,'mounting/holes')
for aid in mounting['asset_ids']:
if aid not in asset_ids:err('ASSET_REFERENCE','mounting',aid)
elif next(a for a in assets['assets'] if a['id']==aid)['kind']!='mechanical':err('MOUNTING_ASSET_KIND','mounting', 'Use a mechanical asset for a mounting sketch')
if mounting['requirement']=='none':
if holes or mounting['hole_count']!=0 or mounting['spacing_constraints']:err('MOUNTING_CONFLICT','mounting','No-hole request must have zero count, no holes and no spacing constraints')
if mounting['requirement']=='required':
if mounting['hole_count'] is None or not holes:pending.append('mounting:hole_geometry')
elif mounting['hole_count']<1 or mounting['hole_count']!=len(holes):err('MOUNTING_COUNT','mounting/hole_count','Hole count must match a nonempty hole list')
complete=[]
for hole in holes:
if any(hole[k] is None for k in ['diameter_mm','x_mm','y_mm']) or hole['plating']=='unknown':pending.append('mounting:'+hole['id'])
if all(hole[k] is not None for k in ['diameter_mm','x_mm','y_mm']):
complete.append(hole);r=hole['diameter_mm']/2;x=hole['x_mm'];y=hole['y_mm']
if x-r<0 or y-r<0 or x+r>request['board']['width_mm'] or y+r>request['board']['height_mm']:err('MOUNTING_BOUNDS',hole['id'],'Hole extends beyond the supplied board bounding rectangle')
for index,a in enumerate(complete):
for b in complete[index+1:]:
if math.hypot(a['x_mm']-b['x_mm'],a['y_mm']-b['y_mm']) <= (a['diameter_mm']+b['diameter_mm'])/2:err('MOUNTING_OVERLAP',a['id']+','+b['id'],'Hole circles overlap or touch')
by_id={h['id']:h for h in holes}
for c in mounting['spacing_constraints']:
a=by_id.get(c['from_hole']);b=by_id.get(c['to_hole'])
if a is None or b is None or c['from_hole']==c['to_hole']:err('MOUNTING_SPACING_REFERENCE','mounting/spacing_constraints','Spacing requires two distinct existing holes');continue
axes=['x_mm','y_mm'] if c['axis']=='distance' else [c['axis']+'_mm']
if any(h[k] is None for h in [a,b] for k in axes):continue
actual=math.hypot(a['x_mm']-b['x_mm'],a['y_mm']-b['y_mm']) if c['axis']=='distance' else abs(a[axes[0]]-b[axes[0]])
if not math.isclose(actual,c['center_spacing_mm'],rel_tol=0,abs_tol=1e-6):err('MOUNTING_SPACING','mounting/spacing_constraints','Specified center spacing conflicts with coordinates')
sha=digest(request)
result={'status':'needs_input' if errors else 'intake_valid','request_sha256':sha,'errors':errors,'pending':pending,'design_allowed':False}
if not plan_path:return result
plan=read(plan_path)
if not validate(plan,'plan'):result['status']='needs_input';return result
if plan['request_sha256']!=sha:err('STALE_PLAN','plan/request_sha256','The request has changed or digest is incorrect')
unique(plan['options'],'options');options={x['id'] for x in plan['options']}
if plan['recommended_option_id'] not in options:err('OPTION_REFERENCE','recommended_option_id','Unknown option')
resolved={x['topic'] for x in plan['engineering']['resolved_requirements']}
unresolved=[x for x in pending if x not in resolved]
# AC is out of scope; mounting unknowns must be resolved in the request, not bypassed in plan prose.
unresolved+= [x for x in pending if (x.startswith('out_of_scope_ac:') or x.startswith('mounting:')) and x not in unresolved]
selection=plan['selection']
if selection:
if selection['option_id'] not in options:err('OPTION_REFERENCE','selection/option_id','Unknown option')
if request['selection_policy']=='propose' and selection['basis']!='user_choice':err('USER_CHOICE_REQUIRED','selection/basis','A real user choice is required')
result['pending']=unresolved+plan['engineering']['blockers']
result['status']='needs_input' if errors else ('engineering_blocked' if result['pending'] else ('needs_selection' if selection is None else 'ready_for_design'))
result['design_allowed']=result['status']=='ready_for_design'
result['approval_authentication']='Not provided: the agent must verify selection evidence against the actual user conversation.'
return result
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('project_root');parser.add_argument('--plan');args=parser.parse_args()
try:
result=check(args.project_root,args.plan); print(json.dumps(result,ensure_ascii=False,indent=2))
sys.exit(0 if (result['design_allowed'] if args.plan else not result['errors']) else 2)
except Exception as exc:
print(json.dumps({'status':'error','error':str(exc)},ensure_ascii=False),file=sys.stderr);sys.exit(1)