diff --git a/codex_pcb/app.py b/codex_pcb/app.py index f8d181c..d4fc25e 100644 --- a/codex_pcb/app.py +++ b/codex_pcb/app.py @@ -12,6 +12,10 @@ from .storage import SOURCE, ROOT, TASKS, MODEL, EFFORT, task_dir, workspace, lo from .rpc import AppServer from .eda import execute from .delivery import deliver +from .eda import verify_native +from .exports import prepare_delivery +from .checks import VALIDATION_POLICY +from .native_policy import DESIGN_POLICY, POLICY_TEXT, WORKSPACE_RULES, refresh_workspace_rules CACHE, JOBS, CLIENTS = {}, {}, {} @@ -23,9 +27,11 @@ def tool(name, description, properties, required=None): STR={'type':'string'} TOOLS=[ + tool('pcb_check','Run the exact delivery electrical gate early and after edits. Accepts schematic container OR page ID and PCB document ID. All schematic pages checked. Explicit warnings are reported and accepted; errors block.',{'schematic_id':STR,'pcb_id':STR}), + tool('pcb_prepare_delivery','After pcb_check accepts, export native project/drawings/STEP/OBJ, render OBJ with installed Blender, and return a file list for pcb_deliver. Built-in chunk transfer, schematic SVG/PDF conversion, model ZIP extraction. No STEP cosmetic rebuilding; warnings are retained. Inspect outputs once before delivery.',{'schematic_id':STR,'pcb_id':STR}), tool('pcb_proposal','Publish or replace the proposal for website review; not production authorization.',{'title':STR,'markdown':STR}), tool('pcb_read_reference','Read official EDA API documentation. Relative path under api-reference, e.g. references/_index.md. Also available via shell during production.',{'path':STR,'offset':{'type':'integer','minimum':0},'limit':{'type':'integer','minimum':100,'maximum':40000}},['path']), - tool('pcb_eda','Execute YOUR JavaScript async function body in this task dedicated EasyEDA session. Only after website approval. Global eda and async pcb_export(file,relative_name) are available. Use code OR code_file (workspace-relative JS path). Full outputs preserved; uncertain writes must be inspected.',{'label':STR,'code':STR,'code_file':STR},['label']), + tool('pcb_eda','Operate native EasyEDA schematic/PCB objects in this task session after approval. External routing exchange (DSN/SES/auto-route JSON) is disabled. Global eda and pcb_export(file,relative_name) are available. Use code OR code_file. Full outputs preserved; uncertain writes must be inspected.',{'label':STR,'code':STR,'code_file':STR},['label']), tool('pcb_deliver','Submit real exported files for independent validation. Rejected submission returns evidence so you can repair in the SAME session.',{'schematic_id':STR,'pcb_id':STR,'notes':STR,'files':{'type':'array','items':object_schema({'path':STR,'kind':{'type':'string','enum':['project','schematic','layout','step','render','bom','report','other']},'label':STR}), 'minItems':5}}), tool('pcb_blocked','Record a concrete unrecoverable blocker and preserve draft. Do not use for ordinary tool errors; investigate and repair first.',{'reason':STR,'evidence':STR}), ] @@ -63,7 +69,11 @@ async def handle(t, method, p): frozen(t) if t['state'] == 'cancelled': raise RuntimeError('Task cancelled') - if name=='pcb_proposal': + if name=='pcb_check': + result=await verify_native(t,a['schematic_id'],a['pcb_id'],require_pass=False) + elif name=='pcb_prepare_delivery': + result=await prepare_delivery(t,a['schematic_id'],a['pcb_id']) + elif name=='pcb_proposal': if t.get('approval'): raise ValueError('Already approved; preserve accepted design and finish production') markdown=a['markdown'].strip() @@ -84,10 +94,25 @@ async def handle(t, method, p): if bool(a.get('code'))==bool(a.get('code_file')): raise ValueError('Specify exactly one of code or code_file') code=a.get('code') or inside(workspace(t),a['code_file']).read_text() - result=await execute(t,code,a['label']) + # Backward-compatible access for resumed threads whose tool catalogue is fixed. + try: request=json.loads(code) + except ValueError: request=None + if isinstance(request,dict) and 'pcb_backend_tool' in request: + if set(request)!={'pcb_backend_tool','schematic_id','pcb_id'} or not all(isinstance(v,str) for v in request.values()): + raise ValueError('Invalid common-tool request') + operation=request['pcb_backend_tool'] + if operation=='prepare_delivery': + result=await prepare_delivery(t,request['schematic_id'],request['pcb_id']) + elif operation=='check': + result=await verify_native(t,request['schematic_id'],request['pcb_id'],require_pass=False) + else:raise ValueError('Unknown common backend tool') + else: + result=await execute(t,code,a['label']) raw=json.dumps(result,ensure_ascii=False) if len(raw)>24000: - result={'output_path':str(workspace(t)/'evidence'/f'eda-{t["eda_calls"]:05d}.json'),'preview':raw[:18000],'truncated':True,'instruction':'Read the complete file using shell; do not guess omitted fields'} + output=workspace(t)/'evidence'/('tool-result-'+uuid.uuid4().hex+'.json') + write(output,result) + result={'output_path':str(output),'preview':raw[:18000],'truncated':True,'instruction':'Read the complete file using shell; do not guess omitted fields'} elif name=='pcb_deliver': if not t.get('approval') or t['state']!='running': raise ValueError('Production approval required') @@ -113,6 +138,9 @@ async def handle(t, method, p): async def run_turn(t, prompt, production): frozen(t) directory=workspace(t) + # Reassert on every turn, including resumed histories with obsolete routing advice. + refresh_workspace_rules(directory) + prompt=POLICY_TEXT+'\n'+prompt async with AppServer(directory, production, lambda m,p:handle(t,m,p)) as client: CLIENTS[t['id']]=client common={'model':MODEL,'modelProvider':'openai','cwd':str(directory),'approvalPolicy':'never','sandbox':'workspace-write' if production else 'read-only','developerInstructions':(SOURCE/'instructions.md').read_text(),'serviceTier':'default'} @@ -248,7 +276,7 @@ class Approval(BaseModel): @app.get('/api/health') async def health(): - return {'ok':True,'engine':'persistent-codex','model':MODEL,'effort':EFFORT,'source_hash':fingerprint(),'legacy_pipeline':False} + return {'ok':True,'engine':'persistent-codex','model':MODEL,'effort':EFFORT,'source_hash':fingerprint(),'legacy_pipeline':False,'design_policy':DESIGN_POLICY,'validation_policy':VALIDATION_POLICY,'delivery_toolkit':1} @app.get('/api/sessions') async def list_sessions(): @@ -257,12 +285,12 @@ async def list_sessions(): @app.post('/api/sessions',status_code=201) async def create(req:Request): tid='pcb-'+uuid.uuid4().hex[:24] - t={'id':tid,'request':req.text,'created_at':time.time(),'state':'planning','cursor':0,'model':MODEL,'effort':EFFORT,'busy':False} + t={'id':tid,'request':req.text,'created_at':time.time(),'state':'planning','cursor':0,'model':MODEL,'effort':EFFORT,'busy':False,'design_policy':DESIGN_POLICY} directory=workspace(t);directory.mkdir(parents=True) for name in ('artifacts','evidence','scripts','tmp'): (directory/name).mkdir() (directory/'api-reference').symlink_to(ROOT/'resources',target_is_directory=True) - (directory/'AGENTS.md').write_text('Use only this workspace for generated PCB scripts/files. Do not read or use legacy PCB pipelines. Official API references are under api-reference. Do not edit service code or unrelated projects. Do not spawn subagents.\n') + (directory/'AGENTS.md').write_text(WORKSPACE_RULES) CACHE[tid]=t;save(t) event(t,'message',{'role':'user','text':req.text}) schedule(t,'User requirement:\n'+req.text+'\n\nFirst prepare a reviewable proposal and publish it with pcb_proposal. Do not produce the board yet.',False) @@ -298,13 +326,14 @@ async def approve(tid:str,req:Approval): raise HTTPException(409,'Approve the latest completed proposal revision') t['approval']={'revision':req.revision,'hash':req.hash,'at':time.time()} t['frozen_source']=fingerprint() + t['design_policy']=DESIGN_POLICY event(t,'proposal.approved',t['approval']) prompt=f'''The user explicitly clicked APPROVE AND START for proposal revision {req.revision}, SHA256 {req.hash}. This server-owned approval authorizes production of the accepted proposal in this same persistent session. Earlier requests to wait applied only to review. Workspace: {workspace(t)} Official API documentation: {workspace(t)}/api-reference/references/_index.md -External router launcher: python3 {SOURCE}/freerouting.py --input --output --jar {ROOT}/resources/freerouting.jar --timeout 900 -- -mp 30 -mt 1 -Use this launcher for Freerouting, including --help. It validates paths, skips the startup countdown and runs on a private virtual display. Choose routing options and timeout according to the board; do not invoke the JAR directly. Blender: /snap/bin/blender. +{POLICY_TEXT} +Blender: /snap/bin/blender (render exported native 3D geometry only). Now use native Codex tools and pcb_eda to implement, inspect, fix, route, verify and export the real board. You write the design scripts yourself. No fixed backend design pipeline exists. Keep working until pcb_deliver accepts native project, schematic, layout, assembled STEP and real 3D render. Do not edit backend code or use legacy PCB flows. Backend source is frozen for this run. Accepted proposal:\n{p['markdown']}''' schedule(t,prompt,True) diff --git a/codex_pcb/checks.py b/codex_pcb/checks.py new file mode 100644 index 0000000..e0e8a2a --- /dev/null +++ b/codex_pcb/checks.py @@ -0,0 +1,46 @@ +"""Severity-aware native diagnostics: errors block; explicit warnings are retained.""" +import json + +VALIDATION_POLICY = 'native-errors-block-warnings-record-v1' + + +def classify_diagnostics(details, native_passed): + errors, warnings = [], [] + if not isinstance(details, list) or not isinstance(native_passed, bool): + return {'passed': False, 'errors': [{'reason': 'Invalid native check response', 'details': details}], 'warnings': []} + + def visit(item, inherited=None): + if not isinstance(item, dict): + errors.append({'reason': 'Unclassified native diagnostic', 'details': item});return + severity = str(item.get('severity', item.get('type', inherited or ''))).lower() + name = str(item.get('name', item.get('errorType', ''))).lower() + if severity in {'error','fatal'} or 'error' in name or '错误' in name: + severity = 'error' + elif severity in {'warn','warning'} or name in {'warning','warnings','警告'}: + severity = 'warning' + children = item.get('list') + if isinstance(children, list) and children: + for child in children:visit(child,severity) + elif severity == 'warning': + warnings.append(item) + else: + # Unknown categories are never silently converted to warnings. + errors.append(item) + + for item in details:visit(item) + if not native_passed and not details: + errors.append({'reason': 'Native check returned false without diagnostic evidence'}) + return {'passed': not errors, 'errors': errors, 'warnings': warnings, 'nativePassed':native_passed} + + +def evaluate_verification(result): + if not isinstance(result, dict):raise ValueError('Missing native verification result') + sch=classify_diagnostics(result.get('schErrors'), result.get('schPassed')) + pcb=classify_diagnostics(result.get('pcbErrors'), result.get('pcbPassed')) + result.update(validation_policy=VALIDATION_POLICY, accepted=sch['passed'] and pcb['passed'], + warnings={'schematic':sch['warnings'],'pcb':pcb['warnings']}, + blockingErrors={'schematic':sch['errors'],'pcb':pcb['errors']}) + if result.get('schematicParts',0)<2 or result.get('pcbParts',0)<2: + result['accepted']=False + result['blockingErrors']['design']=[{'reason':'Native design is empty or incomplete'}] + return result diff --git a/codex_pcb/delivery.py b/codex_pcb/delivery.py index d566d01..76ccc6f 100644 --- a/codex_pcb/delivery.py +++ b/codex_pcb/delivery.py @@ -5,6 +5,8 @@ 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 +from .native_policy import DESIGN_POLICY +from .checks import VALIDATION_POLICY REQUIRED = {'project','schematic','layout','step','render'} @@ -13,10 +15,14 @@ def inspect(path, kind): if len(data)<100: raise ValueError(f'{kind}: file is empty or too small') ext = path.suffix.lower() + warnings=[] 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) + try: + validate_step_colors(data) + except ValueError as exc: + warnings.append({'type':'warning','code':'STEP_APPEARANCE','message':str(exc)}) elif kind == 'project': if ext not in {'.epro','.epro2','.zip'}: raise ValueError('Editable native EasyEDA project required') @@ -33,10 +39,12 @@ def inspect(path, kind): svg = b' { - if (!file || typeof file.arrayBuffer !== 'function') throw new Error('Native export returned no File/Blob'); - const base64 = await new Promise((resolve,reject)=>{const r=new FileReader();r.onload=()=>resolve(String(r.result).split(',')[1]);r.onerror=reject;r.readAsDataURL(file);}); - __files.push({name,base64});return {name,bytes:file.size}; + transfer_key='pcb_export_'+uuid.uuid4().hex + wrapper = 'const __transferKey='+json.dumps(transfer_key)+';\n'+r'''const __files=[]; +globalThis.__pcbBackendTransfers ??= Object.create(null); +globalThis.__pcbBackendTransfers[__transferKey]=[]; +const pcb_export=async(file,name)=>{ + if(/\.(dsn|ses)$/i.test(name))throw Error('easyeda-native-v1: DSN/SES routing exchange exports are disabled'); + if(!file || typeof file.arrayBuffer!=='function')throw Error('Native export returned no File/Blob'); + const index=__files.length; + globalThis.__pcbBackendTransfers[__transferKey].push(file); + __files.push({name,bytes:file.size,index});return {name,bytes:file.size}; }; -const __result = await (async()=>{\n''' + code + '\n})(); return {result:__result,files:__files};' +const __result=await (async()=>{ +''' + guarded_script(HELPERS_JS+'\n'+code) + '\n})(); return {result:__result,files:__files};' try: value = await cli(['invoke','--session',t['eda_session'],'--ext-uuid','eda','--code-file','-','--timeout','180000'],wrapper) files = [] for item in value.get('files',[]): - dst = inside(workspace(t)/'artifacts',item['name']) - data = base64.b64decode(item['base64'],validate=True) + validate_export_name(item['name']) + dst=inside(workspace(t)/'artifacts',item['name']) dst.parent.mkdir(parents=True,exist_ok=True) - dst.write_bytes(data) - files.append({'path':str(dst),'bytes':len(data),'sha256':digest(data)}) + partial=dst.with_name(dst.name+'.'+transfer_key+'.partial') + try: + with partial.open('wb') as output: + for offset in range(0,item['bytes'],1024*1024): + chunk_code=f'''const f=globalThis.__pcbBackendTransfers?.[{json.dumps(transfer_key)}]?.[{int(item['index'])}]; +if(!f || f.size!=={int(item['bytes'])})throw Error('Native export handle expired; retry export without editing the board'); +const blob=f.slice({offset},{offset+1024*1024}); +const base64=await new Promise((resolve,reject)=>{{const r=new FileReader();r.onload=()=>resolve(String(r.result).split(',')[1]);r.onerror=reject;r.readAsDataURL(blob);}}); +return {{base64}};''' + chunk=await cli(['invoke','--session',t['eda_session'],'--ext-uuid','eda','--code-file','-','--timeout','30000'],chunk_code,timeout=40) + data=base64.b64decode(chunk['base64'],validate=True) + if len(data)!=min(1024*1024,item['bytes']-offset):raise ValueError('Truncated native export chunk') + output.write(data) + partial.replace(dst) + finally: + partial.unlink(missing_ok=True) + files.append({'path':str(dst),'bytes':dst.stat().st_size,'sha256':digest(dst.read_bytes())}) result = {'result':value.get('result'),'exports':files} write(prefix.with_suffix('.json'),result) event(t,'eda.completed',{'call':n,'label':label,'files':files}) @@ -91,33 +116,45 @@ const __result = await (async()=>{\n''' + code + '\n})(); return {result:__resul write(prefix.with_suffix('.json'),{'error':str(e),'mutation_outcome':'inspect before retry'}) event(t,'eda.error',{'call':n,'message':str(e)}) raise + finally: + try: + await cli(['invoke','--session',t['eda_session'],'--ext-uuid','eda','--code-file','-','--timeout','10000'], 'delete globalThis.__pcbBackendTransfers?.['+json.dumps(transfer_key)+'];return true;', timeout=15) + except Exception: + pass finally: fcntl.flock(fd,fcntl.LOCK_UN) fd.close() -async def verify_native(t, schematic_id, pcb_id): - # Native booleans must be true. Verbose arrays are retained only as diagnostics. - code = f'''const sch={json.dumps(schematic_id)}, pcb={json.dumps(pcb_id)}; -async function focus(id) {{ const tab=await eda.dmt_EditorControl.openDocument(id); if(!tab || !await eda.dmt_EditorControl.activateDocument(tab)) throw new Error('Cannot focus requested document '+id); }} -await focus(sch); await eda.sch_Document.save(); -const parts=await eda.sch_PrimitiveComponent.getAll('part'); -const schPassed=await eda.sch_Drc.check(true,false,false); -const schErrors=schPassed ? [] : await eda.sch_Drc.check(true,false,true); +async def verify_native(t, schematic_id, pcb_id, *, require_pass=True): + code = f'''const resolved=await pcb_resolve({json.dumps(schematic_id)}, {json.dumps(pcb_id)}); +const allParts=new Set(), allErrors=new Map(); let schPassed=true; +for(const page of resolved.schematic.page) {{ + await pcb_focus(page.uuid); + if(await eda.sch_Document.save()===false)throw Error('Schematic save failed'); + for(const part of await eda.sch_PrimitiveComponent.getAll('part'))allParts.add(page.uuid+':'+part.getState_PrimitiveId()); + const ok=await eda.sch_Drc.check(true,false,false); if(typeof ok!=='boolean')throw Error('Invalid schematic check response'); + schPassed=schPassed && ok; + const rows=await eda.sch_Drc.check(true,false,true); if(!Array.isArray(rows))throw Error('Missing schematic diagnostics'); + for(const row of rows)allErrors.set(JSON.stringify(row),row); +}} const schNet=await eda.sch_ManufactureData.getNetlistFile('verification'); -if(!schNet)throw new Error('Schematic netlist export missing'); +if(!schNet)throw Error('Schematic netlist export missing'); await pcb_export(schNet,'verification-schematic.net'); -await focus(pcb); await eda.pcb_Document.save(); +await pcb_focus(resolved.pcb.uuid); +if(await eda.pcb_Document.save()===false)throw Error('PCB save failed'); const components=await eda.pcb_PrimitiveComponent.getAll(); const pcbPassed=await eda.pcb_Drc.check(true,false,false); -const pcbErrors=pcbPassed ? [] : await eda.pcb_Drc.check(true,false,true); +const pcbErrors=await eda.pcb_Drc.check(true,false,true); const pcbNet=await eda.pcb_ManufactureData.getNetlistFile('verification'); -if(pcbNet)await pcb_export(pcbNet,'verification-pcb.net'); -return {{schPassed,pcbPassed,schematicParts:parts.length,pcbParts:components.length,schErrors,pcbErrors}};''' - evidence = await execute(t,code,'Independent native delivery verification') +if(!pcbNet)throw Error('PCB netlist export missing'); +await pcb_export(pcbNet,'verification-pcb.net'); +return {{schPassed,pcbPassed,schematicParts:allParts.size,pcbParts:components.length, + schErrors:[...allErrors.values()],pcbErrors,schematic_id:resolved.schematic.uuid, + schematic_pages:resolved.schematic.page.map(p=>p.uuid),pcb_id:resolved.pcb.uuid}};''' + evidence=await execute(t,code,'Native error/warning verification across all schematic pages and PCB') + result=evaluate_verification(evidence['result']) + evidence['result']=result write(task_dir(t['id'])/'native-verification.json',evidence) - r = evidence['result'] - if not isinstance(r,dict) or r.get('schPassed') is not True or r.get('pcbPassed') is not True: - raise ValueError('Native checks failed: '+json.dumps(r,ensure_ascii=False)[:16000]) - if r.get('schematicParts',0)<2 or r.get('pcbParts',0)<2: - raise ValueError('Native design is empty or incomplete') - return r + if require_pass and not result['accepted']: + raise ValueError('Native errors block delivery: '+json.dumps(result['blockingErrors'],ensure_ascii=False)[:16000]) + return result diff --git a/codex_pcb/exports.py b/codex_pcb/exports.py new file mode 100644 index 0000000..2fce25f --- /dev/null +++ b/codex_pcb/exports.py @@ -0,0 +1,120 @@ +"""Reusable native exports, SVG conversion, OBJ rendering. No electrical design algorithms.""" +import asyncio +import json +import os +from pathlib import Path +import shutil +import stat +import uuid +import zipfile +from .storage import SOURCE, workspace, inside, write, event +from .eda import execute, verify_native + + +def extract_archive(source, folder): + folder.mkdir(parents=True,exist_ok=True) + with zipfile.ZipFile(source) as archive: + if sum(i.file_size for i in archive.infolist())>1024*1024*1024: + raise ValueError('Native archive uncompressed size exceeds 1 GiB') + for item in archive.infolist(): + target=inside(folder,item.filename) + if stat.S_ISLNK(item.external_attr>>16):raise ValueError('Archive symlinks not permitted') + if item.is_dir():target.mkdir(parents=True,exist_ok=True);continue + target.parent.mkdir(parents=True,exist_ok=True) + with archive.open(item) as src,target.open('wb') as dst:shutil.copyfileobj(src,dst) + return sorted(p for p in folder.rglob('*') if p.is_file()) + + +def extract_step(source, folder): + if zipfile.is_zipfile(source): + paths=extract_archive(source,folder) + steps=[p for p in paths if p.suffix.lower() in {'.step','.stp'}] + if len(steps)!=1:raise ValueError('Expected one assembled STEP, found '+str(len(steps))) + return steps[0] + return source + + +def convert_schematic(source, folder): + # Native SVG retains labels that some native PDF exports omit. + import cairosvg + from pypdf import PdfWriter + paths=extract_archive(source,folder/'svg') if zipfile.is_zipfile(source) else [source] + svgs=[p for p in paths if p.suffix.lower()=='.svg' or b' {target}; confirmation disabled; timeout={args.timeout:g}s', flush=True) - process = subprocess.Popen(command, env=env, start_new_session=True) - try: - code = process.wait(timeout=args.timeout) - except subprocess.TimeoutExpired: - stop_process(process) - print('Freerouting timed out; no output published. Inspect the log before choosing another attempt.', file=sys.stderr) - return 124 - except KeyboardInterrupt: - stop_process(process) - return 130 - if code: - print(f'Freerouting exited with {code}; no output published', file=sys.stderr) - return code if code > 0 else 1 - if not pending.is_file() or pending.stat().st_size < 20 or not pending.read_bytes().lstrip().startswith(b'(session'): - raise ValueError('Freerouting did not produce a valid SES session file') - # Same filesystem, no overwrite race and no stale/partial SES success. - os.link(pending, target) - print(f'Saved {target} ({target.stat().st_size} bytes). Import and run native DRC; process success is not board validation.', flush=True) - return 0 - except (ValueError, OSError) as error: - print(f'Freerouting launcher: {error}', file=sys.stderr) - return 2 +def main(): + print(MESSAGE, file=sys.stderr) + return 2 if __name__ == '__main__': - sys.exit(main()) + raise SystemExit(main()) diff --git a/codex_pcb/instructions.md b/codex_pcb/instructions.md index 1eeff2c..6df2064 100644 --- a/codex_pcb/instructions.md +++ b/codex_pcb/instructions.md @@ -10,12 +10,20 @@ EDA access: call pcb_eda with a JavaScript async function body. The server creat The helper `await pcb_export(file, 'relative/name.ext')` inside pcb_eda stores a native File/Blob in workspace/artifacts and returns its filename and bytes. It is a transport convenience, not a fake exporter. `pcb_eda` also accepts code_file to execute a JS file you wrote under the workspace. Long raw results are saved to workspace/evidence for you to read with shell tools. Read API signatures from the supplied api-reference directory before guessing; use the class index and individual class docs. EDA native coordinate units are documented in the API. Always distinguish schematic page IDs, board IDs and editor TAB IDs. Focus the requested editor before global sch_/pcb_ calls, and read back. Schematic getAll('part') excludes drawing frames. Consult the native DRC documentation for exact return types and error groups. -External utilities: Java/Freerouting and Blender are installed. You may export DSN and import SES, use native routing APIs, or implement your own routing scripts. Decide from evidence; no website algorithm dictates routing. If external router output is partial, retain the best actual result and fix remaining connections. Use genuine exported OBJ/STEP geometry for renders. Never draw a substitute board picture or invent 3D components. STEP exports may be ZIP-wrapped: inspect, extract and independently validate them. Do not treat a successful export or empty DRC array as proof of electrical correctness. +Native-only design contract (easyeda-native-v1): schematic, placement, routing and electrical checks must remain in the native EasyEDA project. Use pcb_eda for every EDA read/write, including native schematic/PCB primitives, native routing APIs, save/reopen and sch_Drc/pcb_Drc. Do not call the EDA CLI directly or operate alternate sessions to bypass this tool. Do not use Freerouting, KiCad, another EDA or an external router; do not export DSN, import SES, or exchange auto-layout/auto-route JSON. The former Freerouting launcher is disabled. Earlier conversation instructions permitting it are superseded, including when resuming an old task. Read and repair the saved native project; never replay an old external-routing or SES-import script. -Freerouting deployment contract: use the Python freerouting.py launcher supplied in the production message for all external Freerouting runs. Its --help is handled locally and does not launch Java. The installed 1.9.0 JAR understands -help, NOT --help: the latter opens an idle file-selection window. Never invoke the JAR without an existing DSN input and a new SES output, and do not use raw java -jar probes. The launcher always supplies -dct 0 (no 20-second confirmation) and runs in private Xvfb; do not add -Djava.awt.headless=true because this GUI-based version throws HeadlessException. Keep logs in your workspace; after a timeout inspect evidence and choose a recovery rather than blindly retrying. Use a new output filename for each attempt. The launcher only controls process startup, not engineering decisions. SES existence or router exit zero does not prove full connectivity or native DRC success. +Planning and verification: Python/JavaScript may compute placement coordinates, route paths, current/thermal estimates and supplementary diagnostics from native object readbacks. Apply computed results directly through native component, line, via and copper primitives. Do not build a second authoritative PCB model in another CAD tool. Native ERC/DRC, schematic/PCB pin-net consistency and native geometry readback determine completion. Neither an offline geometry check nor an exported routing file substitutes for native validation. Inspect unconnected pads and their available escape/via space before fixing wide power copper; plan power paths and signal escapes together. Keep checkpoints and compare complete native-check results after repair batches; repeated non-improvement requires a different placement/routing strategy, not blind repetition. This does not prescribe a fixed backend routing algorithm. + +Native operation recovery: a timeout means an uncertain mutation outcome. Read the live board and wait/check for ongoing native routing before retrying; do not start competing routing operations or fall back to external exchange. Keep all approved nets, functions, manufacturing rules and true native checks. If a concrete native-tool limitation prevents completion after investigation, retain the draft and report evidence with pcb_blocked; never hide errors to deliver. + +Export and visualization utilities: final editable native project, schematic/layout images, netlists for comparison, manufacturing files, BOM, STEP and OBJ exports remain allowed. Blender and CAD utilities may render or inspect exported 3D assembly representation only; they must not change PCB electrical design or geometry or replace native electrical checks. Use genuine exported geometry, never substitute board pictures or invented components. STEP exports may be ZIP-wrapped: inspect, extract and independently validate them. An export or empty diagnostic array alone is not proof of electrical correctness. Engineering: verify regulator pinout, supply limits/decoupling, reset/boot behavior, programming access and connector pin labeling. Check exact chip/module manufacturer's reference circuitry. Antenna keepout, plug access and component envelopes must be respected. Layout and routing must correspond to the actual schematic pin/net mapping. Never remove required nets/components, mask checks, disable DRC categories or weaken rules to obtain a pass. Use sensible manufacturing clearances and trace widths and leave unconnected pins intentionally marked, not accidentally unrouted. Save and reopen/check the native design when practical. Inspect schematic, top layout and genuine 3D views yourself before submission. -Model appearance: the final assembled STEP must retain the actual native board/component/face colors, not just geometry. If you rebuild or transform an assembly, preserve XCAF color/material attributes and instance/face associations alongside the shapes. Transferring bare TopoDS shapes into a new document loses these attributes even when STEPCAFControl_Writer is used. Export with color mode enabled, then reopen the exact final STEP and verify its applied surface colors and rendered appearance. A colored OBJ/MTL or PNG does not prove that STEP colors survived. Do not arbitrarily paint geometry or add unused color declarations to satisfy validation. If a conversion loses appearance, repair the model export in this same session without redesigning the circuit or weakening electrical checks. Also deliver the genuine final OBJ/MTL and referenced textures as a clearly named assembled-3d-obj.zip when available, matching the final board geometry; this supports an independent colored appearance preview. - -Delivery: export native editable project, schematic image/PDF, routed layout image/PDF, assembled board STEP and a rendered 3D PNG/JPEG. Also include BOM, pin/net evidence and verification notes. Use pcb_deliver with those files and actual schematic/PCB document IDs. The service independently runs native checks and validates file formats and applied STEP surface colors. If rejected, inspect feedback and correct the design in this same session; do not claim completion before delivery succeeds. A failed design can be retained with pcb_blocked and exact evidence, but do not use this for ordinary recoverable mistakes. Real hardware testing is outside this software delivery; do not claim bench verification. +Shared delivery helpers and acceptance policy (native-errors-block-warnings-record-v1): +- Call pcb_check as soon as the schematic/PCB pair exists, and again before final exports. It resolves a schematic container or page ID, checks all pages and the selected PCB, and returns explicit warnings separately from blocking errors. Explicit warnings are permitted and included in delivery evidence. Do not change design rules, omit checks, or relabel errors to warnings. Unknown/missing diagnostics are not a pass. PCB DRC alone does not establish circuit functionality or real hardware performance. +- Use pcb_documents(), pcb_focus(id) and pcb_capabilities() inside pcb_eda instead of guessing document/tab IDs or APIs that the installed version may not support. pcb_export automatically transfers large File/Blob exports in chunks. Do not write your own transport/chunking scripts. +- After the circuit checks pass, use pcb_prepare_delivery for native project, schematic drawings, layout image, STEP/OBJ exports, shared installed rendering and standard file preparation. It returns files for pcb_deliver. Inspect drawings and the genuine rendered assembly once; do not regenerate an already valid deliverable for cosmetic perfection. The backend creates the manifest, checksums and delivery ZIP; do not write packaging scripts or install CAD/render dependencies per task. +- Native STEP may contain simplified/missing library components or limited colour. Retain the actual native export, provide native OBJ/MTL/render and record the limitations. These are non-blocking appearance warnings; do not rebuild tessellated STEP assemblies or manually transplant model geometry to satisfy colour checks. Invalid/empty files remain errors. Never invent replacement board pictures or claim model completeness you did not verify. +- If these helper tools are absent in a resumed older thread, call pcb_eda with code containing ONLY JSON: {"pcb_backend_tool":"prepare_delivery","schematic_id":"...","pcb_id":"..."} (or pcb_backend_tool="check"). This is dispatched by the backend to the exact same common tools. Normal JavaScript and automatic pcb_export still work. Do not recreate utility scripts. +- Deliver native editable project, schematic image/PDF/SVG, routed layout image/PDF, native assembled STEP and genuine 3D render, with BOM and engineering evidence when available. pcb_deliver runs the independent native gate and file checks. If rejected, repair the concrete error. Explicit warning-only results are accepted and must not trigger a warning-removal loop. Hardware bench verification remains outside software delivery. diff --git a/codex_pcb/native_helpers.py b/codex_pcb/native_helpers.py new file mode 100644 index 0000000..531b407 --- /dev/null +++ b/codex_pcb/native_helpers.py @@ -0,0 +1,33 @@ +"""Document resolution and capability helpers shared by verification and agent scripts.""" +HELPERS_JS = r''' +const pcb_documents = async () => ({ + schematics: await eda.dmt_Schematic.getAllSchematicsInfo(), + pcbs: await eda.dmt_Pcb.getAllPcbsInfo() +}); +const pcb_capabilities = () => { + const out={}; + for(const [group,names] of Object.entries({ + pcb_Document:['autoRouting','getCalculatingRatlineStatus','getCanvasUpdateCalculationStatus','save'], + pcb_ManufactureData:['get3DFile','getPdfFile','getGerberFile'], + sch_ManufactureData:['getSvgFile','getNetlistFile'], + dmt_EditorControl:['openDocument','activateDocument'] + }))out[group]=Object.fromEntries(names.map(n=>[n,typeof eda[group]?.[n]==='function'])); + return out; +}; +const pcb_focus = async (id) => { + const all=await eda.dmt_Schematic.getAllSchematicsInfo(); + const container=all.find(s=>s.uuid===id); + const resolved=container?.page?.[0]?.uuid || id; + const tab=await eda.dmt_EditorControl.openDocument(resolved); + if(!tab || !await eda.dmt_EditorControl.activateDocument(tab))throw Error('Cannot focus native document '+id+' (resolved '+resolved+')'); + return {documentId:resolved,tabId:tab}; +}; +const pcb_resolve = async (schematicId,pcbId) => { + const inventory=await pcb_documents(); + const schematic=inventory.schematics.find(s=>s.uuid===schematicId || s.page?.some(p=>p.uuid===schematicId)); + const pcb=inventory.pcbs.find(p=>p.uuid===pcbId); + if(!schematic?.page?.length || !pcb)throw Error('Unknown schematic/page or PCB ID. Read pcb_documents(); do not use tab IDs. '+JSON.stringify(inventory)); + if(schematic.parentProjectUuid && pcb.parentProjectUuid && schematic.parentProjectUuid!==pcb.parentProjectUuid)throw Error('Schematic and PCB belong to different projects'); + return {schematic,pcb}; +}; +''' diff --git a/codex_pcb/native_policy.py b/codex_pcb/native_policy.py new file mode 100644 index 0000000..58f17f9 --- /dev/null +++ b/codex_pcb/native_policy.py @@ -0,0 +1,58 @@ +"""Native design workflow contract and EDA transport guard (not a shell sandbox).""" +import json + +DESIGN_POLICY = 'easyeda-native-v1' +POLICY_TEXT = '''Design policy: easyeda-native-v1. +Create, edit, lay out, route, save and check the circuit only in the task's native EasyEDA project through pcb_eda. +Use native schematic/PCB primitives and native routing APIs. Do not use Freerouting, KiCad or any external EDA/router, export DSN, import SES, or exchange auto-layout/auto-route JSON files. +Local Python/JavaScript may calculate coordinates, paths and diagnostics from native object readbacks; apply their results by creating/modifying native EasyEDA objects, not by importing a converted design or routing file. Native ERC/DRC and actual native net/geometry readback are authoritative; offline checks are supplementary only. +Use pcb_eda for all EDA operations; do not bypass it with direct CLI, browser or alternate sessions. Keep the accepted circuit and manufacturing constraints. A native routing timeout has an unknown outcome: inspect the live board before another mutation. Never fall back to external routing after an error. +Validation policy: native-errors-block-warnings-record-v1. Explicit native warnings are allowed and must be recorded; actual errors and unknown/incomplete check results block delivery. Do not change electrical rules to silence errors. STEP colour/model-library appearance warnings are non-blocking: use the native STEP and native OBJ render, disclose limitations, and do not rebuild STEP geometry or spend repeated turns repairing cosmetic/library warnings. The server packages accepted delivery files; do not write packaging scripts. Call pcb_check early, then pcb_prepare_delivery when ready, then pcb_deliver. If helper tools are not present in an older session, use pcb_documents(), pcb_focus(id), pcb_capabilities() inside pcb_eda; pcb_export automatically transfers large files in chunks, and pcb_deliver applies the same warning-aware gate. +Earlier conversation instructions offering external routing are superseded. On resume, inspect the saved native board; do not replay old DSN/SES/import scripts. Existing native geometry may be retained and repaired after checking it. +Final native project, schematic/layout images, manufacturing outputs, STEP/OBJ and BOM exports remain allowed. Blender/CAD utilities may render or validate the exported 3D assembly only; they must not design, route or electrically validate the PCB instead of EasyEDA. +''' + +WORKSPACE_RULES = '''Use only this workspace for generated PCB scripts/files. Do not read or use legacy PCB pipelines or other PCB tasks. Official API references are under api-reference. Do not edit service code or unrelated projects. Do not spawn subagents. +''' + POLICY_TEXT + +BLOCKED_METHODS = { + 'pcb_ManufactureData': ['getDsnFile', 'getAutoRouteJsonFile', 'getAutoRouteJsonFileForJRouter'], + 'pcb_Document': ['importAutoRouteSesFile', 'importAutoRouteJsonFile', 'importAutoLayoutJsonFile'], +} + + +def refresh_workspace_rules(directory): + path = directory / 'AGENTS.md' + marker = '\n## Backend native design policy\n' + existing = path.read_text() if path.exists() else '' + # Preserve recovery notes and task-specific instructions before our section. + path.write_text(existing.split(marker)[0] + marker + WORKSPACE_RULES) + + +def guarded_script(code): + """Shadow eda for the submitted script, including computed/aliased property access. + + The outer invocation retains the real EDA object for the transport. This is + a workflow guard, not isolation from deliberately hostile JavaScript. + """ + return '''const __nativeOnly = (native) => { + const blocked = ''' + json.dumps(BLOCKED_METHODS) + '''; + const cache = new Map(); + return new Proxy(native, {get(target, group) { + const api = Reflect.get(target, group); + if (!Object.prototype.hasOwnProperty.call(blocked, group)) return api; + if (!cache.has(group)) cache.set(group, new Proxy(api, {get(object, method) { + if (blocked[group].includes(method)) throw new Error('easyeda-native-v1: external layout/routing exchange is disabled: '+String(group)+'.'+String(method)+'. Use native primitives or native routing APIs.'); + const value = Reflect.get(object, method); + return typeof value === 'function' ? value.bind(object) : value; + }})); + return cache.get(group); + }}); +}; +return await (async (eda) => { +''' + code + '\n})(__nativeOnly(eda));' + + +def validate_export_name(name): + if name.lower().endswith(('.dsn', '.ses')): + raise ValueError('easyeda-native-v1: DSN/SES routing exchange exports are disabled') diff --git a/codex_pcb/render_assembly.py b/codex_pcb/render_assembly.py new file mode 100644 index 0000000..b1750b8 --- /dev/null +++ b/codex_pcb/render_assembly.py @@ -0,0 +1,32 @@ +"""Run with installed Blender; render original OBJ/MTL geometry, no CAD rebuilding.""" +import sys +import math +import bpy +from mathutils import Vector + +source, output = sys.argv[sys.argv.index('--')+1:][:2] +bpy.ops.object.select_all(action='SELECT') +bpy.ops.object.delete(use_global=False) +bpy.ops.wm.obj_import(filepath=source, forward_axis='Y', up_axis='Z') +meshes=[o for o in bpy.context.scene.objects if o.type=='MESH' and len(o.data.polygons)] +if not meshes:raise RuntimeError('Native OBJ has no renderable geometry') +points=[o.matrix_world @ Vector(v) for o in meshes for v in o.bound_box] +lo=Vector([min(p[i] for p in points) for i in range(3)]) +hi=Vector([max(p[i] for p in points) for i in range(3)]) +center=(lo+hi)/2 +size=max(hi-lo) +if not math.isfinite(size) or size<=0:raise RuntimeError('Invalid native assembly bounds') +def aim(o):o.rotation_euler=(center-o.location).to_track_quat('-Z','Y').to_euler() +bpy.ops.object.camera_add(location=center+Vector((1.1,-1.4,1.5))*size) +camera=bpy.context.object;aim(camera);camera.data.type='ORTHO';camera.data.ortho_scale=size*1.7 +camera.data.clip_end=max(size*20,1000);camera.data.clip_start=max(size*.00001,.0001) +scene=bpy.context.scene;scene.camera=camera +for xyz,energy in [((1,-1,2),1.5),((-1,-.5,1),.8),((0,1,1.5),1.0)]: + bpy.ops.object.light_add(type='AREA',location=center+Vector(xyz)*size) + lamp=bpy.context.object;lamp.data.energy=energy*size*size;lamp.data.size=size;aim(lamp) +scene.render.engine='CYCLES';scene.cycles.samples=16 +scene.world.use_nodes=True;scene.world.node_tree.nodes['Background'].inputs['Strength'].default_value=.7 +scene.render.resolution_x=1400;scene.render.resolution_y=1100;scene.render.resolution_percentage=100 +scene.view_settings.view_transform='Standard';scene.render.image_settings.file_format='PNG';scene.render.filepath=output +bpy.ops.render.render(write_still=True) +print('NATIVE_ASSEMBLY_RENDER',len(meshes),'meshes',len(points),'bounds points') diff --git a/codex_pcb/requirements-delivery.txt b/codex_pcb/requirements-delivery.txt new file mode 100644 index 0000000..6653114 --- /dev/null +++ b/codex_pcb/requirements-delivery.txt @@ -0,0 +1,10 @@ +CairoSVG==2.7.1 +pypdf==5.1.0 +cairocffi==1.7.1 +cffi==2.1.1 +cssselect2==0.10.1 +defusedxml==0.7.1 +pillow==13.0.0 +pycparser==3.12 +tinycss2==1.5.1 +webencodings==0.6.1 diff --git a/codex_pcb/tests/test_delivery_toolkit.py b/codex_pcb/tests/test_delivery_toolkit.py new file mode 100644 index 0000000..39d92a4 --- /dev/null +++ b/codex_pcb/tests/test_delivery_toolkit.py @@ -0,0 +1,82 @@ +import asyncio +import base64 +import json +from pathlib import Path +import re +import tempfile +import unittest +from unittest.mock import patch +import zipfile +from codex_pcb.checks import classify_diagnostics, evaluate_verification +from codex_pcb import eda +from codex_pcb.exports import extract_archive, convert_schematic +from codex_pcb.delivery import inspect + +class WarningGate(unittest.TestCase): + def test_native_warning_false_is_accepted_and_retained(self): + warning={'type':'warn','rule':'ATTRMATCHCODE','primitives':[{'id':x} for x in ['JP1','JP2','J4','J5','J6']]} + r=evaluate_verification(dict(schPassed=False,pcbPassed=True,schErrors=[warning],pcbErrors=[],schematicParts=104,pcbParts=104)) + self.assertTrue(r['accepted']);self.assertEqual(r['warnings']['schematic'],[warning]) + def test_error_unknown_missing_and_inconsistent_results_block(self): + for rows,ok in [([{'type':'error'}],True),([{'type':'warn'},{'rule':'UNKNOWN'}],False),([],False),(None,True),([],None),([{'type':'warn','list':[{'type':'error'}]}],True)]: + with self.subTest(rows=rows,ok=ok):self.assertFalse(classify_diagnostics(rows,ok)['passed']) + def test_nested_warning_and_mixed_errors(self): + self.assertTrue(classify_diagnostics([{'type':'warning','list':[{'rule':'LIB'}]}],False)['passed']) + self.assertFalse(classify_diagnostics([{'type':'warn'},{'type':'error'}],False)['passed']) + def test_missing_geometry_still_blocks_but_step_appearance_does_not(self): + with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp: + p=Path(tmp)/'assembly.step' + p.write_text("ISO-10303-21;\nHEADER;ENDSEC;DATA;#1=CARTESIAN_POINT('',(0.,0.,0.));#2=SHAPE_REPRESENTATION('',(#1),#3);ENDSEC;END-ISO-10303-21;") + self.assertTrue(inspect(p,'step')['warnings']) + p.write_text('not a model'*30) + with self.assertRaises(ValueError):inspect(p,'step') + +class ExportSafety(unittest.TestCase): + def test_zip_escape_rejected(self): + with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp: + root=Path(tmp);p=root/'evil.zip' + with zipfile.ZipFile(p,'w') as z:z.writestr('../escape','no') + with self.assertRaises(ValueError):extract_archive(p,root/'output') + self.assertFalse((root/'escape').exists()) + def test_svg_pages_converted_to_multipage_pdf(self): + from pypdf import PdfReader + with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp: + root=Path(tmp);p=root/'pages.zip' + with zipfile.ZipFile(p,'w') as z: + for n in range(2):z.writestr(f'page-{n}.svg','R1 GND') + pdf,pages=convert_schematic(p,root/'output') + self.assertEqual(len(PdfReader(pdf).pages),2) + +class ChunkTransport(unittest.IsolatedAsyncioTestCase): + async def test_large_transfer_and_truncation_preserve_existing_file(self): + for truncated in [False,True]: + with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp: + folder=Path(tmp);dst=folder/'artifacts/large.bin';dst.parent.mkdir();dst.write_bytes(b'previous') + payload=bytes([37])*(9*1024*1024+17);calls=[] + async def invoke(args,code=None,timeout=210): + calls.append(code) + if 'const __files=[]' in code:return {'result':True,'files':[{'name':'large.bin','bytes':len(payload),'index':0}]} + if code.startswith('delete '):return True + begin,end=map(int,re.search(r'f.slice\((\d+),(\d+)\)',code).groups()) + data=payload[begin:end] + if truncated and begin:data=data[:-1] + return {'base64':base64.b64encode(data).decode()} + async def lock():return (folder/'lock').open('a+') + t={'approval':{'hash':'test'},'state':'running','eda_session':'test'} + with patch.object(eda,'workspace',return_value=folder),patch.object(eda,'event'),patch.object(eda,'host_lock',side_effect=lock),patch.object(eda,'cli',side_effect=invoke),patch.object(eda,'EDA_LOCK',asyncio.Lock()): + if truncated: + with self.assertRaisesRegex(ValueError,'Truncated'):await eda.execute(t,'return true') + self.assertEqual(dst.read_bytes(),b'previous') + else: + await eda.execute(t,'return true');self.assertEqual(dst.read_bytes(),payload) + self.assertTrue(calls[-1].startswith('delete '));self.assertFalse(list(dst.parent.glob('*.partial'))) + +class ResumedToolCompatibility(unittest.IsolatedAsyncioTestCase): + async def test_old_eda_tool_dispatches_shared_preparation(self): + from unittest.mock import AsyncMock + from codex_pcb import app + task={'state':'running','approval':{'hash':'x'}} + prepared={'files':[{'kind':'step','path':'artifacts/board.step'}]} + with patch.object(app,'event'),patch.object(app,'frozen'),patch.object(app,'prepare_delivery',new_callable=AsyncMock,return_value=prepared) as prepare,patch.object(app,'execute',new_callable=AsyncMock) as execute: + result=await app.handle(task,'item/tool/call',{'tool':'pcb_eda','callId':'test','arguments':{'label':'Common delivery','code':json.dumps({'pcb_backend_tool':'prepare_delivery','schematic_id':'sch','pcb_id':'pcb'})}}) + self.assertTrue(result['success']);prepare.assert_awaited_once_with(task,'sch','pcb');execute.assert_not_called() diff --git a/codex_pcb/tests/test_freerouting.py b/codex_pcb/tests/test_freerouting.py index 1bfba6e..ee04e7d 100644 --- a/codex_pcb/tests/test_freerouting.py +++ b/codex_pcb/tests/test_freerouting.py @@ -1,5 +1,4 @@ -"""Launcher boundaries; no live EDA application or real board is modified.""" -import json +"""Old task commands must fail without spawning Java/Xvfb or changing files.""" import os from pathlib import Path import subprocess @@ -9,75 +8,17 @@ import unittest LAUNCHER = Path(__file__).resolve().parents[1] / 'freerouting.py' - -class LauncherTest(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory(dir=Path(__file__).parent) - self.addCleanup(self.temp.cleanup) - self.root = Path(self.temp.name) - self.source = self.root / 'board.dsn' - self.source.write_text('(pcb test)') - self.jar = self.root / 'router.jar' - self.jar.touch() - self.output = self.root / 'result.ses' - java = self.root / 'java' - java.write_text(f'#!{sys.executable}\n' + '''import json,os,sys,time -from pathlib import Path -args=sys.argv[1:] -Path(os.environ['CALL_LOG']).write_text(json.dumps(args)) -if os.environ.get('STALL'):time.sleep(30) -if not os.environ.get('NO_OUTPUT'): - Path(args[args.index('-do')+1]).write_text('(session board (routes (network)))') -''') - java.chmod(0o755) - self.env = dict(os.environ, PATH=str(self.root), CALL_LOG=str(self.root / 'calls.json')) - - def run_cli(self, *extra, help_only=False): - args = [] if help_only else ['--input', str(self.source), '--output', str(self.output), '--jar', str(self.jar), '--visible'] - return subprocess.run([sys.executable, str(LAUNCHER), *args, *extra], env=self.env, capture_output=True, text=True, timeout=10) - - def test_help_never_starts_java(self): - r = self.run_cli('--help', help_only=True) - self.assertEqual(r.returncode, 0) - self.assertFalse((self.root / 'calls.json').exists()) - - def test_missing_input_does_not_open_file_picker(self): - self.source.unlink() - self.assertEqual(self.run_cli().returncode, 2) - self.assertFalse((self.root / 'calls.json').exists()) - - def test_unknown_help_and_dialog_override_are_rejected(self): - for args in [('--', '--help'), ('--', '-dct', '20')]: - self.assertEqual(self.run_cli(*args).returncode, 2) - self.assertFalse((self.root / 'calls.json').exists()) - - def test_route_publishes_ses_without_changing_source(self): - r = self.run_cli('--', '-mp', '7', '-mt', '1') - self.assertEqual(r.returncode, 0, r.stderr) - args = json.loads((self.root / 'calls.json').read_text()) - self.assertEqual(args[args.index('-dct')+1], '0') - self.assertNotEqual(args[args.index('-de')+1], str(self.source)) - self.assertEqual(self.source.read_text(), '(pcb test)') - self.assertTrue(self.output.read_text().startswith('(session')) - self.assertEqual(list(self.root.glob('.freerouting-*')), []) - - def test_existing_output_is_preserved(self): - self.output.write_text('previous result') - self.assertEqual(self.run_cli().returncode, 2) - self.assertEqual(self.output.read_text(), 'previous result') - self.assertFalse((self.root / 'calls.json').exists()) - - def test_exit_zero_without_output_is_failure(self): - self.env['NO_OUTPUT'] = '1' - self.assertEqual(self.run_cli().returncode, 2) - self.assertFalse(self.output.exists()) - - def test_timeout_does_not_publish_partial_result(self): - self.env['STALL'] = '1' - self.assertEqual(self.run_cli('--timeout', '0.2').returncode, 124) - self.assertFalse(self.output.exists()) - self.assertEqual(list(self.root.glob('.freerouting-*')), []) - - -if __name__ == '__main__': - unittest.main() +class RetiredLauncherTest(unittest.TestCase): + def test_old_commands_cannot_route_or_open_windows(self): + with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp: + root = Path(tmp) + source, output = root/'board.dsn', root/'result.ses' + source.write_text('(pcb original)') + output.write_text('previous result') + for args in [[], ['--help'], ['--input',str(source),'--output',str(output),'--visible']]: + r = subprocess.run([sys.executable,str(LAUNCHER),*args],env=dict(os.environ,PATH=str(root)),capture_output=True,text=True,timeout=5) + self.assertEqual(r.returncode,2) + self.assertIn('easyeda-native-v1',r.stderr) + self.assertEqual(source.read_text(),'(pcb original)') + self.assertEqual(output.read_text(),'previous result') + self.assertEqual(len(list(root.iterdir())),2) diff --git a/codex_pcb/tests/test_native_policy.py b/codex_pcb/tests/test_native_policy.py new file mode 100644 index 0000000..f61a7a1 --- /dev/null +++ b/codex_pcb/tests/test_native_policy.py @@ -0,0 +1,67 @@ +import asyncio +import json +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +from unittest.mock import AsyncMock, patch +from codex_pcb.native_policy import BLOCKED_METHODS, guarded_script, validate_export_name, refresh_workspace_rules +from codex_pcb import eda + +class NativePolicyTest(unittest.TestCase): + def run_js(self, code): + self.assertIsNotNone(shutil.which('node'), 'Node is required to verify the EDA guard') + r = subprocess.run(['node','-e',code],capture_output=True,text=True,timeout=10) + self.assertEqual(r.returncode,0,r.stderr) + return json.loads(r.stdout) + + def test_native_edit_route_drc_and_delivery_exports_still_work(self): + result = self.run_js('''const eda={ + pcb_PrimitiveLine:{create:async()=>({net:'GND'})}, + pcb_Document:{flag:7,doLayout:async function(){return this.flag},doRoute:async function(){return this.flag},save:async()=>true,importChanges:async()=>true}, + pcb_Drc:{check:async()=>true},sch_Drc:{check:async()=>true}, + pcb_ManufactureData:{getStepFile:async()=> 'STEP',getNetlistFile:async()=> 'NET'} + };(async()=>{''' + guarded_script('''return [await eda.pcb_PrimitiveLine.create(),await eda.pcb_Document.doRoute(),await eda.pcb_Document.save(),await eda.pcb_Document.importChanges(),await eda.pcb_Drc.check(),await eda.sch_Drc.check(),await eda.pcb_ManufactureData.getStepFile(),await eda.pcb_ManufactureData.getNetlistFile()];''') + '''})().then(x=>console.log(JSON.stringify(x))).catch(e=>{console.error(e);process.exit(1)});''') + self.assertEqual(result,[{'net':'GND'},7,True,True,True,True,'STEP','NET']) + + def test_exchange_calls_are_blocked_even_with_computed_names_and_aliases(self): + for group, methods in BLOCKED_METHODS.items(): + for method in methods: + script = f'''const api=eda[{json.dumps(group)}]; return await api[{json.dumps(method)}]();''' + code = f'''let invoked=false;const eda={{{json.dumps(group)}:{{{json.dumps(method)}:()=>{{invoked=true;}}}}}}; + (async()=>{{{guarded_script(script)}}})().then(()=>{{throw Error('allowed external exchange')}}).catch(e=>console.log(JSON.stringify({{invoked,message:e.message}})));''' + result = self.run_js(code) + self.assertFalse(result['invoked']) + self.assertIn('easyeda-native-v1',result['message']) + + def test_file_guard_and_workspace_recovery_notes(self): + for name in ['route.dsn','a/route.SES']: + with self.assertRaises(ValueError):validate_export_name(name) + for name in ['board.epro2','board.step','board.obj','board.png','schematic.net','diagnostic.json']: + validate_export_name(name) + with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp: + p=Path(tmp);(p/'AGENTS.md').write_text('Recovery: open saved project.\n') + refresh_workspace_rules(p);refresh_workspace_rules(p) + text=(p/'AGENTS.md').read_text() + self.assertIn('Recovery: open saved project.',text) + self.assertEqual(text.count('## Backend native design policy'),1) + +class NativeTransportTest(unittest.IsolatedAsyncioTestCase): + async def test_actual_transport_wrapper_executes_and_blocks_before_native_method(self): + with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp: + folder=Path(tmp) + async def invoke(args, code=None, timeout=210): + harness='''const eda={pcb_Document:{save:async()=>true,importAutoRouteSesFile:()=>{throw Error('UNGUARDED')}}};(async()=>{'''+code+'''})().then(x=>console.log(JSON.stringify(x))).catch(e=>{console.error(e.message);process.exit(1)});''' + r=subprocess.run(['node','-e',harness],capture_output=True,text=True,timeout=10) + if r.returncode:raise RuntimeError(r.stderr) + return json.loads(r.stdout) + async def lock():return (folder/'lock').open('a+') + t={'approval':{'hash':'test'},'state':'running','eda_session':'test'} + with patch.object(eda,'workspace',return_value=folder),patch.object(eda,'event'),patch.object(eda,'host_lock',side_effect=lock),patch.object(eda,'cli',side_effect=invoke),patch.object(eda,'EDA_LOCK',asyncio.Lock()): + result=await eda.execute(t,'return await eda.pcb_Document.save();') + self.assertTrue(result['result']) + with self.assertRaisesRegex(RuntimeError,'easyeda-native-v1'): + await eda.execute(t,'return await eda.pcb_Document.importAutoRouteSesFile();') + with self.assertRaisesRegex(RuntimeError,'DSN/SES'): + await eda.execute(t,"return await pcb_export({},'route.SES');") diff --git a/codex_pcb/tests/test_native_sessions.py b/codex_pcb/tests/test_native_sessions.py new file mode 100644 index 0000000..61e4018 --- /dev/null +++ b/codex_pcb/tests/test_native_sessions.py @@ -0,0 +1,52 @@ +import asyncio +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +from codex_pcb import app as service +from codex_pcb.native_policy import DESIGN_POLICY + +class SessionPolicyTest(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory(dir=Path(__file__).parent) + self.addCleanup(self.tmp.cleanup) + self.folder=Path(self.tmp.name) + + async def test_approval_has_no_external_launcher(self): + t={'id':'test','state':'review','proposal':{'revision':1,'hash':'approved','markdown':'accepted board'}} + with patch.object(service,'get',return_value=t),patch.object(service,'event'),patch.object(service,'workspace',return_value=self.folder),patch.object(service,'schedule') as schedule: + await service.approve('test',service.Approval(revision=1,hash='approved')) + prompt=schedule.call_args.args[1] + self.assertIn(DESIGN_POLICY,prompt) + self.assertNotIn('External router launcher',prompt) + self.assertNotIn('freerouting.py',prompt) + self.assertEqual(t['approval']['hash'],'approved') + self.assertEqual(t['design_policy'],DESIGN_POLICY) + + async def test_resume_keeps_thread_and_reasserts_policy(self): + calls=[] + class FakeServer: + def __init__(self,*args):self.events=asyncio.Queue() + async def __aenter__(self):return self + async def __aexit__(self,*args):pass + async def call(self,method,args): + calls.append((method,args)) + if method=='thread/resume':return {'thread':{'id':'existing-thread'},'model':service.MODEL} + if method=='turn/start': + await self.events.put({'method':'turn/completed','params':{'threadId':'existing-thread','turn':{'id':'next-turn','status':'completed'}}}) + return {'turn':{'id':'next-turn'}} + raise AssertionError(method) + (self.folder/'evidence').mkdir() + (self.folder/'AGENTS.md').write_text('Recovery project identity retained.\n') + t={'id':'test','thread_id':'existing-thread','approval':{'hash':'accepted'},'frozen_source':service.fingerprint()} + with patch.object(service,'workspace',return_value=self.folder),patch.object(service,'event'),patch.object(service,'AppServer',FakeServer): + await service.run_turn(t,'Old external router advice in history',True) + service.CLIENTS.pop('test',None) + self.assertEqual([c[0]for c in calls],['thread/resume','turn/start']) + self.assertIn(DESIGN_POLICY,calls[0][1]['developerInstructions']) + self.assertTrue(calls[1][1]['input'][0]['text'].startswith('Design policy: '+DESIGN_POLICY)) + self.assertIn('Recovery project identity retained.',(self.folder/'AGENTS.md').read_text()) + + def test_source_freeze_still_rejects_unapproved_backend_drift(self): + with self.assertRaisesRegex(RuntimeError,'Backend source changed'): + service.frozen({'approval':{'hash':'accepted'},'frozen_source':'unexpected'}) diff --git a/designer/src/codex-pcb/CodexPcbDock.tsx b/designer/src/codex-pcb/CodexPcbDock.tsx index 3c40c15..012b31f 100644 --- a/designer/src/codex-pcb/CodexPcbDock.tsx +++ b/designer/src/codex-pcb/CodexPcbDock.tsx @@ -1,14 +1,11 @@ import { useEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import './codex-pcb.css'; -import { DeliveryModel3D } from './DeliveryModel3D.js'; -import { findObjArchive } from './model-appearance.js'; +import { DesignPreview } from './DesignPreview.js'; +import type { Artifact, Session, Entry } from './workbench-types.js'; import { TaskProgress } from './TaskProgress.js'; import { Markdown as RichMarkdown } from '@ziroeda/ai/markdown.js'; -type Artifact = { name: string; kind: string; label: string; bytes: number; sha256: string }; -type Session = { id: string; request: string; state: string; busy: boolean; thread_id?: string; error?: string; cursor: number; created_at: number; updated_at?: number; proposal?: { title: string; markdown: string; revision: number; hash: string; at?: number }; approval?: { revision: number; at?: number }; delivery?: { files: Artifact[]; notes: string }; }; -type Entry = { seq: number; at: number; type: string; data: Record }; const BASE = `${import.meta.env.BASE_URL}pcb-api`; const ACTIVE = 'vibemake.pcb2.persistent-session'; const STATES: Record = { planning: '正在制定方案', review: '等待审核方案', needs_input: '等待补充需求', running: '自主设计中', completed: '已完成交付', blocked: '遇到阻碍', failed: '运行失败', interrupted: '等待恢复', cancelled: '已停止' }; @@ -32,11 +29,14 @@ export function CodexPcbDock(): JSX.Element { const [comment, setComment] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); - const [tab, setTab] = useState<'plan' | 'activity' | 'files'>('plan'); + const [tab, setTab] = useState<'plan' | 'activity' | 'files'>('activity'); const cursor = useRef(0); const activeRef = useRef(active); - const activity = useRef(null); - const choose = (id: string | null) => { setActive(id); setTask(null); setEntries([]); cursor.current = 0; activeRef.current = id; setTab('plan'); setError(''); if (id) localStorage.setItem(ACTIVE,id); else localStorage.removeItem(ACTIVE); }; + const followChat = useRef(true); + const main = useRef(null); + // biome-ignore lint/correctness/useExhaustiveDependencies: changing the tab or task resets the content scroll position. + useEffect(() => { followChat.current = true; main.current?.scrollTo({ top: tab === 'activity' ? main.current.scrollHeight : 0 }); }, [tab, active]); + const choose = (id: string | null) => { setActive(id); setTask(null); setEntries([]); cursor.current = 0; activeRef.current = id; setTab('activity'); setComment(''); setError(''); if (id) localStorage.setItem(ACTIVE,id); else localStorage.removeItem(ACTIVE); }; useEffect(() => { if (!open) return; let cancelled = false; let timer: number; const poll = async () => { try { @@ -47,37 +47,67 @@ export function CodexPcbDock(): JSX.Element { setTask(next); if (changes.length) { cursor.current = changes[changes.length - 1]!.seq; setEntries(prev => [...prev, ...changes].slice(-600)); } } - } catch (e) { if (!cancelled) setError(String(e)); } + } catch (e) { if (!cancelled && activeRef.current === active) setError(String(e)); } finally { if (!cancelled) timer = window.setTimeout(poll, 2000); } }; void poll(); return () => { cancelled = true; clearTimeout(timer); }; }, [open, active]); - useEffect(() => { if (tab === 'activity') activity.current?.scrollTo({ top: activity.current.scrollHeight, behavior: 'smooth' }); }, [entries.length, tab]); + useEffect(() => { if (tab === 'activity' && followChat.current) main.current?.scrollTo({ top: main.current.scrollHeight, behavior: 'smooth' }); }, [entries.length, tab]); const action = async (fn: () => Promise) => { setBusy(true); setError(''); try { await fn(); } catch(e) { setError(String(e)); } finally { setBusy(false); } }; const create = () => action(async () => { const t = await api('/sessions', { text: request }); choose(t.id); setTask(t); setRequest(''); }); - const send = () => action(async () => { const t = await api(`/sessions/${active}/comments`, { text: comment }); setTask(t); setComment(''); }); - const approve = () => action(async () => { if (!task?.proposal) return; setTask(await api(`/sessions/${active}/approve`, { revision: task.proposal.revision, hash: task.proposal.hash })); setTab('activity'); }); - const cancel = () => action(async () => { setTask(await api(`/sessions/${active}/cancel`, {})); }); - const resume = () => action(async () => { setTask(await api(`/sessions/${active}/resume`, {})); setTab('activity'); }); + const updateTask = (next: Session) => { if (activeRef.current === next.id) setTask(next); }; + const send = () => action(async () => { const id = active; const t = await api(`/sessions/${id}/comments`, { text: comment }); updateTask(t); if (activeRef.current === id) { setComment(''); setTab('activity'); } }); + const approve = () => action(async () => { if (!task?.proposal) return; const id = active; updateTask(await api(`/sessions/${id}/approve`, { revision: task.proposal.revision, hash: task.proposal.hash })); if (activeRef.current === id) setTab('activity'); }); + const cancel = () => action(async () => { updateTask(await api(`/sessions/${active}/cancel`, {})); }); + const resume = () => action(async () => { const id = active; updateTask(await api(`/sessions/${id}/resume`, {})); if (activeRef.current === id) setTab('activity'); }); const downloadable = (f: Artifact) => `${BASE}/sessions/${active}/files/${encodeURIComponent(f.name)}`; - const step = task?.delivery?.files.find(f => f.kind === 'step' && /\.(step|stp)$/i.test(f.name)); - const objArchive = findObjArchive(task?.delivery?.files ?? []); const canReview = task && !task.approval && !task.busy && ['review','needs_input','failed'].includes(task.state); const interesting = entries.filter(e => ['message','activity','eda.started','eda.error','session.reconnecting','session.failed','production.blocked','delivery.completed','proposal.approved','session.resumed'].includes(e.type)); + const messages = interesting.filter(e => e.type === 'message'); + const logs = interesting.filter(e => e.type !== 'message'); + const setOpened = (value: boolean) => { setOpen(value); const url = new URL(location.href); if (value) url.searchParams.set('ai', '1'); else url.searchParams.delete('ai'); history.replaceState(null, '', url); }; const view =
- {!open ? :
-
Codex PCB 工作台从方案到真实电路板
-
-
{active && task && } -
{error &&
{error}
} - {!active ?
让需求成为电路板

你想设计什么?

描述用途、供电、接口和尺寸要求。AI 会先提出方案,由你审核后再开始绘制。