Files
vibemake-pcb-studio/codex_pcb/delivery.py
T
2026-11-11 19:27:49 +08:00

70 lines
3.6 KiB
Python

import json
import shutil
import zipfile
from pathlib import Path
from .storage import workspace, task_dir, inside, digest, write
from .eda import verify_native
from .step_colors import validate_step_colors
REQUIRED = {'project','schematic','layout','step','render'}
def inspect(path, kind):
data = path.read_bytes()
if len(data)<100:
raise ValueError(f'{kind}: file is empty or too small')
ext = path.suffix.lower()
if kind == 'step':
if ext not in {'.stp','.step'} or not data.lstrip().startswith(b'ISO-10303-21;') or b'END-ISO-10303-21;' not in data or b'CARTESIAN_POINT' not in data or b'SHAPE_REPRESENTATION' not in data:
raise ValueError('STEP must be an extracted, real ISO10303 model')
validate_step_colors(data)
elif kind == 'project':
if ext not in {'.epro','.epro2','.zip'}:
raise ValueError('Editable native EasyEDA project required')
if zipfile.is_zipfile(path):
with zipfile.ZipFile(path) as z:
if not z.namelist() or z.testzip():
raise ValueError('Invalid native project archive')
elif b'DOCHEAD' not in data and not data.lstrip().startswith(b'{'):
raise ValueError('Unrecognized native project')
elif kind in {'render','schematic','layout'}:
png = data.startswith(b'\x89PNG\r\n\x1a\n')
jpg = data.startswith(b'\xff\xd8\xff')
pdf = data.startswith(b'%PDF')
svg = b'<svg' in data[:2000]
if not (png or jpg or (kind != 'render' and (pdf or svg))):
raise ValueError(f'{kind}: native preview or real render required')
return {'bytes':len(data),'sha256':digest(data)}
async def deliver(t, args):
files=args['files']
if not REQUIRED <= {f['kind'] for f in files}:
raise ValueError('Missing required deliverables: '+', '.join(sorted(REQUIRED-{f['kind'] for f in files})))
checked=[]
for f in files:
path=inside(workspace(t),f['path'])
if not path.is_file() or path.is_symlink():
raise ValueError('Missing artifact: '+f['path'])
checked.append({**f,**inspect(path,f['kind']),'source':path})
verification=await verify_native(t,args['schematic_id'],args['pcb_id'])
folder=task_dir(t['id'])/'delivery'
folder.mkdir(exist_ok=True)
entries=[]
for index,f in enumerate(checked):
name=f'{index+1:02d}-{f["source"].name}'
target=folder/name
shutil.copyfile(f['source'],target)
# Recheck after copy: agent may still be doing work in the same filesystem.
if digest(target.read_bytes()) != f['sha256']:
raise ValueError('Artifact changed during delivery')
entries.append({'name':name,'kind':f['kind'],'label':f.get('label') or f['source'].name,'bytes':f['bytes'],'sha256':f['sha256']})
manifest={'task_id':t['id'],'thread_id':t['thread_id'],'approval':t['approval'],'source_hash':t['frozen_source'],'verification':verification,'files':entries,'notes':args['notes']}
write(folder/'manifest.json',manifest)
shutil.copyfile(task_dir(t['id'])/'native-verification.json',folder/'native-verification.json')
bundle=folder/'delivery.zip'
with zipfile.ZipFile(bundle,'w',zipfile.ZIP_DEFLATED) as z:
for p in sorted(folder.iterdir()):
if p.is_file() and p != bundle:
z.write(p,p.name)
entries.append({'name':bundle.name,'kind':'bundle','label':'完整交付包','bytes':bundle.stat().st_size,'sha256':digest(bundle.read_bytes())})
return {'files':entries,'verification':verification,'notes':args['notes'],'schematic_id':args['schematic_id'],'pcb_id':args['pcb_id']}