修复了ai审核流程,该用max思考强度并对应调整了token限流阀和思考时间

This commit is contained in:
2026-11-05 13:38:14 +08:00
parent 4c41ce87ac
commit 08a70fce06
24 changed files with 24734 additions and 124 deletions
+7 -1
View File
@@ -11,5 +11,11 @@ AI_PCB_API_PORT=8000
# AI_PCB_API_DATA=/absolute/private/vibemake-pcb-data
# KICAD_CLI=/usr/bin/kicad-cli
# KICAD_PYTHON=/usr/bin/python3
AI_PCB_TASK_SECONDS=900
AI_PCB_TASK_SECONDS=10800
AI_PCB_ROUTER_SECONDS=180
AI_PCB_MODEL_TIMEOUT=1800
AI_PCB_MODEL_IDLE_TIMEOUT=300
AI_PCB_COMMAND_TIMEOUT=21600
+21 -1
View File
@@ -27,7 +27,9 @@ cp .env.example .env.local
原服务器可继续设置 `AI_PCB_CODEX_HOME=/home/wpz/.config/ai-pcb-codex`,只读取其中原有 DeepSeek provider 凭据,不启动 Codex。显式 `DEEPSEEK_API_KEY` 优先。密钥不返回浏览器。默认运行数据在 `~/.local/share/vibemake-pcb`,也可用 `AI_PCB_API_DATA` 指定仓库外目录。
模型默认 `deepseek-flash`,通过 DeepSeek `/responses` 直接调用。规划与电路数据均有结构约束、真实库引脚校验和有限自动修复;不让模型临时编写执行脚本。调用记录和任务历史放在运行目录,不能纳入 Git。
模型默认 `deepseek-flash`,通过 DeepSeek `/responses` 直接调用。需求与方案、器件选型、电路生成和修复统一使用 `reasoning.effort=max`;单次输出上限为 327680 tokens(含推理),调用记录中保存实际档位。缓存包含思考强度和输出预算,修改配置后不会沿用之前低强度的缓存。规划与电路数据均有结构约束、真实库引脚校验和有限自动修复;不让模型临时编写执行脚本。调用记录和任务历史放在运行目录,不能纳入 Git。
高强度推理默认每次请求允许 30 分钟(`AI_PCB_MODEL_TIMEOUT=1800`,可调至最多 2 小时),超时及临时网络错误自动重试一次,每次尝试重新计时;不会自动降低 `max` 推理强度。连续 5 分钟无网络数据会按连接超时重试(`AI_PCB_MODEL_IDLE_TIMEOUT=300`),持续心跳不会触发此空闲限制。进入设计后的总预算默认 3 小时(`AI_PCB_TASK_SECONDS=10800`,最多 24 小时);外层命令保护默认 6 小时(`AI_PCB_COMMAND_TIMEOUT=21600`,最多 48 小时)。扩大预算时外层命令时限应覆盖方案生成及设计预算。这些是最长等待预算,不是每单固定耗时。模型失败尝试的类型、时长与预算写入任务 calls 目录;只对临时错误做有限重试,预算耗尽仍会明确结束。
可配置 `KICAD_CLI`、`KICAD_PYTHON`、`KICAD_SYMBOL_DIR`、`KICAD_FOOTPRINT_DIR`、`KICAD_3DMODEL_DIR`、`AI_PCB_FREEROUTING_JAR`。后三类资源路径应与 KiCad 实际安装匹配。非 Linux 平台的后台需要另外适配系统 Python 和虚拟显示,当前完整生成验收平台为 Linux;浏览器客户端不受此限制。
@@ -39,6 +41,10 @@ DeepSeek 提供器件、引脚网络和功能意图;程序从安装库解析
PCB 通过 DSN/SES 交给固定版本 Freerouting,在有限预算内选择原生 DRC 更好的候选。电源线宽会在细间距器件处收窄,具体实际线宽记录在检查报告;这些是原型规则,不能被当成额定载流能力保证。
连接器机械门禁独立于电气 DRC:支持的卧式 XT60PW-M 根据真实封装 -Y 插合轴在左边缘旋转 90°,插合面贴到板外,并保留 20mm 宽、25mm 深的插头操作通道;这些净空值是保守设计假设,不是厂家公差。立式 XT30UPB-F 沿 +Z 插合,保留本体周围 1mm 的操作净空。任何其他器件或插头包络都不能占用这些区域;固定板框放不下时明确失败,不允许挤压净空或静默扩板。未知侧插连接器画像阻止制造放行。
检查从实际保存、重开的 PCB 读取坐标和旋转角,在导出及审核时分别执行,不能凭模型文字承诺或电气 DRC 通过替代。缺失连接器 3D 模型会记录在机械报告中,焊盘/丝印预览不能充当完整 3D 碰撞验收。支持的 AMASS 封装极性以实际厂家图与封装标记为准,pin 1 为负、pin 2 为正,不能按通用连接器符号猜测。
交付门禁包括:原生 ERC、原理图与 PCB 字段/引脚网络一致性、原生 DRC(含未连接)、真实铜区重建、保存重开后的再次检查、布局和走线检查。不存在、未确认或解析失败的检查均不能当作通过。完整保存 JSON 报告、警告和排除项。
- **delivery_ready**:完整检查通过,原生工程、Gerber、钻孔、BOM 和报告已预先打包。用户确认当前摘要后立即开放下载,不在点击审核时重新生成。
@@ -74,3 +80,17 @@ KICAD_NATIVE_TESTS=1 PYTHONPATH=.:api .venv/bin/python -m unittest discover -s t
原生负例包括删掉走线、改错焊盘网络,必须被拦截;正确工程必须导出制造文件。API 测试覆盖摘要审核、排队隔离、状态粘性、幂等与非法请求。真实验收脚本另外验证审核前无制造文件、旧摘要拒绝、审核后 ZIP 内容及下载摘要。测试数据均不属于可提交源码。
KiCad 10 的系统 Python SWIG 绑定用于确定性 PCB 操作;检查和导出由 CLI 执行。10.0.7 绑定有 PROPERTY_ENUM 启动日志,原生日志保留。升级到 KiCad 11 前需替换/验证此兼容层。第三方路由器的来源与校验见 THIRD-PARTY.md。
### 元器件三维预览
生成 PCB 时会解析封装的真实 3D 模型,并将可用的 STEP/WRL 文件复制到工程 `models/`,改用 `${KIPRJMOD}` 相对路径,随原生工程和下载包交付。服务器标准库缺失的 HRO USB-C、AMASS XT60PW-M 与 XT30UPB-F 使用仓库内固定版本、校验摘要的真实 STEP 模型;来源、许可与安装变换见 `assets/3dmodels/MODEL-SOURCES.md`。不会把不匹配型号的模型套用到器件上。
检查记录包含 `model_coverage`:总器件数、有模型的器件数及缺失清单;缺失模型会进入成果提示。三维外观帮助检查结构,不取代连接器插拔空间检查和电气 DRC。补充历史任务的三维预览不改写冻结工程,也不解除原有制造限制。
### 原理图局部修复与功能保护
初次生成完整电路后,修复阶段只接收 `CIRCUIT_PATCH`:逐引脚声明修改前网络、目标网络及电气理由。ERC 的类型、严重程度、具体器件/引脚条目、引脚名称/电气类型及当前网络会完整传给模型;编译器电源标记另行标识。只有报错涉及的真实引脚允许修改,原生网表与目标电路不一致不能通过改目标电路掩盖。
服务器锁定器件清单、数值、无关引脚、原有网络名称/类型、外部供电声明和接口复用表。补丁没有删器件或把已连接引脚改成 NC 的操作,禁止借用无关电阻、隔离电源输出凑 ERC 通过,并检查原有通信/烧录映射(含串联电阻通路)是否仍连通。涉及供电引脚跨电源网络的修改需要经过验证的器件专用规则,不能由通用补丁猜测完成。
每轮重新执行完整语义检查及适用的原生 ERC/网表核对。已知错误须减少且不能引入新错误;初次通过语义检查后才能观测到的 ERC 问题作为下一检查阶段处理。被拒绝的补丁不替换上一版电路,具体拒绝证据会传给下一轮。初次生成加两次修复的预算保持不变;需要改 BOM/数值或缺少器件专用依据时保留原电路和明确未解决原因,不降低检查门槛。任务工作目录记录 `repair-*-context.json`、`repair-*-decision.json` 和 `repair-baseline.json`,不纳入仓库。
+2
View File
@@ -11,3 +11,5 @@ Freerouting 1.9.0 is downloaded at setup into an ignored cache. The JAR is not c
The subprocess interface uses KiCad Specctra DSN/SES export/import. Upgrading the router requires changing the pinned checksum and repeating native routing, DRC, and download acceptance. KiCad libraries and tools are installed as system packages and retain their own upstream licenses.
The project-local HRO USB-C STEP fallback is attributed in `assets/3dmodels/MODEL-SOURCES.md`, with the demo's CERN-OHL-P-2.0 license. These notices accompany exported native projects.
The exact AMASS XT60PW-M and XT30UPB-F STEP model fallbacks come from pinned revisions of nate-i-think/pytheas and mjbots/power_dist (Apache-2.0). Full source paths, revisions, attribution, hashes, and model-to-footprint transforms are recorded in `assets/3dmodels/MODEL-SOURCES.md`; `LICENSE.Apache-2.0` accompanies bundled and exported copies. Model geometry is unchanged. Copper, drill geometry, and native footprint pad numbering are retained.
+3 -2
View File
@@ -9,7 +9,7 @@ class Settings:
mode: str = 'simulation'
simulator: Path | None = None
origins: tuple = ('http://127.0.0.1:5173','http://localhost:5173','http://127.0.0.1:8000')
command_timeout: int = 7200
command_timeout: int = 21600
@classmethod
def env(cls):
base=Path(__file__).resolve().parents[2]
@@ -19,6 +19,7 @@ class Settings:
return cls(Path(os.getenv('AI_PCB_API_DATA',str(Path.home()/'.local/share/vibemake-pcb'))).resolve(),
Path(os.getenv('AI_PCB_PACK_DIR',str(base/'deliver_pack'))).resolve(),mode,
Path(simulator).resolve() if simulator else None,
tuple(os.getenv('AI_PCB_ALLOWED_ORIGINS','http://127.0.0.1:5173,http://localhost:5173,http://127.0.0.1:8000').split(',')))
tuple(os.getenv('AI_PCB_ALLOWED_ORIGINS','http://127.0.0.1:5173,http://localhost:5173,http://127.0.0.1:8000').split(',')),
command_timeout=min(172800,max(300,int(os.getenv('AI_PCB_COMMAND_TIMEOUT','21600')))))
@property
def core_root(self):return self.root/'core'
+14 -3
View File
@@ -2,7 +2,7 @@ import hashlib,json,mimetypes,threading,time,uuid
from pathlib import Path
from .provider import Provider,UnknownOutcome
PUBLIC_CORE_FIELDS={'task_id','state','revision','title','eda_engine','metrics','questions','proposal','proposal_hash','selected_option','delivery','delivery_review','download_ready','manufacturing_package','error','findings','manufacturing_blockers','native_job_id'}
PUBLIC_CORE_FIELDS={'task_id','state','revision','title','eda_engine','delivery_revoked','metrics','questions','proposal','proposal_hash','selected_option','delivery','delivery_review','download_ready','manufacturing_package','error','findings','manufacturing_blockers','native_job_id'}
class Engine:
def __init__(self,settings,store):
@@ -110,7 +110,7 @@ class Engine:
self.store.enqueue({'request_id':f'auto-recover-{tid}-{uuid.uuid4().hex}','action':'recover','payload':{'task_id':tid}},tid)
def update_task(self,value):
tid=value['task_id'];old=self.store.task(tid) or {}
if old.get('state')=='completed' and value.get('state')!='completed':
if old.get('state')=='completed' and value.get('state')!='completed' and not value.get('delivery_revoked'):
return # a delayed generation result cannot revoke a released immutable revision
if old.get('state')=='failed' and value.get('state')=='needs_operator':
return # a terminal verdict must not be undone by a status poll
@@ -119,12 +119,18 @@ class Engine:
if current_manifest and previous_manifest and current_manifest!=previous_manifest:
with self.store.db() as db:db.execute('DELETE FROM artifacts WHERE task_id=?',(tid,))
data={**old,**value,'simulation':self.settings.mode=='simulation'}
preview=data.get('render_override') or {}
if preview.get('source_manifest_sha256')!=(data.get('delivery') or {}).get('manifest_sha256'):
data.pop('render_override',None)
if not self.store.save_task(data):return
delivery=data.get('delivery') or {}
for item in delivery.get('artifacts',[]):
path=item.get('absolute_path') or item.get('path')
if path:self.register(tid,path,item.get('kind','other'),item.get('sha256'),False)
if delivery.get('archive'):self.register(tid,delivery['archive'],'review_package',delivery.get('archive_sha256'),False)
preview=data.get('render_override') or {}
if preview.get('path') and preview.get('sha256'):
self.register(tid,preview['path'],'render',preview['sha256'],False)
if data.get('manufacturing_package') and data['state']=='completed':
item=data['manufacturing_package'];self.register(tid,item['path'],'manufacturing_package',item.get('sha256'),True)
def register(self,tid,path,kind,sha,release):
@@ -137,7 +143,7 @@ class Engine:
with self.store.db() as db:
db.execute('INSERT OR REPLACE INTO artifacts VALUES(?,?,?,?,?,?,?,?)',(aid,tid,str(p),kind,actual,mime,int(self.settings.mode=='simulation'),int(release)))
def public_task(self,data):
result={k:v for k,v in data.items() if k not in {'delivery','manufacturing_package','native_job_id'}}
result={k:v for k,v in data.items() if k not in {'delivery','manufacturing_package','native_job_id','render_override'}}
if result.get('state')=='delivery_ready' and (result.get('manufacturing_blockers') or result.get('download_ready') is not True):result['state']='draft_ready'
history=self.store.history(data['task_id'])
if history.get('display_title'):result['title']=history['display_title']
@@ -153,5 +159,10 @@ class Engine:
data=self.store.task(tid)
if not data:return []
with self.store.db() as db:rows=db.execute('SELECT * FROM artifacts WHERE task_id=?',(tid,)).fetchall()
# A model-only preview can supplement an immutable delivery without rewriting it.
preview=data.get('render_override') or {}
if preview.get('source_manifest_sha256')==(data.get('delivery') or {}).get('manifest_sha256'):
preferred=next((r['id'] for r in rows if r['kind']=='render' and r['path']==preview.get('path') and r['sha256']==preview.get('sha256')),None)
if preferred:rows=[r for r in rows if r['kind']!='render' or r['id']==preferred]
return [{'artifact_id':r['id'],'kind':r['kind'],'name':Path(r['path']).name,'sha256':r['sha256'],'mime_type':r['mime'],
'simulation':bool(r['simulation']),'download_url':f'/api/v1/tasks/{tid}/artifacts/{r["id"]}'} for r in rows if not r['release_only'] or data['state']=='completed']
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+16
View File
@@ -9,3 +9,19 @@ Project notice: Modified by KiCad Project Feb 17, 2025 (removed manufacturing fi
SHA-256: `f902880f83a1b397b76360ed8686b6132a66920b3c1aac8e98239315842ff43e`.
The corresponding demo footprint uses zero model offset, rotation, and unit scale. The standard HRO footprint's missing model reference is redirected to this project-local STEP. Copper, drills, body and mating orientation remain those of the installed KiCad footprint. This model supports visual placement review; it is not an enclosure tolerance or collision certification.
# AMASS connector models
The following unchanged STEP files are sourced from public Apache-2.0 projects. `LICENSE.Apache-2.0` is preserved here and in exported projects. Original author/project attribution and immutable source revisions:
- `AMASS_XT60PW-M.step`: nate-i-think/pytheas, revision `3958148603d024ea790e430714f92477c8e1bb61`, source `Footprints/XT60PW-M/XT60PW-M.step`.
Source: https://github.com/nate-i-think/pytheas/blob/3958148603d024ea790e430714f92477c8e1bb61/Footprints/XT60PW-M/XT60PW-M.step
SHA-256: `4275e6105b49a74775c3eb50e679d0736e5a4f2b6ba738f9d29b52eaf1722003`.
Model rotation follows the source footprint (-90, 0, -180). Source footprint body bounds -7.75..7.75 / -10.35..7.85 become stock KiCad bounds -4.15..11.35 / -16.35..1.85 after PCB translation (+3.6, -6). The corresponding 3D offset is (3.6, 15.35, 4.5). Mounting tabs then align with the installed KiCad footprint. Source footprint pad numbering differs; we retain installed KiCad copper/pad numbering and do not import the source footprint.
- `AMASS_XT30UPB-F.step`: mjbots/power_dist, revision `5936cba4d5ece42328b94f7169f05d28672f154c`, source `hw/mjpower-ss/3d/Amass_XT30UPB-F.step`.
Source: https://github.com/mjbots/power_dist/blob/5936cba4d5ece42328b94f7169f05d28672f154c/hw/mjpower-ss/3d/Amass_XT30UPB-F.step
SHA-256: `c353c9e70ed68feb9858d1a3011776a4fd4335be75869b912661031f090be087`.
The source model is centered between contacts; offset (+2.5, 0, 0) aligns it to KiCad's pad-1 origin. Body width/depth are 10.2 x 5.2 mm, matching the installed F.Fab outline. No arbitrary rescaling is applied.
These models provide component-body visualization. They are not substitutes for native electrical checks, insertion-space checks, mating-part tolerance analysis, or an enclosure fit test. Missing models for other parts are reported explicitly, not replaced with invented shapes.
+59
View File
@@ -0,0 +1,59 @@
{
"Connector_USB:USB_C_Receptacle_HRO_TYPE-C-31-M-12": {
"file": "USB_C_Receptacle_HRO_TYPE-C-31-M-12.STEP",
"sha256": "f902880f83a1b397b76360ed8686b6132a66920b3c1aac8e98239315842ff43e",
"offset": [
0,
0,
0
],
"rotation": [
0,
0,
0
],
"scale": [
1,
1,
1
]
},
"Connector_AMASS:AMASS_XT60PW-M_1x02_P7.20mm_Horizontal": {
"file": "AMASS_XT60PW-M.step",
"sha256": "4275e6105b49a74775c3eb50e679d0736e5a4f2b6ba738f9d29b52eaf1722003",
"offset": [
3.6,
15.35,
4.5
],
"rotation": [
-90,
0,
-180
],
"scale": [
1,
1,
1
]
},
"Connector_AMASS:AMASS_XT30UPB-F_1x02_P5.0mm_Vertical": {
"file": "AMASS_XT30UPB-F.step",
"sha256": "c353c9e70ed68feb9858d1a3011776a4fd4335be75869b912661031f090be087",
"offset": [
2.5,
0,
0
],
"rotation": [
0,
0,
0
],
"scale": [
1,
1,
1
]
}
}
+112
View File
@@ -0,0 +1,112 @@
"""Footprint-specific mating axes and conservative assembly access envelopes.
Clearance reserves below are design assumptions, not manufacturer tolerances.
An electrical DRC does not verify these mechanical constraints.
"""
import math
import re
PROFILES = {
'Connector_USB:USB_C_Receptacle_HRO_TYPE-C-31-M-12': {
'kind': 'side', 'opening': [0, 1], 'mouth': [0, 3.65],
'mouth_outside_mm': 1.15, 'preferred_side': 'top',
'access_width_mm': 12, 'access_depth_mm': 20, 'max_face_inset_mm': .5,
'source': 'HRO drawing and official KiCad footprint',
'drawing': 'http://www.krhro.com/uploads/soft/180320/1-1P320120243.pdf',
},
'Connector_AMASS:AMASS_XT60PW-M_1x02_P7.20mm_Horizontal': {
'kind': 'side', 'opening': [0, -1], 'mouth': [3.6, -16.35],
'mouth_outside_mm': .5, 'preferred_side': 'left',
'access_width_mm': 20, 'access_depth_mm': 25, 'max_face_inset_mm': .5,
'pin_polarity': {'1': 'negative', '2': 'positive'},
'source': 'AMASS XT60PW-M drawing, official KiCad F.Fab datum and mounting pads',
'drawing': 'https://www.tme.eu/Document/b13629717d44ae038681dba08d18c0b6/XT60PW-M.pdf',
},
'Connector_AMASS:AMASS_XT30UPB-F_1x02_P5.0mm_Vertical': {
'kind': 'vertical', 'opening_3d': [0, 0, 1], 'access_margin_mm': 1.0,
'pin_polarity': {'1': 'negative', '2': 'positive'},
'source': 'AMASS XT30UPB-F vertical PCB drawing and official KiCad footprint',
'drawing': 'https://www.tme.eu/Document/81f11ca924696756331f21b972812074/XT30PB-F.pdf',
},
}
NORMALS = {'left': (-1, 0), 'right': (1, 0), 'top': (0, -1), 'bottom': (0, 1)}
def rotate(x, y, angle):
a = math.radians(angle)
return x * math.cos(a) + y * math.sin(a), -x * math.sin(a) + y * math.cos(a)
def box_at(bounds, position):
points = [rotate(x, y, position['rotation']) for x in [bounds[0], bounds[2]] for y in [bounds[1], bounds[3]]]
return [min(x for x, y in points) + position['x'], min(y for x, y in points) + position['y'],
max(x for x, y in points) + position['x'], max(y for x, y in points) + position['y']]
def overlaps(a, b, gap=0):
return not (a[2] + gap <= b[0] or b[2] + gap <= a[0] or a[3] + gap <= b[1] or b[3] + gap <= a[1])
def needs_profile(part):
identity = part['footprint']
connector = part.get('role') == 'connector' or identity.startswith(('Connector_', 'TerminalBlock_'))
return bool(re.search(r'Connector_AMASS:|USB|RJ_?45|AudioJack|BarrelJack', identity, re.I)
or (connector and re.search(r'Horizontal|Right.?Angle', identity, re.I)))
def access(part, position):
profile = PROFILES.get(part['footprint'])
if not profile:
return None
info = {'profile': part['footprint'], 'kind': profile['kind'], 'source': profile['source'],
'drawing': profile['drawing'], 'clearance_is_design_assumption': True}
if profile['kind'] == 'vertical':
b = box_at(part['bounds'], position)
margin = profile['access_margin_mm']
return {**info, 'direction_3d': [0, 0, 1], 'keepout': [b[0] - margin, b[1] - margin, b[2] + margin, b[3] + margin]}
dx, dy = rotate(*profile['opening'], position['rotation'])
mx, my = rotate(*profile['mouth'], position['rotation'])
mx, my = mx + position['x'], my + position['y']
half, length = profile['access_width_mm'] / 2, profile['access_depth_mm']
# Begin slightly behind the mating face, covering plug-shell overlap.
points = [(mx + dx * t - dy * lateral, my + dy * t + dx * lateral)
for t in [-.5, length] for lateral in [-half, half]]
side = max(NORMALS, key=lambda s: dx * NORMALS[s][0] + dy * NORMALS[s][1])
return {**info, 'direction_3d': [dx, dy, 0], 'side': side, 'mouth': [mx, my],
'keepout': [min(x for x, y in points), min(y for x, y in points), max(x for x, y in points), max(y for x, y in points)]}
def audit(parts, board, positions):
issues, connectors = [], {}
bodies = {p['reference']: box_at(p['bounds'], positions[p['reference']]) for p in parts if p['reference'] in positions}
for part in parts:
ref = part['reference']
if ref not in positions:
issues.append(ref + ': missing physical placement')
continue
profile = PROFILES.get(part['footprint'])
if not profile:
if needs_profile(part):
issues.append(ref + ': unsupported connector mating axis/access profile (' + part['footprint'] + ')')
continue
info = access(part, positions[ref])
connectors[ref] = info
if profile['kind'] == 'side':
nx, ny = NORMALS[info['side']]
dx, dy, _ = info['direction_3d']
x, y = info['mouth']
inset = {'left': x, 'right': board['width_mm'] - x, 'top': y, 'bottom': board['height_mm'] - y}[info['side']]
info['face_inset_mm'] = inset
if dx * nx + dy * ny < .999 or inset > profile['max_face_inset_mm']:
issues.append(ref + ': mating face is not at an outward board edge (' + info['side'] + ', inset=' + str(round(inset, 3)) + ' mm)')
blocked = [other for other, body in bodies.items() if other != ref and overlaps(info['keepout'], body, .2)]
info['blocked_by'] = blocked
if blocked:
issues.append(ref + ': mating/plug access is blocked by ' + ', '.join(blocked))
for ref, info in connectors.items():
for other, other_info in connectors.items():
if ref < other and overlaps(info['keepout'], other_info['keepout'], .2):
issues.append(ref + '/' + other + ': plug access envelopes overlap')
return {'passed': not issues, 'issues': issues, 'connectors': connectors,
'scope': 'footprint-specific mating axes, board-edge access and conservative XY plug corridors; no enclosure or full 3D collision certification'}
+14
View File
@@ -30,10 +30,24 @@ Header pin assignments must be explicit. Physical interfaces and the MCU's pin-m
In pin_mux, use canonical function names (USART1_TX, USART1_RX, SPI1_SCK/MISO/MOSI, I2C1_SCL/SDA, SWDIO, SWCLK) and real connector pins, not vague promises. For STM32F103, defaults are USART1 PA9/PA10, SPI1 PA5/PA6/PA7, I2C1 PB6/PB7, SWD PA13/PA14, USB PA11/PA12. Document required remapping if choosing alternatives. Expose the remaining available GPIO without shorting distinct MCU GPIO together. Crystal oscillator GPIO already used by the real crystal need not also be on a header. For four-pad crystals, use Device:Crystal_GND24 with active pads 1/3 and grounded case pads 2/4; Device:Crystal is for a truly matching two-pad footprint.
## Local circuit repair
When the response schema is CIRCUIT_PATCH, return a connection patch, never a replacement circuit. Read repair_context.errors: native ERC entries retain severity/type, exact symbol and pin item descriptions, pin names/electrical types, real component values/IDs and current nets. Compiler-generated power flags are identified separately; they cannot be deleted to hide a conflict. Native netlist mismatch evidence is a compiler/persistence problem, not permission to change intended wiring.
Only repair_context.editable_pins may change. Each change must give the exact pin, current from_net, to_net and an electrical reason. Other assignments, existing net names/kinds, the BOM and values, pin_mux and external_power_nets are locked. The service applies the patch to its own saved baseline; it does not trust a regenerated circuit. Do not borrow another function's resistor, sacrifice an indicator, mark connected pins as NC, remap an unrelated MCU pin or disable any requested interface. Maintain every existing communication/debug pin mapping, including paths through series resistors.
Do not invent a series resistor or split required supply rails merely to avoid an ERC electrical-type conflict. Power-pin reassignment between existing supply nets requires a verified component recipe and is unavailable through a generic patch. If correct repair needs BOM/value changes, a datasheet-verified symbol recipe or missing evidence, report unresolved with specific refs/pins and rationale; never replace this with a guessed workaround or a claim of passing checks.
Patches must reduce known errors without introducing new semantic/ERC errors. A rejected patch is rolled back to the previous saved baseline; inspect last_rejected_patch evidence before proposing the next patch. Newly observable native ERC errors after semantic validation first succeeds are recorded as the next validation stage, not concealed. The automatic attempt budget remains bounded. No instruction permits disabling or relaxing ERC/DRC or delivery gates.
## Layout and routing
The compiler controls placement. Side-insertion ports require an audited footprint-specific opening vector, edge datum and mating corridor. Near an edge does not mean facing outward. For HRO TYPE-C-31-M-12, the supported profile points towards local +Y; at the top edge it must rotate 180 degrees. Do not use a default zero-degree angle for every USB port. Unknown side-insertion geometry remains unverified and blocks manufacturing release.
This applies equally to power connectors. AMASS XT60PW-M is horizontal: its installed footprint opens toward local -Y, not toward its two-pad axis. Placing it on the left edge requires 90 degrees, with the mating face at/outside that edge and an unobstructed plug approach corridor. Its body/courtyard alone is not the plug insertion envelope. AMASS XT30UPB-F is vertical: mating is along +Z above the board, so preserve lateral room for the mating plug instead of pretending its opening points along an XY board edge. Never place any connector or component in another connector's plug access envelope. If the fixed outline cannot accommodate all bodies and access envelopes, stop with a mechanical blocker; do not silently pack them closer or enlarge the fixed outline.
Use the supplied pad_polarity metadata. These supported AMASS footprints mark pad 1 negative and pad 2 positive; generic symbol pin numbering is not a polarity definition. Do not assume pin 1 is VIN+. State missing 3D models as missing; pad/silkscreen-only rendering is not 3D collision verification. Mating-axis/access checks must be recomputed from saved PCB placements and must pass before export and before approval, irrespective of native electrical DRC.
Arrange functional blocks across the board, keep the MCU central and interfaces accessible at edges. Local decouplers and crystal components stay near their target pins. Use actual courtyard/body and pad extents; don't infer connector body size solely from the pad bounding box. Respect insertion space, component clearance and board-edge clearance.
Fixed code defines net widths/clearances and invokes a bounded local router. Signal bends use 45-degree chamfers. Rebuild copper zones, save/reopen and inspect real copper and real 3D geometry. No guessed Manhattan lines, images of airwires, or mere existence of a copper-pour object count as routing/fill completion.
+40 -15
View File
@@ -13,6 +13,16 @@ import urllib.request
from .runtime import KiCadError, write_json
# Every current model role makes a design decision (plan, part selection,
# circuit generation or repair). Keep all of them at the requested max effort.
REASONING_EFFORT = 'max'
MAX_OUTPUT_TOKENS = 327680
class ModelTimeout(KiCadError):
"""A transient request deadline, eligible for the bounded model retry."""
def credentials():
key = os.getenv('DEEPSEEK_API_KEY', '')
endpoint = os.getenv('DEEPSEEK_BASE_URL', 'https://api.deepseek.com')
@@ -40,12 +50,14 @@ class DeepSeek:
self.directory = Path(directory)
self.event = event or (lambda *a: None)
self.cancel = cancel or (lambda: None)
self.timeout = min(240, max(30, int(os.getenv('AI_PCB_MODEL_TIMEOUT', '180'))))
self.timeout = min(7200, max(30, int(os.getenv('AI_PCB_MODEL_TIMEOUT', '1800'))))
self.idle_timeout = min(self.timeout, max(30, int(os.getenv('AI_PCB_MODEL_IDLE_TIMEOUT', '300'))))
def call(self, role, payload, schema, *, images=(), retry=1):
from jsonschema import Draft202012Validator, ValidationError
guidance = Path(__file__).with_name('guidance.md').read_text()
fingerprint = hashlib.sha256(json.dumps([role, payload, schema, guidance], sort_keys=True, ensure_ascii=False).encode()).hexdigest()
generation = {'reasoning': {'effort': REASONING_EFFORT}, 'max_output_tokens': MAX_OUTPUT_TOKENS}
fingerprint = hashlib.sha256(json.dumps([role, payload, schema, guidance, generation], sort_keys=True, ensure_ascii=False).encode()).hexdigest()
directory = self.directory / (role + '-' + fingerprint[:12])
response = directory / 'response.json'
validator = Draft202012Validator(schema)
@@ -64,24 +76,25 @@ class DeepSeek:
mime = 'image/png' if path.suffix.lower() == '.png' else 'image/webp' if path.suffix.lower() == '.webp' else 'image/jpeg'
content.append({'type': 'input_image', 'image_url': 'data:' + mime + ';base64,' + base64.b64encode(path.read_bytes()).decode(), 'detail': 'low'})
body = {'model': model, 'instructions': guidance + '\nCurrent role: ' + role + '. Return only JSON matching the response schema.',
'input': [{'role': 'user', 'content': content}], 'reasoning': {'effort': 'low' if role.startswith('circuit') else 'none'},
'max_output_tokens': 18000 if role.startswith('circuit') else 12000,
'input': [{'role': 'user', 'content': content}], **generation,
'text': {'format': {'type': 'json_schema', 'name': role.replace('-', '_'), 'schema': schema, 'strict': True}}, 'stream': True}
write_json(directory / 'input.json', {'role': role, 'payload': payload, 'schema': schema, 'fingerprint': fingerprint})
write_json(directory / 'input.json', {'role': role, 'payload': payload, 'schema': schema, 'fingerprint': fingerprint, **generation})
started = time.monotonic()
self.event('agent.started', {'role': role, 'model': model})
self.event('agent.started', {'role': role, 'model': model, 'reasoning_effort': REASONING_EFFORT,
'attempt_timeout_seconds': self.timeout, 'max_attempts': retry + 1})
for attempt in range(retry + 1):
self.cancel()
attempt_started = time.monotonic()
try:
request = urllib.request.Request(endpoint + '/responses', data=json.dumps(body, ensure_ascii=False).encode(),
headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json', 'Accept': 'text/event-stream'})
output = None
with urllib.request.urlopen(request, timeout=max(1, self.timeout - (time.monotonic() - started))) as stream:
with urllib.request.urlopen(request, timeout=self.idle_timeout) as stream:
last = time.monotonic()
for line in stream:
self.cancel()
if time.monotonic() - started > self.timeout:
raise KiCadError('DeepSeek exceeded its total call deadline')
if time.monotonic() - attempt_started > self.timeout:
raise ModelTimeout('DeepSeek model attempt deadline reached')
if time.monotonic() - last >= 10:
self.event('agent.progress', {'role': role, 'seconds': round(time.monotonic() - started)})
last = time.monotonic()
@@ -93,6 +106,7 @@ class DeepSeek:
data = json.loads(raw)
if data.get('type') in {'response.completed', 'response.incomplete', 'response.failed'}:
output = data.get('response')
break
if not output or output.get('status') != 'completed':
write_json(directory / 'failure.json', {'status': (output or {}).get('status'),
'incomplete_details': (output or {}).get('incomplete_details'),
@@ -104,17 +118,21 @@ class DeepSeek:
defaulted = []
if role.startswith('circuit') and isinstance(value, dict):
for optional_array in ['unconnected', 'external_power_nets', 'findings', 'pin_mux']:
if optional_array not in value:
if optional_array in schema.get('properties', {}) and optional_array not in value:
value[optional_array] = []
defaulted.append(optional_array)
validator.validate(value)
write_json(response, value)
metrics = {'model': model, 'seconds': round(time.monotonic() - started, 2), 'usage': output.get('usage'),
metrics = {'model': model, 'reasoning_effort': REASONING_EFFORT, 'max_output_tokens': MAX_OUTPUT_TOKENS,
'attempt_timeout_seconds': self.timeout, 'idle_timeout_seconds': self.idle_timeout,
'seconds': round(time.monotonic() - started, 2), 'usage': output.get('usage'),
'request_chars': len(text), 'attempts': attempt + 1, 'response_id': output.get('id'), 'defaulted_empty_arrays': defaulted}
write_json(directory / 'metrics.json', metrics)
self.event('agent.completed', {'role': role, **metrics})
return value
except urllib.error.HTTPError as exc:
write_json(directory / f'attempt-{attempt + 1}-failure.json',
{'type': 'http', 'http_status': exc.code, 'seconds': round(time.monotonic() - attempt_started, 2)})
if exc.code not in {408, 429, 500, 502, 503, 504} or attempt == retry:
raise KiCadError(f'DeepSeek request failed (HTTP {exc.code})') from None
except ValidationError as exc:
@@ -124,11 +142,18 @@ class DeepSeek:
raise KiCadError('模型的结构化数据未通过检查:' + compact) from None
body['input'].append({'role': 'assistant', 'content': [{'type': 'output_text', 'text': answer}]})
body['input'].append({'role': 'user', 'content': 'Correct the previous JSON to exactly match the required schema. Error: ' + compact})
except (urllib.error.URLError, socket.timeout, TimeoutError, json.JSONDecodeError) as exc:
except (ModelTimeout, urllib.error.URLError, socket.timeout, TimeoutError, json.JSONDecodeError) as exc:
timed_out = isinstance(exc, (ModelTimeout, TimeoutError)) or isinstance(getattr(exc, 'reason', None), TimeoutError)
write_json(directory / f'attempt-{attempt + 1}-failure.json',
{'type': type(exc).__name__, 'timed_out': timed_out,
'attempt_timeout_seconds': self.timeout, 'idle_timeout_seconds': self.idle_timeout,
'seconds': round(time.monotonic() - attempt_started, 2)})
if attempt == retry:
if timed_out:
raise KiCadError(f'DeepSeek 请求在 {retry + 1} 次尝试后仍超时;每次最长 {self.timeout} 秒,已保留执行记录') from None
raise KiCadError('DeepSeek connection or structured response failed: ' + type(exc).__name__) from None
if time.monotonic() - started >= self.timeout:
raise KiCadError('DeepSeek call deadline reached')
self.event('agent.retry', {'role': role, 'attempt': attempt + 2})
self.cancel()
self.event('agent.retry', {'role': role, 'attempt': attempt + 2, 'max_attempts': retry + 1,
'attempt_timeout_seconds': self.timeout, 'message': '当前请求未完成,正在自动重试'})
time.sleep(1)
raise KiCadError('DeepSeek call exhausted retries')
+71
View File
@@ -0,0 +1,71 @@
"""Resolve real component models and make the native project self-contained."""
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
from .runtime import KiCadError
ASSETS = Path(__file__).resolve().parents[1] / 'assets/3dmodels'
def resolve(path, directory):
path = str(path).replace('${KIPRJMOD}', str(directory))
path = re.sub(r'\$\{KICAD\d+_3DMODEL_DIR\}', os.getenv('KICAD_3DMODEL_DIR', '/usr/share/kicad/3dmodels'), path)
path = re.sub(r':KICAD\d+_3DMODEL_DIR:', os.getenv('KICAD_3DMODEL_DIR', '/usr/share/kicad/3dmodels') + '/', path)
result = Path(os.path.expandvars(path)).expanduser()
return result if result.is_absolute() else directory / result
def package(fp, identity, directory):
"""Rewrite only model paths/transforms; never change pads or mechanics."""
directory = Path(directory)
fallback = json.loads((ASSETS / 'manifest.json').read_text()).get(identity)
models = fp.Models()
report = {'reference': fp.GetReference(), 'footprint': identity, 'files': [], 'missing': [], 'rewritten': False}
for index, model in enumerate(models):
original = model.m_Filename
source = resolve(original, directory)
use_fallback = not source.is_file() and fallback is not None
if use_fallback:
source = ASSETS / fallback['file']
if not source.is_file() or hashlib.sha256(source.read_bytes()).hexdigest() != fallback['sha256']:
raise KiCadError('Bundled 3D model checksum differs: ' + identity)
# SWIG vector elements are copies: assign them back below.
model.m_Offset.x, model.m_Offset.y, model.m_Offset.z = fallback['offset']
model.m_Rotation.x, model.m_Rotation.y, model.m_Rotation.z = fallback['rotation']
model.m_Scale.x, model.m_Scale.y, model.m_Scale.z = fallback['scale']
model.m_Show = True
if not source.is_file():
report['missing'].append(original)
continue
content = source.read_bytes()
digest = hashlib.sha256(content).hexdigest()
suffix = '-' + digest[:12]
filename = source.stem + ('' if source.stem.endswith(suffix) else suffix) + source.suffix
target = directory / 'models' / filename
target.parent.mkdir(parents=True, exist_ok=True)
if not target.exists():
target.write_bytes(content)
model.m_Filename = '${KIPRJMOD}/models/' + filename
report['rewritten'] |= model.m_Filename != original or use_fallback
models[index] = model
report['files'].append({'path': 'models/' + filename, 'sha256': digest, 'bundled_fallback': use_fallback})
if use_fallback:
for notice in ASSETS.iterdir():
if notice.name.startswith('LICENSE') or notice.name == 'MODEL-SOURCES.md':
shutil.copy2(notice, directory / 'models' / notice.name)
if not len(models):
report['missing'].append('Footprint has no 3D model reference')
report['available'] = bool(report['files'])
return report
def summarize(reports):
missing = [r['reference'] for r in reports if not r['available']]
return {'parts': reports, 'total_parts': len(reports), 'parts_with_models': len(reports) - len(missing),
'missing_parts': missing, 'complete': not missing,
'warnings': ['三维预览缺少器件本体:' + ', '.join(missing)] if missing else []}
+16 -29
View File
@@ -4,32 +4,18 @@ import json
import math
from pathlib import Path
import re
import hashlib
import shutil
import xml.etree.ElementTree as ET
from .libraries import Libraries
from .placement import place, intersects, rotate
from .pcb_probe import inspect_board
from .connector_rules import PROFILES
from .models import package as package_models, summarize as summarize_models
from .pcb_probe import inspect_board, mechanical_report
from .runtime import KiCadError, write_json
from .schematic import identity
from .sexpr import parse, dump, child, children, Quoted
HRO = 'Connector_USB:USB_C_Receptacle_HRO_TYPE-C-31-M-12'
def supported_model(fp, footprint):
if footprint != HRO:
return False
models = fp.Models()
for index, model in enumerate(models):
if 'USB_C_Receptacle_HRO_TYPE-C-31-M-12' in model.m_Filename:
model.m_Filename = '${KIPRJMOD}/models/USB_C_Receptacle_HRO_TYPE-C-31-M-12.STEP'
models[index] = model
return True
return False
def native_box(box):
import pcbnew as p
@@ -78,6 +64,7 @@ def footprint_geometry(parts, libraries, pin_nets=None):
raise KiCadError(part['reference'] + ' symbol/footprint pin sets differ: missing=' + str(sorted(expected - numbered)) + ',extra=' + str(sorted(numbered - expected)))
result.append({**{k: part[k] for k in ['reference', 'footprint', 'role', 'near', 'group', 'value']},
'pads': pads, 'bounds': box_for(fp),
'pad_polarity': PROFILES.get(part['footprint'], {}).get('pin_polarity', {}),
'pad_bounds': union([native_box(pad.GetBoundingBox()) for pad in fp.Pads()]),
'nets': sorted({pad['net'] for pad in pads if pad['net']})})
footprints[part['reference']] = fp
@@ -105,6 +92,7 @@ def build(data, directory, attempt):
settings.m_HoleClearance = p.FromMM(.25)
nets = {}
clipped = {}
model_reports = []
for name in sorted(set(pin_nets.values())):
item = p.NETINFO_ITEM(board, name)
board.Add(item)
@@ -112,12 +100,9 @@ def build(data, directory, attempt):
for part in parts:
ref = part['reference']
fp, pos = footprints[ref], layout['positions'][ref]
if supported_model(fp, part['footprint']):
assets = Path(__file__).resolve().parents[1] / 'assets/3dmodels'
model = assets / 'USB_C_Receptacle_HRO_TYPE-C-31-M-12.STEP'
if hashlib.sha256(model.read_bytes()).hexdigest() != 'f902880f83a1b397b76360ed8686b6132a66920b3c1aac8e98239315842ff43e':
raise KiCadError('Bundled USB-C mechanical model checksum differs')
shutil.copytree(assets, directory / 'models', dirs_exist_ok=True)
model_report = package_models(fp, part['footprint'], directory)
model_reports.append(model_report)
if model_report['rewritten']:
clipped.setdefault(part['footprint'], {})
path = p.KIID_PATH()
path.push_back(p.KIID(identity(task, 'sheet')))
@@ -172,14 +157,14 @@ def build(data, directory, attempt):
silk['project_library_variants'] = local_variants(directory, parts, footprints, clipped, libraries)
pcb = directory / (data['name'] + '.kicad_pcb')
p.SaveBoard(str(pcb), board)
return {'passed': True, 'layout': layout, 'silkscreen': silk, 'board': inspect_board(board)}
return {'passed': True, 'layout': layout, 'silkscreen': silk, 'model_coverage': summarize_models(model_reports), 'board': inspect_board(board)}
def local_variants(directory, parts, footprints, clipped, libraries):
"""Make intentional silk changes an explicit, checked project library copy.
No pad, body or drill geometry is changed. The missing HRO model gets a
documented project-local STEP reference. Native library comparison
No pad, body or drill geometry is changed. Component models get
documented project-local references. Native library comparison
remains enabled and checks the board against the supplied local variant.
"""
import pcbnew as p
@@ -203,7 +188,7 @@ def local_variants(directory, parts, footprints, clipped, libraries):
saved.add(identity_fp)
copy = p.FootprintLoad(str(libraries.footprint_path(identity_fp).parent), name)
copy.SetFPIDAsString(identity_fp)
model_changed = supported_model(copy, identity_fp)
model_changed = package_models(copy, identity_fp, directory)['rewritten']
for index, item in enumerate(copy.GraphicalItems()):
if index in changes:
item.SetLayer(changes[index])
@@ -214,7 +199,7 @@ def local_variants(directory, parts, footprints, clipped, libraries):
raise KiCadError('Project-local footprint variant was not saved')
report.append({'footprint': identity_fp, 'base_sha256': part['footprint_sha256'],
'changed_graphics': len(changes), 'bundled_model': model_changed,
'reason': 'outboard silk moved to fabrication layer; missing HRO model resolved to attributed demo STEP; copper/drills preserved'})
'reason': 'outboard silk moved to fabrication layer; component models packaged with source notices; copper/drills preserved'})
table_path = directory / 'fp-lib-table'
table = parse(table_path.read_text())
for entry in children(table, 'lib'):
@@ -350,7 +335,7 @@ def chamfer_signals(board, power_nets):
def main():
import pcbnew as p
parser = argparse.ArgumentParser()
parser.add_argument('action', choices=['footprints', 'build', 'dsn', 'import', 'audit'])
parser.add_argument('action', choices=['footprints', 'build', 'dsn', 'import', 'audit', 'mechanical'])
parser.add_argument('--data')
parser.add_argument('--directory')
parser.add_argument('--board')
@@ -384,6 +369,8 @@ def main():
repairs = chamfer_signals(board, power_nets)
p.SaveBoard(args.output, board)
result = {'passed': True, 'tracks': len(board.GetTracks()), 'corner_repairs': repairs, 'angles': angle_audit(board, power_nets)}
elif args.action == 'mechanical':
result = mechanical_report(p.LoadBoard(args.board))
else:
board = p.LoadBoard(args.board)
result = {'angles': angle_audit(board, power_nets), 'board': inspect_board(board)}
+44
View File
@@ -6,6 +6,49 @@ worker's validation contract. This script never saves the input board.
"""
import json
import sys
import os
from pathlib import Path
if not __package__:
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
def mechanical_report(board):
import pcbnew as p
from kicad_backend.connector_rules import audit
edge = board.GetBoardEdgesBoundingBox()
origin_x, origin_y = p.ToMM(edge.GetLeft()), p.ToMM(edge.GetTop())
parts, positions, missing_models = [], {}, []
for fp in board.GetFootprints():
clone = p.FOOTPRINT(fp)
clone.SetOrientationDegrees(0)
clone.SetPosition(p.VECTOR2I(0, 0))
boxes = []
for layer in [p.F_CrtYd, p.F_Fab]:
boxes = [item.GetBoundingBox() for item in clone.GraphicalItems() if item.GetLayer() == layer]
if boxes:
break
if not boxes:
boxes = [clone.GetBoundingBox(False, False)]
bounds = [p.ToMM(min(b.GetLeft() for b in boxes)), p.ToMM(min(b.GetTop() for b in boxes)),
p.ToMM(max(b.GetRight() for b in boxes)), p.ToMM(max(b.GetBottom() for b in boxes))]
ref = fp.GetReference()
identity = fp.GetFPID().GetUniStringLibId()
parts.append({'reference': ref, 'footprint': identity, 'bounds': bounds})
if identity.startswith('Connector_'):
paths = []
for model in fp.Models():
path = model.m_Filename.replace('${KIPRJMOD}', str(Path(board.GetFileName()).parent))
path = path.replace('${KICAD10_3DMODEL_DIR}', os.getenv('KICAD_3DMODEL_DIR', '/usr/share/kicad/3dmodels'))
paths.append(Path(os.path.expandvars(path)).is_file())
if not paths or not any(paths):
missing_models.append(ref)
positions[ref] = {'x': p.ToMM(fp.GetPosition().x) - origin_x, 'y': p.ToMM(fp.GetPosition().y) - origin_y,
'rotation': fp.GetOrientationDegrees()}
report = audit(parts, {'width_mm': p.ToMM(edge.GetWidth()), 'height_mm': p.ToMM(edge.GetHeight())}, positions)
report['missing_connector_3d_models'] = missing_models
report['preview_note'] = 'Missing connector bodies in 3D preview: ' + ', '.join(missing_models) if missing_models else ''
return report
def inspect_board(board):
@@ -48,6 +91,7 @@ def inspect_board(board):
for t in board.GetTracks()]),
"outline_valid": outline_valid,
"size_mm": [pcbnew.ToMM(box.GetWidth()), pcbnew.ToMM(box.GetHeight())],
"mechanical": mechanical_report(board),
}
return data
+82 -36
View File
@@ -13,6 +13,7 @@ from .runtime import KiCadError, KiCadRuntime, write_json, parse_check
from .routing import route
from .schematic import generate, project_file
from .pinout import optimize as optimize_pinout
from .repair import diagnostics, context as repair_context, apply_patch as apply_circuit_patch, error_keys
class Designer:
@@ -45,54 +46,73 @@ class Designer:
aliases.setdefault((round(pad['x'], 5), round(pad['y'], 5)), []).append(pad['number'])
actual.append({k: part[k] for k in ['reference', 'lib_id', 'value', 'footprint', 'role', 'group', 'near']})
actual[-1].update(pins=[{**{k: pin[k] for k in ['number', 'name', 'type']}, 'pin_id': part['reference'] + '.' + pin['number']} for pin in part['metadata']['pins']],
pad_polarity=native.get('pad_polarity', {}),
coincident_pad_groups=[v for v in aliases.values() if len(v) > 1],
datasheet=part['metadata']['datasheet'])
contract = {key: value for key, value in plan.items() if key not in {'components', 'questions'}}
payload = {'description': description, 'plan': contract, 'actual_parts': actual,
'instruction': 'Define a complete reference circuit using these actual pins. Copy exact pin_id strings such as U1.1 and J1.A6; reference-pin with a hyphen is INVALID. Each pin exactly once: a real net or intentional no-connect with reason. Net names ASCII, no slash prefix. List external supply nets for power flags. GPIO headers must really connect MCU pins; use no-connect only for spare contacts. Provide pin_mux entries documenting actual MCU/connector pin functions. No executable code. Select correct peripheral and voltage/enable/crystal circuitry.'}
previous, issues = None, []
baseline, records, issues, rejected = None, [], [], []
rejected_evidence = None
source = None
circuit = None
verified = False
for attempt in range(3):
self.cancel()
request = {**payload, **({'previous_circuit': previous, 'errors_to_correct': issues} if previous is not None else {})}
circuit = self.agent.call('circuit' if attempt == 0 else 'circuit-repair-' + str(attempt), request, schemas.CIRCUIT)
circuit = optimize_pinout(circuit, parts, geometry, plan, description)
semantic = validate_circuit(parts, circuit, plan)
issues = semantic['issues'][:50]
if issues:
self.event('schematic.repair', {'attempt': attempt + 1, 'issues': issues[:10]})
previous = circuit
continue
source = self.directory / ('schematic-' + str(attempt))
source.mkdir(exist_ok=True)
project_file(source, self.task, parts, self.libraries, plan['board'], plan['routing'])
layout = generate(source, self.task, self.task, parts, circuit, self.libraries)
write_json(source / 'schematic-layout.json', layout)
erc_file = source / 'erc.json'
erc = self.runtime.run([self.runtime.cli, 'sch', 'erc', '--format', 'json', '--severity-all', '--exit-code-violations',
'--output', erc_file, source / (self.task + '.kicad_sch')], log=source / 'erc-command.json', allowed=(0, 5))
native = parse_check(json.loads(erc_file.read_text()), 'erc', erc['exit_code'])
self.runtime.run([self.runtime.cli, 'sch', 'export', 'netlist', '--format', 'kicadxml', '--output', source / 'schematic.xml',
source / (self.task + '.kicad_sch')], log=source / 'netlist-command.json')
netlist = ET.parse(source / 'schematic.xml').getroot()
pin_nets = {(node.get('ref'), node.get('pin')): net.get('name') for net in netlist.findall('./nets/net') for node in net.findall('node')}
for net in circuit['nets']:
for pin in net['pins']:
ref, number = pin.split('.', 1)
if pin_nets.get((ref, number)) != '/' + net['name']:
issues.append('Native schematic net differs from intended circuit: ' + pin)
issues += [str(v.get('description', v.get('type'))) for v in native.get('violations', [])][:30]
if not native['passed'] or issues:
if not native['passed'] and not native.get('violations'):
issues.append('Native ERC result is unverified')
self.event('schematic.repair', {'attempt': attempt + 1, 'issues': issues[:10]})
previous = circuit
patch = None
if baseline is None:
circuit = self.agent.call('circuit', payload, schemas.CIRCUIT)
# Freeze the chosen GPIO map before repairs; never re-permute healthy pins.
circuit = optimize_pinout(circuit, parts, geometry, plan, description)
else:
scope = repair_context(parts, baseline, records, rejected, rejected_evidence)
write_json(self.directory / f'repair-{attempt}-context.json', scope)
if not scope['editable_pins']:
issues.append('检查未定位到可安全修改的真实引脚;保留电路,不以改线掩盖编译器或缺件问题')
break
request = {**payload, 'instruction': 'Return only a minimal CIRCUIT_PATCH for repair_context.editable_pins. Do not regenerate the circuit. Follow every repair policy. If a functional, electrically justified repair is unavailable, report unresolved rather than changing unrelated components or hiding errors.',
'previous_circuit': baseline, 'repair_context': scope}
patch = self.agent.call('circuit-repair-' + str(attempt), request, schemas.CIRCUIT_PATCH)
try:
circuit = apply_circuit_patch(parts, baseline, patch, set(scope['editable_pins']))
except KiCadError as exc:
rejected = [str(exc)]
rejected_evidence = {'patch': patch, 'guard_errors': rejected}
write_json(self.directory / f'repair-{attempt}-decision.json', {'accepted': False, 'patch': patch, 'reasons': rejected})
self.event('schematic.repair_rejected', {'attempt': attempt, 'issues': rejected, 'message': '局部修复未满足功能保护规则,已保留上一版电路'})
if patch['unresolved']:
break
continue
candidate_records, candidate_source, semantic = self.check_circuit(parts, plan, circuit, attempt)
if baseline is not None:
added = error_keys(candidate_records) - error_keys(records)
# Native ERC is first observable only after semantic validation passes.
# Newly discovered native evidence is a stage advance, not a known regression.
stage_advanced = (any(r['source'] == 'semantic' for r in records) and
not any(r['source'] == 'semantic' for r in candidate_records))
progress = stage_advanced or len(error_keys(candidate_records)) < len(error_keys(records))
if (added and not stage_advanced) or not progress:
rejected = ['修复引入新错误' if added else '修复未减少既有错误']
rejected_evidence = {'patch': patch, 'candidate_errors': candidate_records}
write_json(self.directory / f'repair-{attempt}-decision.json',
{'accepted': False, 'patch': patch, 'reasons': rejected, 'candidate_errors': candidate_records})
self.event('schematic.repair_rejected', {'attempt': attempt, 'issues': rejected, 'message': '修复未收敛,已拒绝新错误并保留上一版电路'})
continue
write_json(self.directory / f'repair-{attempt}-decision.json', {'accepted': True, 'patch': patch, 'remaining_errors': candidate_records})
baseline = copy.deepcopy(circuit)
records, rejected = candidate_records, []
rejected_evidence = None
issues = [record['description'] for record in records]
write_json(self.directory / 'repair-baseline.json', {'circuit': baseline, 'errors': records})
if records:
self.event('schematic.repair', {'attempt': attempt + 1, 'issues': issues[:10], 'errors': records[:10]})
continue
source, verified = candidate_source, True
self.event('schematic.wiring_verified', {'components': len(parts), 'pins': semantic['pins'], 'nets': semantic['nets']})
break
else:
write_json(self.directory / 'circuit-failure.json', {'issues': issues, 'circuit': circuit})
if not verified:
issues += rejected
write_json(self.directory / 'circuit-failure.json', {'issues': issues, 'errors': records, 'circuit': baseline, 'last_patch_rejection': rejected})
raise KiCadError('原理图在自动修复预算内未通过:' + '; '.join(issues[:5]))
data['circuit'] = circuit
write_json(self.directory / 'design-data.json', data)
@@ -132,6 +152,7 @@ class Designer:
result['semantic'] = semantic
result['layout'] = built['layout']
result['silkscreen'] = built['silkscreen']
result['model_coverage'] = built['model_coverage']
result['routing'] = routing
if not routing.get('angles', {}).get('passed'):
result['manufacturing_blockers'].append('Signal routing angle or route execution requires correction')
@@ -152,3 +173,28 @@ class Designer:
_, path, result, selected_data = min(candidates, key=lambda c: c[0])
write_json(self.directory / 'selected-result.json', {'directory': str(path), 'quality': result, 'design': selected_data})
return path, result, selected_data
def check_circuit(self, parts, plan, circuit, attempt):
"""Read native ERC evidence without reducing it to generic descriptions."""
semantic = validate_circuit(parts, circuit, plan)
if semantic['issues']:
return diagnostics(parts, circuit, semantic=semantic['issues']), None, semantic
source = self.directory / ('schematic-' + str(attempt))
source.mkdir(exist_ok=True)
project_file(source, self.task, parts, self.libraries, plan['board'], plan['routing'])
layout = generate(source, self.task, self.task, parts, circuit, self.libraries)
write_json(source / 'schematic-layout.json', layout)
erc_file = source / 'erc.json'
erc = self.runtime.run([self.runtime.cli, 'sch', 'erc', '--format', 'json', '--severity-all', '--exit-code-violations',
'--output', erc_file, source / (self.task + '.kicad_sch')], log=source / 'erc-command.json', allowed=(0, 5))
native = parse_check(json.loads(erc_file.read_text()), 'erc', erc['exit_code'])
self.runtime.run([self.runtime.cli, 'sch', 'export', 'netlist', '--format', 'kicadxml', '--output', source / 'schematic.xml',
source / (self.task + '.kicad_sch')], log=source / 'netlist-command.json')
netlist = ET.parse(source / 'schematic.xml').getroot()
pin_nets = {(node.get('ref'), node.get('pin')): net.get('name') for net in netlist.findall('./nets/net') for node in net.findall('node')}
parity = [{'pin': pin, 'expected_net': net['name'], 'actual_net': pin_nets.get(tuple(pin.split('.', 1)))}
for net in circuit['nets'] for pin in net['pins'] if pin_nets.get(tuple(pin.split('.', 1))) != '/' + net['name']]
errors = diagnostics(parts, circuit, violations=native.get('violations', []), parity=parity)
if not native['passed'] and not native.get('violations'):
errors += diagnostics(parts, circuit, semantic=['Native ERC result is unverified'])
return errors, source, semantic
+50 -30
View File
@@ -1,16 +1,10 @@
"""Deterministic placement from real courtyard/pad geometry, in millimetres."""
import math
import re
from .connector_rules import PROFILES, NORMALS, access, audit
# This profile is specific to the installed official footprint and its drawing.
# The mating direction is +Y in the unrotated footprint; pads are behind it.
PORTS = {'Connector_USB:USB_C_Receptacle_HRO_TYPE-C-31-M-12': {
'opening': [0, 1], 'edge_origin_inset_mm': 2.5, 'opening_offset_mm': 3.65,
'source': 'HRO TYPE-C-31-M-12 drawing and official KiCad footprint/3D model',
'drawing': 'http://www.krhro.com/uploads/soft/180320/1-1P320120243.pdf',
'assembly_access_reserve_mm': [12, 20], 'reserve_is_design_assumption': True,
}}
PORTS = {name: profile for name, profile in PROFILES.items() if profile['kind'] == 'side'}
def rotate(x, y, degrees):
@@ -65,8 +59,19 @@ def place(parts, board, attempt=0):
return None
if any(intersects(rect, q, gap) for q in occupied):
return None
return {'reference': p['reference'], 'x': ox, 'y': oy, 'cx': cx, 'cy': cy,
'rotation': angle, 'bounds': rect, 'side': side}
pos = {'reference': p['reference'], 'x': ox, 'y': oy, 'cx': cx, 'cy': cy,
'rotation': angle, 'bounds': rect, 'side': side}
envelope = access(p, pos)
for previous in positions.values():
reserved = previous.get('access')
if reserved and intersects(rect, reserved['keepout'], .2):
return None
if envelope and (intersects(envelope['keepout'], previous['bounds'], .2)
or (reserved and intersects(envelope['keepout'], reserved['keepout'], .2))):
return None
if envelope:
pos['access'] = envelope
return pos
def record(p, position):
positions[p['reference']] = position
@@ -75,29 +80,37 @@ def place(parts, board, attempt=0):
# Put audited side-insertion ports on the edge with the actual opening out.
ports = [p for p in parts if p['footprint'] in PORTS]
for index, p in enumerate(ports):
side = ['top', 'bottom', 'right', 'left'][index % 4]
angle = {'top': 180, 'bottom': 0, 'right': 90, 'left': 270}[side]
profile = PORTS[p['footprint']]
r = rotated_box(p['bounds'], angle)
# Translate footprint origin to the audited edge datum, not bbox centre.
inset = profile['edge_origin_inset_mm']
ox, oy = (width / 2, inset) if side == 'top' else (width / 2, height - inset) if side == 'bottom' else (width - inset, height / 2) if side == 'right' else (inset, height / 2)
cx, cy = ox + (r[0] + r[2]) / 2, oy + (r[1] + r[3]) / 2
pos = fits(p, cx, cy, angle, side)
if not pos:
issues.append(p['reference'] + ' cannot fit its audited connector edge datum')
candidates = []
preferred = profile['preferred_side']
for side in [preferred, *[s for s in NORMALS if s != preferred]]:
nx, ny = NORMALS[side]
for angle in [0, 90, 180, 270]:
dx, dy = rotate(*profile['opening'], angle)
if dx * nx + dy * ny < .999:
continue
r = rotated_box(p['bounds'], angle)
mx, my = rotate(*profile['mouth'], angle)
outside = profile['mouth_outside_mm']
for t in [.5, .25, .75, .15, .85]:
target = (-outside, height * t) if side == 'left' else (width + outside, height * t) if side == 'right' else (width * t, -outside) if side == 'top' else (width * t, height + outside)
ox, oy = target[0] - mx, target[1] - my
cx, cy = ox + (r[0] + r[2]) / 2, oy + (r[1] + r[3]) / 2
pos = fits(p, cx, cy, angle, side)
if pos:
pos['opening_direction'] = [dx, dy]
pos['opening_dot_outward'] = dx * nx + dy * ny
pos['mechanical_profile'] = profile
score = (0 if side == preferred else 30) + abs(t - .5) * 10
candidates.append((score, side, t, angle, pos))
if not candidates:
issues.append(p['reference'] + ' cannot fit its mating face and unobstructed insertion corridor')
continue
direction = rotate(*profile['opening'], angle)
normal = {'top': (0, -1), 'bottom': (0, 1), 'left': (-1, 0), 'right': (1, 0)}[side]
pos['opening_direction'] = list(direction)
pos['opening_dot_outward'] = sum(a * b for a, b in zip(direction, normal))
pos['mechanical_profile'] = profile
if pos['opening_dot_outward'] < .99:
issues.append(p['reference'] + ' connector faces into the board')
record(p, pos)
record(p, min(candidates, key=lambda x: x[:4])[4])
headers = [p for p in parts if p['role'] == 'connector' and p not in ports]
gpio_index = 0
vertical_power_index = 0
for index, p in enumerate(headers):
if re.search(r'USB|RJ45|RJ_?45|AudioJack|BarrelJack', p['footprint'], re.I):
issues.append(p['reference'] + ' needs a footprint-specific mating orientation profile')
@@ -106,6 +119,11 @@ def place(parts, board, attempt=0):
preferred = 'bottom' if is_debug else ['left', 'right'][gpio_index % 2] if is_gpio else ['left', 'right', 'bottom', 'top'][index % 4]
if is_gpio:
gpio_index += 1
target_t = .5
if PROFILES.get(p['footprint'], {}).get('kind') == 'vertical':
preferred = ['top', 'bottom'][vertical_power_index % 2]
target_t = [.25, .75][(vertical_power_index // 2) % 2]
vertical_power_index += 1
candidates = []
for side in ['left', 'right', 'bottom', 'top']:
for angle in [0, 90, 180, 270]:
@@ -118,7 +136,7 @@ def place(parts, board, attempt=0):
pos = fits(p, cx, cy, angle)
if pos:
pos['side'] = side
score = (0 if side == preferred else 30) + abs(t - .5) * 10 + (0 if ((h >= w) == vertical) else 8) + angle * .0001
score = (0 if side == preferred else 30) + abs(t - target_t) * 10 + (0 if ((h >= w) == vertical) else 8) + angle * .0001
candidates.append((score, cx, cy, angle, pos))
if not candidates:
issues.append(p['reference'] + ' cannot fit at an accessible board edge')
@@ -182,6 +200,8 @@ def place(parts, board, attempt=0):
record(p, min(candidates, key=lambda x: x[:4])[4])
else:
issues.append(p['reference'] + ' does not fit within the specified outline/courtyard margins')
return {'passed': not issues and len(positions) == len(parts), 'issues': issues,
mechanical = audit(parts, board, positions)
issues += mechanical['issues']
return {'passed': not issues and len(positions) == len(parts), 'issues': issues, 'mechanical': mechanical,
'positions': positions, 'board': board, 'courtyard_gap_mm': gap,
'scope': 'actual courtyard/body and pad bounds, connector opening profile, functional grouping; not SI/thermal signoff'}
+173
View File
@@ -0,0 +1,173 @@
"""Scoped circuit patches and native error evidence; no whole-circuit repairs."""
import copy
import json
import re
from .runtime import KiCadError
def pin_table(parts):
return {part['reference'] + '.' + pin['number']: {
'pin_id': part['reference'] + '.' + pin['number'], 'reference': part['reference'],
'number': pin['number'], 'name': pin['name'], 'electrical_type': pin['type'],
'lib_id': part['lib_id'], 'value': part['value'], 'group': part['group'],
} for part in parts for pin in part['metadata']['pins']}
def assignments(circuit):
return {pin: net['name'] for net in circuit['nets'] for pin in net['pins']}
def diagnostics(parts, circuit, semantic=(), violations=(), parity=()):
"""Retain actual ERC item descriptions and identify exact editable pins."""
table, nets = pin_table(parts), assignments(circuit)
by_ref = {part['reference']: part for part in parts}
records = []
for message in semantic:
pins = set(re.findall(r'\b[A-Z][A-Z0-9_]*\d+\.[A-Za-z0-9]+\b', message)) & table.keys()
refs = set(re.findall(r'\b[A-Z][A-Z0-9_]*\d+\b', message)) & by_ref.keys()
if not pins:
for ref in refs:
candidates = [pid for pid, item in table.items() if item['reference'] == ref]
named = [pid for pid in candidates if table[pid]['name'] and
re.search(r'(?<!\w)' + re.escape(table[pid]['name']) + r'(?!\w)', message)]
if 'enable' in message.lower():
named = [pid for pid in candidates if table[pid]['name'].upper() in {'EN', 'ENABLE'}]
pad = re.search(r'\bpad\s+([A-Za-z0-9]+)\b', message)
if pad and ref + '.' + pad[1] in table:
named.append(ref + '.' + pad[1])
# A component reference alone is not permission to rewire its MCU/peripheral.
# The explicit whole-component disconnected fault is the sole exception.
pins.update(candidates if 'Component is entirely unconnected:' in message else named)
if not pins and 'USB-C' in message:
for pid, item in table.items():
if 'USB_C_Receptacle' in item['lib_id'] and item['name'] in {'CC1', 'CC2'}:
if ('CC1' not in message and 'CC2' not in message) or item['name'] in message:
pins.add(pid)
records.append({'source': 'semantic', 'type': 'circuit_contract', 'severity': 'error',
'description': message, 'pin_ids': sorted(pins)})
for violation in violations:
pins, items = set(), []
for raw in violation.get('items', []):
item = copy.deepcopy(raw)
match = re.search(r'Symbol\s+(\S+)\s+Pin\s+(\S+)\s+\[', item.get('description', ''))
if match:
pid = match[1] + '.' + match[2]
item['pin_id'] = pid
if pid in table:
pins.add(pid)
item['component_pin'] = {**table[pid], 'current_net': nets.get(pid)}
elif match[1].startswith('#FLG'):
flag = re.fullmatch(r'#FLG(\d+)', match[1])
index = int(flag[1]) - 1 if flag else -1
item['compiler_generated'] = True
item['current_net'] = circuit['nets'][index]['name'] if 0 <= index < len(circuit['nets']) else None
item['instruction'] = 'Compiler power flag; do not remove or change external-power declarations to hide this violation.'
items.append(item)
records.append({'source': 'native_erc', 'type': violation.get('type', 'unknown'),
'severity': violation.get('severity', 'unknown'),
'description': violation.get('description', ''),
'pin_ids': sorted(pins), 'items': items})
records.extend({'source': 'native_netlist', 'type': 'pin_net_mismatch', 'severity': 'error',
'description': f"Native schematic net differs for {row['pin']}", 'pin_ids': [row['pin']], **row}
for row in parity)
for record in records:
record['pins'] = [{**table[pid], 'current_net': nets.get(pid)} for pid in record['pin_ids'] if pid in table]
return records
def error_keys(records):
# Ignore position/UUID changes when comparing regenerated native documents.
return {json.dumps([r['source'], r['type'], r['description'], sorted(r['pin_ids']),
sorted(i.get('description', '') for i in r.get('items', []))], ensure_ascii=False)
for r in records}
def context(parts, circuit, records, rejections=(), rejected_evidence=None):
allowed = sorted({pid for record in records if record['source'] != 'native_netlist'
for pid in record['pin_ids']} & pin_table(parts).keys())
return {'errors': records, 'editable_pins': allowed, 'last_rejection_reasons': list(rejections),
'last_rejected_patch': rejected_evidence,
'policy': [
'Return only connection changes for editable_pins. All other pin assignments are locked.',
'BOM, component values/functions, pin_mux, existing net names/kinds and external power declarations are immutable.',
'Never disconnect a connected pin, omit a component, borrow an unrelated resistor, or disable a feature to satisfy ERC.',
'Do not add an arbitrary series resistor, split a required rail or alter supply voltage just to silence pin-type checks.',
'Use actual component pin IDs and give an electrical reason for each change.',
'If this needs a BOM change, a verified symbol recipe or datasheet evidence unavailable here, return unresolved with exact refs/pins; do not invent a workaround.',
]}
def apply_patch(parts, circuit, patch, allowed):
"""The model has no operation for deleting parts, no-connects or interfaces."""
if patch['unresolved']:
raise KiCadError('局部修复无法在保留功能下完成:' + '; '.join(patch['unresolved'])[:1200])
if not patch['changes']:
raise KiCadError('修复补丁没有任何有效的引脚连接修改')
result = copy.deepcopy(circuit)
table, old = pin_table(parts), assignments(circuit)
net_map = {net['name']: net for net in result['nets']}
for net in patch['new_nets']:
if not re.fullmatch(r'[A-Za-z0-9_+.-]{1,60}', net['name']) or net['name'] in net_map:
raise KiCadError('修复补丁包含重复或无效网络:' + net['name'])
value = {**net, 'pins': []}
result['nets'].append(value)
net_map[net['name']] = value
seen = set()
for change in patch['changes']:
pin, before, after = change['pin'], change['from_net'], change['to_net']
if pin not in allowed or pin not in table or pin in seen:
raise KiCadError('修复补丁越界或重复修改引脚:' + pin)
seen.add(pin)
if before != old.get(pin, '') or before == after or after not in net_map or not change['reason'].strip():
raise KiCadError('修复补丁连接前提、目标网络或电气理由无效:' + pin)
if before and net_map[before]['kind'] in {'ground', 'power'}:
if net_map[after]['kind'] != net_map[before]['kind']:
raise KiCadError('禁止为规避检查改变供电/地网络类别:' + pin)
if table[pin]['electrical_type'] in {'power_in', 'power_out'}:
raise KiCadError('供电引脚跨电源网络的修改需要经过验证的器件专用规则,禁止通过隔离电源输出规避 ERC:' + pin)
for net in result['nets']:
net['pins'] = [item for item in net['pins'] if item != pin]
net_map[after]['pins'].append(pin)
# Empty old nets can disappear only when every member was explicitly in scope.
result['nets'] = [net for net in result['nets'] if net['pins']]
used = {net['name'] for net in result['nets']}
if not set(circuit['external_power_nets']) <= used:
raise KiCadError('禁止修复补丁删除外部供电网络')
result['unconnected'] = [item for item in result['unconnected'] if item['pin'] not in seen]
for item in circuit['pin_mux']:
pin, connector = item['pin'], item['connector_pin']
# Preserve direct functional mappings; series-link mappings are checked below.
if old.get(pin) and old.get(pin) == old.get(connector):
current = assignments(result)
if current.get(pin) != current.get(connector):
raise KiCadError('修复破坏已有接口引脚映射:' + pin + ' -> ' + connector)
_protect_signal_paths(parts, circuit, result)
result['findings'] += patch['findings']
return result
def _protect_signal_paths(parts, before, after):
"""Keep existing mux paths through series resistors, without power-rail bridges."""
def reachable(circuit, start, end):
mapping = assignments(circuit)
kinds = {n['name']: n['kind'] for n in circuit['nets']}
bridges = {}
for part in parts:
if part['lib_id'] not in {'Device:R', 'Device:R_Small'}:
continue
nets = {mapping.get(part['reference'] + '.' + p['number']) for p in part['metadata']['pins']} - {None}
if len(nets) == 2 and all(kinds[n] in {'signal', 'usb'} for n in nets):
for net in nets:
bridges.setdefault(net, set()).update(nets - {net})
todo, seen = [mapping.get(start)], set()
while todo:
net = todo.pop()
if net is None or net in seen:
continue
seen.add(net)
todo.extend(bridges.get(net, set()) - seen)
return mapping.get(end) is not None and mapping[end] in seen
for mux in before['pin_mux']:
if reachable(before, mux['pin'], mux['connector_pin']) and not reachable(after, mux['pin'], mux['connector_pin']):
raise KiCadError('修复断开已有通信/烧录接口:' + mux['pin'] + ' -> ' + mux['connector_pin'])
+8
View File
@@ -24,7 +24,15 @@ F103_AF = {
def audit(parts, circuit, plan, assignments):
from .connector_rules import PROFILES
issues = []
grounds = {n['name'] for n in circuit['nets'] if n['kind'] == 'ground'}
for part in parts:
polarity = PROFILES.get(part.get('footprint', ''), {}).get('pin_polarity', {})
for number, meaning in polarity.items():
net = assignments.get(part['reference'] + '.' + number)
if grounds and ((meaning == 'negative' and net not in grounds) or (meaning == 'positive' and net in grounds)):
issues.append(part['reference'] + '.' + number + ': actual AMASS footprint marks this pin ' + meaning + '; correct connector polarity')
by_ref = {p['reference']: p for p in parts}
pins = {p['reference'] + '.' + pin['number']: pin for p in parts for pin in p['metadata']['pins']}
connectors = {p['reference'] for p in parts if p['role'] == 'connector'}
+7 -3
View File
@@ -234,6 +234,10 @@ class KiCadRuntime:
report["manufacturing_blockers"].append(f"KiCad {kind.upper()} failed or unverified")
after = worker.snapshot(pcb, checks / "readback-after.json")
report["board"] = after
report['mechanical'] = after.get('mechanical', {'passed': False, 'issues': ['Mechanical inspection missing']})
write_json(checks / 'mechanical.json', report['mechanical'])
if not report['mechanical']['passed']:
report['manufacturing_blockers'].append('连接器插拔检查未通过:' + '; '.join(report['mechanical']['issues'][:8]))
report["persistence_passed"] = all(before[k] == after[k] for k in ("footprints", "copper_geometry", "size_mm", "copper_layers"))
if not report["persistence_passed"]:
report["manufacturing_blockers"].append("Board changed unexpectedly during native check/refill")
@@ -271,7 +275,7 @@ class KiCadRuntime:
self._zip(native, root / "native-kicad.zip")
report["artifacts"].append({"kind": "kicad_native", "path": "native-kicad.zip"})
report["seconds"] = round(time.monotonic() - started, 3)
report["validation_scope"] = "Native ERC/DRC, pin/net parity, outline, persistence and zone fill; not bench or functional validation"
report["validation_scope"] = "Native ERC/DRC, pin/net parity, outline, persistence, zone fill and supported connector mating/access profiles; not full 3D collision, bench or functional validation"
write_json(checks / "summary.json", report)
manifest = {"format": "sha256-v1", "files": {
str(p.relative_to(root)): sha256(p) for p in sorted(root.rglob("*")) if p.is_file()}}
@@ -286,7 +290,7 @@ class KiCadRuntime:
for path in source.rglob("*"):
if path.is_symlink():
raise KiCadError("Project contains a symlink; provide a self-contained project")
if not path.is_file() or (path.suffix.lower() not in extensions and path.name not in {"sym-lib-table", "fp-lib-table", "MODEL-SOURCES.md", "LICENSE.CERN-OHL-P-2.0"}):
if not path.is_file() or (path.suffix.lower() not in extensions and path.name not in {"sym-lib-table", "fp-lib-table", "MODEL-SOURCES.md", "LICENSE.CERN-OHL-P-2.0", "LICENSE.Apache-2.0"}):
continue
count += 1
size += path.stat().st_size
@@ -326,7 +330,7 @@ class KiCadRuntime:
report["artifacts"].append({"kind": "bom", "path": "bom/bom.csv"})
if render:
image = root / "renders" / "board-3d.png"
export("render", image, ["pcb", "render", "--width", "1200", "--height", "900", "--quality", "basic", "--background", "opaque", "--rotate", "-30,0,25", "--output", image, pcb])
export("render", image, ["pcb", "render", "--width", "1200", "--height", "900", "--quality", "basic", "--background", "opaque", "--rotate", "-30,0,25", "--zoom", "0.75", "--output", image, pcb])
if not report["manufacturing_blockers"]:
directory = root / "manufacturing"
directory.mkdir()
+7
View File
@@ -21,3 +21,10 @@ CIRCUIT = obj({'nets': {'type': 'array', 'items': obj({'name': STR, 'pins': STRI
'unconnected': {'type': 'array', 'items': obj({'pin': STR, 'reason': STR})},
'external_power_nets': STRINGS, 'findings': STRINGS,
'pin_mux': {'type': 'array', 'items': obj({'pin': STR, 'function': STR, 'connector_pin': STR})}})
# Repairs cannot return replacement BOMs, complete circuits or no-connect edits.
CIRCUIT_PATCH = obj({
'changes': {'type': 'array', 'maxItems': 40, 'items': obj({'pin': STR, 'from_net': STR, 'to_net': STR, 'reason': STR})},
'new_nets': {'type': 'array', 'maxItems': 10, 'items': obj({'name': STR, 'kind': {'type': 'string', 'enum': ['ground', 'power', 'signal', 'usb']}})},
'findings': STRINGS, 'unresolved': STRINGS,
})
+16 -3
View File
@@ -19,7 +19,7 @@ from .state import State, StateError, digest, lock
TERMINAL = {'delivery_ready', 'draft_ready', 'completed', 'cancelled', 'failed', 'needs_input', 'awaiting_selection'}
FIELDS = ['task_id', 'state', 'revision', 'title', 'eda_engine', 'questions', 'proposal', 'proposal_hash',
FIELDS = ['task_id', 'state', 'revision', 'title', 'eda_engine', 'delivery_revoked', 'questions', 'proposal', 'proposal_hash',
'selected_option', 'delivery', 'download_ready', 'manufacturing_package', 'error', 'findings', 'manufacturing_blockers', 'metrics']
@@ -135,7 +135,7 @@ class NativeService:
if task['state'] != 'awaiting_selection' or payload.get('proposal_hash') != task.get('proposal_hash') or payload.get('option_id') != 'A':
raise StateError('方案已变化,请重新查看当前方案')
self.state.save(task, state='designing', selected_option='A', selection_hash=digest({'proposal': task['proposal_hash'], 'option': 'A'}),
design_started_at=time.time(), deadline=time.time() + min(1800, max(300, int(os.getenv('AI_PCB_TASK_SECONDS', '900')))))
design_started_at=time.time(), deadline=time.time() + min(86400, max(300, int(os.getenv('AI_PCB_TASK_SECONDS', '10800')))))
self.snapshot(task, 'design.started')
def metrics(self, task):
@@ -165,7 +165,7 @@ class NativeService:
verify(delivery)
self.state.save(task, state='delivery_ready' if result['passed'] and prepared else 'draft_ready', delivery=delivery,
prepared_manufacturing_package=prepared, download_ready=bool(result['passed'] and prepared),
manufacturing_blockers=result['manufacturing_blockers'], findings=design['circuit']['findings'],
manufacturing_blockers=result['manufacturing_blockers'], findings=design['circuit']['findings'] + result.get('model_coverage', {}).get('warnings', []),
metrics=metrics, error=None)
self.snapshot(task, 'delivery.ready' if task['download_ready'] else 'delivery.draft')
@@ -189,6 +189,19 @@ class NativeService:
if task['state'] not in {'delivery_ready', 'completed'} or not task.get('download_ready') or task.get('manufacturing_blockers'):
raise StateError('当前修订尚未通过完整检查,制造包不能放行')
verify(task['delivery'])
# Re-check the actual frozen board with the current mechanical policy;
# historical ERC/DRC or stale layout metadata cannot approve access.
from .runtime import KiCadRuntime
pcb = Path(task['delivery']['directory']) / 'native' / (task['task_id'] + '.kicad_pcb')
helper = Path(__file__).resolve().parents[1] / 'kicad_native.py'
runtime = KiCadRuntime()
check = runtime.run([runtime.python, helper, 'mechanical', '--board', pcb])
mechanical = json.loads(check['stdout'])
if not mechanical.get('passed'):
blockers = ['连接器插拔检查未通过:' + '; '.join(mechanical.get('issues', [])[:8])]
self.state.save(task, state='draft_ready', download_ready=False, delivery_revoked=True, manufacturing_blockers=blockers)
self.snapshot(task, 'delivery.draft')
raise StateError(blockers[0])
prepared = task.get('prepared_manufacturing_package')
if not prepared or prepared['manifest_sha256'] != payload['manifest_sha256'] or sha256(Path(prepared['path'])) != prepared['sha256']:
raise StateError('预生成下载包的摘要不一致,拒绝放行')
+1 -1
View File
@@ -58,7 +58,7 @@ export async function convertProject(
.filter(
([path]) =>
path.startsWith(prefix) &&
(allowed.test(path) || /(?:^|\/)(?:sym-lib-table|fp-lib-table|MODEL-SOURCES\.md|LICENSE\.CERN-OHL-P-2\.0)$/.test(path)),
(allowed.test(path) || /(?:^|\/)(?:sym-lib-table|fp-lib-table|MODEL-SOURCES\.md|LICENSE\.CERN-OHL-P-2\.0|LICENSE\.Apache-2\.0)$/.test(path)),
)
.map(([path, content]) => ({ name: `${name}/${path.slice(prefix.length)}`, bytes: content }));
files.push({